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