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