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