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