1 /* $OpenBSD: scp.c,v 1.204 2019/02/10 11:15:52 djm 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 */
408 /* Copy argv, because we modify it */
409 newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
410 for (n = 0; n < argc; n++)
411 newargv[n] = xstrdup(argv[n]);
414 __progname = ssh_get_progname(argv[0]);
416 memset(&args, '\0', sizeof(args));
417 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
418 args.list = remote_remote_args.list = NULL;
419 addargs(&args, "%s", ssh_program);
420 addargs(&args, "-x");
421 addargs(&args, "-oForwardAgent=no");
422 addargs(&args, "-oPermitLocalCommand=no");
423 addargs(&args, "-oClearAllForwardings=yes");
424 addargs(&args, "-oRemoteCommand=none");
425 addargs(&args, "-oRequestTTY=no");
427 fflag = Tflag = tflag = 0;
428 while ((ch = getopt(argc, argv,
429 "dfl:prtTvBCc:i:P:q12346S:o:F:J:")) != -1) {
431 /* User-visible flags. */
433 fatal("SSH protocol v.1 is no longer supported");
441 addargs(&args, "-%c", ch);
442 addargs(&remote_remote_args, "-%c", ch);
452 addargs(&remote_remote_args, "-%c", ch);
453 addargs(&remote_remote_args, "%s", optarg);
454 addargs(&args, "-%c", ch);
455 addargs(&args, "%s", optarg);
458 sshport = a2port(optarg);
460 fatal("bad port \"%s\"\n", optarg);
463 addargs(&remote_remote_args, "-oBatchmode=yes");
464 addargs(&args, "-oBatchmode=yes");
467 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
471 limit_kbps *= 1024; /* kbps */
472 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
481 ssh_program = xstrdup(optarg);
484 addargs(&args, "-v");
485 addargs(&remote_remote_args, "-v");
489 addargs(&args, "-q");
490 addargs(&remote_remote_args, "-q");
494 /* Server options. */
496 targetshouldbedirectory = 1;
498 case 'f': /* "from" */
506 setmode(0, O_BINARY);
519 if ((pwd = getpwuid(userid = getuid())) == NULL)
520 fatal("unknown user %u", (u_int) userid);
522 if (!isatty(STDOUT_FILENO))
526 /* Cannot pledge: -p allows setuid/setgid files... */
528 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
535 remin = STDIN_FILENO;
536 remout = STDOUT_FILENO;
539 /* Follow "protocol", send data. */
546 sink(argc, argv, NULL);
552 targetshouldbedirectory = 1;
556 /* Command to be executed on remote system using "ssh". */
557 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
558 verbose_mode ? " -v" : "",
559 iamrecursive ? " -r" : "", pflag ? " -p" : "",
560 targetshouldbedirectory ? " -d" : "");
562 (void) signal(SIGPIPE, lostconn);
564 if (colon(argv[argc - 1])) /* Dest is remote host. */
565 toremote(argc, argv);
567 if (targetshouldbedirectory)
568 verifydir(argv[argc - 1]);
569 tolocal(argc, argv); /* Dest is local host. */
572 * Finally check the exit status of the ssh process, if one was forked
573 * and no error has occurred yet
575 if (do_cmd_pid != -1 && errs == 0) {
579 (void) close(remout);
580 if (waitpid(do_cmd_pid, &status, 0) == -1)
583 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
590 /* Callback from atomicio6 to update progress meter and limit bandwidth */
592 scpio(void *_cnt, size_t s)
594 off_t *cnt = (off_t *)_cnt;
597 refresh_progress_meter(0);
599 bandwidth_limit(&bwlimit, s);
604 do_times(int fd, int verb, const struct stat *sb)
606 /* strlen(2^64) == 20; strlen(10^6) == 7 */
607 char buf[(20 + 7 + 2) * 2 + 2];
609 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
610 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
611 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
613 fprintf(stderr, "File mtime %lld atime %lld\n",
614 (long long)sb->st_mtime, (long long)sb->st_atime);
615 fprintf(stderr, "Sending file timestamps: %s", buf);
617 (void) atomicio(vwrite, fd, buf, strlen(buf));
622 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
627 r = parse_uri("scp", uri, userp, hostp, portp, pathp);
628 if (r == 0 && *pathp == NULL)
629 *pathp = xstrdup(".");
633 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
635 append(char *cp, char ***ap, size_t *np)
639 if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
648 * Finds the start and end of the first brace pair in the pattern.
649 * returns 0 on success or -1 for invalid patterns.
652 find_brace(const char *pattern, int *startp, int *endp)
655 int in_bracket, brace_level;
657 *startp = *endp = -1;
658 in_bracket = brace_level = 0;
659 for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
660 switch (pattern[i]) {
662 /* skip next character */
663 if (pattern[i + 1] != '\0')
675 if (pattern[i + 1] == '}') {
676 /* Protect a single {}, for find(1), like csh */
688 /* Unbalanced brace */
691 if (--brace_level <= 0)
696 /* unbalanced brackets/braces */
697 if (*endp < 0 && (*startp >= 0 || in_bracket))
703 * Assembles and records a successfully-expanded pattern, returns -1 on
707 emit_expansion(const char *pattern, int brace_start, int brace_end,
708 int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
711 int o = 0, tail_len = strlen(pattern + brace_end + 1);
713 if ((cp = malloc(brace_start + (sel_end - sel_start) +
714 tail_len + 1)) == NULL)
717 /* Pattern before initial brace */
718 if (brace_start > 0) {
719 memcpy(cp, pattern, brace_start);
722 /* Current braced selection */
723 if (sel_end - sel_start > 0) {
724 memcpy(cp + o, pattern + sel_start,
725 sel_end - sel_start);
726 o += sel_end - sel_start;
728 /* Remainder of pattern after closing brace */
730 memcpy(cp + o, pattern + brace_end + 1, tail_len);
734 if (append(cp, patternsp, npatternsp) != 0) {
742 * Expand the first encountered brace in pattern, appending the expanded
743 * patterns it yielded to the *patternsp array.
745 * Returns 0 on success or -1 on allocation failure.
747 * Signals whether expansion was performed via *expanded and whether
748 * pattern was invalid via *invalid.
751 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
752 int *expanded, int *invalid)
755 int in_bracket, brace_start, brace_end, brace_level;
756 int sel_start, sel_end;
758 *invalid = *expanded = 0;
760 if (find_brace(pattern, &brace_start, &brace_end) != 0) {
763 } else if (brace_start == -1)
766 in_bracket = brace_level = 0;
767 for (i = sel_start = brace_start + 1; i < brace_end; i++) {
768 switch (pattern[i]) {
786 if (i < brace_end - 1)
790 if (pattern[i] == ',' || i == brace_end - 1) {
791 if (in_bracket || brace_level > 0)
793 /* End of a selection, emit an expanded pattern */
795 /* Adjust end index for last selection */
796 sel_end = (i == brace_end - 1) ? brace_end : i;
797 if (emit_expansion(pattern, brace_start, brace_end,
798 sel_start, sel_end, patternsp, npatternsp) != 0)
800 /* move on to the next selection */
805 if (in_bracket || brace_level > 0) {
814 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
816 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
818 char *cp, *cp2, **active = NULL, **done = NULL;
819 size_t i, nactive = 0, ndone = 0;
820 int ret = -1, invalid = 0, expanded = 0;
825 /* Start the worklist with the original pattern */
826 if ((cp = strdup(pattern)) == NULL)
828 if (append(cp, &active, &nactive) != 0) {
832 while (nactive > 0) {
833 cp = active[nactive - 1];
835 if (brace_expand_one(cp, &active, &nactive,
836 &expanded, &invalid) == -1) {
841 fatal("%s: invalid brace pattern \"%s\"", __func__, cp);
844 * Current entry expanded to new entries on the
845 * active list; discard the progenitor pattern.
851 * Pattern did not expand; append the finename component to
854 if ((cp2 = strrchr(cp, '/')) != NULL)
858 if (append(xstrdup(cp2), &done, &ndone) != 0) {
871 for (i = 0; i < nactive; i++)
874 for (i = 0; i < ndone; i++)
881 toremote(int argc, char **argv)
883 char *suser = NULL, *host = NULL, *src = NULL;
884 char *bp, *tuser, *thost, *targ;
885 int sport = -1, tport = -1;
890 memset(&alist, '\0', sizeof(alist));
894 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
896 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
901 if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
903 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
908 if (tuser != NULL && !okname(tuser)) {
913 /* Parse source files */
914 for (i = 0; i < argc - 1; i++) {
918 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
920 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
925 parse_user_host_path(argv[i], &suser, &host, &src);
927 if (suser != NULL && !okname(suser)) {
931 if (host && throughlocal) { /* extended remote to remote */
932 xasprintf(&bp, "%s -f %s%s", cmd,
933 *src == '-' ? "-- " : "", src);
934 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
937 xasprintf(&bp, "%s -t %s%s", cmd,
938 *targ == '-' ? "-- " : "", targ);
939 if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
943 (void) close(remout);
945 } else if (host) { /* standard remote to remote */
946 if (tport != -1 && tport != SSH_DEFAULT_PORT) {
947 /* This would require the remote support URIs */
948 fatal("target port not supported with two "
949 "remote hosts without the -3 option");
953 addargs(&alist, "%s", ssh_program);
954 addargs(&alist, "-x");
955 addargs(&alist, "-oClearAllForwardings=yes");
956 addargs(&alist, "-n");
957 for (j = 0; j < remote_remote_args.num; j++) {
958 addargs(&alist, "%s",
959 remote_remote_args.list[j]);
963 addargs(&alist, "-p");
964 addargs(&alist, "%d", sport);
967 addargs(&alist, "-l");
968 addargs(&alist, "%s", suser);
970 addargs(&alist, "--");
971 addargs(&alist, "%s", host);
972 addargs(&alist, "%s", cmd);
973 addargs(&alist, "%s", src);
974 addargs(&alist, "%s%s%s:%s",
975 tuser ? tuser : "", tuser ? "@" : "",
977 if (do_local_cmd(&alist) != 0)
979 } else { /* local to remote */
981 xasprintf(&bp, "%s -t %s%s", cmd,
982 *targ == '-' ? "-- " : "", targ);
983 if (do_cmd(thost, tuser, tport, bp, &remin,
1003 tolocal(int argc, char **argv)
1005 char *bp, *host = NULL, *src = NULL, *suser = NULL;
1007 int i, r, sport = -1;
1009 memset(&alist, '\0', sizeof(alist));
1012 for (i = 0; i < argc - 1; i++) {
1016 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1018 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1023 parse_user_host_path(argv[i], &suser, &host, &src);
1024 if (suser != NULL && !okname(suser)) {
1028 if (!host) { /* Local to local. */
1030 addargs(&alist, "%s", _PATH_CP);
1032 addargs(&alist, "-r");
1034 addargs(&alist, "-p");
1035 addargs(&alist, "--");
1036 addargs(&alist, "%s", argv[i]);
1037 addargs(&alist, "%s", argv[argc-1]);
1038 if (do_local_cmd(&alist))
1042 /* Remote to local. */
1043 xasprintf(&bp, "%s -f %s%s",
1044 cmd, *src == '-' ? "-- " : "", src);
1045 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
1051 sink(1, argv + argc - 1, src);
1052 (void) close(remin);
1053 remin = remout = -1;
1061 source(int argc, char **argv)
1068 int fd = -1, haderr, indx;
1069 char *last, *name, buf[2048], encname[PATH_MAX];
1072 for (indx = 0; indx < argc; ++indx) {
1076 while (len > 1 && name[len-1] == '/')
1078 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
1080 if (strchr(name, '\n') != NULL) {
1081 strnvis(encname, name, sizeof(encname), VIS_NL);
1084 if (fstat(fd, &stb) < 0) {
1085 syserr: run_err("%s: %s", name, strerror(errno));
1088 if (stb.st_size < 0) {
1089 run_err("%s: %s", name, "Negative file size");
1093 switch (stb.st_mode & S_IFMT) {
1098 rsource(name, &stb);
1103 run_err("%s: not a regular file", name);
1106 if ((last = strrchr(name, '/')) == NULL)
1112 if (do_times(remout, verbose_mode, &stb) < 0)
1115 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1116 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1117 (u_int) (stb.st_mode & FILEMODEMASK),
1118 (long long)stb.st_size, last);
1120 fmprintf(stderr, "Sending file modes: %s", buf);
1121 (void) atomicio(vwrite, remout, buf, strlen(buf));
1124 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1125 next: if (fd != -1) {
1132 start_progress_meter(curfile, stb.st_size, &statbytes);
1133 set_nonblock(remout);
1134 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1136 if (i + (off_t)amt > stb.st_size)
1137 amt = stb.st_size - i;
1139 if ((nr = atomicio(read, fd,
1140 bp->buf, amt)) != amt) {
1142 memset(bp->buf + nr, 0, amt - nr);
1145 /* Keep writing after error to retain sync */
1147 (void)atomicio(vwrite, remout, bp->buf, amt);
1148 memset(bp->buf, 0, amt);
1151 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1155 unset_nonblock(remout);
1158 if (close(fd) < 0 && !haderr)
1163 (void) atomicio(vwrite, remout, "", 1);
1165 run_err("%s: %s", name, strerror(haderr));
1168 stop_progress_meter();
1173 rsource(char *name, struct stat *statp)
1177 char *last, *vect[1], path[PATH_MAX];
1179 if (!(dirp = opendir(name))) {
1180 run_err("%s: %s", name, strerror(errno));
1183 last = strrchr(name, '/');
1189 if (do_times(remout, verbose_mode, statp) < 0) {
1194 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1195 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1197 fmprintf(stderr, "Entering directory: %s", path);
1198 (void) atomicio(vwrite, remout, path, strlen(path));
1199 if (response() < 0) {
1203 while ((dp = readdir(dirp)) != NULL) {
1206 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1208 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1209 run_err("%s/%s: name too long", name, dp->d_name);
1212 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1216 (void) closedir(dirp);
1217 (void) atomicio(vwrite, remout, "E\n", 2);
1221 #define TYPE_OVERFLOW(type, val) \
1222 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
1223 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1224 (sizeof(type) != 4 && sizeof(type) != 8))
1227 sink(int argc, char **argv, const char *src)
1237 int amt, exists, first, ofd;
1238 mode_t mode, omode, mask;
1239 off_t size, statbytes;
1240 unsigned long long ull;
1241 int setimes, targisdir, wrerrno = 0;
1242 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1243 char **patterns = NULL;
1244 size_t n, npatterns = 0;
1245 struct timeval tv[2];
1249 #define SCREWUP(str) { why = str; goto screwup; }
1251 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1252 SCREWUP("Unexpected off_t/time_t size");
1254 setimes = targisdir = 0;
1259 run_err("ambiguous target");
1263 if (targetshouldbedirectory)
1266 (void) atomicio(vwrite, remout, "", 1);
1267 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1269 if (src != NULL && !iamrecursive && !Tflag) {
1271 * Prepare to try to restrict incoming filenames to match
1272 * the requested destination file glob.
1274 if (brace_expand(src, &patterns, &npatterns) != 0)
1275 fatal("%s: could not expand pattern", __func__);
1277 for (first = 1;; first = 0) {
1279 if (atomicio(read, remin, cp, 1) != 1)
1282 SCREWUP("unexpected <newline>");
1284 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1285 SCREWUP("lost connection");
1287 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1290 fmprintf(stderr, "Sink: %s", buf);
1292 if (buf[0] == '\01' || buf[0] == '\02') {
1293 if (iamremote == 0) {
1294 (void) snmprintf(visbuf, sizeof(visbuf),
1295 NULL, "%s", buf + 1);
1296 (void) atomicio(vwrite, STDERR_FILENO,
1297 visbuf, strlen(visbuf));
1299 if (buf[0] == '\02')
1304 if (buf[0] == 'E') {
1305 (void) atomicio(vwrite, remout, "", 1);
1315 if (!isdigit((unsigned char)*cp))
1316 SCREWUP("mtime.sec not present");
1317 ull = strtoull(cp, &cp, 10);
1318 if (!cp || *cp++ != ' ')
1319 SCREWUP("mtime.sec not delimited");
1320 if (TYPE_OVERFLOW(time_t, ull))
1321 setimes = 0; /* out of range */
1323 mtime.tv_usec = strtol(cp, &cp, 10);
1324 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1325 mtime.tv_usec > 999999)
1326 SCREWUP("mtime.usec not delimited");
1327 if (!isdigit((unsigned char)*cp))
1328 SCREWUP("atime.sec not present");
1329 ull = strtoull(cp, &cp, 10);
1330 if (!cp || *cp++ != ' ')
1331 SCREWUP("atime.sec not delimited");
1332 if (TYPE_OVERFLOW(time_t, ull))
1333 setimes = 0; /* out of range */
1335 atime.tv_usec = strtol(cp, &cp, 10);
1336 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1337 atime.tv_usec > 999999)
1338 SCREWUP("atime.usec not delimited");
1339 (void) atomicio(vwrite, remout, "", 1);
1342 if (*cp != 'C' && *cp != 'D') {
1344 * Check for the case "rcp remote:foo\* local:bar".
1345 * In this case, the line "No match." can be returned
1346 * by the shell before the rcp command on the remote is
1347 * executed so the ^Aerror_message convention isn't
1354 SCREWUP("expected control record");
1357 for (++cp; cp < buf + 5; cp++) {
1358 if (*cp < '0' || *cp > '7')
1359 SCREWUP("bad mode");
1360 mode = (mode << 3) | (*cp - '0');
1365 SCREWUP("mode not delimited");
1367 if (!isdigit((unsigned char)*cp))
1368 SCREWUP("size not present");
1369 ull = strtoull(cp, &cp, 10);
1370 if (!cp || *cp++ != ' ')
1371 SCREWUP("size not delimited");
1372 if (TYPE_OVERFLOW(off_t, ull))
1373 SCREWUP("size out of range");
1376 if (*cp == '\0' || strchr(cp, '/') != NULL ||
1377 strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1378 run_err("error: unexpected filename: %s", cp);
1381 if (npatterns > 0) {
1382 for (n = 0; n < npatterns; n++) {
1383 if (fnmatch(patterns[n], cp, 0) == 0)
1387 SCREWUP("filename does not match request");
1390 static char *namebuf;
1391 static size_t cursize;
1394 need = strlen(targ) + strlen(cp) + 250;
1395 if (need > cursize) {
1397 namebuf = xmalloc(need);
1400 (void) snprintf(namebuf, need, "%s%s%s", targ,
1401 strcmp(targ, "/") ? "/" : "", cp);
1406 exists = stat(np, &stb) == 0;
1407 if (buf[0] == 'D') {
1408 int mod_flag = pflag;
1410 SCREWUP("received directory without -r");
1412 if (!S_ISDIR(stb.st_mode)) {
1417 (void) chmod(np, mode);
1419 /* Handle copying from a read-only
1422 if (mkdir(np, mode | S_IRWXU) < 0)
1425 vect[0] = xstrdup(np);
1429 if (utimes(vect[0], tv) < 0)
1430 run_err("%s: set times: %s",
1431 vect[0], strerror(errno));
1434 (void) chmod(vect[0], mode);
1440 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1441 bad: run_err("%s: %s", np, strerror(errno));
1444 (void) atomicio(vwrite, remout, "", 1);
1445 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1454 start_progress_meter(curfile, size, &statbytes);
1455 set_nonblock(remin);
1456 for (count = i = 0; i < size; i += bp->cnt) {
1462 j = atomicio6(read, remin, cp, amt,
1465 run_err("%s", j != EPIPE ?
1467 "dropped connection");
1474 if (count == bp->cnt) {
1475 /* Keep reading so we stay sync'd up. */
1477 if (atomicio(vwrite, ofd, bp->buf,
1487 unset_nonblock(remin);
1488 if (count != 0 && wrerr == NO &&
1489 atomicio(vwrite, ofd, bp->buf, count) != count) {
1493 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1494 ftruncate(ofd, size) != 0) {
1495 run_err("%s: truncate: %s", np, strerror(errno));
1499 if (exists || omode != mode)
1501 if (fchmod(ofd, omode)) {
1502 #else /* HAVE_FCHMOD */
1503 if (chmod(np, omode)) {
1504 #endif /* HAVE_FCHMOD */
1505 run_err("%s: set mode: %s",
1506 np, strerror(errno));
1510 if (!exists && omode != mode)
1512 if (fchmod(ofd, omode & ~mask)) {
1513 #else /* HAVE_FCHMOD */
1514 if (chmod(np, omode & ~mask)) {
1515 #endif /* HAVE_FCHMOD */
1516 run_err("%s: set mode: %s",
1517 np, strerror(errno));
1521 if (close(ofd) == -1) {
1527 stop_progress_meter();
1528 if (setimes && wrerr == NO) {
1530 if (utimes(np, tv) < 0) {
1531 run_err("%s: set times: %s",
1532 np, strerror(errno));
1538 run_err("%s: %s", np, strerror(wrerrno));
1541 (void) atomicio(vwrite, remout, "", 1);
1548 for (n = 0; n < npatterns; n++)
1553 for (n = 0; n < npatterns; n++)
1556 run_err("protocol error: %s", why);
1563 char ch, *cp, resp, rbuf[2048], visbuf[2048];
1565 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1575 case 1: /* error, followed by error msg */
1576 case 2: /* fatal error, "" */
1578 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1581 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1585 (void) snmprintf(visbuf, sizeof(visbuf),
1586 NULL, "%s\n", rbuf);
1587 (void) atomicio(vwrite, STDERR_FILENO,
1588 visbuf, strlen(visbuf));
1601 (void) fprintf(stderr,
1602 "usage: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1603 " [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
1604 " [-S program] source ... target\n");
1609 run_err(const char *fmt,...)
1615 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1616 (void) fprintf(fp, "%c", 0x01);
1617 (void) fprintf(fp, "scp: ");
1619 (void) vfprintf(fp, fmt, ap);
1621 (void) fprintf(fp, "\n");
1627 vfmprintf(stderr, fmt, ap);
1629 fprintf(stderr, "\n");
1638 if (!stat(cp, &stb)) {
1639 if (S_ISDIR(stb.st_mode))
1643 run_err("%s: %s", cp, strerror(errno));
1658 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1673 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
1678 allocbuf(BUF *bp, int fd, int blksize)
1681 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1684 if (fstat(fd, &stb) < 0) {
1685 run_err("fstat: %s", strerror(errno));
1688 size = ROUNDUP(stb.st_blksize, blksize);
1691 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1693 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1694 if (bp->cnt >= size)
1696 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1705 (void)write(STDERR_FILENO, "lost connection\n", 16);