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