1139965Simp/*-
21556Srgrimes * Copyright (c) 1983, 1990, 1992, 1993
31556Srgrimes *	The Regents of the University of California.  All rights reserved.
496196Sdes * Copyright (c) 2002 Networks Associates Technology, Inc.
596196Sdes * All rights reserved.
61556Srgrimes *
796196Sdes * Portions of this software were developed for the FreeBSD Project by
896196Sdes * ThinkSec AS and NAI Labs, the Security Research Division of Network
996196Sdes * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
1096196Sdes * ("CBOSS"), as part of the DARPA CHATS research program.
1196196Sdes *
121556Srgrimes * Redistribution and use in source and binary forms, with or without
131556Srgrimes * modification, are permitted provided that the following conditions
141556Srgrimes * are met:
151556Srgrimes * 1. Redistributions of source code must retain the above copyright
161556Srgrimes *    notice, this list of conditions and the following disclaimer.
171556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
181556Srgrimes *    notice, this list of conditions and the following disclaimer in the
191556Srgrimes *    documentation and/or other materials provided with the distribution.
201556Srgrimes * 4. Neither the name of the University nor the names of its contributors
211556Srgrimes *    may be used to endorse or promote products derived from this software
221556Srgrimes *    without specific prior written permission.
231556Srgrimes *
241556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
251556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
261556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
271556Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
281556Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
291556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
301556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
311556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
321556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
331556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
341556Srgrimes * SUCH DAMAGE.
351556Srgrimes */
361556Srgrimes
37114433Sobrien#if 0
381556Srgrimes#ifndef lint
3920420Sstevestatic char const copyright[] =
401556Srgrimes"@(#) Copyright (c) 1983, 1990, 1992, 1993\n\
411556Srgrimes	The Regents of the University of California.  All rights reserved.\n";
421556Srgrimes#endif /* not lint */
431556Srgrimes
441556Srgrimes#ifndef lint
4536149Scharnierstatic char sccsid[] = "@(#)rcp.c	8.2 (Berkeley) 4/2/94";
46104559Scharnier#endif /* not lint */
4736149Scharnier#endif
4899110Sobrien#include <sys/cdefs.h>
4999110Sobrien__FBSDID("$FreeBSD$");
501556Srgrimes
511556Srgrimes#include <sys/param.h>
521556Srgrimes#include <sys/stat.h>
531556Srgrimes#include <sys/time.h>
541556Srgrimes#include <sys/socket.h>
551556Srgrimes#include <netinet/in.h>
561556Srgrimes#include <netinet/in_systm.h>
571556Srgrimes#include <netinet/ip.h>
581556Srgrimes
591556Srgrimes#include <ctype.h>
601556Srgrimes#include <dirent.h>
611556Srgrimes#include <err.h>
621556Srgrimes#include <errno.h>
631556Srgrimes#include <fcntl.h>
6477462Simp#include <limits.h>
651556Srgrimes#include <netdb.h>
6696196Sdes#include <paths.h>
671556Srgrimes#include <pwd.h>
681556Srgrimes#include <signal.h>
69104549Stjr#include <stdint.h>
701556Srgrimes#include <stdio.h>
711556Srgrimes#include <stdlib.h>
721556Srgrimes#include <string.h>
731556Srgrimes#include <unistd.h>
741556Srgrimes
751556Srgrimes#include "extern.h"
761556Srgrimes
77101591Sume#define	OPTIONS "46dfprt"
781556Srgrimes
79241720Sedstatic struct passwd *pwd;
80241720Sedstatic u_short	port;
81241720Sedstatic uid_t	userid;
82241720Sedstatic int errs, rem;
83241720Sedint iamremote;
84241720Sedstatic int pflag, iamrecursive, targetshouldbedirectory;
85241720Sedstatic int family = PF_UNSPEC;
861556Srgrimes
8734898Smarkmstatic int argc_copy;
88114583Smarkmstatic const char **argv_copy;
8934898Smarkm
90114583Smarkmstatic char period[] = ".";
91114583Smarkm
921556Srgrimes#define	CMDNEEDS	64
93241720Sedstatic char cmd[CMDNEEDS];	/* must hold "rcp -r -p -d\0" */
941556Srgrimes
9590110Simpint	 response(void);
9690110Simpvoid	 rsource(char *, struct stat *);
9790110Simpvoid	 sink(int, char *[]);
9890110Simpvoid	 source(int, char *[]);
9990110Simpvoid	 tolocal(int, char *[]);
10090110Simpvoid	 toremote(char *, int, char *[]);
10190110Simpvoid	 usage(void);
1021556Srgrimes
1031556Srgrimesint
10490110Simpmain(int argc, char *argv[])
1051556Srgrimes{
1061556Srgrimes	struct servent *sp;
10748560Sbde	int ch, fflag, i, tflag;
108114583Smarkm	char *targ;
1091556Srgrimes
11034898Smarkm	/*
11134898Smarkm	 * Prepare for execing ourselves.
11234898Smarkm	 */
11334898Smarkm	argc_copy = argc + 1;
11434898Smarkm	argv_copy = malloc((argc_copy + 1) * sizeof(*argv_copy));
11534898Smarkm	if (argv_copy == NULL)
11634898Smarkm		err(1, "malloc");
11734898Smarkm	argv_copy[0] = argv[0];
11834898Smarkm	argv_copy[1] = "-K";
11948560Sbde	for (i = 1; i < argc; ++i) {
12034898Smarkm		argv_copy[i + 1] = strdup(argv[i]);
12134898Smarkm		if (argv_copy[i + 1] == NULL)
12234898Smarkm			errx(1, "strdup: out of memory");
12334898Smarkm	}
12434898Smarkm	argv_copy[argc + 1] = NULL;
12534898Smarkm
1261556Srgrimes	fflag = tflag = 0;
12724348Simp	while ((ch = getopt(argc, argv, OPTIONS)) != -1)
1281556Srgrimes		switch(ch) {			/* User-visible flags. */
129101591Sume		case '4':
130101591Sume			family = PF_INET;
131101591Sume			break;
132101591Sume
133101591Sume		case '6':
134101591Sume			family = PF_INET6;
135101591Sume			break;
136101591Sume
1371556Srgrimes		case 'p':
1381556Srgrimes			pflag = 1;
1391556Srgrimes			break;
1401556Srgrimes		case 'r':
1411556Srgrimes			iamrecursive = 1;
1421556Srgrimes			break;
1431556Srgrimes						/* Server options. */
1441556Srgrimes		case 'd':
1451556Srgrimes			targetshouldbedirectory = 1;
1461556Srgrimes			break;
1471556Srgrimes		case 'f':			/* "from" */
1481556Srgrimes			iamremote = 1;
1491556Srgrimes			fflag = 1;
1501556Srgrimes			break;
1511556Srgrimes		case 't':			/* "to" */
1521556Srgrimes			iamremote = 1;
1531556Srgrimes			tflag = 1;
1541556Srgrimes			break;
1551556Srgrimes		case '?':
1561556Srgrimes		default:
1571556Srgrimes			usage();
1581556Srgrimes		}
1591556Srgrimes	argc -= optind;
1601556Srgrimes	argv += optind;
1611556Srgrimes
162114583Smarkm	sp = getservbyname("shell", "tcp");
1631556Srgrimes	if (sp == NULL)
164114583Smarkm		errx(1, "shell/tcp: unknown service");
1651556Srgrimes	port = sp->s_port;
1661556Srgrimes
1671556Srgrimes	if ((pwd = getpwuid(userid = getuid())) == NULL)
1681556Srgrimes		errx(1, "unknown user %d", (int)userid);
1691556Srgrimes
1701556Srgrimes	rem = STDIN_FILENO;		/* XXX */
1711556Srgrimes
1721556Srgrimes	if (fflag) {			/* Follow "protocol", send data. */
1731556Srgrimes		(void)response();
1741556Srgrimes		(void)setuid(userid);
1751556Srgrimes		source(argc, argv);
1761556Srgrimes		exit(errs);
1771556Srgrimes	}
1781556Srgrimes
1791556Srgrimes	if (tflag) {			/* Receive data. */
1801556Srgrimes		(void)setuid(userid);
1811556Srgrimes		sink(argc, argv);
1821556Srgrimes		exit(errs);
1831556Srgrimes	}
1841556Srgrimes
1851556Srgrimes	if (argc < 2)
1861556Srgrimes		usage();
1871556Srgrimes	if (argc > 2)
1881556Srgrimes		targetshouldbedirectory = 1;
1891556Srgrimes
1901556Srgrimes	rem = -1;
1911556Srgrimes	/* Command to be executed on remote system using "rsh". */
1921556Srgrimes	(void)snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
1931556Srgrimes	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
1941556Srgrimes	    targetshouldbedirectory ? " -d" : "");
1951556Srgrimes
1961556Srgrimes	(void)signal(SIGPIPE, lostconn);
1971556Srgrimes
1987165Sjoerg	if ((targ = colon(argv[argc - 1])))	/* Dest is remote host. */
1991556Srgrimes		toremote(targ, argc, argv);
2001556Srgrimes	else {
2011556Srgrimes		tolocal(argc, argv);		/* Dest is local host. */
2021556Srgrimes		if (targetshouldbedirectory)
2031556Srgrimes			verifydir(argv[argc - 1]);
2041556Srgrimes	}
2051556Srgrimes	exit(errs);
2061556Srgrimes}
2071556Srgrimes
2081556Srgrimesvoid
20990110Simptoremote(char *targ, int argc, char *argv[])
2101556Srgrimes{
211121095Smarkm	int i, tos;
2121556Srgrimes	char *bp, *host, *src, *suser, *thost, *tuser;
2131556Srgrimes
2141556Srgrimes	*targ++ = 0;
2151556Srgrimes	if (*targ == 0)
216114583Smarkm		targ = period;
2171556Srgrimes
2187165Sjoerg	if ((thost = strchr(argv[argc - 1], '@'))) {
2191556Srgrimes		/* user@host */
2201556Srgrimes		*thost++ = 0;
2211556Srgrimes		tuser = argv[argc - 1];
2221556Srgrimes		if (*tuser == '\0')
2231556Srgrimes			tuser = NULL;
2241556Srgrimes		else if (!okname(tuser))
2251556Srgrimes			exit(1);
2261556Srgrimes	} else {
2271556Srgrimes		thost = argv[argc - 1];
2281556Srgrimes		tuser = NULL;
2291556Srgrimes	}
2301556Srgrimes
2311556Srgrimes	for (i = 0; i < argc - 1; i++) {
2321556Srgrimes		src = colon(argv[i]);
2331556Srgrimes		if (src) {			/* remote to remote */
2341556Srgrimes			*src++ = 0;
2351556Srgrimes			if (*src == 0)
236114583Smarkm				src = period;
2371556Srgrimes			host = strchr(argv[i], '@');
2381556Srgrimes			if (host) {
2391556Srgrimes				*host++ = 0;
2401556Srgrimes				suser = argv[i];
2411556Srgrimes				if (*suser == '\0')
2421556Srgrimes					suser = pwd->pw_name;
24377491Spirzyk				else if (!okname(suser)) {
24477491Spirzyk					++errs;
2451556Srgrimes					continue;
24677491Spirzyk				}
247121095Smarkm				if (asprintf(&bp,
2481556Srgrimes				    "%s %s -l %s -n %s %s '%s%s%s:%s'",
2491556Srgrimes				    _PATH_RSH, host, suser, cmd, src,
2501556Srgrimes				    tuser ? tuser : "", tuser ? "@" : "",
251121095Smarkm				    thost, targ) == -1)
252121095Smarkm					err(1, "asprintf");
2531556Srgrimes			} else
254121095Smarkm				if (asprintf(&bp,
2551556Srgrimes				    "exec %s %s -n %s %s '%s%s%s:%s'",
2561556Srgrimes				    _PATH_RSH, argv[i], cmd, src,
2571556Srgrimes				    tuser ? tuser : "", tuser ? "@" : "",
258121095Smarkm				    thost, targ) == -1)
259121095Smarkm					err(1, "asprintf");
2601556Srgrimes			(void)susystem(bp, userid);
2611556Srgrimes			(void)free(bp);
2621556Srgrimes		} else {			/* local to remote */
2631556Srgrimes			if (rem == -1) {
264121095Smarkm				if (asprintf(&bp, "%s -t %s", cmd, targ)
265121095Smarkm					== -1)
266121095Smarkm					err(1, "asprintf");
2671556Srgrimes				host = thost;
268105269Smarkm				rem = rcmd_af(&host, port,
269105269Smarkm				    pwd->pw_name,
270105269Smarkm				    tuser ? tuser : pwd->pw_name,
271105269Smarkm				    bp, 0, family);
2721556Srgrimes				if (rem < 0)
2731556Srgrimes					exit(1);
274101591Sume				if (family == PF_INET) {
275101591Sume					tos = IPTOS_THROUGHPUT;
276101591Sume					if (setsockopt(rem, IPPROTO_IP, IP_TOS,
277101591Sume					    &tos, sizeof(int)) < 0)
278101591Sume						warn("TOS (ignored)");
279101591Sume				}
2801556Srgrimes				if (response() < 0)
2811556Srgrimes					exit(1);
2821556Srgrimes				(void)free(bp);
2831556Srgrimes				(void)setuid(userid);
2841556Srgrimes			}
2851556Srgrimes			source(1, argv+i);
2861556Srgrimes		}
2871556Srgrimes	}
2881556Srgrimes}
2891556Srgrimes
2901556Srgrimesvoid
29190110Simptolocal(int argc, char *argv[])
2921556Srgrimes{
2931556Srgrimes	int i, len, tos;
2941556Srgrimes	char *bp, *host, *src, *suser;
2951556Srgrimes
2961556Srgrimes	for (i = 0; i < argc - 1; i++) {
2971556Srgrimes		if (!(src = colon(argv[i]))) {		/* Local to local. */
2981556Srgrimes			len = strlen(_PATH_CP) + strlen(argv[i]) +
2991556Srgrimes			    strlen(argv[argc - 1]) + 20;
3001556Srgrimes			if (!(bp = malloc(len)))
30199744Sdillon				err(1, "malloc");
3021556Srgrimes			(void)snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
30331633Swosch			    iamrecursive ? " -PR" : "", pflag ? " -p" : "",
3041556Srgrimes			    argv[i], argv[argc - 1]);
3051556Srgrimes			if (susystem(bp, userid))
3061556Srgrimes				++errs;
3071556Srgrimes			(void)free(bp);
3081556Srgrimes			continue;
3091556Srgrimes		}
3101556Srgrimes		*src++ = 0;
3111556Srgrimes		if (*src == 0)
312114583Smarkm			src = period;
3131556Srgrimes		if ((host = strchr(argv[i], '@')) == NULL) {
3141556Srgrimes			host = argv[i];
3151556Srgrimes			suser = pwd->pw_name;
3161556Srgrimes		} else {
3171556Srgrimes			*host++ = 0;
3181556Srgrimes			suser = argv[i];
3191556Srgrimes			if (*suser == '\0')
3201556Srgrimes				suser = pwd->pw_name;
32177491Spirzyk			else if (!okname(suser)) {
32277491Spirzyk				++errs;
3231556Srgrimes				continue;
32477491Spirzyk			}
3251556Srgrimes		}
3261556Srgrimes		len = strlen(src) + CMDNEEDS + 20;
3271556Srgrimes		if ((bp = malloc(len)) == NULL)
32899744Sdillon			err(1, "malloc");
3291556Srgrimes		(void)snprintf(bp, len, "%s -f %s", cmd, src);
330105269Smarkm		rem = rcmd_af(&host, port, pwd->pw_name, suser, bp, 0,
331101591Sume			    family);
3321556Srgrimes		(void)free(bp);
3331556Srgrimes		if (rem < 0) {
3341556Srgrimes			++errs;
3351556Srgrimes			continue;
3361556Srgrimes		}
3371556Srgrimes		(void)seteuid(userid);
338101591Sume		if (family == PF_INET) {
339101591Sume			tos = IPTOS_THROUGHPUT;
340101591Sume			if (setsockopt(rem, IPPROTO_IP, IP_TOS, &tos,
341101591Sume			    sizeof(int)) < 0)
342101591Sume				warn("TOS (ignored)");
343101591Sume		}
3441556Srgrimes		sink(1, argv + argc - 1);
3451556Srgrimes		(void)seteuid(0);
3461556Srgrimes		(void)close(rem);
3471556Srgrimes		rem = -1;
3481556Srgrimes	}
3491556Srgrimes}
3501556Srgrimes
3511556Srgrimesvoid
35290110Simpsource(int argc, char *argv[])
3531556Srgrimes{
3541556Srgrimes	struct stat stb;
3551556Srgrimes	static BUF buffer;
3561556Srgrimes	BUF *bp;
3571556Srgrimes	off_t i;
3581556Srgrimes	int amt, fd, haderr, indx, result;
3591556Srgrimes	char *last, *name, buf[BUFSIZ];
3601556Srgrimes
3611556Srgrimes	for (indx = 0; indx < argc; ++indx) {
36296196Sdes		name = argv[indx];
3631556Srgrimes		if ((fd = open(name, O_RDONLY, 0)) < 0)
3641556Srgrimes			goto syserr;
3651556Srgrimes		if (fstat(fd, &stb)) {
3661556Srgrimessyserr:			run_err("%s: %s", name, strerror(errno));
3671556Srgrimes			goto next;
3681556Srgrimes		}
3691556Srgrimes		switch (stb.st_mode & S_IFMT) {
3701556Srgrimes		case S_IFREG:
3711556Srgrimes			break;
3721556Srgrimes		case S_IFDIR:
3731556Srgrimes			if (iamrecursive) {
3741556Srgrimes				rsource(name, &stb);
3751556Srgrimes				goto next;
3761556Srgrimes			}
3771556Srgrimes			/* FALLTHROUGH */
3781556Srgrimes		default:
3791556Srgrimes			run_err("%s: not a regular file", name);
3801556Srgrimes			goto next;
3811556Srgrimes		}
3821556Srgrimes		if ((last = strrchr(name, '/')) == NULL)
3831556Srgrimes			last = name;
3841556Srgrimes		else
3851556Srgrimes			++last;
3861556Srgrimes		if (pflag) {
3871556Srgrimes			/*
3881556Srgrimes			 * Make it compatible with possible future
3891556Srgrimes			 * versions expecting microseconds.
3901556Srgrimes			 */
3911556Srgrimes			(void)snprintf(buf, sizeof(buf), "T%ld 0 %ld 0\n",
392205793Sed			    (long)stb.st_mtim.tv_sec,
393205793Sed			    (long)stb.st_atim.tv_sec);
3941556Srgrimes			(void)write(rem, buf, strlen(buf));
3951556Srgrimes			if (response() < 0)
3961556Srgrimes				goto next;
3971556Srgrimes		}
3981556Srgrimes#define	MODEMASK	(S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
399104549Stjr		(void)snprintf(buf, sizeof(buf), "C%04o %jd %s\n",
400104549Stjr		    stb.st_mode & MODEMASK, (intmax_t)stb.st_size, last);
4011556Srgrimes		(void)write(rem, buf, strlen(buf));
4021556Srgrimes		if (response() < 0)
4031556Srgrimes			goto next;
4041556Srgrimes		if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
405169848Scpercivanext:			if (fd >= 0)
406169848Scperciva				(void)close(fd);
4071556Srgrimes			continue;
4081556Srgrimes		}
4091556Srgrimes
4101556Srgrimes		/* Keep writing after an error so that we stay sync'd up. */
4111556Srgrimes		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
4121556Srgrimes			amt = bp->cnt;
4131556Srgrimes			if (i + amt > stb.st_size)
4141556Srgrimes				amt = stb.st_size - i;
4151556Srgrimes			if (!haderr) {
4161556Srgrimes				result = read(fd, bp->buf, amt);
4171556Srgrimes				if (result != amt)
4181556Srgrimes					haderr = result >= 0 ? EIO : errno;
4191556Srgrimes			}
4201556Srgrimes			if (haderr)
4211556Srgrimes				(void)write(rem, bp->buf, amt);
4221556Srgrimes			else {
4231556Srgrimes				result = write(rem, bp->buf, amt);
4241556Srgrimes				if (result != amt)
4251556Srgrimes					haderr = result >= 0 ? EIO : errno;
4261556Srgrimes			}
4271556Srgrimes		}
4281556Srgrimes		if (close(fd) && !haderr)
4291556Srgrimes			haderr = errno;
4301556Srgrimes		if (!haderr)
4311556Srgrimes			(void)write(rem, "", 1);
4321556Srgrimes		else
4331556Srgrimes			run_err("%s: %s", name, strerror(haderr));
4341556Srgrimes		(void)response();
4351556Srgrimes	}
4361556Srgrimes}
4371556Srgrimes
4381556Srgrimesvoid
43990110Simprsource(char *name, struct stat *statp)
4401556Srgrimes{
4411556Srgrimes	DIR *dirp;
4421556Srgrimes	struct dirent *dp;
44377462Simp	char *last, *vect[1], path[PATH_MAX];
4441556Srgrimes
4451556Srgrimes	if (!(dirp = opendir(name))) {
4461556Srgrimes		run_err("%s: %s", name, strerror(errno));
4471556Srgrimes		return;
4481556Srgrimes	}
4491556Srgrimes	last = strrchr(name, '/');
4501556Srgrimes	if (last == 0)
4511556Srgrimes		last = name;
4521556Srgrimes	else
4531556Srgrimes		last++;
4541556Srgrimes	if (pflag) {
4551556Srgrimes		(void)snprintf(path, sizeof(path), "T%ld 0 %ld 0\n",
456205793Sed		    (long)statp->st_mtim.tv_sec,
457205793Sed		    (long)statp->st_atim.tv_sec);
4581556Srgrimes		(void)write(rem, path, strlen(path));
4591556Srgrimes		if (response() < 0) {
4601556Srgrimes			closedir(dirp);
4611556Srgrimes			return;
4621556Srgrimes		}
4631556Srgrimes	}
4641556Srgrimes	(void)snprintf(path, sizeof(path),
4651556Srgrimes	    "D%04o %d %s\n", statp->st_mode & MODEMASK, 0, last);
4661556Srgrimes	(void)write(rem, path, strlen(path));
4671556Srgrimes	if (response() < 0) {
4681556Srgrimes		closedir(dirp);
4691556Srgrimes		return;
4701556Srgrimes	}
4717165Sjoerg	while ((dp = readdir(dirp))) {
4721556Srgrimes		if (dp->d_ino == 0)
4731556Srgrimes			continue;
4741556Srgrimes		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
4751556Srgrimes			continue;
47677462Simp		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path)) {
4771556Srgrimes			run_err("%s/%s: name too long", name, dp->d_name);
4781556Srgrimes			continue;
4791556Srgrimes		}
4801556Srgrimes		(void)snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
4811556Srgrimes		vect[0] = path;
4821556Srgrimes		source(1, vect);
4831556Srgrimes	}
4841556Srgrimes	(void)closedir(dirp);
4851556Srgrimes	(void)write(rem, "E\n", 2);
4861556Srgrimes	(void)response();
4871556Srgrimes}
4881556Srgrimes
4891556Srgrimesvoid
49090110Simpsink(int argc, char *argv[])
4911556Srgrimes{
4921556Srgrimes	static BUF buffer;
4931556Srgrimes	struct stat stb;
4941556Srgrimes	struct timeval tv[2];
4951556Srgrimes	enum { YES, NO, DISPLAYED } wrerr;
4961556Srgrimes	BUF *bp;
49746057Sdt	off_t i, j, size;
498114509Sobrien	int amt, exists, first, mask, mode, ofd, omode;
499114509Sobrien	size_t count;
50046057Sdt	int setimes, targisdir, wrerrno = 0;
501114583Smarkm	char ch, *cp, *np, *targ, *vect[1], buf[BUFSIZ], path[PATH_MAX];
502114583Smarkm	const char *why;
5031556Srgrimes
5041556Srgrimes#define	atime	tv[0]
5051556Srgrimes#define	mtime	tv[1]
5061556Srgrimes#define	SCREWUP(str)	{ why = str; goto screwup; }
5071556Srgrimes
5081556Srgrimes	setimes = targisdir = 0;
5091556Srgrimes	mask = umask(0);
5101556Srgrimes	if (!pflag)
5111556Srgrimes		(void)umask(mask);
5121556Srgrimes	if (argc != 1) {
5131556Srgrimes		run_err("ambiguous target");
5141556Srgrimes		exit(1);
5151556Srgrimes	}
5161556Srgrimes	targ = *argv;
5171556Srgrimes	if (targetshouldbedirectory)
5181556Srgrimes		verifydir(targ);
5191556Srgrimes	(void)write(rem, "", 1);
5201556Srgrimes	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
5211556Srgrimes		targisdir = 1;
5221556Srgrimes	for (first = 1;; first = 0) {
5231556Srgrimes		cp = buf;
5241556Srgrimes		if (read(rem, cp, 1) <= 0)
5251556Srgrimes			return;
5261556Srgrimes		if (*cp++ == '\n')
5271556Srgrimes			SCREWUP("unexpected <newline>");
5281556Srgrimes		do {
5291556Srgrimes			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
5301556Srgrimes				SCREWUP("lost connection");
5311556Srgrimes			*cp++ = ch;
5321556Srgrimes		} while (cp < &buf[BUFSIZ - 1] && ch != '\n');
5331556Srgrimes		*cp = 0;
5341556Srgrimes
5351556Srgrimes		if (buf[0] == '\01' || buf[0] == '\02') {
5361556Srgrimes			if (iamremote == 0)
5371556Srgrimes				(void)write(STDERR_FILENO,
5381556Srgrimes				    buf + 1, strlen(buf + 1));
5391556Srgrimes			if (buf[0] == '\02')
5401556Srgrimes				exit(1);
5411556Srgrimes			++errs;
5421556Srgrimes			continue;
5431556Srgrimes		}
5441556Srgrimes		if (buf[0] == 'E') {
5451556Srgrimes			(void)write(rem, "", 1);
5461556Srgrimes			return;
5471556Srgrimes		}
5481556Srgrimes
5491556Srgrimes		if (ch == '\n')
5501556Srgrimes			*--cp = 0;
5511556Srgrimes
5521556Srgrimes		cp = buf;
5531556Srgrimes		if (*cp == 'T') {
5541556Srgrimes			setimes++;
5551556Srgrimes			cp++;
55613978Spst			mtime.tv_sec = strtol(cp, &cp, 10);
55713978Spst			if (!cp || *cp++ != ' ')
5581556Srgrimes				SCREWUP("mtime.sec not delimited");
55913978Spst			mtime.tv_usec = strtol(cp, &cp, 10);
56013978Spst			if (!cp || *cp++ != ' ')
5611556Srgrimes				SCREWUP("mtime.usec not delimited");
56213978Spst			atime.tv_sec = strtol(cp, &cp, 10);
56313978Spst			if (!cp || *cp++ != ' ')
5641556Srgrimes				SCREWUP("atime.sec not delimited");
56513978Spst			atime.tv_usec = strtol(cp, &cp, 10);
56613978Spst			if (!cp || *cp++ != '\0')
5671556Srgrimes				SCREWUP("atime.usec not delimited");
5681556Srgrimes			(void)write(rem, "", 1);
5691556Srgrimes			continue;
5701556Srgrimes		}
5711556Srgrimes		if (*cp != 'C' && *cp != 'D') {
5721556Srgrimes			/*
5731556Srgrimes			 * Check for the case "rcp remote:foo\* local:bar".
5741556Srgrimes			 * In this case, the line "No match." can be returned
5751556Srgrimes			 * by the shell before the rcp command on the remote is
5761556Srgrimes			 * executed so the ^Aerror_message convention isn't
5771556Srgrimes			 * followed.
5781556Srgrimes			 */
5791556Srgrimes			if (first) {
5801556Srgrimes				run_err("%s", cp);
5811556Srgrimes				exit(1);
5821556Srgrimes			}
5831556Srgrimes			SCREWUP("expected control record");
5841556Srgrimes		}
5851556Srgrimes		mode = 0;
5861556Srgrimes		for (++cp; cp < buf + 5; cp++) {
5871556Srgrimes			if (*cp < '0' || *cp > '7')
5881556Srgrimes				SCREWUP("bad mode");
5891556Srgrimes			mode = (mode << 3) | (*cp - '0');
5901556Srgrimes		}
5911556Srgrimes		if (*cp++ != ' ')
5921556Srgrimes			SCREWUP("mode not delimited");
5931556Srgrimes
5941556Srgrimes		for (size = 0; isdigit(*cp);)
5951556Srgrimes			size = size * 10 + (*cp++ - '0');
5961556Srgrimes		if (*cp++ != ' ')
5971556Srgrimes			SCREWUP("size not delimited");
5981556Srgrimes		if (targisdir) {
599104559Scharnier			if (strlen(targ) + (*targ ? 1 : 0) + strlen(cp)
600104559Scharnier					>= sizeof(path)) {
601104559Scharnier				run_err("%s%s%s: name too long", targ,
602104559Scharnier					*targ ? "/" : "", cp);
603104559Scharnier				exit(1);
6041556Srgrimes			}
605104559Scharnier			(void)snprintf(path, sizeof(path), "%s%s%s", targ,
6061556Srgrimes			    *targ ? "/" : "", cp);
607104559Scharnier			np = path;
6081556Srgrimes		} else
6091556Srgrimes			np = targ;
6101556Srgrimes		exists = stat(np, &stb) == 0;
6111556Srgrimes		if (buf[0] == 'D') {
6121556Srgrimes			int mod_flag = pflag;
6131556Srgrimes			if (exists) {
6141556Srgrimes				if (!S_ISDIR(stb.st_mode)) {
6151556Srgrimes					errno = ENOTDIR;
6161556Srgrimes					goto bad;
6171556Srgrimes				}
6181556Srgrimes				if (pflag)
6191556Srgrimes					(void)chmod(np, mode);
6201556Srgrimes			} else {
6211556Srgrimes				/* Handle copying from a read-only directory */
6221556Srgrimes				mod_flag = 1;
6231556Srgrimes				if (mkdir(np, mode | S_IRWXU) < 0)
6241556Srgrimes					goto bad;
6251556Srgrimes			}
6261556Srgrimes			vect[0] = np;
6271556Srgrimes			sink(1, vect);
6281556Srgrimes			if (setimes) {
6291556Srgrimes				setimes = 0;
6301556Srgrimes				if (utimes(np, tv) < 0)
6311556Srgrimes				    run_err("%s: set times: %s",
6321556Srgrimes					np, strerror(errno));
6331556Srgrimes			}
6341556Srgrimes			if (mod_flag)
6351556Srgrimes				(void)chmod(np, mode);
6361556Srgrimes			continue;
6371556Srgrimes		}
6381556Srgrimes		omode = mode;
6391556Srgrimes		mode |= S_IWRITE;
6401556Srgrimes		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
6411556Srgrimesbad:			run_err("%s: %s", np, strerror(errno));
6421556Srgrimes			continue;
6431556Srgrimes		}
6441556Srgrimes		(void)write(rem, "", 1);
6451556Srgrimes		if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
6461556Srgrimes			(void)close(ofd);
6471556Srgrimes			continue;
6481556Srgrimes		}
6491556Srgrimes		cp = bp->buf;
6501556Srgrimes		wrerr = NO;
6511556Srgrimes		for (count = i = 0; i < size; i += BUFSIZ) {
6521556Srgrimes			amt = BUFSIZ;
6531556Srgrimes			if (i + amt > size)
6541556Srgrimes				amt = size - i;
6551556Srgrimes			count += amt;
6561556Srgrimes			do {
6571556Srgrimes				j = read(rem, cp, amt);
6581556Srgrimes				if (j <= 0) {
6591556Srgrimes					run_err("%s", j ? strerror(errno) :
6601556Srgrimes					    "dropped connection");
6611556Srgrimes					exit(1);
6621556Srgrimes				}
6631556Srgrimes				amt -= j;
6641556Srgrimes				cp += j;
6651556Srgrimes			} while (amt > 0);
6661556Srgrimes			if (count == bp->cnt) {
6671556Srgrimes				/* Keep reading so we stay sync'd up. */
6681556Srgrimes				if (wrerr == NO) {
6691556Srgrimes					j = write(ofd, bp->buf, count);
670114583Smarkm					if (j != (off_t)count) {
6711556Srgrimes						wrerr = YES;
6728855Srgrimes						wrerrno = j >= 0 ? EIO : errno;
6731556Srgrimes					}
6741556Srgrimes				}
6751556Srgrimes				count = 0;
6761556Srgrimes				cp = bp->buf;
6771556Srgrimes			}
6781556Srgrimes		}
6791556Srgrimes		if (count != 0 && wrerr == NO &&
680114583Smarkm		    (j = write(ofd, bp->buf, count)) != (off_t)count) {
6811556Srgrimes			wrerr = YES;
6828855Srgrimes			wrerrno = j >= 0 ? EIO : errno;
6831556Srgrimes		}
6841556Srgrimes		if (ftruncate(ofd, size)) {
6851556Srgrimes			run_err("%s: truncate: %s", np, strerror(errno));
6861556Srgrimes			wrerr = DISPLAYED;
6871556Srgrimes		}
6881556Srgrimes		if (pflag) {
6891556Srgrimes			if (exists || omode != mode)
6901556Srgrimes				if (fchmod(ofd, omode))
6911556Srgrimes					run_err("%s: set mode: %s",
6921556Srgrimes					    np, strerror(errno));
6931556Srgrimes		} else {
6941556Srgrimes			if (!exists && omode != mode)
6951556Srgrimes				if (fchmod(ofd, omode & ~mask))
6961556Srgrimes					run_err("%s: set mode: %s",
6971556Srgrimes					    np, strerror(errno));
6981556Srgrimes		}
6991556Srgrimes		(void)close(ofd);
7001556Srgrimes		(void)response();
7011556Srgrimes		if (setimes && wrerr == NO) {
7021556Srgrimes			setimes = 0;
7031556Srgrimes			if (utimes(np, tv) < 0) {
7041556Srgrimes				run_err("%s: set times: %s",
7051556Srgrimes				    np, strerror(errno));
7061556Srgrimes				wrerr = DISPLAYED;
7071556Srgrimes			}
7081556Srgrimes		}
7091556Srgrimes		switch(wrerr) {
7101556Srgrimes		case YES:
7111556Srgrimes			run_err("%s: %s", np, strerror(wrerrno));
7121556Srgrimes			break;
7131556Srgrimes		case NO:
7141556Srgrimes			(void)write(rem, "", 1);
7151556Srgrimes			break;
7161556Srgrimes		case DISPLAYED:
7171556Srgrimes			break;
7181556Srgrimes		}
7191556Srgrimes	}
7201556Srgrimesscrewup:
7211556Srgrimes	run_err("protocol error: %s", why);
7221556Srgrimes	exit(1);
7231556Srgrimes}
7241556Srgrimes
7251556Srgrimesint
72690110Simpresponse(void)
7271556Srgrimes{
7281556Srgrimes	char ch, *cp, resp, rbuf[BUFSIZ];
7291556Srgrimes
7301556Srgrimes	if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
7311556Srgrimes		lostconn(0);
7321556Srgrimes
7331556Srgrimes	cp = rbuf;
7341556Srgrimes	switch(resp) {
7351556Srgrimes	case 0:				/* ok */
7361556Srgrimes		return (0);
7371556Srgrimes	default:
7381556Srgrimes		*cp++ = resp;
7391556Srgrimes		/* FALLTHROUGH */
7401556Srgrimes	case 1:				/* error, followed by error msg */
7411556Srgrimes	case 2:				/* fatal error, "" */
7421556Srgrimes		do {
7431556Srgrimes			if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
7441556Srgrimes				lostconn(0);
7451556Srgrimes			*cp++ = ch;
7461556Srgrimes		} while (cp < &rbuf[BUFSIZ] && ch != '\n');
7471556Srgrimes
7481556Srgrimes		if (!iamremote)
7491556Srgrimes			(void)write(STDERR_FILENO, rbuf, cp - rbuf);
7501556Srgrimes		++errs;
7511556Srgrimes		if (resp == 1)
7521556Srgrimes			return (-1);
7531556Srgrimes		exit(1);
7541556Srgrimes	}
7551556Srgrimes	/* NOTREACHED */
7561556Srgrimes}
7571556Srgrimes
7581556Srgrimesvoid
75990110Simpusage(void)
7601556Srgrimes{
76126466Scharnier	(void)fprintf(stderr, "%s\n%s\n",
762141578Sru	    "usage: rcp [-46p] file1 file2",
763141578Sru	    "       rcp [-46pr] file ... directory");
7641556Srgrimes	exit(1);
7651556Srgrimes}
7661556Srgrimes
7671556Srgrimes#include <stdarg.h>
7681556Srgrimes
7691556Srgrimesvoid
7701556Srgrimesrun_err(const char *fmt, ...)
7711556Srgrimes{
7721556Srgrimes	static FILE *fp;
7731556Srgrimes	va_list ap;
7741556Srgrimes
7751556Srgrimes	++errs;
7761556Srgrimes	if (fp == NULL && !(fp = fdopen(rem, "w")))
7771556Srgrimes		return;
7781556Srgrimes	(void)fprintf(fp, "%c", 0x01);
7791556Srgrimes	(void)fprintf(fp, "rcp: ");
780104563Stjr	va_start(ap, fmt);
7811556Srgrimes	(void)vfprintf(fp, fmt, ap);
782104563Stjr	va_end(ap);
7831556Srgrimes	(void)fprintf(fp, "\n");
7841556Srgrimes	(void)fflush(fp);
7851556Srgrimes
786104563Stjr	if (!iamremote) {
787104563Stjr		va_start(ap, fmt);
7881556Srgrimes		vwarnx(fmt, ap);
789104563Stjr		va_end(ap);
790104563Stjr	}
7911556Srgrimes}
792