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>
16 * Copyright (c) 1983, 1990, 1992, 1993, 1995
17 * The Regents of the University of California. All rights reserved.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 * 3. All advertising materials mentioning features or use of this software
28 * must display the following acknowledgement:
29 * This product includes software developed by the University of
30 * California, Berkeley and its contributors.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 RCSID("$OpenBSD: scp.c,v 1.35 2000/08/19 02:50:07 deraadt Exp $");
58 /* For progressmeter() -- number of seconds before xfer considered "stalled" */
61 /* Progress meter bar */
63 "************************************************************"\
64 "************************************************************"\
65 "************************************************************"\
66 "************************************************************"
67 #define MAX_BARLENGTH (sizeof(BAR) - 1)
69 /* Visual statistics about files as they are transferred. */
70 void progressmeter(int);
72 /* Returns width of the terminal (for progress meter calculations). */
73 int getttywidth(void);
74 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc);
76 /* Time a transfer started. */
77 static struct timeval start;
79 /* Number of bytes of current file transferred so far. */
80 volatile unsigned long statbytes;
82 /* Total size of current file. */
85 /* Name of current file being transferred. */
88 /* This is set to non-zero if IPv4 is desired. */
91 /* This is set to non-zero if IPv6 is desired. */
94 /* This is set to non-zero to enable verbose mode. */
97 /* This is set to non-zero if compression is desired. */
98 int compress_flag = 0;
100 /* This is set to zero if the progressmeter is not desired. */
101 int showprogress = 1;
103 /* This is set to non-zero if running in batch mode (that is, password
104 and passphrase queries are not allowed). */
107 /* This is set to the cipher type string if given on the command line. */
110 /* This is set to the RSA authentication identity file name if given on
112 char *identity = NULL;
114 /* This is the port to use in contacting the remote site (is non-NULL). */
117 /* This is the program to execute for the secured connection. ("ssh" or -S) */
118 char *ssh_program = SSH_PROGRAM;
121 * This function executes the given command as the specified user on the
122 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
123 * assigns the input and output file descriptors on success.
127 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
129 int pin[2], pout[2], reserved[2];
132 fprintf(stderr, "Executing: host %s, user %s, command %s\n",
133 host, remuser ? remuser : "(unspecified)", cmd);
136 * Reserve two descriptors so that the real pipes won't get
137 * descriptors 0 and 1 because that will screw up dup2 below.
141 /* Create a socket pair for communicating with ssh. */
143 fatal("pipe: %s", strerror(errno));
145 fatal("pipe: %s", strerror(errno));
147 /* Free the reserved descriptors. */
151 /* For a child to execute the command on the remote host using ssh. */
153 char *args[100]; /* XXX careful */
165 args[i++] = ssh_program;
167 args[i++] = "-oFallBackToRsh no";
177 args[i++] = "-oBatchMode yes";
178 if (cipher != NULL) {
182 if (identity != NULL) {
184 args[i++] = identity;
190 if (remuser != NULL) {
198 execvp(ssh_program, args);
202 /* Parent. Close the other side, and return the local side. */
211 fatal(const char *fmt,...)
217 vsnprintf(buf, sizeof(buf), fmt, ap);
219 fprintf(stderr, "%s\n", buf);
228 extern int iamremote;
230 BUF *allocbuf(BUF *, int, int);
235 void run_err(const char *,...);
236 void verifydir(char *);
240 int errs, remin, remout;
241 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
244 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
247 void rsource(char *, struct stat *);
248 void sink(int, char *[]);
249 void source(int, char *[]);
250 void tolocal(int, char *[]);
251 void toremote(char *, int, char *[]);
259 int ch, fflag, tflag;
265 while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q46S")) != EOF)
267 /* User-visible flags. */
284 ssh_program = optarg;
287 /* Server options. */
289 targetshouldbedirectory = 1;
291 case 'f': /* "from" */
324 if ((pwd = getpwuid(userid = getuid())) == NULL)
325 fatal("unknown user %d", (int) userid);
327 if (!isatty(STDERR_FILENO))
330 remin = STDIN_FILENO;
331 remout = STDOUT_FILENO;
334 /* Follow "protocol", send data. */
347 targetshouldbedirectory = 1;
350 /* Command to be executed on remote system using "ssh". */
351 (void) sprintf(cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "",
352 iamrecursive ? " -r" : "", pflag ? " -p" : "",
353 targetshouldbedirectory ? " -d" : "");
355 (void) signal(SIGPIPE, lostconn);
357 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
358 toremote(targ, argc, argv);
360 tolocal(argc, argv); /* Dest is local host. */
361 if (targetshouldbedirectory)
362 verifydir(argv[argc - 1]);
371 if (*host == '[' && host[strlen(host) - 1] == ']') {
372 host[strlen(host) - 1] = '\0';
379 toremote(targ, argc, argv)
384 char *bp, *host, *src, *suser, *thost, *tuser;
390 if ((thost = strchr(argv[argc - 1], '@'))) {
393 tuser = argv[argc - 1];
396 else if (!okname(tuser))
399 thost = argv[argc - 1];
403 for (i = 0; i < argc - 1; i++) {
404 src = colon(argv[i]);
405 if (src) { /* remote to remote */
409 host = strchr(argv[i], '@');
410 len = strlen(ssh_program) + strlen(argv[i]) +
411 strlen(src) + (tuser ? strlen(tuser) : 0) +
412 strlen(thost) + strlen(targ) + CMDNEEDS + 32;
416 host = cleanhostname(host);
419 suser = pwd->pw_name;
420 else if (!okname(suser))
423 "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
424 ssh_program, verbose_mode ? " -v" : "",
425 suser, host, cmd, src,
426 tuser ? tuser : "", tuser ? "@" : "",
429 host = cleanhostname(argv[i]);
431 "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
432 ssh_program, verbose_mode ? " -v" : "",
434 tuser ? tuser : "", tuser ? "@" : "",
438 fprintf(stderr, "Executing: %s\n", bp);
441 } else { /* local to remote */
443 len = strlen(targ) + CMDNEEDS + 20;
445 (void) sprintf(bp, "%s -t %s", cmd, targ);
446 host = cleanhostname(thost);
447 if (do_cmd(host, tuser, bp, &remin,
465 char *bp, *host, *src, *suser;
467 for (i = 0; i < argc - 1; i++) {
468 if (!(src = colon(argv[i]))) { /* Local to local. */
469 len = strlen(_PATH_CP) + strlen(argv[i]) +
470 strlen(argv[argc - 1]) + 20;
472 (void) sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
473 iamrecursive ? " -r" : "", pflag ? " -p" : "",
474 argv[i], argv[argc - 1]);
476 fprintf(stderr, "Executing: %s\n", bp);
485 if ((host = strchr(argv[i], '@')) == NULL) {
492 suser = pwd->pw_name;
493 else if (!okname(suser))
496 host = cleanhostname(host);
497 len = strlen(src) + CMDNEEDS + 20;
499 (void) sprintf(bp, "%s -f %s", cmd, src);
500 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
506 sink(1, argv + argc - 1);
521 int amt, fd, haderr, indx, result;
522 char *last, *name, buf[2048];
524 for (indx = 0; indx < argc; ++indx) {
527 if ((fd = open(name, O_RDONLY, 0)) < 0)
529 if (fstat(fd, &stb) < 0) {
530 syserr: run_err("%s: %s", name, strerror(errno));
533 switch (stb.st_mode & S_IFMT) {
543 run_err("%s: not a regular file", name);
546 if ((last = strrchr(name, '/')) == NULL)
553 * Make it compatible with possible future
554 * versions expecting microseconds.
556 (void) sprintf(buf, "T%lu 0 %lu 0\n",
557 (unsigned long) stb.st_mtime,
558 (unsigned long) stb.st_atime);
559 (void) atomicio(write, remout, buf, strlen(buf));
563 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
564 (void) sprintf(buf, "C%04o %lu %s\n",
565 (unsigned int) (stb.st_mode & FILEMODEMASK),
566 (unsigned long) stb.st_size,
569 fprintf(stderr, "Sending file modes: %s", buf);
572 (void) atomicio(write, remout, buf, strlen(buf));
575 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
576 next: (void) close(fd);
580 totalbytes = stb.st_size;
583 /* Keep writing after an error so that we stay sync'd up. */
584 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
586 if (i + amt > stb.st_size)
587 amt = stb.st_size - i;
589 result = atomicio(read, fd, bp->buf, amt);
591 haderr = result >= 0 ? EIO : errno;
594 (void) atomicio(write, remout, bp->buf, amt);
596 result = atomicio(write, remout, bp->buf, amt);
598 haderr = result >= 0 ? EIO : errno;
605 if (close(fd) < 0 && !haderr)
608 (void) atomicio(write, remout, "", 1);
610 run_err("%s: %s", name, strerror(haderr));
622 char *last, *vect[1], path[1100];
624 if (!(dirp = opendir(name))) {
625 run_err("%s: %s", name, strerror(errno));
628 last = strrchr(name, '/');
634 (void) sprintf(path, "T%lu 0 %lu 0\n",
635 (unsigned long) statp->st_mtime,
636 (unsigned long) statp->st_atime);
637 (void) atomicio(write, remout, path, strlen(path));
638 if (response() < 0) {
643 (void) sprintf(path, "D%04o %d %.1024s\n",
644 (unsigned int) (statp->st_mode & FILEMODEMASK), 0, last);
646 fprintf(stderr, "Entering directory: %s", path);
647 (void) atomicio(write, remout, path, strlen(path));
648 if (response() < 0) {
652 while ((dp = readdir(dirp))) {
655 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
657 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
658 run_err("%s/%s: name too long", name, dp->d_name);
661 (void) sprintf(path, "%s/%s", name, dp->d_name);
665 (void) closedir(dirp);
666 (void) atomicio(write, remout, "E\n", 2);
682 int amt, count, exists, first, mask, mode, ofd, omode;
683 int setimes, size, targisdir, wrerrno = 0;
684 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
688 #define SCREWUP(str) { why = str; goto screwup; }
690 setimes = targisdir = 0;
695 run_err("ambiguous target");
699 if (targetshouldbedirectory)
702 (void) atomicio(write, remout, "", 1);
703 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
705 for (first = 1;; first = 0) {
707 if (atomicio(read, remin, cp, 1) <= 0)
710 SCREWUP("unexpected <newline>");
712 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
713 SCREWUP("lost connection");
715 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
718 if (buf[0] == '\01' || buf[0] == '\02') {
720 (void) atomicio(write, STDERR_FILENO,
721 buf + 1, strlen(buf + 1));
728 (void) atomicio(write, remout, "", 1);
734 #define getnum(t) (t) = 0; \
735 while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
742 SCREWUP("mtime.sec not delimited");
745 SCREWUP("mtime.usec not delimited");
748 SCREWUP("atime.sec not delimited");
751 SCREWUP("atime.usec not delimited");
752 (void) atomicio(write, remout, "", 1);
755 if (*cp != 'C' && *cp != 'D') {
757 * Check for the case "rcp remote:foo\* local:bar".
758 * In this case, the line "No match." can be returned
759 * by the shell before the rcp command on the remote is
760 * executed so the ^Aerror_message convention isn't
767 SCREWUP("expected control record");
770 for (++cp; cp < buf + 5; cp++) {
771 if (*cp < '0' || *cp > '7')
773 mode = (mode << 3) | (*cp - '0');
776 SCREWUP("mode not delimited");
778 for (size = 0; *cp >= '0' && *cp <= '9';)
779 size = size * 10 + (*cp++ - '0');
781 SCREWUP("size not delimited");
783 static char *namebuf;
787 need = strlen(targ) + strlen(cp) + 250;
789 namebuf = xmalloc(need);
790 (void) sprintf(namebuf, "%s%s%s", targ,
791 *targ ? "/" : "", cp);
796 exists = stat(np, &stb) == 0;
798 int mod_flag = pflag;
800 if (!S_ISDIR(stb.st_mode)) {
805 (void) chmod(np, mode);
807 /* Handle copying from a read-only
810 if (mkdir(np, mode | S_IRWXU) < 0)
817 if (utime(np, &ut) < 0)
818 run_err("%s: set times: %s",
819 np, strerror(errno));
822 (void) chmod(np, mode);
827 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
828 bad: run_err("%s: %s", np, strerror(errno));
831 (void) atomicio(write, remout, "", 1);
832 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
844 for (count = i = 0; i < size; i += 4096) {
850 j = atomicio(read, remin, cp, amt);
852 run_err("%s", j ? strerror(errno) :
853 "dropped connection");
860 if (count == bp->cnt) {
861 /* Keep reading so we stay sync'd up. */
863 j = atomicio(write, ofd, bp->buf, count);
866 wrerrno = j >= 0 ? EIO : errno;
875 if (count != 0 && wrerr == NO &&
876 (j = atomicio(write, ofd, bp->buf, count)) != count) {
878 wrerrno = j >= 0 ? EIO : errno;
881 if (ftruncate(ofd, size)) {
882 run_err("%s: truncate: %s", np, strerror(errno));
887 if (exists || omode != mode)
888 if (fchmod(ofd, omode))
889 run_err("%s: set mode: %s",
890 np, strerror(errno));
892 if (!exists && omode != mode)
893 if (fchmod(ofd, omode & ~mask))
894 run_err("%s: set mode: %s",
895 np, strerror(errno));
897 if (close(ofd) == -1) {
902 if (setimes && wrerr == NO) {
904 if (utime(np, &ut) < 0) {
905 run_err("%s: set times: %s",
906 np, strerror(errno));
912 run_err("%s: %s", np, strerror(wrerrno));
915 (void) atomicio(write, remout, "", 1);
922 run_err("protocol error: %s", why);
929 char ch, *cp, resp, rbuf[2048];
931 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
941 case 1: /* error, followed by error msg */
942 case 2: /* fatal error, "" */
944 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
947 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
950 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
962 (void) fprintf(stderr, "usage: scp "
963 "[-pqrvC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2; or:\n"
964 " scp [options] f1 ... fn directory\n");
969 run_err(const char *fmt,...)
975 if (fp == NULL && !(fp = fdopen(remout, "w")))
977 (void) fprintf(fp, "%c", 0x01);
978 (void) fprintf(fp, "scp: ");
980 (void) vfprintf(fp, fmt, ap);
982 (void) fprintf(fp, "\n");
987 vfprintf(stderr, fmt, ap);
989 fprintf(stderr, "\n");
999 if (*cp == ':') /* Leading colon is part of file name. */
1005 if (*cp == '@' && *(cp+1) == '[')
1007 if (*cp == ']' && *(cp+1) == ':' && flag)
1009 if (*cp == ':' && !flag)
1023 if (!stat(cp, &stb)) {
1024 if (S_ISDIR(stb.st_mode))
1028 run_err("%s: %s", cp, strerror(errno));
1044 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1049 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1054 allocbuf(bp, fd, blksize)
1061 if (fstat(fd, &stb) < 0) {
1062 run_err("fstat: %s", strerror(errno));
1065 if (stb.st_blksize == 0)
1068 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1070 if (bp->cnt >= size)
1072 if (bp->buf == NULL)
1073 bp->buf = xmalloc(size);
1075 bp->buf = xrealloc(bp->buf, size);
1085 fprintf(stderr, "lost connection\n");
1091 alarmtimer(int wait)
1093 struct itimerval itv;
1095 itv.it_value.tv_sec = wait;
1096 itv.it_value.tv_usec = 0;
1097 itv.it_interval = itv.it_value;
1098 setitimer(ITIMER_REAL, &itv, NULL);
1102 updateprogressmeter(int ignore)
1104 int save_errno = errno;
1113 static pid_t pgrp = -1;
1119 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1120 ctty_pgrp == pgrp));
1124 progressmeter(int flag)
1126 static const char prefixes[] = " KMGTP";
1127 static struct timeval lastupdate;
1128 static off_t lastsize;
1129 struct timeval now, td, wait;
1130 off_t cursize, abbrevsize;
1132 int ratio, barlength, i, remaining;
1136 (void) gettimeofday(&start, (struct timezone *) 0);
1140 if (foregroundproc() == 0)
1143 (void) gettimeofday(&now, (struct timezone *) 0);
1144 cursize = statbytes;
1145 if (totalbytes != 0) {
1146 ratio = 100.0 * cursize / totalbytes;
1147 ratio = MAX(ratio, 0);
1148 ratio = MIN(ratio, 100);
1152 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1154 barlength = getttywidth() - 51;
1155 barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
1156 if (barlength > 0) {
1157 i = barlength * ratio / 100;
1158 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1159 "|%.*s%*s|", i, BAR, barlength - i, "");
1162 abbrevsize = cursize;
1163 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1167 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
1168 (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
1171 timersub(&now, &lastupdate, &wait);
1172 if (cursize > lastsize) {
1175 if (wait.tv_sec >= STALLTIME) {
1176 start.tv_sec += wait.tv_sec;
1177 start.tv_usec += wait.tv_usec;
1181 timersub(&now, &start, &td);
1182 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1184 if (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes) {
1185 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1187 } else if (wait.tv_sec >= STALLTIME) {
1188 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1193 (int)(totalbytes / (statbytes / elapsed) - elapsed);
1195 remaining = elapsed;
1197 i = remaining / 3600;
1199 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1202 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1204 i = remaining % 3600;
1205 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1206 "%02d:%02d%s", i / 60, i % 60,
1207 (flag != 1) ? " ETA" : " ");
1209 atomicio(write, fileno(stdout), buf, strlen(buf));
1212 struct sigaction sa;
1213 sa.sa_handler = updateprogressmeter;
1214 sigemptyset(&sa.sa_mask);
1216 sa.sa_flags = SA_RESTART;
1218 sigaction(SIGALRM, &sa, NULL);
1220 } else if (flag == 1) {
1222 atomicio(write, fileno(stdout), "\n", 1);
1230 struct winsize winsize;
1232 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1233 return (winsize.ws_col ? winsize.ws_col : 80);