9947f01aeab7fb38df001ed4432539caa0f906b4
[oweals/busybox.git] / networking / inetd.c
1 /* vi: set sw=4 ts=4: */
2 /*      $Slackware: inetd.c 1.79s 2001/02/06 13:18:00 volkerdi Exp $    */
3 /*      $OpenBSD: inetd.c,v 1.79 2001/01/30 08:30:57 deraadt Exp $      */
4 /*      $NetBSD: inetd.c,v 1.11 1996/02/22 11:14:41 mycroft Exp $       */
5 /* Busybox port by Vladimir Oleynik (C) 2001-2005 <dzo@simtreas.ru>     */
6 /*
7  * Copyright (c) 1983,1991 The Regents of the University of California.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38
39 /*
40  * Inetd - Internet super-server
41  *
42  * This program invokes all internet services as needed.
43  * connection-oriented services are invoked each time a
44  * connection is made, by creating a process.  This process
45  * is passed the connection as file descriptor 0 and is
46  * expected to do a getpeername to find out the source host
47  * and port.
48  *
49  * Datagram oriented services are invoked when a datagram
50  * arrives; a process is created and passed a pending message
51  * on file descriptor 0.  Datagram servers may either connect
52  * to their peer, freeing up the original socket for inetd
53  * to receive further messages on, or ``take over the socket'',
54  * processing all arriving datagrams and, eventually, timing
55  * out.  The first type of server is said to be ``multi-threaded'';
56  * the second type of server ``single-threaded''.
57  *
58  * Inetd uses a configuration file which is read at startup
59  * and, possibly, at some later time in response to a hangup signal.
60  * The configuration file is ``free format'' with fields given in the
61  * order shown below.  Continuation lines for an entry must begin with
62  * a space or tab.  All fields must be present in each entry.
63  *
64  *      service name                    must be in /etc/services
65  *      socket type                     stream/dgram/raw/rdm/seqpacket
66  *      protocol                        must be in /etc/protocols
67  *      wait/nowait[.max]               single-threaded/multi-threaded, max #
68  *      user[.group] or user[:group]    user/group to run daemon as
69  *      server program                  full path name
70  *      server program arguments        maximum of MAXARGS (20)
71  *
72  * For RPC services
73  *      service name/version            must be in /etc/rpc
74  *      socket type                     stream/dgram/raw/rdm/seqpacket
75  *      protocol                        must be in /etc/protocols
76  *      wait/nowait[.max]               single-threaded/multi-threaded
77  *      user[.group] or user[:group]    user to run daemon as
78  *      server program                  full path name
79  *      server program arguments        maximum of MAXARGS (20)
80  *
81  * For non-RPC services, the "service name" can be of the form
82  * hostaddress:servicename, in which case the hostaddress is used
83  * as the host portion of the address to listen on.  If hostaddress
84  * consists of a single `*' character, INADDR_ANY is used.
85  *
86  * A line can also consist of just
87  *      hostaddress:
88  * where hostaddress is as in the preceding paragraph.  Such a line must
89  * have no further fields; the specified hostaddress is remembered and
90  * used for all further lines that have no hostaddress specified,
91  * until the next such line (or EOF).  (This is why * is provided to
92  * allow explicit specification of INADDR_ANY.)  A line
93  *      *:
94  * is implicitly in effect at the beginning of the file.
95  *
96  * The hostaddress specifier may (and often will) contain dots;
97  * the service name must not.
98  *
99  * For RPC services, host-address specifiers are accepted and will
100  * work to some extent; however, because of limitations in the
101  * portmapper interface, it will not work to try to give more than
102  * one line for any given RPC service, even if the host-address
103  * specifiers are different.
104  *
105  * Comment lines are indicated by a `#' in column 1.
106  */
107
108 /*
109  * Here's the scoop concerning the user[.:]group feature:
110  *
111  * 1) set-group-option off.
112  *
113  *      a) user = root: NO setuid() or setgid() is done
114  *
115  *      b) other:       setgid(primary group as found in passwd)
116  *                      initgroups(name, primary group)
117  *                      setuid()
118  *
119  * 2) set-group-option on.
120  *
121  *      a) user = root: setgid(specified group)
122  *                      NO initgroups()
123  *                      NO setuid()
124  *
125  *      b) other:       setgid(specified group)
126  *                      initgroups(name, specified group)
127  *                      setuid()
128  *
129  */
130
131 #include "busybox.h"
132 #include <syslog.h>
133 #include <sys/un.h>
134
135 //#define CONFIG_FEATURE_INETD_RPC
136 //#define CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
137 //#define CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
138 //#define CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME
139 //#define CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
140 //#define CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
141 //#define CONFIG_FEATURE_IPV6
142
143 #ifdef CONFIG_FEATURE_INETD_RPC
144 #include <rpc/rpc.h>
145 #include <rpc/pmap_clnt.h>
146 #endif
147
148 #define _PATH_INETDCONF "/etc/inetd.conf"
149 #define _PATH_INETDPID  "/var/run/inetd.pid"
150
151
152 #define TOOMANY         0               /* don't start more than TOOMANY */
153
154 #define CNT_INTVL       60              /* servers in CNT_INTVL sec. */
155 #define RETRYTIME       (60*10)         /* retry after bind or server fail */
156
157 #ifndef RLIMIT_NOFILE
158 #define RLIMIT_NOFILE   RLIMIT_OFILE
159 #endif
160
161 #ifndef OPEN_MAX
162 #define OPEN_MAX        64
163 #endif
164
165 /* Reserve some descriptors, 3 stdio + at least: 1 log, 1 conf. file */
166 #define FD_MARGIN       (8)
167 static rlim_t rlim_ofile_cur = OPEN_MAX;
168 static struct rlimit rlim_ofile;
169
170
171 /* Check unsupporting builtin */
172 #if defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO || \
173         defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD || \
174         defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME || \
175         defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME || \
176         defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
177 # define INETD_FEATURE_ENABLED
178 #endif
179
180 #if defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO || \
181         defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD || \
182         defined CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
183 # define INETD_SETPROCTITLE
184 #endif
185
186 typedef struct servtab
187 {
188   char *se_hostaddr;                    /* host address to listen on */
189   char *se_service;                     /* name of service */
190   int se_socktype;                      /* type of socket to use */
191   int se_family;                        /* address family */
192   char *se_proto;                       /* protocol used */
193 #ifdef CONFIG_FEATURE_INETD_RPC
194   int se_rpcprog;                       /* rpc program number */
195   int se_rpcversl;                      /* rpc program lowest version */
196   int se_rpcversh;                      /* rpc program highest version */
197 #define isrpcservice(sep)       ((sep)->se_rpcversl != 0)
198 #else
199 #define isrpcservice(sep)       0
200 #endif
201   pid_t se_wait;                        /* single threaded server */
202   short se_checked;                     /* looked at during merge */
203   char *se_user;                        /* user name to run as */
204   char *se_group;                       /* group name to run as */
205 #ifdef INETD_FEATURE_ENABLED
206   const struct builtin *se_bi;                 /* if built-in, description */
207 #endif
208   char *se_server;                      /* server program */
209 #define MAXARGV 20
210   char *se_argv[MAXARGV + 1];           /* program arguments */
211   int se_fd;                            /* open descriptor */
212   union
213   {
214         struct sockaddr se_un_ctrladdr;
215         struct sockaddr_in se_un_ctrladdr_in;
216 #ifdef CONFIG_FEATURE_IPV6
217         struct sockaddr_in6 se_un_ctrladdr_in6;
218 #endif
219         struct sockaddr_un se_un_ctrladdr_un;
220   } se_un;                              /* bound address */
221 #define se_ctrladdr     se_un.se_un_ctrladdr
222 #define se_ctrladdr_in  se_un.se_un_ctrladdr_in
223 #define se_ctrladdr_in6 se_un.se_un_ctrladdr_in6
224 #define se_ctrladdr_un  se_un.se_un_ctrladdr_un
225   int se_ctrladdr_size;
226   int se_max;                           /* max # of instances of this service */
227   int se_count;                         /* number started since se_time */
228   struct timeval se_time;               /* start of se_count */
229   struct servtab *se_next;
230 } servtab_t;
231
232 static servtab_t *servtab;
233
234 #ifdef INETD_FEATURE_ENABLED
235 struct builtin
236 {
237   const char *bi_service;               /* internally provided service name */
238   int bi_socktype;                      /* type of socket supported */
239   short bi_fork;                        /* 1 if should fork before call */
240   short bi_wait;                        /* 1 if should wait for child */
241   void (*bi_fn) (int, servtab_t *);
242 };
243
244         /* Echo received data */
245 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
246 static void echo_stream (int, servtab_t *);
247 static void echo_dg (int, servtab_t *);
248 #endif
249         /* Internet /dev/null */
250 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
251 static void discard_stream (int, servtab_t *);
252 static void discard_dg (int, servtab_t *);
253 #endif
254         /* Return 32 bit time since 1900 */
255 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME
256 static void machtime_stream (int, servtab_t *);
257 static void machtime_dg (int, servtab_t *);
258 #endif
259         /* Return human-readable time */
260 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
261 static void daytime_stream (int, servtab_t *);
262 static void daytime_dg (int, servtab_t *);
263 #endif
264         /* Familiar character generator */
265 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
266 static void chargen_stream (int, servtab_t *);
267 static void chargen_dg (int, servtab_t *);
268 #endif
269
270 static const struct builtin builtins[] = {
271 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
272   /* Echo received data */
273   {"echo", SOCK_STREAM, 1, 0, echo_stream,},
274   {"echo", SOCK_DGRAM, 0, 0, echo_dg,},
275 #endif
276 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
277   /* Internet /dev/null */
278   {"discard", SOCK_STREAM, 1, 0, discard_stream,},
279   {"discard", SOCK_DGRAM, 0, 0, discard_dg,},
280 #endif
281 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME
282   /* Return 32 bit time since 1900 */
283   {"time", SOCK_STREAM, 0, 0, machtime_stream,},
284   {"time", SOCK_DGRAM, 0, 0, machtime_dg,},
285 #endif
286 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
287   /* Return human-readable time */
288   {"daytime", SOCK_STREAM, 0, 0, daytime_stream,},
289   {"daytime", SOCK_DGRAM, 0, 0, daytime_dg,},
290 #endif
291 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
292   /* Familiar character generator */
293   {"chargen", SOCK_STREAM, 1, 0, chargen_stream,},
294   {"chargen", SOCK_DGRAM, 0, 0, chargen_dg,},
295 #endif
296   {NULL, 0, 0, 0, NULL}
297 };
298 #endif /* INETD_FEATURE_ENABLED */
299
300 static int global_queuelen = 128;
301 static int nsock, maxsock;
302 static fd_set allsock;
303 static int toomany = TOOMANY;
304 static int timingout;
305 static struct servent *sp;
306 static uid_t uid;
307
308 static char *CONFIG = _PATH_INETDCONF;
309
310 static FILE *fconfig;
311 static char line[1024];
312 static char *defhost;
313
314 static char *newstr (char *cp)
315 {
316   if ((cp = strdup (cp ? cp : "")))
317         return (cp);
318   syslog (LOG_ERR, "strdup: %m");
319   exit (1);
320 }
321
322 static int setconfig (void)
323 {
324   free (defhost);
325   defhost = newstr ("*");
326   if (fconfig != NULL) {
327         fseek (fconfig, 0L, SEEK_SET);
328         return (1);
329   }
330   fconfig = fopen (CONFIG, "r");
331   return (fconfig != NULL);
332 }
333
334 static void endconfig (void)
335 {
336   if (fconfig) {
337         (void) fclose (fconfig);
338         fconfig = NULL;
339   }
340   free (defhost);
341   defhost = 0;
342 }
343
344 #ifdef CONFIG_FEATURE_INETD_RPC
345 static void register_rpc (servtab_t *sep)
346 {
347   int n;
348   struct sockaddr_in ir_sin;
349   struct protoent *pp;
350   socklen_t size;
351
352   if ((pp = getprotobyname (sep->se_proto + 4)) == NULL) {
353         syslog (LOG_ERR, "%s: getproto: %m", sep->se_proto);
354         return;
355   }
356   size = sizeof ir_sin;
357   if (getsockname (sep->se_fd, (struct sockaddr *) &ir_sin, &size) < 0) {
358         syslog (LOG_ERR, "%s/%s: getsockname: %m",
359                         sep->se_service, sep->se_proto);
360         return;
361   }
362
363   for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
364         (void) pmap_unset (sep->se_rpcprog, n);
365         if (!pmap_set (sep->se_rpcprog, n, pp->p_proto, ntohs (ir_sin.sin_port)))
366           syslog (LOG_ERR, "%s %s: pmap_set: %u %u %u %u: %m",
367                           sep->se_service, sep->se_proto,
368                           sep->se_rpcprog, n, pp->p_proto, ntohs (ir_sin.sin_port));
369   }
370 }
371
372 static void unregister_rpc (servtab_t *sep)
373 {
374   int n;
375
376   for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
377         if (!pmap_unset (sep->se_rpcprog, n))
378           syslog (LOG_ERR, "pmap_unset(%u, %u)", sep->se_rpcprog, n);
379   }
380 }
381 #endif /* CONFIG_FEATURE_INETD_RPC */
382
383 static void freeconfig (servtab_t *cp)
384 {
385   int i;
386
387   free (cp->se_hostaddr);
388   free (cp->se_service);
389   free (cp->se_proto);
390   free (cp->se_user);
391   free (cp->se_group);
392   free (cp->se_server);
393   for (i = 0; i < MAXARGV; i++)
394         free (cp->se_argv[i]);
395 }
396
397 static int bump_nofile (void)
398 {
399 #define FD_CHUNK        32
400
401   struct rlimit rl;
402
403   if (getrlimit (RLIMIT_NOFILE, &rl) < 0) {
404         syslog (LOG_ERR, "getrlimit: %m");
405         return -1;
406   }
407   rl.rlim_cur = MIN (rl.rlim_max, rl.rlim_cur + FD_CHUNK);
408   rl.rlim_cur = MIN (FD_SETSIZE, rl.rlim_cur + FD_CHUNK);
409   if (rl.rlim_cur <= rlim_ofile_cur) {
410         syslog (LOG_ERR, "bump_nofile: cannot extend file limit, max = %d",
411                         (int) rl.rlim_cur);
412         return -1;
413   }
414
415   if (setrlimit (RLIMIT_NOFILE, &rl) < 0) {
416         syslog (LOG_ERR, "setrlimit: %m");
417         return -1;
418   }
419
420   rlim_ofile_cur = rl.rlim_cur;
421   return 0;
422 }
423
424 static void setup (servtab_t *sep)
425 {
426   int on = 1;
427   int r;
428
429   if ((sep->se_fd = socket (sep->se_family, sep->se_socktype, 0)) < 0) {
430         syslog (LOG_ERR, "%s/%s: socket: %m", sep->se_service, sep->se_proto);
431         return;
432   }
433 #define turnon(fd, opt) \
434 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
435   if (turnon (sep->se_fd, SO_REUSEADDR) < 0)
436         syslog (LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
437 #undef turnon
438
439 #ifdef CONFIG_FEATURE_INETD_RPC
440   if (isrpcservice (sep)) {
441         struct passwd *pwd;
442
443         /*
444          * for RPC services, attempt to use a reserved port
445          * if they are going to be running as root.
446          *
447          * Also, zero out the port for all RPC services; let bind()
448          * find one.
449          */
450         sep->se_ctrladdr_in.sin_port = 0;
451         if (sep->se_user && (pwd = getpwnam (sep->se_user)) &&
452                 pwd->pw_uid == 0 && uid == 0)
453           r = bindresvport (sep->se_fd, &sep->se_ctrladdr_in);
454         else {
455           r = bind (sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size);
456           if (r == 0) {
457                 socklen_t len = sep->se_ctrladdr_size;
458                 int saveerrno = errno;
459
460                 /* update se_ctrladdr_in.sin_port */
461                 r = getsockname (sep->se_fd, &sep->se_ctrladdr, &len);
462                 if (r <= 0)
463                   errno = saveerrno;
464           }
465         }
466   } else
467 #endif
468         r = bind (sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size);
469   if (r < 0) {
470         syslog (LOG_ERR, "%s/%s (%d): bind: %m",
471                         sep->se_service, sep->se_proto, sep->se_ctrladdr.sa_family);
472         close (sep->se_fd);
473         sep->se_fd = -1;
474         if (!timingout) {
475           timingout = 1;
476           alarm (RETRYTIME);
477         }
478         return;
479   }
480   if (sep->se_socktype == SOCK_STREAM)
481         listen (sep->se_fd, global_queuelen);
482
483   FD_SET (sep->se_fd, &allsock);
484   nsock++;
485   if (sep->se_fd > maxsock) {
486         maxsock = sep->se_fd;
487         if ((rlim_t)maxsock > rlim_ofile_cur - FD_MARGIN)
488           bump_nofile ();
489   }
490 }
491
492 static char *nextline (void)
493 {
494   char *cp;
495   FILE *fd = fconfig;
496
497   if (fgets (line, sizeof (line), fd) == NULL)
498         return (NULL);
499   cp = strchr (line, '\n');
500   if (cp)
501         *cp = '\0';
502   return (line);
503 }
504
505 static char *skip (char **cpp) /* int report; */
506 {
507   char *cp = *cpp;
508   char *start;
509
510 /* erp: */
511   if (*cpp == NULL) {
512         /* if (report) */
513         /* syslog(LOG_ERR, "syntax error in inetd config file"); */
514         return (NULL);
515   }
516
517 again:
518   while (*cp == ' ' || *cp == '\t')
519         cp++;
520   if (*cp == '\0') {
521         int c;
522
523         c = getc (fconfig);
524         (void) ungetc (c, fconfig);
525         if (c == ' ' || c == '\t')
526           if ((cp = nextline ()))
527                 goto again;
528         *cpp = NULL;
529         /* goto erp; */
530         return (NULL);
531   }
532   start = cp;
533   while (*cp && *cp != ' ' && *cp != '\t')
534         cp++;
535   if (*cp != '\0')
536         *cp++ = '\0';
537   /* if ((*cpp = cp) == NULL) */
538   /* goto erp; */
539
540   *cpp = cp;
541   return (start);
542 }
543
544 static servtab_t *new_servtab(void)
545 {
546   servtab_t *sep;
547
548   sep = (servtab_t *) malloc (sizeof (servtab_t));
549   if (sep == NULL) {
550         syslog (LOG_ERR, bb_msg_memory_exhausted);
551         exit (1);
552   }
553   return sep;
554 }
555
556 static servtab_t *dupconfig (servtab_t *sep)
557 {
558   servtab_t *newtab;
559   int argc;
560
561   newtab = new_servtab();
562   memset (newtab, 0, sizeof (servtab_t));
563   newtab->se_service = sep->se_service ? newstr (sep->se_service) : NULL;
564   newtab->se_socktype = sep->se_socktype;
565   newtab->se_family = sep->se_family;
566   newtab->se_proto = sep->se_proto ? newstr (sep->se_proto) : NULL;
567 #ifdef CONFIG_FEATURE_INETD_RPC
568   newtab->se_rpcprog = sep->se_rpcprog;
569   newtab->se_rpcversl = sep->se_rpcversl;
570   newtab->se_rpcversh = sep->se_rpcversh;
571 #endif
572   newtab->se_wait = sep->se_wait;
573   newtab->se_user = sep->se_user ? newstr (sep->se_user) : NULL;
574   newtab->se_group = sep->se_group ? newstr (sep->se_group) : NULL;
575 #ifdef INETD_FEATURE_ENABLED
576   newtab->se_bi = sep->se_bi;
577 #endif
578   newtab->se_server = sep->se_server ? newstr (sep->se_server) : 0;
579
580   for (argc = 0; argc <= MAXARGV; argc++)
581         newtab->se_argv[argc] = sep->se_argv[argc] ?
582           newstr (sep->se_argv[argc]) : NULL;
583   newtab->se_max = sep->se_max;
584
585   return (newtab);
586 }
587
588 static servtab_t *getconfigent (void)
589 {
590   servtab_t *sep;
591   int argc;
592   char *cp, *arg;
593   char *hostdelim;
594   servtab_t *nsep;
595   servtab_t *psep;
596
597   sep = new_servtab();
598
599   /* memset(sep, 0, sizeof *sep); */
600 more:
601   /* freeconfig(sep); */
602
603   while ((cp = nextline ()) && *cp == '#');
604   if (cp == NULL) {
605         /* free(sep); */
606         return (NULL);
607   }
608
609   memset ((char *) sep, 0, sizeof *sep);
610   arg = skip (&cp);
611   if (arg == NULL) {
612         /* A blank line. */
613         goto more;
614   }
615
616   /* Check for a host name. */
617   hostdelim = strrchr (arg, ':');
618   if (hostdelim) {
619         *hostdelim = '\0';
620         sep->se_hostaddr = newstr (arg);
621         arg = hostdelim + 1;
622         /*
623          * If the line is of the form `host:', then just change the
624          * default host for the following lines.
625          */
626         if (*arg == '\0') {
627           arg = skip (&cp);
628           if (cp == NULL) {
629                 free (defhost);
630                 defhost = sep->se_hostaddr;
631                 goto more;
632           }
633         }
634   } else
635         sep->se_hostaddr = newstr (defhost);
636
637   sep->se_service = newstr (arg);
638   arg = skip (&cp);
639
640   if (strcmp (arg, "stream") == 0)
641         sep->se_socktype = SOCK_STREAM;
642   else if (strcmp (arg, "dgram") == 0)
643         sep->se_socktype = SOCK_DGRAM;
644   else if (strcmp (arg, "rdm") == 0)
645         sep->se_socktype = SOCK_RDM;
646   else if (strcmp (arg, "seqpacket") == 0)
647         sep->se_socktype = SOCK_SEQPACKET;
648   else if (strcmp (arg, "raw") == 0)
649         sep->se_socktype = SOCK_RAW;
650   else
651         sep->se_socktype = -1;
652
653   sep->se_proto = newstr (skip (&cp));
654
655   if (strcmp (sep->se_proto, "unix") == 0) {
656         sep->se_family = AF_UNIX;
657   } else {
658         sep->se_family = AF_INET;
659         if (sep->se_proto[strlen (sep->se_proto) - 1] == '6')
660 #ifdef CONFIG_FEATURE_IPV6
661           sep->se_family = AF_INET6;
662 #else
663           syslog (LOG_ERR, "%s: IPV6 not supported", sep->se_proto);
664 #endif
665         if (strncmp (sep->se_proto, "rpc/", 4) == 0) {
666 #ifdef CONFIG_FEATURE_INETD_RPC
667           char *p, *ccp;
668           long l;
669
670           p = strchr (sep->se_service, '/');
671           if (p == 0) {
672                 syslog (LOG_ERR, "%s: no rpc version", sep->se_service);
673                 goto more;
674           }
675           *p++ = '\0';
676           l = strtol (p, &ccp, 0);
677           if (ccp == p || l < 0 || l > INT_MAX) {
678           badafterall:
679                 syslog (LOG_ERR, "%s/%s: bad rpc version", sep->se_service, p);
680                 goto more;
681           }
682           sep->se_rpcversl = sep->se_rpcversh = l;
683           if (*ccp == '-') {
684                 p = ccp + 1;
685                 l = strtol (p, &ccp, 0);
686                 if (ccp == p || l < 0 || l > INT_MAX || l < sep->se_rpcversl || *ccp)
687                   goto badafterall;
688                 sep->se_rpcversh = l;
689           } else if (*ccp != '\0')
690                 goto badafterall;
691 #else
692         syslog (LOG_ERR, "%s: rpc services not supported", sep->se_service);
693 #endif
694         }
695   }
696   arg = skip (&cp);
697   if (arg == NULL)
698         goto more;
699
700   {
701         char *s = strchr (arg, '.');
702         if (s) {
703           *s++ = '\0';
704           sep->se_max = atoi (s);
705         } else
706           sep->se_max = toomany;
707   }
708   sep->se_wait = strcmp (arg, "wait") == 0;
709   /* if ((arg = skip(&cp, 1)) == NULL) */
710   /* goto more; */
711   sep->se_user = newstr (skip (&cp));
712   arg = strchr (sep->se_user, '.');
713   if (arg == NULL)
714         arg = strchr (sep->se_user, ':');
715   if (arg) {
716         *arg++ = '\0';
717         sep->se_group = newstr (arg);
718   }
719   /* if ((arg = skip(&cp, 1)) == NULL) */
720   /* goto more; */
721
722   sep->se_server = newstr (skip (&cp));
723   if (strcmp (sep->se_server, "internal") == 0) {
724 #ifdef INETD_FEATURE_ENABLED
725         const struct builtin *bi;
726
727         for (bi = builtins; bi->bi_service; bi++)
728           if (bi->bi_socktype == sep->se_socktype &&
729                   strcmp (bi->bi_service, sep->se_service) == 0)
730                 break;
731         if (bi->bi_service == 0) {
732           syslog (LOG_ERR, "internal service %s unknown", sep->se_service);
733           goto more;
734         }
735         sep->se_bi = bi;
736         sep->se_wait = bi->bi_wait;
737 #else
738         syslog (LOG_ERR, "internal service %s unknown", sep->se_service);
739         goto more;
740 #endif
741   }
742 #ifdef INETD_FEATURE_ENABLED
743     else
744         sep->se_bi = NULL;
745 #endif
746   argc = 0;
747   for (arg = skip (&cp); cp; arg = skip (&cp)) {
748         if (argc < MAXARGV)
749           sep->se_argv[argc++] = newstr (arg);
750   }
751   while (argc <= MAXARGV)
752         sep->se_argv[argc++] = NULL;
753
754   /*
755    * Now that we've processed the entire line, check if the hostname
756    * specifier was a comma separated list of hostnames. If so
757    * we'll make new entries for each address.
758    */
759   while ((hostdelim = strrchr (sep->se_hostaddr, ',')) != NULL) {
760         nsep = dupconfig (sep);
761
762         /*
763          * NULL terminate the hostname field of the existing entry,
764          * and make a dup for the new entry.
765          */
766         *hostdelim++ = '\0';
767         nsep->se_hostaddr = newstr (hostdelim);
768
769         nsep->se_next = sep->se_next;
770         sep->se_next = nsep;
771   }
772
773   nsep = sep;
774   while (nsep != NULL) {
775         nsep->se_checked = 1;
776         if (nsep->se_family == AF_INET) {
777           if (!strcmp (nsep->se_hostaddr, "*"))
778                 nsep->se_ctrladdr_in.sin_addr.s_addr = INADDR_ANY;
779           else if (!inet_aton (nsep->se_hostaddr, &nsep->se_ctrladdr_in.sin_addr)) {
780                 struct hostent *hp;
781
782                 hp = gethostbyname (nsep->se_hostaddr);
783                 if (hp == 0) {
784                   syslog (LOG_ERR, "%s: unknown host", nsep->se_hostaddr);
785                   nsep->se_checked = 0;
786                   goto skip;
787                 } else if (hp->h_addrtype != AF_INET) {
788                   syslog (LOG_ERR,
789                                   "%s: address isn't an Internet "
790                                   "address", nsep->se_hostaddr);
791                   nsep->se_checked = 0;
792                   goto skip;
793                 } else {
794                   int i = 1;
795
796                   memmove (&nsep->se_ctrladdr_in.sin_addr,
797                                    hp->h_addr_list[0], sizeof (struct in_addr));
798                   while (hp->h_addr_list[i] != NULL) {
799                         psep = dupconfig (nsep);
800                         psep->se_hostaddr = newstr (nsep->se_hostaddr);
801                         psep->se_checked = 1;
802                         memmove (&psep->se_ctrladdr_in.sin_addr,
803                                          hp->h_addr_list[i], sizeof (struct in_addr));
804                         psep->se_ctrladdr_size = sizeof (psep->se_ctrladdr_in);
805                         i++;
806                         /* Prepend to list, don't want to look up its */
807                         /* hostname again. */
808                         psep->se_next = sep;
809                         sep = psep;
810                   }
811                 }
812           }
813         }
814 /* XXX BUG?: is this skip: label supposed to remain? */
815   skip:
816         nsep = nsep->se_next;
817   }
818
819   /*
820    * Finally, free any entries which failed the gethostbyname
821    * check.
822    */
823   psep = NULL;
824   nsep = sep;
825   while (nsep != NULL) {
826         servtab_t *tsep;
827
828         if (nsep->se_checked == 0) {
829           tsep = nsep;
830           if (psep == NULL) {
831                 sep = nsep->se_next;
832                 nsep = sep;
833           } else {
834                 nsep = nsep->se_next;
835                 psep->se_next = nsep;
836           }
837           freeconfig (tsep);
838         } else {
839           nsep->se_checked = 0;
840           psep = nsep;
841           nsep = nsep->se_next;
842         }
843   }
844
845   return (sep);
846 }
847
848 #define Block_Using_Signals(m) do {     sigemptyset(&m); \
849                                         sigaddset(&m, SIGCHLD); \
850                                         sigaddset(&m, SIGHUP); \
851                                         sigaddset(&m, SIGALRM); \
852                                         sigprocmask(SIG_BLOCK, &m, NULL); \
853                                 } while(0)
854
855
856 static servtab_t *enter (servtab_t *cp)
857 {
858   servtab_t *sep;
859   sigset_t omask;
860
861   sep = new_servtab();
862   *sep = *cp;
863   sep->se_fd = -1;
864 #ifdef CONFIG_FEATURE_INETD_RPC
865   sep->se_rpcprog = -1;
866 #endif
867   Block_Using_Signals(omask);
868   sep->se_next = servtab;
869   servtab = sep;
870   sigprocmask(SIG_UNBLOCK, &omask, NULL);
871   return (sep);
872 }
873
874 static int matchconf (servtab_t *old, servtab_t *new)
875 {
876   if (strcmp (old->se_service, new->se_service) != 0)
877         return (0);
878
879   if (strcmp (old->se_hostaddr, new->se_hostaddr) != 0)
880         return (0);
881
882   if (strcmp (old->se_proto, new->se_proto) != 0)
883         return (0);
884
885   /*
886    * If the new servtab is bound to a specific address, check that the
887    * old servtab is bound to the same entry. If the new service is not
888    * bound to a specific address then the check of se_hostaddr above
889    * is sufficient.
890    */
891
892   if (old->se_family == AF_INET && new->se_family == AF_INET &&
893           memcmp (&old->se_ctrladdr_in.sin_addr,
894                           &new->se_ctrladdr_in.sin_addr,
895                           sizeof (new->se_ctrladdr_in.sin_addr)) != 0)
896         return (0);
897
898 #ifdef CONFIG_FEATURE_IPV6
899   if (old->se_family == AF_INET6 && new->se_family == AF_INET6 &&
900           memcmp (&old->se_ctrladdr_in6.sin6_addr,
901                           &new->se_ctrladdr_in6.sin6_addr,
902                           sizeof (new->se_ctrladdr_in6.sin6_addr)) != 0)
903         return (0);
904 #endif
905   return (1);
906 }
907
908 static void config (int sig ATTRIBUTE_UNUSED)
909 {
910   servtab_t *sep, *cp, **sepp;
911   sigset_t omask;
912   size_t n;
913   char protoname[10];
914
915   if (!setconfig ()) {
916         syslog (LOG_ERR, "%s: %m", CONFIG);
917         return;
918   }
919   for (sep = servtab; sep; sep = sep->se_next)
920         sep->se_checked = 0;
921   cp = getconfigent ();
922   while (cp != NULL) {
923         for (sep = servtab; sep; sep = sep->se_next)
924           if (matchconf (sep, cp))
925                 break;
926
927         if (sep != 0) {
928           int i;
929
930 #define SWAP(type, a, b) do {type c=(type)a; a=(type)b; b=(type)c;} while (0)
931
932           Block_Using_Signals(omask);
933           /*
934            * sep->se_wait may be holding the pid of a daemon
935            * that we're waiting for.  If so, don't overwrite
936            * it unless the config file explicitly says don't
937            * wait.
938            */
939           if (
940 #ifdef INETD_FEATURE_ENABLED
941                    cp->se_bi == 0 &&
942 #endif
943                 (sep->se_wait == 1 || cp->se_wait == 0))
944                 sep->se_wait = cp->se_wait;
945           SWAP (int, cp->se_max, sep->se_max);
946           SWAP (char *, sep->se_user, cp->se_user);
947           SWAP (char *, sep->se_group, cp->se_group);
948           SWAP (char *, sep->se_server, cp->se_server);
949           for (i = 0; i < MAXARGV; i++)
950                 SWAP (char *, sep->se_argv[i], cp->se_argv[i]);
951 #undef SWAP
952
953 #ifdef CONFIG_FEATURE_INETD_RPC
954           if (isrpcservice (sep))
955                 unregister_rpc (sep);
956           sep->se_rpcversl = cp->se_rpcversl;
957           sep->se_rpcversh = cp->se_rpcversh;
958 #endif
959           sigprocmask(SIG_UNBLOCK, &omask, NULL);
960           freeconfig (cp);
961         } else {
962           sep = enter (cp);
963         }
964         sep->se_checked = 1;
965
966         switch (sep->se_family) {
967         case AF_UNIX:
968           if (sep->se_fd != -1)
969                 break;
970           (void) unlink (sep->se_service);
971           n = strlen (sep->se_service);
972           if (n > sizeof sep->se_ctrladdr_un.sun_path - 1)
973                 n = sizeof sep->se_ctrladdr_un.sun_path - 1;
974           safe_strncpy (sep->se_ctrladdr_un.sun_path, sep->se_service, n + 1);
975           sep->se_ctrladdr_un.sun_family = AF_UNIX;
976           sep->se_ctrladdr_size = n + sizeof sep->se_ctrladdr_un.sun_family;
977           setup (sep);
978           break;
979         case AF_INET:
980           sep->se_ctrladdr_in.sin_family = AF_INET;
981           /* se_ctrladdr_in was set in getconfigent */
982           sep->se_ctrladdr_size = sizeof sep->se_ctrladdr_in;
983
984 #ifdef CONFIG_FEATURE_INETD_RPC
985           if (isrpcservice (sep)) {
986                 struct rpcent *rp;
987
988                 sep->se_rpcprog = atoi (sep->se_service);
989                 if (sep->se_rpcprog == 0) {
990                   rp = getrpcbyname (sep->se_service);
991                   if (rp == 0) {
992                         syslog (LOG_ERR, "%s: unknown rpc service", sep->se_service);
993                         goto serv_unknown;
994                   }
995                   sep->se_rpcprog = rp->r_number;
996                 }
997                 if (sep->se_fd == -1)
998                   setup (sep);
999                 if (sep->se_fd != -1)
1000                   register_rpc (sep);
1001           } else
1002 #endif
1003              {
1004                 u_short port = htons (atoi (sep->se_service));
1005
1006                 if (!port) {
1007                    /*XXX*/ strncpy (protoname, sep->se_proto, sizeof (protoname));
1008                   if (isdigit (protoname[strlen (protoname) - 1]))
1009                         protoname[strlen (protoname) - 1] = '\0';
1010                   sp = getservbyname (sep->se_service, protoname);
1011                   if (sp == 0) {
1012                         syslog (LOG_ERR,
1013                                         "%s/%s: unknown service", sep->se_service, sep->se_proto);
1014                         goto serv_unknown;
1015                   }
1016                   port = sp->s_port;
1017                 }
1018                 if (port != sep->se_ctrladdr_in.sin_port) {
1019                   sep->se_ctrladdr_in.sin_port = port;
1020                   if (sep->se_fd != -1) {
1021                         FD_CLR (sep->se_fd, &allsock);
1022                         nsock--;
1023                         (void) close (sep->se_fd);
1024                   }
1025                   sep->se_fd = -1;
1026                 }
1027                 if (sep->se_fd == -1)
1028                   setup (sep);
1029           }
1030           break;
1031 #ifdef CONFIG_FEATURE_IPV6
1032         case AF_INET6:
1033           sep->se_ctrladdr_in6.sin6_family = AF_INET6;
1034           /* se_ctrladdr_in was set in getconfigent */
1035           sep->se_ctrladdr_size = sizeof sep->se_ctrladdr_in6;
1036
1037 #ifdef CONFIG_FEATURE_INETD_RPC
1038           if (isrpcservice (sep)) {
1039                 struct rpcent *rp;
1040
1041                 sep->se_rpcprog = atoi (sep->se_service);
1042                 if (sep->se_rpcprog == 0) {
1043                   rp = getrpcbyname (sep->se_service);
1044                   if (rp == 0) {
1045                         syslog (LOG_ERR, "%s: unknown rpc service", sep->se_service);
1046                         goto serv_unknown;
1047                   }
1048                   sep->se_rpcprog = rp->r_number;
1049                 }
1050                 if (sep->se_fd == -1)
1051                   setup (sep);
1052                 if (sep->se_fd != -1)
1053                   register_rpc (sep);
1054           } else
1055 #endif
1056                 {
1057                 u_short port = htons (atoi (sep->se_service));
1058
1059                 if (!port) {
1060                    /*XXX*/ strncpy (protoname, sep->se_proto, sizeof (protoname));
1061                   if (isdigit (protoname[strlen (protoname) - 1]))
1062                         protoname[strlen (protoname) - 1] = '\0';
1063                   sp = getservbyname (sep->se_service, protoname);
1064                   if (sp == 0) {
1065                         syslog (LOG_ERR,
1066                                         "%s/%s: unknown service", sep->se_service, sep->se_proto);
1067                         goto serv_unknown;
1068                   }
1069                   port = sp->s_port;
1070                 }
1071                 if (port != sep->se_ctrladdr_in6.sin6_port) {
1072                   sep->se_ctrladdr_in6.sin6_port = port;
1073                   if (sep->se_fd != -1) {
1074                         FD_CLR (sep->se_fd, &allsock);
1075                         nsock--;
1076                         (void) close (sep->se_fd);
1077                   }
1078                   sep->se_fd = -1;
1079                 }
1080                 if (sep->se_fd == -1)
1081                   setup (sep);
1082           }
1083           break;
1084 #endif /* CONFIG_FEATURE_IPV6 */
1085         }
1086   serv_unknown:
1087         if (cp->se_next != NULL) {
1088           servtab_t *tmp = cp;
1089
1090           cp = cp->se_next;
1091           free (tmp);
1092         } else {
1093           free (cp);
1094           cp = getconfigent ();
1095         }
1096   }
1097   endconfig ();
1098   /*
1099    * Purge anything not looked at above.
1100    */
1101   Block_Using_Signals(omask);
1102   sepp = &servtab;
1103   while ((sep = *sepp)) {
1104         if (sep->se_checked) {
1105           sepp = &sep->se_next;
1106           continue;
1107         }
1108         *sepp = sep->se_next;
1109         if (sep->se_fd != -1) {
1110           FD_CLR (sep->se_fd, &allsock);
1111           nsock--;
1112           (void) close (sep->se_fd);
1113         }
1114 #ifdef CONFIG_FEATURE_INETD_RPC
1115         if (isrpcservice (sep))
1116           unregister_rpc (sep);
1117 #endif
1118         if (sep->se_family == AF_UNIX)
1119           (void) unlink (sep->se_service);
1120         freeconfig (sep);
1121         free (sep);
1122   }
1123   sigprocmask(SIG_UNBLOCK, &omask, NULL);
1124 }
1125
1126
1127 static void reapchild (int sig ATTRIBUTE_UNUSED)
1128 {
1129   pid_t pid;
1130   int save_errno = errno, status;
1131   servtab_t *sep;
1132
1133   for (;;) {
1134         pid = wait3 (&status, WNOHANG, NULL);
1135         if (pid <= 0)
1136           break;
1137         for (sep = servtab; sep; sep = sep->se_next)
1138           if (sep->se_wait == pid) {
1139                 if (WIFEXITED (status) && WEXITSTATUS (status))
1140                   syslog (LOG_WARNING,
1141                                   "%s: exit status 0x%x",
1142                                   sep->se_server, WEXITSTATUS (status));
1143                 else if (WIFSIGNALED (status))
1144                   syslog (LOG_WARNING,
1145                                   "%s: exit signal 0x%x", sep->se_server, WTERMSIG (status));
1146                 sep->se_wait = 1;
1147                 FD_SET (sep->se_fd, &allsock);
1148                 nsock++;
1149           }
1150   }
1151   errno = save_errno;
1152 }
1153
1154 static void retry (int sig ATTRIBUTE_UNUSED)
1155 {
1156   servtab_t *sep;
1157
1158   timingout = 0;
1159   for (sep = servtab; sep; sep = sep->se_next) {
1160         if (sep->se_fd == -1) {
1161           switch (sep->se_family) {
1162           case AF_UNIX:
1163           case AF_INET:
1164 #ifdef CONFIG_FEATURE_IPV6
1165           case AF_INET6:
1166 #endif
1167                 setup (sep);
1168 #ifdef CONFIG_FEATURE_INETD_RPC
1169                 if (sep->se_fd != -1 && isrpcservice (sep))
1170                   register_rpc (sep);
1171 #endif
1172                 break;
1173           }
1174         }
1175   }
1176 }
1177
1178 static void goaway (int sig ATTRIBUTE_UNUSED)
1179 {
1180   servtab_t *sep;
1181
1182   /* XXX signal race walking sep list */
1183   for (sep = servtab; sep; sep = sep->se_next) {
1184         if (sep->se_fd == -1)
1185           continue;
1186
1187         switch (sep->se_family) {
1188         case AF_UNIX:
1189           (void) unlink (sep->se_service);
1190           break;
1191         case AF_INET:
1192 #ifdef CONFIG_FEATURE_IPV6
1193         case AF_INET6:
1194 #endif
1195 #ifdef CONFIG_FEATURE_INETD_RPC
1196           if (sep->se_wait == 1 && isrpcservice (sep))
1197                 unregister_rpc (sep);   /* XXX signal race */
1198 #endif
1199           break;
1200         }
1201         (void) close (sep->se_fd);
1202   }
1203   (void) unlink (_PATH_INETDPID);
1204   exit (0);
1205 }
1206
1207
1208 #ifdef INETD_SETPROCTITLE
1209 static char **Argv;
1210 static char *LastArg;
1211
1212 static void
1213 inetd_setproctitle (char *a, int s)
1214 {
1215   socklen_t size;
1216   char *cp;
1217   struct sockaddr_in prt_sin;
1218   char buf[80];
1219
1220   cp = Argv[0];
1221   size = sizeof (prt_sin);
1222   (void) snprintf (buf, sizeof buf, "-%s", a);
1223   if (getpeername (s, (struct sockaddr *) &prt_sin, &size) == 0) {
1224         char *sa = inet_ntoa (prt_sin.sin_addr);
1225
1226         buf[sizeof (buf) - 1 - strlen (sa) - 3] = '\0';
1227         strcat (buf, " [");
1228         strcat (buf, sa);
1229         strcat (buf, "]");
1230   }
1231   strncpy (cp, buf, LastArg - cp);
1232   cp += strlen (cp);
1233   while (cp < LastArg)
1234         *cp++ = ' ';
1235 }
1236 #endif
1237
1238
1239 int
1240 inetd_main (int argc, char *argv[])
1241 {
1242   servtab_t *sep;
1243   struct passwd *pwd;
1244   struct group *grp = NULL;
1245   int tmpint;
1246   struct sigaction sa, sapipe;
1247   int opt;
1248   pid_t pid;
1249   char buf[50];
1250   char *stoomany;
1251   sigset_t omask, wait_mask;
1252
1253 #ifdef INETD_SETPROCTITLE
1254   extern char **environ;
1255   char **envp = environ;
1256
1257   Argv = argv;
1258   if (envp == 0 || *envp == 0)
1259         envp = argv;
1260   while (*envp)
1261         envp++;
1262   LastArg = envp[-1] + strlen (envp[-1]);
1263 #endif
1264
1265   openlog (bb_applet_name, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
1266
1267   opt = bb_getopt_ulflags (argc, argv, "R:f", &stoomany);
1268   if(opt & 1) {
1269         char *e;
1270
1271         toomany = strtoul (stoomany, &e, 0);
1272         if (!(toomany >= 0 && *e == '\0')) {
1273                 toomany = TOOMANY;
1274                 syslog (LOG_ERR, "-R %s: bad value for service invocation rate", stoomany);
1275         }
1276   }
1277   argc -= optind;
1278   argv += optind;
1279
1280   uid = getuid ();
1281   if (uid != 0)
1282         CONFIG = NULL;
1283   if (argc > 0)
1284         CONFIG = argv[0];
1285   if (CONFIG == NULL)
1286         bb_error_msg_and_die ("non-root must specify a config file");
1287
1288   if (!(opt & 2)) {
1289 #ifdef BB_NOMMU
1290         /* reexec for vfork() do continue parent */
1291         vfork_daemon_rexec (0, 0, argc, argv, "-f");
1292 #else
1293         xdaemon (0, 0);
1294 #endif
1295   } else {
1296         setsid ();
1297   }
1298
1299   if (uid == 0) {
1300         gid_t gid = getgid ();
1301
1302         /* If run by hand, ensure groups vector gets trashed */
1303         setgroups (1, &gid);
1304   }
1305
1306   {
1307         FILE *fp;
1308
1309         if ((fp = fopen (_PATH_INETDPID, "w")) != NULL) {
1310                 fprintf (fp, "%u\n", getpid ());
1311                 (void) fclose (fp);
1312         }
1313   }
1314
1315   if (getrlimit (RLIMIT_NOFILE, &rlim_ofile) < 0) {
1316         syslog (LOG_ERR, "getrlimit: %m");
1317   } else {
1318         rlim_ofile_cur = rlim_ofile.rlim_cur;
1319         if (rlim_ofile_cur == RLIM_INFINITY)    /* ! */
1320           rlim_ofile_cur = OPEN_MAX;
1321   }
1322
1323   memset ((char *) &sa, 0, sizeof (sa));
1324   sigemptyset (&sa.sa_mask);
1325   sigaddset (&sa.sa_mask, SIGALRM);
1326   sigaddset (&sa.sa_mask, SIGCHLD);
1327   sigaddset (&sa.sa_mask, SIGHUP);
1328   sa.sa_handler = retry;
1329   sigaction (SIGALRM, &sa, NULL);
1330   /* doconfig(); */
1331   config (SIGHUP);
1332   sa.sa_handler = config;
1333   sigaction (SIGHUP, &sa, NULL);
1334   sa.sa_handler = reapchild;
1335   sigaction (SIGCHLD, &sa, NULL);
1336   sa.sa_handler = goaway;
1337   sigaction (SIGTERM, &sa, NULL);
1338   sa.sa_handler = goaway;
1339   sigaction (SIGINT, &sa, NULL);
1340   sa.sa_handler = SIG_IGN;
1341   sigaction (SIGPIPE, &sa, &sapipe);
1342   memset(&wait_mask, 0, sizeof(wait_mask));
1343   {
1344         /* space for daemons to overwrite environment for ps */
1345 #define DUMMYSIZE       100
1346         char dummy[DUMMYSIZE];
1347
1348         (void) memset (dummy, 'x', DUMMYSIZE - 1);
1349         dummy[DUMMYSIZE - 1] = '\0';
1350
1351         (void) setenv ("inetd_dummy", dummy, 1);
1352   }
1353
1354   for (;;) {
1355         int n, ctrl = -1;
1356         fd_set readable;
1357
1358         if (nsock == 0) {
1359           Block_Using_Signals(omask);
1360           while (nsock == 0)
1361                 sigsuspend (&wait_mask);
1362           sigprocmask(SIG_UNBLOCK, &omask, NULL);
1363         }
1364
1365         readable = allsock;
1366         if ((n = select (maxsock + 1, &readable, NULL, NULL, NULL)) <= 0) {
1367           if (n < 0 && errno != EINTR) {
1368                 syslog (LOG_WARNING, "select: %m");
1369                 sleep (1);
1370           }
1371           continue;
1372         }
1373         for (sep = servtab; n && sep; sep = sep->se_next)
1374           if (sep->se_fd != -1 && FD_ISSET (sep->se_fd, &readable)) {
1375                 n--;
1376                 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
1377                   ctrl = accept (sep->se_fd, NULL, NULL);
1378                   if (ctrl < 0) {
1379                         if (errno == EINTR)
1380                           continue;
1381                         syslog (LOG_WARNING, "accept (for %s): %m", sep->se_service);
1382                         continue;
1383                   }
1384                   if (sep->se_family == AF_INET && sep->se_socktype == SOCK_STREAM) {
1385                         struct sockaddr_in peer;
1386                         socklen_t plen = sizeof (peer);
1387
1388                         if (getpeername (ctrl, (struct sockaddr *) &peer, &plen) < 0) {
1389                           syslog (LOG_WARNING, "could not getpeername");
1390                           close (ctrl);
1391                           continue;
1392                         }
1393                         if (ntohs (peer.sin_port) == 20) {
1394                           /* XXX ftp bounce */
1395                           close (ctrl);
1396                           continue;
1397                         }
1398                   }
1399                 } else
1400                   ctrl = sep->se_fd;
1401                 Block_Using_Signals(omask);
1402                 pid = 0;
1403 #ifdef INETD_FEATURE_ENABLED
1404                 if (sep->se_bi == 0 || sep->se_bi->bi_fork)
1405 #endif
1406                 {
1407                   if (sep->se_count++ == 0)
1408                         (void) gettimeofday (&sep->se_time, NULL);
1409                   else if (toomany > 0 && sep->se_count >= sep->se_max) {
1410                         struct timeval now;
1411
1412                         (void) gettimeofday (&now, NULL);
1413                         if (now.tv_sec - sep->se_time.tv_sec > CNT_INTVL) {
1414                           sep->se_time = now;
1415                           sep->se_count = 1;
1416                         } else {
1417                           if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1418                                 close (ctrl);
1419                           if (sep->se_family == AF_INET &&
1420                                   ntohs (sep->se_ctrladdr_in.sin_port) >= IPPORT_RESERVED) {
1421                                 /*
1422                                  * Cannot close it -- there are
1423                                  * thieves on the system.
1424                                  * Simply ignore the connection.
1425                                  */
1426                                 --sep->se_count;
1427                                 continue;
1428                           }
1429                           syslog (LOG_ERR,
1430                                           "%s/%s server failing (looping), service terminated",
1431                                           sep->se_service, sep->se_proto);
1432                           if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1433                                 close (ctrl);
1434                           FD_CLR (sep->se_fd, &allsock);
1435                           (void) close (sep->se_fd);
1436                           sep->se_fd = -1;
1437                           sep->se_count = 0;
1438                           nsock--;
1439                           sigprocmask(SIG_UNBLOCK, &omask, NULL);
1440                           if (!timingout) {
1441                                 timingout = 1;
1442                                 alarm (RETRYTIME);
1443                           }
1444                           continue;
1445                         }
1446                   }
1447                   pid = fork ();
1448                 }
1449                 if (pid < 0) {
1450                   syslog (LOG_ERR, "fork: %m");
1451                   if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1452                         close (ctrl);
1453                   sigprocmask(SIG_UNBLOCK, &omask, NULL);
1454                   sleep (1);
1455                   continue;
1456                 }
1457                 if (pid && sep->se_wait) {
1458                   sep->se_wait = pid;
1459                   FD_CLR (sep->se_fd, &allsock);
1460                   nsock--;
1461                 }
1462                 sigprocmask(SIG_UNBLOCK, &omask, NULL);
1463                 if (pid == 0) {
1464 #ifdef INETD_FEATURE_ENABLED
1465                   if (sep->se_bi) {
1466                         (*sep->se_bi->bi_fn) (ctrl, sep);
1467                   } else
1468 #endif
1469                         {
1470                         if ((pwd = getpwnam (sep->se_user)) == NULL) {
1471                           syslog (LOG_ERR, "getpwnam: %s: No such user", sep->se_user);
1472                           if (sep->se_socktype != SOCK_STREAM)
1473                                 recv (0, buf, sizeof (buf), 0);
1474                           _exit (1);
1475                         }
1476                         if (setsid () < 0)
1477                           syslog (LOG_ERR, "%s: setsid: %m", sep->se_service);
1478                         if (sep->se_group && (grp = getgrnam (sep->se_group)) == NULL) {
1479                           syslog (LOG_ERR, "getgrnam: %s: No such group", sep->se_group);
1480                           if (sep->se_socktype != SOCK_STREAM)
1481                                 recv (0, buf, sizeof (buf), 0);
1482                           _exit (1);
1483                         }
1484                         if (uid != 0) {
1485                           /* a user running private inetd */
1486                           if (uid != pwd->pw_uid)
1487                                 _exit (1);
1488                         } else if (pwd->pw_uid) {
1489                           if (sep->se_group) {
1490                                 pwd->pw_gid = grp->gr_gid;
1491                           }
1492                           xsetgid ((gid_t) pwd->pw_gid);
1493                           initgroups (pwd->pw_name, pwd->pw_gid);
1494                           xsetuid((uid_t) pwd->pw_uid);
1495                         } else if (sep->se_group) {
1496                           xsetgid(grp->gr_gid);
1497                           setgroups (1, &grp->gr_gid);
1498                         }
1499                         dup2 (ctrl, 0);
1500                         close (ctrl);
1501                         dup2 (0, 1);
1502                         dup2 (0, 2);
1503                         if (rlim_ofile.rlim_cur != rlim_ofile_cur)
1504                           if (setrlimit (RLIMIT_NOFILE, &rlim_ofile) < 0)
1505                                 syslog (LOG_ERR, "setrlimit: %m");
1506                         closelog ();
1507                         for (tmpint = rlim_ofile_cur - 1; --tmpint > 2;)
1508                           (void) close (tmpint);
1509                         sigaction (SIGPIPE, &sapipe, NULL);
1510                         execv (sep->se_server, sep->se_argv);
1511                         if (sep->se_socktype != SOCK_STREAM)
1512                           recv (0, buf, sizeof (buf), 0);
1513                         syslog (LOG_ERR, "execv %s: %m", sep->se_server);
1514                         _exit (1);
1515                   }
1516                 }
1517                 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1518                   close (ctrl);
1519           }
1520   }
1521 }
1522
1523 /*
1524  * Internet services provided internally by inetd:
1525  */
1526 #define BUFSIZE 4096
1527
1528 #if defined(CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO) || \
1529     defined(CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN) || \
1530     defined(CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME)
1531 static int dg_badinput (struct sockaddr_in *dg_sin)
1532 {
1533   if (ntohs (dg_sin->sin_port) < IPPORT_RESERVED)
1534         return (1);
1535   if (dg_sin->sin_addr.s_addr == htonl (INADDR_BROADCAST))
1536         return (1);
1537   /* XXX compare against broadcast addresses in SIOCGIFCONF list? */
1538   return (0);
1539 }
1540 #endif
1541
1542 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
1543 /* Echo service -- echo data back */
1544 /* ARGSUSED */
1545 static void
1546 echo_stream (int s, servtab_t *sep)
1547 {
1548   char buffer[BUFSIZE];
1549   int i;
1550
1551   inetd_setproctitle (sep->se_service, s);
1552   while ((i = read (s, buffer, sizeof (buffer))) > 0 &&
1553                  write (s, buffer, i) > 0);
1554   exit (0);
1555 }
1556
1557 /* Echo service -- echo data back */
1558 /* ARGSUSED */
1559 static void
1560 echo_dg (int s, servtab_t *sep ATTRIBUTE_UNUSED)
1561 {
1562   char buffer[BUFSIZE];
1563   int i;
1564   socklen_t size;
1565   /* struct sockaddr_storage ss; */
1566   struct sockaddr sa;
1567
1568   size = sizeof (sa);
1569   if ((i = recvfrom (s, buffer, sizeof (buffer), 0, &sa, &size)) < 0)
1570         return;
1571   if (dg_badinput ((struct sockaddr_in *) &sa))
1572         return;
1573   (void) sendto (s, buffer, i, 0, &sa, sizeof (sa));
1574 }
1575 #endif  /* CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO */
1576
1577 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
1578 /* Discard service -- ignore data */
1579 /* ARGSUSED */
1580 static void
1581 discard_stream (int s, servtab_t *sep)
1582 {
1583   char buffer[BUFSIZE];
1584
1585   inetd_setproctitle (sep->se_service, s);
1586   while ((errno = 0, read (s, buffer, sizeof (buffer)) > 0) ||
1587                  errno == EINTR);
1588   exit (0);
1589 }
1590
1591 /* Discard service -- ignore data */
1592 /* ARGSUSED */
1593 static void
1594 discard_dg (int s, servtab_t *sep ATTRIBUTE_UNUSED)
1595 {
1596   char buffer[BUFSIZE];
1597
1598   (void) read (s, buffer, sizeof (buffer));
1599 }
1600 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD */
1601
1602
1603 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
1604 #define LINESIZ 72
1605 static char ring[128];
1606 static char *endring;
1607
1608 static void
1609 initring (void)
1610 {
1611   int i;
1612
1613   endring = ring;
1614
1615   for (i = 0; i <= 128; ++i)
1616         if (isprint (i))
1617           *endring++ = i;
1618 }
1619
1620 /* Character generator */
1621 /* ARGSUSED */
1622 static void
1623 chargen_stream (int s, servtab_t *sep)
1624 {
1625   char *rs;
1626   int len;
1627   char text[LINESIZ + 2];
1628
1629   inetd_setproctitle (sep->se_service, s);
1630
1631   if (!endring) {
1632         initring ();
1633         rs = ring;
1634   }
1635
1636   text[LINESIZ] = '\r';
1637   text[LINESIZ + 1] = '\n';
1638   for (rs = ring;;) {
1639         if ((len = endring - rs) >= LINESIZ)
1640           memmove (text, rs, LINESIZ);
1641         else {
1642           memmove (text, rs, len);
1643           memmove (text + len, ring, LINESIZ - len);
1644         }
1645         if (++rs == endring)
1646           rs = ring;
1647         if (write (s, text, sizeof (text)) != sizeof (text))
1648           break;
1649   }
1650   exit (0);
1651 }
1652
1653 /* Character generator */
1654 /* ARGSUSED */
1655 static void
1656 chargen_dg (int s, servtab_t *sep ATTRIBUTE_UNUSED)
1657 {
1658   /* struct sockaddr_storage ss; */
1659   struct sockaddr sa;
1660   static char *rs;
1661   int len;
1662   char text[LINESIZ + 2];
1663   socklen_t size;
1664
1665   if (endring == 0) {
1666         initring ();
1667         rs = ring;
1668   }
1669
1670   size = sizeof (sa);
1671   if (recvfrom (s, text, sizeof (text), 0, &sa, &size) < 0)
1672         return;
1673   if (dg_badinput ((struct sockaddr_in *) &sa))
1674         return;
1675
1676   if ((len = endring - rs) >= LINESIZ)
1677         memmove (text, rs, LINESIZ);
1678   else {
1679         memmove (text, rs, len);
1680         memmove (text + len, ring, LINESIZ - len);
1681   }
1682   if (++rs == endring)
1683         rs = ring;
1684   text[LINESIZ] = '\r';
1685   text[LINESIZ + 1] = '\n';
1686   (void) sendto (s, text, sizeof (text), 0, &sa, sizeof (sa));
1687 }
1688 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN */
1689
1690
1691 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME
1692 /*
1693  * Return a machine readable date and time, in the form of the
1694  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
1695  * returns the number of seconds since midnight, Jan 1, 1970,
1696  * we must add 2208988800 seconds to this figure to make up for
1697  * some seventy years Bell Labs was asleep.
1698  */
1699
1700 static u_int machtime (void)
1701 {
1702   struct timeval tv;
1703
1704   if (gettimeofday (&tv, NULL) < 0) {
1705         fprintf (stderr, "Unable to get time of day\n");
1706         return (0L);
1707   }
1708   return (htonl ((u_int) tv.tv_sec + 2208988800UL));
1709 }
1710
1711 /* ARGSUSED */
1712 static void
1713 machtime_stream (int s, servtab_t *sep ATTRIBUTE_UNUSED)
1714 {
1715   u_int result;
1716
1717   result = machtime ();
1718   (void) write (s, (char *) &result, sizeof (result));
1719 }
1720
1721 /* ARGSUSED */
1722 static void
1723 machtime_dg (int s, servtab_t *sep ATTRIBUTE_UNUSED)
1724 {
1725   u_int result;
1726   /* struct sockaddr_storage ss; */
1727   struct sockaddr sa;
1728   struct sockaddr_in *dg_sin;
1729   socklen_t size;
1730
1731   size = sizeof (sa);
1732   if (recvfrom (s, (char *) &result, sizeof (result), 0, &sa, &size) < 0)
1733         return;
1734   /* if (dg_badinput((struct sockaddr *)&ss)) */
1735   dg_sin = (struct sockaddr_in *) &sa;
1736   if (dg_sin->sin_addr.s_addr == htonl (INADDR_BROADCAST) ||
1737           ntohs (dg_sin->sin_port) < IPPORT_RESERVED / 2)
1738         return;
1739   result = machtime ();
1740   (void) sendto (s, (char *) &result, sizeof (result), 0, &sa, sizeof (sa));
1741 }
1742 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME */
1743
1744
1745 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
1746 /* Return human-readable time of day */
1747 /* ARGSUSED */
1748 static void daytime_stream (int s, servtab_t *sep ATTRIBUTE_UNUSED)
1749 {
1750   char buffer[256];
1751   time_t t;
1752
1753   t = time (NULL);
1754
1755   (void) sprintf (buffer, "%.24s\r\n", ctime (&t));
1756   (void) write (s, buffer, strlen (buffer));
1757 }
1758
1759 /* Return human-readable time of day */
1760 /* ARGSUSED */
1761 void
1762 daytime_dg (int s, servtab_t *sep ATTRIBUTE_UNUSED)
1763 {
1764   char buffer[256];
1765   time_t t;
1766   /* struct sockaddr_storage ss; */
1767   struct sockaddr sa;
1768   socklen_t size;
1769
1770   t = time ((time_t *) 0);
1771
1772   size = sizeof (sa);
1773   if (recvfrom (s, buffer, sizeof (buffer), 0, &sa, &size) < 0)
1774         return;
1775   if (dg_badinput ((struct sockaddr_in *) &sa))
1776         return;
1777   (void) sprintf (buffer, "%.24s\r\n", ctime (&t));
1778   (void) sendto (s, buffer, strlen (buffer), 0, &sa, sizeof (sa));
1779 }
1780 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME */