resolv.c 115 KB

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