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