1 /* $OpenBSD: scp.c,v 1.260 2023/10/11 05:42:08 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>
100 #ifdef USE_SYSTEM_GLOB
103 # include "openbsd-compat/glob.h"
124 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
130 #include "atomicio.h"
131 #include "pathnames.h"
134 #include "progressmeter.h"
138 #include "sftp-common.h"
139 #include "sftp-client.h"
141 extern char *__progname;
143 #define COPY_BUFLEN 16384
145 int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t *);
146 int do_cmd2(char *, char *, int, char *, int, int);
148 /* Struct for addargs */
150 arglist remote_remote_args;
152 /* Bandwidth limit */
153 long long limit_kbps = 0;
154 struct bwlimit bwlimit;
156 /* Name of current file being transferred. */
159 /* This is set to non-zero to enable verbose mode. */
160 int verbose_mode = 0;
161 LogLevel log_level = SYSLOG_LEVEL_INFO;
163 /* This is set to zero if the progressmeter is not desired. */
164 int showprogress = 1;
167 * This is set to non-zero if remote-remote copy should be piped
168 * through this process.
170 int throughlocal = 1;
172 /* Non-standard port to use for the ssh connection or -1. */
175 /* This is the program to execute for the secured connection. ("ssh" or -S) */
176 char *ssh_program = _PATH_SSH_PROGRAM;
178 /* This is used to store the pid of ssh_program */
179 pid_t do_cmd_pid = -1;
180 pid_t do_cmd_pid2 = -1;
182 /* SFTP copy parameters */
183 size_t sftp_copy_buflen;
184 size_t sftp_nrequests;
186 /* Needed for sftp */
187 volatile sig_atomic_t interrupted = 0;
189 int sftp_glob(struct sftp_conn *, const char *, int,
190 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
195 if (do_cmd_pid > 1) {
196 kill(do_cmd_pid, signo ? signo : SIGTERM);
197 (void)waitpid(do_cmd_pid, NULL, 0);
199 if (do_cmd_pid2 > 1) {
200 kill(do_cmd_pid2, signo ? signo : SIGTERM);
201 (void)waitpid(do_cmd_pid2, NULL, 0);
210 suspone(int pid, int signo)
216 while (waitpid(pid, &status, WUNTRACED) == -1 &&
225 suspone(do_cmd_pid, signo);
226 suspone(do_cmd_pid2, signo);
227 kill(getpid(), SIGSTOP);
231 do_local_cmd(arglist *a)
238 fatal("do_local_cmd: no arguments");
241 fprintf(stderr, "Executing:");
242 for (i = 0; i < a->num; i++)
243 fmprintf(stderr, " %s", a->list[i]);
244 fprintf(stderr, "\n");
246 if ((pid = fork()) == -1)
247 fatal("do_local_cmd: fork: %s", strerror(errno));
250 execvp(a->list[0], a->list);
256 ssh_signal(SIGTERM, killchild);
257 ssh_signal(SIGINT, killchild);
258 ssh_signal(SIGHUP, killchild);
260 while (waitpid(pid, &status, 0) == -1)
262 fatal("do_local_cmd: waitpid: %s", strerror(errno));
266 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
273 * This function executes the given command as the specified user on the
274 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
275 * assigns the input and output file descriptors on success.
279 do_cmd(char *program, char *host, char *remuser, int port, int subsystem,
280 char *cmd, int *fdin, int *fdout, pid_t *pid)
290 "Executing: program %s host %s, user %s, command %s\n",
292 remuser ? remuser : "(unspecified)", cmd);
298 if (pipe(pin) == -1 || pipe(pout) == -1)
299 fatal("pipe: %s", strerror(errno));
301 /* Create a socket pair for communicating with ssh. */
302 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1)
303 fatal("socketpair: %s", strerror(errno));
306 ssh_signal(SIGTSTP, suspchild);
307 ssh_signal(SIGTTIN, suspchild);
308 ssh_signal(SIGTTOU, suspchild);
310 /* Fork a child to execute the command on the remote host using ssh. */
314 fatal("fork: %s", strerror(errno));
318 if (dup2(pin[0], STDIN_FILENO) == -1 ||
319 dup2(pout[1], STDOUT_FILENO) == -1) {
320 error("dup2: %s", strerror(errno));
328 if (dup2(sv[0], STDIN_FILENO) == -1 ||
329 dup2(sv[0], STDOUT_FILENO) == -1) {
330 error("dup2: %s", strerror(errno));
336 replacearg(&args, 0, "%s", program);
338 addargs(&args, "-p");
339 addargs(&args, "%d", port);
341 if (remuser != NULL) {
342 addargs(&args, "-l");
343 addargs(&args, "%s", remuser);
346 addargs(&args, "-s");
347 addargs(&args, "--");
348 addargs(&args, "%s", host);
349 addargs(&args, "%s", cmd);
351 execvp(program, args.list);
355 /* Parent. Close the other side, and return the local side. */
366 ssh_signal(SIGTERM, killchild);
367 ssh_signal(SIGINT, killchild);
368 ssh_signal(SIGHUP, killchild);
374 * This function executes a command similar to do_cmd(), but expects the
375 * input and output descriptors to be setup by a previous call to do_cmd().
376 * This way the input and output of two commands can be connected.
379 do_cmd2(char *host, char *remuser, int port, char *cmd,
387 "Executing: 2nd program %s host %s, user %s, command %s\n",
389 remuser ? remuser : "(unspecified)", cmd);
394 /* Fork a child to execute the command on the remote host using ssh. */
397 if (dup2(fdin, 0) == -1)
399 if (dup2(fdout, 1) == -1)
402 replacearg(&args, 0, "%s", ssh_program);
404 addargs(&args, "-p");
405 addargs(&args, "%d", port);
407 if (remuser != NULL) {
408 addargs(&args, "-l");
409 addargs(&args, "%s", remuser);
411 addargs(&args, "-oBatchMode=yes");
412 addargs(&args, "--");
413 addargs(&args, "%s", host);
414 addargs(&args, "%s", cmd);
416 execvp(ssh_program, args.list);
419 } else if (pid == -1) {
420 fatal("fork: %s", strerror(errno));
422 while (waitpid(pid, &status, 0) == -1)
424 fatal("do_cmd2: waitpid: %s", strerror(errno));
433 BUF *allocbuf(BUF *, int, int);
436 void run_err(const char *,...)
437 __attribute__((__format__ (printf, 1, 2)))
438 __attribute__((__nonnull__ (1)));
439 int note_err(const char *,...)
440 __attribute__((__format__ (printf, 1, 2)));
441 void verifydir(char *);
445 int errs, remin, remout, remin2, remout2;
446 int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
449 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
457 void rsource(char *, struct stat *);
458 void sink(int, char *[], const char *);
459 void source(int, char *[]);
460 void tolocal(int, char *[], enum scp_mode_e, char *sftp_direct);
461 void toremote(int, char *[], enum scp_mode_e, char *sftp_direct);
464 void source_sftp(int, char *, char *, struct sftp_conn *);
465 void sink_sftp(int, char *, const char *, struct sftp_conn *);
466 void throughlocal_sftp(struct sftp_conn *, struct sftp_conn *,
470 main(int argc, char **argv)
472 int ch, fflag, tflag, status, r, n;
473 char **newargv, *argv0;
477 enum scp_mode_e mode = MODE_SFTP;
478 char *sftp_direct = NULL;
481 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
486 /* Copy argv, because we modify it */
488 newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
489 for (n = 0; n < argc; n++)
490 newargv[n] = xstrdup(argv[n]);
493 __progname = ssh_get_progname(argv[0]);
495 log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
497 memset(&args, '\0', sizeof(args));
498 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
499 args.list = remote_remote_args.list = NULL;
500 addargs(&args, "%s", ssh_program);
501 addargs(&args, "-x");
502 addargs(&args, "-oPermitLocalCommand=no");
503 addargs(&args, "-oClearAllForwardings=yes");
504 addargs(&args, "-oRemoteCommand=none");
505 addargs(&args, "-oRequestTTY=no");
507 fflag = Tflag = tflag = 0;
508 while ((ch = getopt(argc, argv,
509 "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:X:")) != -1) {
511 /* User-visible flags. */
513 fatal("SSH protocol v.1 is no longer supported");
522 addargs(&args, "-%c", ch);
523 addargs(&remote_remote_args, "-%c", ch);
526 sftp_direct = optarg;
539 addargs(&remote_remote_args, "-%c", ch);
540 addargs(&remote_remote_args, "%s", optarg);
541 addargs(&args, "-%c", ch);
542 addargs(&args, "%s", optarg);
551 sshport = a2port(optarg);
553 fatal("bad port \"%s\"\n", optarg);
556 addargs(&remote_remote_args, "-oBatchmode=yes");
557 addargs(&args, "-oBatchmode=yes");
560 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
564 limit_kbps *= 1024; /* kbps */
565 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
574 ssh_program = xstrdup(optarg);
577 addargs(&args, "-v");
578 addargs(&remote_remote_args, "-v");
579 if (verbose_mode == 0)
580 log_level = SYSLOG_LEVEL_DEBUG1;
581 else if (log_level < SYSLOG_LEVEL_DEBUG3)
586 addargs(&args, "-q");
587 addargs(&remote_remote_args, "-q");
591 /* Please keep in sync with sftp.c -X */
592 if (strncmp(optarg, "buffer=", 7) == 0) {
593 r = scan_scaled(optarg + 7, &llv);
594 if (r == 0 && (llv <= 0 || llv > 256 * 1024)) {
599 fatal("Invalid buffer size \"%s\": %s",
600 optarg + 7, strerror(errno));
602 sftp_copy_buflen = (size_t)llv;
603 } else if (strncmp(optarg, "nrequests=", 10) == 0) {
604 llv = strtonum(optarg + 10, 1, 256 * 1024,
606 if (errstr != NULL) {
607 fatal("Invalid number of requests "
608 "\"%s\": %s", optarg + 10, errstr);
610 sftp_nrequests = (size_t)llv;
612 fatal("Invalid -X option");
616 /* Server options. */
618 targetshouldbedirectory = 1;
620 case 'f': /* "from" */
628 setmode(0, O_BINARY);
641 log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
643 /* Do this last because we want the user to be able to override it */
644 addargs(&args, "-oForwardAgent=no");
649 if ((pwd = getpwuid(userid = getuid())) == NULL)
650 fatal("unknown user %u", (u_int) userid);
652 if (!isatty(STDOUT_FILENO))
656 /* Cannot pledge: -p allows setuid/setgid files... */
658 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
665 remin = STDIN_FILENO;
666 remout = STDOUT_FILENO;
669 /* Follow "protocol", send data. */
676 sink(argc, argv, NULL);
682 targetshouldbedirectory = 1;
686 /* Command to be executed on remote system using "ssh". */
687 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
688 verbose_mode ? " -v" : "",
689 iamrecursive ? " -r" : "", pflag ? " -p" : "",
690 targetshouldbedirectory ? " -d" : "");
692 (void) ssh_signal(SIGPIPE, lostconn);
694 if (colon(argv[argc - 1])) /* Dest is remote host. */
695 toremote(argc, argv, mode, sftp_direct);
697 if (targetshouldbedirectory)
698 verifydir(argv[argc - 1]);
699 tolocal(argc, argv, mode, sftp_direct); /* Dest is local host. */
702 * Finally check the exit status of the ssh process, if one was forked
703 * and no error has occurred yet
705 if (do_cmd_pid != -1 && (mode == MODE_SFTP || errs == 0)) {
709 (void) close(remout);
710 if (waitpid(do_cmd_pid, &status, 0) == -1)
713 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
720 /* Callback from atomicio6 to update progress meter and limit bandwidth */
722 scpio(void *_cnt, size_t s)
724 off_t *cnt = (off_t *)_cnt;
727 refresh_progress_meter(0);
729 bandwidth_limit(&bwlimit, s);
734 do_times(int fd, int verb, const struct stat *sb)
736 /* strlen(2^64) == 20; strlen(10^6) == 7 */
737 char buf[(20 + 7 + 2) * 2 + 2];
739 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
740 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
741 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
743 fprintf(stderr, "File mtime %lld atime %lld\n",
744 (long long)sb->st_mtime, (long long)sb->st_atime);
745 fprintf(stderr, "Sending file timestamps: %s", buf);
747 (void) atomicio(vwrite, fd, buf, strlen(buf));
752 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
757 r = parse_uri("scp", uri, userp, hostp, portp, pathp);
758 if (r == 0 && *pathp == NULL)
759 *pathp = xstrdup(".");
763 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
765 append(char *cp, char ***ap, size_t *np)
769 if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
778 * Finds the start and end of the first brace pair in the pattern.
779 * returns 0 on success or -1 for invalid patterns.
782 find_brace(const char *pattern, int *startp, int *endp)
785 int in_bracket, brace_level;
787 *startp = *endp = -1;
788 in_bracket = brace_level = 0;
789 for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
790 switch (pattern[i]) {
792 /* skip next character */
793 if (pattern[i + 1] != '\0')
805 if (pattern[i + 1] == '}') {
806 /* Protect a single {}, for find(1), like csh */
818 /* Unbalanced brace */
821 if (--brace_level <= 0)
826 /* unbalanced brackets/braces */
827 if (*endp < 0 && (*startp >= 0 || in_bracket))
833 * Assembles and records a successfully-expanded pattern, returns -1 on
837 emit_expansion(const char *pattern, int brace_start, int brace_end,
838 int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
844 if ((pattern_len = strlen(pattern)) == 0 || pattern_len >= INT_MAX)
847 tail_len = strlen(pattern + brace_end + 1);
848 if ((cp = malloc(brace_start + (sel_end - sel_start) +
849 tail_len + 1)) == NULL)
852 /* Pattern before initial brace */
853 if (brace_start > 0) {
854 memcpy(cp, pattern, brace_start);
857 /* Current braced selection */
858 if (sel_end - sel_start > 0) {
859 memcpy(cp + o, pattern + sel_start,
860 sel_end - sel_start);
861 o += sel_end - sel_start;
863 /* Remainder of pattern after closing brace */
865 memcpy(cp + o, pattern + brace_end + 1, tail_len);
869 if (append(cp, patternsp, npatternsp) != 0) {
877 * Expand the first encountered brace in pattern, appending the expanded
878 * patterns it yielded to the *patternsp array.
880 * Returns 0 on success or -1 on allocation failure.
882 * Signals whether expansion was performed via *expanded and whether
883 * pattern was invalid via *invalid.
886 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
887 int *expanded, int *invalid)
890 int in_bracket, brace_start, brace_end, brace_level;
891 int sel_start, sel_end;
893 *invalid = *expanded = 0;
895 if (find_brace(pattern, &brace_start, &brace_end) != 0) {
898 } else if (brace_start == -1)
901 in_bracket = brace_level = 0;
902 for (i = sel_start = brace_start + 1; i < brace_end; i++) {
903 switch (pattern[i]) {
921 if (i < brace_end - 1)
925 if (pattern[i] == ',' || i == brace_end - 1) {
926 if (in_bracket || brace_level > 0)
928 /* End of a selection, emit an expanded pattern */
930 /* Adjust end index for last selection */
931 sel_end = (i == brace_end - 1) ? brace_end : i;
932 if (emit_expansion(pattern, brace_start, brace_end,
933 sel_start, sel_end, patternsp, npatternsp) != 0)
935 /* move on to the next selection */
940 if (in_bracket || brace_level > 0) {
949 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
951 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
953 char *cp, *cp2, **active = NULL, **done = NULL;
954 size_t i, nactive = 0, ndone = 0;
955 int ret = -1, invalid = 0, expanded = 0;
960 /* Start the worklist with the original pattern */
961 if ((cp = strdup(pattern)) == NULL)
963 if (append(cp, &active, &nactive) != 0) {
967 while (nactive > 0) {
968 cp = active[nactive - 1];
970 if (brace_expand_one(cp, &active, &nactive,
971 &expanded, &invalid) == -1) {
976 fatal_f("invalid brace pattern \"%s\"", cp);
979 * Current entry expanded to new entries on the
980 * active list; discard the progenitor pattern.
986 * Pattern did not expand; append the finename component to
989 if ((cp2 = strrchr(cp, '/')) != NULL)
993 if (append(xstrdup(cp2), &done, &ndone) != 0) {
1001 *npatternsp = ndone;
1006 for (i = 0; i < nactive; i++)
1009 for (i = 0; i < ndone; i++)
1015 static struct sftp_conn *
1016 do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
1017 int *reminp, int *remoutp, int *pidp)
1019 if (sftp_direct == NULL) {
1020 if (do_cmd(ssh_program, host, user, port, 1, "sftp",
1021 reminp, remoutp, pidp) < 0)
1026 addargs(&args, "sftp-server");
1027 if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
1028 reminp, remoutp, pidp) < 0)
1031 return sftp_init(*reminp, *remoutp,
1032 sftp_copy_buflen, sftp_nrequests, limit_kbps);
1036 toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1038 char *suser = NULL, *host = NULL, *src = NULL;
1039 char *bp, *tuser, *thost, *targ;
1040 int sport = -1, tport = -1;
1041 struct sftp_conn *conn = NULL, *conn2 = NULL;
1047 memset(&alist, '\0', sizeof(alist));
1051 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
1053 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
1058 if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
1060 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
1066 /* Parse source files */
1067 for (i = 0; i < argc - 1; i++) {
1071 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1073 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1078 parse_user_host_path(argv[i], &suser, &host, &src);
1080 if (suser != NULL && !okname(suser)) {
1084 if (host && throughlocal) { /* extended remote to remote */
1085 if (mode == MODE_SFTP) {
1087 /* Connect to dest now */
1088 conn = do_sftp_connect(thost, tuser,
1090 &remin, &remout, &do_cmd_pid);
1092 fatal("Unable to open "
1093 "destination connection");
1095 debug3_f("origin in %d out %d pid %ld",
1096 remin, remout, (long)do_cmd_pid);
1099 * XXX remember suser/host/sport and only
1100 * reconnect if they change between arguments.
1101 * would save reconnections for cases like
1102 * scp -3 hosta:/foo hosta:/bar hostb:
1104 /* Connect to origin now */
1105 conn2 = do_sftp_connect(host, suser,
1107 &remin2, &remout2, &do_cmd_pid2);
1108 if (conn2 == NULL) {
1109 fatal("Unable to open "
1110 "source connection");
1112 debug3_f("destination in %d out %d pid %ld",
1113 remin2, remout2, (long)do_cmd_pid2);
1114 throughlocal_sftp(conn2, conn, src, targ);
1115 (void) close(remin2);
1116 (void) close(remout2);
1117 remin2 = remout2 = -1;
1118 if (waitpid(do_cmd_pid2, &status, 0) == -1)
1120 else if (!WIFEXITED(status) ||
1121 WEXITSTATUS(status) != 0)
1126 xasprintf(&bp, "%s -f %s%s", cmd,
1127 *src == '-' ? "-- " : "", src);
1128 if (do_cmd(ssh_program, host, suser, sport, 0,
1129 bp, &remin, &remout, &do_cmd_pid) < 0)
1132 xasprintf(&bp, "%s -t %s%s", cmd,
1133 *targ == '-' ? "-- " : "", targ);
1134 if (do_cmd2(thost, tuser, tport, bp,
1138 (void) close(remin);
1139 (void) close(remout);
1140 remin = remout = -1;
1142 } else if (host) { /* standard remote to remote */
1144 * Second remote user is passed to first remote side
1145 * via scp command-line. Ensure it contains no obvious
1148 if (tuser != NULL && !okname(tuser)) {
1152 if (tport != -1 && tport != SSH_DEFAULT_PORT) {
1153 /* This would require the remote support URIs */
1154 fatal("target port not supported with two "
1155 "remote hosts and the -R option");
1159 addargs(&alist, "%s", ssh_program);
1160 addargs(&alist, "-x");
1161 addargs(&alist, "-oClearAllForwardings=yes");
1162 addargs(&alist, "-n");
1163 for (j = 0; j < remote_remote_args.num; j++) {
1164 addargs(&alist, "%s",
1165 remote_remote_args.list[j]);
1169 addargs(&alist, "-p");
1170 addargs(&alist, "%d", sport);
1173 addargs(&alist, "-l");
1174 addargs(&alist, "%s", suser);
1176 addargs(&alist, "--");
1177 addargs(&alist, "%s", host);
1178 addargs(&alist, "%s", cmd);
1179 addargs(&alist, "%s", src);
1180 addargs(&alist, "%s%s%s:%s",
1181 tuser ? tuser : "", tuser ? "@" : "",
1183 if (do_local_cmd(&alist) != 0)
1185 } else { /* local to remote */
1186 if (mode == MODE_SFTP) {
1187 /* no need to glob: already done by shell */
1188 if (stat(argv[i], &sb) != 0) {
1189 fatal("stat local \"%s\": %s", argv[i],
1193 /* Connect to remote now */
1194 conn = do_sftp_connect(thost, tuser,
1196 &remin, &remout, &do_cmd_pid);
1198 fatal("Unable to open sftp "
1204 source_sftp(1, argv[i], targ, conn);
1209 xasprintf(&bp, "%s -t %s%s", cmd,
1210 *targ == '-' ? "-- " : "", targ);
1211 if (do_cmd(ssh_program, thost, tuser, tport, 0,
1212 bp, &remin, &remout, &do_cmd_pid) < 0)
1218 source(1, argv + i);
1222 if (mode == MODE_SFTP)
1233 tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1235 char *bp, *host = NULL, *src = NULL, *suser = NULL;
1237 struct sftp_conn *conn = NULL;
1238 int i, r, sport = -1;
1240 memset(&alist, '\0', sizeof(alist));
1243 for (i = 0; i < argc - 1; i++) {
1247 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1249 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1254 parse_user_host_path(argv[i], &suser, &host, &src);
1255 if (suser != NULL && !okname(suser)) {
1259 if (!host) { /* Local to local. */
1261 addargs(&alist, "%s", _PATH_CP);
1263 addargs(&alist, "-r");
1265 addargs(&alist, "-p");
1266 addargs(&alist, "--");
1267 addargs(&alist, "%s", argv[i]);
1268 addargs(&alist, "%s", argv[argc-1]);
1269 if (do_local_cmd(&alist))
1273 /* Remote to local. */
1274 if (mode == MODE_SFTP) {
1275 conn = do_sftp_connect(host, suser, sport,
1276 sftp_direct, &remin, &remout, &do_cmd_pid);
1278 error("sftp connection failed");
1284 sink_sftp(1, argv[argc - 1], src, conn);
1287 (void) close(remin);
1288 (void) close(remout);
1289 remin = remout = -1;
1293 xasprintf(&bp, "%s -f %s%s",
1294 cmd, *src == '-' ? "-- " : "", src);
1295 if (do_cmd(ssh_program, host, suser, sport, 0, bp,
1296 &remin, &remout, &do_cmd_pid) < 0) {
1302 sink(1, argv + argc - 1, src);
1303 (void) close(remin);
1304 remin = remout = -1;
1311 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1313 prepare_remote_path(struct sftp_conn *conn, const char *path)
1317 /* Handle ~ prefixed paths */
1318 if (*path == '\0' || strcmp(path, "~") == 0)
1319 return xstrdup(".");
1321 return xstrdup(path);
1322 if (strncmp(path, "~/", 2) == 0) {
1323 if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
1324 return xstrdup(".");
1325 return xstrdup(path + 2 + nslash);
1327 if (sftp_can_expand_path(conn))
1328 return sftp_expand_path(conn, path);
1329 /* No protocol extension */
1330 error("server expand-path extension is required "
1331 "for ~user paths in SFTP mode");
1336 source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
1338 char *target = NULL, *filename = NULL, *abs_dst = NULL;
1339 int src_is_dir, target_is_dir;
1343 memset(&a, '\0', sizeof(a));
1344 if (stat(src, &st) != 0)
1345 fatal("stat local \"%s\": %s", src, strerror(errno));
1346 src_is_dir = S_ISDIR(st.st_mode);
1347 if ((filename = basename(src)) == NULL)
1348 fatal("basename \"%s\": %s", src, strerror(errno));
1351 * No need to glob here - the local shell already took care of
1354 if ((target = prepare_remote_path(conn, targ)) == NULL)
1356 target_is_dir = sftp_remote_is_dir(conn, target);
1357 if (targetshouldbedirectory && !target_is_dir) {
1358 debug("target directory \"%s\" does not exist", target);
1359 a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
1360 a.perm = st.st_mode | 0700; /* ensure writable */
1361 if (sftp_mkdir(conn, target, &a, 1) != 0)
1362 cleanup_exit(255); /* error already logged */
1366 abs_dst = sftp_path_append(target, filename);
1371 debug3_f("copying local %s to remote %s", src, abs_dst);
1373 if (src_is_dir && iamrecursive) {
1374 if (sftp_upload_dir(conn, src, abs_dst, pflag,
1375 SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
1376 error("failed to upload directory %s to %s", src, targ);
1379 } else if (sftp_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
1380 error("failed to upload file %s to %s", src, targ);
1389 source(int argc, char **argv)
1396 int fd = -1, haderr, indx;
1397 char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1400 for (indx = 0; indx < argc; ++indx) {
1404 while (len > 1 && name[len-1] == '/')
1406 if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1408 if (strchr(name, '\n') != NULL) {
1409 strnvis(encname, name, sizeof(encname), VIS_NL);
1412 if (fstat(fd, &stb) == -1) {
1413 syserr: run_err("%s: %s", name, strerror(errno));
1416 if (stb.st_size < 0) {
1417 run_err("%s: %s", name, "Negative file size");
1421 switch (stb.st_mode & S_IFMT) {
1426 rsource(name, &stb);
1431 run_err("%s: not a regular file", name);
1434 if ((last = strrchr(name, '/')) == NULL)
1440 if (do_times(remout, verbose_mode, &stb) < 0)
1443 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1444 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1445 (u_int) (stb.st_mode & FILEMODEMASK),
1446 (long long)stb.st_size, last);
1448 fmprintf(stderr, "Sending file modes: %s", buf);
1449 (void) atomicio(vwrite, remout, buf, strlen(buf));
1452 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1453 next: if (fd != -1) {
1460 start_progress_meter(curfile, stb.st_size, &statbytes);
1461 set_nonblock(remout);
1462 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1464 if (i + (off_t)amt > stb.st_size)
1465 amt = stb.st_size - i;
1467 if ((nr = atomicio(read, fd,
1468 bp->buf, amt)) != amt) {
1470 memset(bp->buf + nr, 0, amt - nr);
1473 /* Keep writing after error to retain sync */
1475 (void)atomicio(vwrite, remout, bp->buf, amt);
1476 memset(bp->buf, 0, amt);
1479 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1483 unset_nonblock(remout);
1486 if (close(fd) == -1 && !haderr)
1491 (void) atomicio(vwrite, remout, "", 1);
1493 run_err("%s: %s", name, strerror(haderr));
1496 stop_progress_meter();
1501 rsource(char *name, struct stat *statp)
1505 char *last, *vect[1], path[PATH_MAX];
1507 if (!(dirp = opendir(name))) {
1508 run_err("%s: %s", name, strerror(errno));
1511 last = strrchr(name, '/');
1517 if (do_times(remout, verbose_mode, statp) < 0) {
1522 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1523 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1525 fmprintf(stderr, "Entering directory: %s", path);
1526 (void) atomicio(vwrite, remout, path, strlen(path));
1527 if (response() < 0) {
1531 while ((dp = readdir(dirp)) != NULL) {
1534 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1536 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1537 run_err("%s/%s: name too long", name, dp->d_name);
1540 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1544 (void) closedir(dirp);
1545 (void) atomicio(vwrite, remout, "E\n", 2);
1550 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
1552 char *abs_src = NULL;
1553 char *abs_dst = NULL;
1555 char *filename, *tmp = NULL;
1556 int i, r, err = 0, dst_is_dir;
1559 memset(&g, 0, sizeof(g));
1562 * Here, we need remote glob as SFTP can not depend on remote shell
1565 if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
1570 debug3_f("copying remote %s to local %s", abs_src, dst);
1571 if ((r = sftp_glob(conn, abs_src, GLOB_NOCHECK|GLOB_MARK,
1573 if (r == GLOB_NOSPACE)
1574 error("%s: too many glob matches", src);
1576 error("%s: %s", src, strerror(ENOENT));
1581 /* Did we actually get any matches back from the glob? */
1582 if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
1584 * If nothing matched but a path returned, then it's probably
1585 * a GLOB_NOCHECK result. Check whether the unglobbed path
1586 * exists so we can give a nice error message early.
1588 if (sftp_stat(conn, g.gl_pathv[0], 1, NULL) != 0) {
1589 error("%s: %s", src, strerror(ENOENT));
1595 if ((r = stat(dst, &st)) != 0)
1596 debug2_f("stat local \"%s\": %s", dst, strerror(errno));
1597 dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
1599 if (g.gl_matchc > 1 && !dst_is_dir) {
1601 error("Multiple files match pattern, but destination "
1602 "\"%s\" is not a directory", dst);
1606 debug2_f("creating destination \"%s\"", dst);
1607 if (mkdir(dst, 0777) != 0) {
1608 error("local mkdir \"%s\": %s", dst, strerror(errno));
1615 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1616 tmp = xstrdup(g.gl_pathv[i]);
1617 if ((filename = basename(tmp)) == NULL) {
1618 error("basename %s: %s", tmp, strerror(errno));
1624 abs_dst = sftp_path_append(dst, filename);
1626 abs_dst = xstrdup(dst);
1628 debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1629 if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1630 if (sftp_download_dir(conn, g.gl_pathv[i], abs_dst,
1631 NULL, pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
1634 if (sftp_download(conn, g.gl_pathv[i], abs_dst, NULL,
1635 pflag, 0, 0, 1) == -1)
1653 #define TYPE_OVERFLOW(type, val) \
1654 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
1655 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1656 (sizeof(type) != 4 && sizeof(type) != 8))
1659 sink(int argc, char **argv, const char *src)
1666 int amt, exists, first, ofd;
1667 mode_t mode, omode, mask;
1668 off_t size, statbytes;
1669 unsigned long long ull;
1670 int setimes, targisdir, wrerr;
1671 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1672 char **patterns = NULL;
1673 size_t n, npatterns = 0;
1674 struct timeval tv[2];
1678 #define SCREWUP(str) { why = str; goto screwup; }
1680 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1681 SCREWUP("Unexpected off_t/time_t size");
1683 setimes = targisdir = 0;
1688 run_err("ambiguous target");
1692 if (targetshouldbedirectory)
1695 (void) atomicio(vwrite, remout, "", 1);
1696 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1698 if (src != NULL && !iamrecursive && !Tflag) {
1700 * Prepare to try to restrict incoming filenames to match
1701 * the requested destination file glob.
1703 if (brace_expand(src, &patterns, &npatterns) != 0)
1704 fatal_f("could not expand pattern");
1706 for (first = 1;; first = 0) {
1708 if (atomicio(read, remin, cp, 1) != 1)
1711 SCREWUP("unexpected <newline>");
1713 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1714 SCREWUP("lost connection");
1716 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1719 fmprintf(stderr, "Sink: %s", buf);
1721 if (buf[0] == '\01' || buf[0] == '\02') {
1722 if (iamremote == 0) {
1723 (void) snmprintf(visbuf, sizeof(visbuf),
1724 NULL, "%s", buf + 1);
1725 (void) atomicio(vwrite, STDERR_FILENO,
1726 visbuf, strlen(visbuf));
1728 if (buf[0] == '\02')
1733 if (buf[0] == 'E') {
1734 (void) atomicio(vwrite, remout, "", 1);
1744 if (!isdigit((unsigned char)*cp))
1745 SCREWUP("mtime.sec not present");
1746 ull = strtoull(cp, &cp, 10);
1747 if (!cp || *cp++ != ' ')
1748 SCREWUP("mtime.sec not delimited");
1749 if (TYPE_OVERFLOW(time_t, ull))
1750 setimes = 0; /* out of range */
1752 mtime.tv_usec = strtol(cp, &cp, 10);
1753 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1754 mtime.tv_usec > 999999)
1755 SCREWUP("mtime.usec not delimited");
1756 if (!isdigit((unsigned char)*cp))
1757 SCREWUP("atime.sec not present");
1758 ull = strtoull(cp, &cp, 10);
1759 if (!cp || *cp++ != ' ')
1760 SCREWUP("atime.sec not delimited");
1761 if (TYPE_OVERFLOW(time_t, ull))
1762 setimes = 0; /* out of range */
1764 atime.tv_usec = strtol(cp, &cp, 10);
1765 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1766 atime.tv_usec > 999999)
1767 SCREWUP("atime.usec not delimited");
1768 (void) atomicio(vwrite, remout, "", 1);
1771 if (*cp != 'C' && *cp != 'D') {
1773 * Check for the case "rcp remote:foo\* local:bar".
1774 * In this case, the line "No match." can be returned
1775 * by the shell before the rcp command on the remote is
1776 * executed so the ^Aerror_message convention isn't
1783 SCREWUP("expected control record");
1786 for (++cp; cp < buf + 5; cp++) {
1787 if (*cp < '0' || *cp > '7')
1788 SCREWUP("bad mode");
1789 mode = (mode << 3) | (*cp - '0');
1794 SCREWUP("mode not delimited");
1796 if (!isdigit((unsigned char)*cp))
1797 SCREWUP("size not present");
1798 ull = strtoull(cp, &cp, 10);
1799 if (!cp || *cp++ != ' ')
1800 SCREWUP("size not delimited");
1801 if (TYPE_OVERFLOW(off_t, ull))
1802 SCREWUP("size out of range");
1805 if (*cp == '\0' || strchr(cp, '/') != NULL ||
1806 strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1807 run_err("error: unexpected filename: %s", cp);
1810 if (npatterns > 0) {
1811 for (n = 0; n < npatterns; n++) {
1812 if (strcmp(patterns[n], cp) == 0 ||
1813 fnmatch(patterns[n], cp, 0) == 0)
1816 if (n >= npatterns) {
1817 debug2_f("incoming filename \"%s\" does not "
1818 "match any of %zu expected patterns", cp,
1820 for (n = 0; n < npatterns; n++) {
1821 debug3_f("expected pattern %zu: \"%s\"",
1824 SCREWUP("filename does not match request");
1828 static char *namebuf;
1829 static size_t cursize;
1832 need = strlen(targ) + strlen(cp) + 250;
1833 if (need > cursize) {
1835 namebuf = xmalloc(need);
1838 (void) snprintf(namebuf, need, "%s%s%s", targ,
1839 strcmp(targ, "/") ? "/" : "", cp);
1844 exists = stat(np, &stb) == 0;
1845 if (buf[0] == 'D') {
1846 int mod_flag = pflag;
1848 SCREWUP("received directory without -r");
1850 if (!S_ISDIR(stb.st_mode)) {
1855 (void) chmod(np, mode);
1857 /* Handle copying from a read-only directory */
1859 if (mkdir(np, mode | S_IRWXU) == -1)
1862 vect[0] = xstrdup(np);
1866 (void) utimes(vect[0], tv);
1869 (void) chmod(vect[0], mode);
1875 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1876 bad: run_err("%s: %s", np, strerror(errno));
1879 (void) atomicio(vwrite, remout, "", 1);
1880 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1888 * NB. do not use run_err() unless immediately followed by
1889 * exit() below as it may send a spurious reply that might
1890 * desyncronise us from the peer. Use note_err() instead.
1894 start_progress_meter(curfile, size, &statbytes);
1895 set_nonblock(remin);
1896 for (count = i = 0; i < size; i += bp->cnt) {
1902 j = atomicio6(read, remin, cp, amt,
1905 run_err("%s", j != EPIPE ?
1907 "dropped connection");
1914 if (count == bp->cnt) {
1915 /* Keep reading so we stay sync'd up. */
1917 if (atomicio(vwrite, ofd, bp->buf,
1919 note_err("%s: %s", np,
1928 unset_nonblock(remin);
1929 if (count != 0 && !wrerr &&
1930 atomicio(vwrite, ofd, bp->buf, count) != count) {
1931 note_err("%s: %s", np, strerror(errno));
1934 if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1935 ftruncate(ofd, size) != 0)
1936 note_err("%s: truncate: %s", np, strerror(errno));
1938 if (exists || omode != mode)
1940 if (fchmod(ofd, omode)) {
1941 #else /* HAVE_FCHMOD */
1942 if (chmod(np, omode)) {
1943 #endif /* HAVE_FCHMOD */
1944 note_err("%s: set mode: %s",
1945 np, strerror(errno));
1948 if (!exists && omode != mode)
1950 if (fchmod(ofd, omode & ~mask)) {
1951 #else /* HAVE_FCHMOD */
1952 if (chmod(np, omode & ~mask)) {
1953 #endif /* HAVE_FCHMOD */
1954 note_err("%s: set mode: %s",
1955 np, strerror(errno));
1958 if (close(ofd) == -1)
1959 note_err("%s: close: %s", np, strerror(errno));
1962 stop_progress_meter();
1963 if (setimes && !wrerr) {
1965 if (utimes(np, tv) == -1) {
1966 note_err("%s: set times: %s",
1967 np, strerror(errno));
1970 /* If no error was noted then signal success for this file */
1971 if (note_err(NULL) == 0)
1972 (void) atomicio(vwrite, remout, "", 1);
1975 for (n = 0; n < npatterns; n++)
1980 for (n = 0; n < npatterns; n++)
1983 run_err("protocol error: %s", why);
1988 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
1989 char *src, char *targ)
1991 char *target = NULL, *filename = NULL, *abs_dst = NULL;
1992 char *abs_src = NULL, *tmp = NULL;
1994 int i, r, targetisdir, err = 0;
1996 if ((filename = basename(src)) == NULL)
1997 fatal("basename %s: %s", src, strerror(errno));
1999 if ((abs_src = prepare_remote_path(from, src)) == NULL ||
2000 (target = prepare_remote_path(to, targ)) == NULL)
2002 memset(&g, 0, sizeof(g));
2004 targetisdir = sftp_remote_is_dir(to, target);
2005 if (!targetisdir && targetshouldbedirectory) {
2006 error("%s: destination is not a directory", targ);
2011 debug3_f("copying remote %s to remote %s", abs_src, target);
2012 if ((r = sftp_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
2014 if (r == GLOB_NOSPACE)
2015 error("%s: too many glob matches", src);
2017 error("%s: %s", src, strerror(ENOENT));
2022 /* Did we actually get any matches back from the glob? */
2023 if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
2025 * If nothing matched but a path returned, then it's probably
2026 * a GLOB_NOCHECK result. Check whether the unglobbed path
2027 * exists so we can give a nice error message early.
2029 if (sftp_stat(from, g.gl_pathv[0], 1, NULL) != 0) {
2030 error("%s: %s", src, strerror(ENOENT));
2036 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2037 tmp = xstrdup(g.gl_pathv[i]);
2038 if ((filename = basename(tmp)) == NULL) {
2039 error("basename %s: %s", tmp, strerror(errno));
2045 abs_dst = sftp_path_append(target, filename);
2047 abs_dst = xstrdup(target);
2049 debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
2050 if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
2051 if (sftp_crossload_dir(from, to, g.gl_pathv[i], abs_dst,
2052 NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
2055 if (sftp_crossload(from, to, g.gl_pathv[i], abs_dst,
2078 char ch, *cp, resp, rbuf[2048], visbuf[2048];
2080 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
2090 case 1: /* error, followed by error msg */
2091 case 2: /* fatal error, "" */
2093 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
2096 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
2100 (void) snmprintf(visbuf, sizeof(visbuf),
2101 NULL, "%s\n", rbuf);
2102 (void) atomicio(vwrite, STDERR_FILENO,
2103 visbuf, strlen(visbuf));
2116 (void) fprintf(stderr,
2117 "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2118 " [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2119 " [-P port] [-S program] [-X sftp_option] source ... target\n");
2124 run_err(const char *fmt,...)
2130 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2131 (void) fprintf(fp, "%c", 0x01);
2132 (void) fprintf(fp, "scp: ");
2134 (void) vfprintf(fp, fmt, ap);
2136 (void) fprintf(fp, "\n");
2142 vfmprintf(stderr, fmt, ap);
2144 fprintf(stderr, "\n");
2149 * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2150 * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2151 * any active error at the end of the transfer.
2154 note_err(const char *fmt, ...)
2159 /* Replay any previously-noted error */
2163 run_err("%s", emsg);
2170 /* Prefer first-noted error */
2175 vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
2185 if (!stat(cp, &stb)) {
2186 if (S_ISDIR(stb.st_mode))
2190 run_err("%s: %s", cp, strerror(errno));
2205 if (!isalpha(c) && !isdigit((unsigned char)c)) {
2220 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
2225 allocbuf(BUF *bp, int fd, int blksize)
2228 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2231 if (fstat(fd, &stb) == -1) {
2232 run_err("fstat: %s", strerror(errno));
2235 size = ROUNDUP(stb.st_blksize, blksize);
2238 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2240 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2241 if (bp->cnt >= size)
2243 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2252 (void)write(STDERR_FILENO, "lost connection\n", 16);
2271 (void)waitpid(do_cmd_pid, NULL, 0);
2272 if (do_cmd_pid2 > 0)
2273 (void)waitpid(do_cmd_pid2, NULL, 0);