resolv.c 115 KB

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