xref: /freebsd/crypto/openssh/scp.c (revision 2b833162)
1 /* $OpenBSD: scp.c,v 1.253 2023/03/03 03:12:24 dtucker 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 		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 	int o = 0, tail_len = strlen(pattern + brace_end + 1);
842 
843 	if ((cp = malloc(brace_start + (sel_end - sel_start) +
844 	    tail_len + 1)) == NULL)
845 		return -1;
846 
847 	/* Pattern before initial brace */
848 	if (brace_start > 0) {
849 		memcpy(cp, pattern, brace_start);
850 		o = brace_start;
851 	}
852 	/* Current braced selection */
853 	if (sel_end - sel_start > 0) {
854 		memcpy(cp + o, pattern + sel_start,
855 		    sel_end - sel_start);
856 		o += sel_end - sel_start;
857 	}
858 	/* Remainder of pattern after closing brace */
859 	if (tail_len > 0) {
860 		memcpy(cp + o, pattern + brace_end + 1, tail_len);
861 		o += tail_len;
862 	}
863 	cp[o] = '\0';
864 	if (append(cp, patternsp, npatternsp) != 0) {
865 		free(cp);
866 		return -1;
867 	}
868 	return 0;
869 }
870 
871 /*
872  * Expand the first encountered brace in pattern, appending the expanded
873  * patterns it yielded to the *patternsp array.
874  *
875  * Returns 0 on success or -1 on allocation failure.
876  *
877  * Signals whether expansion was performed via *expanded and whether
878  * pattern was invalid via *invalid.
879  */
880 static int
881 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
882     int *expanded, int *invalid)
883 {
884 	int i;
885 	int in_bracket, brace_start, brace_end, brace_level;
886 	int sel_start, sel_end;
887 
888 	*invalid = *expanded = 0;
889 
890 	if (find_brace(pattern, &brace_start, &brace_end) != 0) {
891 		*invalid = 1;
892 		return 0;
893 	} else if (brace_start == -1)
894 		return 0;
895 
896 	in_bracket = brace_level = 0;
897 	for (i = sel_start = brace_start + 1; i < brace_end; i++) {
898 		switch (pattern[i]) {
899 		case '{':
900 			if (in_bracket)
901 				break;
902 			brace_level++;
903 			break;
904 		case '}':
905 			if (in_bracket)
906 				break;
907 			brace_level--;
908 			break;
909 		case '[':
910 			in_bracket = 1;
911 			break;
912 		case ']':
913 			in_bracket = 0;
914 			break;
915 		case '\\':
916 			if (i < brace_end - 1)
917 				i++; /* skip */
918 			break;
919 		}
920 		if (pattern[i] == ',' || i == brace_end - 1) {
921 			if (in_bracket || brace_level > 0)
922 				continue;
923 			/* End of a selection, emit an expanded pattern */
924 
925 			/* Adjust end index for last selection */
926 			sel_end = (i == brace_end - 1) ? brace_end : i;
927 			if (emit_expansion(pattern, brace_start, brace_end,
928 			    sel_start, sel_end, patternsp, npatternsp) != 0)
929 				return -1;
930 			/* move on to the next selection */
931 			sel_start = i + 1;
932 			continue;
933 		}
934 	}
935 	if (in_bracket || brace_level > 0) {
936 		*invalid = 1;
937 		return 0;
938 	}
939 	/* success */
940 	*expanded = 1;
941 	return 0;
942 }
943 
944 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
945 static int
946 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
947 {
948 	char *cp, *cp2, **active = NULL, **done = NULL;
949 	size_t i, nactive = 0, ndone = 0;
950 	int ret = -1, invalid = 0, expanded = 0;
951 
952 	*patternsp = NULL;
953 	*npatternsp = 0;
954 
955 	/* Start the worklist with the original pattern */
956 	if ((cp = strdup(pattern)) == NULL)
957 		return -1;
958 	if (append(cp, &active, &nactive) != 0) {
959 		free(cp);
960 		return -1;
961 	}
962 	while (nactive > 0) {
963 		cp = active[nactive - 1];
964 		nactive--;
965 		if (brace_expand_one(cp, &active, &nactive,
966 		    &expanded, &invalid) == -1) {
967 			free(cp);
968 			goto fail;
969 		}
970 		if (invalid)
971 			fatal_f("invalid brace pattern \"%s\"", cp);
972 		if (expanded) {
973 			/*
974 			 * Current entry expanded to new entries on the
975 			 * active list; discard the progenitor pattern.
976 			 */
977 			free(cp);
978 			continue;
979 		}
980 		/*
981 		 * Pattern did not expand; append the finename component to
982 		 * the completed list
983 		 */
984 		if ((cp2 = strrchr(cp, '/')) != NULL)
985 			*cp2++ = '\0';
986 		else
987 			cp2 = cp;
988 		if (append(xstrdup(cp2), &done, &ndone) != 0) {
989 			free(cp);
990 			goto fail;
991 		}
992 		free(cp);
993 	}
994 	/* success */
995 	*patternsp = done;
996 	*npatternsp = ndone;
997 	done = NULL;
998 	ndone = 0;
999 	ret = 0;
1000  fail:
1001 	for (i = 0; i < nactive; i++)
1002 		free(active[i]);
1003 	free(active);
1004 	for (i = 0; i < ndone; i++)
1005 		free(done[i]);
1006 	free(done);
1007 	return ret;
1008 }
1009 
1010 static struct sftp_conn *
1011 do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
1012    int *reminp, int *remoutp, int *pidp)
1013 {
1014 	if (sftp_direct == NULL) {
1015 		if (do_cmd(ssh_program, host, user, port, 1, "sftp",
1016 		    reminp, remoutp, pidp) < 0)
1017 			return NULL;
1018 
1019 	} else {
1020 		freeargs(&args);
1021 		addargs(&args, "sftp-server");
1022 		if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
1023 		    reminp, remoutp, pidp) < 0)
1024 			return NULL;
1025 	}
1026 	return do_init(*reminp, *remoutp,
1027 	    sftp_copy_buflen, sftp_nrequests, limit_kbps);
1028 }
1029 
1030 void
1031 toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1032 {
1033 	char *suser = NULL, *host = NULL, *src = NULL;
1034 	char *bp, *tuser, *thost, *targ;
1035 	int sport = -1, tport = -1;
1036 	struct sftp_conn *conn = NULL, *conn2 = NULL;
1037 	arglist alist;
1038 	int i, r, status;
1039 	u_int j;
1040 
1041 	memset(&alist, '\0', sizeof(alist));
1042 	alist.list = NULL;
1043 
1044 	/* Parse target */
1045 	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
1046 	if (r == -1) {
1047 		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
1048 		++errs;
1049 		goto out;
1050 	}
1051 	if (r != 0) {
1052 		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
1053 		    &targ) == -1) {
1054 			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
1055 			++errs;
1056 			goto out;
1057 		}
1058 	}
1059 
1060 	/* Parse source files */
1061 	for (i = 0; i < argc - 1; i++) {
1062 		free(suser);
1063 		free(host);
1064 		free(src);
1065 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1066 		if (r == -1) {
1067 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1068 			++errs;
1069 			continue;
1070 		}
1071 		if (r != 0) {
1072 			parse_user_host_path(argv[i], &suser, &host, &src);
1073 		}
1074 		if (suser != NULL && !okname(suser)) {
1075 			++errs;
1076 			continue;
1077 		}
1078 		if (host && throughlocal) {	/* extended remote to remote */
1079 			if (mode == MODE_SFTP) {
1080 				if (remin == -1) {
1081 					/* Connect to dest now */
1082 					conn = do_sftp_connect(thost, tuser,
1083 					    tport, sftp_direct,
1084 					    &remin, &remout, &do_cmd_pid);
1085 					if (conn == NULL) {
1086 						fatal("Unable to open "
1087 						    "destination connection");
1088 					}
1089 					debug3_f("origin in %d out %d pid %ld",
1090 					    remin, remout, (long)do_cmd_pid);
1091 				}
1092 				/*
1093 				 * XXX remember suser/host/sport and only
1094 				 * reconnect if they change between arguments.
1095 				 * would save reconnections for cases like
1096 				 * scp -3 hosta:/foo hosta:/bar hostb:
1097 				 */
1098 				/* Connect to origin now */
1099 				conn2 = do_sftp_connect(host, suser,
1100 				    sport, sftp_direct,
1101 				    &remin2, &remout2, &do_cmd_pid2);
1102 				if (conn2 == NULL) {
1103 					fatal("Unable to open "
1104 					    "source connection");
1105 				}
1106 				debug3_f("destination in %d out %d pid %ld",
1107 				    remin2, remout2, (long)do_cmd_pid2);
1108 				throughlocal_sftp(conn2, conn, src, targ);
1109 				(void) close(remin2);
1110 				(void) close(remout2);
1111 				remin2 = remout2 = -1;
1112 				if (waitpid(do_cmd_pid2, &status, 0) == -1)
1113 					++errs;
1114 				else if (!WIFEXITED(status) ||
1115 				    WEXITSTATUS(status) != 0)
1116 					++errs;
1117 				do_cmd_pid2 = -1;
1118 				continue;
1119 			} else {
1120 				xasprintf(&bp, "%s -f %s%s", cmd,
1121 				    *src == '-' ? "-- " : "", src);
1122 				if (do_cmd(ssh_program, host, suser, sport, 0,
1123 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1124 					exit(1);
1125 				free(bp);
1126 				xasprintf(&bp, "%s -t %s%s", cmd,
1127 				    *targ == '-' ? "-- " : "", targ);
1128 				if (do_cmd2(thost, tuser, tport, bp,
1129 				    remin, remout) < 0)
1130 					exit(1);
1131 				free(bp);
1132 				(void) close(remin);
1133 				(void) close(remout);
1134 				remin = remout = -1;
1135 			}
1136 		} else if (host) {	/* standard remote to remote */
1137 			/*
1138 			 * Second remote user is passed to first remote side
1139 			 * via scp command-line. Ensure it contains no obvious
1140 			 * shell characters.
1141 			 */
1142 			if (tuser != NULL && !okname(tuser)) {
1143 				++errs;
1144 				continue;
1145 			}
1146 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
1147 				/* This would require the remote support URIs */
1148 				fatal("target port not supported with two "
1149 				    "remote hosts and the -R option");
1150 			}
1151 
1152 			freeargs(&alist);
1153 			addargs(&alist, "%s", ssh_program);
1154 			addargs(&alist, "-x");
1155 			addargs(&alist, "-oClearAllForwardings=yes");
1156 			addargs(&alist, "-n");
1157 			for (j = 0; j < remote_remote_args.num; j++) {
1158 				addargs(&alist, "%s",
1159 				    remote_remote_args.list[j]);
1160 			}
1161 
1162 			if (sport != -1) {
1163 				addargs(&alist, "-p");
1164 				addargs(&alist, "%d", sport);
1165 			}
1166 			if (suser) {
1167 				addargs(&alist, "-l");
1168 				addargs(&alist, "%s", suser);
1169 			}
1170 			addargs(&alist, "--");
1171 			addargs(&alist, "%s", host);
1172 			addargs(&alist, "%s", cmd);
1173 			addargs(&alist, "%s", src);
1174 			addargs(&alist, "%s%s%s:%s",
1175 			    tuser ? tuser : "", tuser ? "@" : "",
1176 			    thost, targ);
1177 			if (do_local_cmd(&alist) != 0)
1178 				errs = 1;
1179 		} else {	/* local to remote */
1180 			if (mode == MODE_SFTP) {
1181 				if (remin == -1) {
1182 					/* Connect to remote now */
1183 					conn = do_sftp_connect(thost, tuser,
1184 					    tport, sftp_direct,
1185 					    &remin, &remout, &do_cmd_pid);
1186 					if (conn == NULL) {
1187 						fatal("Unable to open sftp "
1188 						    "connection");
1189 					}
1190 				}
1191 
1192 				/* The protocol */
1193 				source_sftp(1, argv[i], targ, conn);
1194 				continue;
1195 			}
1196 			/* SCP */
1197 			if (remin == -1) {
1198 				xasprintf(&bp, "%s -t %s%s", cmd,
1199 				    *targ == '-' ? "-- " : "", targ);
1200 				if (do_cmd(ssh_program, thost, tuser, tport, 0,
1201 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1202 					exit(1);
1203 				if (response() < 0)
1204 					exit(1);
1205 				free(bp);
1206 			}
1207 			source(1, argv + i);
1208 		}
1209 	}
1210 out:
1211 	if (mode == MODE_SFTP)
1212 		free(conn);
1213 	free(tuser);
1214 	free(thost);
1215 	free(targ);
1216 	free(suser);
1217 	free(host);
1218 	free(src);
1219 }
1220 
1221 void
1222 tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1223 {
1224 	char *bp, *host = NULL, *src = NULL, *suser = NULL;
1225 	arglist alist;
1226 	struct sftp_conn *conn = NULL;
1227 	int i, r, sport = -1;
1228 
1229 	memset(&alist, '\0', sizeof(alist));
1230 	alist.list = NULL;
1231 
1232 	for (i = 0; i < argc - 1; i++) {
1233 		free(suser);
1234 		free(host);
1235 		free(src);
1236 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1237 		if (r == -1) {
1238 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1239 			++errs;
1240 			continue;
1241 		}
1242 		if (r != 0)
1243 			parse_user_host_path(argv[i], &suser, &host, &src);
1244 		if (suser != NULL && !okname(suser)) {
1245 			++errs;
1246 			continue;
1247 		}
1248 		if (!host) {	/* Local to local. */
1249 			freeargs(&alist);
1250 			addargs(&alist, "%s", _PATH_CP);
1251 			if (iamrecursive)
1252 				addargs(&alist, "-r");
1253 			if (pflag)
1254 				addargs(&alist, "-p");
1255 			addargs(&alist, "--");
1256 			addargs(&alist, "%s", argv[i]);
1257 			addargs(&alist, "%s", argv[argc-1]);
1258 			if (do_local_cmd(&alist))
1259 				++errs;
1260 			continue;
1261 		}
1262 		/* Remote to local. */
1263 		if (mode == MODE_SFTP) {
1264 			conn = do_sftp_connect(host, suser, sport,
1265 			    sftp_direct, &remin, &remout, &do_cmd_pid);
1266 			if (conn == NULL) {
1267 				error("sftp connection failed");
1268 				++errs;
1269 				continue;
1270 			}
1271 
1272 			/* The protocol */
1273 			sink_sftp(1, argv[argc - 1], src, conn);
1274 
1275 			free(conn);
1276 			(void) close(remin);
1277 			(void) close(remout);
1278 			remin = remout = -1;
1279 			continue;
1280 		}
1281 		/* SCP */
1282 		xasprintf(&bp, "%s -f %s%s",
1283 		    cmd, *src == '-' ? "-- " : "", src);
1284 		if (do_cmd(ssh_program, host, suser, sport, 0, bp,
1285 		    &remin, &remout, &do_cmd_pid) < 0) {
1286 			free(bp);
1287 			++errs;
1288 			continue;
1289 		}
1290 		free(bp);
1291 		sink(1, argv + argc - 1, src);
1292 		(void) close(remin);
1293 		remin = remout = -1;
1294 	}
1295 	free(suser);
1296 	free(host);
1297 	free(src);
1298 }
1299 
1300 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1301 static char *
1302 prepare_remote_path(struct sftp_conn *conn, const char *path)
1303 {
1304 	size_t nslash;
1305 
1306 	/* Handle ~ prefixed paths */
1307 	if (*path == '\0' || strcmp(path, "~") == 0)
1308 		return xstrdup(".");
1309 	if (*path != '~')
1310 		return xstrdup(path);
1311 	if (strncmp(path, "~/", 2) == 0) {
1312 		if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
1313 			return xstrdup(".");
1314 		return xstrdup(path + 2 + nslash);
1315 	}
1316 	if (can_expand_path(conn))
1317 		return do_expand_path(conn, path);
1318 	/* No protocol extension */
1319 	error("server expand-path extension is required "
1320 	    "for ~user paths in SFTP mode");
1321 	return NULL;
1322 }
1323 
1324 void
1325 source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
1326 {
1327 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1328 	int src_is_dir, target_is_dir;
1329 	Attrib a;
1330 	struct stat st;
1331 
1332 	memset(&a, '\0', sizeof(a));
1333 	if (stat(src, &st) != 0)
1334 		fatal("stat local \"%s\": %s", src, strerror(errno));
1335 	src_is_dir = S_ISDIR(st.st_mode);
1336 	if ((filename = basename(src)) == NULL)
1337 		fatal("basename \"%s\": %s", src, strerror(errno));
1338 
1339 	/*
1340 	 * No need to glob here - the local shell already took care of
1341 	 * the expansions
1342 	 */
1343 	if ((target = prepare_remote_path(conn, targ)) == NULL)
1344 		cleanup_exit(255);
1345 	target_is_dir = remote_is_dir(conn, target);
1346 	if (targetshouldbedirectory && !target_is_dir) {
1347 		debug("target directory \"%s\" does not exist", target);
1348 		a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
1349 		a.perm = st.st_mode | 0700; /* ensure writable */
1350 		if (do_mkdir(conn, target, &a, 1) != 0)
1351 			cleanup_exit(255); /* error already logged */
1352 		target_is_dir = 1;
1353 	}
1354 	if (target_is_dir)
1355 		abs_dst = path_append(target, filename);
1356 	else {
1357 		abs_dst = target;
1358 		target = NULL;
1359 	}
1360 	debug3_f("copying local %s to remote %s", src, abs_dst);
1361 
1362 	if (src_is_dir && iamrecursive) {
1363 		if (upload_dir(conn, src, abs_dst, pflag,
1364 		    SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
1365 			error("failed to upload directory %s to %s", src, targ);
1366 			errs = 1;
1367 		}
1368 	} else if (do_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
1369 		error("failed to upload file %s to %s", src, targ);
1370 		errs = 1;
1371 	}
1372 
1373 	free(abs_dst);
1374 	free(target);
1375 }
1376 
1377 void
1378 source(int argc, char **argv)
1379 {
1380 	struct stat stb;
1381 	static BUF buffer;
1382 	BUF *bp;
1383 	off_t i, statbytes;
1384 	size_t amt, nr;
1385 	int fd = -1, haderr, indx;
1386 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1387 	int len;
1388 
1389 	for (indx = 0; indx < argc; ++indx) {
1390 		name = argv[indx];
1391 		statbytes = 0;
1392 		len = strlen(name);
1393 		while (len > 1 && name[len-1] == '/')
1394 			name[--len] = '\0';
1395 		if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1396 			goto syserr;
1397 		if (strchr(name, '\n') != NULL) {
1398 			strnvis(encname, name, sizeof(encname), VIS_NL);
1399 			name = encname;
1400 		}
1401 		if (fstat(fd, &stb) == -1) {
1402 syserr:			run_err("%s: %s", name, strerror(errno));
1403 			goto next;
1404 		}
1405 		if (stb.st_size < 0) {
1406 			run_err("%s: %s", name, "Negative file size");
1407 			goto next;
1408 		}
1409 		unset_nonblock(fd);
1410 		switch (stb.st_mode & S_IFMT) {
1411 		case S_IFREG:
1412 			break;
1413 		case S_IFDIR:
1414 			if (iamrecursive) {
1415 				rsource(name, &stb);
1416 				goto next;
1417 			}
1418 			/* FALLTHROUGH */
1419 		default:
1420 			run_err("%s: not a regular file", name);
1421 			goto next;
1422 		}
1423 		if ((last = strrchr(name, '/')) == NULL)
1424 			last = name;
1425 		else
1426 			++last;
1427 		curfile = last;
1428 		if (pflag) {
1429 			if (do_times(remout, verbose_mode, &stb) < 0)
1430 				goto next;
1431 		}
1432 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1433 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1434 		    (u_int) (stb.st_mode & FILEMODEMASK),
1435 		    (long long)stb.st_size, last);
1436 		if (verbose_mode)
1437 			fmprintf(stderr, "Sending file modes: %s", buf);
1438 		(void) atomicio(vwrite, remout, buf, strlen(buf));
1439 		if (response() < 0)
1440 			goto next;
1441 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1442 next:			if (fd != -1) {
1443 				(void) close(fd);
1444 				fd = -1;
1445 			}
1446 			continue;
1447 		}
1448 		if (showprogress)
1449 			start_progress_meter(curfile, stb.st_size, &statbytes);
1450 		set_nonblock(remout);
1451 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1452 			amt = bp->cnt;
1453 			if (i + (off_t)amt > stb.st_size)
1454 				amt = stb.st_size - i;
1455 			if (!haderr) {
1456 				if ((nr = atomicio(read, fd,
1457 				    bp->buf, amt)) != amt) {
1458 					haderr = errno;
1459 					memset(bp->buf + nr, 0, amt - nr);
1460 				}
1461 			}
1462 			/* Keep writing after error to retain sync */
1463 			if (haderr) {
1464 				(void)atomicio(vwrite, remout, bp->buf, amt);
1465 				memset(bp->buf, 0, amt);
1466 				continue;
1467 			}
1468 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1469 			    &statbytes) != amt)
1470 				haderr = errno;
1471 		}
1472 		unset_nonblock(remout);
1473 
1474 		if (fd != -1) {
1475 			if (close(fd) == -1 && !haderr)
1476 				haderr = errno;
1477 			fd = -1;
1478 		}
1479 		if (!haderr)
1480 			(void) atomicio(vwrite, remout, "", 1);
1481 		else
1482 			run_err("%s: %s", name, strerror(haderr));
1483 		(void) response();
1484 		if (showprogress)
1485 			stop_progress_meter();
1486 	}
1487 }
1488 
1489 void
1490 rsource(char *name, struct stat *statp)
1491 {
1492 	DIR *dirp;
1493 	struct dirent *dp;
1494 	char *last, *vect[1], path[PATH_MAX];
1495 
1496 	if (!(dirp = opendir(name))) {
1497 		run_err("%s: %s", name, strerror(errno));
1498 		return;
1499 	}
1500 	last = strrchr(name, '/');
1501 	if (last == NULL)
1502 		last = name;
1503 	else
1504 		last++;
1505 	if (pflag) {
1506 		if (do_times(remout, verbose_mode, statp) < 0) {
1507 			closedir(dirp);
1508 			return;
1509 		}
1510 	}
1511 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1512 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1513 	if (verbose_mode)
1514 		fmprintf(stderr, "Entering directory: %s", path);
1515 	(void) atomicio(vwrite, remout, path, strlen(path));
1516 	if (response() < 0) {
1517 		closedir(dirp);
1518 		return;
1519 	}
1520 	while ((dp = readdir(dirp)) != NULL) {
1521 		if (dp->d_ino == 0)
1522 			continue;
1523 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1524 			continue;
1525 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1526 			run_err("%s/%s: name too long", name, dp->d_name);
1527 			continue;
1528 		}
1529 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1530 		vect[0] = path;
1531 		source(1, vect);
1532 	}
1533 	(void) closedir(dirp);
1534 	(void) atomicio(vwrite, remout, "E\n", 2);
1535 	(void) response();
1536 }
1537 
1538 void
1539 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
1540 {
1541 	char *abs_src = NULL;
1542 	char *abs_dst = NULL;
1543 	glob_t g;
1544 	char *filename, *tmp = NULL;
1545 	int i, r, err = 0, dst_is_dir;
1546 	struct stat st;
1547 
1548 	memset(&g, 0, sizeof(g));
1549 
1550 	/*
1551 	 * Here, we need remote glob as SFTP can not depend on remote shell
1552 	 * expansions
1553 	 */
1554 	if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
1555 		err = -1;
1556 		goto out;
1557 	}
1558 
1559 	debug3_f("copying remote %s to local %s", abs_src, dst);
1560 	if ((r = remote_glob(conn, abs_src, GLOB_NOCHECK|GLOB_MARK,
1561 	    NULL, &g)) != 0) {
1562 		if (r == GLOB_NOSPACE)
1563 			error("%s: too many glob matches", src);
1564 		else
1565 			error("%s: %s", src, strerror(ENOENT));
1566 		err = -1;
1567 		goto out;
1568 	}
1569 
1570 	/* Did we actually get any matches back from the glob? */
1571 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
1572 		/*
1573 		 * If nothing matched but a path returned, then it's probably
1574 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
1575 		 * exists so we can give a nice error message early.
1576 		 */
1577 		if (do_stat(conn, g.gl_pathv[0], 1) == NULL) {
1578 			error("%s: %s", src, strerror(ENOENT));
1579 			err = -1;
1580 			goto out;
1581 		}
1582 	}
1583 
1584 	if ((r = stat(dst, &st)) != 0)
1585 		debug2_f("stat local \"%s\": %s", dst, strerror(errno));
1586 	dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
1587 
1588 	if (g.gl_matchc > 1 && !dst_is_dir) {
1589 		if (r == 0) {
1590 			error("Multiple files match pattern, but destination "
1591 			    "\"%s\" is not a directory", dst);
1592 			err = -1;
1593 			goto out;
1594 		}
1595 		debug2_f("creating destination \"%s\"", dst);
1596 		if (mkdir(dst, 0777) != 0) {
1597 			error("local mkdir \"%s\": %s", dst, strerror(errno));
1598 			err = -1;
1599 			goto out;
1600 		}
1601 		dst_is_dir = 1;
1602 	}
1603 
1604 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1605 		tmp = xstrdup(g.gl_pathv[i]);
1606 		if ((filename = basename(tmp)) == NULL) {
1607 			error("basename %s: %s", tmp, strerror(errno));
1608 			err = -1;
1609 			goto out;
1610 		}
1611 
1612 		if (dst_is_dir)
1613 			abs_dst = path_append(dst, filename);
1614 		else
1615 			abs_dst = xstrdup(dst);
1616 
1617 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1618 		if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1619 			if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL,
1620 			    pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
1621 				err = -1;
1622 		} else {
1623 			if (do_download(conn, g.gl_pathv[i], abs_dst, NULL,
1624 			    pflag, 0, 0, 1) == -1)
1625 				err = -1;
1626 		}
1627 		free(abs_dst);
1628 		abs_dst = NULL;
1629 		free(tmp);
1630 		tmp = NULL;
1631 	}
1632 
1633 out:
1634 	free(abs_src);
1635 	free(tmp);
1636 	globfree(&g);
1637 	if (err == -1)
1638 		errs = 1;
1639 }
1640 
1641 
1642 #define TYPE_OVERFLOW(type, val) \
1643 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
1644 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1645 	 (sizeof(type) != 4 && sizeof(type) != 8))
1646 
1647 void
1648 sink(int argc, char **argv, const char *src)
1649 {
1650 	static BUF buffer;
1651 	struct stat stb;
1652 	BUF *bp;
1653 	off_t i;
1654 	size_t j, count;
1655 	int amt, exists, first, ofd;
1656 	mode_t mode, omode, mask;
1657 	off_t size, statbytes;
1658 	unsigned long long ull;
1659 	int setimes, targisdir, wrerr;
1660 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1661 	char **patterns = NULL;
1662 	size_t n, npatterns = 0;
1663 	struct timeval tv[2];
1664 
1665 #define	atime	tv[0]
1666 #define	mtime	tv[1]
1667 #define	SCREWUP(str)	{ why = str; goto screwup; }
1668 
1669 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1670 		SCREWUP("Unexpected off_t/time_t size");
1671 
1672 	setimes = targisdir = 0;
1673 	mask = umask(0);
1674 	if (!pflag)
1675 		(void) umask(mask);
1676 	if (argc != 1) {
1677 		run_err("ambiguous target");
1678 		exit(1);
1679 	}
1680 	targ = *argv;
1681 	if (targetshouldbedirectory)
1682 		verifydir(targ);
1683 
1684 	(void) atomicio(vwrite, remout, "", 1);
1685 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1686 		targisdir = 1;
1687 	if (src != NULL && !iamrecursive && !Tflag) {
1688 		/*
1689 		 * Prepare to try to restrict incoming filenames to match
1690 		 * the requested destination file glob.
1691 		 */
1692 		if (brace_expand(src, &patterns, &npatterns) != 0)
1693 			fatal_f("could not expand pattern");
1694 	}
1695 	for (first = 1;; first = 0) {
1696 		cp = buf;
1697 		if (atomicio(read, remin, cp, 1) != 1)
1698 			goto done;
1699 		if (*cp++ == '\n')
1700 			SCREWUP("unexpected <newline>");
1701 		do {
1702 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1703 				SCREWUP("lost connection");
1704 			*cp++ = ch;
1705 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1706 		*cp = 0;
1707 		if (verbose_mode)
1708 			fmprintf(stderr, "Sink: %s", buf);
1709 
1710 		if (buf[0] == '\01' || buf[0] == '\02') {
1711 			if (iamremote == 0) {
1712 				(void) snmprintf(visbuf, sizeof(visbuf),
1713 				    NULL, "%s", buf + 1);
1714 				(void) atomicio(vwrite, STDERR_FILENO,
1715 				    visbuf, strlen(visbuf));
1716 			}
1717 			if (buf[0] == '\02')
1718 				exit(1);
1719 			++errs;
1720 			continue;
1721 		}
1722 		if (buf[0] == 'E') {
1723 			(void) atomicio(vwrite, remout, "", 1);
1724 			goto done;
1725 		}
1726 		if (ch == '\n')
1727 			*--cp = 0;
1728 
1729 		cp = buf;
1730 		if (*cp == 'T') {
1731 			setimes++;
1732 			cp++;
1733 			if (!isdigit((unsigned char)*cp))
1734 				SCREWUP("mtime.sec not present");
1735 			ull = strtoull(cp, &cp, 10);
1736 			if (!cp || *cp++ != ' ')
1737 				SCREWUP("mtime.sec not delimited");
1738 			if (TYPE_OVERFLOW(time_t, ull))
1739 				setimes = 0;	/* out of range */
1740 			mtime.tv_sec = ull;
1741 			mtime.tv_usec = strtol(cp, &cp, 10);
1742 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1743 			    mtime.tv_usec > 999999)
1744 				SCREWUP("mtime.usec not delimited");
1745 			if (!isdigit((unsigned char)*cp))
1746 				SCREWUP("atime.sec not present");
1747 			ull = strtoull(cp, &cp, 10);
1748 			if (!cp || *cp++ != ' ')
1749 				SCREWUP("atime.sec not delimited");
1750 			if (TYPE_OVERFLOW(time_t, ull))
1751 				setimes = 0;	/* out of range */
1752 			atime.tv_sec = ull;
1753 			atime.tv_usec = strtol(cp, &cp, 10);
1754 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1755 			    atime.tv_usec > 999999)
1756 				SCREWUP("atime.usec not delimited");
1757 			(void) atomicio(vwrite, remout, "", 1);
1758 			continue;
1759 		}
1760 		if (*cp != 'C' && *cp != 'D') {
1761 			/*
1762 			 * Check for the case "rcp remote:foo\* local:bar".
1763 			 * In this case, the line "No match." can be returned
1764 			 * by the shell before the rcp command on the remote is
1765 			 * executed so the ^Aerror_message convention isn't
1766 			 * followed.
1767 			 */
1768 			if (first) {
1769 				run_err("%s", cp);
1770 				exit(1);
1771 			}
1772 			SCREWUP("expected control record");
1773 		}
1774 		mode = 0;
1775 		for (++cp; cp < buf + 5; cp++) {
1776 			if (*cp < '0' || *cp > '7')
1777 				SCREWUP("bad mode");
1778 			mode = (mode << 3) | (*cp - '0');
1779 		}
1780 		if (!pflag)
1781 			mode &= ~mask;
1782 		if (*cp++ != ' ')
1783 			SCREWUP("mode not delimited");
1784 
1785 		if (!isdigit((unsigned char)*cp))
1786 			SCREWUP("size not present");
1787 		ull = strtoull(cp, &cp, 10);
1788 		if (!cp || *cp++ != ' ')
1789 			SCREWUP("size not delimited");
1790 		if (TYPE_OVERFLOW(off_t, ull))
1791 			SCREWUP("size out of range");
1792 		size = (off_t)ull;
1793 
1794 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1795 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1796 			run_err("error: unexpected filename: %s", cp);
1797 			exit(1);
1798 		}
1799 		if (npatterns > 0) {
1800 			for (n = 0; n < npatterns; n++) {
1801 				if (strcmp(patterns[n], cp) == 0 ||
1802 				    fnmatch(patterns[n], cp, 0) == 0)
1803 					break;
1804 			}
1805 			if (n >= npatterns)
1806 				SCREWUP("filename does not match request");
1807 		}
1808 		if (targisdir) {
1809 			static char *namebuf;
1810 			static size_t cursize;
1811 			size_t need;
1812 
1813 			need = strlen(targ) + strlen(cp) + 250;
1814 			if (need > cursize) {
1815 				free(namebuf);
1816 				namebuf = xmalloc(need);
1817 				cursize = need;
1818 			}
1819 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1820 			    strcmp(targ, "/") ? "/" : "", cp);
1821 			np = namebuf;
1822 		} else
1823 			np = targ;
1824 		curfile = cp;
1825 		exists = stat(np, &stb) == 0;
1826 		if (buf[0] == 'D') {
1827 			int mod_flag = pflag;
1828 			if (!iamrecursive)
1829 				SCREWUP("received directory without -r");
1830 			if (exists) {
1831 				if (!S_ISDIR(stb.st_mode)) {
1832 					errno = ENOTDIR;
1833 					goto bad;
1834 				}
1835 				if (pflag)
1836 					(void) chmod(np, mode);
1837 			} else {
1838 				/* Handle copying from a read-only directory */
1839 				mod_flag = 1;
1840 				if (mkdir(np, mode | S_IRWXU) == -1)
1841 					goto bad;
1842 			}
1843 			vect[0] = xstrdup(np);
1844 			sink(1, vect, src);
1845 			if (setimes) {
1846 				setimes = 0;
1847 				(void) utimes(vect[0], tv);
1848 			}
1849 			if (mod_flag)
1850 				(void) chmod(vect[0], mode);
1851 			free(vect[0]);
1852 			continue;
1853 		}
1854 		omode = mode;
1855 		mode |= S_IWUSR;
1856 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1857 bad:			run_err("%s: %s", np, strerror(errno));
1858 			continue;
1859 		}
1860 		(void) atomicio(vwrite, remout, "", 1);
1861 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1862 			(void) close(ofd);
1863 			continue;
1864 		}
1865 		cp = bp->buf;
1866 		wrerr = 0;
1867 
1868 		/*
1869 		 * NB. do not use run_err() unless immediately followed by
1870 		 * exit() below as it may send a spurious reply that might
1871 		 * desyncronise us from the peer. Use note_err() instead.
1872 		 */
1873 		statbytes = 0;
1874 		if (showprogress)
1875 			start_progress_meter(curfile, size, &statbytes);
1876 		set_nonblock(remin);
1877 		for (count = i = 0; i < size; i += bp->cnt) {
1878 			amt = bp->cnt;
1879 			if (i + amt > size)
1880 				amt = size - i;
1881 			count += amt;
1882 			do {
1883 				j = atomicio6(read, remin, cp, amt,
1884 				    scpio, &statbytes);
1885 				if (j == 0) {
1886 					run_err("%s", j != EPIPE ?
1887 					    strerror(errno) :
1888 					    "dropped connection");
1889 					exit(1);
1890 				}
1891 				amt -= j;
1892 				cp += j;
1893 			} while (amt > 0);
1894 
1895 			if (count == bp->cnt) {
1896 				/* Keep reading so we stay sync'd up. */
1897 				if (!wrerr) {
1898 					if (atomicio(vwrite, ofd, bp->buf,
1899 					    count) != count) {
1900 						note_err("%s: %s", np,
1901 						    strerror(errno));
1902 						wrerr = 1;
1903 					}
1904 				}
1905 				count = 0;
1906 				cp = bp->buf;
1907 			}
1908 		}
1909 		unset_nonblock(remin);
1910 		if (count != 0 && !wrerr &&
1911 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1912 			note_err("%s: %s", np, strerror(errno));
1913 			wrerr = 1;
1914 		}
1915 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1916 		    ftruncate(ofd, size) != 0)
1917 			note_err("%s: truncate: %s", np, strerror(errno));
1918 		if (pflag) {
1919 			if (exists || omode != mode)
1920 #ifdef HAVE_FCHMOD
1921 				if (fchmod(ofd, omode)) {
1922 #else /* HAVE_FCHMOD */
1923 				if (chmod(np, omode)) {
1924 #endif /* HAVE_FCHMOD */
1925 					note_err("%s: set mode: %s",
1926 					    np, strerror(errno));
1927 				}
1928 		} else {
1929 			if (!exists && omode != mode)
1930 #ifdef HAVE_FCHMOD
1931 				if (fchmod(ofd, omode & ~mask)) {
1932 #else /* HAVE_FCHMOD */
1933 				if (chmod(np, omode & ~mask)) {
1934 #endif /* HAVE_FCHMOD */
1935 					note_err("%s: set mode: %s",
1936 					    np, strerror(errno));
1937 				}
1938 		}
1939 		if (close(ofd) == -1)
1940 			note_err("%s: close: %s", np, strerror(errno));
1941 		(void) response();
1942 		if (showprogress)
1943 			stop_progress_meter();
1944 		if (setimes && !wrerr) {
1945 			setimes = 0;
1946 			if (utimes(np, tv) == -1) {
1947 				note_err("%s: set times: %s",
1948 				    np, strerror(errno));
1949 			}
1950 		}
1951 		/* If no error was noted then signal success for this file */
1952 		if (note_err(NULL) == 0)
1953 			(void) atomicio(vwrite, remout, "", 1);
1954 	}
1955 done:
1956 	for (n = 0; n < npatterns; n++)
1957 		free(patterns[n]);
1958 	free(patterns);
1959 	return;
1960 screwup:
1961 	for (n = 0; n < npatterns; n++)
1962 		free(patterns[n]);
1963 	free(patterns);
1964 	run_err("protocol error: %s", why);
1965 	exit(1);
1966 }
1967 
1968 void
1969 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
1970     char *src, char *targ)
1971 {
1972 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1973 	char *abs_src = NULL, *tmp = NULL;
1974 	glob_t g;
1975 	int i, r, targetisdir, err = 0;
1976 
1977 	if ((filename = basename(src)) == NULL)
1978 		fatal("basename %s: %s", src, strerror(errno));
1979 
1980 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
1981 	    (target = prepare_remote_path(to, targ)) == NULL)
1982 		cleanup_exit(255);
1983 	memset(&g, 0, sizeof(g));
1984 
1985 	targetisdir = remote_is_dir(to, target);
1986 	if (!targetisdir && targetshouldbedirectory) {
1987 		error("%s: destination is not a directory", targ);
1988 		err = -1;
1989 		goto out;
1990 	}
1991 
1992 	debug3_f("copying remote %s to remote %s", abs_src, target);
1993 	if ((r = remote_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
1994 	    NULL, &g)) != 0) {
1995 		if (r == GLOB_NOSPACE)
1996 			error("%s: too many glob matches", src);
1997 		else
1998 			error("%s: %s", src, strerror(ENOENT));
1999 		err = -1;
2000 		goto out;
2001 	}
2002 
2003 	/* Did we actually get any matches back from the glob? */
2004 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
2005 		/*
2006 		 * If nothing matched but a path returned, then it's probably
2007 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
2008 		 * exists so we can give a nice error message early.
2009 		 */
2010 		if (do_stat(from, g.gl_pathv[0], 1) == NULL) {
2011 			error("%s: %s", src, strerror(ENOENT));
2012 			err = -1;
2013 			goto out;
2014 		}
2015 	}
2016 
2017 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2018 		tmp = xstrdup(g.gl_pathv[i]);
2019 		if ((filename = basename(tmp)) == NULL) {
2020 			error("basename %s: %s", tmp, strerror(errno));
2021 			err = -1;
2022 			goto out;
2023 		}
2024 
2025 		if (targetisdir)
2026 			abs_dst = path_append(target, filename);
2027 		else
2028 			abs_dst = xstrdup(target);
2029 
2030 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
2031 		if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
2032 			if (crossload_dir(from, to, g.gl_pathv[i], abs_dst,
2033 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
2034 				err = -1;
2035 		} else {
2036 			if (do_crossload(from, to, g.gl_pathv[i], abs_dst, NULL,
2037 			    pflag) == -1)
2038 				err = -1;
2039 		}
2040 		free(abs_dst);
2041 		abs_dst = NULL;
2042 		free(tmp);
2043 		tmp = NULL;
2044 	}
2045 
2046 out:
2047 	free(abs_src);
2048 	free(abs_dst);
2049 	free(target);
2050 	free(tmp);
2051 	globfree(&g);
2052 	if (err == -1)
2053 		errs = 1;
2054 }
2055 
2056 int
2057 response(void)
2058 {
2059 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
2060 
2061 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
2062 		lostconn(0);
2063 
2064 	cp = rbuf;
2065 	switch (resp) {
2066 	case 0:		/* ok */
2067 		return (0);
2068 	default:
2069 		*cp++ = resp;
2070 		/* FALLTHROUGH */
2071 	case 1:		/* error, followed by error msg */
2072 	case 2:		/* fatal error, "" */
2073 		do {
2074 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
2075 				lostconn(0);
2076 			*cp++ = ch;
2077 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
2078 
2079 		if (!iamremote) {
2080 			cp[-1] = '\0';
2081 			(void) snmprintf(visbuf, sizeof(visbuf),
2082 			    NULL, "%s\n", rbuf);
2083 			(void) atomicio(vwrite, STDERR_FILENO,
2084 			    visbuf, strlen(visbuf));
2085 		}
2086 		++errs;
2087 		if (resp == 1)
2088 			return (-1);
2089 		exit(1);
2090 	}
2091 	/* NOTREACHED */
2092 }
2093 
2094 void
2095 usage(void)
2096 {
2097 	(void) fprintf(stderr,
2098 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2099 	    "           [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2100 	    "           [-P port] [-S program] [-X sftp_option] source ... target\n");
2101 	exit(1);
2102 }
2103 
2104 void
2105 run_err(const char *fmt,...)
2106 {
2107 	static FILE *fp;
2108 	va_list ap;
2109 
2110 	++errs;
2111 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2112 		(void) fprintf(fp, "%c", 0x01);
2113 		(void) fprintf(fp, "scp: ");
2114 		va_start(ap, fmt);
2115 		(void) vfprintf(fp, fmt, ap);
2116 		va_end(ap);
2117 		(void) fprintf(fp, "\n");
2118 		(void) fflush(fp);
2119 	}
2120 
2121 	if (!iamremote) {
2122 		va_start(ap, fmt);
2123 		vfmprintf(stderr, fmt, ap);
2124 		va_end(ap);
2125 		fprintf(stderr, "\n");
2126 	}
2127 }
2128 
2129 /*
2130  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2131  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2132  * any active error at the end of the transfer.
2133  */
2134 int
2135 note_err(const char *fmt, ...)
2136 {
2137 	static char *emsg;
2138 	va_list ap;
2139 
2140 	/* Replay any previously-noted error */
2141 	if (fmt == NULL) {
2142 		if (emsg == NULL)
2143 			return 0;
2144 		run_err("%s", emsg);
2145 		free(emsg);
2146 		emsg = NULL;
2147 		return -1;
2148 	}
2149 
2150 	errs++;
2151 	/* Prefer first-noted error */
2152 	if (emsg != NULL)
2153 		return -1;
2154 
2155 	va_start(ap, fmt);
2156 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
2157 	va_end(ap);
2158 	return -1;
2159 }
2160 
2161 void
2162 verifydir(char *cp)
2163 {
2164 	struct stat stb;
2165 
2166 	if (!stat(cp, &stb)) {
2167 		if (S_ISDIR(stb.st_mode))
2168 			return;
2169 		errno = ENOTDIR;
2170 	}
2171 	run_err("%s: %s", cp, strerror(errno));
2172 	killchild(0);
2173 }
2174 
2175 int
2176 okname(char *cp0)
2177 {
2178 	int c;
2179 	char *cp;
2180 
2181 	cp = cp0;
2182 	do {
2183 		c = (int)*cp;
2184 		if (c & 0200)
2185 			goto bad;
2186 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
2187 			switch (c) {
2188 			case '\'':
2189 			case '"':
2190 			case '`':
2191 			case ' ':
2192 			case '#':
2193 				goto bad;
2194 			default:
2195 				break;
2196 			}
2197 		}
2198 	} while (*++cp);
2199 	return (1);
2200 
2201 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
2202 	return (0);
2203 }
2204 
2205 BUF *
2206 allocbuf(BUF *bp, int fd, int blksize)
2207 {
2208 	size_t size;
2209 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2210 	struct stat stb;
2211 
2212 	if (fstat(fd, &stb) == -1) {
2213 		run_err("fstat: %s", strerror(errno));
2214 		return (0);
2215 	}
2216 	size = ROUNDUP(stb.st_blksize, blksize);
2217 	if (size == 0)
2218 		size = blksize;
2219 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2220 	size = blksize;
2221 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2222 	if (bp->cnt >= size)
2223 		return (bp);
2224 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2225 	bp->cnt = size;
2226 	return (bp);
2227 }
2228 
2229 void
2230 lostconn(int signo)
2231 {
2232 	if (!iamremote)
2233 		(void)write(STDERR_FILENO, "lost connection\n", 16);
2234 	if (signo)
2235 		_exit(1);
2236 	else
2237 		exit(1);
2238 }
2239 
2240 void
2241 cleanup_exit(int i)
2242 {
2243 	if (remin > 0)
2244 		close(remin);
2245 	if (remout > 0)
2246 		close(remout);
2247 	if (remin2 > 0)
2248 		close(remin2);
2249 	if (remout2 > 0)
2250 		close(remout2);
2251 	if (do_cmd_pid > 0)
2252 		waitpid(do_cmd_pid, NULL, 0);
2253 	if (do_cmd_pid2 > 0)
2254 		waitpid(do_cmd_pid2, NULL, 0);
2255 	exit(i);
2256 }
2257