1 /* $OpenBSD: scp.c,v 1.248 2022/05/13 06:31:50 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"
121 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
127 #include "atomicio.h"
128 #include "pathnames.h"
131 #include "progressmeter.h"
135 #include "sftp-common.h"
136 #include "sftp-client.h"
138 extern char *__progname
;
140 #define COPY_BUFLEN 16384
142 int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t
*);
143 int do_cmd2(char *, char *, int, char *, int, int);
145 /* Struct for addargs */
147 arglist remote_remote_args
;
149 /* Bandwidth limit */
150 long long limit_kbps
= 0;
151 struct bwlimit bwlimit
;
153 /* Name of current file being transferred. */
156 /* This is set to non-zero to enable verbose mode. */
157 int verbose_mode
= 0;
158 LogLevel log_level
= SYSLOG_LEVEL_INFO
;
160 /* This is set to zero if the progressmeter is not desired. */
161 int showprogress
= 1;
164 * This is set to non-zero if remote-remote copy should be piped
165 * through this process.
167 int throughlocal
= 1;
169 /* Non-standard port to use for the ssh connection or -1. */
172 /* This is the program to execute for the secured connection. ("ssh" or -S) */
173 char *ssh_program
= _PATH_SSH_PROGRAM
;
175 /* This is used to store the pid of ssh_program */
176 pid_t do_cmd_pid
= -1;
177 pid_t do_cmd_pid2
= -1;
179 /* Needed for sftp */
180 volatile sig_atomic_t interrupted
= 0;
182 int remote_glob(struct sftp_conn
*, const char *, int,
183 int (*)(const char *, int), glob_t
*); /* proto for sftp-glob.c */
188 if (do_cmd_pid
> 1) {
189 kill(do_cmd_pid
, signo
? signo
: SIGTERM
);
190 waitpid(do_cmd_pid
, NULL
, 0);
192 if (do_cmd_pid2
> 1) {
193 kill(do_cmd_pid2
, signo
? signo
: SIGTERM
);
194 waitpid(do_cmd_pid2
, NULL
, 0);
203 suspone(int pid
, int signo
)
209 while (waitpid(pid
, &status
, WUNTRACED
) == -1 &&
218 suspone(do_cmd_pid
, signo
);
219 suspone(do_cmd_pid2
, signo
);
220 kill(getpid(), SIGSTOP
);
224 do_local_cmd(arglist
*a
)
231 fatal("do_local_cmd: no arguments");
234 fprintf(stderr
, "Executing:");
235 for (i
= 0; i
< a
->num
; i
++)
236 fmprintf(stderr
, " %s", a
->list
[i
]);
237 fprintf(stderr
, "\n");
239 if ((pid
= fork()) == -1)
240 fatal("do_local_cmd: fork: %s", strerror(errno
));
243 execvp(a
->list
[0], a
->list
);
249 ssh_signal(SIGTERM
, killchild
);
250 ssh_signal(SIGINT
, killchild
);
251 ssh_signal(SIGHUP
, killchild
);
253 while (waitpid(pid
, &status
, 0) == -1)
255 fatal("do_local_cmd: waitpid: %s", strerror(errno
));
259 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
266 * This function executes the given command as the specified user on the
267 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
268 * assigns the input and output file descriptors on success.
272 do_cmd(char *program
, char *host
, char *remuser
, int port
, int subsystem
,
273 char *cmd
, int *fdin
, int *fdout
, pid_t
*pid
)
275 int pin
[2], pout
[2], reserved
[2];
279 "Executing: program %s host %s, user %s, command %s\n",
281 remuser
? remuser
: "(unspecified)", cmd
);
287 * Reserve two descriptors so that the real pipes won't get
288 * descriptors 0 and 1 because that will screw up dup2 below.
290 if (pipe(reserved
) == -1)
291 fatal("pipe: %s", strerror(errno
));
293 /* Create a socket pair for communicating with ssh. */
295 fatal("pipe: %s", strerror(errno
));
296 if (pipe(pout
) == -1)
297 fatal("pipe: %s", strerror(errno
));
299 /* Free the reserved descriptors. */
303 ssh_signal(SIGTSTP
, suspchild
);
304 ssh_signal(SIGTTIN
, suspchild
);
305 ssh_signal(SIGTTOU
, suspchild
);
307 /* Fork a child to execute the command on the remote host using ssh. */
318 replacearg(&args
, 0, "%s", program
);
320 addargs(&args
, "-p");
321 addargs(&args
, "%d", port
);
323 if (remuser
!= NULL
) {
324 addargs(&args
, "-l");
325 addargs(&args
, "%s", remuser
);
328 addargs(&args
, "-s");
329 addargs(&args
, "--");
330 addargs(&args
, "%s", host
);
331 addargs(&args
, "%s", cmd
);
333 execvp(program
, args
.list
);
336 } else if (*pid
== -1) {
337 fatal("fork: %s", strerror(errno
));
339 /* Parent. Close the other side, and return the local side. */
344 ssh_signal(SIGTERM
, killchild
);
345 ssh_signal(SIGINT
, killchild
);
346 ssh_signal(SIGHUP
, killchild
);
351 * This function executes a command similar to do_cmd(), but expects the
352 * input and output descriptors to be setup by a previous call to do_cmd().
353 * This way the input and output of two commands can be connected.
356 do_cmd2(char *host
, char *remuser
, int port
, char *cmd
,
364 "Executing: 2nd program %s host %s, user %s, command %s\n",
366 remuser
? remuser
: "(unspecified)", cmd
);
371 /* Fork a child to execute the command on the remote host using ssh. */
377 replacearg(&args
, 0, "%s", ssh_program
);
379 addargs(&args
, "-p");
380 addargs(&args
, "%d", port
);
382 if (remuser
!= NULL
) {
383 addargs(&args
, "-l");
384 addargs(&args
, "%s", remuser
);
386 addargs(&args
, "-oBatchMode=yes");
387 addargs(&args
, "--");
388 addargs(&args
, "%s", host
);
389 addargs(&args
, "%s", cmd
);
391 execvp(ssh_program
, args
.list
);
394 } else if (pid
== -1) {
395 fatal("fork: %s", strerror(errno
));
397 while (waitpid(pid
, &status
, 0) == -1)
399 fatal("do_cmd2: waitpid: %s", strerror(errno
));
408 BUF
*allocbuf(BUF
*, int, int);
411 void run_err(const char *,...)
412 __attribute__((__format__ (printf
, 1, 2)))
413 __attribute__((__nonnull__ (1)));
414 int note_err(const char *,...)
415 __attribute__((__format__ (printf
, 1, 2)));
416 void verifydir(char *);
420 int errs
, remin
, remout
, remin2
, remout2
;
421 int Tflag
, pflag
, iamremote
, iamrecursive
, targetshouldbedirectory
;
424 char cmd
[CMDNEEDS
]; /* must hold "rcp -r -p -d\0" */
432 void rsource(char *, struct stat
*);
433 void sink(int, char *[], const char *);
434 void source(int, char *[]);
435 void tolocal(int, char *[], enum scp_mode_e
, char *sftp_direct
);
436 void toremote(int, char *[], enum scp_mode_e
, char *sftp_direct
);
439 void source_sftp(int, char *, char *, struct sftp_conn
*);
440 void sink_sftp(int, char *, const char *, struct sftp_conn
*);
441 void throughlocal_sftp(struct sftp_conn
*, struct sftp_conn
*,
445 main(int argc
, char **argv
)
447 int ch
, fflag
, tflag
, status
, n
;
448 char **newargv
, *argv0
;
452 enum scp_mode_e mode
= MODE_SFTP
;
453 char *sftp_direct
= NULL
;
455 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
460 /* Copy argv, because we modify it */
462 newargv
= xcalloc(MAXIMUM(argc
+ 1, 1), sizeof(*newargv
));
463 for (n
= 0; n
< argc
; n
++)
464 newargv
[n
] = xstrdup(argv
[n
]);
467 __progname
= ssh_get_progname(argv
[0]);
469 log_init(argv0
, log_level
, SYSLOG_FACILITY_USER
, 2);
471 memset(&args
, '\0', sizeof(args
));
472 memset(&remote_remote_args
, '\0', sizeof(remote_remote_args
));
473 args
.list
= remote_remote_args
.list
= NULL
;
474 addargs(&args
, "%s", ssh_program
);
475 addargs(&args
, "-x");
476 addargs(&args
, "-oPermitLocalCommand=no");
477 addargs(&args
, "-oClearAllForwardings=yes");
478 addargs(&args
, "-oRemoteCommand=none");
479 addargs(&args
, "-oRequestTTY=no");
481 fflag
= Tflag
= tflag
= 0;
482 while ((ch
= getopt(argc
, argv
,
483 "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:")) != -1) {
485 /* User-visible flags. */
487 fatal("SSH protocol v.1 is no longer supported");
496 addargs(&args
, "-%c", ch
);
497 addargs(&remote_remote_args
, "-%c", ch
);
500 sftp_direct
= optarg
;
513 addargs(&remote_remote_args
, "-%c", ch
);
514 addargs(&remote_remote_args
, "%s", optarg
);
515 addargs(&args
, "-%c", ch
);
516 addargs(&args
, "%s", optarg
);
525 sshport
= a2port(optarg
);
527 fatal("bad port \"%s\"\n", optarg
);
530 addargs(&remote_remote_args
, "-oBatchmode=yes");
531 addargs(&args
, "-oBatchmode=yes");
534 limit_kbps
= strtonum(optarg
, 1, 100 * 1024 * 1024,
538 limit_kbps
*= 1024; /* kbps */
539 bandwidth_limit_init(&bwlimit
, limit_kbps
, COPY_BUFLEN
);
548 ssh_program
= xstrdup(optarg
);
551 addargs(&args
, "-v");
552 addargs(&remote_remote_args
, "-v");
553 if (verbose_mode
== 0)
554 log_level
= SYSLOG_LEVEL_DEBUG1
;
555 else if (log_level
< SYSLOG_LEVEL_DEBUG3
)
560 addargs(&args
, "-q");
561 addargs(&remote_remote_args
, "-q");
565 /* Server options. */
567 targetshouldbedirectory
= 1;
569 case 'f': /* "from" */
577 setmode(0, O_BINARY
);
590 log_init(argv0
, log_level
, SYSLOG_FACILITY_USER
, 2);
592 /* Do this last because we want the user to be able to override it */
593 addargs(&args
, "-oForwardAgent=no");
598 if ((pwd
= getpwuid(userid
= getuid())) == NULL
)
599 fatal("unknown user %u", (u_int
) userid
);
601 if (!isatty(STDOUT_FILENO
))
605 /* Cannot pledge: -p allows setuid/setgid files... */
607 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
614 remin
= STDIN_FILENO
;
615 remout
= STDOUT_FILENO
;
618 /* Follow "protocol", send data. */
625 sink(argc
, argv
, NULL
);
631 targetshouldbedirectory
= 1;
635 /* Command to be executed on remote system using "ssh". */
636 (void) snprintf(cmd
, sizeof cmd
, "scp%s%s%s%s",
637 verbose_mode
? " -v" : "",
638 iamrecursive
? " -r" : "", pflag
? " -p" : "",
639 targetshouldbedirectory
? " -d" : "");
641 (void) ssh_signal(SIGPIPE
, lostconn
);
643 if (colon(argv
[argc
- 1])) /* Dest is remote host. */
644 toremote(argc
, argv
, mode
, sftp_direct
);
646 if (targetshouldbedirectory
)
647 verifydir(argv
[argc
- 1]);
648 tolocal(argc
, argv
, mode
, sftp_direct
); /* Dest is local host. */
651 * Finally check the exit status of the ssh process, if one was forked
652 * and no error has occurred yet
654 if (do_cmd_pid
!= -1 && (mode
== MODE_SFTP
|| errs
== 0)) {
658 (void) close(remout
);
659 if (waitpid(do_cmd_pid
, &status
, 0) == -1)
662 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
669 /* Callback from atomicio6 to update progress meter and limit bandwidth */
671 scpio(void *_cnt
, size_t s
)
673 off_t
*cnt
= (off_t
*)_cnt
;
676 refresh_progress_meter(0);
678 bandwidth_limit(&bwlimit
, s
);
683 do_times(int fd
, int verb
, const struct stat
*sb
)
685 /* strlen(2^64) == 20; strlen(10^6) == 7 */
686 char buf
[(20 + 7 + 2) * 2 + 2];
688 (void)snprintf(buf
, sizeof(buf
), "T%llu 0 %llu 0\n",
689 (unsigned long long) (sb
->st_mtime
< 0 ? 0 : sb
->st_mtime
),
690 (unsigned long long) (sb
->st_atime
< 0 ? 0 : sb
->st_atime
));
692 fprintf(stderr
, "File mtime %lld atime %lld\n",
693 (long long)sb
->st_mtime
, (long long)sb
->st_atime
);
694 fprintf(stderr
, "Sending file timestamps: %s", buf
);
696 (void) atomicio(vwrite
, fd
, buf
, strlen(buf
));
701 parse_scp_uri(const char *uri
, char **userp
, char **hostp
, int *portp
,
706 r
= parse_uri("scp", uri
, userp
, hostp
, portp
, pathp
);
707 if (r
== 0 && *pathp
== NULL
)
708 *pathp
= xstrdup(".");
712 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
714 append(char *cp
, char ***ap
, size_t *np
)
718 if ((tmp
= reallocarray(*ap
, *np
+ 1, sizeof(*tmp
))) == NULL
)
727 * Finds the start and end of the first brace pair in the pattern.
728 * returns 0 on success or -1 for invalid patterns.
731 find_brace(const char *pattern
, int *startp
, int *endp
)
734 int in_bracket
, brace_level
;
736 *startp
= *endp
= -1;
737 in_bracket
= brace_level
= 0;
738 for (i
= 0; i
< INT_MAX
&& *endp
< 0 && pattern
[i
] != '\0'; i
++) {
739 switch (pattern
[i
]) {
741 /* skip next character */
742 if (pattern
[i
+ 1] != '\0')
754 if (pattern
[i
+ 1] == '}') {
755 /* Protect a single {}, for find(1), like csh */
767 /* Unbalanced brace */
770 if (--brace_level
<= 0)
775 /* unbalanced brackets/braces */
776 if (*endp
< 0 && (*startp
>= 0 || in_bracket
))
782 * Assembles and records a successfully-expanded pattern, returns -1 on
786 emit_expansion(const char *pattern
, int brace_start
, int brace_end
,
787 int sel_start
, int sel_end
, char ***patternsp
, size_t *npatternsp
)
790 int o
= 0, tail_len
= strlen(pattern
+ brace_end
+ 1);
792 if ((cp
= malloc(brace_start
+ (sel_end
- sel_start
) +
793 tail_len
+ 1)) == NULL
)
796 /* Pattern before initial brace */
797 if (brace_start
> 0) {
798 memcpy(cp
, pattern
, brace_start
);
801 /* Current braced selection */
802 if (sel_end
- sel_start
> 0) {
803 memcpy(cp
+ o
, pattern
+ sel_start
,
804 sel_end
- sel_start
);
805 o
+= sel_end
- sel_start
;
807 /* Remainder of pattern after closing brace */
809 memcpy(cp
+ o
, pattern
+ brace_end
+ 1, tail_len
);
813 if (append(cp
, patternsp
, npatternsp
) != 0) {
821 * Expand the first encountered brace in pattern, appending the expanded
822 * patterns it yielded to the *patternsp array.
824 * Returns 0 on success or -1 on allocation failure.
826 * Signals whether expansion was performed via *expanded and whether
827 * pattern was invalid via *invalid.
830 brace_expand_one(const char *pattern
, char ***patternsp
, size_t *npatternsp
,
831 int *expanded
, int *invalid
)
834 int in_bracket
, brace_start
, brace_end
, brace_level
;
835 int sel_start
, sel_end
;
837 *invalid
= *expanded
= 0;
839 if (find_brace(pattern
, &brace_start
, &brace_end
) != 0) {
842 } else if (brace_start
== -1)
845 in_bracket
= brace_level
= 0;
846 for (i
= sel_start
= brace_start
+ 1; i
< brace_end
; i
++) {
847 switch (pattern
[i
]) {
865 if (i
< brace_end
- 1)
869 if (pattern
[i
] == ',' || i
== brace_end
- 1) {
870 if (in_bracket
|| brace_level
> 0)
872 /* End of a selection, emit an expanded pattern */
874 /* Adjust end index for last selection */
875 sel_end
= (i
== brace_end
- 1) ? brace_end
: i
;
876 if (emit_expansion(pattern
, brace_start
, brace_end
,
877 sel_start
, sel_end
, patternsp
, npatternsp
) != 0)
879 /* move on to the next selection */
884 if (in_bracket
|| brace_level
> 0) {
893 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
895 brace_expand(const char *pattern
, char ***patternsp
, size_t *npatternsp
)
897 char *cp
, *cp2
, **active
= NULL
, **done
= NULL
;
898 size_t i
, nactive
= 0, ndone
= 0;
899 int ret
= -1, invalid
= 0, expanded
= 0;
904 /* Start the worklist with the original pattern */
905 if ((cp
= strdup(pattern
)) == NULL
)
907 if (append(cp
, &active
, &nactive
) != 0) {
911 while (nactive
> 0) {
912 cp
= active
[nactive
- 1];
914 if (brace_expand_one(cp
, &active
, &nactive
,
915 &expanded
, &invalid
) == -1) {
920 fatal_f("invalid brace pattern \"%s\"", cp
);
923 * Current entry expanded to new entries on the
924 * active list; discard the progenitor pattern.
930 * Pattern did not expand; append the finename component to
933 if ((cp2
= strrchr(cp
, '/')) != NULL
)
937 if (append(xstrdup(cp2
), &done
, &ndone
) != 0) {
950 for (i
= 0; i
< nactive
; i
++)
953 for (i
= 0; i
< ndone
; i
++)
959 static struct sftp_conn
*
960 do_sftp_connect(char *host
, char *user
, int port
, char *sftp_direct
,
961 int *reminp
, int *remoutp
, int *pidp
)
963 if (sftp_direct
== NULL
) {
964 if (do_cmd(ssh_program
, host
, user
, port
, 1, "sftp",
965 reminp
, remoutp
, pidp
) < 0)
970 addargs(&args
, "sftp-server");
971 if (do_cmd(sftp_direct
, host
, NULL
, -1, 0, "sftp",
972 reminp
, remoutp
, pidp
) < 0)
975 return do_init(*reminp
, *remoutp
, 32768, 64, limit_kbps
);
979 toremote(int argc
, char **argv
, enum scp_mode_e mode
, char *sftp_direct
)
981 char *suser
= NULL
, *host
= NULL
, *src
= NULL
;
982 char *bp
, *tuser
, *thost
, *targ
;
983 int sport
= -1, tport
= -1;
984 struct sftp_conn
*conn
= NULL
, *conn2
= NULL
;
989 memset(&alist
, '\0', sizeof(alist
));
993 r
= parse_scp_uri(argv
[argc
- 1], &tuser
, &thost
, &tport
, &targ
);
995 fmprintf(stderr
, "%s: invalid uri\n", argv
[argc
- 1]);
1000 if (parse_user_host_path(argv
[argc
- 1], &tuser
, &thost
,
1002 fmprintf(stderr
, "%s: invalid target\n", argv
[argc
- 1]);
1008 /* Parse source files */
1009 for (i
= 0; i
< argc
- 1; i
++) {
1013 r
= parse_scp_uri(argv
[i
], &suser
, &host
, &sport
, &src
);
1015 fmprintf(stderr
, "%s: invalid uri\n", argv
[i
]);
1020 parse_user_host_path(argv
[i
], &suser
, &host
, &src
);
1022 if (suser
!= NULL
&& !okname(suser
)) {
1026 if (host
&& throughlocal
) { /* extended remote to remote */
1027 if (mode
== MODE_SFTP
) {
1029 /* Connect to dest now */
1030 conn
= do_sftp_connect(thost
, tuser
,
1032 &remin
, &remout
, &do_cmd_pid
);
1034 fatal("Unable to open "
1035 "destination connection");
1037 debug3_f("origin in %d out %d pid %ld",
1038 remin
, remout
, (long)do_cmd_pid
);
1041 * XXX remember suser/host/sport and only
1042 * reconnect if they change between arguments.
1043 * would save reconnections for cases like
1044 * scp -3 hosta:/foo hosta:/bar hostb:
1046 /* Connect to origin now */
1047 conn2
= do_sftp_connect(host
, suser
,
1049 &remin2
, &remout2
, &do_cmd_pid2
);
1050 if (conn2
== NULL
) {
1051 fatal("Unable to open "
1052 "source connection");
1054 debug3_f("destination in %d out %d pid %ld",
1055 remin2
, remout2
, (long)do_cmd_pid2
);
1056 throughlocal_sftp(conn2
, conn
, src
, targ
);
1057 (void) close(remin2
);
1058 (void) close(remout2
);
1059 remin2
= remout2
= -1;
1060 if (waitpid(do_cmd_pid2
, &status
, 0) == -1)
1062 else if (!WIFEXITED(status
) ||
1063 WEXITSTATUS(status
) != 0)
1068 xasprintf(&bp
, "%s -f %s%s", cmd
,
1069 *src
== '-' ? "-- " : "", src
);
1070 if (do_cmd(ssh_program
, host
, suser
, sport
, 0,
1071 bp
, &remin
, &remout
, &do_cmd_pid
) < 0)
1074 xasprintf(&bp
, "%s -t %s%s", cmd
,
1075 *targ
== '-' ? "-- " : "", targ
);
1076 if (do_cmd2(thost
, tuser
, tport
, bp
,
1080 (void) close(remin
);
1081 (void) close(remout
);
1082 remin
= remout
= -1;
1084 } else if (host
) { /* standard remote to remote */
1086 * Second remote user is passed to first remote side
1087 * via scp command-line. Ensure it contains no obvious
1090 if (tuser
!= NULL
&& !okname(tuser
)) {
1094 if (tport
!= -1 && tport
!= SSH_DEFAULT_PORT
) {
1095 /* This would require the remote support URIs */
1096 fatal("target port not supported with two "
1097 "remote hosts and the -R option");
1101 addargs(&alist
, "%s", ssh_program
);
1102 addargs(&alist
, "-x");
1103 addargs(&alist
, "-oClearAllForwardings=yes");
1104 addargs(&alist
, "-n");
1105 for (j
= 0; j
< remote_remote_args
.num
; j
++) {
1106 addargs(&alist
, "%s",
1107 remote_remote_args
.list
[j
]);
1111 addargs(&alist
, "-p");
1112 addargs(&alist
, "%d", sport
);
1115 addargs(&alist
, "-l");
1116 addargs(&alist
, "%s", suser
);
1118 addargs(&alist
, "--");
1119 addargs(&alist
, "%s", host
);
1120 addargs(&alist
, "%s", cmd
);
1121 addargs(&alist
, "%s", src
);
1122 addargs(&alist
, "%s%s%s:%s",
1123 tuser
? tuser
: "", tuser
? "@" : "",
1125 if (do_local_cmd(&alist
) != 0)
1127 } else { /* local to remote */
1128 if (mode
== MODE_SFTP
) {
1130 /* Connect to remote now */
1131 conn
= do_sftp_connect(thost
, tuser
,
1133 &remin
, &remout
, &do_cmd_pid
);
1135 fatal("Unable to open sftp "
1141 source_sftp(1, argv
[i
], targ
, conn
);
1146 xasprintf(&bp
, "%s -t %s%s", cmd
,
1147 *targ
== '-' ? "-- " : "", targ
);
1148 if (do_cmd(ssh_program
, thost
, tuser
, tport
, 0,
1149 bp
, &remin
, &remout
, &do_cmd_pid
) < 0)
1155 source(1, argv
+ i
);
1159 if (mode
== MODE_SFTP
)
1170 tolocal(int argc
, char **argv
, enum scp_mode_e mode
, char *sftp_direct
)
1172 char *bp
, *host
= NULL
, *src
= NULL
, *suser
= NULL
;
1174 struct sftp_conn
*conn
= NULL
;
1175 int i
, r
, sport
= -1;
1177 memset(&alist
, '\0', sizeof(alist
));
1180 for (i
= 0; i
< argc
- 1; i
++) {
1184 r
= parse_scp_uri(argv
[i
], &suser
, &host
, &sport
, &src
);
1186 fmprintf(stderr
, "%s: invalid uri\n", argv
[i
]);
1191 parse_user_host_path(argv
[i
], &suser
, &host
, &src
);
1192 if (suser
!= NULL
&& !okname(suser
)) {
1196 if (!host
) { /* Local to local. */
1198 addargs(&alist
, "%s", _PATH_CP
);
1200 addargs(&alist
, "-r");
1202 addargs(&alist
, "-p");
1203 addargs(&alist
, "--");
1204 addargs(&alist
, "%s", argv
[i
]);
1205 addargs(&alist
, "%s", argv
[argc
-1]);
1206 if (do_local_cmd(&alist
))
1210 /* Remote to local. */
1211 if (mode
== MODE_SFTP
) {
1212 conn
= do_sftp_connect(host
, suser
, sport
,
1213 sftp_direct
, &remin
, &remout
, &do_cmd_pid
);
1215 error("sftp connection failed");
1221 sink_sftp(1, argv
[argc
- 1], src
, conn
);
1224 (void) close(remin
);
1225 (void) close(remout
);
1226 remin
= remout
= -1;
1230 xasprintf(&bp
, "%s -f %s%s",
1231 cmd
, *src
== '-' ? "-- " : "", src
);
1232 if (do_cmd(ssh_program
, host
, suser
, sport
, 0, bp
,
1233 &remin
, &remout
, &do_cmd_pid
) < 0) {
1239 sink(1, argv
+ argc
- 1, src
);
1240 (void) close(remin
);
1241 remin
= remout
= -1;
1248 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1250 prepare_remote_path(struct sftp_conn
*conn
, const char *path
)
1254 /* Handle ~ prefixed paths */
1255 if (*path
== '\0' || strcmp(path
, "~") == 0)
1256 return xstrdup(".");
1258 return xstrdup(path
);
1259 if (strncmp(path
, "~/", 2) == 0) {
1260 if ((nslash
= strspn(path
+ 2, "/")) == strlen(path
+ 2))
1261 return xstrdup(".");
1262 return xstrdup(path
+ 2 + nslash
);
1264 if (can_expand_path(conn
))
1265 return do_expand_path(conn
, path
);
1266 /* No protocol extension */
1267 error("server expand-path extension is required "
1268 "for ~user paths in SFTP mode");
1273 source_sftp(int argc
, char *src
, char *targ
, struct sftp_conn
*conn
)
1275 char *target
= NULL
, *filename
= NULL
, *abs_dst
= NULL
;
1276 int src_is_dir
, target_is_dir
;
1280 memset(&a
, '\0', sizeof(a
));
1281 if (stat(src
, &st
) != 0)
1282 fatal("stat local \"%s\": %s", src
, strerror(errno
));
1283 src_is_dir
= S_ISDIR(st
.st_mode
);
1284 if ((filename
= basename(src
)) == NULL
)
1285 fatal("basename \"%s\": %s", src
, strerror(errno
));
1288 * No need to glob here - the local shell already took care of
1291 if ((target
= prepare_remote_path(conn
, targ
)) == NULL
)
1293 target_is_dir
= remote_is_dir(conn
, target
);
1294 if (targetshouldbedirectory
&& !target_is_dir
) {
1295 debug("target directory \"%s\" does not exist", target
);
1296 a
.flags
= SSH2_FILEXFER_ATTR_PERMISSIONS
;
1297 a
.perm
= st
.st_mode
| 0700; /* ensure writable */
1298 if (do_mkdir(conn
, target
, &a
, 1) != 0)
1299 cleanup_exit(255); /* error already logged */
1303 abs_dst
= path_append(target
, filename
);
1308 debug3_f("copying local %s to remote %s", src
, abs_dst
);
1310 if (src_is_dir
&& iamrecursive
) {
1311 if (upload_dir(conn
, src
, abs_dst
, pflag
,
1312 SFTP_PROGRESS_ONLY
, 0, 0, 1, 1) != 0) {
1313 error("failed to upload directory %s to %s", src
, targ
);
1316 } else if (do_upload(conn
, src
, abs_dst
, pflag
, 0, 0, 1) != 0) {
1317 error("failed to upload file %s to %s", src
, targ
);
1326 source(int argc
, char **argv
)
1333 int fd
= -1, haderr
, indx
;
1334 char *last
, *name
, buf
[PATH_MAX
+ 128], encname
[PATH_MAX
];
1337 for (indx
= 0; indx
< argc
; ++indx
) {
1341 while (len
> 1 && name
[len
-1] == '/')
1343 if ((fd
= open(name
, O_RDONLY
|O_NONBLOCK
)) == -1)
1345 if (strchr(name
, '\n') != NULL
) {
1346 strnvis(encname
, name
, sizeof(encname
), VIS_NL
);
1349 if (fstat(fd
, &stb
) == -1) {
1350 syserr
: run_err("%s: %s", name
, strerror(errno
));
1353 if (stb
.st_size
< 0) {
1354 run_err("%s: %s", name
, "Negative file size");
1358 switch (stb
.st_mode
& S_IFMT
) {
1363 rsource(name
, &stb
);
1368 run_err("%s: not a regular file", name
);
1371 if ((last
= strrchr(name
, '/')) == NULL
)
1377 if (do_times(remout
, verbose_mode
, &stb
) < 0)
1380 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1381 snprintf(buf
, sizeof buf
, "C%04o %lld %s\n",
1382 (u_int
) (stb
.st_mode
& FILEMODEMASK
),
1383 (long long)stb
.st_size
, last
);
1385 fmprintf(stderr
, "Sending file modes: %s", buf
);
1386 (void) atomicio(vwrite
, remout
, buf
, strlen(buf
));
1389 if ((bp
= allocbuf(&buffer
, fd
, COPY_BUFLEN
)) == NULL
) {
1390 next
: if (fd
!= -1) {
1397 start_progress_meter(curfile
, stb
.st_size
, &statbytes
);
1398 set_nonblock(remout
);
1399 for (haderr
= i
= 0; i
< stb
.st_size
; i
+= bp
->cnt
) {
1401 if (i
+ (off_t
)amt
> stb
.st_size
)
1402 amt
= stb
.st_size
- i
;
1404 if ((nr
= atomicio(read
, fd
,
1405 bp
->buf
, amt
)) != amt
) {
1407 memset(bp
->buf
+ nr
, 0, amt
- nr
);
1410 /* Keep writing after error to retain sync */
1412 (void)atomicio(vwrite
, remout
, bp
->buf
, amt
);
1413 memset(bp
->buf
, 0, amt
);
1416 if (atomicio6(vwrite
, remout
, bp
->buf
, amt
, scpio
,
1420 unset_nonblock(remout
);
1423 if (close(fd
) == -1 && !haderr
)
1428 (void) atomicio(vwrite
, remout
, "", 1);
1430 run_err("%s: %s", name
, strerror(haderr
));
1433 stop_progress_meter();
1438 rsource(char *name
, struct stat
*statp
)
1442 char *last
, *vect
[1], path
[PATH_MAX
];
1444 if (!(dirp
= opendir(name
))) {
1445 run_err("%s: %s", name
, strerror(errno
));
1448 last
= strrchr(name
, '/');
1454 if (do_times(remout
, verbose_mode
, statp
) < 0) {
1459 (void) snprintf(path
, sizeof path
, "D%04o %d %.1024s\n",
1460 (u_int
) (statp
->st_mode
& FILEMODEMASK
), 0, last
);
1462 fmprintf(stderr
, "Entering directory: %s", path
);
1463 (void) atomicio(vwrite
, remout
, path
, strlen(path
));
1464 if (response() < 0) {
1468 while ((dp
= readdir(dirp
)) != NULL
) {
1471 if (!strcmp(dp
->d_name
, ".") || !strcmp(dp
->d_name
, ".."))
1473 if (strlen(name
) + 1 + strlen(dp
->d_name
) >= sizeof(path
) - 1) {
1474 run_err("%s/%s: name too long", name
, dp
->d_name
);
1477 (void) snprintf(path
, sizeof path
, "%s/%s", name
, dp
->d_name
);
1481 (void) closedir(dirp
);
1482 (void) atomicio(vwrite
, remout
, "E\n", 2);
1487 sink_sftp(int argc
, char *dst
, const char *src
, struct sftp_conn
*conn
)
1489 char *abs_src
= NULL
;
1490 char *abs_dst
= NULL
;
1492 char *filename
, *tmp
= NULL
;
1493 int i
, r
, err
= 0, dst_is_dir
;
1496 memset(&g
, 0, sizeof(g
));
1499 * Here, we need remote glob as SFTP can not depend on remote shell
1502 if ((abs_src
= prepare_remote_path(conn
, src
)) == NULL
) {
1507 debug3_f("copying remote %s to local %s", abs_src
, dst
);
1508 if ((r
= remote_glob(conn
, abs_src
, GLOB_MARK
, NULL
, &g
)) != 0) {
1509 if (r
== GLOB_NOSPACE
)
1510 error("%s: too many glob matches", src
);
1512 error("%s: %s", src
, strerror(ENOENT
));
1517 if ((r
= stat(dst
, &st
)) != 0)
1518 debug2_f("stat local \"%s\": %s", dst
, strerror(errno
));
1519 dst_is_dir
= r
== 0 && S_ISDIR(st
.st_mode
);
1521 if (g
.gl_matchc
> 1 && !dst_is_dir
) {
1523 error("Multiple files match pattern, but destination "
1524 "\"%s\" is not a directory", dst
);
1528 debug2_f("creating destination \"%s\"", dst
);
1529 if (mkdir(dst
, 0777) != 0) {
1530 error("local mkdir \"%s\": %s", dst
, strerror(errno
));
1537 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1538 tmp
= xstrdup(g
.gl_pathv
[i
]);
1539 if ((filename
= basename(tmp
)) == NULL
) {
1540 error("basename %s: %s", tmp
, strerror(errno
));
1546 abs_dst
= path_append(dst
, filename
);
1548 abs_dst
= xstrdup(dst
);
1550 debug("Fetching %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
1551 if (globpath_is_dir(g
.gl_pathv
[i
]) && iamrecursive
) {
1552 if (download_dir(conn
, g
.gl_pathv
[i
], abs_dst
, NULL
,
1553 pflag
, SFTP_PROGRESS_ONLY
, 0, 0, 1, 1) == -1)
1556 if (do_download(conn
, g
.gl_pathv
[i
], abs_dst
, NULL
,
1557 pflag
, 0, 0, 1) == -1)
1575 #define TYPE_OVERFLOW(type, val) \
1576 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
1577 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1578 (sizeof(type) != 4 && sizeof(type) != 8))
1581 sink(int argc
, char **argv
, const char *src
)
1588 int amt
, exists
, first
, ofd
;
1589 mode_t mode
, omode
, mask
;
1590 off_t size
, statbytes
;
1591 unsigned long long ull
;
1592 int setimes
, targisdir
, wrerr
;
1593 char ch
, *cp
, *np
, *targ
, *why
, *vect
[1], buf
[2048], visbuf
[2048];
1594 char **patterns
= NULL
;
1595 size_t n
, npatterns
= 0;
1596 struct timeval tv
[2];
1600 #define SCREWUP(str) { why = str; goto screwup; }
1602 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t
, 0))
1603 SCREWUP("Unexpected off_t/time_t size");
1605 setimes
= targisdir
= 0;
1610 run_err("ambiguous target");
1614 if (targetshouldbedirectory
)
1617 (void) atomicio(vwrite
, remout
, "", 1);
1618 if (stat(targ
, &stb
) == 0 && S_ISDIR(stb
.st_mode
))
1620 if (src
!= NULL
&& !iamrecursive
&& !Tflag
) {
1622 * Prepare to try to restrict incoming filenames to match
1623 * the requested destination file glob.
1625 if (brace_expand(src
, &patterns
, &npatterns
) != 0)
1626 fatal_f("could not expand pattern");
1628 for (first
= 1;; first
= 0) {
1630 if (atomicio(read
, remin
, cp
, 1) != 1)
1633 SCREWUP("unexpected <newline>");
1635 if (atomicio(read
, remin
, &ch
, sizeof(ch
)) != sizeof(ch
))
1636 SCREWUP("lost connection");
1638 } while (cp
< &buf
[sizeof(buf
) - 1] && ch
!= '\n');
1641 fmprintf(stderr
, "Sink: %s", buf
);
1643 if (buf
[0] == '\01' || buf
[0] == '\02') {
1644 if (iamremote
== 0) {
1645 (void) snmprintf(visbuf
, sizeof(visbuf
),
1646 NULL
, "%s", buf
+ 1);
1647 (void) atomicio(vwrite
, STDERR_FILENO
,
1648 visbuf
, strlen(visbuf
));
1650 if (buf
[0] == '\02')
1655 if (buf
[0] == 'E') {
1656 (void) atomicio(vwrite
, remout
, "", 1);
1666 if (!isdigit((unsigned char)*cp
))
1667 SCREWUP("mtime.sec not present");
1668 ull
= strtoull(cp
, &cp
, 10);
1669 if (!cp
|| *cp
++ != ' ')
1670 SCREWUP("mtime.sec not delimited");
1671 if (TYPE_OVERFLOW(time_t, ull
))
1672 setimes
= 0; /* out of range */
1674 mtime
.tv_usec
= strtol(cp
, &cp
, 10);
1675 if (!cp
|| *cp
++ != ' ' || mtime
.tv_usec
< 0 ||
1676 mtime
.tv_usec
> 999999)
1677 SCREWUP("mtime.usec not delimited");
1678 if (!isdigit((unsigned char)*cp
))
1679 SCREWUP("atime.sec not present");
1680 ull
= strtoull(cp
, &cp
, 10);
1681 if (!cp
|| *cp
++ != ' ')
1682 SCREWUP("atime.sec not delimited");
1683 if (TYPE_OVERFLOW(time_t, ull
))
1684 setimes
= 0; /* out of range */
1686 atime
.tv_usec
= strtol(cp
, &cp
, 10);
1687 if (!cp
|| *cp
++ != '\0' || atime
.tv_usec
< 0 ||
1688 atime
.tv_usec
> 999999)
1689 SCREWUP("atime.usec not delimited");
1690 (void) atomicio(vwrite
, remout
, "", 1);
1693 if (*cp
!= 'C' && *cp
!= 'D') {
1695 * Check for the case "rcp remote:foo\* local:bar".
1696 * In this case, the line "No match." can be returned
1697 * by the shell before the rcp command on the remote is
1698 * executed so the ^Aerror_message convention isn't
1705 SCREWUP("expected control record");
1708 for (++cp
; cp
< buf
+ 5; cp
++) {
1709 if (*cp
< '0' || *cp
> '7')
1710 SCREWUP("bad mode");
1711 mode
= (mode
<< 3) | (*cp
- '0');
1716 SCREWUP("mode not delimited");
1718 if (!isdigit((unsigned char)*cp
))
1719 SCREWUP("size not present");
1720 ull
= strtoull(cp
, &cp
, 10);
1721 if (!cp
|| *cp
++ != ' ')
1722 SCREWUP("size not delimited");
1723 if (TYPE_OVERFLOW(off_t
, ull
))
1724 SCREWUP("size out of range");
1727 if (*cp
== '\0' || strchr(cp
, '/') != NULL
||
1728 strcmp(cp
, ".") == 0 || strcmp(cp
, "..") == 0) {
1729 run_err("error: unexpected filename: %s", cp
);
1732 if (npatterns
> 0) {
1733 for (n
= 0; n
< npatterns
; n
++) {
1734 if (fnmatch(patterns
[n
], cp
, 0) == 0)
1738 SCREWUP("filename does not match request");
1741 static char *namebuf
;
1742 static size_t cursize
;
1745 need
= strlen(targ
) + strlen(cp
) + 250;
1746 if (need
> cursize
) {
1748 namebuf
= xmalloc(need
);
1751 (void) snprintf(namebuf
, need
, "%s%s%s", targ
,
1752 strcmp(targ
, "/") ? "/" : "", cp
);
1757 exists
= stat(np
, &stb
) == 0;
1758 if (buf
[0] == 'D') {
1759 int mod_flag
= pflag
;
1761 SCREWUP("received directory without -r");
1763 if (!S_ISDIR(stb
.st_mode
)) {
1768 (void) chmod(np
, mode
);
1770 /* Handle copying from a read-only directory */
1772 if (mkdir(np
, mode
| S_IRWXU
) == -1)
1775 vect
[0] = xstrdup(np
);
1779 (void) utimes(vect
[0], tv
);
1782 (void) chmod(vect
[0], mode
);
1788 if ((ofd
= open(np
, O_WRONLY
|O_CREAT
, mode
)) == -1) {
1789 bad
: run_err("%s: %s", np
, strerror(errno
));
1792 (void) atomicio(vwrite
, remout
, "", 1);
1793 if ((bp
= allocbuf(&buffer
, ofd
, COPY_BUFLEN
)) == NULL
) {
1801 * NB. do not use run_err() unless immediately followed by
1802 * exit() below as it may send a spurious reply that might
1803 * desyncronise us from the peer. Use note_err() instead.
1807 start_progress_meter(curfile
, size
, &statbytes
);
1808 set_nonblock(remin
);
1809 for (count
= i
= 0; i
< size
; i
+= bp
->cnt
) {
1815 j
= atomicio6(read
, remin
, cp
, amt
,
1818 run_err("%s", j
!= EPIPE
?
1820 "dropped connection");
1827 if (count
== bp
->cnt
) {
1828 /* Keep reading so we stay sync'd up. */
1830 if (atomicio(vwrite
, ofd
, bp
->buf
,
1832 note_err("%s: %s", np
,
1841 unset_nonblock(remin
);
1842 if (count
!= 0 && !wrerr
&&
1843 atomicio(vwrite
, ofd
, bp
->buf
, count
) != count
) {
1844 note_err("%s: %s", np
, strerror(errno
));
1847 if (!wrerr
&& (!exists
|| S_ISREG(stb
.st_mode
)) &&
1848 ftruncate(ofd
, size
) != 0)
1849 note_err("%s: truncate: %s", np
, strerror(errno
));
1851 if (exists
|| omode
!= mode
)
1853 if (fchmod(ofd
, omode
)) {
1854 #else /* HAVE_FCHMOD */
1855 if (chmod(np
, omode
)) {
1856 #endif /* HAVE_FCHMOD */
1857 note_err("%s: set mode: %s",
1858 np
, strerror(errno
));
1861 if (!exists
&& omode
!= mode
)
1863 if (fchmod(ofd
, omode
& ~mask
)) {
1864 #else /* HAVE_FCHMOD */
1865 if (chmod(np
, omode
& ~mask
)) {
1866 #endif /* HAVE_FCHMOD */
1867 note_err("%s: set mode: %s",
1868 np
, strerror(errno
));
1871 if (close(ofd
) == -1)
1872 note_err("%s: close: %s", np
, strerror(errno
));
1875 stop_progress_meter();
1876 if (setimes
&& !wrerr
) {
1878 if (utimes(np
, tv
) == -1) {
1879 note_err("%s: set times: %s",
1880 np
, strerror(errno
));
1883 /* If no error was noted then signal success for this file */
1884 if (note_err(NULL
) == 0)
1885 (void) atomicio(vwrite
, remout
, "", 1);
1888 for (n
= 0; n
< npatterns
; n
++)
1893 for (n
= 0; n
< npatterns
; n
++)
1896 run_err("protocol error: %s", why
);
1901 throughlocal_sftp(struct sftp_conn
*from
, struct sftp_conn
*to
,
1902 char *src
, char *targ
)
1904 char *target
= NULL
, *filename
= NULL
, *abs_dst
= NULL
;
1905 char *abs_src
= NULL
, *tmp
= NULL
;
1907 int i
, r
, targetisdir
, err
= 0;
1909 if ((filename
= basename(src
)) == NULL
)
1910 fatal("basename %s: %s", src
, strerror(errno
));
1912 if ((abs_src
= prepare_remote_path(from
, src
)) == NULL
||
1913 (target
= prepare_remote_path(to
, targ
)) == NULL
)
1915 memset(&g
, 0, sizeof(g
));
1917 targetisdir
= remote_is_dir(to
, target
);
1918 if (!targetisdir
&& targetshouldbedirectory
) {
1919 error("%s: destination is not a directory", targ
);
1924 debug3_f("copying remote %s to remote %s", abs_src
, target
);
1925 if ((r
= remote_glob(from
, abs_src
, GLOB_MARK
, NULL
, &g
)) != 0) {
1926 if (r
== GLOB_NOSPACE
)
1927 error("%s: too many glob matches", src
);
1929 error("%s: %s", src
, strerror(ENOENT
));
1934 for (i
= 0; g
.gl_pathv
[i
] && !interrupted
; i
++) {
1935 tmp
= xstrdup(g
.gl_pathv
[i
]);
1936 if ((filename
= basename(tmp
)) == NULL
) {
1937 error("basename %s: %s", tmp
, strerror(errno
));
1943 abs_dst
= path_append(target
, filename
);
1945 abs_dst
= xstrdup(target
);
1947 debug("Fetching %s to %s\n", g
.gl_pathv
[i
], abs_dst
);
1948 if (globpath_is_dir(g
.gl_pathv
[i
]) && iamrecursive
) {
1949 if (crossload_dir(from
, to
, g
.gl_pathv
[i
], abs_dst
,
1950 NULL
, pflag
, SFTP_PROGRESS_ONLY
, 1) == -1)
1953 if (do_crossload(from
, to
, g
.gl_pathv
[i
], abs_dst
, NULL
,
1976 char ch
, *cp
, resp
, rbuf
[2048], visbuf
[2048];
1978 if (atomicio(read
, remin
, &resp
, sizeof(resp
)) != sizeof(resp
))
1988 case 1: /* error, followed by error msg */
1989 case 2: /* fatal error, "" */
1991 if (atomicio(read
, remin
, &ch
, sizeof(ch
)) != sizeof(ch
))
1994 } while (cp
< &rbuf
[sizeof(rbuf
) - 1] && ch
!= '\n');
1998 (void) snmprintf(visbuf
, sizeof(visbuf
),
1999 NULL
, "%s\n", rbuf
);
2000 (void) atomicio(vwrite
, STDERR_FILENO
,
2001 visbuf
, strlen(visbuf
));
2014 (void) fprintf(stderr
,
2015 "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2016 " [-i identity_file] [-J destination] [-l limit]\n"
2017 " [-o ssh_option] [-P port] [-S program] source ... target\n");
2022 run_err(const char *fmt
,...)
2028 if (fp
!= NULL
|| (remout
!= -1 && (fp
= fdopen(remout
, "w")))) {
2029 (void) fprintf(fp
, "%c", 0x01);
2030 (void) fprintf(fp
, "scp: ");
2032 (void) vfprintf(fp
, fmt
, ap
);
2034 (void) fprintf(fp
, "\n");
2040 vfmprintf(stderr
, fmt
, ap
);
2042 fprintf(stderr
, "\n");
2047 * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2048 * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2049 * any active error at the end of the transfer.
2052 note_err(const char *fmt
, ...)
2057 /* Replay any previously-noted error */
2061 run_err("%s", emsg
);
2068 /* Prefer first-noted error */
2073 vasnmprintf(&emsg
, INT_MAX
, NULL
, fmt
, ap
);
2083 if (!stat(cp
, &stb
)) {
2084 if (S_ISDIR(stb
.st_mode
))
2088 run_err("%s: %s", cp
, strerror(errno
));
2103 if (!isalpha(c
) && !isdigit((unsigned char)c
)) {
2118 bad
: fmprintf(stderr
, "%s: invalid user name\n", cp0
);
2123 allocbuf(BUF
*bp
, int fd
, int blksize
)
2126 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2129 if (fstat(fd
, &stb
) == -1) {
2130 run_err("fstat: %s", strerror(errno
));
2133 size
= ROUNDUP(stb
.st_blksize
, blksize
);
2136 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2138 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2139 if (bp
->cnt
>= size
)
2141 bp
->buf
= xrecallocarray(bp
->buf
, bp
->cnt
, size
, 1);
2150 (void)write(STDERR_FILENO
, "lost connection\n", 16);
2169 waitpid(do_cmd_pid
, NULL
, 0);
2170 if (do_cmd_pid2
> 0)
2171 waitpid(do_cmd_pid2
, NULL
, 0);