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