rcp.c revision 96196
1/*
2 * Copyright (c) 1983, 1990, 1992, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * Copyright (c) 2002 Networks Associates Technology, Inc.
5 * All rights reserved.
6 *
7 * Portions of this software were developed for the FreeBSD Project by
8 * ThinkSec AS and NAI Labs, the Security Research Division of Network
9 * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
10 * ("CBOSS"), as part of the DARPA CHATS research program.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 *    must display the following acknowledgement:
22 *	This product includes software developed by the University of
23 *	California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 *    may be used to endorse or promote products derived from this software
26 *    without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 */
40
41#ifndef lint
42static char const copyright[] =
43"@(#) Copyright (c) 1983, 1990, 1992, 1993\n\
44	The Regents of the University of California.  All rights reserved.\n";
45#endif /* not lint */
46
47#ifndef lint
48#if 0
49static char sccsid[] = "@(#)rcp.c	8.2 (Berkeley) 4/2/94";
50#endif
51static const char rcsid[] =
52  "$FreeBSD: head/bin/rcp/rcp.c 96196 2002-05-08 00:47:01Z des $";
53#endif /* not lint */
54
55#include <sys/param.h>
56#include <sys/stat.h>
57#include <sys/time.h>
58#include <sys/socket.h>
59#include <netinet/in.h>
60#include <netinet/in_systm.h>
61#include <netinet/ip.h>
62
63#include <ctype.h>
64#include <dirent.h>
65#include <err.h>
66#include <errno.h>
67#include <fcntl.h>
68#include <libutil.h>
69#include <limits.h>
70#include <netdb.h>
71#include <paths.h>
72#include <pwd.h>
73#include <signal.h>
74#include <stdio.h>
75#include <stdlib.h>
76#include <string.h>
77#include <string.h>
78#include <unistd.h>
79
80#include "extern.h"
81
82#ifdef KERBEROS
83#include <openssl/des.h>
84#include <krb.h>
85#include "bsd_locl.h"
86
87char	dst_realm_buf[REALM_SZ];
88char	*dest_realm = NULL;
89int	use_kerberos = 1;
90CREDENTIALS	cred;
91Key_schedule	schedule;
92extern	char	*krb_realmofhost();
93#ifdef CRYPT
94int	doencrypt = 0;
95#define	OPTIONS	"dfKk:prtx"
96#else
97#define	OPTIONS	"dfKk:prt"
98#endif
99#else
100#define	OPTIONS "dfprt"
101#endif
102
103struct passwd *pwd;
104u_short	port;
105uid_t	userid;
106int errs, rem;
107int pflag, iamremote, iamrecursive, targetshouldbedirectory;
108
109static int argc_copy;
110static char **argv_copy;
111
112#define	CMDNEEDS	64
113char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
114
115#ifdef KERBEROS
116int	 kerberos(char **, char *, char *, char *);
117void	 oldw(const char *, ...) __printflike(1, 2);
118#endif
119int	 response(void);
120void	 rsource(char *, struct stat *);
121void	 run_err(const char *, ...) __printflike(1, 2);
122void	 sink(int, char *[]);
123void	 source(int, char *[]);
124void	 tolocal(int, char *[]);
125void	 toremote(char *, int, char *[]);
126void	 usage(void);
127
128int
129main(int argc, char *argv[])
130{
131	struct servent *sp;
132	int ch, fflag, i, tflag;
133	char *targ, *shell;
134#ifdef KERBEROS
135	char *k;
136#endif
137
138	/*
139	 * Prepare for execing ourselves.
140	 */
141	argc_copy = argc + 1;
142	argv_copy = malloc((argc_copy + 1) * sizeof(*argv_copy));
143	if (argv_copy == NULL)
144		err(1, "malloc");
145	argv_copy[0] = argv[0];
146	argv_copy[1] = "-K";
147	for (i = 1; i < argc; ++i) {
148		argv_copy[i + 1] = strdup(argv[i]);
149		if (argv_copy[i + 1] == NULL)
150			errx(1, "strdup: out of memory");
151	}
152	argv_copy[argc + 1] = NULL;
153
154	fflag = tflag = 0;
155	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
156		switch(ch) {			/* User-visible flags. */
157		case 'K':
158#ifdef KERBEROS
159			use_kerberos = 0;
160#endif
161			break;
162#ifdef	KERBEROS
163		case 'k':
164			dest_realm = dst_realm_buf;
165			(void)strncpy(dst_realm_buf, optarg, REALM_SZ - 1);
166			dst_realm_buf[REALM_SZ - 1] = '\0';
167			break;
168#ifdef CRYPT
169		case 'x':
170			doencrypt = 1;
171			/* des_set_key(cred.session, schedule); */
172			break;
173#endif
174#endif
175		case 'p':
176			pflag = 1;
177			break;
178		case 'r':
179			iamrecursive = 1;
180			break;
181						/* Server options. */
182		case 'd':
183			targetshouldbedirectory = 1;
184			break;
185		case 'f':			/* "from" */
186			iamremote = 1;
187			fflag = 1;
188			break;
189		case 't':			/* "to" */
190			iamremote = 1;
191			tflag = 1;
192			break;
193		case '?':
194		default:
195			usage();
196		}
197	argc -= optind;
198	argv += optind;
199
200#ifdef KERBEROS
201	k = auth_getval("auth_list");
202	if (k && !strstr(k, "kerberos"))
203	    use_kerberos = 0;
204	if (use_kerberos) {
205#ifdef CRYPT
206		shell = doencrypt ? "ekshell" : "kshell";
207#else
208		shell = "kshell";
209#endif
210		if ((sp = getservbyname(shell, "tcp")) == NULL) {
211			use_kerberos = 0;
212			oldw("can't get entry for %s/tcp service", shell);
213			sp = getservbyname(shell = "shell", "tcp");
214		}
215	} else
216		sp = getservbyname(shell = "shell", "tcp");
217#else
218	sp = getservbyname(shell = "shell", "tcp");
219#endif
220	if (sp == NULL)
221		errx(1, "%s/tcp: unknown service", shell);
222	port = sp->s_port;
223
224	if ((pwd = getpwuid(userid = getuid())) == NULL)
225		errx(1, "unknown user %d", (int)userid);
226
227	rem = STDIN_FILENO;		/* XXX */
228
229	if (fflag) {			/* Follow "protocol", send data. */
230		(void)response();
231		(void)setuid(userid);
232		source(argc, argv);
233		exit(errs);
234	}
235
236	if (tflag) {			/* Receive data. */
237		(void)setuid(userid);
238		sink(argc, argv);
239		exit(errs);
240	}
241
242	if (argc < 2)
243		usage();
244	if (argc > 2)
245		targetshouldbedirectory = 1;
246
247	rem = -1;
248	/* Command to be executed on remote system using "rsh". */
249#ifdef	KERBEROS
250	(void)snprintf(cmd, sizeof(cmd),
251	    "rcp%s%s%s%s", iamrecursive ? " -r" : "",
252#ifdef CRYPT
253	    (doencrypt && use_kerberos ? " -x" : ""),
254#else
255	    "",
256#endif
257	    pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
258#else
259	(void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
260	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
261	    targetshouldbedirectory ? " -d" : "");
262#endif
263
264	(void)signal(SIGPIPE, lostconn);
265
266	if ((targ = colon(argv[argc - 1])))	/* Dest is remote host. */
267		toremote(targ, argc, argv);
268	else {
269		tolocal(argc, argv);		/* Dest is local host. */
270		if (targetshouldbedirectory)
271			verifydir(argv[argc - 1]);
272	}
273	exit(errs);
274}
275
276void
277toremote(char *targ, int argc, char *argv[])
278{
279	int i, len, tos;
280	char *bp, *host, *src, *suser, *thost, *tuser;
281
282	*targ++ = 0;
283	if (*targ == 0)
284		targ = ".";
285
286	if ((thost = strchr(argv[argc - 1], '@'))) {
287		/* user@host */
288		*thost++ = 0;
289		tuser = argv[argc - 1];
290		if (*tuser == '\0')
291			tuser = NULL;
292		else if (!okname(tuser))
293			exit(1);
294	} else {
295		thost = argv[argc - 1];
296		tuser = NULL;
297	}
298
299	for (i = 0; i < argc - 1; i++) {
300		src = colon(argv[i]);
301		if (src) {			/* remote to remote */
302			*src++ = 0;
303			if (*src == 0)
304				src = ".";
305			host = strchr(argv[i], '@');
306			len = strlen(_PATH_RSH) + strlen(argv[i]) +
307			    strlen(src) + (tuser ? strlen(tuser) : 0) +
308			    strlen(thost) + strlen(targ) + CMDNEEDS + 20;
309			if (!(bp = malloc(len)))
310				err(1, NULL);
311			if (host) {
312				*host++ = 0;
313				suser = argv[i];
314				if (*suser == '\0')
315					suser = pwd->pw_name;
316				else if (!okname(suser)) {
317					++errs;
318					continue;
319				}
320				(void)snprintf(bp, len,
321				    "%s %s -l %s -n %s %s '%s%s%s:%s'",
322				    _PATH_RSH, host, suser, cmd, src,
323				    tuser ? tuser : "", tuser ? "@" : "",
324				    thost, targ);
325			} else
326				(void)snprintf(bp, len,
327				    "exec %s %s -n %s %s '%s%s%s:%s'",
328				    _PATH_RSH, argv[i], cmd, src,
329				    tuser ? tuser : "", tuser ? "@" : "",
330				    thost, targ);
331			(void)susystem(bp, userid);
332			(void)free(bp);
333		} else {			/* local to remote */
334			if (rem == -1) {
335				len = strlen(targ) + CMDNEEDS + 20;
336				if (!(bp = malloc(len)))
337					err(1, NULL);
338				(void)snprintf(bp, len, "%s -t %s", cmd, targ);
339				host = thost;
340#ifdef KERBEROS
341				if (use_kerberos)
342					rem = kerberos(&host, bp,
343					    pwd->pw_name,
344					    tuser ? tuser : pwd->pw_name);
345				else
346#endif
347					rem = rcmd(&host, port, pwd->pw_name,
348					    tuser ? tuser : pwd->pw_name,
349					    bp, 0);
350				if (rem < 0)
351					exit(1);
352				tos = IPTOS_THROUGHPUT;
353				if (setsockopt(rem, IPPROTO_IP, IP_TOS,
354				    &tos, sizeof(int)) < 0)
355					warn("TOS (ignored)");
356				if (response() < 0)
357					exit(1);
358				(void)free(bp);
359				(void)setuid(userid);
360			}
361			source(1, argv+i);
362		}
363	}
364}
365
366void
367tolocal(int argc, char *argv[])
368{
369	int i, len, tos;
370	char *bp, *host, *src, *suser;
371
372	for (i = 0; i < argc - 1; i++) {
373		if (!(src = colon(argv[i]))) {		/* Local to local. */
374			len = strlen(_PATH_CP) + strlen(argv[i]) +
375			    strlen(argv[argc - 1]) + 20;
376			if (!(bp = malloc(len)))
377				err(1, NULL);
378			(void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
379			    iamrecursive ? " -PR" : "", pflag ? " -p" : "",
380			    argv[i], argv[argc - 1]);
381			if (susystem(bp, userid))
382				++errs;
383			(void)free(bp);
384			continue;
385		}
386		*src++ = 0;
387		if (*src == 0)
388			src = ".";
389		if ((host = strchr(argv[i], '@')) == NULL) {
390			host = argv[i];
391			suser = pwd->pw_name;
392		} else {
393			*host++ = 0;
394			suser = argv[i];
395			if (*suser == '\0')
396				suser = pwd->pw_name;
397			else if (!okname(suser)) {
398				++errs;
399				continue;
400			}
401		}
402		len = strlen(src) + CMDNEEDS + 20;
403		if ((bp = malloc(len)) == NULL)
404			err(1, NULL);
405		(void)snprintf(bp, len, "%s -f %s", cmd, src);
406		rem =
407#ifdef KERBEROS
408		    use_kerberos ?
409			kerberos(&host, bp, pwd->pw_name, suser) :
410#endif
411			rcmd(&host, port, pwd->pw_name, suser, bp, 0);
412		(void)free(bp);
413		if (rem < 0) {
414			++errs;
415			continue;
416		}
417		(void)seteuid(userid);
418		tos = IPTOS_THROUGHPUT;
419		if (setsockopt(rem, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0)
420			warn("TOS (ignored)");
421		sink(1, argv + argc - 1);
422		(void)seteuid(0);
423		(void)close(rem);
424		rem = -1;
425	}
426}
427
428void
429source(int argc, char *argv[])
430{
431	struct stat stb;
432	static BUF buffer;
433	BUF *bp;
434	off_t i;
435	int amt, fd, haderr, indx, result;
436	char *last, *name, buf[BUFSIZ];
437
438	for (indx = 0; indx < argc; ++indx) {
439		name = argv[indx];
440		if ((fd = open(name, O_RDONLY, 0)) < 0)
441			goto syserr;
442		if (fstat(fd, &stb)) {
443syserr:			run_err("%s: %s", name, strerror(errno));
444			goto next;
445		}
446		switch (stb.st_mode & S_IFMT) {
447		case S_IFREG:
448			break;
449		case S_IFDIR:
450			if (iamrecursive) {
451				rsource(name, &stb);
452				goto next;
453			}
454			/* FALLTHROUGH */
455		default:
456			run_err("%s: not a regular file", name);
457			goto next;
458		}
459		if ((last = strrchr(name, '/')) == NULL)
460			last = name;
461		else
462			++last;
463		if (pflag) {
464			/*
465			 * Make it compatible with possible future
466			 * versions expecting microseconds.
467			 */
468			(void)snprintf(buf, sizeof(buf), "T%ld 0 %ld 0\n",
469			    (long)stb.st_mtimespec.tv_sec,
470			    (long)stb.st_atimespec.tv_sec);
471			(void)write(rem, buf, strlen(buf));
472			if (response() < 0)
473				goto next;
474		}
475#define	MODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
476		(void)snprintf(buf, sizeof(buf), "C%04o %qd %s\n",
477		    stb.st_mode & MODEMASK, stb.st_size, last);
478		(void)write(rem, buf, strlen(buf));
479		if (response() < 0)
480			goto next;
481		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
482next:			(void)close(fd);
483			continue;
484		}
485
486		/* Keep writing after an error so that we stay sync'd up. */
487		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
488			amt = bp->cnt;
489			if (i + amt > stb.st_size)
490				amt = stb.st_size - i;
491			if (!haderr) {
492				result = read(fd, bp->buf, amt);
493				if (result != amt)
494					haderr = result >= 0 ? EIO : errno;
495			}
496			if (haderr)
497				(void)write(rem, bp->buf, amt);
498			else {
499				result = write(rem, bp->buf, amt);
500				if (result != amt)
501					haderr = result >= 0 ? EIO : errno;
502			}
503		}
504		if (close(fd) && !haderr)
505			haderr = errno;
506		if (!haderr)
507			(void)write(rem, "", 1);
508		else
509			run_err("%s: %s", name, strerror(haderr));
510		(void)response();
511	}
512}
513
514void
515rsource(char *name, struct stat *statp)
516{
517	DIR *dirp;
518	struct dirent *dp;
519	char *last, *vect[1], path[PATH_MAX];
520
521	if (!(dirp = opendir(name))) {
522		run_err("%s: %s", name, strerror(errno));
523		return;
524	}
525	last = strrchr(name, '/');
526	if (last == 0)
527		last = name;
528	else
529		last++;
530	if (pflag) {
531		(void)snprintf(path, sizeof(path), "T%ld 0 %ld 0\n",
532		    (long)statp->st_mtimespec.tv_sec,
533		    (long)statp->st_atimespec.tv_sec);
534		(void)write(rem, path, strlen(path));
535		if (response() < 0) {
536			closedir(dirp);
537			return;
538		}
539	}
540	(void)snprintf(path, sizeof(path),
541	    "D%04o %d %s\n", statp->st_mode & MODEMASK, 0, last);
542	(void)write(rem, path, strlen(path));
543	if (response() < 0) {
544		closedir(dirp);
545		return;
546	}
547	while ((dp = readdir(dirp))) {
548		if (dp->d_ino == 0)
549			continue;
550		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
551			continue;
552		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path)) {
553			run_err("%s/%s: name too long", name, dp->d_name);
554			continue;
555		}
556		(void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
557		vect[0] = path;
558		source(1, vect);
559	}
560	(void)closedir(dirp);
561	(void)write(rem, "E\n", 2);
562	(void)response();
563}
564
565void
566sink(int argc, char *argv[])
567{
568	static BUF buffer;
569	struct stat stb;
570	struct timeval tv[2];
571	enum { YES, NO, DISPLAYED } wrerr;
572	BUF *bp;
573	off_t i, j, size;
574	int amt, count, exists, first, mask, mode, ofd, omode;
575	int setimes, targisdir, wrerrno = 0;
576	char ch, *cp, *np, *targ, *why, *vect[1], buf[BUFSIZ];
577
578#define	atime	tv[0]
579#define	mtime	tv[1]
580#define	SCREWUP(str)	{ why = str; goto screwup; }
581
582	setimes = targisdir = 0;
583	mask = umask(0);
584	if (!pflag)
585		(void)umask(mask);
586	if (argc != 1) {
587		run_err("ambiguous target");
588		exit(1);
589	}
590	targ = *argv;
591	if (targetshouldbedirectory)
592		verifydir(targ);
593	(void)write(rem, "", 1);
594	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
595		targisdir = 1;
596	for (first = 1;; first = 0) {
597		cp = buf;
598		if (read(rem, cp, 1) <= 0)
599			return;
600		if (*cp++ == '\n')
601			SCREWUP("unexpected <newline>");
602		do {
603			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
604				SCREWUP("lost connection");
605			*cp++ = ch;
606		} while (cp < &buf[BUFSIZ - 1] && ch != '\n');
607		*cp = 0;
608
609		if (buf[0] == '\01' || buf[0] == '\02') {
610			if (iamremote == 0)
611				(void)write(STDERR_FILENO,
612				    buf + 1, strlen(buf + 1));
613			if (buf[0] == '\02')
614				exit(1);
615			++errs;
616			continue;
617		}
618		if (buf[0] == 'E') {
619			(void)write(rem, "", 1);
620			return;
621		}
622
623		if (ch == '\n')
624			*--cp = 0;
625
626		cp = buf;
627		if (*cp == 'T') {
628			setimes++;
629			cp++;
630			mtime.tv_sec = strtol(cp, &cp, 10);
631			if (!cp || *cp++ != ' ')
632				SCREWUP("mtime.sec not delimited");
633			mtime.tv_usec = strtol(cp, &cp, 10);
634			if (!cp || *cp++ != ' ')
635				SCREWUP("mtime.usec not delimited");
636			atime.tv_sec = strtol(cp, &cp, 10);
637			if (!cp || *cp++ != ' ')
638				SCREWUP("atime.sec not delimited");
639			atime.tv_usec = strtol(cp, &cp, 10);
640			if (!cp || *cp++ != '\0')
641				SCREWUP("atime.usec not delimited");
642			(void)write(rem, "", 1);
643			continue;
644		}
645		if (*cp != 'C' && *cp != 'D') {
646			/*
647			 * Check for the case "rcp remote:foo\* local:bar".
648			 * In this case, the line "No match." can be returned
649			 * by the shell before the rcp command on the remote is
650			 * executed so the ^Aerror_message convention isn't
651			 * followed.
652			 */
653			if (first) {
654				run_err("%s", cp);
655				exit(1);
656			}
657			SCREWUP("expected control record");
658		}
659		mode = 0;
660		for (++cp; cp < buf + 5; cp++) {
661			if (*cp < '0' || *cp > '7')
662				SCREWUP("bad mode");
663			mode = (mode << 3) | (*cp - '0');
664		}
665		if (*cp++ != ' ')
666			SCREWUP("mode not delimited");
667
668		for (size = 0; isdigit(*cp);)
669			size = size * 10 + (*cp++ - '0');
670		if (*cp++ != ' ')
671			SCREWUP("size not delimited");
672		if (targisdir) {
673			static char *namebuf;
674			static int cursize;
675			size_t need;
676
677			need = strlen(targ) + strlen(cp) + 250;
678			if (need > cursize) {
679				if (!(namebuf = malloc(need)))
680					run_err("%s", strerror(errno));
681			}
682			(void)snprintf(namebuf, need, "%s%s%s", targ,
683			    *targ ? "/" : "", cp);
684			np = namebuf;
685		} else
686			np = targ;
687		exists = stat(np, &stb) == 0;
688		if (buf[0] == 'D') {
689			int mod_flag = pflag;
690			if (exists) {
691				if (!S_ISDIR(stb.st_mode)) {
692					errno = ENOTDIR;
693					goto bad;
694				}
695				if (pflag)
696					(void)chmod(np, mode);
697			} else {
698				/* Handle copying from a read-only directory */
699				mod_flag = 1;
700				if (mkdir(np, mode | S_IRWXU) < 0)
701					goto bad;
702			}
703			vect[0] = np;
704			sink(1, vect);
705			if (setimes) {
706				setimes = 0;
707				if (utimes(np, tv) < 0)
708				    run_err("%s: set times: %s",
709					np, strerror(errno));
710			}
711			if (mod_flag)
712				(void)chmod(np, mode);
713			continue;
714		}
715		omode = mode;
716		mode |= S_IWRITE;
717		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
718bad:			run_err("%s: %s", np, strerror(errno));
719			continue;
720		}
721		(void)write(rem, "", 1);
722		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
723			(void)close(ofd);
724			continue;
725		}
726		cp = bp->buf;
727		wrerr = NO;
728		for (count = i = 0; i < size; i += BUFSIZ) {
729			amt = BUFSIZ;
730			if (i + amt > size)
731				amt = size - i;
732			count += amt;
733			do {
734				j = read(rem, cp, amt);
735				if (j <= 0) {
736					run_err("%s", j ? strerror(errno) :
737					    "dropped connection");
738					exit(1);
739				}
740				amt -= j;
741				cp += j;
742			} while (amt > 0);
743			if (count == bp->cnt) {
744				/* Keep reading so we stay sync'd up. */
745				if (wrerr == NO) {
746					j = write(ofd, bp->buf, count);
747					if (j != count) {
748						wrerr = YES;
749						wrerrno = j >= 0 ? EIO : errno;
750					}
751				}
752				count = 0;
753				cp = bp->buf;
754			}
755		}
756		if (count != 0 && wrerr == NO &&
757		    (j = write(ofd, bp->buf, count)) != count) {
758			wrerr = YES;
759			wrerrno = j >= 0 ? EIO : errno;
760		}
761		if (ftruncate(ofd, size)) {
762			run_err("%s: truncate: %s", np, strerror(errno));
763			wrerr = DISPLAYED;
764		}
765		if (pflag) {
766			if (exists || omode != mode)
767				if (fchmod(ofd, omode))
768					run_err("%s: set mode: %s",
769					    np, strerror(errno));
770		} else {
771			if (!exists && omode != mode)
772				if (fchmod(ofd, omode & ~mask))
773					run_err("%s: set mode: %s",
774					    np, strerror(errno));
775		}
776		(void)close(ofd);
777		(void)response();
778		if (setimes && wrerr == NO) {
779			setimes = 0;
780			if (utimes(np, tv) < 0) {
781				run_err("%s: set times: %s",
782				    np, strerror(errno));
783				wrerr = DISPLAYED;
784			}
785		}
786		switch(wrerr) {
787		case YES:
788			run_err("%s: %s", np, strerror(wrerrno));
789			break;
790		case NO:
791			(void)write(rem, "", 1);
792			break;
793		case DISPLAYED:
794			break;
795		}
796	}
797screwup:
798	run_err("protocol error: %s", why);
799	exit(1);
800}
801
802#ifdef KERBEROS
803int
804kerberos(char **host, char *bp, char *locuser, char *user)
805{
806	if (use_kerberos) {
807		setuid(getuid());
808		rem = KSUCCESS;
809		errno = 0;
810		if (dest_realm == NULL)
811			dest_realm = krb_realmofhost(*host);
812		rem =
813#ifdef CRYPT
814		    doencrypt ?
815			krcmd_mutual(host,
816			    port, user, bp, 0, dest_realm, &cred, schedule) :
817#endif
818			krcmd(host, port, user, bp, 0, dest_realm);
819
820		if (rem < 0) {
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			execv(_PATH_RCP, argv_copy);
826			err(1, "execv: %s", _PATH_RCP);
827		}
828	} else {
829#ifdef CRYPT
830		if (doencrypt)
831			errx(1,
832			   "the -x option requires Kerberos authentication");
833#endif
834		rem = rcmd(host, port, locuser, user, bp, 0);
835	}
836	return (rem);
837}
838#endif /* KERBEROS */
839
840int
841response(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
873void
874usage(void)
875{
876#ifdef KERBEROS
877#ifdef CRYPT
878	(void)fprintf(stderr, "%s\n%s\n",
879	    "usage: rcp [-Kpx] [-k realm] f1 f2",
880	    "       rcp [-Kprx] [-k realm] f1 ... fn directory");
881#else
882	(void)fprintf(stderr, "%s\n%s\n",
883	    "usage: rcp [-Kp] [-k realm] f1 f2",
884	    "       rcp [-Kpr] [-k realm] f1 ... fn directory");
885#endif
886#else
887	(void)fprintf(stderr, "%s\n%s\n",
888	    "usage: rcp [-p] f1 f2",
889	    "       rcp [-pr] f1 ... fn directory");
890#endif
891	exit(1);
892}
893
894#include <stdarg.h>
895
896#ifdef KERBEROS
897void
898oldw(const char *fmt, ...)
899{
900	va_list ap;
901	va_start(ap, fmt);
902	(void)fprintf(stderr, "rcp: ");
903	(void)vfprintf(stderr, fmt, ap);
904	(void)fprintf(stderr, ", using standard rcp\n");
905	va_end(ap);
906}
907#endif
908
909void
910run_err(const char *fmt, ...)
911{
912	static FILE *fp;
913	va_list ap;
914	va_start(ap, fmt);
915
916	++errs;
917	if (fp == NULL && !(fp = fdopen(rem, "w")))
918		return;
919	(void)fprintf(fp, "%c", 0x01);
920	(void)fprintf(fp, "rcp: ");
921	(void)vfprintf(fp, fmt, ap);
922	(void)fprintf(fp, "\n");
923	(void)fflush(fp);
924
925	if (!iamremote)
926		vwarnx(fmt, ap);
927
928	va_end(ap);
929}
930