sync inetd with slackware-10.2 inetd (OpenBSD-1.79), have destroy bug 455
[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
376   if ((pp = getprotobyname (sep->se_proto + 4)) == NULL) {
377         syslog (LOG_ERR, "%s: getproto: %m", sep->se_proto);
378         return;
379   }
380   n = sizeof ir_sin;
381   if (getsockname (sep->se_fd, (struct sockaddr *) &ir_sin, &n) < 0) {
382         syslog (LOG_ERR, "%s/%s: getsockname: %m",
383                         sep->se_service, sep->se_proto);
384         return;
385   }
386
387   for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
388         (void) pmap_unset (sep->se_rpcprog, n);
389         if (!pmap_set (sep->se_rpcprog, n, pp->p_proto, ntohs (ir_sin.sin_port)))
390           syslog (LOG_ERR, "%s %s: pmap_set: %u %u %u %u: %m",
391                           sep->se_service, sep->se_proto,
392                           sep->se_rpcprog, n, pp->p_proto, ntohs (ir_sin.sin_port));
393   }
394 }
395
396 static void unregister_rpc (servtab_t *sep)
397 {
398   int n;
399
400   for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
401         if (!pmap_unset (sep->se_rpcprog, n))
402           syslog (LOG_ERR, "pmap_unset(%u, %u)", sep->se_rpcprog, n);
403   }
404 }
405 #endif /* CONFIG_FEATURE_INETD_RPC */
406
407 static void freeconfig (servtab_t *cp)
408 {
409   int i;
410
411   free (cp->se_hostaddr);
412   free (cp->se_service);
413   free (cp->se_proto);
414   free (cp->se_user);
415   free (cp->se_group);
416   free (cp->se_server);
417   for (i = 0; i < MAXARGV; i++)
418         if (cp->se_argv[i])
419           free (cp->se_argv[i]);
420 }
421
422 static int bump_nofile (void)
423 {
424 #define FD_CHUNK        32
425
426   struct rlimit rl;
427
428   if (getrlimit (RLIMIT_NOFILE, &rl) < 0) {
429         syslog (LOG_ERR, "getrlimit: %m");
430         return -1;
431   }
432   rl.rlim_cur = MIN (rl.rlim_max, rl.rlim_cur + FD_CHUNK);
433   rl.rlim_cur = MIN (FD_SETSIZE, rl.rlim_cur + FD_CHUNK);
434   if (rl.rlim_cur <= rlim_ofile_cur) {
435         syslog (LOG_ERR, "bump_nofile: cannot extend file limit, max = %d",
436                         (int) rl.rlim_cur);
437         return -1;
438   }
439
440   if (setrlimit (RLIMIT_NOFILE, &rl) < 0) {
441         syslog (LOG_ERR, "setrlimit: %m");
442         return -1;
443   }
444
445   rlim_ofile_cur = rl.rlim_cur;
446   return 0;
447 }
448
449 static void setup (servtab_t *sep)
450 {
451   int on = 1;
452   int r;
453
454   if ((sep->se_fd = socket (sep->se_family, sep->se_socktype, 0)) < 0) {
455         syslog (LOG_ERR, "%s/%s: socket: %m", sep->se_service, sep->se_proto);
456         return;
457   }
458 #define turnon(fd, opt) \
459 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
460   if (turnon (sep->se_fd, SO_REUSEADDR) < 0)
461         syslog (LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
462 #undef turnon
463
464 #ifdef CONFIG_FEATURE_INETD_RPC
465   if (isrpcservice (sep)) {
466         struct passwd *pwd;
467
468         /*
469          * for RPC services, attempt to use a reserved port
470          * if they are going to be running as root.
471          *
472          * Also, zero out the port for all RPC services; let bind()
473          * find one.
474          */
475         sep->se_ctrladdr_in.sin_port = 0;
476         if (sep->se_user && (pwd = getpwnam (sep->se_user)) &&
477                 pwd->pw_uid == 0 && uid == 0)
478           r = bindresvport (sep->se_fd, &sep->se_ctrladdr_in);
479         else {
480           r = bind (sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size);
481           if (r == 0) {
482                 int len = sep->se_ctrladdr_size;
483                 int saveerrno = errno;
484
485                 /* update se_ctrladdr_in.sin_port */
486                 r = getsockname (sep->se_fd, &sep->se_ctrladdr, &len);
487                 if (r <= 0)
488                   errno = saveerrno;
489           }
490         }
491   } else
492 #endif
493         r = bind (sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size);
494   if (r < 0) {
495         syslog (LOG_ERR, "%s/%s (%d): bind: %m",
496                         sep->se_service, sep->se_proto, sep->se_ctrladdr.sa_family);
497         close (sep->se_fd);
498         sep->se_fd = -1;
499         if (!timingout) {
500           timingout = 1;
501           alarm (RETRYTIME);
502         }
503         return;
504   }
505   if (sep->se_socktype == SOCK_STREAM)
506         listen (sep->se_fd, global_queuelen);
507
508   FD_SET (sep->se_fd, &allsock);
509   nsock++;
510   if (sep->se_fd > maxsock) {
511         maxsock = sep->se_fd;
512         if ((rlim_t)maxsock > rlim_ofile_cur - FD_MARGIN)
513           bump_nofile ();
514   }
515 }
516
517 static char *nextline (void)
518 {
519   char *cp;
520   FILE *fd = fconfig;
521
522   if (fgets (line, sizeof (line), fd) == NULL)
523         return (NULL);
524   cp = strchr (line, '\n');
525   if (cp)
526         *cp = '\0';
527   return (line);
528 }
529
530 static char *skip (char **cpp) /* int report; */
531 {
532   char *cp = *cpp;
533   char *start;
534
535 /* erp: */
536   if (*cpp == NULL) {
537         /* if (report) */
538         /* syslog(LOG_ERR, "syntax error in inetd config file"); */
539         return (NULL);
540   }
541
542 again:
543   while (*cp == ' ' || *cp == '\t')
544         cp++;
545   if (*cp == '\0') {
546         int c;
547
548         c = getc (fconfig);
549         (void) ungetc (c, fconfig);
550         if (c == ' ' || c == '\t')
551           if ((cp = nextline ()))
552                 goto again;
553         *cpp = NULL;
554         /* goto erp; */
555         return (NULL);
556   }
557   start = cp;
558   while (*cp && *cp != ' ' && *cp != '\t')
559         cp++;
560   if (*cp != '\0')
561         *cp++ = '\0';
562   /* if ((*cpp = cp) == NULL) */
563   /* goto erp; */
564
565   *cpp = cp;
566   return (start);
567 }
568
569 static servtab_t *new_servtab(void)
570 {
571   servtab_t *sep;
572
573   sep = (servtab_t *) malloc (sizeof (servtab_t));
574   if (sep == NULL) {
575         syslog (LOG_ERR, bb_msg_memory_exhausted);
576         exit (1);
577   }
578   return sep;
579 }
580
581 static servtab_t *dupconfig (servtab_t *sep)
582 {
583   servtab_t *newtab;
584   int argc;
585
586   newtab = new_servtab();
587   memset (newtab, 0, sizeof (servtab_t));
588   newtab->se_service = sep->se_service ? newstr (sep->se_service) : NULL;
589   newtab->se_socktype = sep->se_socktype;
590   newtab->se_family = sep->se_family;
591   newtab->se_proto = sep->se_proto ? newstr (sep->se_proto) : NULL;
592 #ifdef CONFIG_FEATURE_INETD_RPC
593   newtab->se_rpcprog = sep->se_rpcprog;
594   newtab->se_rpcversl = sep->se_rpcversl;
595   newtab->se_rpcversh = sep->se_rpcversh;
596 #endif
597   newtab->se_wait = sep->se_wait;
598   newtab->se_user = sep->se_user ? newstr (sep->se_user) : NULL;
599   newtab->se_group = sep->se_group ? newstr (sep->se_group) : NULL;
600 #ifdef INETD_FEATURE_ENABLED
601   newtab->se_bi = sep->se_bi;
602 #endif
603   newtab->se_server = sep->se_server ? newstr (sep->se_server) : 0;
604
605   for (argc = 0; argc <= MAXARGV; argc++)
606         newtab->se_argv[argc] = sep->se_argv[argc] ?
607           newstr (sep->se_argv[argc]) : NULL;
608   newtab->se_max = sep->se_max;
609
610   return (newtab);
611 }
612
613 static servtab_t *getconfigent (void)
614 {
615   servtab_t *sep;
616   int argc;
617   char *cp, *arg;
618   char *hostdelim;
619   servtab_t *nsep;
620   servtab_t *psep;
621
622   sep = new_servtab();
623
624   /* memset(sep, 0, sizeof *sep); */
625 more:
626   /* freeconfig(sep); */
627
628   while ((cp = nextline ()) && *cp == '#');
629   if (cp == NULL) {
630         /* free(sep); */
631         return (NULL);
632   }
633
634   memset ((char *) sep, 0, sizeof *sep);
635   arg = skip (&cp);
636   if (arg == NULL) {
637         /* A blank line. */
638         goto more;
639   }
640
641   /* Check for a host name. */
642   hostdelim = strrchr (arg, ':');
643   if (hostdelim) {
644         *hostdelim = '\0';
645         sep->se_hostaddr = newstr (arg);
646         arg = hostdelim + 1;
647         /*
648          * If the line is of the form `host:', then just change the
649          * default host for the following lines.
650          */
651         if (*arg == '\0') {
652           arg = skip (&cp);
653           if (cp == NULL) {
654                 free (defhost);
655                 defhost = sep->se_hostaddr;
656                 goto more;
657           }
658         }
659   } else
660         sep->se_hostaddr = newstr (defhost);
661
662   sep->se_service = newstr (arg);
663   arg = skip (&cp);
664
665   if (strcmp (arg, "stream") == 0)
666         sep->se_socktype = SOCK_STREAM;
667   else if (strcmp (arg, "dgram") == 0)
668         sep->se_socktype = SOCK_DGRAM;
669   else if (strcmp (arg, "rdm") == 0)
670         sep->se_socktype = SOCK_RDM;
671   else if (strcmp (arg, "seqpacket") == 0)
672         sep->se_socktype = SOCK_SEQPACKET;
673   else if (strcmp (arg, "raw") == 0)
674         sep->se_socktype = SOCK_RAW;
675   else
676         sep->se_socktype = -1;
677
678   sep->se_proto = newstr (skip (&cp));
679
680   if (strcmp (sep->se_proto, "unix") == 0) {
681         sep->se_family = AF_UNIX;
682   } else {
683         sep->se_family = AF_INET;
684         if (sep->se_proto[strlen (sep->se_proto) - 1] == '6')
685 #ifdef CONFIG_FEATURE_IPV6
686           sep->se_family = AF_INET6;
687 #else
688           syslog (LOG_ERR, "%s: IPV6 not supported", sep->se_proto);
689 #endif
690         if (strncmp (sep->se_proto, "rpc/", 4) == 0) {
691 #ifdef CONFIG_FEATURE_INETD_RPC
692           char *p, *ccp;
693           long l;
694
695           p = strchr (sep->se_service, '/');
696           if (p == 0) {
697                 syslog (LOG_ERR, "%s: no rpc version", sep->se_service);
698                 goto more;
699           }
700           *p++ = '\0';
701           l = strtol (p, &ccp, 0);
702           if (ccp == p || l < 0 || l > INT_MAX) {
703           badafterall:
704                 syslog (LOG_ERR, "%s/%s: bad rpc version", sep->se_service, p);
705                 goto more;
706           }
707           sep->se_rpcversl = sep->se_rpcversh = l;
708           if (*ccp == '-') {
709                 p = ccp + 1;
710                 l = strtol (p, &ccp, 0);
711                 if (ccp == p || l < 0 || l > INT_MAX || l < sep->se_rpcversl || *ccp)
712                   goto badafterall;
713                 sep->se_rpcversh = l;
714           } else if (*ccp != '\0')
715                 goto badafterall;
716 #else
717         syslog (LOG_ERR, "%s: rpc services not supported", sep->se_service);
718 #endif
719         }
720   }
721   arg = skip (&cp);
722   if (arg == NULL)
723         goto more;
724
725   {
726         char *s = strchr (arg, '.');
727         if (s) {
728           *s++ = '\0';
729           sep->se_max = atoi (s);
730         } else
731           sep->se_max = toomany;
732   }
733   sep->se_wait = strcmp (arg, "wait") == 0;
734   /* if ((arg = skip(&cp, 1)) == NULL) */
735   /* goto more; */
736   sep->se_user = newstr (skip (&cp));
737   arg = strchr (sep->se_user, '.');
738   if (arg == NULL)
739         arg = strchr (sep->se_user, ':');
740   if (arg) {
741         *arg++ = '\0';
742         sep->se_group = newstr (arg);
743   }
744   /* if ((arg = skip(&cp, 1)) == NULL) */
745   /* goto more; */
746
747   sep->se_server = newstr (skip (&cp));
748   if (strcmp (sep->se_server, "internal") == 0) {
749 #ifdef INETD_FEATURE_ENABLED
750         const struct biltin *bi;
751
752         for (bi = biltins; bi->bi_service; bi++)
753           if (bi->bi_socktype == sep->se_socktype &&
754                   strcmp (bi->bi_service, sep->se_service) == 0)
755                 break;
756         if (bi->bi_service == 0) {
757           syslog (LOG_ERR, "internal service %s unknown", sep->se_service);
758           goto more;
759         }
760         sep->se_bi = bi;
761         sep->se_wait = bi->bi_wait;
762 #else
763         syslog (LOG_ERR, "internal service %s unknown", sep->se_service);
764         goto more;
765 #endif
766   }
767 #ifdef INETD_FEATURE_ENABLED
768     else
769         sep->se_bi = NULL;
770 #endif
771   argc = 0;
772   for (arg = skip (&cp); cp; arg = skip (&cp)) {
773         if (argc < MAXARGV)
774           sep->se_argv[argc++] = newstr (arg);
775   }
776   while (argc <= MAXARGV)
777         sep->se_argv[argc++] = NULL;
778
779   /*
780    * Now that we've processed the entire line, check if the hostname
781    * specifier was a comma separated list of hostnames. If so
782    * we'll make new entries for each address.
783    */
784   while ((hostdelim = strrchr (sep->se_hostaddr, ',')) != NULL) {
785         nsep = dupconfig (sep);
786
787         /*
788          * NULL terminate the hostname field of the existing entry,
789          * and make a dup for the new entry.
790          */
791         *hostdelim++ = '\0';
792         nsep->se_hostaddr = newstr (hostdelim);
793
794         nsep->se_next = sep->se_next;
795         sep->se_next = nsep;
796   }
797
798   nsep = sep;
799   while (nsep != NULL) {
800         nsep->se_checked = 1;
801         if (nsep->se_family == AF_INET) {
802           if (!strcmp (nsep->se_hostaddr, "*"))
803                 nsep->se_ctrladdr_in.sin_addr.s_addr = INADDR_ANY;
804           else if (!inet_aton (nsep->se_hostaddr, &nsep->se_ctrladdr_in.sin_addr)) {
805                 struct hostent *hp;
806
807                 hp = gethostbyname (nsep->se_hostaddr);
808                 if (hp == 0) {
809                   syslog (LOG_ERR, "%s: unknown host", nsep->se_hostaddr);
810                   nsep->se_checked = 0;
811                   goto skip;
812                 } else if (hp->h_addrtype != AF_INET) {
813                   syslog (LOG_ERR,
814                                   "%s: address isn't an Internet "
815                                   "address", nsep->se_hostaddr);
816                   nsep->se_checked = 0;
817                   goto skip;
818                 } else {
819                   int i = 1;
820
821                   memmove (&nsep->se_ctrladdr_in.sin_addr,
822                                    hp->h_addr_list[0], sizeof (struct in_addr));
823                   while (hp->h_addr_list[i] != NULL) {
824                         psep = dupconfig (nsep);
825                         psep->se_hostaddr = newstr (nsep->se_hostaddr);
826                         psep->se_checked = 1;
827                         memmove (&psep->se_ctrladdr_in.sin_addr,
828                                          hp->h_addr_list[i], sizeof (struct in_addr));
829                         psep->se_ctrladdr_size = sizeof (psep->se_ctrladdr_in);
830                         i++;
831                         /* Prepend to list, don't want to look up its */
832                         /* hostname again. */
833                         psep->se_next = sep;
834                         sep = psep;
835                   }
836                 }
837           }
838         }
839 /* XXX BUG?: is this skip: label supposed to remain? */
840   skip:
841         nsep = nsep->se_next;
842   }
843
844   /*
845    * Finally, free any entries which failed the gethostbyname
846    * check.
847    */
848   psep = NULL;
849   nsep = sep;
850   while (nsep != NULL) {
851         servtab_t *tsep;
852
853         if (nsep->se_checked == 0) {
854           tsep = nsep;
855           if (psep == NULL) {
856                 sep = nsep->se_next;
857                 nsep = sep;
858           } else {
859                 nsep = nsep->se_next;
860                 psep->se_next = nsep;
861           }
862           freeconfig (tsep);
863         } else {
864           nsep->se_checked = 0;
865           psep = nsep;
866           nsep = nsep->se_next;
867         }
868   }
869
870   return (sep);
871 }
872
873 static servtab_t *enter (servtab_t *cp)
874 {
875   servtab_t *sep;
876   int omask;
877
878   sep = new_servtab();
879   *sep = *cp;
880   sep->se_fd = -1;
881 #ifdef CONFIG_FEATURE_INETD_RPC
882   sep->se_rpcprog = -1;
883 #endif
884   omask = sigblock (SIGBLOCK);
885   sep->se_next = servtab;
886   servtab = sep;
887   sigsetmask (omask);
888   return (sep);
889 }
890
891 static int matchconf (servtab_t *old, servtab_t *new)
892 {
893   if (strcmp (old->se_service, new->se_service) != 0)
894         return (0);
895
896   if (strcmp (old->se_hostaddr, new->se_hostaddr) != 0)
897         return (0);
898
899   if (strcmp (old->se_proto, new->se_proto) != 0)
900         return (0);
901
902   /*
903    * If the new servtab is bound to a specific address, check that the
904    * old servtab is bound to the same entry. If the new service is not
905    * bound to a specific address then the check of se_hostaddr above
906    * is sufficient.
907    */
908
909   if (old->se_family == AF_INET && new->se_family == AF_INET &&
910           memcmp (&old->se_ctrladdr_in.sin_addr,
911                           &new->se_ctrladdr_in.sin_addr,
912                           sizeof (new->se_ctrladdr_in.sin_addr)) != 0)
913         return (0);
914
915 #ifdef CONFIG_FEATURE_IPV6
916   if (old->se_family == AF_INET6 && new->se_family == AF_INET6 &&
917           memcmp (&old->se_ctrladdr_in6.sin6_addr,
918                           &new->se_ctrladdr_in6.sin6_addr,
919                           sizeof (new->se_ctrladdr_in6.sin6_addr)) != 0)
920         return (0);
921 #endif
922   return (1);
923 }
924
925 static void config (int sig __attribute__((unused)))
926 {
927   servtab_t *sep, *cp, **sepp;
928   int omask;
929   int add;
930   size_t n;
931   char protoname[10];
932
933   if (!setconfig ()) {
934         syslog (LOG_ERR, "%s: %m", CONFIG);
935         return;
936   }
937   for (sep = servtab; sep; sep = sep->se_next)
938         sep->se_checked = 0;
939   cp = getconfigent ();
940   while (cp != NULL) {
941         for (sep = servtab; sep; sep = sep->se_next)
942           if (matchconf (sep, cp))
943                 break;
944         add = 0;
945         if (sep != 0) {
946           int i;
947
948 #define SWAP(type, a, b) {type c=(type)a; (type)a=(type)b; (type)b=(type)c;}
949
950           omask = sigblock (SIGBLOCK);
951           /*
952            * sep->se_wait may be holding the pid of a daemon
953            * that we're waiting for.  If so, don't overwrite
954            * it unless the config file explicitly says don't
955            * wait.
956            */
957           if (
958 #ifdef INETD_FEATURE_ENABLED
959                    cp->se_bi == 0 &&
960 #endif
961                 (sep->se_wait == 1 || cp->se_wait == 0))
962                 sep->se_wait = cp->se_wait;
963           SWAP (int, cp->se_max, sep->se_max);
964           SWAP (char *, sep->se_user, cp->se_user);
965           SWAP (char *, sep->se_group, cp->se_group);
966           SWAP (char *, sep->se_server, cp->se_server);
967           for (i = 0; i < MAXARGV; i++)
968                 SWAP (char *, sep->se_argv[i], cp->se_argv[i]);
969 #undef SWAP
970
971 #ifdef CONFIG_FEATURE_INETD_RPC
972           if (isrpcservice (sep))
973                 unregister_rpc (sep);
974           sep->se_rpcversl = cp->se_rpcversl;
975           sep->se_rpcversh = cp->se_rpcversh;
976 #endif
977           sigsetmask (omask);
978           freeconfig (cp);
979           add = 1;
980         } else {
981           sep = enter (cp);
982         }
983         sep->se_checked = 1;
984
985         switch (sep->se_family) {
986         case AF_UNIX:
987           if (sep->se_fd != -1)
988                 break;
989           (void) unlink (sep->se_service);
990           n = strlen (sep->se_service);
991           if (n > sizeof sep->se_ctrladdr_un.sun_path - 1)
992                 n = sizeof sep->se_ctrladdr_un.sun_path - 1;
993           safe_strncpy (sep->se_ctrladdr_un.sun_path, sep->se_service, n + 1);
994           sep->se_ctrladdr_un.sun_family = AF_UNIX;
995           sep->se_ctrladdr_size = n + sizeof sep->se_ctrladdr_un.sun_family;
996           setup (sep);
997           break;
998         case AF_INET:
999           sep->se_ctrladdr_in.sin_family = AF_INET;
1000           /* se_ctrladdr_in was set in getconfigent */
1001           sep->se_ctrladdr_size = sizeof sep->se_ctrladdr_in;
1002
1003 #ifdef CONFIG_FEATURE_INETD_RPC
1004           if (isrpcservice (sep)) {
1005                 struct rpcent *rp;
1006
1007                 sep->se_rpcprog = atoi (sep->se_service);
1008                 if (sep->se_rpcprog == 0) {
1009                   rp = getrpcbyname (sep->se_service);
1010                   if (rp == 0) {
1011                         syslog (LOG_ERR, "%s: unknown rpc service", sep->se_service);
1012                         goto serv_unknown;
1013                   }
1014                   sep->se_rpcprog = rp->r_number;
1015                 }
1016                 if (sep->se_fd == -1)
1017                   setup (sep);
1018                 if (sep->se_fd != -1)
1019                   register_rpc (sep);
1020           } else
1021 #endif
1022              {
1023                 u_short port = htons (atoi (sep->se_service));
1024
1025                 if (!port) {
1026                    /*XXX*/ strncpy (protoname, sep->se_proto, sizeof (protoname));
1027                   if (isdigit (protoname[strlen (protoname) - 1]))
1028                         protoname[strlen (protoname) - 1] = '\0';
1029                   sp = getservbyname (sep->se_service, protoname);
1030                   if (sp == 0) {
1031                         syslog (LOG_ERR,
1032                                         "%s/%s: unknown service", sep->se_service, sep->se_proto);
1033                         goto serv_unknown;
1034                   }
1035                   port = sp->s_port;
1036                 }
1037                 if (port != sep->se_ctrladdr_in.sin_port) {
1038                   sep->se_ctrladdr_in.sin_port = port;
1039                   if (sep->se_fd != -1) {
1040                         FD_CLR (sep->se_fd, &allsock);
1041                         nsock--;
1042                         (void) close (sep->se_fd);
1043                   }
1044                   sep->se_fd = -1;
1045                 }
1046                 if (sep->se_fd == -1)
1047                   setup (sep);
1048           }
1049           break;
1050 #ifdef CONFIG_FEATURE_IPV6
1051         case AF_INET6:
1052           sep->se_ctrladdr_in6.sin6_family = AF_INET6;
1053           /* se_ctrladdr_in was set in getconfigent */
1054           sep->se_ctrladdr_size = sizeof sep->se_ctrladdr_in6;
1055
1056 #ifdef CONFIG_FEATURE_INETD_RPC
1057           if (isrpcservice (sep)) {
1058                 struct rpcent *rp;
1059
1060                 sep->se_rpcprog = atoi (sep->se_service);
1061                 if (sep->se_rpcprog == 0) {
1062                   rp = getrpcbyname (sep->se_service);
1063                   if (rp == 0) {
1064                         syslog (LOG_ERR, "%s: unknown rpc service", sep->se_service);
1065                         goto serv_unknown;
1066                   }
1067                   sep->se_rpcprog = rp->r_number;
1068                 }
1069                 if (sep->se_fd == -1)
1070                   setup (sep);
1071                 if (sep->se_fd != -1)
1072                   register_rpc (sep);
1073           } else
1074 #endif
1075                 {
1076                 u_short port = htons (atoi (sep->se_service));
1077
1078                 if (!port) {
1079                    /*XXX*/ strncpy (protoname, sep->se_proto, sizeof (protoname));
1080                   if (isdigit (protoname[strlen (protoname) - 1]))
1081                         protoname[strlen (protoname) - 1] = '\0';
1082                   sp = getservbyname (sep->se_service, protoname);
1083                   if (sp == 0) {
1084                         syslog (LOG_ERR,
1085                                         "%s/%s: unknown service", sep->se_service, sep->se_proto);
1086                         goto serv_unknown;
1087                   }
1088                   port = sp->s_port;
1089                 }
1090                 if (port != sep->se_ctrladdr_in6.sin6_port) {
1091                   sep->se_ctrladdr_in6.sin6_port = port;
1092                   if (sep->se_fd != -1) {
1093                         FD_CLR (sep->se_fd, &allsock);
1094                         nsock--;
1095                         (void) close (sep->se_fd);
1096                   }
1097                   sep->se_fd = -1;
1098                 }
1099                 if (sep->se_fd == -1)
1100                   setup (sep);
1101           }
1102           break;
1103 #endif /* CONFIG_FEATURE_IPV6 */
1104         }
1105   serv_unknown:
1106         if (cp->se_next != NULL) {
1107           servtab_t *tmp = cp;
1108
1109           cp = cp->se_next;
1110           free (tmp);
1111         } else {
1112           free (cp);
1113           cp = getconfigent ();
1114         }
1115   }
1116   endconfig ();
1117   /*
1118    * Purge anything not looked at above.
1119    */
1120   omask = sigblock (SIGBLOCK);
1121   sepp = &servtab;
1122   while ((sep = *sepp)) {
1123         if (sep->se_checked) {
1124           sepp = &sep->se_next;
1125           continue;
1126         }
1127         *sepp = sep->se_next;
1128         if (sep->se_fd != -1) {
1129           FD_CLR (sep->se_fd, &allsock);
1130           nsock--;
1131           (void) close (sep->se_fd);
1132         }
1133 #ifdef CONFIG_FEATURE_INETD_RPC
1134         if (isrpcservice (sep))
1135           unregister_rpc (sep);
1136 #endif
1137         if (sep->se_family == AF_UNIX)
1138           (void) unlink (sep->se_service);
1139         freeconfig (sep);
1140         free (sep);
1141   }
1142   (void) sigsetmask (omask);
1143 }
1144
1145
1146 static void reapchild (int sig __attribute__((unused)))
1147 {
1148   pid_t pid;
1149   int save_errno = errno, status;
1150   servtab_t *sep;
1151
1152   for (;;) {
1153         pid = wait3 (&status, WNOHANG, NULL);
1154         if (pid <= 0)
1155           break;
1156         for (sep = servtab; sep; sep = sep->se_next)
1157           if (sep->se_wait == pid) {
1158                 if (WIFEXITED (status) && WEXITSTATUS (status))
1159                   syslog (LOG_WARNING,
1160                                   "%s: exit status 0x%x",
1161                                   sep->se_server, WEXITSTATUS (status));
1162                 else if (WIFSIGNALED (status))
1163                   syslog (LOG_WARNING,
1164                                   "%s: exit signal 0x%x", sep->se_server, WTERMSIG (status));
1165                 sep->se_wait = 1;
1166                 FD_SET (sep->se_fd, &allsock);
1167                 nsock++;
1168           }
1169   }
1170   errno = save_errno;
1171 }
1172
1173 static void retry (int sig __attribute__((unused)))
1174 {
1175   servtab_t *sep;
1176
1177   timingout = 0;
1178   for (sep = servtab; sep; sep = sep->se_next) {
1179         if (sep->se_fd == -1) {
1180           switch (sep->se_family) {
1181           case AF_UNIX:
1182           case AF_INET:
1183 #ifdef CONFIG_FEATURE_IPV6
1184           case AF_INET6:
1185 #endif
1186                 setup (sep);
1187 #ifdef CONFIG_FEATURE_INETD_RPC
1188                 if (sep->se_fd != -1 && isrpcservice (sep))
1189                   register_rpc (sep);
1190 #endif
1191                 break;
1192           }
1193         }
1194   }
1195 }
1196
1197 static void goaway (int sig __attribute__((unused)))
1198 {
1199   servtab_t *sep;
1200
1201   /* XXX signal race walking sep list */
1202   for (sep = servtab; sep; sep = sep->se_next) {
1203         if (sep->se_fd == -1)
1204           continue;
1205
1206         switch (sep->se_family) {
1207         case AF_UNIX:
1208           (void) unlink (sep->se_service);
1209           break;
1210         case AF_INET:
1211 #ifdef CONFIG_FEATURE_IPV6
1212         case AF_INET6:
1213 #endif
1214 #ifdef CONFIG_FEATURE_INETD_RPC
1215           if (sep->se_wait == 1 && isrpcservice (sep))
1216                 unregister_rpc (sep);   /* XXX signal race */
1217 #endif
1218           break;
1219         }
1220         (void) close (sep->se_fd);
1221   }
1222   (void) unlink (_PATH_INETDPID);
1223   exit (0);
1224 }
1225
1226
1227 #ifdef INETD_SETPROCTITLE
1228 static char **Argv;
1229 static char *LastArg;
1230
1231 static void
1232 inetd_setproctitle (char *a, int s)
1233 {
1234   int size;
1235   char *cp;
1236   struct sockaddr_in prt_sin;
1237   char buf[80];
1238
1239   cp = Argv[0];
1240   size = sizeof (prt_sin);
1241   (void) snprintf (buf, sizeof buf, "-%s", a);
1242   if (getpeername (s, (struct sockaddr *) &prt_sin, &size) == 0) {
1243         char *sa = inet_ntoa (prt_sin.sin_addr);
1244
1245         buf[sizeof (buf) - 1 - strlen (sa) - 3] = '\0';
1246         strcat (buf, " [");
1247         strcat (buf, sa);
1248         strcat (buf, "]");
1249   }
1250   strncpy (cp, buf, LastArg - cp);
1251   cp += strlen (cp);
1252   while (cp < LastArg)
1253         *cp++ = ' ';
1254 }
1255 #endif
1256
1257
1258 int
1259 inetd_main (int argc, char *argv[])
1260 {
1261   servtab_t *sep;
1262   struct passwd *pwd;
1263   struct group *grp = NULL;
1264   int tmpint;
1265   struct sigaction sa, sapipe;
1266   int opt;
1267   pid_t pid;
1268   char buf[50];
1269   char *stoomany;
1270
1271 #ifdef INETD_SETPROCTITLE
1272   extern char **environ;
1273   char **envp = environ;
1274
1275   Argv = argv;
1276   if (envp == 0 || *envp == 0)
1277         envp = argv;
1278   while (*envp)
1279         envp++;
1280   LastArg = envp[-1] + strlen (envp[-1]);
1281 #endif
1282
1283   openlog (bb_applet_name, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
1284
1285   opt = bb_getopt_ulflags (argc, argv, "R:f", &stoomany);
1286   if(opt & 1) {
1287         char *e;
1288
1289         toomany = strtoul (stoomany, &e, 0);
1290         if (!(toomany >= 0 && *e == '\0')) {
1291                 toomany = TOOMANY;
1292                 syslog (LOG_ERR, "-R %s: bad value for service invocation rate", stoomany);
1293         }
1294   }
1295   argc -= optind;
1296   argv += optind;
1297
1298   uid = getuid ();
1299   if (uid != 0)
1300         CONFIG = NULL;
1301   if (argc > 0)
1302         CONFIG = argv[0];
1303   if (CONFIG == NULL)
1304         bb_error_msg_and_die ("non-root must specify a config file");
1305
1306   if (!(opt & 2)) {
1307 #if defined(__uClinux__)
1308         /* reexec for vfork() do continue parent */
1309         vfork_daemon_rexec (0, 0, argc, argv, "-f");
1310 #else
1311         daemon (0, 0);
1312 #endif /* uClinux */
1313   } else {
1314         setsid ();
1315   }
1316
1317   if (uid == 0) {
1318         gid_t gid = getgid ();
1319
1320         /* If run by hand, ensure groups vector gets trashed */
1321         setgroups (1, &gid);
1322   }
1323
1324   {
1325         FILE *fp;
1326
1327         if ((fp = fopen (_PATH_INETDPID, "w")) != NULL) {
1328                 fprintf (fp, "%u\n", getpid ());
1329                 (void) fclose (fp);
1330         }
1331   }
1332
1333   if (getrlimit (RLIMIT_NOFILE, &rlim_ofile) < 0) {
1334         syslog (LOG_ERR, "getrlimit: %m");
1335   } else {
1336         rlim_ofile_cur = rlim_ofile.rlim_cur;
1337         if (rlim_ofile_cur == RLIM_INFINITY)    /* ! */
1338           rlim_ofile_cur = OPEN_MAX;
1339   }
1340
1341   memset ((char *) &sa, 0, sizeof (sa));
1342   sigemptyset (&sa.sa_mask);
1343   sigaddset (&sa.sa_mask, SIGALRM);
1344   sigaddset (&sa.sa_mask, SIGCHLD);
1345   sigaddset (&sa.sa_mask, SIGHUP);
1346   sa.sa_handler = retry;
1347   sigaction (SIGALRM, &sa, NULL);
1348   /* doconfig(); */
1349   config (SIGHUP);
1350   sa.sa_handler = config;
1351   sigaction (SIGHUP, &sa, NULL);
1352   sa.sa_handler = reapchild;
1353   sigaction (SIGCHLD, &sa, NULL);
1354   sa.sa_handler = goaway;
1355   sigaction (SIGTERM, &sa, NULL);
1356   sa.sa_handler = goaway;
1357   sigaction (SIGINT, &sa, NULL);
1358   sa.sa_handler = SIG_IGN;
1359   sigaction (SIGPIPE, &sa, &sapipe);
1360
1361   {
1362         /* space for daemons to overwrite environment for ps */
1363 #define DUMMYSIZE       100
1364         char dummy[DUMMYSIZE];
1365
1366         (void) memset (dummy, 'x', DUMMYSIZE - 1);
1367         dummy[DUMMYSIZE - 1] = '\0';
1368
1369         (void) setenv ("inetd_dummy", dummy, 1);
1370   }
1371
1372   for (;;) {
1373         int n, ctrl = -1;
1374         fd_set readable;
1375
1376         if (nsock == 0) {
1377           (void) sigblock (SIGBLOCK);
1378           while (nsock == 0)
1379                 sigpause (0L);
1380           (void) sigsetmask (0L);
1381         }
1382
1383         readable = allsock;
1384         if ((n = select (maxsock + 1, &readable, NULL, NULL, NULL)) <= 0) {
1385           if (n < 0 && errno != EINTR) {
1386                 syslog (LOG_WARNING, "select: %m");
1387                 sleep (1);
1388           }
1389           continue;
1390         }
1391         for (sep = servtab; n && sep; sep = sep->se_next)
1392           if (sep->se_fd != -1 && FD_ISSET (sep->se_fd, &readable)) {
1393                 n--;
1394                 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
1395                   ctrl = accept (sep->se_fd, NULL, NULL);
1396                   if (ctrl < 0) {
1397                         if (errno == EINTR)
1398                           continue;
1399                         syslog (LOG_WARNING, "accept (for %s): %m", sep->se_service);
1400                         continue;
1401                   }
1402                   if (sep->se_family == AF_INET && sep->se_socktype == SOCK_STREAM) {
1403                         struct sockaddr_in peer;
1404                         int plen = sizeof (peer);
1405
1406                         if (getpeername (ctrl, (struct sockaddr *) &peer, &plen) < 0) {
1407                           syslog (LOG_WARNING, "could not getpeername");
1408                           close (ctrl);
1409                           continue;
1410                         }
1411                         if (ntohs (peer.sin_port) == 20) {
1412                           /* XXX ftp bounce */
1413                           close (ctrl);
1414                           continue;
1415                         }
1416                   }
1417                 } else
1418                   ctrl = sep->se_fd;
1419                 (void) sigblock (SIGBLOCK);
1420                 pid = 0;
1421 #ifdef INETD_FEATURE_ENABLED
1422                 if (sep->se_bi == 0 || sep->se_bi->bi_fork)
1423 #endif
1424                 {
1425                   if (sep->se_count++ == 0)
1426                         (void) gettimeofday (&sep->se_time, NULL);
1427                   else if (toomany > 0 && sep->se_count >= sep->se_max) {
1428                         struct timeval now;
1429
1430                         (void) gettimeofday (&now, NULL);
1431                         if (now.tv_sec - sep->se_time.tv_sec > CNT_INTVL) {
1432                           sep->se_time = now;
1433                           sep->se_count = 1;
1434                         } else {
1435                           if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1436                                 close (ctrl);
1437                           if (sep->se_family == AF_INET &&
1438                                   ntohs (sep->se_ctrladdr_in.sin_port) >= IPPORT_RESERVED) {
1439                                 /*
1440                                  * Cannot close it -- there are
1441                                  * thieves on the system.
1442                                  * Simply ignore the connection.
1443                                  */
1444                                 --sep->se_count;
1445                                 continue;
1446                           }
1447                           syslog (LOG_ERR,
1448                                           "%s/%s server failing (looping), service terminated",
1449                                           sep->se_service, sep->se_proto);
1450                           if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1451                                 close (ctrl);
1452                           FD_CLR (sep->se_fd, &allsock);
1453                           (void) close (sep->se_fd);
1454                           sep->se_fd = -1;
1455                           sep->se_count = 0;
1456                           nsock--;
1457                           sigsetmask (0L);
1458                           if (!timingout) {
1459                                 timingout = 1;
1460                                 alarm (RETRYTIME);
1461                           }
1462                           continue;
1463                         }
1464                   }
1465                   pid = fork ();
1466                 }
1467                 if (pid < 0) {
1468                   syslog (LOG_ERR, "fork: %m");
1469                   if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1470                         close (ctrl);
1471                   sigsetmask (0L);
1472                   sleep (1);
1473                   continue;
1474                 }
1475                 if (pid && sep->se_wait) {
1476                   sep->se_wait = pid;
1477                   FD_CLR (sep->se_fd, &allsock);
1478                   nsock--;
1479                 }
1480                 sigsetmask (0L);
1481                 if (pid == 0) {
1482 #ifdef INETD_FEATURE_ENABLED
1483                   if (sep->se_bi) {
1484                         (*sep->se_bi->bi_fn) (ctrl, sep);
1485                   } else
1486 #endif
1487                         {
1488                         if ((pwd = getpwnam (sep->se_user)) == NULL) {
1489                           syslog (LOG_ERR, "getpwnam: %s: No such user", sep->se_user);
1490                           if (sep->se_socktype != SOCK_STREAM)
1491                                 recv (0, buf, sizeof (buf), 0);
1492                           _exit (1);
1493                         }
1494                         if (setsid () < 0)
1495                           syslog (LOG_ERR, "%s: setsid: %m", sep->se_service);
1496                         if (sep->se_group && (grp = getgrnam (sep->se_group)) == NULL) {
1497                           syslog (LOG_ERR, "getgrnam: %s: No such group", sep->se_group);
1498                           if (sep->se_socktype != SOCK_STREAM)
1499                                 recv (0, buf, sizeof (buf), 0);
1500                           _exit (1);
1501                         }
1502                         if (uid != 0) {
1503                           /* a user running private inetd */
1504                           if (uid != pwd->pw_uid)
1505                                 _exit (1);
1506                         } else if (pwd->pw_uid) {
1507                           if (sep->se_group) {
1508                                 pwd->pw_gid = grp->gr_gid;
1509                           }
1510                           setgid ((gid_t) pwd->pw_gid);
1511                           initgroups (pwd->pw_name, pwd->pw_gid);
1512                           setuid ((uid_t) pwd->pw_uid);
1513                         } else if (sep->se_group) {
1514                           setgid (grp->gr_gid);
1515                           setgroups (1, &grp->gr_gid);
1516                         }
1517                         dup2 (ctrl, 0);
1518                         close (ctrl);
1519                         dup2 (0, 1);
1520                         dup2 (0, 2);
1521                         if (rlim_ofile.rlim_cur != rlim_ofile_cur)
1522                           if (setrlimit (RLIMIT_NOFILE, &rlim_ofile) < 0)
1523                                 syslog (LOG_ERR, "setrlimit: %m");
1524                         closelog ();
1525                         for (tmpint = rlim_ofile_cur - 1; --tmpint > 2;)
1526                           (void) close (tmpint);
1527                         sigaction (SIGPIPE, &sapipe, NULL);
1528                         execv (sep->se_server, sep->se_argv);
1529                         if (sep->se_socktype != SOCK_STREAM)
1530                           recv (0, buf, sizeof (buf), 0);
1531                         syslog (LOG_ERR, "execv %s: %m", sep->se_server);
1532                         _exit (1);
1533                   }
1534                 }
1535                 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
1536                   close (ctrl);
1537           }
1538   }
1539 }
1540
1541 /*
1542  * Internet services provided internally by inetd:
1543  */
1544 #define BUFSIZE 4096
1545
1546 #if defined(CONFIG_FEATURE_INETD_SUPPORT_BILTIN_ECHO) || \
1547     defined(CONFIG_FEATURE_INETD_SUPPORT_BILTIN_CHARGEN) || \
1548     defined(CONFIG_FEATURE_INETD_SUPPORT_BILTIN_DAYTIME)
1549 static int dg_badinput (struct sockaddr_in *dg_sin)
1550 {
1551   if (ntohs (dg_sin->sin_port) < IPPORT_RESERVED)
1552         return (1);
1553   if (dg_sin->sin_addr.s_addr == htonl (INADDR_BROADCAST))
1554         return (1);
1555   /* XXX compare against broadcast addresses in SIOCGIFCONF list? */
1556   return (0);
1557 }
1558 #endif
1559
1560 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BILTIN_ECHO
1561 /* Echo service -- echo data back */
1562 /* ARGSUSED */
1563 static void
1564 echo_stream (int s, servtab_t *sep)
1565 {
1566   char buffer[BUFSIZE];
1567   int i;
1568
1569   inetd_setproctitle (sep->se_service, s);
1570   while ((i = read (s, buffer, sizeof (buffer))) > 0 &&
1571                  write (s, buffer, i) > 0);
1572   exit (0);
1573 }
1574
1575 /* Echo service -- echo data back */
1576 /* ARGSUSED */
1577 static void
1578 echo_dg (int s, servtab_t *sep __attribute__((unused)))
1579 {
1580   char buffer[BUFSIZE];
1581   int i, size;
1582   /* struct sockaddr_storage ss; */
1583   struct sockaddr sa;
1584
1585   size = sizeof (sa);
1586   if ((i = recvfrom (s, buffer, sizeof (buffer), 0, &sa, &size)) < 0)
1587         return;
1588   if (dg_badinput ((struct sockaddr_in *) &sa))
1589         return;
1590   (void) sendto (s, buffer, i, 0, &sa, sizeof (sa));
1591 }
1592 #endif  /* CONFIG_FEATURE_INETD_SUPPORT_BILTIN_ECHO */
1593
1594 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BILTIN_DISCARD
1595 /* Discard service -- ignore data */
1596 /* ARGSUSED */
1597 static void
1598 discard_stream (int s, servtab_t *sep)
1599 {
1600   char buffer[BUFSIZE];
1601
1602   inetd_setproctitle (sep->se_service, s);
1603   while ((errno = 0, read (s, buffer, sizeof (buffer)) > 0) ||
1604                  errno == EINTR);
1605   exit (0);
1606 }
1607
1608 /* Discard service -- ignore data */
1609 /* ARGSUSED */
1610 static void
1611 discard_dg (int s, servtab_t *sep __attribute__((unused)))
1612 {
1613   char buffer[BUFSIZE];
1614
1615   (void) read (s, buffer, sizeof (buffer));
1616 }
1617 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BILTIN_DISCARD */
1618
1619
1620 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BILTIN_CHARGEN
1621 #define LINESIZ 72
1622 static char ring[128];
1623 static char *endring;
1624
1625 static void
1626 initring (void)
1627 {
1628   int i;
1629
1630   endring = ring;
1631
1632   for (i = 0; i <= 128; ++i)
1633         if (isprint (i))
1634           *endring++ = i;
1635 }
1636
1637 /* Character generator */
1638 /* ARGSUSED */
1639 static void
1640 chargen_stream (int s, servtab_t *sep)
1641 {
1642   char *rs;
1643   int len;
1644   char text[LINESIZ + 2];
1645
1646   inetd_setproctitle (sep->se_service, s);
1647
1648   if (!endring) {
1649         initring ();
1650         rs = ring;
1651   }
1652
1653   text[LINESIZ] = '\r';
1654   text[LINESIZ + 1] = '\n';
1655   for (rs = ring;;) {
1656         if ((len = endring - rs) >= LINESIZ)
1657           memmove (text, rs, LINESIZ);
1658         else {
1659           memmove (text, rs, len);
1660           memmove (text + len, ring, LINESIZ - len);
1661         }
1662         if (++rs == endring)
1663           rs = ring;
1664         if (write (s, text, sizeof (text)) != sizeof (text))
1665           break;
1666   }
1667   exit (0);
1668 }
1669
1670 /* Character generator */
1671 /* ARGSUSED */
1672 static void
1673 chargen_dg (int s, servtab_t *sep __attribute__((unused)))
1674 {
1675   /* struct sockaddr_storage ss; */
1676   struct sockaddr sa;
1677   static char *rs;
1678   int len, size;
1679   char text[LINESIZ + 2];
1680
1681   if (endring == 0) {
1682         initring ();
1683         rs = ring;
1684   }
1685
1686   size = sizeof (sa);
1687   if (recvfrom (s, text, sizeof (text), 0, &sa, &size) < 0)
1688         return;
1689   if (dg_badinput ((struct sockaddr_in *) &sa))
1690         return;
1691
1692   if ((len = endring - rs) >= LINESIZ)
1693         memmove (text, rs, LINESIZ);
1694   else {
1695         memmove (text, rs, len);
1696         memmove (text + len, ring, LINESIZ - len);
1697   }
1698   if (++rs == endring)
1699         rs = ring;
1700   text[LINESIZ] = '\r';
1701   text[LINESIZ + 1] = '\n';
1702   (void) sendto (s, text, sizeof (text), 0, &sa, sizeof (sa));
1703 }
1704 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BILTIN_CHARGEN */
1705
1706
1707 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BILTIN_TIME
1708 /*
1709  * Return a machine readable date and time, in the form of the
1710  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
1711  * returns the number of seconds since midnight, Jan 1, 1970,
1712  * we must add 2208988800 seconds to this figure to make up for
1713  * some seventy years Bell Labs was asleep.
1714  */
1715
1716 static u_int machtime (void)
1717 {
1718   struct timeval tv;
1719
1720   if (gettimeofday (&tv, NULL) < 0) {
1721         fprintf (stderr, "Unable to get time of day\n");
1722         return (0L);
1723   }
1724   return (htonl ((u_int) tv.tv_sec + 2208988800UL));
1725 }
1726
1727 /* ARGSUSED */
1728 static void
1729 machtime_stream (int s, servtab_t *sep __attribute__((unused)))
1730 {
1731   u_int result;
1732
1733   result = machtime ();
1734   (void) write (s, (char *) &result, sizeof (result));
1735 }
1736
1737 /* ARGSUSED */
1738 static void
1739 machtime_dg (int s, servtab_t *sep __attribute__((unused)))
1740 {
1741   u_int result;
1742   /* struct sockaddr_storage ss; */
1743   struct sockaddr sa;
1744   struct sockaddr_in *dg_sin;
1745   int size;
1746
1747   size = sizeof (sa);
1748   if (recvfrom (s, (char *) &result, sizeof (result), 0, &sa, &size) < 0)
1749         return;
1750   /* if (dg_badinput((struct sockaddr *)&ss)) */
1751   dg_sin = (struct sockaddr_in *) &sa;
1752   if (dg_sin->sin_addr.s_addr == htonl (INADDR_BROADCAST) ||
1753           ntohs (dg_sin->sin_port) < IPPORT_RESERVED / 2)
1754         return;
1755   result = machtime ();
1756   (void) sendto (s, (char *) &result, sizeof (result), 0, &sa, sizeof (sa));
1757 }
1758 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BILTIN_TIME */
1759
1760
1761 #ifdef CONFIG_FEATURE_INETD_SUPPORT_BILTIN_DAYTIME
1762 /* Return human-readable time of day */
1763 /* ARGSUSED */
1764 static void daytime_stream (int s, servtab_t *sep __attribute__((unused)))
1765 {
1766   char buffer[256];
1767   time_t t;
1768
1769   t = time (NULL);
1770
1771   (void) sprintf (buffer, "%.24s\r\n", ctime (&t));
1772   (void) write (s, buffer, strlen (buffer));
1773 }
1774
1775 /* Return human-readable time of day */
1776 /* ARGSUSED */
1777 void
1778 daytime_dg (int s, servtab_t *sep __attribute__((unused)))
1779 {
1780   char buffer[256];
1781   time_t t;
1782   /* struct sockaddr_storage ss; */
1783   struct sockaddr sa;
1784   int size;
1785
1786   t = time ((time_t *) 0);
1787
1788   size = sizeof (sa);
1789   if (recvfrom (s, buffer, sizeof (buffer), 0, &sa, &size) < 0)
1790         return;
1791   if (dg_badinput ((struct sockaddr_in *) &sa))
1792         return;
1793   (void) sprintf (buffer, "%.24s\r\n", ctime (&t));
1794   (void) sendto (s, buffer, strlen (buffer), 0, &sa, sizeof (sa));
1795 }
1796 #endif /* CONFIG_FEATURE_INETD_SUPPORT_BILTIN_DAYTIME */