Clean up sysconf and associated headers.
[dragonfly.git] / usr.sbin / inetd / inetd.c
blobe775f32589cec203fb972eef7f5c28fb73e695fb
1 /*
2 * Copyright (c) 1983, 1991, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
33 * @(#) Copyright (c) 1983, 1991, 1993, 1994 The Regents of the University of California. All rights reserved.
34 * @(#)from: inetd.c 8.4 (Berkeley) 4/13/94
35 * $FreeBSD: src/usr.sbin/inetd/inetd.c,v 1.80.2.11 2003/04/05 13:39:18 dwmalone Exp $
36 * $DragonFly: src/usr.sbin/inetd/inetd.c,v 1.11 2008/05/23 23:40:59 swildner Exp $
40 * Inetd - Internet super-server
42 * This program invokes all internet services as needed. Connection-oriented
43 * services are invoked each time a connection is made, by creating a process.
44 * This process is passed the connection as file descriptor 0 and is expected
45 * to do a getpeername to find out the source host and port.
47 * Datagram oriented services are invoked when a datagram
48 * arrives; a process is created and passed a pending message
49 * on file descriptor 0. Datagram servers may either connect
50 * to their peer, freeing up the original socket for inetd
51 * to receive further messages on, or ``take over the socket'',
52 * processing all arriving datagrams and, eventually, timing
53 * out. The first type of server is said to be ``multi-threaded'';
54 * the second type of server ``single-threaded''.
56 * Inetd uses a configuration file which is read at startup
57 * and, possibly, at some later time in response to a hangup signal.
58 * The configuration file is ``free format'' with fields given in the
59 * order shown below. Continuation lines for an entry must begin with
60 * a space or tab. All fields must be present in each entry.
62 * service name must be in /etc/services
63 * or name a tcpmux service
64 * or specify a unix domain socket
65 * socket type stream/dgram/raw/rdm/seqpacket
66 * protocol tcp[4][6][/faith,ttcp], udp[4][6], unix
67 * wait/nowait single-threaded/multi-threaded
68 * user user to run daemon as
69 * server program full path name
70 * server program arguments maximum of MAXARGS (20)
72 * TCP services without official port numbers are handled with the
73 * RFC1078-based tcpmux internal service. Tcpmux listens on port 1 for
74 * requests. When a connection is made from a foreign host, the service
75 * requested is passed to tcpmux, which looks it up in the servtab list
76 * and returns the proper entry for the service. Tcpmux returns a
77 * negative reply if the service doesn't exist, otherwise the invoked
78 * server is expected to return the positive reply if the service type in
79 * inetd.conf file has the prefix "tcpmux/". If the service type has the
80 * prefix "tcpmux/+", tcpmux will return the positive reply for the
81 * process; this is for compatibility with older server code, and also
82 * allows you to invoke programs that use stdin/stdout without putting any
83 * special server code in them. Services that use tcpmux are "nowait"
84 * because they do not have a well-known port and hence cannot listen
85 * for new requests.
87 * For RPC services
88 * service name/version must be in /etc/rpc
89 * socket type stream/dgram/raw/rdm/seqpacket
90 * protocol rpc/tcp, rpc/udp
91 * wait/nowait single-threaded/multi-threaded
92 * user user to run daemon as
93 * server program full path name
94 * server program arguments maximum of MAXARGS
96 * Comment lines are indicated by a `#' in column 1.
98 * #ifdef IPSEC
99 * Comment lines that start with "#@" denote IPsec policy string, as described
100 * in ipsec_set_policy(3). This will affect all the following items in
101 * inetd.conf(8). To reset the policy, just use "#@" line. By default,
102 * there's no IPsec policy.
103 * #endif
105 #include <sys/param.h>
106 #include <sys/ioctl.h>
107 #include <sys/wait.h>
108 #include <sys/time.h>
109 #include <sys/resource.h>
110 #include <sys/stat.h>
111 #include <sys/un.h>
113 #include <netinet/in.h>
114 #include <netinet/tcp.h>
115 #include <arpa/inet.h>
116 #include <rpc/rpc.h>
117 #include <rpc/pmap_clnt.h>
119 #include <errno.h>
120 #include <err.h>
121 #include <fcntl.h>
122 #include <grp.h>
123 #include <limits.h>
124 #include <netdb.h>
125 #include <pwd.h>
126 #include <signal.h>
127 #include <stdio.h>
128 #include <stdlib.h>
129 #include <string.h>
130 #include <syslog.h>
131 #include <tcpd.h>
132 #include <unistd.h>
133 #include <libutil.h>
134 #include <sysexits.h>
135 #include <ctype.h>
137 #include "inetd.h"
138 #include "pathnames.h"
140 #ifdef IPSEC
141 #include <netinet6/ipsec.h>
142 #ifndef IPSEC_POLICY_IPSEC /* no ipsec support on old ipsec */
143 #undef IPSEC
144 #endif
145 #endif
147 /* wrapper for KAME-special getnameinfo() */
148 #ifndef NI_WITHSCOPEID
149 #define NI_WITHSCOPEID 0
150 #endif
152 #ifndef LIBWRAP_ALLOW_FACILITY
153 # define LIBWRAP_ALLOW_FACILITY LOG_AUTH
154 #endif
155 #ifndef LIBWRAP_ALLOW_SEVERITY
156 # define LIBWRAP_ALLOW_SEVERITY LOG_INFO
157 #endif
158 #ifndef LIBWRAP_DENY_FACILITY
159 # define LIBWRAP_DENY_FACILITY LOG_AUTH
160 #endif
161 #ifndef LIBWRAP_DENY_SEVERITY
162 # define LIBWRAP_DENY_SEVERITY LOG_WARNING
163 #endif
165 #define ISWRAP(sep) \
166 ( ((wrap_ex && !(sep)->se_bi) || (wrap_bi && (sep)->se_bi)) \
167 && (sep->se_family == AF_INET || sep->se_family == AF_INET6) \
168 && ( ((sep)->se_accept && (sep)->se_socktype == SOCK_STREAM) \
169 || (sep)->se_socktype == SOCK_DGRAM))
171 #ifdef LOGIN_CAP
172 #include <login_cap.h>
174 /* see init.c */
175 #define RESOURCE_RC "daemon"
177 #endif
179 #ifndef MAXCHILD
180 #define MAXCHILD -1 /* maximum number of this service
181 < 0 = no limit */
182 #endif
184 #ifndef MAXCPM
185 #define MAXCPM -1 /* rate limit invocations from a
186 single remote address,
187 < 0 = no limit */
188 #endif
190 #ifndef MAXPERIP
191 #define MAXPERIP -1 /* maximum number of this service
192 from a single remote address,
193 < 0 = no limit */
194 #endif
196 #ifndef TOOMANY
197 #define TOOMANY 256 /* don't start more than TOOMANY */
198 #endif
199 #define CNT_INTVL 60 /* servers in CNT_INTVL sec. */
200 #define RETRYTIME (60*10) /* retry after bind or server fail */
201 #define MAX_MAXCHLD 32767 /* max allowable max children */
203 #define SIGBLOCK (sigmask(SIGCHLD)|sigmask(SIGHUP)|sigmask(SIGALRM))
205 void close_sep(struct servtab *);
206 void flag_signal(int);
207 void flag_config(int);
208 void config(void);
209 int cpmip(const struct servtab *, int);
210 void endconfig(void);
211 struct servtab *enter(struct servtab *);
212 void freeconfig(struct servtab *);
213 struct servtab *getconfigent(void);
214 int matchservent(const char *, const char *, const char *);
215 char *nextline(FILE *);
216 void addchild(struct servtab *, int);
217 void flag_reapchild(int);
218 void reapchild(void);
219 void enable(struct servtab *);
220 void disable(struct servtab *);
221 void flag_retry(int);
222 void retry(void);
223 int setconfig(void);
224 void setup(struct servtab *);
225 #ifdef IPSEC
226 void ipsecsetup(struct servtab *);
227 #endif
228 void unregisterrpc(struct servtab *sep);
229 static struct conninfo *search_conn(struct servtab *sep, int ctrl);
230 static int room_conn(struct servtab *sep, struct conninfo *conn);
231 static void addchild_conn(struct conninfo *conn, pid_t pid);
232 static void reapchild_conn(pid_t pid);
233 static void free_conn(struct conninfo *conn);
234 static void resize_conn(struct servtab *sep, int maxperip);
235 static void free_connlist(struct servtab *sep);
236 static void free_proc(struct procinfo *);
237 static struct procinfo *search_proc(pid_t pid, int add);
238 static int hashval(char *p, int len);
240 int allow_severity;
241 int deny_severity;
242 int wrap_ex = 0;
243 int wrap_bi = 0;
244 int debug = 0;
245 int dolog = 0;
246 int maxsock; /* highest-numbered descriptor */
247 fd_set allsock;
248 int options;
249 int timingout;
250 int toomany = TOOMANY;
251 int maxchild = MAXCHILD;
252 int maxcpm = MAXCPM;
253 int maxperip = MAXPERIP;
254 struct servent *sp;
255 struct rpcent *rpc;
256 char *hostname = NULL;
257 struct sockaddr_in *bind_sa4;
258 int no_v4bind = 1;
259 #ifdef INET6
260 struct sockaddr_in6 *bind_sa6;
261 int no_v6bind = 1;
262 #endif
263 int signalpipe[2];
264 #ifdef SANITY_CHECK
265 int nsock;
266 #endif
267 uid_t euid;
268 gid_t egid;
269 mode_t mask;
271 struct servtab *servtab;
273 extern struct biltin biltins[];
275 #define NUMINT (sizeof(intab) / sizeof(struct inent))
276 const char *CONFIG = _PATH_INETDCONF;
277 const char *pid_file = _PATH_INETDPID;
279 static LIST_HEAD(, procinfo) proctable[PERIPSIZE];
282 getvalue(const char *arg, int *value, const char *whine)
284 int tmp;
285 char *p;
287 tmp = strtol(arg, &p, 0);
288 if (tmp < 0 || *p) {
289 syslog(LOG_ERR, whine, arg);
290 return 1; /* failure */
292 *value = tmp;
293 return 0; /* success */
296 static sa_family_t
297 whichaf(struct request_info *req)
299 struct sockaddr *sa;
301 sa = (struct sockaddr *)req->client->sin;
302 if (sa == NULL)
303 return AF_UNSPEC;
304 if (sa->sa_family == AF_INET6 &&
305 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)sa)->sin6_addr))
306 return AF_INET;
307 return sa->sa_family;
311 main(int argc, char **argv)
313 struct servtab *sep;
314 struct passwd *pwd;
315 struct group *grp;
316 struct sigaction sa, saalrm, sachld, sahup, sapipe;
317 int ch, dofork;
318 pid_t pid;
319 char buf[50];
320 #ifdef LOGIN_CAP
321 login_cap_t *lc = NULL;
322 #endif
323 struct request_info req;
324 int denied;
325 char *service = NULL;
326 union {
327 struct sockaddr peer_un;
328 struct sockaddr_in peer_un4;
329 struct sockaddr_in6 peer_un6;
330 struct sockaddr_storage peer_max;
331 } p_un;
332 #define peer p_un.peer_un
333 #define peer4 p_un.peer_un4
334 #define peer6 p_un.peer_un6
335 #define peermax p_un.peer_max
336 int i;
337 struct addrinfo hints, *res;
338 const char *servname;
339 int error;
340 struct conninfo *conn;
342 openlog("inetd", LOG_PID | LOG_NOWAIT | LOG_PERROR, LOG_DAEMON);
344 while ((ch = getopt(argc, argv, "dlwWR:a:c:C:p:s:")) != -1)
345 switch(ch) {
346 case 'd':
347 debug = 1;
348 options |= SO_DEBUG;
349 break;
350 case 'l':
351 dolog = 1;
352 break;
353 case 'R':
354 getvalue(optarg, &toomany,
355 "-R %s: bad value for service invocation rate");
356 break;
357 case 'c':
358 getvalue(optarg, &maxchild,
359 "-c %s: bad value for maximum children");
360 break;
361 case 'C':
362 getvalue(optarg, &maxcpm,
363 "-C %s: bad value for maximum children/minute");
364 break;
365 case 'a':
366 hostname = optarg;
367 break;
368 case 'p':
369 pid_file = optarg;
370 break;
371 case 's':
372 getvalue(optarg, &maxperip,
373 "-s %s: bad value for maximum children per source address");
374 break;
375 case 'w':
376 wrap_ex++;
377 break;
378 case 'W':
379 wrap_bi++;
380 break;
381 case '?':
382 default:
383 syslog(LOG_ERR,
384 "usage: inetd [-dlwW] [-a address] [-R rate]"
385 " [-c maximum] [-C rate]"
386 " [-p pidfile] [conf-file]");
387 exit(EX_USAGE);
390 * Initialize Bind Addrs.
391 * When hostname is NULL, wild card bind addrs are obtained from
392 * getaddrinfo(). But getaddrinfo() requires at least one of
393 * hostname or servname is non NULL.
394 * So when hostname is NULL, set dummy value to servname.
396 servname = (hostname == NULL) ? "discard" /* dummy */ : NULL;
398 bzero(&hints, sizeof(struct addrinfo));
399 hints.ai_flags = AI_PASSIVE;
400 hints.ai_family = AF_UNSPEC;
401 error = getaddrinfo(hostname, servname, &hints, &res);
402 if (error != 0) {
403 syslog(LOG_ERR, "-a %s: %s", hostname, gai_strerror(error));
404 if (error == EAI_SYSTEM)
405 syslog(LOG_ERR, "%s", strerror(errno));
406 exit(EX_USAGE);
408 do {
409 if (res->ai_addr == NULL) {
410 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
411 exit(EX_USAGE);
413 switch (res->ai_addr->sa_family) {
414 case AF_INET:
415 if (no_v4bind == 0)
416 continue;
417 bind_sa4 = (struct sockaddr_in *)res->ai_addr;
418 /* init port num in case servname is dummy */
419 bind_sa4->sin_port = 0;
420 no_v4bind = 0;
421 continue;
422 #ifdef INET6
423 case AF_INET6:
424 if (no_v6bind == 0)
425 continue;
426 bind_sa6 = (struct sockaddr_in6 *)res->ai_addr;
427 /* init port num in case servname is dummy */
428 bind_sa6->sin6_port = 0;
429 no_v6bind = 0;
430 continue;
431 #endif
433 if (no_v4bind == 0
434 #ifdef INET6
435 && no_v6bind == 0
436 #endif
438 break;
439 } while ((res = res->ai_next) != NULL);
440 if (no_v4bind != 0
441 #ifdef INET6
442 && no_v6bind != 0
443 #endif
445 syslog(LOG_ERR, "-a %s: unknown address family", hostname);
446 exit(EX_USAGE);
449 euid = geteuid();
450 egid = getegid();
451 umask(mask = umask(0777));
453 argc -= optind;
454 argv += optind;
456 if (argc > 0)
457 CONFIG = argv[0];
458 if (debug == 0) {
459 FILE *fp;
460 if (daemon(0, 0) < 0) {
461 syslog(LOG_WARNING, "daemon(0,0) failed: %m");
463 /* From now on we don't want syslog messages going to stderr. */
464 closelog();
465 openlog("inetd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
467 * In case somebody has started inetd manually, we need to
468 * clear the logname, so that old servers run as root do not
469 * get the user's logname..
471 if (setlogin("") < 0) {
472 syslog(LOG_WARNING, "cannot clear logname: %m");
473 /* no big deal if it fails.. */
475 pid = getpid();
476 fp = fopen(pid_file, "w");
477 if (fp) {
478 fprintf(fp, "%ld\n", (long)pid);
479 fclose(fp);
480 } else {
481 syslog(LOG_WARNING, "%s: %m", pid_file);
484 for (i = 0; i < PERIPSIZE; ++i)
485 LIST_INIT(&proctable[i]);
486 sa.sa_flags = 0;
487 sigemptyset(&sa.sa_mask);
488 sigaddset(&sa.sa_mask, SIGALRM);
489 sigaddset(&sa.sa_mask, SIGCHLD);
490 sigaddset(&sa.sa_mask, SIGHUP);
491 sa.sa_handler = flag_retry;
492 sigaction(SIGALRM, &sa, &saalrm);
493 config();
494 sa.sa_handler = flag_config;
495 sigaction(SIGHUP, &sa, &sahup);
496 sa.sa_handler = flag_reapchild;
497 sigaction(SIGCHLD, &sa, &sachld);
498 sa.sa_handler = SIG_IGN;
499 sigaction(SIGPIPE, &sa, &sapipe);
502 /* space for daemons to overwrite environment for ps */
503 #define DUMMYSIZE 100
504 char dummy[DUMMYSIZE];
506 memset(dummy, 'x', DUMMYSIZE - 1);
507 dummy[DUMMYSIZE - 1] = '\0';
508 if (setenv("inetd_dummy", dummy, 1) == -1)
509 syslog(LOG_WARNING, "setenv: cannot set inetd_dummy=%s: %m", dummy);
513 if (pipe(signalpipe) != 0) {
514 syslog(LOG_ERR, "pipe: %m");
515 exit(EX_OSERR);
517 if (fcntl(signalpipe[0], F_SETFD, FD_CLOEXEC) < 0 ||
518 fcntl(signalpipe[1], F_SETFD, FD_CLOEXEC) < 0) {
519 syslog(LOG_ERR, "signalpipe: fcntl (F_SETFD, FD_CLOEXEC): %m");
520 exit(EX_OSERR);
522 FD_SET(signalpipe[0], &allsock);
523 #ifdef SANITY_CHECK
524 nsock++;
525 #endif
526 if (signalpipe[0] > maxsock)
527 maxsock = signalpipe[0];
528 if (signalpipe[1] > maxsock)
529 maxsock = signalpipe[1];
531 for (;;) {
532 int n, ctrl;
533 fd_set readable;
535 #ifdef SANITY_CHECK
536 if (nsock == 0) {
537 syslog(LOG_ERR, "%s: nsock=0", __func__);
538 exit(EX_SOFTWARE);
540 #endif
541 readable = allsock;
542 if ((n = select(maxsock + 1, &readable, (fd_set *)0,
543 (fd_set *)0, (struct timeval *)0)) <= 0) {
544 if (n < 0 && errno != EINTR) {
545 syslog(LOG_WARNING, "select: %m");
546 sleep(1);
548 continue;
550 /* handle any queued signal flags */
551 if (FD_ISSET(signalpipe[0], &readable)) {
552 int nsig;
553 if (ioctl(signalpipe[0], FIONREAD, &nsig) != 0) {
554 syslog(LOG_ERR, "ioctl: %m");
555 exit(EX_OSERR);
557 while (--nsig >= 0) {
558 char c;
559 if (read(signalpipe[0], &c, 1) != 1) {
560 syslog(LOG_ERR, "read: %m");
561 exit(EX_OSERR);
563 if (debug)
564 warnx("handling signal flag %c", c);
565 switch(c) {
566 case 'A': /* sigalrm */
567 retry();
568 break;
569 case 'C': /* sigchld */
570 reapchild();
571 break;
572 case 'H': /* sighup */
573 config();
574 break;
578 for (sep = servtab; n && sep; sep = sep->se_next)
579 if (sep->se_fd != -1 && FD_ISSET(sep->se_fd, &readable)) {
580 n--;
581 if (debug)
582 warnx("someone wants %s", sep->se_service);
583 dofork = !sep->se_bi || sep->se_bi->bi_fork || ISWRAP(sep);
584 conn = NULL;
585 if (sep->se_accept && sep->se_socktype == SOCK_STREAM) {
586 i = 1;
587 if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
588 syslog(LOG_ERR, "ioctl (FIONBIO, 1): %m");
589 ctrl = accept(sep->se_fd, (struct sockaddr *)0,
590 (socklen_t *)0);
591 if (debug)
592 warnx("accept, ctrl %d", ctrl);
593 if (ctrl < 0) {
594 if (errno != EINTR)
595 syslog(LOG_WARNING,
596 "accept (for %s): %m",
597 sep->se_service);
598 if (sep->se_accept &&
599 sep->se_socktype == SOCK_STREAM)
600 close(ctrl);
601 continue;
603 i = 0;
604 if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
605 syslog(LOG_ERR, "ioctl1(FIONBIO, 0): %m");
606 if (ioctl(ctrl, FIONBIO, &i) < 0)
607 syslog(LOG_ERR, "ioctl2(FIONBIO, 0): %m");
608 if (cpmip(sep, ctrl) < 0) {
609 close(ctrl);
610 continue;
612 if (dofork &&
613 (conn = search_conn(sep, ctrl)) != NULL &&
614 !room_conn(sep, conn)) {
615 close(ctrl);
616 continue;
618 } else
619 ctrl = sep->se_fd;
620 if (dolog && !ISWRAP(sep)) {
621 char pname[INET6_ADDRSTRLEN] = "unknown";
622 socklen_t sl;
623 sl = sizeof peermax;
624 if (getpeername(ctrl, (struct sockaddr *)
625 &peermax, &sl)) {
626 sl = sizeof peermax;
627 if (recvfrom(ctrl, buf, sizeof(buf),
628 MSG_PEEK,
629 (struct sockaddr *)&peermax,
630 &sl) >= 0) {
631 getnameinfo((struct sockaddr *)&peermax,
632 peer.sa_len,
633 pname, sizeof(pname),
634 NULL, 0,
635 NI_NUMERICHOST|
636 NI_WITHSCOPEID);
638 } else {
639 getnameinfo((struct sockaddr *)&peermax,
640 peer.sa_len,
641 pname, sizeof(pname),
642 NULL, 0,
643 NI_NUMERICHOST|
644 NI_WITHSCOPEID);
646 syslog(LOG_INFO,"%s from %s", sep->se_service, pname);
648 sigblock(SIGBLOCK);
649 pid = 0;
651 * Fork for all external services, builtins which need to
652 * fork and anything we're wrapping (as wrapping might
653 * block or use hosts_options(5) twist).
655 if (dofork) {
656 if (sep->se_count++ == 0)
657 gettimeofday(&sep->se_time, (struct timezone *)NULL);
658 else if (toomany > 0 && sep->se_count >= toomany) {
659 struct timeval now;
661 gettimeofday(&now, (struct timezone *)NULL);
662 if (now.tv_sec - sep->se_time.tv_sec >
663 CNT_INTVL) {
664 sep->se_time = now;
665 sep->se_count = 1;
666 } else {
667 syslog(LOG_ERR,
668 "%s/%s server failing (looping), service terminated",
669 sep->se_service, sep->se_proto);
670 if (sep->se_accept &&
671 sep->se_socktype == SOCK_STREAM)
672 close(ctrl);
673 close_sep(sep);
674 free_conn(conn);
675 sigsetmask(0L);
676 if (!timingout) {
677 timingout = 1;
678 alarm(RETRYTIME);
680 continue;
683 pid = fork();
685 if (pid < 0) {
686 syslog(LOG_ERR, "fork: %m");
687 if (sep->se_accept &&
688 sep->se_socktype == SOCK_STREAM)
689 close(ctrl);
690 free_conn(conn);
691 sigsetmask(0L);
692 sleep(1);
693 continue;
695 if (pid) {
696 addchild_conn(conn, pid);
697 addchild(sep, pid);
699 sigsetmask(0L);
700 if (pid == 0) {
701 if (dofork) {
702 sigaction(SIGALRM, &saalrm, (struct sigaction *)0);
703 sigaction(SIGCHLD, &sachld, (struct sigaction *)0);
704 sigaction(SIGHUP, &sahup, (struct sigaction *)0);
705 /* SIGPIPE reset before exec */
708 * Call tcpmux to find the real service to exec.
710 if (sep->se_bi &&
711 sep->se_bi->bi_fn == (bi_fn_t *) tcpmux) {
712 sep = tcpmux(ctrl);
713 if (sep == NULL) {
714 close(ctrl);
715 _exit(0);
718 if (ISWRAP(sep)) {
719 inetd_setproctitle("wrapping", ctrl);
720 service = sep->se_server_name ?
721 sep->se_server_name : sep->se_service;
722 request_init(&req, RQ_DAEMON, service, RQ_FILE, ctrl, NULL);
723 fromhost(&req);
724 deny_severity = LIBWRAP_DENY_FACILITY|LIBWRAP_DENY_SEVERITY;
725 allow_severity = LIBWRAP_ALLOW_FACILITY|LIBWRAP_ALLOW_SEVERITY;
726 denied = !hosts_access(&req);
727 if (denied) {
728 syslog(deny_severity,
729 "refused connection from %.500s, service %s (%s%s)",
730 eval_client(&req), service, sep->se_proto,
731 (whichaf(&req) == AF_INET6) ? "6" : "");
732 if (sep->se_socktype != SOCK_STREAM)
733 recv(ctrl, buf, sizeof (buf), 0);
734 if (dofork) {
735 sleep(1);
736 _exit(0);
739 if (dolog) {
740 syslog(allow_severity,
741 "connection from %.500s, service %s (%s%s)",
742 eval_client(&req), service, sep->se_proto,
743 (whichaf(&req) == AF_INET6) ? "6" : "");
746 if (sep->se_bi) {
747 (*sep->se_bi->bi_fn)(ctrl, sep);
748 } else {
749 if (debug)
750 warnx("%d execl %s",
751 getpid(), sep->se_server);
752 /* Clear close-on-exec. */
753 if (fcntl(ctrl, F_SETFD, 0) < 0) {
754 syslog(LOG_ERR,
755 "%s/%s: fcntl (F_SETFD, 0): %m",
756 sep->se_service, sep->se_proto);
757 _exit(EX_OSERR);
759 if (ctrl != 0) {
760 dup2(ctrl, 0);
761 close(ctrl);
763 dup2(0, 1);
764 dup2(0, 2);
765 if ((pwd = getpwnam(sep->se_user)) == NULL) {
766 syslog(LOG_ERR,
767 "%s/%s: %s: no such user",
768 sep->se_service, sep->se_proto,
769 sep->se_user);
770 if (sep->se_socktype != SOCK_STREAM)
771 recv(0, buf, sizeof (buf), 0);
772 _exit(EX_NOUSER);
774 grp = NULL;
775 if ( sep->se_group != NULL
776 && (grp = getgrnam(sep->se_group)) == NULL
778 syslog(LOG_ERR,
779 "%s/%s: %s: no such group",
780 sep->se_service, sep->se_proto,
781 sep->se_group);
782 if (sep->se_socktype != SOCK_STREAM)
783 recv(0, buf, sizeof (buf), 0);
784 _exit(EX_NOUSER);
786 if (grp != NULL)
787 pwd->pw_gid = grp->gr_gid;
788 #ifdef LOGIN_CAP
789 if ((lc = login_getclass(sep->se_class)) == NULL) {
790 /* error syslogged by getclass */
791 syslog(LOG_ERR,
792 "%s/%s: %s: login class error",
793 sep->se_service, sep->se_proto,
794 sep->se_class);
795 if (sep->se_socktype != SOCK_STREAM)
796 recv(0, buf, sizeof (buf), 0);
797 _exit(EX_NOUSER);
799 #endif
800 if (setsid() < 0) {
801 syslog(LOG_ERR,
802 "%s: can't setsid(): %m",
803 sep->se_service);
804 /* _exit(EX_OSERR); not fatal yet */
806 #ifdef LOGIN_CAP
807 if (setusercontext(lc, pwd, pwd->pw_uid,
808 LOGIN_SETALL) != 0) {
809 syslog(LOG_ERR,
810 "%s: can't setusercontext(..%s..): %m",
811 sep->se_service, sep->se_user);
812 _exit(EX_OSERR);
814 login_close(lc);
815 #else
816 if (pwd->pw_uid) {
817 if (setlogin(sep->se_user) < 0) {
818 syslog(LOG_ERR,
819 "%s: can't setlogin(%s): %m",
820 sep->se_service, sep->se_user);
821 /* _exit(EX_OSERR); not yet */
823 if (setgid(pwd->pw_gid) < 0) {
824 syslog(LOG_ERR,
825 "%s: can't set gid %d: %m",
826 sep->se_service, pwd->pw_gid);
827 _exit(EX_OSERR);
829 initgroups(pwd->pw_name,
830 pwd->pw_gid);
831 if (setuid(pwd->pw_uid) < 0) {
832 syslog(LOG_ERR,
833 "%s: can't set uid %d: %m",
834 sep->se_service, pwd->pw_uid);
835 _exit(EX_OSERR);
838 #endif
839 sigaction(SIGPIPE, &sapipe,
840 (struct sigaction *)0);
841 execv(sep->se_server, sep->se_argv);
842 syslog(LOG_ERR,
843 "cannot execute %s: %m", sep->se_server);
844 if (sep->se_socktype != SOCK_STREAM)
845 recv(0, buf, sizeof (buf), 0);
847 if (dofork)
848 _exit(0);
850 if (sep->se_accept && sep->se_socktype == SOCK_STREAM)
851 close(ctrl);
857 * Add a signal flag to the signal flag queue for later handling
860 void
861 flag_signal(int c)
863 char ch = c;
865 if (write(signalpipe[1], &ch, 1) != 1) {
866 syslog(LOG_ERR, "write: %m");
867 _exit(EX_OSERR);
872 * Record a new child pid for this service. If we've reached the
873 * limit on children, then stop accepting incoming requests.
876 void
877 addchild(struct servtab *sep, pid_t pid)
879 if (sep->se_maxchild <= 0)
880 return;
881 #ifdef SANITY_CHECK
882 if (sep->se_numchild >= sep->se_maxchild) {
883 syslog(LOG_ERR, "%s: %d >= %d",
884 __func__, sep->se_numchild, sep->se_maxchild);
885 exit(EX_SOFTWARE);
887 #endif
888 sep->se_pids[sep->se_numchild++] = pid;
889 if (sep->se_numchild == sep->se_maxchild)
890 disable(sep);
894 * Some child process has exited. See if it's on somebody's list.
897 void
898 flag_reapchild(int signo __unused)
900 flag_signal('C');
903 void
904 reapchild(void)
906 int k, status;
907 pid_t pid;
908 struct servtab *sep;
910 for (;;) {
911 pid = wait3(&status, WNOHANG, (struct rusage *)0);
912 if (pid <= 0)
913 break;
914 if (debug)
915 warnx("%d reaped, %s %u", pid,
916 WIFEXITED(status) ? "status" : "signal",
917 WIFEXITED(status) ? WEXITSTATUS(status)
918 : WTERMSIG(status));
919 for (sep = servtab; sep; sep = sep->se_next) {
920 for (k = 0; k < sep->se_numchild; k++)
921 if (sep->se_pids[k] == pid)
922 break;
923 if (k == sep->se_numchild)
924 continue;
925 if (sep->se_numchild == sep->se_maxchild)
926 enable(sep);
927 sep->se_pids[k] = sep->se_pids[--sep->se_numchild];
928 if (WIFSIGNALED(status) || WEXITSTATUS(status))
929 syslog(LOG_WARNING,
930 "%s[%d]: exited, %s %u",
931 sep->se_server, pid,
932 WIFEXITED(status) ? "status" : "signal",
933 WIFEXITED(status) ? WEXITSTATUS(status)
934 : WTERMSIG(status));
935 break;
937 reapchild_conn(pid);
941 void
942 flag_config(int signo __unused)
944 flag_signal('H');
947 void
948 config(void)
950 struct servtab *sep, *new, **sepp;
951 long omask;
952 #ifdef LOGIN_CAP
953 login_cap_t *lc = NULL;
954 #endif
957 if (!setconfig()) {
958 syslog(LOG_ERR, "%s: %m", CONFIG);
959 return;
961 for (sep = servtab; sep; sep = sep->se_next)
962 sep->se_checked = 0;
963 while ((new = getconfigent())) {
964 if (getpwnam(new->se_user) == NULL) {
965 syslog(LOG_ERR,
966 "%s/%s: no such user '%s', service ignored",
967 new->se_service, new->se_proto, new->se_user);
968 continue;
970 if (new->se_group && getgrnam(new->se_group) == NULL) {
971 syslog(LOG_ERR,
972 "%s/%s: no such group '%s', service ignored",
973 new->se_service, new->se_proto, new->se_group);
974 continue;
976 #ifdef LOGIN_CAP
977 if ((lc = login_getclass(new->se_class)) == NULL) {
978 /* error syslogged by getclass */
979 syslog(LOG_ERR,
980 "%s/%s: %s: login class error, service ignored",
981 new->se_service, new->se_proto, new->se_class);
982 continue;
984 login_close(lc);
985 #endif
986 for (sep = servtab; sep; sep = sep->se_next)
987 if (strcmp(sep->se_service, new->se_service) == 0 &&
988 strcmp(sep->se_proto, new->se_proto) == 0 &&
989 sep->se_socktype == new->se_socktype &&
990 sep->se_family == new->se_family)
991 break;
992 if (sep != 0) {
993 int i;
995 #define SWAP(a, b) { typeof(a) c = a; a = b; b = c; }
996 omask = sigblock(SIGBLOCK);
997 if (sep->se_nomapped != new->se_nomapped) {
998 sep->se_nomapped = new->se_nomapped;
999 sep->se_reset = 1;
1001 /* copy over outstanding child pids */
1002 if (sep->se_maxchild > 0 && new->se_maxchild > 0) {
1003 new->se_numchild = sep->se_numchild;
1004 if (new->se_numchild > new->se_maxchild)
1005 new->se_numchild = new->se_maxchild;
1006 memcpy(new->se_pids, sep->se_pids,
1007 new->se_numchild * sizeof(*new->se_pids));
1009 SWAP(sep->se_pids, new->se_pids);
1010 sep->se_maxchild = new->se_maxchild;
1011 sep->se_numchild = new->se_numchild;
1012 sep->se_maxcpm = new->se_maxcpm;
1013 resize_conn(sep, new->se_maxperip);
1014 sep->se_maxperip = new->se_maxperip;
1015 sep->se_bi = new->se_bi;
1016 /* might need to turn on or off service now */
1017 if (sep->se_fd >= 0) {
1018 if (sep->se_maxchild > 0
1019 && sep->se_numchild == sep->se_maxchild) {
1020 if (FD_ISSET(sep->se_fd, &allsock))
1021 disable(sep);
1022 } else {
1023 if (!FD_ISSET(sep->se_fd, &allsock))
1024 enable(sep);
1027 sep->se_accept = new->se_accept;
1028 SWAP(sep->se_user, new->se_user);
1029 SWAP(sep->se_group, new->se_group);
1030 #ifdef LOGIN_CAP
1031 SWAP(sep->se_class, new->se_class);
1032 #endif
1033 SWAP(sep->se_server, new->se_server);
1034 SWAP(sep->se_server_name, new->se_server_name);
1035 for (i = 0; i < MAXARGV; i++)
1036 SWAP(sep->se_argv[i], new->se_argv[i]);
1037 #ifdef IPSEC
1038 SWAP(sep->se_policy, new->se_policy);
1039 ipsecsetup(sep);
1040 #endif
1041 sigsetmask(omask);
1042 freeconfig(new);
1043 if (debug)
1044 print_service("REDO", sep);
1045 } else {
1046 sep = enter(new);
1047 if (debug)
1048 print_service("ADD ", sep);
1050 sep->se_checked = 1;
1051 if (ISMUX(sep)) {
1052 sep->se_fd = -1;
1053 continue;
1055 switch (sep->se_family) {
1056 case AF_INET:
1057 if (no_v4bind != 0) {
1058 sep->se_fd = -1;
1059 continue;
1061 break;
1062 #ifdef INET6
1063 case AF_INET6:
1064 if (no_v6bind != 0) {
1065 sep->se_fd = -1;
1066 continue;
1068 break;
1069 #endif
1071 if (!sep->se_rpc) {
1072 if (sep->se_family != AF_UNIX) {
1073 sp = getservbyname(sep->se_service, sep->se_proto);
1074 if (sp == 0) {
1075 syslog(LOG_ERR, "%s/%s: unknown service",
1076 sep->se_service, sep->se_proto);
1077 sep->se_checked = 0;
1078 continue;
1081 switch (sep->se_family) {
1082 case AF_INET:
1083 if (sp->s_port != sep->se_ctrladdr4.sin_port) {
1084 sep->se_ctrladdr4.sin_port =
1085 sp->s_port;
1086 sep->se_reset = 1;
1088 break;
1089 #ifdef INET6
1090 case AF_INET6:
1091 if (sp->s_port !=
1092 sep->se_ctrladdr6.sin6_port) {
1093 sep->se_ctrladdr6.sin6_port =
1094 sp->s_port;
1095 sep->se_reset = 1;
1097 break;
1098 #endif
1100 if (sep->se_reset != 0 && sep->se_fd >= 0)
1101 close_sep(sep);
1102 } else {
1103 rpc = getrpcbyname(sep->se_service);
1104 if (rpc == 0) {
1105 syslog(LOG_ERR, "%s/%s unknown RPC service",
1106 sep->se_service, sep->se_proto);
1107 if (sep->se_fd != -1)
1108 close(sep->se_fd);
1109 sep->se_fd = -1;
1110 continue;
1112 if (rpc->r_number != sep->se_rpc_prog) {
1113 if (sep->se_rpc_prog)
1114 unregisterrpc(sep);
1115 sep->se_rpc_prog = rpc->r_number;
1116 if (sep->se_fd != -1)
1117 close(sep->se_fd);
1118 sep->se_fd = -1;
1121 if (sep->se_fd == -1)
1122 setup(sep);
1124 endconfig();
1126 * Purge anything not looked at above.
1128 omask = sigblock(SIGBLOCK);
1129 sepp = &servtab;
1130 while ((sep = *sepp)) {
1131 if (sep->se_checked) {
1132 sepp = &sep->se_next;
1133 continue;
1135 *sepp = sep->se_next;
1136 if (sep->se_fd >= 0)
1137 close_sep(sep);
1138 if (debug)
1139 print_service("FREE", sep);
1140 if (sep->se_rpc && sep->se_rpc_prog > 0)
1141 unregisterrpc(sep);
1142 freeconfig(sep);
1143 free(sep);
1145 sigsetmask(omask);
1148 void
1149 unregisterrpc(struct servtab *sep)
1151 u_int i;
1152 struct servtab *sepp;
1153 long omask;
1155 omask = sigblock(SIGBLOCK);
1156 for (sepp = servtab; sepp; sepp = sepp->se_next) {
1157 if (sepp == sep)
1158 continue;
1159 if (sep->se_checked == 0 ||
1160 !sepp->se_rpc ||
1161 sep->se_rpc_prog != sepp->se_rpc_prog)
1162 continue;
1163 return;
1165 if (debug)
1166 print_service("UNREG", sep);
1167 for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++)
1168 pmap_unset(sep->se_rpc_prog, i);
1169 if (sep->se_fd != -1)
1170 close(sep->se_fd);
1171 sep->se_fd = -1;
1172 sigsetmask(omask);
1175 void
1176 flag_retry(int signo __unused)
1178 flag_signal('A');
1181 void
1182 retry(void)
1184 struct servtab *sep;
1186 timingout = 0;
1187 for (sep = servtab; sep; sep = sep->se_next)
1188 if (sep->se_fd == -1 && !ISMUX(sep))
1189 setup(sep);
1192 void
1193 setup(struct servtab *sep)
1195 int on = 1;
1197 if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1198 if (debug)
1199 warn("socket failed on %s/%s",
1200 sep->se_service, sep->se_proto);
1201 syslog(LOG_ERR, "%s/%s: socket: %m",
1202 sep->se_service, sep->se_proto);
1203 return;
1205 /* Set all listening sockets to close-on-exec. */
1206 if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
1207 syslog(LOG_ERR, "%s/%s: fcntl (F_SETFD, FD_CLOEXEC): %m",
1208 sep->se_service, sep->se_proto);
1209 close(sep->se_fd);
1210 return;
1212 #define turnon(fd, opt) \
1213 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1214 if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1215 turnon(sep->se_fd, SO_DEBUG) < 0)
1216 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1217 if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1218 syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1219 #ifdef SO_PRIVSTATE
1220 if (turnon(sep->se_fd, SO_PRIVSTATE) < 0)
1221 syslog(LOG_ERR, "setsockopt (SO_PRIVSTATE): %m");
1222 #endif
1223 /* tftpd opens a new connection then needs more infos */
1224 if ((sep->se_family == AF_INET6) &&
1225 (strcmp(sep->se_proto, "udp") == 0) &&
1226 (sep->se_accept == 0) &&
1227 (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_PKTINFO,
1228 (char *)&on, sizeof (on)) < 0))
1229 syslog(LOG_ERR, "setsockopt (IPV6_RECVPKTINFO): %m");
1230 if (sep->se_family == AF_INET6) {
1231 int flag = sep->se_nomapped ? 1 : 0;
1232 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_V6ONLY,
1233 (char *)&flag, sizeof (flag)) < 0)
1234 syslog(LOG_ERR, "setsockopt (IPV6_V6ONLY): %m");
1236 #undef turnon
1237 if (sep->se_type == TTCP_TYPE)
1238 if (setsockopt(sep->se_fd, IPPROTO_TCP, TCP_NOPUSH,
1239 (char *)&on, sizeof (on)) < 0)
1240 syslog(LOG_ERR, "setsockopt (TCP_NOPUSH): %m");
1241 #ifdef IPV6_FAITH
1242 if (sep->se_type == FAITH_TYPE) {
1243 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_FAITH, &on,
1244 sizeof(on)) < 0) {
1245 syslog(LOG_ERR, "setsockopt (IPV6_FAITH): %m");
1248 #endif
1249 #ifdef IPSEC
1250 ipsecsetup(sep);
1251 #endif
1252 if (sep->se_family == AF_UNIX) {
1253 unlink(sep->se_ctrladdr_un.sun_path);
1254 umask(0777); /* Make socket with conservative permissions */
1256 if (bind(sep->se_fd, (struct sockaddr *)&sep->se_ctrladdr,
1257 sep->se_ctrladdr_size) < 0) {
1258 if (debug)
1259 warn("bind failed on %s/%s",
1260 sep->se_service, sep->se_proto);
1261 syslog(LOG_ERR, "%s/%s: bind: %m",
1262 sep->se_service, sep->se_proto);
1263 close(sep->se_fd);
1264 sep->se_fd = -1;
1265 if (!timingout) {
1266 timingout = 1;
1267 alarm(RETRYTIME);
1269 if (sep->se_family == AF_UNIX)
1270 umask(mask);
1271 return;
1273 if (sep->se_family == AF_UNIX) {
1274 /* Ick - fch{own,mod} don't work on Unix domain sockets */
1275 if (chown(sep->se_service, sep->se_sockuid, sep->se_sockgid) < 0)
1276 syslog(LOG_ERR, "chown socket: %m");
1277 if (chmod(sep->se_service, sep->se_sockmode) < 0)
1278 syslog(LOG_ERR, "chmod socket: %m");
1279 umask(mask);
1281 if (sep->se_rpc) {
1282 u_int i;
1283 socklen_t len = sep->se_ctrladdr_size;
1285 if (sep->se_family != AF_INET) {
1286 syslog(LOG_ERR,
1287 "%s/%s: unsupported address family for rpc",
1288 sep->se_service, sep->se_proto);
1289 close(sep->se_fd);
1290 sep->se_fd = -1;
1291 return;
1293 if (getsockname(sep->se_fd,
1294 (struct sockaddr*)&sep->se_ctrladdr, &len) < 0){
1295 syslog(LOG_ERR, "%s/%s: getsockname: %m",
1296 sep->se_service, sep->se_proto);
1297 close(sep->se_fd);
1298 sep->se_fd = -1;
1299 return;
1301 if (debug)
1302 print_service("REG ", sep);
1303 for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++) {
1304 pmap_unset(sep->se_rpc_prog, i);
1305 pmap_set(sep->se_rpc_prog, i,
1306 (sep->se_socktype == SOCK_DGRAM)
1307 ? IPPROTO_UDP : IPPROTO_TCP,
1308 ntohs(sep->se_ctrladdr4.sin_port));
1311 if (sep->se_socktype == SOCK_STREAM)
1312 listen(sep->se_fd, 64);
1313 enable(sep);
1314 if (debug) {
1315 warnx("registered %s on %d",
1316 sep->se_server, sep->se_fd);
1320 #ifdef IPSEC
1321 void
1322 ipsecsetup(struct servtab *sep)
1324 char *buf;
1325 char *policy_in = NULL;
1326 char *policy_out = NULL;
1327 int level;
1328 int opt;
1330 switch (sep->se_family) {
1331 case AF_INET:
1332 level = IPPROTO_IP;
1333 opt = IP_IPSEC_POLICY;
1334 break;
1335 #ifdef INET6
1336 case AF_INET6:
1337 level = IPPROTO_IPV6;
1338 opt = IPV6_IPSEC_POLICY;
1339 break;
1340 #endif
1341 default:
1342 return;
1345 if (!sep->se_policy || sep->se_policy[0] == '\0') {
1346 static char def_in[] = "in entrust", def_out[] = "out entrust";
1347 policy_in = def_in;
1348 policy_out = def_out;
1349 } else {
1350 if (!strncmp("in", sep->se_policy, 2))
1351 policy_in = sep->se_policy;
1352 else if (!strncmp("out", sep->se_policy, 3))
1353 policy_out = sep->se_policy;
1354 else {
1355 syslog(LOG_ERR, "invalid security policy \"%s\"",
1356 sep->se_policy);
1357 return;
1361 if (policy_in != NULL) {
1362 buf = ipsec_set_policy(policy_in, strlen(policy_in));
1363 if (buf != NULL) {
1364 if (setsockopt(sep->se_fd, level, opt,
1365 buf, ipsec_get_policylen(buf)) < 0 &&
1366 debug != 0)
1367 warnx("%s/%s: ipsec initialization failed; %s",
1368 sep->se_service, sep->se_proto,
1369 policy_in);
1370 free(buf);
1371 } else
1372 syslog(LOG_ERR, "invalid security policy \"%s\"",
1373 policy_in);
1375 if (policy_out != NULL) {
1376 buf = ipsec_set_policy(policy_out, strlen(policy_out));
1377 if (buf != NULL) {
1378 if (setsockopt(sep->se_fd, level, opt,
1379 buf, ipsec_get_policylen(buf)) < 0 &&
1380 debug != 0)
1381 warnx("%s/%s: ipsec initialization failed; %s",
1382 sep->se_service, sep->se_proto,
1383 policy_out);
1384 free(buf);
1385 } else
1386 syslog(LOG_ERR, "invalid security policy \"%s\"",
1387 policy_out);
1390 #endif
1393 * Finish with a service and its socket.
1395 void
1396 close_sep(struct servtab *sep)
1398 if (sep->se_fd >= 0) {
1399 if (FD_ISSET(sep->se_fd, &allsock))
1400 disable(sep);
1401 close(sep->se_fd);
1402 sep->se_fd = -1;
1404 sep->se_count = 0;
1405 sep->se_numchild = 0; /* forget about any existing children */
1409 matchservent(const char *name1, const char *name2, const char *proto)
1411 char **alias, *p;
1412 struct servent *se;
1414 if (strcmp(proto, "unix") == 0) {
1415 if ((p = strrchr(name1, '/')) != NULL)
1416 name1 = p + 1;
1417 if ((p = strrchr(name2, '/')) != NULL)
1418 name2 = p + 1;
1420 if (strcmp(name1, name2) == 0)
1421 return(1);
1422 if ((se = getservbyname(name1, proto)) != NULL) {
1423 if (strcmp(name2, se->s_name) == 0)
1424 return(1);
1425 for (alias = se->s_aliases; *alias; alias++)
1426 if (strcmp(name2, *alias) == 0)
1427 return(1);
1429 return(0);
1432 struct servtab *
1433 enter(struct servtab *cp)
1435 struct servtab *sep;
1436 long omask;
1438 sep = (struct servtab *)malloc(sizeof (*sep));
1439 if (sep == (struct servtab *)0) {
1440 syslog(LOG_ERR, "malloc: %m");
1441 exit(EX_OSERR);
1443 *sep = *cp;
1444 sep->se_fd = -1;
1445 omask = sigblock(SIGBLOCK);
1446 sep->se_next = servtab;
1447 servtab = sep;
1448 sigsetmask(omask);
1449 return (sep);
1452 void
1453 enable(struct servtab *sep)
1455 if (debug)
1456 warnx(
1457 "enabling %s, fd %d", sep->se_service, sep->se_fd);
1458 #ifdef SANITY_CHECK
1459 if (sep->se_fd < 0) {
1460 syslog(LOG_ERR,
1461 "%s: %s: bad fd", __func__, sep->se_service);
1462 exit(EX_SOFTWARE);
1464 if (ISMUX(sep)) {
1465 syslog(LOG_ERR,
1466 "%s: %s: is mux", __func__, sep->se_service);
1467 exit(EX_SOFTWARE);
1469 if (FD_ISSET(sep->se_fd, &allsock)) {
1470 syslog(LOG_ERR,
1471 "%s: %s: not off", __func__, sep->se_service);
1472 exit(EX_SOFTWARE);
1474 nsock++;
1475 #endif
1476 FD_SET(sep->se_fd, &allsock);
1477 if (sep->se_fd > maxsock)
1478 maxsock = sep->se_fd;
1481 void
1482 disable(struct servtab *sep)
1484 if (debug)
1485 warnx(
1486 "disabling %s, fd %d", sep->se_service, sep->se_fd);
1487 #ifdef SANITY_CHECK
1488 if (sep->se_fd < 0) {
1489 syslog(LOG_ERR,
1490 "%s: %s: bad fd", __func__, sep->se_service);
1491 exit(EX_SOFTWARE);
1493 if (ISMUX(sep)) {
1494 syslog(LOG_ERR,
1495 "%s: %s: is mux", __func__, sep->se_service);
1496 exit(EX_SOFTWARE);
1498 if (!FD_ISSET(sep->se_fd, &allsock)) {
1499 syslog(LOG_ERR,
1500 "%s: %s: not on", __func__, sep->se_service);
1501 exit(EX_SOFTWARE);
1503 if (nsock == 0) {
1504 syslog(LOG_ERR, "%s: nsock=0", __func__);
1505 exit(EX_SOFTWARE);
1507 nsock--;
1508 #endif
1509 FD_CLR(sep->se_fd, &allsock);
1510 if (sep->se_fd == maxsock)
1511 maxsock--;
1514 FILE *fconfig = NULL;
1515 struct servtab serv;
1516 char line[LINE_MAX];
1519 setconfig(void)
1522 if (fconfig != NULL) {
1523 fseek(fconfig, 0L, SEEK_SET);
1524 return (1);
1526 fconfig = fopen(CONFIG, "r");
1527 return (fconfig != NULL);
1530 void
1531 endconfig(void)
1533 if (fconfig) {
1534 fclose(fconfig);
1535 fconfig = NULL;
1539 struct servtab *
1540 getconfigent(void)
1542 struct servtab *sep = &serv;
1543 int argc;
1544 char *cp, *arg, *s;
1545 char *versp;
1546 static char TCPMUX_TOKEN[] = "tcpmux/";
1547 #define MUX_LEN (sizeof(TCPMUX_TOKEN)-1)
1548 #ifdef IPSEC
1549 char *policy = NULL;
1550 #endif
1551 int v4bind = 0;
1552 #ifdef INET6
1553 int v6bind = 0;
1554 #endif
1555 int i;
1557 more:
1558 while ((cp = nextline(fconfig)) != NULL) {
1559 #ifdef IPSEC
1560 /* lines starting with #@ is not a comment, but the policy */
1561 if (cp[0] == '#' && cp[1] == '@') {
1562 char *p;
1563 for (p = cp + 2; p && *p && isspace(*p); p++)
1565 if (*p == '\0') {
1566 if (policy)
1567 free(policy);
1568 policy = NULL;
1569 } else if (ipsec_get_policylen(p) >= 0) {
1570 if (policy)
1571 free(policy);
1572 policy = newstr(p);
1573 } else {
1574 syslog(LOG_ERR,
1575 "%s: invalid ipsec policy \"%s\"",
1576 CONFIG, p);
1577 exit(EX_CONFIG);
1580 #endif
1581 if (*cp == '#' || *cp == '\0')
1582 continue;
1583 break;
1585 if (cp == NULL)
1586 return ((struct servtab *)0);
1588 * clear the static buffer, since some fields (se_ctrladdr,
1589 * for example) don't get initialized here.
1591 memset(sep, 0, sizeof *sep);
1592 arg = skip(&cp);
1593 if (cp == NULL) {
1594 /* got an empty line containing just blanks/tabs. */
1595 goto more;
1597 if (arg[0] == ':') { /* :user:group:perm: */
1598 char *user, *group, *perm;
1599 struct passwd *pw;
1600 struct group *gr;
1601 user = arg+1;
1602 if ((group = strchr(user, ':')) == NULL) {
1603 syslog(LOG_ERR, "no group after user '%s'", user);
1604 goto more;
1606 *group++ = '\0';
1607 if ((perm = strchr(group, ':')) == NULL) {
1608 syslog(LOG_ERR, "no mode after group '%s'", group);
1609 goto more;
1611 *perm++ = '\0';
1612 if ((pw = getpwnam(user)) == NULL) {
1613 syslog(LOG_ERR, "no such user '%s'", user);
1614 goto more;
1616 sep->se_sockuid = pw->pw_uid;
1617 if ((gr = getgrnam(group)) == NULL) {
1618 syslog(LOG_ERR, "no such user '%s'", group);
1619 goto more;
1621 sep->se_sockgid = gr->gr_gid;
1622 sep->se_sockmode = strtol(perm, &arg, 8);
1623 if (*arg != ':') {
1624 syslog(LOG_ERR, "bad mode '%s'", perm);
1625 goto more;
1627 *arg++ = '\0';
1628 } else {
1629 sep->se_sockuid = euid;
1630 sep->se_sockgid = egid;
1631 sep->se_sockmode = 0200;
1633 if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1634 char *c = arg + MUX_LEN;
1635 if (*c == '+') {
1636 sep->se_type = MUXPLUS_TYPE;
1637 c++;
1638 } else
1639 sep->se_type = MUX_TYPE;
1640 sep->se_service = newstr(c);
1641 } else {
1642 sep->se_service = newstr(arg);
1643 sep->se_type = NORM_TYPE;
1645 arg = sskip(&cp);
1646 if (strcmp(arg, "stream") == 0)
1647 sep->se_socktype = SOCK_STREAM;
1648 else if (strcmp(arg, "dgram") == 0)
1649 sep->se_socktype = SOCK_DGRAM;
1650 else if (strcmp(arg, "rdm") == 0)
1651 sep->se_socktype = SOCK_RDM;
1652 else if (strcmp(arg, "seqpacket") == 0)
1653 sep->se_socktype = SOCK_SEQPACKET;
1654 else if (strcmp(arg, "raw") == 0)
1655 sep->se_socktype = SOCK_RAW;
1656 else
1657 sep->se_socktype = -1;
1659 arg = sskip(&cp);
1660 if (strncmp(arg, "tcp", 3) == 0) {
1661 sep->se_proto = newstr(strsep(&arg, "/"));
1662 if (arg != NULL) {
1663 if (strcmp(arg, "ttcp") == 0)
1664 sep->se_type = TTCP_TYPE;
1665 else if (strcmp(arg, "faith") == 0)
1666 sep->se_type = FAITH_TYPE;
1668 } else {
1669 if (sep->se_type == NORM_TYPE &&
1670 strncmp(arg, "faith/", 6) == 0) {
1671 arg += 6;
1672 sep->se_type = FAITH_TYPE;
1674 sep->se_proto = newstr(arg);
1676 if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1677 if (no_v4bind != 0) {
1678 syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1679 sep->se_service);
1680 freeconfig(sep);
1681 goto more;
1683 memmove(sep->se_proto, sep->se_proto + 4,
1684 strlen(sep->se_proto) + 1 - 4);
1685 sep->se_rpc = 1;
1686 sep->se_rpc_prog = sep->se_rpc_lowvers =
1687 sep->se_rpc_lowvers = 0;
1688 memcpy(&sep->se_ctrladdr4, bind_sa4,
1689 sizeof(sep->se_ctrladdr4));
1690 if ((versp = strrchr(sep->se_service, '/'))) {
1691 *versp++ = '\0';
1692 switch (sscanf(versp, "%u-%u",
1693 &sep->se_rpc_lowvers,
1694 &sep->se_rpc_highvers)) {
1695 case 2:
1696 break;
1697 case 1:
1698 sep->se_rpc_highvers =
1699 sep->se_rpc_lowvers;
1700 break;
1701 default:
1702 syslog(LOG_ERR,
1703 "bad RPC version specifier; %s",
1704 sep->se_service);
1705 freeconfig(sep);
1706 goto more;
1709 else {
1710 sep->se_rpc_lowvers =
1711 sep->se_rpc_highvers = 1;
1714 sep->se_nomapped = 0;
1715 while (isdigit(sep->se_proto[strlen(sep->se_proto) - 1])) {
1716 #ifdef INET6
1717 if (sep->se_proto[strlen(sep->se_proto) - 1] == '6') {
1718 if (no_v6bind != 0) {
1719 syslog(LOG_NOTICE, "IPv6 bind is ignored for %s",
1720 sep->se_service);
1721 freeconfig(sep);
1722 goto more;
1724 sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1725 v6bind = 1;
1726 continue;
1728 #endif
1729 if (sep->se_proto[strlen(sep->se_proto) - 1] == '4') {
1730 sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1731 v4bind = 1;
1732 continue;
1734 /* illegal version num */
1735 syslog(LOG_ERR, "bad IP version for %s", sep->se_proto);
1736 freeconfig(sep);
1737 goto more;
1739 if (strcmp(sep->se_proto, "unix") == 0) {
1740 sep->se_family = AF_UNIX;
1741 } else
1742 #ifdef INET6
1743 if (v6bind != 0) {
1744 sep->se_family = AF_INET6;
1745 if (v4bind == 0 || no_v4bind != 0)
1746 sep->se_nomapped = 1;
1747 } else
1748 #endif
1749 { /* default to v4 bind if not v6 bind */
1750 if (no_v4bind != 0) {
1751 syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1752 sep->se_service);
1753 freeconfig(sep);
1754 goto more;
1756 sep->se_family = AF_INET;
1758 /* init ctladdr */
1759 switch(sep->se_family) {
1760 case AF_INET:
1761 memcpy(&sep->se_ctrladdr4, bind_sa4,
1762 sizeof(sep->se_ctrladdr4));
1763 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr4);
1764 break;
1765 #ifdef INET6
1766 case AF_INET6:
1767 memcpy(&sep->se_ctrladdr6, bind_sa6,
1768 sizeof(sep->se_ctrladdr6));
1769 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr6);
1770 break;
1771 #endif
1772 case AF_UNIX:
1773 if (strlen(sep->se_service) >= sizeof(sep->se_ctrladdr_un.sun_path)) {
1774 syslog(LOG_ERR,
1775 "domain socket pathname too long for service %s",
1776 sep->se_service);
1777 goto more;
1779 memset(&sep->se_ctrladdr, 0, sizeof(sep->se_ctrladdr));
1780 sep->se_ctrladdr_un.sun_family = sep->se_family;
1781 sep->se_ctrladdr_un.sun_len = strlen(sep->se_service);
1782 strcpy(sep->se_ctrladdr_un.sun_path, sep->se_service);
1783 sep->se_ctrladdr_size = SUN_LEN(&sep->se_ctrladdr_un);
1785 arg = sskip(&cp);
1786 if (!strncmp(arg, "wait", 4))
1787 sep->se_accept = 0;
1788 else if (!strncmp(arg, "nowait", 6))
1789 sep->se_accept = 1;
1790 else {
1791 syslog(LOG_ERR,
1792 "%s: bad wait/nowait for service %s",
1793 CONFIG, sep->se_service);
1794 goto more;
1796 sep->se_maxchild = -1;
1797 sep->se_maxcpm = -1;
1798 sep->se_maxperip = -1;
1799 if ((s = strchr(arg, '/')) != NULL) {
1800 char *eptr;
1801 u_long val;
1803 val = strtoul(s + 1, &eptr, 10);
1804 if (eptr == s + 1 || val > MAX_MAXCHLD) {
1805 syslog(LOG_ERR,
1806 "%s: bad max-child for service %s",
1807 CONFIG, sep->se_service);
1808 goto more;
1810 if (debug)
1811 if (!sep->se_accept && val != 1)
1812 warnx("maxchild=%lu for wait service %s"
1813 " not recommended", val, sep->se_service);
1814 sep->se_maxchild = val;
1815 if (*eptr == '/')
1816 sep->se_maxcpm = strtol(eptr + 1, &eptr, 10);
1817 if (*eptr == '/')
1818 sep->se_maxperip = strtol(eptr + 1, &eptr, 10);
1820 * explicitly do not check for \0 for future expansion /
1821 * backwards compatibility
1824 if (ISMUX(sep)) {
1826 * Silently enforce "nowait" mode for TCPMUX services
1827 * since they don't have an assigned port to listen on.
1829 sep->se_accept = 1;
1830 if (strcmp(sep->se_proto, "tcp")) {
1831 syslog(LOG_ERR,
1832 "%s: bad protocol for tcpmux service %s",
1833 CONFIG, sep->se_service);
1834 goto more;
1836 if (sep->se_socktype != SOCK_STREAM) {
1837 syslog(LOG_ERR,
1838 "%s: bad socket type for tcpmux service %s",
1839 CONFIG, sep->se_service);
1840 goto more;
1843 sep->se_user = newstr(sskip(&cp));
1844 #ifdef LOGIN_CAP
1845 if ((s = strrchr(sep->se_user, '/')) != NULL) {
1846 *s = '\0';
1847 sep->se_class = newstr(s + 1);
1848 } else
1849 sep->se_class = newstr(RESOURCE_RC);
1850 #endif
1851 if ((s = strrchr(sep->se_user, ':')) != NULL) {
1852 *s = '\0';
1853 sep->se_group = newstr(s + 1);
1854 } else
1855 sep->se_group = NULL;
1856 sep->se_server = newstr(sskip(&cp));
1857 if ((sep->se_server_name = strrchr(sep->se_server, '/')))
1858 sep->se_server_name++;
1859 if (strcmp(sep->se_server, "internal") == 0) {
1860 struct biltin *bi;
1862 for (bi = biltins; bi->bi_service; bi++)
1863 if (bi->bi_socktype == sep->se_socktype &&
1864 matchservent(bi->bi_service, sep->se_service,
1865 sep->se_proto))
1866 break;
1867 if (bi->bi_service == 0) {
1868 syslog(LOG_ERR, "internal service %s unknown",
1869 sep->se_service);
1870 goto more;
1872 sep->se_accept = 1; /* force accept mode for built-ins */
1873 sep->se_bi = bi;
1874 } else
1875 sep->se_bi = NULL;
1876 if (sep->se_maxperip < 0)
1877 sep->se_maxperip = maxperip;
1878 if (sep->se_maxcpm < 0)
1879 sep->se_maxcpm = maxcpm;
1880 if (sep->se_maxchild < 0) { /* apply default max-children */
1881 if (sep->se_bi && sep->se_bi->bi_maxchild >= 0)
1882 sep->se_maxchild = sep->se_bi->bi_maxchild;
1883 else if (sep->se_accept)
1884 sep->se_maxchild = maxchild > 0 ? maxchild : 0;
1885 else
1886 sep->se_maxchild = 1;
1888 if (sep->se_maxchild > 0) {
1889 sep->se_pids = malloc(sep->se_maxchild * sizeof(*sep->se_pids));
1890 if (sep->se_pids == NULL) {
1891 syslog(LOG_ERR, "malloc: %m");
1892 exit(EX_OSERR);
1895 argc = 0;
1896 for (arg = skip(&cp); cp; arg = skip(&cp))
1897 if (argc < MAXARGV) {
1898 sep->se_argv[argc++] = newstr(arg);
1899 } else {
1900 syslog(LOG_ERR,
1901 "%s: too many arguments for service %s",
1902 CONFIG, sep->se_service);
1903 goto more;
1905 while (argc <= MAXARGV)
1906 sep->se_argv[argc++] = NULL;
1907 for (i = 0; i < PERIPSIZE; ++i)
1908 LIST_INIT(&sep->se_conn[i]);
1909 #ifdef IPSEC
1910 sep->se_policy = policy ? newstr(policy) : NULL;
1911 #endif
1912 return (sep);
1915 void
1916 freeconfig(struct servtab *cp)
1918 int i;
1920 if (cp->se_service)
1921 free(cp->se_service);
1922 if (cp->se_proto)
1923 free(cp->se_proto);
1924 if (cp->se_user)
1925 free(cp->se_user);
1926 if (cp->se_group)
1927 free(cp->se_group);
1928 #ifdef LOGIN_CAP
1929 if (cp->se_class)
1930 free(cp->se_class);
1931 #endif
1932 if (cp->se_server)
1933 free(cp->se_server);
1934 if (cp->se_pids)
1935 free(cp->se_pids);
1936 for (i = 0; i < MAXARGV; i++)
1937 if (cp->se_argv[i])
1938 free(cp->se_argv[i]);
1939 free_connlist(cp);
1940 #ifdef IPSEC
1941 if (cp->se_policy)
1942 free(cp->se_policy);
1943 #endif
1948 * Safe skip - if skip returns null, log a syntax error in the
1949 * configuration file and exit.
1951 char *
1952 sskip(char **cpp)
1954 char *cp;
1956 cp = skip(cpp);
1957 if (cp == NULL) {
1958 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1959 exit(EX_DATAERR);
1961 return (cp);
1964 char *
1965 skip(char **cpp)
1967 char *cp = *cpp;
1968 char *start;
1969 char quote = '\0';
1971 again:
1972 while (*cp == ' ' || *cp == '\t')
1973 cp++;
1974 if (*cp == '\0') {
1975 int c;
1977 c = getc(fconfig);
1978 ungetc(c, fconfig);
1979 if (c == ' ' || c == '\t')
1980 if ((cp = nextline(fconfig)))
1981 goto again;
1982 *cpp = (char *)0;
1983 return ((char *)0);
1985 if (*cp == '"' || *cp == '\'')
1986 quote = *cp++;
1987 start = cp;
1988 if (quote)
1989 while (*cp && *cp != quote)
1990 cp++;
1991 else
1992 while (*cp && *cp != ' ' && *cp != '\t')
1993 cp++;
1994 if (*cp != '\0')
1995 *cp++ = '\0';
1996 *cpp = cp;
1997 return (start);
2000 char *
2001 nextline(FILE *fd)
2003 char *cp;
2005 if (fgets(line, sizeof (line), fd) == NULL)
2006 return ((char *)0);
2007 cp = strchr(line, '\n');
2008 if (cp)
2009 *cp = '\0';
2010 return (line);
2013 char *
2014 newstr(const char *cp)
2016 char *cr;
2018 if ((cr = strdup(cp != NULL ? cp : "")))
2019 return (cr);
2020 syslog(LOG_ERR, "strdup: %m");
2021 exit(EX_OSERR);
2024 void
2025 inetd_setproctitle(const char *a, int s)
2027 socklen_t size;
2028 struct sockaddr_storage ss;
2029 char buf[80], pbuf[INET6_ADDRSTRLEN];
2031 size = sizeof(ss);
2032 if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
2033 getnameinfo((struct sockaddr *)&ss, size, pbuf, sizeof(pbuf),
2034 NULL, 0, NI_NUMERICHOST|NI_WITHSCOPEID);
2035 sprintf(buf, "%s [%s]", a, pbuf);
2036 } else
2037 sprintf(buf, "%s", a);
2038 setproctitle("%s", buf);
2042 check_loop(const struct sockaddr *sa, const struct servtab *sep)
2044 struct servtab *se2;
2045 char pname[INET6_ADDRSTRLEN];
2047 for (se2 = servtab; se2; se2 = se2->se_next) {
2048 if (!se2->se_bi || se2->se_socktype != SOCK_DGRAM)
2049 continue;
2051 switch (se2->se_family) {
2052 case AF_INET:
2053 if (((const struct sockaddr_in *)sa)->sin_port ==
2054 se2->se_ctrladdr4.sin_port)
2055 goto isloop;
2056 continue;
2057 #ifdef INET6
2058 case AF_INET6:
2059 if (((const struct sockaddr_in *)sa)->sin_port ==
2060 se2->se_ctrladdr4.sin_port)
2061 goto isloop;
2062 continue;
2063 #endif
2064 default:
2065 continue;
2067 isloop:
2068 getnameinfo(sa, sa->sa_len, pname, sizeof(pname), NULL, 0,
2069 NI_NUMERICHOST|NI_WITHSCOPEID);
2070 syslog(LOG_WARNING, "%s/%s:%s/%s loop request REFUSED from %s",
2071 sep->se_service, sep->se_proto,
2072 se2->se_service, se2->se_proto,
2073 pname);
2074 return 1;
2076 return 0;
2080 * print_service:
2081 * Dump relevant information to stderr
2083 void
2084 print_service(const char *action, const struct servtab *sep)
2086 fprintf(stderr,
2087 "%s: %s proto=%s accept=%d max=%d user=%s group=%s"
2088 #ifdef LOGIN_CAP
2089 "class=%s"
2090 #endif
2091 " builtin=%p server=%s"
2092 #ifdef IPSEC
2093 " policy=\"%s\""
2094 #endif
2095 "\n",
2096 action, sep->se_service, sep->se_proto,
2097 sep->se_accept, sep->se_maxchild, sep->se_user, sep->se_group,
2098 #ifdef LOGIN_CAP
2099 sep->se_class,
2100 #endif
2101 (void *) sep->se_bi, sep->se_server
2102 #ifdef IPSEC
2103 , (sep->se_policy ? sep->se_policy : "")
2104 #endif
2108 #define CPMHSIZE 256
2109 #define CPMHMASK (CPMHSIZE-1)
2110 #define CHTGRAN 10
2111 #define CHTSIZE 6
2113 typedef struct CTime {
2114 unsigned long ct_Ticks;
2115 int ct_Count;
2116 } CTime;
2118 typedef struct CHash {
2119 union {
2120 struct in_addr c4_Addr;
2121 struct in6_addr c6_Addr;
2122 } cu_Addr;
2123 #define ch_Addr4 cu_Addr.c4_Addr
2124 #define ch_Addr6 cu_Addr.c6_Addr
2125 int ch_Family;
2126 time_t ch_LTime;
2127 char *ch_Service;
2128 CTime ch_Times[CHTSIZE];
2129 } CHash;
2131 CHash CHashAry[CPMHSIZE];
2134 cpmip(const struct servtab *sep, int ctrl)
2136 struct sockaddr_storage rss;
2137 socklen_t rssLen = sizeof(rss);
2138 int r = 0;
2141 * If getpeername() fails, just let it through (if logging is
2142 * enabled the condition is caught elsewhere)
2145 if (sep->se_maxcpm > 0 &&
2146 getpeername(ctrl, (struct sockaddr *)&rss, &rssLen) == 0 ) {
2147 time_t t = time(NULL);
2148 int hv = 0xABC3D20F;
2149 int i;
2150 int cnt = 0;
2151 CHash *chBest = NULL;
2152 unsigned int ticks = t / CHTGRAN;
2153 struct sockaddr_in *sin4;
2154 #ifdef INET6
2155 struct sockaddr_in6 *sin6;
2156 #endif
2158 sin4 = (struct sockaddr_in *)&rss;
2159 #ifdef INET6
2160 sin6 = (struct sockaddr_in6 *)&rss;
2161 #endif
2163 char *p;
2164 int addrlen;
2166 switch (rss.ss_family) {
2167 case AF_INET:
2168 p = (char *)&sin4->sin_addr;
2169 addrlen = sizeof(struct in_addr);
2170 break;
2171 #ifdef INET6
2172 case AF_INET6:
2173 p = (char *)&sin6->sin6_addr;
2174 addrlen = sizeof(struct in6_addr);
2175 break;
2176 #endif
2177 default:
2178 /* should not happen */
2179 return -1;
2182 for (i = 0; i < addrlen; ++i, ++p) {
2183 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2185 hv = (hv ^ (hv >> 16));
2187 for (i = 0; i < 5; ++i) {
2188 CHash *ch = &CHashAry[(hv + i) & CPMHMASK];
2190 if (rss.ss_family == AF_INET &&
2191 ch->ch_Family == AF_INET &&
2192 sin4->sin_addr.s_addr == ch->ch_Addr4.s_addr &&
2193 ch->ch_Service && strcmp(sep->se_service,
2194 ch->ch_Service) == 0) {
2195 chBest = ch;
2196 break;
2198 #ifdef INET6
2199 if (rss.ss_family == AF_INET6 &&
2200 ch->ch_Family == AF_INET6 &&
2201 IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2202 &ch->ch_Addr6) != 0 &&
2203 ch->ch_Service && strcmp(sep->se_service,
2204 ch->ch_Service) == 0) {
2205 chBest = ch;
2206 break;
2208 #endif
2209 if (chBest == NULL || ch->ch_LTime == 0 ||
2210 ch->ch_LTime < chBest->ch_LTime) {
2211 chBest = ch;
2214 if ((rss.ss_family == AF_INET &&
2215 (chBest->ch_Family != AF_INET ||
2216 sin4->sin_addr.s_addr != chBest->ch_Addr4.s_addr)) ||
2217 chBest->ch_Service == NULL ||
2218 strcmp(sep->se_service, chBest->ch_Service) != 0) {
2219 chBest->ch_Family = sin4->sin_family;
2220 chBest->ch_Addr4 = sin4->sin_addr;
2221 if (chBest->ch_Service)
2222 free(chBest->ch_Service);
2223 chBest->ch_Service = strdup(sep->se_service);
2224 bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2226 #ifdef INET6
2227 if ((rss.ss_family == AF_INET6 &&
2228 (chBest->ch_Family != AF_INET6 ||
2229 IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2230 &chBest->ch_Addr6) == 0)) ||
2231 chBest->ch_Service == NULL ||
2232 strcmp(sep->se_service, chBest->ch_Service) != 0) {
2233 chBest->ch_Family = sin6->sin6_family;
2234 chBest->ch_Addr6 = sin6->sin6_addr;
2235 if (chBest->ch_Service)
2236 free(chBest->ch_Service);
2237 chBest->ch_Service = strdup(sep->se_service);
2238 bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2240 #endif
2241 chBest->ch_LTime = t;
2243 CTime *ct = &chBest->ch_Times[ticks % CHTSIZE];
2244 if (ct->ct_Ticks != ticks) {
2245 ct->ct_Ticks = ticks;
2246 ct->ct_Count = 0;
2248 ++ct->ct_Count;
2250 for (i = 0; i < CHTSIZE; ++i) {
2251 CTime *ct = &chBest->ch_Times[i];
2252 if (ct->ct_Ticks <= ticks &&
2253 ct->ct_Ticks >= ticks - CHTSIZE) {
2254 cnt += ct->ct_Count;
2257 if (cnt * (CHTSIZE * CHTGRAN) / 60 > sep->se_maxcpm) {
2258 char pname[INET6_ADDRSTRLEN];
2260 getnameinfo((struct sockaddr *)&rss,
2261 ((struct sockaddr *)&rss)->sa_len,
2262 pname, sizeof(pname), NULL, 0,
2263 NI_NUMERICHOST|NI_WITHSCOPEID);
2264 r = -1;
2265 syslog(LOG_ERR,
2266 "%s from %s exceeded counts/min (limit %d/min)",
2267 sep->se_service, pname,
2268 sep->se_maxcpm);
2271 return(r);
2274 static struct conninfo *
2275 search_conn(struct servtab *sep, int ctrl)
2277 struct sockaddr_storage ss;
2278 socklen_t sslen = sizeof(ss);
2279 struct conninfo *conn;
2280 int hv;
2281 char pname[NI_MAXHOST], pname2[NI_MAXHOST];
2283 if (sep->se_maxperip <= 0)
2284 return NULL;
2287 * If getpeername() fails, just let it through (if logging is
2288 * enabled the condition is caught elsewhere)
2290 if (getpeername(ctrl, (struct sockaddr *)&ss, &sslen) != 0)
2291 return NULL;
2293 switch (ss.ss_family) {
2294 case AF_INET:
2295 hv = hashval((char *)&((struct sockaddr_in *)&ss)->sin_addr,
2296 sizeof(struct in_addr));
2297 break;
2298 #ifdef INET6
2299 case AF_INET6:
2300 hv = hashval((char *)&((struct sockaddr_in6 *)&ss)->sin6_addr,
2301 sizeof(struct in6_addr));
2302 break;
2303 #endif
2304 default:
2306 * Since we only support AF_INET and AF_INET6, just
2307 * let other than AF_INET and AF_INET6 through.
2309 return NULL;
2312 if (getnameinfo((struct sockaddr *)&ss, sslen, pname, sizeof(pname),
2313 NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID) != 0)
2314 return NULL;
2316 LIST_FOREACH(conn, &sep->se_conn[hv], co_link) {
2317 if (getnameinfo((struct sockaddr *)&conn->co_addr,
2318 conn->co_addr.ss_len, pname2, sizeof(pname2), NULL, 0,
2319 NI_NUMERICHOST | NI_WITHSCOPEID) == 0 &&
2320 strcmp(pname, pname2) == 0)
2321 break;
2324 if (conn == NULL) {
2325 if ((conn = malloc(sizeof(struct conninfo))) == NULL) {
2326 syslog(LOG_ERR, "malloc: %m");
2327 exit(EX_OSERR);
2329 conn->co_proc = malloc(sep->se_maxperip * sizeof(*conn->co_proc));
2330 if (conn->co_proc == NULL) {
2331 syslog(LOG_ERR, "malloc: %m");
2332 exit(EX_OSERR);
2334 memcpy(&conn->co_addr, (struct sockaddr *)&ss, sslen);
2335 conn->co_numchild = 0;
2336 LIST_INSERT_HEAD(&sep->se_conn[hv], conn, co_link);
2340 * Since a child process is not invoked yet, we cannot
2341 * determine a pid of a child. So, co_proc and co_numchild
2342 * should be filled leter.
2345 return conn;
2348 static int
2349 room_conn(struct servtab *sep, struct conninfo *conn)
2351 char pname[NI_MAXHOST];
2353 if (conn->co_numchild >= sep->se_maxperip) {
2354 getnameinfo((struct sockaddr *)&conn->co_addr,
2355 conn->co_addr.ss_len, pname, sizeof(pname), NULL, 0,
2356 NI_NUMERICHOST | NI_WITHSCOPEID);
2357 syslog(LOG_ERR, "%s from %s exceeded counts (limit %d)",
2358 sep->se_service, pname, sep->se_maxperip);
2359 return 0;
2361 return 1;
2364 static void
2365 addchild_conn(struct conninfo *conn, pid_t pid)
2367 struct procinfo *proc;
2369 if (conn == NULL)
2370 return;
2372 if ((proc = search_proc(pid, 1)) != NULL) {
2373 if (proc->pr_conn != NULL) {
2374 syslog(LOG_ERR,
2375 "addchild_conn: child already on process list");
2376 exit(EX_OSERR);
2378 proc->pr_conn = conn;
2381 conn->co_proc[conn->co_numchild++] = proc;
2384 static void
2385 reapchild_conn(pid_t pid)
2387 struct procinfo *proc;
2388 struct conninfo *conn;
2389 int i;
2391 if ((proc = search_proc(pid, 0)) == NULL)
2392 return;
2393 if ((conn = proc->pr_conn) == NULL)
2394 return;
2395 for (i = 0; i < conn->co_numchild; ++i)
2396 if (conn->co_proc[i] == proc) {
2397 conn->co_proc[i] = conn->co_proc[--conn->co_numchild];
2398 break;
2400 free_proc(proc);
2401 free_conn(conn);
2404 static void
2405 resize_conn(struct servtab *sep, int maxpip)
2407 struct conninfo *conn;
2408 int i, j;
2410 if (sep->se_maxperip <= 0)
2411 return;
2412 if (maxpip <= 0) {
2413 free_connlist(sep);
2414 return;
2416 for (i = 0; i < PERIPSIZE; ++i) {
2417 LIST_FOREACH(conn, &sep->se_conn[i], co_link) {
2418 for (j = maxpip; j < conn->co_numchild; ++j)
2419 free_proc(conn->co_proc[j]);
2420 conn->co_proc = realloc(conn->co_proc,
2421 maxpip * sizeof(*conn->co_proc));
2422 if (conn->co_proc == NULL) {
2423 syslog(LOG_ERR, "realloc: %m");
2424 exit(EX_OSERR);
2426 if (conn->co_numchild > maxpip)
2427 conn->co_numchild = maxpip;
2432 static void
2433 free_connlist(struct servtab *sep)
2435 struct conninfo *conn;
2436 int i, j;
2438 for (i = 0; i < PERIPSIZE; ++i) {
2439 while ((conn = LIST_FIRST(&sep->se_conn[i])) != NULL) {
2440 for (j = 0; j < conn->co_numchild; ++j)
2441 free_proc(conn->co_proc[j]);
2442 conn->co_numchild = 0;
2443 free_conn(conn);
2448 static void
2449 free_conn(struct conninfo *conn)
2451 if (conn == NULL)
2452 return;
2453 if (conn->co_numchild <= 0) {
2454 LIST_REMOVE(conn, co_link);
2455 free(conn->co_proc);
2456 free(conn);
2460 static struct procinfo *
2461 search_proc(pid_t pid, int add)
2463 struct procinfo *proc;
2464 int hv;
2466 hv = hashval((char *)&pid, sizeof(pid));
2467 LIST_FOREACH(proc, &proctable[hv], pr_link) {
2468 if (proc->pr_pid == pid)
2469 break;
2471 if (proc == NULL && add) {
2472 if ((proc = malloc(sizeof(struct procinfo))) == NULL) {
2473 syslog(LOG_ERR, "malloc: %m");
2474 exit(EX_OSERR);
2476 proc->pr_pid = pid;
2477 proc->pr_conn = NULL;
2478 LIST_INSERT_HEAD(&proctable[hv], proc, pr_link);
2480 return proc;
2483 static void
2484 free_proc(struct procinfo *proc)
2486 if (proc == NULL)
2487 return;
2488 LIST_REMOVE(proc, pr_link);
2489 free(proc);
2492 static int
2493 hashval(char *p, int len)
2495 int i, hv = 0xABC3D20F;
2497 for (i = 0; i < len; ++i, ++p)
2498 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2499 hv = (hv ^ (hv >> 16)) & (PERIPSIZE - 1);
2500 return hv;