A clone of btpd with my configuration changes.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

2179 строки
57 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. //#define NDEBUG
  39. #ifndef DNS_USE_CPU_CLOCK_FOR_ID
  40. #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
  41. #ifndef DNS_USE_OPENSSL_FOR_ID
  42. #error Must configure at least one id generation method.
  43. #error Please see the documentation.
  44. #endif
  45. #endif
  46. #endif
  47. // #define _POSIX_C_SOURCE 200507
  48. #define _GNU_SOURCE
  49. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  50. #ifdef DNS_USE_OPENSSL_FOR_ID
  51. #error Multiple id options selected
  52. #endif
  53. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  54. #error Multiple id options selected
  55. #endif
  56. #include <time.h>
  57. #endif
  58. #ifdef DNS_USE_OPENSSL_FOR_ID
  59. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  60. #error Multiple id options selected
  61. #endif
  62. #include <openssl/rand.h>
  63. #endif
  64. #define _FORTIFY_SOURCE 3
  65. #include <string.h>
  66. #include <fcntl.h>
  67. #include <sys/time.h>
  68. #include <stdint.h>
  69. #include <stdlib.h>
  70. #include <string.h>
  71. #include <errno.h>
  72. #include <assert.h>
  73. #include <unistd.h>
  74. #include <limits.h>
  75. #include <sys/stat.h>
  76. #include <ctype.h>
  77. #include <stdio.h>
  78. #include <stdarg.h>
  79. #include "evdns.h"
  80. #include "log.h"
  81. #ifdef WIN32
  82. #include <windows.h>
  83. #include <winsock2.h>
  84. #include <iphlpapi.h>
  85. #else
  86. #include <sys/socket.h>
  87. #include <netinet/in.h>
  88. #include <arpa/inet.h>
  89. #endif
  90. #define EVDNS_LOG_DEBUG 0
  91. #define EVDNS_LOG_WARN 1
  92. #ifndef HOST_NAME_MAX
  93. #define HOST_NAME_MAX 255
  94. #endif
  95. #ifndef NDEBUG
  96. #include <stdio.h>
  97. #endif
  98. #undef MIN
  99. #define MIN(a,b) ((a)<(b)?(a):(b))
  100. #ifdef __USE_ISOC99B
  101. // libevent doesn't work without this
  102. typedef uint8_t u_char;
  103. typedef unsigned int uint;
  104. #endif
  105. #include <event.h>
  106. #define u64 uint64_t
  107. #define u32 uint32_t
  108. #define u16 uint16_t
  109. #define u8 uint8_t
  110. #define MAX_ADDRS 4 // maximum number of addresses from a single packet
  111. // which we bother recording
  112. #define TYPE_A 1
  113. #define TYPE_CNAME 5
  114. #define TYPE_PTR 12
  115. #define TYPE_AAAA 28
  116. #define CLASS_INET 1
  117. struct request {
  118. u8 *request; // the dns packet data
  119. unsigned int request_len;
  120. int reissue_count;
  121. int tx_count; // the number of times that this packet has been sent
  122. unsigned int request_type; // TYPE_PTR or TYPE_A
  123. void *user_pointer; // the pointer given to us for this request
  124. evdns_callback_type user_callback;
  125. struct nameserver *ns; // the server which we last sent it
  126. // elements used by the searching code
  127. int search_index;
  128. struct search_state *search_state;
  129. char *search_origname; // needs to be free()ed
  130. int search_flags;
  131. // these objects are kept in a circular list
  132. struct request *next, *prev;
  133. struct event timeout_event;
  134. u16 trans_id; // the transaction id
  135. char request_appended; // true if the request pointer is data which follows this struct
  136. char transmit_me; // needs to be transmitted
  137. };
  138. struct reply {
  139. unsigned int type;
  140. unsigned int have_answer;
  141. union {
  142. struct {
  143. u32 addrcount;
  144. u32 addresses[MAX_ADDRS];
  145. } a;
  146. struct {
  147. char name[HOST_NAME_MAX];
  148. } ptr;
  149. } data;
  150. };
  151. struct nameserver {
  152. int socket; // a connected UDP socket
  153. u32 address;
  154. int failed_times; // number of times which we have given this server a chance
  155. int timedout; // number of times in a row a request has timed out
  156. struct event event;
  157. // these objects are kept in a circular list
  158. struct nameserver *next, *prev;
  159. struct event timeout_event; // used to keep the timeout for
  160. // when we next probe this server.
  161. // Valid if state == 0
  162. char state; // zero if we think that this server is down
  163. char choaked; // true if we have an EAGAIN from this server's socket
  164. char write_waiting; // true if we are waiting for EV_WRITE events
  165. };
  166. static struct request *req_head = NULL, *req_waiting_head = NULL;
  167. static struct nameserver *server_head = NULL;
  168. // The number of good nameservers that we have
  169. static int global_good_nameservers = 0;
  170. // inflight requests are contained in the req_head list
  171. // and are actually going out across the network
  172. static int global_requests_inflight = 0;
  173. // requests which aren't inflight are in the waiting list
  174. // and are counted here
  175. static int global_requests_waiting = 0;
  176. static int global_max_requests_inflight = 64;
  177. static struct timeval global_timeout = {3, 0}; // 3 seconds
  178. static int global_max_reissues = 1; // a reissue occurs when we get some errors from the server
  179. static int global_max_retransmits = 3; // number of times we'll retransmit a request which timed out
  180. // number of timeouts in a row before we consider this server to be down
  181. static int global_max_nameserver_timeout = 3;
  182. // These are the timeout values for nameservers. If we find a nameserver is down
  183. // we try to probe it at intervals as given below. Values are in seconds.
  184. static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
  185. static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
  186. 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"};
  187. static struct nameserver *nameserver_pick(void);
  188. static void evdns_request_insert(struct request *req, struct request **head);
  189. static void nameserver_ready_callback(int fd, short events, void *arg);
  190. static int evdns_transmit(void);
  191. static int evdns_request_transmit(struct request *req);
  192. static void nameserver_send_probe(struct nameserver *const ns);
  193. static void search_request_finished(struct request *const);
  194. static int search_try_next(struct request *const req);
  195. static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
  196. static void evdns_requests_pump_waiting_queue(void);
  197. static u16 transaction_id_pick(void);
  198. static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
  199. static void request_submit(struct request *req);
  200. #ifdef MS_WINDOWS
  201. static int
  202. last_error(int sock)
  203. {
  204. int optval, optvallen=sizeof(optval);
  205. int err = WSAGetLastError();
  206. if (err == WSAEWOULDBLOCK && sock >= 0) {
  207. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
  208. &optvallen))
  209. return err;
  210. if (optval)
  211. return optval;
  212. }
  213. return err;
  214. }
  215. static int
  216. error_is_eagain(int err)
  217. {
  218. return err == EAGAIN || err == WSAEWOULDBLOCK;
  219. }
  220. static int
  221. inet_aton(const char *c, struct in_addr *addr)
  222. {
  223. uint32_t r;
  224. if (strcmp(c, "255.255.255.255") == 0) {
  225. addr->s_addr = 0xffffffffu;
  226. } else {
  227. r = inet_addr(c);
  228. if (r == INADDR_NONE)
  229. return 0;
  230. addr->s_addr = r;
  231. }
  232. return 1;
  233. }
  234. #define CLOSE_SOCKET(x) closesocket(x)
  235. #else
  236. #define last_error(sock) (errno)
  237. #define error_is_eagain(err) ((err) == EAGAIN)
  238. #define CLOSE_SOCKET(x) close(x)
  239. #endif
  240. #define ISSPACE(c) isspace((int)(unsigned char)(c))
  241. #define ISDIGIT(c) isdigit((int)(unsigned char)(c))
  242. #ifndef NDEBUG
  243. static const char *
  244. debug_ntoa(u32 address)
  245. {
  246. static char buf[32];
  247. u32 a = ntohl(address);
  248. sprintf(buf, "%d.%d.%d.%d",
  249. (int)(u8)((a>>24)&0xff),
  250. (int)(u8)((a>>16)&0xff),
  251. (int)(u8)((a>>8 )&0xff),
  252. (int)(u8)((a )&0xff));
  253. return buf;
  254. }
  255. #endif
  256. static evdns_debug_log_fn_type evdns_log_fn = NULL;
  257. void
  258. evdns_set_log_fn(evdns_debug_log_fn_type fn)
  259. {
  260. evdns_log_fn = fn;
  261. }
  262. #ifdef __GNUC__
  263. #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
  264. #else
  265. #define EVDNS_LOG_CHECK
  266. #endif
  267. static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
  268. static void
  269. _evdns_log(int warn, const char *fmt, ...)
  270. {
  271. va_list args;
  272. static char buf[512];
  273. if (!evdns_log_fn)
  274. return;
  275. va_start(args,fmt);
  276. #ifdef MS_WINDOWS
  277. _vsnprintf(buf, sizeof(buf), fmt, args);
  278. #else
  279. vsnprintf(buf, sizeof(buf), fmt, args);
  280. #endif
  281. buf[sizeof(buf)-1] = '\0';
  282. evdns_log_fn(warn, buf);
  283. va_end(args);
  284. }
  285. #define log _evdns_log
  286. // This walks the list of inflight requests to find the
  287. // one with a matching transaction id. Returns NULL on
  288. // failure
  289. static struct request *
  290. request_find_from_trans_id(u16 trans_id) {
  291. struct request *req = req_head, *const started_at = req_head;
  292. if (req) {
  293. do {
  294. if (req->trans_id == trans_id) return req;
  295. req = req->next;
  296. } while (req != started_at);
  297. }
  298. return NULL;
  299. }
  300. // a libevent callback function which is called when a nameserver
  301. // has gone down and we want to test if it has came back to life yet
  302. static void
  303. nameserver_prod_callback(int fd, short events, void *arg) {
  304. struct nameserver *const ns = (struct nameserver *) arg;
  305. (void)fd;
  306. (void)events;
  307. nameserver_send_probe(ns);
  308. }
  309. // a libevent callback which is called when a nameserver probe (to see if
  310. // it has come back to life) times out. We increment the count of failed_times
  311. // and wait longer to send the next probe packet.
  312. static void
  313. nameserver_probe_failed(struct nameserver *const ns) {
  314. const struct timeval * timeout;
  315. (void) evtimer_del(&ns->timeout_event);
  316. if (ns->state == 1) {
  317. // This can happen if the nameserver acts in a way which makes us mark
  318. // it as bad and then starts sending good replies.
  319. return;
  320. }
  321. timeout =
  322. &global_nameserver_timeouts[MIN(ns->failed_times,
  323. global_nameserver_timeouts_length - 1)];
  324. ns->failed_times++;
  325. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  326. if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
  327. log(EVDNS_LOG_WARN,
  328. "Error from libevent when adding timer event for %s",
  329. debug_ntoa(ns->address));
  330. // ???? Do more?
  331. }
  332. }
  333. // called when a nameserver has been deemed to have failed. For example, too
  334. // many packets have timed out etc
  335. static void
  336. nameserver_failed(struct nameserver *const ns, const char *msg) {
  337. struct request *req, *started_at;
  338. // if this nameserver has already been marked as failed
  339. // then don't do anything
  340. if (!ns->state) return;
  341. log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
  342. debug_ntoa(ns->address), msg);
  343. global_good_nameservers--;
  344. assert(global_good_nameservers >= 0);
  345. if (global_good_nameservers == 0) {
  346. log(EVDNS_LOG_WARN, "All nameservers have failed");
  347. }
  348. ns->state = 0;
  349. ns->failed_times = 1;
  350. evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
  351. if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
  352. log(EVDNS_LOG_WARN,
  353. "Error from libevent when adding timer event for %s",
  354. debug_ntoa(ns->address));
  355. // ???? Do more?
  356. }
  357. // walk the list of inflight requests to see if any can be reassigned to
  358. // a different server. Requests in the waiting queue don't have a
  359. // nameserver assigned yet
  360. // if we don't have *any* good nameservers then there's no point
  361. // trying to reassign requests to one
  362. if (!global_good_nameservers) return;
  363. req = req_head;
  364. started_at = req_head;
  365. if (req) {
  366. do {
  367. if (req->tx_count == 0 && req->ns == ns) {
  368. // still waiting to go out, can be moved
  369. // to another server
  370. req->ns = nameserver_pick();
  371. }
  372. req = req->next;
  373. } while (req != started_at);
  374. }
  375. }
  376. static void
  377. nameserver_up(struct nameserver *const ns) {
  378. if (ns->state) return;
  379. log(EVDNS_LOG_WARN, "Nameserver %s is back up",
  380. debug_ntoa(ns->address));
  381. evtimer_del(&ns->timeout_event);
  382. ns->state = 1;
  383. ns->failed_times = 0;
  384. global_good_nameservers++;
  385. }
  386. static void
  387. request_trans_id_set(struct request *const req, const u16 trans_id) {
  388. req->trans_id = trans_id;
  389. *((u16 *) req->request) = htons(trans_id);
  390. }
  391. // Called to remove a request from a list and dealloc it.
  392. // head is a pointer to the head of the list it should be
  393. // removed from or NULL if the request isn't in a list.
  394. static void
  395. request_finished(struct request *const req, struct request **head) {
  396. if (head) {
  397. if (req->next == req) {
  398. // only item in the list
  399. *head = NULL;
  400. } else {
  401. req->next->prev = req->prev;
  402. req->prev->next = req->next;
  403. if (*head == req) *head = req->next;
  404. }
  405. }
  406. log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
  407. (unsigned long) req);
  408. evtimer_del(&req->timeout_event);
  409. search_request_finished(req);
  410. global_requests_inflight--;
  411. if (!req->request_appended) {
  412. // need to free the request data on it's own
  413. free(req->request);
  414. } else {
  415. // the request data is appended onto the header
  416. // so everything gets free()ed when we:
  417. }
  418. free(req);
  419. evdns_requests_pump_waiting_queue();
  420. }
  421. // This is called when a server returns a funny error code.
  422. // We try the request again with another server.
  423. //
  424. // return:
  425. // 0 ok
  426. // 1 failed/reissue is pointless
  427. static int
  428. request_reissue(struct request *req) {
  429. const struct nameserver *const last_ns = req->ns;
  430. // the last nameserver should have been marked as failing
  431. // by the caller of this function, therefore pick will try
  432. // not to return it
  433. req->ns = nameserver_pick();
  434. if (req->ns == last_ns) {
  435. // ... but pick did return it
  436. // not a lot of point in trying again with the
  437. // same server
  438. return 1;
  439. }
  440. req->reissue_count++;
  441. req->tx_count = 0;
  442. req->transmit_me = 1;
  443. return 0;
  444. }
  445. // this function looks for space on the inflight queue and promotes
  446. // requests from the waiting queue if it can.
  447. static void
  448. evdns_requests_pump_waiting_queue(void) {
  449. while (global_requests_inflight < global_max_requests_inflight &&
  450. global_requests_waiting) {
  451. struct request *req;
  452. // move a request from the waiting queue to the inflight queue
  453. assert(req_waiting_head);
  454. if (req_waiting_head->next == req_waiting_head) {
  455. // only one item in the queue
  456. req = req_waiting_head;
  457. req_waiting_head = NULL;
  458. } else {
  459. req = req_waiting_head;
  460. req->next->prev = req->prev;
  461. req->prev->next = req->next;
  462. req_waiting_head = req->next;
  463. }
  464. global_requests_waiting--;
  465. global_requests_inflight++;
  466. req->ns = nameserver_pick();
  467. request_trans_id_set(req, transaction_id_pick());
  468. evdns_request_insert(req, &req_head);
  469. evdns_request_transmit(req);
  470. evdns_transmit();
  471. }
  472. }
  473. static void
  474. reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
  475. switch (req->request_type) {
  476. case TYPE_A:
  477. if (reply)
  478. req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
  479. reply->data.a.addrcount, ttl,
  480. reply->data.a.addresses,
  481. req->user_pointer);
  482. else
  483. req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
  484. return;
  485. case TYPE_PTR:
  486. if (reply) {
  487. char *name = reply->data.ptr.name;
  488. req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
  489. &name, req->user_pointer);
  490. } else {
  491. req->user_callback(err, 0, 0, 0, NULL,
  492. req->user_pointer);
  493. }
  494. return;
  495. }
  496. assert(0);
  497. }
  498. // this processes a parsed reply packet
  499. static void
  500. reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
  501. int error;
  502. static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
  503. if (flags & 0x020f || !reply || !reply->have_answer) {
  504. // there was an error
  505. if (flags & 0x0200) {
  506. error = DNS_ERR_TRUNCATED;
  507. } else {
  508. u16 error_code = (flags & 0x000f) - 1;
  509. if (error_code > 4) {
  510. error = DNS_ERR_UNKNOWN;
  511. } else {
  512. error = error_codes[error_code];
  513. }
  514. }
  515. switch(error) {
  516. case DNS_ERR_SERVERFAILED:
  517. case DNS_ERR_NOTIMPL:
  518. case DNS_ERR_REFUSED:
  519. // we regard these errors as marking a bad nameserver
  520. if (req->reissue_count < global_max_reissues) {
  521. char msg[64];
  522. snprintf(msg, sizeof(msg), "Bad response %d (%s)",
  523. error, evdns_err_to_string(error));
  524. nameserver_failed(req->ns, msg);
  525. if (!request_reissue(req)) return;
  526. }
  527. break;
  528. default:
  529. // we got a good reply from the nameserver
  530. nameserver_up(req->ns);
  531. }
  532. if (req->search_state && req->request_type != TYPE_PTR) {
  533. // if we have a list of domains to search in, try the next one
  534. if (!search_try_next(req)) {
  535. // a new request was issued so this request is finished and
  536. // the user callback will be made when that request (or a
  537. // child of it) finishes.
  538. request_finished(req, &req_head);
  539. return;
  540. }
  541. }
  542. // all else failed. Pass the failure up
  543. reply_callback(req, 0, error, NULL);
  544. request_finished(req, &req_head);
  545. } else {
  546. // all ok, tell the user
  547. reply_callback(req, ttl, 0, reply);
  548. nameserver_up(req->ns);
  549. request_finished(req, &req_head);
  550. }
  551. }
  552. static inline int
  553. name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
  554. int name_end = -1;
  555. int j = *idx;
  556. #define GET32(x) do { if (j + 4 > length) return -1; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0);
  557. #define GET16(x) do { if (j + 2 > length) return -1; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0);
  558. #define GET8(x) do { if (j >= length) return -1; x = packet[j++]; } while(0);
  559. char *cp = name_out;
  560. const char *const end = name_out + name_out_len;
  561. // Normally, names are a series of length prefixed strings terminated
  562. // with a length of 0 (the lengths are u8's < 63).
  563. // However, the length can start with a pair of 1 bits and that
  564. // means that the next 14 bits are a pointer within the current
  565. // packet.
  566. for(;;) {
  567. u8 label_len;
  568. if (j >= length) return -1;
  569. GET8(label_len);
  570. if (!label_len) break;
  571. if (label_len & 0xc0) {
  572. u8 ptr_low;
  573. GET8(ptr_low);
  574. if (name_end < 0) name_end = j;
  575. j = (((int)label_len & 0x3f) << 8) + ptr_low;
  576. if (j < 0 || j >= length) return -1;
  577. continue;
  578. }
  579. if (label_len > 63) return -1;
  580. if (cp != name_out) {
  581. if (cp + 1 >= end) return -1;
  582. *cp++ = '.';
  583. }
  584. if (cp + label_len >= end) return -1;
  585. memcpy(cp, packet + j, label_len);
  586. cp += label_len;
  587. j += label_len;
  588. }
  589. if (cp >= end) return -1;
  590. *cp = '\0';
  591. if (name_end < 0)
  592. *idx = j;
  593. else
  594. *idx = name_end;
  595. return 0;
  596. }
  597. // parses a raw packet from the wire
  598. static int
  599. reply_parse(u8 *packet, int length) {
  600. int j = 0; // index into packet
  601. u16 _t; // used by the macros
  602. u32 _t32; // used by the macros
  603. char tmp_name[256]; // used by the macros
  604. u16 trans_id, flags, questions, answers, authority, additional, datalength;
  605. u32 ttl, ttl_r = 0xffffffff;
  606. struct reply reply;
  607. struct request *req;
  608. unsigned int i;
  609. GET16(trans_id);
  610. GET16(flags);
  611. GET16(questions);
  612. GET16(answers);
  613. GET16(authority);
  614. GET16(additional);
  615. req = request_find_from_trans_id(trans_id);
  616. if (!req) return -1;
  617. // XXXX should the other return points also call reply_handle? -NM
  618. memset(&reply, 0, sizeof(reply));
  619. if (!(flags & 0x8000)) return -1; // must be an answer
  620. if (flags & 0x020f) {
  621. // there was an error
  622. reply_handle(req, flags, 0, NULL);
  623. return -1;
  624. }
  625. // if (!answers) return; // must have an answer of some form
  626. // This macro skips a name in the DNS reply.
  627. #define SKIP_NAME \
  628. do { tmp_name[0] = '\0'; \
  629. if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
  630. return -1; \
  631. } while(0);
  632. reply.type = req->request_type;
  633. // skip over each question in the reply
  634. for (i = 0; i < questions; ++i) {
  635. // the question looks like
  636. // <label:name><u16:type><u16:class>
  637. SKIP_NAME;
  638. j += 4;
  639. if (j >= length) return -1;
  640. }
  641. // now we have the answer section which looks like
  642. // <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
  643. for (i = 0; i < answers; ++i) {
  644. u16 type, class;
  645. SKIP_NAME;
  646. GET16(type);
  647. GET16(class);
  648. GET32(ttl);
  649. GET16(datalength);
  650. if (type == TYPE_A && class == CLASS_INET) {
  651. int addrcount, addrtocopy;
  652. if (req->request_type != TYPE_A) {
  653. j += datalength; continue;
  654. }
  655. // XXXX do something sane with malformed A answers.
  656. addrcount = datalength >> 2;
  657. addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
  658. ttl_r = MIN(ttl_r, ttl);
  659. // we only bother with the first four addresses.
  660. if (j + 4*addrtocopy > length) return -1;
  661. memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
  662. packet + j, 4*addrtocopy);
  663. j += 4*addrtocopy;
  664. reply.data.a.addrcount += addrtocopy;
  665. reply.have_answer = 1;
  666. if (reply.data.a.addrcount == MAX_ADDRS) break;
  667. } else if (type == TYPE_PTR && class == CLASS_INET) {
  668. if (req->request_type != TYPE_PTR) {
  669. j += datalength; continue;
  670. }
  671. if (name_parse(packet, length, &j, reply.data.ptr.name,
  672. sizeof(reply.data.ptr.name))<0)
  673. return -1;
  674. reply.have_answer = 1;
  675. break;
  676. } else {
  677. // skip over any other type of resource
  678. j += datalength;
  679. }
  680. }
  681. reply_handle(req, flags, ttl_r, &reply);
  682. return 0;
  683. #undef SKIP_NAME
  684. #undef GET32
  685. #undef GET16
  686. #undef GET8
  687. }
  688. // Try to choose a strong transaction id which isn't already in flight
  689. static u16
  690. transaction_id_pick(void) {
  691. for (;;) {
  692. const struct request *req = req_head, *started_at;
  693. #ifdef DNS_USE_CPU_CLOCK_FOR_ID
  694. struct timespec ts;
  695. u16 trans_id;
  696. if (clock_gettime(CLOCK_MONOTONIC, &ts))
  697. event_err(1, "clock_gettime");
  698. trans_id = ts.tv_nsec & 0xffff;
  699. #endif
  700. #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
  701. struct timeval tv;
  702. u16 trans_id;
  703. gettimeofday(&tv, NULL);
  704. trans_id = tv.tv_usec & 0xffff;
  705. #endif
  706. #ifdef DNS_USE_OPENSSL_FOR_ID
  707. u16 trans_id;
  708. if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
  709. /* // in the case that the RAND call fails we back
  710. // down to using gettimeofday.
  711. struct timeval tv;
  712. gettimeofday(&tv, NULL);
  713. trans_id = tv.tv_usec & 0xffff; */
  714. abort();
  715. }
  716. #endif
  717. if (trans_id == 0xffff) continue;
  718. // now check to see if that id is already inflight
  719. req = started_at = req_head;
  720. if (req) {
  721. do {
  722. if (req->trans_id == trans_id) break;
  723. req = req->next;
  724. } while (req != started_at);
  725. }
  726. // we didn't find it, so this is a good id
  727. if (req == started_at) return trans_id;
  728. }
  729. }
  730. // choose a namesever to use. This function will try to ignore
  731. // nameservers which we think are down and load balance across the rest
  732. // by updating the server_head global each time.
  733. static struct nameserver *
  734. nameserver_pick(void) {
  735. struct nameserver *started_at = server_head, *picked;
  736. if (!server_head) return NULL;
  737. // if we don't have any good nameservers then there's no
  738. // point in trying to find one.
  739. if (!global_good_nameservers) {
  740. server_head = server_head->next;
  741. return server_head;
  742. }
  743. // remember that nameservers are in a circular list
  744. for (;;) {
  745. if (server_head->state) {
  746. // we think this server is currently good
  747. picked = server_head;
  748. server_head = server_head->next;
  749. return picked;
  750. }
  751. server_head = server_head->next;
  752. if (server_head == started_at) {
  753. // all the nameservers seem to be down
  754. // so we just return this one and hope for the
  755. // best
  756. assert(global_good_nameservers == 0);
  757. picked = server_head;
  758. server_head = server_head->next;
  759. return picked;
  760. }
  761. }
  762. }
  763. // this is called when a namesever socket is ready for reading
  764. static void
  765. nameserver_read(struct nameserver *ns) {
  766. u8 packet[1500];
  767. for (;;) {
  768. const int r = recv(ns->socket, packet, sizeof(packet), 0);
  769. if (r < 0) {
  770. int err = last_error(ns->socket);
  771. if (error_is_eagain(err)) return;
  772. nameserver_failed(ns, strerror(err));
  773. return;
  774. }
  775. reply_parse(packet, r);
  776. }
  777. }
  778. // set if we are waiting for the ability to write to this server.
  779. // if waiting is true then we ask libevent for EV_WRITE events, otherwise
  780. // we stop these events.
  781. static void
  782. nameserver_write_waiting(struct nameserver *ns, char waiting) {
  783. if (ns->write_waiting == waiting) return;
  784. ns->write_waiting = waiting;
  785. (void) event_del(&ns->event);
  786. event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
  787. nameserver_ready_callback, ns);
  788. if (event_add(&ns->event, NULL) < 0) {
  789. log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
  790. debug_ntoa(ns->address));
  791. // ???? Do more?
  792. }
  793. }
  794. // a callback function. Called by libevent when the kernel says that
  795. // a nameserver socket is ready for writing or reading
  796. static void
  797. nameserver_ready_callback(int fd, short events, void *arg) {
  798. struct nameserver *ns = (struct nameserver *) arg;
  799. (void)fd;
  800. if (events & EV_WRITE) {
  801. ns->choaked = 0;
  802. if (!evdns_transmit()) {
  803. nameserver_write_waiting(ns, 0);
  804. }
  805. }
  806. if (events & EV_READ) {
  807. nameserver_read(ns);
  808. }
  809. }
  810. // Converts a string to a length-prefixed set of DNS labels.
  811. // @buf must be strlen(name)+2 or longer. name and buf must
  812. // not overlap. name_len should be the length of name
  813. //
  814. // Input: abc.def
  815. // Output: <3>abc<3>def<0>
  816. //
  817. // Returns the length of the data. negative on error
  818. // -1 label was > 63 bytes
  819. // -2 name was > 255 bytes
  820. static int
  821. dnsname_to_labels(u8 *const buf, const char *name, const int name_len) {
  822. const char *end = name + name_len;
  823. int j = 0; // current offset into buf
  824. if (name_len > 255) return -2;
  825. for (;;) {
  826. const char *const start = name;
  827. name = strchr(name, '.');
  828. if (!name) {
  829. const unsigned int label_len = end - start;
  830. if (label_len > 63) return -1;
  831. buf[j++] = label_len;
  832. memcpy(buf + j, start, end - start);
  833. j += end - start;
  834. break;
  835. } else {
  836. // append length of the label.
  837. const unsigned int label_len = name - start;
  838. if (label_len > 63) return -1;
  839. buf[j++] = label_len;
  840. memcpy(buf + j, start, name - start);
  841. j += name - start;
  842. // hop over the '.'
  843. name++;
  844. }
  845. }
  846. // the labels must be terminated by a 0.
  847. // It's possible that the name ended in a .
  848. // in which case the zero is already there
  849. if (!j || buf[j-1]) buf[j++] = 0;
  850. return j;
  851. }
  852. // Finds the length of a dns request for a DNS name of the given
  853. // length. The actual request may be smaller than the value returned
  854. // here
  855. static int
  856. evdns_request_len(const int name_len) {
  857. return 96 + // length of the DNS standard header
  858. name_len + 2 +
  859. 4; // space for the resource type
  860. }
  861. // build a dns request packet into buf. buf should be at least as long
  862. // as evdns_request_len told you it should be.
  863. //
  864. // Returns the amount of space used. Negative on error.
  865. static int
  866. evdns_request_data_build(const char *const name, const int name_len,
  867. const u16 trans_id, const u16 type, const u16 class,
  868. u8 *const buf, size_t buf_len) {
  869. int j = 0; // current offset into buf
  870. u16 _t; // used by the macros
  871. u8 *labels;
  872. int labels_len;
  873. #define APPEND16(x) do { \
  874. if (j + 2 > buf_len) \
  875. return (-1); \
  876. _t = htons(x); \
  877. memcpy(buf + j, &_t, 2); j += 2; \
  878. } while(0)
  879. APPEND16(trans_id);
  880. APPEND16(0x0100); // standard query, recusion needed
  881. APPEND16(1); // one question
  882. APPEND16(0); // no answers
  883. APPEND16(0); // no authority
  884. APPEND16(0); // no additional
  885. labels = (u8 *) malloc(name_len + 2);
  886. if (labels == NULL)
  887. return (-1);
  888. labels_len = dnsname_to_labels(labels, name, name_len);
  889. if (labels_len < 0) {
  890. free(labels);
  891. return (labels_len);
  892. }
  893. if ((size_t)(j + labels_len) > buf_len) {
  894. free(labels);
  895. return (-1);
  896. }
  897. memcpy(buf + j, labels, labels_len);
  898. j += labels_len;
  899. free(labels);
  900. APPEND16(type);
  901. APPEND16(class);
  902. #undef APPEND16
  903. return (j);
  904. }
  905. // this is a libevent callback function which is called when a request
  906. // has timed out.
  907. static void
  908. evdns_request_timeout_callback(int fd, short events, void *arg) {
  909. struct request *const req = (struct request *) arg;
  910. (void) fd;
  911. (void) events;
  912. log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
  913. req->ns->timedout++;
  914. if (req->ns->timedout > global_max_nameserver_timeout) {
  915. nameserver_failed(req->ns, "request timed out.");
  916. }
  917. (void) evtimer_del(&req->timeout_event);
  918. if (req->tx_count >= global_max_retransmits) {
  919. // this request has failed
  920. reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
  921. request_finished(req, &req_head);
  922. } else {
  923. // retransmit it
  924. evdns_request_transmit(req);
  925. }
  926. }
  927. // try to send a request to a given server.
  928. //
  929. // return:
  930. // 0 ok
  931. // 1 temporary failure
  932. // 2 other failure
  933. static int
  934. evdns_request_transmit_to(struct request *req, struct nameserver *server) {
  935. const int r = send(server->socket, req->request, req->request_len, 0);
  936. if (r < 0) {
  937. int err = last_error(server->socket);
  938. if (error_is_eagain(err)) return 1;
  939. nameserver_failed(req->ns, strerror(err));
  940. return 2;
  941. } else if (r != (int)req->request_len) {
  942. return 1; // short write
  943. } else {
  944. return 0;
  945. }
  946. }
  947. // try to send a request, updating the fields of the request
  948. // as needed
  949. //
  950. // return:
  951. // 0 ok
  952. // 1 failed
  953. static int
  954. evdns_request_transmit(struct request *req) {
  955. int retcode = 0, r;
  956. // if we fail to send this packet then this flag marks it
  957. // for evdns_transmit
  958. req->transmit_me = 1;
  959. if (req->trans_id == 0xffff) abort();
  960. if (req->ns->choaked) {
  961. // don't bother trying to write to a socket
  962. // which we have had EAGAIN from
  963. return 1;
  964. }
  965. r = evdns_request_transmit_to(req, req->ns);
  966. switch (r) {
  967. case 1:
  968. // temp failure
  969. req->ns->choaked = 1;
  970. nameserver_write_waiting(req->ns, 1);
  971. return 1;
  972. case 2:
  973. // failed in some other way
  974. retcode = 1;
  975. // fall through
  976. default:
  977. // all ok
  978. log(EVDNS_LOG_DEBUG,
  979. "Setting timeout for request %lx", (unsigned long) req);
  980. evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
  981. if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
  982. log(EVDNS_LOG_WARN,
  983. "Error from libevent when adding timer for request %lx",
  984. (unsigned long) req);
  985. // ???? Do more?
  986. }
  987. req->tx_count++;
  988. req->transmit_me = 0;
  989. return retcode;
  990. }
  991. }
  992. static void
  993. nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
  994. struct nameserver *const ns = (struct nameserver *) arg;
  995. (void) type;
  996. (void) count;
  997. (void) ttl;
  998. (void) addresses;
  999. if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
  1000. // this is a good reply
  1001. nameserver_up(ns);
  1002. } else nameserver_probe_failed(ns);
  1003. }
  1004. static void
  1005. nameserver_send_probe(struct nameserver *const ns) {
  1006. struct request *req;
  1007. // here we need to send a probe to a given nameserver
  1008. // in the hope that it is up now.
  1009. log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
  1010. req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
  1011. if (!req) return;
  1012. // we force this into the inflight queue no matter what
  1013. request_trans_id_set(req, transaction_id_pick());
  1014. req->ns = ns;
  1015. request_submit(req);
  1016. }
  1017. // returns:
  1018. // 0 didn't try to transmit anything
  1019. // 1 tried to transmit something
  1020. static int
  1021. evdns_transmit(void) {
  1022. char did_try_to_transmit = 0;
  1023. if (req_head) {
  1024. struct request *const started_at = req_head, *req = req_head;
  1025. // first transmit all the requests which are currently waiting
  1026. do {
  1027. if (req->transmit_me) {
  1028. did_try_to_transmit = 1;
  1029. evdns_request_transmit(req);
  1030. }
  1031. req = req->next;
  1032. } while (req != started_at);
  1033. }
  1034. return did_try_to_transmit;
  1035. }
  1036. // exported function
  1037. int
  1038. evdns_count_nameservers(void)
  1039. {
  1040. const struct nameserver *server = server_head;
  1041. int n = 0;
  1042. if (!server)
  1043. return 0;
  1044. do {
  1045. ++n;
  1046. server = server->next;
  1047. } while (server != server_head);
  1048. return n;
  1049. }
  1050. // exported function
  1051. int
  1052. evdns_clear_nameservers_and_suspend(void)
  1053. {
  1054. struct nameserver *server = server_head, *started_at = server_head;
  1055. struct request *req = req_head, *req_started_at = req_head;
  1056. if (!server)
  1057. return 0;
  1058. while (1) {
  1059. struct nameserver *next = server->next;
  1060. (void) event_del(&server->event);
  1061. (void) evtimer_del(&server->timeout_event);
  1062. if (server->socket >= 0)
  1063. CLOSE_SOCKET(server->socket);
  1064. free(server);
  1065. if (next == started_at)
  1066. break;
  1067. server = next;
  1068. }
  1069. server_head = NULL;
  1070. global_good_nameservers = 0;
  1071. while (req) {
  1072. struct request *next = req->next;
  1073. req->tx_count = req->reissue_count = 0;
  1074. req->ns = NULL;
  1075. // ???? What to do about searches?
  1076. (void) evtimer_del(&req->timeout_event);
  1077. req->trans_id = 0;
  1078. req->transmit_me = 0;
  1079. global_requests_waiting++;
  1080. evdns_request_insert(req, &req_waiting_head);
  1081. /* We want to insert these suspended elements at the front of
  1082. * the waiting queue, since they were pending before any of
  1083. * the waiting entries were added. This is a circular list,
  1084. * so we can just shift the start back by one.*/
  1085. req_waiting_head = req_waiting_head->prev;
  1086. if (next == req_started_at)
  1087. break;
  1088. req = next;
  1089. }
  1090. req_head = NULL;
  1091. global_requests_inflight = 0;
  1092. return 0;
  1093. }
  1094. // exported function
  1095. int
  1096. evdns_resume(void)
  1097. {
  1098. evdns_requests_pump_waiting_queue();
  1099. return 0;
  1100. }
  1101. // exported function
  1102. int
  1103. evdns_nameserver_add(unsigned long int address) {
  1104. // first check to see if we already have this nameserver
  1105. const struct nameserver *server = server_head, *const started_at = server_head;
  1106. struct nameserver *ns;
  1107. struct sockaddr_in sin;
  1108. int err = 0;
  1109. if (server) {
  1110. do {
  1111. if (server->address == address) return 3;
  1112. server = server->next;
  1113. } while (server != started_at);
  1114. }
  1115. ns = (struct nameserver *) malloc(sizeof(struct nameserver));
  1116. if (!ns) return -1;
  1117. memset(ns, 0, sizeof(struct nameserver));
  1118. ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
  1119. if (ns->socket < 0) { err = 1; goto out1; }
  1120. #ifdef MS_WINDOWS
  1121. {
  1122. u_long nonblocking = 1;
  1123. ioctlsocket(ns->socket, FIONBIO, &nonblocking);
  1124. }
  1125. #else
  1126. fcntl(ns->socket, F_SETFL, O_NONBLOCK);
  1127. #endif
  1128. sin.sin_addr.s_addr = address;
  1129. sin.sin_port = htons(53);
  1130. sin.sin_family = AF_INET;
  1131. if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  1132. err = 2;
  1133. goto out2;
  1134. }
  1135. ns->address = address;
  1136. ns->state = 1;
  1137. event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
  1138. if (event_add(&ns->event, NULL) < 0) {
  1139. err = 2;
  1140. goto out2;
  1141. }
  1142. log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
  1143. // insert this nameserver into the list of them
  1144. if (!server_head) {
  1145. ns->next = ns->prev = ns;
  1146. server_head = ns;
  1147. } else {
  1148. ns->next = server_head->next;
  1149. ns->prev = server_head;
  1150. server_head->next = ns;
  1151. if (server_head->prev == server_head) {
  1152. server_head->prev = ns;
  1153. }
  1154. }
  1155. global_good_nameservers++;
  1156. return 0;
  1157. out2:
  1158. CLOSE_SOCKET(ns->socket);
  1159. out1:
  1160. free(ns);
  1161. log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
  1162. return err;
  1163. }
  1164. // exported function
  1165. int
  1166. evdns_nameserver_ip_add(const char *ip_as_string) {
  1167. struct in_addr ina;
  1168. if (!inet_aton(ip_as_string, &ina)) return 4;
  1169. return evdns_nameserver_add(ina.s_addr);
  1170. }
  1171. // insert into the tail of the queue
  1172. static void
  1173. evdns_request_insert(struct request *req, struct request **head) {
  1174. if (!*head) {
  1175. *head = req;
  1176. req->next = req->prev = req;
  1177. return;
  1178. }
  1179. req->prev = (*head)->prev;
  1180. req->prev->next = req;
  1181. req->next = *head;
  1182. (*head)->prev = req;
  1183. }
  1184. static int
  1185. string_num_dots(const char *s) {
  1186. int count = 0;
  1187. while ((s = strchr(s, '.'))) {
  1188. s++;
  1189. count++;
  1190. }
  1191. return count;
  1192. }
  1193. static struct request *
  1194. request_new(int type, const char *name, int flags,
  1195. evdns_callback_type callback, void *user_ptr) {
  1196. const char issuing_now =
  1197. (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
  1198. const int name_len = strlen(name);
  1199. const int request_max_len = evdns_request_len(name_len);
  1200. const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
  1201. // the request data is alloced in a single block with the header
  1202. struct request *const req =
  1203. (struct request *) malloc(sizeof(struct request) + request_max_len);
  1204. int rlen;
  1205. (void) flags;
  1206. if (!req) return NULL;
  1207. memset(req, 0, sizeof(struct request));
  1208. // request data lives just after the header
  1209. req->request = ((u8 *) req) + sizeof(struct request);
  1210. // denotes that the request data shouldn't be free()ed
  1211. req->request_appended = 1;
  1212. rlen = evdns_request_data_build(name, name_len, trans_id,
  1213. type, CLASS_INET, req->request, request_max_len);
  1214. if (rlen < 0)
  1215. goto err1;
  1216. req->request_len = rlen;
  1217. req->trans_id = trans_id;
  1218. req->tx_count = 0;
  1219. req->request_type = type;
  1220. req->user_pointer = user_ptr;
  1221. req->user_callback = callback;
  1222. req->ns = issuing_now ? nameserver_pick() : NULL;
  1223. req->next = req->prev = NULL;
  1224. return req;
  1225. err1:
  1226. free(req);
  1227. return NULL;
  1228. }
  1229. static void
  1230. request_submit(struct request *const req) {
  1231. if (req->ns) {
  1232. // if it has a nameserver assigned then this is going
  1233. // straight into the inflight queue
  1234. evdns_request_insert(req, &req_head);
  1235. global_requests_inflight++;
  1236. evdns_request_transmit(req);
  1237. } else {
  1238. evdns_request_insert(req, &req_waiting_head);
  1239. global_requests_waiting++;
  1240. }
  1241. }
  1242. // exported function
  1243. int evdns_resolve_ipv4(const char *name, int flags,
  1244. evdns_callback_type callback, void *ptr) {
  1245. log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
  1246. if (flags & DNS_QUERY_NO_SEARCH) {
  1247. struct request *const req =
  1248. request_new(TYPE_A, name, flags, callback, ptr);
  1249. if (req == NULL)
  1250. return (1);
  1251. request_submit(req);
  1252. return (0);
  1253. } else {
  1254. return (search_request_new(TYPE_A, name, flags, callback, ptr));
  1255. }
  1256. }
  1257. int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
  1258. char buf[32];
  1259. struct request *req;
  1260. u32 a;
  1261. assert(in);
  1262. a = ntohl(in->s_addr);
  1263. sprintf(buf, "%d.%d.%d.%d.in-addr.arpa",
  1264. (int)(u8)((a )&0xff),
  1265. (int)(u8)((a>>8 )&0xff),
  1266. (int)(u8)((a>>16)&0xff),
  1267. (int)(u8)((a>>24)&0xff));
  1268. log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
  1269. req = request_new(TYPE_PTR, buf, flags, callback, ptr);
  1270. if (!req) return 1;
  1271. request_submit(req);
  1272. return 0;
  1273. }
  1274. /////////////////////////////////////////////////////////////////////
  1275. // Search support
  1276. //
  1277. // the libc resolver has support for searching a number of domains
  1278. // to find a name. If nothing else then it takes the single domain
  1279. // from the gethostname() call.
  1280. //
  1281. // It can also be configured via the domain and search options in a
  1282. // resolv.conf.
  1283. //
  1284. // The ndots option controls how many dots it takes for the resolver
  1285. // to decide that a name is non-local and so try a raw lookup first.
  1286. struct search_domain {
  1287. int len;
  1288. struct search_domain *next;
  1289. // the text string is appended to this structure
  1290. };
  1291. struct search_state {
  1292. int refcount;
  1293. int ndots;
  1294. int num_domains;
  1295. struct search_domain *head;
  1296. };
  1297. static struct search_state *global_search_state = NULL;
  1298. static void
  1299. search_state_decref(struct search_state *const state) {
  1300. if (!state) return;
  1301. state->refcount--;
  1302. if (!state->refcount) {
  1303. struct search_domain *next, *dom;
  1304. for (dom = state->head; dom; dom = next) {
  1305. next = dom->next;
  1306. free(dom);
  1307. }
  1308. free(state);
  1309. }
  1310. }
  1311. static struct search_state *
  1312. search_state_new(void) {
  1313. struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
  1314. if (!state) return NULL;
  1315. memset(state, 0, sizeof(struct search_state));
  1316. state->refcount = 1;
  1317. state->ndots = 1;
  1318. return state;
  1319. }
  1320. static void
  1321. search_postfix_clear(void) {
  1322. search_state_decref(global_search_state);
  1323. global_search_state = search_state_new();
  1324. }
  1325. // exported function
  1326. void
  1327. evdns_search_clear(void) {
  1328. search_postfix_clear();
  1329. }
  1330. static void
  1331. search_postfix_add(const char *domain) {
  1332. int domain_len;
  1333. struct search_domain *sdomain;
  1334. while (domain[0] == '.') domain++;
  1335. domain_len = strlen(domain);
  1336. if (!global_search_state) global_search_state = search_state_new();
  1337. if (!global_search_state) return;
  1338. global_search_state->num_domains++;
  1339. sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
  1340. if (!sdomain) return;
  1341. memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
  1342. sdomain->next = global_search_state->head;
  1343. sdomain->len = domain_len;
  1344. global_search_state->head = sdomain;
  1345. }
  1346. // reverse the order of members in the postfix list. This is needed because,
  1347. // when parsing resolv.conf we push elements in the wrong order
  1348. static void
  1349. search_reverse(void) {
  1350. struct search_domain *cur, *prev = NULL, *next;
  1351. cur = global_search_state->head;
  1352. while (cur) {
  1353. next = cur->next;
  1354. cur->next = prev;
  1355. prev = cur;
  1356. cur = next;
  1357. }
  1358. global_search_state->head = prev;
  1359. }
  1360. // exported function
  1361. void
  1362. evdns_search_add(const char *domain) {
  1363. search_postfix_add(domain);
  1364. }
  1365. // exported function
  1366. void
  1367. evdns_search_ndots_set(const int ndots) {
  1368. if (!global_search_state) global_search_state = search_state_new();
  1369. if (!global_search_state) return;
  1370. global_search_state->ndots = ndots;
  1371. }
  1372. static void
  1373. search_set_from_hostname(void) {
  1374. char hostname[HOST_NAME_MAX + 1], *domainname;
  1375. search_postfix_clear();
  1376. if (gethostname(hostname, sizeof(hostname))) return;
  1377. domainname = strchr(hostname, '.');
  1378. if (!domainname) return;
  1379. search_postfix_add(domainname);
  1380. }
  1381. // warning: returns malloced string
  1382. static char *
  1383. search_make_new(const struct search_state *const state, int n, const char *const base_name) {
  1384. const int base_len = strlen(base_name);
  1385. const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
  1386. struct search_domain *dom;
  1387. for (dom = state->head; dom; dom = dom->next) {
  1388. if (!n--) {
  1389. // this is the postfix we want
  1390. // the actual postfix string is kept at the end of the structure
  1391. const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
  1392. const int postfix_len = dom->len;
  1393. char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
  1394. if (!newname) return NULL;
  1395. memcpy(newname, base_name, base_len);
  1396. if (need_to_append_dot) newname[base_len] = '.';
  1397. memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
  1398. newname[base_len + need_to_append_dot + postfix_len] = 0;
  1399. return newname;
  1400. }
  1401. }
  1402. // we ran off the end of the list and still didn't find the requested string
  1403. abort();
  1404. }
  1405. static int
  1406. search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
  1407. assert(type == TYPE_A);
  1408. if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
  1409. global_search_state &&
  1410. global_search_state->num_domains) {
  1411. // we have some domains to search
  1412. struct request *req;
  1413. if (string_num_dots(name) >= global_search_state->ndots) {
  1414. req = request_new(type, name, flags, user_callback, user_arg);
  1415. if (!req) return 1;
  1416. req->search_index = -1;
  1417. } else {
  1418. char *const new_name = search_make_new(global_search_state, 0, name);
  1419. if (!new_name) return 1;
  1420. req = request_new(type, new_name, flags, user_callback, user_arg);
  1421. free(new_name);
  1422. if (!req) return 1;
  1423. req->search_index = 0;
  1424. }
  1425. req->search_origname = strdup(name);
  1426. req->search_state = global_search_state;
  1427. req->search_flags = flags;
  1428. global_search_state->refcount++;
  1429. request_submit(req);
  1430. return 0;
  1431. } else {
  1432. struct request *const req = request_new(type, name, flags, user_callback, user_arg);
  1433. if (!req) return 1;
  1434. request_submit(req);
  1435. return 0;
  1436. }
  1437. }
  1438. // this is called when a request has failed to find a name. We need to check
  1439. // if it is part of a search and, if so, try the next name in the list
  1440. // returns:
  1441. // 0 another request has been submitted
  1442. // 1 no more requests needed
  1443. static int
  1444. search_try_next(struct request *const req) {
  1445. if (req->search_state) {
  1446. // it is part of a search
  1447. char *new_name;
  1448. struct request *newreq;
  1449. req->search_index++;
  1450. if (req->search_index >= req->search_state->num_domains) {
  1451. // no more postfixes to try, however we may need to try
  1452. // this name without a postfix
  1453. if (string_num_dots(req->search_origname) < req->search_state->ndots) {
  1454. // yep, we need to try it raw
  1455. struct request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
  1456. log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
  1457. if (newreq) {
  1458. request_submit(newreq);
  1459. return 0;
  1460. }
  1461. }
  1462. return 1;
  1463. }
  1464. new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
  1465. if (!new_name) return 1;
  1466. log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
  1467. newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
  1468. free(new_name);
  1469. if (!newreq) return 1;
  1470. newreq->search_origname = req->search_origname;
  1471. req->search_origname = NULL;
  1472. newreq->search_state = req->search_state;
  1473. newreq->search_flags = req->search_flags;
  1474. newreq->search_index = req->search_index;
  1475. newreq->search_state->refcount++;
  1476. request_submit(newreq);
  1477. return 0;
  1478. }
  1479. return 1;
  1480. }
  1481. static void
  1482. search_request_finished(struct request *const req) {
  1483. if (req->search_state) {
  1484. search_state_decref(req->search_state);
  1485. req->search_state = NULL;
  1486. }
  1487. if (req->search_origname) {
  1488. free(req->search_origname);
  1489. req->search_origname = NULL;
  1490. }
  1491. }
  1492. /////////////////////////////////////////////////////////////////////
  1493. // Parsing resolv.conf files
  1494. static void
  1495. evdns_resolv_set_defaults(int flags) {
  1496. // if the file isn't found then we assume a local resolver
  1497. if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
  1498. if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
  1499. }
  1500. #ifndef HAVE_STRTOK_R
  1501. static char *
  1502. strtok_r(char *s, const char *delim, char **state) {
  1503. return strtok(s, delim);
  1504. }
  1505. #endif
  1506. // helper version of atoi which returns -1 on error
  1507. static int
  1508. strtoint(const char *const str) {
  1509. char *endptr;
  1510. const int r = strtol(str, &endptr, 10);
  1511. if (*endptr) return -1;
  1512. return r;
  1513. }
  1514. static void
  1515. resolv_conf_parse_line(char *const start, int flags) {
  1516. char *strtok_state;
  1517. static const char *const delims = " \t";
  1518. #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
  1519. char *const first_token = strtok_r(start, delims, &strtok_state);
  1520. if (!first_token) return;
  1521. if (!strcmp(first_token, "nameserver")) {
  1522. const char *const nameserver = NEXT_TOKEN;
  1523. struct in_addr ina;
  1524. if (inet_aton(nameserver, &ina)) {
  1525. // address is valid
  1526. evdns_nameserver_add(ina.s_addr);
  1527. }
  1528. } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
  1529. const char *const domain = NEXT_TOKEN;
  1530. if (domain) {
  1531. search_postfix_clear();
  1532. search_postfix_add(domain);
  1533. }
  1534. } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
  1535. const char *domain;
  1536. search_postfix_clear();
  1537. while ((domain = NEXT_TOKEN)) {
  1538. search_postfix_add(domain);
  1539. }
  1540. search_reverse();
  1541. } else if (!strcmp(first_token, "options")) {
  1542. const char *option;
  1543. while ((option = NEXT_TOKEN)) {
  1544. if (!strncmp(option, "ndots:", 6)) {
  1545. const int ndots = strtoint(&option[6]);
  1546. if (ndots == -1) continue;
  1547. if (!(flags & DNS_OPTION_SEARCH)) continue;
  1548. log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
  1549. if (!global_search_state) global_search_state = search_state_new();
  1550. if (!global_search_state) return;
  1551. global_search_state->ndots = ndots;
  1552. } else if (!strncmp(option, "timeout:", 8)) {
  1553. const int timeout = strtoint(&option[8]);
  1554. if (timeout == -1) continue;
  1555. if (!(flags & DNS_OPTION_MISC)) continue;
  1556. log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
  1557. global_timeout.tv_sec = timeout;
  1558. } else if (!strncmp(option, "attempts:", 9)) {
  1559. int retries = strtoint(&option[9]);
  1560. if (retries == -1) continue;
  1561. if (retries > 255) retries = 255;
  1562. if (!(flags & DNS_OPTION_MISC)) continue;
  1563. log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
  1564. global_max_retransmits = retries;
  1565. }
  1566. }
  1567. }
  1568. #undef NEXT_TOKEN
  1569. }
  1570. // exported function
  1571. // returns:
  1572. // 0 no errors
  1573. // 1 failed to open file
  1574. // 2 failed to stat file
  1575. // 3 file too large
  1576. // 4 out of memory
  1577. // 5 short read from file
  1578. int
  1579. evdns_resolv_conf_parse(int flags, const char *const filename) {
  1580. struct stat st;
  1581. int fd;
  1582. u8 *resolv;
  1583. char *start;
  1584. int err = 0;
  1585. log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
  1586. fd = open(filename, O_RDONLY);
  1587. if (fd < 0) {
  1588. evdns_resolv_set_defaults(flags);
  1589. return 1;
  1590. }
  1591. if (fstat(fd, &st)) { err = 2; goto out1; }
  1592. if (!st.st_size) {
  1593. evdns_resolv_set_defaults(flags);
  1594. err = 0;
  1595. goto out1;
  1596. }
  1597. if (st.st_size > 65535) { err = 3; goto out1; } // no resolv.conf should be any bigger
  1598. resolv = (u8 *) malloc(st.st_size + 1);
  1599. if (!resolv) { err = 4; goto out1; }
  1600. if (read(fd, resolv, st.st_size) != st.st_size) { err = 5; goto out2; }
  1601. resolv[st.st_size] = 0; // we malloced an extra byte
  1602. start = (char *) resolv;
  1603. for (;;) {
  1604. char *const newline = strchr(start, '\n');
  1605. if (!newline) {
  1606. resolv_conf_parse_line(start, flags);
  1607. break;
  1608. } else {
  1609. *newline = 0;
  1610. resolv_conf_parse_line(start, flags);
  1611. start = newline + 1;
  1612. }
  1613. }
  1614. if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
  1615. // no nameservers were configured.
  1616. evdns_nameserver_ip_add("127.0.0.1");
  1617. }
  1618. if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
  1619. search_set_from_hostname();
  1620. }
  1621. out2:
  1622. free(resolv);
  1623. out1:
  1624. close(fd);
  1625. return err;
  1626. }
  1627. #ifdef MS_WINDOWS
  1628. // Add multiple nameservers from a space-or-comma-separated list.
  1629. static int
  1630. evdns_nameserver_ip_add_line(const char *ips) {
  1631. const char *addr;
  1632. char *buf;
  1633. int r;
  1634. while (*ips) {
  1635. while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
  1636. ++ips;
  1637. addr = ips;
  1638. while (ISDIGIT(*ips) || *ips == '.')
  1639. ++ips;
  1640. buf = malloc(ips-addr+1);
  1641. if (!buf) return 4;
  1642. memcpy(buf, addr, ips-addr);
  1643. buf[ips-addr] = '\0';
  1644. r = evdns_nameserver_ip_add(buf);
  1645. free(buf);
  1646. if (r) return r;
  1647. }
  1648. return 0;
  1649. }
  1650. typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
  1651. // Use the windows GetNetworkParams interface in iphlpapi.dll to
  1652. // figure out what our nameservers are.
  1653. static int
  1654. load_nameservers_with_getnetworkparams(void)
  1655. {
  1656. // Based on MSDN examples and inspection of c-ares code.
  1657. FIXED_INFO *fixed;
  1658. HMODULE handle = 0;
  1659. ULONG size = sizeof(FIXED_INFO);
  1660. void *buf = NULL;
  1661. int status = 0, r, added_any;
  1662. IP_ADDR_STRING *ns;
  1663. GetNetworkParams_fn_t fn;
  1664. if (!(handle = LoadLibrary("iphlpapi.dll"))) {
  1665. log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
  1666. status = -1;
  1667. goto done;
  1668. }
  1669. if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
  1670. log(EVDNS_LOG_WARN, "Could not get address of function.");
  1671. status = -1;
  1672. goto done;
  1673. }
  1674. buf = malloc(size);
  1675. if (!buf) { status = 4; goto done; }
  1676. fixed = buf;
  1677. r = fn(fixed, &size);
  1678. if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
  1679. status = -1;
  1680. goto done;
  1681. }
  1682. if (r != ERROR_SUCCESS) {
  1683. free(buf);
  1684. buf = malloc(size);
  1685. if (!buf) { status = 4; goto done; }
  1686. fixed = buf;
  1687. r = fn(fixed, &size);
  1688. if (r != ERROR_SUCCESS) {
  1689. log(EVDNS_LOG_DEBUG, "fn() failed.");
  1690. status = -1;
  1691. goto done;
  1692. }
  1693. }
  1694. assert(fixed);
  1695. added_any = 0;
  1696. ns = &(fixed->DnsServerList);
  1697. while (ns) {
  1698. r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
  1699. if (r) {
  1700. log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
  1701. (ns->IpAddress.String),(int)GetLastError());
  1702. status = r;
  1703. goto done;
  1704. } else {
  1705. log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
  1706. }
  1707. added_any++;
  1708. ns = ns->Next;
  1709. }
  1710. if (!added_any) {
  1711. log(EVDNS_LOG_DEBUG, "No nameservers added.");
  1712. status = -1;
  1713. }
  1714. done:
  1715. if (buf)
  1716. free(buf);
  1717. if (handle)
  1718. FreeLibrary(handle);
  1719. return status;
  1720. }
  1721. static int
  1722. config_nameserver_from_reg_key(HKEY key, const char *subkey)
  1723. {
  1724. char *buf;
  1725. DWORD bufsz = 0, type = 0;
  1726. int status = 0;
  1727. if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
  1728. != ERROR_MORE_DATA)
  1729. return -1;
  1730. if (!(buf = malloc(bufsz)))
  1731. return -1;
  1732. if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
  1733. == ERROR_SUCCESS && bufsz > 1) {
  1734. status = evdns_nameserver_ip_add_line(buf);
  1735. }
  1736. free(buf);
  1737. return status;
  1738. }
  1739. #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
  1740. #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
  1741. #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
  1742. static int
  1743. load_nameservers_from_registry(void)
  1744. {
  1745. int found = 0;
  1746. int r;
  1747. #define TRY(k, name) \
  1748. if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
  1749. log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
  1750. found = 1; \
  1751. } else if (!found) { \
  1752. log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
  1753. #k,#name); \
  1754. }
  1755. if (((int)GetVersion()) > 0) { /* NT */
  1756. HKEY nt_key = 0, interfaces_key = 0;
  1757. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
  1758. KEY_READ, &nt_key) != ERROR_SUCCESS) {
  1759. log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
  1760. return -1;
  1761. }
  1762. r = RegOpenKeyEx(nt_key, "Interfaces", 0,
  1763. KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
  1764. &interfaces_key);
  1765. if (r != ERROR_SUCCESS) {
  1766. log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
  1767. return -1;
  1768. }
  1769. TRY(nt_key, "NameServer");
  1770. TRY(nt_key, "DhcpNameServer");
  1771. TRY(interfaces_key, "NameServer");
  1772. TRY(interfaces_key, "DhcpNameServer");
  1773. RegCloseKey(interfaces_key);
  1774. RegCloseKey(nt_key);
  1775. } else {
  1776. HKEY win_key = 0;
  1777. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
  1778. KEY_READ, &win_key) != ERROR_SUCCESS) {
  1779. log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
  1780. return -1;
  1781. }
  1782. TRY(win_key, "NameServer");
  1783. RegCloseKey(win_key);
  1784. }
  1785. if (found == 0) {
  1786. log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
  1787. }
  1788. return found ? 0 : -1;
  1789. #undef TRY
  1790. }
  1791. int
  1792. evdns_config_windows_nameservers(void)
  1793. {
  1794. if (load_nameservers_with_getnetworkparams() == 0)
  1795. return 0;
  1796. return load_nameservers_from_registry();
  1797. }
  1798. #endif
  1799. int
  1800. evdns_init()
  1801. {
  1802. int res = 0;
  1803. #ifdef MS_WINDOWS
  1804. evdns_config_windows_nameservers(void);
  1805. #else
  1806. res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
  1807. #endif
  1808. return (res);
  1809. }
  1810. const char *
  1811. evdns_err_to_string(int err)
  1812. {
  1813. switch (err) {
  1814. case DNS_ERR_NONE: return "no error";
  1815. case DNS_ERR_FORMAT: return "misformatted query";
  1816. case DNS_ERR_SERVERFAILED: return "server failed";
  1817. case DNS_ERR_NOTEXIST: return "name does not exist";
  1818. case DNS_ERR_NOTIMPL: return "query not implemented";
  1819. case DNS_ERR_REFUSED: return "refused";
  1820. case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
  1821. case DNS_ERR_UNKNOWN: return "unknown";
  1822. case DNS_ERR_TIMEOUT: return "request timed out";
  1823. case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
  1824. default: return "[Unknown error code]";
  1825. }
  1826. }
  1827. void
  1828. evdns_shutdown(int fail_requests)
  1829. {
  1830. struct nameserver *server, *server_next;
  1831. struct search_domain *dom, *dom_next;
  1832. while (req_head) {
  1833. if (fail_requests)
  1834. reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
  1835. request_finished(req_head, &req_head);
  1836. }
  1837. while (req_waiting_head) {
  1838. if (fail_requests)
  1839. reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
  1840. request_finished(req_waiting_head, &req_waiting_head);
  1841. }
  1842. global_requests_inflight = global_requests_waiting = 0;
  1843. for (server = server_head; server; server = server_next) {
  1844. server_next = server->next;
  1845. if (server->socket >= 0)
  1846. CLOSE_SOCKET(server->socket);
  1847. (void) event_del(&server->event);
  1848. free(server);
  1849. if (server_next == server_head)
  1850. break;
  1851. }
  1852. server_head = NULL;
  1853. global_good_nameservers = 0;
  1854. if (global_search_state) {
  1855. for (dom = global_search_state->head; dom; dom = dom_next) {
  1856. dom_next = dom->next;
  1857. free(dom);
  1858. }
  1859. free(global_search_state);
  1860. global_search_state = NULL;
  1861. }
  1862. evdns_log_fn = NULL;
  1863. }
  1864. #ifdef EVDNS_MAIN
  1865. void
  1866. main_callback(int result, char type, int count, int ttl,
  1867. void *addrs, void *orig) {
  1868. char *n = (char*)orig;
  1869. int i;
  1870. for (i = 0; i < count; ++i) {
  1871. if (type == DNS_IPv4_A) {
  1872. printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
  1873. } else if (type == DNS_PTR) {
  1874. printf("%s: %s\n", n, ((char**)addrs)[i]);
  1875. }
  1876. }
  1877. if (!count) {
  1878. printf("%s: No answer (%d)\n", n, result);
  1879. }
  1880. fflush(stdout);
  1881. }
  1882. void
  1883. logfn(const char *msg) {
  1884. fprintf(stderr, "%s\n", msg);
  1885. }
  1886. int
  1887. main(int c, char **v) {
  1888. int idx;
  1889. int reverse = 0, verbose = 1;
  1890. if (c<2) {
  1891. fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
  1892. return 1;
  1893. }
  1894. idx = 1;
  1895. while (idx < c && v[idx][0] == '-') {
  1896. if (!strcmp(v[idx], "-x"))
  1897. reverse = 1;
  1898. else if (!strcmp(v[idx], "-v"))
  1899. verbose = 1;
  1900. else
  1901. fprintf(stderr, "Unknown option %s\n", v[idx]);
  1902. ++idx;
  1903. }
  1904. event_init();
  1905. if (verbose)
  1906. evdns_set_log_fn(logfn);
  1907. evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
  1908. for (; idx < c; ++idx) {
  1909. if (reverse) {
  1910. struct in_addr addr;
  1911. if (!inet_aton(v[idx], &addr)) {
  1912. fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
  1913. continue;
  1914. }
  1915. fprintf(stderr, "resolving %s...\n",v[idx]);
  1916. evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
  1917. } else {
  1918. fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
  1919. evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
  1920. }
  1921. }
  1922. fflush(stdout);
  1923. event_dispatch();
  1924. return 0;
  1925. }
  1926. #endif