resolv.c 87 KB

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