resolv.c 110 KB

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