inetd.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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 echo_stream(int, servtab_t *);
  226. static void echo_dg(int, servtab_t *);
  227. #endif
  228. /* Internet /dev/null */
  229. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
  230. static void discard_stream(int, servtab_t *);
  231. static void 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 machtime_stream(int, servtab_t *);
  236. static void machtime_dg(int, servtab_t *);
  237. #endif
  238. /* Return human-readable time */
  239. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
  240. static void daytime_stream(int, servtab_t *);
  241. static void daytime_dg(int, servtab_t *);
  242. #endif
  243. /* Familiar character generator */
  244. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  245. static void chargen_stream(int, servtab_t *);
  246. static void 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 *);
  253. void (*bi_dgram_fn)(int, servtab_t *);
  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. };
  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 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. /* catch mixups. "<service> stream udp ..." == wtf */
  720. if (sep->se_socktype == SOCK_STREAM) {
  721. if (sep->se_proto_no == IPPROTO_UDP)
  722. goto parse_err;
  723. }
  724. if (sep->se_socktype == SOCK_DGRAM) {
  725. if (sep->se_proto_no == IPPROTO_TCP)
  726. goto parse_err;
  727. }
  728. // bb_info_msg(
  729. // "ENTRY[%s][%s][%s][%d][%d][%d][%d][%d][%s][%s][%s]",
  730. // sep->se_local_hostname, sep->se_service, sep->se_proto, sep->se_wait, sep->se_proto_no,
  731. // sep->se_max, sep->se_count, sep->se_time, sep->se_user, sep->se_group, sep->se_program);
  732. /* check if the hostname specifier is a comma separated list
  733. * of hostnames. we'll make new entries for each address. */
  734. while ((hostdelim = strrchr(sep->se_local_hostname, ',')) != NULL) {
  735. nsep = dup_servtab(sep);
  736. /* NUL terminate the hostname field of the existing entry,
  737. * and make a dup for the new entry. */
  738. *hostdelim++ = '\0';
  739. nsep->se_local_hostname = xstrdup(hostdelim);
  740. nsep->se_next = sep->se_next;
  741. sep->se_next = nsep;
  742. }
  743. /* was doing it here: */
  744. /* DNS resolution, create copies for each IP address */
  745. /* IPv6-ization destroyed it :( */
  746. return sep;
  747. }
  748. static servtab_t *insert_in_servlist(servtab_t *cp)
  749. {
  750. servtab_t *sep;
  751. sigset_t omask;
  752. sep = new_servtab();
  753. *sep = *cp; /* struct copy */
  754. sep->se_fd = -1;
  755. #if ENABLE_FEATURE_INETD_RPC
  756. sep->se_rpcprog = -1;
  757. #endif
  758. block_CHLD_HUP_ALRM(&omask);
  759. sep->se_next = serv_list;
  760. serv_list = sep;
  761. restore_sigmask(&omask);
  762. return sep;
  763. }
  764. static int same_serv_addr_proto(servtab_t *old, servtab_t *new)
  765. {
  766. if (strcmp(old->se_local_hostname, new->se_local_hostname) != 0)
  767. return 0;
  768. if (strcmp(old->se_service, new->se_service) != 0)
  769. return 0;
  770. if (strcmp(old->se_proto, new->se_proto) != 0)
  771. return 0;
  772. return 1;
  773. }
  774. static void reread_config_file(int sig UNUSED_PARAM)
  775. {
  776. servtab_t *sep, *cp, **sepp;
  777. len_and_sockaddr *lsa;
  778. sigset_t omask;
  779. unsigned n;
  780. uint16_t port;
  781. int save_errno = errno;
  782. if (!reopen_config_file())
  783. goto ret;
  784. for (sep = serv_list; sep; sep = sep->se_next)
  785. sep->se_checked = 0;
  786. goto first_line;
  787. while (1) {
  788. if (cp == NULL) {
  789. first_line:
  790. cp = parse_one_line();
  791. if (cp == NULL)
  792. break;
  793. }
  794. for (sep = serv_list; sep; sep = sep->se_next)
  795. if (same_serv_addr_proto(sep, cp))
  796. goto equal_servtab;
  797. /* not an "equal" servtab */
  798. sep = insert_in_servlist(cp);
  799. goto after_check;
  800. equal_servtab:
  801. {
  802. int i;
  803. block_CHLD_HUP_ALRM(&omask);
  804. #if ENABLE_FEATURE_INETD_RPC
  805. if (is_rpc_service(sep))
  806. unregister_rpc(sep);
  807. sep->se_rpcver_lo = cp->se_rpcver_lo;
  808. sep->se_rpcver_hi = cp->se_rpcver_hi;
  809. #endif
  810. if (cp->se_wait == 0) {
  811. /* New config says "nowait". If old one
  812. * was "wait", we currently may be waiting
  813. * for a child (and not accepting connects).
  814. * Stop waiting, start listening again.
  815. * (if it's not true, this op is harmless) */
  816. add_fd_to_set(sep->se_fd);
  817. }
  818. sep->se_wait = cp->se_wait;
  819. sep->se_max = cp->se_max;
  820. /* string fields need more love - we don't want to leak them */
  821. #define SWAP(type, a, b) do { type c = (type)a; a = (type)b; b = (type)c; } while (0)
  822. SWAP(char*, sep->se_user, cp->se_user);
  823. SWAP(char*, sep->se_group, cp->se_group);
  824. SWAP(char*, sep->se_program, cp->se_program);
  825. for (i = 0; i < MAXARGV; i++)
  826. SWAP(char*, sep->se_argv[i], cp->se_argv[i]);
  827. #undef SWAP
  828. restore_sigmask(&omask);
  829. free_servtab_strings(cp);
  830. }
  831. after_check:
  832. /* cp->string_fields are consumed by insert_in_servlist()
  833. * or freed at this point, cp itself is not yet freed. */
  834. sep->se_checked = 1;
  835. /* create new len_and_sockaddr */
  836. switch (sep->se_family) {
  837. struct sockaddr_un *sun;
  838. case AF_UNIX:
  839. lsa = xzalloc_lsa(AF_UNIX);
  840. sun = (struct sockaddr_un*)&lsa->u.sa;
  841. safe_strncpy(sun->sun_path, sep->se_service, sizeof(sun->sun_path));
  842. break;
  843. default: /* case AF_INET, case AF_INET6 */
  844. n = bb_strtou(sep->se_service, NULL, 10);
  845. #if ENABLE_FEATURE_INETD_RPC
  846. if (is_rpc_service(sep)) {
  847. sep->se_rpcprog = n;
  848. if (errno) { /* se_service is not numeric */
  849. struct rpcent *rp = getrpcbyname(sep->se_service);
  850. if (rp == NULL) {
  851. bb_error_msg("%s: unknown rpc service", sep->se_service);
  852. goto next_cp;
  853. }
  854. sep->se_rpcprog = rp->r_number;
  855. }
  856. if (sep->se_fd == -1)
  857. prepare_socket_fd(sep);
  858. if (sep->se_fd != -1)
  859. register_rpc(sep);
  860. goto next_cp;
  861. }
  862. #endif
  863. /* what port to listen on? */
  864. port = htons(n);
  865. if (errno || n > 0xffff) { /* se_service is not numeric */
  866. char protoname[4];
  867. struct servent *sp;
  868. /* can result only in "tcp" or "udp": */
  869. safe_strncpy(protoname, sep->se_proto, 4);
  870. sp = getservbyname(sep->se_service, protoname);
  871. if (sp == NULL) {
  872. bb_error_msg("%s/%s: unknown service",
  873. sep->se_service, sep->se_proto);
  874. goto next_cp;
  875. }
  876. port = sp->s_port;
  877. }
  878. if (LONE_CHAR(sep->se_local_hostname, '*')) {
  879. lsa = xzalloc_lsa(sep->se_family);
  880. set_nport(lsa, port);
  881. } else {
  882. lsa = host_and_af2sockaddr(sep->se_local_hostname,
  883. ntohs(port), sep->se_family);
  884. if (!lsa) {
  885. bb_error_msg("%s/%s: unknown host '%s'",
  886. sep->se_service, sep->se_proto,
  887. sep->se_local_hostname);
  888. goto next_cp;
  889. }
  890. }
  891. break;
  892. } /* end of "switch (sep->se_family)" */
  893. /* did lsa change? Then close/open */
  894. if (sep->se_lsa == NULL
  895. || lsa->len != sep->se_lsa->len
  896. || memcmp(&lsa->u.sa, &sep->se_lsa->u.sa, lsa->len) != 0
  897. ) {
  898. remove_fd_from_set(sep->se_fd);
  899. maybe_close(sep->se_fd);
  900. free(sep->se_lsa);
  901. sep->se_lsa = lsa;
  902. sep->se_fd = -1;
  903. } else {
  904. free(lsa);
  905. }
  906. if (sep->se_fd == -1)
  907. prepare_socket_fd(sep);
  908. next_cp:
  909. sep = cp->se_next;
  910. free(cp);
  911. cp = sep;
  912. } /* end of "while (1) parse lines" */
  913. close_config_file();
  914. /* Purge anything not looked at above - these are stale entries,
  915. * new config file doesnt have them. */
  916. block_CHLD_HUP_ALRM(&omask);
  917. sepp = &serv_list;
  918. while ((sep = *sepp)) {
  919. if (sep->se_checked) {
  920. sepp = &sep->se_next;
  921. continue;
  922. }
  923. *sepp = sep->se_next;
  924. remove_fd_from_set(sep->se_fd);
  925. maybe_close(sep->se_fd);
  926. #if ENABLE_FEATURE_INETD_RPC
  927. if (is_rpc_service(sep))
  928. unregister_rpc(sep);
  929. #endif
  930. if (sep->se_family == AF_UNIX)
  931. unlink(sep->se_service);
  932. free_servtab_strings(sep);
  933. free(sep);
  934. }
  935. restore_sigmask(&omask);
  936. ret:
  937. errno = save_errno;
  938. }
  939. static void reap_child(int sig UNUSED_PARAM)
  940. {
  941. pid_t pid;
  942. int status;
  943. servtab_t *sep;
  944. int save_errno = errno;
  945. for (;;) {
  946. pid = wait_any_nohang(&status);
  947. if (pid <= 0)
  948. break;
  949. for (sep = serv_list; sep; sep = sep->se_next) {
  950. if (sep->se_wait != pid)
  951. continue;
  952. /* One of our "wait" services */
  953. if (WIFEXITED(status) && WEXITSTATUS(status))
  954. bb_error_msg("%s: exit status 0x%x",
  955. sep->se_program, WEXITSTATUS(status));
  956. else if (WIFSIGNALED(status))
  957. bb_error_msg("%s: exit signal 0x%x",
  958. sep->se_program, WTERMSIG(status));
  959. sep->se_wait = 1;
  960. add_fd_to_set(sep->se_fd);
  961. break;
  962. }
  963. }
  964. errno = save_errno;
  965. }
  966. static void retry_network_setup(int sig UNUSED_PARAM)
  967. {
  968. int save_errno = errno;
  969. servtab_t *sep;
  970. alarm_armed = 0;
  971. for (sep = serv_list; sep; sep = sep->se_next) {
  972. if (sep->se_fd == -1) {
  973. prepare_socket_fd(sep);
  974. #if ENABLE_FEATURE_INETD_RPC
  975. if (sep->se_fd != -1 && is_rpc_service(sep))
  976. register_rpc(sep);
  977. #endif
  978. }
  979. }
  980. errno = save_errno;
  981. }
  982. static void clean_up_and_exit(int sig UNUSED_PARAM)
  983. {
  984. servtab_t *sep;
  985. /* XXX signal race walking sep list */
  986. for (sep = serv_list; sep; sep = sep->se_next) {
  987. if (sep->se_fd == -1)
  988. continue;
  989. switch (sep->se_family) {
  990. case AF_UNIX:
  991. unlink(sep->se_service);
  992. break;
  993. default: /* case AF_INET, AF_INET6 */
  994. #if ENABLE_FEATURE_INETD_RPC
  995. if (sep->se_wait == 1 && is_rpc_service(sep))
  996. unregister_rpc(sep); /* XXX signal race */
  997. #endif
  998. break;
  999. }
  1000. if (ENABLE_FEATURE_CLEAN_UP)
  1001. close(sep->se_fd);
  1002. }
  1003. remove_pidfile(_PATH_INETDPID);
  1004. exit(EXIT_SUCCESS);
  1005. }
  1006. int inetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1007. int inetd_main(int argc UNUSED_PARAM, char **argv)
  1008. {
  1009. struct sigaction sa, saved_pipe_handler;
  1010. servtab_t *sep, *sep2;
  1011. struct passwd *pwd;
  1012. struct group *grp = grp; /* for compiler */
  1013. int opt;
  1014. pid_t pid;
  1015. sigset_t omask;
  1016. INIT_G();
  1017. real_uid = getuid();
  1018. if (real_uid != 0) /* run by non-root user */
  1019. config_filename = NULL;
  1020. opt_complementary = "R+:q+"; /* -q N, -R N */
  1021. opt = getopt32(argv, "R:feq:", &max_concurrency, &global_queuelen);
  1022. argv += optind;
  1023. //argc -= optind;
  1024. if (argv[0])
  1025. config_filename = argv[0];
  1026. if (config_filename == NULL)
  1027. bb_error_msg_and_die("non-root must specify config file");
  1028. if (!(opt & 2))
  1029. bb_daemonize_or_rexec(0, argv - optind);
  1030. else
  1031. bb_sanitize_stdio();
  1032. if (!(opt & 4)) {
  1033. openlog(applet_name, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
  1034. logmode = LOGMODE_SYSLOG;
  1035. }
  1036. if (real_uid == 0) {
  1037. /* run by root, ensure groups vector gets trashed */
  1038. gid_t gid = getgid();
  1039. setgroups(1, &gid);
  1040. }
  1041. write_pidfile(_PATH_INETDPID);
  1042. /* never fails under Linux (except if you pass it bad arguments) */
  1043. getrlimit(RLIMIT_NOFILE, &rlim_ofile);
  1044. rlim_ofile_cur = rlim_ofile.rlim_cur;
  1045. if (rlim_ofile_cur == RLIM_INFINITY) /* ! */
  1046. rlim_ofile_cur = OPEN_MAX;
  1047. memset(&sa, 0, sizeof(sa));
  1048. /*sigemptyset(&sa.sa_mask); - memset did it */
  1049. sigaddset(&sa.sa_mask, SIGALRM);
  1050. sigaddset(&sa.sa_mask, SIGCHLD);
  1051. sigaddset(&sa.sa_mask, SIGHUP);
  1052. sa.sa_handler = retry_network_setup;
  1053. sigaction_set(SIGALRM, &sa);
  1054. sa.sa_handler = reread_config_file;
  1055. sigaction_set(SIGHUP, &sa);
  1056. sa.sa_handler = reap_child;
  1057. sigaction_set(SIGCHLD, &sa);
  1058. sa.sa_handler = clean_up_and_exit;
  1059. sigaction_set(SIGTERM, &sa);
  1060. sa.sa_handler = clean_up_and_exit;
  1061. sigaction_set(SIGINT, &sa);
  1062. sa.sa_handler = SIG_IGN;
  1063. sigaction(SIGPIPE, &sa, &saved_pipe_handler);
  1064. reread_config_file(SIGHUP); /* load config from file */
  1065. for (;;) {
  1066. int ready_fd_cnt;
  1067. int ctrl, accepted_fd, new_udp_fd;
  1068. fd_set readable;
  1069. if (maxsock < 0)
  1070. recalculate_maxsock();
  1071. readable = allsock; /* struct copy */
  1072. /* if there are no fds to wait on, we will block
  1073. * until signal wakes us up (maxsock == 0, but readable
  1074. * never contains fds 0 and 1...) */
  1075. ready_fd_cnt = select(maxsock + 1, &readable, NULL, NULL, NULL);
  1076. if (ready_fd_cnt < 0) {
  1077. if (errno != EINTR) {
  1078. bb_perror_msg("select");
  1079. sleep(1);
  1080. }
  1081. continue;
  1082. }
  1083. for (sep = serv_list; ready_fd_cnt && sep; sep = sep->se_next) {
  1084. if (sep->se_fd == -1 || !FD_ISSET(sep->se_fd, &readable))
  1085. continue;
  1086. ready_fd_cnt--;
  1087. ctrl = sep->se_fd;
  1088. accepted_fd = -1;
  1089. new_udp_fd = -1;
  1090. if (!sep->se_wait) {
  1091. if (sep->se_socktype == SOCK_STREAM) {
  1092. ctrl = accepted_fd = accept(sep->se_fd, NULL, NULL);
  1093. if (ctrl < 0) {
  1094. if (errno != EINTR)
  1095. bb_perror_msg("accept (for %s)", sep->se_service);
  1096. continue;
  1097. }
  1098. }
  1099. /* "nowait" udp */
  1100. if (sep->se_socktype == SOCK_DGRAM
  1101. && sep->se_family != AF_UNIX
  1102. ) {
  1103. /* How udp "nowait" works:
  1104. * child peeks at (received and buffered by kernel) UDP packet,
  1105. * performs connect() on the socket so that it is linked only
  1106. * to this peer. But this also affects parent, because descriptors
  1107. * are shared after fork() a-la dup(). When parent performs
  1108. * select(), it will see this descriptor connected to the peer (!)
  1109. * and still readable, will act on it and mess things up
  1110. * (can create many copies of same child, etc).
  1111. * Parent must create and use new socket instead. */
  1112. new_udp_fd = socket(sep->se_family, SOCK_DGRAM, 0);
  1113. if (new_udp_fd < 0) { /* error: eat packet, forget about it */
  1114. udp_err:
  1115. recv(sep->se_fd, line, LINE_SIZE, MSG_DONTWAIT);
  1116. continue;
  1117. }
  1118. setsockopt_reuseaddr(new_udp_fd);
  1119. /* TODO: better do bind after vfork in parent,
  1120. * so that we don't have two wildcard bound sockets
  1121. * even for a brief moment? */
  1122. if (bind(new_udp_fd, &sep->se_lsa->u.sa, sep->se_lsa->len) < 0) {
  1123. close(new_udp_fd);
  1124. goto udp_err;
  1125. }
  1126. }
  1127. }
  1128. block_CHLD_HUP_ALRM(&omask);
  1129. pid = 0;
  1130. #ifdef INETD_BUILTINS_ENABLED
  1131. /* do we need to fork? */
  1132. if (sep->se_builtin == NULL
  1133. || (sep->se_socktype == SOCK_STREAM
  1134. && sep->se_builtin->bi_fork))
  1135. #endif
  1136. {
  1137. if (sep->se_max != 0) {
  1138. if (++sep->se_count == 1)
  1139. sep->se_time = monotonic_sec();
  1140. else if (sep->se_count >= sep->se_max) {
  1141. unsigned now = monotonic_sec();
  1142. /* did we accumulate se_max connects too quickly? */
  1143. if (now - sep->se_time <= CNT_INTERVAL) {
  1144. bb_error_msg("%s/%s: too many connections, pausing",
  1145. sep->se_service, sep->se_proto);
  1146. remove_fd_from_set(sep->se_fd);
  1147. close(sep->se_fd);
  1148. sep->se_fd = -1;
  1149. sep->se_count = 0;
  1150. rearm_alarm(); /* will revive it in RETRYTIME sec */
  1151. restore_sigmask(&omask);
  1152. maybe_close(accepted_fd);
  1153. continue; /* -> check next fd in fd set */
  1154. }
  1155. sep->se_count = 0;
  1156. }
  1157. }
  1158. /* on NOMMU, streamed chargen
  1159. * builtin wouldn't work, but it is
  1160. * not allowed on NOMMU (ifdefed out) */
  1161. #ifdef INETD_BUILTINS_ENABLED
  1162. if (BB_MMU && sep->se_builtin)
  1163. pid = fork();
  1164. else
  1165. #endif
  1166. pid = vfork();
  1167. if (pid < 0) { /* fork error */
  1168. bb_perror_msg("fork");
  1169. sleep(1);
  1170. restore_sigmask(&omask);
  1171. maybe_close(accepted_fd);
  1172. continue; /* -> check next fd in fd set */
  1173. }
  1174. if (pid == 0)
  1175. pid--; /* -1: "we did fork and we are child" */
  1176. }
  1177. /* if pid == 0 here, we never forked */
  1178. if (pid > 0) { /* parent */
  1179. if (sep->se_wait) {
  1180. /* tcp wait: we passed listening socket to child,
  1181. * will wait for child to terminate */
  1182. sep->se_wait = pid;
  1183. remove_fd_from_set(sep->se_fd);
  1184. }
  1185. if (new_udp_fd >= 0) {
  1186. /* udp nowait: child connected the socket,
  1187. * we created and will use new, unconnected one */
  1188. xmove_fd(new_udp_fd, sep->se_fd);
  1189. }
  1190. restore_sigmask(&omask);
  1191. maybe_close(accepted_fd);
  1192. continue; /* -> check next fd in fd set */
  1193. }
  1194. /* we are either child or didn't vfork at all */
  1195. #ifdef INETD_BUILTINS_ENABLED
  1196. if (sep->se_builtin) {
  1197. if (pid) { /* "pid" is -1: we did vfork */
  1198. close(sep->se_fd); /* listening socket */
  1199. logmode = 0; /* make xwrite etc silent */
  1200. }
  1201. restore_sigmask(&omask);
  1202. if (sep->se_socktype == SOCK_STREAM)
  1203. sep->se_builtin->bi_stream_fn(ctrl, sep);
  1204. else
  1205. sep->se_builtin->bi_dgram_fn(ctrl, sep);
  1206. if (pid) /* we did vfork */
  1207. _exit(EXIT_FAILURE);
  1208. maybe_close(accepted_fd);
  1209. continue; /* -> check next fd in fd set */
  1210. }
  1211. #endif
  1212. /* child */
  1213. setsid();
  1214. /* "nowait" udp */
  1215. if (new_udp_fd >= 0) {
  1216. len_and_sockaddr *lsa = xzalloc_lsa(sep->se_family);
  1217. /* peek at the packet and remember peer addr */
  1218. int r = recvfrom(ctrl, NULL, 0, MSG_PEEK|MSG_DONTWAIT,
  1219. &lsa->u.sa, &lsa->len);
  1220. if (r < 0)
  1221. goto do_exit1;
  1222. /* make this socket "connected" to peer addr:
  1223. * only packets from this peer will be recv'ed,
  1224. * and bare write()/send() will work on it */
  1225. connect(ctrl, &lsa->u.sa, lsa->len);
  1226. free(lsa);
  1227. }
  1228. /* prepare env and exec program */
  1229. pwd = getpwnam(sep->se_user);
  1230. if (pwd == NULL) {
  1231. bb_error_msg("%s: no such %s", sep->se_user, "user");
  1232. goto do_exit1;
  1233. }
  1234. if (sep->se_group && (grp = getgrnam(sep->se_group)) == NULL) {
  1235. bb_error_msg("%s: no such %s", sep->se_group, "group");
  1236. goto do_exit1;
  1237. }
  1238. if (real_uid != 0 && real_uid != pwd->pw_uid) {
  1239. /* a user running private inetd */
  1240. bb_error_msg("non-root must run services as himself");
  1241. goto do_exit1;
  1242. }
  1243. if (pwd->pw_uid) {
  1244. if (sep->se_group)
  1245. pwd->pw_gid = grp->gr_gid;
  1246. /* initgroups, setgid, setuid: */
  1247. change_identity(pwd);
  1248. } else if (sep->se_group) {
  1249. xsetgid(grp->gr_gid);
  1250. setgroups(1, &grp->gr_gid);
  1251. }
  1252. if (rlim_ofile.rlim_cur != rlim_ofile_cur)
  1253. if (setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
  1254. bb_perror_msg("setrlimit");
  1255. closelog();
  1256. xmove_fd(ctrl, 0);
  1257. xdup2(0, 1);
  1258. xdup2(0, 2);
  1259. /* NB: among others, this loop closes listening socket
  1260. * for nowait stream children */
  1261. for (sep2 = serv_list; sep2; sep2 = sep2->se_next)
  1262. maybe_close(sep2->se_fd);
  1263. sigaction_set(SIGPIPE, &saved_pipe_handler);
  1264. restore_sigmask(&omask);
  1265. BB_EXECVP(sep->se_program, sep->se_argv);
  1266. bb_perror_msg("exec %s", sep->se_program);
  1267. do_exit1:
  1268. /* eat packet in udp case */
  1269. if (sep->se_socktype != SOCK_STREAM)
  1270. recv(0, line, LINE_SIZE, MSG_DONTWAIT);
  1271. _exit(EXIT_FAILURE);
  1272. } /* for (sep = servtab...) */
  1273. } /* for (;;) */
  1274. }
  1275. #if !BB_MMU
  1276. static const char *const cat_args[] = { "cat", NULL };
  1277. #endif
  1278. /*
  1279. * Internet services provided internally by inetd:
  1280. */
  1281. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
  1282. /* Echo service -- echo data back. */
  1283. /* ARGSUSED */
  1284. static void echo_stream(int s, servtab_t *sep UNUSED_PARAM)
  1285. {
  1286. #if BB_MMU
  1287. while (1) {
  1288. ssize_t sz = safe_read(s, line, LINE_SIZE);
  1289. if (sz <= 0)
  1290. break;
  1291. xwrite(s, line, sz);
  1292. }
  1293. #else
  1294. /* We are after vfork here! */
  1295. /* move network socket to stdin/stdout */
  1296. xmove_fd(s, STDIN_FILENO);
  1297. xdup2(STDIN_FILENO, STDOUT_FILENO);
  1298. /* no error messages please... */
  1299. close(STDERR_FILENO);
  1300. xopen(bb_dev_null, O_WRONLY);
  1301. BB_EXECVP("cat", (char**)cat_args);
  1302. /* on failure we return to main, which does exit(EXIT_FAILURE) */
  1303. #endif
  1304. }
  1305. static void echo_dg(int s, servtab_t *sep)
  1306. {
  1307. enum { BUFSIZE = 12*1024 }; /* for jumbo sized packets! :) */
  1308. char *buf = xmalloc(BUFSIZE); /* too big for stack */
  1309. int sz;
  1310. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1311. lsa->len = sep->se_lsa->len;
  1312. /* dgram builtins are non-forking - DONT BLOCK! */
  1313. sz = recvfrom(s, buf, BUFSIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len);
  1314. if (sz > 0)
  1315. sendto(s, buf, sz, 0, &lsa->u.sa, lsa->len);
  1316. free(buf);
  1317. }
  1318. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_ECHO */
  1319. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
  1320. /* Discard service -- ignore data. */
  1321. /* ARGSUSED */
  1322. static void discard_stream(int s, servtab_t *sep UNUSED_PARAM)
  1323. {
  1324. #if BB_MMU
  1325. while (safe_read(s, line, LINE_SIZE) > 0)
  1326. continue;
  1327. #else
  1328. /* We are after vfork here! */
  1329. /* move network socket to stdin */
  1330. xmove_fd(s, STDIN_FILENO);
  1331. /* discard output */
  1332. close(STDOUT_FILENO);
  1333. xopen(bb_dev_null, O_WRONLY);
  1334. /* no error messages please... */
  1335. xdup2(STDOUT_FILENO, STDERR_FILENO);
  1336. BB_EXECVP("cat", (char**)cat_args);
  1337. /* on failure we return to main, which does exit(EXIT_FAILURE) */
  1338. #endif
  1339. }
  1340. /* ARGSUSED */
  1341. static void discard_dg(int s, servtab_t *sep UNUSED_PARAM)
  1342. {
  1343. /* dgram builtins are non-forking - DONT BLOCK! */
  1344. recv(s, line, LINE_SIZE, MSG_DONTWAIT);
  1345. }
  1346. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_DISCARD */
  1347. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  1348. #define LINESIZ 72
  1349. static void init_ring(void)
  1350. {
  1351. int i;
  1352. end_ring = ring;
  1353. for (i = 0; i <= 128; ++i)
  1354. if (isprint(i))
  1355. *end_ring++ = i;
  1356. }
  1357. /* Character generator. MMU arches only. */
  1358. /* ARGSUSED */
  1359. static void chargen_stream(int s, servtab_t *sep UNUSED_PARAM)
  1360. {
  1361. char *rs;
  1362. int len;
  1363. char text[LINESIZ + 2];
  1364. if (!end_ring) {
  1365. init_ring();
  1366. rs = ring;
  1367. }
  1368. text[LINESIZ] = '\r';
  1369. text[LINESIZ + 1] = '\n';
  1370. rs = ring;
  1371. for (;;) {
  1372. len = end_ring - rs;
  1373. if (len >= LINESIZ)
  1374. memmove(text, rs, LINESIZ);
  1375. else {
  1376. memmove(text, rs, len);
  1377. memmove(text + len, ring, LINESIZ - len);
  1378. }
  1379. if (++rs == end_ring)
  1380. rs = ring;
  1381. xwrite(s, text, sizeof(text));
  1382. }
  1383. }
  1384. /* ARGSUSED */
  1385. static void chargen_dg(int s, servtab_t *sep)
  1386. {
  1387. int len;
  1388. char text[LINESIZ + 2];
  1389. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1390. /* Eat UDP packet which started it all */
  1391. /* dgram builtins are non-forking - DONT BLOCK! */
  1392. lsa->len = sep->se_lsa->len;
  1393. if (recvfrom(s, text, sizeof(text), MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
  1394. return;
  1395. if (!end_ring) {
  1396. init_ring();
  1397. ring_pos = ring;
  1398. }
  1399. len = end_ring - ring_pos;
  1400. if (len >= LINESIZ)
  1401. memmove(text, ring_pos, LINESIZ);
  1402. else {
  1403. memmove(text, ring_pos, len);
  1404. memmove(text + len, ring, LINESIZ - len);
  1405. }
  1406. if (++ring_pos == end_ring)
  1407. ring_pos = ring;
  1408. text[LINESIZ] = '\r';
  1409. text[LINESIZ + 1] = '\n';
  1410. sendto(s, text, sizeof(text), 0, &lsa->u.sa, lsa->len);
  1411. }
  1412. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN */
  1413. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME
  1414. /*
  1415. * Return a machine readable date and time, in the form of the
  1416. * number of seconds since midnight, Jan 1, 1900. Since gettimeofday
  1417. * returns the number of seconds since midnight, Jan 1, 1970,
  1418. * we must add 2208988800 seconds to this figure to make up for
  1419. * some seventy years Bell Labs was asleep.
  1420. */
  1421. static uint32_t machtime(void)
  1422. {
  1423. struct timeval tv;
  1424. gettimeofday(&tv, NULL);
  1425. return htonl((uint32_t)(tv.tv_sec + 2208988800));
  1426. }
  1427. /* ARGSUSED */
  1428. static void machtime_stream(int s, servtab_t *sep UNUSED_PARAM)
  1429. {
  1430. uint32_t result;
  1431. result = machtime();
  1432. full_write(s, &result, sizeof(result));
  1433. }
  1434. static void machtime_dg(int s, servtab_t *sep)
  1435. {
  1436. uint32_t result;
  1437. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1438. lsa->len = sep->se_lsa->len;
  1439. if (recvfrom(s, line, LINE_SIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
  1440. return;
  1441. result = machtime();
  1442. sendto(s, &result, sizeof(result), 0, &lsa->u.sa, lsa->len);
  1443. }
  1444. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_TIME */
  1445. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
  1446. /* Return human-readable time of day */
  1447. /* ARGSUSED */
  1448. static void daytime_stream(int s, servtab_t *sep UNUSED_PARAM)
  1449. {
  1450. time_t t;
  1451. t = time(NULL);
  1452. fdprintf(s, "%.24s\r\n", ctime(&t));
  1453. }
  1454. static void daytime_dg(int s, servtab_t *sep)
  1455. {
  1456. time_t t;
  1457. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1458. lsa->len = sep->se_lsa->len;
  1459. if (recvfrom(s, line, LINE_SIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
  1460. return;
  1461. t = time(NULL);
  1462. sprintf(line, "%.24s\r\n", ctime(&t));
  1463. sendto(s, line, strlen(line), 0, &lsa->u.sa, lsa->len);
  1464. }
  1465. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME */