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