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
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. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#) Copyright (c) 1983, 1991, 1993, 1994 The Regents of the University of California. All rights reserved.
30 * @(#)from: inetd.c 8.4 (Berkeley) 4/13/94
31 * $FreeBSD: src/usr.sbin/inetd/inetd.c,v 1.80.2.11 2003/04/05 13:39:18 dwmalone Exp $
35 * Inetd - Internet super-server
37 * This program invokes all internet services as needed. Connection-oriented
38 * services are invoked each time a connection is made, by creating a process.
39 * This process is passed the connection as file descriptor 0 and is expected
40 * to do a getpeername to find out the source host and port.
42 * Datagram oriented services are invoked when a datagram
43 * arrives; a process is created and passed a pending message
44 * on file descriptor 0. Datagram servers may either connect
45 * to their peer, freeing up the original socket for inetd
46 * to receive further messages on, or ``take over the socket'',
47 * processing all arriving datagrams and, eventually, timing
48 * out. The first type of server is said to be ``multi-threaded'';
49 * the second type of server ``single-threaded''.
51 * Inetd uses a configuration file which is read at startup
52 * and, possibly, at some later time in response to a hangup signal.
53 * The configuration file is ``free format'' with fields given in the
54 * order shown below. Continuation lines for an entry must begin with
55 * a space or tab. All fields must be present in each entry.
57 * service name must be in /etc/services
58 * or name a tcpmux service
59 * or specify a unix domain socket
60 * socket type stream/dgram/raw/rdm/seqpacket
61 * protocol tcp[4][6][/ttcp], udp[4][6], unix
62 * wait/nowait single-threaded/multi-threaded
63 * user user to run daemon as
64 * server program full path name
65 * server program arguments maximum of MAXARGS (20)
67 * TCP services without official port numbers are handled with the
68 * RFC1078-based tcpmux internal service. Tcpmux listens on port 1 for
69 * requests. When a connection is made from a foreign host, the service
70 * requested is passed to tcpmux, which looks it up in the servtab list
71 * and returns the proper entry for the service. Tcpmux returns a
72 * negative reply if the service doesn't exist, otherwise the invoked
73 * server is expected to return the positive reply if the service type in
74 * inetd.conf file has the prefix "tcpmux/". If the service type has the
75 * prefix "tcpmux/+", tcpmux will return the positive reply for the
76 * process; this is for compatibility with older server code, and also
77 * allows you to invoke programs that use stdin/stdout without putting any
78 * special server code in them. Services that use tcpmux are "nowait"
79 * because they do not have a well-known port and hence cannot listen
83 * service name/version must be in /etc/rpc
84 * socket type stream/dgram/raw/rdm/seqpacket
85 * protocol rpc/tcp, rpc/udp
86 * wait/nowait single-threaded/multi-threaded
87 * user user to run daemon as
88 * server program full path name
89 * server program arguments maximum of MAXARGS
91 * Comment lines are indicated by a `#' in column 1.
93 #include <sys/param.h>
94 #include <sys/ioctl.h>
97 #include <sys/resource.h>
101 #include <netinet/in.h>
102 #include <netinet/tcp.h>
103 #include <arpa/inet.h>
105 #include <rpc/pmap_clnt.h>
122 #include <sysexits.h>
126 #include "pathnames.h"
128 /* wrapper for KAME-special getnameinfo() */
129 #ifndef NI_WITHSCOPEID
130 #define NI_WITHSCOPEID 0
133 #ifndef LIBWRAP_ALLOW_FACILITY
134 # define LIBWRAP_ALLOW_FACILITY LOG_AUTH
136 #ifndef LIBWRAP_ALLOW_SEVERITY
137 # define LIBWRAP_ALLOW_SEVERITY LOG_INFO
139 #ifndef LIBWRAP_DENY_FACILITY
140 # define LIBWRAP_DENY_FACILITY LOG_AUTH
142 #ifndef LIBWRAP_DENY_SEVERITY
143 # define LIBWRAP_DENY_SEVERITY LOG_WARNING
146 #define ISWRAP(sep) \
147 ( ((wrap_ex && !(sep)->se_bi) || (wrap_bi && (sep)->se_bi)) \
148 && (sep->se_family == AF_INET || sep->se_family == AF_INET6) \
149 && ( ((sep)->se_accept && (sep)->se_socktype == SOCK_STREAM) \
150 || (sep)->se_socktype == SOCK_DGRAM))
153 #include <login_cap.h>
156 #define RESOURCE_RC "daemon"
161 #define MAXCHILD -1 /* maximum number of this service
166 #define MAXCPM -1 /* rate limit invocations from a
167 single remote address,
172 #define MAXPERIP -1 /* maximum number of this service
173 from a single remote address,
178 #define TOOMANY 256 /* don't start more than TOOMANY */
180 #define CNT_INTVL 60 /* servers in CNT_INTVL sec. */
181 #define RETRYTIME (60*10) /* retry after bind or server fail */
182 #define MAX_MAXCHLD 32767 /* max allowable max children */
184 #define SIGBLOCK (sigmask(SIGCHLD)|sigmask(SIGHUP)|sigmask(SIGALRM))
186 void close_sep(struct servtab *);
187 void flag_signal(int);
188 void flag_config(int);
190 int cpmip(const struct servtab *, int);
191 void endconfig(void);
192 struct servtab *enter(struct servtab *);
193 void freeconfig(struct servtab *);
194 struct servtab *getconfigent(void);
195 int matchservent(const char *, const char *, const char *);
196 char *nextline(FILE *);
197 void addchild(struct servtab *, int);
198 void flag_reapchild(int);
199 void reapchild(void);
200 void enable(struct servtab *);
201 void disable(struct servtab *);
202 void flag_retry(int);
205 void setup(struct servtab *);
206 void unregisterrpc(struct servtab *sep);
207 static struct conninfo *search_conn(struct servtab *sep, int ctrl);
208 static int room_conn(struct servtab *sep, struct conninfo *conn);
209 static void addchild_conn(struct conninfo *conn, pid_t pid);
210 static void reapchild_conn(pid_t pid);
211 static void free_conn(struct conninfo *conn);
212 static void resize_conn(struct servtab *sep, int maxperip);
213 static void free_connlist(struct servtab *sep);
214 static void free_proc(struct procinfo *);
215 static struct procinfo *search_proc(pid_t pid, int add);
216 static int hashval(char *p, int len);
224 int maxsock; /* highest-numbered descriptor */
228 int toomany = TOOMANY;
229 int maxchild = MAXCHILD;
231 int maxperip = MAXPERIP;
234 char *hostname = NULL;
235 struct sockaddr_in *bind_sa4;
238 struct sockaddr_in6 *bind_sa6;
249 struct servtab *servtab;
251 extern struct biltin biltins[];
253 #define NUMINT (sizeof(intab) / sizeof(struct inent))
254 const char *CONFIG = _PATH_INETDCONF;
255 const char *pid_file = _PATH_INETDPID;
257 static LIST_HEAD(, procinfo) proctable[PERIPSIZE];
260 getvalue(const char *arg, int *value, const char *whine)
265 tmp = strtol(arg, &p, 0);
267 syslog(LOG_ERR, whine, arg);
268 return 1; /* failure */
271 return 0; /* success */
275 whichaf(struct request_info *req)
279 sa = (struct sockaddr *)req->client->sin;
282 if (sa->sa_family == AF_INET6 &&
283 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)sa)->sin6_addr))
285 return sa->sa_family;
289 main(int argc, char **argv)
294 struct sigaction sa, saalrm, sachld, sahup, sapipe;
299 login_cap_t *lc = NULL;
301 struct request_info req;
303 char *service = NULL;
305 struct sockaddr peer_un;
306 struct sockaddr_in peer_un4;
307 struct sockaddr_in6 peer_un6;
308 struct sockaddr_storage peer_max;
310 #define peer p_un.peer_un
311 #define peer4 p_un.peer_un4
312 #define peer6 p_un.peer_un6
313 #define peermax p_un.peer_max
315 struct addrinfo hints, *res;
316 const char *servname;
318 struct conninfo *conn;
320 openlog("inetd", LOG_PID | LOG_NOWAIT | LOG_PERROR, LOG_DAEMON);
322 while ((ch = getopt(argc, argv, "dlwWR:a:c:C:p:s:")) != -1)
332 getvalue(optarg, &toomany,
333 "-R %s: bad value for service invocation rate");
336 getvalue(optarg, &maxchild,
337 "-c %s: bad value for maximum children");
340 getvalue(optarg, &maxcpm,
341 "-C %s: bad value for maximum children/minute");
350 getvalue(optarg, &maxperip,
351 "-s %s: bad value for maximum children per source address");
362 "usage: inetd [-dlwW] [-a address] [-R rate]"
363 " [-c maximum] [-C rate]"
364 " [-p pidfile] [conf-file]");
368 * Initialize Bind Addrs.
369 * When hostname is NULL, wild card bind addrs are obtained from
370 * getaddrinfo(). But getaddrinfo() requires at least one of
371 * hostname or servname is non NULL.
372 * So when hostname is NULL, set dummy value to servname.
374 servname = (hostname == NULL) ? "discard" /* dummy */ : NULL;
376 bzero(&hints, sizeof(struct addrinfo));
377 hints.ai_flags = AI_PASSIVE;
378 hints.ai_family = AF_UNSPEC;
379 error = getaddrinfo(hostname, servname, &hints, &res);
381 syslog(LOG_ERR, "-a %s: %s", hostname, gai_strerror(error));
382 if (error == EAI_SYSTEM)
383 syslog(LOG_ERR, "%s", strerror(errno));
387 if (res->ai_addr == NULL) {
388 syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
391 switch (res->ai_addr->sa_family) {
395 bind_sa4 = (struct sockaddr_in *)res->ai_addr;
396 /* init port num in case servname is dummy */
397 bind_sa4->sin_port = 0;
404 bind_sa6 = (struct sockaddr_in6 *)res->ai_addr;
405 /* init port num in case servname is dummy */
406 bind_sa6->sin6_port = 0;
417 } while ((res = res->ai_next) != NULL);
423 syslog(LOG_ERR, "-a %s: unknown address family", hostname);
429 umask(mask = umask(0777));
438 if (daemon(0, 0) < 0) {
439 syslog(LOG_WARNING, "daemon(0,0) failed: %m");
441 /* From now on we don't want syslog messages going to stderr. */
443 openlog("inetd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
445 * In case somebody has started inetd manually, we need to
446 * clear the logname, so that old servers run as root do not
447 * get the user's logname..
449 if (setlogin("") < 0) {
450 syslog(LOG_WARNING, "cannot clear logname: %m");
451 /* no big deal if it fails.. */
454 fp = fopen(pid_file, "w");
456 fprintf(fp, "%ld\n", (long)pid);
459 syslog(LOG_WARNING, "%s: %m", pid_file);
462 for (i = 0; i < PERIPSIZE; ++i)
463 LIST_INIT(&proctable[i]);
465 sigemptyset(&sa.sa_mask);
466 sigaddset(&sa.sa_mask, SIGALRM);
467 sigaddset(&sa.sa_mask, SIGCHLD);
468 sigaddset(&sa.sa_mask, SIGHUP);
469 sa.sa_handler = flag_retry;
470 sigaction(SIGALRM, &sa, &saalrm);
472 sa.sa_handler = flag_config;
473 sigaction(SIGHUP, &sa, &sahup);
474 sa.sa_handler = flag_reapchild;
475 sigaction(SIGCHLD, &sa, &sachld);
476 sa.sa_handler = SIG_IGN;
477 sigaction(SIGPIPE, &sa, &sapipe);
480 /* space for daemons to overwrite environment for ps */
481 #define DUMMYSIZE 100
482 char dummy[DUMMYSIZE];
484 memset(dummy, 'x', DUMMYSIZE - 1);
485 dummy[DUMMYSIZE - 1] = '\0';
486 if (setenv("inetd_dummy", dummy, 1) == -1)
487 syslog(LOG_WARNING, "setenv: cannot set inetd_dummy=%s: %m", dummy);
491 if (pipe2(signalpipe, O_CLOEXEC) != 0) {
492 syslog(LOG_ERR, "pipe2 (O_CLOEXEC): %m");
495 FD_SET(signalpipe[0], &allsock);
499 if (signalpipe[0] > maxsock)
500 maxsock = signalpipe[0];
501 if (signalpipe[1] > maxsock)
502 maxsock = signalpipe[1];
510 syslog(LOG_ERR, "%s: nsock=0", __func__);
515 if ((n = select(maxsock + 1, &readable, NULL, NULL, NULL)) <= 0) {
516 if (n < 0 && errno != EINTR) {
517 syslog(LOG_WARNING, "select: %m");
522 /* handle any queued signal flags */
523 if (FD_ISSET(signalpipe[0], &readable)) {
525 if (ioctl(signalpipe[0], FIONREAD, &nsig) != 0) {
526 syslog(LOG_ERR, "ioctl: %m");
529 while (--nsig >= 0) {
531 if (read(signalpipe[0], &c, 1) != 1) {
532 syslog(LOG_ERR, "read: %m");
536 warnx("handling signal flag %c", c);
538 case 'A': /* sigalrm */
541 case 'C': /* sigchld */
544 case 'H': /* sighup */
550 for (sep = servtab; n && sep; sep = sep->se_next)
551 if (sep->se_fd != -1 && FD_ISSET(sep->se_fd, &readable)) {
554 warnx("someone wants %s", sep->se_service);
555 dofork = !sep->se_bi || sep->se_bi->bi_fork || ISWRAP(sep);
557 if (sep->se_accept && sep->se_socktype == SOCK_STREAM) {
559 if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
560 syslog(LOG_ERR, "ioctl (FIONBIO, 1): %m");
561 ctrl = accept(sep->se_fd, NULL, NULL);
563 warnx("accept, ctrl %d", ctrl);
567 "accept (for %s): %m",
569 if (sep->se_accept &&
570 sep->se_socktype == SOCK_STREAM)
575 if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
576 syslog(LOG_ERR, "ioctl1(FIONBIO, 0): %m");
577 if (ioctl(ctrl, FIONBIO, &i) < 0)
578 syslog(LOG_ERR, "ioctl2(FIONBIO, 0): %m");
579 if (cpmip(sep, ctrl) < 0) {
584 (conn = search_conn(sep, ctrl)) != NULL &&
585 !room_conn(sep, conn)) {
591 if (dolog && !ISWRAP(sep)) {
592 char pname[INET6_ADDRSTRLEN] = "unknown";
595 if (getpeername(ctrl, (struct sockaddr *)
598 if (recvfrom(ctrl, buf, sizeof(buf),
600 (struct sockaddr *)&peermax,
602 getnameinfo((struct sockaddr *)&peermax,
604 pname, sizeof(pname),
610 getnameinfo((struct sockaddr *)&peermax,
612 pname, sizeof(pname),
617 syslog(LOG_INFO,"%s from %s", sep->se_service, pname);
622 * Fork for all external services, builtins which need to
623 * fork and anything we're wrapping (as wrapping might
624 * block or use hosts_options(5) twist).
627 if (sep->se_count++ == 0)
628 gettimeofday(&sep->se_time, NULL);
629 else if (toomany > 0 && sep->se_count >= toomany) {
632 gettimeofday(&now, NULL);
633 if (now.tv_sec - sep->se_time.tv_sec >
639 "%s/%s server failing (looping), service terminated",
640 sep->se_service, sep->se_proto);
641 if (sep->se_accept &&
642 sep->se_socktype == SOCK_STREAM)
657 syslog(LOG_ERR, "fork: %m");
658 if (sep->se_accept &&
659 sep->se_socktype == SOCK_STREAM)
667 addchild_conn(conn, pid);
673 sigaction(SIGALRM, &saalrm, NULL);
674 sigaction(SIGCHLD, &sachld, NULL);
675 sigaction(SIGHUP, &sahup, NULL);
676 /* SIGPIPE reset before exec */
679 * Call tcpmux to find the real service to exec.
682 sep->se_bi->bi_fn == (bi_fn_t *) tcpmux) {
690 inetd_setproctitle("wrapping", ctrl);
691 service = sep->se_server_name ?
692 sep->se_server_name : sep->se_service;
693 request_init(&req, RQ_DAEMON, service, RQ_FILE, ctrl, NULL);
695 deny_severity = LIBWRAP_DENY_FACILITY|LIBWRAP_DENY_SEVERITY;
696 allow_severity = LIBWRAP_ALLOW_FACILITY|LIBWRAP_ALLOW_SEVERITY;
697 denied = !hosts_access(&req);
699 syslog(deny_severity,
700 "refused connection from %.500s, service %s (%s%s)",
701 eval_client(&req), service, sep->se_proto,
702 (whichaf(&req) == AF_INET6) ? "6" : "");
703 if (sep->se_socktype != SOCK_STREAM)
704 recv(ctrl, buf, sizeof (buf), 0);
711 syslog(allow_severity,
712 "connection from %.500s, service %s (%s%s)",
713 eval_client(&req), service, sep->se_proto,
714 (whichaf(&req) == AF_INET6) ? "6" : "");
718 (*sep->se_bi->bi_fn)(ctrl, sep);
722 getpid(), sep->se_server);
723 /* Clear close-on-exec. */
724 if (fcntl(ctrl, F_SETFD, 0) < 0) {
726 "%s/%s: fcntl (F_SETFD, 0): %m",
727 sep->se_service, sep->se_proto);
736 if ((pwd = getpwnam(sep->se_user)) == NULL) {
738 "%s/%s: %s: no such user",
739 sep->se_service, sep->se_proto,
741 if (sep->se_socktype != SOCK_STREAM)
742 recv(0, buf, sizeof (buf), 0);
746 if ( sep->se_group != NULL
747 && (grp = getgrnam(sep->se_group)) == NULL
750 "%s/%s: %s: no such group",
751 sep->se_service, sep->se_proto,
753 if (sep->se_socktype != SOCK_STREAM)
754 recv(0, buf, sizeof (buf), 0);
758 pwd->pw_gid = grp->gr_gid;
760 if ((lc = login_getclass(sep->se_class)) == NULL) {
761 /* error syslogged by getclass */
763 "%s/%s: %s: login class error",
764 sep->se_service, sep->se_proto,
766 if (sep->se_socktype != SOCK_STREAM)
767 recv(0, buf, sizeof (buf), 0);
773 "%s: can't setsid(): %m",
775 /* _exit(EX_OSERR); not fatal yet */
778 if (setusercontext(lc, pwd, pwd->pw_uid,
779 LOGIN_SETALL) != 0) {
781 "%s: can't setusercontext(..%s..): %m",
782 sep->se_service, sep->se_user);
788 if (setlogin(sep->se_user) < 0) {
790 "%s: can't setlogin(%s): %m",
791 sep->se_service, sep->se_user);
792 /* _exit(EX_OSERR); not yet */
794 if (setgid(pwd->pw_gid) < 0) {
796 "%s: can't set gid %d: %m",
797 sep->se_service, pwd->pw_gid);
800 initgroups(pwd->pw_name,
802 if (setuid(pwd->pw_uid) < 0) {
804 "%s: can't set uid %d: %m",
805 sep->se_service, pwd->pw_uid);
810 sigaction(SIGPIPE, &sapipe, NULL);
811 execv(sep->se_server, sep->se_argv);
813 "cannot execute %s: %m", sep->se_server);
814 if (sep->se_socktype != SOCK_STREAM)
815 recv(0, buf, sizeof (buf), 0);
820 if (sep->se_accept && sep->se_socktype == SOCK_STREAM)
827 * Add a signal flag to the signal flag queue for later handling
835 if (write(signalpipe[1], &ch, 1) != 1) {
836 syslog(LOG_ERR, "write: %m");
842 * Record a new child pid for this service. If we've reached the
843 * limit on children, then stop accepting incoming requests.
847 addchild(struct servtab *sep, pid_t pid)
849 if (sep->se_maxchild <= 0)
852 if (sep->se_numchild >= sep->se_maxchild) {
853 syslog(LOG_ERR, "%s: %d >= %d",
854 __func__, sep->se_numchild, sep->se_maxchild);
858 sep->se_pids[sep->se_numchild++] = pid;
859 if (sep->se_numchild == sep->se_maxchild)
864 * Some child process has exited. See if it's on somebody's list.
868 flag_reapchild(int signo __unused)
881 pid = wait3(&status, WNOHANG, NULL);
885 warnx("%d reaped, %s %u", pid,
886 WIFEXITED(status) ? "status" : "signal",
887 WIFEXITED(status) ? WEXITSTATUS(status)
889 for (sep = servtab; sep; sep = sep->se_next) {
890 for (k = 0; k < sep->se_numchild; k++)
891 if (sep->se_pids[k] == pid)
893 if (k == sep->se_numchild)
895 if (sep->se_numchild == sep->se_maxchild)
897 sep->se_pids[k] = sep->se_pids[--sep->se_numchild];
898 if (WIFSIGNALED(status) || WEXITSTATUS(status))
900 "%s[%d]: exited, %s %u",
902 WIFEXITED(status) ? "status" : "signal",
903 WIFEXITED(status) ? WEXITSTATUS(status)
912 flag_config(int signo __unused)
920 struct servtab *sep, *new, **sepp;
923 login_cap_t *lc = NULL;
928 syslog(LOG_ERR, "%s: %m", CONFIG);
931 for (sep = servtab; sep; sep = sep->se_next)
933 while ((new = getconfigent())) {
934 if (getpwnam(new->se_user) == NULL) {
936 "%s/%s: no such user '%s', service ignored",
937 new->se_service, new->se_proto, new->se_user);
940 if (new->se_group && getgrnam(new->se_group) == NULL) {
942 "%s/%s: no such group '%s', service ignored",
943 new->se_service, new->se_proto, new->se_group);
947 if ((lc = login_getclass(new->se_class)) == NULL) {
948 /* error syslogged by getclass */
950 "%s/%s: %s: login class error, service ignored",
951 new->se_service, new->se_proto, new->se_class);
956 for (sep = servtab; sep; sep = sep->se_next)
957 if (strcmp(sep->se_service, new->se_service) == 0 &&
958 strcmp(sep->se_proto, new->se_proto) == 0 &&
959 sep->se_socktype == new->se_socktype &&
960 sep->se_family == new->se_family)
965 #define SWAP(a, b) { typeof(a) c = a; a = b; b = c; }
966 omask = sigblock(SIGBLOCK);
967 if (sep->se_nomapped != new->se_nomapped) {
968 sep->se_nomapped = new->se_nomapped;
971 /* copy over outstanding child pids */
972 if (sep->se_maxchild > 0 && new->se_maxchild > 0) {
973 new->se_numchild = sep->se_numchild;
974 if (new->se_numchild > new->se_maxchild)
975 new->se_numchild = new->se_maxchild;
976 memcpy(new->se_pids, sep->se_pids,
977 new->se_numchild * sizeof(*new->se_pids));
979 SWAP(sep->se_pids, new->se_pids);
980 sep->se_maxchild = new->se_maxchild;
981 sep->se_numchild = new->se_numchild;
982 sep->se_maxcpm = new->se_maxcpm;
983 resize_conn(sep, new->se_maxperip);
984 sep->se_maxperip = new->se_maxperip;
985 sep->se_bi = new->se_bi;
986 /* might need to turn on or off service now */
987 if (sep->se_fd >= 0) {
988 if (sep->se_maxchild > 0
989 && sep->se_numchild == sep->se_maxchild) {
990 if (FD_ISSET(sep->se_fd, &allsock))
993 if (!FD_ISSET(sep->se_fd, &allsock))
997 sep->se_accept = new->se_accept;
998 SWAP(sep->se_user, new->se_user);
999 SWAP(sep->se_group, new->se_group);
1001 SWAP(sep->se_class, new->se_class);
1003 SWAP(sep->se_server, new->se_server);
1004 SWAP(sep->se_server_name, new->se_server_name);
1005 for (i = 0; i < MAXARGV; i++)
1006 SWAP(sep->se_argv[i], new->se_argv[i]);
1010 print_service("REDO", sep);
1014 print_service("ADD ", sep);
1016 sep->se_checked = 1;
1021 switch (sep->se_family) {
1023 if (no_v4bind != 0) {
1030 if (no_v6bind != 0) {
1038 if (sep->se_family != AF_UNIX) {
1039 sp = getservbyname(sep->se_service, sep->se_proto);
1041 syslog(LOG_ERR, "%s/%s: unknown service",
1042 sep->se_service, sep->se_proto);
1043 sep->se_checked = 0;
1047 switch (sep->se_family) {
1049 if (sp->s_port != sep->se_ctrladdr4.sin_port) {
1050 sep->se_ctrladdr4.sin_port =
1058 sep->se_ctrladdr6.sin6_port) {
1059 sep->se_ctrladdr6.sin6_port =
1066 if (sep->se_reset != 0 && sep->se_fd >= 0)
1069 rpc = getrpcbyname(sep->se_service);
1071 syslog(LOG_ERR, "%s/%s unknown RPC service",
1072 sep->se_service, sep->se_proto);
1073 if (sep->se_fd != -1)
1078 if (rpc->r_number != sep->se_rpc_prog) {
1079 if (sep->se_rpc_prog)
1081 sep->se_rpc_prog = rpc->r_number;
1082 if (sep->se_fd != -1)
1087 if (sep->se_fd == -1)
1092 * Purge anything not looked at above.
1094 omask = sigblock(SIGBLOCK);
1096 while ((sep = *sepp)) {
1097 if (sep->se_checked) {
1098 sepp = &sep->se_next;
1101 *sepp = sep->se_next;
1102 if (sep->se_fd >= 0)
1105 print_service("FREE", sep);
1106 if (sep->se_rpc && sep->se_rpc_prog > 0)
1115 unregisterrpc(struct servtab *sep)
1118 struct servtab *sepp;
1121 omask = sigblock(SIGBLOCK);
1122 for (sepp = servtab; sepp; sepp = sepp->se_next) {
1125 if (sep->se_checked == 0 ||
1127 sep->se_rpc_prog != sepp->se_rpc_prog)
1132 print_service("UNREG", sep);
1133 for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++)
1134 pmap_unset(sep->se_rpc_prog, i);
1135 if (sep->se_fd != -1)
1142 flag_retry(int signo __unused)
1150 struct servtab *sep;
1153 for (sep = servtab; sep; sep = sep->se_next)
1154 if (sep->se_fd == -1 && !ISMUX(sep))
1159 setup(struct servtab *sep)
1163 if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1165 warn("socket failed on %s/%s",
1166 sep->se_service, sep->se_proto);
1167 syslog(LOG_ERR, "%s/%s: socket: %m",
1168 sep->se_service, sep->se_proto);
1171 /* Set all listening sockets to close-on-exec. */
1172 if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
1173 syslog(LOG_ERR, "%s/%s: fcntl (F_SETFD, FD_CLOEXEC): %m",
1174 sep->se_service, sep->se_proto);
1178 #define turnon(fd, opt) \
1179 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1180 if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1181 turnon(sep->se_fd, SO_DEBUG) < 0)
1182 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1183 if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1184 syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1186 if (turnon(sep->se_fd, SO_PRIVSTATE) < 0)
1187 syslog(LOG_ERR, "setsockopt (SO_PRIVSTATE): %m");
1189 /* tftpd opens a new connection then needs more infos */
1190 if ((sep->se_family == AF_INET6) &&
1191 (strcmp(sep->se_proto, "udp") == 0) &&
1192 (sep->se_accept == 0) &&
1193 (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_PKTINFO,
1194 (char *)&on, sizeof (on)) < 0))
1195 syslog(LOG_ERR, "setsockopt (IPV6_RECVPKTINFO): %m");
1196 if (sep->se_family == AF_INET6) {
1197 int flag = sep->se_nomapped ? 1 : 0;
1198 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_V6ONLY,
1199 (char *)&flag, sizeof (flag)) < 0)
1200 syslog(LOG_ERR, "setsockopt (IPV6_V6ONLY): %m");
1203 if (sep->se_type == TTCP_TYPE)
1204 if (setsockopt(sep->se_fd, IPPROTO_TCP, TCP_NOPUSH,
1205 (char *)&on, sizeof (on)) < 0)
1206 syslog(LOG_ERR, "setsockopt (TCP_NOPUSH): %m");
1207 if (sep->se_family == AF_UNIX) {
1208 unlink(sep->se_ctrladdr_un.sun_path);
1209 umask(0777); /* Make socket with conservative permissions */
1211 if (bind(sep->se_fd, (struct sockaddr *)&sep->se_ctrladdr,
1212 sep->se_ctrladdr_size) < 0) {
1214 warn("bind failed on %s/%s",
1215 sep->se_service, sep->se_proto);
1216 syslog(LOG_ERR, "%s/%s: bind: %m",
1217 sep->se_service, sep->se_proto);
1224 if (sep->se_family == AF_UNIX)
1228 if (sep->se_family == AF_UNIX) {
1229 /* Ick - fch{own,mod} don't work on Unix domain sockets */
1230 if (chown(sep->se_service, sep->se_sockuid, sep->se_sockgid) < 0)
1231 syslog(LOG_ERR, "chown socket: %m");
1232 if (chmod(sep->se_service, sep->se_sockmode) < 0)
1233 syslog(LOG_ERR, "chmod socket: %m");
1238 socklen_t len = sep->se_ctrladdr_size;
1240 if (sep->se_family != AF_INET) {
1242 "%s/%s: unsupported address family for rpc",
1243 sep->se_service, sep->se_proto);
1248 if (getsockname(sep->se_fd,
1249 (struct sockaddr*)&sep->se_ctrladdr, &len) < 0){
1250 syslog(LOG_ERR, "%s/%s: getsockname: %m",
1251 sep->se_service, sep->se_proto);
1257 print_service("REG ", sep);
1258 for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++) {
1259 pmap_unset(sep->se_rpc_prog, i);
1260 pmap_set(sep->se_rpc_prog, i,
1261 (sep->se_socktype == SOCK_DGRAM)
1262 ? IPPROTO_UDP : IPPROTO_TCP,
1263 ntohs(sep->se_ctrladdr4.sin_port));
1266 if (sep->se_socktype == SOCK_STREAM)
1267 listen(sep->se_fd, 64);
1270 warnx("registered %s on %d",
1271 sep->se_server, sep->se_fd);
1276 * Finish with a service and its socket.
1279 close_sep(struct servtab *sep)
1281 if (sep->se_fd >= 0) {
1282 if (FD_ISSET(sep->se_fd, &allsock))
1288 sep->se_numchild = 0; /* forget about any existing children */
1292 matchservent(const char *name1, const char *name2, const char *proto)
1297 if (strcmp(proto, "unix") == 0) {
1298 if ((p = strrchr(name1, '/')) != NULL)
1300 if ((p = strrchr(name2, '/')) != NULL)
1303 if (strcmp(name1, name2) == 0)
1305 if ((se = getservbyname(name1, proto)) != NULL) {
1306 if (strcmp(name2, se->s_name) == 0)
1308 for (alias = se->s_aliases; *alias; alias++)
1309 if (strcmp(name2, *alias) == 0)
1316 enter(struct servtab *cp)
1318 struct servtab *sep;
1321 sep = (struct servtab *)malloc(sizeof (*sep));
1323 syslog(LOG_ERR, "malloc: %m");
1328 omask = sigblock(SIGBLOCK);
1329 sep->se_next = servtab;
1336 enable(struct servtab *sep)
1340 "enabling %s, fd %d", sep->se_service, sep->se_fd);
1342 if (sep->se_fd < 0) {
1344 "%s: %s: bad fd", __func__, sep->se_service);
1349 "%s: %s: is mux", __func__, sep->se_service);
1352 if (FD_ISSET(sep->se_fd, &allsock)) {
1354 "%s: %s: not off", __func__, sep->se_service);
1359 FD_SET(sep->se_fd, &allsock);
1360 if (sep->se_fd > maxsock)
1361 maxsock = sep->se_fd;
1365 disable(struct servtab *sep)
1369 "disabling %s, fd %d", sep->se_service, sep->se_fd);
1371 if (sep->se_fd < 0) {
1373 "%s: %s: bad fd", __func__, sep->se_service);
1378 "%s: %s: is mux", __func__, sep->se_service);
1381 if (!FD_ISSET(sep->se_fd, &allsock)) {
1383 "%s: %s: not on", __func__, sep->se_service);
1387 syslog(LOG_ERR, "%s: nsock=0", __func__);
1392 FD_CLR(sep->se_fd, &allsock);
1393 if (sep->se_fd == maxsock)
1397 FILE *fconfig = NULL;
1398 struct servtab serv;
1399 char line[LINE_MAX];
1405 if (fconfig != NULL) {
1406 fseek(fconfig, 0L, SEEK_SET);
1409 fconfig = fopen(CONFIG, "r");
1410 return (fconfig != NULL);
1425 struct servtab *sep = &serv;
1429 static char TCPMUX_TOKEN[] = "tcpmux/";
1430 #define MUX_LEN (sizeof(TCPMUX_TOKEN)-1)
1438 while ((cp = nextline(fconfig)) != NULL) {
1439 if (*cp == '#' || *cp == '\0')
1446 * clear the static buffer, since some fields (se_ctrladdr,
1447 * for example) don't get initialized here.
1449 memset(sep, 0, sizeof *sep);
1452 /* got an empty line containing just blanks/tabs. */
1455 if (arg[0] == ':') { /* :user:group:perm: */
1456 char *user, *group, *perm;
1460 if ((group = strchr(user, ':')) == NULL) {
1461 syslog(LOG_ERR, "no group after user '%s'", user);
1465 if ((perm = strchr(group, ':')) == NULL) {
1466 syslog(LOG_ERR, "no mode after group '%s'", group);
1470 if ((pw = getpwnam(user)) == NULL) {
1471 syslog(LOG_ERR, "no such user '%s'", user);
1474 sep->se_sockuid = pw->pw_uid;
1475 if ((gr = getgrnam(group)) == NULL) {
1476 syslog(LOG_ERR, "no such user '%s'", group);
1479 sep->se_sockgid = gr->gr_gid;
1480 sep->se_sockmode = strtol(perm, &arg, 8);
1482 syslog(LOG_ERR, "bad mode '%s'", perm);
1487 sep->se_sockuid = euid;
1488 sep->se_sockgid = egid;
1489 sep->se_sockmode = 0200;
1491 if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1492 char *c = arg + MUX_LEN;
1494 sep->se_type = MUXPLUS_TYPE;
1497 sep->se_type = MUX_TYPE;
1498 sep->se_service = newstr(c);
1500 sep->se_service = newstr(arg);
1501 sep->se_type = NORM_TYPE;
1504 if (strcmp(arg, "stream") == 0)
1505 sep->se_socktype = SOCK_STREAM;
1506 else if (strcmp(arg, "dgram") == 0)
1507 sep->se_socktype = SOCK_DGRAM;
1508 else if (strcmp(arg, "rdm") == 0)
1509 sep->se_socktype = SOCK_RDM;
1510 else if (strcmp(arg, "seqpacket") == 0)
1511 sep->se_socktype = SOCK_SEQPACKET;
1512 else if (strcmp(arg, "raw") == 0)
1513 sep->se_socktype = SOCK_RAW;
1515 sep->se_socktype = -1;
1518 if (strncmp(arg, "tcp", 3) == 0) {
1519 sep->se_proto = newstr(strsep(&arg, "/"));
1521 if (strcmp(arg, "ttcp") == 0)
1522 sep->se_type = TTCP_TYPE;
1525 sep->se_proto = newstr(arg);
1527 if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1528 if (no_v4bind != 0) {
1529 syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1534 memmove(sep->se_proto, sep->se_proto + 4,
1535 strlen(sep->se_proto) + 1 - 4);
1537 sep->se_rpc_prog = sep->se_rpc_lowvers =
1538 sep->se_rpc_highvers = 0;
1539 memcpy(&sep->se_ctrladdr4, bind_sa4,
1540 sizeof(sep->se_ctrladdr4));
1541 if ((versp = strrchr(sep->se_service, '/'))) {
1543 switch (sscanf(versp, "%u-%u",
1544 &sep->se_rpc_lowvers,
1545 &sep->se_rpc_highvers)) {
1549 sep->se_rpc_highvers =
1550 sep->se_rpc_lowvers;
1554 "bad RPC version specifier; %s",
1561 sep->se_rpc_lowvers =
1562 sep->se_rpc_highvers = 1;
1565 sep->se_nomapped = 0;
1566 while (isdigit(sep->se_proto[strlen(sep->se_proto) - 1])) {
1568 if (sep->se_proto[strlen(sep->se_proto) - 1] == '6') {
1569 if (no_v6bind != 0) {
1570 syslog(LOG_NOTICE, "IPv6 bind is ignored for %s",
1575 sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1580 if (sep->se_proto[strlen(sep->se_proto) - 1] == '4') {
1581 sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1585 /* illegal version num */
1586 syslog(LOG_ERR, "bad IP version for %s", sep->se_proto);
1590 if (strcmp(sep->se_proto, "unix") == 0) {
1591 sep->se_family = AF_UNIX;
1595 sep->se_family = AF_INET6;
1596 if (v4bind == 0 || no_v4bind != 0)
1597 sep->se_nomapped = 1;
1600 { /* default to v4 bind if not v6 bind */
1601 if (no_v4bind != 0) {
1602 syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1607 sep->se_family = AF_INET;
1610 switch(sep->se_family) {
1612 memcpy(&sep->se_ctrladdr4, bind_sa4,
1613 sizeof(sep->se_ctrladdr4));
1614 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr4);
1618 memcpy(&sep->se_ctrladdr6, bind_sa6,
1619 sizeof(sep->se_ctrladdr6));
1620 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr6);
1624 if (strlen(sep->se_service) >= sizeof(sep->se_ctrladdr_un.sun_path)) {
1626 "domain socket pathname too long for service %s",
1630 memset(&sep->se_ctrladdr, 0, sizeof(sep->se_ctrladdr));
1631 sep->se_ctrladdr_un.sun_family = sep->se_family;
1632 sep->se_ctrladdr_un.sun_len = strlen(sep->se_service);
1633 strcpy(sep->se_ctrladdr_un.sun_path, sep->se_service);
1634 sep->se_ctrladdr_size = SUN_LEN(&sep->se_ctrladdr_un);
1637 if (!strncmp(arg, "wait", 4))
1639 else if (!strncmp(arg, "nowait", 6))
1643 "%s: bad wait/nowait for service %s",
1644 CONFIG, sep->se_service);
1647 sep->se_maxchild = -1;
1648 sep->se_maxcpm = -1;
1649 sep->se_maxperip = -1;
1650 if ((s = strchr(arg, '/')) != NULL) {
1654 val = strtoul(s + 1, &eptr, 10);
1655 if (eptr == s + 1 || val > MAX_MAXCHLD) {
1657 "%s: bad max-child for service %s",
1658 CONFIG, sep->se_service);
1662 if (!sep->se_accept && val != 1)
1663 warnx("maxchild=%lu for wait service %s"
1664 " not recommended", val, sep->se_service);
1665 sep->se_maxchild = val;
1667 sep->se_maxcpm = strtol(eptr + 1, &eptr, 10);
1669 sep->se_maxperip = strtol(eptr + 1, &eptr, 10);
1671 * explicitly do not check for \0 for future expansion /
1672 * backwards compatibility
1677 * Silently enforce "nowait" mode for TCPMUX services
1678 * since they don't have an assigned port to listen on.
1681 if (strcmp(sep->se_proto, "tcp")) {
1683 "%s: bad protocol for tcpmux service %s",
1684 CONFIG, sep->se_service);
1687 if (sep->se_socktype != SOCK_STREAM) {
1689 "%s: bad socket type for tcpmux service %s",
1690 CONFIG, sep->se_service);
1694 sep->se_user = newstr(sskip(&cp));
1696 if ((s = strrchr(sep->se_user, '/')) != NULL) {
1698 sep->se_class = newstr(s + 1);
1700 sep->se_class = newstr(RESOURCE_RC);
1702 if ((s = strrchr(sep->se_user, ':')) != NULL) {
1704 sep->se_group = newstr(s + 1);
1706 sep->se_group = NULL;
1707 sep->se_server = newstr(sskip(&cp));
1708 if ((sep->se_server_name = strrchr(sep->se_server, '/')))
1709 sep->se_server_name++;
1710 if (strcmp(sep->se_server, "internal") == 0) {
1713 for (bi = biltins; bi->bi_service; bi++)
1714 if (bi->bi_socktype == sep->se_socktype &&
1715 matchservent(bi->bi_service, sep->se_service,
1718 if (bi->bi_service == 0) {
1719 syslog(LOG_ERR, "internal service %s unknown",
1723 sep->se_accept = 1; /* force accept mode for built-ins */
1727 if (sep->se_maxperip < 0)
1728 sep->se_maxperip = maxperip;
1729 if (sep->se_maxcpm < 0)
1730 sep->se_maxcpm = maxcpm;
1731 if (sep->se_maxchild < 0) { /* apply default max-children */
1732 if (sep->se_bi && sep->se_bi->bi_maxchild >= 0)
1733 sep->se_maxchild = sep->se_bi->bi_maxchild;
1734 else if (sep->se_accept)
1735 sep->se_maxchild = maxchild > 0 ? maxchild : 0;
1737 sep->se_maxchild = 1;
1739 if (sep->se_maxchild > 0) {
1740 sep->se_pids = malloc(sep->se_maxchild * sizeof(*sep->se_pids));
1741 if (sep->se_pids == NULL) {
1742 syslog(LOG_ERR, "malloc: %m");
1747 for (arg = skip(&cp); cp; arg = skip(&cp))
1748 if (argc < MAXARGV) {
1749 sep->se_argv[argc++] = newstr(arg);
1752 "%s: too many arguments for service %s",
1753 CONFIG, sep->se_service);
1756 while (argc <= MAXARGV)
1757 sep->se_argv[argc++] = NULL;
1758 for (i = 0; i < PERIPSIZE; ++i)
1759 LIST_INIT(&sep->se_conn[i]);
1764 freeconfig(struct servtab *cp)
1769 free(cp->se_service);
1781 free(cp->se_server);
1784 for (i = 0; i < MAXARGV; i++)
1786 free(cp->se_argv[i]);
1792 * Safe skip - if skip returns null, log a syntax error in the
1793 * configuration file and exit.
1802 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1816 while (*cp == ' ' || *cp == '\t')
1823 if (c == ' ' || c == '\t')
1824 if ((cp = nextline(fconfig)))
1829 if (*cp == '"' || *cp == '\'')
1833 while (*cp && *cp != quote)
1836 while (*cp && *cp != ' ' && *cp != '\t')
1849 if (fgets(line, sizeof (line), fd) == NULL)
1851 cp = strchr(line, '\n');
1858 newstr(const char *cp)
1862 if ((cr = strdup(cp != NULL ? cp : "")))
1864 syslog(LOG_ERR, "strdup: %m");
1869 inetd_setproctitle(const char *a, int s)
1872 struct sockaddr_storage ss;
1873 char buf[80], pbuf[INET6_ADDRSTRLEN];
1876 if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
1877 getnameinfo((struct sockaddr *)&ss, size, pbuf, sizeof(pbuf),
1878 NULL, 0, NI_NUMERICHOST|NI_WITHSCOPEID);
1879 sprintf(buf, "%s [%s]", a, pbuf);
1881 sprintf(buf, "%s", a);
1882 setproctitle("%s", buf);
1886 check_loop(const struct sockaddr *sa, const struct servtab *sep)
1888 struct servtab *se2;
1889 char pname[INET6_ADDRSTRLEN];
1891 for (se2 = servtab; se2; se2 = se2->se_next) {
1892 if (!se2->se_bi || se2->se_socktype != SOCK_DGRAM)
1895 switch (se2->se_family) {
1897 if (((const struct sockaddr_in *)sa)->sin_port ==
1898 se2->se_ctrladdr4.sin_port)
1903 if (((const struct sockaddr_in *)sa)->sin_port ==
1904 se2->se_ctrladdr4.sin_port)
1912 getnameinfo(sa, sa->sa_len, pname, sizeof(pname), NULL, 0,
1913 NI_NUMERICHOST|NI_WITHSCOPEID);
1914 syslog(LOG_WARNING, "%s/%s:%s/%s loop request REFUSED from %s",
1915 sep->se_service, sep->se_proto,
1916 se2->se_service, se2->se_proto,
1925 * Dump relevant information to stderr
1928 print_service(const char *action, const struct servtab *sep)
1931 "%s: %s proto=%s accept=%d max=%d user=%s group=%s"
1935 " builtin=%p server=%s"
1937 action, sep->se_service, sep->se_proto,
1938 sep->se_accept, sep->se_maxchild, sep->se_user, sep->se_group,
1942 (void *) sep->se_bi, sep->se_server
1946 #define CPMHSIZE 256
1947 #define CPMHMASK (CPMHSIZE-1)
1951 typedef struct CTime {
1952 unsigned long ct_Ticks;
1956 typedef struct CHash {
1958 struct in_addr c4_Addr;
1959 struct in6_addr c6_Addr;
1961 #define ch_Addr4 cu_Addr.c4_Addr
1962 #define ch_Addr6 cu_Addr.c6_Addr
1966 CTime ch_Times[CHTSIZE];
1969 CHash CHashAry[CPMHSIZE];
1972 cpmip(const struct servtab *sep, int ctrl)
1974 struct sockaddr_storage rss;
1975 socklen_t rssLen = sizeof(rss);
1979 * If getpeername() fails, just let it through (if logging is
1980 * enabled the condition is caught elsewhere)
1983 if (sep->se_maxcpm > 0 &&
1984 getpeername(ctrl, (struct sockaddr *)&rss, &rssLen) == 0 ) {
1985 time_t t = time(NULL);
1986 int hv = 0xABC3D20F;
1989 CHash *chBest = NULL;
1990 unsigned int ticks = t / CHTGRAN;
1991 struct sockaddr_in *sin4;
1993 struct sockaddr_in6 *sin6;
1996 sin4 = (struct sockaddr_in *)&rss;
1998 sin6 = (struct sockaddr_in6 *)&rss;
2004 switch (rss.ss_family) {
2006 p = (char *)&sin4->sin_addr;
2007 addrlen = sizeof(struct in_addr);
2011 p = (char *)&sin6->sin6_addr;
2012 addrlen = sizeof(struct in6_addr);
2016 /* should not happen */
2020 for (i = 0; i < addrlen; ++i, ++p) {
2021 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2023 hv = (hv ^ (hv >> 16));
2025 for (i = 0; i < 5; ++i) {
2026 CHash *ch = &CHashAry[(hv + i) & CPMHMASK];
2028 if (rss.ss_family == AF_INET &&
2029 ch->ch_Family == AF_INET &&
2030 sin4->sin_addr.s_addr == ch->ch_Addr4.s_addr &&
2031 ch->ch_Service && strcmp(sep->se_service,
2032 ch->ch_Service) == 0) {
2037 if (rss.ss_family == AF_INET6 &&
2038 ch->ch_Family == AF_INET6 &&
2039 IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2040 &ch->ch_Addr6) != 0 &&
2041 ch->ch_Service && strcmp(sep->se_service,
2042 ch->ch_Service) == 0) {
2047 if (chBest == NULL || ch->ch_LTime == 0 ||
2048 ch->ch_LTime < chBest->ch_LTime) {
2052 if ((rss.ss_family == AF_INET &&
2053 (chBest->ch_Family != AF_INET ||
2054 sin4->sin_addr.s_addr != chBest->ch_Addr4.s_addr)) ||
2055 chBest->ch_Service == NULL ||
2056 strcmp(sep->se_service, chBest->ch_Service) != 0) {
2057 chBest->ch_Family = sin4->sin_family;
2058 chBest->ch_Addr4 = sin4->sin_addr;
2059 if (chBest->ch_Service)
2060 free(chBest->ch_Service);
2061 chBest->ch_Service = strdup(sep->se_service);
2062 bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2065 if ((rss.ss_family == AF_INET6 &&
2066 (chBest->ch_Family != AF_INET6 ||
2067 IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2068 &chBest->ch_Addr6) == 0)) ||
2069 chBest->ch_Service == NULL ||
2070 strcmp(sep->se_service, chBest->ch_Service) != 0) {
2071 chBest->ch_Family = sin6->sin6_family;
2072 chBest->ch_Addr6 = sin6->sin6_addr;
2073 if (chBest->ch_Service)
2074 free(chBest->ch_Service);
2075 chBest->ch_Service = strdup(sep->se_service);
2076 bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2079 chBest->ch_LTime = t;
2081 CTime *ct = &chBest->ch_Times[ticks % CHTSIZE];
2082 if (ct->ct_Ticks != ticks) {
2083 ct->ct_Ticks = ticks;
2088 for (i = 0; i < CHTSIZE; ++i) {
2089 CTime *ct = &chBest->ch_Times[i];
2090 if (ct->ct_Ticks <= ticks &&
2091 ct->ct_Ticks >= ticks - CHTSIZE) {
2092 cnt += ct->ct_Count;
2095 if (cnt * (CHTSIZE * CHTGRAN) / 60 > sep->se_maxcpm) {
2096 char pname[INET6_ADDRSTRLEN];
2098 getnameinfo((struct sockaddr *)&rss,
2099 ((struct sockaddr *)&rss)->sa_len,
2100 pname, sizeof(pname), NULL, 0,
2101 NI_NUMERICHOST|NI_WITHSCOPEID);
2104 "%s from %s exceeded counts/min (limit %d/min)",
2105 sep->se_service, pname,
2112 static struct conninfo *
2113 search_conn(struct servtab *sep, int ctrl)
2115 struct sockaddr_storage ss;
2116 socklen_t sslen = sizeof(ss);
2117 struct conninfo *conn;
2119 char pname[NI_MAXHOST], pname2[NI_MAXHOST];
2121 if (sep->se_maxperip <= 0)
2125 * If getpeername() fails, just let it through (if logging is
2126 * enabled the condition is caught elsewhere)
2128 if (getpeername(ctrl, (struct sockaddr *)&ss, &sslen) != 0)
2131 switch (ss.ss_family) {
2133 hv = hashval((char *)&((struct sockaddr_in *)&ss)->sin_addr,
2134 sizeof(struct in_addr));
2138 hv = hashval((char *)&((struct sockaddr_in6 *)&ss)->sin6_addr,
2139 sizeof(struct in6_addr));
2144 * Since we only support AF_INET and AF_INET6, just
2145 * let other than AF_INET and AF_INET6 through.
2150 if (getnameinfo((struct sockaddr *)&ss, sslen, pname, sizeof(pname),
2151 NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID) != 0)
2154 LIST_FOREACH(conn, &sep->se_conn[hv], co_link) {
2155 if (getnameinfo((struct sockaddr *)&conn->co_addr,
2156 conn->co_addr.ss_len, pname2, sizeof(pname2), NULL, 0,
2157 NI_NUMERICHOST | NI_WITHSCOPEID) == 0 &&
2158 strcmp(pname, pname2) == 0)
2163 if ((conn = malloc(sizeof(struct conninfo))) == NULL) {
2164 syslog(LOG_ERR, "malloc: %m");
2167 conn->co_proc = malloc(sep->se_maxperip * sizeof(*conn->co_proc));
2168 if (conn->co_proc == NULL) {
2169 syslog(LOG_ERR, "malloc: %m");
2172 memcpy(&conn->co_addr, (struct sockaddr *)&ss, sslen);
2173 conn->co_numchild = 0;
2174 LIST_INSERT_HEAD(&sep->se_conn[hv], conn, co_link);
2178 * Since a child process is not invoked yet, we cannot
2179 * determine a pid of a child. So, co_proc and co_numchild
2180 * should be filled leter.
2187 room_conn(struct servtab *sep, struct conninfo *conn)
2189 char pname[NI_MAXHOST];
2191 if (conn->co_numchild >= sep->se_maxperip) {
2192 getnameinfo((struct sockaddr *)&conn->co_addr,
2193 conn->co_addr.ss_len, pname, sizeof(pname), NULL, 0,
2194 NI_NUMERICHOST | NI_WITHSCOPEID);
2195 syslog(LOG_ERR, "%s from %s exceeded counts (limit %d)",
2196 sep->se_service, pname, sep->se_maxperip);
2203 addchild_conn(struct conninfo *conn, pid_t pid)
2205 struct procinfo *proc;
2210 if ((proc = search_proc(pid, 1)) != NULL) {
2211 if (proc->pr_conn != NULL) {
2213 "addchild_conn: child already on process list");
2216 proc->pr_conn = conn;
2219 conn->co_proc[conn->co_numchild++] = proc;
2223 reapchild_conn(pid_t pid)
2225 struct procinfo *proc;
2226 struct conninfo *conn;
2229 if ((proc = search_proc(pid, 0)) == NULL)
2231 if ((conn = proc->pr_conn) == NULL)
2233 for (i = 0; i < conn->co_numchild; ++i)
2234 if (conn->co_proc[i] == proc) {
2235 conn->co_proc[i] = conn->co_proc[--conn->co_numchild];
2243 resize_conn(struct servtab *sep, int maxpip)
2245 struct conninfo *conn;
2248 if (sep->se_maxperip <= 0)
2254 for (i = 0; i < PERIPSIZE; ++i) {
2255 LIST_FOREACH(conn, &sep->se_conn[i], co_link) {
2256 for (j = maxpip; j < conn->co_numchild; ++j)
2257 free_proc(conn->co_proc[j]);
2258 conn->co_proc = realloc(conn->co_proc,
2259 maxpip * sizeof(*conn->co_proc));
2260 if (conn->co_proc == NULL) {
2261 syslog(LOG_ERR, "realloc: %m");
2264 if (conn->co_numchild > maxpip)
2265 conn->co_numchild = maxpip;
2271 free_connlist(struct servtab *sep)
2273 struct conninfo *conn;
2276 for (i = 0; i < PERIPSIZE; ++i) {
2277 while ((conn = LIST_FIRST(&sep->se_conn[i])) != NULL) {
2278 for (j = 0; j < conn->co_numchild; ++j)
2279 free_proc(conn->co_proc[j]);
2280 conn->co_numchild = 0;
2287 free_conn(struct conninfo *conn)
2291 if (conn->co_numchild <= 0) {
2292 LIST_REMOVE(conn, co_link);
2293 free(conn->co_proc);
2298 static struct procinfo *
2299 search_proc(pid_t pid, int add)
2301 struct procinfo *proc;
2304 hv = hashval((char *)&pid, sizeof(pid));
2305 LIST_FOREACH(proc, &proctable[hv], pr_link) {
2306 if (proc->pr_pid == pid)
2309 if (proc == NULL && add) {
2310 if ((proc = malloc(sizeof(struct procinfo))) == NULL) {
2311 syslog(LOG_ERR, "malloc: %m");
2315 proc->pr_conn = NULL;
2316 LIST_INSERT_HEAD(&proctable[hv], proc, pr_link);
2322 free_proc(struct procinfo *proc)
2326 LIST_REMOVE(proc, pr_link);
2331 hashval(char *p, int len)
2333 int i, hv = 0xABC3D20F;
2335 for (i = 0; i < len; ++i, ++p)
2336 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2337 hv = (hv ^ (hv >> 16)) & (PERIPSIZE - 1);