Home | History | Annotate | Line # | Download | only in inetd
inetd.c revision 1.88
      1 /*	$NetBSD: inetd.c,v 1.88 2003/02/16 17:57:34 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.88 2003/02/16 17:57:34 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	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[] =
    450     { SIGALRM, SIGHUP, SIGCHLD, SIGTERM, SIGINT, SIGPIPE };
    451 
    452 int
    453 main(int argc, char *argv[])
    454 {
    455 	int		ch, n, reload = 1;
    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 		int	signum;
    507 
    508 		signum = my_signals[n];
    509 		(void) signal(signum, SIG_IGN);
    510 
    511 		if (signum != SIGPIPE) {
    512 			struct kevent	*ev;
    513 
    514 			ev = allocchange();
    515 			EV_SET(ev, signum, EVFILT_SIGNAL, EV_ADD | EV_ENABLE,
    516 			    0, 0, NULL);
    517 		}
    518 	}
    519 
    520 	for (;;) {
    521 		int		ctrl;
    522 		struct kevent	eventbuf[64], *ev;
    523 		struct servtab	*sep;
    524 
    525 		if (reload) {
    526 			reload = 0;
    527 			config();
    528 		}
    529 
    530 		n = my_kevent(changebuf, changes, eventbuf, A_CNT(eventbuf));
    531 		changes = 0;
    532 
    533 		for (ev = eventbuf; n > 0; ev++, n--) {
    534 			if (ev->filter == EVFILT_SIGNAL) {
    535 				switch (ev->ident) {
    536 				case SIGALRM:
    537 					retry();
    538 					break;
    539 				case SIGCHLD:
    540 					reapchild();
    541 					break;
    542 				case SIGTERM:
    543 				case SIGINT:
    544 					goaway();
    545 					break;
    546 				case SIGHUP:
    547 					reload = 1;
    548 					break;
    549 				}
    550 				continue;
    551 			}
    552 			if (ev->filter != EVFILT_READ)
    553 				continue;
    554 			sep = (struct servtab *)ev->udata;
    555 			/* Paranoia */
    556 			if (ev->ident != sep->se_fd)
    557 				continue;
    558 			if (debug)
    559 				fprintf(stderr, "someone wants %s\n", sep->se_service);
    560 			if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
    561 				/* XXX here do the libwrap check-before-accept */
    562 				ctrl = accept(sep->se_fd, NULL, NULL);
    563 				if (debug)
    564 					fprintf(stderr, "accept, ctrl %d\n",
    565 					    ctrl);
    566 				if (ctrl < 0) {
    567 					if (errno != EINTR)
    568 						syslog(LOG_WARNING,
    569 						    "accept (for %s): %m",
    570 						    sep->se_service);
    571 					continue;
    572 				}
    573 			} else
    574 				ctrl = sep->se_fd;
    575 			(void) sigblock(SIGBLOCK);
    576 			spawn(sep, ctrl);
    577 		}
    578 	}
    579 }
    580 
    581 static void
    582 spawn(struct servtab *sep, int ctrl)
    583 {
    584 	int dofork;
    585 	pid_t pid;
    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 		}
    636 		if (pid == 0) {
    637 			int	n;
    638 
    639 			for (n = 0; n < A_CNT(my_signals); n++)
    640 				(void) signal(my_signals[n], SIG_DFL);
    641 			if (debug)
    642 				setsid();
    643 		}
    644 	}
    645 	sigsetmask(0L);
    646 	if (pid == 0) {
    647 		run_service(ctrl, sep);
    648 		if (dofork)
    649 			exit(0);
    650 	}
    651 	if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
    652 		close(ctrl);
    653 }
    654 
    655 static void
    656 run_service(int ctrl, struct servtab *sep)
    657 {
    658 	struct passwd *pwd;
    659 	struct group *grp = NULL;	/* XXX gcc */
    660 	char buf[NI_MAXSERV];
    661 #ifdef LIBWRAP
    662 	struct request_info req;
    663 	int denied;
    664 	char *service = NULL;	/* XXX gcc */
    665 #endif
    666 
    667 #ifdef LIBWRAP
    668 #ifndef LIBWRAP_INTERNAL
    669 	if (sep->se_bi == 0)
    670 #endif
    671 	if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
    672 		request_init(&req, RQ_DAEMON, sep->se_argv[0] ?
    673 		    sep->se_argv[0] : sep->se_service, RQ_FILE, ctrl, NULL);
    674 		fromhost(&req);
    675 		denied = !hosts_access(&req);
    676 		if (denied || lflag) {
    677 			if (getnameinfo(&sep->se_ctrladdr,
    678 					sep->se_ctrladdr.sa_len, NULL, 0,
    679 					buf, sizeof(buf), 0) != 0) {
    680 				/* shouldn't happen */
    681 				(void)snprintf(buf, sizeof buf, "%d",
    682 				    ntohs(sep->se_ctrladdr_in.sin_port));
    683 			}
    684 			service = buf;
    685 		}
    686 		if (denied) {
    687 			syslog(deny_severity,
    688 			    "refused connection from %.500s, service %s (%s)",
    689 			    eval_client(&req), service, sep->se_proto);
    690 			goto reject;
    691 		}
    692 		if (lflag) {
    693 			syslog(allow_severity,
    694 			    "connection from %.500s, service %s (%s)",
    695 			    eval_client(&req), service, sep->se_proto);
    696 		}
    697 	}
    698 #endif /* LIBWRAP */
    699 
    700 	if (sep->se_bi) {
    701 		(*sep->se_bi->bi_fn)(ctrl, sep);
    702 	} else {
    703 		if ((pwd = getpwnam(sep->se_user)) == NULL) {
    704 			syslog(LOG_ERR, "%s/%s: %s: No such user",
    705 			    sep->se_service, sep->se_proto, sep->se_user);
    706 			goto reject;
    707 		}
    708 		if (sep->se_group &&
    709 		    (grp = getgrnam(sep->se_group)) == NULL) {
    710 			syslog(LOG_ERR, "%s/%s: %s: No such group",
    711 			    sep->se_service, sep->se_proto, sep->se_group);
    712 			goto reject;
    713 		}
    714 		if (pwd->pw_uid) {
    715 			if (sep->se_group)
    716 				pwd->pw_gid = grp->gr_gid;
    717 			if (setgid(pwd->pw_gid) < 0) {
    718 				syslog(LOG_ERR,
    719 				 "%s/%s: can't set gid %d: %m", sep->se_service,
    720 				    sep->se_proto, pwd->pw_gid);
    721 				goto reject;
    722 			}
    723 			(void) initgroups(pwd->pw_name,
    724 			    pwd->pw_gid);
    725 			if (setuid(pwd->pw_uid) < 0) {
    726 				syslog(LOG_ERR,
    727 				 "%s/%s: can't set uid %d: %m", sep->se_service,
    728 				    sep->se_proto, pwd->pw_uid);
    729 				goto reject;
    730 			}
    731 		} else if (sep->se_group) {
    732 			(void) setgid((gid_t)grp->gr_gid);
    733 		}
    734 		if (debug)
    735 			fprintf(stderr, "%d execl %s\n",
    736 			    getpid(), sep->se_server);
    737 #ifdef MULOG
    738 		if (sep->se_log)
    739 			dolog(sep, ctrl);
    740 #endif
    741 		/* Set our control descriptor to not close-on-exec... */
    742 		if (fcntl(ctrl, F_SETFD, 0) < 0)
    743 			syslog(LOG_ERR, "fcntl (F_SETFD, 0): %m");
    744 		/* ...and dup it to stdin, stdout, and stderr. */
    745 		if (ctrl != 0) {
    746 			dup2(ctrl, 0);
    747 			close(ctrl);
    748 			ctrl = 0;
    749 		}
    750 		dup2(0, 1);
    751 		dup2(0, 2);
    752 #ifdef RLIMIT_NOFILE
    753 		if (rlim_ofile.rlim_cur != rlim_ofile_cur &&
    754 		    setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
    755 			syslog(LOG_ERR, "setrlimit: %m");
    756 #endif
    757 		execv(sep->se_server, sep->se_argv);
    758 		syslog(LOG_ERR, "cannot execute %s: %m", sep->se_server);
    759 	reject:
    760 		if (sep->se_socktype != SOCK_STREAM)
    761 			recv(ctrl, buf, sizeof (buf), 0);
    762 		_exit(1);
    763 	}
    764 }
    765 
    766 static void
    767 reapchild(void)
    768 {
    769 	int status;
    770 	pid_t pid;
    771 	struct servtab *sep;
    772 
    773 	for (;;) {
    774 		pid = wait3(&status, WNOHANG, NULL);
    775 		if (pid <= 0)
    776 			break;
    777 		if (debug)
    778 			(void) fprintf(stderr, "%d reaped, status %#x\n",
    779 			    pid, status);
    780 		for (sep = servtab; sep != NULL; sep = sep->se_next)
    781 			if (sep->se_wait == pid) {
    782 				struct kevent	*ev;
    783 
    784 				if (WIFEXITED(status) && WEXITSTATUS(status))
    785 					syslog(LOG_WARNING,
    786 					    "%s: exit status 0x%x",
    787 					    sep->se_server, WEXITSTATUS(status));
    788 				else if (WIFSIGNALED(status))
    789 					syslog(LOG_WARNING,
    790 					    "%s: exit signal 0x%x",
    791 					    sep->se_server, WTERMSIG(status));
    792 				sep->se_wait = 1;
    793 				ev = allocchange();
    794 				EV_SET(ev, sep->se_fd, EVFILT_READ,
    795 				    EV_ADD | EV_ENABLE, 0, 0, (intptr_t)sep);
    796 				if (debug)
    797 					fprintf(stderr, "restored %s, fd %d\n",
    798 					    sep->se_service, sep->se_fd);
    799 			}
    800 	}
    801 }
    802 
    803 static void
    804 config(void)
    805 {
    806 	struct servtab *sep, *cp, **sepp;
    807 	long omask;
    808 	int n;
    809 
    810 	if (!setconfig()) {
    811 		syslog(LOG_ERR, "%s: %m", CONFIG);
    812 		return;
    813 	}
    814 	for (sep = servtab; sep != NULL; sep = sep->se_next)
    815 		sep->se_checked = 0;
    816 	while ((cp = getconfigent())) {
    817 		for (sep = servtab; sep != NULL; sep = sep->se_next)
    818 			if (strcmp(sep->se_service, cp->se_service) == 0 &&
    819 			    strcmp(sep->se_hostaddr, cp->se_hostaddr) == 0 &&
    820 			    strcmp(sep->se_proto, cp->se_proto) == 0 &&
    821 			    ISMUX(sep) == ISMUX(cp))
    822 				break;
    823 		if (sep != NULL) {
    824 			int i;
    825 
    826 #define SWAP(type, a, b) {type c=(type)a; (type)a=(type)b; (type)b=(type)c;}
    827 
    828 			omask = sigblock(SIGBLOCK);
    829 			/*
    830 			 * sep->se_wait may be holding the pid of a daemon
    831 			 * that we're waiting for.  If so, don't overwrite
    832 			 * it unless the config file explicitly says don't
    833 			 * wait.
    834 			 */
    835 			if (cp->se_bi == 0 &&
    836 			    (sep->se_wait == 1 || cp->se_wait == 0))
    837 				sep->se_wait = cp->se_wait;
    838 			SWAP(char *, sep->se_user, cp->se_user);
    839 			SWAP(char *, sep->se_group, cp->se_group);
    840 			SWAP(char *, sep->se_server, cp->se_server);
    841 			for (i = 0; i < MAXARGV; i++)
    842 				SWAP(char *, sep->se_argv[i], cp->se_argv[i]);
    843 #ifdef IPSEC
    844 			SWAP(char *, sep->se_policy, cp->se_policy);
    845 #endif
    846 			SWAP(int, cp->se_type, sep->se_type);
    847 			SWAP(int, cp->se_max, sep->se_max);
    848 #undef SWAP
    849 			if (isrpcservice(sep))
    850 				unregister_rpc(sep);
    851 			sep->se_rpcversl = cp->se_rpcversl;
    852 			sep->se_rpcversh = cp->se_rpcversh;
    853 			sigsetmask(omask);
    854 			freeconfig(cp);
    855 			if (debug)
    856 				print_service("REDO", sep);
    857 		} else {
    858 			sep = enter(cp);
    859 			if (debug)
    860 				print_service("ADD ", sep);
    861 		}
    862 		sep->se_checked = 1;
    863 
    864 		switch (sep->se_family) {
    865 		case AF_LOCAL:
    866 			if (sep->se_fd != -1)
    867 				break;
    868 			n = strlen(sep->se_service);
    869 			if (n > sizeof(sep->se_ctrladdr_un.sun_path)) {
    870 				syslog(LOG_ERR, "%s: address too long",
    871 				    sep->se_service);
    872 				sep->se_checked = 0;
    873 				continue;
    874 			}
    875 			(void)unlink(sep->se_service);
    876 			strncpy(sep->se_ctrladdr_un.sun_path,
    877 			    sep->se_service, n);
    878 			sep->se_ctrladdr_un.sun_family = AF_LOCAL;
    879 			sep->se_ctrladdr_size = n +
    880 			    sizeof(sep->se_ctrladdr_un) -
    881 			    sizeof(sep->se_ctrladdr_un.sun_path);
    882 			if (!ISMUX(sep))
    883 				setup(sep);
    884 			break;
    885 		case AF_INET:
    886 #ifdef INET6
    887 		case AF_INET6:
    888 #endif
    889 		    {
    890 			struct addrinfo hints, *res;
    891 			char *host, *port;
    892 			int error;
    893 			int s;
    894 
    895 			/* check if the family is supported */
    896 			s = socket(sep->se_family, SOCK_DGRAM, 0);
    897 			if (s < 0) {
    898 				syslog(LOG_WARNING,
    899 "%s/%s: %s: the address family is not supported by the kernel",
    900 				    sep->se_service, sep->se_proto,
    901 				    sep->se_hostaddr);
    902 				sep->se_checked = 0;
    903 				continue;
    904 			}
    905 			close(s);
    906 
    907 			memset(&hints, 0, sizeof(hints));
    908 			hints.ai_family = sep->se_family;
    909 			hints.ai_socktype = sep->se_socktype;
    910 			hints.ai_flags = AI_PASSIVE;
    911 			if (!strcmp(sep->se_hostaddr, "*"))
    912 				host = NULL;
    913 			else
    914 				host = sep->se_hostaddr;
    915 			if (isrpcservice(sep) || ISMUX(sep))
    916 				port = "0";
    917 			else
    918 				port = sep->se_service;
    919 			error = getaddrinfo(host, port, &hints, &res);
    920 			if (error) {
    921 				if (error == EAI_SERVICE) {
    922 					/* gai_strerror not friendly enough */
    923 					syslog(LOG_WARNING, "%s/%s: "
    924 					    "unknown service",
    925 					    sep->se_service, sep->se_proto);
    926 				} else {
    927 					syslog(LOG_ERR, "%s/%s: %s: %s",
    928 					    sep->se_service, sep->se_proto,
    929 					    sep->se_hostaddr,
    930 					    gai_strerror(error));
    931 				}
    932 				sep->se_checked = 0;
    933 				continue;
    934 			}
    935 			if (res->ai_next) {
    936 				syslog(LOG_ERR,
    937 					"%s/%s: %s: resolved to multiple addr",
    938 				    sep->se_service, sep->se_proto,
    939 				    sep->se_hostaddr);
    940 				sep->se_checked = 0;
    941 				freeaddrinfo(res);
    942 				continue;
    943 			}
    944 			memcpy(&sep->se_ctrladdr, res->ai_addr,
    945 				res->ai_addrlen);
    946 			if (ISMUX(sep)) {
    947 				sep->se_fd = -1;
    948 				freeaddrinfo(res);
    949 				continue;
    950 			}
    951 			sep->se_ctrladdr_size = res->ai_addrlen;
    952 			freeaddrinfo(res);
    953 #ifdef RPC
    954 			if (isrpcservice(sep)) {
    955 				struct rpcent *rp;
    956 
    957 				sep->se_rpcprog = atoi(sep->se_service);
    958 				if (sep->se_rpcprog == 0) {
    959 					rp = getrpcbyname(sep->se_service);
    960 					if (rp == 0) {
    961 						syslog(LOG_ERR,
    962 						    "%s/%s: unknown service",
    963 						    sep->se_service,
    964 						    sep->se_proto);
    965 						sep->se_checked = 0;
    966 						continue;
    967 					}
    968 					sep->se_rpcprog = rp->r_number;
    969 				}
    970 				if (sep->se_fd == -1 && !ISMUX(sep))
    971 					setup(sep);
    972 				if (sep->se_fd != -1)
    973 					register_rpc(sep);
    974 			} else
    975 #endif
    976 			{
    977 				if (sep->se_fd >= 0)
    978 					close_sep(sep);
    979 				if (sep->se_fd == -1 && !ISMUX(sep))
    980 					setup(sep);
    981 			}
    982 		    }
    983 		}
    984 	}
    985 	endconfig();
    986 	/*
    987 	 * Purge anything not looked at above.
    988 	 */
    989 	omask = sigblock(SIGBLOCK);
    990 	sepp = &servtab;
    991 	while ((sep = *sepp)) {
    992 		if (sep->se_checked) {
    993 			sepp = &sep->se_next;
    994 			continue;
    995 		}
    996 		*sepp = sep->se_next;
    997 		if (sep->se_fd >= 0)
    998 			close_sep(sep);
    999 		if (isrpcservice(sep))
   1000 			unregister_rpc(sep);
   1001 		if (sep->se_family == AF_LOCAL)
   1002 			(void)unlink(sep->se_service);
   1003 		if (debug)
   1004 			print_service("FREE", sep);
   1005 		freeconfig(sep);
   1006 		free(sep);
   1007 	}
   1008 	(void) sigsetmask(omask);
   1009 }
   1010 
   1011 static void
   1012 retry(void)
   1013 {
   1014 	struct servtab *sep;
   1015 
   1016 	timingout = 0;
   1017 	for (sep = servtab; sep != NULL; sep = sep->se_next) {
   1018 		if (sep->se_fd == -1 && !ISMUX(sep)) {
   1019 			switch (sep->se_family) {
   1020 			case AF_LOCAL:
   1021 			case AF_INET:
   1022 #ifdef INET6
   1023 			case AF_INET6:
   1024 #endif
   1025 				setup(sep);
   1026 				if (sep->se_fd != -1 && isrpcservice(sep))
   1027 					register_rpc(sep);
   1028 				break;
   1029 			}
   1030 		}
   1031 	}
   1032 }
   1033 
   1034 static void
   1035 goaway(void)
   1036 {
   1037 	struct servtab *sep;
   1038 
   1039 	for (sep = servtab; sep != NULL; sep = sep->se_next) {
   1040 		if (sep->se_fd == -1)
   1041 			continue;
   1042 
   1043 		switch (sep->se_family) {
   1044 		case AF_LOCAL:
   1045 			(void)unlink(sep->se_service);
   1046 			break;
   1047 		case AF_INET:
   1048 #ifdef INET6
   1049 		case AF_INET6:
   1050 #endif
   1051 			if (sep->se_wait == 1 && isrpcservice(sep))
   1052 				unregister_rpc(sep);
   1053 			break;
   1054 		}
   1055 		(void)close(sep->se_fd);
   1056 	}
   1057 	exit(0);
   1058 }
   1059 
   1060 static void
   1061 setup(struct servtab *sep)
   1062 {
   1063 	int		on = 1;
   1064 	struct kevent	*ev;
   1065 
   1066 	if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
   1067 		if (debug)
   1068 			fprintf(stderr, "socket failed on %s/%s: %s\n",
   1069 			    sep->se_service, sep->se_proto, strerror(errno));
   1070 		syslog(LOG_ERR, "%s/%s: socket: %m",
   1071 		    sep->se_service, sep->se_proto);
   1072 		return;
   1073 	}
   1074 	/* Set all listening sockets to close-on-exec. */
   1075 	if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
   1076 		syslog(LOG_ERR, "%s/%s: fcntl(F_SETFD, FD_CLOEXEC): %m",
   1077 		    sep->se_service, sep->se_proto);
   1078 		close(sep->se_fd);
   1079 		return;
   1080 	}
   1081 
   1082 #define	turnon(fd, opt) \
   1083 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
   1084 	if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
   1085 	    turnon(sep->se_fd, SO_DEBUG) < 0)
   1086 		syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
   1087 	if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
   1088 		syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
   1089 #undef turnon
   1090 
   1091 	/* Set the socket buffer sizes, if specified. */
   1092 	if (sep->se_sndbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
   1093 	    SO_SNDBUF, (char *)&sep->se_sndbuf, sizeof(sep->se_sndbuf)) < 0)
   1094 		syslog(LOG_ERR, "setsockopt (SO_SNDBUF %d): %m",
   1095 		    sep->se_sndbuf);
   1096 	if (sep->se_rcvbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
   1097 	    SO_RCVBUF, (char *)&sep->se_rcvbuf, sizeof(sep->se_rcvbuf)) < 0)
   1098 		syslog(LOG_ERR, "setsockopt (SO_RCVBUF %d): %m",
   1099 		    sep->se_rcvbuf);
   1100 	if (sep->se_type == FAITH_TYPE && setsockopt(sep->se_fd, IPPROTO_IPV6,
   1101 	    IPV6_FAITH, (char *)&on, sizeof(on)) < 0)
   1102 		syslog(LOG_ERR, "setsockopt (IPV6_FAITH): %m");
   1103 #ifdef IPSEC
   1104 	if (ipsecsetup(sep->se_family, sep->se_fd, sep->se_policy) < 0 &&
   1105 	    sep->se_policy) {
   1106 		syslog(LOG_ERR, "%s/%s: ipsec setup failed",
   1107 		    sep->se_service, sep->se_proto);
   1108 		(void)close(sep->se_fd);
   1109 		sep->se_fd = -1;
   1110 		return;
   1111 	}
   1112 #endif
   1113 
   1114 	if (bind(sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size) < 0) {
   1115 		if (debug)
   1116 			fprintf(stderr, "bind failed on %s/%s: %s\n",
   1117 			    sep->se_service, sep->se_proto, strerror(errno));
   1118 		syslog(LOG_ERR, "%s/%s: bind: %m",
   1119 		    sep->se_service, sep->se_proto);
   1120 		(void) close(sep->se_fd);
   1121 		sep->se_fd = -1;
   1122 		if (!timingout) {
   1123 			timingout = 1;
   1124 			alarm(RETRYTIME);
   1125 		}
   1126 		return;
   1127 	}
   1128 	if (sep->se_socktype == SOCK_STREAM)
   1129 		listen(sep->se_fd, 10);
   1130 
   1131 	ev = allocchange();
   1132 	EV_SET(ev, sep->se_fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0,
   1133 	    (intptr_t)sep);
   1134 	if (sep->se_fd > maxsock) {
   1135 		maxsock = sep->se_fd;
   1136 		if (maxsock > rlim_ofile_cur - FD_MARGIN)
   1137 			bump_nofile();
   1138 	}
   1139 	if (debug)
   1140 		fprintf(stderr, "registered %s on %d\n",
   1141 		    sep->se_server, sep->se_fd);
   1142 }
   1143 
   1144 /*
   1145  * Finish with a service and its socket.
   1146  */
   1147 static void
   1148 close_sep(struct servtab *sep)
   1149 {
   1150 	if (sep->se_fd >= 0) {
   1151 		(void) close(sep->se_fd);
   1152 		sep->se_fd = -1;
   1153 	}
   1154 	sep->se_count = 0;
   1155 }
   1156 
   1157 static void
   1158 register_rpc(struct servtab *sep)
   1159 {
   1160 #ifdef RPC
   1161 	int n;
   1162 	struct netbuf nbuf;
   1163 	struct sockaddr_storage ss;
   1164 	struct netconfig *nconf;
   1165 
   1166 	if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
   1167 		syslog(LOG_ERR, "%s: getnetconfigent failed",
   1168 		    sep->se_proto);
   1169 		return;
   1170 	}
   1171 	n = sizeof ss;
   1172 	if (getsockname(sep->se_fd, (struct sockaddr *)&ss, &n) < 0) {
   1173 		syslog(LOG_ERR, "%s/%s: getsockname: %m",
   1174 		    sep->se_service, sep->se_proto);
   1175 		return;
   1176 	}
   1177 
   1178 	nbuf.buf = &ss;
   1179 	nbuf.len = ss.ss_len;
   1180 	nbuf.maxlen = sizeof (struct sockaddr_storage);
   1181 	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
   1182 		if (debug)
   1183 			fprintf(stderr, "rpcb_set: %u %d %s %s\n",
   1184 			    sep->se_rpcprog, n, nconf->nc_netid,
   1185 			    taddr2uaddr(nconf, &nbuf));
   1186 		(void)rpcb_unset(sep->se_rpcprog, n, nconf);
   1187 		if (!rpcb_set(sep->se_rpcprog, n, nconf, &nbuf))
   1188 			syslog(LOG_ERR, "rpcb_set: %u %d %s %s%s",
   1189 			    sep->se_rpcprog, n, nconf->nc_netid,
   1190 			    taddr2uaddr(nconf, &nbuf), clnt_spcreateerror(""));
   1191 	}
   1192 #endif /* RPC */
   1193 }
   1194 
   1195 static void
   1196 unregister_rpc(struct servtab *sep)
   1197 {
   1198 #ifdef RPC
   1199 	int n;
   1200 	struct netconfig *nconf;
   1201 
   1202 	if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
   1203 		syslog(LOG_ERR, "%s: getnetconfigent failed",
   1204 		    sep->se_proto);
   1205 		return;
   1206 	}
   1207 
   1208 	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
   1209 		if (debug)
   1210 			fprintf(stderr, "rpcb_unset(%u, %d, %s)\n",
   1211 			    sep->se_rpcprog, n, nconf->nc_netid);
   1212 		if (!rpcb_unset(sep->se_rpcprog, n, nconf))
   1213 			syslog(LOG_ERR, "rpcb_unset(%u, %d, %s) failed\n",
   1214 			    sep->se_rpcprog, n, nconf->nc_netid);
   1215 	}
   1216 #endif /* RPC */
   1217 }
   1218 
   1219 
   1220 static struct servtab *
   1221 enter(struct servtab *cp)
   1222 {
   1223 	struct servtab *sep;
   1224 	long omask;
   1225 
   1226 	sep = (struct servtab *)malloc(sizeof (*sep));
   1227 	if (sep == NULL) {
   1228 		syslog(LOG_ERR, "Out of memory.");
   1229 		exit(1);
   1230 	}
   1231 	*sep = *cp;
   1232 	sep->se_fd = -1;
   1233 	sep->se_rpcprog = -1;
   1234 	omask = sigblock(SIGBLOCK);
   1235 	sep->se_next = servtab;
   1236 	servtab = sep;
   1237 	sigsetmask(omask);
   1238 	return (sep);
   1239 }
   1240 
   1241 FILE	*fconfig = NULL;
   1242 struct	servtab serv;
   1243 char	line[LINE_MAX];
   1244 char    *defhost;
   1245 #ifdef IPSEC
   1246 static char *policy = NULL;
   1247 #endif
   1248 
   1249 static int
   1250 setconfig(void)
   1251 {
   1252 	if (defhost)
   1253 		free(defhost);
   1254 	defhost = newstr("*");
   1255 #ifdef IPSEC
   1256 	if (policy)
   1257 		free(policy);
   1258 	policy = NULL;
   1259 #endif
   1260 	if (fconfig != NULL) {
   1261 		fseek(fconfig, 0L, SEEK_SET);
   1262 		return (1);
   1263 	}
   1264 	fconfig = fopen(CONFIG, "r");
   1265 	return (fconfig != NULL);
   1266 }
   1267 
   1268 static void
   1269 endconfig(void)
   1270 {
   1271 	if (fconfig != NULL) {
   1272 		(void) fclose(fconfig);
   1273 		fconfig = NULL;
   1274 	}
   1275 	if (defhost != NULL) {
   1276 		free(defhost);
   1277 		defhost = NULL;
   1278 	}
   1279 }
   1280 
   1281 static struct servtab *
   1282 getconfigent(void)
   1283 {
   1284 	struct servtab *sep = &serv;
   1285 	int argc, val;
   1286 	char *cp, *cp0, *arg, *buf0, *buf1, *sz0, *sz1;
   1287 	static char TCPMUX_TOKEN[] = "tcpmux/";
   1288 #define MUX_LEN		(sizeof(TCPMUX_TOKEN)-1)
   1289 	char *hostdelim;
   1290 
   1291 more:
   1292 	while ((cp = nextline(fconfig))) {
   1293 #ifdef IPSEC
   1294 		/* lines starting with #@ is not a comment, but the policy */
   1295 		if (cp[0] == '#' && cp[1] == '@') {
   1296 			char *p;
   1297 			for (p = cp + 2; p && *p && isspace(*p); p++)
   1298 				;
   1299 			if (*p == '\0') {
   1300 				if (policy)
   1301 					free(policy);
   1302 				policy = NULL;
   1303 			} else {
   1304 				if (ipsecsetup_test(p) < 0) {
   1305 					syslog(LOG_ERR,
   1306 						"%s: invalid ipsec policy \"%s\"",
   1307 						CONFIG, p);
   1308 					exit(1);
   1309 				} else {
   1310 					if (policy)
   1311 						free(policy);
   1312 					policy = newstr(p);
   1313 				}
   1314 			}
   1315 		}
   1316 #endif
   1317 		if (*cp == '#' || *cp == '\0')
   1318 			continue;
   1319 #ifdef MULOG
   1320 		/* Avoid use of `skip' if there is a danger of it looking
   1321 		 * at continuation lines.
   1322 		 */
   1323 		do {
   1324 			cp++;
   1325 		} while (*cp == ' ' || *cp == '\t');
   1326 		if (*cp == '\0')
   1327 			continue;
   1328 		if ((arg = skip(&cp)) == NULL)
   1329 			continue;
   1330 		if (strcmp(arg, "DOMAIN"))
   1331 			continue;
   1332 		if (curdom)
   1333 			free(curdom);
   1334 		curdom = NULL;
   1335 		while (*cp == ' ' || *cp == '\t')
   1336 			cp++;
   1337 		if (*cp == '\0')
   1338 			continue;
   1339 		arg = cp;
   1340 		while (*cp && *cp != ' ' && *cp != '\t')
   1341 			cp++;
   1342 		if (*cp != '\0')
   1343 			*cp++ = '\0';
   1344 		curdom = newstr(arg);
   1345 #endif
   1346 		break;
   1347 	}
   1348 	if (cp == NULL)
   1349 		return (NULL);
   1350 	/*
   1351 	 * clear the static buffer, since some fields (se_ctrladdr,
   1352 	 * for example) don't get initialized here.
   1353 	 */
   1354 	memset((caddr_t)sep, 0, sizeof *sep);
   1355 	arg = skip(&cp);
   1356 	if (cp == NULL) {
   1357 		/* got an empty line containing just blanks/tabs. */
   1358 		goto more;
   1359 	}
   1360 	/* Check for a host name. */
   1361 	hostdelim = strrchr(arg, ':');
   1362 	if (hostdelim) {
   1363 		*hostdelim = '\0';
   1364 		if (arg[0] == '[' && hostdelim > arg && hostdelim[-1] == ']') {
   1365 			hostdelim[-1] = '\0';
   1366 			sep->se_hostaddr = newstr(arg + 1);
   1367 		} else
   1368 			sep->se_hostaddr = newstr(arg);
   1369 		arg = hostdelim + 1;
   1370 		/*
   1371 		 * If the line is of the form `host:', then just change the
   1372 		 * default host for the following lines.
   1373 		 */
   1374 		if (*arg == '\0') {
   1375 			arg = skip(&cp);
   1376 			if (cp == NULL) {
   1377 				free(defhost);
   1378 				defhost = sep->se_hostaddr;
   1379 				goto more;
   1380 			}
   1381 		}
   1382 	} else
   1383 		sep->se_hostaddr = newstr(defhost);
   1384 	if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
   1385 		char *c = arg + MUX_LEN;
   1386 		if (*c == '+') {
   1387 			sep->se_type = MUXPLUS_TYPE;
   1388 			c++;
   1389 		} else
   1390 			sep->se_type = MUX_TYPE;
   1391 		sep->se_service = newstr(c);
   1392 	} else {
   1393 		sep->se_service = newstr(arg);
   1394 		sep->se_type = NORM_TYPE;
   1395 	}
   1396 
   1397 	arg = sskip(&cp);
   1398 	if (strcmp(arg, "stream") == 0)
   1399 		sep->se_socktype = SOCK_STREAM;
   1400 	else if (strcmp(arg, "dgram") == 0)
   1401 		sep->se_socktype = SOCK_DGRAM;
   1402 	else if (strcmp(arg, "rdm") == 0)
   1403 		sep->se_socktype = SOCK_RDM;
   1404 	else if (strcmp(arg, "seqpacket") == 0)
   1405 		sep->se_socktype = SOCK_SEQPACKET;
   1406 	else if (strcmp(arg, "raw") == 0)
   1407 		sep->se_socktype = SOCK_RAW;
   1408 	else
   1409 		sep->se_socktype = -1;
   1410 
   1411 	arg = sskip(&cp);
   1412 	if (sep->se_type == NORM_TYPE &&
   1413 	    strncmp(arg, "faith/", strlen("faith/")) == 0) {
   1414 		arg += strlen("faith/");
   1415 		sep->se_type = FAITH_TYPE;
   1416 	}
   1417 	sep->se_proto = newstr(arg);
   1418 
   1419 #define	MALFORMED(arg) \
   1420 do { \
   1421 	syslog(LOG_ERR, "%s: malformed buffer size option `%s'", \
   1422 	    sep->se_service, (arg)); \
   1423 	goto more; \
   1424 } while (0)
   1425 
   1426 #define	GETVAL(arg) \
   1427 do { \
   1428 	if (!isdigit(*(arg))) \
   1429 		MALFORMED(arg); \
   1430 	val = strtol((arg), &cp0, 10); \
   1431 	if (cp0 != NULL) { \
   1432 		if (cp0[1] != '\0') \
   1433 			MALFORMED((arg)); \
   1434 		if (cp0[0] == 'k') \
   1435 			val *= 1024; \
   1436 		if (cp0[0] == 'm') \
   1437 			val *= 1024 * 1024; \
   1438 	} \
   1439 	if (val < 1) { \
   1440 		syslog(LOG_ERR, "%s: invalid buffer size `%s'", \
   1441 		    sep->se_service, (arg)); \
   1442 		goto more; \
   1443 	} \
   1444 } while (0)
   1445 
   1446 #define	ASSIGN(arg) \
   1447 do { \
   1448 	if (strcmp((arg), "sndbuf") == 0) \
   1449 		sep->se_sndbuf = val; \
   1450 	else if (strcmp((arg), "rcvbuf") == 0) \
   1451 		sep->se_rcvbuf = val; \
   1452 	else \
   1453 		MALFORMED((arg)); \
   1454 } while (0)
   1455 
   1456 	/*
   1457 	 * Extract the send and receive buffer sizes before parsing
   1458 	 * the protocol.
   1459 	 */
   1460 	sep->se_sndbuf = sep->se_rcvbuf = 0;
   1461 	buf0 = buf1 = sz0 = sz1 = NULL;
   1462 	if ((buf0 = strchr(sep->se_proto, ',')) != NULL) {
   1463 		/* Not meaningful for Tcpmux services. */
   1464 		if (ISMUX(sep)) {
   1465 			syslog(LOG_ERR, "%s: can't specify buffer sizes for "
   1466 			    "tcpmux services", sep->se_service);
   1467 			goto more;
   1468 		}
   1469 
   1470 		/* Skip the , */
   1471 		*buf0++ = '\0';
   1472 
   1473 		/* Check to see if another socket buffer size was specified. */
   1474 		if ((buf1 = strchr(buf0, ',')) != NULL) {
   1475 			/* Skip the , */
   1476 			*buf1++ = '\0';
   1477 
   1478 			/* Make sure a 3rd one wasn't specified. */
   1479 			if (strchr(buf1, ',') != NULL) {
   1480 				syslog(LOG_ERR, "%s: too many buffer sizes",
   1481 				    sep->se_service);
   1482 				goto more;
   1483 			}
   1484 
   1485 			/* Locate the size. */
   1486 			if ((sz1 = strchr(buf1, '=')) == NULL)
   1487 				MALFORMED(buf1);
   1488 
   1489 			/* Skip the = */
   1490 			*sz1++ = '\0';
   1491 		}
   1492 
   1493 		/* Locate the size. */
   1494 		if ((sz0 = strchr(buf0, '=')) == NULL)
   1495 			MALFORMED(buf0);
   1496 
   1497 		/* Skip the = */
   1498 		*sz0++ = '\0';
   1499 
   1500 		GETVAL(sz0);
   1501 		ASSIGN(buf0);
   1502 
   1503 		if (buf1 != NULL) {
   1504 			GETVAL(sz1);
   1505 			ASSIGN(buf1);
   1506 		}
   1507 	}
   1508 
   1509 #undef ASSIGN
   1510 #undef GETVAL
   1511 #undef MALFORMED
   1512 
   1513 	if (strcmp(sep->se_proto, "unix") == 0) {
   1514 		sep->se_family = AF_LOCAL;
   1515 	} else {
   1516 		val = strlen(sep->se_proto);
   1517 		if (!val) {
   1518 			syslog(LOG_ERR, "%s: invalid protocol specified",
   1519 			    sep->se_service);
   1520 			goto more;
   1521 		}
   1522 		val = sep->se_proto[val - 1];
   1523 		switch (val) {
   1524 		case '4':	/*tcp4 or udp4*/
   1525 			sep->se_family = AF_INET;
   1526 			break;
   1527 #ifdef INET6
   1528 		case '6':	/*tcp6 or udp6*/
   1529 			sep->se_family = AF_INET6;
   1530 			break;
   1531 #endif
   1532 		default:
   1533 			sep->se_family = AF_INET;	/*will become AF_INET6*/
   1534 			break;
   1535 		}
   1536 		if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
   1537 #ifdef RPC
   1538 			char *cp, *ccp;
   1539 			cp = strchr(sep->se_service, '/');
   1540 			if (cp == 0) {
   1541 				syslog(LOG_ERR, "%s: no rpc version",
   1542 				    sep->se_service);
   1543 				goto more;
   1544 			}
   1545 			*cp++ = '\0';
   1546 			sep->se_rpcversl = sep->se_rpcversh =
   1547 			    strtol(cp, &ccp, 0);
   1548 			if (ccp == cp) {
   1549 		badafterall:
   1550 				syslog(LOG_ERR, "%s/%s: bad rpc version",
   1551 				    sep->se_service, cp);
   1552 				goto more;
   1553 			}
   1554 			if (*ccp == '-') {
   1555 				cp = ccp + 1;
   1556 				sep->se_rpcversh = strtol(cp, &ccp, 0);
   1557 				if (ccp == cp)
   1558 					goto badafterall;
   1559 			}
   1560 #else
   1561 			syslog(LOG_ERR, "%s: rpc services not suported",
   1562 			    sep->se_service);
   1563 			goto more;
   1564 #endif /* RPC */
   1565 		}
   1566 	}
   1567 	arg = sskip(&cp);
   1568 	{
   1569 		char *cp;
   1570 		if ((cp = strchr(arg, ':')) == NULL)
   1571 			cp = strchr(arg, '.');
   1572 		if (cp != NULL) {
   1573 			*cp++ = '\0';
   1574 			sep->se_max = atoi(cp);
   1575 		} else
   1576 			sep->se_max = TOOMANY;
   1577 	}
   1578 	sep->se_wait = strcmp(arg, "wait") == 0;
   1579 	if (ISMUX(sep)) {
   1580 		/*
   1581 		 * Silently enforce "nowait" for TCPMUX services since
   1582 		 * they don't have an assigned port to listen on.
   1583 		 */
   1584 		sep->se_wait = 0;
   1585 
   1586 		if (strncmp(sep->se_proto, "tcp", 3)) {
   1587 			syslog(LOG_ERR,
   1588 			    "%s: bad protocol for tcpmux service %s",
   1589 			    CONFIG, sep->se_service);
   1590 			goto more;
   1591 		}
   1592 		if (sep->se_socktype != SOCK_STREAM) {
   1593 			syslog(LOG_ERR,
   1594 			    "%s: bad socket type for tcpmux service %s",
   1595 			    CONFIG, sep->se_service);
   1596 			goto more;
   1597 		}
   1598 	}
   1599 	sep->se_user = newstr(sskip(&cp));
   1600 	if ((sep->se_group = strchr(sep->se_user, ':')) != NULL)
   1601 		*sep->se_group++ = '\0';
   1602 	else if ((sep->se_group = strchr(sep->se_user, '.')) != NULL)
   1603 		*sep->se_group++ = '\0';
   1604 
   1605 	sep->se_server = newstr(sskip(&cp));
   1606 	if (strcmp(sep->se_server, "internal") == 0) {
   1607 		struct biltin *bi;
   1608 
   1609 		for (bi = biltins; bi->bi_service; bi++)
   1610 			if (bi->bi_socktype == sep->se_socktype &&
   1611 			    strcmp(bi->bi_service, sep->se_service) == 0)
   1612 				break;
   1613 		if (bi->bi_service == 0) {
   1614 			syslog(LOG_ERR, "internal service %s unknown",
   1615 			    sep->se_service);
   1616 			goto more;
   1617 		}
   1618 		sep->se_bi = bi;
   1619 		sep->se_wait = bi->bi_wait;
   1620 	} else
   1621 		sep->se_bi = NULL;
   1622 	argc = 0;
   1623 	for (arg = skip(&cp); cp; arg = skip(&cp)) {
   1624 #if MULOG
   1625 		char *colon;
   1626 
   1627 		if (argc == 0 && (colon = strrchr(arg, ':'))) {
   1628 			while (arg < colon) {
   1629 				int	x;
   1630 				char	*ccp;
   1631 
   1632 				switch (*arg++) {
   1633 				case 'l':
   1634 					x = 1;
   1635 					if (isdigit(*arg)) {
   1636 						x = strtol(arg, &ccp, 0);
   1637 						if (ccp == arg)
   1638 							break;
   1639 						arg = ccp;
   1640 					}
   1641 					sep->se_log &= ~MULOG_RFC931;
   1642 					sep->se_log |= x;
   1643 					break;
   1644 				case 'a':
   1645 					sep->se_log |= MULOG_RFC931;
   1646 					break;
   1647 				default:
   1648 					break;
   1649 				}
   1650 			}
   1651 			arg = colon + 1;
   1652 		}
   1653 #endif
   1654 		if (argc < MAXARGV)
   1655 			sep->se_argv[argc++] = newstr(arg);
   1656 	}
   1657 	while (argc <= MAXARGV)
   1658 		sep->se_argv[argc++] = NULL;
   1659 #ifdef IPSEC
   1660 	sep->se_policy = policy ? newstr(policy) : NULL;
   1661 #endif
   1662 	return (sep);
   1663 }
   1664 
   1665 static void
   1666 freeconfig(struct servtab *cp)
   1667 {
   1668 	int i;
   1669 
   1670 	if (cp->se_hostaddr)
   1671 		free(cp->se_hostaddr);
   1672 	if (cp->se_service)
   1673 		free(cp->se_service);
   1674 	if (cp->se_proto)
   1675 		free(cp->se_proto);
   1676 	if (cp->se_user)
   1677 		free(cp->se_user);
   1678 	/* Note: se_group is part of the newstr'ed se_user */
   1679 	if (cp->se_server)
   1680 		free(cp->se_server);
   1681 	for (i = 0; i < MAXARGV; i++)
   1682 		if (cp->se_argv[i])
   1683 			free(cp->se_argv[i]);
   1684 #ifdef IPSEC
   1685 	if (cp->se_policy)
   1686 		free(cp->se_policy);
   1687 #endif
   1688 }
   1689 
   1690 
   1691 /*
   1692  * Safe skip - if skip returns null, log a syntax error in the
   1693  * configuration file and exit.
   1694  */
   1695 static char *
   1696 sskip(char **cpp)
   1697 {
   1698 	char *cp;
   1699 
   1700 	cp = skip(cpp);
   1701 	if (cp == NULL) {
   1702 		syslog(LOG_ERR, "%s: syntax error", CONFIG);
   1703 		exit(1);
   1704 	}
   1705 	return (cp);
   1706 }
   1707 
   1708 static char *
   1709 skip(char **cpp)
   1710 {
   1711 	char *cp = *cpp;
   1712 	char *start;
   1713 
   1714 	if (*cpp == NULL)
   1715 		return (NULL);
   1716 
   1717 again:
   1718 	while (*cp == ' ' || *cp == '\t')
   1719 		cp++;
   1720 	if (*cp == '\0') {
   1721 		int c;
   1722 
   1723 		c = getc(fconfig);
   1724 		(void) ungetc(c, fconfig);
   1725 		if (c == ' ' || c == '\t')
   1726 			if ((cp = nextline(fconfig)))
   1727 				goto again;
   1728 		*cpp = NULL;
   1729 		return (NULL);
   1730 	}
   1731 	start = cp;
   1732 	while (*cp && *cp != ' ' && *cp != '\t')
   1733 		cp++;
   1734 	if (*cp != '\0')
   1735 		*cp++ = '\0';
   1736 	*cpp = cp;
   1737 	return (start);
   1738 }
   1739 
   1740 static char *
   1741 nextline(FILE *fd)
   1742 {
   1743 	char *cp;
   1744 
   1745 	if (fgets(line, sizeof (line), fd) == NULL)
   1746 		return (NULL);
   1747 	cp = strchr(line, '\n');
   1748 	if (cp)
   1749 		*cp = '\0';
   1750 	return (line);
   1751 }
   1752 
   1753 static char *
   1754 newstr(char *cp)
   1755 {
   1756 	if ((cp = strdup((cp !=NULL )? cp : "")) != NULL)
   1757 		return (cp);
   1758 	syslog(LOG_ERR, "strdup: %m");
   1759 	exit(1);
   1760 }
   1761 
   1762 static void
   1763 inetd_setproctitle(char *a, int s)
   1764 {
   1765 	socklen_t size;
   1766 	struct sockaddr_storage ss;
   1767 	char hbuf[NI_MAXHOST];
   1768 
   1769 	size = sizeof(ss);
   1770 	if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
   1771 		if (getnameinfo((struct sockaddr *)&ss, size, hbuf,
   1772 		    sizeof(hbuf), NULL, 0, niflags) == 0)
   1773 			setproctitle("-%s [%s]", a, hbuf);
   1774 		else
   1775 			setproctitle("-%s [?]", a);
   1776 	} else
   1777 		setproctitle("-%s", a);
   1778 }
   1779 
   1780 static void
   1781 bump_nofile(void)
   1782 {
   1783 #ifdef RLIMIT_NOFILE
   1784 
   1785 #define FD_CHUNK	32
   1786 
   1787 	struct rlimit rl;
   1788 
   1789 	if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
   1790 		syslog(LOG_ERR, "getrlimit: %m");
   1791 		return;
   1792 	}
   1793 	rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
   1794 	if (rl.rlim_cur <= rlim_ofile_cur) {
   1795 		syslog(LOG_ERR,
   1796 		    "bump_nofile: cannot extend file limit, max = %d",
   1797 		    (int)rl.rlim_cur);
   1798 		return;
   1799 	}
   1800 
   1801 	if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
   1802 		syslog(LOG_ERR, "setrlimit: %m");
   1803 		return;
   1804 	}
   1805 
   1806 	rlim_ofile_cur = rl.rlim_cur;
   1807 	return;
   1808 
   1809 #else
   1810 	syslog(LOG_ERR, "bump_nofile: cannot extend file limit");
   1811 	return;
   1812 #endif
   1813 }
   1814 
   1815 /*
   1816  * Internet services provided internally by inetd:
   1817  */
   1818 #define	BUFSIZE	4096
   1819 
   1820 /* ARGSUSED */
   1821 static void
   1822 echo_stream(int s, struct servtab *sep)	/* Echo service -- echo data back */
   1823 {
   1824 	char buffer[BUFSIZE];
   1825 	int i;
   1826 
   1827 	inetd_setproctitle(sep->se_service, s);
   1828 	while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
   1829 	    write(s, buffer, i) > 0)
   1830 		;
   1831 }
   1832 
   1833 /* ARGSUSED */
   1834 static void
   1835 echo_dg(int s, struct servtab *sep)	/* Echo service -- echo data back */
   1836 {
   1837 	char buffer[BUFSIZE];
   1838 	int i;
   1839 	socklen_t size;
   1840 	struct sockaddr_storage ss;
   1841 	struct sockaddr *sa;
   1842 
   1843 	sa = (struct sockaddr *)&ss;
   1844 	size = sizeof(ss);
   1845 	if ((i = recvfrom(s, buffer, sizeof(buffer), 0, sa, &size)) < 0)
   1846 		return;
   1847 	if (port_good_dg(sa))
   1848 		(void) sendto(s, buffer, i, 0, sa, size);
   1849 }
   1850 
   1851 /* ARGSUSED */
   1852 static void
   1853 discard_stream(int s, struct servtab *sep) /* Discard service -- ignore data */
   1854 {
   1855 	char buffer[BUFSIZE];
   1856 
   1857 	inetd_setproctitle(sep->se_service, s);
   1858 	while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
   1859 			errno == EINTR)
   1860 		;
   1861 }
   1862 
   1863 /* ARGSUSED */
   1864 static void
   1865 discard_dg(int s, struct servtab *sep)	/* Discard service -- ignore data */
   1866 
   1867 {
   1868 	char buffer[BUFSIZE];
   1869 
   1870 	(void) read(s, buffer, sizeof(buffer));
   1871 }
   1872 
   1873 #include <ctype.h>
   1874 #define LINESIZ 72
   1875 char ring[128];
   1876 char *endring;
   1877 
   1878 static void
   1879 initring(void)
   1880 {
   1881 	int i;
   1882 
   1883 	endring = ring;
   1884 
   1885 	for (i = 0; i <= 128; ++i)
   1886 		if (isprint(i))
   1887 			*endring++ = i;
   1888 }
   1889 
   1890 /* ARGSUSED */
   1891 static void
   1892 chargen_stream(int s,struct servtab *sep)	/* Character generator */
   1893 {
   1894 	int len;
   1895 	char *rs, text[LINESIZ+2];
   1896 
   1897 	inetd_setproctitle(sep->se_service, s);
   1898 
   1899 	if (!endring) {
   1900 		initring();
   1901 		rs = ring;
   1902 	}
   1903 
   1904 	text[LINESIZ] = '\r';
   1905 	text[LINESIZ + 1] = '\n';
   1906 	for (rs = ring;;) {
   1907 		if ((len = endring - rs) >= LINESIZ)
   1908 			memmove(text, rs, LINESIZ);
   1909 		else {
   1910 			memmove(text, rs, len);
   1911 			memmove(text + len, ring, LINESIZ - len);
   1912 		}
   1913 		if (++rs == endring)
   1914 			rs = ring;
   1915 		if (write(s, text, sizeof(text)) != sizeof(text))
   1916 			break;
   1917 	}
   1918 }
   1919 
   1920 /* ARGSUSED */
   1921 static void
   1922 chargen_dg(int s, struct servtab *sep)		/* Character generator */
   1923 {
   1924 	struct sockaddr_storage ss;
   1925 	struct sockaddr *sa;
   1926 	static char *rs;
   1927 	int len;
   1928 	socklen_t size;
   1929 	char text[LINESIZ+2];
   1930 
   1931 	if (endring == 0) {
   1932 		initring();
   1933 		rs = ring;
   1934 	}
   1935 
   1936 	sa = (struct sockaddr *)&ss;
   1937 	size = sizeof(ss);
   1938 	if (recvfrom(s, text, sizeof(text), 0, sa, &size) < 0)
   1939 		return;
   1940 
   1941 	if (!port_good_dg(sa))
   1942 		return;
   1943 
   1944 	if ((len = endring - rs) >= LINESIZ)
   1945 		memmove(text, rs, LINESIZ);
   1946 	else {
   1947 		memmove(text, rs, len);
   1948 		memmove(text + len, ring, LINESIZ - len);
   1949 	}
   1950 	if (++rs == endring)
   1951 		rs = ring;
   1952 	text[LINESIZ] = '\r';
   1953 	text[LINESIZ + 1] = '\n';
   1954 	(void) sendto(s, text, sizeof(text), 0, sa, size);
   1955 }
   1956 
   1957 /*
   1958  * Return a machine readable date and time, in the form of the
   1959  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
   1960  * returns the number of seconds since midnight, Jan 1, 1970,
   1961  * we must add 2208988800 seconds to this figure to make up for
   1962  * some seventy years Bell Labs was asleep.
   1963  */
   1964 
   1965 static uint32_t
   1966 machtime(void)
   1967 {
   1968 	struct timeval tv;
   1969 
   1970 	if (gettimeofday(&tv, NULL) < 0) {
   1971 		if (debug)
   1972 			fprintf(stderr, "Unable to get time of day\n");
   1973 		return (0);
   1974 	}
   1975 #define	OFFSET ((uint32_t)25567 * 24*60*60)
   1976 	return (htonl((uint32_t)(tv.tv_sec + OFFSET)));
   1977 #undef OFFSET
   1978 }
   1979 
   1980 /* ARGSUSED */
   1981 static void
   1982 machtime_stream(int s, struct servtab *sep)
   1983 {
   1984 	uint32_t result;
   1985 
   1986 	result = machtime();
   1987 	(void) write(s, (char *) &result, sizeof(result));
   1988 }
   1989 
   1990 /* ARGSUSED */
   1991 void
   1992 machtime_dg(int s, struct servtab *sep)
   1993 {
   1994 	uint32_t result;
   1995 	struct sockaddr_storage ss;
   1996 	struct sockaddr *sa;
   1997 	socklen_t size;
   1998 
   1999 	sa = (struct sockaddr *)&ss;
   2000 	size = sizeof(ss);
   2001 	if (recvfrom(s, (char *)&result, sizeof(result), 0, sa, &size) < 0)
   2002 		return;
   2003 	if (!port_good_dg(sa))
   2004 		return;
   2005 	result = machtime();
   2006 	(void) sendto(s, (char *) &result, sizeof(result), 0, sa, size);
   2007 }
   2008 
   2009 /* ARGSUSED */
   2010 static void
   2011 daytime_stream(int s,struct servtab *sep)
   2012 /* Return human-readable time of day */
   2013 {
   2014 	char buffer[256];
   2015 	time_t clock;
   2016 	int len;
   2017 
   2018 	clock = time((time_t *) 0);
   2019 
   2020 	len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
   2021 	(void) write(s, buffer, len);
   2022 }
   2023 
   2024 /* ARGSUSED */
   2025 void
   2026 daytime_dg(int s, struct servtab *sep)
   2027 /* Return human-readable time of day */
   2028 {
   2029 	char buffer[256];
   2030 	time_t clock;
   2031 	struct sockaddr_storage ss;
   2032 	struct sockaddr *sa;
   2033 	socklen_t size;
   2034 	int len;
   2035 
   2036 	clock = time((time_t *) 0);
   2037 
   2038 	sa = (struct sockaddr *)&ss;
   2039 	size = sizeof(ss);
   2040 	if (recvfrom(s, buffer, sizeof(buffer), 0, sa, &size) < 0)
   2041 		return;
   2042 	if (!port_good_dg(sa))
   2043 		return;
   2044 	len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
   2045 	(void) sendto(s, buffer, len, 0, sa, size);
   2046 }
   2047 
   2048 /*
   2049  * print_service:
   2050  *	Dump relevant information to stderr
   2051  */
   2052 static void
   2053 print_service(char *action, struct servtab *sep)
   2054 {
   2055 
   2056 	if (isrpcservice(sep))
   2057 		fprintf(stderr,
   2058 		    "%s: %s rpcprog=%d, rpcvers = %d/%d, proto=%s, wait:max=%d.%d, user:group=%s.%s builtin=%lx server=%s"
   2059 #ifdef IPSEC
   2060 		    " policy=\"%s\""
   2061 #endif
   2062 		    "\n",
   2063 		    action, sep->se_service,
   2064 		    sep->se_rpcprog, sep->se_rpcversh, sep->se_rpcversl, sep->se_proto,
   2065 		    sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
   2066 		    (long)sep->se_bi, sep->se_server
   2067 #ifdef IPSEC
   2068 		    , (sep->se_policy ? sep->se_policy : "")
   2069 #endif
   2070 		    );
   2071 	else
   2072 		fprintf(stderr,
   2073 		    "%s: %s proto=%s%s, wait:max=%d.%d, user:group=%s.%s builtin=%lx server=%s"
   2074 #ifdef IPSEC
   2075 		    " policy=%s"
   2076 #endif
   2077 		    "\n",
   2078 		    action, sep->se_service,
   2079 		    sep->se_type == FAITH_TYPE ? "faith/" : "",
   2080 		    sep->se_proto,
   2081 		    sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
   2082 		    (long)sep->se_bi, sep->se_server
   2083 #ifdef IPSEC
   2084 		    , (sep->se_policy ? sep->se_policy : "")
   2085 #endif
   2086 		    );
   2087 }
   2088 
   2089 static void
   2090 usage(void)
   2091 {
   2092 #ifdef LIBWRAP
   2093 	(void)fprintf(stderr, "usage: %s [-dl] [conf]\n", getprogname());
   2094 #else
   2095 	(void)fprintf(stderr, "usage: %s [-d] [conf]\n", getprogname());
   2096 #endif
   2097 	exit(1);
   2098 }
   2099 
   2100 
   2101 /*
   2102  *  Based on TCPMUX.C by Mark K. Lottor November 1988
   2103  *  sri-nic::ps:<mkl>tcpmux.c
   2104  */
   2105 
   2106 static int		/* # of characters upto \r,\n or \0 */
   2107 getline(int fd,	char *buf, int len)
   2108 {
   2109 	int count = 0, n;
   2110 
   2111 	do {
   2112 		n = read(fd, buf, len-count);
   2113 		if (n == 0)
   2114 			return (count);
   2115 		if (n < 0)
   2116 			return (-1);
   2117 		while (--n >= 0) {
   2118 			if (*buf == '\r' || *buf == '\n' || *buf == '\0')
   2119 				return (count);
   2120 			count++;
   2121 			buf++;
   2122 		}
   2123 	} while (count < len);
   2124 	return (count);
   2125 }
   2126 
   2127 #define MAX_SERV_LEN	(256+2)		/* 2 bytes for \r\n */
   2128 
   2129 #define strwrite(fd, buf)	(void) write(fd, buf, sizeof(buf)-1)
   2130 
   2131 static void
   2132 tcpmux(int ctrl, struct servtab *sep)
   2133 {
   2134 	char service[MAX_SERV_LEN+1];
   2135 	int len;
   2136 
   2137 	/* Get requested service name */
   2138 	if ((len = getline(ctrl, service, MAX_SERV_LEN)) < 0) {
   2139 		strwrite(ctrl, "-Error reading service name\r\n");
   2140 		goto reject;
   2141 	}
   2142 	service[len] = '\0';
   2143 
   2144 	if (debug)
   2145 		fprintf(stderr, "tcpmux: someone wants %s\n", service);
   2146 
   2147 	/*
   2148 	 * Help is a required command, and lists available services,
   2149 	 * one per line.
   2150 	 */
   2151 	if (!strcasecmp(service, "help")) {
   2152 		strwrite(ctrl, "+Available services:\r\n");
   2153 		strwrite(ctrl, "help\r\n");
   2154 		for (sep = servtab; sep != NULL; sep = sep->se_next) {
   2155 			if (!ISMUX(sep))
   2156 				continue;
   2157 			(void)write(ctrl, sep->se_service,
   2158 			    strlen(sep->se_service));
   2159 			strwrite(ctrl, "\r\n");
   2160 		}
   2161 		goto reject;
   2162 	}
   2163 
   2164 	/* Try matching a service in inetd.conf with the request */
   2165 	for (sep = servtab; sep != NULL; sep = sep->se_next) {
   2166 		if (!ISMUX(sep))
   2167 			continue;
   2168 		if (!strcasecmp(service, sep->se_service)) {
   2169 			if (ISMUXPLUS(sep))
   2170 				strwrite(ctrl, "+Go\r\n");
   2171 			run_service(ctrl, sep);
   2172 			return;
   2173 		}
   2174 	}
   2175 	strwrite(ctrl, "-Service not available\r\n");
   2176 reject:
   2177 	_exit(1);
   2178 }
   2179 
   2180 #ifdef MULOG
   2181 void
   2182 dolog(struct servtab *sep, int ctrl)
   2183 {
   2184 	struct sockaddr_storage	ss;
   2185 	struct sockaddr		*sa = (struct sockaddr *)&ss;
   2186 	socklen_t		len = sizeof(ss);
   2187 	char			*host, *dp, buf[BUFSIZ];
   2188 	int			connected = 1;
   2189 
   2190 	switch (sep->se_family) {
   2191 	case AF_INET:
   2192 #ifdef INET6
   2193 	case AF_INET6:
   2194 #endif
   2195 		break;
   2196 	default:
   2197 		return;
   2198 	}
   2199 
   2200 	if (getpeername(ctrl, sa, &len) < 0) {
   2201 		if (errno != ENOTCONN) {
   2202 			syslog(LOG_ERR, "getpeername: %m");
   2203 			return;
   2204 		}
   2205 		if (recvfrom(ctrl, buf, sizeof(buf), MSG_PEEK, sa, &len) < 0) {
   2206 			syslog(LOG_ERR, "recvfrom: %m");
   2207 			return;
   2208 		}
   2209 		connected = 0;
   2210 	}
   2211 	switch (sa->sa_family) {
   2212 	case AF_INET:
   2213 #ifdef INET6
   2214 	case AF_INET6:
   2215 #endif
   2216 		break;
   2217 	default:
   2218 		syslog(LOG_ERR, "unexpected address family %u", sa->sa_family);
   2219 		return;
   2220 	}
   2221 
   2222 	if (getnameinfo(sa, len, buf, sizeof(buf), NULL, 0, 0) != 0)
   2223 		strcpy(buf, "?");
   2224 	host = buf;
   2225 
   2226 	switch (sep->se_log & ~MULOG_RFC931) {
   2227 	case 0:
   2228 		return;
   2229 	case 1:
   2230 		if (curdom == NULL || *curdom == '\0')
   2231 			break;
   2232 		dp = host + strlen(host) - strlen(curdom);
   2233 		if (dp < host)
   2234 			break;
   2235 		if (debug)
   2236 			fprintf(stderr, "check \"%s\" against curdom \"%s\"\n",
   2237 			    host, curdom);
   2238 		if (strcasecmp(dp, curdom) == 0)
   2239 			return;
   2240 		break;
   2241 	case 2:
   2242 	default:
   2243 		break;
   2244 	}
   2245 
   2246 	openlog("", LOG_NOWAIT, MULOG);
   2247 
   2248 	if (connected && (sep->se_log & MULOG_RFC931))
   2249 		syslog(LOG_INFO, "%s@%s wants %s",
   2250 		    rfc931_name(sa, ctrl), host, sep->se_service);
   2251 	else
   2252 		syslog(LOG_INFO, "%s wants %s",
   2253 		    host, sep->se_service);
   2254 }
   2255 
   2256 /*
   2257  * From tcp_log by
   2258  *  Wietse Venema, Eindhoven University of Technology, The Netherlands.
   2259  */
   2260 #if 0
   2261 static char sccsid[] = "@(#) rfc931.c 1.3 92/08/31 22:54:46";
   2262 #endif
   2263 
   2264 #include <setjmp.h>
   2265 
   2266 #define	RFC931_PORT	113		/* Semi-well-known port */
   2267 #define	TIMEOUT		4
   2268 #define	TIMEOUT2	10
   2269 
   2270 static jmp_buf timebuf;
   2271 
   2272 /* timeout - handle timeouts */
   2273 
   2274 static void
   2275 timeout(int sig)
   2276 {
   2277 	longjmp(timebuf, sig);
   2278 }
   2279 
   2280 /* rfc931_name - return remote user name */
   2281 
   2282 char *
   2283 rfc931_name(struct sockaddr *there,	/* remote link information */
   2284     int ctrl)
   2285 {
   2286 	struct sockaddr_storage here;	/* local link information */
   2287 	struct sockaddr_storage sin;	/* for talking to RFC931 daemon */
   2288 	socklen_t	length;
   2289 	int		s;
   2290 	unsigned	remote;
   2291 	unsigned	local;
   2292 	static char	user[256];		/* XXX */
   2293 	char		buf[256];
   2294 	char		*cp;
   2295 	char		*result = "USER_UNKNOWN";
   2296 	int		len;
   2297 	u_int16_t	myport, hisport;
   2298 
   2299 	/* Find out local port number of our stdin. */
   2300 
   2301 	length = sizeof(here);
   2302 	if (getsockname(ctrl, (struct sockaddr *) &here, &length) == -1) {
   2303 		syslog(LOG_ERR, "getsockname: %m");
   2304 		return (result);
   2305 	}
   2306 	switch (here.ss_family) {
   2307 	case AF_INET:
   2308 		myport = ((struct sockaddr_in *)&here)->sin_port;
   2309 		break;
   2310 #ifdef INET6
   2311 	case AF_INET6:
   2312 		myport = ((struct sockaddr_in6 *)&here)->sin6_port;
   2313 		break;
   2314 #endif
   2315 	}
   2316 	switch (there->sa_family) {
   2317 	case AF_INET:
   2318 		hisport = ((struct sockaddr_in *)&there)->sin_port;
   2319 		break;
   2320 #ifdef INET6
   2321 	case AF_INET6:
   2322 		hisport = ((struct sockaddr_in6 *)&there)->sin6_port;
   2323 		break;
   2324 #endif
   2325 	}
   2326 	/* Set up timer so we won't get stuck. */
   2327 
   2328 	if ((s = socket(here.ss_family, SOCK_STREAM, 0)) == -1) {
   2329 		syslog(LOG_ERR, "socket: %m");
   2330 		return (result);
   2331 	}
   2332 
   2333 	sin = here;
   2334 	switch (sin.ss_family) {
   2335 	case AF_INET:
   2336 		((struct sockaddr_in *)&sin)->sin_port = htons(0);
   2337 		break;
   2338 #ifdef INET6
   2339 	case AF_INET6:
   2340 		((struct sockaddr_in6 *)&sin)->sin6_port = htons(0);
   2341 		break;
   2342 #endif
   2343 	}
   2344 	if (bind(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
   2345 		syslog(LOG_ERR, "bind: %m");
   2346 		return (result);
   2347 	}
   2348 
   2349 	signal(SIGALRM, timeout);
   2350 	if (setjmp(timebuf)) {
   2351 		close(s);			/* not: fclose(fp) */
   2352 		return (result);
   2353 	}
   2354 	alarm(TIMEOUT);
   2355 
   2356 	/* Connect to the RFC931 daemon. */
   2357 
   2358 	memcpy(&sin, there, there->sa_len);
   2359 	switch (sin.ss_family) {
   2360 	case AF_INET:
   2361 		((struct sockaddr_in *)&sin)->sin_port = htons(RFC931_PORT);
   2362 		break;
   2363 #ifdef INET6
   2364 	case AF_INET6:
   2365 		((struct sockaddr_in6 *)&sin)->sin6_port = htons(RFC931_PORT);
   2366 		break;
   2367 #endif
   2368 	}
   2369 	if (connect(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
   2370 		close(s);
   2371 		alarm(0);
   2372 		return (result);
   2373 	}
   2374 
   2375 	/* Query the RFC 931 server. Would 13-byte writes ever be broken up? */
   2376 	(void)snprintf(buf, sizeof buf, "%u,%u\r\n", ntohs(hisport),
   2377 	    ntohs(myport));
   2378 
   2379 	for (len = 0, cp = buf; len < strlen(buf); ) {
   2380 		int	n;
   2381 
   2382 		if ((n = write(s, cp, strlen(buf) - len)) == -1) {
   2383 			close(s);
   2384 			alarm(0);
   2385 			return (result);
   2386 		}
   2387 		cp += n;
   2388 		len += n;
   2389 	}
   2390 
   2391 	/* Read response */
   2392 	for (cp = buf; cp < buf + sizeof(buf) - 1; ) {
   2393 		char	c;
   2394 		if (read(s, &c, 1) != 1) {
   2395 			close(s);
   2396 			alarm(0);
   2397 			return (result);
   2398 		}
   2399 		if (c == '\n')
   2400 			break;
   2401 		*cp++ = c;
   2402 	}
   2403 	*cp = '\0';
   2404 
   2405 	if (sscanf(buf, "%u , %u : USERID :%*[^:]:%255s", &remote, &local,
   2406 	    user) == 3 && ntohs(hisport) == remote && ntohs(myport) == local) {
   2407 		/* Strip trailing carriage return. */
   2408 		if ((cp = strchr(user, '\r')) != NULL)
   2409 			*cp = 0;
   2410 		result = user;
   2411 	}
   2412 
   2413 	alarm(0);
   2414 	close(s);
   2415 	return (result);
   2416 }
   2417 #endif
   2418 
   2419 /*
   2420  * check if the address/port where send data to is one of the obvious ports
   2421  * that are used for denial of service attacks like two echo ports
   2422  * just echoing data between them
   2423  */
   2424 static int
   2425 port_good_dg(struct sockaddr *sa)
   2426 {
   2427 	struct in_addr in;
   2428 #ifdef INET6
   2429 	struct in6_addr *in6;
   2430 #endif
   2431 	u_int16_t port;
   2432 	int i, bad;
   2433 	char hbuf[NI_MAXHOST];
   2434 
   2435 	bad = 0;
   2436 
   2437 	switch (sa->sa_family) {
   2438 	case AF_INET:
   2439 		in.s_addr = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr);
   2440 		port = ntohs(((struct sockaddr_in *)sa)->sin_port);
   2441 	v4chk:
   2442 		if (IN_MULTICAST(in.s_addr))
   2443 			goto bad;
   2444 		switch ((in.s_addr & 0xff000000) >> 24) {
   2445 		case 0: case 127: case 255:
   2446 			goto bad;
   2447 		}
   2448 		if (dg_broadcast(&in))
   2449 			goto bad;
   2450 		break;
   2451 #ifdef INET6
   2452 	case AF_INET6:
   2453 		in6 = &((struct sockaddr_in6 *)sa)->sin6_addr;
   2454 		port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
   2455 		if (IN6_IS_ADDR_MULTICAST(in6) || IN6_IS_ADDR_UNSPECIFIED(in6))
   2456 			goto bad;
   2457 		if (IN6_IS_ADDR_V4MAPPED(in6) || IN6_IS_ADDR_V4COMPAT(in6)) {
   2458 			memcpy(&in, &in6->s6_addr[12], sizeof(in));
   2459 			in.s_addr = ntohl(in.s_addr);
   2460 			goto v4chk;
   2461 		}
   2462 		break;
   2463 #endif
   2464 	default:
   2465 		/* XXX unsupported af, is it safe to assume it to be safe? */
   2466 		return (1);
   2467 	}
   2468 
   2469 	for (i = 0; bad_ports[i] != 0; i++) {
   2470 		if (port == bad_ports[i])
   2471 			goto bad;
   2472 	}
   2473 
   2474 	return (1);
   2475 
   2476 bad:
   2477 	if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,
   2478 	    niflags) != 0)
   2479 		strcpy(hbuf, "?");
   2480 	syslog(LOG_WARNING,"Possible DoS attack from %s, Port %d",
   2481 		hbuf, port);
   2482 	return (0);
   2483 }
   2484 
   2485 /* XXX need optimization */
   2486 static int
   2487 dg_broadcast(struct in_addr *in)
   2488 {
   2489 	struct ifaddrs *ifa, *ifap;
   2490 	struct sockaddr_in *sin;
   2491 
   2492 	if (getifaddrs(&ifap) < 0)
   2493 		return (0);
   2494 	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
   2495 		if (ifa->ifa_addr->sa_family != AF_INET ||
   2496 		    (ifa->ifa_flags & IFF_BROADCAST) == 0)
   2497 			continue;
   2498 		sin = (struct sockaddr_in *)ifa->ifa_broadaddr;
   2499 		if (sin->sin_addr.s_addr == in->s_addr) {
   2500 			freeifaddrs(ifap);
   2501 			return (1);
   2502 		}
   2503 	}
   2504 	freeifaddrs(ifap);
   2505 	return (0);
   2506 }
   2507 
   2508 static int
   2509 my_kevent(const struct kevent *changelist, size_t nchanges,
   2510     struct kevent *eventlist, size_t nevents)
   2511 {
   2512 	int	result;
   2513 
   2514 	while ((result = kevent(kq, changelist, nchanges, eventlist, nevents,
   2515 	    NULL)) < 0)
   2516 		if (errno != EINTR) {
   2517 			syslog(LOG_ERR, "kevent: %m");
   2518 			exit(EXIT_FAILURE);
   2519 		}
   2520 
   2521 	return (result);
   2522 }
   2523 
   2524 static struct kevent *
   2525 allocchange(void)
   2526 {
   2527 	if (changes == A_CNT(changebuf)) {
   2528 		(void) my_kevent(changebuf, A_CNT(changebuf), NULL, 0);
   2529 		changes = 0;
   2530 	}
   2531 
   2532 	return (&changebuf[changes++]);
   2533 }
   2534