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