resolv.c 87 KB

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