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