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