1 /* $OpenBSD: scp.c,v 1.253 2023/03/03 03:12:24 dtucker 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 remote_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 waitpid(do_cmd_pid, NULL, 0);
199 if (do_cmd_pid2 > 1) {
200 kill(do_cmd_pid2, signo ? signo : SIGTERM);
201 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_SCP;
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)
841 int o = 0, tail_len = strlen(pattern + brace_end + 1);
843 if ((cp = malloc(brace_start + (sel_end - sel_start) +
844 tail_len + 1)) == NULL)
847 /* Pattern before initial brace */
848 if (brace_start > 0) {
849 memcpy(cp, pattern, brace_start);
852 /* Current braced selection */
853 if (sel_end - sel_start > 0) {
854 memcpy(cp + o, pattern + sel_start,
855 sel_end - sel_start);
856 o += sel_end - sel_start;
858 /* Remainder of pattern after closing brace */
860 memcpy(cp + o, pattern + brace_end + 1, tail_len);
864 if (append(cp, patternsp, npatternsp) != 0) {
872 * Expand the first encountered brace in pattern, appending the expanded
873 * patterns it yielded to the *patternsp array.
875 * Returns 0 on success or -1 on allocation failure.
877 * Signals whether expansion was performed via *expanded and whether
878 * pattern was invalid via *invalid.
881 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
882 int *expanded, int *invalid)
885 int in_bracket, brace_start, brace_end, brace_level;
886 int sel_start, sel_end;
888 *invalid = *expanded = 0;
890 if (find_brace(pattern, &brace_start, &brace_end) != 0) {
893 } else if (brace_start == -1)
896 in_bracket = brace_level = 0;
897 for (i = sel_start = brace_start + 1; i < brace_end; i++) {
898 switch (pattern[i]) {
916 if (i < brace_end - 1)
920 if (pattern[i] == ',' || i == brace_end - 1) {
921 if (in_bracket || brace_level > 0)
923 /* End of a selection, emit an expanded pattern */
925 /* Adjust end index for last selection */
926 sel_end = (i == brace_end - 1) ? brace_end : i;
927 if (emit_expansion(pattern, brace_start, brace_end,
928 sel_start, sel_end, patternsp, npatternsp) != 0)
930 /* move on to the next selection */
935 if (in_bracket || brace_level > 0) {
944 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
946 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
948 char *cp, *cp2, **active = NULL, **done = NULL;
949 size_t i, nactive = 0, ndone = 0;
950 int ret = -1, invalid = 0, expanded = 0;
955 /* Start the worklist with the original pattern */
956 if ((cp = strdup(pattern)) == NULL)
958 if (append(cp, &active, &nactive) != 0) {
962 while (nactive > 0) {
963 cp = active[nactive - 1];
965 if (brace_expand_one(cp, &active, &nactive,
966 &expanded, &invalid) == -1) {
971 fatal_f("invalid brace pattern \"%s\"", cp);
974 * Current entry expanded to new entries on the
975 * active list; discard the progenitor pattern.
981 * Pattern did not expand; append the finename component to
984 if ((cp2 = strrchr(cp, '/')) != NULL)
988 if (append(xstrdup(cp2), &done, &ndone) != 0) {
1001 for (i = 0; i < nactive; i++)
1004 for (i = 0; i < ndone; i++)
1010 static struct sftp_conn *
1011 do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
1012 int *reminp, int *remoutp, int *pidp)
1014 if (sftp_direct == NULL) {
1015 if (do_cmd(ssh_program, host, user, port, 1, "sftp",
1016 reminp, remoutp, pidp) < 0)
1021 addargs(&args, "sftp-server");
1022 if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
1023 reminp, remoutp, pidp) < 0)
1026 return do_init(*reminp, *remoutp,
1027 sftp_copy_buflen, sftp_nrequests, limit_kbps);
1031 toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1033 char *suser = NULL, *host = NULL, *src = NULL;
1034 char *bp, *tuser, *thost, *targ;
1035 int sport = -1, tport = -1;
1036 struct sftp_conn *conn = NULL, *conn2 = NULL;
1041 memset(&alist, '\0', sizeof(alist));
1045 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
1047 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
1052 if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
1054 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
1060 /* Parse source files */
1061 for (i = 0; i < argc - 1; i++) {
1065 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1067 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1072 parse_user_host_path(argv[i], &suser, &host, &src);
1074 if (suser != NULL && !okname(suser)) {
1078 if (host && throughlocal) { /* extended remote to remote */
1079 if (mode == MODE_SFTP) {
1081 /* Connect to dest now */
1082 conn = do_sftp_connect(thost, tuser,
1084 &remin, &remout, &do_cmd_pid);
1086 fatal("Unable to open "
1087 "destination connection");
1089 debug3_f("origin in %d out %d pid %ld",
1090 remin, remout, (long)do_cmd_pid);
1093 * XXX remember suser/host/sport and only
1094 * reconnect if they change between arguments.
1095 * would save reconnections for cases like
1096 * scp -3 hosta:/foo hosta:/bar hostb:
1098 /* Connect to origin now */
1099 conn2 = do_sftp_connect(host, suser,
1101 &remin2, &remout2, &do_cmd_pid2);
1102 if (conn2 == NULL) {
1103 fatal("Unable to open "
1104 "source connection");
1106 debug3_f("destination in %d out %d pid %ld",
1107 remin2, remout2, (long)do_cmd_pid2);
1108 throughlocal_sftp(conn2, conn, src, targ);
1109 (void) close(remin2);
1110 (void) close(remout2);
1111 remin2 = remout2 = -1;
1112 if (waitpid(do_cmd_pid2, &status, 0) == -1)
1114 else if (!WIFEXITED(status) ||
1115 WEXITSTATUS(status) != 0)
1120 xasprintf(&bp, "%s -f %s%s", cmd,
1121 *src == '-' ? "-- " : "", src);
1122 if (do_cmd(ssh_program, host, suser, sport, 0,
1123 bp, &remin, &remout, &do_cmd_pid) < 0)
1126 xasprintf(&bp, "%s -t %s%s", cmd,
1127 *targ == '-' ? "-- " : "", targ);
1128 if (do_cmd2(thost, tuser, tport, bp,
1132 (void) close(remin);
1133 (void) close(remout);
1134 remin = remout = -1;
1136 } else if (host) { /* standard remote to remote */
1138 * Second remote user is passed to first remote side
1139 * via scp command-line. Ensure it contains no obvious
1142 if (tuser != NULL && !okname(tuser)) {
1146 if (tport != -1 && tport != SSH_DEFAULT_PORT) {
1147 /* This would require the remote support URIs */
1148 fatal("target port not supported with two "
1149 "remote hosts and the -R option");
1153 addargs(&alist, "%s", ssh_program);
1154 addargs(&alist, "-x");
1155 addargs(&alist, "-oClearAllForwardings=yes");
1156 addargs(&alist, "-n");
1157 for (j = 0; j < remote_remote_args.num; j++) {
1158 addargs(&alist, "%s",
1159 remote_remote_args.list[j]);
1163 addargs(&alist, "-p");
1164 addargs(&alist, "%d", sport);
1167 addargs(&alist, "-l");
1168 addargs(&alist, "%s", suser);
1170 addargs(&alist, "--");
1171 addargs(&alist, "%s", host);
1172 addargs(&alist, "%s", cmd);
1173 addargs(&alist, "%s", src);
1174 addargs(&alist, "%s%s%s:%s",
1175 tuser ? tuser : "", tuser ? "@" : "",
1177 if (do_local_cmd(&alist) != 0)
1179 } else { /* local to remote */
1180 if (mode == MODE_SFTP) {
1182 /* Connect to remote now */
1183 conn = do_sftp_connect(thost, tuser,
1185 &remin, &remout, &do_cmd_pid);
1187 fatal("Unable to open sftp "
1193 source_sftp(1, argv[i], targ, conn);
1198 xasprintf(&bp, "%s -t %s%s", cmd,
1199 *targ == '-' ? "-- " : "", targ);
1200 if (do_cmd(ssh_program, thost, tuser, tport, 0,
1201 bp, &remin, &remout, &do_cmd_pid) < 0)
1207 source(1, argv + i);
1211 if (mode == MODE_SFTP)
1222 tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1224 char *bp, *host = NULL, *src = NULL, *suser = NULL;
1226 struct sftp_conn *conn = NULL;
1227 int i, r, sport = -1;
1229 memset(&alist, '\0', sizeof(alist));
1232 for (i = 0; i < argc - 1; i++) {
1236 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1238 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1243 parse_user_host_path(argv[i], &suser, &host, &src);
1244 if (suser != NULL && !okname(suser)) {
1248 if (!host) { /* Local to local. */
1250 addargs(&alist, "%s", _PATH_CP);
1252 addargs(&alist, "-r");
1254 addargs(&alist, "-p");
1255 addargs(&alist, "--");
1256 addargs(&alist, "%s", argv[i]);
1257 addargs(&alist, "%s", argv[argc-1]);
1258 if (do_local_cmd(&alist))
1262 /* Remote to local. */
1263 if (mode == MODE_SFTP) {
1264 conn = do_sftp_connect(host, suser, sport,
1265 sftp_direct, &remin, &remout, &do_cmd_pid);
1267 error("sftp connection failed");
1273 sink_sftp(1, argv[argc - 1], src, conn);
1276 (void) close(remin);
1277 (void) close(remout);
1278 remin = remout = -1;
1282 xasprintf(&bp, "%s -f %s%s",
1283 cmd, *src == '-' ? "-- " : "", src);
1284 if (do_cmd(ssh_program, host, suser, sport, 0, bp,
1285 &remin, &remout, &do_cmd_pid) < 0) {
1291 sink(1, argv + argc - 1, src);
1292 (void) close(remin);
1293 remin = remout = -1;
1300 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1302 prepare_remote_path(struct sftp_conn *conn, const char *path)
1306 /* Handle ~ prefixed paths */
1307 if (*path == '\0' || strcmp(path, "~") == 0)
1308 return xstrdup(".");
1310 return xstrdup(path);
1311 if (strncmp(path, "~/", 2) == 0) {
1312 if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
1313 return xstrdup(".");
1314 return xstrdup(path + 2 + nslash);
1316 if (can_expand_path(conn))
1317 return do_expand_path(conn, path);
1318 /* No protocol extension */
1319 error("server expand-path extension is required "
1320 "for ~user paths in SFTP mode");
1325 source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
1327 char *target = NULL, *filename = NULL, *abs_dst = NULL;
1328 int src_is_dir, target_is_dir;
1332 memset(&a, '\0', sizeof(a));
1333 if (stat(src, &st) != 0)
1334 fatal("stat local \"%s\": %s", src, strerror(errno));
1335 src_is_dir = S_ISDIR(st.st_mode);
1336 if ((filename = basename(src)) == NULL)
1337 fatal("basename \"%s\": %s", src, strerror(errno));
1340 * No need to glob here - the local shell already took care of
1343 if ((target = prepare_remote_path(conn, targ)) == NULL)
1345 target_is_dir = remote_is_dir(conn, target);
1346 if (targetshouldbedirectory && !target_is_dir) {
1347 debug("target directory \"%s\" does not exist", target);
1348 a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
1349 a.perm = st.st_mode | 0700; /* ensure writable */
1350 if (do_mkdir(conn, target, &a, 1) != 0)
1351 cleanup_exit(255); /* error already logged */
1355 abs_dst = path_append(target, filename);
1360 debug3_f("copying local %s to remote %s", src, abs_dst);
1362 if (src_is_dir && iamrecursive) {
1363 if (upload_dir(conn, src, abs_dst, pflag,
1364 SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
1365 error("failed to upload directory %s to %s", src, targ);
1368 } else if (do_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
1369 error("failed to upload file %s to %s", src, targ);
1378 source(int argc, char **argv)
1385 int fd = -1, haderr, indx;
1386 char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1389 for (indx = 0; indx < argc; ++indx) {
1393 while (len > 1 && name[len-1] == '/')
1395 if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1397 if (strchr(name, '\n') != NULL) {
1398 strnvis(encname, name, sizeof(encname), VIS_NL);
1401 if (fstat(fd, &stb) == -1) {
1402 syserr: run_err("%s: %s", name, strerror(errno));
1405 if (stb.st_size < 0) {
1406 run_err("%s: %s", name, "Negative file size");
1410 switch (stb.st_mode & S_IFMT) {
1415 rsource(name, &stb);
1420 run_err("%s: not a regular file", name);
1423 if ((last = strrchr(name, '/')) == NULL)
1429 if (do_times(remout, verbose_mode, &stb) < 0)
1432 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1433 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1434 (u_int) (stb.st_mode & FILEMODEMASK),
1435 (long long)stb.st_size, last);
1437 fmprintf(stderr, "Sending file modes: %s", buf);
1438 (void) atomicio(vwrite, remout, buf, strlen(buf));
1441 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1442 next: if (fd != -1) {
1449 start_progress_meter(curfile, stb.st_size, &statbytes);
1450 set_nonblock(remout);
1451 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1453 if (i + (off_t)amt > stb.st_size)
1454 amt = stb.st_size - i;
1456 if ((nr = atomicio(read, fd,
1457 bp->buf, amt)) != amt) {
1459 memset(bp->buf + nr, 0, amt - nr);
1462 /* Keep writing after error to retain sync */
1464 (void)atomicio(vwrite, remout, bp->buf, amt);
1465 memset(bp->buf, 0, amt);
1468 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1472 unset_nonblock(remout);
1475 if (close(fd) == -1 && !haderr)
1480 (void) atomicio(vwrite, remout, "", 1);
1482 run_err("%s: %s", name, strerror(haderr));
1485 stop_progress_meter();
1490 rsource(char *name, struct stat *statp)
1494 char *last, *vect[1], path[PATH_MAX];
1496 if (!(dirp = opendir(name))) {
1497 run_err("%s: %s", name, strerror(errno));
1500 last = strrchr(name, '/');
1506 if (do_times(remout, verbose_mode, statp) < 0) {
1511 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1512 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1514 fmprintf(stderr, "Entering directory: %s", path);
1515 (void) atomicio(vwrite, remout, path, strlen(path));
1516 if (response() < 0) {
1520 while ((dp = readdir(dirp)) != NULL) {
1523 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1525 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1526 run_err("%s/%s: name too long", name, dp->d_name);
1529 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1533 (void) closedir(dirp);
1534 (void) atomicio(vwrite, remout, "E\n", 2);
1539 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
1541 char *abs_src = NULL;
1542 char *abs_dst = NULL;
1544 char *filename, *tmp = NULL;
1545 int i, r, err = 0, dst_is_dir;
1548 memset(&g, 0, sizeof(g));
1551 * Here, we need remote glob as SFTP can not depend on remote shell
1554 if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
1559 debug3_f("copying remote %s to local %s", abs_src, dst);
1560 if ((r = remote_glob(conn, abs_src, GLOB_NOCHECK|GLOB_MARK,
1562 if (r == GLOB_NOSPACE)
1563 error("%s: too many glob matches", src);
1565 error("%s: %s", src, strerror(ENOENT));
1570 /* Did we actually get any matches back from the glob? */
1571 if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
1573 * If nothing matched but a path returned, then it's probably
1574 * a GLOB_NOCHECK result. Check whether the unglobbed path
1575 * exists so we can give a nice error message early.
1577 if (do_stat(conn, g.gl_pathv[0], 1) == NULL) {
1578 error("%s: %s", src, strerror(ENOENT));
1584 if ((r = stat(dst, &st)) != 0)
1585 debug2_f("stat local \"%s\": %s", dst, strerror(errno));
1586 dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
1588 if (g.gl_matchc > 1 && !dst_is_dir) {
1590 error("Multiple files match pattern, but destination "
1591 "\"%s\" is not a directory", dst);
1595 debug2_f("creating destination \"%s\"", dst);
1596 if (mkdir(dst, 0777) != 0) {
1597 error("local mkdir \"%s\": %s", dst, strerror(errno));
1604 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1605 tmp = xstrdup(g.gl_pathv[i]);
1606 if ((filename = basename(tmp)) == NULL) {
1607 error("basename %s: %s", tmp, strerror(errno));
1613 abs_dst = path_append(dst, filename);
1615 abs_dst = xstrdup(dst);
1617 debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1618 if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1619 if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL,
1620 pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
1623 if (do_download(conn, g.gl_pathv[i], abs_dst, NULL,
1624 pflag, 0, 0, 1) == -1)
1642 #define TYPE_OVERFLOW(type, val) \
1643 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
1644 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1645 (sizeof(type) != 4 && sizeof(type) != 8))
1648 sink(int argc, char **argv, const char *src)
1655 int amt, exists, first, ofd;
1656 mode_t mode, omode, mask;
1657 off_t size, statbytes;
1658 unsigned long long ull;
1659 int setimes, targisdir, wrerr;
1660 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1661 char **patterns = NULL;
1662 size_t n, npatterns = 0;
1663 struct timeval tv[2];
1667 #define SCREWUP(str) { why = str; goto screwup; }
1669 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1670 SCREWUP("Unexpected off_t/time_t size");
1672 setimes = targisdir = 0;
1677 run_err("ambiguous target");
1681 if (targetshouldbedirectory)
1684 (void) atomicio(vwrite, remout, "", 1);
1685 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1687 if (src != NULL && !iamrecursive && !Tflag) {
1689 * Prepare to try to restrict incoming filenames to match
1690 * the requested destination file glob.
1692 if (brace_expand(src, &patterns, &npatterns) != 0)
1693 fatal_f("could not expand pattern");
1695 for (first = 1;; first = 0) {
1697 if (atomicio(read, remin, cp, 1) != 1)
1700 SCREWUP("unexpected <newline>");
1702 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1703 SCREWUP("lost connection");
1705 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1708 fmprintf(stderr, "Sink: %s", buf);
1710 if (buf[0] == '\01' || buf[0] == '\02') {
1711 if (iamremote == 0) {
1712 (void) snmprintf(visbuf, sizeof(visbuf),
1713 NULL, "%s", buf + 1);
1714 (void) atomicio(vwrite, STDERR_FILENO,
1715 visbuf, strlen(visbuf));
1717 if (buf[0] == '\02')
1722 if (buf[0] == 'E') {
1723 (void) atomicio(vwrite, remout, "", 1);
1733 if (!isdigit((unsigned char)*cp))
1734 SCREWUP("mtime.sec not present");
1735 ull = strtoull(cp, &cp, 10);
1736 if (!cp || *cp++ != ' ')
1737 SCREWUP("mtime.sec not delimited");
1738 if (TYPE_OVERFLOW(time_t, ull))
1739 setimes = 0; /* out of range */
1741 mtime.tv_usec = strtol(cp, &cp, 10);
1742 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1743 mtime.tv_usec > 999999)
1744 SCREWUP("mtime.usec not delimited");
1745 if (!isdigit((unsigned char)*cp))
1746 SCREWUP("atime.sec not present");
1747 ull = strtoull(cp, &cp, 10);
1748 if (!cp || *cp++ != ' ')
1749 SCREWUP("atime.sec not delimited");
1750 if (TYPE_OVERFLOW(time_t, ull))
1751 setimes = 0; /* out of range */
1753 atime.tv_usec = strtol(cp, &cp, 10);
1754 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1755 atime.tv_usec > 999999)
1756 SCREWUP("atime.usec not delimited");
1757 (void) atomicio(vwrite, remout, "", 1);
1760 if (*cp != 'C' && *cp != 'D') {
1762 * Check for the case "rcp remote:foo\* local:bar".
1763 * In this case, the line "No match." can be returned
1764 * by the shell before the rcp command on the remote is
1765 * executed so the ^Aerror_message convention isn't
1772 SCREWUP("expected control record");
1775 for (++cp; cp < buf + 5; cp++) {
1776 if (*cp < '0' || *cp > '7')
1777 SCREWUP("bad mode");
1778 mode = (mode << 3) | (*cp - '0');
1783 SCREWUP("mode not delimited");
1785 if (!isdigit((unsigned char)*cp))
1786 SCREWUP("size not present");
1787 ull = strtoull(cp, &cp, 10);
1788 if (!cp || *cp++ != ' ')
1789 SCREWUP("size not delimited");
1790 if (TYPE_OVERFLOW(off_t, ull))
1791 SCREWUP("size out of range");
1794 if (*cp == '\0' || strchr(cp, '/') != NULL ||
1795 strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1796 run_err("error: unexpected filename: %s", cp);
1799 if (npatterns > 0) {
1800 for (n = 0; n < npatterns; n++) {
1801 if (strcmp(patterns[n], cp) == 0 ||
1802 fnmatch(patterns[n], cp, 0) == 0)
1806 SCREWUP("filename does not match request");
1809 static char *namebuf;
1810 static size_t cursize;
1813 need = strlen(targ) + strlen(cp) + 250;
1814 if (need > cursize) {
1816 namebuf = xmalloc(need);
1819 (void) snprintf(namebuf, need, "%s%s%s", targ,
1820 strcmp(targ, "/") ? "/" : "", cp);
1825 exists = stat(np, &stb) == 0;
1826 if (buf[0] == 'D') {
1827 int mod_flag = pflag;
1829 SCREWUP("received directory without -r");
1831 if (!S_ISDIR(stb.st_mode)) {
1836 (void) chmod(np, mode);
1838 /* Handle copying from a read-only directory */
1840 if (mkdir(np, mode | S_IRWXU) == -1)
1843 vect[0] = xstrdup(np);
1847 (void) utimes(vect[0], tv);
1850 (void) chmod(vect[0], mode);
1856 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1857 bad: run_err("%s: %s", np, strerror(errno));
1860 (void) atomicio(vwrite, remout, "", 1);
1861 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1869 * NB. do not use run_err() unless immediately followed by
1870 * exit() below as it may send a spurious reply that might
1871 * desyncronise us from the peer. Use note_err() instead.
1875 start_progress_meter(curfile, size, &statbytes);
1876 set_nonblock(remin);
1877 for (count = i = 0; i < size; i += bp->cnt) {
1883 j = atomicio6(read, remin, cp, amt,
1886 run_err("%s", j != EPIPE ?
1888 "dropped connection");
1895 if (count == bp->cnt) {
1896 /* Keep reading so we stay sync'd up. */
1898 if (atomicio(vwrite, ofd, bp->buf,
1900 note_err("%s: %s", np,
1909 unset_nonblock(remin);
1910 if (count != 0 && !wrerr &&
1911 atomicio(vwrite, ofd, bp->buf, count) != count) {
1912 note_err("%s: %s", np, strerror(errno));
1915 if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1916 ftruncate(ofd, size) != 0)
1917 note_err("%s: truncate: %s", np, strerror(errno));
1919 if (exists || omode != mode)
1921 if (fchmod(ofd, omode)) {
1922 #else /* HAVE_FCHMOD */
1923 if (chmod(np, omode)) {
1924 #endif /* HAVE_FCHMOD */
1925 note_err("%s: set mode: %s",
1926 np, strerror(errno));
1929 if (!exists && omode != mode)
1931 if (fchmod(ofd, omode & ~mask)) {
1932 #else /* HAVE_FCHMOD */
1933 if (chmod(np, omode & ~mask)) {
1934 #endif /* HAVE_FCHMOD */
1935 note_err("%s: set mode: %s",
1936 np, strerror(errno));
1939 if (close(ofd) == -1)
1940 note_err("%s: close: %s", np, strerror(errno));
1943 stop_progress_meter();
1944 if (setimes && !wrerr) {
1946 if (utimes(np, tv) == -1) {
1947 note_err("%s: set times: %s",
1948 np, strerror(errno));
1951 /* If no error was noted then signal success for this file */
1952 if (note_err(NULL) == 0)
1953 (void) atomicio(vwrite, remout, "", 1);
1956 for (n = 0; n < npatterns; n++)
1961 for (n = 0; n < npatterns; n++)
1964 run_err("protocol error: %s", why);
1969 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
1970 char *src, char *targ)
1972 char *target = NULL, *filename = NULL, *abs_dst = NULL;
1973 char *abs_src = NULL, *tmp = NULL;
1975 int i, r, targetisdir, err = 0;
1977 if ((filename = basename(src)) == NULL)
1978 fatal("basename %s: %s", src, strerror(errno));
1980 if ((abs_src = prepare_remote_path(from, src)) == NULL ||
1981 (target = prepare_remote_path(to, targ)) == NULL)
1983 memset(&g, 0, sizeof(g));
1985 targetisdir = remote_is_dir(to, target);
1986 if (!targetisdir && targetshouldbedirectory) {
1987 error("%s: destination is not a directory", targ);
1992 debug3_f("copying remote %s to remote %s", abs_src, target);
1993 if ((r = remote_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
1995 if (r == GLOB_NOSPACE)
1996 error("%s: too many glob matches", src);
1998 error("%s: %s", src, strerror(ENOENT));
2003 /* Did we actually get any matches back from the glob? */
2004 if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
2006 * If nothing matched but a path returned, then it's probably
2007 * a GLOB_NOCHECK result. Check whether the unglobbed path
2008 * exists so we can give a nice error message early.
2010 if (do_stat(from, g.gl_pathv[0], 1) == NULL) {
2011 error("%s: %s", src, strerror(ENOENT));
2017 for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2018 tmp = xstrdup(g.gl_pathv[i]);
2019 if ((filename = basename(tmp)) == NULL) {
2020 error("basename %s: %s", tmp, strerror(errno));
2026 abs_dst = path_append(target, filename);
2028 abs_dst = xstrdup(target);
2030 debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
2031 if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
2032 if (crossload_dir(from, to, g.gl_pathv[i], abs_dst,
2033 NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
2036 if (do_crossload(from, to, g.gl_pathv[i], abs_dst, NULL,
2059 char ch, *cp, resp, rbuf[2048], visbuf[2048];
2061 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
2071 case 1: /* error, followed by error msg */
2072 case 2: /* fatal error, "" */
2074 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
2077 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
2081 (void) snmprintf(visbuf, sizeof(visbuf),
2082 NULL, "%s\n", rbuf);
2083 (void) atomicio(vwrite, STDERR_FILENO,
2084 visbuf, strlen(visbuf));
2097 (void) fprintf(stderr,
2098 "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2099 " [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2100 " [-P port] [-S program] [-X sftp_option] source ... target\n");
2105 run_err(const char *fmt,...)
2111 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2112 (void) fprintf(fp, "%c", 0x01);
2113 (void) fprintf(fp, "scp: ");
2115 (void) vfprintf(fp, fmt, ap);
2117 (void) fprintf(fp, "\n");
2123 vfmprintf(stderr, fmt, ap);
2125 fprintf(stderr, "\n");
2130 * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2131 * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2132 * any active error at the end of the transfer.
2135 note_err(const char *fmt, ...)
2140 /* Replay any previously-noted error */
2144 run_err("%s", emsg);
2151 /* Prefer first-noted error */
2156 vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
2166 if (!stat(cp, &stb)) {
2167 if (S_ISDIR(stb.st_mode))
2171 run_err("%s: %s", cp, strerror(errno));
2186 if (!isalpha(c) && !isdigit((unsigned char)c)) {
2201 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
2206 allocbuf(BUF *bp, int fd, int blksize)
2209 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2212 if (fstat(fd, &stb) == -1) {
2213 run_err("fstat: %s", strerror(errno));
2216 size = ROUNDUP(stb.st_blksize, blksize);
2219 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2221 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2222 if (bp->cnt >= size)
2224 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2233 (void)write(STDERR_FILENO, "lost connection\n", 16);
2252 waitpid(do_cmd_pid, NULL, 0);
2253 if (do_cmd_pid2 > 0)
2254 waitpid(do_cmd_pid2, NULL, 0);