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