3
0

inetd.c 47 KB

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