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