xref: /freebsd/crypto/openssh/scp.c (revision 2546665afcaf0d53dc2c7058fee96354b3680f5a)
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.113 2003/11/23 23:21:21 djm 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 limit_rate = 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 			limit_rate = 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 			addargs(&args, "-q");
277 			showprogress = 0;
278 			break;
279 
280 		/* Server options. */
281 		case 'd':
282 			targetshouldbedirectory = 1;
283 			break;
284 		case 'f':	/* "from" */
285 			iamremote = 1;
286 			fflag = 1;
287 			break;
288 		case 't':	/* "to" */
289 			iamremote = 1;
290 			tflag = 1;
291 #ifdef HAVE_CYGWIN
292 			setmode(0, O_BINARY);
293 #endif
294 			break;
295 		default:
296 			usage();
297 		}
298 	argc -= optind;
299 	argv += optind;
300 
301 	if ((pwd = getpwuid(userid = getuid())) == NULL)
302 		fatal("unknown user %u", (u_int) userid);
303 
304 	if (!isatty(STDERR_FILENO))
305 		showprogress = 0;
306 
307 	remin = STDIN_FILENO;
308 	remout = STDOUT_FILENO;
309 
310 	if (fflag) {
311 		/* Follow "protocol", send data. */
312 		(void) response();
313 		source(argc, argv);
314 		exit(errs != 0);
315 	}
316 	if (tflag) {
317 		/* Receive data. */
318 		sink(argc, argv);
319 		exit(errs != 0);
320 	}
321 	if (argc < 2)
322 		usage();
323 	if (argc > 2)
324 		targetshouldbedirectory = 1;
325 
326 	remin = remout = -1;
327 	do_cmd_pid = -1;
328 	/* Command to be executed on remote system using "ssh". */
329 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
330 	    verbose_mode ? " -v" : "",
331 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
332 	    targetshouldbedirectory ? " -d" : "");
333 
334 	(void) signal(SIGPIPE, lostconn);
335 
336 	if ((targ = colon(argv[argc - 1])))	/* Dest is remote host. */
337 		toremote(targ, argc, argv);
338 	else {
339 		tolocal(argc, argv);	/* Dest is local host. */
340 		if (targetshouldbedirectory)
341 			verifydir(argv[argc - 1]);
342 	}
343 	/*
344 	 * Finally check the exit status of the ssh process, if one was forked
345 	 * and no error has occured yet
346 	 */
347 	if (do_cmd_pid != -1 && errs == 0) {
348 		if (remin != -1)
349 		    (void) close(remin);
350 		if (remout != -1)
351 		    (void) close(remout);
352 		if (waitpid(do_cmd_pid, &status, 0) == -1)
353 			errs = 1;
354 		else {
355 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
356 				errs = 1;
357 		}
358 	}
359 	exit(errs != 0);
360 }
361 
362 void
363 toremote(char *targ, int argc, char **argv)
364 {
365 	int i, len;
366 	char *bp, *host, *src, *suser, *thost, *tuser;
367 
368 	*targ++ = 0;
369 	if (*targ == 0)
370 		targ = ".";
371 
372 	if ((thost = strrchr(argv[argc - 1], '@'))) {
373 		/* user@host */
374 		*thost++ = 0;
375 		tuser = argv[argc - 1];
376 		if (*tuser == '\0')
377 			tuser = NULL;
378 	} else {
379 		thost = argv[argc - 1];
380 		tuser = NULL;
381 	}
382 
383 	for (i = 0; i < argc - 1; i++) {
384 		src = colon(argv[i]);
385 		if (src) {	/* remote to remote */
386 			static char *ssh_options =
387 			    "-x -o'ClearAllForwardings yes'";
388 			*src++ = 0;
389 			if (*src == 0)
390 				src = ".";
391 			host = strrchr(argv[i], '@');
392 			len = strlen(ssh_program) + strlen(argv[i]) +
393 			    strlen(src) + (tuser ? strlen(tuser) : 0) +
394 			    strlen(thost) + strlen(targ) +
395 			    strlen(ssh_options) + CMDNEEDS + 20;
396 			bp = xmalloc(len);
397 			if (host) {
398 				*host++ = 0;
399 				host = cleanhostname(host);
400 				suser = argv[i];
401 				if (*suser == '\0')
402 					suser = pwd->pw_name;
403 				else if (!okname(suser)) {
404 					xfree(bp);
405 					continue;
406 				}
407 				if (tuser && !okname(tuser)) {
408 					xfree(bp);
409 					continue;
410 				}
411 				snprintf(bp, len,
412 				    "%s%s %s -n "
413 				    "-l %s %s %s %s '%s%s%s:%s'",
414 				    ssh_program, verbose_mode ? " -v" : "",
415 				    ssh_options, suser, host, cmd, src,
416 				    tuser ? tuser : "", tuser ? "@" : "",
417 				    thost, targ);
418 			} else {
419 				host = cleanhostname(argv[i]);
420 				snprintf(bp, len,
421 				    "exec %s%s %s -n %s "
422 				    "%s %s '%s%s%s:%s'",
423 				    ssh_program, verbose_mode ? " -v" : "",
424 				    ssh_options, host, cmd, src,
425 				    tuser ? tuser : "", tuser ? "@" : "",
426 				    thost, targ);
427 			}
428 			if (verbose_mode)
429 				fprintf(stderr, "Executing: %s\n", bp);
430 			if (system(bp) != 0)
431 				errs = 1;
432 			(void) xfree(bp);
433 		} else {	/* local to remote */
434 			if (remin == -1) {
435 				len = strlen(targ) + CMDNEEDS + 20;
436 				bp = xmalloc(len);
437 				(void) snprintf(bp, len, "%s -t %s", cmd, targ);
438 				host = cleanhostname(thost);
439 				if (do_cmd(host, tuser, bp, &remin,
440 				    &remout, argc) < 0)
441 					exit(1);
442 				if (response() < 0)
443 					exit(1);
444 				(void) xfree(bp);
445 			}
446 			source(1, argv + i);
447 		}
448 	}
449 }
450 
451 void
452 tolocal(int argc, char **argv)
453 {
454 	int i, len;
455 	char *bp, *host, *src, *suser;
456 
457 	for (i = 0; i < argc - 1; i++) {
458 		if (!(src = colon(argv[i]))) {	/* Local to local. */
459 			len = strlen(_PATH_CP) + strlen(argv[i]) +
460 			    strlen(argv[argc - 1]) + 20;
461 			bp = xmalloc(len);
462 			(void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
463 			    iamrecursive ? " -r" : "", pflag ? " -p" : "",
464 			    argv[i], argv[argc - 1]);
465 			if (verbose_mode)
466 				fprintf(stderr, "Executing: %s\n", bp);
467 			if (system(bp))
468 				++errs;
469 			(void) xfree(bp);
470 			continue;
471 		}
472 		*src++ = 0;
473 		if (*src == 0)
474 			src = ".";
475 		if ((host = strrchr(argv[i], '@')) == NULL) {
476 			host = argv[i];
477 			suser = NULL;
478 		} else {
479 			*host++ = 0;
480 			suser = argv[i];
481 			if (*suser == '\0')
482 				suser = pwd->pw_name;
483 		}
484 		host = cleanhostname(host);
485 		len = strlen(src) + CMDNEEDS + 20;
486 		bp = xmalloc(len);
487 		(void) snprintf(bp, len, "%s -f %s", cmd, src);
488 		if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
489 			(void) xfree(bp);
490 			++errs;
491 			continue;
492 		}
493 		xfree(bp);
494 		sink(1, argv + argc - 1);
495 		(void) close(remin);
496 		remin = remout = -1;
497 	}
498 }
499 
500 void
501 source(int argc, char **argv)
502 {
503 	struct stat stb;
504 	static BUF buffer;
505 	BUF *bp;
506 	off_t i, amt, result, statbytes;
507 	int fd, haderr, indx;
508 	char *last, *name, buf[2048];
509 	int len;
510 
511 	for (indx = 0; indx < argc; ++indx) {
512 		name = argv[indx];
513 		statbytes = 0;
514 		len = strlen(name);
515 		while (len > 1 && name[len-1] == '/')
516 			name[--len] = '\0';
517 		if (strchr(name, '\n') != NULL) {
518 			run_err("%s: skipping, filename contains a newline",
519 			    name);
520 			goto next;
521 		}
522 		if ((fd = open(name, O_RDONLY, 0)) < 0)
523 			goto syserr;
524 		if (fstat(fd, &stb) < 0) {
525 syserr:			run_err("%s: %s", name, strerror(errno));
526 			goto next;
527 		}
528 		switch (stb.st_mode & S_IFMT) {
529 		case S_IFREG:
530 			break;
531 		case S_IFDIR:
532 			if (iamrecursive) {
533 				rsource(name, &stb);
534 				goto next;
535 			}
536 			/* FALLTHROUGH */
537 		default:
538 			run_err("%s: not a regular file", name);
539 			goto next;
540 		}
541 		if ((last = strrchr(name, '/')) == NULL)
542 			last = name;
543 		else
544 			++last;
545 		curfile = last;
546 		if (pflag) {
547 			/*
548 			 * Make it compatible with possible future
549 			 * versions expecting microseconds.
550 			 */
551 			(void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
552 			    (u_long) stb.st_mtime,
553 			    (u_long) stb.st_atime);
554 			(void) atomicio(vwrite, remout, buf, strlen(buf));
555 			if (response() < 0)
556 				goto next;
557 		}
558 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
559 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
560 		    (u_int) (stb.st_mode & FILEMODEMASK),
561 		    (int64_t)stb.st_size, last);
562 		if (verbose_mode) {
563 			fprintf(stderr, "Sending file modes: %s", buf);
564 		}
565 		(void) atomicio(vwrite, remout, buf, strlen(buf));
566 		if (response() < 0)
567 			goto next;
568 		if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
569 next:			(void) close(fd);
570 			continue;
571 		}
572 		if (showprogress)
573 			start_progress_meter(curfile, stb.st_size, &statbytes);
574 		/* Keep writing after an error so that we stay sync'd up. */
575 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
576 			amt = bp->cnt;
577 			if (i + amt > stb.st_size)
578 				amt = stb.st_size - i;
579 			if (!haderr) {
580 				result = atomicio(read, fd, bp->buf, amt);
581 				if (result != amt)
582 					haderr = result >= 0 ? EIO : errno;
583 			}
584 			if (haderr)
585 				(void) atomicio(vwrite, remout, bp->buf, amt);
586 			else {
587 				result = atomicio(vwrite, remout, bp->buf, amt);
588 				if (result != amt)
589 					haderr = result >= 0 ? EIO : errno;
590 				statbytes += result;
591 			}
592 			if (limit_rate)
593 				bwlimit(amt);
594 		}
595 		if (showprogress)
596 			stop_progress_meter();
597 
598 		if (close(fd) < 0 && !haderr)
599 			haderr = errno;
600 		if (!haderr)
601 			(void) atomicio(vwrite, remout, "", 1);
602 		else
603 			run_err("%s: %s", name, strerror(haderr));
604 		(void) response();
605 	}
606 }
607 
608 void
609 rsource(char *name, struct stat *statp)
610 {
611 	DIR *dirp;
612 	struct dirent *dp;
613 	char *last, *vect[1], path[1100];
614 
615 	if (!(dirp = opendir(name))) {
616 		run_err("%s: %s", name, strerror(errno));
617 		return;
618 	}
619 	last = strrchr(name, '/');
620 	if (last == 0)
621 		last = name;
622 	else
623 		last++;
624 	if (pflag) {
625 		(void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
626 		    (u_long) statp->st_mtime,
627 		    (u_long) statp->st_atime);
628 		(void) atomicio(vwrite, remout, path, strlen(path));
629 		if (response() < 0) {
630 			closedir(dirp);
631 			return;
632 		}
633 	}
634 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
635 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
636 	if (verbose_mode)
637 		fprintf(stderr, "Entering directory: %s", path);
638 	(void) atomicio(vwrite, remout, path, strlen(path));
639 	if (response() < 0) {
640 		closedir(dirp);
641 		return;
642 	}
643 	while ((dp = readdir(dirp)) != NULL) {
644 		if (dp->d_ino == 0)
645 			continue;
646 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
647 			continue;
648 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
649 			run_err("%s/%s: name too long", name, dp->d_name);
650 			continue;
651 		}
652 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
653 		vect[0] = path;
654 		source(1, vect);
655 	}
656 	(void) closedir(dirp);
657 	(void) atomicio(vwrite, remout, "E\n", 2);
658 	(void) response();
659 }
660 
661 void
662 bwlimit(int amount)
663 {
664 	static struct timeval bwstart, bwend;
665 	static int lamt, thresh = 16384;
666 	u_int64_t wait;
667 	struct timespec ts, rm;
668 
669 	if (!timerisset(&bwstart)) {
670 		gettimeofday(&bwstart, NULL);
671 		return;
672 	}
673 
674 	lamt += amount;
675 	if (lamt < thresh)
676 		return;
677 
678 	gettimeofday(&bwend, NULL);
679 	timersub(&bwend, &bwstart, &bwend);
680 	if (!timerisset(&bwend))
681 		return;
682 
683 	lamt *= 8;
684 	wait = (double)1000000L * lamt / limit_rate;
685 
686 	bwstart.tv_sec = wait / 1000000L;
687 	bwstart.tv_usec = wait % 1000000L;
688 
689 	if (timercmp(&bwstart, &bwend, >)) {
690 		timersub(&bwstart, &bwend, &bwend);
691 
692 		/* Adjust the wait time */
693 		if (bwend.tv_sec) {
694 			thresh /= 2;
695 			if (thresh < 2048)
696 				thresh = 2048;
697 		} else if (bwend.tv_usec < 100) {
698 			thresh *= 2;
699 			if (thresh > 32768)
700 				thresh = 32768;
701 		}
702 
703 		TIMEVAL_TO_TIMESPEC(&bwend, &ts);
704 		while (nanosleep(&ts, &rm) == -1) {
705 			if (errno != EINTR)
706 				break;
707 			ts = rm;
708 		}
709 	}
710 
711 	lamt = 0;
712 	gettimeofday(&bwstart, NULL);
713 }
714 
715 void
716 sink(int argc, char **argv)
717 {
718 	static BUF buffer;
719 	struct stat stb;
720 	enum {
721 		YES, NO, DISPLAYED
722 	} wrerr;
723 	BUF *bp;
724 	off_t i, j;
725 	int amt, count, exists, first, mask, mode, ofd, omode;
726 	off_t size, statbytes;
727 	int setimes, targisdir, wrerrno = 0;
728 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
729 	struct timeval tv[2];
730 
731 #define	atime	tv[0]
732 #define	mtime	tv[1]
733 #define	SCREWUP(str)	do { why = str; goto screwup; } while (0)
734 
735 	setimes = targisdir = 0;
736 	mask = umask(0);
737 	if (!pflag)
738 		(void) umask(mask);
739 	if (argc != 1) {
740 		run_err("ambiguous target");
741 		exit(1);
742 	}
743 	targ = *argv;
744 	if (targetshouldbedirectory)
745 		verifydir(targ);
746 
747 	(void) atomicio(vwrite, remout, "", 1);
748 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
749 		targisdir = 1;
750 	for (first = 1;; first = 0) {
751 		cp = buf;
752 		if (atomicio(read, remin, cp, 1) <= 0)
753 			return;
754 		if (*cp++ == '\n')
755 			SCREWUP("unexpected <newline>");
756 		do {
757 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
758 				SCREWUP("lost connection");
759 			*cp++ = ch;
760 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
761 		*cp = 0;
762 
763 		if (buf[0] == '\01' || buf[0] == '\02') {
764 			if (iamremote == 0)
765 				(void) atomicio(vwrite, STDERR_FILENO,
766 				    buf + 1, strlen(buf + 1));
767 			if (buf[0] == '\02')
768 				exit(1);
769 			++errs;
770 			continue;
771 		}
772 		if (buf[0] == 'E') {
773 			(void) atomicio(vwrite, remout, "", 1);
774 			return;
775 		}
776 		if (ch == '\n')
777 			*--cp = 0;
778 
779 		cp = buf;
780 		if (*cp == 'T') {
781 			setimes++;
782 			cp++;
783 			mtime.tv_sec = strtol(cp, &cp, 10);
784 			if (!cp || *cp++ != ' ')
785 				SCREWUP("mtime.sec not delimited");
786 			mtime.tv_usec = strtol(cp, &cp, 10);
787 			if (!cp || *cp++ != ' ')
788 				SCREWUP("mtime.usec not delimited");
789 			atime.tv_sec = strtol(cp, &cp, 10);
790 			if (!cp || *cp++ != ' ')
791 				SCREWUP("atime.sec not delimited");
792 			atime.tv_usec = strtol(cp, &cp, 10);
793 			if (!cp || *cp++ != '\0')
794 				SCREWUP("atime.usec not delimited");
795 			(void) atomicio(vwrite, remout, "", 1);
796 			continue;
797 		}
798 		if (*cp != 'C' && *cp != 'D') {
799 			/*
800 			 * Check for the case "rcp remote:foo\* local:bar".
801 			 * In this case, the line "No match." can be returned
802 			 * by the shell before the rcp command on the remote is
803 			 * executed so the ^Aerror_message convention isn't
804 			 * followed.
805 			 */
806 			if (first) {
807 				run_err("%s", cp);
808 				exit(1);
809 			}
810 			SCREWUP("expected control record");
811 		}
812 		mode = 0;
813 		for (++cp; cp < buf + 5; cp++) {
814 			if (*cp < '0' || *cp > '7')
815 				SCREWUP("bad mode");
816 			mode = (mode << 3) | (*cp - '0');
817 		}
818 		if (*cp++ != ' ')
819 			SCREWUP("mode not delimited");
820 
821 		for (size = 0; isdigit(*cp);)
822 			size = size * 10 + (*cp++ - '0');
823 		if (*cp++ != ' ')
824 			SCREWUP("size not delimited");
825 		if (targisdir) {
826 			static char *namebuf;
827 			static int cursize;
828 			size_t need;
829 
830 			need = strlen(targ) + strlen(cp) + 250;
831 			if (need > cursize) {
832 				if (namebuf)
833 					xfree(namebuf);
834 				namebuf = xmalloc(need);
835 				cursize = need;
836 			}
837 			(void) snprintf(namebuf, need, "%s%s%s", targ,
838 			    strcmp(targ, "/") ? "/" : "", cp);
839 			np = namebuf;
840 		} else
841 			np = targ;
842 		curfile = cp;
843 		exists = stat(np, &stb) == 0;
844 		if (buf[0] == 'D') {
845 			int mod_flag = pflag;
846 			if (exists) {
847 				if (!S_ISDIR(stb.st_mode)) {
848 					errno = ENOTDIR;
849 					goto bad;
850 				}
851 				if (pflag)
852 					(void) chmod(np, mode);
853 			} else {
854 				/* Handle copying from a read-only
855 				   directory */
856 				mod_flag = 1;
857 				if (mkdir(np, mode | S_IRWXU) < 0)
858 					goto bad;
859 			}
860 			vect[0] = xstrdup(np);
861 			sink(1, vect);
862 			if (setimes) {
863 				setimes = 0;
864 				if (utimes(vect[0], tv) < 0)
865 					run_err("%s: set times: %s",
866 					    vect[0], strerror(errno));
867 			}
868 			if (mod_flag)
869 				(void) chmod(vect[0], mode);
870 			if (vect[0])
871 				xfree(vect[0]);
872 			continue;
873 		}
874 		omode = mode;
875 		mode |= S_IWRITE;
876 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
877 bad:			run_err("%s: %s", np, strerror(errno));
878 			continue;
879 		}
880 		(void) atomicio(vwrite, remout, "", 1);
881 		if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
882 			(void) close(ofd);
883 			continue;
884 		}
885 		cp = bp->buf;
886 		wrerr = NO;
887 
888 		statbytes = 0;
889 		if (showprogress)
890 			start_progress_meter(curfile, size, &statbytes);
891 		for (count = i = 0; i < size; i += 4096) {
892 			amt = 4096;
893 			if (i + amt > size)
894 				amt = size - i;
895 			count += amt;
896 			do {
897 				j = read(remin, cp, amt);
898 				if (j == -1 && (errno == EINTR ||
899 				    errno == EAGAIN)) {
900 					continue;
901 				} else if (j <= 0) {
902 					run_err("%s", j ? strerror(errno) :
903 					    "dropped connection");
904 					exit(1);
905 				}
906 				amt -= j;
907 				cp += j;
908 				statbytes += j;
909 			} while (amt > 0);
910 
911 			if (limit_rate)
912 				bwlimit(4096);
913 
914 			if (count == bp->cnt) {
915 				/* Keep reading so we stay sync'd up. */
916 				if (wrerr == NO) {
917 					j = atomicio(vwrite, ofd, bp->buf, count);
918 					if (j != count) {
919 						wrerr = YES;
920 						wrerrno = j >= 0 ? EIO : errno;
921 					}
922 				}
923 				count = 0;
924 				cp = bp->buf;
925 			}
926 		}
927 		if (showprogress)
928 			stop_progress_meter();
929 		if (count != 0 && wrerr == NO &&
930 		    (j = atomicio(vwrite, ofd, bp->buf, count)) != count) {
931 			wrerr = YES;
932 			wrerrno = j >= 0 ? EIO : errno;
933 		}
934 		if (wrerr == NO && ftruncate(ofd, size) != 0) {
935 			run_err("%s: truncate: %s", np, strerror(errno));
936 			wrerr = DISPLAYED;
937 		}
938 		if (pflag) {
939 			if (exists || omode != mode)
940 #ifdef HAVE_FCHMOD
941 				if (fchmod(ofd, omode))
942 #else /* HAVE_FCHMOD */
943 				if (chmod(np, omode))
944 #endif /* HAVE_FCHMOD */
945 					run_err("%s: set mode: %s",
946 					    np, strerror(errno));
947 		} else {
948 			if (!exists && omode != mode)
949 #ifdef HAVE_FCHMOD
950 				if (fchmod(ofd, omode & ~mask))
951 #else /* HAVE_FCHMOD */
952 				if (chmod(np, omode & ~mask))
953 #endif /* HAVE_FCHMOD */
954 					run_err("%s: set mode: %s",
955 					    np, strerror(errno));
956 		}
957 		if (close(ofd) == -1) {
958 			wrerr = YES;
959 			wrerrno = errno;
960 		}
961 		(void) response();
962 		if (setimes && wrerr == NO) {
963 			setimes = 0;
964 			if (utimes(np, tv) < 0) {
965 				run_err("%s: set times: %s",
966 				    np, strerror(errno));
967 				wrerr = DISPLAYED;
968 			}
969 		}
970 		switch (wrerr) {
971 		case YES:
972 			run_err("%s: %s", np, strerror(wrerrno));
973 			break;
974 		case NO:
975 			(void) atomicio(vwrite, remout, "", 1);
976 			break;
977 		case DISPLAYED:
978 			break;
979 		}
980 	}
981 screwup:
982 	run_err("protocol error: %s", why);
983 	exit(1);
984 }
985 
986 int
987 response(void)
988 {
989 	char ch, *cp, resp, rbuf[2048];
990 
991 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
992 		lostconn(0);
993 
994 	cp = rbuf;
995 	switch (resp) {
996 	case 0:		/* ok */
997 		return (0);
998 	default:
999 		*cp++ = resp;
1000 		/* FALLTHROUGH */
1001 	case 1:		/* error, followed by error msg */
1002 	case 2:		/* fatal error, "" */
1003 		do {
1004 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1005 				lostconn(0);
1006 			*cp++ = ch;
1007 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1008 
1009 		if (!iamremote)
1010 			(void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1011 		++errs;
1012 		if (resp == 1)
1013 			return (-1);
1014 		exit(1);
1015 	}
1016 	/* NOTREACHED */
1017 }
1018 
1019 void
1020 usage(void)
1021 {
1022 	(void) fprintf(stderr,
1023 	    "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1024 	    "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1025 	    "           [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
1026 	exit(1);
1027 }
1028 
1029 void
1030 run_err(const char *fmt,...)
1031 {
1032 	static FILE *fp;
1033 	va_list ap;
1034 
1035 	++errs;
1036 	if (fp == NULL && !(fp = fdopen(remout, "w")))
1037 		return;
1038 	(void) fprintf(fp, "%c", 0x01);
1039 	(void) fprintf(fp, "scp: ");
1040 	va_start(ap, fmt);
1041 	(void) vfprintf(fp, fmt, ap);
1042 	va_end(ap);
1043 	(void) fprintf(fp, "\n");
1044 	(void) fflush(fp);
1045 
1046 	if (!iamremote) {
1047 		va_start(ap, fmt);
1048 		vfprintf(stderr, fmt, ap);
1049 		va_end(ap);
1050 		fprintf(stderr, "\n");
1051 	}
1052 }
1053 
1054 void
1055 verifydir(char *cp)
1056 {
1057 	struct stat stb;
1058 
1059 	if (!stat(cp, &stb)) {
1060 		if (S_ISDIR(stb.st_mode))
1061 			return;
1062 		errno = ENOTDIR;
1063 	}
1064 	run_err("%s: %s", cp, strerror(errno));
1065 	exit(1);
1066 }
1067 
1068 int
1069 okname(char *cp0)
1070 {
1071 	int c;
1072 	char *cp;
1073 
1074 	cp = cp0;
1075 	do {
1076 		c = (int)*cp;
1077 		if (c & 0200)
1078 			goto bad;
1079 		if (!isalpha(c) && !isdigit(c)) {
1080 			switch (c) {
1081 			case '\'':
1082 			case '"':
1083 			case '`':
1084 			case ' ':
1085 			case '#':
1086 				goto bad;
1087 			default:
1088 				break;
1089 			}
1090 		}
1091 	} while (*++cp);
1092 	return (1);
1093 
1094 bad:	fprintf(stderr, "%s: invalid user name\n", cp0);
1095 	return (0);
1096 }
1097 
1098 BUF *
1099 allocbuf(BUF *bp, int fd, int blksize)
1100 {
1101 	size_t size;
1102 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1103 	struct stat stb;
1104 
1105 	if (fstat(fd, &stb) < 0) {
1106 		run_err("fstat: %s", strerror(errno));
1107 		return (0);
1108 	}
1109 	size = roundup(stb.st_blksize, blksize);
1110 	if (size == 0)
1111 		size = blksize;
1112 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1113 	size = blksize;
1114 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1115 	if (bp->cnt >= size)
1116 		return (bp);
1117 	if (bp->buf == NULL)
1118 		bp->buf = xmalloc(size);
1119 	else
1120 		bp->buf = xrealloc(bp->buf, size);
1121 	memset(bp->buf, 0, size);
1122 	bp->cnt = size;
1123 	return (bp);
1124 }
1125 
1126 void
1127 lostconn(int signo)
1128 {
1129 	if (!iamremote)
1130 		write(STDERR_FILENO, "lost connection\n", 16);
1131 	if (signo)
1132 		_exit(1);
1133 	else
1134 		exit(1);
1135 }
1136