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