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