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