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