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