resolv.c 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358
  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 (4)
  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 /* L_encodeh */
  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 /* L_decodeh */
  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 /* L_encoded */
  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 /* L_decoded */
  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 /* L_encodeq */
  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 /* L_encodea */
  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 /* L_encodep */
  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 /* L_decodep */
  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 /* L_formquery */
  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 /* L_opennameservers */
  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 /* L_closenameservers */
  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 /* !USE_SELECT */
  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 /* USE_SELECT */
  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 || h.rcode == SERVFAIL) {
  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 /* L_dnslookup */
  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. #define MINTOKENS 2 //dotted ip address + canonical name
  1436. #define MAXTOKENS (MINTOKENS + MAXALIASES)
  1437. #define HALISTOFF (sizeof(char*) * MAXTOKENS)
  1438. #define INADDROFF (HALISTOFF + 2 * sizeof(char*))
  1439. int attribute_hidden __read_etc_hosts_r(
  1440. parser_t * parser,
  1441. const char *name,
  1442. int type,
  1443. enum etc_hosts_action action,
  1444. struct hostent *result_buf,
  1445. char *buf, size_t buflen,
  1446. struct hostent **result,
  1447. int *h_errnop)
  1448. {
  1449. char **alias;
  1450. char **host_aliases;
  1451. char **tok = NULL;
  1452. struct in_addr *h_addr0 = NULL;
  1453. const size_t aliaslen = INADDROFF +
  1454. #ifdef __UCLIBC_HAS_IPV6__
  1455. sizeof(struct in6_addr)
  1456. #else
  1457. sizeof(struct in_addr)
  1458. #endif
  1459. ;
  1460. int ret = HOST_NOT_FOUND;
  1461. *h_errnop = NETDB_INTERNAL;
  1462. if (buflen < aliaslen
  1463. || (buflen - aliaslen) < BUFSZ + 1)
  1464. return ERANGE;
  1465. if (parser == NULL)
  1466. parser = __open_etc_hosts();
  1467. if (parser == NULL) {
  1468. *result = NULL;
  1469. return errno;
  1470. }
  1471. /* Layout in buf:
  1472. * char *alias[MAXTOKENS] = {address, name, aliases...}
  1473. * char **h_addr_list[1] = {*in[6]_addr, NULL}
  1474. * struct in[6]_addr
  1475. * char line_buffer[BUFSZ+];
  1476. */
  1477. parser->data = buf;
  1478. parser->data_len = aliaslen;
  1479. parser->line_len = buflen - aliaslen;
  1480. *h_errnop = HOST_NOT_FOUND;
  1481. /* <ip>[[:space:]][<aliases>] */
  1482. while (config_read(parser, &tok, MAXTOKENS, MINTOKENS, "# \t", PARSE_NORMAL)) {
  1483. result_buf->h_aliases = alias = host_aliases = tok+1;
  1484. if (action == GETHOSTENT) {
  1485. /* Return whatever the next entry happens to be. */
  1486. break;
  1487. }
  1488. if (action == GET_HOSTS_BYADDR) {
  1489. if (strcmp(name, *tok) != 0)
  1490. continue;
  1491. } else { /* GET_HOSTS_BYNAME */
  1492. while (*alias) {
  1493. if (strcasecmp(name, *(alias++)) == 0)
  1494. goto found;
  1495. }
  1496. continue;
  1497. }
  1498. found:
  1499. result_buf->h_name = *(result_buf->h_aliases++);
  1500. result_buf->h_addr_list = (char**)(buf + HALISTOFF);
  1501. *(result_buf->h_addr_list + 1) = '\0';
  1502. h_addr0 = (struct in_addr*)(buf + INADDROFF);
  1503. result_buf->h_addr = (char*)h_addr0;
  1504. if (0) /* nothing */;
  1505. #ifdef __UCLIBC_HAS_IPV4__
  1506. else if (type == AF_INET
  1507. && inet_pton(AF_INET, *tok, h_addr0) > 0) {
  1508. DPRINTF("Found INET\n");
  1509. result_buf->h_addrtype = AF_INET;
  1510. result_buf->h_length = sizeof(struct in_addr);
  1511. *result = result_buf;
  1512. ret = NETDB_SUCCESS;
  1513. }
  1514. #endif
  1515. #ifdef __UCLIBC_HAS_IPV6__
  1516. #define in6 ((struct in6_addr *)buf)
  1517. else if (type == AF_INET6
  1518. && inet_pton(AF_INET6, *tok, h_addr0) > 0) {
  1519. DPRINTF("Found INET6\n");
  1520. result_buf->h_addrtype = AF_INET6;
  1521. result_buf->h_length = sizeof(struct in6_addr);
  1522. *result = result_buf;
  1523. ret = NETDB_SUCCESS;
  1524. }
  1525. #endif
  1526. else {
  1527. /* continue parsing in the hope the user has multiple
  1528. * host types listed in the database like so:
  1529. * <ipv4 addr> host
  1530. * <ipv6 addr> host
  1531. * If looking for an IPv6 addr, don't bail when we got the IPv4
  1532. */
  1533. DPRINTF("Error: Found host but different address family\n");
  1534. /* NB: gethostbyname2_r depends on this feature
  1535. * to avoid looking for IPv6 addr of "localhost" etc */
  1536. ret = TRY_AGAIN;
  1537. continue;
  1538. }
  1539. break;
  1540. }
  1541. if (action != GETHOSTENT)
  1542. config_close(parser);
  1543. return ret;
  1544. #undef in6
  1545. }
  1546. #endif /* L_read_etc_hosts_r */
  1547. #ifdef L_get_hosts_byname_r
  1548. int attribute_hidden __get_hosts_byname_r(const char *name,
  1549. int type,
  1550. struct hostent *result_buf,
  1551. char *buf,
  1552. size_t buflen,
  1553. struct hostent **result,
  1554. int *h_errnop)
  1555. {
  1556. return __read_etc_hosts_r(NULL, name, type, GET_HOSTS_BYNAME,
  1557. result_buf, buf, buflen, result, h_errnop);
  1558. }
  1559. #endif /* L_get_hosts_byname_r */
  1560. #ifdef L_get_hosts_byaddr_r
  1561. int attribute_hidden __get_hosts_byaddr_r(const char *addr,
  1562. int len,
  1563. int type,
  1564. struct hostent *result_buf,
  1565. char *buf,
  1566. size_t buflen,
  1567. struct hostent **result,
  1568. int *h_errnop)
  1569. {
  1570. #ifndef __UCLIBC_HAS_IPV6__
  1571. char ipaddr[INET_ADDRSTRLEN];
  1572. #else
  1573. char ipaddr[INET6_ADDRSTRLEN];
  1574. #endif
  1575. switch (type) {
  1576. #ifdef __UCLIBC_HAS_IPV4__
  1577. case AF_INET:
  1578. if (len != sizeof(struct in_addr))
  1579. return 0;
  1580. break;
  1581. #endif
  1582. #ifdef __UCLIBC_HAS_IPV6__
  1583. case AF_INET6:
  1584. if (len != sizeof(struct in6_addr))
  1585. return 0;
  1586. break;
  1587. #endif
  1588. default:
  1589. return 0;
  1590. }
  1591. inet_ntop(type, addr, ipaddr, sizeof(ipaddr));
  1592. return __read_etc_hosts_r(NULL, ipaddr, type, GET_HOSTS_BYADDR,
  1593. result_buf, buf, buflen, result, h_errnop);
  1594. }
  1595. #endif /* L_get_hosts_byaddr_r */
  1596. #ifdef L_getnameinfo
  1597. int getnameinfo(const struct sockaddr *sa,
  1598. socklen_t addrlen,
  1599. char *host,
  1600. socklen_t hostlen,
  1601. char *serv,
  1602. socklen_t servlen,
  1603. unsigned flags)
  1604. {
  1605. int serrno = errno;
  1606. unsigned ok;
  1607. struct hostent *hoste = NULL;
  1608. char domain[256];
  1609. if (flags & ~(NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|NI_DGRAM))
  1610. return EAI_BADFLAGS;
  1611. if (sa == NULL || addrlen < sizeof(sa_family_t))
  1612. return EAI_FAMILY;
  1613. ok = sa->sa_family;
  1614. if (ok == AF_LOCAL) /* valid */;
  1615. #ifdef __UCLIBC_HAS_IPV4__
  1616. else if (ok == AF_INET) {
  1617. if (addrlen < sizeof(struct sockaddr_in))
  1618. return EAI_FAMILY;
  1619. }
  1620. #endif
  1621. #ifdef __UCLIBC_HAS_IPV6__
  1622. else if (ok == AF_INET6) {
  1623. if (addrlen < sizeof(struct sockaddr_in6))
  1624. return EAI_FAMILY;
  1625. }
  1626. #endif
  1627. else
  1628. return EAI_FAMILY;
  1629. ok = 0;
  1630. if (host != NULL && hostlen > 0)
  1631. switch (sa->sa_family) {
  1632. case AF_INET:
  1633. #ifdef __UCLIBC_HAS_IPV6__
  1634. case AF_INET6:
  1635. #endif
  1636. if (!(flags & NI_NUMERICHOST)) {
  1637. if (0) /* nothing */;
  1638. #ifdef __UCLIBC_HAS_IPV6__
  1639. else if (sa->sa_family == AF_INET6)
  1640. hoste = gethostbyaddr((const void *)
  1641. &(((const struct sockaddr_in6 *) sa)->sin6_addr),
  1642. sizeof(struct in6_addr), AF_INET6);
  1643. #endif
  1644. #ifdef __UCLIBC_HAS_IPV4__
  1645. else
  1646. hoste = gethostbyaddr((const void *)
  1647. &(((const struct sockaddr_in *)sa)->sin_addr),
  1648. sizeof(struct in_addr), AF_INET);
  1649. #endif
  1650. if (hoste) {
  1651. char *c;
  1652. #undef min
  1653. #define min(x,y) (((x) > (y)) ? (y) : (x))
  1654. if ((flags & NI_NOFQDN)
  1655. && (getdomainname(domain, sizeof(domain)) == 0)
  1656. && (c = strstr(hoste->h_name, domain)) != NULL
  1657. && (c != hoste->h_name) && (*(--c) == '.')
  1658. ) {
  1659. strncpy(host, hoste->h_name,
  1660. min(hostlen, (size_t) (c - hoste->h_name)));
  1661. host[min(hostlen - 1, (size_t) (c - hoste->h_name))] = '\0';
  1662. } else {
  1663. strncpy(host, hoste->h_name, hostlen);
  1664. }
  1665. ok = 1;
  1666. #undef min
  1667. }
  1668. }
  1669. if (!ok) {
  1670. const char *c = NULL;
  1671. if (flags & NI_NAMEREQD) {
  1672. errno = serrno;
  1673. return EAI_NONAME;
  1674. }
  1675. if (0) /* nothing */;
  1676. #ifdef __UCLIBC_HAS_IPV6__
  1677. else if (sa->sa_family == AF_INET6) {
  1678. const struct sockaddr_in6 *sin6p;
  1679. sin6p = (const struct sockaddr_in6 *) sa;
  1680. c = inet_ntop(AF_INET6,
  1681. (const void *) &sin6p->sin6_addr,
  1682. host, hostlen);
  1683. #if 0
  1684. /* Does scope id need to be supported? */
  1685. uint32_t scopeid;
  1686. scopeid = sin6p->sin6_scope_id;
  1687. if (scopeid != 0) {
  1688. /* Buffer is >= IFNAMSIZ+1. */
  1689. char scopebuf[IFNAMSIZ + 1];
  1690. char *scopeptr;
  1691. int ni_numericscope = 0;
  1692. size_t real_hostlen = strnlen(host, hostlen);
  1693. size_t scopelen = 0;
  1694. scopebuf[0] = SCOPE_DELIMITER;
  1695. scopebuf[1] = '\0';
  1696. scopeptr = &scopebuf[1];
  1697. if (IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr)
  1698. || IN6_IS_ADDR_MC_LINKLOCAL(&sin6p->sin6_addr)) {
  1699. if (if_indextoname(scopeid, scopeptr) == NULL)
  1700. ++ni_numericscope;
  1701. else
  1702. scopelen = strlen(scopebuf);
  1703. } else {
  1704. ++ni_numericscope;
  1705. }
  1706. if (ni_numericscope)
  1707. scopelen = 1 + snprintf(scopeptr,
  1708. (scopebuf
  1709. + sizeof scopebuf
  1710. - scopeptr),
  1711. "%u", scopeid);
  1712. if (real_hostlen + scopelen + 1 > hostlen)
  1713. return EAI_SYSTEM;
  1714. memcpy(host + real_hostlen, scopebuf, scopelen + 1);
  1715. }
  1716. #endif
  1717. }
  1718. #endif /* __UCLIBC_HAS_IPV6__ */
  1719. #if defined __UCLIBC_HAS_IPV4__
  1720. else {
  1721. c = inet_ntop(AF_INET, (const void *)
  1722. &(((const struct sockaddr_in *) sa)->sin_addr),
  1723. host, hostlen);
  1724. }
  1725. #endif
  1726. if (c == NULL) {
  1727. errno = serrno;
  1728. return EAI_SYSTEM;
  1729. }
  1730. ok = 1;
  1731. }
  1732. break;
  1733. case AF_LOCAL:
  1734. if (!(flags & NI_NUMERICHOST)) {
  1735. struct utsname utsname;
  1736. if (!uname(&utsname)) {
  1737. strncpy(host, utsname.nodename, hostlen);
  1738. break;
  1739. };
  1740. };
  1741. if (flags & NI_NAMEREQD) {
  1742. errno = serrno;
  1743. return EAI_NONAME;
  1744. }
  1745. strncpy(host, "localhost", hostlen);
  1746. break;
  1747. /* Already checked above
  1748. default:
  1749. return EAI_FAMILY;
  1750. */
  1751. }
  1752. if (serv && (servlen > 0)) {
  1753. if (sa->sa_family == AF_LOCAL) {
  1754. strncpy(serv, ((const struct sockaddr_un *) sa)->sun_path, servlen);
  1755. } else { /* AF_INET || AF_INET6 */
  1756. if (!(flags & NI_NUMERICSERV)) {
  1757. struct servent *s;
  1758. s = getservbyport(((const struct sockaddr_in *) sa)->sin_port,
  1759. ((flags & NI_DGRAM) ? "udp" : "tcp"));
  1760. if (s) {
  1761. strncpy(serv, s->s_name, servlen);
  1762. goto DONE;
  1763. }
  1764. }
  1765. snprintf(serv, servlen, "%d",
  1766. ntohs(((const struct sockaddr_in *) sa)->sin_port));
  1767. }
  1768. }
  1769. DONE:
  1770. if (host && (hostlen > 0))
  1771. host[hostlen-1] = 0;
  1772. if (serv && (servlen > 0))
  1773. serv[servlen-1] = 0;
  1774. errno = serrno;
  1775. return 0;
  1776. }
  1777. libc_hidden_def(getnameinfo)
  1778. #endif /* L_getnameinfo */
  1779. #ifdef L_gethostbyname_r
  1780. /* Bug 671 says:
  1781. * "uClibc resolver's gethostbyname does not return the requested name
  1782. * as an alias, but instead returns the canonical name. glibc's
  1783. * gethostbyname has a similar bug where it returns the requested name
  1784. * with the search domain name appended (to make a FQDN) as an alias,
  1785. * but not the original name itself. Both contradict POSIX, which says
  1786. * that the name argument passed to gethostbyname must be in the alias list"
  1787. * This is fixed now, and we differ from glibc:
  1788. *
  1789. * $ ./gethostbyname_uclibc wer.google.com
  1790. * h_name:'c13-ss-2-lb.cnet.com'
  1791. * h_length:4
  1792. * h_addrtype:2 AF_INET
  1793. * alias:'wer.google.com' <===
  1794. * addr: 0x4174efd8 '216.239.116.65'
  1795. *
  1796. * $ ./gethostbyname_glibc wer.google.com
  1797. * h_name:'c13-ss-2-lb.cnet.com'
  1798. * h_length:4
  1799. * h_addrtype:2 AF_INET
  1800. * alias:'wer.google.com.com' <===
  1801. * addr:'216.239.116.65'
  1802. *
  1803. * When examples were run, /etc/resolv.conf contained "search com" line.
  1804. */
  1805. int gethostbyname_r(const char *name,
  1806. struct hostent *result_buf,
  1807. char *buf,
  1808. size_t buflen,
  1809. struct hostent **result,
  1810. int *h_errnop)
  1811. {
  1812. struct in_addr **addr_list;
  1813. char **alias;
  1814. char *alias0;
  1815. unsigned char *packet;
  1816. struct resolv_answer a;
  1817. int i;
  1818. int packet_len;
  1819. int wrong_af = 0;
  1820. *result = NULL;
  1821. if (!name)
  1822. return EINVAL;
  1823. /* do /etc/hosts first */
  1824. {
  1825. int old_errno = errno; /* save the old errno and reset errno */
  1826. __set_errno(0); /* to check for missing /etc/hosts. */
  1827. i = __get_hosts_byname_r(name, AF_INET, result_buf,
  1828. buf, buflen, result, h_errnop);
  1829. if (i == NETDB_SUCCESS) {
  1830. __set_errno(old_errno);
  1831. return i;
  1832. }
  1833. switch (*h_errnop) {
  1834. case HOST_NOT_FOUND:
  1835. wrong_af = (i == TRY_AGAIN);
  1836. case NO_ADDRESS:
  1837. break;
  1838. case NETDB_INTERNAL:
  1839. if (errno == ENOENT) {
  1840. break;
  1841. }
  1842. /* else fall through */
  1843. default:
  1844. return i;
  1845. }
  1846. __set_errno(old_errno);
  1847. }
  1848. DPRINTF("Nothing found in /etc/hosts\n");
  1849. *h_errnop = NETDB_INTERNAL;
  1850. /* prepare future h_aliases[0] */
  1851. i = strlen(name) + 1;
  1852. if ((ssize_t)buflen <= i)
  1853. return ERANGE;
  1854. memcpy(buf, name, i); /* paranoia: name might change */
  1855. alias0 = buf;
  1856. buf += i;
  1857. buflen -= i;
  1858. /* make sure pointer is aligned */
  1859. i = ALIGN_BUFFER_OFFSET(buf);
  1860. buf += i;
  1861. buflen -= i;
  1862. /* Layout in buf:
  1863. * char *alias[2];
  1864. * struct in_addr* addr_list[NN+1];
  1865. * struct in_addr* in[NN];
  1866. */
  1867. alias = (char **)buf;
  1868. buf += sizeof(alias[0]) * 2;
  1869. buflen -= sizeof(alias[0]) * 2;
  1870. addr_list = (struct in_addr **)buf;
  1871. /* buflen may be < 0, must do signed compare */
  1872. if ((ssize_t)buflen < 256)
  1873. return ERANGE;
  1874. /* we store only one "alias" - the name itself */
  1875. #ifdef __UCLIBC_MJN3_ONLY__
  1876. #warning TODO -- generate the full list
  1877. #endif
  1878. alias[0] = alias0;
  1879. alias[1] = NULL;
  1880. /* maybe it is already an address? */
  1881. {
  1882. struct in_addr *in = (struct in_addr *)(buf + sizeof(addr_list[0]) * 2);
  1883. if (inet_aton(name, in)) {
  1884. addr_list[0] = in;
  1885. addr_list[1] = NULL;
  1886. result_buf->h_name = alias0;
  1887. result_buf->h_aliases = alias;
  1888. result_buf->h_addrtype = AF_INET;
  1889. result_buf->h_length = sizeof(struct in_addr);
  1890. result_buf->h_addr_list = (char **) addr_list;
  1891. *result = result_buf;
  1892. *h_errnop = NETDB_SUCCESS;
  1893. return NETDB_SUCCESS;
  1894. }
  1895. }
  1896. /* what if /etc/hosts has it but it's not IPv4?
  1897. * F.e. "::1 localhost6". We don't do DNS query for such hosts -
  1898. * "ping localhost6" should be fast even if DNS server is down! */
  1899. if (wrong_af) {
  1900. *h_errnop = HOST_NOT_FOUND;
  1901. return TRY_AGAIN;
  1902. }
  1903. /* talk to DNS servers */
  1904. a.buf = buf;
  1905. /* take into account that at least one address will be there,
  1906. * we'll need space of one in_addr + two addr_list[] elems */
  1907. a.buflen = buflen - ((sizeof(addr_list[0]) * 2 + sizeof(struct in_addr)));
  1908. a.add_count = 0;
  1909. packet_len = __dns_lookup(name, T_A, &packet, &a);
  1910. if (packet_len < 0) {
  1911. *h_errnop = HOST_NOT_FOUND;
  1912. DPRINTF("__dns_lookup returned < 0\n");
  1913. return TRY_AGAIN;
  1914. }
  1915. if (a.atype == T_A) { /* ADDRESS */
  1916. /* we need space for addr_list[] and one IPv4 address */
  1917. /* + 1 accounting for 1st addr (it's in a.rdata),
  1918. * another + 1 for NULL in last addr_list[]: */
  1919. int need_bytes = sizeof(addr_list[0]) * (a.add_count + 1 + 1)
  1920. /* for 1st addr (it's in a.rdata): */
  1921. + sizeof(struct in_addr);
  1922. /* how many bytes will 2nd and following addresses take? */
  1923. int ips_len = a.add_count * a.rdlength;
  1924. buflen -= (need_bytes + ips_len);
  1925. if ((ssize_t)buflen < 0) {
  1926. DPRINTF("buffer too small for all addresses\n");
  1927. /* *h_errnop = NETDB_INTERNAL; - already is */
  1928. i = ERANGE;
  1929. goto free_and_ret;
  1930. }
  1931. /* if there are additional addresses in buf,
  1932. * move them forward so that they are not destroyed */
  1933. DPRINTF("a.add_count:%d a.rdlength:%d a.rdata:%p\n", a.add_count, a.rdlength, a.rdata);
  1934. memmove(buf + need_bytes, buf, ips_len);
  1935. /* 1st address is in a.rdata, insert it */
  1936. buf += need_bytes - sizeof(struct in_addr);
  1937. memcpy(buf, a.rdata, sizeof(struct in_addr));
  1938. /* fill addr_list[] */
  1939. for (i = 0; i <= a.add_count; i++) {
  1940. addr_list[i] = (struct in_addr*)buf;
  1941. buf += sizeof(struct in_addr);
  1942. }
  1943. addr_list[i] = NULL;
  1944. /* if we have enough space, we can report "better" name
  1945. * (it may contain search domains attached by __dns_lookup,
  1946. * or CNAME of the host if it is different from the name
  1947. * we used to find it) */
  1948. if (a.dotted && buflen > strlen(a.dotted)) {
  1949. strcpy(buf, a.dotted);
  1950. alias0 = buf;
  1951. }
  1952. result_buf->h_name = alias0;
  1953. result_buf->h_aliases = alias;
  1954. result_buf->h_addrtype = AF_INET;
  1955. result_buf->h_length = sizeof(struct in_addr);
  1956. result_buf->h_addr_list = (char **) addr_list;
  1957. *result = result_buf;
  1958. *h_errnop = NETDB_SUCCESS;
  1959. i = NETDB_SUCCESS;
  1960. goto free_and_ret;
  1961. }
  1962. *h_errnop = HOST_NOT_FOUND;
  1963. i = TRY_AGAIN;
  1964. free_and_ret:
  1965. free(a.dotted);
  1966. free(packet);
  1967. return i;
  1968. }
  1969. libc_hidden_def(gethostbyname_r)
  1970. link_warning(gethostbyname_r, "gethostbyname_r is obsolescent, use getnameinfo() instead.");
  1971. #endif /* L_gethostbyname_r */
  1972. #ifdef L_gethostbyname2_r
  1973. int gethostbyname2_r(const char *name,
  1974. int family,
  1975. struct hostent *result_buf,
  1976. char *buf,
  1977. size_t buflen,
  1978. struct hostent **result,
  1979. int *h_errnop)
  1980. {
  1981. #ifndef __UCLIBC_HAS_IPV6__
  1982. return family == (AF_INET)
  1983. ? gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop)
  1984. : HOST_NOT_FOUND;
  1985. #else
  1986. struct in6_addr *in;
  1987. struct in6_addr **addr_list;
  1988. unsigned char *packet;
  1989. struct resolv_answer a;
  1990. int i;
  1991. int nest = 0;
  1992. int wrong_af = 0;
  1993. if (family == AF_INET)
  1994. return gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop);
  1995. *result = NULL;
  1996. if (family != AF_INET6)
  1997. return EINVAL;
  1998. if (!name)
  1999. return EINVAL;
  2000. /* do /etc/hosts first */
  2001. {
  2002. int old_errno = errno; /* Save the old errno and reset errno */
  2003. __set_errno(0); /* to check for missing /etc/hosts. */
  2004. i = __get_hosts_byname_r(name, AF_INET6 /*family*/, result_buf,
  2005. buf, buflen, result, h_errnop);
  2006. if (i == NETDB_SUCCESS) {
  2007. __set_errno(old_errno);
  2008. return i;
  2009. }
  2010. switch (*h_errnop) {
  2011. case HOST_NOT_FOUND:
  2012. wrong_af = (i == TRY_AGAIN);
  2013. case NO_ADDRESS:
  2014. break;
  2015. case NETDB_INTERNAL:
  2016. if (errno == ENOENT) {
  2017. break;
  2018. }
  2019. /* else fall through */
  2020. default:
  2021. return i;
  2022. }
  2023. __set_errno(old_errno);
  2024. }
  2025. DPRINTF("Nothing found in /etc/hosts\n");
  2026. *h_errnop = NETDB_INTERNAL;
  2027. /* make sure pointer is aligned */
  2028. i = ALIGN_BUFFER_OFFSET(buf);
  2029. buf += i;
  2030. buflen -= i;
  2031. /* Layout in buf:
  2032. * struct in6_addr* in;
  2033. * struct in6_addr* addr_list[2];
  2034. * char scratch_buf[256];
  2035. */
  2036. in = (struct in6_addr*)buf;
  2037. buf += sizeof(*in);
  2038. buflen -= sizeof(*in);
  2039. addr_list = (struct in6_addr**)buf;
  2040. buf += sizeof(*addr_list) * 2;
  2041. buflen -= sizeof(*addr_list) * 2;
  2042. if ((ssize_t)buflen < 256)
  2043. return ERANGE;
  2044. addr_list[0] = in;
  2045. addr_list[1] = NULL;
  2046. strncpy(buf, name, buflen);
  2047. buf[buflen] = '\0';
  2048. /* maybe it is already an address? */
  2049. if (inet_pton(AF_INET6, name, in)) {
  2050. result_buf->h_name = buf;
  2051. result_buf->h_addrtype = AF_INET6;
  2052. result_buf->h_length = sizeof(*in);
  2053. result_buf->h_addr_list = (char **) addr_list;
  2054. /* result_buf->h_aliases = ??? */
  2055. *result = result_buf;
  2056. *h_errnop = NETDB_SUCCESS;
  2057. return NETDB_SUCCESS;
  2058. }
  2059. /* what if /etc/hosts has it but it's not IPv6?
  2060. * F.e. "127.0.0.1 localhost". We don't do DNS query for such hosts -
  2061. * "ping localhost" should be fast even if DNS server is down! */
  2062. if (wrong_af) {
  2063. *h_errnop = HOST_NOT_FOUND;
  2064. return TRY_AGAIN;
  2065. }
  2066. /* talk to DNS servers */
  2067. /* TODO: why it's so different from gethostbyname_r (IPv4 case)? */
  2068. memset(&a, '\0', sizeof(a));
  2069. for (;;) {
  2070. int packet_len;
  2071. /* Hmm why we memset(a) to zeros only once? */
  2072. packet_len = __dns_lookup(buf, T_AAAA, &packet, &a);
  2073. if (packet_len < 0) {
  2074. *h_errnop = HOST_NOT_FOUND;
  2075. return TRY_AGAIN;
  2076. }
  2077. strncpy(buf, a.dotted, buflen);
  2078. free(a.dotted);
  2079. if (a.atype != T_CNAME)
  2080. break;
  2081. DPRINTF("Got a CNAME in gethostbyname()\n");
  2082. if (++nest > MAX_RECURSE) {
  2083. *h_errnop = NO_RECOVERY;
  2084. return -1;
  2085. }
  2086. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2087. free(packet);
  2088. if (i < 0) {
  2089. *h_errnop = NO_RECOVERY;
  2090. return -1;
  2091. }
  2092. }
  2093. if (a.atype == T_AAAA) { /* ADDRESS */
  2094. memcpy(in, a.rdata, sizeof(*in));
  2095. result_buf->h_name = buf;
  2096. result_buf->h_addrtype = AF_INET6;
  2097. result_buf->h_length = sizeof(*in);
  2098. result_buf->h_addr_list = (char **) addr_list;
  2099. /* result_buf->h_aliases = ??? */
  2100. free(packet);
  2101. *result = result_buf;
  2102. *h_errnop = NETDB_SUCCESS;
  2103. return NETDB_SUCCESS;
  2104. }
  2105. free(packet);
  2106. *h_errnop = HOST_NOT_FOUND;
  2107. return TRY_AGAIN;
  2108. #endif /* __UCLIBC_HAS_IPV6__ */
  2109. }
  2110. libc_hidden_def(gethostbyname2_r)
  2111. #endif /* L_gethostbyname2_r */
  2112. #ifdef L_gethostbyaddr_r
  2113. int gethostbyaddr_r(const void *addr, socklen_t addrlen,
  2114. int type,
  2115. struct hostent *result_buf,
  2116. char *buf, size_t buflen,
  2117. struct hostent **result,
  2118. int *h_errnop)
  2119. {
  2120. struct in_addr *in;
  2121. struct in_addr **addr_list;
  2122. char **alias;
  2123. unsigned char *packet;
  2124. struct resolv_answer a;
  2125. int i;
  2126. int packet_len;
  2127. int nest = 0;
  2128. *result = NULL;
  2129. if (!addr)
  2130. return EINVAL;
  2131. switch (type) {
  2132. #ifdef __UCLIBC_HAS_IPV4__
  2133. case AF_INET:
  2134. if (addrlen != sizeof(struct in_addr))
  2135. return EINVAL;
  2136. break;
  2137. #endif
  2138. #ifdef __UCLIBC_HAS_IPV6__
  2139. case AF_INET6:
  2140. if (addrlen != sizeof(struct in6_addr))
  2141. return EINVAL;
  2142. break;
  2143. #endif
  2144. default:
  2145. return EINVAL;
  2146. }
  2147. /* do /etc/hosts first */
  2148. i = __get_hosts_byaddr_r(addr, addrlen, type, result_buf,
  2149. buf, buflen, result, h_errnop);
  2150. if (i == 0)
  2151. return i;
  2152. switch (*h_errnop) {
  2153. case HOST_NOT_FOUND:
  2154. case NO_ADDRESS:
  2155. break;
  2156. default:
  2157. return i;
  2158. }
  2159. *h_errnop = NETDB_INTERNAL;
  2160. /* make sure pointer is aligned */
  2161. i = ALIGN_BUFFER_OFFSET(buf);
  2162. buf += i;
  2163. buflen -= i;
  2164. /* Layout in buf:
  2165. * char *alias[ALIAS_DIM];
  2166. * struct in[6]_addr* addr_list[2];
  2167. * struct in[6]_addr in;
  2168. * char scratch_buffer[256+];
  2169. */
  2170. #define in6 ((struct in6_addr *)in)
  2171. alias = (char **)buf;
  2172. addr_list = (struct in_addr**)buf;
  2173. buf += sizeof(*addr_list) * 2;
  2174. buflen -= sizeof(*addr_list) * 2;
  2175. in = (struct in_addr*)buf;
  2176. #ifndef __UCLIBC_HAS_IPV6__
  2177. buf += sizeof(*in);
  2178. buflen -= sizeof(*in);
  2179. if (addrlen > sizeof(*in))
  2180. return ERANGE;
  2181. #else
  2182. buf += sizeof(*in6);
  2183. buflen -= sizeof(*in6);
  2184. if (addrlen > sizeof(*in6))
  2185. return ERANGE;
  2186. #endif
  2187. if ((ssize_t)buflen < 256)
  2188. return ERANGE;
  2189. alias[0] = buf;
  2190. alias[1] = NULL;
  2191. addr_list[0] = in;
  2192. addr_list[1] = NULL;
  2193. memcpy(in, addr, addrlen);
  2194. if (0) /* nothing */;
  2195. #ifdef __UCLIBC_HAS_IPV4__
  2196. else IF_HAS_BOTH(if (type == AF_INET)) {
  2197. unsigned char *tp = (unsigned char *)addr;
  2198. sprintf(buf, "%u.%u.%u.%u.in-addr.arpa",
  2199. tp[3], tp[2], tp[1], tp[0]);
  2200. }
  2201. #endif
  2202. #ifdef __UCLIBC_HAS_IPV6__
  2203. else {
  2204. char *dst = buf;
  2205. unsigned char *tp = (unsigned char *)addr + addrlen - 1;
  2206. do {
  2207. dst += sprintf(dst, "%x.%x.", tp[0] & 0xf, tp[0] >> 4);
  2208. tp--;
  2209. } while (tp >= (unsigned char *)addr);
  2210. strcpy(dst, "ip6.arpa");
  2211. }
  2212. #endif
  2213. memset(&a, '\0', sizeof(a));
  2214. for (;;) {
  2215. /* Hmm why we memset(a) to zeros only once? */
  2216. packet_len = __dns_lookup(buf, T_PTR, &packet, &a);
  2217. if (packet_len < 0) {
  2218. *h_errnop = HOST_NOT_FOUND;
  2219. return TRY_AGAIN;
  2220. }
  2221. strncpy(buf, a.dotted, buflen);
  2222. free(a.dotted);
  2223. if (a.atype != T_CNAME)
  2224. break;
  2225. DPRINTF("Got a CNAME in gethostbyaddr()\n");
  2226. if (++nest > MAX_RECURSE) {
  2227. *h_errnop = NO_RECOVERY;
  2228. return -1;
  2229. }
  2230. /* Decode CNAME into buf, feed it to __dns_lookup() again */
  2231. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2232. free(packet);
  2233. if (i < 0) {
  2234. *h_errnop = NO_RECOVERY;
  2235. return -1;
  2236. }
  2237. }
  2238. if (a.atype == T_PTR) { /* ADDRESS */
  2239. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2240. free(packet);
  2241. result_buf->h_name = buf;
  2242. result_buf->h_addrtype = type;
  2243. result_buf->h_length = addrlen;
  2244. result_buf->h_addr_list = (char **) addr_list;
  2245. result_buf->h_aliases = alias;
  2246. *result = result_buf;
  2247. *h_errnop = NETDB_SUCCESS;
  2248. return NETDB_SUCCESS;
  2249. }
  2250. free(packet);
  2251. *h_errnop = NO_ADDRESS;
  2252. return TRY_AGAIN;
  2253. #undef in6
  2254. }
  2255. libc_hidden_def(gethostbyaddr_r)
  2256. link_warning(gethostbyaddr_r, "gethostbyaddr_r is obsolescent, use getaddrinfo() instead.");
  2257. #endif /* L_gethostbyaddr_r */
  2258. #ifdef L_gethostent_r
  2259. __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
  2260. static parser_t *hostp = NULL;
  2261. static smallint host_stayopen;
  2262. void endhostent_unlocked(void)
  2263. {
  2264. if (hostp) {
  2265. config_close(hostp);
  2266. hostp = NULL;
  2267. }
  2268. host_stayopen = 0;
  2269. }
  2270. void endhostent(void)
  2271. {
  2272. __UCLIBC_MUTEX_LOCK(mylock);
  2273. endhostent_unlocked();
  2274. __UCLIBC_MUTEX_UNLOCK(mylock);
  2275. }
  2276. void sethostent(int stay_open)
  2277. {
  2278. __UCLIBC_MUTEX_LOCK(mylock);
  2279. if (stay_open)
  2280. host_stayopen = 1;
  2281. __UCLIBC_MUTEX_UNLOCK(mylock);
  2282. }
  2283. int gethostent_r(struct hostent *result_buf, char *buf, size_t buflen,
  2284. struct hostent **result, int *h_errnop)
  2285. {
  2286. int ret;
  2287. __UCLIBC_MUTEX_LOCK(mylock);
  2288. if (hostp == NULL) {
  2289. hostp = __open_etc_hosts();
  2290. if (hostp == NULL) {
  2291. *result = NULL;
  2292. ret = TRY_AGAIN;
  2293. goto DONE;
  2294. }
  2295. }
  2296. ret = __read_etc_hosts_r(hostp, NULL, AF_INET, GETHOSTENT,
  2297. result_buf, buf, buflen, result, h_errnop);
  2298. if (!host_stayopen)
  2299. endhostent_unlocked();
  2300. DONE:
  2301. __UCLIBC_MUTEX_UNLOCK(mylock);
  2302. return ret;
  2303. }
  2304. libc_hidden_def(gethostent_r)
  2305. #endif /* L_gethostent_r */
  2306. #ifdef L_gethostent
  2307. struct hostent *gethostent(void)
  2308. {
  2309. static struct hostent hoste;
  2310. static char buf[
  2311. #ifndef __UCLIBC_HAS_IPV6__
  2312. sizeof(struct in_addr) + sizeof(struct in_addr *) * 2 +
  2313. #else
  2314. sizeof(struct in6_addr) + sizeof(struct in6_addr *) * 2 +
  2315. #endif /* __UCLIBC_HAS_IPV6__ */
  2316. BUFSZ /*namebuffer*/ + 2 /* margin */];
  2317. struct hostent *host;
  2318. gethostent_r(&hoste, buf, sizeof(buf), &host, &h_errno);
  2319. return host;
  2320. }
  2321. #endif /* L_gethostent */
  2322. #ifdef L_gethostbyname2
  2323. struct hostent *gethostbyname2(const char *name, int family)
  2324. {
  2325. #ifndef __UCLIBC_HAS_IPV6__
  2326. return family == AF_INET ? gethostbyname(name) : (struct hostent*)NULL;
  2327. #else
  2328. static struct hostent hoste;
  2329. static char buf[sizeof(struct in6_addr) +
  2330. sizeof(struct in6_addr *) * 2 +
  2331. /*sizeof(char *)*ALIAS_DIM +*/ 384/*namebuffer*/ + 32/* margin */];
  2332. struct hostent *hp;
  2333. gethostbyname2_r(name, family, &hoste, buf, sizeof(buf), &hp, &h_errno);
  2334. return hp;
  2335. #endif
  2336. }
  2337. libc_hidden_def(gethostbyname2)
  2338. #endif /* L_gethostbyname2 */
  2339. #ifdef L_gethostbyname
  2340. struct hostent *gethostbyname(const char *name)
  2341. {
  2342. #ifndef __UCLIBC_HAS_IPV6__
  2343. static struct hostent hoste;
  2344. static char buf[sizeof(struct in_addr) +
  2345. sizeof(struct in_addr *) * 2 +
  2346. /*sizeof(char *)*ALIAS_DIM +*/ 384/*namebuffer*/ + 32/* margin */];
  2347. struct hostent *hp;
  2348. gethostbyname_r(name, &hoste, buf, sizeof(buf), &hp, &h_errno);
  2349. return hp;
  2350. #else
  2351. return gethostbyname2(name, AF_INET);
  2352. #endif
  2353. }
  2354. libc_hidden_def(gethostbyname)
  2355. link_warning(gethostbyname, "gethostbyname is obsolescent, use getnameinfo() instead.");
  2356. #endif /* L_gethostbyname */
  2357. #ifdef L_gethostbyaddr
  2358. struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type)
  2359. {
  2360. static struct hostent hoste;
  2361. static char buf[
  2362. #ifndef __UCLIBC_HAS_IPV6__
  2363. sizeof(struct in_addr) + sizeof(struct in_addr *)*2 +
  2364. #else
  2365. sizeof(struct in6_addr) + sizeof(struct in6_addr *)*2 +
  2366. #endif /* __UCLIBC_HAS_IPV6__ */
  2367. /*sizeof(char *)*ALIAS_DIM +*/ 384 /*namebuffer*/ + 32 /* margin */];
  2368. struct hostent *hp;
  2369. gethostbyaddr_r(addr, len, type, &hoste, buf, sizeof(buf), &hp, &h_errno);
  2370. return hp;
  2371. }
  2372. libc_hidden_def(gethostbyaddr)
  2373. link_warning(gethostbyaddr, "gethostbyaddr is obsolescent, use getaddrinfo() instead.");
  2374. #endif /* L_gethostbyaddr */
  2375. #ifdef L_res_comp
  2376. /*
  2377. * Expand compressed domain name 'comp_dn' to full domain name.
  2378. * 'msg' is a pointer to the begining of the message,
  2379. * 'eomorig' points to the first location after the message,
  2380. * 'exp_dn' is a pointer to a buffer of size 'length' for the result.
  2381. * Return size of compressed name or -1 if there was an error.
  2382. */
  2383. int dn_expand(const u_char *msg, const u_char *eom, const u_char *src,
  2384. char *dst, int dstsiz)
  2385. {
  2386. int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz);
  2387. if (n > 0 && dst[0] == '.')
  2388. dst[0] = '\0';
  2389. return n;
  2390. }
  2391. #endif /* L_res_comp */
  2392. #ifdef L_ns_name
  2393. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2394. * is this character visible and not a space when printed ?
  2395. */
  2396. static int printable(int ch)
  2397. {
  2398. return (ch > 0x20 && ch < 0x7f);
  2399. }
  2400. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2401. * is this characted special ("in need of quoting") ?
  2402. */
  2403. static int special(int ch)
  2404. {
  2405. switch (ch) {
  2406. case 0x22: /* '"' */
  2407. case 0x2E: /* '.' */
  2408. case 0x3B: /* ';' */
  2409. case 0x5C: /* '\\' */
  2410. /* Special modifiers in zone files. */
  2411. case 0x40: /* '@' */
  2412. case 0x24: /* '$' */
  2413. return 1;
  2414. default:
  2415. return 0;
  2416. }
  2417. }
  2418. /*
  2419. * ns_name_uncompress(msg, eom, src, dst, dstsiz)
  2420. * Expand compressed domain name to presentation format.
  2421. * return:
  2422. * Number of bytes read out of `src', or -1 (with errno set).
  2423. * note:
  2424. * Root domain returns as "." not "".
  2425. */
  2426. int ns_name_uncompress(const u_char *msg, const u_char *eom,
  2427. const u_char *src, char *dst, size_t dstsiz)
  2428. {
  2429. u_char tmp[NS_MAXCDNAME];
  2430. int n;
  2431. n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp);
  2432. if (n == -1)
  2433. return -1;
  2434. if (ns_name_ntop(tmp, dst, dstsiz) == -1)
  2435. return -1;
  2436. return n;
  2437. }
  2438. libc_hidden_def(ns_name_uncompress)
  2439. /*
  2440. * ns_name_ntop(src, dst, dstsiz)
  2441. * Convert an encoded domain name to printable ascii as per RFC1035.
  2442. * return:
  2443. * Number of bytes written to buffer, or -1 (with errno set)
  2444. * notes:
  2445. * The root is returned as "."
  2446. * All other domains are returned in non absolute form
  2447. */
  2448. int ns_name_ntop(const u_char *src, char *dst, size_t dstsiz)
  2449. {
  2450. static const char digits[] = "0123456789";
  2451. const u_char *cp;
  2452. char *dn, *eom;
  2453. u_char c;
  2454. u_int n;
  2455. cp = src;
  2456. dn = dst;
  2457. eom = dst + dstsiz;
  2458. while ((n = *cp++) != 0) {
  2459. if ((n & NS_CMPRSFLGS) != 0) {
  2460. /* Some kind of compression pointer. */
  2461. __set_errno(EMSGSIZE);
  2462. return -1;
  2463. }
  2464. if (dn != dst) {
  2465. if (dn >= eom) {
  2466. __set_errno(EMSGSIZE);
  2467. return -1;
  2468. }
  2469. *dn++ = '.';
  2470. }
  2471. if (dn + n >= eom) {
  2472. __set_errno(EMSGSIZE);
  2473. return -1;
  2474. }
  2475. for (; n > 0; n--) {
  2476. c = *cp++;
  2477. if (special(c)) {
  2478. if (dn + 1 >= eom) {
  2479. __set_errno(EMSGSIZE);
  2480. return -1;
  2481. }
  2482. *dn++ = '\\';
  2483. *dn++ = (char)c;
  2484. } else if (!printable(c)) {
  2485. if (dn + 3 >= eom) {
  2486. __set_errno(EMSGSIZE);
  2487. return -1;
  2488. }
  2489. *dn++ = '\\';
  2490. *dn++ = digits[c / 100];
  2491. *dn++ = digits[(c % 100) / 10];
  2492. *dn++ = digits[c % 10];
  2493. } else {
  2494. if (dn >= eom) {
  2495. __set_errno(EMSGSIZE);
  2496. return -1;
  2497. }
  2498. *dn++ = (char)c;
  2499. }
  2500. }
  2501. }
  2502. if (dn == dst) {
  2503. if (dn >= eom) {
  2504. __set_errno(EMSGSIZE);
  2505. return -1;
  2506. }
  2507. *dn++ = '.';
  2508. }
  2509. if (dn >= eom) {
  2510. __set_errno(EMSGSIZE);
  2511. return -1;
  2512. }
  2513. *dn++ = '\0';
  2514. return (dn - dst);
  2515. }
  2516. libc_hidden_def(ns_name_ntop)
  2517. /*
  2518. * ns_name_unpack(msg, eom, src, dst, dstsiz)
  2519. * Unpack a domain name from a message, source may be compressed.
  2520. * return:
  2521. * -1 if it fails, or consumed octets if it succeeds.
  2522. */
  2523. int ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
  2524. u_char *dst, size_t dstsiz)
  2525. {
  2526. const u_char *srcp, *dstlim;
  2527. u_char *dstp;
  2528. int n, len, checked;
  2529. len = -1;
  2530. checked = 0;
  2531. dstp = dst;
  2532. srcp = src;
  2533. dstlim = dst + dstsiz;
  2534. if (srcp < msg || srcp >= eom) {
  2535. __set_errno(EMSGSIZE);
  2536. return -1;
  2537. }
  2538. /* Fetch next label in domain name. */
  2539. while ((n = *srcp++) != 0) {
  2540. /* Check for indirection. */
  2541. switch (n & NS_CMPRSFLGS) {
  2542. case 0:
  2543. /* Limit checks. */
  2544. if (dstp + n + 1 >= dstlim || srcp + n >= eom) {
  2545. __set_errno(EMSGSIZE);
  2546. return -1;
  2547. }
  2548. checked += n + 1;
  2549. *dstp++ = n;
  2550. memcpy(dstp, srcp, n);
  2551. dstp += n;
  2552. srcp += n;
  2553. break;
  2554. case NS_CMPRSFLGS:
  2555. if (srcp >= eom) {
  2556. __set_errno(EMSGSIZE);
  2557. return -1;
  2558. }
  2559. if (len < 0)
  2560. len = srcp - src + 1;
  2561. srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
  2562. if (srcp < msg || srcp >= eom) { /* Out of range. */
  2563. __set_errno(EMSGSIZE);
  2564. return -1;
  2565. }
  2566. checked += 2;
  2567. /*
  2568. * Check for loops in the compressed name;
  2569. * if we've looked at the whole message,
  2570. * there must be a loop.
  2571. */
  2572. if (checked >= eom - msg) {
  2573. __set_errno(EMSGSIZE);
  2574. return -1;
  2575. }
  2576. break;
  2577. default:
  2578. __set_errno(EMSGSIZE);
  2579. return -1; /* flag error */
  2580. }
  2581. }
  2582. *dstp = '\0';
  2583. if (len < 0)
  2584. len = srcp - src;
  2585. return len;
  2586. }
  2587. libc_hidden_def(ns_name_unpack)
  2588. #endif /* L_ns_name */
  2589. #ifdef L_res_init
  2590. /* Will be called under __resolv_lock. */
  2591. static void res_sync_func(void)
  2592. {
  2593. struct __res_state *rp = &(_res);
  2594. int n;
  2595. /* If we didn't get malloc failure earlier... */
  2596. if (__nameserver != (void*) &__local_nameserver) {
  2597. /* TODO:
  2598. * if (__nameservers < rp->nscount) - try to grow __nameserver[]?
  2599. */
  2600. #ifdef __UCLIBC_HAS_IPV6__
  2601. if (__nameservers > rp->_u._ext.nscount)
  2602. __nameservers = rp->_u._ext.nscount;
  2603. n = __nameservers;
  2604. while (--n >= 0)
  2605. __nameserver[n].sa6 = *rp->_u._ext.nsaddrs[n]; /* struct copy */
  2606. #else /* IPv4 only */
  2607. if (__nameservers > rp->nscount)
  2608. __nameservers = rp->nscount;
  2609. n = __nameservers;
  2610. while (--n >= 0)
  2611. __nameserver[n].sa4 = rp->nsaddr_list[n]; /* struct copy */
  2612. #endif
  2613. }
  2614. __resolv_timeout = rp->retrans ? : RES_TIMEOUT;
  2615. __resolv_attempts = rp->retry ? : RES_DFLRETRY;
  2616. /* Extend and comment what program is known
  2617. * to use which _res.XXX member(s).
  2618. __resolv_opts = rp->options;
  2619. ...
  2620. */
  2621. }
  2622. /* Our res_init never fails (always returns 0) */
  2623. int res_init(void)
  2624. {
  2625. struct __res_state *rp = &(_res);
  2626. int i;
  2627. int n;
  2628. #ifdef __UCLIBC_HAS_IPV6__
  2629. int m = 0;
  2630. #endif
  2631. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2632. __close_nameservers();
  2633. __open_nameservers();
  2634. __res_sync = res_sync_func;
  2635. memset(rp, 0, sizeof(*rp));
  2636. rp->options = RES_INIT;
  2637. rp->retrans = RES_TIMEOUT;
  2638. rp->retry = RES_DFLRETRY;
  2639. rp->ndots = 1;
  2640. #ifdef __UCLIBC_HAS_COMPAT_RES_STATE__
  2641. /* Was: "rp->id = random();" but:
  2642. * - random() pulls in largish static buffers
  2643. * - isn't actually random unless, say, srandom(time(NULL)) was called
  2644. * - is not used by uclibc anyway :)
  2645. */
  2646. /* rp->id = 0; - memset did it */
  2647. #endif
  2648. #ifdef __UCLIBC_HAS_EXTRA_COMPAT_RES_STATE__
  2649. rp->_vcsock = -1;
  2650. #endif
  2651. n = __searchdomains;
  2652. if (n > ARRAY_SIZE(rp->dnsrch))
  2653. n = ARRAY_SIZE(rp->dnsrch);
  2654. for (i = 0; i < n; i++)
  2655. rp->dnsrch[i] = __searchdomain[i];
  2656. /* copy nameservers' addresses */
  2657. i = 0;
  2658. #ifdef __UCLIBC_HAS_IPV4__
  2659. n = 0;
  2660. while (n < ARRAY_SIZE(rp->nsaddr_list) && i < __nameservers) {
  2661. if (__nameserver[i].sa.sa_family == AF_INET) {
  2662. rp->nsaddr_list[n] = __nameserver[i].sa4; /* struct copy */
  2663. #ifdef __UCLIBC_HAS_IPV6__
  2664. if (m < ARRAY_SIZE(rp->_u._ext.nsaddrs)) {
  2665. rp->_u._ext.nsaddrs[m] = (void*) &rp->nsaddr_list[n];
  2666. m++;
  2667. }
  2668. #endif
  2669. n++;
  2670. }
  2671. #ifdef __UCLIBC_HAS_IPV6__
  2672. if (__nameserver[i].sa.sa_family == AF_INET6
  2673. && m < ARRAY_SIZE(rp->_u._ext.nsaddrs)
  2674. ) {
  2675. struct sockaddr_in6 *sa6 = malloc(sizeof(*sa6));
  2676. if (sa6) {
  2677. *sa6 = __nameserver[i].sa6; /* struct copy */
  2678. rp->_u._ext.nsaddrs[m] = sa6;
  2679. m++;
  2680. }
  2681. }
  2682. #endif
  2683. i++;
  2684. }
  2685. rp->nscount = n;
  2686. #ifdef __UCLIBC_HAS_IPV6__
  2687. rp->_u._ext.nscount = m;
  2688. #endif
  2689. #else /* IPv6 only */
  2690. while (m < ARRAY_SIZE(rp->_u._ext.nsaddrs) && i < __nameservers) {
  2691. struct sockaddr_in6 *sa6 = malloc(sizeof(*sa6));
  2692. if (sa6) {
  2693. *sa6 = __nameserver[i].sa6; /* struct copy */
  2694. rp->_u._ext.nsaddrs[m] = sa6;
  2695. m++;
  2696. }
  2697. i++;
  2698. }
  2699. rp->_u._ext.nscount = m;
  2700. #endif
  2701. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2702. return 0;
  2703. }
  2704. libc_hidden_def(res_init)
  2705. #ifdef __UCLIBC_HAS_BSD_RES_CLOSE__
  2706. void res_close(void)
  2707. {
  2708. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2709. __close_nameservers();
  2710. __res_sync = NULL;
  2711. #ifdef __UCLIBC_HAS_IPV6__
  2712. {
  2713. char *p1 = (char*) &(_res.nsaddr_list[0]);
  2714. int m = 0;
  2715. /* free nsaddrs[m] if they do not point to nsaddr_list[x] */
  2716. while (m < ARRAY_SIZE(_res._u._ext.nsaddrs)) {
  2717. char *p2 = (char*)(_res._u._ext.nsaddrs[m++]);
  2718. if (p2 < p1 || (p2 - p1) > sizeof(_res.nsaddr_list))
  2719. free(p2);
  2720. }
  2721. }
  2722. #endif
  2723. memset(&_res, 0, sizeof(_res));
  2724. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2725. }
  2726. #endif /* __UCLIBC_HAS_BSD_RES_CLOSE__ */
  2727. /* This needs to be after the use of _res in res_init, above. */
  2728. #undef _res
  2729. #ifndef __UCLIBC_HAS_THREADS__
  2730. /* The resolver state for use by single-threaded programs.
  2731. This differs from plain `struct __res_state _res;' in that it doesn't
  2732. create a common definition, but a plain symbol that resides in .bss,
  2733. which can have an alias. */
  2734. struct __res_state _res __attribute__((section (".bss")));
  2735. struct __res_state *__resp = &_res;
  2736. #else /* __UCLIBC_HAS_THREADS__ */
  2737. struct __res_state _res __attribute__((section (".bss"))) attribute_hidden;
  2738. # if defined __UCLIBC_HAS_TLS__
  2739. # undef __resp
  2740. __thread struct __res_state *__resp = &_res;
  2741. /*
  2742. * FIXME: Add usage of hidden attribute for this when used in the shared
  2743. * library. It currently crashes the linker when doing section
  2744. * relocations.
  2745. */
  2746. extern __thread struct __res_state *__libc_resp
  2747. __attribute__ ((alias ("__resp"))) attribute_hidden;
  2748. # else
  2749. # undef __resp
  2750. struct __res_state *__resp = &_res;
  2751. # endif
  2752. #endif /* !__UCLIBC_HAS_THREADS__ */
  2753. #endif /* L_res_init */
  2754. #ifdef L_res_state
  2755. # if defined __UCLIBC_HAS_TLS__
  2756. struct __res_state *
  2757. __res_state (void)
  2758. {
  2759. return __resp;
  2760. }
  2761. # else
  2762. # undef _res
  2763. extern struct __res_state _res;
  2764. /* When threaded, _res may be a per-thread variable. */
  2765. struct __res_state *
  2766. weak_const_function
  2767. __res_state (void)
  2768. {
  2769. return &_res;
  2770. }
  2771. # endif
  2772. #endif /* L_res_state */
  2773. #ifdef L_res_query
  2774. int res_query(const char *dname, int class, int type,
  2775. unsigned char *answer, int anslen)
  2776. {
  2777. int i;
  2778. unsigned char *packet = NULL;
  2779. struct resolv_answer a;
  2780. if (!dname || class != 1 /* CLASS_IN */) {
  2781. h_errno = NO_RECOVERY;
  2782. return -1;
  2783. }
  2784. memset(&a, '\0', sizeof(a));
  2785. i = __dns_lookup(dname, type, &packet, &a);
  2786. if (i < 0) {
  2787. if (!h_errno) /* TODO: can this ever happen? */
  2788. h_errno = TRY_AGAIN;
  2789. return -1;
  2790. }
  2791. free(a.dotted);
  2792. if (a.atype == type) { /* CNAME */
  2793. if (i > anslen)
  2794. i = anslen;
  2795. memcpy(answer, packet, i);
  2796. }
  2797. free(packet);
  2798. return i;
  2799. }
  2800. libc_hidden_def(res_query)
  2801. /*
  2802. * Formulate a normal query, send, and retrieve answer in supplied buffer.
  2803. * Return the size of the response on success, -1 on error.
  2804. * If enabled, implement search rules until answer or unrecoverable failure
  2805. * is detected. Error code, if any, is left in h_errno.
  2806. */
  2807. #define __TRAILING_DOT (1<<0)
  2808. #define __GOT_NODATA (1<<1)
  2809. #define __GOT_SERVFAIL (1<<2)
  2810. #define __TRIED_AS_IS (1<<3)
  2811. int res_search(const char *name, int class, int type, u_char *answer,
  2812. int anslen)
  2813. {
  2814. const char *cp;
  2815. char **domain;
  2816. HEADER *hp = (HEADER *)(void *)answer;
  2817. unsigned dots;
  2818. unsigned state;
  2819. int ret, saved_herrno;
  2820. uint32_t _res_options;
  2821. unsigned _res_ndots;
  2822. char **_res_dnsrch;
  2823. if (!name || !answer) {
  2824. h_errno = NETDB_INTERNAL;
  2825. return -1;
  2826. }
  2827. again:
  2828. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2829. _res_options = _res.options;
  2830. _res_ndots = _res.ndots;
  2831. _res_dnsrch = _res.dnsrch;
  2832. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2833. if (!(_res_options & RES_INIT)) {
  2834. res_init(); /* our res_init never fails */
  2835. goto again;
  2836. }
  2837. state = 0;
  2838. errno = 0;
  2839. h_errno = HOST_NOT_FOUND; /* default, if we never query */
  2840. dots = 0;
  2841. for (cp = name; *cp; cp++)
  2842. dots += (*cp == '.');
  2843. if (cp > name && *--cp == '.')
  2844. state |= __TRAILING_DOT;
  2845. /*
  2846. * If there are dots in the name already, let's just give it a try
  2847. * 'as is'. The threshold can be set with the "ndots" option.
  2848. */
  2849. saved_herrno = -1;
  2850. if (dots >= _res_ndots) {
  2851. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  2852. if (ret > 0)
  2853. return ret;
  2854. saved_herrno = h_errno;
  2855. state |= __TRIED_AS_IS;
  2856. }
  2857. /*
  2858. * We do at least one level of search if
  2859. * - there is no dot and RES_DEFNAME is set, or
  2860. * - there is at least one dot, there is no trailing dot,
  2861. * and RES_DNSRCH is set.
  2862. */
  2863. if ((!dots && (_res_options & RES_DEFNAMES))
  2864. || (dots && !(state & __TRAILING_DOT) && (_res_options & RES_DNSRCH))
  2865. ) {
  2866. bool done = 0;
  2867. for (domain = _res_dnsrch; *domain && !done; domain++) {
  2868. ret = res_querydomain(name, *domain, class, type,
  2869. answer, anslen);
  2870. if (ret > 0)
  2871. return ret;
  2872. /*
  2873. * If no server present, give up.
  2874. * If name isn't found in this domain,
  2875. * keep trying higher domains in the search list
  2876. * (if that's enabled).
  2877. * On a NO_DATA error, keep trying, otherwise
  2878. * a wildcard entry of another type could keep us
  2879. * from finding this entry higher in the domain.
  2880. * If we get some other error (negative answer or
  2881. * server failure), then stop searching up,
  2882. * but try the input name below in case it's
  2883. * fully-qualified.
  2884. */
  2885. if (errno == ECONNREFUSED) {
  2886. h_errno = TRY_AGAIN;
  2887. return -1;
  2888. }
  2889. switch (h_errno) {
  2890. case NO_DATA:
  2891. state |= __GOT_NODATA;
  2892. /* FALLTHROUGH */
  2893. case HOST_NOT_FOUND:
  2894. /* keep trying */
  2895. break;
  2896. case TRY_AGAIN:
  2897. if (hp->rcode == SERVFAIL) {
  2898. /* try next search element, if any */
  2899. state |= __GOT_SERVFAIL;
  2900. break;
  2901. }
  2902. /* FALLTHROUGH */
  2903. default:
  2904. /* anything else implies that we're done */
  2905. done = 1;
  2906. }
  2907. /*
  2908. * if we got here for some reason other than DNSRCH,
  2909. * we only wanted one iteration of the loop, so stop.
  2910. */
  2911. if (!(_res_options & RES_DNSRCH))
  2912. done = 1;
  2913. }
  2914. }
  2915. /*
  2916. * if we have not already tried the name "as is", do that now.
  2917. * note that we do this regardless of how many dots were in the
  2918. * name or whether it ends with a dot.
  2919. */
  2920. if (!(state & __TRIED_AS_IS)) {
  2921. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  2922. if (ret > 0)
  2923. return ret;
  2924. }
  2925. /*
  2926. * if we got here, we didn't satisfy the search.
  2927. * if we did an initial full query, return that query's h_errno
  2928. * (note that we wouldn't be here if that query had succeeded).
  2929. * else if we ever got a nodata, send that back as the reason.
  2930. * else send back meaningless h_errno, that being the one from
  2931. * the last DNSRCH we did.
  2932. */
  2933. if (saved_herrno != -1)
  2934. h_errno = saved_herrno;
  2935. else if (state & __GOT_NODATA)
  2936. h_errno = NO_DATA;
  2937. else if (state & __GOT_SERVFAIL)
  2938. h_errno = TRY_AGAIN;
  2939. return -1;
  2940. }
  2941. #undef __TRAILING_DOT
  2942. #undef __GOT_NODATA
  2943. #undef __GOT_SERVFAIL
  2944. #undef __TRIED_AS_IS
  2945. /*
  2946. * Perform a call on res_query on the concatenation of name and domain,
  2947. * removing a trailing dot from name if domain is NULL.
  2948. */
  2949. int res_querydomain(const char *name, const char *domain, int class, int type,
  2950. u_char *answer, int anslen)
  2951. {
  2952. char nbuf[MAXDNAME];
  2953. const char *longname = nbuf;
  2954. size_t n, d;
  2955. #ifdef DEBUG
  2956. uint32_t _res_options;
  2957. #endif
  2958. if (!name || !answer) {
  2959. h_errno = NETDB_INTERNAL;
  2960. return -1;
  2961. }
  2962. #ifdef DEBUG
  2963. again:
  2964. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  2965. _res_options = _res.options;
  2966. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  2967. if (!(_res_options & RES_INIT)) {
  2968. res_init(); /* our res_init never fails */
  2969. goto again;
  2970. }
  2971. if (_res_options & RES_DEBUG)
  2972. printf(";; res_querydomain(%s, %s, %d, %d)\n",
  2973. name, (domain ? domain : "<Nil>"), class, type);
  2974. #endif
  2975. if (domain == NULL) {
  2976. /*
  2977. * Check for trailing '.';
  2978. * copy without '.' if present.
  2979. */
  2980. n = strlen(name);
  2981. if (n + 1 > sizeof(nbuf)) {
  2982. h_errno = NO_RECOVERY;
  2983. return -1;
  2984. }
  2985. if (n > 0 && name[--n] == '.') {
  2986. strncpy(nbuf, name, n);
  2987. nbuf[n] = '\0';
  2988. } else
  2989. longname = name;
  2990. } else {
  2991. n = strlen(name);
  2992. d = strlen(domain);
  2993. if (n + 1 + d + 1 > sizeof(nbuf)) {
  2994. h_errno = NO_RECOVERY;
  2995. return -1;
  2996. }
  2997. snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
  2998. }
  2999. return res_query(longname, class, type, answer, anslen);
  3000. }
  3001. libc_hidden_def(res_querydomain)
  3002. #endif /* L_res_query */
  3003. #ifdef L_ns_netint
  3004. unsigned int ns_get16(const unsigned char *src)
  3005. {
  3006. unsigned int dst;
  3007. NS_GET16(dst, src);
  3008. return dst;
  3009. }
  3010. unsigned long ns_get32(const unsigned char *src)
  3011. {
  3012. unsigned long dst;
  3013. NS_GET32(dst, src);
  3014. return dst;
  3015. }
  3016. void ns_put16(unsigned int src, unsigned char *dst)
  3017. {
  3018. NS_PUT16(src, dst);
  3019. }
  3020. void ns_put32(unsigned long src, unsigned char *dst)
  3021. {
  3022. NS_PUT32(src, dst);
  3023. }
  3024. #endif /* L_ns_netint */
  3025. /* Unimplemented: */
  3026. /* res_mkquery */
  3027. /* res_send */
  3028. /* dn_comp */