3 scp - secure remote copy. This is basically patched BSD rcp which uses ssh
4 to do the data transfer (instead of using rcmd).
6 NOTE: This version should NOT be suid root. (This uses ssh to do the transfer
7 and ssh has the necessary privileges.)
9 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
14 * Copyright (c) 1983, 1990, 1992, 1993, 1995
15 * The Regents of the University of California. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 * must display the following acknowledgement:
27 * This product includes software developed by the University of
28 * California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 * may be used to endorse or promote products derived from this software
31 * without specific prior written permission.
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
60 /* Visual statistics about files as they are transferred. */
61 void progressmeter(int);
63 /* Returns width of the terminal (for progress meter calculations). */
64 int getttywidth(void);
66 /* Time a transfer started. */
67 static struct timeval start;
69 /* Number of bytes of current file transferred so far. */
70 volatile unsigned long statbytes;
72 /* Total size of current file. */
75 /* Name of current file being transferred. */
78 /* This is set to non-zero to enable verbose mode. */
81 /* This is set to non-zero if compression is desired. */
84 /* This is set to zero if the progressmeter is not desired. */
87 /* This is set to non-zero if running in batch mode (that is, password
88 and passphrase queries are not allowed). */
91 /* This is set to the cipher type string if given on the command line. */
94 /* This is set to the RSA authentication identity file name if given on
96 char *identity = NULL;
98 /* This is the port to use in contacting the remote site (is non-NULL). */
101 /* This function executes the given command as the specified user on the given
102 host. This returns < 0 if execution fails, and >= 0 otherwise.
103 This assigns the input and output file descriptors on success. */
105 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
107 int pin[2], pout[2], reserved[2];
110 fprintf(stderr, "Executing: host %s, user %s, command %s\n",
111 host, remuser ? remuser : "(unspecified)", cmd);
113 /* Reserve two descriptors so that the real pipes won't get descriptors
114 0 and 1 because that will screw up dup2 below. */
117 /* Create a socket pair for communicating with ssh. */
119 fatal("pipe: %s", strerror(errno));
121 fatal("pipe: %s", strerror(errno));
123 /* Free the reserved descriptors. */
127 /* For a child to execute the command on the remote host using ssh. */
142 args[i++] = SSH_PROGRAM;
144 args[i++] = "-oFallBackToRsh no";
150 args[i++] = "-oBatchMode yes";
156 if (identity != NULL)
159 args[i++] = identity;
175 execvp(SSH_PROGRAM, args);
179 /* Parent. Close the other side, and return the local side. */
187 void fatal(const char *fmt, ...)
193 vsnprintf(buf, sizeof(buf), fmt, ap);
195 fprintf(stderr, "%s\n", buf);
199 /* This stuff used to be in BSD rcp extern.h. */
206 extern int iamremote;
208 BUF *allocbuf(BUF *, int, int);
213 void run_err(const char *, ...);
214 void verifydir(char *);
216 /* Stuff from BSD rcp.c continues. */
220 int errs, remin, remout;
221 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
224 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
227 void rsource(char *, struct stat *);
228 void sink(int, char *[]);
229 void source(int, char *[]);
230 void tolocal(int, char *[]);
231 void toremote(char *, int, char *[]);
239 int ch, fflag, tflag;
245 while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q")) != EOF)
246 switch(ch) { /* User-visible flags. */
256 /* Server options. */
258 targetshouldbedirectory = 1;
260 case 'f': /* "from" */
293 if ((pwd = getpwuid(userid = getuid())) == NULL)
294 fatal("unknown user %d", (int)userid);
296 if (! isatty(STDERR_FILENO))
299 remin = STDIN_FILENO;
300 remout = STDOUT_FILENO;
302 if (fflag) { /* Follow "protocol", send data. */
308 if (tflag) { /* Receive data. */
316 targetshouldbedirectory = 1;
319 /* Command to be executed on remote system using "ssh". */
320 (void)sprintf(cmd, "scp%s%s%s%s", verbose ? " -v" : "",
321 iamrecursive ? " -r" : "", pflag ? " -p" : "",
322 targetshouldbedirectory ? " -d" : "");
324 (void)signal(SIGPIPE, lostconn);
326 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
327 toremote(targ, argc, argv);
329 tolocal(argc, argv); /* Dest is local host. */
330 if (targetshouldbedirectory)
331 verifydir(argv[argc - 1]);
337 toremote(targ, argc, argv)
342 char *bp, *host, *src, *suser, *thost, *tuser;
348 if ((thost = strchr(argv[argc - 1], '@'))) {
351 tuser = argv[argc - 1];
354 else if (!okname(tuser))
357 thost = argv[argc - 1];
361 for (i = 0; i < argc - 1; i++) {
362 src = colon(argv[i]);
363 if (src) { /* remote to remote */
367 host = strchr(argv[i], '@');
368 len = strlen(SSH_PROGRAM) + strlen(argv[i]) +
369 strlen(src) + (tuser ? strlen(tuser) : 0) +
370 strlen(thost) + strlen(targ) + CMDNEEDS + 32;
376 suser = pwd->pw_name;
377 else if (!okname(suser))
380 "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
381 SSH_PROGRAM, verbose ? " -v" : "",
382 suser, host, cmd, src,
383 tuser ? tuser : "", tuser ? "@" : "",
387 "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
388 SSH_PROGRAM, verbose ? " -v" : "",
390 tuser ? tuser : "", tuser ? "@" : "",
393 fprintf(stderr, "Executing: %s\n", bp);
396 } else { /* local to remote */
398 len = strlen(targ) + CMDNEEDS + 20;
400 (void)sprintf(bp, "%s -t %s", cmd, targ);
402 if (do_cmd(host, tuser,
403 bp, &remin, &remout) < 0)
420 char *bp, *host, *src, *suser;
422 for (i = 0; i < argc - 1; i++) {
423 if (!(src = colon(argv[i]))) { /* Local to local. */
424 len = strlen(_PATH_CP) + strlen(argv[i]) +
425 strlen(argv[argc - 1]) + 20;
427 (void)sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
428 iamrecursive ? " -r" : "", pflag ? " -p" : "",
429 argv[i], argv[argc - 1]);
431 fprintf(stderr, "Executing: %s\n", bp);
440 if ((host = strchr(argv[i], '@')) == NULL) {
447 suser = pwd->pw_name;
448 else if (!okname(suser))
451 len = strlen(src) + CMDNEEDS + 20;
453 (void)sprintf(bp, "%s -f %s", cmd, src);
454 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
460 sink(1, argv + argc - 1);
475 int amt, fd, haderr, indx, result;
476 char *last, *name, buf[2048];
478 for (indx = 0; indx < argc; ++indx) {
481 if ((fd = open(name, O_RDONLY, 0)) < 0)
483 if (fstat(fd, &stb) < 0) {
484 syserr: run_err("%s: %s", name, strerror(errno));
487 switch (stb.st_mode & S_IFMT) {
497 run_err("%s: not a regular file", name);
500 if ((last = strrchr(name, '/')) == NULL)
507 * Make it compatible with possible future
508 * versions expecting microseconds.
510 (void)sprintf(buf, "T%lu 0 %lu 0\n",
511 (unsigned long)stb.st_mtime,
512 (unsigned long)stb.st_atime);
513 (void)write(remout, buf, strlen(buf));
517 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
518 (void)sprintf(buf, "C%04o %lu %s\n",
519 (unsigned int)(stb.st_mode & FILEMODEMASK),
520 (unsigned long)stb.st_size,
524 fprintf(stderr, "Sending file modes: %s", buf);
527 (void)write(remout, buf, strlen(buf));
530 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
531 next: (void)close(fd);
536 totalbytes = stb.st_size;
540 /* Keep writing after an error so that we stay sync'd up. */
541 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
543 if (i + amt > stb.st_size)
544 amt = stb.st_size - i;
546 result = read(fd, bp->buf, amt);
548 haderr = result >= 0 ? EIO : errno;
551 (void)write(remout, bp->buf, amt);
553 result = write(remout, bp->buf, amt);
555 haderr = result >= 0 ? EIO : errno;
562 if (close(fd) < 0 && !haderr)
565 (void)write(remout, "", 1);
567 run_err("%s: %s", name, strerror(haderr));
579 char *last, *vect[1], path[1100];
581 if (!(dirp = opendir(name))) {
582 run_err("%s: %s", name, strerror(errno));
585 last = strrchr(name, '/');
591 (void)sprintf(path, "T%lu 0 %lu 0\n",
592 (unsigned long)statp->st_mtime,
593 (unsigned long)statp->st_atime);
594 (void)write(remout, path, strlen(path));
595 if (response() < 0) {
601 "D%04o %d %.1024s\n", (unsigned int)(statp->st_mode & FILEMODEMASK),
604 fprintf(stderr, "Entering directory: %s", path);
605 (void)write(remout, path, strlen(path));
606 if (response() < 0) {
610 while ((dp = readdir(dirp))) {
613 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
615 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
616 run_err("%s/%s: name too long", name, dp->d_name);
619 (void)sprintf(path, "%s/%s", name, dp->d_name);
623 (void)closedir(dirp);
624 (void)write(remout, "E\n", 2);
635 enum { YES, NO, DISPLAYED } wrerr;
638 int amt, count, exists, first, mask, mode, ofd, omode;
639 int setimes, size, targisdir, wrerrno = 0;
640 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
644 #define SCREWUP(str) { why = str; goto screwup; }
646 setimes = targisdir = 0;
651 run_err("ambiguous target");
655 if (targetshouldbedirectory)
658 (void)write(remout, "", 1);
659 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
661 for (first = 1;; first = 0) {
663 if (read(remin, cp, 1) <= 0)
666 SCREWUP("unexpected <newline>");
668 if (read(remin, &ch, sizeof(ch)) != sizeof(ch))
669 SCREWUP("lost connection");
671 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
674 if (buf[0] == '\01' || buf[0] == '\02') {
676 (void)write(STDERR_FILENO,
677 buf + 1, strlen(buf + 1));
684 (void)write(remout, "", 1);
691 #define getnum(t) (t) = 0; \
692 while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
699 SCREWUP("mtime.sec not delimited");
702 SCREWUP("mtime.usec not delimited");
705 SCREWUP("atime.sec not delimited");
708 SCREWUP("atime.usec not delimited");
709 (void)write(remout, "", 1);
712 if (*cp != 'C' && *cp != 'D') {
714 * Check for the case "rcp remote:foo\* local:bar".
715 * In this case, the line "No match." can be returned
716 * by the shell before the rcp command on the remote is
717 * executed so the ^Aerror_message convention isn't
724 SCREWUP("expected control record");
727 for (++cp; cp < buf + 5; cp++) {
728 if (*cp < '0' || *cp > '7')
730 mode = (mode << 3) | (*cp - '0');
733 SCREWUP("mode not delimited");
735 for (size = 0; *cp >= '0' && *cp <= '9';)
736 size = size * 10 + (*cp++ - '0');
738 SCREWUP("size not delimited");
740 static char *namebuf;
744 need = strlen(targ) + strlen(cp) + 250;
746 namebuf = xmalloc(need);
747 (void)sprintf(namebuf, "%s%s%s", targ,
748 *targ ? "/" : "", cp);
753 exists = stat(np, &stb) == 0;
755 int mod_flag = pflag;
757 if (!S_ISDIR(stb.st_mode)) {
762 (void)chmod(np, mode);
764 /* Handle copying from a read-only directory */
766 if (mkdir(np, mode | S_IRWXU) < 0)
773 if (utime(np, &ut) < 0)
774 run_err("%s: set times: %s",
775 np, strerror(errno));
778 (void)chmod(np, mode);
783 if ((ofd = open(np, O_WRONLY|O_CREAT|O_TRUNC, mode)) < 0) {
784 bad: run_err("%s: %s", np, strerror(errno));
787 (void)write(remout, "", 1);
788 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
800 for (count = i = 0; i < size; i += 4096) {
806 j = read(remin, cp, amt);
808 run_err("%s", j ? strerror(errno) :
809 "dropped connection");
816 if (count == bp->cnt) {
817 /* Keep reading so we stay sync'd up. */
819 j = write(ofd, bp->buf, count);
822 wrerrno = j >= 0 ? EIO : errno;
831 if (count != 0 && wrerr == NO &&
832 (j = write(ofd, bp->buf, count)) != count) {
834 wrerrno = j >= 0 ? EIO : errno;
837 if (ftruncate(ofd, size)) {
838 run_err("%s: truncate: %s", np, strerror(errno));
843 if (exists || omode != mode)
844 if (fchmod(ofd, omode))
845 run_err("%s: set mode: %s",
846 np, strerror(errno));
848 if (!exists && omode != mode)
849 if (fchmod(ofd, omode & ~mask))
850 run_err("%s: set mode: %s",
851 np, strerror(errno));
855 if (setimes && wrerr == NO) {
857 if (utime(np, &ut) < 0) {
858 run_err("%s: set times: %s",
859 np, strerror(errno));
865 run_err("%s: %s", np, strerror(wrerrno));
868 (void)write(remout, "", 1);
875 run_err("protocol error: %s", why);
882 char ch, *cp, resp, rbuf[2048];
884 if (read(remin, &resp, sizeof(resp)) != sizeof(resp))
894 case 1: /* error, followed by error msg */
895 case 2: /* fatal error, "" */
897 if (read(remin, &ch, sizeof(ch)) != sizeof(ch))
900 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
903 (void)write(STDERR_FILENO, rbuf, cp - rbuf);
915 (void)fprintf(stderr,
916 "usage: scp [-pqrvC] [-P port] [-c cipher] [-i identity] f1 f2; or:\n scp [options] f1 ... fn directory\n");
921 run_err(const char *fmt, ...)
928 if (fp == NULL && !(fp = fdopen(remout, "w")))
930 (void)fprintf(fp, "%c", 0x01);
931 (void)fprintf(fp, "scp: ");
932 (void)vfprintf(fp, fmt, ap);
933 (void)fprintf(fp, "\n");
938 vfprintf(stderr, fmt, ap);
939 fprintf(stderr, "\n");
945 /* Stuff below is from BSD rcp util.c. */
948 * Copyright (c) 1992, 1993
949 * The Regents of the University of California. All rights reserved.
951 * Redistribution and use in source and binary forms, with or without
952 * modification, are permitted provided that the following conditions
954 * 1. Redistributions of source code must retain the above copyright
955 * notice, this list of conditions and the following disclaimer.
956 * 2. Redistributions in binary form must reproduce the above copyright
957 * notice, this list of conditions and the following disclaimer in the
958 * documentation and/or other materials provided with the distribution.
959 * 3. All advertising materials mentioning features or use of this software
960 * must display the following acknowledgement:
961 * This product includes software developed by the University of
962 * California, Berkeley and its contributors.
963 * 4. Neither the name of the University nor the names of its contributors
964 * may be used to endorse or promote products derived from this software
965 * without specific prior written permission.
967 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
968 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
969 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
970 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
971 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
972 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
973 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
974 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
975 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
976 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
986 if (*cp == ':') /* Leading colon is part of file name. */
1004 if (!stat(cp, &stb)) {
1005 if (S_ISDIR(stb.st_mode))
1009 run_err("%s: %s", cp, strerror(errno));
1025 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1030 bad: fprintf(stderr, "%s: invalid user name", cp0);
1035 allocbuf(bp, fd, blksize)
1042 if (fstat(fd, &stb) < 0) {
1043 run_err("fstat: %s", strerror(errno));
1046 if (stb.st_blksize == 0)
1049 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1051 if (bp->cnt >= size)
1053 if (bp->buf == NULL)
1054 bp->buf = xmalloc(size);
1056 bp->buf = xrealloc(bp->buf, size);
1066 fprintf(stderr, "lost connection\n");
1071 * ensure all of data on socket comes through. f==read || f==write
1074 atomicio(f, fd, s, n)
1081 res = (f)(fd, s+pos, n-pos);
1084 if (errno==EINTR || errno==EAGAIN)
1096 alarmtimer(int wait)
1098 struct itimerval itv;
1100 itv.it_value.tv_sec = wait;
1101 itv.it_value.tv_usec = 0;
1102 itv.it_interval = itv.it_value;
1103 setitimer(ITIMER_REAL, &itv, NULL);
1107 updateprogressmeter(void)
1109 int save_errno = errno;
1116 progressmeter(int flag)
1118 static const char prefixes[] = " KMGTP";
1119 static struct timeval lastupdate;
1120 static off_t lastsize;
1121 struct timeval now, td, wait;
1122 off_t cursize, abbrevsize;
1124 int ratio, barlength, i, remaining;
1128 (void)gettimeofday(&start, (struct timezone *)0);
1132 (void)gettimeofday(&now, (struct timezone *)0);
1133 cursize = statbytes;
1134 if (totalbytes != 0) {
1135 ratio = cursize * 100 / totalbytes;
1136 ratio = MAX(ratio, 0);
1137 ratio = MIN(ratio, 100);
1142 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1144 barlength = getttywidth() - 51;
1145 if (barlength > 0) {
1146 i = barlength * ratio / 100;
1147 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1149 "*****************************************************************************"
1150 "*****************************************************************************",
1155 abbrevsize = cursize;
1156 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1160 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5qd %c%c ",
1161 (quad_t)abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
1164 timersub(&now, &lastupdate, &wait);
1165 if (cursize > lastsize) {
1168 if (wait.tv_sec >= STALLTIME) {
1169 start.tv_sec += wait.tv_sec;
1170 start.tv_usec += wait.tv_usec;
1175 timersub(&now, &start, &td);
1176 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1178 if (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes) {
1179 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1181 } else if (wait.tv_sec >= STALLTIME) {
1182 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1185 remaining = (int)(totalbytes / (statbytes / elapsed) - elapsed);
1186 i = remaining / 3600;
1188 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1191 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1193 i = remaining % 3600;
1194 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1195 "%02d:%02d ETA", i / 60, i % 60);
1197 atomicio(write, fileno(stdout), buf, strlen(buf));
1200 signal(SIGALRM, (void *)updateprogressmeter);
1202 } else if (flag == 1) {
1204 write(fileno(stdout), "\n", 1);
1212 struct winsize winsize;
1214 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1215 return(winsize.ws_col ? winsize.ws_col : 80);