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