xref: /freebsd/usr.sbin/inetd/inetd.c (revision 49dae58b287906be26f56ba3e3dc693c3ba8cf37)
1 /*
2  * Copyright (c) 1983, 1991, 1993, 1994
3  *	The Regents of the University of California.  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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY 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 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1991, 1993, 1994\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)from: inetd.c	8.4 (Berkeley) 4/13/94";
39 #endif
40 #endif /* not lint */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 /*
46  * Inetd - Internet super-server
47  *
48  * This program invokes all internet services as needed.  Connection-oriented
49  * services are invoked each time a connection is made, by creating a process.
50  * This process is passed the connection as file descriptor 0 and is expected
51  * to do a getpeername to find out the source host and port.
52  *
53  * Datagram oriented services are invoked when a datagram
54  * arrives; a process is created and passed a pending message
55  * on file descriptor 0.  Datagram servers may either connect
56  * to their peer, freeing up the original socket for inetd
57  * to receive further messages on, or ``take over the socket'',
58  * processing all arriving datagrams and, eventually, timing
59  * out.	 The first type of server is said to be ``multi-threaded'';
60  * the second type of server ``single-threaded''.
61  *
62  * Inetd uses a configuration file which is read at startup
63  * and, possibly, at some later time in response to a hangup signal.
64  * The configuration file is ``free format'' with fields given in the
65  * order shown below.  Continuation lines for an entry must begin with
66  * a space or tab.  All fields must be present in each entry.
67  *
68  *	service name			must be in /etc/services
69  *					or name a tcpmux service
70  *					or specify a unix domain socket
71  *	socket type			stream/dgram/raw/rdm/seqpacket
72  *	protocol			tcp[4][6], udp[4][6], unix
73  *	wait/nowait			single-threaded/multi-threaded
74  *	user[:group][/login-class]	user/group/login-class to run daemon as
75  *	server program			full path name
76  *	server program arguments	maximum of MAXARGS (20)
77  *
78  * TCP services without official port numbers are handled with the
79  * RFC1078-based tcpmux internal service. Tcpmux listens on port 1 for
80  * requests. When a connection is made from a foreign host, the service
81  * requested is passed to tcpmux, which looks it up in the servtab list
82  * and returns the proper entry for the service. Tcpmux returns a
83  * negative reply if the service doesn't exist, otherwise the invoked
84  * server is expected to return the positive reply if the service type in
85  * inetd.conf file has the prefix "tcpmux/". If the service type has the
86  * prefix "tcpmux/+", tcpmux will return the positive reply for the
87  * process; this is for compatibility with older server code, and also
88  * allows you to invoke programs that use stdin/stdout without putting any
89  * special server code in them. Services that use tcpmux are "nowait"
90  * because they do not have a well-known port and hence cannot listen
91  * for new requests.
92  *
93  * For RPC services
94  *	service name/version		must be in /etc/rpc
95  *	socket type			stream/dgram/raw/rdm/seqpacket
96  *	protocol			rpc/tcp[4][6], rpc/udp[4][6]
97  *	wait/nowait			single-threaded/multi-threaded
98  *	user[:group][/login-class]	user/group/login-class to run daemon as
99  *	server program			full path name
100  *	server program arguments	maximum of MAXARGS
101  *
102  * Comment lines are indicated by a `#' in column 1.
103  *
104  * #ifdef IPSEC
105  * Comment lines that start with "#@" denote IPsec policy string, as described
106  * in ipsec_set_policy(3).  This will affect all the following items in
107  * inetd.conf(8).  To reset the policy, just use "#@" line.  By default,
108  * there's no IPsec policy.
109  * #endif
110  */
111 #include <sys/param.h>
112 #include <sys/ioctl.h>
113 #include <sys/mman.h>
114 #include <sys/wait.h>
115 #include <sys/time.h>
116 #include <sys/resource.h>
117 #include <sys/stat.h>
118 #include <sys/un.h>
119 
120 #include <netinet/in.h>
121 #include <netinet/tcp.h>
122 #include <arpa/inet.h>
123 #include <rpc/rpc.h>
124 #include <rpc/pmap_clnt.h>
125 
126 #include <ctype.h>
127 #include <errno.h>
128 #include <err.h>
129 #include <fcntl.h>
130 #include <grp.h>
131 #include <libutil.h>
132 #include <limits.h>
133 #include <netdb.h>
134 #include <pwd.h>
135 #include <signal.h>
136 #include <stdio.h>
137 #include <stdlib.h>
138 #include <string.h>
139 #include <sysexits.h>
140 #include <syslog.h>
141 #include <tcpd.h>
142 #include <unistd.h>
143 
144 #include "inetd.h"
145 #include "pathnames.h"
146 
147 #ifdef IPSEC
148 #include <netipsec/ipsec.h>
149 #ifndef IPSEC_POLICY_IPSEC	/* no ipsec support on old ipsec */
150 #undef IPSEC
151 #endif
152 #endif
153 
154 #ifndef LIBWRAP_ALLOW_FACILITY
155 # define LIBWRAP_ALLOW_FACILITY LOG_AUTH
156 #endif
157 #ifndef LIBWRAP_ALLOW_SEVERITY
158 # define LIBWRAP_ALLOW_SEVERITY LOG_INFO
159 #endif
160 #ifndef LIBWRAP_DENY_FACILITY
161 # define LIBWRAP_DENY_FACILITY LOG_AUTH
162 #endif
163 #ifndef LIBWRAP_DENY_SEVERITY
164 # define LIBWRAP_DENY_SEVERITY LOG_WARNING
165 #endif
166 
167 #define ISWRAP(sep)	\
168 	   ( ((wrap_ex && !(sep)->se_bi) || (wrap_bi && (sep)->se_bi)) \
169 	&& (sep->se_family == AF_INET || sep->se_family == AF_INET6) \
170 	&& ( ((sep)->se_accept && (sep)->se_socktype == SOCK_STREAM) \
171 	    || (sep)->se_socktype == SOCK_DGRAM))
172 
173 #ifdef LOGIN_CAP
174 #include <login_cap.h>
175 
176 /* see init.c */
177 #define RESOURCE_RC "daemon"
178 
179 #endif
180 
181 #ifndef	MAXCHILD
182 #define	MAXCHILD	-1		/* maximum number of this service
183 					   < 0 = no limit */
184 #endif
185 
186 #ifndef	MAXCPM
187 #define	MAXCPM		-1		/* rate limit invocations from a
188 					   single remote address,
189 					   < 0 = no limit */
190 #endif
191 
192 #ifndef	MAXPERIP
193 #define	MAXPERIP	-1		/* maximum number of this service
194 					   from a single remote address,
195 					   < 0 = no limit */
196 #endif
197 
198 #ifndef TOOMANY
199 #define	TOOMANY		256		/* don't start more than TOOMANY */
200 #endif
201 #define	CNT_INTVL	60		/* servers in CNT_INTVL sec. */
202 #define	RETRYTIME	(60*10)		/* retry after bind or server fail */
203 #define MAX_MAXCHLD	32767		/* max allowable max children */
204 
205 #define	SIGBLOCK	(sigmask(SIGCHLD)|sigmask(SIGHUP)|sigmask(SIGALRM))
206 
207 void		close_sep(struct servtab *);
208 void		flag_signal(int);
209 void		flag_config(int);
210 void		config(void);
211 int		cpmip(const struct servtab *, int);
212 void		endconfig(void);
213 struct servtab *enter(struct servtab *);
214 void		freeconfig(struct servtab *);
215 struct servtab *getconfigent(void);
216 int		matchservent(const char *, const char *, const char *);
217 char	       *nextline(FILE *);
218 void		addchild(struct servtab *, int);
219 void		flag_reapchild(int);
220 void		reapchild(void);
221 void		enable(struct servtab *);
222 void		disable(struct servtab *);
223 void		flag_retry(int);
224 void		retry(void);
225 int		setconfig(void);
226 void		setup(struct servtab *);
227 #ifdef IPSEC
228 void		ipsecsetup(struct servtab *);
229 #endif
230 void		unregisterrpc(register struct servtab *sep);
231 static struct conninfo *search_conn(struct servtab *sep, int ctrl);
232 static int	room_conn(struct servtab *sep, struct conninfo *conn);
233 static void	addchild_conn(struct conninfo *conn, pid_t pid);
234 static void	reapchild_conn(pid_t pid);
235 static void	free_conn(struct conninfo *conn);
236 static void	resize_conn(struct servtab *sep, int maxperip);
237 static void	free_connlist(struct servtab *sep);
238 static void	free_proc(struct procinfo *);
239 static struct procinfo *search_proc(pid_t pid, int add);
240 static int	hashval(char *p, int len);
241 
242 int	allow_severity;
243 int	deny_severity;
244 int	wrap_ex = 0;
245 int	wrap_bi = 0;
246 int	debug = 0;
247 int	dolog = 0;
248 int	maxsock;			/* highest-numbered descriptor */
249 fd_set	allsock;
250 int	options;
251 int	timingout;
252 int	toomany = TOOMANY;
253 int	maxchild = MAXCHILD;
254 int	maxcpm = MAXCPM;
255 int	maxperip = MAXPERIP;
256 struct	servent *sp;
257 struct	rpcent *rpc;
258 char	*hostname = NULL;
259 struct	sockaddr_in *bind_sa4;
260 int	v4bind_ok = 0;
261 #ifdef INET6
262 struct	sockaddr_in6 *bind_sa6;
263 int	v6bind_ok = 0;
264 #endif
265 int	signalpipe[2];
266 #ifdef SANITY_CHECK
267 int	nsock;
268 #endif
269 uid_t	euid;
270 gid_t	egid;
271 mode_t	mask;
272 
273 struct	servtab *servtab;
274 
275 extern struct biltin biltins[];
276 
277 const char	*CONFIG = _PATH_INETDCONF;
278 const char	*pid_file = _PATH_INETDPID;
279 struct pidfh	*pfh = NULL;
280 
281 struct netconfig *udpconf, *tcpconf, *udp6conf, *tcp6conf;
282 
283 static LIST_HEAD(, procinfo) proctable[PERIPSIZE];
284 
285 int
286 getvalue(const char *arg, int *value, const char *whine)
287 {
288 	int  tmp;
289 	char *p;
290 
291 	tmp = strtol(arg, &p, 0);
292 	if (tmp < 0 || *p) {
293 		syslog(LOG_ERR, whine, arg);
294 		return 1;			/* failure */
295 	}
296 	*value = tmp;
297 	return 0;				/* success */
298 }
299 
300 static sa_family_t
301 whichaf(struct request_info *req)
302 {
303 	struct sockaddr *sa;
304 
305 	sa = (struct sockaddr *)req->client->sin;
306 	if (sa == NULL)
307 		return AF_UNSPEC;
308 	if (sa->sa_family == AF_INET6 &&
309 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)sa)->sin6_addr))
310 		return AF_INET;
311 	return sa->sa_family;
312 }
313 
314 int
315 main(int argc, char **argv)
316 {
317 	struct servtab *sep;
318 	struct passwd *pwd;
319 	struct group *grp;
320 	struct sigaction sa, saalrm, sachld, sahup, sapipe;
321 	int ch, dofork;
322 	pid_t pid;
323 	char buf[50];
324 #ifdef LOGIN_CAP
325 	login_cap_t *lc = NULL;
326 #endif
327 	struct request_info req;
328 	int denied;
329 	char *service = NULL;
330 	struct sockaddr_storage peer;
331 	int i;
332 	struct addrinfo hints, *res;
333 	const char *servname;
334 	int error;
335 	struct conninfo *conn;
336 
337 	openlog("inetd", LOG_PID | LOG_NOWAIT | LOG_PERROR, LOG_DAEMON);
338 
339 	while ((ch = getopt(argc, argv, "dlwWR:a:c:C:p:s:")) != -1)
340 		switch(ch) {
341 		case 'd':
342 			debug = 1;
343 			options |= SO_DEBUG;
344 			break;
345 		case 'l':
346 			dolog = 1;
347 			break;
348 		case 'R':
349 			getvalue(optarg, &toomany,
350 				"-R %s: bad value for service invocation rate");
351 			break;
352 		case 'c':
353 			getvalue(optarg, &maxchild,
354 				"-c %s: bad value for maximum children");
355 			break;
356 		case 'C':
357 			getvalue(optarg, &maxcpm,
358 				"-C %s: bad value for maximum children/minute");
359 			break;
360 		case 'a':
361 			hostname = optarg;
362 			break;
363 		case 'p':
364 			pid_file = optarg;
365 			break;
366 		case 's':
367 			getvalue(optarg, &maxperip,
368 				"-s %s: bad value for maximum children per source address");
369 			break;
370 		case 'w':
371 			wrap_ex++;
372 			break;
373 		case 'W':
374 			wrap_bi++;
375 			break;
376 		case '?':
377 		default:
378 			syslog(LOG_ERR,
379 				"usage: inetd [-dlwW] [-a address] [-R rate]"
380 				" [-c maximum] [-C rate]"
381 				" [-p pidfile] [conf-file]");
382 			exit(EX_USAGE);
383 		}
384 	/*
385 	 * Initialize Bind Addrs.
386 	 *   When hostname is NULL, wild card bind addrs are obtained from
387 	 *   getaddrinfo(). But getaddrinfo() requires at least one of
388 	 *   hostname or servname is non NULL.
389 	 *   So when hostname is NULL, set dummy value to servname.
390 	 *   Since getaddrinfo() doesn't accept numeric servname, and
391 	 *   we doesn't use ai_socktype of struct addrinfo returned
392 	 *   from getaddrinfo(), we set dummy value to ai_socktype.
393 	 */
394 	servname = (hostname == NULL) ? "0" /* dummy */ : NULL;
395 
396 	bzero(&hints, sizeof(struct addrinfo));
397 	hints.ai_flags = AI_PASSIVE;
398 	hints.ai_family = AF_UNSPEC;
399 	hints.ai_socktype = SOCK_STREAM;	/* dummy */
400 	error = getaddrinfo(hostname, servname, &hints, &res);
401 	if (error != 0) {
402 		syslog(LOG_ERR, "-a %s: %s", hostname, gai_strerror(error));
403 		if (error == EAI_SYSTEM)
404 			syslog(LOG_ERR, "%s", strerror(errno));
405 		exit(EX_USAGE);
406 	}
407 	do {
408 		if (res->ai_addr == NULL) {
409 			syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
410 			exit(EX_USAGE);
411 		}
412 		switch (res->ai_addr->sa_family) {
413 		case AF_INET:
414 			if (v4bind_ok)
415 				continue;
416 			bind_sa4 = (struct sockaddr_in *)res->ai_addr;
417 			/* init port num in case servname is dummy */
418 			bind_sa4->sin_port = 0;
419 			v4bind_ok = 1;
420 			continue;
421 #ifdef INET6
422 		case AF_INET6:
423 			if (v6bind_ok)
424 				continue;
425 			bind_sa6 = (struct sockaddr_in6 *)res->ai_addr;
426 			/* init port num in case servname is dummy */
427 			bind_sa6->sin6_port = 0;
428 			v6bind_ok = 1;
429 			continue;
430 #endif
431 		}
432 		if (v4bind_ok
433 #ifdef INET6
434 		    && v6bind_ok
435 #endif
436 		    )
437 			break;
438 	} while ((res = res->ai_next) != NULL);
439 	if (!v4bind_ok
440 #ifdef INET6
441 	    && !v6bind_ok
442 #endif
443 	    ) {
444 		syslog(LOG_ERR, "-a %s: unknown address family", hostname);
445 		exit(EX_USAGE);
446 	}
447 
448 	euid = geteuid();
449 	egid = getegid();
450 	umask(mask = umask(0777));
451 
452 	argc -= optind;
453 	argv += optind;
454 
455 	if (argc > 0)
456 		CONFIG = argv[0];
457 	if (access(CONFIG, R_OK) < 0)
458 		syslog(LOG_ERR, "Accessing %s: %m, continuing anyway.", CONFIG);
459 	if (debug == 0) {
460 		pid_t otherpid;
461 
462 		pfh = pidfile_open(pid_file, 0600, &otherpid);
463 		if (pfh == NULL) {
464 			if (errno == EEXIST) {
465 				syslog(LOG_ERR, "%s already running, pid: %d",
466 				    getprogname(), otherpid);
467 				exit(EX_OSERR);
468 			}
469 			syslog(LOG_WARNING, "pidfile_open() failed: %m");
470 		}
471 
472 		if (daemon(0, 0) < 0) {
473 			syslog(LOG_WARNING, "daemon(0,0) failed: %m");
474 		}
475 		/* From now on we don't want syslog messages going to stderr. */
476 		closelog();
477 		openlog("inetd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
478 		/*
479 		 * In case somebody has started inetd manually, we need to
480 		 * clear the logname, so that old servers run as root do not
481 		 * get the user's logname..
482 		 */
483 		if (setlogin("") < 0) {
484 			syslog(LOG_WARNING, "cannot clear logname: %m");
485 			/* no big deal if it fails.. */
486 		}
487 		if (pfh != NULL && pidfile_write(pfh) == -1) {
488 			syslog(LOG_WARNING, "pidfile_write(): %m");
489 		}
490 	}
491 
492 	if (madvise(NULL, 0, MADV_PROTECT) != 0)
493 		syslog(LOG_WARNING, "madvise() failed: %s", strerror(errno));
494 
495 	for (i = 0; i < PERIPSIZE; ++i)
496 		LIST_INIT(&proctable[i]);
497 
498 	if (v4bind_ok) {
499 		udpconf = getnetconfigent("udp");
500 		tcpconf = getnetconfigent("tcp");
501 		if (udpconf == NULL || tcpconf == NULL) {
502 			syslog(LOG_ERR, "unknown rpc/udp or rpc/tcp");
503 			exit(EX_USAGE);
504 		}
505 	}
506 #ifdef INET6
507 	if (v6bind_ok) {
508 		udp6conf = getnetconfigent("udp6");
509 		tcp6conf = getnetconfigent("tcp6");
510 		if (udp6conf == NULL || tcp6conf == NULL) {
511 			syslog(LOG_ERR, "unknown rpc/udp6 or rpc/tcp6");
512 			exit(EX_USAGE);
513 		}
514 	}
515 #endif
516 
517 	sa.sa_flags = 0;
518 	sigemptyset(&sa.sa_mask);
519 	sigaddset(&sa.sa_mask, SIGALRM);
520 	sigaddset(&sa.sa_mask, SIGCHLD);
521 	sigaddset(&sa.sa_mask, SIGHUP);
522 	sa.sa_handler = flag_retry;
523 	sigaction(SIGALRM, &sa, &saalrm);
524 	config();
525 	sa.sa_handler = flag_config;
526 	sigaction(SIGHUP, &sa, &sahup);
527 	sa.sa_handler = flag_reapchild;
528 	sigaction(SIGCHLD, &sa, &sachld);
529 	sa.sa_handler = SIG_IGN;
530 	sigaction(SIGPIPE, &sa, &sapipe);
531 
532 	{
533 		/* space for daemons to overwrite environment for ps */
534 #define	DUMMYSIZE	100
535 		char dummy[DUMMYSIZE];
536 
537 		(void)memset(dummy, 'x', DUMMYSIZE - 1);
538 		dummy[DUMMYSIZE - 1] = '\0';
539 		(void)setenv("inetd_dummy", dummy, 1);
540 	}
541 
542 	if (pipe2(signalpipe, O_CLOEXEC) != 0) {
543 		syslog(LOG_ERR, "pipe: %m");
544 		exit(EX_OSERR);
545 	}
546 	FD_SET(signalpipe[0], &allsock);
547 #ifdef SANITY_CHECK
548 	nsock++;
549 #endif
550 	if (signalpipe[0] > maxsock)
551 	    maxsock = signalpipe[0];
552 	if (signalpipe[1] > maxsock)
553 	    maxsock = signalpipe[1];
554 
555 	for (;;) {
556 	    int n, ctrl;
557 	    fd_set readable;
558 
559 #ifdef SANITY_CHECK
560 	    if (nsock == 0) {
561 		syslog(LOG_ERR, "%s: nsock=0", __func__);
562 		exit(EX_SOFTWARE);
563 	    }
564 #endif
565 	    readable = allsock;
566 	    if ((n = select(maxsock + 1, &readable, (fd_set *)0,
567 		(fd_set *)0, (struct timeval *)0)) <= 0) {
568 		    if (n < 0 && errno != EINTR) {
569 			syslog(LOG_WARNING, "select: %m");
570 			sleep(1);
571 		    }
572 		    continue;
573 	    }
574 	    /* handle any queued signal flags */
575 	    if (FD_ISSET(signalpipe[0], &readable)) {
576 		int nsig;
577 		if (ioctl(signalpipe[0], FIONREAD, &nsig) != 0) {
578 		    syslog(LOG_ERR, "ioctl: %m");
579 		    exit(EX_OSERR);
580 		}
581 		while (--nsig >= 0) {
582 		    char c;
583 		    if (read(signalpipe[0], &c, 1) != 1) {
584 			syslog(LOG_ERR, "read: %m");
585 			exit(EX_OSERR);
586 		    }
587 		    if (debug)
588 			warnx("handling signal flag %c", c);
589 		    switch(c) {
590 		    case 'A': /* sigalrm */
591 			retry();
592 			break;
593 		    case 'C': /* sigchld */
594 			reapchild();
595 			break;
596 		    case 'H': /* sighup */
597 			config();
598 			break;
599 		    }
600 		}
601 	    }
602 	    for (sep = servtab; n && sep; sep = sep->se_next)
603 	        if (sep->se_fd != -1 && FD_ISSET(sep->se_fd, &readable)) {
604 		    n--;
605 		    if (debug)
606 			    warnx("someone wants %s", sep->se_service);
607 		    dofork = !sep->se_bi || sep->se_bi->bi_fork || ISWRAP(sep);
608 		    conn = NULL;
609 		    if (sep->se_accept && sep->se_socktype == SOCK_STREAM) {
610 			    i = 1;
611 			    if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
612 				    syslog(LOG_ERR, "ioctl (FIONBIO, 1): %m");
613 			    ctrl = accept(sep->se_fd, (struct sockaddr *)0,
614 				(socklen_t *)0);
615 			    if (debug)
616 				    warnx("accept, ctrl %d", ctrl);
617 			    if (ctrl < 0) {
618 				    if (errno != EINTR)
619 					    syslog(LOG_WARNING,
620 						"accept (for %s): %m",
621 						sep->se_service);
622                                       if (sep->se_accept &&
623                                           sep->se_socktype == SOCK_STREAM)
624                                               close(ctrl);
625 				    continue;
626 			    }
627 			    i = 0;
628 			    if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
629 				    syslog(LOG_ERR, "ioctl1(FIONBIO, 0): %m");
630 			    if (ioctl(ctrl, FIONBIO, &i) < 0)
631 				    syslog(LOG_ERR, "ioctl2(FIONBIO, 0): %m");
632 			    if (cpmip(sep, ctrl) < 0) {
633 				close(ctrl);
634 				continue;
635 			    }
636 			    if (dofork &&
637 				(conn = search_conn(sep, ctrl)) != NULL &&
638 				!room_conn(sep, conn)) {
639 				close(ctrl);
640 				continue;
641 			    }
642 		    } else
643 			    ctrl = sep->se_fd;
644 		    if (dolog && !ISWRAP(sep)) {
645 			    char pname[NI_MAXHOST] = "unknown";
646 			    socklen_t sl;
647 			    sl = sizeof(peer);
648 			    if (getpeername(ctrl, (struct sockaddr *)
649 					    &peer, &sl)) {
650 				    sl = sizeof(peer);
651 				    if (recvfrom(ctrl, buf, sizeof(buf),
652 					MSG_PEEK,
653 					(struct sockaddr *)&peer,
654 					&sl) >= 0) {
655 				      getnameinfo((struct sockaddr *)&peer,
656 						  peer.ss_len,
657 						  pname, sizeof(pname),
658 						  NULL, 0, NI_NUMERICHOST);
659 				    }
660 			    } else {
661 			            getnameinfo((struct sockaddr *)&peer,
662 						peer.ss_len,
663 						pname, sizeof(pname),
664 						NULL, 0, NI_NUMERICHOST);
665 			    }
666 			    syslog(LOG_INFO,"%s from %s", sep->se_service, pname);
667 		    }
668 		    (void) sigblock(SIGBLOCK);
669 		    pid = 0;
670 		    /*
671 		     * Fork for all external services, builtins which need to
672 		     * fork and anything we're wrapping (as wrapping might
673 		     * block or use hosts_options(5) twist).
674 		     */
675 		    if (dofork) {
676 			    if (sep->se_count++ == 0)
677 				(void)clock_gettime(CLOCK_MONOTONIC_FAST, &sep->se_time);
678 			    else if (toomany > 0 && sep->se_count >= toomany) {
679 				struct timespec now;
680 
681 				(void)clock_gettime(CLOCK_MONOTONIC_FAST, &now);
682 				if (now.tv_sec - sep->se_time.tv_sec >
683 				    CNT_INTVL) {
684 					sep->se_time = now;
685 					sep->se_count = 1;
686 				} else {
687 					syslog(LOG_ERR,
688 			"%s/%s server failing (looping), service terminated",
689 					    sep->se_service, sep->se_proto);
690 					if (sep->se_accept &&
691 					    sep->se_socktype == SOCK_STREAM)
692 						close(ctrl);
693 					close_sep(sep);
694 					free_conn(conn);
695 					sigsetmask(0L);
696 					if (!timingout) {
697 						timingout = 1;
698 						alarm(RETRYTIME);
699 					}
700 					continue;
701 				}
702 			    }
703 			    pid = fork();
704 		    }
705 		    if (pid < 0) {
706 			    syslog(LOG_ERR, "fork: %m");
707 			    if (sep->se_accept &&
708 				sep->se_socktype == SOCK_STREAM)
709 				    close(ctrl);
710 			    free_conn(conn);
711 			    sigsetmask(0L);
712 			    sleep(1);
713 			    continue;
714 		    }
715 		    if (pid) {
716 			addchild_conn(conn, pid);
717 			addchild(sep, pid);
718 		    }
719 		    sigsetmask(0L);
720 		    if (pid == 0) {
721 			    pidfile_close(pfh);
722 			    if (dofork) {
723 				sigaction(SIGALRM, &saalrm, (struct sigaction *)0);
724 				sigaction(SIGCHLD, &sachld, (struct sigaction *)0);
725 				sigaction(SIGHUP, &sahup, (struct sigaction *)0);
726 				/* SIGPIPE reset before exec */
727 			    }
728 			    /*
729 			     * Call tcpmux to find the real service to exec.
730 			     */
731 			    if (sep->se_bi &&
732 				sep->se_bi->bi_fn == (bi_fn_t *) tcpmux) {
733 				    sep = tcpmux(ctrl);
734 				    if (sep == NULL) {
735 					    close(ctrl);
736 					    _exit(0);
737 				    }
738 			    }
739 			    if (ISWRAP(sep)) {
740 				inetd_setproctitle("wrapping", ctrl);
741 				service = sep->se_server_name ?
742 				    sep->se_server_name : sep->se_service;
743 				request_init(&req, RQ_DAEMON, service, RQ_FILE, ctrl, 0);
744 				fromhost(&req);
745 				deny_severity = LIBWRAP_DENY_FACILITY|LIBWRAP_DENY_SEVERITY;
746 				allow_severity = LIBWRAP_ALLOW_FACILITY|LIBWRAP_ALLOW_SEVERITY;
747 				denied = !hosts_access(&req);
748 				if (denied) {
749 				    syslog(deny_severity,
750 				        "refused connection from %.500s, service %s (%s%s)",
751 				        eval_client(&req), service, sep->se_proto,
752 					(whichaf(&req) == AF_INET6) ? "6" : "");
753 				    if (sep->se_socktype != SOCK_STREAM)
754 					recv(ctrl, buf, sizeof (buf), 0);
755 				    if (dofork) {
756 					sleep(1);
757 					_exit(0);
758 				    }
759 				}
760 				if (dolog) {
761 				    syslog(allow_severity,
762 				        "connection from %.500s, service %s (%s%s)",
763 					eval_client(&req), service, sep->se_proto,
764 					(whichaf(&req) == AF_INET6) ? "6" : "");
765 				}
766 			    }
767 			    if (sep->se_bi) {
768 				(*sep->se_bi->bi_fn)(ctrl, sep);
769 			    } else {
770 				if (debug)
771 					warnx("%d execl %s",
772 						getpid(), sep->se_server);
773 				/* Clear close-on-exec. */
774 				if (fcntl(ctrl, F_SETFD, 0) < 0) {
775 					syslog(LOG_ERR,
776 					    "%s/%s: fcntl (F_SETFD, 0): %m",
777 						sep->se_service, sep->se_proto);
778 					_exit(EX_OSERR);
779 				}
780 				if (ctrl != 0) {
781 					dup2(ctrl, 0);
782 					close(ctrl);
783 				}
784 				dup2(0, 1);
785 				dup2(0, 2);
786 				if ((pwd = getpwnam(sep->se_user)) == NULL) {
787 					syslog(LOG_ERR,
788 					    "%s/%s: %s: no such user",
789 						sep->se_service, sep->se_proto,
790 						sep->se_user);
791 					if (sep->se_socktype != SOCK_STREAM)
792 						recv(0, buf, sizeof (buf), 0);
793 					_exit(EX_NOUSER);
794 				}
795 				grp = NULL;
796 				if (   sep->se_group != NULL
797 				    && (grp = getgrnam(sep->se_group)) == NULL
798 				   ) {
799 					syslog(LOG_ERR,
800 					    "%s/%s: %s: no such group",
801 						sep->se_service, sep->se_proto,
802 						sep->se_group);
803 					if (sep->se_socktype != SOCK_STREAM)
804 						recv(0, buf, sizeof (buf), 0);
805 					_exit(EX_NOUSER);
806 				}
807 				if (grp != NULL)
808 					pwd->pw_gid = grp->gr_gid;
809 #ifdef LOGIN_CAP
810 				if ((lc = login_getclass(sep->se_class)) == NULL) {
811 					/* error syslogged by getclass */
812 					syslog(LOG_ERR,
813 					    "%s/%s: %s: login class error",
814 						sep->se_service, sep->se_proto,
815 						sep->se_class);
816 					if (sep->se_socktype != SOCK_STREAM)
817 						recv(0, buf, sizeof (buf), 0);
818 					_exit(EX_NOUSER);
819 				}
820 #endif
821 				if (setsid() < 0) {
822 					syslog(LOG_ERR,
823 						"%s: can't setsid(): %m",
824 						 sep->se_service);
825 					/* _exit(EX_OSERR); not fatal yet */
826 				}
827 #ifdef LOGIN_CAP
828 				if (setusercontext(lc, pwd, pwd->pw_uid,
829 				    LOGIN_SETALL & ~LOGIN_SETMAC)
830 				    != 0) {
831 					syslog(LOG_ERR,
832 					 "%s: can't setusercontext(..%s..): %m",
833 					 sep->se_service, sep->se_user);
834 					_exit(EX_OSERR);
835 				}
836 				login_close(lc);
837 #else
838 				if (pwd->pw_uid) {
839 					if (setlogin(sep->se_user) < 0) {
840 						syslog(LOG_ERR,
841 						 "%s: can't setlogin(%s): %m",
842 						 sep->se_service, sep->se_user);
843 						/* _exit(EX_OSERR); not yet */
844 					}
845 					if (setgid(pwd->pw_gid) < 0) {
846 						syslog(LOG_ERR,
847 						  "%s: can't set gid %d: %m",
848 						  sep->se_service, pwd->pw_gid);
849 						_exit(EX_OSERR);
850 					}
851 					(void) initgroups(pwd->pw_name,
852 							pwd->pw_gid);
853 					if (setuid(pwd->pw_uid) < 0) {
854 						syslog(LOG_ERR,
855 						  "%s: can't set uid %d: %m",
856 						  sep->se_service, pwd->pw_uid);
857 						_exit(EX_OSERR);
858 					}
859 				}
860 #endif
861 				sigaction(SIGPIPE, &sapipe,
862 				    (struct sigaction *)0);
863 				execv(sep->se_server, sep->se_argv);
864 				syslog(LOG_ERR,
865 				    "cannot execute %s: %m", sep->se_server);
866 				if (sep->se_socktype != SOCK_STREAM)
867 					recv(0, buf, sizeof (buf), 0);
868 			    }
869 			    if (dofork)
870 				_exit(0);
871 		    }
872 		    if (sep->se_accept && sep->se_socktype == SOCK_STREAM)
873 			    close(ctrl);
874 		}
875 	}
876 }
877 
878 /*
879  * Add a signal flag to the signal flag queue for later handling
880  */
881 
882 void
883 flag_signal(int c)
884 {
885 	char ch = c;
886 
887 	if (write(signalpipe[1], &ch, 1) != 1) {
888 		syslog(LOG_ERR, "write: %m");
889 		_exit(EX_OSERR);
890 	}
891 }
892 
893 /*
894  * Record a new child pid for this service. If we've reached the
895  * limit on children, then stop accepting incoming requests.
896  */
897 
898 void
899 addchild(struct servtab *sep, pid_t pid)
900 {
901 	if (sep->se_maxchild <= 0)
902 		return;
903 #ifdef SANITY_CHECK
904 	if (sep->se_numchild >= sep->se_maxchild) {
905 		syslog(LOG_ERR, "%s: %d >= %d",
906 		    __func__, sep->se_numchild, sep->se_maxchild);
907 		exit(EX_SOFTWARE);
908 	}
909 #endif
910 	sep->se_pids[sep->se_numchild++] = pid;
911 	if (sep->se_numchild == sep->se_maxchild)
912 		disable(sep);
913 }
914 
915 /*
916  * Some child process has exited. See if it's on somebody's list.
917  */
918 
919 void
920 flag_reapchild(int signo __unused)
921 {
922 	flag_signal('C');
923 }
924 
925 void
926 reapchild(void)
927 {
928 	int k, status;
929 	pid_t pid;
930 	struct servtab *sep;
931 
932 	for (;;) {
933 		pid = wait3(&status, WNOHANG, (struct rusage *)0);
934 		if (pid <= 0)
935 			break;
936 		if (debug)
937 			warnx("%d reaped, %s %u", pid,
938 			    WIFEXITED(status) ? "status" : "signal",
939 			    WIFEXITED(status) ? WEXITSTATUS(status)
940 				: WTERMSIG(status));
941 		for (sep = servtab; sep; sep = sep->se_next) {
942 			for (k = 0; k < sep->se_numchild; k++)
943 				if (sep->se_pids[k] == pid)
944 					break;
945 			if (k == sep->se_numchild)
946 				continue;
947 			if (sep->se_numchild == sep->se_maxchild)
948 				enable(sep);
949 			sep->se_pids[k] = sep->se_pids[--sep->se_numchild];
950 			if (WIFSIGNALED(status) || WEXITSTATUS(status))
951 				syslog(LOG_WARNING,
952 				    "%s[%d]: exited, %s %u",
953 				    sep->se_server, pid,
954 				    WIFEXITED(status) ? "status" : "signal",
955 				    WIFEXITED(status) ? WEXITSTATUS(status)
956 					: WTERMSIG(status));
957 			break;
958 		}
959 		reapchild_conn(pid);
960 	}
961 }
962 
963 void
964 flag_config(int signo __unused)
965 {
966 	flag_signal('H');
967 }
968 
969 void
970 config(void)
971 {
972 	struct servtab *sep, *new, **sepp;
973 	long omask;
974 	int new_nomapped;
975 #ifdef LOGIN_CAP
976 	login_cap_t *lc = NULL;
977 #endif
978 
979 	if (!setconfig()) {
980 		syslog(LOG_ERR, "%s: %m", CONFIG);
981 		return;
982 	}
983 	for (sep = servtab; sep; sep = sep->se_next)
984 		sep->se_checked = 0;
985 	while ((new = getconfigent())) {
986 		if (getpwnam(new->se_user) == NULL) {
987 			syslog(LOG_ERR,
988 				"%s/%s: no such user '%s', service ignored",
989 				new->se_service, new->se_proto, new->se_user);
990 			continue;
991 		}
992 		if (new->se_group && getgrnam(new->se_group) == NULL) {
993 			syslog(LOG_ERR,
994 				"%s/%s: no such group '%s', service ignored",
995 				new->se_service, new->se_proto, new->se_group);
996 			continue;
997 		}
998 #ifdef LOGIN_CAP
999 		if ((lc = login_getclass(new->se_class)) == NULL) {
1000 			/* error syslogged by getclass */
1001 			syslog(LOG_ERR,
1002 				"%s/%s: %s: login class error, service ignored",
1003 				new->se_service, new->se_proto, new->se_class);
1004 			continue;
1005 		}
1006 		login_close(lc);
1007 #endif
1008 		new_nomapped = new->se_nomapped;
1009 		for (sep = servtab; sep; sep = sep->se_next)
1010 			if (strcmp(sep->se_service, new->se_service) == 0 &&
1011 			    strcmp(sep->se_proto, new->se_proto) == 0 &&
1012 			    sep->se_rpc == new->se_rpc &&
1013 			    sep->se_socktype == new->se_socktype &&
1014 			    sep->se_family == new->se_family)
1015 				break;
1016 		if (sep != 0) {
1017 			int i;
1018 
1019 #define SWAP(t,a, b) { t c = a; a = b; b = c; }
1020 			omask = sigblock(SIGBLOCK);
1021 			if (sep->se_nomapped != new->se_nomapped) {
1022 				/* for rpc keep old nommaped till unregister */
1023 				if (!sep->se_rpc)
1024 					sep->se_nomapped = new->se_nomapped;
1025 				sep->se_reset = 1;
1026 			}
1027 			/* copy over outstanding child pids */
1028 			if (sep->se_maxchild > 0 && new->se_maxchild > 0) {
1029 				new->se_numchild = sep->se_numchild;
1030 				if (new->se_numchild > new->se_maxchild)
1031 					new->se_numchild = new->se_maxchild;
1032 				memcpy(new->se_pids, sep->se_pids,
1033 				    new->se_numchild * sizeof(*new->se_pids));
1034 			}
1035 			SWAP(pid_t *, sep->se_pids, new->se_pids);
1036 			sep->se_maxchild = new->se_maxchild;
1037 			sep->se_numchild = new->se_numchild;
1038 			sep->se_maxcpm = new->se_maxcpm;
1039 			resize_conn(sep, new->se_maxperip);
1040 			sep->se_maxperip = new->se_maxperip;
1041 			sep->se_bi = new->se_bi;
1042 			/* might need to turn on or off service now */
1043 			if (sep->se_fd >= 0) {
1044 			      if (sep->se_maxchild > 0
1045 				  && sep->se_numchild == sep->se_maxchild) {
1046 				      if (FD_ISSET(sep->se_fd, &allsock))
1047 					  disable(sep);
1048 			      } else {
1049 				      if (!FD_ISSET(sep->se_fd, &allsock))
1050 					  enable(sep);
1051 			      }
1052 			}
1053 			sep->se_accept = new->se_accept;
1054 			SWAP(char *, sep->se_user, new->se_user);
1055 			SWAP(char *, sep->se_group, new->se_group);
1056 #ifdef LOGIN_CAP
1057 			SWAP(char *, sep->se_class, new->se_class);
1058 #endif
1059 			SWAP(char *, sep->se_server, new->se_server);
1060 			SWAP(char *, sep->se_server_name, new->se_server_name);
1061 			for (i = 0; i < MAXARGV; i++)
1062 				SWAP(char *, sep->se_argv[i], new->se_argv[i]);
1063 #ifdef IPSEC
1064 			SWAP(char *, sep->se_policy, new->se_policy);
1065 			ipsecsetup(sep);
1066 #endif
1067 			sigsetmask(omask);
1068 			freeconfig(new);
1069 			if (debug)
1070 				print_service("REDO", sep);
1071 		} else {
1072 			sep = enter(new);
1073 			if (debug)
1074 				print_service("ADD ", sep);
1075 		}
1076 		sep->se_checked = 1;
1077 		if (ISMUX(sep)) {
1078 			sep->se_fd = -1;
1079 			continue;
1080 		}
1081 		switch (sep->se_family) {
1082 		case AF_INET:
1083 			if (!v4bind_ok) {
1084 				sep->se_fd = -1;
1085 				continue;
1086 			}
1087 			break;
1088 #ifdef INET6
1089 		case AF_INET6:
1090 			if (!v6bind_ok) {
1091 				sep->se_fd = -1;
1092 				continue;
1093 			}
1094 			break;
1095 #endif
1096 		}
1097 		if (!sep->se_rpc) {
1098 			if (sep->se_family != AF_UNIX) {
1099 				sp = getservbyname(sep->se_service, sep->se_proto);
1100 				if (sp == 0) {
1101 					syslog(LOG_ERR, "%s/%s: unknown service",
1102 					sep->se_service, sep->se_proto);
1103 					sep->se_checked = 0;
1104 					continue;
1105 				}
1106 			}
1107 			switch (sep->se_family) {
1108 			case AF_INET:
1109 				if (sp->s_port != sep->se_ctrladdr4.sin_port) {
1110 					sep->se_ctrladdr4.sin_port =
1111 						sp->s_port;
1112 					sep->se_reset = 1;
1113 				}
1114 				break;
1115 #ifdef INET6
1116 			case AF_INET6:
1117 				if (sp->s_port !=
1118 				    sep->se_ctrladdr6.sin6_port) {
1119 					sep->se_ctrladdr6.sin6_port =
1120 						sp->s_port;
1121 					sep->se_reset = 1;
1122 				}
1123 				break;
1124 #endif
1125 			}
1126 			if (sep->se_reset != 0 && sep->se_fd >= 0)
1127 				close_sep(sep);
1128 		} else {
1129 			rpc = getrpcbyname(sep->se_service);
1130 			if (rpc == 0) {
1131 				syslog(LOG_ERR, "%s/%s unknown RPC service",
1132 					sep->se_service, sep->se_proto);
1133 				if (sep->se_fd != -1)
1134 					(void) close(sep->se_fd);
1135 				sep->se_fd = -1;
1136 					continue;
1137 			}
1138 			if (sep->se_reset != 0 ||
1139 			    rpc->r_number != sep->se_rpc_prog) {
1140 				if (sep->se_rpc_prog)
1141 					unregisterrpc(sep);
1142 				sep->se_rpc_prog = rpc->r_number;
1143 				if (sep->se_fd != -1)
1144 					(void) close(sep->se_fd);
1145 				sep->se_fd = -1;
1146 			}
1147 			sep->se_nomapped = new_nomapped;
1148 		}
1149 		sep->se_reset = 0;
1150 		if (sep->se_fd == -1)
1151 			setup(sep);
1152 	}
1153 	endconfig();
1154 	/*
1155 	 * Purge anything not looked at above.
1156 	 */
1157 	omask = sigblock(SIGBLOCK);
1158 	sepp = &servtab;
1159 	while ((sep = *sepp)) {
1160 		if (sep->se_checked) {
1161 			sepp = &sep->se_next;
1162 			continue;
1163 		}
1164 		*sepp = sep->se_next;
1165 		if (sep->se_fd >= 0)
1166 			close_sep(sep);
1167 		if (debug)
1168 			print_service("FREE", sep);
1169 		if (sep->se_rpc && sep->se_rpc_prog > 0)
1170 			unregisterrpc(sep);
1171 		freeconfig(sep);
1172 		free(sep);
1173 	}
1174 	(void) sigsetmask(omask);
1175 }
1176 
1177 void
1178 unregisterrpc(struct servtab *sep)
1179 {
1180         u_int i;
1181         struct servtab *sepp;
1182 	long omask;
1183 	struct netconfig *netid4, *netid6;
1184 
1185 	omask = sigblock(SIGBLOCK);
1186 	netid4 = sep->se_socktype == SOCK_DGRAM ? udpconf : tcpconf;
1187 	netid6 = sep->se_socktype == SOCK_DGRAM ? udp6conf : tcp6conf;
1188 	if (sep->se_family == AF_INET)
1189 		netid6 = NULL;
1190 	else if (sep->se_nomapped)
1191 		netid4 = NULL;
1192 	/*
1193 	 * Conflict if same prog and protocol - In that case one should look
1194 	 * to versions, but it is not interesting: having separate servers for
1195 	 * different versions does not work well.
1196 	 * Therefore one do not unregister if there is a conflict.
1197 	 * There is also transport conflict if destroying INET when INET46
1198 	 * exists, or destroying INET46 when INET exists
1199 	 */
1200         for (sepp = servtab; sepp; sepp = sepp->se_next) {
1201                 if (sepp == sep)
1202                         continue;
1203 		if (sepp->se_checked == 0 ||
1204                     !sepp->se_rpc ||
1205 		    strcmp(sep->se_proto, sepp->se_proto) != 0 ||
1206                     sep->se_rpc_prog != sepp->se_rpc_prog)
1207 			continue;
1208 		if (sepp->se_family == AF_INET)
1209 			netid4 = NULL;
1210 		if (sepp->se_family == AF_INET6) {
1211 			netid6 = NULL;
1212 			if (!sep->se_nomapped)
1213 				netid4 = NULL;
1214 		}
1215 		if (netid4 == NULL && netid6 == NULL)
1216 			return;
1217         }
1218         if (debug)
1219                 print_service("UNREG", sep);
1220         for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++) {
1221 		if (netid4)
1222 			rpcb_unset(sep->se_rpc_prog, i, netid4);
1223 		if (netid6)
1224 			rpcb_unset(sep->se_rpc_prog, i, netid6);
1225 	}
1226         if (sep->se_fd != -1)
1227                 (void) close(sep->se_fd);
1228         sep->se_fd = -1;
1229 	(void) sigsetmask(omask);
1230 }
1231 
1232 void
1233 flag_retry(int signo __unused)
1234 {
1235 	flag_signal('A');
1236 }
1237 
1238 void
1239 retry(void)
1240 {
1241 	struct servtab *sep;
1242 
1243 	timingout = 0;
1244 	for (sep = servtab; sep; sep = sep->se_next)
1245 		if (sep->se_fd == -1 && !ISMUX(sep))
1246 			setup(sep);
1247 }
1248 
1249 void
1250 setup(struct servtab *sep)
1251 {
1252 	int on = 1;
1253 
1254 	/* Set all listening sockets to close-on-exec. */
1255 	if ((sep->se_fd = socket(sep->se_family,
1256 	    sep->se_socktype | SOCK_CLOEXEC, 0)) < 0) {
1257 		if (debug)
1258 			warn("socket failed on %s/%s",
1259 				sep->se_service, sep->se_proto);
1260 		syslog(LOG_ERR, "%s/%s: socket: %m",
1261 		    sep->se_service, sep->se_proto);
1262 		return;
1263 	}
1264 #define	turnon(fd, opt) \
1265 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1266 	if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1267 	    turnon(sep->se_fd, SO_DEBUG) < 0)
1268 		syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1269 	if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1270 		syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1271 #ifdef SO_PRIVSTATE
1272 	if (turnon(sep->se_fd, SO_PRIVSTATE) < 0)
1273 		syslog(LOG_ERR, "setsockopt (SO_PRIVSTATE): %m");
1274 #endif
1275 	/* tftpd opens a new connection then needs more infos */
1276 	if ((sep->se_family == AF_INET6) &&
1277 	    (strcmp(sep->se_proto, "udp") == 0) &&
1278 	    (sep->se_accept == 0) &&
1279 	    (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
1280 			(char *)&on, sizeof (on)) < 0))
1281 		syslog(LOG_ERR, "setsockopt (IPV6_RECVPKTINFO): %m");
1282 	if (sep->se_family == AF_INET6) {
1283 		int flag = sep->se_nomapped ? 1 : 0;
1284 		if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_V6ONLY,
1285 			       (char *)&flag, sizeof (flag)) < 0)
1286 			syslog(LOG_ERR, "setsockopt (IPV6_V6ONLY): %m");
1287 	}
1288 #undef turnon
1289 #ifdef IPSEC
1290 	ipsecsetup(sep);
1291 #endif
1292 	if (sep->se_family == AF_UNIX) {
1293 		(void) unlink(sep->se_ctrladdr_un.sun_path);
1294 		umask(0777); /* Make socket with conservative permissions */
1295 	}
1296 	if (bind(sep->se_fd, (struct sockaddr *)&sep->se_ctrladdr,
1297 	    sep->se_ctrladdr_size) < 0) {
1298 		if (debug)
1299 			warn("bind failed on %s/%s",
1300 				sep->se_service, sep->se_proto);
1301 		syslog(LOG_ERR, "%s/%s: bind: %m",
1302 		    sep->se_service, sep->se_proto);
1303 		(void) close(sep->se_fd);
1304 		sep->se_fd = -1;
1305 		if (!timingout) {
1306 			timingout = 1;
1307 			alarm(RETRYTIME);
1308 		}
1309 		if (sep->se_family == AF_UNIX)
1310 			umask(mask);
1311 		return;
1312 	}
1313 	if (sep->se_family == AF_UNIX) {
1314 		/* Ick - fch{own,mod} don't work on Unix domain sockets */
1315 		if (chown(sep->se_service, sep->se_sockuid, sep->se_sockgid) < 0)
1316 			syslog(LOG_ERR, "chown socket: %m");
1317 		if (chmod(sep->se_service, sep->se_sockmode) < 0)
1318 			syslog(LOG_ERR, "chmod socket: %m");
1319 		umask(mask);
1320 	}
1321         if (sep->se_rpc) {
1322 		u_int i;
1323 		socklen_t len = sep->se_ctrladdr_size;
1324 		struct netconfig *netid, *netid2 = NULL;
1325 		struct sockaddr_in sock;
1326 		struct netbuf nbuf, nbuf2;
1327 
1328                 if (getsockname(sep->se_fd,
1329 				(struct sockaddr*)&sep->se_ctrladdr, &len) < 0){
1330                         syslog(LOG_ERR, "%s/%s: getsockname: %m",
1331                                sep->se_service, sep->se_proto);
1332                         (void) close(sep->se_fd);
1333                         sep->se_fd = -1;
1334                         return;
1335                 }
1336 		nbuf.buf = &sep->se_ctrladdr;
1337 		nbuf.len = sep->se_ctrladdr.sa_len;
1338 		if (sep->se_family == AF_INET)
1339 			netid = sep->se_socktype==SOCK_DGRAM? udpconf:tcpconf;
1340 		else  {
1341 			netid = sep->se_socktype==SOCK_DGRAM? udp6conf:tcp6conf;
1342 			if (!sep->se_nomapped) { /* INET and INET6 */
1343 				netid2 = netid==udp6conf? udpconf:tcpconf;
1344 				memset(&sock, 0, sizeof sock);	/* ADDR_ANY */
1345 				nbuf2.buf = &sock;
1346 				nbuf2.len = sock.sin_len = sizeof sock;
1347 				sock.sin_family = AF_INET;
1348 				sock.sin_port = sep->se_ctrladdr6.sin6_port;
1349 			}
1350 		}
1351                 if (debug)
1352                         print_service("REG ", sep);
1353                 for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++) {
1354 			rpcb_unset(sep->se_rpc_prog, i, netid);
1355 			rpcb_set(sep->se_rpc_prog, i, netid, &nbuf);
1356 			if (netid2) {
1357 				rpcb_unset(sep->se_rpc_prog, i, netid2);
1358 				rpcb_set(sep->se_rpc_prog, i, netid2, &nbuf2);
1359 			}
1360                 }
1361         }
1362 	if (sep->se_socktype == SOCK_STREAM)
1363 		listen(sep->se_fd, -1);
1364 	enable(sep);
1365 	if (debug) {
1366 		warnx("registered %s on %d",
1367 			sep->se_server, sep->se_fd);
1368 	}
1369 }
1370 
1371 #ifdef IPSEC
1372 void
1373 ipsecsetup(struct servtab *sep)
1374 {
1375 	char *buf;
1376 	char *policy_in = NULL;
1377 	char *policy_out = NULL;
1378 	int level;
1379 	int opt;
1380 
1381 	switch (sep->se_family) {
1382 	case AF_INET:
1383 		level = IPPROTO_IP;
1384 		opt = IP_IPSEC_POLICY;
1385 		break;
1386 #ifdef INET6
1387 	case AF_INET6:
1388 		level = IPPROTO_IPV6;
1389 		opt = IPV6_IPSEC_POLICY;
1390 		break;
1391 #endif
1392 	default:
1393 		return;
1394 	}
1395 
1396 	if (!sep->se_policy || sep->se_policy[0] == '\0') {
1397 		static char def_in[] = "in entrust", def_out[] = "out entrust";
1398 		policy_in = def_in;
1399 		policy_out = def_out;
1400 	} else {
1401 		if (!strncmp("in", sep->se_policy, 2))
1402 			policy_in = sep->se_policy;
1403 		else if (!strncmp("out", sep->se_policy, 3))
1404 			policy_out = sep->se_policy;
1405 		else {
1406 			syslog(LOG_ERR, "invalid security policy \"%s\"",
1407 				sep->se_policy);
1408 			return;
1409 		}
1410 	}
1411 
1412 	if (policy_in != NULL) {
1413 		buf = ipsec_set_policy(policy_in, strlen(policy_in));
1414 		if (buf != NULL) {
1415 			if (setsockopt(sep->se_fd, level, opt,
1416 					buf, ipsec_get_policylen(buf)) < 0 &&
1417 			    debug != 0)
1418 				warnx("%s/%s: ipsec initialization failed; %s",
1419 				      sep->se_service, sep->se_proto,
1420 				      policy_in);
1421 			free(buf);
1422 		} else
1423 			syslog(LOG_ERR, "invalid security policy \"%s\"",
1424 				policy_in);
1425 	}
1426 	if (policy_out != NULL) {
1427 		buf = ipsec_set_policy(policy_out, strlen(policy_out));
1428 		if (buf != NULL) {
1429 			if (setsockopt(sep->se_fd, level, opt,
1430 					buf, ipsec_get_policylen(buf)) < 0 &&
1431 			    debug != 0)
1432 				warnx("%s/%s: ipsec initialization failed; %s",
1433 				      sep->se_service, sep->se_proto,
1434 				      policy_out);
1435 			free(buf);
1436 		} else
1437 			syslog(LOG_ERR, "invalid security policy \"%s\"",
1438 				policy_out);
1439 	}
1440 }
1441 #endif
1442 
1443 /*
1444  * Finish with a service and its socket.
1445  */
1446 void
1447 close_sep(struct servtab *sep)
1448 {
1449 	if (sep->se_fd >= 0) {
1450 		if (FD_ISSET(sep->se_fd, &allsock))
1451 			disable(sep);
1452 		(void) close(sep->se_fd);
1453 		sep->se_fd = -1;
1454 	}
1455 	sep->se_count = 0;
1456 	sep->se_numchild = 0;	/* forget about any existing children */
1457 }
1458 
1459 int
1460 matchservent(const char *name1, const char *name2, const char *proto)
1461 {
1462 	char **alias, *p;
1463 	struct servent *se;
1464 
1465 	if (strcmp(proto, "unix") == 0) {
1466 		if ((p = strrchr(name1, '/')) != NULL)
1467 			name1 = p + 1;
1468 		if ((p = strrchr(name2, '/')) != NULL)
1469 			name2 = p + 1;
1470 	}
1471 	if (strcmp(name1, name2) == 0)
1472 		return(1);
1473 	if ((se = getservbyname(name1, proto)) != NULL) {
1474 		if (strcmp(name2, se->s_name) == 0)
1475 			return(1);
1476 		for (alias = se->s_aliases; *alias; alias++)
1477 			if (strcmp(name2, *alias) == 0)
1478 				return(1);
1479 	}
1480 	return(0);
1481 }
1482 
1483 struct servtab *
1484 enter(struct servtab *cp)
1485 {
1486 	struct servtab *sep;
1487 	long omask;
1488 
1489 	sep = (struct servtab *)malloc(sizeof (*sep));
1490 	if (sep == (struct servtab *)0) {
1491 		syslog(LOG_ERR, "malloc: %m");
1492 		exit(EX_OSERR);
1493 	}
1494 	*sep = *cp;
1495 	sep->se_fd = -1;
1496 	omask = sigblock(SIGBLOCK);
1497 	sep->se_next = servtab;
1498 	servtab = sep;
1499 	sigsetmask(omask);
1500 	return (sep);
1501 }
1502 
1503 void
1504 enable(struct servtab *sep)
1505 {
1506 	if (debug)
1507 		warnx(
1508 		    "enabling %s, fd %d", sep->se_service, sep->se_fd);
1509 #ifdef SANITY_CHECK
1510 	if (sep->se_fd < 0) {
1511 		syslog(LOG_ERR,
1512 		    "%s: %s: bad fd", __func__, sep->se_service);
1513 		exit(EX_SOFTWARE);
1514 	}
1515 	if (ISMUX(sep)) {
1516 		syslog(LOG_ERR,
1517 		    "%s: %s: is mux", __func__, sep->se_service);
1518 		exit(EX_SOFTWARE);
1519 	}
1520 	if (FD_ISSET(sep->se_fd, &allsock)) {
1521 		syslog(LOG_ERR,
1522 		    "%s: %s: not off", __func__, sep->se_service);
1523 		exit(EX_SOFTWARE);
1524 	}
1525 	nsock++;
1526 #endif
1527 	FD_SET(sep->se_fd, &allsock);
1528 	if (sep->se_fd > maxsock)
1529 		maxsock = sep->se_fd;
1530 }
1531 
1532 void
1533 disable(struct servtab *sep)
1534 {
1535 	if (debug)
1536 		warnx(
1537 		    "disabling %s, fd %d", sep->se_service, sep->se_fd);
1538 #ifdef SANITY_CHECK
1539 	if (sep->se_fd < 0) {
1540 		syslog(LOG_ERR,
1541 		    "%s: %s: bad fd", __func__, sep->se_service);
1542 		exit(EX_SOFTWARE);
1543 	}
1544 	if (ISMUX(sep)) {
1545 		syslog(LOG_ERR,
1546 		    "%s: %s: is mux", __func__, sep->se_service);
1547 		exit(EX_SOFTWARE);
1548 	}
1549 	if (!FD_ISSET(sep->se_fd, &allsock)) {
1550 		syslog(LOG_ERR,
1551 		    "%s: %s: not on", __func__, sep->se_service);
1552 		exit(EX_SOFTWARE);
1553 	}
1554 	if (nsock == 0) {
1555 		syslog(LOG_ERR, "%s: nsock=0", __func__);
1556 		exit(EX_SOFTWARE);
1557 	}
1558 	nsock--;
1559 #endif
1560 	FD_CLR(sep->se_fd, &allsock);
1561 	if (sep->se_fd == maxsock)
1562 		maxsock--;
1563 }
1564 
1565 FILE	*fconfig = NULL;
1566 struct	servtab serv;
1567 char	line[LINE_MAX];
1568 
1569 int
1570 setconfig(void)
1571 {
1572 
1573 	if (fconfig != NULL) {
1574 		fseek(fconfig, 0L, SEEK_SET);
1575 		return (1);
1576 	}
1577 	fconfig = fopen(CONFIG, "r");
1578 	return (fconfig != NULL);
1579 }
1580 
1581 void
1582 endconfig(void)
1583 {
1584 	if (fconfig) {
1585 		(void) fclose(fconfig);
1586 		fconfig = NULL;
1587 	}
1588 }
1589 
1590 struct servtab *
1591 getconfigent(void)
1592 {
1593 	struct servtab *sep = &serv;
1594 	int argc;
1595 	char *cp, *arg, *s;
1596 	char *versp;
1597 	static char TCPMUX_TOKEN[] = "tcpmux/";
1598 #define MUX_LEN		(sizeof(TCPMUX_TOKEN)-1)
1599 #ifdef IPSEC
1600 	char *policy;
1601 #endif
1602 	int v4bind;
1603 #ifdef INET6
1604 	int v6bind;
1605 #endif
1606 	int i;
1607 
1608 #ifdef IPSEC
1609 	policy = NULL;
1610 #endif
1611 more:
1612 	v4bind = 0;
1613 #ifdef INET6
1614 	v6bind = 0;
1615 #endif
1616 	while ((cp = nextline(fconfig)) != NULL) {
1617 #ifdef IPSEC
1618 		/* lines starting with #@ is not a comment, but the policy */
1619 		if (cp[0] == '#' && cp[1] == '@') {
1620 			char *p;
1621 			for (p = cp + 2; p && *p && isspace(*p); p++)
1622 				;
1623 			if (*p == '\0') {
1624 				if (policy)
1625 					free(policy);
1626 				policy = NULL;
1627 			} else if (ipsec_get_policylen(p) >= 0) {
1628 				if (policy)
1629 					free(policy);
1630 				policy = newstr(p);
1631 			} else {
1632 				syslog(LOG_ERR,
1633 					"%s: invalid ipsec policy \"%s\"",
1634 					CONFIG, p);
1635 				exit(EX_CONFIG);
1636 			}
1637 		}
1638 #endif
1639 		if (*cp == '#' || *cp == '\0')
1640 			continue;
1641 		break;
1642 	}
1643 	if (cp == NULL)
1644 		return ((struct servtab *)0);
1645 	/*
1646 	 * clear the static buffer, since some fields (se_ctrladdr,
1647 	 * for example) don't get initialized here.
1648 	 */
1649 	memset(sep, 0, sizeof *sep);
1650 	arg = skip(&cp);
1651 	if (cp == NULL) {
1652 		/* got an empty line containing just blanks/tabs. */
1653 		goto more;
1654 	}
1655 	if (arg[0] == ':') { /* :user:group:perm: */
1656 		char *user, *group, *perm;
1657 		struct passwd *pw;
1658 		struct group *gr;
1659 		user = arg+1;
1660 		if ((group = strchr(user, ':')) == NULL) {
1661 			syslog(LOG_ERR, "no group after user '%s'", user);
1662 			goto more;
1663 		}
1664 		*group++ = '\0';
1665 		if ((perm = strchr(group, ':')) == NULL) {
1666 			syslog(LOG_ERR, "no mode after group '%s'", group);
1667 			goto more;
1668 		}
1669 		*perm++ = '\0';
1670 		if ((pw = getpwnam(user)) == NULL) {
1671 			syslog(LOG_ERR, "no such user '%s'", user);
1672 			goto more;
1673 		}
1674 		sep->se_sockuid = pw->pw_uid;
1675 		if ((gr = getgrnam(group)) == NULL) {
1676 			syslog(LOG_ERR, "no such user '%s'", group);
1677 			goto more;
1678 		}
1679 		sep->se_sockgid = gr->gr_gid;
1680 		sep->se_sockmode = strtol(perm, &arg, 8);
1681 		if (*arg != ':') {
1682 			syslog(LOG_ERR, "bad mode '%s'", perm);
1683 			goto more;
1684 		}
1685 		*arg++ = '\0';
1686 	} else {
1687 		sep->se_sockuid = euid;
1688 		sep->se_sockgid = egid;
1689 		sep->se_sockmode = 0200;
1690 	}
1691 	if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1692 		char *c = arg + MUX_LEN;
1693 		if (*c == '+') {
1694 			sep->se_type = MUXPLUS_TYPE;
1695 			c++;
1696 		} else
1697 			sep->se_type = MUX_TYPE;
1698 		sep->se_service = newstr(c);
1699 	} else {
1700 		sep->se_service = newstr(arg);
1701 		sep->se_type = NORM_TYPE;
1702 	}
1703 	arg = sskip(&cp);
1704 	if (strcmp(arg, "stream") == 0)
1705 		sep->se_socktype = SOCK_STREAM;
1706 	else if (strcmp(arg, "dgram") == 0)
1707 		sep->se_socktype = SOCK_DGRAM;
1708 	else if (strcmp(arg, "rdm") == 0)
1709 		sep->se_socktype = SOCK_RDM;
1710 	else if (strcmp(arg, "seqpacket") == 0)
1711 		sep->se_socktype = SOCK_SEQPACKET;
1712 	else if (strcmp(arg, "raw") == 0)
1713 		sep->se_socktype = SOCK_RAW;
1714 	else
1715 		sep->se_socktype = -1;
1716 
1717 	arg = sskip(&cp);
1718 	if (strncmp(arg, "tcp", 3) == 0) {
1719 		sep->se_proto = newstr(strsep(&arg, "/"));
1720 		if (arg != NULL && (strcmp(arg, "faith") == 0)) {
1721 			syslog(LOG_ERR, "faith has been deprecated");
1722 			goto more;
1723 		}
1724 	} else {
1725 		if (sep->se_type == NORM_TYPE &&
1726 		    strncmp(arg, "faith/", 6) == 0) {
1727 			syslog(LOG_ERR, "faith has been deprecated");
1728 			goto more;
1729 		}
1730 		sep->se_proto = newstr(arg);
1731 	}
1732         if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1733                 memmove(sep->se_proto, sep->se_proto + 4,
1734                     strlen(sep->se_proto) + 1 - 4);
1735                 sep->se_rpc = 1;
1736                 sep->se_rpc_prog = sep->se_rpc_lowvers =
1737 			sep->se_rpc_highvers = 0;
1738                 if ((versp = strrchr(sep->se_service, '/'))) {
1739                         *versp++ = '\0';
1740                         switch (sscanf(versp, "%u-%u",
1741                                        &sep->se_rpc_lowvers,
1742                                        &sep->se_rpc_highvers)) {
1743                         case 2:
1744                                 break;
1745                         case 1:
1746                                 sep->se_rpc_highvers =
1747                                         sep->se_rpc_lowvers;
1748                                 break;
1749                         default:
1750                                 syslog(LOG_ERR,
1751 					"bad RPC version specifier; %s",
1752 					sep->se_service);
1753                                 freeconfig(sep);
1754                                 goto more;
1755                         }
1756                 }
1757                 else {
1758                         sep->se_rpc_lowvers =
1759                                 sep->se_rpc_highvers = 1;
1760                 }
1761         }
1762 	sep->se_nomapped = 0;
1763 	if (strcmp(sep->se_proto, "unix") == 0) {
1764 	        sep->se_family = AF_UNIX;
1765 	} else {
1766 		while (isdigit(sep->se_proto[strlen(sep->se_proto) - 1])) {
1767 #ifdef INET6
1768 			if (sep->se_proto[strlen(sep->se_proto) - 1] == '6') {
1769 				sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1770 				v6bind = 1;
1771 				continue;
1772 			}
1773 #endif
1774 			if (sep->se_proto[strlen(sep->se_proto) - 1] == '4') {
1775 				sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1776 				v4bind = 1;
1777 				continue;
1778 			}
1779 			/* illegal version num */
1780 			syslog(LOG_ERR,	"bad IP version for %s", sep->se_proto);
1781 			freeconfig(sep);
1782 			goto more;
1783 		}
1784 #ifdef INET6
1785 		if (v6bind && !v6bind_ok) {
1786 			syslog(LOG_INFO, "IPv6 bind is ignored for %s",
1787 			       sep->se_service);
1788 			if (v4bind && v4bind_ok)
1789 				v6bind = 0;
1790 			else {
1791 				freeconfig(sep);
1792 				goto more;
1793 			}
1794 		}
1795 		if (v6bind) {
1796 			sep->se_family = AF_INET6;
1797 			if (!v4bind || !v4bind_ok)
1798 				sep->se_nomapped = 1;
1799 		} else
1800 #endif
1801 		{ /* default to v4 bind if not v6 bind */
1802 			if (!v4bind_ok) {
1803 				syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1804 				       sep->se_service);
1805 				freeconfig(sep);
1806 				goto more;
1807 			}
1808 			sep->se_family = AF_INET;
1809 		}
1810 	}
1811 	/* init ctladdr */
1812 	switch(sep->se_family) {
1813 	case AF_INET:
1814 		memcpy(&sep->se_ctrladdr4, bind_sa4,
1815 		       sizeof(sep->se_ctrladdr4));
1816 		sep->se_ctrladdr_size =	sizeof(sep->se_ctrladdr4);
1817 		break;
1818 #ifdef INET6
1819 	case AF_INET6:
1820 		memcpy(&sep->se_ctrladdr6, bind_sa6,
1821 		       sizeof(sep->se_ctrladdr6));
1822 		sep->se_ctrladdr_size =	sizeof(sep->se_ctrladdr6);
1823 		break;
1824 #endif
1825 	case AF_UNIX:
1826 		if (strlen(sep->se_service) >= sizeof(sep->se_ctrladdr_un.sun_path)) {
1827 			syslog(LOG_ERR,
1828 			    "domain socket pathname too long for service %s",
1829 			    sep->se_service);
1830 			goto more;
1831 		}
1832 		memset(&sep->se_ctrladdr, 0, sizeof(sep->se_ctrladdr));
1833 		sep->se_ctrladdr_un.sun_family = sep->se_family;
1834 		sep->se_ctrladdr_un.sun_len = strlen(sep->se_service);
1835 		strcpy(sep->se_ctrladdr_un.sun_path, sep->se_service);
1836 		sep->se_ctrladdr_size = SUN_LEN(&sep->se_ctrladdr_un);
1837 	}
1838 	arg = sskip(&cp);
1839 	if (!strncmp(arg, "wait", 4))
1840 		sep->se_accept = 0;
1841 	else if (!strncmp(arg, "nowait", 6))
1842 		sep->se_accept = 1;
1843 	else {
1844 		syslog(LOG_ERR,
1845 			"%s: bad wait/nowait for service %s",
1846 			CONFIG, sep->se_service);
1847 		goto more;
1848 	}
1849 	sep->se_maxchild = -1;
1850 	sep->se_maxcpm = -1;
1851 	sep->se_maxperip = -1;
1852 	if ((s = strchr(arg, '/')) != NULL) {
1853 		char *eptr;
1854 		u_long val;
1855 
1856 		val = strtoul(s + 1, &eptr, 10);
1857 		if (eptr == s + 1 || val > MAX_MAXCHLD) {
1858 			syslog(LOG_ERR,
1859 				"%s: bad max-child for service %s",
1860 				CONFIG, sep->se_service);
1861 			goto more;
1862 		}
1863 		if (debug)
1864 			if (!sep->se_accept && val != 1)
1865 				warnx("maxchild=%lu for wait service %s"
1866 				    " not recommended", val, sep->se_service);
1867 		sep->se_maxchild = val;
1868 		if (*eptr == '/')
1869 			sep->se_maxcpm = strtol(eptr + 1, &eptr, 10);
1870 		if (*eptr == '/')
1871 			sep->se_maxperip = strtol(eptr + 1, &eptr, 10);
1872 		/*
1873 		 * explicitly do not check for \0 for future expansion /
1874 		 * backwards compatibility
1875 		 */
1876 	}
1877 	if (ISMUX(sep)) {
1878 		/*
1879 		 * Silently enforce "nowait" mode for TCPMUX services
1880 		 * since they don't have an assigned port to listen on.
1881 		 */
1882 		sep->se_accept = 1;
1883 		if (strcmp(sep->se_proto, "tcp")) {
1884 			syslog(LOG_ERR,
1885 				"%s: bad protocol for tcpmux service %s",
1886 				CONFIG, sep->se_service);
1887 			goto more;
1888 		}
1889 		if (sep->se_socktype != SOCK_STREAM) {
1890 			syslog(LOG_ERR,
1891 				"%s: bad socket type for tcpmux service %s",
1892 				CONFIG, sep->se_service);
1893 			goto more;
1894 		}
1895 	}
1896 	sep->se_user = newstr(sskip(&cp));
1897 #ifdef LOGIN_CAP
1898 	if ((s = strrchr(sep->se_user, '/')) != NULL) {
1899 		*s = '\0';
1900 		sep->se_class = newstr(s + 1);
1901 	} else
1902 		sep->se_class = newstr(RESOURCE_RC);
1903 #endif
1904 	if ((s = strrchr(sep->se_user, ':')) != NULL) {
1905 		*s = '\0';
1906 		sep->se_group = newstr(s + 1);
1907 	} else
1908 		sep->se_group = NULL;
1909 	sep->se_server = newstr(sskip(&cp));
1910 	if ((sep->se_server_name = strrchr(sep->se_server, '/')))
1911 		sep->se_server_name++;
1912 	if (strcmp(sep->se_server, "internal") == 0) {
1913 		struct biltin *bi;
1914 
1915 		for (bi = biltins; bi->bi_service; bi++)
1916 			if (bi->bi_socktype == sep->se_socktype &&
1917 			    matchservent(bi->bi_service, sep->se_service,
1918 			    sep->se_proto))
1919 				break;
1920 		if (bi->bi_service == 0) {
1921 			syslog(LOG_ERR, "internal service %s unknown",
1922 				sep->se_service);
1923 			goto more;
1924 		}
1925 		sep->se_accept = 1;	/* force accept mode for built-ins */
1926 		sep->se_bi = bi;
1927 	} else
1928 		sep->se_bi = NULL;
1929 	if (sep->se_maxperip < 0)
1930 		sep->se_maxperip = maxperip;
1931 	if (sep->se_maxcpm < 0)
1932 		sep->se_maxcpm = maxcpm;
1933 	if (sep->se_maxchild < 0) {	/* apply default max-children */
1934 		if (sep->se_bi && sep->se_bi->bi_maxchild >= 0)
1935 			sep->se_maxchild = sep->se_bi->bi_maxchild;
1936 		else if (sep->se_accept)
1937 			sep->se_maxchild = maxchild > 0 ? maxchild : 0;
1938 		else
1939 			sep->se_maxchild = 1;
1940 	}
1941 	if (sep->se_maxchild > 0) {
1942 		sep->se_pids = malloc(sep->se_maxchild * sizeof(*sep->se_pids));
1943 		if (sep->se_pids == NULL) {
1944 			syslog(LOG_ERR, "malloc: %m");
1945 			exit(EX_OSERR);
1946 		}
1947 	}
1948 	argc = 0;
1949 	for (arg = skip(&cp); cp; arg = skip(&cp))
1950 		if (argc < MAXARGV) {
1951 			sep->se_argv[argc++] = newstr(arg);
1952 		} else {
1953 			syslog(LOG_ERR,
1954 				"%s: too many arguments for service %s",
1955 				CONFIG, sep->se_service);
1956 			goto more;
1957 		}
1958 	while (argc <= MAXARGV)
1959 		sep->se_argv[argc++] = NULL;
1960 	for (i = 0; i < PERIPSIZE; ++i)
1961 		LIST_INIT(&sep->se_conn[i]);
1962 #ifdef IPSEC
1963 	sep->se_policy = policy ? newstr(policy) : NULL;
1964 #endif
1965 	return (sep);
1966 }
1967 
1968 void
1969 freeconfig(struct servtab *cp)
1970 {
1971 	int i;
1972 
1973 	if (cp->se_service)
1974 		free(cp->se_service);
1975 	if (cp->se_proto)
1976 		free(cp->se_proto);
1977 	if (cp->se_user)
1978 		free(cp->se_user);
1979 	if (cp->se_group)
1980 		free(cp->se_group);
1981 #ifdef LOGIN_CAP
1982 	if (cp->se_class)
1983 		free(cp->se_class);
1984 #endif
1985 	if (cp->se_server)
1986 		free(cp->se_server);
1987 	if (cp->se_pids)
1988 		free(cp->se_pids);
1989 	for (i = 0; i < MAXARGV; i++)
1990 		if (cp->se_argv[i])
1991 			free(cp->se_argv[i]);
1992 	free_connlist(cp);
1993 #ifdef IPSEC
1994 	if (cp->se_policy)
1995 		free(cp->se_policy);
1996 #endif
1997 }
1998 
1999 
2000 /*
2001  * Safe skip - if skip returns null, log a syntax error in the
2002  * configuration file and exit.
2003  */
2004 char *
2005 sskip(char **cpp)
2006 {
2007 	char *cp;
2008 
2009 	cp = skip(cpp);
2010 	if (cp == NULL) {
2011 		syslog(LOG_ERR, "%s: syntax error", CONFIG);
2012 		exit(EX_DATAERR);
2013 	}
2014 	return (cp);
2015 }
2016 
2017 char *
2018 skip(char **cpp)
2019 {
2020 	char *cp = *cpp;
2021 	char *start;
2022 	char quote = '\0';
2023 
2024 again:
2025 	while (*cp == ' ' || *cp == '\t')
2026 		cp++;
2027 	if (*cp == '\0') {
2028 		int c;
2029 
2030 		c = getc(fconfig);
2031 		(void) ungetc(c, fconfig);
2032 		if (c == ' ' || c == '\t')
2033 			if ((cp = nextline(fconfig)))
2034 				goto again;
2035 		*cpp = (char *)0;
2036 		return ((char *)0);
2037 	}
2038 	if (*cp == '"' || *cp == '\'')
2039 		quote = *cp++;
2040 	start = cp;
2041 	if (quote)
2042 		while (*cp && *cp != quote)
2043 			cp++;
2044 	else
2045 		while (*cp && *cp != ' ' && *cp != '\t')
2046 			cp++;
2047 	if (*cp != '\0')
2048 		*cp++ = '\0';
2049 	*cpp = cp;
2050 	return (start);
2051 }
2052 
2053 char *
2054 nextline(FILE *fd)
2055 {
2056 	char *cp;
2057 
2058 	if (fgets(line, sizeof (line), fd) == NULL)
2059 		return ((char *)0);
2060 	cp = strchr(line, '\n');
2061 	if (cp)
2062 		*cp = '\0';
2063 	return (line);
2064 }
2065 
2066 char *
2067 newstr(const char *cp)
2068 {
2069 	char *cr;
2070 
2071 	if ((cr = strdup(cp != NULL ? cp : "")))
2072 		return (cr);
2073 	syslog(LOG_ERR, "strdup: %m");
2074 	exit(EX_OSERR);
2075 }
2076 
2077 void
2078 inetd_setproctitle(const char *a, int s)
2079 {
2080 	socklen_t size;
2081 	struct sockaddr_storage ss;
2082 	char buf[80], pbuf[NI_MAXHOST];
2083 
2084 	size = sizeof(ss);
2085 	if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
2086 		getnameinfo((struct sockaddr *)&ss, size, pbuf, sizeof(pbuf),
2087 			    NULL, 0, NI_NUMERICHOST);
2088 		(void) sprintf(buf, "%s [%s]", a, pbuf);
2089 	} else
2090 		(void) sprintf(buf, "%s", a);
2091 	setproctitle("%s", buf);
2092 }
2093 
2094 int
2095 check_loop(const struct sockaddr *sa, const struct servtab *sep)
2096 {
2097 	struct servtab *se2;
2098 	char pname[NI_MAXHOST];
2099 
2100 	for (se2 = servtab; se2; se2 = se2->se_next) {
2101 		if (!se2->se_bi || se2->se_socktype != SOCK_DGRAM)
2102 			continue;
2103 
2104 		switch (se2->se_family) {
2105 		case AF_INET:
2106 			if (((const struct sockaddr_in *)sa)->sin_port ==
2107 			    se2->se_ctrladdr4.sin_port)
2108 				goto isloop;
2109 			continue;
2110 #ifdef INET6
2111 		case AF_INET6:
2112 			if (((const struct sockaddr_in6 *)sa)->sin6_port ==
2113 			    se2->se_ctrladdr6.sin6_port)
2114 				goto isloop;
2115 			continue;
2116 #endif
2117 		default:
2118 			continue;
2119 		}
2120 	isloop:
2121 		getnameinfo(sa, sa->sa_len, pname, sizeof(pname), NULL, 0,
2122 			    NI_NUMERICHOST);
2123 		syslog(LOG_WARNING, "%s/%s:%s/%s loop request REFUSED from %s",
2124 		       sep->se_service, sep->se_proto,
2125 		       se2->se_service, se2->se_proto,
2126 		       pname);
2127 		return 1;
2128 	}
2129 	return 0;
2130 }
2131 
2132 /*
2133  * print_service:
2134  *	Dump relevant information to stderr
2135  */
2136 void
2137 print_service(const char *action, const struct servtab *sep)
2138 {
2139 	fprintf(stderr,
2140 	    "%s: %s proto=%s accept=%d max=%d user=%s group=%s"
2141 #ifdef LOGIN_CAP
2142 	    "class=%s"
2143 #endif
2144 	    " builtin=%p server=%s"
2145 #ifdef IPSEC
2146 	    " policy=\"%s\""
2147 #endif
2148 	    "\n",
2149 	    action, sep->se_service, sep->se_proto,
2150 	    sep->se_accept, sep->se_maxchild, sep->se_user, sep->se_group,
2151 #ifdef LOGIN_CAP
2152 	    sep->se_class,
2153 #endif
2154 	    (void *) sep->se_bi, sep->se_server
2155 #ifdef IPSEC
2156 	    , (sep->se_policy ? sep->se_policy : "")
2157 #endif
2158 	    );
2159 }
2160 
2161 #define CPMHSIZE	256
2162 #define CPMHMASK	(CPMHSIZE-1)
2163 #define CHTGRAN		10
2164 #define CHTSIZE		6
2165 
2166 typedef struct CTime {
2167 	unsigned long 	ct_Ticks;
2168 	int		ct_Count;
2169 } CTime;
2170 
2171 typedef struct CHash {
2172 	union {
2173 		struct in_addr	c4_Addr;
2174 		struct in6_addr	c6_Addr;
2175 	} cu_Addr;
2176 #define	ch_Addr4	cu_Addr.c4_Addr
2177 #define	ch_Addr6	cu_Addr.c6_Addr
2178 	int		ch_Family;
2179 	time_t		ch_LTime;
2180 	char		*ch_Service;
2181 	CTime		ch_Times[CHTSIZE];
2182 } CHash;
2183 
2184 CHash	CHashAry[CPMHSIZE];
2185 
2186 int
2187 cpmip(const struct servtab *sep, int ctrl)
2188 {
2189 	struct sockaddr_storage rss;
2190 	socklen_t rssLen = sizeof(rss);
2191 	int r = 0;
2192 
2193 	/*
2194 	 * If getpeername() fails, just let it through (if logging is
2195 	 * enabled the condition is caught elsewhere)
2196 	 */
2197 
2198 	if (sep->se_maxcpm > 0 &&
2199 	   (sep->se_family == AF_INET || sep->se_family == AF_INET6) &&
2200 	    getpeername(ctrl, (struct sockaddr *)&rss, &rssLen) == 0 ) {
2201 		time_t t = time(NULL);
2202 		int hv = 0xABC3D20F;
2203 		int i;
2204 		int cnt = 0;
2205 		CHash *chBest = NULL;
2206 		unsigned int ticks = t / CHTGRAN;
2207 		struct sockaddr_in *sin4;
2208 #ifdef INET6
2209 		struct sockaddr_in6 *sin6;
2210 #endif
2211 
2212 		sin4 = (struct sockaddr_in *)&rss;
2213 #ifdef INET6
2214 		sin6 = (struct sockaddr_in6 *)&rss;
2215 #endif
2216 		{
2217 			char *p;
2218 			int addrlen;
2219 
2220 			switch (rss.ss_family) {
2221 			case AF_INET:
2222 				p = (char *)&sin4->sin_addr;
2223 				addrlen = sizeof(struct in_addr);
2224 				break;
2225 #ifdef INET6
2226 			case AF_INET6:
2227 				p = (char *)&sin6->sin6_addr;
2228 				addrlen = sizeof(struct in6_addr);
2229 				break;
2230 #endif
2231 			default:
2232 				/* should not happen */
2233 				return -1;
2234 			}
2235 
2236 			for (i = 0; i < addrlen; ++i, ++p) {
2237 				hv = (hv << 5) ^ (hv >> 23) ^ *p;
2238 			}
2239 			hv = (hv ^ (hv >> 16));
2240 		}
2241 		for (i = 0; i < 5; ++i) {
2242 			CHash *ch = &CHashAry[(hv + i) & CPMHMASK];
2243 
2244 			if (rss.ss_family == AF_INET &&
2245 			    ch->ch_Family == AF_INET &&
2246 			    sin4->sin_addr.s_addr == ch->ch_Addr4.s_addr &&
2247 			    ch->ch_Service && strcmp(sep->se_service,
2248 			    ch->ch_Service) == 0) {
2249 				chBest = ch;
2250 				break;
2251 			}
2252 #ifdef INET6
2253 			if (rss.ss_family == AF_INET6 &&
2254 			    ch->ch_Family == AF_INET6 &&
2255 			    IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2256 					       &ch->ch_Addr6) != 0 &&
2257 			    ch->ch_Service && strcmp(sep->se_service,
2258 			    ch->ch_Service) == 0) {
2259 				chBest = ch;
2260 				break;
2261 			}
2262 #endif
2263 			if (chBest == NULL || ch->ch_LTime == 0 ||
2264 			    ch->ch_LTime < chBest->ch_LTime) {
2265 				chBest = ch;
2266 			}
2267 		}
2268 		if ((rss.ss_family == AF_INET &&
2269 		     (chBest->ch_Family != AF_INET ||
2270 		      sin4->sin_addr.s_addr != chBest->ch_Addr4.s_addr)) ||
2271 		    chBest->ch_Service == NULL ||
2272 		    strcmp(sep->se_service, chBest->ch_Service) != 0) {
2273 			chBest->ch_Family = sin4->sin_family;
2274 			chBest->ch_Addr4 = sin4->sin_addr;
2275 			if (chBest->ch_Service)
2276 				free(chBest->ch_Service);
2277 			chBest->ch_Service = strdup(sep->se_service);
2278 			bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2279 		}
2280 #ifdef INET6
2281 		if ((rss.ss_family == AF_INET6 &&
2282 		     (chBest->ch_Family != AF_INET6 ||
2283 		      IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2284 					 &chBest->ch_Addr6) == 0)) ||
2285 		    chBest->ch_Service == NULL ||
2286 		    strcmp(sep->se_service, chBest->ch_Service) != 0) {
2287 			chBest->ch_Family = sin6->sin6_family;
2288 			chBest->ch_Addr6 = sin6->sin6_addr;
2289 			if (chBest->ch_Service)
2290 				free(chBest->ch_Service);
2291 			chBest->ch_Service = strdup(sep->se_service);
2292 			bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2293 		}
2294 #endif
2295 		chBest->ch_LTime = t;
2296 		{
2297 			CTime *ct = &chBest->ch_Times[ticks % CHTSIZE];
2298 			if (ct->ct_Ticks != ticks) {
2299 				ct->ct_Ticks = ticks;
2300 				ct->ct_Count = 0;
2301 			}
2302 			++ct->ct_Count;
2303 		}
2304 		for (i = 0; i < CHTSIZE; ++i) {
2305 			CTime *ct = &chBest->ch_Times[i];
2306 			if (ct->ct_Ticks <= ticks &&
2307 			    ct->ct_Ticks >= ticks - CHTSIZE) {
2308 				cnt += ct->ct_Count;
2309 			}
2310 		}
2311 		if ((cnt * 60) / (CHTSIZE * CHTGRAN) > sep->se_maxcpm) {
2312 			char pname[NI_MAXHOST];
2313 
2314 			getnameinfo((struct sockaddr *)&rss,
2315 				    ((struct sockaddr *)&rss)->sa_len,
2316 				    pname, sizeof(pname), NULL, 0,
2317 				    NI_NUMERICHOST);
2318 			r = -1;
2319 			syslog(LOG_ERR,
2320 			    "%s from %s exceeded counts/min (limit %d/min)",
2321 			    sep->se_service, pname,
2322 			    sep->se_maxcpm);
2323 		}
2324 	}
2325 	return(r);
2326 }
2327 
2328 static struct conninfo *
2329 search_conn(struct servtab *sep, int ctrl)
2330 {
2331 	struct sockaddr_storage ss;
2332 	socklen_t sslen = sizeof(ss);
2333 	struct conninfo *conn;
2334 	int hv;
2335 	char pname[NI_MAXHOST],  pname2[NI_MAXHOST];
2336 
2337 	if (sep->se_maxperip <= 0)
2338 		return NULL;
2339 
2340 	/*
2341 	 * If getpeername() fails, just let it through (if logging is
2342 	 * enabled the condition is caught elsewhere)
2343 	 */
2344 	if (getpeername(ctrl, (struct sockaddr *)&ss, &sslen) != 0)
2345 		return NULL;
2346 
2347 	switch (ss.ss_family) {
2348 	case AF_INET:
2349 		hv = hashval((char *)&((struct sockaddr_in *)&ss)->sin_addr,
2350 		    sizeof(struct in_addr));
2351 		break;
2352 #ifdef INET6
2353 	case AF_INET6:
2354 		hv = hashval((char *)&((struct sockaddr_in6 *)&ss)->sin6_addr,
2355 		    sizeof(struct in6_addr));
2356 		break;
2357 #endif
2358 	default:
2359 		/*
2360 		 * Since we only support AF_INET and AF_INET6, just
2361 		 * let other than AF_INET and AF_INET6 through.
2362 		 */
2363 		return NULL;
2364 	}
2365 
2366 	if (getnameinfo((struct sockaddr *)&ss, sslen, pname, sizeof(pname),
2367 	    NULL, 0, NI_NUMERICHOST) != 0)
2368 		return NULL;
2369 
2370 	LIST_FOREACH(conn, &sep->se_conn[hv], co_link) {
2371 		if (getnameinfo((struct sockaddr *)&conn->co_addr,
2372 		    conn->co_addr.ss_len, pname2, sizeof(pname2), NULL, 0,
2373 		    NI_NUMERICHOST) == 0 &&
2374 		    strcmp(pname, pname2) == 0)
2375 			break;
2376 	}
2377 
2378 	if (conn == NULL) {
2379 		if ((conn = malloc(sizeof(struct conninfo))) == NULL) {
2380 			syslog(LOG_ERR, "malloc: %m");
2381 			exit(EX_OSERR);
2382 		}
2383 		conn->co_proc = malloc(sep->se_maxperip * sizeof(*conn->co_proc));
2384 		if (conn->co_proc == NULL) {
2385 			syslog(LOG_ERR, "malloc: %m");
2386 			exit(EX_OSERR);
2387 		}
2388 		memcpy(&conn->co_addr, (struct sockaddr *)&ss, sslen);
2389 		conn->co_numchild = 0;
2390 		LIST_INSERT_HEAD(&sep->se_conn[hv], conn, co_link);
2391 	}
2392 
2393 	/*
2394 	 * Since a child process is not invoked yet, we cannot
2395 	 * determine a pid of a child.  So, co_proc and co_numchild
2396 	 * should be filled leter.
2397 	 */
2398 
2399 	return conn;
2400 }
2401 
2402 static int
2403 room_conn(struct servtab *sep, struct conninfo *conn)
2404 {
2405 	char pname[NI_MAXHOST];
2406 
2407 	if (conn->co_numchild >= sep->se_maxperip) {
2408 		getnameinfo((struct sockaddr *)&conn->co_addr,
2409 		    conn->co_addr.ss_len, pname, sizeof(pname), NULL, 0,
2410 		    NI_NUMERICHOST);
2411 		syslog(LOG_ERR, "%s from %s exceeded counts (limit %d)",
2412 		    sep->se_service, pname, sep->se_maxperip);
2413 		return 0;
2414 	}
2415 	return 1;
2416 }
2417 
2418 static void
2419 addchild_conn(struct conninfo *conn, pid_t pid)
2420 {
2421 	struct procinfo *proc;
2422 
2423 	if (conn == NULL)
2424 		return;
2425 
2426 	if ((proc = search_proc(pid, 1)) != NULL) {
2427 		if (proc->pr_conn != NULL) {
2428 			syslog(LOG_ERR,
2429 			    "addchild_conn: child already on process list");
2430 			exit(EX_OSERR);
2431 		}
2432 		proc->pr_conn = conn;
2433 	}
2434 
2435 	conn->co_proc[conn->co_numchild++] = proc;
2436 }
2437 
2438 static void
2439 reapchild_conn(pid_t pid)
2440 {
2441 	struct procinfo *proc;
2442 	struct conninfo *conn;
2443 	int i;
2444 
2445 	if ((proc = search_proc(pid, 0)) == NULL)
2446 		return;
2447 	if ((conn = proc->pr_conn) == NULL)
2448 		return;
2449 	for (i = 0; i < conn->co_numchild; ++i)
2450 		if (conn->co_proc[i] == proc) {
2451 			conn->co_proc[i] = conn->co_proc[--conn->co_numchild];
2452 			break;
2453 		}
2454 	free_proc(proc);
2455 	free_conn(conn);
2456 }
2457 
2458 static void
2459 resize_conn(struct servtab *sep, int maxpip)
2460 {
2461 	struct conninfo *conn;
2462 	int i, j;
2463 
2464 	if (sep->se_maxperip <= 0)
2465 		return;
2466 	if (maxpip <= 0) {
2467 		free_connlist(sep);
2468 		return;
2469 	}
2470 	for (i = 0; i < PERIPSIZE; ++i) {
2471 		LIST_FOREACH(conn, &sep->se_conn[i], co_link) {
2472 			for (j = maxpip; j < conn->co_numchild; ++j)
2473 				free_proc(conn->co_proc[j]);
2474 			conn->co_proc = realloc(conn->co_proc,
2475 			    maxpip * sizeof(*conn->co_proc));
2476 			if (conn->co_proc == NULL) {
2477 				syslog(LOG_ERR, "realloc: %m");
2478 				exit(EX_OSERR);
2479 			}
2480 			if (conn->co_numchild > maxpip)
2481 				conn->co_numchild = maxpip;
2482 		}
2483 	}
2484 }
2485 
2486 static void
2487 free_connlist(struct servtab *sep)
2488 {
2489 	struct conninfo *conn;
2490 	int i, j;
2491 
2492 	for (i = 0; i < PERIPSIZE; ++i) {
2493 		while ((conn = LIST_FIRST(&sep->se_conn[i])) != NULL) {
2494 			for (j = 0; j < conn->co_numchild; ++j)
2495 				free_proc(conn->co_proc[j]);
2496 			conn->co_numchild = 0;
2497 			free_conn(conn);
2498 		}
2499 	}
2500 }
2501 
2502 static void
2503 free_conn(struct conninfo *conn)
2504 {
2505 	if (conn == NULL)
2506 		return;
2507 	if (conn->co_numchild <= 0) {
2508 		LIST_REMOVE(conn, co_link);
2509 		free(conn->co_proc);
2510 		free(conn);
2511 	}
2512 }
2513 
2514 static struct procinfo *
2515 search_proc(pid_t pid, int add)
2516 {
2517 	struct procinfo *proc;
2518 	int hv;
2519 
2520 	hv = hashval((char *)&pid, sizeof(pid));
2521 	LIST_FOREACH(proc, &proctable[hv], pr_link) {
2522 		if (proc->pr_pid == pid)
2523 			break;
2524 	}
2525 	if (proc == NULL && add) {
2526 		if ((proc = malloc(sizeof(struct procinfo))) == NULL) {
2527 			syslog(LOG_ERR, "malloc: %m");
2528 			exit(EX_OSERR);
2529 		}
2530 		proc->pr_pid = pid;
2531 		proc->pr_conn = NULL;
2532 		LIST_INSERT_HEAD(&proctable[hv], proc, pr_link);
2533 	}
2534 	return proc;
2535 }
2536 
2537 static void
2538 free_proc(struct procinfo *proc)
2539 {
2540 	if (proc == NULL)
2541 		return;
2542 	LIST_REMOVE(proc, pr_link);
2543 	free(proc);
2544 }
2545 
2546 static int
2547 hashval(char *p, int len)
2548 {
2549 	int i, hv = 0xABC3D20F;
2550 
2551 	for (i = 0; i < len; ++i, ++p)
2552 		hv = (hv << 5) ^ (hv >> 23) ^ *p;
2553 	hv = (hv ^ (hv >> 16)) & (PERIPSIZE - 1);
2554 	return hv;
2555 }
2556