- (dtucker) platform.c session.c] Move the USE_LIBIAF fragment into
[openssh-git.git] / scp.c
bloba4066c668c1bb0bac2cb1c57dd689d2b99e27d6b
1 /* $OpenBSD: scp.c,v 1.167 2010/09/22 22:58:51 djm 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 #include <sys/param.h>
78 #ifdef HAVE_SYS_STAT_H
79 # include <sys/stat.h>
80 #endif
81 #ifdef HAVE_POLL_H
82 #include <poll.h>
83 #else
84 # ifdef HAVE_SYS_POLL_H
85 # include <sys/poll.h>
86 # endif
87 #endif
88 #ifdef HAVE_SYS_TIME_H
89 # include <sys/time.h>
90 #endif
91 #include <sys/wait.h>
92 #include <sys/uio.h>
94 #include <ctype.h>
95 #include <dirent.h>
96 #include <errno.h>
97 #include <fcntl.h>
98 #include <pwd.h>
99 #include <signal.h>
100 #include <stdarg.h>
101 #include <stdio.h>
102 #include <stdlib.h>
103 #include <string.h>
104 #include <time.h>
105 #include <unistd.h>
106 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H)
107 #include <vis.h>
108 #endif
110 #include "xmalloc.h"
111 #include "atomicio.h"
112 #include "pathnames.h"
113 #include "log.h"
114 #include "misc.h"
115 #include "progressmeter.h"
117 extern char *__progname;
119 #define COPY_BUFLEN 16384
121 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
123 /* Struct for addargs */
124 arglist args;
126 /* Bandwidth limit */
127 long long limit_kbps = 0;
128 struct bwlimit bwlimit;
130 /* Name of current file being transferred. */
131 char *curfile;
133 /* This is set to non-zero to enable verbose mode. */
134 int verbose_mode = 0;
136 /* This is set to zero if the progressmeter is not desired. */
137 int showprogress = 1;
139 /* This is the program to execute for the secured connection. ("ssh" or -S) */
140 char *ssh_program = _PATH_SSH_PROGRAM;
142 /* This is used to store the pid of ssh_program */
143 pid_t do_cmd_pid = -1;
145 static void
146 killchild(int signo)
148 if (do_cmd_pid > 1) {
149 kill(do_cmd_pid, signo ? signo : SIGTERM);
150 waitpid(do_cmd_pid, NULL, 0);
153 if (signo)
154 _exit(1);
155 exit(1);
158 static void
159 suspchild(int signo)
161 int status;
163 if (do_cmd_pid > 1) {
164 kill(do_cmd_pid, signo);
165 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
166 errno == EINTR)
168 kill(getpid(), SIGSTOP);
172 static int
173 do_local_cmd(arglist *a)
175 u_int i;
176 int status;
177 pid_t pid;
179 if (a->num == 0)
180 fatal("do_local_cmd: no arguments");
182 if (verbose_mode) {
183 fprintf(stderr, "Executing:");
184 for (i = 0; i < a->num; i++)
185 fprintf(stderr, " %s", a->list[i]);
186 fprintf(stderr, "\n");
188 if ((pid = fork()) == -1)
189 fatal("do_local_cmd: fork: %s", strerror(errno));
191 if (pid == 0) {
192 execvp(a->list[0], a->list);
193 perror(a->list[0]);
194 exit(1);
197 do_cmd_pid = pid;
198 signal(SIGTERM, killchild);
199 signal(SIGINT, killchild);
200 signal(SIGHUP, killchild);
202 while (waitpid(pid, &status, 0) == -1)
203 if (errno != EINTR)
204 fatal("do_local_cmd: waitpid: %s", strerror(errno));
206 do_cmd_pid = -1;
208 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
209 return (-1);
211 return (0);
215 * This function executes the given command as the specified user on the
216 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
217 * assigns the input and output file descriptors on success.
221 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
223 int pin[2], pout[2], reserved[2];
225 if (verbose_mode)
226 fprintf(stderr,
227 "Executing: program %s host %s, user %s, command %s\n",
228 ssh_program, host,
229 remuser ? remuser : "(unspecified)", cmd);
232 * Reserve two descriptors so that the real pipes won't get
233 * descriptors 0 and 1 because that will screw up dup2 below.
235 if (pipe(reserved) < 0)
236 fatal("pipe: %s", strerror(errno));
238 /* Create a socket pair for communicating with ssh. */
239 if (pipe(pin) < 0)
240 fatal("pipe: %s", strerror(errno));
241 if (pipe(pout) < 0)
242 fatal("pipe: %s", strerror(errno));
244 /* Free the reserved descriptors. */
245 close(reserved[0]);
246 close(reserved[1]);
248 signal(SIGTSTP, suspchild);
249 signal(SIGTTIN, suspchild);
250 signal(SIGTTOU, suspchild);
252 /* Fork a child to execute the command on the remote host using ssh. */
253 do_cmd_pid = fork();
254 if (do_cmd_pid == 0) {
255 /* Child. */
256 close(pin[1]);
257 close(pout[0]);
258 dup2(pin[0], 0);
259 dup2(pout[1], 1);
260 close(pin[0]);
261 close(pout[1]);
263 replacearg(&args, 0, "%s", ssh_program);
264 if (remuser != NULL) {
265 addargs(&args, "-l");
266 addargs(&args, "%s", remuser);
268 addargs(&args, "--");
269 addargs(&args, "%s", host);
270 addargs(&args, "%s", cmd);
272 execvp(ssh_program, args.list);
273 perror(ssh_program);
274 exit(1);
275 } else if (do_cmd_pid == -1) {
276 fatal("fork: %s", strerror(errno));
278 /* Parent. Close the other side, and return the local side. */
279 close(pin[0]);
280 *fdout = pin[1];
281 close(pout[1]);
282 *fdin = pout[0];
283 signal(SIGTERM, killchild);
284 signal(SIGINT, killchild);
285 signal(SIGHUP, killchild);
286 return 0;
289 typedef struct {
290 size_t cnt;
291 char *buf;
292 } BUF;
294 BUF *allocbuf(BUF *, int, int);
295 void lostconn(int);
296 int okname(char *);
297 void run_err(const char *,...);
298 void verifydir(char *);
300 struct passwd *pwd;
301 uid_t userid;
302 int errs, remin, remout;
303 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
305 #define CMDNEEDS 64
306 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
308 int response(void);
309 void rsource(char *, struct stat *);
310 void sink(int, char *[]);
311 void source(int, char *[]);
312 void tolocal(int, char *[]);
313 void toremote(char *, int, char *[]);
314 void usage(void);
317 main(int argc, char **argv)
319 int ch, fflag, tflag, status, n;
320 char *targ, **newargv;
321 const char *errstr;
322 extern char *optarg;
323 extern int optind;
325 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
326 sanitise_stdfd();
328 /* Copy argv, because we modify it */
329 newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv));
330 for (n = 0; n < argc; n++)
331 newargv[n] = xstrdup(argv[n]);
332 argv = newargv;
334 __progname = ssh_get_progname(argv[0]);
336 memset(&args, '\0', sizeof(args));
337 args.list = NULL;
338 addargs(&args, "%s", ssh_program);
339 addargs(&args, "-x");
340 addargs(&args, "-oForwardAgent no");
341 addargs(&args, "-oPermitLocalCommand no");
342 addargs(&args, "-oClearAllForwardings yes");
344 fflag = tflag = 0;
345 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
346 switch (ch) {
347 /* User-visible flags. */
348 case '1':
349 case '2':
350 case '4':
351 case '6':
352 case 'C':
353 addargs(&args, "-%c", ch);
354 break;
355 case 'o':
356 case 'c':
357 case 'i':
358 case 'F':
359 addargs(&args, "-%c", ch);
360 addargs(&args, "%s", optarg);
361 break;
362 case 'P':
363 addargs(&args, "-p");
364 addargs(&args, "%s", optarg);
365 break;
366 case 'B':
367 addargs(&args, "-oBatchmode yes");
368 break;
369 case 'l':
370 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
371 &errstr);
372 if (errstr != NULL)
373 usage();
374 limit_kbps *= 1024; /* kbps */
375 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
376 break;
377 case 'p':
378 pflag = 1;
379 break;
380 case 'r':
381 iamrecursive = 1;
382 break;
383 case 'S':
384 ssh_program = xstrdup(optarg);
385 break;
386 case 'v':
387 addargs(&args, "-v");
388 verbose_mode = 1;
389 break;
390 case 'q':
391 addargs(&args, "-q");
392 showprogress = 0;
393 break;
395 /* Server options. */
396 case 'd':
397 targetshouldbedirectory = 1;
398 break;
399 case 'f': /* "from" */
400 iamremote = 1;
401 fflag = 1;
402 break;
403 case 't': /* "to" */
404 iamremote = 1;
405 tflag = 1;
406 #ifdef HAVE_CYGWIN
407 setmode(0, O_BINARY);
408 #endif
409 break;
410 default:
411 usage();
413 argc -= optind;
414 argv += optind;
416 if ((pwd = getpwuid(userid = getuid())) == NULL)
417 fatal("unknown user %u", (u_int) userid);
419 if (!isatty(STDOUT_FILENO))
420 showprogress = 0;
422 remin = STDIN_FILENO;
423 remout = STDOUT_FILENO;
425 if (fflag) {
426 /* Follow "protocol", send data. */
427 (void) response();
428 source(argc, argv);
429 exit(errs != 0);
431 if (tflag) {
432 /* Receive data. */
433 sink(argc, argv);
434 exit(errs != 0);
436 if (argc < 2)
437 usage();
438 if (argc > 2)
439 targetshouldbedirectory = 1;
441 remin = remout = -1;
442 do_cmd_pid = -1;
443 /* Command to be executed on remote system using "ssh". */
444 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
445 verbose_mode ? " -v" : "",
446 iamrecursive ? " -r" : "", pflag ? " -p" : "",
447 targetshouldbedirectory ? " -d" : "");
449 (void) signal(SIGPIPE, lostconn);
451 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
452 toremote(targ, argc, argv);
453 else {
454 if (targetshouldbedirectory)
455 verifydir(argv[argc - 1]);
456 tolocal(argc, argv); /* Dest is local host. */
459 * Finally check the exit status of the ssh process, if one was forked
460 * and no error has occurred yet
462 if (do_cmd_pid != -1 && errs == 0) {
463 if (remin != -1)
464 (void) close(remin);
465 if (remout != -1)
466 (void) close(remout);
467 if (waitpid(do_cmd_pid, &status, 0) == -1)
468 errs = 1;
469 else {
470 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
471 errs = 1;
474 exit(errs != 0);
477 /* Callback from atomicio6 to update progress meter and limit bandwidth */
478 static int
479 scpio(void *_cnt, size_t s)
481 off_t *cnt = (off_t *)_cnt;
483 *cnt += s;
484 if (limit_kbps > 0)
485 bandwidth_limit(&bwlimit, s);
486 return 0;
489 void
490 toremote(char *targ, int argc, char **argv)
492 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
493 arglist alist;
494 int i;
496 memset(&alist, '\0', sizeof(alist));
497 alist.list = NULL;
499 *targ++ = 0;
500 if (*targ == 0)
501 targ = ".";
503 arg = xstrdup(argv[argc - 1]);
504 if ((thost = strrchr(arg, '@'))) {
505 /* user@host */
506 *thost++ = 0;
507 tuser = arg;
508 if (*tuser == '\0')
509 tuser = NULL;
510 } else {
511 thost = arg;
512 tuser = NULL;
515 if (tuser != NULL && !okname(tuser)) {
516 xfree(arg);
517 return;
520 for (i = 0; i < argc - 1; i++) {
521 src = colon(argv[i]);
522 if (src) { /* remote to remote */
523 freeargs(&alist);
524 addargs(&alist, "%s", ssh_program);
525 if (verbose_mode)
526 addargs(&alist, "-v");
527 addargs(&alist, "-x");
528 addargs(&alist, "-oClearAllForwardings yes");
529 addargs(&alist, "-n");
531 *src++ = 0;
532 if (*src == 0)
533 src = ".";
534 host = strrchr(argv[i], '@');
536 if (host) {
537 *host++ = 0;
538 host = cleanhostname(host);
539 suser = argv[i];
540 if (*suser == '\0')
541 suser = pwd->pw_name;
542 else if (!okname(suser))
543 continue;
544 addargs(&alist, "-l");
545 addargs(&alist, "%s", suser);
546 } else {
547 host = cleanhostname(argv[i]);
549 addargs(&alist, "--");
550 addargs(&alist, "%s", host);
551 addargs(&alist, "%s", cmd);
552 addargs(&alist, "%s", src);
553 addargs(&alist, "%s%s%s:%s",
554 tuser ? tuser : "", tuser ? "@" : "",
555 thost, targ);
556 if (do_local_cmd(&alist) != 0)
557 errs = 1;
558 } else { /* local to remote */
559 if (remin == -1) {
560 xasprintf(&bp, "%s -t -- %s", cmd, targ);
561 host = cleanhostname(thost);
562 if (do_cmd(host, tuser, bp, &remin,
563 &remout) < 0)
564 exit(1);
565 if (response() < 0)
566 exit(1);
567 (void) xfree(bp);
569 source(1, argv + i);
572 xfree(arg);
575 void
576 tolocal(int argc, char **argv)
578 char *bp, *host, *src, *suser;
579 arglist alist;
580 int i;
582 memset(&alist, '\0', sizeof(alist));
583 alist.list = NULL;
585 for (i = 0; i < argc - 1; i++) {
586 if (!(src = colon(argv[i]))) { /* Local to local. */
587 freeargs(&alist);
588 addargs(&alist, "%s", _PATH_CP);
589 if (iamrecursive)
590 addargs(&alist, "-r");
591 if (pflag)
592 addargs(&alist, "-p");
593 addargs(&alist, "--");
594 addargs(&alist, "%s", argv[i]);
595 addargs(&alist, "%s", argv[argc-1]);
596 if (do_local_cmd(&alist))
597 ++errs;
598 continue;
600 *src++ = 0;
601 if (*src == 0)
602 src = ".";
603 if ((host = strrchr(argv[i], '@')) == NULL) {
604 host = argv[i];
605 suser = NULL;
606 } else {
607 *host++ = 0;
608 suser = argv[i];
609 if (*suser == '\0')
610 suser = pwd->pw_name;
612 host = cleanhostname(host);
613 xasprintf(&bp, "%s -f -- %s", cmd, src);
614 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
615 (void) xfree(bp);
616 ++errs;
617 continue;
619 xfree(bp);
620 sink(1, argv + argc - 1);
621 (void) close(remin);
622 remin = remout = -1;
626 void
627 source(int argc, char **argv)
629 struct stat stb;
630 static BUF buffer;
631 BUF *bp;
632 off_t i, statbytes;
633 size_t amt;
634 int fd = -1, haderr, indx;
635 char *last, *name, buf[2048], encname[MAXPATHLEN];
636 int len;
638 for (indx = 0; indx < argc; ++indx) {
639 name = argv[indx];
640 statbytes = 0;
641 len = strlen(name);
642 while (len > 1 && name[len-1] == '/')
643 name[--len] = '\0';
644 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
645 goto syserr;
646 if (strchr(name, '\n') != NULL) {
647 strnvis(encname, name, sizeof(encname), VIS_NL);
648 name = encname;
650 if (fstat(fd, &stb) < 0) {
651 syserr: run_err("%s: %s", name, strerror(errno));
652 goto next;
654 if (stb.st_size < 0) {
655 run_err("%s: %s", name, "Negative file size");
656 goto next;
658 unset_nonblock(fd);
659 switch (stb.st_mode & S_IFMT) {
660 case S_IFREG:
661 break;
662 case S_IFDIR:
663 if (iamrecursive) {
664 rsource(name, &stb);
665 goto next;
667 /* FALLTHROUGH */
668 default:
669 run_err("%s: not a regular file", name);
670 goto next;
672 if ((last = strrchr(name, '/')) == NULL)
673 last = name;
674 else
675 ++last;
676 curfile = last;
677 if (pflag) {
679 * Make it compatible with possible future
680 * versions expecting microseconds.
682 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
683 (u_long) (stb.st_mtime < 0 ? 0 : stb.st_mtime),
684 (u_long) (stb.st_atime < 0 ? 0 : stb.st_atime));
685 if (verbose_mode) {
686 fprintf(stderr, "File mtime %ld atime %ld\n",
687 (long)stb.st_mtime, (long)stb.st_atime);
688 fprintf(stderr, "Sending file timestamps: %s",
689 buf);
691 (void) atomicio(vwrite, remout, buf, strlen(buf));
692 if (response() < 0)
693 goto next;
695 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
696 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
697 (u_int) (stb.st_mode & FILEMODEMASK),
698 (long long)stb.st_size, last);
699 if (verbose_mode) {
700 fprintf(stderr, "Sending file modes: %s", buf);
702 (void) atomicio(vwrite, remout, buf, strlen(buf));
703 if (response() < 0)
704 goto next;
705 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
706 next: if (fd != -1) {
707 (void) close(fd);
708 fd = -1;
710 continue;
712 if (showprogress)
713 start_progress_meter(curfile, stb.st_size, &statbytes);
714 set_nonblock(remout);
715 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
716 amt = bp->cnt;
717 if (i + (off_t)amt > stb.st_size)
718 amt = stb.st_size - i;
719 if (!haderr) {
720 if (atomicio(read, fd, bp->buf, amt) != amt)
721 haderr = errno;
723 /* Keep writing after error to retain sync */
724 if (haderr) {
725 (void)atomicio(vwrite, remout, bp->buf, amt);
726 continue;
728 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
729 &statbytes) != amt)
730 haderr = errno;
732 unset_nonblock(remout);
733 if (showprogress)
734 stop_progress_meter();
736 if (fd != -1) {
737 if (close(fd) < 0 && !haderr)
738 haderr = errno;
739 fd = -1;
741 if (!haderr)
742 (void) atomicio(vwrite, remout, "", 1);
743 else
744 run_err("%s: %s", name, strerror(haderr));
745 (void) response();
749 void
750 rsource(char *name, struct stat *statp)
752 DIR *dirp;
753 struct dirent *dp;
754 char *last, *vect[1], path[1100];
756 if (!(dirp = opendir(name))) {
757 run_err("%s: %s", name, strerror(errno));
758 return;
760 last = strrchr(name, '/');
761 if (last == 0)
762 last = name;
763 else
764 last++;
765 if (pflag) {
766 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
767 (u_long) statp->st_mtime,
768 (u_long) statp->st_atime);
769 (void) atomicio(vwrite, remout, path, strlen(path));
770 if (response() < 0) {
771 closedir(dirp);
772 return;
775 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
776 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
777 if (verbose_mode)
778 fprintf(stderr, "Entering directory: %s", path);
779 (void) atomicio(vwrite, remout, path, strlen(path));
780 if (response() < 0) {
781 closedir(dirp);
782 return;
784 while ((dp = readdir(dirp)) != NULL) {
785 if (dp->d_ino == 0)
786 continue;
787 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
788 continue;
789 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
790 run_err("%s/%s: name too long", name, dp->d_name);
791 continue;
793 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
794 vect[0] = path;
795 source(1, vect);
797 (void) closedir(dirp);
798 (void) atomicio(vwrite, remout, "E\n", 2);
799 (void) response();
802 void
803 sink(int argc, char **argv)
805 static BUF buffer;
806 struct stat stb;
807 enum {
808 YES, NO, DISPLAYED
809 } wrerr;
810 BUF *bp;
811 off_t i;
812 size_t j, count;
813 int amt, exists, first, ofd;
814 mode_t mode, omode, mask;
815 off_t size, statbytes;
816 int setimes, targisdir, wrerrno = 0;
817 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
818 struct timeval tv[2];
820 #define atime tv[0]
821 #define mtime tv[1]
822 #define SCREWUP(str) { why = str; goto screwup; }
824 setimes = targisdir = 0;
825 mask = umask(0);
826 if (!pflag)
827 (void) umask(mask);
828 if (argc != 1) {
829 run_err("ambiguous target");
830 exit(1);
832 targ = *argv;
833 if (targetshouldbedirectory)
834 verifydir(targ);
836 (void) atomicio(vwrite, remout, "", 1);
837 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
838 targisdir = 1;
839 for (first = 1;; first = 0) {
840 cp = buf;
841 if (atomicio(read, remin, cp, 1) != 1)
842 return;
843 if (*cp++ == '\n')
844 SCREWUP("unexpected <newline>");
845 do {
846 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
847 SCREWUP("lost connection");
848 *cp++ = ch;
849 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
850 *cp = 0;
851 if (verbose_mode)
852 fprintf(stderr, "Sink: %s", buf);
854 if (buf[0] == '\01' || buf[0] == '\02') {
855 if (iamremote == 0)
856 (void) atomicio(vwrite, STDERR_FILENO,
857 buf + 1, strlen(buf + 1));
858 if (buf[0] == '\02')
859 exit(1);
860 ++errs;
861 continue;
863 if (buf[0] == 'E') {
864 (void) atomicio(vwrite, remout, "", 1);
865 return;
867 if (ch == '\n')
868 *--cp = 0;
870 cp = buf;
871 if (*cp == 'T') {
872 setimes++;
873 cp++;
874 mtime.tv_sec = strtol(cp, &cp, 10);
875 if (!cp || *cp++ != ' ')
876 SCREWUP("mtime.sec not delimited");
877 mtime.tv_usec = strtol(cp, &cp, 10);
878 if (!cp || *cp++ != ' ')
879 SCREWUP("mtime.usec not delimited");
880 atime.tv_sec = strtol(cp, &cp, 10);
881 if (!cp || *cp++ != ' ')
882 SCREWUP("atime.sec not delimited");
883 atime.tv_usec = strtol(cp, &cp, 10);
884 if (!cp || *cp++ != '\0')
885 SCREWUP("atime.usec not delimited");
886 (void) atomicio(vwrite, remout, "", 1);
887 continue;
889 if (*cp != 'C' && *cp != 'D') {
891 * Check for the case "rcp remote:foo\* local:bar".
892 * In this case, the line "No match." can be returned
893 * by the shell before the rcp command on the remote is
894 * executed so the ^Aerror_message convention isn't
895 * followed.
897 if (first) {
898 run_err("%s", cp);
899 exit(1);
901 SCREWUP("expected control record");
903 mode = 0;
904 for (++cp; cp < buf + 5; cp++) {
905 if (*cp < '0' || *cp > '7')
906 SCREWUP("bad mode");
907 mode = (mode << 3) | (*cp - '0');
909 if (*cp++ != ' ')
910 SCREWUP("mode not delimited");
912 for (size = 0; isdigit(*cp);)
913 size = size * 10 + (*cp++ - '0');
914 if (*cp++ != ' ')
915 SCREWUP("size not delimited");
916 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
917 run_err("error: unexpected filename: %s", cp);
918 exit(1);
920 if (targisdir) {
921 static char *namebuf;
922 static size_t cursize;
923 size_t need;
925 need = strlen(targ) + strlen(cp) + 250;
926 if (need > cursize) {
927 if (namebuf)
928 xfree(namebuf);
929 namebuf = xmalloc(need);
930 cursize = need;
932 (void) snprintf(namebuf, need, "%s%s%s", targ,
933 strcmp(targ, "/") ? "/" : "", cp);
934 np = namebuf;
935 } else
936 np = targ;
937 curfile = cp;
938 exists = stat(np, &stb) == 0;
939 if (buf[0] == 'D') {
940 int mod_flag = pflag;
941 if (!iamrecursive)
942 SCREWUP("received directory without -r");
943 if (exists) {
944 if (!S_ISDIR(stb.st_mode)) {
945 errno = ENOTDIR;
946 goto bad;
948 if (pflag)
949 (void) chmod(np, mode);
950 } else {
951 /* Handle copying from a read-only
952 directory */
953 mod_flag = 1;
954 if (mkdir(np, mode | S_IRWXU) < 0)
955 goto bad;
957 vect[0] = xstrdup(np);
958 sink(1, vect);
959 if (setimes) {
960 setimes = 0;
961 if (utimes(vect[0], tv) < 0)
962 run_err("%s: set times: %s",
963 vect[0], strerror(errno));
965 if (mod_flag)
966 (void) chmod(vect[0], mode);
967 if (vect[0])
968 xfree(vect[0]);
969 continue;
971 omode = mode;
972 mode |= S_IWRITE;
973 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
974 bad: run_err("%s: %s", np, strerror(errno));
975 continue;
977 (void) atomicio(vwrite, remout, "", 1);
978 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
979 (void) close(ofd);
980 continue;
982 cp = bp->buf;
983 wrerr = NO;
985 statbytes = 0;
986 if (showprogress)
987 start_progress_meter(curfile, size, &statbytes);
988 set_nonblock(remin);
989 for (count = i = 0; i < size; i += bp->cnt) {
990 amt = bp->cnt;
991 if (i + amt > size)
992 amt = size - i;
993 count += amt;
994 do {
995 j = atomicio6(read, remin, cp, amt,
996 scpio, &statbytes);
997 if (j == 0) {
998 run_err("%s", j != EPIPE ?
999 strerror(errno) :
1000 "dropped connection");
1001 exit(1);
1003 amt -= j;
1004 cp += j;
1005 } while (amt > 0);
1007 if (count == bp->cnt) {
1008 /* Keep reading so we stay sync'd up. */
1009 if (wrerr == NO) {
1010 if (atomicio(vwrite, ofd, bp->buf,
1011 count) != count) {
1012 wrerr = YES;
1013 wrerrno = errno;
1016 count = 0;
1017 cp = bp->buf;
1020 unset_nonblock(remin);
1021 if (showprogress)
1022 stop_progress_meter();
1023 if (count != 0 && wrerr == NO &&
1024 atomicio(vwrite, ofd, bp->buf, count) != count) {
1025 wrerr = YES;
1026 wrerrno = errno;
1028 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1029 ftruncate(ofd, size) != 0) {
1030 run_err("%s: truncate: %s", np, strerror(errno));
1031 wrerr = DISPLAYED;
1033 if (pflag) {
1034 if (exists || omode != mode)
1035 #ifdef HAVE_FCHMOD
1036 if (fchmod(ofd, omode)) {
1037 #else /* HAVE_FCHMOD */
1038 if (chmod(np, omode)) {
1039 #endif /* HAVE_FCHMOD */
1040 run_err("%s: set mode: %s",
1041 np, strerror(errno));
1042 wrerr = DISPLAYED;
1044 } else {
1045 if (!exists && omode != mode)
1046 #ifdef HAVE_FCHMOD
1047 if (fchmod(ofd, omode & ~mask)) {
1048 #else /* HAVE_FCHMOD */
1049 if (chmod(np, omode & ~mask)) {
1050 #endif /* HAVE_FCHMOD */
1051 run_err("%s: set mode: %s",
1052 np, strerror(errno));
1053 wrerr = DISPLAYED;
1056 if (close(ofd) == -1) {
1057 wrerr = YES;
1058 wrerrno = errno;
1060 (void) response();
1061 if (setimes && wrerr == NO) {
1062 setimes = 0;
1063 if (utimes(np, tv) < 0) {
1064 run_err("%s: set times: %s",
1065 np, strerror(errno));
1066 wrerr = DISPLAYED;
1069 switch (wrerr) {
1070 case YES:
1071 run_err("%s: %s", np, strerror(wrerrno));
1072 break;
1073 case NO:
1074 (void) atomicio(vwrite, remout, "", 1);
1075 break;
1076 case DISPLAYED:
1077 break;
1080 screwup:
1081 run_err("protocol error: %s", why);
1082 exit(1);
1086 response(void)
1088 char ch, *cp, resp, rbuf[2048];
1090 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1091 lostconn(0);
1093 cp = rbuf;
1094 switch (resp) {
1095 case 0: /* ok */
1096 return (0);
1097 default:
1098 *cp++ = resp;
1099 /* FALLTHROUGH */
1100 case 1: /* error, followed by error msg */
1101 case 2: /* fatal error, "" */
1102 do {
1103 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1104 lostconn(0);
1105 *cp++ = ch;
1106 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1108 if (!iamremote)
1109 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1110 ++errs;
1111 if (resp == 1)
1112 return (-1);
1113 exit(1);
1115 /* NOTREACHED */
1118 void
1119 usage(void)
1121 (void) fprintf(stderr,
1122 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1123 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1124 " [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1125 exit(1);
1128 void
1129 run_err(const char *fmt,...)
1131 static FILE *fp;
1132 va_list ap;
1134 ++errs;
1135 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1136 (void) fprintf(fp, "%c", 0x01);
1137 (void) fprintf(fp, "scp: ");
1138 va_start(ap, fmt);
1139 (void) vfprintf(fp, fmt, ap);
1140 va_end(ap);
1141 (void) fprintf(fp, "\n");
1142 (void) fflush(fp);
1145 if (!iamremote) {
1146 va_start(ap, fmt);
1147 vfprintf(stderr, fmt, ap);
1148 va_end(ap);
1149 fprintf(stderr, "\n");
1153 void
1154 verifydir(char *cp)
1156 struct stat stb;
1158 if (!stat(cp, &stb)) {
1159 if (S_ISDIR(stb.st_mode))
1160 return;
1161 errno = ENOTDIR;
1163 run_err("%s: %s", cp, strerror(errno));
1164 killchild(0);
1168 okname(char *cp0)
1170 int c;
1171 char *cp;
1173 cp = cp0;
1174 do {
1175 c = (int)*cp;
1176 if (c & 0200)
1177 goto bad;
1178 if (!isalpha(c) && !isdigit(c)) {
1179 switch (c) {
1180 case '\'':
1181 case '"':
1182 case '`':
1183 case ' ':
1184 case '#':
1185 goto bad;
1186 default:
1187 break;
1190 } while (*++cp);
1191 return (1);
1193 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1194 return (0);
1197 BUF *
1198 allocbuf(BUF *bp, int fd, int blksize)
1200 size_t size;
1201 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1202 struct stat stb;
1204 if (fstat(fd, &stb) < 0) {
1205 run_err("fstat: %s", strerror(errno));
1206 return (0);
1208 size = roundup(stb.st_blksize, blksize);
1209 if (size == 0)
1210 size = blksize;
1211 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1212 size = blksize;
1213 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1214 if (bp->cnt >= size)
1215 return (bp);
1216 if (bp->buf == NULL)
1217 bp->buf = xmalloc(size);
1218 else
1219 bp->buf = xrealloc(bp->buf, 1, size);
1220 memset(bp->buf, 0, size);
1221 bp->cnt = size;
1222 return (bp);
1225 void
1226 lostconn(int signo)
1228 if (!iamremote)
1229 write(STDERR_FILENO, "lost connection\n", 16);
1230 if (signo)
1231 _exit(1);
1232 else
1233 exit(1);