eventdns.c 63 KB

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