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.

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