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