]> andersk Git - openssh.git/blame - scp.c
- millert@cvs.openbsd.org 2001/07/27 14:50:45
[openssh.git] / scp.c
CommitLineData
8efc0c15 1/*
bcbf86ec 2 * scp - secure remote copy. This is basically patched BSD rcp which
3 * uses ssh to do the data transfer (instead of using rcmd).
6ae2364d 4 *
bcbf86ec 5 * NOTE: This version should NOT be suid root. (This uses ssh to
6 * do the transfer and ssh has the necessary privileges.)
6ae2364d 7 *
5260325f 8 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
6ae2364d 9 *
bcbf86ec 10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 */
16/*
f3c7c613 17 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
bcbf86ec 19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 */
8efc0c15 40
41/*
2e73a022 42 * Parts from:
43 *
8efc0c15 44 * Copyright (c) 1983, 1990, 1992, 1993, 1995
45 * The Regents of the University of California. All rights reserved.
46 *
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. All advertising materials mentioning features or use of this software
56 * must display the following acknowledgement:
57 * This product includes software developed by the University of
58 * California, Berkeley and its contributors.
59 * 4. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 *
8efc0c15 75 */
76
77#include "includes.h"
c3941fa6 78RCSID("$OpenBSD: scp.c,v 1.77 2001/07/18 16:45:52 mouring Exp $");
8efc0c15 79
8efc0c15 80#include "xmalloc.h"
42f11eb2 81#include "atomicio.h"
82#include "pathnames.h"
83#include "log.h"
36a358ca 84#include "misc.h"
8efc0c15 85
260d427b 86#ifdef HAVE___PROGNAME
87extern char *__progname;
88#else
89char *__progname;
90#endif
91
8efc0c15 92/* For progressmeter() -- number of seconds before xfer considered "stalled" */
93#define STALLTIME 5
94
a4070484 95/* Progress meter bar */
96#define BAR \
97 "************************************************************"\
98 "************************************************************"\
99 "************************************************************"\
100 "************************************************************"
101#define MAX_BARLENGTH (sizeof(BAR) - 1)
102
8efc0c15 103/* Visual statistics about files as they are transferred. */
104void progressmeter(int);
105
106/* Returns width of the terminal (for progress meter calculations). */
107int getttywidth(void);
2e73a022 108int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc);
8efc0c15 109
8a624ebf 110/* Struct for addargs */
111arglist args;
94ec8c6b 112
8efc0c15 113/* Time a transfer started. */
114static struct timeval start;
115
116/* Number of bytes of current file transferred so far. */
ba917921 117volatile off_t statbytes;
8efc0c15 118
119/* Total size of current file. */
b4ad3727 120off_t totalbytes = 0;
8efc0c15 121
122/* Name of current file being transferred. */
123char *curfile;
124
125/* This is set to non-zero to enable verbose mode. */
5260325f 126int verbose_mode = 0;
8efc0c15 127
8efc0c15 128/* This is set to zero if the progressmeter is not desired. */
129int showprogress = 1;
130
2e73a022 131/* This is the program to execute for the secured connection. ("ssh" or -S) */
42f11eb2 132char *ssh_program = _PATH_SSH_PROGRAM;
2e73a022 133
aa3378df 134/*
135 * This function executes the given command as the specified user on the
136 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
137 * assigns the input and output file descriptors on success.
138 */
8efc0c15 139
6ae2364d 140int
2e73a022 141do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
8efc0c15 142{
5260325f 143 int pin[2], pout[2], reserved[2];
144
145 if (verbose_mode)
94ec8c6b 146 fprintf(stderr, "Executing: program %s host %s, user %s, command %s\n",
147 ssh_program, host, remuser ? remuser : "(unspecified)", cmd);
5260325f 148
aa3378df 149 /*
150 * Reserve two descriptors so that the real pipes won't get
151 * descriptors 0 and 1 because that will screw up dup2 below.
152 */
5260325f 153 pipe(reserved);
154
155 /* Create a socket pair for communicating with ssh. */
156 if (pipe(pin) < 0)
157 fatal("pipe: %s", strerror(errno));
158 if (pipe(pout) < 0)
159 fatal("pipe: %s", strerror(errno));
160
161 /* Free the reserved descriptors. */
162 close(reserved[0]);
163 close(reserved[1]);
164
165 /* For a child to execute the command on the remote host using ssh. */
94ec8c6b 166 if (fork() == 0) {
5260325f 167 /* Child. */
168 close(pin[1]);
169 close(pout[0]);
170 dup2(pin[0], 0);
171 dup2(pout[1], 1);
172 close(pin[0]);
173 close(pout[1]);
174
94ec8c6b 175 args.list[0] = ssh_program;
176 if (remuser != NULL)
8a624ebf 177 addargs(&args, "-l%s", remuser);
178 addargs(&args, "%s", host);
179 addargs(&args, "%s", cmd);
5260325f 180
94ec8c6b 181 execvp(ssh_program, args.list);
2e73a022 182 perror(ssh_program);
5260325f 183 exit(1);
8efc0c15 184 }
5260325f 185 /* Parent. Close the other side, and return the local side. */
186 close(pin[0]);
187 *fdout = pin[1];
188 close(pout[1]);
189 *fdin = pout[0];
190 return 0;
8efc0c15 191}
192
8efc0c15 193typedef struct {
194 int cnt;
195 char *buf;
196} BUF;
197
5260325f 198BUF *allocbuf(BUF *, int, int);
5260325f 199void lostconn(int);
200void nospace(void);
201int okname(char *);
202void run_err(const char *,...);
203void verifydir(char *);
8efc0c15 204
8efc0c15 205struct passwd *pwd;
5260325f 206uid_t userid;
8efc0c15 207int errs, remin, remout;
208int pflag, iamremote, iamrecursive, targetshouldbedirectory;
209
210#define CMDNEEDS 64
211char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
212
396c147e 213int main(int, char *[]);
5260325f 214int response(void);
215void rsource(char *, struct stat *);
216void sink(int, char *[]);
217void source(int, char *[]);
218void tolocal(int, char *[]);
219void toremote(char *, int, char *[]);
220void usage(void);
8efc0c15 221
222int
223main(argc, argv)
224 int argc;
225 char *argv[];
226{
227 int ch, fflag, tflag;
228 char *targ;
229 extern char *optarg;
230 extern int optind;
231
260d427b 232 __progname = get_progname(argv[0]);
233
94ec8c6b 234 args.list = NULL;
8a624ebf 235 addargs(&args, "ssh"); /* overwritten with ssh_program */
236 addargs(&args, "-x");
237 addargs(&args, "-oFallBackToRsh no");
94ec8c6b 238
8efc0c15 239 fflag = tflag = 0;
b5c334cc 240 while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q46S:o:")) != -1)
5260325f 241 switch (ch) {
242 /* User-visible flags. */
48e671d5 243 case '4':
48e671d5 244 case '6':
94ec8c6b 245 case 'C':
8a624ebf 246 addargs(&args, "-%c", ch);
48e671d5 247 break;
94ec8c6b 248 case 'o':
249 case 'c':
250 case 'i':
8a624ebf 251 addargs(&args, "-%c%s", ch, optarg);
8efc0c15 252 break;
253 case 'P':
8a624ebf 254 addargs(&args, "-p%s", optarg);
94ec8c6b 255 break;
256 case 'B':
8a624ebf 257 addargs(&args, "-oBatchmode yes");
94ec8c6b 258 break;
259 case 'p':
260 pflag = 1;
5260325f 261 break;
8efc0c15 262 case 'r':
263 iamrecursive = 1;
264 break;
2e73a022 265 case 'S':
94ec8c6b 266 ssh_program = xstrdup(optarg);
267 break;
268 case 'v':
4fc334a2 269 addargs(&args, "-v");
94ec8c6b 270 verbose_mode = 1;
271 break;
272 case 'q':
273 showprogress = 0;
2e73a022 274 break;
275
5260325f 276 /* Server options. */
8efc0c15 277 case 'd':
278 targetshouldbedirectory = 1;
279 break;
5260325f 280 case 'f': /* "from" */
8efc0c15 281 iamremote = 1;
282 fflag = 1;
283 break;
5260325f 284 case 't': /* "to" */
8efc0c15 285 iamremote = 1;
286 tflag = 1;
fe56c12b 287#ifdef HAVE_CYGWIN
288 setmode(0, O_BINARY);
289#endif
8efc0c15 290 break;
8efc0c15 291 default:
292 usage();
293 }
294 argc -= optind;
295 argv += optind;
296
297 if ((pwd = getpwuid(userid = getuid())) == NULL)
5260325f 298 fatal("unknown user %d", (int) userid);
8efc0c15 299
5260325f 300 if (!isatty(STDERR_FILENO))
8efc0c15 301 showprogress = 0;
302
303 remin = STDIN_FILENO;
304 remout = STDOUT_FILENO;
305
2b87da3b 306 if (fflag) {
5260325f 307 /* Follow "protocol", send data. */
308 (void) response();
8efc0c15 309 source(argc, argv);
310 exit(errs != 0);
311 }
5260325f 312 if (tflag) {
313 /* Receive data. */
8efc0c15 314 sink(argc, argv);
315 exit(errs != 0);
316 }
8efc0c15 317 if (argc < 2)
318 usage();
319 if (argc > 2)
320 targetshouldbedirectory = 1;
321
322 remin = remout = -1;
323 /* Command to be executed on remote system using "ssh". */
0ed28836 324 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
325 verbose_mode ? " -v" : "",
2e73a022 326 iamrecursive ? " -r" : "", pflag ? " -p" : "",
327 targetshouldbedirectory ? " -d" : "");
8efc0c15 328
5260325f 329 (void) signal(SIGPIPE, lostconn);
8efc0c15 330
331 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
332 toremote(targ, argc, argv);
333 else {
5260325f 334 tolocal(argc, argv); /* Dest is local host. */
8efc0c15 335 if (targetshouldbedirectory)
336 verifydir(argv[argc - 1]);
337 }
338 exit(errs != 0);
339}
340
341void
342toremote(targ, argc, argv)
343 char *targ, *argv[];
344 int argc;
345{
346 int i, len;
347 char *bp, *host, *src, *suser, *thost, *tuser;
348
349 *targ++ = 0;
350 if (*targ == 0)
351 targ = ".";
352
353 if ((thost = strchr(argv[argc - 1], '@'))) {
354 /* user@host */
355 *thost++ = 0;
356 tuser = argv[argc - 1];
357 if (*tuser == '\0')
358 tuser = NULL;
359 else if (!okname(tuser))
360 exit(1);
361 } else {
362 thost = argv[argc - 1];
363 tuser = NULL;
364 }
365
366 for (i = 0; i < argc - 1; i++) {
367 src = colon(argv[i]);
5260325f 368 if (src) { /* remote to remote */
8efc0c15 369 *src++ = 0;
370 if (*src == 0)
371 src = ".";
372 host = strchr(argv[i], '@');
2e73a022 373 len = strlen(ssh_program) + strlen(argv[i]) +
374 strlen(src) + (tuser ? strlen(tuser) : 0) +
375 strlen(thost) + strlen(targ) + CMDNEEDS + 32;
5260325f 376 bp = xmalloc(len);
8efc0c15 377 if (host) {
378 *host++ = 0;
48e671d5 379 host = cleanhostname(host);
8efc0c15 380 suser = argv[i];
381 if (*suser == '\0')
382 suser = pwd->pw_name;
383 else if (!okname(suser))
384 continue;
0ed28836 385 snprintf(bp, len,
386 "%s%s -x -o'FallBackToRsh no' -n "
387 "-l %s %s %s %s '%s%s%s:%s'",
71c0d06a 388 ssh_program, verbose_mode ? " -v" : "",
389 suser, host, cmd, src,
390 tuser ? tuser : "", tuser ? "@" : "",
391 thost, targ);
48e671d5 392 } else {
393 host = cleanhostname(argv[i]);
0ed28836 394 snprintf(bp, len,
395 "exec %s%s -x -o'FallBackToRsh no' -n %s "
396 "%s %s '%s%s%s:%s'",
71c0d06a 397 ssh_program, verbose_mode ? " -v" : "",
398 host, cmd, src,
399 tuser ? tuser : "", tuser ? "@" : "",
400 thost, targ);
48e671d5 401 }
5260325f 402 if (verbose_mode)
403 fprintf(stderr, "Executing: %s\n", bp);
404 (void) system(bp);
405 (void) xfree(bp);
406 } else { /* local to remote */
8efc0c15 407 if (remin == -1) {
408 len = strlen(targ) + CMDNEEDS + 20;
5260325f 409 bp = xmalloc(len);
0ed28836 410 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
48e671d5 411 host = cleanhostname(thost);
2e73a022 412 if (do_cmd(host, tuser, bp, &remin,
413 &remout, argc) < 0)
5260325f 414 exit(1);
8efc0c15 415 if (response() < 0)
416 exit(1);
5260325f 417 (void) xfree(bp);
8efc0c15 418 }
5260325f 419 source(1, argv + i);
8efc0c15 420 }
421 }
422}
423
424void
425tolocal(argc, argv)
426 int argc;
427 char *argv[];
428{
429 int i, len;
430 char *bp, *host, *src, *suser;
431
432 for (i = 0; i < argc - 1; i++) {
5260325f 433 if (!(src = colon(argv[i]))) { /* Local to local. */
8efc0c15 434 len = strlen(_PATH_CP) + strlen(argv[i]) +
2e73a022 435 strlen(argv[argc - 1]) + 20;
8efc0c15 436 bp = xmalloc(len);
0ed28836 437 (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
2e73a022 438 iamrecursive ? " -r" : "", pflag ? " -p" : "",
439 argv[i], argv[argc - 1]);
5260325f 440 if (verbose_mode)
441 fprintf(stderr, "Executing: %s\n", bp);
8efc0c15 442 if (system(bp))
443 ++errs;
5260325f 444 (void) xfree(bp);
8efc0c15 445 continue;
446 }
447 *src++ = 0;
448 if (*src == 0)
449 src = ".";
450 if ((host = strchr(argv[i], '@')) == NULL) {
451 host = argv[i];
452 suser = NULL;
453 } else {
454 *host++ = 0;
455 suser = argv[i];
456 if (*suser == '\0')
457 suser = pwd->pw_name;
458 else if (!okname(suser))
459 continue;
460 }
48e671d5 461 host = cleanhostname(host);
8efc0c15 462 len = strlen(src) + CMDNEEDS + 20;
5260325f 463 bp = xmalloc(len);
0ed28836 464 (void) snprintf(bp, len, "%s -f %s", cmd, src);
2e73a022 465 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
5260325f 466 (void) xfree(bp);
467 ++errs;
468 continue;
8efc0c15 469 }
5260325f 470 xfree(bp);
8efc0c15 471 sink(1, argv + argc - 1);
5260325f 472 (void) close(remin);
8efc0c15 473 remin = remout = -1;
474 }
475}
476
477void
478source(argc, argv)
479 int argc;
480 char *argv[];
481{
482 struct stat stb;
483 static BUF buffer;
484 BUF *bp;
ba917921 485 off_t i, amt, result;
486 int fd, haderr, indx;
8efc0c15 487 char *last, *name, buf[2048];
0fc791ba 488 int len;
8efc0c15 489
490 for (indx = 0; indx < argc; ++indx) {
5260325f 491 name = argv[indx];
8efc0c15 492 statbytes = 0;
0fc791ba 493 len = strlen(name);
494 while (len > 1 && name[len-1] == '/')
495 name[--len] = '\0';
8efc0c15 496 if ((fd = open(name, O_RDONLY, 0)) < 0)
497 goto syserr;
498 if (fstat(fd, &stb) < 0) {
499syserr: run_err("%s: %s", name, strerror(errno));
500 goto next;
501 }
502 switch (stb.st_mode & S_IFMT) {
503 case S_IFREG:
504 break;
505 case S_IFDIR:
506 if (iamrecursive) {
507 rsource(name, &stb);
508 goto next;
509 }
510 /* FALLTHROUGH */
511 default:
512 run_err("%s: not a regular file", name);
513 goto next;
514 }
515 if ((last = strrchr(name, '/')) == NULL)
516 last = name;
517 else
518 ++last;
519 curfile = last;
520 if (pflag) {
521 /*
522 * Make it compatible with possible future
523 * versions expecting microseconds.
524 */
0ed28836 525 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
1e3b8b07 526 (u_long) stb.st_mtime,
527 (u_long) stb.st_atime);
3189621b 528 (void) atomicio(write, remout, buf, strlen(buf));
8efc0c15 529 if (response() < 0)
530 goto next;
531 }
532#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
30eac028 533#ifdef HAVE_LONG_LONG_INT
bf1d27bd 534 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1e3b8b07 535 (u_int) (stb.st_mode & FILEMODEMASK),
ec0ad9c2 536 (long long) stb.st_size, last);
f8f230bf 537#else
538 /* XXX: Handle integer overflow? */
d1581d5f 539 snprintf(buf, sizeof buf, "C%04o %lu %s\n",
f8f230bf 540 (u_int) (stb.st_mode & FILEMODEMASK),
d1581d5f 541 (u_long) stb.st_size, last);
f8f230bf 542#endif
543
5260325f 544 if (verbose_mode) {
545 fprintf(stderr, "Sending file modes: %s", buf);
546 fflush(stderr);
547 }
3189621b 548 (void) atomicio(write, remout, buf, strlen(buf));
8efc0c15 549 if (response() < 0)
550 goto next;
551 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
5260325f 552next: (void) close(fd);
8efc0c15 553 continue;
554 }
8efc0c15 555 if (showprogress) {
556 totalbytes = stb.st_size;
557 progressmeter(-1);
558 }
8efc0c15 559 /* Keep writing after an error so that we stay sync'd up. */
560 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
561 amt = bp->cnt;
562 if (i + amt > stb.st_size)
563 amt = stb.st_size - i;
564 if (!haderr) {
1d1ffb87 565 result = atomicio(read, fd, bp->buf, amt);
8efc0c15 566 if (result != amt)
567 haderr = result >= 0 ? EIO : errno;
568 }
569 if (haderr)
3189621b 570 (void) atomicio(write, remout, bp->buf, amt);
8efc0c15 571 else {
68227e6d 572 result = atomicio(write, remout, bp->buf, amt);
8efc0c15 573 if (result != amt)
574 haderr = result >= 0 ? EIO : errno;
575 statbytes += result;
576 }
577 }
5260325f 578 if (showprogress)
8efc0c15 579 progressmeter(1);
580
581 if (close(fd) < 0 && !haderr)
582 haderr = errno;
583 if (!haderr)
3189621b 584 (void) atomicio(write, remout, "", 1);
8efc0c15 585 else
586 run_err("%s: %s", name, strerror(haderr));
5260325f 587 (void) response();
8efc0c15 588 }
589}
590
591void
592rsource(name, statp)
593 char *name;
594 struct stat *statp;
595{
596 DIR *dirp;
597 struct dirent *dp;
598 char *last, *vect[1], path[1100];
599
600 if (!(dirp = opendir(name))) {
601 run_err("%s: %s", name, strerror(errno));
602 return;
603 }
604 last = strrchr(name, '/');
605 if (last == 0)
606 last = name;
607 else
608 last++;
609 if (pflag) {
0ed28836 610 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
1e3b8b07 611 (u_long) statp->st_mtime,
612 (u_long) statp->st_atime);
3189621b 613 (void) atomicio(write, remout, path, strlen(path));
8efc0c15 614 if (response() < 0) {
615 closedir(dirp);
616 return;
617 }
618 }
0ed28836 619 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1e3b8b07 620 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
5260325f 621 if (verbose_mode)
622 fprintf(stderr, "Entering directory: %s", path);
3189621b 623 (void) atomicio(write, remout, path, strlen(path));
8efc0c15 624 if (response() < 0) {
625 closedir(dirp);
626 return;
627 }
e5ff6ecf 628 while ((dp = readdir(dirp)) != NULL) {
8efc0c15 629 if (dp->d_ino == 0)
630 continue;
631 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
632 continue;
633 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
634 run_err("%s/%s: name too long", name, dp->d_name);
635 continue;
636 }
0ed28836 637 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
8efc0c15 638 vect[0] = path;
639 source(1, vect);
640 }
5260325f 641 (void) closedir(dirp);
3189621b 642 (void) atomicio(write, remout, "E\n", 2);
5260325f 643 (void) response();
8efc0c15 644}
645
646void
647sink(argc, argv)
648 int argc;
649 char *argv[];
650{
651 static BUF buffer;
652 struct stat stb;
5260325f 653 enum {
654 YES, NO, DISPLAYED
655 } wrerr;
8efc0c15 656 BUF *bp;
657 off_t i, j;
658 int amt, count, exists, first, mask, mode, ofd, omode;
14a9a859 659 off_t size;
660 int setimes, targisdir, wrerrno = 0;
8efc0c15 661 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
188adeb2 662 struct timeval tv[2];
8efc0c15 663
36967a16 664#define atime tv[0]
665#define mtime tv[1]
cb220a93 666#define SCREWUP(str) do { why = str; goto screwup; } while (0)
8efc0c15 667
668 setimes = targisdir = 0;
669 mask = umask(0);
670 if (!pflag)
5260325f 671 (void) umask(mask);
8efc0c15 672 if (argc != 1) {
673 run_err("ambiguous target");
674 exit(1);
675 }
676 targ = *argv;
677 if (targetshouldbedirectory)
678 verifydir(targ);
5260325f 679
3189621b 680 (void) atomicio(write, remout, "", 1);
8efc0c15 681 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
682 targisdir = 1;
683 for (first = 1;; first = 0) {
684 cp = buf;
1d1ffb87 685 if (atomicio(read, remin, cp, 1) <= 0)
8efc0c15 686 return;
687 if (*cp++ == '\n')
688 SCREWUP("unexpected <newline>");
689 do {
1d1ffb87 690 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 691 SCREWUP("lost connection");
692 *cp++ = ch;
693 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
694 *cp = 0;
695
696 if (buf[0] == '\01' || buf[0] == '\02') {
697 if (iamremote == 0)
3189621b 698 (void) atomicio(write, STDERR_FILENO,
71c0d06a 699 buf + 1, strlen(buf + 1));
8efc0c15 700 if (buf[0] == '\02')
701 exit(1);
702 ++errs;
703 continue;
704 }
705 if (buf[0] == 'E') {
3189621b 706 (void) atomicio(write, remout, "", 1);
8efc0c15 707 return;
708 }
8efc0c15 709 if (ch == '\n')
710 *--cp = 0;
711
8efc0c15 712 cp = buf;
713 if (*cp == 'T') {
714 setimes++;
715 cp++;
36967a16 716 mtime.tv_sec = strtol(cp, &cp, 10);
717 if (!cp || *cp++ != ' ')
8efc0c15 718 SCREWUP("mtime.sec not delimited");
36967a16 719 mtime.tv_usec = strtol(cp, &cp, 10);
720 if (!cp || *cp++ != ' ')
8efc0c15 721 SCREWUP("mtime.usec not delimited");
36967a16 722 atime.tv_sec = strtol(cp, &cp, 10);
723 if (!cp || *cp++ != ' ')
8efc0c15 724 SCREWUP("atime.sec not delimited");
36967a16 725 atime.tv_usec = strtol(cp, &cp, 10);
726 if (!cp || *cp++ != '\0')
8efc0c15 727 SCREWUP("atime.usec not delimited");
3189621b 728 (void) atomicio(write, remout, "", 1);
8efc0c15 729 continue;
730 }
731 if (*cp != 'C' && *cp != 'D') {
732 /*
733 * Check for the case "rcp remote:foo\* local:bar".
734 * In this case, the line "No match." can be returned
735 * by the shell before the rcp command on the remote is
736 * executed so the ^Aerror_message convention isn't
737 * followed.
738 */
739 if (first) {
740 run_err("%s", cp);
741 exit(1);
742 }
743 SCREWUP("expected control record");
744 }
745 mode = 0;
746 for (++cp; cp < buf + 5; cp++) {
747 if (*cp < '0' || *cp > '7')
748 SCREWUP("bad mode");
749 mode = (mode << 3) | (*cp - '0');
750 }
751 if (*cp++ != ' ')
752 SCREWUP("mode not delimited");
753
e5ff6ecf 754 for (size = 0; isdigit(*cp);)
8efc0c15 755 size = size * 10 + (*cp++ - '0');
756 if (*cp++ != ' ')
757 SCREWUP("size not delimited");
758 if (targisdir) {
759 static char *namebuf;
760 static int cursize;
761 size_t need;
762
763 need = strlen(targ) + strlen(cp) + 250;
0ed28836 764 if (need > cursize) {
765 if (namebuf)
766 xfree(namebuf);
5260325f 767 namebuf = xmalloc(need);
0ed28836 768 cursize = need;
769 }
770 (void) snprintf(namebuf, need, "%s%s%s", targ,
2e73a022 771 *targ ? "/" : "", cp);
8efc0c15 772 np = namebuf;
773 } else
774 np = targ;
775 curfile = cp;
776 exists = stat(np, &stb) == 0;
777 if (buf[0] == 'D') {
778 int mod_flag = pflag;
779 if (exists) {
780 if (!S_ISDIR(stb.st_mode)) {
781 errno = ENOTDIR;
782 goto bad;
783 }
784 if (pflag)
5260325f 785 (void) chmod(np, mode);
8efc0c15 786 } else {
5260325f 787 /* Handle copying from a read-only
788 directory */
8efc0c15 789 mod_flag = 1;
790 if (mkdir(np, mode | S_IRWXU) < 0)
791 goto bad;
792 }
5c470997 793 vect[0] = xstrdup(np);
8efc0c15 794 sink(1, vect);
795 if (setimes) {
796 setimes = 0;
e68225b2 797 if (utimes(vect[0], tv) < 0)
5260325f 798 run_err("%s: set times: %s",
e68225b2 799 vect[0], strerror(errno));
8efc0c15 800 }
801 if (mod_flag)
e68225b2 802 (void) chmod(vect[0], mode);
803 if (vect[0])
804 xfree(vect[0]);
8efc0c15 805 continue;
806 }
807 omode = mode;
808 mode |= S_IWRITE;
3e4fc5f9 809 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
8efc0c15 810bad: run_err("%s: %s", np, strerror(errno));
811 continue;
812 }
3189621b 813 (void) atomicio(write, remout, "", 1);
8efc0c15 814 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
5260325f 815 (void) close(ofd);
8efc0c15 816 continue;
817 }
818 cp = bp->buf;
819 wrerr = NO;
820
821 if (showprogress) {
822 totalbytes = size;
823 progressmeter(-1);
824 }
825 statbytes = 0;
826 for (count = i = 0; i < size; i += 4096) {
827 amt = 4096;
828 if (i + amt > size)
829 amt = size - i;
830 count += amt;
831 do {
a22aff1f 832 j = read(remin, cp, amt);
833 if (j == -1 && (errno == EINTR || errno == EAGAIN)) {
834 continue;
835 } else if (j <= 0) {
8efc0c15 836 run_err("%s", j ? strerror(errno) :
e5ff6ecf 837 "dropped connection");
8efc0c15 838 exit(1);
839 }
840 amt -= j;
841 cp += j;
5260325f 842 statbytes += j;
8efc0c15 843 } while (amt > 0);
844 if (count == bp->cnt) {
845 /* Keep reading so we stay sync'd up. */
846 if (wrerr == NO) {
1d1ffb87 847 j = atomicio(write, ofd, bp->buf, count);
8efc0c15 848 if (j != count) {
849 wrerr = YES;
5260325f 850 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 851 }
852 }
853 count = 0;
854 cp = bp->buf;
855 }
856 }
857 if (showprogress)
858 progressmeter(1);
859 if (count != 0 && wrerr == NO &&
1d1ffb87 860 (j = atomicio(write, ofd, bp->buf, count)) != count) {
8efc0c15 861 wrerr = YES;
5260325f 862 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 863 }
8efc0c15 864 if (ftruncate(ofd, size)) {
865 run_err("%s: truncate: %s", np, strerror(errno));
866 wrerr = DISPLAYED;
867 }
8efc0c15 868 if (pflag) {
869 if (exists || omode != mode)
77bb0bca 870#ifdef HAVE_FCHMOD
8efc0c15 871 if (fchmod(ofd, omode))
77bb0bca 872#else /* HAVE_FCHMOD */
873 if (chmod(np, omode))
874#endif /* HAVE_FCHMOD */
8efc0c15 875 run_err("%s: set mode: %s",
e5ff6ecf 876 np, strerror(errno));
8efc0c15 877 } else {
878 if (!exists && omode != mode)
77bb0bca 879#ifdef HAVE_FCHMOD
8efc0c15 880 if (fchmod(ofd, omode & ~mask))
77bb0bca 881#else /* HAVE_FCHMOD */
882 if (chmod(np, omode & ~mask))
883#endif /* HAVE_FCHMOD */
8efc0c15 884 run_err("%s: set mode: %s",
e5ff6ecf 885 np, strerror(errno));
8efc0c15 886 }
704b1659 887 if (close(ofd) == -1) {
888 wrerr = YES;
889 wrerrno = errno;
890 }
5260325f 891 (void) response();
8efc0c15 892 if (setimes && wrerr == NO) {
893 setimes = 0;
188adeb2 894 if (utimes(np, tv) < 0) {
8efc0c15 895 run_err("%s: set times: %s",
e5ff6ecf 896 np, strerror(errno));
8efc0c15 897 wrerr = DISPLAYED;
898 }
899 }
5260325f 900 switch (wrerr) {
8efc0c15 901 case YES:
902 run_err("%s: %s", np, strerror(wrerrno));
903 break;
904 case NO:
3189621b 905 (void) atomicio(write, remout, "", 1);
8efc0c15 906 break;
907 case DISPLAYED:
908 break;
909 }
910 }
911screwup:
912 run_err("protocol error: %s", why);
913 exit(1);
914}
915
916int
917response()
918{
919 char ch, *cp, resp, rbuf[2048];
920
1d1ffb87 921 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
8efc0c15 922 lostconn(0);
923
924 cp = rbuf;
5260325f 925 switch (resp) {
926 case 0: /* ok */
8efc0c15 927 return (0);
928 default:
929 *cp++ = resp;
930 /* FALLTHROUGH */
5260325f 931 case 1: /* error, followed by error msg */
932 case 2: /* fatal error, "" */
8efc0c15 933 do {
1d1ffb87 934 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 935 lostconn(0);
936 *cp++ = ch;
937 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
938
939 if (!iamremote)
3189621b 940 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
8efc0c15 941 ++errs;
942 if (resp == 1)
943 return (-1);
944 exit(1);
945 }
946 /* NOTREACHED */
947}
948
949void
950usage()
951{
2e73a022 952 (void) fprintf(stderr, "usage: scp "
c3941fa6 953 "[-pqrvBC46] [-S ssh] [-P port] [-c cipher] [-i identity] "
954 "[-o option] f1 f2\n"
03cb2621 955 " or: scp [options] f1 ... fn directory\n");
8efc0c15 956 exit(1);
957}
958
959void
5260325f 960run_err(const char *fmt,...)
8efc0c15 961{
962 static FILE *fp;
963 va_list ap;
8efc0c15 964
965 ++errs;
966 if (fp == NULL && !(fp = fdopen(remout, "w")))
967 return;
5260325f 968 (void) fprintf(fp, "%c", 0x01);
969 (void) fprintf(fp, "scp: ");
b92964b7 970 va_start(ap, fmt);
5260325f 971 (void) vfprintf(fp, fmt, ap);
b92964b7 972 va_end(ap);
5260325f 973 (void) fprintf(fp, "\n");
974 (void) fflush(fp);
975
976 if (!iamremote) {
b92964b7 977 va_start(ap, fmt);
5260325f 978 vfprintf(stderr, fmt, ap);
b92964b7 979 va_end(ap);
5260325f 980 fprintf(stderr, "\n");
981 }
8efc0c15 982}
983
8efc0c15 984void
985verifydir(cp)
986 char *cp;
987{
988 struct stat stb;
989
990 if (!stat(cp, &stb)) {
991 if (S_ISDIR(stb.st_mode))
992 return;
993 errno = ENOTDIR;
994 }
995 run_err("%s: %s", cp, strerror(errno));
996 exit(1);
997}
998
999int
1000okname(cp0)
1001 char *cp0;
1002{
1003 int c;
1004 char *cp;
1005
1006 cp = cp0;
1007 do {
cb220a93 1008 c = (int)*cp;
8efc0c15 1009 if (c & 0200)
1010 goto bad;
731c1541 1011 if (!isalpha(c) && !isdigit(c) &&
1012 c != '_' && c != '-' && c != '.' && c != '+')
8efc0c15 1013 goto bad;
1014 } while (*++cp);
1015 return (1);
1016
c8d54615 1017bad: fprintf(stderr, "%s: invalid user name\n", cp0);
8efc0c15 1018 return (0);
1019}
1020
1021BUF *
1022allocbuf(bp, fd, blksize)
1023 BUF *bp;
1024 int fd, blksize;
1025{
1026 size_t size;
77bb0bca 1027#ifdef HAVE_ST_BLKSIZE
8efc0c15 1028 struct stat stb;
1029
1030 if (fstat(fd, &stb) < 0) {
1031 run_err("fstat: %s", strerror(errno));
1032 return (0);
1033 }
5260325f 1034 if (stb.st_blksize == 0)
1035 size = blksize;
1036 else
1037 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
2e73a022 1038 stb.st_blksize;
77bb0bca 1039#else /* HAVE_ST_BLKSIZE */
2b87da3b 1040 size = blksize;
77bb0bca 1041#endif /* HAVE_ST_BLKSIZE */
8efc0c15 1042 if (bp->cnt >= size)
1043 return (bp);
5260325f 1044 if (bp->buf == NULL)
1045 bp->buf = xmalloc(size);
1046 else
1047 bp->buf = xrealloc(bp->buf, size);
8efc0c15 1048 bp->cnt = size;
1049 return (bp);
1050}
1051
1052void
1053lostconn(signo)
1054 int signo;
1055{
1056 if (!iamremote)
08c260ea 1057 write(STDERR_FILENO, "lost connection\n", 16);
1058 if (signo)
1059 _exit(1);
1060 else
1061 exit(1);
8efc0c15 1062}
1063
8efc0c15 1064
396c147e 1065static void
8efc0c15 1066alarmtimer(int wait)
1067{
5260325f 1068 struct itimerval itv;
8efc0c15 1069
5260325f 1070 itv.it_value.tv_sec = wait;
1071 itv.it_value.tv_usec = 0;
1072 itv.it_interval = itv.it_value;
1073 setitimer(ITIMER_REAL, &itv, NULL);
8efc0c15 1074}
1075
396c147e 1076static void
610cd5c6 1077updateprogressmeter(int ignore)
8efc0c15 1078{
1079 int save_errno = errno;
1080
1081 progressmeter(0);
1082 errno = save_errno;
1083}
1084
396c147e 1085static int
5ca51e19 1086foregroundproc(void)
2bd61362 1087{
1088 static pid_t pgrp = -1;
1089 int ctty_pgrp;
1090
1091 if (pgrp == -1)
1092 pgrp = getpgrp();
1093
63fe0529 1094#ifdef HAVE_TCGETPGRP
3c62e7eb 1095 return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 &&
1096 ctty_pgrp == pgrp);
1097#else
5260325f 1098 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1099 ctty_pgrp == pgrp));
3c62e7eb 1100#endif
2bd61362 1101}
1102
8efc0c15 1103void
1104progressmeter(int flag)
1105{
1106 static const char prefixes[] = " KMGTP";
1107 static struct timeval lastupdate;
1108 static off_t lastsize;
1109 struct timeval now, td, wait;
1110 off_t cursize, abbrevsize;
1111 double elapsed;
b6573a35 1112 int ratio, barlength, i, remaining;
8efc0c15 1113 char buf[256];
1114
1115 if (flag == -1) {
5260325f 1116 (void) gettimeofday(&start, (struct timezone *) 0);
8efc0c15 1117 lastupdate = start;
1118 lastsize = 0;
5260325f 1119 }
2bd61362 1120 if (foregroundproc() == 0)
1121 return;
1122
5260325f 1123 (void) gettimeofday(&now, (struct timezone *) 0);
8efc0c15 1124 cursize = statbytes;
b4ad3727 1125 if (totalbytes != 0) {
aa3378df 1126 ratio = 100.0 * cursize / totalbytes;
8efc0c15 1127 ratio = MAX(ratio, 0);
1128 ratio = MIN(ratio, 100);
5260325f 1129 } else
8efc0c15 1130 ratio = 100;
1131
5260325f 1132 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
8efc0c15 1133
1134 barlength = getttywidth() - 51;
a4070484 1135 barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
8efc0c15 1136 if (barlength > 0) {
1137 i = barlength * ratio / 100;
1138 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
a4070484 1139 "|%.*s%*s|", i, BAR, barlength - i, "");
8efc0c15 1140 }
8efc0c15 1141 i = 0;
1142 abbrevsize = cursize;
1143 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1144 i++;
1145 abbrevsize >>= 10;
1146 }
6a416424 1147 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5lu %c%c ",
2c92c680 1148 (unsigned long) abbrevsize, prefixes[i],
1149 prefixes[i] == ' ' ? ' ' : 'B');
8efc0c15 1150
1151 timersub(&now, &lastupdate, &wait);
1152 if (cursize > lastsize) {
1153 lastupdate = now;
1154 lastsize = cursize;
1155 if (wait.tv_sec >= STALLTIME) {
1156 start.tv_sec += wait.tv_sec;
1157 start.tv_usec += wait.tv_usec;
1158 }
1159 wait.tv_sec = 0;
1160 }
8efc0c15 1161 timersub(&now, &start, &td);
1162 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1163
71c0d06a 1164 if (flag != 1 &&
1165 (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes)) {
8efc0c15 1166 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
71c0d06a 1167 " --:-- ETA");
8efc0c15 1168 } else if (wait.tv_sec >= STALLTIME) {
1169 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
71c0d06a 1170 " - stalled -");
8efc0c15 1171 } else {
d6f24e45 1172 if (flag != 1)
71c0d06a 1173 remaining = (int)(totalbytes / (statbytes / elapsed) -
1174 elapsed);
d6f24e45 1175 else
1176 remaining = elapsed;
1177
5068f573 1178 i = remaining / 3600;
8efc0c15 1179 if (i)
1180 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1181 "%2d:", i);
8efc0c15 1182 else
1183 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1184 " ");
8efc0c15 1185 i = remaining % 3600;
1186 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1187 "%02d:%02d%s", i / 60, i % 60,
1188 (flag != 1) ? " ETA" : " ");
8efc0c15 1189 }
1190 atomicio(write, fileno(stdout), buf, strlen(buf));
1191
1192 if (flag == -1) {
36a358ca 1193 mysignal(SIGALRM, updateprogressmeter);
8efc0c15 1194 alarmtimer(1);
1195 } else if (flag == 1) {
1196 alarmtimer(0);
3189621b 1197 atomicio(write, fileno(stdout), "\n", 1);
8efc0c15 1198 statbytes = 0;
1199 }
1200}
1201
1202int
1203getttywidth(void)
1204{
1205 struct winsize winsize;
1206
1207 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
5260325f 1208 return (winsize.ws_col ? winsize.ws_col : 80);
8efc0c15 1209 else
5260325f 1210 return (80);
8efc0c15 1211}
This page took 0.3626 seconds and 5 git commands to generate.