xref: /openbsd-src/usr.bin/ssh/scp.c (revision e5157e49389faebcb42b7237d55fbf096d9c2523)
1 /* $OpenBSD: scp.c,v 1.180 2014/06/24 02:21: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 <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 static int
533 do_times(int fd, int verb, const struct stat *sb)
534 {
535 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
536 	char buf[(20 + 7 + 2) * 2 + 2];
537 
538 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
539 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
540 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
541 	if (verb) {
542 		fprintf(stderr, "File mtime %lld atime %lld\n",
543 		    (long long)sb->st_mtime, (long long)sb->st_atime);
544 		fprintf(stderr, "Sending file timestamps: %s", buf);
545 	}
546 	(void) atomicio(vwrite, fd, buf, strlen(buf));
547 	return (response());
548 }
549 
550 void
551 toremote(char *targ, int argc, char **argv)
552 {
553 	char *bp, *host, *src, *suser, *thost, *tuser, *arg;
554 	arglist alist;
555 	int i;
556 	u_int j;
557 
558 	memset(&alist, '\0', sizeof(alist));
559 	alist.list = NULL;
560 
561 	*targ++ = 0;
562 	if (*targ == 0)
563 		targ = ".";
564 
565 	arg = xstrdup(argv[argc - 1]);
566 	if ((thost = strrchr(arg, '@'))) {
567 		/* user@host */
568 		*thost++ = 0;
569 		tuser = arg;
570 		if (*tuser == '\0')
571 			tuser = NULL;
572 	} else {
573 		thost = arg;
574 		tuser = NULL;
575 	}
576 
577 	if (tuser != NULL && !okname(tuser)) {
578 		free(arg);
579 		return;
580 	}
581 
582 	for (i = 0; i < argc - 1; i++) {
583 		src = colon(argv[i]);
584 		if (src && throughlocal) {	/* extended remote to remote */
585 			*src++ = 0;
586 			if (*src == 0)
587 				src = ".";
588 			host = strrchr(argv[i], '@');
589 			if (host) {
590 				*host++ = 0;
591 				host = cleanhostname(host);
592 				suser = argv[i];
593 				if (*suser == '\0')
594 					suser = pwd->pw_name;
595 				else if (!okname(suser))
596 					continue;
597 			} else {
598 				host = cleanhostname(argv[i]);
599 				suser = NULL;
600 			}
601 			xasprintf(&bp, "%s -f %s%s", cmd,
602 			    *src == '-' ? "-- " : "", src);
603 			if (do_cmd(host, suser, bp, &remin, &remout) < 0)
604 				exit(1);
605 			free(bp);
606 			host = cleanhostname(thost);
607 			xasprintf(&bp, "%s -t %s%s", cmd,
608 			    *targ == '-' ? "-- " : "", targ);
609 			if (do_cmd2(host, tuser, bp, remin, remout) < 0)
610 				exit(1);
611 			free(bp);
612 			(void) close(remin);
613 			(void) close(remout);
614 			remin = remout = -1;
615 		} else if (src) {	/* standard remote to remote */
616 			freeargs(&alist);
617 			addargs(&alist, "%s", ssh_program);
618 			addargs(&alist, "-x");
619 			addargs(&alist, "-oClearAllForwardings=yes");
620 			addargs(&alist, "-n");
621 			for (j = 0; j < remote_remote_args.num; j++) {
622 				addargs(&alist, "%s",
623 				    remote_remote_args.list[j]);
624 			}
625 			*src++ = 0;
626 			if (*src == 0)
627 				src = ".";
628 			host = strrchr(argv[i], '@');
629 
630 			if (host) {
631 				*host++ = 0;
632 				host = cleanhostname(host);
633 				suser = argv[i];
634 				if (*suser == '\0')
635 					suser = pwd->pw_name;
636 				else if (!okname(suser))
637 					continue;
638 				addargs(&alist, "-l");
639 				addargs(&alist, "%s", suser);
640 			} else {
641 				host = cleanhostname(argv[i]);
642 			}
643 			addargs(&alist, "--");
644 			addargs(&alist, "%s", host);
645 			addargs(&alist, "%s", cmd);
646 			addargs(&alist, "%s", src);
647 			addargs(&alist, "%s%s%s:%s",
648 			    tuser ? tuser : "", tuser ? "@" : "",
649 			    thost, targ);
650 			if (do_local_cmd(&alist) != 0)
651 				errs = 1;
652 		} else {	/* local to remote */
653 			if (remin == -1) {
654 				xasprintf(&bp, "%s -t %s%s", cmd,
655 				    *targ == '-' ? "-- " : "", targ);
656 				host = cleanhostname(thost);
657 				if (do_cmd(host, tuser, bp, &remin,
658 				    &remout) < 0)
659 					exit(1);
660 				if (response() < 0)
661 					exit(1);
662 				free(bp);
663 			}
664 			source(1, argv + i);
665 		}
666 	}
667 	free(arg);
668 }
669 
670 void
671 tolocal(int argc, char **argv)
672 {
673 	char *bp, *host, *src, *suser;
674 	arglist alist;
675 	int i;
676 
677 	memset(&alist, '\0', sizeof(alist));
678 	alist.list = NULL;
679 
680 	for (i = 0; i < argc - 1; i++) {
681 		if (!(src = colon(argv[i]))) {	/* Local to local. */
682 			freeargs(&alist);
683 			addargs(&alist, "%s", _PATH_CP);
684 			if (iamrecursive)
685 				addargs(&alist, "-r");
686 			if (pflag)
687 				addargs(&alist, "-p");
688 			addargs(&alist, "--");
689 			addargs(&alist, "%s", argv[i]);
690 			addargs(&alist, "%s", argv[argc-1]);
691 			if (do_local_cmd(&alist))
692 				++errs;
693 			continue;
694 		}
695 		*src++ = 0;
696 		if (*src == 0)
697 			src = ".";
698 		if ((host = strrchr(argv[i], '@')) == NULL) {
699 			host = argv[i];
700 			suser = NULL;
701 		} else {
702 			*host++ = 0;
703 			suser = argv[i];
704 			if (*suser == '\0')
705 				suser = pwd->pw_name;
706 		}
707 		host = cleanhostname(host);
708 		xasprintf(&bp, "%s -f %s%s",
709 		    cmd, *src == '-' ? "-- " : "", src);
710 		if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
711 			free(bp);
712 			++errs;
713 			continue;
714 		}
715 		free(bp);
716 		sink(1, argv + argc - 1);
717 		(void) close(remin);
718 		remin = remout = -1;
719 	}
720 }
721 
722 void
723 source(int argc, char **argv)
724 {
725 	struct stat stb;
726 	static BUF buffer;
727 	BUF *bp;
728 	off_t i, statbytes;
729 	size_t amt, nr;
730 	int fd = -1, haderr, indx;
731 	char *last, *name, buf[2048], encname[MAXPATHLEN];
732 	int len;
733 
734 	for (indx = 0; indx < argc; ++indx) {
735 		name = argv[indx];
736 		statbytes = 0;
737 		len = strlen(name);
738 		while (len > 1 && name[len-1] == '/')
739 			name[--len] = '\0';
740 		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
741 			goto syserr;
742 		if (strchr(name, '\n') != NULL) {
743 			strnvis(encname, name, sizeof(encname), VIS_NL);
744 			name = encname;
745 		}
746 		if (fstat(fd, &stb) < 0) {
747 syserr:			run_err("%s: %s", name, strerror(errno));
748 			goto next;
749 		}
750 		if (stb.st_size < 0) {
751 			run_err("%s: %s", name, "Negative file size");
752 			goto next;
753 		}
754 		unset_nonblock(fd);
755 		switch (stb.st_mode & S_IFMT) {
756 		case S_IFREG:
757 			break;
758 		case S_IFDIR:
759 			if (iamrecursive) {
760 				rsource(name, &stb);
761 				goto next;
762 			}
763 			/* FALLTHROUGH */
764 		default:
765 			run_err("%s: not a regular file", name);
766 			goto next;
767 		}
768 		if ((last = strrchr(name, '/')) == NULL)
769 			last = name;
770 		else
771 			++last;
772 		curfile = last;
773 		if (pflag) {
774 			if (do_times(remout, verbose_mode, &stb) < 0)
775 				goto next;
776 		}
777 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
778 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
779 		    (u_int) (stb.st_mode & FILEMODEMASK),
780 		    (long long)stb.st_size, last);
781 		if (verbose_mode) {
782 			fprintf(stderr, "Sending file modes: %s", buf);
783 		}
784 		(void) atomicio(vwrite, remout, buf, strlen(buf));
785 		if (response() < 0)
786 			goto next;
787 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
788 next:			if (fd != -1) {
789 				(void) close(fd);
790 				fd = -1;
791 			}
792 			continue;
793 		}
794 		if (showprogress)
795 			start_progress_meter(curfile, stb.st_size, &statbytes);
796 		set_nonblock(remout);
797 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
798 			amt = bp->cnt;
799 			if (i + (off_t)amt > stb.st_size)
800 				amt = stb.st_size - i;
801 			if (!haderr) {
802 				if ((nr = atomicio(read, fd,
803 				    bp->buf, amt)) != amt) {
804 					haderr = errno;
805 					memset(bp->buf + nr, 0, amt - nr);
806 				}
807 			}
808 			/* Keep writing after error to retain sync */
809 			if (haderr) {
810 				(void)atomicio(vwrite, remout, bp->buf, amt);
811 				memset(bp->buf, 0, amt);
812 				continue;
813 			}
814 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
815 			    &statbytes) != amt)
816 				haderr = errno;
817 		}
818 		unset_nonblock(remout);
819 		if (showprogress)
820 			stop_progress_meter();
821 
822 		if (fd != -1) {
823 			if (close(fd) < 0 && !haderr)
824 				haderr = errno;
825 			fd = -1;
826 		}
827 		if (!haderr)
828 			(void) atomicio(vwrite, remout, "", 1);
829 		else
830 			run_err("%s: %s", name, strerror(haderr));
831 		(void) response();
832 	}
833 }
834 
835 void
836 rsource(char *name, struct stat *statp)
837 {
838 	DIR *dirp;
839 	struct dirent *dp;
840 	char *last, *vect[1], path[MAXPATHLEN];
841 
842 	if (!(dirp = opendir(name))) {
843 		run_err("%s: %s", name, strerror(errno));
844 		return;
845 	}
846 	last = strrchr(name, '/');
847 	if (last == 0)
848 		last = name;
849 	else
850 		last++;
851 	if (pflag) {
852 		if (do_times(remout, verbose_mode, statp) < 0) {
853 			closedir(dirp);
854 			return;
855 		}
856 	}
857 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
858 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
859 	if (verbose_mode)
860 		fprintf(stderr, "Entering directory: %s", path);
861 	(void) atomicio(vwrite, remout, path, strlen(path));
862 	if (response() < 0) {
863 		closedir(dirp);
864 		return;
865 	}
866 	while ((dp = readdir(dirp)) != NULL) {
867 		if (dp->d_ino == 0)
868 			continue;
869 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
870 			continue;
871 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
872 			run_err("%s/%s: name too long", name, dp->d_name);
873 			continue;
874 		}
875 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
876 		vect[0] = path;
877 		source(1, vect);
878 	}
879 	(void) closedir(dirp);
880 	(void) atomicio(vwrite, remout, "E\n", 2);
881 	(void) response();
882 }
883 
884 void
885 sink(int argc, char **argv)
886 {
887 	static BUF buffer;
888 	struct stat stb;
889 	enum {
890 		YES, NO, DISPLAYED
891 	} wrerr;
892 	BUF *bp;
893 	off_t i;
894 	size_t j, count;
895 	int amt, exists, first, ofd;
896 	mode_t mode, omode, mask;
897 	off_t size, statbytes;
898 	unsigned long long ull;
899 	int setimes, targisdir, wrerrno = 0;
900 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
901 	struct timeval tv[2];
902 
903 #define	atime	tv[0]
904 #define	mtime	tv[1]
905 #define	SCREWUP(str)	{ why = str; goto screwup; }
906 
907 	setimes = targisdir = 0;
908 	mask = umask(0);
909 	if (!pflag)
910 		(void) umask(mask);
911 	if (argc != 1) {
912 		run_err("ambiguous target");
913 		exit(1);
914 	}
915 	targ = *argv;
916 	if (targetshouldbedirectory)
917 		verifydir(targ);
918 
919 	(void) atomicio(vwrite, remout, "", 1);
920 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
921 		targisdir = 1;
922 	for (first = 1;; first = 0) {
923 		cp = buf;
924 		if (atomicio(read, remin, cp, 1) != 1)
925 			return;
926 		if (*cp++ == '\n')
927 			SCREWUP("unexpected <newline>");
928 		do {
929 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
930 				SCREWUP("lost connection");
931 			*cp++ = ch;
932 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
933 		*cp = 0;
934 		if (verbose_mode)
935 			fprintf(stderr, "Sink: %s", buf);
936 
937 		if (buf[0] == '\01' || buf[0] == '\02') {
938 			if (iamremote == 0)
939 				(void) atomicio(vwrite, STDERR_FILENO,
940 				    buf + 1, strlen(buf + 1));
941 			if (buf[0] == '\02')
942 				exit(1);
943 			++errs;
944 			continue;
945 		}
946 		if (buf[0] == 'E') {
947 			(void) atomicio(vwrite, remout, "", 1);
948 			return;
949 		}
950 		if (ch == '\n')
951 			*--cp = 0;
952 
953 		cp = buf;
954 		if (*cp == 'T') {
955 			setimes++;
956 			cp++;
957 			if (!isdigit((unsigned char)*cp))
958 				SCREWUP("mtime.sec not present");
959 			ull = strtoull(cp, &cp, 10);
960 			if (!cp || *cp++ != ' ')
961 				SCREWUP("mtime.sec not delimited");
962 			if ((time_t)ull < 0 ||
963 			    (unsigned long long)(time_t)ull != ull)
964 				setimes = 0;	/* out of range */
965 			mtime.tv_sec = ull;
966 			mtime.tv_usec = strtol(cp, &cp, 10);
967 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
968 			    mtime.tv_usec > 999999)
969 				SCREWUP("mtime.usec not delimited");
970 			if (!isdigit((unsigned char)*cp))
971 				SCREWUP("atime.sec not present");
972 			ull = strtoull(cp, &cp, 10);
973 			if (!cp || *cp++ != ' ')
974 				SCREWUP("atime.sec not delimited");
975 			if ((time_t)ull < 0 ||
976 			    (unsigned long long)(time_t)ull != ull)
977 				setimes = 0;	/* out of range */
978 			atime.tv_sec = ull;
979 			atime.tv_usec = strtol(cp, &cp, 10);
980 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
981 			    atime.tv_usec > 999999)
982 				SCREWUP("atime.usec not delimited");
983 			(void) atomicio(vwrite, remout, "", 1);
984 			continue;
985 		}
986 		if (*cp != 'C' && *cp != 'D') {
987 			/*
988 			 * Check for the case "rcp remote:foo\* local:bar".
989 			 * In this case, the line "No match." can be returned
990 			 * by the shell before the rcp command on the remote is
991 			 * executed so the ^Aerror_message convention isn't
992 			 * followed.
993 			 */
994 			if (first) {
995 				run_err("%s", cp);
996 				exit(1);
997 			}
998 			SCREWUP("expected control record");
999 		}
1000 		mode = 0;
1001 		for (++cp; cp < buf + 5; cp++) {
1002 			if (*cp < '0' || *cp > '7')
1003 				SCREWUP("bad mode");
1004 			mode = (mode << 3) | (*cp - '0');
1005 		}
1006 		if (*cp++ != ' ')
1007 			SCREWUP("mode not delimited");
1008 
1009 		for (size = 0; isdigit((unsigned char)*cp);)
1010 			size = size * 10 + (*cp++ - '0');
1011 		if (*cp++ != ' ')
1012 			SCREWUP("size not delimited");
1013 		if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
1014 			run_err("error: unexpected filename: %s", cp);
1015 			exit(1);
1016 		}
1017 		if (targisdir) {
1018 			static char *namebuf;
1019 			static size_t cursize;
1020 			size_t need;
1021 
1022 			need = strlen(targ) + strlen(cp) + 250;
1023 			if (need > cursize) {
1024 				free(namebuf);
1025 				namebuf = xmalloc(need);
1026 				cursize = need;
1027 			}
1028 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1029 			    strcmp(targ, "/") ? "/" : "", cp);
1030 			np = namebuf;
1031 		} else
1032 			np = targ;
1033 		curfile = cp;
1034 		exists = stat(np, &stb) == 0;
1035 		if (buf[0] == 'D') {
1036 			int mod_flag = pflag;
1037 			if (!iamrecursive)
1038 				SCREWUP("received directory without -r");
1039 			if (exists) {
1040 				if (!S_ISDIR(stb.st_mode)) {
1041 					errno = ENOTDIR;
1042 					goto bad;
1043 				}
1044 				if (pflag)
1045 					(void) chmod(np, mode);
1046 			} else {
1047 				/* Handle copying from a read-only
1048 				   directory */
1049 				mod_flag = 1;
1050 				if (mkdir(np, mode | S_IRWXU) < 0)
1051 					goto bad;
1052 			}
1053 			vect[0] = xstrdup(np);
1054 			sink(1, vect);
1055 			if (setimes) {
1056 				setimes = 0;
1057 				if (utimes(vect[0], tv) < 0)
1058 					run_err("%s: set times: %s",
1059 					    vect[0], strerror(errno));
1060 			}
1061 			if (mod_flag)
1062 				(void) chmod(vect[0], mode);
1063 			free(vect[0]);
1064 			continue;
1065 		}
1066 		omode = mode;
1067 		mode |= S_IWUSR;
1068 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1069 bad:			run_err("%s: %s", np, strerror(errno));
1070 			continue;
1071 		}
1072 		(void) atomicio(vwrite, remout, "", 1);
1073 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1074 			(void) close(ofd);
1075 			continue;
1076 		}
1077 		cp = bp->buf;
1078 		wrerr = NO;
1079 
1080 		statbytes = 0;
1081 		if (showprogress)
1082 			start_progress_meter(curfile, size, &statbytes);
1083 		set_nonblock(remin);
1084 		for (count = i = 0; i < size; i += bp->cnt) {
1085 			amt = bp->cnt;
1086 			if (i + amt > size)
1087 				amt = size - i;
1088 			count += amt;
1089 			do {
1090 				j = atomicio6(read, remin, cp, amt,
1091 				    scpio, &statbytes);
1092 				if (j == 0) {
1093 					run_err("%s", j != EPIPE ?
1094 					    strerror(errno) :
1095 					    "dropped connection");
1096 					exit(1);
1097 				}
1098 				amt -= j;
1099 				cp += j;
1100 			} while (amt > 0);
1101 
1102 			if (count == bp->cnt) {
1103 				/* Keep reading so we stay sync'd up. */
1104 				if (wrerr == NO) {
1105 					if (atomicio(vwrite, ofd, bp->buf,
1106 					    count) != count) {
1107 						wrerr = YES;
1108 						wrerrno = errno;
1109 					}
1110 				}
1111 				count = 0;
1112 				cp = bp->buf;
1113 			}
1114 		}
1115 		unset_nonblock(remin);
1116 		if (showprogress)
1117 			stop_progress_meter();
1118 		if (count != 0 && wrerr == NO &&
1119 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1120 			wrerr = YES;
1121 			wrerrno = errno;
1122 		}
1123 		if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1124 		    ftruncate(ofd, size) != 0) {
1125 			run_err("%s: truncate: %s", np, strerror(errno));
1126 			wrerr = DISPLAYED;
1127 		}
1128 		if (pflag) {
1129 			if (exists || omode != mode)
1130 				if (fchmod(ofd, omode)) {
1131 					run_err("%s: set mode: %s",
1132 					    np, strerror(errno));
1133 					wrerr = DISPLAYED;
1134 				}
1135 		} else {
1136 			if (!exists && omode != mode)
1137 				if (fchmod(ofd, omode & ~mask)) {
1138 					run_err("%s: set mode: %s",
1139 					    np, strerror(errno));
1140 					wrerr = DISPLAYED;
1141 				}
1142 		}
1143 		if (close(ofd) == -1) {
1144 			wrerr = YES;
1145 			wrerrno = errno;
1146 		}
1147 		(void) response();
1148 		if (setimes && wrerr == NO) {
1149 			setimes = 0;
1150 			if (utimes(np, tv) < 0) {
1151 				run_err("%s: set times: %s",
1152 				    np, strerror(errno));
1153 				wrerr = DISPLAYED;
1154 			}
1155 		}
1156 		switch (wrerr) {
1157 		case YES:
1158 			run_err("%s: %s", np, strerror(wrerrno));
1159 			break;
1160 		case NO:
1161 			(void) atomicio(vwrite, remout, "", 1);
1162 			break;
1163 		case DISPLAYED:
1164 			break;
1165 		}
1166 	}
1167 screwup:
1168 	run_err("protocol error: %s", why);
1169 	exit(1);
1170 }
1171 
1172 int
1173 response(void)
1174 {
1175 	char ch, *cp, resp, rbuf[2048];
1176 
1177 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1178 		lostconn(0);
1179 
1180 	cp = rbuf;
1181 	switch (resp) {
1182 	case 0:		/* ok */
1183 		return (0);
1184 	default:
1185 		*cp++ = resp;
1186 		/* FALLTHROUGH */
1187 	case 1:		/* error, followed by error msg */
1188 	case 2:		/* fatal error, "" */
1189 		do {
1190 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1191 				lostconn(0);
1192 			*cp++ = ch;
1193 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1194 
1195 		if (!iamremote)
1196 			(void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1197 		++errs;
1198 		if (resp == 1)
1199 			return (-1);
1200 		exit(1);
1201 	}
1202 	/* NOTREACHED */
1203 }
1204 
1205 void
1206 usage(void)
1207 {
1208 	(void) fprintf(stderr,
1209 	    "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1210 	    "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1211 	    "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1212 	exit(1);
1213 }
1214 
1215 void
1216 run_err(const char *fmt,...)
1217 {
1218 	static FILE *fp;
1219 	va_list ap;
1220 
1221 	++errs;
1222 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1223 		(void) fprintf(fp, "%c", 0x01);
1224 		(void) fprintf(fp, "scp: ");
1225 		va_start(ap, fmt);
1226 		(void) vfprintf(fp, fmt, ap);
1227 		va_end(ap);
1228 		(void) fprintf(fp, "\n");
1229 		(void) fflush(fp);
1230 	}
1231 
1232 	if (!iamremote) {
1233 		va_start(ap, fmt);
1234 		vfprintf(stderr, fmt, ap);
1235 		va_end(ap);
1236 		fprintf(stderr, "\n");
1237 	}
1238 }
1239 
1240 void
1241 verifydir(char *cp)
1242 {
1243 	struct stat stb;
1244 
1245 	if (!stat(cp, &stb)) {
1246 		if (S_ISDIR(stb.st_mode))
1247 			return;
1248 		errno = ENOTDIR;
1249 	}
1250 	run_err("%s: %s", cp, strerror(errno));
1251 	killchild(0);
1252 }
1253 
1254 int
1255 okname(char *cp0)
1256 {
1257 	int c;
1258 	char *cp;
1259 
1260 	cp = cp0;
1261 	do {
1262 		c = (int)*cp;
1263 		if (c & 0200)
1264 			goto bad;
1265 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
1266 			switch (c) {
1267 			case '\'':
1268 			case '"':
1269 			case '`':
1270 			case ' ':
1271 			case '#':
1272 				goto bad;
1273 			default:
1274 				break;
1275 			}
1276 		}
1277 	} while (*++cp);
1278 	return (1);
1279 
1280 bad:	fprintf(stderr, "%s: invalid user name\n", cp0);
1281 	return (0);
1282 }
1283 
1284 BUF *
1285 allocbuf(BUF *bp, int fd, int blksize)
1286 {
1287 	size_t size;
1288 	struct stat stb;
1289 
1290 	if (fstat(fd, &stb) < 0) {
1291 		run_err("fstat: %s", strerror(errno));
1292 		return (0);
1293 	}
1294 	size = roundup(stb.st_blksize, blksize);
1295 	if (size == 0)
1296 		size = blksize;
1297 	if (bp->cnt >= size)
1298 		return (bp);
1299 	if (bp->buf == NULL)
1300 		bp->buf = xmalloc(size);
1301 	else
1302 		bp->buf = xrealloc(bp->buf, 1, size);
1303 	memset(bp->buf, 0, size);
1304 	bp->cnt = size;
1305 	return (bp);
1306 }
1307 
1308 void
1309 lostconn(int signo)
1310 {
1311 	if (!iamremote)
1312 		(void)write(STDERR_FILENO, "lost connection\n", 16);
1313 	if (signo)
1314 		_exit(1);
1315 	else
1316 		exit(1);
1317 }
1318