Annotation of src/usr.bin/ssh/scp.c, Revision 1.117
1.1 deraadt 1: /*
1.38 deraadt 2: * scp - secure remote copy. This is basically patched BSD rcp which
3: * uses ssh to do the data transfer (instead of using rcmd).
1.27 markus 4: *
1.38 deraadt 5: * NOTE: This version should NOT be suid root. (This uses ssh to
6: * do the transfer and ssh has the necessary privileges.)
1.27 markus 7: *
1.38 deraadt 8: * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
9: *
10: * As far as I am concerned, the code I have written for this software
11: * can be used freely for any purpose. Any derived versions of this
12: * software must be clearly marked as such, and if the derived work is
13: * incompatible with the protocol description in the RFC file, it must be
14: * called by a name other than "ssh" or "Secure Shell".
1.39 markus 15: */
1.38 deraadt 16: /*
1.60 deraadt 17: * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18: * Copyright (c) 1999 Aaron Campbell. All rights reserved.
1.27 markus 19: *
1.38 deraadt 20: * Redistribution and use in source and binary forms, with or without
21: * modification, are permitted provided that the following conditions
22: * are met:
23: * 1. Redistributions of source code must retain the above copyright
24: * notice, this list of conditions and the following disclaimer.
25: * 2. Redistributions in binary form must reproduce the above copyright
26: * notice, this list of conditions and the following disclaimer in the
27: * documentation and/or other materials provided with the distribution.
1.27 markus 28: *
1.38 deraadt 29: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39: */
1.1 deraadt 40:
41: /*
1.35 deraadt 42: * Parts from:
43: *
1.1 deraadt 44: * Copyright (c) 1983, 1990, 1992, 1993, 1995
45: * The Regents of the University of California. All rights reserved.
46: *
47: * Redistribution and use in source and binary forms, with or without
48: * modification, are permitted provided that the following conditions
49: * are met:
50: * 1. Redistributions of source code must retain the above copyright
51: * notice, this list of conditions and the following disclaimer.
52: * 2. Redistributions in binary form must reproduce the above copyright
53: * notice, this list of conditions and the following disclaimer in the
54: * documentation and/or other materials provided with the distribution.
1.103 millert 55: * 3. Neither the name of the University nor the names of its contributors
1.1 deraadt 56: * may be used to endorse or promote products derived from this software
57: * without specific prior written permission.
58: *
59: * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62: * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69: * SUCH DAMAGE.
70: *
71: */
72:
73: #include "includes.h"
1.117 ! avsm 74: RCSID("$OpenBSD: scp.c,v 1.116 2004/07/08 12:47:21 dtucker Exp $");
1.1 deraadt 75:
76: #include "xmalloc.h"
1.51 markus 77: #include "atomicio.h"
1.50 markus 78: #include "pathnames.h"
1.51 markus 79: #include "log.h"
1.69 mouring 80: #include "misc.h"
1.97 fgsch 81: #include "progressmeter.h"
1.1 deraadt 82:
1.35 deraadt 83: int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc);
1.11 aaron 84:
1.99 markus 85: void bwlimit(int);
86:
1.70 mouring 87: /* Struct for addargs */
88: arglist args;
1.41 markus 89:
1.99 markus 90: /* Bandwidth limit */
1.113 djm 91: off_t limit_rate = 0;
1.99 markus 92:
1.11 aaron 93: /* Name of current file being transferred. */
94: char *curfile;
1.4 aaron 95:
1.1 deraadt 96: /* This is set to non-zero to enable verbose mode. */
1.17 markus 97: int verbose_mode = 0;
1.1 deraadt 98:
1.6 aaron 99: /* This is set to zero if the progressmeter is not desired. */
100: int showprogress = 1;
101:
1.34 deraadt 102: /* This is the program to execute for the secured connection. ("ssh" or -S) */
1.50 markus 103: char *ssh_program = _PATH_SSH_PROGRAM;
1.34 deraadt 104:
1.92 markus 105: /* This is used to store the pid of ssh_program */
1.105 djm 106: pid_t do_cmd_pid = -1;
107:
108: static void
109: killchild(int signo)
110: {
111: if (do_cmd_pid > 1)
112: kill(do_cmd_pid, signo);
113:
114: _exit(1);
115: }
1.92 markus 116:
1.20 markus 117: /*
118: * This function executes the given command as the specified user on the
119: * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
120: * assigns the input and output file descriptors on success.
121: */
1.1 deraadt 122:
1.27 markus 123: int
1.35 deraadt 124: do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
1.1 deraadt 125: {
1.18 markus 126: int pin[2], pout[2], reserved[2];
127:
128: if (verbose_mode)
1.78 deraadt 129: fprintf(stderr,
130: "Executing: program %s host %s, user %s, command %s\n",
131: ssh_program, host,
132: remuser ? remuser : "(unspecified)", cmd);
1.18 markus 133:
1.20 markus 134: /*
135: * Reserve two descriptors so that the real pipes won't get
136: * descriptors 0 and 1 because that will screw up dup2 below.
137: */
1.18 markus 138: pipe(reserved);
139:
140: /* Create a socket pair for communicating with ssh. */
141: if (pipe(pin) < 0)
142: fatal("pipe: %s", strerror(errno));
143: if (pipe(pout) < 0)
144: fatal("pipe: %s", strerror(errno));
145:
146: /* Free the reserved descriptors. */
147: close(reserved[0]);
148: close(reserved[1]);
149:
1.106 nino 150: /* Fork a child to execute the command on the remote host using ssh. */
1.92 markus 151: do_cmd_pid = fork();
152: if (do_cmd_pid == 0) {
1.18 markus 153: /* Child. */
154: close(pin[1]);
155: close(pout[0]);
156: dup2(pin[0], 0);
157: dup2(pout[1], 1);
158: close(pin[0]);
159: close(pout[1]);
160:
1.41 markus 161: args.list[0] = ssh_program;
162: if (remuser != NULL)
1.70 mouring 163: addargs(&args, "-l%s", remuser);
164: addargs(&args, "%s", host);
165: addargs(&args, "%s", cmd);
1.18 markus 166:
1.41 markus 167: execvp(ssh_program, args.list);
1.34 deraadt 168: perror(ssh_program);
1.18 markus 169: exit(1);
1.92 markus 170: } else if (do_cmd_pid == -1) {
171: fatal("fork: %s", strerror(errno));
1.18 markus 172: }
173: /* Parent. Close the other side, and return the local side. */
174: close(pin[0]);
175: *fdout = pin[1];
176: close(pout[1]);
177: *fdin = pout[0];
1.105 djm 178: signal(SIGTERM, killchild);
179: signal(SIGINT, killchild);
180: signal(SIGHUP, killchild);
1.18 markus 181: return 0;
1.1 deraadt 182: }
183:
184: typedef struct {
185: int cnt;
186: char *buf;
187: } BUF;
188:
1.18 markus 189: BUF *allocbuf(BUF *, int, int);
190: void lostconn(int);
191: void nospace(void);
192: int okname(char *);
193: void run_err(const char *,...);
194: void verifydir(char *);
1.1 deraadt 195:
196: struct passwd *pwd;
1.18 markus 197: uid_t userid;
1.1 deraadt 198: int errs, remin, remout;
199: int pflag, iamremote, iamrecursive, targetshouldbedirectory;
200:
201: #define CMDNEEDS 64
202: char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
203:
1.18 markus 204: int response(void);
205: void rsource(char *, struct stat *);
206: void sink(int, char *[]);
207: void source(int, char *[]);
208: void tolocal(int, char *[]);
209: void toremote(char *, int, char *[]);
210: void usage(void);
1.1 deraadt 211:
212: int
1.104 djm 213: main(int argc, char **argv)
1.1 deraadt 214: {
1.92 markus 215: int ch, fflag, tflag, status;
1.99 markus 216: double speed;
217: char *targ, *endp;
1.1 deraadt 218: extern char *optarg;
219: extern int optind;
220:
1.41 markus 221: args.list = NULL;
1.91 deraadt 222: addargs(&args, "ssh"); /* overwritten with ssh_program */
1.70 mouring 223: addargs(&args, "-x");
1.82 stevesk 224: addargs(&args, "-oForwardAgent no");
1.84 stevesk 225: addargs(&args, "-oClearAllForwardings yes");
1.41 markus 226:
1.1 deraadt 227: fflag = tflag = 0;
1.100 markus 228: while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
1.18 markus 229: switch (ch) {
230: /* User-visible flags. */
1.100 markus 231: case '1':
232: case '2':
1.23 markus 233: case '4':
1.41 markus 234: case '6':
235: case 'C':
1.70 mouring 236: addargs(&args, "-%c", ch);
1.41 markus 237: break;
238: case 'o':
239: case 'c':
240: case 'i':
1.83 stevesk 241: case 'F':
1.70 mouring 242: addargs(&args, "-%c%s", ch, optarg);
1.23 markus 243: break;
1.41 markus 244: case 'P':
1.70 mouring 245: addargs(&args, "-p%s", optarg);
1.41 markus 246: break;
247: case 'B':
1.70 mouring 248: addargs(&args, "-oBatchmode yes");
1.23 markus 249: break;
1.99 markus 250: case 'l':
251: speed = strtod(optarg, &endp);
252: if (speed <= 0 || *endp != '\0')
253: usage();
1.113 djm 254: limit_rate = speed * 1024;
1.99 markus 255: break;
1.1 deraadt 256: case 'p':
257: pflag = 1;
258: break;
259: case 'r':
260: iamrecursive = 1;
261: break;
1.34 deraadt 262: case 'S':
1.41 markus 263: ssh_program = xstrdup(optarg);
264: break;
265: case 'v':
1.72 markus 266: addargs(&args, "-v");
1.41 markus 267: verbose_mode = 1;
268: break;
269: case 'q':
1.111 dtucker 270: addargs(&args, "-q");
1.41 markus 271: showprogress = 0;
1.34 deraadt 272: break;
273:
1.18 markus 274: /* Server options. */
1.1 deraadt 275: case 'd':
276: targetshouldbedirectory = 1;
277: break;
1.18 markus 278: case 'f': /* "from" */
1.1 deraadt 279: iamremote = 1;
280: fflag = 1;
281: break;
1.18 markus 282: case 't': /* "to" */
1.1 deraadt 283: iamremote = 1;
284: tflag = 1;
285: break;
286: default:
287: usage();
288: }
289: argc -= optind;
290: argv += optind;
291:
292: if ((pwd = getpwuid(userid = getuid())) == NULL)
1.108 deraadt 293: fatal("unknown user %u", (u_int) userid);
1.1 deraadt 294:
1.18 markus 295: if (!isatty(STDERR_FILENO))
1.7 deraadt 296: showprogress = 0;
297:
1.1 deraadt 298: remin = STDIN_FILENO;
299: remout = STDOUT_FILENO;
300:
1.52 stevesk 301: if (fflag) {
1.18 markus 302: /* Follow "protocol", send data. */
303: (void) response();
1.1 deraadt 304: source(argc, argv);
305: exit(errs != 0);
306: }
1.18 markus 307: if (tflag) {
308: /* Receive data. */
1.1 deraadt 309: sink(argc, argv);
310: exit(errs != 0);
311: }
312: if (argc < 2)
313: usage();
314: if (argc > 2)
315: targetshouldbedirectory = 1;
316:
317: remin = remout = -1;
1.92 markus 318: do_cmd_pid = -1;
1.1 deraadt 319: /* Command to be executed on remote system using "ssh". */
1.55 deraadt 320: (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
321: verbose_mode ? " -v" : "",
1.35 deraadt 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]);
1.92 markus 333: }
334: /*
335: * Finally check the exit status of the ssh process, if one was forked
336: * and no error has occured yet
337: */
338: if (do_cmd_pid != -1 && errs == 0) {
339: if (remin != -1)
340: (void) close(remin);
341: if (remout != -1)
342: (void) close(remout);
343: if (waitpid(do_cmd_pid, &status, 0) == -1)
344: errs = 1;
345: else {
346: if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
347: errs = 1;
348: }
1.1 deraadt 349: }
350: exit(errs != 0);
351: }
352:
353: void
1.104 djm 354: toremote(char *targ, int argc, char **argv)
1.1 deraadt 355: {
356: int i, len;
357: char *bp, *host, *src, *suser, *thost, *tuser;
358:
359: *targ++ = 0;
360: if (*targ == 0)
361: targ = ".";
362:
1.94 markus 363: if ((thost = strrchr(argv[argc - 1], '@'))) {
1.1 deraadt 364: /* user@host */
365: *thost++ = 0;
366: tuser = argv[argc - 1];
367: if (*tuser == '\0')
368: tuser = NULL;
369: } else {
370: thost = argv[argc - 1];
371: tuser = NULL;
372: }
373:
374: for (i = 0; i < argc - 1; i++) {
375: src = colon(argv[i]);
1.18 markus 376: if (src) { /* remote to remote */
1.84 stevesk 377: static char *ssh_options =
1.89 markus 378: "-x -o'ClearAllForwardings yes'";
1.1 deraadt 379: *src++ = 0;
380: if (*src == 0)
381: src = ".";
1.94 markus 382: host = strrchr(argv[i], '@');
1.34 deraadt 383: len = strlen(ssh_program) + strlen(argv[i]) +
1.35 deraadt 384: strlen(src) + (tuser ? strlen(tuser) : 0) +
1.84 stevesk 385: strlen(thost) + strlen(targ) +
386: strlen(ssh_options) + CMDNEEDS + 20;
1.18 markus 387: bp = xmalloc(len);
1.1 deraadt 388: if (host) {
389: *host++ = 0;
1.23 markus 390: host = cleanhostname(host);
1.1 deraadt 391: suser = argv[i];
392: if (*suser == '\0')
393: suser = pwd->pw_name;
1.102 markus 394: else if (!okname(suser)) {
395: xfree(bp);
1.1 deraadt 396: continue;
1.102 markus 397: }
398: if (tuser && !okname(tuser)) {
399: xfree(bp);
1.101 markus 400: continue;
1.102 markus 401: }
1.55 deraadt 402: snprintf(bp, len,
1.84 stevesk 403: "%s%s %s -n "
1.55 deraadt 404: "-l %s %s %s %s '%s%s%s:%s'",
1.44 deraadt 405: ssh_program, verbose_mode ? " -v" : "",
1.84 stevesk 406: ssh_options, suser, host, cmd, src,
1.44 deraadt 407: tuser ? tuser : "", tuser ? "@" : "",
408: thost, targ);
1.23 markus 409: } else {
410: host = cleanhostname(argv[i]);
1.55 deraadt 411: snprintf(bp, len,
1.84 stevesk 412: "exec %s%s %s -n %s "
1.55 deraadt 413: "%s %s '%s%s%s:%s'",
1.44 deraadt 414: ssh_program, verbose_mode ? " -v" : "",
1.84 stevesk 415: ssh_options, host, cmd, src,
1.44 deraadt 416: tuser ? tuser : "", tuser ? "@" : "",
417: thost, targ);
1.23 markus 418: }
1.18 markus 419: if (verbose_mode)
420: fprintf(stderr, "Executing: %s\n", bp);
1.109 markus 421: if (system(bp) != 0)
422: errs = 1;
1.18 markus 423: (void) xfree(bp);
424: } else { /* local to remote */
1.1 deraadt 425: if (remin == -1) {
426: len = strlen(targ) + CMDNEEDS + 20;
1.18 markus 427: bp = xmalloc(len);
1.55 deraadt 428: (void) snprintf(bp, len, "%s -t %s", cmd, targ);
1.23 markus 429: host = cleanhostname(thost);
1.35 deraadt 430: if (do_cmd(host, tuser, bp, &remin,
431: &remout, argc) < 0)
1.18 markus 432: exit(1);
1.1 deraadt 433: if (response() < 0)
434: exit(1);
1.18 markus 435: (void) xfree(bp);
1.1 deraadt 436: }
1.18 markus 437: source(1, argv + i);
1.1 deraadt 438: }
439: }
440: }
441:
442: void
1.104 djm 443: tolocal(int argc, char **argv)
1.1 deraadt 444: {
445: int i, len;
446: char *bp, *host, *src, *suser;
447:
448: for (i = 0; i < argc - 1; i++) {
1.18 markus 449: if (!(src = colon(argv[i]))) { /* Local to local. */
1.1 deraadt 450: len = strlen(_PATH_CP) + strlen(argv[i]) +
1.35 deraadt 451: strlen(argv[argc - 1]) + 20;
1.1 deraadt 452: bp = xmalloc(len);
1.55 deraadt 453: (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
1.35 deraadt 454: iamrecursive ? " -r" : "", pflag ? " -p" : "",
455: argv[i], argv[argc - 1]);
1.18 markus 456: if (verbose_mode)
457: fprintf(stderr, "Executing: %s\n", bp);
1.1 deraadt 458: if (system(bp))
459: ++errs;
1.18 markus 460: (void) xfree(bp);
1.1 deraadt 461: continue;
462: }
463: *src++ = 0;
464: if (*src == 0)
465: src = ".";
1.94 markus 466: if ((host = strrchr(argv[i], '@')) == NULL) {
1.1 deraadt 467: host = argv[i];
468: suser = NULL;
469: } else {
470: *host++ = 0;
471: suser = argv[i];
472: if (*suser == '\0')
473: suser = pwd->pw_name;
474: }
1.23 markus 475: host = cleanhostname(host);
1.1 deraadt 476: len = strlen(src) + CMDNEEDS + 20;
1.18 markus 477: bp = xmalloc(len);
1.55 deraadt 478: (void) snprintf(bp, len, "%s -f %s", cmd, src);
1.35 deraadt 479: if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
1.18 markus 480: (void) xfree(bp);
481: ++errs;
482: continue;
1.1 deraadt 483: }
1.18 markus 484: xfree(bp);
1.1 deraadt 485: sink(1, argv + argc - 1);
1.18 markus 486: (void) close(remin);
1.1 deraadt 487: remin = remout = -1;
488: }
489: }
490:
491: void
1.104 djm 492: source(int argc, char **argv)
1.1 deraadt 493: {
494: struct stat stb;
495: static BUF buffer;
496: BUF *bp;
1.97 fgsch 497: off_t i, amt, result, statbytes;
1.68 markus 498: int fd, haderr, indx;
1.1 deraadt 499: char *last, *name, buf[2048];
1.65 deraadt 500: int len;
1.1 deraadt 501:
502: for (indx = 0; indx < argc; ++indx) {
1.18 markus 503: name = argv[indx];
1.11 aaron 504: statbytes = 0;
1.65 deraadt 505: len = strlen(name);
506: while (len > 1 && name[len-1] == '/')
507: name[--len] = '\0';
1.85 markus 508: if (strchr(name, '\n') != NULL) {
509: run_err("%s: skipping, filename contains a newline",
510: name);
511: goto next;
512: }
1.1 deraadt 513: if ((fd = open(name, O_RDONLY, 0)) < 0)
514: goto syserr;
515: if (fstat(fd, &stb) < 0) {
516: syserr: run_err("%s: %s", name, strerror(errno));
517: goto next;
518: }
519: switch (stb.st_mode & S_IFMT) {
520: case S_IFREG:
521: break;
522: case S_IFDIR:
523: if (iamrecursive) {
524: rsource(name, &stb);
525: goto next;
526: }
527: /* FALLTHROUGH */
528: default:
529: run_err("%s: not a regular file", name);
530: goto next;
531: }
532: if ((last = strrchr(name, '/')) == NULL)
533: last = name;
534: else
535: ++last;
1.11 aaron 536: curfile = last;
1.1 deraadt 537: if (pflag) {
538: /*
539: * Make it compatible with possible future
540: * versions expecting microseconds.
541: */
1.55 deraadt 542: (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
1.47 markus 543: (u_long) stb.st_mtime,
544: (u_long) stb.st_atime);
1.107 deraadt 545: (void) atomicio(vwrite, remout, buf, strlen(buf));
1.1 deraadt 546: if (response() < 0)
547: goto next;
548: }
549: #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1.61 markus 550: snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1.47 markus 551: (u_int) (stb.st_mode & FILEMODEMASK),
1.62 markus 552: (long long)stb.st_size, last);
1.18 markus 553: if (verbose_mode) {
554: fprintf(stderr, "Sending file modes: %s", buf);
555: }
1.107 deraadt 556: (void) atomicio(vwrite, remout, buf, strlen(buf));
1.1 deraadt 557: if (response() < 0)
558: goto next;
559: if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
1.18 markus 560: next: (void) close(fd);
1.1 deraadt 561: continue;
562: }
1.97 fgsch 563: if (showprogress)
564: start_progress_meter(curfile, stb.st_size, &statbytes);
1.1 deraadt 565: /* Keep writing after an error so that we stay sync'd up. */
566: for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
567: amt = bp->cnt;
568: if (i + amt > stb.st_size)
569: amt = stb.st_size - i;
570: if (!haderr) {
1.30 deraadt 571: result = atomicio(read, fd, bp->buf, amt);
1.1 deraadt 572: if (result != amt)
573: haderr = result >= 0 ? EIO : errno;
574: }
575: if (haderr)
1.107 deraadt 576: (void) atomicio(vwrite, remout, bp->buf, amt);
1.1 deraadt 577: else {
1.107 deraadt 578: result = atomicio(vwrite, remout, bp->buf, amt);
1.1 deraadt 579: if (result != amt)
580: haderr = result >= 0 ? EIO : errno;
1.4 aaron 581: statbytes += result;
1.1 deraadt 582: }
1.113 djm 583: if (limit_rate)
1.99 markus 584: bwlimit(amt);
1.1 deraadt 585: }
1.18 markus 586: if (showprogress)
1.97 fgsch 587: stop_progress_meter();
1.4 aaron 588:
1.1 deraadt 589: if (close(fd) < 0 && !haderr)
590: haderr = errno;
591: if (!haderr)
1.107 deraadt 592: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 593: else
594: run_err("%s: %s", name, strerror(haderr));
1.18 markus 595: (void) response();
1.1 deraadt 596: }
597: }
598:
599: void
1.104 djm 600: rsource(char *name, struct stat *statp)
1.1 deraadt 601: {
602: DIR *dirp;
603: struct dirent *dp;
604: char *last, *vect[1], path[1100];
605:
606: if (!(dirp = opendir(name))) {
607: run_err("%s: %s", name, strerror(errno));
608: return;
609: }
610: last = strrchr(name, '/');
611: if (last == 0)
612: last = name;
613: else
614: last++;
615: if (pflag) {
1.55 deraadt 616: (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
1.47 markus 617: (u_long) statp->st_mtime,
618: (u_long) statp->st_atime);
1.107 deraadt 619: (void) atomicio(vwrite, remout, path, strlen(path));
1.1 deraadt 620: if (response() < 0) {
621: closedir(dirp);
622: return;
623: }
624: }
1.55 deraadt 625: (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1.47 markus 626: (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1.18 markus 627: if (verbose_mode)
628: fprintf(stderr, "Entering directory: %s", path);
1.107 deraadt 629: (void) atomicio(vwrite, remout, path, strlen(path));
1.1 deraadt 630: if (response() < 0) {
631: closedir(dirp);
632: return;
633: }
1.63 stevesk 634: while ((dp = readdir(dirp)) != NULL) {
1.1 deraadt 635: if (dp->d_ino == 0)
636: continue;
637: if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
638: continue;
639: if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
640: run_err("%s/%s: name too long", name, dp->d_name);
641: continue;
642: }
1.55 deraadt 643: (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1.1 deraadt 644: vect[0] = path;
645: source(1, vect);
646: }
1.18 markus 647: (void) closedir(dirp);
1.107 deraadt 648: (void) atomicio(vwrite, remout, "E\n", 2);
1.18 markus 649: (void) response();
1.1 deraadt 650: }
651:
652: void
1.99 markus 653: bwlimit(int amount)
654: {
655: static struct timeval bwstart, bwend;
656: static int lamt, thresh = 16384;
1.115 avsm 657: u_int64_t waitlen;
1.99 markus 658: struct timespec ts, rm;
659:
660: if (!timerisset(&bwstart)) {
661: gettimeofday(&bwstart, NULL);
662: return;
663: }
664:
665: lamt += amount;
666: if (lamt < thresh)
667: return;
668:
669: gettimeofday(&bwend, NULL);
670: timersub(&bwend, &bwstart, &bwend);
671: if (!timerisset(&bwend))
672: return;
673:
674: lamt *= 8;
1.115 avsm 675: waitlen = (double)1000000L * lamt / limit_rate;
1.99 markus 676:
1.115 avsm 677: bwstart.tv_sec = waitlen / 1000000L;
678: bwstart.tv_usec = waitlen % 1000000L;
1.99 markus 679:
680: if (timercmp(&bwstart, &bwend, >)) {
681: timersub(&bwstart, &bwend, &bwend);
682:
683: /* Adjust the wait time */
684: if (bwend.tv_sec) {
685: thresh /= 2;
686: if (thresh < 2048)
687: thresh = 2048;
688: } else if (bwend.tv_usec < 100) {
689: thresh *= 2;
690: if (thresh > 32768)
691: thresh = 32768;
692: }
693:
694: TIMEVAL_TO_TIMESPEC(&bwend, &ts);
695: while (nanosleep(&ts, &rm) == -1) {
696: if (errno != EINTR)
697: break;
698: ts = rm;
699: }
700: }
701:
702: lamt = 0;
703: gettimeofday(&bwstart, NULL);
704: }
705:
706: void
1.104 djm 707: sink(int argc, char **argv)
1.1 deraadt 708: {
709: static BUF buffer;
710: struct stat stb;
1.18 markus 711: enum {
712: YES, NO, DISPLAYED
713: } wrerr;
1.1 deraadt 714: BUF *bp;
715: off_t i, j;
716: int amt, count, exists, first, mask, mode, ofd, omode;
1.97 fgsch 717: off_t size, statbytes;
1.36 deraadt 718: int setimes, targisdir, wrerrno = 0;
1.1 deraadt 719: char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
1.40 markus 720: struct timeval tv[2];
1.1 deraadt 721:
1.66 stevesk 722: #define atime tv[0]
723: #define mtime tv[1]
1.75 deraadt 724: #define SCREWUP(str) do { why = str; goto screwup; } while (0)
1.1 deraadt 725:
726: setimes = targisdir = 0;
727: mask = umask(0);
728: if (!pflag)
1.18 markus 729: (void) umask(mask);
1.1 deraadt 730: if (argc != 1) {
731: run_err("ambiguous target");
732: exit(1);
733: }
734: targ = *argv;
735: if (targetshouldbedirectory)
736: verifydir(targ);
1.18 markus 737:
1.107 deraadt 738: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 739: if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
740: targisdir = 1;
741: for (first = 1;; first = 0) {
742: cp = buf;
1.30 deraadt 743: if (atomicio(read, remin, cp, 1) <= 0)
1.1 deraadt 744: return;
745: if (*cp++ == '\n')
746: SCREWUP("unexpected <newline>");
747: do {
1.30 deraadt 748: if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1 deraadt 749: SCREWUP("lost connection");
750: *cp++ = ch;
751: } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
752: *cp = 0;
1.114 markus 753: if (verbose_mode)
754: fprintf(stderr, "Sink: %s", buf);
1.1 deraadt 755:
756: if (buf[0] == '\01' || buf[0] == '\02') {
757: if (iamremote == 0)
1.107 deraadt 758: (void) atomicio(vwrite, STDERR_FILENO,
1.44 deraadt 759: buf + 1, strlen(buf + 1));
1.1 deraadt 760: if (buf[0] == '\02')
761: exit(1);
762: ++errs;
763: continue;
764: }
765: if (buf[0] == 'E') {
1.107 deraadt 766: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 767: return;
768: }
769: if (ch == '\n')
770: *--cp = 0;
771:
772: cp = buf;
773: if (*cp == 'T') {
774: setimes++;
775: cp++;
1.66 stevesk 776: mtime.tv_sec = strtol(cp, &cp, 10);
777: if (!cp || *cp++ != ' ')
1.1 deraadt 778: SCREWUP("mtime.sec not delimited");
1.66 stevesk 779: mtime.tv_usec = strtol(cp, &cp, 10);
780: if (!cp || *cp++ != ' ')
1.1 deraadt 781: SCREWUP("mtime.usec not delimited");
1.66 stevesk 782: atime.tv_sec = strtol(cp, &cp, 10);
783: if (!cp || *cp++ != ' ')
1.1 deraadt 784: SCREWUP("atime.sec not delimited");
1.66 stevesk 785: atime.tv_usec = strtol(cp, &cp, 10);
786: if (!cp || *cp++ != '\0')
1.1 deraadt 787: SCREWUP("atime.usec not delimited");
1.107 deraadt 788: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 789: continue;
790: }
791: if (*cp != 'C' && *cp != 'D') {
792: /*
793: * Check for the case "rcp remote:foo\* local:bar".
794: * In this case, the line "No match." can be returned
795: * by the shell before the rcp command on the remote is
796: * executed so the ^Aerror_message convention isn't
797: * followed.
798: */
799: if (first) {
800: run_err("%s", cp);
801: exit(1);
802: }
803: SCREWUP("expected control record");
804: }
805: mode = 0;
806: for (++cp; cp < buf + 5; cp++) {
807: if (*cp < '0' || *cp > '7')
808: SCREWUP("bad mode");
809: mode = (mode << 3) | (*cp - '0');
810: }
811: if (*cp++ != ' ')
812: SCREWUP("mode not delimited");
813:
1.63 stevesk 814: for (size = 0; isdigit(*cp);)
1.1 deraadt 815: size = size * 10 + (*cp++ - '0');
816: if (*cp++ != ' ')
817: SCREWUP("size not delimited");
1.114 markus 818: if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
819: run_err("error: unexpected filename: %s", cp);
820: exit(1);
821: }
1.1 deraadt 822: if (targisdir) {
823: static char *namebuf;
824: static int cursize;
825: size_t need;
826:
827: need = strlen(targ) + strlen(cp) + 250;
1.55 deraadt 828: if (need > cursize) {
1.58 danh 829: if (namebuf)
830: xfree(namebuf);
1.18 markus 831: namebuf = xmalloc(need);
1.55 deraadt 832: cursize = need;
833: }
834: (void) snprintf(namebuf, need, "%s%s%s", targ,
1.88 mouring 835: strcmp(targ, "/") ? "/" : "", cp);
1.1 deraadt 836: np = namebuf;
837: } else
838: np = targ;
1.12 aaron 839: curfile = cp;
1.1 deraadt 840: exists = stat(np, &stb) == 0;
841: if (buf[0] == 'D') {
842: int mod_flag = pflag;
1.114 markus 843: if (!iamrecursive)
844: SCREWUP("received directory without -r");
1.1 deraadt 845: if (exists) {
846: if (!S_ISDIR(stb.st_mode)) {
847: errno = ENOTDIR;
848: goto bad;
849: }
850: if (pflag)
1.18 markus 851: (void) chmod(np, mode);
1.1 deraadt 852: } else {
1.18 markus 853: /* Handle copying from a read-only
854: directory */
1.1 deraadt 855: mod_flag = 1;
856: if (mkdir(np, mode | S_IRWXU) < 0)
857: goto bad;
858: }
1.58 danh 859: vect[0] = xstrdup(np);
1.1 deraadt 860: sink(1, vect);
861: if (setimes) {
862: setimes = 0;
1.59 deraadt 863: if (utimes(vect[0], tv) < 0)
1.18 markus 864: run_err("%s: set times: %s",
1.59 deraadt 865: vect[0], strerror(errno));
1.1 deraadt 866: }
867: if (mod_flag)
1.59 deraadt 868: (void) chmod(vect[0], mode);
869: if (vect[0])
870: xfree(vect[0]);
1.1 deraadt 871: continue;
872: }
873: omode = mode;
874: mode |= S_IWRITE;
1.71 markus 875: if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1.1 deraadt 876: bad: run_err("%s: %s", np, strerror(errno));
877: continue;
878: }
1.107 deraadt 879: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 880: if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
1.18 markus 881: (void) close(ofd);
1.1 deraadt 882: continue;
883: }
884: cp = bp->buf;
885: wrerr = NO;
1.7 deraadt 886:
1.12 aaron 887: statbytes = 0;
1.97 fgsch 888: if (showprogress)
889: start_progress_meter(curfile, size, &statbytes);
1.1 deraadt 890: for (count = i = 0; i < size; i += 4096) {
891: amt = 4096;
892: if (i + amt > size)
893: amt = size - i;
894: count += amt;
895: do {
1.117 ! avsm 896: j = atomicio(read, remin, cp, amt);
! 897: if (j <= 0) {
1.1 deraadt 898: run_err("%s", j ? strerror(errno) :
1.63 stevesk 899: "dropped connection");
1.1 deraadt 900: exit(1);
901: }
902: amt -= j;
903: cp += j;
1.18 markus 904: statbytes += j;
1.1 deraadt 905: } while (amt > 0);
1.112 djm 906:
1.113 djm 907: if (limit_rate)
1.99 markus 908: bwlimit(4096);
909:
1.1 deraadt 910: if (count == bp->cnt) {
911: /* Keep reading so we stay sync'd up. */
912: if (wrerr == NO) {
1.107 deraadt 913: j = atomicio(vwrite, ofd, bp->buf, count);
1.1 deraadt 914: if (j != count) {
915: wrerr = YES;
1.18 markus 916: wrerrno = j >= 0 ? EIO : errno;
1.1 deraadt 917: }
918: }
919: count = 0;
920: cp = bp->buf;
921: }
922: }
1.7 deraadt 923: if (showprogress)
1.97 fgsch 924: stop_progress_meter();
1.1 deraadt 925: if (count != 0 && wrerr == NO &&
1.107 deraadt 926: (j = atomicio(vwrite, ofd, bp->buf, count)) != count) {
1.1 deraadt 927: wrerr = YES;
1.18 markus 928: wrerrno = j >= 0 ? EIO : errno;
1.1 deraadt 929: }
1.98 djm 930: if (wrerr == NO && ftruncate(ofd, size) != 0) {
1.1 deraadt 931: run_err("%s: truncate: %s", np, strerror(errno));
932: wrerr = DISPLAYED;
933: }
934: if (pflag) {
935: if (exists || omode != mode)
1.116 dtucker 936: if (fchmod(ofd, omode)) {
1.1 deraadt 937: run_err("%s: set mode: %s",
1.63 stevesk 938: np, strerror(errno));
1.116 dtucker 939: wrerr = DISPLAYED;
940: }
1.1 deraadt 941: } else {
942: if (!exists && omode != mode)
1.116 dtucker 943: if (fchmod(ofd, omode & ~mask)) {
1.1 deraadt 944: run_err("%s: set mode: %s",
1.63 stevesk 945: np, strerror(errno));
1.116 dtucker 946: wrerr = DISPLAYED;
947: }
1.1 deraadt 948: }
1.33 provos 949: if (close(ofd) == -1) {
950: wrerr = YES;
951: wrerrno = errno;
952: }
1.18 markus 953: (void) response();
1.1 deraadt 954: if (setimes && wrerr == NO) {
955: setimes = 0;
1.40 markus 956: if (utimes(np, tv) < 0) {
1.1 deraadt 957: run_err("%s: set times: %s",
1.63 stevesk 958: np, strerror(errno));
1.1 deraadt 959: wrerr = DISPLAYED;
960: }
961: }
1.18 markus 962: switch (wrerr) {
1.1 deraadt 963: case YES:
964: run_err("%s: %s", np, strerror(wrerrno));
965: break;
966: case NO:
1.107 deraadt 967: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 968: break;
969: case DISPLAYED:
970: break;
971: }
972: }
973: screwup:
974: run_err("protocol error: %s", why);
975: exit(1);
976: }
977:
978: int
1.86 itojun 979: response(void)
1.1 deraadt 980: {
981: char ch, *cp, resp, rbuf[2048];
982:
1.30 deraadt 983: if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1.1 deraadt 984: lostconn(0);
985:
986: cp = rbuf;
1.18 markus 987: switch (resp) {
988: case 0: /* ok */
1.1 deraadt 989: return (0);
990: default:
991: *cp++ = resp;
992: /* FALLTHROUGH */
1.18 markus 993: case 1: /* error, followed by error msg */
994: case 2: /* fatal error, "" */
1.1 deraadt 995: do {
1.30 deraadt 996: if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1 deraadt 997: lostconn(0);
998: *cp++ = ch;
999: } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1000:
1001: if (!iamremote)
1.107 deraadt 1002: (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1.1 deraadt 1003: ++errs;
1004: if (resp == 1)
1005: return (-1);
1006: exit(1);
1007: }
1008: /* NOTREACHED */
1009: }
1010:
1011: void
1.86 itojun 1012: usage(void)
1.1 deraadt 1013: {
1.83 stevesk 1014: (void) fprintf(stderr,
1.110 jmc 1015: "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1016: " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1.90 deraadt 1017: " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1.1 deraadt 1018: exit(1);
1019: }
1020:
1021: void
1.18 markus 1022: run_err(const char *fmt,...)
1.1 deraadt 1023: {
1024: static FILE *fp;
1025: va_list ap;
1026:
1027: ++errs;
1028: if (fp == NULL && !(fp = fdopen(remout, "w")))
1029: return;
1.18 markus 1030: (void) fprintf(fp, "%c", 0x01);
1031: (void) fprintf(fp, "scp: ");
1.73 markus 1032: va_start(ap, fmt);
1.18 markus 1033: (void) vfprintf(fp, fmt, ap);
1.73 markus 1034: va_end(ap);
1.18 markus 1035: (void) fprintf(fp, "\n");
1036: (void) fflush(fp);
1037:
1038: if (!iamremote) {
1.73 markus 1039: va_start(ap, fmt);
1.18 markus 1040: vfprintf(stderr, fmt, ap);
1.73 markus 1041: va_end(ap);
1.18 markus 1042: fprintf(stderr, "\n");
1043: }
1.1 deraadt 1044: }
1045:
1046: void
1.104 djm 1047: verifydir(char *cp)
1.1 deraadt 1048: {
1049: struct stat stb;
1050:
1051: if (!stat(cp, &stb)) {
1052: if (S_ISDIR(stb.st_mode))
1053: return;
1054: errno = ENOTDIR;
1055: }
1056: run_err("%s: %s", cp, strerror(errno));
1057: exit(1);
1058: }
1059:
1060: int
1.104 djm 1061: okname(char *cp0)
1.1 deraadt 1062: {
1063: int c;
1064: char *cp;
1065:
1066: cp = cp0;
1067: do {
1.75 deraadt 1068: c = (int)*cp;
1.1 deraadt 1069: if (c & 0200)
1070: goto bad;
1.101 markus 1071: if (!isalpha(c) && !isdigit(c)) {
1072: switch (c) {
1073: case '\'':
1074: case '"':
1075: case '`':
1076: case ' ':
1077: case '#':
1078: goto bad;
1079: default:
1080: break;
1081: }
1082: }
1.1 deraadt 1083: } while (*++cp);
1084: return (1);
1085:
1.25 markus 1086: bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1.1 deraadt 1087: return (0);
1088: }
1089:
1090: BUF *
1.104 djm 1091: allocbuf(BUF *bp, int fd, int blksize)
1.1 deraadt 1092: {
1093: size_t size;
1094: struct stat stb;
1095:
1096: if (fstat(fd, &stb) < 0) {
1097: run_err("fstat: %s", strerror(errno));
1098: return (0);
1099: }
1.95 markus 1100: size = roundup(stb.st_blksize, blksize);
1101: if (size == 0)
1.18 markus 1102: size = blksize;
1.1 deraadt 1103: if (bp->cnt >= size)
1104: return (bp);
1.18 markus 1105: if (bp->buf == NULL)
1106: bp->buf = xmalloc(size);
1107: else
1108: bp->buf = xrealloc(bp->buf, size);
1.81 markus 1109: memset(bp->buf, 0, size);
1.1 deraadt 1110: bp->cnt = size;
1111: return (bp);
1112: }
1113:
1114: void
1.104 djm 1115: lostconn(int signo)
1.1 deraadt 1116: {
1117: if (!iamremote)
1.74 markus 1118: write(STDERR_FILENO, "lost connection\n", 16);
1119: if (signo)
1120: _exit(1);
1121: else
1122: exit(1);
1.4 aaron 1123: }