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