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