eventdns.c 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381
  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. * - Have a way to query for AAAA and A records simultaneously.
  10. * - Improve request API.
  11. * - (Can we suppress cnames? Should we?)
  12. * - Replace all externally visible magic numbers with #defined constants.
  13. * - Write documentation for APIs of all external functions.
  14. */
  15. /* Async DNS Library
  16. * Adam Langley <agl@imperialviolet.org>
  17. * Public Domain code
  18. *
  19. * This software is Public Domain. To view a copy of the public domain dedication,
  20. * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  21. * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  22. *
  23. * I ask and expect, but do not require, that all derivative works contain an
  24. * attribution similar to:
  25. * Parts developed by Adam Langley <agl@imperialviolet.org>
  26. *
  27. * You may wish to replace the word "Parts" with something else depending on
  28. * the amount of original code.
  29. *
  30. * (Derivative works does not include programs which link against, run or include
  31. * the source verbatim in their source distributions)
  32. *
  33. * Version: 0.1b
  34. *
  35. *
  36. * Welcome, gentle reader
  37. *
  38. * Async DNS lookups are really a whole lot harder than they should be,
  39. * mostly stemming from the fact that the libc resolver has never been
  40. * very good at them. Before you use this library you should see if libc
  41. * can do the job for you with the modern async call getaddrinfo_a
  42. * (see http://www.imperialviolet.org/page25.html#e498). Otherwise,
  43. * please continue.
  44. *
  45. * This code is based on libevent and you must call event_init before
  46. * any of the APIs in this file. You must also seed the OpenSSL random
  47. * source if you are using OpenSSL for ids (see below).
  48. *
  49. * This library is designed to be included and shipped with your source
  50. * code. You statically link with it. You should also test for the
  51. * existence of strtok_r and define HAVE_STRTOK_R if you have it.
  52. *
  53. * The DNS protocol requires a good source of id numbers and these
  54. * numbers should be unpredictable for spoofing reasons. There are
  55. * three methods for generating them here and you must define exactly
  56. * one of them. In increasing order of preference:
  57. *
  58. * DNS_USE_GETTIMEOFDAY_FOR_ID:
  59. * Using the bottom 16 bits of the usec result from gettimeofday. This
  60. * is a pretty poor solution but should work anywhere.
  61. * DNS_USE_CPU_CLOCK_FOR_ID:
  62. * Using the bottom 16 bits of the nsec result from the CPU's time
  63. * counter. This is better, but may not work everywhere. Requires
  64. * POSIX realtime support and you'll need to link against -lrt on
  65. * glibc systems at least.
  66. * DNS_USE_OPENSSL_FOR_ID:
  67. * Uses the OpenSSL RAND_bytes call to generate the data. You must
  68. * have seeded the pool before making any calls to this library.
  69. *
  70. * The library keeps track of the state of nameservers and will avoid
  71. * them when they go down. Otherwise it will round robin between them.
  72. *
  73. * Quick start guide:
  74. * #include "eventdns.h"
  75. * void callback(int result, char type, int count, int ttl,
  76. * void *addresses, void *arg);
  77. * evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  78. * evdns_resolve("www.hostname.com", 0, callback, NULL);
  79. *
  80. * When the lookup is complete the callback function is called. The
  81. * first argument will be one of the DNS_ERR_* defines in eventdns.h.
  82. * Hopefully it will be DNS_ERR_NONE, in which case type will be
  83. * DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
  84. * which the data can be cached for (in seconds), addresses will point
  85. * to an array of uint32_t's and arg will be whatever you passed to
  86. * evdns_resolve.
  87. *
  88. * Searching:
  89. *
  90. * In order for this library to be a good replacement for glibc's resolver it
  91. * supports searching. This involves setting a list of default domains, in
  92. * which names will be queried for. The number of dots in the query name
  93. * determines the order in which this list is used.
  94. *
  95. * Searching appears to be a single lookup from the point of view of the API,
  96. * although many DNS queries may be generated from a single call to
  97. * evdns_resolve. Searching can also drastically slow down the resolution
  98. * of names.
  99. *
  100. * To disable searching:
  101. * 1. Never set it up. If you never call evdns_resolv_conf_parse or
  102. * evdns_search_add then no searching will occur.
  103. *
  104. * 2. If you do call evdns_resolv_conf_parse then don't pass
  105. * DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
  106. *
  107. * 3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag.
  108. *
  109. * The order of searches depends on the number of dots in the name. If the
  110. * number is greater than the ndots setting then the names is first tried
  111. * globally. Otherwise each search domain is appended in turn.
  112. *
  113. * The ndots setting can either be set from a resolv.conf, or by calling
  114. * evdns_search_ndots_set.
  115. *
  116. * For example, with ndots set to 1 (the default) and a search domain list of
  117. * ["myhome.net"]:
  118. * Query: www
  119. * Order: www.myhome.net, www.
  120. *
  121. * Query: www.abc
  122. * Order: www.abc., www.abc.myhome.net
  123. *
  124. * API reference:
  125. *
  126. * int evdns_nameserver_add(unsigned long int address)
  127. * Add a nameserver. The address should be an IP address in
  128. * network byte order. The type of address is chosen so that
  129. * it matches in_addr.s_addr.
  130. * Returns non-zero on error.
  131. *
  132. * int evdns_nameserver_ip_add(const char *ip_as_string)
  133. * This wraps the above function by parsing a string as an IP
  134. * address and adds it as a nameserver.
  135. * Returns non-zero on error
  136. *
  137. * int evdns_resolve(const char *name, int flags,
  138. * evdns_callback_type callback,
  139. * void *ptr)
  140. * Resolve a name. The name parameter should be a DNS name.
  141. * The flags parameter should be 0, or DNS_QUERY_NO_SEARCH
  142. * which disables searching for this query. (see defn of
  143. * searching above).
  144. *
  145. * The callback argument is a function which is called when
  146. * this query completes and ptr is an argument which is passed
  147. * to that callback function.
  148. *
  149. * Returns non-zero on error
  150. *
  151. * void evdns_search_clear()
  152. * Clears the list of search domains
  153. *
  154. * void evdns_search_add(const char *domain)
  155. * Add a domain to the list of search domains
  156. *
  157. * void evdns_search_ndots_set(int ndots)
  158. * Set the number of dots which, when found in a name, causes
  159. * the first query to be without any search domain.
  160. *
  161. * int evdns_count_nameservers(void)
  162. * Return the number of configured nameservers (not necessarily the
  163. * number of running nameservers). This is useful for double-checking
  164. * whether our calls to the various nameserver configuration functions
  165. * have been successful.
  166. *
  167. * int evdns_clear_nameservers_and_suspend(void)
  168. * Remove all currently configured nameservers, and suspend all pending
  169. * resolves. Resolves will not necessarily be re-attempted until
  170. * evdns_resume() is called.
  171. *
  172. * int evdns_resume(void)
  173. * Re-attempt resolves left in limbo after an earlier call to
  174. * evdns_clear_nameservers_and_suspend().
  175. *
  176. * int evdns_config_windows_nameservers(void)
  177. * Attempt to configure a set of nameservers based on platform settings on
  178. * a win32 host. Preferentially tries to use GetNetworkParams; if that fails,
  179. * looks in the registry. Returns 0 on success, nonzero on failure.
  180. *
  181. * int evdns_resolv_conf_parse(int flags, const char *filename)
  182. * Parse a resolv.conf like file from the given filename.
  183. *
  184. * See the man page for resolv.conf for the format of this file.
  185. * The flags argument determines what information is parsed from
  186. * this file:
  187. * DNS_OPTION_SEARCH - domain, search and ndots options
  188. * DNS_OPTION_NAMESERVERS - nameserver lines
  189. * DNS_OPTION_MISC - timeout and attempts options
  190. * DNS_OPTIONS_ALL - all of the above
  191. * The following directives are not parsed from the file:
  192. * sortlist, rotate, no-check-names, inet6, debug
  193. *
  194. * Returns non-zero on error:
  195. * 0 no errors
  196. * 1 failed to open file
  197. * 2 failed to stat file
  198. * 3 file too large
  199. * 4 out of memory
  200. * 5 short read from file
  201. *
  202. * Internals:
  203. *
  204. * Requests are kept in two queues. The first is the inflight queue. In
  205. * this queue requests have an allocated transaction id and nameserver.
  206. * They will soon be transmitted if they haven't already been.
  207. *
  208. * The second is the waiting queue. The size of the inflight ring is
  209. * limited and all other requests wait in waiting queue for space. This
  210. * bounds the number of concurrent requests so that we don't flood the
  211. * nameserver. Several algorithms require a full walk of the inflight
  212. * queue and so bounding its size keeps thing going nicely under huge
  213. * (many thousands of requests) loads.
  214. *
  215. * If a nameserver loses too many requests it is considered down and we
  216. * try not to use it. After a while we send a probe to that nameserver
  217. * (a lookup for google.com) and, if it replies, we consider it working
  218. * again. If the nameserver fails a probe we wait longer to try again
  219. * with the next probe.
  220. */
  221. #include "eventdns.h"
  222. #include "eventdns_tor.h"
  223. //#define NDEBUG
  224. #include "../common/torint.h"
  225. #ifndef DNS_USE_CPU_CLOCK_FOR_ID
  226. #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
  227. #ifndef DNS_USE_OPENSSL_FOR_ID
  228. #error Must configure at least one id generation method.
  229. #error Please see the documentation.
  230. #endif
  231. #endif
  232. #endif
  233. // #define _POSIX_C_SOURCE 200507
  234. #define _GNU_SOURCE
  235. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  236. #ifdef DNS_USE_OPENSSL_FOR_ID
  237. #error Multiple id options selected
  238. #endif
  239. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  240. #error Multiple id options selected
  241. #endif
  242. #include <time.h>
  243. #endif
  244. #ifdef DNS_USE_OPENSSL_FOR_ID
  245. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  246. #error Multiple id options selected
  247. #endif
  248. #include <openssl/rand.h>
  249. #endif
  250. #define _FORTIFY_SOURCE 3
  251. #include <string.h>
  252. #include <sys/types.h>
  253. #include <fcntl.h>
  254. #include <sys/time.h>
  255. // #include <stdint.h>
  256. #include <stdlib.h>
  257. #include <string.h>
  258. #include <errno.h>
  259. #include <assert.h>
  260. #include <unistd.h>
  261. #include <limits.h>
  262. #include <sys/stat.h>
  263. #include <ctype.h>
  264. #include <stdio.h>
  265. #include <stdarg.h>
  266. #ifdef WIN32
  267. #include <windows.h>
  268. #include <winsock2.h>
  269. #include <iphlpapi.h>
  270. #else
  271. #include <sys/socket.h>
  272. #include <netinet/in.h>
  273. #include <arpa/inet.h>
  274. #endif
  275. #define EVDNS_LOG_DEBUG 0
  276. #define EVDNS_LOG_WARN 1
  277. #ifndef HOST_NAME_MAX
  278. #define HOST_NAME_MAX 255
  279. #endif
  280. #ifndef NDEBUG
  281. #include <stdio.h>
  282. #endif
  283. #undef MIN
  284. #define MIN(a,b) ((a)<(b)?(a):(b))
  285. #if 0
  286. #ifdef __USE_ISOC99B
  287. // libevent doesn't work without this
  288. typedef uint8_t u_char;
  289. typedef unsigned int uint;
  290. #endif
  291. #endif
  292. #include <event.h>
  293. #define u64 uint64_t
  294. #define u32 uint32_t
  295. #define u16 uint16_t
  296. #define u8 uint8_t
  297. #include "eventdns.h"
  298. #define MAX_ADDRS 4 // maximum number of addresses from a single packet
  299. // which we bother recording
  300. #define TYPE_A 1
  301. #define TYPE_CNAME 5
  302. #define TYPE_PTR 12
  303. #define TYPE_AAAA 28
  304. #define CLASS_INET 1
  305. struct request {
  306. u8 *request; // the dns packet data
  307. unsigned int request_len;
  308. int reissue_count;
  309. int tx_count; // the number of times that this packet has been sent
  310. unsigned int request_type; // TYPE_PTR or TYPE_A
  311. void *user_pointer; // the pointer given to us for this request
  312. evdns_callback_type user_callback;
  313. struct nameserver *ns; // the server which we last sent it
  314. // elements used by the searching code
  315. int search_index;
  316. struct search_state *search_state;
  317. char *search_origname; // needs to be free()ed
  318. int search_flags;
  319. // these objects are kept in a circular list
  320. struct request *next, *prev;
  321. struct event timeout_event;
  322. u16 trans_id; // the transaction id
  323. char request_appended; // true if the request pointer is data which follows this struct
  324. char transmit_me; // needs to be transmitted
  325. };
  326. struct reply {
  327. unsigned int type;
  328. unsigned int have_answer;
  329. union {
  330. struct {
  331. u32 addrcount;
  332. u32 addresses[MAX_ADDRS];
  333. } a;
  334. struct {
  335. char name[HOST_NAME_MAX];
  336. } ptr;
  337. } data;
  338. };
  339. struct nameserver {
  340. int socket; // a connected UDP socket
  341. u32 address;
  342. int failed_times; // number of times which we have given this server a chance
  343. int timedout; // number of times in a row a request has timed out
  344. struct event event;
  345. // these objects are kept in a circular list
  346. struct nameserver *next, *prev;
  347. struct event timeout_event; // used to keep the timeout for
  348. // when we next probe this server.
  349. // Valid if state == 0
  350. char state; // zero if we think that this server is down
  351. char choaked; // true if we have an EAGAIN from this server's socket
  352. char write_waiting; // true if we are waiting for EV_WRITE events
  353. };
  354. static struct request *req_head = NULL, *req_waiting_head = NULL;
  355. static struct nameserver *server_head = NULL;
  356. // The number of good nameservers that we have
  357. static int global_good_nameservers = 0;
  358. // inflight requests are contained in the req_head list
  359. // and are actually going out across the network
  360. static int global_requests_inflight = 0;
  361. // requests which aren't inflight are in the waiting list
  362. // and are counted here
  363. static int global_requests_waiting = 0;
  364. static int global_max_requests_inflight = 64;
  365. static struct timeval global_timeout = {3, 0}; // 3 seconds
  366. static int global_max_reissues = 1; // a reissue occurs when we get some errors from the server
  367. static int global_max_retransmits = 3; // number of times we'll retransmit a request which timed out
  368. // number of timeouts in a row before we consider this server to be down
  369. static int global_max_nameserver_timeout = 3;
  370. // These are the timeout values for nameservers. If we find a nameserver is down
  371. // we try to probe it at intervals as given below. Values are in seconds.
  372. static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
  373. static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
  374. 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"};
  375. static struct nameserver *nameserver_pick(void);
  376. static void evdns_request_insert(struct request *req, struct request **head);
  377. static void nameserver_ready_callback(int fd, short events, void *arg);
  378. static int evdns_transmit(void);
  379. static int evdns_request_transmit(struct request *req);
  380. static void nameserver_send_probe(struct nameserver *const ns);
  381. static void search_request_finished(struct request *const);
  382. static int search_try_next(struct request *const req);
  383. static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
  384. static void evdns_requests_pump_waiting_queue(void);
  385. static u16 transaction_id_pick(void);
  386. static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
  387. static void request_submit(struct request *req);
  388. #ifdef MS_WINDOWS
  389. static int
  390. last_error(int sock)
  391. {
  392. int optval, optvallen=sizeof(optval);
  393. int err = WSAGetLastError();
  394. if (err == WSAEWOULDBLOCK && sock >= 0) {
  395. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
  396. &optvallen))
  397. return err;
  398. if (optval)
  399. return optval;
  400. }
  401. return err;
  402. }
  403. static int
  404. error_is_eagain(int err)
  405. {
  406. return err == EAGAIN || err == WSAEWOULDBLOCK;
  407. }
  408. static int
  409. inet_aton(const char *c, struct in_addr *addr)
  410. {
  411. uint32_t r;
  412. if (strcmp(c, "255.255.255.255") == 0) {
  413. addr->s_addr = 0xffffffffu;
  414. } else {
  415. r = inet_addr(c);
  416. if (r == INADDR_NONE)
  417. return 0;
  418. addr->s_addr = r;
  419. }
  420. return 1;
  421. }
  422. #define CLOSE_SOCKET(x) closesocket(x)
  423. #else
  424. #define last_error(sock) (errno)
  425. #define error_is_eagain(err) ((err) == EAGAIN)
  426. #define CLOSE_SOCKET(x) close(x)
  427. #endif
  428. #define ISSPACE(c) isspace((int)(unsigned char)(c))
  429. #define ISDIGIT(c) isdigit((int)(unsigned char)(c))
  430. #ifndef NDEBUG
  431. static const char *
  432. debug_ntoa(u32 address)
  433. {
  434. static char buf[32];
  435. u32 a = ntohl(address);
  436. sprintf(buf, "%d.%d.%d.%d",
  437. (int)(u8)((a>>24)&0xff),
  438. (int)(u8)((a>>16)&0xff),
  439. (int)(u8)((a>>8 )&0xff),
  440. (int)(u8)((a )&0xff));
  441. return buf;
  442. }
  443. #endif
  444. static evdns_debug_log_fn_type evdns_log_fn = NULL;
  445. void
  446. evdns_set_log_fn(evdns_debug_log_fn_type fn)
  447. {
  448. evdns_log_fn = fn;
  449. }
  450. #ifdef __GNUC__
  451. #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
  452. #else
  453. #define EVDNS_LOG_CHECK
  454. #endif
  455. static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
  456. static void
  457. _evdns_log(int warn, const char *fmt, ...) {
  458. va_list args;
  459. static char buf[512];
  460. if (!evdns_log_fn)
  461. return;
  462. va_start(args,fmt);
  463. #ifdef MS_WINDOWS
  464. _vsnprintf(buf, sizeof(buf), fmt, args);
  465. #else
  466. vsnprintf(buf, sizeof(buf), fmt, args);
  467. #endif
  468. buf[sizeof(buf)-1] = '\0';
  469. evdns_log_fn(warn, buf);
  470. va_end(args);
  471. }
  472. #define log _evdns_log
  473. // This walks the list of inflight requests to find the
  474. // one with a matching transaction id. Returns NULL on
  475. // failure
  476. static struct request *
  477. request_find_from_trans_id(u16 trans_id) {
  478. struct request *req = req_head, *const started_at = req_head;
  479. if (req) {
  480. do {
  481. if (req->trans_id == trans_id) return req;
  482. req = req->next;
  483. } while (req != started_at);
  484. }
  485. return NULL;
  486. }
  487. // a libevent callback function which is called when a nameserver
  488. // has gone down and we want to test if it has came back to life yet
  489. static void
  490. nameserver_prod_callback(int fd, short events, void *arg) {
  491. struct nameserver *const ns = (struct nameserver *) arg;
  492. (void)fd;
  493. (void)events;
  494. nameserver_send_probe(ns);
  495. }
  496. // a libevent callback which is called when a nameserver probe (to see if
  497. // it has come back to life) times out. We increment the count of failed_times
  498. // and wait longer to send the next probe packet.
  499. static void
  500. nameserver_probe_failed(struct nameserver *const ns) {
  501. const struct timeval * timeout;
  502. (void) evtimer_del(&ns->timeout_event);
  503. if (ns->state == 1) {
  504. // This can happen if the nameserver acts in a way which makes us mark
  505. // it as bad and then starts sending good replies.
  506. return;
  507. }
  508. timeout =
  509. &global_nameserver_timeouts[MIN(ns->failed_times,
  510. global_nameserver_timeouts_length - 1)];
  511. ns->failed_times++;
  512. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  513. if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
  514. log(EVDNS_LOG_WARN,
  515. "Error from libevent when adding timer event for %s",
  516. debug_ntoa(ns->address));
  517. // ???? Do more?
  518. }
  519. }
  520. // called when a nameserver has been deemed to have failed. For example, too
  521. // many packets have timed out etc
  522. static void
  523. nameserver_failed(struct nameserver *const ns, const char *msg) {
  524. struct request *req, *started_at;
  525. // if this nameserver has already been marked as failed
  526. // then don't do anything
  527. if (!ns->state) return;
  528. log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
  529. debug_ntoa(ns->address), msg);
  530. global_good_nameservers--;
  531. assert(global_good_nameservers >= 0);
  532. if (global_good_nameservers == 0) {
  533. log(EVDNS_LOG_WARN, "All nameservers have failed");
  534. }
  535. ns->state = 0;
  536. ns->failed_times = 1;
  537. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  538. if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
  539. log(EVDNS_LOG_WARN,
  540. "Error from libevent when adding timer event for %s",
  541. debug_ntoa(ns->address));
  542. // ???? Do more?
  543. }
  544. // walk the list of inflight requests to see if any can be reassigned to
  545. // a different server. Requests in the waiting queue don't have a
  546. // nameserver assigned yet
  547. // if we don't have *any* good nameservers then there's no point
  548. // trying to reassign requests to one
  549. if (!global_good_nameservers) return;
  550. req = req_head;
  551. started_at = req_head;
  552. if (req) {
  553. do {
  554. if (req->tx_count == 0 && req->ns == ns) {
  555. // still waiting to go out, can be moved
  556. // to another server
  557. req->ns = nameserver_pick();
  558. }
  559. req = req->next;
  560. } while (req != started_at);
  561. }
  562. }
  563. static void
  564. nameserver_up(struct nameserver *const ns) {
  565. if (ns->state) return;
  566. log(EVDNS_LOG_WARN, "Nameserver %s is back up",
  567. debug_ntoa(ns->address));
  568. evtimer_del(&ns->timeout_event);
  569. ns->state = 1;
  570. ns->failed_times = 0;
  571. global_good_nameservers++;
  572. }
  573. static void
  574. request_trans_id_set(struct request *const req, const u16 trans_id) {
  575. req->trans_id = trans_id;
  576. *((u16 *) req->request) = htons(trans_id);
  577. }
  578. // Called to remove a request from a list and dealloc it.
  579. // head is a pointer to the head of the list it should be
  580. // removed from or NULL if the request isn't in a list.
  581. static void
  582. request_finished(struct request *const req, struct request **head) {
  583. if (head) {
  584. if (req->next == req) {
  585. // only item in the list
  586. *head = NULL;
  587. } else {
  588. req->next->prev = req->prev;
  589. req->prev->next = req->next;
  590. if (*head == req) *head = req->next;
  591. }
  592. }
  593. log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
  594. (unsigned long) req);
  595. evtimer_del(&req->timeout_event);
  596. search_request_finished(req);
  597. global_requests_inflight--;
  598. if (!req->request_appended) {
  599. // need to free the request data on it's own
  600. free(req->request);
  601. } else {
  602. // the request data is appended onto the header
  603. // so everything gets free()ed when we:
  604. }
  605. free(req);
  606. evdns_requests_pump_waiting_queue();
  607. }
  608. // This is called when a server returns a funny error code.
  609. // We try the request again with another server.
  610. //
  611. // return:
  612. // 0 ok
  613. // 1 failed/reissue is pointless
  614. static int
  615. request_reissue(struct request *req) {
  616. const struct nameserver *const last_ns = req->ns;
  617. // the last nameserver should have been marked as failing
  618. // by the caller of this function, therefore pick will try
  619. // not to return it
  620. req->ns = nameserver_pick();
  621. if (req->ns == last_ns) {
  622. // ... but pick did return it
  623. // not a lot of point in trying again with the
  624. // same server
  625. return 1;
  626. }
  627. req->reissue_count++;
  628. req->tx_count = 0;
  629. req->transmit_me = 1;
  630. return 0;
  631. }
  632. // this function looks for space on the inflight queue and promotes
  633. // requests from the waiting queue if it can.
  634. static void
  635. evdns_requests_pump_waiting_queue(void) {
  636. while (global_requests_inflight < global_max_requests_inflight &&
  637. global_requests_waiting) {
  638. struct request *req;
  639. // move a request from the waiting queue to the inflight queue
  640. assert(req_waiting_head);
  641. if (req_waiting_head->next == req_waiting_head) {
  642. // only one item in the queue
  643. req = req_waiting_head;
  644. req_waiting_head = NULL;
  645. } else {
  646. req = req_waiting_head;
  647. req->next->prev = req->prev;
  648. req->prev->next = req->next;
  649. req_waiting_head = req->next;
  650. }
  651. global_requests_waiting--;
  652. global_requests_inflight++;
  653. req->ns = nameserver_pick();
  654. request_trans_id_set(req, transaction_id_pick());
  655. evdns_request_insert(req, &req_head);
  656. evdns_request_transmit(req);
  657. evdns_transmit();
  658. }
  659. }
  660. static void
  661. reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
  662. switch (req->request_type) {
  663. case TYPE_A:
  664. if (reply)
  665. req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
  666. reply->data.a.addrcount, ttl,
  667. reply->data.a.addresses,
  668. req->user_pointer);
  669. else
  670. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  671. return;
  672. case TYPE_PTR:
  673. if (reply) {
  674. char *name = reply->data.ptr.name;
  675. req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
  676. &name, req->user_pointer);
  677. } else {
  678. req->user_callback(err, 0, 0, 0, NULL,
  679. req->user_pointer);
  680. }
  681. return;
  682. }
  683. assert(0);
  684. }
  685. // this processes a parsed reply packet
  686. static void
  687. reply_handle(struct request *const req,
  688. u16 flags, u32 ttl, struct reply *reply) {
  689. int error;
  690. static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
  691. if (flags & 0x020f || !reply || !reply->have_answer) {
  692. // there was an error
  693. if (flags & 0x0200) {
  694. error = DNS_ERR_TRUNCATED;
  695. } else {
  696. u16 error_code = (flags & 0x000f) - 1;
  697. if (error_code > 4) {
  698. error = DNS_ERR_UNKNOWN;
  699. } else {
  700. error = error_codes[error_code];
  701. }
  702. }
  703. switch(error) {
  704. case DNS_ERR_SERVERFAILED:
  705. case DNS_ERR_NOTIMPL:
  706. case DNS_ERR_REFUSED:
  707. // we regard these errors as marking a bad nameserver
  708. if (req->reissue_count < global_max_reissues) {
  709. char msg[64];
  710. snprintf(msg, sizeof(msg), "Bad response %d (%s)",
  711. error, evdns_err_to_string(error));
  712. nameserver_failed(req->ns, msg);
  713. if (!request_reissue(req)) return;
  714. }
  715. break;
  716. default:
  717. // we got a good reply from the nameserver
  718. nameserver_up(req->ns);
  719. }
  720. if (req->search_state && req->request_type != TYPE_PTR) {
  721. // if we have a list of domains to search in, try the next one
  722. if (!search_try_next(req)) {
  723. // a new request was issued so this request is finished and
  724. // the user callback will be made when that request (or a
  725. // child of it) finishes.
  726. request_finished(req, &req_head);
  727. return;
  728. }
  729. }
  730. // all else failed. Pass the failure up
  731. reply_callback(req, 0, error, NULL);
  732. request_finished(req, &req_head);
  733. } else {
  734. // all ok, tell the user
  735. reply_callback(req, ttl, 0, reply);
  736. nameserver_up(req->ns);
  737. request_finished(req, &req_head);
  738. }
  739. }
  740. static inline int
  741. name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
  742. int name_end = -1;
  743. int j = *idx;
  744. #define GET32(x) do { if (j + 4 > length) return -1; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0);
  745. #define GET16(x) do { if (j + 2 > length) return -1; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0);
  746. #define GET8(x) do { if (j >= length) return -1; x = packet[j++]; } while(0);
  747. char *cp = name_out;
  748. const char *const end = name_out + name_out_len;
  749. // Normally, names are a series of length prefixed strings terminated
  750. // with a length of 0 (the lengths are u8's < 63).
  751. // However, the length can start with a pair of 1 bits and that
  752. // means that the next 14 bits are a pointer within the current
  753. // packet.
  754. for(;;) {
  755. u8 label_len;
  756. if (j >= length) return -1;
  757. GET8(label_len);
  758. if (!label_len) break;
  759. if (label_len & 0xc0) {
  760. u8 ptr_low;
  761. GET8(ptr_low);
  762. if (name_end < 0) name_end = j;
  763. j = (((int)label_len & 0x3f) << 8) + ptr_low;
  764. if (j < 0 || j >= length) return -1;
  765. continue;
  766. }
  767. if (label_len > 63) return -1;
  768. if (cp != name_out) {
  769. if (cp + 1 >= end) return -1;
  770. *cp++ = '.';
  771. }
  772. if (cp + label_len >= end) return -1;
  773. memcpy(cp, packet + j, label_len);
  774. cp += label_len;
  775. j += label_len;
  776. }
  777. if (cp >= end) return -1;
  778. *cp = '\0';
  779. if (name_end < 0)
  780. *idx = j;
  781. else
  782. *idx = name_end;
  783. return 0;
  784. }
  785. // parses a raw packet from the wire
  786. static int
  787. reply_parse(u8 *packet, int length) {
  788. int j = 0; // index into packet
  789. u16 _t; // used by the macros
  790. u32 _t32; // used by the macros
  791. char tmp_name[256]; // used by the macros
  792. u16 trans_id, flags, questions, answers, authority, additional, datalength;
  793. u32 ttl, ttl_r = 0xffffffff;
  794. struct reply reply;
  795. struct request *req;
  796. unsigned int i;
  797. GET16(trans_id);
  798. GET16(flags);
  799. GET16(questions);
  800. GET16(answers);
  801. GET16(authority);
  802. GET16(additional);
  803. req = request_find_from_trans_id(trans_id);
  804. if (!req) return -1;
  805. // XXXX should the other return points also call reply_handle? -NM
  806. // log("reqparse: trans was %d\n", (int)trans_id);
  807. memset(&reply, 0, sizeof(reply));
  808. if (!(flags & 0x8000)) return -1; // must be an answer
  809. if (flags & 0x020f) {
  810. // there was an error
  811. reply_handle(req, flags, 0, NULL);
  812. return -1;
  813. }
  814. // if (!answers) return; // must have an answer of some form
  815. // This macro skips a name in the DNS reply.
  816. #define SKIP_NAME \
  817. do { tmp_name[0] = '\0'; \
  818. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
  819. return -1; \
  820. } while(0);
  821. reply.type = req->request_type;
  822. // skip over each question in the reply
  823. for (i = 0; i < questions; ++i) {
  824. // the question looks like
  825. // <label:name><u16:type><u16:class>
  826. SKIP_NAME;
  827. j += 4;
  828. if (j >= length) return -1;
  829. }
  830. // now we have the answer section which looks like
  831. // <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
  832. for (i = 0; i < answers; ++i) {
  833. u16 type, class;
  834. // XXX I'd be more comfortable if we actually checked the name
  835. // here. -NM
  836. SKIP_NAME;
  837. GET16(type);
  838. GET16(class);
  839. GET32(ttl);
  840. GET16(datalength);
  841. // log("@%d, Name %s, type %d, class %d, j=%d", pre, tmp_name, (int)type, (int)class, j);
  842. if (type == TYPE_A && class == CLASS_INET) {
  843. int addrcount, addrtocopy;
  844. if (req->request_type != TYPE_A) {
  845. j += datalength; continue;
  846. }
  847. // XXXX do something sane with malformed A answers.
  848. addrcount = datalength >> 2; // each IP address is 4 bytes
  849. addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
  850. ttl_r = MIN(ttl_r, ttl);
  851. // we only bother with the first four addresses.
  852. if (j + 4*addrtocopy > length) return -1;
  853. memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
  854. packet + j, 4*addrtocopy);
  855. j += 4*addrtocopy;
  856. reply.data.a.addrcount += addrtocopy;
  857. reply.have_answer = 1;
  858. if (reply.data.a.addrcount == MAX_ADDRS) break;
  859. } else if (type == TYPE_PTR && class == CLASS_INET) {
  860. if (req->request_type != TYPE_PTR) {
  861. j += datalength; continue;
  862. }
  863. if (name_parse(packet, length, &j, reply.data.ptr.name,
  864. sizeof(reply.data.ptr.name))<0)
  865. return -1;
  866. reply.have_answer = 1;
  867. break;
  868. } else if (type == TYPE_AAAA && class == CLASS_INET) {
  869. if (req->request_type != TYPE_AAAA) {
  870. j += datalength; continue;
  871. }
  872. // XXXX Implement me. -NM
  873. j += datalength;
  874. } else {
  875. // skip over any other type of resource
  876. j += datalength;
  877. }
  878. }
  879. reply_handle(req, flags, ttl_r, &reply);
  880. return 0;
  881. #undef SKIP_NAME
  882. #undef GET32
  883. #undef GET16
  884. #undef GET8
  885. }
  886. // Try to choose a strong transaction id which isn't already in flight
  887. static u16
  888. transaction_id_pick(void) {
  889. for (;;) {
  890. const struct request *req = req_head, *started_at;
  891. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  892. struct timespec ts;
  893. const u16 trans_id = ts.tv_nsec & 0xffff;
  894. if (clock_gettime(CLOCK_MONOTONIC, &ts))
  895. abort();
  896. #endif
  897. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  898. struct timeval tv;
  899. const u16 trans_id = tv.tv_usec & 0xffff;
  900. gettimeofday(&tv, NULL);
  901. #endif
  902. #ifdef DNS_USE_OPENSSL_FOR_ID
  903. u16 trans_id;
  904. if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
  905. /* // in the case that the RAND call fails we back
  906. // down to using gettimeofday.
  907. struct timeval tv;
  908. gettimeofday(&tv, NULL);
  909. trans_id = tv.tv_usec & 0xffff; */
  910. abort();
  911. }
  912. #endif
  913. if (trans_id == 0xffff) continue;
  914. // now check to see if that id is already inflight
  915. req = started_at = req_head;
  916. if (req) {
  917. do {
  918. if (req->trans_id == trans_id) break;
  919. req = req->next;
  920. } while (req != started_at);
  921. }
  922. // we didn't find it, so this is a good id
  923. if (req == started_at) return trans_id;
  924. }
  925. }
  926. // choose a namesever to use. This function will try to ignore
  927. // nameservers which we think are down and load balance across the rest
  928. // by updating the server_head global each time.
  929. static struct nameserver *
  930. nameserver_pick(void) {
  931. struct nameserver *started_at = server_head, *picked;
  932. if (!server_head) return NULL;
  933. // if we don't have any good nameservers then there's no
  934. // point in trying to find one.
  935. if (!global_good_nameservers) {
  936. server_head = server_head->next;
  937. return server_head;
  938. }
  939. // remember that nameservers are in a circular list
  940. for (;;) {
  941. if (server_head->state) {
  942. // we think this server is currently good
  943. picked = server_head;
  944. server_head = server_head->next;
  945. return picked;
  946. }
  947. server_head = server_head->next;
  948. if (server_head == started_at) {
  949. // all the nameservers seem to be down
  950. // so we just return this one and hope for the
  951. // best
  952. assert(global_good_nameservers == 0);
  953. picked = server_head;
  954. server_head = server_head->next;
  955. return picked;
  956. }
  957. }
  958. }
  959. // this is called when a namesever socket is ready for reading
  960. static void
  961. nameserver_read(struct nameserver *ns) {
  962. u8 packet[1500];
  963. for (;;) {
  964. const int r = recv(ns->socket, packet, sizeof(packet), 0);
  965. if (r < 0) {
  966. int err = last_error(ns->socket);
  967. if (error_is_eagain(err)) return;
  968. nameserver_failed(ns, strerror(err));
  969. return;
  970. }
  971. reply_parse(packet, r);
  972. }
  973. }
  974. // set if we are waiting for the ability to write to this server.
  975. // if waiting is true then we ask libevent for EV_WRITE events, otherwise
  976. // we stop these events.
  977. static void
  978. nameserver_write_waiting(struct nameserver *ns, char waiting) {
  979. if (ns->write_waiting == waiting) return;
  980. ns->write_waiting = waiting;
  981. (void) event_del(&ns->event);
  982. event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
  983. nameserver_ready_callback, ns);
  984. if (event_add(&ns->event, NULL) < 0) {
  985. log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
  986. debug_ntoa(ns->address));
  987. // ???? Do more?
  988. }
  989. }
  990. // a callback function. Called by libevent when the kernel says that
  991. // a nameserver socket is ready for writing or reading
  992. static void
  993. nameserver_ready_callback(int fd, short events, void *arg) {
  994. struct nameserver *ns = (struct nameserver *) arg;
  995. (void)fd;
  996. if (events & EV_WRITE) {
  997. ns->choaked = 0;
  998. if (!evdns_transmit()) {
  999. nameserver_write_waiting(ns, 0);
  1000. }
  1001. }
  1002. if (events & EV_READ) {
  1003. nameserver_read(ns);
  1004. }
  1005. }
  1006. // Converts a string to a length-prefixed set of DNS labels.
  1007. // @buf must be strlen(name)+2 or longer. name and buf must
  1008. // not overlap. name_len should be the length of name
  1009. //
  1010. // Input: abc.def
  1011. // Output: <3>abc<3>def<0>
  1012. //
  1013. // Returns the length of the data. negative on error
  1014. // -1 label was > 63 bytes
  1015. // -2 name was > 255 bytes
  1016. static int
  1017. dnsname_to_labels(u8 *const buf, const char *name, const int name_len) {
  1018. const char *end = name + name_len;
  1019. int j = 0; // current offset into buf
  1020. if (name_len > 255) return -2;
  1021. for (;;) {
  1022. const char *const start = name;
  1023. name = strchr(name, '.');
  1024. if (!name) {
  1025. const unsigned int label_len = end - start;
  1026. if (label_len > 63) return -1;
  1027. buf[j++] = label_len;
  1028. memcpy(buf + j, start, end - start);
  1029. j += end - start;
  1030. break;
  1031. } else {
  1032. // append length of the label.
  1033. const unsigned int label_len = name - start;
  1034. if (label_len > 63) return -1;
  1035. buf[j++] = label_len;
  1036. memcpy(buf + j, start, name - start);
  1037. j += name - start;
  1038. // hop over the '.'
  1039. name++;
  1040. }
  1041. }
  1042. // the labels must be terminated by a 0.
  1043. // It's possible that the name ended in a .
  1044. // in which case the zero is already there
  1045. if (!j || buf[j-1]) buf[j++] = 0;
  1046. return j;
  1047. }
  1048. // Finds the length of a dns request for a DNS name of the given
  1049. // length. The actual request may be smaller than the value returned
  1050. // here
  1051. static int
  1052. evdns_request_len(const int name_len) {
  1053. return 96 + // length of the DNS standard header
  1054. name_len + 2 +
  1055. 4; // space for the resource type
  1056. }
  1057. // build a dns request packet into buf. buf should be at least as long
  1058. // as evdns_request_len told you it should be.
  1059. //
  1060. // Returns the amount of space used. Negative on error.
  1061. static int
  1062. evdns_request_data_build(const char *const name, const int name_len, const u16 trans_id,
  1063. const u16 type, const u16 class,
  1064. u8 *const buf, size_t buf_len) {
  1065. off_t j = 0; // current offset into buf
  1066. u16 _t; // used by the macros
  1067. u8 *labels;
  1068. int labels_len;
  1069. #define APPEND16(x) do { \
  1070. if (j + 2 > buf_len) \
  1071. return (-1); \
  1072. _t = htons(x); \
  1073. memcpy(buf + j, &_t, 2); \
  1074. j += 2; \
  1075. } while (0)
  1076. APPEND16(trans_id);
  1077. APPEND16(0x0100); // standard query, recusion needed
  1078. APPEND16(1); // one question
  1079. APPEND16(0); // no answers
  1080. APPEND16(0); // no authority
  1081. APPEND16(0); // no additional
  1082. labels = (u8 *) malloc(name_len + 2);
  1083. if (labels == NULL)
  1084. return -1;
  1085. labels_len = dnsname_to_labels(labels, name, name_len);
  1086. if (labels_len < 0) {
  1087. free(labels);
  1088. return labels_len;
  1089. }
  1090. if ((size_t)(j + labels_len) > buf_len) {
  1091. free(labels);
  1092. return (-1);
  1093. }
  1094. memcpy(buf + j, labels, labels_len);
  1095. j += labels_len;
  1096. free(labels);
  1097. APPEND16(type);
  1098. APPEND16(class);
  1099. #undef APPEND16
  1100. return j;
  1101. }
  1102. // this is a libevent callback function which is called when a request
  1103. // has timed out.
  1104. static void
  1105. evdns_request_timeout_callback(int fd, short events, void *arg) {
  1106. struct request *const req = (struct request *) arg;
  1107. (void) fd;
  1108. (void) events;
  1109. log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
  1110. req->ns->timedout++;
  1111. if (req->ns->timedout > global_max_nameserver_timeout) {
  1112. nameserver_failed(req->ns, "request timed out.");
  1113. }
  1114. (void) evtimer_del(&req->timeout_event);
  1115. if (req->tx_count >= global_max_retransmits) {
  1116. // this request has failed
  1117. reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
  1118. request_finished(req, &req_head);
  1119. } else {
  1120. // retransmit it
  1121. evdns_request_transmit(req);
  1122. }
  1123. }
  1124. // try to send a request to a given server.
  1125. //
  1126. // return:
  1127. // 0 ok
  1128. // 1 temporary failure
  1129. // 2 other failure
  1130. static int
  1131. evdns_request_transmit_to(struct request *req, struct nameserver *server) {
  1132. const int r = send(server->socket, req->request, req->request_len, 0);
  1133. if (r < 0) {
  1134. int err = last_error(server->socket);
  1135. if (error_is_eagain(err)) return 1;
  1136. nameserver_failed(req->ns, strerror(err));
  1137. return 2;
  1138. } else if (r != (int)req->request_len) {
  1139. return 1; // short write
  1140. } else {
  1141. return 0;
  1142. }
  1143. }
  1144. // try to send a request, updating the fields of the request
  1145. // as needed
  1146. //
  1147. // return:
  1148. // 0 ok
  1149. // 1 failed
  1150. static int
  1151. evdns_request_transmit(struct request *req) {
  1152. int retcode = 0, r;
  1153. // if we fail to send this packet then this flag marks it
  1154. // for evdns_transmit
  1155. req->transmit_me = 1;
  1156. if (req->trans_id == 0xffff) abort();
  1157. if (req->ns->choaked) {
  1158. // don't bother trying to write to a socket
  1159. // which we have had EAGAIN from
  1160. return 1;
  1161. }
  1162. r = evdns_request_transmit_to(req, req->ns);
  1163. switch (r) {
  1164. case 1:
  1165. // temp failure
  1166. req->ns->choaked = 1;
  1167. nameserver_write_waiting(req->ns, 1);
  1168. return 1;
  1169. case 2:
  1170. // failed in some other way
  1171. retcode = 1;
  1172. // fall through
  1173. default:
  1174. // all ok
  1175. log(EVDNS_LOG_DEBUG,
  1176. "Setting timeout for request %lx", (unsigned long) req);
  1177. evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
  1178. if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
  1179. log(EVDNS_LOG_WARN,
  1180. "Error from libevent when adding timer for "
  1181. "request %lx", (unsigned long) req);
  1182. // ???? Do more?
  1183. }
  1184. req->tx_count++;
  1185. req->transmit_me = 0;
  1186. return retcode;
  1187. }
  1188. }
  1189. static void
  1190. nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
  1191. struct nameserver *const ns = (struct nameserver *) arg;
  1192. (void) type;
  1193. (void) count;
  1194. (void) ttl;
  1195. (void) addresses;
  1196. if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
  1197. // this is a good reply
  1198. nameserver_up(ns);
  1199. } else nameserver_probe_failed(ns);
  1200. }
  1201. static void
  1202. nameserver_send_probe(struct nameserver *const ns) {
  1203. struct request *req;
  1204. // here we need to send a probe to a given nameserver
  1205. // in the hope that it is up now.
  1206. log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
  1207. req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
  1208. if (!req) return;
  1209. // we force this into the inflight queue no matter what
  1210. request_trans_id_set(req, transaction_id_pick());
  1211. req->ns = ns;
  1212. request_submit(req);
  1213. }
  1214. // returns:
  1215. // 0 didn't try to transmit anything
  1216. // 1 tried to transmit something
  1217. static int
  1218. evdns_transmit(void) {
  1219. char did_try_to_transmit = 0;
  1220. if (req_head) {
  1221. struct request *const started_at = req_head, *req = req_head;
  1222. // first transmit all the requests which are currently waiting
  1223. do {
  1224. if (req->transmit_me) {
  1225. did_try_to_transmit = 1;
  1226. evdns_request_transmit(req);
  1227. }
  1228. req = req->next;
  1229. } while (req != started_at);
  1230. }
  1231. return did_try_to_transmit;
  1232. }
  1233. // exported function
  1234. int
  1235. evdns_count_nameservers(void) {
  1236. const struct nameserver *server = server_head;
  1237. int n = 0;
  1238. if (!server)
  1239. return 0;
  1240. do {
  1241. ++n;
  1242. server = server->next;
  1243. } while (server != server_head);
  1244. return n;
  1245. }
  1246. // exported function
  1247. int
  1248. evdns_clear_nameservers_and_suspend(void) {
  1249. struct nameserver *server = server_head, *started_at = server_head;
  1250. struct request *req = req_head, *req_started_at = req_head;
  1251. if (!server)
  1252. return 0;
  1253. while (1) {
  1254. struct nameserver *next = server->next;
  1255. (void) event_del(&server->event);
  1256. (void) evtimer_del(&server->timeout_event);
  1257. if (server->socket >= 0)
  1258. CLOSE_SOCKET(server->socket);
  1259. free(server);
  1260. if (next == started_at)
  1261. break;
  1262. server = next;
  1263. }
  1264. server_head = NULL;
  1265. global_good_nameservers = 0;
  1266. while (req) {
  1267. struct request *next = req->next;
  1268. req->tx_count = req->reissue_count = 0;
  1269. req->ns = NULL;
  1270. // ???? What to do about searches?
  1271. (void) evtimer_del(&req->timeout_event);
  1272. req->trans_id = 0;
  1273. req->transmit_me = 0;
  1274. global_requests_waiting++;
  1275. evdns_request_insert(req, &req_waiting_head);
  1276. /* We want to insert these suspended elements at the front of
  1277. * the waiting queue, since they were pending before any of
  1278. * the waiting entries were added. This is a circular list,
  1279. * so we can just shift the start back by one.*/
  1280. req_waiting_head = req_waiting_head->prev;
  1281. if (next == req_started_at)
  1282. break;
  1283. req = next;
  1284. }
  1285. req_head = NULL;
  1286. global_requests_inflight = 0;
  1287. return 0;
  1288. }
  1289. // exported function
  1290. int
  1291. evdns_resume(void) {
  1292. evdns_requests_pump_waiting_queue();
  1293. return 0;
  1294. }
  1295. // exported function
  1296. int
  1297. evdns_nameserver_add(unsigned long int address) {
  1298. // first check to see if we already have this nameserver
  1299. const struct nameserver *server = server_head, *const started_at = server_head;
  1300. struct nameserver *ns;
  1301. struct sockaddr_in sin;
  1302. int err = 0;
  1303. if (server) {
  1304. do {
  1305. if (server->address == address) return 3;
  1306. server = server->next;
  1307. } while (server != started_at);
  1308. }
  1309. ns = (struct nameserver *) malloc(sizeof(struct nameserver));
  1310. if (!ns) return -1;
  1311. memset(ns, 0, sizeof(struct nameserver));
  1312. ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
  1313. if (ns->socket < 0) { err = 1; goto out1; }
  1314. #ifdef MS_WINDOWS
  1315. {
  1316. u_long nonblocking = 1;
  1317. ioctlsocket(ns->socket, FIONBIO, &nonblocking);
  1318. }
  1319. #else
  1320. fcntl(ns->socket, F_SETFL, O_NONBLOCK);
  1321. #endif
  1322. sin.sin_addr.s_addr = address;
  1323. sin.sin_port = htons(53);
  1324. sin.sin_family = AF_INET;
  1325. if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  1326. err = 2;
  1327. goto out2;
  1328. }
  1329. ns->address = address;
  1330. ns->state = 1;
  1331. event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
  1332. if (event_add(&ns->event, NULL) < 0) {
  1333. err = 2;
  1334. goto out2;
  1335. }
  1336. log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
  1337. // insert this nameserver into the list of them
  1338. if (!server_head) {
  1339. ns->next = ns->prev = ns;
  1340. server_head = ns;
  1341. } else {
  1342. ns->next = server_head->next;
  1343. ns->prev = server_head;
  1344. server_head->next = ns;
  1345. if (server_head->prev == server_head) {
  1346. server_head->prev = ns;
  1347. }
  1348. }
  1349. global_good_nameservers++;
  1350. return 0;
  1351. out2:
  1352. CLOSE_SOCKET(ns->socket);
  1353. out1:
  1354. free(ns);
  1355. log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
  1356. debug_ntoa(address), err);
  1357. return err;
  1358. }
  1359. // exported function
  1360. int
  1361. evdns_nameserver_ip_add(const char *ip_as_string) {
  1362. struct in_addr ina;
  1363. if (!inet_aton(ip_as_string, &ina)) return 4;
  1364. return evdns_nameserver_add(ina.s_addr);
  1365. }
  1366. // insert into the tail of the queue
  1367. static void
  1368. evdns_request_insert(struct request *req, struct request **head) {
  1369. if (!*head) {
  1370. *head = req;
  1371. req->next = req->prev = req;
  1372. return;
  1373. }
  1374. req->prev = (*head)->prev;
  1375. req->prev->next = req;
  1376. req->next = *head;
  1377. (*head)->prev = req;
  1378. }
  1379. static int
  1380. string_num_dots(const char *s) {
  1381. int count = 0;
  1382. while ((s = strchr(s, '.'))) {
  1383. s++;
  1384. count++;
  1385. }
  1386. return count;
  1387. }
  1388. static struct request *
  1389. request_new(int type, const char *name, int flags, evdns_callback_type callback, void *user_ptr) {
  1390. const char issuing_now = (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
  1391. const int name_len = strlen(name);
  1392. const int request_max_len = evdns_request_len(name_len);
  1393. const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
  1394. // the request data is alloced in a single block with the header
  1395. struct request *const req = (struct request *) malloc(sizeof(struct request) + request_max_len);
  1396. int rlen;
  1397. (void) flags;
  1398. if (!req) return NULL;
  1399. memset(req, 0, sizeof(struct request));
  1400. // request data lives just after the header
  1401. req->request = ((u8 *) req) + sizeof(struct request);
  1402. // denotes that the request data shouldn't be free()ed
  1403. req->request_appended = 1;
  1404. rlen = evdns_request_data_build(name, name_len, trans_id,
  1405. type, CLASS_INET, req->request, request_max_len);
  1406. if (rlen < 0)
  1407. goto err1;
  1408. req->request_len = rlen;
  1409. req->trans_id = trans_id;
  1410. req->tx_count = 0;
  1411. req->request_type = type;
  1412. req->user_pointer = user_ptr;
  1413. req->user_callback = callback;
  1414. req->ns = issuing_now ? nameserver_pick() : NULL;
  1415. req->next = req->prev = NULL;
  1416. return req;
  1417. err1:
  1418. free(req);
  1419. return NULL;
  1420. }
  1421. static void
  1422. request_submit(struct request *const req) {
  1423. if (req->ns) {
  1424. // if it has a nameserver assigned then this is going
  1425. // straight into the inflight queue
  1426. evdns_request_insert(req, &req_head);
  1427. global_requests_inflight++;
  1428. evdns_request_transmit(req);
  1429. } else {
  1430. evdns_request_insert(req, &req_waiting_head);
  1431. global_requests_waiting++;
  1432. }
  1433. }
  1434. // exported function
  1435. int evdns_resolve_ipv4(const char *name, int flags,
  1436. evdns_callback_type callback, void *ptr) {
  1437. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  1438. if (flags & DNS_QUERY_NO_SEARCH) {
  1439. struct request *const req =
  1440. request_new(TYPE_A, name, flags, callback, ptr);
  1441. if (req == NULL)
  1442. return 1;
  1443. request_submit(req);
  1444. return 0;
  1445. } else {
  1446. return search_request_new(TYPE_A, name, flags, callback, ptr);
  1447. }
  1448. }
  1449. int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  1450. char buf[32];
  1451. struct request *req;
  1452. u32 a;
  1453. assert(in);
  1454. a = ntohl(in->s_addr);
  1455. sprintf(buf, "%d.%d.%d.%d.in-addr.arpa",
  1456. (int)(u8)((a )&0xff),
  1457. (int)(u8)((a>>8 )&0xff),
  1458. (int)(u8)((a>>16)&0xff),
  1459. (int)(u8)((a>>24)&0xff));
  1460. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  1461. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  1462. if (!req) return 1;
  1463. request_submit(req);
  1464. return 0;
  1465. }
  1466. /////////////////////////////////////////////////////////////////////
  1467. // Search support
  1468. //
  1469. // the libc resolver has support for searching a number of domains
  1470. // to find a name. If nothing else then it takes the single domain
  1471. // from the gethostname() call.
  1472. //
  1473. // It can also be configured via the domain and search options in a
  1474. // resolv.conf.
  1475. //
  1476. // The ndots option controls how many dots it takes for the resolver
  1477. // to decide that a name is non-local and so try a raw lookup first.
  1478. struct search_domain {
  1479. int len;
  1480. struct search_domain *next;
  1481. // the text string is appended to this structure
  1482. };
  1483. struct search_state {
  1484. int refcount;
  1485. int ndots;
  1486. int num_domains;
  1487. struct search_domain *head;
  1488. };
  1489. static struct search_state *global_search_state = NULL;
  1490. static void
  1491. search_state_decref(struct search_state *const state) {
  1492. if (!state) return;
  1493. state->refcount--;
  1494. if (!state->refcount) {
  1495. struct search_domain *next, *dom;
  1496. for (dom = state->head; dom; dom = next) {
  1497. next = dom->next;
  1498. free(dom);
  1499. }
  1500. free(state);
  1501. }
  1502. }
  1503. static struct search_state *
  1504. search_state_new(void) {
  1505. struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
  1506. if (!state) return NULL;
  1507. memset(state, 0, sizeof(struct search_state));
  1508. state->refcount = 1;
  1509. state->ndots = 1;
  1510. return state;
  1511. }
  1512. static void
  1513. search_postfix_clear(void) {
  1514. search_state_decref(global_search_state);
  1515. global_search_state = search_state_new();
  1516. }
  1517. // exported function
  1518. void
  1519. evdns_search_clear(void) {
  1520. search_postfix_clear();
  1521. }
  1522. static void
  1523. search_postfix_add(const char *domain) {
  1524. int domain_len;
  1525. struct search_domain *sdomain;
  1526. while (domain[0] == '.') domain++;
  1527. domain_len = strlen(domain);
  1528. if (!global_search_state) global_search_state = search_state_new();
  1529. if (!global_search_state) return;
  1530. global_search_state->num_domains++;
  1531. sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
  1532. if (!sdomain) return;
  1533. memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
  1534. sdomain->next = global_search_state->head;
  1535. sdomain->len = domain_len;
  1536. global_search_state->head = sdomain;
  1537. }
  1538. // reverse the order of members in the postfix list. This is needed because,
  1539. // when parsing resolv.conf we push elements in the wrong order
  1540. static void
  1541. search_reverse(void) {
  1542. struct search_domain *cur, *prev = NULL, *next;
  1543. cur = global_search_state->head;
  1544. while (cur) {
  1545. next = cur->next;
  1546. cur->next = prev;
  1547. prev = cur;
  1548. cur = next;
  1549. }
  1550. global_search_state->head = prev;
  1551. }
  1552. // exported function
  1553. void
  1554. evdns_search_add(const char *domain) {
  1555. search_postfix_add(domain);
  1556. }
  1557. // exported function
  1558. void
  1559. evdns_search_ndots_set(const int ndots) {
  1560. if (!global_search_state) global_search_state = search_state_new();
  1561. if (!global_search_state) return;
  1562. global_search_state->ndots = ndots;
  1563. }
  1564. static void
  1565. search_set_from_hostname(void) {
  1566. char hostname[HOST_NAME_MAX + 1], *domainname;
  1567. search_postfix_clear();
  1568. if (gethostname(hostname, sizeof(hostname))) return;
  1569. domainname = strchr(hostname, '.');
  1570. if (!domainname) return;
  1571. search_postfix_add(domainname);
  1572. }
  1573. // warning: returns malloced string
  1574. static char *
  1575. search_make_new(const struct search_state *const state, int n, const char *const base_name) {
  1576. const int base_len = strlen(base_name);
  1577. const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
  1578. struct search_domain *dom;
  1579. for (dom = state->head; dom; dom = dom->next) {
  1580. if (!n--) {
  1581. // this is the postfix we want
  1582. // the actual postfix string is kept at the end of the structure
  1583. const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
  1584. const int postfix_len = dom->len;
  1585. char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
  1586. if (!newname) return NULL;
  1587. memcpy(newname, base_name, base_len);
  1588. if (need_to_append_dot) newname[base_len] = '.';
  1589. memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
  1590. newname[base_len + need_to_append_dot + postfix_len] = 0;
  1591. return newname;
  1592. }
  1593. }
  1594. // we ran off the end of the list and still didn't find the requested string
  1595. abort();
  1596. }
  1597. static int
  1598. search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
  1599. assert(type == TYPE_A);
  1600. if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
  1601. global_search_state &&
  1602. global_search_state->num_domains) {
  1603. // we have some domains to search
  1604. struct request *req;
  1605. if (string_num_dots(name) >= global_search_state->ndots) {
  1606. req = request_new(type, name, flags, user_callback, user_arg);
  1607. if (!req) return 1;
  1608. req->search_index = -1;
  1609. } else {
  1610. char *const new_name = search_make_new(global_search_state, 0, name);
  1611. if (!new_name) return 1;
  1612. req = request_new(type, new_name, flags, user_callback, user_arg);
  1613. free(new_name);
  1614. if (!req) return 1;
  1615. req->search_index = 0;
  1616. }
  1617. req->search_origname = strdup(name);
  1618. req->search_state = global_search_state;
  1619. req->search_flags = flags;
  1620. global_search_state->refcount++;
  1621. request_submit(req);
  1622. return 0;
  1623. } else {
  1624. struct request *const req = request_new(type, name, flags, user_callback, user_arg);
  1625. if (!req) return 1;
  1626. request_submit(req);
  1627. return 0;
  1628. }
  1629. }
  1630. // this is called when a request has failed to find a name. We need to check
  1631. // if it is part of a search and, if so, try the next name in the list
  1632. // returns:
  1633. // 0 another request has been submitted
  1634. // 1 no more requests needed
  1635. static int
  1636. search_try_next(struct request *const req) {
  1637. if (req->search_state) {
  1638. // it is part of a search
  1639. char *new_name;
  1640. struct request *newreq;
  1641. req->search_index++;
  1642. if (req->search_index >= req->search_state->num_domains) {
  1643. // no more postfixes to try, however we may need to try
  1644. // this name without a postfix
  1645. if (string_num_dots(req->search_origname) < req->search_state->ndots) {
  1646. // yep, we need to try it raw
  1647. struct request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
  1648. log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
  1649. if (newreq) {
  1650. request_submit(newreq);
  1651. return 0;
  1652. }
  1653. }
  1654. return 1;
  1655. }
  1656. new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
  1657. if (!new_name) return 1;
  1658. log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
  1659. newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
  1660. free(new_name);
  1661. if (!newreq) return 1;
  1662. newreq->search_origname = req->search_origname;
  1663. req->search_origname = NULL;
  1664. newreq->search_state = req->search_state;
  1665. newreq->search_flags = req->search_flags;
  1666. newreq->search_index = req->search_index;
  1667. newreq->search_state->refcount++;
  1668. request_submit(newreq);
  1669. return 0;
  1670. }
  1671. return 1;
  1672. }
  1673. static void
  1674. search_request_finished(struct request *const req) {
  1675. if (req->search_state) {
  1676. search_state_decref(req->search_state);
  1677. req->search_state = NULL;
  1678. }
  1679. if (req->search_origname) {
  1680. free(req->search_origname);
  1681. req->search_origname = NULL;
  1682. }
  1683. }
  1684. /////////////////////////////////////////////////////////////////////
  1685. // Parsing resolv.conf files
  1686. static void
  1687. evdns_resolv_set_defaults(int flags) {
  1688. // if the file isn't found then we assume a local resolver
  1689. if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
  1690. if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
  1691. }
  1692. #ifndef HAVE_STRTOK_R
  1693. static char *
  1694. strtok_r(char *s, const char *delim, char **state) {
  1695. return strtok(s, delim);
  1696. }
  1697. #endif
  1698. // helper version of atoi which returns -1 on error
  1699. static int
  1700. strtoint(const char *const str) {
  1701. char *endptr;
  1702. const int r = strtol(str, &endptr, 10);
  1703. if (*endptr) return -1;
  1704. return r;
  1705. }
  1706. static void
  1707. resolv_conf_parse_line(char *const start, int flags) {
  1708. char *strtok_state;
  1709. static const char *const delims = " \t";
  1710. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  1711. char *const first_token = strtok_r(start, delims, &strtok_state);
  1712. if (!first_token) return;
  1713. if (!strcmp(first_token, "nameserver")) {
  1714. const char *const nameserver = NEXT_TOKEN;
  1715. struct in_addr ina;
  1716. if (inet_aton(nameserver, &ina)) {
  1717. // address is valid
  1718. evdns_nameserver_add(ina.s_addr);
  1719. }
  1720. } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
  1721. const char *const domain = NEXT_TOKEN;
  1722. if (domain) {
  1723. search_postfix_clear();
  1724. search_postfix_add(domain);
  1725. }
  1726. } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
  1727. const char *domain;
  1728. search_postfix_clear();
  1729. while ((domain = NEXT_TOKEN)) {
  1730. search_postfix_add(domain);
  1731. }
  1732. search_reverse();
  1733. } else if (!strcmp(first_token, "options")) {
  1734. const char *option;
  1735. while ((option = NEXT_TOKEN)) {
  1736. if (!strncmp(option, "ndots:", 6)) {
  1737. const int ndots = strtoint(&option[6]);
  1738. if (ndots == -1) continue;
  1739. if (!(flags & DNS_OPTION_SEARCH)) continue;
  1740. log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
  1741. if (!global_search_state) global_search_state = search_state_new();
  1742. if (!global_search_state) return;
  1743. global_search_state->ndots = ndots;
  1744. } else if (!strncmp(option, "timeout:", 8)) {
  1745. const int timeout = strtoint(&option[8]);
  1746. if (timeout == -1) continue;
  1747. if (!(flags & DNS_OPTION_MISC)) continue;
  1748. log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
  1749. global_timeout.tv_sec = timeout;
  1750. } else if (!strncmp(option, "attempts:", 9)) {
  1751. int retries = strtoint(&option[9]);
  1752. if (retries == -1) continue;
  1753. if (retries > 255) retries = 255;
  1754. if (!(flags & DNS_OPTION_MISC)) continue;
  1755. log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
  1756. global_max_retransmits = retries;
  1757. }
  1758. }
  1759. }
  1760. #undef NEXT_TOKEN
  1761. }
  1762. // exported function
  1763. // returns:
  1764. // 0 no errors
  1765. // 1 failed to open file
  1766. // 2 failed to stat file
  1767. // 3 file too large
  1768. // 4 out of memory
  1769. // 5 short read from file
  1770. int
  1771. evdns_resolv_conf_parse(int flags, const char *const filename) {
  1772. struct stat st;
  1773. int fd;
  1774. u8 *resolv;
  1775. char *start;
  1776. int err = 0;
  1777. log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
  1778. fd = open(filename, O_RDONLY);
  1779. if (fd < 0) {
  1780. evdns_resolv_set_defaults(flags);
  1781. return 0;
  1782. }
  1783. if (fstat(fd, &st)) { err = 2; goto out1; }
  1784. if (!st.st_size) {
  1785. evdns_resolv_set_defaults(flags);
  1786. err = 0;
  1787. goto out1;
  1788. }
  1789. if (st.st_size > 65535) { err = 3; goto out1; } // no resolv.conf should be any bigger
  1790. resolv = (u8 *) malloc(st.st_size + 1);
  1791. if (!resolv) { err = 4; goto out1; }
  1792. if (read(fd, resolv, st.st_size) != st.st_size) { err = 5; goto out2; }
  1793. resolv[st.st_size] = 0; // we malloced an extra byte
  1794. start = (char *) resolv;
  1795. for (;;) {
  1796. char *const newline = strchr(start, '\n');
  1797. if (!newline) {
  1798. resolv_conf_parse_line(start, flags);
  1799. break;
  1800. } else {
  1801. *newline = 0;
  1802. resolv_conf_parse_line(start, flags);
  1803. start = newline + 1;
  1804. }
  1805. }
  1806. if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
  1807. // no nameservers were configured.
  1808. evdns_nameserver_ip_add("127.0.0.1");
  1809. }
  1810. if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
  1811. search_set_from_hostname();
  1812. }
  1813. out2:
  1814. free(resolv);
  1815. out1:
  1816. close(fd);
  1817. return err;
  1818. }
  1819. #ifdef MS_WINDOWS
  1820. // Add multiple nameservers from a space-or-comma-separated list.
  1821. static int
  1822. evdns_nameserver_ip_add_line(const char *ips) {
  1823. const char *addr;
  1824. char *buf;
  1825. int r;
  1826. while (*ips) {
  1827. while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
  1828. ++ips;
  1829. addr = ips;
  1830. while (ISDIGIT(*ips) || *ips == '.')
  1831. ++ips;
  1832. buf = malloc(ips-addr+1);
  1833. if (!buf) return 4;
  1834. memcpy(buf, addr, ips-addr);
  1835. buf[ips-addr] = '\0';
  1836. r = evdns_nameserver_ip_add(buf);
  1837. free(buf);
  1838. if (r) return r;
  1839. }
  1840. return 0;
  1841. }
  1842. typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
  1843. // Use the windows GetNetworkParams interface in iphlpapi.dll to
  1844. // figure out what our nameservers are.
  1845. static int
  1846. load_nameservers_with_getnetworkparams(void) {
  1847. // Based on MSDN examples and inspection of c-ares code.
  1848. FIXED_INFO *fixed;
  1849. HMODULE handle = 0;
  1850. ULONG size = sizeof(FIXED_INFO);
  1851. void *buf = NULL;
  1852. int status = 0, r, added_any;
  1853. IP_ADDR_STRING *ns;
  1854. GetNetworkParams_fn_t fn;
  1855. if (!(handle = LoadLibrary("iphlpapi.dll"))) {
  1856. log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
  1857. //right now status = 0, doesn't that mean "good" - mikec
  1858. status = -1;
  1859. goto done;
  1860. }
  1861. if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
  1862. log(EVDNS_LOG_WARN, "Could not get address of function.");
  1863. //same as above
  1864. status = -1;
  1865. goto done;
  1866. }
  1867. buf = malloc(size);
  1868. if (!buf) {
  1869. status = 4;
  1870. goto done;
  1871. }
  1872. fixed = buf;
  1873. r = fn(fixed, &size);
  1874. if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
  1875. status = -1;
  1876. goto done;
  1877. }
  1878. if (r != ERROR_SUCCESS) {
  1879. free(buf);
  1880. buf = malloc(size);
  1881. if (!buf) { status = 4; goto done; }
  1882. fixed = buf;
  1883. r = fn(fixed, &size);
  1884. if (r != ERROR_SUCCESS) {
  1885. log(EVDNS_LOG_DEBUG, "fn() failed.");
  1886. status = -1;
  1887. goto done;
  1888. }
  1889. }
  1890. assert(fixed);
  1891. added_any = 0;
  1892. ns = &(fixed->DnsServerList);
  1893. while (ns) {
  1894. r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
  1895. if (r) {
  1896. log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
  1897. (ns->IpAddress.String),(int)GetLastError());
  1898. status = r;
  1899. goto done;
  1900. } else {
  1901. log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
  1902. }
  1903. added_any++;
  1904. ns = ns->Next;
  1905. }
  1906. if (!added_any) {
  1907. //should we ever get here? - mikec
  1908. log(EVDNS_LOG_DEBUG, "No nameservers added.");
  1909. status = -1;
  1910. }
  1911. done:
  1912. if (buf)
  1913. free(buf);
  1914. if (handle)
  1915. FreeLibrary(handle);
  1916. return status;
  1917. }
  1918. static int
  1919. config_nameserver_from_reg_key(HKEY key, const char *subkey) {
  1920. char *buf;
  1921. DWORD bufsz = 0, type = 0;
  1922. int status = 0;
  1923. if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
  1924. != ERROR_MORE_DATA)
  1925. return -1;
  1926. if (!(buf = malloc(bufsz)))
  1927. return -1;
  1928. if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
  1929. == ERROR_SUCCESS && bufsz > 1) {
  1930. status = evdns_nameserver_ip_add_line(buf);
  1931. }
  1932. free(buf);
  1933. return status;
  1934. }
  1935. #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
  1936. #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
  1937. #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
  1938. static int
  1939. load_nameservers_from_registry(void) {
  1940. int found = 0;
  1941. int r;
  1942. #define TRY(k, name) \
  1943. if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
  1944. log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
  1945. found = 1; \
  1946. } else if (!found) { \
  1947. log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
  1948. #k,#name); \
  1949. }
  1950. if (((int)GetVersion()) > 0) { /* NT */
  1951. HKEY nt_key = 0, interfaces_key = 0;
  1952. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
  1953. KEY_READ, &nt_key) != ERROR_SUCCESS) {
  1954. log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
  1955. return -1;
  1956. }
  1957. r = RegOpenKeyEx(nt_key, "Interfaces", 0,
  1958. KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
  1959. &interfaces_key);
  1960. if (r != ERROR_SUCCESS) {
  1961. log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
  1962. return -1;
  1963. }
  1964. TRY(nt_key, "NameServer");
  1965. TRY(nt_key, "DhcpNameServer");
  1966. TRY(interfaces_key, "NameServer");
  1967. TRY(interfaces_key, "DhcpNameServer");
  1968. RegCloseKey(interfaces_key);
  1969. RegCloseKey(nt_key);
  1970. } else {
  1971. HKEY win_key = 0;
  1972. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
  1973. KEY_READ, &win_key) != ERROR_SUCCESS) {
  1974. log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
  1975. return -1;
  1976. }
  1977. TRY(win_key, "NameServer");
  1978. RegCloseKey(win_key);
  1979. }
  1980. if (found == 0) {
  1981. log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
  1982. }
  1983. return found ? 0 : -1;
  1984. #undef TRY
  1985. }
  1986. int
  1987. evdns_config_windows_nameservers(void) {
  1988. if (load_nameservers_with_getnetworkparams() == 0)
  1989. return 0;
  1990. return load_nameservers_from_registry();
  1991. }
  1992. #endif
  1993. #ifdef EVDNS_MAIN
  1994. void
  1995. main_callback(int result, char type, int count, int ttl,
  1996. void *addrs, void *orig) {
  1997. char *n = (char*)orig;
  1998. int i;
  1999. for (i = 0; i < count; ++i) {
  2000. if (type == DNS_IPv4_A) {
  2001. printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
  2002. } else if (type == DNS_PTR) {
  2003. printf("%s: %s\n", n, ((char**)addrs)[i]);
  2004. }
  2005. }
  2006. if (!count) {
  2007. printf("%s: No answer (%d)\n", n, result);
  2008. }
  2009. fflush(stdout);
  2010. }
  2011. void
  2012. logfn(const char *msg) {
  2013. fprintf(stderr, "%s\n", msg);
  2014. }
  2015. int
  2016. main(int c, char **v) {
  2017. int idx;
  2018. int reverse = 0, verbose = 1;
  2019. if (c<2) {
  2020. fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
  2021. return 1;
  2022. }
  2023. idx = 1;
  2024. while (idx < c && v[idx][0] == '-') {
  2025. if (!strcmp(v[idx], "-x"))
  2026. reverse = 1;
  2027. else if (!strcmp(v[idx], "-v"))
  2028. verbose = 1;
  2029. else
  2030. fprintf(stderr, "Unknown option %s\n", v[idx]);
  2031. ++idx;
  2032. }
  2033. event_init();
  2034. if (verbose)
  2035. evdns_set_log_fn(logfn);
  2036. evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
  2037. for (; idx < c; ++idx) {
  2038. if (reverse) {
  2039. struct in_addr addr;
  2040. if (!inet_aton(v[idx], &addr)) {
  2041. fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
  2042. continue;
  2043. }
  2044. fprintf(stderr, "resolving %s...\n",v[idx]);
  2045. evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
  2046. } else {
  2047. fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
  2048. evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
  2049. }
  2050. }
  2051. fflush(stdout);
  2052. event_dispatch();
  2053. return 0;
  2054. }
  2055. #endif
  2056. int
  2057. evdns_init(void)
  2058. {
  2059. int res = 0;
  2060. #ifdef MS_WINDOWS
  2061. evdns_config_windows_nameservers();
  2062. #else
  2063. res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  2064. #endif
  2065. return (res);
  2066. }
  2067. const char *
  2068. evdns_err_to_string(int err)
  2069. {
  2070. switch (err) {
  2071. case DNS_ERR_NONE: return "no error";
  2072. case DNS_ERR_FORMAT: return "misformatted query";
  2073. case DNS_ERR_SERVERFAILED: return "server failed";
  2074. case DNS_ERR_NOTEXIST: return "name does not exist";
  2075. case DNS_ERR_NOTIMPL: return "query not implemented";
  2076. case DNS_ERR_REFUSED: return "refused";
  2077. case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
  2078. case DNS_ERR_UNKNOWN: return "unknown";
  2079. case DNS_ERR_TIMEOUT: return "request timed out";
  2080. case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
  2081. default: return "[Unknown error code]";
  2082. }
  2083. }
  2084. void
  2085. evdns_shutdown(int fail_requests)
  2086. {
  2087. struct nameserver *server, *server_next;
  2088. struct search_domain *dom, *dom_next;
  2089. while (req_head) {
  2090. if (fail_requests)
  2091. reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
  2092. request_finished(req_head, &req_head);
  2093. }
  2094. while (req_waiting_head) {
  2095. if (fail_requests)
  2096. reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
  2097. request_finished(req_waiting_head, &req_waiting_head);
  2098. }
  2099. global_requests_inflight = global_requests_waiting = 0;
  2100. for (server = server_head; server; server = server_next) {
  2101. server_next = server->next;
  2102. if (server->socket >= 0)
  2103. CLOSE_SOCKET(server->socket);
  2104. (void) event_del(&server->event);
  2105. free(server);
  2106. if (server_next == server_head)
  2107. break;
  2108. }
  2109. server_head = NULL;
  2110. global_good_nameservers = 0;
  2111. if (global_search_state) {
  2112. for (dom = global_search_state->head; dom; dom = dom_next) {
  2113. dom_next = dom->next;
  2114. free(dom);
  2115. }
  2116. free(global_search_state);
  2117. global_search_state = NULL;
  2118. }
  2119. evdns_log_fn = NULL;
  2120. }
  2121. // Local Variables:
  2122. // tab-width: 4
  2123. // c-basic-offset: 4
  2124. // indent-tabs-mode: t
  2125. // End: