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