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