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