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