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