Remove faith(4) and faithd(8) from the tree.
[dragonfly.git] / usr.sbin / inetd / inetd.c
1 /*
2  * Copyright (c) 1983, 1991, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
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. 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.
16  *
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
27  * SUCH DAMAGE.
28  *
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 $
32  */
33
34 /*
35  * Inetd - Internet super-server
36  *
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.
41  *
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''.
50  *
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.
56  *
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)
66  *
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
80  * for new requests.
81  *
82  * For RPC services
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
90  *
91  * Comment lines are indicated by a `#' in column 1.
92  *
93  * #ifdef IPSEC
94  * Comment lines that start with "#@" denote IPsec policy string, as described
95  * in ipsec_set_policy(3).  This will affect all the following items in
96  * inetd.conf(8).  To reset the policy, just use "#@" line.  By default,
97  * there's no IPsec policy.
98  * #endif
99  */
100 #include <sys/param.h>
101 #include <sys/ioctl.h>
102 #include <sys/wait.h>
103 #include <sys/time.h>
104 #include <sys/resource.h>
105 #include <sys/stat.h>
106 #include <sys/un.h>
107
108 #include <netinet/in.h>
109 #include <netinet/tcp.h>
110 #include <arpa/inet.h>
111 #include <rpc/rpc.h>
112 #include <rpc/pmap_clnt.h>
113
114 #include <errno.h>
115 #include <err.h>
116 #include <fcntl.h>
117 #include <grp.h>
118 #include <limits.h>
119 #include <netdb.h>
120 #include <pwd.h>
121 #include <signal.h>
122 #include <stdio.h>
123 #include <stdlib.h>
124 #include <string.h>
125 #include <syslog.h>
126 #include <tcpd.h>
127 #include <unistd.h>
128 #include <libutil.h>
129 #include <sysexits.h>
130 #include <ctype.h>
131
132 #include "inetd.h"
133 #include "pathnames.h"
134
135 #ifdef IPSEC
136 #include <netinet6/ipsec.h>
137 #ifndef IPSEC_POLICY_IPSEC      /* no ipsec support on old ipsec */
138 #undef IPSEC
139 #endif
140 #endif
141
142 /* wrapper for KAME-special getnameinfo() */
143 #ifndef NI_WITHSCOPEID
144 #define NI_WITHSCOPEID  0
145 #endif
146
147 #ifndef LIBWRAP_ALLOW_FACILITY
148 # define LIBWRAP_ALLOW_FACILITY LOG_AUTH
149 #endif
150 #ifndef LIBWRAP_ALLOW_SEVERITY
151 # define LIBWRAP_ALLOW_SEVERITY LOG_INFO
152 #endif
153 #ifndef LIBWRAP_DENY_FACILITY
154 # define LIBWRAP_DENY_FACILITY LOG_AUTH
155 #endif
156 #ifndef LIBWRAP_DENY_SEVERITY
157 # define LIBWRAP_DENY_SEVERITY LOG_WARNING
158 #endif
159
160 #define ISWRAP(sep)     \
161            ( ((wrap_ex && !(sep)->se_bi) || (wrap_bi && (sep)->se_bi)) \
162         && (sep->se_family == AF_INET || sep->se_family == AF_INET6) \
163         && ( ((sep)->se_accept && (sep)->se_socktype == SOCK_STREAM) \
164             || (sep)->se_socktype == SOCK_DGRAM))
165
166 #ifdef LOGIN_CAP
167 #include <login_cap.h>
168
169 /* see init.c */
170 #define RESOURCE_RC "daemon"
171
172 #endif
173
174 #ifndef MAXCHILD
175 #define MAXCHILD        -1              /* maximum number of this service
176                                            < 0 = no limit */
177 #endif
178
179 #ifndef MAXCPM
180 #define MAXCPM          -1              /* rate limit invocations from a
181                                            single remote address,
182                                            < 0 = no limit */
183 #endif
184
185 #ifndef MAXPERIP
186 #define MAXPERIP        -1              /* maximum number of this service
187                                            from a single remote address,
188                                            < 0 = no limit */
189 #endif
190
191 #ifndef TOOMANY
192 #define TOOMANY         256             /* don't start more than TOOMANY */
193 #endif
194 #define CNT_INTVL       60              /* servers in CNT_INTVL sec. */
195 #define RETRYTIME       (60*10)         /* retry after bind or server fail */
196 #define MAX_MAXCHLD     32767           /* max allowable max children */
197
198 #define SIGBLOCK        (sigmask(SIGCHLD)|sigmask(SIGHUP)|sigmask(SIGALRM))
199
200 void            close_sep(struct servtab *);
201 void            flag_signal(int);
202 void            flag_config(int);
203 void            config(void);
204 int             cpmip(const struct servtab *, int);
205 void            endconfig(void);
206 struct servtab *enter(struct servtab *);
207 void            freeconfig(struct servtab *);
208 struct servtab *getconfigent(void);
209 int             matchservent(const char *, const char *, const char *);
210 char           *nextline(FILE *);
211 void            addchild(struct servtab *, int);
212 void            flag_reapchild(int);
213 void            reapchild(void);
214 void            enable(struct servtab *);
215 void            disable(struct servtab *);
216 void            flag_retry(int);
217 void            retry(void);
218 int             setconfig(void);
219 void            setup(struct servtab *);
220 #ifdef IPSEC
221 void            ipsecsetup(struct servtab *);
222 #endif
223 void            unregisterrpc(struct servtab *sep);
224 static struct conninfo *search_conn(struct servtab *sep, int ctrl);
225 static int      room_conn(struct servtab *sep, struct conninfo *conn);
226 static void     addchild_conn(struct conninfo *conn, pid_t pid);
227 static void     reapchild_conn(pid_t pid);
228 static void     free_conn(struct conninfo *conn);
229 static void     resize_conn(struct servtab *sep, int maxperip);
230 static void     free_connlist(struct servtab *sep);
231 static void     free_proc(struct procinfo *);
232 static struct procinfo *search_proc(pid_t pid, int add);
233 static int      hashval(char *p, int len);
234
235 int     allow_severity;
236 int     deny_severity;
237 int     wrap_ex = 0;
238 int     wrap_bi = 0;
239 int     debug = 0;
240 int     dolog = 0;
241 int     maxsock;                        /* highest-numbered descriptor */
242 fd_set  allsock;
243 int     options;
244 int     timingout;
245 int     toomany = TOOMANY;
246 int     maxchild = MAXCHILD;
247 int     maxcpm = MAXCPM;
248 int     maxperip = MAXPERIP;
249 struct  servent *sp;
250 struct  rpcent *rpc;
251 char    *hostname = NULL;
252 struct  sockaddr_in *bind_sa4;
253 int     no_v4bind = 1;
254 #ifdef INET6
255 struct  sockaddr_in6 *bind_sa6;
256 int     no_v6bind = 1;
257 #endif
258 int     signalpipe[2];
259 #ifdef SANITY_CHECK
260 int     nsock;
261 #endif
262 uid_t   euid;
263 gid_t   egid;
264 mode_t  mask;
265
266 struct  servtab *servtab;
267
268 extern struct biltin biltins[];
269
270 #define NUMINT  (sizeof(intab) / sizeof(struct inent))
271 const char      *CONFIG = _PATH_INETDCONF;
272 const char      *pid_file = _PATH_INETDPID;
273
274 static LIST_HEAD(, procinfo) proctable[PERIPSIZE];
275
276 int
277 getvalue(const char *arg, int *value, const char *whine)
278 {
279         int  tmp;
280         char *p;
281
282         tmp = strtol(arg, &p, 0);
283         if (tmp < 0 || *p) {
284                 syslog(LOG_ERR, whine, arg);
285                 return 1;                       /* failure */
286         }
287         *value = tmp;
288         return 0;                               /* success */
289 }
290
291 static sa_family_t
292 whichaf(struct request_info *req)
293 {
294         struct sockaddr *sa;
295
296         sa = (struct sockaddr *)req->client->sin;
297         if (sa == NULL)
298                 return AF_UNSPEC;
299         if (sa->sa_family == AF_INET6 &&
300             IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)sa)->sin6_addr))
301                 return AF_INET;
302         return sa->sa_family;
303 }
304
305 int
306 main(int argc, char **argv)
307 {
308         struct servtab *sep;
309         struct passwd *pwd;
310         struct group *grp;
311         struct sigaction sa, saalrm, sachld, sahup, sapipe;
312         int ch, dofork;
313         pid_t pid;
314         char buf[50];
315 #ifdef LOGIN_CAP
316         login_cap_t *lc = NULL;
317 #endif
318         struct request_info req;
319         int denied;
320         char *service = NULL;
321         union {
322                 struct sockaddr peer_un;
323                 struct sockaddr_in peer_un4;
324                 struct sockaddr_in6 peer_un6;
325                 struct sockaddr_storage peer_max;
326         } p_un;
327 #define peer    p_un.peer_un
328 #define peer4   p_un.peer_un4
329 #define peer6   p_un.peer_un6
330 #define peermax p_un.peer_max
331         int i;
332         struct addrinfo hints, *res;
333         const char *servname;
334         int error;
335         struct conninfo *conn;
336
337         openlog("inetd", LOG_PID | LOG_NOWAIT | LOG_PERROR, LOG_DAEMON);
338
339         while ((ch = getopt(argc, argv, "dlwWR:a:c:C:p:s:")) != -1)
340                 switch(ch) {
341                 case 'd':
342                         debug = 1;
343                         options |= SO_DEBUG;
344                         break;
345                 case 'l':
346                         dolog = 1;
347                         break;
348                 case 'R':
349                         getvalue(optarg, &toomany,
350                                 "-R %s: bad value for service invocation rate");
351                         break;
352                 case 'c':
353                         getvalue(optarg, &maxchild,
354                                 "-c %s: bad value for maximum children");
355                         break;
356                 case 'C':
357                         getvalue(optarg, &maxcpm,
358                                 "-C %s: bad value for maximum children/minute");
359                         break;
360                 case 'a':
361                         hostname = optarg;
362                         break;
363                 case 'p':
364                         pid_file = optarg;
365                         break;
366                 case 's':
367                         getvalue(optarg, &maxperip,
368                                 "-s %s: bad value for maximum children per source address");
369                         break;
370                 case 'w':
371                         wrap_ex++;
372                         break;
373                 case 'W':
374                         wrap_bi++;
375                         break;
376                 case '?':
377                 default:
378                         syslog(LOG_ERR,
379                                 "usage: inetd [-dlwW] [-a address] [-R rate]"
380                                 " [-c maximum] [-C rate]"
381                                 " [-p pidfile] [conf-file]");
382                         exit(EX_USAGE);
383                 }
384         /*
385          * Initialize Bind Addrs.
386          *   When hostname is NULL, wild card bind addrs are obtained from
387          *   getaddrinfo(). But getaddrinfo() requires at least one of
388          *   hostname or servname is non NULL.
389          *   So when hostname is NULL, set dummy value to servname.
390          */
391         servname = (hostname == NULL) ? "discard" /* dummy */ : NULL;
392
393         bzero(&hints, sizeof(struct addrinfo));
394         hints.ai_flags = AI_PASSIVE;
395         hints.ai_family = AF_UNSPEC;
396         error = getaddrinfo(hostname, servname, &hints, &res);
397         if (error != 0) {
398                 syslog(LOG_ERR, "-a %s: %s", hostname, gai_strerror(error));
399                 if (error == EAI_SYSTEM)
400                         syslog(LOG_ERR, "%s", strerror(errno));
401                 exit(EX_USAGE);
402         }
403         do {
404                 if (res->ai_addr == NULL) {
405                         syslog(LOG_ERR, "-a %s: getaddrinfo failed", hostname);
406                         exit(EX_USAGE);
407                 }
408                 switch (res->ai_addr->sa_family) {
409                 case AF_INET:
410                         if (no_v4bind == 0)
411                                 continue;
412                         bind_sa4 = (struct sockaddr_in *)res->ai_addr;
413                         /* init port num in case servname is dummy */
414                         bind_sa4->sin_port = 0;
415                         no_v4bind = 0;
416                         continue;
417 #ifdef INET6
418                 case AF_INET6:
419                         if (no_v6bind == 0)
420                                 continue;
421                         bind_sa6 = (struct sockaddr_in6 *)res->ai_addr;
422                         /* init port num in case servname is dummy */
423                         bind_sa6->sin6_port = 0;
424                         no_v6bind = 0;
425                         continue;
426 #endif
427                 }
428                 if (no_v4bind == 0
429 #ifdef INET6
430                     && no_v6bind == 0
431 #endif
432                     )
433                         break;
434         } while ((res = res->ai_next) != NULL);
435         if (no_v4bind != 0
436 #ifdef INET6
437             && no_v6bind != 0
438 #endif
439             ) {
440                 syslog(LOG_ERR, "-a %s: unknown address family", hostname);
441                 exit(EX_USAGE);
442         }
443
444         euid = geteuid();
445         egid = getegid();
446         umask(mask = umask(0777));
447
448         argc -= optind;
449         argv += optind;
450
451         if (argc > 0)
452                 CONFIG = argv[0];
453         if (debug == 0) {
454                 FILE *fp;
455                 if (daemon(0, 0) < 0) {
456                         syslog(LOG_WARNING, "daemon(0,0) failed: %m");
457                 }
458                 /* From now on we don't want syslog messages going to stderr. */
459                 closelog();
460                 openlog("inetd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
461                 /*
462                  * In case somebody has started inetd manually, we need to
463                  * clear the logname, so that old servers run as root do not
464                  * get the user's logname..
465                  */
466                 if (setlogin("") < 0) {
467                         syslog(LOG_WARNING, "cannot clear logname: %m");
468                         /* no big deal if it fails.. */
469                 }
470                 pid = getpid();
471                 fp = fopen(pid_file, "w");
472                 if (fp) {
473                         fprintf(fp, "%ld\n", (long)pid);
474                         fclose(fp);
475                 } else {
476                         syslog(LOG_WARNING, "%s: %m", pid_file);
477                 }
478         }
479         for (i = 0; i < PERIPSIZE; ++i)
480                 LIST_INIT(&proctable[i]);
481         sa.sa_flags = 0;
482         sigemptyset(&sa.sa_mask);
483         sigaddset(&sa.sa_mask, SIGALRM);
484         sigaddset(&sa.sa_mask, SIGCHLD);
485         sigaddset(&sa.sa_mask, SIGHUP);
486         sa.sa_handler = flag_retry;
487         sigaction(SIGALRM, &sa, &saalrm);
488         config();
489         sa.sa_handler = flag_config;
490         sigaction(SIGHUP, &sa, &sahup);
491         sa.sa_handler = flag_reapchild;
492         sigaction(SIGCHLD, &sa, &sachld);
493         sa.sa_handler = SIG_IGN;
494         sigaction(SIGPIPE, &sa, &sapipe);
495
496         {
497                 /* space for daemons to overwrite environment for ps */
498 #define DUMMYSIZE       100
499                 char dummy[DUMMYSIZE];
500
501                 memset(dummy, 'x', DUMMYSIZE - 1);
502                 dummy[DUMMYSIZE - 1] = '\0';
503                 if (setenv("inetd_dummy", dummy, 1) == -1)
504                         syslog(LOG_WARNING, "setenv: cannot set inetd_dummy=%s: %m", dummy);
505                 
506         }
507
508         if (pipe(signalpipe) != 0) {
509                 syslog(LOG_ERR, "pipe: %m");
510                 exit(EX_OSERR);
511         }
512         if (fcntl(signalpipe[0], F_SETFD, FD_CLOEXEC) < 0 ||
513             fcntl(signalpipe[1], F_SETFD, FD_CLOEXEC) < 0) {
514                 syslog(LOG_ERR, "signalpipe: fcntl (F_SETFD, FD_CLOEXEC): %m");
515                 exit(EX_OSERR);
516         }
517         FD_SET(signalpipe[0], &allsock);
518 #ifdef SANITY_CHECK
519         nsock++;
520 #endif
521         if (signalpipe[0] > maxsock)
522             maxsock = signalpipe[0];
523         if (signalpipe[1] > maxsock)
524             maxsock = signalpipe[1];
525
526         for (;;) {
527             int n, ctrl;
528             fd_set readable;
529
530 #ifdef SANITY_CHECK
531             if (nsock == 0) {
532                 syslog(LOG_ERR, "%s: nsock=0", __func__);
533                 exit(EX_SOFTWARE);
534             }
535 #endif
536             readable = allsock;
537             if ((n = select(maxsock + 1, &readable, NULL, NULL, NULL)) <= 0) {
538                     if (n < 0 && errno != EINTR) {
539                         syslog(LOG_WARNING, "select: %m");
540                         sleep(1);
541                     }
542                     continue;
543             }
544             /* handle any queued signal flags */
545             if (FD_ISSET(signalpipe[0], &readable)) {
546                 int nsig;
547                 if (ioctl(signalpipe[0], FIONREAD, &nsig) != 0) {
548                     syslog(LOG_ERR, "ioctl: %m");
549                     exit(EX_OSERR);
550                 }
551                 while (--nsig >= 0) {
552                     char c;
553                     if (read(signalpipe[0], &c, 1) != 1) {
554                         syslog(LOG_ERR, "read: %m");
555                         exit(EX_OSERR);
556                     }
557                     if (debug)
558                         warnx("handling signal flag %c", c);
559                     switch(c) {
560                     case 'A': /* sigalrm */
561                         retry();
562                         break;
563                     case 'C': /* sigchld */
564                         reapchild();
565                         break;
566                     case 'H': /* sighup */
567                         config();
568                         break;
569                     }
570                 }
571             }
572             for (sep = servtab; n && sep; sep = sep->se_next)
573                 if (sep->se_fd != -1 && FD_ISSET(sep->se_fd, &readable)) {
574                     n--;
575                     if (debug)
576                             warnx("someone wants %s", sep->se_service);
577                     dofork = !sep->se_bi || sep->se_bi->bi_fork || ISWRAP(sep);
578                     conn = NULL;
579                     if (sep->se_accept && sep->se_socktype == SOCK_STREAM) {
580                             i = 1;
581                             if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
582                                     syslog(LOG_ERR, "ioctl (FIONBIO, 1): %m");
583                             ctrl = accept(sep->se_fd, NULL, NULL);
584                             if (debug)
585                                     warnx("accept, ctrl %d", ctrl);
586                             if (ctrl < 0) {
587                                     if (errno != EINTR)
588                                             syslog(LOG_WARNING,
589                                                 "accept (for %s): %m",
590                                                 sep->se_service);
591                                       if (sep->se_accept &&
592                                           sep->se_socktype == SOCK_STREAM)
593                                               close(ctrl);
594                                     continue;
595                             }
596                             i = 0;
597                             if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
598                                     syslog(LOG_ERR, "ioctl1(FIONBIO, 0): %m");
599                             if (ioctl(ctrl, FIONBIO, &i) < 0)
600                                     syslog(LOG_ERR, "ioctl2(FIONBIO, 0): %m");
601                             if (cpmip(sep, ctrl) < 0) {
602                                 close(ctrl);
603                                 continue;
604                             }
605                             if (dofork &&
606                                 (conn = search_conn(sep, ctrl)) != NULL &&
607                                 !room_conn(sep, conn)) {
608                                 close(ctrl);
609                                 continue;
610                             }
611                     } else
612                             ctrl = sep->se_fd;
613                     if (dolog && !ISWRAP(sep)) {
614                             char pname[INET6_ADDRSTRLEN] = "unknown";
615                             socklen_t sl;
616                             sl = sizeof peermax;
617                             if (getpeername(ctrl, (struct sockaddr *)
618                                             &peermax, &sl)) {
619                                     sl = sizeof peermax;
620                                     if (recvfrom(ctrl, buf, sizeof(buf),
621                                         MSG_PEEK,
622                                         (struct sockaddr *)&peermax,
623                                         &sl) >= 0) {
624                                       getnameinfo((struct sockaddr *)&peermax,
625                                                   peer.sa_len,
626                                                   pname, sizeof(pname),
627                                                   NULL, 0, 
628                                                   NI_NUMERICHOST|
629                                                   NI_WITHSCOPEID);
630                                     }
631                             } else {
632                                     getnameinfo((struct sockaddr *)&peermax,
633                                                 peer.sa_len,
634                                                 pname, sizeof(pname),
635                                                 NULL, 0, 
636                                                 NI_NUMERICHOST|
637                                                 NI_WITHSCOPEID);
638                             }
639                             syslog(LOG_INFO,"%s from %s", sep->se_service, pname);
640                     }
641                     sigblock(SIGBLOCK);
642                     pid = 0;
643                     /*
644                      * Fork for all external services, builtins which need to
645                      * fork and anything we're wrapping (as wrapping might
646                      * block or use hosts_options(5) twist).
647                      */
648                     if (dofork) {
649                             if (sep->se_count++ == 0)
650                                 gettimeofday(&sep->se_time, NULL);
651                             else if (toomany > 0 && sep->se_count >= toomany) {
652                                 struct timeval now;
653
654                                 gettimeofday(&now, NULL);
655                                 if (now.tv_sec - sep->se_time.tv_sec >
656                                     CNT_INTVL) {
657                                         sep->se_time = now;
658                                         sep->se_count = 1;
659                                 } else {
660                                         syslog(LOG_ERR,
661                         "%s/%s server failing (looping), service terminated",
662                                             sep->se_service, sep->se_proto);
663                                         if (sep->se_accept &&
664                                             sep->se_socktype == SOCK_STREAM)
665                                                 close(ctrl);
666                                         close_sep(sep);
667                                         free_conn(conn);
668                                         sigsetmask(0L);
669                                         if (!timingout) {
670                                                 timingout = 1;
671                                                 alarm(RETRYTIME);
672                                         }
673                                         continue;
674                                 }
675                             }
676                             pid = fork();
677                     }
678                     if (pid < 0) {
679                             syslog(LOG_ERR, "fork: %m");
680                             if (sep->se_accept &&
681                                 sep->se_socktype == SOCK_STREAM)
682                                     close(ctrl);
683                             free_conn(conn);
684                             sigsetmask(0L);
685                             sleep(1);
686                             continue;
687                     }
688                     if (pid) {
689                         addchild_conn(conn, pid);
690                         addchild(sep, pid);
691                     }
692                     sigsetmask(0L);
693                     if (pid == 0) {
694                             if (dofork) {
695                                 sigaction(SIGALRM, &saalrm, NULL);
696                                 sigaction(SIGCHLD, &sachld, NULL);
697                                 sigaction(SIGHUP, &sahup, NULL);
698                                 /* SIGPIPE reset before exec */
699                             }
700                             /*
701                              * Call tcpmux to find the real service to exec.
702                              */
703                             if (sep->se_bi &&
704                                 sep->se_bi->bi_fn == (bi_fn_t *) tcpmux) {
705                                     sep = tcpmux(ctrl);
706                                     if (sep == NULL) {
707                                             close(ctrl);
708                                             _exit(0);
709                                     }
710                             }
711                             if (ISWRAP(sep)) {
712                                 inetd_setproctitle("wrapping", ctrl);
713                                 service = sep->se_server_name ?
714                                     sep->se_server_name : sep->se_service;
715                                 request_init(&req, RQ_DAEMON, service, RQ_FILE, ctrl, NULL);
716                                 fromhost(&req);
717                                 deny_severity = LIBWRAP_DENY_FACILITY|LIBWRAP_DENY_SEVERITY;
718                                 allow_severity = LIBWRAP_ALLOW_FACILITY|LIBWRAP_ALLOW_SEVERITY;
719                                 denied = !hosts_access(&req);
720                                 if (denied) {
721                                     syslog(deny_severity,
722                                         "refused connection from %.500s, service %s (%s%s)",
723                                         eval_client(&req), service, sep->se_proto,
724                                         (whichaf(&req) == AF_INET6) ? "6" : "");
725                                     if (sep->se_socktype != SOCK_STREAM)
726                                         recv(ctrl, buf, sizeof (buf), 0);
727                                     if (dofork) {
728                                         sleep(1);
729                                         _exit(0);
730                                     }
731                                 }
732                                 if (dolog) {
733                                     syslog(allow_severity,
734                                         "connection from %.500s, service %s (%s%s)",
735                                         eval_client(&req), service, sep->se_proto,
736                                         (whichaf(&req) == AF_INET6) ? "6" : "");
737                                 }
738                             }
739                             if (sep->se_bi) {
740                                 (*sep->se_bi->bi_fn)(ctrl, sep);
741                             } else {
742                                 if (debug)
743                                         warnx("%d execl %s",
744                                                 getpid(), sep->se_server);
745                                 /* Clear close-on-exec. */
746                                 if (fcntl(ctrl, F_SETFD, 0) < 0) {
747                                         syslog(LOG_ERR,
748                                             "%s/%s: fcntl (F_SETFD, 0): %m",
749                                                 sep->se_service, sep->se_proto);
750                                         _exit(EX_OSERR);
751                                 }
752                                 if (ctrl != 0) {
753                                         dup2(ctrl, 0);
754                                         close(ctrl);
755                                 }
756                                 dup2(0, 1);
757                                 dup2(0, 2);
758                                 if ((pwd = getpwnam(sep->se_user)) == NULL) {
759                                         syslog(LOG_ERR,
760                                             "%s/%s: %s: no such user",
761                                                 sep->se_service, sep->se_proto,
762                                                 sep->se_user);
763                                         if (sep->se_socktype != SOCK_STREAM)
764                                                 recv(0, buf, sizeof (buf), 0);
765                                         _exit(EX_NOUSER);
766                                 }
767                                 grp = NULL;
768                                 if (   sep->se_group != NULL
769                                     && (grp = getgrnam(sep->se_group)) == NULL
770                                    ) {
771                                         syslog(LOG_ERR,
772                                             "%s/%s: %s: no such group",
773                                                 sep->se_service, sep->se_proto,
774                                                 sep->se_group);
775                                         if (sep->se_socktype != SOCK_STREAM)
776                                                 recv(0, buf, sizeof (buf), 0);
777                                         _exit(EX_NOUSER);
778                                 }
779                                 if (grp != NULL)
780                                         pwd->pw_gid = grp->gr_gid;
781 #ifdef LOGIN_CAP
782                                 if ((lc = login_getclass(sep->se_class)) == NULL) {
783                                         /* error syslogged by getclass */
784                                         syslog(LOG_ERR,
785                                             "%s/%s: %s: login class error",
786                                                 sep->se_service, sep->se_proto,
787                                                 sep->se_class);
788                                         if (sep->se_socktype != SOCK_STREAM)
789                                                 recv(0, buf, sizeof (buf), 0);
790                                         _exit(EX_NOUSER);
791                                 }
792 #endif
793                                 if (setsid() < 0) {
794                                         syslog(LOG_ERR,
795                                                 "%s: can't setsid(): %m",
796                                                  sep->se_service);
797                                         /* _exit(EX_OSERR); not fatal yet */
798                                 }
799 #ifdef LOGIN_CAP
800                                 if (setusercontext(lc, pwd, pwd->pw_uid,
801                                     LOGIN_SETALL) != 0) {
802                                         syslog(LOG_ERR,
803                                          "%s: can't setusercontext(..%s..): %m",
804                                          sep->se_service, sep->se_user);
805                                         _exit(EX_OSERR);
806                                 }
807                                 login_close(lc);
808 #else
809                                 if (pwd->pw_uid) {
810                                         if (setlogin(sep->se_user) < 0) {
811                                                 syslog(LOG_ERR,
812                                                  "%s: can't setlogin(%s): %m",
813                                                  sep->se_service, sep->se_user);
814                                                 /* _exit(EX_OSERR); not yet */
815                                         }
816                                         if (setgid(pwd->pw_gid) < 0) {
817                                                 syslog(LOG_ERR,
818                                                   "%s: can't set gid %d: %m",
819                                                   sep->se_service, pwd->pw_gid);
820                                                 _exit(EX_OSERR);
821                                         }
822                                         initgroups(pwd->pw_name,
823                                                         pwd->pw_gid);
824                                         if (setuid(pwd->pw_uid) < 0) {
825                                                 syslog(LOG_ERR,
826                                                   "%s: can't set uid %d: %m",
827                                                   sep->se_service, pwd->pw_uid);
828                                                 _exit(EX_OSERR);
829                                         }
830                                 }
831 #endif
832                                 sigaction(SIGPIPE, &sapipe, NULL);
833                                 execv(sep->se_server, sep->se_argv);
834                                 syslog(LOG_ERR,
835                                     "cannot execute %s: %m", sep->se_server);
836                                 if (sep->se_socktype != SOCK_STREAM)
837                                         recv(0, buf, sizeof (buf), 0);
838                             }
839                             if (dofork)
840                                 _exit(0);
841                     }
842                     if (sep->se_accept && sep->se_socktype == SOCK_STREAM)
843                             close(ctrl);
844                 }
845         }
846 }
847
848 /*
849  * Add a signal flag to the signal flag queue for later handling
850  */
851
852 void
853 flag_signal(int c)
854 {
855         char ch = c;
856
857         if (write(signalpipe[1], &ch, 1) != 1) {
858                 syslog(LOG_ERR, "write: %m");
859                 _exit(EX_OSERR);
860         }
861 }
862
863 /*
864  * Record a new child pid for this service. If we've reached the
865  * limit on children, then stop accepting incoming requests.
866  */
867
868 void
869 addchild(struct servtab *sep, pid_t pid)
870 {
871         if (sep->se_maxchild <= 0)
872                 return;
873 #ifdef SANITY_CHECK
874         if (sep->se_numchild >= sep->se_maxchild) {
875                 syslog(LOG_ERR, "%s: %d >= %d",
876                     __func__, sep->se_numchild, sep->se_maxchild);
877                 exit(EX_SOFTWARE);
878         }
879 #endif
880         sep->se_pids[sep->se_numchild++] = pid;
881         if (sep->se_numchild == sep->se_maxchild)
882                 disable(sep);
883 }
884
885 /*
886  * Some child process has exited. See if it's on somebody's list.
887  */
888
889 void
890 flag_reapchild(int signo __unused)
891 {
892         flag_signal('C');
893 }
894
895 void
896 reapchild(void)
897 {
898         int k, status;
899         pid_t pid;
900         struct servtab *sep;
901
902         for (;;) {
903                 pid = wait3(&status, WNOHANG, NULL);
904                 if (pid <= 0)
905                         break;
906                 if (debug)
907                         warnx("%d reaped, %s %u", pid,
908                             WIFEXITED(status) ? "status" : "signal",
909                             WIFEXITED(status) ? WEXITSTATUS(status)
910                                 : WTERMSIG(status));
911                 for (sep = servtab; sep; sep = sep->se_next) {
912                         for (k = 0; k < sep->se_numchild; k++)
913                                 if (sep->se_pids[k] == pid)
914                                         break;
915                         if (k == sep->se_numchild)
916                                 continue;
917                         if (sep->se_numchild == sep->se_maxchild)
918                                 enable(sep);
919                         sep->se_pids[k] = sep->se_pids[--sep->se_numchild];
920                         if (WIFSIGNALED(status) || WEXITSTATUS(status))
921                                 syslog(LOG_WARNING,
922                                     "%s[%d]: exited, %s %u",
923                                     sep->se_server, pid,
924                                     WIFEXITED(status) ? "status" : "signal",
925                                     WIFEXITED(status) ? WEXITSTATUS(status)
926                                         : WTERMSIG(status));
927                         break;
928                 }
929                 reapchild_conn(pid);
930         }
931 }
932
933 void
934 flag_config(int signo __unused)
935 {
936         flag_signal('H');
937 }
938
939 void
940 config(void)
941 {
942         struct servtab *sep, *new, **sepp;
943         long omask;
944 #ifdef LOGIN_CAP
945         login_cap_t *lc = NULL;
946 #endif
947
948
949         if (!setconfig()) {
950                 syslog(LOG_ERR, "%s: %m", CONFIG);
951                 return;
952         }
953         for (sep = servtab; sep; sep = sep->se_next)
954                 sep->se_checked = 0;
955         while ((new = getconfigent())) {
956                 if (getpwnam(new->se_user) == NULL) {
957                         syslog(LOG_ERR,
958                                 "%s/%s: no such user '%s', service ignored",
959                                 new->se_service, new->se_proto, new->se_user);
960                         continue;
961                 }
962                 if (new->se_group && getgrnam(new->se_group) == NULL) {
963                         syslog(LOG_ERR,
964                                 "%s/%s: no such group '%s', service ignored",
965                                 new->se_service, new->se_proto, new->se_group);
966                         continue;
967                 }
968 #ifdef LOGIN_CAP
969                 if ((lc = login_getclass(new->se_class)) == NULL) {
970                         /* error syslogged by getclass */
971                         syslog(LOG_ERR,
972                                 "%s/%s: %s: login class error, service ignored",
973                                 new->se_service, new->se_proto, new->se_class);
974                         continue;
975                 }
976                 login_close(lc);
977 #endif
978                 for (sep = servtab; sep; sep = sep->se_next)
979                         if (strcmp(sep->se_service, new->se_service) == 0 &&
980                             strcmp(sep->se_proto, new->se_proto) == 0 &&
981                             sep->se_socktype == new->se_socktype &&
982                             sep->se_family == new->se_family)
983                                 break;
984                 if (sep != NULL) {
985                         int i;
986
987 #define SWAP(a, b) { typeof(a) c = a; a = b; b = c; }
988                         omask = sigblock(SIGBLOCK);
989                         if (sep->se_nomapped != new->se_nomapped) {
990                                 sep->se_nomapped = new->se_nomapped;
991                                 sep->se_reset = 1;
992                         }
993                         /* copy over outstanding child pids */
994                         if (sep->se_maxchild > 0 && new->se_maxchild > 0) {
995                                 new->se_numchild = sep->se_numchild;
996                                 if (new->se_numchild > new->se_maxchild)
997                                         new->se_numchild = new->se_maxchild;
998                                 memcpy(new->se_pids, sep->se_pids,
999                                     new->se_numchild * sizeof(*new->se_pids));
1000                         }
1001                         SWAP(sep->se_pids, new->se_pids);
1002                         sep->se_maxchild = new->se_maxchild;
1003                         sep->se_numchild = new->se_numchild;
1004                         sep->se_maxcpm = new->se_maxcpm;
1005                         resize_conn(sep, new->se_maxperip);
1006                         sep->se_maxperip = new->se_maxperip;
1007                         sep->se_bi = new->se_bi;
1008                         /* might need to turn on or off service now */
1009                         if (sep->se_fd >= 0) {
1010                               if (sep->se_maxchild > 0
1011                                   && sep->se_numchild == sep->se_maxchild) {
1012                                       if (FD_ISSET(sep->se_fd, &allsock))
1013                                           disable(sep);
1014                               } else {
1015                                       if (!FD_ISSET(sep->se_fd, &allsock))
1016                                           enable(sep);
1017                               }
1018                         }
1019                         sep->se_accept = new->se_accept;
1020                         SWAP(sep->se_user, new->se_user);
1021                         SWAP(sep->se_group, new->se_group);
1022 #ifdef LOGIN_CAP
1023                         SWAP(sep->se_class, new->se_class);
1024 #endif
1025                         SWAP(sep->se_server, new->se_server);
1026                         SWAP(sep->se_server_name, new->se_server_name);
1027                         for (i = 0; i < MAXARGV; i++)
1028                                 SWAP(sep->se_argv[i], new->se_argv[i]);
1029 #ifdef IPSEC
1030                         SWAP(sep->se_policy, new->se_policy);
1031                         ipsecsetup(sep);
1032 #endif
1033                         sigsetmask(omask);
1034                         freeconfig(new);
1035                         if (debug)
1036                                 print_service("REDO", sep);
1037                 } else {
1038                         sep = enter(new);
1039                         if (debug)
1040                                 print_service("ADD ", sep);
1041                 }
1042                 sep->se_checked = 1;
1043                 if (ISMUX(sep)) {
1044                         sep->se_fd = -1;
1045                         continue;
1046                 }
1047                 switch (sep->se_family) {
1048                 case AF_INET:
1049                         if (no_v4bind != 0) {
1050                                 sep->se_fd = -1;
1051                                 continue;
1052                         }
1053                         break;
1054 #ifdef INET6
1055                 case AF_INET6:
1056                         if (no_v6bind != 0) {
1057                                 sep->se_fd = -1;
1058                                 continue;
1059                         }
1060                         break;
1061 #endif
1062                 }
1063                 if (!sep->se_rpc) {
1064                         if (sep->se_family != AF_UNIX) {
1065                                 sp = getservbyname(sep->se_service, sep->se_proto);
1066                                 if (sp == NULL) {
1067                                         syslog(LOG_ERR, "%s/%s: unknown service",
1068                                         sep->se_service, sep->se_proto);
1069                                         sep->se_checked = 0;
1070                                         continue;
1071                                 }
1072                         }
1073                         switch (sep->se_family) {
1074                         case AF_INET:
1075                                 if (sp->s_port != sep->se_ctrladdr4.sin_port) {
1076                                         sep->se_ctrladdr4.sin_port =
1077                                                 sp->s_port;
1078                                         sep->se_reset = 1;
1079                                 }
1080                                 break;
1081 #ifdef INET6
1082                         case AF_INET6:
1083                                 if (sp->s_port !=
1084                                     sep->se_ctrladdr6.sin6_port) {
1085                                         sep->se_ctrladdr6.sin6_port =
1086                                                 sp->s_port;
1087                                         sep->se_reset = 1;
1088                                 }
1089                                 break;
1090 #endif
1091                         }
1092                         if (sep->se_reset != 0 && sep->se_fd >= 0)
1093                                 close_sep(sep);
1094                 } else {
1095                         rpc = getrpcbyname(sep->se_service);
1096                         if (rpc == NULL) {
1097                                 syslog(LOG_ERR, "%s/%s unknown RPC service",
1098                                         sep->se_service, sep->se_proto);
1099                                 if (sep->se_fd != -1)
1100                                         close(sep->se_fd);
1101                                 sep->se_fd = -1;
1102                                         continue;
1103                         }
1104                         if (rpc->r_number != sep->se_rpc_prog) {
1105                                 if (sep->se_rpc_prog)
1106                                         unregisterrpc(sep);
1107                                 sep->se_rpc_prog = rpc->r_number;
1108                                 if (sep->se_fd != -1)
1109                                         close(sep->se_fd);
1110                                 sep->se_fd = -1;
1111                         }
1112                 }
1113                 if (sep->se_fd == -1)
1114                         setup(sep);
1115         }
1116         endconfig();
1117         /*
1118          * Purge anything not looked at above.
1119          */
1120         omask = sigblock(SIGBLOCK);
1121         sepp = &servtab;
1122         while ((sep = *sepp)) {
1123                 if (sep->se_checked) {
1124                         sepp = &sep->se_next;
1125                         continue;
1126                 }
1127                 *sepp = sep->se_next;
1128                 if (sep->se_fd >= 0)
1129                         close_sep(sep);
1130                 if (debug)
1131                         print_service("FREE", sep);
1132                 if (sep->se_rpc && sep->se_rpc_prog > 0)
1133                         unregisterrpc(sep);
1134                 freeconfig(sep);
1135                 free(sep);
1136         }
1137         sigsetmask(omask);
1138 }
1139
1140 void
1141 unregisterrpc(struct servtab *sep)
1142 {
1143         u_int i;
1144         struct servtab *sepp;
1145         long omask;
1146
1147         omask = sigblock(SIGBLOCK);
1148         for (sepp = servtab; sepp; sepp = sepp->se_next) {
1149                 if (sepp == sep)
1150                         continue;
1151                 if (sep->se_checked == 0 ||
1152                     !sepp->se_rpc ||
1153                     sep->se_rpc_prog != sepp->se_rpc_prog)
1154                         continue;
1155                 return;
1156         }
1157         if (debug)
1158                 print_service("UNREG", sep);
1159         for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++)
1160                 pmap_unset(sep->se_rpc_prog, i);
1161         if (sep->se_fd != -1)
1162                 close(sep->se_fd);
1163         sep->se_fd = -1;
1164         sigsetmask(omask);
1165 }
1166
1167 void
1168 flag_retry(int signo __unused)
1169 {
1170         flag_signal('A');
1171 }
1172
1173 void
1174 retry(void)
1175 {
1176         struct servtab *sep;
1177
1178         timingout = 0;
1179         for (sep = servtab; sep; sep = sep->se_next)
1180                 if (sep->se_fd == -1 && !ISMUX(sep))
1181                         setup(sep);
1182 }
1183
1184 void
1185 setup(struct servtab *sep)
1186 {
1187         int on = 1;
1188
1189         if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1190                 if (debug)
1191                         warn("socket failed on %s/%s",
1192                                 sep->se_service, sep->se_proto);
1193                 syslog(LOG_ERR, "%s/%s: socket: %m",
1194                     sep->se_service, sep->se_proto);
1195                 return;
1196         }
1197         /* Set all listening sockets to close-on-exec. */
1198         if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
1199                 syslog(LOG_ERR, "%s/%s: fcntl (F_SETFD, FD_CLOEXEC): %m",
1200                     sep->se_service, sep->se_proto);
1201                 close(sep->se_fd);
1202                 return;
1203         }
1204 #define turnon(fd, opt) \
1205 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1206         if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1207             turnon(sep->se_fd, SO_DEBUG) < 0)
1208                 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1209         if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1210                 syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1211 #ifdef SO_PRIVSTATE
1212         if (turnon(sep->se_fd, SO_PRIVSTATE) < 0)
1213                 syslog(LOG_ERR, "setsockopt (SO_PRIVSTATE): %m");
1214 #endif
1215         /* tftpd opens a new connection then needs more infos */
1216         if ((sep->se_family == AF_INET6) &&
1217             (strcmp(sep->se_proto, "udp") == 0) &&
1218             (sep->se_accept == 0) &&
1219             (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_PKTINFO,
1220                         (char *)&on, sizeof (on)) < 0))
1221                 syslog(LOG_ERR, "setsockopt (IPV6_RECVPKTINFO): %m");
1222         if (sep->se_family == AF_INET6) {
1223                 int flag = sep->se_nomapped ? 1 : 0;
1224                 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_V6ONLY,
1225                                (char *)&flag, sizeof (flag)) < 0)
1226                         syslog(LOG_ERR, "setsockopt (IPV6_V6ONLY): %m");
1227         }
1228 #undef turnon
1229         if (sep->se_type == TTCP_TYPE)
1230                 if (setsockopt(sep->se_fd, IPPROTO_TCP, TCP_NOPUSH,
1231                     (char *)&on, sizeof (on)) < 0)
1232                         syslog(LOG_ERR, "setsockopt (TCP_NOPUSH): %m");
1233 #ifdef IPSEC
1234         ipsecsetup(sep);
1235 #endif
1236         if (sep->se_family == AF_UNIX) {
1237                 unlink(sep->se_ctrladdr_un.sun_path);
1238                 umask(0777); /* Make socket with conservative permissions */
1239         }
1240         if (bind(sep->se_fd, (struct sockaddr *)&sep->se_ctrladdr,
1241             sep->se_ctrladdr_size) < 0) {
1242                 if (debug)
1243                         warn("bind failed on %s/%s",
1244                                 sep->se_service, sep->se_proto);
1245                 syslog(LOG_ERR, "%s/%s: bind: %m",
1246                     sep->se_service, sep->se_proto);
1247                 close(sep->se_fd);
1248                 sep->se_fd = -1;
1249                 if (!timingout) {
1250                         timingout = 1;
1251                         alarm(RETRYTIME);
1252                 }
1253                 if (sep->se_family == AF_UNIX)
1254                         umask(mask);
1255                 return;
1256         }
1257         if (sep->se_family == AF_UNIX) {
1258                 /* Ick - fch{own,mod} don't work on Unix domain sockets */
1259                 if (chown(sep->se_service, sep->se_sockuid, sep->se_sockgid) < 0)
1260                         syslog(LOG_ERR, "chown socket: %m");
1261                 if (chmod(sep->se_service, sep->se_sockmode) < 0)
1262                         syslog(LOG_ERR, "chmod socket: %m");
1263                 umask(mask);
1264         }
1265         if (sep->se_rpc) {
1266                 u_int i;
1267                 socklen_t len = sep->se_ctrladdr_size;
1268
1269                 if (sep->se_family != AF_INET) {
1270                         syslog(LOG_ERR,
1271                                "%s/%s: unsupported address family for rpc",
1272                                sep->se_service, sep->se_proto);
1273                         close(sep->se_fd);
1274                         sep->se_fd = -1;
1275                         return;
1276                 }
1277                 if (getsockname(sep->se_fd,
1278                                 (struct sockaddr*)&sep->se_ctrladdr, &len) < 0){
1279                         syslog(LOG_ERR, "%s/%s: getsockname: %m",
1280                                sep->se_service, sep->se_proto);
1281                         close(sep->se_fd);
1282                         sep->se_fd = -1;
1283                         return;
1284                 }
1285                 if (debug)
1286                         print_service("REG ", sep);
1287                 for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++) {
1288                         pmap_unset(sep->se_rpc_prog, i);
1289                         pmap_set(sep->se_rpc_prog, i,
1290                                  (sep->se_socktype == SOCK_DGRAM)
1291                                  ? IPPROTO_UDP : IPPROTO_TCP,
1292                                  ntohs(sep->se_ctrladdr4.sin_port));
1293                 }
1294         }
1295         if (sep->se_socktype == SOCK_STREAM)
1296                 listen(sep->se_fd, 64);
1297         enable(sep);
1298         if (debug) {
1299                 warnx("registered %s on %d",
1300                         sep->se_server, sep->se_fd);
1301         }
1302 }
1303
1304 #ifdef IPSEC
1305 void
1306 ipsecsetup(struct servtab *sep)
1307 {
1308         char *buf;
1309         char *policy_in = NULL;
1310         char *policy_out = NULL;
1311         int level;
1312         int opt;
1313
1314         switch (sep->se_family) {
1315         case AF_INET:
1316                 level = IPPROTO_IP;
1317                 opt = IP_IPSEC_POLICY;
1318                 break;
1319 #ifdef INET6
1320         case AF_INET6:
1321                 level = IPPROTO_IPV6;
1322                 opt = IPV6_IPSEC_POLICY;
1323                 break;
1324 #endif
1325         default:
1326                 return;
1327         }
1328
1329         if (!sep->se_policy || sep->se_policy[0] == '\0') {
1330                 static char def_in[] = "in entrust", def_out[] = "out entrust";
1331                 policy_in = def_in;
1332                 policy_out = def_out;
1333         } else {
1334                 if (!strncmp("in", sep->se_policy, 2))
1335                         policy_in = sep->se_policy;
1336                 else if (!strncmp("out", sep->se_policy, 3))
1337                         policy_out = sep->se_policy;
1338                 else {
1339                         syslog(LOG_ERR, "invalid security policy \"%s\"",
1340                                 sep->se_policy);
1341                         return;
1342                 }
1343         }
1344
1345         if (policy_in != NULL) {
1346                 buf = ipsec_set_policy(policy_in, strlen(policy_in));
1347                 if (buf != NULL) {
1348                         if (setsockopt(sep->se_fd, level, opt,
1349                                         buf, ipsec_get_policylen(buf)) < 0 &&
1350                             debug != 0)
1351                                 warnx("%s/%s: ipsec initialization failed; %s",
1352                                       sep->se_service, sep->se_proto,
1353                                       policy_in);
1354                         free(buf);
1355                 } else
1356                         syslog(LOG_ERR, "invalid security policy \"%s\"",
1357                                 policy_in);
1358         }
1359         if (policy_out != NULL) {
1360                 buf = ipsec_set_policy(policy_out, strlen(policy_out));
1361                 if (buf != NULL) {
1362                         if (setsockopt(sep->se_fd, level, opt,
1363                                         buf, ipsec_get_policylen(buf)) < 0 &&
1364                             debug != 0)
1365                                 warnx("%s/%s: ipsec initialization failed; %s",
1366                                       sep->se_service, sep->se_proto,
1367                                       policy_out);
1368                         free(buf);
1369                 } else
1370                         syslog(LOG_ERR, "invalid security policy \"%s\"",
1371                                 policy_out);
1372         }
1373 }
1374 #endif
1375
1376 /*
1377  * Finish with a service and its socket.
1378  */
1379 void
1380 close_sep(struct servtab *sep)
1381 {
1382         if (sep->se_fd >= 0) {
1383                 if (FD_ISSET(sep->se_fd, &allsock))
1384                         disable(sep);
1385                 close(sep->se_fd);
1386                 sep->se_fd = -1;
1387         }
1388         sep->se_count = 0;
1389         sep->se_numchild = 0;   /* forget about any existing children */
1390 }
1391
1392 int
1393 matchservent(const char *name1, const char *name2, const char *proto)
1394 {
1395         char **alias, *p;
1396         struct servent *se;
1397
1398         if (strcmp(proto, "unix") == 0) {
1399                 if ((p = strrchr(name1, '/')) != NULL)
1400                         name1 = p + 1;
1401                 if ((p = strrchr(name2, '/')) != NULL)
1402                         name2 = p + 1;
1403         }
1404         if (strcmp(name1, name2) == 0)
1405                 return(1);
1406         if ((se = getservbyname(name1, proto)) != NULL) {
1407                 if (strcmp(name2, se->s_name) == 0)
1408                         return(1);
1409                 for (alias = se->s_aliases; *alias; alias++)
1410                         if (strcmp(name2, *alias) == 0)
1411                                 return(1);
1412         }
1413         return(0);
1414 }
1415
1416 struct servtab *
1417 enter(struct servtab *cp)
1418 {
1419         struct servtab *sep;
1420         long omask;
1421
1422         sep = (struct servtab *)malloc(sizeof (*sep));
1423         if (sep == NULL) {
1424                 syslog(LOG_ERR, "malloc: %m");
1425                 exit(EX_OSERR);
1426         }
1427         *sep = *cp;
1428         sep->se_fd = -1;
1429         omask = sigblock(SIGBLOCK);
1430         sep->se_next = servtab;
1431         servtab = sep;
1432         sigsetmask(omask);
1433         return (sep);
1434 }
1435
1436 void
1437 enable(struct servtab *sep)
1438 {
1439         if (debug)
1440                 warnx(
1441                     "enabling %s, fd %d", sep->se_service, sep->se_fd);
1442 #ifdef SANITY_CHECK
1443         if (sep->se_fd < 0) {
1444                 syslog(LOG_ERR,
1445                     "%s: %s: bad fd", __func__, sep->se_service);
1446                 exit(EX_SOFTWARE);
1447         }
1448         if (ISMUX(sep)) {
1449                 syslog(LOG_ERR,
1450                     "%s: %s: is mux", __func__, sep->se_service);
1451                 exit(EX_SOFTWARE);
1452         }
1453         if (FD_ISSET(sep->se_fd, &allsock)) {
1454                 syslog(LOG_ERR,
1455                     "%s: %s: not off", __func__, sep->se_service);
1456                 exit(EX_SOFTWARE);
1457         }
1458         nsock++;
1459 #endif
1460         FD_SET(sep->se_fd, &allsock);
1461         if (sep->se_fd > maxsock)
1462                 maxsock = sep->se_fd;
1463 }
1464
1465 void
1466 disable(struct servtab *sep)
1467 {
1468         if (debug)
1469                 warnx(
1470                     "disabling %s, fd %d", sep->se_service, sep->se_fd);
1471 #ifdef SANITY_CHECK
1472         if (sep->se_fd < 0) {
1473                 syslog(LOG_ERR,
1474                     "%s: %s: bad fd", __func__, sep->se_service);
1475                 exit(EX_SOFTWARE);
1476         }
1477         if (ISMUX(sep)) {
1478                 syslog(LOG_ERR,
1479                     "%s: %s: is mux", __func__, sep->se_service);
1480                 exit(EX_SOFTWARE);
1481         }
1482         if (!FD_ISSET(sep->se_fd, &allsock)) {
1483                 syslog(LOG_ERR,
1484                     "%s: %s: not on", __func__, sep->se_service);
1485                 exit(EX_SOFTWARE);
1486         }
1487         if (nsock == 0) {
1488                 syslog(LOG_ERR, "%s: nsock=0", __func__);
1489                 exit(EX_SOFTWARE);
1490         }
1491         nsock--;
1492 #endif
1493         FD_CLR(sep->se_fd, &allsock);
1494         if (sep->se_fd == maxsock)
1495                 maxsock--;
1496 }
1497
1498 FILE    *fconfig = NULL;
1499 struct  servtab serv;
1500 char    line[LINE_MAX];
1501
1502 int
1503 setconfig(void)
1504 {
1505
1506         if (fconfig != NULL) {
1507                 fseek(fconfig, 0L, SEEK_SET);
1508                 return (1);
1509         }
1510         fconfig = fopen(CONFIG, "r");
1511         return (fconfig != NULL);
1512 }
1513
1514 void
1515 endconfig(void)
1516 {
1517         if (fconfig) {
1518                 fclose(fconfig);
1519                 fconfig = NULL;
1520         }
1521 }
1522
1523 struct servtab *
1524 getconfigent(void)
1525 {
1526         struct servtab *sep = &serv;
1527         int argc;
1528         char *cp, *arg, *s;
1529         char *versp;
1530         static char TCPMUX_TOKEN[] = "tcpmux/";
1531 #define MUX_LEN         (sizeof(TCPMUX_TOKEN)-1)
1532 #ifdef IPSEC
1533         char *policy = NULL;
1534 #endif
1535         int v4bind = 0;
1536 #ifdef INET6
1537         int v6bind = 0;
1538 #endif
1539         int i;
1540
1541 more:
1542         while ((cp = nextline(fconfig)) != NULL) {
1543 #ifdef IPSEC
1544                 /* lines starting with #@ is not a comment, but the policy */
1545                 if (cp[0] == '#' && cp[1] == '@') {
1546                         char *p;
1547                         for (p = cp + 2; p && *p && isspace(*p); p++)
1548                                 ;
1549                         if (*p == '\0') {
1550                                 if (policy)
1551                                         free(policy);
1552                                 policy = NULL;
1553                         } else if (ipsec_get_policylen(p) >= 0) {
1554                                 if (policy)
1555                                         free(policy);
1556                                 policy = newstr(p);
1557                         } else {
1558                                 syslog(LOG_ERR,
1559                                         "%s: invalid ipsec policy \"%s\"",
1560                                         CONFIG, p);
1561                                 exit(EX_CONFIG);
1562                         }
1563                 }
1564 #endif
1565                 if (*cp == '#' || *cp == '\0')
1566                         continue;
1567                 break;
1568         }
1569         if (cp == NULL)
1570                 return (NULL);
1571         /*
1572          * clear the static buffer, since some fields (se_ctrladdr,
1573          * for example) don't get initialized here.
1574          */
1575         memset(sep, 0, sizeof *sep);
1576         arg = skip(&cp);
1577         if (cp == NULL) {
1578                 /* got an empty line containing just blanks/tabs. */
1579                 goto more;
1580         }
1581         if (arg[0] == ':') { /* :user:group:perm: */
1582                 char *user, *group, *perm;
1583                 struct passwd *pw;
1584                 struct group *gr;
1585                 user = arg+1;
1586                 if ((group = strchr(user, ':')) == NULL) {
1587                         syslog(LOG_ERR, "no group after user '%s'", user);
1588                         goto more;
1589                 }
1590                 *group++ = '\0';
1591                 if ((perm = strchr(group, ':')) == NULL) {
1592                         syslog(LOG_ERR, "no mode after group '%s'", group);
1593                         goto more;
1594                 }
1595                 *perm++ = '\0';
1596                 if ((pw = getpwnam(user)) == NULL) {
1597                         syslog(LOG_ERR, "no such user '%s'", user);
1598                         goto more;
1599                 }
1600                 sep->se_sockuid = pw->pw_uid;
1601                 if ((gr = getgrnam(group)) == NULL) {
1602                         syslog(LOG_ERR, "no such user '%s'", group);
1603                         goto more;
1604                 }
1605                 sep->se_sockgid = gr->gr_gid;
1606                 sep->se_sockmode = strtol(perm, &arg, 8);
1607                 if (*arg != ':') {
1608                         syslog(LOG_ERR, "bad mode '%s'", perm);
1609                         goto more;
1610                 }
1611                 *arg++ = '\0';
1612         } else {
1613                 sep->se_sockuid = euid;
1614                 sep->se_sockgid = egid;
1615                 sep->se_sockmode = 0200;
1616         }
1617         if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1618                 char *c = arg + MUX_LEN;
1619                 if (*c == '+') {
1620                         sep->se_type = MUXPLUS_TYPE;
1621                         c++;
1622                 } else
1623                         sep->se_type = MUX_TYPE;
1624                 sep->se_service = newstr(c);
1625         } else {
1626                 sep->se_service = newstr(arg);
1627                 sep->se_type = NORM_TYPE;
1628         }
1629         arg = sskip(&cp);
1630         if (strcmp(arg, "stream") == 0)
1631                 sep->se_socktype = SOCK_STREAM;
1632         else if (strcmp(arg, "dgram") == 0)
1633                 sep->se_socktype = SOCK_DGRAM;
1634         else if (strcmp(arg, "rdm") == 0)
1635                 sep->se_socktype = SOCK_RDM;
1636         else if (strcmp(arg, "seqpacket") == 0)
1637                 sep->se_socktype = SOCK_SEQPACKET;
1638         else if (strcmp(arg, "raw") == 0)
1639                 sep->se_socktype = SOCK_RAW;
1640         else
1641                 sep->se_socktype = -1;
1642
1643         arg = sskip(&cp);
1644         if (strncmp(arg, "tcp", 3) == 0) {
1645                 sep->se_proto = newstr(strsep(&arg, "/"));
1646                 if (arg != NULL) {
1647                         if (strcmp(arg, "ttcp") == 0)
1648                                 sep->se_type = TTCP_TYPE;
1649                 }
1650         } else {
1651                 sep->se_proto = newstr(arg);
1652         }
1653         if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1654                 if (no_v4bind != 0) {
1655                         syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1656                                sep->se_service);
1657                         freeconfig(sep);
1658                         goto more;
1659                 }
1660                 memmove(sep->se_proto, sep->se_proto + 4,
1661                     strlen(sep->se_proto) + 1 - 4);
1662                 sep->se_rpc = 1;
1663                 sep->se_rpc_prog = sep->se_rpc_lowvers =
1664                         sep->se_rpc_highvers = 0;
1665                 memcpy(&sep->se_ctrladdr4, bind_sa4,
1666                        sizeof(sep->se_ctrladdr4));
1667                 if ((versp = strrchr(sep->se_service, '/'))) {
1668                         *versp++ = '\0';
1669                         switch (sscanf(versp, "%u-%u",
1670                                        &sep->se_rpc_lowvers,
1671                                        &sep->se_rpc_highvers)) {
1672                         case 2:
1673                                 break;
1674                         case 1:
1675                                 sep->se_rpc_highvers =
1676                                         sep->se_rpc_lowvers;
1677                                 break;
1678                         default:
1679                                 syslog(LOG_ERR,
1680                                         "bad RPC version specifier; %s",
1681                                         sep->se_service);
1682                                 freeconfig(sep);
1683                                 goto more;
1684                         }
1685                 }
1686                 else {
1687                         sep->se_rpc_lowvers =
1688                                 sep->se_rpc_highvers = 1;
1689                 }
1690         }
1691         sep->se_nomapped = 0;
1692         while (isdigit(sep->se_proto[strlen(sep->se_proto) - 1])) {
1693 #ifdef INET6
1694                 if (sep->se_proto[strlen(sep->se_proto) - 1] == '6') {
1695                         if (no_v6bind != 0) {
1696                                 syslog(LOG_NOTICE, "IPv6 bind is ignored for %s",
1697                                        sep->se_service);
1698                                 freeconfig(sep);
1699                                 goto more;
1700                         }
1701                         sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1702                         v6bind = 1;
1703                         continue;
1704                 }
1705 #endif
1706                 if (sep->se_proto[strlen(sep->se_proto) - 1] == '4') {
1707                         sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1708                         v4bind = 1;
1709                         continue;
1710                 }
1711                 /* illegal version num */
1712                 syslog(LOG_ERR, "bad IP version for %s", sep->se_proto);
1713                 freeconfig(sep);
1714                 goto more;
1715         }
1716         if (strcmp(sep->se_proto, "unix") == 0) {
1717                 sep->se_family = AF_UNIX;
1718         } else
1719 #ifdef INET6
1720         if (v6bind != 0) {
1721                 sep->se_family = AF_INET6;
1722                 if (v4bind == 0 || no_v4bind != 0)
1723                         sep->se_nomapped = 1;
1724         } else
1725 #endif
1726         { /* default to v4 bind if not v6 bind */
1727                 if (no_v4bind != 0) {
1728                         syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1729                                sep->se_service);
1730                         freeconfig(sep);
1731                         goto more;
1732                 }
1733                 sep->se_family = AF_INET;
1734         }
1735         /* init ctladdr */
1736         switch(sep->se_family) {
1737         case AF_INET:
1738                 memcpy(&sep->se_ctrladdr4, bind_sa4,
1739                        sizeof(sep->se_ctrladdr4));
1740                 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr4);
1741                 break;
1742 #ifdef INET6
1743         case AF_INET6:
1744                 memcpy(&sep->se_ctrladdr6, bind_sa6,
1745                        sizeof(sep->se_ctrladdr6));
1746                 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr6);
1747                 break;
1748 #endif
1749         case AF_UNIX:
1750                 if (strlen(sep->se_service) >= sizeof(sep->se_ctrladdr_un.sun_path)) {
1751                         syslog(LOG_ERR, 
1752                             "domain socket pathname too long for service %s",
1753                             sep->se_service);
1754                         goto more;
1755                 }
1756                 memset(&sep->se_ctrladdr, 0, sizeof(sep->se_ctrladdr));
1757                 sep->se_ctrladdr_un.sun_family = sep->se_family;
1758                 sep->se_ctrladdr_un.sun_len = strlen(sep->se_service);
1759                 strcpy(sep->se_ctrladdr_un.sun_path, sep->se_service);
1760                 sep->se_ctrladdr_size = SUN_LEN(&sep->se_ctrladdr_un);
1761         }
1762         arg = sskip(&cp);
1763         if (!strncmp(arg, "wait", 4))
1764                 sep->se_accept = 0;
1765         else if (!strncmp(arg, "nowait", 6))
1766                 sep->se_accept = 1;
1767         else {
1768                 syslog(LOG_ERR,
1769                         "%s: bad wait/nowait for service %s",
1770                         CONFIG, sep->se_service);
1771                 goto more;
1772         }
1773         sep->se_maxchild = -1;
1774         sep->se_maxcpm = -1;
1775         sep->se_maxperip = -1;
1776         if ((s = strchr(arg, '/')) != NULL) {
1777                 char *eptr;
1778                 u_long val;
1779
1780                 val = strtoul(s + 1, &eptr, 10);
1781                 if (eptr == s + 1 || val > MAX_MAXCHLD) {
1782                         syslog(LOG_ERR,
1783                                 "%s: bad max-child for service %s",
1784                                 CONFIG, sep->se_service);
1785                         goto more;
1786                 }
1787                 if (debug)
1788                         if (!sep->se_accept && val != 1)
1789                                 warnx("maxchild=%lu for wait service %s"
1790                                     " not recommended", val, sep->se_service);
1791                 sep->se_maxchild = val;
1792                 if (*eptr == '/')
1793                         sep->se_maxcpm = strtol(eptr + 1, &eptr, 10);
1794                 if (*eptr == '/')
1795                         sep->se_maxperip = strtol(eptr + 1, &eptr, 10);
1796                 /*
1797                  * explicitly do not check for \0 for future expansion /
1798                  * backwards compatibility
1799                  */
1800         }
1801         if (ISMUX(sep)) {
1802                 /*
1803                  * Silently enforce "nowait" mode for TCPMUX services
1804                  * since they don't have an assigned port to listen on.
1805                  */
1806                 sep->se_accept = 1;
1807                 if (strcmp(sep->se_proto, "tcp")) {
1808                         syslog(LOG_ERR,
1809                                 "%s: bad protocol for tcpmux service %s",
1810                                 CONFIG, sep->se_service);
1811                         goto more;
1812                 }
1813                 if (sep->se_socktype != SOCK_STREAM) {
1814                         syslog(LOG_ERR,
1815                                 "%s: bad socket type for tcpmux service %s",
1816                                 CONFIG, sep->se_service);
1817                         goto more;
1818                 }
1819         }
1820         sep->se_user = newstr(sskip(&cp));
1821 #ifdef LOGIN_CAP
1822         if ((s = strrchr(sep->se_user, '/')) != NULL) {
1823                 *s = '\0';
1824                 sep->se_class = newstr(s + 1);
1825         } else
1826                 sep->se_class = newstr(RESOURCE_RC);
1827 #endif
1828         if ((s = strrchr(sep->se_user, ':')) != NULL) {
1829                 *s = '\0';
1830                 sep->se_group = newstr(s + 1);
1831         } else
1832                 sep->se_group = NULL;
1833         sep->se_server = newstr(sskip(&cp));
1834         if ((sep->se_server_name = strrchr(sep->se_server, '/')))
1835                 sep->se_server_name++;
1836         if (strcmp(sep->se_server, "internal") == 0) {
1837                 struct biltin *bi;
1838
1839                 for (bi = biltins; bi->bi_service; bi++)
1840                         if (bi->bi_socktype == sep->se_socktype &&
1841                             matchservent(bi->bi_service, sep->se_service,
1842                             sep->se_proto))
1843                                 break;
1844                 if (bi->bi_service == 0) {
1845                         syslog(LOG_ERR, "internal service %s unknown",
1846                                 sep->se_service);
1847                         goto more;
1848                 }
1849                 sep->se_accept = 1;     /* force accept mode for built-ins */
1850                 sep->se_bi = bi;
1851         } else
1852                 sep->se_bi = NULL;
1853         if (sep->se_maxperip < 0)
1854                 sep->se_maxperip = maxperip;
1855         if (sep->se_maxcpm < 0)
1856                 sep->se_maxcpm = maxcpm;
1857         if (sep->se_maxchild < 0) {     /* apply default max-children */
1858                 if (sep->se_bi && sep->se_bi->bi_maxchild >= 0)
1859                         sep->se_maxchild = sep->se_bi->bi_maxchild;
1860                 else if (sep->se_accept) 
1861                         sep->se_maxchild = maxchild > 0 ? maxchild : 0;
1862                 else
1863                         sep->se_maxchild = 1;
1864         }
1865         if (sep->se_maxchild > 0) {
1866                 sep->se_pids = malloc(sep->se_maxchild * sizeof(*sep->se_pids));
1867                 if (sep->se_pids == NULL) {
1868                         syslog(LOG_ERR, "malloc: %m");
1869                         exit(EX_OSERR);
1870                 }
1871         }
1872         argc = 0;
1873         for (arg = skip(&cp); cp; arg = skip(&cp))
1874                 if (argc < MAXARGV) {
1875                         sep->se_argv[argc++] = newstr(arg);
1876                 } else {
1877                         syslog(LOG_ERR,
1878                                 "%s: too many arguments for service %s",
1879                                 CONFIG, sep->se_service);
1880                         goto more;
1881                 }
1882         while (argc <= MAXARGV)
1883                 sep->se_argv[argc++] = NULL;
1884         for (i = 0; i < PERIPSIZE; ++i)
1885                 LIST_INIT(&sep->se_conn[i]);
1886 #ifdef IPSEC
1887         sep->se_policy = policy ? newstr(policy) : NULL;
1888 #endif
1889         return (sep);
1890 }
1891
1892 void
1893 freeconfig(struct servtab *cp)
1894 {
1895         int i;
1896
1897         if (cp->se_service)
1898                 free(cp->se_service);
1899         if (cp->se_proto)
1900                 free(cp->se_proto);
1901         if (cp->se_user)
1902                 free(cp->se_user);
1903         if (cp->se_group)
1904                 free(cp->se_group);
1905 #ifdef LOGIN_CAP
1906         if (cp->se_class)
1907                 free(cp->se_class);
1908 #endif
1909         if (cp->se_server)
1910                 free(cp->se_server);
1911         if (cp->se_pids)
1912                 free(cp->se_pids);
1913         for (i = 0; i < MAXARGV; i++)
1914                 if (cp->se_argv[i])
1915                         free(cp->se_argv[i]);
1916         free_connlist(cp);
1917 #ifdef IPSEC
1918         if (cp->se_policy)
1919                 free(cp->se_policy);
1920 #endif
1921 }
1922
1923
1924 /*
1925  * Safe skip - if skip returns null, log a syntax error in the
1926  * configuration file and exit.
1927  */
1928 char *
1929 sskip(char **cpp)
1930 {
1931         char *cp;
1932
1933         cp = skip(cpp);
1934         if (cp == NULL) {
1935                 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1936                 exit(EX_DATAERR);
1937         }
1938         return (cp);
1939 }
1940
1941 char *
1942 skip(char **cpp)
1943 {
1944         char *cp = *cpp;
1945         char *start;
1946         char quote = '\0';
1947
1948 again:
1949         while (*cp == ' ' || *cp == '\t')
1950                 cp++;
1951         if (*cp == '\0') {
1952                 int c;
1953
1954                 c = getc(fconfig);
1955                 ungetc(c, fconfig);
1956                 if (c == ' ' || c == '\t')
1957                         if ((cp = nextline(fconfig)))
1958                                 goto again;
1959                 *cpp = NULL;
1960                 return (NULL);
1961         }
1962         if (*cp == '"' || *cp == '\'')
1963                 quote = *cp++;
1964         start = cp;
1965         if (quote)
1966                 while (*cp && *cp != quote)
1967                         cp++;
1968         else
1969                 while (*cp && *cp != ' ' && *cp != '\t')
1970                         cp++;
1971         if (*cp != '\0')
1972                 *cp++ = '\0';
1973         *cpp = cp;
1974         return (start);
1975 }
1976
1977 char *
1978 nextline(FILE *fd)
1979 {
1980         char *cp;
1981
1982         if (fgets(line, sizeof (line), fd) == NULL)
1983                 return (NULL);
1984         cp = strchr(line, '\n');
1985         if (cp)
1986                 *cp = '\0';
1987         return (line);
1988 }
1989
1990 char *
1991 newstr(const char *cp)
1992 {
1993         char *cr;
1994
1995         if ((cr = strdup(cp != NULL ? cp : "")))
1996                 return (cr);
1997         syslog(LOG_ERR, "strdup: %m");
1998         exit(EX_OSERR);
1999 }
2000
2001 void
2002 inetd_setproctitle(const char *a, int s)
2003 {
2004         socklen_t size;
2005         struct sockaddr_storage ss;
2006         char buf[80], pbuf[INET6_ADDRSTRLEN];
2007
2008         size = sizeof(ss);
2009         if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
2010                 getnameinfo((struct sockaddr *)&ss, size, pbuf, sizeof(pbuf),
2011                             NULL, 0, NI_NUMERICHOST|NI_WITHSCOPEID);
2012                 sprintf(buf, "%s [%s]", a, pbuf);
2013         } else
2014                 sprintf(buf, "%s", a);
2015         setproctitle("%s", buf);
2016 }
2017
2018 int
2019 check_loop(const struct sockaddr *sa, const struct servtab *sep)
2020 {
2021         struct servtab *se2;
2022         char pname[INET6_ADDRSTRLEN];
2023
2024         for (se2 = servtab; se2; se2 = se2->se_next) {
2025                 if (!se2->se_bi || se2->se_socktype != SOCK_DGRAM)
2026                         continue;
2027
2028                 switch (se2->se_family) {
2029                 case AF_INET:
2030                         if (((const struct sockaddr_in *)sa)->sin_port ==
2031                             se2->se_ctrladdr4.sin_port)
2032                                 goto isloop;
2033                         continue;
2034 #ifdef INET6
2035                 case AF_INET6:
2036                         if (((const struct sockaddr_in *)sa)->sin_port ==
2037                             se2->se_ctrladdr4.sin_port)
2038                                 goto isloop;
2039                         continue;
2040 #endif
2041                 default:
2042                         continue;
2043                 }
2044         isloop:
2045                 getnameinfo(sa, sa->sa_len, pname, sizeof(pname), NULL, 0,
2046                             NI_NUMERICHOST|NI_WITHSCOPEID);
2047                 syslog(LOG_WARNING, "%s/%s:%s/%s loop request REFUSED from %s",
2048                        sep->se_service, sep->se_proto,
2049                        se2->se_service, se2->se_proto,
2050                        pname);
2051                 return 1;
2052         }
2053         return 0;
2054 }
2055
2056 /*
2057  * print_service:
2058  *      Dump relevant information to stderr
2059  */
2060 void
2061 print_service(const char *action, const struct servtab *sep)
2062 {
2063         fprintf(stderr,
2064             "%s: %s proto=%s accept=%d max=%d user=%s group=%s"
2065 #ifdef LOGIN_CAP
2066             "class=%s"
2067 #endif
2068             " builtin=%p server=%s"
2069 #ifdef IPSEC
2070             " policy=\"%s\""
2071 #endif
2072             "\n",
2073             action, sep->se_service, sep->se_proto,
2074             sep->se_accept, sep->se_maxchild, sep->se_user, sep->se_group,
2075 #ifdef LOGIN_CAP
2076             sep->se_class,
2077 #endif
2078             (void *) sep->se_bi, sep->se_server
2079 #ifdef IPSEC
2080             , (sep->se_policy ? sep->se_policy : "")
2081 #endif
2082             );
2083 }
2084
2085 #define CPMHSIZE        256
2086 #define CPMHMASK        (CPMHSIZE-1)
2087 #define CHTGRAN         10
2088 #define CHTSIZE         6
2089
2090 typedef struct CTime {
2091         unsigned long   ct_Ticks;
2092         int             ct_Count;
2093 } CTime;
2094
2095 typedef struct CHash {
2096         union {
2097                 struct in_addr  c4_Addr;
2098                 struct in6_addr c6_Addr;
2099         } cu_Addr;
2100 #define ch_Addr4        cu_Addr.c4_Addr
2101 #define ch_Addr6        cu_Addr.c6_Addr
2102         int             ch_Family;
2103         time_t          ch_LTime;
2104         char            *ch_Service;
2105         CTime           ch_Times[CHTSIZE];
2106 } CHash;
2107
2108 CHash   CHashAry[CPMHSIZE];
2109
2110 int
2111 cpmip(const struct servtab *sep, int ctrl)
2112 {
2113         struct sockaddr_storage rss;
2114         socklen_t rssLen = sizeof(rss);
2115         int r = 0;
2116
2117         /*
2118          * If getpeername() fails, just let it through (if logging is
2119          * enabled the condition is caught elsewhere)
2120          */
2121
2122         if (sep->se_maxcpm > 0 && 
2123             getpeername(ctrl, (struct sockaddr *)&rss, &rssLen) == 0 ) {
2124                 time_t t = time(NULL);
2125                 int hv = 0xABC3D20F;
2126                 int i;
2127                 int cnt = 0;
2128                 CHash *chBest = NULL;
2129                 unsigned int ticks = t / CHTGRAN;
2130                 struct sockaddr_in *sin4;
2131 #ifdef INET6
2132                 struct sockaddr_in6 *sin6;
2133 #endif
2134
2135                 sin4 = (struct sockaddr_in *)&rss;
2136 #ifdef INET6
2137                 sin6 = (struct sockaddr_in6 *)&rss;
2138 #endif
2139                 {
2140                         char *p;
2141                         int addrlen;
2142
2143                         switch (rss.ss_family) {
2144                         case AF_INET:
2145                                 p = (char *)&sin4->sin_addr;
2146                                 addrlen = sizeof(struct in_addr);
2147                                 break;
2148 #ifdef INET6
2149                         case AF_INET6:
2150                                 p = (char *)&sin6->sin6_addr;
2151                                 addrlen = sizeof(struct in6_addr);
2152                                 break;
2153 #endif
2154                         default:
2155                                 /* should not happen */
2156                                 return -1;
2157                         }
2158
2159                         for (i = 0; i < addrlen; ++i, ++p) {
2160                                 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2161                         }
2162                         hv = (hv ^ (hv >> 16));
2163                 }
2164                 for (i = 0; i < 5; ++i) {
2165                         CHash *ch = &CHashAry[(hv + i) & CPMHMASK];
2166
2167                         if (rss.ss_family == AF_INET &&
2168                             ch->ch_Family == AF_INET &&
2169                             sin4->sin_addr.s_addr == ch->ch_Addr4.s_addr &&
2170                             ch->ch_Service && strcmp(sep->se_service,
2171                             ch->ch_Service) == 0) {
2172                                 chBest = ch;
2173                                 break;
2174                         }
2175 #ifdef INET6
2176                         if (rss.ss_family == AF_INET6 &&
2177                             ch->ch_Family == AF_INET6 &&
2178                             IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2179                                                &ch->ch_Addr6) != 0 &&
2180                             ch->ch_Service && strcmp(sep->se_service,
2181                             ch->ch_Service) == 0) {
2182                                 chBest = ch;
2183                                 break;
2184                         }
2185 #endif
2186                         if (chBest == NULL || ch->ch_LTime == 0 || 
2187                             ch->ch_LTime < chBest->ch_LTime) {
2188                                 chBest = ch;
2189                         }
2190                 }
2191                 if ((rss.ss_family == AF_INET &&
2192                      (chBest->ch_Family != AF_INET ||
2193                       sin4->sin_addr.s_addr != chBest->ch_Addr4.s_addr)) ||
2194                     chBest->ch_Service == NULL ||
2195                     strcmp(sep->se_service, chBest->ch_Service) != 0) {
2196                         chBest->ch_Family = sin4->sin_family;
2197                         chBest->ch_Addr4 = sin4->sin_addr;
2198                         if (chBest->ch_Service)
2199                                 free(chBest->ch_Service);
2200                         chBest->ch_Service = strdup(sep->se_service);
2201                         bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2202                 } 
2203 #ifdef INET6
2204                 if ((rss.ss_family == AF_INET6 &&
2205                      (chBest->ch_Family != AF_INET6 ||
2206                       IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2207                                          &chBest->ch_Addr6) == 0)) ||
2208                     chBest->ch_Service == NULL ||
2209                     strcmp(sep->se_service, chBest->ch_Service) != 0) {
2210                         chBest->ch_Family = sin6->sin6_family;
2211                         chBest->ch_Addr6 = sin6->sin6_addr;
2212                         if (chBest->ch_Service)
2213                                 free(chBest->ch_Service);
2214                         chBest->ch_Service = strdup(sep->se_service);
2215                         bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2216                 }
2217 #endif
2218                 chBest->ch_LTime = t;
2219                 {
2220                         CTime *ct = &chBest->ch_Times[ticks % CHTSIZE];
2221                         if (ct->ct_Ticks != ticks) {
2222                                 ct->ct_Ticks = ticks;
2223                                 ct->ct_Count = 0;
2224                         }
2225                         ++ct->ct_Count;
2226                 }
2227                 for (i = 0; i < CHTSIZE; ++i) {
2228                         CTime *ct = &chBest->ch_Times[i];
2229                         if (ct->ct_Ticks <= ticks &&
2230                             ct->ct_Ticks >= ticks - CHTSIZE) {
2231                                 cnt += ct->ct_Count;
2232                         }
2233                 }
2234                 if (cnt * (CHTSIZE * CHTGRAN) / 60 > sep->se_maxcpm) {
2235                         char pname[INET6_ADDRSTRLEN];
2236
2237                         getnameinfo((struct sockaddr *)&rss,
2238                                     ((struct sockaddr *)&rss)->sa_len,
2239                                     pname, sizeof(pname), NULL, 0,
2240                                     NI_NUMERICHOST|NI_WITHSCOPEID);
2241                         r = -1;
2242                         syslog(LOG_ERR,
2243                             "%s from %s exceeded counts/min (limit %d/min)",
2244                             sep->se_service, pname,
2245                             sep->se_maxcpm);
2246                 }
2247         }
2248         return(r);
2249 }
2250
2251 static struct conninfo *
2252 search_conn(struct servtab *sep, int ctrl)
2253 {
2254         struct sockaddr_storage ss;
2255         socklen_t sslen = sizeof(ss);
2256         struct conninfo *conn;
2257         int hv;
2258         char pname[NI_MAXHOST],  pname2[NI_MAXHOST];
2259
2260         if (sep->se_maxperip <= 0)
2261                 return NULL;
2262
2263         /*
2264          * If getpeername() fails, just let it through (if logging is
2265          * enabled the condition is caught elsewhere)
2266          */
2267         if (getpeername(ctrl, (struct sockaddr *)&ss, &sslen) != 0)
2268                 return NULL;
2269
2270         switch (ss.ss_family) {
2271         case AF_INET:
2272                 hv = hashval((char *)&((struct sockaddr_in *)&ss)->sin_addr,
2273                     sizeof(struct in_addr));
2274                 break;
2275 #ifdef INET6
2276         case AF_INET6:
2277                 hv = hashval((char *)&((struct sockaddr_in6 *)&ss)->sin6_addr,
2278                     sizeof(struct in6_addr));
2279                 break;
2280 #endif
2281         default:
2282                 /*
2283                  * Since we only support AF_INET and AF_INET6, just
2284                  * let other than AF_INET and AF_INET6 through.
2285                  */
2286                 return NULL;
2287         }
2288
2289         if (getnameinfo((struct sockaddr *)&ss, sslen, pname, sizeof(pname),
2290             NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID) != 0)
2291                 return NULL;
2292
2293         LIST_FOREACH(conn, &sep->se_conn[hv], co_link) {
2294                 if (getnameinfo((struct sockaddr *)&conn->co_addr,
2295                     conn->co_addr.ss_len, pname2, sizeof(pname2), NULL, 0,
2296                     NI_NUMERICHOST | NI_WITHSCOPEID) == 0 &&
2297                     strcmp(pname, pname2) == 0)
2298                         break;
2299         }
2300
2301         if (conn == NULL) {
2302                 if ((conn = malloc(sizeof(struct conninfo))) == NULL) {
2303                         syslog(LOG_ERR, "malloc: %m");
2304                         exit(EX_OSERR);
2305                 }
2306                 conn->co_proc = malloc(sep->se_maxperip * sizeof(*conn->co_proc));
2307                 if (conn->co_proc == NULL) {
2308                         syslog(LOG_ERR, "malloc: %m");
2309                         exit(EX_OSERR);
2310                 }
2311                 memcpy(&conn->co_addr, (struct sockaddr *)&ss, sslen);
2312                 conn->co_numchild = 0;
2313                 LIST_INSERT_HEAD(&sep->se_conn[hv], conn, co_link);
2314         }
2315
2316         /*
2317          * Since a child process is not invoked yet, we cannot
2318          * determine a pid of a child.  So, co_proc and co_numchild
2319          * should be filled leter.
2320          */
2321
2322         return conn;
2323 }
2324
2325 static int
2326 room_conn(struct servtab *sep, struct conninfo *conn)
2327 {
2328         char pname[NI_MAXHOST];
2329
2330         if (conn->co_numchild >= sep->se_maxperip) {
2331                 getnameinfo((struct sockaddr *)&conn->co_addr,
2332                     conn->co_addr.ss_len, pname, sizeof(pname), NULL, 0,
2333                     NI_NUMERICHOST | NI_WITHSCOPEID);
2334                 syslog(LOG_ERR, "%s from %s exceeded counts (limit %d)",
2335                     sep->se_service, pname, sep->se_maxperip);
2336                 return 0;
2337         }
2338         return 1;
2339 }
2340
2341 static void
2342 addchild_conn(struct conninfo *conn, pid_t pid)
2343 {
2344         struct procinfo *proc;
2345
2346         if (conn == NULL)
2347                 return;
2348
2349         if ((proc = search_proc(pid, 1)) != NULL) {
2350                 if (proc->pr_conn != NULL) {
2351                         syslog(LOG_ERR,
2352                             "addchild_conn: child already on process list");
2353                         exit(EX_OSERR);
2354                 }
2355                 proc->pr_conn = conn;
2356         }
2357
2358         conn->co_proc[conn->co_numchild++] = proc;
2359 }
2360
2361 static void
2362 reapchild_conn(pid_t pid)
2363 {
2364         struct procinfo *proc;
2365         struct conninfo *conn;
2366         int i;
2367
2368         if ((proc = search_proc(pid, 0)) == NULL)
2369                 return;
2370         if ((conn = proc->pr_conn) == NULL)
2371                 return;
2372         for (i = 0; i < conn->co_numchild; ++i)
2373                 if (conn->co_proc[i] == proc) {
2374                         conn->co_proc[i] = conn->co_proc[--conn->co_numchild];
2375                         break;
2376                 }
2377         free_proc(proc);
2378         free_conn(conn);
2379 }
2380
2381 static void
2382 resize_conn(struct servtab *sep, int maxpip)
2383 {
2384         struct conninfo *conn;
2385         int i, j;
2386
2387         if (sep->se_maxperip <= 0)
2388                 return;
2389         if (maxpip <= 0) {
2390                 free_connlist(sep);
2391                 return;
2392         }
2393         for (i = 0; i < PERIPSIZE; ++i) {
2394                 LIST_FOREACH(conn, &sep->se_conn[i], co_link) {
2395                         for (j = maxpip; j < conn->co_numchild; ++j)
2396                                 free_proc(conn->co_proc[j]);
2397                         conn->co_proc = realloc(conn->co_proc,
2398                             maxpip * sizeof(*conn->co_proc));
2399                         if (conn->co_proc == NULL) {
2400                                 syslog(LOG_ERR, "realloc: %m");
2401                                 exit(EX_OSERR);
2402                         }
2403                         if (conn->co_numchild > maxpip)
2404                                 conn->co_numchild = maxpip;
2405                 }
2406         }
2407 }
2408
2409 static void
2410 free_connlist(struct servtab *sep)
2411 {
2412         struct conninfo *conn;
2413         int i, j;
2414
2415         for (i = 0; i < PERIPSIZE; ++i) {
2416                 while ((conn = LIST_FIRST(&sep->se_conn[i])) != NULL) {
2417                         for (j = 0; j < conn->co_numchild; ++j)
2418                                 free_proc(conn->co_proc[j]);
2419                         conn->co_numchild = 0;
2420                         free_conn(conn);
2421                 }
2422         }
2423 }
2424
2425 static void
2426 free_conn(struct conninfo *conn)
2427 {
2428         if (conn == NULL)
2429                 return;
2430         if (conn->co_numchild <= 0) {
2431                 LIST_REMOVE(conn, co_link);
2432                 free(conn->co_proc);
2433                 free(conn);
2434         }
2435 }
2436
2437 static struct procinfo *
2438 search_proc(pid_t pid, int add)
2439 {
2440         struct procinfo *proc;
2441         int hv;
2442
2443         hv = hashval((char *)&pid, sizeof(pid));
2444         LIST_FOREACH(proc, &proctable[hv], pr_link) {
2445                 if (proc->pr_pid == pid)
2446                         break;
2447         }
2448         if (proc == NULL && add) {
2449                 if ((proc = malloc(sizeof(struct procinfo))) == NULL) {
2450                         syslog(LOG_ERR, "malloc: %m");
2451                         exit(EX_OSERR);
2452                 }
2453                 proc->pr_pid = pid;
2454                 proc->pr_conn = NULL;
2455                 LIST_INSERT_HEAD(&proctable[hv], proc, pr_link);
2456         }
2457         return proc;
2458 }
2459
2460 static void
2461 free_proc(struct procinfo *proc)
2462 {
2463         if (proc == NULL)
2464                 return;
2465         LIST_REMOVE(proc, pr_link);
2466         free(proc);
2467 }
2468
2469 static int
2470 hashval(char *p, int len)
2471 {
2472         int i, hv = 0xABC3D20F;
2473
2474         for (i = 0; i < len; ++i, ++p)
2475                 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2476         hv = (hv ^ (hv >> 16)) & (PERIPSIZE - 1);
2477         return hv;
2478 }