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.104 2003/06/04 12:18:49 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 */
113 * This function executes the given command as the specified user on the
114 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
115 * assigns the input and output file descriptors on success.
119 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
121 int pin[2], pout[2], reserved[2];
125 "Executing: program %s host %s, user %s, command %s\n",
127 remuser ? remuser : "(unspecified)", cmd);
130 * Reserve two descriptors so that the real pipes won't get
131 * descriptors 0 and 1 because that will screw up dup2 below.
135 /* Create a socket pair for communicating with ssh. */
137 fatal("pipe: %s", strerror(errno));
139 fatal("pipe: %s", strerror(errno));
141 /* Free the reserved descriptors. */
145 /* For a child to execute the command on the remote host using ssh. */
147 if (do_cmd_pid == 0) {
156 args.list[0] = ssh_program;
158 addargs(&args, "-l%s", remuser);
159 addargs(&args, "%s", host);
160 addargs(&args, "%s", cmd);
162 execvp(ssh_program, args.list);
165 } else if (do_cmd_pid == -1) {
166 fatal("fork: %s", strerror(errno));
168 /* Parent. Close the other side, and return the local side. */
181 BUF *allocbuf(BUF *, int, int);
185 void run_err(const char *,...);
186 void verifydir(char *);
190 int errs, remin, remout;
191 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
194 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
197 void rsource(char *, struct stat *);
198 void sink(int, char *[]);
199 void source(int, char *[]);
200 void tolocal(int, char *[]);
201 void toremote(char *, int, char *[]);
205 main(int argc, char **argv)
207 int ch, fflag, tflag, status;
213 __progname = get_progname(argv[0]);
216 addargs(&args, "ssh"); /* overwritten with ssh_program */
217 addargs(&args, "-x");
218 addargs(&args, "-oForwardAgent no");
219 addargs(&args, "-oClearAllForwardings yes");
222 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
224 /* User-visible flags. */
230 addargs(&args, "-%c", ch);
236 addargs(&args, "-%c%s", ch, optarg);
239 addargs(&args, "-p%s", optarg);
242 addargs(&args, "-oBatchmode yes");
245 speed = strtod(optarg, &endp);
246 if (speed <= 0 || *endp != '\0')
248 limitbw = speed * 1024;
257 ssh_program = xstrdup(optarg);
260 addargs(&args, "-v");
267 /* Server options. */
269 targetshouldbedirectory = 1;
271 case 'f': /* "from" */
279 setmode(0, O_BINARY);
288 if ((pwd = getpwuid(userid = getuid())) == NULL)
289 fatal("unknown user %d", (int) userid);
291 if (!isatty(STDERR_FILENO))
294 remin = STDIN_FILENO;
295 remout = STDOUT_FILENO;
298 /* Follow "protocol", send data. */
311 targetshouldbedirectory = 1;
315 /* Command to be executed on remote system using "ssh". */
316 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
317 verbose_mode ? " -v" : "",
318 iamrecursive ? " -r" : "", pflag ? " -p" : "",
319 targetshouldbedirectory ? " -d" : "");
321 (void) signal(SIGPIPE, lostconn);
323 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
324 toremote(targ, argc, argv);
326 tolocal(argc, argv); /* Dest is local host. */
327 if (targetshouldbedirectory)
328 verifydir(argv[argc - 1]);
331 * Finally check the exit status of the ssh process, if one was forked
332 * and no error has occured yet
334 if (do_cmd_pid != -1 && errs == 0) {
338 (void) close(remout);
339 if (waitpid(do_cmd_pid, &status, 0) == -1)
342 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
350 toremote(char *targ, int argc, char **argv)
353 char *bp, *host, *src, *suser, *thost, *tuser;
359 if ((thost = strrchr(argv[argc - 1], '@'))) {
362 tuser = argv[argc - 1];
366 thost = argv[argc - 1];
370 for (i = 0; i < argc - 1; i++) {
371 src = colon(argv[i]);
372 if (src) { /* remote to remote */
373 static char *ssh_options =
374 "-x -o'ClearAllForwardings yes'";
378 host = strrchr(argv[i], '@');
379 len = strlen(ssh_program) + strlen(argv[i]) +
380 strlen(src) + (tuser ? strlen(tuser) : 0) +
381 strlen(thost) + strlen(targ) +
382 strlen(ssh_options) + CMDNEEDS + 20;
386 host = cleanhostname(host);
389 suser = pwd->pw_name;
390 else if (!okname(suser)) {
394 if (tuser && !okname(tuser)) {
400 "-l %s %s %s %s '%s%s%s:%s'",
401 ssh_program, verbose_mode ? " -v" : "",
402 ssh_options, suser, host, cmd, src,
403 tuser ? tuser : "", tuser ? "@" : "",
406 host = cleanhostname(argv[i]);
408 "exec %s%s %s -n %s "
410 ssh_program, verbose_mode ? " -v" : "",
411 ssh_options, host, cmd, src,
412 tuser ? tuser : "", tuser ? "@" : "",
416 fprintf(stderr, "Executing: %s\n", bp);
419 } else { /* local to remote */
421 len = strlen(targ) + CMDNEEDS + 20;
423 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
424 host = cleanhostname(thost);
425 if (do_cmd(host, tuser, bp, &remin,
438 tolocal(int argc, char **argv)
441 char *bp, *host, *src, *suser;
443 for (i = 0; i < argc - 1; i++) {
444 if (!(src = colon(argv[i]))) { /* Local to local. */
445 len = strlen(_PATH_CP) + strlen(argv[i]) +
446 strlen(argv[argc - 1]) + 20;
448 (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
449 iamrecursive ? " -r" : "", pflag ? " -p" : "",
450 argv[i], argv[argc - 1]);
452 fprintf(stderr, "Executing: %s\n", bp);
461 if ((host = strrchr(argv[i], '@')) == NULL) {
468 suser = pwd->pw_name;
470 host = cleanhostname(host);
471 len = strlen(src) + CMDNEEDS + 20;
473 (void) snprintf(bp, len, "%s -f %s", cmd, src);
474 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
480 sink(1, argv + argc - 1);
487 source(int argc, char **argv)
492 off_t i, amt, result, statbytes;
493 int fd, haderr, indx;
494 char *last, *name, buf[2048];
497 for (indx = 0; indx < argc; ++indx) {
501 while (len > 1 && name[len-1] == '/')
503 if (strchr(name, '\n') != NULL) {
504 run_err("%s: skipping, filename contains a newline",
508 if ((fd = open(name, O_RDONLY, 0)) < 0)
510 if (fstat(fd, &stb) < 0) {
511 syserr: run_err("%s: %s", name, strerror(errno));
514 switch (stb.st_mode & S_IFMT) {
524 run_err("%s: not a regular file", name);
527 if ((last = strrchr(name, '/')) == NULL)
534 * Make it compatible with possible future
535 * versions expecting microseconds.
537 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
538 (u_long) stb.st_mtime,
539 (u_long) stb.st_atime);
540 (void) atomicio(write, remout, buf, strlen(buf));
544 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
545 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
546 (u_int) (stb.st_mode & FILEMODEMASK),
547 (int64_t)stb.st_size, last);
549 fprintf(stderr, "Sending file modes: %s", buf);
551 (void) atomicio(write, remout, buf, strlen(buf));
554 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
555 next: (void) close(fd);
559 start_progress_meter(curfile, stb.st_size, &statbytes);
560 /* Keep writing after an error so that we stay sync'd up. */
561 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
563 if (i + amt > stb.st_size)
564 amt = stb.st_size - i;
566 result = atomicio(read, fd, bp->buf, amt);
568 haderr = result >= 0 ? EIO : errno;
571 (void) atomicio(write, remout, bp->buf, amt);
573 result = atomicio(write, remout, bp->buf, amt);
575 haderr = result >= 0 ? EIO : errno;
582 stop_progress_meter();
584 if (close(fd) < 0 && !haderr)
587 (void) atomicio(write, remout, "", 1);
589 run_err("%s: %s", name, strerror(haderr));
595 rsource(char *name, struct stat *statp)
599 char *last, *vect[1], path[1100];
601 if (!(dirp = opendir(name))) {
602 run_err("%s: %s", name, strerror(errno));
605 last = strrchr(name, '/');
611 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
612 (u_long) statp->st_mtime,
613 (u_long) statp->st_atime);
614 (void) atomicio(write, remout, path, strlen(path));
615 if (response() < 0) {
620 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
621 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
623 fprintf(stderr, "Entering directory: %s", path);
624 (void) atomicio(write, remout, path, strlen(path));
625 if (response() < 0) {
629 while ((dp = readdir(dirp)) != NULL) {
632 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
634 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
635 run_err("%s/%s: name too long", name, dp->d_name);
638 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
642 (void) closedir(dirp);
643 (void) atomicio(write, remout, "E\n", 2);
650 static struct timeval bwstart, bwend;
651 static int lamt, thresh = 16384;
653 struct timespec ts, rm;
655 if (!timerisset(&bwstart)) {
656 gettimeofday(&bwstart, NULL);
664 gettimeofday(&bwend, NULL);
665 timersub(&bwend, &bwstart, &bwend);
666 if (!timerisset(&bwend))
670 wait = (double)1000000L * lamt / limitbw;
672 bwstart.tv_sec = wait / 1000000L;
673 bwstart.tv_usec = wait % 1000000L;
675 if (timercmp(&bwstart, &bwend, >)) {
676 timersub(&bwstart, &bwend, &bwend);
678 /* Adjust the wait time */
683 } else if (bwend.tv_usec < 100) {
689 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
690 while (nanosleep(&ts, &rm) == -1) {
698 gettimeofday(&bwstart, NULL);
702 sink(int argc, char **argv)
711 int amt, count, exists, first, mask, mode, ofd, omode;
712 off_t size, statbytes;
713 int setimes, targisdir, wrerrno = 0;
714 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
715 struct timeval tv[2];
719 #define SCREWUP(str) do { why = str; goto screwup; } while (0)
721 setimes = targisdir = 0;
726 run_err("ambiguous target");
730 if (targetshouldbedirectory)
733 (void) atomicio(write, remout, "", 1);
734 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
736 for (first = 1;; first = 0) {
738 if (atomicio(read, remin, cp, 1) <= 0)
741 SCREWUP("unexpected <newline>");
743 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
744 SCREWUP("lost connection");
746 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
749 if (buf[0] == '\01' || buf[0] == '\02') {
751 (void) atomicio(write, STDERR_FILENO,
752 buf + 1, strlen(buf + 1));
759 (void) atomicio(write, remout, "", 1);
769 mtime.tv_sec = strtol(cp, &cp, 10);
770 if (!cp || *cp++ != ' ')
771 SCREWUP("mtime.sec not delimited");
772 mtime.tv_usec = strtol(cp, &cp, 10);
773 if (!cp || *cp++ != ' ')
774 SCREWUP("mtime.usec not delimited");
775 atime.tv_sec = strtol(cp, &cp, 10);
776 if (!cp || *cp++ != ' ')
777 SCREWUP("atime.sec not delimited");
778 atime.tv_usec = strtol(cp, &cp, 10);
779 if (!cp || *cp++ != '\0')
780 SCREWUP("atime.usec not delimited");
781 (void) atomicio(write, remout, "", 1);
784 if (*cp != 'C' && *cp != 'D') {
786 * Check for the case "rcp remote:foo\* local:bar".
787 * In this case, the line "No match." can be returned
788 * by the shell before the rcp command on the remote is
789 * executed so the ^Aerror_message convention isn't
796 SCREWUP("expected control record");
799 for (++cp; cp < buf + 5; cp++) {
800 if (*cp < '0' || *cp > '7')
802 mode = (mode << 3) | (*cp - '0');
805 SCREWUP("mode not delimited");
807 for (size = 0; isdigit(*cp);)
808 size = size * 10 + (*cp++ - '0');
810 SCREWUP("size not delimited");
812 static char *namebuf;
816 need = strlen(targ) + strlen(cp) + 250;
817 if (need > cursize) {
820 namebuf = xmalloc(need);
823 (void) snprintf(namebuf, need, "%s%s%s", targ,
824 strcmp(targ, "/") ? "/" : "", cp);
829 exists = stat(np, &stb) == 0;
831 int mod_flag = pflag;
833 if (!S_ISDIR(stb.st_mode)) {
838 (void) chmod(np, mode);
840 /* Handle copying from a read-only
843 if (mkdir(np, mode | S_IRWXU) < 0)
846 vect[0] = xstrdup(np);
850 if (utimes(vect[0], tv) < 0)
851 run_err("%s: set times: %s",
852 vect[0], strerror(errno));
855 (void) chmod(vect[0], mode);
862 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
863 bad: run_err("%s: %s", np, strerror(errno));
866 (void) atomicio(write, remout, "", 1);
867 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
876 start_progress_meter(curfile, size, &statbytes);
877 for (count = i = 0; i < size; i += 4096) {
883 j = read(remin, cp, amt);
884 if (j == -1 && (errno == EINTR ||
888 run_err("%s", j ? strerror(errno) :
889 "dropped connection");
900 if (count == bp->cnt) {
901 /* Keep reading so we stay sync'd up. */
903 j = atomicio(write, ofd, bp->buf, count);
906 wrerrno = j >= 0 ? EIO : errno;
914 stop_progress_meter();
915 if (count != 0 && wrerr == NO &&
916 (j = atomicio(write, ofd, bp->buf, count)) != count) {
918 wrerrno = j >= 0 ? EIO : errno;
920 if (wrerr == NO && ftruncate(ofd, size) != 0) {
921 run_err("%s: truncate: %s", np, strerror(errno));
925 if (exists || omode != mode)
927 if (fchmod(ofd, omode))
928 #else /* HAVE_FCHMOD */
929 if (chmod(np, omode))
930 #endif /* HAVE_FCHMOD */
931 run_err("%s: set mode: %s",
932 np, strerror(errno));
934 if (!exists && omode != mode)
936 if (fchmod(ofd, omode & ~mask))
937 #else /* HAVE_FCHMOD */
938 if (chmod(np, omode & ~mask))
939 #endif /* HAVE_FCHMOD */
940 run_err("%s: set mode: %s",
941 np, strerror(errno));
943 if (close(ofd) == -1) {
948 if (setimes && wrerr == NO) {
950 if (utimes(np, tv) < 0) {
951 run_err("%s: set times: %s",
952 np, strerror(errno));
958 run_err("%s: %s", np, strerror(wrerrno));
961 (void) atomicio(write, remout, "", 1);
968 run_err("protocol error: %s", why);
975 char ch, *cp, resp, rbuf[2048];
977 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
987 case 1: /* error, followed by error msg */
988 case 2: /* fatal error, "" */
990 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
993 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
996 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
1008 (void) fprintf(stderr,
1009 "usage: scp [-pqrvBC1246] [-F config] [-S program] [-P port]\n"
1010 " [-c cipher] [-i identity] [-l limit] [-o option]\n"
1011 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1016 run_err(const char *fmt,...)
1022 if (fp == NULL && !(fp = fdopen(remout, "w")))
1024 (void) fprintf(fp, "%c", 0x01);
1025 (void) fprintf(fp, "scp: ");
1027 (void) vfprintf(fp, fmt, ap);
1029 (void) fprintf(fp, "\n");
1034 vfprintf(stderr, fmt, ap);
1036 fprintf(stderr, "\n");
1045 if (!stat(cp, &stb)) {
1046 if (S_ISDIR(stb.st_mode))
1050 run_err("%s: %s", cp, strerror(errno));
1065 if (!isalpha(c) && !isdigit(c)) {
1080 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1085 allocbuf(BUF *bp, int fd, int blksize)
1088 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1091 if (fstat(fd, &stb) < 0) {
1092 run_err("fstat: %s", strerror(errno));
1095 size = roundup(stb.st_blksize, blksize);
1098 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1100 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1101 if (bp->cnt >= size)
1103 if (bp->buf == NULL)
1104 bp->buf = xmalloc(size);
1106 bp->buf = xrealloc(bp->buf, size);
1107 memset(bp->buf, 0, size);
1116 write(STDERR_FILENO, "lost connection\n", 16);