evdns.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /*
  2. * Copyright (c) 2006 Niels Provos <provos@citi.umich.edu>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  17. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  18. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  19. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  21. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  25. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. /*
  28. * The original DNS code is due to Adam Langley with heavy
  29. * modifications by Nick Mathewson. Adam put his DNS software in the
  30. * public domain. You can find his original copyright below. Please,
  31. * aware that the code as part of libevent is governed by the 3-clause
  32. * BSD license above.
  33. *
  34. * This software is Public Domain. To view a copy of the public domain dedication,
  35. * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
  36. * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
  37. *
  38. * I ask and expect, but do not require, that all derivative works contain an
  39. * attribution similar to:
  40. * Parts developed by Adam Langley <agl@imperialviolet.org>
  41. *
  42. * You may wish to replace the word "Parts" with something else depending on
  43. * the amount of original code.
  44. *
  45. * (Derivative works does not include programs which link against, run or include
  46. * the source verbatim in their source distributions)
  47. */
  48. /** @file evdns.h
  49. *
  50. * Welcome, gentle reader
  51. *
  52. * Async DNS lookups are really a whole lot harder than they should be,
  53. * mostly stemming from the fact that the libc resolver has never been
  54. * very good at them. Before you use this library you should see if libc
  55. * can do the job for you with the modern async call getaddrinfo_a
  56. * (see http://www.imperialviolet.org/page25.html#e498). Otherwise,
  57. * please continue.
  58. *
  59. * This code is based on libevent and you must call event_init before
  60. * any of the APIs in this file. You must also seed the OpenSSL random
  61. * source if you are using OpenSSL for ids (see below).
  62. *
  63. * This library is designed to be included and shipped with your source
  64. * code. You statically link with it. You should also test for the
  65. * existence of strtok_r and define HAVE_STRTOK_R if you have it.
  66. *
  67. * The DNS protocol requires a good source of id numbers and these
  68. * numbers should be unpredictable for spoofing reasons. There are
  69. * three methods for generating them here and you must define exactly
  70. * one of them. In increasing order of preference:
  71. *
  72. * DNS_USE_GETTIMEOFDAY_FOR_ID:
  73. * Using the bottom 16 bits of the usec result from gettimeofday. This
  74. * is a pretty poor solution but should work anywhere.
  75. * DNS_USE_CPU_CLOCK_FOR_ID:
  76. * Using the bottom 16 bits of the nsec result from the CPU's time
  77. * counter. This is better, but may not work everywhere. Requires
  78. * POSIX realtime support and you'll need to link against -lrt on
  79. * glibc systems at least.
  80. * DNS_USE_OPENSSL_FOR_ID:
  81. * Uses the OpenSSL RAND_bytes call to generate the data. You must
  82. * have seeded the pool before making any calls to this library.
  83. *
  84. * The library keeps track of the state of nameservers and will avoid
  85. * them when they go down. Otherwise it will round robin between them.
  86. *
  87. * Quick start guide:
  88. * #include "evdns.h"
  89. * void callback(int result, char type, int count, int ttl,
  90. * void *addresses, void *arg);
  91. * evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  92. * evdns_resolve("www.hostname.com", 0, callback, NULL);
  93. *
  94. * When the lookup is complete the callback function is called. The
  95. * first argument will be one of the DNS_ERR_* defines in evdns.h.
  96. * Hopefully it will be DNS_ERR_NONE, in which case type will be
  97. * DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
  98. * which the data can be cached for (in seconds), addresses will point
  99. * to an array of uint32_t's and arg will be whatever you passed to
  100. * evdns_resolve.
  101. *
  102. * Searching:
  103. *
  104. * In order for this library to be a good replacement for glibc's resolver it
  105. * supports searching. This involves setting a list of default domains, in
  106. * which names will be queried for. The number of dots in the query name
  107. * determines the order in which this list is used.
  108. *
  109. * Searching appears to be a single lookup from the point of view of the API,
  110. * although many DNS queries may be generated from a single call to
  111. * evdns_resolve. Searching can also drastically slow down the resolution
  112. * of names.
  113. *
  114. * To disable searching:
  115. * 1. Never set it up. If you never call evdns_resolv_conf_parse or
  116. * evdns_search_add then no searching will occur.
  117. *
  118. * 2. If you do call evdns_resolv_conf_parse then don't pass
  119. * DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
  120. *
  121. * 3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag.
  122. *
  123. * The order of searches depends on the number of dots in the name. If the
  124. * number is greater than the ndots setting then the names is first tried
  125. * globally. Otherwise each search domain is appended in turn.
  126. *
  127. * The ndots setting can either be set from a resolv.conf, or by calling
  128. * evdns_search_ndots_set.
  129. *
  130. * For example, with ndots set to 1 (the default) and a search domain list of
  131. * ["myhome.net"]:
  132. * Query: www
  133. * Order: www.myhome.net, www.
  134. *
  135. * Query: www.abc
  136. * Order: www.abc., www.abc.myhome.net
  137. *
  138. * Internals:
  139. *
  140. * Requests are kept in two queues. The first is the inflight queue. In
  141. * this queue requests have an allocated transaction id and nameserver.
  142. * They will soon be transmitted if they haven't already been.
  143. *
  144. * The second is the waiting queue. The size of the inflight ring is
  145. * limited and all other requests wait in waiting queue for space. This
  146. * bounds the number of concurrent requests so that we don't flood the
  147. * nameserver. Several algorithms require a full walk of the inflight
  148. * queue and so bounding its size keeps thing going nicely under huge
  149. * (many thousands of requests) loads.
  150. *
  151. * If a nameserver loses too many requests it is considered down and we
  152. * try not to use it. After a while we send a probe to that nameserver
  153. * (a lookup for google.com) and, if it replies, we consider it working
  154. * again. If the nameserver fails a probe we wait longer to try again
  155. * with the next probe.
  156. */
  157. #ifndef EVENTDNS_H
  158. #define EVENTDNS_H
  159. #ifdef __cplusplus
  160. extern "C" {
  161. #endif
  162. /* For integer types. */
  163. #include "evutil.h"
  164. /** Error codes 0-5 are as described in RFC 1035. */
  165. #define DNS_ERR_NONE 0
  166. /** The name server was unable to interpret the query */
  167. #define DNS_ERR_FORMAT 1
  168. /** The name server was unable to process this query due to a problem with the
  169. * name server */
  170. #define DNS_ERR_SERVERFAILED 2
  171. /** The domain name does not exist */
  172. #define DNS_ERR_NOTEXIST 3
  173. /** The name server does not support the requested kind of query */
  174. #define DNS_ERR_NOTIMPL 4
  175. /** The name server refuses to reform the specified operation for policy
  176. * reasons */
  177. #define DNS_ERR_REFUSED 5
  178. /** The reply was truncated or ill-formated */
  179. #define DNS_ERR_TRUNCATED 65
  180. /** An unknown error occurred */
  181. #define DNS_ERR_UNKNOWN 66
  182. /** Communication with the server timed out */
  183. #define DNS_ERR_TIMEOUT 67
  184. /** The request was canceled because the DNS subsystem was shut down. */
  185. #define DNS_ERR_SHUTDOWN 68
  186. #define DNS_IPv4_A 1
  187. #define DNS_PTR 2
  188. #define DNS_IPv6_AAAA 3
  189. #define DNS_QUERY_NO_SEARCH 1
  190. #define DNS_OPTION_SEARCH 1
  191. #define DNS_OPTION_NAMESERVERS 2
  192. #define DNS_OPTION_MISC 4
  193. #define DNS_OPTIONS_ALL 7
  194. /**
  195. * The callback that contains the results from a lookup.
  196. * - type is either DNS_IPv4_A or DNS_PTR or DNS_IPv6_AAAA
  197. * - count contains the number of addresses of form type
  198. * - ttl is the number of seconds the resolution may be cached for.
  199. * - addresses needs to be cast according to type
  200. */
  201. typedef void (*evdns_callback_type) (int result, char type, int count, int ttl, void *addresses, void *arg);
  202. /**
  203. Initialize the asynchronous DNS library.
  204. This function initializes support for non-blocking name resolution by
  205. calling evdns_resolv_conf_parse() on UNIX and
  206. evdns_config_windows_nameservers() on Windows.
  207. @return 0 if successful, or -1 if an error occurred
  208. @see evdns_shutdown()
  209. */
  210. int evdns_init(void);
  211. /**
  212. Shut down the asynchronous DNS resolver and terminate all active requests.
  213. If the 'fail_requests' option is enabled, all active requests will return
  214. an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
  215. the requests will be silently discarded.
  216. @param fail_requests if zero, active requests will be aborted; if non-zero,
  217. active requests will return DNS_ERR_SHUTDOWN.
  218. @see evdns_init()
  219. */
  220. void evdns_shutdown(int fail_requests);
  221. /**
  222. Convert a DNS error code to a string.
  223. @param err the DNS error code
  224. @return a string containing an explanation of the error code
  225. */
  226. const char *evdns_err_to_string(int err);
  227. /**
  228. Add a nameserver.
  229. The address should be an IPv4 address in network byte order.
  230. The type of address is chosen so that it matches in_addr.s_addr.
  231. @param address an IP address in network byte order
  232. @return 0 if successful, or -1 if an error occurred
  233. @see evdns_nameserver_ip_add()
  234. */
  235. int evdns_nameserver_add(unsigned long int address);
  236. /**
  237. Get the number of configured nameservers.
  238. This returns the number of configured nameservers (not necessarily the
  239. number of running nameservers). This is useful for double-checking
  240. whether our calls to the various nameserver configuration functions
  241. have been successful.
  242. @return the number of configured nameservers
  243. @see evdns_nameserver_add()
  244. */
  245. int evdns_count_nameservers(void);
  246. /**
  247. Remove all configured nameservers, and suspend all pending resolves.
  248. Resolves will not necessarily be re-attempted until evdns_resume() is called.
  249. @return 0 if successful, or -1 if an error occurred
  250. @see evdns_resume()
  251. */
  252. int evdns_clear_nameservers_and_suspend(void);
  253. /**
  254. Resume normal operation and continue any suspended resolve requests.
  255. Re-attempt resolves left in limbo after an earlier call to
  256. evdns_clear_nameservers_and_suspend().
  257. @return 0 if successful, or -1 if an error occurred
  258. @see evdns_clear_nameservers_and_suspend()
  259. */
  260. int evdns_resume(void);
  261. /**
  262. Add a nameserver.
  263. This wraps the evdns_nameserver_add() function by parsing a string as an IP
  264. address and adds it as a nameserver.
  265. @return 0 if successful, or -1 if an error occurred
  266. @see evdns_nameserver_add()
  267. */
  268. int evdns_nameserver_ip_add(const char *ip_as_string);
  269. /**
  270. Lookup an A record for a given name.
  271. @param name a DNS hostname
  272. @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
  273. @param callback a callback function to invoke when the request is completed
  274. @param ptr an argument to pass to the callback function
  275. @return 0 if successful, or -1 if an error occurred
  276. @see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
  277. */
  278. int evdns_resolve_ipv4(const char *name, int flags, evdns_callback_type callback, void *ptr);
  279. /**
  280. Lookup an AAAA record for a given name.
  281. @param name a DNS hostname
  282. @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
  283. @param callback a callback function to invoke when the request is completed
  284. @param ptr an argument to pass to the callback function
  285. @return 0 if successful, or -1 if an error occurred
  286. @see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
  287. */
  288. int evdns_resolve_ipv6(const char *name, int flags, evdns_callback_type callback, void *ptr);
  289. struct in_addr;
  290. struct in6_addr;
  291. /**
  292. Lookup a PTR record for a given IP address.
  293. @param in an IPv4 address
  294. @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
  295. @param callback a callback function to invoke when the request is completed
  296. @param ptr an argument to pass to the callback function
  297. @return 0 if successful, or -1 if an error occurred
  298. @see evdns_resolve_reverse_ipv6()
  299. */
  300. int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
  301. /**
  302. Lookup a PTR record for a given IPv6 address.
  303. @param in an IPv6 address
  304. @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
  305. @param callback a callback function to invoke when the request is completed
  306. @param ptr an argument to pass to the callback function
  307. @return 0 if successful, or -1 if an error occurred
  308. @see evdns_resolve_reverse_ipv6()
  309. */
  310. int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
  311. /**
  312. Set the value of a configuration option.
  313. The currently available configuration options are:
  314. ndots, timeout, max-timeouts, max-inflight, and attempts
  315. @param option the name of the configuration option to be modified
  316. @param val the value to be set
  317. @param flags either 0 | DNS_OPTION_SEARCH | DNS_OPTION_MISC
  318. @return 0 if successful, or -1 if an error occurred
  319. */
  320. int evdns_set_option(const char *option, const char *val, int flags);
  321. /**
  322. Parse a resolv.conf file.
  323. The 'flags' parameter determines what information is parsed from the
  324. resolv.conf file. See the man page for resolv.conf for the format of this
  325. file.
  326. The following directives are not parsed from the file: sortlist, rotate,
  327. no-check-names, inet6, debug.
  328. If this function encounters an error, the possible return values are: 1 =
  329. failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
  330. memory, 5 = short read from file, 6 = no nameservers listed in the file
  331. @param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
  332. DNS_OPTIONS_ALL
  333. @param filename the path to the resolv.conf file
  334. @return 0 if successful, or various positive error codes if an error
  335. occurred (see above)
  336. @see resolv.conf(3), evdns_config_windows_nameservers()
  337. */
  338. int evdns_resolv_conf_parse(int flags, const char *const filename);
  339. /**
  340. Obtain nameserver information using the Windows API.
  341. Attempt to configure a set of nameservers based on platform settings on
  342. a win32 host. Preferentially tries to use GetNetworkParams; if that fails,
  343. looks in the registry.
  344. @return 0 if successful, or -1 if an error occurred
  345. @see evdns_resolv_conf_parse()
  346. */
  347. #ifdef WIN32
  348. int evdns_config_windows_nameservers(void);
  349. #endif
  350. /**
  351. Clear the list of search domains.
  352. */
  353. void evdns_search_clear(void);
  354. /**
  355. Add a domain to the list of search domains
  356. @param domain the domain to be added to the search list
  357. */
  358. void evdns_search_add(const char *domain);
  359. /**
  360. Set the 'ndots' parameter for searches.
  361. Sets the number of dots which, when found in a name, causes
  362. the first query to be without any search domain.
  363. @param ndots the new ndots parameter
  364. */
  365. void evdns_search_ndots_set(const int ndots);
  366. /**
  367. A callback that is invoked when a log message is generated
  368. @param is_warning indicates if the log message is a 'warning'
  369. @param msg the content of the log message
  370. */
  371. typedef void (*evdns_debug_log_fn_type)(int is_warning, const char *msg);
  372. /**
  373. Set the callback function to handle log messages.
  374. @param fn the callback to be invoked when a log message is generated
  375. */
  376. void evdns_set_log_fn(evdns_debug_log_fn_type fn);
  377. /**
  378. Set a callback that will be invoked to generate transaction IDs. By
  379. default, we pick transaction IDs based on the current clock time.
  380. @param fn the new callback, or NULL to use the default.
  381. */
  382. void evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void));
  383. #define DNS_NO_SEARCH 1
  384. /*
  385. * Structures and functions used to implement a DNS server.
  386. */
  387. struct evdns_server_request {
  388. int flags;
  389. int nquestions;
  390. struct evdns_server_question **questions;
  391. };
  392. struct evdns_server_question {
  393. int type;
  394. #ifdef __cplusplus
  395. int dns_question_class;
  396. #else
  397. /* You should refer to this field as "dns_question_class". The
  398. * name "class" works in C for backward compatibility, and will be
  399. * removed in a future version. (1.5 or later). */
  400. int class;
  401. #define dns_question_class class
  402. #endif
  403. char name[1];
  404. };
  405. typedef void (*evdns_request_callback_fn_type)(struct evdns_server_request *, void *);
  406. #define EVDNS_ANSWER_SECTION 0
  407. #define EVDNS_AUTHORITY_SECTION 1
  408. #define EVDNS_ADDITIONAL_SECTION 2
  409. #define EVDNS_TYPE_A 1
  410. #define EVDNS_TYPE_NS 2
  411. #define EVDNS_TYPE_CNAME 5
  412. #define EVDNS_TYPE_SOA 6
  413. #define EVDNS_TYPE_PTR 12
  414. #define EVDNS_TYPE_MX 15
  415. #define EVDNS_TYPE_TXT 16
  416. #define EVDNS_TYPE_AAAA 28
  417. #define EVDNS_QTYPE_AXFR 252
  418. #define EVDNS_QTYPE_ALL 255
  419. #define EVDNS_CLASS_INET 1
  420. struct evdns_server_port *evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type callback, void *user_data);
  421. void evdns_close_server_port(struct evdns_server_port *port);
  422. int evdns_server_request_add_reply(struct evdns_server_request *req, int section, const char *name, int type, int dns_class, int ttl, int datalen, int is_name, const char *data);
  423. int evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl);
  424. int evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl);
  425. int evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl);
  426. int evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl);
  427. int evdns_server_request_respond(struct evdns_server_request *req, int err);
  428. int evdns_server_request_drop(struct evdns_server_request *req);
  429. struct sockaddr;
  430. int evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len);
  431. #ifdef __cplusplus
  432. }
  433. #endif
  434. #endif /* !EVENTDNS_H */