Home | History | Annotate | Line # | Download | only in inetd
inetd.c revision 1.41
      1 /*	$NetBSD: inetd.c,v 1.41 1998/03/21 06:25:37 mycroft 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.41 1998/03/21 06:25:37 mycroft 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 		} else
    499 			ctrl = sep->se_fd;
    500 		(void) sigblock(SIGBLOCK);
    501 		pid = 0;
    502 #ifdef LIBWRAP_INTERNAL
    503 		dofork = 1;
    504 #else
    505 		dofork = (sep->se_bi == 0 || sep->se_bi->bi_fork);
    506 #endif
    507 		if (dofork) {
    508 			if (sep->se_count++ == 0)
    509 			    (void)gettimeofday(&sep->se_time,
    510 			        (struct timezone *)0);
    511 			else if (sep->se_count >= sep->se_max) {
    512 				struct timeval now;
    513 
    514 				(void)gettimeofday(&now, (struct timezone *)0);
    515 				if (now.tv_sec - sep->se_time.tv_sec >
    516 				    CNT_INTVL) {
    517 					sep->se_time = now;
    518 					sep->se_count = 1;
    519 				} else {
    520 					syslog(LOG_ERR,
    521 			"%s/%s server failing (looping), service terminated\n",
    522 					    sep->se_service, sep->se_proto);
    523 					close_sep(sep);
    524 					sigsetmask(0L);
    525 					if (!timingout) {
    526 						timingout = 1;
    527 						alarm(RETRYTIME);
    528 					}
    529 					continue;
    530 				}
    531 			}
    532 			pid = fork();
    533 			if (pid < 0) {
    534 				syslog(LOG_ERR, "fork: %m");
    535 				if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
    536 					close(ctrl);
    537 				sigsetmask(0L);
    538 				sleep(1);
    539 				continue;
    540 			}
    541 			if (pid != 0 && sep->se_wait) {
    542 				sep->se_wait = pid;
    543 				FD_CLR(sep->se_fd, &allsock);
    544 				nsock--;
    545 			}
    546 			if (pid == 0) {
    547 				sv.sv_mask = 0L;
    548 				sv.sv_handler = SIG_DFL;
    549 				sigvec(SIGPIPE, &sv, (struct sigvec *)0);
    550 				if (debug)
    551 					setsid();
    552 			}
    553 		}
    554 		sigsetmask(0L);
    555 		if (pid == 0) {
    556 			run_service(ctrl, sep);
    557 			if (dofork)
    558 				exit(0);
    559 		}
    560 		if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
    561 			close(ctrl);
    562 	    }
    563 	    }
    564 	}
    565 }
    566 
    567 void
    568 run_service(ctrl, sep)
    569 	int ctrl;
    570 	struct servtab *sep;
    571 {
    572 	struct passwd *pwd;
    573 	struct group *grp = NULL;	/* XXX gcc */
    574 	char buf[7];
    575 #ifdef LIBWRAP
    576 	struct request_info req;
    577 	int denied;
    578 	char *service = NULL;	/* XXX gcc */
    579 #endif
    580 
    581 #ifdef LIBWRAP
    582 #ifndef LIBWRAP_INTERNAL
    583 	if (sep->se_bi == 0)
    584 #endif
    585 	if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
    586 		request_init(&req, RQ_DAEMON, sep->se_argv[0] ?
    587 		    sep->se_argv[0] : sep->se_service, RQ_FILE, ctrl, NULL);
    588 		fromhost(&req);
    589 		denied = !hosts_access(&req);
    590 		if (denied || lflag) {
    591 			sp = getservbyport(sep->se_ctrladdr_in.sin_port,
    592 			    sep->se_proto);
    593 			if (sp == NULL) {
    594 				(void)snprintf(buf, sizeof buf, "%d",
    595 				    ntohs(sep->se_ctrladdr_in.sin_port));
    596 				service = buf;
    597 			} else
    598 				service = sp->s_name;
    599 		}
    600 		if (denied) {
    601 			syslog(deny_severity,
    602 			    "refused connection from %.500s, service %s (%s)",
    603 			    eval_client(&req), service, sep->se_proto);
    604 			goto reject;
    605 		}
    606 		if (lflag) {
    607 			syslog(allow_severity,
    608 			    "connection from %.500s, service %s (%s)",
    609 			    eval_client(&req), service, sep->se_proto);
    610 		}
    611 	}
    612 #endif /* LIBWRAP */
    613 
    614 	if (sep->se_bi) {
    615 		(*sep->se_bi->bi_fn)(ctrl, sep);
    616 	} else {
    617 		if ((pwd = getpwnam(sep->se_user)) == NULL) {
    618 			syslog(LOG_ERR, "%s/%s: %s: No such user",
    619 			    sep->se_service, sep->se_proto, sep->se_user);
    620 			goto reject;
    621 		}
    622 		if (sep->se_group &&
    623 		    (grp = getgrnam(sep->se_group)) == NULL) {
    624 			syslog(LOG_ERR, "%s/%s: %s: No such group",
    625 			    sep->se_service, sep->se_proto, sep->se_group);
    626 			goto reject;
    627 		}
    628 		if (pwd->pw_uid) {
    629 			if (sep->se_group)
    630 				pwd->pw_gid = grp->gr_gid;
    631 			if (setgid(pwd->pw_gid) < 0) {
    632 				syslog(LOG_ERR,
    633 				 "%s/%s: can't set gid %d: %m", sep->se_service,
    634 				    sep->se_proto, pwd->pw_gid);
    635 				goto reject;
    636 			}
    637 			(void) initgroups(pwd->pw_name,
    638 			    pwd->pw_gid);
    639 			if (setuid(pwd->pw_uid) < 0) {
    640 				syslog(LOG_ERR,
    641 				 "%s/%s: can't set uid %d: %m", sep->se_service,
    642 				    sep->se_proto, pwd->pw_uid);
    643 				goto reject;
    644 			}
    645 		} else if (sep->se_group) {
    646 			(void) setgid((gid_t)grp->gr_gid);
    647 		}
    648 		if (debug)
    649 			fprintf(stderr, "%d execl %s\n",
    650 			    getpid(), sep->se_server);
    651 #ifdef MULOG
    652 		if (sep->se_log)
    653 			dolog(sep, ctrl);
    654 #endif
    655 		/* Set our control descriptor to not close-on-exec... */
    656 		if (fcntl(ctrl, F_SETFD, 0) < 0)
    657 			syslog(LOG_ERR, "fcntl (F_SETFD, 0): %m");
    658 		/* ...and dup it to stdin, stdout, and stderr. */
    659 		if (ctrl != 0) {
    660 			dup2(ctrl, 0);
    661 			close(ctrl);
    662 			ctrl = 0;
    663 		}
    664 		dup2(0, 1);
    665 		dup2(0, 2);
    666 #ifdef RLIMIT_NOFILE
    667 		if (rlim_ofile.rlim_cur != rlim_ofile_cur &&
    668 		    setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
    669 			syslog(LOG_ERR, "setrlimit: %m");
    670 #endif
    671 		execv(sep->se_server, sep->se_argv);
    672 		syslog(LOG_ERR, "cannot execute %s: %m", sep->se_server);
    673 	reject:
    674 		if (sep->se_socktype != SOCK_STREAM)
    675 			recv(ctrl, buf, sizeof (buf), 0);
    676 		_exit(1);
    677 	}
    678 }
    679 
    680 void
    681 reapchild(signo)
    682 	int signo;
    683 {
    684 	int status;
    685 	pid_t pid;
    686 	struct servtab *sep;
    687 
    688 	for (;;) {
    689 		pid = wait3(&status, WNOHANG, (struct rusage *)0);
    690 		if (pid <= 0)
    691 			break;
    692 		if (debug)
    693 			fprintf(stderr, "%d reaped, status %#x\n",
    694 			    pid, status);
    695 		for (sep = servtab; sep; sep = sep->se_next)
    696 			if (sep->se_wait == pid) {
    697 				if (WIFEXITED(status) && WEXITSTATUS(status))
    698 					syslog(LOG_WARNING,
    699 					    "%s: exit status 0x%x",
    700 					    sep->se_server, WEXITSTATUS(status));
    701 				else if (WIFSIGNALED(status))
    702 					syslog(LOG_WARNING,
    703 					    "%s: exit signal 0x%x",
    704 					    sep->se_server, WTERMSIG(status));
    705 				sep->se_wait = 1;
    706 				FD_SET(sep->se_fd, &allsock);
    707 				nsock++;
    708 				if (debug)
    709 					fprintf(stderr, "restored %s, fd %d\n",
    710 					    sep->se_service, sep->se_fd);
    711 			}
    712 	}
    713 }
    714 
    715 void
    716 config(signo)
    717 	int signo;
    718 {
    719 	struct servtab *sep, *cp, **sepp;
    720 	long omask;
    721 	int n;
    722 
    723 	if (!setconfig()) {
    724 		syslog(LOG_ERR, "%s: %m", CONFIG);
    725 		return;
    726 	}
    727 	for (sep = servtab; sep; sep = sep->se_next)
    728 		sep->se_checked = 0;
    729 	while ((cp = getconfigent())) {
    730 		for (sep = servtab; sep; sep = sep->se_next)
    731 			if (strcmp(sep->se_service, cp->se_service) == 0 &&
    732 			    strcmp(sep->se_hostaddr, cp->se_hostaddr) == 0 &&
    733 			    strcmp(sep->se_proto, cp->se_proto) == 0 &&
    734 			    ISMUX(sep) == ISMUX(cp))
    735 				break;
    736 		if (sep != 0) {
    737 			int i;
    738 
    739 #define SWAP(type, a, b) {type c=(type)a; (type)a=(type)b; (type)b=(type)c;}
    740 
    741 			omask = sigblock(SIGBLOCK);
    742 			/*
    743 			 * sep->se_wait may be holding the pid of a daemon
    744 			 * that we're waiting for.  If so, don't overwrite
    745 			 * it unless the config file explicitly says don't
    746 			 * wait.
    747 			 */
    748 			if (cp->se_bi == 0 &&
    749 			    (sep->se_wait == 1 || cp->se_wait == 0))
    750 				sep->se_wait = cp->se_wait;
    751 			SWAP(char *, sep->se_user, cp->se_user);
    752 			SWAP(char *, sep->se_group, cp->se_group);
    753 			SWAP(char *, sep->se_server, cp->se_server);
    754 			for (i = 0; i < MAXARGV; i++)
    755 				SWAP(char *, sep->se_argv[i], cp->se_argv[i]);
    756 			SWAP(int, cp->se_type, sep->se_type);
    757 			SWAP(int, cp->se_max, sep->se_max);
    758 #undef SWAP
    759 			if (isrpcservice(sep))
    760 				unregister_rpc(sep);
    761 			sep->se_rpcversl = cp->se_rpcversl;
    762 			sep->se_rpcversh = cp->se_rpcversh;
    763 			sigsetmask(omask);
    764 			freeconfig(cp);
    765 			if (debug)
    766 				print_service("REDO", sep);
    767 		} else {
    768 			sep = enter(cp);
    769 			if (debug)
    770 				print_service("ADD ", sep);
    771 		}
    772 		sep->se_checked = 1;
    773 
    774 		switch (sep->se_family) {
    775 		case AF_UNIX:
    776 			if (sep->se_fd != -1)
    777 				break;
    778 			n = strlen(sep->se_service);
    779 			if (n > sizeof(sep->se_ctrladdr_un.sun_path)) {
    780 				syslog(LOG_ERR, "%s: address too long",
    781 				    sep->se_service);
    782 				sep->se_checked = 0;
    783 				continue;
    784 			}
    785 			(void)unlink(sep->se_service);
    786 			strncpy(sep->se_ctrladdr_un.sun_path,
    787 			    sep->se_service, n);
    788 			sep->se_ctrladdr_un.sun_family = AF_UNIX;
    789 			sep->se_ctrladdr_size = n +
    790 			    sizeof(sep->se_ctrladdr_un) -
    791 			    sizeof(sep->se_ctrladdr_un.sun_path);
    792 			if (!ISMUX(sep))
    793 				setup(sep);
    794 			break;
    795 		case AF_INET:
    796 			sep->se_ctrladdr_in.sin_family = AF_INET;
    797 			if (!strcmp(sep->se_hostaddr,"*"))
    798 				sep->se_ctrladdr_in.sin_addr.s_addr =
    799 				    INADDR_ANY;
    800 			else if (!inet_aton(sep->se_hostaddr,
    801 			    &sep->se_ctrladdr_in.sin_addr)) {
    802 				/* Do we really want to support hostname lookups here? */
    803 				struct hostent *hp;
    804 				hp = gethostbyname(sep->se_hostaddr);
    805 				if (hp == 0) {
    806 					syslog(LOG_ERR, "%s: unknown host",
    807 					    sep->se_hostaddr);
    808 					sep->se_checked = 0;
    809 					continue;
    810 				} else if (hp->h_addrtype != AF_INET) {
    811 					syslog(LOG_ERR,
    812 				       "%s: address isn't an Internet address",
    813 					    sep->se_hostaddr);
    814 					sep->se_checked = 0;
    815 					continue;
    816 				} else if (hp->h_length != sizeof(struct in_addr)) {
    817 					syslog(LOG_ERR,
    818 		       "%s: address size wrong (under DNS corruption attack?)",
    819 					    sep->se_hostaddr);
    820 					sep->se_checked = 0;
    821 					continue;
    822 				} else {
    823 					memcpy(&sep->se_ctrladdr_in.sin_addr,
    824 					    hp->h_addr_list[0],
    825 					    sizeof(struct in_addr));
    826 				}
    827 			}
    828 			if (ISMUX(sep)) {
    829 				sep->se_fd = -1;
    830 				continue;
    831 			}
    832 			sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr_in);
    833 			if (isrpcservice(sep)) {
    834 				struct rpcent *rp;
    835 
    836 				sep->se_rpcprog = atoi(sep->se_service);
    837 				if (sep->se_rpcprog == 0) {
    838 					rp = getrpcbyname(sep->se_service);
    839 					if (rp == 0) {
    840 						syslog(LOG_ERR,
    841 						    "%s/%s: unknown service",
    842 						    sep->se_service,
    843 						    sep->se_proto);
    844 						sep->se_checked = 0;
    845 						continue;
    846 					}
    847 					sep->se_rpcprog = rp->r_number;
    848 				}
    849 				if (sep->se_fd == -1 && !ISMUX(sep))
    850 					setup(sep);
    851 				if (sep->se_fd != -1)
    852 					register_rpc(sep);
    853 			} else {
    854 				u_short port = htons(atoi(sep->se_service));
    855 
    856 				if (!port) {
    857 					sp = getservbyname(sep->se_service,
    858 					    sep->se_proto);
    859 					if (sp == 0) {
    860 						syslog(LOG_ERR,
    861 						    "%s/%s: unknown service",
    862 						    sep->se_service,
    863 						    sep->se_proto);
    864 						sep->se_checked = 0;
    865 						continue;
    866 					}
    867 					port = sp->s_port;
    868 				}
    869 				if (port != sep->se_ctrladdr_in.sin_port) {
    870 					sep->se_ctrladdr_in.sin_port = port;
    871 					if (sep->se_fd >= 0)
    872 						close_sep(sep);
    873 				}
    874 				if (sep->se_fd == -1 && !ISMUX(sep))
    875 					setup(sep);
    876 			}
    877 		}
    878 	}
    879 	endconfig();
    880 	/*
    881 	 * Purge anything not looked at above.
    882 	 */
    883 	omask = sigblock(SIGBLOCK);
    884 	sepp = &servtab;
    885 	while ((sep = *sepp)) {
    886 		if (sep->se_checked) {
    887 			sepp = &sep->se_next;
    888 			continue;
    889 		}
    890 		*sepp = sep->se_next;
    891 		if (sep->se_fd >= 0)
    892 			close_sep(sep);
    893 		if (isrpcservice(sep))
    894 			unregister_rpc(sep);
    895 		if (sep->se_family == AF_UNIX)
    896 			(void)unlink(sep->se_service);
    897 		if (debug)
    898 			print_service("FREE", sep);
    899 		freeconfig(sep);
    900 		free((char *)sep);
    901 	}
    902 	(void) sigsetmask(omask);
    903 }
    904 
    905 void
    906 retry(signo)
    907 	int signo;
    908 {
    909 	struct servtab *sep;
    910 
    911 	timingout = 0;
    912 	for (sep = servtab; sep; sep = sep->se_next) {
    913 		if (sep->se_fd == -1 && !ISMUX(sep)) {
    914 			switch (sep->se_family) {
    915 			case AF_UNIX:
    916 			case AF_INET:
    917 				setup(sep);
    918 				if (sep->se_fd != -1 && isrpcservice(sep))
    919 					register_rpc(sep);
    920 				break;
    921 			}
    922 		}
    923 	}
    924 }
    925 
    926 void
    927 goaway(signo)
    928 	int signo;
    929 {
    930 	struct servtab *sep;
    931 
    932 	for (sep = servtab; sep; sep = sep->se_next) {
    933 		if (sep->se_fd == -1)
    934 			continue;
    935 
    936 		switch (sep->se_family) {
    937 		case AF_UNIX:
    938 			(void)unlink(sep->se_service);
    939 			break;
    940 		case AF_INET:
    941 			if (sep->se_wait == 1 && isrpcservice(sep))
    942 				unregister_rpc(sep);
    943 			break;
    944 		}
    945 		(void)close(sep->se_fd);
    946 	}
    947 	(void)unlink(_PATH_INETDPID);
    948 	exit(0);
    949 }
    950 
    951 void
    952 setup(sep)
    953 	struct servtab *sep;
    954 {
    955 	int on = 1;
    956 
    957 	if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
    958 		if (debug)
    959 			fprintf(stderr, "socket failed on %s/%s: %s\n",
    960 			    sep->se_service, sep->se_proto, strerror(errno));
    961 		syslog(LOG_ERR, "%s/%s: socket: %m",
    962 		    sep->se_service, sep->se_proto);
    963 		return;
    964 	}
    965 	/* Set all listening sockets to close-on-exec. */
    966 	if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0)
    967 		syslog(LOG_ERR, "fcntl (F_SETFD, FD_CLOEXEC): %m");
    968 #define	turnon(fd, opt) \
    969 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
    970 	if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
    971 	    turnon(sep->se_fd, SO_DEBUG) < 0)
    972 		syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
    973 	if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
    974 		syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
    975 #undef turnon
    976 	if (bind(sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size) < 0) {
    977 		if (debug)
    978 			fprintf(stderr, "bind failed on %s/%s: %s\n",
    979 			    sep->se_service, sep->se_proto, strerror(errno));
    980 		syslog(LOG_ERR, "%s/%s: bind: %m",
    981 		    sep->se_service, sep->se_proto);
    982 		(void) close(sep->se_fd);
    983 		sep->se_fd = -1;
    984 		if (!timingout) {
    985 			timingout = 1;
    986 			alarm(RETRYTIME);
    987 		}
    988 		return;
    989 	}
    990 	if (sep->se_socktype == SOCK_STREAM)
    991 		listen(sep->se_fd, 10);
    992 
    993 	FD_SET(sep->se_fd, &allsock);
    994 	nsock++;
    995 	if (sep->se_fd > maxsock) {
    996 		maxsock = sep->se_fd;
    997 		if (maxsock > rlim_ofile_cur - FD_MARGIN)
    998 			bump_nofile();
    999 	}
   1000 	if (debug)
   1001 		fprintf(stderr, "registered %s on %d\n",
   1002 		    sep->se_server, sep->se_fd);
   1003 }
   1004 
   1005 /*
   1006  * Finish with a service and its socket.
   1007  */
   1008 void
   1009 close_sep(sep)
   1010 	struct servtab *sep;
   1011 {
   1012 	if (sep->se_fd >= 0) {
   1013 		nsock--;
   1014 		FD_CLR(sep->se_fd, &allsock);
   1015 		(void) close(sep->se_fd);
   1016 		sep->se_fd = -1;
   1017 	}
   1018 	sep->se_count = 0;
   1019 	/*
   1020 	 * Don't keep the pid of this running deamon: when reapchild()
   1021 	 * reaps this pid, it would erroneously increment nsock.
   1022 	 */
   1023 	if (sep->se_wait > 1)
   1024 		sep->se_wait = 1;
   1025 }
   1026 
   1027 void
   1028 register_rpc(sep)
   1029 	struct servtab *sep;
   1030 {
   1031 #ifdef RPC
   1032 	int n;
   1033 	struct sockaddr_in sin;
   1034 	struct protoent *pp;
   1035 
   1036 	if ((pp = getprotobyname(sep->se_proto+4)) == NULL) {
   1037 		syslog(LOG_ERR, "%s: getproto: %m",
   1038 		    sep->se_proto);
   1039 		return;
   1040 	}
   1041 	n = sizeof sin;
   1042 	if (getsockname(sep->se_fd, (struct sockaddr *)&sin, &n) < 0) {
   1043 		syslog(LOG_ERR, "%s/%s: getsockname: %m",
   1044 		    sep->se_service, sep->se_proto);
   1045 		return;
   1046 	}
   1047 
   1048 	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
   1049 		if (debug)
   1050 			fprintf(stderr, "pmap_set: %u %u %u %u\n",
   1051 			    sep->se_rpcprog, n, pp->p_proto,
   1052 			    ntohs(sin.sin_port));
   1053 		(void)pmap_unset(sep->se_rpcprog, n);
   1054 		if (!pmap_set(sep->se_rpcprog, n, pp->p_proto, ntohs(sin.sin_port)))
   1055 			syslog(LOG_ERR, "pmap_set: %u %u %u %u: %m",
   1056 			    sep->se_rpcprog, n, pp->p_proto,
   1057 			    ntohs(sin.sin_port));
   1058 	}
   1059 #endif /* RPC */
   1060 }
   1061 
   1062 void
   1063 unregister_rpc(sep)
   1064 	struct servtab *sep;
   1065 {
   1066 #ifdef RPC
   1067 	int n;
   1068 
   1069 	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
   1070 		if (debug)
   1071 			fprintf(stderr, "pmap_unset(%u, %u)\n",
   1072 			    sep->se_rpcprog, n);
   1073 		if (!pmap_unset(sep->se_rpcprog, n))
   1074 			syslog(LOG_ERR, "pmap_unset(%u, %u)\n",
   1075 			    sep->se_rpcprog, n);
   1076 	}
   1077 #endif /* RPC */
   1078 }
   1079 
   1080 
   1081 struct servtab *
   1082 enter(cp)
   1083 	struct servtab *cp;
   1084 {
   1085 	struct servtab *sep;
   1086 	long omask;
   1087 
   1088 	sep = (struct servtab *)malloc(sizeof (*sep));
   1089 	if (sep == (struct servtab *)0) {
   1090 		syslog(LOG_ERR, "Out of memory.");
   1091 		exit(-1);
   1092 	}
   1093 	*sep = *cp;
   1094 	sep->se_fd = -1;
   1095 	sep->se_rpcprog = -1;
   1096 	omask = sigblock(SIGBLOCK);
   1097 	sep->se_next = servtab;
   1098 	servtab = sep;
   1099 	sigsetmask(omask);
   1100 	return (sep);
   1101 }
   1102 
   1103 FILE	*fconfig = NULL;
   1104 struct	servtab serv;
   1105 char	line[LINE_MAX];
   1106 char    *defhost;
   1107 
   1108 int
   1109 setconfig()
   1110 {
   1111 	if (defhost) free(defhost);
   1112 	defhost = newstr("*");
   1113 	if (fconfig != NULL) {
   1114 		fseek(fconfig, 0L, SEEK_SET);
   1115 		return (1);
   1116 	}
   1117 	fconfig = fopen(CONFIG, "r");
   1118 	return (fconfig != NULL);
   1119 }
   1120 
   1121 void
   1122 endconfig()
   1123 {
   1124 	if (fconfig) {
   1125 		(void) fclose(fconfig);
   1126 		fconfig = NULL;
   1127 	}
   1128 	if (defhost) {
   1129 		free(defhost);
   1130 		defhost = 0;
   1131 	}
   1132 }
   1133 
   1134 struct servtab *
   1135 getconfigent()
   1136 {
   1137 	struct servtab *sep = &serv;
   1138 	int argc;
   1139 	char *cp, *arg;
   1140 	static char TCPMUX_TOKEN[] = "tcpmux/";
   1141 #define MUX_LEN		(sizeof(TCPMUX_TOKEN)-1)
   1142 	char *hostdelim;
   1143 
   1144 more:
   1145 #ifdef MULOG
   1146 	while ((cp = nextline(fconfig)) && (*cp == '#' || *cp == '\0')) {
   1147 		/* Avoid use of `skip' if there is a danger of it looking
   1148 		 * at continuation lines.
   1149 		 */
   1150 		do {
   1151 			cp++;
   1152 		} while (*cp == ' ' || *cp == '\t');
   1153 		if (*cp == '\0')
   1154 			continue;
   1155 		if ((arg = skip(&cp)) == NULL)
   1156 			continue;
   1157 		if (strcmp(arg, "DOMAIN"))
   1158 			continue;
   1159 		if (curdom)
   1160 			free(curdom);
   1161 		curdom = NULL;
   1162 		while (*cp == ' ' || *cp == '\t')
   1163 			cp++;
   1164 		if (*cp == '\0')
   1165 			continue;
   1166 		arg = cp;
   1167 		while (*cp && *cp != ' ' && *cp != '\t')
   1168 			cp++;
   1169 		if (*cp != '\0')
   1170 			*cp++ = '\0';
   1171 		curdom = newstr(arg);
   1172 	}
   1173 #else
   1174 	while ((cp = nextline(fconfig)) && (*cp == '#' || *cp == '\0'))
   1175 		;
   1176 #endif
   1177 	if (cp == NULL)
   1178 		return ((struct servtab *)0);
   1179 	/*
   1180 	 * clear the static buffer, since some fields (se_ctrladdr,
   1181 	 * for example) don't get initialized here.
   1182 	 */
   1183 	memset((caddr_t)sep, 0, sizeof *sep);
   1184 	arg = skip(&cp);
   1185 	if (cp == NULL) {
   1186 		/* got an empty line containing just blanks/tabs. */
   1187 		goto more;
   1188 	}
   1189 	/* Check for a host name. */
   1190 	hostdelim = strrchr(arg, ':');
   1191 	if (hostdelim) {
   1192 		*hostdelim = '\0';
   1193 		sep->se_hostaddr = newstr(arg);
   1194 		arg = hostdelim + 1;
   1195 		/*
   1196 		 * If the line is of the form `host:', then just change the
   1197 		 * default host for the following lines.
   1198 		 */
   1199 		if (*arg == '\0') {
   1200 			arg = skip(&cp);
   1201 			if (cp == NULL) {
   1202 				free(defhost);
   1203 				defhost = sep->se_hostaddr;
   1204 				goto more;
   1205 			}
   1206 		}
   1207 	} else
   1208 		sep->se_hostaddr = newstr(defhost);
   1209 	if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
   1210 		char *c = arg + MUX_LEN;
   1211 		if (*c == '+') {
   1212 			sep->se_type = MUXPLUS_TYPE;
   1213 			c++;
   1214 		} else
   1215 			sep->se_type = MUX_TYPE;
   1216 		sep->se_service = newstr(c);
   1217 	} else {
   1218 		sep->se_service = newstr(arg);
   1219 		sep->se_type = NORM_TYPE;
   1220 	}
   1221 
   1222 	arg = sskip(&cp);
   1223 	if (strcmp(arg, "stream") == 0)
   1224 		sep->se_socktype = SOCK_STREAM;
   1225 	else if (strcmp(arg, "dgram") == 0)
   1226 		sep->se_socktype = SOCK_DGRAM;
   1227 	else if (strcmp(arg, "rdm") == 0)
   1228 		sep->se_socktype = SOCK_RDM;
   1229 	else if (strcmp(arg, "seqpacket") == 0)
   1230 		sep->se_socktype = SOCK_SEQPACKET;
   1231 	else if (strcmp(arg, "raw") == 0)
   1232 		sep->se_socktype = SOCK_RAW;
   1233 	else
   1234 		sep->se_socktype = -1;
   1235 
   1236 	sep->se_proto = newstr(sskip(&cp));
   1237 	if (strcmp(sep->se_proto, "unix") == 0) {
   1238 		sep->se_family = AF_UNIX;
   1239 	} else {
   1240 		sep->se_family = AF_INET;
   1241 		if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
   1242 #ifdef RPC
   1243 			char *cp, *ccp;
   1244 			cp = strchr(sep->se_service, '/');
   1245 			if (cp == 0) {
   1246 				syslog(LOG_ERR, "%s: no rpc version",
   1247 				    sep->se_service);
   1248 				goto more;
   1249 			}
   1250 			*cp++ = '\0';
   1251 			sep->se_rpcversl = sep->se_rpcversh =
   1252 			    strtol(cp, &ccp, 0);
   1253 			if (ccp == cp) {
   1254 		badafterall:
   1255 				syslog(LOG_ERR, "%s/%s: bad rpc version",
   1256 				    sep->se_service, cp);
   1257 				goto more;
   1258 			}
   1259 			if (*ccp == '-') {
   1260 				cp = ccp + 1;
   1261 				sep->se_rpcversh = strtol(cp, &ccp, 0);
   1262 				if (ccp == cp)
   1263 					goto badafterall;
   1264 			}
   1265 #else
   1266 			syslog(LOG_ERR, "%s: rpc services not suported",
   1267 			    sep->se_service);
   1268 			goto more;
   1269 #endif /* RPC */
   1270 		}
   1271 	}
   1272 	arg = sskip(&cp);
   1273 	{
   1274 		char *cp;
   1275 		cp = strchr(arg, '.');
   1276 		if (cp) {
   1277 			*cp++ = '\0';
   1278 			sep->se_max = atoi(cp);
   1279 		} else
   1280 			sep->se_max = TOOMANY;
   1281 	}
   1282 	sep->se_wait = strcmp(arg, "wait") == 0;
   1283 	if (ISMUX(sep)) {
   1284 		/*
   1285 		 * Silently enforce "nowait" for TCPMUX services since
   1286 		 * they don't have an assigned port to listen on.
   1287 		 */
   1288 		sep->se_wait = 0;
   1289 
   1290 		if (strcmp(sep->se_proto, "tcp")) {
   1291 			syslog(LOG_ERR,
   1292 			    "%s: bad protocol for tcpmux service %s",
   1293 			    CONFIG, sep->se_service);
   1294 			goto more;
   1295 		}
   1296 		if (sep->se_socktype != SOCK_STREAM) {
   1297 			syslog(LOG_ERR,
   1298 			    "%s: bad socket type for tcpmux service %s",
   1299 			    CONFIG, sep->se_service);
   1300 			goto more;
   1301 		}
   1302 	}
   1303 	sep->se_user = newstr(sskip(&cp));
   1304 	if ((sep->se_group = strchr(sep->se_user, '.')))
   1305 		*sep->se_group++ = '\0';
   1306 	sep->se_server = newstr(sskip(&cp));
   1307 	if (strcmp(sep->se_server, "internal") == 0) {
   1308 		struct biltin *bi;
   1309 
   1310 		for (bi = biltins; bi->bi_service; bi++)
   1311 			if (bi->bi_socktype == sep->se_socktype &&
   1312 			    strcmp(bi->bi_service, sep->se_service) == 0)
   1313 				break;
   1314 		if (bi->bi_service == 0) {
   1315 			syslog(LOG_ERR, "internal service %s unknown",
   1316 			    sep->se_service);
   1317 			goto more;
   1318 		}
   1319 		sep->se_bi = bi;
   1320 		sep->se_wait = bi->bi_wait;
   1321 	} else
   1322 		sep->se_bi = NULL;
   1323 	argc = 0;
   1324 	for (arg = skip(&cp); cp; arg = skip(&cp)) {
   1325 #if MULOG
   1326 		char *colon;
   1327 
   1328 		if (argc == 0 && (colon = strrchr(arg, ':'))) {
   1329 			while (arg < colon) {
   1330 				int	x;
   1331 				char	*ccp;
   1332 
   1333 				switch (*arg++) {
   1334 				case 'l':
   1335 					x = 1;
   1336 					if (isdigit(*arg)) {
   1337 						x = strtol(arg, &ccp, 0);
   1338 						if (ccp == arg)
   1339 							break;
   1340 						arg = ccp;
   1341 					}
   1342 					sep->se_log &= ~MULOG_RFC931;
   1343 					sep->se_log |= x;
   1344 					break;
   1345 				case 'a':
   1346 					sep->se_log |= MULOG_RFC931;
   1347 					break;
   1348 				default:
   1349 					break;
   1350 				}
   1351 			}
   1352 			arg = colon + 1;
   1353 		}
   1354 #endif
   1355 		if (argc < MAXARGV)
   1356 			sep->se_argv[argc++] = newstr(arg);
   1357 	}
   1358 	while (argc <= MAXARGV)
   1359 		sep->se_argv[argc++] = NULL;
   1360 	return (sep);
   1361 }
   1362 
   1363 void
   1364 freeconfig(cp)
   1365 	struct servtab *cp;
   1366 {
   1367 	int i;
   1368 
   1369 	if (cp->se_hostaddr)
   1370 		free(cp->se_hostaddr);
   1371 	if (cp->se_service)
   1372 		free(cp->se_service);
   1373 	if (cp->se_proto)
   1374 		free(cp->se_proto);
   1375 	if (cp->se_user)
   1376 		free(cp->se_user);
   1377 	/* Note: se_group is part of the newstr'ed se_user */
   1378 	if (cp->se_server)
   1379 		free(cp->se_server);
   1380 	for (i = 0; i < MAXARGV; i++)
   1381 		if (cp->se_argv[i])
   1382 			free(cp->se_argv[i]);
   1383 }
   1384 
   1385 
   1386 /*
   1387  * Safe skip - if skip returns null, log a syntax error in the
   1388  * configuration file and exit.
   1389  */
   1390 char *
   1391 sskip(cpp)
   1392 	char **cpp;
   1393 {
   1394 	char *cp;
   1395 
   1396 	cp = skip(cpp);
   1397 	if (cp == NULL) {
   1398 		syslog(LOG_ERR, "%s: syntax error", CONFIG);
   1399 		exit(-1);
   1400 	}
   1401 	return (cp);
   1402 }
   1403 
   1404 char *
   1405 skip(cpp)
   1406 	char **cpp;
   1407 {
   1408 	char *cp = *cpp;
   1409 	char *start;
   1410 
   1411 	if (*cpp == NULL)
   1412 		return ((char *)0);
   1413 
   1414 again:
   1415 	while (*cp == ' ' || *cp == '\t')
   1416 		cp++;
   1417 	if (*cp == '\0') {
   1418 		int c;
   1419 
   1420 		c = getc(fconfig);
   1421 		(void) ungetc(c, fconfig);
   1422 		if (c == ' ' || c == '\t')
   1423 			if ((cp = nextline(fconfig)))
   1424 				goto again;
   1425 		*cpp = (char *)0;
   1426 		return ((char *)0);
   1427 	}
   1428 	start = cp;
   1429 	while (*cp && *cp != ' ' && *cp != '\t')
   1430 		cp++;
   1431 	if (*cp != '\0')
   1432 		*cp++ = '\0';
   1433 	*cpp = cp;
   1434 	return (start);
   1435 }
   1436 
   1437 char *
   1438 nextline(fd)
   1439 	FILE *fd;
   1440 {
   1441 	char *cp;
   1442 
   1443 	if (fgets(line, sizeof (line), fd) == NULL)
   1444 		return ((char *)0);
   1445 	cp = strchr(line, '\n');
   1446 	if (cp)
   1447 		*cp = '\0';
   1448 	return (line);
   1449 }
   1450 
   1451 char *
   1452 newstr(cp)
   1453 	char *cp;
   1454 {
   1455 	if ((cp = strdup(cp ? cp : "")))
   1456 		return (cp);
   1457 	syslog(LOG_ERR, "strdup: %m");
   1458 	exit(-1);
   1459 }
   1460 
   1461 void
   1462 inetd_setproctitle(a, s)
   1463 	char *a;
   1464 	int s;
   1465 {
   1466 	int size;
   1467 	char *cp;
   1468 	struct sockaddr_in sin;
   1469 	char buf[80];
   1470 
   1471 	cp = Argv[0];
   1472 	size = sizeof(sin);
   1473 	if (getpeername(s, (struct sockaddr *)&sin, &size) == 0)
   1474 		(void)snprintf(buf, sizeof buf, "-%s [%s]", a,
   1475 		    inet_ntoa(sin.sin_addr));
   1476 	else
   1477 		(void)snprintf(buf, sizeof buf, "-%s", a);
   1478 	strncpy(cp, buf, LastArg - cp);
   1479 	cp += strlen(cp);
   1480 	while (cp < LastArg)
   1481 		*cp++ = ' ';
   1482 }
   1483 
   1484 void
   1485 logpid()
   1486 {
   1487 	FILE *fp;
   1488 
   1489 	if ((fp = fopen(_PATH_INETDPID, "w")) != NULL) {
   1490 		fprintf(fp, "%u\n", getpid());
   1491 		(void)fclose(fp);
   1492 	}
   1493 }
   1494 
   1495 void
   1496 bump_nofile()
   1497 {
   1498 #ifdef RLIMIT_NOFILE
   1499 
   1500 #define FD_CHUNK	32
   1501 
   1502 	struct rlimit rl;
   1503 
   1504 	if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
   1505 		syslog(LOG_ERR, "getrlimit: %m");
   1506 		return;
   1507 	}
   1508 	rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
   1509 	if (rl.rlim_cur <= rlim_ofile_cur) {
   1510 		syslog(LOG_ERR,
   1511 		    "bump_nofile: cannot extend file limit, max = %d",
   1512 		    (int)rl.rlim_cur);
   1513 		return;
   1514 	}
   1515 
   1516 	if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
   1517 		syslog(LOG_ERR, "setrlimit: %m");
   1518 		return;
   1519 	}
   1520 
   1521 	rlim_ofile_cur = rl.rlim_cur;
   1522 	return;
   1523 
   1524 #else
   1525 	syslog(LOG_ERR, "bump_nofile: cannot extend file limit");
   1526 	return;
   1527 #endif
   1528 }
   1529 
   1530 /*
   1531  * Internet services provided internally by inetd:
   1532  */
   1533 #define	BUFSIZE	4096
   1534 
   1535 /* ARGSUSED */
   1536 void
   1537 echo_stream(s, sep)		/* Echo service -- echo data back */
   1538 	int s;
   1539 	struct servtab *sep;
   1540 {
   1541 	char buffer[BUFSIZE];
   1542 	int i;
   1543 
   1544 	inetd_setproctitle(sep->se_service, s);
   1545 	while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
   1546 	    write(s, buffer, i) > 0)
   1547 		;
   1548 }
   1549 
   1550 /* ARGSUSED */
   1551 void
   1552 echo_dg(s, sep)			/* Echo service -- echo data back */
   1553 	int s;
   1554 	struct servtab *sep;
   1555 {
   1556 	char buffer[BUFSIZE];
   1557 	int i, size;
   1558 	struct sockaddr sa;
   1559 
   1560 	size = sizeof(sa);
   1561 	if ((i = recvfrom(s, buffer, sizeof(buffer), 0, &sa, &size)) < 0)
   1562 		return;
   1563 	(void) sendto(s, buffer, i, 0, &sa, sizeof(sa));
   1564 }
   1565 
   1566 /* ARGSUSED */
   1567 void
   1568 discard_stream(s, sep)		/* Discard service -- ignore data */
   1569 	int s;
   1570 	struct servtab *sep;
   1571 {
   1572 	char buffer[BUFSIZE];
   1573 
   1574 	inetd_setproctitle(sep->se_service, s);
   1575 	while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
   1576 			errno == EINTR)
   1577 		;
   1578 }
   1579 
   1580 /* ARGSUSED */
   1581 void
   1582 discard_dg(s, sep)		/* Discard service -- ignore data */
   1583 	int s;
   1584 	struct servtab *sep;
   1585 {
   1586 	char buffer[BUFSIZE];
   1587 
   1588 	(void) read(s, buffer, sizeof(buffer));
   1589 }
   1590 
   1591 #include <ctype.h>
   1592 #define LINESIZ 72
   1593 char ring[128];
   1594 char *endring;
   1595 
   1596 void
   1597 initring()
   1598 {
   1599 	int i;
   1600 
   1601 	endring = ring;
   1602 
   1603 	for (i = 0; i <= 128; ++i)
   1604 		if (isprint(i))
   1605 			*endring++ = i;
   1606 }
   1607 
   1608 /* ARGSUSED */
   1609 void
   1610 chargen_stream(s, sep)		/* Character generator */
   1611 	int s;
   1612 	struct servtab *sep;
   1613 {
   1614 	int len;
   1615 	char *rs, text[LINESIZ+2];
   1616 
   1617 	inetd_setproctitle(sep->se_service, s);
   1618 
   1619 	if (!endring) {
   1620 		initring();
   1621 		rs = ring;
   1622 	}
   1623 
   1624 	text[LINESIZ] = '\r';
   1625 	text[LINESIZ + 1] = '\n';
   1626 	for (rs = ring;;) {
   1627 		if ((len = endring - rs) >= LINESIZ)
   1628 			memmove(text, rs, LINESIZ);
   1629 		else {
   1630 			memmove(text, rs, len);
   1631 			memmove(text + len, ring, LINESIZ - len);
   1632 		}
   1633 		if (++rs == endring)
   1634 			rs = ring;
   1635 		if (write(s, text, sizeof(text)) != sizeof(text))
   1636 			break;
   1637 	}
   1638 }
   1639 
   1640 /* ARGSUSED */
   1641 void
   1642 chargen_dg(s, sep)		/* Character generator */
   1643 	int s;
   1644 	struct servtab *sep;
   1645 {
   1646 	struct sockaddr sa;
   1647 	static char *rs;
   1648 	int len, size;
   1649 	char text[LINESIZ+2];
   1650 
   1651 	if (endring == 0) {
   1652 		initring();
   1653 		rs = ring;
   1654 	}
   1655 
   1656 	size = sizeof(sa);
   1657 	if (recvfrom(s, text, sizeof(text), 0, &sa, &size) < 0)
   1658 		return;
   1659 
   1660 	if ((len = endring - rs) >= LINESIZ)
   1661 		memmove(text, rs, LINESIZ);
   1662 	else {
   1663 		memmove(text, rs, len);
   1664 		memmove(text + len, ring, LINESIZ - len);
   1665 	}
   1666 	if (++rs == endring)
   1667 		rs = ring;
   1668 	text[LINESIZ] = '\r';
   1669 	text[LINESIZ + 1] = '\n';
   1670 	(void) sendto(s, text, sizeof(text), 0, &sa, sizeof(sa));
   1671 }
   1672 
   1673 /*
   1674  * Return a machine readable date and time, in the form of the
   1675  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
   1676  * returns the number of seconds since midnight, Jan 1, 1970,
   1677  * we must add 2208988800 seconds to this figure to make up for
   1678  * some seventy years Bell Labs was asleep.
   1679  */
   1680 
   1681 long
   1682 machtime()
   1683 {
   1684 	struct timeval tv;
   1685 
   1686 	if (gettimeofday(&tv, (struct timezone *)0) < 0) {
   1687 		if (debug)
   1688 			fprintf(stderr, "Unable to get time of day\n");
   1689 		return (0L);
   1690 	}
   1691 #define	OFFSET ((u_long)25567 * 24*60*60)
   1692 	return (htonl((long)(tv.tv_sec + OFFSET)));
   1693 #undef OFFSET
   1694 }
   1695 
   1696 /* ARGSUSED */
   1697 void
   1698 machtime_stream(s, sep)
   1699 	int s;
   1700 	struct servtab *sep;
   1701 {
   1702 	long result;
   1703 
   1704 	result = machtime();
   1705 	(void) write(s, (char *) &result, sizeof(result));
   1706 }
   1707 
   1708 /* ARGSUSED */
   1709 void
   1710 machtime_dg(s, sep)
   1711 	int s;
   1712 	struct servtab *sep;
   1713 {
   1714 	long result;
   1715 	struct sockaddr sa;
   1716 	int size;
   1717 
   1718 	size = sizeof(sa);
   1719 	if (recvfrom(s, (char *)&result, sizeof(result), 0, &sa, &size) < 0)
   1720 		return;
   1721 	result = machtime();
   1722 	(void) sendto(s, (char *) &result, sizeof(result), 0, &sa, sizeof(sa));
   1723 }
   1724 
   1725 /* ARGSUSED */
   1726 void
   1727 daytime_stream(s, sep)		/* Return human-readable time of day */
   1728 	int s;
   1729 	struct servtab *sep;
   1730 {
   1731 	char buffer[256];
   1732 	time_t clock;
   1733 	int len;
   1734 
   1735 	clock = time((time_t *) 0);
   1736 
   1737 	len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
   1738 	(void) write(s, buffer, len);
   1739 }
   1740 
   1741 /* ARGSUSED */
   1742 void
   1743 daytime_dg(s, sep)		/* Return human-readable time of day */
   1744 	int s;
   1745 	struct servtab *sep;
   1746 {
   1747 	char buffer[256];
   1748 	time_t clock;
   1749 	struct sockaddr sa;
   1750 	int size, len;
   1751 
   1752 	clock = time((time_t *) 0);
   1753 
   1754 	size = sizeof(sa);
   1755 	if (recvfrom(s, buffer, sizeof(buffer), 0, &sa, &size) < 0)
   1756 		return;
   1757 	len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
   1758 	(void) sendto(s, buffer, len, 0, &sa, sizeof(sa));
   1759 }
   1760 
   1761 /*
   1762  * print_service:
   1763  *	Dump relevant information to stderr
   1764  */
   1765 void
   1766 print_service(action, sep)
   1767 	char *action;
   1768 	struct servtab *sep;
   1769 {
   1770 	if (isrpcservice(sep))
   1771 		fprintf(stderr,
   1772 		    "%s: %s rpcprog=%d, rpcvers = %d/%d, proto=%s, wait.max=%d.%d, user.group=%s.%s builtin=%lx server=%s\n",
   1773 		    action, sep->se_service,
   1774 		    sep->se_rpcprog, sep->se_rpcversh, sep->se_rpcversl, sep->se_proto,
   1775 		    sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
   1776 		    (long)sep->se_bi, sep->se_server);
   1777 	else
   1778 		fprintf(stderr,
   1779 		    "%s: %s proto=%s, wait.max=%d.%d, user.group=%s.%s builtin=%lx server=%s\n",
   1780 		    action, sep->se_service, 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 }
   1784 
   1785 void
   1786 usage()
   1787 {
   1788 
   1789 #ifdef LIBWRAP
   1790 	(void)fprintf(stderr, "usage: %s [-dl] [conf]\n", __progname);
   1791 #else
   1792 	(void)fprintf(stderr, "usage: %s [-d] [conf]\n", __progname);
   1793 #endif
   1794 	exit(1);
   1795 }
   1796 
   1797 
   1798 /*
   1799  *  Based on TCPMUX.C by Mark K. Lottor November 1988
   1800  *  sri-nic::ps:<mkl>tcpmux.c
   1801  */
   1802 
   1803 static int		/* # of characters upto \r,\n or \0 */
   1804 getline(fd, buf, len)
   1805 	int fd;
   1806 	char *buf;
   1807 	int len;
   1808 {
   1809 	int count = 0, n;
   1810 
   1811 	do {
   1812 		n = read(fd, buf, len-count);
   1813 		if (n == 0)
   1814 			return (count);
   1815 		if (n < 0)
   1816 			return (-1);
   1817 		while (--n >= 0) {
   1818 			if (*buf == '\r' || *buf == '\n' || *buf == '\0')
   1819 				return (count);
   1820 			count++;
   1821 			buf++;
   1822 		}
   1823 	} while (count < len);
   1824 	return (count);
   1825 }
   1826 
   1827 #define MAX_SERV_LEN	(256+2)		/* 2 bytes for \r\n */
   1828 
   1829 #define strwrite(fd, buf)	(void) write(fd, buf, sizeof(buf)-1)
   1830 
   1831 void
   1832 tcpmux(ctrl, sep)
   1833 	int ctrl;
   1834 	struct servtab *sep;
   1835 {
   1836 	char service[MAX_SERV_LEN+1];
   1837 	int len;
   1838 
   1839 	/* Get requested service name */
   1840 	if ((len = getline(ctrl, service, MAX_SERV_LEN)) < 0) {
   1841 		strwrite(ctrl, "-Error reading service name\r\n");
   1842 		goto reject;
   1843 	}
   1844 	service[len] = '\0';
   1845 
   1846 	if (debug)
   1847 		fprintf(stderr, "tcpmux: someone wants %s\n", service);
   1848 
   1849 	/*
   1850 	 * Help is a required command, and lists available services,
   1851 	 * one per line.
   1852 	 */
   1853 	if (!strcasecmp(service, "help")) {
   1854 		strwrite(ctrl, "+Available services:\r\n");
   1855 		strwrite(ctrl, "help\r\n");
   1856 		for (sep = servtab; sep; sep = sep->se_next) {
   1857 			if (!ISMUX(sep))
   1858 				continue;
   1859 			(void)write(ctrl, sep->se_service,
   1860 			    strlen(sep->se_service));
   1861 			strwrite(ctrl, "\r\n");
   1862 		}
   1863 		goto reject;
   1864 	}
   1865 
   1866 	/* Try matching a service in inetd.conf with the request */
   1867 	for (sep = servtab; sep; sep = sep->se_next) {
   1868 		if (!ISMUX(sep))
   1869 			continue;
   1870 		if (!strcasecmp(service, sep->se_service)) {
   1871 			if (ISMUXPLUS(sep))
   1872 				strwrite(ctrl, "+Go\r\n");
   1873 			run_service(ctrl, sep);
   1874 			return;
   1875 		}
   1876 	}
   1877 	strwrite(ctrl, "-Service not available\r\n");
   1878 reject:
   1879 	_exit(1);
   1880 }
   1881 
   1882 
   1883 #ifdef MULOG
   1884 dolog(sep, ctrl)
   1885 	struct servtab *sep;
   1886 	int		ctrl;
   1887 {
   1888 	struct sockaddr		sa;
   1889 	struct sockaddr_in	*sin = (struct sockaddr_in *)&sa;
   1890 	int			len = sizeof(sa);
   1891 	struct hostent		*hp;
   1892 	char			*host, *dp, buf[BUFSIZ], *rfc931_name();
   1893 	int			connected = 1;
   1894 
   1895 	if (sep->se_family != AF_INET)
   1896 		return;
   1897 
   1898 	if (getpeername(ctrl, &sa, &len) < 0) {
   1899 		if (errno != ENOTCONN) {
   1900 			syslog(LOG_ERR, "getpeername: %m");
   1901 			return;
   1902 		}
   1903 		if (recvfrom(ctrl, buf, sizeof(buf), MSG_PEEK, &sa, &len) < 0) {
   1904 			syslog(LOG_ERR, "recvfrom: %m");
   1905 			return;
   1906 		}
   1907 		connected = 0;
   1908 	}
   1909 	if (sa.sa_family != AF_INET) {
   1910 		syslog(LOG_ERR, "unexpected address family %u", sa.sa_family);
   1911 		return;
   1912 	}
   1913 
   1914 	hp = gethostbyaddr((char *) &sin->sin_addr.s_addr,
   1915 				sizeof (sin->sin_addr.s_addr), AF_INET);
   1916 
   1917 	host = hp?hp->h_name:inet_ntoa(sin->sin_addr);
   1918 
   1919 	switch (sep->se_log & ~MULOG_RFC931) {
   1920 	case 0:
   1921 		return;
   1922 	case 1:
   1923 		if (curdom == NULL || *curdom == '\0')
   1924 			break;
   1925 		dp = host + strlen(host) - strlen(curdom);
   1926 		if (dp < host)
   1927 			break;
   1928 		if (debug)
   1929 			fprintf(stderr, "check \"%s\" against curdom \"%s\"\n",
   1930 			    host, curdom);
   1931 		if (strcasecmp(dp, curdom) == 0)
   1932 			return;
   1933 		break;
   1934 	case 2:
   1935 	default:
   1936 		break;
   1937 	}
   1938 
   1939 	openlog("", LOG_NOWAIT, MULOG);
   1940 
   1941 	if (connected && (sep->se_log & MULOG_RFC931))
   1942 		syslog(LOG_INFO, "%s@%s wants %s",
   1943 		    rfc931_name(sin, ctrl), host, sep->se_service);
   1944 	else
   1945 		syslog(LOG_INFO, "%s wants %s",
   1946 		    host, sep->se_service);
   1947 }
   1948 
   1949 /*
   1950  * From tcp_log by
   1951  *  Wietse Venema, Eindhoven University of Technology, The Netherlands.
   1952  */
   1953 #if 0
   1954 static char sccsid[] = "@(#) rfc931.c 1.3 92/08/31 22:54:46";
   1955 #endif
   1956 
   1957 #include <setjmp.h>
   1958 
   1959 #define	RFC931_PORT	113		/* Semi-well-known port */
   1960 #define	TIMEOUT		4
   1961 #define	TIMEOUT2	10
   1962 
   1963 static jmp_buf timebuf;
   1964 
   1965 /* timeout - handle timeouts */
   1966 
   1967 static void timeout(sig)
   1968 int     sig;
   1969 {
   1970 	longjmp(timebuf, sig);
   1971 }
   1972 
   1973 /* rfc931_name - return remote user name */
   1974 
   1975 char *
   1976 rfc931_name(there, ctrl)
   1977 struct sockaddr_in *there;		/* remote link information */
   1978 int	ctrl;
   1979 {
   1980 	struct sockaddr_in here;	/* local link information */
   1981 	struct sockaddr_in sin;		/* for talking to RFC931 daemon */
   1982 	int		length;
   1983 	int		s;
   1984 	unsigned	remote;
   1985 	unsigned	local;
   1986 	static char	user[256];		/* XXX */
   1987 	char		buf[256];
   1988 	char		*cp;
   1989 	char		*result = "USER_UNKNOWN";
   1990 	int		len;
   1991 
   1992 	/* Find out local port number of our stdin. */
   1993 
   1994 	length = sizeof(here);
   1995 	if (getsockname(ctrl, (struct sockaddr *) &here, &length) == -1) {
   1996 		syslog(LOG_ERR, "getsockname: %m");
   1997 		return (result);
   1998 	}
   1999 	/* Set up timer so we won't get stuck. */
   2000 
   2001 	if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
   2002 		syslog(LOG_ERR, "socket: %m");
   2003 		return (result);
   2004 	}
   2005 
   2006 	sin = here;
   2007 	sin.sin_port = htons(0);
   2008 	if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) == -1) {
   2009 		syslog(LOG_ERR, "bind: %m");
   2010 		return (result);
   2011 	}
   2012 
   2013 	signal(SIGALRM, timeout);
   2014 	if (setjmp(timebuf)) {
   2015 		close(s);			/* not: fclose(fp) */
   2016 		return (result);
   2017 	}
   2018 	alarm(TIMEOUT);
   2019 
   2020 	/* Connect to the RFC931 daemon. */
   2021 
   2022 	sin = *there;
   2023 	sin.sin_port = htons(RFC931_PORT);
   2024 	if (connect(s, (struct sockaddr *) &sin, sizeof(sin)) == -1) {
   2025 		close(s);
   2026 		alarm(0);
   2027 		return (result);
   2028 	}
   2029 
   2030 	/* Query the RFC 931 server. Would 13-byte writes ever be broken up? */
   2031 	(void)snprintf(buf, sizeof buf, "%u,%u\r\n", ntohs(there->sin_port),
   2032 	    ntohs(here.sin_port));
   2033 
   2034 
   2035 	for (len = 0, cp = buf; len < strlen(buf); ) {
   2036 		int	n;
   2037 
   2038 		if ((n = write(s, cp, strlen(buf) - len)) == -1) {
   2039 			close(s);
   2040 			alarm(0);
   2041 			return (result);
   2042 		}
   2043 		cp += n;
   2044 		len += n;
   2045 	}
   2046 
   2047 	/* Read response */
   2048 	for (cp = buf; cp < buf + sizeof(buf) - 1; ) {
   2049 		char	c;
   2050 		if (read(s, &c, 1) != 1) {
   2051 			close(s);
   2052 			alarm(0);
   2053 			return (result);
   2054 		}
   2055 		if (c == '\n')
   2056 			break;
   2057 		*cp++ = c;
   2058 	}
   2059 	*cp = '\0';
   2060 
   2061 	if (sscanf(buf, "%u , %u : USERID :%*[^:]:%255s", &remote, &local, user) == 3
   2062 		&& ntohs(there->sin_port) == remote
   2063 		&& ntohs(here.sin_port) == local) {
   2064 
   2065 		/* Strip trailing carriage return. */
   2066 		if (cp = strchr(user, '\r'))
   2067 			*cp = 0;
   2068 		result = user;
   2069 	}
   2070 
   2071 	alarm(0);
   2072 	close(s);
   2073 	return (result);
   2074 }
   2075 #endif
   2076