xref: /openbsd-src/usr.bin/ssh/scp.c (revision fcde59b201a29a2b4570b00b71e7aa25d61cb5c1)
1 /* $OpenBSD: scp.c,v 1.213 2020/10/18 11:32:01 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 	if (tuser != NULL && !okname(tuser)) {
892 		++errs;
893 		goto out;
894 	}
895 
896 	/* Parse source files */
897 	for (i = 0; i < argc - 1; i++) {
898 		free(suser);
899 		free(host);
900 		free(src);
901 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
902 		if (r == -1) {
903 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
904 			++errs;
905 			continue;
906 		}
907 		if (r != 0) {
908 			parse_user_host_path(argv[i], &suser, &host, &src);
909 		}
910 		if (suser != NULL && !okname(suser)) {
911 			++errs;
912 			continue;
913 		}
914 		if (host && throughlocal) {	/* extended remote to remote */
915 			xasprintf(&bp, "%s -f %s%s", cmd,
916 			    *src == '-' ? "-- " : "", src);
917 			if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
918 				exit(1);
919 			free(bp);
920 			xasprintf(&bp, "%s -t %s%s", cmd,
921 			    *targ == '-' ? "-- " : "", targ);
922 			if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
923 				exit(1);
924 			free(bp);
925 			(void) close(remin);
926 			(void) close(remout);
927 			remin = remout = -1;
928 		} else if (host) {	/* standard remote to remote */
929 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
930 				/* This would require the remote support URIs */
931 				fatal("target port not supported with two "
932 				    "remote hosts without the -3 option");
933 			}
934 
935 			freeargs(&alist);
936 			addargs(&alist, "%s", ssh_program);
937 			addargs(&alist, "-x");
938 			addargs(&alist, "-oClearAllForwardings=yes");
939 			addargs(&alist, "-n");
940 			for (j = 0; j < remote_remote_args.num; j++) {
941 				addargs(&alist, "%s",
942 				    remote_remote_args.list[j]);
943 			}
944 
945 			if (sport != -1) {
946 				addargs(&alist, "-p");
947 				addargs(&alist, "%d", sport);
948 			}
949 			if (suser) {
950 				addargs(&alist, "-l");
951 				addargs(&alist, "%s", suser);
952 			}
953 			addargs(&alist, "--");
954 			addargs(&alist, "%s", host);
955 			addargs(&alist, "%s", cmd);
956 			addargs(&alist, "%s", src);
957 			addargs(&alist, "%s%s%s:%s",
958 			    tuser ? tuser : "", tuser ? "@" : "",
959 			    thost, targ);
960 			if (do_local_cmd(&alist) != 0)
961 				errs = 1;
962 		} else {	/* local to remote */
963 			if (remin == -1) {
964 				xasprintf(&bp, "%s -t %s%s", cmd,
965 				    *targ == '-' ? "-- " : "", targ);
966 				if (do_cmd(thost, tuser, tport, bp, &remin,
967 				    &remout) < 0)
968 					exit(1);
969 				if (response() < 0)
970 					exit(1);
971 				free(bp);
972 			}
973 			source(1, argv + i);
974 		}
975 	}
976 out:
977 	free(tuser);
978 	free(thost);
979 	free(targ);
980 	free(suser);
981 	free(host);
982 	free(src);
983 }
984 
985 void
986 tolocal(int argc, char **argv)
987 {
988 	char *bp, *host = NULL, *src = NULL, *suser = NULL;
989 	arglist alist;
990 	int i, r, sport = -1;
991 
992 	memset(&alist, '\0', sizeof(alist));
993 	alist.list = NULL;
994 
995 	for (i = 0; i < argc - 1; i++) {
996 		free(suser);
997 		free(host);
998 		free(src);
999 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1000 		if (r == -1) {
1001 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1002 			++errs;
1003 			continue;
1004 		}
1005 		if (r != 0)
1006 			parse_user_host_path(argv[i], &suser, &host, &src);
1007 		if (suser != NULL && !okname(suser)) {
1008 			++errs;
1009 			continue;
1010 		}
1011 		if (!host) {	/* Local to local. */
1012 			freeargs(&alist);
1013 			addargs(&alist, "%s", _PATH_CP);
1014 			if (iamrecursive)
1015 				addargs(&alist, "-r");
1016 			if (pflag)
1017 				addargs(&alist, "-p");
1018 			addargs(&alist, "--");
1019 			addargs(&alist, "%s", argv[i]);
1020 			addargs(&alist, "%s", argv[argc-1]);
1021 			if (do_local_cmd(&alist))
1022 				++errs;
1023 			continue;
1024 		}
1025 		/* Remote to local. */
1026 		xasprintf(&bp, "%s -f %s%s",
1027 		    cmd, *src == '-' ? "-- " : "", src);
1028 		if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
1029 			free(bp);
1030 			++errs;
1031 			continue;
1032 		}
1033 		free(bp);
1034 		sink(1, argv + argc - 1, src);
1035 		(void) close(remin);
1036 		remin = remout = -1;
1037 	}
1038 	free(suser);
1039 	free(host);
1040 	free(src);
1041 }
1042 
1043 void
1044 source(int argc, char **argv)
1045 {
1046 	struct stat stb;
1047 	static BUF buffer;
1048 	BUF *bp;
1049 	off_t i, statbytes;
1050 	size_t amt, nr;
1051 	int fd = -1, haderr, indx;
1052 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1053 	int len;
1054 
1055 	for (indx = 0; indx < argc; ++indx) {
1056 		name = argv[indx];
1057 		statbytes = 0;
1058 		len = strlen(name);
1059 		while (len > 1 && name[len-1] == '/')
1060 			name[--len] = '\0';
1061 		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) == -1)
1062 			goto syserr;
1063 		if (strchr(name, '\n') != NULL) {
1064 			strnvis(encname, name, sizeof(encname), VIS_NL);
1065 			name = encname;
1066 		}
1067 		if (fstat(fd, &stb) == -1) {
1068 syserr:			run_err("%s: %s", name, strerror(errno));
1069 			goto next;
1070 		}
1071 		if (stb.st_size < 0) {
1072 			run_err("%s: %s", name, "Negative file size");
1073 			goto next;
1074 		}
1075 		unset_nonblock(fd);
1076 		switch (stb.st_mode & S_IFMT) {
1077 		case S_IFREG:
1078 			break;
1079 		case S_IFDIR:
1080 			if (iamrecursive) {
1081 				rsource(name, &stb);
1082 				goto next;
1083 			}
1084 			/* FALLTHROUGH */
1085 		default:
1086 			run_err("%s: not a regular file", name);
1087 			goto next;
1088 		}
1089 		if ((last = strrchr(name, '/')) == NULL)
1090 			last = name;
1091 		else
1092 			++last;
1093 		curfile = last;
1094 		if (pflag) {
1095 			if (do_times(remout, verbose_mode, &stb) < 0)
1096 				goto next;
1097 		}
1098 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1099 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1100 		    (u_int) (stb.st_mode & FILEMODEMASK),
1101 		    (long long)stb.st_size, last);
1102 		if (verbose_mode)
1103 			fmprintf(stderr, "Sending file modes: %s", buf);
1104 		(void) atomicio(vwrite, remout, buf, strlen(buf));
1105 		if (response() < 0)
1106 			goto next;
1107 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1108 next:			if (fd != -1) {
1109 				(void) close(fd);
1110 				fd = -1;
1111 			}
1112 			continue;
1113 		}
1114 		if (showprogress)
1115 			start_progress_meter(curfile, stb.st_size, &statbytes);
1116 		set_nonblock(remout);
1117 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1118 			amt = bp->cnt;
1119 			if (i + (off_t)amt > stb.st_size)
1120 				amt = stb.st_size - i;
1121 			if (!haderr) {
1122 				if ((nr = atomicio(read, fd,
1123 				    bp->buf, amt)) != amt) {
1124 					haderr = errno;
1125 					memset(bp->buf + nr, 0, amt - nr);
1126 				}
1127 			}
1128 			/* Keep writing after error to retain sync */
1129 			if (haderr) {
1130 				(void)atomicio(vwrite, remout, bp->buf, amt);
1131 				memset(bp->buf, 0, amt);
1132 				continue;
1133 			}
1134 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1135 			    &statbytes) != amt)
1136 				haderr = errno;
1137 		}
1138 		unset_nonblock(remout);
1139 
1140 		if (fd != -1) {
1141 			if (close(fd) == -1 && !haderr)
1142 				haderr = errno;
1143 			fd = -1;
1144 		}
1145 		if (!haderr)
1146 			(void) atomicio(vwrite, remout, "", 1);
1147 		else
1148 			run_err("%s: %s", name, strerror(haderr));
1149 		(void) response();
1150 		if (showprogress)
1151 			stop_progress_meter();
1152 	}
1153 }
1154 
1155 void
1156 rsource(char *name, struct stat *statp)
1157 {
1158 	DIR *dirp;
1159 	struct dirent *dp;
1160 	char *last, *vect[1], path[PATH_MAX];
1161 
1162 	if (!(dirp = opendir(name))) {
1163 		run_err("%s: %s", name, strerror(errno));
1164 		return;
1165 	}
1166 	last = strrchr(name, '/');
1167 	if (last == NULL)
1168 		last = name;
1169 	else
1170 		last++;
1171 	if (pflag) {
1172 		if (do_times(remout, verbose_mode, statp) < 0) {
1173 			closedir(dirp);
1174 			return;
1175 		}
1176 	}
1177 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1178 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1179 	if (verbose_mode)
1180 		fmprintf(stderr, "Entering directory: %s", path);
1181 	(void) atomicio(vwrite, remout, path, strlen(path));
1182 	if (response() < 0) {
1183 		closedir(dirp);
1184 		return;
1185 	}
1186 	while ((dp = readdir(dirp)) != NULL) {
1187 		if (dp->d_ino == 0)
1188 			continue;
1189 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1190 			continue;
1191 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1192 			run_err("%s/%s: name too long", name, dp->d_name);
1193 			continue;
1194 		}
1195 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1196 		vect[0] = path;
1197 		source(1, vect);
1198 	}
1199 	(void) closedir(dirp);
1200 	(void) atomicio(vwrite, remout, "E\n", 2);
1201 	(void) response();
1202 }
1203 
1204 #define TYPE_OVERFLOW(type, val) \
1205 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
1206 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1207 	 (sizeof(type) != 4 && sizeof(type) != 8))
1208 
1209 void
1210 sink(int argc, char **argv, const char *src)
1211 {
1212 	static BUF buffer;
1213 	struct stat stb;
1214 	BUF *bp;
1215 	off_t i;
1216 	size_t j, count;
1217 	int amt, exists, first, ofd;
1218 	mode_t mode, omode, mask;
1219 	off_t size, statbytes;
1220 	unsigned long long ull;
1221 	int setimes, targisdir, wrerr;
1222 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1223 	char **patterns = NULL;
1224 	size_t n, npatterns = 0;
1225 	struct timeval tv[2];
1226 
1227 #define	atime	tv[0]
1228 #define	mtime	tv[1]
1229 #define	SCREWUP(str)	{ why = str; goto screwup; }
1230 
1231 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1232 		SCREWUP("Unexpected off_t/time_t size");
1233 
1234 	setimes = targisdir = 0;
1235 	mask = umask(0);
1236 	if (!pflag)
1237 		(void) umask(mask);
1238 	if (argc != 1) {
1239 		run_err("ambiguous target");
1240 		exit(1);
1241 	}
1242 	targ = *argv;
1243 	if (targetshouldbedirectory)
1244 		verifydir(targ);
1245 
1246 	(void) atomicio(vwrite, remout, "", 1);
1247 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1248 		targisdir = 1;
1249 	if (src != NULL && !iamrecursive && !Tflag) {
1250 		/*
1251 		 * Prepare to try to restrict incoming filenames to match
1252 		 * the requested destination file glob.
1253 		 */
1254 		if (brace_expand(src, &patterns, &npatterns) != 0)
1255 			fatal_f("could not expand pattern");
1256 	}
1257 	for (first = 1;; first = 0) {
1258 		cp = buf;
1259 		if (atomicio(read, remin, cp, 1) != 1)
1260 			goto done;
1261 		if (*cp++ == '\n')
1262 			SCREWUP("unexpected <newline>");
1263 		do {
1264 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1265 				SCREWUP("lost connection");
1266 			*cp++ = ch;
1267 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1268 		*cp = 0;
1269 		if (verbose_mode)
1270 			fmprintf(stderr, "Sink: %s", buf);
1271 
1272 		if (buf[0] == '\01' || buf[0] == '\02') {
1273 			if (iamremote == 0) {
1274 				(void) snmprintf(visbuf, sizeof(visbuf),
1275 				    NULL, "%s", buf + 1);
1276 				(void) atomicio(vwrite, STDERR_FILENO,
1277 				    visbuf, strlen(visbuf));
1278 			}
1279 			if (buf[0] == '\02')
1280 				exit(1);
1281 			++errs;
1282 			continue;
1283 		}
1284 		if (buf[0] == 'E') {
1285 			(void) atomicio(vwrite, remout, "", 1);
1286 			goto done;
1287 		}
1288 		if (ch == '\n')
1289 			*--cp = 0;
1290 
1291 		cp = buf;
1292 		if (*cp == 'T') {
1293 			setimes++;
1294 			cp++;
1295 			if (!isdigit((unsigned char)*cp))
1296 				SCREWUP("mtime.sec not present");
1297 			ull = strtoull(cp, &cp, 10);
1298 			if (!cp || *cp++ != ' ')
1299 				SCREWUP("mtime.sec not delimited");
1300 			if (TYPE_OVERFLOW(time_t, ull))
1301 				setimes = 0;	/* out of range */
1302 			mtime.tv_sec = ull;
1303 			mtime.tv_usec = strtol(cp, &cp, 10);
1304 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1305 			    mtime.tv_usec > 999999)
1306 				SCREWUP("mtime.usec not delimited");
1307 			if (!isdigit((unsigned char)*cp))
1308 				SCREWUP("atime.sec not present");
1309 			ull = strtoull(cp, &cp, 10);
1310 			if (!cp || *cp++ != ' ')
1311 				SCREWUP("atime.sec not delimited");
1312 			if (TYPE_OVERFLOW(time_t, ull))
1313 				setimes = 0;	/* out of range */
1314 			atime.tv_sec = ull;
1315 			atime.tv_usec = strtol(cp, &cp, 10);
1316 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1317 			    atime.tv_usec > 999999)
1318 				SCREWUP("atime.usec not delimited");
1319 			(void) atomicio(vwrite, remout, "", 1);
1320 			continue;
1321 		}
1322 		if (*cp != 'C' && *cp != 'D') {
1323 			/*
1324 			 * Check for the case "rcp remote:foo\* local:bar".
1325 			 * In this case, the line "No match." can be returned
1326 			 * by the shell before the rcp command on the remote is
1327 			 * executed so the ^Aerror_message convention isn't
1328 			 * followed.
1329 			 */
1330 			if (first) {
1331 				run_err("%s", cp);
1332 				exit(1);
1333 			}
1334 			SCREWUP("expected control record");
1335 		}
1336 		mode = 0;
1337 		for (++cp; cp < buf + 5; cp++) {
1338 			if (*cp < '0' || *cp > '7')
1339 				SCREWUP("bad mode");
1340 			mode = (mode << 3) | (*cp - '0');
1341 		}
1342 		if (!pflag)
1343 			mode &= ~mask;
1344 		if (*cp++ != ' ')
1345 			SCREWUP("mode not delimited");
1346 
1347 		if (!isdigit((unsigned char)*cp))
1348 			SCREWUP("size not present");
1349 		ull = strtoull(cp, &cp, 10);
1350 		if (!cp || *cp++ != ' ')
1351 			SCREWUP("size not delimited");
1352 		if (TYPE_OVERFLOW(off_t, ull))
1353 			SCREWUP("size out of range");
1354 		size = (off_t)ull;
1355 
1356 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1357 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1358 			run_err("error: unexpected filename: %s", cp);
1359 			exit(1);
1360 		}
1361 		if (npatterns > 0) {
1362 			for (n = 0; n < npatterns; n++) {
1363 				if (fnmatch(patterns[n], cp, 0) == 0)
1364 					break;
1365 			}
1366 			if (n >= npatterns)
1367 				SCREWUP("filename does not match request");
1368 		}
1369 		if (targisdir) {
1370 			static char *namebuf;
1371 			static size_t cursize;
1372 			size_t need;
1373 
1374 			need = strlen(targ) + strlen(cp) + 250;
1375 			if (need > cursize) {
1376 				free(namebuf);
1377 				namebuf = xmalloc(need);
1378 				cursize = need;
1379 			}
1380 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1381 			    strcmp(targ, "/") ? "/" : "", cp);
1382 			np = namebuf;
1383 		} else
1384 			np = targ;
1385 		curfile = cp;
1386 		exists = stat(np, &stb) == 0;
1387 		if (buf[0] == 'D') {
1388 			int mod_flag = pflag;
1389 			if (!iamrecursive)
1390 				SCREWUP("received directory without -r");
1391 			if (exists) {
1392 				if (!S_ISDIR(stb.st_mode)) {
1393 					errno = ENOTDIR;
1394 					goto bad;
1395 				}
1396 				if (pflag)
1397 					(void) chmod(np, mode);
1398 			} else {
1399 				/* Handle copying from a read-only
1400 				   directory */
1401 				mod_flag = 1;
1402 				if (mkdir(np, mode | S_IRWXU) == -1)
1403 					goto bad;
1404 			}
1405 			vect[0] = xstrdup(np);
1406 			sink(1, vect, src);
1407 			if (setimes) {
1408 				setimes = 0;
1409 				(void) utimes(vect[0], tv);
1410 			}
1411 			if (mod_flag)
1412 				(void) chmod(vect[0], mode);
1413 			free(vect[0]);
1414 			continue;
1415 		}
1416 		omode = mode;
1417 		mode |= S_IWUSR;
1418 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1419 bad:			run_err("%s: %s", np, strerror(errno));
1420 			continue;
1421 		}
1422 		(void) atomicio(vwrite, remout, "", 1);
1423 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1424 			(void) close(ofd);
1425 			continue;
1426 		}
1427 		cp = bp->buf;
1428 		wrerr = 0;
1429 
1430 		/*
1431 		 * NB. do not use run_err() unless immediately followed by
1432 		 * exit() below as it may send a spurious reply that might
1433 		 * desyncronise us from the peer. Use note_err() instead.
1434 		 */
1435 		statbytes = 0;
1436 		if (showprogress)
1437 			start_progress_meter(curfile, size, &statbytes);
1438 		set_nonblock(remin);
1439 		for (count = i = 0; i < size; i += bp->cnt) {
1440 			amt = bp->cnt;
1441 			if (i + amt > size)
1442 				amt = size - i;
1443 			count += amt;
1444 			do {
1445 				j = atomicio6(read, remin, cp, amt,
1446 				    scpio, &statbytes);
1447 				if (j == 0) {
1448 					run_err("%s", j != EPIPE ?
1449 					    strerror(errno) :
1450 					    "dropped connection");
1451 					exit(1);
1452 				}
1453 				amt -= j;
1454 				cp += j;
1455 			} while (amt > 0);
1456 
1457 			if (count == bp->cnt) {
1458 				/* Keep reading so we stay sync'd up. */
1459 				if (!wrerr) {
1460 					if (atomicio(vwrite, ofd, bp->buf,
1461 					    count) != count) {
1462 						note_err("%s: %s", np,
1463 						    strerror(errno));
1464 						wrerr = 1;
1465 					}
1466 				}
1467 				count = 0;
1468 				cp = bp->buf;
1469 			}
1470 		}
1471 		unset_nonblock(remin);
1472 		if (count != 0 && !wrerr &&
1473 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1474 			note_err("%s: %s", np, strerror(errno));
1475 			wrerr = 1;
1476 		}
1477 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1478 		    ftruncate(ofd, size) != 0)
1479 			note_err("%s: truncate: %s", np, strerror(errno));
1480 		if (pflag) {
1481 			if (exists || omode != mode)
1482 				if (fchmod(ofd, omode)) {
1483 					note_err("%s: set mode: %s",
1484 					    np, strerror(errno));
1485 				}
1486 		} else {
1487 			if (!exists && omode != mode)
1488 				if (fchmod(ofd, omode & ~mask)) {
1489 					note_err("%s: set mode: %s",
1490 					    np, strerror(errno));
1491 				}
1492 		}
1493 		if (close(ofd) == -1)
1494 			note_err("%s: close: %s", np, strerror(errno));
1495 		(void) response();
1496 		if (showprogress)
1497 			stop_progress_meter();
1498 		if (setimes && !wrerr) {
1499 			setimes = 0;
1500 			if (utimes(np, tv) == -1) {
1501 				note_err("%s: set times: %s",
1502 				    np, strerror(errno));
1503 			}
1504 		}
1505 		/* If no error was noted then signal success for this file */
1506 		if (note_err(NULL) == 0)
1507 			(void) atomicio(vwrite, remout, "", 1);
1508 	}
1509 done:
1510 	for (n = 0; n < npatterns; n++)
1511 		free(patterns[n]);
1512 	free(patterns);
1513 	return;
1514 screwup:
1515 	for (n = 0; n < npatterns; n++)
1516 		free(patterns[n]);
1517 	free(patterns);
1518 	run_err("protocol error: %s", why);
1519 	exit(1);
1520 }
1521 
1522 int
1523 response(void)
1524 {
1525 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
1526 
1527 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1528 		lostconn(0);
1529 
1530 	cp = rbuf;
1531 	switch (resp) {
1532 	case 0:		/* ok */
1533 		return (0);
1534 	default:
1535 		*cp++ = resp;
1536 		/* FALLTHROUGH */
1537 	case 1:		/* error, followed by error msg */
1538 	case 2:		/* fatal error, "" */
1539 		do {
1540 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1541 				lostconn(0);
1542 			*cp++ = ch;
1543 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1544 
1545 		if (!iamremote) {
1546 			cp[-1] = '\0';
1547 			(void) snmprintf(visbuf, sizeof(visbuf),
1548 			    NULL, "%s\n", rbuf);
1549 			(void) atomicio(vwrite, STDERR_FILENO,
1550 			    visbuf, strlen(visbuf));
1551 		}
1552 		++errs;
1553 		if (resp == 1)
1554 			return (-1);
1555 		exit(1);
1556 	}
1557 	/* NOTREACHED */
1558 }
1559 
1560 void
1561 usage(void)
1562 {
1563 	(void) fprintf(stderr,
1564 	    "usage: scp [-346ABCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1565 	    "            [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
1566 	    "            [-S program] source ... target\n");
1567 	exit(1);
1568 }
1569 
1570 void
1571 run_err(const char *fmt,...)
1572 {
1573 	static FILE *fp;
1574 	va_list ap;
1575 
1576 	++errs;
1577 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1578 		(void) fprintf(fp, "%c", 0x01);
1579 		(void) fprintf(fp, "scp: ");
1580 		va_start(ap, fmt);
1581 		(void) vfprintf(fp, fmt, ap);
1582 		va_end(ap);
1583 		(void) fprintf(fp, "\n");
1584 		(void) fflush(fp);
1585 	}
1586 
1587 	if (!iamremote) {
1588 		va_start(ap, fmt);
1589 		vfmprintf(stderr, fmt, ap);
1590 		va_end(ap);
1591 		fprintf(stderr, "\n");
1592 	}
1593 }
1594 
1595 /*
1596  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
1597  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
1598  * any active error at the end of the transfer.
1599  */
1600 int
1601 note_err(const char *fmt, ...)
1602 {
1603 	static char *emsg;
1604 	va_list ap;
1605 
1606 	/* Replay any previously-noted error */
1607 	if (fmt == NULL) {
1608 		if (emsg == NULL)
1609 			return 0;
1610 		run_err("%s", emsg);
1611 		free(emsg);
1612 		emsg = NULL;
1613 		return -1;
1614 	}
1615 
1616 	errs++;
1617 	/* Prefer first-noted error */
1618 	if (emsg != NULL)
1619 		return -1;
1620 
1621 	va_start(ap, fmt);
1622 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
1623 	va_end(ap);
1624 	return -1;
1625 }
1626 
1627 void
1628 verifydir(char *cp)
1629 {
1630 	struct stat stb;
1631 
1632 	if (!stat(cp, &stb)) {
1633 		if (S_ISDIR(stb.st_mode))
1634 			return;
1635 		errno = ENOTDIR;
1636 	}
1637 	run_err("%s: %s", cp, strerror(errno));
1638 	killchild(0);
1639 }
1640 
1641 int
1642 okname(char *cp0)
1643 {
1644 	int c;
1645 	char *cp;
1646 
1647 	cp = cp0;
1648 	do {
1649 		c = (int)*cp;
1650 		if (c & 0200)
1651 			goto bad;
1652 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
1653 			switch (c) {
1654 			case '\'':
1655 			case '"':
1656 			case '`':
1657 			case ' ':
1658 			case '#':
1659 				goto bad;
1660 			default:
1661 				break;
1662 			}
1663 		}
1664 	} while (*++cp);
1665 	return (1);
1666 
1667 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
1668 	return (0);
1669 }
1670 
1671 BUF *
1672 allocbuf(BUF *bp, int fd, int blksize)
1673 {
1674 	size_t size;
1675 	struct stat stb;
1676 
1677 	if (fstat(fd, &stb) == -1) {
1678 		run_err("fstat: %s", strerror(errno));
1679 		return (0);
1680 	}
1681 	size = ROUNDUP(stb.st_blksize, blksize);
1682 	if (size == 0)
1683 		size = blksize;
1684 	if (bp->cnt >= size)
1685 		return (bp);
1686 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1687 	bp->cnt = size;
1688 	return (bp);
1689 }
1690 
1691 void
1692 lostconn(int signo)
1693 {
1694 	if (!iamremote)
1695 		(void)write(STDERR_FILENO, "lost connection\n", 16);
1696 	if (signo)
1697 		_exit(1);
1698 	else
1699 		exit(1);
1700 }
1701