dropbear

view scp.c @ 895:5608a5a61c2a

Change port separator to ^ since % is used in ipv6 addresses
author Matt Johnston <matt@ucc.asn.au>
date Sat, 15 Feb 2014 21:42:35 +0800
parents fedfb8ede1fd
children
line source
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).
4 *
5 * NOTE: This version should NOT be suid root. (This uses ssh to
6 * do the transfer and ssh has the necessary privileges.)
7 *
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".
15 */
16 /*
17 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
19 *
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.
28 *
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 */
41 /*
42 * Parts from:
43 *
44 * Copyright (c) 1983, 1990, 1992, 1993, 1995
45 * The Regents of the University of California. All rights reserved.
46 *
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. 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.
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 */
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 USE_VFORK
134 pid = vfork();
135 #else
136 pid = fork();
137 #endif
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 USE_VFORK
145 _exit(1);
146 #else
147 exit(1);
148 #endif
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);
168 /*
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.
172 */
174 static void
175 arg_setup(char *host, char *remuser, char *cmd)
177 replacearg(&args, 0, "%s", ssh_program);
178 if (remuser != NULL)
179 addargs(&args, "-l%s", remuser);
180 addargs(&args, "%s", host);
181 addargs(&args, "%s", cmd);
184 int
185 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
187 int pin[2], pout[2], reserved[2];
189 if (verbose_mode)
190 fprintf(stderr,
191 "Executing: program %s host %s, user %s, command %s\n",
192 ssh_program, host,
193 remuser ? remuser : "(unspecified)", cmd);
195 /*
196 * Reserve two descriptors so that the real pipes won't get
197 * descriptors 0 and 1 because that will screw up dup2 below.
198 */
199 pipe(reserved);
201 /* Create a socket pair for communicating with ssh. */
202 if (pipe(pin) < 0)
203 fatal("pipe: %s", strerror(errno));
204 if (pipe(pout) < 0)
205 fatal("pipe: %s", strerror(errno));
207 /* Free the reserved descriptors. */
208 close(reserved[0]);
209 close(reserved[1]);
211 /* uClinux needs to build the args here before vforking,
212 otherwise we do it later on. */
213 #ifdef USE_VFORK
214 arg_setup(host, remuser, cmd);
215 #endif
217 /* Fork a child to execute the command on the remote host using ssh. */
218 #ifdef USE_VFORK
219 do_cmd_pid = vfork();
220 #else
221 do_cmd_pid = fork();
222 #endif
224 if (do_cmd_pid == 0) {
225 /* Child. */
226 close(pin[1]);
227 close(pout[0]);
228 dup2(pin[0], 0);
229 dup2(pout[1], 1);
230 close(pin[0]);
231 close(pout[1]);
233 #ifndef USE_VFORK
234 arg_setup(host, remuser, cmd);
235 #endif
237 execvp(ssh_program, args.list);
238 perror(ssh_program);
239 #ifdef USE_VFORK
240 _exit(1);
241 #else
242 exit(1);
243 #endif
244 } else if (do_cmd_pid == -1) {
245 fatal("fork: %s", strerror(errno));
248 #ifdef USE_VFORK
249 /* clean up command */
250 /* pop cmd */
251 xfree(args.list[args.num-1]);
252 args.list[args.num-1]=NULL;
253 args.num--;
254 /* pop host */
255 xfree(args.list[args.num-1]);
256 args.list[args.num-1]=NULL;
257 args.num--;
258 /* pop user */
259 if (remuser != NULL) {
260 xfree(args.list[args.num-1]);
261 args.list[args.num-1]=NULL;
262 args.num--;
264 #endif
266 /* Parent. Close the other side, and return the local side. */
267 close(pin[0]);
268 *fdout = pin[1];
269 close(pout[1]);
270 *fdin = pout[0];
271 signal(SIGTERM, killchild);
272 signal(SIGINT, killchild);
273 signal(SIGHUP, killchild);
274 return 0;
277 typedef struct {
278 size_t cnt;
279 char *buf;
280 } BUF;
282 BUF *allocbuf(BUF *, int, int);
283 void lostconn(int);
284 void nospace(void);
285 int okname(char *);
286 void run_err(const char *,...);
287 void verifydir(char *);
289 struct passwd *pwd;
290 uid_t userid;
291 int errs, remin, remout;
292 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
294 #define CMDNEEDS 64
295 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
297 int response(void);
298 void rsource(char *, struct stat *);
299 void sink(int, char *[]);
300 void source(int, char *[]);
301 void tolocal(int, char *[]);
302 void toremote(char *, int, char *[]);
303 void usage(void);
305 #if defined(DBMULTI_scp) || !defined(DROPBEAR_MULTI)
306 #if defined(DBMULTI_scp) && defined(DROPBEAR_MULTI)
307 int scp_main(int argc, char **argv)
308 #else
309 int
310 main(int argc, char **argv)
311 #endif
313 int ch, fflag, tflag, status;
314 double speed;
315 char *targ, *endp;
316 extern char *optarg;
317 extern int optind;
319 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
320 sanitise_stdfd();
322 memset(&args, '\0', sizeof(args));
323 args.list = NULL;
324 addargs(&args, "%s", ssh_program);
326 fflag = tflag = 0;
327 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
328 switch (ch) {
329 /* User-visible flags. */
330 case '1':
331 case '2':
332 case '4':
333 case '6':
334 case 'C':
335 addargs(&args, "-%c", ch);
336 break;
337 case 'o':
338 case 'c':
339 case 'i':
340 case 'F':
341 addargs(&args, "-%c%s", ch, optarg);
342 break;
343 case 'P':
344 addargs(&args, "-p%s", optarg);
345 break;
346 case 'B':
347 fprintf(stderr, "Note: -B option is disabled in this version of scp");
348 break;
349 case 'l':
350 speed = strtod(optarg, &endp);
351 if (speed <= 0 || *endp != '\0')
352 usage();
353 limit_rate = speed * 1024;
354 break;
355 case 'p':
356 pflag = 1;
357 break;
358 case 'r':
359 iamrecursive = 1;
360 break;
361 case 'S':
362 ssh_program = xstrdup(optarg);
363 break;
364 case 'v':
365 addargs(&args, "-v");
366 verbose_mode = 1;
367 break;
368 case 'q':
369 #ifdef PROGRESS_METER
370 addargs(&args, "-q");
371 showprogress = 0;
372 #endif
373 break;
375 /* Server options. */
376 case 'd':
377 targetshouldbedirectory = 1;
378 break;
379 case 'f': /* "from" */
380 iamremote = 1;
381 fflag = 1;
382 break;
383 case 't': /* "to" */
384 iamremote = 1;
385 tflag = 1;
386 #ifdef HAVE_CYGWIN
387 setmode(0, O_BINARY);
388 #endif
389 break;
390 default:
391 usage();
393 argc -= optind;
394 argv += optind;
396 if ((pwd = getpwuid(userid = getuid())) == NULL)
397 fatal("unknown user %u", (u_int) userid);
399 if (!isatty(STDERR_FILENO))
400 showprogress = 0;
402 remin = STDIN_FILENO;
403 remout = STDOUT_FILENO;
405 if (fflag) {
406 /* Follow "protocol", send data. */
407 (void) response();
408 source(argc, argv);
409 exit(errs != 0);
411 if (tflag) {
412 /* Receive data. */
413 sink(argc, argv);
414 exit(errs != 0);
416 if (argc < 2)
417 usage();
418 if (argc > 2)
419 targetshouldbedirectory = 1;
421 remin = remout = -1;
422 do_cmd_pid = -1;
423 /* Command to be executed on remote system using "ssh". */
424 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
425 verbose_mode ? " -v" : "",
426 iamrecursive ? " -r" : "", pflag ? " -p" : "",
427 targetshouldbedirectory ? " -d" : "");
429 (void) signal(SIGPIPE, lostconn);
431 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
432 toremote(targ, argc, argv);
433 else {
434 if (targetshouldbedirectory)
435 verifydir(argv[argc - 1]);
436 tolocal(argc, argv); /* Dest is local host. */
438 /*
439 * Finally check the exit status of the ssh process, if one was forked
440 * and no error has occured yet
441 */
442 if (do_cmd_pid != -1 && errs == 0) {
443 if (remin != -1)
444 (void) close(remin);
445 if (remout != -1)
446 (void) close(remout);
447 if (waitpid(do_cmd_pid, &status, 0) == -1)
448 errs = 1;
449 else {
450 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
451 errs = 1;
454 exit(errs != 0);
456 #endif /* DBMULTI_scp stuff */
458 void
459 toremote(char *targ, int argc, char **argv)
461 int i, len;
462 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
463 arglist alist;
465 memset(&alist, '\0', sizeof(alist));
466 alist.list = NULL;
468 *targ++ = 0;
469 if (*targ == 0)
470 targ = ".";
472 arg = xstrdup(argv[argc - 1]);
473 if ((thost = strrchr(arg, '@'))) {
474 /* user@host */
475 *thost++ = 0;
476 tuser = arg;
477 if (*tuser == '\0')
478 tuser = NULL;
479 } else {
480 thost = arg;
481 tuser = NULL;
484 if (tuser != NULL && !okname(tuser)) {
485 xfree(arg);
486 return;
489 for (i = 0; i < argc - 1; i++) {
490 src = colon(argv[i]);
491 if (src) { /* remote to remote */
492 freeargs(&alist);
493 addargs(&alist, "%s", ssh_program);
494 if (verbose_mode)
495 addargs(&alist, "-v");
496 #if 0
497 /* Disabled since dbclient won't understand them
498 and scp works fine without them. */
499 addargs(&alist, "-x");
500 addargs(&alist, "-oClearAllForwardings yes");
501 addargs(&alist, "-n");
502 #endif
504 *src++ = 0;
505 if (*src == 0)
506 src = ".";
507 host = strrchr(argv[i], '@');
509 if (host) {
510 *host++ = 0;
511 host = cleanhostname(host);
512 suser = argv[i];
513 if (*suser == '\0')
514 suser = pwd->pw_name;
515 else if (!okname(suser))
516 continue;
517 addargs(&alist, "-l");
518 addargs(&alist, "%s", suser);
519 } else {
520 host = cleanhostname(argv[i]);
522 addargs(&alist, "%s", host);
523 addargs(&alist, "%s", cmd);
524 addargs(&alist, "%s", src);
525 addargs(&alist, "%s%s%s:%s",
526 tuser ? tuser : "", tuser ? "@" : "",
527 thost, targ);
528 if (do_local_cmd(&alist) != 0)
529 errs = 1;
530 } else { /* local to remote */
531 if (remin == -1) {
532 len = strlen(targ) + CMDNEEDS + 20;
533 bp = xmalloc(len);
534 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
535 host = cleanhostname(thost);
536 if (do_cmd(host, tuser, bp, &remin,
537 &remout, argc) < 0)
538 exit(1);
539 if (response() < 0)
540 exit(1);
541 (void) xfree(bp);
543 source(1, argv + i);
548 void
549 tolocal(int argc, char **argv)
551 int i, len;
552 char *bp, *host, *src, *suser;
553 arglist alist;
555 memset(&alist, '\0', sizeof(alist));
556 alist.list = NULL;
558 for (i = 0; i < argc - 1; i++) {
559 if (!(src = colon(argv[i]))) { /* Local to local. */
560 freeargs(&alist);
561 addargs(&alist, "%s", _PATH_CP);
562 if (iamrecursive)
563 addargs(&alist, "-r");
564 if (pflag)
565 addargs(&alist, "-p");
566 addargs(&alist, "%s", argv[i]);
567 addargs(&alist, "%s", argv[argc-1]);
568 if (do_local_cmd(&alist))
569 ++errs;
570 continue;
572 *src++ = 0;
573 if (*src == 0)
574 src = ".";
575 if ((host = strrchr(argv[i], '@')) == NULL) {
576 host = argv[i];
577 suser = NULL;
578 } else {
579 *host++ = 0;
580 suser = argv[i];
581 if (*suser == '\0')
582 suser = pwd->pw_name;
584 host = cleanhostname(host);
585 len = strlen(src) + CMDNEEDS + 20;
586 bp = xmalloc(len);
587 (void) snprintf(bp, len, "%s -f %s", cmd, src);
588 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
589 (void) xfree(bp);
590 ++errs;
591 continue;
593 xfree(bp);
594 sink(1, argv + argc - 1);
595 (void) close(remin);
596 remin = remout = -1;
600 void
601 source(int argc, char **argv)
603 struct stat stb;
604 static BUF buffer;
605 BUF *bp;
606 off_t i, amt, statbytes;
607 size_t result;
608 int fd = -1, haderr, indx;
609 char *last, *name, buf[2048];
610 int len;
612 for (indx = 0; indx < argc; ++indx) {
613 name = argv[indx];
614 statbytes = 0;
615 len = strlen(name);
616 while (len > 1 && name[len-1] == '/')
617 name[--len] = '\0';
618 if (strchr(name, '\n') != NULL) {
619 run_err("%s: skipping, filename contains a newline",
620 name);
621 goto next;
623 if ((fd = open(name, O_RDONLY, 0)) < 0)
624 goto syserr;
625 if (fstat(fd, &stb) < 0) {
626 syserr: run_err("%s: %s", name, strerror(errno));
627 goto next;
629 switch (stb.st_mode & S_IFMT) {
630 case S_IFREG:
631 break;
632 case S_IFDIR:
633 if (iamrecursive) {
634 rsource(name, &stb);
635 goto next;
637 /* FALLTHROUGH */
638 default:
639 run_err("%s: not a regular file", name);
640 goto next;
642 if ((last = strrchr(name, '/')) == NULL)
643 last = name;
644 else
645 ++last;
646 curfile = last;
647 if (pflag) {
648 /*
649 * Make it compatible with possible future
650 * versions expecting microseconds.
651 */
652 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
653 (u_long) stb.st_mtime,
654 (u_long) stb.st_atime);
655 (void) atomicio(vwrite, remout, buf, strlen(buf));
656 if (response() < 0)
657 goto next;
659 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
660 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
661 (u_int) (stb.st_mode & FILEMODEMASK),
662 (long long)stb.st_size, last);
663 if (verbose_mode) {
664 fprintf(stderr, "Sending file modes: %s", buf);
666 (void) atomicio(vwrite, remout, buf, strlen(buf));
667 if (response() < 0)
668 goto next;
669 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
670 next: if (fd != -1) {
671 (void) close(fd);
672 fd = -1;
674 continue;
676 #if PROGRESS_METER
677 if (showprogress)
678 start_progress_meter(curfile, stb.st_size, &statbytes);
679 #endif
680 /* Keep writing after an error so that we stay sync'd up. */
681 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
682 amt = bp->cnt;
683 if (i + amt > stb.st_size)
684 amt = stb.st_size - i;
685 if (!haderr) {
686 result = atomicio(read, fd, bp->buf, amt);
687 if (result != amt)
688 haderr = errno;
690 if (haderr)
691 (void) atomicio(vwrite, remout, bp->buf, amt);
692 else {
693 result = atomicio(vwrite, remout, bp->buf, amt);
694 if (result != amt)
695 haderr = errno;
696 statbytes += result;
698 if (limit_rate)
699 bwlimit(amt);
701 #ifdef PROGRESS_METER
702 if (showprogress)
703 stop_progress_meter();
704 #endif
706 if (fd != -1) {
707 if (close(fd) < 0 && !haderr)
708 haderr = errno;
709 fd = -1;
711 if (!haderr)
712 (void) atomicio(vwrite, remout, "", 1);
713 else
714 run_err("%s: %s", name, strerror(haderr));
715 (void) response();
719 void
720 rsource(char *name, struct stat *statp)
722 DIR *dirp;
723 struct dirent *dp;
724 char *last, *vect[1], path[1100];
726 if (!(dirp = opendir(name))) {
727 run_err("%s: %s", name, strerror(errno));
728 return;
730 last = strrchr(name, '/');
731 if (last == 0)
732 last = name;
733 else
734 last++;
735 if (pflag) {
736 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
737 (u_long) statp->st_mtime,
738 (u_long) statp->st_atime);
739 (void) atomicio(vwrite, remout, path, strlen(path));
740 if (response() < 0) {
741 closedir(dirp);
742 return;
745 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
746 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
747 if (verbose_mode)
748 fprintf(stderr, "Entering directory: %s", path);
749 (void) atomicio(vwrite, remout, path, strlen(path));
750 if (response() < 0) {
751 closedir(dirp);
752 return;
754 while ((dp = readdir(dirp)) != NULL) {
755 if (dp->d_ino == 0)
756 continue;
757 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
758 continue;
759 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
760 run_err("%s/%s: name too long", name, dp->d_name);
761 continue;
763 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
764 vect[0] = path;
765 source(1, vect);
767 (void) closedir(dirp);
768 (void) atomicio(vwrite, remout, "E\n", 2);
769 (void) response();
772 void
773 bwlimit(int amount)
775 static struct timeval bwstart, bwend;
776 static int lamt, thresh = 16384;
777 uint64_t waitlen;
778 struct timespec ts, rm;
780 if (!timerisset(&bwstart)) {
781 gettimeofday(&bwstart, NULL);
782 return;
785 lamt += amount;
786 if (lamt < thresh)
787 return;
789 gettimeofday(&bwend, NULL);
790 timersub(&bwend, &bwstart, &bwend);
791 if (!timerisset(&bwend))
792 return;
794 lamt *= 8;
795 waitlen = (double)1000000L * lamt / limit_rate;
797 bwstart.tv_sec = waitlen / 1000000L;
798 bwstart.tv_usec = waitlen % 1000000L;
800 if (timercmp(&bwstart, &bwend, >)) {
801 timersub(&bwstart, &bwend, &bwend);
803 /* Adjust the wait time */
804 if (bwend.tv_sec) {
805 thresh /= 2;
806 if (thresh < 2048)
807 thresh = 2048;
808 } else if (bwend.tv_usec < 100) {
809 thresh *= 2;
810 if (thresh > 32768)
811 thresh = 32768;
814 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
815 while (nanosleep(&ts, &rm) == -1) {
816 if (errno != EINTR)
817 break;
818 ts = rm;
822 lamt = 0;
823 gettimeofday(&bwstart, NULL);
826 void
827 sink(int argc, char **argv)
829 static BUF buffer;
830 struct stat stb;
831 enum {
832 YES, NO, DISPLAYED
833 } wrerr;
834 BUF *bp;
835 off_t i;
836 size_t j, count;
837 int amt, exists, first, mask, mode, ofd, omode;
838 off_t size, statbytes;
839 int setimes, targisdir, wrerrno = 0;
840 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
841 struct timeval tv[2];
843 #define atime tv[0]
844 #define mtime tv[1]
845 #define SCREWUP(str) { why = str; goto screwup; }
847 setimes = targisdir = 0;
848 mask = umask(0);
849 if (!pflag)
850 (void) umask(mask);
851 if (argc != 1) {
852 run_err("ambiguous target");
853 exit(1);
855 targ = *argv;
856 if (targetshouldbedirectory)
857 verifydir(targ);
859 (void) atomicio(vwrite, remout, "", 1);
860 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
861 targisdir = 1;
862 for (first = 1;; first = 0) {
863 cp = buf;
864 if (atomicio(read, remin, cp, 1) != 1)
865 return;
866 if (*cp++ == '\n')
867 SCREWUP("unexpected <newline>");
868 do {
869 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
870 SCREWUP("lost connection");
871 *cp++ = ch;
872 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
873 *cp = 0;
874 if (verbose_mode)
875 fprintf(stderr, "Sink: %s", buf);
877 if (buf[0] == '\01' || buf[0] == '\02') {
878 if (iamremote == 0)
879 (void) atomicio(vwrite, STDERR_FILENO,
880 buf + 1, strlen(buf + 1));
881 if (buf[0] == '\02')
882 exit(1);
883 ++errs;
884 continue;
886 if (buf[0] == 'E') {
887 (void) atomicio(vwrite, remout, "", 1);
888 return;
890 if (ch == '\n')
891 *--cp = 0;
893 cp = buf;
894 if (*cp == 'T') {
895 setimes++;
896 cp++;
897 mtime.tv_sec = strtol(cp, &cp, 10);
898 if (!cp || *cp++ != ' ')
899 SCREWUP("mtime.sec not delimited");
900 mtime.tv_usec = strtol(cp, &cp, 10);
901 if (!cp || *cp++ != ' ')
902 SCREWUP("mtime.usec not delimited");
903 atime.tv_sec = strtol(cp, &cp, 10);
904 if (!cp || *cp++ != ' ')
905 SCREWUP("atime.sec not delimited");
906 atime.tv_usec = strtol(cp, &cp, 10);
907 if (!cp || *cp++ != '\0')
908 SCREWUP("atime.usec not delimited");
909 (void) atomicio(vwrite, remout, "", 1);
910 continue;
912 if (*cp != 'C' && *cp != 'D') {
913 /*
914 * Check for the case "rcp remote:foo\* local:bar".
915 * In this case, the line "No match." can be returned
916 * by the shell before the rcp command on the remote is
917 * executed so the ^Aerror_message convention isn't
918 * followed.
919 */
920 if (first) {
921 run_err("%s", cp);
922 exit(1);
924 SCREWUP("expected control record");
926 mode = 0;
927 for (++cp; cp < buf + 5; cp++) {
928 if (*cp < '0' || *cp > '7')
929 SCREWUP("bad mode");
930 mode = (mode << 3) | (*cp - '0');
932 if (*cp++ != ' ')
933 SCREWUP("mode not delimited");
935 for (size = 0; isdigit(*cp);)
936 size = size * 10 + (*cp++ - '0');
937 if (*cp++ != ' ')
938 SCREWUP("size not delimited");
939 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
940 run_err("error: unexpected filename: %s", cp);
941 exit(1);
943 if (targisdir) {
944 static char *namebuf;
945 static size_t cursize;
946 size_t need;
948 need = strlen(targ) + strlen(cp) + 250;
949 if (need > cursize) {
950 if (namebuf)
951 xfree(namebuf);
952 namebuf = xmalloc(need);
953 cursize = need;
955 (void) snprintf(namebuf, need, "%s%s%s", targ,
956 strcmp(targ, "/") ? "/" : "", cp);
957 np = namebuf;
958 } else
959 np = targ;
960 curfile = cp;
961 exists = stat(np, &stb) == 0;
962 if (buf[0] == 'D') {
963 int mod_flag = pflag;
964 if (!iamrecursive)
965 SCREWUP("received directory without -r");
966 if (exists) {
967 if (!S_ISDIR(stb.st_mode)) {
968 errno = ENOTDIR;
969 goto bad;
971 if (pflag)
972 (void) chmod(np, mode);
973 } else {
974 /* Handle copying from a read-only
975 directory */
976 mod_flag = 1;
977 if (mkdir(np, mode | S_IRWXU) < 0)
978 goto bad;
980 vect[0] = xstrdup(np);
981 sink(1, vect);
982 if (setimes) {
983 setimes = 0;
984 if (utimes(vect[0], tv) < 0)
985 run_err("%s: set times: %s",
986 vect[0], strerror(errno));
988 if (mod_flag)
989 (void) chmod(vect[0], mode);
990 if (vect[0])
991 xfree(vect[0]);
992 continue;
994 omode = mode;
995 mode |= S_IWRITE;
996 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
997 bad: run_err("%s: %s", np, strerror(errno));
998 continue;
1000 (void) atomicio(vwrite, remout, "", 1);
1001 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
1002 (void) close(ofd);
1003 continue;
1005 cp = bp->buf;
1006 wrerr = NO;
1008 statbytes = 0;
1009 #ifdef PROGRESS_METER
1010 if (showprogress)
1011 start_progress_meter(curfile, size, &statbytes);
1012 #endif
1013 for (count = i = 0; i < size; i += 4096) {
1014 amt = 4096;
1015 if (i + amt > size)
1016 amt = size - i;
1017 count += amt;
1018 do {
1019 j = atomicio(read, remin, cp, amt);
1020 if (j == 0) {
1021 run_err("%s", j ? strerror(errno) :
1022 "dropped connection");
1023 exit(1);
1025 amt -= j;
1026 cp += j;
1027 statbytes += j;
1028 } while (amt > 0);
1030 if (limit_rate)
1031 bwlimit(4096);
1033 if (count == bp->cnt) {
1034 /* Keep reading so we stay sync'd up. */
1035 if (wrerr == NO) {
1036 if (atomicio(vwrite, ofd, bp->buf,
1037 count) != count) {
1038 wrerr = YES;
1039 wrerrno = errno;
1042 count = 0;
1043 cp = bp->buf;
1046 #ifdef PROGRESS_METER
1047 if (showprogress)
1048 stop_progress_meter();
1049 #endif
1050 if (count != 0 && wrerr == NO &&
1051 atomicio(vwrite, ofd, bp->buf, count) != count) {
1052 wrerr = YES;
1053 wrerrno = errno;
1055 if (wrerr == NO && ftruncate(ofd, size) != 0) {
1056 run_err("%s: truncate: %s", np, strerror(errno));
1057 wrerr = DISPLAYED;
1059 if (pflag) {
1060 if (exists || omode != mode)
1061 #ifdef HAVE_FCHMOD
1062 if (fchmod(ofd, omode)) {
1063 #else /* HAVE_FCHMOD */
1064 if (chmod(np, omode)) {
1065 #endif /* HAVE_FCHMOD */
1066 run_err("%s: set mode: %s",
1067 np, strerror(errno));
1068 wrerr = DISPLAYED;
1070 } else {
1071 if (!exists && omode != mode)
1072 #ifdef HAVE_FCHMOD
1073 if (fchmod(ofd, omode & ~mask)) {
1074 #else /* HAVE_FCHMOD */
1075 if (chmod(np, omode & ~mask)) {
1076 #endif /* HAVE_FCHMOD */
1077 run_err("%s: set mode: %s",
1078 np, strerror(errno));
1079 wrerr = DISPLAYED;
1082 if (close(ofd) == -1) {
1083 wrerr = YES;
1084 wrerrno = errno;
1086 (void) response();
1087 if (setimes && wrerr == NO) {
1088 setimes = 0;
1089 if (utimes(np, tv) < 0) {
1090 run_err("%s: set times: %s",
1091 np, strerror(errno));
1092 wrerr = DISPLAYED;
1095 switch (wrerr) {
1096 case YES:
1097 run_err("%s: %s", np, strerror(wrerrno));
1098 break;
1099 case NO:
1100 (void) atomicio(vwrite, remout, "", 1);
1101 break;
1102 case DISPLAYED:
1103 break;
1106 screwup:
1107 run_err("protocol error: %s", why);
1108 exit(1);
1111 int
1112 response(void)
1114 char ch, *cp, resp, rbuf[2048];
1116 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1117 lostconn(0);
1119 cp = rbuf;
1120 switch (resp) {
1121 case 0: /* ok */
1122 return (0);
1123 default:
1124 *cp++ = resp;
1125 /* FALLTHROUGH */
1126 case 1: /* error, followed by error msg */
1127 case 2: /* fatal error, "" */
1128 do {
1129 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1130 lostconn(0);
1131 *cp++ = ch;
1132 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1134 if (!iamremote)
1135 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1136 ++errs;
1137 if (resp == 1)
1138 return (-1);
1139 exit(1);
1141 /* NOTREACHED */
1144 void
1145 usage(void)
1147 (void) fprintf(stderr,
1148 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1149 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1150 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1151 exit(1);
1154 void
1155 run_err(const char *fmt,...)
1157 static FILE *fp;
1158 va_list ap;
1160 ++errs;
1161 if (fp == NULL && !(fp = fdopen(remout, "w")))
1162 return;
1163 (void) fprintf(fp, "%c", 0x01);
1164 (void) fprintf(fp, "scp: ");
1165 va_start(ap, fmt);
1166 (void) vfprintf(fp, fmt, ap);
1167 va_end(ap);
1168 (void) fprintf(fp, "\n");
1169 (void) fflush(fp);
1171 if (!iamremote) {
1172 va_start(ap, fmt);
1173 vfprintf(stderr, fmt, ap);
1174 va_end(ap);
1175 fprintf(stderr, "\n");
1179 void
1180 verifydir(char *cp)
1182 struct stat stb;
1184 if (!stat(cp, &stb)) {
1185 if (S_ISDIR(stb.st_mode))
1186 return;
1187 errno = ENOTDIR;
1189 run_err("%s: %s", cp, strerror(errno));
1190 killchild(0);
1193 int
1194 okname(char *cp0)
1196 int c;
1197 char *cp;
1199 cp = cp0;
1200 do {
1201 c = (int)*cp;
1202 if (c & 0200)
1203 goto bad;
1204 if (!isalpha(c) && !isdigit(c)) {
1205 switch (c) {
1206 case '\'':
1207 case '"':
1208 case '`':
1209 case ' ':
1210 case '#':
1211 goto bad;
1212 default:
1213 break;
1216 } while (*++cp);
1217 return (1);
1219 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1220 return (0);
1223 BUF *
1224 allocbuf(BUF *bp, int fd, int blksize)
1226 size_t size;
1227 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1228 struct stat stb;
1230 if (fstat(fd, &stb) < 0) {
1231 run_err("fstat: %s", strerror(errno));
1232 return (0);
1234 size = roundup(stb.st_blksize, blksize);
1235 if (size == 0)
1236 size = blksize;
1237 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1238 size = blksize;
1239 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1240 if (bp->cnt >= size)
1241 return (bp);
1242 if (bp->buf == NULL)
1243 bp->buf = xmalloc(size);
1244 else
1245 bp->buf = xrealloc(bp->buf, size);
1246 memset(bp->buf, 0, size);
1247 bp->cnt = size;
1248 return (bp);
1251 void
1252 lostconn(int signo)
1254 if (!iamremote)
1255 write(STDERR_FILENO, "lost connection\n", 16);
1256 if (signo)
1257 _exit(1);
1258 else
1259 exit(1);