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