Home | History | Annotate | Line # | Download | only in rcp
rcp.c revision 1.32
      1 /*	$NetBSD: rcp.c,v 1.32 2003/07/23 21:10:36 itojun 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.32 2003/07/23 21:10:36 itojun 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 <des.h>
     77 #include <kerberosIV/krb.h>
     78 #include "krb.h"
     79 
     80 char	dst_realm_buf[REALM_SZ];
     81 char	*dest_realm = NULL;
     82 int	use_kerberos = 1;
     83 CREDENTIALS 	cred;
     84 Key_schedule	schedule;
     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 			if (strlcpy(dst_realm_buf, optarg,
    139 			    sizeof(dst_realm_buf)) >= sizeof(dst_realm_buf))
    140 				errx(1, "Argument `realm' is too long");
    141 			break;
    142 #ifdef CRYPT
    143 		case 'x':
    144 			doencrypt = 1;
    145 			/* des_set_key(cred.session, schedule); */
    146 			break;
    147 #endif
    148 #endif
    149 		case 'p':
    150 			pflag = 1;
    151 			break;
    152 		case 'r':
    153 			iamrecursive = 1;
    154 			break;
    155 						/* Server options. */
    156 		case 'd':
    157 			targetshouldbedirectory = 1;
    158 			break;
    159 		case 'f':			/* "from" */
    160 			iamremote = 1;
    161 			fflag = 1;
    162 			break;
    163 		case 't':			/* "to" */
    164 			iamremote = 1;
    165 			tflag = 1;
    166 			break;
    167 		case '?':
    168 		default:
    169 			usage();
    170 		}
    171 	argc -= optind;
    172 	argv += optind;
    173 
    174 #ifdef KERBEROS
    175 	if (use_kerberos) {
    176 #ifdef CRYPT
    177 		shell = doencrypt ? "ekshell" : "kshell";
    178 #else
    179 		shell = "kshell";
    180 #endif
    181 		if ((sp = getservbyname(shell, "tcp")) == NULL) {
    182 			use_kerberos = 0;
    183 			oldw("can't get entry for %s/tcp service", shell);
    184 			sp = getservbyname(shell = "shell", "tcp");
    185 		}
    186 	} else
    187 		sp = getservbyname(shell = "shell", "tcp");
    188 #else
    189 	sp = getservbyname(shell = "shell", "tcp");
    190 #endif
    191 	if (sp == NULL)
    192 		errx(1, "%s/tcp: unknown service", shell);
    193 	port = sp->s_port;
    194 
    195 	if ((pwd = getpwuid(userid = getuid())) == NULL)
    196 		errx(1, "unknown user %d", (int)userid);
    197 
    198 	if ((pwname = strdup(pwd->pw_name)) == NULL)
    199 		err(1, NULL);
    200 
    201 	rem = STDIN_FILENO;		/* XXX */
    202 
    203 	if (fflag) {			/* Follow "protocol", send data. */
    204 		(void)response();
    205 		source(argc, argv);
    206 		exit(errs);
    207 	}
    208 
    209 	if (tflag) {			/* Receive data. */
    210 		sink(argc, argv);
    211 		exit(errs);
    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 	} else {
    270 		thost = argv[argc - 1];
    271 		tuser = NULL;
    272 	}
    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 = ".";
    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 				suser = argv[i];
    289 				if (*suser == '\0')
    290 					suser = pwname;
    291 				else if (!okname(suser))
    292 					continue;
    293 				(void)snprintf(bp, len,
    294 				    "%s %s -l %s -n %s %s '%s%s%s:%s'",
    295 				    _PATH_RSH, host, suser, cmd, src,
    296 				    tuser ? tuser : "", tuser ? "@" : "",
    297 				    thost, targ);
    298 			} else
    299 				(void)snprintf(bp, len,
    300 				    "exec %s %s -n %s %s '%s%s%s:%s'",
    301 				    _PATH_RSH, argv[i], cmd, src,
    302 				    tuser ? tuser : "", tuser ? "@" : "",
    303 				    thost, targ);
    304 			(void)susystem(bp);
    305 			(void)free(bp);
    306 		} else {			/* local to remote */
    307 			if (rem == -1) {
    308 				len = strlen(targ) + CMDNEEDS + 20;
    309 				if (!(bp = malloc(len)))
    310 					err(1, NULL);
    311 				(void)snprintf(bp, len, "%s -t %s", cmd, targ);
    312 				host = thost;
    313 #ifdef KERBEROS
    314 				if (use_kerberos)
    315 					rem = kerberos(&host, bp, pwname,
    316 					    tuser ? tuser : pwname);
    317 				else
    318 #endif
    319 					rem = rcmd(&host, port, pwname,
    320 					    tuser ? tuser : pwname,
    321 					    bp, 0);
    322 				if (rem < 0)
    323 					exit(1);
    324 				if (response() < 0)
    325 					exit(1);
    326 				(void)free(bp);
    327 			}
    328 			source(1, argv+i);
    329 		}
    330 	}
    331 }
    332 
    333 void
    334 tolocal(argc, argv)
    335 	int argc;
    336 	char *argv[];
    337 {
    338 	int i, len;
    339 	char *bp, *host, *src, *suser;
    340 
    341 	for (i = 0; i < argc - 1; i++) {
    342 		if (!(src = colon(argv[i]))) {		/* Local to local. */
    343 			len = strlen(_PATH_CP) + strlen(argv[i]) +
    344 			    strlen(argv[argc - 1]) + 20;
    345 			if (!(bp = malloc(len)))
    346 				err(1, NULL);
    347 			(void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
    348 			    iamrecursive ? " -r" : "", pflag ? " -p" : "",
    349 			    argv[i], argv[argc - 1]);
    350 			if (susystem(bp))
    351 				++errs;
    352 			(void)free(bp);
    353 			continue;
    354 		}
    355 		*src++ = 0;
    356 		if (*src == 0)
    357 			src = ".";
    358 		if ((host = strchr(argv[i], '@')) == NULL) {
    359 			host = argv[i];
    360 			suser = pwname;
    361 		} else {
    362 			*host++ = 0;
    363 			suser = argv[i];
    364 			if (*suser == '\0')
    365 				suser = pwname;
    366 			else if (!okname(suser))
    367 				continue;
    368 		}
    369 		len = strlen(src) + CMDNEEDS + 20;
    370 		if ((bp = malloc(len)) == NULL)
    371 			err(1, NULL);
    372 		(void)snprintf(bp, len, "%s -f %s", cmd, src);
    373 		rem =
    374 #ifdef KERBEROS
    375 		    use_kerberos ?
    376 			kerberos(&host, bp, pwname, suser) :
    377 #endif
    378 			rcmd(&host, port, pwname, suser, bp, 0);
    379 		(void)free(bp);
    380 		if (rem < 0) {
    381 			++errs;
    382 			continue;
    383 		}
    384 		sink(1, argv + argc - 1);
    385 		(void)close(rem);
    386 		rem = -1;
    387 	}
    388 }
    389 
    390 void
    391 source(argc, argv)
    392 	int argc;
    393 	char *argv[];
    394 {
    395 	struct stat stb;
    396 	static BUF buffer;
    397 	BUF *bp;
    398 	off_t i;
    399 	int amt, fd, haderr, indx, result;
    400 	char *last, *name, buf[BUFSIZ];
    401 
    402 #ifdef __GNUC__
    403 	/* This outrageous construct just to shut up a GCC warning. */
    404 	(void) &i;
    405 #endif
    406 
    407 	for (indx = 0; indx < argc; ++indx) {
    408                 name = argv[indx];
    409 		if ((fd = open(name, O_RDONLY, 0)) < 0)
    410 			goto syserr;
    411 		if (fstat(fd, &stb)) {
    412 syserr:			run_err("%s: %s", name, strerror(errno));
    413 			goto next;
    414 		}
    415 		switch (stb.st_mode & S_IFMT) {
    416 		case S_IFREG:
    417 			break;
    418 		case S_IFDIR:
    419 			if (iamrecursive) {
    420 				rsource(name, &stb);
    421 				goto next;
    422 			}
    423 			/* FALLTHROUGH */
    424 		default:
    425 			run_err("%s: not a regular file", name);
    426 			goto next;
    427 		}
    428 		if ((last = strrchr(name, '/')) == NULL)
    429 			last = name;
    430 		else
    431 			++last;
    432 		if (pflag) {
    433 			/*
    434 			 * Make it compatible with possible future
    435 			 * versions expecting microseconds.
    436 			 */
    437 			(void)snprintf(buf, sizeof(buf), "T%ld %ld %ld %ld\n",
    438 			    (long)stb.st_mtimespec.tv_sec,
    439 			    (long)stb.st_mtimespec.tv_nsec / 1000,
    440 			    (long)stb.st_atimespec.tv_sec,
    441 			    (long)stb.st_atimespec.tv_nsec / 1000);
    442 			(void)write(rem, buf, strlen(buf));
    443 			if (response() < 0)
    444 				goto next;
    445 		}
    446 #define	RCPMODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
    447 		(void)snprintf(buf, sizeof(buf), "C%04o %lld %s\n",
    448 		    stb.st_mode & RCPMODEMASK, (long long)stb.st_size, last);
    449 		(void)write(rem, buf, strlen(buf));
    450 		if (response() < 0)
    451 			goto next;
    452 		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
    453 next:			(void)close(fd);
    454 			continue;
    455 		}
    456 
    457 		/* Keep writing after an error so that we stay sync'd up. */
    458 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
    459 			amt = bp->cnt;
    460 			if (i + amt > stb.st_size)
    461 				amt = stb.st_size - i;
    462 			if (!haderr) {
    463 				result = read(fd, bp->buf, amt);
    464 				if (result != amt)
    465 					haderr = result >= 0 ? EIO : errno;
    466 			}
    467 			if (haderr)
    468 				(void)write(rem, bp->buf, amt);
    469 			else {
    470 				result = write(rem, bp->buf, amt);
    471 				if (result != amt)
    472 					haderr = result >= 0 ? EIO : errno;
    473 			}
    474 		}
    475 		if (close(fd) && !haderr)
    476 			haderr = errno;
    477 		if (!haderr)
    478 			(void)write(rem, "", 1);
    479 		else
    480 			run_err("%s: %s", name, strerror(haderr));
    481 		(void)response();
    482 	}
    483 }
    484 
    485 void
    486 rsource(name, statp)
    487 	char *name;
    488 	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, ".") || !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(argc, argv)
    542 	int argc;
    543 	char *argv[];
    544 {
    545 	static BUF buffer;
    546 	struct stat stb;
    547 	struct timeval tv[2];
    548 	enum { YES, NO, DISPLAYED } wrerr;
    549 	BUF *bp;
    550 	off_t i, j;
    551 	int amt, count, exists, first, mask, mode, ofd, omode;
    552 	int setimes, targisdir;
    553 	int wrerrno = 0;	/* pacify gcc */
    554 	char ch, *cp, *np, *targ, *why, *vect[1], buf[BUFSIZ];
    555 	off_t size;
    556 
    557 #define	atime	tv[0]
    558 #define	mtime	tv[1]
    559 #define	SCREWUP(str)	{ why = str; goto screwup; }
    560 
    561 #ifdef __GNUC__
    562 	/* This outrageous construct just to shut up a GCC warning. */
    563 	(void) &i;
    564 #endif
    565 
    566 	setimes = targisdir = 0;
    567 	mask = umask(0);
    568 	if (!pflag)
    569 		(void)umask(mask);
    570 	if (argc != 1) {
    571 		run_err("ambiguous target");
    572 		exit(1);
    573 	}
    574 	targ = *argv;
    575 	if (targetshouldbedirectory)
    576 		verifydir(targ);
    577 	(void)write(rem, "", 1);
    578 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
    579 		targisdir = 1;
    580 	for (first = 1;; first = 0) {
    581 		cp = buf;
    582 		if (read(rem, cp, 1) <= 0)
    583 			return;
    584 		if (*cp++ == '\n')
    585 			SCREWUP("unexpected <newline>");
    586 		do {
    587 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
    588 				SCREWUP("lost connection");
    589 			*cp++ = ch;
    590 		} while (cp < &buf[BUFSIZ - 1] && ch != '\n');
    591 		*cp = 0;
    592 
    593 		if (buf[0] == '\01' || buf[0] == '\02') {
    594 			if (iamremote == 0)
    595 				(void)write(STDERR_FILENO,
    596 				    buf + 1, strlen(buf + 1));
    597 			if (buf[0] == '\02')
    598 				exit(1);
    599 			++errs;
    600 			continue;
    601 		}
    602 		if (buf[0] == 'E') {
    603 			(void)write(rem, "", 1);
    604 			return;
    605 		}
    606 
    607 		if (ch == '\n')
    608 			*--cp = 0;
    609 
    610 #define getnum(t) (t) = 0; while (isdigit((unsigned char)*cp)) (t) = (t) * 10 + (*cp++ - '0');
    611 		cp = buf;
    612 		if (*cp == 'T') {
    613 			setimes++;
    614 			cp++;
    615 			getnum(mtime.tv_sec);
    616 			if (*cp++ != ' ')
    617 				SCREWUP("mtime.sec not delimited");
    618 			getnum(mtime.tv_usec);
    619 			if (*cp++ != ' ')
    620 				SCREWUP("mtime.usec not delimited");
    621 			getnum(atime.tv_sec);
    622 			if (*cp++ != ' ')
    623 				SCREWUP("atime.sec not delimited");
    624 			getnum(atime.tv_usec);
    625 			if (*cp++ != '\0')
    626 				SCREWUP("atime.usec not delimited");
    627 			(void)write(rem, "", 1);
    628 			continue;
    629 		}
    630 		if (*cp != 'C' && *cp != 'D') {
    631 			/*
    632 			 * Check for the case "rcp remote:foo\* local:bar".
    633 			 * In this case, the line "No match." can be returned
    634 			 * by the shell before the rcp command on the remote is
    635 			 * executed so the ^Aerror_message convention isn't
    636 			 * followed.
    637 			 */
    638 			if (first) {
    639 				run_err("%s", cp);
    640 				exit(1);
    641 			}
    642 			SCREWUP("expected control record");
    643 		}
    644 		mode = 0;
    645 		for (++cp; cp < buf + 5; cp++) {
    646 			if (*cp < '0' || *cp > '7')
    647 				SCREWUP("bad mode");
    648 			mode = (mode << 3) | (*cp - '0');
    649 		}
    650 		if (*cp++ != ' ')
    651 			SCREWUP("mode not delimited");
    652 
    653 		for (size = 0; isdigit((unsigned char)*cp);)
    654 			size = size * 10 + (*cp++ - '0');
    655 		if (*cp++ != ' ')
    656 			SCREWUP("size not delimited");
    657 		if (targisdir) {
    658 			static char *namebuf;
    659 			static int cursize;
    660 			size_t need;
    661 
    662 			need = strlen(targ) + strlen(cp) + 250;
    663 			if (need > cursize) {
    664 				if (!(namebuf = malloc(need)))
    665 					run_err("%s", strerror(errno));
    666 			}
    667 			(void)snprintf(namebuf, need, "%s%s%s", targ,
    668 			    *targ ? "/" : "", cp);
    669 			np = namebuf;
    670 		} else
    671 			np = targ;
    672 		exists = stat(np, &stb) == 0;
    673 		if (buf[0] == 'D') {
    674 			int mod_flag = pflag;
    675 			if (exists) {
    676 				if (!S_ISDIR(stb.st_mode)) {
    677 					errno = ENOTDIR;
    678 					goto bad;
    679 				}
    680 				if (pflag)
    681 					(void)chmod(np, mode);
    682 			} else {
    683 				/* Handle copying from a read-only directory */
    684 				mod_flag = 1;
    685 				if (mkdir(np, mode | S_IRWXU) < 0)
    686 					goto bad;
    687 			}
    688 			vect[0] = np;
    689 			sink(1, vect);
    690 			if (setimes) {
    691 				setimes = 0;
    692 				if (utimes(np, tv) < 0)
    693 				    run_err("%s: set times: %s",
    694 					np, strerror(errno));
    695 			}
    696 			if (mod_flag)
    697 				(void)chmod(np, mode);
    698 			continue;
    699 		}
    700 		omode = mode;
    701 		mode |= S_IWRITE;
    702 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
    703 bad:			run_err("%s: %s", np, strerror(errno));
    704 			continue;
    705 		}
    706 		(void)write(rem, "", 1);
    707 		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
    708 			(void)close(ofd);
    709 			continue;
    710 		}
    711 		cp = bp->buf;
    712 		wrerr = NO;
    713 		for (count = i = 0; i < size; i += BUFSIZ) {
    714 			amt = BUFSIZ;
    715 			if (i + amt > size)
    716 				amt = size - i;
    717 			count += amt;
    718 			do {
    719 				j = read(rem, cp, amt);
    720 				if (j <= 0) {
    721 					run_err("%s", j ? strerror(errno) :
    722 					    "dropped connection");
    723 					exit(1);
    724 				}
    725 				amt -= j;
    726 				cp += j;
    727 			} while (amt > 0);
    728 			if (count == bp->cnt) {
    729 				/* Keep reading so we stay sync'd up. */
    730 				if (wrerr == NO) {
    731 					j = write(ofd, bp->buf, count);
    732 					if (j != count) {
    733 						wrerr = YES;
    734 						wrerrno = j >= 0 ? EIO : errno;
    735 					}
    736 				}
    737 				count = 0;
    738 				cp = bp->buf;
    739 			}
    740 		}
    741 		if (count != 0 && wrerr == NO &&
    742 		    (j = write(ofd, bp->buf, count)) != count) {
    743 			wrerr = YES;
    744 			wrerrno = j >= 0 ? EIO : errno;
    745 		}
    746 		if (ftruncate(ofd, size)) {
    747 			run_err("%s: truncate: %s", np, strerror(errno));
    748 			wrerr = DISPLAYED;
    749 		}
    750 		if (pflag) {
    751 			if (exists || omode != mode)
    752 				if (fchmod(ofd, omode))
    753 					run_err("%s: set mode: %s",
    754 					    np, strerror(errno));
    755 		} else {
    756 			if (!exists && omode != mode)
    757 				if (fchmod(ofd, omode & ~mask))
    758 					run_err("%s: set mode: %s",
    759 					    np, strerror(errno));
    760 		}
    761 #ifndef __SVR4
    762 		if (setimes && wrerr == NO) {
    763 			setimes = 0;
    764 			if (futimes(ofd, tv) < 0) {
    765 				run_err("%s: set times: %s",
    766 				    np, strerror(errno));
    767 				wrerr = DISPLAYED;
    768 			}
    769 		}
    770 #endif
    771 		(void)close(ofd);
    772 #ifdef __SVR4
    773 		if (setimes && wrerr == NO) {
    774 			setimes = 0;
    775 			if (utimes(np, tv) < 0) {
    776 				run_err("%s: set times: %s",
    777 				    np, strerror(errno));
    778 				wrerr = DISPLAYED;
    779 			}
    780 		}
    781 #endif
    782 		(void)response();
    783 		switch(wrerr) {
    784 		case YES:
    785 			run_err("%s: write: %s", np, strerror(wrerrno));
    786 			break;
    787 		case NO:
    788 			(void)write(rem, "", 1);
    789 			break;
    790 		case DISPLAYED:
    791 			break;
    792 		}
    793 	}
    794 screwup:
    795 	run_err("protocol error: %s", why);
    796 	exit(1);
    797 	/* NOTREACHED */
    798 }
    799 
    800 #ifdef KERBEROS
    801 int
    802 kerberos(host, bp, locuser, user)
    803 	char **host, *bp, *locuser, *user;
    804 {
    805 	struct servent *sp;
    806 
    807 again:
    808 	if (use_kerberos) {
    809 		rem = KSUCCESS;
    810 		errno = 0;
    811 		if (dest_realm == NULL)
    812 			dest_realm = krb_realmofhost(*host);
    813 		rem =
    814 #ifdef CRYPT
    815 		    doencrypt ?
    816 			krcmd_mutual(host,
    817 			    port, user, bp, 0, dest_realm, &cred, schedule) :
    818 #endif
    819 			krcmd(host, port, user, bp, 0, dest_realm);
    820 
    821 		if (rem < 0) {
    822 			use_kerberos = 0;
    823 			if ((sp = getservbyname("shell", "tcp")) == NULL)
    824 				errx(1, "unknown service shell/tcp");
    825 			if (errno == ECONNREFUSED)
    826 			    oldw("remote host doesn't support Kerberos");
    827 			else if (errno == ENOENT)
    828 			    oldw("can't provide Kerberos authentication data");
    829 			port = sp->s_port;
    830 			goto again;
    831 		}
    832 	} else {
    833 #ifdef CRYPT
    834 		if (doencrypt)
    835 			errx(1,
    836 			   "the -x option requires Kerberos authentication");
    837 #endif
    838 		rem = rcmd(host, port, locuser, user, bp, 0);
    839 	}
    840 	return (rem);
    841 }
    842 #endif /* KERBEROS */
    843 
    844 int
    845 response()
    846 {
    847 	char ch, *cp, resp, rbuf[BUFSIZ];
    848 
    849 	if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
    850 		lostconn(0);
    851 
    852 	cp = rbuf;
    853 	switch(resp) {
    854 	case 0:				/* ok */
    855 		return (0);
    856 	default:
    857 		*cp++ = resp;
    858 		/* FALLTHROUGH */
    859 	case 1:				/* error, followed by error msg */
    860 	case 2:				/* fatal error, "" */
    861 		do {
    862 			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
    863 				lostconn(0);
    864 			*cp++ = ch;
    865 		} while (cp < &rbuf[BUFSIZ] && ch != '\n');
    866 
    867 		if (!iamremote)
    868 			(void)write(STDERR_FILENO, rbuf, cp - rbuf);
    869 		++errs;
    870 		if (resp == 1)
    871 			return (-1);
    872 		exit(1);
    873 	}
    874 	/* NOTREACHED */
    875 }
    876 
    877 void
    878 usage()
    879 {
    880 #ifdef KERBEROS
    881 #ifdef CRYPT
    882 	(void)fprintf(stderr, "%s\n\t%s\n",
    883 	    "usage: rcp [-Kpx] [-k realm] f1 f2",
    884 	    "or: rcp [-Kprx] [-k realm] f1 ... fn directory");
    885 #else
    886 	(void)fprintf(stderr, "%s\n\t%s\n",
    887 	    "usage: rcp [-Kp] [-k realm] f1 f2",
    888 	    "or: rcp [-Kpr] [-k realm] f1 ... fn directory");
    889 #endif
    890 #else
    891 	(void)fprintf(stderr,
    892 	    "usage: rcp [-p] f1 f2; or: rcp [-pr] f1 ... fn directory\n");
    893 #endif
    894 	exit(1);
    895 	/* NOTREACHED */
    896 }
    897 
    898 #include <stdarg.h>
    899 
    900 #ifdef KERBEROS
    901 void
    902 oldw(const char *fmt, ...)
    903 {
    904 	va_list ap;
    905 
    906 	va_start(ap, fmt);
    907 	(void)fprintf(stderr, "rcp: ");
    908 	(void)vfprintf(stderr, fmt, ap);
    909 	(void)fprintf(stderr, ", using standard rcp\n");
    910 	va_end(ap);
    911 }
    912 #endif
    913 
    914 void
    915 run_err(const char *fmt, ...)
    916 {
    917 	static FILE *fp;
    918 	va_list ap;
    919 
    920 	++errs;
    921 	if (fp == NULL && !(fp = fdopen(rem, "w")))
    922 		return;
    923 
    924 	va_start(ap, fmt);
    925 
    926 	(void)fprintf(fp, "%c", 0x01);
    927 	(void)fprintf(fp, "rcp: ");
    928 	(void)vfprintf(fp, fmt, ap);
    929 	(void)fprintf(fp, "\n");
    930 	(void)fflush(fp);
    931 	va_end(ap);
    932 
    933 	if (!iamremote) {
    934 		va_start(ap, fmt);
    935 		vwarnx(fmt, ap);
    936 		va_end(ap);
    937 	}
    938 }
    939