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.

1325 lines
41 KiB

  1. /* udns_resolver.c
  2. resolver stuff (main module)
  3. Copyright (C) 2005 Michael Tokarev <mjt@corpit.ru>
  4. This file is part of UDNS library, an async DNS stub resolver.
  5. This library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. This library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with this library, in file named COPYING.LGPL; if not,
  15. write to the Free Software Foundation, Inc., 59 Temple Place,
  16. Suite 330, Boston, MA 02111-1307 USA
  17. */
  18. #ifdef HAVE_CONFIG_H
  19. # include "config.h"
  20. #endif
  21. #ifdef __MINGW32__
  22. # include <winsock2.h> /* includes <windows.h> */
  23. # include <ws2tcpip.h> /* needed for struct in6_addr */
  24. #else
  25. # include <sys/types.h>
  26. # include <sys/socket.h>
  27. # include <netinet/in.h>
  28. # include <unistd.h>
  29. # include <fcntl.h>
  30. # include <sys/time.h>
  31. # ifdef HAVE_POLL
  32. # include <sys/poll.h>
  33. # else
  34. # ifdef HAVE_SYS_SELECT_H
  35. # include <sys/select.h>
  36. # endif
  37. # endif
  38. # ifdef HAVE_TIMES
  39. # include <sys/times.h>
  40. # endif
  41. # define closesocket(sock) close(sock)
  42. #endif /* !__MINGW32__ */
  43. #include <stdlib.h>
  44. #include <string.h>
  45. #include <time.h>
  46. #include <errno.h>
  47. #include <assert.h>
  48. #include <stddef.h>
  49. #include "udns.h"
  50. #ifndef EAFNOSUPPORT
  51. # define EAFNOSUPPORT EINVAL
  52. #endif
  53. #ifndef MSG_DONTWAIT
  54. # define MSG_DONTWAIT 0
  55. #endif
  56. struct dns_qlist {
  57. struct dns_query *head, *tail;
  58. };
  59. struct dns_query {
  60. struct dns_query *dnsq_next; /* double-linked list */
  61. struct dns_query *dnsq_prev;
  62. unsigned dnsq_origdnl0; /* original query DN len w/o last 0 */
  63. unsigned dnsq_flags; /* control flags for this query */
  64. unsigned dnsq_servi; /* index of next server to try */
  65. unsigned dnsq_servwait; /* bitmask: servers left to wait */
  66. unsigned dnsq_servskip; /* bitmask: servers to skip */
  67. unsigned dnsq_servnEDNS0; /* bitmask: servers refusing EDNS0 */
  68. unsigned dnsq_try; /* number of tries made so far */
  69. dnscc_t *dnsq_nxtsrch; /* next search pointer @dnsc_srchbuf */
  70. time_t dnsq_deadline; /* when current try will expire */
  71. dns_parse_fn *dnsq_parse; /* parse: raw => application */
  72. dns_query_fn *dnsq_cbck; /* the callback to call when done */
  73. void *dnsq_cbdata; /* user data for the callback */
  74. #ifndef NDEBUG
  75. struct dns_ctx *dnsq_ctx; /* the resolver context */
  76. #endif
  77. /* char fields at the end to avoid padding */
  78. dnsc_t dnsq_id[2]; /* query ID */
  79. dnsc_t dnsq_typcls[4]; /* requested RR type+class */
  80. dnsc_t dnsq_dn[DNS_MAXDN+DNS_DNPAD]; /* the query DN +alignment */
  81. };
  82. /* working with dns_query lists */
  83. static __inline void qlist_init(struct dns_qlist *list) {
  84. list->head = list->tail = NULL;
  85. }
  86. static __inline void qlist_remove(struct dns_qlist *list, struct dns_query *q) {
  87. if (q->dnsq_prev) q->dnsq_prev->dnsq_next = q->dnsq_next;
  88. else list->head = q->dnsq_next;
  89. if (q->dnsq_next) q->dnsq_next->dnsq_prev = q->dnsq_prev;
  90. else list->tail = q->dnsq_prev;
  91. }
  92. static __inline void
  93. qlist_add_head(struct dns_qlist *list, struct dns_query *q) {
  94. q->dnsq_next = list->head;
  95. if (list->head) list->head->dnsq_prev = q;
  96. else list->tail = q;
  97. list->head = q;
  98. q->dnsq_prev = NULL;
  99. }
  100. static __inline void
  101. qlist_insert_after(struct dns_qlist *list,
  102. struct dns_query *q, struct dns_query *prev) {
  103. if ((q->dnsq_prev = prev) != NULL) {
  104. if ((q->dnsq_next = prev->dnsq_next) != NULL)
  105. q->dnsq_next->dnsq_prev = q;
  106. else
  107. list->tail = q;
  108. prev->dnsq_next = q;
  109. }
  110. else
  111. qlist_add_head(list, q);
  112. }
  113. struct sockaddr_ns {
  114. union {
  115. struct sockaddr sa;
  116. struct sockaddr_in sin;
  117. #ifdef HAVE_IPv6
  118. struct sockaddr_in6 sin6;
  119. #endif
  120. };
  121. };
  122. #define sin_eq(a,b) \
  123. ((a).sin_port == (b).sin_port && \
  124. (a).sin_addr.s_addr == (b).sin_addr.s_addr)
  125. #define sin6_eq(a,b) \
  126. ((a).sin6_port == (b).sin6_port && \
  127. memcmp(&(a).sin6_addr, &(b).sin6_addr, sizeof(struct in6_addr)) == 0)
  128. struct dns_ctx { /* resolver context */
  129. /* settings */
  130. unsigned dnsc_flags; /* various flags */
  131. unsigned dnsc_timeout; /* timeout (base value) for queries */
  132. unsigned dnsc_ntries; /* number of retries */
  133. unsigned dnsc_ndots; /* ndots to assume absolute name */
  134. unsigned dnsc_port; /* default port (DNS_PORT) */
  135. unsigned dnsc_udpbuf; /* size of UDP buffer */
  136. /* array of nameserver addresses */
  137. struct sockaddr_ns dnsc_serv[DNS_MAXSERV];
  138. unsigned dnsc_nserv; /* number of nameservers */
  139. unsigned dnsc_salen; /* length of socket addresses */
  140. dnsc_t dnsc_srchbuf[1024]; /* buffer for searchlist */
  141. dnsc_t *dnsc_srchend; /* current end of srchbuf */
  142. dns_utm_fn *dnsc_utmfn; /* register/cancel timer events */
  143. void *dnsc_utmctx; /* user timer context for utmfn() */
  144. time_t dnsc_utmexp; /* when user timer expires */
  145. dns_dbgfn *dnsc_udbgfn; /* debugging function */
  146. /* dynamic data */
  147. struct udns_jranctx dnsc_jran; /* random number generator state */
  148. unsigned dnsc_nextid; /* next queue ID to use if !0 */
  149. int dnsc_udpsock; /* UDP socket */
  150. struct dns_qlist dnsc_qactive; /* active list sorted by deadline */
  151. int dnsc_nactive; /* number entries in dnsc_qactive */
  152. dnsc_t *dnsc_pbuf; /* packet buffer (udpbuf size) */
  153. int dnsc_qstatus; /* last query status value */
  154. };
  155. static const struct {
  156. const char *name;
  157. enum dns_opt opt;
  158. unsigned offset;
  159. unsigned min, max;
  160. } dns_opts[] = {
  161. #define opt(name,opt,field,min,max) \
  162. {name,opt,offsetof(struct dns_ctx,field),min,max}
  163. opt("retrans", DNS_OPT_TIMEOUT, dnsc_timeout, 1,300),
  164. opt("timeout", DNS_OPT_TIMEOUT, dnsc_timeout, 1,300),
  165. opt("retry", DNS_OPT_NTRIES, dnsc_ntries, 1,50),
  166. opt("attempts", DNS_OPT_NTRIES, dnsc_ntries, 1,50),
  167. opt("ndots", DNS_OPT_NDOTS, dnsc_ndots, 0,1000),
  168. opt("port", DNS_OPT_PORT, dnsc_port, 1,0xffff),
  169. opt("udpbuf", DNS_OPT_UDPSIZE, dnsc_udpbuf, DNS_MAXPACKET,65536),
  170. #undef opt
  171. };
  172. #define dns_ctxopt(ctx,idx) (*((unsigned*)(((char*)ctx)+dns_opts[idx].offset)))
  173. #define ISSPACE(x) (x == ' ' || x == '\t' || x == '\r' || x == '\n')
  174. struct dns_ctx dns_defctx;
  175. #define SETCTX(ctx) if (!ctx) ctx = &dns_defctx
  176. #define SETCTXINITED(ctx) SETCTX(ctx); assert(CTXINITED(ctx))
  177. #define CTXINITED(ctx) (ctx->dnsc_flags & DNS_INITED)
  178. #define SETCTXFRESH(ctx) SETCTXINITED(ctx); assert(!CTXOPEN(ctx))
  179. #define SETCTXINACTIVE(ctx) \
  180. SETCTXINITED(ctx); assert(!ctx->dnsc_nactive)
  181. #define SETCTXOPEN(ctx) SETCTXINITED(ctx); assert(CTXOPEN(ctx))
  182. #define CTXOPEN(ctx) (ctx->dnsc_udpsock >= 0)
  183. #if defined(NDEBUG) || !defined(DEBUG)
  184. #define dns_assert_ctx(ctx)
  185. #else
  186. static void dns_assert_ctx(const struct dns_ctx *ctx) {
  187. int nactive = 0;
  188. const struct dns_query *q;
  189. for(q = ctx->dnsc_qactive.head; q; q = q->dnsq_next) {
  190. assert(q->dnsq_ctx == ctx);
  191. assert(q == (q->dnsq_next ?
  192. q->dnsq_next->dnsq_prev : ctx->dnsc_qactive.tail));
  193. assert(q == (q->dnsq_prev ?
  194. q->dnsq_prev->dnsq_next : ctx->dnsc_qactive.head));
  195. ++nactive;
  196. }
  197. assert(nactive == ctx->dnsc_nactive);
  198. }
  199. #endif
  200. enum {
  201. DNS_INTERNAL = 0xffff, /* internal flags mask */
  202. DNS_INITED = 0x0001, /* the context is initialized */
  203. DNS_ASIS_DONE = 0x0002, /* search: skip the last as-is query */
  204. DNS_SEEN_NODATA = 0x0004, /* search: NODATA has been received */
  205. };
  206. int dns_add_serv(struct dns_ctx *ctx, const char *serv) {
  207. struct sockaddr_ns *sns;
  208. SETCTXFRESH(ctx);
  209. if (!serv)
  210. return (ctx->dnsc_nserv = 0);
  211. if (ctx->dnsc_nserv >= DNS_MAXSERV)
  212. return errno = ENFILE, -1;
  213. sns = &ctx->dnsc_serv[ctx->dnsc_nserv];
  214. memset(sns, 0, sizeof(*sns));
  215. if (dns_pton(AF_INET, serv, &sns->sin.sin_addr) > 0) {
  216. sns->sin.sin_family = AF_INET;
  217. return ++ctx->dnsc_nserv;
  218. }
  219. #ifdef HAVE_IPv6
  220. if (dns_pton(AF_INET6, serv, &sns->sin6.sin6_addr) > 0) {
  221. sns->sin6.sin6_family = AF_INET6;
  222. return ++ctx->dnsc_nserv;
  223. }
  224. #endif
  225. errno = EINVAL;
  226. return -1;
  227. }
  228. int dns_add_serv_s(struct dns_ctx *ctx, const struct sockaddr *sa) {
  229. SETCTXFRESH(ctx);
  230. if (!sa)
  231. return (ctx->dnsc_nserv = 0);
  232. if (ctx->dnsc_nserv >= DNS_MAXSERV)
  233. return errno = ENFILE, -1;
  234. #ifdef HAVE_IPv6
  235. else if (sa->sa_family == AF_INET6)
  236. ctx->dnsc_serv[ctx->dnsc_nserv].sin6 = *(struct sockaddr_in6*)sa;
  237. #endif
  238. else if (sa->sa_family == AF_INET)
  239. ctx->dnsc_serv[ctx->dnsc_nserv].sin = *(struct sockaddr_in*)sa;
  240. else
  241. return errno = EAFNOSUPPORT, -1;
  242. return ++ctx->dnsc_nserv;
  243. }
  244. int dns_set_opts(struct dns_ctx *ctx, const char *opts) {
  245. unsigned i, v;
  246. int err = 0;
  247. SETCTXINACTIVE(ctx);
  248. for(;;) {
  249. while(ISSPACE(*opts)) ++opts;
  250. if (!*opts) break;
  251. for(i = 0; ; ++i) {
  252. if (i >= sizeof(dns_opts)/sizeof(dns_opts[0])) { ++err; break; }
  253. v = strlen(dns_opts[i].name);
  254. if (strncmp(dns_opts[i].name, opts, v) != 0 ||
  255. (opts[v] != ':' && opts[v] != '='))
  256. continue;
  257. opts += v + 1;
  258. v = 0;
  259. if (*opts < '0' || *opts > '9') { ++err; break; }
  260. do v = v * 10 + (*opts++ - '0');
  261. while (*opts >= '0' && *opts <= '9');
  262. if (v < dns_opts[i].min) v = dns_opts[i].min;
  263. if (v > dns_opts[i].max) v = dns_opts[i].max;
  264. dns_ctxopt(ctx, i) = v;
  265. break;
  266. }
  267. while(*opts && !ISSPACE(*opts)) ++opts;
  268. }
  269. return err;
  270. }
  271. int dns_set_opt(struct dns_ctx *ctx, enum dns_opt opt, int val) {
  272. int prev;
  273. unsigned i;
  274. SETCTXINACTIVE(ctx);
  275. for(i = 0; i < sizeof(dns_opts)/sizeof(dns_opts[0]); ++i) {
  276. if (dns_opts[i].opt != opt) continue;
  277. prev = dns_ctxopt(ctx, i);
  278. if (val >= 0) {
  279. unsigned v = val;
  280. if (v < dns_opts[i].min || v > dns_opts[i].max) {
  281. errno = EINVAL;
  282. return -1;
  283. }
  284. dns_ctxopt(ctx, i) = v;
  285. }
  286. return prev;
  287. }
  288. if (opt == DNS_OPT_FLAGS) {
  289. prev = ctx->dnsc_flags & ~DNS_INTERNAL;
  290. if (val >= 0)
  291. ctx->dnsc_flags =
  292. (ctx->dnsc_flags & DNS_INTERNAL) | (val & ~DNS_INTERNAL);
  293. return prev;
  294. }
  295. errno = ENOSYS;
  296. return -1;
  297. }
  298. int dns_add_srch(struct dns_ctx *ctx, const char *srch) {
  299. int dnl;
  300. SETCTXINACTIVE(ctx);
  301. if (!srch) {
  302. memset(ctx->dnsc_srchbuf, 0, sizeof(ctx->dnsc_srchbuf));
  303. ctx->dnsc_srchend = ctx->dnsc_srchbuf;
  304. return 0;
  305. }
  306. dnl =
  307. sizeof(ctx->dnsc_srchbuf) - (ctx->dnsc_srchend - ctx->dnsc_srchbuf) - 1;
  308. dnl = dns_sptodn(srch, ctx->dnsc_srchend, dnl);
  309. if (dnl > 0)
  310. ctx->dnsc_srchend += dnl;
  311. ctx->dnsc_srchend[0] = '\0'; /* we ensure the list is always ends at . */
  312. if (dnl > 0)
  313. return 0;
  314. errno = EINVAL;
  315. return -1;
  316. }
  317. static void dns_drop_utm(struct dns_ctx *ctx) {
  318. if (ctx->dnsc_utmfn)
  319. ctx->dnsc_utmfn(NULL, -1, ctx->dnsc_utmctx);
  320. ctx->dnsc_utmctx = NULL;
  321. ctx->dnsc_utmexp = -1;
  322. }
  323. static void
  324. _dns_request_utm(struct dns_ctx *ctx, time_t now) {
  325. struct dns_query *q;
  326. time_t deadline;
  327. int timeout;
  328. q = ctx->dnsc_qactive.head;
  329. if (!q)
  330. deadline = -1, timeout = -1;
  331. else if (!now || q->dnsq_deadline <= now)
  332. deadline = 0, timeout = 0;
  333. else
  334. deadline = q->dnsq_deadline, timeout = (int)(deadline - now);
  335. if (ctx->dnsc_utmexp == deadline)
  336. return;
  337. ctx->dnsc_utmfn(ctx, timeout, ctx->dnsc_utmctx);
  338. ctx->dnsc_utmexp = deadline;
  339. }
  340. static __inline void
  341. dns_request_utm(struct dns_ctx *ctx, time_t now) {
  342. if (ctx->dnsc_utmfn)
  343. _dns_request_utm(ctx, now);
  344. }
  345. void dns_set_dbgfn(struct dns_ctx *ctx, dns_dbgfn *dbgfn) {
  346. SETCTXINITED(ctx);
  347. ctx->dnsc_udbgfn = dbgfn;
  348. }
  349. void
  350. dns_set_tmcbck(struct dns_ctx *ctx, dns_utm_fn *fn, void *data) {
  351. SETCTXINITED(ctx);
  352. dns_drop_utm(ctx);
  353. ctx->dnsc_utmfn = fn;
  354. ctx->dnsc_utmctx = data;
  355. if (CTXOPEN(ctx))
  356. dns_request_utm(ctx, 0);
  357. }
  358. static unsigned dns_nonrandom_32(void) {
  359. #ifdef __MINGW32__
  360. FILETIME ft;
  361. GetSystemTimeAsFileTime(&ft);
  362. return ft.dwLowDateTime;
  363. #else
  364. struct timeval tv;
  365. gettimeofday(&tv, NULL);
  366. return tv.tv_usec;
  367. #endif
  368. }
  369. /* This is historic deprecated API */
  370. UDNS_API unsigned dns_random16(void);
  371. unsigned dns_random16(void) {
  372. unsigned x = dns_nonrandom_32();
  373. return (x ^ (x >> 16)) & 0xffff;
  374. }
  375. static void dns_init_rng(struct dns_ctx *ctx) {
  376. udns_jraninit(&ctx->dnsc_jran, dns_nonrandom_32());
  377. ctx->dnsc_nextid = 0;
  378. }
  379. void dns_close(struct dns_ctx *ctx) {
  380. struct dns_query *q, *p;
  381. SETCTX(ctx);
  382. if (CTXINITED(ctx)) {
  383. if (ctx->dnsc_udpsock >= 0)
  384. closesocket(ctx->dnsc_udpsock);
  385. ctx->dnsc_udpsock = -1;
  386. if (ctx->dnsc_pbuf)
  387. free(ctx->dnsc_pbuf);
  388. ctx->dnsc_pbuf = NULL;
  389. q = ctx->dnsc_qactive.head;
  390. while((p = q) != NULL) {
  391. q = q->dnsq_next;
  392. free(p);
  393. }
  394. qlist_init(&ctx->dnsc_qactive);
  395. ctx->dnsc_nactive = 0;
  396. dns_drop_utm(ctx);
  397. }
  398. }
  399. void dns_reset(struct dns_ctx *ctx) {
  400. SETCTX(ctx);
  401. dns_close(ctx);
  402. memset(ctx, 0, sizeof(*ctx));
  403. ctx->dnsc_timeout = 4;
  404. ctx->dnsc_ntries = 3;
  405. ctx->dnsc_ndots = 1;
  406. ctx->dnsc_udpbuf = DNS_EDNS0PACKET;
  407. ctx->dnsc_port = DNS_PORT;
  408. ctx->dnsc_udpsock = -1;
  409. ctx->dnsc_srchend = ctx->dnsc_srchbuf;
  410. qlist_init(&ctx->dnsc_qactive);
  411. dns_init_rng(ctx);
  412. ctx->dnsc_flags = DNS_INITED;
  413. }
  414. struct dns_ctx *dns_new(const struct dns_ctx *copy) {
  415. struct dns_ctx *ctx;
  416. SETCTXINITED(copy);
  417. dns_assert_ctx(copy);
  418. ctx = malloc(sizeof(*ctx));
  419. if (!ctx)
  420. return NULL;
  421. *ctx = *copy;
  422. ctx->dnsc_udpsock = -1;
  423. qlist_init(&ctx->dnsc_qactive);
  424. ctx->dnsc_nactive = 0;
  425. ctx->dnsc_pbuf = NULL;
  426. ctx->dnsc_qstatus = 0;
  427. ctx->dnsc_srchend = ctx->dnsc_srchbuf +
  428. (copy->dnsc_srchend - copy->dnsc_srchbuf);
  429. ctx->dnsc_utmfn = NULL;
  430. ctx->dnsc_utmctx = NULL;
  431. dns_init_rng(ctx);
  432. return ctx;
  433. }
  434. void dns_free(struct dns_ctx *ctx) {
  435. assert(ctx != NULL && ctx != &dns_defctx);
  436. dns_reset(ctx);
  437. free(ctx);
  438. }
  439. int dns_open(struct dns_ctx *ctx) {
  440. int sock;
  441. unsigned i;
  442. int port;
  443. struct sockaddr_ns *sns;
  444. #ifdef HAVE_IPv6
  445. unsigned have_inet6 = 0;
  446. #endif
  447. SETCTXINITED(ctx);
  448. assert(!CTXOPEN(ctx));
  449. port = htons((unsigned short)ctx->dnsc_port);
  450. /* ensure we have at least one server */
  451. if (!ctx->dnsc_nserv) {
  452. sns = ctx->dnsc_serv;
  453. sns->sin.sin_family = AF_INET;
  454. sns->sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  455. ctx->dnsc_nserv = 1;
  456. }
  457. for (i = 0; i < ctx->dnsc_nserv; ++i) {
  458. sns = &ctx->dnsc_serv[i];
  459. /* set port for each sockaddr */
  460. #ifdef HAVE_IPv6
  461. if (sns->sa.sa_family == AF_INET6) {
  462. if (!sns->sin6.sin6_port) sns->sin6.sin6_port = (unsigned short)port;
  463. ++have_inet6;
  464. }
  465. else
  466. #endif
  467. {
  468. assert(sns->sa.sa_family == AF_INET);
  469. if (!sns->sin.sin_port) sns->sin.sin_port = (unsigned short)port;
  470. }
  471. }
  472. #ifdef HAVE_IPv6
  473. if (have_inet6 && have_inet6 < ctx->dnsc_nserv) {
  474. /* convert all IPv4 addresses to IPv6 V4MAPPED */
  475. struct sockaddr_in6 sin6;
  476. memset(&sin6, 0, sizeof(sin6));
  477. sin6.sin6_family = AF_INET6;
  478. /* V4MAPPED: ::ffff:1.2.3.4 */
  479. sin6.sin6_addr.s6_addr[10] = 0xff;
  480. sin6.sin6_addr.s6_addr[11] = 0xff;
  481. for(i = 0; i < ctx->dnsc_nserv; ++i) {
  482. sns = &ctx->dnsc_serv[i];
  483. if (sns->sa.sa_family == AF_INET) {
  484. sin6.sin6_port = sns->sin.sin_port;
  485. memcpy(sin6.sin6_addr.s6_addr + 4*3, &sns->sin.sin_addr, 4);
  486. sns->sin6 = sin6;
  487. }
  488. }
  489. }
  490. ctx->dnsc_salen = have_inet6 ?
  491. sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
  492. if (have_inet6)
  493. sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
  494. else
  495. sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  496. #else /* !HAVE_IPv6 */
  497. sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  498. ctx->dnsc_salen = sizeof(struct sockaddr_in);
  499. #endif /* HAVE_IPv6 */
  500. if (sock < 0) {
  501. ctx->dnsc_qstatus = DNS_E_TEMPFAIL;
  502. return -1;
  503. }
  504. #ifdef __MINGW32__
  505. { unsigned long on = 1;
  506. if (ioctlsocket(sock, FIONBIO, &on) == SOCKET_ERROR) {
  507. closesocket(sock);
  508. ctx->dnsc_qstatus = DNS_E_TEMPFAIL;
  509. return -1;
  510. }
  511. }
  512. #else /* !__MINGW32__ */
  513. if (fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK) < 0 ||
  514. fcntl(sock, F_SETFD, FD_CLOEXEC) < 0) {
  515. closesocket(sock);
  516. ctx->dnsc_qstatus = DNS_E_TEMPFAIL;
  517. return -1;
  518. }
  519. #endif /* __MINGW32__ */
  520. /* allocate the packet buffer */
  521. if ((ctx->dnsc_pbuf = malloc(ctx->dnsc_udpbuf)) == NULL) {
  522. closesocket(sock);
  523. ctx->dnsc_qstatus = DNS_E_NOMEM;
  524. errno = ENOMEM;
  525. return -1;
  526. }
  527. ctx->dnsc_udpsock = sock;
  528. dns_request_utm(ctx, 0);
  529. return sock;
  530. }
  531. int dns_sock(const struct dns_ctx *ctx) {
  532. SETCTXINITED(ctx);
  533. return ctx->dnsc_udpsock;
  534. }
  535. int dns_active(const struct dns_ctx *ctx) {
  536. SETCTXINITED(ctx);
  537. dns_assert_ctx(ctx);
  538. return ctx->dnsc_nactive;
  539. }
  540. int dns_status(const struct dns_ctx *ctx) {
  541. SETCTX(ctx);
  542. return ctx->dnsc_qstatus;
  543. }
  544. void dns_setstatus(struct dns_ctx *ctx, int status) {
  545. SETCTX(ctx);
  546. ctx->dnsc_qstatus = status;
  547. }
  548. /* End the query: disconnect it from the active list, free it,
  549. * and return the result to the caller.
  550. */
  551. static void
  552. dns_end_query(struct dns_ctx *ctx, struct dns_query *q,
  553. int status, void *result) {
  554. dns_query_fn *cbck = q->dnsq_cbck;
  555. void *cbdata = q->dnsq_cbdata;
  556. ctx->dnsc_qstatus = status;
  557. assert((status < 0 && result == 0) || (status >= 0 && result != 0));
  558. assert(cbck != 0); /*XXX callback may be NULL */
  559. assert(ctx->dnsc_nactive > 0);
  560. --ctx->dnsc_nactive;
  561. qlist_remove(&ctx->dnsc_qactive, q);
  562. /* force the query to be unconnected */
  563. /*memset(q, 0, sizeof(*q));*/
  564. #ifndef NDEBUG
  565. q->dnsq_ctx = NULL;
  566. #endif
  567. free(q);
  568. cbck(ctx, result, cbdata);
  569. }
  570. #define DNS_DBG(ctx, code, sa, slen, pkt, plen) \
  571. do { \
  572. if (ctx->dnsc_udbgfn) \
  573. ctx->dnsc_udbgfn(code, (sa), slen, pkt, plen, 0, 0); \
  574. } while(0)
  575. #define DNS_DBGQ(ctx, q, code, sa, slen, pkt, plen) \
  576. do { \
  577. if (ctx->dnsc_udbgfn) \
  578. ctx->dnsc_udbgfn(code, (sa), slen, pkt, plen, q, q->dnsq_cbdata); \
  579. } while(0)
  580. static void dns_newid(struct dns_ctx *ctx, struct dns_query *q) {
  581. /* this is how we choose an identifier for a new query (qID).
  582. * For now, it's just sequential number, incremented for every query, and
  583. * thus obviously trivial to guess.
  584. * There are two choices:
  585. * a) use sequential numbers. It is plain insecure. In DNS, there are two
  586. * places where random numbers are (or can) be used to increase security:
  587. * random qID and random source port number. Without this randomness
  588. * (udns uses fixed port for all queries), or when the randomness is weak,
  589. * it's trivial to spoof query replies. With randomness however, it
  590. * becomes a bit more difficult task. Too bad we only have 16 bits for
  591. * our security, as qID is only two bytes. It isn't a security per se,
  592. * to rely on those 16 bits - an attacker can just flood us with fake
  593. * replies with all possible qIDs (only 65536 of them), and in this case,
  594. * even if we'll use true random qIDs, we'll be in trouble (not protected
  595. * against spoofing). Yes, this is only possible on a high-speed network
  596. * (probably on the LAN only, since usually a border router for a LAN
  597. * protects internal machines from packets with spoofed local addresses
  598. * from outside, and usually a nameserver resides on LAN), but it's
  599. * still very well possible to send us fake replies.
  600. * In other words: there's nothing a DNS (stub) resolver can do against
  601. * spoofing attacks, unless DNSSEC is in use, which helps here alot.
  602. * Too bad that DNSSEC isn't widespread, so relying on it isn't an
  603. * option in almost all cases...
  604. * b) use random qID, based on some random-number generation mechanism.
  605. * This way, we increase our protection a bit (see above - it's very weak
  606. * still), but we also increase risk of qID reuse and matching late replies
  607. * that comes to queries we've sent before against new queries. There are
  608. * some more corner cases around that, as well - for example, normally,
  609. * udns tries to find the query for a given reply by qID, *and* by
  610. * verifying that the query DN and other parameters are also the same
  611. * (so if the new query is against another domain name, old reply will
  612. * be ignored automatically). But certain types of replies which we now
  613. * handle - for example, FORMERR reply from servers which refuses to
  614. * process EDNS0-enabled packets - comes without all the query parameters
  615. * but the qID - so we're forced to use qID only when determining which
  616. * query the given reply corresponds to. This makes us even more
  617. * vulnerable to spoofing attacks, because an attacker don't even need to
  618. * know which queries we perform to spoof the replies - he only needs to
  619. * flood us with fake FORMERR "replies".
  620. *
  621. * That all to say: using sequential (or any other trivially guessable)
  622. * numbers for qIDs is insecure, but the whole thing is inherently insecure
  623. * as well, and this "extra weakness" that comes from weak qID choosing
  624. * algorithm adds almost nothing to the underlying problem.
  625. *
  626. * It CAN NOT be made secure. Period. That's it.
  627. * Unless we choose to implement DNSSEC, which is a whole different story.
  628. * Forcing TCP mode makes it better, but who uses TCP for DNS anyway?
  629. * (and it's hardly possible because of huge impact on the recursive
  630. * nameservers).
  631. *
  632. * Note that ALL stub resolvers (again, unless they implement and enforce
  633. * DNSSEC) suffers from this same problem.
  634. *
  635. * Here, I use a pseudo-random number generator for qIDs, instead of a
  636. * simpler sequential IDs. This is _not_ more secure than sequential
  637. * ID, but some found random IDs more enjoyeable for some reason. So
  638. * here it goes.
  639. */
  640. /* Use random number and check if it's unique.
  641. * If it's not, try again up to 5 times.
  642. */
  643. unsigned loop;
  644. dnsc_t c0, c1;
  645. for(loop = 0; loop < 5; ++loop) {
  646. const struct dns_query *c;
  647. if (!ctx->dnsc_nextid)
  648. ctx->dnsc_nextid = udns_jranval(&ctx->dnsc_jran);
  649. c0 = ctx->dnsc_nextid & 0xff;
  650. c1 = (ctx->dnsc_nextid >> 8) & 0xff;
  651. ctx->dnsc_nextid >>= 16;
  652. for(c = ctx->dnsc_qactive.head; c; c = c->dnsq_next)
  653. if (c->dnsq_id[0] == c0 && c->dnsq_id[1] == c1)
  654. break; /* found such entry, try again */
  655. if (!c)
  656. break;
  657. }
  658. q->dnsq_id[0] = c0; q->dnsq_id[1] = c1;
  659. /* reset all parameters relevant for previous query lifetime */
  660. q->dnsq_try = 0;
  661. q->dnsq_servi = 0;
  662. /*XXX probably should keep dnsq_servnEDNS0 bits?
  663. * See also comments in dns_ioevent() about FORMERR case */
  664. q->dnsq_servwait = q->dnsq_servskip = q->dnsq_servnEDNS0 = 0;
  665. }
  666. /* Find next search suffix and fills in q->dnsq_dn.
  667. * Return 0 if no more to try. */
  668. static int dns_next_srch(struct dns_ctx *ctx, struct dns_query *q) {
  669. unsigned dnl;
  670. for(;;) {
  671. if (q->dnsq_nxtsrch > ctx->dnsc_srchend)
  672. return 0;
  673. dnl = dns_dnlen(q->dnsq_nxtsrch);
  674. if (dnl + q->dnsq_origdnl0 <= DNS_MAXDN &&
  675. (*q->dnsq_nxtsrch || !(q->dnsq_flags & DNS_ASIS_DONE)))
  676. break;
  677. q->dnsq_nxtsrch += dnl;
  678. }
  679. memcpy(q->dnsq_dn + q->dnsq_origdnl0, q->dnsq_nxtsrch, dnl);
  680. if (!*q->dnsq_nxtsrch)
  681. q->dnsq_flags |= DNS_ASIS_DONE;
  682. q->dnsq_nxtsrch += dnl;
  683. dns_newid(ctx, q); /* new ID for new qDN */
  684. return 1;
  685. }
  686. /* find the server to try for current iteration.
  687. * Note that current dnsq_servi may point to a server we should skip --
  688. * in that case advance to the next server.
  689. * Return true if found, false if all tried.
  690. */
  691. static int dns_find_serv(const struct dns_ctx *ctx, struct dns_query *q) {
  692. while(q->dnsq_servi < ctx->dnsc_nserv) {
  693. if (!(q->dnsq_servskip & (1 << q->dnsq_servi)))
  694. return 1;
  695. ++q->dnsq_servi;
  696. }
  697. return 0;
  698. }
  699. /* format and send the query to a given server.
  700. * In case of network problem (sendto() fails), return -1,
  701. * else return 0.
  702. */
  703. static int
  704. dns_send_this(struct dns_ctx *ctx, struct dns_query *q,
  705. unsigned servi, time_t now) {
  706. unsigned qlen;
  707. unsigned tries;
  708. { /* format the query buffer */
  709. dnsc_t *p = ctx->dnsc_pbuf;
  710. memset(p, 0, DNS_HSIZE);
  711. if (!(q->dnsq_flags & DNS_NORD)) p[DNS_H_F1] |= DNS_HF1_RD;
  712. if (q->dnsq_flags & DNS_AAONLY) p[DNS_H_F1] |= DNS_HF1_AA;
  713. if (q->dnsq_flags & DNS_SET_CD) p[DNS_H_F2] |= DNS_HF2_CD;
  714. p[DNS_H_QDCNT2] = 1;
  715. memcpy(p + DNS_H_QID, q->dnsq_id, 2);
  716. p = dns_payload(p);
  717. /* copy query dn */
  718. p += dns_dntodn(q->dnsq_dn, p, DNS_MAXDN);
  719. /* query type and class */
  720. memcpy(p, q->dnsq_typcls, 4); p += 4;
  721. /* add EDNS0 record. DO flag requires it */
  722. if (q->dnsq_flags & DNS_SET_DO ||
  723. (ctx->dnsc_udpbuf > DNS_MAXPACKET &&
  724. !(q->dnsq_servnEDNS0 & (1 << servi)))) {
  725. *p++ = 0; /* empty (root) DN */
  726. p = dns_put16(p, DNS_T_OPT);
  727. p = dns_put16(p, ctx->dnsc_udpbuf);
  728. /* EDNS0 RCODE & VERSION; rest of the TTL field; RDLEN */
  729. memset(p, 0, 2+2+2);
  730. if (q->dnsq_flags & DNS_SET_DO) p[2] |= DNS_EF1_DO;
  731. p += 2+2+2;
  732. ctx->dnsc_pbuf[DNS_H_ARCNT2] = 1;
  733. }
  734. qlen = p - ctx->dnsc_pbuf;
  735. assert(qlen <= ctx->dnsc_udpbuf);
  736. }
  737. /* send the query */
  738. tries = 10;
  739. while (sendto(ctx->dnsc_udpsock, (void*)ctx->dnsc_pbuf, qlen, 0,
  740. &ctx->dnsc_serv[servi].sa, ctx->dnsc_salen) < 0) {
  741. /*XXX just ignore the sendto() error for now and try again.
  742. * In the future, it may be possible to retrieve the error code
  743. * and find which operation/query failed.
  744. *XXX try the next server too? (if ENETUNREACH is returned immediately)
  745. */
  746. if (--tries) continue;
  747. /* if we can't send the query, fail it. */
  748. dns_end_query(ctx, q, DNS_E_TEMPFAIL, 0);
  749. return -1;
  750. }
  751. DNS_DBGQ(ctx, q, 1,
  752. &ctx->dnsc_serv[servi].sa, sizeof(struct sockaddr_ns),
  753. ctx->dnsc_pbuf, qlen);
  754. q->dnsq_servwait |= 1 << servi; /* expect reply from this ns */
  755. q->dnsq_deadline = now +
  756. (dns_find_serv(ctx, q) ? 1 : ctx->dnsc_timeout << q->dnsq_try);
  757. /* move the query to the proper place, according to the new deadline */
  758. qlist_remove(&ctx->dnsc_qactive, q);
  759. { /* insert from the tail */
  760. struct dns_query *p;
  761. for(p = ctx->dnsc_qactive.tail; p; p = p->dnsq_prev)
  762. if (p->dnsq_deadline <= q->dnsq_deadline)
  763. break;
  764. qlist_insert_after(&ctx->dnsc_qactive, q, p);
  765. }
  766. return 0;
  767. }
  768. /* send the query out using next available server
  769. * and add it to the active list, or, if no servers available,
  770. * end it.
  771. */
  772. static void
  773. dns_send(struct dns_ctx *ctx, struct dns_query *q, time_t now) {
  774. /* if we can't send the query, return TEMPFAIL even when searching:
  775. * we can't be sure whenever the name we tried to search exists or not,
  776. * so don't continue searching, or we may find the wrong name. */
  777. if (!dns_find_serv(ctx, q)) {
  778. /* no more servers in this iteration. Try the next cycle */
  779. q->dnsq_servi = 0; /* reset */
  780. q->dnsq_try++; /* next try */
  781. if (q->dnsq_try >= ctx->dnsc_ntries ||
  782. !dns_find_serv(ctx, q)) {
  783. /* no more servers and tries, fail the query */
  784. /* return TEMPFAIL even when searching: no more tries for this
  785. * searchlist, and no single definitive reply (handled in dns_ioevent()
  786. * in NOERROR or NXDOMAIN cases) => all nameservers failed to process
  787. * current search list element, so we don't know whenever the name exists.
  788. */
  789. dns_end_query(ctx, q, DNS_E_TEMPFAIL, 0);
  790. return;
  791. }
  792. }
  793. dns_send_this(ctx, q, q->dnsq_servi++, now);
  794. }
  795. static void dns_dummy_cb(struct dns_ctx *ctx, void *result, void *data) {
  796. if (result) free(result);
  797. data = ctx = 0; /* used */
  798. }
  799. /* The (only, main, real) query submission routine.
  800. * Allocate new query structure, initialize it, check validity of
  801. * parameters, and add it to the head of the active list, without
  802. * trying to send it (to be picked up on next event).
  803. * Error return (without calling the callback routine) -
  804. * no memory or wrong parameters.
  805. *XXX The `no memory' case probably should go to the callback anyway...
  806. */
  807. struct dns_query *
  808. dns_submit_dn(struct dns_ctx *ctx,
  809. dnscc_t *dn, int qcls, int qtyp, int flags,
  810. dns_parse_fn *parse, dns_query_fn *cbck, void *data) {
  811. struct dns_query *q;
  812. SETCTXOPEN(ctx);
  813. dns_assert_ctx(ctx);
  814. q = calloc(sizeof(*q), 1);
  815. if (!q) {
  816. ctx->dnsc_qstatus = DNS_E_NOMEM;
  817. return NULL;
  818. }
  819. #ifndef NDEBUG
  820. q->dnsq_ctx = ctx;
  821. #endif
  822. q->dnsq_parse = parse;
  823. q->dnsq_cbck = cbck ? cbck : dns_dummy_cb;
  824. q->dnsq_cbdata = data;
  825. q->dnsq_origdnl0 = dns_dntodn(dn, q->dnsq_dn, sizeof(q->dnsq_dn));
  826. assert(q->dnsq_origdnl0 > 0);
  827. --q->dnsq_origdnl0; /* w/o the trailing 0 */
  828. dns_put16(q->dnsq_typcls+0, qtyp);
  829. dns_put16(q->dnsq_typcls+2, qcls);
  830. q->dnsq_flags = (flags | ctx->dnsc_flags) & ~DNS_INTERNAL;
  831. if (flags & DNS_NOSRCH ||
  832. dns_dnlabels(q->dnsq_dn) > ctx->dnsc_ndots) {
  833. q->dnsq_nxtsrch = flags & DNS_NOSRCH ?
  834. ctx->dnsc_srchend /* end of the search list if no search requested */ :
  835. ctx->dnsc_srchbuf /* beginning of the list, but try as-is first */;
  836. q->dnsq_flags |= DNS_ASIS_DONE;
  837. dns_newid(ctx, q);
  838. }
  839. else {
  840. q->dnsq_nxtsrch = ctx->dnsc_srchbuf;
  841. dns_next_srch(ctx, q);
  842. }
  843. /* q->dnsq_deadline is set to 0 (calloc above): the new query is
  844. * "already expired" when first inserted into queue, so it's safe
  845. * to insert it into the head of the list. Next call to dns_timeouts()
  846. * will actually send it.
  847. */
  848. qlist_add_head(&ctx->dnsc_qactive, q);
  849. ++ctx->dnsc_nactive;
  850. dns_request_utm(ctx, 0);
  851. return q;
  852. }
  853. struct dns_query *
  854. dns_submit_p(struct dns_ctx *ctx,
  855. const char *name, int qcls, int qtyp, int flags,
  856. dns_parse_fn *parse, dns_query_fn *cbck, void *data) {
  857. int isabs;
  858. SETCTXOPEN(ctx);
  859. if (dns_ptodn(name, 0, ctx->dnsc_pbuf, DNS_MAXDN, &isabs) <= 0) {
  860. ctx->dnsc_qstatus = DNS_E_BADQUERY;
  861. return NULL;
  862. }
  863. if (isabs)
  864. flags |= DNS_NOSRCH;
  865. return
  866. dns_submit_dn(ctx, ctx->dnsc_pbuf, qcls, qtyp, flags, parse, cbck, data);
  867. }
  868. /* process readable fd condition.
  869. * To be usable in edge-triggered environment, the routine
  870. * should consume all input so it should loop over.
  871. * Note it isn't really necessary to loop here, because
  872. * an application may perform the loop just fine by it's own,
  873. * but in this case we should return some sensitive result,
  874. * to indicate when to stop calling and error conditions.
  875. * Note also we may encounter all sorts of recvfrom()
  876. * errors which aren't fatal, and at the same time we may
  877. * loop forever if an error IS fatal.
  878. */
  879. void dns_ioevent(struct dns_ctx *ctx, time_t now) {
  880. int r;
  881. unsigned servi;
  882. struct dns_query *q;
  883. dnsc_t *pbuf;
  884. dnscc_t *pend, *pcur;
  885. void *result;
  886. struct sockaddr_ns sns;
  887. socklen_t slen;
  888. SETCTX(ctx);
  889. if (!CTXOPEN(ctx))
  890. return;
  891. dns_assert_ctx(ctx);
  892. pbuf = ctx->dnsc_pbuf;
  893. if (!now) now = time(NULL);
  894. again: /* receive the reply */
  895. slen = sizeof(sns);
  896. r = recvfrom(ctx->dnsc_udpsock, (void*)pbuf, ctx->dnsc_udpbuf,
  897. MSG_DONTWAIT, &sns.sa, &slen);
  898. if (r < 0) {
  899. /*XXX just ignore recvfrom() errors for now.
  900. * in the future it may be possible to determine which
  901. * query failed and requeue it.
  902. * Note there may be various error conditions, triggered
  903. * by both local problems and remote problems. It isn't
  904. * quite trivial to determine whenever an error is local
  905. * or remote. On local errors, we should stop, while
  906. * remote errors should be ignored (for now anyway).
  907. */
  908. #ifdef __MINGW32__
  909. if (WSAGetLastError() == WSAEWOULDBLOCK)
  910. #else
  911. if (errno == EAGAIN)
  912. #endif
  913. {
  914. dns_request_utm(ctx, now);
  915. return;
  916. }
  917. goto again;
  918. }
  919. pend = pbuf + r;
  920. pcur = dns_payload(pbuf);
  921. /* check reply header */
  922. if (pcur > pend || dns_numqd(pbuf) > 1 || dns_opcode(pbuf) != 0) {
  923. DNS_DBG(ctx, -1/*bad reply*/, &sns.sa, slen, pbuf, r);
  924. goto again;
  925. }
  926. /* find the matching query, by qID */
  927. for (q = ctx->dnsc_qactive.head; ; q = q->dnsq_next) {
  928. if (!q) {
  929. /* no more requests: old reply? */
  930. DNS_DBG(ctx, -5/*no matching query*/, &sns.sa, slen, pbuf, r);
  931. goto again;
  932. }
  933. if (pbuf[DNS_H_QID1] == q->dnsq_id[0] &&
  934. pbuf[DNS_H_QID2] == q->dnsq_id[1])
  935. break;
  936. }
  937. /* if we have numqd, compare with our query qDN */
  938. if (dns_numqd(pbuf)) {
  939. /* decode the qDN */
  940. dnsc_t dn[DNS_MAXDN];
  941. if (dns_getdn(pbuf, &pcur, pend, dn, sizeof(dn)) < 0 ||
  942. pcur + 4 > pend) {
  943. DNS_DBG(ctx, -1/*bad reply*/, &sns.sa, slen, pbuf, r);
  944. goto again;
  945. }
  946. if (!dns_dnequal(dn, q->dnsq_dn) ||
  947. memcmp(pcur, q->dnsq_typcls, 4) != 0) {
  948. /* not this query */
  949. DNS_DBG(ctx, -5/*no matching query*/, &sns.sa, slen, pbuf, r);
  950. goto again;
  951. }
  952. /* here, query match, and pcur points past qDN in query section in pbuf */
  953. }
  954. /* if no numqd, we only allow FORMERR rcode */
  955. else if (dns_rcode(pbuf) != DNS_R_FORMERR) {
  956. /* treat it as bad reply if !FORMERR */
  957. DNS_DBG(ctx, -1/*bad reply*/, &sns.sa, slen, pbuf, r);
  958. goto again;
  959. }
  960. else {
  961. /* else it's FORMERR, handled below */
  962. }
  963. /* find server */
  964. #ifdef HAVE_IPv6
  965. if (sns.sa.sa_family == AF_INET6 && slen >= sizeof(sns.sin6)) {
  966. for(servi = 0; servi < ctx->dnsc_nserv; ++servi)
  967. if (sin6_eq(ctx->dnsc_serv[servi].sin6, sns.sin6))
  968. break;
  969. }
  970. else
  971. #endif
  972. if (sns.sa.sa_family == AF_INET && slen >= sizeof(sns.sin)) {
  973. for(servi = 0; servi < ctx->dnsc_nserv; ++servi)
  974. if (sin_eq(ctx->dnsc_serv[servi].sin, sns.sin))
  975. break;
  976. }
  977. else
  978. servi = ctx->dnsc_nserv;
  979. /* check if we expect reply from this server.
  980. * Note we can receive reply from first try if we're already at next */
  981. if (!(q->dnsq_servwait & (1 << servi))) { /* if ever asked this NS */
  982. DNS_DBG(ctx, -2/*wrong server*/, &sns.sa, slen, pbuf, r);
  983. goto again;
  984. }
  985. /* we got (some) reply for our query */
  986. DNS_DBGQ(ctx, q, 0, &sns.sa, slen, pbuf, r);
  987. q->dnsq_servwait &= ~(1 << servi); /* don't expect reply from this serv */
  988. /* process the RCODE */
  989. switch(dns_rcode(pbuf)) {
  990. case DNS_R_NOERROR:
  991. if (dns_tc(pbuf)) {
  992. /* possible truncation. We can't deal with it. */
  993. /*XXX for now, treat TC bit the same as SERVFAIL.
  994. * It is possible to:
  995. * a) try to decode the reply - may be ANSWER section is ok;
  996. * b) check if server understands EDNS0, and if it is, and
  997. * answer still don't fit, end query.
  998. */
  999. break;
  1000. }
  1001. if (!dns_numan(pbuf)) { /* no data of requested type */
  1002. if (dns_next_srch(ctx, q)) {
  1003. /* if we're searching, try next searchlist element,
  1004. * but remember NODATA reply. */
  1005. q->dnsq_flags |= DNS_SEEN_NODATA;
  1006. dns_send(ctx, q, now);
  1007. }
  1008. else
  1009. /* else - nothing to search any more - finish the query.
  1010. * It will be NODATA since we've seen a NODATA reply. */
  1011. dns_end_query(ctx, q, DNS_E_NODATA, 0);
  1012. }
  1013. /* we've got a positive reply here */
  1014. else if (q->dnsq_parse) {
  1015. /* if we have parsing routine, call it and return whatever it returned */
  1016. /* don't try to re-search if NODATA here. For example,
  1017. * if we asked for A but only received CNAME. Unless we'll
  1018. * someday do recursive queries. And that's problematic too, since
  1019. * we may be dealing with specific AA-only nameservers for a given
  1020. * domain, but CNAME points elsewhere...
  1021. */
  1022. r = q->dnsq_parse(q->dnsq_dn, pbuf, pcur, pend, &result);
  1023. dns_end_query(ctx, q, r, r < 0 ? NULL : result);
  1024. }
  1025. /* else just malloc+copy the raw DNS reply */
  1026. else if ((result = malloc(r)) == NULL)
  1027. dns_end_query(ctx, q, DNS_E_NOMEM, NULL);
  1028. else {
  1029. memcpy(result, pbuf, r);
  1030. dns_end_query(ctx, q, r, result);
  1031. }
  1032. goto again;
  1033. case DNS_R_NXDOMAIN: /* Non-existing domain. */
  1034. if (dns_next_srch(ctx, q))
  1035. /* more search entries exists, try them. */
  1036. dns_send(ctx, q, now);
  1037. else
  1038. /* nothing to search anymore. End the query, returning either NODATA
  1039. * if we've seen it before, or NXDOMAIN if not. */
  1040. dns_end_query(ctx, q,
  1041. q->dnsq_flags & DNS_SEEN_NODATA ? DNS_E_NODATA : DNS_E_NXDOMAIN, 0);
  1042. goto again;
  1043. case DNS_R_FORMERR:
  1044. case DNS_R_NOTIMPL:
  1045. /* for FORMERR and NOTIMPL rcodes, if we tried EDNS0-enabled query,
  1046. * try w/o EDNS0. */
  1047. if (ctx->dnsc_udpbuf > DNS_MAXPACKET &&
  1048. !(q->dnsq_servnEDNS0 & (1 << servi))) {
  1049. /* we always trying EDNS0 first if enabled, and retry a given query
  1050. * if not available. Maybe it's better to remember inavailability of
  1051. * EDNS0 in ctx as a per-NS flag, and never try again for this NS.
  1052. * For long-running applications.. maybe they will change the nameserver
  1053. * while we're running? :) Also, since FORMERR is the only rcode we
  1054. * allow to be header-only, and in this case the only check we do to
  1055. * find a query it belongs to is qID (not qDN+qCLS+qTYP), it's much
  1056. * easier to spoof and to force us to perform non-EDNS0 queries only...
  1057. */
  1058. q->dnsq_servnEDNS0 |= 1 << servi;
  1059. dns_send_this(ctx, q, servi, now);
  1060. goto again;
  1061. }
  1062. /* else we handle it the same as SERVFAIL etc */
  1063. case DNS_R_SERVFAIL:
  1064. case DNS_R_REFUSED:
  1065. /* for these rcodes, advance this request
  1066. * to the next server and reschedule */
  1067. default: /* unknown rcode? hmmm... */
  1068. break;
  1069. }
  1070. /* here, we received unexpected reply */
  1071. q->dnsq_servskip |= (1 << servi); /* don't retry this server */
  1072. /* we don't expect replies from this server anymore.
  1073. * But there may be other servers. Some may be still processing our
  1074. * query, and some may be left to try.
  1075. * We just ignore this reply and wait a bit more if some NSes haven't
  1076. * replied yet (dnsq_servwait != 0), and let the situation to be handled
  1077. * on next event processing. Timeout for this query is set correctly,
  1078. * if not taking into account the one-second difference - we can try
  1079. * next server in the same iteration sooner.
  1080. */
  1081. /* try next server */
  1082. if (!q->dnsq_servwait) {
  1083. /* next retry: maybe some other servers will reply next time.
  1084. * dns_send() will end the query for us if no more servers to try.
  1085. * Note we can't continue with the next searchlist element here:
  1086. * we don't know if the current qdn exists or not, there's no definitive
  1087. * answer yet (which is seen in cases above).
  1088. *XXX standard resolver also tries as-is query in case all nameservers
  1089. * failed to process our query and if not tried before. We don't do it.
  1090. */
  1091. dns_send(ctx, q, now);
  1092. }
  1093. else {
  1094. /* else don't do anything - not all servers replied yet */
  1095. }
  1096. goto again;
  1097. }
  1098. /* handle all timeouts */
  1099. int dns_timeouts(struct dns_ctx *ctx, int maxwait, time_t now) {
  1100. /* this is a hot routine */
  1101. struct dns_query *q;
  1102. SETCTX(ctx);
  1103. dns_assert_ctx(ctx);
  1104. /* Pick up first entry from query list.
  1105. * If its deadline has passed, (re)send it
  1106. * (dns_send() will move it next in the list).
  1107. * If not, this is the query which determines the closest deadline.
  1108. */
  1109. q = ctx->dnsc_qactive.head;
  1110. if (!q)
  1111. return maxwait;
  1112. if (!now)
  1113. now = time(NULL);
  1114. do {
  1115. if (q->dnsq_deadline > now) { /* first non-expired query */
  1116. int w = (int)(q->dnsq_deadline - now);
  1117. if (maxwait < 0 || maxwait > w)
  1118. maxwait = w;
  1119. break;
  1120. }
  1121. else {
  1122. /* process expired deadline */
  1123. dns_send(ctx, q, now);
  1124. }
  1125. } while((q = ctx->dnsc_qactive.head) != NULL);
  1126. dns_request_utm(ctx, now); /* update timer with new deadline */
  1127. return maxwait;
  1128. }
  1129. struct dns_resolve_data {
  1130. int dnsrd_done;
  1131. void *dnsrd_result;
  1132. };
  1133. static void dns_resolve_cb(struct dns_ctx *ctx, void *result, void *data) {
  1134. struct dns_resolve_data *d = data;
  1135. d->dnsrd_result = result;
  1136. d->dnsrd_done = 1;
  1137. ctx = ctx;
  1138. }
  1139. void *dns_resolve(struct dns_ctx *ctx, struct dns_query *q) {
  1140. time_t now;
  1141. struct dns_resolve_data d;
  1142. int n;
  1143. SETCTXOPEN(ctx);
  1144. if (!q)
  1145. return NULL;
  1146. assert(ctx == q->dnsq_ctx);
  1147. dns_assert_ctx(ctx);
  1148. /* do not allow re-resolving syncronous queries */
  1149. assert(q->dnsq_cbck != dns_resolve_cb && "can't resolve syncronous query");
  1150. if (q->dnsq_cbck == dns_resolve_cb) {
  1151. ctx->dnsc_qstatus = DNS_E_BADQUERY;
  1152. return NULL;
  1153. }
  1154. q->dnsq_cbck = dns_resolve_cb;
  1155. q->dnsq_cbdata = &d;
  1156. d.dnsrd_done = 0;
  1157. now = time(NULL);
  1158. while(!d.dnsrd_done && (n = dns_timeouts(ctx, -1, now)) >= 0) {
  1159. #ifdef HAVE_POLL
  1160. struct pollfd pfd;
  1161. pfd.fd = ctx->dnsc_udpsock;
  1162. pfd.events = POLLIN;
  1163. n = poll(&pfd, 1, n * 1000);
  1164. #else
  1165. fd_set rfd;
  1166. struct timeval tv;
  1167. FD_ZERO(&rfd);
  1168. FD_SET(ctx->dnsc_udpsock, &rfd);
  1169. tv.tv_sec = n; tv.tv_usec = 0;
  1170. n = select(ctx->dnsc_udpsock + 1, &rfd, NULL, NULL, &tv);
  1171. #endif
  1172. now = time(NULL);
  1173. if (n > 0)
  1174. dns_ioevent(ctx, now);
  1175. }
  1176. return d.dnsrd_result;
  1177. }
  1178. void *dns_resolve_dn(struct dns_ctx *ctx,
  1179. dnscc_t *dn, int qcls, int qtyp, int flags,
  1180. dns_parse_fn *parse) {
  1181. return
  1182. dns_resolve(ctx,
  1183. dns_submit_dn(ctx, dn, qcls, qtyp, flags, parse, NULL, NULL));
  1184. }
  1185. void *dns_resolve_p(struct dns_ctx *ctx,
  1186. const char *name, int qcls, int qtyp, int flags,
  1187. dns_parse_fn *parse) {
  1188. return
  1189. dns_resolve(ctx,
  1190. dns_submit_p(ctx, name, qcls, qtyp, flags, parse, NULL, NULL));
  1191. }
  1192. int dns_cancel(struct dns_ctx *ctx, struct dns_query *q) {
  1193. SETCTX(ctx);
  1194. dns_assert_ctx(ctx);
  1195. assert(q->dnsq_ctx == ctx);
  1196. /* do not allow cancelling syncronous queries */
  1197. assert(q->dnsq_cbck != dns_resolve_cb && "can't cancel syncronous query");
  1198. if (q->dnsq_cbck == dns_resolve_cb)
  1199. return (ctx->dnsc_qstatus = DNS_E_BADQUERY);
  1200. qlist_remove(&ctx->dnsc_qactive, q);
  1201. --ctx->dnsc_nactive;
  1202. dns_request_utm(ctx, 0);
  1203. return 0;
  1204. }