inetd.c 51 KB

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