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