xref: /freebsd/crypto/openssh/scp.c (revision 5e3190f700637fcfc1a52daeaa4a031fdd2557c7)
1 /* $OpenBSD: scp.c,v 1.259 2023/09/10 23:12:32 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 				SCREWUP("filename does not match request");
1818 		}
1819 		if (targisdir) {
1820 			static char *namebuf;
1821 			static size_t cursize;
1822 			size_t need;
1823 
1824 			need = strlen(targ) + strlen(cp) + 250;
1825 			if (need > cursize) {
1826 				free(namebuf);
1827 				namebuf = xmalloc(need);
1828 				cursize = need;
1829 			}
1830 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1831 			    strcmp(targ, "/") ? "/" : "", cp);
1832 			np = namebuf;
1833 		} else
1834 			np = targ;
1835 		curfile = cp;
1836 		exists = stat(np, &stb) == 0;
1837 		if (buf[0] == 'D') {
1838 			int mod_flag = pflag;
1839 			if (!iamrecursive)
1840 				SCREWUP("received directory without -r");
1841 			if (exists) {
1842 				if (!S_ISDIR(stb.st_mode)) {
1843 					errno = ENOTDIR;
1844 					goto bad;
1845 				}
1846 				if (pflag)
1847 					(void) chmod(np, mode);
1848 			} else {
1849 				/* Handle copying from a read-only directory */
1850 				mod_flag = 1;
1851 				if (mkdir(np, mode | S_IRWXU) == -1)
1852 					goto bad;
1853 			}
1854 			vect[0] = xstrdup(np);
1855 			sink(1, vect, src);
1856 			if (setimes) {
1857 				setimes = 0;
1858 				(void) utimes(vect[0], tv);
1859 			}
1860 			if (mod_flag)
1861 				(void) chmod(vect[0], mode);
1862 			free(vect[0]);
1863 			continue;
1864 		}
1865 		omode = mode;
1866 		mode |= S_IWUSR;
1867 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1868 bad:			run_err("%s: %s", np, strerror(errno));
1869 			continue;
1870 		}
1871 		(void) atomicio(vwrite, remout, "", 1);
1872 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1873 			(void) close(ofd);
1874 			continue;
1875 		}
1876 		cp = bp->buf;
1877 		wrerr = 0;
1878 
1879 		/*
1880 		 * NB. do not use run_err() unless immediately followed by
1881 		 * exit() below as it may send a spurious reply that might
1882 		 * desyncronise us from the peer. Use note_err() instead.
1883 		 */
1884 		statbytes = 0;
1885 		if (showprogress)
1886 			start_progress_meter(curfile, size, &statbytes);
1887 		set_nonblock(remin);
1888 		for (count = i = 0; i < size; i += bp->cnt) {
1889 			amt = bp->cnt;
1890 			if (i + amt > size)
1891 				amt = size - i;
1892 			count += amt;
1893 			do {
1894 				j = atomicio6(read, remin, cp, amt,
1895 				    scpio, &statbytes);
1896 				if (j == 0) {
1897 					run_err("%s", j != EPIPE ?
1898 					    strerror(errno) :
1899 					    "dropped connection");
1900 					exit(1);
1901 				}
1902 				amt -= j;
1903 				cp += j;
1904 			} while (amt > 0);
1905 
1906 			if (count == bp->cnt) {
1907 				/* Keep reading so we stay sync'd up. */
1908 				if (!wrerr) {
1909 					if (atomicio(vwrite, ofd, bp->buf,
1910 					    count) != count) {
1911 						note_err("%s: %s", np,
1912 						    strerror(errno));
1913 						wrerr = 1;
1914 					}
1915 				}
1916 				count = 0;
1917 				cp = bp->buf;
1918 			}
1919 		}
1920 		unset_nonblock(remin);
1921 		if (count != 0 && !wrerr &&
1922 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1923 			note_err("%s: %s", np, strerror(errno));
1924 			wrerr = 1;
1925 		}
1926 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1927 		    ftruncate(ofd, size) != 0)
1928 			note_err("%s: truncate: %s", np, strerror(errno));
1929 		if (pflag) {
1930 			if (exists || omode != mode)
1931 #ifdef HAVE_FCHMOD
1932 				if (fchmod(ofd, omode)) {
1933 #else /* HAVE_FCHMOD */
1934 				if (chmod(np, omode)) {
1935 #endif /* HAVE_FCHMOD */
1936 					note_err("%s: set mode: %s",
1937 					    np, strerror(errno));
1938 				}
1939 		} else {
1940 			if (!exists && omode != mode)
1941 #ifdef HAVE_FCHMOD
1942 				if (fchmod(ofd, omode & ~mask)) {
1943 #else /* HAVE_FCHMOD */
1944 				if (chmod(np, omode & ~mask)) {
1945 #endif /* HAVE_FCHMOD */
1946 					note_err("%s: set mode: %s",
1947 					    np, strerror(errno));
1948 				}
1949 		}
1950 		if (close(ofd) == -1)
1951 			note_err("%s: close: %s", np, strerror(errno));
1952 		(void) response();
1953 		if (showprogress)
1954 			stop_progress_meter();
1955 		if (setimes && !wrerr) {
1956 			setimes = 0;
1957 			if (utimes(np, tv) == -1) {
1958 				note_err("%s: set times: %s",
1959 				    np, strerror(errno));
1960 			}
1961 		}
1962 		/* If no error was noted then signal success for this file */
1963 		if (note_err(NULL) == 0)
1964 			(void) atomicio(vwrite, remout, "", 1);
1965 	}
1966 done:
1967 	for (n = 0; n < npatterns; n++)
1968 		free(patterns[n]);
1969 	free(patterns);
1970 	return;
1971 screwup:
1972 	for (n = 0; n < npatterns; n++)
1973 		free(patterns[n]);
1974 	free(patterns);
1975 	run_err("protocol error: %s", why);
1976 	exit(1);
1977 }
1978 
1979 void
1980 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
1981     char *src, char *targ)
1982 {
1983 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1984 	char *abs_src = NULL, *tmp = NULL;
1985 	glob_t g;
1986 	int i, r, targetisdir, err = 0;
1987 
1988 	if ((filename = basename(src)) == NULL)
1989 		fatal("basename %s: %s", src, strerror(errno));
1990 
1991 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
1992 	    (target = prepare_remote_path(to, targ)) == NULL)
1993 		cleanup_exit(255);
1994 	memset(&g, 0, sizeof(g));
1995 
1996 	targetisdir = sftp_remote_is_dir(to, target);
1997 	if (!targetisdir && targetshouldbedirectory) {
1998 		error("%s: destination is not a directory", targ);
1999 		err = -1;
2000 		goto out;
2001 	}
2002 
2003 	debug3_f("copying remote %s to remote %s", abs_src, target);
2004 	if ((r = sftp_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
2005 	    NULL, &g)) != 0) {
2006 		if (r == GLOB_NOSPACE)
2007 			error("%s: too many glob matches", src);
2008 		else
2009 			error("%s: %s", src, strerror(ENOENT));
2010 		err = -1;
2011 		goto out;
2012 	}
2013 
2014 	/* Did we actually get any matches back from the glob? */
2015 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
2016 		/*
2017 		 * If nothing matched but a path returned, then it's probably
2018 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
2019 		 * exists so we can give a nice error message early.
2020 		 */
2021 		if (sftp_stat(from, g.gl_pathv[0], 1, NULL) != 0) {
2022 			error("%s: %s", src, strerror(ENOENT));
2023 			err = -1;
2024 			goto out;
2025 		}
2026 	}
2027 
2028 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2029 		tmp = xstrdup(g.gl_pathv[i]);
2030 		if ((filename = basename(tmp)) == NULL) {
2031 			error("basename %s: %s", tmp, strerror(errno));
2032 			err = -1;
2033 			goto out;
2034 		}
2035 
2036 		if (targetisdir)
2037 			abs_dst = sftp_path_append(target, filename);
2038 		else
2039 			abs_dst = xstrdup(target);
2040 
2041 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
2042 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
2043 			if (sftp_crossload_dir(from, to, g.gl_pathv[i], abs_dst,
2044 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
2045 				err = -1;
2046 		} else {
2047 			if (sftp_crossload(from, to, g.gl_pathv[i], abs_dst,
2048 			    NULL, pflag) == -1)
2049 				err = -1;
2050 		}
2051 		free(abs_dst);
2052 		abs_dst = NULL;
2053 		free(tmp);
2054 		tmp = NULL;
2055 	}
2056 
2057 out:
2058 	free(abs_src);
2059 	free(abs_dst);
2060 	free(target);
2061 	free(tmp);
2062 	globfree(&g);
2063 	if (err == -1)
2064 		errs = 1;
2065 }
2066 
2067 int
2068 response(void)
2069 {
2070 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
2071 
2072 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
2073 		lostconn(0);
2074 
2075 	cp = rbuf;
2076 	switch (resp) {
2077 	case 0:		/* ok */
2078 		return (0);
2079 	default:
2080 		*cp++ = resp;
2081 		/* FALLTHROUGH */
2082 	case 1:		/* error, followed by error msg */
2083 	case 2:		/* fatal error, "" */
2084 		do {
2085 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
2086 				lostconn(0);
2087 			*cp++ = ch;
2088 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
2089 
2090 		if (!iamremote) {
2091 			cp[-1] = '\0';
2092 			(void) snmprintf(visbuf, sizeof(visbuf),
2093 			    NULL, "%s\n", rbuf);
2094 			(void) atomicio(vwrite, STDERR_FILENO,
2095 			    visbuf, strlen(visbuf));
2096 		}
2097 		++errs;
2098 		if (resp == 1)
2099 			return (-1);
2100 		exit(1);
2101 	}
2102 	/* NOTREACHED */
2103 }
2104 
2105 void
2106 usage(void)
2107 {
2108 	(void) fprintf(stderr,
2109 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2110 	    "           [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2111 	    "           [-P port] [-S program] [-X sftp_option] source ... target\n");
2112 	exit(1);
2113 }
2114 
2115 void
2116 run_err(const char *fmt,...)
2117 {
2118 	static FILE *fp;
2119 	va_list ap;
2120 
2121 	++errs;
2122 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2123 		(void) fprintf(fp, "%c", 0x01);
2124 		(void) fprintf(fp, "scp: ");
2125 		va_start(ap, fmt);
2126 		(void) vfprintf(fp, fmt, ap);
2127 		va_end(ap);
2128 		(void) fprintf(fp, "\n");
2129 		(void) fflush(fp);
2130 	}
2131 
2132 	if (!iamremote) {
2133 		va_start(ap, fmt);
2134 		vfmprintf(stderr, fmt, ap);
2135 		va_end(ap);
2136 		fprintf(stderr, "\n");
2137 	}
2138 }
2139 
2140 /*
2141  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2142  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2143  * any active error at the end of the transfer.
2144  */
2145 int
2146 note_err(const char *fmt, ...)
2147 {
2148 	static char *emsg;
2149 	va_list ap;
2150 
2151 	/* Replay any previously-noted error */
2152 	if (fmt == NULL) {
2153 		if (emsg == NULL)
2154 			return 0;
2155 		run_err("%s", emsg);
2156 		free(emsg);
2157 		emsg = NULL;
2158 		return -1;
2159 	}
2160 
2161 	errs++;
2162 	/* Prefer first-noted error */
2163 	if (emsg != NULL)
2164 		return -1;
2165 
2166 	va_start(ap, fmt);
2167 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
2168 	va_end(ap);
2169 	return -1;
2170 }
2171 
2172 void
2173 verifydir(char *cp)
2174 {
2175 	struct stat stb;
2176 
2177 	if (!stat(cp, &stb)) {
2178 		if (S_ISDIR(stb.st_mode))
2179 			return;
2180 		errno = ENOTDIR;
2181 	}
2182 	run_err("%s: %s", cp, strerror(errno));
2183 	killchild(0);
2184 }
2185 
2186 int
2187 okname(char *cp0)
2188 {
2189 	int c;
2190 	char *cp;
2191 
2192 	cp = cp0;
2193 	do {
2194 		c = (int)*cp;
2195 		if (c & 0200)
2196 			goto bad;
2197 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
2198 			switch (c) {
2199 			case '\'':
2200 			case '"':
2201 			case '`':
2202 			case ' ':
2203 			case '#':
2204 				goto bad;
2205 			default:
2206 				break;
2207 			}
2208 		}
2209 	} while (*++cp);
2210 	return (1);
2211 
2212 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
2213 	return (0);
2214 }
2215 
2216 BUF *
2217 allocbuf(BUF *bp, int fd, int blksize)
2218 {
2219 	size_t size;
2220 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2221 	struct stat stb;
2222 
2223 	if (fstat(fd, &stb) == -1) {
2224 		run_err("fstat: %s", strerror(errno));
2225 		return (0);
2226 	}
2227 	size = ROUNDUP(stb.st_blksize, blksize);
2228 	if (size == 0)
2229 		size = blksize;
2230 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2231 	size = blksize;
2232 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2233 	if (bp->cnt >= size)
2234 		return (bp);
2235 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2236 	bp->cnt = size;
2237 	return (bp);
2238 }
2239 
2240 void
2241 lostconn(int signo)
2242 {
2243 	if (!iamremote)
2244 		(void)write(STDERR_FILENO, "lost connection\n", 16);
2245 	if (signo)
2246 		_exit(1);
2247 	else
2248 		exit(1);
2249 }
2250 
2251 void
2252 cleanup_exit(int i)
2253 {
2254 	if (remin > 0)
2255 		close(remin);
2256 	if (remout > 0)
2257 		close(remout);
2258 	if (remin2 > 0)
2259 		close(remin2);
2260 	if (remout2 > 0)
2261 		close(remout2);
2262 	if (do_cmd_pid > 0)
2263 		(void)waitpid(do_cmd_pid, NULL, 0);
2264 	if (do_cmd_pid2 > 0)
2265 		(void)waitpid(do_cmd_pid2, NULL, 0);
2266 	exit(i);
2267 }
2268