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