xref: /freebsd/usr.sbin/ypbind/ypbind.c (revision eacee0ff7ec955b32e09515246bd97b6edcd2b0f)
1 /*
2  * Copyright (c) 1992/3 Theo de Raadt <deraadt@fsa.ca>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote
14  *    products derived from this software without specific prior written
15  *    permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 static const char rcsid[] =
32   "$FreeBSD$";
33 #endif /* not lint */
34 
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <sys/ioctl.h>
39 #include <sys/signal.h>
40 #include <sys/socket.h>
41 #include <sys/file.h>
42 #include <sys/fcntl.h>
43 #include <sys/stat.h>
44 #include <sys/uio.h>
45 #include <ctype.h>
46 #include <dirent.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <netdb.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <syslog.h>
55 #include <unistd.h>
56 #include <rpc/rpc.h>
57 #include <rpc/xdr.h>
58 #include <net/if.h>
59 #include <netinet/in.h>
60 #include <arpa/inet.h>
61 #include <rpc/pmap_clnt.h>
62 #include <rpc/pmap_prot.h>
63 #include <rpc/pmap_rmt.h>
64 #include <rpc/rpc_com.h>
65 #include <rpcsvc/yp.h>
66 struct dom_binding{};
67 #include <rpcsvc/ypclnt.h>
68 #include "yp_ping.h"
69 
70 #ifndef BINDINGDIR
71 #define BINDINGDIR "/var/yp/binding"
72 #endif
73 
74 #ifndef YPBINDLOCK
75 #define YPBINDLOCK "/var/run/ypbind.lock"
76 #endif
77 
78 struct _dom_binding {
79 	struct _dom_binding *dom_pnext;
80 	char dom_domain[YPMAXDOMAIN + 1];
81 	struct sockaddr_in dom_server_addr;
82 	long int dom_vers;
83 	int dom_lockfd;
84 	int dom_alive;
85 	int dom_broadcast_pid;
86 	int dom_pipe_fds[2];
87 	int dom_default;
88 };
89 
90 #define READFD ypdb->dom_pipe_fds[0]
91 #define WRITEFD ypdb->dom_pipe_fds[1]
92 #define BROADFD broad_domain->dom_pipe_fds[1]
93 
94 extern bool_t xdr_domainname(), xdr_ypbind_resp();
95 extern bool_t xdr_ypreq_key(), xdr_ypresp_val();
96 extern bool_t xdr_ypbind_setdom();
97 
98 void	checkwork(void);
99 void	*ypbindproc_null_2_yp(SVCXPRT *, void *, CLIENT *);
100 void	*ypbindproc_setdom_2_yp(SVCXPRT *, struct ypbind_setdom *, CLIENT *);
101 void	rpc_received(char *, struct sockaddr_in *, int);
102 void	broadcast(struct _dom_binding *);
103 int	ping(struct _dom_binding *);
104 int	tell_parent(char *, struct sockaddr_in *);
105 void	handle_children(struct _dom_binding *);
106 void	reaper(int);
107 void	terminate(int);
108 void	yp_restricted_mode(char *);
109 int	verify(struct in_addr);
110 
111 char *domain_name;
112 struct _dom_binding *ypbindlist;
113 static struct _dom_binding *broad_domain;
114 
115 #define YPSET_NO	0
116 #define YPSET_LOCAL	1
117 #define YPSET_ALL	2
118 int ypsetmode = YPSET_NO;
119 int ypsecuremode = 0;
120 int ppid;
121 
122 /*
123  * Special restricted mode variables: when in restricted mode, only the
124  * specified restricted_domain will be bound, and only the servers listed
125  * in restricted_addrs will be used for binding.
126  */
127 #define RESTRICTED_SERVERS 10
128 int yp_restricted = 0;
129 int yp_manycast = 0;
130 struct in_addr restricted_addrs[RESTRICTED_SERVERS];
131 
132 /* No more than MAX_CHILDREN child broadcasters at a time. */
133 #ifndef MAX_CHILDREN
134 #define MAX_CHILDREN 5
135 #endif
136 /* No more than MAX_DOMAINS simultaneous domains */
137 #ifndef MAX_DOMAINS
138 #define MAX_DOMAINS 200
139 #endif
140 /* RPC timeout value */
141 #ifndef FAIL_THRESHOLD
142 #define FAIL_THRESHOLD 20
143 #endif
144 
145 /* Number of times to fish for a response froma particular set of hosts */
146 #ifndef MAX_RETRIES
147 #define MAX_RETRIES 30
148 #endif
149 
150 int retries = 0;
151 int children = 0;
152 int domains = 0;
153 int yplockfd;
154 fd_set fdsr;
155 
156 SVCXPRT *udptransp, *tcptransp;
157 
158 void *
159 ypbindproc_null_2_yp(SVCXPRT *transp, void *argp, CLIENT *clnt)
160 {
161 	static char res;
162 
163 	bzero((char *)&res, sizeof(res));
164 	return (void *)&res;
165 }
166 
167 struct ypbind_resp *
168 ypbindproc_domain_2_yp(SVCXPRT *transp, domainname *argp, CLIENT *clnt)
169 {
170 	static struct ypbind_resp res;
171 	struct _dom_binding *ypdb;
172 	char path[MAXPATHLEN];
173 
174 	bzero((char *)&res, sizeof res);
175 	res.ypbind_status = YPBIND_FAIL_VAL;
176 	res.ypbind_resp_u.ypbind_error = YPBIND_ERR_NOSERV;
177 
178 	if (strchr(*argp, '/')) {
179 		syslog(LOG_WARNING, "Domain name '%s' has embedded slash -- \
180 rejecting.", *argp);
181 		return(&res);
182 	}
183 
184 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext) {
185 		if (strcmp(ypdb->dom_domain, *argp) == 0)
186 			break;
187 		}
188 
189 	if (ypdb == NULL) {
190 		if (yp_restricted) {
191 			syslog(LOG_NOTICE, "Running in restricted mode -- request to bind domain \"%s\" rejected.\n", *argp);
192 			return (&res);
193 		}
194 
195 		if (domains >= MAX_DOMAINS) {
196 			syslog(LOG_WARNING, "domain limit (%d) exceeded",
197 							MAX_DOMAINS);
198 			res.ypbind_resp_u.ypbind_error = YPBIND_ERR_RESC;
199 			return (&res);
200 		}
201 		ypdb = (struct _dom_binding *)malloc(sizeof *ypdb);
202 		if (ypdb == NULL) {
203 			syslog(LOG_WARNING, "malloc: %m");
204 			res.ypbind_resp_u.ypbind_error = YPBIND_ERR_RESC;
205 			return (&res);
206 		}
207 		bzero((char *)ypdb, sizeof *ypdb);
208 		strncpy(ypdb->dom_domain, *argp, sizeof ypdb->dom_domain);
209 		ypdb->dom_vers = YPVERS;
210 		ypdb->dom_alive = 0;
211 		ypdb->dom_default = 0;
212 		ypdb->dom_lockfd = -1;
213 		sprintf(path, "%s/%s.%ld", BINDINGDIR,
214 					ypdb->dom_domain, ypdb->dom_vers);
215 		unlink(path);
216 		ypdb->dom_pnext = ypbindlist;
217 		ypbindlist = ypdb;
218 		domains++;
219 	}
220 
221 	if (ping(ypdb)) {
222 		return (&res);
223 	}
224 
225 	res.ypbind_status = YPBIND_SUCC_VAL;
226 	res.ypbind_resp_u.ypbind_error = 0; /* Success */
227 	*(u_int32_t *)&res.ypbind_resp_u.ypbind_bindinfo.ypbind_binding_addr =
228 		ypdb->dom_server_addr.sin_addr.s_addr;
229 	*(u_short *)&res.ypbind_resp_u.ypbind_bindinfo.ypbind_binding_port =
230 		ypdb->dom_server_addr.sin_port;
231 	/*printf("domain %s at %s/%d\n", ypdb->dom_domain,
232 		inet_ntoa(ypdb->dom_server_addr.sin_addr),
233 		ntohs(ypdb->dom_server_addr.sin_port));*/
234 	return (&res);
235 }
236 
237 void *
238 ypbindproc_setdom_2_yp(SVCXPRT *transp, ypbind_setdom *argp, CLIENT *clnt)
239 {
240 	struct sockaddr_in *fromsin, bindsin;
241 	static char		*result = NULL;
242 
243 	if (strchr(argp->ypsetdom_domain, '/')) {
244 		syslog(LOG_WARNING, "Domain name '%s' has embedded slash -- \
245 rejecting.", argp->ypsetdom_domain);
246 		return(NULL);
247 	}
248 	fromsin = svc_getcaller(transp);
249 
250 	switch (ypsetmode) {
251 	case YPSET_LOCAL:
252 		if (fromsin->sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
253 			svcerr_noprog(transp);
254 			return(NULL);
255 		}
256 		break;
257 	case YPSET_ALL:
258 		break;
259 	case YPSET_NO:
260 	default:
261 		svcerr_noprog(transp);
262 		return(NULL);
263 	}
264 
265 	if (ntohs(fromsin->sin_port) >= IPPORT_RESERVED) {
266 		svcerr_noprog(transp);
267 		return(NULL);
268 	}
269 
270 	if (argp->ypsetdom_vers != YPVERS) {
271 		svcerr_noprog(transp);
272 		return(NULL);
273 	}
274 
275 	bzero((char *)&bindsin, sizeof bindsin);
276 	bindsin.sin_family = AF_INET;
277 	bindsin.sin_addr.s_addr = *(u_int32_t *)argp->ypsetdom_binding.ypbind_binding_addr;
278 	bindsin.sin_port = *(u_short *)argp->ypsetdom_binding.ypbind_binding_port;
279 	rpc_received(argp->ypsetdom_domain, &bindsin, 1);
280 
281 	return((void *) &result);
282 }
283 
284 static void
285 ypbindprog_2(struct svc_req *rqstp, register SVCXPRT *transp)
286 {
287 	union {
288 		domainname ypbindproc_domain_2_arg;
289 		struct ypbind_setdom ypbindproc_setdom_2_arg;
290 	} argument;
291 	struct authunix_parms *creds;
292 	char *result;
293 	bool_t (*xdr_argument)(), (*xdr_result)();
294 	char *(*local)();
295 
296 	switch (rqstp->rq_proc) {
297 	case YPBINDPROC_NULL:
298 		xdr_argument = xdr_void;
299 		xdr_result = xdr_void;
300 		local = (char *(*)()) ypbindproc_null_2_yp;
301 		break;
302 
303 	case YPBINDPROC_DOMAIN:
304 		xdr_argument = xdr_domainname;
305 		xdr_result = xdr_ypbind_resp;
306 		local = (char *(*)()) ypbindproc_domain_2_yp;
307 		break;
308 
309 	case YPBINDPROC_SETDOM:
310 		switch (rqstp->rq_cred.oa_flavor) {
311 		case AUTH_UNIX:
312 			creds = (struct authunix_parms *)rqstp->rq_clntcred;
313 			if (creds->aup_uid != 0) {
314 				svcerr_auth(transp, AUTH_BADCRED);
315 				return;
316 			}
317 			break;
318 		default:
319 			svcerr_auth(transp, AUTH_TOOWEAK);
320 			return;
321 		}
322 
323 		xdr_argument = xdr_ypbind_setdom;
324 		xdr_result = xdr_void;
325 		local = (char *(*)()) ypbindproc_setdom_2_yp;
326 		break;
327 
328 	default:
329 		svcerr_noproc(transp);
330 		return;
331 	}
332 	bzero((char *)&argument, sizeof(argument));
333 	if (!svc_getargs(transp, xdr_argument, (caddr_t)&argument)) {
334 		svcerr_decode(transp);
335 		return;
336 	}
337 	result = (*local)(transp, &argument, rqstp);
338 	if (result != NULL && !svc_sendreply(transp, xdr_result, result)) {
339 		svcerr_systemerr(transp);
340 	}
341 	return;
342 }
343 
344 /* Jack the reaper */
345 void
346 reaper(int sig)
347 {
348 	int st;
349 
350 	while (wait3(&st, WNOHANG, NULL) > 0)
351 		children--;
352 }
353 
354 void
355 terminate(int sig)
356 {
357 	struct _dom_binding *ypdb;
358 	char path[MAXPATHLEN];
359 
360 	if (ppid != getpid())
361 		exit(0);
362 
363 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext) {
364 		close(ypdb->dom_lockfd);
365 		if (ypdb->dom_broadcast_pid)
366 			kill(ypdb->dom_broadcast_pid, SIGINT);
367 		sprintf(path, "%s/%s.%ld", BINDINGDIR,
368 			ypdb->dom_domain, ypdb->dom_vers);
369 		unlink(path);
370 	}
371 	close(yplockfd);
372 	unlink(YPBINDLOCK);
373 	pmap_unset(YPBINDPROG, YPBINDVERS);
374 	exit(0);
375 }
376 
377 int
378 main(int argc, char *argv[])
379 {
380 	struct timeval tv;
381 	int i;
382 	DIR *dird;
383 	struct dirent *dirp;
384 	struct _dom_binding *ypdb, *next;
385 
386 	/* Check that another ypbind isn't already running. */
387 	if ((yplockfd = (open(YPBINDLOCK, O_RDONLY|O_CREAT, 0444))) == -1)
388 		err(1, "%s", YPBINDLOCK);
389 
390 	if (flock(yplockfd, LOCK_EX|LOCK_NB) == -1 && errno == EWOULDBLOCK)
391 		errx(1, "another ypbind is already running. Aborting");
392 
393 	/* XXX domainname will be overriden if we use restricted mode */
394 	yp_get_default_domain(&domain_name);
395 	if (domain_name[0] == '\0')
396 		errx(1, "domainname not set. Aborting");
397 
398 	for (i = 1; i<argc; i++) {
399 		if (strcmp("-ypset", argv[i]) == 0)
400 			ypsetmode = YPSET_ALL;
401 		else if (strcmp("-ypsetme", argv[i]) == 0)
402 		        ypsetmode = YPSET_LOCAL;
403 		else if (strcmp("-s", argv[i]) == 0)
404 		        ypsecuremode++;
405 		else if (strcmp("-S", argv[i]) == 0 && argc > i)
406 			yp_restricted_mode(argv[++i]);
407 		else if (strcmp("-m", argv[i]) == 0)
408 			yp_manycast++;
409 		else
410 			errx(1, "unknown option: %s", argv[i]);
411 	}
412 
413 	/* blow away everything in BINDINGDIR (if it exists) */
414 
415 	if ((dird = opendir(BINDINGDIR)) != NULL) {
416 		char path[MAXPATHLEN];
417 		while ((dirp = readdir(dird)) != NULL)
418 			if (strcmp(dirp->d_name, ".") &&
419 			    strcmp(dirp->d_name, "..")) {
420 				sprintf(path,"%s/%s",BINDINGDIR,dirp->d_name);
421 				unlink(path);
422 			}
423 		closedir(dird);
424 	}
425 
426 #ifdef DAEMON
427 	if (daemon(0,0))
428 		err(1, "fork");
429 #endif
430 
431 	pmap_unset(YPBINDPROG, YPBINDVERS);
432 
433 	udptransp = svcudp_create(RPC_ANYSOCK);
434 	if (udptransp == NULL)
435 		errx(1, "cannot create udp service");
436 	if (!svc_register(udptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
437 	    IPPROTO_UDP))
438 		errx(1, "unable to register (YPBINDPROG, YPBINDVERS, udp)");
439 
440 	tcptransp = svctcp_create(RPC_ANYSOCK, 0, 0);
441 	if (tcptransp == NULL)
442 		errx(1, "cannot create tcp service");
443 
444 	if (!svc_register(tcptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
445 	    IPPROTO_TCP))
446 		errx(1, "unable to register (YPBINDPROG, YPBINDVERS, tcp)");
447 
448 	/* build initial domain binding, make it "unsuccessful" */
449 	ypbindlist = (struct _dom_binding *)malloc(sizeof *ypbindlist);
450 	if (ypbindlist == NULL)
451 		errx(1, "malloc");
452 	bzero((char *)ypbindlist, sizeof *ypbindlist);
453 	strncpy(ypbindlist->dom_domain, domain_name, sizeof ypbindlist->dom_domain);
454 	ypbindlist->dom_vers = YPVERS;
455 	ypbindlist->dom_alive = 0;
456 	ypbindlist->dom_lockfd = -1;
457 	ypbindlist->dom_default = 1;
458 	domains++;
459 
460 	signal(SIGCHLD, reaper);
461 	signal(SIGTERM, terminate);
462 
463 	ppid = getpid(); /* Remember who we are. */
464 
465 	openlog(argv[0], LOG_PID, LOG_DAEMON);
466 
467 	/* Kick off the default domain */
468 	broadcast(ypbindlist);
469 
470 	while (1) {
471 		fdsr = svc_fdset;
472 
473 		tv.tv_sec = 60;
474 		tv.tv_usec = 0;
475 
476 		switch (select(_rpc_dtablesize(), &fdsr, NULL, NULL, &tv)) {
477 		case 0:
478 			checkwork();
479 			break;
480 		case -1:
481 			if (errno != EINTR)
482 				syslog(LOG_WARNING, "select: %m");
483 			break;
484 		default:
485 			for (ypdb = ypbindlist; ypdb; ypdb = next) {
486 				next = ypdb->dom_pnext;
487 				if (READFD > 0 && FD_ISSET(READFD, &fdsr)) {
488 					handle_children(ypdb);
489 					if (children == (MAX_CHILDREN - 1))
490 						checkwork();
491 				}
492 			}
493 			svc_getreqset(&fdsr);
494 			break;
495 		}
496 	}
497 
498 	/* NOTREACHED */
499 	exit(1);
500 }
501 
502 void
503 checkwork(void)
504 {
505 	struct _dom_binding *ypdb;
506 
507 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext)
508 		ping(ypdb);
509 }
510 
511 /* The clnt_broadcast() callback mechanism sucks. */
512 
513 /*
514  * Receive results from broadcaster. Don't worry about passing
515  * bogus info to rpc_received() -- it can handle it. Note that we
516  * must be sure to invalidate the dom_pipe_fds descriptors here:
517  * since descriptors can be re-used, we have to make sure we
518  * don't mistake one of the RPC descriptors for one of the pipes.
519  * What's weird is that forgetting to invalidate the pipe descriptors
520  * doesn't always result in an error (otherwise I would have caught
521  * the mistake much sooner), even though logically it should.
522  */
523 void
524 handle_children(struct _dom_binding *ypdb)
525 {
526 	char buf[YPMAXDOMAIN + 1];
527 	struct sockaddr_in addr;
528 	int d = 0, a = 0;
529 	struct _dom_binding *y, *prev = NULL;
530 	char path[MAXPATHLEN];
531 
532 	if ((d = read(READFD, &buf, sizeof(buf))) <= 0)
533 		syslog(LOG_WARNING, "could not read from child: %m");
534 
535 	if ((a = read(READFD, &addr, sizeof(struct sockaddr_in))) < 0)
536 		syslog(LOG_WARNING, "could not read from child: %m");
537 
538 	close(READFD);
539 	FD_CLR(READFD, &fdsr);
540 	FD_CLR(READFD, &svc_fdset);
541 	READFD = WRITEFD = -1;
542 	if (d > 0 && a > 0)
543 		rpc_received((char *)&buf, &addr, 0);
544 	else {
545 		for (y = ypbindlist; y; y = y->dom_pnext) {
546 			if (y == ypdb)
547 				break;
548 			prev = y;
549 		}
550 		switch (ypdb->dom_default) {
551 		case 0:
552 			if (prev == NULL)
553 				ypbindlist = y->dom_pnext;
554 			else
555 				prev->dom_pnext = y->dom_pnext;
556 			sprintf(path, "%s/%s.%ld", BINDINGDIR,
557 				ypdb->dom_domain, YPVERS);
558 			close(ypdb->dom_lockfd);
559 			unlink(path);
560 			free(ypdb);
561 			domains--;
562 			return;
563 		case 1:
564 			ypdb->dom_broadcast_pid = 0;
565 			ypdb->dom_alive = 0;
566 			broadcast(ypdb);
567 			return;
568 		default:
569 			break;
570 		}
571 	}
572 
573 	return;
574 }
575 
576 /*
577  * Send our dying words back to our parent before we perish.
578  */
579 int
580 tell_parent(char *dom, struct sockaddr_in *addr)
581 {
582 	char buf[YPMAXDOMAIN + 1];
583 	struct timeval timeout;
584 	fd_set fds;
585 
586 	timeout.tv_sec = 5;
587 	timeout.tv_usec = 0;
588 
589 	sprintf(buf, "%s", broad_domain->dom_domain);
590 	if (write(BROADFD, &buf, sizeof(buf)) < 0)
591 		return(1);
592 
593 	/*
594 	 * Stay in sync with parent: wait for it to read our first
595 	 * message before sending the second.
596 	 */
597 
598 	FD_ZERO(&fds);
599 	FD_SET(BROADFD, &fds);
600 	if (select(FD_SETSIZE, NULL, &fds, NULL, &timeout) == -1)
601 		return(1);
602 	if (FD_ISSET(BROADFD, &fds)) {
603 		if (write(BROADFD, addr, sizeof(struct sockaddr_in)) < 0)
604 			return(1);
605 	} else {
606 		return(1);
607 	}
608 
609 	close(BROADFD);
610 	return (0);
611 }
612 
613 bool_t broadcast_result(out, addr)
614 bool_t *out;
615 struct sockaddr_in *addr;
616 {
617 	if (retries >= MAX_RETRIES) {
618 		bzero((char *)addr, sizeof(struct sockaddr_in));
619 		if (tell_parent(broad_domain->dom_domain, addr))
620 			syslog(LOG_WARNING, "lost connection to parent");
621 		return (TRUE);
622 	}
623 
624 	if (yp_restricted && verify(addr->sin_addr)) {
625 		retries++;
626 		syslog(LOG_NOTICE, "NIS server at %s not in restricted mode access list -- rejecting.\n",inet_ntoa(addr->sin_addr));
627 		return (FALSE);
628 	} else {
629 		if (tell_parent(broad_domain->dom_domain, addr))
630 			syslog(LOG_WARNING, "lost connection to parent");
631 		return (TRUE);
632 	}
633 }
634 
635 /*
636  * The right way to send RPC broadcasts.
637  * Use the clnt_broadcast() RPC service. Unfortunately, clnt_broadcast()
638  * blocks while waiting for replies, so we have to fork off separate
639  * broadcaster processes that do the waiting and then transmit their
640  * results back to the parent for processing. We also have to remember
641  * to save the name of the domain we're trying to bind in a global
642  * variable since clnt_broadcast() provides no way to pass things to
643  * the 'eachresult' callback function.
644  */
645 void
646 broadcast(struct _dom_binding *ypdb)
647 {
648 	bool_t out = FALSE;
649 	enum clnt_stat stat;
650 
651 	if (children >= MAX_CHILDREN || ypdb->dom_broadcast_pid)
652 		return;
653 
654 	if (pipe(ypdb->dom_pipe_fds) < 0) {
655 		syslog(LOG_WARNING, "pipe: %m");
656 		return;
657 	}
658 
659 	if (ypdb->dom_vers == -1 && (long)ypdb->dom_server_addr.sin_addr.s_addr)
660 		syslog(LOG_WARNING, "NIS server [%s] for domain \"%s\" not responding",
661 		inet_ntoa(ypdb->dom_server_addr.sin_addr), ypdb->dom_domain);
662 
663 	broad_domain = ypdb;
664 	flock(ypdb->dom_lockfd, LOCK_UN);
665 
666 	switch ((ypdb->dom_broadcast_pid = fork())) {
667 	case 0:
668 		close(READFD);
669 		signal(SIGCHLD, SIG_DFL);
670 		signal(SIGTERM, SIG_DFL);
671 		break;
672 	case -1:
673 		syslog(LOG_WARNING, "fork: %m");
674 		close(READFD);
675 		close(WRITEFD);
676 		return;
677 	default:
678 		close(WRITEFD);
679 		FD_SET(READFD, &svc_fdset);
680 		children++;
681 		return;
682 	}
683 
684 	/* Release all locks before doing anything else. */
685 	while (ypbindlist) {
686 		close(ypbindlist->dom_lockfd);
687 		ypbindlist = ypbindlist->dom_pnext;
688 	}
689 	close(yplockfd);
690 
691 	/*
692 	 * Special 'many-cast' behavior. If we're in restricted mode,
693 	 * we have a list of possible server addresses to try. What
694 	 * we can do is transmit to each ypserv's YPPROC_DOMAIN_NONACK
695 	 * procedure and time the replies. Whoever replies fastest
696 	 * gets to be our server. Note that this is not a broadcast
697 	 * operation: we transmit uni-cast datagrams only.
698 	 */
699 	if (yp_restricted && yp_manycast) {
700 		short			port;
701 		int			i;
702 		struct sockaddr_in	sin;
703 
704 		i = __yp_ping(restricted_addrs, yp_restricted,
705 				ypdb->dom_domain, &port);
706 		if (i == -1) {
707 			bzero((char *)&ypdb->dom_server_addr,
708 						sizeof(struct sockaddr_in));
709 			if (tell_parent(ypdb->dom_domain,
710 					&ypdb->dom_server_addr))
711 			syslog(LOG_WARNING, "lost connection to parent");
712 		} else {
713 			bzero((char *)&sin, sizeof(struct sockaddr_in));
714 			bcopy((char *)&restricted_addrs[i],
715 				(char *)&sin.sin_addr, sizeof(struct in_addr));
716 			sin.sin_family = AF_INET;
717 			sin.sin_port = port;
718 			if (tell_parent(broad_domain->dom_domain, &sin))
719 				syslog(LOG_WARNING,
720 					"lost connection to parent");
721 		}
722 		_exit(0);
723 	}
724 
725 	retries = 0;
726 
727 	{
728 		char *ptr;
729 
730 		ptr = (char *)&ypdb->dom_domain;
731 		stat = clnt_broadcast(YPPROG, YPVERS, YPPROC_DOMAIN_NONACK,
732 	    		xdr_domainname, (char *)&ptr, xdr_bool, (char *)&out,
733 	    		(resultproc_t)broadcast_result);
734 	}
735 
736 	if (stat != RPC_SUCCESS) {
737 		bzero((char *)&ypdb->dom_server_addr,
738 						sizeof(struct sockaddr_in));
739 		if (tell_parent(ypdb->dom_domain, &ypdb->dom_server_addr))
740 			syslog(LOG_WARNING, "lost connection to parent");
741 	}
742 
743 	_exit(0);
744 }
745 
746 /*
747  * The right way to check if a server is alive.
748  * Attempt to get a client handle pointing to the server and send a
749  * YPPROC_DOMAIN. If we can't get a handle or we get a reply of FALSE,
750  * we invalidate this binding entry and send out a broadcast to try to
751  * establish a new binding. Note that we treat non-default domains
752  * specially: once bound, we keep tabs on our server, but if it
753  * goes away and fails to respond after one round of broadcasting, we
754  * abandon it until a client specifically references it again. We make
755  * every effort to keep our default domain bound, however, since we
756  * need it to keep the system on its feet.
757  */
758 int
759 ping(struct _dom_binding *ypdb)
760 {
761 	bool_t out;
762 	struct timeval interval, timeout;
763 	enum clnt_stat stat;
764 	int rpcsock = RPC_ANYSOCK;
765 	CLIENT *client_handle;
766 
767 	interval.tv_sec = FAIL_THRESHOLD;
768 	interval.tv_usec = 0;
769 	timeout.tv_sec = FAIL_THRESHOLD;
770 	timeout.tv_usec = 0;
771 
772 	if (ypdb->dom_broadcast_pid)
773 		return(1);
774 
775 	if ((client_handle = clntudp_bufcreate(&ypdb->dom_server_addr,
776 		YPPROG, YPVERS, interval, &rpcsock, RPCSMALLMSGSIZE,
777 		RPCSMALLMSGSIZE)) == (CLIENT *)NULL) {
778 		/* Can't get a handle: we're dead. */
779 		ypdb->dom_alive = 0;
780 		ypdb->dom_vers = -1;
781 		broadcast(ypdb);
782 		return(1);
783 	}
784 
785 	{
786 		char *ptr;
787 
788 		ptr = (char *)&ypdb->dom_domain;
789 
790 		if ((stat = clnt_call(client_handle, YPPROC_DOMAIN,
791 			xdr_domainname, (char *)&ptr, xdr_bool, (char *)&out,
792 			timeout)) != RPC_SUCCESS || out == FALSE) {
793 			ypdb->dom_alive = 0;
794 			ypdb->dom_vers = -1;
795 			clnt_destroy(client_handle);
796 			broadcast(ypdb);
797 			return(1);
798 		}
799 	}
800 
801 	clnt_destroy(client_handle);
802 	return(0);
803 }
804 
805 void
806 rpc_received(char *dom, struct sockaddr_in *raddrp, int force)
807 {
808 	struct _dom_binding *ypdb, *prev = NULL;
809 	struct iovec iov[2];
810 	struct ypbind_resp ybr;
811 	char path[MAXPATHLEN];
812 	int fd;
813 
814 	/*printf("returned from %s/%d about %s\n", inet_ntoa(raddrp->sin_addr),
815 	       ntohs(raddrp->sin_port), dom);*/
816 
817 	if (dom == NULL)
818 		return;
819 
820 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext) {
821 		if (strcmp(ypdb->dom_domain, dom) == 0)
822 			break;
823 		prev = ypdb;
824 	}
825 
826 	if (ypdb && force) {
827 		if (ypdb->dom_broadcast_pid) {
828 			kill(ypdb->dom_broadcast_pid, SIGINT);
829 			close(READFD);
830 			FD_CLR(READFD, &fdsr);
831 			FD_CLR(READFD, &svc_fdset);
832 			READFD = WRITEFD = -1;
833 		}
834 	}
835 
836 	/* if in secure mode, check originating port number */
837 	if ((ypsecuremode && (ntohs(raddrp->sin_port) >= IPPORT_RESERVED))) {
838 	    syslog(LOG_WARNING, "Rejected NIS server on [%s/%d] for domain %s.",
839 		   inet_ntoa(raddrp->sin_addr), ntohs(raddrp->sin_port),
840 		   dom);
841 	    if (ypdb != NULL) {
842 		ypdb->dom_broadcast_pid = 0;
843 		ypdb->dom_alive = 0;
844 	    }
845 	    return;
846 	}
847 
848 	if (raddrp->sin_addr.s_addr == (long)0) {
849 		switch (ypdb->dom_default) {
850 		case 0:
851 			if (prev == NULL)
852 				ypbindlist = ypdb->dom_pnext;
853 			else
854 				prev->dom_pnext = ypdb->dom_pnext;
855 			sprintf(path, "%s/%s.%ld", BINDINGDIR,
856 				ypdb->dom_domain, YPVERS);
857 			close(ypdb->dom_lockfd);
858 			unlink(path);
859 			free(ypdb);
860 			domains--;
861 			return;
862 		case 1:
863 			ypdb->dom_broadcast_pid = 0;
864 			ypdb->dom_alive = 0;
865 			broadcast(ypdb);
866 			return;
867 		default:
868 			break;
869 		}
870 	}
871 
872 	if (ypdb == NULL) {
873 		if (force == 0)
874 			return;
875 		ypdb = (struct _dom_binding *)malloc(sizeof *ypdb);
876 		if (ypdb == NULL) {
877 			syslog(LOG_WARNING, "malloc: %m");
878 			return;
879 		}
880 		bzero((char *)ypdb, sizeof *ypdb);
881 		strncpy(ypdb->dom_domain, dom, sizeof ypdb->dom_domain);
882 		ypdb->dom_lockfd = -1;
883 		ypdb->dom_default = 0;
884 		ypdb->dom_pnext = ypbindlist;
885 		ypbindlist = ypdb;
886 	}
887 
888 	/* We've recovered from a crash: inform the world. */
889 	if (ypdb->dom_vers == -1 && ypdb->dom_server_addr.sin_addr.s_addr)
890 		syslog(LOG_WARNING, "NIS server [%s] for domain \"%s\" OK",
891 		inet_ntoa(raddrp->sin_addr), ypdb->dom_domain);
892 
893 	bcopy((char *)raddrp, (char *)&ypdb->dom_server_addr,
894 		sizeof ypdb->dom_server_addr);
895 
896 	ypdb->dom_vers = YPVERS;
897 	ypdb->dom_alive = 1;
898 	ypdb->dom_broadcast_pid = 0;
899 
900 	if (ypdb->dom_lockfd != -1)
901 		close(ypdb->dom_lockfd);
902 
903 	sprintf(path, "%s/%s.%ld", BINDINGDIR,
904 		ypdb->dom_domain, ypdb->dom_vers);
905 #ifdef O_SHLOCK
906 	if ((fd = open(path, O_CREAT|O_SHLOCK|O_RDWR|O_TRUNC, 0644)) == -1) {
907 		(void)mkdir(BINDINGDIR, 0755);
908 		if ((fd = open(path, O_CREAT|O_SHLOCK|O_RDWR|O_TRUNC, 0644)) == -1)
909 			return;
910 	}
911 #else
912 	if ((fd = open(path, O_CREAT|O_RDWR|O_TRUNC, 0644)) == -1) {
913 		(void)mkdir(BINDINGDIR, 0755);
914 		if ((fd = open(path, O_CREAT|O_RDWR|O_TRUNC, 0644)) == -1)
915 			return;
916 	}
917 	flock(fd, LOCK_SH);
918 #endif
919 
920 	/*
921 	 * ok, if BINDINGDIR exists, and we can create the binding file,
922 	 * then write to it..
923 	 */
924 	ypdb->dom_lockfd = fd;
925 
926 	iov[0].iov_base = (caddr_t)&(udptransp->xp_port);
927 	iov[0].iov_len = sizeof udptransp->xp_port;
928 	iov[1].iov_base = (caddr_t)&ybr;
929 	iov[1].iov_len = sizeof ybr;
930 
931 	bzero(&ybr, sizeof ybr);
932 	ybr.ypbind_status = YPBIND_SUCC_VAL;
933 	*(u_int32_t *)&ybr.ypbind_resp_u.ypbind_bindinfo.ypbind_binding_addr = raddrp->sin_addr.s_addr;
934 	*(u_short *)&ybr.ypbind_resp_u.ypbind_bindinfo.ypbind_binding_port = raddrp->sin_port;
935 
936 	if (writev(ypdb->dom_lockfd, iov, 2) != iov[0].iov_len + iov[1].iov_len) {
937 		syslog(LOG_WARNING, "write: %m");
938 		close(ypdb->dom_lockfd);
939 		ypdb->dom_lockfd = -1;
940 		return;
941 	}
942 }
943 
944 /*
945  * Check address against list of allowed servers. Return 0 if okay,
946  * 1 if not matched.
947  */
948 int
949 verify(struct in_addr addr)
950 {
951 	int i;
952 
953 	for (i = 0; i < RESTRICTED_SERVERS; i++)
954 		if (!bcmp((char *)&addr, (char *)&restricted_addrs[i],
955 			sizeof(struct in_addr)))
956 			return(0);
957 
958 	return(1);
959 }
960 
961 /*
962  * Try to set restricted mode. We default to normal mode if we can't
963  * resolve the specified hostnames.
964  */
965 void
966 yp_restricted_mode(char *args)
967 {
968 	struct hostent *h;
969 	int i = 0;
970 	char *s;
971 
972 	/* Find the restricted domain. */
973 	if ((s = strsep(&args, ",")) == NULL)
974 		return;
975 	domain_name = s;
976 
977 	/* Get the addresses of the servers. */
978 	while ((s = strsep(&args, ",")) != NULL && i < RESTRICTED_SERVERS) {
979 		if ((h = gethostbyname(s)) == NULL)
980 			return;
981 		bcopy ((char *)h->h_addr_list[0], (char *)&restricted_addrs[i],
982 			sizeof(struct in_addr));
983 	i++;
984 	}
985 
986 	/* ypset and ypsetme not allowed with restricted mode */
987 	ypsetmode = YPSET_NO;
988 
989 	yp_restricted = i;
990 	return;
991 }
992