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