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