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