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