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