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