Home | History | Annotate | Line # | Download | only in rcp
rcp.c revision 1.41
      1 /*	$NetBSD: rcp.c,v 1.41 2006/03/18 04:44:49 ginsbach 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.41 2006/03/18 04:44:49 ginsbach 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 					(void)free(bp);
    294 					continue;
    295 				}
    296 				(void)snprintf(bp, len,
    297 				    "%s %s -l %s -n %s %s '%s%s%s:%s'",
    298 				    _PATH_RSH, host, suser, cmd, src,
    299 				    tuser ? tuser : "", tuser ? "@" : "",
    300 				    thost, targ);
    301 			} else {
    302 				host = unbracket(argv[i]);
    303 				(void)snprintf(bp, len,
    304 				    "exec %s %s -n %s %s '%s%s%s:%s'",
    305 				    _PATH_RSH, argv[i], cmd, src,
    306 				    tuser ? tuser : "", tuser ? "@" : "",
    307 				    thost, targ);
    308 			}
    309 			(void)susystem(bp);
    310 			(void)free(bp);
    311 		} else {			/* local to remote */
    312 			if (rem == -1) {
    313 				len = strlen(targ) + CMDNEEDS + 20;
    314 				if (!(bp = malloc(len)))
    315 					err(1, NULL);
    316 				(void)snprintf(bp, len, "%s -t %s", cmd, targ);
    317 				host = thost;
    318 #ifdef KERBEROS
    319 				if (use_kerberos)
    320 					rem = kerberos(&host, bp, pwname,
    321 					    tuser ? tuser : pwname);
    322 				else
    323 #endif
    324 					rem = rcmd_af(&host, port, pwname,
    325 					    tuser ? tuser : pwname,
    326 					    bp, NULL, family);
    327 				if (rem < 0)
    328 					exit(1);
    329 				if (response() < 0)
    330 					exit(1);
    331 				(void)free(bp);
    332 			}
    333 			source(1, argv+i);
    334 		}
    335 	}
    336 }
    337 
    338 void
    339 tolocal(int argc, char *argv[])
    340 {
    341 	int i, len;
    342 	char *bp, *host, *src, *suser;
    343 
    344 	for (i = 0; i < argc - 1; i++) {
    345 		if (!(src = colon(argv[i]))) {		/* Local to local. */
    346 			len = strlen(_PATH_CP) + strlen(argv[i]) +
    347 			    strlen(argv[argc - 1]) + 20;
    348 			if (!(bp = malloc(len)))
    349 				err(1, NULL);
    350 			(void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
    351 			    iamrecursive ? " -r" : "", pflag ? " -p" : "",
    352 			    argv[i], argv[argc - 1]);
    353 			if (susystem(bp))
    354 				++errs;
    355 			(void)free(bp);
    356 			continue;
    357 		}
    358 		*src++ = 0;
    359 		if (*src == 0)
    360 			src = dot;
    361 		if ((host = strchr(argv[i], '@')) == NULL) {
    362 			host = argv[i];
    363 			suser = pwname;
    364 		} else {
    365 			*host++ = 0;
    366 			suser = argv[i];
    367 			if (*suser == '\0')
    368 				suser = pwname;
    369 			else if (!okname(suser))
    370 				continue;
    371 		}
    372 		host = unbracket(host);
    373 		len = strlen(src) + CMDNEEDS + 20;
    374 		if ((bp = malloc(len)) == NULL)
    375 			err(1, NULL);
    376 		(void)snprintf(bp, len, "%s -f %s", cmd, src);
    377 		rem =
    378 #ifdef KERBEROS
    379 		    use_kerberos ?
    380 			kerberos(&host, bp, pwname, suser) :
    381 #endif
    382 			rcmd_af(&host, port, pwname, suser, bp, NULL, family);
    383 		(void)free(bp);
    384 		if (rem < 0) {
    385 			++errs;
    386 			continue;
    387 		}
    388 		sink(1, argv + argc - 1);
    389 		(void)close(rem);
    390 		rem = -1;
    391 	}
    392 }
    393 
    394 void
    395 source(int argc, char *argv[])
    396 {
    397 	struct stat stb;
    398 	static BUF buffer;
    399 	BUF *bp;
    400 	off_t i;
    401 	int amt, fd, haderr, indx, result;
    402 	char *last, *name, buf[BUFSIZ];
    403 
    404 #ifdef __GNUC__
    405 	/* This outrageous construct just to shut up a GCC warning. */
    406 	(void) &i;
    407 #endif
    408 
    409 	for (indx = 0; indx < argc; ++indx) {
    410 		name = argv[indx];
    411 		if ((fd = open(name, O_RDONLY, 0)) < 0)
    412 			goto syserr;
    413 		if (fstat(fd, &stb)) {
    414 syserr:			run_err("%s: %s", name, strerror(errno));
    415 			goto next;
    416 		}
    417 		switch (stb.st_mode & S_IFMT) {
    418 		case S_IFREG:
    419 			break;
    420 		case S_IFDIR:
    421 			if (iamrecursive) {
    422 				rsource(name, &stb);
    423 				goto next;
    424 			}
    425 			/* FALLTHROUGH */
    426 		default:
    427 			run_err("%s: not a regular file", name);
    428 			goto next;
    429 		}
    430 		if ((last = strrchr(name, '/')) == NULL)
    431 			last = name;
    432 		else
    433 			++last;
    434 		if (pflag) {
    435 			/*
    436 			 * Make it compatible with possible future
    437 			 * versions expecting microseconds.
    438 			 */
    439 			(void)snprintf(buf, sizeof(buf), "T%ld %ld %ld %ld\n",
    440 			    (long)stb.st_mtimespec.tv_sec,
    441 			    (long)stb.st_mtimespec.tv_nsec / 1000,
    442 			    (long)stb.st_atimespec.tv_sec,
    443 			    (long)stb.st_atimespec.tv_nsec / 1000);
    444 			(void)write(rem, buf, strlen(buf));
    445 			if (response() < 0)
    446 				goto next;
    447 		}
    448 #define	RCPMODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
    449 		(void)snprintf(buf, sizeof(buf), "C%04o %lld %s\n",
    450 		    stb.st_mode & RCPMODEMASK, (long long)stb.st_size, last);
    451 		(void)write(rem, buf, strlen(buf));
    452 		if (response() < 0)
    453 			goto next;
    454 		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
    455 next:			(void)close(fd);
    456 			continue;
    457 		}
    458 
    459 		/* Keep writing after an error so that we stay sync'd up. */
    460 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
    461 			amt = bp->cnt;
    462 			if (i + amt > stb.st_size)
    463 				amt = stb.st_size - i;
    464 			if (!haderr) {
    465 				result = read(fd, bp->buf, amt);
    466 				if (result != amt)
    467 					haderr = result >= 0 ? EIO : errno;
    468 			}
    469 			if (haderr)
    470 				(void)write(rem, bp->buf, amt);
    471 			else {
    472 				result = write(rem, bp->buf, amt);
    473 				if (result != amt)
    474 					haderr = result >= 0 ? EIO : errno;
    475 			}
    476 		}
    477 		if (close(fd) && !haderr)
    478 			haderr = errno;
    479 		if (!haderr)
    480 			(void)write(rem, "", 1);
    481 		else
    482 			run_err("%s: %s", name, strerror(haderr));
    483 		(void)response();
    484 	}
    485 }
    486 
    487 void
    488 rsource(char *name, struct stat *statp)
    489 {
    490 	DIR *dirp;
    491 	struct dirent *dp;
    492 	char *last, *vect[1], path[MAXPATHLEN];
    493 
    494 	if (!(dirp = opendir(name))) {
    495 		run_err("%s: %s", name, strerror(errno));
    496 		return;
    497 	}
    498 	last = strrchr(name, '/');
    499 	if (last == 0)
    500 		last = name;
    501 	else
    502 		last++;
    503 	if (pflag) {
    504 		(void)snprintf(path, sizeof(path), "T%ld %ld %ld %ld\n",
    505 		    (long)statp->st_mtimespec.tv_sec,
    506 		    (long)statp->st_mtimespec.tv_nsec / 1000,
    507 		    (long)statp->st_atimespec.tv_sec,
    508 		    (long)statp->st_atimespec.tv_nsec / 1000);
    509 		(void)write(rem, path, strlen(path));
    510 		if (response() < 0) {
    511 			closedir(dirp);
    512 			return;
    513 		}
    514 	}
    515 	(void)snprintf(path, sizeof(path),
    516 	    "D%04o %d %s\n", statp->st_mode & RCPMODEMASK, 0, last);
    517 	(void)write(rem, path, strlen(path));
    518 	if (response() < 0) {
    519 		closedir(dirp);
    520 		return;
    521 	}
    522 	while ((dp = readdir(dirp)) != NULL) {
    523 		if (dp->d_ino == 0)
    524 			continue;
    525 		if (!strcmp(dp->d_name, dot) || !strcmp(dp->d_name, ".."))
    526 			continue;
    527 		if (strlen(name) + 1 + strlen(dp->d_name) >= MAXPATHLEN - 1) {
    528 			run_err("%s/%s: name too long", name, dp->d_name);
    529 			continue;
    530 		}
    531 		(void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
    532 		vect[0] = path;
    533 		source(1, vect);
    534 	}
    535 	(void)closedir(dirp);
    536 	(void)write(rem, "E\n", 2);
    537 	(void)response();
    538 }
    539 
    540 void
    541 sink(int argc, char *argv[])
    542 {
    543 	static BUF buffer;
    544 	struct stat stb;
    545 	struct timeval tv[2];
    546 	enum { YES, NO, DISPLAYED } wrerr;
    547 	BUF *bp;
    548 	off_t i, j;
    549 	int amt, count, exists, first, mask, mode, ofd, omode;
    550 	int setimes, targisdir;
    551 	int wrerrno = 0;	/* pacify gcc */
    552 	char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ];
    553 	const char *why;
    554 	off_t size;
    555 
    556 #define	atime	tv[0]
    557 #define	mtime	tv[1]
    558 #define	SCREWUP(str)	{ why = str; goto screwup; }
    559 
    560 #ifdef __GNUC__
    561 	/* This outrageous construct just to shut up a GCC warning. */
    562 	(void) &i;
    563 #endif
    564 
    565 	setimes = targisdir = 0;
    566 	mask = umask(0);
    567 	if (!pflag)
    568 		(void)umask(mask);
    569 	if (argc != 1) {
    570 		run_err("ambiguous target");
    571 		exit(1);
    572 	}
    573 	targ = *argv;
    574 	if (targetshouldbedirectory)
    575 		verifydir(targ);
    576 	(void)write(rem, "", 1);
    577 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
    578 		targisdir = 1;
    579 	for (first = 1;; first = 0) {
    580 		cp = buf;
    581 		if (read(rem, cp, 1) <= 0)
    582 			return;
    583 		if (*cp++ == '\n')
    584 			SCREWUP("unexpected <newline>");
    585 		do {
    586 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
    587 				SCREWUP("lost connection");
    588 			*cp++ = ch;
    589 		} while (cp < &buf[BUFSIZ - 1] && ch != '\n');
    590 		*cp = 0;
    591 
    592 		if (buf[0] == '\01' || buf[0] == '\02') {
    593 			if (iamremote == 0)
    594 				(void)write(STDERR_FILENO,
    595 				    buf + 1, strlen(buf + 1));
    596 			if (buf[0] == '\02')
    597 				exit(1);
    598 			++errs;
    599 			continue;
    600 		}
    601 		if (buf[0] == 'E') {
    602 			(void)write(rem, "", 1);
    603 			return;
    604 		}
    605 
    606 		if (ch == '\n')
    607 			*--cp = 0;
    608 
    609 #define getnum(t) (t) = 0; while (isdigit((unsigned char)*cp)) (t) = (t) * 10 + (*cp++ - '0');
    610 		cp = buf;
    611 		if (*cp == 'T') {
    612 			setimes++;
    613 			cp++;
    614 			getnum(mtime.tv_sec);
    615 			if (*cp++ != ' ')
    616 				SCREWUP("mtime.sec not delimited");
    617 			getnum(mtime.tv_usec);
    618 			if (*cp++ != ' ')
    619 				SCREWUP("mtime.usec not delimited");
    620 			getnum(atime.tv_sec);
    621 			if (*cp++ != ' ')
    622 				SCREWUP("atime.sec not delimited");
    623 			getnum(atime.tv_usec);
    624 			if (*cp++ != '\0')
    625 				SCREWUP("atime.usec not delimited");
    626 			(void)write(rem, "", 1);
    627 			continue;
    628 		}
    629 		if (*cp != 'C' && *cp != 'D') {
    630 			/*
    631 			 * Check for the case "rcp remote:foo\* local:bar".
    632 			 * In this case, the line "No match." can be returned
    633 			 * by the shell before the rcp command on the remote is
    634 			 * executed so the ^Aerror_message convention isn't
    635 			 * followed.
    636 			 */
    637 			if (first) {
    638 				run_err("%s", cp);
    639 				exit(1);
    640 			}
    641 			SCREWUP("expected control record");
    642 		}
    643 		mode = 0;
    644 		for (++cp; cp < buf + 5; cp++) {
    645 			if (*cp < '0' || *cp > '7')
    646 				SCREWUP("bad mode");
    647 			mode = (mode << 3) | (*cp - '0');
    648 		}
    649 		if (*cp++ != ' ')
    650 			SCREWUP("mode not delimited");
    651 
    652 		for (size = 0; isdigit((unsigned char)*cp);)
    653 			size = size * 10 + (*cp++ - '0');
    654 		if (*cp++ != ' ')
    655 			SCREWUP("size not delimited");
    656 		if (targisdir) {
    657 			static char *namebuf;
    658 			static int cursize;
    659 			size_t need;
    660 
    661 			need = strlen(targ) + strlen(cp) + 250;
    662 			if (need > cursize) {
    663 				if (!(namebuf = malloc(need)))
    664 					run_err("%s", strerror(errno));
    665 			}
    666 			(void)snprintf(namebuf, need, "%s%s%s", targ,
    667 			    *targ ? "/" : "", cp);
    668 			np = namebuf;
    669 		} else
    670 			np = targ;
    671 		exists = stat(np, &stb) == 0;
    672 		if (buf[0] == 'D') {
    673 			int mod_flag = pflag;
    674 			if (exists) {
    675 				if (!S_ISDIR(stb.st_mode)) {
    676 					errno = ENOTDIR;
    677 					goto bad;
    678 				}
    679 				if (pflag)
    680 					(void)chmod(np, mode);
    681 			} else {
    682 				/* Handle copying from a read-only directory */
    683 				mod_flag = 1;
    684 				if (mkdir(np, mode | S_IRWXU) < 0)
    685 					goto bad;
    686 			}
    687 			vect[0] = np;
    688 			sink(1, vect);
    689 			if (setimes) {
    690 				setimes = 0;
    691 				if (utimes(np, tv) < 0)
    692 				    run_err("%s: set times: %s",
    693 					np, strerror(errno));
    694 			}
    695 			if (mod_flag)
    696 				(void)chmod(np, mode);
    697 			continue;
    698 		}
    699 		omode = mode;
    700 		mode |= S_IWRITE;
    701 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
    702 bad:			run_err("%s: %s", np, strerror(errno));
    703 			continue;
    704 		}
    705 		(void)write(rem, "", 1);
    706 		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
    707 			(void)close(ofd);
    708 			continue;
    709 		}
    710 		cp = bp->buf;
    711 		wrerr = NO;
    712 		for (count = i = 0; i < size; i += BUFSIZ) {
    713 			amt = BUFSIZ;
    714 			if (i + amt > size)
    715 				amt = size - i;
    716 			count += amt;
    717 			do {
    718 				j = read(rem, cp, amt);
    719 				if (j <= 0) {
    720 					run_err("%s", j ? strerror(errno) :
    721 					    "dropped connection");
    722 					exit(1);
    723 				}
    724 				amt -= j;
    725 				cp += j;
    726 			} while (amt > 0);
    727 			if (count == bp->cnt) {
    728 				/* Keep reading so we stay sync'd up. */
    729 				if (wrerr == NO) {
    730 					j = write(ofd, bp->buf, count);
    731 					if (j != count) {
    732 						wrerr = YES;
    733 						wrerrno = j >= 0 ? EIO : errno;
    734 					}
    735 				}
    736 				count = 0;
    737 				cp = bp->buf;
    738 			}
    739 		}
    740 		if (count != 0 && wrerr == NO &&
    741 		    (j = write(ofd, bp->buf, count)) != count) {
    742 			wrerr = YES;
    743 			wrerrno = j >= 0 ? EIO : errno;
    744 		}
    745 		if (ftruncate(ofd, size)) {
    746 			run_err("%s: truncate: %s", np, strerror(errno));
    747 			wrerr = DISPLAYED;
    748 		}
    749 		if (pflag) {
    750 			if (exists || omode != mode)
    751 				if (fchmod(ofd, omode))
    752 					run_err("%s: set mode: %s",
    753 					    np, strerror(errno));
    754 		} else {
    755 			if (!exists && omode != mode)
    756 				if (fchmod(ofd, omode & ~mask))
    757 					run_err("%s: set mode: %s",
    758 					    np, strerror(errno));
    759 		}
    760 #ifndef __SVR4
    761 		if (setimes && wrerr == NO) {
    762 			setimes = 0;
    763 			if (futimes(ofd, tv) < 0) {
    764 				run_err("%s: set times: %s",
    765 				    np, strerror(errno));
    766 				wrerr = DISPLAYED;
    767 			}
    768 		}
    769 #endif
    770 		(void)close(ofd);
    771 #ifdef __SVR4
    772 		if (setimes && wrerr == NO) {
    773 			setimes = 0;
    774 			if (utimes(np, tv) < 0) {
    775 				run_err("%s: set times: %s",
    776 				    np, strerror(errno));
    777 				wrerr = DISPLAYED;
    778 			}
    779 		}
    780 #endif
    781 		(void)response();
    782 		switch(wrerr) {
    783 		case YES:
    784 			run_err("%s: write: %s", np, strerror(wrerrno));
    785 			break;
    786 		case NO:
    787 			(void)write(rem, "", 1);
    788 			break;
    789 		case DISPLAYED:
    790 			break;
    791 		}
    792 	}
    793 screwup:
    794 	run_err("protocol error: %s", why);
    795 	exit(1);
    796 	/* NOTREACHED */
    797 }
    798 
    799 #ifdef KERBEROS
    800 int
    801 kerberos(char **host, char *bp, char *locuser, char *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_af(host, port, locuser, user, bp, NULL, family);
    837 	}
    838 	return (rem);
    839 }
    840 #endif /* KERBEROS */
    841 
    842 int
    843 response(void)
    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(void)
    877 {
    878 #ifdef KERBEROS
    879 #ifdef CRYPT
    880 	(void)fprintf(stderr, "%s\n\t%s\n",
    881 	    "usage: rcp [-46Kpx] [-k realm] f1 f2",
    882 	    "or: rcp [-46Kprx] [-k realm] f1 ... fn directory");
    883 #else
    884 	(void)fprintf(stderr, "%s\n\t%s\n",
    885 	    "usage: rcp [-46Kp] [-k realm] f1 f2",
    886 	    "or: rcp [-46Kpr] [-k realm] f1 ... fn directory");
    887 #endif
    888 #else
    889 	(void)fprintf(stderr,
    890 	    "usage: rcp [-46p] f1 f2; or: rcp [-46pr] f1 ... fn directory\n");
    891 #endif
    892 	exit(1);
    893 	/* NOTREACHED */
    894 }
    895 
    896 #include <stdarg.h>
    897 
    898 #ifdef KERBEROS
    899 void
    900 oldw(const char *fmt, ...)
    901 {
    902 	va_list ap;
    903 
    904 	va_start(ap, fmt);
    905 	(void)fprintf(stderr, "rcp: ");
    906 	(void)vfprintf(stderr, fmt, ap);
    907 	(void)fprintf(stderr, ", using standard rcp\n");
    908 	va_end(ap);
    909 }
    910 #endif
    911 
    912 void
    913 run_err(const char *fmt, ...)
    914 {
    915 	static FILE *fp;
    916 	va_list ap;
    917 
    918 	++errs;
    919 	if (fp == NULL && !(fp = fdopen(rem, "w")))
    920 		return;
    921 
    922 	va_start(ap, fmt);
    923 
    924 	(void)fprintf(fp, "%c", 0x01);
    925 	(void)fprintf(fp, "rcp: ");
    926 	(void)vfprintf(fp, fmt, ap);
    927 	(void)fprintf(fp, "\n");
    928 	(void)fflush(fp);
    929 	va_end(ap);
    930 
    931 	if (!iamremote) {
    932 		va_start(ap, fmt);
    933 		vwarnx(fmt, ap);
    934 		va_end(ap);
    935 	}
    936 }
    937