1 /* $OpenBSD: scp.c,v 1.203 2019/01/27 07:14:11 jmc 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>
111 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
117 #include "atomicio.h"
118 #include "pathnames.h"
121 #include "progressmeter.h"
124 extern char *__progname;
126 #define COPY_BUFLEN 16384
128 int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
129 int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
131 /* Struct for addargs */
133 arglist remote_remote_args;
135 /* Bandwidth limit */
136 long long limit_kbps = 0;
137 struct bwlimit bwlimit;
139 /* Name of current file being transferred. */
142 /* This is set to non-zero to enable verbose mode. */
143 int verbose_mode = 0;
145 /* This is set to zero if the progressmeter is not desired. */
146 int showprogress = 1;
149 * This is set to non-zero if remote-remote copy should be piped
150 * through this process.
152 int throughlocal = 0;
154 /* Non-standard port to use for the ssh connection or -1. */
157 /* This is the program to execute for the secured connection. ("ssh" or -S) */
158 char *ssh_program = _PATH_SSH_PROGRAM;
160 /* This is used to store the pid of ssh_program */
161 pid_t do_cmd_pid = -1;
166 if (do_cmd_pid > 1) {
167 kill(do_cmd_pid, signo ? signo : SIGTERM);
168 waitpid(do_cmd_pid, NULL, 0);
181 if (do_cmd_pid > 1) {
182 kill(do_cmd_pid, signo);
183 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
186 kill(getpid(), SIGSTOP);
191 do_local_cmd(arglist *a)
198 fatal("do_local_cmd: no arguments");
201 fprintf(stderr, "Executing:");
202 for (i = 0; i < a->num; i++)
203 fmprintf(stderr, " %s", a->list[i]);
204 fprintf(stderr, "\n");
206 if ((pid = fork()) == -1)
207 fatal("do_local_cmd: fork: %s", strerror(errno));
210 execvp(a->list[0], a->list);
216 signal(SIGTERM, killchild);
217 signal(SIGINT, killchild);
218 signal(SIGHUP, killchild);
220 while (waitpid(pid, &status, 0) == -1)
222 fatal("do_local_cmd: waitpid: %s", strerror(errno));
226 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
233 * This function executes the given command as the specified user on the
234 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
235 * assigns the input and output file descriptors on success.
239 do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
241 int pin[2], pout[2], reserved[2];
245 "Executing: program %s host %s, user %s, command %s\n",
247 remuser ? remuser : "(unspecified)", cmd);
253 * Reserve two descriptors so that the real pipes won't get
254 * descriptors 0 and 1 because that will screw up dup2 below.
256 if (pipe(reserved) < 0)
257 fatal("pipe: %s", strerror(errno));
259 /* Create a socket pair for communicating with ssh. */
261 fatal("pipe: %s", strerror(errno));
263 fatal("pipe: %s", strerror(errno));
265 /* Free the reserved descriptors. */
269 signal(SIGTSTP, suspchild);
270 signal(SIGTTIN, suspchild);
271 signal(SIGTTOU, suspchild);
273 /* Fork a child to execute the command on the remote host using ssh. */
275 if (do_cmd_pid == 0) {
284 replacearg(&args, 0, "%s", ssh_program);
286 addargs(&args, "-p");
287 addargs(&args, "%d", port);
289 if (remuser != NULL) {
290 addargs(&args, "-l");
291 addargs(&args, "%s", remuser);
293 addargs(&args, "--");
294 addargs(&args, "%s", host);
295 addargs(&args, "%s", cmd);
297 execvp(ssh_program, args.list);
300 } else if (do_cmd_pid == -1) {
301 fatal("fork: %s", strerror(errno));
303 /* Parent. Close the other side, and return the local side. */
308 signal(SIGTERM, killchild);
309 signal(SIGINT, killchild);
310 signal(SIGHUP, killchild);
315 * This function executes a command similar to do_cmd(), but expects the
316 * input and output descriptors to be setup by a previous call to do_cmd().
317 * This way the input and output of two commands can be connected.
320 do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
327 "Executing: 2nd program %s host %s, user %s, command %s\n",
329 remuser ? remuser : "(unspecified)", cmd);
334 /* Fork a child to execute the command on the remote host using ssh. */
340 replacearg(&args, 0, "%s", ssh_program);
342 addargs(&args, "-p");
343 addargs(&args, "%d", port);
345 if (remuser != NULL) {
346 addargs(&args, "-l");
347 addargs(&args, "%s", remuser);
349 addargs(&args, "--");
350 addargs(&args, "%s", host);
351 addargs(&args, "%s", cmd);
353 execvp(ssh_program, args.list);
356 } else if (pid == -1) {
357 fatal("fork: %s", strerror(errno));
359 while (waitpid(pid, &status, 0) == -1)
361 fatal("do_cmd2: waitpid: %s", strerror(errno));
370 BUF *allocbuf(BUF *, int, int);
373 void run_err(const char *,...);
374 void verifydir(char *);
378 int errs, remin, remout;
379 int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
382 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
385 void rsource(char *, struct stat *);
386 void sink(int, char *[], const char *);
387 void source(int, char *[]);
388 void tolocal(int, char *[]);
389 void toremote(int, char *[]);
393 main(int argc, char **argv)
395 int ch, fflag, tflag, status, n;
401 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
406 /* Copy argv, because we modify it */
407 newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
408 for (n = 0; n < argc; n++)
409 newargv[n] = xstrdup(argv[n]);
412 __progname = ssh_get_progname(argv[0]);
414 memset(&args, '\0', sizeof(args));
415 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
416 args.list = remote_remote_args.list = NULL;
417 addargs(&args, "%s", ssh_program);
418 addargs(&args, "-x");
419 addargs(&args, "-oForwardAgent=no");
420 addargs(&args, "-oPermitLocalCommand=no");
421 addargs(&args, "-oClearAllForwardings=yes");
422 addargs(&args, "-oRemoteCommand=none");
423 addargs(&args, "-oRequestTTY=no");
425 fflag = Tflag = tflag = 0;
426 while ((ch = getopt(argc, argv,
427 "dfl:prtTvBCc:i:P:q12346S:o:F:")) != -1) {
429 /* User-visible flags. */
431 fatal("SSH protocol v.1 is no longer supported");
439 addargs(&args, "-%c", ch);
440 addargs(&remote_remote_args, "-%c", ch);
449 addargs(&remote_remote_args, "-%c", ch);
450 addargs(&remote_remote_args, "%s", optarg);
451 addargs(&args, "-%c", ch);
452 addargs(&args, "%s", optarg);
455 sshport = a2port(optarg);
457 fatal("bad port \"%s\"\n", optarg);
460 addargs(&remote_remote_args, "-oBatchmode=yes");
461 addargs(&args, "-oBatchmode=yes");
464 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
468 limit_kbps *= 1024; /* kbps */
469 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
478 ssh_program = xstrdup(optarg);
481 addargs(&args, "-v");
482 addargs(&remote_remote_args, "-v");
486 addargs(&args, "-q");
487 addargs(&remote_remote_args, "-q");
491 /* Server options. */
493 targetshouldbedirectory = 1;
495 case 'f': /* "from" */
503 setmode(0, O_BINARY);
516 if ((pwd = getpwuid(userid = getuid())) == NULL)
517 fatal("unknown user %u", (u_int) userid);
519 if (!isatty(STDOUT_FILENO))
523 /* Cannot pledge: -p allows setuid/setgid files... */
525 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
532 remin = STDIN_FILENO;
533 remout = STDOUT_FILENO;
536 /* Follow "protocol", send data. */
543 sink(argc, argv, NULL);
549 targetshouldbedirectory = 1;
553 /* Command to be executed on remote system using "ssh". */
554 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
555 verbose_mode ? " -v" : "",
556 iamrecursive ? " -r" : "", pflag ? " -p" : "",
557 targetshouldbedirectory ? " -d" : "");
559 (void) signal(SIGPIPE, lostconn);
561 if (colon(argv[argc - 1])) /* Dest is remote host. */
562 toremote(argc, argv);
564 if (targetshouldbedirectory)
565 verifydir(argv[argc - 1]);
566 tolocal(argc, argv); /* Dest is local host. */
569 * Finally check the exit status of the ssh process, if one was forked
570 * and no error has occurred yet
572 if (do_cmd_pid != -1 && errs == 0) {
576 (void) close(remout);
577 if (waitpid(do_cmd_pid, &status, 0) == -1)
580 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
587 /* Callback from atomicio6 to update progress meter and limit bandwidth */
589 scpio(void *_cnt, size_t s)
591 off_t *cnt = (off_t *)_cnt;
595 bandwidth_limit(&bwlimit, s);
600 do_times(int fd, int verb, const struct stat *sb)
602 /* strlen(2^64) == 20; strlen(10^6) == 7 */
603 char buf[(20 + 7 + 2) * 2 + 2];
605 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
606 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
607 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
609 fprintf(stderr, "File mtime %lld atime %lld\n",
610 (long long)sb->st_mtime, (long long)sb->st_atime);
611 fprintf(stderr, "Sending file timestamps: %s", buf);
613 (void) atomicio(vwrite, fd, buf, strlen(buf));
618 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
623 r = parse_uri("scp", uri, userp, hostp, portp, pathp);
624 if (r == 0 && *pathp == NULL)
625 *pathp = xstrdup(".");
630 toremote(int argc, char **argv)
632 char *suser = NULL, *host = NULL, *src = NULL;
633 char *bp, *tuser, *thost, *targ;
634 int sport = -1, tport = -1;
639 memset(&alist, '\0', sizeof(alist));
643 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
645 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
650 if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
652 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
657 if (tuser != NULL && !okname(tuser)) {
662 /* Parse source files */
663 for (i = 0; i < argc - 1; i++) {
667 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
669 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
674 parse_user_host_path(argv[i], &suser, &host, &src);
676 if (suser != NULL && !okname(suser)) {
680 if (host && throughlocal) { /* extended remote to remote */
681 xasprintf(&bp, "%s -f %s%s", cmd,
682 *src == '-' ? "-- " : "", src);
683 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
686 xasprintf(&bp, "%s -t %s%s", cmd,
687 *targ == '-' ? "-- " : "", targ);
688 if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
692 (void) close(remout);
694 } else if (host) { /* standard remote to remote */
695 if (tport != -1 && tport != SSH_DEFAULT_PORT) {
696 /* This would require the remote support URIs */
697 fatal("target port not supported with two "
698 "remote hosts without the -3 option");
702 addargs(&alist, "%s", ssh_program);
703 addargs(&alist, "-x");
704 addargs(&alist, "-oClearAllForwardings=yes");
705 addargs(&alist, "-n");
706 for (j = 0; j < remote_remote_args.num; j++) {
707 addargs(&alist, "%s",
708 remote_remote_args.list[j]);
712 addargs(&alist, "-p");
713 addargs(&alist, "%d", sport);
716 addargs(&alist, "-l");
717 addargs(&alist, "%s", suser);
719 addargs(&alist, "--");
720 addargs(&alist, "%s", host);
721 addargs(&alist, "%s", cmd);
722 addargs(&alist, "%s", src);
723 addargs(&alist, "%s%s%s:%s",
724 tuser ? tuser : "", tuser ? "@" : "",
726 if (do_local_cmd(&alist) != 0)
728 } else { /* local to remote */
730 xasprintf(&bp, "%s -t %s%s", cmd,
731 *targ == '-' ? "-- " : "", targ);
732 if (do_cmd(thost, tuser, tport, bp, &remin,
752 tolocal(int argc, char **argv)
754 char *bp, *host = NULL, *src = NULL, *suser = NULL;
756 int i, r, sport = -1;
758 memset(&alist, '\0', sizeof(alist));
761 for (i = 0; i < argc - 1; i++) {
765 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
767 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
772 parse_user_host_path(argv[i], &suser, &host, &src);
773 if (suser != NULL && !okname(suser)) {
777 if (!host) { /* Local to local. */
779 addargs(&alist, "%s", _PATH_CP);
781 addargs(&alist, "-r");
783 addargs(&alist, "-p");
784 addargs(&alist, "--");
785 addargs(&alist, "%s", argv[i]);
786 addargs(&alist, "%s", argv[argc-1]);
787 if (do_local_cmd(&alist))
791 /* Remote to local. */
792 xasprintf(&bp, "%s -f %s%s",
793 cmd, *src == '-' ? "-- " : "", src);
794 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
800 sink(1, argv + argc - 1, src);
810 source(int argc, char **argv)
817 int fd = -1, haderr, indx;
818 char *last, *name, buf[2048], encname[PATH_MAX];
821 for (indx = 0; indx < argc; ++indx) {
825 while (len > 1 && name[len-1] == '/')
827 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
829 if (strchr(name, '\n') != NULL) {
830 strnvis(encname, name, sizeof(encname), VIS_NL);
833 if (fstat(fd, &stb) < 0) {
834 syserr: run_err("%s: %s", name, strerror(errno));
837 if (stb.st_size < 0) {
838 run_err("%s: %s", name, "Negative file size");
842 switch (stb.st_mode & S_IFMT) {
852 run_err("%s: not a regular file", name);
855 if ((last = strrchr(name, '/')) == NULL)
861 if (do_times(remout, verbose_mode, &stb) < 0)
864 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
865 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
866 (u_int) (stb.st_mode & FILEMODEMASK),
867 (long long)stb.st_size, last);
869 fmprintf(stderr, "Sending file modes: %s", buf);
870 (void) atomicio(vwrite, remout, buf, strlen(buf));
873 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
874 next: if (fd != -1) {
881 start_progress_meter(curfile, stb.st_size, &statbytes);
882 set_nonblock(remout);
883 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
885 if (i + (off_t)amt > stb.st_size)
886 amt = stb.st_size - i;
888 if ((nr = atomicio(read, fd,
889 bp->buf, amt)) != amt) {
891 memset(bp->buf + nr, 0, amt - nr);
894 /* Keep writing after error to retain sync */
896 (void)atomicio(vwrite, remout, bp->buf, amt);
897 memset(bp->buf, 0, amt);
900 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
904 unset_nonblock(remout);
907 if (close(fd) < 0 && !haderr)
912 (void) atomicio(vwrite, remout, "", 1);
914 run_err("%s: %s", name, strerror(haderr));
917 stop_progress_meter();
922 rsource(char *name, struct stat *statp)
926 char *last, *vect[1], path[PATH_MAX];
928 if (!(dirp = opendir(name))) {
929 run_err("%s: %s", name, strerror(errno));
932 last = strrchr(name, '/');
938 if (do_times(remout, verbose_mode, statp) < 0) {
943 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
944 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
946 fmprintf(stderr, "Entering directory: %s", path);
947 (void) atomicio(vwrite, remout, path, strlen(path));
948 if (response() < 0) {
952 while ((dp = readdir(dirp)) != NULL) {
955 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
957 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
958 run_err("%s/%s: name too long", name, dp->d_name);
961 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
965 (void) closedir(dirp);
966 (void) atomicio(vwrite, remout, "E\n", 2);
970 #define TYPE_OVERFLOW(type, val) \
971 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
972 (sizeof(type) == 8 && (val) > INT64_MAX) || \
973 (sizeof(type) != 4 && sizeof(type) != 8))
976 sink(int argc, char **argv, const char *src)
986 int amt, exists, first, ofd;
987 mode_t mode, omode, mask;
988 off_t size, statbytes;
989 unsigned long long ull;
990 int setimes, targisdir, wrerrno = 0;
991 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
992 char *src_copy = NULL, *restrict_pattern = NULL;
993 struct timeval tv[2];
997 #define SCREWUP(str) { why = str; goto screwup; }
999 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1000 SCREWUP("Unexpected off_t/time_t size");
1002 setimes = targisdir = 0;
1007 run_err("ambiguous target");
1011 if (targetshouldbedirectory)
1014 (void) atomicio(vwrite, remout, "", 1);
1015 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1017 if (src != NULL && !iamrecursive && !Tflag) {
1019 * Prepare to try to restrict incoming filenames to match
1020 * the requested destination file glob.
1022 if ((src_copy = strdup(src)) == NULL)
1023 fatal("strdup failed");
1024 if ((restrict_pattern = strrchr(src_copy, '/')) != NULL) {
1025 *restrict_pattern++ = '\0';
1028 for (first = 1;; first = 0) {
1030 if (atomicio(read, remin, cp, 1) != 1)
1033 SCREWUP("unexpected <newline>");
1035 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1036 SCREWUP("lost connection");
1038 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1041 fmprintf(stderr, "Sink: %s", buf);
1043 if (buf[0] == '\01' || buf[0] == '\02') {
1044 if (iamremote == 0) {
1045 (void) snmprintf(visbuf, sizeof(visbuf),
1046 NULL, "%s", buf + 1);
1047 (void) atomicio(vwrite, STDERR_FILENO,
1048 visbuf, strlen(visbuf));
1050 if (buf[0] == '\02')
1055 if (buf[0] == 'E') {
1056 (void) atomicio(vwrite, remout, "", 1);
1066 if (!isdigit((unsigned char)*cp))
1067 SCREWUP("mtime.sec not present");
1068 ull = strtoull(cp, &cp, 10);
1069 if (!cp || *cp++ != ' ')
1070 SCREWUP("mtime.sec not delimited");
1071 if (TYPE_OVERFLOW(time_t, ull))
1072 setimes = 0; /* out of range */
1074 mtime.tv_usec = strtol(cp, &cp, 10);
1075 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1076 mtime.tv_usec > 999999)
1077 SCREWUP("mtime.usec not delimited");
1078 if (!isdigit((unsigned char)*cp))
1079 SCREWUP("atime.sec not present");
1080 ull = strtoull(cp, &cp, 10);
1081 if (!cp || *cp++ != ' ')
1082 SCREWUP("atime.sec not delimited");
1083 if (TYPE_OVERFLOW(time_t, ull))
1084 setimes = 0; /* out of range */
1086 atime.tv_usec = strtol(cp, &cp, 10);
1087 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1088 atime.tv_usec > 999999)
1089 SCREWUP("atime.usec not delimited");
1090 (void) atomicio(vwrite, remout, "", 1);
1093 if (*cp != 'C' && *cp != 'D') {
1095 * Check for the case "rcp remote:foo\* local:bar".
1096 * In this case, the line "No match." can be returned
1097 * by the shell before the rcp command on the remote is
1098 * executed so the ^Aerror_message convention isn't
1105 SCREWUP("expected control record");
1108 for (++cp; cp < buf + 5; cp++) {
1109 if (*cp < '0' || *cp > '7')
1110 SCREWUP("bad mode");
1111 mode = (mode << 3) | (*cp - '0');
1116 SCREWUP("mode not delimited");
1118 if (!isdigit((unsigned char)*cp))
1119 SCREWUP("size not present");
1120 ull = strtoull(cp, &cp, 10);
1121 if (!cp || *cp++ != ' ')
1122 SCREWUP("size not delimited");
1123 if (TYPE_OVERFLOW(off_t, ull))
1124 SCREWUP("size out of range");
1127 if (*cp == '\0' || strchr(cp, '/') != NULL ||
1128 strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1129 run_err("error: unexpected filename: %s", cp);
1132 if (restrict_pattern != NULL &&
1133 fnmatch(restrict_pattern, cp, 0) != 0)
1134 SCREWUP("filename does not match request");
1136 static char *namebuf;
1137 static size_t cursize;
1140 need = strlen(targ) + strlen(cp) + 250;
1141 if (need > cursize) {
1143 namebuf = xmalloc(need);
1146 (void) snprintf(namebuf, need, "%s%s%s", targ,
1147 strcmp(targ, "/") ? "/" : "", cp);
1152 exists = stat(np, &stb) == 0;
1153 if (buf[0] == 'D') {
1154 int mod_flag = pflag;
1156 SCREWUP("received directory without -r");
1158 if (!S_ISDIR(stb.st_mode)) {
1163 (void) chmod(np, mode);
1165 /* Handle copying from a read-only
1168 if (mkdir(np, mode | S_IRWXU) < 0)
1171 vect[0] = xstrdup(np);
1175 if (utimes(vect[0], tv) < 0)
1176 run_err("%s: set times: %s",
1177 vect[0], strerror(errno));
1180 (void) chmod(vect[0], mode);
1186 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1187 bad: run_err("%s: %s", np, strerror(errno));
1190 (void) atomicio(vwrite, remout, "", 1);
1191 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1200 start_progress_meter(curfile, size, &statbytes);
1201 set_nonblock(remin);
1202 for (count = i = 0; i < size; i += bp->cnt) {
1208 j = atomicio6(read, remin, cp, amt,
1211 run_err("%s", j != EPIPE ?
1213 "dropped connection");
1220 if (count == bp->cnt) {
1221 /* Keep reading so we stay sync'd up. */
1223 if (atomicio(vwrite, ofd, bp->buf,
1233 unset_nonblock(remin);
1234 if (count != 0 && wrerr == NO &&
1235 atomicio(vwrite, ofd, bp->buf, count) != count) {
1239 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1240 ftruncate(ofd, size) != 0) {
1241 run_err("%s: truncate: %s", np, strerror(errno));
1245 if (exists || omode != mode)
1247 if (fchmod(ofd, omode)) {
1248 #else /* HAVE_FCHMOD */
1249 if (chmod(np, omode)) {
1250 #endif /* HAVE_FCHMOD */
1251 run_err("%s: set mode: %s",
1252 np, strerror(errno));
1256 if (!exists && omode != mode)
1258 if (fchmod(ofd, omode & ~mask)) {
1259 #else /* HAVE_FCHMOD */
1260 if (chmod(np, omode & ~mask)) {
1261 #endif /* HAVE_FCHMOD */
1262 run_err("%s: set mode: %s",
1263 np, strerror(errno));
1267 if (close(ofd) == -1) {
1273 stop_progress_meter();
1274 if (setimes && wrerr == NO) {
1276 if (utimes(np, tv) < 0) {
1277 run_err("%s: set times: %s",
1278 np, strerror(errno));
1284 run_err("%s: %s", np, strerror(wrerrno));
1287 (void) atomicio(vwrite, remout, "", 1);
1294 run_err("protocol error: %s", why);
1301 char ch, *cp, resp, rbuf[2048], visbuf[2048];
1303 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1313 case 1: /* error, followed by error msg */
1314 case 2: /* fatal error, "" */
1316 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1319 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1323 (void) snmprintf(visbuf, sizeof(visbuf),
1324 NULL, "%s\n", rbuf);
1325 (void) atomicio(vwrite, STDERR_FILENO,
1326 visbuf, strlen(visbuf));
1339 (void) fprintf(stderr,
1340 "usage: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1341 " [-l limit] [-o ssh_option] [-P port] [-S program] source ... target\n");
1346 run_err(const char *fmt,...)
1352 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1353 (void) fprintf(fp, "%c", 0x01);
1354 (void) fprintf(fp, "scp: ");
1356 (void) vfprintf(fp, fmt, ap);
1358 (void) fprintf(fp, "\n");
1364 vfmprintf(stderr, fmt, ap);
1366 fprintf(stderr, "\n");
1375 if (!stat(cp, &stb)) {
1376 if (S_ISDIR(stb.st_mode))
1380 run_err("%s: %s", cp, strerror(errno));
1395 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1410 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
1415 allocbuf(BUF *bp, int fd, int blksize)
1418 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1421 if (fstat(fd, &stb) < 0) {
1422 run_err("fstat: %s", strerror(errno));
1425 size = ROUNDUP(stb.st_blksize, blksize);
1428 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1430 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1431 if (bp->cnt >= size)
1433 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1442 (void)write(STDERR_FILENO, "lost connection\n", 16);