Home | History | Annotate | Line # | Download | only in rcp
rcp.c revision 1.45.2.1
      1 /*	$NetBSD: rcp.c,v 1.45.2.1 2008/06/04 02:02:57 yamt Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1983, 1990, 1992, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1983, 1990, 1992, 1993\n\
     35 	The Regents of the University of California.  All rights reserved.\n");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)rcp.c	8.2 (Berkeley) 4/2/94";
     41 #else
     42 __RCSID("$NetBSD: rcp.c,v 1.45.2.1 2008/06/04 02:02:57 yamt Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 #include <sys/param.h>
     47 #include <sys/stat.h>
     48 #include <sys/time.h>
     49 #include <sys/socket.h>
     50 #include <netinet/in.h>
     51 #include <netinet/in_systm.h>
     52 #include <netinet/ip.h>
     53 
     54 #include <ctype.h>
     55 #include <dirent.h>
     56 #include <err.h>
     57 #include <errno.h>
     58 #include <fcntl.h>
     59 #include <locale.h>
     60 #include <netdb.h>
     61 #include <pwd.h>
     62 #include <signal.h>
     63 #include <stdio.h>
     64 #include <stdlib.h>
     65 #include <string.h>
     66 #include <unistd.h>
     67 
     68 #include "pathnames.h"
     69 #include "extern.h"
     70 
     71 #define	OPTIONS "46dfprt"
     72 
     73 struct passwd *pwd;
     74 char *pwname;
     75 u_short	port;
     76 uid_t	userid;
     77 int errs, rem;
     78 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
     79 int family = AF_UNSPEC;
     80 static char dot[] = ".";
     81 
     82 #define	CMDNEEDS	64
     83 char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
     84 
     85 int	 response(void);
     86 void	 rsource(char *, struct stat *);
     87 void	 sink(int, char *[]);
     88 void	 source(int, char *[]);
     89 void	 tolocal(int, char *[]);
     90 void	 toremote(char *, int, char *[]);
     91 void	 usage(void);
     92 
     93 int
     94 main(int argc, char *argv[])
     95 {
     96 	struct servent *sp;
     97 	int ch, fflag, tflag;
     98 	char *targ;
     99 	const char *shell;
    100 
    101 	setprogname(argv[0]);
    102 	(void)setlocale(LC_ALL, "");
    103 
    104 	fflag = tflag = 0;
    105 	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
    106 		switch(ch) {			/* User-visible flags. */
    107 		case '4':
    108 			family = AF_INET;
    109 			break;
    110 		case '6':
    111 			family = AF_INET6;
    112 			break;
    113 		case 'K':
    114 			break;
    115 		case 'p':
    116 			pflag = 1;
    117 			break;
    118 		case 'r':
    119 			iamrecursive = 1;
    120 			break;
    121 						/* Server options. */
    122 		case 'd':
    123 			targetshouldbedirectory = 1;
    124 			break;
    125 		case 'f':			/* "from" */
    126 			iamremote = 1;
    127 			fflag = 1;
    128 			break;
    129 		case 't':			/* "to" */
    130 			iamremote = 1;
    131 			tflag = 1;
    132 			break;
    133 		case '?':
    134 		default:
    135 			usage();
    136 		}
    137 	argc -= optind;
    138 	argv += optind;
    139 
    140 	sp = getservbyname(shell = "shell", "tcp");
    141 	if (sp == NULL)
    142 		errx(1, "%s/tcp: unknown service", shell);
    143 	port = sp->s_port;
    144 
    145 	if ((pwd = getpwuid(userid = getuid())) == NULL)
    146 		errx(1, "unknown user %d", (int)userid);
    147 
    148 	if ((pwname = strdup(pwd->pw_name)) == NULL)
    149 		err(1, NULL);
    150 
    151 	rem = STDIN_FILENO;		/* XXX */
    152 
    153 	if (fflag) {			/* Follow "protocol", send data. */
    154 		(void)response();
    155 		source(argc, argv);
    156 		exit(errs);
    157 	}
    158 
    159 	if (tflag) {			/* Receive data. */
    160 		sink(argc, argv);
    161 		exit(errs);
    162 	}
    163 
    164 	if (argc < 2)
    165 		usage();
    166 	if (argc > 2)
    167 		targetshouldbedirectory = 1;
    168 
    169 	rem = -1;
    170 	/* Command to be executed on remote system using "rsh". */
    171 	(void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
    172 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
    173 	    targetshouldbedirectory ? " -d" : "");
    174 
    175 	(void)signal(SIGPIPE, lostconn);
    176 
    177 	if ((targ = colon(argv[argc - 1])) != NULL)/* Dest is remote host. */
    178 		toremote(targ, argc, argv);
    179 	else {
    180 		tolocal(argc, argv);		/* Dest is local host. */
    181 		if (targetshouldbedirectory)
    182 			verifydir(argv[argc - 1]);
    183 	}
    184 	exit(errs);
    185 	/* NOTREACHED */
    186 }
    187 
    188 void
    189 toremote(char *targ, int argc, char *argv[])
    190 {
    191 	int i;
    192 	size_t len;
    193 	char *bp, *host, *src, *suser, *thost, *tuser;
    194 
    195 	*targ++ = 0;
    196 	if (*targ == 0)
    197 		targ = dot;
    198 
    199 	if ((thost = strchr(argv[argc - 1], '@')) != NULL) {
    200 		/* user@host */
    201 		*thost++ = 0;
    202 		tuser = argv[argc - 1];
    203 		if (*tuser == '\0')
    204 			tuser = NULL;
    205 		else if (!okname(tuser))
    206 			exit(1);
    207 	} else {
    208 		thost = argv[argc - 1];
    209 		tuser = NULL;
    210 	}
    211 	thost = unbracket(thost);
    212 
    213 	for (i = 0; i < argc - 1; i++) {
    214 		src = colon(argv[i]);
    215 		if (src) {			/* remote to remote */
    216 			*src++ = 0;
    217 			if (*src == 0)
    218 				src = dot;
    219 			host = strchr(argv[i], '@');
    220 			len = strlen(_PATH_RSH) + strlen(argv[i]) +
    221 			    strlen(src) + (tuser ? strlen(tuser) : 0) +
    222 			    strlen(thost) + strlen(targ) + CMDNEEDS + 20;
    223 			if (!(bp = malloc(len)))
    224 				err(1, NULL);
    225 			if (host) {
    226 				*host++ = 0;
    227 				host = unbracket(host);
    228 				suser = argv[i];
    229 				if (*suser == '\0')
    230 					suser = pwname;
    231 				else if (!okname(suser)) {
    232 					(void)free(bp);
    233 					continue;
    234 				}
    235 				(void)snprintf(bp, len,
    236 				    "%s %s -l %s -n %s %s '%s%s%s:%s'",
    237 				    _PATH_RSH, host, suser, cmd, src,
    238 				    tuser ? tuser : "", tuser ? "@" : "",
    239 				    thost, targ);
    240 			} else {
    241 				host = unbracket(argv[i]);
    242 				(void)snprintf(bp, len,
    243 				    "exec %s %s -n %s %s '%s%s%s:%s'",
    244 				    _PATH_RSH, argv[i], cmd, src,
    245 				    tuser ? tuser : "", tuser ? "@" : "",
    246 				    thost, targ);
    247 			}
    248 			(void)susystem(bp);
    249 			(void)free(bp);
    250 		} else {			/* local to remote */
    251 			if (rem == -1) {
    252 				len = strlen(targ) + CMDNEEDS + 20;
    253 				if (!(bp = malloc(len)))
    254 					err(1, NULL);
    255 				(void)snprintf(bp, len, "%s -t %s", cmd, targ);
    256 				host = thost;
    257 					rem = rcmd_af(&host, port, pwname,
    258 					    tuser ? tuser : pwname,
    259 					    bp, NULL, family);
    260 				if (rem < 0)
    261 					exit(1);
    262 				if (response() < 0)
    263 					exit(1);
    264 				(void)free(bp);
    265 			}
    266 			source(1, argv+i);
    267 		}
    268 	}
    269 }
    270 
    271 void
    272 tolocal(int argc, char *argv[])
    273 {
    274 	int i;
    275 	size_t len;
    276 	char *bp, *host, *src, *suser;
    277 
    278 	for (i = 0; i < argc - 1; i++) {
    279 		if (!(src = colon(argv[i]))) {		/* Local to local. */
    280 			len = strlen(_PATH_CP) + strlen(argv[i]) +
    281 			    strlen(argv[argc - 1]) + 20;
    282 			if (!(bp = malloc(len)))
    283 				err(1, NULL);
    284 			(void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
    285 			    iamrecursive ? " -r" : "", pflag ? " -p" : "",
    286 			    argv[i], argv[argc - 1]);
    287 			if (susystem(bp))
    288 				++errs;
    289 			(void)free(bp);
    290 			continue;
    291 		}
    292 		*src++ = 0;
    293 		if (*src == 0)
    294 			src = dot;
    295 		if ((host = strchr(argv[i], '@')) == NULL) {
    296 			host = argv[i];
    297 			suser = pwname;
    298 		} else {
    299 			*host++ = 0;
    300 			suser = argv[i];
    301 			if (*suser == '\0')
    302 				suser = pwname;
    303 			else if (!okname(suser))
    304 				continue;
    305 		}
    306 		host = unbracket(host);
    307 		len = strlen(src) + CMDNEEDS + 20;
    308 		if ((bp = malloc(len)) == NULL)
    309 			err(1, NULL);
    310 		(void)snprintf(bp, len, "%s -f %s", cmd, src);
    311 		rem =
    312 			rcmd_af(&host, port, pwname, suser, bp, NULL, family);
    313 		(void)free(bp);
    314 		if (rem < 0) {
    315 			++errs;
    316 			continue;
    317 		}
    318 		sink(1, argv + argc - 1);
    319 		(void)close(rem);
    320 		rem = -1;
    321 	}
    322 }
    323 
    324 void
    325 source(int argc, char *argv[])
    326 {
    327 	struct stat stb;
    328 	static BUF buffer;
    329 	BUF *bp;
    330 	off_t i;
    331 	off_t amt;
    332 	int fd, haderr, indx, result;
    333 	char *last, *name, buf[BUFSIZ];
    334 
    335 	for (indx = 0; indx < argc; ++indx) {
    336 		name = argv[indx];
    337 		if ((fd = open(name, O_RDONLY, 0)) < 0)
    338 			goto syserr;
    339 		if (fstat(fd, &stb)) {
    340 syserr:			run_err("%s: %s", name, strerror(errno));
    341 			goto next;
    342 		}
    343 		switch (stb.st_mode & S_IFMT) {
    344 		case S_IFREG:
    345 			break;
    346 		case S_IFDIR:
    347 			if (iamrecursive) {
    348 				rsource(name, &stb);
    349 				goto next;
    350 			}
    351 			/* FALLTHROUGH */
    352 		default:
    353 			run_err("%s: not a regular file", name);
    354 			goto next;
    355 		}
    356 		if ((last = strrchr(name, '/')) == NULL)
    357 			last = name;
    358 		else
    359 			++last;
    360 		if (pflag) {
    361 			/*
    362 			 * Make it compatible with possible future
    363 			 * versions expecting microseconds.
    364 			 */
    365 			(void)snprintf(buf, sizeof(buf), "T%lld %ld %lld %ld\n",
    366 			    (long long)stb.st_mtimespec.tv_sec,
    367 			    (long)stb.st_mtimespec.tv_nsec / 1000,
    368 			    (long long)stb.st_atimespec.tv_sec,
    369 			    (long)stb.st_atimespec.tv_nsec / 1000);
    370 			(void)write(rem, buf, strlen(buf));
    371 			if (response() < 0)
    372 				goto next;
    373 		}
    374 #define	RCPMODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
    375 		(void)snprintf(buf, sizeof(buf), "C%04o %lld %s\n",
    376 		    stb.st_mode & RCPMODEMASK, (long long)stb.st_size, last);
    377 		(void)write(rem, buf, strlen(buf));
    378 		if (response() < 0)
    379 			goto next;
    380 		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
    381 next:			(void)close(fd);
    382 			continue;
    383 		}
    384 
    385 		/* Keep writing after an error so that we stay sync'd up. */
    386 		haderr = 0;
    387 		for (i = 0; i < stb.st_size; i += bp->cnt) {
    388 			amt = bp->cnt;
    389 			if (i + amt > stb.st_size)
    390 				amt = stb.st_size - i;
    391 			if (!haderr) {
    392 				result = read(fd, bp->buf, (size_t)amt);
    393 				if (result != amt)
    394 					haderr = result >= 0 ? EIO : errno;
    395 			}
    396 			if (haderr)
    397 				(void)write(rem, bp->buf, (size_t)amt);
    398 			else {
    399 				result = write(rem, bp->buf, (size_t)amt);
    400 				if (result != amt)
    401 					haderr = result >= 0 ? EIO : errno;
    402 			}
    403 		}
    404 		if (close(fd) && !haderr)
    405 			haderr = errno;
    406 		if (!haderr)
    407 			(void)write(rem, "", 1);
    408 		else
    409 			run_err("%s: %s", name, strerror(haderr));
    410 		(void)response();
    411 	}
    412 }
    413 
    414 void
    415 rsource(char *name, struct stat *statp)
    416 {
    417 	DIR *dirp;
    418 	struct dirent *dp;
    419 	char *last, *vect[1], path[MAXPATHLEN];
    420 
    421 	if (!(dirp = opendir(name))) {
    422 		run_err("%s: %s", name, strerror(errno));
    423 		return;
    424 	}
    425 	last = strrchr(name, '/');
    426 	if (last == 0)
    427 		last = name;
    428 	else
    429 		last++;
    430 	if (pflag) {
    431 		(void)snprintf(path, sizeof(path), "T%lld %ld %lld %ld\n",
    432 		    (long long)statp->st_mtimespec.tv_sec,
    433 		    (long)statp->st_mtimespec.tv_nsec / 1000,
    434 		    (long long)statp->st_atimespec.tv_sec,
    435 		    (long)statp->st_atimespec.tv_nsec / 1000);
    436 		(void)write(rem, path, strlen(path));
    437 		if (response() < 0) {
    438 			(void)closedir(dirp);
    439 			return;
    440 		}
    441 	}
    442 	(void)snprintf(path, sizeof(path),
    443 	    "D%04o %d %s\n", statp->st_mode & RCPMODEMASK, 0, last);
    444 	(void)write(rem, path, strlen(path));
    445 	if (response() < 0) {
    446 		(void)closedir(dirp);
    447 		return;
    448 	}
    449 	while ((dp = readdir(dirp)) != NULL) {
    450 		if (dp->d_ino == 0)
    451 			continue;
    452 		if (!strcmp(dp->d_name, dot) || !strcmp(dp->d_name, ".."))
    453 			continue;
    454 		if (strlen(name) + 1 + strlen(dp->d_name) >= MAXPATHLEN - 1) {
    455 			run_err("%s/%s: name too long", name, dp->d_name);
    456 			continue;
    457 		}
    458 		(void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
    459 		vect[0] = path;
    460 		source(1, vect);
    461 	}
    462 	(void)closedir(dirp);
    463 	(void)write(rem, "E\n", 2);
    464 	(void)response();
    465 }
    466 
    467 void
    468 sink(int argc, char *argv[])
    469 {
    470 	static BUF buffer;
    471 	struct stat stb;
    472 	struct timeval tv[2];
    473 	enum { YES, NO, DISPLAYED } wrerr;
    474 	BUF *bp;
    475 	ssize_t j;
    476 	off_t i;
    477 	off_t amt;
    478 	off_t count;
    479 	int exists, first, ofd;
    480 	mode_t mask;
    481 	mode_t mode;
    482 	mode_t omode;
    483 	int setimes, targisdir;
    484 	int wrerrno = 0;	/* pacify gcc */
    485 	char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ];
    486 	const char *why;
    487 	off_t size;
    488 
    489 #define	atime	tv[0]
    490 #define	mtime	tv[1]
    491 #define	SCREWUP(str)	{ why = str; goto screwup; }
    492 
    493 	setimes = targisdir = 0;
    494 	mask = umask(0);
    495 	if (!pflag)
    496 		(void)umask(mask);
    497 	if (argc != 1) {
    498 		run_err("ambiguous target");
    499 		exit(1);
    500 	}
    501 	targ = *argv;
    502 	if (targetshouldbedirectory)
    503 		verifydir(targ);
    504 	(void)write(rem, "", 1);
    505 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
    506 		targisdir = 1;
    507 	for (first = 1;; first = 0) {
    508 		cp = buf;
    509 		if (read(rem, cp, 1) <= 0)
    510 			return;
    511 		if (*cp++ == '\n')
    512 			SCREWUP("unexpected <newline>");
    513 		do {
    514 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
    515 				SCREWUP("lost connection");
    516 			*cp++ = ch;
    517 		} while (cp < &buf[BUFSIZ - 1] && ch != '\n');
    518 		*cp = 0;
    519 
    520 		if (buf[0] == '\01' || buf[0] == '\02') {
    521 			if (iamremote == 0)
    522 				(void)write(STDERR_FILENO,
    523 				    buf + 1, strlen(buf + 1));
    524 			if (buf[0] == '\02')
    525 				exit(1);
    526 			++errs;
    527 			continue;
    528 		}
    529 		if (buf[0] == 'E') {
    530 			(void)write(rem, "", 1);
    531 			return;
    532 		}
    533 
    534 		if (ch == '\n')
    535 			*--cp = 0;
    536 
    537 #define getnum(t) (t) = 0; while (isdigit((unsigned char)*cp)) (t) = (t) * 10 + (*cp++ - '0');
    538 		cp = buf;
    539 		if (*cp == 'T') {
    540 			setimes++;
    541 			cp++;
    542 			getnum(mtime.tv_sec);
    543 			if (*cp++ != ' ')
    544 				SCREWUP("mtime.sec not delimited");
    545 			getnum(mtime.tv_usec);
    546 			if (*cp++ != ' ')
    547 				SCREWUP("mtime.usec not delimited");
    548 			getnum(atime.tv_sec);
    549 			if (*cp++ != ' ')
    550 				SCREWUP("atime.sec not delimited");
    551 			getnum(atime.tv_usec);
    552 			if (*cp++ != '\0')
    553 				SCREWUP("atime.usec not delimited");
    554 			(void)write(rem, "", 1);
    555 			continue;
    556 		}
    557 		if (*cp != 'C' && *cp != 'D') {
    558 			/*
    559 			 * Check for the case "rcp remote:foo\* local:bar".
    560 			 * In this case, the line "No match." can be returned
    561 			 * by the shell before the rcp command on the remote is
    562 			 * executed so the ^Aerror_message convention isn't
    563 			 * followed.
    564 			 */
    565 			if (first) {
    566 				run_err("%s", cp);
    567 				exit(1);
    568 			}
    569 			SCREWUP("expected control record");
    570 		}
    571 		mode = 0;
    572 		for (++cp; cp < buf + 5; cp++) {
    573 			if (*cp < '0' || *cp > '7')
    574 				SCREWUP("bad mode");
    575 			mode = (mode << 3) | (*cp - '0');
    576 		}
    577 		if (*cp++ != ' ')
    578 			SCREWUP("mode not delimited");
    579 
    580 		for (size = 0; isdigit((unsigned char)*cp);)
    581 			size = size * 10 + (*cp++ - '0');
    582 		if (*cp++ != ' ')
    583 			SCREWUP("size not delimited");
    584 		if (targisdir) {
    585 			static char *namebuf;
    586 			static int cursize;
    587 			size_t need;
    588 
    589 			need = strlen(targ) + strlen(cp) + 250;
    590 			if (need > cursize) {
    591 				if (!(namebuf = malloc(need)))
    592 					run_err("%s", strerror(errno));
    593 			}
    594 			(void)snprintf(namebuf, need, "%s%s%s", targ,
    595 			    *targ ? "/" : "", cp);
    596 			np = namebuf;
    597 		} else
    598 			np = targ;
    599 		exists = stat(np, &stb) == 0;
    600 		if (buf[0] == 'D') {
    601 			int mod_flag = pflag;
    602 			if (exists) {
    603 				if (!S_ISDIR(stb.st_mode)) {
    604 					errno = ENOTDIR;
    605 					goto bad;
    606 				}
    607 				if (pflag)
    608 					(void)chmod(np, mode);
    609 			} else {
    610 				/* Handle copying from a read-only directory */
    611 				mod_flag = 1;
    612 				if (mkdir(np, mode | S_IRWXU) < 0)
    613 					goto bad;
    614 			}
    615 			vect[0] = np;
    616 			sink(1, vect);
    617 			if (setimes) {
    618 				setimes = 0;
    619 				if (utimes(np, tv) < 0)
    620 				    run_err("%s: set times: %s",
    621 					np, strerror(errno));
    622 			}
    623 			if (mod_flag)
    624 				(void)chmod(np, mode);
    625 			continue;
    626 		}
    627 		omode = mode;
    628 		mode |= S_IWRITE;
    629 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
    630 bad:			run_err("%s: %s", np, strerror(errno));
    631 			continue;
    632 		}
    633 		(void)write(rem, "", 1);
    634 		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
    635 			(void)close(ofd);
    636 			continue;
    637 		}
    638 		cp = bp->buf;
    639 		wrerr = NO;
    640 		count = 0;
    641 		for (i = 0; i < size; i += BUFSIZ) {
    642 			amt = BUFSIZ;
    643 			if (i + amt > size)
    644 				amt = size - i;
    645 			count += amt;
    646 			do {
    647 				j = read(rem, cp, (size_t)amt);
    648 				if (j == -1) {
    649 					run_err("%s", j ? strerror(errno) :
    650 					    "dropped connection");
    651 					exit(1);
    652 				}
    653 				amt -= j;
    654 				cp += j;
    655 			} while (amt > 0);
    656 			if (count == bp->cnt) {
    657 				/* Keep reading so we stay sync'd up. */
    658 				if (wrerr == NO) {
    659 					j = write(ofd, bp->buf, (size_t)count);
    660 					if (j != count) {
    661 						wrerr = YES;
    662 						wrerrno = j >= 0 ? EIO : errno;
    663 					}
    664 				}
    665 				count = 0;
    666 				cp = bp->buf;
    667 			}
    668 		}
    669 		if (count != 0 && wrerr == NO &&
    670 		    (j = write(ofd, bp->buf, (size_t)count)) != count) {
    671 			wrerr = YES;
    672 			wrerrno = j >= 0 ? EIO : errno;
    673 		}
    674 		if (ftruncate(ofd, size)) {
    675 			run_err("%s: truncate: %s", np, strerror(errno));
    676 			wrerr = DISPLAYED;
    677 		}
    678 		if (pflag) {
    679 			if (exists || omode != mode)
    680 				if (fchmod(ofd, omode))
    681 					run_err("%s: set mode: %s",
    682 					    np, strerror(errno));
    683 		} else {
    684 			if (!exists && omode != mode)
    685 				if (fchmod(ofd, omode & ~mask))
    686 					run_err("%s: set mode: %s",
    687 					    np, strerror(errno));
    688 		}
    689 #ifndef __SVR4
    690 		if (setimes && wrerr == NO) {
    691 			setimes = 0;
    692 			if (futimes(ofd, tv) < 0) {
    693 				run_err("%s: set times: %s",
    694 				    np, strerror(errno));
    695 				wrerr = DISPLAYED;
    696 			}
    697 		}
    698 #endif
    699 		(void)close(ofd);
    700 #ifdef __SVR4
    701 		if (setimes && wrerr == NO) {
    702 			setimes = 0;
    703 			if (utimes(np, tv) < 0) {
    704 				run_err("%s: set times: %s",
    705 				    np, strerror(errno));
    706 				wrerr = DISPLAYED;
    707 			}
    708 		}
    709 #endif
    710 		(void)response();
    711 		switch(wrerr) {
    712 		case YES:
    713 			run_err("%s: write: %s", np, strerror(wrerrno));
    714 			break;
    715 		case NO:
    716 			(void)write(rem, "", 1);
    717 			break;
    718 		case DISPLAYED:
    719 			break;
    720 		}
    721 	}
    722 screwup:
    723 	run_err("protocol error: %s", why);
    724 	exit(1);
    725 	/* NOTREACHED */
    726 }
    727 
    728 
    729 int
    730 response(void)
    731 {
    732 	char ch, *cp, resp, rbuf[BUFSIZ];
    733 
    734 	if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
    735 		lostconn(0);
    736 
    737 	cp = rbuf;
    738 	switch(resp) {
    739 	case 0:				/* ok */
    740 		return (0);
    741 	default:
    742 		*cp++ = resp;
    743 		/* FALLTHROUGH */
    744 	case 1:				/* error, followed by error msg */
    745 	case 2:				/* fatal error, "" */
    746 		do {
    747 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
    748 				lostconn(0);
    749 			*cp++ = ch;
    750 		} while (cp < &rbuf[BUFSIZ] && ch != '\n');
    751 
    752 		if (!iamremote)
    753 			(void)write(STDERR_FILENO, rbuf, (size_t)(cp - rbuf));
    754 		++errs;
    755 		if (resp == 1)
    756 			return (-1);
    757 		exit(1);
    758 	}
    759 	/* NOTREACHED */
    760 }
    761 
    762 void
    763 usage(void)
    764 {
    765 	(void)fprintf(stderr,
    766 	    "usage: rcp [-46p] f1 f2; or: rcp [-46pr] f1 ... fn directory\n");
    767 	exit(1);
    768 	/* NOTREACHED */
    769 }
    770 
    771 #include <stdarg.h>
    772 
    773 
    774 void
    775 run_err(const char *fmt, ...)
    776 {
    777 	static FILE *fp;
    778 	va_list ap;
    779 
    780 	++errs;
    781 	if (fp == NULL && !(fp = fdopen(rem, "w")))
    782 		return;
    783 
    784 	va_start(ap, fmt);
    785 
    786 	(void)fprintf(fp, "%c", 0x01);
    787 	(void)fprintf(fp, "rcp: ");
    788 	(void)vfprintf(fp, fmt, ap);
    789 	(void)fprintf(fp, "\n");
    790 	(void)fflush(fp);
    791 	va_end(ap);
    792 
    793 	if (!iamremote) {
    794 		va_start(ap, fmt);
    795 		vwarnx(fmt, ap);
    796 		va_end(ap);
    797 	}
    798 }
    799