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