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