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