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