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. */
81 int compress_flag = 0;
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). */
101 * This function executes the given command as the specified user on the
102 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
103 * assigns the input and output file descriptors on success.
107 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
109 int pin[2], pout[2], reserved[2];
112 fprintf(stderr, "Executing: host %s, user %s, command %s\n",
113 host, remuser ? remuser : "(unspecified)", cmd);
116 * Reserve two descriptors so that the real pipes won't get
117 * descriptors 0 and 1 because that will screw up dup2 below.
121 /* Create a socket pair for communicating with ssh. */
123 fatal("pipe: %s", strerror(errno));
125 fatal("pipe: %s", strerror(errno));
127 /* Free the reserved descriptors. */
131 /* For a child to execute the command on the remote host using ssh. */
145 args[i++] = SSH_PROGRAM;
147 args[i++] = "-oFallBackToRsh no";
153 args[i++] = "-oBatchMode yes";
154 if (cipher != NULL) {
158 if (identity != NULL) {
160 args[i++] = identity;
166 if (remuser != NULL) {
174 execvp(SSH_PROGRAM, args);
178 /* Parent. Close the other side, and return the local side. */
187 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)
247 /* User-visible flags. */
257 /* Server options. */
259 targetshouldbedirectory = 1;
261 case 'f': /* "from" */
294 if ((pwd = getpwuid(userid = getuid())) == NULL)
295 fatal("unknown user %d", (int) userid);
297 if (!isatty(STDERR_FILENO))
300 remin = STDIN_FILENO;
301 remout = STDOUT_FILENO;
304 /* Follow "protocol", send data. */
317 targetshouldbedirectory = 1;
320 /* Command to be executed on remote system using "ssh". */
321 (void) sprintf(cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "",
322 iamrecursive ? " -r" : "", pflag ? " -p" : "",
323 targetshouldbedirectory ? " -d" : "");
325 (void) signal(SIGPIPE, lostconn);
327 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
328 toremote(targ, argc, argv);
330 tolocal(argc, argv); /* Dest is local host. */
331 if (targetshouldbedirectory)
332 verifydir(argv[argc - 1]);
338 toremote(targ, argc, argv)
343 char *bp, *host, *src, *suser, *thost, *tuser;
349 if ((thost = strchr(argv[argc - 1], '@'))) {
352 tuser = argv[argc - 1];
355 else if (!okname(tuser))
358 thost = argv[argc - 1];
362 for (i = 0; i < argc - 1; i++) {
363 src = colon(argv[i]);
364 if (src) { /* remote to remote */
368 host = strchr(argv[i], '@');
369 len = strlen(SSH_PROGRAM) + strlen(argv[i]) +
370 strlen(src) + (tuser ? strlen(tuser) : 0) +
371 strlen(thost) + strlen(targ) + CMDNEEDS + 32;
377 suser = pwd->pw_name;
378 else if (!okname(suser))
381 "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
382 SSH_PROGRAM, verbose_mode ? " -v" : "",
383 suser, host, cmd, src,
384 tuser ? tuser : "", tuser ? "@" : "",
388 "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
389 SSH_PROGRAM, verbose_mode ? " -v" : "",
391 tuser ? tuser : "", tuser ? "@" : "",
394 fprintf(stderr, "Executing: %s\n", bp);
397 } else { /* local to remote */
399 len = strlen(targ) + CMDNEEDS + 20;
401 (void) sprintf(bp, "%s -t %s", cmd, targ);
403 if (do_cmd(host, tuser,
404 bp, &remin, &remout) < 0)
421 char *bp, *host, *src, *suser;
423 for (i = 0; i < argc - 1; i++) {
424 if (!(src = colon(argv[i]))) { /* Local to local. */
425 len = strlen(_PATH_CP) + strlen(argv[i]) +
426 strlen(argv[argc - 1]) + 20;
428 (void) sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
429 iamrecursive ? " -r" : "", pflag ? " -p" : "",
430 argv[i], argv[argc - 1]);
432 fprintf(stderr, "Executing: %s\n", bp);
441 if ((host = strchr(argv[i], '@')) == NULL) {
448 suser = pwd->pw_name;
449 else if (!okname(suser))
452 len = strlen(src) + CMDNEEDS + 20;
454 (void) sprintf(bp, "%s -f %s", cmd, src);
455 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
461 sink(1, argv + argc - 1);
476 int amt, fd, haderr, indx, result;
477 char *last, *name, buf[2048];
479 for (indx = 0; indx < argc; ++indx) {
482 if ((fd = open(name, O_RDONLY, 0)) < 0)
484 if (fstat(fd, &stb) < 0) {
485 syserr: run_err("%s: %s", name, strerror(errno));
488 switch (stb.st_mode & S_IFMT) {
498 run_err("%s: not a regular file", name);
501 if ((last = strrchr(name, '/')) == NULL)
508 * Make it compatible with possible future
509 * versions expecting microseconds.
511 (void) sprintf(buf, "T%lu 0 %lu 0\n",
512 (unsigned long) stb.st_mtime,
513 (unsigned long) stb.st_atime);
514 (void) write(remout, buf, strlen(buf));
518 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
519 (void) sprintf(buf, "C%04o %lu %s\n",
520 (unsigned int) (stb.st_mode & FILEMODEMASK),
521 (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);
535 totalbytes = stb.st_size;
538 /* Keep writing after an error so that we stay sync'd up. */
539 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
541 if (i + amt > stb.st_size)
542 amt = stb.st_size - i;
544 result = read(fd, bp->buf, amt);
546 haderr = result >= 0 ? EIO : errno;
549 (void) write(remout, bp->buf, amt);
551 result = write(remout, bp->buf, amt);
553 haderr = result >= 0 ? EIO : errno;
560 if (close(fd) < 0 && !haderr)
563 (void) write(remout, "", 1);
565 run_err("%s: %s", name, strerror(haderr));
577 char *last, *vect[1], path[1100];
579 if (!(dirp = opendir(name))) {
580 run_err("%s: %s", name, strerror(errno));
583 last = strrchr(name, '/');
589 (void) sprintf(path, "T%lu 0 %lu 0\n",
590 (unsigned long) statp->st_mtime,
591 (unsigned long) statp->st_atime);
592 (void) write(remout, path, strlen(path));
593 if (response() < 0) {
598 (void) sprintf(path, "D%04o %d %.1024s\n",
599 (unsigned int) (statp->st_mode & FILEMODEMASK),
602 fprintf(stderr, "Entering directory: %s", path);
603 (void) write(remout, path, strlen(path));
604 if (response() < 0) {
608 while ((dp = readdir(dirp))) {
611 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
613 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
614 run_err("%s/%s: name too long", name, dp->d_name);
617 (void) sprintf(path, "%s/%s", name, dp->d_name);
621 (void) closedir(dirp);
622 (void) write(remout, "E\n", 2);
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);
690 #define getnum(t) (t) = 0; \
691 while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
698 SCREWUP("mtime.sec not delimited");
701 SCREWUP("mtime.usec not delimited");
704 SCREWUP("atime.sec not delimited");
707 SCREWUP("atime.usec not delimited");
708 (void) write(remout, "", 1);
711 if (*cp != 'C' && *cp != 'D') {
713 * Check for the case "rcp remote:foo\* local:bar".
714 * In this case, the line "No match." can be returned
715 * by the shell before the rcp command on the remote is
716 * executed so the ^Aerror_message convention isn't
723 SCREWUP("expected control record");
726 for (++cp; cp < buf + 5; cp++) {
727 if (*cp < '0' || *cp > '7')
729 mode = (mode << 3) | (*cp - '0');
732 SCREWUP("mode not delimited");
734 for (size = 0; *cp >= '0' && *cp <= '9';)
735 size = size * 10 + (*cp++ - '0');
737 SCREWUP("size not delimited");
739 static char *namebuf;
743 need = strlen(targ) + strlen(cp) + 250;
745 namebuf = xmalloc(need);
746 (void) sprintf(namebuf, "%s%s%s", targ,
747 *targ ? "/" : "", cp);
752 exists = stat(np, &stb) == 0;
754 int mod_flag = pflag;
756 if (!S_ISDIR(stb.st_mode)) {
761 (void) chmod(np, mode);
763 /* Handle copying from a read-only
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");
937 vfprintf(stderr, fmt, ap);
938 fprintf(stderr, "\n");
943 /* Stuff below is from BSD rcp util.c. */
946 * Copyright (c) 1992, 1993
947 * The Regents of the University of California. All rights reserved.
949 * Redistribution and use in source and binary forms, with or without
950 * modification, are permitted provided that the following conditions
952 * 1. Redistributions of source code must retain the above copyright
953 * notice, this list of conditions and the following disclaimer.
954 * 2. Redistributions in binary form must reproduce the above copyright
955 * notice, this list of conditions and the following disclaimer in the
956 * documentation and/or other materials provided with the distribution.
957 * 3. All advertising materials mentioning features or use of this software
958 * must display the following acknowledgement:
959 * This product includes software developed by the University of
960 * California, Berkeley and its contributors.
961 * 4. Neither the name of the University nor the names of its contributors
962 * may be used to endorse or promote products derived from this software
963 * without specific prior written permission.
965 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
966 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
967 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
968 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
969 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
970 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
971 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
972 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
973 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
974 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
984 if (*cp == ':') /* Leading colon is part of file name. */
1002 if (!stat(cp, &stb)) {
1003 if (S_ISDIR(stb.st_mode))
1007 run_err("%s: %s", cp, strerror(errno));
1023 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1028 bad: fprintf(stderr, "%s: invalid user name", cp0);
1033 allocbuf(bp, fd, blksize)
1040 if (fstat(fd, &stb) < 0) {
1041 run_err("fstat: %s", strerror(errno));
1044 if (stb.st_blksize == 0)
1047 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1049 if (bp->cnt >= size)
1051 if (bp->buf == NULL)
1052 bp->buf = xmalloc(size);
1054 bp->buf = xrealloc(bp->buf, size);
1064 fprintf(stderr, "lost connection\n");
1070 alarmtimer(int wait)
1072 struct itimerval itv;
1074 itv.it_value.tv_sec = wait;
1075 itv.it_value.tv_usec = 0;
1076 itv.it_interval = itv.it_value;
1077 setitimer(ITIMER_REAL, &itv, NULL);
1081 updateprogressmeter(void)
1083 int save_errno = errno;
1092 static pid_t pgrp = -1;
1098 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1099 ctty_pgrp == pgrp));
1103 progressmeter(int flag)
1105 static const char prefixes[] = " KMGTP";
1106 static struct timeval lastupdate;
1107 static off_t lastsize;
1108 struct timeval now, td, wait;
1109 off_t cursize, abbrevsize;
1111 int ratio, barlength, i, remaining;
1115 (void) gettimeofday(&start, (struct timezone *) 0);
1119 if (foregroundproc() == 0)
1122 (void) gettimeofday(&now, (struct timezone *) 0);
1123 cursize = statbytes;
1124 if (totalbytes != 0) {
1125 ratio = 100.0 * cursize / totalbytes;
1126 ratio = MAX(ratio, 0);
1127 ratio = MIN(ratio, 100);
1131 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1133 barlength = getttywidth() - 51;
1134 if (barlength > 0) {
1135 i = barlength * ratio / 100;
1136 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1138 "*****************************************************************************"
1139 "*****************************************************************************",
1143 abbrevsize = cursize;
1144 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1148 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5qd %c%c ",
1149 (quad_t) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
1152 timersub(&now, &lastupdate, &wait);
1153 if (cursize > lastsize) {
1156 if (wait.tv_sec >= STALLTIME) {
1157 start.tv_sec += wait.tv_sec;
1158 start.tv_usec += wait.tv_usec;
1162 timersub(&now, &start, &td);
1163 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1165 if (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes) {
1166 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1168 } else if (wait.tv_sec >= STALLTIME) {
1169 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1172 remaining = (int) (totalbytes / (statbytes / elapsed) - elapsed);
1173 i = remaining / 3600;
1175 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1178 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1180 i = remaining % 3600;
1181 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1182 "%02d:%02d ETA", i / 60, i % 60);
1184 atomicio(write, fileno(stdout), buf, strlen(buf));
1187 signal(SIGALRM, (void *) updateprogressmeter);
1189 } else if (flag == 1) {
1191 write(fileno(stdout), "\n", 1);
1199 struct winsize winsize;
1201 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1202 return (winsize.ws_col ? winsize.ws_col : 80);