Use strchr instead of index, and strrchr instead of rindex because the str*chr
[dragonfly.git] / usr.sbin / inetd / inetd.c
1 /*
2  * Copyright (c) 1983, 1991, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1983, 1991, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)from: inetd.c    8.4 (Berkeley) 4/13/94
35  * $FreeBSD: src/usr.sbin/inetd/inetd.c,v 1.80.2.11 2003/04/05 13:39:18 dwmalone Exp $
36  * $DragonFly: src/usr.sbin/inetd/inetd.c,v 1.6 2004/08/30 19:27:21 eirikn Exp $
37  */
38
39 /*
40  * Inetd - Internet super-server
41  *
42  * This program invokes all internet services as needed.  Connection-oriented
43  * services are invoked each time a connection is made, by creating a process.
44  * This process is passed the connection as file descriptor 0 and is expected
45  * to do a getpeername to find out the source host and port.
46  *
47  * Datagram oriented services are invoked when a datagram
48  * arrives; a process is created and passed a pending message
49  * on file descriptor 0.  Datagram servers may either connect
50  * to their peer, freeing up the original socket for inetd
51  * to receive further messages on, or ``take over the socket'',
52  * processing all arriving datagrams and, eventually, timing
53  * out.  The first type of server is said to be ``multi-threaded'';
54  * the second type of server ``single-threaded''.
55  *
56  * Inetd uses a configuration file which is read at startup
57  * and, possibly, at some later time in response to a hangup signal.
58  * The configuration file is ``free format'' with fields given in the
59  * order shown below.  Continuation lines for an entry must begin with
60  * a space or tab.  All fields must be present in each entry.
61  *
62  *      service name                    must be in /etc/services
63  *                                      or name a tcpmux service 
64  *                                      or specify a unix domain socket
65  *      socket type                     stream/dgram/raw/rdm/seqpacket
66  *      protocol                        tcp[4][6][/faith,ttcp], udp[4][6], unix
67  *      wait/nowait                     single-threaded/multi-threaded
68  *      user                            user to run daemon as
69  *      server program                  full path name
70  *      server program arguments        maximum of MAXARGS (20)
71  *
72  * TCP services without official port numbers are handled with the
73  * RFC1078-based tcpmux internal service. Tcpmux listens on port 1 for
74  * requests. When a connection is made from a foreign host, the service
75  * requested is passed to tcpmux, which looks it up in the servtab list
76  * and returns the proper entry for the service. Tcpmux returns a
77  * negative reply if the service doesn't exist, otherwise the invoked
78  * server is expected to return the positive reply if the service type in
79  * inetd.conf file has the prefix "tcpmux/". If the service type has the
80  * prefix "tcpmux/+", tcpmux will return the positive reply for the
81  * process; this is for compatibility with older server code, and also
82  * allows you to invoke programs that use stdin/stdout without putting any
83  * special server code in them. Services that use tcpmux are "nowait"
84  * because they do not have a well-known port and hence cannot listen
85  * for new requests.
86  *
87  * For RPC services
88  *      service name/version            must be in /etc/rpc
89  *      socket type                     stream/dgram/raw/rdm/seqpacket
90  *      protocol                        rpc/tcp, rpc/udp
91  *      wait/nowait                     single-threaded/multi-threaded
92  *      user                            user to run daemon as
93  *      server program                  full path name
94  *      server program arguments        maximum of MAXARGS
95  *
96  * Comment lines are indicated by a `#' in column 1.
97  *
98  * #ifdef IPSEC
99  * Comment lines that start with "#@" denote IPsec policy string, as described
100  * in ipsec_set_policy(3).  This will affect all the following items in
101  * inetd.conf(8).  To reset the policy, just use "#@" line.  By default,
102  * there's no IPsec policy.
103  * #endif
104  */
105 #include <sys/param.h>
106 #include <sys/ioctl.h>
107 #include <sys/wait.h>
108 #include <sys/time.h>
109 #include <sys/resource.h>
110 #include <sys/stat.h>
111 #include <sys/un.h>
112
113 #include <netinet/in.h>
114 #include <netinet/tcp.h>
115 #include <arpa/inet.h>
116 #include <rpc/rpc.h>
117 #include <rpc/pmap_clnt.h>
118
119 #include <errno.h>
120 #include <err.h>
121 #include <fcntl.h>
122 #include <grp.h>
123 #include <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     log = 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 tmpint, 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                         log = 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                 setenv("inetd_dummy", dummy, 1);
508         }
509
510         if (pipe(signalpipe) != 0) {
511                 syslog(LOG_ERR, "pipe: %m");
512                 exit(EX_OSERR);
513         }
514         if (fcntl(signalpipe[0], F_SETFD, FD_CLOEXEC) < 0 ||
515             fcntl(signalpipe[1], F_SETFD, FD_CLOEXEC) < 0) {
516                 syslog(LOG_ERR, "signalpipe: fcntl (F_SETFD, FD_CLOEXEC): %m");
517                 exit(EX_OSERR);
518         }
519         FD_SET(signalpipe[0], &allsock);
520 #ifdef SANITY_CHECK
521         nsock++;
522 #endif
523         if (signalpipe[0] > maxsock)
524             maxsock = signalpipe[0];
525         if (signalpipe[1] > maxsock)
526             maxsock = signalpipe[1];
527
528         for (;;) {
529             int n, ctrl;
530             fd_set readable;
531
532 #ifdef SANITY_CHECK
533             if (nsock == 0) {
534                 syslog(LOG_ERR, "%s: nsock=0", __FUNCTION__);
535                 exit(EX_SOFTWARE);
536             }
537 #endif
538             readable = allsock;
539             if ((n = select(maxsock + 1, &readable, (fd_set *)0,
540                 (fd_set *)0, (struct timeval *)0)) <= 0) {
541                     if (n < 0 && errno != EINTR) {
542                         syslog(LOG_WARNING, "select: %m");
543                         sleep(1);
544                     }
545                     continue;
546             }
547             /* handle any queued signal flags */
548             if (FD_ISSET(signalpipe[0], &readable)) {
549                 int nsig;
550                 if (ioctl(signalpipe[0], FIONREAD, &nsig) != 0) {
551                     syslog(LOG_ERR, "ioctl: %m");
552                     exit(EX_OSERR);
553                 }
554                 while (--nsig >= 0) {
555                     char c;
556                     if (read(signalpipe[0], &c, 1) != 1) {
557                         syslog(LOG_ERR, "read: %m");
558                         exit(EX_OSERR);
559                     }
560                     if (debug)
561                         warnx("handling signal flag %c", c);
562                     switch(c) {
563                     case 'A': /* sigalrm */
564                         retry();
565                         break;
566                     case 'C': /* sigchld */
567                         reapchild();
568                         break;
569                     case 'H': /* sighup */
570                         config();
571                         break;
572                     }
573                 }
574             }
575             for (sep = servtab; n && sep; sep = sep->se_next)
576                 if (sep->se_fd != -1 && FD_ISSET(sep->se_fd, &readable)) {
577                     n--;
578                     if (debug)
579                             warnx("someone wants %s", sep->se_service);
580                     dofork = !sep->se_bi || sep->se_bi->bi_fork || ISWRAP(sep);
581                     conn = NULL;
582                     if (sep->se_accept && sep->se_socktype == SOCK_STREAM) {
583                             i = 1;
584                             if (ioctl(sep->se_fd, FIONBIO, &i) < 0)
585                                     syslog(LOG_ERR, "ioctl (FIONBIO, 1): %m");
586                             ctrl = accept(sep->se_fd, (struct sockaddr *)0,
587                                 (socklen_t *)0);
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 (log && !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, (struct timezone *)NULL);
655                             else if (toomany > 0 && sep->se_count >= toomany) {
656                                 struct timeval now;
657
658                                 gettimeofday(&now, (struct timezone *)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, (struct sigaction *)0);
700                                 sigaction(SIGCHLD, &sachld, (struct sigaction *)0);
701                                 sigaction(SIGHUP, &sahup, (struct sigaction *)0);
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 (log) {
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,
837                                     (struct sigaction *)0);
838                                 execv(sep->se_server, sep->se_argv);
839                                 syslog(LOG_ERR,
840                                     "cannot execute %s: %m", sep->se_server);
841                                 if (sep->se_socktype != SOCK_STREAM)
842                                         recv(0, buf, sizeof (buf), 0);
843                             }
844                             if (dofork)
845                                 _exit(0);
846                     }
847                     if (sep->se_accept && sep->se_socktype == SOCK_STREAM)
848                             close(ctrl);
849                 }
850         }
851 }
852
853 /*
854  * Add a signal flag to the signal flag queue for later handling
855  */
856
857 void
858 flag_signal(int c)
859 {
860         char ch = c;
861
862         if (write(signalpipe[1], &ch, 1) != 1) {
863                 syslog(LOG_ERR, "write: %m");
864                 _exit(EX_OSERR);
865         }
866 }
867
868 /*
869  * Record a new child pid for this service. If we've reached the
870  * limit on children, then stop accepting incoming requests.
871  */
872
873 void
874 addchild(struct servtab *sep, pid_t pid)
875 {
876         if (sep->se_maxchild <= 0)
877                 return;
878 #ifdef SANITY_CHECK
879         if (sep->se_numchild >= sep->se_maxchild) {
880                 syslog(LOG_ERR, "%s: %d >= %d",
881                     __FUNCTION__, sep->se_numchild, sep->se_maxchild);
882                 exit(EX_SOFTWARE);
883         }
884 #endif
885         sep->se_pids[sep->se_numchild++] = pid;
886         if (sep->se_numchild == sep->se_maxchild)
887                 disable(sep);
888 }
889
890 /*
891  * Some child process has exited. See if it's on somebody's list.
892  */
893
894 void
895 flag_reapchild(int signo __unused)
896 {
897         flag_signal('C');
898 }
899
900 void
901 reapchild(void)
902 {
903         int k, status;
904         pid_t pid;
905         struct servtab *sep;
906
907         for (;;) {
908                 pid = wait3(&status, WNOHANG, (struct rusage *)0);
909                 if (pid <= 0)
910                         break;
911                 if (debug)
912                         warnx("%d reaped, %s %u", pid,
913                             WIFEXITED(status) ? "status" : "signal",
914                             WIFEXITED(status) ? WEXITSTATUS(status)
915                                 : WTERMSIG(status));
916                 for (sep = servtab; sep; sep = sep->se_next) {
917                         for (k = 0; k < sep->se_numchild; k++)
918                                 if (sep->se_pids[k] == pid)
919                                         break;
920                         if (k == sep->se_numchild)
921                                 continue;
922                         if (sep->se_numchild == sep->se_maxchild)
923                                 enable(sep);
924                         sep->se_pids[k] = sep->se_pids[--sep->se_numchild];
925                         if (WIFSIGNALED(status) || WEXITSTATUS(status))
926                                 syslog(LOG_WARNING,
927                                     "%s[%d]: exited, %s %u",
928                                     sep->se_server, pid,
929                                     WIFEXITED(status) ? "status" : "signal",
930                                     WIFEXITED(status) ? WEXITSTATUS(status)
931                                         : WTERMSIG(status));
932                         break;
933                 }
934                 reapchild_conn(pid);
935         }
936 }
937
938 void
939 flag_config(int signo __unused)
940 {
941         flag_signal('H');
942 }
943
944 void
945 config(void)
946 {
947         struct servtab *sep, *new, **sepp;
948         long omask;
949 #ifdef LOGIN_CAP
950         login_cap_t *lc = NULL;
951 #endif
952
953
954         if (!setconfig()) {
955                 syslog(LOG_ERR, "%s: %m", CONFIG);
956                 return;
957         }
958         for (sep = servtab; sep; sep = sep->se_next)
959                 sep->se_checked = 0;
960         while ((new = getconfigent())) {
961                 if (getpwnam(new->se_user) == NULL) {
962                         syslog(LOG_ERR,
963                                 "%s/%s: no such user '%s', service ignored",
964                                 new->se_service, new->se_proto, new->se_user);
965                         continue;
966                 }
967                 if (new->se_group && getgrnam(new->se_group) == NULL) {
968                         syslog(LOG_ERR,
969                                 "%s/%s: no such group '%s', service ignored",
970                                 new->se_service, new->se_proto, new->se_group);
971                         continue;
972                 }
973 #ifdef LOGIN_CAP
974                 if ((lc = login_getclass(new->se_class)) == NULL) {
975                         /* error syslogged by getclass */
976                         syslog(LOG_ERR,
977                                 "%s/%s: %s: login class error, service ignored",
978                                 new->se_service, new->se_proto, new->se_class);
979                         continue;
980                 }
981                 login_close(lc);
982 #endif
983                 for (sep = servtab; sep; sep = sep->se_next)
984                         if (strcmp(sep->se_service, new->se_service) == 0 &&
985                             strcmp(sep->se_proto, new->se_proto) == 0 &&
986                             sep->se_socktype == new->se_socktype &&
987                             sep->se_family == new->se_family)
988                                 break;
989                 if (sep != 0) {
990                         int i;
991
992 #define SWAP(a, b) { typeof(a) c = a; a = b; b = c; }
993                         omask = sigblock(SIGBLOCK);
994                         if (sep->se_nomapped != new->se_nomapped) {
995                                 sep->se_nomapped = new->se_nomapped;
996                                 sep->se_reset = 1;
997                         }
998                         /* copy over outstanding child pids */
999                         if (sep->se_maxchild > 0 && new->se_maxchild > 0) {
1000                                 new->se_numchild = sep->se_numchild;
1001                                 if (new->se_numchild > new->se_maxchild)
1002                                         new->se_numchild = new->se_maxchild;
1003                                 memcpy(new->se_pids, sep->se_pids,
1004                                     new->se_numchild * sizeof(*new->se_pids));
1005                         }
1006                         SWAP(sep->se_pids, new->se_pids);
1007                         sep->se_maxchild = new->se_maxchild;
1008                         sep->se_numchild = new->se_numchild;
1009                         sep->se_maxcpm = new->se_maxcpm;
1010                         resize_conn(sep, new->se_maxperip);
1011                         sep->se_maxperip = new->se_maxperip;
1012                         sep->se_bi = new->se_bi;
1013                         /* might need to turn on or off service now */
1014                         if (sep->se_fd >= 0) {
1015                               if (sep->se_maxchild > 0
1016                                   && sep->se_numchild == sep->se_maxchild) {
1017                                       if (FD_ISSET(sep->se_fd, &allsock))
1018                                           disable(sep);
1019                               } else {
1020                                       if (!FD_ISSET(sep->se_fd, &allsock))
1021                                           enable(sep);
1022                               }
1023                         }
1024                         sep->se_accept = new->se_accept;
1025                         SWAP(sep->se_user, new->se_user);
1026                         SWAP(sep->se_group, new->se_group);
1027 #ifdef LOGIN_CAP
1028                         SWAP(sep->se_class, new->se_class);
1029 #endif
1030                         SWAP(sep->se_server, new->se_server);
1031                         SWAP(sep->se_server_name, new->se_server_name);
1032                         for (i = 0; i < MAXARGV; i++)
1033                                 SWAP(sep->se_argv[i], new->se_argv[i]);
1034 #ifdef IPSEC
1035                         SWAP(sep->se_policy, new->se_policy);
1036                         ipsecsetup(sep);
1037 #endif
1038                         sigsetmask(omask);
1039                         freeconfig(new);
1040                         if (debug)
1041                                 print_service("REDO", sep);
1042                 } else {
1043                         sep = enter(new);
1044                         if (debug)
1045                                 print_service("ADD ", sep);
1046                 }
1047                 sep->se_checked = 1;
1048                 if (ISMUX(sep)) {
1049                         sep->se_fd = -1;
1050                         continue;
1051                 }
1052                 switch (sep->se_family) {
1053                 case AF_INET:
1054                         if (no_v4bind != 0) {
1055                                 sep->se_fd = -1;
1056                                 continue;
1057                         }
1058                         break;
1059 #ifdef INET6
1060                 case AF_INET6:
1061                         if (no_v6bind != 0) {
1062                                 sep->se_fd = -1;
1063                                 continue;
1064                         }
1065                         break;
1066 #endif
1067                 }
1068                 if (!sep->se_rpc) {
1069                         if (sep->se_family != AF_UNIX) {
1070                                 sp = getservbyname(sep->se_service, sep->se_proto);
1071                                 if (sp == 0) {
1072                                         syslog(LOG_ERR, "%s/%s: unknown service",
1073                                         sep->se_service, sep->se_proto);
1074                                         sep->se_checked = 0;
1075                                         continue;
1076                                 }
1077                         }
1078                         switch (sep->se_family) {
1079                         case AF_INET:
1080                                 if (sp->s_port != sep->se_ctrladdr4.sin_port) {
1081                                         sep->se_ctrladdr4.sin_port =
1082                                                 sp->s_port;
1083                                         sep->se_reset = 1;
1084                                 }
1085                                 break;
1086 #ifdef INET6
1087                         case AF_INET6:
1088                                 if (sp->s_port !=
1089                                     sep->se_ctrladdr6.sin6_port) {
1090                                         sep->se_ctrladdr6.sin6_port =
1091                                                 sp->s_port;
1092                                         sep->se_reset = 1;
1093                                 }
1094                                 break;
1095 #endif
1096                         }
1097                         if (sep->se_reset != 0 && sep->se_fd >= 0)
1098                                 close_sep(sep);
1099                 } else {
1100                         rpc = getrpcbyname(sep->se_service);
1101                         if (rpc == 0) {
1102                                 syslog(LOG_ERR, "%s/%s unknown RPC service",
1103                                         sep->se_service, sep->se_proto);
1104                                 if (sep->se_fd != -1)
1105                                         close(sep->se_fd);
1106                                 sep->se_fd = -1;
1107                                         continue;
1108                         }
1109                         if (rpc->r_number != sep->se_rpc_prog) {
1110                                 if (sep->se_rpc_prog)
1111                                         unregisterrpc(sep);
1112                                 sep->se_rpc_prog = rpc->r_number;
1113                                 if (sep->se_fd != -1)
1114                                         close(sep->se_fd);
1115                                 sep->se_fd = -1;
1116                         }
1117                 }
1118                 if (sep->se_fd == -1)
1119                         setup(sep);
1120         }
1121         endconfig();
1122         /*
1123          * Purge anything not looked at above.
1124          */
1125         omask = sigblock(SIGBLOCK);
1126         sepp = &servtab;
1127         while ((sep = *sepp)) {
1128                 if (sep->se_checked) {
1129                         sepp = &sep->se_next;
1130                         continue;
1131                 }
1132                 *sepp = sep->se_next;
1133                 if (sep->se_fd >= 0)
1134                         close_sep(sep);
1135                 if (debug)
1136                         print_service("FREE", sep);
1137                 if (sep->se_rpc && sep->se_rpc_prog > 0)
1138                         unregisterrpc(sep);
1139                 freeconfig(sep);
1140                 free(sep);
1141         }
1142         sigsetmask(omask);
1143 }
1144
1145 void
1146 unregisterrpc(struct servtab *sep)
1147 {
1148         u_int i;
1149         struct servtab *sepp;
1150         long omask;
1151
1152         omask = sigblock(SIGBLOCK);
1153         for (sepp = servtab; sepp; sepp = sepp->se_next) {
1154                 if (sepp == sep)
1155                         continue;
1156                 if (sep->se_checked == 0 ||
1157                     !sepp->se_rpc ||
1158                     sep->se_rpc_prog != sepp->se_rpc_prog)
1159                         continue;
1160                 return;
1161         }
1162         if (debug)
1163                 print_service("UNREG", sep);
1164         for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++)
1165                 pmap_unset(sep->se_rpc_prog, i);
1166         if (sep->se_fd != -1)
1167                 close(sep->se_fd);
1168         sep->se_fd = -1;
1169         sigsetmask(omask);
1170 }
1171
1172 void
1173 flag_retry(int signo __unused)
1174 {
1175         flag_signal('A');
1176 }
1177
1178 void
1179 retry(void)
1180 {
1181         struct servtab *sep;
1182
1183         timingout = 0;
1184         for (sep = servtab; sep; sep = sep->se_next)
1185                 if (sep->se_fd == -1 && !ISMUX(sep))
1186                         setup(sep);
1187 }
1188
1189 void
1190 setup(struct servtab *sep)
1191 {
1192         int on = 1;
1193
1194         if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1195                 if (debug)
1196                         warn("socket failed on %s/%s",
1197                                 sep->se_service, sep->se_proto);
1198                 syslog(LOG_ERR, "%s/%s: socket: %m",
1199                     sep->se_service, sep->se_proto);
1200                 return;
1201         }
1202         /* Set all listening sockets to close-on-exec. */
1203         if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
1204                 syslog(LOG_ERR, "%s/%s: fcntl (F_SETFD, FD_CLOEXEC): %m",
1205                     sep->se_service, sep->se_proto);
1206                 close(sep->se_fd);
1207                 return;
1208         }
1209 #define turnon(fd, opt) \
1210 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1211         if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1212             turnon(sep->se_fd, SO_DEBUG) < 0)
1213                 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1214         if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1215                 syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1216 #ifdef SO_PRIVSTATE
1217         if (turnon(sep->se_fd, SO_PRIVSTATE) < 0)
1218                 syslog(LOG_ERR, "setsockopt (SO_PRIVSTATE): %m");
1219 #endif
1220         /* tftpd opens a new connection then needs more infos */
1221         if ((sep->se_family == AF_INET6) &&
1222             (strcmp(sep->se_proto, "udp") == 0) &&
1223             (sep->se_accept == 0) &&
1224             (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_PKTINFO,
1225                         (char *)&on, sizeof (on)) < 0))
1226                 syslog(LOG_ERR, "setsockopt (IPV6_RECVPKTINFO): %m");
1227         if (sep->se_family == AF_INET6) {
1228                 int flag = sep->se_nomapped ? 1 : 0;
1229                 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_V6ONLY,
1230                                (char *)&flag, sizeof (flag)) < 0)
1231                         syslog(LOG_ERR, "setsockopt (IPV6_V6ONLY): %m");
1232         }
1233 #undef turnon
1234         if (sep->se_type == TTCP_TYPE)
1235                 if (setsockopt(sep->se_fd, IPPROTO_TCP, TCP_NOPUSH,
1236                     (char *)&on, sizeof (on)) < 0)
1237                         syslog(LOG_ERR, "setsockopt (TCP_NOPUSH): %m");
1238 #ifdef IPV6_FAITH
1239         if (sep->se_type == FAITH_TYPE) {
1240                 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_FAITH, &on,
1241                                 sizeof(on)) < 0) {
1242                         syslog(LOG_ERR, "setsockopt (IPV6_FAITH): %m");
1243                 }
1244         }
1245 #endif
1246 #ifdef IPSEC
1247         ipsecsetup(sep);
1248 #endif
1249         if (sep->se_family == AF_UNIX) {
1250                 unlink(sep->se_ctrladdr_un.sun_path);
1251                 umask(0777); /* Make socket with conservative permissions */
1252         }
1253         if (bind(sep->se_fd, (struct sockaddr *)&sep->se_ctrladdr,
1254             sep->se_ctrladdr_size) < 0) {
1255                 if (debug)
1256                         warn("bind failed on %s/%s",
1257                                 sep->se_service, sep->se_proto);
1258                 syslog(LOG_ERR, "%s/%s: bind: %m",
1259                     sep->se_service, sep->se_proto);
1260                 close(sep->se_fd);
1261                 sep->se_fd = -1;
1262                 if (!timingout) {
1263                         timingout = 1;
1264                         alarm(RETRYTIME);
1265                 }
1266                 if (sep->se_family == AF_UNIX)
1267                         umask(mask);
1268                 return;
1269         }
1270         if (sep->se_family == AF_UNIX) {
1271                 /* Ick - fch{own,mod} don't work on Unix domain sockets */
1272                 if (chown(sep->se_service, sep->se_sockuid, sep->se_sockgid) < 0)
1273                         syslog(LOG_ERR, "chown socket: %m");
1274                 if (chmod(sep->se_service, sep->se_sockmode) < 0)
1275                         syslog(LOG_ERR, "chmod socket: %m");
1276                 umask(mask);
1277         }
1278         if (sep->se_rpc) {
1279                 u_int i;
1280                 socklen_t len = sep->se_ctrladdr_size;
1281
1282                 if (sep->se_family != AF_INET) {
1283                         syslog(LOG_ERR,
1284                                "%s/%s: unsupported address family for rpc",
1285                                sep->se_service, sep->se_proto);
1286                         close(sep->se_fd);
1287                         sep->se_fd = -1;
1288                         return;
1289                 }
1290                 if (getsockname(sep->se_fd,
1291                                 (struct sockaddr*)&sep->se_ctrladdr, &len) < 0){
1292                         syslog(LOG_ERR, "%s/%s: getsockname: %m",
1293                                sep->se_service, sep->se_proto);
1294                         close(sep->se_fd);
1295                         sep->se_fd = -1;
1296                         return;
1297                 }
1298                 if (debug)
1299                         print_service("REG ", sep);
1300                 for (i = sep->se_rpc_lowvers; i <= sep->se_rpc_highvers; i++) {
1301                         pmap_unset(sep->se_rpc_prog, i);
1302                         pmap_set(sep->se_rpc_prog, i,
1303                                  (sep->se_socktype == SOCK_DGRAM)
1304                                  ? IPPROTO_UDP : IPPROTO_TCP,
1305                                  ntohs(sep->se_ctrladdr4.sin_port));
1306                 }
1307         }
1308         if (sep->se_socktype == SOCK_STREAM)
1309                 listen(sep->se_fd, 64);
1310         enable(sep);
1311         if (debug) {
1312                 warnx("registered %s on %d",
1313                         sep->se_server, sep->se_fd);
1314         }
1315 }
1316
1317 #ifdef IPSEC
1318 void
1319 ipsecsetup(struct servtab *sep)
1320 {
1321         char *buf;
1322         char *policy_in = NULL;
1323         char *policy_out = NULL;
1324         int level;
1325         int opt;
1326
1327         switch (sep->se_family) {
1328         case AF_INET:
1329                 level = IPPROTO_IP;
1330                 opt = IP_IPSEC_POLICY;
1331                 break;
1332 #ifdef INET6
1333         case AF_INET6:
1334                 level = IPPROTO_IPV6;
1335                 opt = IPV6_IPSEC_POLICY;
1336                 break;
1337 #endif
1338         default:
1339                 return;
1340         }
1341
1342         if (!sep->se_policy || sep->se_policy[0] == '\0') {
1343                 static char def_in[] = "in entrust", def_out[] = "out entrust";
1344                 policy_in = def_in;
1345                 policy_out = def_out;
1346         } else {
1347                 if (!strncmp("in", sep->se_policy, 2))
1348                         policy_in = sep->se_policy;
1349                 else if (!strncmp("out", sep->se_policy, 3))
1350                         policy_out = sep->se_policy;
1351                 else {
1352                         syslog(LOG_ERR, "invalid security policy \"%s\"",
1353                                 sep->se_policy);
1354                         return;
1355                 }
1356         }
1357
1358         if (policy_in != NULL) {
1359                 buf = ipsec_set_policy(policy_in, strlen(policy_in));
1360                 if (buf != NULL) {
1361                         if (setsockopt(sep->se_fd, level, opt,
1362                                         buf, ipsec_get_policylen(buf)) < 0 &&
1363                             debug != 0)
1364                                 warnx("%s/%s: ipsec initialization failed; %s",
1365                                       sep->se_service, sep->se_proto,
1366                                       policy_in);
1367                         free(buf);
1368                 } else
1369                         syslog(LOG_ERR, "invalid security policy \"%s\"",
1370                                 policy_in);
1371         }
1372         if (policy_out != NULL) {
1373                 buf = ipsec_set_policy(policy_out, strlen(policy_out));
1374                 if (buf != NULL) {
1375                         if (setsockopt(sep->se_fd, level, opt,
1376                                         buf, ipsec_get_policylen(buf)) < 0 &&
1377                             debug != 0)
1378                                 warnx("%s/%s: ipsec initialization failed; %s",
1379                                       sep->se_service, sep->se_proto,
1380                                       policy_out);
1381                         free(buf);
1382                 } else
1383                         syslog(LOG_ERR, "invalid security policy \"%s\"",
1384                                 policy_out);
1385         }
1386 }
1387 #endif
1388
1389 /*
1390  * Finish with a service and its socket.
1391  */
1392 void
1393 close_sep(struct servtab *sep)
1394 {
1395         if (sep->se_fd >= 0) {
1396                 if (FD_ISSET(sep->se_fd, &allsock))
1397                         disable(sep);
1398                 close(sep->se_fd);
1399                 sep->se_fd = -1;
1400         }
1401         sep->se_count = 0;
1402         sep->se_numchild = 0;   /* forget about any existing children */
1403 }
1404
1405 int
1406 matchservent(const char *name1, const char *name2, const char *proto)
1407 {
1408         char **alias, *p;
1409         struct servent *se;
1410
1411         if (strcmp(proto, "unix") == 0) {
1412                 if ((p = strrchr(name1, '/')) != NULL)
1413                         name1 = p + 1;
1414                 if ((p = strrchr(name2, '/')) != NULL)
1415                         name2 = p + 1;
1416         }
1417         if (strcmp(name1, name2) == 0)
1418                 return(1);
1419         if ((se = getservbyname(name1, proto)) != NULL) {
1420                 if (strcmp(name2, se->s_name) == 0)
1421                         return(1);
1422                 for (alias = se->s_aliases; *alias; alias++)
1423                         if (strcmp(name2, *alias) == 0)
1424                                 return(1);
1425         }
1426         return(0);
1427 }
1428
1429 struct servtab *
1430 enter(struct servtab *cp)
1431 {
1432         struct servtab *sep;
1433         long omask;
1434
1435         sep = (struct servtab *)malloc(sizeof (*sep));
1436         if (sep == (struct servtab *)0) {
1437                 syslog(LOG_ERR, "malloc: %m");
1438                 exit(EX_OSERR);
1439         }
1440         *sep = *cp;
1441         sep->se_fd = -1;
1442         omask = sigblock(SIGBLOCK);
1443         sep->se_next = servtab;
1444         servtab = sep;
1445         sigsetmask(omask);
1446         return (sep);
1447 }
1448
1449 void
1450 enable(struct servtab *sep)
1451 {
1452         if (debug)
1453                 warnx(
1454                     "enabling %s, fd %d", sep->se_service, sep->se_fd);
1455 #ifdef SANITY_CHECK
1456         if (sep->se_fd < 0) {
1457                 syslog(LOG_ERR,
1458                     "%s: %s: bad fd", __FUNCTION__, sep->se_service);
1459                 exit(EX_SOFTWARE);
1460         }
1461         if (ISMUX(sep)) {
1462                 syslog(LOG_ERR,
1463                     "%s: %s: is mux", __FUNCTION__, sep->se_service);
1464                 exit(EX_SOFTWARE);
1465         }
1466         if (FD_ISSET(sep->se_fd, &allsock)) {
1467                 syslog(LOG_ERR,
1468                     "%s: %s: not off", __FUNCTION__, sep->se_service);
1469                 exit(EX_SOFTWARE);
1470         }
1471         nsock++;
1472 #endif
1473         FD_SET(sep->se_fd, &allsock);
1474         if (sep->se_fd > maxsock)
1475                 maxsock = sep->se_fd;
1476 }
1477
1478 void
1479 disable(struct servtab *sep)
1480 {
1481         if (debug)
1482                 warnx(
1483                     "disabling %s, fd %d", sep->se_service, sep->se_fd);
1484 #ifdef SANITY_CHECK
1485         if (sep->se_fd < 0) {
1486                 syslog(LOG_ERR,
1487                     "%s: %s: bad fd", __FUNCTION__, sep->se_service);
1488                 exit(EX_SOFTWARE);
1489         }
1490         if (ISMUX(sep)) {
1491                 syslog(LOG_ERR,
1492                     "%s: %s: is mux", __FUNCTION__, sep->se_service);
1493                 exit(EX_SOFTWARE);
1494         }
1495         if (!FD_ISSET(sep->se_fd, &allsock)) {
1496                 syslog(LOG_ERR,
1497                     "%s: %s: not on", __FUNCTION__, sep->se_service);
1498                 exit(EX_SOFTWARE);
1499         }
1500         if (nsock == 0) {
1501                 syslog(LOG_ERR, "%s: nsock=0", __FUNCTION__);
1502                 exit(EX_SOFTWARE);
1503         }
1504         nsock--;
1505 #endif
1506         FD_CLR(sep->se_fd, &allsock);
1507         if (sep->se_fd == maxsock)
1508                 maxsock--;
1509 }
1510
1511 FILE    *fconfig = NULL;
1512 struct  servtab serv;
1513 char    line[LINE_MAX];
1514
1515 int
1516 setconfig(void)
1517 {
1518
1519         if (fconfig != NULL) {
1520                 fseek(fconfig, 0L, SEEK_SET);
1521                 return (1);
1522         }
1523         fconfig = fopen(CONFIG, "r");
1524         return (fconfig != NULL);
1525 }
1526
1527 void
1528 endconfig(void)
1529 {
1530         if (fconfig) {
1531                 fclose(fconfig);
1532                 fconfig = NULL;
1533         }
1534 }
1535
1536 struct servtab *
1537 getconfigent(void)
1538 {
1539         struct servtab *sep = &serv;
1540         int argc;
1541         char *cp, *arg, *s;
1542         char *versp;
1543         static char TCPMUX_TOKEN[] = "tcpmux/";
1544 #define MUX_LEN         (sizeof(TCPMUX_TOKEN)-1)
1545 #ifdef IPSEC
1546         char *policy = NULL;
1547 #endif
1548         int v4bind = 0;
1549 #ifdef INET6
1550         int v6bind = 0;
1551 #endif
1552         int i;
1553
1554 more:
1555         while ((cp = nextline(fconfig)) != NULL) {
1556 #ifdef IPSEC
1557                 /* lines starting with #@ is not a comment, but the policy */
1558                 if (cp[0] == '#' && cp[1] == '@') {
1559                         char *p;
1560                         for (p = cp + 2; p && *p && isspace(*p); p++)
1561                                 ;
1562                         if (*p == '\0') {
1563                                 if (policy)
1564                                         free(policy);
1565                                 policy = NULL;
1566                         } else if (ipsec_get_policylen(p) >= 0) {
1567                                 if (policy)
1568                                         free(policy);
1569                                 policy = newstr(p);
1570                         } else {
1571                                 syslog(LOG_ERR,
1572                                         "%s: invalid ipsec policy \"%s\"",
1573                                         CONFIG, p);
1574                                 exit(EX_CONFIG);
1575                         }
1576                 }
1577 #endif
1578                 if (*cp == '#' || *cp == '\0')
1579                         continue;
1580                 break;
1581         }
1582         if (cp == NULL)
1583                 return ((struct servtab *)0);
1584         /*
1585          * clear the static buffer, since some fields (se_ctrladdr,
1586          * for example) don't get initialized here.
1587          */
1588         memset(sep, 0, sizeof *sep);
1589         arg = skip(&cp);
1590         if (cp == NULL) {
1591                 /* got an empty line containing just blanks/tabs. */
1592                 goto more;
1593         }
1594         if (arg[0] == ':') { /* :user:group:perm: */
1595                 char *user, *group, *perm;
1596                 struct passwd *pw;
1597                 struct group *gr;
1598                 user = arg+1;
1599                 if ((group = strchr(user, ':')) == NULL) {
1600                         syslog(LOG_ERR, "no group after user '%s'", user);
1601                         goto more;
1602                 }
1603                 *group++ = '\0';
1604                 if ((perm = strchr(group, ':')) == NULL) {
1605                         syslog(LOG_ERR, "no mode after group '%s'", group);
1606                         goto more;
1607                 }
1608                 *perm++ = '\0';
1609                 if ((pw = getpwnam(user)) == NULL) {
1610                         syslog(LOG_ERR, "no such user '%s'", user);
1611                         goto more;
1612                 }
1613                 sep->se_sockuid = pw->pw_uid;
1614                 if ((gr = getgrnam(group)) == NULL) {
1615                         syslog(LOG_ERR, "no such user '%s'", group);
1616                         goto more;
1617                 }
1618                 sep->se_sockgid = gr->gr_gid;
1619                 sep->se_sockmode = strtol(perm, &arg, 8);
1620                 if (*arg != ':') {
1621                         syslog(LOG_ERR, "bad mode '%s'", perm);
1622                         goto more;
1623                 }
1624                 *arg++ = '\0';
1625         } else {
1626                 sep->se_sockuid = euid;
1627                 sep->se_sockgid = egid;
1628                 sep->se_sockmode = 0200;
1629         }
1630         if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1631                 char *c = arg + MUX_LEN;
1632                 if (*c == '+') {
1633                         sep->se_type = MUXPLUS_TYPE;
1634                         c++;
1635                 } else
1636                         sep->se_type = MUX_TYPE;
1637                 sep->se_service = newstr(c);
1638         } else {
1639                 sep->se_service = newstr(arg);
1640                 sep->se_type = NORM_TYPE;
1641         }
1642         arg = sskip(&cp);
1643         if (strcmp(arg, "stream") == 0)
1644                 sep->se_socktype = SOCK_STREAM;
1645         else if (strcmp(arg, "dgram") == 0)
1646                 sep->se_socktype = SOCK_DGRAM;
1647         else if (strcmp(arg, "rdm") == 0)
1648                 sep->se_socktype = SOCK_RDM;
1649         else if (strcmp(arg, "seqpacket") == 0)
1650                 sep->se_socktype = SOCK_SEQPACKET;
1651         else if (strcmp(arg, "raw") == 0)
1652                 sep->se_socktype = SOCK_RAW;
1653         else
1654                 sep->se_socktype = -1;
1655
1656         arg = sskip(&cp);
1657         if (strncmp(arg, "tcp", 3) == 0) {
1658                 sep->se_proto = newstr(strsep(&arg, "/"));
1659                 if (arg != NULL) {
1660                         if (strcmp(arg, "ttcp") == 0)
1661                                 sep->se_type = TTCP_TYPE;
1662                         else if (strcmp(arg, "faith") == 0)
1663                                 sep->se_type = FAITH_TYPE;
1664                 }
1665         } else {
1666                 if (sep->se_type == NORM_TYPE &&
1667                     strncmp(arg, "faith/", 6) == 0) {
1668                         arg += 6;
1669                         sep->se_type = FAITH_TYPE;
1670                 }
1671                 sep->se_proto = newstr(arg);
1672         }
1673         if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1674                 if (no_v4bind != 0) {
1675                         syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1676                                sep->se_service);
1677                         freeconfig(sep);
1678                         goto more;
1679                 }
1680                 memmove(sep->se_proto, sep->se_proto + 4,
1681                     strlen(sep->se_proto) + 1 - 4);
1682                 sep->se_rpc = 1;
1683                 sep->se_rpc_prog = sep->se_rpc_lowvers =
1684                         sep->se_rpc_lowvers = 0;
1685                 memcpy(&sep->se_ctrladdr4, bind_sa4,
1686                        sizeof(sep->se_ctrladdr4));
1687                 if ((versp = strrchr(sep->se_service, '/'))) {
1688                         *versp++ = '\0';
1689                         switch (sscanf(versp, "%u-%u",
1690                                        &sep->se_rpc_lowvers,
1691                                        &sep->se_rpc_highvers)) {
1692                         case 2:
1693                                 break;
1694                         case 1:
1695                                 sep->se_rpc_highvers =
1696                                         sep->se_rpc_lowvers;
1697                                 break;
1698                         default:
1699                                 syslog(LOG_ERR,
1700                                         "bad RPC version specifier; %s",
1701                                         sep->se_service);
1702                                 freeconfig(sep);
1703                                 goto more;
1704                         }
1705                 }
1706                 else {
1707                         sep->se_rpc_lowvers =
1708                                 sep->se_rpc_highvers = 1;
1709                 }
1710         }
1711         sep->se_nomapped = 0;
1712         while (isdigit(sep->se_proto[strlen(sep->se_proto) - 1])) {
1713 #ifdef INET6
1714                 if (sep->se_proto[strlen(sep->se_proto) - 1] == '6') {
1715                         if (no_v6bind != 0) {
1716                                 syslog(LOG_NOTICE, "IPv6 bind is ignored for %s",
1717                                        sep->se_service);
1718                                 freeconfig(sep);
1719                                 goto more;
1720                         }
1721                         sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1722                         v6bind = 1;
1723                         continue;
1724                 }
1725 #endif
1726                 if (sep->se_proto[strlen(sep->se_proto) - 1] == '4') {
1727                         sep->se_proto[strlen(sep->se_proto) - 1] = '\0';
1728                         v4bind = 1;
1729                         continue;
1730                 }
1731                 /* illegal version num */
1732                 syslog(LOG_ERR, "bad IP version for %s", sep->se_proto);
1733                 freeconfig(sep);
1734                 goto more;
1735         }
1736         if (strcmp(sep->se_proto, "unix") == 0) {
1737                 sep->se_family = AF_UNIX;
1738         } else
1739 #ifdef INET6
1740         if (v6bind != 0) {
1741                 sep->se_family = AF_INET6;
1742                 if (v4bind == 0 || no_v4bind != 0)
1743                         sep->se_nomapped = 1;
1744         } else
1745 #endif
1746         { /* default to v4 bind if not v6 bind */
1747                 if (no_v4bind != 0) {
1748                         syslog(LOG_NOTICE, "IPv4 bind is ignored for %s",
1749                                sep->se_service);
1750                         freeconfig(sep);
1751                         goto more;
1752                 }
1753                 sep->se_family = AF_INET;
1754         }
1755         /* init ctladdr */
1756         switch(sep->se_family) {
1757         case AF_INET:
1758                 memcpy(&sep->se_ctrladdr4, bind_sa4,
1759                        sizeof(sep->se_ctrladdr4));
1760                 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr4);
1761                 break;
1762 #ifdef INET6
1763         case AF_INET6:
1764                 memcpy(&sep->se_ctrladdr6, bind_sa6,
1765                        sizeof(sep->se_ctrladdr6));
1766                 sep->se_ctrladdr_size = sizeof(sep->se_ctrladdr6);
1767                 break;
1768 #endif
1769         case AF_UNIX:
1770                 if (strlen(sep->se_service) >= sizeof(sep->se_ctrladdr_un.sun_path)) {
1771                         syslog(LOG_ERR, 
1772                             "domain socket pathname too long for service %s",
1773                             sep->se_service);
1774                         goto more;
1775                 }
1776                 memset(&sep->se_ctrladdr, 0, sizeof(sep->se_ctrladdr));
1777                 sep->se_ctrladdr_un.sun_family = sep->se_family;
1778                 sep->se_ctrladdr_un.sun_len = strlen(sep->se_service);
1779                 strcpy(sep->se_ctrladdr_un.sun_path, sep->se_service);
1780                 sep->se_ctrladdr_size = SUN_LEN(&sep->se_ctrladdr_un);
1781         }
1782         arg = sskip(&cp);
1783         if (!strncmp(arg, "wait", 4))
1784                 sep->se_accept = 0;
1785         else if (!strncmp(arg, "nowait", 6))
1786                 sep->se_accept = 1;
1787         else {
1788                 syslog(LOG_ERR,
1789                         "%s: bad wait/nowait for service %s",
1790                         CONFIG, sep->se_service);
1791                 goto more;
1792         }
1793         sep->se_maxchild = -1;
1794         sep->se_maxcpm = -1;
1795         sep->se_maxperip = -1;
1796         if ((s = strchr(arg, '/')) != NULL) {
1797                 char *eptr;
1798                 u_long val;
1799
1800                 val = strtoul(s + 1, &eptr, 10);
1801                 if (eptr == s + 1 || val > MAX_MAXCHLD) {
1802                         syslog(LOG_ERR,
1803                                 "%s: bad max-child for service %s",
1804                                 CONFIG, sep->se_service);
1805                         goto more;
1806                 }
1807                 if (debug)
1808                         if (!sep->se_accept && val != 1)
1809                                 warnx("maxchild=%lu for wait service %s"
1810                                     " not recommended", val, sep->se_service);
1811                 sep->se_maxchild = val;
1812                 if (*eptr == '/')
1813                         sep->se_maxcpm = strtol(eptr + 1, &eptr, 10);
1814                 if (*eptr == '/')
1815                         sep->se_maxperip = strtol(eptr + 1, &eptr, 10);
1816                 /*
1817                  * explicitly do not check for \0 for future expansion /
1818                  * backwards compatibility
1819                  */
1820         }
1821         if (ISMUX(sep)) {
1822                 /*
1823                  * Silently enforce "nowait" mode for TCPMUX services
1824                  * since they don't have an assigned port to listen on.
1825                  */
1826                 sep->se_accept = 1;
1827                 if (strcmp(sep->se_proto, "tcp")) {
1828                         syslog(LOG_ERR,
1829                                 "%s: bad protocol for tcpmux service %s",
1830                                 CONFIG, sep->se_service);
1831                         goto more;
1832                 }
1833                 if (sep->se_socktype != SOCK_STREAM) {
1834                         syslog(LOG_ERR,
1835                                 "%s: bad socket type for tcpmux service %s",
1836                                 CONFIG, sep->se_service);
1837                         goto more;
1838                 }
1839         }
1840         sep->se_user = newstr(sskip(&cp));
1841 #ifdef LOGIN_CAP
1842         if ((s = strrchr(sep->se_user, '/')) != NULL) {
1843                 *s = '\0';
1844                 sep->se_class = newstr(s + 1);
1845         } else
1846                 sep->se_class = newstr(RESOURCE_RC);
1847 #endif
1848         if ((s = strrchr(sep->se_user, ':')) != NULL) {
1849                 *s = '\0';
1850                 sep->se_group = newstr(s + 1);
1851         } else
1852                 sep->se_group = NULL;
1853         sep->se_server = newstr(sskip(&cp));
1854         if ((sep->se_server_name = strrchr(sep->se_server, '/')))
1855                 sep->se_server_name++;
1856         if (strcmp(sep->se_server, "internal") == 0) {
1857                 struct biltin *bi;
1858
1859                 for (bi = biltins; bi->bi_service; bi++)
1860                         if (bi->bi_socktype == sep->se_socktype &&
1861                             matchservent(bi->bi_service, sep->se_service,
1862                             sep->se_proto))
1863                                 break;
1864                 if (bi->bi_service == 0) {
1865                         syslog(LOG_ERR, "internal service %s unknown",
1866                                 sep->se_service);
1867                         goto more;
1868                 }
1869                 sep->se_accept = 1;     /* force accept mode for built-ins */
1870                 sep->se_bi = bi;
1871         } else
1872                 sep->se_bi = NULL;
1873         if (sep->se_maxperip < 0)
1874                 sep->se_maxperip = maxperip;
1875         if (sep->se_maxcpm < 0)
1876                 sep->se_maxcpm = maxcpm;
1877         if (sep->se_maxchild < 0) {     /* apply default max-children */
1878                 if (sep->se_bi && sep->se_bi->bi_maxchild >= 0)
1879                         sep->se_maxchild = sep->se_bi->bi_maxchild;
1880                 else if (sep->se_accept) 
1881                         sep->se_maxchild = maxchild > 0 ? maxchild : 0;
1882                 else
1883                         sep->se_maxchild = 1;
1884         }
1885         if (sep->se_maxchild > 0) {
1886                 sep->se_pids = malloc(sep->se_maxchild * sizeof(*sep->se_pids));
1887                 if (sep->se_pids == NULL) {
1888                         syslog(LOG_ERR, "malloc: %m");
1889                         exit(EX_OSERR);
1890                 }
1891         }
1892         argc = 0;
1893         for (arg = skip(&cp); cp; arg = skip(&cp))
1894                 if (argc < MAXARGV) {
1895                         sep->se_argv[argc++] = newstr(arg);
1896                 } else {
1897                         syslog(LOG_ERR,
1898                                 "%s: too many arguments for service %s",
1899                                 CONFIG, sep->se_service);
1900                         goto more;
1901                 }
1902         while (argc <= MAXARGV)
1903                 sep->se_argv[argc++] = NULL;
1904         for (i = 0; i < PERIPSIZE; ++i)
1905                 LIST_INIT(&sep->se_conn[i]);
1906 #ifdef IPSEC
1907         sep->se_policy = policy ? newstr(policy) : NULL;
1908 #endif
1909         return (sep);
1910 }
1911
1912 void
1913 freeconfig(struct servtab *cp)
1914 {
1915         int i;
1916
1917         if (cp->se_service)
1918                 free(cp->se_service);
1919         if (cp->se_proto)
1920                 free(cp->se_proto);
1921         if (cp->se_user)
1922                 free(cp->se_user);
1923         if (cp->se_group)
1924                 free(cp->se_group);
1925 #ifdef LOGIN_CAP
1926         if (cp->se_class)
1927                 free(cp->se_class);
1928 #endif
1929         if (cp->se_server)
1930                 free(cp->se_server);
1931         if (cp->se_pids)
1932                 free(cp->se_pids);
1933         for (i = 0; i < MAXARGV; i++)
1934                 if (cp->se_argv[i])
1935                         free(cp->se_argv[i]);
1936         free_connlist(cp);
1937 #ifdef IPSEC
1938         if (cp->se_policy)
1939                 free(cp->se_policy);
1940 #endif
1941 }
1942
1943
1944 /*
1945  * Safe skip - if skip returns null, log a syntax error in the
1946  * configuration file and exit.
1947  */
1948 char *
1949 sskip(char **cpp)
1950 {
1951         char *cp;
1952
1953         cp = skip(cpp);
1954         if (cp == NULL) {
1955                 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1956                 exit(EX_DATAERR);
1957         }
1958         return (cp);
1959 }
1960
1961 char *
1962 skip(char **cpp)
1963 {
1964         char *cp = *cpp;
1965         char *start;
1966         char quote = '\0';
1967
1968 again:
1969         while (*cp == ' ' || *cp == '\t')
1970                 cp++;
1971         if (*cp == '\0') {
1972                 int c;
1973
1974                 c = getc(fconfig);
1975                 ungetc(c, fconfig);
1976                 if (c == ' ' || c == '\t')
1977                         if ((cp = nextline(fconfig)))
1978                                 goto again;
1979                 *cpp = (char *)0;
1980                 return ((char *)0);
1981         }
1982         if (*cp == '"' || *cp == '\'')
1983                 quote = *cp++;
1984         start = cp;
1985         if (quote)
1986                 while (*cp && *cp != quote)
1987                         cp++;
1988         else
1989                 while (*cp && *cp != ' ' && *cp != '\t')
1990                         cp++;
1991         if (*cp != '\0')
1992                 *cp++ = '\0';
1993         *cpp = cp;
1994         return (start);
1995 }
1996
1997 char *
1998 nextline(FILE *fd)
1999 {
2000         char *cp;
2001
2002         if (fgets(line, sizeof (line), fd) == NULL)
2003                 return ((char *)0);
2004         cp = strchr(line, '\n');
2005         if (cp)
2006                 *cp = '\0';
2007         return (line);
2008 }
2009
2010 char *
2011 newstr(const char *cp)
2012 {
2013         char *cr;
2014
2015         if ((cr = strdup(cp != NULL ? cp : "")))
2016                 return (cr);
2017         syslog(LOG_ERR, "strdup: %m");
2018         exit(EX_OSERR);
2019 }
2020
2021 void
2022 inetd_setproctitle(const char *a, int s)
2023 {
2024         socklen_t size;
2025         struct sockaddr_storage ss;
2026         char buf[80], pbuf[INET6_ADDRSTRLEN];
2027
2028         size = sizeof(ss);
2029         if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
2030                 getnameinfo((struct sockaddr *)&ss, size, pbuf, sizeof(pbuf),
2031                             NULL, 0, NI_NUMERICHOST|NI_WITHSCOPEID);
2032                 sprintf(buf, "%s [%s]", a, pbuf);
2033         } else
2034                 sprintf(buf, "%s", a);
2035         setproctitle("%s", buf);
2036 }
2037
2038 int
2039 check_loop(const struct sockaddr *sa, const struct servtab *sep)
2040 {
2041         struct servtab *se2;
2042         char pname[INET6_ADDRSTRLEN];
2043
2044         for (se2 = servtab; se2; se2 = se2->se_next) {
2045                 if (!se2->se_bi || se2->se_socktype != SOCK_DGRAM)
2046                         continue;
2047
2048                 switch (se2->se_family) {
2049                 case AF_INET:
2050                         if (((const struct sockaddr_in *)sa)->sin_port ==
2051                             se2->se_ctrladdr4.sin_port)
2052                                 goto isloop;
2053                         continue;
2054 #ifdef INET6
2055                 case AF_INET6:
2056                         if (((const struct sockaddr_in *)sa)->sin_port ==
2057                             se2->se_ctrladdr4.sin_port)
2058                                 goto isloop;
2059                         continue;
2060 #endif
2061                 default:
2062                         continue;
2063                 }
2064         isloop:
2065                 getnameinfo(sa, sa->sa_len, pname, sizeof(pname), NULL, 0,
2066                             NI_NUMERICHOST|NI_WITHSCOPEID);
2067                 syslog(LOG_WARNING, "%s/%s:%s/%s loop request REFUSED from %s",
2068                        sep->se_service, sep->se_proto,
2069                        se2->se_service, se2->se_proto,
2070                        pname);
2071                 return 1;
2072         }
2073         return 0;
2074 }
2075
2076 /*
2077  * print_service:
2078  *      Dump relevant information to stderr
2079  */
2080 void
2081 print_service(const char *action, const struct servtab *sep)
2082 {
2083         fprintf(stderr,
2084             "%s: %s proto=%s accept=%d max=%d user=%s group=%s"
2085 #ifdef LOGIN_CAP
2086             "class=%s"
2087 #endif
2088             " builtin=%p server=%s"
2089 #ifdef IPSEC
2090             " policy=\"%s\""
2091 #endif
2092             "\n",
2093             action, sep->se_service, sep->se_proto,
2094             sep->se_accept, sep->se_maxchild, sep->se_user, sep->se_group,
2095 #ifdef LOGIN_CAP
2096             sep->se_class,
2097 #endif
2098             (void *) sep->se_bi, sep->se_server
2099 #ifdef IPSEC
2100             , (sep->se_policy ? sep->se_policy : "")
2101 #endif
2102             );
2103 }
2104
2105 #define CPMHSIZE        256
2106 #define CPMHMASK        (CPMHSIZE-1)
2107 #define CHTGRAN         10
2108 #define CHTSIZE         6
2109
2110 typedef struct CTime {
2111         unsigned long   ct_Ticks;
2112         int             ct_Count;
2113 } CTime;
2114
2115 typedef struct CHash {
2116         union {
2117                 struct in_addr  c4_Addr;
2118                 struct in6_addr c6_Addr;
2119         } cu_Addr;
2120 #define ch_Addr4        cu_Addr.c4_Addr
2121 #define ch_Addr6        cu_Addr.c6_Addr
2122         int             ch_Family;
2123         time_t          ch_LTime;
2124         char            *ch_Service;
2125         CTime           ch_Times[CHTSIZE];
2126 } CHash;
2127
2128 CHash   CHashAry[CPMHSIZE];
2129
2130 int
2131 cpmip(const struct servtab *sep, int ctrl)
2132 {
2133         struct sockaddr_storage rss;
2134         socklen_t rssLen = sizeof(rss);
2135         int r = 0;
2136
2137         /*
2138          * If getpeername() fails, just let it through (if logging is
2139          * enabled the condition is caught elsewhere)
2140          */
2141
2142         if (sep->se_maxcpm > 0 && 
2143             getpeername(ctrl, (struct sockaddr *)&rss, &rssLen) == 0 ) {
2144                 time_t t = time(NULL);
2145                 int hv = 0xABC3D20F;
2146                 int i;
2147                 int cnt = 0;
2148                 CHash *chBest = NULL;
2149                 unsigned int ticks = t / CHTGRAN;
2150                 struct sockaddr_in *sin4;
2151 #ifdef INET6
2152                 struct sockaddr_in6 *sin6;
2153 #endif
2154
2155                 sin4 = (struct sockaddr_in *)&rss;
2156 #ifdef INET6
2157                 sin6 = (struct sockaddr_in6 *)&rss;
2158 #endif
2159                 {
2160                         char *p;
2161                         int addrlen;
2162
2163                         switch (rss.ss_family) {
2164                         case AF_INET:
2165                                 p = (char *)&sin4->sin_addr;
2166                                 addrlen = sizeof(struct in_addr);
2167                                 break;
2168 #ifdef INET6
2169                         case AF_INET6:
2170                                 p = (char *)&sin6->sin6_addr;
2171                                 addrlen = sizeof(struct in6_addr);
2172                                 break;
2173 #endif
2174                         default:
2175                                 /* should not happen */
2176                                 return -1;
2177                         }
2178
2179                         for (i = 0; i < addrlen; ++i, ++p) {
2180                                 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2181                         }
2182                         hv = (hv ^ (hv >> 16));
2183                 }
2184                 for (i = 0; i < 5; ++i) {
2185                         CHash *ch = &CHashAry[(hv + i) & CPMHMASK];
2186
2187                         if (rss.ss_family == AF_INET &&
2188                             ch->ch_Family == AF_INET &&
2189                             sin4->sin_addr.s_addr == ch->ch_Addr4.s_addr &&
2190                             ch->ch_Service && strcmp(sep->se_service,
2191                             ch->ch_Service) == 0) {
2192                                 chBest = ch;
2193                                 break;
2194                         }
2195 #ifdef INET6
2196                         if (rss.ss_family == AF_INET6 &&
2197                             ch->ch_Family == AF_INET6 &&
2198                             IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2199                                                &ch->ch_Addr6) != 0 &&
2200                             ch->ch_Service && strcmp(sep->se_service,
2201                             ch->ch_Service) == 0) {
2202                                 chBest = ch;
2203                                 break;
2204                         }
2205 #endif
2206                         if (chBest == NULL || ch->ch_LTime == 0 || 
2207                             ch->ch_LTime < chBest->ch_LTime) {
2208                                 chBest = ch;
2209                         }
2210                 }
2211                 if ((rss.ss_family == AF_INET &&
2212                      (chBest->ch_Family != AF_INET ||
2213                       sin4->sin_addr.s_addr != chBest->ch_Addr4.s_addr)) ||
2214                     chBest->ch_Service == NULL ||
2215                     strcmp(sep->se_service, chBest->ch_Service) != 0) {
2216                         chBest->ch_Family = sin4->sin_family;
2217                         chBest->ch_Addr4 = sin4->sin_addr;
2218                         if (chBest->ch_Service)
2219                                 free(chBest->ch_Service);
2220                         chBest->ch_Service = strdup(sep->se_service);
2221                         bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2222                 } 
2223 #ifdef INET6
2224                 if ((rss.ss_family == AF_INET6 &&
2225                      (chBest->ch_Family != AF_INET6 ||
2226                       IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2227                                          &chBest->ch_Addr6) == 0)) ||
2228                     chBest->ch_Service == NULL ||
2229                     strcmp(sep->se_service, chBest->ch_Service) != 0) {
2230                         chBest->ch_Family = sin6->sin6_family;
2231                         chBest->ch_Addr6 = sin6->sin6_addr;
2232                         if (chBest->ch_Service)
2233                                 free(chBest->ch_Service);
2234                         chBest->ch_Service = strdup(sep->se_service);
2235                         bzero(chBest->ch_Times, sizeof(chBest->ch_Times));
2236                 }
2237 #endif
2238                 chBest->ch_LTime = t;
2239                 {
2240                         CTime *ct = &chBest->ch_Times[ticks % CHTSIZE];
2241                         if (ct->ct_Ticks != ticks) {
2242                                 ct->ct_Ticks = ticks;
2243                                 ct->ct_Count = 0;
2244                         }
2245                         ++ct->ct_Count;
2246                 }
2247                 for (i = 0; i < CHTSIZE; ++i) {
2248                         CTime *ct = &chBest->ch_Times[i];
2249                         if (ct->ct_Ticks <= ticks &&
2250                             ct->ct_Ticks >= ticks - CHTSIZE) {
2251                                 cnt += ct->ct_Count;
2252                         }
2253                 }
2254                 if (cnt * (CHTSIZE * CHTGRAN) / 60 > sep->se_maxcpm) {
2255                         char pname[INET6_ADDRSTRLEN];
2256
2257                         getnameinfo((struct sockaddr *)&rss,
2258                                     ((struct sockaddr *)&rss)->sa_len,
2259                                     pname, sizeof(pname), NULL, 0,
2260                                     NI_NUMERICHOST|NI_WITHSCOPEID);
2261                         r = -1;
2262                         syslog(LOG_ERR,
2263                             "%s from %s exceeded counts/min (limit %d/min)",
2264                             sep->se_service, pname,
2265                             sep->se_maxcpm);
2266                 }
2267         }
2268         return(r);
2269 }
2270
2271 static struct conninfo *
2272 search_conn(struct servtab *sep, int ctrl)
2273 {
2274         struct sockaddr_storage ss;
2275         socklen_t sslen = sizeof(ss);
2276         struct conninfo *conn;
2277         int hv;
2278         char pname[NI_MAXHOST],  pname2[NI_MAXHOST];
2279
2280         if (sep->se_maxperip <= 0)
2281                 return NULL;
2282
2283         /*
2284          * If getpeername() fails, just let it through (if logging is
2285          * enabled the condition is caught elsewhere)
2286          */
2287         if (getpeername(ctrl, (struct sockaddr *)&ss, &sslen) != 0)
2288                 return NULL;
2289
2290         switch (ss.ss_family) {
2291         case AF_INET:
2292                 hv = hashval((char *)&((struct sockaddr_in *)&ss)->sin_addr,
2293                     sizeof(struct in_addr));
2294                 break;
2295 #ifdef INET6
2296         case AF_INET6:
2297                 hv = hashval((char *)&((struct sockaddr_in6 *)&ss)->sin6_addr,
2298                     sizeof(struct in6_addr));
2299                 break;
2300 #endif
2301         default:
2302                 /*
2303                  * Since we only support AF_INET and AF_INET6, just
2304                  * let other than AF_INET and AF_INET6 through.
2305                  */
2306                 return NULL;
2307         }
2308
2309         if (getnameinfo((struct sockaddr *)&ss, sslen, pname, sizeof(pname),
2310             NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID) != 0)
2311                 return NULL;
2312
2313         LIST_FOREACH(conn, &sep->se_conn[hv], co_link) {
2314                 if (getnameinfo((struct sockaddr *)&conn->co_addr,
2315                     conn->co_addr.ss_len, pname2, sizeof(pname2), NULL, 0,
2316                     NI_NUMERICHOST | NI_WITHSCOPEID) == 0 &&
2317                     strcmp(pname, pname2) == 0)
2318                         break;
2319         }
2320
2321         if (conn == NULL) {
2322                 if ((conn = malloc(sizeof(struct conninfo))) == NULL) {
2323                         syslog(LOG_ERR, "malloc: %m");
2324                         exit(EX_OSERR);
2325                 }
2326                 conn->co_proc = malloc(sep->se_maxperip * sizeof(*conn->co_proc));
2327                 if (conn->co_proc == NULL) {
2328                         syslog(LOG_ERR, "malloc: %m");
2329                         exit(EX_OSERR);
2330                 }
2331                 memcpy(&conn->co_addr, (struct sockaddr *)&ss, sslen);
2332                 conn->co_numchild = 0;
2333                 LIST_INSERT_HEAD(&sep->se_conn[hv], conn, co_link);
2334         }
2335
2336         /*
2337          * Since a child process is not invoked yet, we cannot
2338          * determine a pid of a child.  So, co_proc and co_numchild
2339          * should be filled leter.
2340          */
2341
2342         return conn;
2343 }
2344
2345 static int
2346 room_conn(struct servtab *sep, struct conninfo *conn)
2347 {
2348         char pname[NI_MAXHOST];
2349
2350         if (conn->co_numchild >= sep->se_maxperip) {
2351                 getnameinfo((struct sockaddr *)&conn->co_addr,
2352                     conn->co_addr.ss_len, pname, sizeof(pname), NULL, 0,
2353                     NI_NUMERICHOST | NI_WITHSCOPEID);
2354                 syslog(LOG_ERR, "%s from %s exceeded counts (limit %d)",
2355                     sep->se_service, pname, sep->se_maxperip);
2356                 return 0;
2357         }
2358         return 1;
2359 }
2360
2361 static void
2362 addchild_conn(struct conninfo *conn, pid_t pid)
2363 {
2364         struct procinfo *proc;
2365
2366         if (conn == NULL)
2367                 return;
2368
2369         if ((proc = search_proc(pid, 1)) != NULL) {
2370                 if (proc->pr_conn != NULL) {
2371                         syslog(LOG_ERR,
2372                             "addchild_conn: child already on process list");
2373                         exit(EX_OSERR);
2374                 }
2375                 proc->pr_conn = conn;
2376         }
2377
2378         conn->co_proc[conn->co_numchild++] = proc;
2379 }
2380
2381 static void
2382 reapchild_conn(pid_t pid)
2383 {
2384         struct procinfo *proc;
2385         struct conninfo *conn;
2386         int i;
2387
2388         if ((proc = search_proc(pid, 0)) == NULL)
2389                 return;
2390         if ((conn = proc->pr_conn) == NULL)
2391                 return;
2392         for (i = 0; i < conn->co_numchild; ++i)
2393                 if (conn->co_proc[i] == proc) {
2394                         conn->co_proc[i] = conn->co_proc[--conn->co_numchild];
2395                         break;
2396                 }
2397         free_proc(proc);
2398         free_conn(conn);
2399 }
2400
2401 static void
2402 resize_conn(struct servtab *sep, int maxpip)
2403 {
2404         struct conninfo *conn;
2405         int i, j;
2406
2407         if (sep->se_maxperip <= 0)
2408                 return;
2409         if (maxpip <= 0) {
2410                 free_connlist(sep);
2411                 return;
2412         }
2413         for (i = 0; i < PERIPSIZE; ++i) {
2414                 LIST_FOREACH(conn, &sep->se_conn[i], co_link) {
2415                         for (j = maxpip; j < conn->co_numchild; ++j)
2416                                 free_proc(conn->co_proc[j]);
2417                         conn->co_proc = realloc(conn->co_proc,
2418                             maxpip * sizeof(*conn->co_proc));
2419                         if (conn->co_proc == NULL) {
2420                                 syslog(LOG_ERR, "realloc: %m");
2421                                 exit(EX_OSERR);
2422                         }
2423                         if (conn->co_numchild > maxpip)
2424                                 conn->co_numchild = maxpip;
2425                 }
2426         }
2427 }
2428
2429 static void
2430 free_connlist(struct servtab *sep)
2431 {
2432         struct conninfo *conn;
2433         int i, j;
2434
2435         for (i = 0; i < PERIPSIZE; ++i) {
2436                 while ((conn = LIST_FIRST(&sep->se_conn[i])) != NULL) {
2437                         for (j = 0; j < conn->co_numchild; ++j)
2438                                 free_proc(conn->co_proc[j]);
2439                         conn->co_numchild = 0;
2440                         free_conn(conn);
2441                 }
2442         }
2443 }
2444
2445 static void
2446 free_conn(struct conninfo *conn)
2447 {
2448         if (conn == NULL)
2449                 return;
2450         if (conn->co_numchild <= 0) {
2451                 LIST_REMOVE(conn, co_link);
2452                 free(conn->co_proc);
2453                 free(conn);
2454         }
2455 }
2456
2457 static struct procinfo *
2458 search_proc(pid_t pid, int add)
2459 {
2460         struct procinfo *proc;
2461         int hv;
2462
2463         hv = hashval((char *)&pid, sizeof(pid));
2464         LIST_FOREACH(proc, &proctable[hv], pr_link) {
2465                 if (proc->pr_pid == pid)
2466                         break;
2467         }
2468         if (proc == NULL && add) {
2469                 if ((proc = malloc(sizeof(struct procinfo))) == NULL) {
2470                         syslog(LOG_ERR, "malloc: %m");
2471                         exit(EX_OSERR);
2472                 }
2473                 proc->pr_pid = pid;
2474                 proc->pr_conn = NULL;
2475                 LIST_INSERT_HEAD(&proctable[hv], proc, pr_link);
2476         }
2477         return proc;
2478 }
2479
2480 static void
2481 free_proc(struct procinfo *proc)
2482 {
2483         if (proc == NULL)
2484                 return;
2485         LIST_REMOVE(proc, pr_link);
2486         free(proc);
2487 }
2488
2489 static int
2490 hashval(char *p, int len)
2491 {
2492         int i, hv = 0xABC3D20F;
2493
2494         for (i = 0; i < len; ++i, ++p)
2495                 hv = (hv << 5) ^ (hv >> 23) ^ *p;
2496         hv = (hv ^ (hv >> 16)) & (PERIPSIZE - 1);
2497         return hv;
2498 }