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