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