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