A clone of btpd with my configuration changes.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3088 lines
81 KiB

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