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