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