eventdns.c 80 KB

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