eventdns.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. /* Async DNS Library
  2. * Adam Langley <agl@imperialviolet.org>
  3. * http://www.imperialviolet.org/eventdns.html
  4. * Public Domain codenext
  5. *
  6. * This software is Public Domain. To view a copy of the public domain dedication,
  7. * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  8. * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  9. *
  10. * I ask and expect, but do not require, that all derivative works contain an
  11. * attribution similar to:
  12. * Parts developed by Adam Langley <agl@imperialviolet.org>
  13. *
  14. * You may wish to replace the word "Parts" with something else depending on
  15. * the amount of original code.
  16. *
  17. * (Derivative works does not include programs which link against, run or include
  18. * the source verbatim in their source distributions)
  19. *
  20. * Version: 0.1b
  21. *
  22. *
  23. * Welcome, gentle reader
  24. *
  25. * Async DNS lookups are really a whole lot harder than they should be,
  26. * mostly stemming from the fact that the libc resolver has never been
  27. * very good at them. Before you use this library you should see if libc
  28. * can do the job for you with the modern async call getaddrinfo_r
  29. * (Google for it). Otherwise, please continue.
  30. *
  31. * This code is based on libevent and you must call event_init before
  32. * any of the APIs in this file. You must also seed the OpenSSL random
  33. * source if you are using OpenSSL for ids (see below).
  34. *
  35. * This library is designed to be included and shipped with your source
  36. * code. You statically link with it. You should also test for the
  37. * existance of strtok_r and define HAVE_STRTOK_R if you have it.
  38. *
  39. * The DNS protocol requires a good source of id numbers and these
  40. * numbers should be unpredictable for spoofing reasons. There are
  41. * three methods for generating them here and you must define exactly
  42. * one of them. In increasing order of preference:
  43. *
  44. * DNS_USE_GETTIMEOFDAY_FOR_ID:
  45. * Using the bottom 16 bits of the usec result from gettimeofday. This
  46. * is a pretty poor solution but should work anywhere
  47. * DNS_USE_CPU_CLOCK_FOR_ID:
  48. * Using the bottom 16 bits of the nsec result from the CPU's time
  49. * counter. This is better, but may not work everywhere. Requires
  50. * POSIX realtime support and you'll need to link against -lrt on
  51. * glibc systems at least
  52. * DNS_USE_OPENSSL_FOR_ID:
  53. * Uses the OpenSSL RAND_bytes call to generate the data. You must
  54. * have seeded the pool before making any calls to this library.
  55. *
  56. * The library keeps track of the state of nameservers and will avoid
  57. * them when they go down. Otherwise it will round robin between them.
  58. *
  59. * Quick start guide:
  60. * #include "eventdns.h"
  61. * void callback(int result, char type, int count, int ttl,
  62. * void *addresses, void *arg);
  63. * eventdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  64. * eventdns_resolve("www.hostname.com", 0, callback, NULL);
  65. *
  66. * When the lookup is complete the callback function is called. The
  67. * first argument will be one of the DNS_ERR_* defines in eventdns.h.
  68. * Hopefully it will be DNS_ERR_NONE, in which case type will be
  69. * DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
  70. * which the data can be cached for (in seconds), addresses will point
  71. * to an array of uint32_t's and arg will be whatever you passed to
  72. * eventdns_resolve.
  73. *
  74. * Searching:
  75. *
  76. * In order for this library to be a good replacment for glibc's resolver it
  77. * supports searching. This involves setting a list of default domains, in
  78. * which names will be queried for. The number of nots in the query name
  79. * determines the order in which this list is used.
  80. *
  81. * Searching appears to be a single lookup from the point of view of the API,
  82. * although many DNS queries may be generated from a single call to
  83. * eventdns_resolve. Searching can also drastically slow down the resolution of
  84. * names.
  85. *
  86. * To disable searching:
  87. * 1. Never set it up. If you never call eventdns_resolv_conf_parse or
  88. * eventdns_search_add then no searching will occur.
  89. *
  90. * 2. If you do call eventdns_resolv_conf_parse then don't pass
  91. * DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it)
  92. *
  93. * 3. When calling eventdns_resolve, pass the DNS_QUERY_NO_SEARCH flag
  94. *
  95. * The order of searches depends on the number of dots in the name. If the
  96. * number is greater than the ndots setting then the names is first tried
  97. * globally. Otherwise each search domain is appended in turn.
  98. *
  99. * The ndots setting can either be set from a resolv.conf, or by calling
  100. * eventdns_search_ndots_set.
  101. *
  102. * For example, with ndots set to 1 (the default) and a search domain list of
  103. * ["myhome.net"]:
  104. * Query: www
  105. * Order: www.myhome.net, www.
  106. *
  107. * Query: www.abc
  108. * Order: www.abc., www.abc.myhome.net
  109. *
  110. * API reference:
  111. *
  112. * int eventdns_nameserver_add(unsigned long int addresss)
  113. * Add a nameserver. The address should be an IP address in
  114. * network byte order. The type of address is chosen so that
  115. * it match in_addr.s_addr.
  116. * Returns non-zero on error.
  117. *
  118. * int eventdns_nameserer_ip_add(const char *ip_as_string)
  119. * This wraps the above function by parsing a string as an IP
  120. * address and add it as a nameserver.
  121. * Returns non-zero on error
  122. *
  123. * int eventdns_resolve(const char *name, int flags,
  124. * eventdns_callback_type callback,
  125. * void *ptr)
  126. * Resolve a name. The name parameter should be a DNS name.
  127. * The flags parameter should be 0, or DNS_QUERY_NO_SEARCH
  128. * which disables searching for this query. (see defn of
  129. * searching above).
  130. *
  131. * The callback argument is a function which is called when
  132. * this query completes and ptr is an argument which is passed
  133. * to that callback function.
  134. *
  135. * Returns non-zero on error
  136. *
  137. * void eventdns_search_clear()
  138. * Clears the list of search domains
  139. *
  140. * void eventdns_search_add(const char *domain)
  141. * Add a domain to the list of search domains
  142. *
  143. * void eventdns_search_ndots_set(int ndots)
  144. * Set the number of dots which, when found in a name, causes
  145. * the first query to be without any search domain.
  146. *
  147. * int eventdns_resolv_conf_parse(int flags, const char *filename)
  148. * Parse a resolv.conf like file from the given filename.
  149. *
  150. * See the manpage for resolv.conf for the format of this file.
  151. * The flags argument determines what information is parsed from
  152. * this file:
  153. * DNS_OPTION_SEARCH - domain, search and ndots options
  154. * DNS_OPTION_NAMESERVERS - nameserver lines
  155. * DNS_OPTION_MISC - timeout and attempts options
  156. * DNS_OPTIONS_ALL - all of the above
  157. * The following directives are not parsed from the file:
  158. * sortlist, rotate, no-check-names, inet6, debug
  159. *
  160. * Returns non-zero on error:
  161. * 0 no errors
  162. * 1 failed to open file
  163. * 2 failed to stat file
  164. * 3 file too large
  165. * 4 out of memory
  166. * 5 short read from file
  167. *
  168. * Internals:
  169. *
  170. * Requests are kept in two queues. The first is the inflight queue. In
  171. * this queue requests have an allocated transaction id and nameserver.
  172. * They will soon be transmitted if they haven't already been.
  173. *
  174. * The second is the waiting queue. The size of the inflight ring is
  175. * limited and all other requests wait in waiting queue for space. This
  176. * bounds the number of concurrent requests so that we don't flood the
  177. * nameserver. Several algorithms require a full walk of the inflight
  178. * queue and so bounding its size keeps thing going nicly under huge
  179. * (many thousands of requests) loads.
  180. *
  181. * If a nameserver looses too many requests it is considered down and we
  182. * try not to use it. After a while we send a probe to that nameserver
  183. * (a lookup for google.com) and, if it replies, we consider it working
  184. * again. If the nameserver fails a probe we wait longer to try again
  185. * with the next probe.
  186. */
  187. #include "eventdns.h"
  188. #include "eventdns_tor.h"
  189. //#define NDEBUG
  190. #ifndef DNS_USE_CPU_CLOCK_FOR_ID
  191. #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
  192. #ifndef DNS_USE_OPENSSL_FOR_ID
  193. #error Must configure at least one id generation method.
  194. #error Please see the documentation
  195. #endif
  196. #endif
  197. #endif
  198. // #define _POSIX_C_SOURCE 200507
  199. #define _GNU_SOURCE
  200. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  201. #ifdef DNS_USE_OPENSSL_FOR_ID
  202. #error Multiple id options selected
  203. #endif
  204. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  205. #error Multiple id options selected
  206. #endif
  207. #include <time.h>
  208. #endif
  209. #ifdef DNS_USE_OPENSSL_FOR_ID
  210. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  211. #error Multiple id options selected
  212. #endif
  213. #include <openssl/rand.h>
  214. #endif
  215. #define _FORTIFY_SOURCE 3
  216. #include <string.h>
  217. #include <sys/types.h>
  218. #include <fcntl.h>
  219. #include <sys/socket.h>
  220. #include <sys/time.h>
  221. #include <stdint.h>
  222. #include <stdlib.h>
  223. #include <string.h>
  224. #include <errno.h>
  225. #include <alloca.h>
  226. #include <assert.h>
  227. #include <netinet/in.h>
  228. #include <arpa/inet.h>
  229. #include <unistd.h>
  230. #include <limits.h>
  231. #include <sys/stat.h>
  232. #ifndef HOST_NAME_MAX
  233. #define HOST_NAME_MAX 255
  234. #endif
  235. #ifndef NDEBUG
  236. #include <stdio.h>
  237. #endif
  238. #undef MIN
  239. #define MIN(a,b) ((a)<(b)?(a):(b))
  240. #ifdef __USE_ISOC99B
  241. // libevent doesn't work without this
  242. typedef uint8_t u_char;
  243. typedef unsigned int uint;
  244. #endif
  245. #include <event.h>
  246. #define u64 uint64_t
  247. #define u32 uint32_t
  248. #define u16 uint16_t
  249. #define u8 uint8_t
  250. #ifndef NDEBUG
  251. #include <stdio.h>
  252. #define log printf
  253. #else
  254. #define log(x,...)
  255. #endif
  256. #include "eventdns.h"
  257. #define MAX_ADDRS 4 // maximum number of addresses from a single packet
  258. // which we bother recording
  259. #define TYPE_A 1
  260. #define CLASS_INET 1
  261. struct request {
  262. u8 *request; // the dns packet data
  263. uint request_len;
  264. int reissue_count;
  265. int tx_count; // the number of times that this packet has been sent
  266. void *user_pointer; // the pointer given to us for this request
  267. eventdns_callback_type user_callback;
  268. struct nameserver *ns; // the server which we last sent it
  269. // elements used by the searching code
  270. int search_index;
  271. struct search_state *search_state;
  272. char *search_origname; // needs to be free()ed
  273. int search_flags;
  274. // these objects are kept in a circular list
  275. struct request *next, *prev;
  276. struct event timeout_event;
  277. u16 trans_id; // the transaction id
  278. char request_appended; // true if the request pointer is data which follows this struct
  279. char transmit_me; // needs to be transmitted
  280. };
  281. struct nameserver {
  282. int socket; // a connected UDP socket
  283. u32 address;
  284. int failed_times; // number of times which we have given this server a chance
  285. int timedout; // number of times in a row a request has timed out
  286. struct event event;
  287. // these objects are kept in a circular list
  288. struct nameserver *next, *prev;
  289. struct event timeout_event; // used to keep the timeout for
  290. // when we next probe this server.
  291. // Valid if state == 0
  292. char state; // zero if we think that this server is down
  293. char choaked; // true if we have an EAGAIN from this server's socket
  294. char write_waiting; // true if we are waiting for EV_WRITE events
  295. };
  296. static struct request *req_head = NULL, *req_waiting_head = NULL;
  297. static struct nameserver *server_head = NULL;
  298. // The number of good nameservers that we have
  299. static int global_good_nameservers = 0;
  300. // inflight requests are contained in the req_head list
  301. // and are actually going out across the network
  302. static int global_requests_inflight = 0;
  303. // requests which aren't inflight are in the waiting list
  304. // and are counted here
  305. static int global_requests_waiting = 0;
  306. static int global_max_requests_inflight = 64;
  307. static struct timeval global_timeout = {3, 0}; // 3 seconds
  308. static int global_max_reissues = 1; // a reissue occurs when we get some errors from the server
  309. static int global_max_retransmits = 3; // number of times we'll retransmit a request which timed out
  310. // number of timeouts in a row before we consider this server to be down
  311. static int global_max_nameserver_timeout = 3;
  312. // These are the timeout values for nameservers. If we find a nameserver is down
  313. // we try to probe it at intervals as given below. Values are in seconds.
  314. static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
  315. static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
  316. 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"};
  317. static struct nameserver *nameserver_pick();
  318. static void eventdns_request_insert(struct request *req, struct request **head);
  319. static void nameserver_ready_callback(int fd, short events, void *arg);
  320. static int eventdns_transmit();
  321. static int eventdns_request_transmit(struct request *req);
  322. static void nameserver_send_probe(struct nameserver *const ns);
  323. static void search_request_finished(struct request *const);
  324. static int search_try_next(struct request *const req);
  325. static int search_request_new(const char *const name, int flags, eventdns_callback_type user_callback, void *user_arg);
  326. static void eventdns_requests_pump_waiting_queue();
  327. static u16 transaction_id_pick();
  328. static struct request *request_new(const char *name, int flags, eventdns_callback_type callback, void *ptr);
  329. static void request_submit(struct request *req);
  330. // This walks the list of inflight requests to find the
  331. // one with a matching transaction id. Returns NULL on
  332. // failure
  333. static struct request *
  334. request_find_from_trans_id(u16 trans_id) {
  335. struct request *req = req_head, *const started_at = req_head;
  336. if (req) {
  337. do {
  338. if (req->trans_id == trans_id) return req;
  339. req = req->next;
  340. } while (req != started_at);
  341. }
  342. return NULL;
  343. }
  344. // a libevent callback function which is called when a nameserver
  345. // has gone down and we want to test if it has came back to life yet
  346. static void
  347. nameserver_prod_callback(int fd, short events, void *arg) {
  348. struct nameserver *const ns = (struct nameserver *) arg;
  349. nameserver_send_probe(ns);
  350. }
  351. // a libevent callback which is called when a nameserver probe (to see if
  352. // it has come back to life) times out. We increment the count of failed_times
  353. // and wait longer to send the next probe packet.
  354. static void
  355. nameserver_probe_failed(struct nameserver *const ns) {
  356. assert(ns->state == 0);
  357. evtimer_del(&ns->timeout_event);
  358. const struct timeval *const timeout =
  359. &global_nameserver_timeouts[MIN(ns->failed_times,
  360. global_nameserver_timeouts_length - 1)];
  361. ns->failed_times++;
  362. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  363. evtimer_add(&ns->timeout_event, (struct timeval *) timeout);
  364. }
  365. // called when a nameserver has been deemed to have failed. For example, too
  366. // many packets have timed out etc
  367. static void
  368. nameserver_failed(struct nameserver *const ns) {
  369. // if this nameserver has already been marked as failed
  370. // then don't do anything
  371. if (!ns->state) return;
  372. log("Nameserver %lx has failed\n", (unsigned long)ns->address);
  373. global_good_nameservers--;
  374. assert(global_good_nameservers >= 0);
  375. if (global_good_nameservers == 0) {
  376. log("All nameservers have failed\n");
  377. }
  378. ns->state = 0;
  379. ns->failed_times = 1;
  380. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  381. evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]);
  382. // walk the list of inflight requests to see if any can be reassigned to
  383. // a different server. Requests in the waiting queue don't have a
  384. // nameserver assigned yet
  385. // if we don't have *any* good nameservers then there's no point
  386. // trying to reassign requests to one
  387. if (!global_good_nameservers) return;
  388. struct request *req = req_head, *const started_at = req_head;
  389. if (req) {
  390. do {
  391. if (req->tx_count == 0 && req->ns == ns) {
  392. // still waiting to go out, can be moved
  393. // to another server
  394. req->ns = nameserver_pick();
  395. }
  396. req = req->next;
  397. } while (req != started_at);
  398. }
  399. }
  400. static void
  401. nameserver_up(struct nameserver *const ns) {
  402. if (ns->state) return;
  403. log("Nameserver %lx is back up\n", (unsigned long)ns->address);
  404. evtimer_del(&ns->timeout_event);
  405. ns->state = 1;
  406. ns->failed_times = 0;
  407. global_good_nameservers++;
  408. }
  409. static void
  410. request_trans_id_set(struct request *const req, const u16 trans_id) {
  411. req->trans_id = trans_id;
  412. *((u16 *) req->request) = htons(trans_id);
  413. }
  414. // Called to remove a request from a list and dealloc it.
  415. // head is a pointer to the head of the list it should be
  416. // removed from or NULL if the request isn't in a list.
  417. static void
  418. request_finished(struct request *const req, struct request **head) {
  419. if (head) {
  420. if (req->next == req) {
  421. // only item in the list
  422. *head = NULL;
  423. } else {
  424. req->next->prev = req->prev;
  425. req->prev->next = req->next;
  426. if (*head == req) *head = req->next;
  427. }
  428. }
  429. log("Removing timeout for %x\n", (unsigned) req);
  430. evtimer_del(&req->timeout_event);
  431. search_request_finished(req);
  432. global_requests_inflight--;
  433. if (!req->request_appended) {
  434. // need to free the request data on it's own
  435. free(req->request);
  436. } else {
  437. // the request data is appended onto the header
  438. // so everything gets free()ed when we:
  439. }
  440. free(req);
  441. eventdns_requests_pump_waiting_queue();
  442. }
  443. // This is called when a server returns a funny error code.
  444. // We try the request again with another server.
  445. //
  446. // return:
  447. // 0 ok
  448. // 1 failed/reissue is pointless
  449. static int
  450. request_reissue(struct request *req) {
  451. const struct nameserver *const last_ns = req->ns;
  452. // the last nameserver should have been marked as failing
  453. // by the caller of this function, therefore pick will try
  454. // not to return it
  455. req->ns = nameserver_pick();
  456. if (req->ns == last_ns) {
  457. // ... but pick did return it
  458. // not a lot of point in trying again with the
  459. // same server
  460. return 1;
  461. }
  462. req->reissue_count++;
  463. req->tx_count = 0;
  464. req->transmit_me = 1;
  465. return 0;
  466. }
  467. // this function looks for space on the inflight queue and promotes
  468. // requests from the waiting queue if it can.
  469. static void
  470. eventdns_requests_pump_waiting_queue() {
  471. while (global_requests_inflight < global_max_requests_inflight &&
  472. global_requests_waiting) {
  473. // move a request from the waiting queue to the inflight queue
  474. assert(req_waiting_head);
  475. struct request *req;
  476. if (req_waiting_head->next == req_waiting_head) {
  477. // only one item in the queue
  478. req = req_waiting_head;
  479. req_waiting_head = NULL;
  480. } else {
  481. req = req_waiting_head;
  482. req->next->prev = req->prev;
  483. req->prev->next = req->next;
  484. req_waiting_head = req->next;
  485. }
  486. global_requests_waiting--;
  487. global_requests_inflight++;
  488. req->ns = nameserver_pick();
  489. request_trans_id_set(req, transaction_id_pick());
  490. eventdns_request_insert(req, &req_head);
  491. eventdns_request_transmit(req);
  492. eventdns_transmit();
  493. }
  494. }
  495. // this processes a parsed reply packet
  496. static void
  497. reply_handle(u16 trans_id, u16 flags, u32 ttl, u32 addrcount, u32 *addresses) {
  498. int error;
  499. static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
  500. struct request *const req = request_find_from_trans_id(trans_id);
  501. if (!req) return;
  502. if (flags & 0x020f || !addrcount) {
  503. // there was an error
  504. if (flags & 0x0200) {
  505. error = DNS_ERR_TRUNCATED;
  506. } else {
  507. u16 error_code = (flags & 0x000f) - 1;
  508. if (error_code > 4) {
  509. error = DNS_ERR_UNKNOWN;
  510. } else {
  511. error = error_codes[error_code];
  512. }
  513. }
  514. switch(error) {
  515. case DNS_ERR_SERVERFAILED:
  516. case DNS_ERR_NOTIMPL:
  517. case DNS_ERR_REFUSED:
  518. // we regard these errors as marking a bad nameserver
  519. if (req->reissue_count < global_max_reissues) {
  520. nameserver_failed(req->ns);
  521. if (!request_reissue(req)) return;
  522. }
  523. break;
  524. default:
  525. // we got a good reply from the nameserver
  526. nameserver_up(req->ns);
  527. }
  528. if (req->search_state) {
  529. // if we have a list of domains to search in, try the next one
  530. if (!search_try_next(req)) {
  531. // a new request was issued so this request is finished and
  532. // the user callback will be made when that request (or a
  533. // child of it) finishes.
  534. request_finished(req, &req_head);
  535. return;
  536. }
  537. }
  538. // all else failed. Pass the failure up
  539. req->user_callback(error, 0, 0, 0, NULL, req->user_pointer);
  540. request_finished(req, &req_head);
  541. } else {
  542. // all ok, tell the user
  543. req->user_callback(DNS_ERR_NONE, DNS_IPv4_A, addrcount, ttl, addresses, req->user_pointer);
  544. nameserver_up(req->ns);
  545. request_finished(req, &req_head);
  546. }
  547. }
  548. // parses a raw packet from the wire
  549. static void
  550. reply_parse(u8 *packet, int length) {
  551. int j = 0; // index into packet
  552. u16 _t; // used by the macros
  553. u32 _t32; // used by the macros
  554. #define GET32(x) do { if (j + 4 > length) return; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0);
  555. #define GET16(x) do { if (j + 2 > length) return; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0);
  556. #define GET8(x) do { if (j >= length) return; x = packet[j++]; } while(0);
  557. u16 trans_id, flags, questions, answers, authority, additional, datalength;
  558. u32 ttl, ttl_r = 0xffffffff;
  559. u32 addresses[MAX_ADDRS];
  560. int addresses_done = 0;
  561. GET16(trans_id);
  562. GET16(flags);
  563. GET16(questions);
  564. GET16(answers);
  565. GET16(authority);
  566. GET16(additional);
  567. if (!(flags & 0x8000)) return; // must be an answer
  568. if (flags & 0x020f) {
  569. // there was an error
  570. reply_handle(trans_id, flags, 0, 0, NULL);
  571. return;
  572. }
  573. // if (!answers) return; // must have an answer of some form
  574. // This macro skips a name in the DNS reply. Normally the
  575. // names are a series of length prefixed strings terminated with
  576. // a length of 0 (the lengths are u8's < 63).
  577. // However, the length can start with a pair of 1 bits and that
  578. // means that the next 14 bits are a pointer within the current
  579. // packet. The name stops after a pointer like that.
  580. #define SKIP_NAME \
  581. for(;;) { \
  582. u8 label_len; \
  583. GET8(label_len); \
  584. if (!label_len) break; \
  585. if (label_len & 0xc0) { \
  586. GET8(label_len); \
  587. break; \
  588. } \
  589. if (label_len > 63) return; \
  590. j += label_len; \
  591. }
  592. uint i;
  593. // skip over each question in the reply
  594. for (i = 0; i < questions; ++i) {
  595. // the question looks like
  596. // <label:name><u16:type><u16:class>
  597. SKIP_NAME;
  598. j += 4;
  599. }
  600. // now we have the answer section which looks like
  601. // <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
  602. for (i = 0; i < answers; ++i) {
  603. u16 type, class;
  604. SKIP_NAME;
  605. GET16(type);
  606. GET16(class);
  607. GET32(ttl);
  608. GET16(datalength);
  609. if (type == TYPE_A && class == CLASS_INET) {
  610. const uint addrcount = datalength >> 2; // each IP address is 4 bytes
  611. const uint addrtocopy = MIN(MAX_ADDRS - addresses_done, addrcount);
  612. ttl_r = MIN(ttl_r, ttl);
  613. // we only bother with the first four addresses.
  614. if (j + 4*addrtocopy > length) return;
  615. memcpy(&addresses[addresses_done], packet + j, 4*addrtocopy);
  616. j += 4*addrtocopy;
  617. addresses_done += addrtocopy;
  618. if (addresses_done == MAX_ADDRS) break;
  619. } else {
  620. // skip over any other type of resource
  621. j += datalength;
  622. }
  623. }
  624. reply_handle(trans_id, flags, ttl_r, addresses_done, addresses);
  625. #undef SKIP_NAME
  626. #undef GET32
  627. #undef GET16
  628. #undef GET8
  629. }
  630. // Try to choose a strong transaction id which isn't already in flight
  631. static u16
  632. transaction_id_pick() {
  633. for (;;) {
  634. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  635. struct timespec ts;
  636. if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts)) abort();
  637. const u16 trans_id = ts.tv_nsec & 0xffff;
  638. #endif
  639. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  640. struct timeval tv;
  641. gettimeofday(&tv, NULL);
  642. const u16 trans_id = tv.tv_usec & 0xffff;
  643. #endif
  644. #ifdef DNS_USE_OPENSSL_FOR_ID
  645. u16 trans_id;
  646. if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
  647. /* // in the case that the RAND call fails we back
  648. // down to using gettimeofday.
  649. struct timeval tv;
  650. gettimeofday(&tv, NULL);
  651. trans_id = tv.tv_usec & 0xffff; */
  652. abort();
  653. }
  654. #endif
  655. if (trans_id == 0xffff) continue;
  656. // now check to see if that id is already inflight
  657. const struct request *req = req_head, *const started_at = req_head;
  658. if (req) {
  659. do {
  660. if (req->trans_id == trans_id) break;
  661. req = req->next;
  662. } while (req != started_at);
  663. }
  664. // we didn't find it, so this is a good id
  665. if (req == started_at) return trans_id;
  666. }
  667. }
  668. // choose a namesever to use. This function will try to ignore
  669. // nameservers which we think are down and load balence across the rest
  670. // by updating the server_head global each time.
  671. static struct nameserver *
  672. nameserver_pick() {
  673. if (!server_head) return NULL;
  674. // if we don't have any good nameservers then there's no
  675. // point in trying to find one.
  676. if (!global_good_nameservers) {
  677. server_head = server_head->next;
  678. return server_head;
  679. }
  680. // remember that nameservers are in a circular list
  681. struct nameserver *started_at = server_head, *picked;
  682. for (;;) {
  683. if (server_head->state) {
  684. // we think this server is currently good
  685. picked = server_head;
  686. server_head = server_head->next;
  687. return picked;
  688. }
  689. server_head = server_head->next;
  690. if (server_head == started_at) {
  691. // all the nameservers seem to be down
  692. // so we just return this one and hope for the
  693. // best
  694. assert(global_good_nameservers == 0);
  695. picked = server_head;
  696. server_head = server_head->next;
  697. return picked;
  698. }
  699. }
  700. }
  701. // this is called when a namesever socket is ready for reading
  702. static void
  703. nameserver_read(struct nameserver *ns) {
  704. u8 packet[1500];
  705. for (;;) {
  706. const int r = recv(ns->socket, packet, sizeof(packet), 0);
  707. if (r < 0) {
  708. if (errno == EAGAIN) return;
  709. nameserver_failed(ns);
  710. return;
  711. }
  712. reply_parse(packet, r);
  713. }
  714. }
  715. // set if we are waiting for the ability to write to this server.
  716. // if waiting is true then we ask libevent for EV_WRITE events, otherwise
  717. // we stop these events.
  718. static void
  719. nameserver_write_waiting(struct nameserver *ns, char waiting) {
  720. if (ns->write_waiting == waiting) return;
  721. ns->write_waiting = waiting;
  722. event_del(&ns->event);
  723. event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
  724. nameserver_ready_callback, ns);
  725. event_add(&ns->event, NULL);
  726. }
  727. // a callback function. Called by libevent when the kernel says that
  728. // a nameserver socket is ready for writing or reading
  729. static void
  730. nameserver_ready_callback(int fd, short events, void *arg) {
  731. struct nameserver *ns = (struct nameserver *) arg;
  732. if (events & EV_WRITE) {
  733. ns->choaked = 0;
  734. if (!eventdns_transmit()) {
  735. nameserver_write_waiting(ns, 0);
  736. }
  737. }
  738. if (events & EV_READ) {
  739. nameserver_read(ns);
  740. }
  741. }
  742. // Converts a string to a length-prefixed set of DNS labels.
  743. // @buf must be strlen(name)+2 or longer. name and buf must
  744. // not overlap. name_len should be the length of name
  745. //
  746. // Input: abc.def
  747. // Output: <3>abc<3>def<0>
  748. //
  749. // Returns the length of the data. negative on error
  750. // -1 label was > 63 bytes
  751. // -2 name was > 255 bytes
  752. static int
  753. dnsname_to_labels(u8 *const buf, const char *name, const int name_len) { \
  754. const char *end = name + name_len; \
  755. int j = 0; // current offset into buf
  756. if (name_len > 255) return -2;
  757. for (;;) {
  758. const char *const start = name;
  759. name = strchr(name, '.');
  760. if (!name) {
  761. const uint label_len = end - start;
  762. if (label_len > 63) return -1;
  763. buf[j++] = label_len;
  764. memcpy(buf + j, start, end - start);
  765. j += end - start;
  766. break;
  767. } else {
  768. // append length of the label.
  769. const uint label_len = name - start;
  770. if (label_len > 63) return -1;
  771. buf[j++] = label_len;
  772. memcpy(buf + j, start, name - start);
  773. j += name - start;
  774. // hop over the '.'
  775. name++;
  776. }
  777. }
  778. // the labels must be terminated by a 0.
  779. // It's possible that the name ended in a .
  780. // in which case the zero is already there
  781. if (!j || buf[j-1]) buf[j++] = 0;
  782. return j;
  783. }
  784. // Finds the length of a dns request for a DNS name of the given
  785. // length. The actual request may be smaller than the value returned
  786. // here
  787. static int
  788. eventdns_request_len(const int name_len) {
  789. return 96 + // length of the DNS standard header
  790. name_len + 2 +
  791. 4; // space for the resource type
  792. }
  793. // build a dns request packet into buf. buf should be at least as long
  794. // as eventdns_request_len told you it should be.
  795. //
  796. // Returns the amount of space used. Negative on error.
  797. static int
  798. eventdns_request_data_build(const char *const name, const int name_len, const u16 trans_id,
  799. const u16 type, const u16 class,
  800. u8 *const buf) {
  801. int j = 0; // current offset into buf
  802. u16 _t; // used by the macros
  803. #define APPEND16(x) do { _t = htons(x); memcpy(buf + j, &_t, 2); j += 2; } while(0);
  804. APPEND16(trans_id);
  805. APPEND16(0x0100); // standard query, recusion needed
  806. APPEND16(1); // one question
  807. APPEND16(0); // no answers
  808. APPEND16(0); // no authority
  809. APPEND16(0); // no additional
  810. u8 *labels = (u8 *) alloca(name_len + 2);
  811. const int labels_len = dnsname_to_labels(labels, name, name_len);
  812. if (labels_len < 0) return labels_len;
  813. memcpy(buf + j, labels, labels_len);
  814. j += labels_len;
  815. APPEND16(type);
  816. APPEND16(class);
  817. #undef APPEND16
  818. return j;
  819. }
  820. // this is a libevent callback function which is called when a request
  821. // has timed out.
  822. static void
  823. eventdns_request_timeout_callback(int fd, short events, void *arg) {
  824. struct request *const req = (struct request *) arg;
  825. log("Request %x timed out\n", (unsigned) arg);
  826. req->ns->timedout++;
  827. if (req->ns->timedout > global_max_nameserver_timeout) {
  828. nameserver_failed(req->ns);
  829. }
  830. evtimer_del(&req->timeout_event);
  831. if (req->tx_count >= global_max_retransmits) {
  832. // this request has failed
  833. req->user_callback(DNS_ERR_TIMEOUT, 0, 0, 0, NULL, req->user_pointer);
  834. request_finished(req, &req_head);
  835. } else {
  836. // retransmit it
  837. eventdns_request_transmit(req);
  838. }
  839. }
  840. // try to send a request to a given server.
  841. //
  842. // return:
  843. // 0 ok
  844. // 1 temporary failure
  845. // 2 other failure
  846. static int
  847. eventdns_request_transmit_to(struct request *req, struct nameserver *server) {
  848. const int r = send(server->socket, req->request, req->request_len, 0);
  849. if (r < 0) {
  850. if (errno == EAGAIN) return 1;
  851. return 2;
  852. } else if (r != req->request_len) {
  853. return 1; // short write
  854. } else {
  855. return 0;
  856. }
  857. }
  858. // try to send a request, updating the fields of the request
  859. // as needed
  860. //
  861. // return:
  862. // 0 ok
  863. // 1 failed
  864. static int
  865. eventdns_request_transmit(struct request *req) {
  866. int retcode = 0;
  867. // if we fail to send this packet then this flag marks it
  868. // for eventdns_transmit
  869. req->transmit_me = 1;
  870. if (req->trans_id == 0xffff) abort();
  871. if (req->ns->choaked) {
  872. // don't bother trying to write to a socket
  873. // which we have had EAGAIN from
  874. return 1;
  875. }
  876. const int r = eventdns_request_transmit_to(req, req->ns);
  877. switch (r) {
  878. case 1:
  879. // temp failure
  880. req->ns->choaked = 1;
  881. nameserver_write_waiting(req->ns, 1);
  882. return 1;
  883. case 2:
  884. // failed in some other way
  885. nameserver_failed(req->ns);
  886. retcode = 1;
  887. // fall through
  888. default:
  889. // all ok
  890. log("Setting timeout for %x\n", (unsigned) req);
  891. evtimer_set(&req->timeout_event, eventdns_request_timeout_callback, req);
  892. evtimer_add(&req->timeout_event, &global_timeout);
  893. req->tx_count++;
  894. req->transmit_me = 0;
  895. return retcode;
  896. }
  897. }
  898. static void
  899. nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
  900. struct nameserver *const ns = (struct nameserver *) arg;
  901. if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
  902. // this is a good reply
  903. nameserver_up(ns);
  904. } else nameserver_probe_failed(ns);
  905. }
  906. static void
  907. nameserver_send_probe(struct nameserver *const ns) {
  908. // here we need to send a probe to a given nameserver
  909. // in the hope that it is up now.
  910. log("Sending probe to %lx\n", (unsigned long)ns->address);
  911. struct request *const req = request_new("www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
  912. // we force this into the inflight queue no matter what
  913. request_trans_id_set(req, transaction_id_pick());
  914. req->ns = ns;
  915. request_submit(req);
  916. }
  917. // returns:
  918. // 0 didn't try to transmit anything
  919. // 1 tried to transmit something
  920. static int
  921. eventdns_transmit() {
  922. char did_try_to_transmit = 0;
  923. if (req_head) {
  924. struct request *const started_at = req_head, *req = req_head;
  925. // first transmit all the requests which are currently waiting
  926. do {
  927. if (req->transmit_me) {
  928. did_try_to_transmit = 1;
  929. eventdns_request_transmit(req);
  930. }
  931. req = req->next;
  932. } while (req != started_at);
  933. }
  934. return did_try_to_transmit;
  935. }
  936. // exported function
  937. int
  938. eventdns_nameserver_add(unsigned long int address) {
  939. // first check to see if we already have this nameserver
  940. const struct nameserver *server = server_head, *const started_at = server_head;
  941. if (server) {
  942. do {
  943. if (server->address == address) return 3;
  944. server = server->next;
  945. } while (server != started_at);
  946. }
  947. struct nameserver *ns = (struct nameserver *) malloc(sizeof(struct nameserver));
  948. struct sockaddr_in sin;
  949. int err = 0;
  950. memset(ns, 0, sizeof(struct nameserver));
  951. ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
  952. if (ns->socket < 0) { err = 1; goto out1; }
  953. fcntl(ns->socket, F_SETFL, O_NONBLOCK);
  954. sin.sin_addr.s_addr = address;
  955. sin.sin_port = htons(53);
  956. sin.sin_family = AF_INET;
  957. if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  958. err = 2;
  959. goto out2;
  960. }
  961. ns->address = address;
  962. ns->state = 1;
  963. event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
  964. event_add(&ns->event, NULL);
  965. // insert this nameserver into the list of them
  966. if (!server_head) {
  967. ns->next = ns->prev = ns;
  968. server_head = ns;
  969. } else {
  970. ns->next = server_head->next;
  971. ns->prev = server_head;
  972. server_head->next = ns;
  973. if (server_head->prev == server_head) {
  974. server_head->prev = ns;
  975. }
  976. }
  977. global_good_nameservers++;
  978. return 0;
  979. out2:
  980. close(ns->socket);
  981. out1:
  982. free(ns);
  983. return err;
  984. }
  985. // exported function
  986. int
  987. eventdns_nameserver_ip_add(const char *ip_as_string) {
  988. struct in_addr ina;
  989. if (!inet_aton(ip_as_string, &ina)) return 4;
  990. return eventdns_nameserver_add(ina.s_addr);
  991. }
  992. // insert into the tail of the queue
  993. static void
  994. eventdns_request_insert(struct request *req, struct request **head) {
  995. if (!*head) {
  996. *head = req;
  997. req->next = req->prev = req;
  998. return;
  999. }
  1000. req->prev = (*head)->prev;
  1001. req->prev->next = req;
  1002. req->next = *head;
  1003. (*head)->prev = req;
  1004. }
  1005. static int
  1006. string_num_dots(const char *s) {
  1007. int count = 0;
  1008. while ((s = strchr(s, '.'))) {
  1009. s++;
  1010. count++;
  1011. }
  1012. return count;
  1013. }
  1014. static struct request *
  1015. request_new(const char *name, int flags, eventdns_callback_type callback, void *ptr) {
  1016. const char issuing_now = (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
  1017. const int name_len = strlen(name);
  1018. const int request_max_len = eventdns_request_len(name_len);
  1019. const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
  1020. // the request data is alloced in a single block with the header
  1021. struct request *const req = (struct request *) malloc(sizeof(struct request) + request_max_len);
  1022. memset(req, 0, sizeof(struct request));
  1023. // request data lives just after the header
  1024. req->request = ((u8 *) req) + sizeof(struct request);
  1025. req->request_appended = 1; // denotes that the request data shouldn't be free()ed
  1026. req->request_len = eventdns_request_data_build(name, name_len, trans_id, TYPE_A, CLASS_INET, req->request);
  1027. if (req->request_len < 0) goto err1;
  1028. req->trans_id = trans_id;
  1029. req->tx_count = 0;
  1030. req->user_pointer = ptr;
  1031. req->user_callback = callback;
  1032. req->ns = issuing_now ? nameserver_pick() : NULL;
  1033. req->next = req->prev = NULL;
  1034. return req;
  1035. err1:
  1036. free(req->request);
  1037. return NULL;
  1038. }
  1039. static void
  1040. request_submit(struct request *const req) {
  1041. if (req->ns) {
  1042. // if it has a nameserver assigned then this is going
  1043. // straight into the inflight queue
  1044. eventdns_request_insert(req, &req_head);
  1045. global_requests_inflight++;
  1046. eventdns_request_transmit(req);
  1047. } else {
  1048. eventdns_request_insert(req, &req_waiting_head);
  1049. global_requests_waiting++;
  1050. }
  1051. }
  1052. // exported function
  1053. int eventdns_resolve(const char *name, int flags, eventdns_callback_type callback, void *ptr) {
  1054. log("resolve for %s\n", name);
  1055. if (flags & DNS_QUERY_NO_SEARCH) {
  1056. struct request *const req = request_new(name, flags, callback, ptr);
  1057. if (!req) return 1;
  1058. request_submit(req);
  1059. return 0;
  1060. } else {
  1061. return search_request_new(name, flags, callback, ptr);
  1062. }
  1063. }
  1064. /////////////////////////////////////////////////////////////////////
  1065. // Search support
  1066. //
  1067. // the libc resolver has support for searching a number of domains
  1068. // to find a name. If nothing else then it takes the single domain
  1069. // from the gethostname() call.
  1070. //
  1071. // It can also be configured via the domain and search options in a
  1072. // resolv.conf.
  1073. //
  1074. // The ndots option controls how many dots it takes for the resolver
  1075. // to decide that a name is non-local and so try a raw lookup first.
  1076. struct search_domain {
  1077. int len;
  1078. struct search_domain *next;
  1079. // the text string is appended to this structure
  1080. };
  1081. struct search_state {
  1082. int refcount;
  1083. int ndots;
  1084. int num_domains;
  1085. struct search_domain *head;
  1086. };
  1087. static struct search_state *global_search_state = NULL;
  1088. static void
  1089. search_state_decref(struct search_state *const state) {
  1090. if (!state) return;
  1091. state->refcount--;
  1092. if (!state->refcount) {
  1093. struct search_domain *next, *dom;
  1094. for (dom = state->head; dom; dom = next) {
  1095. next = dom->next;
  1096. free(dom);
  1097. }
  1098. free(state);
  1099. }
  1100. };
  1101. static struct search_state *
  1102. search_state_new() {
  1103. struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
  1104. memset(state, 0, sizeof(struct search_state));
  1105. state->refcount = 1;
  1106. state->ndots = 1;
  1107. return state;
  1108. }
  1109. static void
  1110. search_postfix_clear() {
  1111. search_state_decref(global_search_state);
  1112. global_search_state = search_state_new();
  1113. }
  1114. // exported function
  1115. void
  1116. eventdns_search_clear() {
  1117. search_postfix_clear();
  1118. }
  1119. static void
  1120. search_postfix_add(const char *domain) {
  1121. while (domain[0] == '.') domain++;
  1122. const int domain_len = strlen(domain);
  1123. if (!global_search_state) global_search_state = search_state_new();
  1124. global_search_state->num_domains++;
  1125. struct search_domain *sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
  1126. memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
  1127. sdomain->next = global_search_state->head;
  1128. sdomain->len = domain_len;
  1129. global_search_state->head = sdomain;
  1130. }
  1131. // reverse the order of members in the postfix list. This is needed because,
  1132. // when parsing resolv.conf we push elements in the wrong order
  1133. static void
  1134. search_reverse() {
  1135. struct search_domain *cur, *prev = NULL, *next;
  1136. cur = global_search_state->head;
  1137. while (cur) {
  1138. next = cur->next;
  1139. cur->next = prev;
  1140. prev = cur;
  1141. cur = next;
  1142. }
  1143. global_search_state->head = prev;
  1144. }
  1145. // exported function
  1146. void
  1147. eventdns_search_add(const char *domain) {
  1148. search_postfix_add(domain);
  1149. }
  1150. // exported function
  1151. void
  1152. eventdns_search_ndots_set(const int ndots) {
  1153. if (!global_search_state) global_search_state = search_state_new();
  1154. global_search_state->ndots = ndots;
  1155. }
  1156. static void
  1157. search_set_from_hostname() {
  1158. char hostname[HOST_NAME_MAX + 1];
  1159. search_postfix_clear();
  1160. if (gethostname(hostname, sizeof(hostname))) return;
  1161. char *domainname = strchr(hostname, '.');
  1162. if (!domainname) return;
  1163. search_postfix_add(domainname);
  1164. }
  1165. // warning: returns malloced string
  1166. static char *
  1167. search_make_new(const struct search_state *const state, int n, const char *const base_name) {
  1168. const int base_len = strlen(base_name);
  1169. const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
  1170. struct search_domain *dom;
  1171. for (dom = state->head; dom; dom = dom->next) {
  1172. if (!n--) {
  1173. // this is the postfix we want
  1174. // the actual postfix string is kept at the end of the structure
  1175. const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
  1176. const int postfix_len = dom->len;
  1177. char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
  1178. memcpy(newname, base_name, base_len);
  1179. if (need_to_append_dot) newname[base_len] = '.';
  1180. memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
  1181. newname[base_len + need_to_append_dot + postfix_len] = 0;
  1182. return newname;
  1183. }
  1184. }
  1185. // we ran off the end of the list and still didn't find the requested string
  1186. abort();
  1187. }
  1188. static int
  1189. search_request_new(const char *const name, int flags, eventdns_callback_type user_callback, void *user_arg) {
  1190. if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
  1191. global_search_state &&
  1192. global_search_state->num_domains) {
  1193. // we have some domains to search
  1194. struct request *req;
  1195. if (string_num_dots(name) >= global_search_state->ndots) {
  1196. req = request_new(name, flags, user_callback, user_arg);
  1197. if (!req) return 1;
  1198. req->search_index = -1;
  1199. } else {
  1200. char *const new_name = search_make_new(global_search_state, 0, name);
  1201. req = request_new(new_name, flags, user_callback, user_arg);
  1202. free(new_name);
  1203. if (!req) return 1;
  1204. req->search_index = 0;
  1205. }
  1206. req->search_origname = strdup(name);
  1207. req->search_state = global_search_state;
  1208. req->search_flags = flags;
  1209. global_search_state->refcount++;
  1210. request_submit(req);
  1211. return 0;
  1212. } else {
  1213. struct request *const req = request_new(name, flags, user_callback, user_arg);
  1214. if (!req) return 1;
  1215. request_submit(req);
  1216. return 0;
  1217. }
  1218. }
  1219. // this is called when a request has failed to find a name. We need to check
  1220. // if it is part of a search and, if so, try the next name in the list
  1221. // returns:
  1222. // 0 another request has been submitted
  1223. // 1 no more requests needed
  1224. static int
  1225. search_try_next(struct request *const req) {
  1226. if (req->search_state) {
  1227. // it is part of a search
  1228. req->search_index++;
  1229. if (req->search_index >= req->search_state->num_domains) {
  1230. // no more postfixes to try, however we may need to try
  1231. // this name without a postfix
  1232. if (string_num_dots(req->search_origname) < req->search_state->ndots) {
  1233. // yep, we need to try it raw
  1234. log("search: trying raw query %s\n", req->search_origname);
  1235. struct request *const newreq = request_new(req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
  1236. if (newreq) {
  1237. request_submit(newreq);
  1238. return 0;
  1239. }
  1240. }
  1241. return 1;
  1242. }
  1243. char *const new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
  1244. log("search: now trying %s (%d)\n", new_name, req->search_index);
  1245. struct request *const newreq = request_new(new_name, req->search_flags, req->user_callback, req->user_pointer);
  1246. free(new_name);
  1247. if (!newreq) return 1;
  1248. newreq->search_origname = req->search_origname;
  1249. req->search_origname = NULL;
  1250. newreq->search_state = req->search_state;
  1251. newreq->search_flags = req->search_flags;
  1252. newreq->search_index = req->search_index;
  1253. newreq->search_state->refcount++;
  1254. request_submit(newreq);
  1255. return 0;
  1256. }
  1257. return 1;
  1258. }
  1259. static void
  1260. search_request_finished(struct request *const req) {
  1261. if (req->search_state) {
  1262. search_state_decref(req->search_state);
  1263. req->search_state = NULL;
  1264. }
  1265. if (req->search_origname) {
  1266. free(req->search_origname);
  1267. req->search_origname = NULL;
  1268. }
  1269. }
  1270. /////////////////////////////////////////////////////////////////////
  1271. // Parsing resolv.conf files
  1272. static void
  1273. eventdns_resolv_set_defaults(int flags) {
  1274. // if the file isn't found then we assume a local resolver
  1275. if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
  1276. if (flags & DNS_OPTION_NAMESERVERS) eventdns_nameserver_ip_add("127.0.0.1");
  1277. }
  1278. #ifndef HAVE_STRTOK_R
  1279. static char *
  1280. strtok_r(char *s, const char *delim, char **state) {
  1281. return strtok(s, delim);
  1282. }
  1283. #endif
  1284. // helper version of atoi which returns -1 on error
  1285. static int
  1286. strtoint(const char *const str) {
  1287. char *endptr;
  1288. const int r = strtol(str, &endptr, 10);
  1289. if (*endptr) return -1;
  1290. return r;
  1291. }
  1292. static void
  1293. resolv_conf_parse_line(char *const start, int flags) {
  1294. char *strtok_state;
  1295. static const char *const delims = " \t";
  1296. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  1297. char *const first_token = strtok_r(start, delims, &strtok_state);
  1298. if (!first_token) return;
  1299. if (!strcmp(first_token, "nameserver")) {
  1300. const char *const nameserver = NEXT_TOKEN;
  1301. struct in_addr ina;
  1302. if (inet_aton(nameserver, &ina)) {
  1303. // address is valid
  1304. eventdns_nameserver_add(ina.s_addr);
  1305. }
  1306. } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
  1307. const char *const domain = NEXT_TOKEN;
  1308. if (domain) {
  1309. search_postfix_clear();
  1310. search_postfix_add(domain);
  1311. }
  1312. } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
  1313. search_postfix_clear();
  1314. const char *domain;
  1315. while ((domain = NEXT_TOKEN)) {
  1316. search_postfix_add(domain);
  1317. }
  1318. search_reverse();
  1319. } else if (!strcmp(first_token, "options")) {
  1320. const char *option;
  1321. while ((option = NEXT_TOKEN)) {
  1322. if (!strncmp(option, "ndots:", 6)) {
  1323. const int ndots = strtoint(&option[6]);
  1324. if (ndots == -1) continue;
  1325. if (!(flags & DNS_OPTION_SEARCH)) continue;
  1326. log("setting ndots to %d\n", ndots);
  1327. if (!global_search_state) global_search_state = search_state_new();
  1328. global_search_state->ndots = ndots;
  1329. } else if (!strncmp(option, "timeout:", 8)) {
  1330. const int timeout = strtoint(&option[8]);
  1331. if (timeout == -1) continue;
  1332. if (!(flags & DNS_OPTION_MISC)) continue;
  1333. log("setting timeout to %d\n", timeout);
  1334. global_timeout.tv_sec = timeout;
  1335. } else if (!strncmp(option, "attempts:", 9)) {
  1336. const int retries = strtoint(&option[9]);
  1337. if (retries == -1) continue;
  1338. if (!(flags & DNS_OPTION_MISC)) continue;
  1339. log("setting retries to %d\n", retries);
  1340. global_max_retransmits = retries;
  1341. }
  1342. }
  1343. }
  1344. #undef NEXT_TOKEN
  1345. }
  1346. // exported function
  1347. // returns:
  1348. // 0 no errors
  1349. // 1 failed to open file
  1350. // 2 failed to stat file
  1351. // 3 file too large
  1352. // 4 out of memory
  1353. // 5 short read from file
  1354. int
  1355. eventdns_resolv_conf_parse(int flags, const char *const filename) {
  1356. struct stat st;
  1357. int err = 0;
  1358. log("parsing resolve file %s\n", filename);
  1359. const int fd = open(filename, O_RDONLY);
  1360. if (fd < 0) {
  1361. eventdns_resolv_set_defaults(flags);
  1362. return 0;
  1363. }
  1364. if (fstat(fd, &st)) { err = 2; goto out1; }
  1365. if (!st.st_size) {
  1366. eventdns_resolv_set_defaults(flags);
  1367. err = 0;
  1368. goto out1;
  1369. }
  1370. if (st.st_size > 65535) { err = 3; goto out1; } // no resolv.conf should be any bigger
  1371. u8 *const resolv = (u8 *) malloc(st.st_size + 1);
  1372. if (!resolv) { err = 4; goto out1; }
  1373. if (read(fd, resolv, st.st_size) != st.st_size) { err = 5; goto out2; }
  1374. resolv[st.st_size] = 0; // we malloced an extra byte
  1375. char *start = (char *) resolv;
  1376. for (;;) {
  1377. char *const newline = strchr(start, '\n');
  1378. if (!newline) {
  1379. resolv_conf_parse_line(start, flags);
  1380. break;
  1381. } else {
  1382. *newline = 0;
  1383. resolv_conf_parse_line(start, flags);
  1384. start = newline + 1;
  1385. }
  1386. }
  1387. if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
  1388. // no nameservers were configured.
  1389. eventdns_nameserver_ip_add("127.0.0.1");
  1390. }
  1391. if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
  1392. search_set_from_hostname();
  1393. }
  1394. out2:
  1395. free(resolv);
  1396. out1:
  1397. close(fd);
  1398. return err;
  1399. }