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