xref: /freebsd/crypto/openssh/scp.c (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 /* $OpenBSD: scp.c,v 1.260 2023/10/11 05:42:08 djm Exp $ */
2 /*
3  * scp - secure remote copy.  This is basically patched BSD rcp which
4  * uses ssh to do the data transfer (instead of using rcmd).
5  *
6  * NOTE: This version should NOT be suid root.  (This uses ssh to
7  * do the transfer and ssh has the necessary privileges.)
8  *
9  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
10  *
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".
16  */
17 /*
18  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
19  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
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.
29  *
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.
40  */
41 
42 /*
43  * Parts from:
44  *
45  * Copyright (c) 1983, 1990, 1992, 1993, 1995
46  *	The Regents of the University of California.  All rights reserved.
47  *
48  * Redistribution and use in source and binary forms, with or without
49  * modification, are permitted provided that the following conditions
50  * are met:
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.
59  *
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
70  * SUCH DAMAGE.
71  *
72  */
73 
74 #include "includes.h"
75 
76 #include <sys/types.h>
77 #ifdef HAVE_SYS_STAT_H
78 # include <sys/stat.h>
79 #endif
80 #ifdef HAVE_POLL_H
81 #include <poll.h>
82 #else
83 # ifdef HAVE_SYS_POLL_H
84 #  include <sys/poll.h>
85 # endif
86 #endif
87 #ifdef HAVE_SYS_TIME_H
88 # include <sys/time.h>
89 #endif
90 #include <sys/wait.h>
91 #include <sys/uio.h>
92 
93 #include <ctype.h>
94 #include <dirent.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #ifdef HAVE_FNMATCH_H
98 #include <fnmatch.h>
99 #endif
100 #ifdef USE_SYSTEM_GLOB
101 # include <glob.h>
102 #else
103 # include "openbsd-compat/glob.h"
104 #endif
105 #ifdef HAVE_LIBGEN_H
106 #include <libgen.h>
107 #endif
108 #include <limits.h>
109 #ifdef HAVE_UTIL_H
110 # include <util.h>
111 #endif
112 #include <locale.h>
113 #include <pwd.h>
114 #include <signal.h>
115 #include <stdarg.h>
116 #ifdef HAVE_STDINT_H
117 # include <stdint.h>
118 #endif
119 #include <stdio.h>
120 #include <stdlib.h>
121 #include <string.h>
122 #include <time.h>
123 #include <unistd.h>
124 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
125 #include <vis.h>
126 #endif
127 
128 #include "xmalloc.h"
129 #include "ssh.h"
130 #include "atomicio.h"
131 #include "pathnames.h"
132 #include "log.h"
133 #include "misc.h"
134 #include "progressmeter.h"
135 #include "utf8.h"
136 #include "sftp.h"
137 
138 #include "sftp-common.h"
139 #include "sftp-client.h"
140 
141 extern char *__progname;
142 
143 #define COPY_BUFLEN	16384
144 
145 int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t *);
146 int do_cmd2(char *, char *, int, char *, int, int);
147 
148 /* Struct for addargs */
149 arglist args;
150 arglist remote_remote_args;
151 
152 /* Bandwidth limit */
153 long long limit_kbps = 0;
154 struct bwlimit bwlimit;
155 
156 /* Name of current file being transferred. */
157 char *curfile;
158 
159 /* This is set to non-zero to enable verbose mode. */
160 int verbose_mode = 0;
161 LogLevel log_level = SYSLOG_LEVEL_INFO;
162 
163 /* This is set to zero if the progressmeter is not desired. */
164 int showprogress = 1;
165 
166 /*
167  * This is set to non-zero if remote-remote copy should be piped
168  * through this process.
169  */
170 int throughlocal = 1;
171 
172 /* Non-standard port to use for the ssh connection or -1. */
173 int sshport = -1;
174 
175 /* This is the program to execute for the secured connection. ("ssh" or -S) */
176 char *ssh_program = _PATH_SSH_PROGRAM;
177 
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;
181 
182 /* SFTP copy parameters */
183 size_t sftp_copy_buflen;
184 size_t sftp_nrequests;
185 
186 /* Needed for sftp */
187 volatile sig_atomic_t interrupted = 0;
188 
189 int sftp_glob(struct sftp_conn *, const char *, int,
190     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
191 
192 static void
193 killchild(int signo)
194 {
195 	if (do_cmd_pid > 1) {
196 		kill(do_cmd_pid, signo ? signo : SIGTERM);
197 		(void)waitpid(do_cmd_pid, NULL, 0);
198 	}
199 	if (do_cmd_pid2 > 1) {
200 		kill(do_cmd_pid2, signo ? signo : SIGTERM);
201 		(void)waitpid(do_cmd_pid2, NULL, 0);
202 	}
203 
204 	if (signo)
205 		_exit(1);
206 	exit(1);
207 }
208 
209 static void
210 suspone(int pid, int signo)
211 {
212 	int status;
213 
214 	if (pid > 1) {
215 		kill(pid, signo);
216 		while (waitpid(pid, &status, WUNTRACED) == -1 &&
217 		    errno == EINTR)
218 			;
219 	}
220 }
221 
222 static void
223 suspchild(int signo)
224 {
225 	suspone(do_cmd_pid, signo);
226 	suspone(do_cmd_pid2, signo);
227 	kill(getpid(), SIGSTOP);
228 }
229 
230 static int
231 do_local_cmd(arglist *a)
232 {
233 	u_int i;
234 	int status;
235 	pid_t pid;
236 
237 	if (a->num == 0)
238 		fatal("do_local_cmd: no arguments");
239 
240 	if (verbose_mode) {
241 		fprintf(stderr, "Executing:");
242 		for (i = 0; i < a->num; i++)
243 			fmprintf(stderr, " %s", a->list[i]);
244 		fprintf(stderr, "\n");
245 	}
246 	if ((pid = fork()) == -1)
247 		fatal("do_local_cmd: fork: %s", strerror(errno));
248 
249 	if (pid == 0) {
250 		execvp(a->list[0], a->list);
251 		perror(a->list[0]);
252 		exit(1);
253 	}
254 
255 	do_cmd_pid = pid;
256 	ssh_signal(SIGTERM, killchild);
257 	ssh_signal(SIGINT, killchild);
258 	ssh_signal(SIGHUP, killchild);
259 
260 	while (waitpid(pid, &status, 0) == -1)
261 		if (errno != EINTR)
262 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
263 
264 	do_cmd_pid = -1;
265 
266 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
267 		return (-1);
268 
269 	return (0);
270 }
271 
272 /*
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.
276  */
277 
278 int
279 do_cmd(char *program, char *host, char *remuser, int port, int subsystem,
280     char *cmd, int *fdin, int *fdout, pid_t *pid)
281 {
282 #ifdef USE_PIPES
283 	int pin[2], pout[2];
284 #else
285 	int sv[2];
286 #endif
287 
288 	if (verbose_mode)
289 		fmprintf(stderr,
290 		    "Executing: program %s host %s, user %s, command %s\n",
291 		    program, host,
292 		    remuser ? remuser : "(unspecified)", cmd);
293 
294 	if (port == -1)
295 		port = sshport;
296 
297 #ifdef USE_PIPES
298 	if (pipe(pin) == -1 || pipe(pout) == -1)
299 		fatal("pipe: %s", strerror(errno));
300 #else
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));
304 #endif
305 
306 	ssh_signal(SIGTSTP, suspchild);
307 	ssh_signal(SIGTTIN, suspchild);
308 	ssh_signal(SIGTTOU, suspchild);
309 
310 	/* Fork a child to execute the command on the remote host using ssh. */
311 	*pid = fork();
312 	switch (*pid) {
313 	case -1:
314 		fatal("fork: %s", strerror(errno));
315 	case 0:
316 		/* Child. */
317 #ifdef USE_PIPES
318 		if (dup2(pin[0], STDIN_FILENO) == -1 ||
319 		    dup2(pout[1], STDOUT_FILENO) == -1) {
320 			error("dup2: %s", strerror(errno));
321 			_exit(1);
322 		}
323 		close(pin[0]);
324 		close(pin[1]);
325 		close(pout[0]);
326 		close(pout[1]);
327 #else
328 		if (dup2(sv[0], STDIN_FILENO) == -1 ||
329 		    dup2(sv[0], STDOUT_FILENO) == -1) {
330 			error("dup2: %s", strerror(errno));
331 			_exit(1);
332 		}
333 		close(sv[0]);
334 		close(sv[1]);
335 #endif
336 		replacearg(&args, 0, "%s", program);
337 		if (port != -1) {
338 			addargs(&args, "-p");
339 			addargs(&args, "%d", port);
340 		}
341 		if (remuser != NULL) {
342 			addargs(&args, "-l");
343 			addargs(&args, "%s", remuser);
344 		}
345 		if (subsystem)
346 			addargs(&args, "-s");
347 		addargs(&args, "--");
348 		addargs(&args, "%s", host);
349 		addargs(&args, "%s", cmd);
350 
351 		execvp(program, args.list);
352 		perror(program);
353 		_exit(1);
354 	default:
355 		/* Parent.  Close the other side, and return the local side. */
356 #ifdef USE_PIPES
357 		close(pin[0]);
358 		close(pout[1]);
359 		*fdout = pin[1];
360 		*fdin = pout[0];
361 #else
362 		close(sv[0]);
363 		*fdin = sv[1];
364 		*fdout = sv[1];
365 #endif
366 		ssh_signal(SIGTERM, killchild);
367 		ssh_signal(SIGINT, killchild);
368 		ssh_signal(SIGHUP, killchild);
369 		return 0;
370 	}
371 }
372 
373 /*
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.
377  */
378 int
379 do_cmd2(char *host, char *remuser, int port, char *cmd,
380     int fdin, int fdout)
381 {
382 	int status;
383 	pid_t pid;
384 
385 	if (verbose_mode)
386 		fmprintf(stderr,
387 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
388 		    ssh_program, host,
389 		    remuser ? remuser : "(unspecified)", cmd);
390 
391 	if (port == -1)
392 		port = sshport;
393 
394 	/* Fork a child to execute the command on the remote host using ssh. */
395 	pid = fork();
396 	if (pid == 0) {
397 		if (dup2(fdin, 0) == -1)
398 			perror("dup2");
399 		if (dup2(fdout, 1) == -1)
400 			perror("dup2");
401 
402 		replacearg(&args, 0, "%s", ssh_program);
403 		if (port != -1) {
404 			addargs(&args, "-p");
405 			addargs(&args, "%d", port);
406 		}
407 		if (remuser != NULL) {
408 			addargs(&args, "-l");
409 			addargs(&args, "%s", remuser);
410 		}
411 		addargs(&args, "-oBatchMode=yes");
412 		addargs(&args, "--");
413 		addargs(&args, "%s", host);
414 		addargs(&args, "%s", cmd);
415 
416 		execvp(ssh_program, args.list);
417 		perror(ssh_program);
418 		exit(1);
419 	} else if (pid == -1) {
420 		fatal("fork: %s", strerror(errno));
421 	}
422 	while (waitpid(pid, &status, 0) == -1)
423 		if (errno != EINTR)
424 			fatal("do_cmd2: waitpid: %s", strerror(errno));
425 	return 0;
426 }
427 
428 typedef struct {
429 	size_t cnt;
430 	char *buf;
431 } BUF;
432 
433 BUF *allocbuf(BUF *, int, int);
434 void lostconn(int);
435 int okname(char *);
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 *);
442 
443 struct passwd *pwd;
444 uid_t userid;
445 int errs, remin, remout, remin2, remout2;
446 int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
447 
448 #define	CMDNEEDS	64
449 char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
450 
451 enum scp_mode_e {
452 	MODE_SCP,
453 	MODE_SFTP
454 };
455 
456 int response(void);
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);
462 void usage(void);
463 
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 *,
467     char *, char *);
468 
469 int
470 main(int argc, char **argv)
471 {
472 	int ch, fflag, tflag, status, r, n;
473 	char **newargv, *argv0;
474 	const char *errstr;
475 	extern char *optarg;
476 	extern int optind;
477 	enum scp_mode_e mode = MODE_SFTP;
478 	char *sftp_direct = NULL;
479 	long long llv;
480 
481 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
482 	sanitise_stdfd();
483 
484 	msetlocale();
485 
486 	/* Copy argv, because we modify it */
487 	argv0 = argv[0];
488 	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
489 	for (n = 0; n < argc; n++)
490 		newargv[n] = xstrdup(argv[n]);
491 	argv = newargv;
492 
493 	__progname = ssh_get_progname(argv[0]);
494 
495 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
496 
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");
506 
507 	fflag = Tflag = tflag = 0;
508 	while ((ch = getopt(argc, argv,
509 	    "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:X:")) != -1) {
510 		switch (ch) {
511 		/* User-visible flags. */
512 		case '1':
513 			fatal("SSH protocol v.1 is no longer supported");
514 			break;
515 		case '2':
516 			/* Ignored */
517 			break;
518 		case 'A':
519 		case '4':
520 		case '6':
521 		case 'C':
522 			addargs(&args, "-%c", ch);
523 			addargs(&remote_remote_args, "-%c", ch);
524 			break;
525 		case 'D':
526 			sftp_direct = optarg;
527 			break;
528 		case '3':
529 			throughlocal = 1;
530 			break;
531 		case 'R':
532 			throughlocal = 0;
533 			break;
534 		case 'o':
535 		case 'c':
536 		case 'i':
537 		case 'F':
538 		case 'J':
539 			addargs(&remote_remote_args, "-%c", ch);
540 			addargs(&remote_remote_args, "%s", optarg);
541 			addargs(&args, "-%c", ch);
542 			addargs(&args, "%s", optarg);
543 			break;
544 		case 'O':
545 			mode = MODE_SCP;
546 			break;
547 		case 's':
548 			mode = MODE_SFTP;
549 			break;
550 		case 'P':
551 			sshport = a2port(optarg);
552 			if (sshport <= 0)
553 				fatal("bad port \"%s\"\n", optarg);
554 			break;
555 		case 'B':
556 			addargs(&remote_remote_args, "-oBatchmode=yes");
557 			addargs(&args, "-oBatchmode=yes");
558 			break;
559 		case 'l':
560 			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
561 			    &errstr);
562 			if (errstr != NULL)
563 				usage();
564 			limit_kbps *= 1024; /* kbps */
565 			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
566 			break;
567 		case 'p':
568 			pflag = 1;
569 			break;
570 		case 'r':
571 			iamrecursive = 1;
572 			break;
573 		case 'S':
574 			ssh_program = xstrdup(optarg);
575 			break;
576 		case 'v':
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)
582 				log_level++;
583 			verbose_mode = 1;
584 			break;
585 		case 'q':
586 			addargs(&args, "-q");
587 			addargs(&remote_remote_args, "-q");
588 			showprogress = 0;
589 			break;
590 		case 'X':
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)) {
595 					r = -1;
596 					errno = EINVAL;
597 				}
598 				if (r == -1) {
599 					fatal("Invalid buffer size \"%s\": %s",
600 					     optarg + 7, strerror(errno));
601 				}
602 				sftp_copy_buflen = (size_t)llv;
603 			} else if (strncmp(optarg, "nrequests=", 10) == 0) {
604 				llv = strtonum(optarg + 10, 1, 256 * 1024,
605 				    &errstr);
606 				if (errstr != NULL) {
607 					fatal("Invalid number of requests "
608 					    "\"%s\": %s", optarg + 10, errstr);
609 				}
610 				sftp_nrequests = (size_t)llv;
611 			} else {
612 				fatal("Invalid -X option");
613 			}
614 			break;
615 
616 		/* Server options. */
617 		case 'd':
618 			targetshouldbedirectory = 1;
619 			break;
620 		case 'f':	/* "from" */
621 			iamremote = 1;
622 			fflag = 1;
623 			break;
624 		case 't':	/* "to" */
625 			iamremote = 1;
626 			tflag = 1;
627 #ifdef HAVE_CYGWIN
628 			setmode(0, O_BINARY);
629 #endif
630 			break;
631 		case 'T':
632 			Tflag = 1;
633 			break;
634 		default:
635 			usage();
636 		}
637 	}
638 	argc -= optind;
639 	argv += optind;
640 
641 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
642 
643 	/* Do this last because we want the user to be able to override it */
644 	addargs(&args, "-oForwardAgent=no");
645 
646 	if (iamremote)
647 		mode = MODE_SCP;
648 
649 	if ((pwd = getpwuid(userid = getuid())) == NULL)
650 		fatal("unknown user %u", (u_int) userid);
651 
652 	if (!isatty(STDOUT_FILENO))
653 		showprogress = 0;
654 
655 	if (pflag) {
656 		/* Cannot pledge: -p allows setuid/setgid files... */
657 	} else {
658 		if (pledge("stdio rpath wpath cpath fattr tty proc exec",
659 		    NULL) == -1) {
660 			perror("pledge");
661 			exit(1);
662 		}
663 	}
664 
665 	remin = STDIN_FILENO;
666 	remout = STDOUT_FILENO;
667 
668 	if (fflag) {
669 		/* Follow "protocol", send data. */
670 		(void) response();
671 		source(argc, argv);
672 		exit(errs != 0);
673 	}
674 	if (tflag) {
675 		/* Receive data. */
676 		sink(argc, argv, NULL);
677 		exit(errs != 0);
678 	}
679 	if (argc < 2)
680 		usage();
681 	if (argc > 2)
682 		targetshouldbedirectory = 1;
683 
684 	remin = remout = -1;
685 	do_cmd_pid = -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" : "");
691 
692 	(void) ssh_signal(SIGPIPE, lostconn);
693 
694 	if (colon(argv[argc - 1]))	/* Dest is remote host. */
695 		toremote(argc, argv, mode, sftp_direct);
696 	else {
697 		if (targetshouldbedirectory)
698 			verifydir(argv[argc - 1]);
699 		tolocal(argc, argv, mode, sftp_direct);	/* Dest is local host. */
700 	}
701 	/*
702 	 * Finally check the exit status of the ssh process, if one was forked
703 	 * and no error has occurred yet
704 	 */
705 	if (do_cmd_pid != -1 && (mode == MODE_SFTP || errs == 0)) {
706 		if (remin != -1)
707 		    (void) close(remin);
708 		if (remout != -1)
709 		    (void) close(remout);
710 		if (waitpid(do_cmd_pid, &status, 0) == -1)
711 			errs = 1;
712 		else {
713 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
714 				errs = 1;
715 		}
716 	}
717 	exit(errs != 0);
718 }
719 
720 /* Callback from atomicio6 to update progress meter and limit bandwidth */
721 static int
722 scpio(void *_cnt, size_t s)
723 {
724 	off_t *cnt = (off_t *)_cnt;
725 
726 	*cnt += s;
727 	refresh_progress_meter(0);
728 	if (limit_kbps > 0)
729 		bandwidth_limit(&bwlimit, s);
730 	return 0;
731 }
732 
733 static int
734 do_times(int fd, int verb, const struct stat *sb)
735 {
736 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
737 	char buf[(20 + 7 + 2) * 2 + 2];
738 
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));
742 	if (verb) {
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);
746 	}
747 	(void) atomicio(vwrite, fd, buf, strlen(buf));
748 	return (response());
749 }
750 
751 static int
752 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
753     char **pathp)
754 {
755 	int r;
756 
757 	r = parse_uri("scp", uri, userp, hostp, portp, pathp);
758 	if (r == 0 && *pathp == NULL)
759 		*pathp = xstrdup(".");
760 	return r;
761 }
762 
763 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
764 static int
765 append(char *cp, char ***ap, size_t *np)
766 {
767 	char **tmp;
768 
769 	if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
770 		return -1;
771 	tmp[(*np)] = cp;
772 	(*np)++;
773 	*ap = tmp;
774 	return 0;
775 }
776 
777 /*
778  * Finds the start and end of the first brace pair in the pattern.
779  * returns 0 on success or -1 for invalid patterns.
780  */
781 static int
782 find_brace(const char *pattern, int *startp, int *endp)
783 {
784 	int i;
785 	int in_bracket, brace_level;
786 
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]) {
791 		case '\\':
792 			/* skip next character */
793 			if (pattern[i + 1] != '\0')
794 				i++;
795 			break;
796 		case '[':
797 			in_bracket = 1;
798 			break;
799 		case ']':
800 			in_bracket = 0;
801 			break;
802 		case '{':
803 			if (in_bracket)
804 				break;
805 			if (pattern[i + 1] == '}') {
806 				/* Protect a single {}, for find(1), like csh */
807 				i++; /* skip */
808 				break;
809 			}
810 			if (*startp == -1)
811 				*startp = i;
812 			brace_level++;
813 			break;
814 		case '}':
815 			if (in_bracket)
816 				break;
817 			if (*startp < 0) {
818 				/* Unbalanced brace */
819 				return -1;
820 			}
821 			if (--brace_level <= 0)
822 				*endp = i;
823 			break;
824 		}
825 	}
826 	/* unbalanced brackets/braces */
827 	if (*endp < 0 && (*startp >= 0 || in_bracket))
828 		return -1;
829 	return 0;
830 }
831 
832 /*
833  * Assembles and records a successfully-expanded pattern, returns -1 on
834  * alloc failure.
835  */
836 static int
837 emit_expansion(const char *pattern, int brace_start, int brace_end,
838     int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
839 {
840 	char *cp;
841 	size_t pattern_len;
842 	int o = 0, tail_len;
843 
844 	if ((pattern_len = strlen(pattern)) == 0 || pattern_len >= INT_MAX)
845 		return -1;
846 
847 	tail_len = strlen(pattern + brace_end + 1);
848 	if ((cp = malloc(brace_start + (sel_end - sel_start) +
849 	    tail_len + 1)) == NULL)
850 		return -1;
851 
852 	/* Pattern before initial brace */
853 	if (brace_start > 0) {
854 		memcpy(cp, pattern, brace_start);
855 		o = brace_start;
856 	}
857 	/* Current braced selection */
858 	if (sel_end - sel_start > 0) {
859 		memcpy(cp + o, pattern + sel_start,
860 		    sel_end - sel_start);
861 		o += sel_end - sel_start;
862 	}
863 	/* Remainder of pattern after closing brace */
864 	if (tail_len > 0) {
865 		memcpy(cp + o, pattern + brace_end + 1, tail_len);
866 		o += tail_len;
867 	}
868 	cp[o] = '\0';
869 	if (append(cp, patternsp, npatternsp) != 0) {
870 		free(cp);
871 		return -1;
872 	}
873 	return 0;
874 }
875 
876 /*
877  * Expand the first encountered brace in pattern, appending the expanded
878  * patterns it yielded to the *patternsp array.
879  *
880  * Returns 0 on success or -1 on allocation failure.
881  *
882  * Signals whether expansion was performed via *expanded and whether
883  * pattern was invalid via *invalid.
884  */
885 static int
886 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
887     int *expanded, int *invalid)
888 {
889 	int i;
890 	int in_bracket, brace_start, brace_end, brace_level;
891 	int sel_start, sel_end;
892 
893 	*invalid = *expanded = 0;
894 
895 	if (find_brace(pattern, &brace_start, &brace_end) != 0) {
896 		*invalid = 1;
897 		return 0;
898 	} else if (brace_start == -1)
899 		return 0;
900 
901 	in_bracket = brace_level = 0;
902 	for (i = sel_start = brace_start + 1; i < brace_end; i++) {
903 		switch (pattern[i]) {
904 		case '{':
905 			if (in_bracket)
906 				break;
907 			brace_level++;
908 			break;
909 		case '}':
910 			if (in_bracket)
911 				break;
912 			brace_level--;
913 			break;
914 		case '[':
915 			in_bracket = 1;
916 			break;
917 		case ']':
918 			in_bracket = 0;
919 			break;
920 		case '\\':
921 			if (i < brace_end - 1)
922 				i++; /* skip */
923 			break;
924 		}
925 		if (pattern[i] == ',' || i == brace_end - 1) {
926 			if (in_bracket || brace_level > 0)
927 				continue;
928 			/* End of a selection, emit an expanded pattern */
929 
930 			/* Adjust end index for last selection */
931 			sel_end = (i == brace_end - 1) ? brace_end : i;
932 			if (emit_expansion(pattern, brace_start, brace_end,
933 			    sel_start, sel_end, patternsp, npatternsp) != 0)
934 				return -1;
935 			/* move on to the next selection */
936 			sel_start = i + 1;
937 			continue;
938 		}
939 	}
940 	if (in_bracket || brace_level > 0) {
941 		*invalid = 1;
942 		return 0;
943 	}
944 	/* success */
945 	*expanded = 1;
946 	return 0;
947 }
948 
949 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
950 static int
951 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
952 {
953 	char *cp, *cp2, **active = NULL, **done = NULL;
954 	size_t i, nactive = 0, ndone = 0;
955 	int ret = -1, invalid = 0, expanded = 0;
956 
957 	*patternsp = NULL;
958 	*npatternsp = 0;
959 
960 	/* Start the worklist with the original pattern */
961 	if ((cp = strdup(pattern)) == NULL)
962 		return -1;
963 	if (append(cp, &active, &nactive) != 0) {
964 		free(cp);
965 		return -1;
966 	}
967 	while (nactive > 0) {
968 		cp = active[nactive - 1];
969 		nactive--;
970 		if (brace_expand_one(cp, &active, &nactive,
971 		    &expanded, &invalid) == -1) {
972 			free(cp);
973 			goto fail;
974 		}
975 		if (invalid)
976 			fatal_f("invalid brace pattern \"%s\"", cp);
977 		if (expanded) {
978 			/*
979 			 * Current entry expanded to new entries on the
980 			 * active list; discard the progenitor pattern.
981 			 */
982 			free(cp);
983 			continue;
984 		}
985 		/*
986 		 * Pattern did not expand; append the finename component to
987 		 * the completed list
988 		 */
989 		if ((cp2 = strrchr(cp, '/')) != NULL)
990 			*cp2++ = '\0';
991 		else
992 			cp2 = cp;
993 		if (append(xstrdup(cp2), &done, &ndone) != 0) {
994 			free(cp);
995 			goto fail;
996 		}
997 		free(cp);
998 	}
999 	/* success */
1000 	*patternsp = done;
1001 	*npatternsp = ndone;
1002 	done = NULL;
1003 	ndone = 0;
1004 	ret = 0;
1005  fail:
1006 	for (i = 0; i < nactive; i++)
1007 		free(active[i]);
1008 	free(active);
1009 	for (i = 0; i < ndone; i++)
1010 		free(done[i]);
1011 	free(done);
1012 	return ret;
1013 }
1014 
1015 static struct sftp_conn *
1016 do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
1017    int *reminp, int *remoutp, int *pidp)
1018 {
1019 	if (sftp_direct == NULL) {
1020 		if (do_cmd(ssh_program, host, user, port, 1, "sftp",
1021 		    reminp, remoutp, pidp) < 0)
1022 			return NULL;
1023 
1024 	} else {
1025 		freeargs(&args);
1026 		addargs(&args, "sftp-server");
1027 		if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
1028 		    reminp, remoutp, pidp) < 0)
1029 			return NULL;
1030 	}
1031 	return sftp_init(*reminp, *remoutp,
1032 	    sftp_copy_buflen, sftp_nrequests, limit_kbps);
1033 }
1034 
1035 void
1036 toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1037 {
1038 	char *suser = NULL, *host = NULL, *src = NULL;
1039 	char *bp, *tuser, *thost, *targ;
1040 	int sport = -1, tport = -1;
1041 	struct sftp_conn *conn = NULL, *conn2 = NULL;
1042 	arglist alist;
1043 	int i, r, status;
1044 	struct stat sb;
1045 	u_int j;
1046 
1047 	memset(&alist, '\0', sizeof(alist));
1048 	alist.list = NULL;
1049 
1050 	/* Parse target */
1051 	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
1052 	if (r == -1) {
1053 		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
1054 		++errs;
1055 		goto out;
1056 	}
1057 	if (r != 0) {
1058 		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
1059 		    &targ) == -1) {
1060 			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
1061 			++errs;
1062 			goto out;
1063 		}
1064 	}
1065 
1066 	/* Parse source files */
1067 	for (i = 0; i < argc - 1; i++) {
1068 		free(suser);
1069 		free(host);
1070 		free(src);
1071 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1072 		if (r == -1) {
1073 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1074 			++errs;
1075 			continue;
1076 		}
1077 		if (r != 0) {
1078 			parse_user_host_path(argv[i], &suser, &host, &src);
1079 		}
1080 		if (suser != NULL && !okname(suser)) {
1081 			++errs;
1082 			continue;
1083 		}
1084 		if (host && throughlocal) {	/* extended remote to remote */
1085 			if (mode == MODE_SFTP) {
1086 				if (remin == -1) {
1087 					/* Connect to dest now */
1088 					conn = do_sftp_connect(thost, tuser,
1089 					    tport, sftp_direct,
1090 					    &remin, &remout, &do_cmd_pid);
1091 					if (conn == NULL) {
1092 						fatal("Unable to open "
1093 						    "destination connection");
1094 					}
1095 					debug3_f("origin in %d out %d pid %ld",
1096 					    remin, remout, (long)do_cmd_pid);
1097 				}
1098 				/*
1099 				 * XXX remember suser/host/sport and only
1100 				 * reconnect if they change between arguments.
1101 				 * would save reconnections for cases like
1102 				 * scp -3 hosta:/foo hosta:/bar hostb:
1103 				 */
1104 				/* Connect to origin now */
1105 				conn2 = do_sftp_connect(host, suser,
1106 				    sport, sftp_direct,
1107 				    &remin2, &remout2, &do_cmd_pid2);
1108 				if (conn2 == NULL) {
1109 					fatal("Unable to open "
1110 					    "source connection");
1111 				}
1112 				debug3_f("destination in %d out %d pid %ld",
1113 				    remin2, remout2, (long)do_cmd_pid2);
1114 				throughlocal_sftp(conn2, conn, src, targ);
1115 				(void) close(remin2);
1116 				(void) close(remout2);
1117 				remin2 = remout2 = -1;
1118 				if (waitpid(do_cmd_pid2, &status, 0) == -1)
1119 					++errs;
1120 				else if (!WIFEXITED(status) ||
1121 				    WEXITSTATUS(status) != 0)
1122 					++errs;
1123 				do_cmd_pid2 = -1;
1124 				continue;
1125 			} else {
1126 				xasprintf(&bp, "%s -f %s%s", cmd,
1127 				    *src == '-' ? "-- " : "", src);
1128 				if (do_cmd(ssh_program, host, suser, sport, 0,
1129 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1130 					exit(1);
1131 				free(bp);
1132 				xasprintf(&bp, "%s -t %s%s", cmd,
1133 				    *targ == '-' ? "-- " : "", targ);
1134 				if (do_cmd2(thost, tuser, tport, bp,
1135 				    remin, remout) < 0)
1136 					exit(1);
1137 				free(bp);
1138 				(void) close(remin);
1139 				(void) close(remout);
1140 				remin = remout = -1;
1141 			}
1142 		} else if (host) {	/* standard remote to remote */
1143 			/*
1144 			 * Second remote user is passed to first remote side
1145 			 * via scp command-line. Ensure it contains no obvious
1146 			 * shell characters.
1147 			 */
1148 			if (tuser != NULL && !okname(tuser)) {
1149 				++errs;
1150 				continue;
1151 			}
1152 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
1153 				/* This would require the remote support URIs */
1154 				fatal("target port not supported with two "
1155 				    "remote hosts and the -R option");
1156 			}
1157 
1158 			freeargs(&alist);
1159 			addargs(&alist, "%s", ssh_program);
1160 			addargs(&alist, "-x");
1161 			addargs(&alist, "-oClearAllForwardings=yes");
1162 			addargs(&alist, "-n");
1163 			for (j = 0; j < remote_remote_args.num; j++) {
1164 				addargs(&alist, "%s",
1165 				    remote_remote_args.list[j]);
1166 			}
1167 
1168 			if (sport != -1) {
1169 				addargs(&alist, "-p");
1170 				addargs(&alist, "%d", sport);
1171 			}
1172 			if (suser) {
1173 				addargs(&alist, "-l");
1174 				addargs(&alist, "%s", suser);
1175 			}
1176 			addargs(&alist, "--");
1177 			addargs(&alist, "%s", host);
1178 			addargs(&alist, "%s", cmd);
1179 			addargs(&alist, "%s", src);
1180 			addargs(&alist, "%s%s%s:%s",
1181 			    tuser ? tuser : "", tuser ? "@" : "",
1182 			    thost, targ);
1183 			if (do_local_cmd(&alist) != 0)
1184 				errs = 1;
1185 		} else {	/* local to remote */
1186 			if (mode == MODE_SFTP) {
1187 				/* no need to glob: already done by shell */
1188 				if (stat(argv[i], &sb) != 0) {
1189 					fatal("stat local \"%s\": %s", argv[i],
1190 					    strerror(errno));
1191 				}
1192 				if (remin == -1) {
1193 					/* Connect to remote now */
1194 					conn = do_sftp_connect(thost, tuser,
1195 					    tport, sftp_direct,
1196 					    &remin, &remout, &do_cmd_pid);
1197 					if (conn == NULL) {
1198 						fatal("Unable to open sftp "
1199 						    "connection");
1200 					}
1201 				}
1202 
1203 				/* The protocol */
1204 				source_sftp(1, argv[i], targ, conn);
1205 				continue;
1206 			}
1207 			/* SCP */
1208 			if (remin == -1) {
1209 				xasprintf(&bp, "%s -t %s%s", cmd,
1210 				    *targ == '-' ? "-- " : "", targ);
1211 				if (do_cmd(ssh_program, thost, tuser, tport, 0,
1212 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1213 					exit(1);
1214 				if (response() < 0)
1215 					exit(1);
1216 				free(bp);
1217 			}
1218 			source(1, argv + i);
1219 		}
1220 	}
1221 out:
1222 	if (mode == MODE_SFTP)
1223 		free(conn);
1224 	free(tuser);
1225 	free(thost);
1226 	free(targ);
1227 	free(suser);
1228 	free(host);
1229 	free(src);
1230 }
1231 
1232 void
1233 tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1234 {
1235 	char *bp, *host = NULL, *src = NULL, *suser = NULL;
1236 	arglist alist;
1237 	struct sftp_conn *conn = NULL;
1238 	int i, r, sport = -1;
1239 
1240 	memset(&alist, '\0', sizeof(alist));
1241 	alist.list = NULL;
1242 
1243 	for (i = 0; i < argc - 1; i++) {
1244 		free(suser);
1245 		free(host);
1246 		free(src);
1247 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1248 		if (r == -1) {
1249 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1250 			++errs;
1251 			continue;
1252 		}
1253 		if (r != 0)
1254 			parse_user_host_path(argv[i], &suser, &host, &src);
1255 		if (suser != NULL && !okname(suser)) {
1256 			++errs;
1257 			continue;
1258 		}
1259 		if (!host) {	/* Local to local. */
1260 			freeargs(&alist);
1261 			addargs(&alist, "%s", _PATH_CP);
1262 			if (iamrecursive)
1263 				addargs(&alist, "-r");
1264 			if (pflag)
1265 				addargs(&alist, "-p");
1266 			addargs(&alist, "--");
1267 			addargs(&alist, "%s", argv[i]);
1268 			addargs(&alist, "%s", argv[argc-1]);
1269 			if (do_local_cmd(&alist))
1270 				++errs;
1271 			continue;
1272 		}
1273 		/* Remote to local. */
1274 		if (mode == MODE_SFTP) {
1275 			conn = do_sftp_connect(host, suser, sport,
1276 			    sftp_direct, &remin, &remout, &do_cmd_pid);
1277 			if (conn == NULL) {
1278 				error("sftp connection failed");
1279 				++errs;
1280 				continue;
1281 			}
1282 
1283 			/* The protocol */
1284 			sink_sftp(1, argv[argc - 1], src, conn);
1285 
1286 			free(conn);
1287 			(void) close(remin);
1288 			(void) close(remout);
1289 			remin = remout = -1;
1290 			continue;
1291 		}
1292 		/* SCP */
1293 		xasprintf(&bp, "%s -f %s%s",
1294 		    cmd, *src == '-' ? "-- " : "", src);
1295 		if (do_cmd(ssh_program, host, suser, sport, 0, bp,
1296 		    &remin, &remout, &do_cmd_pid) < 0) {
1297 			free(bp);
1298 			++errs;
1299 			continue;
1300 		}
1301 		free(bp);
1302 		sink(1, argv + argc - 1, src);
1303 		(void) close(remin);
1304 		remin = remout = -1;
1305 	}
1306 	free(suser);
1307 	free(host);
1308 	free(src);
1309 }
1310 
1311 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1312 static char *
1313 prepare_remote_path(struct sftp_conn *conn, const char *path)
1314 {
1315 	size_t nslash;
1316 
1317 	/* Handle ~ prefixed paths */
1318 	if (*path == '\0' || strcmp(path, "~") == 0)
1319 		return xstrdup(".");
1320 	if (*path != '~')
1321 		return xstrdup(path);
1322 	if (strncmp(path, "~/", 2) == 0) {
1323 		if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
1324 			return xstrdup(".");
1325 		return xstrdup(path + 2 + nslash);
1326 	}
1327 	if (sftp_can_expand_path(conn))
1328 		return sftp_expand_path(conn, path);
1329 	/* No protocol extension */
1330 	error("server expand-path extension is required "
1331 	    "for ~user paths in SFTP mode");
1332 	return NULL;
1333 }
1334 
1335 void
1336 source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
1337 {
1338 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1339 	int src_is_dir, target_is_dir;
1340 	Attrib a;
1341 	struct stat st;
1342 
1343 	memset(&a, '\0', sizeof(a));
1344 	if (stat(src, &st) != 0)
1345 		fatal("stat local \"%s\": %s", src, strerror(errno));
1346 	src_is_dir = S_ISDIR(st.st_mode);
1347 	if ((filename = basename(src)) == NULL)
1348 		fatal("basename \"%s\": %s", src, strerror(errno));
1349 
1350 	/*
1351 	 * No need to glob here - the local shell already took care of
1352 	 * the expansions
1353 	 */
1354 	if ((target = prepare_remote_path(conn, targ)) == NULL)
1355 		cleanup_exit(255);
1356 	target_is_dir = sftp_remote_is_dir(conn, target);
1357 	if (targetshouldbedirectory && !target_is_dir) {
1358 		debug("target directory \"%s\" does not exist", target);
1359 		a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
1360 		a.perm = st.st_mode | 0700; /* ensure writable */
1361 		if (sftp_mkdir(conn, target, &a, 1) != 0)
1362 			cleanup_exit(255); /* error already logged */
1363 		target_is_dir = 1;
1364 	}
1365 	if (target_is_dir)
1366 		abs_dst = sftp_path_append(target, filename);
1367 	else {
1368 		abs_dst = target;
1369 		target = NULL;
1370 	}
1371 	debug3_f("copying local %s to remote %s", src, abs_dst);
1372 
1373 	if (src_is_dir && iamrecursive) {
1374 		if (sftp_upload_dir(conn, src, abs_dst, pflag,
1375 		    SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
1376 			error("failed to upload directory %s to %s", src, targ);
1377 			errs = 1;
1378 		}
1379 	} else if (sftp_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
1380 		error("failed to upload file %s to %s", src, targ);
1381 		errs = 1;
1382 	}
1383 
1384 	free(abs_dst);
1385 	free(target);
1386 }
1387 
1388 void
1389 source(int argc, char **argv)
1390 {
1391 	struct stat stb;
1392 	static BUF buffer;
1393 	BUF *bp;
1394 	off_t i, statbytes;
1395 	size_t amt, nr;
1396 	int fd = -1, haderr, indx;
1397 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1398 	int len;
1399 
1400 	for (indx = 0; indx < argc; ++indx) {
1401 		name = argv[indx];
1402 		statbytes = 0;
1403 		len = strlen(name);
1404 		while (len > 1 && name[len-1] == '/')
1405 			name[--len] = '\0';
1406 		if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1407 			goto syserr;
1408 		if (strchr(name, '\n') != NULL) {
1409 			strnvis(encname, name, sizeof(encname), VIS_NL);
1410 			name = encname;
1411 		}
1412 		if (fstat(fd, &stb) == -1) {
1413 syserr:			run_err("%s: %s", name, strerror(errno));
1414 			goto next;
1415 		}
1416 		if (stb.st_size < 0) {
1417 			run_err("%s: %s", name, "Negative file size");
1418 			goto next;
1419 		}
1420 		unset_nonblock(fd);
1421 		switch (stb.st_mode & S_IFMT) {
1422 		case S_IFREG:
1423 			break;
1424 		case S_IFDIR:
1425 			if (iamrecursive) {
1426 				rsource(name, &stb);
1427 				goto next;
1428 			}
1429 			/* FALLTHROUGH */
1430 		default:
1431 			run_err("%s: not a regular file", name);
1432 			goto next;
1433 		}
1434 		if ((last = strrchr(name, '/')) == NULL)
1435 			last = name;
1436 		else
1437 			++last;
1438 		curfile = last;
1439 		if (pflag) {
1440 			if (do_times(remout, verbose_mode, &stb) < 0)
1441 				goto next;
1442 		}
1443 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1444 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1445 		    (u_int) (stb.st_mode & FILEMODEMASK),
1446 		    (long long)stb.st_size, last);
1447 		if (verbose_mode)
1448 			fmprintf(stderr, "Sending file modes: %s", buf);
1449 		(void) atomicio(vwrite, remout, buf, strlen(buf));
1450 		if (response() < 0)
1451 			goto next;
1452 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1453 next:			if (fd != -1) {
1454 				(void) close(fd);
1455 				fd = -1;
1456 			}
1457 			continue;
1458 		}
1459 		if (showprogress)
1460 			start_progress_meter(curfile, stb.st_size, &statbytes);
1461 		set_nonblock(remout);
1462 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1463 			amt = bp->cnt;
1464 			if (i + (off_t)amt > stb.st_size)
1465 				amt = stb.st_size - i;
1466 			if (!haderr) {
1467 				if ((nr = atomicio(read, fd,
1468 				    bp->buf, amt)) != amt) {
1469 					haderr = errno;
1470 					memset(bp->buf + nr, 0, amt - nr);
1471 				}
1472 			}
1473 			/* Keep writing after error to retain sync */
1474 			if (haderr) {
1475 				(void)atomicio(vwrite, remout, bp->buf, amt);
1476 				memset(bp->buf, 0, amt);
1477 				continue;
1478 			}
1479 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1480 			    &statbytes) != amt)
1481 				haderr = errno;
1482 		}
1483 		unset_nonblock(remout);
1484 
1485 		if (fd != -1) {
1486 			if (close(fd) == -1 && !haderr)
1487 				haderr = errno;
1488 			fd = -1;
1489 		}
1490 		if (!haderr)
1491 			(void) atomicio(vwrite, remout, "", 1);
1492 		else
1493 			run_err("%s: %s", name, strerror(haderr));
1494 		(void) response();
1495 		if (showprogress)
1496 			stop_progress_meter();
1497 	}
1498 }
1499 
1500 void
1501 rsource(char *name, struct stat *statp)
1502 {
1503 	DIR *dirp;
1504 	struct dirent *dp;
1505 	char *last, *vect[1], path[PATH_MAX];
1506 
1507 	if (!(dirp = opendir(name))) {
1508 		run_err("%s: %s", name, strerror(errno));
1509 		return;
1510 	}
1511 	last = strrchr(name, '/');
1512 	if (last == NULL)
1513 		last = name;
1514 	else
1515 		last++;
1516 	if (pflag) {
1517 		if (do_times(remout, verbose_mode, statp) < 0) {
1518 			closedir(dirp);
1519 			return;
1520 		}
1521 	}
1522 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1523 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1524 	if (verbose_mode)
1525 		fmprintf(stderr, "Entering directory: %s", path);
1526 	(void) atomicio(vwrite, remout, path, strlen(path));
1527 	if (response() < 0) {
1528 		closedir(dirp);
1529 		return;
1530 	}
1531 	while ((dp = readdir(dirp)) != NULL) {
1532 		if (dp->d_ino == 0)
1533 			continue;
1534 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1535 			continue;
1536 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1537 			run_err("%s/%s: name too long", name, dp->d_name);
1538 			continue;
1539 		}
1540 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1541 		vect[0] = path;
1542 		source(1, vect);
1543 	}
1544 	(void) closedir(dirp);
1545 	(void) atomicio(vwrite, remout, "E\n", 2);
1546 	(void) response();
1547 }
1548 
1549 void
1550 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
1551 {
1552 	char *abs_src = NULL;
1553 	char *abs_dst = NULL;
1554 	glob_t g;
1555 	char *filename, *tmp = NULL;
1556 	int i, r, err = 0, dst_is_dir;
1557 	struct stat st;
1558 
1559 	memset(&g, 0, sizeof(g));
1560 
1561 	/*
1562 	 * Here, we need remote glob as SFTP can not depend on remote shell
1563 	 * expansions
1564 	 */
1565 	if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
1566 		err = -1;
1567 		goto out;
1568 	}
1569 
1570 	debug3_f("copying remote %s to local %s", abs_src, dst);
1571 	if ((r = sftp_glob(conn, abs_src, GLOB_NOCHECK|GLOB_MARK,
1572 	    NULL, &g)) != 0) {
1573 		if (r == GLOB_NOSPACE)
1574 			error("%s: too many glob matches", src);
1575 		else
1576 			error("%s: %s", src, strerror(ENOENT));
1577 		err = -1;
1578 		goto out;
1579 	}
1580 
1581 	/* Did we actually get any matches back from the glob? */
1582 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
1583 		/*
1584 		 * If nothing matched but a path returned, then it's probably
1585 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
1586 		 * exists so we can give a nice error message early.
1587 		 */
1588 		if (sftp_stat(conn, g.gl_pathv[0], 1, NULL) != 0) {
1589 			error("%s: %s", src, strerror(ENOENT));
1590 			err = -1;
1591 			goto out;
1592 		}
1593 	}
1594 
1595 	if ((r = stat(dst, &st)) != 0)
1596 		debug2_f("stat local \"%s\": %s", dst, strerror(errno));
1597 	dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
1598 
1599 	if (g.gl_matchc > 1 && !dst_is_dir) {
1600 		if (r == 0) {
1601 			error("Multiple files match pattern, but destination "
1602 			    "\"%s\" is not a directory", dst);
1603 			err = -1;
1604 			goto out;
1605 		}
1606 		debug2_f("creating destination \"%s\"", dst);
1607 		if (mkdir(dst, 0777) != 0) {
1608 			error("local mkdir \"%s\": %s", dst, strerror(errno));
1609 			err = -1;
1610 			goto out;
1611 		}
1612 		dst_is_dir = 1;
1613 	}
1614 
1615 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1616 		tmp = xstrdup(g.gl_pathv[i]);
1617 		if ((filename = basename(tmp)) == NULL) {
1618 			error("basename %s: %s", tmp, strerror(errno));
1619 			err = -1;
1620 			goto out;
1621 		}
1622 
1623 		if (dst_is_dir)
1624 			abs_dst = sftp_path_append(dst, filename);
1625 		else
1626 			abs_dst = xstrdup(dst);
1627 
1628 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1629 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1630 			if (sftp_download_dir(conn, g.gl_pathv[i], abs_dst,
1631 			    NULL, pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
1632 				err = -1;
1633 		} else {
1634 			if (sftp_download(conn, g.gl_pathv[i], abs_dst, NULL,
1635 			    pflag, 0, 0, 1) == -1)
1636 				err = -1;
1637 		}
1638 		free(abs_dst);
1639 		abs_dst = NULL;
1640 		free(tmp);
1641 		tmp = NULL;
1642 	}
1643 
1644 out:
1645 	free(abs_src);
1646 	free(tmp);
1647 	globfree(&g);
1648 	if (err == -1)
1649 		errs = 1;
1650 }
1651 
1652 
1653 #define TYPE_OVERFLOW(type, val) \
1654 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
1655 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1656 	 (sizeof(type) != 4 && sizeof(type) != 8))
1657 
1658 void
1659 sink(int argc, char **argv, const char *src)
1660 {
1661 	static BUF buffer;
1662 	struct stat stb;
1663 	BUF *bp;
1664 	off_t i;
1665 	size_t j, count;
1666 	int amt, exists, first, ofd;
1667 	mode_t mode, omode, mask;
1668 	off_t size, statbytes;
1669 	unsigned long long ull;
1670 	int setimes, targisdir, wrerr;
1671 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1672 	char **patterns = NULL;
1673 	size_t n, npatterns = 0;
1674 	struct timeval tv[2];
1675 
1676 #define	atime	tv[0]
1677 #define	mtime	tv[1]
1678 #define	SCREWUP(str)	{ why = str; goto screwup; }
1679 
1680 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1681 		SCREWUP("Unexpected off_t/time_t size");
1682 
1683 	setimes = targisdir = 0;
1684 	mask = umask(0);
1685 	if (!pflag)
1686 		(void) umask(mask);
1687 	if (argc != 1) {
1688 		run_err("ambiguous target");
1689 		exit(1);
1690 	}
1691 	targ = *argv;
1692 	if (targetshouldbedirectory)
1693 		verifydir(targ);
1694 
1695 	(void) atomicio(vwrite, remout, "", 1);
1696 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1697 		targisdir = 1;
1698 	if (src != NULL && !iamrecursive && !Tflag) {
1699 		/*
1700 		 * Prepare to try to restrict incoming filenames to match
1701 		 * the requested destination file glob.
1702 		 */
1703 		if (brace_expand(src, &patterns, &npatterns) != 0)
1704 			fatal_f("could not expand pattern");
1705 	}
1706 	for (first = 1;; first = 0) {
1707 		cp = buf;
1708 		if (atomicio(read, remin, cp, 1) != 1)
1709 			goto done;
1710 		if (*cp++ == '\n')
1711 			SCREWUP("unexpected <newline>");
1712 		do {
1713 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1714 				SCREWUP("lost connection");
1715 			*cp++ = ch;
1716 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1717 		*cp = 0;
1718 		if (verbose_mode)
1719 			fmprintf(stderr, "Sink: %s", buf);
1720 
1721 		if (buf[0] == '\01' || buf[0] == '\02') {
1722 			if (iamremote == 0) {
1723 				(void) snmprintf(visbuf, sizeof(visbuf),
1724 				    NULL, "%s", buf + 1);
1725 				(void) atomicio(vwrite, STDERR_FILENO,
1726 				    visbuf, strlen(visbuf));
1727 			}
1728 			if (buf[0] == '\02')
1729 				exit(1);
1730 			++errs;
1731 			continue;
1732 		}
1733 		if (buf[0] == 'E') {
1734 			(void) atomicio(vwrite, remout, "", 1);
1735 			goto done;
1736 		}
1737 		if (ch == '\n')
1738 			*--cp = 0;
1739 
1740 		cp = buf;
1741 		if (*cp == 'T') {
1742 			setimes++;
1743 			cp++;
1744 			if (!isdigit((unsigned char)*cp))
1745 				SCREWUP("mtime.sec not present");
1746 			ull = strtoull(cp, &cp, 10);
1747 			if (!cp || *cp++ != ' ')
1748 				SCREWUP("mtime.sec not delimited");
1749 			if (TYPE_OVERFLOW(time_t, ull))
1750 				setimes = 0;	/* out of range */
1751 			mtime.tv_sec = ull;
1752 			mtime.tv_usec = strtol(cp, &cp, 10);
1753 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1754 			    mtime.tv_usec > 999999)
1755 				SCREWUP("mtime.usec not delimited");
1756 			if (!isdigit((unsigned char)*cp))
1757 				SCREWUP("atime.sec not present");
1758 			ull = strtoull(cp, &cp, 10);
1759 			if (!cp || *cp++ != ' ')
1760 				SCREWUP("atime.sec not delimited");
1761 			if (TYPE_OVERFLOW(time_t, ull))
1762 				setimes = 0;	/* out of range */
1763 			atime.tv_sec = ull;
1764 			atime.tv_usec = strtol(cp, &cp, 10);
1765 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1766 			    atime.tv_usec > 999999)
1767 				SCREWUP("atime.usec not delimited");
1768 			(void) atomicio(vwrite, remout, "", 1);
1769 			continue;
1770 		}
1771 		if (*cp != 'C' && *cp != 'D') {
1772 			/*
1773 			 * Check for the case "rcp remote:foo\* local:bar".
1774 			 * In this case, the line "No match." can be returned
1775 			 * by the shell before the rcp command on the remote is
1776 			 * executed so the ^Aerror_message convention isn't
1777 			 * followed.
1778 			 */
1779 			if (first) {
1780 				run_err("%s", cp);
1781 				exit(1);
1782 			}
1783 			SCREWUP("expected control record");
1784 		}
1785 		mode = 0;
1786 		for (++cp; cp < buf + 5; cp++) {
1787 			if (*cp < '0' || *cp > '7')
1788 				SCREWUP("bad mode");
1789 			mode = (mode << 3) | (*cp - '0');
1790 		}
1791 		if (!pflag)
1792 			mode &= ~mask;
1793 		if (*cp++ != ' ')
1794 			SCREWUP("mode not delimited");
1795 
1796 		if (!isdigit((unsigned char)*cp))
1797 			SCREWUP("size not present");
1798 		ull = strtoull(cp, &cp, 10);
1799 		if (!cp || *cp++ != ' ')
1800 			SCREWUP("size not delimited");
1801 		if (TYPE_OVERFLOW(off_t, ull))
1802 			SCREWUP("size out of range");
1803 		size = (off_t)ull;
1804 
1805 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1806 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1807 			run_err("error: unexpected filename: %s", cp);
1808 			exit(1);
1809 		}
1810 		if (npatterns > 0) {
1811 			for (n = 0; n < npatterns; n++) {
1812 				if (strcmp(patterns[n], cp) == 0 ||
1813 				    fnmatch(patterns[n], cp, 0) == 0)
1814 					break;
1815 			}
1816 			if (n >= npatterns) {
1817 				debug2_f("incoming filename \"%s\" does not "
1818 				    "match any of %zu expected patterns", cp,
1819 				    npatterns);
1820 				for (n = 0; n < npatterns; n++) {
1821 					debug3_f("expected pattern %zu: \"%s\"",
1822 					    n, patterns[n]);
1823 				}
1824 				SCREWUP("filename does not match request");
1825 			}
1826 		}
1827 		if (targisdir) {
1828 			static char *namebuf;
1829 			static size_t cursize;
1830 			size_t need;
1831 
1832 			need = strlen(targ) + strlen(cp) + 250;
1833 			if (need > cursize) {
1834 				free(namebuf);
1835 				namebuf = xmalloc(need);
1836 				cursize = need;
1837 			}
1838 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1839 			    strcmp(targ, "/") ? "/" : "", cp);
1840 			np = namebuf;
1841 		} else
1842 			np = targ;
1843 		curfile = cp;
1844 		exists = stat(np, &stb) == 0;
1845 		if (buf[0] == 'D') {
1846 			int mod_flag = pflag;
1847 			if (!iamrecursive)
1848 				SCREWUP("received directory without -r");
1849 			if (exists) {
1850 				if (!S_ISDIR(stb.st_mode)) {
1851 					errno = ENOTDIR;
1852 					goto bad;
1853 				}
1854 				if (pflag)
1855 					(void) chmod(np, mode);
1856 			} else {
1857 				/* Handle copying from a read-only directory */
1858 				mod_flag = 1;
1859 				if (mkdir(np, mode | S_IRWXU) == -1)
1860 					goto bad;
1861 			}
1862 			vect[0] = xstrdup(np);
1863 			sink(1, vect, src);
1864 			if (setimes) {
1865 				setimes = 0;
1866 				(void) utimes(vect[0], tv);
1867 			}
1868 			if (mod_flag)
1869 				(void) chmod(vect[0], mode);
1870 			free(vect[0]);
1871 			continue;
1872 		}
1873 		omode = mode;
1874 		mode |= S_IWUSR;
1875 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1876 bad:			run_err("%s: %s", np, strerror(errno));
1877 			continue;
1878 		}
1879 		(void) atomicio(vwrite, remout, "", 1);
1880 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1881 			(void) close(ofd);
1882 			continue;
1883 		}
1884 		cp = bp->buf;
1885 		wrerr = 0;
1886 
1887 		/*
1888 		 * NB. do not use run_err() unless immediately followed by
1889 		 * exit() below as it may send a spurious reply that might
1890 		 * desyncronise us from the peer. Use note_err() instead.
1891 		 */
1892 		statbytes = 0;
1893 		if (showprogress)
1894 			start_progress_meter(curfile, size, &statbytes);
1895 		set_nonblock(remin);
1896 		for (count = i = 0; i < size; i += bp->cnt) {
1897 			amt = bp->cnt;
1898 			if (i + amt > size)
1899 				amt = size - i;
1900 			count += amt;
1901 			do {
1902 				j = atomicio6(read, remin, cp, amt,
1903 				    scpio, &statbytes);
1904 				if (j == 0) {
1905 					run_err("%s", j != EPIPE ?
1906 					    strerror(errno) :
1907 					    "dropped connection");
1908 					exit(1);
1909 				}
1910 				amt -= j;
1911 				cp += j;
1912 			} while (amt > 0);
1913 
1914 			if (count == bp->cnt) {
1915 				/* Keep reading so we stay sync'd up. */
1916 				if (!wrerr) {
1917 					if (atomicio(vwrite, ofd, bp->buf,
1918 					    count) != count) {
1919 						note_err("%s: %s", np,
1920 						    strerror(errno));
1921 						wrerr = 1;
1922 					}
1923 				}
1924 				count = 0;
1925 				cp = bp->buf;
1926 			}
1927 		}
1928 		unset_nonblock(remin);
1929 		if (count != 0 && !wrerr &&
1930 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1931 			note_err("%s: %s", np, strerror(errno));
1932 			wrerr = 1;
1933 		}
1934 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1935 		    ftruncate(ofd, size) != 0)
1936 			note_err("%s: truncate: %s", np, strerror(errno));
1937 		if (pflag) {
1938 			if (exists || omode != mode)
1939 #ifdef HAVE_FCHMOD
1940 				if (fchmod(ofd, omode)) {
1941 #else /* HAVE_FCHMOD */
1942 				if (chmod(np, omode)) {
1943 #endif /* HAVE_FCHMOD */
1944 					note_err("%s: set mode: %s",
1945 					    np, strerror(errno));
1946 				}
1947 		} else {
1948 			if (!exists && omode != mode)
1949 #ifdef HAVE_FCHMOD
1950 				if (fchmod(ofd, omode & ~mask)) {
1951 #else /* HAVE_FCHMOD */
1952 				if (chmod(np, omode & ~mask)) {
1953 #endif /* HAVE_FCHMOD */
1954 					note_err("%s: set mode: %s",
1955 					    np, strerror(errno));
1956 				}
1957 		}
1958 		if (close(ofd) == -1)
1959 			note_err("%s: close: %s", np, strerror(errno));
1960 		(void) response();
1961 		if (showprogress)
1962 			stop_progress_meter();
1963 		if (setimes && !wrerr) {
1964 			setimes = 0;
1965 			if (utimes(np, tv) == -1) {
1966 				note_err("%s: set times: %s",
1967 				    np, strerror(errno));
1968 			}
1969 		}
1970 		/* If no error was noted then signal success for this file */
1971 		if (note_err(NULL) == 0)
1972 			(void) atomicio(vwrite, remout, "", 1);
1973 	}
1974 done:
1975 	for (n = 0; n < npatterns; n++)
1976 		free(patterns[n]);
1977 	free(patterns);
1978 	return;
1979 screwup:
1980 	for (n = 0; n < npatterns; n++)
1981 		free(patterns[n]);
1982 	free(patterns);
1983 	run_err("protocol error: %s", why);
1984 	exit(1);
1985 }
1986 
1987 void
1988 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
1989     char *src, char *targ)
1990 {
1991 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1992 	char *abs_src = NULL, *tmp = NULL;
1993 	glob_t g;
1994 	int i, r, targetisdir, err = 0;
1995 
1996 	if ((filename = basename(src)) == NULL)
1997 		fatal("basename %s: %s", src, strerror(errno));
1998 
1999 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
2000 	    (target = prepare_remote_path(to, targ)) == NULL)
2001 		cleanup_exit(255);
2002 	memset(&g, 0, sizeof(g));
2003 
2004 	targetisdir = sftp_remote_is_dir(to, target);
2005 	if (!targetisdir && targetshouldbedirectory) {
2006 		error("%s: destination is not a directory", targ);
2007 		err = -1;
2008 		goto out;
2009 	}
2010 
2011 	debug3_f("copying remote %s to remote %s", abs_src, target);
2012 	if ((r = sftp_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
2013 	    NULL, &g)) != 0) {
2014 		if (r == GLOB_NOSPACE)
2015 			error("%s: too many glob matches", src);
2016 		else
2017 			error("%s: %s", src, strerror(ENOENT));
2018 		err = -1;
2019 		goto out;
2020 	}
2021 
2022 	/* Did we actually get any matches back from the glob? */
2023 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
2024 		/*
2025 		 * If nothing matched but a path returned, then it's probably
2026 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
2027 		 * exists so we can give a nice error message early.
2028 		 */
2029 		if (sftp_stat(from, g.gl_pathv[0], 1, NULL) != 0) {
2030 			error("%s: %s", src, strerror(ENOENT));
2031 			err = -1;
2032 			goto out;
2033 		}
2034 	}
2035 
2036 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2037 		tmp = xstrdup(g.gl_pathv[i]);
2038 		if ((filename = basename(tmp)) == NULL) {
2039 			error("basename %s: %s", tmp, strerror(errno));
2040 			err = -1;
2041 			goto out;
2042 		}
2043 
2044 		if (targetisdir)
2045 			abs_dst = sftp_path_append(target, filename);
2046 		else
2047 			abs_dst = xstrdup(target);
2048 
2049 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
2050 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
2051 			if (sftp_crossload_dir(from, to, g.gl_pathv[i], abs_dst,
2052 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
2053 				err = -1;
2054 		} else {
2055 			if (sftp_crossload(from, to, g.gl_pathv[i], abs_dst,
2056 			    NULL, pflag) == -1)
2057 				err = -1;
2058 		}
2059 		free(abs_dst);
2060 		abs_dst = NULL;
2061 		free(tmp);
2062 		tmp = NULL;
2063 	}
2064 
2065 out:
2066 	free(abs_src);
2067 	free(abs_dst);
2068 	free(target);
2069 	free(tmp);
2070 	globfree(&g);
2071 	if (err == -1)
2072 		errs = 1;
2073 }
2074 
2075 int
2076 response(void)
2077 {
2078 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
2079 
2080 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
2081 		lostconn(0);
2082 
2083 	cp = rbuf;
2084 	switch (resp) {
2085 	case 0:		/* ok */
2086 		return (0);
2087 	default:
2088 		*cp++ = resp;
2089 		/* FALLTHROUGH */
2090 	case 1:		/* error, followed by error msg */
2091 	case 2:		/* fatal error, "" */
2092 		do {
2093 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
2094 				lostconn(0);
2095 			*cp++ = ch;
2096 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
2097 
2098 		if (!iamremote) {
2099 			cp[-1] = '\0';
2100 			(void) snmprintf(visbuf, sizeof(visbuf),
2101 			    NULL, "%s\n", rbuf);
2102 			(void) atomicio(vwrite, STDERR_FILENO,
2103 			    visbuf, strlen(visbuf));
2104 		}
2105 		++errs;
2106 		if (resp == 1)
2107 			return (-1);
2108 		exit(1);
2109 	}
2110 	/* NOTREACHED */
2111 }
2112 
2113 void
2114 usage(void)
2115 {
2116 	(void) fprintf(stderr,
2117 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2118 	    "           [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2119 	    "           [-P port] [-S program] [-X sftp_option] source ... target\n");
2120 	exit(1);
2121 }
2122 
2123 void
2124 run_err(const char *fmt,...)
2125 {
2126 	static FILE *fp;
2127 	va_list ap;
2128 
2129 	++errs;
2130 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2131 		(void) fprintf(fp, "%c", 0x01);
2132 		(void) fprintf(fp, "scp: ");
2133 		va_start(ap, fmt);
2134 		(void) vfprintf(fp, fmt, ap);
2135 		va_end(ap);
2136 		(void) fprintf(fp, "\n");
2137 		(void) fflush(fp);
2138 	}
2139 
2140 	if (!iamremote) {
2141 		va_start(ap, fmt);
2142 		vfmprintf(stderr, fmt, ap);
2143 		va_end(ap);
2144 		fprintf(stderr, "\n");
2145 	}
2146 }
2147 
2148 /*
2149  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2150  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2151  * any active error at the end of the transfer.
2152  */
2153 int
2154 note_err(const char *fmt, ...)
2155 {
2156 	static char *emsg;
2157 	va_list ap;
2158 
2159 	/* Replay any previously-noted error */
2160 	if (fmt == NULL) {
2161 		if (emsg == NULL)
2162 			return 0;
2163 		run_err("%s", emsg);
2164 		free(emsg);
2165 		emsg = NULL;
2166 		return -1;
2167 	}
2168 
2169 	errs++;
2170 	/* Prefer first-noted error */
2171 	if (emsg != NULL)
2172 		return -1;
2173 
2174 	va_start(ap, fmt);
2175 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
2176 	va_end(ap);
2177 	return -1;
2178 }
2179 
2180 void
2181 verifydir(char *cp)
2182 {
2183 	struct stat stb;
2184 
2185 	if (!stat(cp, &stb)) {
2186 		if (S_ISDIR(stb.st_mode))
2187 			return;
2188 		errno = ENOTDIR;
2189 	}
2190 	run_err("%s: %s", cp, strerror(errno));
2191 	killchild(0);
2192 }
2193 
2194 int
2195 okname(char *cp0)
2196 {
2197 	int c;
2198 	char *cp;
2199 
2200 	cp = cp0;
2201 	do {
2202 		c = (int)*cp;
2203 		if (c & 0200)
2204 			goto bad;
2205 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
2206 			switch (c) {
2207 			case '\'':
2208 			case '"':
2209 			case '`':
2210 			case ' ':
2211 			case '#':
2212 				goto bad;
2213 			default:
2214 				break;
2215 			}
2216 		}
2217 	} while (*++cp);
2218 	return (1);
2219 
2220 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
2221 	return (0);
2222 }
2223 
2224 BUF *
2225 allocbuf(BUF *bp, int fd, int blksize)
2226 {
2227 	size_t size;
2228 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2229 	struct stat stb;
2230 
2231 	if (fstat(fd, &stb) == -1) {
2232 		run_err("fstat: %s", strerror(errno));
2233 		return (0);
2234 	}
2235 	size = ROUNDUP(stb.st_blksize, blksize);
2236 	if (size == 0)
2237 		size = blksize;
2238 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2239 	size = blksize;
2240 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2241 	if (bp->cnt >= size)
2242 		return (bp);
2243 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2244 	bp->cnt = size;
2245 	return (bp);
2246 }
2247 
2248 void
2249 lostconn(int signo)
2250 {
2251 	if (!iamremote)
2252 		(void)write(STDERR_FILENO, "lost connection\n", 16);
2253 	if (signo)
2254 		_exit(1);
2255 	else
2256 		exit(1);
2257 }
2258 
2259 void
2260 cleanup_exit(int i)
2261 {
2262 	if (remin > 0)
2263 		close(remin);
2264 	if (remout > 0)
2265 		close(remout);
2266 	if (remin2 > 0)
2267 		close(remin2);
2268 	if (remout2 > 0)
2269 		close(remout2);
2270 	if (do_cmd_pid > 0)
2271 		(void)waitpid(do_cmd_pid, NULL, 0);
2272 	if (do_cmd_pid2 > 0)
2273 		(void)waitpid(do_cmd_pid2, NULL, 0);
2274 	exit(i);
2275 }
2276