inetd.c 43.7 KB
Newer Older
1
/*	$OpenBSD: inetd.c,v 1.153 2016/03/16 20:16:39 mestre Exp $	*/
2

3 4 5 6 7 8 9 10 11 12 13 14
/*
 * Copyright (c) 1983,1991 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
15
 * 3. Neither the name of the University nor the names of its contributors
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Inetd - Internet super-server
 *
 * This program invokes all internet services as needed.
 * connection-oriented services are invoked each time a
 * connection is made, by creating a process.  This process
 * is passed the connection as file descriptor 0 and is
 * expected to do a getpeername to find out the source host
 * and port.
 *
 * Datagram oriented services are invoked when a datagram
 * arrives; a process is created and passed a pending message
 * on file descriptor 0.  Datagram servers may either connect
 * to their peer, freeing up the original socket for inetd
 * to receive further messages on, or ``take over the socket'',
 * processing all arriving datagrams and, eventually, timing
 * out.	 The first type of server is said to be ``multi-threaded'';
 * the second type of server ``single-threaded''.
 *
 * Inetd uses a configuration file which is read at startup
 * and, possibly, at some later time in response to a hangup signal.
 * The configuration file is ``free format'' with fields given in the
 * order shown below.  Continuation lines for an entry must begin with
 * a space or tab.  All fields must be present in each entry.
 *
 *	service name			must be in /etc/services
 *	socket type			stream/dgram/raw/rdm/seqpacket
 *	protocol			must be in /etc/protocols
 *	wait/nowait[.max]		single-threaded/multi-threaded, max #
 *	user[.group] or user[:group]	user/group to run daemon as
 *	server program			full path name
 *	server program arguments	maximum of MAXARGS (20)
 *
 * For RPC services
 *      service name/version            must be in /etc/rpc
 *	socket type			stream/dgram/raw/rdm/seqpacket
 *	protocol			must be in /etc/protocols
 *	wait/nowait[.max]		single-threaded/multi-threaded
 *	user[.group] or user[:group]	user to run daemon as
 *	server program			full path name
 *	server program arguments	maximum of MAXARGS (20)
 *
 * For non-RPC services, the "service name" can be of the form
 * hostaddress:servicename, in which case the hostaddress is used
 * as the host portion of the address to listen on.  If hostaddress
 * consists of a single `*' character, INADDR_ANY is used.
 *
 * A line can also consist of just
 *      hostaddress:
 * where hostaddress is as in the preceding paragraph.  Such a line must
 * have no further fields; the specified hostaddress is remembered and
 * used for all further lines that have no hostaddress specified,
 * until the next such line (or EOF).  (This is why * is provided to
 * allow explicit specification of INADDR_ANY.)  A line
 *      *:
 * is implicitly in effect at the beginning of the file.
 *
 * The hostaddress specifier may (and often will) contain dots;
 * the service name must not.
 *
 * For RPC services, host-address specifiers are accepted and will
 * work to some extent; however, because of limitations in the
 * portmapper interface, it will not work to try to give more than
 * one line for any given RPC service, even if the host-address
 * specifiers are different.
 *
 * Comment lines are indicated by a `#' in column 1.
 */

/*
 * Here's the scoop concerning the user[.:]group feature:
 *
 * 1) set-group-option off.
 *
 *	a) user = root:	NO setuid() or setgid() is done
 *
 *	b) other:	setgid(primary group as found in passwd)
 *			initgroups(name, primary group)
 *			setuid()
 *
 * 2) set-group-option on.
 *
 *	a) user = root:	setgid(specified group)
 *			NO initgroups()
 *			NO setuid()
 *
 *	b) other:	setgid(specified group)
 *			initgroups(name, specified group)
 *			setuid()
 *
 */

#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/file.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>

#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>

137
#include <err.h>
138 139 140 141 142 143 144 145 146 147
#include <errno.h>
#include <ctype.h>
#include <signal.h>
#include <netdb.h>
#include <syslog.h>
#include <pwd.h>
#include <grp.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
148
#include <limits.h>
149 150 151 152 153 154
#include <string.h>
#include <login_cap.h>
#include <ifaddrs.h>
#include <rpc/rpc.h>
#include <rpc/pmap_clnt.h>
#include <rpcsvc/nfs_prot.h>
155
#include <event.h>
156 157
#include "pathnames.h"

158 159
#define MINIMUM(a, b)	(((a) < (b)) ? (a) : (b))

160 161 162 163 164
#define	TOOMANY		256		/* don't start more than TOOMANY */
#define	CNT_INTVL	60		/* servers in CNT_INTVL sec. */
#define	RETRYTIME	(60*10)		/* retry after bind or server fail */

int	 debug = 0;
165
int	 maxsock;
166 167 168 169 170 171 172 173 174 175 176
int	 toomany = TOOMANY;
int	 timingout;
struct	 servent *sp;
uid_t	 uid;

#ifndef OPEN_MAX
#define OPEN_MAX	64
#endif

/* Reserve some descriptors, 3 stdio + at least: 1 log, 1 conf. file */
#define FD_MARGIN	(8)
177
rlim_t	rlim_nofile_cur = OPEN_MAX;
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

struct rlimit	rlim_nofile;

struct	servtab {
	char	*se_hostaddr;		/* host address to listen on */
	char	*se_service;		/* name of service */
	int	se_socktype;		/* type of socket to use */
	int	se_family;		/* address family */
	char	*se_proto;		/* protocol used */
	int	se_rpcprog;		/* rpc program number */
	int	se_rpcversl;		/* rpc program lowest version */
	int	se_rpcversh;		/* rpc program highest version */
#define isrpcservice(sep)	((sep)->se_rpcversl != 0)
	pid_t	se_wait;		/* single threaded server */
	short	se_checked;		/* looked at during merge */
	char	*se_user;		/* user name to run as */
	char	*se_group;		/* group name to run as */
	struct	biltin *se_bi;		/* if built-in, description */
	char	*se_server;		/* server program */
#define	MAXARGV 20
	char	*se_argv[MAXARGV+1];	/* program arguments */
	int	se_fd;			/* open descriptor */
	union {
		struct	sockaddr se_un_ctrladdr;
		struct	sockaddr_in se_un_ctrladdr_in;
		struct	sockaddr_in6 se_un_ctrladdr_in6;
		struct	sockaddr_un se_un_ctrladdr_un;
		struct	sockaddr_storage se_un_ctrladdr_storage;
	} se_un;			/* bound address */
#define se_ctrladdr	se_un.se_un_ctrladdr
#define se_ctrladdr_in	se_un.se_un_ctrladdr_in
#define se_ctrladdr_in6	se_un.se_un_ctrladdr_in6
#define se_ctrladdr_un	se_un.se_un_ctrladdr_un
#define se_ctrladdr_storage	se_un.se_un_ctrladdr_storage
	int	se_ctrladdr_size;
	int	se_max;			/* max # of instances of this service */
	int	se_count;		/* number started since se_time */
	struct	timeval se_time;	/* start of se_count */
	struct	servtab *se_next;
217
	struct	event se_event;
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
} *servtab;

void echo_stream(int, struct servtab *);
void discard_stream(int, struct servtab *);
void machtime_stream(int, struct servtab *);
void daytime_stream(int, struct servtab *);
void chargen_stream(int, struct servtab *);
void echo_dg(int, struct servtab *);
void discard_dg(int, struct servtab *);
void machtime_dg(int, struct servtab *);
void daytime_dg(int, struct servtab *);
void chargen_dg(int, struct servtab *);

struct biltin {
	char	*bi_service;		/* internally provided service name */
	int	bi_socktype;		/* type of socket supported */
	short	bi_fork;		/* 1 if should fork before call */
	short	bi_wait;		/* 1 if should wait for child */
	void	(*bi_fn)(int, struct servtab *);
} biltins[] = {
	/* Echo received data */
	{ "echo",	SOCK_STREAM,	1, 0,	echo_stream },
	{ "echo",	SOCK_DGRAM,	0, 0,	echo_dg },

	/* Internet /dev/null */
	{ "discard",	SOCK_STREAM,	1, 0,	discard_stream },
	{ "discard",	SOCK_DGRAM,	0, 0,	discard_dg },

	/* Return 32 bit time since 1900 */
	{ "time",	SOCK_STREAM,	0, 0,	machtime_stream },
	{ "time",	SOCK_DGRAM,	0, 0,	machtime_dg },

	/* Return human-readable time */
	{ "daytime",	SOCK_STREAM,	0, 0,	daytime_stream },
	{ "daytime",	SOCK_DGRAM,	0, 0,	daytime_dg },

	/* Familiar character generator */
	{ "chargen",	SOCK_STREAM,	1, 0,	chargen_stream },
	{ "chargen",	SOCK_DGRAM,	0, 0,	chargen_dg },

	{ 0 }
};

261 262 263 264 265 266 267 268 269 270 271 272 273
struct event evsig_alrm;
struct event evsig_hup;
struct event evsig_chld;
struct event evsig_term;
struct event evsig_int;

void	config(int, short, void *);
void	reap(int, short, void *);
void	retry(int, short, void *);
void	die(int, short, void *);

void	spawn(int, short, void *);
void	gettcp(int, short, void *);
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
int	setconfig(void);
void	endconfig(void);
void	register_rpc(struct servtab *);
void	unregister_rpc(struct servtab *);
void	freeconfig(struct servtab *);
void	print_service(char *, struct servtab *);
void	setup(struct servtab *);
struct servtab *getconfigent(void);
int	bump_nofile(void);
struct servtab *enter(struct servtab *);
int	matchconf(struct servtab *, struct servtab *);
int	dg_broadcast(struct in_addr *in);

#define NUMINT	(sizeof(intab) / sizeof(struct inent))
char	*CONFIG = _PATH_INETDCONF;

290 291 292 293 294
int		dg_badinput(struct sockaddr *sa);
void		inetd_setproctitle(char *a, int s);
void		initring(void);
u_int32_t	machtime(void);

295 296 297
int
main(int argc, char *argv[])
{
298 299
	int ch;

300 301 302 303 304 305 306 307 308 309
	while ((ch = getopt(argc, argv, "dR:")) != -1)
		switch (ch) {
		case 'd':
			debug = 1;
			break;
		case 'R': {	/* invocation rate */
			char *p;
			int val;

			val = strtoul(optarg, &p, 0);
310
			if (val >= 1 && *p == '\0') {
311 312 313 314 315 316 317 318 319 320
				toomany = val;
				break;
			}
			syslog(LOG_ERR,
			    "-R %s: bad value for service invocation rate",
			    optarg);
			break;
		}
		case '?':
		default:
321
			fprintf(stderr,
322
			    "usage: inetd [-d] [-R rate] [configuration_file]\n");
323 324 325 326 327 328 329 330 331 332 333
			exit(1);
		}
	argc -= optind;
	argv += optind;

	uid = getuid();
	if (uid != 0)
		CONFIG = NULL;
	if (argc > 0)
		CONFIG = argv[0];
	if (CONFIG == NULL) {
334
		fprintf(stderr, "inetd: non-root must specify a config file\n");
335 336
		exit(1);
	}
337
	if (argc > 1) {
338
		fprintf(stderr, "inetd: more than one argument specified\n");
339 340
		exit(1);
	}
341

342
	umask(022);
343 344 345 346 347 348
	if (debug == 0) {
		daemon(0, 0);
		if (uid == 0)
			(void) setlogin("");
	}

349 350 351
	if (pledge("stdio rpath cpath getpw dns inet unix proc exec id", NULL) == -1)
		err(1, "pledge");

352 353 354 355 356 357 358
	if (uid == 0) {
		gid_t gid = getgid();

		/* If run by hand, ensure groups vector gets trashed */
		setgroups(1, &gid);
	}

359
	openlog("inetd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
360 361 362 363 364 365 366 367 368

	if (getrlimit(RLIMIT_NOFILE, &rlim_nofile) < 0) {
		syslog(LOG_ERR, "getrlimit: %m");
	} else {
		rlim_nofile_cur = rlim_nofile.rlim_cur;
		if (rlim_nofile_cur == RLIM_INFINITY)	/* ! */
			rlim_nofile_cur = OPEN_MAX;
	}

369
	event_init();
370

371 372
	signal_set(&evsig_alrm, SIGALRM, retry, NULL);
	signal_add(&evsig_alrm, NULL);
373

374
	config(0, 0, NULL);
375

376 377 378 379 380 381 382 383
	signal_set(&evsig_hup, SIGHUP, config, NULL);
	signal_add(&evsig_hup, NULL);
	signal_set(&evsig_chld, SIGCHLD, reap, NULL);
	signal_add(&evsig_chld, NULL);
	signal_set(&evsig_term, SIGTERM, die, NULL);
	signal_add(&evsig_term, NULL);
	signal_set(&evsig_int, SIGINT, die, NULL);
	signal_add(&evsig_int, NULL);
384

385
	signal(SIGPIPE, SIG_IGN);
386

387 388 389
	event_dispatch();

	return (0);
390 391
}

392 393
void
gettcp(int fd, short events, void *xsep)
394
{
395
	struct servtab *sep = xsep;
396 397
	int ctrl;

398 399 400
	if (debug)
		fprintf(stderr, "someone wants %s\n", sep->se_service);

401 402 403 404
	ctrl = accept(sep->se_fd, NULL, NULL);
	if (debug)
		fprintf(stderr, "accept, ctrl %d\n", ctrl);
	if (ctrl < 0) {
405 406 407 408
		if (errno != EWOULDBLOCK && errno != EINTR &&
		    errno != ECONNABORTED)
			syslog(LOG_WARNING, "accept (for %s): %m",
			    sep->se_service);
409
		return;
410 411 412 413 414 415 416 417 418 419
	}
	if ((sep->se_family == AF_INET || sep->se_family == AF_INET6) &&
	    sep->se_socktype == SOCK_STREAM) {
		struct sockaddr_storage peer;
		socklen_t plen = sizeof(peer);
		char sbuf[NI_MAXSERV];

		if (getpeername(ctrl, (struct sockaddr *)&peer, &plen) < 0) {
			syslog(LOG_WARNING, "could not getpeername");
			close(ctrl);
420
			return;
421 422 423
		}
		if (getnameinfo((struct sockaddr *)&peer, plen, NULL, 0,
		    sbuf, sizeof(sbuf), NI_NUMERICSERV) == 0 &&
424
		    strtonum(sbuf, 1, USHRT_MAX, NULL) == 20) {
425 426 427 428
			/*
			 * ignore things that look like ftp bounce
			 */
			close(ctrl);
429
			return;
430 431 432
		}
	}

433 434
	spawn(ctrl, 0, sep);
}
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462

int
dg_badinput(struct sockaddr *sa)
{
	struct in_addr in;
	struct in6_addr *in6;
	u_int16_t port;

	switch (sa->sa_family) {
	case AF_INET:
		in.s_addr = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr);
		port = ntohs(((struct sockaddr_in *)sa)->sin_port);
	v4chk:
		if (IN_MULTICAST(in.s_addr))
			goto bad;
		switch ((in.s_addr & 0xff000000) >> 24) {
		case 0: case 127: case 255:
			goto bad;
		}
		if (dg_broadcast(&in))
			goto bad;
		break;
	case AF_INET6:
		in6 = &((struct sockaddr_in6 *)sa)->sin6_addr;
		port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
		if (IN6_IS_ADDR_MULTICAST(in6) || IN6_IS_ADDR_UNSPECIFIED(in6))
			goto bad;
		/*
463
		 * OpenBSD does not support IPv4 mapped address (RFC2553
464 465 466 467 468 469 470 471 472 473 474
		 * inbound behavior) at all.  We should drop it.
		 */
		if (IN6_IS_ADDR_V4MAPPED(in6))
			goto bad;
		if (IN6_IS_ADDR_V4COMPAT(in6)) {
			memcpy(&in, &in6->s6_addr[12], sizeof(in));
			in.s_addr = ntohl(in.s_addr);
			goto v4chk;
		}
		break;
	default:
475 476
		/* Unsupported AF */
		goto bad;
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
	}

	if (port < IPPORT_RESERVED || port == NFS_PORT)
		goto bad;

	return (0);

bad:
	return (1);
}

int
dg_broadcast(struct in_addr *in)
{
	struct ifaddrs *ifa, *ifap;
	struct sockaddr_in *sin;

	if (getifaddrs(&ifap) < 0)
		return (0);
	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr->sa_family != AF_INET ||
		    (ifa->ifa_flags & IFF_BROADCAST) == 0)
			continue;
		sin = (struct sockaddr_in *)ifa->ifa_broadaddr;
		if (sin->sin_addr.s_addr == in->s_addr) {
			freeifaddrs(ifap);
			return (1);
		}
	}
	freeifaddrs(ifap);
	return (0);
}

void
511
reap(int sig, short event, void *arg)
512 513 514 515 516 517 518 519 520
{
	struct servtab *sep;
	int status;
	pid_t pid;

	if (debug)
		fprintf(stderr, "reaping asked for\n");

	for (;;) {
521 522 523
		if ((pid = wait3(&status, WNOHANG, NULL)) <= 0) {
			if (pid == -1 && errno == EINTR)
				continue;
524
			break;
525
		}
526 527 528 529 530 531 532 533 534 535 536 537 538 539
		if (debug)
			fprintf(stderr, "%ld reaped, status %x\n",
			    (long)pid, status);
		for (sep = servtab; sep; sep = sep->se_next)
			if (sep->se_wait == pid) {
				if (WIFEXITED(status) && WEXITSTATUS(status))
					syslog(LOG_WARNING,
					    "%s: exit status %d",
					    sep->se_server, WEXITSTATUS(status));
				else if (WIFSIGNALED(status))
					syslog(LOG_WARNING,
					    "%s: exit signal %d",
					    sep->se_server, WTERMSIG(status));
				sep->se_wait = 1;
540
				event_add(&sep->se_event, NULL);
541 542 543 544 545 546 547 548
				if (debug)
					fprintf(stderr, "restored %s, fd %d\n",
					    sep->se_service, sep->se_fd);
			}
	}
}

void
549
config(int sig, short event, void *arg)
550 551
{
	struct servtab *sep, *cp, **sepp;
552
	int add;
553
	char protoname[11];
554 555 556

	if (!setconfig()) {
		syslog(LOG_ERR, "%s: %m", CONFIG);
557
		exit(1);
558 559 560 561 562 563 564 565 566
	}
	for (sep = servtab; sep; sep = sep->se_next)
		sep->se_checked = 0;
	cp = getconfigent();
	while (cp != NULL) {
		for (sep = servtab; sep; sep = sep->se_next)
			if (matchconf(sep, cp))
				break;
		add = 0;
567
		if (sep != NULL) {
568 569
			int i;

570
#define SWAP(type, a, b) {type c=(type)a; a=(type)b; b=(type)c;}
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602

			/*
			 * sep->se_wait may be holding the pid of a daemon
			 * that we're waiting for.  If so, don't overwrite
			 * it unless the config file explicitly says don't
			 * wait.
			 */
			if (cp->se_bi == 0 &&
			    (sep->se_wait == 1 || cp->se_wait == 0))
				sep->se_wait = cp->se_wait;
			SWAP(int, cp->se_max, sep->se_max);
			SWAP(char *, sep->se_user, cp->se_user);
			SWAP(char *, sep->se_group, cp->se_group);
			SWAP(char *, sep->se_server, cp->se_server);
			for (i = 0; i < MAXARGV; i++)
				SWAP(char *, sep->se_argv[i], cp->se_argv[i]);
#undef SWAP
			if (isrpcservice(sep))
				unregister_rpc(sep);
			sep->se_rpcversl = cp->se_rpcversl;
			sep->se_rpcversh = cp->se_rpcversh;
			freeconfig(cp);
			add = 1;
		} else {
			sep = enter(cp);
		}
		sep->se_checked = 1;

		switch (sep->se_family) {
		case AF_UNIX:
			if (sep->se_fd != -1)
				break;
603 604 605 606 607 608 609 610 611 612 613
			sep->se_ctrladdr_size =
			    strlcpy(sep->se_ctrladdr_un.sun_path,
			    sep->se_service,
			    sizeof sep->se_ctrladdr_un.sun_path);
			if (sep->se_ctrladdr_size >=
			    sizeof sep->se_ctrladdr_un.sun_path) {
				syslog(LOG_WARNING, "%s/%s: UNIX domain socket "
				    "path too long", sep->se_service,
				    sep->se_proto);
				goto serv_unknown;
			}
614
			sep->se_ctrladdr_un.sun_family = AF_UNIX;
615 616 617
			sep->se_ctrladdr_size +=
			    1 + sizeof sep->se_ctrladdr_un.sun_family;
			(void)unlink(sep->se_service);
618 619 620 621 622 623 624 625 626 627
			setup(sep);
			break;
		case AF_INET:
			sep->se_ctrladdr_in.sin_family = AF_INET;
			/* se_ctrladdr_in was set in getconfigent */
			sep->se_ctrladdr_size = sizeof sep->se_ctrladdr_in;

			if (isrpcservice(sep)) {
				struct rpcent *rp;

628 629
				sep->se_rpcprog = strtonum(sep->se_service,
				    1, USHRT_MAX, NULL);
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
				if (sep->se_rpcprog == 0) {
					rp = getrpcbyname(sep->se_service);
					if (rp == 0) {
						syslog(LOG_ERR,
						    "%s: unknown rpc service",
						    sep->se_service);
						goto serv_unknown;
					}
					sep->se_rpcprog = rp->r_number;
				}
				if (sep->se_fd == -1)
					setup(sep);
				if (sep->se_fd != -1)
					register_rpc(sep);
			} else {
645 646
				u_short port = htons(strtonum(sep->se_service,
				    1, USHRT_MAX, NULL));
647 648

				if (!port) {
649 650
					(void)strlcpy(protoname, sep->se_proto,
					    sizeof(protoname));
651 652
					if (isdigit((unsigned char)
					    protoname[strlen(protoname) - 1]))
653 654 655 656 657 658 659 660 661 662 663 664 665 666
						protoname[strlen(protoname) - 1] = '\0';
					sp = getservbyname(sep->se_service,
					    protoname);
					if (sp == 0) {
						syslog(LOG_ERR,
						    "%s/%s: unknown service",
						    sep->se_service, sep->se_proto);
						goto serv_unknown;
					}
					port = sp->s_port;
				}
				if (port != sep->se_ctrladdr_in.sin_port) {
					sep->se_ctrladdr_in.sin_port = port;
					if (sep->se_fd != -1) {
667
						event_del(&sep->se_event);
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
						(void) close(sep->se_fd);
					}
					sep->se_fd = -1;
				}
				if (sep->se_fd == -1)
					setup(sep);
			}
			break;
		case AF_INET6:
			sep->se_ctrladdr_in6.sin6_family = AF_INET6;
			/* se_ctrladdr_in was set in getconfigent */
			sep->se_ctrladdr_size = sizeof sep->se_ctrladdr_in6;

			if (isrpcservice(sep)) {
				struct rpcent *rp;

684 685
				sep->se_rpcprog = strtonum(sep->se_service,
				    1, USHRT_MAX, NULL);
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
				if (sep->se_rpcprog == 0) {
					rp = getrpcbyname(sep->se_service);
					if (rp == 0) {
						syslog(LOG_ERR,
						    "%s: unknown rpc service",
						    sep->se_service);
						goto serv_unknown;
					}
					sep->se_rpcprog = rp->r_number;
				}
				if (sep->se_fd == -1)
					setup(sep);
				if (sep->se_fd != -1)
					register_rpc(sep);
			} else {
701 702
				u_short port = htons(strtonum(sep->se_service,
				    1, USHRT_MAX, NULL));
703 704

				if (!port) {
705 706
					(void)strlcpy(protoname, sep->se_proto,
					    sizeof(protoname));
707 708
					if (isdigit((unsigned char)
					    protoname[strlen(protoname) - 1]))
709 710 711 712 713 714 715 716 717 718 719 720 721 722
						protoname[strlen(protoname) - 1] = '\0';
					sp = getservbyname(sep->se_service,
					    protoname);
					if (sp == 0) {
						syslog(LOG_ERR,
						    "%s/%s: unknown service",
						    sep->se_service, sep->se_proto);
						goto serv_unknown;
					}
					port = sp->s_port;
				}
				if (port != sep->se_ctrladdr_in6.sin6_port) {
					sep->se_ctrladdr_in6.sin6_port = port;
					if (sep->se_fd != -1) {
723
						event_del(&sep->se_event);
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
						(void) close(sep->se_fd);
					}
					sep->se_fd = -1;
				}
				if (sep->se_fd == -1)
					setup(sep);
			}
			break;
		}
	serv_unknown:
		if (cp->se_next != NULL) {
			struct servtab *tmp = cp;

			cp = cp->se_next;
			free(tmp);
		} else {
			free(cp);
			cp = getconfigent();
		}
		if (debug)
			print_service(add ? "REDO" : "ADD", sep);
	}
	endconfig();
	/*
	 * Purge anything not looked at above.
	 */
	sepp = &servtab;
	while ((sep = *sepp)) {
		if (sep->se_checked) {
			sepp = &sep->se_next;
			continue;
		}
		*sepp = sep->se_next;
		if (sep->se_fd != -1) {
758
			event_del(&sep->se_event);
759 760 761 762 763 764 765 766 767
			(void) close(sep->se_fd);
		}
		if (isrpcservice(sep))
			unregister_rpc(sep);
		if (sep->se_family == AF_UNIX)
			(void)unlink(sep->se_service);
		if (debug)
			print_service("FREE", sep);
		freeconfig(sep);
768
		free(sep);
769 770 771 772
	}
}

void
773
retry(int sig, short events, void *arg)
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
{
	struct servtab *sep;

	timingout = 0;
	for (sep = servtab; sep; sep = sep->se_next) {
		if (sep->se_fd == -1) {
			switch (sep->se_family) {
			case AF_UNIX:
			case AF_INET:
			case AF_INET6:
				setup(sep);
				if (sep->se_fd != -1 && isrpcservice(sep))
					register_rpc(sep);
				break;
			}
		}
	}
}

void
794
die(int sig, short events, void *arg)
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
{
	struct servtab *sep;

	for (sep = servtab; sep; sep = sep->se_next) {
		if (sep->se_fd == -1)
			continue;

		switch (sep->se_family) {
		case AF_UNIX:
			(void)unlink(sep->se_service);
			break;
		case AF_INET:
		case AF_INET6:
			if (sep->se_wait == 1 && isrpcservice(sep))
				unregister_rpc(sep);
			break;
		}
		(void)close(sep->se_fd);
	}
	exit(0);
}

void
setup(struct servtab *sep)
{
	int on = 1;
	int r;
822
	mode_t mask = 0;
823 824 825 826 827 828 829

	if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
		syslog(LOG_ERR, "%s/%s: socket: %m",
		    sep->se_service, sep->se_proto);
		return;
	}
#define	turnon(fd, opt) \
830
setsockopt(fd, SOL_SOCKET, opt, &on, sizeof (on))
831
	if (strncmp(sep->se_proto, "tcp", 3) == 0 && debug &&
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
	    turnon(sep->se_fd, SO_DEBUG) < 0)
		syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
	if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
		syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
#undef turnon
	if (isrpcservice(sep)) {
		struct passwd *pwd;

		/*
		 * for RPC services, attempt to use a reserved port
		 * if they are going to be running as root.
		 *
		 * Also, zero out the port for all RPC services; let bind()
		 * find one.
		 */
		sep->se_ctrladdr_in.sin_port = 0;
		if (sep->se_user && (pwd = getpwnam(sep->se_user)) &&
		    pwd->pw_uid == 0 && uid == 0)
			r = bindresvport(sep->se_fd, &sep->se_ctrladdr_in);
		else {
			r = bind(sep->se_fd, &sep->se_ctrladdr,
			    sep->se_ctrladdr_size);
			if (r == 0) {
				socklen_t len = sep->se_ctrladdr_size;
				int saveerrno = errno;

				/* update se_ctrladdr_in.sin_port */
				r = getsockname(sep->se_fd, &sep->se_ctrladdr,
				    &len);
				if (r <= 0)
					errno = saveerrno;
			}
		}
865 866 867
	} else {
		if (sep->se_family == AF_UNIX)
			mask = umask(0111);
868
		r = bind(sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size);
869 870 871
		if (sep->se_family == AF_UNIX)
			umask(mask);
	}
872 873 874 875 876 877 878 879 880 881 882 883 884 885
	if (r < 0) {
		syslog(LOG_ERR, "%s/%s: bind: %m",
		    sep->se_service, sep->se_proto);
		(void) close(sep->se_fd);
		sep->se_fd = -1;
		if (!timingout) {
			timingout = 1;
			alarm(RETRYTIME);
		}
		return;
	}
	if (sep->se_socktype == SOCK_STREAM)
		listen(sep->se_fd, 10);

886 887 888 889 890 891 892 893 894 895
	if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
		event_set(&sep->se_event, sep->se_fd, EV_READ|EV_PERSIST,
		    gettcp, sep);
	} else {
		event_set(&sep->se_event, sep->se_fd, EV_READ|EV_PERSIST,
		    spawn, sep);
	}

	event_add(&sep->se_event, NULL);

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
	if (sep->se_fd > maxsock) {
		maxsock = sep->se_fd;
		if (maxsock > rlim_nofile_cur - FD_MARGIN)
			bump_nofile();
	}
}

void
register_rpc(struct servtab *sep)
{
	socklen_t n;
	struct sockaddr_in sin;
	struct protoent *pp;

	if ((pp = getprotobyname(sep->se_proto+4)) == NULL) {
		syslog(LOG_ERR, "%s: getproto: %m",
		    sep->se_proto);
		return;
	}
	n = sizeof sin;
	if (getsockname(sep->se_fd, (struct sockaddr *)&sin, &n) < 0) {
		syslog(LOG_ERR, "%s/%s: getsockname: %m",
		    sep->se_service, sep->se_proto);
		return;
	}

	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
		if (debug)
			fprintf(stderr, "pmap_set: %u %u %u %u\n",
			    sep->se_rpcprog, n, pp->p_proto,
			    ntohs(sin.sin_port));
		(void)pmap_unset(sep->se_rpcprog, n);
		if (!pmap_set(sep->se_rpcprog, n, pp->p_proto, ntohs(sin.sin_port)))
			syslog(LOG_ERR, "%s %s: pmap_set: %u %u %u %u: %m",
			    sep->se_service, sep->se_proto,
			    sep->se_rpcprog, n, pp->p_proto,
			    ntohs(sin.sin_port));
	}
}

void
unregister_rpc(struct servtab *sep)
{
	int n;

	for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
		if (debug)
			fprintf(stderr, "pmap_unset(%u, %u)\n",
			    sep->se_rpcprog, n);
		if (!pmap_unset(sep->se_rpcprog, n))
			syslog(LOG_ERR, "pmap_unset(%u, %u)",
			    sep->se_rpcprog, n);
	}
}


struct servtab *
enter(struct servtab *cp)
{
	struct servtab *sep;

957
	sep = malloc(sizeof (*sep));
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
	if (sep == NULL) {
		syslog(LOG_ERR, "Out of memory.");
		exit(1);
	}
	*sep = *cp;
	sep->se_fd = -1;
	sep->se_rpcprog = -1;
	sep->se_next = servtab;
	servtab = sep;
	return (sep);
}

int
matchconf(struct servtab *old, struct servtab *new)
{
	if (strcmp(old->se_service, new->se_service) != 0)
		return (0);

	if (strcmp(old->se_hostaddr, new->se_hostaddr) != 0)
		return (0);

	if (strcmp(old->se_proto, new->se_proto) != 0)
		return (0);

	/*
	 * If the new servtab is bound to a specific address, check that the
	 * old servtab is bound to the same entry. If the new service is not
	 * bound to a specific address then the check of se_hostaddr above
	 * is sufficient.
	 */

	if (old->se_family == AF_INET && new->se_family == AF_INET &&
	    bcmp(&old->se_ctrladdr_in.sin_addr,
	    &new->se_ctrladdr_in.sin_addr,
	    sizeof(new->se_ctrladdr_in.sin_addr)) != 0)
		return (0);

	if (old->se_family == AF_INET6 && new->se_family == AF_INET6 &&
	    bcmp(&old->se_ctrladdr_in6.sin6_addr,
	    &new->se_ctrladdr_in6.sin6_addr,
	    sizeof(new->se_ctrladdr_in6.sin6_addr)) != 0)
		return (0);
	if (old->se_family == AF_INET6 && new->se_family == AF_INET6 &&
	    old->se_ctrladdr_in6.sin6_scope_id !=
	    new->se_ctrladdr_in6.sin6_scope_id)
		return (0);

	return (1);
}

FILE		*fconfig = NULL;
char		line[1024];
char		*defhost;
char		*skip(char **, int);
char		*nextline(FILE *);
char		*newstr(char *);
struct servtab	*dupconfig(struct servtab *);

int
setconfig(void)
{
1019
	free(defhost);
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
	defhost = newstr("*");
	if (fconfig != NULL) {
		fseek(fconfig, 0L, SEEK_SET);
		return (1);
	}
	fconfig = fopen(CONFIG, "r");
	return (fconfig != NULL);
}

void
endconfig(void)
{
	if (fconfig) {
		(void) fclose(fconfig);
		fconfig = NULL;
	}
	if (defhost) {
		free(defhost);
		defhost = 0;
	}
}

struct servtab *
getconfigent(void)
{
1045 1046
	struct servtab *sep, *tsep;
	char *arg, *cp, *hostdelim, *s;
1047 1048
	int argc;

1049
	sep = calloc(1, sizeof(struct servtab));
1050
	if (sep == NULL) {
1051
		syslog(LOG_ERR, "calloc: %m");
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
		exit(1);
	}
more:
	freeconfig(sep);

	while ((cp = nextline(fconfig)) && *cp == '#')
		;
	if (cp == NULL) {
		free(sep);
		return (NULL);
	}

1064
	memset(sep, 0, sizeof *sep);
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
	arg = skip(&cp, 0);
	if (arg == NULL) {
		/* A blank line. */
		goto more;
	}

	/* Check for a host name. */
	hostdelim = strrchr(arg, ':');
	if (hostdelim) {
		*hostdelim = '\0';
		if (arg[0] == '[' && hostdelim > arg && hostdelim[-1] == ']') {
			hostdelim[-1] = '\0';
			sep->se_hostaddr = newstr(arg + 1);
1078 1079 1080
		} else if (hostdelim == arg)
			sep->se_hostaddr = newstr("*");
		else
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
			sep->se_hostaddr = newstr(arg);
		arg = hostdelim + 1;
		/*
		 * If the line is of the form `host:', then just change the
		 * default host for the following lines.
		 */
		if (*arg == '\0') {
			arg = skip(&cp, 0);
			if (cp == NULL) {
				free(defhost);
				defhost = newstr(sep->se_hostaddr);
				goto more;
			}
		}
	} else
		sep->se_hostaddr = newstr(defhost);

	sep->se_service = newstr(arg);
	if ((arg = skip(&cp, 1)) == NULL)
		goto more;

	if (strcmp(arg, "stream") == 0)
		sep->se_socktype = SOCK_STREAM;
	else if (strcmp(arg, "dgram") == 0)
		sep->se_socktype = SOCK_DGRAM;
	else if (strcmp(arg, "rdm") == 0)
		sep->se_socktype = SOCK_RDM;
	else if (strcmp(arg, "seqpacket") == 0)
		sep->se_socktype = SOCK_SEQPACKET;
	else if (strcmp(arg, "raw") == 0)
		sep->se_socktype = SOCK_RAW;
	else
		sep->se_socktype = -1;

	if ((arg = skip(&cp, 1)) == NULL)
		goto more;

	sep->se_proto = newstr(arg);

	if (strcmp(sep->se_proto, "unix") == 0) {
		sep->se_family = AF_UNIX;
	} else {
1123 1124
		int s;

1125 1126 1127
		sep->se_family = AF_INET;
		if (sep->se_proto[strlen(sep->se_proto) - 1] == '6')
			sep->se_family = AF_INET6;
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

		/* check if the family is supported */
		s = socket(sep->se_family, SOCK_DGRAM, 0);
		if (s < 0) {
			syslog(LOG_WARNING, "%s/%s: %s: the address family is "
			    "not supported by the kernel", sep->se_service,
			    sep->se_proto, sep->se_hostaddr);
			goto more;
		}
		close(s);

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
		if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
			char *cp, *ccp;
			long l;

			cp = strchr(sep->se_service, '/');
			if (cp == 0) {
				syslog(LOG_ERR, "%s: no rpc version",
				    sep->se_service);
				goto more;
			}
			*cp++ = '\0';
			l = strtol(cp, &ccp, 0);
			if (ccp == cp || l < 0 || l > INT_MAX) {
		badafterall:
				syslog(LOG_ERR, "%s/%s: bad rpc version",
				    sep->se_service, cp);
				goto more;
			}
			sep->se_rpcversl = sep->se_rpcversh = l;
			if (*ccp == '-') {
				cp = ccp + 1;
				l = strtol(cp, &ccp, 0);
				if (ccp == cp || l < 0 || l > INT_MAX ||
				    l < sep->se_rpcversl || *ccp)
					goto badafterall;
				sep->se_rpcversh = l;
			} else if (*ccp != '\0')
				goto badafterall;
		}
	}
	arg = skip(&cp, 1);
	if (arg == NULL)
		goto more;

	s = strchr(arg, '.');
	if (s) {
		char *p;

		*s++ = '\0';
		sep->se_max = strtoul(s, &p, 0);
		if (sep->se_max < 1 || *p) {
			syslog(LOG_ERR,
			    "%s: illegal max field \"%s\", setting to %d",
			    sep->se_service, s, toomany);
			sep->se_max = toomany;
		}
	} else
		sep->se_max = toomany;

	sep->se_wait = strcmp(arg, "wait") == 0;
	if ((arg = skip(&cp, 1)) == NULL)
		goto more;
	sep->se_user = newstr(arg);
	arg = strchr(sep->se_user, '.');
	if (arg == NULL)
		arg = strchr(sep->se_user, ':');
	if (arg) {
		*arg++ = '\0';
		sep->se_group = newstr(arg);
	}
	if ((arg = skip(&cp, 1)) == NULL)
		goto more;

	sep->se_server = newstr(arg);
	if (strcmp(sep->se_server, "internal") == 0) {
		struct biltin *bi;

		for (bi = biltins; bi->bi_service; bi++)
			if (bi->bi_socktype == sep->se_socktype &&
			    strcmp(bi->bi_service, sep->se_service) == 0)
				break;
		if (bi->bi_service == 0) {
			syslog(LOG_ERR, "internal service %s unknown",
			    sep->se_service);
			goto more;
		}
		sep->se_bi = bi;
		sep->se_wait = bi->bi_wait;
	} else
		sep->se_bi = NULL;
	argc = 0;
	for (arg = skip(&cp, 0); cp; arg = skip(&cp, 0)) {
		if (argc < MAXARGV)
			sep->se_argv[argc++] = newstr(arg);
	}
1224 1225 1226 1227 1228 1229 1230
	if (argc == 0 && sep->se_bi == NULL) {
		if ((arg = strrchr(sep->se_server, '/')) != NULL)
			arg++;
		else
			arg = sep->se_server;
		sep->se_argv[argc++] = newstr(arg);
	}
1231 1232 1233 1234
	while (argc <= MAXARGV)
		sep->se_argv[argc++] = NULL;

	/*
1235 1236
	 * Resolve each hostname in the se_hostaddr list (if any)
	 * and create a new entry for each resolved address.
1237
	 */
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
	if (sep->se_hostaddr != NULL && strcmp(sep->se_proto, "unix") != 0) {
		struct addrinfo hints, *res0, *res;
		char *host, *hostlist0, *hostlist, *port;
		int error;

		hostlist = hostlist0 = sep->se_hostaddr;
		sep->se_hostaddr = NULL;
		sep->se_checked = -1;
		while ((host = strsep(&hostlist, ",")) != NULL) {
			if (*host == '\0')
				continue;
1249 1250

			memset(&hints, 0, sizeof(hints));
1251 1252
			hints.ai_family = sep->se_family;
			hints.ai_socktype = sep->se_socktype;
1253 1254
			hints.ai_flags = AI_PASSIVE;
			port = "0";
1255 1256
			error = getaddrinfo(strcmp(host, "*") ? host : NULL,
			    port, &hints, &res0);
1257 1258
			if (error) {
				syslog(LOG_ERR, "%s/%s: %s: %s",
1259 1260 1261
				    sep->se_service, sep->se_proto,
				    host, gai_strerror(error));
				continue;
1262 1263 1264
			}
			for (res = res0; res; res = res->ai_next) {
				if (res->ai_addrlen >
1265
				    sizeof(sep->se_ctrladdr_storage))
1266 1267
					continue;
				/*
1268 1269
				 * If sep is unused, store host in there.
				 * Otherwise, dup a new entry and prepend it.
1270
				 */
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
				if (sep->se_checked == -1) {
					sep->se_checked = 0;
				} else {
					tsep = dupconfig(sep);
					tsep->se_next = sep;
					sep = tsep;
				}
				sep->se_hostaddr = newstr(host);
				memcpy(&sep->se_ctrladdr_storage,
				    res->ai_addr, res->ai_addrlen);
				sep->se_ctrladdr_size = res->ai_addrlen;
1282 1283 1284
			}
			freeaddrinfo(res0);
		}
1285 1286 1287
		free(hostlist0);
		if (sep->se_checked == -1)
			goto more;	/* no resolvable names/addresses */
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
	}

	return (sep);
}

void
freeconfig(struct servtab *cp)
{
	int i;

1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
	free(cp->se_hostaddr);
	cp->se_hostaddr = NULL;
	free(cp->se_service);
	cp->se_service = NULL;
	free(cp->se_proto);
	cp->se_proto = NULL;
	free(cp->se_user);
	cp->se_user = NULL;
	free(cp->se_group);
	cp->se_group = NULL;
	free(cp->se_server);
	cp->se_server = NULL;
	for (i = 0; i < MAXARGV; i++) {
		free(cp->se_argv[i]);
		cp->se_argv[i] = NULL;
	}
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
}

char *
skip(char **cpp, int report)
{
	char *cp = *cpp;
	char *start;

erp:
	if (*cpp == NULL) {
		if (report)
			syslog(LOG_ERR, "syntax error in inetd config file");
		return (NULL);
	}

again:
	while (*cp == ' ' || *cp == '\t')
		cp++;
	if (*cp == '\0') {
		int c;

		c = getc(fconfig);
		(void) ungetc(c, fconfig);
		if (c == ' ' || c == '\t')
			if ((cp = nextline(fconfig)))
				goto again;
		*cpp = NULL;
		goto erp;
	}
	start = cp;
	while (*cp && *cp != ' ' && *cp != '\t')
		cp++;
	if (*cp != '\0')
		*cp++ = '\0';
	if ((*cpp = cp) == NULL)
		goto erp;

	return (start);
}

char *
nextline(FILE *fd)
{
	if (fgets(line, sizeof (line), fd) == NULL)
		return (NULL);
1359
	line[strcspn(line, "\n")] = '\0';
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
	return (line);
}

char *
newstr(char *cp)
{
	if ((cp = strdup(cp ? cp : "")))
		return(cp);
	syslog(LOG_ERR, "strdup: %m");
	exit(1);
}

struct servtab *
dupconfig(struct servtab *sep)
{
	struct servtab *newtab;
	int argc;

1378
	newtab = calloc(1, sizeof(struct servtab));
1379 1380

	if (newtab == NULL) {
1381
		syslog(LOG_ERR, "calloc: %m");
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
		exit(1);
	}

	newtab->se_service = sep->se_service ? newstr(sep->se_service) : NULL;
	newtab->se_socktype = sep->se_socktype;
	newtab->se_family = sep->se_family;
	newtab->se_proto = sep->se_proto ? newstr(sep->se_proto) : NULL;
	newtab->se_rpcprog = sep->se_rpcprog;
	newtab->se_rpcversl = sep->se_rpcversl;
	newtab->se_rpcversh = sep->se_rpcversh;
	newtab->se_wait = sep->se_wait;
	newtab->se_user = sep->se_user ? newstr(sep->se_user) : NULL;
	newtab->se_group = sep->se_group ? newstr(sep->se_group) : NULL;
	newtab->se_bi = sep->se_bi;
	newtab->se_server = sep->se_server ? newstr(sep->se_server) : 0;

	for (argc = 0; argc <= MAXARGV; argc++)
		newtab->se_argv[argc] = sep->se_argv[argc] ?
		    newstr(sep->se_argv[argc]) : NULL;
	newtab->se_max = sep->se_max;

	return (newtab);
}

void
inetd_setproctitle(char *a, int s)
{
	socklen_t size;
	struct sockaddr_storage ss;
	char hbuf[NI_MAXHOST];

	size = sizeof(ss);
	if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
		if (getnameinfo((struct sockaddr *)&ss, size, hbuf,
		    sizeof(hbuf), NULL, 0, NI_NUMERICHOST) == 0)
			setproctitle("-%s [%s]", a, hbuf);
		else
			setproctitle("-%s [?]", a);
	} else
		setproctitle("-%s", a);
}

int
bump_nofile(void)
{
#define FD_CHUNK	32

	struct rlimit rl;

	if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
		syslog(LOG_ERR, "getrlimit: %m");
		return -1;
	}
1435 1436
	rl.rlim_cur = MINIMUM(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
	rl.rlim_cur = MINIMUM(FD_SETSIZE, rl.rlim_cur + FD_CHUNK);
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
	if (rl.rlim_cur <= rlim_nofile_cur) {
		syslog(LOG_ERR,
		    "bump_nofile: cannot extend file limit, max = %d",
		    (int)rl.rlim_cur);
		return -1;
	}

	if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
		syslog(LOG_ERR, "setrlimit: %m");
		return -1;
	}

	rlim_nofile_cur = rl.rlim_cur;
	return 0;
}

/*
 * Internet services provided internally by inetd:
 */
#define	BUFSIZE	4096

void
echo_stream(int s, struct servtab *sep)
{
	char buffer[BUFSIZE];
	int i;

	inetd_setproctitle(sep->se_service, s);
	while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
	    write(s, buffer, i) > 0)
		;
	exit(0);
}

void
echo_dg(int s, struct servtab *sep)
{
	char buffer[BUFSIZE];
1475 1476
	int i;
	socklen_t size;
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
	struct sockaddr_storage ss;

	size = sizeof(ss);
	if ((i = recvfrom(s, buffer, sizeof(buffer), 0,
	    (struct sockaddr *)&ss, &size)) < 0)
		return;
	if (dg_badinput((struct sockaddr *)&ss))
		return;
	(void) sendto(s, buffer, i, 0, (struct sockaddr *)&ss, size);
}

void
discard_stream(int s, struct servtab *sep)
{
	char buffer[BUFSIZE];

	inetd_setproctitle(sep->se_service, s);
	while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
	    errno == EINTR)
		;
	exit(0);
}

void
discard_dg(int s, struct servtab *sep)
{
	char buffer[BUFSIZE];

	(void) read(s, buffer, sizeof(buffer));
}

#include <ctype.h>
#define LINESIZ 72
char ring[128];
char *endring;

void
initring(void)
{
	int i;

	endring = ring;

	for (i = 0; i <= sizeof ring; ++i)
1521
		if (isprint((unsigned char)i))
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
			*endring++ = i;
}

void
chargen_stream(int s, struct servtab *sep)
{
	char *rs;
	int len;
	char text[LINESIZ+2];

	inetd_setproctitle(sep->se_service, s);

	if (!endring) {
		initring();
		rs = ring;
	}

	text[LINESIZ] = '\r';
	text[LINESIZ + 1] = '\n';
	for (rs = ring;;) {
		if ((len = endring - rs) >= LINESIZ)
			memmove(text, rs, LINESIZ);
		else {
			memmove(text, rs, len);
			memmove(text + len, ring, LINESIZ - len);
		}
		if (++rs == endring)
			rs = ring;
		if (write(s, text, sizeof(text)) != sizeof(text))
			break;
	}
	exit(0);
}

void
chargen_dg(int s, struct servtab *sep)
{
	struct sockaddr_storage ss;
	static char *rs;
1561 1562
	int len;
	socklen_t size;
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
	char text[LINESIZ+2];

	if (endring == 0) {
		initring();
		rs = ring;
	}

	size = sizeof(ss);
	if (recvfrom(s, text, sizeof(text), 0, (struct sockaddr *)&ss,
	    &size) < 0)
		return;
	if (dg_badinput((struct sockaddr *)&ss))
		return;

	if ((len = endring - rs) >= LINESIZ)
		memmove(text, rs, LINESIZ);
	else {
		memmove(text, rs, len);
		memmove(text + len, ring, LINESIZ - len);
	}
	if (++rs == endring)
		rs = ring;
	text[LINESIZ] = '\r';
	text[LINESIZ + 1] = '\n';
	(void) sendto(s, text, sizeof(text), 0, (struct sockaddr *)&ss, size);
}

/*
 * Return a machine readable date and time, in the form of the
 * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
 * returns the number of seconds since midnight, Jan 1, 1970,
 * we must add 2208988800 seconds to this figure to make up for
 * some seventy years Bell Labs was asleep.
 */
u_int32_t
machtime(void)
{
	struct timeval tv;

	if (gettimeofday(&tv, NULL) < 0)
		return (0L);

	return (htonl((u_int32_t)tv.tv_sec + 2208988800UL));
}

void
1609
machtime_stream(int s, struct servtab *sep)
1610 1611 1612 1613
{
	u_int32_t result;

	result = machtime();
1614
	(void) write(s, &result, sizeof(result));
1615 1616 1617 1618 1619 1620 1621
}

void
machtime_dg(int s, struct servtab *sep)
{
	u_int32_t result;
	struct sockaddr_storage ss;
1622
	socklen_t size;
1623 1624

	size = sizeof(ss);
1625
	if (recvfrom(s, &result, sizeof(result), 0,
1626 1627 1628 1629 1630
	    (struct sockaddr *)&ss, &size) < 0)
		return;
	if (dg_badinput((struct sockaddr *)&ss))
		return;
	result = machtime();
1631
	(void) sendto(s, &result, sizeof(result), 0,
1632 1633 1634 1635 1636 1637 1638 1639
	    (struct sockaddr *)&ss, size);
}

/* Return human-readable time of day */
void
daytime_stream(int s, struct servtab *sep)
{
	char buffer[256];
1640
	time_t clock;
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652

	clock = time(NULL);

	(void) snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
	(void) write(s, buffer, strlen(buffer));
}

/* Return human-readable time of day */
void
daytime_dg(int s, struct servtab *sep)
{
	char buffer[256];
1653
	time_t clock;
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
	struct sockaddr_storage ss;
	socklen_t size;

	clock = time(NULL);

	size = sizeof(ss);
	if (recvfrom(s, buffer, sizeof(buffer), 0, (struct sockaddr *)&ss,
	    &size) < 0)
		return;
	if (dg_badinput((struct sockaddr *)&ss))
		return;
	(void) snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
	(void) sendto(s, buffer, strlen(buffer), 0, (struct sockaddr *)&ss,
	    size);
}

/*
 * print_service:
 *	Dump relevant information to stderr
 */
void
print_service(char *action, struct servtab *sep)
{
	if (strcmp(sep->se_hostaddr, "*") == 0)
		fprintf(stderr, "%s: %s ", action, sep->se_service);
	else
		fprintf(stderr, "%s: %s:%s ", action, sep->se_hostaddr,
		    sep->se_service);

	if (isrpcservice(sep))
		fprintf(stderr, "rpcprog=%d, rpcvers=%d/%d, proto=%s,",
		    sep->se_rpcprog, sep->se_rpcversh,
		    sep->se_rpcversl, sep->se_proto);
	else
		fprintf(stderr, "proto=%s,", sep->se_proto);

	fprintf(stderr,
1691
	    " wait.max=%d.%d user:group=%s:%s builtin=%lx server=%s\n",
1692 1693 1694 1695 1696 1697
	    sep->se_wait, sep->se_max, sep->se_user,
	    sep->se_group ? sep->se_group : "wheel",
	    (long)sep->se_bi, sep->se_server);
}

void
1698
spawn(int ctrl, short events, void *xsep)
1699
{
1700
	struct servtab *sep = xsep;
1701 1702 1703 1704 1705 1706
	struct passwd *pwd;
	int tmpint, dofork;
	struct group *grp = NULL;
	char buf[50];
	pid_t pid;

1707 1708 1709
	if (debug)
		fprintf(stderr, "someone wants %s\n", sep->se_service);

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
	pid = 0;
	dofork = (sep->se_bi == 0 || sep->se_bi->bi_fork);
	if (dofork) {
		if (sep->se_count++ == 0)
		    (void)gettimeofday(&sep->se_time, NULL);
		else if (sep->se_count >= sep->se_max) {
			struct timeval now;

			(void)gettimeofday(&now, NULL);
			if (now.tv_sec - sep->se_time.tv_sec >
			    CNT_INTVL) {
				sep->se_time = now;
				sep->se_count = 1;
			} else {
				if (!sep->se_wait &&
				    sep->se_socktype == SOCK_STREAM)
					close(ctrl);
				if (sep->se_family == AF_INET &&
				    ntohs(sep->se_ctrladdr_in.sin_port) >=
				    IPPORT_RESERVED) {
					/*
					 * Cannot close it -- there are
					 * thieves on the system.
					 * Simply ignore the connection.
					 */
					--sep->se_count;
					return;
				}
				syslog(LOG_ERR,
				    "%s/%s server failing (looping), service terminated",
				    sep->se_service, sep->se_proto);
				if (!sep->se_wait &&
				    sep->se_socktype == SOCK_STREAM)
					close(ctrl);
1744
				event_del(&sep->se_event);
1745
				(void) close(sep->se_fd);
1746

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
				sep->se_fd = -1;
				sep->se_count = 0;
				if (!timingout) {
					timingout = 1;
					alarm(RETRYTIME);
				}
				return;
			}
		}
		pid = fork();
	}
	if (pid < 0) {
		syslog(LOG_ERR, "fork: %m");
		if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
			close(ctrl);
		sleep(1);
		return;
	}
1765 1766 1767 1768

	if (pledge("stdio rpath getpw inet proc exec id", NULL) == -1)
		err(1, "pledge");

1769 1770
	if (pid && sep->se_wait) {
		sep->se_wait = pid;
1771
		event_del(&sep->se_event);
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
	}
	if (pid == 0) {
		if (sep->se_bi)
			(*sep->se_bi->bi_fn)(ctrl, sep);
		else {
			if ((pwd = getpwnam(sep->se_user)) == NULL) {
				syslog(LOG_ERR,
				    "getpwnam: %s: No such user",
				    sep->se_user);
				if (sep->se_socktype != SOCK_STREAM)
					recv(0, buf, sizeof (buf), 0);
				exit(1);
			}
			if (setsid() <0)
				syslog(LOG_ERR, "%s: setsid: %m",
				    sep->se_service);
			if (sep->se_group &&
			    (grp = getgrnam(sep->se_group)) == NULL) {
				syslog(LOG_ERR,
				    "getgrnam: %s: No such group",
				    sep->se_group);
				if (sep->se_socktype != SOCK_STREAM)
					recv(0, buf, sizeof (buf), 0);
				exit(1);
			}
			if (uid != 0) {
				/* a user running private inetd */
				if (uid != pwd->pw_uid)
					exit(1);
			} else {
				tmpint = LOGIN_SETALL &
				    ~(LOGIN_SETGROUP|LOGIN_SETLOGIN);
				if (pwd->pw_uid)
					tmpint |= LOGIN_SETGROUP|LOGIN_SETLOGIN;
				if (sep->se_group) {
					pwd->pw_gid = grp->gr_gid;
					tmpint |= LOGIN_SETGROUP;
				}
				if (setusercontext(NULL, pwd, pwd->pw_uid,
				    tmpint) < 0) {
					syslog(LOG_ERR,
					    "%s/%s: setusercontext: %m",
					    sep->se_service, sep->se_proto);
					exit(1);
				}
			}
			if (debug)
1819
				fprintf(stderr, "%ld execv %s\n",
1820 1821 1822 1823 1824 1825 1826 1827
				    (long)getpid(), sep->se_server);
			if (ctrl != STDIN_FILENO) {
				dup2(ctrl, STDIN_FILENO);
				close(ctrl);
			}
			dup2(STDIN_FILENO, STDOUT_FILENO);
			dup2(STDIN_FILENO, STDERR_FILENO);
			closelog();
1828
			closefrom(3);
1829
			signal(SIGPIPE, SIG_DFL);
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
			execv(sep->se_server, sep->se_argv);
			if (sep->se_socktype != SOCK_STREAM)
				recv(0, buf, sizeof (buf), 0);
			syslog(LOG_ERR, "execv %s: %m", sep->se_server);
			exit(1);
		}
	}
	if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
		close(ctrl);
}