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