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
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.
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
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
74 RCSID("$OpenBSD: scp.c,v 1.113 2003/11/23 23:21:21 djm Exp $");
78 #include "pathnames.h"
81 #include "progressmeter.h"
83 #ifdef HAVE___PROGNAME
84 extern char *__progname;
91 /* Struct for addargs */
97 /* Name of current file being transferred. */
100 /* This is set to non-zero to enable verbose mode. */
101 int verbose_mode = 0;
103 /* This is set to zero if the progressmeter is not desired. */
104 int showprogress = 1;
106 /* This is the program to execute for the secured connection. ("ssh" or -S) */
107 char *ssh_program = _PATH_SSH_PROGRAM;
109 /* This is used to store the pid of ssh_program */
110 pid_t do_cmd_pid = -1;
116 kill(do_cmd_pid, signo);
122 * This function executes the given command as the specified user on the
123 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
124 * assigns the input and output file descriptors on success.
128 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
130 int pin[2], pout[2], reserved[2];
134 "Executing: program %s host %s, user %s, command %s\n",
136 remuser ? remuser : "(unspecified)", cmd);
139 * Reserve two descriptors so that the real pipes won't get
140 * descriptors 0 and 1 because that will screw up dup2 below.
144 /* Create a socket pair for communicating with ssh. */
146 fatal("pipe: %s", strerror(errno));
148 fatal("pipe: %s", strerror(errno));
150 /* Free the reserved descriptors. */
154 /* Fork a child to execute the command on the remote host using ssh. */
156 if (do_cmd_pid == 0) {
165 args.list[0] = ssh_program;
167 addargs(&args, "-l%s", remuser);
168 addargs(&args, "%s", host);
169 addargs(&args, "%s", cmd);
171 execvp(ssh_program, args.list);
174 } else if (do_cmd_pid == -1) {
175 fatal("fork: %s", strerror(errno));
177 /* Parent. Close the other side, and return the local side. */
182 signal(SIGTERM, killchild);
183 signal(SIGINT, killchild);
184 signal(SIGHUP, killchild);
193 BUF *allocbuf(BUF *, int, int);
197 void run_err(const char *,...);
198 void verifydir(char *);
202 int errs, remin, remout;
203 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
206 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
209 void rsource(char *, struct stat *);
210 void sink(int, char *[]);
211 void source(int, char *[]);
212 void tolocal(int, char *[]);
213 void toremote(char *, int, char *[]);
217 main(int argc, char **argv)
219 int ch, fflag, tflag, status;
225 __progname = ssh_get_progname(argv[0]);
228 addargs(&args, "ssh"); /* overwritten with ssh_program */
229 addargs(&args, "-x");
230 addargs(&args, "-oForwardAgent no");
231 addargs(&args, "-oClearAllForwardings yes");
234 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
236 /* User-visible flags. */
242 addargs(&args, "-%c", ch);
248 addargs(&args, "-%c%s", ch, optarg);
251 addargs(&args, "-p%s", optarg);
254 addargs(&args, "-oBatchmode yes");
257 speed = strtod(optarg, &endp);
258 if (speed <= 0 || *endp != '\0')
260 limit_rate = speed * 1024;
269 ssh_program = xstrdup(optarg);
272 addargs(&args, "-v");
276 addargs(&args, "-q");
280 /* Server options. */
282 targetshouldbedirectory = 1;
284 case 'f': /* "from" */
292 setmode(0, O_BINARY);
301 if ((pwd = getpwuid(userid = getuid())) == NULL)
302 fatal("unknown user %u", (u_int) userid);
304 if (!isatty(STDERR_FILENO))
307 remin = STDIN_FILENO;
308 remout = STDOUT_FILENO;
311 /* Follow "protocol", send data. */
324 targetshouldbedirectory = 1;
328 /* Command to be executed on remote system using "ssh". */
329 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
330 verbose_mode ? " -v" : "",
331 iamrecursive ? " -r" : "", pflag ? " -p" : "",
332 targetshouldbedirectory ? " -d" : "");
334 (void) signal(SIGPIPE, lostconn);
336 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
337 toremote(targ, argc, argv);
339 tolocal(argc, argv); /* Dest is local host. */
340 if (targetshouldbedirectory)
341 verifydir(argv[argc - 1]);
344 * Finally check the exit status of the ssh process, if one was forked
345 * and no error has occured yet
347 if (do_cmd_pid != -1 && errs == 0) {
351 (void) close(remout);
352 if (waitpid(do_cmd_pid, &status, 0) == -1)
355 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
363 toremote(char *targ, int argc, char **argv)
366 char *bp, *host, *src, *suser, *thost, *tuser;
372 if ((thost = strrchr(argv[argc - 1], '@'))) {
375 tuser = argv[argc - 1];
379 thost = argv[argc - 1];
383 for (i = 0; i < argc - 1; i++) {
384 src = colon(argv[i]);
385 if (src) { /* remote to remote */
386 static char *ssh_options =
387 "-x -o'ClearAllForwardings yes'";
391 host = strrchr(argv[i], '@');
392 len = strlen(ssh_program) + strlen(argv[i]) +
393 strlen(src) + (tuser ? strlen(tuser) : 0) +
394 strlen(thost) + strlen(targ) +
395 strlen(ssh_options) + CMDNEEDS + 20;
399 host = cleanhostname(host);
402 suser = pwd->pw_name;
403 else if (!okname(suser)) {
407 if (tuser && !okname(tuser)) {
413 "-l %s %s %s %s '%s%s%s:%s'",
414 ssh_program, verbose_mode ? " -v" : "",
415 ssh_options, suser, host, cmd, src,
416 tuser ? tuser : "", tuser ? "@" : "",
419 host = cleanhostname(argv[i]);
421 "exec %s%s %s -n %s "
423 ssh_program, verbose_mode ? " -v" : "",
424 ssh_options, host, cmd, src,
425 tuser ? tuser : "", tuser ? "@" : "",
429 fprintf(stderr, "Executing: %s\n", bp);
433 } else { /* local to remote */
435 len = strlen(targ) + CMDNEEDS + 20;
437 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
438 host = cleanhostname(thost);
439 if (do_cmd(host, tuser, bp, &remin,
452 tolocal(int argc, char **argv)
455 char *bp, *host, *src, *suser;
457 for (i = 0; i < argc - 1; i++) {
458 if (!(src = colon(argv[i]))) { /* Local to local. */
459 len = strlen(_PATH_CP) + strlen(argv[i]) +
460 strlen(argv[argc - 1]) + 20;
462 (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
463 iamrecursive ? " -r" : "", pflag ? " -p" : "",
464 argv[i], argv[argc - 1]);
466 fprintf(stderr, "Executing: %s\n", bp);
475 if ((host = strrchr(argv[i], '@')) == NULL) {
482 suser = pwd->pw_name;
484 host = cleanhostname(host);
485 len = strlen(src) + CMDNEEDS + 20;
487 (void) snprintf(bp, len, "%s -f %s", cmd, src);
488 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
494 sink(1, argv + argc - 1);
501 source(int argc, char **argv)
506 off_t i, amt, result, statbytes;
507 int fd, haderr, indx;
508 char *last, *name, buf[2048];
511 for (indx = 0; indx < argc; ++indx) {
515 while (len > 1 && name[len-1] == '/')
517 if (strchr(name, '\n') != NULL) {
518 run_err("%s: skipping, filename contains a newline",
522 if ((fd = open(name, O_RDONLY, 0)) < 0)
524 if (fstat(fd, &stb) < 0) {
525 syserr: run_err("%s: %s", name, strerror(errno));
528 switch (stb.st_mode & S_IFMT) {
538 run_err("%s: not a regular file", name);
541 if ((last = strrchr(name, '/')) == NULL)
548 * Make it compatible with possible future
549 * versions expecting microseconds.
551 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
552 (u_long) stb.st_mtime,
553 (u_long) stb.st_atime);
554 (void) atomicio(vwrite, remout, buf, strlen(buf));
558 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
559 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
560 (u_int) (stb.st_mode & FILEMODEMASK),
561 (int64_t)stb.st_size, last);
563 fprintf(stderr, "Sending file modes: %s", buf);
565 (void) atomicio(vwrite, remout, buf, strlen(buf));
568 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
569 next: (void) close(fd);
573 start_progress_meter(curfile, stb.st_size, &statbytes);
574 /* Keep writing after an error so that we stay sync'd up. */
575 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
577 if (i + amt > stb.st_size)
578 amt = stb.st_size - i;
580 result = atomicio(read, fd, bp->buf, amt);
582 haderr = result >= 0 ? EIO : errno;
585 (void) atomicio(vwrite, remout, bp->buf, amt);
587 result = atomicio(vwrite, remout, bp->buf, amt);
589 haderr = result >= 0 ? EIO : errno;
596 stop_progress_meter();
598 if (close(fd) < 0 && !haderr)
601 (void) atomicio(vwrite, remout, "", 1);
603 run_err("%s: %s", name, strerror(haderr));
609 rsource(char *name, struct stat *statp)
613 char *last, *vect[1], path[1100];
615 if (!(dirp = opendir(name))) {
616 run_err("%s: %s", name, strerror(errno));
619 last = strrchr(name, '/');
625 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
626 (u_long) statp->st_mtime,
627 (u_long) statp->st_atime);
628 (void) atomicio(vwrite, remout, path, strlen(path));
629 if (response() < 0) {
634 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
635 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
637 fprintf(stderr, "Entering directory: %s", path);
638 (void) atomicio(vwrite, remout, path, strlen(path));
639 if (response() < 0) {
643 while ((dp = readdir(dirp)) != NULL) {
646 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
648 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
649 run_err("%s/%s: name too long", name, dp->d_name);
652 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
656 (void) closedir(dirp);
657 (void) atomicio(vwrite, remout, "E\n", 2);
664 static struct timeval bwstart, bwend;
665 static int lamt, thresh = 16384;
667 struct timespec ts, rm;
669 if (!timerisset(&bwstart)) {
670 gettimeofday(&bwstart, NULL);
678 gettimeofday(&bwend, NULL);
679 timersub(&bwend, &bwstart, &bwend);
680 if (!timerisset(&bwend))
684 wait = (double)1000000L * lamt / limit_rate;
686 bwstart.tv_sec = wait / 1000000L;
687 bwstart.tv_usec = wait % 1000000L;
689 if (timercmp(&bwstart, &bwend, >)) {
690 timersub(&bwstart, &bwend, &bwend);
692 /* Adjust the wait time */
697 } else if (bwend.tv_usec < 100) {
703 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
704 while (nanosleep(&ts, &rm) == -1) {
712 gettimeofday(&bwstart, NULL);
716 sink(int argc, char **argv)
725 int amt, count, exists, first, mask, mode, ofd, omode;
726 off_t size, statbytes;
727 int setimes, targisdir, wrerrno = 0;
728 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
729 struct timeval tv[2];
733 #define SCREWUP(str) do { why = str; goto screwup; } while (0)
735 setimes = targisdir = 0;
740 run_err("ambiguous target");
744 if (targetshouldbedirectory)
747 (void) atomicio(vwrite, remout, "", 1);
748 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
750 for (first = 1;; first = 0) {
752 if (atomicio(read, remin, cp, 1) <= 0)
755 SCREWUP("unexpected <newline>");
757 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
758 SCREWUP("lost connection");
760 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
763 if (buf[0] == '\01' || buf[0] == '\02') {
765 (void) atomicio(vwrite, STDERR_FILENO,
766 buf + 1, strlen(buf + 1));
773 (void) atomicio(vwrite, remout, "", 1);
783 mtime.tv_sec = strtol(cp, &cp, 10);
784 if (!cp || *cp++ != ' ')
785 SCREWUP("mtime.sec not delimited");
786 mtime.tv_usec = strtol(cp, &cp, 10);
787 if (!cp || *cp++ != ' ')
788 SCREWUP("mtime.usec not delimited");
789 atime.tv_sec = strtol(cp, &cp, 10);
790 if (!cp || *cp++ != ' ')
791 SCREWUP("atime.sec not delimited");
792 atime.tv_usec = strtol(cp, &cp, 10);
793 if (!cp || *cp++ != '\0')
794 SCREWUP("atime.usec not delimited");
795 (void) atomicio(vwrite, remout, "", 1);
798 if (*cp != 'C' && *cp != 'D') {
800 * Check for the case "rcp remote:foo\* local:bar".
801 * In this case, the line "No match." can be returned
802 * by the shell before the rcp command on the remote is
803 * executed so the ^Aerror_message convention isn't
810 SCREWUP("expected control record");
813 for (++cp; cp < buf + 5; cp++) {
814 if (*cp < '0' || *cp > '7')
816 mode = (mode << 3) | (*cp - '0');
819 SCREWUP("mode not delimited");
821 for (size = 0; isdigit(*cp);)
822 size = size * 10 + (*cp++ - '0');
824 SCREWUP("size not delimited");
826 static char *namebuf;
830 need = strlen(targ) + strlen(cp) + 250;
831 if (need > cursize) {
834 namebuf = xmalloc(need);
837 (void) snprintf(namebuf, need, "%s%s%s", targ,
838 strcmp(targ, "/") ? "/" : "", cp);
843 exists = stat(np, &stb) == 0;
845 int mod_flag = pflag;
847 if (!S_ISDIR(stb.st_mode)) {
852 (void) chmod(np, mode);
854 /* Handle copying from a read-only
857 if (mkdir(np, mode | S_IRWXU) < 0)
860 vect[0] = xstrdup(np);
864 if (utimes(vect[0], tv) < 0)
865 run_err("%s: set times: %s",
866 vect[0], strerror(errno));
869 (void) chmod(vect[0], mode);
876 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
877 bad: run_err("%s: %s", np, strerror(errno));
880 (void) atomicio(vwrite, remout, "", 1);
881 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
890 start_progress_meter(curfile, size, &statbytes);
891 for (count = i = 0; i < size; i += 4096) {
897 j = read(remin, cp, amt);
898 if (j == -1 && (errno == EINTR ||
902 run_err("%s", j ? strerror(errno) :
903 "dropped connection");
914 if (count == bp->cnt) {
915 /* Keep reading so we stay sync'd up. */
917 j = atomicio(vwrite, ofd, bp->buf, count);
920 wrerrno = j >= 0 ? EIO : errno;
928 stop_progress_meter();
929 if (count != 0 && wrerr == NO &&
930 (j = atomicio(vwrite, ofd, bp->buf, count)) != count) {
932 wrerrno = j >= 0 ? EIO : errno;
934 if (wrerr == NO && ftruncate(ofd, size) != 0) {
935 run_err("%s: truncate: %s", np, strerror(errno));
939 if (exists || omode != mode)
941 if (fchmod(ofd, omode))
942 #else /* HAVE_FCHMOD */
943 if (chmod(np, omode))
944 #endif /* HAVE_FCHMOD */
945 run_err("%s: set mode: %s",
946 np, strerror(errno));
948 if (!exists && omode != mode)
950 if (fchmod(ofd, omode & ~mask))
951 #else /* HAVE_FCHMOD */
952 if (chmod(np, omode & ~mask))
953 #endif /* HAVE_FCHMOD */
954 run_err("%s: set mode: %s",
955 np, strerror(errno));
957 if (close(ofd) == -1) {
962 if (setimes && wrerr == NO) {
964 if (utimes(np, tv) < 0) {
965 run_err("%s: set times: %s",
966 np, strerror(errno));
972 run_err("%s: %s", np, strerror(wrerrno));
975 (void) atomicio(vwrite, remout, "", 1);
982 run_err("protocol error: %s", why);
989 char ch, *cp, resp, rbuf[2048];
991 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1001 case 1: /* error, followed by error msg */
1002 case 2: /* fatal error, "" */
1004 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1007 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1010 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1022 (void) fprintf(stderr,
1023 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1024 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1025 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1030 run_err(const char *fmt,...)
1036 if (fp == NULL && !(fp = fdopen(remout, "w")))
1038 (void) fprintf(fp, "%c", 0x01);
1039 (void) fprintf(fp, "scp: ");
1041 (void) vfprintf(fp, fmt, ap);
1043 (void) fprintf(fp, "\n");
1048 vfprintf(stderr, fmt, ap);
1050 fprintf(stderr, "\n");
1059 if (!stat(cp, &stb)) {
1060 if (S_ISDIR(stb.st_mode))
1064 run_err("%s: %s", cp, strerror(errno));
1079 if (!isalpha(c) && !isdigit(c)) {
1094 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1099 allocbuf(BUF *bp, int fd, int blksize)
1102 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1105 if (fstat(fd, &stb) < 0) {
1106 run_err("fstat: %s", strerror(errno));
1109 size = roundup(stb.st_blksize, blksize);
1112 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1114 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1115 if (bp->cnt >= size)
1117 if (bp->buf == NULL)
1118 bp->buf = xmalloc(size);
1120 bp->buf = xrealloc(bp->buf, size);
1121 memset(bp->buf, 0, size);
1130 write(STDERR_FILENO, "lost connection\n", 16);