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