xref: /netbsd-src/bin/rcp/rcp.c (revision fad4c9f71477ae11cea2ee75ec82151ac770a534)
1 /*	$NetBSD: rcp.c,v 1.42 2006/03/20 04:03:10 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.42 2006/03/20 04:03:10 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 #ifdef __GNUC__
329 	/* This outrageous construct just to shut up a GCC warning. */
330 	(void) &i;
331 #endif
332 
333 	for (indx = 0; indx < argc; ++indx) {
334 		name = argv[indx];
335 		if ((fd = open(name, O_RDONLY, 0)) < 0)
336 			goto syserr;
337 		if (fstat(fd, &stb)) {
338 syserr:			run_err("%s: %s", name, strerror(errno));
339 			goto next;
340 		}
341 		switch (stb.st_mode & S_IFMT) {
342 		case S_IFREG:
343 			break;
344 		case S_IFDIR:
345 			if (iamrecursive) {
346 				rsource(name, &stb);
347 				goto next;
348 			}
349 			/* FALLTHROUGH */
350 		default:
351 			run_err("%s: not a regular file", name);
352 			goto next;
353 		}
354 		if ((last = strrchr(name, '/')) == NULL)
355 			last = name;
356 		else
357 			++last;
358 		if (pflag) {
359 			/*
360 			 * Make it compatible with possible future
361 			 * versions expecting microseconds.
362 			 */
363 			(void)snprintf(buf, sizeof(buf), "T%ld %ld %ld %ld\n",
364 			    (long)stb.st_mtimespec.tv_sec,
365 			    (long)stb.st_mtimespec.tv_nsec / 1000,
366 			    (long)stb.st_atimespec.tv_sec,
367 			    (long)stb.st_atimespec.tv_nsec / 1000);
368 			(void)write(rem, buf, strlen(buf));
369 			if (response() < 0)
370 				goto next;
371 		}
372 #define	RCPMODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
373 		(void)snprintf(buf, sizeof(buf), "C%04o %lld %s\n",
374 		    stb.st_mode & RCPMODEMASK, (long long)stb.st_size, last);
375 		(void)write(rem, buf, strlen(buf));
376 		if (response() < 0)
377 			goto next;
378 		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
379 next:			(void)close(fd);
380 			continue;
381 		}
382 
383 		/* Keep writing after an error so that we stay sync'd up. */
384 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
385 			amt = bp->cnt;
386 			if (i + amt > stb.st_size)
387 				amt = stb.st_size - i;
388 			if (!haderr) {
389 				result = read(fd, bp->buf, amt);
390 				if (result != amt)
391 					haderr = result >= 0 ? EIO : errno;
392 			}
393 			if (haderr)
394 				(void)write(rem, bp->buf, amt);
395 			else {
396 				result = write(rem, bp->buf, amt);
397 				if (result != amt)
398 					haderr = result >= 0 ? EIO : errno;
399 			}
400 		}
401 		if (close(fd) && !haderr)
402 			haderr = errno;
403 		if (!haderr)
404 			(void)write(rem, "", 1);
405 		else
406 			run_err("%s: %s", name, strerror(haderr));
407 		(void)response();
408 	}
409 }
410 
411 void
412 rsource(char *name, struct stat *statp)
413 {
414 	DIR *dirp;
415 	struct dirent *dp;
416 	char *last, *vect[1], path[MAXPATHLEN];
417 
418 	if (!(dirp = opendir(name))) {
419 		run_err("%s: %s", name, strerror(errno));
420 		return;
421 	}
422 	last = strrchr(name, '/');
423 	if (last == 0)
424 		last = name;
425 	else
426 		last++;
427 	if (pflag) {
428 		(void)snprintf(path, sizeof(path), "T%ld %ld %ld %ld\n",
429 		    (long)statp->st_mtimespec.tv_sec,
430 		    (long)statp->st_mtimespec.tv_nsec / 1000,
431 		    (long)statp->st_atimespec.tv_sec,
432 		    (long)statp->st_atimespec.tv_nsec / 1000);
433 		(void)write(rem, path, strlen(path));
434 		if (response() < 0) {
435 			closedir(dirp);
436 			return;
437 		}
438 	}
439 	(void)snprintf(path, sizeof(path),
440 	    "D%04o %d %s\n", statp->st_mode & RCPMODEMASK, 0, last);
441 	(void)write(rem, path, strlen(path));
442 	if (response() < 0) {
443 		closedir(dirp);
444 		return;
445 	}
446 	while ((dp = readdir(dirp)) != NULL) {
447 		if (dp->d_ino == 0)
448 			continue;
449 		if (!strcmp(dp->d_name, dot) || !strcmp(dp->d_name, ".."))
450 			continue;
451 		if (strlen(name) + 1 + strlen(dp->d_name) >= MAXPATHLEN - 1) {
452 			run_err("%s/%s: name too long", name, dp->d_name);
453 			continue;
454 		}
455 		(void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
456 		vect[0] = path;
457 		source(1, vect);
458 	}
459 	(void)closedir(dirp);
460 	(void)write(rem, "E\n", 2);
461 	(void)response();
462 }
463 
464 void
465 sink(int argc, char *argv[])
466 {
467 	static BUF buffer;
468 	struct stat stb;
469 	struct timeval tv[2];
470 	enum { YES, NO, DISPLAYED } wrerr;
471 	BUF *bp;
472 	off_t i, j;
473 	int amt, count, exists, first, mask, mode, ofd, omode;
474 	int setimes, targisdir;
475 	int wrerrno = 0;	/* pacify gcc */
476 	char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ];
477 	const char *why;
478 	off_t size;
479 
480 #define	atime	tv[0]
481 #define	mtime	tv[1]
482 #define	SCREWUP(str)	{ why = str; goto screwup; }
483 
484 #ifdef __GNUC__
485 	/* This outrageous construct just to shut up a GCC warning. */
486 	(void) &i;
487 #endif
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 		for (count = i = 0; i < size; i += BUFSIZ) {
637 			amt = BUFSIZ;
638 			if (i + amt > size)
639 				amt = size - i;
640 			count += amt;
641 			do {
642 				j = read(rem, cp, amt);
643 				if (j <= 0) {
644 					run_err("%s", j ? strerror(errno) :
645 					    "dropped connection");
646 					exit(1);
647 				}
648 				amt -= j;
649 				cp += j;
650 			} while (amt > 0);
651 			if (count == bp->cnt) {
652 				/* Keep reading so we stay sync'd up. */
653 				if (wrerr == NO) {
654 					j = write(ofd, bp->buf, count);
655 					if (j != count) {
656 						wrerr = YES;
657 						wrerrno = j >= 0 ? EIO : errno;
658 					}
659 				}
660 				count = 0;
661 				cp = bp->buf;
662 			}
663 		}
664 		if (count != 0 && wrerr == NO &&
665 		    (j = write(ofd, bp->buf, count)) != count) {
666 			wrerr = YES;
667 			wrerrno = j >= 0 ? EIO : errno;
668 		}
669 		if (ftruncate(ofd, size)) {
670 			run_err("%s: truncate: %s", np, strerror(errno));
671 			wrerr = DISPLAYED;
672 		}
673 		if (pflag) {
674 			if (exists || omode != mode)
675 				if (fchmod(ofd, omode))
676 					run_err("%s: set mode: %s",
677 					    np, strerror(errno));
678 		} else {
679 			if (!exists && omode != mode)
680 				if (fchmod(ofd, omode & ~mask))
681 					run_err("%s: set mode: %s",
682 					    np, strerror(errno));
683 		}
684 #ifndef __SVR4
685 		if (setimes && wrerr == NO) {
686 			setimes = 0;
687 			if (futimes(ofd, tv) < 0) {
688 				run_err("%s: set times: %s",
689 				    np, strerror(errno));
690 				wrerr = DISPLAYED;
691 			}
692 		}
693 #endif
694 		(void)close(ofd);
695 #ifdef __SVR4
696 		if (setimes && wrerr == NO) {
697 			setimes = 0;
698 			if (utimes(np, tv) < 0) {
699 				run_err("%s: set times: %s",
700 				    np, strerror(errno));
701 				wrerr = DISPLAYED;
702 			}
703 		}
704 #endif
705 		(void)response();
706 		switch(wrerr) {
707 		case YES:
708 			run_err("%s: write: %s", np, strerror(wrerrno));
709 			break;
710 		case NO:
711 			(void)write(rem, "", 1);
712 			break;
713 		case DISPLAYED:
714 			break;
715 		}
716 	}
717 screwup:
718 	run_err("protocol error: %s", why);
719 	exit(1);
720 	/* NOTREACHED */
721 }
722 
723 
724 int
725 response(void)
726 {
727 	char ch, *cp, resp, rbuf[BUFSIZ];
728 
729 	if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
730 		lostconn(0);
731 
732 	cp = rbuf;
733 	switch(resp) {
734 	case 0:				/* ok */
735 		return (0);
736 	default:
737 		*cp++ = resp;
738 		/* FALLTHROUGH */
739 	case 1:				/* error, followed by error msg */
740 	case 2:				/* fatal error, "" */
741 		do {
742 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
743 				lostconn(0);
744 			*cp++ = ch;
745 		} while (cp < &rbuf[BUFSIZ] && ch != '\n');
746 
747 		if (!iamremote)
748 			(void)write(STDERR_FILENO, rbuf, cp - rbuf);
749 		++errs;
750 		if (resp == 1)
751 			return (-1);
752 		exit(1);
753 	}
754 	/* NOTREACHED */
755 }
756 
757 void
758 usage(void)
759 {
760 	(void)fprintf(stderr,
761 	    "usage: rcp [-46p] f1 f2; or: rcp [-46pr] f1 ... fn directory\n");
762 	exit(1);
763 	/* NOTREACHED */
764 }
765 
766 #include <stdarg.h>
767 
768 
769 void
770 run_err(const char *fmt, ...)
771 {
772 	static FILE *fp;
773 	va_list ap;
774 
775 	++errs;
776 	if (fp == NULL && !(fp = fdopen(rem, "w")))
777 		return;
778 
779 	va_start(ap, fmt);
780 
781 	(void)fprintf(fp, "%c", 0x01);
782 	(void)fprintf(fp, "rcp: ");
783 	(void)vfprintf(fp, fmt, ap);
784 	(void)fprintf(fp, "\n");
785 	(void)fflush(fp);
786 	va_end(ap);
787 
788 	if (!iamremote) {
789 		va_start(ap, fmt);
790 		vwarnx(fmt, ap);
791 		va_end(ap);
792 	}
793 }
794