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