xref: /illumos-gate/usr/src/cmd/rpcbind/rpcbind.c (revision a5f69788de7ac07553de47f7fec8c05a9a94c105)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */
26 /* All Rights Reserved */
27 /*
28  * University Copyright- Copyright (c) 1982, 1986, 1988
29  * The Regents of the University of California
30  * All Rights Reserved
31  *
32  * University Acknowledgment- Portions of this document are derived from
33  * software developed by the University of California, Berkeley, and its
34  * contributors.
35  */
36 
37 #pragma ident	"%Z%%M%	%I%	%E% SMI"
38 
39 /*
40  * rpcbind.c
41  * Implements the program, version to address mapping for rpc.
42  *
43  */
44 
45 #include <dlfcn.h>
46 #include <stdio.h>
47 #include <sys/types.h>
48 #include <unistd.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <rpc/rpc.h>
52 #include <netconfig.h>
53 #include <netdir.h>
54 #include <errno.h>
55 #include <sys/wait.h>
56 #include <signal.h>
57 #include <string.h>
58 #include <stdlib.h>
59 #include <thread.h>
60 #include <synch.h>
61 #include <deflt.h>
62 #include <stdarg.h>
63 #ifdef PORTMAP
64 #include <netinet/in.h>
65 #endif
66 #include <arpa/inet.h>
67 #include <sys/termios.h>
68 #include "rpcbind.h"
69 #include <sys/syslog.h>
70 #include <sys/stat.h>
71 #include <syslog.h>
72 #include <string.h>
73 #include <sys/time.h>
74 #include <sys/resource.h>
75 #include <rpcsvc/daemon_utils.h>
76 #include <priv_utils.h>
77 #include <libscf.h>
78 
79 #ifdef PORTMAP
80 extern void pmap_service(struct svc_req *, SVCXPRT *xprt);
81 #endif
82 extern void rpcb_service_3(struct svc_req *, SVCXPRT *xprt);
83 extern void rpcb_service_4(struct svc_req *, SVCXPRT *xprt);
84 extern void read_warmstart(void);
85 extern void write_warmstart(void);
86 extern int Is_ipv6present(void);
87 
88 #define	MAX_FILEDESC_LIMIT	1023
89 
90 static void terminate(int);
91 static void detachfromtty(void);
92 static void parseargs(int, char *[]);
93 static void rbllist_add(ulong_t, ulong_t, struct netconfig *, struct netbuf *);
94 static int init_transport(struct netconfig *);
95 static int check_netconfig(void);
96 
97 static boolean_t check_hostserv(struct netconfig *, const char *, const char *);
98 static void rpcb_check_init(void);
99 static int setopt_reuseaddr(int);
100 static int setopt_anon_mlp(int);
101 static int setup_callit(int);
102 
103 /* Global variables */
104 #ifdef ND_DEBUG
105 int debugging = 1;	/* Tell me what's going on */
106 #else
107 int debugging = 0;	/* Tell me what's going on */
108 #endif
109 static int ipv6flag = 0;
110 int doabort = 0;	/* When debugging, do an abort on errors */
111 static int listen_backlog = 64;
112 rpcblist_ptr list_rbl;	/* A list of version 3/4 rpcbind services */
113 char *loopback_dg;	/* Datagram loopback transport, for set and unset */
114 char *loopback_vc;	/* COTS loopback transport, for set and unset */
115 char *loopback_vc_ord;	/* COTS_ORD loopback transport, for set and unset */
116 
117 boolean_t verboselog = B_FALSE;
118 boolean_t wrap_enabled = B_FALSE;
119 boolean_t allow_indirect = B_TRUE;
120 
121 /* Local Variable */
122 static int warmstart = 0;	/* Grab a old copy of registrations */
123 
124 #ifdef PORTMAP
125 PMAPLIST *list_pml;	/* A list of version 2 rpcbind services */
126 char *udptrans;		/* Name of UDP transport */
127 char *tcptrans;		/* Name of TCP transport */
128 char *udp_uaddr;	/* Universal UDP address */
129 char *tcp_uaddr;	/* Universal TCP address */
130 #endif
131 static char servname[] = "rpcbind";
132 static char superuser[] = "superuser";
133 
134 static const char daemon_dir[] = DAEMON_DIR;
135 
136 int
137 main(int argc, char *argv[])
138 {
139 	struct netconfig *nconf;
140 	void *nc_handle;	/* Net config handle */
141 	struct rlimit rl;
142 	int maxrecsz = RPC_MAXDATASIZE;
143 	boolean_t can_do_mlp;
144 
145 	parseargs(argc, argv);
146 
147 	getrlimit(RLIMIT_NOFILE, &rl);
148 
149 	if (rl.rlim_cur < MAX_FILEDESC_LIMIT) {
150 		if (rl.rlim_max <= MAX_FILEDESC_LIMIT)
151 			rl.rlim_cur = rl.rlim_max;
152 		else
153 			rl.rlim_cur = MAX_FILEDESC_LIMIT;
154 		setrlimit(RLIMIT_NOFILE, &rl);
155 	}
156 	openlog("rpcbind", LOG_CONS, LOG_DAEMON);
157 
158 	/*
159 	 * Create the daemon directory in /var/run
160 	 */
161 	if (mkdir(daemon_dir, DAEMON_DIR_MODE) == 0 || errno == EEXIST) {
162 		chmod(daemon_dir, DAEMON_DIR_MODE);
163 		chown(daemon_dir, DAEMON_UID, DAEMON_GID);
164 	} else {
165 		syslog(LOG_ERR, "failed to create \"%s\": %m", daemon_dir);
166 	}
167 
168 	/*
169 	 * These privileges are required for the t_bind check rpcbind uses
170 	 * to determine whether a service is still live or not.
171 	 */
172 	can_do_mlp = priv_ineffect(PRIV_NET_BINDMLP);
173 	if (__init_daemon_priv(PU_RESETGROUPS|PU_CLEARLIMITSET, DAEMON_UID,
174 	    DAEMON_GID, PRIV_NET_PRIVADDR, PRIV_SYS_NFS,
175 	    can_do_mlp ? PRIV_NET_BINDMLP : NULL, NULL) == -1) {
176 		fprintf(stderr, "Insufficient privileges\n");
177 		exit(1);
178 	}
179 
180 	/*
181 	 * Enable non-blocking mode and maximum record size checks for
182 	 * connection oriented transports.
183 	 */
184 	if (!rpc_control(RPC_SVC_CONNMAXREC_SET, &maxrecsz)) {
185 		syslog(LOG_INFO, "unable to set RPC max record size");
186 	}
187 
188 	nc_handle = setnetconfig(); 	/* open netconfig file */
189 	if (nc_handle == NULL) {
190 		syslog(LOG_ERR, "could not read /etc/netconfig");
191 		exit(1);
192 	}
193 	loopback_dg = "";
194 	loopback_vc = "";
195 	loopback_vc_ord = "";
196 #ifdef PORTMAP
197 	udptrans = "";
198 	tcptrans = "";
199 #endif
200 
201 	{
202 		/*
203 		 * rpcbind is the first application to encounter the
204 		 * various netconfig files.  check_netconfig() verifies
205 		 * that they are set up correctly and complains loudly
206 		 * if not.
207 		 */
208 		int trouble;
209 
210 		trouble = check_netconfig();
211 		if (trouble) {
212 			syslog(LOG_ERR,
213 	"%s: found %d errors with network configuration files. Exiting.",
214 				argv[0], trouble);
215 			fprintf(stderr,
216 	"%s: found %d errors with network configuration files. Exiting.\n",
217 				argv[0], trouble);
218 			exit(1);
219 		}
220 	}
221 	ipv6flag = Is_ipv6present();
222 	rpcb_check_init();
223 	while (nconf = getnetconfig(nc_handle)) {
224 		if (nconf->nc_flag & NC_VISIBLE)
225 			init_transport(nconf);
226 	}
227 	endnetconfig(nc_handle);
228 
229 	if ((loopback_dg[0] == NULL) && (loopback_vc[0] == NULL) &&
230 		(loopback_vc_ord[0] == NULL)) {
231 		syslog(LOG_ERR, "could not find loopback transports");
232 		exit(1);
233 	}
234 
235 	/* catch the usual termination signals for graceful exit */
236 	(void) signal(SIGINT, terminate);
237 	(void) signal(SIGTERM, terminate);
238 	(void) signal(SIGQUIT, terminate);
239 	/* ignore others that could get sent */
240 	(void) signal(SIGHUP, SIG_IGN);
241 	(void) signal(SIGUSR1, SIG_IGN);
242 	(void) signal(SIGUSR2, SIG_IGN);
243 	if (warmstart) {
244 		read_warmstart();
245 	}
246 	if (debugging) {
247 		printf("rpcbind debugging enabled.");
248 		if (doabort) {
249 			printf("  Will abort on errors!\n");
250 		} else {
251 			printf("\n");
252 		}
253 	} else {
254 		detachfromtty();
255 	}
256 
257 	/* These are basic privileges we do not need */
258 	__fini_daemon_priv(PRIV_PROC_EXEC, PRIV_PROC_SESSION,
259 	    PRIV_FILE_LINK_ANY, PRIV_PROC_INFO, (char *)NULL);
260 
261 	my_svc_run();
262 	syslog(LOG_ERR, "svc_run returned unexpectedly");
263 	rpcbind_abort();
264 	/* NOTREACHED */
265 }
266 
267 /*
268  * Increments a counter each time a problem is found with the network
269  * configuration information.
270  */
271 static int
272 check_netconfig(void)
273 {
274 	void	*nc;
275 	void	*dlcookie;
276 	int	busted = 0;
277 	int	i;
278 	int	lo_clts_found = 0, lo_cots_found = 0, lo_cotsord_found = 0;
279 	struct netconfig	*nconf, *np;
280 	struct stat	sb;
281 
282 	nc = setnetconfig();
283 	if (nc == NULL) {
284 		if (debugging)
285 			fprintf(stderr,
286 				"setnetconfig() failed:  %s\n", nc_sperror());
287 		syslog(LOG_ALERT, "setnetconfig() failed:  %s", nc_sperror());
288 		return (1);
289 	}
290 	while (np = getnetconfig(nc)) {
291 		if ((np->nc_flag & NC_VISIBLE) == 0)
292 			continue;
293 		if (debugging)
294 			fprintf(stderr, "checking netid \"%s\"\n",
295 				np->nc_netid);
296 		if (strcmp(np->nc_protofmly, NC_LOOPBACK) == 0)
297 			switch (np->nc_semantics) {
298 			case NC_TPI_CLTS:
299 				lo_clts_found = 1;
300 				break;
301 
302 			case NC_TPI_COTS:
303 				lo_cots_found = 1;
304 				break;
305 
306 			case NC_TPI_COTS_ORD:
307 				lo_cotsord_found = 1;
308 				break;
309 			}
310 		if (stat(np->nc_device, &sb) == -1 && errno == ENOENT) {
311 			if (debugging)
312 				fprintf(stderr, "\tdevice %s does not exist\n",
313 					np->nc_device);
314 			syslog(LOG_ERR, "netid %s:  device %s does not exist",
315 				np->nc_netid, np->nc_device);
316 			busted++;
317 		} else
318 			if (debugging)
319 				fprintf(stderr, "\tdevice %s present\n",
320 					np->nc_device);
321 		for (i = 0; i < np->nc_nlookups; i++) {
322 			char	*libname = np->nc_lookups[i];
323 
324 			if ((dlcookie = dlopen(libname, RTLD_LAZY)) == NULL) {
325 				char *dlerrstr;
326 
327 				dlerrstr = dlerror();
328 				if (debugging) {
329 					fprintf(stderr,
330 	"\tnetid %s: dlopen of name-to-address library %s failed\ndlerror: %s",
331 	np->nc_netid, libname, dlerrstr ? dlerrstr : "");
332 				}
333 				syslog(LOG_ERR,
334 	"netid %s:  dlopen of name-to-address library %s failed",
335 						np->nc_netid, libname);
336 				if (dlerrstr)
337 					syslog(LOG_ERR, "%s", dlerrstr);
338 				busted++;
339 			} else {
340 				if (debugging)
341 					fprintf(stderr,
342 	"\tdlopen of name-to-address library %s succeeded\n", libname);
343 				(void) dlclose(dlcookie);
344 			}
345 		}
346 		nconf = getnetconfigent(np->nc_netid);
347 
348 		if (!check_hostserv(nconf, HOST_SELF, ""))
349 			busted++;
350 		if (!check_hostserv(nconf, HOST_SELF_CONNECT, ""))
351 			busted++;
352 		if (!check_hostserv(nconf, HOST_SELF, "rpcbind"))
353 			busted++;
354 		if (!check_hostserv(nconf, HOST_SELF_CONNECT, "rpcbind"))
355 			busted++;
356 
357 		freenetconfigent(nconf);
358 	}
359 	endnetconfig(nc);
360 
361 	if (lo_clts_found) {
362 		if (debugging)
363 			fprintf(stderr, "Found CLTS loopback transport\n");
364 	} else {
365 		syslog(LOG_ALERT, "no CLTS loopback transport found\n");
366 		if (debugging)
367 			fprintf(stderr, "no CLTS loopback transport found\n");
368 	}
369 	if (lo_cots_found) {
370 		if (debugging)
371 			fprintf(stderr, "Found COTS loopback transport\n");
372 	} else {
373 		syslog(LOG_ALERT, "no COTS loopback transport found\n");
374 		if (debugging)
375 			fprintf(stderr, "no COTS loopback transport found\n");
376 	}
377 	if (lo_cotsord_found) {
378 		if (debugging)
379 			fprintf(stderr, "Found COTS ORD loopback transport\n");
380 	} else {
381 		syslog(LOG_ALERT, "no COTS ORD loopback transport found\n");
382 		if (debugging)
383 			fprintf(stderr,
384 				"no COTS ORD loopback transport found\n");
385 	}
386 
387 	return (busted);
388 }
389 
390 /*
391  * Adds the entry into the rpcbind database.
392  * If PORTMAP, then for UDP and TCP, it adds the entries for version 2 also
393  * Returns 0 if succeeds, else fails
394  */
395 static int
396 init_transport(struct netconfig *nconf)
397 {
398 	int fd;
399 	struct t_bind *taddr, *baddr;
400 	SVCXPRT	*my_xprt;
401 	struct nd_addrlist *nas;
402 	struct nd_hostserv hs;
403 	int status;	/* bound checking ? */
404 	static int msgprt = 0;
405 
406 	if ((nconf->nc_semantics != NC_TPI_CLTS) &&
407 		(nconf->nc_semantics != NC_TPI_COTS) &&
408 		(nconf->nc_semantics != NC_TPI_COTS_ORD))
409 		return (1);	/* not my type */
410 
411 	if ((strcmp(nconf->nc_protofmly, NC_INET6) == 0) && !ipv6flag) {
412 		if (!msgprt)
413 			syslog(LOG_DEBUG,
414 "/etc/netconfig has IPv6 entries but IPv6 is not configured");
415 		msgprt++;
416 		return (1);
417 	}
418 #ifdef ND_DEBUG
419 	{
420 	int i;
421 	char **s;
422 
423 	(void) fprintf(stderr, "%s: %d lookup routines :\n",
424 		nconf->nc_netid, nconf->nc_nlookups);
425 	for (i = 0, s = nconf->nc_lookups; i < nconf->nc_nlookups; i++, s++)
426 		fprintf(stderr, "[%d] - %s\n", i, *s);
427 	}
428 #endif
429 
430 	if ((fd = t_open(nconf->nc_device, O_RDWR, NULL)) < 0) {
431 		syslog(LOG_ERR, "%s: cannot open connection: %s",
432 				nconf->nc_netid, t_errlist[t_errno]);
433 		return (1);
434 	}
435 
436 	if (is_system_labeled() &&
437 	    (strcmp(nconf->nc_protofmly, NC_INET) == 0 ||
438 	    strcmp(nconf->nc_protofmly, NC_INET6) == 0) &&
439 	    setopt_anon_mlp(fd) == -1) {
440 		syslog(LOG_ERR, "%s: couldn't set SO_ANON_MLP option",
441 		    nconf->nc_netid);
442 	}
443 
444 	/*
445 	 * Negotiate for returning the ucred of the caller. This should
446 	 * done before enabling the endpoint for service via
447 	 * t_bind() so that requests to rpcbind contain the uid.
448 	 */
449 	svc_fd_negotiate_ucred(fd);
450 
451 	taddr = (struct t_bind *)t_alloc(fd, T_BIND, T_ADDR);
452 	baddr = (struct t_bind *)t_alloc(fd, T_BIND, T_ADDR);
453 	if ((baddr == NULL) || (taddr == NULL)) {
454 		syslog(LOG_ERR, "%s: cannot allocate netbuf: %s",
455 				nconf->nc_netid, t_errlist[t_errno]);
456 		exit(1);
457 	}
458 
459 	/* Get rpcbind's address on this transport */
460 	hs.h_host = HOST_SELF;
461 	hs.h_serv = servname;
462 	if (netdir_getbyname(nconf, &hs, &nas))
463 		goto error;
464 
465 	/* Copy the address */
466 	taddr->addr.len = nas->n_addrs->len;
467 	memcpy(taddr->addr.buf, nas->n_addrs->buf, (int)nas->n_addrs->len);
468 #ifdef ND_DEBUG
469 	{
470 	/* for debugging print out our universal address */
471 	char *uaddr;
472 
473 	uaddr = taddr2uaddr(nconf, nas->n_addrs);
474 	(void) fprintf(stderr, "rpcbind : my address is %s\n", uaddr);
475 	(void) free(uaddr);
476 	}
477 #endif
478 	netdir_free((char *)nas, ND_ADDRLIST);
479 
480 	if (nconf->nc_semantics == NC_TPI_CLTS)
481 		taddr->qlen = 0;
482 	else
483 		taddr->qlen = listen_backlog;
484 
485 	if (strcmp(nconf->nc_proto, NC_TCP) == 0) {
486 		/*
487 		 * Sm: If we are running then set SO_REUSEADDR option
488 		 * so that we can bind to our preferred address even if
489 		 * previous connections are in FIN_WAIT state
490 		 */
491 #ifdef ND_DEBUG
492 		fprintf(stdout, "Setting SO_REUSEADDR.\n");
493 #endif
494 		if (setopt_reuseaddr(fd) == -1) {
495 			syslog(LOG_ERR, "Couldn't set SO_REUSEADDR option");
496 		}
497 	}
498 
499 	if (t_bind(fd, taddr, baddr) != 0) {
500 		syslog(LOG_ERR, "%s: cannot bind: %s",
501 			nconf->nc_netid, t_errlist[t_errno]);
502 		goto error;
503 	}
504 
505 
506 	if (memcmp(taddr->addr.buf, baddr->addr.buf, (int)baddr->addr.len)) {
507 		syslog(LOG_ERR, "%s: address in use", nconf->nc_netid);
508 		goto error;
509 	}
510 
511 	my_xprt = (SVCXPRT *)svc_tli_create(fd, nconf, baddr, 0, 0);
512 	if (my_xprt == (SVCXPRT *)NULL) {
513 		syslog(LOG_ERR, "%s: could not create service",
514 				nconf->nc_netid);
515 		goto error;
516 	}
517 
518 	/* set up multicast address for RPC CALL_IT, IPv6 */
519 
520 	if ((strcmp(nconf->nc_protofmly, NC_INET6) == 0) &&
521 	    (strcmp(nconf->nc_proto, NC_UDP) == 0)) {
522 		if (setup_callit(fd) < 0) {
523 			syslog(LOG_ERR, "Unable to join IPv6 multicast group \
524 for rpc broadcast %s", RPCB_MULTICAST_ADDR);
525 		}
526 	}
527 
528 	if (strcmp(nconf->nc_proto, NC_TCP) == 0) {
529 			svc_control(my_xprt, SVCSET_KEEPALIVE, (void *) TRUE);
530 	}
531 
532 #ifdef PORTMAP
533 	/*
534 	 * Register both the versions for tcp/ip and udp/ip
535 	 */
536 	if ((strcmp(nconf->nc_protofmly, NC_INET) == 0) &&
537 		((strcmp(nconf->nc_proto, NC_TCP) == 0) ||
538 		(strcmp(nconf->nc_proto, NC_UDP) == 0))) {
539 		PMAPLIST *pml;
540 
541 		if (!svc_register(my_xprt, PMAPPROG, PMAPVERS,
542 			pmap_service, NULL)) {
543 			syslog(LOG_ERR, "could not register on %s",
544 					nconf->nc_netid);
545 			goto error;
546 		}
547 		pml = (PMAPLIST *)malloc((uint_t)sizeof (PMAPLIST));
548 		if (pml == (PMAPLIST *)NULL) {
549 			syslog(LOG_ERR, "no memory!");
550 			exit(1);
551 		}
552 		pml->pml_map.pm_prog = PMAPPROG;
553 		pml->pml_map.pm_vers = PMAPVERS;
554 		pml->pml_map.pm_port = PMAPPORT;
555 		if (strcmp(nconf->nc_proto, NC_TCP) == 0) {
556 			if (tcptrans[0]) {
557 				syslog(LOG_ERR,
558 				"cannot have more than one TCP transport");
559 				goto error;
560 			}
561 			tcptrans = strdup(nconf->nc_netid);
562 			pml->pml_map.pm_prot = IPPROTO_TCP;
563 
564 			/* Let's snarf the universal address */
565 			/* "h1.h2.h3.h4.p1.p2" */
566 			tcp_uaddr = taddr2uaddr(nconf, &baddr->addr);
567 		} else {
568 			if (udptrans[0]) {
569 				syslog(LOG_ERR,
570 				"cannot have more than one UDP transport");
571 				goto error;
572 			}
573 			udptrans = strdup(nconf->nc_netid);
574 			pml->pml_map.pm_prot = IPPROTO_UDP;
575 
576 			/* Let's snarf the universal address */
577 			/* "h1.h2.h3.h4.p1.p2" */
578 			udp_uaddr = taddr2uaddr(nconf, &baddr->addr);
579 		}
580 		pml->pml_next = list_pml;
581 		list_pml = pml;
582 
583 		/* Add version 3 information */
584 		pml = (PMAPLIST *)malloc((uint_t)sizeof (PMAPLIST));
585 		if (pml == (PMAPLIST *)NULL) {
586 			syslog(LOG_ERR, "no memory!");
587 			exit(1);
588 		}
589 		pml->pml_map = list_pml->pml_map;
590 		pml->pml_map.pm_vers = RPCBVERS;
591 		pml->pml_next = list_pml;
592 		list_pml = pml;
593 
594 		/* Add version 4 information */
595 		pml = (PMAPLIST *)malloc((uint_t)sizeof (PMAPLIST));
596 		if (pml == (PMAPLIST *)NULL) {
597 			syslog(LOG_ERR, "no memory!");
598 			exit(1);
599 		}
600 		pml->pml_map = list_pml->pml_map;
601 		pml->pml_map.pm_vers = RPCBVERS4;
602 		pml->pml_next = list_pml;
603 		list_pml = pml;
604 
605 		/* Also add version 2 stuff to rpcbind list */
606 		rbllist_add(PMAPPROG, PMAPVERS, nconf, &baddr->addr);
607 	}
608 #endif
609 
610 	/* version 3 registration */
611 	if (!svc_reg(my_xprt, RPCBPROG, RPCBVERS, rpcb_service_3, NULL)) {
612 		syslog(LOG_ERR, "could not register %s version 3",
613 				nconf->nc_netid);
614 		goto error;
615 	}
616 	rbllist_add(RPCBPROG, RPCBVERS, nconf, &baddr->addr);
617 
618 	/* version 4 registration */
619 	if (!svc_reg(my_xprt, RPCBPROG, RPCBVERS4, rpcb_service_4, NULL)) {
620 		syslog(LOG_ERR, "could not register %s version 4",
621 				nconf->nc_netid);
622 		goto error;
623 	}
624 	rbllist_add(RPCBPROG, RPCBVERS4, nconf, &baddr->addr);
625 
626 	if (strcmp(nconf->nc_protofmly, NC_LOOPBACK) == 0) {
627 		if (nconf->nc_semantics == NC_TPI_CLTS)
628 			loopback_dg = strdup(nconf->nc_netid);
629 		else if (nconf->nc_semantics == NC_TPI_COTS)
630 			loopback_vc = strdup(nconf->nc_netid);
631 		else if (nconf->nc_semantics == NC_TPI_COTS_ORD)
632 			loopback_vc_ord = strdup(nconf->nc_netid);
633 	}
634 
635 	/* decide if bound checking works for this transport */
636 	status = add_bndlist(nconf, taddr, baddr);
637 #ifdef BIND_DEBUG
638 	if (status < 0) {
639 		fprintf(stderr, "Error in finding bind status for %s\n",
640 			nconf->nc_netid);
641 	} else if (status == 0) {
642 		fprintf(stderr, "check binding for %s\n",
643 			nconf->nc_netid);
644 	} else if (status > 0) {
645 		fprintf(stderr, "No check binding for %s\n",
646 			nconf->nc_netid);
647 	}
648 #endif
649 	/*
650 	 * rmtcall only supported on CLTS transports for now.
651 	 * only needed when we are allowing indirect calls
652 	 */
653 	if (allow_indirect && nconf->nc_semantics == NC_TPI_CLTS) {
654 		status = create_rmtcall_fd(nconf);
655 
656 #ifdef BIND_DEBUG
657 		if (status < 0) {
658 			fprintf(stderr, "Could not create rmtcall fd for %s\n",
659 				nconf->nc_netid);
660 		} else {
661 			fprintf(stderr, "rmtcall fd for %s is %d\n",
662 				nconf->nc_netid, status);
663 		}
664 #endif
665 	}
666 	(void) t_free((char *)taddr, T_BIND);
667 	(void) t_free((char *)baddr, T_BIND);
668 	return (0);
669 error:
670 	(void) t_free((char *)taddr, T_BIND);
671 	(void) t_free((char *)baddr, T_BIND);
672 	(void) t_close(fd);
673 	return (1);
674 }
675 
676 static void
677 rbllist_add(ulong_t prog, ulong_t vers, struct netconfig *nconf,
678 	struct netbuf *addr)
679 {
680 	rpcblist_ptr rbl;
681 
682 	rbl = (rpcblist_ptr)malloc((uint_t)sizeof (rpcblist));
683 	if (rbl == (rpcblist_ptr)NULL) {
684 		syslog(LOG_ERR, "no memory!");
685 		exit(1);
686 	}
687 
688 	rbl->rpcb_map.r_prog = prog;
689 	rbl->rpcb_map.r_vers = vers;
690 	rbl->rpcb_map.r_netid = strdup(nconf->nc_netid);
691 	rbl->rpcb_map.r_addr = taddr2uaddr(nconf, addr);
692 	rbl->rpcb_map.r_owner = strdup(superuser);
693 	rbl->rpcb_next = list_rbl;	/* Attach to global list */
694 	list_rbl = rbl;
695 }
696 
697 /*
698  * Catch the signal and die
699  */
700 /* ARGSUSED */
701 static void
702 terminate(int sig)
703 {
704 	syslog(LOG_ERR, "rpcbind terminating on signal.");
705 	write_warmstart();	/* Dump yourself */
706 	exit(2);
707 }
708 
709 void
710 rpcbind_abort(void)
711 {
712 	write_warmstart();	/* Dump yourself */
713 	abort();
714 }
715 
716 /*
717  * detach from tty
718  */
719 static void
720 detachfromtty(void)
721 {
722 	close(0);
723 	close(1);
724 	close(2);
725 	switch (forkall()) {
726 	case (pid_t)-1:
727 		perror("fork");
728 		break;
729 	case 0:
730 		break;
731 	default:
732 		exit(0);
733 	}
734 	setsid();
735 	(void) open("/dev/null", O_RDWR, 0);
736 	dup(0);
737 	dup(0);
738 }
739 
740 /* get command line options */
741 static void
742 parseargs(int argc, char *argv[])
743 {
744 	int c;
745 	int tmp;
746 
747 	while ((c = getopt(argc, argv, "dwal:")) != EOF) {
748 		switch (c) {
749 		case 'd':
750 			debugging = 1;
751 			break;
752 		case 'a':
753 			doabort = 1;	/* when debugging, do an abort on */
754 			break;		/* errors; for rpcbind developers */
755 					/* only! */
756 		case 'w':
757 			warmstart = 1;
758 			break;
759 
760 		case 'l':
761 			if (sscanf(optarg, "%d", &tmp)) {
762 				if (tmp > listen_backlog) {
763 					listen_backlog = tmp;
764 				}
765 			}
766 			break;
767 		default:	/* error */
768 			fprintf(stderr,
769 			"usage: rpcbind [-d] [-w] [-l listen_backlog]\n");
770 			exit(1);
771 		}
772 	}
773 	if (doabort && !debugging) {
774 	    fprintf(stderr,
775 		"-a (abort) specified without -d (debugging) -- ignored.\n");
776 	    doabort = 0;
777 	}
778 }
779 
780 static int
781 setopt_int(int fd, int level, int name, int value)
782 {
783 	struct t_optmgmt req, resp;
784 	struct {
785 		struct opthdr opt;
786 		int value;
787 	} optdata;
788 
789 	optdata.opt.level = level;
790 	optdata.opt.name = name;
791 	optdata.opt.len = sizeof (int);
792 
793 	optdata.value = value;
794 
795 	req.flags = T_NEGOTIATE;
796 	req.opt.len = sizeof (optdata);
797 	req.opt.buf = (char *)&optdata;
798 
799 	resp.flags = 0;
800 	resp.opt.buf = (char *)&optdata;
801 	resp.opt.maxlen = sizeof (optdata);
802 
803 	if (t_optmgmt(fd, &req, &resp) < 0 || resp.flags != T_SUCCESS) {
804 		t_error("t_optmgmt");
805 		return (-1);
806 	}
807 	return (0);
808 }
809 
810 static int
811 setopt_reuseaddr(int fd)
812 {
813 	return (setopt_int(fd, SOL_SOCKET, SO_REUSEADDR, 1));
814 }
815 
816 static int
817 setopt_anon_mlp(int fd)
818 {
819 	return (setopt_int(fd, SOL_SOCKET, SO_ANON_MLP, 1));
820 }
821 
822 static int
823 setup_callit(int fd)
824 {
825 	struct ipv6_mreq mreq;
826 	struct t_optmgmt req, resp;
827 	struct opthdr *opt;
828 	char reqbuf[ sizeof (struct ipv6_mreq) + 24];
829 	struct ipv6_mreq *pmreq;
830 
831 	opt = (struct opthdr *)reqbuf;
832 
833 	opt->level = IPPROTO_IPV6;
834 	opt->name = IPV6_ADD_MEMBERSHIP;
835 	opt->len = sizeof (struct ipv6_mreq);
836 
837 	/* multicast address */
838 	(void) inet_pton(AF_INET6, RPCB_MULTICAST_ADDR,
839 		mreq.ipv6mr_multiaddr.s6_addr);
840 	mreq.ipv6mr_interface = 0;
841 
842 	/* insert it into opt */
843 	pmreq = (struct ipv6_mreq *)&reqbuf[sizeof (struct opthdr)];
844 	memcpy(pmreq, &mreq, sizeof (struct ipv6_mreq));
845 
846 	req.flags = T_NEGOTIATE;
847 	req.opt.len = sizeof (struct opthdr) + opt->len;
848 	req.opt.buf = (char *)opt;
849 
850 	resp.flags = 0;
851 	resp.opt.buf = reqbuf;
852 	resp.opt.maxlen = sizeof (reqbuf);
853 
854 	if (t_optmgmt(fd, &req, &resp) < 0 || resp.flags != T_SUCCESS) {
855 		t_error("t_optmgmt");
856 		return (-1);
857 	}
858 	return (0);
859 }
860 
861 static boolean_t
862 check_hostserv(struct netconfig *nconf, const char *host, const char *serv)
863 {
864 	struct nd_hostserv nh;
865 	struct nd_addrlist *na;
866 	const char *hostname = host;
867 	const char *servname = serv;
868 	int retval;
869 
870 	if (strcmp(host, HOST_SELF) == 0)
871 		hostname = "HOST_SELF";
872 	else if (strcmp(host, HOST_SELF_CONNECT) == 0)
873 		hostname = "HOST_SELF_CONNECT";
874 
875 	if (serv[0] == '\0')
876 		servname = "<any>";
877 
878 	nh.h_host = (char *)host;
879 	nh.h_serv = (char *)serv;
880 
881 	retval = netdir_getbyname(nconf, &nh, &na);
882 	if (retval != ND_OK || na->n_cnt == 0) {
883 		if (retval == ND_OK)
884 			netdir_free(na, ND_ADDRLIST);
885 
886 		syslog(LOG_ALERT, "netid %s: cannot find an address for host "
887 		    "%s, service \"%s\"", nconf->nc_netid, hostname, servname);
888 		if (debugging) {
889 			(void) fprintf(stderr, "\tnetdir_getbyname for %s, "
890 			    "service \"%s\" failed\n", hostname, servname);
891 		}
892 		return (B_FALSE);
893 	}
894 	netdir_free(na, ND_ADDRLIST);
895 
896 	if (debugging) {
897 		(void) fprintf(stderr, "\tnetdir_getbyname for %s, service "
898 		    "service \"%s\" succeeded\n", hostname, servname);
899 	}
900 	return (B_TRUE);
901 }
902 
903 #define	DEFRPCBIND	"/etc/default/rpcbind"
904 
905 /* Maximum outstanding syslog requests */
906 #define	MAXLOG		100
907 /* Maximum length: the messages generated are fairly short; no hostnames. */
908 #define	MAXMSG		128
909 
910 typedef struct logmsg {
911 	struct logmsg	*log_next;
912 	int		log_pri;
913 	char		log_msg[MAXMSG];
914 } logmsg;
915 
916 static logmsg *loghead = NULL;
917 static logmsg **logtailp = &loghead;
918 static mutex_t logmutex = DEFAULTMUTEX;
919 static cond_t logcond = DEFAULTCV;
920 static int logcount = 0;
921 
922 /*ARGSUSED*/
923 static void *
924 logthread(void *arg)
925 {
926 	while (1) {
927 		logmsg *msg;
928 		(void) mutex_lock(&logmutex);
929 		while ((msg = loghead) == NULL)
930 			(void) cond_wait(&logcond, &logmutex);
931 
932 		loghead = msg->log_next;
933 		logcount--;
934 		if (loghead == NULL) {
935 			logtailp = &loghead;
936 			logcount = 0;
937 		}
938 		(void) mutex_unlock(&logmutex);
939 		syslog(msg->log_pri, "%s", msg->log_msg);
940 		free(msg);
941 	}
942 	/* NOTREACHED */
943 }
944 
945 /*
946  * Initialize: read the configuration parameters from the default file.
947  */
948 static void
949 rpcb_check_init(void)
950 {
951 	thread_t tid;
952 	scf_simple_prop_t *prop;
953 	uint8_t	*bool;
954 
955 	if ((prop = scf_simple_prop_get(NULL, NULL, "config",
956 	    "enable_tcpwrappers")) != NULL) {
957 
958 		if ((bool = scf_simple_prop_next_boolean(prop)) != NULL) {
959 			wrap_enabled = (*bool == 0) ? B_FALSE : B_TRUE;
960 		} else {
961 			syslog(LOG_ALERT, "enable_tcpwrappers no value %s",
962 			    scf_strerror(scf_error()));
963 		}
964 		scf_simple_prop_free(prop);
965 	} else {
966 		syslog(LOG_ALERT, "unable to get enable_tcpwrappers %s",
967 		    scf_strerror(scf_error()));
968 	}
969 	if ((prop = scf_simple_prop_get(NULL, NULL, "config",
970 	    "verbose_logging")) != NULL) {
971 
972 		if ((bool = scf_simple_prop_next_boolean(prop)) != NULL) {
973 			verboselog = (*bool == 0) ? B_FALSE : B_TRUE;
974 		} else {
975 			syslog(LOG_ALERT, "verboselog no value %s",
976 			    scf_strerror(scf_error()));
977 		}
978 		scf_simple_prop_free(prop);
979 	} else {
980 		syslog(LOG_ALERT, "unable to get verbose_logging %s",
981 		    scf_strerror(scf_error()));
982 	}
983 	if ((prop = scf_simple_prop_get(NULL, NULL, "config",
984 	    "allow_indirect")) != NULL) {
985 
986 		if ((bool = scf_simple_prop_next_boolean(prop)) != NULL) {
987 			allow_indirect = (*bool == 0) ? B_FALSE : B_TRUE;
988 		} else {
989 			syslog(LOG_ALERT, "allow_indirect no value %s",
990 			    scf_strerror(scf_error()));
991 		}
992 		scf_simple_prop_free(prop);
993 	} else {
994 		syslog(LOG_ALERT, "unable to get allow_indirect %s",
995 		    scf_strerror(scf_error()));
996 	}
997 
998 	if (wrap_enabled)
999 		(void) thr_create(NULL, 0, logthread, NULL, THR_DETACHED, &tid);
1000 }
1001 
1002 /*
1003  * qsyslog() - queue a request for syslog(); if syslog blocks, the other
1004  * thread blocks; we make sure we don't run out of memory by allowing
1005  * only a limited number of outstandig syslog() requests.
1006  */
1007 void
1008 qsyslog(int pri, const char *fmt, ...)
1009 {
1010 	logmsg *msg = malloc(sizeof (*msg));
1011 	int oldcount;
1012 	va_list ap;
1013 
1014 	if (msg == NULL)
1015 		return;
1016 
1017 	msg->log_pri = pri;
1018 
1019 	va_start(ap, fmt);
1020 	(void) vsnprintf(msg->log_msg, sizeof (msg->log_msg), fmt, ap);
1021 	va_end(ap);
1022 
1023 	msg->log_next = NULL;
1024 
1025 	(void) mutex_lock(&logmutex);
1026 	oldcount = logcount;
1027 	if (logcount < MAXLOG) {
1028 		logcount++;
1029 		*logtailp = msg;
1030 		logtailp = &msg->log_next;
1031 	} else {
1032 		free(msg);
1033 	}
1034 	(void) mutex_unlock(&logmutex);
1035 	if (oldcount == 0)
1036 		(void) cond_signal(&logcond);
1037 }
1038