Annotation of src/usr.bin/ssh/scp.c, Revision 1.119
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.119 ! dtucker 74: RCSID("$OpenBSD: scp.c,v 1.118 2004/09/15 18:46:04 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;
359: char *bp, *host, *src, *suser, *thost, *tuser;
360:
361: *targ++ = 0;
362: if (*targ == 0)
363: targ = ".";
364:
1.94 markus 365: if ((thost = strrchr(argv[argc - 1], '@'))) {
1.1 deraadt 366: /* user@host */
367: *thost++ = 0;
368: tuser = argv[argc - 1];
369: if (*tuser == '\0')
370: tuser = NULL;
371: } else {
372: thost = argv[argc - 1];
373: tuser = NULL;
374: }
375:
376: for (i = 0; i < argc - 1; i++) {
377: src = colon(argv[i]);
1.18 markus 378: if (src) { /* remote to remote */
1.84 stevesk 379: static char *ssh_options =
1.89 markus 380: "-x -o'ClearAllForwardings yes'";
1.1 deraadt 381: *src++ = 0;
382: if (*src == 0)
383: src = ".";
1.94 markus 384: host = strrchr(argv[i], '@');
1.34 deraadt 385: len = strlen(ssh_program) + strlen(argv[i]) +
1.35 deraadt 386: strlen(src) + (tuser ? strlen(tuser) : 0) +
1.84 stevesk 387: strlen(thost) + strlen(targ) +
388: strlen(ssh_options) + CMDNEEDS + 20;
1.18 markus 389: bp = xmalloc(len);
1.1 deraadt 390: if (host) {
391: *host++ = 0;
1.23 markus 392: host = cleanhostname(host);
1.1 deraadt 393: suser = argv[i];
394: if (*suser == '\0')
395: suser = pwd->pw_name;
1.102 markus 396: else if (!okname(suser)) {
397: xfree(bp);
1.1 deraadt 398: continue;
1.102 markus 399: }
400: if (tuser && !okname(tuser)) {
401: xfree(bp);
1.101 markus 402: continue;
1.102 markus 403: }
1.55 deraadt 404: snprintf(bp, len,
1.84 stevesk 405: "%s%s %s -n "
1.55 deraadt 406: "-l %s %s %s %s '%s%s%s:%s'",
1.44 deraadt 407: ssh_program, verbose_mode ? " -v" : "",
1.84 stevesk 408: ssh_options, suser, host, cmd, src,
1.44 deraadt 409: tuser ? tuser : "", tuser ? "@" : "",
410: thost, targ);
1.23 markus 411: } else {
412: host = cleanhostname(argv[i]);
1.55 deraadt 413: snprintf(bp, len,
1.84 stevesk 414: "exec %s%s %s -n %s "
1.55 deraadt 415: "%s %s '%s%s%s:%s'",
1.44 deraadt 416: ssh_program, verbose_mode ? " -v" : "",
1.84 stevesk 417: ssh_options, host, cmd, src,
1.44 deraadt 418: tuser ? tuser : "", tuser ? "@" : "",
419: thost, targ);
1.23 markus 420: }
1.18 markus 421: if (verbose_mode)
422: fprintf(stderr, "Executing: %s\n", bp);
1.109 markus 423: if (system(bp) != 0)
424: errs = 1;
1.18 markus 425: (void) xfree(bp);
426: } else { /* local to remote */
1.1 deraadt 427: if (remin == -1) {
428: len = strlen(targ) + CMDNEEDS + 20;
1.18 markus 429: bp = xmalloc(len);
1.55 deraadt 430: (void) snprintf(bp, len, "%s -t %s", cmd, targ);
1.23 markus 431: host = cleanhostname(thost);
1.35 deraadt 432: if (do_cmd(host, tuser, bp, &remin,
433: &remout, argc) < 0)
1.18 markus 434: exit(1);
1.1 deraadt 435: if (response() < 0)
436: exit(1);
1.18 markus 437: (void) xfree(bp);
1.1 deraadt 438: }
1.18 markus 439: source(1, argv + i);
1.1 deraadt 440: }
441: }
442: }
443:
444: void
1.104 djm 445: tolocal(int argc, char **argv)
1.1 deraadt 446: {
447: int i, len;
448: char *bp, *host, *src, *suser;
449:
450: for (i = 0; i < argc - 1; i++) {
1.18 markus 451: if (!(src = colon(argv[i]))) { /* Local to local. */
1.1 deraadt 452: len = strlen(_PATH_CP) + strlen(argv[i]) +
1.35 deraadt 453: strlen(argv[argc - 1]) + 20;
1.1 deraadt 454: bp = xmalloc(len);
1.55 deraadt 455: (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
1.35 deraadt 456: iamrecursive ? " -r" : "", pflag ? " -p" : "",
457: argv[i], argv[argc - 1]);
1.18 markus 458: if (verbose_mode)
459: fprintf(stderr, "Executing: %s\n", bp);
1.1 deraadt 460: if (system(bp))
461: ++errs;
1.18 markus 462: (void) xfree(bp);
1.1 deraadt 463: continue;
464: }
465: *src++ = 0;
466: if (*src == 0)
467: src = ".";
1.94 markus 468: if ((host = strrchr(argv[i], '@')) == NULL) {
1.1 deraadt 469: host = argv[i];
470: suser = NULL;
471: } else {
472: *host++ = 0;
473: suser = argv[i];
474: if (*suser == '\0')
475: suser = pwd->pw_name;
476: }
1.23 markus 477: host = cleanhostname(host);
1.1 deraadt 478: len = strlen(src) + CMDNEEDS + 20;
1.18 markus 479: bp = xmalloc(len);
1.55 deraadt 480: (void) snprintf(bp, len, "%s -f %s", cmd, src);
1.35 deraadt 481: if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
1.18 markus 482: (void) xfree(bp);
483: ++errs;
484: continue;
1.1 deraadt 485: }
1.18 markus 486: xfree(bp);
1.1 deraadt 487: sink(1, argv + argc - 1);
1.18 markus 488: (void) close(remin);
1.1 deraadt 489: remin = remout = -1;
490: }
491: }
492:
493: void
1.104 djm 494: source(int argc, char **argv)
1.1 deraadt 495: {
496: struct stat stb;
497: static BUF buffer;
498: BUF *bp;
1.97 fgsch 499: off_t i, amt, result, statbytes;
1.68 markus 500: int fd, haderr, indx;
1.1 deraadt 501: char *last, *name, buf[2048];
1.65 deraadt 502: int len;
1.1 deraadt 503:
504: for (indx = 0; indx < argc; ++indx) {
1.18 markus 505: name = argv[indx];
1.11 aaron 506: statbytes = 0;
1.65 deraadt 507: len = strlen(name);
508: while (len > 1 && name[len-1] == '/')
509: name[--len] = '\0';
1.85 markus 510: if (strchr(name, '\n') != NULL) {
511: run_err("%s: skipping, filename contains a newline",
512: name);
513: goto next;
514: }
1.1 deraadt 515: if ((fd = open(name, O_RDONLY, 0)) < 0)
516: goto syserr;
517: if (fstat(fd, &stb) < 0) {
518: syserr: run_err("%s: %s", name, strerror(errno));
519: goto next;
520: }
521: switch (stb.st_mode & S_IFMT) {
522: case S_IFREG:
523: break;
524: case S_IFDIR:
525: if (iamrecursive) {
526: rsource(name, &stb);
527: goto next;
528: }
529: /* FALLTHROUGH */
530: default:
531: run_err("%s: not a regular file", name);
532: goto next;
533: }
534: if ((last = strrchr(name, '/')) == NULL)
535: last = name;
536: else
537: ++last;
1.11 aaron 538: curfile = last;
1.1 deraadt 539: if (pflag) {
540: /*
541: * Make it compatible with possible future
542: * versions expecting microseconds.
543: */
1.55 deraadt 544: (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
1.47 markus 545: (u_long) stb.st_mtime,
546: (u_long) stb.st_atime);
1.107 deraadt 547: (void) atomicio(vwrite, remout, buf, strlen(buf));
1.1 deraadt 548: if (response() < 0)
549: goto next;
550: }
551: #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1.61 markus 552: snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1.47 markus 553: (u_int) (stb.st_mode & FILEMODEMASK),
1.62 markus 554: (long long)stb.st_size, last);
1.18 markus 555: if (verbose_mode) {
556: fprintf(stderr, "Sending file modes: %s", buf);
557: }
1.107 deraadt 558: (void) atomicio(vwrite, remout, buf, strlen(buf));
1.1 deraadt 559: if (response() < 0)
560: goto next;
561: if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
1.18 markus 562: next: (void) close(fd);
1.1 deraadt 563: continue;
564: }
1.97 fgsch 565: if (showprogress)
566: start_progress_meter(curfile, stb.st_size, &statbytes);
1.1 deraadt 567: /* Keep writing after an error so that we stay sync'd up. */
568: for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
569: amt = bp->cnt;
570: if (i + amt > stb.st_size)
571: amt = stb.st_size - i;
572: if (!haderr) {
1.30 deraadt 573: result = atomicio(read, fd, bp->buf, amt);
1.1 deraadt 574: if (result != amt)
575: haderr = result >= 0 ? EIO : errno;
576: }
577: if (haderr)
1.107 deraadt 578: (void) atomicio(vwrite, remout, bp->buf, amt);
1.1 deraadt 579: else {
1.107 deraadt 580: result = atomicio(vwrite, remout, bp->buf, amt);
1.1 deraadt 581: if (result != amt)
582: haderr = result >= 0 ? EIO : errno;
1.4 aaron 583: statbytes += result;
1.1 deraadt 584: }
1.113 djm 585: if (limit_rate)
1.99 markus 586: bwlimit(amt);
1.1 deraadt 587: }
1.18 markus 588: if (showprogress)
1.97 fgsch 589: stop_progress_meter();
1.4 aaron 590:
1.1 deraadt 591: if (close(fd) < 0 && !haderr)
592: haderr = errno;
593: if (!haderr)
1.107 deraadt 594: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 595: else
596: run_err("%s: %s", name, strerror(haderr));
1.18 markus 597: (void) response();
1.1 deraadt 598: }
599: }
600:
601: void
1.104 djm 602: rsource(char *name, struct stat *statp)
1.1 deraadt 603: {
604: DIR *dirp;
605: struct dirent *dp;
606: char *last, *vect[1], path[1100];
607:
608: if (!(dirp = opendir(name))) {
609: run_err("%s: %s", name, strerror(errno));
610: return;
611: }
612: last = strrchr(name, '/');
613: if (last == 0)
614: last = name;
615: else
616: last++;
617: if (pflag) {
1.55 deraadt 618: (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
1.47 markus 619: (u_long) statp->st_mtime,
620: (u_long) statp->st_atime);
1.107 deraadt 621: (void) atomicio(vwrite, remout, path, strlen(path));
1.1 deraadt 622: if (response() < 0) {
623: closedir(dirp);
624: return;
625: }
626: }
1.55 deraadt 627: (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1.47 markus 628: (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1.18 markus 629: if (verbose_mode)
630: fprintf(stderr, "Entering directory: %s", path);
1.107 deraadt 631: (void) atomicio(vwrite, remout, path, strlen(path));
1.1 deraadt 632: if (response() < 0) {
633: closedir(dirp);
634: return;
635: }
1.63 stevesk 636: while ((dp = readdir(dirp)) != NULL) {
1.1 deraadt 637: if (dp->d_ino == 0)
638: continue;
639: if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
640: continue;
641: if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
642: run_err("%s/%s: name too long", name, dp->d_name);
643: continue;
644: }
1.55 deraadt 645: (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1.1 deraadt 646: vect[0] = path;
647: source(1, vect);
648: }
1.18 markus 649: (void) closedir(dirp);
1.107 deraadt 650: (void) atomicio(vwrite, remout, "E\n", 2);
1.18 markus 651: (void) response();
1.1 deraadt 652: }
653:
654: void
1.99 markus 655: bwlimit(int amount)
656: {
657: static struct timeval bwstart, bwend;
658: static int lamt, thresh = 16384;
1.115 avsm 659: u_int64_t waitlen;
1.99 markus 660: struct timespec ts, rm;
661:
662: if (!timerisset(&bwstart)) {
663: gettimeofday(&bwstart, NULL);
664: return;
665: }
666:
667: lamt += amount;
668: if (lamt < thresh)
669: return;
670:
671: gettimeofday(&bwend, NULL);
672: timersub(&bwend, &bwstart, &bwend);
673: if (!timerisset(&bwend))
674: return;
675:
676: lamt *= 8;
1.115 avsm 677: waitlen = (double)1000000L * lamt / limit_rate;
1.99 markus 678:
1.115 avsm 679: bwstart.tv_sec = waitlen / 1000000L;
680: bwstart.tv_usec = waitlen % 1000000L;
1.99 markus 681:
682: if (timercmp(&bwstart, &bwend, >)) {
683: timersub(&bwstart, &bwend, &bwend);
684:
685: /* Adjust the wait time */
686: if (bwend.tv_sec) {
687: thresh /= 2;
688: if (thresh < 2048)
689: thresh = 2048;
690: } else if (bwend.tv_usec < 100) {
691: thresh *= 2;
692: if (thresh > 32768)
693: thresh = 32768;
694: }
695:
696: TIMEVAL_TO_TIMESPEC(&bwend, &ts);
697: while (nanosleep(&ts, &rm) == -1) {
698: if (errno != EINTR)
699: break;
700: ts = rm;
701: }
702: }
703:
704: lamt = 0;
705: gettimeofday(&bwstart, NULL);
706: }
707:
708: void
1.104 djm 709: sink(int argc, char **argv)
1.1 deraadt 710: {
711: static BUF buffer;
712: struct stat stb;
1.18 markus 713: enum {
714: YES, NO, DISPLAYED
715: } wrerr;
1.1 deraadt 716: BUF *bp;
717: off_t i, j;
718: int amt, count, exists, first, mask, mode, ofd, omode;
1.97 fgsch 719: off_t size, statbytes;
1.36 deraadt 720: int setimes, targisdir, wrerrno = 0;
1.1 deraadt 721: char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
1.40 markus 722: struct timeval tv[2];
1.1 deraadt 723:
1.66 stevesk 724: #define atime tv[0]
725: #define mtime tv[1]
1.118 deraadt 726: #define SCREWUP(str) { why = str; goto screwup; }
1.1 deraadt 727:
728: setimes = targisdir = 0;
729: mask = umask(0);
730: if (!pflag)
1.18 markus 731: (void) umask(mask);
1.1 deraadt 732: if (argc != 1) {
733: run_err("ambiguous target");
734: exit(1);
735: }
736: targ = *argv;
737: if (targetshouldbedirectory)
738: verifydir(targ);
1.18 markus 739:
1.107 deraadt 740: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 741: if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
742: targisdir = 1;
743: for (first = 1;; first = 0) {
744: cp = buf;
1.30 deraadt 745: if (atomicio(read, remin, cp, 1) <= 0)
1.1 deraadt 746: return;
747: if (*cp++ == '\n')
748: SCREWUP("unexpected <newline>");
749: do {
1.30 deraadt 750: if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1 deraadt 751: SCREWUP("lost connection");
752: *cp++ = ch;
753: } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
754: *cp = 0;
1.114 markus 755: if (verbose_mode)
756: fprintf(stderr, "Sink: %s", buf);
1.1 deraadt 757:
758: if (buf[0] == '\01' || buf[0] == '\02') {
759: if (iamremote == 0)
1.107 deraadt 760: (void) atomicio(vwrite, STDERR_FILENO,
1.44 deraadt 761: buf + 1, strlen(buf + 1));
1.1 deraadt 762: if (buf[0] == '\02')
763: exit(1);
764: ++errs;
765: continue;
766: }
767: if (buf[0] == 'E') {
1.107 deraadt 768: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 769: return;
770: }
771: if (ch == '\n')
772: *--cp = 0;
773:
774: cp = buf;
775: if (*cp == 'T') {
776: setimes++;
777: cp++;
1.66 stevesk 778: mtime.tv_sec = strtol(cp, &cp, 10);
779: if (!cp || *cp++ != ' ')
1.1 deraadt 780: SCREWUP("mtime.sec not delimited");
1.66 stevesk 781: mtime.tv_usec = strtol(cp, &cp, 10);
782: if (!cp || *cp++ != ' ')
1.1 deraadt 783: SCREWUP("mtime.usec not delimited");
1.66 stevesk 784: atime.tv_sec = strtol(cp, &cp, 10);
785: if (!cp || *cp++ != ' ')
1.1 deraadt 786: SCREWUP("atime.sec not delimited");
1.66 stevesk 787: atime.tv_usec = strtol(cp, &cp, 10);
788: if (!cp || *cp++ != '\0')
1.1 deraadt 789: SCREWUP("atime.usec not delimited");
1.107 deraadt 790: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 791: continue;
792: }
793: if (*cp != 'C' && *cp != 'D') {
794: /*
795: * Check for the case "rcp remote:foo\* local:bar".
796: * In this case, the line "No match." can be returned
797: * by the shell before the rcp command on the remote is
798: * executed so the ^Aerror_message convention isn't
799: * followed.
800: */
801: if (first) {
802: run_err("%s", cp);
803: exit(1);
804: }
805: SCREWUP("expected control record");
806: }
807: mode = 0;
808: for (++cp; cp < buf + 5; cp++) {
809: if (*cp < '0' || *cp > '7')
810: SCREWUP("bad mode");
811: mode = (mode << 3) | (*cp - '0');
812: }
813: if (*cp++ != ' ')
814: SCREWUP("mode not delimited");
815:
1.63 stevesk 816: for (size = 0; isdigit(*cp);)
1.1 deraadt 817: size = size * 10 + (*cp++ - '0');
818: if (*cp++ != ' ')
819: SCREWUP("size not delimited");
1.114 markus 820: if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
821: run_err("error: unexpected filename: %s", cp);
822: exit(1);
823: }
1.1 deraadt 824: if (targisdir) {
825: static char *namebuf;
826: static int cursize;
827: size_t need;
828:
829: need = strlen(targ) + strlen(cp) + 250;
1.55 deraadt 830: if (need > cursize) {
1.58 danh 831: if (namebuf)
832: xfree(namebuf);
1.18 markus 833: namebuf = xmalloc(need);
1.55 deraadt 834: cursize = need;
835: }
836: (void) snprintf(namebuf, need, "%s%s%s", targ,
1.88 mouring 837: strcmp(targ, "/") ? "/" : "", cp);
1.1 deraadt 838: np = namebuf;
839: } else
840: np = targ;
1.12 aaron 841: curfile = cp;
1.1 deraadt 842: exists = stat(np, &stb) == 0;
843: if (buf[0] == 'D') {
844: int mod_flag = pflag;
1.114 markus 845: if (!iamrecursive)
846: SCREWUP("received directory without -r");
1.1 deraadt 847: if (exists) {
848: if (!S_ISDIR(stb.st_mode)) {
849: errno = ENOTDIR;
850: goto bad;
851: }
852: if (pflag)
1.18 markus 853: (void) chmod(np, mode);
1.1 deraadt 854: } else {
1.18 markus 855: /* Handle copying from a read-only
856: directory */
1.1 deraadt 857: mod_flag = 1;
858: if (mkdir(np, mode | S_IRWXU) < 0)
859: goto bad;
860: }
1.58 danh 861: vect[0] = xstrdup(np);
1.1 deraadt 862: sink(1, vect);
863: if (setimes) {
864: setimes = 0;
1.59 deraadt 865: if (utimes(vect[0], tv) < 0)
1.18 markus 866: run_err("%s: set times: %s",
1.59 deraadt 867: vect[0], strerror(errno));
1.1 deraadt 868: }
869: if (mod_flag)
1.59 deraadt 870: (void) chmod(vect[0], mode);
871: if (vect[0])
872: xfree(vect[0]);
1.1 deraadt 873: continue;
874: }
875: omode = mode;
876: mode |= S_IWRITE;
1.71 markus 877: if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1.1 deraadt 878: bad: run_err("%s: %s", np, strerror(errno));
879: continue;
880: }
1.107 deraadt 881: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 882: if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
1.18 markus 883: (void) close(ofd);
1.1 deraadt 884: continue;
885: }
886: cp = bp->buf;
887: wrerr = NO;
1.7 deraadt 888:
1.12 aaron 889: statbytes = 0;
1.97 fgsch 890: if (showprogress)
891: start_progress_meter(curfile, size, &statbytes);
1.1 deraadt 892: for (count = i = 0; i < size; i += 4096) {
893: amt = 4096;
894: if (i + amt > size)
895: amt = size - i;
896: count += amt;
897: do {
1.117 avsm 898: j = atomicio(read, remin, cp, amt);
899: if (j <= 0) {
1.1 deraadt 900: run_err("%s", j ? strerror(errno) :
1.63 stevesk 901: "dropped connection");
1.1 deraadt 902: exit(1);
903: }
904: amt -= j;
905: cp += j;
1.18 markus 906: statbytes += j;
1.1 deraadt 907: } while (amt > 0);
1.112 djm 908:
1.113 djm 909: if (limit_rate)
1.99 markus 910: bwlimit(4096);
911:
1.1 deraadt 912: if (count == bp->cnt) {
913: /* Keep reading so we stay sync'd up. */
914: if (wrerr == NO) {
1.107 deraadt 915: j = atomicio(vwrite, ofd, bp->buf, count);
1.1 deraadt 916: if (j != count) {
917: wrerr = YES;
1.18 markus 918: wrerrno = j >= 0 ? EIO : errno;
1.1 deraadt 919: }
920: }
921: count = 0;
922: cp = bp->buf;
923: }
924: }
1.7 deraadt 925: if (showprogress)
1.97 fgsch 926: stop_progress_meter();
1.1 deraadt 927: if (count != 0 && wrerr == NO &&
1.107 deraadt 928: (j = atomicio(vwrite, ofd, bp->buf, count)) != count) {
1.1 deraadt 929: wrerr = YES;
1.18 markus 930: wrerrno = j >= 0 ? EIO : errno;
1.1 deraadt 931: }
1.98 djm 932: if (wrerr == NO && ftruncate(ofd, size) != 0) {
1.1 deraadt 933: run_err("%s: truncate: %s", np, strerror(errno));
934: wrerr = DISPLAYED;
935: }
936: if (pflag) {
937: if (exists || omode != mode)
1.116 dtucker 938: if (fchmod(ofd, omode)) {
1.1 deraadt 939: run_err("%s: set mode: %s",
1.63 stevesk 940: np, strerror(errno));
1.116 dtucker 941: wrerr = DISPLAYED;
942: }
1.1 deraadt 943: } else {
944: if (!exists && omode != mode)
1.116 dtucker 945: if (fchmod(ofd, omode & ~mask)) {
1.1 deraadt 946: run_err("%s: set mode: %s",
1.63 stevesk 947: np, strerror(errno));
1.116 dtucker 948: wrerr = DISPLAYED;
949: }
1.1 deraadt 950: }
1.33 provos 951: if (close(ofd) == -1) {
952: wrerr = YES;
953: wrerrno = errno;
954: }
1.18 markus 955: (void) response();
1.1 deraadt 956: if (setimes && wrerr == NO) {
957: setimes = 0;
1.40 markus 958: if (utimes(np, tv) < 0) {
1.1 deraadt 959: run_err("%s: set times: %s",
1.63 stevesk 960: np, strerror(errno));
1.1 deraadt 961: wrerr = DISPLAYED;
962: }
963: }
1.18 markus 964: switch (wrerr) {
1.1 deraadt 965: case YES:
966: run_err("%s: %s", np, strerror(wrerrno));
967: break;
968: case NO:
1.107 deraadt 969: (void) atomicio(vwrite, remout, "", 1);
1.1 deraadt 970: break;
971: case DISPLAYED:
972: break;
973: }
974: }
975: screwup:
976: run_err("protocol error: %s", why);
977: exit(1);
978: }
979:
980: int
1.86 itojun 981: response(void)
1.1 deraadt 982: {
983: char ch, *cp, resp, rbuf[2048];
984:
1.30 deraadt 985: if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1.1 deraadt 986: lostconn(0);
987:
988: cp = rbuf;
1.18 markus 989: switch (resp) {
990: case 0: /* ok */
1.1 deraadt 991: return (0);
992: default:
993: *cp++ = resp;
994: /* FALLTHROUGH */
1.18 markus 995: case 1: /* error, followed by error msg */
996: case 2: /* fatal error, "" */
1.1 deraadt 997: do {
1.30 deraadt 998: if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1 deraadt 999: lostconn(0);
1000: *cp++ = ch;
1001: } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1002:
1003: if (!iamremote)
1.107 deraadt 1004: (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1.1 deraadt 1005: ++errs;
1006: if (resp == 1)
1007: return (-1);
1008: exit(1);
1009: }
1010: /* NOTREACHED */
1011: }
1012:
1013: void
1.86 itojun 1014: usage(void)
1.1 deraadt 1015: {
1.83 stevesk 1016: (void) fprintf(stderr,
1.110 jmc 1017: "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1018: " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1.90 deraadt 1019: " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1.1 deraadt 1020: exit(1);
1021: }
1022:
1023: void
1.18 markus 1024: run_err(const char *fmt,...)
1.1 deraadt 1025: {
1026: static FILE *fp;
1027: va_list ap;
1028:
1029: ++errs;
1030: if (fp == NULL && !(fp = fdopen(remout, "w")))
1031: return;
1.18 markus 1032: (void) fprintf(fp, "%c", 0x01);
1033: (void) fprintf(fp, "scp: ");
1.73 markus 1034: va_start(ap, fmt);
1.18 markus 1035: (void) vfprintf(fp, fmt, ap);
1.73 markus 1036: va_end(ap);
1.18 markus 1037: (void) fprintf(fp, "\n");
1038: (void) fflush(fp);
1039:
1040: if (!iamremote) {
1.73 markus 1041: va_start(ap, fmt);
1.18 markus 1042: vfprintf(stderr, fmt, ap);
1.73 markus 1043: va_end(ap);
1.18 markus 1044: fprintf(stderr, "\n");
1045: }
1.1 deraadt 1046: }
1047:
1048: void
1.104 djm 1049: verifydir(char *cp)
1.1 deraadt 1050: {
1051: struct stat stb;
1052:
1053: if (!stat(cp, &stb)) {
1054: if (S_ISDIR(stb.st_mode))
1055: return;
1056: errno = ENOTDIR;
1057: }
1058: run_err("%s: %s", cp, strerror(errno));
1059: exit(1);
1060: }
1061:
1062: int
1.104 djm 1063: okname(char *cp0)
1.1 deraadt 1064: {
1065: int c;
1066: char *cp;
1067:
1068: cp = cp0;
1069: do {
1.75 deraadt 1070: c = (int)*cp;
1.1 deraadt 1071: if (c & 0200)
1072: goto bad;
1.101 markus 1073: if (!isalpha(c) && !isdigit(c)) {
1074: switch (c) {
1075: case '\'':
1076: case '"':
1077: case '`':
1078: case ' ':
1079: case '#':
1080: goto bad;
1081: default:
1082: break;
1083: }
1084: }
1.1 deraadt 1085: } while (*++cp);
1086: return (1);
1087:
1.25 markus 1088: bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1.1 deraadt 1089: return (0);
1090: }
1091:
1092: BUF *
1.104 djm 1093: allocbuf(BUF *bp, int fd, int blksize)
1.1 deraadt 1094: {
1095: size_t size;
1096: struct stat stb;
1097:
1098: if (fstat(fd, &stb) < 0) {
1099: run_err("fstat: %s", strerror(errno));
1100: return (0);
1101: }
1.95 markus 1102: size = roundup(stb.st_blksize, blksize);
1103: if (size == 0)
1.18 markus 1104: size = blksize;
1.1 deraadt 1105: if (bp->cnt >= size)
1106: return (bp);
1.18 markus 1107: if (bp->buf == NULL)
1108: bp->buf = xmalloc(size);
1109: else
1110: bp->buf = xrealloc(bp->buf, size);
1.81 markus 1111: memset(bp->buf, 0, size);
1.1 deraadt 1112: bp->cnt = size;
1113: return (bp);
1114: }
1115:
1116: void
1.104 djm 1117: lostconn(int signo)
1.1 deraadt 1118: {
1119: if (!iamremote)
1.74 markus 1120: write(STDERR_FILENO, "lost connection\n", 16);
1121: if (signo)
1122: _exit(1);
1123: else
1124: exit(1);
1.4 aaron 1125: }