resolv.c 107 KB

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