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