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