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