xref: /original-bsd/usr.bin/rdist/server.c (revision 0958d343)
1 /*
2  * Copyright (c) 1983 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)server.c	5.16 (Berkeley) 11/08/91";
10 #endif /* not lint */
11 
12 #include "defs.h"
13 
14 #define	ack() 	(void) write(rem, "\0\n", 2)
15 #define	err() 	(void) write(rem, "\1\n", 2)
16 
17 struct	linkbuf *ihead;		/* list of files with more than one link */
18 char	buf[BUFSIZ];		/* general purpose buffer */
19 char	target[BUFSIZ];		/* target/source directory name */
20 char	*tp;			/* pointer to end of target name */
21 char	*Tdest;			/* pointer to last T dest*/
22 int	catname;		/* cat name to target name */
23 char	*stp[32];		/* stack of saved tp's for directories */
24 int	oumask;			/* old umask for creating files */
25 
26 extern	FILE *lfp;		/* log file for mailing changes */
27 
28 void	cleanup();
29 struct	linkbuf *savelink();
30 
31 /*
32  * Server routine to read requests and process them.
33  * Commands are:
34  *	Tname	- Transmit file if out of date
35  *	Vname	- Verify if file out of date or not
36  *	Qname	- Query if file exists. Return mtime & size if it does.
37  */
38 server()
39 {
40 	char cmdbuf[BUFSIZ];
41 	register char *cp;
42 
43 	signal(SIGHUP, cleanup);
44 	signal(SIGINT, cleanup);
45 	signal(SIGQUIT, cleanup);
46 	signal(SIGTERM, cleanup);
47 	signal(SIGPIPE, cleanup);
48 
49 	rem = 0;
50 	oumask = umask(0);
51 	(void) sprintf(buf, "V%d\n", VERSION);
52 	(void) write(rem, buf, strlen(buf));
53 
54 	for (;;) {
55 		cp = cmdbuf;
56 		if (read(rem, cp, 1) <= 0)
57 			return;
58 		if (*cp++ == '\n') {
59 			error("server: expected control record\n");
60 			continue;
61 		}
62 		do {
63 			if (read(rem, cp, 1) != 1)
64 				cleanup();
65 		} while (*cp++ != '\n' && cp < &cmdbuf[BUFSIZ]);
66 		*--cp = '\0';
67 		cp = cmdbuf;
68 		switch (*cp++) {
69 		case 'T':  /* init target file/directory name */
70 			catname = 1;	/* target should be directory */
71 			goto dotarget;
72 
73 		case 't':  /* init target file/directory name */
74 			catname = 0;
75 		dotarget:
76 			if (exptilde(target, cp) == NULL)
77 				continue;
78 			tp = target;
79 			while (*tp)
80 				tp++;
81 			ack();
82 			continue;
83 
84 		case 'R':  /* Transfer a regular file. */
85 			recvf(cp, S_IFREG);
86 			continue;
87 
88 		case 'D':  /* Transfer a directory. */
89 			recvf(cp, S_IFDIR);
90 			continue;
91 
92 		case 'K':  /* Transfer symbolic link. */
93 			recvf(cp, S_IFLNK);
94 			continue;
95 
96 		case 'k':  /* Transfer hard link. */
97 			hardlink(cp);
98 			continue;
99 
100 		case 'E':  /* End. (of directory) */
101 			*tp = '\0';
102 			if (catname <= 0) {
103 				error("server: too many 'E's\n");
104 				continue;
105 			}
106 			tp = stp[--catname];
107 			*tp = '\0';
108 			ack();
109 			continue;
110 
111 		case 'C':  /* Clean. Cleanup a directory */
112 			clean(cp);
113 			continue;
114 
115 		case 'Q':  /* Query. Does the file/directory exist? */
116 			query(cp);
117 			continue;
118 
119 		case 'S':  /* Special. Execute commands */
120 			dospecial(cp);
121 			continue;
122 
123 #ifdef notdef
124 		/*
125 		 * These entries are reserved but not currently used.
126 		 * The intent is to allow remote hosts to have master copies.
127 		 * Currently, only the host rdist runs on can have masters.
128 		 */
129 		case 'X':  /* start a new list of files to exclude */
130 			except = bp = NULL;
131 		case 'x':  /* add name to list of files to exclude */
132 			if (*cp == '\0') {
133 				ack();
134 				continue;
135 			}
136 			if (*cp == '~') {
137 				if (exptilde(buf, cp) == NULL)
138 					continue;
139 				cp = buf;
140 			}
141 			if (bp == NULL)
142 				except = bp = expand(makeblock(NAME, cp), E_VARS);
143 			else
144 				bp->b_next = expand(makeblock(NAME, cp), E_VARS);
145 			while (bp->b_next != NULL)
146 				bp = bp->b_next;
147 			ack();
148 			continue;
149 
150 		case 'I':  /* Install. Transfer file if out of date. */
151 			opts = 0;
152 			while (*cp >= '0' && *cp <= '7')
153 				opts = (opts << 3) | (*cp++ - '0');
154 			if (*cp++ != ' ') {
155 				error("server: options not delimited\n");
156 				return;
157 			}
158 			install(cp, opts);
159 			continue;
160 
161 		case 'L':  /* Log. save message in log file */
162 			log(lfp, cp);
163 			continue;
164 #endif
165 
166 		case '\1':
167 			nerrs++;
168 			continue;
169 
170 		case '\2':
171 			return;
172 
173 		default:
174 			error("server: unknown command '%s'\n", cp);
175 		case '\0':
176 			continue;
177 		}
178 	}
179 }
180 
181 /*
182  * Update the file(s) if they are different.
183  * destdir = 1 if destination should be a directory
184  * (i.e., more than one source is being copied to the same destination).
185  */
186 install(src, dest, destdir, opts)
187 	char *src, *dest;
188 	int destdir, opts;
189 {
190 	char *rname;
191 	char destcopy[BUFSIZ];
192 
193 	if (dest == NULL) {
194 		opts &= ~WHOLE; /* WHOLE mode only useful if renaming */
195 		dest = src;
196 	}
197 
198 	if (nflag || debug) {
199 		printf("%s%s%s%s%s %s %s\n", opts & VERIFY ? "verify":"install",
200 			opts & WHOLE ? " -w" : "",
201 			opts & YOUNGER ? " -y" : "",
202 			opts & COMPARE ? " -b" : "",
203 			opts & REMOVE ? " -R" : "", src, dest);
204 		if (nflag)
205 			return;
206 	}
207 
208 	rname = exptilde(target, src);
209 	if (rname == NULL)
210 		return;
211 	tp = target;
212 	while (*tp)
213 		tp++;
214 	/*
215 	 * If we are renaming a directory and we want to preserve
216 	 * the directory heirarchy (-w), we must strip off the leading
217 	 * directory name and preserve the rest.
218 	 */
219 	if (opts & WHOLE) {
220 		while (*rname == '/')
221 			rname++;
222 		destdir = 1;
223 	} else {
224 		rname = rindex(target, '/');
225 		if (rname == NULL)
226 			rname = target;
227 		else
228 			rname++;
229 	}
230 	if (debug)
231 		printf("target = %s, rname = %s\n", target, rname);
232 	/*
233 	 * Pass the destination file/directory name to remote.
234 	 */
235 	(void) sprintf(buf, "%c%s\n", destdir ? 'T' : 't', dest);
236 	if (debug)
237 		printf("buf = %s", buf);
238 	(void) write(rem, buf, strlen(buf));
239 	if (response() < 0)
240 		return;
241 
242 	if (destdir) {
243 		strcpy(destcopy, dest);
244 		Tdest = destcopy;
245 	}
246 	sendf(rname, opts);
247 	Tdest = 0;
248 }
249 
250 #define protoname() (pw ? pw->pw_name : user)
251 #define protogroup() (gr ? gr->gr_name : group)
252 /*
253  * Transfer the file or directory in target[].
254  * rname is the name of the file on the remote host.
255  */
256 sendf(rname, opts)
257 	char *rname;
258 	int opts;
259 {
260 	register struct subcmd *sc;
261 	struct stat stb;
262 	int sizerr, f, u, len;
263 	off_t i;
264 	DIR *d;
265 	struct direct *dp;
266 	char *otp, *cp;
267 	extern struct subcmd *subcmds;
268 	static char user[15], group[15];
269 
270 	if (debug)
271 		printf("sendf(%s, %x)\n", rname, opts);
272 
273 	if (except(target))
274 		return;
275 	if ((opts & FOLLOW ? stat(target, &stb) : lstat(target, &stb)) < 0) {
276 		error("%s: %s\n", target, strerror(errno));
277 		return;
278 	}
279 	if ((u = update(rname, opts, &stb)) == 0) {
280 		if ((stb.st_mode & S_IFMT) == S_IFREG && stb.st_nlink > 1)
281 			(void) savelink(&stb);
282 		return;
283 	}
284 
285 	if (pw == NULL || pw->pw_uid != stb.st_uid)
286 		if ((pw = getpwuid(stb.st_uid)) == NULL) {
287 			log(lfp, "%s: no password entry for uid %d \n",
288 				target, stb.st_uid);
289 			pw = NULL;
290 			sprintf(user, ":%d", stb.st_uid);
291 		}
292 	if (gr == NULL || gr->gr_gid != stb.st_gid)
293 		if ((gr = getgrgid(stb.st_gid)) == NULL) {
294 			log(lfp, "%s: no name for group %d\n",
295 				target, stb.st_gid);
296 			gr = NULL;
297 			sprintf(group, ":%d", stb.st_gid);
298 		}
299 	if (u == 1) {
300 		if (opts & VERIFY) {
301 			log(lfp, "need to install: %s\n", target);
302 			goto dospecial;
303 		}
304 		log(lfp, "installing: %s\n", target);
305 		opts &= ~(COMPARE|REMOVE);
306 	}
307 
308 	switch (stb.st_mode & S_IFMT) {
309 	case S_IFDIR:
310 		if ((d = opendir(target)) == NULL) {
311 			error("%s: %s\n", target, strerror(errno));
312 			return;
313 		}
314 		(void) sprintf(buf, "D%o %04o 0 0 %s %s %s\n", opts,
315 			stb.st_mode & 07777, protoname(), protogroup(), rname);
316 		if (debug)
317 			printf("buf = %s", buf);
318 		(void) write(rem, buf, strlen(buf));
319 		if (response() < 0) {
320 			closedir(d);
321 			return;
322 		}
323 
324 		if (opts & REMOVE)
325 			rmchk(opts);
326 
327 		otp = tp;
328 		len = tp - target;
329 		while (dp = readdir(d)) {
330 			if (!strcmp(dp->d_name, ".") ||
331 			    !strcmp(dp->d_name, ".."))
332 				continue;
333 			if (len + 1 + strlen(dp->d_name) >= BUFSIZ - 1) {
334 				error("%s/%s: Name too long\n", target,
335 					dp->d_name);
336 				continue;
337 			}
338 			tp = otp;
339 			*tp++ = '/';
340 			cp = dp->d_name;
341 			while (*tp++ = *cp++)
342 				;
343 			tp--;
344 			sendf(dp->d_name, opts);
345 		}
346 		closedir(d);
347 		(void) write(rem, "E\n", 2);
348 		(void) response();
349 		tp = otp;
350 		*tp = '\0';
351 		return;
352 
353 	case S_IFLNK:
354 		if (u != 1)
355 			opts |= COMPARE;
356 		if (stb.st_nlink > 1) {
357 			struct linkbuf *lp;
358 
359 			if ((lp = savelink(&stb)) != NULL) {
360 				/* install link */
361 				if (*lp->target == 0)
362 				(void) sprintf(buf, "k%o %s %s\n", opts,
363 					lp->pathname, rname);
364 				else
365 				(void) sprintf(buf, "k%o %s/%s %s\n", opts,
366 					lp->target, lp->pathname, rname);
367 				if (debug)
368 					printf("buf = %s", buf);
369 				(void) write(rem, buf, strlen(buf));
370 				(void) response();
371 				return;
372 			}
373 		}
374 		(void) sprintf(buf, "K%o %o %ld %ld %s %s %s\n", opts,
375 			stb.st_mode & 07777, stb.st_size, stb.st_mtime,
376 			protoname(), protogroup(), rname);
377 		if (debug)
378 			printf("buf = %s", buf);
379 		(void) write(rem, buf, strlen(buf));
380 		if (response() < 0)
381 			return;
382 		sizerr = (readlink(target, buf, BUFSIZ) != stb.st_size);
383 		(void) write(rem, buf, stb.st_size);
384 		if (debug)
385 			printf("readlink = %.*s\n", (int)stb.st_size, buf);
386 		goto done;
387 
388 	case S_IFREG:
389 		break;
390 
391 	default:
392 		error("%s: not a file or directory\n", target);
393 		return;
394 	}
395 
396 	if (u == 2) {
397 		if (opts & VERIFY) {
398 			log(lfp, "need to update: %s\n", target);
399 			goto dospecial;
400 		}
401 		log(lfp, "updating: %s\n", target);
402 	}
403 
404 	if (stb.st_nlink > 1) {
405 		struct linkbuf *lp;
406 
407 		if ((lp = savelink(&stb)) != NULL) {
408 			/* install link */
409 			if (*lp->target == 0)
410 			(void) sprintf(buf, "k%o %s %s\n", opts,
411 				lp->pathname, rname);
412 			else
413 			(void) sprintf(buf, "k%o %s/%s %s\n", opts,
414 				lp->target, lp->pathname, rname);
415 			if (debug)
416 				printf("buf = %s", buf);
417 			(void) write(rem, buf, strlen(buf));
418 			(void) response();
419 			return;
420 		}
421 	}
422 
423 	if ((f = open(target, 0)) < 0) {
424 		error("%s: %s\n", target, strerror(errno));
425 		return;
426 	}
427 	(void) sprintf(buf, "R%o %o %ld %ld %s %s %s\n", opts,
428 		stb.st_mode & 07777, stb.st_size, stb.st_mtime,
429 		protoname(), protogroup(), rname);
430 	if (debug)
431 		printf("buf = %s", buf);
432 	(void) write(rem, buf, strlen(buf));
433 	if (response() < 0) {
434 		(void) close(f);
435 		return;
436 	}
437 	sizerr = 0;
438 	for (i = 0; i < stb.st_size; i += BUFSIZ) {
439 		int amt = BUFSIZ;
440 		if (i + amt > stb.st_size)
441 			amt = stb.st_size - i;
442 		if (sizerr == 0 && read(f, buf, amt) != amt)
443 			sizerr = 1;
444 		(void) write(rem, buf, amt);
445 	}
446 	(void) close(f);
447 done:
448 	if (sizerr) {
449 		error("%s: file changed size\n", target);
450 		err();
451 	} else
452 		ack();
453 	f = response();
454 	if (f < 0 || f == 0 && (opts & COMPARE))
455 		return;
456 dospecial:
457 	for (sc = subcmds; sc != NULL; sc = sc->sc_next) {
458 		if (sc->sc_type != SPECIAL)
459 			continue;
460 		if (sc->sc_args != NULL && !inlist(sc->sc_args, target))
461 			continue;
462 		log(lfp, "special \"%s\"\n", sc->sc_name);
463 		if (opts & VERIFY)
464 			continue;
465 		(void) sprintf(buf, "SFILE=%s;%s\n", target, sc->sc_name);
466 		if (debug)
467 			printf("buf = %s", buf);
468 		(void) write(rem, buf, strlen(buf));
469 		while (response() > 0)
470 			;
471 	}
472 }
473 
474 struct linkbuf *
475 savelink(stp)
476 	struct stat *stp;
477 {
478 	struct linkbuf *lp;
479 	int found = 0;
480 
481 	for (lp = ihead; lp != NULL; lp = lp->nextp)
482 		if (lp->inum == stp->st_ino && lp->devnum == stp->st_dev) {
483 			lp->count--;
484 			return(lp);
485 		}
486 	lp = (struct linkbuf *) malloc(sizeof(*lp));
487 	if (lp == NULL)
488 		log(lfp, "out of memory, link information lost\n");
489 	else {
490 		lp->nextp = ihead;
491 		ihead = lp;
492 		lp->inum = stp->st_ino;
493 		lp->devnum = stp->st_dev;
494 		lp->count = stp->st_nlink - 1;
495 		strcpy(lp->pathname, target);
496 		if (Tdest)
497 			strcpy(lp->target, Tdest);
498 		else
499 			*lp->target = 0;
500 	}
501 	return(NULL);
502 }
503 
504 /*
505  * Check to see if file needs to be updated on the remote machine.
506  * Returns 0 if no update, 1 if remote doesn't exist, 2 if out of date
507  * and 3 if comparing binaries to determine if out of date.
508  */
509 update(rname, opts, stp)
510 	char *rname;
511 	int opts;
512 	struct stat *stp;
513 {
514 	register char *cp, *s;
515 	register off_t size;
516 	register time_t mtime;
517 
518 	if (debug)
519 		printf("update(%s, %x, %x)\n", rname, opts, stp);
520 
521 	/*
522 	 * Check to see if the file exists on the remote machine.
523 	 */
524 	(void) sprintf(buf, "Q%s\n", rname);
525 	if (debug)
526 		printf("buf = %s", buf);
527 	(void) write(rem, buf, strlen(buf));
528 again:
529 	cp = s = buf;
530 	do {
531 		if (read(rem, cp, 1) != 1)
532 			lostconn();
533 	} while (*cp++ != '\n' && cp < &buf[BUFSIZ]);
534 
535 	switch (*s++) {
536 	case 'Y':
537 		break;
538 
539 	case 'N':  /* file doesn't exist so install it */
540 		return(1);
541 
542 	case '\1':
543 		nerrs++;
544 		if (*s != '\n') {
545 			if (!iamremote) {
546 				fflush(stdout);
547 				(void) write(2, s, cp - s);
548 			}
549 			if (lfp != NULL)
550 				(void) fwrite(s, 1, cp - s, lfp);
551 		}
552 		return(0);
553 
554 	case '\3':
555 		*--cp = '\0';
556 		if (lfp != NULL)
557 			log(lfp, "update: note: %s\n", s);
558 		goto again;
559 
560 	default:
561 		*--cp = '\0';
562 		error("update: unexpected response '%s'\n", s);
563 		return(0);
564 	}
565 
566 	if (*s == '\n')
567 		return(2);
568 
569 	if (opts & COMPARE)
570 		return(3);
571 
572 	size = 0;
573 	while (isdigit(*s))
574 		size = size * 10 + (*s++ - '0');
575 	if (*s++ != ' ') {
576 		error("update: size not delimited\n");
577 		return(0);
578 	}
579 	mtime = 0;
580 	while (isdigit(*s))
581 		mtime = mtime * 10 + (*s++ - '0');
582 	if (*s != '\n') {
583 		error("update: mtime not delimited\n");
584 		return(0);
585 	}
586 	/*
587 	 * File needs to be updated?
588 	 */
589 	if (opts & YOUNGER) {
590 		if (stp->st_mtime == mtime)
591 			return(0);
592 		if (stp->st_mtime < mtime) {
593 			log(lfp, "Warning: %s: remote copy is newer\n", target);
594 			return(0);
595 		}
596 	} else if (stp->st_mtime == mtime && stp->st_size == size)
597 		return(0);
598 	return(2);
599 }
600 
601 /*
602  * Query. Check to see if file exists. Return one of the following:
603  *	N\n		- doesn't exist
604  *	Ysize mtime\n	- exists and its a regular file (size & mtime of file)
605  *	Y\n		- exists and its a directory or symbolic link
606  *	^Aerror message\n
607  */
608 query(name)
609 	char *name;
610 {
611 	struct stat stb;
612 
613 	if (catname)
614 		(void) sprintf(tp, "/%s", name);
615 
616 	if (lstat(target, &stb) < 0) {
617 		if (errno == ENOENT)
618 			(void) write(rem, "N\n", 2);
619 		else
620 			error("%s:%s: %s\n", host, target, strerror(errno));
621 		*tp = '\0';
622 		return;
623 	}
624 
625 	switch (stb.st_mode & S_IFMT) {
626 	case S_IFREG:
627 		(void) sprintf(buf, "Y%ld %ld\n", stb.st_size, stb.st_mtime);
628 		(void) write(rem, buf, strlen(buf));
629 		break;
630 
631 	case S_IFLNK:
632 	case S_IFDIR:
633 		(void) write(rem, "Y\n", 2);
634 		break;
635 
636 	default:
637 		error("%s: not a file or directory\n", name);
638 		break;
639 	}
640 	*tp = '\0';
641 }
642 
643 recvf(cmd, type)
644 	char *cmd;
645 	int type;
646 {
647 	register char *cp;
648 	int f, mode, opts, wrerr, olderrno;
649 	off_t i, size;
650 	time_t mtime;
651 	struct stat stb;
652 	struct timeval tvp[2];
653 	char *owner, *group;
654 	char new[BUFSIZ];
655 	extern char *tempname;
656 
657 	cp = cmd;
658 	opts = 0;
659 	while (*cp >= '0' && *cp <= '7')
660 		opts = (opts << 3) | (*cp++ - '0');
661 	if (*cp++ != ' ') {
662 		error("recvf: options not delimited\n");
663 		return;
664 	}
665 	mode = 0;
666 	while (*cp >= '0' && *cp <= '7')
667 		mode = (mode << 3) | (*cp++ - '0');
668 	if (*cp++ != ' ') {
669 		error("recvf: mode not delimited\n");
670 		return;
671 	}
672 	size = 0;
673 	while (isdigit(*cp))
674 		size = size * 10 + (*cp++ - '0');
675 	if (*cp++ != ' ') {
676 		error("recvf: size not delimited\n");
677 		return;
678 	}
679 	mtime = 0;
680 	while (isdigit(*cp))
681 		mtime = mtime * 10 + (*cp++ - '0');
682 	if (*cp++ != ' ') {
683 		error("recvf: mtime not delimited\n");
684 		return;
685 	}
686 	owner = cp;
687 	while (*cp && *cp != ' ')
688 		cp++;
689 	if (*cp != ' ') {
690 		error("recvf: owner name not delimited\n");
691 		return;
692 	}
693 	*cp++ = '\0';
694 	group = cp;
695 	while (*cp && *cp != ' ')
696 		cp++;
697 	if (*cp != ' ') {
698 		error("recvf: group name not delimited\n");
699 		return;
700 	}
701 	*cp++ = '\0';
702 
703 	if (type == S_IFDIR) {
704 		if (catname >= sizeof(stp)) {
705 			error("%s:%s: too many directory levels\n",
706 				host, target);
707 			return;
708 		}
709 		stp[catname] = tp;
710 		if (catname++) {
711 			*tp++ = '/';
712 			while (*tp++ = *cp++)
713 				;
714 			tp--;
715 		}
716 		if (opts & VERIFY) {
717 			ack();
718 			return;
719 		}
720 		if (lstat(target, &stb) == 0) {
721 			if (ISDIR(stb.st_mode)) {
722 				if ((stb.st_mode & 07777) == mode) {
723 					ack();
724 					return;
725 				}
726 				buf[0] = '\0';
727 				(void) sprintf(buf + 1,
728 					"%s: Warning: remote mode %o != local mode %o\n",
729 					target, stb.st_mode & 07777, mode);
730 				(void) write(rem, buf, strlen(buf + 1) + 1);
731 				return;
732 			}
733 			errno = ENOTDIR;
734 		} else if (errno == ENOENT && (mkdir(target, mode) == 0 ||
735 		    chkparent(target) == 0 && mkdir(target, mode) == 0)) {
736 			if (fchog(-1, target, owner, group, mode) == 0)
737 				ack();
738 			return;
739 		}
740 		error("%s:%s: %s\n", host, target, strerror(errno));
741 		tp = stp[--catname];
742 		*tp = '\0';
743 		return;
744 	}
745 
746 	if (catname)
747 		(void) sprintf(tp, "/%s", cp);
748 	cp = rindex(target, '/');
749 	if (cp == NULL)
750 		strcpy(new, tempname);
751 	else if (cp == target)
752 		(void) sprintf(new, "/%s", tempname);
753 	else {
754 		*cp = '\0';
755 		(void) sprintf(new, "%s/%s", target, tempname);
756 		*cp = '/';
757 	}
758 
759 	if (type == S_IFLNK) {
760 		int j;
761 
762 		ack();
763 		cp = buf;
764 		for (i = 0; i < size; i += j) {
765 			if ((j = read(rem, cp, size - i)) <= 0)
766 				cleanup();
767 			cp += j;
768 		}
769 		*cp = '\0';
770 		if (response() < 0) {
771 			err();
772 			return;
773 		}
774 		if (symlink(buf, new) < 0) {
775 			if (errno != ENOENT || chkparent(new) < 0 ||
776 			    symlink(buf, new) < 0)
777 				goto badnew1;
778 		}
779 		mode &= 0777;
780 		if (opts & COMPARE) {
781 			char tbuf[BUFSIZ];
782 
783 			if ((i = readlink(target, tbuf, BUFSIZ)) >= 0 &&
784 			    i == size && strncmp(buf, tbuf, size) == 0) {
785 				(void) unlink(new);
786 				ack();
787 				return;
788 			}
789 			if (opts & VERIFY)
790 				goto differ;
791 		}
792 		goto fixup;
793 	}
794 
795 	if ((f = creat(new, mode)) < 0) {
796 		if (errno != ENOENT || chkparent(new) < 0 ||
797 		    (f = creat(new, mode)) < 0)
798 			goto badnew1;
799 	}
800 
801 	ack();
802 	wrerr = 0;
803 	for (i = 0; i < size; i += BUFSIZ) {
804 		int amt = BUFSIZ;
805 
806 		cp = buf;
807 		if (i + amt > size)
808 			amt = size - i;
809 		do {
810 			int j = read(rem, cp, amt);
811 
812 			if (j <= 0) {
813 				(void) close(f);
814 				(void) unlink(new);
815 				cleanup();
816 			}
817 			amt -= j;
818 			cp += j;
819 		} while (amt > 0);
820 		amt = BUFSIZ;
821 		if (i + amt > size)
822 			amt = size - i;
823 		if (wrerr == 0 && write(f, buf, amt) != amt) {
824 			olderrno = errno;
825 			wrerr++;
826 		}
827 	}
828 	if (response() < 0) {
829 		err();
830 		goto badnew2;
831 	}
832 	if (wrerr)
833 		goto badnew1;
834 	if (opts & COMPARE) {
835 		FILE *f1, *f2;
836 		int c;
837 
838 		if ((f1 = fopen(target, "r")) == NULL)
839 			goto badtarget;
840 		if ((f2 = fopen(new, "r")) == NULL) {
841 badnew1:		error("%s:%s: %s\n", host, new, strerror(errno));
842 			goto badnew2;
843 		}
844 		while ((c = getc(f1)) == getc(f2))
845 			if (c == EOF) {
846 				(void) fclose(f1);
847 				(void) fclose(f2);
848 				ack();
849 				goto badnew2;
850 			}
851 		(void) fclose(f1);
852 		(void) fclose(f2);
853 		if (opts & VERIFY) {
854 differ:			buf[0] = '\0';
855 			(void) sprintf(buf + 1, "need to update: %s\n",target);
856 			(void) write(rem, buf, strlen(buf + 1) + 1);
857 			goto badnew2;
858 		}
859 	}
860 
861 	/*
862 	 * Set last modified time
863 	 */
864 	tvp[0].tv_sec = time(0);
865 	tvp[0].tv_usec = 0;
866 	tvp[1].tv_sec = mtime;
867 	tvp[1].tv_usec = 0;
868 	if (utimes(new, tvp) < 0)
869 		note("%s: utimes failed %s: %s\n", host, new, strerror(errno));
870 
871 	if (fchog(f, new, owner, group, mode) < 0) {
872 badnew2:	(void) close(f);
873 		(void) unlink(new);
874 		return;
875 	}
876 	(void) close(f);
877 
878 fixup:	if (rename(new, target) < 0) {
879 badtarget:	error("%s:%s: %s\n", host, target, strerror(errno));
880 		(void) unlink(new);
881 		return;
882 	}
883 
884 	if (opts & COMPARE) {
885 		buf[0] = '\0';
886 		(void) sprintf(buf + 1, "updated %s\n", target);
887 		(void) write(rem, buf, strlen(buf + 1) + 1);
888 	} else
889 		ack();
890 }
891 
892 /*
893  * Creat a hard link to existing file.
894  */
895 hardlink(cmd)
896 	char *cmd;
897 {
898 	register char *cp;
899 	struct stat stb;
900 	char *oldname;
901 	int opts, exists = 0;
902 
903 	cp = cmd;
904 	opts = 0;
905 	while (*cp >= '0' && *cp <= '7')
906 		opts = (opts << 3) | (*cp++ - '0');
907 	if (*cp++ != ' ') {
908 		error("hardlink: options not delimited\n");
909 		return;
910 	}
911 	oldname = cp;
912 	while (*cp && *cp != ' ')
913 		cp++;
914 	if (*cp != ' ') {
915 		error("hardlink: oldname name not delimited\n");
916 		return;
917 	}
918 	*cp++ = '\0';
919 
920 	if (catname) {
921 		(void) sprintf(tp, "/%s", cp);
922 	}
923 	if (lstat(target, &stb) == 0) {
924 		int mode = stb.st_mode & S_IFMT;
925 		if (mode != S_IFREG && mode != S_IFLNK) {
926 			error("%s:%s: not a regular file\n", host, target);
927 			return;
928 		}
929 		exists = 1;
930 	}
931 	if (chkparent(target) < 0 ) {
932 		error("%s:%s: %s (no parent)\n",
933 			host, target, strerror(errno));
934 		return;
935 	}
936 	if (exists && (unlink(target) < 0)) {
937 		error("%s:%s: %s (unlink)\n",
938 			host, target, strerror(errno));
939 		return;
940 	}
941 	if (link(oldname, target) < 0) {
942 		error("%s:can't link %s to %s\n",
943 			host, target, oldname);
944 		return;
945 	}
946 	ack();
947 }
948 
949 /*
950  * Check to see if parent directory exists and create one if not.
951  */
952 chkparent(name)
953 	char *name;
954 {
955 	register char *cp;
956 	struct stat stb;
957 
958 	cp = rindex(name, '/');
959 	if (cp == NULL || cp == name)
960 		return(0);
961 	*cp = '\0';
962 	if (lstat(name, &stb) < 0) {
963 		if (errno == ENOENT && chkparent(name) >= 0 &&
964 		    mkdir(name, 0777 & ~oumask) >= 0) {
965 			*cp = '/';
966 			return(0);
967 		}
968 	} else if (ISDIR(stb.st_mode)) {
969 		*cp = '/';
970 		return(0);
971 	}
972 	*cp = '/';
973 	return(-1);
974 }
975 
976 /*
977  * Change owner, group and mode of file.
978  */
979 fchog(fd, file, owner, group, mode)
980 	int fd;
981 	char *file, *owner, *group;
982 	int mode;
983 {
984 	register int i;
985 	int uid, gid;
986 	extern char user[];
987 	extern int userid;
988 
989 	uid = userid;
990 	if (userid == 0) {
991 		if (*owner == ':') {
992 			uid = atoi(owner + 1);
993 		} else if (pw == NULL || strcmp(owner, pw->pw_name) != 0) {
994 			if ((pw = getpwnam(owner)) == NULL) {
995 				if (mode & 04000) {
996 					note("%s:%s: unknown login name, clearing setuid",
997 						host, owner);
998 					mode &= ~04000;
999 					uid = 0;
1000 				}
1001 			} else
1002 				uid = pw->pw_uid;
1003 		} else
1004 			uid = pw->pw_uid;
1005 		if (*group == ':') {
1006 			gid = atoi(group + 1);
1007 			goto ok;
1008 		}
1009 	} else if ((mode & 04000) && strcmp(user, owner) != 0)
1010 		mode &= ~04000;
1011 	gid = -1;
1012 	if (gr == NULL || strcmp(group, gr->gr_name) != 0) {
1013 		if ((*group == ':' && (getgrgid(gid = atoi(group + 1)) == NULL))
1014 		   || ((gr = getgrnam(group)) == NULL)) {
1015 			if (mode & 02000) {
1016 				note("%s:%s: unknown group", host, group);
1017 				mode &= ~02000;
1018 			}
1019 		} else
1020 			gid = gr->gr_gid;
1021 	} else
1022 		gid = gr->gr_gid;
1023 	if (userid && gid >= 0) {
1024 		if (gr) for (i = 0; gr->gr_mem[i] != NULL; i++)
1025 			if (!(strcmp(user, gr->gr_mem[i])))
1026 				goto ok;
1027 		mode &= ~02000;
1028 		gid = -1;
1029 	}
1030 ok:	if (fd != -1 && fchown(fd, uid, gid) < 0 || chown(file, uid, gid) < 0)
1031 		note("%s: %s chown: %s", host, file, strerror(errno));
1032 	else if (mode & 07000 &&
1033 	   (fd != -1 && fchmod(fd, mode) < 0 || chmod(file, mode) < 0))
1034 		note("%s: %s chmod: %s", host, file, strerror(errno));
1035 	return(0);
1036 }
1037 
1038 /*
1039  * Check for files on the machine being updated that are not on the master
1040  * machine and remove them.
1041  */
1042 rmchk(opts)
1043 	int opts;
1044 {
1045 	register char *cp, *s;
1046 	struct stat stb;
1047 
1048 	if (debug)
1049 		printf("rmchk()\n");
1050 
1051 	/*
1052 	 * Tell the remote to clean the files from the last directory sent.
1053 	 */
1054 	(void) sprintf(buf, "C%o\n", opts & VERIFY);
1055 	if (debug)
1056 		printf("buf = %s", buf);
1057 	(void) write(rem, buf, strlen(buf));
1058 	if (response() < 0)
1059 		return;
1060 	for (;;) {
1061 		cp = s = buf;
1062 		do {
1063 			if (read(rem, cp, 1) != 1)
1064 				lostconn();
1065 		} while (*cp++ != '\n' && cp < &buf[BUFSIZ]);
1066 
1067 		switch (*s++) {
1068 		case 'Q': /* Query if file should be removed */
1069 			/*
1070 			 * Return the following codes to remove query.
1071 			 * N\n -- file exists - DON'T remove.
1072 			 * Y\n -- file doesn't exist - REMOVE.
1073 			 */
1074 			*--cp = '\0';
1075 			(void) sprintf(tp, "/%s", s);
1076 			if (debug)
1077 				printf("check %s\n", target);
1078 			if (except(target))
1079 				(void) write(rem, "N\n", 2);
1080 			else if (lstat(target, &stb) < 0)
1081 				(void) write(rem, "Y\n", 2);
1082 			else
1083 				(void) write(rem, "N\n", 2);
1084 			break;
1085 
1086 		case '\0':
1087 			*--cp = '\0';
1088 			if (*s != '\0')
1089 				log(lfp, "%s\n", s);
1090 			break;
1091 
1092 		case 'E':
1093 			*tp = '\0';
1094 			ack();
1095 			return;
1096 
1097 		case '\1':
1098 		case '\2':
1099 			nerrs++;
1100 			if (*s != '\n') {
1101 				if (!iamremote) {
1102 					fflush(stdout);
1103 					(void) write(2, s, cp - s);
1104 				}
1105 				if (lfp != NULL)
1106 					(void) fwrite(s, 1, cp - s, lfp);
1107 			}
1108 			if (buf[0] == '\2')
1109 				lostconn();
1110 			break;
1111 
1112 		default:
1113 			error("rmchk: unexpected response '%s'\n", buf);
1114 			err();
1115 		}
1116 	}
1117 }
1118 
1119 /*
1120  * Check the current directory (initialized by the 'T' command to server())
1121  * for extraneous files and remove them.
1122  */
1123 clean(cp)
1124 	register char *cp;
1125 {
1126 	DIR *d;
1127 	register struct direct *dp;
1128 	struct stat stb;
1129 	char *otp;
1130 	int len, opts;
1131 
1132 	opts = 0;
1133 	while (*cp >= '0' && *cp <= '7')
1134 		opts = (opts << 3) | (*cp++ - '0');
1135 	if (*cp != '\0') {
1136 		error("clean: options not delimited\n");
1137 		return;
1138 	}
1139 	if ((d = opendir(target)) == NULL) {
1140 		error("%s:%s: %s\n", host, target, strerror(errno));
1141 		return;
1142 	}
1143 	ack();
1144 
1145 	otp = tp;
1146 	len = tp - target;
1147 	while (dp = readdir(d)) {
1148 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1149 			continue;
1150 		if (len + 1 + strlen(dp->d_name) >= BUFSIZ - 1) {
1151 			error("%s:%s/%s: Name too long\n",
1152 				host, target, dp->d_name);
1153 			continue;
1154 		}
1155 		tp = otp;
1156 		*tp++ = '/';
1157 		cp = dp->d_name;;
1158 		while (*tp++ = *cp++)
1159 			;
1160 		tp--;
1161 		if (lstat(target, &stb) < 0) {
1162 			error("%s:%s: %s\n", host, target, strerror(errno));
1163 			continue;
1164 		}
1165 		(void) sprintf(buf, "Q%s\n", dp->d_name);
1166 		(void) write(rem, buf, strlen(buf));
1167 		cp = buf;
1168 		do {
1169 			if (read(rem, cp, 1) != 1)
1170 				cleanup();
1171 		} while (*cp++ != '\n' && cp < &buf[BUFSIZ]);
1172 		*--cp = '\0';
1173 		cp = buf;
1174 		if (*cp != 'Y')
1175 			continue;
1176 		if (opts & VERIFY) {
1177 			cp = buf;
1178 			*cp++ = '\0';
1179 			(void) sprintf(cp, "need to remove: %s\n", target);
1180 			(void) write(rem, buf, strlen(cp) + 1);
1181 		} else
1182 			removeit(&stb);
1183 	}
1184 	closedir(d);
1185 	(void) write(rem, "E\n", 2);
1186 	(void) response();
1187 	tp = otp;
1188 	*tp = '\0';
1189 }
1190 
1191 /*
1192  * Remove a file or directory (recursively) and send back an acknowledge
1193  * or an error message.
1194  */
1195 removeit(stp)
1196 	struct stat *stp;
1197 {
1198 	DIR *d;
1199 	struct direct *dp;
1200 	register char *cp;
1201 	struct stat stb;
1202 	char *otp;
1203 	int len;
1204 
1205 	switch (stp->st_mode & S_IFMT) {
1206 	case S_IFREG:
1207 	case S_IFLNK:
1208 		if (unlink(target) < 0)
1209 			goto bad;
1210 		goto removed;
1211 
1212 	case S_IFDIR:
1213 		break;
1214 
1215 	default:
1216 		error("%s:%s: not a plain file\n", host, target);
1217 		return;
1218 	}
1219 
1220 	if ((d = opendir(target)) == NULL)
1221 		goto bad;
1222 
1223 	otp = tp;
1224 	len = tp - target;
1225 	while (dp = readdir(d)) {
1226 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1227 			continue;
1228 		if (len + 1 + strlen(dp->d_name) >= BUFSIZ - 1) {
1229 			error("%s:%s/%s: Name too long\n",
1230 				host, target, dp->d_name);
1231 			continue;
1232 		}
1233 		tp = otp;
1234 		*tp++ = '/';
1235 		cp = dp->d_name;;
1236 		while (*tp++ = *cp++)
1237 			;
1238 		tp--;
1239 		if (lstat(target, &stb) < 0) {
1240 			error("%s:%s: %s\n", host, target, strerror(errno));
1241 			continue;
1242 		}
1243 		removeit(&stb);
1244 	}
1245 	closedir(d);
1246 	tp = otp;
1247 	*tp = '\0';
1248 	if (rmdir(target) < 0) {
1249 bad:
1250 		error("%s:%s: %s\n", host, target, strerror(errno));
1251 		return;
1252 	}
1253 removed:
1254 	cp = buf;
1255 	*cp++ = '\0';
1256 	(void) sprintf(cp, "removed %s\n", target);
1257 	(void) write(rem, buf, strlen(cp) + 1);
1258 }
1259 
1260 /*
1261  * Execute a shell command to handle special cases.
1262  */
1263 dospecial(cmd)
1264 	char *cmd;
1265 {
1266 	int fd[2], status, pid, i;
1267 	register char *cp, *s;
1268 	char sbuf[BUFSIZ];
1269 	extern int userid, groupid;
1270 
1271 	if (pipe(fd) < 0) {
1272 		error("%s\n", strerror(errno));
1273 		return;
1274 	}
1275 	if ((pid = fork()) == 0) {
1276 		/*
1277 		 * Return everything the shell commands print.
1278 		 */
1279 		(void) close(0);
1280 		(void) close(1);
1281 		(void) close(2);
1282 		(void) open(_PATH_DEVNULL, O_RDONLY);
1283 		(void) dup(fd[1]);
1284 		(void) dup(fd[1]);
1285 		(void) close(fd[0]);
1286 		(void) close(fd[1]);
1287 		setgid(groupid);
1288 		setuid(userid);
1289 		execl(_PATH_BSHELL, "sh", "-c", cmd, 0);
1290 		_exit(127);
1291 	}
1292 	(void) close(fd[1]);
1293 	s = sbuf;
1294 	*s++ = '\0';
1295 	while ((i = read(fd[0], buf, sizeof(buf))) > 0) {
1296 		cp = buf;
1297 		do {
1298 			*s++ = *cp++;
1299 			if (cp[-1] != '\n') {
1300 				if (s < &sbuf[sizeof(sbuf)-1])
1301 					continue;
1302 				*s++ = '\n';
1303 			}
1304 			/*
1305 			 * Throw away blank lines.
1306 			 */
1307 			if (s == &sbuf[2]) {
1308 				s--;
1309 				continue;
1310 			}
1311 			(void) write(rem, sbuf, s - sbuf);
1312 			s = &sbuf[1];
1313 		} while (--i);
1314 	}
1315 	if (s > &sbuf[1]) {
1316 		*s++ = '\n';
1317 		(void) write(rem, sbuf, s - sbuf);
1318 	}
1319 	while ((i = wait(&status)) != pid && i != -1)
1320 		;
1321 	if (i == -1)
1322 		status = -1;
1323 	(void) close(fd[0]);
1324 	if (status)
1325 		error("shell returned %d\n", status);
1326 	else
1327 		ack();
1328 }
1329 
1330 /*VARARGS2*/
1331 log(fp, fmt, a1, a2, a3)
1332 	FILE *fp;
1333 	char *fmt;
1334 	int a1, a2, a3;
1335 {
1336 	/* Print changes locally if not quiet mode */
1337 	if (!qflag)
1338 		printf(fmt, a1, a2, a3);
1339 
1340 	/* Save changes (for mailing) if really updating files */
1341 	if (!(options & VERIFY) && fp != NULL)
1342 		fprintf(fp, fmt, a1, a2, a3);
1343 }
1344 
1345 /*VARARGS1*/
1346 error(fmt, a1, a2, a3)
1347 	char *fmt;
1348 	int a1, a2, a3;
1349 {
1350 	static FILE *fp;
1351 
1352 	++nerrs;
1353 	if (!fp && !(fp = fdopen(rem, "w")))
1354 		return;
1355 	if (iamremote) {
1356 		(void)fprintf(fp, "%crdist: ", 0x01);
1357 		(void)fprintf(fp, fmt, a1, a2, a3);
1358 		fflush(fp);
1359 	}
1360 	else {
1361 		fflush(stdout);
1362 		(void)fprintf(stderr, "rdist: ");
1363 		(void)fprintf(stderr, fmt, a1, a2, a3);
1364 		fflush(stderr);
1365 	}
1366 	if (lfp != NULL) {
1367 		(void)fprintf(lfp, "rdist: ");
1368 		(void)fprintf(lfp, fmt, a1, a2, a3);
1369 		fflush(lfp);
1370 	}
1371 }
1372 
1373 /*VARARGS1*/
1374 fatal(fmt, a1, a2,a3)
1375 	char *fmt;
1376 	int a1, a2, a3;
1377 {
1378 	static FILE *fp;
1379 
1380 	++nerrs;
1381 	if (!fp && !(fp = fdopen(rem, "w")))
1382 		return;
1383 	if (iamremote) {
1384 		(void)fprintf(fp, "%crdist: ", 0x02);
1385 		(void)fprintf(fp, fmt, a1, a2, a3);
1386 		fflush(fp);
1387 	}
1388 	else {
1389 		fflush(stdout);
1390 		(void)fprintf(stderr, "rdist: ");
1391 		(void)fprintf(stderr, fmt, a1, a2, a3);
1392 		fflush(stderr);
1393 	}
1394 	if (lfp != NULL) {
1395 		(void)fprintf(lfp, "rdist: ");
1396 		(void)fprintf(lfp, fmt, a1, a2, a3);
1397 		fflush(lfp);
1398 	}
1399 	cleanup();
1400 }
1401 
1402 response()
1403 {
1404 	char *cp, *s;
1405 	char resp[BUFSIZ];
1406 
1407 	if (debug)
1408 		printf("response()\n");
1409 
1410 	cp = s = resp;
1411 	do {
1412 		if (read(rem, cp, 1) != 1)
1413 			lostconn();
1414 	} while (*cp++ != '\n' && cp < &resp[BUFSIZ]);
1415 
1416 	switch (*s++) {
1417 	case '\0':
1418 		*--cp = '\0';
1419 		if (*s != '\0') {
1420 			log(lfp, "%s\n", s);
1421 			return(1);
1422 		}
1423 		return(0);
1424 	case '\3':
1425 		*--cp = '\0';
1426 		log(lfp, "Note: %s\n",s);
1427 		return(response());
1428 
1429 	default:
1430 		s--;
1431 		/* fall into... */
1432 	case '\1':
1433 	case '\2':
1434 		nerrs++;
1435 		if (*s != '\n') {
1436 			if (!iamremote) {
1437 				fflush(stdout);
1438 				(void) write(2, s, cp - s);
1439 			}
1440 			if (lfp != NULL)
1441 				(void) fwrite(s, 1, cp - s, lfp);
1442 		}
1443 		if (resp[0] == '\2')
1444 			lostconn();
1445 		return(-1);
1446 	}
1447 }
1448 
1449 /*
1450  * Remove temporary files and do any cleanup operations before exiting.
1451  */
1452 void
1453 cleanup()
1454 {
1455 	(void) unlink(tempfile);
1456 	exit(1);
1457 }
1458 
1459 note(fmt, a1, a2, a3)
1460 	char *fmt;
1461 	int a1, a2, a3;
1462 {
1463 	static char buf[BUFSIZ];
1464 	sprintf(buf, fmt, a1, a2, a3);
1465 	comment(buf);
1466 }
1467 
1468 comment(s)
1469 char *s;
1470 {
1471 	char c = '\3';
1472 	write(rem, &c, 1);
1473 	write(rem, s, strlen(s));
1474 	c = '\n';
1475 	write(rem, &c, 1);
1476 }
1477