xref: /minix/bin/rcp/rcp.c (revision 9f988b79)
1 /*	$NetBSD: rcp.c,v 1.49 2012/05/07 15:22:54 chs 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 2012/05/07 15:22:54 chs Exp $");
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 #include <sys/stat.h>
48 #include <sys/time.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
53 
54 #include <ctype.h>
55 #include <dirent.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <locale.h>
60 #include <netdb.h>
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 
68 #include "pathnames.h"
69 #include "extern.h"
70 
71 #define	OPTIONS "46dfprt"
72 
73 struct passwd *pwd;
74 char *pwname;
75 u_short	port;
76 uid_t	userid;
77 int errs, rem;
78 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
79 int family = AF_UNSPEC;
80 static char dot[] = ".";
81 
82 #define	CMDNEEDS	64
83 char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
84 
85 int	 response(void);
86 void	 rsource(char *, struct stat *);
87 void	 sink(int, char *[]);
88 void	 source(int, char *[]);
89 void	 tolocal(int, char *[]);
90 void	 toremote(char *, int, char *[]);
91 void	 usage(void);
92 
93 int
94 main(int argc, char *argv[])
95 {
96 	struct servent *sp;
97 	int ch, fflag, tflag;
98 	char *targ;
99 	const char *shell;
100 
101 	setprogname(argv[0]);
102 	(void)setlocale(LC_ALL, "");
103 
104 	fflag = tflag = 0;
105 	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
106 		switch(ch) {			/* User-visible flags. */
107 		case '4':
108 			family = AF_INET;
109 			break;
110 		case '6':
111 			family = AF_INET6;
112 			break;
113 		case 'K':
114 			break;
115 		case 'p':
116 			pflag = 1;
117 			break;
118 		case 'r':
119 			iamrecursive = 1;
120 			break;
121 						/* Server options. */
122 		case 'd':
123 			targetshouldbedirectory = 1;
124 			break;
125 		case 'f':			/* "from" */
126 			iamremote = 1;
127 			fflag = 1;
128 			break;
129 		case 't':			/* "to" */
130 			iamremote = 1;
131 			tflag = 1;
132 			break;
133 		case '?':
134 		default:
135 			usage();
136 		}
137 	argc -= optind;
138 	argv += optind;
139 
140 	sp = getservbyname(shell = "shell", "tcp");
141 	if (sp == NULL)
142 		errx(1, "%s/tcp: unknown service", shell);
143 	port = sp->s_port;
144 
145 	if ((pwd = getpwuid(userid = getuid())) == NULL)
146 		errx(1, "unknown user %d", (int)userid);
147 
148 	if ((pwname = strdup(pwd->pw_name)) == NULL)
149 		err(1, NULL);
150 
151 	rem = STDIN_FILENO;		/* XXX */
152 
153 	if (fflag) {			/* Follow "protocol", send data. */
154 		(void)response();
155 		source(argc, argv);
156 		exit(errs);
157 	}
158 
159 	if (tflag) {			/* Receive data. */
160 		sink(argc, argv);
161 		exit(errs);
162 	}
163 
164 	if (argc < 2)
165 		usage();
166 	if (argc > 2)
167 		targetshouldbedirectory = 1;
168 
169 	rem = -1;
170 	/* Command to be executed on remote system using "rsh". */
171 	(void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
172 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
173 	    targetshouldbedirectory ? " -d" : "");
174 
175 	(void)signal(SIGPIPE, lostconn);
176 
177 	if ((targ = colon(argv[argc - 1])) != NULL)/* Dest is remote host. */
178 		toremote(targ, argc, argv);
179 	else {
180 		tolocal(argc, argv);		/* Dest is local host. */
181 		if (targetshouldbedirectory)
182 			verifydir(argv[argc - 1]);
183 	}
184 	exit(errs);
185 	/* NOTREACHED */
186 }
187 
188 void
189 toremote(char *targ, int argc, char *argv[])
190 {
191 	int i;
192 	size_t len;
193 	char *bp, *host, *src, *suser, *thost, *tuser;
194 
195 	*targ++ = 0;
196 	if (*targ == 0)
197 		targ = dot;
198 
199 	if ((thost = strchr(argv[argc - 1], '@')) != NULL) {
200 		/* user@host */
201 		*thost++ = 0;
202 		tuser = argv[argc - 1];
203 		if (*tuser == '\0')
204 			tuser = NULL;
205 		else if (!okname(tuser))
206 			exit(1);
207 	} else {
208 		thost = argv[argc - 1];
209 		tuser = NULL;
210 	}
211 	thost = unbracket(thost);
212 
213 	for (i = 0; i < argc - 1; i++) {
214 		src = colon(argv[i]);
215 		if (src) {			/* remote to remote */
216 			*src++ = 0;
217 			if (*src == 0)
218 				src = dot;
219 			host = strchr(argv[i], '@');
220 			len = strlen(_PATH_RSH) + strlen(argv[i]) +
221 			    strlen(src) + (tuser ? strlen(tuser) : 0) +
222 			    strlen(thost) + strlen(targ) + CMDNEEDS + 20;
223 			if (!(bp = malloc(len)))
224 				err(1, NULL);
225 			if (host) {
226 				*host++ = 0;
227 				host = unbracket(host);
228 				suser = argv[i];
229 				if (*suser == '\0')
230 					suser = pwname;
231 				else if (!okname(suser)) {
232 					(void)free(bp);
233 					continue;
234 				}
235 				(void)snprintf(bp, len,
236 				    "%s %s -l %s -n %s %s '%s%s%s:%s'",
237 				    _PATH_RSH, host, suser, cmd, src,
238 				    tuser ? tuser : "", tuser ? "@" : "",
239 				    thost, targ);
240 			} else {
241 				host = unbracket(argv[i]);
242 				(void)snprintf(bp, len,
243 				    "exec %s %s -n %s %s '%s%s%s:%s'",
244 				    _PATH_RSH, argv[i], cmd, src,
245 				    tuser ? tuser : "", tuser ? "@" : "",
246 				    thost, targ);
247 			}
248 			(void)susystem(bp);
249 			(void)free(bp);
250 		} else {			/* local to remote */
251 			if (rem == -1) {
252 				len = strlen(targ) + CMDNEEDS + 20;
253 				if (!(bp = malloc(len)))
254 					err(1, NULL);
255 				(void)snprintf(bp, len, "%s -t %s", cmd, targ);
256 				host = thost;
257 					rem = rcmd_af(&host, port, pwname,
258 					    tuser ? tuser : pwname,
259 					    bp, NULL, family);
260 				if (rem < 0)
261 					exit(1);
262 				if (response() < 0)
263 					exit(1);
264 				(void)free(bp);
265 			}
266 			source(1, argv+i);
267 		}
268 	}
269 }
270 
271 void
272 tolocal(int argc, char *argv[])
273 {
274 	int i;
275 	size_t len;
276 	char *bp, *host, *src, *suser;
277 
278 	for (i = 0; i < argc - 1; i++) {
279 		if (!(src = colon(argv[i]))) {		/* Local to local. */
280 			len = strlen(_PATH_CP) + strlen(argv[i]) +
281 			    strlen(argv[argc - 1]) + 20;
282 			if (!(bp = malloc(len)))
283 				err(1, NULL);
284 			(void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
285 			    iamrecursive ? " -r" : "", pflag ? " -p" : "",
286 			    argv[i], argv[argc - 1]);
287 			if (susystem(bp))
288 				++errs;
289 			(void)free(bp);
290 			continue;
291 		}
292 		*src++ = 0;
293 		if (*src == 0)
294 			src = dot;
295 		if ((host = strchr(argv[i], '@')) == NULL) {
296 			host = argv[i];
297 			suser = pwname;
298 		} else {
299 			*host++ = 0;
300 			suser = argv[i];
301 			if (*suser == '\0')
302 				suser = pwname;
303 			else if (!okname(suser))
304 				continue;
305 		}
306 		host = unbracket(host);
307 		len = strlen(src) + CMDNEEDS + 20;
308 		if ((bp = malloc(len)) == NULL)
309 			err(1, NULL);
310 		(void)snprintf(bp, len, "%s -f %s", cmd, src);
311 		rem =
312 			rcmd_af(&host, port, pwname, suser, bp, NULL, family);
313 		(void)free(bp);
314 		if (rem < 0) {
315 			++errs;
316 			continue;
317 		}
318 		sink(1, argv + argc - 1);
319 		(void)close(rem);
320 		rem = -1;
321 	}
322 }
323 
324 void
325 source(int argc, char *argv[])
326 {
327 	struct stat stb;
328 	static BUF buffer;
329 	BUF *bp;
330 	off_t i;
331 	off_t amt;
332 	int fd, haderr, indx, result;
333 	char *last, *name, buf[BUFSIZ];
334 
335 	for (indx = 0; indx < argc; ++indx) {
336 		name = argv[indx];
337 		if ((fd = open(name, O_RDONLY, 0)) < 0)
338 			goto syserr;
339 		if (fstat(fd, &stb)) {
340 syserr:			run_err("%s: %s", name, strerror(errno));
341 			goto next;
342 		}
343 		switch (stb.st_mode & S_IFMT) {
344 		case S_IFREG:
345 			break;
346 		case S_IFDIR:
347 			if (iamrecursive) {
348 				rsource(name, &stb);
349 				goto next;
350 			}
351 			/* FALLTHROUGH */
352 		default:
353 			run_err("%s: not a regular file", name);
354 			goto next;
355 		}
356 		if ((last = strrchr(name, '/')) == NULL)
357 			last = name;
358 		else
359 			++last;
360 		if (pflag) {
361 			/*
362 			 * Make it compatible with possible future
363 			 * versions expecting microseconds.
364 			 */
365 			(void)snprintf(buf, sizeof(buf), "T%lld %ld %lld %ld\n",
366 			    (long long)stb.st_mtimespec.tv_sec,
367 			    (long)stb.st_mtimespec.tv_nsec / 1000,
368 			    (long long)stb.st_atimespec.tv_sec,
369 			    (long)stb.st_atimespec.tv_nsec / 1000);
370 			(void)write(rem, buf, strlen(buf));
371 			if (response() < 0)
372 				goto next;
373 		}
374 #define	RCPMODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
375 		(void)snprintf(buf, sizeof(buf), "C%04o %lld %s\n",
376 		    stb.st_mode & RCPMODEMASK, (long long)stb.st_size, last);
377 		(void)write(rem, buf, strlen(buf));
378 		if (response() < 0)
379 			goto next;
380 		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
381 next:			(void)close(fd);
382 			continue;
383 		}
384 
385 		/* Keep writing after an error so that we stay sync'd up. */
386 		haderr = 0;
387 		for (i = 0; i < stb.st_size; i += bp->cnt) {
388 			amt = bp->cnt;
389 			if (i + amt > stb.st_size)
390 				amt = stb.st_size - i;
391 			if (!haderr) {
392 				result = read(fd, bp->buf, (size_t)amt);
393 				if (result != amt)
394 					haderr = result >= 0 ? EIO : errno;
395 			}
396 			if (haderr)
397 				(void)write(rem, bp->buf, (size_t)amt);
398 			else {
399 				result = write(rem, bp->buf, (size_t)amt);
400 				if (result != amt)
401 					haderr = result >= 0 ? EIO : errno;
402 			}
403 		}
404 		if (close(fd) && !haderr)
405 			haderr = errno;
406 		if (!haderr)
407 			(void)write(rem, "", 1);
408 		else
409 			run_err("%s: %s", name, strerror(haderr));
410 		(void)response();
411 	}
412 }
413 
414 void
415 rsource(char *name, struct stat *statp)
416 {
417 	DIR *dirp;
418 	struct dirent *dp;
419 	char *last, *vect[1], path[MAXPATHLEN];
420 
421 	if (!(dirp = opendir(name))) {
422 		run_err("%s: %s", name, strerror(errno));
423 		return;
424 	}
425 	last = strrchr(name, '/');
426 	if (last == 0)
427 		last = name;
428 	else
429 		last++;
430 	if (pflag) {
431 		(void)snprintf(path, sizeof(path), "T%lld %ld %lld %ld\n",
432 		    (long long)statp->st_mtimespec.tv_sec,
433 		    (long)statp->st_mtimespec.tv_nsec / 1000,
434 		    (long long)statp->st_atimespec.tv_sec,
435 		    (long)statp->st_atimespec.tv_nsec / 1000);
436 		(void)write(rem, path, strlen(path));
437 		if (response() < 0) {
438 			(void)closedir(dirp);
439 			return;
440 		}
441 	}
442 	(void)snprintf(path, sizeof(path),
443 	    "D%04o %d %s\n", statp->st_mode & RCPMODEMASK, 0, last);
444 	(void)write(rem, path, strlen(path));
445 	if (response() < 0) {
446 		(void)closedir(dirp);
447 		return;
448 	}
449 	while ((dp = readdir(dirp)) != NULL) {
450 		if (dp->d_ino == 0)
451 			continue;
452 		if (!strcmp(dp->d_name, dot) || !strcmp(dp->d_name, ".."))
453 			continue;
454 		if (strlen(name) + 1 + strlen(dp->d_name) >= MAXPATHLEN - 1) {
455 			run_err("%s/%s: name too long", name, dp->d_name);
456 			continue;
457 		}
458 		(void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
459 		vect[0] = path;
460 		source(1, vect);
461 	}
462 	(void)closedir(dirp);
463 	(void)write(rem, "E\n", 2);
464 	(void)response();
465 }
466 
467 void
468 sink(int argc, char *argv[])
469 {
470 	static BUF buffer;
471 	struct stat stb;
472 	struct timeval tv[2];
473 	enum { YES, NO, DISPLAYED } wrerr;
474 	BUF *bp;
475 	ssize_t j;
476 	off_t i;
477 	off_t amt;
478 	off_t count;
479 	int exists, first, ofd;
480 	mode_t mask;
481 	mode_t mode;
482 	mode_t omode;
483 	int setimes, targisdir;
484 	int wrerrno = 0;	/* pacify gcc */
485 	char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ];
486 	const char *why;
487 	off_t size;
488 	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 				if (utimes(np, tv) < 0)
628 				    run_err("%s: set times: %s",
629 					np, strerror(errno));
630 			}
631 			if (mod_flag)
632 				(void)chmod(np, mode);
633 			continue;
634 		}
635 		omode = mode;
636 		mode |= S_IWRITE;
637 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
638 bad:			run_err("%s: %s", np, strerror(errno));
639 			continue;
640 		}
641 		(void)write(rem, "", 1);
642 		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
643 			(void)close(ofd);
644 			continue;
645 		}
646 		cp = bp->buf;
647 		wrerr = NO;
648 		count = 0;
649 		for (i = 0; i < size; i += BUFSIZ) {
650 			amt = BUFSIZ;
651 			if (i + amt > size)
652 				amt = size - i;
653 			count += amt;
654 			do {
655 				j = read(rem, cp, (size_t)amt);
656 				if (j == -1) {
657 					run_err("%s", j ? strerror(errno) :
658 					    "dropped connection");
659 					exit(1);
660 				}
661 				amt -= j;
662 				cp += j;
663 			} while (amt > 0);
664 			if (count == bp->cnt) {
665 				/* Keep reading so we stay sync'd up. */
666 				if (wrerr == NO) {
667 					j = write(ofd, bp->buf, (size_t)count);
668 					if (j != count) {
669 						wrerr = YES;
670 						wrerrno = j >= 0 ? EIO : errno;
671 					}
672 				}
673 				count = 0;
674 				cp = bp->buf;
675 			}
676 		}
677 		if (count != 0 && wrerr == NO &&
678 		    (j = write(ofd, bp->buf, (size_t)count)) != count) {
679 			wrerr = YES;
680 			wrerrno = j >= 0 ? EIO : errno;
681 		}
682 		if (ftruncate(ofd, size)) {
683 			run_err("%s: truncate: %s", np, strerror(errno));
684 			wrerr = DISPLAYED;
685 		}
686 		if (pflag) {
687 			if (exists || omode != mode)
688 				if (fchmod(ofd, omode))
689 					run_err("%s: set mode: %s",
690 					    np, strerror(errno));
691 		} else {
692 			if (!exists && omode != mode)
693 				if (fchmod(ofd, omode & ~mask))
694 					run_err("%s: set mode: %s",
695 					    np, strerror(errno));
696 		}
697 #ifndef __SVR4
698 		if (setimes && wrerr == NO) {
699 			setimes = 0;
700 			if (futimes(ofd, tv) < 0) {
701 				run_err("%s: set times: %s",
702 				    np, strerror(errno));
703 				wrerr = DISPLAYED;
704 			}
705 		}
706 #endif
707 		(void)close(ofd);
708 #ifdef __SVR4
709 		if (setimes && wrerr == NO) {
710 			setimes = 0;
711 			if (utimes(np, tv) < 0) {
712 				run_err("%s: set times: %s",
713 				    np, strerror(errno));
714 				wrerr = DISPLAYED;
715 			}
716 		}
717 #endif
718 		(void)response();
719 		switch(wrerr) {
720 		case YES:
721 			run_err("%s: write: %s", np, strerror(wrerrno));
722 			break;
723 		case NO:
724 			(void)write(rem, "", 1);
725 			break;
726 		case DISPLAYED:
727 			break;
728 		}
729 	}
730 
731 out:
732 	if (namebuf) {
733 		free(namebuf);
734 	}
735 	return;
736 
737 screwup:
738 	run_err("protocol error: %s", why);
739 	exit(1);
740 	/* NOTREACHED */
741 }
742 
743 
744 int
745 response(void)
746 {
747 	char ch, *cp, resp, rbuf[BUFSIZ];
748 
749 	if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
750 		lostconn(0);
751 
752 	cp = rbuf;
753 	switch(resp) {
754 	case 0:				/* ok */
755 		return (0);
756 	default:
757 		*cp++ = resp;
758 		/* FALLTHROUGH */
759 	case 1:				/* error, followed by error msg */
760 	case 2:				/* fatal error, "" */
761 		do {
762 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
763 				lostconn(0);
764 			*cp++ = ch;
765 		} while (cp < &rbuf[BUFSIZ] && ch != '\n');
766 
767 		if (!iamremote)
768 			(void)write(STDERR_FILENO, rbuf, (size_t)(cp - rbuf));
769 		++errs;
770 		if (resp == 1)
771 			return (-1);
772 		exit(1);
773 	}
774 	/* NOTREACHED */
775 }
776 
777 void
778 usage(void)
779 {
780 	(void)fprintf(stderr,
781 	    "usage: rcp [-46p] f1 f2; or: rcp [-46pr] f1 ... fn directory\n");
782 	exit(1);
783 	/* NOTREACHED */
784 }
785 
786 #include <stdarg.h>
787 
788 
789 void
790 run_err(const char *fmt, ...)
791 {
792 	static FILE *fp;
793 	va_list ap;
794 
795 	++errs;
796 	if (fp == NULL && !(fp = fdopen(rem, "w")))
797 		return;
798 
799 	va_start(ap, fmt);
800 
801 	(void)fprintf(fp, "%c", 0x01);
802 	(void)fprintf(fp, "rcp: ");
803 	(void)vfprintf(fp, fmt, ap);
804 	(void)fprintf(fp, "\n");
805 	(void)fflush(fp);
806 	va_end(ap);
807 
808 	if (!iamremote) {
809 		va_start(ap, fmt);
810 		vwarnx(fmt, ap);
811 		va_end(ap);
812 	}
813 }
814