- stevesk@cvs.openbsd.org 2006/07/22 19:08:54
[openssh-git.git] / scp.c
blob72c4ee430115bf3168c45e97618b98068a01e028
1 /* $OpenBSD: scp.c,v 1.149 2006/07/22 19:08:54 stevesk Exp $ */
2 /*
3 * scp - secure remote copy. This is basically patched BSD rcp which
4 * uses ssh to do the data transfer (instead of using rcmd).
6 * NOTE: This version should NOT be suid root. (This uses ssh to
7 * do the transfer and ssh has the necessary privileges.)
9 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
18 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
19 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 * Parts from:
45 * Copyright (c) 1983, 1990, 1992, 1993, 1995
46 * The Regents of the University of California. All rights reserved.
48 * Redistribution and use in source and binary forms, with or without
49 * modification, are permitted provided that the following conditions
50 * are met:
51 * 1. Redistributions of source code must retain the above copyright
52 * notice, this list of conditions and the following disclaimer.
53 * 2. Redistributions in binary form must reproduce the above copyright
54 * notice, this list of conditions and the following disclaimer in the
55 * documentation and/or other materials provided with the distribution.
56 * 3. Neither the name of the University nor the names of its contributors
57 * may be used to endorse or promote products derived from this software
58 * without specific prior written permission.
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
74 #include "includes.h"
76 #include <sys/types.h>
77 #ifdef HAVE_SYS_STAT_H
78 # include <sys/stat.h>
79 #endif
80 #include <sys/wait.h>
82 #include <ctype.h>
83 #include <dirent.h>
84 #include <errno.h>
85 #include <fcntl.h>
86 #include <pwd.h>
87 #include <signal.h>
88 #include <stdarg.h>
89 #include <time.h>
90 #include <unistd.h>
92 #include "xmalloc.h"
93 #include "atomicio.h"
94 #include "pathnames.h"
95 #include "log.h"
96 #include "misc.h"
97 #include "progressmeter.h"
99 extern char *__progname;
101 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
103 void bwlimit(int);
105 /* Struct for addargs */
106 arglist args;
108 /* Bandwidth limit */
109 off_t limit_rate = 0;
111 /* Name of current file being transferred. */
112 char *curfile;
114 /* This is set to non-zero to enable verbose mode. */
115 int verbose_mode = 0;
117 /* This is set to zero if the progressmeter is not desired. */
118 int showprogress = 1;
120 /* This is the program to execute for the secured connection. ("ssh" or -S) */
121 char *ssh_program = _PATH_SSH_PROGRAM;
123 /* This is used to store the pid of ssh_program */
124 pid_t do_cmd_pid = -1;
126 static void
127 killchild(int signo)
129 if (do_cmd_pid > 1) {
130 kill(do_cmd_pid, signo ? signo : SIGTERM);
131 waitpid(do_cmd_pid, NULL, 0);
134 if (signo)
135 _exit(1);
136 exit(1);
139 static int
140 do_local_cmd(arglist *a)
142 u_int i;
143 int status;
144 pid_t pid;
146 if (a->num == 0)
147 fatal("do_local_cmd: no arguments");
149 if (verbose_mode) {
150 fprintf(stderr, "Executing:");
151 for (i = 0; i < a->num; i++)
152 fprintf(stderr, " %s", a->list[i]);
153 fprintf(stderr, "\n");
155 if ((pid = fork()) == -1)
156 fatal("do_local_cmd: fork: %s", strerror(errno));
158 if (pid == 0) {
159 execvp(a->list[0], a->list);
160 perror(a->list[0]);
161 exit(1);
164 do_cmd_pid = pid;
165 signal(SIGTERM, killchild);
166 signal(SIGINT, killchild);
167 signal(SIGHUP, killchild);
169 while (waitpid(pid, &status, 0) == -1)
170 if (errno != EINTR)
171 fatal("do_local_cmd: waitpid: %s", strerror(errno));
173 do_cmd_pid = -1;
175 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
176 return (-1);
178 return (0);
182 * This function executes the given command as the specified user on the
183 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
184 * assigns the input and output file descriptors on success.
188 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
190 int pin[2], pout[2], reserved[2];
192 if (verbose_mode)
193 fprintf(stderr,
194 "Executing: program %s host %s, user %s, command %s\n",
195 ssh_program, host,
196 remuser ? remuser : "(unspecified)", cmd);
199 * Reserve two descriptors so that the real pipes won't get
200 * descriptors 0 and 1 because that will screw up dup2 below.
202 if (pipe(reserved) < 0)
203 fatal("pipe: %s", strerror(errno));
205 /* Create a socket pair for communicating with ssh. */
206 if (pipe(pin) < 0)
207 fatal("pipe: %s", strerror(errno));
208 if (pipe(pout) < 0)
209 fatal("pipe: %s", strerror(errno));
211 /* Free the reserved descriptors. */
212 close(reserved[0]);
213 close(reserved[1]);
215 /* Fork a child to execute the command on the remote host using ssh. */
216 do_cmd_pid = fork();
217 if (do_cmd_pid == 0) {
218 /* Child. */
219 close(pin[1]);
220 close(pout[0]);
221 dup2(pin[0], 0);
222 dup2(pout[1], 1);
223 close(pin[0]);
224 close(pout[1]);
226 replacearg(&args, 0, "%s", ssh_program);
227 if (remuser != NULL)
228 addargs(&args, "-l%s", remuser);
229 addargs(&args, "%s", host);
230 addargs(&args, "%s", cmd);
232 execvp(ssh_program, args.list);
233 perror(ssh_program);
234 exit(1);
235 } else if (do_cmd_pid == -1) {
236 fatal("fork: %s", strerror(errno));
238 /* Parent. Close the other side, and return the local side. */
239 close(pin[0]);
240 *fdout = pin[1];
241 close(pout[1]);
242 *fdin = pout[0];
243 signal(SIGTERM, killchild);
244 signal(SIGINT, killchild);
245 signal(SIGHUP, killchild);
246 return 0;
249 typedef struct {
250 size_t cnt;
251 char *buf;
252 } BUF;
254 BUF *allocbuf(BUF *, int, int);
255 void lostconn(int);
256 int okname(char *);
257 void run_err(const char *,...);
258 void verifydir(char *);
260 struct passwd *pwd;
261 uid_t userid;
262 int errs, remin, remout;
263 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
265 #define CMDNEEDS 64
266 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
268 int response(void);
269 void rsource(char *, struct stat *);
270 void sink(int, char *[]);
271 void source(int, char *[]);
272 void tolocal(int, char *[]);
273 void toremote(char *, int, char *[]);
274 void usage(void);
277 main(int argc, char **argv)
279 int ch, fflag, tflag, status, n;
280 double speed;
281 char *targ, *endp, **newargv;
282 extern char *optarg;
283 extern int optind;
285 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
286 sanitise_stdfd();
288 /* Copy argv, because we modify it */
289 newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv));
290 for (n = 0; n < argc; n++)
291 newargv[n] = xstrdup(argv[n]);
292 argv = newargv;
294 __progname = ssh_get_progname(argv[0]);
296 memset(&args, '\0', sizeof(args));
297 args.list = NULL;
298 addargs(&args, "%s", ssh_program);
299 addargs(&args, "-x");
300 addargs(&args, "-oForwardAgent no");
301 addargs(&args, "-oPermitLocalCommand no");
302 addargs(&args, "-oClearAllForwardings yes");
304 fflag = tflag = 0;
305 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
306 switch (ch) {
307 /* User-visible flags. */
308 case '1':
309 case '2':
310 case '4':
311 case '6':
312 case 'C':
313 addargs(&args, "-%c", ch);
314 break;
315 case 'o':
316 case 'c':
317 case 'i':
318 case 'F':
319 addargs(&args, "-%c%s", ch, optarg);
320 break;
321 case 'P':
322 addargs(&args, "-p%s", optarg);
323 break;
324 case 'B':
325 addargs(&args, "-oBatchmode yes");
326 break;
327 case 'l':
328 speed = strtod(optarg, &endp);
329 if (speed <= 0 || *endp != '\0')
330 usage();
331 limit_rate = speed * 1024;
332 break;
333 case 'p':
334 pflag = 1;
335 break;
336 case 'r':
337 iamrecursive = 1;
338 break;
339 case 'S':
340 ssh_program = xstrdup(optarg);
341 break;
342 case 'v':
343 addargs(&args, "-v");
344 verbose_mode = 1;
345 break;
346 case 'q':
347 addargs(&args, "-q");
348 showprogress = 0;
349 break;
351 /* Server options. */
352 case 'd':
353 targetshouldbedirectory = 1;
354 break;
355 case 'f': /* "from" */
356 iamremote = 1;
357 fflag = 1;
358 break;
359 case 't': /* "to" */
360 iamremote = 1;
361 tflag = 1;
362 #ifdef HAVE_CYGWIN
363 setmode(0, O_BINARY);
364 #endif
365 break;
366 default:
367 usage();
369 argc -= optind;
370 argv += optind;
372 if ((pwd = getpwuid(userid = getuid())) == NULL)
373 fatal("unknown user %u", (u_int) userid);
375 if (!isatty(STDERR_FILENO))
376 showprogress = 0;
378 remin = STDIN_FILENO;
379 remout = STDOUT_FILENO;
381 if (fflag) {
382 /* Follow "protocol", send data. */
383 (void) response();
384 source(argc, argv);
385 exit(errs != 0);
387 if (tflag) {
388 /* Receive data. */
389 sink(argc, argv);
390 exit(errs != 0);
392 if (argc < 2)
393 usage();
394 if (argc > 2)
395 targetshouldbedirectory = 1;
397 remin = remout = -1;
398 do_cmd_pid = -1;
399 /* Command to be executed on remote system using "ssh". */
400 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
401 verbose_mode ? " -v" : "",
402 iamrecursive ? " -r" : "", pflag ? " -p" : "",
403 targetshouldbedirectory ? " -d" : "");
405 (void) signal(SIGPIPE, lostconn);
407 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
408 toremote(targ, argc, argv);
409 else {
410 if (targetshouldbedirectory)
411 verifydir(argv[argc - 1]);
412 tolocal(argc, argv); /* Dest is local host. */
415 * Finally check the exit status of the ssh process, if one was forked
416 * and no error has occured yet
418 if (do_cmd_pid != -1 && errs == 0) {
419 if (remin != -1)
420 (void) close(remin);
421 if (remout != -1)
422 (void) close(remout);
423 if (waitpid(do_cmd_pid, &status, 0) == -1)
424 errs = 1;
425 else {
426 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
427 errs = 1;
430 exit(errs != 0);
433 void
434 toremote(char *targ, int argc, char **argv)
436 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
437 arglist alist;
438 int i;
440 memset(&alist, '\0', sizeof(alist));
441 alist.list = NULL;
443 *targ++ = 0;
444 if (*targ == 0)
445 targ = ".";
447 arg = xstrdup(argv[argc - 1]);
448 if ((thost = strrchr(arg, '@'))) {
449 /* user@host */
450 *thost++ = 0;
451 tuser = arg;
452 if (*tuser == '\0')
453 tuser = NULL;
454 } else {
455 thost = arg;
456 tuser = NULL;
459 if (tuser != NULL && !okname(tuser)) {
460 xfree(arg);
461 return;
464 for (i = 0; i < argc - 1; i++) {
465 src = colon(argv[i]);
466 if (src) { /* remote to remote */
467 freeargs(&alist);
468 addargs(&alist, "%s", ssh_program);
469 if (verbose_mode)
470 addargs(&alist, "-v");
471 addargs(&alist, "-x");
472 addargs(&alist, "-oClearAllForwardings yes");
473 addargs(&alist, "-n");
475 *src++ = 0;
476 if (*src == 0)
477 src = ".";
478 host = strrchr(argv[i], '@');
480 if (host) {
481 *host++ = 0;
482 host = cleanhostname(host);
483 suser = argv[i];
484 if (*suser == '\0')
485 suser = pwd->pw_name;
486 else if (!okname(suser))
487 continue;
488 addargs(&alist, "-l");
489 addargs(&alist, "%s", suser);
490 } else {
491 host = cleanhostname(argv[i]);
493 addargs(&alist, "%s", host);
494 addargs(&alist, "%s", cmd);
495 addargs(&alist, "%s", src);
496 addargs(&alist, "%s%s%s:%s",
497 tuser ? tuser : "", tuser ? "@" : "",
498 thost, targ);
499 if (do_local_cmd(&alist) != 0)
500 errs = 1;
501 } else { /* local to remote */
502 if (remin == -1) {
503 xasprintf(&bp, "%s -t %s", cmd, targ);
504 host = cleanhostname(thost);
505 if (do_cmd(host, tuser, bp, &remin,
506 &remout) < 0)
507 exit(1);
508 if (response() < 0)
509 exit(1);
510 (void) xfree(bp);
512 source(1, argv + i);
515 xfree(arg);
518 void
519 tolocal(int argc, char **argv)
521 char *bp, *host, *src, *suser;
522 arglist alist;
523 int i;
525 memset(&alist, '\0', sizeof(alist));
526 alist.list = NULL;
528 for (i = 0; i < argc - 1; i++) {
529 if (!(src = colon(argv[i]))) { /* Local to local. */
530 freeargs(&alist);
531 addargs(&alist, "%s", _PATH_CP);
532 if (iamrecursive)
533 addargs(&alist, "-r");
534 if (pflag)
535 addargs(&alist, "-p");
536 addargs(&alist, "%s", argv[i]);
537 addargs(&alist, "%s", argv[argc-1]);
538 if (do_local_cmd(&alist))
539 ++errs;
540 continue;
542 *src++ = 0;
543 if (*src == 0)
544 src = ".";
545 if ((host = strrchr(argv[i], '@')) == NULL) {
546 host = argv[i];
547 suser = NULL;
548 } else {
549 *host++ = 0;
550 suser = argv[i];
551 if (*suser == '\0')
552 suser = pwd->pw_name;
554 host = cleanhostname(host);
555 xasprintf(&bp, "%s -f %s", cmd, src);
556 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
557 (void) xfree(bp);
558 ++errs;
559 continue;
561 xfree(bp);
562 sink(1, argv + argc - 1);
563 (void) close(remin);
564 remin = remout = -1;
568 void
569 source(int argc, char **argv)
571 struct stat stb;
572 static BUF buffer;
573 BUF *bp;
574 off_t i, amt, statbytes;
575 size_t result;
576 int fd = -1, haderr, indx;
577 char *last, *name, buf[2048];
578 int len;
580 for (indx = 0; indx < argc; ++indx) {
581 name = argv[indx];
582 statbytes = 0;
583 len = strlen(name);
584 while (len > 1 && name[len-1] == '/')
585 name[--len] = '\0';
586 if (strchr(name, '\n') != NULL) {
587 run_err("%s: skipping, filename contains a newline",
588 name);
589 goto next;
591 if ((fd = open(name, O_RDONLY, 0)) < 0)
592 goto syserr;
593 if (fstat(fd, &stb) < 0) {
594 syserr: run_err("%s: %s", name, strerror(errno));
595 goto next;
597 switch (stb.st_mode & S_IFMT) {
598 case S_IFREG:
599 break;
600 case S_IFDIR:
601 if (iamrecursive) {
602 rsource(name, &stb);
603 goto next;
605 /* FALLTHROUGH */
606 default:
607 run_err("%s: not a regular file", name);
608 goto next;
610 if ((last = strrchr(name, '/')) == NULL)
611 last = name;
612 else
613 ++last;
614 curfile = last;
615 if (pflag) {
617 * Make it compatible with possible future
618 * versions expecting microseconds.
620 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
621 (u_long) stb.st_mtime,
622 (u_long) stb.st_atime);
623 (void) atomicio(vwrite, remout, buf, strlen(buf));
624 if (response() < 0)
625 goto next;
627 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
628 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
629 (u_int) (stb.st_mode & FILEMODEMASK),
630 (long long)stb.st_size, last);
631 if (verbose_mode) {
632 fprintf(stderr, "Sending file modes: %s", buf);
634 (void) atomicio(vwrite, remout, buf, strlen(buf));
635 if (response() < 0)
636 goto next;
637 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
638 next: if (fd != -1) {
639 (void) close(fd);
640 fd = -1;
642 continue;
644 if (showprogress)
645 start_progress_meter(curfile, stb.st_size, &statbytes);
646 /* Keep writing after an error so that we stay sync'd up. */
647 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
648 amt = bp->cnt;
649 if (i + amt > stb.st_size)
650 amt = stb.st_size - i;
651 if (!haderr) {
652 result = atomicio(read, fd, bp->buf, amt);
653 if (result != amt)
654 haderr = errno;
656 if (haderr)
657 (void) atomicio(vwrite, remout, bp->buf, amt);
658 else {
659 result = atomicio(vwrite, remout, bp->buf, amt);
660 if (result != amt)
661 haderr = errno;
662 statbytes += result;
664 if (limit_rate)
665 bwlimit(amt);
667 if (showprogress)
668 stop_progress_meter();
670 if (fd != -1) {
671 if (close(fd) < 0 && !haderr)
672 haderr = errno;
673 fd = -1;
675 if (!haderr)
676 (void) atomicio(vwrite, remout, "", 1);
677 else
678 run_err("%s: %s", name, strerror(haderr));
679 (void) response();
683 void
684 rsource(char *name, struct stat *statp)
686 DIR *dirp;
687 struct dirent *dp;
688 char *last, *vect[1], path[1100];
690 if (!(dirp = opendir(name))) {
691 run_err("%s: %s", name, strerror(errno));
692 return;
694 last = strrchr(name, '/');
695 if (last == 0)
696 last = name;
697 else
698 last++;
699 if (pflag) {
700 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
701 (u_long) statp->st_mtime,
702 (u_long) statp->st_atime);
703 (void) atomicio(vwrite, remout, path, strlen(path));
704 if (response() < 0) {
705 closedir(dirp);
706 return;
709 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
710 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
711 if (verbose_mode)
712 fprintf(stderr, "Entering directory: %s", path);
713 (void) atomicio(vwrite, remout, path, strlen(path));
714 if (response() < 0) {
715 closedir(dirp);
716 return;
718 while ((dp = readdir(dirp)) != NULL) {
719 if (dp->d_ino == 0)
720 continue;
721 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
722 continue;
723 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
724 run_err("%s/%s: name too long", name, dp->d_name);
725 continue;
727 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
728 vect[0] = path;
729 source(1, vect);
731 (void) closedir(dirp);
732 (void) atomicio(vwrite, remout, "E\n", 2);
733 (void) response();
736 void
737 bwlimit(int amount)
739 static struct timeval bwstart, bwend;
740 static int lamt, thresh = 16384;
741 u_int64_t waitlen;
742 struct timespec ts, rm;
744 if (!timerisset(&bwstart)) {
745 gettimeofday(&bwstart, NULL);
746 return;
749 lamt += amount;
750 if (lamt < thresh)
751 return;
753 gettimeofday(&bwend, NULL);
754 timersub(&bwend, &bwstart, &bwend);
755 if (!timerisset(&bwend))
756 return;
758 lamt *= 8;
759 waitlen = (double)1000000L * lamt / limit_rate;
761 bwstart.tv_sec = waitlen / 1000000L;
762 bwstart.tv_usec = waitlen % 1000000L;
764 if (timercmp(&bwstart, &bwend, >)) {
765 timersub(&bwstart, &bwend, &bwend);
767 /* Adjust the wait time */
768 if (bwend.tv_sec) {
769 thresh /= 2;
770 if (thresh < 2048)
771 thresh = 2048;
772 } else if (bwend.tv_usec < 100) {
773 thresh *= 2;
774 if (thresh > 32768)
775 thresh = 32768;
778 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
779 while (nanosleep(&ts, &rm) == -1) {
780 if (errno != EINTR)
781 break;
782 ts = rm;
786 lamt = 0;
787 gettimeofday(&bwstart, NULL);
790 void
791 sink(int argc, char **argv)
793 static BUF buffer;
794 struct stat stb;
795 enum {
796 YES, NO, DISPLAYED
797 } wrerr;
798 BUF *bp;
799 off_t i;
800 size_t j, count;
801 int amt, exists, first, ofd;
802 mode_t mode, omode, mask;
803 off_t size, statbytes;
804 int setimes, targisdir, wrerrno = 0;
805 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
806 struct timeval tv[2];
808 #define atime tv[0]
809 #define mtime tv[1]
810 #define SCREWUP(str) { why = str; goto screwup; }
812 setimes = targisdir = 0;
813 mask = umask(0);
814 if (!pflag)
815 (void) umask(mask);
816 if (argc != 1) {
817 run_err("ambiguous target");
818 exit(1);
820 targ = *argv;
821 if (targetshouldbedirectory)
822 verifydir(targ);
824 (void) atomicio(vwrite, remout, "", 1);
825 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
826 targisdir = 1;
827 for (first = 1;; first = 0) {
828 cp = buf;
829 if (atomicio(read, remin, cp, 1) != 1)
830 return;
831 if (*cp++ == '\n')
832 SCREWUP("unexpected <newline>");
833 do {
834 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
835 SCREWUP("lost connection");
836 *cp++ = ch;
837 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
838 *cp = 0;
839 if (verbose_mode)
840 fprintf(stderr, "Sink: %s", buf);
842 if (buf[0] == '\01' || buf[0] == '\02') {
843 if (iamremote == 0)
844 (void) atomicio(vwrite, STDERR_FILENO,
845 buf + 1, strlen(buf + 1));
846 if (buf[0] == '\02')
847 exit(1);
848 ++errs;
849 continue;
851 if (buf[0] == 'E') {
852 (void) atomicio(vwrite, remout, "", 1);
853 return;
855 if (ch == '\n')
856 *--cp = 0;
858 cp = buf;
859 if (*cp == 'T') {
860 setimes++;
861 cp++;
862 mtime.tv_sec = strtol(cp, &cp, 10);
863 if (!cp || *cp++ != ' ')
864 SCREWUP("mtime.sec not delimited");
865 mtime.tv_usec = strtol(cp, &cp, 10);
866 if (!cp || *cp++ != ' ')
867 SCREWUP("mtime.usec not delimited");
868 atime.tv_sec = strtol(cp, &cp, 10);
869 if (!cp || *cp++ != ' ')
870 SCREWUP("atime.sec not delimited");
871 atime.tv_usec = strtol(cp, &cp, 10);
872 if (!cp || *cp++ != '\0')
873 SCREWUP("atime.usec not delimited");
874 (void) atomicio(vwrite, remout, "", 1);
875 continue;
877 if (*cp != 'C' && *cp != 'D') {
879 * Check for the case "rcp remote:foo\* local:bar".
880 * In this case, the line "No match." can be returned
881 * by the shell before the rcp command on the remote is
882 * executed so the ^Aerror_message convention isn't
883 * followed.
885 if (first) {
886 run_err("%s", cp);
887 exit(1);
889 SCREWUP("expected control record");
891 mode = 0;
892 for (++cp; cp < buf + 5; cp++) {
893 if (*cp < '0' || *cp > '7')
894 SCREWUP("bad mode");
895 mode = (mode << 3) | (*cp - '0');
897 if (*cp++ != ' ')
898 SCREWUP("mode not delimited");
900 for (size = 0; isdigit(*cp);)
901 size = size * 10 + (*cp++ - '0');
902 if (*cp++ != ' ')
903 SCREWUP("size not delimited");
904 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
905 run_err("error: unexpected filename: %s", cp);
906 exit(1);
908 if (targisdir) {
909 static char *namebuf;
910 static size_t cursize;
911 size_t need;
913 need = strlen(targ) + strlen(cp) + 250;
914 if (need > cursize) {
915 if (namebuf)
916 xfree(namebuf);
917 namebuf = xmalloc(need);
918 cursize = need;
920 (void) snprintf(namebuf, need, "%s%s%s", targ,
921 strcmp(targ, "/") ? "/" : "", cp);
922 np = namebuf;
923 } else
924 np = targ;
925 curfile = cp;
926 exists = stat(np, &stb) == 0;
927 if (buf[0] == 'D') {
928 int mod_flag = pflag;
929 if (!iamrecursive)
930 SCREWUP("received directory without -r");
931 if (exists) {
932 if (!S_ISDIR(stb.st_mode)) {
933 errno = ENOTDIR;
934 goto bad;
936 if (pflag)
937 (void) chmod(np, mode);
938 } else {
939 /* Handle copying from a read-only
940 directory */
941 mod_flag = 1;
942 if (mkdir(np, mode | S_IRWXU) < 0)
943 goto bad;
945 vect[0] = xstrdup(np);
946 sink(1, vect);
947 if (setimes) {
948 setimes = 0;
949 if (utimes(vect[0], tv) < 0)
950 run_err("%s: set times: %s",
951 vect[0], strerror(errno));
953 if (mod_flag)
954 (void) chmod(vect[0], mode);
955 if (vect[0])
956 xfree(vect[0]);
957 continue;
959 omode = mode;
960 mode |= S_IWRITE;
961 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
962 bad: run_err("%s: %s", np, strerror(errno));
963 continue;
965 (void) atomicio(vwrite, remout, "", 1);
966 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
967 (void) close(ofd);
968 continue;
970 cp = bp->buf;
971 wrerr = NO;
973 statbytes = 0;
974 if (showprogress)
975 start_progress_meter(curfile, size, &statbytes);
976 for (count = i = 0; i < size; i += 4096) {
977 amt = 4096;
978 if (i + amt > size)
979 amt = size - i;
980 count += amt;
981 do {
982 j = atomicio(read, remin, cp, amt);
983 if (j == 0) {
984 run_err("%s", j ? strerror(errno) :
985 "dropped connection");
986 exit(1);
988 amt -= j;
989 cp += j;
990 statbytes += j;
991 } while (amt > 0);
993 if (limit_rate)
994 bwlimit(4096);
996 if (count == bp->cnt) {
997 /* Keep reading so we stay sync'd up. */
998 if (wrerr == NO) {
999 if (atomicio(vwrite, ofd, bp->buf,
1000 count) != count) {
1001 wrerr = YES;
1002 wrerrno = errno;
1005 count = 0;
1006 cp = bp->buf;
1009 if (showprogress)
1010 stop_progress_meter();
1011 if (count != 0 && wrerr == NO &&
1012 atomicio(vwrite, ofd, bp->buf, count) != count) {
1013 wrerr = YES;
1014 wrerrno = errno;
1016 if (wrerr == NO && ftruncate(ofd, size) != 0) {
1017 run_err("%s: truncate: %s", np, strerror(errno));
1018 wrerr = DISPLAYED;
1020 if (pflag) {
1021 if (exists || omode != mode)
1022 #ifdef HAVE_FCHMOD
1023 if (fchmod(ofd, omode)) {
1024 #else /* HAVE_FCHMOD */
1025 if (chmod(np, omode)) {
1026 #endif /* HAVE_FCHMOD */
1027 run_err("%s: set mode: %s",
1028 np, strerror(errno));
1029 wrerr = DISPLAYED;
1031 } else {
1032 if (!exists && omode != mode)
1033 #ifdef HAVE_FCHMOD
1034 if (fchmod(ofd, omode & ~mask)) {
1035 #else /* HAVE_FCHMOD */
1036 if (chmod(np, omode & ~mask)) {
1037 #endif /* HAVE_FCHMOD */
1038 run_err("%s: set mode: %s",
1039 np, strerror(errno));
1040 wrerr = DISPLAYED;
1043 if (close(ofd) == -1) {
1044 wrerr = YES;
1045 wrerrno = errno;
1047 (void) response();
1048 if (setimes && wrerr == NO) {
1049 setimes = 0;
1050 if (utimes(np, tv) < 0) {
1051 run_err("%s: set times: %s",
1052 np, strerror(errno));
1053 wrerr = DISPLAYED;
1056 switch (wrerr) {
1057 case YES:
1058 run_err("%s: %s", np, strerror(wrerrno));
1059 break;
1060 case NO:
1061 (void) atomicio(vwrite, remout, "", 1);
1062 break;
1063 case DISPLAYED:
1064 break;
1067 screwup:
1068 run_err("protocol error: %s", why);
1069 exit(1);
1073 response(void)
1075 char ch, *cp, resp, rbuf[2048];
1077 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1078 lostconn(0);
1080 cp = rbuf;
1081 switch (resp) {
1082 case 0: /* ok */
1083 return (0);
1084 default:
1085 *cp++ = resp;
1086 /* FALLTHROUGH */
1087 case 1: /* error, followed by error msg */
1088 case 2: /* fatal error, "" */
1089 do {
1090 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1091 lostconn(0);
1092 *cp++ = ch;
1093 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1095 if (!iamremote)
1096 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1097 ++errs;
1098 if (resp == 1)
1099 return (-1);
1100 exit(1);
1102 /* NOTREACHED */
1105 void
1106 usage(void)
1108 (void) fprintf(stderr,
1109 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1110 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1111 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1112 exit(1);
1115 void
1116 run_err(const char *fmt,...)
1118 static FILE *fp;
1119 va_list ap;
1121 ++errs;
1122 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1123 (void) fprintf(fp, "%c", 0x01);
1124 (void) fprintf(fp, "scp: ");
1125 va_start(ap, fmt);
1126 (void) vfprintf(fp, fmt, ap);
1127 va_end(ap);
1128 (void) fprintf(fp, "\n");
1129 (void) fflush(fp);
1132 if (!iamremote) {
1133 va_start(ap, fmt);
1134 vfprintf(stderr, fmt, ap);
1135 va_end(ap);
1136 fprintf(stderr, "\n");
1140 void
1141 verifydir(char *cp)
1143 struct stat stb;
1145 if (!stat(cp, &stb)) {
1146 if (S_ISDIR(stb.st_mode))
1147 return;
1148 errno = ENOTDIR;
1150 run_err("%s: %s", cp, strerror(errno));
1151 killchild(0);
1155 okname(char *cp0)
1157 int c;
1158 char *cp;
1160 cp = cp0;
1161 do {
1162 c = (int)*cp;
1163 if (c & 0200)
1164 goto bad;
1165 if (!isalpha(c) && !isdigit(c)) {
1166 switch (c) {
1167 case '\'':
1168 case '"':
1169 case '`':
1170 case ' ':
1171 case '#':
1172 goto bad;
1173 default:
1174 break;
1177 } while (*++cp);
1178 return (1);
1180 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1181 return (0);
1184 BUF *
1185 allocbuf(BUF *bp, int fd, int blksize)
1187 size_t size;
1188 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1189 struct stat stb;
1191 if (fstat(fd, &stb) < 0) {
1192 run_err("fstat: %s", strerror(errno));
1193 return (0);
1195 size = roundup(stb.st_blksize, blksize);
1196 if (size == 0)
1197 size = blksize;
1198 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1199 size = blksize;
1200 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1201 if (bp->cnt >= size)
1202 return (bp);
1203 if (bp->buf == NULL)
1204 bp->buf = xmalloc(size);
1205 else
1206 bp->buf = xrealloc(bp->buf, 1, size);
1207 memset(bp->buf, 0, size);
1208 bp->cnt = size;
1209 return (bp);
1212 void
1213 lostconn(int signo)
1215 if (!iamremote)
1216 write(STDERR_FILENO, "lost connection\n", 16);
1217 if (signo)
1218 _exit(1);
1219 else
1220 exit(1);