resolv.c 87 KB

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