xref: /netbsd-src/usr.sbin/inetd/inetd.c (revision cd22f25e6f6d1cc1f197fe8c5468a80f51d1c4e1)
1 /*	$NetBSD: inetd.c,v 1.104 2008/04/28 20:24:16 martin Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998, 2003 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center and by Matthias Scheler.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1983, 1991, 1993, 1994
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  */
61 
62 #include <sys/cdefs.h>
63 #ifndef lint
64 __COPYRIGHT("@(#) Copyright (c) 1983, 1991, 1993, 1994\n\
65 	The Regents of the University of California.  All rights reserved.\n");
66 #if 0
67 static char sccsid[] = "@(#)inetd.c	8.4 (Berkeley) 4/13/94";
68 #else
69 __RCSID("$NetBSD: inetd.c,v 1.104 2008/04/28 20:24:16 martin Exp $");
70 #endif
71 #endif /* not lint */
72 
73 /*
74  * Inetd - Internet super-server
75  *
76  * This program invokes all internet services as needed.  Connection-oriented
77  * services are invoked each time a connection is made, by creating a process.
78  * This process is passed the connection as file descriptor 0 and is expected
79  * to do a getpeername to find out the source host and port.
80  *
81  * Datagram oriented services are invoked when a datagram
82  * arrives; a process is created and passed a pending message
83  * on file descriptor 0.  Datagram servers may either connect
84  * to their peer, freeing up the original socket for inetd
85  * to receive further messages on, or ``take over the socket'',
86  * processing all arriving datagrams and, eventually, timing
87  * out.	 The first type of server is said to be ``multi-threaded'';
88  * the second type of server ``single-threaded''.
89  *
90  * Inetd uses a configuration file which is read at startup
91  * and, possibly, at some later time in response to a hangup signal.
92  * The configuration file is ``free format'' with fields given in the
93  * order shown below.  Continuation lines for an entry must being with
94  * a space or tab.  All fields must be present in each entry.
95  *
96  *	service name			must be in /etc/services or must
97  *					name a tcpmux service
98  *	socket type			stream/dgram/raw/rdm/seqpacket
99  *	protocol			must be in /etc/protocols
100  *	wait/nowait[:max]		single-threaded/multi-threaded, max #
101  *	user[:group]			user/group to run daemon as
102  *	server program			full path name
103  *	server program arguments	maximum of MAXARGS (20)
104  *
105  * For RPC services
106  *      service name/version            must be in /etc/rpc
107  *	socket type			stream/dgram/raw/rdm/seqpacket
108  *	protocol			must be in /etc/protocols
109  *	wait/nowait[:max]		single-threaded/multi-threaded
110  *	user[:group]			user to run daemon as
111  *	server program			full path name
112  *	server program arguments	maximum of MAXARGS (20)
113  *
114  * For non-RPC services, the "service name" can be of the form
115  * hostaddress:servicename, in which case the hostaddress is used
116  * as the host portion of the address to listen on.  If hostaddress
117  * consists of a single `*' character, INADDR_ANY is used.
118  *
119  * A line can also consist of just
120  *	hostaddress:
121  * where hostaddress is as in the preceding paragraph.  Such a line must
122  * have no further fields; the specified hostaddress is remembered and
123  * used for all further lines that have no hostaddress specified,
124  * until the next such line (or EOF).  (This is why * is provided to
125  * allow explicit specification of INADDR_ANY.)  A line
126  *	*:
127  * is implicitly in effect at the beginning of the file.
128  *
129  * The hostaddress specifier may (and often will) contain dots;
130  * the service name must not.
131  *
132  * For RPC services, host-address specifiers are accepted and will
133  * work to some extent; however, because of limitations in the
134  * portmapper interface, it will not work to try to give more than
135  * one line for any given RPC service, even if the host-address
136  * specifiers are different.
137  *
138  * TCP services without official port numbers are handled with the
139  * RFC1078-based tcpmux internal service. Tcpmux listens on port 1 for
140  * requests. When a connection is made from a foreign host, the service
141  * requested is passed to tcpmux, which looks it up in the servtab list
142  * and returns the proper entry for the service. Tcpmux returns a
143  * negative reply if the service doesn't exist, otherwise the invoked
144  * server is expected to return the positive reply if the service type in
145  * inetd.conf file has the prefix "tcpmux/". If the service type has the
146  * prefix "tcpmux/+", tcpmux will return the positive reply for the
147  * process; this is for compatibility with older server code, and also
148  * allows you to invoke programs that use stdin/stdout without putting any
149  * special server code in them. Services that use tcpmux are "nowait"
150  * because they do not have a well-known port and hence cannot listen
151  * for new requests.
152  *
153  * Comment lines are indicated by a `#' in column 1.
154  *
155  * #ifdef IPSEC
156  * Comment lines that start with "#@" denote IPsec policy string, as described
157  * in ipsec_set_policy(3).  This will affect all the following items in
158  * inetd.conf(8).  To reset the policy, just use "#@" line.  By default,
159  * there's no IPsec policy.
160  * #endif
161  */
162 
163 /*
164  * Here's the scoop concerning the user:group feature:
165  *
166  * 1) set-group-option off.
167  *
168  * 	a) user = root:	NO setuid() or setgid() is done
169  *
170  * 	b) other:	setuid()
171  * 			setgid(primary group as found in passwd)
172  * 			initgroups(name, primary group)
173  *
174  * 2) set-group-option on.
175  *
176  * 	a) user = root:	NO setuid()
177  * 			setgid(specified group)
178  * 			NO initgroups()
179  *
180  * 	b) other:	setuid()
181  * 			setgid(specified group)
182  * 			initgroups(name, specified group)
183  *
184  */
185 
186 #include <sys/param.h>
187 #include <sys/stat.h>
188 #include <sys/ioctl.h>
189 #include <sys/socket.h>
190 #include <sys/un.h>
191 #include <sys/wait.h>
192 #include <sys/time.h>
193 #include <sys/resource.h>
194 #include <sys/event.h>
195 
196 #ifndef RLIMIT_NOFILE
197 #define RLIMIT_NOFILE	RLIMIT_OFILE
198 #endif
199 
200 #ifndef NO_RPC
201 #define RPC
202 #endif
203 
204 #include <net/if.h>
205 
206 #include <netinet/in.h>
207 #include <arpa/inet.h>
208 #ifdef RPC
209 #include <rpc/rpc.h>
210 #include <rpc/rpcb_clnt.h>
211 #include <netconfig.h>
212 #endif
213 
214 #include <ctype.h>
215 #include <errno.h>
216 #include <fcntl.h>
217 #include <grp.h>
218 #include <netdb.h>
219 #include <pwd.h>
220 #include <signal.h>
221 #include <stdio.h>
222 #include <stdlib.h>
223 #include <string.h>
224 #include <syslog.h>
225 #include <unistd.h>
226 #include <util.h>
227 #include <ifaddrs.h>
228 
229 #include "pathnames.h"
230 
231 #ifdef IPSEC
232 #include <netinet6/ipsec.h>
233 #ifndef IPSEC_POLICY_IPSEC	/* no ipsec support on old ipsec */
234 #undef IPSEC
235 #endif
236 #include "ipsec.h"
237 #endif
238 
239 #ifdef LIBWRAP
240 # include <tcpd.h>
241 #ifndef LIBWRAP_ALLOW_FACILITY
242 # define LIBWRAP_ALLOW_FACILITY LOG_AUTH
243 #endif
244 #ifndef LIBWRAP_ALLOW_SEVERITY
245 # define LIBWRAP_ALLOW_SEVERITY LOG_INFO
246 #endif
247 #ifndef LIBWRAP_DENY_FACILITY
248 # define LIBWRAP_DENY_FACILITY LOG_AUTH
249 #endif
250 #ifndef LIBWRAP_DENY_SEVERITY
251 # define LIBWRAP_DENY_SEVERITY LOG_WARNING
252 #endif
253 int allow_severity = LIBWRAP_ALLOW_FACILITY|LIBWRAP_ALLOW_SEVERITY;
254 int deny_severity = LIBWRAP_DENY_FACILITY|LIBWRAP_DENY_SEVERITY;
255 #endif
256 
257 #define	TOOMANY		40		/* don't start more than TOOMANY */
258 #define	CNT_INTVL	60		/* servers in CNT_INTVL sec. */
259 #define	RETRYTIME	(60*10)		/* retry after bind or server fail */
260 
261 #define	A_CNT(a)	(sizeof (a) / sizeof (a[0]))
262 
263 int	debug;
264 #ifdef LIBWRAP
265 int	lflag;
266 #endif
267 int	maxsock;
268 int	kq;
269 int	options;
270 int	timingout;
271 struct	servent *sp;
272 char	*curdom;
273 const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
274 
275 #ifndef OPEN_MAX
276 #define OPEN_MAX	64
277 #endif
278 
279 /* Reserve some descriptors, 3 stdio + at least: 1 log, 1 conf. file */
280 #define FD_MARGIN	(8)
281 rlim_t		rlim_ofile_cur = OPEN_MAX;
282 
283 #ifdef RLIMIT_NOFILE
284 struct rlimit	rlim_ofile;
285 #endif
286 
287 struct kevent	changebuf[64];
288 size_t		changes;
289 
290 struct	servtab {
291 	char	*se_hostaddr;		/* host address to listen on */
292 	char	*se_service;		/* name of service */
293 	int	se_socktype;		/* type of socket to use */
294 	int	se_family;		/* address family */
295 	char	*se_proto;		/* protocol used */
296 	int	se_sndbuf;		/* sndbuf size */
297 	int	se_rcvbuf;		/* rcvbuf size */
298 	int	se_rpcprog;		/* rpc program number */
299 	int	se_rpcversl;		/* rpc program lowest version */
300 	int	se_rpcversh;		/* rpc program highest version */
301 #define isrpcservice(sep)	((sep)->se_rpcversl != 0)
302 	pid_t	se_wait;		/* single threaded server */
303 	short	se_checked;		/* looked at during merge */
304 	char	*se_user;		/* user name to run as */
305 	char	*se_group;		/* group name to run as */
306 	struct	biltin *se_bi;		/* if built-in, description */
307 	char	*se_server;		/* server program */
308 #define	MAXARGV 20
309 	char	*se_argv[MAXARGV+1];	/* program arguments */
310 #ifdef IPSEC
311 	char	*se_policy;		/* IPsec poilcy string */
312 #endif
313 	int	se_fd;			/* open descriptor */
314 	int	se_type;		/* type */
315 	union {
316 		struct	sockaddr se_un_ctrladdr;
317 		struct	sockaddr_in se_un_ctrladdr_in;
318 		struct	sockaddr_in6 se_un_ctrladdr_in6;
319 		struct	sockaddr_un se_un_ctrladdr_un;
320 	} se_un;			/* bound address */
321 #define se_ctrladdr	se_un.se_un_ctrladdr
322 #define se_ctrladdr_in	se_un.se_un_ctrladdr_in
323 #define se_ctrladdr_un	se_un.se_un_ctrladdr_un
324 	int	se_ctrladdr_size;
325 	int	se_max;			/* max # of instances of this service */
326 	int	se_count;		/* number started since se_time */
327 	struct	timeval se_time;	/* start of se_count */
328 #ifdef MULOG
329 	int	se_log;
330 #define MULOG_RFC931	0x40000000
331 #endif
332 	struct	servtab *se_next;
333 } *servtab;
334 
335 #define NORM_TYPE	0
336 #define MUX_TYPE	1
337 #define MUXPLUS_TYPE	2
338 #define FAITH_TYPE	3
339 #define ISMUX(sep)	(((sep)->se_type == MUX_TYPE) || \
340 			 ((sep)->se_type == MUXPLUS_TYPE))
341 #define ISMUXPLUS(sep)	((sep)->se_type == MUXPLUS_TYPE)
342 
343 
344 static void	chargen_dg(int, struct servtab *);
345 static void	chargen_stream(int, struct servtab *);
346 static void	close_sep(struct servtab *);
347 static void	config(void);
348 static void	daytime_dg(int, struct servtab *);
349 static void	daytime_stream(int, struct servtab *);
350 static void	discard_dg(int, struct servtab *);
351 static void	discard_stream(int, struct servtab *);
352 static void	echo_dg(int, struct servtab *);
353 static void	echo_stream(int, struct servtab *);
354 static void	endconfig(void);
355 static struct servtab *enter(struct servtab *);
356 static void	freeconfig(struct servtab *);
357 static struct servtab *getconfigent(void);
358 static void	goaway(void);
359 static void	machtime_dg(int, struct servtab *);
360 static void	machtime_stream(int, struct servtab *);
361 static char    *newstr(char *);
362 static char    *nextline(FILE *);
363 static void	print_service(char *, struct servtab *);
364 static void	reapchild(void);
365 static void	retry(void);
366 static void	run_service(int, struct servtab *);
367 static int	setconfig(void);
368 static void	setup(struct servtab *);
369 static char    *sskip(char **);
370 static char    *skip(char **);
371 static void	tcpmux(int, struct servtab *);
372 static void	usage(void);
373 static void	register_rpc(struct servtab *);
374 static void	unregister_rpc(struct servtab *);
375 static void	bump_nofile(void);
376 static void	inetd_setproctitle(char *, int);
377 static void	initring(void);
378 static uint32_t	machtime(void);
379 static int	port_good_dg(struct sockaddr *);
380 static int 	dg_broadcast(struct in_addr *);
381 static int	my_kevent(const struct kevent *, size_t, struct kevent *,
382 		size_t);
383 static struct kevent *	allocchange(void);
384 static int	getline(int, char *, int);
385 static void	spawn(struct servtab *, int);
386 #ifdef MULOG
387 static void	dolog(struct servtab *, int);
388 static void	timeout(int);
389 static char    *rfc931_name(struct sockaddr *, int);
390 #endif
391 
392 struct biltin {
393 	char	*bi_service;		/* internally provided service name */
394 	int	bi_socktype;		/* type of socket supported */
395 	short	bi_fork;		/* 1 if should fork before call */
396 	short	bi_wait;		/* 1 if should wait for child */
397 	void	(*bi_fn)(int, struct servtab *);
398 					/* function which performs it */
399 } biltins[] = {
400 	/* Echo received data */
401 	{ "echo",	SOCK_STREAM,	1, 0,	echo_stream },
402 	{ "echo",	SOCK_DGRAM,	0, 0,	echo_dg },
403 
404 	/* Internet /dev/null */
405 	{ "discard",	SOCK_STREAM,	1, 0,	discard_stream },
406 	{ "discard",	SOCK_DGRAM,	0, 0,	discard_dg },
407 
408 	/* Return 32 bit time since 1970 */
409 	{ "time",	SOCK_STREAM,	0, 0,	machtime_stream },
410 	{ "time",	SOCK_DGRAM,	0, 0,	machtime_dg },
411 
412 	/* Return human-readable time */
413 	{ "daytime",	SOCK_STREAM,	0, 0,	daytime_stream },
414 	{ "daytime",	SOCK_DGRAM,	0, 0,	daytime_dg },
415 
416 	/* Familiar character generator */
417 	{ "chargen",	SOCK_STREAM,	1, 0,	chargen_stream },
418 	{ "chargen",	SOCK_DGRAM,	0, 0,	chargen_dg },
419 
420 	{ "tcpmux",	SOCK_STREAM,	1, 0,	tcpmux },
421 
422 	{ NULL }
423 };
424 
425 /* list of "bad" ports. I.e. ports that are most obviously used for
426  * "cycling packets" denial of service attacks. See /etc/services.
427  * List must end with port number "0".
428  */
429 
430 u_int16_t bad_ports[] =  { 7, 9, 13, 19, 37, 0 };
431 
432 
433 #define NUMINT	(sizeof(intab) / sizeof(struct inent))
434 char	*CONFIG = _PATH_INETDCONF;
435 
436 static int my_signals[] =
437     { SIGALRM, SIGHUP, SIGCHLD, SIGTERM, SIGINT, SIGPIPE };
438 
439 int
440 main(int argc, char *argv[])
441 {
442 	int		ch, n, reload = 1;
443 
444 	while ((ch = getopt(argc, argv,
445 #ifdef LIBWRAP
446 					"dl"
447 #else
448 					"d"
449 #endif
450 					   )) != -1)
451 		switch(ch) {
452 		case 'd':
453 			debug = 1;
454 			options |= SO_DEBUG;
455 			break;
456 #ifdef LIBWRAP
457 		case 'l':
458 			lflag = 1;
459 			break;
460 #endif
461 		case '?':
462 		default:
463 			usage();
464 		}
465 	argc -= optind;
466 	argv += optind;
467 
468 	if (argc > 0)
469 		CONFIG = argv[0];
470 
471 	if (!debug)
472 		daemon(0, 0);
473 	openlog("inetd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
474 	pidfile(NULL);
475 
476 	kq = kqueue();
477 	if (kq < 0) {
478 		syslog(LOG_ERR, "kqueue: %m");
479 		return (EXIT_FAILURE);
480 	}
481 
482 #ifdef RLIMIT_NOFILE
483 	if (getrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0) {
484 		syslog(LOG_ERR, "getrlimit: %m");
485 	} else {
486 		rlim_ofile_cur = rlim_ofile.rlim_cur;
487 		if (rlim_ofile_cur == RLIM_INFINITY)	/* ! */
488 			rlim_ofile_cur = OPEN_MAX;
489 	}
490 #endif
491 
492 	for (n = 0; n < (int)A_CNT(my_signals); n++) {
493 		int	signum;
494 
495 		signum = my_signals[n];
496 		if (signum != SIGCHLD)
497 			(void) signal(signum, SIG_IGN);
498 
499 		if (signum != SIGPIPE) {
500 			struct kevent	*ev;
501 
502 			ev = allocchange();
503 			EV_SET(ev, signum, EVFILT_SIGNAL, EV_ADD | EV_ENABLE,
504 			    0, 0, 0);
505 		}
506 	}
507 
508 	for (;;) {
509 		int		ctrl;
510 		struct kevent	eventbuf[64], *ev;
511 		struct servtab	*sep;
512 
513 		if (reload) {
514 			reload = 0;
515 			config();
516 		}
517 
518 		n = my_kevent(changebuf, changes, eventbuf, A_CNT(eventbuf));
519 		changes = 0;
520 
521 		for (ev = eventbuf; n > 0; ev++, n--) {
522 			if (ev->filter == EVFILT_SIGNAL) {
523 				switch (ev->ident) {
524 				case SIGALRM:
525 					retry();
526 					break;
527 				case SIGCHLD:
528 					reapchild();
529 					break;
530 				case SIGTERM:
531 				case SIGINT:
532 					goaway();
533 					break;
534 				case SIGHUP:
535 					reload = 1;
536 					break;
537 				}
538 				continue;
539 			}
540 			if (ev->filter != EVFILT_READ)
541 				continue;
542 			sep = (struct servtab *)ev->udata;
543 			/* Paranoia */
544 			if ((int)ev->ident != sep->se_fd)
545 				continue;
546 			if (debug)
547 				fprintf(stderr, "someone wants %s\n",
548 				    sep->se_service);
549 			if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
550 				/* XXX here do the libwrap check-before-accept*/
551 				ctrl = accept(sep->se_fd, NULL, NULL);
552 				if (debug)
553 					fprintf(stderr, "accept, ctrl %d\n",
554 					    ctrl);
555 				if (ctrl < 0) {
556 					if (errno != EINTR)
557 						syslog(LOG_WARNING,
558 						    "accept (for %s): %m",
559 						    sep->se_service);
560 					continue;
561 				}
562 			} else
563 				ctrl = sep->se_fd;
564 			spawn(sep, ctrl);
565 		}
566 	}
567 }
568 
569 static void
570 spawn(struct servtab *sep, int ctrl)
571 {
572 	int dofork;
573 	pid_t pid;
574 
575 	pid = 0;
576 #ifdef LIBWRAP_INTERNAL
577 	dofork = 1;
578 #else
579 	dofork = (sep->se_bi == 0 || sep->se_bi->bi_fork);
580 #endif
581 	if (dofork) {
582 		if (sep->se_count++ == 0)
583 			(void)gettimeofday(&sep->se_time, NULL);
584 		else if (sep->se_count >= sep->se_max) {
585 			struct timeval now;
586 
587 			(void)gettimeofday(&now, NULL);
588 			if (now.tv_sec - sep->se_time.tv_sec > CNT_INTVL) {
589 				sep->se_time = now;
590 				sep->se_count = 1;
591 			} else {
592 				syslog(LOG_ERR,
593 				    "%s/%s max spawn rate (%d in %d seconds) "
594 				    "exceeded; service not started",
595 				    sep->se_service, sep->se_proto,
596 				    sep->se_max, CNT_INTVL);
597 				if (!sep->se_wait && sep->se_socktype ==
598 				    SOCK_STREAM)
599 					close(ctrl);
600 				close_sep(sep);
601 				if (!timingout) {
602 					timingout = 1;
603 					alarm(RETRYTIME);
604 				}
605 				return;
606 			}
607 		}
608 		pid = fork();
609 		if (pid < 0) {
610 			syslog(LOG_ERR, "fork: %m");
611 			if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
612 				close(ctrl);
613 			sleep(1);
614 			return;
615 		}
616 		if (pid != 0 && sep->se_wait) {
617 			struct kevent	*ev;
618 
619 			sep->se_wait = pid;
620 			ev = allocchange();
621 			EV_SET(ev, sep->se_fd, EVFILT_READ,
622 			    EV_DELETE, 0, 0, 0);
623 		}
624 		if (pid == 0) {
625 			size_t	n;
626 
627 			for (n = 0; n < A_CNT(my_signals); n++)
628 				(void) signal(my_signals[n], SIG_DFL);
629 			if (debug)
630 				setsid();
631 		}
632 	}
633 	if (pid == 0) {
634 		run_service(ctrl, sep);
635 		if (dofork)
636 			exit(0);
637 	}
638 	if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
639 		close(ctrl);
640 }
641 
642 static void
643 run_service(int ctrl, struct servtab *sep)
644 {
645 	struct passwd *pwd;
646 	struct group *grp = NULL;	/* XXX gcc */
647 	char buf[NI_MAXSERV];
648 #ifdef LIBWRAP
649 	struct request_info req;
650 	int denied;
651 	char *service = NULL;	/* XXX gcc */
652 #endif
653 
654 #ifdef LIBWRAP
655 #ifndef LIBWRAP_INTERNAL
656 	if (sep->se_bi == 0)
657 #endif
658 	if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
659 		request_init(&req, RQ_DAEMON, sep->se_argv[0] ?
660 		    sep->se_argv[0] : sep->se_service, RQ_FILE, ctrl, NULL);
661 		fromhost(&req);
662 		denied = !hosts_access(&req);
663 		if (denied || lflag) {
664 			if (getnameinfo(&sep->se_ctrladdr,
665 					sep->se_ctrladdr.sa_len, NULL, 0,
666 					buf, sizeof(buf), 0) != 0) {
667 				/* shouldn't happen */
668 				(void)snprintf(buf, sizeof buf, "%d",
669 				    ntohs(sep->se_ctrladdr_in.sin_port));
670 			}
671 			service = buf;
672 		}
673 		if (denied) {
674 			syslog(deny_severity,
675 			    "refused connection from %.500s, service %s (%s)",
676 			    eval_client(&req), service, sep->se_proto);
677 			goto reject;
678 		}
679 		if (lflag) {
680 			syslog(allow_severity,
681 			    "connection from %.500s, service %s (%s)",
682 			    eval_client(&req), service, sep->se_proto);
683 		}
684 	}
685 #endif /* LIBWRAP */
686 
687 	if (sep->se_bi) {
688 		(*sep->se_bi->bi_fn)(ctrl, sep);
689 	} else {
690 		if ((pwd = getpwnam(sep->se_user)) == NULL) {
691 			syslog(LOG_ERR, "%s/%s: %s: No such user",
692 			    sep->se_service, sep->se_proto, sep->se_user);
693 			goto reject;
694 		}
695 		if (sep->se_group &&
696 		    (grp = getgrnam(sep->se_group)) == NULL) {
697 			syslog(LOG_ERR, "%s/%s: %s: No such group",
698 			    sep->se_service, sep->se_proto, sep->se_group);
699 			goto reject;
700 		}
701 		if (pwd->pw_uid) {
702 			if (sep->se_group)
703 				pwd->pw_gid = grp->gr_gid;
704 			if (setgid(pwd->pw_gid) < 0) {
705 				syslog(LOG_ERR,
706 				 "%s/%s: can't set gid %d: %m", sep->se_service,
707 				    sep->se_proto, pwd->pw_gid);
708 				goto reject;
709 			}
710 			(void) initgroups(pwd->pw_name,
711 			    pwd->pw_gid);
712 			if (setuid(pwd->pw_uid) < 0) {
713 				syslog(LOG_ERR,
714 				 "%s/%s: can't set uid %d: %m", sep->se_service,
715 				    sep->se_proto, pwd->pw_uid);
716 				goto reject;
717 			}
718 		} else if (sep->se_group) {
719 			(void) setgid((gid_t)grp->gr_gid);
720 		}
721 		if (debug)
722 			fprintf(stderr, "%d execl %s\n",
723 			    getpid(), sep->se_server);
724 #ifdef MULOG
725 		if (sep->se_log)
726 			dolog(sep, ctrl);
727 #endif
728 		/* Set our control descriptor to not close-on-exec... */
729 		if (fcntl(ctrl, F_SETFD, 0) < 0)
730 			syslog(LOG_ERR, "fcntl (F_SETFD, 0): %m");
731 		/* ...and dup it to stdin, stdout, and stderr. */
732 		if (ctrl != 0) {
733 			dup2(ctrl, 0);
734 			close(ctrl);
735 			ctrl = 0;
736 		}
737 		dup2(0, 1);
738 		dup2(0, 2);
739 #ifdef RLIMIT_NOFILE
740 		if (rlim_ofile.rlim_cur != rlim_ofile_cur &&
741 		    setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
742 			syslog(LOG_ERR, "setrlimit: %m");
743 #endif
744 		execv(sep->se_server, sep->se_argv);
745 		syslog(LOG_ERR, "cannot execute %s: %m", sep->se_server);
746 	reject:
747 		if (sep->se_socktype != SOCK_STREAM)
748 			recv(ctrl, buf, sizeof (buf), 0);
749 		_exit(1);
750 	}
751 }
752 
753 static void
754 reapchild(void)
755 {
756 	int status;
757 	pid_t pid;
758 	struct servtab *sep;
759 
760 	for (;;) {
761 		pid = wait3(&status, WNOHANG, NULL);
762 		if (pid <= 0)
763 			break;
764 		if (debug)
765 			(void) fprintf(stderr, "%d reaped, status %#x\n",
766 			    pid, status);
767 		for (sep = servtab; sep != NULL; sep = sep->se_next)
768 			if (sep->se_wait == pid) {
769 				struct kevent	*ev;
770 
771 				if (WIFEXITED(status) && WEXITSTATUS(status))
772 					syslog(LOG_WARNING,
773 					    "%s: exit status 0x%x",
774 					    sep->se_server, WEXITSTATUS(status));
775 				else if (WIFSIGNALED(status))
776 					syslog(LOG_WARNING,
777 					    "%s: exit signal 0x%x",
778 					    sep->se_server, WTERMSIG(status));
779 				sep->se_wait = 1;
780 				ev = allocchange();
781 				EV_SET(ev, sep->se_fd, EVFILT_READ,
782 				    EV_ADD | EV_ENABLE, 0, 0, (intptr_t)sep);
783 				if (debug)
784 					fprintf(stderr, "restored %s, fd %d\n",
785 					    sep->se_service, sep->se_fd);
786 			}
787 	}
788 }
789 
790 static void
791 config(void)
792 {
793 	struct servtab *sep, *cp, **sepp;
794 	size_t n;
795 
796 	if (!setconfig()) {
797 		syslog(LOG_ERR, "%s: %m", CONFIG);
798 		return;
799 	}
800 	for (sep = servtab; sep != NULL; sep = sep->se_next)
801 		sep->se_checked = 0;
802 	while ((cp = getconfigent())) {
803 		for (sep = servtab; sep != NULL; sep = sep->se_next)
804 			if (strcmp(sep->se_service, cp->se_service) == 0 &&
805 			    strcmp(sep->se_hostaddr, cp->se_hostaddr) == 0 &&
806 			    strcmp(sep->se_proto, cp->se_proto) == 0 &&
807 			    ISMUX(sep) == ISMUX(cp))
808 				break;
809 		if (sep != NULL) {
810 			int i;
811 
812 #define SWAP(type, a, b) {type c = a; a = b; b = c;}
813 
814 			/*
815 			 * sep->se_wait may be holding the pid of a daemon
816 			 * that we're waiting for.  If so, don't overwrite
817 			 * it unless the config file explicitly says don't
818 			 * wait.
819 			 */
820 			if (cp->se_bi == 0 &&
821 			    (sep->se_wait == 1 || cp->se_wait == 0))
822 				sep->se_wait = cp->se_wait;
823 			SWAP(char *, sep->se_user, cp->se_user);
824 			SWAP(char *, sep->se_group, cp->se_group);
825 			SWAP(char *, sep->se_server, cp->se_server);
826 			for (i = 0; i < MAXARGV; i++)
827 				SWAP(char *, sep->se_argv[i], cp->se_argv[i]);
828 #ifdef IPSEC
829 			SWAP(char *, sep->se_policy, cp->se_policy);
830 #endif
831 			SWAP(int, cp->se_type, sep->se_type);
832 			SWAP(int, cp->se_max, sep->se_max);
833 #undef SWAP
834 			if (isrpcservice(sep))
835 				unregister_rpc(sep);
836 			sep->se_rpcversl = cp->se_rpcversl;
837 			sep->se_rpcversh = cp->se_rpcversh;
838 			freeconfig(cp);
839 			if (debug)
840 				print_service("REDO", sep);
841 		} else {
842 			sep = enter(cp);
843 			if (debug)
844 				print_service("ADD ", sep);
845 		}
846 		sep->se_checked = 1;
847 
848 		switch (sep->se_family) {
849 		case AF_LOCAL:
850 			if (sep->se_fd != -1)
851 				break;
852 			n = strlen(sep->se_service);
853 			if (n > sizeof(sep->se_ctrladdr_un.sun_path)) {
854 				syslog(LOG_ERR, "%s: address too long",
855 				    sep->se_service);
856 				sep->se_checked = 0;
857 				continue;
858 			}
859 			(void)unlink(sep->se_service);
860 			strncpy(sep->se_ctrladdr_un.sun_path,
861 			    sep->se_service, n);
862 			sep->se_ctrladdr_un.sun_family = AF_LOCAL;
863 			sep->se_ctrladdr_size = n +
864 			    sizeof(sep->se_ctrladdr_un) -
865 			    sizeof(sep->se_ctrladdr_un.sun_path);
866 			if (!ISMUX(sep))
867 				setup(sep);
868 			break;
869 		case AF_INET:
870 #ifdef INET6
871 		case AF_INET6:
872 #endif
873 		    {
874 			struct addrinfo hints, *res;
875 			char *host, *port;
876 			int error;
877 			int s;
878 
879 			/* check if the family is supported */
880 			s = socket(sep->se_family, SOCK_DGRAM, 0);
881 			if (s < 0) {
882 				syslog(LOG_WARNING,
883 				    "%s/%s: %s: the address family is not "
884 				    "supported by the kernel",
885 				    sep->se_service, sep->se_proto,
886 				    sep->se_hostaddr);
887 				sep->se_checked = 0;
888 				continue;
889 			}
890 			close(s);
891 
892 			memset(&hints, 0, sizeof(hints));
893 			hints.ai_family = sep->se_family;
894 			hints.ai_socktype = sep->se_socktype;
895 			hints.ai_flags = AI_PASSIVE;
896 			if (!strcmp(sep->se_hostaddr, "*"))
897 				host = NULL;
898 			else
899 				host = sep->se_hostaddr;
900 			if (isrpcservice(sep) || ISMUX(sep))
901 				port = "0";
902 			else
903 				port = sep->se_service;
904 			error = getaddrinfo(host, port, &hints, &res);
905 			if (error) {
906 				if (error == EAI_SERVICE) {
907 					/* gai_strerror not friendly enough */
908 					syslog(LOG_WARNING, "%s/%s: "
909 					    "unknown service",
910 					    sep->se_service, sep->se_proto);
911 				} else {
912 					syslog(LOG_ERR, "%s/%s: %s: %s",
913 					    sep->se_service, sep->se_proto,
914 					    sep->se_hostaddr,
915 					    gai_strerror(error));
916 				}
917 				sep->se_checked = 0;
918 				continue;
919 			}
920 			if (res->ai_next) {
921 				syslog(LOG_ERR,
922 					"%s/%s: %s: resolved to multiple addr",
923 				    sep->se_service, sep->se_proto,
924 				    sep->se_hostaddr);
925 				sep->se_checked = 0;
926 				freeaddrinfo(res);
927 				continue;
928 			}
929 			memcpy(&sep->se_ctrladdr, res->ai_addr,
930 				res->ai_addrlen);
931 			if (ISMUX(sep)) {
932 				sep->se_fd = -1;
933 				freeaddrinfo(res);
934 				continue;
935 			}
936 			sep->se_ctrladdr_size = res->ai_addrlen;
937 			freeaddrinfo(res);
938 #ifdef RPC
939 			if (isrpcservice(sep)) {
940 				struct rpcent *rp;
941 
942 				sep->se_rpcprog = atoi(sep->se_service);
943 				if (sep->se_rpcprog == 0) {
944 					rp = getrpcbyname(sep->se_service);
945 					if (rp == 0) {
946 						syslog(LOG_ERR,
947 						    "%s/%s: unknown service",
948 						    sep->se_service,
949 						    sep->se_proto);
950 						sep->se_checked = 0;
951 						continue;
952 					}
953 					sep->se_rpcprog = rp->r_number;
954 				}
955 				if (sep->se_fd == -1 && !ISMUX(sep))
956 					setup(sep);
957 				if (sep->se_fd != -1)
958 					register_rpc(sep);
959 			} else
960 #endif
961 			{
962 				if (sep->se_fd >= 0)
963 					close_sep(sep);
964 				if (sep->se_fd == -1 && !ISMUX(sep))
965 					setup(sep);
966 			}
967 		    }
968 		}
969 	}
970 	endconfig();
971 	/*
972 	 * Purge anything not looked at above.
973 	 */
974 	sepp = &servtab;
975 	while ((sep = *sepp)) {
976 		if (sep->se_checked) {
977 			sepp = &sep->se_next;
978 			continue;
979 		}
980 		*sepp = sep->se_next;
981 		if (sep->se_fd >= 0)
982 			close_sep(sep);
983 		if (isrpcservice(sep))
984 			unregister_rpc(sep);
985 		if (sep->se_family == AF_LOCAL)
986 			(void)unlink(sep->se_service);
987 		if (debug)
988 			print_service("FREE", sep);
989 		freeconfig(sep);
990 		free(sep);
991 	}
992 }
993 
994 static void
995 retry(void)
996 {
997 	struct servtab *sep;
998 
999 	timingout = 0;
1000 	for (sep = servtab; sep != NULL; sep = sep->se_next) {
1001 		if (sep->se_fd == -1 && !ISMUX(sep)) {
1002 			switch (sep->se_family) {
1003 			case AF_LOCAL:
1004 			case AF_INET:
1005 #ifdef INET6
1006 			case AF_INET6:
1007 #endif
1008 				setup(sep);
1009 				if (sep->se_fd != -1 && isrpcservice(sep))
1010 					register_rpc(sep);
1011 				break;
1012 			}
1013 		}
1014 	}
1015 }
1016 
1017 static void
1018 goaway(void)
1019 {
1020 	struct servtab *sep;
1021 
1022 	for (sep = servtab; sep != NULL; sep = sep->se_next) {
1023 		if (sep->se_fd == -1)
1024 			continue;
1025 
1026 		switch (sep->se_family) {
1027 		case AF_LOCAL:
1028 			(void)unlink(sep->se_service);
1029 			break;
1030 		case AF_INET:
1031 #ifdef INET6
1032 		case AF_INET6:
1033 #endif
1034 			if (sep->se_wait == 1 && isrpcservice(sep))
1035 				unregister_rpc(sep);
1036 			break;
1037 		}
1038 		(void)close(sep->se_fd);
1039 	}
1040 	exit(0);
1041 }
1042 
1043 static void
1044 setup(struct servtab *sep)
1045 {
1046 	int		on = 1;
1047 #ifdef INET6
1048 	int		off = 0;
1049 #endif
1050 	struct kevent	*ev;
1051 
1052 	if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1053 		if (debug)
1054 			fprintf(stderr, "socket failed on %s/%s: %s\n",
1055 			    sep->se_service, sep->se_proto, strerror(errno));
1056 		syslog(LOG_ERR, "%s/%s: socket: %m",
1057 		    sep->se_service, sep->se_proto);
1058 		return;
1059 	}
1060 	/* Set all listening sockets to close-on-exec. */
1061 	if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
1062 		syslog(LOG_ERR, "%s/%s: fcntl(F_SETFD, FD_CLOEXEC): %m",
1063 		    sep->se_service, sep->se_proto);
1064 		close(sep->se_fd);
1065 		return;
1066 	}
1067 
1068 #define	turnon(fd, opt) \
1069 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1070 	if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1071 	    turnon(sep->se_fd, SO_DEBUG) < 0)
1072 		syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1073 	if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1074 		syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1075 #undef turnon
1076 
1077 	/* Set the socket buffer sizes, if specified. */
1078 	if (sep->se_sndbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1079 	    SO_SNDBUF, (char *)&sep->se_sndbuf, sizeof(sep->se_sndbuf)) < 0)
1080 		syslog(LOG_ERR, "setsockopt (SO_SNDBUF %d): %m",
1081 		    sep->se_sndbuf);
1082 	if (sep->se_rcvbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1083 	    SO_RCVBUF, (char *)&sep->se_rcvbuf, sizeof(sep->se_rcvbuf)) < 0)
1084 		syslog(LOG_ERR, "setsockopt (SO_RCVBUF %d): %m",
1085 		    sep->se_rcvbuf);
1086 #ifdef INET6
1087 	if (sep->se_family == AF_INET6) {
1088 		int *v;
1089 		v = (sep->se_type == FAITH_TYPE) ? &on : &off;
1090 		if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_FAITH,
1091 		    (char *)v, sizeof(*v)) < 0)
1092 			syslog(LOG_ERR, "setsockopt (IPV6_FAITH): %m");
1093 	}
1094 #endif
1095 #ifdef IPSEC
1096 	if (ipsecsetup(sep->se_family, sep->se_fd, sep->se_policy) < 0 &&
1097 	    sep->se_policy) {
1098 		syslog(LOG_ERR, "%s/%s: ipsec setup failed",
1099 		    sep->se_service, sep->se_proto);
1100 		(void)close(sep->se_fd);
1101 		sep->se_fd = -1;
1102 		return;
1103 	}
1104 #endif
1105 
1106 	if (bind(sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size) < 0) {
1107 		if (debug)
1108 			fprintf(stderr, "bind failed on %s/%s: %s\n",
1109 			    sep->se_service, sep->se_proto, strerror(errno));
1110 		syslog(LOG_ERR, "%s/%s: bind: %m",
1111 		    sep->se_service, sep->se_proto);
1112 		(void) close(sep->se_fd);
1113 		sep->se_fd = -1;
1114 		if (!timingout) {
1115 			timingout = 1;
1116 			alarm(RETRYTIME);
1117 		}
1118 		return;
1119 	}
1120 	if (sep->se_socktype == SOCK_STREAM)
1121 		listen(sep->se_fd, 10);
1122 
1123 	ev = allocchange();
1124 	EV_SET(ev, sep->se_fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0,
1125 	    (intptr_t)sep);
1126 	if (sep->se_fd > maxsock) {
1127 		maxsock = sep->se_fd;
1128 		if (maxsock > rlim_ofile_cur - FD_MARGIN)
1129 			bump_nofile();
1130 	}
1131 	if (debug)
1132 		fprintf(stderr, "registered %s on %d\n",
1133 		    sep->se_server, sep->se_fd);
1134 }
1135 
1136 /*
1137  * Finish with a service and its socket.
1138  */
1139 static void
1140 close_sep(struct servtab *sep)
1141 {
1142 	if (sep->se_fd >= 0) {
1143 		(void) close(sep->se_fd);
1144 		sep->se_fd = -1;
1145 	}
1146 	sep->se_count = 0;
1147 }
1148 
1149 static void
1150 register_rpc(struct servtab *sep)
1151 {
1152 #ifdef RPC
1153 	struct netbuf nbuf;
1154 	struct sockaddr_storage ss;
1155 	struct netconfig *nconf;
1156 	socklen_t socklen;
1157 	int n;
1158 
1159 	if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
1160 		syslog(LOG_ERR, "%s: getnetconfigent failed",
1161 		    sep->se_proto);
1162 		return;
1163 	}
1164 	socklen = sizeof ss;
1165 	if (getsockname(sep->se_fd, (struct sockaddr *)&ss, &socklen) < 0) {
1166 		syslog(LOG_ERR, "%s/%s: getsockname: %m",
1167 		    sep->se_service, sep->se_proto);
1168 		return;
1169 	}
1170 
1171 	nbuf.buf = &ss;
1172 	nbuf.len = ss.ss_len;
1173 	nbuf.maxlen = sizeof (struct sockaddr_storage);
1174 	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1175 		if (debug)
1176 			fprintf(stderr, "rpcb_set: %u %d %s %s\n",
1177 			    sep->se_rpcprog, n, nconf->nc_netid,
1178 			    taddr2uaddr(nconf, &nbuf));
1179 		(void)rpcb_unset(sep->se_rpcprog, n, nconf);
1180 		if (!rpcb_set(sep->se_rpcprog, n, nconf, &nbuf))
1181 			syslog(LOG_ERR, "rpcb_set: %u %d %s %s%s",
1182 			    sep->se_rpcprog, n, nconf->nc_netid,
1183 			    taddr2uaddr(nconf, &nbuf), clnt_spcreateerror(""));
1184 	}
1185 #endif /* RPC */
1186 }
1187 
1188 static void
1189 unregister_rpc(struct servtab *sep)
1190 {
1191 #ifdef RPC
1192 	int n;
1193 	struct netconfig *nconf;
1194 
1195 	if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
1196 		syslog(LOG_ERR, "%s: getnetconfigent failed",
1197 		    sep->se_proto);
1198 		return;
1199 	}
1200 
1201 	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1202 		if (debug)
1203 			fprintf(stderr, "rpcb_unset(%u, %d, %s)\n",
1204 			    sep->se_rpcprog, n, nconf->nc_netid);
1205 		if (!rpcb_unset(sep->se_rpcprog, n, nconf))
1206 			syslog(LOG_ERR, "rpcb_unset(%u, %d, %s) failed\n",
1207 			    sep->se_rpcprog, n, nconf->nc_netid);
1208 	}
1209 #endif /* RPC */
1210 }
1211 
1212 
1213 static struct servtab *
1214 enter(struct servtab *cp)
1215 {
1216 	struct servtab *sep;
1217 
1218 	sep = (struct servtab *)malloc(sizeof (*sep));
1219 	if (sep == NULL) {
1220 		syslog(LOG_ERR, "Out of memory.");
1221 		exit(1);
1222 	}
1223 	*sep = *cp;
1224 	sep->se_fd = -1;
1225 	sep->se_rpcprog = -1;
1226 	sep->se_next = servtab;
1227 	servtab = sep;
1228 	return (sep);
1229 }
1230 
1231 FILE	*fconfig = NULL;
1232 struct	servtab serv;
1233 char	line[LINE_MAX];
1234 char    *defhost;
1235 #ifdef IPSEC
1236 static char *policy = NULL;
1237 #endif
1238 
1239 static int
1240 setconfig(void)
1241 {
1242 	if (defhost)
1243 		free(defhost);
1244 	defhost = newstr("*");
1245 #ifdef IPSEC
1246 	if (policy)
1247 		free(policy);
1248 	policy = NULL;
1249 #endif
1250 	if (fconfig != NULL) {
1251 		fseek(fconfig, 0L, SEEK_SET);
1252 		return (1);
1253 	}
1254 	fconfig = fopen(CONFIG, "r");
1255 	return (fconfig != NULL);
1256 }
1257 
1258 static void
1259 endconfig(void)
1260 {
1261 	if (fconfig != NULL) {
1262 		(void) fclose(fconfig);
1263 		fconfig = NULL;
1264 	}
1265 	if (defhost != NULL) {
1266 		free(defhost);
1267 		defhost = NULL;
1268 	}
1269 }
1270 
1271 static struct servtab *
1272 getconfigent(void)
1273 {
1274 	struct servtab *sep = &serv;
1275 	int argc, val;
1276 	char *cp, *cp0, *arg, *buf0, *buf1, *sz0, *sz1;
1277 	static char TCPMUX_TOKEN[] = "tcpmux/";
1278 #define MUX_LEN		(sizeof(TCPMUX_TOKEN)-1)
1279 	char *hostdelim;
1280 
1281 more:
1282 	while ((cp = nextline(fconfig))) {
1283 #ifdef IPSEC
1284 		/* lines starting with #@ is not a comment, but the policy */
1285 		if (cp[0] == '#' && cp[1] == '@') {
1286 			char *p;
1287 			for (p = cp + 2; p && *p && isspace((unsigned char)*p); p++)
1288 				;
1289 			if (*p == '\0') {
1290 				if (policy)
1291 					free(policy);
1292 				policy = NULL;
1293 			} else {
1294 				if (ipsecsetup_test(p) < 0) {
1295 					syslog(LOG_ERR,
1296 						"%s: invalid ipsec policy \"%s\"",
1297 						CONFIG, p);
1298 					exit(1);
1299 				} else {
1300 					if (policy)
1301 						free(policy);
1302 					policy = newstr(p);
1303 				}
1304 			}
1305 		}
1306 #endif
1307 		if (*cp == '#' || *cp == '\0')
1308 			continue;
1309 #ifdef MULOG
1310 		/* Avoid use of `skip' if there is a danger of it looking
1311 		 * at continuation lines.
1312 		 */
1313 		do {
1314 			cp++;
1315 		} while (*cp == ' ' || *cp == '\t');
1316 		if (*cp == '\0')
1317 			continue;
1318 		if ((arg = skip(&cp)) == NULL)
1319 			continue;
1320 		if (strcmp(arg, "DOMAIN"))
1321 			continue;
1322 		if (curdom)
1323 			free(curdom);
1324 		curdom = NULL;
1325 		while (*cp == ' ' || *cp == '\t')
1326 			cp++;
1327 		if (*cp == '\0')
1328 			continue;
1329 		arg = cp;
1330 		while (*cp && *cp != ' ' && *cp != '\t')
1331 			cp++;
1332 		if (*cp != '\0')
1333 			*cp++ = '\0';
1334 		curdom = newstr(arg);
1335 #endif
1336 		break;
1337 	}
1338 	if (cp == NULL)
1339 		return (NULL);
1340 	/*
1341 	 * clear the static buffer, since some fields (se_ctrladdr,
1342 	 * for example) don't get initialized here.
1343 	 */
1344 	memset((caddr_t)sep, 0, sizeof *sep);
1345 	arg = skip(&cp);
1346 	if (cp == NULL) {
1347 		/* got an empty line containing just blanks/tabs. */
1348 		goto more;
1349 	}
1350 	/* Check for a host name. */
1351 	hostdelim = strrchr(arg, ':');
1352 	if (hostdelim) {
1353 		*hostdelim = '\0';
1354 		if (arg[0] == '[' && hostdelim > arg && hostdelim[-1] == ']') {
1355 			hostdelim[-1] = '\0';
1356 			sep->se_hostaddr = newstr(arg + 1);
1357 		} else
1358 			sep->se_hostaddr = newstr(arg);
1359 		arg = hostdelim + 1;
1360 		/*
1361 		 * If the line is of the form `host:', then just change the
1362 		 * default host for the following lines.
1363 		 */
1364 		if (*arg == '\0') {
1365 			arg = skip(&cp);
1366 			if (cp == NULL) {
1367 				free(defhost);
1368 				defhost = sep->se_hostaddr;
1369 				goto more;
1370 			}
1371 		}
1372 	} else
1373 		sep->se_hostaddr = newstr(defhost);
1374 	if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1375 		char *c = arg + MUX_LEN;
1376 		if (*c == '+') {
1377 			sep->se_type = MUXPLUS_TYPE;
1378 			c++;
1379 		} else
1380 			sep->se_type = MUX_TYPE;
1381 		sep->se_service = newstr(c);
1382 	} else {
1383 		sep->se_service = newstr(arg);
1384 		sep->se_type = NORM_TYPE;
1385 	}
1386 
1387 	arg = sskip(&cp);
1388 	if (strcmp(arg, "stream") == 0)
1389 		sep->se_socktype = SOCK_STREAM;
1390 	else if (strcmp(arg, "dgram") == 0)
1391 		sep->se_socktype = SOCK_DGRAM;
1392 	else if (strcmp(arg, "rdm") == 0)
1393 		sep->se_socktype = SOCK_RDM;
1394 	else if (strcmp(arg, "seqpacket") == 0)
1395 		sep->se_socktype = SOCK_SEQPACKET;
1396 	else if (strcmp(arg, "raw") == 0)
1397 		sep->se_socktype = SOCK_RAW;
1398 	else
1399 		sep->se_socktype = -1;
1400 
1401 	arg = sskip(&cp);
1402 	if (sep->se_type == NORM_TYPE &&
1403 	    strncmp(arg, "faith/", strlen("faith/")) == 0) {
1404 		arg += strlen("faith/");
1405 		sep->se_type = FAITH_TYPE;
1406 	}
1407 	sep->se_proto = newstr(arg);
1408 
1409 #define	MALFORMED(arg) \
1410 do { \
1411 	syslog(LOG_ERR, "%s: malformed buffer size option `%s'", \
1412 	    sep->se_service, (arg)); \
1413 	goto more; \
1414 } while (0)
1415 
1416 #define	GETVAL(arg) \
1417 do { \
1418 	if (!isdigit((unsigned char)*(arg))) \
1419 		MALFORMED(arg); \
1420 	val = strtol((arg), &cp0, 10); \
1421 	if (cp0 != NULL) { \
1422 		if (cp0[1] != '\0') \
1423 			MALFORMED((arg)); \
1424 		if (cp0[0] == 'k') \
1425 			val *= 1024; \
1426 		if (cp0[0] == 'm') \
1427 			val *= 1024 * 1024; \
1428 	} \
1429 	if (val < 1) { \
1430 		syslog(LOG_ERR, "%s: invalid buffer size `%s'", \
1431 		    sep->se_service, (arg)); \
1432 		goto more; \
1433 	} \
1434 } while (0)
1435 
1436 #define	ASSIGN(arg) \
1437 do { \
1438 	if (strcmp((arg), "sndbuf") == 0) \
1439 		sep->se_sndbuf = val; \
1440 	else if (strcmp((arg), "rcvbuf") == 0) \
1441 		sep->se_rcvbuf = val; \
1442 	else \
1443 		MALFORMED((arg)); \
1444 } while (0)
1445 
1446 	/*
1447 	 * Extract the send and receive buffer sizes before parsing
1448 	 * the protocol.
1449 	 */
1450 	sep->se_sndbuf = sep->se_rcvbuf = 0;
1451 	buf0 = buf1 = sz0 = sz1 = NULL;
1452 	if ((buf0 = strchr(sep->se_proto, ',')) != NULL) {
1453 		/* Not meaningful for Tcpmux services. */
1454 		if (ISMUX(sep)) {
1455 			syslog(LOG_ERR, "%s: can't specify buffer sizes for "
1456 			    "tcpmux services", sep->se_service);
1457 			goto more;
1458 		}
1459 
1460 		/* Skip the , */
1461 		*buf0++ = '\0';
1462 
1463 		/* Check to see if another socket buffer size was specified. */
1464 		if ((buf1 = strchr(buf0, ',')) != NULL) {
1465 			/* Skip the , */
1466 			*buf1++ = '\0';
1467 
1468 			/* Make sure a 3rd one wasn't specified. */
1469 			if (strchr(buf1, ',') != NULL) {
1470 				syslog(LOG_ERR, "%s: too many buffer sizes",
1471 				    sep->se_service);
1472 				goto more;
1473 			}
1474 
1475 			/* Locate the size. */
1476 			if ((sz1 = strchr(buf1, '=')) == NULL)
1477 				MALFORMED(buf1);
1478 
1479 			/* Skip the = */
1480 			*sz1++ = '\0';
1481 		}
1482 
1483 		/* Locate the size. */
1484 		if ((sz0 = strchr(buf0, '=')) == NULL)
1485 			MALFORMED(buf0);
1486 
1487 		/* Skip the = */
1488 		*sz0++ = '\0';
1489 
1490 		GETVAL(sz0);
1491 		ASSIGN(buf0);
1492 
1493 		if (buf1 != NULL) {
1494 			GETVAL(sz1);
1495 			ASSIGN(buf1);
1496 		}
1497 	}
1498 
1499 #undef ASSIGN
1500 #undef GETVAL
1501 #undef MALFORMED
1502 
1503 	if (strcmp(sep->se_proto, "unix") == 0) {
1504 		sep->se_family = AF_LOCAL;
1505 	} else {
1506 		val = strlen(sep->se_proto);
1507 		if (!val) {
1508 			syslog(LOG_ERR, "%s: invalid protocol specified",
1509 			    sep->se_service);
1510 			goto more;
1511 		}
1512 		val = sep->se_proto[val - 1];
1513 		switch (val) {
1514 		case '4':	/*tcp4 or udp4*/
1515 			sep->se_family = AF_INET;
1516 			break;
1517 #ifdef INET6
1518 		case '6':	/*tcp6 or udp6*/
1519 			sep->se_family = AF_INET6;
1520 			break;
1521 #endif
1522 		default:
1523 			sep->se_family = AF_INET;	/*will become AF_INET6*/
1524 			break;
1525 		}
1526 		if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1527 #ifdef RPC
1528 			char *cp, *ccp;
1529 			cp = strchr(sep->se_service, '/');
1530 			if (cp == 0) {
1531 				syslog(LOG_ERR, "%s: no rpc version",
1532 				    sep->se_service);
1533 				goto more;
1534 			}
1535 			*cp++ = '\0';
1536 			sep->se_rpcversl = sep->se_rpcversh =
1537 			    strtol(cp, &ccp, 0);
1538 			if (ccp == cp) {
1539 		badafterall:
1540 				syslog(LOG_ERR, "%s/%s: bad rpc version",
1541 				    sep->se_service, cp);
1542 				goto more;
1543 			}
1544 			if (*ccp == '-') {
1545 				cp = ccp + 1;
1546 				sep->se_rpcversh = strtol(cp, &ccp, 0);
1547 				if (ccp == cp)
1548 					goto badafterall;
1549 			}
1550 #else
1551 			syslog(LOG_ERR, "%s: rpc services not suported",
1552 			    sep->se_service);
1553 			goto more;
1554 #endif /* RPC */
1555 		}
1556 	}
1557 	arg = sskip(&cp);
1558 	{
1559 		char *cp;
1560 		if ((cp = strchr(arg, ':')) == NULL)
1561 			cp = strchr(arg, '.');
1562 		if (cp != NULL) {
1563 			*cp++ = '\0';
1564 			sep->se_max = atoi(cp);
1565 		} else
1566 			sep->se_max = TOOMANY;
1567 	}
1568 	sep->se_wait = strcmp(arg, "wait") == 0;
1569 	if (ISMUX(sep)) {
1570 		/*
1571 		 * Silently enforce "nowait" for TCPMUX services since
1572 		 * they don't have an assigned port to listen on.
1573 		 */
1574 		sep->se_wait = 0;
1575 
1576 		if (strncmp(sep->se_proto, "tcp", 3)) {
1577 			syslog(LOG_ERR,
1578 			    "%s: bad protocol for tcpmux service %s",
1579 			    CONFIG, sep->se_service);
1580 			goto more;
1581 		}
1582 		if (sep->se_socktype != SOCK_STREAM) {
1583 			syslog(LOG_ERR,
1584 			    "%s: bad socket type for tcpmux service %s",
1585 			    CONFIG, sep->se_service);
1586 			goto more;
1587 		}
1588 	}
1589 	sep->se_user = newstr(sskip(&cp));
1590 	if ((sep->se_group = strchr(sep->se_user, ':')) != NULL)
1591 		*sep->se_group++ = '\0';
1592 	else if ((sep->se_group = strchr(sep->se_user, '.')) != NULL)
1593 		*sep->se_group++ = '\0';
1594 
1595 	sep->se_server = newstr(sskip(&cp));
1596 	if (strcmp(sep->se_server, "internal") == 0) {
1597 		struct biltin *bi;
1598 
1599 		for (bi = biltins; bi->bi_service; bi++)
1600 			if (bi->bi_socktype == sep->se_socktype &&
1601 			    strcmp(bi->bi_service, sep->se_service) == 0)
1602 				break;
1603 		if (bi->bi_service == 0) {
1604 			syslog(LOG_ERR, "internal service %s unknown",
1605 			    sep->se_service);
1606 			goto more;
1607 		}
1608 		sep->se_bi = bi;
1609 		sep->se_wait = bi->bi_wait;
1610 	} else
1611 		sep->se_bi = NULL;
1612 	argc = 0;
1613 	for (arg = skip(&cp); cp; arg = skip(&cp)) {
1614 #if MULOG
1615 		char *colon;
1616 
1617 		if (argc == 0 && (colon = strrchr(arg, ':'))) {
1618 			while (arg < colon) {
1619 				int	x;
1620 				char	*ccp;
1621 
1622 				switch (*arg++) {
1623 				case 'l':
1624 					x = 1;
1625 					if (isdigit(*arg)) {
1626 						x = strtol(arg, &ccp, 0);
1627 						if (ccp == arg)
1628 							break;
1629 						arg = ccp;
1630 					}
1631 					sep->se_log &= ~MULOG_RFC931;
1632 					sep->se_log |= x;
1633 					break;
1634 				case 'a':
1635 					sep->se_log |= MULOG_RFC931;
1636 					break;
1637 				default:
1638 					break;
1639 				}
1640 			}
1641 			arg = colon + 1;
1642 		}
1643 #endif
1644 		if (argc < MAXARGV)
1645 			sep->se_argv[argc++] = newstr(arg);
1646 	}
1647 	while (argc <= MAXARGV)
1648 		sep->se_argv[argc++] = NULL;
1649 #ifdef IPSEC
1650 	sep->se_policy = policy ? newstr(policy) : NULL;
1651 #endif
1652 	return (sep);
1653 }
1654 
1655 static void
1656 freeconfig(struct servtab *cp)
1657 {
1658 	int i;
1659 
1660 	if (cp->se_hostaddr)
1661 		free(cp->se_hostaddr);
1662 	if (cp->se_service)
1663 		free(cp->se_service);
1664 	if (cp->se_proto)
1665 		free(cp->se_proto);
1666 	if (cp->se_user)
1667 		free(cp->se_user);
1668 	/* Note: se_group is part of the newstr'ed se_user */
1669 	if (cp->se_server)
1670 		free(cp->se_server);
1671 	for (i = 0; i < MAXARGV; i++)
1672 		if (cp->se_argv[i])
1673 			free(cp->se_argv[i]);
1674 #ifdef IPSEC
1675 	if (cp->se_policy)
1676 		free(cp->se_policy);
1677 #endif
1678 }
1679 
1680 
1681 /*
1682  * Safe skip - if skip returns null, log a syntax error in the
1683  * configuration file and exit.
1684  */
1685 static char *
1686 sskip(char **cpp)
1687 {
1688 	char *cp;
1689 
1690 	cp = skip(cpp);
1691 	if (cp == NULL) {
1692 		syslog(LOG_ERR, "%s: syntax error", CONFIG);
1693 		exit(1);
1694 	}
1695 	return (cp);
1696 }
1697 
1698 static char *
1699 skip(char **cpp)
1700 {
1701 	char *cp = *cpp;
1702 	char *start;
1703 	char quote;
1704 
1705 	if (*cpp == NULL)
1706 		return (NULL);
1707 
1708 again:
1709 	while (*cp == ' ' || *cp == '\t')
1710 		cp++;
1711 	if (*cp == '\0') {
1712 		int c;
1713 
1714 		c = getc(fconfig);
1715 		(void) ungetc(c, fconfig);
1716 		if (c == ' ' || c == '\t')
1717 			if ((cp = nextline(fconfig)))
1718 				goto again;
1719 		*cpp = NULL;
1720 		return (NULL);
1721 	}
1722 	start = cp;
1723 	quote = '\0';
1724 	while (*cp && (quote || (*cp != ' ' && *cp != '\t'))) {
1725 		if (*cp == '\'' || *cp == '"') {
1726 			if (quote && *cp != quote)
1727 				cp++;
1728 			else {
1729 				if (quote)
1730 					quote = '\0';
1731 				else
1732 					quote = *cp;
1733 				memmove(cp, cp+1, strlen(cp));
1734 			}
1735 		} else
1736 			cp++;
1737 	}
1738 	if (*cp != '\0')
1739 		*cp++ = '\0';
1740 	*cpp = cp;
1741 	return (start);
1742 }
1743 
1744 static char *
1745 nextline(FILE *fd)
1746 {
1747 	char *cp;
1748 
1749 	if (fgets(line, sizeof (line), fd) == NULL)
1750 		return (NULL);
1751 	cp = strchr(line, '\n');
1752 	if (cp)
1753 		*cp = '\0';
1754 	return (line);
1755 }
1756 
1757 static char *
1758 newstr(char *cp)
1759 {
1760 	if ((cp = strdup((cp != NULL) ? cp : "")) != NULL)
1761 		return (cp);
1762 	syslog(LOG_ERR, "strdup: %m");
1763 	exit(1);
1764 }
1765 
1766 static void
1767 inetd_setproctitle(char *a, int s)
1768 {
1769 	socklen_t size;
1770 	struct sockaddr_storage ss;
1771 	char hbuf[NI_MAXHOST], *hp;
1772 
1773 	size = sizeof(ss);
1774 	if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
1775 		if (getnameinfo((struct sockaddr *)&ss, size, hp = hbuf,
1776 		    sizeof(hbuf), NULL, 0, niflags) != 0)
1777 			hp = "?";
1778 		setproctitle("-%s [%s]", a, hp);
1779 	} else
1780 		setproctitle("-%s", a);
1781 }
1782 
1783 static void
1784 bump_nofile(void)
1785 {
1786 #ifdef RLIMIT_NOFILE
1787 
1788 #define FD_CHUNK	32
1789 
1790 	struct rlimit rl;
1791 
1792 	if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1793 		syslog(LOG_ERR, "getrlimit: %m");
1794 		return;
1795 	}
1796 	rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
1797 	if (rl.rlim_cur <= rlim_ofile_cur) {
1798 		syslog(LOG_ERR,
1799 		    "bump_nofile: cannot extend file limit, max = %d",
1800 		    (int)rl.rlim_cur);
1801 		return;
1802 	}
1803 
1804 	if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
1805 		syslog(LOG_ERR, "setrlimit: %m");
1806 		return;
1807 	}
1808 
1809 	rlim_ofile_cur = rl.rlim_cur;
1810 	return;
1811 
1812 #else
1813 	syslog(LOG_ERR, "bump_nofile: cannot extend file limit");
1814 	return;
1815 #endif
1816 }
1817 
1818 /*
1819  * Internet services provided internally by inetd:
1820  */
1821 #define	BUFSIZE	4096
1822 
1823 /* ARGSUSED */
1824 static void
1825 echo_stream(int s, struct servtab *sep)	/* Echo service -- echo data back */
1826 {
1827 	char buffer[BUFSIZE];
1828 	int i;
1829 
1830 	inetd_setproctitle(sep->se_service, s);
1831 	while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
1832 	    write(s, buffer, i) > 0)
1833 		;
1834 }
1835 
1836 /* ARGSUSED */
1837 static void
1838 echo_dg(int s, struct servtab *sep)	/* Echo service -- echo data back */
1839 {
1840 	char buffer[BUFSIZE];
1841 	int i;
1842 	socklen_t size;
1843 	struct sockaddr_storage ss;
1844 	struct sockaddr *sa;
1845 
1846 	sa = (struct sockaddr *)&ss;
1847 	size = sizeof(ss);
1848 	if ((i = recvfrom(s, buffer, sizeof(buffer), 0, sa, &size)) < 0)
1849 		return;
1850 	if (port_good_dg(sa))
1851 		(void) sendto(s, buffer, i, 0, sa, size);
1852 }
1853 
1854 /* ARGSUSED */
1855 static void
1856 discard_stream(int s, struct servtab *sep) /* Discard service -- ignore data */
1857 {
1858 	char buffer[BUFSIZE];
1859 
1860 	inetd_setproctitle(sep->se_service, s);
1861 	while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
1862 			errno == EINTR)
1863 		;
1864 }
1865 
1866 /* ARGSUSED */
1867 static void
1868 discard_dg(int s, struct servtab *sep)	/* Discard service -- ignore data */
1869 
1870 {
1871 	char buffer[BUFSIZE];
1872 
1873 	(void) read(s, buffer, sizeof(buffer));
1874 }
1875 
1876 #define LINESIZ 72
1877 char ring[128];
1878 char *endring;
1879 
1880 static void
1881 initring(void)
1882 {
1883 	int i;
1884 
1885 	endring = ring;
1886 
1887 	for (i = 0; i <= 128; ++i)
1888 		if (isprint(i))
1889 			*endring++ = i;
1890 }
1891 
1892 /* ARGSUSED */
1893 static void
1894 chargen_stream(int s,struct servtab *sep)	/* Character generator */
1895 {
1896 	int len;
1897 	char *rs, text[LINESIZ+2];
1898 
1899 	inetd_setproctitle(sep->se_service, s);
1900 
1901 	if (!endring) {
1902 		initring();
1903 		rs = ring;
1904 	}
1905 
1906 	text[LINESIZ] = '\r';
1907 	text[LINESIZ + 1] = '\n';
1908 	for (rs = ring;;) {
1909 		if ((len = endring - rs) >= LINESIZ)
1910 			memmove(text, rs, LINESIZ);
1911 		else {
1912 			memmove(text, rs, len);
1913 			memmove(text + len, ring, LINESIZ - len);
1914 		}
1915 		if (++rs == endring)
1916 			rs = ring;
1917 		if (write(s, text, sizeof(text)) != sizeof(text))
1918 			break;
1919 	}
1920 }
1921 
1922 /* ARGSUSED */
1923 static void
1924 chargen_dg(int s, struct servtab *sep)		/* Character generator */
1925 {
1926 	struct sockaddr_storage ss;
1927 	struct sockaddr *sa;
1928 	static char *rs;
1929 	int len;
1930 	socklen_t size;
1931 	char text[LINESIZ+2];
1932 
1933 	if (endring == 0) {
1934 		initring();
1935 		rs = ring;
1936 	}
1937 
1938 	sa = (struct sockaddr *)&ss;
1939 	size = sizeof(ss);
1940 	if (recvfrom(s, text, sizeof(text), 0, sa, &size) < 0)
1941 		return;
1942 
1943 	if (!port_good_dg(sa))
1944 		return;
1945 
1946 	if ((len = endring - rs) >= LINESIZ)
1947 		memmove(text, rs, LINESIZ);
1948 	else {
1949 		memmove(text, rs, len);
1950 		memmove(text + len, ring, LINESIZ - len);
1951 	}
1952 	if (++rs == endring)
1953 		rs = ring;
1954 	text[LINESIZ] = '\r';
1955 	text[LINESIZ + 1] = '\n';
1956 	(void) sendto(s, text, sizeof(text), 0, sa, size);
1957 }
1958 
1959 /*
1960  * Return a machine readable date and time, in the form of the
1961  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
1962  * returns the number of seconds since midnight, Jan 1, 1970,
1963  * we must add 2208988800 seconds to this figure to make up for
1964  * some seventy years Bell Labs was asleep.
1965  */
1966 
1967 static uint32_t
1968 machtime(void)
1969 {
1970 	struct timeval tv;
1971 
1972 	if (gettimeofday(&tv, NULL) < 0) {
1973 		if (debug)
1974 			fprintf(stderr, "Unable to get time of day\n");
1975 		return (0);
1976 	}
1977 #define	OFFSET ((uint32_t)25567 * 24*60*60)
1978 	return (htonl((uint32_t)(tv.tv_sec + OFFSET)));
1979 #undef OFFSET
1980 }
1981 
1982 /* ARGSUSED */
1983 static void
1984 machtime_stream(int s, struct servtab *sep)
1985 {
1986 	uint32_t result;
1987 
1988 	result = machtime();
1989 	(void) write(s, (char *) &result, sizeof(result));
1990 }
1991 
1992 /* ARGSUSED */
1993 void
1994 machtime_dg(int s, struct servtab *sep)
1995 {
1996 	uint32_t result;
1997 	struct sockaddr_storage ss;
1998 	struct sockaddr *sa;
1999 	socklen_t size;
2000 
2001 	sa = (struct sockaddr *)&ss;
2002 	size = sizeof(ss);
2003 	if (recvfrom(s, (char *)&result, sizeof(result), 0, sa, &size) < 0)
2004 		return;
2005 	if (!port_good_dg(sa))
2006 		return;
2007 	result = machtime();
2008 	(void) sendto(s, (char *) &result, sizeof(result), 0, sa, size);
2009 }
2010 
2011 /* ARGSUSED */
2012 static void
2013 daytime_stream(int s,struct servtab *sep)
2014 /* Return human-readable time of day */
2015 {
2016 	char buffer[256];
2017 	time_t clock;
2018 	int len;
2019 
2020 	clock = time((time_t *) 0);
2021 
2022 	len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2023 	(void) write(s, buffer, len);
2024 }
2025 
2026 /* ARGSUSED */
2027 void
2028 daytime_dg(int s, struct servtab *sep)
2029 /* Return human-readable time of day */
2030 {
2031 	char buffer[256];
2032 	time_t clock;
2033 	struct sockaddr_storage ss;
2034 	struct sockaddr *sa;
2035 	socklen_t size;
2036 	int len;
2037 
2038 	clock = time((time_t *) 0);
2039 
2040 	sa = (struct sockaddr *)&ss;
2041 	size = sizeof(ss);
2042 	if (recvfrom(s, buffer, sizeof(buffer), 0, sa, &size) < 0)
2043 		return;
2044 	if (!port_good_dg(sa))
2045 		return;
2046 	len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2047 	(void) sendto(s, buffer, len, 0, sa, size);
2048 }
2049 
2050 /*
2051  * print_service:
2052  *	Dump relevant information to stderr
2053  */
2054 static void
2055 print_service(char *action, struct servtab *sep)
2056 {
2057 
2058 	if (isrpcservice(sep))
2059 		fprintf(stderr,
2060 		    "%s: %s rpcprog=%d, rpcvers = %d/%d, proto=%s, wait.max=%d.%d, user:group=%s:%s builtin=%lx server=%s"
2061 #ifdef IPSEC
2062 		    " policy=\"%s\""
2063 #endif
2064 		    "\n",
2065 		    action, sep->se_service,
2066 		    sep->se_rpcprog, sep->se_rpcversh, sep->se_rpcversl, sep->se_proto,
2067 		    sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2068 		    (long)sep->se_bi, sep->se_server
2069 #ifdef IPSEC
2070 		    , (sep->se_policy ? sep->se_policy : "")
2071 #endif
2072 		    );
2073 	else
2074 		fprintf(stderr,
2075 		    "%s: %s proto=%s%s, wait.max=%d.%d, user:group=%s:%s builtin=%lx server=%s"
2076 #ifdef IPSEC
2077 		    " policy=%s"
2078 #endif
2079 		    "\n",
2080 		    action, sep->se_service,
2081 		    sep->se_type == FAITH_TYPE ? "faith/" : "",
2082 		    sep->se_proto,
2083 		    sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2084 		    (long)sep->se_bi, sep->se_server
2085 #ifdef IPSEC
2086 		    , (sep->se_policy ? sep->se_policy : "")
2087 #endif
2088 		    );
2089 }
2090 
2091 static void
2092 usage(void)
2093 {
2094 #ifdef LIBWRAP
2095 	(void)fprintf(stderr, "usage: %s [-dl] [conf]\n", getprogname());
2096 #else
2097 	(void)fprintf(stderr, "usage: %s [-d] [conf]\n", getprogname());
2098 #endif
2099 	exit(1);
2100 }
2101 
2102 
2103 /*
2104  *  Based on TCPMUX.C by Mark K. Lottor November 1988
2105  *  sri-nic::ps:<mkl>tcpmux.c
2106  */
2107 
2108 static int		/* # of characters upto \r,\n or \0 */
2109 getline(int fd,	char *buf, int len)
2110 {
2111 	int count = 0, n;
2112 
2113 	do {
2114 		n = read(fd, buf, len-count);
2115 		if (n == 0)
2116 			return (count);
2117 		if (n < 0)
2118 			return (-1);
2119 		while (--n >= 0) {
2120 			if (*buf == '\r' || *buf == '\n' || *buf == '\0')
2121 				return (count);
2122 			count++;
2123 			buf++;
2124 		}
2125 	} while (count < len);
2126 	return (count);
2127 }
2128 
2129 #define MAX_SERV_LEN	(256+2)		/* 2 bytes for \r\n */
2130 
2131 #define strwrite(fd, buf)	(void) write(fd, buf, sizeof(buf)-1)
2132 
2133 static void
2134 tcpmux(int ctrl, struct servtab *sep)
2135 {
2136 	char service[MAX_SERV_LEN+1];
2137 	int len;
2138 
2139 	/* Get requested service name */
2140 	if ((len = getline(ctrl, service, MAX_SERV_LEN)) < 0) {
2141 		strwrite(ctrl, "-Error reading service name\r\n");
2142 		goto reject;
2143 	}
2144 	service[len] = '\0';
2145 
2146 	if (debug)
2147 		fprintf(stderr, "tcpmux: someone wants %s\n", service);
2148 
2149 	/*
2150 	 * Help is a required command, and lists available services,
2151 	 * one per line.
2152 	 */
2153 	if (!strcasecmp(service, "help")) {
2154 		strwrite(ctrl, "+Available services:\r\n");
2155 		strwrite(ctrl, "help\r\n");
2156 		for (sep = servtab; sep != NULL; sep = sep->se_next) {
2157 			if (!ISMUX(sep))
2158 				continue;
2159 			(void)write(ctrl, sep->se_service,
2160 			    strlen(sep->se_service));
2161 			strwrite(ctrl, "\r\n");
2162 		}
2163 		goto reject;
2164 	}
2165 
2166 	/* Try matching a service in inetd.conf with the request */
2167 	for (sep = servtab; sep != NULL; sep = sep->se_next) {
2168 		if (!ISMUX(sep))
2169 			continue;
2170 		if (!strcasecmp(service, sep->se_service)) {
2171 			if (ISMUXPLUS(sep))
2172 				strwrite(ctrl, "+Go\r\n");
2173 			run_service(ctrl, sep);
2174 			return;
2175 		}
2176 	}
2177 	strwrite(ctrl, "-Service not available\r\n");
2178 reject:
2179 	_exit(1);
2180 }
2181 
2182 #ifdef MULOG
2183 void
2184 dolog(struct servtab *sep, int ctrl)
2185 {
2186 	struct sockaddr_storage	ss;
2187 	struct sockaddr		*sa = (struct sockaddr *)&ss;
2188 	socklen_t		len = sizeof(ss);
2189 	char			*host, *dp, buf[BUFSIZ];
2190 	int			connected = 1;
2191 
2192 	switch (sep->se_family) {
2193 	case AF_INET:
2194 #ifdef INET6
2195 	case AF_INET6:
2196 #endif
2197 		break;
2198 	default:
2199 		return;
2200 	}
2201 
2202 	if (getpeername(ctrl, sa, &len) < 0) {
2203 		if (errno != ENOTCONN) {
2204 			syslog(LOG_ERR, "getpeername: %m");
2205 			return;
2206 		}
2207 		if (recvfrom(ctrl, buf, sizeof(buf), MSG_PEEK, sa, &len) < 0) {
2208 			syslog(LOG_ERR, "recvfrom: %m");
2209 			return;
2210 		}
2211 		connected = 0;
2212 	}
2213 	switch (sa->sa_family) {
2214 	case AF_INET:
2215 #ifdef INET6
2216 	case AF_INET6:
2217 #endif
2218 		break;
2219 	default:
2220 		syslog(LOG_ERR, "unexpected address family %u", sa->sa_family);
2221 		return;
2222 	}
2223 
2224 	if (getnameinfo(sa, len, buf, sizeof(buf), NULL, 0, 0) != 0)
2225 		strlcpy(buf, "?", sizeof(buf));
2226 	host = buf;
2227 
2228 	switch (sep->se_log & ~MULOG_RFC931) {
2229 	case 0:
2230 		return;
2231 	case 1:
2232 		if (curdom == NULL || *curdom == '\0')
2233 			break;
2234 		dp = host + strlen(host) - strlen(curdom);
2235 		if (dp < host)
2236 			break;
2237 		if (debug)
2238 			fprintf(stderr, "check \"%s\" against curdom \"%s\"\n",
2239 			    host, curdom);
2240 		if (strcasecmp(dp, curdom) == 0)
2241 			return;
2242 		break;
2243 	case 2:
2244 	default:
2245 		break;
2246 	}
2247 
2248 	openlog("", LOG_NOWAIT, MULOG);
2249 
2250 	if (connected && (sep->se_log & MULOG_RFC931))
2251 		syslog(LOG_INFO, "%s@%s wants %s",
2252 		    rfc931_name(sa, ctrl), host, sep->se_service);
2253 	else
2254 		syslog(LOG_INFO, "%s wants %s",
2255 		    host, sep->se_service);
2256 }
2257 
2258 /*
2259  * From tcp_log by
2260  *  Wietse Venema, Eindhoven University of Technology, The Netherlands.
2261  */
2262 #if 0
2263 static char sccsid[] = "@(#) rfc931.c 1.3 92/08/31 22:54:46";
2264 #endif
2265 
2266 #include <setjmp.h>
2267 
2268 #define	RFC931_PORT	113		/* Semi-well-known port */
2269 #define	TIMEOUT		4
2270 #define	TIMEOUT2	10
2271 
2272 static jmp_buf timebuf;
2273 
2274 /* timeout - handle timeouts */
2275 
2276 static void
2277 timeout(int sig)
2278 {
2279 	longjmp(timebuf, sig);
2280 }
2281 
2282 /* rfc931_name - return remote user name */
2283 
2284 char *
2285 rfc931_name(struct sockaddr *there,	/* remote link information */
2286     int ctrl)
2287 {
2288 	struct sockaddr_storage here;	/* local link information */
2289 	struct sockaddr_storage sin;	/* for talking to RFC931 daemon */
2290 	socklen_t	length;
2291 	int		s;
2292 	unsigned	remote;
2293 	unsigned	local;
2294 	static char	user[256];		/* XXX */
2295 	char		buf[256];
2296 	char		*cp;
2297 	char		*result = "USER_UNKNOWN";
2298 	int		len;
2299 	u_int16_t	myport, hisport;
2300 
2301 	/* Find out local port number of our stdin. */
2302 
2303 	length = sizeof(here);
2304 	if (getsockname(ctrl, (struct sockaddr *) &here, &length) == -1) {
2305 		syslog(LOG_ERR, "getsockname: %m");
2306 		return (result);
2307 	}
2308 	switch (here.ss_family) {
2309 	case AF_INET:
2310 		myport = ((struct sockaddr_in *)&here)->sin_port;
2311 		break;
2312 #ifdef INET6
2313 	case AF_INET6:
2314 		myport = ((struct sockaddr_in6 *)&here)->sin6_port;
2315 		break;
2316 #endif
2317 	}
2318 	switch (there->sa_family) {
2319 	case AF_INET:
2320 		hisport = ((struct sockaddr_in *)&there)->sin_port;
2321 		break;
2322 #ifdef INET6
2323 	case AF_INET6:
2324 		hisport = ((struct sockaddr_in6 *)&there)->sin6_port;
2325 		break;
2326 #endif
2327 	}
2328 	/* Set up timer so we won't get stuck. */
2329 
2330 	if ((s = socket(here.ss_family, SOCK_STREAM, 0)) == -1) {
2331 		syslog(LOG_ERR, "socket: %m");
2332 		return (result);
2333 	}
2334 
2335 	sin = here;
2336 	switch (sin.ss_family) {
2337 	case AF_INET:
2338 		((struct sockaddr_in *)&sin)->sin_port = htons(0);
2339 		break;
2340 #ifdef INET6
2341 	case AF_INET6:
2342 		((struct sockaddr_in6 *)&sin)->sin6_port = htons(0);
2343 		break;
2344 #endif
2345 	}
2346 	if (bind(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2347 		syslog(LOG_ERR, "bind: %m");
2348 		return (result);
2349 	}
2350 
2351 	signal(SIGALRM, timeout);
2352 	if (setjmp(timebuf)) {
2353 		close(s);			/* not: fclose(fp) */
2354 		return (result);
2355 	}
2356 	alarm(TIMEOUT);
2357 
2358 	/* Connect to the RFC931 daemon. */
2359 
2360 	memcpy(&sin, there, there->sa_len);
2361 	switch (sin.ss_family) {
2362 	case AF_INET:
2363 		((struct sockaddr_in *)&sin)->sin_port = htons(RFC931_PORT);
2364 		break;
2365 #ifdef INET6
2366 	case AF_INET6:
2367 		((struct sockaddr_in6 *)&sin)->sin6_port = htons(RFC931_PORT);
2368 		break;
2369 #endif
2370 	}
2371 	if (connect(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2372 		close(s);
2373 		alarm(0);
2374 		return (result);
2375 	}
2376 
2377 	/* Query the RFC 931 server. Would 13-byte writes ever be broken up? */
2378 	(void)snprintf(buf, sizeof buf, "%u,%u\r\n", ntohs(hisport),
2379 	    ntohs(myport));
2380 
2381 	for (len = 0, cp = buf; len < strlen(buf); ) {
2382 		int	n;
2383 
2384 		if ((n = write(s, cp, strlen(buf) - len)) == -1) {
2385 			close(s);
2386 			alarm(0);
2387 			return (result);
2388 		}
2389 		cp += n;
2390 		len += n;
2391 	}
2392 
2393 	/* Read response */
2394 	for (cp = buf; cp < buf + sizeof(buf) - 1; ) {
2395 		char	c;
2396 		if (read(s, &c, 1) != 1) {
2397 			close(s);
2398 			alarm(0);
2399 			return (result);
2400 		}
2401 		if (c == '\n')
2402 			break;
2403 		*cp++ = c;
2404 	}
2405 	*cp = '\0';
2406 
2407 	if (sscanf(buf, "%u , %u : USERID :%*[^:]:%255s", &remote, &local,
2408 	    user) == 3 && ntohs(hisport) == remote && ntohs(myport) == local) {
2409 		/* Strip trailing carriage return. */
2410 		if ((cp = strchr(user, '\r')) != NULL)
2411 			*cp = 0;
2412 		result = user;
2413 	}
2414 
2415 	alarm(0);
2416 	close(s);
2417 	return (result);
2418 }
2419 #endif
2420 
2421 /*
2422  * check if the address/port where send data to is one of the obvious ports
2423  * that are used for denial of service attacks like two echo ports
2424  * just echoing data between them
2425  */
2426 static int
2427 port_good_dg(struct sockaddr *sa)
2428 {
2429 	struct in_addr in;
2430 #ifdef INET6
2431 	struct in6_addr *in6;
2432 #endif
2433 	u_int16_t port;
2434 	int i, bad;
2435 	char hbuf[NI_MAXHOST];
2436 
2437 	bad = 0;
2438 
2439 	switch (sa->sa_family) {
2440 	case AF_INET:
2441 		in.s_addr = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr);
2442 		port = ntohs(((struct sockaddr_in *)sa)->sin_port);
2443 #ifdef INET6
2444 	v4chk:
2445 #endif
2446 		if (IN_MULTICAST(in.s_addr))
2447 			goto bad;
2448 		switch ((in.s_addr & 0xff000000) >> 24) {
2449 		case 0: case 127: case 255:
2450 			goto bad;
2451 		}
2452 		if (dg_broadcast(&in))
2453 			goto bad;
2454 		break;
2455 #ifdef INET6
2456 	case AF_INET6:
2457 		in6 = &((struct sockaddr_in6 *)sa)->sin6_addr;
2458 		port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
2459 		if (IN6_IS_ADDR_MULTICAST(in6) || IN6_IS_ADDR_UNSPECIFIED(in6))
2460 			goto bad;
2461 		if (IN6_IS_ADDR_V4MAPPED(in6) || IN6_IS_ADDR_V4COMPAT(in6)) {
2462 			memcpy(&in, &in6->s6_addr[12], sizeof(in));
2463 			in.s_addr = ntohl(in.s_addr);
2464 			goto v4chk;
2465 		}
2466 		break;
2467 #endif
2468 	default:
2469 		/* XXX unsupported af, is it safe to assume it to be safe? */
2470 		return (1);
2471 	}
2472 
2473 	for (i = 0; bad_ports[i] != 0; i++) {
2474 		if (port == bad_ports[i])
2475 			goto bad;
2476 	}
2477 
2478 	return (1);
2479 
2480 bad:
2481 	if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,
2482 	    niflags) != 0)
2483 		strlcpy(hbuf, "?", sizeof(hbuf));
2484 	syslog(LOG_WARNING,"Possible DoS attack from %s, Port %d",
2485 		hbuf, port);
2486 	return (0);
2487 }
2488 
2489 /* XXX need optimization */
2490 static int
2491 dg_broadcast(struct in_addr *in)
2492 {
2493 	struct ifaddrs *ifa, *ifap;
2494 	struct sockaddr_in *sin;
2495 
2496 	if (getifaddrs(&ifap) < 0)
2497 		return (0);
2498 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
2499 		if (ifa->ifa_addr->sa_family != AF_INET ||
2500 		    (ifa->ifa_flags & IFF_BROADCAST) == 0)
2501 			continue;
2502 		sin = (struct sockaddr_in *)ifa->ifa_broadaddr;
2503 		if (sin->sin_addr.s_addr == in->s_addr) {
2504 			freeifaddrs(ifap);
2505 			return (1);
2506 		}
2507 	}
2508 	freeifaddrs(ifap);
2509 	return (0);
2510 }
2511 
2512 static int
2513 my_kevent(const struct kevent *changelist, size_t nchanges,
2514     struct kevent *eventlist, size_t nevents)
2515 {
2516 	int	result;
2517 
2518 	while ((result = kevent(kq, changelist, nchanges, eventlist, nevents,
2519 	    NULL)) < 0)
2520 		if (errno != EINTR) {
2521 			syslog(LOG_ERR, "kevent: %m");
2522 			exit(EXIT_FAILURE);
2523 		}
2524 
2525 	return (result);
2526 }
2527 
2528 static struct kevent *
2529 allocchange(void)
2530 {
2531 	if (changes == A_CNT(changebuf)) {
2532 		(void) my_kevent(changebuf, A_CNT(changebuf), NULL, 0);
2533 		changes = 0;
2534 	}
2535 
2536 	return (&changebuf[changes++]);
2537 }
2538