xref: /openbsd-src/usr.bin/ssh/scp.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /* $OpenBSD: scp.c,v 1.187 2016/09/12 01:22:38 deraadt Exp $ */
2 /*
3  * scp - secure remote copy.  This is basically patched BSD rcp which
4  * uses ssh to do the data transfer (instead of using rcmd).
5  *
6  * NOTE: This version should NOT be suid root.  (This uses ssh to
7  * do the transfer and ssh has the necessary privileges.)
8  *
9  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
10  *
11  * As far as I am concerned, the code I have written for this software
12  * can be used freely for any purpose.  Any derived versions of this
13  * software must be clearly marked as such, and if the derived work is
14  * incompatible with the protocol description in the RFC file, it must be
15  * called by a name other than "ssh" or "Secure Shell".
16  */
17 /*
18  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
19  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 /*
43  * Parts from:
44  *
45  * Copyright (c) 1983, 1990, 1992, 1993, 1995
46  *	The Regents of the University of California.  All rights reserved.
47  *
48  * Redistribution and use in source and binary forms, with or without
49  * modification, are permitted provided that the following conditions
50  * are met:
51  * 1. Redistributions of source code must retain the above copyright
52  *    notice, this list of conditions and the following disclaimer.
53  * 2. Redistributions in binary form must reproduce the above copyright
54  *    notice, this list of conditions and the following disclaimer in the
55  *    documentation and/or other materials provided with the distribution.
56  * 3. Neither the name of the University nor the names of its contributors
57  *    may be used to endorse or promote products derived from this software
58  *    without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70  * SUCH DAMAGE.
71  *
72  */
73 
74 #include <sys/types.h>
75 #include <sys/poll.h>
76 #include <sys/wait.h>
77 #include <sys/stat.h>
78 #include <sys/time.h>
79 #include <sys/uio.h>
80 
81 #include <ctype.h>
82 #include <dirent.h>
83 #include <errno.h>
84 #include <fcntl.h>
85 #include <locale.h>
86 #include <pwd.h>
87 #include <signal.h>
88 #include <stdarg.h>
89 #include <stdio.h>
90 #include <stdlib.h>
91 #include <string.h>
92 #include <time.h>
93 #include <unistd.h>
94 #include <limits.h>
95 #include <vis.h>
96 
97 #include "xmalloc.h"
98 #include "atomicio.h"
99 #include "pathnames.h"
100 #include "log.h"
101 #include "misc.h"
102 #include "progressmeter.h"
103 #include "utf8.h"
104 
105 #define COPY_BUFLEN	16384
106 
107 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
108 int do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout);
109 
110 /* Struct for addargs */
111 arglist args;
112 arglist remote_remote_args;
113 
114 /* Bandwidth limit */
115 long long limit_kbps = 0;
116 struct bwlimit bwlimit;
117 
118 /* Name of current file being transferred. */
119 char *curfile;
120 
121 /* This is set to non-zero to enable verbose mode. */
122 int verbose_mode = 0;
123 
124 /* This is set to zero if the progressmeter is not desired. */
125 int showprogress = 1;
126 
127 /*
128  * This is set to non-zero if remote-remote copy should be piped
129  * through this process.
130  */
131 int throughlocal = 0;
132 
133 /* This is the program to execute for the secured connection. ("ssh" or -S) */
134 char *ssh_program = _PATH_SSH_PROGRAM;
135 
136 /* This is used to store the pid of ssh_program */
137 pid_t do_cmd_pid = -1;
138 
139 static void
140 killchild(int signo)
141 {
142 	if (do_cmd_pid > 1) {
143 		kill(do_cmd_pid, signo ? signo : SIGTERM);
144 		waitpid(do_cmd_pid, NULL, 0);
145 	}
146 
147 	if (signo)
148 		_exit(1);
149 	exit(1);
150 }
151 
152 static void
153 suspchild(int signo)
154 {
155 	int status;
156 
157 	if (do_cmd_pid > 1) {
158 		kill(do_cmd_pid, signo);
159 		while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
160 		    errno == EINTR)
161 			;
162 		kill(getpid(), SIGSTOP);
163 	}
164 }
165 
166 static int
167 do_local_cmd(arglist *a)
168 {
169 	u_int i;
170 	int status;
171 	pid_t pid;
172 
173 	if (a->num == 0)
174 		fatal("do_local_cmd: no arguments");
175 
176 	if (verbose_mode) {
177 		fprintf(stderr, "Executing:");
178 		for (i = 0; i < a->num; i++)
179 			fmprintf(stderr, " %s", a->list[i]);
180 		fprintf(stderr, "\n");
181 	}
182 	if ((pid = fork()) == -1)
183 		fatal("do_local_cmd: fork: %s", strerror(errno));
184 
185 	if (pid == 0) {
186 		execvp(a->list[0], a->list);
187 		perror(a->list[0]);
188 		exit(1);
189 	}
190 
191 	do_cmd_pid = pid;
192 	signal(SIGTERM, killchild);
193 	signal(SIGINT, killchild);
194 	signal(SIGHUP, killchild);
195 
196 	while (waitpid(pid, &status, 0) == -1)
197 		if (errno != EINTR)
198 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
199 
200 	do_cmd_pid = -1;
201 
202 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
203 		return (-1);
204 
205 	return (0);
206 }
207 
208 /*
209  * This function executes the given command as the specified user on the
210  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
211  * assigns the input and output file descriptors on success.
212  */
213 
214 int
215 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
216 {
217 	int pin[2], pout[2], reserved[2];
218 
219 	if (verbose_mode)
220 		fmprintf(stderr,
221 		    "Executing: program %s host %s, user %s, command %s\n",
222 		    ssh_program, host,
223 		    remuser ? remuser : "(unspecified)", cmd);
224 
225 	/*
226 	 * Reserve two descriptors so that the real pipes won't get
227 	 * descriptors 0 and 1 because that will screw up dup2 below.
228 	 */
229 	if (pipe(reserved) < 0)
230 		fatal("pipe: %s", strerror(errno));
231 
232 	/* Create a socket pair for communicating with ssh. */
233 	if (pipe(pin) < 0)
234 		fatal("pipe: %s", strerror(errno));
235 	if (pipe(pout) < 0)
236 		fatal("pipe: %s", strerror(errno));
237 
238 	/* Free the reserved descriptors. */
239 	close(reserved[0]);
240 	close(reserved[1]);
241 
242 	signal(SIGTSTP, suspchild);
243 	signal(SIGTTIN, suspchild);
244 	signal(SIGTTOU, suspchild);
245 
246 	/* Fork a child to execute the command on the remote host using ssh. */
247 	do_cmd_pid = fork();
248 	if (do_cmd_pid == 0) {
249 		/* Child. */
250 		close(pin[1]);
251 		close(pout[0]);
252 		dup2(pin[0], 0);
253 		dup2(pout[1], 1);
254 		close(pin[0]);
255 		close(pout[1]);
256 
257 		replacearg(&args, 0, "%s", ssh_program);
258 		if (remuser != NULL) {
259 			addargs(&args, "-l");
260 			addargs(&args, "%s", remuser);
261 		}
262 		addargs(&args, "--");
263 		addargs(&args, "%s", host);
264 		addargs(&args, "%s", cmd);
265 
266 		execvp(ssh_program, args.list);
267 		perror(ssh_program);
268 		exit(1);
269 	} else if (do_cmd_pid == -1) {
270 		fatal("fork: %s", strerror(errno));
271 	}
272 	/* Parent.  Close the other side, and return the local side. */
273 	close(pin[0]);
274 	*fdout = pin[1];
275 	close(pout[1]);
276 	*fdin = pout[0];
277 	signal(SIGTERM, killchild);
278 	signal(SIGINT, killchild);
279 	signal(SIGHUP, killchild);
280 	return 0;
281 }
282 
283 /*
284  * This functions executes a command simlar to do_cmd(), but expects the
285  * input and output descriptors to be setup by a previous call to do_cmd().
286  * This way the input and output of two commands can be connected.
287  */
288 int
289 do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout)
290 {
291 	pid_t pid;
292 	int status;
293 
294 	if (verbose_mode)
295 		fmprintf(stderr,
296 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
297 		    ssh_program, host,
298 		    remuser ? remuser : "(unspecified)", cmd);
299 
300 	/* Fork a child to execute the command on the remote host using ssh. */
301 	pid = fork();
302 	if (pid == 0) {
303 		dup2(fdin, 0);
304 		dup2(fdout, 1);
305 
306 		replacearg(&args, 0, "%s", ssh_program);
307 		if (remuser != NULL) {
308 			addargs(&args, "-l");
309 			addargs(&args, "%s", remuser);
310 		}
311 		addargs(&args, "--");
312 		addargs(&args, "%s", host);
313 		addargs(&args, "%s", cmd);
314 
315 		execvp(ssh_program, args.list);
316 		perror(ssh_program);
317 		exit(1);
318 	} else if (pid == -1) {
319 		fatal("fork: %s", strerror(errno));
320 	}
321 	while (waitpid(pid, &status, 0) == -1)
322 		if (errno != EINTR)
323 			fatal("do_cmd2: waitpid: %s", strerror(errno));
324 	return 0;
325 }
326 
327 typedef struct {
328 	size_t cnt;
329 	char *buf;
330 } BUF;
331 
332 BUF *allocbuf(BUF *, int, int);
333 void lostconn(int);
334 int okname(char *);
335 void run_err(const char *,...);
336 void verifydir(char *);
337 
338 struct passwd *pwd;
339 uid_t userid;
340 int errs, remin, remout;
341 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
342 
343 #define	CMDNEEDS	64
344 char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
345 
346 int response(void);
347 void rsource(char *, struct stat *);
348 void sink(int, char *[]);
349 void source(int, char *[]);
350 void tolocal(int, char *[]);
351 void toremote(char *, int, char *[]);
352 void usage(void);
353 
354 int
355 main(int argc, char **argv)
356 {
357 	int ch, fflag, tflag, status, n;
358 	char *targ, **newargv;
359 	const char *errstr;
360 	extern char *optarg;
361 	extern int optind;
362 
363 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
364 	sanitise_stdfd();
365 
366 	setlocale(LC_CTYPE, "");
367 
368 	/* Copy argv, because we modify it */
369 	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
370 	for (n = 0; n < argc; n++)
371 		newargv[n] = xstrdup(argv[n]);
372 	argv = newargv;
373 
374 	memset(&args, '\0', sizeof(args));
375 	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
376 	args.list = remote_remote_args.list = NULL;
377 	addargs(&args, "%s", ssh_program);
378 	addargs(&args, "-x");
379 	addargs(&args, "-oForwardAgent=no");
380 	addargs(&args, "-oPermitLocalCommand=no");
381 	addargs(&args, "-oClearAllForwardings=yes");
382 
383 	fflag = tflag = 0;
384 	while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
385 		switch (ch) {
386 		/* User-visible flags. */
387 		case '1':
388 		case '2':
389 		case '4':
390 		case '6':
391 		case 'C':
392 			addargs(&args, "-%c", ch);
393 			addargs(&remote_remote_args, "-%c", ch);
394 			break;
395 		case '3':
396 			throughlocal = 1;
397 			break;
398 		case 'o':
399 		case 'c':
400 		case 'i':
401 		case 'F':
402 			addargs(&remote_remote_args, "-%c", ch);
403 			addargs(&remote_remote_args, "%s", optarg);
404 			addargs(&args, "-%c", ch);
405 			addargs(&args, "%s", optarg);
406 			break;
407 		case 'P':
408 			addargs(&remote_remote_args, "-p");
409 			addargs(&remote_remote_args, "%s", optarg);
410 			addargs(&args, "-p");
411 			addargs(&args, "%s", optarg);
412 			break;
413 		case 'B':
414 			addargs(&remote_remote_args, "-oBatchmode=yes");
415 			addargs(&args, "-oBatchmode=yes");
416 			break;
417 		case 'l':
418 			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
419 			    &errstr);
420 			if (errstr != NULL)
421 				usage();
422 			limit_kbps *= 1024; /* kbps */
423 			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
424 			break;
425 		case 'p':
426 			pflag = 1;
427 			break;
428 		case 'r':
429 			iamrecursive = 1;
430 			break;
431 		case 'S':
432 			ssh_program = xstrdup(optarg);
433 			break;
434 		case 'v':
435 			addargs(&args, "-v");
436 			addargs(&remote_remote_args, "-v");
437 			verbose_mode = 1;
438 			break;
439 		case 'q':
440 			addargs(&args, "-q");
441 			addargs(&remote_remote_args, "-q");
442 			showprogress = 0;
443 			break;
444 
445 		/* Server options. */
446 		case 'd':
447 			targetshouldbedirectory = 1;
448 			break;
449 		case 'f':	/* "from" */
450 			iamremote = 1;
451 			fflag = 1;
452 			break;
453 		case 't':	/* "to" */
454 			iamremote = 1;
455 			tflag = 1;
456 			break;
457 		default:
458 			usage();
459 		}
460 	argc -= optind;
461 	argv += optind;
462 
463 	if ((pwd = getpwuid(userid = getuid())) == NULL)
464 		fatal("unknown user %u", (u_int) userid);
465 
466 	if (!isatty(STDOUT_FILENO))
467 		showprogress = 0;
468 
469 	if (pflag) {
470 		/* Cannot pledge: -p allows setuid/setgid files... */
471 	} else {
472 		if (pledge("stdio rpath wpath cpath fattr tty proc exec",
473 		    NULL) == -1) {
474 			perror("pledge");
475 			exit(1);
476 		}
477 	}
478 
479 	remin = STDIN_FILENO;
480 	remout = STDOUT_FILENO;
481 
482 	if (fflag) {
483 		/* Follow "protocol", send data. */
484 		(void) response();
485 		source(argc, argv);
486 		exit(errs != 0);
487 	}
488 	if (tflag) {
489 		/* Receive data. */
490 		sink(argc, argv);
491 		exit(errs != 0);
492 	}
493 	if (argc < 2)
494 		usage();
495 	if (argc > 2)
496 		targetshouldbedirectory = 1;
497 
498 	remin = remout = -1;
499 	do_cmd_pid = -1;
500 	/* Command to be executed on remote system using "ssh". */
501 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
502 	    verbose_mode ? " -v" : "",
503 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
504 	    targetshouldbedirectory ? " -d" : "");
505 
506 	(void) signal(SIGPIPE, lostconn);
507 
508 	if ((targ = colon(argv[argc - 1])))	/* Dest is remote host. */
509 		toremote(targ, argc, argv);
510 	else {
511 		if (targetshouldbedirectory)
512 			verifydir(argv[argc - 1]);
513 		tolocal(argc, argv);	/* Dest is local host. */
514 	}
515 	/*
516 	 * Finally check the exit status of the ssh process, if one was forked
517 	 * and no error has occurred yet
518 	 */
519 	if (do_cmd_pid != -1 && errs == 0) {
520 		if (remin != -1)
521 		    (void) close(remin);
522 		if (remout != -1)
523 		    (void) close(remout);
524 		if (waitpid(do_cmd_pid, &status, 0) == -1)
525 			errs = 1;
526 		else {
527 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
528 				errs = 1;
529 		}
530 	}
531 	exit(errs != 0);
532 }
533 
534 /* Callback from atomicio6 to update progress meter and limit bandwidth */
535 static int
536 scpio(void *_cnt, size_t s)
537 {
538 	off_t *cnt = (off_t *)_cnt;
539 
540 	*cnt += s;
541 	if (limit_kbps > 0)
542 		bandwidth_limit(&bwlimit, s);
543 	return 0;
544 }
545 
546 static int
547 do_times(int fd, int verb, const struct stat *sb)
548 {
549 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
550 	char buf[(20 + 7 + 2) * 2 + 2];
551 
552 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
553 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
554 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
555 	if (verb) {
556 		fprintf(stderr, "File mtime %lld atime %lld\n",
557 		    (long long)sb->st_mtime, (long long)sb->st_atime);
558 		fprintf(stderr, "Sending file timestamps: %s", buf);
559 	}
560 	(void) atomicio(vwrite, fd, buf, strlen(buf));
561 	return (response());
562 }
563 
564 void
565 toremote(char *targ, int argc, char **argv)
566 {
567 	char *bp, *host, *src, *suser, *thost, *tuser, *arg;
568 	arglist alist;
569 	int i;
570 	u_int j;
571 
572 	memset(&alist, '\0', sizeof(alist));
573 	alist.list = NULL;
574 
575 	*targ++ = 0;
576 	if (*targ == 0)
577 		targ = ".";
578 
579 	arg = xstrdup(argv[argc - 1]);
580 	if ((thost = strrchr(arg, '@'))) {
581 		/* user@host */
582 		*thost++ = 0;
583 		tuser = arg;
584 		if (*tuser == '\0')
585 			tuser = NULL;
586 	} else {
587 		thost = arg;
588 		tuser = NULL;
589 	}
590 
591 	if (tuser != NULL && !okname(tuser)) {
592 		free(arg);
593 		return;
594 	}
595 
596 	for (i = 0; i < argc - 1; i++) {
597 		src = colon(argv[i]);
598 		if (src && throughlocal) {	/* extended remote to remote */
599 			*src++ = 0;
600 			if (*src == 0)
601 				src = ".";
602 			host = strrchr(argv[i], '@');
603 			if (host) {
604 				*host++ = 0;
605 				host = cleanhostname(host);
606 				suser = argv[i];
607 				if (*suser == '\0')
608 					suser = pwd->pw_name;
609 				else if (!okname(suser))
610 					continue;
611 			} else {
612 				host = cleanhostname(argv[i]);
613 				suser = NULL;
614 			}
615 			xasprintf(&bp, "%s -f %s%s", cmd,
616 			    *src == '-' ? "-- " : "", src);
617 			if (do_cmd(host, suser, bp, &remin, &remout) < 0)
618 				exit(1);
619 			free(bp);
620 			host = cleanhostname(thost);
621 			xasprintf(&bp, "%s -t %s%s", cmd,
622 			    *targ == '-' ? "-- " : "", targ);
623 			if (do_cmd2(host, tuser, bp, remin, remout) < 0)
624 				exit(1);
625 			free(bp);
626 			(void) close(remin);
627 			(void) close(remout);
628 			remin = remout = -1;
629 		} else if (src) {	/* standard remote to remote */
630 			freeargs(&alist);
631 			addargs(&alist, "%s", ssh_program);
632 			addargs(&alist, "-x");
633 			addargs(&alist, "-oClearAllForwardings=yes");
634 			addargs(&alist, "-n");
635 			for (j = 0; j < remote_remote_args.num; j++) {
636 				addargs(&alist, "%s",
637 				    remote_remote_args.list[j]);
638 			}
639 			*src++ = 0;
640 			if (*src == 0)
641 				src = ".";
642 			host = strrchr(argv[i], '@');
643 
644 			if (host) {
645 				*host++ = 0;
646 				host = cleanhostname(host);
647 				suser = argv[i];
648 				if (*suser == '\0')
649 					suser = pwd->pw_name;
650 				else if (!okname(suser))
651 					continue;
652 				addargs(&alist, "-l");
653 				addargs(&alist, "%s", suser);
654 			} else {
655 				host = cleanhostname(argv[i]);
656 			}
657 			addargs(&alist, "--");
658 			addargs(&alist, "%s", host);
659 			addargs(&alist, "%s", cmd);
660 			addargs(&alist, "%s", src);
661 			addargs(&alist, "%s%s%s:%s",
662 			    tuser ? tuser : "", tuser ? "@" : "",
663 			    thost, targ);
664 			if (do_local_cmd(&alist) != 0)
665 				errs = 1;
666 		} else {	/* local to remote */
667 			if (remin == -1) {
668 				xasprintf(&bp, "%s -t %s%s", cmd,
669 				    *targ == '-' ? "-- " : "", targ);
670 				host = cleanhostname(thost);
671 				if (do_cmd(host, tuser, bp, &remin,
672 				    &remout) < 0)
673 					exit(1);
674 				if (response() < 0)
675 					exit(1);
676 				free(bp);
677 			}
678 			source(1, argv + i);
679 		}
680 	}
681 	free(arg);
682 }
683 
684 void
685 tolocal(int argc, char **argv)
686 {
687 	char *bp, *host, *src, *suser;
688 	arglist alist;
689 	int i;
690 
691 	memset(&alist, '\0', sizeof(alist));
692 	alist.list = NULL;
693 
694 	for (i = 0; i < argc - 1; i++) {
695 		if (!(src = colon(argv[i]))) {	/* Local to local. */
696 			freeargs(&alist);
697 			addargs(&alist, "%s", _PATH_CP);
698 			if (iamrecursive)
699 				addargs(&alist, "-r");
700 			if (pflag)
701 				addargs(&alist, "-p");
702 			addargs(&alist, "--");
703 			addargs(&alist, "%s", argv[i]);
704 			addargs(&alist, "%s", argv[argc-1]);
705 			if (do_local_cmd(&alist))
706 				++errs;
707 			continue;
708 		}
709 		*src++ = 0;
710 		if (*src == 0)
711 			src = ".";
712 		if ((host = strrchr(argv[i], '@')) == NULL) {
713 			host = argv[i];
714 			suser = NULL;
715 		} else {
716 			*host++ = 0;
717 			suser = argv[i];
718 			if (*suser == '\0')
719 				suser = pwd->pw_name;
720 		}
721 		host = cleanhostname(host);
722 		xasprintf(&bp, "%s -f %s%s",
723 		    cmd, *src == '-' ? "-- " : "", src);
724 		if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
725 			free(bp);
726 			++errs;
727 			continue;
728 		}
729 		free(bp);
730 		sink(1, argv + argc - 1);
731 		(void) close(remin);
732 		remin = remout = -1;
733 	}
734 }
735 
736 void
737 source(int argc, char **argv)
738 {
739 	struct stat stb;
740 	static BUF buffer;
741 	BUF *bp;
742 	off_t i, statbytes;
743 	size_t amt, nr;
744 	int fd = -1, haderr, indx;
745 	char *last, *name, buf[2048], encname[PATH_MAX];
746 	int len;
747 
748 	for (indx = 0; indx < argc; ++indx) {
749 		name = argv[indx];
750 		statbytes = 0;
751 		len = strlen(name);
752 		while (len > 1 && name[len-1] == '/')
753 			name[--len] = '\0';
754 		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
755 			goto syserr;
756 		if (strchr(name, '\n') != NULL) {
757 			strnvis(encname, name, sizeof(encname), VIS_NL);
758 			name = encname;
759 		}
760 		if (fstat(fd, &stb) < 0) {
761 syserr:			run_err("%s: %s", name, strerror(errno));
762 			goto next;
763 		}
764 		if (stb.st_size < 0) {
765 			run_err("%s: %s", name, "Negative file size");
766 			goto next;
767 		}
768 		unset_nonblock(fd);
769 		switch (stb.st_mode & S_IFMT) {
770 		case S_IFREG:
771 			break;
772 		case S_IFDIR:
773 			if (iamrecursive) {
774 				rsource(name, &stb);
775 				goto next;
776 			}
777 			/* FALLTHROUGH */
778 		default:
779 			run_err("%s: not a regular file", name);
780 			goto next;
781 		}
782 		if ((last = strrchr(name, '/')) == NULL)
783 			last = name;
784 		else
785 			++last;
786 		curfile = last;
787 		if (pflag) {
788 			if (do_times(remout, verbose_mode, &stb) < 0)
789 				goto next;
790 		}
791 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
792 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
793 		    (u_int) (stb.st_mode & FILEMODEMASK),
794 		    (long long)stb.st_size, last);
795 		if (verbose_mode)
796 			fmprintf(stderr, "Sending file modes: %s", buf);
797 		(void) atomicio(vwrite, remout, buf, strlen(buf));
798 		if (response() < 0)
799 			goto next;
800 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
801 next:			if (fd != -1) {
802 				(void) close(fd);
803 				fd = -1;
804 			}
805 			continue;
806 		}
807 		if (showprogress)
808 			start_progress_meter(curfile, stb.st_size, &statbytes);
809 		set_nonblock(remout);
810 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
811 			amt = bp->cnt;
812 			if (i + (off_t)amt > stb.st_size)
813 				amt = stb.st_size - i;
814 			if (!haderr) {
815 				if ((nr = atomicio(read, fd,
816 				    bp->buf, amt)) != amt) {
817 					haderr = errno;
818 					memset(bp->buf + nr, 0, amt - nr);
819 				}
820 			}
821 			/* Keep writing after error to retain sync */
822 			if (haderr) {
823 				(void)atomicio(vwrite, remout, bp->buf, amt);
824 				memset(bp->buf, 0, amt);
825 				continue;
826 			}
827 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
828 			    &statbytes) != amt)
829 				haderr = errno;
830 		}
831 		unset_nonblock(remout);
832 
833 		if (fd != -1) {
834 			if (close(fd) < 0 && !haderr)
835 				haderr = errno;
836 			fd = -1;
837 		}
838 		if (!haderr)
839 			(void) atomicio(vwrite, remout, "", 1);
840 		else
841 			run_err("%s: %s", name, strerror(haderr));
842 		(void) response();
843 		if (showprogress)
844 			stop_progress_meter();
845 	}
846 }
847 
848 void
849 rsource(char *name, struct stat *statp)
850 {
851 	DIR *dirp;
852 	struct dirent *dp;
853 	char *last, *vect[1], path[PATH_MAX];
854 
855 	if (!(dirp = opendir(name))) {
856 		run_err("%s: %s", name, strerror(errno));
857 		return;
858 	}
859 	last = strrchr(name, '/');
860 	if (last == NULL)
861 		last = name;
862 	else
863 		last++;
864 	if (pflag) {
865 		if (do_times(remout, verbose_mode, statp) < 0) {
866 			closedir(dirp);
867 			return;
868 		}
869 	}
870 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
871 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
872 	if (verbose_mode)
873 		fmprintf(stderr, "Entering directory: %s", path);
874 	(void) atomicio(vwrite, remout, path, strlen(path));
875 	if (response() < 0) {
876 		closedir(dirp);
877 		return;
878 	}
879 	while ((dp = readdir(dirp)) != NULL) {
880 		if (dp->d_ino == 0)
881 			continue;
882 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
883 			continue;
884 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
885 			run_err("%s/%s: name too long", name, dp->d_name);
886 			continue;
887 		}
888 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
889 		vect[0] = path;
890 		source(1, vect);
891 	}
892 	(void) closedir(dirp);
893 	(void) atomicio(vwrite, remout, "E\n", 2);
894 	(void) response();
895 }
896 
897 void
898 sink(int argc, char **argv)
899 {
900 	static BUF buffer;
901 	struct stat stb;
902 	enum {
903 		YES, NO, DISPLAYED
904 	} wrerr;
905 	BUF *bp;
906 	off_t i;
907 	size_t j, count;
908 	int amt, exists, first, ofd;
909 	mode_t mode, omode, mask;
910 	off_t size, statbytes;
911 	unsigned long long ull;
912 	int setimes, targisdir, wrerrno = 0;
913 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
914 	struct timeval tv[2];
915 
916 #define	atime	tv[0]
917 #define	mtime	tv[1]
918 #define	SCREWUP(str)	{ why = str; goto screwup; }
919 
920 	setimes = targisdir = 0;
921 	mask = umask(0);
922 	if (!pflag)
923 		(void) umask(mask);
924 	if (argc != 1) {
925 		run_err("ambiguous target");
926 		exit(1);
927 	}
928 	targ = *argv;
929 	if (targetshouldbedirectory)
930 		verifydir(targ);
931 
932 	(void) atomicio(vwrite, remout, "", 1);
933 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
934 		targisdir = 1;
935 	for (first = 1;; first = 0) {
936 		cp = buf;
937 		if (atomicio(read, remin, cp, 1) != 1)
938 			return;
939 		if (*cp++ == '\n')
940 			SCREWUP("unexpected <newline>");
941 		do {
942 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
943 				SCREWUP("lost connection");
944 			*cp++ = ch;
945 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
946 		*cp = 0;
947 		if (verbose_mode)
948 			fmprintf(stderr, "Sink: %s", buf);
949 
950 		if (buf[0] == '\01' || buf[0] == '\02') {
951 			if (iamremote == 0) {
952 				(void) snmprintf(visbuf, sizeof(visbuf),
953 				    NULL, "%s", buf + 1);
954 				(void) atomicio(vwrite, STDERR_FILENO,
955 				    visbuf, strlen(visbuf));
956 			}
957 			if (buf[0] == '\02')
958 				exit(1);
959 			++errs;
960 			continue;
961 		}
962 		if (buf[0] == 'E') {
963 			(void) atomicio(vwrite, remout, "", 1);
964 			return;
965 		}
966 		if (ch == '\n')
967 			*--cp = 0;
968 
969 		cp = buf;
970 		if (*cp == 'T') {
971 			setimes++;
972 			cp++;
973 			if (!isdigit((unsigned char)*cp))
974 				SCREWUP("mtime.sec not present");
975 			ull = strtoull(cp, &cp, 10);
976 			if (!cp || *cp++ != ' ')
977 				SCREWUP("mtime.sec not delimited");
978 			if ((time_t)ull < 0 ||
979 			    (unsigned long long)(time_t)ull != ull)
980 				setimes = 0;	/* out of range */
981 			mtime.tv_sec = ull;
982 			mtime.tv_usec = strtol(cp, &cp, 10);
983 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
984 			    mtime.tv_usec > 999999)
985 				SCREWUP("mtime.usec not delimited");
986 			if (!isdigit((unsigned char)*cp))
987 				SCREWUP("atime.sec not present");
988 			ull = strtoull(cp, &cp, 10);
989 			if (!cp || *cp++ != ' ')
990 				SCREWUP("atime.sec not delimited");
991 			if ((time_t)ull < 0 ||
992 			    (unsigned long long)(time_t)ull != ull)
993 				setimes = 0;	/* out of range */
994 			atime.tv_sec = ull;
995 			atime.tv_usec = strtol(cp, &cp, 10);
996 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
997 			    atime.tv_usec > 999999)
998 				SCREWUP("atime.usec not delimited");
999 			(void) atomicio(vwrite, remout, "", 1);
1000 			continue;
1001 		}
1002 		if (*cp != 'C' && *cp != 'D') {
1003 			/*
1004 			 * Check for the case "rcp remote:foo\* local:bar".
1005 			 * In this case, the line "No match." can be returned
1006 			 * by the shell before the rcp command on the remote is
1007 			 * executed so the ^Aerror_message convention isn't
1008 			 * followed.
1009 			 */
1010 			if (first) {
1011 				run_err("%s", cp);
1012 				exit(1);
1013 			}
1014 			SCREWUP("expected control record");
1015 		}
1016 		mode = 0;
1017 		for (++cp; cp < buf + 5; cp++) {
1018 			if (*cp < '0' || *cp > '7')
1019 				SCREWUP("bad mode");
1020 			mode = (mode << 3) | (*cp - '0');
1021 		}
1022 		if (*cp++ != ' ')
1023 			SCREWUP("mode not delimited");
1024 
1025 		for (size = 0; isdigit((unsigned char)*cp);)
1026 			size = size * 10 + (*cp++ - '0');
1027 		if (*cp++ != ' ')
1028 			SCREWUP("size not delimited");
1029 		if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
1030 			run_err("error: unexpected filename: %s", cp);
1031 			exit(1);
1032 		}
1033 		if (targisdir) {
1034 			static char *namebuf;
1035 			static size_t cursize;
1036 			size_t need;
1037 
1038 			need = strlen(targ) + strlen(cp) + 250;
1039 			if (need > cursize) {
1040 				free(namebuf);
1041 				namebuf = xmalloc(need);
1042 				cursize = need;
1043 			}
1044 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1045 			    strcmp(targ, "/") ? "/" : "", cp);
1046 			np = namebuf;
1047 		} else
1048 			np = targ;
1049 		curfile = cp;
1050 		exists = stat(np, &stb) == 0;
1051 		if (buf[0] == 'D') {
1052 			int mod_flag = pflag;
1053 			if (!iamrecursive)
1054 				SCREWUP("received directory without -r");
1055 			if (exists) {
1056 				if (!S_ISDIR(stb.st_mode)) {
1057 					errno = ENOTDIR;
1058 					goto bad;
1059 				}
1060 				if (pflag)
1061 					(void) chmod(np, mode);
1062 			} else {
1063 				/* Handle copying from a read-only
1064 				   directory */
1065 				mod_flag = 1;
1066 				if (mkdir(np, mode | S_IRWXU) < 0)
1067 					goto bad;
1068 			}
1069 			vect[0] = xstrdup(np);
1070 			sink(1, vect);
1071 			if (setimes) {
1072 				setimes = 0;
1073 				if (utimes(vect[0], tv) < 0)
1074 					run_err("%s: set times: %s",
1075 					    vect[0], strerror(errno));
1076 			}
1077 			if (mod_flag)
1078 				(void) chmod(vect[0], mode);
1079 			free(vect[0]);
1080 			continue;
1081 		}
1082 		omode = mode;
1083 		mode |= S_IWUSR;
1084 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1085 bad:			run_err("%s: %s", np, strerror(errno));
1086 			continue;
1087 		}
1088 		(void) atomicio(vwrite, remout, "", 1);
1089 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1090 			(void) close(ofd);
1091 			continue;
1092 		}
1093 		cp = bp->buf;
1094 		wrerr = NO;
1095 
1096 		statbytes = 0;
1097 		if (showprogress)
1098 			start_progress_meter(curfile, size, &statbytes);
1099 		set_nonblock(remin);
1100 		for (count = i = 0; i < size; i += bp->cnt) {
1101 			amt = bp->cnt;
1102 			if (i + amt > size)
1103 				amt = size - i;
1104 			count += amt;
1105 			do {
1106 				j = atomicio6(read, remin, cp, amt,
1107 				    scpio, &statbytes);
1108 				if (j == 0) {
1109 					run_err("%s", j != EPIPE ?
1110 					    strerror(errno) :
1111 					    "dropped connection");
1112 					exit(1);
1113 				}
1114 				amt -= j;
1115 				cp += j;
1116 			} while (amt > 0);
1117 
1118 			if (count == bp->cnt) {
1119 				/* Keep reading so we stay sync'd up. */
1120 				if (wrerr == NO) {
1121 					if (atomicio(vwrite, ofd, bp->buf,
1122 					    count) != count) {
1123 						wrerr = YES;
1124 						wrerrno = errno;
1125 					}
1126 				}
1127 				count = 0;
1128 				cp = bp->buf;
1129 			}
1130 		}
1131 		unset_nonblock(remin);
1132 		if (count != 0 && wrerr == NO &&
1133 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1134 			wrerr = YES;
1135 			wrerrno = errno;
1136 		}
1137 		if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1138 		    ftruncate(ofd, size) != 0) {
1139 			run_err("%s: truncate: %s", np, strerror(errno));
1140 			wrerr = DISPLAYED;
1141 		}
1142 		if (pflag) {
1143 			if (exists || omode != mode)
1144 				if (fchmod(ofd, omode)) {
1145 					run_err("%s: set mode: %s",
1146 					    np, strerror(errno));
1147 					wrerr = DISPLAYED;
1148 				}
1149 		} else {
1150 			if (!exists && omode != mode)
1151 				if (fchmod(ofd, omode & ~mask)) {
1152 					run_err("%s: set mode: %s",
1153 					    np, strerror(errno));
1154 					wrerr = DISPLAYED;
1155 				}
1156 		}
1157 		if (close(ofd) == -1) {
1158 			wrerr = YES;
1159 			wrerrno = errno;
1160 		}
1161 		(void) response();
1162 		if (showprogress)
1163 			stop_progress_meter();
1164 		if (setimes && wrerr == NO) {
1165 			setimes = 0;
1166 			if (utimes(np, tv) < 0) {
1167 				run_err("%s: set times: %s",
1168 				    np, strerror(errno));
1169 				wrerr = DISPLAYED;
1170 			}
1171 		}
1172 		switch (wrerr) {
1173 		case YES:
1174 			run_err("%s: %s", np, strerror(wrerrno));
1175 			break;
1176 		case NO:
1177 			(void) atomicio(vwrite, remout, "", 1);
1178 			break;
1179 		case DISPLAYED:
1180 			break;
1181 		}
1182 	}
1183 screwup:
1184 	run_err("protocol error: %s", why);
1185 	exit(1);
1186 }
1187 
1188 int
1189 response(void)
1190 {
1191 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
1192 
1193 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1194 		lostconn(0);
1195 
1196 	cp = rbuf;
1197 	switch (resp) {
1198 	case 0:		/* ok */
1199 		return (0);
1200 	default:
1201 		*cp++ = resp;
1202 		/* FALLTHROUGH */
1203 	case 1:		/* error, followed by error msg */
1204 	case 2:		/* fatal error, "" */
1205 		do {
1206 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1207 				lostconn(0);
1208 			*cp++ = ch;
1209 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1210 
1211 		if (!iamremote) {
1212 			cp[-1] = '\0';
1213 			(void) snmprintf(visbuf, sizeof(visbuf),
1214 			    NULL, "%s\n", rbuf);
1215 			(void) atomicio(vwrite, STDERR_FILENO,
1216 			    visbuf, strlen(visbuf));
1217 		}
1218 		++errs;
1219 		if (resp == 1)
1220 			return (-1);
1221 		exit(1);
1222 	}
1223 	/* NOTREACHED */
1224 }
1225 
1226 void
1227 usage(void)
1228 {
1229 	(void) fprintf(stderr,
1230 	    "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1231 	    "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1232 	    "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1233 	exit(1);
1234 }
1235 
1236 void
1237 run_err(const char *fmt,...)
1238 {
1239 	static FILE *fp;
1240 	va_list ap;
1241 
1242 	++errs;
1243 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1244 		(void) fprintf(fp, "%c", 0x01);
1245 		(void) fprintf(fp, "scp: ");
1246 		va_start(ap, fmt);
1247 		(void) vfprintf(fp, fmt, ap);
1248 		va_end(ap);
1249 		(void) fprintf(fp, "\n");
1250 		(void) fflush(fp);
1251 	}
1252 
1253 	if (!iamremote) {
1254 		va_start(ap, fmt);
1255 		vfmprintf(stderr, fmt, ap);
1256 		va_end(ap);
1257 		fprintf(stderr, "\n");
1258 	}
1259 }
1260 
1261 void
1262 verifydir(char *cp)
1263 {
1264 	struct stat stb;
1265 
1266 	if (!stat(cp, &stb)) {
1267 		if (S_ISDIR(stb.st_mode))
1268 			return;
1269 		errno = ENOTDIR;
1270 	}
1271 	run_err("%s: %s", cp, strerror(errno));
1272 	killchild(0);
1273 }
1274 
1275 int
1276 okname(char *cp0)
1277 {
1278 	int c;
1279 	char *cp;
1280 
1281 	cp = cp0;
1282 	do {
1283 		c = (int)*cp;
1284 		if (c & 0200)
1285 			goto bad;
1286 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
1287 			switch (c) {
1288 			case '\'':
1289 			case '"':
1290 			case '`':
1291 			case ' ':
1292 			case '#':
1293 				goto bad;
1294 			default:
1295 				break;
1296 			}
1297 		}
1298 	} while (*++cp);
1299 	return (1);
1300 
1301 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
1302 	return (0);
1303 }
1304 
1305 BUF *
1306 allocbuf(BUF *bp, int fd, int blksize)
1307 {
1308 	size_t size;
1309 	struct stat stb;
1310 
1311 	if (fstat(fd, &stb) < 0) {
1312 		run_err("fstat: %s", strerror(errno));
1313 		return (0);
1314 	}
1315 	size = ROUNDUP(stb.st_blksize, blksize);
1316 	if (size == 0)
1317 		size = blksize;
1318 	if (bp->cnt >= size)
1319 		return (bp);
1320 	if (bp->buf == NULL)
1321 		bp->buf = xmalloc(size);
1322 	else
1323 		bp->buf = xreallocarray(bp->buf, 1, size);
1324 	memset(bp->buf, 0, size);
1325 	bp->cnt = size;
1326 	return (bp);
1327 }
1328 
1329 void
1330 lostconn(int signo)
1331 {
1332 	if (!iamremote)
1333 		(void)write(STDERR_FILENO, "lost connection\n", 16);
1334 	if (signo)
1335 		_exit(1);
1336 	else
1337 		exit(1);
1338 }
1339