evdns.c 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847
  1. /* Copyright 2006-2007 Niels Provos
  2. * Copyright 2007-2012 Nick Mathewson and Niels Provos
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * 3. The name of the author may not be used to endorse or promote products
  13. * derived from this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  16. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  17. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  19. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  20. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  24. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. /* Based on software by Adam Langly. Adam's original message:
  27. *
  28. * Async DNS Library
  29. * Adam Langley <agl@imperialviolet.org>
  30. * http://www.imperialviolet.org/eventdns.html
  31. * Public Domain code
  32. *
  33. * This software is Public Domain. To view a copy of the public domain dedication,
  34. * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  35. * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  36. *
  37. * I ask and expect, but do not require, that all derivative works contain an
  38. * attribution similar to:
  39. * Parts developed by Adam Langley <agl@imperialviolet.org>
  40. *
  41. * You may wish to replace the word "Parts" with something else depending on
  42. * the amount of original code.
  43. *
  44. * (Derivative works does not include programs which link against, run or include
  45. * the source verbatim in their source distributions)
  46. *
  47. * Version: 0.1b
  48. */
  49. #include "event2/event-config.h"
  50. #include "evconfig-private.h"
  51. #include <sys/types.h>
  52. #ifndef _FORTIFY_SOURCE
  53. #define _FORTIFY_SOURCE 3
  54. #endif
  55. #include <string.h>
  56. #include <fcntl.h>
  57. #ifdef EVENT__HAVE_SYS_TIME_H
  58. #include <sys/time.h>
  59. #endif
  60. #ifdef EVENT__HAVE_STDINT_H
  61. #include <stdint.h>
  62. #endif
  63. #include <stdlib.h>
  64. #include <string.h>
  65. #include <errno.h>
  66. #ifdef EVENT__HAVE_UNISTD_H
  67. #include <unistd.h>
  68. #endif
  69. #include <limits.h>
  70. #include <sys/stat.h>
  71. #include <stdio.h>
  72. #include <stdarg.h>
  73. #ifdef _WIN32
  74. #include <winsock2.h>
  75. #include <winerror.h>
  76. #include <ws2tcpip.h>
  77. #ifndef _WIN32_IE
  78. #define _WIN32_IE 0x400
  79. #endif
  80. #include <shlobj.h>
  81. #endif
  82. #include "event2/dns.h"
  83. #include "event2/dns_struct.h"
  84. #include "event2/dns_compat.h"
  85. #include "event2/util.h"
  86. #include "event2/event.h"
  87. #include "event2/event_struct.h"
  88. #include "event2/thread.h"
  89. #include "defer-internal.h"
  90. #include "log-internal.h"
  91. #include "mm-internal.h"
  92. #include "strlcpy-internal.h"
  93. #include "ipv6-internal.h"
  94. #include "util-internal.h"
  95. #include "evthread-internal.h"
  96. #ifdef _WIN32
  97. #include <ctype.h>
  98. #include <winsock2.h>
  99. #include <windows.h>
  100. #include <iphlpapi.h>
  101. #include <io.h>
  102. #else
  103. #include <sys/socket.h>
  104. #include <netinet/in.h>
  105. #include <arpa/inet.h>
  106. #endif
  107. #ifdef EVENT__HAVE_NETINET_IN6_H
  108. #error #include <netinet/in6.h>
  109. #endif
  110. #define EVDNS_LOG_DEBUG EVENT_LOG_DEBUG
  111. #define EVDNS_LOG_WARN EVENT_LOG_WARN
  112. #define EVDNS_LOG_MSG EVENT_LOG_MSG
  113. #ifndef HOST_NAME_MAX
  114. #define HOST_NAME_MAX 255
  115. #endif
  116. #include <stdio.h>
  117. #undef MIN
  118. #define MIN(a,b) ((a)<(b)?(a):(b))
  119. #define ASSERT_VALID_REQUEST(req) \
  120. EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
  121. #define u64 ev_uint64_t
  122. #define u32 ev_uint32_t
  123. #define u16 ev_uint16_t
  124. #define u8 ev_uint8_t
  125. /* maximum number of addresses from a single packet */
  126. /* that we bother recording */
  127. #define MAX_V4_ADDRS 32
  128. #define MAX_V6_ADDRS 32
  129. #define TYPE_A EVDNS_TYPE_A
  130. #define TYPE_CNAME 5
  131. #define TYPE_PTR EVDNS_TYPE_PTR
  132. #define TYPE_SOA EVDNS_TYPE_SOA
  133. #define TYPE_AAAA EVDNS_TYPE_AAAA
  134. #define CLASS_INET EVDNS_CLASS_INET
  135. /* Persistent handle. We keep this separate from 'struct request' since we
  136. * need some object to last for as long as an evdns_request is outstanding so
  137. * that it can be canceled, whereas a search request can lead to multiple
  138. * 'struct request' instances being created over its lifetime. */
  139. struct evdns_request {
  140. struct request *current_req;
  141. struct evdns_base *base;
  142. int pending_cb; /* Waiting for its callback to be invoked; not
  143. * owned by event base any more. */
  144. /* elements used by the searching code */
  145. int search_index;
  146. struct search_state *search_state;
  147. char *search_origname; /* needs to be free()ed */
  148. int search_flags;
  149. };
  150. struct request {
  151. u8 *request; /* the dns packet data */
  152. u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
  153. unsigned int request_len;
  154. int reissue_count;
  155. int tx_count; /* the number of times that this packet has been sent */
  156. void *user_pointer; /* the pointer given to us for this request */
  157. evdns_callback_type user_callback;
  158. struct nameserver *ns; /* the server which we last sent it */
  159. /* these objects are kept in a circular list */
  160. /* XXX We could turn this into a CIRCLEQ. */
  161. struct request *next, *prev;
  162. struct event timeout_event;
  163. u16 trans_id; /* the transaction id */
  164. unsigned request_appended :1; /* true if the request pointer is data which follows this struct */
  165. unsigned transmit_me :1; /* needs to be transmitted */
  166. /* XXXX This is a horrible hack. */
  167. char **put_cname_in_ptr; /* store the cname here if we get one. */
  168. struct evdns_base *base;
  169. struct evdns_request *handle;
  170. };
  171. struct reply {
  172. unsigned int type;
  173. unsigned int have_answer : 1;
  174. union {
  175. struct {
  176. u32 addrcount;
  177. u32 addresses[MAX_V4_ADDRS];
  178. } a;
  179. struct {
  180. u32 addrcount;
  181. struct in6_addr addresses[MAX_V6_ADDRS];
  182. } aaaa;
  183. struct {
  184. char name[HOST_NAME_MAX];
  185. } ptr;
  186. } data;
  187. };
  188. struct nameserver {
  189. evutil_socket_t socket; /* a connected UDP socket */
  190. struct sockaddr_storage address;
  191. ev_socklen_t addrlen;
  192. int failed_times; /* number of times which we have given this server a chance */
  193. int timedout; /* number of times in a row a request has timed out */
  194. struct event event;
  195. /* these objects are kept in a circular list */
  196. struct nameserver *next, *prev;
  197. struct event timeout_event; /* used to keep the timeout for */
  198. /* when we next probe this server. */
  199. /* Valid if state == 0 */
  200. /* Outstanding probe request for this nameserver, if any */
  201. struct evdns_request *probe_request;
  202. char state; /* zero if we think that this server is down */
  203. char choked; /* true if we have an EAGAIN from this server's socket */
  204. char write_waiting; /* true if we are waiting for EV_WRITE events */
  205. struct evdns_base *base;
  206. /* Number of currently inflight requests: used
  207. * to track when we should add/del the event. */
  208. int requests_inflight;
  209. };
  210. /* Represents a local port where we're listening for DNS requests. Right now, */
  211. /* only UDP is supported. */
  212. struct evdns_server_port {
  213. evutil_socket_t socket; /* socket we use to read queries and write replies. */
  214. int refcnt; /* reference count. */
  215. char choked; /* Are we currently blocked from writing? */
  216. char closing; /* Are we trying to close this port, pending writes? */
  217. evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
  218. void *user_data; /* Opaque pointer passed to user_callback */
  219. struct event event; /* Read/write event */
  220. /* circular list of replies that we want to write. */
  221. struct server_request *pending_replies;
  222. struct event_base *event_base;
  223. #ifndef EVENT__DISABLE_THREAD_SUPPORT
  224. void *lock;
  225. #endif
  226. };
  227. /* Represents part of a reply being built. (That is, a single RR.) */
  228. struct server_reply_item {
  229. struct server_reply_item *next; /* next item in sequence. */
  230. char *name; /* name part of the RR */
  231. u16 type; /* The RR type */
  232. u16 class; /* The RR class (usually CLASS_INET) */
  233. u32 ttl; /* The RR TTL */
  234. char is_name; /* True iff data is a label */
  235. u16 datalen; /* Length of data; -1 if data is a label */
  236. void *data; /* The contents of the RR */
  237. };
  238. /* Represents a request that we've received as a DNS server, and holds */
  239. /* the components of the reply as we're constructing it. */
  240. struct server_request {
  241. /* Pointers to the next and previous entries on the list of replies */
  242. /* that we're waiting to write. Only set if we have tried to respond */
  243. /* and gotten EAGAIN. */
  244. struct server_request *next_pending;
  245. struct server_request *prev_pending;
  246. u16 trans_id; /* Transaction id. */
  247. struct evdns_server_port *port; /* Which port received this request on? */
  248. struct sockaddr_storage addr; /* Where to send the response */
  249. ev_socklen_t addrlen; /* length of addr */
  250. int n_answer; /* how many answer RRs have been set? */
  251. int n_authority; /* how many authority RRs have been set? */
  252. int n_additional; /* how many additional RRs have been set? */
  253. struct server_reply_item *answer; /* linked list of answer RRs */
  254. struct server_reply_item *authority; /* linked list of authority RRs */
  255. struct server_reply_item *additional; /* linked list of additional RRs */
  256. /* Constructed response. Only set once we're ready to send a reply. */
  257. /* Once this is set, the RR fields are cleared, and no more should be set. */
  258. char *response;
  259. size_t response_len;
  260. /* Caller-visible fields: flags, questions. */
  261. struct evdns_server_request base;
  262. };
  263. struct evdns_base {
  264. /* An array of n_req_heads circular lists for inflight requests.
  265. * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
  266. */
  267. struct request **req_heads;
  268. /* A circular list of requests that we're waiting to send, but haven't
  269. * sent yet because there are too many requests inflight */
  270. struct request *req_waiting_head;
  271. /* A circular list of nameservers. */
  272. struct nameserver *server_head;
  273. int n_req_heads;
  274. struct event_base *event_base;
  275. /* The number of good nameservers that we have */
  276. int global_good_nameservers;
  277. /* inflight requests are contained in the req_head list */
  278. /* and are actually going out across the network */
  279. int global_requests_inflight;
  280. /* requests which aren't inflight are in the waiting list */
  281. /* and are counted here */
  282. int global_requests_waiting;
  283. int global_max_requests_inflight;
  284. struct timeval global_timeout; /* 5 seconds by default */
  285. int global_max_reissues; /* a reissue occurs when we get some errors from the server */
  286. int global_max_retransmits; /* number of times we'll retransmit a request which timed out */
  287. /* number of timeouts in a row before we consider this server to be down */
  288. int global_max_nameserver_timeout;
  289. /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
  290. int global_randomize_case;
  291. /* The first time that a nameserver fails, how long do we wait before
  292. * probing to see if it has returned? */
  293. struct timeval global_nameserver_probe_initial_timeout;
  294. /** Port to bind to for outgoing DNS packets. */
  295. struct sockaddr_storage global_outgoing_address;
  296. /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
  297. ev_socklen_t global_outgoing_addrlen;
  298. struct timeval global_getaddrinfo_allow_skew;
  299. int so_rcvbuf;
  300. int so_sndbuf;
  301. int getaddrinfo_ipv4_timeouts;
  302. int getaddrinfo_ipv6_timeouts;
  303. int getaddrinfo_ipv4_answered;
  304. int getaddrinfo_ipv6_answered;
  305. struct search_state *global_search_state;
  306. TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
  307. #ifndef EVENT__DISABLE_THREAD_SUPPORT
  308. void *lock;
  309. #endif
  310. int disable_when_inactive;
  311. };
  312. struct hosts_entry {
  313. TAILQ_ENTRY(hosts_entry) next;
  314. union {
  315. struct sockaddr sa;
  316. struct sockaddr_in sin;
  317. struct sockaddr_in6 sin6;
  318. } addr;
  319. int addrlen;
  320. char hostname[1];
  321. };
  322. static struct evdns_base *current_base = NULL;
  323. struct evdns_base *
  324. evdns_get_global_base(void)
  325. {
  326. return current_base;
  327. }
  328. /* Given a pointer to an evdns_server_request, get the corresponding */
  329. /* server_request. */
  330. #define TO_SERVER_REQUEST(base_ptr) \
  331. ((struct server_request*) \
  332. (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
  333. #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
  334. static struct nameserver *nameserver_pick(struct evdns_base *base);
  335. static void evdns_request_insert(struct request *req, struct request **head);
  336. static void evdns_request_remove(struct request *req, struct request **head);
  337. static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
  338. static int evdns_transmit(struct evdns_base *base);
  339. static int evdns_request_transmit(struct request *req);
  340. static void nameserver_send_probe(struct nameserver *const ns);
  341. static void search_request_finished(struct evdns_request *const);
  342. static int search_try_next(struct evdns_request *const req);
  343. static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
  344. static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
  345. static u16 transaction_id_pick(struct evdns_base *base);
  346. static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
  347. static void request_submit(struct request *const req);
  348. static int server_request_free(struct server_request *req);
  349. static void server_request_free_answers(struct server_request *req);
  350. static void server_port_free(struct evdns_server_port *port);
  351. static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
  352. static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
  353. static int evdns_base_set_option_impl(struct evdns_base *base,
  354. const char *option, const char *val, int flags);
  355. static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
  356. static void evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg);
  357. static int strtoint(const char *const str);
  358. #ifdef EVENT__DISABLE_THREAD_SUPPORT
  359. #define EVDNS_LOCK(base) EVUTIL_NIL_STMT_
  360. #define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
  361. #define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
  362. #else
  363. #define EVDNS_LOCK(base) \
  364. EVLOCK_LOCK((base)->lock, 0)
  365. #define EVDNS_UNLOCK(base) \
  366. EVLOCK_UNLOCK((base)->lock, 0)
  367. #define ASSERT_LOCKED(base) \
  368. EVLOCK_ASSERT_LOCKED((base)->lock)
  369. #endif
  370. static evdns_debug_log_fn_type evdns_log_fn = NULL;
  371. void
  372. evdns_set_log_fn(evdns_debug_log_fn_type fn)
  373. {
  374. evdns_log_fn = fn;
  375. }
  376. #ifdef __GNUC__
  377. #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
  378. #else
  379. #define EVDNS_LOG_CHECK
  380. #endif
  381. static void evdns_log_(int severity, const char *fmt, ...) EVDNS_LOG_CHECK;
  382. static void
  383. evdns_log_(int severity, const char *fmt, ...)
  384. {
  385. va_list args;
  386. va_start(args,fmt);
  387. if (evdns_log_fn) {
  388. char buf[512];
  389. int is_warn = (severity == EVDNS_LOG_WARN);
  390. evutil_vsnprintf(buf, sizeof(buf), fmt, args);
  391. evdns_log_fn(is_warn, buf);
  392. } else {
  393. event_logv_(severity, NULL, fmt, args);
  394. }
  395. va_end(args);
  396. }
  397. #define log evdns_log_
  398. /* This walks the list of inflight requests to find the */
  399. /* one with a matching transaction id. Returns NULL on */
  400. /* failure */
  401. static struct request *
  402. request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
  403. struct request *req = REQ_HEAD(base, trans_id);
  404. struct request *const started_at = req;
  405. ASSERT_LOCKED(base);
  406. if (req) {
  407. do {
  408. if (req->trans_id == trans_id) return req;
  409. req = req->next;
  410. } while (req != started_at);
  411. }
  412. return NULL;
  413. }
  414. /* a libevent callback function which is called when a nameserver */
  415. /* has gone down and we want to test if it has came back to life yet */
  416. static void
  417. nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
  418. struct nameserver *const ns = (struct nameserver *) arg;
  419. (void)fd;
  420. (void)events;
  421. EVDNS_LOCK(ns->base);
  422. nameserver_send_probe(ns);
  423. EVDNS_UNLOCK(ns->base);
  424. }
  425. /* a libevent callback which is called when a nameserver probe (to see if */
  426. /* it has come back to life) times out. We increment the count of failed_times */
  427. /* and wait longer to send the next probe packet. */
  428. static void
  429. nameserver_probe_failed(struct nameserver *const ns) {
  430. struct timeval timeout;
  431. int i;
  432. ASSERT_LOCKED(ns->base);
  433. (void) evtimer_del(&ns->timeout_event);
  434. if (ns->state == 1) {
  435. /* This can happen if the nameserver acts in a way which makes us mark */
  436. /* it as bad and then starts sending good replies. */
  437. return;
  438. }
  439. #define MAX_PROBE_TIMEOUT 3600
  440. #define TIMEOUT_BACKOFF_FACTOR 3
  441. memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
  442. sizeof(struct timeval));
  443. for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
  444. timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
  445. timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
  446. if (timeout.tv_usec > 1000000) {
  447. timeout.tv_sec += timeout.tv_usec / 1000000;
  448. timeout.tv_usec %= 1000000;
  449. }
  450. }
  451. if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
  452. timeout.tv_sec = MAX_PROBE_TIMEOUT;
  453. timeout.tv_usec = 0;
  454. }
  455. ns->failed_times++;
  456. if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
  457. char addrbuf[128];
  458. log(EVDNS_LOG_WARN,
  459. "Error from libevent when adding timer event for %s",
  460. evutil_format_sockaddr_port_(
  461. (struct sockaddr *)&ns->address,
  462. addrbuf, sizeof(addrbuf)));
  463. }
  464. }
  465. static void
  466. request_swap_ns(struct request *req, struct nameserver *ns) {
  467. if (ns && req->ns != ns) {
  468. EVUTIL_ASSERT(req->ns->requests_inflight > 0);
  469. req->ns->requests_inflight--;
  470. ns->requests_inflight++;
  471. req->ns = ns;
  472. }
  473. }
  474. /* called when a nameserver has been deemed to have failed. For example, too */
  475. /* many packets have timed out etc */
  476. static void
  477. nameserver_failed(struct nameserver *const ns, const char *msg) {
  478. struct request *req, *started_at;
  479. struct evdns_base *base = ns->base;
  480. int i;
  481. char addrbuf[128];
  482. ASSERT_LOCKED(base);
  483. /* if this nameserver has already been marked as failed */
  484. /* then don't do anything */
  485. if (!ns->state) return;
  486. log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
  487. evutil_format_sockaddr_port_(
  488. (struct sockaddr *)&ns->address,
  489. addrbuf, sizeof(addrbuf)),
  490. msg);
  491. base->global_good_nameservers--;
  492. EVUTIL_ASSERT(base->global_good_nameservers >= 0);
  493. if (base->global_good_nameservers == 0) {
  494. log(EVDNS_LOG_MSG, "All nameservers have failed");
  495. }
  496. ns->state = 0;
  497. ns->failed_times = 1;
  498. if (evtimer_add(&ns->timeout_event,
  499. &base->global_nameserver_probe_initial_timeout) < 0) {
  500. log(EVDNS_LOG_WARN,
  501. "Error from libevent when adding timer event for %s",
  502. evutil_format_sockaddr_port_(
  503. (struct sockaddr *)&ns->address,
  504. addrbuf, sizeof(addrbuf)));
  505. /* ???? Do more? */
  506. }
  507. /* walk the list of inflight requests to see if any can be reassigned to */
  508. /* a different server. Requests in the waiting queue don't have a */
  509. /* nameserver assigned yet */
  510. /* if we don't have *any* good nameservers then there's no point */
  511. /* trying to reassign requests to one */
  512. if (!base->global_good_nameservers) return;
  513. for (i = 0; i < base->n_req_heads; ++i) {
  514. req = started_at = base->req_heads[i];
  515. if (req) {
  516. do {
  517. if (req->tx_count == 0 && req->ns == ns) {
  518. /* still waiting to go out, can be moved */
  519. /* to another server */
  520. request_swap_ns(req, nameserver_pick(base));
  521. }
  522. req = req->next;
  523. } while (req != started_at);
  524. }
  525. }
  526. }
  527. static void
  528. nameserver_up(struct nameserver *const ns)
  529. {
  530. char addrbuf[128];
  531. ASSERT_LOCKED(ns->base);
  532. if (ns->state) return;
  533. log(EVDNS_LOG_MSG, "Nameserver %s is back up",
  534. evutil_format_sockaddr_port_(
  535. (struct sockaddr *)&ns->address,
  536. addrbuf, sizeof(addrbuf)));
  537. evtimer_del(&ns->timeout_event);
  538. if (ns->probe_request) {
  539. evdns_cancel_request(ns->base, ns->probe_request);
  540. ns->probe_request = NULL;
  541. }
  542. ns->state = 1;
  543. ns->failed_times = 0;
  544. ns->timedout = 0;
  545. ns->base->global_good_nameservers++;
  546. }
  547. static void
  548. request_trans_id_set(struct request *const req, const u16 trans_id) {
  549. req->trans_id = trans_id;
  550. *((u16 *) req->request) = htons(trans_id);
  551. }
  552. /* Called to remove a request from a list and dealloc it. */
  553. /* head is a pointer to the head of the list it should be */
  554. /* removed from or NULL if the request isn't in a list. */
  555. /* when free_handle is one, free the handle as well. */
  556. static void
  557. request_finished(struct request *const req, struct request **head, int free_handle) {
  558. struct evdns_base *base = req->base;
  559. int was_inflight = (head != &base->req_waiting_head);
  560. EVDNS_LOCK(base);
  561. ASSERT_VALID_REQUEST(req);
  562. if (head)
  563. evdns_request_remove(req, head);
  564. log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
  565. if (was_inflight) {
  566. evtimer_del(&req->timeout_event);
  567. base->global_requests_inflight--;
  568. req->ns->requests_inflight--;
  569. } else {
  570. base->global_requests_waiting--;
  571. }
  572. /* it was initialized during request_new / evtimer_assign */
  573. event_debug_unassign(&req->timeout_event);
  574. if (req->ns &&
  575. req->ns->requests_inflight == 0 &&
  576. req->base->disable_when_inactive) {
  577. event_del(&req->ns->event);
  578. evtimer_del(&req->ns->timeout_event);
  579. }
  580. if (!req->request_appended) {
  581. /* need to free the request data on it's own */
  582. mm_free(req->request);
  583. } else {
  584. /* the request data is appended onto the header */
  585. /* so everything gets free()ed when we: */
  586. }
  587. if (req->handle) {
  588. EVUTIL_ASSERT(req->handle->current_req == req);
  589. if (free_handle) {
  590. search_request_finished(req->handle);
  591. req->handle->current_req = NULL;
  592. if (! req->handle->pending_cb) {
  593. /* If we're planning to run the callback,
  594. * don't free the handle until later. */
  595. mm_free(req->handle);
  596. }
  597. req->handle = NULL; /* If we have a bug, let's crash
  598. * early */
  599. } else {
  600. req->handle->current_req = NULL;
  601. }
  602. }
  603. mm_free(req);
  604. evdns_requests_pump_waiting_queue(base);
  605. EVDNS_UNLOCK(base);
  606. }
  607. /* This is called when a server returns a funny error code. */
  608. /* We try the request again with another server. */
  609. /* */
  610. /* return: */
  611. /* 0 ok */
  612. /* 1 failed/reissue is pointless */
  613. static int
  614. request_reissue(struct request *req) {
  615. const struct nameserver *const last_ns = req->ns;
  616. ASSERT_LOCKED(req->base);
  617. ASSERT_VALID_REQUEST(req);
  618. /* the last nameserver should have been marked as failing */
  619. /* by the caller of this function, therefore pick will try */
  620. /* not to return it */
  621. request_swap_ns(req, nameserver_pick(req->base));
  622. if (req->ns == last_ns) {
  623. /* ... but pick did return it */
  624. /* not a lot of point in trying again with the */
  625. /* same server */
  626. return 1;
  627. }
  628. req->reissue_count++;
  629. req->tx_count = 0;
  630. req->transmit_me = 1;
  631. return 0;
  632. }
  633. /* this function looks for space on the inflight queue and promotes */
  634. /* requests from the waiting queue if it can. */
  635. /* */
  636. /* TODO: */
  637. /* add return code, see at nameserver_pick() and other functions. */
  638. static void
  639. evdns_requests_pump_waiting_queue(struct evdns_base *base) {
  640. ASSERT_LOCKED(base);
  641. while (base->global_requests_inflight < base->global_max_requests_inflight &&
  642. base->global_requests_waiting) {
  643. struct request *req;
  644. EVUTIL_ASSERT(base->req_waiting_head);
  645. req = base->req_waiting_head;
  646. req->ns = nameserver_pick(base);
  647. if (!req->ns)
  648. return;
  649. /* move a request from the waiting queue to the inflight queue */
  650. req->ns->requests_inflight++;
  651. evdns_request_remove(req, &base->req_waiting_head);
  652. base->global_requests_waiting--;
  653. base->global_requests_inflight++;
  654. request_trans_id_set(req, transaction_id_pick(base));
  655. evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
  656. evdns_request_transmit(req);
  657. evdns_transmit(base);
  658. }
  659. }
  660. /* TODO(nickm) document */
  661. struct deferred_reply_callback {
  662. struct event_callback deferred;
  663. struct evdns_request *handle;
  664. u8 request_type;
  665. u8 have_reply;
  666. u32 ttl;
  667. u32 err;
  668. evdns_callback_type user_callback;
  669. struct reply reply;
  670. };
  671. static void
  672. reply_run_callback(struct event_callback *d, void *user_pointer)
  673. {
  674. struct deferred_reply_callback *cb =
  675. EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
  676. switch (cb->request_type) {
  677. case TYPE_A:
  678. if (cb->have_reply)
  679. cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
  680. cb->reply.data.a.addrcount, cb->ttl,
  681. cb->reply.data.a.addresses,
  682. user_pointer);
  683. else
  684. cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
  685. break;
  686. case TYPE_PTR:
  687. if (cb->have_reply) {
  688. char *name = cb->reply.data.ptr.name;
  689. cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
  690. &name, user_pointer);
  691. } else {
  692. cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
  693. }
  694. break;
  695. case TYPE_AAAA:
  696. if (cb->have_reply)
  697. cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
  698. cb->reply.data.aaaa.addrcount, cb->ttl,
  699. cb->reply.data.aaaa.addresses,
  700. user_pointer);
  701. else
  702. cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
  703. break;
  704. default:
  705. EVUTIL_ASSERT(0);
  706. }
  707. if (cb->handle && cb->handle->pending_cb) {
  708. mm_free(cb->handle);
  709. }
  710. mm_free(cb);
  711. }
  712. static void
  713. reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
  714. {
  715. struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
  716. if (!d) {
  717. event_warn("%s: Couldn't allocate space for deferred callback.",
  718. __func__);
  719. return;
  720. }
  721. ASSERT_LOCKED(req->base);
  722. d->request_type = req->request_type;
  723. d->user_callback = req->user_callback;
  724. d->ttl = ttl;
  725. d->err = err;
  726. if (reply) {
  727. d->have_reply = 1;
  728. memcpy(&d->reply, reply, sizeof(struct reply));
  729. }
  730. if (req->handle) {
  731. req->handle->pending_cb = 1;
  732. d->handle = req->handle;
  733. }
  734. event_deferred_cb_init_(
  735. &d->deferred,
  736. event_get_priority(&req->timeout_event),
  737. reply_run_callback,
  738. req->user_pointer);
  739. event_deferred_cb_schedule_(
  740. req->base->event_base,
  741. &d->deferred);
  742. }
  743. #define _QR_MASK 0x8000U
  744. #define _OP_MASK 0x7800U
  745. #define _AA_MASK 0x0400U
  746. #define _TC_MASK 0x0200U
  747. #define _RD_MASK 0x0100U
  748. #define _RA_MASK 0x0080U
  749. #define _Z_MASK 0x0040U
  750. #define _AD_MASK 0x0020U
  751. #define _CD_MASK 0x0010U
  752. #define _RCODE_MASK 0x000fU
  753. #define _Z_MASK_DEPRECATED 0x0070U
  754. /* this processes a parsed reply packet */
  755. static void
  756. reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
  757. int error;
  758. char addrbuf[128];
  759. static const int error_codes[] = {
  760. DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
  761. DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
  762. };
  763. ASSERT_LOCKED(req->base);
  764. ASSERT_VALID_REQUEST(req);
  765. if (flags & (_RCODE_MASK | _TC_MASK) || !reply || !reply->have_answer) {
  766. /* there was an error */
  767. if (flags & _TC_MASK) {
  768. error = DNS_ERR_TRUNCATED;
  769. } else if (flags & _RCODE_MASK) {
  770. u16 error_code = (flags & _RCODE_MASK) - 1;
  771. if (error_code > 4) {
  772. error = DNS_ERR_UNKNOWN;
  773. } else {
  774. error = error_codes[error_code];
  775. }
  776. } else if (reply && !reply->have_answer) {
  777. error = DNS_ERR_NODATA;
  778. } else {
  779. error = DNS_ERR_UNKNOWN;
  780. }
  781. switch (error) {
  782. case DNS_ERR_NOTIMPL:
  783. case DNS_ERR_REFUSED:
  784. /* we regard these errors as marking a bad nameserver */
  785. if (req->reissue_count < req->base->global_max_reissues) {
  786. char msg[64];
  787. evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
  788. error, evdns_err_to_string(error));
  789. nameserver_failed(req->ns, msg);
  790. if (!request_reissue(req)) return;
  791. }
  792. break;
  793. case DNS_ERR_SERVERFAILED:
  794. /* rcode 2 (servfailed) sometimes means "we
  795. * are broken" and sometimes (with some binds)
  796. * means "that request was very confusing."
  797. * Treat this as a timeout, not a failure.
  798. */
  799. log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
  800. "at %s; will allow the request to time out.",
  801. evutil_format_sockaddr_port_(
  802. (struct sockaddr *)&req->ns->address,
  803. addrbuf, sizeof(addrbuf)));
  804. /* Call the timeout function */
  805. evdns_request_timeout_callback(0, 0, req);
  806. return;
  807. default:
  808. /* we got a good reply from the nameserver: it is up. */
  809. if (req->handle == req->ns->probe_request) {
  810. /* Avoid double-free */
  811. req->ns->probe_request = NULL;
  812. }
  813. nameserver_up(req->ns);
  814. }
  815. if (req->handle->search_state &&
  816. req->request_type != TYPE_PTR) {
  817. /* if we have a list of domains to search in,
  818. * try the next one */
  819. if (!search_try_next(req->handle)) {
  820. /* a new request was issued so this
  821. * request is finished and */
  822. /* the user callback will be made when
  823. * that request (or a */
  824. /* child of it) finishes. */
  825. return;
  826. }
  827. }
  828. /* all else failed. Pass the failure up */
  829. reply_schedule_callback(req, ttl, error, NULL);
  830. request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
  831. } else {
  832. /* all ok, tell the user */
  833. reply_schedule_callback(req, ttl, 0, reply);
  834. if (req->handle == req->ns->probe_request)
  835. req->ns->probe_request = NULL; /* Avoid double-free */
  836. nameserver_up(req->ns);
  837. request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
  838. }
  839. }
  840. static int
  841. name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
  842. int name_end = -1;
  843. int j = *idx;
  844. int ptr_count = 0;
  845. #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
  846. #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
  847. #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
  848. char *cp = name_out;
  849. const char *const end = name_out + name_out_len;
  850. /* Normally, names are a series of length prefixed strings terminated */
  851. /* with a length of 0 (the lengths are u8's < 63). */
  852. /* However, the length can start with a pair of 1 bits and that */
  853. /* means that the next 14 bits are a pointer within the current */
  854. /* packet. */
  855. for (;;) {
  856. u8 label_len;
  857. GET8(label_len);
  858. if (!label_len) break;
  859. if (label_len & 0xc0) {
  860. u8 ptr_low;
  861. GET8(ptr_low);
  862. if (name_end < 0) name_end = j;
  863. j = (((int)label_len & 0x3f) << 8) + ptr_low;
  864. /* Make sure that the target offset is in-bounds. */
  865. if (j < 0 || j >= length) return -1;
  866. /* If we've jumped more times than there are characters in the
  867. * message, we must have a loop. */
  868. if (++ptr_count > length) return -1;
  869. continue;
  870. }
  871. if (label_len > 63) return -1;
  872. if (cp != name_out) {
  873. if (cp + 1 >= end) return -1;
  874. *cp++ = '.';
  875. }
  876. if (cp + label_len >= end) return -1;
  877. if (j + label_len > length) return -1;
  878. memcpy(cp, packet + j, label_len);
  879. cp += label_len;
  880. j += label_len;
  881. }
  882. if (cp >= end) return -1;
  883. *cp = '\0';
  884. if (name_end < 0)
  885. *idx = j;
  886. else
  887. *idx = name_end;
  888. return 0;
  889. err:
  890. return -1;
  891. }
  892. /* parses a raw request from a nameserver */
  893. static int
  894. reply_parse(struct evdns_base *base, u8 *packet, int length) {
  895. int j = 0, k = 0; /* index into packet */
  896. u16 t_; /* used by the macros */
  897. u32 t32_; /* used by the macros */
  898. char tmp_name[256], cmp_name[256]; /* used by the macros */
  899. int name_matches = 0;
  900. u16 trans_id, questions, answers, authority, additional, datalength;
  901. u16 flags = 0;
  902. u32 ttl, ttl_r = 0xffffffff;
  903. struct reply reply;
  904. struct request *req = NULL;
  905. unsigned int i;
  906. ASSERT_LOCKED(base);
  907. GET16(trans_id);
  908. GET16(flags);
  909. GET16(questions);
  910. GET16(answers);
  911. GET16(authority);
  912. GET16(additional);
  913. (void) authority; /* suppress "unused variable" warnings. */
  914. (void) additional; /* suppress "unused variable" warnings. */
  915. req = request_find_from_trans_id(base, trans_id);
  916. if (!req) return -1;
  917. EVUTIL_ASSERT(req->base == base);
  918. memset(&reply, 0, sizeof(reply));
  919. /* If it's not an answer, it doesn't correspond to any request. */
  920. if (!(flags & _QR_MASK)) return -1; /* must be an answer */
  921. if ((flags & (_RCODE_MASK|_TC_MASK)) && (flags & (_RCODE_MASK|_TC_MASK)) != DNS_ERR_NOTEXIST) {
  922. /* there was an error and it's not NXDOMAIN */
  923. goto err;
  924. }
  925. /* if (!answers) return; */ /* must have an answer of some form */
  926. /* This macro skips a name in the DNS reply. */
  927. #define SKIP_NAME \
  928. do { tmp_name[0] = '\0'; \
  929. if (name_parse(packet, length, &j, tmp_name, \
  930. sizeof(tmp_name))<0) \
  931. goto err; \
  932. } while (0)
  933. reply.type = req->request_type;
  934. /* skip over each question in the reply */
  935. for (i = 0; i < questions; ++i) {
  936. /* the question looks like
  937. * <label:name><u16:type><u16:class>
  938. */
  939. tmp_name[0] = '\0';
  940. cmp_name[0] = '\0';
  941. k = j;
  942. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name)) < 0)
  943. goto err;
  944. if (name_parse(req->request, req->request_len, &k,
  945. cmp_name, sizeof(cmp_name))<0)
  946. goto err;
  947. if (!base->global_randomize_case) {
  948. if (strcmp(tmp_name, cmp_name) == 0)
  949. name_matches = 1;
  950. } else {
  951. if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0)
  952. name_matches = 1;
  953. }
  954. j += 4;
  955. if (j > length)
  956. goto err;
  957. }
  958. if (!name_matches)
  959. goto err;
  960. /* now we have the answer section which looks like
  961. * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
  962. */
  963. for (i = 0; i < answers; ++i) {
  964. u16 type, class;
  965. SKIP_NAME;
  966. GET16(type);
  967. GET16(class);
  968. GET32(ttl);
  969. GET16(datalength);
  970. if (type == TYPE_A && class == CLASS_INET) {
  971. int addrcount, addrtocopy;
  972. if (req->request_type != TYPE_A) {
  973. j += datalength; continue;
  974. }
  975. if ((datalength & 3) != 0) /* not an even number of As. */
  976. goto err;
  977. addrcount = datalength >> 2;
  978. addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
  979. ttl_r = MIN(ttl_r, ttl);
  980. /* we only bother with the first four addresses. */
  981. if (j + 4*addrtocopy > length) goto err;
  982. memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
  983. packet + j, 4*addrtocopy);
  984. j += 4*addrtocopy;
  985. reply.data.a.addrcount += addrtocopy;
  986. reply.have_answer = 1;
  987. if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
  988. } else if (type == TYPE_PTR && class == CLASS_INET) {
  989. if (req->request_type != TYPE_PTR) {
  990. j += datalength; continue;
  991. }
  992. if (name_parse(packet, length, &j, reply.data.ptr.name,
  993. sizeof(reply.data.ptr.name))<0)
  994. goto err;
  995. ttl_r = MIN(ttl_r, ttl);
  996. reply.have_answer = 1;
  997. break;
  998. } else if (type == TYPE_CNAME) {
  999. char cname[HOST_NAME_MAX];
  1000. if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
  1001. j += datalength; continue;
  1002. }
  1003. if (name_parse(packet, length, &j, cname,
  1004. sizeof(cname))<0)
  1005. goto err;
  1006. *req->put_cname_in_ptr = mm_strdup(cname);
  1007. } else if (type == TYPE_AAAA && class == CLASS_INET) {
  1008. int addrcount, addrtocopy;
  1009. if (req->request_type != TYPE_AAAA) {
  1010. j += datalength; continue;
  1011. }
  1012. if ((datalength & 15) != 0) /* not an even number of AAAAs. */
  1013. goto err;
  1014. addrcount = datalength >> 4; /* each address is 16 bytes long */
  1015. addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
  1016. ttl_r = MIN(ttl_r, ttl);
  1017. /* we only bother with the first four addresses. */
  1018. if (j + 16*addrtocopy > length) goto err;
  1019. memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
  1020. packet + j, 16*addrtocopy);
  1021. reply.data.aaaa.addrcount += addrtocopy;
  1022. j += 16*addrtocopy;
  1023. reply.have_answer = 1;
  1024. if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
  1025. } else {
  1026. /* skip over any other type of resource */
  1027. j += datalength;
  1028. }
  1029. }
  1030. if (!reply.have_answer) {
  1031. for (i = 0; i < authority; ++i) {
  1032. u16 type, class;
  1033. SKIP_NAME;
  1034. GET16(type);
  1035. GET16(class);
  1036. GET32(ttl);
  1037. GET16(datalength);
  1038. if (type == TYPE_SOA && class == CLASS_INET) {
  1039. u32 serial, refresh, retry, expire, minimum;
  1040. SKIP_NAME;
  1041. SKIP_NAME;
  1042. GET32(serial);
  1043. GET32(refresh);
  1044. GET32(retry);
  1045. GET32(expire);
  1046. GET32(minimum);
  1047. (void)expire;
  1048. (void)retry;
  1049. (void)refresh;
  1050. (void)serial;
  1051. ttl_r = MIN(ttl_r, ttl);
  1052. ttl_r = MIN(ttl_r, minimum);
  1053. } else {
  1054. /* skip over any other type of resource */
  1055. j += datalength;
  1056. }
  1057. }
  1058. }
  1059. if (ttl_r == 0xffffffff)
  1060. ttl_r = 0;
  1061. reply_handle(req, flags, ttl_r, &reply);
  1062. return 0;
  1063. err:
  1064. if (req)
  1065. reply_handle(req, flags, 0, NULL);
  1066. return -1;
  1067. }
  1068. /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
  1069. /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
  1070. /* callback. */
  1071. static int
  1072. request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
  1073. {
  1074. int j = 0; /* index into packet */
  1075. u16 t_; /* used by the macros */
  1076. char tmp_name[256]; /* used by the macros */
  1077. int i;
  1078. u16 trans_id, flags, questions, answers, authority, additional;
  1079. struct server_request *server_req = NULL;
  1080. ASSERT_LOCKED(port);
  1081. /* Get the header fields */
  1082. GET16(trans_id);
  1083. GET16(flags);
  1084. GET16(questions);
  1085. GET16(answers);
  1086. GET16(authority);
  1087. GET16(additional);
  1088. (void)answers;
  1089. (void)additional;
  1090. (void)authority;
  1091. if (flags & _QR_MASK) return -1; /* Must not be an answer. */
  1092. flags &= (_RD_MASK|_CD_MASK); /* Only RD and CD get preserved. */
  1093. server_req = mm_malloc(sizeof(struct server_request));
  1094. if (server_req == NULL) return -1;
  1095. memset(server_req, 0, sizeof(struct server_request));
  1096. server_req->trans_id = trans_id;
  1097. memcpy(&server_req->addr, addr, addrlen);
  1098. server_req->addrlen = addrlen;
  1099. server_req->base.flags = flags;
  1100. server_req->base.nquestions = 0;
  1101. server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
  1102. if (server_req->base.questions == NULL)
  1103. goto err;
  1104. for (i = 0; i < questions; ++i) {
  1105. u16 type, class;
  1106. struct evdns_server_question *q;
  1107. int namelen;
  1108. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
  1109. goto err;
  1110. GET16(type);
  1111. GET16(class);
  1112. namelen = (int)strlen(tmp_name);
  1113. q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
  1114. if (!q)
  1115. goto err;
  1116. q->type = type;
  1117. q->dns_question_class = class;
  1118. memcpy(q->name, tmp_name, namelen+1);
  1119. server_req->base.questions[server_req->base.nquestions++] = q;
  1120. }
  1121. /* Ignore answers, authority, and additional. */
  1122. server_req->port = port;
  1123. port->refcnt++;
  1124. /* Only standard queries are supported. */
  1125. if (flags & _OP_MASK) {
  1126. evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
  1127. return -1;
  1128. }
  1129. port->user_callback(&(server_req->base), port->user_data);
  1130. return 0;
  1131. err:
  1132. if (server_req->base.questions) {
  1133. for (i = 0; i < server_req->base.nquestions; ++i)
  1134. mm_free(server_req->base.questions[i]);
  1135. mm_free(server_req->base.questions);
  1136. }
  1137. mm_free(server_req);
  1138. return -1;
  1139. #undef SKIP_NAME
  1140. #undef GET32
  1141. #undef GET16
  1142. #undef GET8
  1143. }
  1144. void
  1145. evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
  1146. {
  1147. }
  1148. void
  1149. evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
  1150. {
  1151. }
  1152. /* Try to choose a strong transaction id which isn't already in flight */
  1153. static u16
  1154. transaction_id_pick(struct evdns_base *base) {
  1155. ASSERT_LOCKED(base);
  1156. for (;;) {
  1157. u16 trans_id;
  1158. evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
  1159. if (trans_id == 0xffff) continue;
  1160. /* now check to see if that id is already inflight */
  1161. if (request_find_from_trans_id(base, trans_id) == NULL)
  1162. return trans_id;
  1163. }
  1164. }
  1165. /* choose a namesever to use. This function will try to ignore */
  1166. /* nameservers which we think are down and load balance across the rest */
  1167. /* by updating the server_head global each time. */
  1168. static struct nameserver *
  1169. nameserver_pick(struct evdns_base *base) {
  1170. struct nameserver *started_at = base->server_head, *picked;
  1171. ASSERT_LOCKED(base);
  1172. if (!base->server_head) return NULL;
  1173. /* if we don't have any good nameservers then there's no */
  1174. /* point in trying to find one. */
  1175. if (!base->global_good_nameservers) {
  1176. base->server_head = base->server_head->next;
  1177. return base->server_head;
  1178. }
  1179. /* remember that nameservers are in a circular list */
  1180. for (;;) {
  1181. if (base->server_head->state) {
  1182. /* we think this server is currently good */
  1183. picked = base->server_head;
  1184. base->server_head = base->server_head->next;
  1185. return picked;
  1186. }
  1187. base->server_head = base->server_head->next;
  1188. if (base->server_head == started_at) {
  1189. /* all the nameservers seem to be down */
  1190. /* so we just return this one and hope for the */
  1191. /* best */
  1192. EVUTIL_ASSERT(base->global_good_nameservers == 0);
  1193. picked = base->server_head;
  1194. base->server_head = base->server_head->next;
  1195. return picked;
  1196. }
  1197. }
  1198. }
  1199. /* this is called when a namesever socket is ready for reading */
  1200. static void
  1201. nameserver_read(struct nameserver *ns) {
  1202. struct sockaddr_storage ss;
  1203. ev_socklen_t addrlen = sizeof(ss);
  1204. u8 packet[1500];
  1205. char addrbuf[128];
  1206. ASSERT_LOCKED(ns->base);
  1207. for (;;) {
  1208. const int r = recvfrom(ns->socket, (void*)packet,
  1209. sizeof(packet), 0,
  1210. (struct sockaddr*)&ss, &addrlen);
  1211. if (r < 0) {
  1212. int err = evutil_socket_geterror(ns->socket);
  1213. if (EVUTIL_ERR_RW_RETRIABLE(err))
  1214. return;
  1215. nameserver_failed(ns,
  1216. evutil_socket_error_to_string(err));
  1217. return;
  1218. }
  1219. if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
  1220. (struct sockaddr*)&ns->address, 0)) {
  1221. log(EVDNS_LOG_WARN, "Address mismatch on received "
  1222. "DNS packet. Apparent source was %s",
  1223. evutil_format_sockaddr_port_(
  1224. (struct sockaddr *)&ss,
  1225. addrbuf, sizeof(addrbuf)));
  1226. return;
  1227. }
  1228. ns->timedout = 0;
  1229. reply_parse(ns->base, packet, r);
  1230. }
  1231. }
  1232. /* Read a packet from a DNS client on a server port s, parse it, and */
  1233. /* act accordingly. */
  1234. static void
  1235. server_port_read(struct evdns_server_port *s) {
  1236. u8 packet[1500];
  1237. struct sockaddr_storage addr;
  1238. ev_socklen_t addrlen;
  1239. int r;
  1240. ASSERT_LOCKED(s);
  1241. for (;;) {
  1242. addrlen = sizeof(struct sockaddr_storage);
  1243. r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
  1244. (struct sockaddr*) &addr, &addrlen);
  1245. if (r < 0) {
  1246. int err = evutil_socket_geterror(s->socket);
  1247. if (EVUTIL_ERR_RW_RETRIABLE(err))
  1248. return;
  1249. log(EVDNS_LOG_WARN,
  1250. "Error %s (%d) while reading request.",
  1251. evutil_socket_error_to_string(err), err);
  1252. return;
  1253. }
  1254. request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
  1255. }
  1256. }
  1257. /* Try to write all pending replies on a given DNS server port. */
  1258. static void
  1259. server_port_flush(struct evdns_server_port *port)
  1260. {
  1261. struct server_request *req = port->pending_replies;
  1262. ASSERT_LOCKED(port);
  1263. while (req) {
  1264. int r = sendto(port->socket, req->response, (int)req->response_len, 0,
  1265. (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
  1266. if (r < 0) {
  1267. int err = evutil_socket_geterror(port->socket);
  1268. if (EVUTIL_ERR_RW_RETRIABLE(err))
  1269. return;
  1270. log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
  1271. }
  1272. if (server_request_free(req)) {
  1273. /* we released the last reference to req->port. */
  1274. return;
  1275. } else {
  1276. EVUTIL_ASSERT(req != port->pending_replies);
  1277. req = port->pending_replies;
  1278. }
  1279. }
  1280. /* We have no more pending requests; stop listening for 'writeable' events. */
  1281. (void) event_del(&port->event);
  1282. event_assign(&port->event, port->event_base,
  1283. port->socket, EV_READ | EV_PERSIST,
  1284. server_port_ready_callback, port);
  1285. if (event_add(&port->event, NULL) < 0) {
  1286. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
  1287. /* ???? Do more? */
  1288. }
  1289. }
  1290. /* set if we are waiting for the ability to write to this server. */
  1291. /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
  1292. /* we stop these events. */
  1293. static void
  1294. nameserver_write_waiting(struct nameserver *ns, char waiting) {
  1295. ASSERT_LOCKED(ns->base);
  1296. if (ns->write_waiting == waiting) return;
  1297. ns->write_waiting = waiting;
  1298. (void) event_del(&ns->event);
  1299. event_assign(&ns->event, ns->base->event_base,
  1300. ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
  1301. nameserver_ready_callback, ns);
  1302. if (event_add(&ns->event, NULL) < 0) {
  1303. char addrbuf[128];
  1304. log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
  1305. evutil_format_sockaddr_port_(
  1306. (struct sockaddr *)&ns->address,
  1307. addrbuf, sizeof(addrbuf)));
  1308. /* ???? Do more? */
  1309. }
  1310. }
  1311. /* a callback function. Called by libevent when the kernel says that */
  1312. /* a nameserver socket is ready for writing or reading */
  1313. static void
  1314. nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
  1315. struct nameserver *ns = (struct nameserver *) arg;
  1316. (void)fd;
  1317. EVDNS_LOCK(ns->base);
  1318. if (events & EV_WRITE) {
  1319. ns->choked = 0;
  1320. if (!evdns_transmit(ns->base)) {
  1321. nameserver_write_waiting(ns, 0);
  1322. }
  1323. }
  1324. if (events & EV_READ) {
  1325. nameserver_read(ns);
  1326. }
  1327. EVDNS_UNLOCK(ns->base);
  1328. }
  1329. /* a callback function. Called by libevent when the kernel says that */
  1330. /* a server socket is ready for writing or reading. */
  1331. static void
  1332. server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
  1333. struct evdns_server_port *port = (struct evdns_server_port *) arg;
  1334. (void) fd;
  1335. EVDNS_LOCK(port);
  1336. if (events & EV_WRITE) {
  1337. port->choked = 0;
  1338. server_port_flush(port);
  1339. }
  1340. if (events & EV_READ) {
  1341. server_port_read(port);
  1342. }
  1343. EVDNS_UNLOCK(port);
  1344. }
  1345. /* This is an inefficient representation; only use it via the dnslabel_table_*
  1346. * functions, so that is can be safely replaced with something smarter later. */
  1347. #define MAX_LABELS 128
  1348. /* Structures used to implement name compression */
  1349. struct dnslabel_entry { char *v; off_t pos; };
  1350. struct dnslabel_table {
  1351. int n_labels; /* number of current entries */
  1352. /* map from name to position in message */
  1353. struct dnslabel_entry labels[MAX_LABELS];
  1354. };
  1355. /* Initialize dnslabel_table. */
  1356. static void
  1357. dnslabel_table_init(struct dnslabel_table *table)
  1358. {
  1359. table->n_labels = 0;
  1360. }
  1361. /* Free all storage held by table, but not the table itself. */
  1362. static void
  1363. dnslabel_clear(struct dnslabel_table *table)
  1364. {
  1365. int i;
  1366. for (i = 0; i < table->n_labels; ++i)
  1367. mm_free(table->labels[i].v);
  1368. table->n_labels = 0;
  1369. }
  1370. /* return the position of the label in the current message, or -1 if the label */
  1371. /* hasn't been used yet. */
  1372. static int
  1373. dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
  1374. {
  1375. int i;
  1376. for (i = 0; i < table->n_labels; ++i) {
  1377. if (!strcmp(label, table->labels[i].v))
  1378. return table->labels[i].pos;
  1379. }
  1380. return -1;
  1381. }
  1382. /* remember that we've used the label at position pos */
  1383. static int
  1384. dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
  1385. {
  1386. char *v;
  1387. int p;
  1388. if (table->n_labels == MAX_LABELS)
  1389. return (-1);
  1390. v = mm_strdup(label);
  1391. if (v == NULL)
  1392. return (-1);
  1393. p = table->n_labels++;
  1394. table->labels[p].v = v;
  1395. table->labels[p].pos = pos;
  1396. return (0);
  1397. }
  1398. /* Converts a string to a length-prefixed set of DNS labels, starting */
  1399. /* at buf[j]. name and buf must not overlap. name_len should be the length */
  1400. /* of name. table is optional, and is used for compression. */
  1401. /* */
  1402. /* Input: abc.def */
  1403. /* Output: <3>abc<3>def<0> */
  1404. /* */
  1405. /* Returns the first index after the encoded name, or negative on error. */
  1406. /* -1 label was > 63 bytes */
  1407. /* -2 name too long to fit in buffer. */
  1408. /* */
  1409. static off_t
  1410. dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
  1411. const char *name, const size_t name_len,
  1412. struct dnslabel_table *table) {
  1413. const char *end = name + name_len;
  1414. int ref = 0;
  1415. u16 t_;
  1416. #define APPEND16(x) do { \
  1417. if (j + 2 > (off_t)buf_len) \
  1418. goto overflow; \
  1419. t_ = htons(x); \
  1420. memcpy(buf + j, &t_, 2); \
  1421. j += 2; \
  1422. } while (0)
  1423. #define APPEND32(x) do { \
  1424. if (j + 4 > (off_t)buf_len) \
  1425. goto overflow; \
  1426. t32_ = htonl(x); \
  1427. memcpy(buf + j, &t32_, 4); \
  1428. j += 4; \
  1429. } while (0)
  1430. if (name_len > 255) return -2;
  1431. for (;;) {
  1432. const char *const start = name;
  1433. if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
  1434. APPEND16(ref | 0xc000);
  1435. return j;
  1436. }
  1437. name = strchr(name, '.');
  1438. if (!name) {
  1439. const size_t label_len = end - start;
  1440. if (label_len > 63) return -1;
  1441. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1442. if (table) dnslabel_table_add(table, start, j);
  1443. buf[j++] = (ev_uint8_t)label_len;
  1444. memcpy(buf + j, start, label_len);
  1445. j += (int) label_len;
  1446. break;
  1447. } else {
  1448. /* append length of the label. */
  1449. const size_t label_len = name - start;
  1450. if (label_len > 63) return -1;
  1451. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1452. if (table) dnslabel_table_add(table, start, j);
  1453. buf[j++] = (ev_uint8_t)label_len;
  1454. memcpy(buf + j, start, label_len);
  1455. j += (int) label_len;
  1456. /* hop over the '.' */
  1457. name++;
  1458. }
  1459. }
  1460. /* the labels must be terminated by a 0. */
  1461. /* It's possible that the name ended in a . */
  1462. /* in which case the zero is already there */
  1463. if (!j || buf[j-1]) buf[j++] = 0;
  1464. return j;
  1465. overflow:
  1466. return (-2);
  1467. }
  1468. /* Finds the length of a dns request for a DNS name of the given */
  1469. /* length. The actual request may be smaller than the value returned */
  1470. /* here */
  1471. static size_t
  1472. evdns_request_len(const size_t name_len) {
  1473. return 96 + /* length of the DNS standard header */
  1474. name_len + 2 +
  1475. 4; /* space for the resource type */
  1476. }
  1477. /* build a dns request packet into buf. buf should be at least as long */
  1478. /* as evdns_request_len told you it should be. */
  1479. /* */
  1480. /* Returns the amount of space used. Negative on error. */
  1481. static int
  1482. evdns_request_data_build(const char *const name, const size_t name_len,
  1483. const u16 trans_id, const u16 type, const u16 class,
  1484. u8 *const buf, size_t buf_len) {
  1485. off_t j = 0; /* current offset into buf */
  1486. u16 t_; /* used by the macros */
  1487. APPEND16(trans_id);
  1488. APPEND16(0x0100); /* standard query, recusion needed */
  1489. APPEND16(1); /* one question */
  1490. APPEND16(0); /* no answers */
  1491. APPEND16(0); /* no authority */
  1492. APPEND16(0); /* no additional */
  1493. j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
  1494. if (j < 0) {
  1495. return (int)j;
  1496. }
  1497. APPEND16(type);
  1498. APPEND16(class);
  1499. return (int)j;
  1500. overflow:
  1501. return (-1);
  1502. }
  1503. /* exported function */
  1504. struct evdns_server_port *
  1505. evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
  1506. {
  1507. struct evdns_server_port *port;
  1508. if (flags)
  1509. return NULL; /* flags not yet implemented */
  1510. if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
  1511. return NULL;
  1512. memset(port, 0, sizeof(struct evdns_server_port));
  1513. port->socket = socket;
  1514. port->refcnt = 1;
  1515. port->choked = 0;
  1516. port->closing = 0;
  1517. port->user_callback = cb;
  1518. port->user_data = user_data;
  1519. port->pending_replies = NULL;
  1520. port->event_base = base;
  1521. event_assign(&port->event, port->event_base,
  1522. port->socket, EV_READ | EV_PERSIST,
  1523. server_port_ready_callback, port);
  1524. if (event_add(&port->event, NULL) < 0) {
  1525. mm_free(port);
  1526. return NULL;
  1527. }
  1528. EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  1529. return port;
  1530. }
  1531. struct evdns_server_port *
  1532. evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
  1533. {
  1534. return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
  1535. }
  1536. /* exported function */
  1537. void
  1538. evdns_close_server_port(struct evdns_server_port *port)
  1539. {
  1540. EVDNS_LOCK(port);
  1541. if (--port->refcnt == 0) {
  1542. EVDNS_UNLOCK(port);
  1543. server_port_free(port);
  1544. } else {
  1545. port->closing = 1;
  1546. EVDNS_UNLOCK(port);
  1547. }
  1548. }
  1549. /* exported function */
  1550. int
  1551. evdns_server_request_add_reply(struct evdns_server_request *req_, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
  1552. {
  1553. struct server_request *req = TO_SERVER_REQUEST(req_);
  1554. struct server_reply_item **itemp, *item;
  1555. int *countp;
  1556. int result = -1;
  1557. EVDNS_LOCK(req->port);
  1558. if (req->response) /* have we already answered? */
  1559. goto done;
  1560. switch (section) {
  1561. case EVDNS_ANSWER_SECTION:
  1562. itemp = &req->answer;
  1563. countp = &req->n_answer;
  1564. break;
  1565. case EVDNS_AUTHORITY_SECTION:
  1566. itemp = &req->authority;
  1567. countp = &req->n_authority;
  1568. break;
  1569. case EVDNS_ADDITIONAL_SECTION:
  1570. itemp = &req->additional;
  1571. countp = &req->n_additional;
  1572. break;
  1573. default:
  1574. goto done;
  1575. }
  1576. while (*itemp) {
  1577. itemp = &((*itemp)->next);
  1578. }
  1579. item = mm_malloc(sizeof(struct server_reply_item));
  1580. if (!item)
  1581. goto done;
  1582. item->next = NULL;
  1583. if (!(item->name = mm_strdup(name))) {
  1584. mm_free(item);
  1585. goto done;
  1586. }
  1587. item->type = type;
  1588. item->dns_question_class = class;
  1589. item->ttl = ttl;
  1590. item->is_name = is_name != 0;
  1591. item->datalen = 0;
  1592. item->data = NULL;
  1593. if (data) {
  1594. if (item->is_name) {
  1595. if (!(item->data = mm_strdup(data))) {
  1596. mm_free(item->name);
  1597. mm_free(item);
  1598. goto done;
  1599. }
  1600. item->datalen = (u16)-1;
  1601. } else {
  1602. if (!(item->data = mm_malloc(datalen))) {
  1603. mm_free(item->name);
  1604. mm_free(item);
  1605. goto done;
  1606. }
  1607. item->datalen = datalen;
  1608. memcpy(item->data, data, datalen);
  1609. }
  1610. }
  1611. *itemp = item;
  1612. ++(*countp);
  1613. result = 0;
  1614. done:
  1615. EVDNS_UNLOCK(req->port);
  1616. return result;
  1617. }
  1618. /* exported function */
  1619. int
  1620. evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
  1621. {
  1622. return evdns_server_request_add_reply(
  1623. req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
  1624. ttl, n*4, 0, addrs);
  1625. }
  1626. /* exported function */
  1627. int
  1628. evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
  1629. {
  1630. return evdns_server_request_add_reply(
  1631. req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
  1632. ttl, n*16, 0, addrs);
  1633. }
  1634. /* exported function */
  1635. int
  1636. evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
  1637. {
  1638. u32 a;
  1639. char buf[32];
  1640. if (in && inaddr_name)
  1641. return -1;
  1642. else if (!in && !inaddr_name)
  1643. return -1;
  1644. if (in) {
  1645. a = ntohl(in->s_addr);
  1646. evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  1647. (int)(u8)((a )&0xff),
  1648. (int)(u8)((a>>8 )&0xff),
  1649. (int)(u8)((a>>16)&0xff),
  1650. (int)(u8)((a>>24)&0xff));
  1651. inaddr_name = buf;
  1652. }
  1653. return evdns_server_request_add_reply(
  1654. req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
  1655. ttl, -1, 1, hostname);
  1656. }
  1657. /* exported function */
  1658. int
  1659. evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
  1660. {
  1661. return evdns_server_request_add_reply(
  1662. req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
  1663. ttl, -1, 1, cname);
  1664. }
  1665. /* exported function */
  1666. void
  1667. evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
  1668. {
  1669. struct server_request *req = TO_SERVER_REQUEST(exreq);
  1670. req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
  1671. req->base.flags |= flags;
  1672. }
  1673. static int
  1674. evdns_server_request_format_response(struct server_request *req, int err)
  1675. {
  1676. unsigned char buf[1500];
  1677. size_t buf_len = sizeof(buf);
  1678. off_t j = 0, r;
  1679. u16 t_;
  1680. u32 t32_;
  1681. int i;
  1682. u16 flags;
  1683. struct dnslabel_table table;
  1684. if (err < 0 || err > 15) return -1;
  1685. /* Set response bit and error code; copy OPCODE and RD fields from
  1686. * question; copy RA and AA if set by caller. */
  1687. flags = req->base.flags;
  1688. flags |= (_QR_MASK | err);
  1689. dnslabel_table_init(&table);
  1690. APPEND16(req->trans_id);
  1691. APPEND16(flags);
  1692. APPEND16(req->base.nquestions);
  1693. APPEND16(req->n_answer);
  1694. APPEND16(req->n_authority);
  1695. APPEND16(req->n_additional);
  1696. /* Add questions. */
  1697. for (i=0; i < req->base.nquestions; ++i) {
  1698. const char *s = req->base.questions[i]->name;
  1699. j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
  1700. if (j < 0) {
  1701. dnslabel_clear(&table);
  1702. return (int) j;
  1703. }
  1704. APPEND16(req->base.questions[i]->type);
  1705. APPEND16(req->base.questions[i]->dns_question_class);
  1706. }
  1707. /* Add answer, authority, and additional sections. */
  1708. for (i=0; i<3; ++i) {
  1709. struct server_reply_item *item;
  1710. if (i==0)
  1711. item = req->answer;
  1712. else if (i==1)
  1713. item = req->authority;
  1714. else
  1715. item = req->additional;
  1716. while (item) {
  1717. r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
  1718. if (r < 0)
  1719. goto overflow;
  1720. j = r;
  1721. APPEND16(item->type);
  1722. APPEND16(item->dns_question_class);
  1723. APPEND32(item->ttl);
  1724. if (item->is_name) {
  1725. off_t len_idx = j, name_start;
  1726. j += 2;
  1727. name_start = j;
  1728. r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
  1729. if (r < 0)
  1730. goto overflow;
  1731. j = r;
  1732. t_ = htons( (short) (j-name_start) );
  1733. memcpy(buf+len_idx, &t_, 2);
  1734. } else {
  1735. APPEND16(item->datalen);
  1736. if (j+item->datalen > (off_t)buf_len)
  1737. goto overflow;
  1738. memcpy(buf+j, item->data, item->datalen);
  1739. j += item->datalen;
  1740. }
  1741. item = item->next;
  1742. }
  1743. }
  1744. if (j > 512) {
  1745. overflow:
  1746. j = 512;
  1747. buf[2] |= 0x02; /* set the truncated bit. */
  1748. }
  1749. req->response_len = j;
  1750. if (!(req->response = mm_malloc(req->response_len))) {
  1751. server_request_free_answers(req);
  1752. dnslabel_clear(&table);
  1753. return (-1);
  1754. }
  1755. memcpy(req->response, buf, req->response_len);
  1756. server_request_free_answers(req);
  1757. dnslabel_clear(&table);
  1758. return (0);
  1759. }
  1760. /* exported function */
  1761. int
  1762. evdns_server_request_respond(struct evdns_server_request *req_, int err)
  1763. {
  1764. struct server_request *req = TO_SERVER_REQUEST(req_);
  1765. struct evdns_server_port *port = req->port;
  1766. int r = -1;
  1767. EVDNS_LOCK(port);
  1768. if (!req->response) {
  1769. if ((r = evdns_server_request_format_response(req, err))<0)
  1770. goto done;
  1771. }
  1772. r = sendto(port->socket, req->response, (int)req->response_len, 0,
  1773. (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
  1774. if (r<0) {
  1775. int sock_err = evutil_socket_geterror(port->socket);
  1776. if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
  1777. goto done;
  1778. if (port->pending_replies) {
  1779. req->prev_pending = port->pending_replies->prev_pending;
  1780. req->next_pending = port->pending_replies;
  1781. req->prev_pending->next_pending =
  1782. req->next_pending->prev_pending = req;
  1783. } else {
  1784. req->prev_pending = req->next_pending = req;
  1785. port->pending_replies = req;
  1786. port->choked = 1;
  1787. (void) event_del(&port->event);
  1788. event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
  1789. if (event_add(&port->event, NULL) < 0) {
  1790. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
  1791. }
  1792. }
  1793. r = 1;
  1794. goto done;
  1795. }
  1796. if (server_request_free(req)) {
  1797. r = 0;
  1798. goto done;
  1799. }
  1800. if (port->pending_replies)
  1801. server_port_flush(port);
  1802. r = 0;
  1803. done:
  1804. EVDNS_UNLOCK(port);
  1805. return r;
  1806. }
  1807. /* Free all storage held by RRs in req. */
  1808. static void
  1809. server_request_free_answers(struct server_request *req)
  1810. {
  1811. struct server_reply_item *victim, *next, **list;
  1812. int i;
  1813. for (i = 0; i < 3; ++i) {
  1814. if (i==0)
  1815. list = &req->answer;
  1816. else if (i==1)
  1817. list = &req->authority;
  1818. else
  1819. list = &req->additional;
  1820. victim = *list;
  1821. while (victim) {
  1822. next = victim->next;
  1823. mm_free(victim->name);
  1824. if (victim->data)
  1825. mm_free(victim->data);
  1826. mm_free(victim);
  1827. victim = next;
  1828. }
  1829. *list = NULL;
  1830. }
  1831. }
  1832. /* Free all storage held by req, and remove links to it. */
  1833. /* return true iff we just wound up freeing the server_port. */
  1834. static int
  1835. server_request_free(struct server_request *req)
  1836. {
  1837. int i, rc=1, lock=0;
  1838. if (req->base.questions) {
  1839. for (i = 0; i < req->base.nquestions; ++i)
  1840. mm_free(req->base.questions[i]);
  1841. mm_free(req->base.questions);
  1842. }
  1843. if (req->port) {
  1844. EVDNS_LOCK(req->port);
  1845. lock=1;
  1846. if (req->port->pending_replies == req) {
  1847. if (req->next_pending && req->next_pending != req)
  1848. req->port->pending_replies = req->next_pending;
  1849. else
  1850. req->port->pending_replies = NULL;
  1851. }
  1852. rc = --req->port->refcnt;
  1853. }
  1854. if (req->response) {
  1855. mm_free(req->response);
  1856. }
  1857. server_request_free_answers(req);
  1858. if (req->next_pending && req->next_pending != req) {
  1859. req->next_pending->prev_pending = req->prev_pending;
  1860. req->prev_pending->next_pending = req->next_pending;
  1861. }
  1862. if (rc == 0) {
  1863. EVDNS_UNLOCK(req->port); /* ????? nickm */
  1864. server_port_free(req->port);
  1865. mm_free(req);
  1866. return (1);
  1867. }
  1868. if (lock)
  1869. EVDNS_UNLOCK(req->port);
  1870. mm_free(req);
  1871. return (0);
  1872. }
  1873. /* Free all storage held by an evdns_server_port. Only called when */
  1874. static void
  1875. server_port_free(struct evdns_server_port *port)
  1876. {
  1877. EVUTIL_ASSERT(port);
  1878. EVUTIL_ASSERT(!port->refcnt);
  1879. EVUTIL_ASSERT(!port->pending_replies);
  1880. if (port->socket > 0) {
  1881. evutil_closesocket(port->socket);
  1882. port->socket = -1;
  1883. }
  1884. (void) event_del(&port->event);
  1885. event_debug_unassign(&port->event);
  1886. EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  1887. mm_free(port);
  1888. }
  1889. /* exported function */
  1890. int
  1891. evdns_server_request_drop(struct evdns_server_request *req_)
  1892. {
  1893. struct server_request *req = TO_SERVER_REQUEST(req_);
  1894. server_request_free(req);
  1895. return 0;
  1896. }
  1897. /* exported function */
  1898. int
  1899. evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len)
  1900. {
  1901. struct server_request *req = TO_SERVER_REQUEST(req_);
  1902. if (addr_len < (int)req->addrlen)
  1903. return -1;
  1904. memcpy(sa, &(req->addr), req->addrlen);
  1905. return req->addrlen;
  1906. }
  1907. #undef APPEND16
  1908. #undef APPEND32
  1909. /* this is a libevent callback function which is called when a request */
  1910. /* has timed out. */
  1911. static void
  1912. evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
  1913. struct request *const req = (struct request *) arg;
  1914. struct evdns_base *base = req->base;
  1915. (void) fd;
  1916. (void) events;
  1917. log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
  1918. EVDNS_LOCK(base);
  1919. if (req->tx_count >= req->base->global_max_retransmits) {
  1920. struct nameserver *ns = req->ns;
  1921. /* this request has failed */
  1922. log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
  1923. arg, req->tx_count);
  1924. reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
  1925. request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
  1926. nameserver_failed(ns, "request timed out.");
  1927. } else {
  1928. /* retransmit it */
  1929. log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
  1930. arg, req->tx_count);
  1931. (void) evtimer_del(&req->timeout_event);
  1932. request_swap_ns(req, nameserver_pick(base));
  1933. evdns_request_transmit(req);
  1934. req->ns->timedout++;
  1935. if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
  1936. req->ns->timedout = 0;
  1937. nameserver_failed(req->ns, "request timed out.");
  1938. }
  1939. }
  1940. EVDNS_UNLOCK(base);
  1941. }
  1942. /* try to send a request to a given server. */
  1943. /* */
  1944. /* return: */
  1945. /* 0 ok */
  1946. /* 1 temporary failure */
  1947. /* 2 other failure */
  1948. static int
  1949. evdns_request_transmit_to(struct request *req, struct nameserver *server) {
  1950. int r;
  1951. ASSERT_LOCKED(req->base);
  1952. ASSERT_VALID_REQUEST(req);
  1953. if (server->requests_inflight == 1 &&
  1954. req->base->disable_when_inactive &&
  1955. event_add(&server->event, NULL) < 0) {
  1956. return 1;
  1957. }
  1958. r = sendto(server->socket, (void*)req->request, req->request_len, 0,
  1959. (struct sockaddr *)&server->address, server->addrlen);
  1960. if (r < 0) {
  1961. int err = evutil_socket_geterror(server->socket);
  1962. if (EVUTIL_ERR_RW_RETRIABLE(err))
  1963. return 1;
  1964. nameserver_failed(req->ns, evutil_socket_error_to_string(err));
  1965. return 2;
  1966. } else if (r != (int)req->request_len) {
  1967. return 1; /* short write */
  1968. } else {
  1969. return 0;
  1970. }
  1971. }
  1972. /* try to send a request, updating the fields of the request */
  1973. /* as needed */
  1974. /* */
  1975. /* return: */
  1976. /* 0 ok */
  1977. /* 1 failed */
  1978. static int
  1979. evdns_request_transmit(struct request *req) {
  1980. int retcode = 0, r;
  1981. ASSERT_LOCKED(req->base);
  1982. ASSERT_VALID_REQUEST(req);
  1983. /* if we fail to send this packet then this flag marks it */
  1984. /* for evdns_transmit */
  1985. req->transmit_me = 1;
  1986. EVUTIL_ASSERT(req->trans_id != 0xffff);
  1987. if (!req->ns)
  1988. {
  1989. /* unable to transmit request if no nameservers */
  1990. return 1;
  1991. }
  1992. if (req->ns->choked) {
  1993. /* don't bother trying to write to a socket */
  1994. /* which we have had EAGAIN from */
  1995. return 1;
  1996. }
  1997. r = evdns_request_transmit_to(req, req->ns);
  1998. switch (r) {
  1999. case 1:
  2000. /* temp failure */
  2001. req->ns->choked = 1;
  2002. nameserver_write_waiting(req->ns, 1);
  2003. return 1;
  2004. case 2:
  2005. /* failed to transmit the request entirely. we can fallthrough since
  2006. * we'll set a timeout, which will time out, and make us retransmit the
  2007. * request anyway. */
  2008. retcode = 1;
  2009. EVUTIL_FALLTHROUGH;
  2010. default:
  2011. /* all ok */
  2012. log(EVDNS_LOG_DEBUG,
  2013. "Setting timeout for request %p, sent to nameserver %p", req, req->ns);
  2014. if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
  2015. log(EVDNS_LOG_WARN,
  2016. "Error from libevent when adding timer for request %p",
  2017. req);
  2018. /* ???? Do more? */
  2019. }
  2020. req->tx_count++;
  2021. req->transmit_me = 0;
  2022. return retcode;
  2023. }
  2024. }
  2025. static void
  2026. nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
  2027. struct nameserver *const ns = (struct nameserver *) arg;
  2028. (void) type;
  2029. (void) count;
  2030. (void) ttl;
  2031. (void) addresses;
  2032. if (result == DNS_ERR_CANCEL) {
  2033. /* We canceled this request because the nameserver came up
  2034. * for some other reason. Do not change our opinion about
  2035. * the nameserver. */
  2036. return;
  2037. }
  2038. EVDNS_LOCK(ns->base);
  2039. ns->probe_request = NULL;
  2040. if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
  2041. /* this is a good reply */
  2042. nameserver_up(ns);
  2043. } else {
  2044. nameserver_probe_failed(ns);
  2045. }
  2046. EVDNS_UNLOCK(ns->base);
  2047. }
  2048. static void
  2049. nameserver_send_probe(struct nameserver *const ns) {
  2050. struct evdns_request *handle;
  2051. struct request *req;
  2052. char addrbuf[128];
  2053. /* here we need to send a probe to a given nameserver */
  2054. /* in the hope that it is up now. */
  2055. ASSERT_LOCKED(ns->base);
  2056. log(EVDNS_LOG_DEBUG, "Sending probe to %s",
  2057. evutil_format_sockaddr_port_(
  2058. (struct sockaddr *)&ns->address,
  2059. addrbuf, sizeof(addrbuf)));
  2060. handle = mm_calloc(1, sizeof(*handle));
  2061. if (!handle) return;
  2062. req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
  2063. if (!req) {
  2064. mm_free(handle);
  2065. return;
  2066. }
  2067. ns->probe_request = handle;
  2068. /* we force this into the inflight queue no matter what */
  2069. request_trans_id_set(req, transaction_id_pick(ns->base));
  2070. req->ns = ns;
  2071. request_submit(req);
  2072. }
  2073. /* returns: */
  2074. /* 0 didn't try to transmit anything */
  2075. /* 1 tried to transmit something */
  2076. static int
  2077. evdns_transmit(struct evdns_base *base) {
  2078. char did_try_to_transmit = 0;
  2079. int i;
  2080. ASSERT_LOCKED(base);
  2081. for (i = 0; i < base->n_req_heads; ++i) {
  2082. if (base->req_heads[i]) {
  2083. struct request *const started_at = base->req_heads[i], *req = started_at;
  2084. /* first transmit all the requests which are currently waiting */
  2085. do {
  2086. if (req->transmit_me) {
  2087. did_try_to_transmit = 1;
  2088. evdns_request_transmit(req);
  2089. }
  2090. req = req->next;
  2091. } while (req != started_at);
  2092. }
  2093. }
  2094. return did_try_to_transmit;
  2095. }
  2096. /* exported function */
  2097. int
  2098. evdns_base_count_nameservers(struct evdns_base *base)
  2099. {
  2100. const struct nameserver *server;
  2101. int n = 0;
  2102. EVDNS_LOCK(base);
  2103. server = base->server_head;
  2104. if (!server)
  2105. goto done;
  2106. do {
  2107. ++n;
  2108. server = server->next;
  2109. } while (server != base->server_head);
  2110. done:
  2111. EVDNS_UNLOCK(base);
  2112. return n;
  2113. }
  2114. int
  2115. evdns_count_nameservers(void)
  2116. {
  2117. return evdns_base_count_nameservers(current_base);
  2118. }
  2119. /* exported function */
  2120. int
  2121. evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
  2122. {
  2123. struct nameserver *server, *started_at;
  2124. int i;
  2125. EVDNS_LOCK(base);
  2126. server = base->server_head;
  2127. started_at = base->server_head;
  2128. if (!server) {
  2129. EVDNS_UNLOCK(base);
  2130. return 0;
  2131. }
  2132. while (1) {
  2133. struct nameserver *next = server->next;
  2134. (void) event_del(&server->event);
  2135. if (evtimer_initialized(&server->timeout_event))
  2136. (void) evtimer_del(&server->timeout_event);
  2137. if (server->probe_request) {
  2138. evdns_cancel_request(server->base, server->probe_request);
  2139. server->probe_request = NULL;
  2140. }
  2141. if (server->socket >= 0)
  2142. evutil_closesocket(server->socket);
  2143. mm_free(server);
  2144. if (next == started_at)
  2145. break;
  2146. server = next;
  2147. }
  2148. base->server_head = NULL;
  2149. base->global_good_nameservers = 0;
  2150. for (i = 0; i < base->n_req_heads; ++i) {
  2151. struct request *req, *req_started_at;
  2152. req = req_started_at = base->req_heads[i];
  2153. while (req) {
  2154. struct request *next = req->next;
  2155. req->tx_count = req->reissue_count = 0;
  2156. req->ns = NULL;
  2157. /* ???? What to do about searches? */
  2158. (void) evtimer_del(&req->timeout_event);
  2159. req->trans_id = 0;
  2160. req->transmit_me = 0;
  2161. base->global_requests_waiting++;
  2162. evdns_request_insert(req, &base->req_waiting_head);
  2163. /* We want to insert these suspended elements at the front of
  2164. * the waiting queue, since they were pending before any of
  2165. * the waiting entries were added. This is a circular list,
  2166. * so we can just shift the start back by one.*/
  2167. base->req_waiting_head = base->req_waiting_head->prev;
  2168. if (next == req_started_at)
  2169. break;
  2170. req = next;
  2171. }
  2172. base->req_heads[i] = NULL;
  2173. }
  2174. base->global_requests_inflight = 0;
  2175. EVDNS_UNLOCK(base);
  2176. return 0;
  2177. }
  2178. int
  2179. evdns_clear_nameservers_and_suspend(void)
  2180. {
  2181. return evdns_base_clear_nameservers_and_suspend(current_base);
  2182. }
  2183. /* exported function */
  2184. int
  2185. evdns_base_resume(struct evdns_base *base)
  2186. {
  2187. EVDNS_LOCK(base);
  2188. evdns_requests_pump_waiting_queue(base);
  2189. EVDNS_UNLOCK(base);
  2190. return 0;
  2191. }
  2192. int
  2193. evdns_resume(void)
  2194. {
  2195. return evdns_base_resume(current_base);
  2196. }
  2197. static int
  2198. evdns_nameserver_add_impl_(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
  2199. /* first check to see if we already have this nameserver */
  2200. const struct nameserver *server = base->server_head, *const started_at = base->server_head;
  2201. struct nameserver *ns;
  2202. int err = 0;
  2203. char addrbuf[128];
  2204. ASSERT_LOCKED(base);
  2205. if (server) {
  2206. do {
  2207. if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3;
  2208. server = server->next;
  2209. } while (server != started_at);
  2210. }
  2211. if (addrlen > (int)sizeof(ns->address)) {
  2212. log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
  2213. return 2;
  2214. }
  2215. ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
  2216. if (!ns) return -1;
  2217. memset(ns, 0, sizeof(struct nameserver));
  2218. ns->base = base;
  2219. evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
  2220. ns->socket = evutil_socket_(address->sa_family,
  2221. SOCK_DGRAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
  2222. if (ns->socket < 0) { err = 1; goto out1; }
  2223. if (base->global_outgoing_addrlen &&
  2224. !evutil_sockaddr_is_loopback_(address)) {
  2225. if (bind(ns->socket,
  2226. (struct sockaddr*)&base->global_outgoing_address,
  2227. base->global_outgoing_addrlen) < 0) {
  2228. log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
  2229. err = 2;
  2230. goto out2;
  2231. }
  2232. }
  2233. if (base->so_rcvbuf) {
  2234. if (setsockopt(ns->socket, SOL_SOCKET, SO_RCVBUF,
  2235. (void *)&base->so_rcvbuf, sizeof(base->so_rcvbuf))) {
  2236. log(EVDNS_LOG_WARN, "Couldn't set SO_RCVBUF to %i", base->so_rcvbuf);
  2237. err = -SO_RCVBUF;
  2238. goto out2;
  2239. }
  2240. }
  2241. if (base->so_sndbuf) {
  2242. if (setsockopt(ns->socket, SOL_SOCKET, SO_SNDBUF,
  2243. (void *)&base->so_sndbuf, sizeof(base->so_sndbuf))) {
  2244. log(EVDNS_LOG_WARN, "Couldn't set SO_SNDBUF to %i", base->so_sndbuf);
  2245. err = -SO_SNDBUF;
  2246. goto out2;
  2247. }
  2248. }
  2249. memcpy(&ns->address, address, addrlen);
  2250. ns->addrlen = addrlen;
  2251. ns->state = 1;
  2252. event_assign(&ns->event, ns->base->event_base, ns->socket,
  2253. EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
  2254. if (!base->disable_when_inactive && event_add(&ns->event, NULL) < 0) {
  2255. err = 2;
  2256. goto out2;
  2257. }
  2258. log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
  2259. evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), ns);
  2260. /* insert this nameserver into the list of them */
  2261. if (!base->server_head) {
  2262. ns->next = ns->prev = ns;
  2263. base->server_head = ns;
  2264. } else {
  2265. ns->next = base->server_head->next;
  2266. ns->prev = base->server_head;
  2267. base->server_head->next = ns;
  2268. ns->next->prev = ns;
  2269. }
  2270. base->global_good_nameservers++;
  2271. return 0;
  2272. out2:
  2273. evutil_closesocket(ns->socket);
  2274. out1:
  2275. event_debug_unassign(&ns->event);
  2276. mm_free(ns);
  2277. log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
  2278. evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), err);
  2279. return err;
  2280. }
  2281. /* exported function */
  2282. int
  2283. evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
  2284. {
  2285. struct sockaddr_in sin;
  2286. int res;
  2287. memset(&sin, 0, sizeof(sin));
  2288. sin.sin_addr.s_addr = address;
  2289. sin.sin_port = htons(53);
  2290. sin.sin_family = AF_INET;
  2291. EVDNS_LOCK(base);
  2292. res = evdns_nameserver_add_impl_(base, (struct sockaddr*)&sin, sizeof(sin));
  2293. EVDNS_UNLOCK(base);
  2294. return res;
  2295. }
  2296. int
  2297. evdns_nameserver_add(unsigned long int address) {
  2298. if (!current_base)
  2299. current_base = evdns_base_new(NULL, 0);
  2300. return evdns_base_nameserver_add(current_base, address);
  2301. }
  2302. static void
  2303. sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
  2304. {
  2305. if (sa->sa_family == AF_INET) {
  2306. ((struct sockaddr_in *)sa)->sin_port = htons(port);
  2307. } else if (sa->sa_family == AF_INET6) {
  2308. ((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
  2309. }
  2310. }
  2311. static ev_uint16_t
  2312. sockaddr_getport(struct sockaddr *sa)
  2313. {
  2314. if (sa->sa_family == AF_INET) {
  2315. return ntohs(((struct sockaddr_in *)sa)->sin_port);
  2316. } else if (sa->sa_family == AF_INET6) {
  2317. return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
  2318. } else {
  2319. return 0;
  2320. }
  2321. }
  2322. /* exported function */
  2323. int
  2324. evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
  2325. struct sockaddr_storage ss;
  2326. struct sockaddr *sa;
  2327. int len = sizeof(ss);
  2328. int res;
  2329. if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
  2330. &len)) {
  2331. log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
  2332. ip_as_string);
  2333. return 4;
  2334. }
  2335. sa = (struct sockaddr *) &ss;
  2336. if (sockaddr_getport(sa) == 0)
  2337. sockaddr_setport(sa, 53);
  2338. EVDNS_LOCK(base);
  2339. res = evdns_nameserver_add_impl_(base, sa, len);
  2340. EVDNS_UNLOCK(base);
  2341. return res;
  2342. }
  2343. int
  2344. evdns_nameserver_ip_add(const char *ip_as_string) {
  2345. if (!current_base)
  2346. current_base = evdns_base_new(NULL, 0);
  2347. return evdns_base_nameserver_ip_add(current_base, ip_as_string);
  2348. }
  2349. int
  2350. evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
  2351. const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
  2352. {
  2353. int res;
  2354. EVUTIL_ASSERT(base);
  2355. EVDNS_LOCK(base);
  2356. res = evdns_nameserver_add_impl_(base, sa, len);
  2357. EVDNS_UNLOCK(base);
  2358. return res;
  2359. }
  2360. int
  2361. evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
  2362. struct sockaddr *sa, ev_socklen_t len)
  2363. {
  2364. int result = -1;
  2365. int i;
  2366. struct nameserver *server;
  2367. EVDNS_LOCK(base);
  2368. server = base->server_head;
  2369. for (i = 0; i < idx && server; ++i, server = server->next) {
  2370. if (server->next == base->server_head)
  2371. goto done;
  2372. }
  2373. if (! server)
  2374. goto done;
  2375. if (server->addrlen > len) {
  2376. result = (int) server->addrlen;
  2377. goto done;
  2378. }
  2379. memcpy(sa, &server->address, server->addrlen);
  2380. result = (int) server->addrlen;
  2381. done:
  2382. EVDNS_UNLOCK(base);
  2383. return result;
  2384. }
  2385. /* remove from the queue */
  2386. static void
  2387. evdns_request_remove(struct request *req, struct request **head)
  2388. {
  2389. ASSERT_LOCKED(req->base);
  2390. ASSERT_VALID_REQUEST(req);
  2391. #if 0
  2392. {
  2393. struct request *ptr;
  2394. int found = 0;
  2395. EVUTIL_ASSERT(*head != NULL);
  2396. ptr = *head;
  2397. do {
  2398. if (ptr == req) {
  2399. found = 1;
  2400. break;
  2401. }
  2402. ptr = ptr->next;
  2403. } while (ptr != *head);
  2404. EVUTIL_ASSERT(found);
  2405. EVUTIL_ASSERT(req->next);
  2406. }
  2407. #endif
  2408. if (req->next == req) {
  2409. /* only item in the list */
  2410. *head = NULL;
  2411. } else {
  2412. req->next->prev = req->prev;
  2413. req->prev->next = req->next;
  2414. if (*head == req) *head = req->next;
  2415. }
  2416. req->next = req->prev = NULL;
  2417. }
  2418. /* insert into the tail of the queue */
  2419. static void
  2420. evdns_request_insert(struct request *req, struct request **head) {
  2421. ASSERT_LOCKED(req->base);
  2422. ASSERT_VALID_REQUEST(req);
  2423. if (!*head) {
  2424. *head = req;
  2425. req->next = req->prev = req;
  2426. return;
  2427. }
  2428. req->prev = (*head)->prev;
  2429. req->prev->next = req;
  2430. req->next = *head;
  2431. (*head)->prev = req;
  2432. }
  2433. static int
  2434. string_num_dots(const char *s) {
  2435. int count = 0;
  2436. while ((s = strchr(s, '.'))) {
  2437. s++;
  2438. count++;
  2439. }
  2440. return count;
  2441. }
  2442. static struct request *
  2443. request_new(struct evdns_base *base, struct evdns_request *handle, int type,
  2444. const char *name, int flags, evdns_callback_type callback,
  2445. void *user_ptr) {
  2446. const char issuing_now =
  2447. (base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
  2448. const size_t name_len = strlen(name);
  2449. const size_t request_max_len = evdns_request_len(name_len);
  2450. const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
  2451. /* the request data is alloced in a single block with the header */
  2452. struct request *const req =
  2453. mm_malloc(sizeof(struct request) + request_max_len);
  2454. int rlen;
  2455. char namebuf[256];
  2456. (void) flags;
  2457. ASSERT_LOCKED(base);
  2458. if (!req) return NULL;
  2459. if (name_len >= sizeof(namebuf)) {
  2460. mm_free(req);
  2461. return NULL;
  2462. }
  2463. memset(req, 0, sizeof(struct request));
  2464. req->base = base;
  2465. evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
  2466. if (base->global_randomize_case) {
  2467. unsigned i;
  2468. char randbits[(sizeof(namebuf)+7)/8];
  2469. strlcpy(namebuf, name, sizeof(namebuf));
  2470. evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
  2471. for (i = 0; i < name_len; ++i) {
  2472. if (EVUTIL_ISALPHA_(namebuf[i])) {
  2473. if ((randbits[i >> 3] & (1<<(i & 7))))
  2474. namebuf[i] |= 0x20;
  2475. else
  2476. namebuf[i] &= ~0x20;
  2477. }
  2478. }
  2479. name = namebuf;
  2480. }
  2481. /* request data lives just after the header */
  2482. req->request = ((u8 *) req) + sizeof(struct request);
  2483. /* denotes that the request data shouldn't be free()ed */
  2484. req->request_appended = 1;
  2485. rlen = evdns_request_data_build(name, name_len, trans_id,
  2486. type, CLASS_INET, req->request, request_max_len);
  2487. if (rlen < 0)
  2488. goto err1;
  2489. req->request_len = rlen;
  2490. req->trans_id = trans_id;
  2491. req->tx_count = 0;
  2492. req->request_type = type;
  2493. req->user_pointer = user_ptr;
  2494. req->user_callback = callback;
  2495. req->ns = issuing_now ? nameserver_pick(base) : NULL;
  2496. req->next = req->prev = NULL;
  2497. req->handle = handle;
  2498. if (handle) {
  2499. handle->current_req = req;
  2500. handle->base = base;
  2501. }
  2502. return req;
  2503. err1:
  2504. mm_free(req);
  2505. return NULL;
  2506. }
  2507. static void
  2508. request_submit(struct request *const req) {
  2509. struct evdns_base *base = req->base;
  2510. ASSERT_LOCKED(base);
  2511. ASSERT_VALID_REQUEST(req);
  2512. if (req->ns) {
  2513. /* if it has a nameserver assigned then this is going */
  2514. /* straight into the inflight queue */
  2515. evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
  2516. base->global_requests_inflight++;
  2517. req->ns->requests_inflight++;
  2518. evdns_request_transmit(req);
  2519. } else {
  2520. evdns_request_insert(req, &base->req_waiting_head);
  2521. base->global_requests_waiting++;
  2522. }
  2523. }
  2524. /* exported function */
  2525. void
  2526. evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
  2527. {
  2528. struct request *req;
  2529. if (!handle->current_req)
  2530. return;
  2531. if (!base) {
  2532. /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
  2533. base = handle->base;
  2534. if (!base)
  2535. base = handle->current_req->base;
  2536. }
  2537. EVDNS_LOCK(base);
  2538. if (handle->pending_cb) {
  2539. EVDNS_UNLOCK(base);
  2540. return;
  2541. }
  2542. req = handle->current_req;
  2543. ASSERT_VALID_REQUEST(req);
  2544. reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
  2545. if (req->ns) {
  2546. /* remove from inflight queue */
  2547. request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
  2548. } else {
  2549. /* remove from global_waiting head */
  2550. request_finished(req, &base->req_waiting_head, 1);
  2551. }
  2552. EVDNS_UNLOCK(base);
  2553. }
  2554. /* exported function */
  2555. struct evdns_request *
  2556. evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
  2557. evdns_callback_type callback, void *ptr) {
  2558. struct evdns_request *handle;
  2559. struct request *req;
  2560. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2561. handle = mm_calloc(1, sizeof(*handle));
  2562. if (handle == NULL)
  2563. return NULL;
  2564. EVDNS_LOCK(base);
  2565. if (flags & DNS_QUERY_NO_SEARCH) {
  2566. req =
  2567. request_new(base, handle, TYPE_A, name, flags,
  2568. callback, ptr);
  2569. if (req)
  2570. request_submit(req);
  2571. } else {
  2572. search_request_new(base, handle, TYPE_A, name, flags,
  2573. callback, ptr);
  2574. }
  2575. if (handle->current_req == NULL) {
  2576. mm_free(handle);
  2577. handle = NULL;
  2578. }
  2579. EVDNS_UNLOCK(base);
  2580. return handle;
  2581. }
  2582. int evdns_resolve_ipv4(const char *name, int flags,
  2583. evdns_callback_type callback, void *ptr)
  2584. {
  2585. return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
  2586. ? 0 : -1;
  2587. }
  2588. /* exported function */
  2589. struct evdns_request *
  2590. evdns_base_resolve_ipv6(struct evdns_base *base,
  2591. const char *name, int flags,
  2592. evdns_callback_type callback, void *ptr)
  2593. {
  2594. struct evdns_request *handle;
  2595. struct request *req;
  2596. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2597. handle = mm_calloc(1, sizeof(*handle));
  2598. if (handle == NULL)
  2599. return NULL;
  2600. EVDNS_LOCK(base);
  2601. if (flags & DNS_QUERY_NO_SEARCH) {
  2602. req = request_new(base, handle, TYPE_AAAA, name, flags,
  2603. callback, ptr);
  2604. if (req)
  2605. request_submit(req);
  2606. } else {
  2607. search_request_new(base, handle, TYPE_AAAA, name, flags,
  2608. callback, ptr);
  2609. }
  2610. if (handle->current_req == NULL) {
  2611. mm_free(handle);
  2612. handle = NULL;
  2613. }
  2614. EVDNS_UNLOCK(base);
  2615. return handle;
  2616. }
  2617. int evdns_resolve_ipv6(const char *name, int flags,
  2618. evdns_callback_type callback, void *ptr) {
  2619. return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
  2620. ? 0 : -1;
  2621. }
  2622. struct evdns_request *
  2623. evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2624. char buf[32];
  2625. struct evdns_request *handle;
  2626. struct request *req;
  2627. u32 a;
  2628. EVUTIL_ASSERT(in);
  2629. a = ntohl(in->s_addr);
  2630. evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  2631. (int)(u8)((a )&0xff),
  2632. (int)(u8)((a>>8 )&0xff),
  2633. (int)(u8)((a>>16)&0xff),
  2634. (int)(u8)((a>>24)&0xff));
  2635. handle = mm_calloc(1, sizeof(*handle));
  2636. if (handle == NULL)
  2637. return NULL;
  2638. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2639. EVDNS_LOCK(base);
  2640. req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
  2641. if (req)
  2642. request_submit(req);
  2643. if (handle->current_req == NULL) {
  2644. mm_free(handle);
  2645. handle = NULL;
  2646. }
  2647. EVDNS_UNLOCK(base);
  2648. return (handle);
  2649. }
  2650. int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2651. return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
  2652. ? 0 : -1;
  2653. }
  2654. struct evdns_request *
  2655. evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2656. /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
  2657. char buf[73];
  2658. char *cp;
  2659. struct evdns_request *handle;
  2660. struct request *req;
  2661. int i;
  2662. EVUTIL_ASSERT(in);
  2663. cp = buf;
  2664. for (i=15; i >= 0; --i) {
  2665. u8 byte = in->s6_addr[i];
  2666. *cp++ = "0123456789abcdef"[byte & 0x0f];
  2667. *cp++ = '.';
  2668. *cp++ = "0123456789abcdef"[byte >> 4];
  2669. *cp++ = '.';
  2670. }
  2671. EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
  2672. memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
  2673. handle = mm_calloc(1, sizeof(*handle));
  2674. if (handle == NULL)
  2675. return NULL;
  2676. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2677. EVDNS_LOCK(base);
  2678. req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
  2679. if (req)
  2680. request_submit(req);
  2681. if (handle->current_req == NULL) {
  2682. mm_free(handle);
  2683. handle = NULL;
  2684. }
  2685. EVDNS_UNLOCK(base);
  2686. return (handle);
  2687. }
  2688. int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2689. return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
  2690. ? 0 : -1;
  2691. }
  2692. /* ================================================================= */
  2693. /* Search support */
  2694. /* */
  2695. /* the libc resolver has support for searching a number of domains */
  2696. /* to find a name. If nothing else then it takes the single domain */
  2697. /* from the gethostname() call. */
  2698. /* */
  2699. /* It can also be configured via the domain and search options in a */
  2700. /* resolv.conf. */
  2701. /* */
  2702. /* The ndots option controls how many dots it takes for the resolver */
  2703. /* to decide that a name is non-local and so try a raw lookup first. */
  2704. struct search_domain {
  2705. int len;
  2706. struct search_domain *next;
  2707. /* the text string is appended to this structure */
  2708. };
  2709. struct search_state {
  2710. int refcount;
  2711. int ndots;
  2712. int num_domains;
  2713. struct search_domain *head;
  2714. };
  2715. static void
  2716. search_state_decref(struct search_state *const state) {
  2717. if (!state) return;
  2718. state->refcount--;
  2719. if (!state->refcount) {
  2720. struct search_domain *next, *dom;
  2721. for (dom = state->head; dom; dom = next) {
  2722. next = dom->next;
  2723. mm_free(dom);
  2724. }
  2725. mm_free(state);
  2726. }
  2727. }
  2728. static struct search_state *
  2729. search_state_new(void) {
  2730. struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
  2731. if (!state) return NULL;
  2732. memset(state, 0, sizeof(struct search_state));
  2733. state->refcount = 1;
  2734. state->ndots = 1;
  2735. return state;
  2736. }
  2737. static void
  2738. search_postfix_clear(struct evdns_base *base) {
  2739. search_state_decref(base->global_search_state);
  2740. base->global_search_state = search_state_new();
  2741. }
  2742. /* exported function */
  2743. void
  2744. evdns_base_search_clear(struct evdns_base *base)
  2745. {
  2746. EVDNS_LOCK(base);
  2747. search_postfix_clear(base);
  2748. EVDNS_UNLOCK(base);
  2749. }
  2750. void
  2751. evdns_search_clear(void) {
  2752. evdns_base_search_clear(current_base);
  2753. }
  2754. static void
  2755. search_postfix_add(struct evdns_base *base, const char *domain) {
  2756. size_t domain_len;
  2757. struct search_domain *sdomain;
  2758. while (domain[0] == '.') domain++;
  2759. domain_len = strlen(domain);
  2760. ASSERT_LOCKED(base);
  2761. if (!base->global_search_state) base->global_search_state = search_state_new();
  2762. if (!base->global_search_state) return;
  2763. base->global_search_state->num_domains++;
  2764. sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
  2765. if (!sdomain) return;
  2766. memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
  2767. sdomain->next = base->global_search_state->head;
  2768. sdomain->len = (int) domain_len;
  2769. base->global_search_state->head = sdomain;
  2770. }
  2771. /* reverse the order of members in the postfix list. This is needed because, */
  2772. /* when parsing resolv.conf we push elements in the wrong order */
  2773. static void
  2774. search_reverse(struct evdns_base *base) {
  2775. struct search_domain *cur, *prev = NULL, *next;
  2776. ASSERT_LOCKED(base);
  2777. cur = base->global_search_state->head;
  2778. while (cur) {
  2779. next = cur->next;
  2780. cur->next = prev;
  2781. prev = cur;
  2782. cur = next;
  2783. }
  2784. base->global_search_state->head = prev;
  2785. }
  2786. /* exported function */
  2787. void
  2788. evdns_base_search_add(struct evdns_base *base, const char *domain) {
  2789. EVDNS_LOCK(base);
  2790. search_postfix_add(base, domain);
  2791. EVDNS_UNLOCK(base);
  2792. }
  2793. void
  2794. evdns_search_add(const char *domain) {
  2795. evdns_base_search_add(current_base, domain);
  2796. }
  2797. /* exported function */
  2798. void
  2799. evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
  2800. EVDNS_LOCK(base);
  2801. if (!base->global_search_state) base->global_search_state = search_state_new();
  2802. if (base->global_search_state)
  2803. base->global_search_state->ndots = ndots;
  2804. EVDNS_UNLOCK(base);
  2805. }
  2806. void
  2807. evdns_search_ndots_set(const int ndots) {
  2808. evdns_base_search_ndots_set(current_base, ndots);
  2809. }
  2810. static void
  2811. search_set_from_hostname(struct evdns_base *base) {
  2812. char hostname[HOST_NAME_MAX + 1], *domainname;
  2813. ASSERT_LOCKED(base);
  2814. search_postfix_clear(base);
  2815. if (gethostname(hostname, sizeof(hostname))) return;
  2816. domainname = strchr(hostname, '.');
  2817. if (!domainname) return;
  2818. search_postfix_add(base, domainname);
  2819. }
  2820. /* warning: returns malloced string */
  2821. static char *
  2822. search_make_new(const struct search_state *const state, int n, const char *const base_name) {
  2823. const size_t base_len = strlen(base_name);
  2824. char need_to_append_dot;
  2825. struct search_domain *dom;
  2826. if (!base_len) return NULL;
  2827. need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
  2828. for (dom = state->head; dom; dom = dom->next) {
  2829. if (!n--) {
  2830. /* this is the postfix we want */
  2831. /* the actual postfix string is kept at the end of the structure */
  2832. const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
  2833. const int postfix_len = dom->len;
  2834. char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
  2835. if (!newname) return NULL;
  2836. memcpy(newname, base_name, base_len);
  2837. if (need_to_append_dot) newname[base_len] = '.';
  2838. memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
  2839. newname[base_len + need_to_append_dot + postfix_len] = 0;
  2840. return newname;
  2841. }
  2842. }
  2843. /* we ran off the end of the list and still didn't find the requested string */
  2844. EVUTIL_ASSERT(0);
  2845. return NULL; /* unreachable; stops warnings in some compilers. */
  2846. }
  2847. static struct request *
  2848. search_request_new(struct evdns_base *base, struct evdns_request *handle,
  2849. int type, const char *const name, int flags,
  2850. evdns_callback_type user_callback, void *user_arg) {
  2851. ASSERT_LOCKED(base);
  2852. EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
  2853. EVUTIL_ASSERT(handle->current_req == NULL);
  2854. if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
  2855. base->global_search_state &&
  2856. base->global_search_state->num_domains) {
  2857. /* we have some domains to search */
  2858. struct request *req;
  2859. if (string_num_dots(name) >= base->global_search_state->ndots) {
  2860. req = request_new(base, handle, type, name, flags, user_callback, user_arg);
  2861. if (!req) return NULL;
  2862. handle->search_index = -1;
  2863. } else {
  2864. char *const new_name = search_make_new(base->global_search_state, 0, name);
  2865. if (!new_name) return NULL;
  2866. req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
  2867. mm_free(new_name);
  2868. if (!req) return NULL;
  2869. handle->search_index = 0;
  2870. }
  2871. EVUTIL_ASSERT(handle->search_origname == NULL);
  2872. handle->search_origname = mm_strdup(name);
  2873. if (handle->search_origname == NULL) {
  2874. /* XXX Should we dealloc req? If yes, how? */
  2875. if (req)
  2876. mm_free(req);
  2877. return NULL;
  2878. }
  2879. handle->search_state = base->global_search_state;
  2880. handle->search_flags = flags;
  2881. base->global_search_state->refcount++;
  2882. request_submit(req);
  2883. return req;
  2884. } else {
  2885. struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
  2886. if (!req) return NULL;
  2887. request_submit(req);
  2888. return req;
  2889. }
  2890. }
  2891. /* this is called when a request has failed to find a name. We need to check */
  2892. /* if it is part of a search and, if so, try the next name in the list */
  2893. /* returns: */
  2894. /* 0 another request has been submitted */
  2895. /* 1 no more requests needed */
  2896. static int
  2897. search_try_next(struct evdns_request *const handle) {
  2898. struct request *req = handle->current_req;
  2899. struct evdns_base *base = req->base;
  2900. struct request *newreq;
  2901. ASSERT_LOCKED(base);
  2902. if (handle->search_state) {
  2903. /* it is part of a search */
  2904. char *new_name;
  2905. handle->search_index++;
  2906. if (handle->search_index >= handle->search_state->num_domains) {
  2907. /* no more postfixes to try, however we may need to try */
  2908. /* this name without a postfix */
  2909. if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
  2910. /* yep, we need to try it raw */
  2911. newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
  2912. log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
  2913. if (newreq) {
  2914. search_request_finished(handle);
  2915. goto submit_next;
  2916. }
  2917. }
  2918. return 1;
  2919. }
  2920. new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
  2921. if (!new_name) return 1;
  2922. log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
  2923. newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
  2924. mm_free(new_name);
  2925. if (!newreq) return 1;
  2926. goto submit_next;
  2927. }
  2928. return 1;
  2929. submit_next:
  2930. request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
  2931. handle->current_req = newreq;
  2932. newreq->handle = handle;
  2933. request_submit(newreq);
  2934. return 0;
  2935. }
  2936. static void
  2937. search_request_finished(struct evdns_request *const handle) {
  2938. ASSERT_LOCKED(handle->current_req->base);
  2939. if (handle->search_state) {
  2940. search_state_decref(handle->search_state);
  2941. handle->search_state = NULL;
  2942. }
  2943. if (handle->search_origname) {
  2944. mm_free(handle->search_origname);
  2945. handle->search_origname = NULL;
  2946. }
  2947. }
  2948. /* ================================================================= */
  2949. /* Parsing resolv.conf files */
  2950. static void
  2951. evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
  2952. int add_default = flags & DNS_OPTION_NAMESERVERS;
  2953. if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
  2954. add_default = 0;
  2955. /* if the file isn't found then we assume a local resolver */
  2956. ASSERT_LOCKED(base);
  2957. if (flags & DNS_OPTION_SEARCH)
  2958. search_set_from_hostname(base);
  2959. if (add_default)
  2960. evdns_base_nameserver_ip_add(base, "127.0.0.1");
  2961. }
  2962. #ifndef EVENT__HAVE_STRTOK_R
  2963. static char *
  2964. strtok_r(char *s, const char *delim, char **state) {
  2965. char *cp, *start;
  2966. start = cp = s ? s : *state;
  2967. if (!cp)
  2968. return NULL;
  2969. while (*cp && !strchr(delim, *cp))
  2970. ++cp;
  2971. if (!*cp) {
  2972. if (cp == start)
  2973. return NULL;
  2974. *state = NULL;
  2975. return start;
  2976. } else {
  2977. *cp++ = '\0';
  2978. *state = cp;
  2979. return start;
  2980. }
  2981. }
  2982. #endif
  2983. /* helper version of atoi which returns -1 on error */
  2984. static int
  2985. strtoint(const char *const str)
  2986. {
  2987. char *endptr;
  2988. const int r = strtol(str, &endptr, 10);
  2989. if (*endptr) return -1;
  2990. return r;
  2991. }
  2992. /* Parse a number of seconds into a timeval; return -1 on error. */
  2993. static int
  2994. evdns_strtotimeval(const char *const str, struct timeval *out)
  2995. {
  2996. double d;
  2997. char *endptr;
  2998. d = strtod(str, &endptr);
  2999. if (*endptr) return -1;
  3000. if (d < 0) return -1;
  3001. out->tv_sec = (int) d;
  3002. out->tv_usec = (int) ((d - (int) d)*1000000);
  3003. if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
  3004. return -1;
  3005. return 0;
  3006. }
  3007. /* helper version of atoi that returns -1 on error and clips to bounds. */
  3008. static int
  3009. strtoint_clipped(const char *const str, int min, int max)
  3010. {
  3011. int r = strtoint(str);
  3012. if (r == -1)
  3013. return r;
  3014. else if (r<min)
  3015. return min;
  3016. else if (r>max)
  3017. return max;
  3018. else
  3019. return r;
  3020. }
  3021. static int
  3022. evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
  3023. {
  3024. int old_n_heads = base->n_req_heads, n_heads;
  3025. struct request **old_heads = base->req_heads, **new_heads, *req;
  3026. int i;
  3027. ASSERT_LOCKED(base);
  3028. if (maxinflight < 1)
  3029. maxinflight = 1;
  3030. n_heads = (maxinflight+4) / 5;
  3031. EVUTIL_ASSERT(n_heads > 0);
  3032. new_heads = mm_calloc(n_heads, sizeof(struct request*));
  3033. if (!new_heads)
  3034. return (-1);
  3035. if (old_heads) {
  3036. for (i = 0; i < old_n_heads; ++i) {
  3037. while (old_heads[i]) {
  3038. req = old_heads[i];
  3039. evdns_request_remove(req, &old_heads[i]);
  3040. evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
  3041. }
  3042. }
  3043. mm_free(old_heads);
  3044. }
  3045. base->req_heads = new_heads;
  3046. base->n_req_heads = n_heads;
  3047. base->global_max_requests_inflight = maxinflight;
  3048. return (0);
  3049. }
  3050. /* exported function */
  3051. int
  3052. evdns_base_set_option(struct evdns_base *base,
  3053. const char *option, const char *val)
  3054. {
  3055. int res;
  3056. EVDNS_LOCK(base);
  3057. res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
  3058. EVDNS_UNLOCK(base);
  3059. return res;
  3060. }
  3061. static inline int
  3062. str_matches_option(const char *s1, const char *optionname)
  3063. {
  3064. /* Option names are given as "option:" We accept either 'option' in
  3065. * s1, or 'option:randomjunk'. The latter form is to implement the
  3066. * resolv.conf parser. */
  3067. size_t optlen = strlen(optionname);
  3068. size_t slen = strlen(s1);
  3069. if (slen == optlen || slen == optlen - 1)
  3070. return !strncmp(s1, optionname, slen);
  3071. else if (slen > optlen)
  3072. return !strncmp(s1, optionname, optlen);
  3073. else
  3074. return 0;
  3075. }
  3076. static int
  3077. evdns_base_set_option_impl(struct evdns_base *base,
  3078. const char *option, const char *val, int flags)
  3079. {
  3080. ASSERT_LOCKED(base);
  3081. if (str_matches_option(option, "ndots:")) {
  3082. const int ndots = strtoint(val);
  3083. if (ndots == -1) return -1;
  3084. if (!(flags & DNS_OPTION_SEARCH)) return 0;
  3085. log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
  3086. if (!base->global_search_state) base->global_search_state = search_state_new();
  3087. if (!base->global_search_state) return -1;
  3088. base->global_search_state->ndots = ndots;
  3089. } else if (str_matches_option(option, "timeout:")) {
  3090. struct timeval tv;
  3091. if (evdns_strtotimeval(val, &tv) == -1) return -1;
  3092. if (!(flags & DNS_OPTION_MISC)) return 0;
  3093. log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
  3094. memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
  3095. } else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
  3096. struct timeval tv;
  3097. if (evdns_strtotimeval(val, &tv) == -1) return -1;
  3098. if (!(flags & DNS_OPTION_MISC)) return 0;
  3099. log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
  3100. val);
  3101. memcpy(&base->global_getaddrinfo_allow_skew, &tv,
  3102. sizeof(struct timeval));
  3103. } else if (str_matches_option(option, "max-timeouts:")) {
  3104. const int maxtimeout = strtoint_clipped(val, 1, 255);
  3105. if (maxtimeout == -1) return -1;
  3106. if (!(flags & DNS_OPTION_MISC)) return 0;
  3107. log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
  3108. maxtimeout);
  3109. base->global_max_nameserver_timeout = maxtimeout;
  3110. } else if (str_matches_option(option, "max-inflight:")) {
  3111. const int maxinflight = strtoint_clipped(val, 1, 65000);
  3112. if (maxinflight == -1) return -1;
  3113. if (!(flags & DNS_OPTION_MISC)) return 0;
  3114. log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
  3115. maxinflight);
  3116. evdns_base_set_max_requests_inflight(base, maxinflight);
  3117. } else if (str_matches_option(option, "attempts:")) {
  3118. int retries = strtoint(val);
  3119. if (retries == -1) return -1;
  3120. if (retries > 255) retries = 255;
  3121. if (!(flags & DNS_OPTION_MISC)) return 0;
  3122. log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
  3123. base->global_max_retransmits = retries;
  3124. } else if (str_matches_option(option, "randomize-case:")) {
  3125. int randcase = strtoint(val);
  3126. if (randcase == -1) return -1;
  3127. if (!(flags & DNS_OPTION_MISC)) return 0;
  3128. base->global_randomize_case = randcase;
  3129. } else if (str_matches_option(option, "bind-to:")) {
  3130. /* XXX This only applies to successive nameservers, not
  3131. * to already-configured ones. We might want to fix that. */
  3132. int len = sizeof(base->global_outgoing_address);
  3133. if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
  3134. if (evutil_parse_sockaddr_port(val,
  3135. (struct sockaddr*)&base->global_outgoing_address, &len))
  3136. return -1;
  3137. base->global_outgoing_addrlen = len;
  3138. } else if (str_matches_option(option, "initial-probe-timeout:")) {
  3139. struct timeval tv;
  3140. if (evdns_strtotimeval(val, &tv) == -1) return -1;
  3141. if (tv.tv_sec > 3600)
  3142. tv.tv_sec = 3600;
  3143. if (!(flags & DNS_OPTION_MISC)) return 0;
  3144. log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
  3145. val);
  3146. memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
  3147. sizeof(tv));
  3148. } else if (str_matches_option(option, "so-rcvbuf:")) {
  3149. int buf = strtoint(val);
  3150. if (buf == -1) return -1;
  3151. if (!(flags & DNS_OPTION_MISC)) return 0;
  3152. log(EVDNS_LOG_DEBUG, "Setting SO_RCVBUF to %s", val);
  3153. base->so_rcvbuf = buf;
  3154. } else if (str_matches_option(option, "so-sndbuf:")) {
  3155. int buf = strtoint(val);
  3156. if (buf == -1) return -1;
  3157. if (!(flags & DNS_OPTION_MISC)) return 0;
  3158. log(EVDNS_LOG_DEBUG, "Setting SO_SNDBUF to %s", val);
  3159. base->so_sndbuf = buf;
  3160. }
  3161. return 0;
  3162. }
  3163. int
  3164. evdns_set_option(const char *option, const char *val, int flags)
  3165. {
  3166. if (!current_base)
  3167. current_base = evdns_base_new(NULL, 0);
  3168. return evdns_base_set_option(current_base, option, val);
  3169. }
  3170. static void
  3171. resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
  3172. char *strtok_state;
  3173. static const char *const delims = " \t";
  3174. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  3175. char *const first_token = strtok_r(start, delims, &strtok_state);
  3176. ASSERT_LOCKED(base);
  3177. if (!first_token) return;
  3178. if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
  3179. const char *const nameserver = NEXT_TOKEN;
  3180. if (nameserver)
  3181. evdns_base_nameserver_ip_add(base, nameserver);
  3182. } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
  3183. const char *const domain = NEXT_TOKEN;
  3184. if (domain) {
  3185. search_postfix_clear(base);
  3186. search_postfix_add(base, domain);
  3187. }
  3188. } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
  3189. const char *domain;
  3190. search_postfix_clear(base);
  3191. while ((domain = NEXT_TOKEN)) {
  3192. search_postfix_add(base, domain);
  3193. }
  3194. search_reverse(base);
  3195. } else if (!strcmp(first_token, "options")) {
  3196. const char *option;
  3197. while ((option = NEXT_TOKEN)) {
  3198. const char *val = strchr(option, ':');
  3199. evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
  3200. }
  3201. }
  3202. #undef NEXT_TOKEN
  3203. }
  3204. /* exported function */
  3205. /* returns: */
  3206. /* 0 no errors */
  3207. /* 1 failed to open file */
  3208. /* 2 failed to stat file */
  3209. /* 3 file too large */
  3210. /* 4 out of memory */
  3211. /* 5 short read from file */
  3212. int
  3213. evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
  3214. int res;
  3215. EVDNS_LOCK(base);
  3216. res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
  3217. EVDNS_UNLOCK(base);
  3218. return res;
  3219. }
  3220. static char *
  3221. evdns_get_default_hosts_filename(void)
  3222. {
  3223. #ifdef _WIN32
  3224. /* Windows is a little coy about where it puts its configuration
  3225. * files. Sure, they're _usually_ in C:\windows\system32, but
  3226. * there's no reason in principle they couldn't be in
  3227. * W:\hoboken chicken emergency\
  3228. */
  3229. char path[MAX_PATH+1];
  3230. static const char hostfile[] = "\\drivers\\etc\\hosts";
  3231. char *path_out;
  3232. size_t len_out;
  3233. if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
  3234. return NULL;
  3235. len_out = strlen(path)+strlen(hostfile)+1;
  3236. path_out = mm_malloc(len_out);
  3237. evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
  3238. return path_out;
  3239. #else
  3240. return mm_strdup("/etc/hosts");
  3241. #endif
  3242. }
  3243. static int
  3244. evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
  3245. size_t n;
  3246. char *resolv;
  3247. char *start;
  3248. int err = 0;
  3249. int add_default;
  3250. log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
  3251. add_default = flags & DNS_OPTION_NAMESERVERS;
  3252. if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
  3253. add_default = 0;
  3254. if (flags & DNS_OPTION_HOSTSFILE) {
  3255. char *fname = evdns_get_default_hosts_filename();
  3256. evdns_base_load_hosts(base, fname);
  3257. if (fname)
  3258. mm_free(fname);
  3259. }
  3260. if (!filename) {
  3261. evdns_resolv_set_defaults(base, flags);
  3262. return 1;
  3263. }
  3264. if ((err = evutil_read_file_(filename, &resolv, &n, 0)) < 0) {
  3265. if (err == -1) {
  3266. /* No file. */
  3267. evdns_resolv_set_defaults(base, flags);
  3268. return 1;
  3269. } else {
  3270. return 2;
  3271. }
  3272. }
  3273. start = resolv;
  3274. for (;;) {
  3275. char *const newline = strchr(start, '\n');
  3276. if (!newline) {
  3277. resolv_conf_parse_line(base, start, flags);
  3278. break;
  3279. } else {
  3280. *newline = 0;
  3281. resolv_conf_parse_line(base, start, flags);
  3282. start = newline + 1;
  3283. }
  3284. }
  3285. if (!base->server_head && add_default) {
  3286. /* no nameservers were configured. */
  3287. evdns_base_nameserver_ip_add(base, "127.0.0.1");
  3288. err = 6;
  3289. }
  3290. if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
  3291. search_set_from_hostname(base);
  3292. }
  3293. mm_free(resolv);
  3294. return err;
  3295. }
  3296. int
  3297. evdns_resolv_conf_parse(int flags, const char *const filename) {
  3298. if (!current_base)
  3299. current_base = evdns_base_new(NULL, 0);
  3300. return evdns_base_resolv_conf_parse(current_base, flags, filename);
  3301. }
  3302. #ifdef _WIN32
  3303. /* Add multiple nameservers from a space-or-comma-separated list. */
  3304. static int
  3305. evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
  3306. const char *addr;
  3307. char *buf;
  3308. int r;
  3309. ASSERT_LOCKED(base);
  3310. while (*ips) {
  3311. while (isspace(*ips) || *ips == ',' || *ips == '\t')
  3312. ++ips;
  3313. addr = ips;
  3314. while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
  3315. *ips=='[' || *ips==']')
  3316. ++ips;
  3317. buf = mm_malloc(ips-addr+1);
  3318. if (!buf) return 4;
  3319. memcpy(buf, addr, ips-addr);
  3320. buf[ips-addr] = '\0';
  3321. r = evdns_base_nameserver_ip_add(base, buf);
  3322. mm_free(buf);
  3323. if (r) return r;
  3324. }
  3325. return 0;
  3326. }
  3327. typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
  3328. /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
  3329. /* figure out what our nameservers are. */
  3330. static int
  3331. load_nameservers_with_getnetworkparams(struct evdns_base *base)
  3332. {
  3333. /* Based on MSDN examples and inspection of c-ares code. */
  3334. FIXED_INFO *fixed;
  3335. HMODULE handle = 0;
  3336. ULONG size = sizeof(FIXED_INFO);
  3337. void *buf = NULL;
  3338. int status = 0, r, added_any;
  3339. IP_ADDR_STRING *ns;
  3340. GetNetworkParams_fn_t fn;
  3341. ASSERT_LOCKED(base);
  3342. if (!(handle = evutil_load_windows_system_library_(
  3343. TEXT("iphlpapi.dll")))) {
  3344. log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
  3345. status = -1;
  3346. goto done;
  3347. }
  3348. if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
  3349. log(EVDNS_LOG_WARN, "Could not get address of function.");
  3350. status = -1;
  3351. goto done;
  3352. }
  3353. buf = mm_malloc(size);
  3354. if (!buf) { status = 4; goto done; }
  3355. fixed = buf;
  3356. r = fn(fixed, &size);
  3357. if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
  3358. status = -1;
  3359. goto done;
  3360. }
  3361. if (r != ERROR_SUCCESS) {
  3362. mm_free(buf);
  3363. buf = mm_malloc(size);
  3364. if (!buf) { status = 4; goto done; }
  3365. fixed = buf;
  3366. r = fn(fixed, &size);
  3367. if (r != ERROR_SUCCESS) {
  3368. log(EVDNS_LOG_DEBUG, "fn() failed.");
  3369. status = -1;
  3370. goto done;
  3371. }
  3372. }
  3373. EVUTIL_ASSERT(fixed);
  3374. added_any = 0;
  3375. ns = &(fixed->DnsServerList);
  3376. while (ns) {
  3377. r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
  3378. if (r) {
  3379. log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
  3380. (ns->IpAddress.String),(int)GetLastError());
  3381. status = r;
  3382. } else {
  3383. ++added_any;
  3384. log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
  3385. }
  3386. ns = ns->Next;
  3387. }
  3388. if (!added_any) {
  3389. log(EVDNS_LOG_DEBUG, "No nameservers added.");
  3390. if (status == 0)
  3391. status = -1;
  3392. } else {
  3393. status = 0;
  3394. }
  3395. done:
  3396. if (buf)
  3397. mm_free(buf);
  3398. if (handle)
  3399. FreeLibrary(handle);
  3400. return status;
  3401. }
  3402. static int
  3403. config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
  3404. {
  3405. char *buf;
  3406. DWORD bufsz = 0, type = 0;
  3407. int status = 0;
  3408. ASSERT_LOCKED(base);
  3409. if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
  3410. != ERROR_MORE_DATA)
  3411. return -1;
  3412. if (!(buf = mm_malloc(bufsz)))
  3413. return -1;
  3414. if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
  3415. == ERROR_SUCCESS && bufsz > 1) {
  3416. status = evdns_nameserver_ip_add_line(base,buf);
  3417. }
  3418. mm_free(buf);
  3419. return status;
  3420. }
  3421. #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
  3422. #define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
  3423. #define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
  3424. static int
  3425. load_nameservers_from_registry(struct evdns_base *base)
  3426. {
  3427. int found = 0;
  3428. int r;
  3429. #define TRY(k, name) \
  3430. if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
  3431. log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
  3432. found = 1; \
  3433. } else if (!found) { \
  3434. log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
  3435. #k,#name); \
  3436. }
  3437. ASSERT_LOCKED(base);
  3438. if (((int)GetVersion()) > 0) { /* NT */
  3439. HKEY nt_key = 0, interfaces_key = 0;
  3440. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
  3441. KEY_READ, &nt_key) != ERROR_SUCCESS) {
  3442. log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
  3443. return -1;
  3444. }
  3445. r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
  3446. KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
  3447. &interfaces_key);
  3448. if (r != ERROR_SUCCESS) {
  3449. log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
  3450. return -1;
  3451. }
  3452. TRY(nt_key, "NameServer");
  3453. TRY(nt_key, "DhcpNameServer");
  3454. TRY(interfaces_key, "NameServer");
  3455. TRY(interfaces_key, "DhcpNameServer");
  3456. RegCloseKey(interfaces_key);
  3457. RegCloseKey(nt_key);
  3458. } else {
  3459. HKEY win_key = 0;
  3460. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
  3461. KEY_READ, &win_key) != ERROR_SUCCESS) {
  3462. log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
  3463. return -1;
  3464. }
  3465. TRY(win_key, "NameServer");
  3466. RegCloseKey(win_key);
  3467. }
  3468. if (found == 0) {
  3469. log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
  3470. }
  3471. return found ? 0 : -1;
  3472. #undef TRY
  3473. }
  3474. int
  3475. evdns_base_config_windows_nameservers(struct evdns_base *base)
  3476. {
  3477. int r;
  3478. char *fname;
  3479. if (base == NULL)
  3480. base = current_base;
  3481. if (base == NULL)
  3482. return -1;
  3483. EVDNS_LOCK(base);
  3484. fname = evdns_get_default_hosts_filename();
  3485. log(EVDNS_LOG_DEBUG, "Loading hosts entries from %s", fname);
  3486. evdns_base_load_hosts(base, fname);
  3487. if (fname)
  3488. mm_free(fname);
  3489. if (load_nameservers_with_getnetworkparams(base) == 0) {
  3490. EVDNS_UNLOCK(base);
  3491. return 0;
  3492. }
  3493. r = load_nameservers_from_registry(base);
  3494. EVDNS_UNLOCK(base);
  3495. return r;
  3496. }
  3497. int
  3498. evdns_config_windows_nameservers(void)
  3499. {
  3500. if (!current_base) {
  3501. current_base = evdns_base_new(NULL, 1);
  3502. return current_base == NULL ? -1 : 0;
  3503. } else {
  3504. return evdns_base_config_windows_nameservers(current_base);
  3505. }
  3506. }
  3507. #endif
  3508. struct evdns_base *
  3509. evdns_base_new(struct event_base *event_base, int flags)
  3510. {
  3511. struct evdns_base *base;
  3512. if (evutil_secure_rng_init() < 0) {
  3513. log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
  3514. "DNS can't run.");
  3515. return NULL;
  3516. }
  3517. /* Give the evutil library a hook into its evdns-enabled
  3518. * functionality. We can't just call evdns_getaddrinfo directly or
  3519. * else libevent-core will depend on libevent-extras. */
  3520. evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo);
  3521. evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel);
  3522. base = mm_malloc(sizeof(struct evdns_base));
  3523. if (base == NULL)
  3524. return (NULL);
  3525. memset(base, 0, sizeof(struct evdns_base));
  3526. base->req_waiting_head = NULL;
  3527. EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  3528. EVDNS_LOCK(base);
  3529. /* Set max requests inflight and allocate req_heads. */
  3530. base->req_heads = NULL;
  3531. evdns_base_set_max_requests_inflight(base, 64);
  3532. base->server_head = NULL;
  3533. base->event_base = event_base;
  3534. base->global_good_nameservers = base->global_requests_inflight =
  3535. base->global_requests_waiting = 0;
  3536. base->global_timeout.tv_sec = 5;
  3537. base->global_timeout.tv_usec = 0;
  3538. base->global_max_reissues = 1;
  3539. base->global_max_retransmits = 3;
  3540. base->global_max_nameserver_timeout = 3;
  3541. base->global_search_state = NULL;
  3542. base->global_randomize_case = 1;
  3543. base->global_getaddrinfo_allow_skew.tv_sec = 3;
  3544. base->global_getaddrinfo_allow_skew.tv_usec = 0;
  3545. base->global_nameserver_probe_initial_timeout.tv_sec = 10;
  3546. base->global_nameserver_probe_initial_timeout.tv_usec = 0;
  3547. TAILQ_INIT(&base->hostsdb);
  3548. #define EVDNS_BASE_ALL_FLAGS ( \
  3549. EVDNS_BASE_INITIALIZE_NAMESERVERS | \
  3550. EVDNS_BASE_DISABLE_WHEN_INACTIVE | \
  3551. EVDNS_BASE_NAMESERVERS_NO_DEFAULT | \
  3552. 0)
  3553. if (flags & ~EVDNS_BASE_ALL_FLAGS) {
  3554. flags = EVDNS_BASE_INITIALIZE_NAMESERVERS;
  3555. log(EVDNS_LOG_WARN,
  3556. "Unrecognized flag passed to evdns_base_new(). Assuming "
  3557. "you meant EVDNS_BASE_INITIALIZE_NAMESERVERS.");
  3558. }
  3559. #undef EVDNS_BASE_ALL_FLAGS
  3560. if (flags & EVDNS_BASE_INITIALIZE_NAMESERVERS) {
  3561. int r;
  3562. int opts = DNS_OPTIONS_ALL;
  3563. if (flags & EVDNS_BASE_NAMESERVERS_NO_DEFAULT) {
  3564. opts |= DNS_OPTION_NAMESERVERS_NO_DEFAULT;
  3565. }
  3566. #ifdef _WIN32
  3567. r = evdns_base_config_windows_nameservers(base);
  3568. #else
  3569. r = evdns_base_resolv_conf_parse(base, opts, "/etc/resolv.conf");
  3570. #endif
  3571. if (r) {
  3572. evdns_base_free_and_unlock(base, 0);
  3573. return NULL;
  3574. }
  3575. }
  3576. if (flags & EVDNS_BASE_DISABLE_WHEN_INACTIVE) {
  3577. base->disable_when_inactive = 1;
  3578. }
  3579. EVDNS_UNLOCK(base);
  3580. return base;
  3581. }
  3582. int
  3583. evdns_init(void)
  3584. {
  3585. struct evdns_base *base = evdns_base_new(NULL, 1);
  3586. if (base) {
  3587. current_base = base;
  3588. return 0;
  3589. } else {
  3590. return -1;
  3591. }
  3592. }
  3593. const char *
  3594. evdns_err_to_string(int err)
  3595. {
  3596. switch (err) {
  3597. case DNS_ERR_NONE: return "no error";
  3598. case DNS_ERR_FORMAT: return "misformatted query";
  3599. case DNS_ERR_SERVERFAILED: return "server failed";
  3600. case DNS_ERR_NOTEXIST: return "name does not exist";
  3601. case DNS_ERR_NOTIMPL: return "query not implemented";
  3602. case DNS_ERR_REFUSED: return "refused";
  3603. case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
  3604. case DNS_ERR_UNKNOWN: return "unknown";
  3605. case DNS_ERR_TIMEOUT: return "request timed out";
  3606. case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
  3607. case DNS_ERR_CANCEL: return "dns request canceled";
  3608. case DNS_ERR_NODATA: return "no records in the reply";
  3609. default: return "[Unknown error code]";
  3610. }
  3611. }
  3612. static void
  3613. evdns_nameserver_free(struct nameserver *server)
  3614. {
  3615. if (server->socket >= 0)
  3616. evutil_closesocket(server->socket);
  3617. (void) event_del(&server->event);
  3618. event_debug_unassign(&server->event);
  3619. if (server->state == 0)
  3620. (void) event_del(&server->timeout_event);
  3621. if (server->probe_request) {
  3622. evdns_cancel_request(server->base, server->probe_request);
  3623. server->probe_request = NULL;
  3624. }
  3625. event_debug_unassign(&server->timeout_event);
  3626. mm_free(server);
  3627. }
  3628. static void
  3629. evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
  3630. {
  3631. struct nameserver *server, *server_next;
  3632. struct search_domain *dom, *dom_next;
  3633. int i;
  3634. /* Requires that we hold the lock. */
  3635. /* TODO(nickm) we might need to refcount here. */
  3636. while (base->req_waiting_head) {
  3637. if (fail_requests)
  3638. reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
  3639. request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
  3640. }
  3641. for (i = 0; i < base->n_req_heads; ++i) {
  3642. while (base->req_heads[i]) {
  3643. if (fail_requests)
  3644. reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
  3645. request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
  3646. }
  3647. }
  3648. base->global_requests_inflight = base->global_requests_waiting = 0;
  3649. for (server = base->server_head; server; server = server_next) {
  3650. server_next = server->next;
  3651. /** already done something before */
  3652. server->probe_request = NULL;
  3653. evdns_nameserver_free(server);
  3654. if (server_next == base->server_head)
  3655. break;
  3656. }
  3657. base->server_head = NULL;
  3658. base->global_good_nameservers = 0;
  3659. if (base->global_search_state) {
  3660. for (dom = base->global_search_state->head; dom; dom = dom_next) {
  3661. dom_next = dom->next;
  3662. mm_free(dom);
  3663. }
  3664. mm_free(base->global_search_state);
  3665. base->global_search_state = NULL;
  3666. }
  3667. {
  3668. struct hosts_entry *victim;
  3669. while ((victim = TAILQ_FIRST(&base->hostsdb))) {
  3670. TAILQ_REMOVE(&base->hostsdb, victim, next);
  3671. mm_free(victim);
  3672. }
  3673. }
  3674. mm_free(base->req_heads);
  3675. EVDNS_UNLOCK(base);
  3676. EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  3677. mm_free(base);
  3678. }
  3679. void
  3680. evdns_base_free(struct evdns_base *base, int fail_requests)
  3681. {
  3682. EVDNS_LOCK(base);
  3683. evdns_base_free_and_unlock(base, fail_requests);
  3684. }
  3685. void
  3686. evdns_base_clear_host_addresses(struct evdns_base *base)
  3687. {
  3688. struct hosts_entry *victim;
  3689. EVDNS_LOCK(base);
  3690. while ((victim = TAILQ_FIRST(&base->hostsdb))) {
  3691. TAILQ_REMOVE(&base->hostsdb, victim, next);
  3692. mm_free(victim);
  3693. }
  3694. EVDNS_UNLOCK(base);
  3695. }
  3696. void
  3697. evdns_shutdown(int fail_requests)
  3698. {
  3699. if (current_base) {
  3700. struct evdns_base *b = current_base;
  3701. current_base = NULL;
  3702. evdns_base_free(b, fail_requests);
  3703. }
  3704. evdns_log_fn = NULL;
  3705. }
  3706. static int
  3707. evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
  3708. {
  3709. char *strtok_state;
  3710. static const char *const delims = " \t";
  3711. char *const addr = strtok_r(line, delims, &strtok_state);
  3712. char *hostname, *hash;
  3713. struct sockaddr_storage ss;
  3714. int socklen = sizeof(ss);
  3715. ASSERT_LOCKED(base);
  3716. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  3717. if (!addr || *addr == '#')
  3718. return 0;
  3719. memset(&ss, 0, sizeof(ss));
  3720. if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
  3721. return -1;
  3722. if (socklen > (int)sizeof(struct sockaddr_in6))
  3723. return -1;
  3724. if (sockaddr_getport((struct sockaddr*)&ss))
  3725. return -1;
  3726. while ((hostname = NEXT_TOKEN)) {
  3727. struct hosts_entry *he;
  3728. size_t namelen;
  3729. if ((hash = strchr(hostname, '#'))) {
  3730. if (hash == hostname)
  3731. return 0;
  3732. *hash = '\0';
  3733. }
  3734. namelen = strlen(hostname);
  3735. he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
  3736. if (!he)
  3737. return -1;
  3738. EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
  3739. memcpy(&he->addr, &ss, socklen);
  3740. memcpy(he->hostname, hostname, namelen+1);
  3741. he->addrlen = socklen;
  3742. TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
  3743. if (hash)
  3744. return 0;
  3745. }
  3746. return 0;
  3747. #undef NEXT_TOKEN
  3748. }
  3749. static int
  3750. evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
  3751. {
  3752. char *str=NULL, *cp, *eol;
  3753. size_t len;
  3754. int err=0;
  3755. ASSERT_LOCKED(base);
  3756. if (hosts_fname == NULL ||
  3757. (err = evutil_read_file_(hosts_fname, &str, &len, 0)) < 0) {
  3758. char tmp[64];
  3759. strlcpy(tmp, "127.0.0.1 localhost", sizeof(tmp));
  3760. evdns_base_parse_hosts_line(base, tmp);
  3761. strlcpy(tmp, "::1 localhost", sizeof(tmp));
  3762. evdns_base_parse_hosts_line(base, tmp);
  3763. return err ? -1 : 0;
  3764. }
  3765. /* This will break early if there is a NUL in the hosts file.
  3766. * Probably not a problem.*/
  3767. cp = str;
  3768. for (;;) {
  3769. eol = strchr(cp, '\n');
  3770. if (eol) {
  3771. *eol = '\0';
  3772. evdns_base_parse_hosts_line(base, cp);
  3773. cp = eol+1;
  3774. } else {
  3775. evdns_base_parse_hosts_line(base, cp);
  3776. break;
  3777. }
  3778. }
  3779. mm_free(str);
  3780. return 0;
  3781. }
  3782. int
  3783. evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
  3784. {
  3785. int res;
  3786. if (!base)
  3787. base = current_base;
  3788. EVDNS_LOCK(base);
  3789. res = evdns_base_load_hosts_impl(base, hosts_fname);
  3790. EVDNS_UNLOCK(base);
  3791. return res;
  3792. }
  3793. /* A single request for a getaddrinfo, either v4 or v6. */
  3794. struct getaddrinfo_subrequest {
  3795. struct evdns_request *r;
  3796. ev_uint32_t type;
  3797. };
  3798. /* State data used to implement an in-progress getaddrinfo. */
  3799. struct evdns_getaddrinfo_request {
  3800. struct evdns_base *evdns_base;
  3801. /* Copy of the modified 'hints' data that we'll use to build
  3802. * answers. */
  3803. struct evutil_addrinfo hints;
  3804. /* The callback to invoke when we're done */
  3805. evdns_getaddrinfo_cb user_cb;
  3806. /* User-supplied data to give to the callback. */
  3807. void *user_data;
  3808. /* The port to use when building sockaddrs. */
  3809. ev_uint16_t port;
  3810. /* The sub_request for an A record (if any) */
  3811. struct getaddrinfo_subrequest ipv4_request;
  3812. /* The sub_request for an AAAA record (if any) */
  3813. struct getaddrinfo_subrequest ipv6_request;
  3814. /* The cname result that we were told (if any) */
  3815. char *cname_result;
  3816. /* If we have one request answered and one request still inflight,
  3817. * then this field holds the answer from the first request... */
  3818. struct evutil_addrinfo *pending_result;
  3819. /* And this event is a timeout that will tell us to cancel the second
  3820. * request if it's taking a long time. */
  3821. struct event timeout;
  3822. /* And this field holds the error code from the first request... */
  3823. int pending_error;
  3824. /* If this is set, the user canceled this request. */
  3825. unsigned user_canceled : 1;
  3826. /* If this is set, the user can no longer cancel this request; we're
  3827. * just waiting for the free. */
  3828. unsigned request_done : 1;
  3829. };
  3830. /* Convert an evdns errors to the equivalent getaddrinfo error. */
  3831. static int
  3832. evdns_err_to_getaddrinfo_err(int e1)
  3833. {
  3834. /* XXX Do this better! */
  3835. if (e1 == DNS_ERR_NONE)
  3836. return 0;
  3837. else if (e1 == DNS_ERR_NOTEXIST)
  3838. return EVUTIL_EAI_NONAME;
  3839. else
  3840. return EVUTIL_EAI_FAIL;
  3841. }
  3842. /* Return the more informative of two getaddrinfo errors. */
  3843. static int
  3844. getaddrinfo_merge_err(int e1, int e2)
  3845. {
  3846. /* XXXX be cleverer here. */
  3847. if (e1 == 0)
  3848. return e2;
  3849. else
  3850. return e1;
  3851. }
  3852. static void
  3853. free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
  3854. {
  3855. /* DO NOT CALL this if either of the requests is pending. Only once
  3856. * both callbacks have been invoked is it safe to free the request */
  3857. if (data->pending_result)
  3858. evutil_freeaddrinfo(data->pending_result);
  3859. if (data->cname_result)
  3860. mm_free(data->cname_result);
  3861. event_del(&data->timeout);
  3862. mm_free(data);
  3863. return;
  3864. }
  3865. static void
  3866. add_cname_to_reply(struct evdns_getaddrinfo_request *data,
  3867. struct evutil_addrinfo *ai)
  3868. {
  3869. if (data->cname_result && ai) {
  3870. ai->ai_canonname = data->cname_result;
  3871. data->cname_result = NULL;
  3872. }
  3873. }
  3874. /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
  3875. * request has finished, but the other one took too long to answer. Pass
  3876. * along the answer we got, and cancel the other request.
  3877. */
  3878. static void
  3879. evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
  3880. {
  3881. int v4_timedout = 0, v6_timedout = 0;
  3882. struct evdns_getaddrinfo_request *data = ptr;
  3883. /* Cancel any pending requests, and note which one */
  3884. if (data->ipv4_request.r) {
  3885. /* XXXX This does nothing if the request's callback is already
  3886. * running (pending_cb is set). */
  3887. evdns_cancel_request(NULL, data->ipv4_request.r);
  3888. v4_timedout = 1;
  3889. EVDNS_LOCK(data->evdns_base);
  3890. ++data->evdns_base->getaddrinfo_ipv4_timeouts;
  3891. EVDNS_UNLOCK(data->evdns_base);
  3892. }
  3893. if (data->ipv6_request.r) {
  3894. /* XXXX This does nothing if the request's callback is already
  3895. * running (pending_cb is set). */
  3896. evdns_cancel_request(NULL, data->ipv6_request.r);
  3897. v6_timedout = 1;
  3898. EVDNS_LOCK(data->evdns_base);
  3899. ++data->evdns_base->getaddrinfo_ipv6_timeouts;
  3900. EVDNS_UNLOCK(data->evdns_base);
  3901. }
  3902. /* We only use this timeout callback when we have an answer for
  3903. * one address. */
  3904. EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
  3905. /* Report the outcome of the other request that didn't time out. */
  3906. if (data->pending_result) {
  3907. add_cname_to_reply(data, data->pending_result);
  3908. data->user_cb(0, data->pending_result, data->user_data);
  3909. data->pending_result = NULL;
  3910. } else {
  3911. int e = data->pending_error;
  3912. if (!e)
  3913. e = EVUTIL_EAI_AGAIN;
  3914. data->user_cb(e, NULL, data->user_data);
  3915. }
  3916. data->user_cb = NULL; /* prevent double-call if evdns callbacks are
  3917. * in-progress. XXXX It would be better if this
  3918. * weren't necessary. */
  3919. if (!v4_timedout && !v6_timedout) {
  3920. /* should be impossible? XXXX */
  3921. free_getaddrinfo_request(data);
  3922. }
  3923. }
  3924. static int
  3925. evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
  3926. struct evdns_getaddrinfo_request *data)
  3927. {
  3928. return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
  3929. }
  3930. static inline int
  3931. evdns_result_is_answer(int result)
  3932. {
  3933. return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
  3934. result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
  3935. }
  3936. static void
  3937. evdns_getaddrinfo_gotresolve(int result, char type, int count,
  3938. int ttl, void *addresses, void *arg)
  3939. {
  3940. int i;
  3941. struct getaddrinfo_subrequest *req = arg;
  3942. struct getaddrinfo_subrequest *other_req;
  3943. struct evdns_getaddrinfo_request *data;
  3944. struct evutil_addrinfo *res;
  3945. struct sockaddr_in sin;
  3946. struct sockaddr_in6 sin6;
  3947. struct sockaddr *sa;
  3948. int socklen, addrlen;
  3949. void *addrp;
  3950. int err;
  3951. int user_canceled;
  3952. EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
  3953. if (req->type == DNS_IPv4_A) {
  3954. data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
  3955. other_req = &data->ipv6_request;
  3956. } else {
  3957. data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
  3958. other_req = &data->ipv4_request;
  3959. }
  3960. /** Called from evdns_base_free() with @fail_requests == 1 */
  3961. if (result != DNS_ERR_SHUTDOWN) {
  3962. EVDNS_LOCK(data->evdns_base);
  3963. if (evdns_result_is_answer(result)) {
  3964. if (req->type == DNS_IPv4_A)
  3965. ++data->evdns_base->getaddrinfo_ipv4_answered;
  3966. else
  3967. ++data->evdns_base->getaddrinfo_ipv6_answered;
  3968. }
  3969. user_canceled = data->user_canceled;
  3970. if (other_req->r == NULL)
  3971. data->request_done = 1;
  3972. EVDNS_UNLOCK(data->evdns_base);
  3973. } else {
  3974. data->evdns_base = NULL;
  3975. user_canceled = data->user_canceled;
  3976. }
  3977. req->r = NULL;
  3978. if (result == DNS_ERR_CANCEL && ! user_canceled) {
  3979. /* Internal cancel request from timeout or internal error.
  3980. * we already answered the user. */
  3981. if (other_req->r == NULL)
  3982. free_getaddrinfo_request(data);
  3983. return;
  3984. }
  3985. if (data->user_cb == NULL) {
  3986. /* We already answered. XXXX This shouldn't be needed; see
  3987. * comments in evdns_getaddrinfo_timeout_cb */
  3988. free_getaddrinfo_request(data);
  3989. return;
  3990. }
  3991. if (result == DNS_ERR_NONE) {
  3992. if (count == 0)
  3993. err = EVUTIL_EAI_NODATA;
  3994. else
  3995. err = 0;
  3996. } else {
  3997. err = evdns_err_to_getaddrinfo_err(result);
  3998. }
  3999. if (err) {
  4000. /* Looks like we got an error. */
  4001. if (other_req->r) {
  4002. /* The other request is still working; maybe it will
  4003. * succeed. */
  4004. /* XXXX handle failure from set_timeout */
  4005. if (result != DNS_ERR_SHUTDOWN) {
  4006. evdns_getaddrinfo_set_timeout(data->evdns_base, data);
  4007. }
  4008. data->pending_error = err;
  4009. return;
  4010. }
  4011. if (user_canceled) {
  4012. data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
  4013. } else if (data->pending_result) {
  4014. /* If we have an answer waiting, and we weren't
  4015. * canceled, ignore this error. */
  4016. add_cname_to_reply(data, data->pending_result);
  4017. data->user_cb(0, data->pending_result, data->user_data);
  4018. data->pending_result = NULL;
  4019. } else {
  4020. if (data->pending_error)
  4021. err = getaddrinfo_merge_err(err,
  4022. data->pending_error);
  4023. data->user_cb(err, NULL, data->user_data);
  4024. }
  4025. free_getaddrinfo_request(data);
  4026. return;
  4027. } else if (user_canceled) {
  4028. if (other_req->r) {
  4029. /* The other request is still working; let it hit this
  4030. * callback with EVUTIL_EAI_CANCEL callback and report
  4031. * the failure. */
  4032. return;
  4033. }
  4034. data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
  4035. free_getaddrinfo_request(data);
  4036. return;
  4037. }
  4038. /* Looks like we got some answers. We should turn them into addrinfos
  4039. * and then either queue those or return them all. */
  4040. EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
  4041. if (type == DNS_IPv4_A) {
  4042. memset(&sin, 0, sizeof(sin));
  4043. sin.sin_family = AF_INET;
  4044. sin.sin_port = htons(data->port);
  4045. sa = (struct sockaddr *)&sin;
  4046. socklen = sizeof(sin);
  4047. addrlen = 4;
  4048. addrp = &sin.sin_addr.s_addr;
  4049. } else {
  4050. memset(&sin6, 0, sizeof(sin6));
  4051. sin6.sin6_family = AF_INET6;
  4052. sin6.sin6_port = htons(data->port);
  4053. sa = (struct sockaddr *)&sin6;
  4054. socklen = sizeof(sin6);
  4055. addrlen = 16;
  4056. addrp = &sin6.sin6_addr.s6_addr;
  4057. }
  4058. res = NULL;
  4059. for (i=0; i < count; ++i) {
  4060. struct evutil_addrinfo *ai;
  4061. memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
  4062. ai = evutil_new_addrinfo_(sa, socklen, &data->hints);
  4063. if (!ai) {
  4064. if (other_req->r) {
  4065. evdns_cancel_request(NULL, other_req->r);
  4066. }
  4067. data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
  4068. if (res)
  4069. evutil_freeaddrinfo(res);
  4070. if (other_req->r == NULL)
  4071. free_getaddrinfo_request(data);
  4072. return;
  4073. }
  4074. res = evutil_addrinfo_append_(res, ai);
  4075. }
  4076. if (other_req->r) {
  4077. /* The other request is still in progress; wait for it */
  4078. /* XXXX handle failure from set_timeout */
  4079. evdns_getaddrinfo_set_timeout(data->evdns_base, data);
  4080. data->pending_result = res;
  4081. return;
  4082. } else {
  4083. /* The other request is done or never started; append its
  4084. * results (if any) and return them. */
  4085. if (data->pending_result) {
  4086. if (req->type == DNS_IPv4_A)
  4087. res = evutil_addrinfo_append_(res,
  4088. data->pending_result);
  4089. else
  4090. res = evutil_addrinfo_append_(
  4091. data->pending_result, res);
  4092. data->pending_result = NULL;
  4093. }
  4094. /* Call the user callback. */
  4095. add_cname_to_reply(data, res);
  4096. data->user_cb(0, res, data->user_data);
  4097. /* Free data. */
  4098. free_getaddrinfo_request(data);
  4099. }
  4100. }
  4101. static struct hosts_entry *
  4102. find_hosts_entry(struct evdns_base *base, const char *hostname,
  4103. struct hosts_entry *find_after)
  4104. {
  4105. struct hosts_entry *e;
  4106. if (find_after)
  4107. e = TAILQ_NEXT(find_after, next);
  4108. else
  4109. e = TAILQ_FIRST(&base->hostsdb);
  4110. for (; e; e = TAILQ_NEXT(e, next)) {
  4111. if (!evutil_ascii_strcasecmp(e->hostname, hostname))
  4112. return e;
  4113. }
  4114. return NULL;
  4115. }
  4116. static int
  4117. evdns_getaddrinfo_fromhosts(struct evdns_base *base,
  4118. const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
  4119. struct evutil_addrinfo **res)
  4120. {
  4121. int n_found = 0;
  4122. struct hosts_entry *e;
  4123. struct evutil_addrinfo *ai=NULL;
  4124. int f = hints->ai_family;
  4125. EVDNS_LOCK(base);
  4126. for (e = find_hosts_entry(base, nodename, NULL); e;
  4127. e = find_hosts_entry(base, nodename, e)) {
  4128. struct evutil_addrinfo *ai_new;
  4129. ++n_found;
  4130. if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
  4131. (e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
  4132. continue;
  4133. ai_new = evutil_new_addrinfo_(&e->addr.sa, e->addrlen, hints);
  4134. if (!ai_new) {
  4135. n_found = 0;
  4136. goto out;
  4137. }
  4138. sockaddr_setport(ai_new->ai_addr, port);
  4139. ai = evutil_addrinfo_append_(ai, ai_new);
  4140. }
  4141. EVDNS_UNLOCK(base);
  4142. out:
  4143. if (n_found) {
  4144. /* Note that we return an empty answer if we found entries for
  4145. * this hostname but none were of the right address type. */
  4146. *res = ai;
  4147. return 0;
  4148. } else {
  4149. if (ai)
  4150. evutil_freeaddrinfo(ai);
  4151. return -1;
  4152. }
  4153. }
  4154. struct evdns_getaddrinfo_request *
  4155. evdns_getaddrinfo(struct evdns_base *dns_base,
  4156. const char *nodename, const char *servname,
  4157. const struct evutil_addrinfo *hints_in,
  4158. evdns_getaddrinfo_cb cb, void *arg)
  4159. {
  4160. struct evdns_getaddrinfo_request *data;
  4161. struct evutil_addrinfo hints;
  4162. struct evutil_addrinfo *res = NULL;
  4163. int err;
  4164. int port = 0;
  4165. int want_cname = 0;
  4166. int started = 0;
  4167. if (!dns_base) {
  4168. dns_base = current_base;
  4169. if (!dns_base) {
  4170. log(EVDNS_LOG_WARN,
  4171. "Call to getaddrinfo_async with no "
  4172. "evdns_base configured.");
  4173. cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
  4174. return NULL;
  4175. }
  4176. }
  4177. /* If we _must_ answer this immediately, do so. */
  4178. if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
  4179. res = NULL;
  4180. err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
  4181. cb(err, res, arg);
  4182. return NULL;
  4183. }
  4184. if (hints_in) {
  4185. memcpy(&hints, hints_in, sizeof(hints));
  4186. } else {
  4187. memset(&hints, 0, sizeof(hints));
  4188. hints.ai_family = PF_UNSPEC;
  4189. }
  4190. evutil_adjust_hints_for_addrconfig_(&hints);
  4191. /* Now try to see if we _can_ answer immediately. */
  4192. /* (It would be nice to do this by calling getaddrinfo directly, with
  4193. * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
  4194. * a reliable way to distinguish the "that wasn't a numeric host!" case
  4195. * from any other EAI_NONAME cases.) */
  4196. err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
  4197. if (err != EVUTIL_EAI_NEED_RESOLVE) {
  4198. cb(err, res, arg);
  4199. return NULL;
  4200. }
  4201. /* If there is an entry in the hosts file, we should give it now. */
  4202. if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
  4203. cb(0, res, arg);
  4204. return NULL;
  4205. }
  4206. /* Okay, things are serious now. We're going to need to actually
  4207. * launch a request.
  4208. */
  4209. data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
  4210. if (!data) {
  4211. cb(EVUTIL_EAI_MEMORY, NULL, arg);
  4212. return NULL;
  4213. }
  4214. memcpy(&data->hints, &hints, sizeof(data->hints));
  4215. data->port = (ev_uint16_t)port;
  4216. data->ipv4_request.type = DNS_IPv4_A;
  4217. data->ipv6_request.type = DNS_IPv6_AAAA;
  4218. data->user_cb = cb;
  4219. data->user_data = arg;
  4220. data->evdns_base = dns_base;
  4221. want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
  4222. /* If we are asked for a PF_UNSPEC address, we launch two requests in
  4223. * parallel: one for an A address and one for an AAAA address. We
  4224. * can't send just one request, since many servers only answer one
  4225. * question per DNS request.
  4226. *
  4227. * Once we have the answer to one request, we allow for a short
  4228. * timeout before we report it, to see if the other one arrives. If
  4229. * they both show up in time, then we report both the answers.
  4230. *
  4231. * If too many addresses of one type time out or fail, we should stop
  4232. * launching those requests. (XXX we don't do that yet.)
  4233. */
  4234. EVDNS_LOCK(dns_base);
  4235. if (hints.ai_family != PF_INET6) {
  4236. log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
  4237. nodename, &data->ipv4_request);
  4238. data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
  4239. nodename, 0, evdns_getaddrinfo_gotresolve,
  4240. &data->ipv4_request);
  4241. if (want_cname && data->ipv4_request.r)
  4242. data->ipv4_request.r->current_req->put_cname_in_ptr =
  4243. &data->cname_result;
  4244. }
  4245. if (hints.ai_family != PF_INET) {
  4246. log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
  4247. nodename, &data->ipv6_request);
  4248. data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
  4249. nodename, 0, evdns_getaddrinfo_gotresolve,
  4250. &data->ipv6_request);
  4251. if (want_cname && data->ipv6_request.r)
  4252. data->ipv6_request.r->current_req->put_cname_in_ptr =
  4253. &data->cname_result;
  4254. }
  4255. evtimer_assign(&data->timeout, dns_base->event_base,
  4256. evdns_getaddrinfo_timeout_cb, data);
  4257. started = (data->ipv4_request.r || data->ipv6_request.r);
  4258. EVDNS_UNLOCK(dns_base);
  4259. if (started) {
  4260. return data;
  4261. } else {
  4262. mm_free(data);
  4263. cb(EVUTIL_EAI_FAIL, NULL, arg);
  4264. return NULL;
  4265. }
  4266. }
  4267. void
  4268. evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
  4269. {
  4270. EVDNS_LOCK(data->evdns_base);
  4271. if (data->request_done) {
  4272. EVDNS_UNLOCK(data->evdns_base);
  4273. return;
  4274. }
  4275. event_del(&data->timeout);
  4276. data->user_canceled = 1;
  4277. if (data->ipv4_request.r)
  4278. evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
  4279. if (data->ipv6_request.r)
  4280. evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
  4281. EVDNS_UNLOCK(data->evdns_base);
  4282. }