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