xref: /openbsd/usr.bin/ssh/scp.c (revision 76d0caae)
1 /* $OpenBSD: scp.c,v 1.241 2021/10/24 21:24:17 deraadt 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, 2);
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, 2);
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 && (mode == MODE_SFTP || 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("sftp connection failed");
1184 				++errs;
1185 				continue;
1186 			}
1187 
1188 			/* The protocol */
1189 			sink_sftp(1, argv[argc - 1], src, conn);
1190 
1191 			free(conn);
1192 			(void) close(remin);
1193 			(void) close(remout);
1194 			remin = remout = -1;
1195 			continue;
1196 		}
1197 		/* SCP */
1198 		xasprintf(&bp, "%s -f %s%s",
1199 		    cmd, *src == '-' ? "-- " : "", src);
1200 		if (do_cmd(ssh_program, host, suser, sport, 0, bp,
1201 		    &remin, &remout, &do_cmd_pid) < 0) {
1202 			free(bp);
1203 			++errs;
1204 			continue;
1205 		}
1206 		free(bp);
1207 		sink(1, argv + argc - 1, src);
1208 		(void) close(remin);
1209 		remin = remout = -1;
1210 	}
1211 	free(suser);
1212 	free(host);
1213 	free(src);
1214 }
1215 
1216 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1217 static char *
1218 prepare_remote_path(struct sftp_conn *conn, const char *path)
1219 {
1220 	/* Handle ~ prefixed paths */
1221 	if (*path != '~')
1222 		return xstrdup(path);
1223 	if (*path == '\0' || strcmp(path, "~") == 0)
1224 		return xstrdup(".");
1225 	if (strncmp(path, "~/", 2) == 0)
1226 		return xstrdup(path + 2);
1227 	if (can_expand_path(conn))
1228 		return do_expand_path(conn, path);
1229 	/* No protocol extension */
1230 	error("server expand-path extension is required "
1231 	    "for ~user paths in SFTP mode");
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 			error("failed to upload directory %s to %s",
1267 				src, abs_dst);
1268 			errs = 1;
1269 		}
1270 	} else if (do_upload(conn, src, abs_dst, pflag, 0, 0) != 0) {
1271 		error("failed to upload file %s to %s", src, abs_dst);
1272 		errs = 1;
1273 	}
1274 
1275 	free(abs_dst);
1276 	free(target);
1277 }
1278 
1279 void
1280 source(int argc, char **argv)
1281 {
1282 	struct stat stb;
1283 	static BUF buffer;
1284 	BUF *bp;
1285 	off_t i, statbytes;
1286 	size_t amt, nr;
1287 	int fd = -1, haderr, indx;
1288 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1289 	int len;
1290 
1291 	for (indx = 0; indx < argc; ++indx) {
1292 		name = argv[indx];
1293 		statbytes = 0;
1294 		len = strlen(name);
1295 		while (len > 1 && name[len-1] == '/')
1296 			name[--len] = '\0';
1297 		if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1298 			goto syserr;
1299 		if (strchr(name, '\n') != NULL) {
1300 			strnvis(encname, name, sizeof(encname), VIS_NL);
1301 			name = encname;
1302 		}
1303 		if (fstat(fd, &stb) == -1) {
1304 syserr:			run_err("%s: %s", name, strerror(errno));
1305 			goto next;
1306 		}
1307 		if (stb.st_size < 0) {
1308 			run_err("%s: %s", name, "Negative file size");
1309 			goto next;
1310 		}
1311 		unset_nonblock(fd);
1312 		switch (stb.st_mode & S_IFMT) {
1313 		case S_IFREG:
1314 			break;
1315 		case S_IFDIR:
1316 			if (iamrecursive) {
1317 				rsource(name, &stb);
1318 				goto next;
1319 			}
1320 			/* FALLTHROUGH */
1321 		default:
1322 			run_err("%s: not a regular file", name);
1323 			goto next;
1324 		}
1325 		if ((last = strrchr(name, '/')) == NULL)
1326 			last = name;
1327 		else
1328 			++last;
1329 		curfile = last;
1330 		if (pflag) {
1331 			if (do_times(remout, verbose_mode, &stb) < 0)
1332 				goto next;
1333 		}
1334 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1335 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1336 		    (u_int) (stb.st_mode & FILEMODEMASK),
1337 		    (long long)stb.st_size, last);
1338 		if (verbose_mode)
1339 			fmprintf(stderr, "Sending file modes: %s", buf);
1340 		(void) atomicio(vwrite, remout, buf, strlen(buf));
1341 		if (response() < 0)
1342 			goto next;
1343 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1344 next:			if (fd != -1) {
1345 				(void) close(fd);
1346 				fd = -1;
1347 			}
1348 			continue;
1349 		}
1350 		if (showprogress)
1351 			start_progress_meter(curfile, stb.st_size, &statbytes);
1352 		set_nonblock(remout);
1353 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1354 			amt = bp->cnt;
1355 			if (i + (off_t)amt > stb.st_size)
1356 				amt = stb.st_size - i;
1357 			if (!haderr) {
1358 				if ((nr = atomicio(read, fd,
1359 				    bp->buf, amt)) != amt) {
1360 					haderr = errno;
1361 					memset(bp->buf + nr, 0, amt - nr);
1362 				}
1363 			}
1364 			/* Keep writing after error to retain sync */
1365 			if (haderr) {
1366 				(void)atomicio(vwrite, remout, bp->buf, amt);
1367 				memset(bp->buf, 0, amt);
1368 				continue;
1369 			}
1370 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1371 			    &statbytes) != amt)
1372 				haderr = errno;
1373 		}
1374 		unset_nonblock(remout);
1375 
1376 		if (fd != -1) {
1377 			if (close(fd) == -1 && !haderr)
1378 				haderr = errno;
1379 			fd = -1;
1380 		}
1381 		if (!haderr)
1382 			(void) atomicio(vwrite, remout, "", 1);
1383 		else
1384 			run_err("%s: %s", name, strerror(haderr));
1385 		(void) response();
1386 		if (showprogress)
1387 			stop_progress_meter();
1388 	}
1389 }
1390 
1391 void
1392 rsource(char *name, struct stat *statp)
1393 {
1394 	DIR *dirp;
1395 	struct dirent *dp;
1396 	char *last, *vect[1], path[PATH_MAX];
1397 
1398 	if (!(dirp = opendir(name))) {
1399 		run_err("%s: %s", name, strerror(errno));
1400 		return;
1401 	}
1402 	last = strrchr(name, '/');
1403 	if (last == NULL)
1404 		last = name;
1405 	else
1406 		last++;
1407 	if (pflag) {
1408 		if (do_times(remout, verbose_mode, statp) < 0) {
1409 			closedir(dirp);
1410 			return;
1411 		}
1412 	}
1413 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1414 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1415 	if (verbose_mode)
1416 		fmprintf(stderr, "Entering directory: %s", path);
1417 	(void) atomicio(vwrite, remout, path, strlen(path));
1418 	if (response() < 0) {
1419 		closedir(dirp);
1420 		return;
1421 	}
1422 	while ((dp = readdir(dirp)) != NULL) {
1423 		if (dp->d_ino == 0)
1424 			continue;
1425 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1426 			continue;
1427 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1428 			run_err("%s/%s: name too long", name, dp->d_name);
1429 			continue;
1430 		}
1431 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1432 		vect[0] = path;
1433 		source(1, vect);
1434 	}
1435 	(void) closedir(dirp);
1436 	(void) atomicio(vwrite, remout, "E\n", 2);
1437 	(void) response();
1438 }
1439 
1440 void
1441 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
1442 {
1443 	char *abs_src = NULL;
1444 	char *abs_dst = NULL;
1445 	glob_t g;
1446 	char *filename, *tmp = NULL;
1447 	int i, r, err = 0;
1448 
1449 	memset(&g, 0, sizeof(g));
1450 	/*
1451 	 * Here, we need remote glob as SFTP can not depend on remote shell
1452 	 * expansions
1453 	 */
1454 
1455 	if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
1456 		err = -1;
1457 		goto out;
1458 	}
1459 
1460 	debug3_f("copying remote %s to local %s", abs_src, dst);
1461 	if ((r = remote_glob(conn, abs_src, GLOB_MARK, NULL, &g)) != 0) {
1462 		if (r == GLOB_NOSPACE)
1463 			error("%s: too many glob matches", abs_src);
1464 		else
1465 			error("%s: %s", abs_src, strerror(ENOENT));
1466 		err = -1;
1467 		goto out;
1468 	}
1469 
1470 	if (g.gl_matchc > 1 && !local_is_dir(dst)) {
1471 		error("Multiple files match pattern, but destination "
1472 		    "\"%s\" is not a directory", dst);
1473 		err = -1;
1474 		goto out;
1475 	}
1476 
1477 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1478 		tmp = xstrdup(g.gl_pathv[i]);
1479 		if ((filename = basename(tmp)) == NULL) {
1480 			error("basename %s: %s", tmp, strerror(errno));
1481 			err = -1;
1482 			goto out;
1483 		}
1484 
1485 		if (local_is_dir(dst))
1486 			abs_dst = path_append(dst, filename);
1487 		else
1488 			abs_dst = xstrdup(dst);
1489 
1490 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1491 		if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1492 			if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL,
1493 			    pflag, SFTP_PROGRESS_ONLY, 0, 0, 1) == -1)
1494 				err = -1;
1495 		} else {
1496 			if (do_download(conn, g.gl_pathv[i], abs_dst, NULL,
1497 			    pflag, 0, 0) == -1)
1498 				err = -1;
1499 		}
1500 		free(abs_dst);
1501 		abs_dst = NULL;
1502 		free(tmp);
1503 		tmp = NULL;
1504 	}
1505 
1506 out:
1507 	free(abs_src);
1508 	free(tmp);
1509 	globfree(&g);
1510 	if (err == -1)
1511 		errs = 1;
1512 }
1513 
1514 
1515 #define TYPE_OVERFLOW(type, val) \
1516 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
1517 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1518 	 (sizeof(type) != 4 && sizeof(type) != 8))
1519 
1520 void
1521 sink(int argc, char **argv, const char *src)
1522 {
1523 	static BUF buffer;
1524 	struct stat stb;
1525 	BUF *bp;
1526 	off_t i;
1527 	size_t j, count;
1528 	int amt, exists, first, ofd;
1529 	mode_t mode, omode, mask;
1530 	off_t size, statbytes;
1531 	unsigned long long ull;
1532 	int setimes, targisdir, wrerr;
1533 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1534 	char **patterns = NULL;
1535 	size_t n, npatterns = 0;
1536 	struct timeval tv[2];
1537 
1538 #define	atime	tv[0]
1539 #define	mtime	tv[1]
1540 #define	SCREWUP(str)	{ why = str; goto screwup; }
1541 
1542 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1543 		SCREWUP("Unexpected off_t/time_t size");
1544 
1545 	setimes = targisdir = 0;
1546 	mask = umask(0);
1547 	if (!pflag)
1548 		(void) umask(mask);
1549 	if (argc != 1) {
1550 		run_err("ambiguous target");
1551 		exit(1);
1552 	}
1553 	targ = *argv;
1554 	if (targetshouldbedirectory)
1555 		verifydir(targ);
1556 
1557 	(void) atomicio(vwrite, remout, "", 1);
1558 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1559 		targisdir = 1;
1560 	if (src != NULL && !iamrecursive && !Tflag) {
1561 		/*
1562 		 * Prepare to try to restrict incoming filenames to match
1563 		 * the requested destination file glob.
1564 		 */
1565 		if (brace_expand(src, &patterns, &npatterns) != 0)
1566 			fatal_f("could not expand pattern");
1567 	}
1568 	for (first = 1;; first = 0) {
1569 		cp = buf;
1570 		if (atomicio(read, remin, cp, 1) != 1)
1571 			goto done;
1572 		if (*cp++ == '\n')
1573 			SCREWUP("unexpected <newline>");
1574 		do {
1575 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1576 				SCREWUP("lost connection");
1577 			*cp++ = ch;
1578 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1579 		*cp = 0;
1580 		if (verbose_mode)
1581 			fmprintf(stderr, "Sink: %s", buf);
1582 
1583 		if (buf[0] == '\01' || buf[0] == '\02') {
1584 			if (iamremote == 0) {
1585 				(void) snmprintf(visbuf, sizeof(visbuf),
1586 				    NULL, "%s", buf + 1);
1587 				(void) atomicio(vwrite, STDERR_FILENO,
1588 				    visbuf, strlen(visbuf));
1589 			}
1590 			if (buf[0] == '\02')
1591 				exit(1);
1592 			++errs;
1593 			continue;
1594 		}
1595 		if (buf[0] == 'E') {
1596 			(void) atomicio(vwrite, remout, "", 1);
1597 			goto done;
1598 		}
1599 		if (ch == '\n')
1600 			*--cp = 0;
1601 
1602 		cp = buf;
1603 		if (*cp == 'T') {
1604 			setimes++;
1605 			cp++;
1606 			if (!isdigit((unsigned char)*cp))
1607 				SCREWUP("mtime.sec not present");
1608 			ull = strtoull(cp, &cp, 10);
1609 			if (!cp || *cp++ != ' ')
1610 				SCREWUP("mtime.sec not delimited");
1611 			if (TYPE_OVERFLOW(time_t, ull))
1612 				setimes = 0;	/* out of range */
1613 			mtime.tv_sec = ull;
1614 			mtime.tv_usec = strtol(cp, &cp, 10);
1615 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1616 			    mtime.tv_usec > 999999)
1617 				SCREWUP("mtime.usec not delimited");
1618 			if (!isdigit((unsigned char)*cp))
1619 				SCREWUP("atime.sec not present");
1620 			ull = strtoull(cp, &cp, 10);
1621 			if (!cp || *cp++ != ' ')
1622 				SCREWUP("atime.sec not delimited");
1623 			if (TYPE_OVERFLOW(time_t, ull))
1624 				setimes = 0;	/* out of range */
1625 			atime.tv_sec = ull;
1626 			atime.tv_usec = strtol(cp, &cp, 10);
1627 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1628 			    atime.tv_usec > 999999)
1629 				SCREWUP("atime.usec not delimited");
1630 			(void) atomicio(vwrite, remout, "", 1);
1631 			continue;
1632 		}
1633 		if (*cp != 'C' && *cp != 'D') {
1634 			/*
1635 			 * Check for the case "rcp remote:foo\* local:bar".
1636 			 * In this case, the line "No match." can be returned
1637 			 * by the shell before the rcp command on the remote is
1638 			 * executed so the ^Aerror_message convention isn't
1639 			 * followed.
1640 			 */
1641 			if (first) {
1642 				run_err("%s", cp);
1643 				exit(1);
1644 			}
1645 			SCREWUP("expected control record");
1646 		}
1647 		mode = 0;
1648 		for (++cp; cp < buf + 5; cp++) {
1649 			if (*cp < '0' || *cp > '7')
1650 				SCREWUP("bad mode");
1651 			mode = (mode << 3) | (*cp - '0');
1652 		}
1653 		if (!pflag)
1654 			mode &= ~mask;
1655 		if (*cp++ != ' ')
1656 			SCREWUP("mode not delimited");
1657 
1658 		if (!isdigit((unsigned char)*cp))
1659 			SCREWUP("size not present");
1660 		ull = strtoull(cp, &cp, 10);
1661 		if (!cp || *cp++ != ' ')
1662 			SCREWUP("size not delimited");
1663 		if (TYPE_OVERFLOW(off_t, ull))
1664 			SCREWUP("size out of range");
1665 		size = (off_t)ull;
1666 
1667 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1668 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1669 			run_err("error: unexpected filename: %s", cp);
1670 			exit(1);
1671 		}
1672 		if (npatterns > 0) {
1673 			for (n = 0; n < npatterns; n++) {
1674 				if (fnmatch(patterns[n], cp, 0) == 0)
1675 					break;
1676 			}
1677 			if (n >= npatterns)
1678 				SCREWUP("filename does not match request");
1679 		}
1680 		if (targisdir) {
1681 			static char *namebuf;
1682 			static size_t cursize;
1683 			size_t need;
1684 
1685 			need = strlen(targ) + strlen(cp) + 250;
1686 			if (need > cursize) {
1687 				free(namebuf);
1688 				namebuf = xmalloc(need);
1689 				cursize = need;
1690 			}
1691 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1692 			    strcmp(targ, "/") ? "/" : "", cp);
1693 			np = namebuf;
1694 		} else
1695 			np = targ;
1696 		curfile = cp;
1697 		exists = stat(np, &stb) == 0;
1698 		if (buf[0] == 'D') {
1699 			int mod_flag = pflag;
1700 			if (!iamrecursive)
1701 				SCREWUP("received directory without -r");
1702 			if (exists) {
1703 				if (!S_ISDIR(stb.st_mode)) {
1704 					errno = ENOTDIR;
1705 					goto bad;
1706 				}
1707 				if (pflag)
1708 					(void) chmod(np, mode);
1709 			} else {
1710 				/* Handle copying from a read-only directory */
1711 				mod_flag = 1;
1712 				if (mkdir(np, mode | S_IRWXU) == -1)
1713 					goto bad;
1714 			}
1715 			vect[0] = xstrdup(np);
1716 			sink(1, vect, src);
1717 			if (setimes) {
1718 				setimes = 0;
1719 				(void) utimes(vect[0], tv);
1720 			}
1721 			if (mod_flag)
1722 				(void) chmod(vect[0], mode);
1723 			free(vect[0]);
1724 			continue;
1725 		}
1726 		omode = mode;
1727 		mode |= S_IWUSR;
1728 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1729 bad:			run_err("%s: %s", np, strerror(errno));
1730 			continue;
1731 		}
1732 		(void) atomicio(vwrite, remout, "", 1);
1733 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1734 			(void) close(ofd);
1735 			continue;
1736 		}
1737 		cp = bp->buf;
1738 		wrerr = 0;
1739 
1740 		/*
1741 		 * NB. do not use run_err() unless immediately followed by
1742 		 * exit() below as it may send a spurious reply that might
1743 		 * desyncronise us from the peer. Use note_err() instead.
1744 		 */
1745 		statbytes = 0;
1746 		if (showprogress)
1747 			start_progress_meter(curfile, size, &statbytes);
1748 		set_nonblock(remin);
1749 		for (count = i = 0; i < size; i += bp->cnt) {
1750 			amt = bp->cnt;
1751 			if (i + amt > size)
1752 				amt = size - i;
1753 			count += amt;
1754 			do {
1755 				j = atomicio6(read, remin, cp, amt,
1756 				    scpio, &statbytes);
1757 				if (j == 0) {
1758 					run_err("%s", j != EPIPE ?
1759 					    strerror(errno) :
1760 					    "dropped connection");
1761 					exit(1);
1762 				}
1763 				amt -= j;
1764 				cp += j;
1765 			} while (amt > 0);
1766 
1767 			if (count == bp->cnt) {
1768 				/* Keep reading so we stay sync'd up. */
1769 				if (!wrerr) {
1770 					if (atomicio(vwrite, ofd, bp->buf,
1771 					    count) != count) {
1772 						note_err("%s: %s", np,
1773 						    strerror(errno));
1774 						wrerr = 1;
1775 					}
1776 				}
1777 				count = 0;
1778 				cp = bp->buf;
1779 			}
1780 		}
1781 		unset_nonblock(remin);
1782 		if (count != 0 && !wrerr &&
1783 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1784 			note_err("%s: %s", np, strerror(errno));
1785 			wrerr = 1;
1786 		}
1787 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1788 		    ftruncate(ofd, size) != 0)
1789 			note_err("%s: truncate: %s", np, strerror(errno));
1790 		if (pflag) {
1791 			if (exists || omode != mode)
1792 				if (fchmod(ofd, omode)) {
1793 					note_err("%s: set mode: %s",
1794 					    np, strerror(errno));
1795 				}
1796 		} else {
1797 			if (!exists && omode != mode)
1798 				if (fchmod(ofd, omode & ~mask)) {
1799 					note_err("%s: set mode: %s",
1800 					    np, strerror(errno));
1801 				}
1802 		}
1803 		if (close(ofd) == -1)
1804 			note_err("%s: close: %s", np, strerror(errno));
1805 		(void) response();
1806 		if (showprogress)
1807 			stop_progress_meter();
1808 		if (setimes && !wrerr) {
1809 			setimes = 0;
1810 			if (utimes(np, tv) == -1) {
1811 				note_err("%s: set times: %s",
1812 				    np, strerror(errno));
1813 			}
1814 		}
1815 		/* If no error was noted then signal success for this file */
1816 		if (note_err(NULL) == 0)
1817 			(void) atomicio(vwrite, remout, "", 1);
1818 	}
1819 done:
1820 	for (n = 0; n < npatterns; n++)
1821 		free(patterns[n]);
1822 	free(patterns);
1823 	return;
1824 screwup:
1825 	for (n = 0; n < npatterns; n++)
1826 		free(patterns[n]);
1827 	free(patterns);
1828 	run_err("protocol error: %s", why);
1829 	exit(1);
1830 }
1831 
1832 void
1833 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
1834     char *src, char *targ)
1835 {
1836 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1837 	char *abs_src = NULL, *tmp = NULL;
1838 	glob_t g;
1839 	int i, r, targetisdir, err = 0;
1840 
1841 	if ((filename = basename(src)) == NULL)
1842 		fatal("basename %s: %s", src, strerror(errno));
1843 
1844 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
1845 	    (target = prepare_remote_path(to, targ)) == NULL)
1846 		cleanup_exit(255);
1847 	memset(&g, 0, sizeof(g));
1848 
1849 	targetisdir = remote_is_dir(to, target);
1850 	if (!targetisdir && targetshouldbedirectory) {
1851 		error("%s: destination is not a directory", target);
1852 		err = -1;
1853 		goto out;
1854 	}
1855 
1856 	debug3_f("copying remote %s to remote %s", abs_src, target);
1857 	if ((r = remote_glob(from, abs_src, GLOB_MARK, NULL, &g)) != 0) {
1858 		if (r == GLOB_NOSPACE)
1859 			error("%s: too many glob matches", abs_src);
1860 		else
1861 			error("%s: %s", abs_src, strerror(ENOENT));
1862 		err = -1;
1863 		goto out;
1864 	}
1865 
1866 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1867 		tmp = xstrdup(g.gl_pathv[i]);
1868 		if ((filename = basename(tmp)) == NULL) {
1869 			error("basename %s: %s", tmp, strerror(errno));
1870 			err = -1;
1871 			goto out;
1872 		}
1873 
1874 		if (targetisdir)
1875 			abs_dst = path_append(target, filename);
1876 		else
1877 			abs_dst = xstrdup(target);
1878 
1879 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1880 		if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1881 			if (crossload_dir(from, to, g.gl_pathv[i], abs_dst,
1882 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
1883 				err = -1;
1884 		} else {
1885 			if (do_crossload(from, to, g.gl_pathv[i], abs_dst, NULL,
1886 			    pflag) == -1)
1887 				err = -1;
1888 		}
1889 		free(abs_dst);
1890 		abs_dst = NULL;
1891 		free(tmp);
1892 		tmp = NULL;
1893 	}
1894 
1895 out:
1896 	free(abs_src);
1897 	free(abs_dst);
1898 	free(target);
1899 	free(tmp);
1900 	globfree(&g);
1901 	if (err == -1)
1902 		errs = 1;
1903 }
1904 
1905 int
1906 response(void)
1907 {
1908 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
1909 
1910 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1911 		lostconn(0);
1912 
1913 	cp = rbuf;
1914 	switch (resp) {
1915 	case 0:		/* ok */
1916 		return (0);
1917 	default:
1918 		*cp++ = resp;
1919 		/* FALLTHROUGH */
1920 	case 1:		/* error, followed by error msg */
1921 	case 2:		/* fatal error, "" */
1922 		do {
1923 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1924 				lostconn(0);
1925 			*cp++ = ch;
1926 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1927 
1928 		if (!iamremote) {
1929 			cp[-1] = '\0';
1930 			(void) snmprintf(visbuf, sizeof(visbuf),
1931 			    NULL, "%s\n", rbuf);
1932 			(void) atomicio(vwrite, STDERR_FILENO,
1933 			    visbuf, strlen(visbuf));
1934 		}
1935 		++errs;
1936 		if (resp == 1)
1937 			return (-1);
1938 		exit(1);
1939 	}
1940 	/* NOTREACHED */
1941 }
1942 
1943 void
1944 usage(void)
1945 {
1946 	(void) fprintf(stderr,
1947 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
1948 	    "           [-i identity_file] [-J destination] [-l limit]\n"
1949 	    "           [-o ssh_option] [-P port] [-S program] source ... target\n");
1950 	exit(1);
1951 }
1952 
1953 void
1954 run_err(const char *fmt,...)
1955 {
1956 	static FILE *fp;
1957 	va_list ap;
1958 
1959 	++errs;
1960 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1961 		(void) fprintf(fp, "%c", 0x01);
1962 		(void) fprintf(fp, "scp: ");
1963 		va_start(ap, fmt);
1964 		(void) vfprintf(fp, fmt, ap);
1965 		va_end(ap);
1966 		(void) fprintf(fp, "\n");
1967 		(void) fflush(fp);
1968 	}
1969 
1970 	if (!iamremote) {
1971 		va_start(ap, fmt);
1972 		vfmprintf(stderr, fmt, ap);
1973 		va_end(ap);
1974 		fprintf(stderr, "\n");
1975 	}
1976 }
1977 
1978 /*
1979  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
1980  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
1981  * any active error at the end of the transfer.
1982  */
1983 int
1984 note_err(const char *fmt, ...)
1985 {
1986 	static char *emsg;
1987 	va_list ap;
1988 
1989 	/* Replay any previously-noted error */
1990 	if (fmt == NULL) {
1991 		if (emsg == NULL)
1992 			return 0;
1993 		run_err("%s", emsg);
1994 		free(emsg);
1995 		emsg = NULL;
1996 		return -1;
1997 	}
1998 
1999 	errs++;
2000 	/* Prefer first-noted error */
2001 	if (emsg != NULL)
2002 		return -1;
2003 
2004 	va_start(ap, fmt);
2005 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
2006 	va_end(ap);
2007 	return -1;
2008 }
2009 
2010 void
2011 verifydir(char *cp)
2012 {
2013 	struct stat stb;
2014 
2015 	if (!stat(cp, &stb)) {
2016 		if (S_ISDIR(stb.st_mode))
2017 			return;
2018 		errno = ENOTDIR;
2019 	}
2020 	run_err("%s: %s", cp, strerror(errno));
2021 	killchild(0);
2022 }
2023 
2024 int
2025 okname(char *cp0)
2026 {
2027 	int c;
2028 	char *cp;
2029 
2030 	cp = cp0;
2031 	do {
2032 		c = (int)*cp;
2033 		if (c & 0200)
2034 			goto bad;
2035 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
2036 			switch (c) {
2037 			case '\'':
2038 			case '"':
2039 			case '`':
2040 			case ' ':
2041 			case '#':
2042 				goto bad;
2043 			default:
2044 				break;
2045 			}
2046 		}
2047 	} while (*++cp);
2048 	return (1);
2049 
2050 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
2051 	return (0);
2052 }
2053 
2054 BUF *
2055 allocbuf(BUF *bp, int fd, int blksize)
2056 {
2057 	size_t size;
2058 	struct stat stb;
2059 
2060 	if (fstat(fd, &stb) == -1) {
2061 		run_err("fstat: %s", strerror(errno));
2062 		return (0);
2063 	}
2064 	size = ROUNDUP(stb.st_blksize, blksize);
2065 	if (size == 0)
2066 		size = blksize;
2067 	if (bp->cnt >= size)
2068 		return (bp);
2069 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2070 	bp->cnt = size;
2071 	return (bp);
2072 }
2073 
2074 void
2075 lostconn(int signo)
2076 {
2077 	if (!iamremote)
2078 		(void)write(STDERR_FILENO, "lost connection\n", 16);
2079 	if (signo)
2080 		_exit(1);
2081 	else
2082 		exit(1);
2083 }
2084 
2085 void
2086 cleanup_exit(int i)
2087 {
2088 	if (remin > 0)
2089 		close(remin);
2090 	if (remout > 0)
2091 		close(remout);
2092 	if (remin2 > 0)
2093 		close(remin2);
2094 	if (remout2 > 0)
2095 		close(remout2);
2096 	if (do_cmd_pid > 0)
2097 		waitpid(do_cmd_pid, NULL, 0);
2098 	if (do_cmd_pid2 > 0)
2099 		waitpid(do_cmd_pid2, NULL, 0);
2100 	exit(i);
2101 }
2102