eventdns.c 78 KB

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