Tomato 1.28
[tomato.git] / release / src / router / dropbear / scp.c
blobda64dd16939c8083a07f63be99ef6a61692a374a
1 /*
2 * scp - secure remote copy. This is basically patched BSD rcp which
3 * uses ssh to do the data transfer (instead of using rcmd).
5 * NOTE: This version should NOT be suid root. (This uses ssh to
6 * do the transfer and ssh has the necessary privileges.)
8 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
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".
17 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
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.
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.
42 * Parts from:
44 * Copyright (c) 1983, 1990, 1992, 1993, 1995
45 * The Regents of the University of California. All rights reserved.
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. Neither the name of the University nor the names of its contributors
56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
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.
73 #include "includes.h"
74 /*RCSID("$OpenBSD: scp.c,v 1.130 2006/01/31 10:35:43 djm Exp $");*/
76 #include "atomicio.h"
77 #include "compat.h"
78 #include "scpmisc.h"
79 #include "progressmeter.h"
81 void bwlimit(int);
83 /* Struct for addargs */
84 arglist args;
86 /* Bandwidth limit */
87 off_t limit_rate = 0;
89 /* Name of current file being transferred. */
90 char *curfile;
92 /* This is set to non-zero to enable verbose mode. */
93 int verbose_mode = 0;
95 /* This is set to zero if the progressmeter is not desired. */
96 int showprogress = 1;
98 /* This is the program to execute for the secured connection. ("ssh" or -S) */
99 char *ssh_program = _PATH_SSH_PROGRAM;
101 /* This is used to store the pid of ssh_program */
102 pid_t do_cmd_pid = -1;
104 static void
105 killchild(int signo)
107 if (do_cmd_pid > 1) {
108 kill(do_cmd_pid, signo ? signo : SIGTERM);
109 waitpid(do_cmd_pid, NULL, 0);
112 if (signo)
113 _exit(1);
114 exit(1);
117 static int
118 do_local_cmd(arglist *a)
120 u_int i;
121 int status;
122 pid_t pid;
124 if (a->num == 0)
125 fatal("do_local_cmd: no arguments");
127 if (verbose_mode) {
128 fprintf(stderr, "Executing:");
129 for (i = 0; i < a->num; i++)
130 fprintf(stderr, " %s", a->list[i]);
131 fprintf(stderr, "\n");
133 #ifdef __uClinux__
134 pid = vfork();
135 #else
136 pid = fork();
137 #endif /* __uClinux__ */
138 if (pid == -1)
139 fatal("do_local_cmd: fork: %s", strerror(errno));
141 if (pid == 0) {
142 execvp(a->list[0], a->list);
143 perror(a->list[0]);
144 #ifdef __uClinux__
145 _exit(1);
146 #else
147 exit(1);
148 #endif /* __uClinux__ */
151 do_cmd_pid = pid;
152 signal(SIGTERM, killchild);
153 signal(SIGINT, killchild);
154 signal(SIGHUP, killchild);
156 while (waitpid(pid, &status, 0) == -1)
157 if (errno != EINTR)
158 fatal("do_local_cmd: waitpid: %s", strerror(errno));
160 do_cmd_pid = -1;
162 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
163 return (-1);
165 return (0);
169 * This function executes the given command as the specified user on the
170 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
171 * assigns the input and output file descriptors on success.
175 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
177 int pin[2], pout[2], reserved[2];
179 if (verbose_mode)
180 fprintf(stderr,
181 "Executing: program %s host %s, user %s, command %s\n",
182 ssh_program, host,
183 remuser ? remuser : "(unspecified)", cmd);
186 * Reserve two descriptors so that the real pipes won't get
187 * descriptors 0 and 1 because that will screw up dup2 below.
189 pipe(reserved);
191 /* Create a socket pair for communicating with ssh. */
192 if (pipe(pin) < 0)
193 fatal("pipe: %s", strerror(errno));
194 if (pipe(pout) < 0)
195 fatal("pipe: %s", strerror(errno));
197 /* Free the reserved descriptors. */
198 close(reserved[0]);
199 close(reserved[1]);
201 /* uClinux needs to build the args here before vforking,
202 otherwise we do it later on. */
203 #ifdef __uClinux__
204 replacearg(&args, 0, "%s", ssh_program);
205 if (remuser != NULL)
206 addargs(&args, "-l%s", remuser);
207 addargs(&args, "%s", host);
208 addargs(&args, "%s", cmd);
209 #endif /* __uClinux__ */
211 /* Fork a child to execute the command on the remote host using ssh. */
212 #ifdef __uClinux__
213 do_cmd_pid = vfork();
214 #else
215 do_cmd_pid = fork();
216 #endif /* __uClinux__ */
218 if (do_cmd_pid == 0) {
219 /* Child. */
220 close(pin[1]);
221 close(pout[0]);
222 dup2(pin[0], 0);
223 dup2(pout[1], 1);
224 close(pin[0]);
225 close(pout[1]);
227 #ifndef __uClinux__
228 replacearg(&args, 0, "%s", ssh_program);
229 if (remuser != NULL)
230 addargs(&args, "-l%s", remuser);
231 addargs(&args, "%s", host);
232 addargs(&args, "%s", cmd);
233 #endif /* __uClinux__ */
235 execvp(ssh_program, args.list);
236 perror(ssh_program);
237 #ifndef __uClinux__
238 exit(1);
239 #else
240 _exit(1);
241 #endif /* __uClinux__ */
242 } else if (do_cmd_pid == -1) {
243 fatal("fork: %s", strerror(errno));
247 #ifdef __uClinux__
248 /* clean up command */
249 /* pop cmd */
250 xfree(args.list[args.num-1]);
251 args.list[args.num-1]=NULL;
252 args.num--;
253 /* pop host */
254 xfree(args.list[args.num-1]);
255 args.list[args.num-1]=NULL;
256 args.num--;
257 /* pop user */
258 if (remuser != NULL) {
259 xfree(args.list[args.num-1]);
260 args.list[args.num-1]=NULL;
261 args.num--;
263 #endif /* __uClinux__ */
265 /* Parent. Close the other side, and return the local side. */
266 close(pin[0]);
267 *fdout = pin[1];
268 close(pout[1]);
269 *fdin = pout[0];
270 signal(SIGTERM, killchild);
271 signal(SIGINT, killchild);
272 signal(SIGHUP, killchild);
273 return 0;
276 typedef struct {
277 size_t cnt;
278 char *buf;
279 } BUF;
281 BUF *allocbuf(BUF *, int, int);
282 void lostconn(int);
283 void nospace(void);
284 int okname(char *);
285 void run_err(const char *,...);
286 void verifydir(char *);
288 struct passwd *pwd;
289 uid_t userid;
290 int errs, remin, remout;
291 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
293 #define CMDNEEDS 64
294 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
296 int response(void);
297 void rsource(char *, struct stat *);
298 void sink(int, char *[]);
299 void source(int, char *[]);
300 void tolocal(int, char *[]);
301 void toremote(char *, int, char *[]);
302 void usage(void);
304 #if defined(DBMULTI_scp) || !defined(DROPBEAR_MULTI)
305 #if defined(DBMULTI_scp) && defined(DROPBEAR_MULTI)
306 int scp_main(int argc, char **argv)
307 #else
309 main(int argc, char **argv)
310 #endif
312 int ch, fflag, tflag, status;
313 double speed;
314 char *targ, *endp;
315 extern char *optarg;
316 extern int optind;
318 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
319 sanitise_stdfd();
321 memset(&args, '\0', sizeof(args));
322 args.list = NULL;
323 addargs(&args, "%s", ssh_program);
325 fflag = tflag = 0;
326 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
327 switch (ch) {
328 /* User-visible flags. */
329 case '1':
330 case '2':
331 case '4':
332 case '6':
333 case 'C':
334 addargs(&args, "-%c", ch);
335 break;
336 case 'o':
337 case 'c':
338 case 'i':
339 case 'F':
340 addargs(&args, "-%c%s", ch, optarg);
341 break;
342 case 'P':
343 addargs(&args, "-p%s", optarg);
344 break;
345 case 'B':
346 addargs(&args, "-oBatchmode yes");
347 break;
348 case 'l':
349 speed = strtod(optarg, &endp);
350 if (speed <= 0 || *endp != '\0')
351 usage();
352 limit_rate = speed * 1024;
353 break;
354 case 'p':
355 pflag = 1;
356 break;
357 case 'r':
358 iamrecursive = 1;
359 break;
360 case 'S':
361 ssh_program = xstrdup(optarg);
362 break;
363 case 'v':
364 addargs(&args, "-v");
365 verbose_mode = 1;
366 break;
367 #ifdef PROGRESS_METER
368 case 'q':
369 addargs(&args, "-q");
370 showprogress = 0;
371 break;
372 #endif
374 /* Server options. */
375 case 'd':
376 targetshouldbedirectory = 1;
377 break;
378 case 'f': /* "from" */
379 iamremote = 1;
380 fflag = 1;
381 break;
382 case 't': /* "to" */
383 iamremote = 1;
384 tflag = 1;
385 #ifdef HAVE_CYGWIN
386 setmode(0, O_BINARY);
387 #endif
388 break;
389 default:
390 usage();
392 argc -= optind;
393 argv += optind;
395 if ((pwd = getpwuid(userid = getuid())) == NULL)
396 fatal("unknown user %u", (u_int) userid);
398 if (!isatty(STDERR_FILENO))
399 showprogress = 0;
401 remin = STDIN_FILENO;
402 remout = STDOUT_FILENO;
404 if (fflag) {
405 /* Follow "protocol", send data. */
406 (void) response();
407 source(argc, argv);
408 exit(errs != 0);
410 if (tflag) {
411 /* Receive data. */
412 sink(argc, argv);
413 exit(errs != 0);
415 if (argc < 2)
416 usage();
417 if (argc > 2)
418 targetshouldbedirectory = 1;
420 remin = remout = -1;
421 do_cmd_pid = -1;
422 /* Command to be executed on remote system using "ssh". */
423 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
424 verbose_mode ? " -v" : "",
425 iamrecursive ? " -r" : "", pflag ? " -p" : "",
426 targetshouldbedirectory ? " -d" : "");
428 (void) signal(SIGPIPE, lostconn);
430 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
431 toremote(targ, argc, argv);
432 else {
433 if (targetshouldbedirectory)
434 verifydir(argv[argc - 1]);
435 tolocal(argc, argv); /* Dest is local host. */
438 * Finally check the exit status of the ssh process, if one was forked
439 * and no error has occured yet
441 if (do_cmd_pid != -1 && errs == 0) {
442 if (remin != -1)
443 (void) close(remin);
444 if (remout != -1)
445 (void) close(remout);
446 if (waitpid(do_cmd_pid, &status, 0) == -1)
447 errs = 1;
448 else {
449 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
450 errs = 1;
453 exit(errs != 0);
455 #endif /* DBMULTI_scp stuff */
457 void
458 toremote(char *targ, int argc, char **argv)
460 int i, len;
461 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
462 arglist alist;
464 memset(&alist, '\0', sizeof(alist));
465 alist.list = NULL;
467 *targ++ = 0;
468 if (*targ == 0)
469 targ = ".";
471 arg = xstrdup(argv[argc - 1]);
472 if ((thost = strrchr(arg, '@'))) {
473 /* user@host */
474 *thost++ = 0;
475 tuser = arg;
476 if (*tuser == '\0')
477 tuser = NULL;
478 } else {
479 thost = arg;
480 tuser = NULL;
483 if (tuser != NULL && !okname(tuser)) {
484 xfree(arg);
485 return;
488 for (i = 0; i < argc - 1; i++) {
489 src = colon(argv[i]);
490 if (src) { /* remote to remote */
491 freeargs(&alist);
492 addargs(&alist, "%s", ssh_program);
493 if (verbose_mode)
494 addargs(&alist, "-v");
495 addargs(&alist, "-x");
496 addargs(&alist, "-oClearAllForwardings yes");
497 addargs(&alist, "-n");
499 *src++ = 0;
500 if (*src == 0)
501 src = ".";
502 host = strrchr(argv[i], '@');
504 if (host) {
505 *host++ = 0;
506 host = cleanhostname(host);
507 suser = argv[i];
508 if (*suser == '\0')
509 suser = pwd->pw_name;
510 else if (!okname(suser))
511 continue;
512 addargs(&alist, "-l");
513 addargs(&alist, "%s", suser);
514 } else {
515 host = cleanhostname(argv[i]);
517 addargs(&alist, "%s", host);
518 addargs(&alist, "%s", cmd);
519 addargs(&alist, "%s", src);
520 addargs(&alist, "%s%s%s:%s",
521 tuser ? tuser : "", tuser ? "@" : "",
522 thost, targ);
523 if (do_local_cmd(&alist) != 0)
524 errs = 1;
525 } else { /* local to remote */
526 if (remin == -1) {
527 len = strlen(targ) + CMDNEEDS + 20;
528 bp = xmalloc(len);
529 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
530 host = cleanhostname(thost);
531 if (do_cmd(host, tuser, bp, &remin,
532 &remout, argc) < 0)
533 exit(1);
534 if (response() < 0)
535 exit(1);
536 (void) xfree(bp);
538 source(1, argv + i);
543 void
544 tolocal(int argc, char **argv)
546 int i, len;
547 char *bp, *host, *src, *suser;
548 arglist alist;
550 memset(&alist, '\0', sizeof(alist));
551 alist.list = NULL;
553 for (i = 0; i < argc - 1; i++) {
554 if (!(src = colon(argv[i]))) { /* Local to local. */
555 freeargs(&alist);
556 addargs(&alist, "%s", _PATH_CP);
557 if (iamrecursive)
558 addargs(&alist, "-r");
559 if (pflag)
560 addargs(&alist, "-p");
561 addargs(&alist, "%s", argv[i]);
562 addargs(&alist, "%s", argv[argc-1]);
563 if (do_local_cmd(&alist))
564 ++errs;
565 continue;
567 *src++ = 0;
568 if (*src == 0)
569 src = ".";
570 if ((host = strrchr(argv[i], '@')) == NULL) {
571 host = argv[i];
572 suser = NULL;
573 } else {
574 *host++ = 0;
575 suser = argv[i];
576 if (*suser == '\0')
577 suser = pwd->pw_name;
579 host = cleanhostname(host);
580 len = strlen(src) + CMDNEEDS + 20;
581 bp = xmalloc(len);
582 (void) snprintf(bp, len, "%s -f %s", cmd, src);
583 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
584 (void) xfree(bp);
585 ++errs;
586 continue;
588 xfree(bp);
589 sink(1, argv + argc - 1);
590 (void) close(remin);
591 remin = remout = -1;
595 void
596 source(int argc, char **argv)
598 struct stat stb;
599 static BUF buffer;
600 BUF *bp;
601 off_t i, amt, statbytes;
602 size_t result;
603 int fd = -1, haderr, indx;
604 char *last, *name, buf[2048];
605 int len;
607 for (indx = 0; indx < argc; ++indx) {
608 name = argv[indx];
609 statbytes = 0;
610 len = strlen(name);
611 while (len > 1 && name[len-1] == '/')
612 name[--len] = '\0';
613 if (strchr(name, '\n') != NULL) {
614 run_err("%s: skipping, filename contains a newline",
615 name);
616 goto next;
618 if ((fd = open(name, O_RDONLY, 0)) < 0)
619 goto syserr;
620 if (fstat(fd, &stb) < 0) {
621 syserr: run_err("%s: %s", name, strerror(errno));
622 goto next;
624 switch (stb.st_mode & S_IFMT) {
625 case S_IFREG:
626 break;
627 case S_IFDIR:
628 if (iamrecursive) {
629 rsource(name, &stb);
630 goto next;
632 /* FALLTHROUGH */
633 default:
634 run_err("%s: not a regular file", name);
635 goto next;
637 if ((last = strrchr(name, '/')) == NULL)
638 last = name;
639 else
640 ++last;
641 curfile = last;
642 if (pflag) {
644 * Make it compatible with possible future
645 * versions expecting microseconds.
647 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
648 (u_long) stb.st_mtime,
649 (u_long) stb.st_atime);
650 (void) atomicio(vwrite, remout, buf, strlen(buf));
651 if (response() < 0)
652 goto next;
654 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
655 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
656 (u_int) (stb.st_mode & FILEMODEMASK),
657 (long long)stb.st_size, last);
658 if (verbose_mode) {
659 fprintf(stderr, "Sending file modes: %s", buf);
661 (void) atomicio(vwrite, remout, buf, strlen(buf));
662 if (response() < 0)
663 goto next;
664 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
665 next: if (fd != -1) {
666 (void) close(fd);
667 fd = -1;
669 continue;
671 #if PROGRESS_METER
672 if (showprogress)
673 start_progress_meter(curfile, stb.st_size, &statbytes);
674 #endif
675 /* Keep writing after an error so that we stay sync'd up. */
676 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
677 amt = bp->cnt;
678 if (i + amt > stb.st_size)
679 amt = stb.st_size - i;
680 if (!haderr) {
681 result = atomicio(read, fd, bp->buf, amt);
682 if (result != amt)
683 haderr = errno;
685 if (haderr)
686 (void) atomicio(vwrite, remout, bp->buf, amt);
687 else {
688 result = atomicio(vwrite, remout, bp->buf, amt);
689 if (result != amt)
690 haderr = errno;
691 statbytes += result;
693 if (limit_rate)
694 bwlimit(amt);
696 #ifdef PROGRESS_METER
697 if (showprogress)
698 stop_progress_meter();
699 #endif
701 if (fd != -1) {
702 if (close(fd) < 0 && !haderr)
703 haderr = errno;
704 fd = -1;
706 if (!haderr)
707 (void) atomicio(vwrite, remout, "", 1);
708 else
709 run_err("%s: %s", name, strerror(haderr));
710 (void) response();
714 void
715 rsource(char *name, struct stat *statp)
717 DIR *dirp;
718 struct dirent *dp;
719 char *last, *vect[1], path[1100];
721 if (!(dirp = opendir(name))) {
722 run_err("%s: %s", name, strerror(errno));
723 return;
725 last = strrchr(name, '/');
726 if (last == 0)
727 last = name;
728 else
729 last++;
730 if (pflag) {
731 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
732 (u_long) statp->st_mtime,
733 (u_long) statp->st_atime);
734 (void) atomicio(vwrite, remout, path, strlen(path));
735 if (response() < 0) {
736 closedir(dirp);
737 return;
740 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
741 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
742 if (verbose_mode)
743 fprintf(stderr, "Entering directory: %s", path);
744 (void) atomicio(vwrite, remout, path, strlen(path));
745 if (response() < 0) {
746 closedir(dirp);
747 return;
749 while ((dp = readdir(dirp)) != NULL) {
750 if (dp->d_ino == 0)
751 continue;
752 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
753 continue;
754 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
755 run_err("%s/%s: name too long", name, dp->d_name);
756 continue;
758 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
759 vect[0] = path;
760 source(1, vect);
762 (void) closedir(dirp);
763 (void) atomicio(vwrite, remout, "E\n", 2);
764 (void) response();
767 void
768 bwlimit(int amount)
770 static struct timeval bwstart, bwend;
771 static int lamt, thresh = 16384;
772 u_int64_t waitlen;
773 struct timespec ts, rm;
775 if (!timerisset(&bwstart)) {
776 gettimeofday(&bwstart, NULL);
777 return;
780 lamt += amount;
781 if (lamt < thresh)
782 return;
784 gettimeofday(&bwend, NULL);
785 timersub(&bwend, &bwstart, &bwend);
786 if (!timerisset(&bwend))
787 return;
789 lamt *= 8;
790 waitlen = (double)1000000L * lamt / limit_rate;
792 bwstart.tv_sec = waitlen / 1000000L;
793 bwstart.tv_usec = waitlen % 1000000L;
795 if (timercmp(&bwstart, &bwend, >)) {
796 timersub(&bwstart, &bwend, &bwend);
798 /* Adjust the wait time */
799 if (bwend.tv_sec) {
800 thresh /= 2;
801 if (thresh < 2048)
802 thresh = 2048;
803 } else if (bwend.tv_usec < 100) {
804 thresh *= 2;
805 if (thresh > 32768)
806 thresh = 32768;
809 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
810 while (nanosleep(&ts, &rm) == -1) {
811 if (errno != EINTR)
812 break;
813 ts = rm;
817 lamt = 0;
818 gettimeofday(&bwstart, NULL);
821 void
822 sink(int argc, char **argv)
824 static BUF buffer;
825 struct stat stb;
826 enum {
827 YES, NO, DISPLAYED
828 } wrerr;
829 BUF *bp;
830 off_t i;
831 size_t j, count;
832 int amt, exists, first, mask, mode, ofd, omode;
833 off_t size, statbytes;
834 int setimes, targisdir, wrerrno = 0;
835 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
836 struct timeval tv[2];
838 #define atime tv[0]
839 #define mtime tv[1]
840 #define SCREWUP(str) { why = str; goto screwup; }
842 setimes = targisdir = 0;
843 mask = umask(0);
844 if (!pflag)
845 (void) umask(mask);
846 if (argc != 1) {
847 run_err("ambiguous target");
848 exit(1);
850 targ = *argv;
851 if (targetshouldbedirectory)
852 verifydir(targ);
854 (void) atomicio(vwrite, remout, "", 1);
855 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
856 targisdir = 1;
857 for (first = 1;; first = 0) {
858 cp = buf;
859 if (atomicio(read, remin, cp, 1) != 1)
860 return;
861 if (*cp++ == '\n')
862 SCREWUP("unexpected <newline>");
863 do {
864 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
865 SCREWUP("lost connection");
866 *cp++ = ch;
867 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
868 *cp = 0;
869 if (verbose_mode)
870 fprintf(stderr, "Sink: %s", buf);
872 if (buf[0] == '\01' || buf[0] == '\02') {
873 if (iamremote == 0)
874 (void) atomicio(vwrite, STDERR_FILENO,
875 buf + 1, strlen(buf + 1));
876 if (buf[0] == '\02')
877 exit(1);
878 ++errs;
879 continue;
881 if (buf[0] == 'E') {
882 (void) atomicio(vwrite, remout, "", 1);
883 return;
885 if (ch == '\n')
886 *--cp = 0;
888 cp = buf;
889 if (*cp == 'T') {
890 setimes++;
891 cp++;
892 mtime.tv_sec = strtol(cp, &cp, 10);
893 if (!cp || *cp++ != ' ')
894 SCREWUP("mtime.sec not delimited");
895 mtime.tv_usec = strtol(cp, &cp, 10);
896 if (!cp || *cp++ != ' ')
897 SCREWUP("mtime.usec not delimited");
898 atime.tv_sec = strtol(cp, &cp, 10);
899 if (!cp || *cp++ != ' ')
900 SCREWUP("atime.sec not delimited");
901 atime.tv_usec = strtol(cp, &cp, 10);
902 if (!cp || *cp++ != '\0')
903 SCREWUP("atime.usec not delimited");
904 (void) atomicio(vwrite, remout, "", 1);
905 continue;
907 if (*cp != 'C' && *cp != 'D') {
909 * Check for the case "rcp remote:foo\* local:bar".
910 * In this case, the line "No match." can be returned
911 * by the shell before the rcp command on the remote is
912 * executed so the ^Aerror_message convention isn't
913 * followed.
915 if (first) {
916 run_err("%s", cp);
917 exit(1);
919 SCREWUP("expected control record");
921 mode = 0;
922 for (++cp; cp < buf + 5; cp++) {
923 if (*cp < '0' || *cp > '7')
924 SCREWUP("bad mode");
925 mode = (mode << 3) | (*cp - '0');
927 if (*cp++ != ' ')
928 SCREWUP("mode not delimited");
930 for (size = 0; isdigit(*cp);)
931 size = size * 10 + (*cp++ - '0');
932 if (*cp++ != ' ')
933 SCREWUP("size not delimited");
934 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
935 run_err("error: unexpected filename: %s", cp);
936 exit(1);
938 if (targisdir) {
939 static char *namebuf;
940 static size_t cursize;
941 size_t need;
943 need = strlen(targ) + strlen(cp) + 250;
944 if (need > cursize) {
945 if (namebuf)
946 xfree(namebuf);
947 namebuf = xmalloc(need);
948 cursize = need;
950 (void) snprintf(namebuf, need, "%s%s%s", targ,
951 strcmp(targ, "/") ? "/" : "", cp);
952 np = namebuf;
953 } else
954 np = targ;
955 curfile = cp;
956 exists = stat(np, &stb) == 0;
957 if (buf[0] == 'D') {
958 int mod_flag = pflag;
959 if (!iamrecursive)
960 SCREWUP("received directory without -r");
961 if (exists) {
962 if (!S_ISDIR(stb.st_mode)) {
963 errno = ENOTDIR;
964 goto bad;
966 if (pflag)
967 (void) chmod(np, mode);
968 } else {
969 /* Handle copying from a read-only
970 directory */
971 mod_flag = 1;
972 if (mkdir(np, mode | S_IRWXU) < 0)
973 goto bad;
975 vect[0] = xstrdup(np);
976 sink(1, vect);
977 if (setimes) {
978 setimes = 0;
979 if (utimes(vect[0], tv) < 0)
980 run_err("%s: set times: %s",
981 vect[0], strerror(errno));
983 if (mod_flag)
984 (void) chmod(vect[0], mode);
985 if (vect[0])
986 xfree(vect[0]);
987 continue;
989 omode = mode;
990 mode |= S_IWRITE;
991 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
992 bad: run_err("%s: %s", np, strerror(errno));
993 continue;
995 (void) atomicio(vwrite, remout, "", 1);
996 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
997 (void) close(ofd);
998 continue;
1000 cp = bp->buf;
1001 wrerr = NO;
1003 statbytes = 0;
1004 #ifdef PROGRESS_METER
1005 if (showprogress)
1006 start_progress_meter(curfile, size, &statbytes);
1007 #endif
1008 for (count = i = 0; i < size; i += 4096) {
1009 amt = 4096;
1010 if (i + amt > size)
1011 amt = size - i;
1012 count += amt;
1013 do {
1014 j = atomicio(read, remin, cp, amt);
1015 if (j == 0) {
1016 run_err("%s", j ? strerror(errno) :
1017 "dropped connection");
1018 exit(1);
1020 amt -= j;
1021 cp += j;
1022 statbytes += j;
1023 } while (amt > 0);
1025 if (limit_rate)
1026 bwlimit(4096);
1028 if (count == bp->cnt) {
1029 /* Keep reading so we stay sync'd up. */
1030 if (wrerr == NO) {
1031 if (atomicio(vwrite, ofd, bp->buf,
1032 count) != count) {
1033 wrerr = YES;
1034 wrerrno = errno;
1037 count = 0;
1038 cp = bp->buf;
1041 #ifdef PROGRESS_METER
1042 if (showprogress)
1043 stop_progress_meter();
1044 #endif
1045 if (count != 0 && wrerr == NO &&
1046 atomicio(vwrite, ofd, bp->buf, count) != count) {
1047 wrerr = YES;
1048 wrerrno = errno;
1050 if (wrerr == NO && ftruncate(ofd, size) != 0) {
1051 run_err("%s: truncate: %s", np, strerror(errno));
1052 wrerr = DISPLAYED;
1054 if (pflag) {
1055 if (exists || omode != mode)
1056 #ifdef HAVE_FCHMOD
1057 if (fchmod(ofd, omode)) {
1058 #else /* HAVE_FCHMOD */
1059 if (chmod(np, omode)) {
1060 #endif /* HAVE_FCHMOD */
1061 run_err("%s: set mode: %s",
1062 np, strerror(errno));
1063 wrerr = DISPLAYED;
1065 } else {
1066 if (!exists && omode != mode)
1067 #ifdef HAVE_FCHMOD
1068 if (fchmod(ofd, omode & ~mask)) {
1069 #else /* HAVE_FCHMOD */
1070 if (chmod(np, omode & ~mask)) {
1071 #endif /* HAVE_FCHMOD */
1072 run_err("%s: set mode: %s",
1073 np, strerror(errno));
1074 wrerr = DISPLAYED;
1077 if (close(ofd) == -1) {
1078 wrerr = YES;
1079 wrerrno = errno;
1081 (void) response();
1082 if (setimes && wrerr == NO) {
1083 setimes = 0;
1084 if (utimes(np, tv) < 0) {
1085 run_err("%s: set times: %s",
1086 np, strerror(errno));
1087 wrerr = DISPLAYED;
1090 switch (wrerr) {
1091 case YES:
1092 run_err("%s: %s", np, strerror(wrerrno));
1093 break;
1094 case NO:
1095 (void) atomicio(vwrite, remout, "", 1);
1096 break;
1097 case DISPLAYED:
1098 break;
1101 screwup:
1102 run_err("protocol error: %s", why);
1103 exit(1);
1107 response(void)
1109 char ch, *cp, resp, rbuf[2048];
1111 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1112 lostconn(0);
1114 cp = rbuf;
1115 switch (resp) {
1116 case 0: /* ok */
1117 return (0);
1118 default:
1119 *cp++ = resp;
1120 /* FALLTHROUGH */
1121 case 1: /* error, followed by error msg */
1122 case 2: /* fatal error, "" */
1123 do {
1124 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1125 lostconn(0);
1126 *cp++ = ch;
1127 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1129 if (!iamremote)
1130 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1131 ++errs;
1132 if (resp == 1)
1133 return (-1);
1134 exit(1);
1136 /* NOTREACHED */
1139 void
1140 usage(void)
1142 (void) fprintf(stderr,
1143 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1144 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1145 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1146 exit(1);
1149 void
1150 run_err(const char *fmt,...)
1152 static FILE *fp;
1153 va_list ap;
1155 ++errs;
1156 if (fp == NULL && !(fp = fdopen(remout, "w")))
1157 return;
1158 (void) fprintf(fp, "%c", 0x01);
1159 (void) fprintf(fp, "scp: ");
1160 va_start(ap, fmt);
1161 (void) vfprintf(fp, fmt, ap);
1162 va_end(ap);
1163 (void) fprintf(fp, "\n");
1164 (void) fflush(fp);
1166 if (!iamremote) {
1167 va_start(ap, fmt);
1168 vfprintf(stderr, fmt, ap);
1169 va_end(ap);
1170 fprintf(stderr, "\n");
1174 void
1175 verifydir(char *cp)
1177 struct stat stb;
1179 if (!stat(cp, &stb)) {
1180 if (S_ISDIR(stb.st_mode))
1181 return;
1182 errno = ENOTDIR;
1184 run_err("%s: %s", cp, strerror(errno));
1185 killchild(0);
1189 okname(char *cp0)
1191 int c;
1192 char *cp;
1194 cp = cp0;
1195 do {
1196 c = (int)*cp;
1197 if (c & 0200)
1198 goto bad;
1199 if (!isalpha(c) && !isdigit(c)) {
1200 switch (c) {
1201 case '\'':
1202 case '"':
1203 case '`':
1204 case ' ':
1205 case '#':
1206 goto bad;
1207 default:
1208 break;
1211 } while (*++cp);
1212 return (1);
1214 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1215 return (0);
1218 BUF *
1219 allocbuf(BUF *bp, int fd, int blksize)
1221 size_t size;
1222 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1223 struct stat stb;
1225 if (fstat(fd, &stb) < 0) {
1226 run_err("fstat: %s", strerror(errno));
1227 return (0);
1229 size = roundup(stb.st_blksize, blksize);
1230 if (size == 0)
1231 size = blksize;
1232 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1233 size = blksize;
1234 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1235 if (bp->cnt >= size)
1236 return (bp);
1237 if (bp->buf == NULL)
1238 bp->buf = xmalloc(size);
1239 else
1240 bp->buf = xrealloc(bp->buf, size);
1241 memset(bp->buf, 0, size);
1242 bp->cnt = size;
1243 return (bp);
1246 void
1247 lostconn(int signo)
1249 if (!iamremote)
1250 write(STDERR_FILENO, "lost connection\n", 16);
1251 if (signo)
1252 _exit(1);
1253 else
1254 exit(1);