resolv.c 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366
  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. sockaddr46_t sa;
  1139. fd = -1;
  1140. lookup = NULL;
  1141. name_len = strlen(name);
  1142. if ((unsigned)name_len >= MAXDNAME - MAXLEN_searchdomain - 2)
  1143. goto fail; /* paranoia */
  1144. lookup = malloc(name_len + 1/*for '.'*/ + MAXLEN_searchdomain + 1);
  1145. if (!packet || !lookup || !name[0])
  1146. goto fail;
  1147. ends_with_dot = (name[name_len - 1] == '.');
  1148. /* no strcpy! paranoia, user might change name[] under us */
  1149. memcpy(lookup, name, name_len);
  1150. DPRINTF("Looking up type %d answer for '%s'\n", type, name);
  1151. retries_left = 0; /* for compiler */
  1152. do {
  1153. int pos;
  1154. unsigned reply_timeout;
  1155. if (fd != -1) {
  1156. close(fd);
  1157. fd = -1;
  1158. }
  1159. /* Mess with globals while under lock */
  1160. /* NB: even data *pointed to* by globals may vanish
  1161. * outside the locks. We should assume any and all
  1162. * globals can completely change between locked
  1163. * code regions. OTOH, this is rare, so we don't need
  1164. * to handle it "nicely" (do not skip servers,
  1165. * search domains, etc), we only need to ensure
  1166. * we do not SEGV, use freed+overwritten data
  1167. * or do other Really Bad Things. */
  1168. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  1169. __open_nameservers();
  1170. if (type != T_PTR) {
  1171. sdomains = __searchdomains;
  1172. }
  1173. lookup[name_len] = '\0';
  1174. if ((unsigned)variant < sdomains) {
  1175. /* lookup is name_len + 1 + MAXLEN_searchdomain + 1 long */
  1176. /* __searchdomain[] is not bigger than MAXLEN_searchdomain */
  1177. lookup[name_len] = '.';
  1178. strcpy(&lookup[name_len + 1], __searchdomain[variant]);
  1179. }
  1180. /* first time? pick starting server etc */
  1181. if (local_ns_num < 0) {
  1182. local_id = last_id;
  1183. /*TODO: implement /etc/resolv.conf's "options rotate"
  1184. (a.k.a. RES_ROTATE bit in _res.options)
  1185. local_ns_num = 0;
  1186. if (_res.options & RES_ROTATE) */
  1187. local_ns_num = last_ns_num;
  1188. retries_left = __nameservers * __resolv_attempts;
  1189. }
  1190. if (local_ns_num >= __nameservers)
  1191. local_ns_num = 0;
  1192. local_id++;
  1193. local_id &= 0xffff;
  1194. /* write new values back while still under lock */
  1195. last_id = local_id;
  1196. last_ns_num = local_ns_num;
  1197. /* struct copy */
  1198. /* can't just take a pointer, __nameserver[x]
  1199. * is not safe to use outside of locks */
  1200. sa = __nameserver[local_ns_num];
  1201. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  1202. memset(packet, 0, PACKETSZ);
  1203. memset(&h, 0, sizeof(h));
  1204. /* encode header */
  1205. h.id = local_id;
  1206. h.qdcount = 1;
  1207. h.rd = 1;
  1208. DPRINTF("encoding header\n", h.rd);
  1209. i = __encode_header(&h, packet, PACKETSZ);
  1210. if (i < 0)
  1211. goto fail;
  1212. /* encode question */
  1213. DPRINTF("lookup name: %s\n", lookup);
  1214. q.dotted = lookup;
  1215. q.qtype = type;
  1216. q.qclass = C_IN; /* CLASS_IN */
  1217. j = __encode_question(&q, packet+i, PACKETSZ-i);
  1218. if (j < 0)
  1219. goto fail;
  1220. packet_len = i + j;
  1221. /* send packet */
  1222. #ifdef DEBUG
  1223. {
  1224. const socklen_t plen = sa.sa.sa_family == AF_INET ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN;
  1225. char *pbuf = malloc(plen);
  1226. if (pbuf == NULL) ;/* nothing */
  1227. #ifdef __UCLIBC_HAS_IPV6__
  1228. else if (sa.sa.sa_family == AF_INET6)
  1229. pbuf = (char*)inet_ntop(AF_INET6, &sa.sa6.sin6_addr, pbuf, plen);
  1230. #endif
  1231. #ifdef __UCLIBC_HAS_IPV4__
  1232. else if (sa.sa.sa_family == AF_INET)
  1233. pbuf = (char*)inet_ntop(AF_INET, &sa.sa4.sin_addr, pbuf, plen);
  1234. #endif
  1235. DPRINTF("On try %d, sending query to %s, port %d\n",
  1236. retries_left, pbuf, NAMESERVER_PORT);
  1237. free(pbuf);
  1238. }
  1239. #endif
  1240. fd = socket(sa.sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
  1241. if (fd < 0) /* paranoia */
  1242. goto try_next_server;
  1243. rc = connect(fd, &sa.sa, sizeof(sa));
  1244. if (rc < 0) {
  1245. /*if (errno == ENETUNREACH) { */
  1246. /* routing error, presume not transient */
  1247. goto try_next_server;
  1248. /*} */
  1249. /*For example, what transient error this can be? Can't think of any */
  1250. /* retry */
  1251. /*continue; */
  1252. }
  1253. DPRINTF("Xmit packet len:%d id:%d qr:%d\n", packet_len, h.id, h.qr);
  1254. /* no error check - if it fails, we time out on recv */
  1255. send(fd, packet, packet_len, 0);
  1256. #ifdef USE_SELECT
  1257. reply_timeout = __resolv_timeout;
  1258. wait_again:
  1259. FD_ZERO(&fds);
  1260. FD_SET(fd, &fds);
  1261. tv.tv_sec = reply_timeout;
  1262. tv.tv_usec = 0;
  1263. if (select(fd + 1, &fds, NULL, NULL, &tv) <= 0) {
  1264. DPRINTF("Timeout\n");
  1265. /* timed out, so retry send and receive
  1266. * to next nameserver */
  1267. goto try_next_server;
  1268. }
  1269. reply_timeout--;
  1270. #else /* !USE_SELECT */
  1271. reply_timeout = __resolv_timeout * 1000;
  1272. wait_again:
  1273. fds.fd = fd;
  1274. fds.events = POLLIN;
  1275. if (poll(&fds, 1, reply_timeout) <= 0) {
  1276. DPRINTF("Timeout\n");
  1277. /* timed out, so retry send and receive
  1278. * to next nameserver */
  1279. goto try_next_server;
  1280. }
  1281. if (fds.revents & (POLLERR | POLLHUP | POLLNVAL)) {
  1282. DPRINTF("Bad event\n");
  1283. goto try_next_server;
  1284. }
  1285. /*TODO: better timeout accounting?*/
  1286. reply_timeout -= 1000;
  1287. #endif /* USE_SELECT */
  1288. /* vda: a bogus response seen in real world (caused SEGV in uclibc):
  1289. * "ping www.google.com" sending AAAA query and getting
  1290. * response with one answer... with answer part missing!
  1291. * Fixed by thorough checks for not going past the packet's end.
  1292. */
  1293. #ifdef DEBUG
  1294. {
  1295. 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";
  1296. 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";
  1297. pos = memcmp(packet + 2, test_query + 2, 30);
  1298. packet_len = recv(fd, packet, PACKETSZ, MSG_DONTWAIT);
  1299. if (pos == 0) {
  1300. packet_len = 32;
  1301. memcpy(packet + 2, test_respn + 2, 30);
  1302. }
  1303. }
  1304. #else
  1305. packet_len = recv(fd, packet, PACKETSZ, MSG_DONTWAIT);
  1306. #endif
  1307. if (packet_len < HFIXEDSZ) {
  1308. /* too short!
  1309. * If the peer did shutdown then retry later,
  1310. * try next peer on error.
  1311. * it's just a bogus packet from somewhere */
  1312. bogus_packet:
  1313. if (packet_len >= 0 && reply_timeout)
  1314. goto wait_again;
  1315. goto try_next_server;
  1316. }
  1317. __decode_header(packet, &h);
  1318. DPRINTF("len:%d id:%d qr:%d\n", packet_len, h.id, h.qr);
  1319. if (h.id != local_id || !h.qr) {
  1320. /* unsolicited */
  1321. goto bogus_packet;
  1322. }
  1323. DPRINTF("Got response (i think)!\n");
  1324. DPRINTF("qrcount=%d,ancount=%d,nscount=%d,arcount=%d\n",
  1325. h.qdcount, h.ancount, h.nscount, h.arcount);
  1326. DPRINTF("opcode=%d,aa=%d,tc=%d,rd=%d,ra=%d,rcode=%d\n",
  1327. h.opcode, h.aa, h.tc, h.rd, h.ra, h.rcode);
  1328. /* bug 660 says we treat negative response as an error
  1329. * and retry, which is, eh, an error. :)
  1330. * We were incurring long delays because of this. */
  1331. if (h.rcode == NXDOMAIN || h.rcode == SERVFAIL) {
  1332. /* if possible, try next search domain */
  1333. if (!ends_with_dot) {
  1334. DPRINTF("variant:%d sdomains:%d\n", variant, sdomains);
  1335. if (variant < sdomains - 1) {
  1336. /* next search domain */
  1337. variant++;
  1338. continue;
  1339. }
  1340. /* no more search domains to try */
  1341. }
  1342. if (h.rcode != SERVFAIL) {
  1343. /* dont loop, this is "no such host" situation */
  1344. h_errno = HOST_NOT_FOUND;
  1345. goto fail1;
  1346. }
  1347. }
  1348. /* Insert other non-fatal errors here, which do not warrant
  1349. * switching to next nameserver */
  1350. /* Strange error, assuming this nameserver is feeling bad */
  1351. if (h.rcode != 0)
  1352. goto try_next_server;
  1353. /* Code below won't work correctly with h.ancount == 0, so... */
  1354. if (h.ancount <= 0) {
  1355. h_errno = NO_DATA; /* [is this correct code to check for?] */
  1356. goto fail1;
  1357. }
  1358. pos = HFIXEDSZ;
  1359. for (j = 0; j < h.qdcount; j++) {
  1360. DPRINTF("Skipping question %d at %d\n", j, pos);
  1361. i = __length_question(packet + pos, packet_len - pos);
  1362. if (i < 0) {
  1363. DPRINTF("Packet'question section "
  1364. "is truncated, trying next server\n");
  1365. goto try_next_server;
  1366. }
  1367. pos += i;
  1368. DPRINTF("Length of question %d is %d\n", j, i);
  1369. }
  1370. DPRINTF("Decoding answer at pos %d\n", pos);
  1371. first_answer = 1;
  1372. a->dotted = NULL;
  1373. for (j = 0; j < h.ancount; j++) {
  1374. i = __decode_answer(packet, pos, packet_len, &ma);
  1375. if (i < 0) {
  1376. DPRINTF("failed decode %d\n", i);
  1377. /* If the message was truncated but we have
  1378. * decoded some answers, pretend it's OK */
  1379. if (j && h.tc)
  1380. break;
  1381. goto try_next_server;
  1382. }
  1383. pos += i;
  1384. if (first_answer) {
  1385. ma.buf = a->buf;
  1386. ma.buflen = a->buflen;
  1387. ma.add_count = a->add_count;
  1388. free(a->dotted);
  1389. memcpy(a, &ma, sizeof(ma));
  1390. if (a->atype != T_SIG && (NULL == a->buf || (type != T_A && type != T_AAAA)))
  1391. break;
  1392. if (a->atype != type)
  1393. continue;
  1394. a->add_count = h.ancount - j - 1;
  1395. if ((a->rdlength + sizeof(struct in_addr*)) * a->add_count > a->buflen)
  1396. break;
  1397. a->add_count = 0;
  1398. first_answer = 0;
  1399. } else {
  1400. free(ma.dotted);
  1401. if (ma.atype != type)
  1402. continue;
  1403. if (a->rdlength != ma.rdlength) {
  1404. free(a->dotted);
  1405. DPRINTF("Answer address len(%u) differs from original(%u)\n",
  1406. ma.rdlength, a->rdlength);
  1407. goto try_next_server;
  1408. }
  1409. memcpy(a->buf + (a->add_count * ma.rdlength), ma.rdata, ma.rdlength);
  1410. ++a->add_count;
  1411. }
  1412. }
  1413. /* Success! */
  1414. DPRINTF("Answer name = |%s|\n", a->dotted);
  1415. DPRINTF("Answer type = |%d|\n", a->atype);
  1416. if (fd != -1)
  1417. close(fd);
  1418. if (outpacket)
  1419. *outpacket = packet;
  1420. else
  1421. free(packet);
  1422. free(lookup);
  1423. return packet_len;
  1424. try_next_server:
  1425. /* Try next nameserver */
  1426. retries_left--;
  1427. local_ns_num++;
  1428. variant = -1;
  1429. } while (retries_left > 0);
  1430. fail:
  1431. h_errno = NETDB_INTERNAL;
  1432. fail1:
  1433. if (fd != -1)
  1434. close(fd);
  1435. free(lookup);
  1436. free(packet);
  1437. return -1;
  1438. }
  1439. #endif /* L_dnslookup */
  1440. #ifdef L_read_etc_hosts_r
  1441. parser_t * __open_etc_hosts(void)
  1442. {
  1443. parser_t *parser;
  1444. parser = config_open("/etc/hosts");
  1445. #ifdef FALLBACK_TO_CONFIG_RESOLVCONF
  1446. if (parser == NULL)
  1447. parser = config_open("/etc/config/hosts");
  1448. #endif
  1449. return parser;
  1450. }
  1451. #define MINTOKENS 2 /* ip address + canonical name */
  1452. #define MAXTOKENS (MINTOKENS + MAXALIASES)
  1453. #define HALISTOFF (sizeof(char*) * (MAXTOKENS + 1)) /* reserve space for list terminator */
  1454. #define INADDROFF (HALISTOFF + 2 * sizeof(char*))
  1455. int __read_etc_hosts_r(
  1456. parser_t * parser,
  1457. const char *name,
  1458. int type,
  1459. enum etc_hosts_action action,
  1460. struct hostent *result_buf,
  1461. char *buf, size_t buflen,
  1462. struct hostent **result,
  1463. int *h_errnop)
  1464. {
  1465. char **tok = NULL;
  1466. struct in_addr *h_addr0 = NULL;
  1467. const size_t aliaslen = INADDROFF +
  1468. #ifdef __UCLIBC_HAS_IPV6__
  1469. sizeof(struct in6_addr)
  1470. #else
  1471. sizeof(struct in_addr)
  1472. #endif
  1473. ;
  1474. int ret = HOST_NOT_FOUND;
  1475. /* make sure pointer is aligned */
  1476. int i = ALIGN_BUFFER_OFFSET(buf);
  1477. buf += i;
  1478. buflen -= i;
  1479. *h_errnop = NETDB_INTERNAL;
  1480. if (/* (ssize_t)buflen < 0 || */ buflen < aliaslen
  1481. || (buflen - aliaslen) < BUFSZ + 1)
  1482. return ERANGE;
  1483. if (parser == NULL)
  1484. parser = __open_etc_hosts();
  1485. if (parser == NULL) {
  1486. *result = NULL;
  1487. return errno;
  1488. }
  1489. /* Layout in buf:
  1490. * char *alias[MAXTOKENS] = {address, name, aliases...}
  1491. * char **h_addr_list[1] = {*in[6]_addr, NULL}
  1492. * struct in[6]_addr
  1493. * char line_buffer[BUFSZ+];
  1494. */
  1495. parser->data = buf;
  1496. parser->data_len = aliaslen;
  1497. parser->line_len = buflen - aliaslen;
  1498. *h_errnop = HOST_NOT_FOUND;
  1499. /* <ip>[[:space:]][<aliases>] */
  1500. while (config_read(parser, &tok, MAXTOKENS, MINTOKENS, "# \t", PARSE_NORMAL)) {
  1501. result_buf->h_aliases = tok+1;
  1502. if (action == GETHOSTENT) {
  1503. /* Return whatever the next entry happens to be. */
  1504. ;
  1505. } else if (action == GET_HOSTS_BYADDR) {
  1506. if (strcmp(name, *tok) != 0)
  1507. continue;
  1508. } else { /* GET_HOSTS_BYNAME */
  1509. int aliases = 0;
  1510. char **alias = tok + 1;
  1511. while (aliases < MAXALIASES) {
  1512. char *tmp = *(alias+aliases++);
  1513. if (tmp && strcasecmp(name, tmp) == 0)
  1514. goto found;
  1515. }
  1516. continue;
  1517. }
  1518. found:
  1519. result_buf->h_name = *(result_buf->h_aliases++);
  1520. result_buf->h_addr_list = (char**)(buf + HALISTOFF);
  1521. *(result_buf->h_addr_list + 1) = '\0';
  1522. h_addr0 = (struct in_addr*)(buf + INADDROFF);
  1523. result_buf->h_addr = (char*)h_addr0;
  1524. if (0) /* nothing */;
  1525. #ifdef __UCLIBC_HAS_IPV4__
  1526. else if (type == AF_INET
  1527. && inet_pton(AF_INET, *tok, h_addr0) > 0) {
  1528. DPRINTF("Found INET\n");
  1529. result_buf->h_addrtype = AF_INET;
  1530. result_buf->h_length = sizeof(struct in_addr);
  1531. *result = result_buf;
  1532. ret = NETDB_SUCCESS;
  1533. }
  1534. #endif
  1535. #ifdef __UCLIBC_HAS_IPV6__
  1536. #define in6 ((struct in6_addr *)buf)
  1537. else if (type == AF_INET6
  1538. && inet_pton(AF_INET6, *tok, h_addr0) > 0) {
  1539. DPRINTF("Found INET6\n");
  1540. result_buf->h_addrtype = AF_INET6;
  1541. result_buf->h_length = sizeof(struct in6_addr);
  1542. *result = result_buf;
  1543. ret = NETDB_SUCCESS;
  1544. }
  1545. #endif
  1546. else {
  1547. /* continue parsing in the hope the user has multiple
  1548. * host types listed in the database like so:
  1549. * <ipv4 addr> host
  1550. * <ipv6 addr> host
  1551. * If looking for an IPv6 addr, don't bail when we got the IPv4
  1552. */
  1553. DPRINTF("Error: Found host but different address family\n");
  1554. /* NB: gethostbyname2_r depends on this feature
  1555. * to avoid looking for IPv6 addr of "localhost" etc */
  1556. ret = TRY_AGAIN;
  1557. continue;
  1558. }
  1559. break;
  1560. }
  1561. if (action != GETHOSTENT)
  1562. config_close(parser);
  1563. return ret;
  1564. #undef in6
  1565. }
  1566. #endif /* L_read_etc_hosts_r */
  1567. #ifdef L_get_hosts_byname_r
  1568. int __get_hosts_byname_r(const char *name,
  1569. int type,
  1570. struct hostent *result_buf,
  1571. char *buf,
  1572. size_t buflen,
  1573. struct hostent **result,
  1574. int *h_errnop)
  1575. {
  1576. return __read_etc_hosts_r(NULL, name, type, GET_HOSTS_BYNAME,
  1577. result_buf, buf, buflen, result, h_errnop);
  1578. }
  1579. #endif /* L_get_hosts_byname_r */
  1580. #ifdef L_get_hosts_byaddr_r
  1581. int __get_hosts_byaddr_r(const char *addr,
  1582. int len,
  1583. int type,
  1584. struct hostent *result_buf,
  1585. char *buf,
  1586. size_t buflen,
  1587. struct hostent **result,
  1588. int *h_errnop)
  1589. {
  1590. #ifndef __UCLIBC_HAS_IPV6__
  1591. char ipaddr[INET_ADDRSTRLEN];
  1592. #else
  1593. char ipaddr[INET6_ADDRSTRLEN];
  1594. #endif
  1595. switch (type) {
  1596. #ifdef __UCLIBC_HAS_IPV4__
  1597. case AF_INET:
  1598. if (len != sizeof(struct in_addr))
  1599. return 0;
  1600. break;
  1601. #endif
  1602. #ifdef __UCLIBC_HAS_IPV6__
  1603. case AF_INET6:
  1604. if (len != sizeof(struct in6_addr))
  1605. return 0;
  1606. break;
  1607. #endif
  1608. default:
  1609. return 0;
  1610. }
  1611. inet_ntop(type, addr, ipaddr, sizeof(ipaddr));
  1612. return __read_etc_hosts_r(NULL, ipaddr, type, GET_HOSTS_BYADDR,
  1613. result_buf, buf, buflen, result, h_errnop);
  1614. }
  1615. #endif /* L_get_hosts_byaddr_r */
  1616. #ifdef L_getnameinfo
  1617. int getnameinfo(const struct sockaddr *sa,
  1618. socklen_t addrlen,
  1619. char *host,
  1620. socklen_t hostlen,
  1621. char *serv,
  1622. socklen_t servlen,
  1623. unsigned flags)
  1624. {
  1625. int serrno = errno;
  1626. bool ok = 0;
  1627. struct hostent *hoste = NULL;
  1628. char domain[256];
  1629. if (flags & ~(NI_NUMERICHOST|NI_NUMERICSERV|NI_NOFQDN|NI_NAMEREQD|NI_DGRAM))
  1630. return EAI_BADFLAGS;
  1631. if (sa == NULL || addrlen < sizeof(sa_family_t))
  1632. return EAI_FAMILY;
  1633. if (sa->sa_family == AF_LOCAL) /* valid */;
  1634. #ifdef __UCLIBC_HAS_IPV4__
  1635. else if (sa->sa_family == AF_INET) {
  1636. if (addrlen < sizeof(struct sockaddr_in))
  1637. return EAI_FAMILY;
  1638. }
  1639. #endif
  1640. #ifdef __UCLIBC_HAS_IPV6__
  1641. else if (sa->sa_family == AF_INET6) {
  1642. if (addrlen < sizeof(struct sockaddr_in6))
  1643. return EAI_FAMILY;
  1644. }
  1645. #endif
  1646. else
  1647. return EAI_FAMILY;
  1648. if (host != NULL && hostlen > 0)
  1649. switch (sa->sa_family) {
  1650. case AF_INET:
  1651. #ifdef __UCLIBC_HAS_IPV6__
  1652. case AF_INET6:
  1653. #endif
  1654. if (!(flags & NI_NUMERICHOST)) {
  1655. if (0) /* nothing */;
  1656. #ifdef __UCLIBC_HAS_IPV6__
  1657. else if (sa->sa_family == AF_INET6)
  1658. hoste = gethostbyaddr((const void *)
  1659. &(((const struct sockaddr_in6 *) sa)->sin6_addr),
  1660. sizeof(struct in6_addr), AF_INET6);
  1661. #endif
  1662. #ifdef __UCLIBC_HAS_IPV4__
  1663. else
  1664. hoste = gethostbyaddr((const void *)
  1665. &(((const struct sockaddr_in *)sa)->sin_addr),
  1666. sizeof(struct in_addr), AF_INET);
  1667. #endif
  1668. if (hoste) {
  1669. char *c;
  1670. if ((flags & NI_NOFQDN)
  1671. && (getdomainname(domain, sizeof(domain)) == 0)
  1672. && (c = strstr(hoste->h_name, domain)) != NULL
  1673. && (c != hoste->h_name) && (*(--c) == '.')
  1674. ) {
  1675. strncpy(host, hoste->h_name,
  1676. MIN(hostlen, (size_t) (c - hoste->h_name)));
  1677. host[MIN(hostlen - 1, (size_t) (c - hoste->h_name))] = '\0';
  1678. } else {
  1679. strncpy(host, hoste->h_name, hostlen);
  1680. }
  1681. ok = 1;
  1682. }
  1683. }
  1684. if (!ok) {
  1685. const char *c = NULL;
  1686. if (flags & NI_NAMEREQD) {
  1687. errno = serrno;
  1688. return EAI_NONAME;
  1689. }
  1690. if (0) /* nothing */;
  1691. #ifdef __UCLIBC_HAS_IPV6__
  1692. else if (sa->sa_family == AF_INET6) {
  1693. const struct sockaddr_in6 *sin6p;
  1694. sin6p = (const struct sockaddr_in6 *) sa;
  1695. c = inet_ntop(AF_INET6,
  1696. (const void *) &sin6p->sin6_addr,
  1697. host, hostlen);
  1698. #if 0
  1699. /* Does scope id need to be supported? */
  1700. uint32_t scopeid;
  1701. scopeid = sin6p->sin6_scope_id;
  1702. if (scopeid != 0) {
  1703. /* Buffer is >= IFNAMSIZ+1. */
  1704. char scopebuf[IFNAMSIZ + 1];
  1705. char *scopeptr;
  1706. int ni_numericscope = 0;
  1707. size_t real_hostlen = strnlen(host, hostlen);
  1708. size_t scopelen = 0;
  1709. scopebuf[0] = SCOPE_DELIMITER;
  1710. scopebuf[1] = '\0';
  1711. scopeptr = &scopebuf[1];
  1712. if (IN6_IS_ADDR_LINKLOCAL(&sin6p->sin6_addr)
  1713. || IN6_IS_ADDR_MC_LINKLOCAL(&sin6p->sin6_addr)) {
  1714. if (if_indextoname(scopeid, scopeptr) == NULL)
  1715. ++ni_numericscope;
  1716. else
  1717. scopelen = strlen(scopebuf);
  1718. } else {
  1719. ++ni_numericscope;
  1720. }
  1721. if (ni_numericscope)
  1722. scopelen = 1 + snprintf(scopeptr,
  1723. (scopebuf
  1724. + sizeof scopebuf
  1725. - scopeptr),
  1726. "%u", scopeid);
  1727. if (real_hostlen + scopelen + 1 > hostlen)
  1728. return EAI_SYSTEM;
  1729. memcpy(host + real_hostlen, scopebuf, scopelen + 1);
  1730. }
  1731. #endif
  1732. }
  1733. #endif /* __UCLIBC_HAS_IPV6__ */
  1734. #if defined __UCLIBC_HAS_IPV4__
  1735. else {
  1736. c = inet_ntop(AF_INET, (const void *)
  1737. &(((const struct sockaddr_in *) sa)->sin_addr),
  1738. host, hostlen);
  1739. }
  1740. #endif
  1741. if (c == NULL) {
  1742. errno = serrno;
  1743. return EAI_SYSTEM;
  1744. }
  1745. ok = 1;
  1746. }
  1747. break;
  1748. case AF_LOCAL:
  1749. if (!(flags & NI_NUMERICHOST)) {
  1750. struct utsname utsname;
  1751. if (!uname(&utsname)) {
  1752. strncpy(host, utsname.nodename, hostlen);
  1753. break;
  1754. };
  1755. };
  1756. if (flags & NI_NAMEREQD) {
  1757. errno = serrno;
  1758. return EAI_NONAME;
  1759. }
  1760. strncpy(host, "localhost", hostlen);
  1761. break;
  1762. /* Already checked above
  1763. default:
  1764. return EAI_FAMILY;
  1765. */
  1766. }
  1767. if (serv && (servlen > 0)) {
  1768. if (sa->sa_family == AF_LOCAL) {
  1769. strncpy(serv, ((const struct sockaddr_un *) sa)->sun_path, servlen);
  1770. } else { /* AF_INET || AF_INET6 */
  1771. if (!(flags & NI_NUMERICSERV)) {
  1772. struct servent *s;
  1773. s = getservbyport(((const struct sockaddr_in *) sa)->sin_port,
  1774. ((flags & NI_DGRAM) ? "udp" : "tcp"));
  1775. if (s) {
  1776. strncpy(serv, s->s_name, servlen);
  1777. goto DONE;
  1778. }
  1779. }
  1780. snprintf(serv, servlen, "%d",
  1781. ntohs(((const struct sockaddr_in *) sa)->sin_port));
  1782. }
  1783. }
  1784. DONE:
  1785. if (host && (hostlen > 0))
  1786. host[hostlen-1] = 0;
  1787. if (serv && (servlen > 0))
  1788. serv[servlen-1] = 0;
  1789. errno = serrno;
  1790. return 0;
  1791. }
  1792. libc_hidden_def(getnameinfo)
  1793. #endif /* L_getnameinfo */
  1794. #ifdef L_gethostbyname_r
  1795. /* Bug 671 says:
  1796. * "uClibc resolver's gethostbyname does not return the requested name
  1797. * as an alias, but instead returns the canonical name. glibc's
  1798. * gethostbyname has a similar bug where it returns the requested name
  1799. * with the search domain name appended (to make a FQDN) as an alias,
  1800. * but not the original name itself. Both contradict POSIX, which says
  1801. * that the name argument passed to gethostbyname must be in the alias list"
  1802. * This is fixed now, and we differ from glibc:
  1803. *
  1804. * $ ./gethostbyname_uclibc wer.google.com
  1805. * h_name:'c13-ss-2-lb.cnet.com'
  1806. * h_length:4
  1807. * h_addrtype:2 AF_INET
  1808. * alias:'wer.google.com' <===
  1809. * addr: 0x4174efd8 '216.239.116.65'
  1810. *
  1811. * $ ./gethostbyname_glibc wer.google.com
  1812. * h_name:'c13-ss-2-lb.cnet.com'
  1813. * h_length:4
  1814. * h_addrtype:2 AF_INET
  1815. * alias:'wer.google.com.com' <===
  1816. * addr:'216.239.116.65'
  1817. *
  1818. * When examples were run, /etc/resolv.conf contained "search com" line.
  1819. */
  1820. int gethostbyname_r(const char *name,
  1821. struct hostent *result_buf,
  1822. char *buf,
  1823. size_t buflen,
  1824. struct hostent **result,
  1825. int *h_errnop)
  1826. {
  1827. struct in_addr **addr_list;
  1828. char **alias;
  1829. char *alias0;
  1830. unsigned char *packet;
  1831. struct resolv_answer a;
  1832. int i;
  1833. int packet_len;
  1834. int wrong_af = 0;
  1835. *result = NULL;
  1836. if (!name)
  1837. return EINVAL;
  1838. /* do /etc/hosts first */
  1839. {
  1840. int old_errno = errno; /* save the old errno and reset errno */
  1841. __set_errno(0); /* to check for missing /etc/hosts. */
  1842. i = __get_hosts_byname_r(name, AF_INET, result_buf,
  1843. buf, buflen, result, h_errnop);
  1844. if (i == NETDB_SUCCESS) {
  1845. __set_errno(old_errno);
  1846. return i;
  1847. }
  1848. switch (*h_errnop) {
  1849. case HOST_NOT_FOUND:
  1850. wrong_af = (i == TRY_AGAIN);
  1851. case NO_ADDRESS:
  1852. break;
  1853. case NETDB_INTERNAL:
  1854. if (errno == ENOENT) {
  1855. break;
  1856. }
  1857. /* else fall through */
  1858. default:
  1859. return i;
  1860. }
  1861. __set_errno(old_errno);
  1862. }
  1863. DPRINTF("Nothing found in /etc/hosts\n");
  1864. *h_errnop = NETDB_INTERNAL;
  1865. /* prepare future h_aliases[0] */
  1866. i = strlen(name) + 1;
  1867. if ((ssize_t)buflen <= i)
  1868. return ERANGE;
  1869. memcpy(buf, name, i); /* paranoia: name might change */
  1870. alias0 = buf;
  1871. buf += i;
  1872. buflen -= i;
  1873. /* make sure pointer is aligned */
  1874. i = ALIGN_BUFFER_OFFSET(buf);
  1875. buf += i;
  1876. buflen -= i;
  1877. /* Layout in buf:
  1878. * char *alias[2];
  1879. * struct in_addr* addr_list[NN+1];
  1880. * struct in_addr* in[NN];
  1881. */
  1882. alias = (char **)buf;
  1883. buf += sizeof(alias[0]) * 2;
  1884. buflen -= sizeof(alias[0]) * 2;
  1885. addr_list = (struct in_addr **)buf;
  1886. /* buflen may be < 0, must do signed compare */
  1887. if ((ssize_t)buflen < 256)
  1888. return ERANGE;
  1889. /* we store only one "alias" - the name itself */
  1890. #ifdef __UCLIBC_MJN3_ONLY__
  1891. #warning TODO -- generate the full list
  1892. #endif
  1893. alias[0] = alias0;
  1894. alias[1] = NULL;
  1895. /* maybe it is already an address? */
  1896. {
  1897. struct in_addr *in = (struct in_addr *)(buf + sizeof(addr_list[0]) * 2);
  1898. if (inet_aton(name, in)) {
  1899. addr_list[0] = in;
  1900. addr_list[1] = NULL;
  1901. result_buf->h_name = alias0;
  1902. result_buf->h_aliases = alias;
  1903. result_buf->h_addrtype = AF_INET;
  1904. result_buf->h_length = sizeof(struct in_addr);
  1905. result_buf->h_addr_list = (char **) addr_list;
  1906. *result = result_buf;
  1907. *h_errnop = NETDB_SUCCESS;
  1908. return NETDB_SUCCESS;
  1909. }
  1910. }
  1911. /* what if /etc/hosts has it but it's not IPv4?
  1912. * F.e. "::1 localhost6". We don't do DNS query for such hosts -
  1913. * "ping localhost6" should be fast even if DNS server is down! */
  1914. if (wrong_af) {
  1915. *h_errnop = HOST_NOT_FOUND;
  1916. return TRY_AGAIN;
  1917. }
  1918. /* talk to DNS servers */
  1919. a.buf = buf;
  1920. /* take into account that at least one address will be there,
  1921. * we'll need space for one in_addr + two addr_list[] elems */
  1922. a.buflen = buflen - ((sizeof(addr_list[0]) * 2 + sizeof(struct in_addr)));
  1923. a.add_count = 0;
  1924. packet_len = __dns_lookup(name, T_A, &packet, &a);
  1925. if (packet_len < 0) {
  1926. *h_errnop = HOST_NOT_FOUND;
  1927. DPRINTF("__dns_lookup returned < 0\n");
  1928. return TRY_AGAIN;
  1929. }
  1930. if (a.atype == T_A) { /* ADDRESS */
  1931. /* we need space for addr_list[] and one IPv4 address */
  1932. /* + 1 accounting for 1st addr (it's in a.rdata),
  1933. * another + 1 for NULL in last addr_list[]: */
  1934. int need_bytes = sizeof(addr_list[0]) * (a.add_count + 1 + 1)
  1935. /* for 1st addr (it's in a.rdata): */
  1936. + sizeof(struct in_addr);
  1937. /* how many bytes will 2nd and following addresses take? */
  1938. int ips_len = a.add_count * a.rdlength;
  1939. buflen -= (need_bytes + ips_len);
  1940. if ((ssize_t)buflen < 0) {
  1941. DPRINTF("buffer too small for all addresses\n");
  1942. /* *h_errnop = NETDB_INTERNAL; - already is */
  1943. i = ERANGE;
  1944. goto free_and_ret;
  1945. }
  1946. /* if there are additional addresses in buf,
  1947. * move them forward so that they are not destroyed */
  1948. DPRINTF("a.add_count:%d a.rdlength:%d a.rdata:%p\n", a.add_count, a.rdlength, a.rdata);
  1949. memmove(buf + need_bytes, buf, ips_len);
  1950. /* 1st address is in a.rdata, insert it */
  1951. buf += need_bytes - sizeof(struct in_addr);
  1952. memcpy(buf, a.rdata, sizeof(struct in_addr));
  1953. /* fill addr_list[] */
  1954. for (i = 0; i <= a.add_count; i++) {
  1955. addr_list[i] = (struct in_addr*)buf;
  1956. buf += sizeof(struct in_addr);
  1957. }
  1958. addr_list[i] = NULL;
  1959. /* if we have enough space, we can report "better" name
  1960. * (it may contain search domains attached by __dns_lookup,
  1961. * or CNAME of the host if it is different from the name
  1962. * we used to find it) */
  1963. if (a.dotted && buflen > strlen(a.dotted)) {
  1964. strcpy(buf, a.dotted);
  1965. alias0 = buf;
  1966. }
  1967. result_buf->h_name = alias0;
  1968. result_buf->h_aliases = alias;
  1969. result_buf->h_addrtype = AF_INET;
  1970. result_buf->h_length = sizeof(struct in_addr);
  1971. result_buf->h_addr_list = (char **) addr_list;
  1972. *result = result_buf;
  1973. *h_errnop = NETDB_SUCCESS;
  1974. i = NETDB_SUCCESS;
  1975. goto free_and_ret;
  1976. }
  1977. *h_errnop = HOST_NOT_FOUND;
  1978. __set_h_errno(HOST_NOT_FOUND);
  1979. i = TRY_AGAIN;
  1980. free_and_ret:
  1981. free(a.dotted);
  1982. free(packet);
  1983. return i;
  1984. }
  1985. libc_hidden_def(gethostbyname_r)
  1986. #endif /* L_gethostbyname_r */
  1987. #ifdef L_gethostbyname2_r
  1988. int gethostbyname2_r(const char *name,
  1989. int family,
  1990. struct hostent *result_buf,
  1991. char *buf,
  1992. size_t buflen,
  1993. struct hostent **result,
  1994. int *h_errnop)
  1995. {
  1996. #ifndef __UCLIBC_HAS_IPV6__
  1997. return family == (AF_INET)
  1998. ? gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop)
  1999. : HOST_NOT_FOUND;
  2000. #else
  2001. struct in6_addr **addr_list;
  2002. char **alias;
  2003. char *alias0;
  2004. unsigned char *packet;
  2005. struct resolv_answer a;
  2006. int i;
  2007. int packet_len;
  2008. int wrong_af = 0;
  2009. if (family == AF_INET)
  2010. return gethostbyname_r(name, result_buf, buf, buflen, result, h_errnop);
  2011. *result = NULL;
  2012. if (family != AF_INET6)
  2013. return EINVAL;
  2014. if (!name)
  2015. return EINVAL;
  2016. /* do /etc/hosts first */
  2017. {
  2018. int old_errno = errno; /* save the old errno and reset errno */
  2019. __set_errno(0); /* to check for missing /etc/hosts. */
  2020. i = __get_hosts_byname_r(name, AF_INET6 /*family*/, result_buf,
  2021. buf, buflen, result, h_errnop);
  2022. if (i == NETDB_SUCCESS) {
  2023. __set_errno(old_errno);
  2024. return i;
  2025. }
  2026. switch (*h_errnop) {
  2027. case HOST_NOT_FOUND:
  2028. wrong_af = (i == TRY_AGAIN);
  2029. case NO_ADDRESS:
  2030. break;
  2031. case NETDB_INTERNAL:
  2032. if (errno == ENOENT) {
  2033. break;
  2034. }
  2035. /* else fall through */
  2036. default:
  2037. return i;
  2038. }
  2039. __set_errno(old_errno);
  2040. }
  2041. DPRINTF("Nothing found in /etc/hosts\n");
  2042. *h_errnop = NETDB_INTERNAL;
  2043. /* prepare future h_aliases[0] */
  2044. i = strlen(name) + 1;
  2045. if ((ssize_t)buflen <= i)
  2046. return ERANGE;
  2047. memcpy(buf, name, i); /* paranoia: name might change */
  2048. alias0 = buf;
  2049. buf += i;
  2050. buflen -= i;
  2051. /* make sure pointer is aligned */
  2052. i = ALIGN_BUFFER_OFFSET(buf);
  2053. buf += i;
  2054. buflen -= i;
  2055. /* Layout in buf:
  2056. * char *alias[2];
  2057. * struct in6_addr* addr_list[NN+1];
  2058. * struct in6_addr* in[NN];
  2059. */
  2060. alias = (char **)buf;
  2061. buf += sizeof(alias[0]) * 2;
  2062. buflen -= sizeof(alias[0]) * 2;
  2063. addr_list = (struct in6_addr **)buf;
  2064. /* buflen may be < 0, must do signed compare */
  2065. if ((ssize_t)buflen < 256)
  2066. return ERANGE;
  2067. /* we store only one "alias" - the name itself */
  2068. #ifdef __UCLIBC_MJN3_ONLY__
  2069. #warning TODO -- generate the full list
  2070. #endif
  2071. alias[0] = alias0;
  2072. alias[1] = NULL;
  2073. /* maybe it is already an address? */
  2074. {
  2075. struct in6_addr *in = (struct in6_addr *)(buf + sizeof(addr_list[0]) * 2);
  2076. if (inet_pton(AF_INET6, name, in)) {
  2077. addr_list[0] = in;
  2078. addr_list[1] = NULL;
  2079. result_buf->h_name = alias0;
  2080. result_buf->h_aliases = alias;
  2081. result_buf->h_addrtype = AF_INET6;
  2082. result_buf->h_length = sizeof(struct in6_addr);
  2083. result_buf->h_addr_list = (char **) addr_list;
  2084. *result = result_buf;
  2085. *h_errnop = NETDB_SUCCESS;
  2086. return NETDB_SUCCESS;
  2087. }
  2088. }
  2089. /* what if /etc/hosts has it but it's not IPv6?
  2090. * F.e. "127.0.0.1 localhost". We don't do DNS query for such hosts -
  2091. * "ping localhost" should be fast even if DNS server is down! */
  2092. if (wrong_af) {
  2093. *h_errnop = HOST_NOT_FOUND;
  2094. return TRY_AGAIN;
  2095. }
  2096. /* talk to DNS servers */
  2097. a.buf = buf;
  2098. /* take into account that at least one address will be there,
  2099. * we'll need space of one in6_addr + two addr_list[] elems */
  2100. a.buflen = buflen - ((sizeof(addr_list[0]) * 2 + sizeof(struct in6_addr)));
  2101. a.add_count = 0;
  2102. packet_len = __dns_lookup(name, T_AAAA, &packet, &a);
  2103. if (packet_len < 0) {
  2104. *h_errnop = HOST_NOT_FOUND;
  2105. DPRINTF("__dns_lookup returned < 0\n");
  2106. return TRY_AGAIN;
  2107. }
  2108. if (a.atype == T_AAAA) { /* ADDRESS */
  2109. /* we need space for addr_list[] and one IPv6 address */
  2110. /* + 1 accounting for 1st addr (it's in a.rdata),
  2111. * another + 1 for NULL in last addr_list[]: */
  2112. int need_bytes = sizeof(addr_list[0]) * (a.add_count + 1 + 1)
  2113. /* for 1st addr (it's in a.rdata): */
  2114. + sizeof(struct in6_addr);
  2115. /* how many bytes will 2nd and following addresses take? */
  2116. int ips_len = a.add_count * a.rdlength;
  2117. buflen -= (need_bytes + ips_len);
  2118. if ((ssize_t)buflen < 0) {
  2119. DPRINTF("buffer too small for all addresses\n");
  2120. /* *h_errnop = NETDB_INTERNAL; - already is */
  2121. i = ERANGE;
  2122. goto free_and_ret;
  2123. }
  2124. /* if there are additional addresses in buf,
  2125. * move them forward so that they are not destroyed */
  2126. DPRINTF("a.add_count:%d a.rdlength:%d a.rdata:%p\n", a.add_count, a.rdlength, a.rdata);
  2127. memmove(buf + need_bytes, buf, ips_len);
  2128. /* 1st address is in a.rdata, insert it */
  2129. buf += need_bytes - sizeof(struct in6_addr);
  2130. memcpy(buf, a.rdata, sizeof(struct in6_addr));
  2131. /* fill addr_list[] */
  2132. for (i = 0; i <= a.add_count; i++) {
  2133. addr_list[i] = (struct in6_addr*)buf;
  2134. buf += sizeof(struct in6_addr);
  2135. }
  2136. addr_list[i] = NULL;
  2137. /* if we have enough space, we can report "better" name
  2138. * (it may contain search domains attached by __dns_lookup,
  2139. * or CNAME of the host if it is different from the name
  2140. * we used to find it) */
  2141. if (a.dotted && buflen > strlen(a.dotted)) {
  2142. strcpy(buf, a.dotted);
  2143. alias0 = buf;
  2144. }
  2145. result_buf->h_name = alias0;
  2146. result_buf->h_aliases = alias;
  2147. result_buf->h_addrtype = AF_INET6;
  2148. result_buf->h_length = sizeof(struct in6_addr);
  2149. result_buf->h_addr_list = (char **) addr_list;
  2150. *result = result_buf;
  2151. *h_errnop = NETDB_SUCCESS;
  2152. i = NETDB_SUCCESS;
  2153. goto free_and_ret;
  2154. }
  2155. *h_errnop = HOST_NOT_FOUND;
  2156. __set_h_errno(HOST_NOT_FOUND);
  2157. i = TRY_AGAIN;
  2158. free_and_ret:
  2159. free(a.dotted);
  2160. free(packet);
  2161. return i;
  2162. #endif /* __UCLIBC_HAS_IPV6__ */
  2163. }
  2164. libc_hidden_def(gethostbyname2_r)
  2165. #endif /* L_gethostbyname2_r */
  2166. #ifdef L_gethostbyaddr_r
  2167. int gethostbyaddr_r(const void *addr, socklen_t addrlen,
  2168. int type,
  2169. struct hostent *result_buf,
  2170. char *buf, size_t buflen,
  2171. struct hostent **result,
  2172. int *h_errnop)
  2173. {
  2174. struct in_addr *in;
  2175. struct in_addr **addr_list;
  2176. char **alias;
  2177. unsigned char *packet;
  2178. struct resolv_answer a;
  2179. int i;
  2180. int packet_len;
  2181. int nest = 0;
  2182. *result = NULL;
  2183. if (!addr)
  2184. return EINVAL;
  2185. switch (type) {
  2186. #ifdef __UCLIBC_HAS_IPV4__
  2187. case AF_INET:
  2188. if (addrlen != sizeof(struct in_addr))
  2189. return EINVAL;
  2190. break;
  2191. #endif
  2192. #ifdef __UCLIBC_HAS_IPV6__
  2193. case AF_INET6:
  2194. if (addrlen != sizeof(struct in6_addr))
  2195. return EINVAL;
  2196. break;
  2197. #endif
  2198. default:
  2199. return EINVAL;
  2200. }
  2201. /* do /etc/hosts first */
  2202. i = __get_hosts_byaddr_r(addr, addrlen, type, result_buf,
  2203. buf, buflen, result, h_errnop);
  2204. if (i == 0)
  2205. return i;
  2206. switch (*h_errnop) {
  2207. case HOST_NOT_FOUND:
  2208. case NO_ADDRESS:
  2209. break;
  2210. default:
  2211. return i;
  2212. }
  2213. *h_errnop = NETDB_INTERNAL;
  2214. /* make sure pointer is aligned */
  2215. i = ALIGN_BUFFER_OFFSET(buf);
  2216. buf += i;
  2217. buflen -= i;
  2218. /* Layout in buf:
  2219. * char *alias[ALIAS_DIM];
  2220. * struct in[6]_addr* addr_list[2];
  2221. * struct in[6]_addr in;
  2222. * char scratch_buffer[256+];
  2223. */
  2224. #define in6 ((struct in6_addr *)in)
  2225. alias = (char **)buf;
  2226. addr_list = (struct in_addr**)buf;
  2227. buf += sizeof(*addr_list) * 2;
  2228. buflen -= sizeof(*addr_list) * 2;
  2229. in = (struct in_addr*)buf;
  2230. #ifndef __UCLIBC_HAS_IPV6__
  2231. buf += sizeof(*in);
  2232. buflen -= sizeof(*in);
  2233. if (addrlen > sizeof(*in))
  2234. return ERANGE;
  2235. #else
  2236. buf += sizeof(*in6);
  2237. buflen -= sizeof(*in6);
  2238. if (addrlen > sizeof(*in6))
  2239. return ERANGE;
  2240. #endif
  2241. if ((ssize_t)buflen < 256)
  2242. return ERANGE;
  2243. alias[0] = buf;
  2244. alias[1] = NULL;
  2245. addr_list[0] = in;
  2246. addr_list[1] = NULL;
  2247. memcpy(in, addr, addrlen);
  2248. if (0) /* nothing */;
  2249. #ifdef __UCLIBC_HAS_IPV4__
  2250. else IF_HAS_BOTH(if (type == AF_INET)) {
  2251. unsigned char *tp = (unsigned char *)addr;
  2252. sprintf(buf, "%u.%u.%u.%u.in-addr.arpa",
  2253. tp[3], tp[2], tp[1], tp[0]);
  2254. }
  2255. #endif
  2256. #ifdef __UCLIBC_HAS_IPV6__
  2257. else {
  2258. char *dst = buf;
  2259. unsigned char *tp = (unsigned char *)addr + addrlen - 1;
  2260. do {
  2261. dst += sprintf(dst, "%x.%x.", tp[0] & 0xf, tp[0] >> 4);
  2262. tp--;
  2263. } while (tp >= (unsigned char *)addr);
  2264. strcpy(dst, "ip6.arpa");
  2265. }
  2266. #endif
  2267. memset(&a, '\0', sizeof(a));
  2268. for (;;) {
  2269. /* Hmm why we memset(a) to zeros only once? */
  2270. packet_len = __dns_lookup(buf, T_PTR, &packet, &a);
  2271. if (packet_len < 0) {
  2272. *h_errnop = HOST_NOT_FOUND;
  2273. return TRY_AGAIN;
  2274. }
  2275. strncpy(buf, a.dotted, buflen);
  2276. free(a.dotted);
  2277. if (a.atype != T_CNAME)
  2278. break;
  2279. DPRINTF("Got a CNAME in gethostbyaddr()\n");
  2280. if (++nest > MAX_RECURSE) {
  2281. *h_errnop = NO_RECOVERY;
  2282. return -1;
  2283. }
  2284. /* Decode CNAME into buf, feed it to __dns_lookup() again */
  2285. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2286. free(packet);
  2287. if (i < 0) {
  2288. *h_errnop = NO_RECOVERY;
  2289. return -1;
  2290. }
  2291. }
  2292. if (a.atype == T_PTR) { /* ADDRESS */
  2293. i = __decode_dotted(packet, a.rdoffset, packet_len, buf, buflen);
  2294. free(packet);
  2295. result_buf->h_name = buf;
  2296. result_buf->h_addrtype = type;
  2297. result_buf->h_length = addrlen;
  2298. result_buf->h_addr_list = (char **) addr_list;
  2299. result_buf->h_aliases = alias;
  2300. *result = result_buf;
  2301. *h_errnop = NETDB_SUCCESS;
  2302. return NETDB_SUCCESS;
  2303. }
  2304. free(packet);
  2305. *h_errnop = NO_ADDRESS;
  2306. return TRY_AGAIN;
  2307. #undef in6
  2308. }
  2309. libc_hidden_def(gethostbyaddr_r)
  2310. #endif /* L_gethostbyaddr_r */
  2311. #ifdef L_gethostent_r
  2312. __UCLIBC_MUTEX_STATIC(mylock, PTHREAD_MUTEX_INITIALIZER);
  2313. static parser_t *hostp = NULL;
  2314. static smallint host_stayopen;
  2315. void endhostent_unlocked(void)
  2316. {
  2317. if (hostp) {
  2318. config_close(hostp);
  2319. hostp = NULL;
  2320. }
  2321. host_stayopen = 0;
  2322. }
  2323. void endhostent(void)
  2324. {
  2325. __UCLIBC_MUTEX_LOCK(mylock);
  2326. endhostent_unlocked();
  2327. __UCLIBC_MUTEX_UNLOCK(mylock);
  2328. }
  2329. void sethostent(int stay_open)
  2330. {
  2331. __UCLIBC_MUTEX_LOCK(mylock);
  2332. if (stay_open)
  2333. host_stayopen = 1;
  2334. __UCLIBC_MUTEX_UNLOCK(mylock);
  2335. }
  2336. int gethostent_r(struct hostent *result_buf, char *buf, size_t buflen,
  2337. struct hostent **result, int *h_errnop)
  2338. {
  2339. int ret;
  2340. __UCLIBC_MUTEX_LOCK(mylock);
  2341. if (hostp == NULL) {
  2342. hostp = __open_etc_hosts();
  2343. if (hostp == NULL) {
  2344. *result = NULL;
  2345. ret = TRY_AGAIN;
  2346. goto DONE;
  2347. }
  2348. }
  2349. ret = __read_etc_hosts_r(hostp, NULL, AF_INET, GETHOSTENT,
  2350. result_buf, buf, buflen, result, h_errnop);
  2351. if (!host_stayopen)
  2352. endhostent_unlocked();
  2353. DONE:
  2354. __UCLIBC_MUTEX_UNLOCK(mylock);
  2355. return ret;
  2356. }
  2357. libc_hidden_def(gethostent_r)
  2358. #endif /* L_gethostent_r */
  2359. #ifndef __UCLIBC_HAS_IPV6__
  2360. #define GETXX_BUFSZ (sizeof(struct in_addr) + sizeof(struct in_addr *) * 2 + \
  2361. /*sizeof(char *)*ALIAS_DIM */+ 384/*namebuffer*/ + 32/* margin */)
  2362. #else
  2363. #define GETXX_BUFSZ (sizeof(struct in6_addr) + sizeof(struct in6_addr *) * 2 + \
  2364. /*sizeof(char *)*ALIAS_DIM */+ 384/*namebuffer*/ + 32/* margin */)
  2365. #endif /* __UCLIBC_HAS_IPV6__ */
  2366. #define __INIT_GETXX_BUF(sz) \
  2367. if (buf == NULL) \
  2368. buf = (char *)__uc_malloc((sz));
  2369. #ifdef L_gethostent
  2370. struct hostent *gethostent(void)
  2371. {
  2372. static struct hostent hoste;
  2373. static char *buf = NULL;
  2374. struct hostent *host = NULL;
  2375. #ifndef __UCLIBC_HAS_IPV6__
  2376. #define HOSTENT_BUFSZ (sizeof(struct in_addr) + sizeof(struct in_addr *) * 2 + \
  2377. sizeof(char *)*ALIAS_DIM + BUFSZ /*namebuffer*/ + 2 /* margin */)
  2378. #else
  2379. #define HOSTENT_BUFSZ (sizeof(struct in6_addr) + sizeof(struct in6_addr *) * 2 + \
  2380. sizeof(char *)*ALIAS_DIM + BUFSZ /*namebuffer*/ + 2 /* margin */)
  2381. #endif /* __UCLIBC_HAS_IPV6__ */
  2382. __INIT_GETXX_BUF(HOSTENT_BUFSZ);
  2383. gethostent_r(&hoste, buf, HOSTENT_BUFSZ, &host, &h_errno);
  2384. return host;
  2385. }
  2386. #undef HOSTENT_BUFSZ
  2387. #endif /* L_gethostent */
  2388. #ifdef L_gethostbyname2
  2389. struct hostent *gethostbyname2(const char *name, int family)
  2390. {
  2391. static struct hostent hoste;
  2392. static char *buf = NULL;
  2393. struct hostent *hp;
  2394. __INIT_GETXX_BUF(GETXX_BUFSZ);
  2395. #ifndef __UCLIBC_HAS_IPV6__
  2396. if (family != AF_INET)
  2397. return (struct hostent*)NULL;
  2398. gethostbyname_r(name, &hoste, buf, GETXX_BUFSZ, &hp, &h_errno);
  2399. #else
  2400. gethostbyname2_r(name, family, &hoste, buf, GETXX_BUFSZ, &hp, &h_errno);
  2401. #endif /* __UCLIBC_HAS_IPV6__ */
  2402. return hp;
  2403. }
  2404. libc_hidden_def(gethostbyname2)
  2405. #endif /* L_gethostbyname2 */
  2406. #ifdef L_gethostbyname
  2407. struct hostent *gethostbyname(const char *name)
  2408. {
  2409. return gethostbyname2(name, AF_INET);
  2410. }
  2411. libc_hidden_def(gethostbyname)
  2412. #endif /* L_gethostbyname */
  2413. #ifdef L_gethostbyaddr
  2414. struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type)
  2415. {
  2416. static struct hostent hoste;
  2417. static char *buf = NULL;
  2418. struct hostent *hp;
  2419. __INIT_GETXX_BUF(GETXX_BUFSZ);
  2420. gethostbyaddr_r(addr, len, type, &hoste, buf, GETXX_BUFSZ, &hp, &h_errno);
  2421. return hp;
  2422. }
  2423. libc_hidden_def(gethostbyaddr)
  2424. #endif /* L_gethostbyaddr */
  2425. #ifdef L_res_comp
  2426. /*
  2427. * Expand compressed domain name 'comp_dn' to full domain name.
  2428. * 'msg' is a pointer to the begining of the message,
  2429. * 'eomorig' points to the first location after the message,
  2430. * 'exp_dn' is a pointer to a buffer of size 'length' for the result.
  2431. * Return size of compressed name or -1 if there was an error.
  2432. */
  2433. int dn_expand(const u_char *msg, const u_char *eom, const u_char *src,
  2434. char *dst, int dstsiz)
  2435. {
  2436. int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz);
  2437. if (n > 0 && dst[0] == '.')
  2438. dst[0] = '\0';
  2439. return n;
  2440. }
  2441. libc_hidden_def(dn_expand)
  2442. /*
  2443. * Pack domain name 'exp_dn' in presentation form into 'comp_dn'.
  2444. * Return the size of the compressed name or -1.
  2445. * 'length' is the size of the array pointed to by 'comp_dn'.
  2446. */
  2447. int
  2448. dn_comp(const char *src, u_char *dst, int dstsiz,
  2449. u_char **dnptrs, u_char **lastdnptr)
  2450. {
  2451. return ns_name_compress(src, dst, (size_t) dstsiz,
  2452. (const u_char **) dnptrs,
  2453. (const u_char **) lastdnptr);
  2454. }
  2455. libc_hidden_def(dn_comp)
  2456. #endif /* L_res_comp */
  2457. #ifdef L_ns_name
  2458. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2459. * is this character visible and not a space when printed ?
  2460. */
  2461. static int printable(int ch)
  2462. {
  2463. return (ch > 0x20 && ch < 0x7f);
  2464. }
  2465. /* Thinking in noninternationalized USASCII (per the DNS spec),
  2466. * is this characted special ("in need of quoting") ?
  2467. */
  2468. static int special(int ch)
  2469. {
  2470. switch (ch) {
  2471. case 0x22: /* '"' */
  2472. case 0x2E: /* '.' */
  2473. case 0x3B: /* ';' */
  2474. case 0x5C: /* '\\' */
  2475. /* Special modifiers in zone files. */
  2476. case 0x40: /* '@' */
  2477. case 0x24: /* '$' */
  2478. return 1;
  2479. default:
  2480. return 0;
  2481. }
  2482. }
  2483. /*
  2484. * ns_name_uncompress(msg, eom, src, dst, dstsiz)
  2485. * Expand compressed domain name to presentation format.
  2486. * return:
  2487. * Number of bytes read out of `src', or -1 (with errno set).
  2488. * note:
  2489. * Root domain returns as "." not "".
  2490. */
  2491. int ns_name_uncompress(const u_char *msg, const u_char *eom,
  2492. const u_char *src, char *dst, size_t dstsiz)
  2493. {
  2494. u_char tmp[NS_MAXCDNAME];
  2495. int n;
  2496. n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp);
  2497. if (n == -1)
  2498. return -1;
  2499. if (ns_name_ntop(tmp, dst, dstsiz) == -1)
  2500. return -1;
  2501. return n;
  2502. }
  2503. libc_hidden_def(ns_name_uncompress)
  2504. /*
  2505. * ns_name_ntop(src, dst, dstsiz)
  2506. * Convert an encoded domain name to printable ascii as per RFC1035.
  2507. * return:
  2508. * Number of bytes written to buffer, or -1 (with errno set)
  2509. * notes:
  2510. * The root is returned as "."
  2511. * All other domains are returned in non absolute form
  2512. */
  2513. int ns_name_ntop(const u_char *src, char *dst, size_t dstsiz)
  2514. {
  2515. const u_char *cp;
  2516. char *dn, *eom;
  2517. u_char c;
  2518. u_int n;
  2519. cp = src;
  2520. dn = dst;
  2521. eom = dst + dstsiz;
  2522. while ((n = *cp++) != 0) {
  2523. if ((n & NS_CMPRSFLGS) != 0) {
  2524. /* Some kind of compression pointer. */
  2525. __set_errno(EMSGSIZE);
  2526. return -1;
  2527. }
  2528. if (dn != dst) {
  2529. if (dn >= eom) {
  2530. __set_errno(EMSGSIZE);
  2531. return -1;
  2532. }
  2533. *dn++ = '.';
  2534. }
  2535. if (dn + n >= eom) {
  2536. __set_errno(EMSGSIZE);
  2537. return -1;
  2538. }
  2539. for (; n > 0; n--) {
  2540. c = *cp++;
  2541. if (special(c)) {
  2542. if (dn + 1 >= eom) {
  2543. __set_errno(EMSGSIZE);
  2544. return -1;
  2545. }
  2546. *dn++ = '\\';
  2547. *dn++ = (char)c;
  2548. } else if (!printable(c)) {
  2549. if (dn + 3 >= eom) {
  2550. __set_errno(EMSGSIZE);
  2551. return -1;
  2552. }
  2553. *dn++ = '\\';
  2554. *dn++ = "0123456789"[c / 100];
  2555. c = c % 100;
  2556. *dn++ = "0123456789"[c / 10];
  2557. *dn++ = "0123456789"[c % 10];
  2558. } else {
  2559. if (dn >= eom) {
  2560. __set_errno(EMSGSIZE);
  2561. return -1;
  2562. }
  2563. *dn++ = (char)c;
  2564. }
  2565. }
  2566. }
  2567. if (dn == dst) {
  2568. if (dn >= eom) {
  2569. __set_errno(EMSGSIZE);
  2570. return -1;
  2571. }
  2572. *dn++ = '.';
  2573. }
  2574. if (dn >= eom) {
  2575. __set_errno(EMSGSIZE);
  2576. return -1;
  2577. }
  2578. *dn++ = '\0';
  2579. return (dn - dst);
  2580. }
  2581. libc_hidden_def(ns_name_ntop)
  2582. static int encode_bitstring(const char **bp, const char *end,
  2583. unsigned char **labelp,
  2584. unsigned char ** dst,
  2585. unsigned const char *eom)
  2586. {
  2587. int afterslash = 0;
  2588. const char *cp = *bp;
  2589. unsigned char *tp;
  2590. const char *beg_blen;
  2591. int value = 0, count = 0, tbcount = 0, blen = 0;
  2592. beg_blen = NULL;
  2593. /* a bitstring must contain at least 2 characters */
  2594. if (end - cp < 2)
  2595. return EINVAL;
  2596. /* XXX: currently, only hex strings are supported */
  2597. if (*cp++ != 'x')
  2598. return EINVAL;
  2599. if (!isxdigit((unsigned char) *cp)) /*%< reject '\[x/BLEN]' */
  2600. return EINVAL;
  2601. for (tp = *dst + 1; cp < end && tp < eom; cp++) {
  2602. unsigned char c = *cp;
  2603. switch (c) {
  2604. case ']': /*%< end of the bitstring */
  2605. if (afterslash) {
  2606. char *end_blen;
  2607. if (beg_blen == NULL)
  2608. return EINVAL;
  2609. blen = (int)strtol(beg_blen, &end_blen, 10);
  2610. if (*end_blen != ']')
  2611. return EINVAL;
  2612. }
  2613. if (count)
  2614. *tp++ = ((value << 4) & 0xff);
  2615. cp++; /*%< skip ']' */
  2616. goto done;
  2617. case '/':
  2618. afterslash = 1;
  2619. break;
  2620. default:
  2621. if (afterslash) {
  2622. if (!__isdigit_char(c))
  2623. return EINVAL;
  2624. if (beg_blen == NULL) {
  2625. if (c == '0') {
  2626. /* blen never begings with 0 */
  2627. return EINVAL;
  2628. }
  2629. beg_blen = cp;
  2630. }
  2631. } else {
  2632. if (!__isdigit_char(c)) {
  2633. c = c | 0x20; /* lowercase */
  2634. c = c - 'a';
  2635. if (c > 5) /* not a-f? */
  2636. return EINVAL;
  2637. c += 10 + '0';
  2638. }
  2639. value <<= 4;
  2640. value += (c - '0');
  2641. count += 4;
  2642. tbcount += 4;
  2643. if (tbcount > 256)
  2644. return EINVAL;
  2645. if (count == 8) {
  2646. *tp++ = value;
  2647. count = 0;
  2648. }
  2649. }
  2650. break;
  2651. }
  2652. }
  2653. done:
  2654. if (cp >= end || tp >= eom)
  2655. return EMSGSIZE;
  2656. /*
  2657. * bit length validation:
  2658. * If a <length> is present, the number of digits in the <bit-data>
  2659. * MUST be just sufficient to contain the number of bits specified
  2660. * by the <length>. If there are insignificant bits in a final
  2661. * hexadecimal or octal digit, they MUST be zero.
  2662. * RFC2673, Section 3.2.
  2663. */
  2664. if (blen > 0) {
  2665. int traillen;
  2666. if (((blen + 3) & ~3) != tbcount)
  2667. return EINVAL;
  2668. traillen = tbcount - blen; /*%< between 0 and 3 */
  2669. if (((value << (8 - traillen)) & 0xff) != 0)
  2670. return EINVAL;
  2671. }
  2672. else
  2673. blen = tbcount;
  2674. if (blen == 256)
  2675. blen = 0;
  2676. /* encode the type and the significant bit fields */
  2677. **labelp = DNS_LABELTYPE_BITSTRING;
  2678. **dst = blen;
  2679. *bp = cp;
  2680. *dst = tp;
  2681. return 0;
  2682. }
  2683. int ns_name_pton(const char *src, u_char *dst, size_t dstsiz)
  2684. {
  2685. static const char digits[] = "0123456789";
  2686. u_char *label, *bp, *eom;
  2687. int c, n, escaped, e = 0;
  2688. char *cp;
  2689. escaped = 0;
  2690. bp = dst;
  2691. eom = dst + dstsiz;
  2692. label = bp++;
  2693. while ((c = *src++) != 0) {
  2694. if (escaped) {
  2695. if (c == '[') { /*%< start a bit string label */
  2696. cp = strchr(src, ']');
  2697. if (cp == NULL) {
  2698. errno = EINVAL; /*%< ??? */
  2699. return -1;
  2700. }
  2701. e = encode_bitstring(&src, cp + 2,
  2702. &label, &bp, eom);
  2703. if (e != 0) {
  2704. errno = e;
  2705. return -1;
  2706. }
  2707. escaped = 0;
  2708. label = bp++;
  2709. c = *src++;
  2710. if (c == '\0')
  2711. goto done;
  2712. if (c != '.') {
  2713. errno = EINVAL;
  2714. return -1;
  2715. }
  2716. continue;
  2717. }
  2718. cp = strchr(digits, c);
  2719. if (cp != NULL) {
  2720. n = (cp - digits) * 100;
  2721. c = *src++;
  2722. if (c == '\0')
  2723. goto ret_EMSGSIZE;
  2724. cp = strchr(digits, c);
  2725. if (cp == NULL)
  2726. goto ret_EMSGSIZE;
  2727. n += (cp - digits) * 10;
  2728. c = *src++;
  2729. if (c == '\0')
  2730. goto ret_EMSGSIZE;
  2731. cp = strchr(digits, c);
  2732. if (cp == NULL)
  2733. goto ret_EMSGSIZE;
  2734. n += (cp - digits);
  2735. if (n > 255)
  2736. goto ret_EMSGSIZE;
  2737. c = n;
  2738. }
  2739. escaped = 0;
  2740. } else if (c == '\\') {
  2741. escaped = 1;
  2742. continue;
  2743. } else if (c == '.') {
  2744. c = (bp - label - 1);
  2745. if ((c & NS_CMPRSFLGS) != 0) { /*%< Label too big. */
  2746. goto ret_EMSGSIZE;
  2747. }
  2748. if (label >= eom) {
  2749. goto ret_EMSGSIZE;
  2750. }
  2751. *label = c;
  2752. /* Fully qualified ? */
  2753. if (*src == '\0') {
  2754. if (c != 0) {
  2755. if (bp >= eom) {
  2756. goto ret_EMSGSIZE;
  2757. }
  2758. *bp++ = '\0';
  2759. }
  2760. if ((bp - dst) > MAXCDNAME) {
  2761. goto ret_EMSGSIZE;
  2762. }
  2763. return 1;
  2764. }
  2765. if (c == 0 || *src == '.') {
  2766. goto ret_EMSGSIZE;
  2767. }
  2768. label = bp++;
  2769. continue;
  2770. }
  2771. if (bp >= eom) {
  2772. goto ret_EMSGSIZE;
  2773. }
  2774. *bp++ = (u_char)c;
  2775. }
  2776. c = (bp - label - 1);
  2777. if ((c & NS_CMPRSFLGS) != 0) { /*%< Label too big. */
  2778. goto ret_EMSGSIZE;
  2779. }
  2780. done:
  2781. if (label >= eom) {
  2782. goto ret_EMSGSIZE;
  2783. }
  2784. *label = c;
  2785. if (c != 0) {
  2786. if (bp >= eom) {
  2787. goto ret_EMSGSIZE;
  2788. }
  2789. *bp++ = 0;
  2790. }
  2791. if ((bp - dst) > MAXCDNAME) { /*%< src too big */
  2792. goto ret_EMSGSIZE;
  2793. }
  2794. return 0;
  2795. ret_EMSGSIZE:
  2796. errno = EMSGSIZE;
  2797. return -1;
  2798. }
  2799. libc_hidden_def(ns_name_pton)
  2800. /*
  2801. * ns_name_unpack(msg, eom, src, dst, dstsiz)
  2802. * Unpack a domain name from a message, source may be compressed.
  2803. * return:
  2804. * -1 if it fails, or consumed octets if it succeeds.
  2805. */
  2806. int ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src,
  2807. u_char *dst, size_t dstsiz)
  2808. {
  2809. const u_char *srcp, *dstlim;
  2810. u_char *dstp;
  2811. int n, len, checked;
  2812. len = -1;
  2813. checked = 0;
  2814. dstp = dst;
  2815. srcp = src;
  2816. dstlim = dst + dstsiz;
  2817. if (srcp < msg || srcp >= eom) {
  2818. __set_errno(EMSGSIZE);
  2819. return -1;
  2820. }
  2821. /* Fetch next label in domain name. */
  2822. while ((n = *srcp++) != 0) {
  2823. /* Check for indirection. */
  2824. switch (n & NS_CMPRSFLGS) {
  2825. case 0:
  2826. /* Limit checks. */
  2827. if (dstp + n + 1 >= dstlim || srcp + n >= eom) {
  2828. __set_errno(EMSGSIZE);
  2829. return -1;
  2830. }
  2831. checked += n + 1;
  2832. *dstp++ = n;
  2833. memcpy(dstp, srcp, n);
  2834. dstp += n;
  2835. srcp += n;
  2836. break;
  2837. case NS_CMPRSFLGS:
  2838. if (srcp >= eom) {
  2839. __set_errno(EMSGSIZE);
  2840. return -1;
  2841. }
  2842. if (len < 0)
  2843. len = srcp - src + 1;
  2844. srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff));
  2845. if (srcp < msg || srcp >= eom) { /* Out of range. */
  2846. __set_errno(EMSGSIZE);
  2847. return -1;
  2848. }
  2849. checked += 2;
  2850. /*
  2851. * Check for loops in the compressed name;
  2852. * if we've looked at the whole message,
  2853. * there must be a loop.
  2854. */
  2855. if (checked >= eom - msg) {
  2856. __set_errno(EMSGSIZE);
  2857. return -1;
  2858. }
  2859. break;
  2860. default:
  2861. __set_errno(EMSGSIZE);
  2862. return -1; /* flag error */
  2863. }
  2864. }
  2865. *dstp = '\0';
  2866. if (len < 0)
  2867. len = srcp - src;
  2868. return len;
  2869. }
  2870. libc_hidden_def(ns_name_unpack)
  2871. static int labellen(const unsigned char *lp)
  2872. {
  2873. unsigned bitlen;
  2874. unsigned char l = *lp;
  2875. if ((l & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
  2876. /* should be avoided by the caller */
  2877. return -1;
  2878. }
  2879. if ((l & NS_CMPRSFLGS) == NS_TYPE_ELT) {
  2880. if (l == DNS_LABELTYPE_BITSTRING) {
  2881. bitlen = lp[1];
  2882. if (bitlen == 0)
  2883. bitlen = 256;
  2884. return ((bitlen + 7 ) / 8 + 1);
  2885. }
  2886. return -1; /*%< unknwon ELT */
  2887. }
  2888. return l;
  2889. }
  2890. static int mklower(int ch)
  2891. {
  2892. if (ch >= 0x41 && ch <= 0x5A)
  2893. return (ch + 0x20);
  2894. return ch;
  2895. }
  2896. static int dn_find(const unsigned char *domain,
  2897. const unsigned char *msg,
  2898. const unsigned char * const *dnptrs,
  2899. const unsigned char * const *lastdnptr)
  2900. {
  2901. const unsigned char *dn, *cp, *sp;
  2902. const unsigned char * const *cpp;
  2903. u_int n;
  2904. for (cpp = dnptrs; cpp < lastdnptr; cpp++) {
  2905. sp = *cpp;
  2906. /*
  2907. * terminate search on:
  2908. * root label
  2909. * compression pointer
  2910. * unusable offset
  2911. */
  2912. while (*sp != 0 && (*sp & NS_CMPRSFLGS) == 0 &&
  2913. (sp - msg) < 0x4000) {
  2914. dn = domain;
  2915. cp = sp;
  2916. while ((n = *cp++) != 0) {
  2917. /*
  2918. * check for indirection
  2919. */
  2920. switch (n & NS_CMPRSFLGS) {
  2921. case 0: /*%< normal case, n == len */
  2922. n = labellen(cp - 1); /*%< XXX */
  2923. if (n != *dn++)
  2924. goto next;
  2925. for (; n > 0; n--)
  2926. if (mklower(*dn++) !=
  2927. mklower(*cp++))
  2928. goto next;
  2929. /* Is next root for both ? */
  2930. if (*dn == '\0' && *cp == '\0')
  2931. return (sp - msg);
  2932. if (*dn)
  2933. continue;
  2934. goto next;
  2935. case NS_CMPRSFLGS: /*%< indirection */
  2936. cp = msg + (((n & 0x3f) << 8) | *cp);
  2937. break;
  2938. default: /*%< illegal type */
  2939. errno = EMSGSIZE;
  2940. return -1;
  2941. }
  2942. }
  2943. next:
  2944. sp += *sp + 1;
  2945. }
  2946. }
  2947. errno = ENOENT;
  2948. return -1;
  2949. }
  2950. int ns_name_pack(const unsigned char *src,
  2951. unsigned char *dst, int dstsiz,
  2952. const unsigned char **dnptrs,
  2953. const unsigned char **lastdnptr)
  2954. {
  2955. unsigned char *dstp;
  2956. const unsigned char **cpp, **lpp, *eob, *msg;
  2957. const unsigned char *srcp;
  2958. int n, l, first = 1;
  2959. srcp = src;
  2960. dstp = dst;
  2961. eob = dstp + dstsiz;
  2962. lpp = cpp = NULL;
  2963. if (dnptrs != NULL) {
  2964. msg = *dnptrs++;
  2965. if (msg != NULL) {
  2966. for (cpp = dnptrs; *cpp != NULL; cpp++)
  2967. continue;
  2968. lpp = cpp; /*%< end of list to search */
  2969. }
  2970. } else {
  2971. msg = NULL;
  2972. }
  2973. /* make sure the domain we are about to add is legal */
  2974. l = 0;
  2975. do {
  2976. int l0;
  2977. n = *srcp;
  2978. if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
  2979. errno = EMSGSIZE;
  2980. return -1;
  2981. }
  2982. l0 = labellen(srcp);
  2983. if (l0 < 0) {
  2984. errno = EINVAL;
  2985. return -1;
  2986. }
  2987. l += l0 + 1;
  2988. if (l > MAXCDNAME) {
  2989. errno = EMSGSIZE;
  2990. return -1;
  2991. }
  2992. srcp += l0 + 1;
  2993. } while (n != 0);
  2994. /* from here on we need to reset compression pointer array on error */
  2995. srcp = src;
  2996. do {
  2997. /* Look to see if we can use pointers. */
  2998. n = *srcp;
  2999. if (n != 0 && msg != NULL) {
  3000. l = dn_find(srcp, msg, (const unsigned char * const *) dnptrs,
  3001. (const unsigned char * const *) lpp);
  3002. if (l >= 0) {
  3003. if (dstp + 1 >= eob) {
  3004. goto cleanup;
  3005. }
  3006. *dstp++ = ((u_int32_t)l >> 8) | NS_CMPRSFLGS;
  3007. *dstp++ = l % 256;
  3008. return (dstp - dst);
  3009. }
  3010. /* Not found, save it. */
  3011. if (lastdnptr != NULL && cpp < lastdnptr - 1 &&
  3012. (dstp - msg) < 0x4000 && first) {
  3013. *cpp++ = dstp;
  3014. *cpp = NULL;
  3015. first = 0;
  3016. }
  3017. }
  3018. /* copy label to buffer */
  3019. if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) {
  3020. /* Should not happen. */
  3021. goto cleanup;
  3022. }
  3023. n = labellen(srcp);
  3024. if (dstp + 1 + n >= eob) {
  3025. goto cleanup;
  3026. }
  3027. memcpy(dstp, srcp, (size_t)(n + 1));
  3028. srcp += n + 1;
  3029. dstp += n + 1;
  3030. } while (n != 0);
  3031. if (dstp > eob) {
  3032. cleanup:
  3033. if (msg != NULL)
  3034. *lpp = NULL;
  3035. errno = EMSGSIZE;
  3036. return -1;
  3037. }
  3038. return dstp - dst;
  3039. }
  3040. libc_hidden_def(ns_name_pack)
  3041. int ns_name_compress(const char *src,
  3042. unsigned char *dst, size_t dstsiz,
  3043. const unsigned char **dnptrs,
  3044. const unsigned char **lastdnptr)
  3045. {
  3046. unsigned char tmp[NS_MAXCDNAME];
  3047. if (ns_name_pton(src, tmp, sizeof(tmp)) == -1)
  3048. return -1;
  3049. return ns_name_pack(tmp, dst, dstsiz, dnptrs, lastdnptr);
  3050. }
  3051. libc_hidden_def(ns_name_compress)
  3052. int ns_name_skip(const unsigned char **ptrptr,
  3053. const unsigned char *eom)
  3054. {
  3055. const unsigned char *cp;
  3056. u_int n;
  3057. int l;
  3058. cp = *ptrptr;
  3059. while (cp < eom && (n = *cp++) != 0) {
  3060. /* Check for indirection. */
  3061. switch (n & NS_CMPRSFLGS) {
  3062. case 0: /*%< normal case, n == len */
  3063. cp += n;
  3064. continue;
  3065. case NS_TYPE_ELT: /*%< EDNS0 extended label */
  3066. l = labellen(cp - 1);
  3067. if (l < 0) {
  3068. errno = EMSGSIZE; /*%< XXX */
  3069. return -1;
  3070. }
  3071. cp += l;
  3072. continue;
  3073. case NS_CMPRSFLGS: /*%< indirection */
  3074. cp++;
  3075. break;
  3076. default: /*%< illegal type */
  3077. errno = EMSGSIZE;
  3078. return -1;
  3079. }
  3080. break;
  3081. }
  3082. if (cp > eom) {
  3083. errno = EMSGSIZE;
  3084. return -1;
  3085. }
  3086. *ptrptr = cp;
  3087. return 0;
  3088. }
  3089. libc_hidden_def(ns_name_skip)
  3090. int dn_skipname(const unsigned char *ptr, const unsigned char *eom)
  3091. {
  3092. const unsigned char *saveptr = ptr;
  3093. if (ns_name_skip(&ptr, eom) == -1)
  3094. return -1;
  3095. return ptr - saveptr;
  3096. }
  3097. libc_hidden_def(dn_skipname)
  3098. #endif /* L_ns_name */
  3099. #ifdef L_res_init
  3100. /* Will be called under __resolv_lock. */
  3101. static void res_sync_func(void)
  3102. {
  3103. struct __res_state *rp = &(_res);
  3104. int n;
  3105. /* If we didn't get malloc failure earlier... */
  3106. if (__nameserver != (void*) &__local_nameserver) {
  3107. /* TODO:
  3108. * if (__nameservers < rp->nscount) - try to grow __nameserver[]?
  3109. */
  3110. #ifdef __UCLIBC_HAS_IPV6__
  3111. if (__nameservers > rp->_u._ext.nscount)
  3112. __nameservers = rp->_u._ext.nscount;
  3113. n = __nameservers;
  3114. while (--n >= 0)
  3115. __nameserver[n].sa6 = *rp->_u._ext.nsaddrs[n]; /* struct copy */
  3116. #else /* IPv4 only */
  3117. if (__nameservers > rp->nscount)
  3118. __nameservers = rp->nscount;
  3119. n = __nameservers;
  3120. while (--n >= 0)
  3121. __nameserver[n].sa4 = rp->nsaddr_list[n]; /* struct copy */
  3122. #endif
  3123. }
  3124. __resolv_timeout = rp->retrans ? : RES_TIMEOUT;
  3125. __resolv_attempts = rp->retry ? : RES_DFLRETRY;
  3126. /* Extend and comment what program is known
  3127. * to use which _res.XXX member(s).
  3128. __resolv_opts = rp->options;
  3129. ...
  3130. */
  3131. }
  3132. /* has to be called under __resolv_lock */
  3133. static int
  3134. __res_vinit(res_state rp, int preinit)
  3135. {
  3136. int i, n, options, retrans, retry, ndots;
  3137. #ifdef __UCLIBC_HAS_IPV6__
  3138. int m = 0;
  3139. #endif
  3140. __close_nameservers();
  3141. __open_nameservers();
  3142. if (preinit) {
  3143. options = rp->options;
  3144. retrans = rp->retrans;
  3145. retry = rp->retry;
  3146. ndots = rp->ndots;
  3147. }
  3148. memset(rp, 0, sizeof(*rp));
  3149. if (!preinit) {
  3150. rp->options = RES_DEFAULT;
  3151. rp->retrans = RES_TIMEOUT;
  3152. rp->retry = RES_DFLRETRY;
  3153. rp->ndots = 1;
  3154. } else {
  3155. rp->options = options;
  3156. rp->retrans = retrans;
  3157. rp->retry = retry;
  3158. rp->ndots = ndots;
  3159. }
  3160. #ifdef __UCLIBC_HAS_COMPAT_RES_STATE__
  3161. /* Was: "rp->id = random();" but:
  3162. * - random() pulls in largish static buffers
  3163. * - isn't actually random unless, say, srandom(time(NULL)) was called
  3164. * - is not used by uclibc anyway :)
  3165. */
  3166. /* rp->id = 0; - memset did it */
  3167. #endif
  3168. #ifdef __UCLIBC_HAS_EXTRA_COMPAT_RES_STATE__
  3169. rp->_vcsock = -1;
  3170. #endif
  3171. n = __searchdomains;
  3172. if (n > ARRAY_SIZE(rp->dnsrch))
  3173. n = ARRAY_SIZE(rp->dnsrch);
  3174. for (i = 0; i < n; i++)
  3175. rp->dnsrch[i] = __searchdomain[i];
  3176. /* copy nameservers' addresses */
  3177. i = 0;
  3178. #ifdef __UCLIBC_HAS_IPV4__
  3179. n = 0;
  3180. while (n < ARRAY_SIZE(rp->nsaddr_list) && i < __nameservers) {
  3181. if (__nameserver[i].sa.sa_family == AF_INET) {
  3182. rp->nsaddr_list[n] = __nameserver[i].sa4; /* struct copy */
  3183. #ifdef __UCLIBC_HAS_IPV6__
  3184. if (m < ARRAY_SIZE(rp->_u._ext.nsaddrs)) {
  3185. rp->_u._ext.nsaddrs[m] = (void*) &rp->nsaddr_list[n];
  3186. m++;
  3187. }
  3188. #endif
  3189. n++;
  3190. }
  3191. #ifdef __UCLIBC_HAS_IPV6__
  3192. if (__nameserver[i].sa.sa_family == AF_INET6
  3193. && m < ARRAY_SIZE(rp->_u._ext.nsaddrs)
  3194. ) {
  3195. struct sockaddr_in6 *sa6 = malloc(sizeof(*sa6));
  3196. if (sa6) {
  3197. *sa6 = __nameserver[i].sa6; /* struct copy */
  3198. rp->_u._ext.nsaddrs[m] = sa6;
  3199. m++;
  3200. }
  3201. }
  3202. #endif
  3203. i++;
  3204. }
  3205. rp->nscount = n;
  3206. #ifdef __UCLIBC_HAS_IPV6__
  3207. rp->_u._ext.nscount = m;
  3208. #endif
  3209. #else /* IPv6 only */
  3210. while (m < ARRAY_SIZE(rp->_u._ext.nsaddrs) && i < __nameservers) {
  3211. struct sockaddr_in6 *sa6 = malloc(sizeof(*sa6));
  3212. if (sa6) {
  3213. *sa6 = __nameserver[i].sa6; /* struct copy */
  3214. rp->_u._ext.nsaddrs[m] = sa6;
  3215. m++;
  3216. }
  3217. i++;
  3218. }
  3219. rp->_u._ext.nscount = m;
  3220. #endif
  3221. rp->options |= RES_INIT;
  3222. return 0;
  3223. }
  3224. static unsigned int
  3225. res_randomid(void)
  3226. {
  3227. return 0xffff & getpid();
  3228. }
  3229. /* Our res_init never fails (always returns 0) */
  3230. int
  3231. res_init(void)
  3232. {
  3233. /*
  3234. * These three fields used to be statically initialized. This made
  3235. * it hard to use this code in a shared library. It is necessary,
  3236. * now that we're doing dynamic initialization here, that we preserve
  3237. * the old semantics: if an application modifies one of these three
  3238. * fields of _res before res_init() is called, res_init() will not
  3239. * alter them. Of course, if an application is setting them to
  3240. * _zero_ before calling res_init(), hoping to override what used
  3241. * to be the static default, we can't detect it and unexpected results
  3242. * will follow. Zero for any of these fields would make no sense,
  3243. * so one can safely assume that the applications were already getting
  3244. * unexpected results.
  3245. *
  3246. * _res.options is tricky since some apps were known to diddle the bits
  3247. * before res_init() was first called. We can't replicate that semantic
  3248. * with dynamic initialization (they may have turned bits off that are
  3249. * set in RES_DEFAULT). Our solution is to declare such applications
  3250. * "broken". They could fool us by setting RES_INIT but none do (yet).
  3251. */
  3252. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  3253. if (!_res.retrans)
  3254. _res.retrans = RES_TIMEOUT;
  3255. if (!_res.retry)
  3256. _res.retry = 4;
  3257. if (!(_res.options & RES_INIT))
  3258. _res.options = RES_DEFAULT;
  3259. /*
  3260. * This one used to initialize implicitly to zero, so unless the app
  3261. * has set it to something in particular, we can randomize it now.
  3262. */
  3263. if (!_res.id)
  3264. _res.id = res_randomid();
  3265. __res_sync = NULL;
  3266. __res_vinit(&_res, 1);
  3267. __res_sync = res_sync_func;
  3268. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  3269. return 0;
  3270. }
  3271. libc_hidden_def(res_init)
  3272. static void
  3273. __res_iclose(res_state statp)
  3274. {
  3275. struct __res_state * rp = statp;
  3276. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  3277. if (rp == NULL)
  3278. rp = __res_state();
  3279. __close_nameservers();
  3280. __res_sync = NULL;
  3281. #ifdef __UCLIBC_HAS_IPV6__
  3282. {
  3283. char *p1 = (char*) &(rp->nsaddr_list[0]);
  3284. unsigned int m = 0;
  3285. /* free nsaddrs[m] if they do not point to nsaddr_list[x] */
  3286. while (m < ARRAY_SIZE(rp->_u._ext.nsaddrs)) {
  3287. char *p2 = (char*)(rp->_u._ext.nsaddrs[m++]);
  3288. if (p2 < p1 || (p2 - p1) > (signed)sizeof(rp->nsaddr_list))
  3289. free(p2);
  3290. }
  3291. }
  3292. #endif
  3293. memset(rp, 0, sizeof(struct __res_state));
  3294. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  3295. }
  3296. /*
  3297. * This routine is for closing the socket if a virtual circuit is used and
  3298. * the program wants to close it. This provides support for endhostent()
  3299. * which expects to close the socket.
  3300. *
  3301. * This routine is not expected to be user visible.
  3302. */
  3303. void
  3304. res_nclose(res_state statp)
  3305. {
  3306. __res_iclose(statp);
  3307. }
  3308. #ifdef __UCLIBC_HAS_BSD_RES_CLOSE__
  3309. void res_close(void)
  3310. {
  3311. __res_iclose(NULL);
  3312. }
  3313. #endif
  3314. /* This needs to be after the use of _res in res_init, above. */
  3315. #undef _res
  3316. #ifndef __UCLIBC_HAS_THREADS__
  3317. /* The resolver state for use by single-threaded programs.
  3318. This differs from plain `struct __res_state _res;' in that it doesn't
  3319. create a common definition, but a plain symbol that resides in .bss,
  3320. which can have an alias. */
  3321. struct __res_state _res __attribute__((section (".bss")));
  3322. struct __res_state *__resp = &_res;
  3323. #else /* __UCLIBC_HAS_THREADS__ */
  3324. struct __res_state _res __attribute__((section (".bss"))) attribute_hidden;
  3325. # if defined __UCLIBC_HAS_TLS__
  3326. # undef __resp
  3327. __thread struct __res_state *__resp = &_res;
  3328. extern __thread struct __res_state *__libc_resp
  3329. __attribute__ ((alias ("__resp"))) attribute_hidden attribute_tls_model_ie;
  3330. # else
  3331. # undef __resp
  3332. struct __res_state *__resp = &_res;
  3333. # endif
  3334. #endif /* !__UCLIBC_HAS_THREADS__ */
  3335. /*
  3336. * Set up default settings. If the configuration file exist, the values
  3337. * there will have precedence. Otherwise, the server address is set to
  3338. * INADDR_ANY and the default domain name comes from the gethostname().
  3339. *
  3340. * An interrim version of this code (BIND 4.9, pre-4.4BSD) used 127.0.0.1
  3341. * rather than INADDR_ANY ("0.0.0.0") as the default name server address
  3342. * since it was noted that INADDR_ANY actually meant ``the first interface
  3343. * you "ifconfig"'d at boot time'' and if this was a SLIP or PPP interface,
  3344. * it had to be "up" in order for you to reach your own name server. It
  3345. * was later decided that since the recommended practice is to always
  3346. * install local static routes through 127.0.0.1 for all your network
  3347. * interfaces, that we could solve this problem without a code change.
  3348. *
  3349. * The configuration file should always be used, since it is the only way
  3350. * to specify a default domain. If you are running a server on your local
  3351. * machine, you should say "nameserver 0.0.0.0" or "nameserver 127.0.0.1"
  3352. * in the configuration file.
  3353. *
  3354. * Return 0 if completes successfully, -1 on error
  3355. */
  3356. int
  3357. res_ninit(res_state statp)
  3358. {
  3359. int ret;
  3360. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  3361. ret = __res_vinit(statp, 0);
  3362. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  3363. return ret;
  3364. }
  3365. #endif /* L_res_init */
  3366. #ifdef L_res_state
  3367. # if defined __UCLIBC_HAS_TLS__
  3368. struct __res_state *
  3369. __res_state (void)
  3370. {
  3371. return __resp;
  3372. }
  3373. # else
  3374. # undef _res
  3375. extern struct __res_state _res;
  3376. /* When threaded, _res may be a per-thread variable. */
  3377. struct __res_state *
  3378. weak_const_function
  3379. __res_state (void)
  3380. {
  3381. return &_res;
  3382. }
  3383. # endif
  3384. #endif /* L_res_state */
  3385. #ifdef L_res_query
  3386. int res_query(const char *dname, int class, int type,
  3387. unsigned char *answer, int anslen)
  3388. {
  3389. int i;
  3390. unsigned char *packet = NULL;
  3391. struct resolv_answer a;
  3392. if (!dname || class != 1 /* CLASS_IN */) {
  3393. h_errno = NO_RECOVERY;
  3394. return -1;
  3395. }
  3396. memset(&a, '\0', sizeof(a));
  3397. i = __dns_lookup(dname, type, &packet, &a);
  3398. if (i < 0) {
  3399. if (!h_errno) /* TODO: can this ever happen? */
  3400. h_errno = TRY_AGAIN;
  3401. return -1;
  3402. }
  3403. free(a.dotted);
  3404. if (i > anslen)
  3405. i = anslen;
  3406. memcpy(answer, packet, i);
  3407. free(packet);
  3408. return i;
  3409. }
  3410. libc_hidden_def(res_query)
  3411. /*
  3412. * Formulate a normal query, send, and retrieve answer in supplied buffer.
  3413. * Return the size of the response on success, -1 on error.
  3414. * If enabled, implement search rules until answer or unrecoverable failure
  3415. * is detected. Error code, if any, is left in h_errno.
  3416. */
  3417. #define __TRAILING_DOT (1<<0)
  3418. #define __GOT_NODATA (1<<1)
  3419. #define __GOT_SERVFAIL (1<<2)
  3420. #define __TRIED_AS_IS (1<<3)
  3421. int res_search(const char *name, int class, int type, u_char *answer,
  3422. int anslen)
  3423. {
  3424. const char *cp;
  3425. char **domain;
  3426. HEADER *hp = (HEADER *)(void *)answer;
  3427. unsigned dots;
  3428. unsigned state;
  3429. int ret, saved_herrno;
  3430. uint32_t _res_options;
  3431. unsigned _res_ndots;
  3432. char **_res_dnsrch;
  3433. if (!name || !answer) {
  3434. h_errno = NETDB_INTERNAL;
  3435. return -1;
  3436. }
  3437. again:
  3438. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  3439. _res_options = _res.options;
  3440. _res_ndots = _res.ndots;
  3441. _res_dnsrch = _res.dnsrch;
  3442. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  3443. if (!(_res_options & RES_INIT)) {
  3444. res_init(); /* our res_init never fails */
  3445. goto again;
  3446. }
  3447. state = 0;
  3448. errno = 0;
  3449. h_errno = HOST_NOT_FOUND; /* default, if we never query */
  3450. dots = 0;
  3451. for (cp = name; *cp; cp++)
  3452. dots += (*cp == '.');
  3453. if (cp > name && *--cp == '.')
  3454. state |= __TRAILING_DOT;
  3455. /*
  3456. * If there are dots in the name already, let's just give it a try
  3457. * 'as is'. The threshold can be set with the "ndots" option.
  3458. */
  3459. saved_herrno = -1;
  3460. if (dots >= _res_ndots) {
  3461. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  3462. if (ret > 0)
  3463. return ret;
  3464. saved_herrno = h_errno;
  3465. state |= __TRIED_AS_IS;
  3466. }
  3467. /*
  3468. * We do at least one level of search if
  3469. * - there is no dot and RES_DEFNAME is set, or
  3470. * - there is at least one dot, there is no trailing dot,
  3471. * and RES_DNSRCH is set.
  3472. */
  3473. if ((!dots && (_res_options & RES_DEFNAMES))
  3474. || (dots && !(state & __TRAILING_DOT) && (_res_options & RES_DNSRCH))
  3475. ) {
  3476. bool done = 0;
  3477. for (domain = _res_dnsrch; *domain && !done; domain++) {
  3478. ret = res_querydomain(name, *domain, class, type,
  3479. answer, anslen);
  3480. if (ret > 0)
  3481. return ret;
  3482. /*
  3483. * If no server present, give up.
  3484. * If name isn't found in this domain,
  3485. * keep trying higher domains in the search list
  3486. * (if that's enabled).
  3487. * On a NO_DATA error, keep trying, otherwise
  3488. * a wildcard entry of another type could keep us
  3489. * from finding this entry higher in the domain.
  3490. * If we get some other error (negative answer or
  3491. * server failure), then stop searching up,
  3492. * but try the input name below in case it's
  3493. * fully-qualified.
  3494. */
  3495. if (errno == ECONNREFUSED) {
  3496. h_errno = TRY_AGAIN;
  3497. return -1;
  3498. }
  3499. switch (h_errno) {
  3500. case NO_DATA:
  3501. state |= __GOT_NODATA;
  3502. /* FALLTHROUGH */
  3503. case HOST_NOT_FOUND:
  3504. /* keep trying */
  3505. break;
  3506. case TRY_AGAIN:
  3507. if (hp->rcode == SERVFAIL) {
  3508. /* try next search element, if any */
  3509. state |= __GOT_SERVFAIL;
  3510. break;
  3511. }
  3512. /* FALLTHROUGH */
  3513. default:
  3514. /* anything else implies that we're done */
  3515. done = 1;
  3516. }
  3517. /*
  3518. * if we got here for some reason other than DNSRCH,
  3519. * we only wanted one iteration of the loop, so stop.
  3520. */
  3521. if (!(_res_options & RES_DNSRCH))
  3522. done = 1;
  3523. }
  3524. }
  3525. /*
  3526. * if we have not already tried the name "as is", do that now.
  3527. * note that we do this regardless of how many dots were in the
  3528. * name or whether it ends with a dot.
  3529. */
  3530. if (!(state & __TRIED_AS_IS)) {
  3531. ret = res_querydomain(name, NULL, class, type, answer, anslen);
  3532. if (ret > 0)
  3533. return ret;
  3534. }
  3535. /*
  3536. * if we got here, we didn't satisfy the search.
  3537. * if we did an initial full query, return that query's h_errno
  3538. * (note that we wouldn't be here if that query had succeeded).
  3539. * else if we ever got a nodata, send that back as the reason.
  3540. * else send back meaningless h_errno, that being the one from
  3541. * the last DNSRCH we did.
  3542. */
  3543. if (saved_herrno != -1)
  3544. h_errno = saved_herrno;
  3545. else if (state & __GOT_NODATA)
  3546. h_errno = NO_DATA;
  3547. else if (state & __GOT_SERVFAIL)
  3548. h_errno = TRY_AGAIN;
  3549. return -1;
  3550. }
  3551. #undef __TRAILING_DOT
  3552. #undef __GOT_NODATA
  3553. #undef __GOT_SERVFAIL
  3554. #undef __TRIED_AS_IS
  3555. /*
  3556. * Perform a call on res_query on the concatenation of name and domain,
  3557. * removing a trailing dot from name if domain is NULL.
  3558. */
  3559. int res_querydomain(const char *name, const char *domain, int class, int type,
  3560. u_char *answer, int anslen)
  3561. {
  3562. char nbuf[MAXDNAME];
  3563. const char *longname = nbuf;
  3564. size_t n, d;
  3565. #ifdef DEBUG
  3566. uint32_t _res_options;
  3567. #endif
  3568. if (!name || !answer) {
  3569. h_errno = NETDB_INTERNAL;
  3570. return -1;
  3571. }
  3572. #ifdef DEBUG
  3573. again:
  3574. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  3575. _res_options = _res.options;
  3576. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  3577. if (!(_res_options & RES_INIT)) {
  3578. res_init(); /* our res_init never fails */
  3579. goto again;
  3580. }
  3581. if (_res_options & RES_DEBUG)
  3582. printf(";; res_querydomain(%s, %s, %d, %d)\n",
  3583. name, (domain ? domain : "<Nil>"), class, type);
  3584. #endif
  3585. if (domain == NULL) {
  3586. /*
  3587. * Check for trailing '.';
  3588. * copy without '.' if present.
  3589. */
  3590. n = strlen(name);
  3591. if (n + 1 > sizeof(nbuf)) {
  3592. h_errno = NO_RECOVERY;
  3593. return -1;
  3594. }
  3595. if (n > 0 && name[--n] == '.') {
  3596. strncpy(nbuf, name, n);
  3597. nbuf[n] = '\0';
  3598. } else
  3599. longname = name;
  3600. } else {
  3601. n = strlen(name);
  3602. d = strlen(domain);
  3603. if (n + 1 + d + 1 > sizeof(nbuf)) {
  3604. h_errno = NO_RECOVERY;
  3605. return -1;
  3606. }
  3607. snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
  3608. }
  3609. return res_query(longname, class, type, answer, anslen);
  3610. }
  3611. libc_hidden_def(res_querydomain)
  3612. #endif /* L_res_query */
  3613. #ifdef L_ns_netint
  3614. unsigned int ns_get16(const unsigned char *src)
  3615. {
  3616. unsigned int dst;
  3617. NS_GET16(dst, src);
  3618. return dst;
  3619. }
  3620. unsigned long ns_get32(const unsigned char *src)
  3621. {
  3622. unsigned long dst;
  3623. NS_GET32(dst, src);
  3624. return dst;
  3625. }
  3626. void ns_put16(unsigned int src, unsigned char *dst)
  3627. {
  3628. NS_PUT16(src, dst);
  3629. }
  3630. void ns_put32(unsigned long src, unsigned char *dst)
  3631. {
  3632. NS_PUT32(src, dst);
  3633. }
  3634. #endif /* L_ns_netint */
  3635. #ifdef L_ns_parse
  3636. /* These need to be in the same order as the nres.h:ns_flag enum. */
  3637. struct _ns_flagdata { unsigned short mask, shift; };
  3638. static const struct _ns_flagdata _ns_flagdata[16] = {
  3639. { 0x8000, 15 }, /*%< qr. */
  3640. { 0x7800, 11 }, /*%< opcode. */
  3641. { 0x0400, 10 }, /*%< aa. */
  3642. { 0x0200, 9 }, /*%< tc. */
  3643. { 0x0100, 8 }, /*%< rd. */
  3644. { 0x0080, 7 }, /*%< ra. */
  3645. { 0x0040, 6 }, /*%< z. */
  3646. { 0x0020, 5 }, /*%< ad. */
  3647. { 0x0010, 4 }, /*%< cd. */
  3648. { 0x000f, 0 }, /*%< rcode. */
  3649. { 0x0000, 0 }, /*%< expansion (1/6). */
  3650. { 0x0000, 0 }, /*%< expansion (2/6). */
  3651. { 0x0000, 0 }, /*%< expansion (3/6). */
  3652. { 0x0000, 0 }, /*%< expansion (4/6). */
  3653. { 0x0000, 0 }, /*%< expansion (5/6). */
  3654. { 0x0000, 0 }, /*%< expansion (6/6). */
  3655. };
  3656. static void setsection(ns_msg *msg, ns_sect sect)
  3657. {
  3658. msg->_sect = sect;
  3659. if (sect == ns_s_max) {
  3660. msg->_rrnum = -1;
  3661. msg->_ptr = NULL;
  3662. } else {
  3663. msg->_rrnum = 0;
  3664. msg->_ptr = msg->_sections[(int)sect];
  3665. }
  3666. }
  3667. int ns_skiprr(const unsigned char *ptr,
  3668. const unsigned char *eom,
  3669. ns_sect section, int count)
  3670. {
  3671. const u_char *optr = ptr;
  3672. for (; count > 0; count--) {
  3673. int b, rdlength;
  3674. b = dn_skipname(ptr, eom);
  3675. if (b < 0) {
  3676. errno = EMSGSIZE;
  3677. return -1;
  3678. }
  3679. ptr += b/*Name*/ + NS_INT16SZ/*Type*/ + NS_INT16SZ/*Class*/;
  3680. if (section != ns_s_qd) {
  3681. if (ptr + NS_INT32SZ + NS_INT16SZ > eom) {
  3682. errno = EMSGSIZE;
  3683. return -1;
  3684. }
  3685. ptr += NS_INT32SZ/*TTL*/;
  3686. NS_GET16(rdlength, ptr);
  3687. ptr += rdlength/*RData*/;
  3688. }
  3689. }
  3690. if (ptr > eom) {
  3691. errno = EMSGSIZE;
  3692. return -1;
  3693. }
  3694. return ptr - optr;
  3695. }
  3696. libc_hidden_def(ns_skiprr)
  3697. int
  3698. ns_initparse(const unsigned char *msg, int msglen, ns_msg *handle)
  3699. {
  3700. const u_char *eom = msg + msglen;
  3701. int i;
  3702. handle->_msg = msg;
  3703. handle->_eom = eom;
  3704. if (msg + NS_INT16SZ > eom) {
  3705. errno = EMSGSIZE;
  3706. return -1;
  3707. }
  3708. NS_GET16(handle->_id, msg);
  3709. if (msg + NS_INT16SZ > eom) {
  3710. errno = EMSGSIZE;
  3711. return -1;
  3712. }
  3713. NS_GET16(handle->_flags, msg);
  3714. for (i = 0; i < ns_s_max; i++) {
  3715. if (msg + NS_INT16SZ > eom) {
  3716. errno = EMSGSIZE;
  3717. return -1;
  3718. }
  3719. NS_GET16(handle->_counts[i], msg);
  3720. }
  3721. for (i = 0; i < ns_s_max; i++)
  3722. if (handle->_counts[i] == 0)
  3723. handle->_sections[i] = NULL;
  3724. else {
  3725. int b = ns_skiprr(msg, eom, (ns_sect)i,
  3726. handle->_counts[i]);
  3727. if (b < 0)
  3728. return -1;
  3729. handle->_sections[i] = msg;
  3730. msg += b;
  3731. }
  3732. if (msg != eom) {
  3733. errno = EMSGSIZE;
  3734. return -1;
  3735. }
  3736. setsection(handle, ns_s_max);
  3737. return 0;
  3738. }
  3739. int
  3740. ns_parserr(ns_msg *handle, ns_sect section, int rrnum, ns_rr *rr)
  3741. {
  3742. int b;
  3743. int tmp;
  3744. /* Make section right. */
  3745. tmp = section;
  3746. if (tmp < 0 || section >= ns_s_max) {
  3747. errno = ENODEV;
  3748. return -1;
  3749. }
  3750. if (section != handle->_sect)
  3751. setsection(handle, section);
  3752. /* Make rrnum right. */
  3753. if (rrnum == -1)
  3754. rrnum = handle->_rrnum;
  3755. if (rrnum < 0 || rrnum >= handle->_counts[(int)section]) {
  3756. errno = ENODEV;
  3757. return -1;
  3758. }
  3759. if (rrnum < handle->_rrnum)
  3760. setsection(handle, section);
  3761. if (rrnum > handle->_rrnum) {
  3762. b = ns_skiprr(handle->_ptr, handle->_eom, section,
  3763. rrnum - handle->_rrnum);
  3764. if (b < 0)
  3765. return -1;
  3766. handle->_ptr += b;
  3767. handle->_rrnum = rrnum;
  3768. }
  3769. /* Do the parse. */
  3770. b = dn_expand(handle->_msg, handle->_eom,
  3771. handle->_ptr, rr->name, NS_MAXDNAME);
  3772. if (b < 0)
  3773. return -1;
  3774. handle->_ptr += b;
  3775. if (handle->_ptr + NS_INT16SZ + NS_INT16SZ > handle->_eom) {
  3776. errno = EMSGSIZE;
  3777. return -1;
  3778. }
  3779. NS_GET16(rr->type, handle->_ptr);
  3780. NS_GET16(rr->rr_class, handle->_ptr);
  3781. if (section == ns_s_qd) {
  3782. rr->ttl = 0;
  3783. rr->rdlength = 0;
  3784. rr->rdata = NULL;
  3785. } else {
  3786. if (handle->_ptr + NS_INT32SZ + NS_INT16SZ > handle->_eom) {
  3787. errno = EMSGSIZE;
  3788. return -1;
  3789. }
  3790. NS_GET32(rr->ttl, handle->_ptr);
  3791. NS_GET16(rr->rdlength, handle->_ptr);
  3792. if (handle->_ptr + rr->rdlength > handle->_eom) {
  3793. errno = EMSGSIZE;
  3794. return -1;
  3795. }
  3796. rr->rdata = handle->_ptr;
  3797. handle->_ptr += rr->rdlength;
  3798. }
  3799. if (++handle->_rrnum > handle->_counts[(int)section])
  3800. setsection(handle, (ns_sect)((int)section + 1));
  3801. return 0;
  3802. }
  3803. int ns_msg_getflag(ns_msg handle, int flag)
  3804. {
  3805. return ((handle)._flags & _ns_flagdata[flag].mask) >> _ns_flagdata[flag].shift;
  3806. }
  3807. #endif /* L_ns_parse */
  3808. #ifdef L_res_data
  3809. int res_mkquery(int op, const char *dname, int class, int type,
  3810. const unsigned char *data, int datalen,
  3811. const unsigned char *newrr_in,
  3812. unsigned char *buf, int buflen)
  3813. {
  3814. HEADER *hp;
  3815. unsigned char *cp, *ep;
  3816. unsigned char *dnptrs[20], **dpp, **lastdnptr;
  3817. uint32_t _res_options;
  3818. int n;
  3819. if (!buf || buflen < HFIXEDSZ) {
  3820. h_errno = NETDB_INTERNAL;
  3821. return -1;
  3822. }
  3823. again:
  3824. __UCLIBC_MUTEX_LOCK(__resolv_lock);
  3825. _res_options = _res.options;
  3826. __UCLIBC_MUTEX_UNLOCK(__resolv_lock);
  3827. if (!(_res_options & RES_INIT)) {
  3828. res_init(); /* our res_init never fails */
  3829. goto again;
  3830. }
  3831. #ifdef DEBUG
  3832. if (_res_options & RES_DEBUG)
  3833. printf(";; res_mkquery(%d, %s, %d, %d)\n",
  3834. op, dname && *dname ? dname : "<null>", class, type);
  3835. #endif
  3836. memset(buf, 0, HFIXEDSZ);
  3837. hp = (HEADER *) buf;
  3838. hp->id = getpid() & 0xffff;
  3839. hp->opcode = op;
  3840. hp->rd = (_res_options & RES_RECURSE) != 0U;
  3841. hp->rcode = NOERROR;
  3842. cp = buf + HFIXEDSZ;
  3843. ep = buf + buflen;
  3844. dpp = dnptrs;
  3845. *dpp++ = buf;
  3846. *dpp++ = NULL;
  3847. lastdnptr = dnptrs + sizeof dnptrs / sizeof dnptrs[0];
  3848. /*
  3849. * perform opcode specific processing
  3850. */
  3851. switch (op) {
  3852. case QUERY:
  3853. case NS_NOTIFY_OP:
  3854. if (ep - cp < QFIXEDSZ)
  3855. return -1;
  3856. n = dn_comp(dname, cp, ep - cp - QFIXEDSZ, dnptrs, lastdnptr);
  3857. if (n < 0)
  3858. return -1;
  3859. cp += n;
  3860. NS_PUT16(type, cp);
  3861. NS_PUT16(class, cp);
  3862. hp->qdcount = htons(1);
  3863. if (op == QUERY || data == NULL)
  3864. break;
  3865. /*
  3866. * Make an additional record for completion domain.
  3867. */
  3868. if ((ep - cp) < RRFIXEDSZ)
  3869. return -1;
  3870. n = dn_comp((const char *)data, cp, ep - cp - RRFIXEDSZ,
  3871. dnptrs, lastdnptr);
  3872. if (n < 0)
  3873. return -1;
  3874. cp += n;
  3875. NS_PUT16(T_NULL, cp);
  3876. NS_PUT16(class, cp);
  3877. NS_PUT32(0, cp);
  3878. NS_PUT16(0, cp);
  3879. hp->arcount = htons(1);
  3880. break;
  3881. case IQUERY:
  3882. /*
  3883. * Initialize answer section
  3884. */
  3885. if (ep - cp < 1 + RRFIXEDSZ + datalen)
  3886. return -1;
  3887. *cp++ = '\0'; /*%< no domain name */
  3888. NS_PUT16(type, cp);
  3889. NS_PUT16(class, cp);
  3890. NS_PUT32(0, cp);
  3891. NS_PUT16(datalen, cp);
  3892. if (datalen) {
  3893. memcpy(cp, data, (size_t)datalen);
  3894. cp += datalen;
  3895. }
  3896. hp->ancount = htons(1);
  3897. break;
  3898. default:
  3899. return -1;
  3900. }
  3901. return cp - buf;
  3902. }
  3903. #endif /* L_res_data */
  3904. /* Unimplemented: */
  3905. /* res_send */