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