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