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