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