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
56 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
59 /* Visual statistics about files as they are transferred. */
60 void progressmeter(int);
62 /* Returns width of the terminal (for progress meter calculations). */
63 int getttywidth(void);
65 /* Time a transfer started. */
66 static struct timeval start;
68 /* Number of bytes of current file transferred so far. */
69 volatile unsigned long statbytes;
71 /* Total size of current file. */
74 /* Name of current file being transferred. */
77 /* This is set to non-zero to enable verbose mode. */
80 /* This is set to non-zero if compression is desired. */
83 /* This is set to zero if the progressmeter is not desired. */
86 /* This is set to non-zero if running in batch mode (that is, password
87 and passphrase queries are not allowed). */
90 /* This is set to the cipher type string if given on the command line. */
93 /* This is set to the RSA authentication identity file name if given on
95 char *identity = NULL;
97 /* This is the port to use in contacting the remote site (is non-NULL). */
100 /* This function executes the given command as the specified user on the given
101 host. This returns < 0 if execution fails, and >= 0 otherwise.
102 This assigns the input and output file descriptors on success. */
105 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
114 descriptors 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. */
141 args[i++] = SSH_PROGRAM;
143 args[i++] = "-oFallBackToRsh no";
149 args[i++] = "-oBatchMode yes";
150 if (cipher != NULL) {
154 if (identity != NULL) {
156 args[i++] = identity;
162 if (remuser != NULL) {
170 execvp(SSH_PROGRAM, args);
174 /* Parent. Close the other side, and return the local side. */
183 fatal(const char *fmt,...)
189 vsnprintf(buf, sizeof(buf), fmt, ap);
191 fprintf(stderr, "%s\n", buf);
195 /* This stuff used to be in BSD rcp extern.h. */
202 extern int iamremote;
204 BUF *allocbuf(BUF *, int, int);
209 void run_err(const char *,...);
210 void verifydir(char *);
212 /* Stuff from BSD rcp.c continues. */
216 int errs, remin, remout;
217 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
220 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
223 void rsource(char *, struct stat *);
224 void sink(int, char *[]);
225 void source(int, char *[]);
226 void tolocal(int, char *[]);
227 void toremote(char *, int, char *[]);
235 int ch, fflag, tflag;
241 while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q")) != EOF)
243 /* User-visible flags. */
253 /* Server options. */
255 targetshouldbedirectory = 1;
257 case 'f': /* "from" */
290 if ((pwd = getpwuid(userid = getuid())) == NULL)
291 fatal("unknown user %d", (int) userid);
293 if (!isatty(STDERR_FILENO))
296 remin = STDIN_FILENO;
297 remout = STDOUT_FILENO;
300 /* Follow "protocol", send data. */
313 targetshouldbedirectory = 1;
316 /* Command to be executed on remote system using "ssh". */
317 (void) sprintf(cmd, "scp%s%s%s%s", 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]);
334 toremote(targ, argc, argv)
339 char *bp, *host, *src, *suser, *thost, *tuser;
345 if ((thost = strchr(argv[argc - 1], '@'))) {
348 tuser = argv[argc - 1];
351 else if (!okname(tuser))
354 thost = argv[argc - 1];
358 for (i = 0; i < argc - 1; i++) {
359 src = colon(argv[i]);
360 if (src) { /* remote to remote */
364 host = strchr(argv[i], '@');
365 len = strlen(SSH_PROGRAM) + strlen(argv[i]) +
366 strlen(src) + (tuser ? strlen(tuser) : 0) +
367 strlen(thost) + strlen(targ) + CMDNEEDS + 32;
373 suser = pwd->pw_name;
374 else if (!okname(suser))
377 "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
378 SSH_PROGRAM, verbose_mode ? " -v" : "",
379 suser, host, cmd, src,
380 tuser ? tuser : "", tuser ? "@" : "",
384 "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
385 SSH_PROGRAM, verbose_mode ? " -v" : "",
387 tuser ? tuser : "", tuser ? "@" : "",
390 fprintf(stderr, "Executing: %s\n", bp);
393 } else { /* local to remote */
395 len = strlen(targ) + CMDNEEDS + 20;
397 (void) sprintf(bp, "%s -t %s", cmd, targ);
399 if (do_cmd(host, tuser,
400 bp, &remin, &remout) < 0)
417 char *bp, *host, *src, *suser;
419 for (i = 0; i < argc - 1; i++) {
420 if (!(src = colon(argv[i]))) { /* Local to local. */
421 len = strlen(_PATH_CP) + strlen(argv[i]) +
422 strlen(argv[argc - 1]) + 20;
424 (void) sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
425 iamrecursive ? " -r" : "", pflag ? " -p" : "",
426 argv[i], argv[argc - 1]);
428 fprintf(stderr, "Executing: %s\n", bp);
437 if ((host = strchr(argv[i], '@')) == NULL) {
444 suser = pwd->pw_name;
445 else if (!okname(suser))
448 len = strlen(src) + CMDNEEDS + 20;
450 (void) sprintf(bp, "%s -f %s", cmd, src);
451 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
457 sink(1, argv + argc - 1);
472 int amt, fd, haderr, indx, result;
473 char *last, *name, buf[2048];
475 for (indx = 0; indx < argc; ++indx) {
478 if ((fd = open(name, O_RDONLY, 0)) < 0)
480 if (fstat(fd, &stb) < 0) {
481 syserr: run_err("%s: %s", name, strerror(errno));
484 switch (stb.st_mode & S_IFMT) {
494 run_err("%s: not a regular file", name);
497 if ((last = strrchr(name, '/')) == NULL)
504 * Make it compatible with possible future
505 * versions expecting microseconds.
507 (void) sprintf(buf, "T%lu 0 %lu 0\n",
508 (unsigned long) stb.st_mtime,
509 (unsigned long) stb.st_atime);
510 (void) write(remout, buf, strlen(buf));
514 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
515 (void) sprintf(buf, "C%04o %lu %s\n",
516 (unsigned int) (stb.st_mode & FILEMODEMASK),
517 (unsigned long) stb.st_size,
520 fprintf(stderr, "Sending file modes: %s", buf);
523 (void) write(remout, buf, strlen(buf));
526 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
527 next: (void) close(fd);
531 totalbytes = stb.st_size;
534 /* Keep writing after an error so that we stay sync'd up. */
535 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
537 if (i + amt > stb.st_size)
538 amt = stb.st_size - i;
540 result = read(fd, bp->buf, amt);
542 haderr = result >= 0 ? EIO : errno;
545 (void) write(remout, bp->buf, amt);
547 result = write(remout, bp->buf, amt);
549 haderr = result >= 0 ? EIO : errno;
556 if (close(fd) < 0 && !haderr)
559 (void) write(remout, "", 1);
561 run_err("%s: %s", name, strerror(haderr));
573 char *last, *vect[1], path[1100];
575 if (!(dirp = opendir(name))) {
576 run_err("%s: %s", name, strerror(errno));
579 last = strrchr(name, '/');
585 (void) sprintf(path, "T%lu 0 %lu 0\n",
586 (unsigned long) statp->st_mtime,
587 (unsigned long) statp->st_atime);
588 (void) write(remout, path, strlen(path));
589 if (response() < 0) {
594 (void) sprintf(path, "D%04o %d %.1024s\n",
595 (unsigned int) (statp->st_mode & FILEMODEMASK),
598 fprintf(stderr, "Entering directory: %s", path);
599 (void) write(remout, path, strlen(path));
600 if (response() < 0) {
604 while ((dp = readdir(dirp))) {
607 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
609 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
610 run_err("%s/%s: name too long", name, dp->d_name);
613 (void) sprintf(path, "%s/%s", name, dp->d_name);
617 (void) closedir(dirp);
618 (void) write(remout, "E\n", 2);
634 int amt, count, exists, first, mask, mode, ofd, omode;
635 int setimes, size, targisdir, wrerrno = 0;
636 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
640 #define SCREWUP(str) { why = str; goto screwup; }
642 setimes = targisdir = 0;
647 run_err("ambiguous target");
651 if (targetshouldbedirectory)
654 (void) write(remout, "", 1);
655 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
657 for (first = 1;; first = 0) {
659 if (read(remin, cp, 1) <= 0)
662 SCREWUP("unexpected <newline>");
664 if (read(remin, &ch, sizeof(ch)) != sizeof(ch))
665 SCREWUP("lost connection");
667 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
670 if (buf[0] == '\01' || buf[0] == '\02') {
672 (void) write(STDERR_FILENO,
673 buf + 1, strlen(buf + 1));
680 (void) write(remout, "", 1);
686 #define getnum(t) (t) = 0; \
687 while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
694 SCREWUP("mtime.sec not delimited");
697 SCREWUP("mtime.usec not delimited");
700 SCREWUP("atime.sec not delimited");
703 SCREWUP("atime.usec not delimited");
704 (void) write(remout, "", 1);
707 if (*cp != 'C' && *cp != 'D') {
709 * Check for the case "rcp remote:foo\* local:bar".
710 * In this case, the line "No match." can be returned
711 * by the shell before the rcp command on the remote is
712 * executed so the ^Aerror_message convention isn't
719 SCREWUP("expected control record");
722 for (++cp; cp < buf + 5; cp++) {
723 if (*cp < '0' || *cp > '7')
725 mode = (mode << 3) | (*cp - '0');
728 SCREWUP("mode not delimited");
730 for (size = 0; *cp >= '0' && *cp <= '9';)
731 size = size * 10 + (*cp++ - '0');
733 SCREWUP("size not delimited");
735 static char *namebuf;
739 need = strlen(targ) + strlen(cp) + 250;
741 namebuf = xmalloc(need);
742 (void) sprintf(namebuf, "%s%s%s", targ,
743 *targ ? "/" : "", cp);
748 exists = stat(np, &stb) == 0;
750 int mod_flag = pflag;
752 if (!S_ISDIR(stb.st_mode)) {
757 (void) chmod(np, mode);
759 /* Handle copying from a read-only
762 if (mkdir(np, mode | S_IRWXU) < 0)
769 if (utime(np, &ut) < 0)
770 run_err("%s: set times: %s",
771 np, strerror(errno));
774 (void) chmod(np, mode);
779 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
780 bad: run_err("%s: %s", np, strerror(errno));
783 (void) write(remout, "", 1);
784 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
796 for (count = i = 0; i < size; i += 4096) {
802 j = read(remin, cp, amt);
804 run_err("%s", j ? strerror(errno) :
805 "dropped connection");
812 if (count == bp->cnt) {
813 /* Keep reading so we stay sync'd up. */
815 j = write(ofd, bp->buf, count);
818 wrerrno = j >= 0 ? EIO : errno;
827 if (count != 0 && wrerr == NO &&
828 (j = write(ofd, bp->buf, count)) != count) {
830 wrerrno = j >= 0 ? EIO : errno;
833 if (ftruncate(ofd, size)) {
834 run_err("%s: truncate: %s", np, strerror(errno));
839 if (exists || omode != mode)
840 if (fchmod(ofd, omode))
841 run_err("%s: set mode: %s",
842 np, strerror(errno));
844 if (!exists && omode != mode)
845 if (fchmod(ofd, omode & ~mask))
846 run_err("%s: set mode: %s",
847 np, strerror(errno));
851 if (setimes && wrerr == NO) {
853 if (utime(np, &ut) < 0) {
854 run_err("%s: set times: %s",
855 np, strerror(errno));
861 run_err("%s: %s", np, strerror(wrerrno));
864 (void) write(remout, "", 1);
871 run_err("protocol error: %s", why);
878 char ch, *cp, resp, rbuf[2048];
880 if (read(remin, &resp, sizeof(resp)) != sizeof(resp))
890 case 1: /* error, followed by error msg */
891 case 2: /* fatal error, "" */
893 if (read(remin, &ch, sizeof(ch)) != sizeof(ch))
896 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
899 (void) write(STDERR_FILENO, rbuf, cp - rbuf);
911 (void) fprintf(stderr,
912 "usage: scp [-pqrvC] [-P port] [-c cipher] [-i identity] f1 f2; or:\n scp [options] f1 ... fn directory\n");
917 run_err(const char *fmt,...)
924 if (fp == NULL && !(fp = fdopen(remout, "w")))
926 (void) fprintf(fp, "%c", 0x01);
927 (void) fprintf(fp, "scp: ");
928 (void) vfprintf(fp, fmt, ap);
929 (void) fprintf(fp, "\n");
933 vfprintf(stderr, fmt, ap);
934 fprintf(stderr, "\n");
939 /* Stuff below is from BSD rcp util.c. */
942 * Copyright (c) 1992, 1993
943 * The Regents of the University of California. All rights reserved.
945 * Redistribution and use in source and binary forms, with or without
946 * modification, are permitted provided that the following conditions
948 * 1. Redistributions of source code must retain the above copyright
949 * notice, this list of conditions and the following disclaimer.
950 * 2. Redistributions in binary form must reproduce the above copyright
951 * notice, this list of conditions and the following disclaimer in the
952 * documentation and/or other materials provided with the distribution.
953 * 3. All advertising materials mentioning features or use of this software
954 * must display the following acknowledgement:
955 * This product includes software developed by the University of
956 * California, Berkeley and its contributors.
957 * 4. Neither the name of the University nor the names of its contributors
958 * may be used to endorse or promote products derived from this software
959 * without specific prior written permission.
961 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
962 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
963 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
964 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
965 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
966 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
967 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
968 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
969 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
970 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
980 if (*cp == ':') /* Leading colon is part of file name. */
998 if (!stat(cp, &stb)) {
999 if (S_ISDIR(stb.st_mode))
1003 run_err("%s: %s", cp, strerror(errno));
1019 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1024 bad: fprintf(stderr, "%s: invalid user name", cp0);
1029 allocbuf(bp, fd, blksize)
1036 if (fstat(fd, &stb) < 0) {
1037 run_err("fstat: %s", strerror(errno));
1040 if (stb.st_blksize == 0)
1043 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1045 if (bp->cnt >= size)
1047 if (bp->buf == NULL)
1048 bp->buf = xmalloc(size);
1050 bp->buf = xrealloc(bp->buf, size);
1060 fprintf(stderr, "lost connection\n");
1065 * ensure all of data on socket comes through. f==read || f==write
1068 atomicio(f, fd, s, n)
1075 res = (f) (fd, s + pos, n - pos);
1078 if (errno == EINTR || errno == EAGAIN)
1090 alarmtimer(int wait)
1092 struct itimerval itv;
1094 itv.it_value.tv_sec = wait;
1095 itv.it_value.tv_usec = 0;
1096 itv.it_interval = itv.it_value;
1097 setitimer(ITIMER_REAL, &itv, NULL);
1101 updateprogressmeter(void)
1103 int save_errno = errno;
1112 static pid_t pgrp = -1;
1118 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1119 ctty_pgrp == pgrp));
1123 progressmeter(int flag)
1125 static const char prefixes[] = " KMGTP";
1126 static struct timeval lastupdate;
1127 static off_t lastsize;
1128 struct timeval now, td, wait;
1129 off_t cursize, abbrevsize;
1131 int ratio, barlength, i, remaining;
1135 (void) gettimeofday(&start, (struct timezone *) 0);
1139 if (foregroundproc() == 0)
1142 (void) gettimeofday(&now, (struct timezone *) 0);
1143 cursize = statbytes;
1144 if (totalbytes != 0) {
1145 ratio = cursize * 100.0 / totalbytes;
1146 ratio = MAX(ratio, 0);
1147 ratio = MIN(ratio, 100);
1151 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1153 barlength = getttywidth() - 51;
1154 if (barlength > 0) {
1155 i = barlength * ratio / 100;
1156 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1158 "*****************************************************************************"
1159 "*****************************************************************************",
1163 abbrevsize = cursize;
1164 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1168 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5qd %c%c ",
1169 (quad_t) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
1172 timersub(&now, &lastupdate, &wait);
1173 if (cursize > lastsize) {
1176 if (wait.tv_sec >= STALLTIME) {
1177 start.tv_sec += wait.tv_sec;
1178 start.tv_usec += wait.tv_usec;
1182 timersub(&now, &start, &td);
1183 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1185 if (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes) {
1186 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1188 } else if (wait.tv_sec >= STALLTIME) {
1189 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1192 remaining = (int) (totalbytes / (statbytes / elapsed) - elapsed);
1193 i = remaining / 3600;
1195 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1198 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1200 i = remaining % 3600;
1201 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1202 "%02d:%02d ETA", i / 60, i % 60);
1204 atomicio(write, fileno(stdout), buf, strlen(buf));
1207 signal(SIGALRM, (void *) updateprogressmeter);
1209 } else if (flag == 1) {
1211 write(fileno(stdout), "\n", 1);
1219 struct winsize winsize;
1221 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1222 return (winsize.ws_col ? winsize.ws_col : 80);