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