xref: /freebsd/usr.sbin/ypbind/ypbind.c (revision fb2971ccd2bab42f5406f919812ceb8e014773ea)
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 #define NOT_RESPONDING_HYSTERESIS 10
120 static int not_responding_count = 0;
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(&res, sizeof(res));
164 	return &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(&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(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(&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 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(&argument, sizeof(argument));
333 	if (!svc_getargs(transp, (xdrproc_t)xdr_argument, &argument)) {
334 		svcerr_decode(transp);
335 		return;
336 	}
337 	result = (*local)(transp, &argument, rqstp);
338 	if (result != NULL &&
339 	    !svc_sendreply(transp, (xdrproc_t)xdr_result, result)) {
340 		svcerr_systemerr(transp);
341 	}
342 	return;
343 }
344 
345 /* Jack the reaper */
346 void
347 reaper(int sig)
348 {
349 	int st;
350 
351 	while (wait3(&st, WNOHANG, NULL) > 0)
352 		children--;
353 }
354 
355 void
356 terminate(int sig)
357 {
358 	struct _dom_binding *ypdb;
359 	char path[MAXPATHLEN];
360 
361 	if (ppid != getpid())
362 		exit(0);
363 
364 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext) {
365 		close(ypdb->dom_lockfd);
366 		if (ypdb->dom_broadcast_pid)
367 			kill(ypdb->dom_broadcast_pid, SIGINT);
368 		sprintf(path, "%s/%s.%ld", BINDINGDIR,
369 			ypdb->dom_domain, ypdb->dom_vers);
370 		unlink(path);
371 	}
372 	close(yplockfd);
373 	unlink(YPBINDLOCK);
374 	pmap_unset(YPBINDPROG, YPBINDVERS);
375 	exit(0);
376 }
377 
378 int
379 main(int argc, char *argv[])
380 {
381 	struct timeval tv;
382 	int i;
383 	DIR *dird;
384 	struct dirent *dirp;
385 	struct _dom_binding *ypdb, *next;
386 
387 	/* Check that another ypbind isn't already running. */
388 	if ((yplockfd = (open(YPBINDLOCK, O_RDONLY|O_CREAT, 0444))) == -1)
389 		err(1, "%s", YPBINDLOCK);
390 
391 	if (flock(yplockfd, LOCK_EX|LOCK_NB) == -1 && errno == EWOULDBLOCK)
392 		errx(1, "another ypbind is already running. Aborting");
393 
394 	/* XXX domainname will be overriden if we use restricted mode */
395 	yp_get_default_domain(&domain_name);
396 	if (domain_name[0] == '\0')
397 		errx(1, "domainname not set. Aborting");
398 
399 	for (i = 1; i<argc; i++) {
400 		if (strcmp("-ypset", argv[i]) == 0)
401 			ypsetmode = YPSET_ALL;
402 		else if (strcmp("-ypsetme", argv[i]) == 0)
403 		        ypsetmode = YPSET_LOCAL;
404 		else if (strcmp("-s", argv[i]) == 0)
405 		        ypsecuremode++;
406 		else if (strcmp("-S", argv[i]) == 0 && argc > i)
407 			yp_restricted_mode(argv[++i]);
408 		else if (strcmp("-m", argv[i]) == 0)
409 			yp_manycast++;
410 		else
411 			errx(1, "unknown option: %s", argv[i]);
412 	}
413 
414 	/* blow away everything in BINDINGDIR (if it exists) */
415 
416 	if ((dird = opendir(BINDINGDIR)) != NULL) {
417 		char path[MAXPATHLEN];
418 		while ((dirp = readdir(dird)) != NULL)
419 			if (strcmp(dirp->d_name, ".") &&
420 			    strcmp(dirp->d_name, "..")) {
421 				sprintf(path,"%s/%s",BINDINGDIR,dirp->d_name);
422 				unlink(path);
423 			}
424 		closedir(dird);
425 	}
426 
427 #ifdef DAEMON
428 	if (daemon(0,0))
429 		err(1, "fork");
430 #endif
431 
432 	pmap_unset(YPBINDPROG, YPBINDVERS);
433 
434 	udptransp = svcudp_create(RPC_ANYSOCK);
435 	if (udptransp == NULL)
436 		errx(1, "cannot create udp service");
437 	if (!svc_register(udptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
438 	    IPPROTO_UDP))
439 		errx(1, "unable to register (YPBINDPROG, YPBINDVERS, udp)");
440 
441 	tcptransp = svctcp_create(RPC_ANYSOCK, 0, 0);
442 	if (tcptransp == NULL)
443 		errx(1, "cannot create tcp service");
444 
445 	if (!svc_register(tcptransp, YPBINDPROG, YPBINDVERS, ypbindprog_2,
446 	    IPPROTO_TCP))
447 		errx(1, "unable to register (YPBINDPROG, YPBINDVERS, tcp)");
448 
449 	/* build initial domain binding, make it "unsuccessful" */
450 	ypbindlist = (struct _dom_binding *)malloc(sizeof *ypbindlist);
451 	if (ypbindlist == NULL)
452 		errx(1, "malloc");
453 	bzero(ypbindlist, sizeof *ypbindlist);
454 	strncpy(ypbindlist->dom_domain, domain_name, sizeof ypbindlist->dom_domain);
455 	ypbindlist->dom_vers = YPVERS;
456 	ypbindlist->dom_alive = 0;
457 	ypbindlist->dom_lockfd = -1;
458 	ypbindlist->dom_default = 1;
459 	domains++;
460 
461 	signal(SIGCHLD, reaper);
462 	signal(SIGTERM, terminate);
463 
464 	ppid = getpid(); /* Remember who we are. */
465 
466 	openlog(argv[0], LOG_PID, LOG_DAEMON);
467 
468 	/* Kick off the default domain */
469 	broadcast(ypbindlist);
470 
471 	while (1) {
472 		fdsr = svc_fdset;
473 
474 		tv.tv_sec = 60;
475 		tv.tv_usec = 0;
476 
477 		switch (select(_rpc_dtablesize(), &fdsr, NULL, NULL, &tv)) {
478 		case 0:
479 			checkwork();
480 			break;
481 		case -1:
482 			if (errno != EINTR)
483 				syslog(LOG_WARNING, "select: %m");
484 			break;
485 		default:
486 			for (ypdb = ypbindlist; ypdb; ypdb = next) {
487 				next = ypdb->dom_pnext;
488 				if (READFD > 0 && FD_ISSET(READFD, &fdsr)) {
489 					handle_children(ypdb);
490 					if (children == (MAX_CHILDREN - 1))
491 						checkwork();
492 				}
493 			}
494 			svc_getreqset(&fdsr);
495 			break;
496 		}
497 	}
498 
499 	/* NOTREACHED */
500 	exit(1);
501 }
502 
503 void
504 checkwork(void)
505 {
506 	struct _dom_binding *ypdb;
507 
508 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext)
509 		ping(ypdb);
510 }
511 
512 /* The clnt_broadcast() callback mechanism sucks. */
513 
514 /*
515  * Receive results from broadcaster. Don't worry about passing
516  * bogus info to rpc_received() -- it can handle it. Note that we
517  * must be sure to invalidate the dom_pipe_fds descriptors here:
518  * since descriptors can be re-used, we have to make sure we
519  * don't mistake one of the RPC descriptors for one of the pipes.
520  * What's weird is that forgetting to invalidate the pipe descriptors
521  * doesn't always result in an error (otherwise I would have caught
522  * the mistake much sooner), even though logically it should.
523  */
524 void
525 handle_children(struct _dom_binding *ypdb)
526 {
527 	char buf[YPMAXDOMAIN + 1];
528 	struct sockaddr_in addr;
529 	int d = 0, a = 0;
530 	struct _dom_binding *y, *prev = NULL;
531 	char path[MAXPATHLEN];
532 
533 	if ((d = read(READFD, &buf, sizeof(buf))) <= 0)
534 		syslog(LOG_WARNING, "could not read from child: %m");
535 
536 	if ((a = read(READFD, &addr, sizeof(struct sockaddr_in))) < 0)
537 		syslog(LOG_WARNING, "could not read from child: %m");
538 
539 	close(READFD);
540 	FD_CLR(READFD, &fdsr);
541 	FD_CLR(READFD, &svc_fdset);
542 	READFD = WRITEFD = -1;
543 	if (d > 0 && a > 0)
544 		rpc_received(buf, &addr, 0);
545 	else {
546 		for (y = ypbindlist; y; y = y->dom_pnext) {
547 			if (y == ypdb)
548 				break;
549 			prev = y;
550 		}
551 		switch (ypdb->dom_default) {
552 		case 0:
553 			if (prev == NULL)
554 				ypbindlist = y->dom_pnext;
555 			else
556 				prev->dom_pnext = y->dom_pnext;
557 			sprintf(path, "%s/%s.%ld", BINDINGDIR,
558 				ypdb->dom_domain, YPVERS);
559 			close(ypdb->dom_lockfd);
560 			unlink(path);
561 			free(ypdb);
562 			domains--;
563 			return;
564 		case 1:
565 			ypdb->dom_broadcast_pid = 0;
566 			ypdb->dom_alive = 0;
567 			broadcast(ypdb);
568 			return;
569 		default:
570 			break;
571 		}
572 	}
573 
574 	return;
575 }
576 
577 /*
578  * Send our dying words back to our parent before we perish.
579  */
580 int
581 tell_parent(char *dom, struct sockaddr_in *addr)
582 {
583 	char buf[YPMAXDOMAIN + 1];
584 	struct timeval timeout;
585 	fd_set fds;
586 
587 	timeout.tv_sec = 5;
588 	timeout.tv_usec = 0;
589 
590 	sprintf(buf, "%s", broad_domain->dom_domain);
591 	if (write(BROADFD, &buf, sizeof(buf)) < 0)
592 		return(1);
593 
594 	/*
595 	 * Stay in sync with parent: wait for it to read our first
596 	 * message before sending the second.
597 	 */
598 
599 	FD_ZERO(&fds);
600 	FD_SET(BROADFD, &fds);
601 	if (select(FD_SETSIZE, NULL, &fds, NULL, &timeout) == -1)
602 		return(1);
603 	if (FD_ISSET(BROADFD, &fds)) {
604 		if (write(BROADFD, addr, sizeof(struct sockaddr_in)) < 0)
605 			return(1);
606 	} else {
607 		return(1);
608 	}
609 
610 	close(BROADFD);
611 	return (0);
612 }
613 
614 bool_t broadcast_result(out, addr)
615 bool_t *out;
616 struct sockaddr_in *addr;
617 {
618 	if (retries >= MAX_RETRIES) {
619 		bzero(addr, sizeof(struct sockaddr_in));
620 		if (tell_parent(broad_domain->dom_domain, addr))
621 			syslog(LOG_WARNING, "lost connection to parent");
622 		return (TRUE);
623 	}
624 
625 	if (yp_restricted && verify(addr->sin_addr)) {
626 		retries++;
627 		syslog(LOG_NOTICE, "NIS server at %s not in restricted mode access list -- rejecting.\n",inet_ntoa(addr->sin_addr));
628 		return (FALSE);
629 	} else {
630 		if (tell_parent(broad_domain->dom_domain, addr))
631 			syslog(LOG_WARNING, "lost connection to parent");
632 		return (TRUE);
633 	}
634 }
635 
636 /*
637  * The right way to send RPC broadcasts.
638  * Use the clnt_broadcast() RPC service. Unfortunately, clnt_broadcast()
639  * blocks while waiting for replies, so we have to fork off separate
640  * broadcaster processes that do the waiting and then transmit their
641  * results back to the parent for processing. We also have to remember
642  * to save the name of the domain we're trying to bind in a global
643  * variable since clnt_broadcast() provides no way to pass things to
644  * the 'eachresult' callback function.
645  */
646 void
647 broadcast(struct _dom_binding *ypdb)
648 {
649 	bool_t out = FALSE;
650 	enum clnt_stat stat;
651 
652 	if (children >= MAX_CHILDREN || ypdb->dom_broadcast_pid)
653 		return;
654 
655 	if (pipe(ypdb->dom_pipe_fds) < 0) {
656 		syslog(LOG_WARNING, "pipe: %m");
657 		return;
658 	}
659 
660 	if (ypdb->dom_vers == -1 && (long)ypdb->dom_server_addr.sin_addr.s_addr) {
661 		if (not_responding_count++ >= NOT_RESPONDING_HYSTERESIS) {
662 			not_responding_count = NOT_RESPONDING_HYSTERESIS;
663 			syslog(LOG_WARNING, "NIS server [%s] for domain \"%s\" not responding",
664 			    inet_ntoa(ypdb->dom_server_addr.sin_addr), ypdb->dom_domain);
665 		}
666 	}
667 
668 	broad_domain = ypdb;
669 	flock(ypdb->dom_lockfd, LOCK_UN);
670 
671 	switch ((ypdb->dom_broadcast_pid = fork())) {
672 	case 0:
673 		close(READFD);
674 		signal(SIGCHLD, SIG_DFL);
675 		signal(SIGTERM, SIG_DFL);
676 		break;
677 	case -1:
678 		syslog(LOG_WARNING, "fork: %m");
679 		close(READFD);
680 		close(WRITEFD);
681 		return;
682 	default:
683 		close(WRITEFD);
684 		FD_SET(READFD, &svc_fdset);
685 		children++;
686 		return;
687 	}
688 
689 	/* Release all locks before doing anything else. */
690 	while (ypbindlist) {
691 		close(ypbindlist->dom_lockfd);
692 		ypbindlist = ypbindlist->dom_pnext;
693 	}
694 	close(yplockfd);
695 
696 	/*
697 	 * Special 'many-cast' behavior. If we're in restricted mode,
698 	 * we have a list of possible server addresses to try. What
699 	 * we can do is transmit to each ypserv's YPPROC_DOMAIN_NONACK
700 	 * procedure and time the replies. Whoever replies fastest
701 	 * gets to be our server. Note that this is not a broadcast
702 	 * operation: we transmit uni-cast datagrams only.
703 	 */
704 	if (yp_restricted && yp_manycast) {
705 		short			port;
706 		int			i;
707 		struct sockaddr_in	sin;
708 
709 		i = __yp_ping(restricted_addrs, yp_restricted,
710 				ypdb->dom_domain, &port);
711 		if (i == -1) {
712 			bzero(&ypdb->dom_server_addr,
713 			    sizeof(struct sockaddr_in));
714 			if (tell_parent(ypdb->dom_domain,
715 				&ypdb->dom_server_addr))
716 			syslog(LOG_WARNING, "lost connection to parent");
717 		} else {
718 			bzero(&sin, sizeof(struct sockaddr_in));
719 			bcopy(&restricted_addrs[i],
720 			    &sin.sin_addr, sizeof(struct in_addr));
721 			sin.sin_family = AF_INET;
722 			sin.sin_port = port;
723 			if (tell_parent(broad_domain->dom_domain, &sin))
724 				syslog(LOG_WARNING,
725 					"lost connection to parent");
726 		}
727 		_exit(0);
728 	}
729 
730 	retries = 0;
731 
732 	{
733 		char *ptr;
734 
735 		ptr = ypdb->dom_domain;
736 		stat = clnt_broadcast(YPPROG, YPVERS, YPPROC_DOMAIN_NONACK,
737 	    		(xdrproc_t)xdr_domainname, &ptr,
738 		        (xdrproc_t)xdr_bool, &out,
739 	    		(resultproc_t)broadcast_result);
740 	}
741 
742 	if (stat != RPC_SUCCESS) {
743 		bzero(&ypdb->dom_server_addr,
744 		    sizeof(struct sockaddr_in));
745 		if (tell_parent(ypdb->dom_domain, &ypdb->dom_server_addr))
746 			syslog(LOG_WARNING, "lost connection to parent");
747 	}
748 
749 	_exit(0);
750 }
751 
752 /*
753  * The right way to check if a server is alive.
754  * Attempt to get a client handle pointing to the server and send a
755  * YPPROC_DOMAIN. If we can't get a handle or we get a reply of FALSE,
756  * we invalidate this binding entry and send out a broadcast to try to
757  * establish a new binding. Note that we treat non-default domains
758  * specially: once bound, we keep tabs on our server, but if it
759  * goes away and fails to respond after one round of broadcasting, we
760  * abandon it until a client specifically references it again. We make
761  * every effort to keep our default domain bound, however, since we
762  * need it to keep the system on its feet.
763  */
764 int
765 ping(struct _dom_binding *ypdb)
766 {
767 	bool_t out;
768 	struct timeval interval, timeout;
769 	enum clnt_stat stat;
770 	int rpcsock = RPC_ANYSOCK;
771 	CLIENT *client_handle;
772 
773 	interval.tv_sec = FAIL_THRESHOLD;
774 	interval.tv_usec = 0;
775 	timeout.tv_sec = FAIL_THRESHOLD;
776 	timeout.tv_usec = 0;
777 
778 	if (ypdb->dom_broadcast_pid)
779 		return(1);
780 
781 	if ((client_handle = clntudp_bufcreate(&ypdb->dom_server_addr,
782 		YPPROG, YPVERS, interval, &rpcsock, RPCSMALLMSGSIZE,
783 		RPCSMALLMSGSIZE)) == (CLIENT *)NULL) {
784 		/* Can't get a handle: we're dead. */
785 		ypdb->dom_alive = 0;
786 		ypdb->dom_vers = -1;
787 		broadcast(ypdb);
788 		return(1);
789 	}
790 
791 	{
792 		char *ptr;
793 
794 		ptr = ypdb->dom_domain;
795 
796 		stat = clnt_call(client_handle, YPPROC_DOMAIN,
797 		    (xdrproc_t)xdr_domainname, &ptr,
798 		    (xdrproc_t)xdr_bool, &out, timeout);
799 		if (stat != RPC_SUCCESS || out == FALSE) {
800 			ypdb->dom_alive = 0;
801 			ypdb->dom_vers = -1;
802 			clnt_destroy(client_handle);
803 			broadcast(ypdb);
804 			return(1);
805 		}
806 	}
807 
808 	clnt_destroy(client_handle);
809 	return(0);
810 }
811 
812 void
813 rpc_received(char *dom, struct sockaddr_in *raddrp, int force)
814 {
815 	struct _dom_binding *ypdb, *prev = NULL;
816 	struct iovec iov[2];
817 	struct ypbind_resp ybr;
818 	char path[MAXPATHLEN];
819 	int fd;
820 
821 	/*printf("returned from %s/%d about %s\n", inet_ntoa(raddrp->sin_addr),
822 	       ntohs(raddrp->sin_port), dom);*/
823 
824 	if (dom == NULL)
825 		return;
826 
827 	for (ypdb = ypbindlist; ypdb; ypdb = ypdb->dom_pnext) {
828 		if (strcmp(ypdb->dom_domain, dom) == 0)
829 			break;
830 		prev = ypdb;
831 	}
832 
833 	if (ypdb && force) {
834 		if (ypdb->dom_broadcast_pid) {
835 			kill(ypdb->dom_broadcast_pid, SIGINT);
836 			close(READFD);
837 			FD_CLR(READFD, &fdsr);
838 			FD_CLR(READFD, &svc_fdset);
839 			READFD = WRITEFD = -1;
840 		}
841 	}
842 
843 	/* if in secure mode, check originating port number */
844 	if ((ypsecuremode && (ntohs(raddrp->sin_port) >= IPPORT_RESERVED))) {
845 	    syslog(LOG_WARNING, "Rejected NIS server on [%s/%d] for domain %s.",
846 		   inet_ntoa(raddrp->sin_addr), ntohs(raddrp->sin_port),
847 		   dom);
848 	    if (ypdb != NULL) {
849 		ypdb->dom_broadcast_pid = 0;
850 		ypdb->dom_alive = 0;
851 	    }
852 	    return;
853 	}
854 
855 	if (raddrp->sin_addr.s_addr == (long)0) {
856 		switch (ypdb->dom_default) {
857 		case 0:
858 			if (prev == NULL)
859 				ypbindlist = ypdb->dom_pnext;
860 			else
861 				prev->dom_pnext = ypdb->dom_pnext;
862 			sprintf(path, "%s/%s.%ld", BINDINGDIR,
863 				ypdb->dom_domain, YPVERS);
864 			close(ypdb->dom_lockfd);
865 			unlink(path);
866 			free(ypdb);
867 			domains--;
868 			return;
869 		case 1:
870 			ypdb->dom_broadcast_pid = 0;
871 			ypdb->dom_alive = 0;
872 			broadcast(ypdb);
873 			return;
874 		default:
875 			break;
876 		}
877 	}
878 
879 	if (ypdb == NULL) {
880 		if (force == 0)
881 			return;
882 		ypdb = (struct _dom_binding *)malloc(sizeof *ypdb);
883 		if (ypdb == NULL) {
884 			syslog(LOG_WARNING, "malloc: %m");
885 			return;
886 		}
887 		bzero(ypdb, sizeof *ypdb);
888 		strncpy(ypdb->dom_domain, dom, sizeof ypdb->dom_domain);
889 		ypdb->dom_lockfd = -1;
890 		ypdb->dom_default = 0;
891 		ypdb->dom_pnext = ypbindlist;
892 		ypbindlist = ypdb;
893 	}
894 
895 	/* We've recovered from a crash: inform the world. */
896 	if (ypdb->dom_vers == -1 && ypdb->dom_server_addr.sin_addr.s_addr) {
897 		if (not_responding_count >= NOT_RESPONDING_HYSTERESIS) {
898 			not_responding_count = 0;
899 			syslog(LOG_WARNING, "NIS server [%s] for domain \"%s\" OK",
900 			    inet_ntoa(raddrp->sin_addr), ypdb->dom_domain);
901 		}
902 	}
903 
904 	bcopy(raddrp, &ypdb->dom_server_addr,
905 		sizeof ypdb->dom_server_addr);
906 
907 	ypdb->dom_vers = YPVERS;
908 	ypdb->dom_alive = 1;
909 	ypdb->dom_broadcast_pid = 0;
910 
911 	if (ypdb->dom_lockfd != -1)
912 		close(ypdb->dom_lockfd);
913 
914 	sprintf(path, "%s/%s.%ld", BINDINGDIR,
915 		ypdb->dom_domain, ypdb->dom_vers);
916 #ifdef O_SHLOCK
917 	if ((fd = open(path, O_CREAT|O_SHLOCK|O_RDWR|O_TRUNC, 0644)) == -1) {
918 		(void)mkdir(BINDINGDIR, 0755);
919 		if ((fd = open(path, O_CREAT|O_SHLOCK|O_RDWR|O_TRUNC, 0644)) == -1)
920 			return;
921 	}
922 #else
923 	if ((fd = open(path, O_CREAT|O_RDWR|O_TRUNC, 0644)) == -1) {
924 		(void)mkdir(BINDINGDIR, 0755);
925 		if ((fd = open(path, O_CREAT|O_RDWR|O_TRUNC, 0644)) == -1)
926 			return;
927 	}
928 	flock(fd, LOCK_SH);
929 #endif
930 
931 	/*
932 	 * ok, if BINDINGDIR exists, and we can create the binding file,
933 	 * then write to it..
934 	 */
935 	ypdb->dom_lockfd = fd;
936 
937 	iov[0].iov_base = (char *)&(udptransp->xp_port);
938 	iov[0].iov_len = sizeof udptransp->xp_port;
939 	iov[1].iov_base = (char *)&ybr;
940 	iov[1].iov_len = sizeof ybr;
941 
942 	bzero(&ybr, sizeof ybr);
943 	ybr.ypbind_status = YPBIND_SUCC_VAL;
944 	*(u_int32_t *)&ybr.ypbind_resp_u.ypbind_bindinfo.ypbind_binding_addr = raddrp->sin_addr.s_addr;
945 	*(u_short *)&ybr.ypbind_resp_u.ypbind_bindinfo.ypbind_binding_port = raddrp->sin_port;
946 
947 	if (writev(ypdb->dom_lockfd, iov, 2) != iov[0].iov_len + iov[1].iov_len) {
948 		syslog(LOG_WARNING, "write: %m");
949 		close(ypdb->dom_lockfd);
950 		ypdb->dom_lockfd = -1;
951 		return;
952 	}
953 }
954 
955 /*
956  * Check address against list of allowed servers. Return 0 if okay,
957  * 1 if not matched.
958  */
959 int
960 verify(struct in_addr addr)
961 {
962 	int i;
963 
964 	for (i = 0; i < RESTRICTED_SERVERS; i++)
965 		if (!bcmp(&addr, &restricted_addrs[i], sizeof(struct in_addr)))
966 			return(0);
967 
968 	return(1);
969 }
970 
971 /*
972  * Try to set restricted mode. We default to normal mode if we can't
973  * resolve the specified hostnames.
974  */
975 void
976 yp_restricted_mode(char *args)
977 {
978 	struct hostent *h;
979 	int i = 0;
980 	char *s;
981 
982 	/* Find the restricted domain. */
983 	if ((s = strsep(&args, ",")) == NULL)
984 		return;
985 	domain_name = s;
986 
987 	/* Get the addresses of the servers. */
988 	while ((s = strsep(&args, ",")) != NULL && i < RESTRICTED_SERVERS) {
989 		if ((h = gethostbyname(s)) == NULL)
990 			return;
991 		bcopy (h->h_addr_list[0], &restricted_addrs[i],
992 		    sizeof(struct in_addr));
993 		i++;
994 	}
995 
996 	/* ypset and ypsetme not allowed with restricted mode */
997 	ypsetmode = YPSET_NO;
998 
999 	yp_restricted = i;
1000 	return;
1001 }
1002