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