resolv.c 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328
  1. /* vi: set sw=4 ts=4: */
  2. /* resolv.c: DNS Resolver
  3. *
  4. * Copyright (C) 1998 Kenneth Albanowski <kjahds@kjahds.com>,
  5. * The Silver Hammer Group, Ltd.
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Library General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2 of the License, or (at your option) any later version.
  11. */
  12. /*
  13. * Portions Copyright (c) 1985, 1993
  14. * The Regents of the University of California. All rights reserved.
  15. *
  16. * Redistribution and use in source and binary forms, with or without
  17. * modification, are permitted provided that the following conditions
  18. * are met:
  19. * 1. Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. * 2. Redistributions in binary form must reproduce the above copyright
  22. * notice, this list of conditions and the following disclaimer in the
  23. * documentation and/or other materials provided with the distribution.
  24. * 4. Neither the name of the University nor the names of its contributors
  25. * may be used to endorse or promote products derived from this software
  26. * without specific prior written permission.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  29. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  30. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  31. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  32. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  33. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  34. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  37. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  38. * SUCH DAMAGE.
  39. */
  40. /*
  41. * Portions Copyright (c) 1993 by Digital Equipment Corporation.
  42. *
  43. * Permission to use, copy, modify, and distribute this software for any
  44. * purpose with or without fee is hereby granted, provided that the above
  45. * copyright notice and this permission notice appear in all copies, and that
  46. * the name of Digital Equipment Corporation not be used in advertising or
  47. * publicity pertaining to distribution of the document or software without
  48. * specific, written prior permission.
  49. *
  50. * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
  51. * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
  52. * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
  53. * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  54. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  55. * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  56. * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  57. * SOFTWARE.
  58. */
  59. /*
  60. * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
  61. *
  62. * Permission to use, copy, modify, and distribute this software for any
  63. * purpose with or without fee is hereby granted, provided that the above
  64. * copyright notice and this permission notice appear in all copies.
  65. *
  66. * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
  67. * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
  68. * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
  69. * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  70. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  71. * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  72. * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  73. * SOFTWARE.
  74. */
  75. /*
  76. * 5-Oct-2000 W. Greathouse wgreathouse@smva.com
  77. * Fix memory leak and memory corruption.
  78. * -- Every name resolution resulted in
  79. * a new parse of resolv.conf and new
  80. * copy of nameservers allocated by
  81. * strdup.
  82. * -- Every name resolution resulted in
  83. * a new read of resolv.conf without
  84. * resetting index from prior read...
  85. * resulting in exceeding array bounds.
  86. *
  87. * Limit nameservers read from resolv.conf.
  88. * Add "search" domains from resolv.conf.
  89. * Some systems will return a security
  90. * signature along with query answer for
  91. * dynamic DNS entries -- skip/ignore this answer.
  92. * Include arpa/nameser.h for defines.
  93. * General cleanup.
  94. *
  95. * 20-Jun-2001 Michal Moskal <malekith@pld.org.pl>
  96. * partial IPv6 support (i.e. gethostbyname2() and resolve_address2()
  97. * functions added), IPv6 nameservers are also supported.
  98. *
  99. * 6-Oct-2001 Jari Korva <jari.korva@iki.fi>
  100. * more IPv6 support (IPv6 support for gethostbyaddr();
  101. * address family parameter and improved IPv6 support for get_hosts_byname
  102. * and read_etc_hosts; getnameinfo() port from glibc; defined
  103. * defined ip6addr_any and in6addr_loopback)
  104. *
  105. * 2-Feb-2002 Erik Andersen <andersen@codepoet.org>
  106. * Added gethostent(), sethostent(), and endhostent()
  107. *
  108. * 17-Aug-2002 Manuel Novoa III <mjn3@codepoet.org>
  109. * Fixed __read_etc_hosts_r to return alias list, and modified buffer
  110. * allocation accordingly. See MAX_ALIASES and ALIAS_DIM below.
  111. * This fixes the segfault in the Python 2.2.1 socket test.
  112. *
  113. * 04-Jan-2003 Jay Kulpinski <jskulpin@berkshire.rr.com>
  114. * Fixed __decode_dotted to count the terminating null character
  115. * in a host name.
  116. *
  117. * 02-Oct-2003 Tony J. White <tjw@tjw.org>
  118. * Lifted dn_expand() and dependent ns_name_uncompress(), ns_name_unpack(),
  119. * and ns_name_ntop() from glibc 2.3.2 for compatibility with ipsec-tools
  120. * and openldap.
  121. *
  122. * 7-Sep-2004 Erik Andersen <andersen@codepoet.org>
  123. * Added gethostent_r()
  124. *
  125. * 2008, 2009 Denys Vlasenko <vda.linux@googlemail.com>
  126. * Cleanups, fixes, readability, more cleanups and more fixes.
  127. *
  128. * March 2010 Bernhard Reutner-Fischer
  129. * Switch to common config parser
  130. */
  131. /* Nota bene:
  132. * The whole resolver code has several (severe) problems:
  133. * - it doesn't even build without IPv4, i.e. !UCLIBC_HAS_IPV4 but only IPv6
  134. * - it is way too big
  135. *
  136. * Both points above are considered bugs, patches/reimplementations welcome.
  137. */
  138. /* RFC 1035
  139. ...
  140. Whenever an octet represents a numeric quantity, the left most bit
  141. in the diagram is the high order or most significant bit.
  142. That is, the bit labeled 0 is the most significant bit.
  143. ...
  144. 4.1.1. Header section format
  145. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  146. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  147. | ID |
  148. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  149. |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE |
  150. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  151. | QDCOUNT |
  152. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  153. | ANCOUNT |
  154. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  155. | NSCOUNT |
  156. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  157. | ARCOUNT |
  158. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  159. ID 16 bit random identifier assigned by querying peer.
  160. Used to match query/response.
  161. QR message is a query (0), or a response (1).
  162. OPCODE 0 standard query (QUERY)
  163. 1 inverse query (IQUERY)
  164. 2 server status request (STATUS)
  165. AA Authoritative Answer - this bit is valid in responses.
  166. Responding name server is an authority for the domain name
  167. in question section. Answer section may have multiple owner names
  168. because of aliases. The AA bit corresponds to the name which matches
  169. the query name, or the first owner name in the answer section.
  170. TC TrunCation - this message was truncated.
  171. RD Recursion Desired - this bit may be set in a query and
  172. is copied into the response. If RD is set, it directs
  173. the name server to pursue the query recursively.
  174. Recursive query support is optional.
  175. RA Recursion Available - this be is set or cleared in a
  176. response, and denotes whether recursive query support is
  177. available in the name server.
  178. RCODE Response code.
  179. 0 No error condition
  180. 1 Format error
  181. 2 Server failure - server was unable to process the query
  182. due to a problem with the name server.
  183. 3 Name Error - meaningful only for responses from
  184. an authoritative name server. The referenced domain name
  185. does not exist.
  186. 4 Not Implemented.
  187. 5 Refused.
  188. QDCOUNT number of entries in the question section.
  189. ANCOUNT number of records in the answer section.
  190. NSCOUNT number of records in the authority records section.
  191. ARCOUNT number of records in the additional records section.
  192. 4.1.2. Question section format
  193. The section contains QDCOUNT (usually 1) entries, each of this format:
  194. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  195. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  196. / QNAME /
  197. / /
  198. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  199. | QTYPE |
  200. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  201. | QCLASS |
  202. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  203. QNAME a domain name represented as a sequence of labels, where
  204. each label consists of a length octet followed by that
  205. number of octets. The domain name terminates with the
  206. zero length octet for the null label of the root. Note
  207. that this field may be an odd number of octets; no
  208. padding is used.
  209. QTYPE a two octet type of the query.
  210. 1 a host address [REQ_A const]
  211. 2 an authoritative name server
  212. 3 a mail destination (Obsolete - use MX)
  213. 4 a mail forwarder (Obsolete - use MX)
  214. 5 the canonical name for an alias
  215. 6 marks the start of a zone of authority
  216. 7 a mailbox domain name (EXPERIMENTAL)
  217. 8 a mail group member (EXPERIMENTAL)
  218. 9 a mail rename domain name (EXPERIMENTAL)
  219. 10 a null RR (EXPERIMENTAL)
  220. 11 a well known service description
  221. 12 a domain name pointer [REQ_PTR const]
  222. 13 host information
  223. 14 mailbox or mail list information
  224. 15 mail exchange
  225. 16 text strings
  226. 0x1c IPv6?
  227. 252 a request for a transfer of an entire zone
  228. 253 a request for mailbox-related records (MB, MG or MR)
  229. 254 a request for mail agent RRs (Obsolete - see MX)
  230. 255 a request for all records
  231. QCLASS a two octet code that specifies the class of the query.
  232. 1 the Internet
  233. (others are historic only)
  234. 255 any class
  235. 4.1.3. Resource record format
  236. The answer, authority, and additional sections all share the same format:
  237. a variable number of resource records, where the number of records
  238. is specified in the corresponding count field in the header.
  239. Each resource record has this format:
  240. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  241. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  242. / /
  243. / NAME /
  244. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  245. | TYPE |
  246. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  247. | CLASS |
  248. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  249. | TTL |
  250. | |
  251. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  252. | RDLENGTH |
  253. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
  254. / RDATA /
  255. / /
  256. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  257. NAME a domain name to which this resource record pertains.
  258. TYPE two octets containing one of the RR type codes. This
  259. field specifies the meaning of the data in the RDATA field.
  260. CLASS two octets which specify the class of the data in the RDATA field.
  261. TTL a 32 bit unsigned integer that specifies the time interval
  262. (in seconds) that the record may be cached.
  263. RDLENGTH a 16 bit integer, length in octets of the RDATA field.
  264. RDATA a variable length string of octets that describes the resource.
  265. The format of this information varies according to the TYPE
  266. and CLASS of the resource record.
  267. If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
  268. 4.1.4. Message compression
  269. In order to reduce the size of messages, domain names can be compressed.
  270. An entire domain name or a list of labels at the end of a domain name
  271. is replaced with a pointer to a prior occurance of the same name.
  272. The pointer takes the form of a two octet sequence:
  273. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  274. | 1 1| OFFSET |
  275. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  276. The first two bits are ones. This allows a pointer to be distinguished
  277. from a label, since the label must begin with two zero bits because
  278. labels are restricted to 63 octets or less. The OFFSET field specifies
  279. an offset from the start of the message (i.e., the first octet
  280. of the ID field in the domain header).
  281. A zero offset specifies the first byte of the ID field, etc.
  282. Domain name in a message can be represented as either:
  283. - a sequence of labels ending in a zero octet
  284. - a pointer
  285. - a sequence of labels ending with a pointer
  286. */
  287. #define __FORCE_GLIBC
  288. #include <features.h>
  289. #include <string.h>
  290. #include <stdio.h>
  291. #include <signal.h>
  292. #include <errno.h>
  293. #include <sys/poll.h>
  294. #include <sys/socket.h>
  295. #include <sys/types.h>
  296. #include <sys/time.h>
  297. #include <netinet/in.h>
  298. #include <arpa/inet.h>
  299. #include <stdlib.h>
  300. #include <unistd.h>
  301. #include <resolv.h>
  302. #include <netdb.h>
  303. #include <ctype.h>
  304. #include <stdbool.h>
  305. #include <time.h>
  306. #include <arpa/nameser.h>
  307. #include <sys/utsname.h>
  308. #include <sys/un.h>
  309. #include <sys/stat.h>
  310. #include <bits/uClibc_mutex.h>
  311. #include "internal/parse_config.h"
  312. /* poll() is not supported in kernel <= 2.0, therefore if __NR_poll is
  313. * not available, we assume an old Linux kernel is in use and we will
  314. * use select() instead. */
  315. #include <sys/syscall.h>
  316. #ifndef __NR_poll
  317. # define USE_SELECT
  318. #endif
  319. #if defined __UCLIBC_HAS_IPV4__ && defined __UCLIBC_HAS_IPV6__
  320. #define IF_HAS_BOTH(...) __VA_ARGS__
  321. #else
  322. #define IF_HAS_BOTH(...)
  323. #endif
  324. #define MAX_RECURSE 5
  325. #define MAXALIASES (6)
  326. #define BUFSZ (80) /* one line */
  327. #define SBUFSIZE (BUFSZ + 1 + (sizeof(char *) * MAXALIASES))
  328. #undef DEBUG
  329. /* #define DEBUG */
  330. #ifdef DEBUG
  331. #define DPRINTF(X,args...) fprintf(stderr, X, ##args)
  332. #else
  333. #define DPRINTF(X,args...)
  334. #endif
  335. #undef ARRAY_SIZE
  336. #define ARRAY_SIZE(v) (sizeof(v) / sizeof((v)[0]))
  337. /* Make sure the incoming char * buffer is aligned enough to handle our random
  338. * structures. This define is the same as we use for malloc alignment (which
  339. * has same requirements). The offset is the number of bytes we need to adjust
  340. * in order to attain desired alignment.
  341. */
  342. #define ALIGN_ATTR __alignof__(double __attribute_aligned__ (sizeof(size_t)))
  343. #define ALIGN_BUFFER_OFFSET(buf) ((ALIGN_ATTR - ((size_t)buf % ALIGN_ATTR)) % ALIGN_ATTR)
  344. /* Structs */
  345. struct resolv_header {
  346. int id;
  347. int qr, opcode, aa, tc, rd, ra, rcode;
  348. int qdcount;
  349. int ancount;
  350. int nscount;
  351. int arcount;
  352. };
  353. struct resolv_question {
  354. char *dotted;
  355. int qtype;
  356. int qclass;
  357. };
  358. struct resolv_answer {
  359. char *dotted;
  360. int atype;
  361. int aclass;
  362. int ttl;
  363. int rdlength;
  364. const unsigned char *rdata;
  365. int rdoffset;
  366. char* buf;
  367. size_t buflen;
  368. size_t add_count;
  369. };
  370. enum etc_hosts_action {
  371. GET_HOSTS_BYNAME = 0,
  372. GETHOSTENT,
  373. GET_HOSTS_BYADDR,
  374. };
  375. typedef union sockaddr46_t {
  376. struct sockaddr sa;
  377. #ifdef __UCLIBC_HAS_IPV4__
  378. struct sockaddr_in sa4;
  379. #endif
  380. #ifdef __UCLIBC_HAS_IPV6__
  381. struct sockaddr_in6 sa6;
  382. #endif
  383. } sockaddr46_t;
  384. __UCLIBC_MUTEX_EXTERN(__resolv_lock);
  385. /* Protected by __resolv_lock */
  386. extern void (*__res_sync)(void) attribute_hidden;
  387. /*extern uint32_t __resolv_opts attribute_hidden; */
  388. extern uint8_t __resolv_timeout attribute_hidden;
  389. extern uint8_t __resolv_attempts attribute_hidden;
  390. extern unsigned __nameservers attribute_hidden;
  391. extern unsigned __searchdomains attribute_hidden;
  392. extern sockaddr46_t *__nameserver attribute_hidden;
  393. extern char **__searchdomain attribute_hidden;
  394. #ifdef __UCLIBC_HAS_IPV4__
  395. extern const struct sockaddr_in __local_nameserver attribute_hidden;
  396. #else
  397. extern const struct sockaddr_in6 __local_nameserver attribute_hidden;
  398. #endif
  399. /* Arbitrary */
  400. #define MAXLEN_searchdomain 128
  401. /* prototypes for internal functions */
  402. extern void endhostent_unlocked(void) attribute_hidden;
  403. extern int __get_hosts_byname_r(const char *name,
  404. int type,
  405. struct hostent *result_buf,
  406. char *buf,
  407. size_t buflen,
  408. struct hostent **result,
  409. int *h_errnop) attribute_hidden;
  410. extern int __get_hosts_byaddr_r(const char *addr,
  411. int len,
  412. int type,
  413. struct hostent *result_buf,
  414. char *buf,
  415. size_t buflen,
  416. struct hostent **result,
  417. int *h_errnop) attribute_hidden;
  418. extern parser_t *__open_etc_hosts(void) attribute_hidden;
  419. extern int __read_etc_hosts_r(parser_t *parser,
  420. const char *name,
  421. int type,
  422. enum etc_hosts_action action,
  423. struct hostent *result_buf,
  424. char *buf,
  425. size_t buflen,
  426. struct hostent **result,
  427. int *h_errnop) attribute_hidden;
  428. extern int __dns_lookup(const char *name,
  429. int type,
  430. unsigned char **outpacket,
  431. struct resolv_answer *a) attribute_hidden;
  432. extern int __encode_dotted(const char *dotted,
  433. unsigned char *dest,
  434. int maxlen) attribute_hidden;
  435. extern int __decode_dotted(const unsigned char *packet,
  436. int offset,
  437. int packet_len,
  438. char *dest,
  439. int dest_len) attribute_hidden;
  440. extern int __encode_header(struct resolv_header *h,
  441. unsigned char *dest,
  442. int maxlen) attribute_hidden;
  443. extern void __decode_header(unsigned char *data,
  444. struct resolv_header *h) attribute_hidden;
  445. extern int __encode_question(const struct resolv_question *q,
  446. unsigned char *dest,
  447. int maxlen) attribute_hidden;
  448. extern int __encode_answer(struct resolv_answer *a,
  449. unsigned char *dest,
  450. int maxlen) attribute_hidden;
  451. extern void __open_nameservers(void) attribute_hidden;
  452. extern void __close_nameservers(void) attribute_hidden;
  453. /*
  454. * Theory of operation.
  455. *
  456. * gethostbyname, getaddrinfo and friends end up here, and they sometimes
  457. * need to talk to DNS servers. In order to do this, we need to read /etc/resolv.conf
  458. * and determine servers' addresses and the like. resolv.conf format:
  459. *
  460. * nameserver <IP[v6]>
  461. * Address of DNS server. Cumulative.
  462. * If not specified, assumed to be on localhost.
  463. * search <domain1>[ <domain2>]...
  464. * Append these domains to unqualified names.
  465. * See ndots:n option.
  466. * $LOCALDOMAIN (space-separated list) overrides this.
  467. * domain <domain>
  468. * Effectively same as "search" with one domain.
  469. * If no "domain" line is present, the domain is determined
  470. * from the local host name returned by gethostname();
  471. * the domain part is taken to be everything after the first dot.
  472. * If there are no dots, there will be no "domain".
  473. * The domain and search keywords are mutually exclusive.
  474. * If more than one instance of these keywords is present,
  475. * the last instance wins.
  476. * sortlist 130.155.160.0[/255.255.240.0] 130.155.0.0
  477. * Allows addresses returned by gethostbyname to be sorted.
  478. * Not supported.
  479. * options option[ option]...
  480. * (so far we support timeout:n and attempts:n)
  481. * $RES_OPTIONS (space-separated list) is to be added to "options"
  482. * debug sets RES_DEBUG in _res.options
  483. * ndots:n how many dots there should be so that name will be tried
  484. * first as an absolute name before any search list elements
  485. * are appended to it. Default 1
  486. * timeout:n how long to wait for response. Default 5
  487. * (sun seems to have retrans:n synonym)
  488. * attempts:n number of rounds to do before giving up and returning
  489. * an error. Default 2
  490. * (sun seems to have retry:n synonym)
  491. * rotate sets RES_ROTATE in _res.options, round robin
  492. * selection of nameservers. Otherwise try
  493. * the first listed server first every time
  494. * no-check-names
  495. * sets RES_NOCHECKNAME in _res.options, which disables
  496. * checking of incoming host names for invalid characters
  497. * such as underscore (_), non-ASCII, or control characters
  498. * inet6 sets RES_USE_INET6 in _res.options. Try a AAAA query
  499. * before an A query inside the gethostbyname(), and map
  500. * IPv4 responses in IPv6 "tunnelled form" if no AAAA records
  501. * are found but an A record set exists
  502. * no_tld_query (FreeBSDism?)
  503. * do not attempt to resolve names without dots
  504. *
  505. * We will read and analyze /etc/resolv.conf as needed before
  506. * we do a DNS request. This happens in __dns_lookup.
  507. * It is reread if its mtime is changed.
  508. *
  509. * BSD has res_init routine which is used to initialize resolver state
  510. * which is held in global structure _res.
  511. * Generally, programs call res_init, then fiddle with _res.XXX
  512. * (_res.options and _res.nscount, _res.nsaddr_list[N]
  513. * are popular targets of fiddling) and expect subsequent calls
  514. * to gethostbyname, getaddrinfo, etc to use modified information.
  515. *
  516. * However, historical _res structure is quite awkward.
  517. * Using it for storing /etc/resolv.conf info is not desirable,
  518. * and __dns_lookup does not use it.
  519. *
  520. * We would like to avoid using it unless absolutely necessary.
  521. * If user doesn't use res_init, we should arrange it so that
  522. * _res structure doesn't even *get linked in* into user's application
  523. * (imagine static uclibc build here).
  524. *
  525. * The solution is a __res_sync function pointer, which is normally NULL.
  526. * But if res_init is called, it gets set and any subsequent gethostbyname
  527. * et al "syncronizes" our internal structures with potentially
  528. * modified _res.XXX stuff by calling __res_sync.
  529. * The trick here is that if res_init is not used and not linked in,
  530. * gethostbyname itself won't reference _res and _res won't be linked in
  531. * either. Other possible methods like
  532. * if (__res_sync_just_an_int_flag)
  533. * __sync_me_with_res()
  534. * would pull in __sync_me_with_res, which pulls in _res. Bad.
  535. */
  536. #ifdef L_encodeh
  537. int attribute_hidden __encode_header(struct resolv_header *h, unsigned char *dest, int maxlen)
  538. {
  539. if (maxlen < HFIXEDSZ)
  540. return -1;
  541. dest[0] = (h->id & 0xff00) >> 8;
  542. dest[1] = (h->id & 0x00ff) >> 0;
  543. dest[2] = (h->qr ? 0x80 : 0) |
  544. ((h->opcode & 0x0f) << 3) |
  545. (h->aa ? 0x04 : 0) |
  546. (h->tc ? 0x02 : 0) |
  547. (h->rd ? 0x01 : 0);
  548. dest[3] = (h->ra ? 0x80 : 0) | (h->rcode & 0x0f);
  549. dest[4] = (h->qdcount & 0xff00) >> 8;
  550. dest[5] = (h->qdcount & 0x00ff) >> 0;
  551. dest[6] = (h->ancount & 0xff00) >> 8;
  552. dest[7] = (h->ancount & 0x00ff) >> 0;
  553. dest[8] = (h->nscount & 0xff00) >> 8;
  554. dest[9] = (h->nscount & 0x00ff) >> 0;
  555. dest[10] = (h->arcount & 0xff00) >> 8;
  556. dest[11] = (h->arcount & 0x00ff) >> 0;
  557. return HFIXEDSZ;
  558. }
  559. #endif
  560. #ifdef L_decodeh
  561. void attribute_hidden __decode_header(unsigned char *data,
  562. struct resolv_header *h)
  563. {
  564. h->id = (data[0] << 8) | data[1];
  565. h->qr = (data[2] & 0x80) ? 1 : 0;
  566. h->opcode = (data[2] >> 3) & 0x0f;
  567. h->aa = (data[2] & 0x04) ? 1 : 0;
  568. h->tc = (data[2] & 0x02) ? 1 : 0;
  569. h->rd = (data[2] & 0x01) ? 1 : 0;
  570. h->ra = (data[3] & 0x80) ? 1 : 0;
  571. h->rcode = data[3] & 0x0f;
  572. h->qdcount = (data[4] << 8) | data[5];
  573. h->ancount = (data[6] << 8) | data[7];
  574. h->nscount = (data[8] << 8) | data[9];
  575. h->arcount = (data[10] << 8) | data[11];
  576. }
  577. #endif
  578. #ifdef L_encoded
  579. /* Encode a dotted string into nameserver transport-level encoding.
  580. This routine is fairly dumb, and doesn't attempt to compress
  581. the data */
  582. int attribute_hidden __encode_dotted(const char *dotted, unsigned char *dest, int maxlen)
  583. {
  584. unsigned used = 0;
  585. while (dotted && *dotted) {
  586. char *c = strchr(dotted, '.');
  587. int l = c ? c - dotted : strlen(dotted);
  588. /* two consecutive dots are not valid */
  589. if (l == 0)
  590. return -1;
  591. if (l >= (maxlen - used - 1))
  592. return -1;
  593. dest[used++] = l;
  594. memcpy(dest + used, dotted, l);
  595. used += l;
  596. if (!c)
  597. break;
  598. dotted = c + 1;
  599. }
  600. if (maxlen < 1)
  601. return -1;
  602. dest[used++] = 0;
  603. return used;
  604. }
  605. #endif
  606. #ifdef L_decoded
  607. /* Decode a dotted string from nameserver transport-level encoding.
  608. This routine understands compressed data. */
  609. int attribute_hidden __decode_dotted(const unsigned char *packet,
  610. int offset,
  611. int packet_len,
  612. char *dest,
  613. int dest_len)
  614. {
  615. unsigned b;
  616. bool measure = 1;
  617. unsigned total = 0;
  618. unsigned used = 0;
  619. if (!packet)
  620. return -1;
  621. while (1) {
  622. if (offset >= packet_len)
  623. return -1;
  624. b = packet[offset++];
  625. if (b == 0)
  626. break;
  627. if (measure)
  628. total++;
  629. if ((b & 0xc0) == 0xc0) {
  630. if (offset >= packet_len)
  631. return -1;
  632. if (measure)
  633. total++;
  634. /* compressed item, redirect */
  635. offset = ((b & 0x3f) << 8) | packet[offset];
  636. measure = 0;
  637. continue;
  638. }
  639. if (used + b + 1 >= dest_len)
  640. return -1;
  641. if (offset + b >= packet_len)
  642. return -1;
  643. memcpy(dest + used, packet + offset, b);
  644. offset += b;
  645. used += b;
  646. if (measure)
  647. total += b;
  648. if (packet[offset] != 0)
  649. dest[used++] = '.';
  650. else
  651. dest[used++] = '\0';
  652. }
  653. /* The null byte must be counted too */
  654. if (measure)
  655. total++;
  656. DPRINTF("Total decode len = %d\n", total);
  657. return total;
  658. }
  659. #endif
  660. #ifdef L_encodeq
  661. int attribute_hidden __encode_question(const struct resolv_question *q,
  662. unsigned char *dest,
  663. int maxlen)
  664. {
  665. int i;
  666. i = __encode_dotted(q->dotted, dest, maxlen);
  667. if (i < 0)
  668. return i;
  669. dest += i;
  670. maxlen -= i;
  671. if (maxlen < 4)
  672. return -1;
  673. dest[0] = (q->qtype & 0xff00) >> 8;
  674. dest[1] = (q->qtype & 0x00ff) >> 0;
  675. dest[2] = (q->qclass & 0xff00) >> 8;
  676. dest[3] = (q->qclass & 0x00ff) >> 0;
  677. return i + 4;
  678. }
  679. #endif
  680. #ifdef L_encodea
  681. int attribute_hidden __encode_answer(struct resolv_answer *a, unsigned char *dest, int maxlen)
  682. {
  683. int i;
  684. i = __encode_dotted(a->dotted, dest, maxlen);
  685. if (i < 0)
  686. return i;
  687. dest += i;
  688. maxlen -= i;
  689. if (maxlen < (RRFIXEDSZ + a->rdlength))
  690. return -1;
  691. *dest++ = (a->atype & 0xff00) >> 8;
  692. *dest++ = (a->atype & 0x00ff) >> 0;
  693. *dest++ = (a->aclass & 0xff00) >> 8;
  694. *dest++ = (a->aclass & 0x00ff) >> 0;
  695. *dest++ = (a->ttl & 0xff000000) >> 24;
  696. *dest++ = (a->ttl & 0x00ff0000) >> 16;
  697. *dest++ = (a->ttl & 0x0000ff00) >> 8;
  698. *dest++ = (a->ttl & 0x000000ff) >> 0;
  699. *dest++ = (a->rdlength & 0xff00) >> 8;
  700. *dest++ = (a->rdlength & 0x00ff) >> 0;
  701. memcpy(dest, a->rdata, a->rdlength);
  702. return i + RRFIXEDSZ + a->rdlength;
  703. }
  704. #endif
  705. #ifdef CURRENTLY_UNUSED
  706. #ifdef L_encodep
  707. int __encode_packet(struct resolv_header *h,
  708. struct resolv_question **q,
  709. struct resolv_answer **an,
  710. struct resolv_answer **ns,
  711. struct resolv_answer **ar,
  712. unsigned char *dest, int maxlen) attribute_hidden;
  713. int __encode_packet(struct resolv_header *h,
  714. struct resolv_question **q,
  715. struct resolv_answer **an,
  716. struct resolv_answer **ns,
  717. struct resolv_answer **ar,
  718. unsigned char *dest, int maxlen)
  719. {
  720. int i, total = 0;
  721. unsigned j;
  722. i = __encode_header(h, dest, maxlen);
  723. if (i < 0)
  724. return i;
  725. dest += i;
  726. maxlen -= i;
  727. total += i;
  728. for (j = 0; j < h->qdcount; j++) {
  729. i = __encode_question(q[j], dest, maxlen);
  730. if (i < 0)
  731. return i;
  732. dest += i;
  733. maxlen -= i;
  734. total += i;
  735. }
  736. for (j = 0; j < h->ancount; j++) {
  737. i = __encode_answer(an[j], dest, maxlen);
  738. if (i < 0)
  739. return i;
  740. dest += i;
  741. maxlen -= i;
  742. total += i;
  743. }
  744. for (j = 0; j < h->nscount; j++) {
  745. i = __encode_answer(ns[j], dest, maxlen);
  746. if (i < 0)
  747. return i;
  748. dest += i;
  749. maxlen -= i;
  750. total += i;
  751. }
  752. for (j = 0; j < h->arcount; j++) {
  753. i = __encode_answer(ar[j], dest, maxlen);
  754. if (i < 0)
  755. return i;
  756. dest += i;
  757. maxlen -= i;
  758. total += i;
  759. }
  760. return total;
  761. }
  762. #endif
  763. #ifdef L_decodep
  764. int __decode_packet(unsigned char *data, struct resolv_header *h) attribute_hidden;
  765. int __decode_packet(unsigned char *data, struct resolv_header *h)
  766. {
  767. __decode_header(data, h);
  768. return HFIXEDSZ;
  769. }
  770. #endif
  771. #ifdef L_formquery
  772. int __form_query(int id,
  773. const char *name,
  774. int type,
  775. unsigned char *packet,
  776. int maxlen);
  777. int __form_query(int id,
  778. const char *name,
  779. int type,
  780. unsigned char *packet,
  781. int maxlen)
  782. {
  783. struct resolv_header h;
  784. struct resolv_question q;
  785. int i, j;
  786. memset(&h, 0, sizeof(h));
  787. h.id = id;
  788. h.qdcount = 1;
  789. q.dotted = (char *) name;
  790. q.qtype = type;
  791. q.qclass = C_IN; /* CLASS_IN */
  792. i = __encode_header(&h, packet, maxlen);
  793. if (i < 0)
  794. return i;
  795. j = __encode_question(&q, packet + i, maxlen - i);
  796. if (j < 0)
  797. return j;
  798. return i + j;
  799. }
  800. #endif
  801. #endif /* CURRENTLY_UNUSED */
  802. #ifdef L_opennameservers
  803. # if __BYTE_ORDER == __LITTLE_ENDIAN
  804. #define NAMESERVER_PORT_N (__bswap_constant_16(NAMESERVER_PORT))
  805. #else
  806. #define NAMESERVER_PORT_N NAMESERVER_PORT
  807. #endif
  808. __UCLIBC_MUTEX_INIT(__resolv_lock, PTHREAD_MUTEX_INITIALIZER);
  809. /* Protected by __resolv_lock */
  810. void (*__res_sync)(void);
  811. /*uint32_t __resolv_opts; */
  812. uint8_t __resolv_timeout = RES_TIMEOUT;
  813. uint8_t __resolv_attempts = RES_DFLRETRY;
  814. unsigned __nameservers;
  815. unsigned __searchdomains;
  816. sockaddr46_t *__nameserver;
  817. char **__searchdomain;
  818. #ifdef __UCLIBC_HAS_IPV4__
  819. const struct sockaddr_in __local_nameserver = {
  820. .sin_family = AF_INET,
  821. .sin_port = NAMESERVER_PORT_N,
  822. };
  823. #else
  824. const struct sockaddr_in6 __local_nameserver = {
  825. .sin6_family = AF_INET6,
  826. .sin6_port = NAMESERVER_PORT_N,
  827. };
  828. #endif
  829. /* Helpers. Both stop on EOL, if it's '\n', it is converted to NUL first */
  830. static char *skip_nospace(char *p)
  831. {
  832. while (*p != '\0' && !isspace(*p)) {
  833. if (*p == '\n') {
  834. *p = '\0';
  835. break;
  836. }
  837. p++;
  838. }
  839. return p;
  840. }
  841. static char *skip_and_NUL_space(char *p)
  842. {
  843. /* NB: '\n' is not isspace! */
  844. while (1) {
  845. char c = *p;
  846. if (c == '\0' || !isspace(c))
  847. break;
  848. *p = '\0';
  849. if (c == '\n' || c == '#')
  850. break;
  851. p++;
  852. }
  853. return p;
  854. }
  855. /* Must be called under __resolv_lock. */
  856. void attribute_hidden __open_nameservers(void)
  857. {
  858. static uint32_t resolv_conf_mtime;
  859. char szBuffer[MAXLEN_searchdomain];
  860. FILE *fp;
  861. int i;
  862. sockaddr46_t sa;
  863. if (!__res_sync) {
  864. /* Reread /etc/resolv.conf if it was modified. */
  865. struct stat sb;
  866. if (stat("/etc/resolv.conf", &sb) != 0)
  867. sb.st_mtime = 0;
  868. if (resolv_conf_mtime != (uint32_t)sb.st_mtime) {
  869. resolv_conf_mtime = sb.st_mtime;
  870. __close_nameservers(); /* force config reread */
  871. }
  872. }
  873. if (__nameservers)
  874. goto sync;
  875. __resolv_timeout = RES_TIMEOUT;
  876. __resolv_attempts = RES_DFLRETRY;
  877. fp = fopen("/etc/resolv.conf", "r");
  878. #ifdef FALLBACK_TO_CONFIG_RESOLVCONF
  879. if (!fp) {
  880. /* If we do not have a pre-populated /etc/resolv.conf then
  881. try to use the one from /etc/config which exists on numerous
  882. systems ranging from some uClinux to IRIX installations and
  883. may be the only /etc dir that was mounted rw. */
  884. fp = fopen("/etc/config/resolv.conf", "r");
  885. }
  886. #endif
  887. if (fp) {
  888. while (fgets(szBuffer, sizeof(szBuffer), fp) != NULL) {
  889. void *ptr;
  890. char *keyword, *p;
  891. keyword = p = skip_and_NUL_space(szBuffer);
  892. /* skip keyword */
  893. p = skip_nospace(p);
  894. /* find next word */
  895. p = skip_and_NUL_space(p);
  896. if (strcmp(keyword, "nameserver") == 0) {
  897. /* terminate IP addr */
  898. *skip_nospace(p) = '\0';
  899. memset(&sa, 0, sizeof(sa));
  900. if (0) /* nothing */;
  901. #ifdef __UCLIBC_HAS_IPV6__
  902. else if (inet_pton(AF_INET6, p, &sa.sa6.sin6_addr) > 0) {
  903. sa.sa6.sin6_family = AF_INET6;
  904. sa.sa6.sin6_port = htons(NAMESERVER_PORT);
  905. }
  906. #endif
  907. #ifdef __UCLIBC_HAS_IPV4__
  908. else if (inet_pton(AF_INET, p, &sa.sa4.sin_addr) > 0) {
  909. sa.sa4.sin_family = AF_INET;
  910. sa.sa4.sin_port = htons(NAMESERVER_PORT);
  911. }
  912. #endif
  913. else
  914. continue; /* garbage on this line */
  915. ptr = realloc(__nameserver, (__nameservers + 1) * sizeof(__nameserver[0]));
  916. if (!ptr)
  917. continue;
  918. __nameserver = ptr;
  919. __nameserver[__nameservers++] = sa; /* struct copy */
  920. continue;
  921. }
  922. if (strcmp(keyword, "domain") == 0 || strcmp(keyword, "search") == 0) {
  923. char *p1;
  924. /* free old domains ("last 'domain' or 'search' wins" rule) */
  925. while (__searchdomains)
  926. free(__searchdomain[--__searchdomains]);
  927. /*free(__searchdomain);*/
  928. /*__searchdomain = NULL; - not necessary */
  929. next_word:
  930. /* terminate current word */
  931. p1 = skip_nospace(p);
  932. /* find next word (maybe) */
  933. p1 = skip_and_NUL_space(p1);
  934. /* add it */
  935. ptr = realloc(__searchdomain, (__searchdomains + 1) * sizeof(__searchdomain[0]));
  936. if (!ptr)
  937. continue;
  938. __searchdomain = ptr;
  939. /* NB: strlen(p) <= MAXLEN_searchdomain) because szBuffer[] is smaller */
  940. ptr = strdup(p);
  941. if (!ptr)
  942. continue;
  943. DPRINTF("adding search %s\n", (char*)ptr);
  944. __searchdomain[__searchdomains++] = (char*)ptr;
  945. p = p1;
  946. if (*p)
  947. goto next_word;
  948. continue;
  949. }
  950. /* if (strcmp(keyword, "sortlist") == 0)... */
  951. if (strcmp(keyword, "options") == 0) {
  952. char *p1;
  953. uint8_t *what;
  954. if (p == NULL || (p1 = strchr(p, ':')) == NULL)
  955. continue;
  956. *p1++ = '\0';
  957. if (strcmp(p, "timeout") == 0)
  958. what = &__resolv_timeout;
  959. else if (strcmp(p, "attempts") == 0)
  960. what = &__resolv_attempts;
  961. else
  962. continue;
  963. *what = atoi(p1);
  964. DPRINTF("option %s:%d\n", p, *what);
  965. }
  966. }
  967. fclose(fp);
  968. }
  969. if (__nameservers == 0) {
  970. /* Have to handle malloc failure! What a mess...
  971. * And it's not only here, we need to be careful
  972. * to never write into __nameserver[0] if it points
  973. * to constant __local_nameserver, or free it. */
  974. __nameserver = malloc(sizeof(__nameserver[0]));
  975. if (__nameserver)
  976. memcpy(__nameserver, &__local_nameserver, sizeof(__local_nameserver));
  977. else
  978. __nameserver = (void*) &__local_nameserver;
  979. __nameservers++;
  980. }
  981. if (__searchdomains == 0) {
  982. char buf[256];
  983. char *p;
  984. i = gethostname(buf, sizeof(buf) - 1);
  985. buf[sizeof(buf) - 1] = '\0';
  986. if (i == 0 && (p = strchr(buf, '.')) != NULL && p[1]) {
  987. p = strdup(p + 1);
  988. if (!p)
  989. goto err;
  990. __searchdomain = malloc(sizeof(__searchdomain[0]));
  991. if (!__searchdomain) {
  992. free(p);
  993. goto err;
  994. }
  995. __searchdomain[0] = p;
  996. __searchdomains++;
  997. err: ;
  998. }
  999. }
  1000. DPRINTF("nameservers = %d\n", __nameservers);
  1001. sync:
  1002. if (__res_sync)
  1003. __res_sync();
  1004. }
  1005. #endif
  1006. #ifdef L_closenameservers
  1007. /* Must be called under __resolv_lock. */
  1008. void attribute_hidden __close_nameservers(void)
  1009. {
  1010. if (__nameserver != (void*) &__local_nameserver)
  1011. free(__nameserver);
  1012. __nameserver = NULL;
  1013. __nameservers = 0;
  1014. while (__searchdomains)
  1015. free(__searchdomain[--__searchdomains]);
  1016. free(__searchdomain);
  1017. __searchdomain = NULL;
  1018. /*__searchdomains = 0; - already is */
  1019. }
  1020. #endif
  1021. #ifdef L_dnslookup
  1022. /* Helpers */
  1023. static int __length_question(const unsigned char *data, int maxlen)
  1024. {
  1025. const unsigned char *start;
  1026. unsigned b;
  1027. if (!data)
  1028. return -1;
  1029. start = data;
  1030. while (1) {
  1031. if (maxlen <= 0)
  1032. return -1;
  1033. b = *data++;
  1034. if (b == 0)
  1035. break;
  1036. if ((b & 0xc0) == 0xc0) {
  1037. /* It's a "compressed" name. */
  1038. data++; /* skip lsb of redirected offset */
  1039. maxlen -= 2;
  1040. break;
  1041. }
  1042. data += b;
  1043. maxlen -= (b + 1); /* account for data++ above */
  1044. }
  1045. /* Up to here we were skipping encoded name */
  1046. /* Account for QTYPE and QCLASS fields */
  1047. if (maxlen < 4)
  1048. return -1;
  1049. return data - start + 2 + 2;
  1050. }
  1051. static int __decode_answer(const unsigned char *message, /* packet */
  1052. int offset,
  1053. int len, /* total packet len */
  1054. struct resolv_answer *a)
  1055. {
  1056. char temp[256];
  1057. int i;
  1058. DPRINTF("decode_answer(start): off %d, len %d\n", offset, len);
  1059. i = __decode_dotted(message, offset, len, temp, sizeof(temp));
  1060. if (i < 0)
  1061. return i;
  1062. message += offset + i;
  1063. len -= i + RRFIXEDSZ + offset;
  1064. if (len < 0) {
  1065. DPRINTF("decode_answer: off %d, len %d, i %d\n", offset, len, i);
  1066. return len;
  1067. }
  1068. /* TODO: what if strdup fails? */
  1069. a->dotted = strdup(temp);
  1070. a->atype = (message[0] << 8) | message[1];
  1071. message += 2;
  1072. a->aclass = (message[0] << 8) | message[1];
  1073. message += 2;
  1074. a->ttl = (message[0] << 24) |
  1075. (message[1] << 16) | (message[2] << 8) | (message[3] << 0);
  1076. message += 4;
  1077. a->rdlength = (message[0] << 8) | message[1];
  1078. message += 2;
  1079. a->rdata = message;
  1080. a->rdoffset = offset + i + RRFIXEDSZ;
  1081. DPRINTF("i=%d,rdlength=%d\n", i, a->rdlength);
  1082. if (len < a->rdlength)
  1083. return -1;
  1084. return i + RRFIXEDSZ + a->rdlength;
  1085. }
  1086. /* On entry:
  1087. * a.buf(len) = auxiliary buffer for IP addresses after first one
  1088. * a.add_count = how many additional addresses are there already
  1089. * outpacket = where to save ptr to raw packet? can be NULL
  1090. * On exit:
  1091. * ret < 0: error, all other data is not valid
  1092. * ret >= 0: length of reply packet
  1093. * a.add_count & a.buf: updated
  1094. * a.rdlength: length of addresses (4 bytes for IPv4)
  1095. * *outpacket: updated (packet is malloced, you need to free it)
  1096. * a.rdata: points into *outpacket to 1st IP addr
  1097. * NB: don't pass outpacket == NULL if you need to use a.rdata!
  1098. * a.atype: type of query?
  1099. * a.dotted: which name we _actually_ used. May contain search domains
  1100. * appended. (why the filed is called "dotted" I have no idea)
  1101. * This is a malloced string. May be NULL because strdup failed.
  1102. */
  1103. int attribute_hidden __dns_lookup(const char *name,
  1104. int type,
  1105. unsigned char **outpacket,
  1106. struct resolv_answer *a)
  1107. {
  1108. /* Protected by __resolv_lock: */
  1109. static int last_ns_num = 0;
  1110. static uint16_t last_id = 1;
  1111. int i, j, fd, rc;
  1112. int packet_len;
  1113. int name_len;
  1114. #ifdef USE_SELECT
  1115. struct timeval tv;
  1116. fd_set fds;
  1117. #else
  1118. struct pollfd fds;
  1119. #endif
  1120. struct resolv_header h;
  1121. struct resolv_question q;
  1122. struct resolv_answer ma;
  1123. bool first_answer = 1;
  1124. int retries_left;
  1125. unsigned char *packet = malloc(PACKETSZ);
  1126. char *lookup;
  1127. int variant = -1; /* search domain to append, -1: none */
  1128. int local_ns_num = -1; /* Nth server to use */
  1129. int local_id = local_id; /* for compiler */
  1130. int sdomains;
  1131. bool ends_with_dot;
  1132. sockaddr46_t sa;
  1133. fd = -1;
  1134. lookup = NULL;
  1135. name_len = strlen(name);
  1136. if ((unsigned)name_len >= MAXDNAME - MAXLEN_searchdomain - 2)
  1137. goto fail; /* paranoia */
  1138. lookup = malloc(name_len + 1/*for '.'*/ + MAXLEN_searchdomain + 1);
  1139. if (!packet || !lookup || !name[0])
  1140. goto fail;
  1141. ends_with_dot = (name[name_len - 1] == '.');
  1142. /* no strcpy! paranoia, user might change name[] under us */
  1143. memcpy(lookup, name, name_len);
  1144. DPRINTF("Looking up type %d answer for '%s'\n", type, name);
  1145. retries_left = 0; /* for compiler */
  1146. do {
  1147. int pos;
  1148. unsigned reply_timeout;
  1149. if (fd != -1) {
  1150. close(fd);
  1151. fd = -1;
  1152. }
  1153. /* Mess with globals while under lock */
  1154. /* NB: even data *pointed to* by globals may vanish
  1155. * outside the locks. We should assume any and all
  1156. * globals can completely change between locked
  1157. * code regions. OTOH, this is rare, so we don't need
  1158. * to handle it "nicely" (do not skip servers,
  1159. * search domains, etc), we only need to ensure
  1160. * we do not SEGV, use freed+overwritten data
  1161. * or do other Really Bad Things. */
  1162. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  1163. __open_nameservers();
  1164. sdomains = __searchdomains;
  1165. lookup[name_len] = '\0';
  1166. if ((unsigned)variant < sdomains) {
  1167. /* lookup is name_len + 1 + MAXLEN_searchdomain + 1 long */
  1168. /* __searchdomain[] is not bigger than MAXLEN_searchdomain */
  1169. lookup[name_len] = '.';
  1170. strcpy(&lookup[name_len + 1], __searchdomain[variant]);
  1171. }
  1172. /* first time? pick starting server etc */
  1173. if (local_ns_num < 0) {
  1174. local_id = last_id;
  1175. /*TODO: implement /etc/resolv.conf's "options rotate"
  1176. (a.k.a. RES_ROTATE bit in _res.options)
  1177. local_ns_num = 0;
  1178. if (_res.options & RES_ROTATE) */
  1179. local_ns_num = last_ns_num;
  1180. retries_left = __nameservers * __resolv_attempts;
  1181. }
  1182. retries_left--;
  1183. if (local_ns_num >= __nameservers)
  1184. local_ns_num = 0;
  1185. local_id++;
  1186. local_id &= 0xffff;
  1187. /* write new values back while still under lock */
  1188. last_id = local_id;
  1189. last_ns_num = local_ns_num;
  1190. /* struct copy */
  1191. /* can't just take a pointer, __nameserver[x]
  1192. * is not safe to use outside of locks */
  1193. sa = __nameserver[local_ns_num];
  1194. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  1195. memset(packet, 0, PACKETSZ);
  1196. memset(&h, 0, sizeof(h));
  1197. /* encode header */
  1198. h.id = local_id;
  1199. h.qdcount = 1;
  1200. h.rd = 1;
  1201. DPRINTF("encoding header\n", h.rd);
  1202. i = __encode_header(&h, packet, PACKETSZ);
  1203. if (i < 0)
  1204. goto fail;
  1205. /* encode question */
  1206. DPRINTF("lookup name: %s\n", lookup);
  1207. q.dotted = lookup;
  1208. q.qtype = type;
  1209. q.qclass = C_IN; /* CLASS_IN */
  1210. j = __encode_question(&q, packet+i, PACKETSZ-i);
  1211. if (j < 0)
  1212. goto fail;
  1213. packet_len = i + j;
  1214. /* send packet */
  1215. #ifdef DEBUG
  1216. {
  1217. const socklen_t plen = sa.sa.sa_family == AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN;
  1218. char *pbuf = malloc(plen);
  1219. if (pbuf == NULL) ;/* nothing */
  1220. #ifdef __UCLIBC_HAS_IPV6__
  1221. else if (sa.sa.sa_family == AF_INET6)
  1222. pbuf = (char*)inet_ntop(AF_INET6, &sa.sa6.sin6_addr, pbuf, plen);
  1223. #endif
  1224. #ifdef __UCLIBC_HAS_IPV4__
  1225. else if (sa.sa.sa_family == AF_INET)
  1226. pbuf = (char*)inet_ntop(AF_INET, &sa.sa4.sin_addr, pbuf, plen);
  1227. #endif
  1228. DPRINTF("On try %d, sending query to %s, port %d\n",
  1229. retries_left, pbuf, NAMESERVER_PORT);
  1230. free(pbuf);
  1231. }
  1232. #endif
  1233. fd = socket(sa.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
  1234. if (fd < 0) /* paranoia */
  1235. goto try_next_server;
  1236. rc = connect(fd, &sa.sa, sizeof(sa));
  1237. if (rc < 0) {
  1238. /*if (errno == ENETUNREACH) { */
  1239. /* routing error, presume not transient */
  1240. goto try_next_server;
  1241. /*} */
  1242. /*For example, what transient error this can be? Can't think of any */
  1243. /* retry */
  1244. /*continue; */
  1245. }
  1246. DPRINTF("Xmit packet len:%d id:%d qr:%d\n", packet_len, h.id, h.qr);
  1247. /* no error check - if it fails, we time out on recv */
  1248. send(fd, packet, packet_len, 0);
  1249. #ifdef USE_SELECT
  1250. reply_timeout = __resolv_timeout;
  1251. wait_again:
  1252. FD_ZERO(&fds);
  1253. FD_SET(fd, &fds);
  1254. tv.tv_sec = reply_timeout;
  1255. tv.tv_usec = 0;
  1256. if (select(fd + 1, &fds, NULL, NULL, &tv) <= 0) {
  1257. DPRINTF("Timeout\n");
  1258. /* timed out, so retry send and receive
  1259. * to next nameserver */
  1260. goto try_next_server;
  1261. }
  1262. reply_timeout--;
  1263. #else
  1264. reply_timeout = __resolv_timeout * 1000;
  1265. wait_again:
  1266. fds.fd = fd;
  1267. fds.events = POLLIN;
  1268. if (poll(&fds, 1, reply_timeout) <= 0) {
  1269. DPRINTF("Timeout\n");
  1270. /* timed out, so retry send and receive
  1271. * to next nameserver */
  1272. goto try_next_server;
  1273. }
  1274. /*TODO: better timeout accounting?*/
  1275. reply_timeout -= 1000;
  1276. #endif
  1277. /* vda: a bogus response seen in real world (caused SEGV in uclibc):
  1278. * "ping www.google.com" sending AAAA query and getting
  1279. * response with one answer... with answer part missing!
  1280. * Fixed by thorough checks for not going past the packet's end.
  1281. */
  1282. #ifdef DEBUG
  1283. {
  1284. static const char test_query[32] = "\0\2\1\0\0\1\0\0\0\0\0\0\3www\6google\3com\0\0\34\0\1";
  1285. static const char test_respn[32] = "\0\2\201\200\0\1\0\1\0\0\0\0\3www\6google\3com\0\0\34\0\1";
  1286. pos = memcmp(packet + 2, test_query + 2, 30);
  1287. packet_len = recv(fd, packet, PACKETSZ, MSG_DONTWAIT);
  1288. if (pos == 0) {
  1289. packet_len = 32;
  1290. memcpy(packet + 2, test_respn + 2, 30);
  1291. }
  1292. }
  1293. #else
  1294. packet_len = recv(fd, packet, PACKETSZ, MSG_DONTWAIT);
  1295. #endif
  1296. if (packet_len < HFIXEDSZ) {
  1297. /* too short!
  1298. * If the peer did shutdown then retry later,
  1299. * try next peer on error.
  1300. * it's just a bogus packet from somewhere */
  1301. bogus_packet:
  1302. if (packet_len >= 0 && reply_timeout)
  1303. goto wait_again;
  1304. goto try_next_server;
  1305. }
  1306. __decode_header(packet, &h);
  1307. DPRINTF("len:%d id:%d qr:%d\n", packet_len, h.id, h.qr);
  1308. if (h.id != local_id || !h.qr) {
  1309. /* unsolicited */
  1310. goto bogus_packet;
  1311. }
  1312. DPRINTF("Got response (i think)!\n");
  1313. DPRINTF("qrcount=%d,ancount=%d,nscount=%d,arcount=%d\n",
  1314. h.qdcount, h.ancount, h.nscount, h.arcount);
  1315. DPRINTF("opcode=%d,aa=%d,tc=%d,rd=%d,ra=%d,rcode=%d\n",
  1316. h.opcode, h.aa, h.tc, h.rd, h.ra, h.rcode);
  1317. /* bug 660 says we treat negative response as an error
  1318. * and retry, which is, eh, an error. :)
  1319. * We were incurring long delays because of this. */
  1320. if (h.rcode == NXDOMAIN) {
  1321. /* if possible, try next search domain */
  1322. if (!ends_with_dot) {
  1323. DPRINTF("variant:%d sdomains:%d\n", variant, sdomains);
  1324. if (variant < sdomains - 1) {
  1325. /* next search domain */
  1326. variant++;
  1327. continue;
  1328. }
  1329. /* no more search domains to try */
  1330. }
  1331. /* dont loop, this is "no such host" situation */
  1332. h_errno = HOST_NOT_FOUND;
  1333. goto fail1;
  1334. }
  1335. /* Insert other non-fatal errors here, which do not warrant
  1336. * switching to next nameserver */
  1337. /* Strange error, assuming this nameserver is feeling bad */
  1338. if (h.rcode != 0)
  1339. goto try_next_server;
  1340. /* Code below won't work correctly with h.ancount == 0, so... */
  1341. if (h.ancount <= 0) {
  1342. h_errno = NO_DATA; /* [is this correct code to check for?] */
  1343. goto fail1;
  1344. }
  1345. pos = HFIXEDSZ;
  1346. for (j = 0; j < h.qdcount; j++) {
  1347. DPRINTF("Skipping question %d at %d\n", j, pos);
  1348. i = __length_question(packet + pos, packet_len - pos);
  1349. if (i < 0) {
  1350. DPRINTF("Packet'question section "
  1351. "is truncated, trying next server\n");
  1352. goto try_next_server;
  1353. }
  1354. pos += i;
  1355. DPRINTF("Length of question %d is %d\n", j, i);
  1356. }
  1357. DPRINTF("Decoding answer at pos %d\n", pos);
  1358. first_answer = 1;
  1359. for (j = 0; j < h.ancount; j++) {
  1360. i = __decode_answer(packet, pos, packet_len, &ma);
  1361. if (i < 0) {
  1362. DPRINTF("failed decode %d\n", i);
  1363. /* If the message was truncated but we have
  1364. * decoded some answers, pretend it's OK */
  1365. if (j && h.tc)
  1366. break;
  1367. goto try_next_server;
  1368. }
  1369. pos += i;
  1370. if (first_answer) {
  1371. ma.buf = a->buf;
  1372. ma.buflen = a->buflen;
  1373. ma.add_count = a->add_count;
  1374. memcpy(a, &ma, sizeof(ma));
  1375. if (a->atype != T_SIG && (NULL == a->buf || (type != T_A && type != T_AAAA)))
  1376. break;
  1377. if (a->atype != type)
  1378. continue;
  1379. a->add_count = h.ancount - j - 1;
  1380. if ((a->rdlength + sizeof(struct in_addr*)) * a->add_count > a->buflen)
  1381. break;
  1382. a->add_count = 0;
  1383. first_answer = 0;
  1384. } else {
  1385. free(ma.dotted);
  1386. if (ma.atype != type)
  1387. continue;
  1388. if (a->rdlength != ma.rdlength) {
  1389. free(a->dotted);
  1390. DPRINTF("Answer address len(%u) differs from original(%u)\n",
  1391. ma.rdlength, a->rdlength);
  1392. goto try_next_server;
  1393. }
  1394. memcpy(a->buf + (a->add_count * ma.rdlength), ma.rdata, ma.rdlength);
  1395. ++a->add_count;
  1396. }
  1397. }
  1398. /* Success! */
  1399. DPRINTF("Answer name = |%s|\n", a->dotted);
  1400. DPRINTF("Answer type = |%d|\n", a->atype);
  1401. if (fd != -1)
  1402. close(fd);
  1403. if (outpacket)
  1404. *outpacket = packet;
  1405. else
  1406. free(packet);
  1407. free(lookup);
  1408. return packet_len;
  1409. try_next_server:
  1410. /* Try next nameserver */
  1411. local_ns_num++;
  1412. variant = -1;
  1413. } while (retries_left > 0);
  1414. fail:
  1415. h_errno = NETDB_INTERNAL;
  1416. fail1:
  1417. if (fd != -1)
  1418. close(fd);
  1419. free(lookup);
  1420. free(packet);
  1421. return -1;
  1422. }
  1423. #endif
  1424. #ifdef L_read_etc_hosts_r
  1425. parser_t * __open_etc_hosts(void)
  1426. {
  1427. parser_t * parser;
  1428. if ((parser = config_open("/etc/hosts")) == NULL) {
  1429. #ifdef FALLBACK_TO_CONFIG_RESOLVCONF
  1430. parser = config_open("/etc/config/hosts");
  1431. #endif
  1432. }
  1433. return parser;
  1434. }
  1435. int attribute_hidden __read_etc_hosts_r(
  1436. parser_t * parser,
  1437. const char *name,
  1438. int type,
  1439. enum etc_hosts_action action,
  1440. struct hostent *result_buf,
  1441. char *buf, size_t buflen,
  1442. struct hostent **result,
  1443. int *h_errnop)
  1444. {
  1445. char **alias;
  1446. char **host_aliases;
  1447. char **tok = NULL;
  1448. struct in_addr *h_addr0 = NULL;
  1449. #define ALIASOFF (sizeof(*host_aliases) * MAXALIASES + 2 * sizeof(char*))
  1450. const size_t aliaslen = ALIASOFF +
  1451. #ifdef __UCLIBC_HAS_IPV6__
  1452. sizeof(struct in6_addr)
  1453. #else
  1454. sizeof(struct in_addr)
  1455. #endif
  1456. ;
  1457. int ret = HOST_NOT_FOUND;
  1458. *h_errnop = NETDB_INTERNAL;
  1459. if (buflen < aliaslen
  1460. || (buflen - aliaslen) < BUFSZ + 1)
  1461. return ERANGE;
  1462. if (parser == NULL)
  1463. parser = __open_etc_hosts();
  1464. if (parser == NULL) {
  1465. *result = NULL;
  1466. return errno;
  1467. }
  1468. /* Layout in buf:
  1469. * char **alias for MAXALIAS aliases
  1470. * char **h_addr_list[1] = {*in[6]_addr, NULL}
  1471. * struct in[6]_addr
  1472. * char line_buffer[BUFSZ+];
  1473. */
  1474. parser->data = buf;
  1475. parser->data_len = aliaslen;
  1476. parser->line_len = buflen - aliaslen;
  1477. *h_errnop = HOST_NOT_FOUND;
  1478. /* <ip>[[:space:]][<aliases>] */
  1479. while (config_read(parser, &tok, MAXALIASES, 2, "# \t", PARSE_NORMAL)) {
  1480. result_buf->h_aliases = alias = host_aliases = tok+1;
  1481. if (action == GETHOSTENT) {
  1482. /* Return whatever the next entry happens to be. */
  1483. break;
  1484. }
  1485. if (action == GET_HOSTS_BYADDR) {
  1486. if (strcmp(name, *tok) != 0)
  1487. continue;
  1488. } else { /* GET_HOSTS_BYNAME */
  1489. while (*alias) {
  1490. if (strcasecmp(name, *(alias++)) == 0)
  1491. goto found;
  1492. }
  1493. continue;
  1494. }
  1495. found:
  1496. result_buf->h_name = *(result_buf->h_aliases++);
  1497. result_buf->h_addr_list = (char**)(buf + ALIASOFF);
  1498. *(result_buf->h_addr_list + 1) = '\0';
  1499. h_addr0 = (struct in_addr*)(buf + ALIASOFF + 2 * sizeof (char*));
  1500. result_buf->h_addr = (char*)h_addr0;
  1501. if (0) /* nothing */;
  1502. #ifdef __UCLIBC_HAS_IPV4__
  1503. else if (type == AF_INET
  1504. && inet_pton(AF_INET, *tok, h_addr0) > 0) {
  1505. DPRINTF("Found INET\n");
  1506. result_buf->h_addrtype = AF_INET;
  1507. result_buf->h_length = sizeof(struct in_addr);
  1508. *result = result_buf;
  1509. ret = NETDB_SUCCESS;
  1510. }
  1511. #endif
  1512. #ifdef __UCLIBC_HAS_IPV6__
  1513. #define in6 ((struct in6_addr *)buf)
  1514. else if (type == AF_INET6
  1515. && inet_pton(AF_INET6, *tok, h_addr0) > 0) {
  1516. DPRINTF("Found INET6\n");
  1517. result_buf->h_addrtype = AF_INET6;
  1518. result_buf->h_length = sizeof(struct in6_addr);
  1519. *result = result_buf;
  1520. ret = NETDB_SUCCESS;
  1521. }
  1522. #endif
  1523. else {
  1524. /* continue parsing in the hope the user has multiple
  1525. * host types listed in the database like so:
  1526. * <ipv4 addr> host
  1527. * <ipv6 addr> host
  1528. * If looking for an IPv6 addr, don't bail when we got the IPv4
  1529. */
  1530. DPRINTF("Error: Found host but different address family\n");
  1531. /* NB: gethostbyname2_r depends on this feature
  1532. * to avoid looking for IPv6 addr of "localhost" etc */
  1533. ret = TRY_AGAIN;
  1534. continue;
  1535. }
  1536. break;
  1537. }
  1538. if (action != GETHOSTENT)
  1539. config_close(parser);
  1540. return ret;
  1541. #undef in6
  1542. }
  1543. #endif
  1544. #ifdef L_get_hosts_byname_r
  1545. int attribute_hidden __get_hosts_byname_r(const char *name,
  1546. int type,
  1547. struct hostent *result_buf,
  1548. char *buf,
  1549. size_t buflen,
  1550. struct hostent **result,
  1551. int *h_errnop)
  1552. {
  1553. return __read_etc_hosts_r(NULL, name, type, GET_HOSTS_BYNAME,
  1554. result_buf, buf, buflen, result, h_errnop);
  1555. }
  1556. #endif
  1557. #ifdef L_get_hosts_byaddr_r
  1558. int attribute_hidden __get_hosts_byaddr_r(const char *addr,
  1559. int len,
  1560. int type,
  1561. struct hostent *result_buf,
  1562. char *buf,
  1563. size_t buflen,
  1564. struct hostent **result,
  1565. int *h_errnop)
  1566. {
  1567. #ifndef __UCLIBC_HAS_IPV6__
  1568. char ipaddr[INET_ADDRSTRLEN];
  1569. #else
  1570. char ipaddr[INET6_ADDRSTRLEN];
  1571. #endif
  1572. switch (type) {
  1573. #ifdef __UCLIBC_HAS_IPV4__
  1574. case AF_INET:
  1575. if (len != sizeof(struct in_addr))
  1576. return 0;
  1577. break;
  1578. #endif
  1579. #ifdef __UCLIBC_HAS_IPV6__
  1580. case AF_INET6:
  1581. if (len != sizeof(struct in6_addr))
  1582. return 0;
  1583. break;
  1584. #endif
  1585. default:
  1586. return 0;
  1587. }
  1588. inet_ntop(type, addr, ipaddr, sizeof(ipaddr));
  1589. return __read_etc_hosts_r(NULL, ipaddr, type, GET_HOSTS_BYADDR,
  1590. result_buf, buf, buflen, result, h_errnop);
  1591. }
  1592. #endif
  1593. #ifdef L_getnameinfo
  1594. int getnameinfo(const struct sockaddr *sa,
  1595. socklen_t addrlen,
  1596. char *host,
  1597. socklen_t hostlen,
  1598. char *serv,
  1599. socklen_t servlen,
  1600. unsigned flags)
  1601. {
  1602. int serrno = errno;
  1603. unsigned ok;
  1604. struct hostent *hoste = NULL;
  1605. char domain[256];
  1606. if (flags & ~(NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|NI_DGRAM))
  1607. return EAI_BADFLAGS;
  1608. if (sa == NULL || addrlen < sizeof(sa_family_t))
  1609. return EAI_FAMILY;
  1610. ok = sa->sa_family;
  1611. if (ok == AF_LOCAL) /* valid */;
  1612. #ifdef __UCLIBC_HAS_IPV4__
  1613. else if (ok == AF_INET) {
  1614. if (addrlen < sizeof(struct sockaddr_in))
  1615. return EAI_FAMILY;
  1616. }
  1617. #endif
  1618. #ifdef __UCLIBC_HAS_IPV6__
  1619. else if (ok == AF_INET6) {
  1620. if (addrlen < sizeof(struct sockaddr_in6))
  1621. return EAI_FAMILY;
  1622. }
  1623. #endif
  1624. else
  1625. return EAI_FAMILY;
  1626. ok = 0;
  1627. if (host != NULL && hostlen > 0)
  1628. switch (sa->sa_family) {
  1629. case AF_INET:
  1630. #ifdef __UCLIBC_HAS_IPV6__
  1631. case AF_INET6:
  1632. #endif
  1633. if (!(flags & NI_NUMERICHOST)) {
  1634. if (0) /* nothing */;
  1635. #ifdef __UCLIBC_HAS_IPV6__
  1636. else if (sa->sa_family == AF_INET6)
  1637. hoste = gethostbyaddr((const void *)
  1638. &(((const struct sockaddr_in6 *) sa)->sin6_addr),
  1639. sizeof(struct in6_addr), AF_INET6);
  1640. #endif
  1641. #ifdef __UCLIBC_HAS_IPV4__
  1642. else
  1643. hoste = gethostbyaddr((const void *)
  1644. &(((const struct sockaddr_in *)sa)->sin_addr),
  1645. sizeof(struct in_addr), AF_INET);
  1646. #endif
  1647. if (hoste) {
  1648. char *c;
  1649. #undef min
  1650. #define min(x,y) (((x) > (y)) ? (y) : (x))
  1651. if ((flags & NI_NOFQDN)
  1652. && (getdomainname(domain, sizeof(domain)) == 0)
  1653. && (c = strstr(hoste->h_name, domain)) != NULL
  1654. && (c != hoste->h_name) && (*(--c) == '.')
  1655. ) {
  1656. strncpy(host, hoste->h_name,
  1657. min(hostlen, (size_t) (c - hoste->h_name)));
  1658. host[min(hostlen - 1, (size_t) (c - hoste->h_name))] = '\0';
  1659. } else {
  1660. strncpy(host, hoste->h_name, hostlen);
  1661. }
  1662. ok = 1;
  1663. #undef min
  1664. }
  1665. }
  1666. if (!ok) {
  1667. const char *c = NULL;
  1668. if (flags & NI_NAMEREQD) {
  1669. errno = serrno;
  1670. return EAI_NONAME;
  1671. }
  1672. if (0) /* nothing */;
  1673. #ifdef __UCLIBC_HAS_IPV6__
  1674. else if (sa->sa_family == AF_INET6) {
  1675. const struct sockaddr_in6 *sin6p;
  1676. sin6p = (const struct sockaddr_in6 *) sa;
  1677. c = inet_ntop(AF_INET6,
  1678. (const void *) &sin6p->sin6_addr,
  1679. host, hostlen);
  1680. #if 0
  1681. /* Does scope id need to be supported? */
  1682. uint32_t scopeid;
  1683. scopeid = sin6p->sin6_scope_id;
  1684. if (scopeid != 0) {
  1685. /* Buffer is >= IFNAMSIZ+1. */
  1686. char scopebuf[IFNAMSIZ + 1];
  1687. char *scopeptr;
  1688. int ni_numericscope = 0;
  1689. size_t real_hostlen = strnlen(host, hostlen);
  1690. size_t scopelen = 0;
  1691. scopebuf[0] = SCOPE_DELIMITER;
  1692. scopebuf[1] = '\0';
  1693. scopeptr = &scopebuf[1];
  1694. if (IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr)
  1695. || IN6_IS_ADDR_MC_LINKLOCAL(&sin6p->sin6_addr)) {
  1696. if (if_indextoname(scopeid, scopeptr) == NULL)
  1697. ++ni_numericscope;
  1698. else
  1699. scopelen = strlen(scopebuf);
  1700. } else {
  1701. ++ni_numericscope;
  1702. }
  1703. if (ni_numericscope)
  1704. scopelen = 1 + snprintf(scopeptr,
  1705. (scopebuf
  1706. + sizeof scopebuf
  1707. - scopeptr),
  1708. "%u", scopeid);
  1709. if (real_hostlen + scopelen + 1 > hostlen)
  1710. return EAI_SYSTEM;
  1711. memcpy(host + real_hostlen, scopebuf, scopelen + 1);
  1712. }
  1713. #endif
  1714. }
  1715. #endif /* __UCLIBC_HAS_IPV6__ */
  1716. #if defined __UCLIBC_HAS_IPV4__
  1717. else {
  1718. c = inet_ntop(AF_INET, (const void *)
  1719. &(((const struct sockaddr_in *) sa)->sin_addr),
  1720. host, hostlen);
  1721. }
  1722. #endif
  1723. if (c == NULL) {
  1724. errno = serrno;
  1725. return EAI_SYSTEM;
  1726. }
  1727. ok = 1;
  1728. }
  1729. break;
  1730. case AF_LOCAL:
  1731. if (!(flags & NI_NUMERICHOST)) {
  1732. struct utsname utsname;
  1733. if (!uname(&utsname)) {
  1734. strncpy(host, utsname.nodename, hostlen);
  1735. break;
  1736. };
  1737. };
  1738. if (flags & NI_NAMEREQD) {
  1739. errno = serrno;
  1740. return EAI_NONAME;
  1741. }
  1742. strncpy(host, "localhost", hostlen);
  1743. break;
  1744. /* Already checked above
  1745. default:
  1746. return EAI_FAMILY;
  1747. */
  1748. }
  1749. if (serv && (servlen > 0)) {
  1750. if (sa->sa_family == AF_LOCAL) {
  1751. strncpy(serv, ((const struct sockaddr_un *) sa)->sun_path, servlen);
  1752. } else { /* AF_INET || AF_INET6 */
  1753. if (!(flags & NI_NUMERICSERV)) {
  1754. struct servent *s;
  1755. s = getservbyport(((const struct sockaddr_in *) sa)->sin_port,
  1756. ((flags & NI_DGRAM) ? "udp" : "tcp"));
  1757. if (s) {
  1758. strncpy(serv, s->s_name, servlen);
  1759. goto DONE;
  1760. }
  1761. }
  1762. snprintf(serv, servlen, "%d",
  1763. ntohs(((const struct sockaddr_in *) sa)->sin_port));
  1764. }
  1765. }
  1766. DONE:
  1767. if (host && (hostlen > 0))
  1768. host[hostlen-1] = 0;
  1769. if (serv && (servlen > 0))
  1770. serv[servlen-1] = 0;
  1771. errno = serrno;
  1772. return 0;
  1773. }
  1774. libc_hidden_def(getnameinfo)
  1775. #endif
  1776. #ifdef L_gethostbyname_r
  1777. /* Bug 671 says:
  1778. * "uClibc resolver's gethostbyname does not return the requested name
  1779. * as an alias, but instead returns the canonical name. glibc's
  1780. * gethostbyname has a similar bug where it returns the requested name
  1781. * with the search domain name appended (to make a FQDN) as an alias,
  1782. * but not the original name itself. Both contradict POSIX, which says
  1783. * that the name argument passed to gethostbyname must be in the alias list"
  1784. * This is fixed now, and we differ from glibc:
  1785. *
  1786. * $ ./gethostbyname_uclibc wer.google.com
  1787. * h_name:'c13-ss-2-lb.cnet.com'
  1788. * h_length:4
  1789. * h_addrtype:2 AF_INET
  1790. * alias:'wer.google.com' <===
  1791. * addr: 0x4174efd8 '216.239.116.65'
  1792. *
  1793. * $ ./gethostbyname_glibc wer.google.com
  1794. * h_name:'c13-ss-2-lb.cnet.com'
  1795. * h_length:4
  1796. * h_addrtype:2 AF_INET
  1797. * alias:'wer.google.com.com' <===
  1798. * addr:'216.239.116.65'
  1799. *
  1800. * When examples were run, /etc/resolv.conf contained "search com" line.
  1801. */
  1802. int gethostbyname_r(const char *name,
  1803. struct hostent *result_buf,
  1804. char *buf,
  1805. size_t buflen,
  1806. struct hostent **result,
  1807. int *h_errnop)
  1808. {
  1809. struct in_addr **addr_list;
  1810. char **alias;
  1811. char *alias0;
  1812. unsigned char *packet;
  1813. struct resolv_answer a;
  1814. int i;
  1815. int packet_len;
  1816. int wrong_af = 0;
  1817. *result = NULL;
  1818. if (!name)
  1819. return EINVAL;
  1820. /* do /etc/hosts first */
  1821. {
  1822. int old_errno = errno; /* save the old errno and reset errno */
  1823. __set_errno(0); /* to check for missing /etc/hosts. */
  1824. i = __get_hosts_byname_r(name, AF_INET, result_buf,
  1825. buf, buflen, result, h_errnop);
  1826. if (i == NETDB_SUCCESS) {
  1827. __set_errno(old_errno);
  1828. return i;
  1829. }
  1830. switch (*h_errnop) {
  1831. case HOST_NOT_FOUND:
  1832. wrong_af = (i == TRY_AGAIN);
  1833. case NO_ADDRESS:
  1834. break;
  1835. case NETDB_INTERNAL:
  1836. if (errno == ENOENT) {
  1837. break;
  1838. }
  1839. /* else fall through */
  1840. default:
  1841. return i;
  1842. }
  1843. __set_errno(old_errno);
  1844. }
  1845. DPRINTF("Nothing found in /etc/hosts\n");
  1846. *h_errnop = NETDB_INTERNAL;
  1847. /* prepare future h_aliases[0] */
  1848. i = strlen(name) + 1;
  1849. if ((ssize_t)buflen <= i)
  1850. return ERANGE;
  1851. memcpy(buf, name, i); /* paranoia: name might change */
  1852. alias0 = buf;
  1853. buf += i;
  1854. buflen -= i;
  1855. /* make sure pointer is aligned */
  1856. i = ALIGN_BUFFER_OFFSET(buf);
  1857. buf += i;
  1858. buflen -= i;
  1859. /* Layout in buf:
  1860. * char *alias[2];
  1861. * struct in_addr* addr_list[NN+1];
  1862. * struct in_addr* in[NN];
  1863. */
  1864. alias = (char **)buf;
  1865. buf += sizeof(alias[0]) * 2;
  1866. buflen -= sizeof(alias[0]) * 2;
  1867. addr_list = (struct in_addr **)buf;
  1868. /* buflen may be < 0, must do signed compare */
  1869. if ((ssize_t)buflen < 256)
  1870. return ERANGE;
  1871. /* we store only one "alias" - the name itself */
  1872. #ifdef __UCLIBC_MJN3_ONLY__
  1873. #warning TODO -- generate the full list
  1874. #endif
  1875. alias[0] = alias0;
  1876. alias[1] = NULL;
  1877. /* maybe it is already an address? */
  1878. {
  1879. struct in_addr *in = (struct in_addr *)(buf + sizeof(addr_list[0]) * 2);
  1880. if (inet_aton(name, in)) {
  1881. addr_list[0] = in;
  1882. addr_list[1] = NULL;
  1883. result_buf->h_name = alias0;
  1884. result_buf->h_aliases = alias;
  1885. result_buf->h_addrtype = AF_INET;
  1886. result_buf->h_length = sizeof(struct in_addr);
  1887. result_buf->h_addr_list = (char **) addr_list;
  1888. *result = result_buf;
  1889. *h_errnop = NETDB_SUCCESS;
  1890. return NETDB_SUCCESS;
  1891. }
  1892. }
  1893. /* what if /etc/hosts has it but it's not IPv4?
  1894. * F.e. "::1 localhost6". We don't do DNS query for such hosts -
  1895. * "ping localhost6" should be fast even if DNS server is down! */
  1896. if (wrong_af) {
  1897. *h_errnop = HOST_NOT_FOUND;
  1898. return TRY_AGAIN;
  1899. }
  1900. /* talk to DNS servers */
  1901. a.buf = buf;
  1902. /* take into account that at least one address will be there,
  1903. * we'll need space of one in_addr + two addr_list[] elems */
  1904. a.buflen = buflen - ((sizeof(addr_list[0]) * 2 + sizeof(struct in_addr)));
  1905. a.add_count = 0;
  1906. packet_len = __dns_lookup(name, T_A, &packet, &a);
  1907. if (packet_len < 0) {
  1908. *h_errnop = HOST_NOT_FOUND;
  1909. DPRINTF("__dns_lookup returned < 0\n");
  1910. return TRY_AGAIN;
  1911. }
  1912. if (a.atype == T_A) { /* ADDRESS */
  1913. /* we need space for addr_list[] and one IPv4 address */
  1914. /* + 1 accounting for 1st addr (it's in a.rdata),
  1915. * another + 1 for NULL in last addr_list[]: */
  1916. int need_bytes = sizeof(addr_list[0]) * (a.add_count + 1 + 1)
  1917. /* for 1st addr (it's in a.rdata): */
  1918. + sizeof(struct in_addr);
  1919. /* how many bytes will 2nd and following addresses take? */
  1920. int ips_len = a.add_count * a.rdlength;
  1921. buflen -= (need_bytes + ips_len);
  1922. if ((ssize_t)buflen < 0) {
  1923. DPRINTF("buffer too small for all addresses\n");
  1924. /* *h_errnop = NETDB_INTERNAL; - already is */
  1925. i = ERANGE;
  1926. goto free_and_ret;
  1927. }
  1928. /* if there are additional addresses in buf,
  1929. * move them forward so that they are not destroyed */
  1930. DPRINTF("a.add_count:%d a.rdlength:%d a.rdata:%p\n", a.add_count, a.rdlength, a.rdata);
  1931. memmove(buf + need_bytes, buf, ips_len);
  1932. /* 1st address is in a.rdata, insert it */
  1933. buf += need_bytes - sizeof(struct in_addr);
  1934. memcpy(buf, a.rdata, sizeof(struct in_addr));
  1935. /* fill addr_list[] */
  1936. for (i = 0; i <= a.add_count; i++) {
  1937. addr_list[i] = (struct in_addr*)buf;
  1938. buf += sizeof(struct in_addr);
  1939. }
  1940. addr_list[i] = NULL;
  1941. /* if we have enough space, we can report "better" name
  1942. * (it may contain search domains attached by __dns_lookup,
  1943. * or CNAME of the host if it is different from the name
  1944. * we used to find it) */
  1945. if (a.dotted && buflen > strlen(a.dotted)) {
  1946. strcpy(buf, a.dotted);
  1947. alias0 = buf;
  1948. }
  1949. result_buf->h_name = alias0;
  1950. result_buf->h_aliases = alias;
  1951. result_buf->h_addrtype = AF_INET;
  1952. result_buf->h_length = sizeof(struct in_addr);
  1953. result_buf->h_addr_list = (char **) addr_list;
  1954. *result = result_buf;
  1955. *h_errnop = NETDB_SUCCESS;
  1956. i = NETDB_SUCCESS;
  1957. goto free_and_ret;
  1958. }
  1959. *h_errnop = HOST_NOT_FOUND;
  1960. i = TRY_AGAIN;
  1961. free_and_ret:
  1962. free(a.dotted);
  1963. free(packet);
  1964. return i;
  1965. }
  1966. libc_hidden_def(gethostbyname_r)
  1967. link_warning(gethostbyname_r, "gethostbyname_r is obsolescent, use getnameinfo() instead.");
  1968. #endif
  1969. #ifdef L_gethostbyname2_r
  1970. int gethostbyname2_r(const char *name,
  1971. int family,
  1972. struct hostent *result_buf,
  1973. char *buf,
  1974. size_t buflen,
  1975. struct hostent **result,
  1976. int *h_errnop)
  1977. {
  1978. #ifndef __UCLIBC_HAS_IPV6__
  1979. return family == (AF_INET)
  1980. ? gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop)
  1981. : HOST_NOT_FOUND;
  1982. #else
  1983. struct in6_addr *in;
  1984. struct in6_addr **addr_list;
  1985. unsigned char *packet;
  1986. struct resolv_answer a;
  1987. int i;
  1988. int nest = 0;
  1989. int wrong_af = 0;
  1990. if (family == AF_INET)
  1991. return gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop);
  1992. *result = NULL;
  1993. if (family != AF_INET6)
  1994. return EINVAL;
  1995. if (!name)
  1996. return EINVAL;
  1997. /* do /etc/hosts first */
  1998. {
  1999. int old_errno = errno; /* Save the old errno and reset errno */
  2000. __set_errno(0); /* to check for missing /etc/hosts. */
  2001. i = __get_hosts_byname_r(name, AF_INET6 /*family*/, result_buf,
  2002. buf, buflen, result, h_errnop);
  2003. if (i == NETDB_SUCCESS) {
  2004. __set_errno(old_errno);
  2005. return i;
  2006. }
  2007. switch (*h_errnop) {
  2008. case HOST_NOT_FOUND:
  2009. wrong_af = (i == TRY_AGAIN);
  2010. case NO_ADDRESS:
  2011. break;
  2012. case NETDB_INTERNAL:
  2013. if (errno == ENOENT) {
  2014. break;
  2015. }
  2016. /* else fall through */
  2017. default:
  2018. return i;
  2019. }
  2020. __set_errno(old_errno);
  2021. }
  2022. DPRINTF("Nothing found in /etc/hosts\n");
  2023. *h_errnop = NETDB_INTERNAL;
  2024. /* make sure pointer is aligned */
  2025. i = ALIGN_BUFFER_OFFSET(buf);
  2026. buf += i;
  2027. buflen -= i;
  2028. /* Layout in buf:
  2029. * struct in6_addr* in;
  2030. * struct in6_addr* addr_list[2];
  2031. * char scratch_buf[256];
  2032. */
  2033. in = (struct in6_addr*)buf;
  2034. buf += sizeof(*in);
  2035. buflen -= sizeof(*in);
  2036. addr_list = (struct in6_addr**)buf;
  2037. buf += sizeof(*addr_list) * 2;
  2038. buflen -= sizeof(*addr_list) * 2;
  2039. if ((ssize_t)buflen < 256)
  2040. return ERANGE;
  2041. addr_list[0] = in;
  2042. addr_list[1] = NULL;
  2043. strncpy(buf, name, buflen);
  2044. buf[buflen] = '\0';
  2045. /* maybe it is already an address? */
  2046. if (inet_pton(AF_INET6, name, in)) {
  2047. result_buf->h_name = buf;
  2048. result_buf->h_addrtype = AF_INET6;
  2049. result_buf->h_length = sizeof(*in);
  2050. result_buf->h_addr_list = (char **) addr_list;
  2051. /* result_buf->h_aliases = ??? */
  2052. *result = result_buf;
  2053. *h_errnop = NETDB_SUCCESS;
  2054. return NETDB_SUCCESS;
  2055. }
  2056. /* what if /etc/hosts has it but it's not IPv6?
  2057. * F.e. "127.0.0.1 localhost". We don't do DNS query for such hosts -
  2058. * "ping localhost" should be fast even if DNS server is down! */
  2059. if (wrong_af) {
  2060. *h_errnop = HOST_NOT_FOUND;
  2061. return TRY_AGAIN;
  2062. }
  2063. /* talk to DNS servers */
  2064. /* TODO: why it's so different from gethostbyname_r (IPv4 case)? */
  2065. memset(&a, '\0', sizeof(a));
  2066. for (;;) {
  2067. int packet_len;
  2068. /* Hmm why we memset(a) to zeros only once? */
  2069. packet_len = __dns_lookup(buf, T_AAAA, &packet, &a);
  2070. if (packet_len < 0) {
  2071. *h_errnop = HOST_NOT_FOUND;
  2072. return TRY_AGAIN;
  2073. }
  2074. strncpy(buf, a.dotted, buflen);
  2075. free(a.dotted);
  2076. if (a.atype != T_CNAME)
  2077. break;
  2078. DPRINTF("Got a CNAME in gethostbyname()\n");
  2079. if (++nest > MAX_RECURSE) {
  2080. *h_errnop = NO_RECOVERY;
  2081. return -1;
  2082. }
  2083. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2084. free(packet);
  2085. if (i < 0) {
  2086. *h_errnop = NO_RECOVERY;
  2087. return -1;
  2088. }
  2089. }
  2090. if (a.atype == T_AAAA) { /* ADDRESS */
  2091. memcpy(in, a.rdata, sizeof(*in));
  2092. result_buf->h_name = buf;
  2093. result_buf->h_addrtype = AF_INET6;
  2094. result_buf->h_length = sizeof(*in);
  2095. result_buf->h_addr_list = (char **) addr_list;
  2096. /* result_buf->h_aliases = ??? */
  2097. free(packet);
  2098. *result = result_buf;
  2099. *h_errnop = NETDB_SUCCESS;
  2100. return NETDB_SUCCESS;
  2101. }
  2102. free(packet);
  2103. *h_errnop = HOST_NOT_FOUND;
  2104. return TRY_AGAIN;
  2105. #endif /* __UCLIBC_HAS_IPV6__ */
  2106. }
  2107. libc_hidden_def(gethostbyname2_r)
  2108. #endif
  2109. #ifdef L_gethostbyaddr_r
  2110. int gethostbyaddr_r(const void *addr, socklen_t addrlen,
  2111. int type,
  2112. struct hostent *result_buf,
  2113. char *buf, size_t buflen,
  2114. struct hostent **result,
  2115. int *h_errnop)
  2116. {
  2117. struct in_addr *in;
  2118. struct in_addr **addr_list;
  2119. char **alias;
  2120. unsigned char *packet;
  2121. struct resolv_answer a;
  2122. int i;
  2123. int packet_len;
  2124. int nest = 0;
  2125. *result = NULL;
  2126. if (!addr)
  2127. return EINVAL;
  2128. switch (type) {
  2129. #ifdef __UCLIBC_HAS_IPV4__
  2130. case AF_INET:
  2131. if (addrlen != sizeof(struct in_addr))
  2132. return EINVAL;
  2133. break;
  2134. #endif
  2135. #ifdef __UCLIBC_HAS_IPV6__
  2136. case AF_INET6:
  2137. if (addrlen != sizeof(struct in6_addr))
  2138. return EINVAL;
  2139. break;
  2140. #endif
  2141. default:
  2142. return EINVAL;
  2143. }
  2144. /* do /etc/hosts first */
  2145. i = __get_hosts_byaddr_r(addr, addrlen, type, result_buf,
  2146. buf, buflen, result, h_errnop);
  2147. if (i == 0)
  2148. return i;
  2149. switch (*h_errnop) {
  2150. case HOST_NOT_FOUND:
  2151. case NO_ADDRESS:
  2152. break;
  2153. default:
  2154. return i;
  2155. }
  2156. *h_errnop = NETDB_INTERNAL;
  2157. /* make sure pointer is aligned */
  2158. i = ALIGN_BUFFER_OFFSET(buf);
  2159. buf += i;
  2160. buflen -= i;
  2161. /* Layout in buf:
  2162. * char *alias[ALIAS_DIM];
  2163. * struct in[6]_addr* addr_list[2];
  2164. * struct in[6]_addr in;
  2165. * char scratch_buffer[256+];
  2166. */
  2167. #define in6 ((struct in6_addr *)in)
  2168. alias = (char **)buf;
  2169. addr_list = (struct in_addr**)buf;
  2170. buf += sizeof(*addr_list) * 2;
  2171. buflen -= sizeof(*addr_list) * 2;
  2172. in = (struct in_addr*)buf;
  2173. #ifndef __UCLIBC_HAS_IPV6__
  2174. buf += sizeof(*in);
  2175. buflen -= sizeof(*in);
  2176. if (addrlen > sizeof(*in))
  2177. return ERANGE;
  2178. #else
  2179. buf += sizeof(*in6);
  2180. buflen -= sizeof(*in6);
  2181. if (addrlen > sizeof(*in6))
  2182. return ERANGE;
  2183. #endif
  2184. if ((ssize_t)buflen < 256)
  2185. return ERANGE;
  2186. alias[0] = buf;
  2187. alias[1] = NULL;
  2188. addr_list[0] = in;
  2189. addr_list[1] = NULL;
  2190. memcpy(in, addr, addrlen);
  2191. if (0) /* nothing */;
  2192. #ifdef __UCLIBC_HAS_IPV4__
  2193. else IF_HAS_BOTH(if (type == AF_INET)) {
  2194. unsigned char *tp = (unsigned char *)addr;
  2195. sprintf(buf, "%u.%u.%u.%u.in-addr.arpa",
  2196. tp[3], tp[2], tp[1], tp[0]);
  2197. }
  2198. #endif
  2199. #ifdef __UCLIBC_HAS_IPV6__
  2200. else {
  2201. char *dst = buf;
  2202. unsigned char *tp = (unsigned char *)addr + addrlen - 1;
  2203. do {
  2204. dst += sprintf(dst, "%x.%x.", tp[0] & 0xf, tp[0] >> 4);
  2205. tp--;
  2206. } while (tp >= (unsigned char *)addr);
  2207. strcpy(dst, "ip6.arpa");
  2208. }
  2209. #endif
  2210. memset(&a, '\0', sizeof(a));
  2211. for (;;) {
  2212. /* Hmm why we memset(a) to zeros only once? */
  2213. packet_len = __dns_lookup(buf, T_PTR, &packet, &a);
  2214. if (packet_len < 0) {
  2215. *h_errnop = HOST_NOT_FOUND;
  2216. return TRY_AGAIN;
  2217. }
  2218. strncpy(buf, a.dotted, buflen);
  2219. free(a.dotted);
  2220. if (a.atype != T_CNAME)
  2221. break;
  2222. DPRINTF("Got a CNAME in gethostbyaddr()\n");
  2223. if (++nest > MAX_RECURSE) {
  2224. *h_errnop = NO_RECOVERY;
  2225. return -1;
  2226. }
  2227. /* Decode CNAME into buf, feed it to __dns_lookup() again */
  2228. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2229. free(packet);
  2230. if (i < 0) {
  2231. *h_errnop = NO_RECOVERY;
  2232. return -1;
  2233. }
  2234. }
  2235. if (a.atype == T_PTR) { /* ADDRESS */
  2236. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2237. free(packet);
  2238. result_buf->h_name = buf;
  2239. result_buf->h_addrtype = type;
  2240. result_buf->h_length = addrlen;
  2241. result_buf->h_addr_list = (char **) addr_list;
  2242. result_buf->h_aliases = alias;
  2243. *result = result_buf;
  2244. *h_errnop = NETDB_SUCCESS;
  2245. return NETDB_SUCCESS;
  2246. }
  2247. free(packet);
  2248. *h_errnop = NO_ADDRESS;
  2249. return TRY_AGAIN;
  2250. #undef in6
  2251. }
  2252. libc_hidden_def(gethostbyaddr_r)
  2253. link_warning(gethostbyaddr_r, "gethostbyaddr_r is obsolescent, use getaddrinfo() instead.");
  2254. #endif
  2255. #ifdef L_gethostent_r
  2256. __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
  2257. static parser_t *hostp = NULL;
  2258. static smallint host_stayopen;
  2259. void endhostent_unlocked(void)
  2260. {
  2261. if (hostp) {
  2262. config_close(hostp);
  2263. hostp = NULL;
  2264. }
  2265. host_stayopen = 0;
  2266. }
  2267. void endhostent(void)
  2268. {
  2269. __UCLIBC_MUTEX_LOCK(mylock);
  2270. endhostent_unlocked();
  2271. __UCLIBC_MUTEX_UNLOCK(mylock);
  2272. }
  2273. void sethostent(int stay_open)
  2274. {
  2275. __UCLIBC_MUTEX_LOCK(mylock);
  2276. if (stay_open)
  2277. host_stayopen = 1;
  2278. __UCLIBC_MUTEX_UNLOCK(mylock);
  2279. }
  2280. int gethostent_r(struct hostent *result_buf, char *buf, size_t buflen,
  2281. struct hostent **result, int *h_errnop)
  2282. {
  2283. int ret;
  2284. __UCLIBC_MUTEX_LOCK(mylock);
  2285. if (hostp == NULL) {
  2286. hostp = __open_etc_hosts();
  2287. if (hostp == NULL) {
  2288. *result = NULL;
  2289. ret = TRY_AGAIN;
  2290. goto DONE;
  2291. }
  2292. }
  2293. ret = __read_etc_hosts_r(hostp, NULL, AF_INET, GETHOSTENT,
  2294. result_buf, buf, buflen, result, h_errnop);
  2295. if (!host_stayopen)
  2296. endhostent_unlocked();
  2297. DONE:
  2298. __UCLIBC_MUTEX_UNLOCK(mylock);
  2299. return ret;
  2300. }
  2301. libc_hidden_def(gethostent_r)
  2302. #endif
  2303. #ifdef L_gethostent
  2304. struct hostent *gethostent(void)
  2305. {
  2306. static struct hostent hoste;
  2307. static char buf[
  2308. #ifndef __UCLIBC_HAS_IPV6__
  2309. sizeof(struct in_addr) + sizeof(struct in_addr *) * 2 +
  2310. #else
  2311. sizeof(struct in6_addr) + sizeof(struct in6_addr *) * 2 +
  2312. #endif /* __UCLIBC_HAS_IPV6__ */
  2313. BUFSZ /*namebuffer*/ + 2 /* margin */];
  2314. struct hostent *host;
  2315. gethostent_r(&hoste, buf, sizeof(buf), &host, &h_errno);
  2316. return host;
  2317. }
  2318. #endif
  2319. #ifdef L_gethostbyname2
  2320. struct hostent *gethostbyname2(const char *name, int family)
  2321. {
  2322. #ifndef __UCLIBC_HAS_IPV6__
  2323. return family == AF_INET ? gethostbyname(name) : (struct hostent*)NULL;
  2324. #else
  2325. static struct hostent hoste;
  2326. static char buf[sizeof(struct in6_addr) +
  2327. sizeof(struct in6_addr *) * 2 +
  2328. /*sizeof(char *)*ALIAS_DIM +*/ 384/*namebuffer*/ + 32/* margin */];
  2329. struct hostent *hp;
  2330. gethostbyname2_r(name, family, &hoste, buf, sizeof(buf), &hp, &h_errno);
  2331. return hp;
  2332. #endif
  2333. }
  2334. libc_hidden_def(gethostbyname2)
  2335. #endif
  2336. #ifdef L_gethostbyname
  2337. struct hostent *gethostbyname(const char *name)
  2338. {
  2339. #ifndef __UCLIBC_HAS_IPV6__
  2340. static struct hostent hoste;
  2341. static char buf[sizeof(struct in_addr) +
  2342. sizeof(struct in_addr *) * 2 +
  2343. /*sizeof(char *)*ALIAS_DIM +*/ 384/*namebuffer*/ + 32/* margin */];
  2344. struct hostent *hp;
  2345. gethostbyname_r(name, &hoste, buf, sizeof(buf), &hp, &h_errno);
  2346. return hp;
  2347. #else
  2348. return gethostbyname2(name, AF_INET);
  2349. #endif
  2350. }
  2351. libc_hidden_def(gethostbyname)
  2352. link_warning(gethostbyname, "gethostbyname is obsolescent, use getnameinfo() instead.");
  2353. #endif
  2354. #ifdef L_gethostbyaddr
  2355. struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type)
  2356. {
  2357. static struct hostent hoste;
  2358. static char buf[
  2359. #ifndef __UCLIBC_HAS_IPV6__
  2360. sizeof(struct in_addr) + sizeof(struct in_addr *)*2 +
  2361. #else
  2362. sizeof(struct in6_addr) + sizeof(struct in6_addr *)*2 +
  2363. #endif /* __UCLIBC_HAS_IPV6__ */
  2364. /*sizeof(char *)*ALIAS_DIM +*/ 384 /*namebuffer*/ + 32 /* margin */];
  2365. struct hostent *hp;
  2366. gethostbyaddr_r(addr, len, type, &hoste, buf, sizeof(buf), &hp, &h_errno);
  2367. return hp;
  2368. }
  2369. libc_hidden_def(gethostbyaddr)
  2370. link_warning(gethostbyaddr, "gethostbyaddr is obsolescent, use getaddrinfo() instead.");
  2371. #endif
  2372. #ifdef L_res_comp
  2373. /*
  2374. * Expand compressed domain name 'comp_dn' to full domain name.
  2375. * 'msg' is a pointer to the begining of the message,
  2376. * 'eomorig' points to the first location after the message,
  2377. * 'exp_dn' is a pointer to a buffer of size 'length' for the result.
  2378. * Return size of compressed name or -1 if there was an error.
  2379. */
  2380. int dn_expand(const u_char *msg, const u_char *eom, const u_char *src,
  2381. char *dst, int dstsiz)
  2382. {
  2383. int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz);
  2384. if (n > 0 && dst[0] == '.')
  2385. dst[0] = '\0';
  2386. return n;
  2387. }
  2388. #endif /* L_res_comp */
  2389. #ifdef L_ns_name
  2390. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2391. * is this character visible and not a space when printed ?
  2392. */
  2393. static int printable(int ch)
  2394. {
  2395. return (ch > 0x20 && ch < 0x7f);
  2396. }
  2397. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2398. * is this characted special ("in need of quoting") ?
  2399. */
  2400. static int special(int ch)
  2401. {
  2402. switch (ch) {
  2403. case 0x22: /* '"' */
  2404. case 0x2E: /* '.' */
  2405. case 0x3B: /* ';' */
  2406. case 0x5C: /* '\\' */
  2407. /* Special modifiers in zone files. */
  2408. case 0x40: /* '@' */
  2409. case 0x24: /* '$' */
  2410. return 1;
  2411. default:
  2412. return 0;
  2413. }
  2414. }
  2415. /*
  2416. * ns_name_uncompress(msg, eom, src, dst, dstsiz)
  2417. * Expand compressed domain name to presentation format.
  2418. * return:
  2419. * Number of bytes read out of `src', or -1 (with errno set).
  2420. * note:
  2421. * Root domain returns as "." not "".
  2422. */
  2423. int ns_name_uncompress(const u_char *msg, const u_char *eom,
  2424. const u_char *src, char *dst, size_t dstsiz)
  2425. {
  2426. u_char tmp[NS_MAXCDNAME];
  2427. int n;
  2428. n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp);
  2429. if (n == -1)
  2430. return -1;
  2431. if (ns_name_ntop(tmp, dst, dstsiz) == -1)
  2432. return -1;
  2433. return n;
  2434. }
  2435. libc_hidden_def(ns_name_uncompress)
  2436. /*
  2437. * ns_name_ntop(src, dst, dstsiz)
  2438. * Convert an encoded domain name to printable ascii as per RFC1035.
  2439. * return:
  2440. * Number of bytes written to buffer, or -1 (with errno set)
  2441. * notes:
  2442. * The root is returned as "."
  2443. * All other domains are returned in non absolute form
  2444. */
  2445. int ns_name_ntop(const u_char *src, char *dst, size_t dstsiz)
  2446. {
  2447. static const char digits[] = "0123456789";
  2448. const u_char *cp;
  2449. char *dn, *eom;
  2450. u_char c;
  2451. u_int n;
  2452. cp = src;
  2453. dn = dst;
  2454. eom = dst + dstsiz;
  2455. while ((n = *cp++) != 0) {
  2456. if ((n & NS_CMPRSFLGS) != 0) {
  2457. /* Some kind of compression pointer. */
  2458. __set_errno(EMSGSIZE);
  2459. return -1;
  2460. }
  2461. if (dn != dst) {
  2462. if (dn >= eom) {
  2463. __set_errno(EMSGSIZE);
  2464. return -1;
  2465. }
  2466. *dn++ = '.';
  2467. }
  2468. if (dn + n >= eom) {
  2469. __set_errno(EMSGSIZE);
  2470. return -1;
  2471. }
  2472. for (; n > 0; n--) {
  2473. c = *cp++;
  2474. if (special(c)) {
  2475. if (dn + 1 >= eom) {
  2476. __set_errno(EMSGSIZE);
  2477. return -1;
  2478. }
  2479. *dn++ = '\\';
  2480. *dn++ = (char)c;
  2481. } else if (!printable(c)) {
  2482. if (dn + 3 >= eom) {
  2483. __set_errno(EMSGSIZE);
  2484. return -1;
  2485. }
  2486. *dn++ = '\\';
  2487. *dn++ = digits[c / 100];
  2488. *dn++ = digits[(c % 100) / 10];
  2489. *dn++ = digits[c % 10];
  2490. } else {
  2491. if (dn >= eom) {
  2492. __set_errno(EMSGSIZE);
  2493. return -1;
  2494. }
  2495. *dn++ = (char)c;
  2496. }
  2497. }
  2498. }
  2499. if (dn == dst) {
  2500. if (dn >= eom) {
  2501. __set_errno(EMSGSIZE);
  2502. return -1;
  2503. }
  2504. *dn++ = '.';
  2505. }
  2506. if (dn >= eom) {
  2507. __set_errno(EMSGSIZE);
  2508. return -1;
  2509. }
  2510. *dn++ = '\0';
  2511. return (dn - dst);
  2512. }
  2513. libc_hidden_def(ns_name_ntop)
  2514. /*
  2515. * ns_name_unpack(msg, eom, src, dst, dstsiz)
  2516. * Unpack a domain name from a message, source may be compressed.
  2517. * return:
  2518. * -1 if it fails, or consumed octets if it succeeds.
  2519. */
  2520. int ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
  2521. u_char *dst, size_t dstsiz)
  2522. {
  2523. const u_char *srcp, *dstlim;
  2524. u_char *dstp;
  2525. int n, len, checked;
  2526. len = -1;
  2527. checked = 0;
  2528. dstp = dst;
  2529. srcp = src;
  2530. dstlim = dst + dstsiz;
  2531. if (srcp < msg || srcp >= eom) {
  2532. __set_errno(EMSGSIZE);
  2533. return -1;
  2534. }
  2535. /* Fetch next label in domain name. */
  2536. while ((n = *srcp++) != 0) {
  2537. /* Check for indirection. */
  2538. switch (n & NS_CMPRSFLGS) {
  2539. case 0:
  2540. /* Limit checks. */
  2541. if (dstp + n + 1 >= dstlim || srcp + n >= eom) {
  2542. __set_errno(EMSGSIZE);
  2543. return -1;
  2544. }
  2545. checked += n + 1;
  2546. *dstp++ = n;
  2547. memcpy(dstp, srcp, n);
  2548. dstp += n;
  2549. srcp += n;
  2550. break;
  2551. case NS_CMPRSFLGS:
  2552. if (srcp >= eom) {
  2553. __set_errno(EMSGSIZE);
  2554. return -1;
  2555. }
  2556. if (len < 0)
  2557. len = srcp - src + 1;
  2558. srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
  2559. if (srcp < msg || srcp >= eom) { /* Out of range. */
  2560. __set_errno(EMSGSIZE);
  2561. return -1;
  2562. }
  2563. checked += 2;
  2564. /*
  2565. * Check for loops in the compressed name;
  2566. * if we've looked at the whole message,
  2567. * there must be a loop.
  2568. */
  2569. if (checked >= eom - msg) {
  2570. __set_errno(EMSGSIZE);
  2571. return -1;
  2572. }
  2573. break;
  2574. default:
  2575. __set_errno(EMSGSIZE);
  2576. return -1; /* flag error */
  2577. }
  2578. }
  2579. *dstp = '\0';
  2580. if (len < 0)
  2581. len = srcp - src;
  2582. return len;
  2583. }
  2584. libc_hidden_def(ns_name_unpack)
  2585. #endif /* L_ns_name */
  2586. #ifdef L_res_init
  2587. /* Will be called under __resolv_lock. */
  2588. static void res_sync_func(void)
  2589. {
  2590. struct __res_state *rp = &(_res);
  2591. int n;
  2592. /* If we didn't get malloc failure earlier... */
  2593. if (__nameserver != (void*) &__local_nameserver) {
  2594. /* TODO:
  2595. * if (__nameservers < rp->nscount) - try to grow __nameserver[]?
  2596. */
  2597. #ifdef __UCLIBC_HAS_IPV6__
  2598. if (__nameservers > rp->_u._ext.nscount)
  2599. __nameservers = rp->_u._ext.nscount;
  2600. n = __nameservers;
  2601. while (--n >= 0)
  2602. __nameserver[n].sa6 = *rp->_u._ext.nsaddrs[n]; /* struct copy */
  2603. #else /* IPv4 only */
  2604. if (__nameservers > rp->nscount)
  2605. __nameservers = rp->nscount;
  2606. n = __nameservers;
  2607. while (--n >= 0)
  2608. __nameserver[n].sa4 = rp->nsaddr_list[n]; /* struct copy */
  2609. #endif
  2610. }
  2611. __resolv_timeout = rp->retrans ? : RES_TIMEOUT;
  2612. __resolv_attempts = rp->retry ? : RES_DFLRETRY;
  2613. /* Extend and comment what program is known
  2614. * to use which _res.XXX member(s).
  2615. __resolv_opts = rp->options;
  2616. ...
  2617. */
  2618. }
  2619. /* Our res_init never fails (always returns 0) */
  2620. int res_init(void)
  2621. {
  2622. struct __res_state *rp = &(_res);
  2623. int i;
  2624. int n;
  2625. #ifdef __UCLIBC_HAS_IPV6__
  2626. int m = 0;
  2627. #endif
  2628. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2629. __close_nameservers();
  2630. __open_nameservers();
  2631. __res_sync = res_sync_func;
  2632. memset(rp, 0, sizeof(*rp));
  2633. rp->options = RES_INIT;
  2634. rp->retrans = RES_TIMEOUT;
  2635. rp->retry = RES_DFLRETRY;
  2636. rp->ndots = 1;
  2637. #ifdef __UCLIBC_HAS_COMPAT_RES_STATE__
  2638. /* Was: "rp->id = random();" but:
  2639. * - random() pulls in largish static buffers
  2640. * - isn't actually random unless, say, srandom(time(NULL)) was called
  2641. * - is not used by uclibc anyway :)
  2642. */
  2643. /* rp->id = 0; - memset did it */
  2644. #endif
  2645. #ifdef __UCLIBC_HAS_EXTRA_COMPAT_RES_STATE__
  2646. rp->_vcsock = -1;
  2647. #endif
  2648. n = __searchdomains;
  2649. if (n > ARRAY_SIZE(rp->dnsrch))
  2650. n = ARRAY_SIZE(rp->dnsrch);
  2651. for (i = 0; i < n; i++)
  2652. rp->dnsrch[i] = __searchdomain[i];
  2653. /* copy nameservers' addresses */
  2654. i = 0;
  2655. #ifdef __UCLIBC_HAS_IPV4__
  2656. n = 0;
  2657. while (n < ARRAY_SIZE(rp->nsaddr_list) && i < __nameservers) {
  2658. if (__nameserver[i].sa.sa_family == AF_INET) {
  2659. rp->nsaddr_list[n] = __nameserver[i].sa4; /* struct copy */
  2660. #ifdef __UCLIBC_HAS_IPV6__
  2661. if (m < ARRAY_SIZE(rp->_u._ext.nsaddrs)) {
  2662. rp->_u._ext.nsaddrs[m] = (void*) &rp->nsaddr_list[n];
  2663. m++;
  2664. }
  2665. #endif
  2666. n++;
  2667. }
  2668. #ifdef __UCLIBC_HAS_IPV6__
  2669. if (__nameserver[i].sa.sa_family == AF_INET6
  2670. && m < ARRAY_SIZE(rp->_u._ext.nsaddrs)
  2671. ) {
  2672. struct sockaddr_in6 *sa6 = malloc(sizeof(sa6));
  2673. if (sa6) {
  2674. *sa6 = __nameserver[i].sa6; /* struct copy */
  2675. rp->_u._ext.nsaddrs[m] = sa6;
  2676. m++;
  2677. }
  2678. }
  2679. #endif
  2680. i++;
  2681. }
  2682. rp->nscount = n;
  2683. #ifdef __UCLIBC_HAS_IPV6__
  2684. rp->_u._ext.nscount = m;
  2685. #endif
  2686. #else /* IPv6 only */
  2687. while (m < ARRAY_SIZE(rp->_u._ext.nsaddrs) && i < __nameservers) {
  2688. struct sockaddr_in6 *sa6 = malloc(sizeof(sa6));
  2689. if (sa6) {
  2690. *sa6 = __nameserver[i].sa6; /* struct copy */
  2691. rp->_u._ext.nsaddrs[m] = sa6;
  2692. m++;
  2693. }
  2694. i++;
  2695. }
  2696. rp->_u._ext.nscount = m;
  2697. #endif
  2698. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2699. return 0;
  2700. }
  2701. libc_hidden_def(res_init)
  2702. #ifdef __UCLIBC_HAS_BSD_RES_CLOSE__
  2703. void res_close(void)
  2704. {
  2705. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2706. __close_nameservers();
  2707. __res_sync = NULL;
  2708. #ifdef __UCLIBC_HAS_IPV6__
  2709. {
  2710. char *p1 = (char*) &(_res.nsaddr_list[0]);
  2711. int m = 0;
  2712. /* free nsaddrs[m] if they do not point to nsaddr_list[x] */
  2713. while (m < ARRAY_SIZE(_res._u._ext.nsaddrs)) {
  2714. char *p2 = (char*)(_res._u._ext.nsaddrs[m]);
  2715. if (p2 < p1 || (p2 - p1) > sizeof(_res.nsaddr_list))
  2716. free(p2);
  2717. }
  2718. }
  2719. #endif
  2720. memset(&_res, 0, sizeof(_res));
  2721. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2722. }
  2723. #endif
  2724. /* This needs to be after the use of _res in res_init, above. */
  2725. #undef _res
  2726. #ifndef __UCLIBC_HAS_THREADS__
  2727. /* The resolver state for use by single-threaded programs.
  2728. This differs from plain `struct __res_state _res;' in that it doesn't
  2729. create a common definition, but a plain symbol that resides in .bss,
  2730. which can have an alias. */
  2731. struct __res_state _res __attribute__((section (".bss")));
  2732. struct __res_state *__resp = &_res;
  2733. #else /* __UCLIBC_HAS_THREADS__ */
  2734. struct __res_state _res __attribute__((section (".bss"))) attribute_hidden;
  2735. # if defined __UCLIBC_HAS_TLS__
  2736. # undef __resp
  2737. __thread struct __res_state *__resp = &_res;
  2738. /*
  2739. * FIXME: Add usage of hidden attribute for this when used in the shared
  2740. * library. It currently crashes the linker when doing section
  2741. * relocations.
  2742. */
  2743. extern __thread struct __res_state *__libc_resp
  2744. __attribute__ ((alias ("__resp"))) attribute_hidden;
  2745. # else
  2746. # undef __resp
  2747. struct __res_state *__resp = &_res;
  2748. # endif
  2749. #endif
  2750. #endif /* L_res_init */
  2751. #ifdef L_res_state
  2752. # if defined __UCLIBC_HAS_TLS__
  2753. struct __res_state *
  2754. __res_state (void)
  2755. {
  2756. return __resp;
  2757. }
  2758. # else
  2759. # undef _res
  2760. extern struct __res_state _res;
  2761. /* When threaded, _res may be a per-thread variable. */
  2762. struct __res_state *
  2763. weak_const_function
  2764. __res_state (void)
  2765. {
  2766. return &_res;
  2767. }
  2768. # endif
  2769. #endif
  2770. #ifdef L_res_query
  2771. int res_query(const char *dname, int class, int type,
  2772. unsigned char *answer, int anslen)
  2773. {
  2774. int i;
  2775. unsigned char *packet = NULL;
  2776. struct resolv_answer a;
  2777. if (!dname || class != 1 /* CLASS_IN */) {
  2778. h_errno = NO_RECOVERY;
  2779. return -1;
  2780. }
  2781. memset(&a, '\0', sizeof(a));
  2782. i = __dns_lookup(dname, type, &packet, &a);
  2783. if (i < 0) {
  2784. if (!h_errno) /* TODO: can this ever happen? */
  2785. h_errno = TRY_AGAIN;
  2786. return -1;
  2787. }
  2788. free(a.dotted);
  2789. if (a.atype == type) { /* CNAME */
  2790. if (i > anslen)
  2791. i = anslen;
  2792. memcpy(answer, packet, i);
  2793. }
  2794. free(packet);
  2795. return i;
  2796. }
  2797. libc_hidden_def(res_query)
  2798. /*
  2799. * Formulate a normal query, send, and retrieve answer in supplied buffer.
  2800. * Return the size of the response on success, -1 on error.
  2801. * If enabled, implement search rules until answer or unrecoverable failure
  2802. * is detected. Error code, if any, is left in h_errno.
  2803. */
  2804. #define __TRAILING_DOT (1<<0)
  2805. #define __GOT_NODATA (1<<1)
  2806. #define __GOT_SERVFAIL (1<<2)
  2807. #define __TRIED_AS_IS (1<<3)
  2808. int res_search(const char *name, int class, int type, u_char *answer,
  2809. int anslen)
  2810. {
  2811. const char *cp;
  2812. char **domain;
  2813. HEADER *hp = (HEADER *)(void *)answer;
  2814. unsigned dots;
  2815. unsigned state;
  2816. int ret, saved_herrno;
  2817. uint32_t _res_options;
  2818. unsigned _res_ndots;
  2819. char **_res_dnsrch;
  2820. if (!name || !answer) {
  2821. h_errno = NETDB_INTERNAL;
  2822. return -1;
  2823. }
  2824. again:
  2825. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2826. _res_options = _res.options;
  2827. _res_ndots = _res.ndots;
  2828. _res_dnsrch = _res.dnsrch;
  2829. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2830. if (!(_res_options & RES_INIT)) {
  2831. res_init(); /* our res_init never fails */
  2832. goto again;
  2833. }
  2834. state = 0;
  2835. errno = 0;
  2836. h_errno = HOST_NOT_FOUND; /* default, if we never query */
  2837. dots = 0;
  2838. for (cp = name; *cp; cp++)
  2839. dots += (*cp == '.');
  2840. if (cp > name && *--cp == '.')
  2841. state |= __TRAILING_DOT;
  2842. /*
  2843. * If there are dots in the name already, let's just give it a try
  2844. * 'as is'. The threshold can be set with the "ndots" option.
  2845. */
  2846. saved_herrno = -1;
  2847. if (dots >= _res_ndots) {
  2848. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  2849. if (ret > 0)
  2850. return ret;
  2851. saved_herrno = h_errno;
  2852. state |= __TRIED_AS_IS;
  2853. }
  2854. /*
  2855. * We do at least one level of search if
  2856. * - there is no dot and RES_DEFNAME is set, or
  2857. * - there is at least one dot, there is no trailing dot,
  2858. * and RES_DNSRCH is set.
  2859. */
  2860. if ((!dots && (_res_options & RES_DEFNAMES))
  2861. || (dots && !(state & __TRAILING_DOT) && (_res_options & RES_DNSRCH))
  2862. ) {
  2863. bool done = 0;
  2864. for (domain = _res_dnsrch; *domain && !done; domain++) {
  2865. ret = res_querydomain(name, *domain, class, type,
  2866. answer, anslen);
  2867. if (ret > 0)
  2868. return ret;
  2869. /*
  2870. * If no server present, give up.
  2871. * If name isn't found in this domain,
  2872. * keep trying higher domains in the search list
  2873. * (if that's enabled).
  2874. * On a NO_DATA error, keep trying, otherwise
  2875. * a wildcard entry of another type could keep us
  2876. * from finding this entry higher in the domain.
  2877. * If we get some other error (negative answer or
  2878. * server failure), then stop searching up,
  2879. * but try the input name below in case it's
  2880. * fully-qualified.
  2881. */
  2882. if (errno == ECONNREFUSED) {
  2883. h_errno = TRY_AGAIN;
  2884. return -1;
  2885. }
  2886. switch (h_errno) {
  2887. case NO_DATA:
  2888. state |= __GOT_NODATA;
  2889. /* FALLTHROUGH */
  2890. case HOST_NOT_FOUND:
  2891. /* keep trying */
  2892. break;
  2893. case TRY_AGAIN:
  2894. if (hp->rcode == SERVFAIL) {
  2895. /* try next search element, if any */
  2896. state |= __GOT_SERVFAIL;
  2897. break;
  2898. }
  2899. /* FALLTHROUGH */
  2900. default:
  2901. /* anything else implies that we're done */
  2902. done = 1;
  2903. }
  2904. /*
  2905. * if we got here for some reason other than DNSRCH,
  2906. * we only wanted one iteration of the loop, so stop.
  2907. */
  2908. if (!(_res_options & RES_DNSRCH))
  2909. done = 1;
  2910. }
  2911. }
  2912. /*
  2913. * if we have not already tried the name "as is", do that now.
  2914. * note that we do this regardless of how many dots were in the
  2915. * name or whether it ends with a dot.
  2916. */
  2917. if (!(state & __TRIED_AS_IS)) {
  2918. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  2919. if (ret > 0)
  2920. return ret;
  2921. }
  2922. /*
  2923. * if we got here, we didn't satisfy the search.
  2924. * if we did an initial full query, return that query's h_errno
  2925. * (note that we wouldn't be here if that query had succeeded).
  2926. * else if we ever got a nodata, send that back as the reason.
  2927. * else send back meaningless h_errno, that being the one from
  2928. * the last DNSRCH we did.
  2929. */
  2930. if (saved_herrno != -1)
  2931. h_errno = saved_herrno;
  2932. else if (state & __GOT_NODATA)
  2933. h_errno = NO_DATA;
  2934. else if (state & __GOT_SERVFAIL)
  2935. h_errno = TRY_AGAIN;
  2936. return -1;
  2937. }
  2938. #undef __TRAILING_DOT
  2939. #undef __GOT_NODATA
  2940. #undef __GOT_SERVFAIL
  2941. #undef __TRIED_AS_IS
  2942. /*
  2943. * Perform a call on res_query on the concatenation of name and domain,
  2944. * removing a trailing dot from name if domain is NULL.
  2945. */
  2946. int res_querydomain(const char *name, const char *domain, int class, int type,
  2947. u_char *answer, int anslen)
  2948. {
  2949. char nbuf[MAXDNAME];
  2950. const char *longname = nbuf;
  2951. size_t n, d;
  2952. #ifdef DEBUG
  2953. uint32_t _res_options;
  2954. #endif
  2955. if (!name || !answer) {
  2956. h_errno = NETDB_INTERNAL;
  2957. return -1;
  2958. }
  2959. #ifdef DEBUG
  2960. again:
  2961. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2962. _res_options = _res.options;
  2963. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2964. if (!(_res_options & RES_INIT)) {
  2965. res_init(); /* our res_init never fails */
  2966. goto again;
  2967. }
  2968. if (_res_options & RES_DEBUG)
  2969. printf(";; res_querydomain(%s, %s, %d, %d)\n",
  2970. name, (domain ? domain : "<Nil>"), class, type);
  2971. #endif
  2972. if (domain == NULL) {
  2973. /*
  2974. * Check for trailing '.';
  2975. * copy without '.' if present.
  2976. */
  2977. n = strlen(name);
  2978. if (n + 1 > sizeof(nbuf)) {
  2979. h_errno = NO_RECOVERY;
  2980. return -1;
  2981. }
  2982. if (n > 0 && name[--n] == '.') {
  2983. strncpy(nbuf, name, n);
  2984. nbuf[n] = '\0';
  2985. } else
  2986. longname = name;
  2987. } else {
  2988. n = strlen(name);
  2989. d = strlen(domain);
  2990. if (n + 1 + d + 1 > sizeof(nbuf)) {
  2991. h_errno = NO_RECOVERY;
  2992. return -1;
  2993. }
  2994. snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
  2995. }
  2996. return res_query(longname, class, type, answer, anslen);
  2997. }
  2998. libc_hidden_def(res_querydomain)
  2999. #endif
  3000. /* Unimplemented: */
  3001. /* res_mkquery */
  3002. /* res_send */
  3003. /* dn_comp */