eventdns.c 90 KB

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