1 /* $OpenBSD: scp.c,v 1.182 2015/04/24 01:36:00 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 #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>
107 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
112 #include "atomicio.h"
113 #include "pathnames.h"
116 #include "progressmeter.h"
118 extern char *__progname;
120 #define COPY_BUFLEN 16384
122 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
123 int do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout);
125 /* Struct for addargs */
127 arglist remote_remote_args;
129 /* Bandwidth limit */
130 long long limit_kbps = 0;
131 struct bwlimit bwlimit;
133 /* Name of current file being transferred. */
136 /* This is set to non-zero to enable verbose mode. */
137 int verbose_mode = 0;
139 /* This is set to zero if the progressmeter is not desired. */
140 int showprogress = 1;
143 * This is set to non-zero if remote-remote copy should be piped
144 * through this process.
146 int throughlocal = 0;
148 /* This is the program to execute for the secured connection. ("ssh" or -S) */
149 char *ssh_program = _PATH_SSH_PROGRAM;
151 /* This is used to store the pid of ssh_program */
152 pid_t do_cmd_pid = -1;
157 if (do_cmd_pid > 1) {
158 kill(do_cmd_pid, signo ? signo : SIGTERM);
159 waitpid(do_cmd_pid, NULL, 0);
172 if (do_cmd_pid > 1) {
173 kill(do_cmd_pid, signo);
174 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
177 kill(getpid(), SIGSTOP);
182 do_local_cmd(arglist *a)
189 fatal("do_local_cmd: no arguments");
192 fprintf(stderr, "Executing:");
193 for (i = 0; i < a->num; i++)
194 fprintf(stderr, " %s", a->list[i]);
195 fprintf(stderr, "\n");
197 if ((pid = fork()) == -1)
198 fatal("do_local_cmd: fork: %s", strerror(errno));
201 execvp(a->list[0], a->list);
207 signal(SIGTERM, killchild);
208 signal(SIGINT, killchild);
209 signal(SIGHUP, killchild);
211 while (waitpid(pid, &status, 0) == -1)
213 fatal("do_local_cmd: waitpid: %s", strerror(errno));
217 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
224 * This function executes the given command as the specified user on the
225 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
226 * assigns the input and output file descriptors on success.
230 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
232 int pin[2], pout[2], reserved[2];
236 "Executing: program %s host %s, user %s, command %s\n",
238 remuser ? remuser : "(unspecified)", cmd);
241 * Reserve two descriptors so that the real pipes won't get
242 * descriptors 0 and 1 because that will screw up dup2 below.
244 if (pipe(reserved) < 0)
245 fatal("pipe: %s", strerror(errno));
247 /* Create a socket pair for communicating with ssh. */
249 fatal("pipe: %s", strerror(errno));
251 fatal("pipe: %s", strerror(errno));
253 /* Free the reserved descriptors. */
257 signal(SIGTSTP, suspchild);
258 signal(SIGTTIN, suspchild);
259 signal(SIGTTOU, suspchild);
261 /* Fork a child to execute the command on the remote host using ssh. */
263 if (do_cmd_pid == 0) {
272 replacearg(&args, 0, "%s", ssh_program);
273 if (remuser != NULL) {
274 addargs(&args, "-l");
275 addargs(&args, "%s", remuser);
277 addargs(&args, "--");
278 addargs(&args, "%s", host);
279 addargs(&args, "%s", cmd);
281 execvp(ssh_program, args.list);
284 } else if (do_cmd_pid == -1) {
285 fatal("fork: %s", strerror(errno));
287 /* Parent. Close the other side, and return the local side. */
292 signal(SIGTERM, killchild);
293 signal(SIGINT, killchild);
294 signal(SIGHUP, killchild);
299 * This functions executes a command simlar to do_cmd(), but expects the
300 * input and output descriptors to be setup by a previous call to do_cmd().
301 * This way the input and output of two commands can be connected.
304 do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout)
311 "Executing: 2nd program %s host %s, user %s, command %s\n",
313 remuser ? remuser : "(unspecified)", cmd);
315 /* Fork a child to execute the command on the remote host using ssh. */
321 replacearg(&args, 0, "%s", ssh_program);
322 if (remuser != NULL) {
323 addargs(&args, "-l");
324 addargs(&args, "%s", remuser);
326 addargs(&args, "--");
327 addargs(&args, "%s", host);
328 addargs(&args, "%s", cmd);
330 execvp(ssh_program, args.list);
333 } else if (pid == -1) {
334 fatal("fork: %s", strerror(errno));
336 while (waitpid(pid, &status, 0) == -1)
338 fatal("do_cmd2: waitpid: %s", strerror(errno));
347 BUF *allocbuf(BUF *, int, int);
350 void run_err(const char *,...);
351 void verifydir(char *);
355 int errs, remin, remout;
356 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
359 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
362 void rsource(char *, struct stat *);
363 void sink(int, char *[]);
364 void source(int, char *[]);
365 void tolocal(int, char *[]);
366 void toremote(char *, int, char *[]);
370 main(int argc, char **argv)
372 int ch, fflag, tflag, status, n;
373 char *targ, **newargv;
378 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
381 /* Copy argv, because we modify it */
382 newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv));
383 for (n = 0; n < argc; n++)
384 newargv[n] = xstrdup(argv[n]);
387 __progname = ssh_get_progname(argv[0]);
389 memset(&args, '\0', sizeof(args));
390 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
391 args.list = remote_remote_args.list = NULL;
392 addargs(&args, "%s", ssh_program);
393 addargs(&args, "-x");
394 addargs(&args, "-oForwardAgent=no");
395 addargs(&args, "-oPermitLocalCommand=no");
396 addargs(&args, "-oClearAllForwardings=yes");
399 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
401 /* User-visible flags. */
407 addargs(&args, "-%c", ch);
408 addargs(&remote_remote_args, "-%c", ch);
417 addargs(&remote_remote_args, "-%c", ch);
418 addargs(&remote_remote_args, "%s", optarg);
419 addargs(&args, "-%c", ch);
420 addargs(&args, "%s", optarg);
423 addargs(&remote_remote_args, "-p");
424 addargs(&remote_remote_args, "%s", optarg);
425 addargs(&args, "-p");
426 addargs(&args, "%s", optarg);
429 addargs(&remote_remote_args, "-oBatchmode=yes");
430 addargs(&args, "-oBatchmode=yes");
433 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
437 limit_kbps *= 1024; /* kbps */
438 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
447 ssh_program = xstrdup(optarg);
450 addargs(&args, "-v");
451 addargs(&remote_remote_args, "-v");
455 addargs(&args, "-q");
456 addargs(&remote_remote_args, "-q");
460 /* Server options. */
462 targetshouldbedirectory = 1;
464 case 'f': /* "from" */
472 setmode(0, O_BINARY);
481 if ((pwd = getpwuid(userid = getuid())) == NULL)
482 fatal("unknown user %u", (u_int) userid);
484 if (!isatty(STDOUT_FILENO))
487 remin = STDIN_FILENO;
488 remout = STDOUT_FILENO;
491 /* Follow "protocol", send data. */
504 targetshouldbedirectory = 1;
508 /* Command to be executed on remote system using "ssh". */
509 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
510 verbose_mode ? " -v" : "",
511 iamrecursive ? " -r" : "", pflag ? " -p" : "",
512 targetshouldbedirectory ? " -d" : "");
514 (void) signal(SIGPIPE, lostconn);
516 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
517 toremote(targ, argc, argv);
519 if (targetshouldbedirectory)
520 verifydir(argv[argc - 1]);
521 tolocal(argc, argv); /* Dest is local host. */
524 * Finally check the exit status of the ssh process, if one was forked
525 * and no error has occurred yet
527 if (do_cmd_pid != -1 && errs == 0) {
531 (void) close(remout);
532 if (waitpid(do_cmd_pid, &status, 0) == -1)
535 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
542 /* Callback from atomicio6 to update progress meter and limit bandwidth */
544 scpio(void *_cnt, size_t s)
546 off_t *cnt = (off_t *)_cnt;
550 bandwidth_limit(&bwlimit, s);
555 do_times(int fd, int verb, const struct stat *sb)
557 /* strlen(2^64) == 20; strlen(10^6) == 7 */
558 char buf[(20 + 7 + 2) * 2 + 2];
560 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
561 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
562 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
564 fprintf(stderr, "File mtime %lld atime %lld\n",
565 (long long)sb->st_mtime, (long long)sb->st_atime);
566 fprintf(stderr, "Sending file timestamps: %s", buf);
568 (void) atomicio(vwrite, fd, buf, strlen(buf));
573 toremote(char *targ, int argc, char **argv)
575 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
580 memset(&alist, '\0', sizeof(alist));
587 arg = xstrdup(argv[argc - 1]);
588 if ((thost = strrchr(arg, '@'))) {
599 if (tuser != NULL && !okname(tuser)) {
604 for (i = 0; i < argc - 1; i++) {
605 src = colon(argv[i]);
606 if (src && throughlocal) { /* extended remote to remote */
610 host = strrchr(argv[i], '@');
613 host = cleanhostname(host);
616 suser = pwd->pw_name;
617 else if (!okname(suser))
620 host = cleanhostname(argv[i]);
623 xasprintf(&bp, "%s -f %s%s", cmd,
624 *src == '-' ? "-- " : "", src);
625 if (do_cmd(host, suser, bp, &remin, &remout) < 0)
628 host = cleanhostname(thost);
629 xasprintf(&bp, "%s -t %s%s", cmd,
630 *targ == '-' ? "-- " : "", targ);
631 if (do_cmd2(host, tuser, bp, remin, remout) < 0)
635 (void) close(remout);
637 } else if (src) { /* standard remote to remote */
639 addargs(&alist, "%s", ssh_program);
640 addargs(&alist, "-x");
641 addargs(&alist, "-oClearAllForwardings=yes");
642 addargs(&alist, "-n");
643 for (j = 0; j < remote_remote_args.num; j++) {
644 addargs(&alist, "%s",
645 remote_remote_args.list[j]);
650 host = strrchr(argv[i], '@');
654 host = cleanhostname(host);
657 suser = pwd->pw_name;
658 else if (!okname(suser))
660 addargs(&alist, "-l");
661 addargs(&alist, "%s", suser);
663 host = cleanhostname(argv[i]);
665 addargs(&alist, "--");
666 addargs(&alist, "%s", host);
667 addargs(&alist, "%s", cmd);
668 addargs(&alist, "%s", src);
669 addargs(&alist, "%s%s%s:%s",
670 tuser ? tuser : "", tuser ? "@" : "",
672 if (do_local_cmd(&alist) != 0)
674 } else { /* local to remote */
676 xasprintf(&bp, "%s -t %s%s", cmd,
677 *targ == '-' ? "-- " : "", targ);
678 host = cleanhostname(thost);
679 if (do_cmd(host, tuser, bp, &remin,
693 tolocal(int argc, char **argv)
695 char *bp, *host, *src, *suser;
699 memset(&alist, '\0', sizeof(alist));
702 for (i = 0; i < argc - 1; i++) {
703 if (!(src = colon(argv[i]))) { /* Local to local. */
705 addargs(&alist, "%s", _PATH_CP);
707 addargs(&alist, "-r");
709 addargs(&alist, "-p");
710 addargs(&alist, "--");
711 addargs(&alist, "%s", argv[i]);
712 addargs(&alist, "%s", argv[argc-1]);
713 if (do_local_cmd(&alist))
720 if ((host = strrchr(argv[i], '@')) == NULL) {
727 suser = pwd->pw_name;
729 host = cleanhostname(host);
730 xasprintf(&bp, "%s -f %s%s",
731 cmd, *src == '-' ? "-- " : "", src);
732 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
738 sink(1, argv + argc - 1);
745 source(int argc, char **argv)
752 int fd = -1, haderr, indx;
753 char *last, *name, buf[2048], encname[PATH_MAX];
756 for (indx = 0; indx < argc; ++indx) {
760 while (len > 1 && name[len-1] == '/')
762 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
764 if (strchr(name, '\n') != NULL) {
765 strnvis(encname, name, sizeof(encname), VIS_NL);
768 if (fstat(fd, &stb) < 0) {
769 syserr: run_err("%s: %s", name, strerror(errno));
772 if (stb.st_size < 0) {
773 run_err("%s: %s", name, "Negative file size");
777 switch (stb.st_mode & S_IFMT) {
787 run_err("%s: not a regular file", name);
790 if ((last = strrchr(name, '/')) == NULL)
796 if (do_times(remout, verbose_mode, &stb) < 0)
799 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
800 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
801 (u_int) (stb.st_mode & FILEMODEMASK),
802 (long long)stb.st_size, last);
804 fprintf(stderr, "Sending file modes: %s", buf);
806 (void) atomicio(vwrite, remout, buf, strlen(buf));
809 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
810 next: if (fd != -1) {
817 start_progress_meter(curfile, stb.st_size, &statbytes);
818 set_nonblock(remout);
819 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
821 if (i + (off_t)amt > stb.st_size)
822 amt = stb.st_size - i;
824 if ((nr = atomicio(read, fd,
825 bp->buf, amt)) != amt) {
827 memset(bp->buf + nr, 0, amt - nr);
830 /* Keep writing after error to retain sync */
832 (void)atomicio(vwrite, remout, bp->buf, amt);
833 memset(bp->buf, 0, amt);
836 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
840 unset_nonblock(remout);
842 stop_progress_meter();
845 if (close(fd) < 0 && !haderr)
850 (void) atomicio(vwrite, remout, "", 1);
852 run_err("%s: %s", name, strerror(haderr));
858 rsource(char *name, struct stat *statp)
862 char *last, *vect[1], path[PATH_MAX];
864 if (!(dirp = opendir(name))) {
865 run_err("%s: %s", name, strerror(errno));
868 last = strrchr(name, '/');
874 if (do_times(remout, verbose_mode, statp) < 0) {
879 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
880 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
882 fprintf(stderr, "Entering directory: %s", path);
883 (void) atomicio(vwrite, remout, path, strlen(path));
884 if (response() < 0) {
888 while ((dp = readdir(dirp)) != NULL) {
891 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
893 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
894 run_err("%s/%s: name too long", name, dp->d_name);
897 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
901 (void) closedir(dirp);
902 (void) atomicio(vwrite, remout, "E\n", 2);
907 sink(int argc, char **argv)
917 int amt, exists, first, ofd;
918 mode_t mode, omode, mask;
919 off_t size, statbytes;
920 unsigned long long ull;
921 int setimes, targisdir, wrerrno = 0;
922 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
923 struct timeval tv[2];
927 #define SCREWUP(str) { why = str; goto screwup; }
929 setimes = targisdir = 0;
934 run_err("ambiguous target");
938 if (targetshouldbedirectory)
941 (void) atomicio(vwrite, remout, "", 1);
942 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
944 for (first = 1;; first = 0) {
946 if (atomicio(read, remin, cp, 1) != 1)
949 SCREWUP("unexpected <newline>");
951 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
952 SCREWUP("lost connection");
954 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
957 fprintf(stderr, "Sink: %s", buf);
959 if (buf[0] == '\01' || buf[0] == '\02') {
961 (void) atomicio(vwrite, STDERR_FILENO,
962 buf + 1, strlen(buf + 1));
969 (void) atomicio(vwrite, remout, "", 1);
979 if (!isdigit((unsigned char)*cp))
980 SCREWUP("mtime.sec not present");
981 ull = strtoull(cp, &cp, 10);
982 if (!cp || *cp++ != ' ')
983 SCREWUP("mtime.sec not delimited");
984 if ((time_t)ull < 0 ||
985 (unsigned long long)(time_t)ull != ull)
986 setimes = 0; /* out of range */
988 mtime.tv_usec = strtol(cp, &cp, 10);
989 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
990 mtime.tv_usec > 999999)
991 SCREWUP("mtime.usec not delimited");
992 if (!isdigit((unsigned char)*cp))
993 SCREWUP("atime.sec not present");
994 ull = strtoull(cp, &cp, 10);
995 if (!cp || *cp++ != ' ')
996 SCREWUP("atime.sec not delimited");
997 if ((time_t)ull < 0 ||
998 (unsigned long long)(time_t)ull != ull)
999 setimes = 0; /* out of range */
1001 atime.tv_usec = strtol(cp, &cp, 10);
1002 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1003 atime.tv_usec > 999999)
1004 SCREWUP("atime.usec not delimited");
1005 (void) atomicio(vwrite, remout, "", 1);
1008 if (*cp != 'C' && *cp != 'D') {
1010 * Check for the case "rcp remote:foo\* local:bar".
1011 * In this case, the line "No match." can be returned
1012 * by the shell before the rcp command on the remote is
1013 * executed so the ^Aerror_message convention isn't
1020 SCREWUP("expected control record");
1023 for (++cp; cp < buf + 5; cp++) {
1024 if (*cp < '0' || *cp > '7')
1025 SCREWUP("bad mode");
1026 mode = (mode << 3) | (*cp - '0');
1029 SCREWUP("mode not delimited");
1031 for (size = 0; isdigit((unsigned char)*cp);)
1032 size = size * 10 + (*cp++ - '0');
1034 SCREWUP("size not delimited");
1035 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
1036 run_err("error: unexpected filename: %s", cp);
1040 static char *namebuf;
1041 static size_t cursize;
1044 need = strlen(targ) + strlen(cp) + 250;
1045 if (need > cursize) {
1047 namebuf = xmalloc(need);
1050 (void) snprintf(namebuf, need, "%s%s%s", targ,
1051 strcmp(targ, "/") ? "/" : "", cp);
1056 exists = stat(np, &stb) == 0;
1057 if (buf[0] == 'D') {
1058 int mod_flag = pflag;
1060 SCREWUP("received directory without -r");
1062 if (!S_ISDIR(stb.st_mode)) {
1067 (void) chmod(np, mode);
1069 /* Handle copying from a read-only
1072 if (mkdir(np, mode | S_IRWXU) < 0)
1075 vect[0] = xstrdup(np);
1079 if (utimes(vect[0], tv) < 0)
1080 run_err("%s: set times: %s",
1081 vect[0], strerror(errno));
1084 (void) chmod(vect[0], mode);
1090 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1091 bad: run_err("%s: %s", np, strerror(errno));
1094 (void) atomicio(vwrite, remout, "", 1);
1095 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1104 start_progress_meter(curfile, size, &statbytes);
1105 set_nonblock(remin);
1106 for (count = i = 0; i < size; i += bp->cnt) {
1112 j = atomicio6(read, remin, cp, amt,
1115 run_err("%s", j != EPIPE ?
1117 "dropped connection");
1124 if (count == bp->cnt) {
1125 /* Keep reading so we stay sync'd up. */
1127 if (atomicio(vwrite, ofd, bp->buf,
1137 unset_nonblock(remin);
1139 stop_progress_meter();
1140 if (count != 0 && wrerr == NO &&
1141 atomicio(vwrite, ofd, bp->buf, count) != count) {
1145 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1146 ftruncate(ofd, size) != 0) {
1147 run_err("%s: truncate: %s", np, strerror(errno));
1151 if (exists || omode != mode)
1153 if (fchmod(ofd, omode)) {
1154 #else /* HAVE_FCHMOD */
1155 if (chmod(np, omode)) {
1156 #endif /* HAVE_FCHMOD */
1157 run_err("%s: set mode: %s",
1158 np, strerror(errno));
1162 if (!exists && omode != mode)
1164 if (fchmod(ofd, omode & ~mask)) {
1165 #else /* HAVE_FCHMOD */
1166 if (chmod(np, omode & ~mask)) {
1167 #endif /* HAVE_FCHMOD */
1168 run_err("%s: set mode: %s",
1169 np, strerror(errno));
1173 if (close(ofd) == -1) {
1178 if (setimes && wrerr == NO) {
1180 if (utimes(np, tv) < 0) {
1181 run_err("%s: set times: %s",
1182 np, strerror(errno));
1188 run_err("%s: %s", np, strerror(wrerrno));
1191 (void) atomicio(vwrite, remout, "", 1);
1198 run_err("protocol error: %s", why);
1205 char ch, *cp, resp, rbuf[2048];
1207 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1217 case 1: /* error, followed by error msg */
1218 case 2: /* fatal error, "" */
1220 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1223 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1226 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1238 (void) fprintf(stderr,
1239 "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1240 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1241 " [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1246 run_err(const char *fmt,...)
1252 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1253 (void) fprintf(fp, "%c", 0x01);
1254 (void) fprintf(fp, "scp: ");
1256 (void) vfprintf(fp, fmt, ap);
1258 (void) fprintf(fp, "\n");
1264 vfprintf(stderr, fmt, ap);
1266 fprintf(stderr, "\n");
1275 if (!stat(cp, &stb)) {
1276 if (S_ISDIR(stb.st_mode))
1280 run_err("%s: %s", cp, strerror(errno));
1295 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1310 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1315 allocbuf(BUF *bp, int fd, int blksize)
1318 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1321 if (fstat(fd, &stb) < 0) {
1322 run_err("fstat: %s", strerror(errno));
1325 size = roundup(stb.st_blksize, blksize);
1328 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1330 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1331 if (bp->cnt >= size)
1333 if (bp->buf == NULL)
1334 bp->buf = xmalloc(size);
1336 bp->buf = xreallocarray(bp->buf, 1, size);
1337 memset(bp->buf, 0, size);
1346 (void)write(STDERR_FILENO, "lost connection\n", 16);