eventdns.c 92 KB

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