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