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