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