8a4c9fbf6e0493ef5c07abc00f6f6541a8c47273
[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  *                                      (usually "tcp" or "udp")
67  *      wait/nowait[.max]               single-threaded/multi-threaded, max #
68  *      user[.group] or user[:group]    user/group to run daemon as
69  *      server program                  full path name
70  *      server program arguments        maximum of MAXARGS (20)
71  *
72  * For RPC services
73  *      service name/version            must be in /etc/rpc
74  *      socket type                     stream/dgram/raw/rdm/seqpacket
75  *      rpc/protocol                    "rpc/tcp" etc
76  *      wait/nowait[.max]               single-threaded/multi-threaded
77  *      user[.group] or user[:group]    user to run daemon as
78  *      server program                  full path name
79  *      server program arguments        maximum of MAXARGS (20)
80  *
81  * For non-RPC services, the "service name" can be of the form
82  * hostaddress:servicename, in which case the hostaddress is used
83  * as the host portion of the address to listen on.  If hostaddress
84  * consists of a single `*' character, INADDR_ANY is used.
85  *
86  * A line can also consist of just
87  *      hostaddress:
88  * where hostaddress is as in the preceding paragraph.  Such a line must
89  * have no further fields; the specified hostaddress is remembered and
90  * used for all further lines that have no hostaddress specified,
91  * until the next such line (or EOF).  (This is why * is provided to
92  * allow explicit specification of INADDR_ANY.)  A line
93  *      *:
94  * is implicitly in effect at the beginning of the file.
95  *
96  * The hostaddress specifier may (and often will) contain dots;
97  * the service name must not.
98  *
99  * For RPC services, host-address specifiers are accepted and will
100  * work to some extent; however, because of limitations in the
101  * portmapper interface, it will not work to try to give more than
102  * one line for any given RPC service, even if the host-address
103  * specifiers are different.
104  *
105  * Comment lines are indicated by a `#' in column 1.
106  */
107
108 /* inetd rules for passing file descriptors to children
109  * (http://www.freebsd.org/cgi/man.cgi?query=inetd):
110  *
111  * The wait/nowait entry specifies whether the server that is invoked by
112  * inetd will take over the socket associated with the service access point,
113  * and thus whether inetd should wait for the server to exit before listen-
114  * ing for new service requests.  Datagram servers must use "wait", as
115  * they are always invoked with the original datagram socket bound to the
116  * specified service address.  These servers must read at least one datagram
117  * from the socket before exiting.  If a datagram server connects to its
118  * peer, freeing the socket so inetd can receive further messages on the
119  * socket, it is said to be a "multi-threaded" server; it should read one
120  * datagram from the socket and create a new socket connected to the peer.
121  * It should fork, and the parent should then exit to allow inetd to check
122  * for new service requests to spawn new servers.  Datagram servers which
123  * process all incoming datagrams on a socket and eventually time out are
124  * said to be "single-threaded".  The comsat(8), biff(1) and talkd(8)
125  * utilities are both examples of the latter type of datagram server.  The
126  * tftpd(8) utility is an example of a multi-threaded datagram server.
127  *
128  * Servers using stream sockets generally are multi-threaded and use the
129  * "nowait" entry. Connection requests for these services are accepted by
130  * inetd, and the server is given only the newly-accepted socket connected
131  * to a client of the service.  Most stream-based services operate in this
132  * manner.  Stream-based servers that use "wait" are started with the lis-
133  * tening service socket, and must accept at least one connection request
134  * before exiting.  Such a server would normally accept and process incoming
135  * connection requests until a timeout.
136  */
137
138 /* Here's the scoop concerning the user[:group] feature:
139  * 1) group is not specified:
140  *      a) user = root: NO setuid() or setgid() is done
141  *      b) other:       setgid(primary group as found in passwd)
142  *                      initgroups(name, primary group)
143  *                      setuid()
144  * 2) group is specified:
145  *      a) user = root: setgid(specified group)
146  *                      NO initgroups()
147  *                      NO setuid()
148  *      b) other:       setgid(specified group)
149  *                      initgroups(name, specified group)
150  *                      setuid()
151  */
152
153 #include <syslog.h>
154 #include <sys/un.h>
155 #include "libbb.h"
156
157 #if !BB_MMU
158 /* stream versions of these builtins are forking,
159  * can't do that (easily) on NOMMU */
160 #undef  ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
161 #define ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD 0
162 #undef  ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
163 #define ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN 0
164 #endif
165
166 #if ENABLE_FEATURE_INETD_RPC
167 #include <rpc/rpc.h>
168 #include <rpc/pmap_clnt.h>
169 #endif
170
171 #define _PATH_INETDPID  "/var/run/inetd.pid"
172
173 #define CNT_INTERVAL    60              /* servers in CNT_INTERVAL sec. */
174 #define RETRYTIME       (60*10)         /* retry after bind or server fail */
175
176 #ifndef RLIMIT_NOFILE
177 #define RLIMIT_NOFILE   RLIMIT_OFILE
178 #endif
179
180 #ifndef OPEN_MAX
181 #define OPEN_MAX        64
182 #endif
183
184 /* Reserve some descriptors, 3 stdio + at least: 1 log, 1 conf. file */
185 #define FD_MARGIN       8
186
187 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD \
188  || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO    \
189  || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN \
190  || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME    \
191  || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
192 # define INETD_BUILTINS_ENABLED
193 #endif
194
195 typedef struct servtab_t {
196         /* The most frequently referenced one: */
197         int se_fd;                            /* open descriptor */
198         /* NB: 'biggest fields last' saves on code size (~250 bytes) */
199         /* [addr:]service socktype proto wait user[:group] prog [args] */
200         char *se_local_hostname;              /* addr to listen on */
201         char *se_service;                     /* "80" or "www" or "mount/2[-3]" */
202         /* socktype is in se_socktype */      /* "stream" "dgram" "raw" "rdm" "seqpacket" */
203         char *se_proto;                       /* "unix" or "[rpc/]tcp[6]" */
204 #if ENABLE_FEATURE_INETD_RPC
205         int se_rpcprog;                       /* rpc program number */
206         int se_rpcver_lo;                     /* rpc program lowest version */
207         int se_rpcver_hi;                     /* rpc program highest version */
208 #define is_rpc_service(sep)       ((sep)->se_rpcver_lo != 0)
209 #else
210 #define is_rpc_service(sep)       0
211 #endif
212         pid_t se_wait;                        /* 0:"nowait", 1:"wait" */
213         socktype_t se_socktype;               /* SOCK_STREAM/DGRAM/RDM/... */
214         family_t se_family;                   /* AF_UNIX/INET[6] */
215         smallint se_proto_no;                 /* almost "getprotobyname(se_proto)" */
216         smallint se_checked;                  /* looked at during merge */
217         char *se_user;                        /* user name to run as */
218         char *se_group;                       /* group name to run as, can be NULL */
219 #ifdef INETD_BUILTINS_ENABLED
220         const struct builtin *se_builtin;     /* if built-in, description */
221 #endif
222 // TODO: wrong algorithm!!!
223         unsigned se_max;                      /* max # of instances of this service */
224         unsigned se_count;                    /* number started since se_time */
225         unsigned se_time;                     /* start of se_count */
226         struct servtab_t *se_next;
227         len_and_sockaddr *se_lsa;
228         char *se_program;                     /* server program */
229 #define MAXARGV 20
230         char *se_argv[MAXARGV + 1];           /* program arguments */
231 } servtab_t;
232
233 #ifdef INETD_BUILTINS_ENABLED
234                 /* Echo received data */
235 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
236 static void echo_stream(int, servtab_t *);
237 static void echo_dg(int, servtab_t *);
238 #endif
239                 /* Internet /dev/null */
240 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
241 static void discard_stream(int, servtab_t *);
242 static void discard_dg(int, servtab_t *);
243 #endif
244                 /* Return 32 bit time since 1900 */
245 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME
246 static void machtime_stream(int, servtab_t *);
247 static void machtime_dg(int, servtab_t *);
248 #endif
249                 /* Return human-readable time */
250 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
251 static void daytime_stream(int, servtab_t *);
252 static void daytime_dg(int, servtab_t *);
253 #endif
254                 /* Familiar character generator */
255 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
256 static void chargen_stream(int, servtab_t *);
257 static void chargen_dg(int, servtab_t *);
258 #endif
259
260 struct builtin {
261         const char *bi_service;         /* internally provided service name */
262         uint8_t bi_fork;                /* 1 if stream fn should run in child */
263         /* All builtins are "nowait" */
264         /* uint8_t bi_wait; */          /* 1 if should wait for child */
265         void (*bi_stream_fn)(int, servtab_t *);
266         void (*bi_dgram_fn)(int, servtab_t *);
267 };
268
269 static const struct builtin builtins[] = {
270 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
271         /* Echo received data */
272         { "echo", 1, echo_stream, echo_dg },
273 #endif
274 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
275         /* Internet /dev/null */
276         { "discard", 1, discard_stream, discard_dg },
277 #endif
278 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
279         /* Familiar character generator */
280         { "chargen", 1, chargen_stream, chargen_dg },
281 #endif
282 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME
283         /* Return 32 bit time since 1900 */
284         { "time", 0, machtime_stream, machtime_dg },
285 #endif
286 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
287         /* Return human-readable time */
288         { "daytime", 0, daytime_stream, daytime_dg },
289 #endif
290 };
291 #endif /* INETD_BUILTINS_ENABLED */
292
293 struct globals {
294         rlim_t rlim_ofile_cur;
295         struct rlimit rlim_ofile;
296         servtab_t *serv_list;
297         int global_queuelen;
298         int prev_maxsock;
299         int maxsock;
300         unsigned max_concurrency;
301         smallint alarm_armed;
302         uid_t real_uid; /* user ID who ran us */
303         unsigned config_lineno;
304         const char *config_filename;
305         FILE *fconfig;
306         char *default_local_hostname;
307 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
308         char *endring;
309         char *ringpos;
310         char ring[128];
311 #endif
312         fd_set allsock;
313         /* Used in next_line(), and as scratch read buffer */
314         char line[256];          /* _at least_ 256, see LINE_SIZE */
315 };
316 #define G (*(struct globals*)&bb_common_bufsiz1)
317 enum { LINE_SIZE = COMMON_BUFSIZE - offsetof(struct globals, line) };
318 struct BUG_G_too_big {
319         char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
320 };
321 #define rlim_ofile_cur  (G.rlim_ofile_cur )
322 #define rlim_ofile      (G.rlim_ofile     )
323 #define serv_list       (G.serv_list      )
324 #define global_queuelen (G.global_queuelen)
325 #define prev_maxsock    (G.prev_maxsock   )
326 #define maxsock         (G.maxsock        )
327 #define max_concurrency (G.max_concurrency)
328 #define alarm_armed     (G.alarm_armed    )
329 #define real_uid        (G.real_uid       )
330 #define config_lineno   (G.config_lineno  )
331 #define config_filename (G.config_filename)
332 #define fconfig         (G.fconfig        )
333 #define default_local_hostname (G.default_local_hostname)
334 #define first_ps_byte   (G.first_ps_byte  )
335 #define last_ps_byte    (G.last_ps_byte   )
336 #define endring         (G.endring        )
337 #define ringpos         (G.ringpos        )
338 #define ring            (G.ring           )
339 #define allsock         (G.allsock        )
340 #define line            (G.line           )
341 #define INIT_G() do { \
342         rlim_ofile_cur = OPEN_MAX; \
343         global_queuelen = 128; \
344         config_filename = "/etc/inetd.conf"; \
345 } while (0)
346
347 static void maybe_close(int fd)
348 {
349         if (fd >= 0)
350                 close(fd);
351 }
352
353 // TODO: move to libbb?
354 static len_and_sockaddr *xzalloc_lsa(int family)
355 {
356         len_and_sockaddr *lsa;
357         int sz;
358
359         sz = sizeof(struct sockaddr_in);
360 #if ENABLE_FEATURE_IPV6
361         if (family == AF_INET6)
362                 sz = sizeof(struct sockaddr_in6);
363 #endif
364         lsa = xzalloc(LSA_LEN_SIZE + sz);
365         lsa->len = sz;
366         lsa->u.sa.sa_family = family;
367         return lsa;     
368 }
369
370
371 static void rearm_alarm(void)
372 {
373         if (!alarm_armed) {
374                 alarm_armed = 1;
375                 alarm(RETRYTIME);
376         }
377 }
378
379 static void block_CHLD_HUP_ALRM(sigset_t *m)
380 {
381         sigemptyset(m);
382         sigaddset(m, SIGCHLD);
383         sigaddset(m, SIGHUP);
384         sigaddset(m, SIGALRM);
385         sigprocmask(SIG_BLOCK, m, NULL);
386 }
387
388 static void unblock_sigs(sigset_t *m)
389 {
390         sigprocmask(SIG_UNBLOCK, m, NULL);
391 }
392
393 #if ENABLE_FEATURE_INETD_RPC
394 static void register_rpc(servtab_t *sep)
395 {
396         int n;
397         struct sockaddr_in ir_sin;
398         socklen_t size;
399
400         size = sizeof(ir_sin);
401         if (getsockname(sep->se_fd, (struct sockaddr *) &ir_sin, &size) < 0) {
402                 bb_perror_msg("getsockname");
403                 return;
404         }
405
406         for (n = sep->se_rpcver_lo; n <= sep->se_rpcver_hi; n++) {
407                 pmap_unset(sep->se_rpcprog, n);
408                 if (!pmap_set(sep->se_rpcprog, n, sep->se_proto_no, ntohs(ir_sin.sin_port)))
409                         bb_perror_msg("%s %s: pmap_set(%u,%u,%u,%u)",
410                                 sep->se_service, sep->se_proto,
411                                 sep->se_rpcprog, n, sep->se_proto_no, ntohs(ir_sin.sin_port));
412         }
413 }
414
415 static void unregister_rpc(servtab_t *sep)
416 {
417         int n;
418
419         for (n = sep->se_rpcver_lo; n <= sep->se_rpcver_hi; n++) {
420                 if (!pmap_unset(sep->se_rpcprog, n))
421                         bb_perror_msg("pmap_unset(%u,%u)", sep->se_rpcprog, n);
422         }
423 }
424 #endif /* FEATURE_INETD_RPC */
425
426 static void bump_nofile(void)
427 {
428         enum { FD_CHUNK = 32 };
429         struct rlimit rl;
430
431         /* Never fails under Linux (except if you pass it bad arguments) */
432         getrlimit(RLIMIT_NOFILE, &rl);
433         rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
434         rl.rlim_cur = MIN(FD_SETSIZE, rl.rlim_cur + FD_CHUNK);
435         if (rl.rlim_cur <= rlim_ofile_cur) {
436                 bb_error_msg("can't extend file limit, max = %d",
437                                                 (int) rl.rlim_cur);
438                 return;
439         }
440
441         if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
442                 bb_perror_msg("setrlimit");
443                 return;
444         }
445
446         rlim_ofile_cur = rl.rlim_cur;
447 }
448
449 static void remove_fd_from_set(int fd)
450 {
451         if (fd >= 0) {
452                 FD_CLR(fd, &allsock);
453                 maxsock = -1;
454         }
455 }
456
457 static void add_fd_to_set(int fd)
458 {
459         if (fd >= 0) {
460                 FD_SET(fd, &allsock);
461                 if (maxsock >= 0 && fd > maxsock) {
462                         prev_maxsock = maxsock = fd;
463                         if ((rlim_t)maxsock > rlim_ofile_cur - FD_MARGIN)
464                                 bump_nofile();
465                 }
466         }
467 }
468
469 static void recalculate_maxsock(void)
470 {
471         int fd = 0;
472         while (fd <= prev_maxsock) {
473                 if (FD_ISSET(fd, &allsock))
474                         maxsock = fd;
475                 fd++;
476         }
477         prev_maxsock = maxsock;
478         if ((rlim_t)maxsock > rlim_ofile_cur - FD_MARGIN)
479                 bump_nofile();
480 }
481
482 static void prepare_socket_fd(servtab_t *sep)
483 {
484         int r, fd;
485
486         fd = socket(sep->se_family, sep->se_socktype, 0);
487         if (fd < 0) {
488                 bb_perror_msg("socket");
489                 return;
490         }
491         setsockopt_reuseaddr(fd);
492
493 #if ENABLE_FEATURE_INETD_RPC
494         if (is_rpc_service(sep)) {
495                 struct passwd *pwd;
496
497                 /* zero out the port for all RPC services; let bind()
498                  * find one. */
499                 set_nport(sep->se_lsa, 0);
500
501                 /* for RPC services, attempt to use a reserved port
502                  * if they are going to be running as root. */
503                 if (real_uid == 0 && sep->se_family == AF_INET
504                  && (pwd = getpwnam(sep->se_user)) != NULL
505                  && pwd->pw_uid == 0
506                 ) {
507                         r = bindresvport(fd, &sep->se_lsa->u.sin);
508                 } else {
509                         r = bind(fd, &sep->se_lsa->u.sa, sep->se_lsa->len);
510                 }
511                 if (r == 0) {
512                         int saveerrno = errno;
513                         /* update lsa with port# */
514                         getsockname(fd, &sep->se_lsa->u.sa, &sep->se_lsa->len);
515                         errno = saveerrno;
516                 }
517         } else
518 #endif
519         {
520                 if (sep->se_family == AF_UNIX) {
521                         struct sockaddr_un *sun;
522                         sun = (struct sockaddr_un*)&(sep->se_lsa->u.sa);
523                         unlink(sun->sun_path);
524                 }
525                 r = bind(fd, &sep->se_lsa->u.sa, sep->se_lsa->len);
526         }
527         if (r < 0) {
528                 bb_perror_msg("%s/%s: bind",
529                                 sep->se_service, sep->se_proto);
530                 close(fd);
531                 rearm_alarm();
532                 return;
533         }
534         if (sep->se_socktype == SOCK_STREAM)
535                 listen(fd, global_queuelen);
536
537         add_fd_to_set(fd);
538         sep->se_fd = fd;
539 }
540
541 static int reopen_config_file(void)
542 {
543         free(default_local_hostname);
544         default_local_hostname = xstrdup("*");
545         if (fconfig != NULL)
546                 fclose(fconfig);
547         config_lineno = 0;
548         fconfig = fopen_or_warn(config_filename, "r");
549         return (fconfig != NULL);
550 }
551
552 static void close_config_file(void)
553 {
554         if (fconfig) {
555                 fclose(fconfig);
556                 fconfig = NULL;
557         }
558 }
559
560 static char *next_line(void)
561 {
562         if (fgets(line, LINE_SIZE, fconfig) == NULL)
563                 return NULL;
564         config_lineno++;
565         *strchrnul(line, '\n') = '\0';
566         return line;
567 }
568
569 static char *next_word(char **cpp)
570 {
571         char *start;
572         char *cp = *cpp;
573
574         if (cp == NULL)
575                 return NULL;
576  again:
577         while (*cp == ' ' || *cp == '\t')
578                 cp++;
579         if (*cp == '\0') {
580                 int c = getc(fconfig);
581                 ungetc(c, fconfig);
582                 if (c == ' ' || c == '\t') {
583                         cp = next_line();
584                         if (cp)
585                                 goto again;
586                 }
587                 *cpp = NULL;
588                 return NULL;
589         }
590         start = cp;
591         while (*cp && *cp != ' ' && *cp != '\t')
592                 cp++;
593         if (*cp != '\0')
594                 *cp++ = '\0';
595
596         *cpp = cp;
597         return start;
598 }
599
600 static void free_servtab_strings(servtab_t *cp)
601 {
602         int i;
603
604         free(cp->se_local_hostname);
605         free(cp->se_service);
606         free(cp->se_proto);
607         free(cp->se_user);
608         free(cp->se_group);
609         free(cp->se_lsa); /* not a string in fact */
610         free(cp->se_program);
611         for (i = 0; i < MAXARGV; i++)
612                 free(cp->se_argv[i]);
613 }
614
615 static servtab_t *new_servtab(void)
616 {
617         servtab_t *newtab = xzalloc(sizeof(servtab_t));
618         newtab->se_fd = -1; /* paranoia */
619         return newtab;
620 }
621
622 static servtab_t *dup_servtab(servtab_t *sep)
623 {
624         servtab_t *newtab;
625         int argc;
626
627         newtab = new_servtab();
628         *newtab = *sep; /* struct copy */
629         /* deep-copying strings */
630         newtab->se_service = xstrdup(newtab->se_service);
631         newtab->se_proto = xstrdup(newtab->se_proto);
632         newtab->se_user = xstrdup(newtab->se_user);
633         newtab->se_group = xstrdup(newtab->se_group);
634         newtab->se_program = xstrdup(newtab->se_program);
635         for (argc = 0; argc <= MAXARGV; argc++)
636                 newtab->se_argv[argc] = xstrdup(newtab->se_argv[argc]);
637         /* NB: se_fd, se_hostaddr and se_next are always
638          * overwrittend by callers, so we don't bother resetting them
639          * to NULL/0/-1 etc */
640
641         return newtab;
642 }
643
644 /* gcc generates much more code if this is inlined */
645 static NOINLINE servtab_t *parse_one_line(void)
646 {
647         int argc;
648         char *p, *cp, *arg;
649         char *hostdelim;
650         servtab_t *sep;
651         servtab_t *nsep;
652  new:
653         sep = new_servtab();
654  more:
655         while ((cp = next_line()) && *cp == '#')
656                 continue; /* skip comment lines */
657         if (cp == NULL) {
658                 free(sep);
659                 return NULL;
660         }
661
662         arg = next_word(&cp);
663         if (arg == NULL) {
664                 /* A blank line. */
665                 goto more;
666         }
667
668         /* [host:]service socktype proto wait user[:group] prog [args] */
669         /* Check for "host:...." line */
670         hostdelim = strrchr(arg, ':');
671         if (hostdelim) {
672                 *hostdelim = '\0';
673                 sep->se_local_hostname = xstrdup(arg);
674                 arg = hostdelim + 1;
675                 if (*arg == '\0') {
676                         arg = next_word(&cp);
677                         if (arg == NULL) {
678                                 /* Line has just "host:", change the
679                                  * default host for the following lines. */
680                                 free(default_local_hostname);
681                                 default_local_hostname = sep->se_local_hostname;
682                                 goto more;
683                         }
684                 }
685         } else
686                 sep->se_local_hostname = xstrdup(default_local_hostname);
687
688         /* service socktype proto wait user[:group] prog [args] */
689         sep->se_service = xstrdup(arg);
690         /* socktype proto wait user[:group] prog [args] */
691         arg = next_word(&cp);
692         if (arg == NULL) {
693  parse_err:
694                 bb_error_msg("parse error on line %u, line is ignored",
695                                 config_lineno);
696                 free_servtab_strings(sep);
697                 /* Just "goto more" can make sep to carry over e.g.
698                  * "rpc"-ness (by having se_rpcver_lo != 0).
699                  * We will be more paranoid: */
700                 free(sep);
701                 goto new;
702         }
703         {
704                 static int8_t SOCK_xxx[] ALIGN1 = {
705                         -1,
706                         SOCK_STREAM, SOCK_DGRAM, SOCK_RDM,
707                         SOCK_SEQPACKET, SOCK_RAW
708                 };
709                 sep->se_socktype = SOCK_xxx[1 + index_in_strings(
710                         "stream""\0" "dgram""\0" "rdm""\0"
711                         "seqpacket""\0" "raw""\0"
712                         , arg)];
713         }
714
715         /* {unix,[rpc/]{tcp,udp}[6]} wait user[:group] prog [args] */
716         sep->se_proto = arg = xstrdup(next_word(&cp));
717         if (arg == NULL)
718                 goto parse_err;
719         if (strcmp(arg, "unix") == 0) {
720                 sep->se_family = AF_UNIX;
721         } else {
722                 char *six;
723                 sep->se_family = AF_INET;
724                 six = last_char_is(arg, '6');
725                 if (six) {
726 #if ENABLE_FEATURE_IPV6
727                         *six = '\0';
728                         sep->se_family = AF_INET6;
729 #else
730                         bb_error_msg("%s: no support for IPv6", sep->se_proto);
731                         goto parse_err;
732 #endif
733                 }
734                 if (strncmp(arg, "rpc/", 4) == 0) {
735 #if ENABLE_FEATURE_INETD_RPC
736                         unsigned n;
737                         arg += 4;
738                         p = strchr(sep->se_service, '/');
739                         if (p == NULL) {
740                                 bb_error_msg("no rpc version: '%s'", sep->se_service);
741                                 goto parse_err;
742                         }
743                         *p++ = '\0';
744                         n = bb_strtou(p, &p, 10);
745                         if (n > INT_MAX) {
746  bad_ver_spec:
747                                 bb_error_msg("bad rpc version");
748                                 goto parse_err;
749                         }
750                         sep->se_rpcver_lo = sep->se_rpcver_hi = n;
751                         if (*p == '-') {
752                                 p++;
753                                 n = bb_strtou(p, &p, 10);
754                                 if (n > INT_MAX || n < sep->se_rpcver_lo)
755                                         goto bad_ver_spec;
756                                 sep->se_rpcver_hi = n;
757                         }
758                         if (*p != '\0')
759                                 goto bad_ver_spec;
760 #else
761                         bb_error_msg("no support for rpc services");
762                         goto parse_err;
763 #endif
764                 }
765                 /* we don't really need getprotobyname()! */
766                 if (strcmp(arg, "tcp") == 0)
767                         sep->se_proto_no = 6;
768                 if (strcmp(arg, "udp") == 0)
769                         sep->se_proto_no = 17;
770                 if (six)
771                         *six = '6';
772                 if (!sep->se_proto_no) /* not tcp/udp?? */
773                         goto parse_err;
774         }
775
776         /* [no]wait[.max] user[:group] prog [args] */
777         arg = next_word(&cp);
778         if (arg == NULL)
779                 goto parse_err;
780         sep->se_max = max_concurrency;
781         p = strchr(arg, '.');
782         if (p) {
783                 *p++ = '\0';
784                 sep->se_max = bb_strtou(p, NULL, 10);
785                 if (errno)
786                         goto parse_err;
787         }
788         sep->se_wait = (strcmp(arg, "wait") == 0);
789
790         /* user[:group] prog [args] */
791         sep->se_user = xstrdup(next_word(&cp));
792         if (sep->se_user == NULL)
793                 goto parse_err;
794         arg = strchr(sep->se_user, '.');
795         if (arg == NULL)
796                 arg = strchr(sep->se_user, ':');
797         if (arg) {
798                 *arg++ = '\0';
799                 sep->se_group = xstrdup(arg);
800         }
801
802         /* prog [args] */
803         sep->se_program = xstrdup(next_word(&cp));
804         if (sep->se_program == NULL)
805                 goto parse_err;
806 #ifdef INETD_BUILTINS_ENABLED
807         /* sep->se_builtin = NULL; - done by new_servtab() */
808         if (strcmp(sep->se_program, "internal") == 0
809          && (sep->se_socktype == SOCK_STREAM
810              || sep->se_socktype == SOCK_DGRAM)
811         ) {
812                 int i;
813                 for (i = 0; i < ARRAY_SIZE(builtins); i++)
814                         if (strcmp(builtins[i].bi_service, sep->se_service) == 0)
815                                 goto found_bi;
816                 bb_error_msg("unknown internal service %s", sep->se_service);
817                 goto parse_err;
818  found_bi:
819                 sep->se_builtin = &builtins[i];
820                 sep->se_wait = 0; /* = builtins[i].bi_wait; - always 0 */
821         }
822 #endif
823         argc = 0;
824         while ((arg = next_word(&cp)) != NULL && argc < MAXARGV) {
825                 sep->se_argv[argc++] = xstrdup(arg);
826         }
827         /* while (argc <= MAXARGV) */
828         /*      sep->se_argv[argc++] = NULL; - done by new_servtab() */
829
830         /*
831          * Now that we've processed the entire line, check if the hostname
832          * specifier was a comma separated list of hostnames. If so
833          * we'll make new entries for each address.
834          */
835         while ((hostdelim = strrchr(sep->se_local_hostname, ',')) != NULL) {
836                 nsep = dup_servtab(sep);
837                 /*
838                  * NUL terminate the hostname field of the existing entry,
839                  * and make a dup for the new entry.
840                  */
841                 *hostdelim++ = '\0';
842                 nsep->se_local_hostname = xstrdup(hostdelim);
843                 nsep->se_next = sep->se_next;
844                 sep->se_next = nsep;
845         }
846
847         /* Was doing it here: */
848         /* DNS resolution, create copies for each IP address */
849
850         return sep;
851 }
852
853 static servtab_t *insert_in_servlist(servtab_t *cp)
854 {
855         servtab_t *sep;
856         sigset_t omask;
857
858         sep = new_servtab();
859         *sep = *cp; /* struct copy */
860         sep->se_fd = -1;
861 #if ENABLE_FEATURE_INETD_RPC
862         sep->se_rpcprog = -1;
863 #endif
864         block_CHLD_HUP_ALRM(&omask);
865         sep->se_next = serv_list;
866         serv_list = sep;
867         unblock_sigs(&omask);
868         return sep;
869 }
870
871 static int same_serv_addr_proto(servtab_t *old, servtab_t *new)
872 {
873         if (strcmp(old->se_local_hostname, new->se_local_hostname) != 0)
874                 return 0;
875         if (strcmp(old->se_service, new->se_service) != 0)
876                 return 0;
877         if (strcmp(old->se_proto, new->se_proto) != 0)
878                 return 0;
879         return 1;
880 }
881
882 static void reread_config_file(int sig ATTRIBUTE_UNUSED)
883 {
884         servtab_t *sep, *cp, **sepp;
885         len_and_sockaddr *lsa;
886         sigset_t omask;
887         unsigned n;
888         uint16_t port;
889
890         if (!reopen_config_file())
891                 return;
892         for (sep = serv_list; sep; sep = sep->se_next)
893                 sep->se_checked = 0;
894
895         goto first_line;
896         while (1) {
897                 if (cp == NULL) {
898  first_line:
899                         cp = parse_one_line();
900                         if (cp == NULL)
901                                 break;
902                 }
903                 for (sep = serv_list; sep; sep = sep->se_next)
904                         if (same_serv_addr_proto(sep, cp))
905                                 goto equal_servtab;
906                 /* not an "equal" servtab */
907                 sep = insert_in_servlist(cp);
908                 goto after_check;
909  equal_servtab:
910                 {
911                         int i;
912
913                         block_CHLD_HUP_ALRM(&omask);
914 #if ENABLE_FEATURE_INETD_RPC
915                         if (is_rpc_service(sep))
916                                 unregister_rpc(sep);
917                         sep->se_rpcver_lo = cp->se_rpcver_lo;
918                         sep->se_rpcver_hi = cp->se_rpcver_hi;
919 #endif
920                         if (cp->se_wait == 0) {
921                                 /* New config says "nowait". If old one
922                                  * was "wait", we currently may be waiting
923                                  * for a child (and not accepting connects).
924                                  * Stop waiting, start listening again.
925                                  * (if it's not true, this op is harmless) */
926                                 add_fd_to_set(sep->se_fd);
927                         }
928                         sep->se_wait = cp->se_wait;
929                         sep->se_max = cp->se_max;
930                         /* string fields need more love - we don't want to leak them */
931 #define SWAP(type, a, b) do { type c = (type)a; a = (type)b; b = (type)c; } while (0)
932                         SWAP(char*, sep->se_user, cp->se_user);
933                         SWAP(char*, sep->se_group, cp->se_group);
934                         SWAP(char*, sep->se_program, cp->se_program);
935                         for (i = 0; i < MAXARGV; i++)
936                                 SWAP(char*, sep->se_argv[i], cp->se_argv[i]);
937 #undef SWAP
938                         unblock_sigs(&omask);
939                         free_servtab_strings(cp);
940                 }
941  after_check:
942                 /* cp->string_fields are consumed by insert_in_servlist()
943                  * or freed at this point, cp itself is not yet freed. */
944                 sep->se_checked = 1;
945
946                 /* create new len_and_sockaddr */
947                 switch (sep->se_family) {
948                         struct sockaddr_un *sun;
949                 case AF_UNIX:
950                         /* we have poor infrastructure for AF_UNIX... */
951                         n = strlen(sep->se_service);
952                         if (n > sizeof(sun->sun_path) - 1)
953                                 n = sizeof(sun->sun_path) - 1;
954                         lsa = xzalloc(LSA_LEN_SIZE + sizeof(struct sockaddr_un));
955                         lsa->len = sizeof(struct sockaddr_un);
956                         sun = (struct sockaddr_un*)&lsa->u.sa;
957                         sun->sun_family = AF_UNIX;
958                         strncpy(sun->sun_path, sep->se_service, n);
959                         break;
960
961                 default: /* case AF_INET, case AF_INET6 */
962                         n = bb_strtou(sep->se_service, NULL, 10);
963 #if ENABLE_FEATURE_INETD_RPC
964                         if (is_rpc_service(sep)) {
965                                 sep->se_rpcprog = n;
966                                 if (errno) { /* se_service is not numeric */
967                                         struct rpcent *rp = getrpcbyname(sep->se_service);
968                                         if (rp == NULL) {
969                                                 bb_error_msg("%s: unknown rpc service", sep->se_service);
970                                                 goto next_cp;
971                                         }
972                                         sep->se_rpcprog = rp->r_number;
973                                 }
974                                 if (sep->se_fd == -1)
975                                         prepare_socket_fd(sep);
976                                 if (sep->se_fd != -1)
977                                         register_rpc(sep);
978                                 goto next_cp;
979                         }
980 #endif
981                         /* what port to listen on? */
982                         port = htons(n);
983                         if (errno || n > 0xffff) { /* se_service is not numeric */
984                                 char protoname[4];
985                                 struct servent *sp;
986                                 /* can result only in "tcp" or "udp": */
987                                 safe_strncpy(protoname, sep->se_proto, 4);
988                                 sp = getservbyname(sep->se_service, protoname);
989                                 if (sp == NULL) {
990                                         bb_error_msg("%s/%s: unknown service",
991                                                         sep->se_service, sep->se_proto);
992                                         goto next_cp;
993                                 }
994                                 port = sp->s_port;
995                         }
996                         if (LONE_CHAR(sep->se_local_hostname, '*')) {
997                                 lsa = xzalloc_lsa(sep->se_family);
998                                 set_nport(lsa, port);
999                         } else {
1000                                 lsa = host_and_af2sockaddr(sep->se_local_hostname,
1001                                                 ntohs(port), sep->se_family);
1002                                 if (!lsa) {
1003                                         bb_error_msg("%s/%s: unknown host '%s'",
1004                                                 sep->se_service, sep->se_proto,
1005                                                 sep->se_local_hostname);
1006                                         goto next_cp;
1007                                 }
1008                         }
1009                         break;
1010                 } /* end of "switch (sep->se_family)" */
1011
1012                 /* did lsa change? Then close/open */
1013                 if (sep->se_lsa == NULL
1014                  || lsa->len != sep->se_lsa->len
1015                  || memcmp(&lsa->u.sa, &sep->se_lsa->u.sa, lsa->len) != 0
1016                 ) {
1017                         remove_fd_from_set(sep->se_fd);
1018                         maybe_close(sep->se_fd);
1019                         free(sep->se_lsa);
1020                         sep->se_lsa = lsa;
1021                         sep->se_fd = -1;
1022                 } else {
1023                         free(lsa);
1024                 }
1025                 if (sep->se_fd == -1)
1026                         prepare_socket_fd(sep);
1027  next_cp:
1028                 sep = cp->se_next;
1029                 free(cp);
1030                 cp = sep;
1031         } /* end of "while (1) parse lines" */
1032         close_config_file();
1033
1034         /* Purge anything not looked at above - these are stale entries,
1035          * new config file doesnt have them. */
1036         block_CHLD_HUP_ALRM(&omask);
1037         sepp = &serv_list;
1038         while ((sep = *sepp)) {
1039                 if (sep->se_checked) {
1040                         sepp = &sep->se_next;
1041                         continue;
1042                 }
1043                 *sepp = sep->se_next;
1044                 remove_fd_from_set(sep->se_fd);
1045                 maybe_close(sep->se_fd);
1046 #if ENABLE_FEATURE_INETD_RPC
1047                 if (is_rpc_service(sep))
1048                         unregister_rpc(sep);
1049 #endif
1050                 if (sep->se_family == AF_UNIX)
1051                         unlink(sep->se_service);
1052                 free_servtab_strings(sep);
1053                 free(sep);
1054         }
1055         unblock_sigs(&omask);
1056 }
1057
1058 static void reap_child(int sig ATTRIBUTE_UNUSED)
1059 {
1060         pid_t pid;
1061         int status;
1062         servtab_t *sep;
1063         int save_errno = errno;
1064
1065         for (;;) {
1066                 pid = wait_any_nohang(&status);
1067                 if (pid <= 0)
1068                         break;
1069                 for (sep = serv_list; sep; sep = sep->se_next)
1070                         if (sep->se_wait == pid) {
1071                                 /* One of our "wait" services */
1072                                 if (WIFEXITED(status) && WEXITSTATUS(status))
1073                                         bb_error_msg("%s: exit status 0x%x",
1074                                                         sep->se_program, WEXITSTATUS(status));
1075                                 else if (WIFSIGNALED(status))
1076                                         bb_error_msg("%s: exit signal 0x%x",
1077                                                         sep->se_program, WTERMSIG(status));
1078                                 sep->se_wait = 1;
1079                                 add_fd_to_set(sep->se_fd);
1080                         }
1081         }
1082         errno = save_errno;
1083 }
1084
1085 static void retry_network_setup(int sig ATTRIBUTE_UNUSED)
1086 {
1087         servtab_t *sep;
1088
1089         alarm_armed = 0;
1090         for (sep = serv_list; sep; sep = sep->se_next) {
1091                 if (sep->se_fd == -1) {
1092                         prepare_socket_fd(sep);
1093 #if ENABLE_FEATURE_INETD_RPC
1094                         if (sep->se_fd != -1 && is_rpc_service(sep))
1095                                 register_rpc(sep);
1096 #endif
1097                 }
1098         }
1099 }
1100
1101 static void clean_up_and_exit(int sig ATTRIBUTE_UNUSED)
1102 {
1103         servtab_t *sep;
1104
1105         /* XXX signal race walking sep list */
1106         for (sep = serv_list; sep; sep = sep->se_next) {
1107                 if (sep->se_fd == -1)
1108                         continue;
1109
1110                 switch (sep->se_family) {
1111                 case AF_UNIX:
1112                         unlink(sep->se_service);
1113                         break;
1114                 default: /* case AF_INET, AF_INET6 */
1115 #if ENABLE_FEATURE_INETD_RPC
1116                         if (sep->se_wait == 1 && is_rpc_service(sep))
1117                                 unregister_rpc(sep);   /* XXX signal race */
1118 #endif
1119                         break;
1120                 }
1121                 if (ENABLE_FEATURE_CLEAN_UP)
1122                         close(sep->se_fd);
1123         }
1124         remove_pidfile(_PATH_INETDPID);
1125         exit(0);
1126 }
1127
1128 int inetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1129 int inetd_main(int argc, char **argv)
1130 {
1131         struct sigaction sa, saved_pipe_handler;
1132         servtab_t *sep, *sep2;
1133         struct passwd *pwd;
1134         struct group *grp = grp; /* for compiler */
1135         int opt;
1136         pid_t pid;
1137         sigset_t omask;
1138
1139         INIT_G();
1140
1141         real_uid = getuid();
1142         if (real_uid != 0) /* run by non-root user */
1143                 config_filename = NULL;
1144
1145         opt_complementary = "R+:q+"; /* -q N, -R N */
1146         opt = getopt32(argv, "R:feq:", &max_concurrency, &global_queuelen);
1147         argv += optind;
1148         //argc -= optind;
1149         if (argv[0])
1150                 config_filename = argv[0];
1151         if (config_filename == NULL)
1152                 bb_error_msg_and_die("non-root must specify config file");
1153         if (!(opt & 2))
1154                 bb_daemonize_or_rexec(0, argv - optind);
1155         else
1156                 bb_sanitize_stdio();
1157         if (!(opt & 4)) {
1158                 openlog(applet_name, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
1159                 logmode = LOGMODE_SYSLOG;
1160         }
1161
1162         if (real_uid == 0) {
1163                 /* run by root, ensure groups vector gets trashed */
1164                 gid_t gid = getgid();
1165                 setgroups(1, &gid);
1166         }
1167
1168         write_pidfile(_PATH_INETDPID);
1169
1170         /* never fails under Linux (except if you pass it bad arguments) */
1171         getrlimit(RLIMIT_NOFILE, &rlim_ofile);
1172         rlim_ofile_cur = rlim_ofile.rlim_cur;
1173         if (rlim_ofile_cur == RLIM_INFINITY)    /* ! */
1174                 rlim_ofile_cur = OPEN_MAX;
1175
1176         memset(&sa, 0, sizeof(sa));
1177         /*sigemptyset(&sa.sa_mask); - memset did it */
1178         sigaddset(&sa.sa_mask, SIGALRM);
1179         sigaddset(&sa.sa_mask, SIGCHLD);
1180         sigaddset(&sa.sa_mask, SIGHUP);
1181         sa.sa_handler = retry_network_setup;
1182         sigaction(SIGALRM, &sa, NULL);
1183         sa.sa_handler = reread_config_file;
1184         sigaction(SIGHUP, &sa, NULL);
1185         sa.sa_handler = reap_child;
1186         sigaction(SIGCHLD, &sa, NULL);
1187         sa.sa_handler = clean_up_and_exit;
1188         sigaction(SIGTERM, &sa, NULL);
1189         sa.sa_handler = clean_up_and_exit;
1190         sigaction(SIGINT, &sa, NULL);
1191         sa.sa_handler = SIG_IGN;
1192         sigaction(SIGPIPE, &sa, &saved_pipe_handler);
1193
1194         reread_config_file(SIGHUP); /* load config from file */
1195
1196         for (;;) {
1197                 int ready_fd_cnt;
1198                 int ctrl, accepted_fd;
1199                 fd_set readable;
1200
1201                 if (maxsock < 0)
1202                         recalculate_maxsock();
1203
1204                 readable = allsock; /* struct copy */
1205                 /* if there are no fds to wait on, we will block
1206                  * until signal wakes us up */
1207                 ready_fd_cnt = select(maxsock + 1, &readable, NULL, NULL, NULL);
1208                 if (ready_fd_cnt < 0) {
1209                         if (errno != EINTR) {
1210                                 bb_perror_msg("select");
1211                                 sleep(1);
1212                         }
1213                         continue;
1214                 }
1215
1216                 for (sep = serv_list; ready_fd_cnt && sep; sep = sep->se_next) {
1217                         if (sep->se_fd == -1 || !FD_ISSET(sep->se_fd, &readable))
1218                                 continue;
1219
1220                         ready_fd_cnt--;
1221                         ctrl = sep->se_fd;
1222                         accepted_fd = -1;
1223                         if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
1224                                 ctrl = accepted_fd = accept(sep->se_fd, NULL, NULL);
1225                                 if (ctrl < 0) {
1226                                         if (errno != EINTR)
1227                                                 bb_perror_msg("accept (for %s)", sep->se_service);
1228                                         continue;
1229                                 }
1230                         }
1231
1232                         block_CHLD_HUP_ALRM(&omask);
1233                         pid = 0;
1234 #ifdef INETD_BUILTINS_ENABLED
1235                         /* do we need to fork? */
1236                         if (sep->se_builtin == NULL
1237                          || (sep->se_socktype == SOCK_STREAM
1238                              && sep->se_builtin->bi_fork))
1239 #endif
1240                         {
1241                                 if (sep->se_max != 0) {
1242                                         if (++sep->se_count == 1)
1243                                                 sep->se_time = monotonic_sec();
1244                                         else if (sep->se_count >= sep->se_max) {
1245                                                 unsigned now = monotonic_sec();
1246                                                 /* did we accumulate se_max connects too quickly? */
1247                                                 if (now - sep->se_time <= CNT_INTERVAL) {
1248                                                         bb_error_msg("%s/%s: too many connections, pausing",
1249                                                                         sep->se_service, sep->se_proto);
1250                                                         remove_fd_from_set(sep->se_fd);
1251                                                         close(sep->se_fd);
1252                                                         sep->se_fd = -1;
1253                                                         sep->se_count = 0;
1254                                                         rearm_alarm(); /* will revive it in RETRYTIME sec */
1255                                                         unblock_sigs(&omask);
1256                                                         maybe_close(accepted_fd);
1257                                                         continue; /* -> check next fd in fd set */
1258                                                 }
1259                                                 sep->se_count = 0;
1260                                         }
1261                                 }
1262                                 /* on NOMMU, streamed echo, chargen and discard
1263                                  * builtins wouldn't work, but they are
1264                                  * not allowed on NOMMU (ifdefed out) */
1265 #ifdef INETD_BUILTINS_ENABLED
1266                                 if (BB_MMU && sep->se_builtin)
1267                                         pid = fork();
1268                                 else
1269 #endif
1270                                         pid = vfork();
1271
1272                                 if (pid < 0) { /* fork error */
1273                                         bb_perror_msg("fork");
1274                                         sleep(1);
1275                                         unblock_sigs(&omask);
1276                                         maybe_close(accepted_fd);
1277                                         continue; /* -> check next fd in fd set */
1278                                 }
1279                                 if (pid == 0)
1280                                         pid--; /* -1: "we did fork and we are child" */
1281                         }
1282                         /* if pid == 0 here, we never forked */
1283
1284                         if (pid > 0) { /* parent */
1285                                 if (sep->se_wait) {
1286                                         sep->se_wait = pid;
1287                                         remove_fd_from_set(sep->se_fd);
1288                                         /* we passed listening socket to child,
1289                                          * will wait for child to terminate */
1290                                 }
1291                                 unblock_sigs(&omask);
1292                                 maybe_close(accepted_fd);
1293                                 continue; /* -> check next fd in fd set */
1294                         }
1295
1296                         /* we are either child or didn't fork at all */
1297 #ifdef INETD_BUILTINS_ENABLED
1298                         if (sep->se_builtin) {
1299                                 if (pid) { /* "pid" is -1: we did fork */
1300                                         close(sep->se_fd); /* listening socket */
1301                                         logmode = 0; /* make xwrite etc silent */
1302                                 }
1303                                 unblock_sigs(&omask);
1304                                 if (sep->se_socktype == SOCK_STREAM)
1305                                         sep->se_builtin->bi_stream_fn(ctrl, sep);
1306                                 else
1307                                         sep->se_builtin->bi_dgram_fn(ctrl, sep);
1308                                 if (pid) /* we did fork */
1309                                         _exit(0);
1310                                 maybe_close(accepted_fd);
1311                                 continue; /* -> check next fd in fd set */
1312                         }
1313 #endif
1314                         /* child. prepare env and exec program */
1315                         setsid();
1316                         pwd = getpwnam(sep->se_user);
1317                         if (pwd == NULL) {
1318                                 bb_error_msg("%s: no such user", sep->se_user);
1319                                 goto do_exit1;
1320                         }
1321                         if (sep->se_group && (grp = getgrnam(sep->se_group)) == NULL) {
1322                                 bb_error_msg("%s: no such group", sep->se_group);
1323                                 goto do_exit1;
1324                         }
1325                         if (real_uid != 0 && real_uid != pwd->pw_uid) {
1326                                 /* a user running private inetd */
1327                                 bb_error_msg("non-root must run services as himself");
1328                                 goto do_exit1;
1329                         }
1330                         if (pwd->pw_uid) {
1331                                 if (sep->se_group)
1332                                         pwd->pw_gid = grp->gr_gid;
1333                                 xsetgid(pwd->pw_gid);
1334                                 initgroups(pwd->pw_name, pwd->pw_gid);
1335                                 xsetuid(pwd->pw_uid);
1336                         } else if (sep->se_group) {
1337                                 xsetgid(grp->gr_gid);
1338                                 setgroups(1, &grp->gr_gid);
1339                         }
1340                         if (rlim_ofile.rlim_cur != rlim_ofile_cur)
1341                                 if (setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
1342                                         bb_perror_msg("setrlimit");
1343                         closelog();
1344                         xmove_fd(ctrl, 0);
1345                         dup2(0, 1);
1346                         dup2(0, 2);
1347                         /* NB: among others, this loop closes listening socket
1348                          * for nowait stream children */
1349                         for (sep2 = serv_list; sep2; sep2 = sep2->se_next)
1350                                 maybe_close(sep2->se_fd);
1351                         sigaction(SIGPIPE, &saved_pipe_handler, NULL);
1352                         unblock_sigs(&omask);
1353                         BB_EXECVP(sep->se_program, sep->se_argv);
1354                         bb_perror_msg("exec %s", sep->se_program);
1355  do_exit1:
1356                         /* eat packet in udp case */
1357                         if (sep->se_socktype != SOCK_STREAM)
1358                                 recv(0, line, LINE_SIZE, MSG_DONTWAIT);
1359                         _exit(1);
1360                 } /* for (sep = servtab...) */
1361         } /* for (;;) */
1362 }
1363
1364 /*
1365  * Internet services provided internally by inetd:
1366  */
1367 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
1368 /* Echo service -- echo data back. */
1369 /* ARGSUSED */
1370 static void echo_stream(int s, servtab_t *sep ATTRIBUTE_UNUSED)
1371 {
1372 #if BB_MMU
1373         while (1) {
1374                 ssize_t sz = safe_read(s, line, LINE_SIZE);
1375                 if (sz <= 0)
1376                         break;
1377                 xwrite(s, line, sz);
1378         }
1379 #else
1380         static const char *const args[] = { "cat", NULL };
1381         BB_EXECVP("cat", (char**)args);
1382         _exit(1);
1383 #endif
1384 }
1385 static void echo_dg(int s, servtab_t *sep)
1386 {
1387         enum { BUFSIZE = 12*1024 }; /* for jumbo sized packets! :) */
1388         char *buf = xmalloc(BUFSIZE); /* too big for stack */
1389         int sz;
1390         len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
1391
1392         lsa->len = sep->se_lsa->len;
1393         /* dgram builtins are non-forking - DONT BLOCK! */
1394         sz = recvfrom(s, buf, BUFSIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len);
1395         if (sz > 0)
1396                 sendto(s, buf, sz, 0, &lsa->u.sa, lsa->len);
1397         free(buf);
1398 }
1399 #endif  /* FEATURE_INETD_SUPPORT_BUILTIN_ECHO */
1400
1401
1402 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
1403 /* Discard service -- ignore data. MMU arches only. */
1404 /* ARGSUSED */
1405 static void discard_stream(int s, servtab_t *sep ATTRIBUTE_UNUSED)
1406 {
1407         while (safe_read(s, line, LINE_SIZE) > 0)
1408                 continue;
1409 }
1410 /* ARGSUSED */
1411 static void discard_dg(int s, servtab_t *sep ATTRIBUTE_UNUSED)
1412 {
1413         /* dgram builtins are non-forking - DONT BLOCK! */
1414         recv(s, line, LINE_SIZE, MSG_DONTWAIT);
1415 }
1416 #endif /* FEATURE_INETD_SUPPORT_BUILTIN_DISCARD */
1417
1418
1419 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
1420 #define LINESIZ 72
1421 static void initring(void)
1422 {
1423         int i;
1424
1425         endring = ring;
1426         for (i = 0; i <= 128; ++i)
1427                 if (isprint(i))
1428                         *endring++ = i;
1429 }
1430 /* Character generator. MMU arches only. */
1431 /* ARGSUSED */
1432 static void chargen_stream(int s, servtab_t *sep)
1433 {
1434         char *rs;
1435         int len;
1436         char text[LINESIZ + 2];
1437
1438         if (!endring) {
1439                 initring();
1440                 rs = ring;
1441         }
1442
1443         text[LINESIZ] = '\r';
1444         text[LINESIZ + 1] = '\n';
1445         rs = ring;
1446         for (;;) {
1447                 len = endring - rs;
1448                 if (len >= LINESIZ)
1449                         memmove(text, rs, LINESIZ);
1450                 else {
1451                         memmove(text, rs, len);
1452                         memmove(text + len, ring, LINESIZ - len);
1453                 }
1454                 if (++rs == endring)
1455                         rs = ring;
1456                 xwrite(s, text, sizeof(text));
1457         }
1458 }
1459 /* ARGSUSED */
1460 static void chargen_dg(int s, servtab_t *sep)
1461 {
1462         int len;
1463         char text[LINESIZ + 2];
1464         len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
1465
1466         /* Eat UDP packet which started it all */
1467         /* dgram builtins are non-forking - DONT BLOCK! */
1468         lsa->len = sep->se_lsa->len;
1469         if (recvfrom(s, text, sizeof(text), MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
1470                 return;
1471
1472         if (!endring) {
1473                 initring();
1474                 ringpos = ring;
1475         }
1476
1477         len = endring - ringpos;
1478         if (len >= LINESIZ)
1479                 memmove(text, ringpos, LINESIZ);
1480         else {
1481                 memmove(text, ringpos, len);
1482                 memmove(text + len, ring, LINESIZ - len);
1483         }
1484         if (++ringpos == endring)
1485                 ringpos = ring;
1486         text[LINESIZ] = '\r';
1487         text[LINESIZ + 1] = '\n';
1488         sendto(s, text, sizeof(text), 0, &lsa->u.sa, lsa->len);
1489 }
1490 #endif /* FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN */
1491
1492
1493 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME
1494 /*
1495  * Return a machine readable date and time, in the form of the
1496  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
1497  * returns the number of seconds since midnight, Jan 1, 1970,
1498  * we must add 2208988800 seconds to this figure to make up for
1499  * some seventy years Bell Labs was asleep.
1500  */
1501 static unsigned machtime(void)
1502 {
1503         struct timeval tv;
1504
1505         gettimeofday(&tv, NULL);
1506         return htonl((uint32_t)(tv.tv_sec + 2208988800));
1507 }
1508 /* ARGSUSED */
1509 static void machtime_stream(int s, servtab_t *sep ATTRIBUTE_UNUSED)
1510 {
1511         uint32_t result;
1512
1513         result = machtime();
1514         full_write(s, &result, sizeof(result));
1515 }
1516 static void machtime_dg(int s, servtab_t *sep)
1517 {
1518         uint32_t result;
1519         len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
1520
1521         lsa->len = sep->se_lsa->len;
1522         if (recvfrom(s, line, LINE_SIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
1523                 return;
1524
1525         result = machtime();
1526         sendto(s, &result, sizeof(result), 0, &lsa->u.sa, lsa->len);
1527 }
1528 #endif /* FEATURE_INETD_SUPPORT_BUILTIN_TIME */
1529
1530
1531 #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
1532 /* Return human-readable time of day */
1533 /* ARGSUSED */
1534 static void daytime_stream(int s, servtab_t *sep ATTRIBUTE_UNUSED)
1535 {
1536         time_t t;
1537
1538         t = time(NULL);
1539         fdprintf(s, "%.24s\r\n", ctime(&t));
1540 }
1541 static void daytime_dg(int s, servtab_t *sep)
1542 {
1543         time_t t;
1544         len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
1545
1546         lsa->len = sep->se_lsa->len;
1547         if (recvfrom(s, line, LINE_SIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
1548                 return;
1549
1550         t = time(NULL);
1551         sprintf(line, "%.24s\r\n", ctime(&t));
1552         sendto(s, line, strlen(line), 0, &lsa->u.sa, lsa->len);
1553 }
1554 #endif /* FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME */