resolv.c 108 KB

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