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