1 /* $OpenBSD: scp.c,v 1.261 2024/06/26 23:14:14 deraadt 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 int save_errno
= errno
;
226 suspone(do_cmd_pid
, signo
);
227 suspone(do_cmd_pid2
, signo
);
228 kill(getpid(), SIGSTOP
);
233 do_local_cmd(arglist
*a
)
240 fatal("do_local_cmd: no arguments");
243 fprintf(stderr
, "Executing:");
244 for (i
= 0; i
< a
->num
; i
++)
245 fmprintf(stderr
, " %s", a
->list
[i
]);
246 fprintf(stderr
, "\n");
248 if ((pid
= fork()) == -1)
249 fatal("do_local_cmd: fork: %s", strerror(errno
));
252 execvp(a
->list
[0], a
->list
);
258 ssh_signal(SIGTERM
, killchild
);
259 ssh_signal(SIGINT
, killchild
);
260 ssh_signal(SIGHUP
, killchild
);
262 while (waitpid(pid
, &status
, 0) == -1)
264 fatal("do_local_cmd: waitpid: %s", strerror(errno
));
268 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
275 * This function executes the given command as the specified user on the
276 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
277 * assigns the input and output file descriptors on success.
281 do_cmd(char *program
, char *host
, char *remuser
, int port
, int subsystem
,
282 char *cmd
, int *fdin
, int *fdout
, pid_t
*pid
)
292 "Executing: program %s host %s, user %s, command %s\n",
294 remuser
? remuser
: "(unspecified)", cmd
);
300 if (pipe(pin
) == -1 || pipe(pout
) == -1)
301 fatal("pipe: %s", strerror(errno
));
303 /* Create a socket pair for communicating with ssh. */
304 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, sv
) == -1)
305 fatal("socketpair: %s", strerror(errno
));
308 ssh_signal(SIGTSTP
, suspchild
);
309 ssh_signal(SIGTTIN
, suspchild
);
310 ssh_signal(SIGTTOU
, suspchild
);
312 /* Fork a child to execute the command on the remote host using ssh. */
316 fatal("fork: %s", strerror(errno
));
320 if (dup2(pin
[0], STDIN_FILENO
) == -1 ||
321 dup2(pout
[1], STDOUT_FILENO
) == -1) {
322 error("dup2: %s", strerror(errno
));
330 if (dup2(sv
[0], STDIN_FILENO
) == -1 ||
331 dup2(sv
[0], STDOUT_FILENO
) == -1) {
332 error("dup2: %s", strerror(errno
));
338 replacearg(&args
, 0, "%s", program
);
340 addargs(&args
, "-p");
341 addargs(&args
, "%d", port
);
343 if (remuser
!= NULL
) {
344 addargs(&args
, "-l");
345 addargs(&args
, "%s", remuser
);
348 addargs(&args
, "-s");
349 addargs(&args
, "--");
350 addargs(&args
, "%s", host
);
351 addargs(&args
, "%s", cmd
);
353 execvp(program
, args
.list
);
357 /* Parent. Close the other side, and return the local side. */
368 ssh_signal(SIGTERM
, killchild
);
369 ssh_signal(SIGINT
, killchild
);
370 ssh_signal(SIGHUP
, killchild
);
376 * This function executes a command similar to do_cmd(), but expects the
377 * input and output descriptors to be setup by a previous call to do_cmd().
378 * This way the input and output of two commands can be connected.
381 do_cmd2(char *host
, char *remuser
, int port
, char *cmd
,
389 "Executing: 2nd program %s host %s, user %s, command %s\n",
391 remuser
? remuser
: "(unspecified)", cmd
);
396 /* Fork a child to execute the command on the remote host using ssh. */
399 if (dup2(fdin
, 0) == -1)
401 if (dup2(fdout
, 1) == -1)
404 replacearg(&args
, 0, "%s", ssh_program
);
406 addargs(&args
, "-p");
407 addargs(&args
, "%d", port
);
409 if (remuser
!= NULL
) {
410 addargs(&args
, "-l");
411 addargs(&args
, "%s", remuser
);
413 addargs(&args
, "-oBatchMode=yes");
414 addargs(&args
, "--");
415 addargs(&args
, "%s", host
);
416 addargs(&args
, "%s", cmd
);
418 execvp(ssh_program
, args
.list
);
421 } else if (pid
== -1) {
422 fatal("fork: %s", strerror(errno
));
424 while (waitpid(pid
, &status
, 0) == -1)
426 fatal("do_cmd2: waitpid: %s", strerror(errno
));
435 BUF
*allocbuf(BUF
*, int, int);
438 void run_err(const char *,...)
439 __attribute__((__format__ (printf
, 1, 2)))
440 __attribute__((__nonnull__ (1)));
441 int note_err(const char *,...)
442 __attribute__((__format__ (printf
, 1, 2)));
443 void verifydir(char *);
447 int errs
, remin
, remout
, remin2
, remout2
;
448 int Tflag
, pflag
, iamremote
, iamrecursive
, targetshouldbedirectory
;
451 char cmd
[CMDNEEDS
]; /* must hold "rcp -r -p -d\0" */
459 void rsource(char *, struct stat
*);
460 void sink(int, char *[], const char *);
461 void source(int, char *[]);
462 void tolocal(int, char *[], enum scp_mode_e
, char *sftp_direct
);
463 void toremote(int, char *[], enum scp_mode_e
, char *sftp_direct
);
466 void source_sftp(int, char *, char *, struct sftp_conn
*);
467 void sink_sftp(int, char *, const char *, struct sftp_conn
*);
468 void throughlocal_sftp(struct sftp_conn
*, struct sftp_conn
*,
472 main(int argc
, char **argv
)
474 int ch
, fflag
, tflag
, status
, r
, n
;
475 char **newargv
, *argv0
;
479 enum scp_mode_e mode
= MODE_SFTP
;
480 char *sftp_direct
= NULL
;
483 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
488 /* Copy argv, because we modify it */
490 newargv
= xcalloc(MAXIMUM(argc
+ 1, 1), sizeof(*newargv
));
491 for (n
= 0; n
< argc
; n
++)
492 newargv
[n
] = xstrdup(argv
[n
]);
495 __progname
= ssh_get_progname(argv
[0]);
497 log_init(argv0
, log_level
, SYSLOG_FACILITY_USER
, 2);
499 memset(&args
, '\0', sizeof(args
));
500 memset(&remote_remote_args
, '\0', sizeof(remote_remote_args
));
501 args
.list
= remote_remote_args
.list
= NULL
;
502 addargs(&args
, "%s", ssh_program
);
503 addargs(&args
, "-x");
504 addargs(&args
, "-oPermitLocalCommand=no");
505 addargs(&args
, "-oClearAllForwardings=yes");
506 addargs(&args
, "-oRemoteCommand=none");
507 addargs(&args
, "-oRequestTTY=no");
509 fflag
= Tflag
= tflag
= 0;
510 while ((ch
= getopt(argc
, argv
,
511 "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:X:")) != -1) {
513 /* User-visible flags. */
515 fatal("SSH protocol v.1 is no longer supported");
524 addargs(&args
, "-%c", ch
);
525 addargs(&remote_remote_args
, "-%c", ch
);
528 sftp_direct
= optarg
;
541 addargs(&remote_remote_args
, "-%c", ch
);
542 addargs(&remote_remote_args
, "%s", optarg
);
543 addargs(&args
, "-%c", ch
);
544 addargs(&args
, "%s", optarg
);
553 sshport
= a2port(optarg
);
555 fatal("bad port \"%s\"\n", optarg
);
558 addargs(&remote_remote_args
, "-oBatchmode=yes");
559 addargs(&args
, "-oBatchmode=yes");
562 limit_kbps
= strtonum(optarg
, 1, 100 * 1024 * 1024,
566 limit_kbps
*= 1024; /* kbps */
567 bandwidth_limit_init(&bwlimit
, limit_kbps
, COPY_BUFLEN
);
576 ssh_program
= xstrdup(optarg
);
579 addargs(&args
, "-v");
580 addargs(&remote_remote_args
, "-v");
581 if (verbose_mode
== 0)
582 log_level
= SYSLOG_LEVEL_DEBUG1
;
583 else if (log_level
< SYSLOG_LEVEL_DEBUG3
)
588 addargs(&args
, "-q");
589 addargs(&remote_remote_args
, "-q");
593 /* Please keep in sync with sftp.c -X */
594 if (strncmp(optarg
, "buffer=", 7) == 0) {
595 r
= scan_scaled(optarg
+ 7, &llv
);
596 if (r
== 0 && (llv
<= 0 || llv
> 256 * 1024)) {
601 fatal("Invalid buffer size \"%s\": %s",
602 optarg
+ 7, strerror(errno
));
604 sftp_copy_buflen
= (size_t)llv
;
605 } else if (strncmp(optarg
, "nrequests=", 10) == 0) {
606 llv
= strtonum(optarg
+ 10, 1, 256 * 1024,
608 if (errstr
!= NULL
) {
609 fatal("Invalid number of requests "
610 "\"%s\": %s", optarg
+ 10, errstr
);
612 sftp_nrequests
= (size_t)llv
;
614 fatal("Invalid -X option");
618 /* Server options. */
620 targetshouldbedirectory
= 1;
622 case 'f': /* "from" */
630 setmode(0, O_BINARY
);
643 log_init(argv0
, log_level
, SYSLOG_FACILITY_USER
, 2);
645 /* Do this last because we want the user to be able to override it */
646 addargs(&args
, "-oForwardAgent=no");
651 if ((pwd
= getpwuid(userid
= getuid())) == NULL
)
652 fatal("unknown user %u", (u_int
) userid
);
654 if (!isatty(STDOUT_FILENO
))
658 /* Cannot pledge: -p allows setuid/setgid files... */
660 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
667 remin
= STDIN_FILENO
;
668 remout
= STDOUT_FILENO
;
671 /* Follow "protocol", send data. */
678 sink(argc
, argv
, NULL
);
684 targetshouldbedirectory
= 1;
688 /* Command to be executed on remote system using "ssh". */
689 (void) snprintf(cmd
, sizeof cmd
, "scp%s%s%s%s",
690 verbose_mode
? " -v" : "",
691 iamrecursive
? " -r" : "", pflag
? " -p" : "",
692 targetshouldbedirectory
? " -d" : "");
694 (void) ssh_signal(SIGPIPE
, lostconn
);
696 if (colon(argv
[argc
- 1])) /* Dest is remote host. */
697 toremote(argc
, argv
, mode
, sftp_direct
);
699 if (targetshouldbedirectory
)
700 verifydir(argv
[argc
- 1]);
701 tolocal(argc
, argv
, mode
, sftp_direct
); /* Dest is local host. */
704 * Finally check the exit status of the ssh process, if one was forked
705 * and no error has occurred yet
707 if (do_cmd_pid
!= -1 && (mode
== MODE_SFTP
|| errs
== 0)) {
711 (void) close(remout
);
712 if (waitpid(do_cmd_pid
, &status
, 0) == -1)
715 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
722 /* Callback from atomicio6 to update progress meter and limit bandwidth */
724 scpio(void *_cnt
, size_t s
)
726 off_t
*cnt
= (off_t
*)_cnt
;
729 refresh_progress_meter(0);
731 bandwidth_limit(&bwlimit
, s
);
736 do_times(int fd
, int verb
, const struct stat
*sb
)
738 /* strlen(2^64) == 20; strlen(10^6) == 7 */
739 char buf
[(20 + 7 + 2) * 2 + 2];
741 (void)snprintf(buf
, sizeof(buf
), "T%llu 0 %llu 0\n",
742 (unsigned long long) (sb
->st_mtime
< 0 ? 0 : sb
->st_mtime
),
743 (unsigned long long) (sb
->st_atime
< 0 ? 0 : sb
->st_atime
));
745 fprintf(stderr
, "File mtime %lld atime %lld\n",
746 (long long)sb
->st_mtime
, (long long)sb
->st_atime
);
747 fprintf(stderr
, "Sending file timestamps: %s", buf
);
749 (void) atomicio(vwrite
, fd
, buf
, strlen(buf
));
754 parse_scp_uri(const char *uri
, char **userp
, char **hostp
, int *portp
,
759 r
= parse_uri("scp", uri
, userp
, hostp
, portp
, pathp
);
760 if (r
== 0 && *pathp
== NULL
)
761 *pathp
= xstrdup(".");
765 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
767 append(char *cp
, char ***ap
, size_t *np
)
771 if ((tmp
= reallocarray(*ap
, *np
+ 1, sizeof(*tmp
))) == NULL
)
780 * Finds the start and end of the first brace pair in the pattern.
781 * returns 0 on success or -1 for invalid patterns.
784 find_brace(const char *pattern
, int *startp
, int *endp
)
787 int in_bracket
, brace_level
;
789 *startp
= *endp
= -1;
790 in_bracket
= brace_level
= 0;
791 for (i
= 0; i
< INT_MAX
&& *endp
< 0 && pattern
[i
] != '\0'; i
++) {
792 switch (pattern
[i
]) {
794 /* skip next character */
795 if (pattern
[i
+ 1] != '\0')
807 if (pattern
[i
+ 1] == '}') {
808 /* Protect a single {}, for find(1), like csh */
820 /* Unbalanced brace */
823 if (--brace_level
<= 0)
828 /* unbalanced brackets/braces */
829 if (*endp
< 0 && (*startp
>= 0 || in_bracket
))
835 * Assembles and records a successfully-expanded pattern, returns -1 on
839 emit_expansion(const char *pattern
, int brace_start
, int brace_end
,
840 int sel_start
, int sel_end
, char ***patternsp
, size_t *npatternsp
)
846 if ((pattern_len
= strlen(pattern
)) == 0 || pattern_len
>= INT_MAX
)
849 tail_len
= strlen(pattern
+ brace_end
+ 1);
850 if ((cp
= malloc(brace_start
+ (sel_end
- sel_start
) +
851 tail_len
+ 1)) == NULL
)
854 /* Pattern before initial brace */
855 if (brace_start
> 0) {
856 memcpy(cp
, pattern
, brace_start
);
859 /* Current braced selection */
860 if (sel_end
- sel_start
> 0) {
861 memcpy(cp
+ o
, pattern
+ sel_start
,
862 sel_end
- sel_start
);
863 o
+= sel_end
- sel_start
;
865 /* Remainder of pattern after closing brace */
867 memcpy(cp
+ o
, pattern
+ brace_end
+ 1, tail_len
);
871 if (append(cp
, patternsp
, npatternsp
) != 0) {
879 * Expand the first encountered brace in pattern, appending the expanded
880 * patterns it yielded to the *patternsp array.
882 * Returns 0 on success or -1 on allocation failure.
884 * Signals whether expansion was performed via *expanded and whether
885 * pattern was invalid via *invalid.
888 brace_expand_one(const char *pattern
, char ***patternsp
, size_t *npatternsp
,
889 int *expanded
, int *invalid
)
892 int in_bracket
, brace_start
, brace_end
, brace_level
;
893 int sel_start
, sel_end
;
895 *invalid
= *expanded
= 0;
897 if (find_brace(pattern
, &brace_start
, &brace_end
) != 0) {
900 } else if (brace_start
== -1)
903 in_bracket
= brace_level
= 0;
904 for (i
= sel_start
= brace_start
+ 1; i
< brace_end
; i
++) {
905 switch (pattern
[i
]) {
923 if (i
< brace_end
- 1)
927 if (pattern
[i
] == ',' || i
== brace_end
- 1) {
928 if (in_bracket
|| brace_level
> 0)
930 /* End of a selection, emit an expanded pattern */
932 /* Adjust end index for last selection */
933 sel_end
= (i
== brace_end
- 1) ? brace_end
: i
;
934 if (emit_expansion(pattern
, brace_start
, brace_end
,
935 sel_start
, sel_end
, patternsp
, npatternsp
) != 0)
937 /* move on to the next selection */
942 if (in_bracket
|| brace_level
> 0) {
951 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
953 brace_expand(const char *pattern
, char ***patternsp
, size_t *npatternsp
)
955 char *cp
, *cp2
, **active
= NULL
, **done
= NULL
;
956 size_t i
, nactive
= 0, ndone
= 0;
957 int ret
= -1, invalid
= 0, expanded
= 0;
962 /* Start the worklist with the original pattern */
963 if ((cp
= strdup(pattern
)) == NULL
)
965 if (append(cp
, &active
, &nactive
) != 0) {
969 while (nactive
> 0) {
970 cp
= active
[nactive
- 1];
972 if (brace_expand_one(cp
, &active
, &nactive
,
973 &expanded
, &invalid
) == -1) {
978 fatal_f("invalid brace pattern \"%s\"", cp
);
981 * Current entry expanded to new entries on the
982 * active list; discard the progenitor pattern.
988 * Pattern did not expand; append the finename component to
991 if ((cp2
= strrchr(cp
, '/')) != NULL
)
995 if (append(xstrdup(cp2
), &done
, &ndone
) != 0) {
1003 *npatternsp
= ndone
;
1008 for (i
= 0; i
< nactive
; i
++)
1011 for (i
= 0; i
< ndone
; i
++)
1017 static struct sftp_conn
*
1018 do_sftp_connect(char *host
, char *user
, int port
, char *sftp_direct
,
1019 int *reminp
, int *remoutp
, int *pidp
)
1021 if (sftp_direct
== NULL
) {
1022 if (do_cmd(ssh_program
, host
, user
, port
, 1, "sftp",
1023 reminp
, remoutp
, pidp
) < 0)
1028 addargs(&args
, "sftp-server");
1029 if (do_cmd(sftp_direct
, host
, NULL
, -1, 0, "sftp",
1030 reminp
, remoutp
, pidp
) < 0)
1033 return sftp_init(*reminp
, *remoutp
,
1034 sftp_copy_buflen
, sftp_nrequests
, limit_kbps
);
1038 toremote(int argc
, char **argv
, enum scp_mode_e mode
, char *sftp_direct
)
1040 char *suser
= NULL
, *host
= NULL
, *src
= NULL
;
1041 char *bp
, *tuser
, *thost
, *targ
;
1042 int sport
= -1, tport
= -1;
1043 struct sftp_conn
*conn
= NULL
, *conn2
= NULL
;
1049 memset(&alist
, '\0', sizeof(alist
));
1053 r
= parse_scp_uri(argv
[argc
- 1], &tuser
, &thost
, &tport
, &targ
);
1055 fmprintf(stderr
, "%s: invalid uri\n", argv
[argc
- 1]);
1060 if (parse_user_host_path(argv
[argc
- 1], &tuser
, &thost
,
1062 fmprintf(stderr
, "%s: invalid target\n", argv
[argc
- 1]);
1068 /* Parse source files */
1069 for (i
= 0; i
< argc
- 1; i
++) {
1073 r
= parse_scp_uri(argv
[i
], &suser
, &host
, &sport
, &src
);
1075 fmprintf(stderr
, "%s: invalid uri\n", argv
[i
]);
1080 parse_user_host_path(argv
[i
], &suser
, &host
, &src
);
1082 if (suser
!= NULL
&& !okname(suser
)) {
1086 if (host
&& throughlocal
) { /* extended remote to remote */
1087 if (mode
== MODE_SFTP
) {
1089 /* Connect to dest now */
1090 conn
= do_sftp_connect(thost
, tuser
,
1092 &remin
, &remout
, &do_cmd_pid
);
1094 fatal("Unable to open "
1095 "destination connection");
1097 debug3_f("origin in %d out %d pid %ld",
1098 remin
, remout
, (long)do_cmd_pid
);
1101 * XXX remember suser/host/sport and only
1102 * reconnect if they change between arguments.
1103 * would save reconnections for cases like
1104 * scp -3 hosta:/foo hosta:/bar hostb:
1106 /* Connect to origin now */
1107 conn2
= do_sftp_connect(host
, suser
,
1109 &remin2
, &remout2
, &do_cmd_pid2
);
1110 if (conn2
== NULL
) {
1111 fatal("Unable to open "
1112 "source connection");
1114 debug3_f("destination in %d out %d pid %ld",
1115 remin2
, remout2
, (long)do_cmd_pid2
);
1116 throughlocal_sftp(conn2
, conn
, src
, targ
);
1117 (void) close(remin2
);
1118 (void) close(remout2
);
1119 remin2
= remout2
= -1;
1120 if (waitpid(do_cmd_pid2
, &status
, 0) == -1)
1122 else if (!WIFEXITED(status
) ||
1123 WEXITSTATUS(status
) != 0)
1128 xasprintf(&bp
, "%s -f %s%s", cmd
,
1129 *src
== '-' ? "-- " : "", src
);
1130 if (do_cmd(ssh_program
, host
, suser
, sport
, 0,
1131 bp
, &remin
, &remout
, &do_cmd_pid
) < 0)
1134 xasprintf(&bp
, "%s -t %s%s", cmd
,
1135 *targ
== '-' ? "-- " : "", targ
);
1136 if (do_cmd2(thost
, tuser
, tport
, bp
,
1140 (void) close(remin
);
1141 (void) close(remout
);
1142 remin
= remout
= -1;
1144 } else if (host
) { /* standard remote to remote */
1146 * Second remote user is passed to first remote side
1147 * via scp command-line. Ensure it contains no obvious
1150 if (tuser
!= NULL
&& !okname(tuser
)) {
1154 if (tport
!= -1 && tport
!= SSH_DEFAULT_PORT
) {
1155 /* This would require the remote support URIs */
1156 fatal("target port not supported with two "
1157 "remote hosts and the -R option");
1161 addargs(&alist
, "%s", ssh_program
);
1162 addargs(&alist
, "-x");
1163 addargs(&alist
, "-oClearAllForwardings=yes");
1164 addargs(&alist
, "-n");
1165 for (j
= 0; j
< remote_remote_args
.num
; j
++) {
1166 addargs(&alist
, "%s",
1167 remote_remote_args
.list
[j
]);
1171 addargs(&alist
, "-p");
1172 addargs(&alist
, "%d", sport
);
1175 addargs(&alist
, "-l");
1176 addargs(&alist
, "%s", suser
);
1178 addargs(&alist
, "--");
1179 addargs(&alist
, "%s", host
);
1180 addargs(&alist
, "%s", cmd
);
1181 addargs(&alist
, "%s", src
);
1182 addargs(&alist
, "%s%s%s:%s",
1183 tuser
? tuser
: "", tuser
? "@" : "",
1185 if (do_local_cmd(&alist
) != 0)
1187 } else { /* local to remote */
1188 if (mode
== MODE_SFTP
) {
1189 /* no need to glob: already done by shell */
1190 if (stat(argv
[i
], &sb
) != 0) {
1191 fatal("stat local \"%s\": %s", argv
[i
],
1195 /* Connect to remote now */
1196 conn
= do_sftp_connect(thost
, tuser
,
1198 &remin
, &remout
, &do_cmd_pid
);
1200 fatal("Unable to open sftp "
1206 source_sftp(1, argv
[i
], targ
, conn
);
1211 xasprintf(&bp
, "%s -t %s%s", cmd
,
1212 *targ
== '-' ? "-- " : "", targ
);
1213 if (do_cmd(ssh_program
, thost
, tuser
, tport
, 0,
1214 bp
, &remin
, &remout
, &do_cmd_pid
) < 0)
1220 source(1, argv
+ i
);
1224 if (mode
== MODE_SFTP
)
1235 tolocal(int argc
, char **argv
, enum scp_mode_e mode
, char *sftp_direct
)
1237 char *bp
, *host
= NULL
, *src
= NULL
, *suser
= NULL
;
1239 struct sftp_conn
*conn
= NULL
;
1240 int i
, r
, sport
= -1;
1242 memset(&alist
, '\0', sizeof(alist
));
1245 for (i
= 0; i
< argc
- 1; i
++) {
1249 r
= parse_scp_uri(argv
[i
], &suser
, &host
, &sport
, &src
);
1251 fmprintf(stderr
, "%s: invalid uri\n", argv
[i
]);
1256 parse_user_host_path(argv
[i
], &suser
, &host
, &src
);
1257 if (suser
!= NULL
&& !okname(suser
)) {
1261 if (!host
) { /* Local to local. */
1263 addargs(&alist
, "%s", _PATH_CP
);
1265 addargs(&alist
, "-r");
1267 addargs(&alist
, "-p");
1268 addargs(&alist
, "--");
1269 addargs(&alist
, "%s", argv
[i
]);
1270 addargs(&alist
, "%s", argv
[argc
-1]);
1271 if (do_local_cmd(&alist
))
1275 /* Remote to local. */
1276 if (mode
== MODE_SFTP
) {
1277 conn
= do_sftp_connect(host
, suser
, sport
,
1278 sftp_direct
, &remin
, &remout
, &do_cmd_pid
);
1280 error("sftp connection failed");
1286 sink_sftp(1, argv
[argc
- 1], src
, conn
);
1289 (void) close(remin
);
1290 (void) close(remout
);
1291 remin
= remout
= -1;
1295 xasprintf(&bp
, "%s -f %s%s",
1296 cmd
, *src
== '-' ? "-- " : "", src
);
1297 if (do_cmd(ssh_program
, host
, suser
, sport
, 0, bp
,
1298 &remin
, &remout
, &do_cmd_pid
) < 0) {
1304 sink(1, argv
+ argc
- 1, src
);
1305 (void) close(remin
);
1306 remin
= remout
= -1;
1313 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1315 prepare_remote_path(struct sftp_conn
*conn
, const char *path
)
1319 /* Handle ~ prefixed paths */
1320 if (*path
== '\0' || strcmp(path
, "~") == 0)
1321 return xstrdup(".");
1323 return xstrdup(path
);
1324 if (strncmp(path
, "~/", 2) == 0) {
1325 if ((nslash
= strspn(path
+ 2, "/")) == strlen(path
+ 2))
1326 return xstrdup(".");
1327 return xstrdup(path
+ 2 + nslash
);
1329 if (sftp_can_expand_path(conn
))
1330 return sftp_expand_path(conn
, path
);
1331 /* No protocol extension */
1332 error("server expand-path extension is required "
1333 "for ~user paths in SFTP mode");
1338 source_sftp(int argc
, char *src
, char *targ
, struct sftp_conn
*conn
)
1340 char *target
= NULL
, *filename
= NULL
, *abs_dst
= NULL
;
1341 int src_is_dir
, target_is_dir
;
1345 memset(&a
, '\0', sizeof(a
));
1346 if (stat(src
, &st
) != 0)
1347 fatal("stat local \"%s\": %s", src
, strerror(errno
));
1348 src_is_dir
= S_ISDIR(st
.st_mode
);
1349 if ((filename
= basename(src
)) == NULL
)
1350 fatal("basename \"%s\": %s", src
, strerror(errno
));
1353 * No need to glob here - the local shell already took care of
1356 if ((target
= prepare_remote_path(conn
, targ
)) == NULL
)
1358 target_is_dir
= sftp_remote_is_dir(conn
, target
);
1359 if (targetshouldbedirectory
&& !target_is_dir
) {
1360 debug("target directory \"%s\" does not exist", target
);
1361 a
.flags
= SSH2_FILEXFER_ATTR_PERMISSIONS
;
1362 a
.perm
= st
.st_mode
| 0700; /* ensure writable */
1363 if (sftp_mkdir(conn
, target
, &a
, 1) != 0)
1364 cleanup_exit(255); /* error already logged */
1368 abs_dst
= sftp_path_append(target
, filename
);
1373 debug3_f("copying local %s to remote %s", src
, abs_dst
);
1375 if (src_is_dir
&& iamrecursive
) {
1376 if (sftp_upload_dir(conn
, src
, abs_dst
, pflag
,
1377 SFTP_PROGRESS_ONLY
, 0, 0, 1, 1) != 0) {
1378 error("failed to upload directory %s to %s", src
, targ
);
1381 } else if (sftp_upload(conn
, src
, abs_dst
, pflag
, 0, 0, 1) != 0) {
1382 error("failed to upload file %s to %s", src
, targ
);
1391 source(int argc
, char **argv
)
1398 int fd
= -1, haderr
, indx
;
1399 char *last
, *name
, buf
[PATH_MAX
+ 128], encname
[PATH_MAX
];
1402 for (indx
= 0; indx
< argc
; ++indx
) {
1406 while (len
> 1 && name
[len
-1] == '/')
1408 if ((fd
= open(name
, O_RDONLY
|O_NONBLOCK
)) == -1)
1410 if (strchr(name
, '\n') != NULL
) {
1411 strnvis(encname
, name
, sizeof(encname
), VIS_NL
);
1414 if (fstat(fd
, &stb
) == -1) {
1415 syserr
: run_err("%s: %s", name
, strerror(errno
));
1418 if (stb
.st_size
< 0) {
1419 run_err("%s: %s", name
, "Negative file size");
1423 switch (stb
.st_mode
& S_IFMT
) {
1428 rsource(name
, &stb
);
1433 run_err("%s: not a regular file", name
);
1436 if ((last
= strrchr(name
, '/')) == NULL
)
1442 if (do_times(remout
, verbose_mode
, &stb
) < 0)
1445 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1446 snprintf(buf
, sizeof buf
, "C%04o %lld %s\n",
1447 (u_int
) (stb
.st_mode
& FILEMODEMASK
),
1448 (long long)stb
.st_size
, last
);
1450 fmprintf(stderr
, "Sending file modes: %s", buf
);
1451 (void) atomicio(vwrite
, remout
, buf
, strlen(buf
));
1454 if ((bp
= allocbuf(&buffer
, fd
, COPY_BUFLEN
)) == NULL
) {
1455 next
: if (fd
!= -1) {
1462 start_progress_meter(curfile
, stb
.st_size
, &statbytes
);
1463 set_nonblock(remout
);
1464 for (haderr
= i
= 0; i
< stb
.st_size
; i
+= bp
->cnt
) {
1466 if (i
+ (off_t
)amt
> stb
.st_size
)
1467 amt
= stb
.st_size
- i
;
1469 if ((nr
= atomicio(read
, fd
,
1470 bp
->buf
, amt
)) != amt
) {
1472 memset(bp
->buf
+ nr
, 0, amt
- nr
);
1475 /* Keep writing after error to retain sync */
1477 (void)atomicio(vwrite
, remout
, bp
->buf
, amt
);
1478 memset(bp
->buf
, 0, amt
);
1481 if (atomicio6(vwrite
, remout
, bp
->buf
, amt
, scpio
,
1485 unset_nonblock(remout
);
1488 if (close(fd
) == -1 && !haderr
)
1493 (void) atomicio(vwrite
, remout
, "", 1);
1495 run_err("%s: %s", name
, strerror(haderr
));
1498 stop_progress_meter();
1503 rsource(char *name
, struct stat
*statp
)
1507 char *last
, *vect
[1], path
[PATH_MAX
];
1509 if (!(dirp
= opendir(name
))) {
1510 run_err("%s: %s", name
, strerror(errno
));
1513 last
= strrchr(name
, '/');
1519 if (do_times(remout
, verbose_mode
, statp
) < 0) {
1524 (void) snprintf(path
, sizeof path
, "D%04o %d %.1024s\n",
1525 (u_int
) (statp
->st_mode
& FILEMODEMASK
), 0, last
);
1527 fmprintf(stderr
, "Entering directory: %s", path
);
1528 (void) atomicio(vwrite
, remout
, path
, strlen(path
));
1529 if (response() < 0) {
1533 while ((dp
= readdir(dirp
)) != NULL
) {
1536 if (!strcmp(dp
->d_name
, ".") || !strcmp(dp
->d_name
, ".."))
1538 if (strlen(name
) + 1 + strlen(dp
->d_name
) >= sizeof(path
) - 1) {
1539 run_err("%s/%s: name too long", name
, dp
->d_name
);
1542 (void) snprintf(path
, sizeof path
, "%s/%s", name
, dp
->d_name
);
1546 (void) closedir(dirp
);
1547 (void) atomicio(vwrite
, remout
, "E\n", 2);
1552 sink_sftp(int argc
, char *dst
, const char *src
, struct sftp_conn
*conn
)
1554 char *abs_src
= NULL
;
1555 char *abs_dst
= NULL
;
1557 char *filename
, *tmp
= NULL
;
1558 int i
, r
, err
= 0, dst_is_dir
;
1561 memset(&g
, 0, sizeof(g
));
1564 * Here, we need remote glob as SFTP can not depend on remote shell
1567 if ((abs_src
= prepare_remote_path(conn
, src
)) == NULL
) {
1572 debug3_f("copying remote %s to local %s", abs_src
, dst
);
1573 if ((r
= sftp_glob(conn
, abs_src
, GLOB_NOCHECK
|GLOB_MARK
,
1575 if (r
== GLOB_NOSPACE
)
1576 error("%s: too many glob matches", src
);
1578 error("%s: %s", src
, strerror(ENOENT
));
1583 /* Did we actually get any matches back from the glob? */
1584 if (g
.gl_matchc
== 0 && g
.gl_pathc
== 1 && g
.gl_pathv
[0] != 0) {
1586 * If nothing matched but a path returned, then it's probably
1587 * a GLOB_NOCHECK result. Check whether the unglobbed path
1588 * exists so we can give a nice error message early.
1590 if (sftp_stat(conn
, g
.gl_pathv
[0], 1, NULL
) != 0) {
1591 error("%s: %s", src
, strerror(ENOENT
));
1597 if ((r
= stat(dst
, &st
)) != 0)
1598 debug2_f("stat local \"%s\": %s", dst
, strerror(errno
));
1599 dst_is_dir
= r
== 0 && S_ISDIR(st
.st_mode
);
1601 if (g
.gl_matchc
> 1 && !dst_is_dir
) {
1603 error("Multiple files match pattern, but destination "
1604 "\"%s\" is not a directory", dst
);
1608 debug2_f("creating destination \"%s\"", dst
);
1609 if (mkdir(dst
, 0777) != 0) {
1610 error("local mkdir \"%s\": %s", dst
, strerror(errno
));
1617 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1618 tmp
= xstrdup(g
.gl_pathv
[i
]);
1619 if ((filename
= basename(tmp
)) == NULL
) {
1620 error("basename %s: %s", tmp
, strerror(errno
));
1626 abs_dst
= sftp_path_append(dst
, filename
);
1628 abs_dst
= xstrdup(dst
);
1630 debug("Fetching %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
1631 if (sftp_globpath_is_dir(g
.gl_pathv
[i
]) && iamrecursive
) {
1632 if (sftp_download_dir(conn
, g
.gl_pathv
[i
], abs_dst
,
1633 NULL
, pflag
, SFTP_PROGRESS_ONLY
, 0, 0, 1, 1) == -1)
1636 if (sftp_download(conn
, g
.gl_pathv
[i
], abs_dst
, NULL
,
1637 pflag
, 0, 0, 1) == -1)
1655 #define TYPE_OVERFLOW(type, val) \
1656 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
1657 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1658 (sizeof(type) != 4 && sizeof(type) != 8))
1661 sink(int argc
, char **argv
, const char *src
)
1668 int amt
, exists
, first
, ofd
;
1669 mode_t mode
, omode
, mask
;
1670 off_t size
, statbytes
;
1671 unsigned long long ull
;
1672 int setimes
, targisdir
, wrerr
;
1673 char ch
, *cp
, *np
, *targ
, *why
, *vect
[1], buf
[2048], visbuf
[2048];
1674 char **patterns
= NULL
;
1675 size_t n
, npatterns
= 0;
1676 struct timeval tv
[2];
1680 #define SCREWUP(str) { why = str; goto screwup; }
1682 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t
, 0))
1683 SCREWUP("Unexpected off_t/time_t size");
1685 setimes
= targisdir
= 0;
1690 run_err("ambiguous target");
1694 if (targetshouldbedirectory
)
1697 (void) atomicio(vwrite
, remout
, "", 1);
1698 if (stat(targ
, &stb
) == 0 && S_ISDIR(stb
.st_mode
))
1700 if (src
!= NULL
&& !iamrecursive
&& !Tflag
) {
1702 * Prepare to try to restrict incoming filenames to match
1703 * the requested destination file glob.
1705 if (brace_expand(src
, &patterns
, &npatterns
) != 0)
1706 fatal_f("could not expand pattern");
1708 for (first
= 1;; first
= 0) {
1710 if (atomicio(read
, remin
, cp
, 1) != 1)
1713 SCREWUP("unexpected <newline>");
1715 if (atomicio(read
, remin
, &ch
, sizeof(ch
)) != sizeof(ch
))
1716 SCREWUP("lost connection");
1718 } while (cp
< &buf
[sizeof(buf
) - 1] && ch
!= '\n');
1721 fmprintf(stderr
, "Sink: %s", buf
);
1723 if (buf
[0] == '\01' || buf
[0] == '\02') {
1724 if (iamremote
== 0) {
1725 (void) snmprintf(visbuf
, sizeof(visbuf
),
1726 NULL
, "%s", buf
+ 1);
1727 (void) atomicio(vwrite
, STDERR_FILENO
,
1728 visbuf
, strlen(visbuf
));
1730 if (buf
[0] == '\02')
1735 if (buf
[0] == 'E') {
1736 (void) atomicio(vwrite
, remout
, "", 1);
1746 if (!isdigit((unsigned char)*cp
))
1747 SCREWUP("mtime.sec not present");
1748 ull
= strtoull(cp
, &cp
, 10);
1749 if (!cp
|| *cp
++ != ' ')
1750 SCREWUP("mtime.sec not delimited");
1751 if (TYPE_OVERFLOW(time_t, ull
))
1752 setimes
= 0; /* out of range */
1754 mtime
.tv_usec
= strtol(cp
, &cp
, 10);
1755 if (!cp
|| *cp
++ != ' ' || mtime
.tv_usec
< 0 ||
1756 mtime
.tv_usec
> 999999)
1757 SCREWUP("mtime.usec not delimited");
1758 if (!isdigit((unsigned char)*cp
))
1759 SCREWUP("atime.sec not present");
1760 ull
= strtoull(cp
, &cp
, 10);
1761 if (!cp
|| *cp
++ != ' ')
1762 SCREWUP("atime.sec not delimited");
1763 if (TYPE_OVERFLOW(time_t, ull
))
1764 setimes
= 0; /* out of range */
1766 atime
.tv_usec
= strtol(cp
, &cp
, 10);
1767 if (!cp
|| *cp
++ != '\0' || atime
.tv_usec
< 0 ||
1768 atime
.tv_usec
> 999999)
1769 SCREWUP("atime.usec not delimited");
1770 (void) atomicio(vwrite
, remout
, "", 1);
1773 if (*cp
!= 'C' && *cp
!= 'D') {
1775 * Check for the case "rcp remote:foo\* local:bar".
1776 * In this case, the line "No match." can be returned
1777 * by the shell before the rcp command on the remote is
1778 * executed so the ^Aerror_message convention isn't
1785 SCREWUP("expected control record");
1788 for (++cp
; cp
< buf
+ 5; cp
++) {
1789 if (*cp
< '0' || *cp
> '7')
1790 SCREWUP("bad mode");
1791 mode
= (mode
<< 3) | (*cp
- '0');
1796 SCREWUP("mode not delimited");
1798 if (!isdigit((unsigned char)*cp
))
1799 SCREWUP("size not present");
1800 ull
= strtoull(cp
, &cp
, 10);
1801 if (!cp
|| *cp
++ != ' ')
1802 SCREWUP("size not delimited");
1803 if (TYPE_OVERFLOW(off_t
, ull
))
1804 SCREWUP("size out of range");
1807 if (*cp
== '\0' || strchr(cp
, '/') != NULL
||
1808 strcmp(cp
, ".") == 0 || strcmp(cp
, "..") == 0) {
1809 run_err("error: unexpected filename: %s", cp
);
1812 if (npatterns
> 0) {
1813 for (n
= 0; n
< npatterns
; n
++) {
1814 if (strcmp(patterns
[n
], cp
) == 0 ||
1815 fnmatch(patterns
[n
], cp
, 0) == 0)
1818 if (n
>= npatterns
) {
1819 debug2_f("incoming filename \"%s\" does not "
1820 "match any of %zu expected patterns", cp
,
1822 for (n
= 0; n
< npatterns
; n
++) {
1823 debug3_f("expected pattern %zu: \"%s\"",
1826 SCREWUP("filename does not match request");
1830 static char *namebuf
;
1831 static size_t cursize
;
1834 need
= strlen(targ
) + strlen(cp
) + 250;
1835 if (need
> cursize
) {
1837 namebuf
= xmalloc(need
);
1840 (void) snprintf(namebuf
, need
, "%s%s%s", targ
,
1841 strcmp(targ
, "/") ? "/" : "", cp
);
1846 exists
= stat(np
, &stb
) == 0;
1847 if (buf
[0] == 'D') {
1848 int mod_flag
= pflag
;
1850 SCREWUP("received directory without -r");
1852 if (!S_ISDIR(stb
.st_mode
)) {
1857 (void) chmod(np
, mode
);
1859 /* Handle copying from a read-only directory */
1861 if (mkdir(np
, mode
| S_IRWXU
) == -1)
1864 vect
[0] = xstrdup(np
);
1868 (void) utimes(vect
[0], tv
);
1871 (void) chmod(vect
[0], mode
);
1877 if ((ofd
= open(np
, O_WRONLY
|O_CREAT
, mode
)) == -1) {
1878 bad
: run_err("%s: %s", np
, strerror(errno
));
1881 (void) atomicio(vwrite
, remout
, "", 1);
1882 if ((bp
= allocbuf(&buffer
, ofd
, COPY_BUFLEN
)) == NULL
) {
1890 * NB. do not use run_err() unless immediately followed by
1891 * exit() below as it may send a spurious reply that might
1892 * desyncronise us from the peer. Use note_err() instead.
1896 start_progress_meter(curfile
, size
, &statbytes
);
1897 set_nonblock(remin
);
1898 for (count
= i
= 0; i
< size
; i
+= bp
->cnt
) {
1904 j
= atomicio6(read
, remin
, cp
, amt
,
1907 run_err("%s", j
!= EPIPE
?
1909 "dropped connection");
1916 if (count
== bp
->cnt
) {
1917 /* Keep reading so we stay sync'd up. */
1919 if (atomicio(vwrite
, ofd
, bp
->buf
,
1921 note_err("%s: %s", np
,
1930 unset_nonblock(remin
);
1931 if (count
!= 0 && !wrerr
&&
1932 atomicio(vwrite
, ofd
, bp
->buf
, count
) != count
) {
1933 note_err("%s: %s", np
, strerror(errno
));
1936 if (!wrerr
&& (!exists
|| S_ISREG(stb
.st_mode
)) &&
1937 ftruncate(ofd
, size
) != 0)
1938 note_err("%s: truncate: %s", np
, strerror(errno
));
1940 if (exists
|| omode
!= mode
)
1942 if (fchmod(ofd
, omode
)) {
1943 #else /* HAVE_FCHMOD */
1944 if (chmod(np
, omode
)) {
1945 #endif /* HAVE_FCHMOD */
1946 note_err("%s: set mode: %s",
1947 np
, strerror(errno
));
1950 if (!exists
&& omode
!= mode
)
1952 if (fchmod(ofd
, omode
& ~mask
)) {
1953 #else /* HAVE_FCHMOD */
1954 if (chmod(np
, omode
& ~mask
)) {
1955 #endif /* HAVE_FCHMOD */
1956 note_err("%s: set mode: %s",
1957 np
, strerror(errno
));
1960 if (close(ofd
) == -1)
1961 note_err("%s: close: %s", np
, strerror(errno
));
1964 stop_progress_meter();
1965 if (setimes
&& !wrerr
) {
1967 if (utimes(np
, tv
) == -1) {
1968 note_err("%s: set times: %s",
1969 np
, strerror(errno
));
1972 /* If no error was noted then signal success for this file */
1973 if (note_err(NULL
) == 0)
1974 (void) atomicio(vwrite
, remout
, "", 1);
1977 for (n
= 0; n
< npatterns
; n
++)
1982 for (n
= 0; n
< npatterns
; n
++)
1985 run_err("protocol error: %s", why
);
1990 throughlocal_sftp(struct sftp_conn
*from
, struct sftp_conn
*to
,
1991 char *src
, char *targ
)
1993 char *target
= NULL
, *filename
= NULL
, *abs_dst
= NULL
;
1994 char *abs_src
= NULL
, *tmp
= NULL
;
1996 int i
, r
, targetisdir
, err
= 0;
1998 if ((filename
= basename(src
)) == NULL
)
1999 fatal("basename %s: %s", src
, strerror(errno
));
2001 if ((abs_src
= prepare_remote_path(from
, src
)) == NULL
||
2002 (target
= prepare_remote_path(to
, targ
)) == NULL
)
2004 memset(&g
, 0, sizeof(g
));
2006 targetisdir
= sftp_remote_is_dir(to
, target
);
2007 if (!targetisdir
&& targetshouldbedirectory
) {
2008 error("%s: destination is not a directory", targ
);
2013 debug3_f("copying remote %s to remote %s", abs_src
, target
);
2014 if ((r
= sftp_glob(from
, abs_src
, GLOB_NOCHECK
|GLOB_MARK
,
2016 if (r
== GLOB_NOSPACE
)
2017 error("%s: too many glob matches", src
);
2019 error("%s: %s", src
, strerror(ENOENT
));
2024 /* Did we actually get any matches back from the glob? */
2025 if (g
.gl_matchc
== 0 && g
.gl_pathc
== 1 && g
.gl_pathv
[0] != 0) {
2027 * If nothing matched but a path returned, then it's probably
2028 * a GLOB_NOCHECK result. Check whether the unglobbed path
2029 * exists so we can give a nice error message early.
2031 if (sftp_stat(from
, g
.gl_pathv
[0], 1, NULL
) != 0) {
2032 error("%s: %s", src
, strerror(ENOENT
));
2038 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
2039 tmp
= xstrdup(g
.gl_pathv
[i
]);
2040 if ((filename
= basename(tmp
)) == NULL
) {
2041 error("basename %s: %s", tmp
, strerror(errno
));
2047 abs_dst
= sftp_path_append(target
, filename
);
2049 abs_dst
= xstrdup(target
);
2051 debug("Fetching %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
2052 if (sftp_globpath_is_dir(g
.gl_pathv
[i
]) && iamrecursive
) {
2053 if (sftp_crossload_dir(from
, to
, g
.gl_pathv
[i
], abs_dst
,
2054 NULL
, pflag
, SFTP_PROGRESS_ONLY
, 1) == -1)
2057 if (sftp_crossload(from
, to
, g
.gl_pathv
[i
], abs_dst
,
2080 char ch
, *cp
, resp
, rbuf
[2048], visbuf
[2048];
2082 if (atomicio(read
, remin
, &resp
, sizeof(resp
)) != sizeof(resp
))
2092 case 1: /* error, followed by error msg */
2093 case 2: /* fatal error, "" */
2095 if (atomicio(read
, remin
, &ch
, sizeof(ch
)) != sizeof(ch
))
2098 } while (cp
< &rbuf
[sizeof(rbuf
) - 1] && ch
!= '\n');
2102 (void) snmprintf(visbuf
, sizeof(visbuf
),
2103 NULL
, "%s\n", rbuf
);
2104 (void) atomicio(vwrite
, STDERR_FILENO
,
2105 visbuf
, strlen(visbuf
));
2118 (void) fprintf(stderr
,
2119 "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2120 " [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2121 " [-P port] [-S program] [-X sftp_option] source ... target\n");
2126 run_err(const char *fmt
,...)
2132 if (fp
!= NULL
|| (remout
!= -1 && (fp
= fdopen(remout
, "w")))) {
2133 (void) fprintf(fp
, "%c", 0x01);
2134 (void) fprintf(fp
, "scp: ");
2136 (void) vfprintf(fp
, fmt
, ap
);
2138 (void) fprintf(fp
, "\n");
2144 vfmprintf(stderr
, fmt
, ap
);
2146 fprintf(stderr
, "\n");
2151 * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2152 * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2153 * any active error at the end of the transfer.
2156 note_err(const char *fmt
, ...)
2161 /* Replay any previously-noted error */
2165 run_err("%s", emsg
);
2172 /* Prefer first-noted error */
2177 vasnmprintf(&emsg
, INT_MAX
, NULL
, fmt
, ap
);
2187 if (!stat(cp
, &stb
)) {
2188 if (S_ISDIR(stb
.st_mode
))
2192 run_err("%s: %s", cp
, strerror(errno
));
2207 if (!isalpha(c
) && !isdigit((unsigned char)c
)) {
2222 bad
: fmprintf(stderr
, "%s: invalid user name\n", cp0
);
2227 allocbuf(BUF
*bp
, int fd
, int blksize
)
2230 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2233 if (fstat(fd
, &stb
) == -1) {
2234 run_err("fstat: %s", strerror(errno
));
2237 size
= ROUNDUP(stb
.st_blksize
, blksize
);
2240 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2242 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2243 if (bp
->cnt
>= size
)
2245 bp
->buf
= xrecallocarray(bp
->buf
, bp
->cnt
, size
, 1);
2254 (void)write(STDERR_FILENO
, "lost connection\n", 16);
2273 (void)waitpid(do_cmd_pid
, NULL
, 0);
2274 if (do_cmd_pid2
> 0)
2275 (void)waitpid(do_cmd_pid2
, NULL
, 0);