Home | History | Annotate | Line # | Download | only in rcp
rcp.c revision 1.49.12.1
      1 /*	$NetBSD: rcp.c,v 1.49.12.1 2020/05/07 12:01:00 sborrill 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\
     35  The Regents of the University of California.  All rights reserved.");
     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.49.12.1 2020/05/07 12:01:00 sborrill 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 	BUF *bp;
    474 	ssize_t j;
    475 	off_t i;
    476 	off_t amt;
    477 	off_t count;
    478 	int exists, first, ofd;
    479 	mode_t mask;
    480 	mode_t mode;
    481 	mode_t omode;
    482 	int setimes, targisdir, wrerr;
    483 	int wrerrno = 0;	/* pacify gcc */
    484 	const char *wrcontext = NULL;
    485 	char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ];
    486 	const char *why;
    487 	off_t size;
    488 	char *namebuf = NULL;
    489 	size_t cursize = 0;
    490 
    491 #define	atime	tv[0]
    492 #define	mtime	tv[1]
    493 #define	SCREWUP(str)	{ why = str; goto screwup; }
    494 
    495 	setimes = targisdir = 0;
    496 	mask = umask(0);
    497 	if (!pflag)
    498 		(void)umask(mask);
    499 	if (argc != 1) {
    500 		run_err("ambiguous target");
    501 		exit(1);
    502 	}
    503 	targ = *argv;
    504 	if (targetshouldbedirectory)
    505 		verifydir(targ);
    506 	(void)write(rem, "", 1);
    507 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
    508 		targisdir = 1;
    509 	for (first = 1;; first = 0) {
    510 		cp = buf;
    511 		if (read(rem, cp, 1) <= 0)
    512 			goto out;
    513 		if (*cp++ == '\n')
    514 			SCREWUP("unexpected <newline>");
    515 		do {
    516 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
    517 				SCREWUP("lost connection");
    518 			*cp++ = ch;
    519 		} while (cp < &buf[BUFSIZ - 1] && ch != '\n');
    520 		*cp = 0;
    521 
    522 		if (buf[0] == '\01' || buf[0] == '\02') {
    523 			if (iamremote == 0)
    524 				(void)write(STDERR_FILENO,
    525 				    buf + 1, strlen(buf + 1));
    526 			if (buf[0] == '\02')
    527 				exit(1);
    528 			++errs;
    529 			continue;
    530 		}
    531 		if (buf[0] == 'E') {
    532 			(void)write(rem, "", 1);
    533 			goto out;
    534 		}
    535 
    536 		if (ch == '\n')
    537 			*--cp = 0;
    538 
    539 #define getnum(t) (t) = 0; while (isdigit((unsigned char)*cp)) (t) = (t) * 10 + (*cp++ - '0');
    540 		cp = buf;
    541 		if (*cp == 'T') {
    542 			setimes++;
    543 			cp++;
    544 			getnum(mtime.tv_sec);
    545 			if (*cp++ != ' ')
    546 				SCREWUP("mtime.sec not delimited");
    547 			getnum(mtime.tv_usec);
    548 			if (*cp++ != ' ')
    549 				SCREWUP("mtime.usec not delimited");
    550 			getnum(atime.tv_sec);
    551 			if (*cp++ != ' ')
    552 				SCREWUP("atime.sec not delimited");
    553 			getnum(atime.tv_usec);
    554 			if (*cp++ != '\0')
    555 				SCREWUP("atime.usec not delimited");
    556 			(void)write(rem, "", 1);
    557 			continue;
    558 		}
    559 		if (*cp != 'C' && *cp != 'D') {
    560 			/*
    561 			 * Check for the case "rcp remote:foo\* local:bar".
    562 			 * In this case, the line "No match." can be returned
    563 			 * by the shell before the rcp command on the remote is
    564 			 * executed so the ^Aerror_message convention isn't
    565 			 * followed.
    566 			 */
    567 			if (first) {
    568 				run_err("%s", cp);
    569 				exit(1);
    570 			}
    571 			SCREWUP("expected control record");
    572 		}
    573 		mode = 0;
    574 		for (++cp; cp < buf + 5; cp++) {
    575 			if (*cp < '0' || *cp > '7')
    576 				SCREWUP("bad mode");
    577 			mode = (mode << 3) | (*cp - '0');
    578 		}
    579 		if (*cp++ != ' ')
    580 			SCREWUP("mode not delimited");
    581 
    582 		for (size = 0; isdigit((unsigned char)*cp);)
    583 			size = size * 10 + (*cp++ - '0');
    584 		if (*cp++ != ' ')
    585 			SCREWUP("size not delimited");
    586 		if (targisdir) {
    587 			char *newnamebuf;
    588 			size_t need;
    589 
    590 			need = strlen(targ) + strlen(cp) + 2;
    591 			if (need > cursize) {
    592 				need += 256;
    593 				newnamebuf = realloc(namebuf, need);
    594 				if (newnamebuf != NULL) {
    595 					namebuf = newnamebuf;
    596 					cursize = need;
    597 				} else {
    598 					run_err("%s", strerror(errno));
    599 					exit(1);
    600 				}
    601 			}
    602 			(void)snprintf(namebuf, cursize, "%s%s%s", targ,
    603 			    *targ ? "/" : "", cp);
    604 			np = namebuf;
    605 		} else
    606 			np = targ;
    607 		exists = stat(np, &stb) == 0;
    608 		if (buf[0] == 'D') {
    609 			int mod_flag = pflag;
    610 			if (exists) {
    611 				if (!S_ISDIR(stb.st_mode)) {
    612 					errno = ENOTDIR;
    613 					goto bad;
    614 				}
    615 				if (pflag)
    616 					(void)chmod(np, mode);
    617 			} else {
    618 				/* Handle copying from a read-only directory */
    619 				mod_flag = 1;
    620 				if (mkdir(np, mode | S_IRWXU) < 0)
    621 					goto bad;
    622 			}
    623 			vect[0] = np;
    624 			sink(1, vect);
    625 			if (setimes) {
    626 				setimes = 0;
    627 				(void) utimes(np, tv);
    628 			}
    629 			if (mod_flag)
    630 				(void)chmod(np, mode);
    631 			continue;
    632 		}
    633 		omode = mode;
    634 		mode |= S_IWRITE;
    635 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
    636 bad:			run_err("%s: %s", np, strerror(errno));
    637 			continue;
    638 		}
    639 		(void)write(rem, "", 1);
    640 		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
    641 			(void)close(ofd);
    642 			continue;
    643 		}
    644 		cp = bp->buf;
    645 		wrerr = 0;
    646 
    647 /*
    648  * Like run_err(), but don't send any message to the remote end.
    649  * Instead, record the first error and send that in the end.
    650  */
    651 #define RUN_ERR(w_context) do { \
    652 	if (!wrerr) {							\
    653 		wrerrno = errno;					\
    654 		wrcontext = w_context;					\
    655 		wrerr = 1;						\
    656 	}								\
    657 } while(0)
    658 
    659 		count = 0;
    660 		for (i = 0; i < size; i += BUFSIZ) {
    661 			amt = BUFSIZ;
    662 			if (i + amt > size)
    663 				amt = size - i;
    664 			count += amt;
    665 			do {
    666 				j = read(rem, cp, (size_t)amt);
    667 				if (j == -1) {
    668 					run_err("%s", j ? strerror(errno) :
    669 					    "dropped connection");
    670 					exit(1);
    671 				}
    672 				amt -= j;
    673 				cp += j;
    674 			} while (amt > 0);
    675 			if (count == bp->cnt) {
    676 				/* Keep reading so we stay sync'd up. */
    677 				if (!wrerr) {
    678 					j = write(ofd, bp->buf, (size_t)count);
    679 					if (j != count) {
    680 						if (j >= 0)
    681 							errno = EIO;
    682 						RUN_ERR("write");
    683 					}
    684 				}
    685 				count = 0;
    686 				cp = bp->buf;
    687 			}
    688 		}
    689 		if (count != 0 && !wrerr &&
    690 		    (j = write(ofd, bp->buf, (size_t)count)) != count) {
    691 			if (j >= 0)
    692 				errno = EIO;
    693 			RUN_ERR("write");
    694 		}
    695 		if (ftruncate(ofd, size))
    696 			RUN_ERR("truncate");
    697 
    698 		if (pflag) {
    699 			if (exists || omode != mode)
    700 				if (fchmod(ofd, omode))
    701 					RUN_ERR("set mode");
    702 		} else {
    703 			if (!exists && omode != mode)
    704 				if (fchmod(ofd, omode & ~mask))
    705 					RUN_ERR("set mode");
    706 		}
    707 #ifndef __SVR4
    708 		if (setimes && !wrerr) {
    709 			setimes = 0;
    710 			if (futimes(ofd, tv) < 0)
    711 				RUN_ERR("set times");
    712 		}
    713 #endif
    714 		(void)close(ofd);
    715 #ifdef __SVR4
    716 		if (setimes && !wrerr) {
    717 			setimes = 0;
    718 			if (utimes(np, tv) < 0)
    719 				RUN_ERR("set times");
    720 		}
    721 #endif
    722 		(void)response();
    723 		if (wrerr)
    724 			run_err("%s: %s: %s", np, wrcontext, strerror(wrerrno));
    725 		else
    726 			(void)write(rem, "", 1);
    727 	}
    728 
    729 out:
    730 	if (namebuf) {
    731 		free(namebuf);
    732 	}
    733 	return;
    734 
    735 screwup:
    736 	run_err("protocol error: %s", why);
    737 	exit(1);
    738 	/* NOTREACHED */
    739 }
    740 
    741 
    742 int
    743 response(void)
    744 {
    745 	char ch, *cp, resp, rbuf[BUFSIZ];
    746 
    747 	if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
    748 		lostconn(0);
    749 
    750 	cp = rbuf;
    751 	switch(resp) {
    752 	case 0:				/* ok */
    753 		return (0);
    754 	default:
    755 		*cp++ = resp;
    756 		/* FALLTHROUGH */
    757 	case 1:				/* error, followed by error msg */
    758 	case 2:				/* fatal error, "" */
    759 		do {
    760 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
    761 				lostconn(0);
    762 			*cp++ = ch;
    763 		} while (cp < &rbuf[BUFSIZ] && ch != '\n');
    764 
    765 		if (!iamremote)
    766 			(void)write(STDERR_FILENO, rbuf, (size_t)(cp - rbuf));
    767 		++errs;
    768 		if (resp == 1)
    769 			return (-1);
    770 		exit(1);
    771 	}
    772 	/* NOTREACHED */
    773 }
    774 
    775 void
    776 usage(void)
    777 {
    778 	(void)fprintf(stderr,
    779 	    "usage: rcp [-46p] f1 f2; or: rcp [-46pr] f1 ... fn directory\n");
    780 	exit(1);
    781 	/* NOTREACHED */
    782 }
    783 
    784 #include <stdarg.h>
    785 
    786 
    787 void
    788 run_err(const char *fmt, ...)
    789 {
    790 	static FILE *fp;
    791 	va_list ap;
    792 
    793 	++errs;
    794 	if (fp == NULL && !(fp = fdopen(rem, "w")))
    795 		return;
    796 
    797 	va_start(ap, fmt);
    798 
    799 	(void)fprintf(fp, "%c", 0x01);
    800 	(void)fprintf(fp, "rcp: ");
    801 	(void)vfprintf(fp, fmt, ap);
    802 	(void)fprintf(fp, "\n");
    803 	(void)fflush(fp);
    804 	va_end(ap);
    805 
    806 	if (!iamremote) {
    807 		va_start(ap, fmt);
    808 		vwarnx(fmt, ap);
    809 		va_end(ap);
    810 	}
    811 }
    812