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