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