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 */
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(".");
629 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
631 append(char *cp, char ***ap, size_t *np)
635 if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
644 * Finds the start and end of the first brace pair in the pattern.
645 * returns 0 on success or -1 for invalid patterns.
648 find_brace(const char *pattern, int *startp, int *endp)
651 int in_bracket, brace_level;
653 *startp = *endp = -1;
654 in_bracket = brace_level = 0;
655 for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
656 switch (pattern[i]) {
658 /* skip next character */
659 if (pattern[i + 1] != '\0')
671 if (pattern[i + 1] == '}') {
672 /* Protect a single {}, for find(1), like csh */
684 /* Unbalanced brace */
687 if (--brace_level <= 0)
692 /* unbalanced brackets/braces */
693 if (*endp < 0 && (*startp >= 0 || in_bracket))
699 * Assembles and records a successfully-expanded pattern, returns -1 on
703 emit_expansion(const char *pattern, int brace_start, int brace_end,
704 int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
707 int o = 0, tail_len = strlen(pattern + brace_end + 1);
709 if ((cp = malloc(brace_start + (sel_end - sel_start) +
710 tail_len + 1)) == NULL)
713 /* Pattern before initial brace */
714 if (brace_start > 0) {
715 memcpy(cp, pattern, brace_start);
718 /* Current braced selection */
719 if (sel_end - sel_start > 0) {
720 memcpy(cp + o, pattern + sel_start,
721 sel_end - sel_start);
722 o += sel_end - sel_start;
724 /* Remainder of pattern after closing brace */
726 memcpy(cp + o, pattern + brace_end + 1, tail_len);
730 if (append(cp, patternsp, npatternsp) != 0) {
738 * Expand the first encountered brace in pattern, appending the expanded
739 * patterns it yielded to the *patternsp array.
741 * Returns 0 on success or -1 on allocation failure.
743 * Signals whether expansion was performed via *expanded and whether
744 * pattern was invalid via *invalid.
747 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
748 int *expanded, int *invalid)
751 int in_bracket, brace_start, brace_end, brace_level;
752 int sel_start, sel_end;
754 *invalid = *expanded = 0;
756 if (find_brace(pattern, &brace_start, &brace_end) != 0) {
759 } else if (brace_start == -1)
762 in_bracket = brace_level = 0;
763 for (i = sel_start = brace_start + 1; i < brace_end; i++) {
764 switch (pattern[i]) {
782 if (i < brace_end - 1)
786 if (pattern[i] == ',' || i == brace_end - 1) {
787 if (in_bracket || brace_level > 0)
789 /* End of a selection, emit an expanded pattern */
791 /* Adjust end index for last selection */
792 sel_end = (i == brace_end - 1) ? brace_end : i;
793 if (emit_expansion(pattern, brace_start, brace_end,
794 sel_start, sel_end, patternsp, npatternsp) != 0)
796 /* move on to the next selection */
801 if (in_bracket || brace_level > 0) {
810 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
812 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
814 char *cp, *cp2, **active = NULL, **done = NULL;
815 size_t i, nactive = 0, ndone = 0;
816 int ret = -1, invalid = 0, expanded = 0;
821 /* Start the worklist with the original pattern */
822 if ((cp = strdup(pattern)) == NULL)
824 if (append(cp, &active, &nactive) != 0) {
828 while (nactive > 0) {
829 cp = active[nactive - 1];
831 if (brace_expand_one(cp, &active, &nactive,
832 &expanded, &invalid) == -1) {
837 fatal("%s: invalid brace pattern \"%s\"", __func__, cp);
840 * Current entry expanded to new entries on the
841 * active list; discard the progenitor pattern.
847 * Pattern did not expand; append the finename component to
850 if ((cp2 = strrchr(cp, '/')) != NULL)
854 if (append(xstrdup(cp2), &done, &ndone) != 0) {
867 for (i = 0; i < nactive; i++)
870 for (i = 0; i < ndone; i++)
877 toremote(int argc, char **argv)
879 char *suser = NULL, *host = NULL, *src = NULL;
880 char *bp, *tuser, *thost, *targ;
881 int sport = -1, tport = -1;
886 memset(&alist, '\0', sizeof(alist));
890 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
892 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
897 if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
899 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
904 if (tuser != NULL && !okname(tuser)) {
909 /* Parse source files */
910 for (i = 0; i < argc - 1; i++) {
914 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
916 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
921 parse_user_host_path(argv[i], &suser, &host, &src);
923 if (suser != NULL && !okname(suser)) {
927 if (host && throughlocal) { /* extended remote to remote */
928 xasprintf(&bp, "%s -f %s%s", cmd,
929 *src == '-' ? "-- " : "", src);
930 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
933 xasprintf(&bp, "%s -t %s%s", cmd,
934 *targ == '-' ? "-- " : "", targ);
935 if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
939 (void) close(remout);
941 } else if (host) { /* standard remote to remote */
942 if (tport != -1 && tport != SSH_DEFAULT_PORT) {
943 /* This would require the remote support URIs */
944 fatal("target port not supported with two "
945 "remote hosts without the -3 option");
949 addargs(&alist, "%s", ssh_program);
950 addargs(&alist, "-x");
951 addargs(&alist, "-oClearAllForwardings=yes");
952 addargs(&alist, "-n");
953 for (j = 0; j < remote_remote_args.num; j++) {
954 addargs(&alist, "%s",
955 remote_remote_args.list[j]);
959 addargs(&alist, "-p");
960 addargs(&alist, "%d", sport);
963 addargs(&alist, "-l");
964 addargs(&alist, "%s", suser);
966 addargs(&alist, "--");
967 addargs(&alist, "%s", host);
968 addargs(&alist, "%s", cmd);
969 addargs(&alist, "%s", src);
970 addargs(&alist, "%s%s%s:%s",
971 tuser ? tuser : "", tuser ? "@" : "",
973 if (do_local_cmd(&alist) != 0)
975 } else { /* local to remote */
977 xasprintf(&bp, "%s -t %s%s", cmd,
978 *targ == '-' ? "-- " : "", targ);
979 if (do_cmd(thost, tuser, tport, bp, &remin,
999 tolocal(int argc, char **argv)
1001 char *bp, *host = NULL, *src = NULL, *suser = NULL;
1003 int i, r, sport = -1;
1005 memset(&alist, '\0', sizeof(alist));
1008 for (i = 0; i < argc - 1; i++) {
1012 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1014 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1019 parse_user_host_path(argv[i], &suser, &host, &src);
1020 if (suser != NULL && !okname(suser)) {
1024 if (!host) { /* Local to local. */
1026 addargs(&alist, "%s", _PATH_CP);
1028 addargs(&alist, "-r");
1030 addargs(&alist, "-p");
1031 addargs(&alist, "--");
1032 addargs(&alist, "%s", argv[i]);
1033 addargs(&alist, "%s", argv[argc-1]);
1034 if (do_local_cmd(&alist))
1038 /* Remote to local. */
1039 xasprintf(&bp, "%s -f %s%s",
1040 cmd, *src == '-' ? "-- " : "", src);
1041 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
1047 sink(1, argv + argc - 1, src);
1048 (void) close(remin);
1049 remin = remout = -1;
1057 source(int argc, char **argv)
1064 int fd = -1, haderr, indx;
1065 char *last, *name, buf[2048], encname[PATH_MAX];
1068 for (indx = 0; indx < argc; ++indx) {
1072 while (len > 1 && name[len-1] == '/')
1074 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
1076 if (strchr(name, '\n') != NULL) {
1077 strnvis(encname, name, sizeof(encname), VIS_NL);
1080 if (fstat(fd, &stb) < 0) {
1081 syserr: run_err("%s: %s", name, strerror(errno));
1084 if (stb.st_size < 0) {
1085 run_err("%s: %s", name, "Negative file size");
1089 switch (stb.st_mode & S_IFMT) {
1094 rsource(name, &stb);
1099 run_err("%s: not a regular file", name);
1102 if ((last = strrchr(name, '/')) == NULL)
1108 if (do_times(remout, verbose_mode, &stb) < 0)
1111 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1112 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1113 (u_int) (stb.st_mode & FILEMODEMASK),
1114 (long long)stb.st_size, last);
1116 fmprintf(stderr, "Sending file modes: %s", buf);
1117 (void) atomicio(vwrite, remout, buf, strlen(buf));
1120 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1121 next: if (fd != -1) {
1128 start_progress_meter(curfile, stb.st_size, &statbytes);
1129 set_nonblock(remout);
1130 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1132 if (i + (off_t)amt > stb.st_size)
1133 amt = stb.st_size - i;
1135 if ((nr = atomicio(read, fd,
1136 bp->buf, amt)) != amt) {
1138 memset(bp->buf + nr, 0, amt - nr);
1141 /* Keep writing after error to retain sync */
1143 (void)atomicio(vwrite, remout, bp->buf, amt);
1144 memset(bp->buf, 0, amt);
1147 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1151 unset_nonblock(remout);
1154 if (close(fd) < 0 && !haderr)
1159 (void) atomicio(vwrite, remout, "", 1);
1161 run_err("%s: %s", name, strerror(haderr));
1164 stop_progress_meter();
1169 rsource(char *name, struct stat *statp)
1173 char *last, *vect[1], path[PATH_MAX];
1175 if (!(dirp = opendir(name))) {
1176 run_err("%s: %s", name, strerror(errno));
1179 last = strrchr(name, '/');
1185 if (do_times(remout, verbose_mode, statp) < 0) {
1190 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1191 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1193 fmprintf(stderr, "Entering directory: %s", path);
1194 (void) atomicio(vwrite, remout, path, strlen(path));
1195 if (response() < 0) {
1199 while ((dp = readdir(dirp)) != NULL) {
1202 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1204 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1205 run_err("%s/%s: name too long", name, dp->d_name);
1208 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1212 (void) closedir(dirp);
1213 (void) atomicio(vwrite, remout, "E\n", 2);
1217 #define TYPE_OVERFLOW(type, val) \
1218 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
1219 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1220 (sizeof(type) != 4 && sizeof(type) != 8))
1223 sink(int argc, char **argv, const char *src)
1233 int amt, exists, first, ofd;
1234 mode_t mode, omode, mask;
1235 off_t size, statbytes;
1236 unsigned long long ull;
1237 int setimes, targisdir, wrerrno = 0;
1238 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1239 char **patterns = NULL;
1240 size_t n, npatterns = 0;
1241 struct timeval tv[2];
1245 #define SCREWUP(str) { why = str; goto screwup; }
1247 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1248 SCREWUP("Unexpected off_t/time_t size");
1250 setimes = targisdir = 0;
1255 run_err("ambiguous target");
1259 if (targetshouldbedirectory)
1262 (void) atomicio(vwrite, remout, "", 1);
1263 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1265 if (src != NULL && !iamrecursive && !Tflag) {
1267 * Prepare to try to restrict incoming filenames to match
1268 * the requested destination file glob.
1270 if (brace_expand(src, &patterns, &npatterns) != 0)
1271 fatal("%s: could not expand pattern", __func__);
1273 for (first = 1;; first = 0) {
1275 if (atomicio(read, remin, cp, 1) != 1)
1278 SCREWUP("unexpected <newline>");
1280 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1281 SCREWUP("lost connection");
1283 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1286 fmprintf(stderr, "Sink: %s", buf);
1288 if (buf[0] == '\01' || buf[0] == '\02') {
1289 if (iamremote == 0) {
1290 (void) snmprintf(visbuf, sizeof(visbuf),
1291 NULL, "%s", buf + 1);
1292 (void) atomicio(vwrite, STDERR_FILENO,
1293 visbuf, strlen(visbuf));
1295 if (buf[0] == '\02')
1300 if (buf[0] == 'E') {
1301 (void) atomicio(vwrite, remout, "", 1);
1311 if (!isdigit((unsigned char)*cp))
1312 SCREWUP("mtime.sec not present");
1313 ull = strtoull(cp, &cp, 10);
1314 if (!cp || *cp++ != ' ')
1315 SCREWUP("mtime.sec not delimited");
1316 if (TYPE_OVERFLOW(time_t, ull))
1317 setimes = 0; /* out of range */
1319 mtime.tv_usec = strtol(cp, &cp, 10);
1320 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1321 mtime.tv_usec > 999999)
1322 SCREWUP("mtime.usec not delimited");
1323 if (!isdigit((unsigned char)*cp))
1324 SCREWUP("atime.sec not present");
1325 ull = strtoull(cp, &cp, 10);
1326 if (!cp || *cp++ != ' ')
1327 SCREWUP("atime.sec not delimited");
1328 if (TYPE_OVERFLOW(time_t, ull))
1329 setimes = 0; /* out of range */
1331 atime.tv_usec = strtol(cp, &cp, 10);
1332 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1333 atime.tv_usec > 999999)
1334 SCREWUP("atime.usec not delimited");
1335 (void) atomicio(vwrite, remout, "", 1);
1338 if (*cp != 'C' && *cp != 'D') {
1340 * Check for the case "rcp remote:foo\* local:bar".
1341 * In this case, the line "No match." can be returned
1342 * by the shell before the rcp command on the remote is
1343 * executed so the ^Aerror_message convention isn't
1350 SCREWUP("expected control record");
1353 for (++cp; cp < buf + 5; cp++) {
1354 if (*cp < '0' || *cp > '7')
1355 SCREWUP("bad mode");
1356 mode = (mode << 3) | (*cp - '0');
1361 SCREWUP("mode not delimited");
1363 if (!isdigit((unsigned char)*cp))
1364 SCREWUP("size not present");
1365 ull = strtoull(cp, &cp, 10);
1366 if (!cp || *cp++ != ' ')
1367 SCREWUP("size not delimited");
1368 if (TYPE_OVERFLOW(off_t, ull))
1369 SCREWUP("size out of range");
1372 if (*cp == '\0' || strchr(cp, '/') != NULL ||
1373 strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1374 run_err("error: unexpected filename: %s", cp);
1377 if (npatterns > 0) {
1378 for (n = 0; n < npatterns; n++) {
1379 if (fnmatch(patterns[n], cp, 0) == 0)
1383 SCREWUP("filename does not match request");
1386 static char *namebuf;
1387 static size_t cursize;
1390 need = strlen(targ) + strlen(cp) + 250;
1391 if (need > cursize) {
1393 namebuf = xmalloc(need);
1396 (void) snprintf(namebuf, need, "%s%s%s", targ,
1397 strcmp(targ, "/") ? "/" : "", cp);
1402 exists = stat(np, &stb) == 0;
1403 if (buf[0] == 'D') {
1404 int mod_flag = pflag;
1406 SCREWUP("received directory without -r");
1408 if (!S_ISDIR(stb.st_mode)) {
1413 (void) chmod(np, mode);
1415 /* Handle copying from a read-only
1418 if (mkdir(np, mode | S_IRWXU) < 0)
1421 vect[0] = xstrdup(np);
1425 if (utimes(vect[0], tv) < 0)
1426 run_err("%s: set times: %s",
1427 vect[0], strerror(errno));
1430 (void) chmod(vect[0], mode);
1436 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1437 bad: run_err("%s: %s", np, strerror(errno));
1440 (void) atomicio(vwrite, remout, "", 1);
1441 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1450 start_progress_meter(curfile, size, &statbytes);
1451 set_nonblock(remin);
1452 for (count = i = 0; i < size; i += bp->cnt) {
1458 j = atomicio6(read, remin, cp, amt,
1461 run_err("%s", j != EPIPE ?
1463 "dropped connection");
1470 if (count == bp->cnt) {
1471 /* Keep reading so we stay sync'd up. */
1473 if (atomicio(vwrite, ofd, bp->buf,
1483 unset_nonblock(remin);
1484 if (count != 0 && wrerr == NO &&
1485 atomicio(vwrite, ofd, bp->buf, count) != count) {
1489 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1490 ftruncate(ofd, size) != 0) {
1491 run_err("%s: truncate: %s", np, strerror(errno));
1495 if (exists || omode != mode)
1497 if (fchmod(ofd, omode)) {
1498 #else /* HAVE_FCHMOD */
1499 if (chmod(np, omode)) {
1500 #endif /* HAVE_FCHMOD */
1501 run_err("%s: set mode: %s",
1502 np, strerror(errno));
1506 if (!exists && omode != mode)
1508 if (fchmod(ofd, omode & ~mask)) {
1509 #else /* HAVE_FCHMOD */
1510 if (chmod(np, omode & ~mask)) {
1511 #endif /* HAVE_FCHMOD */
1512 run_err("%s: set mode: %s",
1513 np, strerror(errno));
1517 if (close(ofd) == -1) {
1523 stop_progress_meter();
1524 if (setimes && wrerr == NO) {
1526 if (utimes(np, tv) < 0) {
1527 run_err("%s: set times: %s",
1528 np, strerror(errno));
1534 run_err("%s: %s", np, strerror(wrerrno));
1537 (void) atomicio(vwrite, remout, "", 1);
1544 for (n = 0; n < npatterns; n++)
1549 for (n = 0; n < npatterns; n++)
1552 run_err("protocol error: %s", why);
1559 char ch, *cp, resp, rbuf[2048], visbuf[2048];
1561 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1571 case 1: /* error, followed by error msg */
1572 case 2: /* fatal error, "" */
1574 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1577 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1581 (void) snmprintf(visbuf, sizeof(visbuf),
1582 NULL, "%s\n", rbuf);
1583 (void) atomicio(vwrite, STDERR_FILENO,
1584 visbuf, strlen(visbuf));
1597 (void) fprintf(stderr,
1598 "usage: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1599 " [-l limit] [-o ssh_option] [-P port] [-S program] source ... target\n");
1604 run_err(const char *fmt,...)
1610 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1611 (void) fprintf(fp, "%c", 0x01);
1612 (void) fprintf(fp, "scp: ");
1614 (void) vfprintf(fp, fmt, ap);
1616 (void) fprintf(fp, "\n");
1622 vfmprintf(stderr, fmt, ap);
1624 fprintf(stderr, "\n");
1633 if (!stat(cp, &stb)) {
1634 if (S_ISDIR(stb.st_mode))
1638 run_err("%s: %s", cp, strerror(errno));
1653 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1668 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
1673 allocbuf(BUF *bp, int fd, int blksize)
1676 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1679 if (fstat(fd, &stb) < 0) {
1680 run_err("fstat: %s", strerror(errno));
1683 size = ROUNDUP(stb.st_blksize, blksize);
1686 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1688 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1689 if (bp->cnt >= size)
1691 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1700 (void)write(STDERR_FILENO, "lost connection\n", 16);