inetd.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  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. //config:config INETD
  153. //config: bool "inetd (18 kb)"
  154. //config: default y
  155. //config: select FEATURE_SYSLOG
  156. //config: help
  157. //config: Internet superserver daemon
  158. //config:
  159. //config:config FEATURE_INETD_SUPPORT_BUILTIN_ECHO
  160. //config: bool "Support echo service on port 7"
  161. //config: default y
  162. //config: depends on INETD
  163. //config: help
  164. //config: Internal service which echoes data back.
  165. //config: Activated by configuration lines like these:
  166. //config: echo stream tcp nowait root internal
  167. //config: echo dgram udp wait root internal
  168. //config:
  169. //config:config FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
  170. //config: bool "Support discard service on port 8"
  171. //config: default y
  172. //config: depends on INETD
  173. //config: help
  174. //config: Internal service which discards all input.
  175. //config: Activated by configuration lines like these:
  176. //config: discard stream tcp nowait root internal
  177. //config: discard dgram udp wait root internal
  178. //config:
  179. //config:config FEATURE_INETD_SUPPORT_BUILTIN_TIME
  180. //config: bool "Support time service on port 37"
  181. //config: default y
  182. //config: depends on INETD
  183. //config: help
  184. //config: Internal service which returns big-endian 32-bit number
  185. //config: of seconds passed since 1900-01-01. The number wraps around
  186. //config: on overflow.
  187. //config: Activated by configuration lines like these:
  188. //config: time stream tcp nowait root internal
  189. //config: time dgram udp wait root internal
  190. //config:
  191. //config:config FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
  192. //config: bool "Support daytime service on port 13"
  193. //config: default y
  194. //config: depends on INETD
  195. //config: help
  196. //config: Internal service which returns human-readable time.
  197. //config: Activated by configuration lines like these:
  198. //config: daytime stream tcp nowait root internal
  199. //config: daytime dgram udp wait root internal
  200. //config:
  201. //config:config FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  202. //config: bool "Support chargen service on port 19"
  203. //config: default y
  204. //config: depends on INETD
  205. //config: help
  206. //config: Internal service which generates endless stream
  207. //config: of all ASCII chars beetween space and char 126.
  208. //config: Activated by configuration lines like these:
  209. //config: chargen stream tcp nowait root internal
  210. //config: chargen dgram udp wait root internal
  211. //config:
  212. //config:config FEATURE_INETD_RPC
  213. //config: bool "Support RPC services"
  214. //config: default n # very rarely used, and needs Sun RPC support in libc
  215. //config: depends on INETD
  216. //config: select FEATURE_HAVE_RPC
  217. //config: help
  218. //config: Support Sun-RPC based services
  219. //applet:IF_INETD(APPLET(inetd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  220. //kbuild:lib-$(CONFIG_INETD) += inetd.o
  221. //usage:#define inetd_trivial_usage
  222. //usage: "[-fe] [-q N] [-R N] [CONFFILE]"
  223. //usage:#define inetd_full_usage "\n\n"
  224. //usage: "Listen for network connections and launch programs\n"
  225. //usage: "\n -f Run in foreground"
  226. //usage: "\n -e Log to stderr"
  227. //usage: "\n -q N Socket listen queue (default 128)"
  228. //usage: "\n -R N Pause services after N connects/min"
  229. //usage: "\n (default 0 - disabled)"
  230. //usage: "\n Default CONFFILE is /etc/inetd.conf"
  231. #include <syslog.h>
  232. #include <sys/resource.h> /* setrlimit */
  233. #include <sys/socket.h> /* un.h may need this */
  234. #include <sys/un.h>
  235. #include "libbb.h"
  236. #include "common_bufsiz.h"
  237. #if ENABLE_FEATURE_INETD_RPC
  238. # if defined(__UCLIBC__) && ! defined(__UCLIBC_HAS_RPC__)
  239. # warning "You probably need to build uClibc with UCLIBC_HAS_RPC for NFS support"
  240. /* not #error, since user may be using e.g. libtirpc instead */
  241. # endif
  242. # include <rpc/rpc.h>
  243. # include <rpc/pmap_clnt.h>
  244. #endif
  245. #if !BB_MMU
  246. /* stream version of chargen is forking but not execing,
  247. * can't do that (easily) on NOMMU */
  248. #undef ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  249. #define ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN 0
  250. #endif
  251. #define CNT_INTERVAL 60 /* servers in CNT_INTERVAL sec. */
  252. #define RETRYTIME 60 /* retry after bind or server fail */
  253. // TODO: explain, or get rid of setrlimit games
  254. #ifndef RLIMIT_NOFILE
  255. #define RLIMIT_NOFILE RLIMIT_OFILE
  256. #endif
  257. #ifndef OPEN_MAX
  258. #define OPEN_MAX 64
  259. #endif
  260. /* Reserve some descriptors, 3 stdio + at least: 1 log, 1 conf. file */
  261. #define FD_MARGIN 8
  262. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD \
  263. || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO \
  264. || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN \
  265. || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME \
  266. || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
  267. # define INETD_BUILTINS_ENABLED
  268. #endif
  269. typedef struct servtab_t {
  270. /* The most frequently referenced one: */
  271. int se_fd; /* open descriptor */
  272. /* NB: 'biggest fields last' saves on code size (~250 bytes) */
  273. /* [addr:]service socktype proto wait user[:group] prog [args] */
  274. char *se_local_hostname; /* addr to listen on */
  275. char *se_service; /* "80" or "www" or "mount/2[-3]" */
  276. /* socktype is in se_socktype */ /* "stream" "dgram" "raw" "rdm" "seqpacket" */
  277. char *se_proto; /* "unix" or "[rpc/]tcp[6]" */
  278. #if ENABLE_FEATURE_INETD_RPC
  279. int se_rpcprog; /* rpc program number */
  280. int se_rpcver_lo; /* rpc program lowest version */
  281. int se_rpcver_hi; /* rpc program highest version */
  282. #define is_rpc_service(sep) ((sep)->se_rpcver_lo != 0)
  283. #else
  284. #define is_rpc_service(sep) 0
  285. #endif
  286. pid_t se_wait; /* 0:"nowait", 1:"wait", >1:"wait" */
  287. /* and waiting for this pid */
  288. socktype_t se_socktype; /* SOCK_STREAM/DGRAM/RDM/... */
  289. family_t se_family; /* AF_UNIX/INET[6] */
  290. /* se_proto_no is used by RPC code only... hmm */
  291. smallint se_proto_no; /* IPPROTO_TCP/UDP, n/a for AF_UNIX */
  292. smallint se_checked; /* looked at during merge */
  293. unsigned se_max; /* allowed instances per minute */
  294. unsigned se_count; /* number started since se_time */
  295. unsigned se_time; /* when we started counting */
  296. char *se_user; /* user name to run as */
  297. char *se_group; /* group name to run as, can be NULL */
  298. #ifdef INETD_BUILTINS_ENABLED
  299. const struct builtin *se_builtin; /* if built-in, description */
  300. #endif
  301. struct servtab_t *se_next;
  302. len_and_sockaddr *se_lsa;
  303. char *se_program; /* server program */
  304. #define MAXARGV 20
  305. char *se_argv[MAXARGV + 1]; /* program arguments */
  306. } servtab_t;
  307. #ifdef INETD_BUILTINS_ENABLED
  308. /* Echo received data */
  309. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
  310. static void FAST_FUNC echo_stream(int, servtab_t *);
  311. static void FAST_FUNC echo_dg(int, servtab_t *);
  312. #endif
  313. /* Internet /dev/null */
  314. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
  315. static void FAST_FUNC discard_stream(int, servtab_t *);
  316. static void FAST_FUNC discard_dg(int, servtab_t *);
  317. #endif
  318. /* Return 32 bit time since 1900 */
  319. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME
  320. static void FAST_FUNC machtime_stream(int, servtab_t *);
  321. static void FAST_FUNC machtime_dg(int, servtab_t *);
  322. #endif
  323. /* Return human-readable time */
  324. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
  325. static void FAST_FUNC daytime_stream(int, servtab_t *);
  326. static void FAST_FUNC daytime_dg(int, servtab_t *);
  327. #endif
  328. /* Familiar character generator */
  329. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  330. static void FAST_FUNC chargen_stream(int, servtab_t *);
  331. static void FAST_FUNC chargen_dg(int, servtab_t *);
  332. #endif
  333. struct builtin {
  334. /* NB: not necessarily NUL terminated */
  335. char bi_service7[7]; /* internally provided service name */
  336. uint8_t bi_fork; /* 1 if stream fn should run in child */
  337. void (*bi_stream_fn)(int, servtab_t *) FAST_FUNC;
  338. void (*bi_dgram_fn)(int, servtab_t *) FAST_FUNC;
  339. };
  340. static const struct builtin builtins[] = {
  341. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
  342. { "echo", 1, echo_stream, echo_dg },
  343. #endif
  344. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
  345. { "discard", 1, discard_stream, discard_dg },
  346. #endif
  347. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  348. { "chargen", 1, chargen_stream, chargen_dg },
  349. #endif
  350. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME
  351. { "time", 0, machtime_stream, machtime_dg },
  352. #endif
  353. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
  354. { "daytime", 0, daytime_stream, daytime_dg },
  355. #endif
  356. };
  357. #endif /* INETD_BUILTINS_ENABLED */
  358. struct globals {
  359. rlim_t rlim_ofile_cur;
  360. struct rlimit rlim_ofile;
  361. servtab_t *serv_list;
  362. int global_queuelen;
  363. int maxsock; /* max fd# in allsock, -1: unknown */
  364. /* whenever maxsock grows, prev_maxsock is set to new maxsock,
  365. * but if maxsock is set to -1, prev_maxsock is not changed */
  366. int prev_maxsock;
  367. unsigned max_concurrency;
  368. smallint alarm_armed;
  369. uid_t real_uid; /* user ID who ran us */
  370. const char *config_filename;
  371. parser_t *parser;
  372. char *default_local_hostname;
  373. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  374. char *end_ring;
  375. char *ring_pos;
  376. char ring[128];
  377. #endif
  378. fd_set allsock;
  379. /* Used in next_line(), and as scratch read buffer */
  380. char line[256]; /* _at least_ 256, see LINE_SIZE */
  381. } FIX_ALIASING;
  382. #define G (*(struct globals*)bb_common_bufsiz1)
  383. enum { LINE_SIZE = COMMON_BUFSIZE - offsetof(struct globals, line) };
  384. #define rlim_ofile_cur (G.rlim_ofile_cur )
  385. #define rlim_ofile (G.rlim_ofile )
  386. #define serv_list (G.serv_list )
  387. #define global_queuelen (G.global_queuelen)
  388. #define maxsock (G.maxsock )
  389. #define prev_maxsock (G.prev_maxsock )
  390. #define max_concurrency (G.max_concurrency)
  391. #define alarm_armed (G.alarm_armed )
  392. #define real_uid (G.real_uid )
  393. #define config_filename (G.config_filename)
  394. #define parser (G.parser )
  395. #define default_local_hostname (G.default_local_hostname)
  396. #define first_ps_byte (G.first_ps_byte )
  397. #define last_ps_byte (G.last_ps_byte )
  398. #define end_ring (G.end_ring )
  399. #define ring_pos (G.ring_pos )
  400. #define ring (G.ring )
  401. #define allsock (G.allsock )
  402. #define line (G.line )
  403. #define INIT_G() do { \
  404. setup_common_bufsiz(); \
  405. BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
  406. rlim_ofile_cur = OPEN_MAX; \
  407. global_queuelen = 128; \
  408. config_filename = "/etc/inetd.conf"; \
  409. } while (0)
  410. #if 1
  411. # define dbg(...) ((void)0)
  412. #else
  413. # define dbg(...) \
  414. do { \
  415. int dbg_fd = open("inetd_debug.log", O_WRONLY | O_CREAT | O_APPEND, 0666); \
  416. if (dbg_fd >= 0) { \
  417. fdprintf(dbg_fd, "%d: ", getpid()); \
  418. fdprintf(dbg_fd, __VA_ARGS__); \
  419. close(dbg_fd); \
  420. } \
  421. } while (0)
  422. #endif
  423. static void maybe_close(int fd)
  424. {
  425. if (fd >= 0) {
  426. close(fd);
  427. dbg("closed fd:%d\n", fd);
  428. }
  429. }
  430. // TODO: move to libbb?
  431. static len_and_sockaddr *xzalloc_lsa(int family)
  432. {
  433. len_and_sockaddr *lsa;
  434. int sz;
  435. sz = sizeof(struct sockaddr_in);
  436. if (family == AF_UNIX)
  437. sz = sizeof(struct sockaddr_un);
  438. #if ENABLE_FEATURE_IPV6
  439. if (family == AF_INET6)
  440. sz = sizeof(struct sockaddr_in6);
  441. #endif
  442. lsa = xzalloc(LSA_LEN_SIZE + sz);
  443. lsa->len = sz;
  444. lsa->u.sa.sa_family = family;
  445. return lsa;
  446. }
  447. static void rearm_alarm(void)
  448. {
  449. if (!alarm_armed) {
  450. alarm_armed = 1;
  451. alarm(RETRYTIME);
  452. }
  453. }
  454. static void block_CHLD_HUP_ALRM(sigset_t *m)
  455. {
  456. sigemptyset(m);
  457. sigaddset(m, SIGCHLD);
  458. sigaddset(m, SIGHUP);
  459. sigaddset(m, SIGALRM);
  460. sigprocmask(SIG_BLOCK, m, m); /* old sigmask is stored in m */
  461. }
  462. static void restore_sigmask(sigset_t *m)
  463. {
  464. sigprocmask(SIG_SETMASK, m, NULL);
  465. }
  466. #if ENABLE_FEATURE_INETD_RPC
  467. static void register_rpc(servtab_t *sep)
  468. {
  469. int n;
  470. struct sockaddr_in ir_sin;
  471. socklen_t size;
  472. size = sizeof(ir_sin);
  473. if (getsockname(sep->se_fd, (struct sockaddr *) &ir_sin, &size) < 0) {
  474. bb_perror_msg("getsockname");
  475. return;
  476. }
  477. for (n = sep->se_rpcver_lo; n <= sep->se_rpcver_hi; n++) {
  478. pmap_unset(sep->se_rpcprog, n);
  479. if (!pmap_set(sep->se_rpcprog, n, sep->se_proto_no, ntohs(ir_sin.sin_port)))
  480. bb_perror_msg("%s %s: pmap_set(%u,%u,%u,%u)",
  481. sep->se_service, sep->se_proto,
  482. sep->se_rpcprog, n, sep->se_proto_no, ntohs(ir_sin.sin_port));
  483. }
  484. }
  485. static void unregister_rpc(servtab_t *sep)
  486. {
  487. int n;
  488. for (n = sep->se_rpcver_lo; n <= sep->se_rpcver_hi; n++) {
  489. if (!pmap_unset(sep->se_rpcprog, n))
  490. bb_perror_msg("pmap_unset(%u,%u)", sep->se_rpcprog, n);
  491. }
  492. }
  493. #endif /* FEATURE_INETD_RPC */
  494. static void bump_nofile(void)
  495. {
  496. enum { FD_CHUNK = 32 };
  497. struct rlimit rl;
  498. /* Never fails under Linux (except if you pass it bad arguments) */
  499. getrlimit(RLIMIT_NOFILE, &rl);
  500. rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
  501. rl.rlim_cur = MIN(FD_SETSIZE, rl.rlim_cur + FD_CHUNK);
  502. if (rl.rlim_cur <= rlim_ofile_cur) {
  503. bb_error_msg("can't extend file limit, max = %d",
  504. (int) rl.rlim_cur);
  505. return;
  506. }
  507. if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
  508. bb_perror_msg("setrlimit");
  509. return;
  510. }
  511. rlim_ofile_cur = rl.rlim_cur;
  512. }
  513. static void remove_fd_from_set(int fd)
  514. {
  515. if (fd >= 0) {
  516. FD_CLR(fd, &allsock);
  517. dbg("stopped listening on fd:%d\n", fd);
  518. maxsock = -1;
  519. dbg("maxsock:%d\n", maxsock);
  520. }
  521. }
  522. static void add_fd_to_set(int fd)
  523. {
  524. if (fd >= 0) {
  525. FD_SET(fd, &allsock);
  526. dbg("started listening on fd:%d\n", fd);
  527. if (maxsock >= 0 && fd > maxsock) {
  528. prev_maxsock = maxsock = fd;
  529. dbg("maxsock:%d\n", maxsock);
  530. if ((rlim_t)fd > rlim_ofile_cur - FD_MARGIN)
  531. bump_nofile();
  532. }
  533. }
  534. }
  535. static void recalculate_maxsock(void)
  536. {
  537. int fd = 0;
  538. /* We may have no services, in this case maxsock should still be >= 0
  539. * (code elsewhere is not happy with maxsock == -1) */
  540. maxsock = 0;
  541. while (fd <= prev_maxsock) {
  542. if (FD_ISSET(fd, &allsock))
  543. maxsock = fd;
  544. fd++;
  545. }
  546. dbg("recalculated maxsock:%d\n", maxsock);
  547. prev_maxsock = maxsock;
  548. if ((rlim_t)maxsock > rlim_ofile_cur - FD_MARGIN)
  549. bump_nofile();
  550. }
  551. static void prepare_socket_fd(servtab_t *sep)
  552. {
  553. int r, fd;
  554. fd = socket(sep->se_family, sep->se_socktype, 0);
  555. if (fd < 0) {
  556. bb_perror_msg("socket");
  557. return;
  558. }
  559. setsockopt_reuseaddr(fd);
  560. #if ENABLE_FEATURE_INETD_RPC
  561. if (is_rpc_service(sep)) {
  562. struct passwd *pwd;
  563. /* zero out the port for all RPC services; let bind()
  564. * find one. */
  565. set_nport(&sep->se_lsa->u.sa, 0);
  566. /* for RPC services, attempt to use a reserved port
  567. * if they are going to be running as root. */
  568. if (real_uid == 0 && sep->se_family == AF_INET
  569. && (pwd = getpwnam(sep->se_user)) != NULL
  570. && pwd->pw_uid == 0
  571. ) {
  572. r = bindresvport(fd, &sep->se_lsa->u.sin);
  573. } else {
  574. r = bind(fd, &sep->se_lsa->u.sa, sep->se_lsa->len);
  575. }
  576. if (r == 0) {
  577. int saveerrno = errno;
  578. /* update lsa with port# */
  579. getsockname(fd, &sep->se_lsa->u.sa, &sep->se_lsa->len);
  580. errno = saveerrno;
  581. }
  582. } else
  583. #endif
  584. {
  585. if (sep->se_family == AF_UNIX) {
  586. struct sockaddr_un *sun;
  587. sun = (struct sockaddr_un*)&(sep->se_lsa->u.sa);
  588. unlink(sun->sun_path);
  589. }
  590. r = bind(fd, &sep->se_lsa->u.sa, sep->se_lsa->len);
  591. }
  592. if (r < 0) {
  593. bb_perror_msg("%s/%s: bind",
  594. sep->se_service, sep->se_proto);
  595. close(fd);
  596. rearm_alarm();
  597. return;
  598. }
  599. if (sep->se_socktype == SOCK_STREAM) {
  600. listen(fd, global_queuelen);
  601. dbg("new sep->se_fd:%d (stream)\n", fd);
  602. } else {
  603. dbg("new sep->se_fd:%d (!stream)\n", fd);
  604. }
  605. add_fd_to_set(fd);
  606. sep->se_fd = fd;
  607. }
  608. static int reopen_config_file(void)
  609. {
  610. free(default_local_hostname);
  611. default_local_hostname = xstrdup("*");
  612. if (parser != NULL)
  613. config_close(parser);
  614. parser = config_open(config_filename);
  615. return (parser != NULL);
  616. }
  617. static void close_config_file(void)
  618. {
  619. if (parser) {
  620. config_close(parser);
  621. parser = NULL;
  622. }
  623. }
  624. static void free_servtab_strings(servtab_t *cp)
  625. {
  626. int i;
  627. free(cp->se_local_hostname);
  628. free(cp->se_service);
  629. free(cp->se_proto);
  630. free(cp->se_user);
  631. free(cp->se_group);
  632. free(cp->se_lsa); /* not a string in fact */
  633. free(cp->se_program);
  634. for (i = 0; i < MAXARGV; i++)
  635. free(cp->se_argv[i]);
  636. }
  637. static servtab_t *new_servtab(void)
  638. {
  639. servtab_t *newtab = xzalloc(sizeof(servtab_t));
  640. newtab->se_fd = -1; /* paranoia */
  641. return newtab;
  642. }
  643. static servtab_t *dup_servtab(servtab_t *sep)
  644. {
  645. servtab_t *newtab;
  646. int argc;
  647. newtab = new_servtab();
  648. *newtab = *sep; /* struct copy */
  649. /* deep-copying strings */
  650. newtab->se_service = xstrdup(newtab->se_service);
  651. newtab->se_proto = xstrdup(newtab->se_proto);
  652. newtab->se_user = xstrdup(newtab->se_user);
  653. newtab->se_group = xstrdup(newtab->se_group);
  654. newtab->se_program = xstrdup(newtab->se_program);
  655. for (argc = 0; argc <= MAXARGV; argc++)
  656. newtab->se_argv[argc] = xstrdup(newtab->se_argv[argc]);
  657. /* NB: se_fd, se_hostaddr and se_next are always
  658. * overwrittend by callers, so we don't bother resetting them
  659. * to NULL/0/-1 etc */
  660. return newtab;
  661. }
  662. /* gcc generates much more code if this is inlined */
  663. static NOINLINE servtab_t *parse_one_line(void)
  664. {
  665. int argc;
  666. char *token[6+MAXARGV];
  667. char *p, *arg;
  668. char *hostdelim;
  669. servtab_t *sep;
  670. servtab_t *nsep;
  671. new:
  672. sep = new_servtab();
  673. more:
  674. argc = config_read(parser, token, 6+MAXARGV, 1, "# \t", PARSE_NORMAL);
  675. if (!argc) {
  676. free(sep);
  677. return NULL;
  678. }
  679. /* [host:]service socktype proto wait user[:group] prog [args] */
  680. /* Check for "host:...." line */
  681. arg = token[0];
  682. hostdelim = strrchr(arg, ':');
  683. if (hostdelim) {
  684. *hostdelim = '\0';
  685. sep->se_local_hostname = xstrdup(arg);
  686. arg = hostdelim + 1;
  687. if (*arg == '\0' && argc == 1) {
  688. /* Line has just "host:", change the
  689. * default host for the following lines. */
  690. free(default_local_hostname);
  691. default_local_hostname = sep->se_local_hostname;
  692. /*sep->se_local_hostname = NULL; - redundant */
  693. /* (we'll overwrite this field anyway) */
  694. goto more;
  695. }
  696. } else
  697. sep->se_local_hostname = xstrdup(default_local_hostname);
  698. /* service socktype proto wait user[:group] prog [args] */
  699. sep->se_service = xstrdup(arg);
  700. /* socktype proto wait user[:group] prog [args] */
  701. if (argc < 6) {
  702. parse_err:
  703. bb_error_msg("parse error on line %u, line is ignored",
  704. parser->lineno);
  705. /* Just "goto more" can make sep to carry over e.g.
  706. * "rpc"-ness (by having se_rpcver_lo != 0).
  707. * We will be more paranoid: */
  708. free_servtab_strings(sep);
  709. free(sep);
  710. goto new;
  711. }
  712. {
  713. static const int8_t SOCK_xxx[] ALIGN1 = {
  714. -1,
  715. SOCK_STREAM, SOCK_DGRAM, SOCK_RDM,
  716. SOCK_SEQPACKET, SOCK_RAW
  717. };
  718. sep->se_socktype = SOCK_xxx[1 + index_in_strings(
  719. "stream""\0" "dgram""\0" "rdm""\0"
  720. "seqpacket""\0" "raw""\0"
  721. , token[1])];
  722. }
  723. /* {unix,[rpc/]{tcp,udp}[6]} wait user[:group] prog [args] */
  724. sep->se_proto = arg = xstrdup(token[2]);
  725. if (strcmp(arg, "unix") == 0) {
  726. sep->se_family = AF_UNIX;
  727. } else {
  728. char *six;
  729. sep->se_family = AF_INET;
  730. six = last_char_is(arg, '6');
  731. if (six) {
  732. #if ENABLE_FEATURE_IPV6
  733. *six = '\0';
  734. sep->se_family = AF_INET6;
  735. #else
  736. bb_error_msg("%s: no support for IPv6", sep->se_proto);
  737. goto parse_err;
  738. #endif
  739. }
  740. if (is_prefixed_with(arg, "rpc/")) {
  741. #if ENABLE_FEATURE_INETD_RPC
  742. unsigned n;
  743. arg += 4;
  744. p = strchr(sep->se_service, '/');
  745. if (p == NULL) {
  746. bb_error_msg("no rpc version: '%s'", sep->se_service);
  747. goto parse_err;
  748. }
  749. *p++ = '\0';
  750. n = bb_strtou(p, &p, 10);
  751. if (n > INT_MAX) {
  752. bad_ver_spec:
  753. bb_error_msg("bad rpc version");
  754. goto parse_err;
  755. }
  756. sep->se_rpcver_lo = sep->se_rpcver_hi = n;
  757. if (*p == '-') {
  758. p++;
  759. n = bb_strtou(p, &p, 10);
  760. if (n > INT_MAX || (int)n < sep->se_rpcver_lo)
  761. goto bad_ver_spec;
  762. sep->se_rpcver_hi = n;
  763. }
  764. if (*p != '\0')
  765. goto bad_ver_spec;
  766. #else
  767. bb_error_msg("no support for rpc services");
  768. goto parse_err;
  769. #endif
  770. }
  771. /* we don't really need getprotobyname()! */
  772. if (strcmp(arg, "tcp") == 0)
  773. sep->se_proto_no = IPPROTO_TCP; /* = 6 */
  774. if (strcmp(arg, "udp") == 0)
  775. sep->se_proto_no = IPPROTO_UDP; /* = 17 */
  776. if (six)
  777. *six = '6';
  778. if (!sep->se_proto_no) /* not tcp/udp?? */
  779. goto parse_err;
  780. }
  781. /* [no]wait[.max] user[:group] prog [args] */
  782. arg = token[3];
  783. sep->se_max = max_concurrency;
  784. p = strchr(arg, '.');
  785. if (p) {
  786. *p++ = '\0';
  787. sep->se_max = bb_strtou(p, NULL, 10);
  788. if (errno)
  789. goto parse_err;
  790. }
  791. sep->se_wait = (arg[0] != 'n' || arg[1] != 'o');
  792. if (!sep->se_wait) /* "no" seen */
  793. arg += 2;
  794. if (strcmp(arg, "wait") != 0)
  795. goto parse_err;
  796. /* user[:group] prog [args] */
  797. sep->se_user = xstrdup(token[4]);
  798. arg = strchr(sep->se_user, '.');
  799. if (arg == NULL)
  800. arg = strchr(sep->se_user, ':');
  801. if (arg) {
  802. *arg++ = '\0';
  803. sep->se_group = xstrdup(arg);
  804. }
  805. /* prog [args] */
  806. sep->se_program = xstrdup(token[5]);
  807. #ifdef INETD_BUILTINS_ENABLED
  808. if (strcmp(sep->se_program, "internal") == 0
  809. && strlen(sep->se_service) <= 7
  810. && (sep->se_socktype == SOCK_STREAM
  811. || sep->se_socktype == SOCK_DGRAM)
  812. ) {
  813. unsigned i;
  814. for (i = 0; i < ARRAY_SIZE(builtins); i++)
  815. if (strncmp(builtins[i].bi_service7, sep->se_service, 7) == 0)
  816. goto found_bi;
  817. bb_error_msg("unknown internal service %s", sep->se_service);
  818. goto parse_err;
  819. found_bi:
  820. sep->se_builtin = &builtins[i];
  821. /* stream builtins must be "nowait", dgram must be "wait" */
  822. if (sep->se_wait != (sep->se_socktype == SOCK_DGRAM))
  823. goto parse_err;
  824. }
  825. #endif
  826. argc = 0;
  827. while (argc < MAXARGV && (arg = token[6+argc]) != NULL)
  828. sep->se_argv[argc++] = xstrdup(arg);
  829. /* Some inetd.conf files have no argv's, not even argv[0].
  830. * Fix them up.
  831. * (Technically, programs can be execed with argv[0] = NULL,
  832. * but many programs do not like that at all) */
  833. if (argc == 0)
  834. sep->se_argv[0] = xstrdup(sep->se_program);
  835. /* catch mixups. "<service> stream udp ..." == wtf */
  836. if (sep->se_socktype == SOCK_STREAM) {
  837. if (sep->se_proto_no == IPPROTO_UDP)
  838. goto parse_err;
  839. }
  840. if (sep->se_socktype == SOCK_DGRAM) {
  841. if (sep->se_proto_no == IPPROTO_TCP)
  842. goto parse_err;
  843. }
  844. //bb_error_msg(
  845. // "ENTRY[%s][%s][%s][%d][%d][%d][%d][%d][%s][%s][%s]",
  846. // sep->se_local_hostname, sep->se_service, sep->se_proto, sep->se_wait, sep->se_proto_no,
  847. // sep->se_max, sep->se_count, sep->se_time, sep->se_user, sep->se_group, sep->se_program);
  848. /* check if the hostname specifier is a comma separated list
  849. * of hostnames. we'll make new entries for each address. */
  850. while ((hostdelim = strrchr(sep->se_local_hostname, ',')) != NULL) {
  851. nsep = dup_servtab(sep);
  852. /* NUL terminate the hostname field of the existing entry,
  853. * and make a dup for the new entry. */
  854. *hostdelim++ = '\0';
  855. nsep->se_local_hostname = xstrdup(hostdelim);
  856. nsep->se_next = sep->se_next;
  857. sep->se_next = nsep;
  858. }
  859. /* was doing it here: */
  860. /* DNS resolution, create copies for each IP address */
  861. /* IPv6-ization destroyed it :( */
  862. return sep;
  863. }
  864. static servtab_t *insert_in_servlist(servtab_t *cp)
  865. {
  866. servtab_t *sep;
  867. sigset_t omask;
  868. sep = new_servtab();
  869. *sep = *cp; /* struct copy */
  870. sep->se_fd = -1;
  871. #if ENABLE_FEATURE_INETD_RPC
  872. sep->se_rpcprog = -1;
  873. #endif
  874. block_CHLD_HUP_ALRM(&omask);
  875. sep->se_next = serv_list;
  876. serv_list = sep;
  877. restore_sigmask(&omask);
  878. return sep;
  879. }
  880. static int same_serv_addr_proto(servtab_t *old, servtab_t *new)
  881. {
  882. if (strcmp(old->se_local_hostname, new->se_local_hostname) != 0)
  883. return 0;
  884. if (strcmp(old->se_service, new->se_service) != 0)
  885. return 0;
  886. if (strcmp(old->se_proto, new->se_proto) != 0)
  887. return 0;
  888. return 1;
  889. }
  890. static void reread_config_file(int sig UNUSED_PARAM)
  891. {
  892. servtab_t *sep, *cp, **sepp;
  893. len_and_sockaddr *lsa;
  894. sigset_t omask;
  895. unsigned n;
  896. uint16_t port;
  897. int save_errno = errno;
  898. if (!reopen_config_file())
  899. goto ret;
  900. for (sep = serv_list; sep; sep = sep->se_next)
  901. sep->se_checked = 0;
  902. goto first_line;
  903. while (1) {
  904. if (cp == NULL) {
  905. first_line:
  906. cp = parse_one_line();
  907. if (cp == NULL)
  908. break;
  909. }
  910. for (sep = serv_list; sep; sep = sep->se_next)
  911. if (same_serv_addr_proto(sep, cp))
  912. goto equal_servtab;
  913. /* not an "equal" servtab */
  914. sep = insert_in_servlist(cp);
  915. goto after_check;
  916. equal_servtab:
  917. {
  918. int i;
  919. block_CHLD_HUP_ALRM(&omask);
  920. #if ENABLE_FEATURE_INETD_RPC
  921. if (is_rpc_service(sep))
  922. unregister_rpc(sep);
  923. sep->se_rpcver_lo = cp->se_rpcver_lo;
  924. sep->se_rpcver_hi = cp->se_rpcver_hi;
  925. #endif
  926. if (cp->se_wait == 0) {
  927. /* New config says "nowait". If old one
  928. * was "wait", we currently may be waiting
  929. * for a child (and not accepting connects).
  930. * Stop waiting, start listening again.
  931. * (if it's not true, this op is harmless) */
  932. add_fd_to_set(sep->se_fd);
  933. }
  934. sep->se_wait = cp->se_wait;
  935. sep->se_max = cp->se_max;
  936. /* string fields need more love - we don't want to leak them */
  937. #define SWAP(type, a, b) do { type c = (type)a; a = (type)b; b = (type)c; } while (0)
  938. SWAP(char*, sep->se_user, cp->se_user);
  939. SWAP(char*, sep->se_group, cp->se_group);
  940. SWAP(char*, sep->se_program, cp->se_program);
  941. for (i = 0; i < MAXARGV; i++)
  942. SWAP(char*, sep->se_argv[i], cp->se_argv[i]);
  943. #undef SWAP
  944. restore_sigmask(&omask);
  945. free_servtab_strings(cp);
  946. }
  947. after_check:
  948. /* cp->string_fields are consumed by insert_in_servlist()
  949. * or freed at this point, cp itself is not yet freed. */
  950. sep->se_checked = 1;
  951. /* create new len_and_sockaddr */
  952. switch (sep->se_family) {
  953. struct sockaddr_un *sun;
  954. case AF_UNIX:
  955. lsa = xzalloc_lsa(AF_UNIX);
  956. sun = (struct sockaddr_un*)&lsa->u.sa;
  957. safe_strncpy(sun->sun_path, sep->se_service, sizeof(sun->sun_path));
  958. break;
  959. default: /* case AF_INET, case AF_INET6 */
  960. n = bb_strtou(sep->se_service, NULL, 10);
  961. #if ENABLE_FEATURE_INETD_RPC
  962. if (is_rpc_service(sep)) {
  963. sep->se_rpcprog = n;
  964. if (errno) { /* se_service is not numeric */
  965. struct rpcent *rp = getrpcbyname(sep->se_service);
  966. if (rp == NULL) {
  967. bb_error_msg("%s: unknown rpc service", sep->se_service);
  968. goto next_cp;
  969. }
  970. sep->se_rpcprog = rp->r_number;
  971. }
  972. if (sep->se_fd == -1)
  973. prepare_socket_fd(sep);
  974. if (sep->se_fd != -1)
  975. register_rpc(sep);
  976. goto next_cp;
  977. }
  978. #endif
  979. /* what port to listen on? */
  980. port = htons(n);
  981. if (errno || n > 0xffff) { /* se_service is not numeric */
  982. char protoname[4];
  983. struct servent *sp;
  984. /* can result only in "tcp" or "udp": */
  985. safe_strncpy(protoname, sep->se_proto, 4);
  986. sp = getservbyname(sep->se_service, protoname);
  987. if (sp == NULL) {
  988. bb_error_msg("%s/%s: unknown service",
  989. sep->se_service, sep->se_proto);
  990. goto next_cp;
  991. }
  992. port = sp->s_port;
  993. }
  994. if (LONE_CHAR(sep->se_local_hostname, '*')) {
  995. lsa = xzalloc_lsa(sep->se_family);
  996. set_nport(&lsa->u.sa, port);
  997. } else {
  998. lsa = host_and_af2sockaddr(sep->se_local_hostname,
  999. ntohs(port), sep->se_family);
  1000. if (!lsa) {
  1001. bb_error_msg("%s/%s: unknown host '%s'",
  1002. sep->se_service, sep->se_proto,
  1003. sep->se_local_hostname);
  1004. goto next_cp;
  1005. }
  1006. }
  1007. break;
  1008. } /* end of "switch (sep->se_family)" */
  1009. /* did lsa change? Then close/open */
  1010. if (sep->se_lsa == NULL
  1011. || lsa->len != sep->se_lsa->len
  1012. || memcmp(&lsa->u.sa, &sep->se_lsa->u.sa, lsa->len) != 0
  1013. ) {
  1014. remove_fd_from_set(sep->se_fd);
  1015. maybe_close(sep->se_fd);
  1016. free(sep->se_lsa);
  1017. sep->se_lsa = lsa;
  1018. sep->se_fd = -1;
  1019. } else {
  1020. free(lsa);
  1021. }
  1022. if (sep->se_fd == -1)
  1023. prepare_socket_fd(sep);
  1024. next_cp:
  1025. sep = cp->se_next;
  1026. free(cp);
  1027. cp = sep;
  1028. } /* end of "while (1) parse lines" */
  1029. close_config_file();
  1030. /* Purge anything not looked at above - these are stale entries,
  1031. * new config file doesnt have them. */
  1032. block_CHLD_HUP_ALRM(&omask);
  1033. sepp = &serv_list;
  1034. while ((sep = *sepp) != NULL) {
  1035. if (sep->se_checked) {
  1036. sepp = &sep->se_next;
  1037. continue;
  1038. }
  1039. *sepp = sep->se_next;
  1040. remove_fd_from_set(sep->se_fd);
  1041. maybe_close(sep->se_fd);
  1042. #if ENABLE_FEATURE_INETD_RPC
  1043. if (is_rpc_service(sep))
  1044. unregister_rpc(sep);
  1045. #endif
  1046. if (sep->se_family == AF_UNIX)
  1047. unlink(sep->se_service);
  1048. free_servtab_strings(sep);
  1049. free(sep);
  1050. }
  1051. restore_sigmask(&omask);
  1052. ret:
  1053. errno = save_errno;
  1054. }
  1055. static void reap_child(int sig UNUSED_PARAM)
  1056. {
  1057. pid_t pid;
  1058. int status;
  1059. servtab_t *sep;
  1060. int save_errno = errno;
  1061. for (;;) {
  1062. pid = wait_any_nohang(&status);
  1063. if (pid <= 0)
  1064. break;
  1065. for (sep = serv_list; sep; sep = sep->se_next) {
  1066. if (sep->se_wait != pid)
  1067. continue;
  1068. /* One of our "wait" services */
  1069. if (WIFEXITED(status) && WEXITSTATUS(status))
  1070. bb_error_msg("%s: exit status %u",
  1071. sep->se_program, WEXITSTATUS(status));
  1072. else if (WIFSIGNALED(status))
  1073. bb_error_msg("%s: exit signal %u",
  1074. sep->se_program, WTERMSIG(status));
  1075. sep->se_wait = 1;
  1076. add_fd_to_set(sep->se_fd);
  1077. break;
  1078. }
  1079. }
  1080. errno = save_errno;
  1081. }
  1082. static void retry_network_setup(int sig UNUSED_PARAM)
  1083. {
  1084. int save_errno = errno;
  1085. servtab_t *sep;
  1086. alarm_armed = 0;
  1087. for (sep = serv_list; sep; sep = sep->se_next) {
  1088. if (sep->se_fd == -1) {
  1089. prepare_socket_fd(sep);
  1090. #if ENABLE_FEATURE_INETD_RPC
  1091. if (sep->se_fd != -1 && is_rpc_service(sep))
  1092. register_rpc(sep);
  1093. #endif
  1094. }
  1095. }
  1096. errno = save_errno;
  1097. }
  1098. static void clean_up_and_exit(int sig UNUSED_PARAM)
  1099. {
  1100. servtab_t *sep;
  1101. /* XXX signal race walking sep list */
  1102. for (sep = serv_list; sep; sep = sep->se_next) {
  1103. if (sep->se_fd == -1)
  1104. continue;
  1105. switch (sep->se_family) {
  1106. case AF_UNIX:
  1107. unlink(sep->se_service);
  1108. break;
  1109. default: /* case AF_INET, AF_INET6 */
  1110. #if ENABLE_FEATURE_INETD_RPC
  1111. if (sep->se_wait == 1 && is_rpc_service(sep))
  1112. unregister_rpc(sep); /* XXX signal race */
  1113. #endif
  1114. break;
  1115. }
  1116. if (ENABLE_FEATURE_CLEAN_UP)
  1117. close(sep->se_fd);
  1118. }
  1119. remove_pidfile(CONFIG_PID_FILE_PATH "/inetd.pid");
  1120. exit(EXIT_SUCCESS);
  1121. }
  1122. int inetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1123. int inetd_main(int argc UNUSED_PARAM, char **argv)
  1124. {
  1125. struct sigaction sa, saved_pipe_handler;
  1126. servtab_t *sep, *sep2;
  1127. struct passwd *pwd;
  1128. struct group *grp = grp; /* for compiler */
  1129. int opt;
  1130. pid_t pid;
  1131. sigset_t omask;
  1132. INIT_G();
  1133. real_uid = getuid();
  1134. if (real_uid != 0) /* run by non-root user */
  1135. config_filename = NULL;
  1136. /* -q N, -R N */
  1137. opt = getopt32(argv, "R:+feq:+", &max_concurrency, &global_queuelen);
  1138. argv += optind;
  1139. //argc -= optind;
  1140. if (argv[0])
  1141. config_filename = argv[0];
  1142. if (config_filename == NULL)
  1143. bb_error_msg_and_die("non-root must specify config file");
  1144. if (!(opt & 2))
  1145. bb_daemonize_or_rexec(0, argv - optind);
  1146. else
  1147. bb_sanitize_stdio();
  1148. if (!(opt & 4)) {
  1149. /* LOG_NDELAY: connect to syslog daemon NOW.
  1150. * Otherwise, we may open syslog socket
  1151. * in vforked child, making opened fds and syslog()
  1152. * internal state inconsistent.
  1153. * This was observed to leak file descriptors. */
  1154. openlog(applet_name, LOG_PID | LOG_NDELAY, LOG_DAEMON);
  1155. logmode = LOGMODE_SYSLOG;
  1156. }
  1157. if (real_uid == 0) {
  1158. /* run by root, ensure groups vector gets trashed */
  1159. gid_t gid = getgid();
  1160. setgroups(1, &gid);
  1161. }
  1162. write_pidfile(CONFIG_PID_FILE_PATH "/inetd.pid");
  1163. /* never fails under Linux (except if you pass it bad arguments) */
  1164. getrlimit(RLIMIT_NOFILE, &rlim_ofile);
  1165. rlim_ofile_cur = rlim_ofile.rlim_cur;
  1166. if (rlim_ofile_cur == RLIM_INFINITY) /* ! */
  1167. rlim_ofile_cur = OPEN_MAX;
  1168. memset(&sa, 0, sizeof(sa));
  1169. /*sigemptyset(&sa.sa_mask); - memset did it */
  1170. sigaddset(&sa.sa_mask, SIGALRM);
  1171. sigaddset(&sa.sa_mask, SIGCHLD);
  1172. sigaddset(&sa.sa_mask, SIGHUP);
  1173. //FIXME: explain why no SA_RESTART
  1174. //FIXME: retry_network_setup is unsafe to run in signal handler (many reasons)!
  1175. sa.sa_handler = retry_network_setup;
  1176. sigaction_set(SIGALRM, &sa);
  1177. //FIXME: reread_config_file is unsafe to run in signal handler(many reasons)!
  1178. sa.sa_handler = reread_config_file;
  1179. sigaction_set(SIGHUP, &sa);
  1180. //FIXME: reap_child is unsafe to run in signal handler (uses stdio)!
  1181. sa.sa_handler = reap_child;
  1182. sigaction_set(SIGCHLD, &sa);
  1183. //FIXME: clean_up_and_exit is unsafe to run in signal handler (uses stdio)!
  1184. sa.sa_handler = clean_up_and_exit;
  1185. sigaction_set(SIGTERM, &sa);
  1186. sa.sa_handler = clean_up_and_exit;
  1187. sigaction_set(SIGINT, &sa);
  1188. sa.sa_handler = SIG_IGN;
  1189. sigaction(SIGPIPE, &sa, &saved_pipe_handler);
  1190. reread_config_file(SIGHUP); /* load config from file */
  1191. for (;;) {
  1192. int ready_fd_cnt;
  1193. int ctrl, accepted_fd, new_udp_fd;
  1194. fd_set readable;
  1195. if (maxsock < 0)
  1196. recalculate_maxsock();
  1197. readable = allsock; /* struct copy */
  1198. /* if there are no fds to wait on, we will block
  1199. * until signal wakes us up (maxsock == 0, but readable
  1200. * never contains fds 0 and 1...) */
  1201. ready_fd_cnt = select(maxsock + 1, &readable, NULL, NULL, NULL);
  1202. if (ready_fd_cnt < 0) {
  1203. if (errno != EINTR) {
  1204. bb_perror_msg("select");
  1205. sleep(1);
  1206. }
  1207. continue;
  1208. }
  1209. dbg("ready_fd_cnt:%d\n", ready_fd_cnt);
  1210. for (sep = serv_list; ready_fd_cnt && sep; sep = sep->se_next) {
  1211. if (sep->se_fd == -1 || !FD_ISSET(sep->se_fd, &readable))
  1212. continue;
  1213. dbg("ready fd:%d\n", sep->se_fd);
  1214. ready_fd_cnt--;
  1215. ctrl = sep->se_fd;
  1216. accepted_fd = -1;
  1217. new_udp_fd = -1;
  1218. if (!sep->se_wait) {
  1219. if (sep->se_socktype == SOCK_STREAM) {
  1220. ctrl = accepted_fd = accept(sep->se_fd, NULL, NULL);
  1221. dbg("accepted_fd:%d\n", accepted_fd);
  1222. if (ctrl < 0) {
  1223. if (errno != EINTR)
  1224. bb_perror_msg("accept (for %s)", sep->se_service);
  1225. continue;
  1226. }
  1227. }
  1228. /* "nowait" udp */
  1229. if (sep->se_socktype == SOCK_DGRAM
  1230. && sep->se_family != AF_UNIX
  1231. ) {
  1232. /* How udp "nowait" works:
  1233. * child peeks at (received and buffered by kernel) UDP packet,
  1234. * performs connect() on the socket so that it is linked only
  1235. * to this peer. But this also affects parent, because descriptors
  1236. * are shared after fork() a-la dup(). When parent performs
  1237. * select(), it will see this descriptor connected to the peer (!)
  1238. * and still readable, will act on it and mess things up
  1239. * (can create many copies of same child, etc).
  1240. * Parent must create and use new socket instead. */
  1241. new_udp_fd = socket(sep->se_family, SOCK_DGRAM, 0);
  1242. dbg("new_udp_fd:%d\n", new_udp_fd);
  1243. if (new_udp_fd < 0) { /* error: eat packet, forget about it */
  1244. udp_err:
  1245. recv(sep->se_fd, line, LINE_SIZE, MSG_DONTWAIT);
  1246. continue;
  1247. }
  1248. setsockopt_reuseaddr(new_udp_fd);
  1249. /* TODO: better do bind after fork in parent,
  1250. * so that we don't have two wildcard bound sockets
  1251. * even for a brief moment? */
  1252. if (bind(new_udp_fd, &sep->se_lsa->u.sa, sep->se_lsa->len) < 0) {
  1253. dbg("bind(new_udp_fd) failed\n");
  1254. close(new_udp_fd);
  1255. goto udp_err;
  1256. }
  1257. dbg("bind(new_udp_fd) succeeded\n");
  1258. }
  1259. }
  1260. block_CHLD_HUP_ALRM(&omask);
  1261. pid = 0;
  1262. #ifdef INETD_BUILTINS_ENABLED
  1263. /* do we need to fork? */
  1264. if (sep->se_builtin == NULL
  1265. || (sep->se_socktype == SOCK_STREAM
  1266. && sep->se_builtin->bi_fork))
  1267. #endif
  1268. {
  1269. if (sep->se_max != 0) {
  1270. if (++sep->se_count == 1)
  1271. sep->se_time = monotonic_sec();
  1272. else if (sep->se_count >= sep->se_max) {
  1273. unsigned now = monotonic_sec();
  1274. /* did we accumulate se_max connects too quickly? */
  1275. if (now - sep->se_time <= CNT_INTERVAL) {
  1276. bb_error_msg("%s/%s: too many connections, pausing",
  1277. sep->se_service, sep->se_proto);
  1278. remove_fd_from_set(sep->se_fd);
  1279. close(sep->se_fd);
  1280. sep->se_fd = -1;
  1281. sep->se_count = 0;
  1282. rearm_alarm(); /* will revive it in RETRYTIME sec */
  1283. restore_sigmask(&omask);
  1284. maybe_close(new_udp_fd);
  1285. maybe_close(accepted_fd);
  1286. continue; /* -> check next fd in fd set */
  1287. }
  1288. sep->se_count = 0;
  1289. }
  1290. }
  1291. /* on NOMMU, streamed chargen
  1292. * builtin wouldn't work, but it is
  1293. * not allowed on NOMMU (ifdefed out) */
  1294. #ifdef INETD_BUILTINS_ENABLED
  1295. if (BB_MMU && sep->se_builtin)
  1296. pid = fork();
  1297. else
  1298. #endif
  1299. pid = vfork();
  1300. if (pid < 0) { /* fork error */
  1301. bb_perror_msg("vfork"+1);
  1302. sleep(1);
  1303. restore_sigmask(&omask);
  1304. maybe_close(new_udp_fd);
  1305. maybe_close(accepted_fd);
  1306. continue; /* -> check next fd in fd set */
  1307. }
  1308. if (pid == 0)
  1309. pid--; /* -1: "we did fork and we are child" */
  1310. }
  1311. /* if pid == 0 here, we didn't fork */
  1312. if (pid > 0) { /* parent */
  1313. if (sep->se_wait) {
  1314. /* wait: we passed socket to child,
  1315. * will wait for child to terminate */
  1316. sep->se_wait = pid;
  1317. remove_fd_from_set(sep->se_fd);
  1318. }
  1319. if (new_udp_fd >= 0) {
  1320. /* udp nowait: child connected the socket,
  1321. * we created and will use new, unconnected one */
  1322. xmove_fd(new_udp_fd, sep->se_fd);
  1323. dbg("moved new_udp_fd:%d to sep->se_fd:%d\n", new_udp_fd, sep->se_fd);
  1324. }
  1325. restore_sigmask(&omask);
  1326. maybe_close(accepted_fd);
  1327. continue; /* -> check next fd in fd set */
  1328. }
  1329. /* we are either child or didn't fork at all */
  1330. #ifdef INETD_BUILTINS_ENABLED
  1331. if (sep->se_builtin) {
  1332. if (pid) { /* "pid" is -1: we did fork */
  1333. close(sep->se_fd); /* listening socket */
  1334. dbg("closed sep->se_fd:%d\n", sep->se_fd);
  1335. logmode = LOGMODE_NONE; /* make xwrite etc silent */
  1336. }
  1337. restore_sigmask(&omask);
  1338. if (sep->se_socktype == SOCK_STREAM)
  1339. sep->se_builtin->bi_stream_fn(ctrl, sep);
  1340. else
  1341. sep->se_builtin->bi_dgram_fn(ctrl, sep);
  1342. if (pid) /* we did fork */
  1343. _exit(EXIT_FAILURE);
  1344. maybe_close(accepted_fd);
  1345. continue; /* -> check next fd in fd set */
  1346. }
  1347. #endif
  1348. /* child */
  1349. setsid();
  1350. /* "nowait" udp */
  1351. if (new_udp_fd >= 0) {
  1352. len_and_sockaddr *lsa;
  1353. int r;
  1354. close(new_udp_fd);
  1355. dbg("closed new_udp_fd:%d\n", new_udp_fd);
  1356. lsa = xzalloc_lsa(sep->se_family);
  1357. /* peek at the packet and remember peer addr */
  1358. r = recvfrom(ctrl, NULL, 0, MSG_PEEK|MSG_DONTWAIT,
  1359. &lsa->u.sa, &lsa->len);
  1360. if (r < 0)
  1361. goto do_exit1;
  1362. /* make this socket "connected" to peer addr:
  1363. * only packets from this peer will be recv'ed,
  1364. * and bare write()/send() will work on it */
  1365. connect(ctrl, &lsa->u.sa, lsa->len);
  1366. dbg("connected ctrl:%d to remote peer\n", ctrl);
  1367. free(lsa);
  1368. }
  1369. /* prepare env and exec program */
  1370. pwd = getpwnam(sep->se_user);
  1371. if (pwd == NULL) {
  1372. bb_error_msg("%s: no such %s", sep->se_user, "user");
  1373. goto do_exit1;
  1374. }
  1375. if (sep->se_group && (grp = getgrnam(sep->se_group)) == NULL) {
  1376. bb_error_msg("%s: no such %s", sep->se_group, "group");
  1377. goto do_exit1;
  1378. }
  1379. if (real_uid != 0 && real_uid != pwd->pw_uid) {
  1380. /* a user running private inetd */
  1381. bb_error_msg("non-root must run services as himself");
  1382. goto do_exit1;
  1383. }
  1384. if (pwd->pw_uid != 0) {
  1385. if (sep->se_group)
  1386. pwd->pw_gid = grp->gr_gid;
  1387. /* initgroups, setgid, setuid: */
  1388. change_identity(pwd);
  1389. } else if (sep->se_group) {
  1390. xsetgid(grp->gr_gid);
  1391. setgroups(1, &grp->gr_gid);
  1392. }
  1393. if (rlim_ofile.rlim_cur != rlim_ofile_cur)
  1394. if (setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
  1395. bb_perror_msg("setrlimit");
  1396. /* closelog(); - WRONG. we are after vfork,
  1397. * this may confuse syslog() internal state.
  1398. * Let's hope libc sets syslog fd to CLOEXEC...
  1399. */
  1400. xmove_fd(ctrl, STDIN_FILENO);
  1401. xdup2(STDIN_FILENO, STDOUT_FILENO);
  1402. dbg("moved ctrl:%d to fd 0,1[,2]\n", ctrl);
  1403. /* manpages of inetd I managed to find either say
  1404. * that stderr is also redirected to the network,
  1405. * or do not talk about redirection at all (!) */
  1406. if (!sep->se_wait) /* only for usual "tcp nowait" */
  1407. xdup2(STDIN_FILENO, STDERR_FILENO);
  1408. /* NB: among others, this loop closes listening sockets
  1409. * for nowait stream children */
  1410. for (sep2 = serv_list; sep2; sep2 = sep2->se_next)
  1411. if (sep2->se_fd != ctrl)
  1412. maybe_close(sep2->se_fd);
  1413. sigaction_set(SIGPIPE, &saved_pipe_handler);
  1414. restore_sigmask(&omask);
  1415. dbg("execing:'%s'\n", sep->se_program);
  1416. BB_EXECVP(sep->se_program, sep->se_argv);
  1417. bb_perror_msg("can't execute '%s'", sep->se_program);
  1418. do_exit1:
  1419. /* eat packet in udp case */
  1420. if (sep->se_socktype != SOCK_STREAM)
  1421. recv(0, line, LINE_SIZE, MSG_DONTWAIT);
  1422. _exit(EXIT_FAILURE);
  1423. } /* for (sep = servtab...) */
  1424. } /* for (;;) */
  1425. }
  1426. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO \
  1427. || ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
  1428. # if !BB_MMU
  1429. static const char *const cat_args[] = { "cat", NULL };
  1430. # endif
  1431. #endif
  1432. /*
  1433. * Internet services provided internally by inetd:
  1434. */
  1435. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_ECHO
  1436. /* Echo service -- echo data back. */
  1437. /* ARGSUSED */
  1438. static void FAST_FUNC echo_stream(int s, servtab_t *sep UNUSED_PARAM)
  1439. {
  1440. # if BB_MMU
  1441. while (1) {
  1442. ssize_t sz = safe_read(s, line, LINE_SIZE);
  1443. if (sz <= 0)
  1444. break;
  1445. xwrite(s, line, sz);
  1446. }
  1447. # else
  1448. /* We are after vfork here! */
  1449. /* move network socket to stdin/stdout */
  1450. xmove_fd(s, STDIN_FILENO);
  1451. xdup2(STDIN_FILENO, STDOUT_FILENO);
  1452. /* no error messages please... */
  1453. close(STDERR_FILENO);
  1454. xopen(bb_dev_null, O_WRONLY);
  1455. BB_EXECVP("cat", (char**)cat_args);
  1456. /* on failure we return to main, which does exit(EXIT_FAILURE) */
  1457. # endif
  1458. }
  1459. static void FAST_FUNC echo_dg(int s, servtab_t *sep)
  1460. {
  1461. enum { BUFSIZE = 12*1024 }; /* for jumbo sized packets! :) */
  1462. char *buf = xmalloc(BUFSIZE); /* too big for stack */
  1463. int sz;
  1464. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1465. lsa->len = sep->se_lsa->len;
  1466. /* dgram builtins are non-forking - DONT BLOCK! */
  1467. sz = recvfrom(s, buf, BUFSIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len);
  1468. if (sz > 0)
  1469. sendto(s, buf, sz, 0, &lsa->u.sa, lsa->len);
  1470. free(buf);
  1471. }
  1472. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_ECHO */
  1473. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD
  1474. /* Discard service -- ignore data. */
  1475. /* ARGSUSED */
  1476. static void FAST_FUNC discard_stream(int s, servtab_t *sep UNUSED_PARAM)
  1477. {
  1478. # if BB_MMU
  1479. while (safe_read(s, line, LINE_SIZE) > 0)
  1480. continue;
  1481. # else
  1482. /* We are after vfork here! */
  1483. /* move network socket to stdin */
  1484. xmove_fd(s, STDIN_FILENO);
  1485. /* discard output */
  1486. close(STDOUT_FILENO);
  1487. xopen(bb_dev_null, O_WRONLY);
  1488. /* no error messages please... */
  1489. xdup2(STDOUT_FILENO, STDERR_FILENO);
  1490. BB_EXECVP("cat", (char**)cat_args);
  1491. /* on failure we return to main, which does exit(EXIT_FAILURE) */
  1492. # endif
  1493. }
  1494. /* ARGSUSED */
  1495. static void FAST_FUNC discard_dg(int s, servtab_t *sep UNUSED_PARAM)
  1496. {
  1497. /* dgram builtins are non-forking - DONT BLOCK! */
  1498. recv(s, line, LINE_SIZE, MSG_DONTWAIT);
  1499. }
  1500. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_DISCARD */
  1501. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN
  1502. #define LINESIZ 72
  1503. static void init_ring(void)
  1504. {
  1505. int i;
  1506. end_ring = ring;
  1507. for (i = ' '; i < 127; i++)
  1508. *end_ring++ = i;
  1509. }
  1510. /* Character generator. MMU arches only. */
  1511. /* ARGSUSED */
  1512. static void FAST_FUNC chargen_stream(int s, servtab_t *sep UNUSED_PARAM)
  1513. {
  1514. char *rs;
  1515. int len;
  1516. char text[LINESIZ + 2];
  1517. if (!end_ring) {
  1518. init_ring();
  1519. rs = ring;
  1520. }
  1521. text[LINESIZ] = '\r';
  1522. text[LINESIZ + 1] = '\n';
  1523. rs = ring;
  1524. for (;;) {
  1525. len = end_ring - rs;
  1526. if (len >= LINESIZ)
  1527. memmove(text, rs, LINESIZ);
  1528. else {
  1529. memmove(text, rs, len);
  1530. memmove(text + len, ring, LINESIZ - len);
  1531. }
  1532. if (++rs == end_ring)
  1533. rs = ring;
  1534. xwrite(s, text, sizeof(text));
  1535. }
  1536. }
  1537. /* ARGSUSED */
  1538. static void FAST_FUNC chargen_dg(int s, servtab_t *sep)
  1539. {
  1540. int len;
  1541. char text[LINESIZ + 2];
  1542. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1543. /* Eat UDP packet which started it all */
  1544. /* dgram builtins are non-forking - DONT BLOCK! */
  1545. lsa->len = sep->se_lsa->len;
  1546. if (recvfrom(s, text, sizeof(text), MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
  1547. return;
  1548. if (!end_ring) {
  1549. init_ring();
  1550. ring_pos = ring;
  1551. }
  1552. len = end_ring - ring_pos;
  1553. if (len >= LINESIZ)
  1554. memmove(text, ring_pos, LINESIZ);
  1555. else {
  1556. memmove(text, ring_pos, len);
  1557. memmove(text + len, ring, LINESIZ - len);
  1558. }
  1559. if (++ring_pos == end_ring)
  1560. ring_pos = ring;
  1561. text[LINESIZ] = '\r';
  1562. text[LINESIZ + 1] = '\n';
  1563. sendto(s, text, sizeof(text), 0, &lsa->u.sa, lsa->len);
  1564. }
  1565. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN */
  1566. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_TIME
  1567. /*
  1568. * Return a machine readable date and time, in the form of the
  1569. * number of seconds since midnight, Jan 1, 1900. Since gettimeofday
  1570. * returns the number of seconds since midnight, Jan 1, 1970,
  1571. * we must add 2208988800 seconds to this figure to make up for
  1572. * some seventy years Bell Labs was asleep.
  1573. */
  1574. static uint32_t machtime(void)
  1575. {
  1576. struct timeval tv;
  1577. gettimeofday(&tv, NULL);
  1578. return htonl((uint32_t)(tv.tv_sec + 2208988800U));
  1579. }
  1580. /* ARGSUSED */
  1581. static void FAST_FUNC machtime_stream(int s, servtab_t *sep UNUSED_PARAM)
  1582. {
  1583. uint32_t result;
  1584. result = machtime();
  1585. full_write(s, &result, sizeof(result));
  1586. }
  1587. static void FAST_FUNC machtime_dg(int s, servtab_t *sep)
  1588. {
  1589. uint32_t result;
  1590. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1591. lsa->len = sep->se_lsa->len;
  1592. if (recvfrom(s, line, LINE_SIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
  1593. return;
  1594. result = machtime();
  1595. sendto(s, &result, sizeof(result), 0, &lsa->u.sa, lsa->len);
  1596. }
  1597. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_TIME */
  1598. #if ENABLE_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME
  1599. /* Return human-readable time of day */
  1600. /* ARGSUSED */
  1601. static void FAST_FUNC daytime_stream(int s, servtab_t *sep UNUSED_PARAM)
  1602. {
  1603. time_t t;
  1604. time(&t);
  1605. fdprintf(s, "%.24s\r\n", ctime(&t));
  1606. }
  1607. static void FAST_FUNC daytime_dg(int s, servtab_t *sep)
  1608. {
  1609. time_t t;
  1610. len_and_sockaddr *lsa = alloca(LSA_LEN_SIZE + sep->se_lsa->len);
  1611. lsa->len = sep->se_lsa->len;
  1612. if (recvfrom(s, line, LINE_SIZE, MSG_DONTWAIT, &lsa->u.sa, &lsa->len) < 0)
  1613. return;
  1614. t = time(NULL);
  1615. sprintf(line, "%.24s\r\n", ctime(&t));
  1616. sendto(s, line, strlen(line), 0, &lsa->u.sa, lsa->len);
  1617. }
  1618. #endif /* FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME */