eventdns.c 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503
  1. /* The original version of this module was written by Adam Langley; for
  2. * a history of modifications, check out the subversion logs.
  3. *
  4. * When editing this module, try to keep it re-mergeable by Adam. Don't
  5. * reformat the whitespace, add Tor dependencies, or so on.
  6. *
  7. * TODO:
  8. * - Replace all externally visible magic numbers with #defined constants.
  9. * - Write documentation for APIs of all external functions.
  10. */
  11. /* Async DNS Library
  12. * Adam Langley <agl@imperialviolet.org>
  13. * Public Domain code
  14. *
  15. * This software is Public Domain. To view a copy of the public domain dedication,
  16. * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  17. * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  18. *
  19. * I ask and expect, but do not require, that all derivative works contain an
  20. * attribution similar to:
  21. * Parts developed by Adam Langley <agl@imperialviolet.org>
  22. *
  23. * You may wish to replace the word "Parts" with something else depending on
  24. * the amount of original code.
  25. *
  26. * (Derivative works does not include programs which link against, run or include
  27. * the source verbatim in their source distributions)
  28. *
  29. * Version: 0.1b
  30. */
  31. #include "eventdns_tor.h"
  32. #include <sys/types.h>
  33. /* #define NDEBUG */
  34. #ifndef DNS_USE_CPU_CLOCK_FOR_ID
  35. #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
  36. #ifndef DNS_USE_OPENSSL_FOR_ID
  37. #error Must configure at least one id generation method.
  38. #error Please see the documentation.
  39. #endif
  40. #endif
  41. #endif
  42. /* #define _POSIX_C_SOURCE 200507 */
  43. #define _GNU_SOURCE
  44. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  45. #ifdef DNS_USE_OPENSSL_FOR_ID
  46. #error Multiple id options selected
  47. #endif
  48. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  49. #error Multiple id options selected
  50. #endif
  51. #include <time.h>
  52. #endif
  53. #ifdef DNS_USE_OPENSSL_FOR_ID
  54. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  55. #error Multiple id options selected
  56. #endif
  57. #include <openssl/rand.h>
  58. #endif
  59. #include <string.h>
  60. #ifdef HAVE_FCNTL_H
  61. #include <fcntl.h>
  62. #endif
  63. #ifdef HAVE_SYS_TIME_H
  64. #include <sys/time.h>
  65. #endif
  66. #ifdef HAVE_STDINT_H
  67. #include <stdint.h>
  68. #endif
  69. #include <stdlib.h>
  70. #include <string.h>
  71. #include <errno.h>
  72. #include <assert.h>
  73. #ifdef HAVE_UNISTD_H
  74. #include <unistd.h>
  75. #endif
  76. #ifdef HAVE_LIMITS_H
  77. #include <limits.h>
  78. #endif
  79. #include <sys/stat.h>
  80. #include <ctype.h>
  81. #include <stdio.h>
  82. #include <stdarg.h>
  83. #include "eventdns.h"
  84. #ifdef WIN32
  85. #include <windows.h>
  86. #include <winsock2.h>
  87. #include <iphlpapi.h>
  88. #else
  89. #include <sys/socket.h>
  90. #include <netinet/in.h>
  91. #include <arpa/inet.h>
  92. #endif
  93. #ifdef HAVE_NETINET_IN6_H
  94. #include <netinet/in6.h>
  95. #endif
  96. #ifdef WIN32
  97. typedef int socklen_t;
  98. #endif
  99. #define EVDNS_LOG_DEBUG 0
  100. #define EVDNS_LOG_WARN 1
  101. #ifndef HOST_NAME_MAX
  102. #define HOST_NAME_MAX 255
  103. #endif
  104. #ifndef NDEBUG
  105. #include <stdio.h>
  106. #endif
  107. /* for debugging possible memory leaks. */
  108. #define mm_malloc(x) tor_malloc(x)
  109. #define mm_realloc(x,y) tor_realloc((x),(y))
  110. #define mm_free(x) tor_free(x)
  111. #define mm_strdup(x) tor_strdup(x)
  112. #define _mm_free(x) _tor_free(x)
  113. #undef MIN
  114. #define MIN(a,b) ((a)<(b)?(a):(b))
  115. #if 0
  116. #ifdef __USE_ISOC99B
  117. /* libevent doesn't work without this */
  118. typedef uint8_t u_char;
  119. typedef unsigned int uint;
  120. #endif
  121. #endif
  122. #include <event.h>
  123. #define u64 uint64_t
  124. #define u32 uint32_t
  125. #define u16 uint16_t
  126. #define u8 uint8_t
  127. #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
  128. /* which we bother recording */
  129. #define TYPE_A EVDNS_TYPE_A
  130. #define TYPE_CNAME 5
  131. #define TYPE_PTR EVDNS_TYPE_PTR
  132. #define TYPE_AAAA EVDNS_TYPE_AAAA
  133. #define CLASS_INET EVDNS_CLASS_INET
  134. #define CLEAR(x) do { memset((x), 0xF0, sizeof(*(x))); } while(0)
  135. struct evdns_request {
  136. u8 *request; /* the dns packet data */
  137. unsigned int request_len;
  138. int reissue_count;
  139. int tx_count; /* the number of times that this packet has been sent */
  140. unsigned int request_type; /* TYPE_PTR or TYPE_A */
  141. void *user_pointer; /* the pointer given to us for this request */
  142. evdns_callback_type user_callback;
  143. struct nameserver *ns; /* the server which we last sent it */
  144. /* elements used by the searching code */
  145. int search_index;
  146. struct search_state *search_state;
  147. char *search_origname; /* needs to be mm_free()ed */
  148. int search_flags;
  149. /* these objects are kept in a circular list */
  150. struct evdns_request *next, *prev;
  151. u16 timeout_event_deleted; /**< Debugging: where was timeout_event
  152. * deleted? 0 for "it's added." */
  153. struct event timeout_event;
  154. u16 trans_id; /* the transaction id */
  155. char request_appended; /* true if the request pointer is data which follows this struct */
  156. char transmit_me; /* needs to be transmitted */
  157. };
  158. #ifndef HAVE_STRUCT_IN6_ADDR
  159. struct in6_addr {
  160. u8 s6_addr[16];
  161. };
  162. #endif
  163. struct reply {
  164. unsigned int type;
  165. unsigned int have_answer;
  166. union {
  167. struct {
  168. u32 addrcount;
  169. u32 addresses[MAX_ADDRS];
  170. } a;
  171. struct {
  172. u32 addrcount;
  173. struct in6_addr addresses[MAX_ADDRS];
  174. } aaaa;
  175. struct {
  176. char name[HOST_NAME_MAX];
  177. } ptr;
  178. } data;
  179. };
  180. struct nameserver {
  181. int socket; /* a connected UDP socket */
  182. struct sockaddr_storage address;
  183. int failed_times; /* number of times which we have given this server a chance */
  184. int timedout; /* number of times in a row a request has timed out */
  185. struct event event;
  186. /* these objects are kept in a circular list */
  187. struct nameserver *next, *prev;
  188. u16 timeout_event_deleted; /**< Debugging: where was timeout_event
  189. * deleted? 0 for "it's added." */
  190. struct event timeout_event; /* used to keep the timeout for */
  191. /* when we next probe this server. */
  192. /* Valid if state == 0 */
  193. char state; /* zero if we think that this server is down */
  194. char choked; /* true if we have an EAGAIN from this server's socket */
  195. char write_waiting; /* true if we are waiting for EV_WRITE events */
  196. };
  197. static struct evdns_request *req_head = NULL, *req_waiting_head = NULL;
  198. static struct nameserver *server_head = NULL;
  199. /* Represents a local port where we're listening for DNS requests. Right now, */
  200. /* only UDP is supported. */
  201. struct evdns_server_port {
  202. int socket; /* socket we use to read queries and write replies. */
  203. int refcnt; /* reference count. */
  204. char choked; /* Are we currently blocked from writing? */
  205. char closing; /* Are we trying to close this port, pending writes? */
  206. evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
  207. void *user_data; /* Opaque pointer passed to user_callback */
  208. struct event event; /* Read/write event */
  209. /* circular list of replies that we want to write. */
  210. struct server_request *pending_replies;
  211. };
  212. /* Represents part of a reply being built. (That is, a single RR.) */
  213. struct server_reply_item {
  214. struct server_reply_item *next; /* next item in sequence. */
  215. char *name; /* name part of the RR */
  216. u16 type : 16; /* The RR type */
  217. u16 class : 16; /* The RR class (usually CLASS_INET) */
  218. u32 ttl; /* The RR TTL */
  219. char is_name; /* True iff data is a label */
  220. u16 datalen; /* Length of data; -1 if data is a label */
  221. void *data; /* The contents of the RR */
  222. };
  223. /* Represents a request that we've received as a DNS server, and holds */
  224. /* the components of the reply as we're constructing it. */
  225. struct server_request {
  226. /* Pointers to the next and previous entries on the list of replies */
  227. /* that we're waiting to write. Only set if we have tried to respond */
  228. /* and gotten EAGAIN. */
  229. struct server_request *next_pending;
  230. struct server_request *prev_pending;
  231. u16 trans_id; /* Transaction id. */
  232. struct evdns_server_port *port; /* Which port received this request on? */
  233. struct sockaddr_storage addr; /* Where to send the response */
  234. socklen_t addrlen; /* length of addr */
  235. int n_answer; /* how many answer RRs have been set? */
  236. int n_authority; /* how many authority RRs have been set? */
  237. int n_additional; /* how many additional RRs have been set? */
  238. struct server_reply_item *answer; /* linked list of answer RRs */
  239. struct server_reply_item *authority; /* linked list of authority RRs */
  240. struct server_reply_item *additional; /* linked list of additional RRs */
  241. /* Constructed response. Only set once we're ready to send a reply. */
  242. /* Once this is set, the RR fields are cleared, and no more should be set. */
  243. char *response;
  244. size_t response_len;
  245. /* Caller-visible fields: flags, questions. */
  246. struct evdns_server_request base;
  247. };
  248. /* helper macro */
  249. #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
  250. /* Given a pointer to an evdns_server_request, get the corresponding */
  251. /* server_request. */
  252. #define TO_SERVER_REQUEST(base_ptr) \
  253. ((struct server_request*) \
  254. (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
  255. /* The number of good nameservers that we have */
  256. static int global_good_nameservers = 0;
  257. /* inflight requests are contained in the req_head list */
  258. /* and are actually going out across the network */
  259. static int global_requests_inflight = 0;
  260. /* requests which aren't inflight are in the waiting list */
  261. /* and are counted here */
  262. static int global_requests_waiting = 0;
  263. static int global_max_requests_inflight = 64;
  264. static struct timeval global_timeout = {5, 0}; /* 5 seconds */
  265. static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */
  266. static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */
  267. /* number of timeouts in a row before we consider this server to be down */
  268. static int global_max_nameserver_timeout = 3;
  269. /* true iff we should use the 0x20 hack. */
  270. static int global_randomize_case = 1;
  271. /* These are the timeout values for nameservers. If we find a nameserver is down */
  272. /* we try to probe it at intervals as given below. Values are in seconds. */
  273. static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
  274. static const int global_nameserver_timeouts_length = (int)(sizeof(global_nameserver_timeouts)/sizeof(struct timeval));
  275. static struct nameserver *nameserver_pick(void);
  276. static void evdns_request_insert(struct evdns_request *req, struct evdns_request **head);
  277. static void nameserver_ready_callback(int fd, short events, void *arg);
  278. static int evdns_transmit(void);
  279. static int evdns_request_transmit(struct evdns_request *req);
  280. static void nameserver_send_probe(struct nameserver *const ns);
  281. static void search_request_finished(struct evdns_request *const);
  282. static int search_try_next(struct evdns_request *const req);
  283. static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
  284. static void evdns_requests_pump_waiting_queue(void);
  285. static u16 transaction_id_pick(void);
  286. static struct evdns_request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
  287. static void request_submit(struct evdns_request *req);
  288. static int server_request_free(struct server_request *req);
  289. static void server_request_free_answers(struct server_request *req);
  290. static void server_port_free(struct evdns_server_port *port);
  291. static void server_port_ready_callback(int fd, short events, void *arg);
  292. static int strtoint(const char *const str);
  293. #ifdef WIN32
  294. static int
  295. last_error(int sock)
  296. {
  297. int optval, optvallen=sizeof(optval);
  298. int err = WSAGetLastError();
  299. if (err == WSAEWOULDBLOCK && sock >= 0) {
  300. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
  301. &optvallen))
  302. return err;
  303. if (optval)
  304. return optval;
  305. }
  306. return err;
  307. }
  308. static int
  309. error_is_eagain(int err)
  310. {
  311. return err == EAGAIN || err == WSAEWOULDBLOCK;
  312. }
  313. #define inet_aton(c, addr) tor_inet_aton((c), (addr))
  314. #define CLOSE_SOCKET(x) closesocket(x)
  315. #else
  316. #define last_error(sock) (errno)
  317. #define error_is_eagain(err) ((err) == EAGAIN)
  318. #define CLOSE_SOCKET(x) close(x)
  319. #endif
  320. #define ISSPACE(c) TOR_ISSPACE(c)
  321. #define ISDIGIT(c) TOR_ISDIGIT(c)
  322. #define ISALPHA(c) TOR_ISALPHA(c)
  323. #define TOLOWER(c) TOR_TOLOWER(c)
  324. #define TOUPPER(c) TOR_TOUPPER(c)
  325. #ifndef NDEBUG
  326. static const char *
  327. debug_ntoa(u32 address)
  328. {
  329. static char buf[32];
  330. u32 a = ntohl(address);
  331. snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
  332. (int)(u8)((a>>24)&0xff),
  333. (int)(u8)((a>>16)&0xff),
  334. (int)(u8)((a>>8 )&0xff),
  335. (int)(u8)((a )&0xff));
  336. return buf;
  337. }
  338. static const char *
  339. debug_ntop(const struct sockaddr *sa)
  340. {
  341. if (sa->sa_family == AF_INET) {
  342. struct sockaddr_in *sin = (struct sockaddr_in *) sa;
  343. return debug_ntoa(sin->sin_addr.s_addr);
  344. }
  345. if (sa->sa_family == AF_INET6) {
  346. /* Tor-specific. In libevent, add more check code. */
  347. static char buf[128];
  348. struct sockaddr_in6 *sin = (struct sockaddr_in6 *) sa;
  349. tor_inet_ntop(AF_INET6, &sin->sin6_addr, buf, sizeof(buf));
  350. return buf;
  351. }
  352. return "<unknown>";
  353. }
  354. #endif
  355. static evdns_debug_log_fn_type evdns_log_fn = NULL;
  356. void
  357. evdns_set_log_fn(evdns_debug_log_fn_type fn)
  358. {
  359. evdns_log_fn = fn;
  360. }
  361. #ifdef __GNUC__
  362. #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
  363. #else
  364. #define EVDNS_LOG_CHECK
  365. #endif
  366. static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
  367. static void
  368. _evdns_log(int warn, const char *fmt, ...)
  369. {
  370. va_list args;
  371. static char buf[512];
  372. if (!evdns_log_fn)
  373. return;
  374. va_start(args,fmt);
  375. #ifdef WIN32
  376. _vsnprintf(buf, sizeof(buf), fmt, args);
  377. #else
  378. vsnprintf(buf, sizeof(buf), fmt, args);
  379. #endif
  380. buf[sizeof(buf)-1] = '\0';
  381. evdns_log_fn(warn, buf);
  382. va_end(args);
  383. }
  384. #define log _evdns_log
  385. static int
  386. sockaddr_eq(const struct sockaddr *sa1, const struct sockaddr *sa2,
  387. int include_port)
  388. {
  389. if (sa1->sa_family != sa2->sa_family)
  390. return 0;
  391. if (sa1->sa_family == AF_INET) {
  392. const struct sockaddr_in *sin1, *sin2;
  393. sin1 = (const struct sockaddr_in *)sa1;
  394. sin2 = (const struct sockaddr_in *)sa2;
  395. if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr)
  396. return 0;
  397. else if (include_port && sin1->sin_port != sin2->sin_port)
  398. return 0;
  399. else
  400. return 1;
  401. }
  402. #ifdef AF_INET6
  403. if (sa1->sa_family == AF_INET6) {
  404. const struct sockaddr_in6 *sin1, *sin2;
  405. sin1 = (const struct sockaddr_in6 *)sa1;
  406. sin2 = (const struct sockaddr_in6 *)sa2;
  407. if (memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16))
  408. return 0;
  409. else if (include_port && sin1->sin6_port != sin2->sin6_port)
  410. return 0;
  411. else
  412. return 1;
  413. }
  414. #endif
  415. return 1;
  416. }
  417. /* for debugging bug 929. XXXX021 */
  418. static int
  419. _add_timeout_event(u16 *lineno, struct event *ev, struct timeval *to)
  420. {
  421. *lineno = 0;
  422. return evtimer_add(ev, to);
  423. }
  424. #define add_timeout_event(s, to) \
  425. (_add_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, (to)))
  426. /* for debugging bug 929. XXXX021 */
  427. static int
  428. _del_timeout_event(u16 *lineno, struct event *ev, int line)
  429. {
  430. if (*lineno) {
  431. log(EVDNS_LOG_WARN,
  432. "Duplicate timeout event_del from line %d: first call "
  433. "was at %d.", line, (int)*lineno);
  434. return 0;
  435. } else {
  436. *lineno = (u16)line;
  437. return event_del(ev);
  438. }
  439. }
  440. #define del_timeout_event(s) \
  441. (_del_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, \
  442. __LINE__))
  443. /* This walks the list of inflight requests to find the */
  444. /* one with a matching transaction id. Returns NULL on */
  445. /* failure */
  446. static struct evdns_request *
  447. request_find_from_trans_id(u16 trans_id) {
  448. struct evdns_request *req = req_head, *const started_at = req_head;
  449. if (req) {
  450. do {
  451. if (req->trans_id == trans_id) return req;
  452. req = req->next;
  453. } while (req != started_at);
  454. }
  455. return NULL;
  456. }
  457. /* a libevent callback function which is called when a nameserver */
  458. /* has gone down and we want to test if it has came back to life yet */
  459. static void
  460. nameserver_prod_callback(int fd, short events, void *arg) {
  461. struct nameserver *const ns = (struct nameserver *) arg;
  462. (void)fd;
  463. (void)events;
  464. nameserver_send_probe(ns);
  465. }
  466. /* a libevent callback which is called when a nameserver probe (to see if */
  467. /* it has come back to life) times out. We increment the count of failed_times */
  468. /* and wait longer to send the next probe packet. */
  469. static void
  470. nameserver_probe_failed(struct nameserver *const ns) {
  471. const struct timeval * timeout;
  472. del_timeout_event(ns);
  473. CLEAR(&ns->timeout_event);
  474. if (ns->state == 1) {
  475. /* This can happen if the nameserver acts in a way which makes us mark */
  476. /* it as bad and then starts sending good replies. */
  477. return;
  478. }
  479. timeout =
  480. &global_nameserver_timeouts[MIN(ns->failed_times,
  481. global_nameserver_timeouts_length - 1)];
  482. ns->failed_times++;
  483. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  484. if (add_timeout_event(ns, (struct timeval *) timeout) < 0) {
  485. log(EVDNS_LOG_WARN,
  486. "Error from libevent when adding timer event for %s",
  487. debug_ntop((struct sockaddr *)&ns->address));
  488. /* ???? Do more? */
  489. }
  490. }
  491. /* called when a nameserver has been deemed to have failed. For example, too */
  492. /* many packets have timed out etc */
  493. static void
  494. nameserver_failed(struct nameserver *const ns, const char *msg) {
  495. struct evdns_request *req, *started_at;
  496. /* if this nameserver has already been marked as failed */
  497. /* then don't do anything */
  498. if (!ns->state) return;
  499. log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
  500. debug_ntop((struct sockaddr *)&ns->address), msg);
  501. global_good_nameservers--;
  502. assert(global_good_nameservers >= 0);
  503. if (global_good_nameservers == 0) {
  504. log(EVDNS_LOG_WARN, "All nameservers have failed");
  505. }
  506. ns->state = 0;
  507. ns->failed_times = 1;
  508. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  509. if (add_timeout_event(ns, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
  510. log(EVDNS_LOG_WARN,
  511. "Error from libevent when adding timer event for %s",
  512. debug_ntop((struct sockaddr *)&ns->address));
  513. /* ???? Do more? */
  514. }
  515. /* walk the list of inflight requests to see if any can be reassigned to */
  516. /* a different server. Requests in the waiting queue don't have a */
  517. /* nameserver assigned yet */
  518. /* if we don't have *any* good nameservers then there's no point */
  519. /* trying to reassign requests to one */
  520. if (!global_good_nameservers) return;
  521. req = req_head;
  522. started_at = req_head;
  523. if (req) {
  524. do {
  525. if (req->tx_count == 0 && req->ns == ns) {
  526. /* still waiting to go out, can be moved */
  527. /* to another server */
  528. req->ns = nameserver_pick();
  529. }
  530. req = req->next;
  531. } while (req != started_at);
  532. }
  533. }
  534. static void
  535. nameserver_up(struct nameserver *const ns) {
  536. if (ns->state) return;
  537. log(EVDNS_LOG_WARN, "Nameserver %s is back up",
  538. debug_ntop((struct sockaddr *)&ns->address));
  539. del_timeout_event(ns);
  540. CLEAR(&ns->timeout_event);
  541. ns->state = 1;
  542. ns->failed_times = 0;
  543. ns->timedout = 0;
  544. global_good_nameservers++;
  545. }
  546. static void
  547. request_trans_id_set(struct evdns_request *const req, const u16 trans_id) {
  548. req->trans_id = trans_id;
  549. *((u16 *) req->request) = htons(trans_id);
  550. }
  551. /* Called to remove a request from a list and dealloc it. */
  552. /* head is a pointer to the head of the list it should be */
  553. /* removed from or NULL if the request isn't in a list. */
  554. static void
  555. request_finished(struct evdns_request *const req, struct evdns_request **head) {
  556. if (head) {
  557. if (req->next == req) {
  558. /* only item in the list */
  559. *head = NULL;
  560. } else {
  561. req->next->prev = req->prev;
  562. req->prev->next = req->next;
  563. if (*head == req) *head = req->next;
  564. }
  565. }
  566. log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
  567. (unsigned long) req);
  568. del_timeout_event(req);
  569. CLEAR(&req->timeout_event);
  570. search_request_finished(req);
  571. global_requests_inflight--;
  572. if (!req->request_appended) {
  573. /* need to free the request data on it's own */
  574. mm_free(req->request);
  575. } else {
  576. /* the request data is appended onto the header */
  577. /* so everything gets mm_free()ed when we: */
  578. }
  579. CLEAR(req);
  580. _mm_free(req);
  581. evdns_requests_pump_waiting_queue();
  582. }
  583. /* This is called when a server returns a funny error code. */
  584. /* We try the request again with another server. */
  585. /* */
  586. /* return: */
  587. /* 0 ok */
  588. /* 1 failed/reissue is pointless */
  589. static int
  590. request_reissue(struct evdns_request *req) {
  591. const struct nameserver *const last_ns = req->ns;
  592. /* the last nameserver should have been marked as failing */
  593. /* by the caller of this function, therefore pick will try */
  594. /* not to return it */
  595. req->ns = nameserver_pick();
  596. if (req->ns == last_ns) {
  597. /* ... but pick did return it */
  598. /* not a lot of point in trying again with the */
  599. /* same server */
  600. return 1;
  601. }
  602. req->reissue_count++;
  603. req->tx_count = 0;
  604. req->transmit_me = 1;
  605. return 0;
  606. }
  607. /* this function looks for space on the inflight queue and promotes */
  608. /* requests from the waiting queue if it can. */
  609. static void
  610. evdns_requests_pump_waiting_queue(void) {
  611. while (global_requests_inflight < global_max_requests_inflight &&
  612. global_requests_waiting) {
  613. struct evdns_request *req;
  614. /* move a request from the waiting queue to the inflight queue */
  615. assert(req_waiting_head);
  616. if (req_waiting_head->next == req_waiting_head) {
  617. /* only one item in the queue */
  618. req = req_waiting_head;
  619. req_waiting_head = NULL;
  620. } else {
  621. req = req_waiting_head;
  622. req->next->prev = req->prev;
  623. req->prev->next = req->next;
  624. req_waiting_head = req->next;
  625. }
  626. global_requests_waiting--;
  627. global_requests_inflight++;
  628. req->ns = nameserver_pick();
  629. request_trans_id_set(req, transaction_id_pick());
  630. evdns_request_insert(req, &req_head);
  631. evdns_request_transmit(req);
  632. evdns_transmit();
  633. }
  634. }
  635. static void
  636. reply_callback(struct evdns_request *const req, u32 ttl, u32 err, struct reply *reply) {
  637. switch (req->request_type) {
  638. case TYPE_A:
  639. if (reply)
  640. req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
  641. reply->data.a.addrcount, ttl,
  642. reply->data.a.addresses,
  643. req->user_pointer);
  644. else
  645. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  646. return;
  647. case TYPE_PTR:
  648. if (reply) {
  649. char *name = reply->data.ptr.name;
  650. req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
  651. &name, req->user_pointer);
  652. } else {
  653. req->user_callback(err, 0, 0, 0, NULL,
  654. req->user_pointer);
  655. }
  656. return;
  657. case TYPE_AAAA:
  658. if (reply)
  659. req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
  660. reply->data.aaaa.addrcount, ttl,
  661. reply->data.aaaa.addresses,
  662. req->user_pointer);
  663. else
  664. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  665. return;
  666. }
  667. assert(0);
  668. }
  669. /* this processes a parsed reply packet */
  670. static void
  671. reply_handle(struct evdns_request *const req, u16 flags, u32 ttl, struct reply *reply) {
  672. int error;
  673. static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
  674. if (flags & 0x020f || !reply || !reply->have_answer) {
  675. /* there was an error */
  676. if (flags & 0x0200) {
  677. error = DNS_ERR_TRUNCATED;
  678. } else {
  679. u16 error_code = (flags & 0x000f) - 1;
  680. if (error_code > 4) {
  681. error = DNS_ERR_UNKNOWN;
  682. } else {
  683. error = error_codes[error_code];
  684. }
  685. }
  686. switch(error) {
  687. case DNS_ERR_NOTIMPL:
  688. case DNS_ERR_REFUSED:
  689. /* we regard these errors as marking a bad nameserver */
  690. if (req->reissue_count < global_max_reissues) {
  691. char msg[64];
  692. snprintf(msg, sizeof(msg), "Bad response %d (%s)",
  693. error, evdns_err_to_string(error));
  694. nameserver_failed(req->ns, msg);
  695. if (!request_reissue(req)) return;
  696. }
  697. break;
  698. case DNS_ERR_SERVERFAILED:
  699. /* rcode 2 (servfailed) sometimes means "we are broken" and
  700. * sometimes (with some binds) means "that request was very
  701. * confusing." Treat this as a timeout, not a failure.
  702. */
  703. /*XXXX refactor the parts of */
  704. log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
  705. "will allow the request to time out.",
  706. debug_ntop((struct sockaddr *)&req->ns->address));
  707. break;
  708. default:
  709. /* we got a good reply from the nameserver */
  710. nameserver_up(req->ns);
  711. }
  712. if (req->search_state && req->request_type != TYPE_PTR) {
  713. /* if we have a list of domains to search in, try the next one */
  714. if (!search_try_next(req)) {
  715. /* a new request was issued so this request is finished and */
  716. /* the user callback will be made when that request (or a */
  717. /* child of it) finishes. */
  718. request_finished(req, &req_head);
  719. return;
  720. }
  721. }
  722. /* all else failed. Pass the failure up */
  723. reply_callback(req, 0, error, NULL);
  724. request_finished(req, &req_head);
  725. } else {
  726. /* all ok, tell the user */
  727. reply_callback(req, ttl, 0, reply);
  728. nameserver_up(req->ns);
  729. request_finished(req, &req_head);
  730. }
  731. }
  732. static INLINE int
  733. name_parse(u8 *packet, int length, int *idx, char *name_out, size_t name_out_len) {
  734. int name_end = -1;
  735. int j = *idx;
  736. int ptr_count = 0;
  737. #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
  738. #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
  739. #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
  740. char *cp = name_out;
  741. const char *const end = name_out + name_out_len;
  742. /* Normally, names are a series of length prefixed strings terminated */
  743. /* with a length of 0 (the lengths are u8's < 63). */
  744. /* However, the length can start with a pair of 1 bits and that */
  745. /* means that the next 14 bits are a pointer within the current */
  746. /* packet. */
  747. for(;;) {
  748. u8 label_len;
  749. if (j >= length) return -1;
  750. GET8(label_len);
  751. if (!label_len) break;
  752. if (label_len & 0xc0) {
  753. u8 ptr_low;
  754. GET8(ptr_low);
  755. if (name_end < 0) name_end = j;
  756. j = (((int)label_len & 0x3f) << 8) + ptr_low;
  757. /* Make sure that the target offset is in-bounds. */
  758. if (j < 0 || j >= length) return -1;
  759. /* If we've jumped more times than there are characters in the
  760. * message, we must have a loop. */
  761. if (++ptr_count > length) return -1;
  762. continue;
  763. }
  764. if (label_len > 63) return -1;
  765. if (cp != name_out) {
  766. if (cp + 1 >= end) return -1;
  767. *cp++ = '.';
  768. }
  769. if (cp + label_len >= end) return -1;
  770. memcpy(cp, packet + j, label_len);
  771. cp += label_len;
  772. j += label_len;
  773. }
  774. if (cp >= end) return -1;
  775. *cp = '\0';
  776. if (name_end < 0)
  777. *idx = j;
  778. else
  779. *idx = name_end;
  780. return 0;
  781. err:
  782. return -1;
  783. }
  784. /* parses a raw reply from a nameserver. */
  785. static int
  786. reply_parse(u8 *packet, int length) {
  787. int j = 0; /* index into packet */
  788. int k;
  789. u16 _t; /* used by the macros */
  790. u32 _t32; /* used by the macros */
  791. char tmp_name[256], cmp_name[256]; /* used by the macros */
  792. u16 trans_id, questions, answers, authority, additional, datalength;
  793. u16 flags = 0;
  794. u32 ttl, ttl_r = 0xffffffff;
  795. struct reply reply;
  796. struct evdns_request *req = NULL;
  797. unsigned int i;
  798. int name_matches = 0;
  799. GET16(trans_id);
  800. GET16(flags);
  801. GET16(questions);
  802. GET16(answers);
  803. GET16(authority);
  804. GET16(additional);
  805. (void) authority; /* suppress "unused variable" warnings. */
  806. (void) additional; /* suppress "unused variable" warnings. */
  807. req = request_find_from_trans_id(trans_id);
  808. /* if no request, can't do anything. */
  809. if (!req) return -1;
  810. memset(&reply, 0, sizeof(reply));
  811. /* If it's not an answer, it doesn't go with any of our requests. */
  812. if (!(flags & 0x8000)) return -1; /* must be an answer */
  813. if (flags & 0x020f) {
  814. /* there was an error */
  815. goto err;
  816. }
  817. /* if (!answers) return; */ /* must have an answer of some form */
  818. /* This macro skips a name in the DNS reply. */
  819. #define GET_NAME \
  820. do { tmp_name[0] = '\0'; \
  821. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
  822. goto err; \
  823. } while(0)
  824. #define TEST_NAME \
  825. do { tmp_name[0] = '\0'; \
  826. cmp_name[0] = '\0'; \
  827. k = j; \
  828. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
  829. goto err; \
  830. if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \
  831. goto err; \
  832. if (global_randomize_case) { \
  833. if (strcmp(tmp_name, cmp_name) == 0) \
  834. name_matches = 1; /* we ignore mismatching names */ \
  835. } else { \
  836. if (strcasecmp(tmp_name, cmp_name) == 0) \
  837. name_matches = 1; \
  838. } \
  839. } while(0)
  840. reply.type = req->request_type;
  841. /* skip over each question in the reply */
  842. for (i = 0; i < questions; ++i) {
  843. /* the question looks like
  844. * <label:name><u16:type><u16:class>
  845. */
  846. TEST_NAME;
  847. j += 4;
  848. if (j >= length) goto err;
  849. }
  850. if (!name_matches)
  851. goto err;
  852. /* now we have the answer section which looks like
  853. * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
  854. */
  855. for (i = 0; i < answers; ++i) {
  856. u16 type, class;
  857. GET_NAME;
  858. GET16(type);
  859. GET16(class);
  860. GET32(ttl);
  861. GET16(datalength);
  862. if (type == TYPE_A && class == CLASS_INET) {
  863. int addrcount, addrtocopy;
  864. if (req->request_type != TYPE_A) {
  865. j += datalength; continue;
  866. }
  867. if ((datalength & 3) != 0) /* not an even number of As. */
  868. goto err;
  869. addrcount = datalength >> 2;
  870. addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
  871. ttl_r = MIN(ttl_r, ttl);
  872. /* we only bother with the first four addresses. */
  873. if (j + 4*addrtocopy > length) goto err;
  874. memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
  875. packet + j, 4*addrtocopy);
  876. reply.data.a.addrcount += addrtocopy;
  877. reply.have_answer = 1;
  878. if (reply.data.a.addrcount == MAX_ADDRS) break;
  879. j += 4*addrtocopy;
  880. } else if (type == TYPE_PTR && class == CLASS_INET) {
  881. if (req->request_type != TYPE_PTR) {
  882. j += datalength; continue;
  883. }
  884. GET_NAME;
  885. strlcpy(reply.data.ptr.name, tmp_name,
  886. sizeof(reply.data.ptr.name));
  887. ttl_r = MIN(ttl_r, ttl);
  888. reply.have_answer = 1;
  889. break;
  890. } else if (type == TYPE_AAAA && class == CLASS_INET) {
  891. int addrcount, addrtocopy;
  892. if (req->request_type != TYPE_AAAA) {
  893. j += datalength; continue;
  894. }
  895. if ((datalength & 15) != 0) /* not an even number of AAAAs. */
  896. goto err;
  897. addrcount = datalength >> 4; /* each address is 16 bytes long */
  898. addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
  899. ttl_r = MIN(ttl_r, ttl);
  900. /* we only bother with the first four addresses. */
  901. if (j + 16*addrtocopy > length) goto err;
  902. memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
  903. packet + j, 16*addrtocopy);
  904. reply.data.aaaa.addrcount += addrtocopy;
  905. reply.have_answer = 1;
  906. if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
  907. j += 16*addrtocopy;
  908. } else {
  909. /* skip over any other type of resource */
  910. j += datalength;
  911. }
  912. }
  913. reply_handle(req, flags, ttl_r, &reply);
  914. return 0;
  915. err:
  916. if (req)
  917. reply_handle(req, flags, 0, NULL);
  918. return -1;
  919. }
  920. /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
  921. /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
  922. /* callback. */
  923. static int
  924. request_parse(u8 *packet, ssize_t length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
  925. {
  926. int j = 0; /* index into packet */
  927. u16 _t; /* used by the macros */
  928. char tmp_name[256]; /* used by the macros */
  929. int i;
  930. u16 trans_id, flags, questions, answers, authority, additional;
  931. struct server_request *server_req = NULL;
  932. /* Get the header fields */
  933. GET16(trans_id);
  934. GET16(flags);
  935. GET16(questions);
  936. GET16(answers);
  937. GET16(authority);
  938. GET16(additional);
  939. if (flags & 0x8000) return -1; /* Must not be an answer. */
  940. flags &= 0x0110; /* Only RD and CD get preserved. */
  941. if (length > INT_MAX)
  942. return -1;
  943. server_req = mm_malloc(sizeof(struct server_request));
  944. if (server_req == NULL) return -1;
  945. memset(server_req, 0, sizeof(struct server_request));
  946. server_req->trans_id = trans_id;
  947. memcpy(&server_req->addr, addr, addrlen);
  948. server_req->addrlen = addrlen;
  949. server_req->base.flags = flags;
  950. server_req->base.nquestions = 0;
  951. server_req->base.questions = mm_malloc(sizeof(struct evdns_server_question *) * questions);
  952. if (server_req->base.questions == NULL)
  953. goto err;
  954. for (i = 0; i < questions; ++i) {
  955. u16 type, class;
  956. struct evdns_server_question *q;
  957. size_t namelen;
  958. if (name_parse(packet, (int)length, &j, tmp_name, sizeof(tmp_name))<0)
  959. goto err;
  960. GET16(type);
  961. GET16(class);
  962. namelen = strlen(tmp_name);
  963. q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
  964. if (!q)
  965. goto err;
  966. q->type = type;
  967. q->dns_question_class = class;
  968. memcpy(q->name, tmp_name, namelen+1);
  969. server_req->base.questions[server_req->base.nquestions++] = q;
  970. }
  971. /* Ignore answers, authority, and additional. */
  972. server_req->port = port;
  973. port->refcnt++;
  974. /* Only standard queries are supported. */
  975. if (flags & 0x7800) {
  976. evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
  977. return -1;
  978. }
  979. port->user_callback(&(server_req->base), port->user_data);
  980. return 0;
  981. err:
  982. if (server_req) {
  983. if (server_req->base.questions) {
  984. for (i = 0; i < server_req->base.nquestions; ++i)
  985. mm_free(server_req->base.questions[i]);
  986. mm_free(server_req->base.questions);
  987. }
  988. CLEAR(server_req);
  989. mm_free(server_req);
  990. }
  991. return -1;
  992. #undef SKIP_NAME
  993. #undef GET32
  994. #undef GET16
  995. #undef GET8
  996. }
  997. static uint16_t
  998. default_transaction_id_fn(void)
  999. {
  1000. u16 trans_id;
  1001. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  1002. struct timespec ts;
  1003. #ifdef CLOCK_MONOTONIC
  1004. if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
  1005. #else
  1006. if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
  1007. #endif
  1008. event_err(1, "clock_gettime");
  1009. trans_id = ts.tv_nsec & 0xffff;
  1010. #endif
  1011. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  1012. struct timeval tv;
  1013. gettimeofday(&tv, NULL);
  1014. trans_id = tv.tv_usec & 0xffff;
  1015. #endif
  1016. #ifdef DNS_USE_OPENSSL_FOR_ID
  1017. if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
  1018. /* in the case that the RAND call fails we back */
  1019. /* down to using gettimeofday. */
  1020. /*
  1021. struct timeval tv;
  1022. gettimeofday(&tv, NULL);
  1023. trans_id = tv.tv_usec & 0xffff;
  1024. */
  1025. abort();
  1026. }
  1027. #endif
  1028. return (unsigned short) trans_id;
  1029. }
  1030. static uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
  1031. static void
  1032. default_random_bytes_fn(char *buf, size_t n)
  1033. {
  1034. unsigned i;
  1035. for (i = 0; i < n; i += 2) {
  1036. u16 tid = trans_id_function();
  1037. buf[i] = (tid >> 8) & 0xff;
  1038. if (i+1<n)
  1039. buf[i+1] = tid & 0xff;
  1040. }
  1041. }
  1042. static void (*rand_bytes_function)(char *buf, size_t n) =
  1043. default_random_bytes_fn;
  1044. static u16
  1045. trans_id_from_random_bytes_fn(void)
  1046. {
  1047. u16 tid;
  1048. rand_bytes_function((char*) &tid, sizeof(tid));
  1049. return tid;
  1050. }
  1051. void
  1052. evdns_set_transaction_id_fn(uint16_t (*fn)(void))
  1053. {
  1054. if (fn)
  1055. trans_id_function = fn;
  1056. else
  1057. trans_id_function = default_transaction_id_fn;
  1058. rand_bytes_function = default_random_bytes_fn;
  1059. }
  1060. void
  1061. evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
  1062. {
  1063. rand_bytes_function = fn;
  1064. trans_id_function = trans_id_from_random_bytes_fn;
  1065. }
  1066. /* Try to choose a strong transaction id which isn't already in flight */
  1067. static u16
  1068. transaction_id_pick(void) {
  1069. for (;;) {
  1070. const struct evdns_request *req = req_head, *started_at;
  1071. u16 trans_id = trans_id_function();
  1072. if (trans_id == 0xffff) continue;
  1073. /* now check to see if that id is already inflight */
  1074. req = started_at = req_head;
  1075. if (req) {
  1076. do {
  1077. if (req->trans_id == trans_id) break;
  1078. req = req->next;
  1079. } while (req != started_at);
  1080. }
  1081. /* we didn't find it, so this is a good id */
  1082. if (req == started_at) return trans_id;
  1083. }
  1084. }
  1085. /* choose a namesever to use. This function will try to ignore */
  1086. /* nameservers which we think are down and load balance across the rest */
  1087. /* by updating the server_head global each time. */
  1088. static struct nameserver *
  1089. nameserver_pick(void) {
  1090. struct nameserver *started_at = server_head, *picked;
  1091. if (!server_head) return NULL;
  1092. /* if we don't have any good nameservers then there's no */
  1093. /* point in trying to find one. */
  1094. if (!global_good_nameservers) {
  1095. server_head = server_head->next;
  1096. return server_head;
  1097. }
  1098. /* remember that nameservers are in a circular list */
  1099. for (;;) {
  1100. if (server_head->state) {
  1101. /* we think this server is currently good */
  1102. picked = server_head;
  1103. server_head = server_head->next;
  1104. return picked;
  1105. }
  1106. server_head = server_head->next;
  1107. if (server_head == started_at) {
  1108. /* all the nameservers seem to be down */
  1109. /* so we just return this one and hope for the */
  1110. /* best */
  1111. assert(global_good_nameservers == 0);
  1112. picked = server_head;
  1113. server_head = server_head->next;
  1114. return picked;
  1115. }
  1116. }
  1117. }
  1118. /* this is called when a namesever socket is ready for reading */
  1119. static void
  1120. nameserver_read(struct nameserver *ns) {
  1121. struct sockaddr_storage ss;
  1122. struct sockaddr *sa = (struct sockaddr *) &ss;
  1123. socklen_t addrlen = sizeof(ss);
  1124. u8 packet[1500];
  1125. for (;;) {
  1126. const int r =
  1127. (int)recvfrom(ns->socket, packet, (socklen_t)sizeof(packet), 0,
  1128. sa, &addrlen);
  1129. if (r < 0) {
  1130. int err = last_error(ns->socket);
  1131. if (error_is_eagain(err)) return;
  1132. nameserver_failed(ns, strerror(err));
  1133. return;
  1134. }
  1135. /* XXX Match port too? */
  1136. if (!sockaddr_eq(sa, (struct sockaddr*)&ns->address, 0)) {
  1137. log(EVDNS_LOG_WARN,
  1138. "Address mismatch on received DNS packet. Address was %s",
  1139. debug_ntop(sa));
  1140. return;
  1141. }
  1142. ns->timedout = 0;
  1143. reply_parse(packet, r);
  1144. }
  1145. }
  1146. /* Read a packet from a DNS client on a server port s, parse it, and */
  1147. /* act accordingly. */
  1148. static void
  1149. server_port_read(struct evdns_server_port *s) {
  1150. u8 packet[1500];
  1151. struct sockaddr_storage addr;
  1152. socklen_t addrlen;
  1153. ssize_t r;
  1154. for (;;) {
  1155. addrlen = (socklen_t)sizeof(struct sockaddr_storage);
  1156. r = recvfrom(s->socket, packet, sizeof(packet), 0,
  1157. (struct sockaddr*) &addr, &addrlen);
  1158. if (r < 0) {
  1159. int err = last_error(s->socket);
  1160. if (error_is_eagain(err)) return;
  1161. log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
  1162. strerror(err), err);
  1163. return;
  1164. }
  1165. request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
  1166. }
  1167. }
  1168. /* Try to write all pending replies on a given DNS server port. */
  1169. static void
  1170. server_port_flush(struct evdns_server_port *port)
  1171. {
  1172. while (port->pending_replies) {
  1173. struct server_request *req = port->pending_replies;
  1174. ssize_t r = sendto(port->socket, req->response, req->response_len, 0,
  1175. (struct sockaddr*) &req->addr, (socklen_t)req->addrlen);
  1176. if (r < 0) {
  1177. int err = last_error(port->socket);
  1178. if (error_is_eagain(err))
  1179. return;
  1180. log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
  1181. }
  1182. if (server_request_free(req)) {
  1183. /* we released the last reference to req->port. */
  1184. return;
  1185. }
  1186. }
  1187. /* We have no more pending requests; stop listening for 'writeable' events. */
  1188. (void) event_del(&port->event);
  1189. CLEAR(&port->event);
  1190. event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
  1191. server_port_ready_callback, port);
  1192. if (event_add(&port->event, NULL) < 0) {
  1193. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
  1194. /* ???? Do more? */
  1195. }
  1196. }
  1197. /* set if we are waiting for the ability to write to this server. */
  1198. /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
  1199. /* we stop these events. */
  1200. static void
  1201. nameserver_write_waiting(struct nameserver *ns, char waiting) {
  1202. if (ns->write_waiting == waiting) return;
  1203. ns->write_waiting = waiting;
  1204. (void) event_del(&ns->event);
  1205. CLEAR(&ns->event);
  1206. event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
  1207. nameserver_ready_callback, ns);
  1208. if (event_add(&ns->event, NULL) < 0) {
  1209. log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
  1210. debug_ntop((struct sockaddr *)&ns->address));
  1211. /* ???? Do more? */
  1212. }
  1213. }
  1214. /* a callback function. Called by libevent when the kernel says that */
  1215. /* a nameserver socket is ready for writing or reading */
  1216. static void
  1217. nameserver_ready_callback(int fd, short events, void *arg) {
  1218. struct nameserver *ns = (struct nameserver *) arg;
  1219. (void)fd;
  1220. if (events & EV_WRITE) {
  1221. ns->choked = 0;
  1222. if (!evdns_transmit()) {
  1223. nameserver_write_waiting(ns, 0);
  1224. }
  1225. }
  1226. if (events & EV_READ) {
  1227. nameserver_read(ns);
  1228. }
  1229. }
  1230. /* a callback function. Called by libevent when the kernel says that */
  1231. /* a server socket is ready for writing or reading. */
  1232. static void
  1233. server_port_ready_callback(int fd, short events, void *arg) {
  1234. struct evdns_server_port *port = (struct evdns_server_port *) arg;
  1235. (void) fd;
  1236. if (events & EV_WRITE) {
  1237. port->choked = 0;
  1238. server_port_flush(port);
  1239. }
  1240. if (events & EV_READ) {
  1241. server_port_read(port);
  1242. }
  1243. }
  1244. /* This is an inefficient representation; only use it via the dnslabel_table_*
  1245. * functions, so that is can be safely replaced with something smarter later. */
  1246. #define MAX_LABELS 128
  1247. /* Structures used to implement name compression */
  1248. struct dnslabel_entry { char *v; off_t pos; };
  1249. struct dnslabel_table {
  1250. int n_labels; /* number of current entries */
  1251. /* map from name to position in message */
  1252. struct dnslabel_entry labels[MAX_LABELS];
  1253. };
  1254. /* Initialize dnslabel_table. */
  1255. static void
  1256. dnslabel_table_init(struct dnslabel_table *table)
  1257. {
  1258. table->n_labels = 0;
  1259. }
  1260. /* Free all storage held by table, but not the table itself. */
  1261. static void
  1262. dnslabel_clear(struct dnslabel_table *table)
  1263. {
  1264. int i;
  1265. for (i = 0; i < table->n_labels; ++i)
  1266. mm_free(table->labels[i].v);
  1267. table->n_labels = 0;
  1268. }
  1269. /* return the position of the label in the current message, or -1 if the label */
  1270. /* hasn't been used yet. */
  1271. static int
  1272. dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
  1273. {
  1274. int i;
  1275. for (i = 0; i < table->n_labels; ++i) {
  1276. if (!strcmp(label, table->labels[i].v)) {
  1277. off_t pos = table->labels[i].pos;
  1278. if (pos > 65535)
  1279. return -1;
  1280. return (int)pos;
  1281. }
  1282. }
  1283. return -1;
  1284. }
  1285. /* remember that we've used the label at position pos */
  1286. static int
  1287. dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
  1288. {
  1289. char *v;
  1290. int p;
  1291. if (table->n_labels == MAX_LABELS)
  1292. return (-1);
  1293. v = mm_strdup(label);
  1294. if (v == NULL)
  1295. return (-1);
  1296. p = table->n_labels++;
  1297. table->labels[p].v = v;
  1298. table->labels[p].pos = pos;
  1299. return (0);
  1300. }
  1301. /* Converts a string to a length-prefixed set of DNS labels, starting */
  1302. /* at buf[j]. name and buf must not overlap. name_len should be the length */
  1303. /* of name. table is optional, and is used for compression. */
  1304. /* */
  1305. /* Input: abc.def */
  1306. /* Output: <3>abc<3>def<0> */
  1307. /* */
  1308. /* Returns the first index after the encoded name, or negative on error. */
  1309. /* -1 label was > 63 bytes */
  1310. /* -2 name too long to fit in buffer. */
  1311. /* */
  1312. static off_t
  1313. dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
  1314. const char *name, const size_t name_len,
  1315. struct dnslabel_table *table) {
  1316. const char *end = name + name_len;
  1317. int ref = 0;
  1318. u16 _t;
  1319. #define APPEND16(x) do { \
  1320. if (j + 2 > (off_t)buf_len) \
  1321. goto overflow; \
  1322. _t = htons(x); \
  1323. memcpy(buf + j, &_t, 2); \
  1324. j += 2; \
  1325. } while (0)
  1326. #define APPEND32(x) do { \
  1327. if (j + 4 > (off_t)buf_len) \
  1328. goto overflow; \
  1329. _t32 = htonl(x); \
  1330. memcpy(buf + j, &_t32, 4); \
  1331. j += 4; \
  1332. } while (0)
  1333. if (name_len > 255) return -2;
  1334. for (;;) {
  1335. const char *const start = name;
  1336. if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
  1337. APPEND16(ref | 0xc000);
  1338. return j;
  1339. }
  1340. name = strchr(name, '.');
  1341. if (!name) {
  1342. const size_t label_len = end - start;
  1343. if (label_len > 63) return -1;
  1344. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1345. if (table) dnslabel_table_add(table, start, j);
  1346. buf[j++] = (uint8_t)label_len;
  1347. memcpy(buf + j, start, label_len);
  1348. j += end - start;
  1349. break;
  1350. } else {
  1351. /* append length of the label. */
  1352. const size_t label_len = name - start;
  1353. if (label_len > 63) return -1;
  1354. if ((size_t)(j+label_len+1) > buf_len) return -2;
  1355. if (table) dnslabel_table_add(table, start, j);
  1356. buf[j++] = (uint8_t)label_len;
  1357. memcpy(buf + j, start, name - start);
  1358. j += name - start;
  1359. /* hop over the '.' */
  1360. name++;
  1361. }
  1362. }
  1363. /* the labels must be terminated by a 0. */
  1364. /* It's possible that the name ended in a . */
  1365. /* in which case the zero is already there */
  1366. if (!j || buf[j-1]) buf[j++] = 0;
  1367. return j;
  1368. overflow:
  1369. return (-2);
  1370. }
  1371. /* Finds the length of a dns request for a DNS name of the given */
  1372. /* length. The actual request may be smaller than the value returned */
  1373. /* here */
  1374. static size_t
  1375. evdns_request_len(const size_t name_len) {
  1376. return 96 + /* length of the DNS standard header */
  1377. name_len + 2 +
  1378. 4; /* space for the resource type */
  1379. }
  1380. /* build a dns request packet into buf. buf should be at least as long */
  1381. /* as evdns_request_len told you it should be. */
  1382. /* */
  1383. /* Returns the amount of space used. Negative on error. */
  1384. static int
  1385. evdns_request_data_build(const char *const name, const size_t name_len,
  1386. const u16 trans_id, const u16 type, const u16 class,
  1387. u8 *const buf, size_t buf_len) {
  1388. off_t j = 0; /* current offset into buf */
  1389. u16 _t; /* used by the macros */
  1390. APPEND16(trans_id);
  1391. APPEND16(0x0100); /* standard query, recusion needed */
  1392. APPEND16(1); /* one question */
  1393. APPEND16(0); /* no answers */
  1394. APPEND16(0); /* no authority */
  1395. APPEND16(0); /* no additional */
  1396. j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
  1397. if (j < 0) {
  1398. return (int)j;
  1399. }
  1400. APPEND16(type);
  1401. APPEND16(class);
  1402. return (int)j;
  1403. overflow:
  1404. return (-1);
  1405. }
  1406. /* exported function */
  1407. struct evdns_server_port *
  1408. evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
  1409. {
  1410. struct evdns_server_port *port;
  1411. if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
  1412. return NULL;
  1413. memset(port, 0, sizeof(struct evdns_server_port));
  1414. assert(!is_tcp); /* TCP sockets not yet implemented */
  1415. port->socket = socket;
  1416. port->refcnt = 1;
  1417. port->choked = 0;
  1418. port->closing = 0;
  1419. port->user_callback = cb;
  1420. port->user_data = user_data;
  1421. port->pending_replies = NULL;
  1422. event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
  1423. server_port_ready_callback, port);
  1424. if (event_add(&port->event, NULL)<0) {
  1425. mm_free(port);
  1426. return NULL;
  1427. }
  1428. return port;
  1429. }
  1430. /* exported function */
  1431. void
  1432. evdns_close_server_port(struct evdns_server_port *port)
  1433. {
  1434. port->closing = 1;
  1435. if (--port->refcnt == 0)
  1436. server_port_free(port);
  1437. }
  1438. /* exported function */
  1439. int
  1440. 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)
  1441. {
  1442. struct server_request *req = TO_SERVER_REQUEST(_req);
  1443. struct server_reply_item **itemp, *item;
  1444. int *countp;
  1445. if (req->response) /* have we already answered? */
  1446. return (-1);
  1447. switch (section) {
  1448. case EVDNS_ANSWER_SECTION:
  1449. itemp = &req->answer;
  1450. countp = &req->n_answer;
  1451. break;
  1452. case EVDNS_AUTHORITY_SECTION:
  1453. itemp = &req->authority;
  1454. countp = &req->n_authority;
  1455. break;
  1456. case EVDNS_ADDITIONAL_SECTION:
  1457. itemp = &req->additional;
  1458. countp = &req->n_additional;
  1459. break;
  1460. default:
  1461. return (-1);
  1462. }
  1463. while (*itemp) {
  1464. itemp = &((*itemp)->next);
  1465. }
  1466. item = mm_malloc(sizeof(struct server_reply_item));
  1467. if (!item)
  1468. return -1;
  1469. CLEAR(item);
  1470. item->next = NULL;
  1471. if (!(item->name = mm_strdup(name))) {
  1472. CLEAR(item);
  1473. mm_free(item);
  1474. return -1;
  1475. }
  1476. item->type = type;
  1477. item->class = class;
  1478. item->ttl = ttl;
  1479. item->is_name = is_name != 0;
  1480. item->datalen = 0;
  1481. item->data = NULL;
  1482. if (data) {
  1483. if (item->is_name) {
  1484. if (!(item->data = mm_strdup(data))) {
  1485. mm_free(item->name);
  1486. CLEAR(item);
  1487. mm_free(item);
  1488. return -1;
  1489. }
  1490. item->datalen = (u16)-1;
  1491. } else {
  1492. if (!(item->data = mm_malloc(datalen))) {
  1493. mm_free(item->name);
  1494. CLEAR(item);
  1495. mm_free(item);
  1496. return -1;
  1497. }
  1498. item->datalen = datalen;
  1499. memcpy(item->data, data, datalen);
  1500. }
  1501. }
  1502. *itemp = item;
  1503. ++(*countp);
  1504. return 0;
  1505. }
  1506. /* exported function */
  1507. int
  1508. evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
  1509. {
  1510. return evdns_server_request_add_reply(
  1511. req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
  1512. ttl, n*4, 0, addrs);
  1513. }
  1514. /* exported function */
  1515. int
  1516. evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
  1517. {
  1518. return evdns_server_request_add_reply(
  1519. req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
  1520. ttl, n*16, 0, addrs);
  1521. }
  1522. /* exported function */
  1523. int
  1524. evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
  1525. {
  1526. u32 a;
  1527. char buf[32];
  1528. assert(in || inaddr_name);
  1529. assert(!(in && inaddr_name));
  1530. if (in) {
  1531. a = ntohl(in->s_addr);
  1532. snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  1533. (int)(u8)((a )&0xff),
  1534. (int)(u8)((a>>8 )&0xff),
  1535. (int)(u8)((a>>16)&0xff),
  1536. (int)(u8)((a>>24)&0xff));
  1537. inaddr_name = buf;
  1538. }
  1539. return evdns_server_request_add_reply(
  1540. req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
  1541. ttl, -1, 1, hostname);
  1542. }
  1543. /* exported function */
  1544. int
  1545. evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
  1546. {
  1547. return evdns_server_request_add_reply(
  1548. req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
  1549. ttl, -1, 1, cname);
  1550. }
  1551. static int
  1552. evdns_server_request_format_response(struct server_request *req, int err)
  1553. {
  1554. unsigned char buf[1500];
  1555. size_t buf_len = sizeof(buf);
  1556. off_t j = 0, r;
  1557. u16 _t;
  1558. u32 _t32;
  1559. int i;
  1560. u16 flags;
  1561. struct dnslabel_table table;
  1562. if (err < 0 || err > 15) return -1;
  1563. /* Set response bit and error code; copy OPCODE and RD fields from
  1564. * question; copy RA and AA if set by caller. */
  1565. flags = req->base.flags;
  1566. flags |= (0x8000 | err);
  1567. dnslabel_table_init(&table);
  1568. APPEND16(req->trans_id);
  1569. APPEND16(flags);
  1570. APPEND16(req->base.nquestions);
  1571. APPEND16(req->n_answer);
  1572. APPEND16(req->n_authority);
  1573. APPEND16(req->n_additional);
  1574. /* Add questions. */
  1575. for (i=0; i < req->base.nquestions; ++i) {
  1576. const char *s = req->base.questions[i]->name;
  1577. j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
  1578. if (j < 0) {
  1579. dnslabel_clear(&table);
  1580. return (int) j;
  1581. }
  1582. APPEND16(req->base.questions[i]->type);
  1583. APPEND16(req->base.questions[i]->dns_question_class);
  1584. }
  1585. /* Add answer, authority, and additional sections. */
  1586. for (i=0; i<3; ++i) {
  1587. struct server_reply_item *item;
  1588. if (i==0)
  1589. item = req->answer;
  1590. else if (i==1)
  1591. item = req->authority;
  1592. else
  1593. item = req->additional;
  1594. while (item) {
  1595. r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
  1596. if (r < 0)
  1597. goto overflow;
  1598. j = r;
  1599. APPEND16(item->type);
  1600. APPEND16(item->class);
  1601. APPEND32(item->ttl);
  1602. if (item->is_name) {
  1603. off_t len_idx = j, name_start;
  1604. j += 2;
  1605. name_start = j;
  1606. r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
  1607. if (r < 0)
  1608. goto overflow;
  1609. j = r;
  1610. _t = htons( (j-name_start) );
  1611. memcpy(buf+len_idx, &_t, 2);
  1612. } else {
  1613. APPEND16(item->datalen);
  1614. if (j+item->datalen > (off_t)buf_len)
  1615. goto overflow;
  1616. memcpy(buf+j, item->data, item->datalen);
  1617. j += item->datalen;
  1618. }
  1619. item = item->next;
  1620. }
  1621. }
  1622. if (j > 512) {
  1623. overflow:
  1624. j = 512;
  1625. buf[3] |= 0x02; /* set the truncated bit. */
  1626. }
  1627. req->response_len = (size_t)j;
  1628. if (!(req->response = mm_malloc(req->response_len))) {
  1629. server_request_free_answers(req);
  1630. dnslabel_clear(&table);
  1631. return (-1);
  1632. }
  1633. memcpy(req->response, buf, req->response_len);
  1634. server_request_free_answers(req);
  1635. dnslabel_clear(&table);
  1636. return (0);
  1637. }
  1638. /* exported function */
  1639. int
  1640. evdns_server_request_respond(struct evdns_server_request *_req, int err)
  1641. {
  1642. struct server_request *req = TO_SERVER_REQUEST(_req);
  1643. struct evdns_server_port *port = req->port;
  1644. ssize_t r;
  1645. if (!req->response) {
  1646. if ((r = evdns_server_request_format_response(req, err))<0)
  1647. return (int)r;
  1648. }
  1649. r = sendto(port->socket, req->response, req->response_len, 0,
  1650. (struct sockaddr*) &req->addr, req->addrlen);
  1651. if (r<0) {
  1652. int err = last_error(port->socket);
  1653. if (! error_is_eagain(err))
  1654. return -1;
  1655. if (port->pending_replies) {
  1656. req->prev_pending = port->pending_replies->prev_pending;
  1657. req->next_pending = port->pending_replies;
  1658. req->prev_pending->next_pending =
  1659. req->next_pending->prev_pending = req;
  1660. } else {
  1661. req->prev_pending = req->next_pending = req;
  1662. port->pending_replies = req;
  1663. port->choked = 1;
  1664. (void) event_del(&port->event);
  1665. CLEAR(&port->event);
  1666. event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
  1667. if (event_add(&port->event, NULL) < 0) {
  1668. log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
  1669. }
  1670. }
  1671. return 1;
  1672. }
  1673. if (server_request_free(req))
  1674. return 0;
  1675. if (port->pending_replies)
  1676. server_port_flush(port);
  1677. return 0;
  1678. }
  1679. /* Free all storage held by RRs in req. */
  1680. static void
  1681. server_request_free_answers(struct server_request *req)
  1682. {
  1683. struct server_reply_item *victim, *next, **list;
  1684. int i;
  1685. for (i = 0; i < 3; ++i) {
  1686. if (i==0)
  1687. list = &req->answer;
  1688. else if (i==1)
  1689. list = &req->authority;
  1690. else
  1691. list = &req->additional;
  1692. victim = *list;
  1693. while (victim) {
  1694. next = victim->next;
  1695. mm_free(victim->name);
  1696. if (victim->data)
  1697. mm_free(victim->data);
  1698. mm_free(victim);
  1699. victim = next;
  1700. }
  1701. *list = NULL;
  1702. }
  1703. }
  1704. /* Free all storage held by req, and remove links to it. */
  1705. /* return true iff we just wound up freeing the server_port. */
  1706. static int
  1707. server_request_free(struct server_request *req)
  1708. {
  1709. int i, rc=1;
  1710. if (req->base.questions) {
  1711. for (i = 0; i < req->base.nquestions; ++i)
  1712. mm_free(req->base.questions[i]);
  1713. mm_free(req->base.questions);
  1714. }
  1715. if (req->port) {
  1716. if (req->port->pending_replies == req) {
  1717. if (req->next_pending)
  1718. req->port->pending_replies = req->next_pending;
  1719. else
  1720. req->port->pending_replies = NULL;
  1721. }
  1722. rc = --req->port->refcnt;
  1723. }
  1724. if (req->response) {
  1725. mm_free(req->response);
  1726. }
  1727. server_request_free_answers(req);
  1728. if (req->next_pending && req->next_pending != req) {
  1729. req->next_pending->prev_pending = req->prev_pending;
  1730. req->prev_pending->next_pending = req->next_pending;
  1731. }
  1732. if (rc == 0) {
  1733. server_port_free(req->port);
  1734. CLEAR(req);
  1735. mm_free(req);
  1736. return (1);
  1737. }
  1738. CLEAR(req);
  1739. mm_free(req);
  1740. return (0);
  1741. }
  1742. /* Free all storage held by an evdns_server_port. Only called when the
  1743. * reference count is down to 0. */
  1744. static void
  1745. server_port_free(struct evdns_server_port *port)
  1746. {
  1747. assert(port);
  1748. assert(!port->refcnt);
  1749. assert(!port->pending_replies);
  1750. if (port->socket > 0) {
  1751. CLOSE_SOCKET(port->socket);
  1752. port->socket = -1;
  1753. }
  1754. (void) event_del(&port->event);
  1755. CLEAR(&port->event);
  1756. CLEAR(port);
  1757. mm_free(port);
  1758. }
  1759. /* exported function */
  1760. int
  1761. evdns_server_request_drop(struct evdns_server_request *_req)
  1762. {
  1763. struct server_request *req = TO_SERVER_REQUEST(_req);
  1764. server_request_free(req);
  1765. return 0;
  1766. }
  1767. /* exported function */
  1768. int
  1769. evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
  1770. {
  1771. struct server_request *req = TO_SERVER_REQUEST(_req);
  1772. if (addr_len < (int)req->addrlen)
  1773. return -1;
  1774. memcpy(sa, &(req->addr), req->addrlen);
  1775. return req->addrlen;
  1776. }
  1777. #undef APPEND16
  1778. #undef APPEND32
  1779. /* this is a libevent callback function which is called when a request */
  1780. /* has timed out. */
  1781. static void
  1782. evdns_request_timeout_callback(int fd, short events, void *arg) {
  1783. struct evdns_request *const req = (struct evdns_request *) arg;
  1784. (void) fd;
  1785. (void) events;
  1786. log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
  1787. req->ns->timedout++;
  1788. if (req->ns->timedout > global_max_nameserver_timeout) {
  1789. req->ns->timedout = 0;
  1790. nameserver_failed(req->ns, "request timed out.");
  1791. }
  1792. del_timeout_event(req);
  1793. CLEAR(&req->timeout_event);
  1794. if (req->tx_count >= global_max_retransmits) {
  1795. /* this request has failed */
  1796. reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
  1797. request_finished(req, &req_head);
  1798. } else {
  1799. /* retransmit it */
  1800. evdns_request_transmit(req);
  1801. }
  1802. }
  1803. /* try to send a request to a given server. */
  1804. /* */
  1805. /* return: */
  1806. /* 0 ok */
  1807. /* 1 temporary failure */
  1808. /* 2 other failure */
  1809. static int
  1810. evdns_request_transmit_to(struct evdns_request *req, struct nameserver *server) {
  1811. const ssize_t r = send(server->socket, req->request, req->request_len, 0);
  1812. if (r < 0) {
  1813. int err = last_error(server->socket);
  1814. if (error_is_eagain(err)) return 1;
  1815. nameserver_failed(req->ns, strerror(err));
  1816. return 2;
  1817. } else if (r != (ssize_t)req->request_len) {
  1818. return 1; /* short write */
  1819. } else {
  1820. return 0;
  1821. }
  1822. }
  1823. /* try to send a request, updating the fields of the request */
  1824. /* as needed */
  1825. /* */
  1826. /* return: */
  1827. /* 0 ok */
  1828. /* 1 failed */
  1829. static int
  1830. evdns_request_transmit(struct evdns_request *req) {
  1831. int retcode = 0, r;
  1832. /* if we fail to send this packet then this flag marks it */
  1833. /* for evdns_transmit */
  1834. req->transmit_me = 1;
  1835. if (req->trans_id == 0xffff) abort();
  1836. if (req->ns->choked) {
  1837. /* don't bother trying to write to a socket */
  1838. /* which we have had EAGAIN from */
  1839. return 1;
  1840. }
  1841. r = evdns_request_transmit_to(req, req->ns);
  1842. switch (r) {
  1843. case 1:
  1844. /* temp failure */
  1845. req->ns->choked = 1;
  1846. nameserver_write_waiting(req->ns, 1);
  1847. return 1;
  1848. case 2:
  1849. /* failed to transmit the request entirely. */
  1850. retcode = 1;
  1851. /* fall through: we'll set a timeout, which will time out,
  1852. * and make us retransmit the request anyway. */
  1853. default:
  1854. /* transmitted; we need to check for timeout. */
  1855. log(EVDNS_LOG_DEBUG,
  1856. "Setting timeout for request %lx", (unsigned long) req);
  1857. evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
  1858. if (add_timeout_event(req, &global_timeout) < 0) {
  1859. log(EVDNS_LOG_WARN,
  1860. "Error from libevent when adding timer for request %lx",
  1861. (unsigned long) req);
  1862. /* ???? Do more? */
  1863. }
  1864. req->tx_count++;
  1865. req->transmit_me = 0;
  1866. return retcode;
  1867. }
  1868. }
  1869. static void
  1870. nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
  1871. struct sockaddr *addr = arg;
  1872. struct nameserver *server;
  1873. (void) type;
  1874. (void) count;
  1875. (void) ttl;
  1876. (void) addresses;
  1877. for (server = server_head; server; server = server->next) {
  1878. if (sockaddr_eq(addr, (struct sockaddr*) &server->address, 1)) {
  1879. if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
  1880. /* this is a good reply */
  1881. nameserver_up(server);
  1882. } else {
  1883. nameserver_probe_failed(server);
  1884. }
  1885. }
  1886. if (server->next == server_head)
  1887. break;
  1888. }
  1889. mm_free(addr);
  1890. }
  1891. static void
  1892. nameserver_send_probe(struct nameserver *const ns) {
  1893. struct evdns_request *req;
  1894. struct sockaddr_storage *addr;
  1895. /* here we need to send a probe to a given nameserver */
  1896. /* in the hope that it is up now. */
  1897. /* We identify the nameserver by its address, in case it is removed before
  1898. * our probe comes back. */
  1899. addr = mm_malloc(sizeof(struct sockaddr_storage));
  1900. memcpy(addr, &ns->address, sizeof(struct sockaddr_storage));
  1901. log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntop((struct sockaddr *)&ns->address));
  1902. req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, addr);
  1903. if (!req) {
  1904. mm_free(addr);
  1905. return;
  1906. }
  1907. /* we force this into the inflight queue no matter what */
  1908. request_trans_id_set(req, transaction_id_pick());
  1909. req->ns = ns;
  1910. request_submit(req);
  1911. }
  1912. /* returns: */
  1913. /* 0 didn't try to transmit anything */
  1914. /* 1 tried to transmit something */
  1915. static int
  1916. evdns_transmit(void) {
  1917. char did_try_to_transmit = 0;
  1918. if (req_head) {
  1919. struct evdns_request *const started_at = req_head, *req = req_head;
  1920. /* first transmit all the requests which are currently waiting */
  1921. do {
  1922. if (req->transmit_me) {
  1923. did_try_to_transmit = 1;
  1924. evdns_request_transmit(req);
  1925. }
  1926. req = req->next;
  1927. } while (req != started_at);
  1928. }
  1929. return did_try_to_transmit;
  1930. }
  1931. /* exported function */
  1932. int
  1933. evdns_count_nameservers(void)
  1934. {
  1935. const struct nameserver *server = server_head;
  1936. int n = 0;
  1937. if (!server)
  1938. return 0;
  1939. do {
  1940. ++n;
  1941. server = server->next;
  1942. } while (server != server_head);
  1943. return n;
  1944. }
  1945. /* exported function */
  1946. int
  1947. evdns_clear_nameservers_and_suspend(void)
  1948. {
  1949. struct nameserver *server = server_head, *started_at = server_head;
  1950. struct evdns_request *req = req_head, *req_started_at = req_head;
  1951. if (!server)
  1952. return 0;
  1953. while (1) {
  1954. struct nameserver *next = server->next;
  1955. (void) event_del(&server->event);
  1956. CLEAR(&server->event);
  1957. del_timeout_event(server);
  1958. CLEAR(&server->timeout_event);
  1959. if (server->socket >= 0)
  1960. CLOSE_SOCKET(server->socket);
  1961. CLEAR(server);
  1962. mm_free(server);
  1963. if (next == started_at)
  1964. break;
  1965. server = next;
  1966. }
  1967. server_head = NULL;
  1968. global_good_nameservers = 0;
  1969. while (req) {
  1970. struct evdns_request *next = req->next;
  1971. req->tx_count = req->reissue_count = 0;
  1972. req->ns = NULL;
  1973. /* ???? What to do about searches? */
  1974. del_timeout_event(req);
  1975. CLEAR(&req->timeout_event);
  1976. req->trans_id = 0;
  1977. req->transmit_me = 0;
  1978. global_requests_waiting++;
  1979. evdns_request_insert(req, &req_waiting_head);
  1980. /* We want to insert these suspended elements at the front of
  1981. * the waiting queue, since they were pending before any of
  1982. * the waiting entries were added. This is a circular list,
  1983. * so we can just shift the start back by one.*/
  1984. req_waiting_head = req_waiting_head->prev;
  1985. if (next == req_started_at)
  1986. break;
  1987. req = next;
  1988. }
  1989. req_head = NULL;
  1990. global_requests_inflight = 0;
  1991. return 0;
  1992. }
  1993. static struct sockaddr_storage global_bind_address;
  1994. static socklen_t global_bind_addrlen = 0;
  1995. static int global_bind_addr_is_set = 0;
  1996. void
  1997. evdns_set_default_outgoing_bind_address(const struct sockaddr *addr,
  1998. socklen_t addrlen)
  1999. {
  2000. memset(&global_bind_address, 0, sizeof(global_bind_address));
  2001. if (addr) {
  2002. assert(addrlen <= (socklen_t)sizeof(global_bind_address));
  2003. memcpy(&global_bind_address, addr, addrlen);
  2004. global_bind_addrlen = addrlen;
  2005. global_bind_addr_is_set = 1;
  2006. } else {
  2007. global_bind_addr_is_set = 0;
  2008. }
  2009. }
  2010. /* exported function */
  2011. int
  2012. evdns_resume(void)
  2013. {
  2014. evdns_requests_pump_waiting_queue();
  2015. return 0;
  2016. }
  2017. static int
  2018. _evdns_nameserver_add_impl(const struct sockaddr *address,
  2019. socklen_t addrlen) {
  2020. /* first check to see if we already have this nameserver */
  2021. const struct nameserver *server = server_head, *const started_at = server_head;
  2022. struct nameserver *ns;
  2023. int err = 0;
  2024. if (server) {
  2025. do {
  2026. if (sockaddr_eq(address, (struct sockaddr *)&server->address, 1)) {
  2027. log(EVDNS_LOG_DEBUG, "Duplicate nameserver.");
  2028. return 3;
  2029. }
  2030. server = server->next;
  2031. } while (server != started_at);
  2032. }
  2033. if (addrlen > (int)sizeof(ns->address)) {
  2034. log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
  2035. return 2;
  2036. }
  2037. ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
  2038. if (!ns) return -1;
  2039. memset(ns, 0, sizeof(struct nameserver));
  2040. ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
  2041. if (ns->socket < 0) { err = 1; goto out1; }
  2042. #ifdef WIN32
  2043. {
  2044. u_long nonblocking = 1;
  2045. ioctlsocket(ns->socket, FIONBIO, &nonblocking);
  2046. }
  2047. #else
  2048. fcntl(ns->socket, F_SETFL, O_NONBLOCK);
  2049. #endif
  2050. if (global_bind_addr_is_set) {
  2051. if (bind(ns->socket, (struct sockaddr *)&global_bind_address,
  2052. global_bind_addrlen) < 0) {
  2053. log(EVDNS_LOG_DEBUG, "Couldn't bind to outgoing address.");
  2054. err = 2;
  2055. goto out2;
  2056. }
  2057. }
  2058. if (connect(ns->socket, address, addrlen) != 0) {
  2059. log(EVDNS_LOG_DEBUG, "Couldn't open socket to nameserver.");
  2060. err = 2;
  2061. goto out2;
  2062. }
  2063. memcpy(&ns->address, address, addrlen);
  2064. ns->state = 1;
  2065. event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
  2066. if (event_add(&ns->event, NULL) < 0) {
  2067. log(EVDNS_LOG_DEBUG, "Couldn't add event for nameserver.");
  2068. err = 2;
  2069. goto out2;
  2070. }
  2071. log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntop(address));
  2072. /* insert this nameserver into the list of them */
  2073. if (!server_head) {
  2074. ns->next = ns->prev = ns;
  2075. server_head = ns;
  2076. } else {
  2077. ns->next = server_head->next;
  2078. ns->prev = server_head;
  2079. server_head->next = ns;
  2080. if (server_head->prev == server_head) {
  2081. server_head->prev = ns;
  2082. }
  2083. }
  2084. global_good_nameservers++;
  2085. return 0;
  2086. out2:
  2087. CLOSE_SOCKET(ns->socket);
  2088. out1:
  2089. CLEAR(ns);
  2090. mm_free(ns);
  2091. log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntop(address), err);
  2092. return err;
  2093. }
  2094. /* exported function */
  2095. int
  2096. evdns_nameserver_add(unsigned long int address) {
  2097. struct sockaddr_in sin;
  2098. memset(&sin, 0, sizeof(sin));
  2099. sin.sin_family = AF_INET;
  2100. #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  2101. sin.sin_len = sizeof(sin);
  2102. #endif
  2103. sin.sin_addr.s_addr = htonl(address);
  2104. sin.sin_port = 53;
  2105. return _evdns_nameserver_add_impl((struct sockaddr*) &sin, sizeof(sin));
  2106. }
  2107. /* exported function */
  2108. int
  2109. evdns_nameserver_ip_add(const char *ip_as_string) {
  2110. int port;
  2111. char buf[128];
  2112. const char *cp, *addr_part, *port_part;
  2113. int is_ipv6;
  2114. /* recognized formats are:
  2115. * [ipv6]:port
  2116. * ipv6
  2117. * [ipv6]
  2118. * ipv4:port
  2119. * ipv4
  2120. */
  2121. log(EVDNS_LOG_DEBUG, "Trying to add nameserver <%s>", ip_as_string);
  2122. cp = strchr(ip_as_string, ':');
  2123. if (*ip_as_string == '[') {
  2124. int len;
  2125. if (!(cp = strchr(ip_as_string, ']'))) {
  2126. log(EVDNS_LOG_DEBUG, "Nameserver missing closing ]");
  2127. return 4;
  2128. }
  2129. len = cp-(ip_as_string + 1);
  2130. if (len > (int)sizeof(buf)-1) {
  2131. log(EVDNS_LOG_DEBUG, "[Nameserver] does not fit in buffer.");
  2132. return 4;
  2133. }
  2134. memcpy(buf, ip_as_string+1, len);
  2135. buf[len] = '\0';
  2136. addr_part = buf;
  2137. if (cp[1] == ':')
  2138. port_part = cp+2;
  2139. else
  2140. port_part = NULL;
  2141. is_ipv6 = 1;
  2142. } else if (cp && strchr(cp+1, ':')) {
  2143. is_ipv6 = 1;
  2144. addr_part = ip_as_string;
  2145. port_part = NULL;
  2146. } else if (cp) {
  2147. is_ipv6 = 0;
  2148. if (cp - ip_as_string > (int)sizeof(buf)-1) {
  2149. log(EVDNS_LOG_DEBUG, "Nameserver does not fit in buffer.");
  2150. return 4;
  2151. }
  2152. memcpy(buf, ip_as_string, cp-ip_as_string);
  2153. buf[cp-ip_as_string] = '\0';
  2154. addr_part = buf;
  2155. port_part = cp+1;
  2156. } else {
  2157. addr_part = ip_as_string;
  2158. port_part = NULL;
  2159. is_ipv6 = 0;
  2160. }
  2161. if (port_part == NULL) {
  2162. port = 53;
  2163. } else {
  2164. port = strtoint(port_part);
  2165. if (port <= 0 || port > 65535) {
  2166. log(EVDNS_LOG_DEBUG, "Nameserver port <%s> out of range",
  2167. port_part);
  2168. return 4;
  2169. }
  2170. }
  2171. /* Tor-only. needs a more general fix. */
  2172. assert(addr_part);
  2173. if (is_ipv6) {
  2174. struct sockaddr_in6 sin6;
  2175. memset(&sin6, 0, sizeof(sin6));
  2176. #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
  2177. sin6.sin6_len = sizeof(sin6);
  2178. #endif
  2179. sin6.sin6_family = AF_INET6;
  2180. sin6.sin6_port = htons(port);
  2181. if (1 != tor_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) {
  2182. log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
  2183. return 4;
  2184. }
  2185. return _evdns_nameserver_add_impl((struct sockaddr*)&sin6,
  2186. sizeof(sin6));
  2187. } else {
  2188. struct sockaddr_in sin;
  2189. memset(&sin, 0, sizeof(sin));
  2190. #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  2191. sin.sin_len = sizeof(sin);
  2192. #endif
  2193. sin.sin_family = AF_INET;
  2194. sin.sin_port = htons(port);
  2195. if (!inet_aton(addr_part, &sin.sin_addr)) {
  2196. log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
  2197. return 4;
  2198. }
  2199. return _evdns_nameserver_add_impl((struct sockaddr*)&sin,
  2200. sizeof(sin));
  2201. }
  2202. }
  2203. int
  2204. evdns_nameserver_sockaddr_add(const struct sockaddr *sa, socklen_t len)
  2205. {
  2206. return _evdns_nameserver_add_impl(sa, len);
  2207. }
  2208. /* insert into the tail of the queue */
  2209. static void
  2210. evdns_request_insert(struct evdns_request *req, struct evdns_request **head) {
  2211. if (!*head) {
  2212. *head = req;
  2213. req->next = req->prev = req;
  2214. return;
  2215. }
  2216. req->prev = (*head)->prev;
  2217. req->prev->next = req;
  2218. req->next = *head;
  2219. (*head)->prev = req;
  2220. }
  2221. static int
  2222. string_num_dots(const char *s) {
  2223. int count = 0;
  2224. while ((s = strchr(s, '.'))) {
  2225. s++;
  2226. count++;
  2227. }
  2228. return count;
  2229. }
  2230. static struct evdns_request *
  2231. request_new(int type, const char *name, int flags,
  2232. evdns_callback_type callback, void *user_ptr) {
  2233. const char issuing_now =
  2234. (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
  2235. const size_t name_len = strlen(name);
  2236. const size_t request_max_len = evdns_request_len(name_len);
  2237. const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
  2238. /* the request data is alloced in a single block with the header */
  2239. struct evdns_request *const req =
  2240. (struct evdns_request *) mm_malloc(sizeof(struct evdns_request) + request_max_len);
  2241. char namebuf[256];
  2242. int rlen;
  2243. (void) flags;
  2244. if (!req) return NULL;
  2245. if (name_len >= sizeof(namebuf)) {
  2246. _mm_free(req);
  2247. return NULL;
  2248. }
  2249. memset(req, 0, sizeof(struct evdns_request));
  2250. if (global_randomize_case) {
  2251. unsigned i;
  2252. char randbits[32];
  2253. strlcpy(namebuf, name, sizeof(namebuf));
  2254. rand_bytes_function(randbits, (name_len+7)/8);
  2255. for (i = 0; i < name_len; ++i) {
  2256. if (ISALPHA(namebuf[i])) {
  2257. if ((randbits[i >> 3] & (1<<(i%7))))
  2258. namebuf[i] = TOLOWER(namebuf[i]);
  2259. else
  2260. namebuf[i] = TOUPPER(namebuf[i]);
  2261. }
  2262. }
  2263. name = namebuf;
  2264. }
  2265. /* request data lives just after the header */
  2266. req->request = ((u8 *) req) + sizeof(struct evdns_request);
  2267. /* denotes that the request data shouldn't be mm_free()ed */
  2268. req->request_appended = 1;
  2269. rlen = evdns_request_data_build(name, name_len, trans_id,
  2270. type, CLASS_INET, req->request, request_max_len);
  2271. if (rlen < 0)
  2272. goto err1;
  2273. req->request_len = rlen;
  2274. req->trans_id = trans_id;
  2275. req->tx_count = 0;
  2276. req->request_type = type;
  2277. req->user_pointer = user_ptr;
  2278. req->user_callback = callback;
  2279. req->ns = issuing_now ? nameserver_pick() : NULL;
  2280. req->next = req->prev = NULL;
  2281. return req;
  2282. err1:
  2283. CLEAR(req);
  2284. _mm_free(req);
  2285. return NULL;
  2286. }
  2287. static void
  2288. request_submit(struct evdns_request *const req) {
  2289. if (req->ns) {
  2290. /* if it has a nameserver assigned then this is going */
  2291. /* straight into the inflight queue */
  2292. evdns_request_insert(req, &req_head);
  2293. global_requests_inflight++;
  2294. evdns_request_transmit(req);
  2295. } else {
  2296. evdns_request_insert(req, &req_waiting_head);
  2297. global_requests_waiting++;
  2298. }
  2299. }
  2300. /* exported function */
  2301. int evdns_resolve_ipv4(const char *name, int flags,
  2302. evdns_callback_type callback, void *ptr) {
  2303. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2304. if (flags & DNS_QUERY_NO_SEARCH) {
  2305. struct evdns_request *const req =
  2306. request_new(TYPE_A, name, flags, callback, ptr);
  2307. if (req == NULL)
  2308. return (1);
  2309. request_submit(req);
  2310. return (0);
  2311. } else {
  2312. return (search_request_new(TYPE_A, name, flags, callback, ptr));
  2313. }
  2314. }
  2315. /* exported function */
  2316. int evdns_resolve_ipv6(const char *name, int flags,
  2317. evdns_callback_type callback, void *ptr) {
  2318. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  2319. if (flags & DNS_QUERY_NO_SEARCH) {
  2320. struct evdns_request *const req =
  2321. request_new(TYPE_AAAA, name, flags, callback, ptr);
  2322. if (req == NULL)
  2323. return (1);
  2324. request_submit(req);
  2325. return (0);
  2326. } else {
  2327. return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
  2328. }
  2329. }
  2330. int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2331. char buf[32];
  2332. struct evdns_request *req;
  2333. u32 a;
  2334. assert(in);
  2335. a = ntohl(in->s_addr);
  2336. snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
  2337. (int)(u8)((a )&0xff),
  2338. (int)(u8)((a>>8 )&0xff),
  2339. (int)(u8)((a>>16)&0xff),
  2340. (int)(u8)((a>>24)&0xff));
  2341. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2342. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  2343. if (!req) return 1;
  2344. request_submit(req);
  2345. return 0;
  2346. }
  2347. int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  2348. /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
  2349. char buf[73];
  2350. char *cp;
  2351. struct evdns_request *req;
  2352. int i;
  2353. assert(in);
  2354. cp = buf;
  2355. for (i=15; i >= 0; --i) {
  2356. u8 byte = in->s6_addr[i];
  2357. *cp++ = "0123456789abcdef"[byte & 0x0f];
  2358. *cp++ = '.';
  2359. *cp++ = "0123456789abcdef"[byte >> 4];
  2360. *cp++ = '.';
  2361. }
  2362. assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
  2363. memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
  2364. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  2365. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  2366. if (!req) return 1;
  2367. request_submit(req);
  2368. return 0;
  2369. }
  2370. /*/////////////////////////////////////////////////////////////////// */
  2371. /* Search support */
  2372. /* */
  2373. /* the libc resolver has support for searching a number of domains */
  2374. /* to find a name. If nothing else then it takes the single domain */
  2375. /* from the gethostname() call. */
  2376. /* */
  2377. /* It can also be configured via the domain and search options in a */
  2378. /* resolv.conf. */
  2379. /* */
  2380. /* The ndots option controls how many dots it takes for the resolver */
  2381. /* to decide that a name is non-local and so try a raw lookup first. */
  2382. struct search_domain {
  2383. size_t len;
  2384. struct search_domain *next;
  2385. /* the text string is appended to this structure */
  2386. };
  2387. struct search_state {
  2388. int refcount;
  2389. int ndots;
  2390. int num_domains;
  2391. struct search_domain *head;
  2392. };
  2393. static struct search_state *global_search_state = NULL;
  2394. static void
  2395. search_state_decref(struct search_state *const state) {
  2396. if (!state) return;
  2397. state->refcount--;
  2398. if (!state->refcount) {
  2399. struct search_domain *next, *dom;
  2400. for (dom = state->head; dom; dom = next) {
  2401. next = dom->next;
  2402. CLEAR(dom);
  2403. _mm_free(dom);
  2404. }
  2405. CLEAR(state);
  2406. _mm_free(state);
  2407. }
  2408. }
  2409. static struct search_state *
  2410. search_state_new(void) {
  2411. struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
  2412. if (!state) return NULL;
  2413. memset(state, 0, sizeof(struct search_state));
  2414. state->refcount = 1;
  2415. state->ndots = 1;
  2416. return state;
  2417. }
  2418. static void
  2419. search_postfix_clear(void) {
  2420. search_state_decref(global_search_state);
  2421. global_search_state = search_state_new();
  2422. }
  2423. /* exported function */
  2424. void
  2425. evdns_search_clear(void) {
  2426. search_postfix_clear();
  2427. }
  2428. static void
  2429. search_postfix_add(const char *domain) {
  2430. size_t domain_len;
  2431. struct search_domain *sdomain;
  2432. while (domain[0] == '.') domain++;
  2433. domain_len = strlen(domain);
  2434. if (!global_search_state) global_search_state = search_state_new();
  2435. if (!global_search_state) return;
  2436. global_search_state->num_domains++;
  2437. sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
  2438. if (!sdomain) return;
  2439. memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
  2440. sdomain->next = global_search_state->head;
  2441. sdomain->len = domain_len;
  2442. global_search_state->head = sdomain;
  2443. }
  2444. /* reverse the order of members in the postfix list. This is needed because, */
  2445. /* when parsing resolv.conf we push elements in the wrong order */
  2446. static void
  2447. search_reverse(void) {
  2448. struct search_domain *cur, *prev = NULL, *next;
  2449. cur = global_search_state->head;
  2450. while (cur) {
  2451. next = cur->next;
  2452. cur->next = prev;
  2453. prev = cur;
  2454. cur = next;
  2455. }
  2456. global_search_state->head = prev;
  2457. }
  2458. /* exported function */
  2459. void
  2460. evdns_search_add(const char *domain) {
  2461. search_postfix_add(domain);
  2462. }
  2463. /* exported function */
  2464. void
  2465. evdns_search_ndots_set(const int ndots) {
  2466. if (!global_search_state) global_search_state = search_state_new();
  2467. if (!global_search_state) return;
  2468. global_search_state->ndots = ndots;
  2469. }
  2470. static void
  2471. search_set_from_hostname(void) {
  2472. char hostname[HOST_NAME_MAX + 1], *domainname;
  2473. search_postfix_clear();
  2474. if (gethostname(hostname, sizeof(hostname))) return;
  2475. domainname = strchr(hostname, '.');
  2476. if (!domainname) return;
  2477. search_postfix_add(domainname);
  2478. }
  2479. /* warning: returns malloced string */
  2480. static char *
  2481. search_make_new(const struct search_state *const state, int n, const char *const base_name) {
  2482. const size_t base_len = strlen(base_name);
  2483. const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
  2484. struct search_domain *dom;
  2485. for (dom = state->head; dom; dom = dom->next) {
  2486. if (!n--) {
  2487. /* this is the postfix we want */
  2488. /* the actual postfix string is kept at the end of the structure */
  2489. const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
  2490. const size_t postfix_len = dom->len;
  2491. char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
  2492. if (!newname) return NULL;
  2493. memcpy(newname, base_name, base_len);
  2494. if (need_to_append_dot) newname[base_len] = '.';
  2495. memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
  2496. newname[base_len + need_to_append_dot + postfix_len] = 0;
  2497. return newname;
  2498. }
  2499. }
  2500. /* we ran off the end of the list and still didn't find the requested string */
  2501. abort();
  2502. return NULL; /* unreachable; stops warnings in some compilers. */
  2503. }
  2504. static int
  2505. search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
  2506. assert(type == TYPE_A || type == TYPE_AAAA);
  2507. if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
  2508. global_search_state &&
  2509. global_search_state->num_domains) {
  2510. /* we have some domains to search */
  2511. struct evdns_request *req;
  2512. if (string_num_dots(name) >= global_search_state->ndots) {
  2513. req = request_new(type, name, flags, user_callback, user_arg);
  2514. if (!req) return 1;
  2515. req->search_index = -1;
  2516. } else {
  2517. char *const new_name = search_make_new(global_search_state, 0, name);
  2518. if (!new_name) return 1;
  2519. req = request_new(type, new_name, flags, user_callback, user_arg);
  2520. _mm_free(new_name);
  2521. if (!req) return 1;
  2522. req->search_index = 0;
  2523. }
  2524. req->search_origname = mm_strdup(name);
  2525. req->search_state = global_search_state;
  2526. req->search_flags = flags;
  2527. global_search_state->refcount++;
  2528. request_submit(req);
  2529. return 0;
  2530. } else {
  2531. struct evdns_request *const req = request_new(type, name, flags, user_callback, user_arg);
  2532. if (!req) return 1;
  2533. request_submit(req);
  2534. return 0;
  2535. }
  2536. }
  2537. /* this is called when a request has failed to find a name. We need to check */
  2538. /* if it is part of a search and, if so, try the next name in the list */
  2539. /* returns: */
  2540. /* 0 another request has been submitted */
  2541. /* 1 no more requests needed */
  2542. static int
  2543. search_try_next(struct evdns_request *const req) {
  2544. if (req->search_state) {
  2545. /* it is part of a search */
  2546. char *new_name;
  2547. struct evdns_request *newreq;
  2548. req->search_index++;
  2549. if (req->search_index >= req->search_state->num_domains) {
  2550. /* no more postfixes to try, however we may need to try */
  2551. /* this name without a postfix */
  2552. if (string_num_dots(req->search_origname) < req->search_state->ndots) {
  2553. /* yep, we need to try it raw */
  2554. struct evdns_request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
  2555. log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
  2556. if (newreq) {
  2557. request_submit(newreq);
  2558. return 0;
  2559. }
  2560. }
  2561. return 1;
  2562. }
  2563. new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
  2564. if (!new_name) return 1;
  2565. log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
  2566. newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
  2567. mm_free(new_name);
  2568. if (!newreq) return 1;
  2569. newreq->search_origname = req->search_origname;
  2570. req->search_origname = NULL;
  2571. newreq->search_state = req->search_state;
  2572. newreq->search_flags = req->search_flags;
  2573. newreq->search_index = req->search_index;
  2574. newreq->search_state->refcount++;
  2575. request_submit(newreq);
  2576. return 0;
  2577. }
  2578. return 1;
  2579. }
  2580. static void
  2581. search_request_finished(struct evdns_request *const req) {
  2582. if (req->search_state) {
  2583. search_state_decref(req->search_state);
  2584. req->search_state = NULL;
  2585. }
  2586. if (req->search_origname) {
  2587. mm_free(req->search_origname);
  2588. req->search_origname = NULL;
  2589. }
  2590. }
  2591. /*/////////////////////////////////////////////////////////////////// */
  2592. /* Parsing resolv.conf files */
  2593. static void
  2594. evdns_resolv_set_defaults(int flags) {
  2595. /* if the file isn't found then we assume a local resolver */
  2596. if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
  2597. if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
  2598. }
  2599. #ifndef HAVE_STRTOK_R
  2600. static char *
  2601. strtok_r(char *s, const char *delim, char **state) {
  2602. (void)state;
  2603. return strtok(s, delim);
  2604. }
  2605. #endif
  2606. /* helper version of atoi which returns -1 on error */
  2607. static int
  2608. strtoint(const char *const str) {
  2609. char *endptr;
  2610. const long r = strtol(str, &endptr, 10);
  2611. if (*endptr || r > INT_MAX) return -1;
  2612. return (int)r;
  2613. }
  2614. /* helper version of atoi that returns -1 on error and clips to bounds. */
  2615. static int
  2616. strtoint_clipped(const char *const str, int min, int max)
  2617. {
  2618. int r = strtoint(str);
  2619. if (r == -1)
  2620. return r;
  2621. else if (r<min)
  2622. return min;
  2623. else if (r>max)
  2624. return max;
  2625. else
  2626. return r;
  2627. }
  2628. /* exported function */
  2629. int
  2630. evdns_set_option(const char *option, const char *val, int flags)
  2631. {
  2632. if (!strncmp(option, "ndots:", 6)) {
  2633. const int ndots = strtoint(val);
  2634. if (ndots == -1) return -1;
  2635. if (!(flags & DNS_OPTION_SEARCH)) return 0;
  2636. log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
  2637. if (!global_search_state) global_search_state = search_state_new();
  2638. if (!global_search_state) return -1;
  2639. global_search_state->ndots = ndots;
  2640. } else if (!strncmp(option, "timeout:", 8)) {
  2641. const int timeout = strtoint(val);
  2642. if (timeout == -1) return -1;
  2643. if (!(flags & DNS_OPTION_MISC)) return 0;
  2644. log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
  2645. global_timeout.tv_sec = timeout;
  2646. } else if (!strncmp(option, "max-timeouts:", 12)) {
  2647. const int maxtimeout = strtoint_clipped(val, 1, 255);
  2648. if (maxtimeout == -1) return -1;
  2649. if (!(flags & DNS_OPTION_MISC)) return 0;
  2650. log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
  2651. maxtimeout);
  2652. global_max_nameserver_timeout = maxtimeout;
  2653. } else if (!strncmp(option, "max-inflight:", 13)) {
  2654. const int maxinflight = strtoint_clipped(val, 1, 65000);
  2655. if (maxinflight == -1) return -1;
  2656. if (!(flags & DNS_OPTION_MISC)) return 0;
  2657. log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
  2658. maxinflight);
  2659. global_max_requests_inflight = maxinflight;
  2660. } else if (!strncmp(option, "attempts:", 9)) {
  2661. int retries = strtoint(val);
  2662. if (retries == -1) return -1;
  2663. if (retries > 255) retries = 255;
  2664. if (!(flags & DNS_OPTION_MISC)) return 0;
  2665. log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
  2666. global_max_retransmits = retries;
  2667. } else if (!strncmp(option, "randomize-case:", 15)) {
  2668. int randcase = strtoint(val);
  2669. if (!(flags & DNS_OPTION_MISC)) return 0;
  2670. log(EVDNS_LOG_DEBUG, "Setting randomize_case to %d", randcase);
  2671. global_randomize_case = randcase;
  2672. }
  2673. return 0;
  2674. }
  2675. static void
  2676. resolv_conf_parse_line(char *const start, int flags) {
  2677. char *strtok_state;
  2678. static const char *const delims = " \t";
  2679. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  2680. char *const first_token = strtok_r(start, delims, &strtok_state);
  2681. if (!first_token) return;
  2682. if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
  2683. const char *const nameserver = NEXT_TOKEN;
  2684. evdns_nameserver_ip_add(nameserver);
  2685. } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
  2686. const char *const domain = NEXT_TOKEN;
  2687. if (domain) {
  2688. search_postfix_clear();
  2689. search_postfix_add(domain);
  2690. }
  2691. } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
  2692. const char *domain;
  2693. search_postfix_clear();
  2694. while ((domain = NEXT_TOKEN)) {
  2695. search_postfix_add(domain);
  2696. }
  2697. search_reverse();
  2698. } else if (!strcmp(first_token, "options")) {
  2699. const char *option;
  2700. while ((option = NEXT_TOKEN)) {
  2701. const char *val = strchr(option, ':');
  2702. evdns_set_option(option, val ? val+1 : "", flags);
  2703. }
  2704. }
  2705. #undef NEXT_TOKEN
  2706. }
  2707. /* exported function */
  2708. /* returns: */
  2709. /* 0 no errors */
  2710. /* 1 failed to open file */
  2711. /* 2 failed to stat file */
  2712. /* 3 file too large */
  2713. /* 4 out of memory */
  2714. /* 5 short read from file */
  2715. int
  2716. evdns_resolv_conf_parse(int flags, const char *const filename) {
  2717. struct stat st;
  2718. int fd, n, r;
  2719. u8 *resolv;
  2720. char *start;
  2721. int err = 0;
  2722. log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
  2723. fd = open(filename, O_RDONLY);
  2724. if (fd < 0) {
  2725. evdns_resolv_set_defaults(flags);
  2726. return 1;
  2727. }
  2728. if (fstat(fd, &st)) { err = 2; goto out1; }
  2729. if (!st.st_size) {
  2730. evdns_resolv_set_defaults(flags);
  2731. err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
  2732. goto out1;
  2733. }
  2734. if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */
  2735. resolv = (u8 *) mm_malloc((size_t)st.st_size + 1);
  2736. if (!resolv) { err = 4; goto out1; }
  2737. n = 0;
  2738. while ((r = (int)read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
  2739. n += r;
  2740. if (n == st.st_size)
  2741. break;
  2742. assert(n < st.st_size);
  2743. }
  2744. if (r < 0) { err = 5; goto out2; }
  2745. resolv[n] = 0; /* we malloced an extra byte; this should be fine. */
  2746. start = (char *) resolv;
  2747. for (;;) {
  2748. char *const newline = strchr(start, '\n');
  2749. if (!newline) {
  2750. resolv_conf_parse_line(start, flags);
  2751. break;
  2752. } else {
  2753. *newline = 0;
  2754. resolv_conf_parse_line(start, flags);
  2755. start = newline + 1;
  2756. }
  2757. }
  2758. if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
  2759. /* no nameservers were configured. */
  2760. evdns_nameserver_ip_add("127.0.0.1");
  2761. err = 6;
  2762. }
  2763. if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
  2764. search_set_from_hostname();
  2765. }
  2766. out2:
  2767. mm_free(resolv);
  2768. out1:
  2769. close(fd);
  2770. return err;
  2771. }
  2772. #ifdef WIN32
  2773. /* Add multiple nameservers from a space-or-comma-separated list. */
  2774. static int
  2775. evdns_nameserver_ip_add_line(const char *ips) {
  2776. const char *addr;
  2777. char *buf;
  2778. int r;
  2779. while (*ips) {
  2780. while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
  2781. ++ips;
  2782. addr = ips;
  2783. while (ISDIGIT(*ips) || *ips == '.' || *ips == ':' || *ips == '[' || *ips == ']')
  2784. ++ips;
  2785. buf = mm_malloc(ips-addr+1);
  2786. if (!buf) return 4;
  2787. memcpy(buf, addr, ips-addr);
  2788. buf[ips-addr] = '\0';
  2789. r = evdns_nameserver_ip_add(buf);
  2790. mm_free(buf);
  2791. if (r) return r;
  2792. }
  2793. return 0;
  2794. }
  2795. typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
  2796. /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
  2797. /* figure out what our nameservers are. */
  2798. static int
  2799. load_nameservers_with_getnetworkparams(void)
  2800. {
  2801. /* Based on MSDN examples and inspection of c-ares code. */
  2802. FIXED_INFO *fixed;
  2803. HMODULE handle = 0;
  2804. ULONG size = sizeof(FIXED_INFO);
  2805. void *buf = NULL;
  2806. int status = 0, r, added_any;
  2807. IP_ADDR_STRING *ns;
  2808. GetNetworkParams_fn_t fn;
  2809. /* XXXX Possibly, we should hardcode the location of this DLL. */
  2810. if (!(handle = LoadLibrary("iphlpapi.dll"))) {
  2811. log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
  2812. /* right now status = 0, doesn't that mean "good" - mikec */
  2813. status = -1;
  2814. goto done;
  2815. }
  2816. if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
  2817. log(EVDNS_LOG_WARN, "Could not get address of function.");
  2818. /* same as above */
  2819. status = -1;
  2820. goto done;
  2821. }
  2822. buf = mm_malloc(size);
  2823. if (!buf) { status = 4; goto done; }
  2824. fixed = buf;
  2825. r = fn(fixed, &size);
  2826. if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
  2827. status = -1;
  2828. goto done;
  2829. }
  2830. if (r != ERROR_SUCCESS) {
  2831. mm_free(buf);
  2832. buf = mm_malloc(size);
  2833. if (!buf) { status = 4; goto done; }
  2834. fixed = buf;
  2835. r = fn(fixed, &size);
  2836. if (r != ERROR_SUCCESS) {
  2837. log(EVDNS_LOG_DEBUG, "fn() failed.");
  2838. status = -1;
  2839. goto done;
  2840. }
  2841. }
  2842. assert(fixed);
  2843. added_any = 0;
  2844. ns = &(fixed->DnsServerList);
  2845. while (ns) {
  2846. r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
  2847. if (r) {
  2848. log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list, "
  2849. "error: %d; status: %d",
  2850. (ns->IpAddress.String),(int)GetLastError(), r);
  2851. status = r;
  2852. } else {
  2853. log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
  2854. added_any++;
  2855. }
  2856. ns = ns->Next;
  2857. }
  2858. if (!added_any) {
  2859. log(EVDNS_LOG_DEBUG, "No nameservers added.");
  2860. if (status == 0)
  2861. status = -1;
  2862. } else {
  2863. status = 0;
  2864. }
  2865. done:
  2866. if (buf)
  2867. mm_free(buf);
  2868. if (handle)
  2869. FreeLibrary(handle);
  2870. return status;
  2871. }
  2872. static int
  2873. config_nameserver_from_reg_key(HKEY key, const char *subkey)
  2874. {
  2875. char *buf;
  2876. DWORD bufsz = 0, type = 0;
  2877. int status = 0;
  2878. if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
  2879. != ERROR_MORE_DATA)
  2880. return -1;
  2881. if (!(buf = mm_malloc(bufsz)))
  2882. return -1;
  2883. if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
  2884. == ERROR_SUCCESS && bufsz > 1) {
  2885. status = evdns_nameserver_ip_add_line(buf);
  2886. }
  2887. mm_free(buf);
  2888. return status;
  2889. }
  2890. #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
  2891. #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
  2892. #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
  2893. static int
  2894. load_nameservers_from_registry(void)
  2895. {
  2896. int found = 0;
  2897. int r;
  2898. #define TRY(k, name) \
  2899. if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
  2900. log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
  2901. found = 1; \
  2902. } else if (!found) { \
  2903. log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
  2904. #k,#name); \
  2905. }
  2906. if (((int)GetVersion()) > 0) { /* NT */
  2907. HKEY nt_key = 0, interfaces_key = 0;
  2908. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
  2909. KEY_READ, &nt_key) != ERROR_SUCCESS) {
  2910. log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
  2911. return -1;
  2912. }
  2913. r = RegOpenKeyEx(nt_key, "Interfaces", 0,
  2914. KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
  2915. &interfaces_key);
  2916. if (r != ERROR_SUCCESS) {
  2917. log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
  2918. return -1;
  2919. }
  2920. TRY(nt_key, "NameServer");
  2921. TRY(nt_key, "DhcpNameServer");
  2922. TRY(interfaces_key, "NameServer");
  2923. TRY(interfaces_key, "DhcpNameServer");
  2924. RegCloseKey(interfaces_key);
  2925. RegCloseKey(nt_key);
  2926. } else {
  2927. HKEY win_key = 0;
  2928. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
  2929. KEY_READ, &win_key) != ERROR_SUCCESS) {
  2930. log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
  2931. return -1;
  2932. }
  2933. TRY(win_key, "NameServer");
  2934. RegCloseKey(win_key);
  2935. }
  2936. if (found == 0) {
  2937. log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
  2938. }
  2939. return found ? 0 : -1;
  2940. #undef TRY
  2941. }
  2942. int
  2943. evdns_config_windows_nameservers(void)
  2944. {
  2945. if (load_nameservers_with_getnetworkparams() == 0)
  2946. return 0;
  2947. return load_nameservers_from_registry();
  2948. }
  2949. #endif
  2950. int
  2951. evdns_init(void)
  2952. {
  2953. int res = 0;
  2954. #ifdef WIN32
  2955. evdns_config_windows_nameservers();
  2956. #else
  2957. res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  2958. #endif
  2959. return (res);
  2960. }
  2961. const char *
  2962. evdns_err_to_string(int err)
  2963. {
  2964. switch (err) {
  2965. case DNS_ERR_NONE: return "no error";
  2966. case DNS_ERR_FORMAT: return "misformatted query";
  2967. case DNS_ERR_SERVERFAILED: return "server failed";
  2968. case DNS_ERR_NOTEXIST: return "name does not exist";
  2969. case DNS_ERR_NOTIMPL: return "query not implemented";
  2970. case DNS_ERR_REFUSED: return "refused";
  2971. case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
  2972. case DNS_ERR_UNKNOWN: return "unknown";
  2973. case DNS_ERR_TIMEOUT: return "request timed out";
  2974. case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
  2975. default: return "[Unknown error code]";
  2976. }
  2977. }
  2978. void
  2979. evdns_shutdown(int fail_requests)
  2980. {
  2981. struct nameserver *server, *server_next;
  2982. struct search_domain *dom, *dom_next;
  2983. while (req_head) {
  2984. if (fail_requests)
  2985. reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
  2986. request_finished(req_head, &req_head);
  2987. }
  2988. while (req_waiting_head) {
  2989. if (fail_requests)
  2990. reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
  2991. request_finished(req_waiting_head, &req_waiting_head);
  2992. }
  2993. global_requests_inflight = global_requests_waiting = 0;
  2994. for (server = server_head; server; server = server_next) {
  2995. server_next = server->next;
  2996. if (server->socket >= 0)
  2997. CLOSE_SOCKET(server->socket);
  2998. (void) event_del(&server->event);
  2999. if (server->state == 0)
  3000. del_timeout_event(server);
  3001. CLEAR(server);
  3002. mm_free(server);
  3003. if (server_next == server_head)
  3004. break;
  3005. }
  3006. server_head = NULL;
  3007. global_good_nameservers = 0;
  3008. if (global_search_state) {
  3009. for (dom = global_search_state->head; dom; dom = dom_next) {
  3010. dom_next = dom->next;
  3011. CLEAR(dom);
  3012. mm_free(dom);
  3013. }
  3014. CLEAR(global_search_state);
  3015. mm_free(global_search_state);
  3016. global_search_state = NULL;
  3017. }
  3018. evdns_log_fn = NULL;
  3019. }
  3020. #ifdef EVDNS_MAIN
  3021. void
  3022. main_callback(int result, char type, int count, int ttl,
  3023. void *addrs, void *orig) {
  3024. char *n = (char*)orig;
  3025. int i;
  3026. for (i = 0; i < count; ++i) {
  3027. if (type == DNS_IPv4_A) {
  3028. printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
  3029. } else if (type == DNS_PTR) {
  3030. printf("%s: %s\n", n, ((char**)addrs)[i]);
  3031. }
  3032. }
  3033. if (!count) {
  3034. printf("%s: No answer (%d)\n", n, result);
  3035. }
  3036. fflush(stdout);
  3037. }
  3038. void
  3039. evdns_server_callback(struct evdns_server_request *req, void *data)
  3040. {
  3041. int i, r;
  3042. (void)data;
  3043. /* dummy; give 192.168.11.11 as an answer for all A questions,
  3044. * give foo.bar.example.com as an answer for all PTR questions. */
  3045. for (i = 0; i < req->nquestions; ++i) {
  3046. u32 ans = htonl(0xc0a80b0bUL);
  3047. if (req->questions[i]->type == EVDNS_TYPE_A &&
  3048. req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
  3049. printf(" -- replying for %s (A)\n", req->questions[i]->name);
  3050. r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
  3051. 1, &ans, 10);
  3052. if (r<0)
  3053. printf("eeep, didn't work.\n");
  3054. } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
  3055. req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
  3056. printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
  3057. r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
  3058. "foo.bar.example.com", 10);
  3059. } else {
  3060. printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
  3061. req->questions[i]->type, req->questions[i]->dns_question_class);
  3062. }
  3063. }
  3064. r = evdns_server_request_respond(req, 0);
  3065. if (r<0)
  3066. printf("eeek, couldn't send reply.\n");
  3067. }
  3068. void
  3069. logfn(int is_warn, const char *msg) {
  3070. (void) is_warn;
  3071. fprintf(stderr, "%s\n", msg);
  3072. }
  3073. int
  3074. main(int c, char **v) {
  3075. int idx;
  3076. int reverse = 0, verbose = 1, servertest = 0;
  3077. if (c<2) {
  3078. fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
  3079. fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
  3080. return 1;
  3081. }
  3082. idx = 1;
  3083. while (idx < c && v[idx][0] == '-') {
  3084. if (!strcmp(v[idx], "-x"))
  3085. reverse = 1;
  3086. else if (!strcmp(v[idx], "-v"))
  3087. verbose = 1;
  3088. else if (!strcmp(v[idx], "-servertest"))
  3089. servertest = 1;
  3090. else
  3091. fprintf(stderr, "Unknown option %s\n", v[idx]);
  3092. ++idx;
  3093. }
  3094. event_init();
  3095. if (verbose)
  3096. evdns_set_log_fn(logfn);
  3097. evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
  3098. if (servertest) {
  3099. int sock;
  3100. struct sockaddr_in my_addr;
  3101. sock = socket(PF_INET, SOCK_DGRAM, 0);
  3102. fcntl(sock, F_SETFL, O_NONBLOCK);
  3103. my_addr.sin_family = AF_INET;
  3104. my_addr.sin_port = htons(10053);
  3105. my_addr.sin_addr.s_addr = INADDR_ANY;
  3106. if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
  3107. perror("bind");
  3108. exit(1);
  3109. }
  3110. evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
  3111. }
  3112. for (; idx < c; ++idx) {
  3113. if (reverse) {
  3114. struct in_addr addr;
  3115. if (!inet_aton(v[idx], &addr)) {
  3116. fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
  3117. continue;
  3118. }
  3119. fprintf(stderr, "resolving %s...\n",v[idx]);
  3120. evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
  3121. } else {
  3122. fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
  3123. evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
  3124. }
  3125. }
  3126. fflush(stdout);
  3127. event_dispatch();
  3128. return 0;
  3129. }
  3130. #endif
  3131. /* Local Variables: */
  3132. /* tab-width: 4 */
  3133. /* c-basic-offset: 4 */
  3134. /* indent-tabs-mode: t */
  3135. /* End: */