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.36 2000/08/24 21:46:59 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;
684 int setimes, targisdir, wrerrno = 0;
685 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
689 #define SCREWUP(str) { why = str; goto screwup; }
691 setimes = targisdir = 0;
696 run_err("ambiguous target");
700 if (targetshouldbedirectory)
703 (void) atomicio(write, remout, "", 1);
704 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
706 for (first = 1;; first = 0) {
708 if (atomicio(read, remin, cp, 1) <= 0)
711 SCREWUP("unexpected <newline>");
713 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
714 SCREWUP("lost connection");
716 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
719 if (buf[0] == '\01' || buf[0] == '\02') {
721 (void) atomicio(write, STDERR_FILENO,
722 buf + 1, strlen(buf + 1));
729 (void) atomicio(write, remout, "", 1);
735 #define getnum(t) (t) = 0; \
736 while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
743 SCREWUP("mtime.sec not delimited");
746 SCREWUP("mtime.usec not delimited");
749 SCREWUP("atime.sec not delimited");
752 SCREWUP("atime.usec not delimited");
753 (void) atomicio(write, remout, "", 1);
756 if (*cp != 'C' && *cp != 'D') {
758 * Check for the case "rcp remote:foo\* local:bar".
759 * In this case, the line "No match." can be returned
760 * by the shell before the rcp command on the remote is
761 * executed so the ^Aerror_message convention isn't
768 SCREWUP("expected control record");
771 for (++cp; cp < buf + 5; cp++) {
772 if (*cp < '0' || *cp > '7')
774 mode = (mode << 3) | (*cp - '0');
777 SCREWUP("mode not delimited");
779 for (size = 0; *cp >= '0' && *cp <= '9';)
780 size = size * 10 + (*cp++ - '0');
782 SCREWUP("size not delimited");
784 static char *namebuf;
788 need = strlen(targ) + strlen(cp) + 250;
790 namebuf = xmalloc(need);
791 (void) sprintf(namebuf, "%s%s%s", targ,
792 *targ ? "/" : "", cp);
797 exists = stat(np, &stb) == 0;
799 int mod_flag = pflag;
801 if (!S_ISDIR(stb.st_mode)) {
806 (void) chmod(np, mode);
808 /* Handle copying from a read-only
811 if (mkdir(np, mode | S_IRWXU) < 0)
818 if (utime(np, &ut) < 0)
819 run_err("%s: set times: %s",
820 np, strerror(errno));
823 (void) chmod(np, mode);
828 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
829 bad: run_err("%s: %s", np, strerror(errno));
832 (void) atomicio(write, remout, "", 1);
833 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
845 for (count = i = 0; i < size; i += 4096) {
851 j = atomicio(read, remin, cp, amt);
853 run_err("%s", j ? strerror(errno) :
854 "dropped connection");
861 if (count == bp->cnt) {
862 /* Keep reading so we stay sync'd up. */
864 j = atomicio(write, ofd, bp->buf, count);
867 wrerrno = j >= 0 ? EIO : errno;
876 if (count != 0 && wrerr == NO &&
877 (j = atomicio(write, ofd, bp->buf, count)) != count) {
879 wrerrno = j >= 0 ? EIO : errno;
882 if (ftruncate(ofd, size)) {
883 run_err("%s: truncate: %s", np, strerror(errno));
888 if (exists || omode != mode)
889 if (fchmod(ofd, omode))
890 run_err("%s: set mode: %s",
891 np, strerror(errno));
893 if (!exists && omode != mode)
894 if (fchmod(ofd, omode & ~mask))
895 run_err("%s: set mode: %s",
896 np, strerror(errno));
898 if (close(ofd) == -1) {
903 if (setimes && wrerr == NO) {
905 if (utime(np, &ut) < 0) {
906 run_err("%s: set times: %s",
907 np, strerror(errno));
913 run_err("%s: %s", np, strerror(wrerrno));
916 (void) atomicio(write, remout, "", 1);
923 run_err("protocol error: %s", why);
930 char ch, *cp, resp, rbuf[2048];
932 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
942 case 1: /* error, followed by error msg */
943 case 2: /* fatal error, "" */
945 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
948 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
951 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
963 (void) fprintf(stderr, "usage: scp "
964 "[-pqrvC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2; or:\n"
965 " scp [options] f1 ... fn directory\n");
970 run_err(const char *fmt,...)
976 if (fp == NULL && !(fp = fdopen(remout, "w")))
978 (void) fprintf(fp, "%c", 0x01);
979 (void) fprintf(fp, "scp: ");
981 (void) vfprintf(fp, fmt, ap);
983 (void) fprintf(fp, "\n");
988 vfprintf(stderr, fmt, ap);
990 fprintf(stderr, "\n");
1000 if (*cp == ':') /* Leading colon is part of file name. */
1006 if (*cp == '@' && *(cp+1) == '[')
1008 if (*cp == ']' && *(cp+1) == ':' && flag)
1010 if (*cp == ':' && !flag)
1024 if (!stat(cp, &stb)) {
1025 if (S_ISDIR(stb.st_mode))
1029 run_err("%s: %s", cp, strerror(errno));
1045 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1050 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1055 allocbuf(bp, fd, blksize)
1062 if (fstat(fd, &stb) < 0) {
1063 run_err("fstat: %s", strerror(errno));
1066 if (stb.st_blksize == 0)
1069 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1071 if (bp->cnt >= size)
1073 if (bp->buf == NULL)
1074 bp->buf = xmalloc(size);
1076 bp->buf = xrealloc(bp->buf, size);
1086 fprintf(stderr, "lost connection\n");
1092 alarmtimer(int wait)
1094 struct itimerval itv;
1096 itv.it_value.tv_sec = wait;
1097 itv.it_value.tv_usec = 0;
1098 itv.it_interval = itv.it_value;
1099 setitimer(ITIMER_REAL, &itv, NULL);
1103 updateprogressmeter(int ignore)
1105 int save_errno = errno;
1114 static pid_t pgrp = -1;
1120 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1121 ctty_pgrp == pgrp));
1125 progressmeter(int flag)
1127 static const char prefixes[] = " KMGTP";
1128 static struct timeval lastupdate;
1129 static off_t lastsize;
1130 struct timeval now, td, wait;
1131 off_t cursize, abbrevsize;
1133 int ratio, barlength, i, remaining;
1137 (void) gettimeofday(&start, (struct timezone *) 0);
1141 if (foregroundproc() == 0)
1144 (void) gettimeofday(&now, (struct timezone *) 0);
1145 cursize = statbytes;
1146 if (totalbytes != 0) {
1147 ratio = 100.0 * cursize / totalbytes;
1148 ratio = MAX(ratio, 0);
1149 ratio = MIN(ratio, 100);
1153 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1155 barlength = getttywidth() - 51;
1156 barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
1157 if (barlength > 0) {
1158 i = barlength * ratio / 100;
1159 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1160 "|%.*s%*s|", i, BAR, barlength - i, "");
1163 abbrevsize = cursize;
1164 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1168 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
1169 (int) 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),
1194 (int)(totalbytes / (statbytes / elapsed) - elapsed);
1196 remaining = elapsed;
1198 i = remaining / 3600;
1200 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1203 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1205 i = remaining % 3600;
1206 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1207 "%02d:%02d%s", i / 60, i % 60,
1208 (flag != 1) ? " ETA" : " ");
1210 atomicio(write, fileno(stdout), buf, strlen(buf));
1213 struct sigaction sa;
1214 sa.sa_handler = updateprogressmeter;
1215 sigemptyset((sigset_t *)&sa.sa_mask);
1217 sa.sa_flags = SA_RESTART;
1219 sigaction(SIGALRM, &sa, NULL);
1221 } else if (flag == 1) {
1223 atomicio(write, fileno(stdout), "\n", 1);
1231 struct winsize winsize;
1233 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1234 return (winsize.ws_col ? winsize.ws_col : 80);