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