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