1 /* $OpenBSD: scp.c,v 1.186 2016/05/25 23:48:45 schwarze Exp $ */
3 * scp - secure remote copy. This is basically patched BSD rcp which
4 * uses ssh to do the data transfer (instead of using rcmd).
6 * NOTE: This version should NOT be suid root. (This uses ssh to
7 * do the transfer and ssh has the necessary privileges.)
9 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
18 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
19 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 * Copyright (c) 1983, 1990, 1992, 1993, 1995
46 * The Regents of the University of California. All rights reserved.
48 * Redistribution and use in source and binary forms, with or without
49 * modification, are permitted provided that the following conditions
51 * 1. Redistributions of source code must retain the above copyright
52 * notice, this list of conditions and the following disclaimer.
53 * 2. Redistributions in binary form must reproduce the above copyright
54 * notice, this list of conditions and the following disclaimer in the
55 * documentation and/or other materials provided with the distribution.
56 * 3. Neither the name of the University nor the names of its contributors
57 * may be used to endorse or promote products derived from this software
58 * without specific prior written permission.
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #ifdef HAVE_SYS_STAT_H
79 # include <sys/stat.h>
84 # ifdef HAVE_SYS_POLL_H
85 # include <sys/poll.h>
88 #ifdef HAVE_SYS_TIME_H
89 # include <sys/time.h>
108 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
113 #include "atomicio.h"
114 #include "pathnames.h"
117 #include "progressmeter.h"
120 extern char *__progname;
122 #define COPY_BUFLEN 16384
124 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
125 int do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout);
127 /* Struct for addargs */
129 arglist remote_remote_args;
131 /* Bandwidth limit */
132 long long limit_kbps = 0;
133 struct bwlimit bwlimit;
135 /* Name of current file being transferred. */
138 /* This is set to non-zero to enable verbose mode. */
139 int verbose_mode = 0;
141 /* This is set to zero if the progressmeter is not desired. */
142 int showprogress = 1;
145 * This is set to non-zero if remote-remote copy should be piped
146 * through this process.
148 int throughlocal = 0;
150 /* This is the program to execute for the secured connection. ("ssh" or -S) */
151 char *ssh_program = _PATH_SSH_PROGRAM;
153 /* This is used to store the pid of ssh_program */
154 pid_t do_cmd_pid = -1;
159 if (do_cmd_pid > 1) {
160 kill(do_cmd_pid, signo ? signo : SIGTERM);
161 waitpid(do_cmd_pid, NULL, 0);
174 if (do_cmd_pid > 1) {
175 kill(do_cmd_pid, signo);
176 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
179 kill(getpid(), SIGSTOP);
184 do_local_cmd(arglist *a)
191 fatal("do_local_cmd: no arguments");
194 fprintf(stderr, "Executing:");
195 for (i = 0; i < a->num; i++)
196 fmprintf(stderr, " %s", a->list[i]);
197 fprintf(stderr, "\n");
199 if ((pid = fork()) == -1)
200 fatal("do_local_cmd: fork: %s", strerror(errno));
203 execvp(a->list[0], a->list);
209 signal(SIGTERM, killchild);
210 signal(SIGINT, killchild);
211 signal(SIGHUP, killchild);
213 while (waitpid(pid, &status, 0) == -1)
215 fatal("do_local_cmd: waitpid: %s", strerror(errno));
219 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
226 * This function executes the given command as the specified user on the
227 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
228 * assigns the input and output file descriptors on success.
232 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
234 int pin[2], pout[2], reserved[2];
238 "Executing: program %s host %s, user %s, command %s\n",
240 remuser ? remuser : "(unspecified)", cmd);
243 * Reserve two descriptors so that the real pipes won't get
244 * descriptors 0 and 1 because that will screw up dup2 below.
246 if (pipe(reserved) < 0)
247 fatal("pipe: %s", strerror(errno));
249 /* Create a socket pair for communicating with ssh. */
251 fatal("pipe: %s", strerror(errno));
253 fatal("pipe: %s", strerror(errno));
255 /* Free the reserved descriptors. */
259 signal(SIGTSTP, suspchild);
260 signal(SIGTTIN, suspchild);
261 signal(SIGTTOU, suspchild);
263 /* Fork a child to execute the command on the remote host using ssh. */
265 if (do_cmd_pid == 0) {
274 replacearg(&args, 0, "%s", ssh_program);
275 if (remuser != NULL) {
276 addargs(&args, "-l");
277 addargs(&args, "%s", remuser);
279 addargs(&args, "--");
280 addargs(&args, "%s", host);
281 addargs(&args, "%s", cmd);
283 execvp(ssh_program, args.list);
286 } else if (do_cmd_pid == -1) {
287 fatal("fork: %s", strerror(errno));
289 /* Parent. Close the other side, and return the local side. */
294 signal(SIGTERM, killchild);
295 signal(SIGINT, killchild);
296 signal(SIGHUP, killchild);
301 * This functions executes a command simlar to do_cmd(), but expects the
302 * input and output descriptors to be setup by a previous call to do_cmd().
303 * This way the input and output of two commands can be connected.
306 do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout)
313 "Executing: 2nd program %s host %s, user %s, command %s\n",
315 remuser ? remuser : "(unspecified)", cmd);
317 /* Fork a child to execute the command on the remote host using ssh. */
323 replacearg(&args, 0, "%s", ssh_program);
324 if (remuser != NULL) {
325 addargs(&args, "-l");
326 addargs(&args, "%s", remuser);
328 addargs(&args, "--");
329 addargs(&args, "%s", host);
330 addargs(&args, "%s", cmd);
332 execvp(ssh_program, args.list);
335 } else if (pid == -1) {
336 fatal("fork: %s", strerror(errno));
338 while (waitpid(pid, &status, 0) == -1)
340 fatal("do_cmd2: waitpid: %s", strerror(errno));
349 BUF *allocbuf(BUF *, int, int);
352 void run_err(const char *,...);
353 void verifydir(char *);
357 int errs, remin, remout;
358 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
361 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
364 void rsource(char *, struct stat *);
365 void sink(int, char *[]);
366 void source(int, char *[]);
367 void tolocal(int, char *[]);
368 void toremote(char *, int, char *[]);
372 main(int argc, char **argv)
374 int ch, fflag, tflag, status, n;
375 char *targ, **newargv;
380 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
383 setlocale(LC_CTYPE, "");
385 /* Copy argv, because we modify it */
386 newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv));
387 for (n = 0; n < argc; n++)
388 newargv[n] = xstrdup(argv[n]);
391 __progname = ssh_get_progname(argv[0]);
393 memset(&args, '\0', sizeof(args));
394 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
395 args.list = remote_remote_args.list = NULL;
396 addargs(&args, "%s", ssh_program);
397 addargs(&args, "-x");
398 addargs(&args, "-oForwardAgent=no");
399 addargs(&args, "-oPermitLocalCommand=no");
400 addargs(&args, "-oClearAllForwardings=yes");
403 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
405 /* User-visible flags. */
411 addargs(&args, "-%c", ch);
412 addargs(&remote_remote_args, "-%c", ch);
421 addargs(&remote_remote_args, "-%c", ch);
422 addargs(&remote_remote_args, "%s", optarg);
423 addargs(&args, "-%c", ch);
424 addargs(&args, "%s", optarg);
427 addargs(&remote_remote_args, "-p");
428 addargs(&remote_remote_args, "%s", optarg);
429 addargs(&args, "-p");
430 addargs(&args, "%s", optarg);
433 addargs(&remote_remote_args, "-oBatchmode=yes");
434 addargs(&args, "-oBatchmode=yes");
437 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
441 limit_kbps *= 1024; /* kbps */
442 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
451 ssh_program = xstrdup(optarg);
454 addargs(&args, "-v");
455 addargs(&remote_remote_args, "-v");
459 addargs(&args, "-q");
460 addargs(&remote_remote_args, "-q");
464 /* Server options. */
466 targetshouldbedirectory = 1;
468 case 'f': /* "from" */
476 setmode(0, O_BINARY);
485 if ((pwd = getpwuid(userid = getuid())) == NULL)
486 fatal("unknown user %u", (u_int) userid);
488 if (!isatty(STDOUT_FILENO))
492 /* Cannot pledge: -p allows setuid/setgid files... */
494 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
501 remin = STDIN_FILENO;
502 remout = STDOUT_FILENO;
505 /* Follow "protocol", send data. */
518 targetshouldbedirectory = 1;
522 /* Command to be executed on remote system using "ssh". */
523 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
524 verbose_mode ? " -v" : "",
525 iamrecursive ? " -r" : "", pflag ? " -p" : "",
526 targetshouldbedirectory ? " -d" : "");
528 (void) signal(SIGPIPE, lostconn);
530 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
531 toremote(targ, argc, argv);
533 if (targetshouldbedirectory)
534 verifydir(argv[argc - 1]);
535 tolocal(argc, argv); /* Dest is local host. */
538 * Finally check the exit status of the ssh process, if one was forked
539 * and no error has occurred yet
541 if (do_cmd_pid != -1 && errs == 0) {
545 (void) close(remout);
546 if (waitpid(do_cmd_pid, &status, 0) == -1)
549 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
556 /* Callback from atomicio6 to update progress meter and limit bandwidth */
558 scpio(void *_cnt, size_t s)
560 off_t *cnt = (off_t *)_cnt;
564 bandwidth_limit(&bwlimit, s);
569 do_times(int fd, int verb, const struct stat *sb)
571 /* strlen(2^64) == 20; strlen(10^6) == 7 */
572 char buf[(20 + 7 + 2) * 2 + 2];
574 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
575 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
576 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
578 fprintf(stderr, "File mtime %lld atime %lld\n",
579 (long long)sb->st_mtime, (long long)sb->st_atime);
580 fprintf(stderr, "Sending file timestamps: %s", buf);
582 (void) atomicio(vwrite, fd, buf, strlen(buf));
587 toremote(char *targ, int argc, char **argv)
589 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
594 memset(&alist, '\0', sizeof(alist));
601 arg = xstrdup(argv[argc - 1]);
602 if ((thost = strrchr(arg, '@'))) {
613 if (tuser != NULL && !okname(tuser)) {
618 for (i = 0; i < argc - 1; i++) {
619 src = colon(argv[i]);
620 if (src && throughlocal) { /* extended remote to remote */
624 host = strrchr(argv[i], '@');
627 host = cleanhostname(host);
630 suser = pwd->pw_name;
631 else if (!okname(suser))
634 host = cleanhostname(argv[i]);
637 xasprintf(&bp, "%s -f %s%s", cmd,
638 *src == '-' ? "-- " : "", src);
639 if (do_cmd(host, suser, bp, &remin, &remout) < 0)
642 host = cleanhostname(thost);
643 xasprintf(&bp, "%s -t %s%s", cmd,
644 *targ == '-' ? "-- " : "", targ);
645 if (do_cmd2(host, tuser, bp, remin, remout) < 0)
649 (void) close(remout);
651 } else if (src) { /* standard remote to remote */
653 addargs(&alist, "%s", ssh_program);
654 addargs(&alist, "-x");
655 addargs(&alist, "-oClearAllForwardings=yes");
656 addargs(&alist, "-n");
657 for (j = 0; j < remote_remote_args.num; j++) {
658 addargs(&alist, "%s",
659 remote_remote_args.list[j]);
664 host = strrchr(argv[i], '@');
668 host = cleanhostname(host);
671 suser = pwd->pw_name;
672 else if (!okname(suser))
674 addargs(&alist, "-l");
675 addargs(&alist, "%s", suser);
677 host = cleanhostname(argv[i]);
679 addargs(&alist, "--");
680 addargs(&alist, "%s", host);
681 addargs(&alist, "%s", cmd);
682 addargs(&alist, "%s", src);
683 addargs(&alist, "%s%s%s:%s",
684 tuser ? tuser : "", tuser ? "@" : "",
686 if (do_local_cmd(&alist) != 0)
688 } else { /* local to remote */
690 xasprintf(&bp, "%s -t %s%s", cmd,
691 *targ == '-' ? "-- " : "", targ);
692 host = cleanhostname(thost);
693 if (do_cmd(host, tuser, bp, &remin,
707 tolocal(int argc, char **argv)
709 char *bp, *host, *src, *suser;
713 memset(&alist, '\0', sizeof(alist));
716 for (i = 0; i < argc - 1; i++) {
717 if (!(src = colon(argv[i]))) { /* Local to local. */
719 addargs(&alist, "%s", _PATH_CP);
721 addargs(&alist, "-r");
723 addargs(&alist, "-p");
724 addargs(&alist, "--");
725 addargs(&alist, "%s", argv[i]);
726 addargs(&alist, "%s", argv[argc-1]);
727 if (do_local_cmd(&alist))
734 if ((host = strrchr(argv[i], '@')) == NULL) {
741 suser = pwd->pw_name;
743 host = cleanhostname(host);
744 xasprintf(&bp, "%s -f %s%s",
745 cmd, *src == '-' ? "-- " : "", src);
746 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
752 sink(1, argv + argc - 1);
759 source(int argc, char **argv)
766 int fd = -1, haderr, indx;
767 char *last, *name, buf[2048], encname[PATH_MAX];
770 for (indx = 0; indx < argc; ++indx) {
774 while (len > 1 && name[len-1] == '/')
776 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
778 if (strchr(name, '\n') != NULL) {
779 strnvis(encname, name, sizeof(encname), VIS_NL);
782 if (fstat(fd, &stb) < 0) {
783 syserr: run_err("%s: %s", name, strerror(errno));
786 if (stb.st_size < 0) {
787 run_err("%s: %s", name, "Negative file size");
791 switch (stb.st_mode & S_IFMT) {
801 run_err("%s: not a regular file", name);
804 if ((last = strrchr(name, '/')) == NULL)
810 if (do_times(remout, verbose_mode, &stb) < 0)
813 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
814 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
815 (u_int) (stb.st_mode & FILEMODEMASK),
816 (long long)stb.st_size, last);
818 fmprintf(stderr, "Sending file modes: %s", buf);
819 (void) atomicio(vwrite, remout, buf, strlen(buf));
822 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
823 next: if (fd != -1) {
830 start_progress_meter(curfile, stb.st_size, &statbytes);
831 set_nonblock(remout);
832 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
834 if (i + (off_t)amt > stb.st_size)
835 amt = stb.st_size - i;
837 if ((nr = atomicio(read, fd,
838 bp->buf, amt)) != amt) {
840 memset(bp->buf + nr, 0, amt - nr);
843 /* Keep writing after error to retain sync */
845 (void)atomicio(vwrite, remout, bp->buf, amt);
846 memset(bp->buf, 0, amt);
849 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
853 unset_nonblock(remout);
856 if (close(fd) < 0 && !haderr)
861 (void) atomicio(vwrite, remout, "", 1);
863 run_err("%s: %s", name, strerror(haderr));
866 stop_progress_meter();
871 rsource(char *name, struct stat *statp)
875 char *last, *vect[1], path[PATH_MAX];
877 if (!(dirp = opendir(name))) {
878 run_err("%s: %s", name, strerror(errno));
881 last = strrchr(name, '/');
887 if (do_times(remout, verbose_mode, statp) < 0) {
892 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
893 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
895 fmprintf(stderr, "Entering directory: %s", path);
896 (void) atomicio(vwrite, remout, path, strlen(path));
897 if (response() < 0) {
901 while ((dp = readdir(dirp)) != NULL) {
904 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
906 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
907 run_err("%s/%s: name too long", name, dp->d_name);
910 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
914 (void) closedir(dirp);
915 (void) atomicio(vwrite, remout, "E\n", 2);
920 sink(int argc, char **argv)
930 int amt, exists, first, ofd;
931 mode_t mode, omode, mask;
932 off_t size, statbytes;
933 unsigned long long ull;
934 int setimes, targisdir, wrerrno = 0;
935 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
936 struct timeval tv[2];
940 #define SCREWUP(str) { why = str; goto screwup; }
942 setimes = targisdir = 0;
947 run_err("ambiguous target");
951 if (targetshouldbedirectory)
954 (void) atomicio(vwrite, remout, "", 1);
955 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
957 for (first = 1;; first = 0) {
959 if (atomicio(read, remin, cp, 1) != 1)
962 SCREWUP("unexpected <newline>");
964 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
965 SCREWUP("lost connection");
967 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
970 fmprintf(stderr, "Sink: %s", buf);
972 if (buf[0] == '\01' || buf[0] == '\02') {
973 if (iamremote == 0) {
974 (void) snmprintf(visbuf, sizeof(visbuf),
975 NULL, "%s", buf + 1);
976 (void) atomicio(vwrite, STDERR_FILENO,
977 visbuf, strlen(visbuf));
985 (void) atomicio(vwrite, remout, "", 1);
995 if (!isdigit((unsigned char)*cp))
996 SCREWUP("mtime.sec not present");
997 ull = strtoull(cp, &cp, 10);
998 if (!cp || *cp++ != ' ')
999 SCREWUP("mtime.sec not delimited");
1000 if ((time_t)ull < 0 ||
1001 (unsigned long long)(time_t)ull != ull)
1002 setimes = 0; /* out of range */
1004 mtime.tv_usec = strtol(cp, &cp, 10);
1005 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1006 mtime.tv_usec > 999999)
1007 SCREWUP("mtime.usec not delimited");
1008 if (!isdigit((unsigned char)*cp))
1009 SCREWUP("atime.sec not present");
1010 ull = strtoull(cp, &cp, 10);
1011 if (!cp || *cp++ != ' ')
1012 SCREWUP("atime.sec not delimited");
1013 if ((time_t)ull < 0 ||
1014 (unsigned long long)(time_t)ull != ull)
1015 setimes = 0; /* out of range */
1017 atime.tv_usec = strtol(cp, &cp, 10);
1018 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1019 atime.tv_usec > 999999)
1020 SCREWUP("atime.usec not delimited");
1021 (void) atomicio(vwrite, remout, "", 1);
1024 if (*cp != 'C' && *cp != 'D') {
1026 * Check for the case "rcp remote:foo\* local:bar".
1027 * In this case, the line "No match." can be returned
1028 * by the shell before the rcp command on the remote is
1029 * executed so the ^Aerror_message convention isn't
1036 SCREWUP("expected control record");
1039 for (++cp; cp < buf + 5; cp++) {
1040 if (*cp < '0' || *cp > '7')
1041 SCREWUP("bad mode");
1042 mode = (mode << 3) | (*cp - '0');
1045 SCREWUP("mode not delimited");
1047 for (size = 0; isdigit((unsigned char)*cp);)
1048 size = size * 10 + (*cp++ - '0');
1050 SCREWUP("size not delimited");
1051 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
1052 run_err("error: unexpected filename: %s", cp);
1056 static char *namebuf;
1057 static size_t cursize;
1060 need = strlen(targ) + strlen(cp) + 250;
1061 if (need > cursize) {
1063 namebuf = xmalloc(need);
1066 (void) snprintf(namebuf, need, "%s%s%s", targ,
1067 strcmp(targ, "/") ? "/" : "", cp);
1072 exists = stat(np, &stb) == 0;
1073 if (buf[0] == 'D') {
1074 int mod_flag = pflag;
1076 SCREWUP("received directory without -r");
1078 if (!S_ISDIR(stb.st_mode)) {
1083 (void) chmod(np, mode);
1085 /* Handle copying from a read-only
1088 if (mkdir(np, mode | S_IRWXU) < 0)
1091 vect[0] = xstrdup(np);
1095 if (utimes(vect[0], tv) < 0)
1096 run_err("%s: set times: %s",
1097 vect[0], strerror(errno));
1100 (void) chmod(vect[0], mode);
1106 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1107 bad: run_err("%s: %s", np, strerror(errno));
1110 (void) atomicio(vwrite, remout, "", 1);
1111 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1120 start_progress_meter(curfile, size, &statbytes);
1121 set_nonblock(remin);
1122 for (count = i = 0; i < size; i += bp->cnt) {
1128 j = atomicio6(read, remin, cp, amt,
1131 run_err("%s", j != EPIPE ?
1133 "dropped connection");
1140 if (count == bp->cnt) {
1141 /* Keep reading so we stay sync'd up. */
1143 if (atomicio(vwrite, ofd, bp->buf,
1153 unset_nonblock(remin);
1154 if (count != 0 && wrerr == NO &&
1155 atomicio(vwrite, ofd, bp->buf, count) != count) {
1159 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1160 ftruncate(ofd, size) != 0) {
1161 run_err("%s: truncate: %s", np, strerror(errno));
1165 if (exists || omode != mode)
1167 if (fchmod(ofd, omode)) {
1168 #else /* HAVE_FCHMOD */
1169 if (chmod(np, omode)) {
1170 #endif /* HAVE_FCHMOD */
1171 run_err("%s: set mode: %s",
1172 np, strerror(errno));
1176 if (!exists && omode != mode)
1178 if (fchmod(ofd, omode & ~mask)) {
1179 #else /* HAVE_FCHMOD */
1180 if (chmod(np, omode & ~mask)) {
1181 #endif /* HAVE_FCHMOD */
1182 run_err("%s: set mode: %s",
1183 np, strerror(errno));
1187 if (close(ofd) == -1) {
1193 stop_progress_meter();
1194 if (setimes && wrerr == NO) {
1196 if (utimes(np, tv) < 0) {
1197 run_err("%s: set times: %s",
1198 np, strerror(errno));
1204 run_err("%s: %s", np, strerror(wrerrno));
1207 (void) atomicio(vwrite, remout, "", 1);
1214 run_err("protocol error: %s", why);
1221 char ch, *cp, resp, rbuf[2048], visbuf[2048];
1223 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1233 case 1: /* error, followed by error msg */
1234 case 2: /* fatal error, "" */
1236 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1239 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1243 (void) snmprintf(visbuf, sizeof(visbuf),
1244 NULL, "%s\n", rbuf);
1245 (void) atomicio(vwrite, STDERR_FILENO,
1246 visbuf, strlen(visbuf));
1259 (void) fprintf(stderr,
1260 "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1261 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1262 " [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1267 run_err(const char *fmt,...)
1273 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1274 (void) fprintf(fp, "%c", 0x01);
1275 (void) fprintf(fp, "scp: ");
1277 (void) vfprintf(fp, fmt, ap);
1279 (void) fprintf(fp, "\n");
1285 vfmprintf(stderr, fmt, ap);
1287 fprintf(stderr, "\n");
1296 if (!stat(cp, &stb)) {
1297 if (S_ISDIR(stb.st_mode))
1301 run_err("%s: %s", cp, strerror(errno));
1316 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1331 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
1336 allocbuf(BUF *bp, int fd, int blksize)
1339 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1342 if (fstat(fd, &stb) < 0) {
1343 run_err("fstat: %s", strerror(errno));
1346 size = roundup(stb.st_blksize, blksize);
1349 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1351 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1352 if (bp->cnt >= size)
1354 if (bp->buf == NULL)
1355 bp->buf = xmalloc(size);
1357 bp->buf = xreallocarray(bp->buf, 1, size);
1358 memset(bp->buf, 0, size);
1367 (void)write(STDERR_FILENO, "lost connection\n", 16);