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