1 /* $OpenBSD: scp.c,v 1.187 2016/09/12 01:22:38 deraadt 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 #ifdef HAVE_SYS_STAT_H
78 # include <sys/stat.h>
83 # ifdef HAVE_SYS_POLL_H
84 # include <sys/poll.h>
87 #ifdef HAVE_SYS_TIME_H
88 # include <sys/time.h>
107 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
112 #include "atomicio.h"
113 #include "pathnames.h"
116 #include "progressmeter.h"
119 extern char *__progname;
121 #define COPY_BUFLEN 16384
123 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
124 int do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout);
126 /* Struct for addargs */
128 arglist remote_remote_args;
130 /* Bandwidth limit */
131 long long limit_kbps = 0;
132 struct bwlimit bwlimit;
134 /* Name of current file being transferred. */
137 /* This is set to non-zero to enable verbose mode. */
138 int verbose_mode = 0;
140 /* This is set to zero if the progressmeter is not desired. */
141 int showprogress = 1;
144 * This is set to non-zero if remote-remote copy should be piped
145 * through this process.
147 int throughlocal = 0;
149 /* This is the program to execute for the secured connection. ("ssh" or -S) */
150 char *ssh_program = _PATH_SSH_PROGRAM;
152 /* This is used to store the pid of ssh_program */
153 pid_t do_cmd_pid = -1;
158 if (do_cmd_pid > 1) {
159 kill(do_cmd_pid, signo ? signo : SIGTERM);
160 waitpid(do_cmd_pid, NULL, 0);
173 if (do_cmd_pid > 1) {
174 kill(do_cmd_pid, signo);
175 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
178 kill(getpid(), SIGSTOP);
183 do_local_cmd(arglist *a)
190 fatal("do_local_cmd: no arguments");
193 fprintf(stderr, "Executing:");
194 for (i = 0; i < a->num; i++)
195 fmprintf(stderr, " %s", a->list[i]);
196 fprintf(stderr, "\n");
198 if ((pid = fork()) == -1)
199 fatal("do_local_cmd: fork: %s", strerror(errno));
202 execvp(a->list[0], a->list);
208 signal(SIGTERM, killchild);
209 signal(SIGINT, killchild);
210 signal(SIGHUP, killchild);
212 while (waitpid(pid, &status, 0) == -1)
214 fatal("do_local_cmd: waitpid: %s", strerror(errno));
218 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
225 * This function executes the given command as the specified user on the
226 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
227 * assigns the input and output file descriptors on success.
231 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
233 int pin[2], pout[2], reserved[2];
237 "Executing: program %s host %s, user %s, command %s\n",
239 remuser ? remuser : "(unspecified)", cmd);
242 * Reserve two descriptors so that the real pipes won't get
243 * descriptors 0 and 1 because that will screw up dup2 below.
245 if (pipe(reserved) < 0)
246 fatal("pipe: %s", strerror(errno));
248 /* Create a socket pair for communicating with ssh. */
250 fatal("pipe: %s", strerror(errno));
252 fatal("pipe: %s", strerror(errno));
254 /* Free the reserved descriptors. */
258 signal(SIGTSTP, suspchild);
259 signal(SIGTTIN, suspchild);
260 signal(SIGTTOU, suspchild);
262 /* Fork a child to execute the command on the remote host using ssh. */
264 if (do_cmd_pid == 0) {
273 replacearg(&args, 0, "%s", ssh_program);
274 if (remuser != NULL) {
275 addargs(&args, "-l");
276 addargs(&args, "%s", remuser);
278 addargs(&args, "--");
279 addargs(&args, "%s", host);
280 addargs(&args, "%s", cmd);
282 execvp(ssh_program, args.list);
285 } else if (do_cmd_pid == -1) {
286 fatal("fork: %s", strerror(errno));
288 /* Parent. Close the other side, and return the local side. */
293 signal(SIGTERM, killchild);
294 signal(SIGINT, killchild);
295 signal(SIGHUP, killchild);
300 * This functions executes a command simlar to do_cmd(), but expects the
301 * input and output descriptors to be setup by a previous call to do_cmd().
302 * This way the input and output of two commands can be connected.
305 do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout)
312 "Executing: 2nd program %s host %s, user %s, command %s\n",
314 remuser ? remuser : "(unspecified)", cmd);
316 /* Fork a child to execute the command on the remote host using ssh. */
322 replacearg(&args, 0, "%s", ssh_program);
323 if (remuser != NULL) {
324 addargs(&args, "-l");
325 addargs(&args, "%s", remuser);
327 addargs(&args, "--");
328 addargs(&args, "%s", host);
329 addargs(&args, "%s", cmd);
331 execvp(ssh_program, args.list);
334 } else if (pid == -1) {
335 fatal("fork: %s", strerror(errno));
337 while (waitpid(pid, &status, 0) == -1)
339 fatal("do_cmd2: waitpid: %s", strerror(errno));
348 BUF *allocbuf(BUF *, int, int);
351 void run_err(const char *,...);
352 void verifydir(char *);
356 int errs, remin, remout;
357 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
360 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
363 void rsource(char *, struct stat *);
364 void sink(int, char *[]);
365 void source(int, char *[]);
366 void tolocal(int, char *[]);
367 void toremote(char *, int, char *[]);
371 main(int argc, char **argv)
373 int ch, fflag, tflag, status, n;
374 char *targ, **newargv;
379 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
384 /* Copy argv, because we modify it */
385 newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
386 for (n = 0; n < argc; n++)
387 newargv[n] = xstrdup(argv[n]);
390 __progname = ssh_get_progname(argv[0]);
392 memset(&args, '\0', sizeof(args));
393 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
394 args.list = remote_remote_args.list = NULL;
395 addargs(&args, "%s", ssh_program);
396 addargs(&args, "-x");
397 addargs(&args, "-oForwardAgent=no");
398 addargs(&args, "-oPermitLocalCommand=no");
399 addargs(&args, "-oClearAllForwardings=yes");
402 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
404 /* User-visible flags. */
410 addargs(&args, "-%c", ch);
411 addargs(&remote_remote_args, "-%c", ch);
420 addargs(&remote_remote_args, "-%c", ch);
421 addargs(&remote_remote_args, "%s", optarg);
422 addargs(&args, "-%c", ch);
423 addargs(&args, "%s", optarg);
426 addargs(&remote_remote_args, "-p");
427 addargs(&remote_remote_args, "%s", optarg);
428 addargs(&args, "-p");
429 addargs(&args, "%s", optarg);
432 addargs(&remote_remote_args, "-oBatchmode=yes");
433 addargs(&args, "-oBatchmode=yes");
436 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
440 limit_kbps *= 1024; /* kbps */
441 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
450 ssh_program = xstrdup(optarg);
453 addargs(&args, "-v");
454 addargs(&remote_remote_args, "-v");
458 addargs(&args, "-q");
459 addargs(&remote_remote_args, "-q");
463 /* Server options. */
465 targetshouldbedirectory = 1;
467 case 'f': /* "from" */
475 setmode(0, O_BINARY);
484 if ((pwd = getpwuid(userid = getuid())) == NULL)
485 fatal("unknown user %u", (u_int) userid);
487 if (!isatty(STDOUT_FILENO))
491 /* Cannot pledge: -p allows setuid/setgid files... */
493 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
500 remin = STDIN_FILENO;
501 remout = STDOUT_FILENO;
504 /* Follow "protocol", send data. */
517 targetshouldbedirectory = 1;
521 /* Command to be executed on remote system using "ssh". */
522 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
523 verbose_mode ? " -v" : "",
524 iamrecursive ? " -r" : "", pflag ? " -p" : "",
525 targetshouldbedirectory ? " -d" : "");
527 (void) signal(SIGPIPE, lostconn);
529 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
530 toremote(targ, argc, argv);
532 if (targetshouldbedirectory)
533 verifydir(argv[argc - 1]);
534 tolocal(argc, argv); /* Dest is local host. */
537 * Finally check the exit status of the ssh process, if one was forked
538 * and no error has occurred yet
540 if (do_cmd_pid != -1 && errs == 0) {
544 (void) close(remout);
545 if (waitpid(do_cmd_pid, &status, 0) == -1)
548 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
555 /* Callback from atomicio6 to update progress meter and limit bandwidth */
557 scpio(void *_cnt, size_t s)
559 off_t *cnt = (off_t *)_cnt;
563 bandwidth_limit(&bwlimit, s);
568 do_times(int fd, int verb, const struct stat *sb)
570 /* strlen(2^64) == 20; strlen(10^6) == 7 */
571 char buf[(20 + 7 + 2) * 2 + 2];
573 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
574 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
575 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
577 fprintf(stderr, "File mtime %lld atime %lld\n",
578 (long long)sb->st_mtime, (long long)sb->st_atime);
579 fprintf(stderr, "Sending file timestamps: %s", buf);
581 (void) atomicio(vwrite, fd, buf, strlen(buf));
586 toremote(char *targ, int argc, char **argv)
588 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
593 memset(&alist, '\0', sizeof(alist));
600 arg = xstrdup(argv[argc - 1]);
601 if ((thost = strrchr(arg, '@'))) {
612 if (tuser != NULL && !okname(tuser)) {
617 for (i = 0; i < argc - 1; i++) {
618 src = colon(argv[i]);
619 if (src && throughlocal) { /* extended remote to remote */
623 host = strrchr(argv[i], '@');
626 host = cleanhostname(host);
629 suser = pwd->pw_name;
630 else if (!okname(suser))
633 host = cleanhostname(argv[i]);
636 xasprintf(&bp, "%s -f %s%s", cmd,
637 *src == '-' ? "-- " : "", src);
638 if (do_cmd(host, suser, bp, &remin, &remout) < 0)
641 host = cleanhostname(thost);
642 xasprintf(&bp, "%s -t %s%s", cmd,
643 *targ == '-' ? "-- " : "", targ);
644 if (do_cmd2(host, tuser, bp, remin, remout) < 0)
648 (void) close(remout);
650 } else if (src) { /* standard remote to remote */
652 addargs(&alist, "%s", ssh_program);
653 addargs(&alist, "-x");
654 addargs(&alist, "-oClearAllForwardings=yes");
655 addargs(&alist, "-n");
656 for (j = 0; j < remote_remote_args.num; j++) {
657 addargs(&alist, "%s",
658 remote_remote_args.list[j]);
663 host = strrchr(argv[i], '@');
667 host = cleanhostname(host);
670 suser = pwd->pw_name;
671 else if (!okname(suser))
673 addargs(&alist, "-l");
674 addargs(&alist, "%s", suser);
676 host = cleanhostname(argv[i]);
678 addargs(&alist, "--");
679 addargs(&alist, "%s", host);
680 addargs(&alist, "%s", cmd);
681 addargs(&alist, "%s", src);
682 addargs(&alist, "%s%s%s:%s",
683 tuser ? tuser : "", tuser ? "@" : "",
685 if (do_local_cmd(&alist) != 0)
687 } else { /* local to remote */
689 xasprintf(&bp, "%s -t %s%s", cmd,
690 *targ == '-' ? "-- " : "", targ);
691 host = cleanhostname(thost);
692 if (do_cmd(host, tuser, bp, &remin,
706 tolocal(int argc, char **argv)
708 char *bp, *host, *src, *suser;
712 memset(&alist, '\0', sizeof(alist));
715 for (i = 0; i < argc - 1; i++) {
716 if (!(src = colon(argv[i]))) { /* Local to local. */
718 addargs(&alist, "%s", _PATH_CP);
720 addargs(&alist, "-r");
722 addargs(&alist, "-p");
723 addargs(&alist, "--");
724 addargs(&alist, "%s", argv[i]);
725 addargs(&alist, "%s", argv[argc-1]);
726 if (do_local_cmd(&alist))
733 if ((host = strrchr(argv[i], '@')) == NULL) {
740 suser = pwd->pw_name;
742 host = cleanhostname(host);
743 xasprintf(&bp, "%s -f %s%s",
744 cmd, *src == '-' ? "-- " : "", src);
745 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
751 sink(1, argv + argc - 1);
758 source(int argc, char **argv)
765 int fd = -1, haderr, indx;
766 char *last, *name, buf[2048], encname[PATH_MAX];
769 for (indx = 0; indx < argc; ++indx) {
773 while (len > 1 && name[len-1] == '/')
775 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
777 if (strchr(name, '\n') != NULL) {
778 strnvis(encname, name, sizeof(encname), VIS_NL);
781 if (fstat(fd, &stb) < 0) {
782 syserr: run_err("%s: %s", name, strerror(errno));
785 if (stb.st_size < 0) {
786 run_err("%s: %s", name, "Negative file size");
790 switch (stb.st_mode & S_IFMT) {
800 run_err("%s: not a regular file", name);
803 if ((last = strrchr(name, '/')) == NULL)
809 if (do_times(remout, verbose_mode, &stb) < 0)
812 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
813 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
814 (u_int) (stb.st_mode & FILEMODEMASK),
815 (long long)stb.st_size, last);
817 fmprintf(stderr, "Sending file modes: %s", buf);
818 (void) atomicio(vwrite, remout, buf, strlen(buf));
821 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
822 next: if (fd != -1) {
829 start_progress_meter(curfile, stb.st_size, &statbytes);
830 set_nonblock(remout);
831 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
833 if (i + (off_t)amt > stb.st_size)
834 amt = stb.st_size - i;
836 if ((nr = atomicio(read, fd,
837 bp->buf, amt)) != amt) {
839 memset(bp->buf + nr, 0, amt - nr);
842 /* Keep writing after error to retain sync */
844 (void)atomicio(vwrite, remout, bp->buf, amt);
845 memset(bp->buf, 0, amt);
848 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
852 unset_nonblock(remout);
855 if (close(fd) < 0 && !haderr)
860 (void) atomicio(vwrite, remout, "", 1);
862 run_err("%s: %s", name, strerror(haderr));
865 stop_progress_meter();
870 rsource(char *name, struct stat *statp)
874 char *last, *vect[1], path[PATH_MAX];
876 if (!(dirp = opendir(name))) {
877 run_err("%s: %s", name, strerror(errno));
880 last = strrchr(name, '/');
886 if (do_times(remout, verbose_mode, statp) < 0) {
891 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
892 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
894 fmprintf(stderr, "Entering directory: %s", path);
895 (void) atomicio(vwrite, remout, path, strlen(path));
896 if (response() < 0) {
900 while ((dp = readdir(dirp)) != NULL) {
903 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
905 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
906 run_err("%s/%s: name too long", name, dp->d_name);
909 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
913 (void) closedir(dirp);
914 (void) atomicio(vwrite, remout, "E\n", 2);
919 sink(int argc, char **argv)
929 int amt, exists, first, ofd;
930 mode_t mode, omode, mask;
931 off_t size, statbytes;
932 unsigned long long ull;
933 int setimes, targisdir, wrerrno = 0;
934 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
935 struct timeval tv[2];
939 #define SCREWUP(str) { why = str; goto screwup; }
941 setimes = targisdir = 0;
946 run_err("ambiguous target");
950 if (targetshouldbedirectory)
953 (void) atomicio(vwrite, remout, "", 1);
954 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
956 for (first = 1;; first = 0) {
958 if (atomicio(read, remin, cp, 1) != 1)
961 SCREWUP("unexpected <newline>");
963 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
964 SCREWUP("lost connection");
966 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
969 fmprintf(stderr, "Sink: %s", buf);
971 if (buf[0] == '\01' || buf[0] == '\02') {
972 if (iamremote == 0) {
973 (void) snmprintf(visbuf, sizeof(visbuf),
974 NULL, "%s", buf + 1);
975 (void) atomicio(vwrite, STDERR_FILENO,
976 visbuf, strlen(visbuf));
984 (void) atomicio(vwrite, remout, "", 1);
994 if (!isdigit((unsigned char)*cp))
995 SCREWUP("mtime.sec not present");
996 ull = strtoull(cp, &cp, 10);
997 if (!cp || *cp++ != ' ')
998 SCREWUP("mtime.sec not delimited");
999 if ((time_t)ull < 0 ||
1000 (unsigned long long)(time_t)ull != ull)
1001 setimes = 0; /* out of range */
1003 mtime.tv_usec = strtol(cp, &cp, 10);
1004 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1005 mtime.tv_usec > 999999)
1006 SCREWUP("mtime.usec not delimited");
1007 if (!isdigit((unsigned char)*cp))
1008 SCREWUP("atime.sec not present");
1009 ull = strtoull(cp, &cp, 10);
1010 if (!cp || *cp++ != ' ')
1011 SCREWUP("atime.sec not delimited");
1012 if ((time_t)ull < 0 ||
1013 (unsigned long long)(time_t)ull != ull)
1014 setimes = 0; /* out of range */
1016 atime.tv_usec = strtol(cp, &cp, 10);
1017 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1018 atime.tv_usec > 999999)
1019 SCREWUP("atime.usec not delimited");
1020 (void) atomicio(vwrite, remout, "", 1);
1023 if (*cp != 'C' && *cp != 'D') {
1025 * Check for the case "rcp remote:foo\* local:bar".
1026 * In this case, the line "No match." can be returned
1027 * by the shell before the rcp command on the remote is
1028 * executed so the ^Aerror_message convention isn't
1035 SCREWUP("expected control record");
1038 for (++cp; cp < buf + 5; cp++) {
1039 if (*cp < '0' || *cp > '7')
1040 SCREWUP("bad mode");
1041 mode = (mode << 3) | (*cp - '0');
1044 SCREWUP("mode not delimited");
1046 for (size = 0; isdigit((unsigned char)*cp);)
1047 size = size * 10 + (*cp++ - '0');
1049 SCREWUP("size not delimited");
1050 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
1051 run_err("error: unexpected filename: %s", cp);
1055 static char *namebuf;
1056 static size_t cursize;
1059 need = strlen(targ) + strlen(cp) + 250;
1060 if (need > cursize) {
1062 namebuf = xmalloc(need);
1065 (void) snprintf(namebuf, need, "%s%s%s", targ,
1066 strcmp(targ, "/") ? "/" : "", cp);
1071 exists = stat(np, &stb) == 0;
1072 if (buf[0] == 'D') {
1073 int mod_flag = pflag;
1075 SCREWUP("received directory without -r");
1077 if (!S_ISDIR(stb.st_mode)) {
1082 (void) chmod(np, mode);
1084 /* Handle copying from a read-only
1087 if (mkdir(np, mode | S_IRWXU) < 0)
1090 vect[0] = xstrdup(np);
1094 if (utimes(vect[0], tv) < 0)
1095 run_err("%s: set times: %s",
1096 vect[0], strerror(errno));
1099 (void) chmod(vect[0], mode);
1105 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1106 bad: run_err("%s: %s", np, strerror(errno));
1109 (void) atomicio(vwrite, remout, "", 1);
1110 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1119 start_progress_meter(curfile, size, &statbytes);
1120 set_nonblock(remin);
1121 for (count = i = 0; i < size; i += bp->cnt) {
1127 j = atomicio6(read, remin, cp, amt,
1130 run_err("%s", j != EPIPE ?
1132 "dropped connection");
1139 if (count == bp->cnt) {
1140 /* Keep reading so we stay sync'd up. */
1142 if (atomicio(vwrite, ofd, bp->buf,
1152 unset_nonblock(remin);
1153 if (count != 0 && wrerr == NO &&
1154 atomicio(vwrite, ofd, bp->buf, count) != count) {
1158 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1159 ftruncate(ofd, size) != 0) {
1160 run_err("%s: truncate: %s", np, strerror(errno));
1164 if (exists || omode != mode)
1166 if (fchmod(ofd, omode)) {
1167 #else /* HAVE_FCHMOD */
1168 if (chmod(np, omode)) {
1169 #endif /* HAVE_FCHMOD */
1170 run_err("%s: set mode: %s",
1171 np, strerror(errno));
1175 if (!exists && omode != mode)
1177 if (fchmod(ofd, omode & ~mask)) {
1178 #else /* HAVE_FCHMOD */
1179 if (chmod(np, omode & ~mask)) {
1180 #endif /* HAVE_FCHMOD */
1181 run_err("%s: set mode: %s",
1182 np, strerror(errno));
1186 if (close(ofd) == -1) {
1192 stop_progress_meter();
1193 if (setimes && wrerr == NO) {
1195 if (utimes(np, tv) < 0) {
1196 run_err("%s: set times: %s",
1197 np, strerror(errno));
1203 run_err("%s: %s", np, strerror(wrerrno));
1206 (void) atomicio(vwrite, remout, "", 1);
1213 run_err("protocol error: %s", why);
1220 char ch, *cp, resp, rbuf[2048], visbuf[2048];
1222 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1232 case 1: /* error, followed by error msg */
1233 case 2: /* fatal error, "" */
1235 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1238 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1242 (void) snmprintf(visbuf, sizeof(visbuf),
1243 NULL, "%s\n", rbuf);
1244 (void) atomicio(vwrite, STDERR_FILENO,
1245 visbuf, strlen(visbuf));
1258 (void) fprintf(stderr,
1259 "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1260 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1261 " [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1266 run_err(const char *fmt,...)
1272 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1273 (void) fprintf(fp, "%c", 0x01);
1274 (void) fprintf(fp, "scp: ");
1276 (void) vfprintf(fp, fmt, ap);
1278 (void) fprintf(fp, "\n");
1284 vfmprintf(stderr, fmt, ap);
1286 fprintf(stderr, "\n");
1295 if (!stat(cp, &stb)) {
1296 if (S_ISDIR(stb.st_mode))
1300 run_err("%s: %s", cp, strerror(errno));
1315 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1330 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
1335 allocbuf(BUF *bp, int fd, int blksize)
1338 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1341 if (fstat(fd, &stb) < 0) {
1342 run_err("fstat: %s", strerror(errno));
1345 size = ROUNDUP(stb.st_blksize, blksize);
1348 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1350 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1351 if (bp->cnt >= size)
1353 if (bp->buf == NULL)
1354 bp->buf = xmalloc(size);
1356 bp->buf = xreallocarray(bp->buf, 1, size);
1357 memset(bp->buf, 0, size);
1366 (void)write(STDERR_FILENO, "lost connection\n", 16);