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