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