1 /* $OpenBSD: scp.c,v 1.210 2020/05/06 20:57:38 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>
113 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
119 #include "atomicio.h"
120 #include "pathnames.h"
123 #include "progressmeter.h"
126 extern char *__progname;
128 #define COPY_BUFLEN 16384
130 int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
131 int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
133 /* Struct for addargs */
135 arglist remote_remote_args;
137 /* Bandwidth limit */
138 long long limit_kbps = 0;
139 struct bwlimit bwlimit;
141 /* Name of current file being transferred. */
144 /* This is set to non-zero to enable verbose mode. */
145 int verbose_mode = 0;
147 /* This is set to zero if the progressmeter is not desired. */
148 int showprogress = 1;
151 * This is set to non-zero if remote-remote copy should be piped
152 * through this process.
154 int throughlocal = 0;
156 /* Non-standard port to use for the ssh connection or -1. */
159 /* This is the program to execute for the secured connection. ("ssh" or -S) */
160 char *ssh_program = _PATH_SSH_PROGRAM;
162 /* This is used to store the pid of ssh_program */
163 pid_t do_cmd_pid = -1;
168 if (do_cmd_pid > 1) {
169 kill(do_cmd_pid, signo ? signo : SIGTERM);
170 waitpid(do_cmd_pid, NULL, 0);
183 if (do_cmd_pid > 1) {
184 kill(do_cmd_pid, signo);
185 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
188 kill(getpid(), SIGSTOP);
193 do_local_cmd(arglist *a)
200 fatal("do_local_cmd: no arguments");
203 fprintf(stderr, "Executing:");
204 for (i = 0; i < a->num; i++)
205 fmprintf(stderr, " %s", a->list[i]);
206 fprintf(stderr, "\n");
208 if ((pid = fork()) == -1)
209 fatal("do_local_cmd: fork: %s", strerror(errno));
212 execvp(a->list[0], a->list);
218 ssh_signal(SIGTERM, killchild);
219 ssh_signal(SIGINT, killchild);
220 ssh_signal(SIGHUP, killchild);
222 while (waitpid(pid, &status, 0) == -1)
224 fatal("do_local_cmd: waitpid: %s", strerror(errno));
228 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
235 * This function executes the given command as the specified user on the
236 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
237 * assigns the input and output file descriptors on success.
241 do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
243 int pin[2], pout[2], reserved[2];
247 "Executing: program %s host %s, user %s, command %s\n",
249 remuser ? remuser : "(unspecified)", cmd);
255 * Reserve two descriptors so that the real pipes won't get
256 * descriptors 0 and 1 because that will screw up dup2 below.
258 if (pipe(reserved) == -1)
259 fatal("pipe: %s", strerror(errno));
261 /* Create a socket pair for communicating with ssh. */
263 fatal("pipe: %s", strerror(errno));
264 if (pipe(pout) == -1)
265 fatal("pipe: %s", strerror(errno));
267 /* Free the reserved descriptors. */
271 ssh_signal(SIGTSTP, suspchild);
272 ssh_signal(SIGTTIN, suspchild);
273 ssh_signal(SIGTTOU, suspchild);
275 /* Fork a child to execute the command on the remote host using ssh. */
277 if (do_cmd_pid == 0) {
286 replacearg(&args, 0, "%s", ssh_program);
288 addargs(&args, "-p");
289 addargs(&args, "%d", port);
291 if (remuser != NULL) {
292 addargs(&args, "-l");
293 addargs(&args, "%s", remuser);
295 addargs(&args, "--");
296 addargs(&args, "%s", host);
297 addargs(&args, "%s", cmd);
299 execvp(ssh_program, args.list);
302 } else if (do_cmd_pid == -1) {
303 fatal("fork: %s", strerror(errno));
305 /* Parent. Close the other side, and return the local side. */
310 ssh_signal(SIGTERM, killchild);
311 ssh_signal(SIGINT, killchild);
312 ssh_signal(SIGHUP, killchild);
317 * This function executes a command similar to do_cmd(), but expects the
318 * input and output descriptors to be setup by a previous call to do_cmd().
319 * This way the input and output of two commands can be connected.
322 do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
329 "Executing: 2nd program %s host %s, user %s, command %s\n",
331 remuser ? remuser : "(unspecified)", cmd);
336 /* Fork a child to execute the command on the remote host using ssh. */
342 replacearg(&args, 0, "%s", ssh_program);
344 addargs(&args, "-p");
345 addargs(&args, "%d", port);
347 if (remuser != NULL) {
348 addargs(&args, "-l");
349 addargs(&args, "%s", remuser);
351 addargs(&args, "-oBatchMode=yes");
352 addargs(&args, "--");
353 addargs(&args, "%s", host);
354 addargs(&args, "%s", cmd);
356 execvp(ssh_program, args.list);
359 } else if (pid == -1) {
360 fatal("fork: %s", strerror(errno));
362 while (waitpid(pid, &status, 0) == -1)
364 fatal("do_cmd2: waitpid: %s", strerror(errno));
373 BUF *allocbuf(BUF *, int, int);
376 void run_err(const char *,...);
377 int note_err(const char *,...);
378 void verifydir(char *);
382 int errs, remin, remout;
383 int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
386 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
389 void rsource(char *, struct stat *);
390 void sink(int, char *[], const char *);
391 void source(int, char *[]);
392 void tolocal(int, char *[]);
393 void toremote(int, char *[]);
397 main(int argc, char **argv)
399 int ch, fflag, tflag, status, n;
405 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
412 /* Copy argv, because we modify it */
413 newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
414 for (n = 0; n < argc; n++)
415 newargv[n] = xstrdup(argv[n]);
418 __progname = ssh_get_progname(argv[0]);
420 memset(&args, '\0', sizeof(args));
421 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
422 args.list = remote_remote_args.list = NULL;
423 addargs(&args, "%s", ssh_program);
424 addargs(&args, "-x");
425 addargs(&args, "-oForwardAgent=no");
426 addargs(&args, "-oPermitLocalCommand=no");
427 addargs(&args, "-oClearAllForwardings=yes");
428 addargs(&args, "-oRemoteCommand=none");
429 addargs(&args, "-oRequestTTY=no");
431 fflag = Tflag = tflag = 0;
432 while ((ch = getopt(argc, argv,
433 "dfl:prtTvBCc:i:P:q12346S:o:F:J:")) != -1) {
435 /* User-visible flags. */
437 fatal("SSH protocol v.1 is no longer supported");
445 addargs(&args, "-%c", ch);
446 addargs(&remote_remote_args, "-%c", ch);
456 addargs(&remote_remote_args, "-%c", ch);
457 addargs(&remote_remote_args, "%s", optarg);
458 addargs(&args, "-%c", ch);
459 addargs(&args, "%s", optarg);
462 sshport = a2port(optarg);
464 fatal("bad port \"%s\"\n", optarg);
467 addargs(&remote_remote_args, "-oBatchmode=yes");
468 addargs(&args, "-oBatchmode=yes");
471 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
475 limit_kbps *= 1024; /* kbps */
476 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
485 ssh_program = xstrdup(optarg);
488 addargs(&args, "-v");
489 addargs(&remote_remote_args, "-v");
493 addargs(&args, "-q");
494 addargs(&remote_remote_args, "-q");
498 /* Server options. */
500 targetshouldbedirectory = 1;
502 case 'f': /* "from" */
510 setmode(0, O_BINARY);
523 if ((pwd = getpwuid(userid = getuid())) == NULL)
524 fatal("unknown user %u", (u_int) userid);
526 if (!isatty(STDOUT_FILENO))
530 /* Cannot pledge: -p allows setuid/setgid files... */
532 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
539 remin = STDIN_FILENO;
540 remout = STDOUT_FILENO;
543 /* Follow "protocol", send data. */
550 sink(argc, argv, NULL);
556 targetshouldbedirectory = 1;
560 /* Command to be executed on remote system using "ssh". */
561 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
562 verbose_mode ? " -v" : "",
563 iamrecursive ? " -r" : "", pflag ? " -p" : "",
564 targetshouldbedirectory ? " -d" : "");
566 (void) ssh_signal(SIGPIPE, lostconn);
568 if (colon(argv[argc - 1])) /* Dest is remote host. */
569 toremote(argc, argv);
571 if (targetshouldbedirectory)
572 verifydir(argv[argc - 1]);
573 tolocal(argc, argv); /* Dest is local host. */
576 * Finally check the exit status of the ssh process, if one was forked
577 * and no error has occurred yet
579 if (do_cmd_pid != -1 && errs == 0) {
583 (void) close(remout);
584 if (waitpid(do_cmd_pid, &status, 0) == -1)
587 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
594 /* Callback from atomicio6 to update progress meter and limit bandwidth */
596 scpio(void *_cnt, size_t s)
598 off_t *cnt = (off_t *)_cnt;
601 refresh_progress_meter(0);
603 bandwidth_limit(&bwlimit, s);
608 do_times(int fd, int verb, const struct stat *sb)
610 /* strlen(2^64) == 20; strlen(10^6) == 7 */
611 char buf[(20 + 7 + 2) * 2 + 2];
613 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
614 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
615 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
617 fprintf(stderr, "File mtime %lld atime %lld\n",
618 (long long)sb->st_mtime, (long long)sb->st_atime);
619 fprintf(stderr, "Sending file timestamps: %s", buf);
621 (void) atomicio(vwrite, fd, buf, strlen(buf));
626 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
631 r = parse_uri("scp", uri, userp, hostp, portp, pathp);
632 if (r == 0 && *pathp == NULL)
633 *pathp = xstrdup(".");
637 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
639 append(char *cp, char ***ap, size_t *np)
643 if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
652 * Finds the start and end of the first brace pair in the pattern.
653 * returns 0 on success or -1 for invalid patterns.
656 find_brace(const char *pattern, int *startp, int *endp)
659 int in_bracket, brace_level;
661 *startp = *endp = -1;
662 in_bracket = brace_level = 0;
663 for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
664 switch (pattern[i]) {
666 /* skip next character */
667 if (pattern[i + 1] != '\0')
679 if (pattern[i + 1] == '}') {
680 /* Protect a single {}, for find(1), like csh */
692 /* Unbalanced brace */
695 if (--brace_level <= 0)
700 /* unbalanced brackets/braces */
701 if (*endp < 0 && (*startp >= 0 || in_bracket))
707 * Assembles and records a successfully-expanded pattern, returns -1 on
711 emit_expansion(const char *pattern, int brace_start, int brace_end,
712 int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
715 int o = 0, tail_len = strlen(pattern + brace_end + 1);
717 if ((cp = malloc(brace_start + (sel_end - sel_start) +
718 tail_len + 1)) == NULL)
721 /* Pattern before initial brace */
722 if (brace_start > 0) {
723 memcpy(cp, pattern, brace_start);
726 /* Current braced selection */
727 if (sel_end - sel_start > 0) {
728 memcpy(cp + o, pattern + sel_start,
729 sel_end - sel_start);
730 o += sel_end - sel_start;
732 /* Remainder of pattern after closing brace */
734 memcpy(cp + o, pattern + brace_end + 1, tail_len);
738 if (append(cp, patternsp, npatternsp) != 0) {
746 * Expand the first encountered brace in pattern, appending the expanded
747 * patterns it yielded to the *patternsp array.
749 * Returns 0 on success or -1 on allocation failure.
751 * Signals whether expansion was performed via *expanded and whether
752 * pattern was invalid via *invalid.
755 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
756 int *expanded, int *invalid)
759 int in_bracket, brace_start, brace_end, brace_level;
760 int sel_start, sel_end;
762 *invalid = *expanded = 0;
764 if (find_brace(pattern, &brace_start, &brace_end) != 0) {
767 } else if (brace_start == -1)
770 in_bracket = brace_level = 0;
771 for (i = sel_start = brace_start + 1; i < brace_end; i++) {
772 switch (pattern[i]) {
790 if (i < brace_end - 1)
794 if (pattern[i] == ',' || i == brace_end - 1) {
795 if (in_bracket || brace_level > 0)
797 /* End of a selection, emit an expanded pattern */
799 /* Adjust end index for last selection */
800 sel_end = (i == brace_end - 1) ? brace_end : i;
801 if (emit_expansion(pattern, brace_start, brace_end,
802 sel_start, sel_end, patternsp, npatternsp) != 0)
804 /* move on to the next selection */
809 if (in_bracket || brace_level > 0) {
818 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
820 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
822 char *cp, *cp2, **active = NULL, **done = NULL;
823 size_t i, nactive = 0, ndone = 0;
824 int ret = -1, invalid = 0, expanded = 0;
829 /* Start the worklist with the original pattern */
830 if ((cp = strdup(pattern)) == NULL)
832 if (append(cp, &active, &nactive) != 0) {
836 while (nactive > 0) {
837 cp = active[nactive - 1];
839 if (brace_expand_one(cp, &active, &nactive,
840 &expanded, &invalid) == -1) {
845 fatal("%s: invalid brace pattern \"%s\"", __func__, cp);
848 * Current entry expanded to new entries on the
849 * active list; discard the progenitor pattern.
855 * Pattern did not expand; append the finename component to
858 if ((cp2 = strrchr(cp, '/')) != NULL)
862 if (append(xstrdup(cp2), &done, &ndone) != 0) {
875 for (i = 0; i < nactive; i++)
878 for (i = 0; i < ndone; i++)
885 toremote(int argc, char **argv)
887 char *suser = NULL, *host = NULL, *src = NULL;
888 char *bp, *tuser, *thost, *targ;
889 int sport = -1, tport = -1;
894 memset(&alist, '\0', sizeof(alist));
898 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
900 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
905 if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
907 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
912 if (tuser != NULL && !okname(tuser)) {
917 /* Parse source files */
918 for (i = 0; i < argc - 1; i++) {
922 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
924 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
929 parse_user_host_path(argv[i], &suser, &host, &src);
931 if (suser != NULL && !okname(suser)) {
935 if (host && throughlocal) { /* extended remote to remote */
936 xasprintf(&bp, "%s -f %s%s", cmd,
937 *src == '-' ? "-- " : "", src);
938 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
941 xasprintf(&bp, "%s -t %s%s", cmd,
942 *targ == '-' ? "-- " : "", targ);
943 if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
947 (void) close(remout);
949 } else if (host) { /* standard remote to remote */
950 if (tport != -1 && tport != SSH_DEFAULT_PORT) {
951 /* This would require the remote support URIs */
952 fatal("target port not supported with two "
953 "remote hosts without the -3 option");
957 addargs(&alist, "%s", ssh_program);
958 addargs(&alist, "-x");
959 addargs(&alist, "-oClearAllForwardings=yes");
960 addargs(&alist, "-n");
961 for (j = 0; j < remote_remote_args.num; j++) {
962 addargs(&alist, "%s",
963 remote_remote_args.list[j]);
967 addargs(&alist, "-p");
968 addargs(&alist, "%d", sport);
971 addargs(&alist, "-l");
972 addargs(&alist, "%s", suser);
974 addargs(&alist, "--");
975 addargs(&alist, "%s", host);
976 addargs(&alist, "%s", cmd);
977 addargs(&alist, "%s", src);
978 addargs(&alist, "%s%s%s:%s",
979 tuser ? tuser : "", tuser ? "@" : "",
981 if (do_local_cmd(&alist) != 0)
983 } else { /* local to remote */
985 xasprintf(&bp, "%s -t %s%s", cmd,
986 *targ == '-' ? "-- " : "", targ);
987 if (do_cmd(thost, tuser, tport, bp, &remin,
1007 tolocal(int argc, char **argv)
1009 char *bp, *host = NULL, *src = NULL, *suser = NULL;
1011 int i, r, sport = -1;
1013 memset(&alist, '\0', sizeof(alist));
1016 for (i = 0; i < argc - 1; i++) {
1020 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1022 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1027 parse_user_host_path(argv[i], &suser, &host, &src);
1028 if (suser != NULL && !okname(suser)) {
1032 if (!host) { /* Local to local. */
1034 addargs(&alist, "%s", _PATH_CP);
1036 addargs(&alist, "-r");
1038 addargs(&alist, "-p");
1039 addargs(&alist, "--");
1040 addargs(&alist, "%s", argv[i]);
1041 addargs(&alist, "%s", argv[argc-1]);
1042 if (do_local_cmd(&alist))
1046 /* Remote to local. */
1047 xasprintf(&bp, "%s -f %s%s",
1048 cmd, *src == '-' ? "-- " : "", src);
1049 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
1055 sink(1, argv + argc - 1, src);
1056 (void) close(remin);
1057 remin = remout = -1;
1065 source(int argc, char **argv)
1072 int fd = -1, haderr, indx;
1073 char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1076 for (indx = 0; indx < argc; ++indx) {
1080 while (len > 1 && name[len-1] == '/')
1082 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) == -1)
1084 if (strchr(name, '\n') != NULL) {
1085 strnvis(encname, name, sizeof(encname), VIS_NL);
1088 if (fstat(fd, &stb) == -1) {
1089 syserr: run_err("%s: %s", name, strerror(errno));
1092 if (stb.st_size < 0) {
1093 run_err("%s: %s", name, "Negative file size");
1097 switch (stb.st_mode & S_IFMT) {
1102 rsource(name, &stb);
1107 run_err("%s: not a regular file", name);
1110 if ((last = strrchr(name, '/')) == NULL)
1116 if (do_times(remout, verbose_mode, &stb) < 0)
1119 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1120 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1121 (u_int) (stb.st_mode & FILEMODEMASK),
1122 (long long)stb.st_size, last);
1124 fmprintf(stderr, "Sending file modes: %s", buf);
1125 (void) atomicio(vwrite, remout, buf, strlen(buf));
1128 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1129 next: if (fd != -1) {
1136 start_progress_meter(curfile, stb.st_size, &statbytes);
1137 set_nonblock(remout);
1138 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1140 if (i + (off_t)amt > stb.st_size)
1141 amt = stb.st_size - i;
1143 if ((nr = atomicio(read, fd,
1144 bp->buf, amt)) != amt) {
1146 memset(bp->buf + nr, 0, amt - nr);
1149 /* Keep writing after error to retain sync */
1151 (void)atomicio(vwrite, remout, bp->buf, amt);
1152 memset(bp->buf, 0, amt);
1155 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1159 unset_nonblock(remout);
1162 if (close(fd) == -1 && !haderr)
1167 (void) atomicio(vwrite, remout, "", 1);
1169 run_err("%s: %s", name, strerror(haderr));
1172 stop_progress_meter();
1177 rsource(char *name, struct stat *statp)
1181 char *last, *vect[1], path[PATH_MAX];
1183 if (!(dirp = opendir(name))) {
1184 run_err("%s: %s", name, strerror(errno));
1187 last = strrchr(name, '/');
1193 if (do_times(remout, verbose_mode, statp) < 0) {
1198 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1199 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1201 fmprintf(stderr, "Entering directory: %s", path);
1202 (void) atomicio(vwrite, remout, path, strlen(path));
1203 if (response() < 0) {
1207 while ((dp = readdir(dirp)) != NULL) {
1210 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1212 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1213 run_err("%s/%s: name too long", name, dp->d_name);
1216 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1220 (void) closedir(dirp);
1221 (void) atomicio(vwrite, remout, "E\n", 2);
1225 #define TYPE_OVERFLOW(type, val) \
1226 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
1227 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1228 (sizeof(type) != 4 && sizeof(type) != 8))
1231 sink(int argc, char **argv, const char *src)
1238 int amt, exists, first, ofd;
1239 mode_t mode, omode, mask;
1240 off_t size, statbytes;
1241 unsigned long long ull;
1242 int setimes, targisdir, wrerr;
1243 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1244 char **patterns = NULL;
1245 size_t n, npatterns = 0;
1246 struct timeval tv[2];
1250 #define SCREWUP(str) { why = str; goto screwup; }
1252 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1253 SCREWUP("Unexpected off_t/time_t size");
1255 setimes = targisdir = 0;
1260 run_err("ambiguous target");
1264 if (targetshouldbedirectory)
1267 (void) atomicio(vwrite, remout, "", 1);
1268 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1270 if (src != NULL && !iamrecursive && !Tflag) {
1272 * Prepare to try to restrict incoming filenames to match
1273 * the requested destination file glob.
1275 if (brace_expand(src, &patterns, &npatterns) != 0)
1276 fatal("%s: could not expand pattern", __func__);
1278 for (first = 1;; first = 0) {
1280 if (atomicio(read, remin, cp, 1) != 1)
1283 SCREWUP("unexpected <newline>");
1285 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1286 SCREWUP("lost connection");
1288 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1291 fmprintf(stderr, "Sink: %s", buf);
1293 if (buf[0] == '\01' || buf[0] == '\02') {
1294 if (iamremote == 0) {
1295 (void) snmprintf(visbuf, sizeof(visbuf),
1296 NULL, "%s", buf + 1);
1297 (void) atomicio(vwrite, STDERR_FILENO,
1298 visbuf, strlen(visbuf));
1300 if (buf[0] == '\02')
1305 if (buf[0] == 'E') {
1306 (void) atomicio(vwrite, remout, "", 1);
1316 if (!isdigit((unsigned char)*cp))
1317 SCREWUP("mtime.sec not present");
1318 ull = strtoull(cp, &cp, 10);
1319 if (!cp || *cp++ != ' ')
1320 SCREWUP("mtime.sec not delimited");
1321 if (TYPE_OVERFLOW(time_t, ull))
1322 setimes = 0; /* out of range */
1324 mtime.tv_usec = strtol(cp, &cp, 10);
1325 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1326 mtime.tv_usec > 999999)
1327 SCREWUP("mtime.usec not delimited");
1328 if (!isdigit((unsigned char)*cp))
1329 SCREWUP("atime.sec not present");
1330 ull = strtoull(cp, &cp, 10);
1331 if (!cp || *cp++ != ' ')
1332 SCREWUP("atime.sec not delimited");
1333 if (TYPE_OVERFLOW(time_t, ull))
1334 setimes = 0; /* out of range */
1336 atime.tv_usec = strtol(cp, &cp, 10);
1337 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1338 atime.tv_usec > 999999)
1339 SCREWUP("atime.usec not delimited");
1340 (void) atomicio(vwrite, remout, "", 1);
1343 if (*cp != 'C' && *cp != 'D') {
1345 * Check for the case "rcp remote:foo\* local:bar".
1346 * In this case, the line "No match." can be returned
1347 * by the shell before the rcp command on the remote is
1348 * executed so the ^Aerror_message convention isn't
1355 SCREWUP("expected control record");
1358 for (++cp; cp < buf + 5; cp++) {
1359 if (*cp < '0' || *cp > '7')
1360 SCREWUP("bad mode");
1361 mode = (mode << 3) | (*cp - '0');
1366 SCREWUP("mode not delimited");
1368 if (!isdigit((unsigned char)*cp))
1369 SCREWUP("size not present");
1370 ull = strtoull(cp, &cp, 10);
1371 if (!cp || *cp++ != ' ')
1372 SCREWUP("size not delimited");
1373 if (TYPE_OVERFLOW(off_t, ull))
1374 SCREWUP("size out of range");
1377 if (*cp == '\0' || strchr(cp, '/') != NULL ||
1378 strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1379 run_err("error: unexpected filename: %s", cp);
1382 if (npatterns > 0) {
1383 for (n = 0; n < npatterns; n++) {
1384 if (fnmatch(patterns[n], cp, 0) == 0)
1388 SCREWUP("filename does not match request");
1391 static char *namebuf;
1392 static size_t cursize;
1395 need = strlen(targ) + strlen(cp) + 250;
1396 if (need > cursize) {
1398 namebuf = xmalloc(need);
1401 (void) snprintf(namebuf, need, "%s%s%s", targ,
1402 strcmp(targ, "/") ? "/" : "", cp);
1407 exists = stat(np, &stb) == 0;
1408 if (buf[0] == 'D') {
1409 int mod_flag = pflag;
1411 SCREWUP("received directory without -r");
1413 if (!S_ISDIR(stb.st_mode)) {
1418 (void) chmod(np, mode);
1420 /* Handle copying from a read-only
1423 if (mkdir(np, mode | S_IRWXU) == -1)
1426 vect[0] = xstrdup(np);
1430 (void) utimes(vect[0], tv);
1433 (void) chmod(vect[0], mode);
1439 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1440 bad: run_err("%s: %s", np, strerror(errno));
1443 (void) atomicio(vwrite, remout, "", 1);
1444 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1452 * NB. do not use run_err() unless immediately followed by
1453 * exit() below as it may send a spurious reply that might
1454 * desyncronise us from the peer. Use note_err() instead.
1458 start_progress_meter(curfile, size, &statbytes);
1459 set_nonblock(remin);
1460 for (count = i = 0; i < size; i += bp->cnt) {
1466 j = atomicio6(read, remin, cp, amt,
1469 run_err("%s", j != EPIPE ?
1471 "dropped connection");
1478 if (count == bp->cnt) {
1479 /* Keep reading so we stay sync'd up. */
1481 if (atomicio(vwrite, ofd, bp->buf,
1483 note_err("%s: %s", np,
1492 unset_nonblock(remin);
1493 if (count != 0 && !wrerr &&
1494 atomicio(vwrite, ofd, bp->buf, count) != count) {
1495 note_err("%s: %s", np, strerror(errno));
1498 if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1499 ftruncate(ofd, size) != 0)
1500 note_err("%s: truncate: %s", np, strerror(errno));
1502 if (exists || omode != mode)
1504 if (fchmod(ofd, omode)) {
1505 #else /* HAVE_FCHMOD */
1506 if (chmod(np, omode)) {
1507 #endif /* HAVE_FCHMOD */
1508 note_err("%s: set mode: %s",
1509 np, strerror(errno));
1512 if (!exists && omode != mode)
1514 if (fchmod(ofd, omode & ~mask)) {
1515 #else /* HAVE_FCHMOD */
1516 if (chmod(np, omode & ~mask)) {
1517 #endif /* HAVE_FCHMOD */
1518 note_err("%s: set mode: %s",
1519 np, strerror(errno));
1522 if (close(ofd) == -1)
1523 note_err(np, "%s: close: %s", np, strerror(errno));
1526 stop_progress_meter();
1527 if (setimes && !wrerr) {
1529 if (utimes(np, tv) == -1) {
1530 note_err("%s: set times: %s",
1531 np, strerror(errno));
1534 /* If no error was noted then signal success for this file */
1535 if (note_err(NULL) == 0)
1536 (void) atomicio(vwrite, remout, "", 1);
1539 for (n = 0; n < npatterns; n++)
1544 for (n = 0; n < npatterns; n++)
1547 run_err("protocol error: %s", why);
1554 char ch, *cp, resp, rbuf[2048], visbuf[2048];
1556 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1566 case 1: /* error, followed by error msg */
1567 case 2: /* fatal error, "" */
1569 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1572 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1576 (void) snmprintf(visbuf, sizeof(visbuf),
1577 NULL, "%s\n", rbuf);
1578 (void) atomicio(vwrite, STDERR_FILENO,
1579 visbuf, strlen(visbuf));
1592 (void) fprintf(stderr,
1593 "usage: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1594 " [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
1595 " [-S program] source ... target\n");
1600 run_err(const char *fmt,...)
1606 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1607 (void) fprintf(fp, "%c", 0x01);
1608 (void) fprintf(fp, "scp: ");
1610 (void) vfprintf(fp, fmt, ap);
1612 (void) fprintf(fp, "\n");
1618 vfmprintf(stderr, fmt, ap);
1620 fprintf(stderr, "\n");
1625 * Notes a sink error for sending at the end of a file transfer. Returns 0 if
1626 * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
1627 * any active error at the end of the transfer.
1630 note_err(const char *fmt, ...)
1635 /* Replay any previously-noted error */
1639 run_err("%s", emsg);
1646 /* Prefer first-noted error */
1651 vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
1661 if (!stat(cp, &stb)) {
1662 if (S_ISDIR(stb.st_mode))
1666 run_err("%s: %s", cp, strerror(errno));
1681 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1696 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
1701 allocbuf(BUF *bp, int fd, int blksize)
1704 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1707 if (fstat(fd, &stb) == -1) {
1708 run_err("fstat: %s", strerror(errno));
1711 size = ROUNDUP(stb.st_blksize, blksize);
1714 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1716 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1717 if (bp->cnt >= size)
1719 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1728 (void)write(STDERR_FILENO, "lost connection\n", 16);