xref: /netbsd-src/bin/rcp/rcp.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: rcp.c,v 1.40 2005/06/26 19:10:49 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.40 2005/06/26 19:10:49 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 #ifdef KERBEROS
71 #include <des.h>
72 #include <kerberosIV/krb.h>
73 #include "krb.h"
74 
75 char	dst_realm_buf[REALM_SZ];
76 char	*dest_realm = NULL;
77 int	use_kerberos = 1;
78 CREDENTIALS 	cred;
79 Key_schedule	schedule;
80 #ifdef CRYPT
81 int	doencrypt = 0;
82 #define	OPTIONS	"46dfKk:prtx"
83 #else
84 #define	OPTIONS	"46dfKk:prt"
85 #endif
86 #else
87 #define	OPTIONS "46dfprt"
88 #endif
89 
90 struct passwd *pwd;
91 char *pwname;
92 u_short	port;
93 uid_t	userid;
94 int errs, rem;
95 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
96 int family = AF_UNSPEC;
97 static char dot[] = ".";
98 
99 #define	CMDNEEDS	64
100 char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
101 
102 #ifdef KERBEROS
103 int	 kerberos(char **, char *, char *, char *);
104 void	 oldw(const char *, ...);
105 #endif
106 int	 response(void);
107 void	 rsource(char *, struct stat *);
108 void	 sink(int, char *[]);
109 void	 source(int, char *[]);
110 void	 tolocal(int, char *[]);
111 void	 toremote(char *, int, char *[]);
112 void	 usage(void);
113 
114 int
115 main(int argc, char *argv[])
116 {
117 	struct servent *sp;
118 	int ch, fflag, tflag;
119 	char *targ;
120 	const char *shell;
121 
122 	fflag = tflag = 0;
123 	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
124 		switch(ch) {			/* User-visible flags. */
125 		case '4':
126 			family = AF_INET;
127 			break;
128 		case '6':
129 			family = AF_INET6;
130 			break;
131 		case 'K':
132 #ifdef KERBEROS
133 			use_kerberos = 0;
134 #endif
135 			break;
136 #ifdef	KERBEROS
137 		case 'k':
138 			dest_realm = dst_realm_buf;
139 			if (strlcpy(dst_realm_buf, optarg,
140 			    sizeof(dst_realm_buf)) >= sizeof(dst_realm_buf))
141 				errx(1, "Argument `realm' is too long");
142 			break;
143 #ifdef CRYPT
144 		case 'x':
145 			doencrypt = 1;
146 			/* des_set_key(cred.session, schedule); */
147 			break;
148 #endif
149 #endif
150 		case 'p':
151 			pflag = 1;
152 			break;
153 		case 'r':
154 			iamrecursive = 1;
155 			break;
156 						/* Server options. */
157 		case 'd':
158 			targetshouldbedirectory = 1;
159 			break;
160 		case 'f':			/* "from" */
161 			iamremote = 1;
162 			fflag = 1;
163 			break;
164 		case 't':			/* "to" */
165 			iamremote = 1;
166 			tflag = 1;
167 			break;
168 		case '?':
169 		default:
170 			usage();
171 		}
172 	argc -= optind;
173 	argv += optind;
174 
175 #ifdef KERBEROS
176 	if (use_kerberos) {
177 #ifdef CRYPT
178 		shell = doencrypt ? "ekshell" : "kshell";
179 #else
180 		shell = "kshell";
181 #endif
182 		if ((sp = getservbyname(shell, "tcp")) == NULL) {
183 			use_kerberos = 0;
184 			oldw("can't get entry for %s/tcp service", shell);
185 			sp = getservbyname(shell = "shell", "tcp");
186 		}
187 	} else
188 		sp = getservbyname(shell = "shell", "tcp");
189 #else
190 	sp = getservbyname(shell = "shell", "tcp");
191 #endif
192 	if (sp == NULL)
193 		errx(1, "%s/tcp: unknown service", shell);
194 	port = sp->s_port;
195 
196 	if ((pwd = getpwuid(userid = getuid())) == NULL)
197 		errx(1, "unknown user %d", (int)userid);
198 
199 	if ((pwname = strdup(pwd->pw_name)) == NULL)
200 		err(1, NULL);
201 
202 	rem = STDIN_FILENO;		/* XXX */
203 
204 	if (fflag) {			/* Follow "protocol", send data. */
205 		(void)response();
206 		source(argc, argv);
207 		exit(errs);
208 	}
209 
210 	if (tflag) {			/* Receive data. */
211 		sink(argc, argv);
212 		exit(errs);
213 	}
214 
215 	if (argc < 2)
216 		usage();
217 	if (argc > 2)
218 		targetshouldbedirectory = 1;
219 
220 	rem = -1;
221 	/* Command to be executed on remote system using "rsh". */
222 #ifdef	KERBEROS
223 	(void)snprintf(cmd, sizeof(cmd),
224 	    "rcp%s%s%s%s", iamrecursive ? " -r" : "",
225 #ifdef CRYPT
226 	    (doencrypt && use_kerberos ? " -x" : ""),
227 #else
228 	    "",
229 #endif
230 	    pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
231 #else
232 	(void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
233 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
234 	    targetshouldbedirectory ? " -d" : "");
235 #endif
236 
237 	(void)signal(SIGPIPE, lostconn);
238 
239 	if ((targ = colon(argv[argc - 1])) != NULL)/* Dest is remote host. */
240 		toremote(targ, argc, argv);
241 	else {
242 		tolocal(argc, argv);		/* Dest is local host. */
243 		if (targetshouldbedirectory)
244 			verifydir(argv[argc - 1]);
245 	}
246 	exit(errs);
247 	/* NOTREACHED */
248 }
249 
250 void
251 toremote(char *targ, int argc, char *argv[])
252 {
253 	int i, len;
254 	char *bp, *host, *src, *suser, *thost, *tuser;
255 
256 	*targ++ = 0;
257 	if (*targ == 0)
258 		targ = dot;
259 
260 	if ((thost = strchr(argv[argc - 1], '@')) != NULL) {
261 		/* user@host */
262 		*thost++ = 0;
263 		tuser = argv[argc - 1];
264 		if (*tuser == '\0')
265 			tuser = NULL;
266 		else if (!okname(tuser))
267 			exit(1);
268 	} else {
269 		thost = argv[argc - 1];
270 		tuser = NULL;
271 	}
272 	thost = unbracket(thost);
273 
274 	for (i = 0; i < argc - 1; i++) {
275 		src = colon(argv[i]);
276 		if (src) {			/* remote to remote */
277 			*src++ = 0;
278 			if (*src == 0)
279 				src = dot;
280 			host = strchr(argv[i], '@');
281 			len = strlen(_PATH_RSH) + strlen(argv[i]) +
282 			    strlen(src) + (tuser ? strlen(tuser) : 0) +
283 			    strlen(thost) + strlen(targ) + CMDNEEDS + 20;
284 			if (!(bp = malloc(len)))
285 				err(1, NULL);
286 			if (host) {
287 				*host++ = 0;
288 				host = unbracket(host);
289 				suser = argv[i];
290 				if (*suser == '\0')
291 					suser = pwname;
292 				else if (!okname(suser))
293 					continue;
294 				(void)snprintf(bp, len,
295 				    "%s %s -l %s -n %s %s '%s%s%s:%s'",
296 				    _PATH_RSH, host, suser, cmd, src,
297 				    tuser ? tuser : "", tuser ? "@" : "",
298 				    thost, targ);
299 			} else {
300 				host = unbracket(argv[i]);
301 				(void)snprintf(bp, len,
302 				    "exec %s %s -n %s %s '%s%s%s:%s'",
303 				    _PATH_RSH, argv[i], cmd, src,
304 				    tuser ? tuser : "", tuser ? "@" : "",
305 				    thost, targ);
306 			}
307 			(void)susystem(bp);
308 			(void)free(bp);
309 		} else {			/* local to remote */
310 			if (rem == -1) {
311 				len = strlen(targ) + CMDNEEDS + 20;
312 				if (!(bp = malloc(len)))
313 					err(1, NULL);
314 				(void)snprintf(bp, len, "%s -t %s", cmd, targ);
315 				host = thost;
316 #ifdef KERBEROS
317 				if (use_kerberos)
318 					rem = kerberos(&host, bp, pwname,
319 					    tuser ? tuser : pwname);
320 				else
321 #endif
322 					rem = rcmd_af(&host, port, pwname,
323 					    tuser ? tuser : pwname,
324 					    bp, NULL, family);
325 				if (rem < 0)
326 					exit(1);
327 				if (response() < 0)
328 					exit(1);
329 				(void)free(bp);
330 			}
331 			source(1, argv+i);
332 		}
333 	}
334 }
335 
336 void
337 tolocal(int argc, char *argv[])
338 {
339 	int i, len;
340 	char *bp, *host, *src, *suser;
341 
342 	for (i = 0; i < argc - 1; i++) {
343 		if (!(src = colon(argv[i]))) {		/* Local to local. */
344 			len = strlen(_PATH_CP) + strlen(argv[i]) +
345 			    strlen(argv[argc - 1]) + 20;
346 			if (!(bp = malloc(len)))
347 				err(1, NULL);
348 			(void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
349 			    iamrecursive ? " -r" : "", pflag ? " -p" : "",
350 			    argv[i], argv[argc - 1]);
351 			if (susystem(bp))
352 				++errs;
353 			(void)free(bp);
354 			continue;
355 		}
356 		*src++ = 0;
357 		if (*src == 0)
358 			src = dot;
359 		if ((host = strchr(argv[i], '@')) == NULL) {
360 			host = argv[i];
361 			suser = pwname;
362 		} else {
363 			*host++ = 0;
364 			suser = argv[i];
365 			if (*suser == '\0')
366 				suser = pwname;
367 			else if (!okname(suser))
368 				continue;
369 		}
370 		host = unbracket(host);
371 		len = strlen(src) + CMDNEEDS + 20;
372 		if ((bp = malloc(len)) == NULL)
373 			err(1, NULL);
374 		(void)snprintf(bp, len, "%s -f %s", cmd, src);
375 		rem =
376 #ifdef KERBEROS
377 		    use_kerberos ?
378 			kerberos(&host, bp, pwname, suser) :
379 #endif
380 			rcmd_af(&host, port, pwname, suser, bp, NULL, family);
381 		(void)free(bp);
382 		if (rem < 0) {
383 			++errs;
384 			continue;
385 		}
386 		sink(1, argv + argc - 1);
387 		(void)close(rem);
388 		rem = -1;
389 	}
390 }
391 
392 void
393 source(int argc, char *argv[])
394 {
395 	struct stat stb;
396 	static BUF buffer;
397 	BUF *bp;
398 	off_t i;
399 	int amt, fd, haderr, indx, result;
400 	char *last, *name, buf[BUFSIZ];
401 
402 #ifdef __GNUC__
403 	/* This outrageous construct just to shut up a GCC warning. */
404 	(void) &i;
405 #endif
406 
407 	for (indx = 0; indx < argc; ++indx) {
408 		name = argv[indx];
409 		if ((fd = open(name, O_RDONLY, 0)) < 0)
410 			goto syserr;
411 		if (fstat(fd, &stb)) {
412 syserr:			run_err("%s: %s", name, strerror(errno));
413 			goto next;
414 		}
415 		switch (stb.st_mode & S_IFMT) {
416 		case S_IFREG:
417 			break;
418 		case S_IFDIR:
419 			if (iamrecursive) {
420 				rsource(name, &stb);
421 				goto next;
422 			}
423 			/* FALLTHROUGH */
424 		default:
425 			run_err("%s: not a regular file", name);
426 			goto next;
427 		}
428 		if ((last = strrchr(name, '/')) == NULL)
429 			last = name;
430 		else
431 			++last;
432 		if (pflag) {
433 			/*
434 			 * Make it compatible with possible future
435 			 * versions expecting microseconds.
436 			 */
437 			(void)snprintf(buf, sizeof(buf), "T%ld %ld %ld %ld\n",
438 			    (long)stb.st_mtimespec.tv_sec,
439 			    (long)stb.st_mtimespec.tv_nsec / 1000,
440 			    (long)stb.st_atimespec.tv_sec,
441 			    (long)stb.st_atimespec.tv_nsec / 1000);
442 			(void)write(rem, buf, strlen(buf));
443 			if (response() < 0)
444 				goto next;
445 		}
446 #define	RCPMODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
447 		(void)snprintf(buf, sizeof(buf), "C%04o %lld %s\n",
448 		    stb.st_mode & RCPMODEMASK, (long long)stb.st_size, last);
449 		(void)write(rem, buf, strlen(buf));
450 		if (response() < 0)
451 			goto next;
452 		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
453 next:			(void)close(fd);
454 			continue;
455 		}
456 
457 		/* Keep writing after an error so that we stay sync'd up. */
458 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
459 			amt = bp->cnt;
460 			if (i + amt > stb.st_size)
461 				amt = stb.st_size - i;
462 			if (!haderr) {
463 				result = read(fd, bp->buf, amt);
464 				if (result != amt)
465 					haderr = result >= 0 ? EIO : errno;
466 			}
467 			if (haderr)
468 				(void)write(rem, bp->buf, amt);
469 			else {
470 				result = write(rem, bp->buf, amt);
471 				if (result != amt)
472 					haderr = result >= 0 ? EIO : errno;
473 			}
474 		}
475 		if (close(fd) && !haderr)
476 			haderr = errno;
477 		if (!haderr)
478 			(void)write(rem, "", 1);
479 		else
480 			run_err("%s: %s", name, strerror(haderr));
481 		(void)response();
482 	}
483 }
484 
485 void
486 rsource(char *name, struct stat *statp)
487 {
488 	DIR *dirp;
489 	struct dirent *dp;
490 	char *last, *vect[1], path[MAXPATHLEN];
491 
492 	if (!(dirp = opendir(name))) {
493 		run_err("%s: %s", name, strerror(errno));
494 		return;
495 	}
496 	last = strrchr(name, '/');
497 	if (last == 0)
498 		last = name;
499 	else
500 		last++;
501 	if (pflag) {
502 		(void)snprintf(path, sizeof(path), "T%ld %ld %ld %ld\n",
503 		    (long)statp->st_mtimespec.tv_sec,
504 		    (long)statp->st_mtimespec.tv_nsec / 1000,
505 		    (long)statp->st_atimespec.tv_sec,
506 		    (long)statp->st_atimespec.tv_nsec / 1000);
507 		(void)write(rem, path, strlen(path));
508 		if (response() < 0) {
509 			closedir(dirp);
510 			return;
511 		}
512 	}
513 	(void)snprintf(path, sizeof(path),
514 	    "D%04o %d %s\n", statp->st_mode & RCPMODEMASK, 0, last);
515 	(void)write(rem, path, strlen(path));
516 	if (response() < 0) {
517 		closedir(dirp);
518 		return;
519 	}
520 	while ((dp = readdir(dirp)) != NULL) {
521 		if (dp->d_ino == 0)
522 			continue;
523 		if (!strcmp(dp->d_name, dot) || !strcmp(dp->d_name, ".."))
524 			continue;
525 		if (strlen(name) + 1 + strlen(dp->d_name) >= MAXPATHLEN - 1) {
526 			run_err("%s/%s: name too long", name, dp->d_name);
527 			continue;
528 		}
529 		(void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
530 		vect[0] = path;
531 		source(1, vect);
532 	}
533 	(void)closedir(dirp);
534 	(void)write(rem, "E\n", 2);
535 	(void)response();
536 }
537 
538 void
539 sink(int argc, char *argv[])
540 {
541 	static BUF buffer;
542 	struct stat stb;
543 	struct timeval tv[2];
544 	enum { YES, NO, DISPLAYED } wrerr;
545 	BUF *bp;
546 	off_t i, j;
547 	int amt, count, exists, first, mask, mode, ofd, omode;
548 	int setimes, targisdir;
549 	int wrerrno = 0;	/* pacify gcc */
550 	char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ];
551 	const char *why;
552 	off_t size;
553 
554 #define	atime	tv[0]
555 #define	mtime	tv[1]
556 #define	SCREWUP(str)	{ why = str; goto screwup; }
557 
558 #ifdef __GNUC__
559 	/* This outrageous construct just to shut up a GCC warning. */
560 	(void) &i;
561 #endif
562 
563 	setimes = targisdir = 0;
564 	mask = umask(0);
565 	if (!pflag)
566 		(void)umask(mask);
567 	if (argc != 1) {
568 		run_err("ambiguous target");
569 		exit(1);
570 	}
571 	targ = *argv;
572 	if (targetshouldbedirectory)
573 		verifydir(targ);
574 	(void)write(rem, "", 1);
575 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
576 		targisdir = 1;
577 	for (first = 1;; first = 0) {
578 		cp = buf;
579 		if (read(rem, cp, 1) <= 0)
580 			return;
581 		if (*cp++ == '\n')
582 			SCREWUP("unexpected <newline>");
583 		do {
584 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
585 				SCREWUP("lost connection");
586 			*cp++ = ch;
587 		} while (cp < &buf[BUFSIZ - 1] && ch != '\n');
588 		*cp = 0;
589 
590 		if (buf[0] == '\01' || buf[0] == '\02') {
591 			if (iamremote == 0)
592 				(void)write(STDERR_FILENO,
593 				    buf + 1, strlen(buf + 1));
594 			if (buf[0] == '\02')
595 				exit(1);
596 			++errs;
597 			continue;
598 		}
599 		if (buf[0] == 'E') {
600 			(void)write(rem, "", 1);
601 			return;
602 		}
603 
604 		if (ch == '\n')
605 			*--cp = 0;
606 
607 #define getnum(t) (t) = 0; while (isdigit((unsigned char)*cp)) (t) = (t) * 10 + (*cp++ - '0');
608 		cp = buf;
609 		if (*cp == 'T') {
610 			setimes++;
611 			cp++;
612 			getnum(mtime.tv_sec);
613 			if (*cp++ != ' ')
614 				SCREWUP("mtime.sec not delimited");
615 			getnum(mtime.tv_usec);
616 			if (*cp++ != ' ')
617 				SCREWUP("mtime.usec not delimited");
618 			getnum(atime.tv_sec);
619 			if (*cp++ != ' ')
620 				SCREWUP("atime.sec not delimited");
621 			getnum(atime.tv_usec);
622 			if (*cp++ != '\0')
623 				SCREWUP("atime.usec not delimited");
624 			(void)write(rem, "", 1);
625 			continue;
626 		}
627 		if (*cp != 'C' && *cp != 'D') {
628 			/*
629 			 * Check for the case "rcp remote:foo\* local:bar".
630 			 * In this case, the line "No match." can be returned
631 			 * by the shell before the rcp command on the remote is
632 			 * executed so the ^Aerror_message convention isn't
633 			 * followed.
634 			 */
635 			if (first) {
636 				run_err("%s", cp);
637 				exit(1);
638 			}
639 			SCREWUP("expected control record");
640 		}
641 		mode = 0;
642 		for (++cp; cp < buf + 5; cp++) {
643 			if (*cp < '0' || *cp > '7')
644 				SCREWUP("bad mode");
645 			mode = (mode << 3) | (*cp - '0');
646 		}
647 		if (*cp++ != ' ')
648 			SCREWUP("mode not delimited");
649 
650 		for (size = 0; isdigit((unsigned char)*cp);)
651 			size = size * 10 + (*cp++ - '0');
652 		if (*cp++ != ' ')
653 			SCREWUP("size not delimited");
654 		if (targisdir) {
655 			static char *namebuf;
656 			static int cursize;
657 			size_t need;
658 
659 			need = strlen(targ) + strlen(cp) + 250;
660 			if (need > cursize) {
661 				if (!(namebuf = malloc(need)))
662 					run_err("%s", strerror(errno));
663 			}
664 			(void)snprintf(namebuf, need, "%s%s%s", targ,
665 			    *targ ? "/" : "", cp);
666 			np = namebuf;
667 		} else
668 			np = targ;
669 		exists = stat(np, &stb) == 0;
670 		if (buf[0] == 'D') {
671 			int mod_flag = pflag;
672 			if (exists) {
673 				if (!S_ISDIR(stb.st_mode)) {
674 					errno = ENOTDIR;
675 					goto bad;
676 				}
677 				if (pflag)
678 					(void)chmod(np, mode);
679 			} else {
680 				/* Handle copying from a read-only directory */
681 				mod_flag = 1;
682 				if (mkdir(np, mode | S_IRWXU) < 0)
683 					goto bad;
684 			}
685 			vect[0] = np;
686 			sink(1, vect);
687 			if (setimes) {
688 				setimes = 0;
689 				if (utimes(np, tv) < 0)
690 				    run_err("%s: set times: %s",
691 					np, strerror(errno));
692 			}
693 			if (mod_flag)
694 				(void)chmod(np, mode);
695 			continue;
696 		}
697 		omode = mode;
698 		mode |= S_IWRITE;
699 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
700 bad:			run_err("%s: %s", np, strerror(errno));
701 			continue;
702 		}
703 		(void)write(rem, "", 1);
704 		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
705 			(void)close(ofd);
706 			continue;
707 		}
708 		cp = bp->buf;
709 		wrerr = NO;
710 		for (count = i = 0; i < size; i += BUFSIZ) {
711 			amt = BUFSIZ;
712 			if (i + amt > size)
713 				amt = size - i;
714 			count += amt;
715 			do {
716 				j = read(rem, cp, amt);
717 				if (j <= 0) {
718 					run_err("%s", j ? strerror(errno) :
719 					    "dropped connection");
720 					exit(1);
721 				}
722 				amt -= j;
723 				cp += j;
724 			} while (amt > 0);
725 			if (count == bp->cnt) {
726 				/* Keep reading so we stay sync'd up. */
727 				if (wrerr == NO) {
728 					j = write(ofd, bp->buf, count);
729 					if (j != count) {
730 						wrerr = YES;
731 						wrerrno = j >= 0 ? EIO : errno;
732 					}
733 				}
734 				count = 0;
735 				cp = bp->buf;
736 			}
737 		}
738 		if (count != 0 && wrerr == NO &&
739 		    (j = write(ofd, bp->buf, count)) != count) {
740 			wrerr = YES;
741 			wrerrno = j >= 0 ? EIO : errno;
742 		}
743 		if (ftruncate(ofd, size)) {
744 			run_err("%s: truncate: %s", np, strerror(errno));
745 			wrerr = DISPLAYED;
746 		}
747 		if (pflag) {
748 			if (exists || omode != mode)
749 				if (fchmod(ofd, omode))
750 					run_err("%s: set mode: %s",
751 					    np, strerror(errno));
752 		} else {
753 			if (!exists && omode != mode)
754 				if (fchmod(ofd, omode & ~mask))
755 					run_err("%s: set mode: %s",
756 					    np, strerror(errno));
757 		}
758 #ifndef __SVR4
759 		if (setimes && wrerr == NO) {
760 			setimes = 0;
761 			if (futimes(ofd, tv) < 0) {
762 				run_err("%s: set times: %s",
763 				    np, strerror(errno));
764 				wrerr = DISPLAYED;
765 			}
766 		}
767 #endif
768 		(void)close(ofd);
769 #ifdef __SVR4
770 		if (setimes && wrerr == NO) {
771 			setimes = 0;
772 			if (utimes(np, tv) < 0) {
773 				run_err("%s: set times: %s",
774 				    np, strerror(errno));
775 				wrerr = DISPLAYED;
776 			}
777 		}
778 #endif
779 		(void)response();
780 		switch(wrerr) {
781 		case YES:
782 			run_err("%s: write: %s", np, strerror(wrerrno));
783 			break;
784 		case NO:
785 			(void)write(rem, "", 1);
786 			break;
787 		case DISPLAYED:
788 			break;
789 		}
790 	}
791 screwup:
792 	run_err("protocol error: %s", why);
793 	exit(1);
794 	/* NOTREACHED */
795 }
796 
797 #ifdef KERBEROS
798 int
799 kerberos(char **host, char *bp, char *locuser, char *user)
800 {
801 	struct servent *sp;
802 
803 again:
804 	if (use_kerberos) {
805 		rem = KSUCCESS;
806 		errno = 0;
807 		if (dest_realm == NULL)
808 			dest_realm = krb_realmofhost(*host);
809 		rem =
810 #ifdef CRYPT
811 		    doencrypt ?
812 			krcmd_mutual(host,
813 			    port, user, bp, 0, dest_realm, &cred, schedule) :
814 #endif
815 			krcmd(host, port, user, bp, 0, dest_realm);
816 
817 		if (rem < 0) {
818 			use_kerberos = 0;
819 			if ((sp = getservbyname("shell", "tcp")) == NULL)
820 				errx(1, "unknown service shell/tcp");
821 			if (errno == ECONNREFUSED)
822 			    oldw("remote host doesn't support Kerberos");
823 			else if (errno == ENOENT)
824 			    oldw("can't provide Kerberos authentication data");
825 			port = sp->s_port;
826 			goto again;
827 		}
828 	} else {
829 #ifdef CRYPT
830 		if (doencrypt)
831 			errx(1,
832 			   "the -x option requires Kerberos authentication");
833 #endif
834 		rem = rcmd_af(host, port, locuser, user, bp, NULL, family);
835 	}
836 	return (rem);
837 }
838 #endif /* KERBEROS */
839 
840 int
841 response(void)
842 {
843 	char ch, *cp, resp, rbuf[BUFSIZ];
844 
845 	if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
846 		lostconn(0);
847 
848 	cp = rbuf;
849 	switch(resp) {
850 	case 0:				/* ok */
851 		return (0);
852 	default:
853 		*cp++ = resp;
854 		/* FALLTHROUGH */
855 	case 1:				/* error, followed by error msg */
856 	case 2:				/* fatal error, "" */
857 		do {
858 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
859 				lostconn(0);
860 			*cp++ = ch;
861 		} while (cp < &rbuf[BUFSIZ] && ch != '\n');
862 
863 		if (!iamremote)
864 			(void)write(STDERR_FILENO, rbuf, cp - rbuf);
865 		++errs;
866 		if (resp == 1)
867 			return (-1);
868 		exit(1);
869 	}
870 	/* NOTREACHED */
871 }
872 
873 void
874 usage(void)
875 {
876 #ifdef KERBEROS
877 #ifdef CRYPT
878 	(void)fprintf(stderr, "%s\n\t%s\n",
879 	    "usage: rcp [-46Kpx] [-k realm] f1 f2",
880 	    "or: rcp [-46Kprx] [-k realm] f1 ... fn directory");
881 #else
882 	(void)fprintf(stderr, "%s\n\t%s\n",
883 	    "usage: rcp [-46Kp] [-k realm] f1 f2",
884 	    "or: rcp [-46Kpr] [-k realm] f1 ... fn directory");
885 #endif
886 #else
887 	(void)fprintf(stderr,
888 	    "usage: rcp [-46p] f1 f2; or: rcp [-46pr] f1 ... fn directory\n");
889 #endif
890 	exit(1);
891 	/* NOTREACHED */
892 }
893 
894 #include <stdarg.h>
895 
896 #ifdef KERBEROS
897 void
898 oldw(const char *fmt, ...)
899 {
900 	va_list ap;
901 
902 	va_start(ap, fmt);
903 	(void)fprintf(stderr, "rcp: ");
904 	(void)vfprintf(stderr, fmt, ap);
905 	(void)fprintf(stderr, ", using standard rcp\n");
906 	va_end(ap);
907 }
908 #endif
909 
910 void
911 run_err(const char *fmt, ...)
912 {
913 	static FILE *fp;
914 	va_list ap;
915 
916 	++errs;
917 	if (fp == NULL && !(fp = fdopen(rem, "w")))
918 		return;
919 
920 	va_start(ap, fmt);
921 
922 	(void)fprintf(fp, "%c", 0x01);
923 	(void)fprintf(fp, "rcp: ");
924 	(void)vfprintf(fp, fmt, ap);
925 	(void)fprintf(fp, "\n");
926 	(void)fflush(fp);
927 	va_end(ap);
928 
929 	if (!iamremote) {
930 		va_start(ap, fmt);
931 		vwarnx(fmt, ap);
932 		va_end(ap);
933 	}
934 }
935