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