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