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