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.

resolver.c 37KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  1. /*
  2. * Copyright (c) 2014, Vsevolod Stakhov
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY AUTHOR ''AS IS'' AND ANY
  15. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
  18. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  21. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #include <sys/socket.h>
  26. #include <netinet/in.h>
  27. #include <arpa/inet.h>
  28. #include <unistd.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <errno.h>
  32. #include <stdarg.h>
  33. #include <sys/uio.h>
  34. #include "rdns.h"
  35. #include "dns_private.h"
  36. #include "ottery.h"
  37. #include "util.h"
  38. #include "packet.h"
  39. #include "parse.h"
  40. #include "logger.h"
  41. #include "compression.h"
  42. __KHASH_IMPL(rdns_requests_hash, kh_inline, int, struct rdns_request *, true,
  43. kh_int_hash_func, kh_int_hash_equal);
  44. static int
  45. rdns_send_request (struct rdns_request *req, int fd, bool new_req)
  46. {
  47. ssize_t r;
  48. struct rdns_server *serv = req->io->srv;
  49. struct rdns_resolver *resolver = req->resolver;
  50. struct dns_header *header;
  51. const int max_id_cycles = 32;
  52. khiter_t k;
  53. /* Find ID collision */
  54. if (new_req) {
  55. r = 0;
  56. for (;;) {
  57. k = kh_get(rdns_requests_hash, req->io->requests, req->id);
  58. if (k != kh_end(req->io->requests)) {
  59. /* Check for unique id */
  60. header = (struct dns_header *) req->packet;
  61. header->qid = rdns_permutor_generate_id();
  62. req->id = header->qid;
  63. if (++r > max_id_cycles) {
  64. return -1;
  65. }
  66. }
  67. else {
  68. break;
  69. }
  70. }
  71. }
  72. if (resolver->curve_plugin == NULL) {
  73. if (!IS_CHANNEL_CONNECTED(req->io)) {
  74. r = sendto (fd, req->packet, req->pos, 0,
  75. req->io->saddr,
  76. req->io->slen);
  77. }
  78. else {
  79. r = send (fd, req->packet, req->pos, 0);
  80. }
  81. }
  82. else {
  83. if (!IS_CHANNEL_CONNECTED(req->io)) {
  84. r = resolver->curve_plugin->cb.curve_plugin.send_cb (req,
  85. resolver->curve_plugin->data,
  86. req->io->saddr,
  87. req->io->slen);
  88. }
  89. else {
  90. r = resolver->curve_plugin->cb.curve_plugin.send_cb (req,
  91. resolver->curve_plugin->data,
  92. NULL,
  93. 0);
  94. }
  95. }
  96. if (r == -1) {
  97. if (errno == EAGAIN || errno == EINTR) {
  98. if (new_req) {
  99. /* Write when socket is ready */
  100. int pr;
  101. k = kh_put(rdns_requests_hash, req->io->requests, req->id, &pr);
  102. kh_value(req->io->requests, k) = req;
  103. req->async_event = resolver->async->add_write (resolver->async->data,
  104. fd, req);
  105. req->state = RDNS_REQUEST_WAIT_SEND;
  106. }
  107. /*
  108. * If request is already processed then the calling function
  109. * should take care about events processing
  110. */
  111. return 0;
  112. }
  113. else {
  114. rdns_debug ("send failed: %s for server %s", strerror (errno), serv->name);
  115. return -1;
  116. }
  117. }
  118. else if (!IS_CHANNEL_CONNECTED(req->io)) {
  119. /* Connect socket */
  120. r = connect (fd, req->io->saddr, req->io->slen);
  121. if (r == -1) {
  122. rdns_err ("cannot connect after sending request: %s for server %s",
  123. strerror (errno), serv->name);
  124. }
  125. else {
  126. req->io->flags |= RDNS_CHANNEL_CONNECTED;
  127. }
  128. }
  129. if (new_req) {
  130. /* Add request to hash table */
  131. int pr;
  132. k = kh_put(rdns_requests_hash, req->io->requests, req->id, &pr);
  133. kh_value(req->io->requests, k) = req;
  134. /* Fill timeout */
  135. req->async_event = resolver->async->add_timer (resolver->async->data,
  136. req->timeout, req);
  137. req->state = RDNS_REQUEST_WAIT_REPLY;
  138. }
  139. return 1;
  140. }
  141. static struct rdns_request *
  142. rdns_find_dns_request (uint8_t *in, struct rdns_io_channel *ioc)
  143. {
  144. struct dns_header header;
  145. int id;
  146. struct rdns_resolver *resolver = ioc->resolver;
  147. memcpy (&header, in, sizeof(header));
  148. id = header.qid;
  149. khiter_t k = kh_get(rdns_requests_hash, ioc->requests, id);
  150. if (k == kh_end(ioc->requests)) {
  151. /* No such requests found */
  152. rdns_debug ("DNS request with id %d has not been found for IO channel", id);
  153. return NULL;
  154. }
  155. return kh_value(ioc->requests, k);
  156. }
  157. static bool
  158. rdns_parse_reply (uint8_t *in, int r, struct rdns_request *req,
  159. struct rdns_reply **_rep)
  160. {
  161. struct dns_header *header = (struct dns_header *)in;
  162. struct rdns_reply *rep;
  163. struct rdns_reply_entry *elt;
  164. uint8_t *pos, *npos;
  165. struct rdns_resolver *resolver = req->resolver;
  166. uint16_t qdcount;
  167. int type;
  168. bool found = false;
  169. int i, t;
  170. /* First check header fields */
  171. if (header->qr == 0) {
  172. rdns_info ("got request while waiting for reply");
  173. return false;
  174. }
  175. qdcount = ntohs (header->qdcount);
  176. if (qdcount != req->qcount) {
  177. rdns_info ("request has %d queries, reply has %d queries", (int)req->qcount, (int)header->qdcount);
  178. return false;
  179. }
  180. /*
  181. * Now we have request and query data is now at the end of header, so compare
  182. * request QR section and reply QR section
  183. */
  184. req->pos = sizeof (struct dns_header);
  185. pos = in + sizeof (struct dns_header);
  186. t = r - sizeof (struct dns_header);
  187. for (i = 0; i < (int)qdcount; i ++) {
  188. if ((npos = rdns_request_reply_cmp (req, pos,t)) == NULL) {
  189. rdns_info ("DNS request with id %d is for different query, ignoring", (int)req->id);
  190. return false;
  191. }
  192. t -= npos - pos;
  193. pos = npos;
  194. }
  195. /*
  196. * Now pos is in answer section, so we should extract data and form reply
  197. */
  198. rep = rdns_make_reply (req, header->rcode);
  199. if (header->ad) {
  200. rep->flags |= RDNS_AUTH;
  201. }
  202. if (header->tc) {
  203. rep->flags |= RDNS_TRUNCATED;
  204. }
  205. if (rep == NULL) {
  206. rdns_warn ("Cannot allocate memory for reply");
  207. return false;
  208. }
  209. type = req->requested_names[0].type;
  210. if (rep->code == RDNS_RC_NOERROR) {
  211. r -= pos - in;
  212. /* Extract RR records */
  213. for (i = 0; i < ntohs (header->ancount); i ++) {
  214. elt = malloc (sizeof (struct rdns_reply_entry));
  215. t = rdns_parse_rr (resolver, in, elt, &pos, rep, &r);
  216. if (t == -1) {
  217. free (elt);
  218. rdns_debug ("incomplete reply");
  219. break;
  220. }
  221. else if (t == 1) {
  222. DL_APPEND (rep->entries, elt);
  223. if (elt->type == type) {
  224. found = true;
  225. }
  226. }
  227. else {
  228. rdns_debug ("no matching reply for %s",
  229. req->requested_names[0].name);
  230. free (elt);
  231. }
  232. }
  233. }
  234. if (!found && type != RDNS_REQUEST_ANY) {
  235. /* We have not found the requested RR type */
  236. if (rep->code == RDNS_RC_NOERROR) {
  237. rep->code = RDNS_RC_NOREC;
  238. }
  239. }
  240. *_rep = rep;
  241. return true;
  242. }
  243. static bool
  244. rdns_tcp_maybe_realloc_read_buf (struct rdns_io_channel *ioc)
  245. {
  246. if (ioc->tcp->read_buf_allocated == 0 && ioc->tcp->next_read_size > 0) {
  247. ioc->tcp->cur_read_buf = malloc(ioc->tcp->next_read_size);
  248. if (ioc->tcp->cur_read_buf == NULL) {
  249. return false;
  250. }
  251. ioc->tcp->read_buf_allocated = ioc->tcp->next_read_size;
  252. }
  253. else if (ioc->tcp->read_buf_allocated < ioc->tcp->next_read_size) {
  254. /* Need to realloc */
  255. unsigned next_shift = ioc->tcp->next_read_size;
  256. if (next_shift < ioc->tcp->read_buf_allocated * 2) {
  257. if (next_shift < UINT16_MAX && ioc->tcp->read_buf_allocated * 2 <= UINT16_MAX) {
  258. next_shift = ioc->tcp->read_buf_allocated * 2;
  259. }
  260. }
  261. void *next_buf = realloc(ioc->tcp->cur_read_buf, next_shift);
  262. if (next_buf == NULL) {
  263. free (ioc->tcp->cur_read_buf);
  264. ioc->tcp->cur_read_buf = NULL;
  265. return false;
  266. }
  267. ioc->tcp->cur_read_buf = next_buf;
  268. }
  269. return true;
  270. }
  271. static void
  272. rdns_process_tcp_read (int fd, struct rdns_io_channel *ioc)
  273. {
  274. ssize_t r;
  275. struct rdns_resolver *resolver = ioc->resolver;
  276. if (ioc->tcp->cur_read == 0) {
  277. /* We have to read size first */
  278. r = read(fd, &ioc->tcp->next_read_size, sizeof(ioc->tcp->next_read_size));
  279. if (r == -1 || r == 0) {
  280. goto err;
  281. }
  282. ioc->tcp->cur_read += r;
  283. if (r == sizeof(ioc->tcp->next_read_size)) {
  284. ioc->tcp->next_read_size = ntohs(ioc->tcp->next_read_size);
  285. /* We have read the size, so we can try read one more time */
  286. if (!rdns_tcp_maybe_realloc_read_buf(ioc)) {
  287. rdns_err("failed to allocate %d bytes: %s",
  288. (int)ioc->tcp->next_read_size, strerror(errno));
  289. r = -1;
  290. goto err;
  291. }
  292. }
  293. else {
  294. /* We have read one byte, need to retry... */
  295. return;
  296. }
  297. }
  298. else if (ioc->tcp->cur_read == 1) {
  299. r = read(fd, ((unsigned char *)&ioc->tcp->next_read_size) + 1, 1);
  300. if (r == -1 || r == 0) {
  301. goto err;
  302. }
  303. ioc->tcp->cur_read += r;
  304. ioc->tcp->next_read_size = ntohs(ioc->tcp->next_read_size);
  305. /* We have read the size, so we can try read one more time */
  306. if (!rdns_tcp_maybe_realloc_read_buf(ioc)) {
  307. rdns_err("failed to allocate %d bytes: %s",
  308. (int)ioc->tcp->next_read_size, strerror(errno));
  309. r = -1;
  310. goto err;
  311. }
  312. }
  313. if (ioc->tcp->next_read_size < sizeof(struct dns_header)) {
  314. /* Truncated reply, reset channel */
  315. rdns_err("got truncated size: %d on TCP read", ioc->tcp->next_read_size);
  316. r = -1;
  317. errno = EINVAL;
  318. goto err;
  319. }
  320. /* Try to read the full packet if we can */
  321. int to_read = ioc->tcp->next_read_size - (ioc->tcp->cur_read - 2);
  322. if (to_read <= 0) {
  323. /* Internal error */
  324. rdns_err("internal buffer error on reading!");
  325. r = -1;
  326. errno = EINVAL;
  327. goto err;
  328. }
  329. r = read(fd, ioc->tcp->cur_read_buf + (ioc->tcp->cur_read - 2), to_read);
  330. ioc->tcp->cur_read += r;
  331. if ((ioc->tcp->cur_read - 2) == ioc->tcp->next_read_size) {
  332. /* We have a full packet ready, process it */
  333. struct rdns_request *req = rdns_find_dns_request (ioc->tcp->cur_read_buf, ioc);
  334. if (req != NULL) {
  335. struct rdns_reply *rep;
  336. if (rdns_parse_reply (ioc->tcp->cur_read_buf,
  337. ioc->tcp->next_read_size, req, &rep)) {
  338. UPSTREAM_OK (req->io->srv);
  339. if (req->resolver->ups && req->io->srv->ups_elt) {
  340. req->resolver->ups->ok (req->io->srv->ups_elt,
  341. req->resolver->ups->data);
  342. }
  343. req->func (rep, req->arg);
  344. REF_RELEASE (req);
  345. }
  346. }
  347. else {
  348. rdns_warn("unwanted DNS id received over TCP");
  349. }
  350. ioc->tcp->next_read_size = 0;
  351. ioc->tcp->cur_read = 0;
  352. /* Retry read the next packet to avoid unnecessary polling */
  353. rdns_process_tcp_read (fd, ioc);
  354. }
  355. return;
  356. err:
  357. if (r == 0) {
  358. /* Got EOF, just close the socket */
  359. rdns_debug ("closing TCP channel due to EOF");
  360. rdns_ioc_tcp_reset (ioc);
  361. }
  362. else if (errno == EINTR || errno == EAGAIN) {
  363. /* We just retry later as there is no real error */
  364. return;
  365. }
  366. else {
  367. rdns_debug ("closing TCP channel due to IO error: %s", strerror(errno));
  368. rdns_ioc_tcp_reset (ioc);
  369. }
  370. }
  371. static void
  372. rdns_process_tcp_connect (int fd, struct rdns_io_channel *ioc)
  373. {
  374. ioc->flags |= RDNS_CHANNEL_CONNECTED|RDNS_CHANNEL_ACTIVE;
  375. ioc->flags &= ~RDNS_CHANNEL_TCP_CONNECTING;
  376. if (ioc->tcp->async_read == NULL) {
  377. ioc->tcp->async_read = ioc->resolver->async->add_read(ioc->resolver->async->data,
  378. ioc->sock, ioc);
  379. }
  380. }
  381. static bool
  382. rdns_reschedule_req_over_tcp (struct rdns_request *req, struct rdns_server *serv)
  383. {
  384. struct rdns_resolver *resolver;
  385. struct rdns_io_channel *old_ioc = req->io,
  386. *ioc = serv->tcp_io_channels[ottery_rand_uint32 () % serv->tcp_io_cnt];
  387. resolver = req->resolver;
  388. if (ioc != NULL) {
  389. if (!IS_CHANNEL_CONNECTED(ioc)) {
  390. if (!rdns_ioc_tcp_connect(ioc)) {
  391. return false;
  392. }
  393. }
  394. struct rdns_tcp_output_chain *oc;
  395. oc = calloc(1, sizeof(*oc) + req->packet_len);
  396. if (oc == NULL) {
  397. rdns_err("failed to allocate output buffer for TCP ioc: %s",
  398. strerror(errno));
  399. return false;
  400. }
  401. oc->write_buf = ((unsigned char *)oc) + sizeof(*oc);
  402. memcpy(oc->write_buf, req->packet, req->packet_len);
  403. oc->next_write_size = htons(req->packet_len);
  404. DL_APPEND(ioc->tcp->output_chain, oc);
  405. if (ioc->tcp->async_write == NULL) {
  406. ioc->tcp->async_write = resolver->async->add_write (
  407. resolver->async->data,
  408. ioc->sock, ioc);
  409. }
  410. req->state = RDNS_REQUEST_TCP;
  411. /* Switch IO channel from UDP to TCP */
  412. rdns_request_remove_from_hash (req);
  413. req->io = ioc;
  414. khiter_t k;
  415. for (;;) {
  416. int pr;
  417. k = kh_put(rdns_requests_hash, ioc->requests, req->id, &pr);
  418. if (pr == 0) {
  419. /* We have already a request with this id, so we have to regenerate ID */
  420. req->id = rdns_permutor_generate_id ();
  421. /* Update packet as well */
  422. uint16_t raw_id = req->id;
  423. memcpy(req->packet, &raw_id, sizeof(raw_id));
  424. }
  425. else {
  426. break;
  427. }
  428. }
  429. req->async_event = resolver->async->add_timer (resolver->async->data,
  430. req->timeout, req);
  431. kh_value(req->io->requests, k) = req;
  432. REF_RELEASE(old_ioc);
  433. REF_RETAIN(ioc);
  434. return true;
  435. }
  436. return false;
  437. }
  438. static void
  439. rdns_process_udp_read (int fd, struct rdns_io_channel *ioc)
  440. {
  441. struct rdns_resolver *resolver;
  442. struct rdns_request *req = NULL;
  443. ssize_t r;
  444. struct rdns_reply *rep;
  445. uint8_t in[UDP_PACKET_SIZE];
  446. resolver = ioc->resolver;
  447. /* First read packet from socket */
  448. if (resolver->curve_plugin == NULL) {
  449. r = recv (fd, in, sizeof (in), 0);
  450. if (r > (int)(sizeof (struct dns_header) + sizeof (struct dns_query))) {
  451. req = rdns_find_dns_request (in, ioc);
  452. }
  453. }
  454. else {
  455. r = resolver->curve_plugin->cb.curve_plugin.recv_cb (ioc, in,
  456. sizeof (in), resolver->curve_plugin->data, &req,
  457. ioc->saddr, ioc->slen);
  458. if (req == NULL &&
  459. r > (int)(sizeof (struct dns_header) + sizeof (struct dns_query))) {
  460. req = rdns_find_dns_request (in, ioc);
  461. }
  462. }
  463. if (req != NULL) {
  464. if (rdns_parse_reply (in, r, req, &rep)) {
  465. UPSTREAM_OK (req->io->srv);
  466. if (req->resolver->ups && req->io->srv->ups_elt) {
  467. req->resolver->ups->ok (req->io->srv->ups_elt,
  468. req->resolver->ups->data);
  469. }
  470. rdns_request_unschedule (req);
  471. if (!(rep->flags & RDNS_TRUNCATED)) {
  472. req->state = RDNS_REQUEST_REPLIED;
  473. req->func(rep, req->arg);
  474. REF_RELEASE (req);
  475. }
  476. else {
  477. rdns_debug("truncated UDP reply for %s", req->requested_names[0].name);
  478. if (req->io->srv->tcp_io_cnt > 0) {
  479. /* Reschedule via TCP */
  480. if (!rdns_reschedule_req_over_tcp (req, req->io->srv)) {
  481. /* Use truncated reply as we have no other options */
  482. req->state = RDNS_REQUEST_REPLIED;
  483. req->func(rep, req->arg);
  484. REF_RELEASE (req);
  485. }
  486. }
  487. }
  488. }
  489. }
  490. else {
  491. /* Still want to increase uses */
  492. ioc->uses ++;
  493. }
  494. }
  495. void
  496. rdns_process_read (int fd, void *arg)
  497. {
  498. struct rdns_io_channel *ioc = (struct rdns_io_channel *)arg;
  499. struct rdns_resolver *resolver;
  500. resolver = ioc->resolver;
  501. if (IS_CHANNEL_TCP(ioc)) {
  502. if (IS_CHANNEL_CONNECTED(ioc)) {
  503. rdns_process_tcp_read (fd, ioc);
  504. }
  505. else {
  506. rdns_err ("read readiness on non connected TCP channel!");
  507. }
  508. }
  509. else {
  510. rdns_process_udp_read (fd, ioc);
  511. }
  512. }
  513. void
  514. rdns_process_timer (void *arg)
  515. {
  516. struct rdns_request *req = (struct rdns_request *)arg;
  517. struct rdns_reply *rep;
  518. int r;
  519. bool renew = false;
  520. struct rdns_resolver *resolver;
  521. struct rdns_server *serv = NULL;
  522. unsigned cnt;
  523. req->retransmits --;
  524. resolver = req->resolver;
  525. if (req->resolver->ups && req->io->srv->ups_elt) {
  526. req->resolver->ups->fail (req->io->srv->ups_elt,
  527. req->resolver->ups->data, "timeout waiting reply");
  528. }
  529. else {
  530. UPSTREAM_FAIL (req->io->srv, time (NULL));
  531. }
  532. if (req->state == RDNS_REQUEST_TCP) {
  533. rep = rdns_make_reply (req, RDNS_RC_TIMEOUT);
  534. rdns_request_unschedule (req);
  535. req->state = RDNS_REQUEST_REPLIED;
  536. req->func (rep, req->arg);
  537. REF_RELEASE (req);
  538. return;
  539. }
  540. if (req->retransmits == 0) {
  541. rep = rdns_make_reply (req, RDNS_RC_TIMEOUT);
  542. rdns_request_unschedule (req);
  543. req->state = RDNS_REQUEST_REPLIED;
  544. req->func (rep, req->arg);
  545. REF_RELEASE (req);
  546. return;
  547. }
  548. if (!IS_CHANNEL_ACTIVE(req->io) || req->retransmits == 1) {
  549. if (resolver->ups) {
  550. cnt = resolver->ups->count (resolver->ups->data);
  551. }
  552. else {
  553. cnt = 0;
  554. UPSTREAM_FOREACH (resolver->servers, serv) {
  555. cnt ++;
  556. }
  557. }
  558. if (!IS_CHANNEL_ACTIVE(req->io) || cnt > 1) {
  559. /* Do not reschedule IO requests on inactive sockets */
  560. rdns_debug ("reschedule request with id: %d", (int)req->id);
  561. rdns_request_unschedule (req);
  562. REF_RELEASE (req->io);
  563. if (resolver->ups) {
  564. struct rdns_upstream_elt *elt;
  565. elt = resolver->ups->select_retransmit (
  566. req->requested_names[0].name,
  567. req->requested_names[0].len,
  568. req->io->srv->ups_elt,
  569. resolver->ups->data);
  570. if (elt) {
  571. serv = elt->server;
  572. serv->ups_elt = elt;
  573. }
  574. else {
  575. UPSTREAM_SELECT_ROUND_ROBIN (resolver->servers, serv);
  576. }
  577. }
  578. else {
  579. UPSTREAM_SELECT_ROUND_ROBIN (resolver->servers, serv);
  580. }
  581. if (serv == NULL) {
  582. rdns_warn ("cannot find suitable server for request");
  583. rep = rdns_make_reply (req, RDNS_RC_SERVFAIL);
  584. req->state = RDNS_REQUEST_REPLIED;
  585. req->func (rep, req->arg);
  586. REF_RELEASE (req);
  587. return;
  588. }
  589. /* Select random IO channel */
  590. req->io = serv->io_channels[ottery_rand_uint32 () % serv->io_cnt];
  591. req->io->uses ++;
  592. REF_RETAIN (req->io);
  593. renew = true;
  594. }
  595. }
  596. /*
  597. * Note: when `renew` is true, then send_request deals with the
  598. * timers and events itself
  599. */
  600. r = rdns_send_request (req, req->io->sock, renew);
  601. if (r == 0) {
  602. /* Retransmit one more time */
  603. if (!renew) {
  604. req->async->del_timer (req->async->data,
  605. req->async_event);
  606. req->async_event = req->async->add_write (req->async->data,
  607. req->io->sock, req);
  608. }
  609. req->state = RDNS_REQUEST_WAIT_SEND;
  610. }
  611. else if (r == -1) {
  612. if (req->resolver->ups && req->io->srv->ups_elt) {
  613. req->resolver->ups->fail (req->io->srv->ups_elt,
  614. req->resolver->ups->data, "cannot send retransmit after timeout");
  615. }
  616. else {
  617. UPSTREAM_FAIL (req->io->srv, time (NULL));
  618. }
  619. if (!renew) {
  620. req->async->del_timer (req->async->data,
  621. req->async_event);
  622. req->async_event = NULL;
  623. rdns_request_remove_from_hash(req);
  624. }
  625. /* We have not scheduled timeout actually due to send error */
  626. rep = rdns_make_reply (req, RDNS_RC_NETERR);
  627. req->state = RDNS_REQUEST_REPLIED;
  628. req->func (rep, req->arg);
  629. REF_RELEASE (req);
  630. }
  631. else {
  632. req->async->repeat_timer (req->async->data, req->async_event);
  633. req->state = RDNS_REQUEST_WAIT_REPLY;
  634. }
  635. }
  636. static void
  637. rdns_process_periodic (void *arg)
  638. {
  639. struct rdns_resolver *resolver = (struct rdns_resolver*)arg;
  640. struct rdns_server *serv;
  641. UPSTREAM_RESCAN (resolver->servers, time (NULL));
  642. UPSTREAM_FOREACH (resolver->servers, serv) {
  643. for (int i = 0; i < serv->tcp_io_cnt; i ++) {
  644. if (IS_CHANNEL_CONNECTED(serv->tcp_io_channels[i])) {
  645. /* Disconnect channels with no requests in flight */
  646. if (kh_size(serv->tcp_io_channels[i]->requests) == 0) {
  647. rdns_debug ("reset inactive TCP connection to %s", serv->name);
  648. rdns_ioc_tcp_reset (serv->tcp_io_channels[i]);
  649. }
  650. }
  651. }
  652. }
  653. }
  654. static void
  655. rdns_process_ioc_refresh (void *arg)
  656. {
  657. struct rdns_resolver *resolver = (struct rdns_resolver*)arg;
  658. struct rdns_server *serv;
  659. struct rdns_io_channel *ioc, *nioc;
  660. unsigned int i;
  661. if (resolver->max_ioc_uses > 0) {
  662. UPSTREAM_FOREACH (resolver->servers, serv) {
  663. for (i = 0; i < serv->io_cnt; i ++) {
  664. ioc = serv->io_channels[i];
  665. if (ioc->uses > resolver->max_ioc_uses) {
  666. /* Schedule IOC removing */
  667. nioc = rdns_ioc_new (serv, resolver, false);
  668. if (nioc == NULL) {
  669. rdns_err ("calloc fails to allocate rdns_io_channel");
  670. continue;
  671. }
  672. serv->io_channels[i] = nioc;
  673. rdns_debug ("scheduled io channel for server %s to be refreshed after "
  674. "%lu usages", serv->name, (unsigned long)ioc->uses);
  675. ioc->flags &= ~RDNS_CHANNEL_ACTIVE;
  676. REF_RELEASE (ioc);
  677. }
  678. }
  679. }
  680. }
  681. }
  682. static void
  683. rdns_process_udp_retransmit (int fd, struct rdns_request *req)
  684. {
  685. struct rdns_resolver *resolver;
  686. struct rdns_reply *rep;
  687. int r;
  688. resolver = req->resolver;
  689. resolver->async->del_write (resolver->async->data,
  690. req->async_event);
  691. req->async_event = NULL;
  692. if (req->state == RDNS_REQUEST_FAKE) {
  693. /* Reply is ready */
  694. req->func (req->reply, req->arg);
  695. REF_RELEASE (req);
  696. return;
  697. }
  698. r = rdns_send_request (req, fd, false);
  699. if (r == 0) {
  700. /* Retransmit one more time */
  701. req->async_event = req->async->add_write (req->async->data,
  702. fd, req);
  703. req->state = RDNS_REQUEST_WAIT_SEND;
  704. }
  705. else if (r == -1) {
  706. if (req->resolver->ups && req->io->srv->ups_elt) {
  707. req->resolver->ups->fail (req->io->srv->ups_elt,
  708. req->resolver->ups->data, "retransmit send failed");
  709. }
  710. else {
  711. UPSTREAM_FAIL (req->io->srv, time (NULL));
  712. }
  713. rep = rdns_make_reply (req, RDNS_RC_NETERR);
  714. req->state = RDNS_REQUEST_REPLIED;
  715. req->func (rep, req->arg);
  716. REF_RELEASE (req);
  717. }
  718. else {
  719. req->async_event = req->async->add_timer (req->async->data,
  720. req->timeout, req);
  721. req->state = RDNS_REQUEST_WAIT_REPLY;
  722. }
  723. }
  724. static ssize_t
  725. rdns_write_output_chain (struct rdns_io_channel *ioc, struct rdns_tcp_output_chain *oc)
  726. {
  727. ssize_t r;
  728. struct iovec iov[2];
  729. int niov, already_written;
  730. int packet_len = ntohs (oc->next_write_size);
  731. switch (oc->cur_write) {
  732. case 0:
  733. /* Size + DNS request in full */
  734. iov[0].iov_base = &oc->next_write_size;
  735. iov[0].iov_len = sizeof (oc->next_write_size);
  736. iov[1].iov_base = oc->write_buf;
  737. iov[1].iov_len = packet_len;
  738. niov = 2;
  739. break;
  740. case 1:
  741. /* Partial Size + DNS request in full */
  742. iov[0].iov_base = ((unsigned char *)&oc->next_write_size) + 1;
  743. iov[0].iov_len = 1;
  744. iov[1].iov_base = oc->write_buf;
  745. iov[1].iov_len = packet_len;
  746. niov = 2;
  747. break;
  748. default:
  749. /* Merely DNS packet */
  750. already_written = oc->cur_write - 2;
  751. if (packet_len <= already_written) {
  752. errno = EINVAL;
  753. return -1;
  754. }
  755. iov[0].iov_base = oc->write_buf + already_written;
  756. iov[0].iov_len = packet_len - already_written;
  757. niov = 1;
  758. break;
  759. }
  760. r = writev(ioc->sock, iov, niov);
  761. if (r > 0) {
  762. oc->cur_write += r;
  763. }
  764. return r;
  765. }
  766. static void
  767. rdns_process_tcp_write (int fd, struct rdns_io_channel *ioc)
  768. {
  769. struct rdns_resolver *resolver = ioc->resolver;
  770. /* Try to write as much as we can */
  771. struct rdns_tcp_output_chain *oc, *tmp;
  772. DL_FOREACH_SAFE(ioc->tcp->output_chain, oc, tmp) {
  773. ssize_t r = rdns_write_output_chain (ioc, oc);
  774. if (r == -1) {
  775. if (errno == EAGAIN || errno == EINTR) {
  776. /* Write even is persistent */
  777. return;
  778. }
  779. else {
  780. rdns_err ("error when trying to write request to %s: %s",
  781. ioc->srv->name, strerror (errno));
  782. rdns_ioc_tcp_reset (ioc);
  783. return;
  784. }
  785. }
  786. else if (ntohs(oc->next_write_size) < oc->cur_write) {
  787. /* Packet has been fully written, remove it */
  788. DL_DELETE(ioc->tcp->output_chain, oc);
  789. free (oc); /* It also frees write buf */
  790. ioc->tcp->cur_output_chains --;
  791. }
  792. else {
  793. /* Buffer is not yet processed, stop unless we can continue */
  794. break;
  795. }
  796. }
  797. if (ioc->tcp->cur_output_chains == 0) {
  798. /* Unregister write event */
  799. ioc->resolver->async->del_write (ioc->resolver->async->data,
  800. ioc->tcp->async_write);
  801. ioc->tcp->async_write = NULL;
  802. }
  803. }
  804. void
  805. rdns_process_write (int fd, void *arg)
  806. {
  807. /*
  808. * We first need to dispatch *arg to understand what has caused the write
  809. * readiness event.
  810. * The one possibility is that it was a UDP retransmit request, so our
  811. * arg will be struct rdns_request *
  812. * Another possibility is that write event was triggered by some TCP related
  813. * stuff. In this case the only possibility is that our arg is struct rdns_io_channel *
  814. * To distinguish these two cases (due to flaws in the rdns architecture in the first
  815. * place) we compare the first 8 bytes with RDNS_IO_CHANNEL_TAG
  816. */
  817. uint64_t tag;
  818. memcpy (&tag, arg, sizeof(tag));
  819. if (tag == RDNS_IO_CHANNEL_TAG) {
  820. struct rdns_io_channel *ioc = (struct rdns_io_channel *) arg;
  821. if (IS_CHANNEL_CONNECTED(ioc)) {
  822. rdns_process_tcp_write(fd, ioc);
  823. }
  824. else {
  825. rdns_process_tcp_connect(fd, ioc);
  826. rdns_process_tcp_write(fd, ioc);
  827. }
  828. }
  829. else {
  830. struct rdns_request *req = (struct rdns_request *) arg;
  831. rdns_process_udp_retransmit(fd, req);
  832. }
  833. }
  834. struct rdns_server *
  835. rdns_select_request_upstream (struct rdns_resolver *resolver,
  836. struct rdns_request *req,
  837. bool is_retransmit,
  838. struct rdns_server *prev_serv)
  839. {
  840. struct rdns_server *serv = NULL;
  841. if (resolver->ups) {
  842. struct rdns_upstream_elt *elt;
  843. if (is_retransmit && prev_serv) {
  844. elt = resolver->ups->select_retransmit (req->requested_names[0].name,
  845. req->requested_names[0].len,
  846. prev_serv->ups_elt,
  847. resolver->ups->data);
  848. }
  849. else {
  850. elt = resolver->ups->select (req->requested_names[0].name,
  851. req->requested_names[0].len, resolver->ups->data);
  852. }
  853. if (elt) {
  854. serv = elt->server;
  855. serv->ups_elt = elt;
  856. }
  857. else {
  858. UPSTREAM_SELECT_ROUND_ROBIN (resolver->servers, serv);
  859. }
  860. }
  861. else {
  862. UPSTREAM_SELECT_ROUND_ROBIN (resolver->servers, serv);
  863. }
  864. return serv;
  865. }
  866. #define align_ptr(p, a) \
  867. (guint8 *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1))
  868. struct rdns_request*
  869. rdns_make_request_full (
  870. struct rdns_resolver *resolver,
  871. dns_callback_type cb,
  872. void *cbdata,
  873. double timeout,
  874. unsigned int repeats,
  875. unsigned int queries,
  876. ...
  877. )
  878. {
  879. va_list args;
  880. struct rdns_request *req;
  881. struct rdns_server *serv;
  882. int r, type;
  883. unsigned int i, tlen = 0, clen = 0, cur;
  884. size_t olen;
  885. const char *cur_name, *last_name = NULL;
  886. struct rdns_compression_entry *comp = NULL;
  887. struct rdns_fake_reply *fake_rep = NULL;
  888. char fake_buf[MAX_FAKE_NAME + sizeof (struct rdns_fake_reply_idx) + 16];
  889. struct rdns_fake_reply_idx *idx;
  890. if (resolver == NULL || !resolver->initialized) {
  891. if (resolver == NULL) {
  892. return NULL;
  893. }
  894. rdns_err ("resolver is uninitialized");
  895. return NULL;
  896. }
  897. req = malloc (sizeof (struct rdns_request));
  898. if (req == NULL) {
  899. rdns_err ("failed to allocate memory for request: %s",
  900. strerror (errno));
  901. return NULL;
  902. }
  903. req->resolver = resolver;
  904. req->func = cb;
  905. req->arg = cbdata;
  906. req->reply = NULL;
  907. req->qcount = queries;
  908. req->io = NULL;
  909. req->state = RDNS_REQUEST_NEW;
  910. req->packet = NULL;
  911. req->requested_names = calloc (queries, sizeof (struct rdns_request_name));
  912. req->async_event = NULL;
  913. if (req->requested_names == NULL) {
  914. free (req);
  915. rdns_err ("failed to allocate memory for request data: %s",
  916. strerror (errno));
  917. return NULL;
  918. }
  919. req->type = 0;
  920. #ifdef TWEETNACL
  921. req->curve_plugin_data = NULL;
  922. #endif
  923. REF_INIT_RETAIN (req, rdns_request_free);
  924. /* Calculate packet's total length based on records count */
  925. va_start (args, queries);
  926. for (i = 0; i < queries * 2; i += 2) {
  927. cur = i / 2;
  928. cur_name = va_arg (args, const char *);
  929. type = va_arg (args, int);
  930. if (cur_name != NULL) {
  931. clen = strlen (cur_name);
  932. if (clen == 0) {
  933. rdns_warn ("got empty name to resolve");
  934. rdns_request_free (req);
  935. return NULL;
  936. }
  937. if (cur_name[0] == '.') {
  938. /* Skip dots at the begin */
  939. unsigned int ndots = strspn (cur_name, ".");
  940. cur_name += ndots;
  941. clen -= ndots;
  942. if (clen == 0) {
  943. rdns_warn ("got empty name to resolve");
  944. rdns_request_free (req);
  945. return NULL;
  946. }
  947. }
  948. if (cur_name[clen - 1] == '.') {
  949. /* Skip trailing dots */
  950. while (clen >= 1 && cur_name[clen - 1] == '.') {
  951. clen --;
  952. }
  953. if (clen == 0) {
  954. rdns_warn ("got empty name to resolve");
  955. rdns_request_free (req);
  956. return NULL;
  957. }
  958. }
  959. if (last_name == NULL && queries == 1 && clen < MAX_FAKE_NAME) {
  960. /* We allocate structure in the static space */
  961. idx = (struct rdns_fake_reply_idx *)align_ptr (fake_buf, 16);
  962. idx->type = type;
  963. idx->len = clen;
  964. memcpy (idx->request, cur_name, clen);
  965. HASH_FIND (hh, resolver->fake_elts, idx, sizeof (*idx) + clen,
  966. fake_rep);
  967. if (fake_rep) {
  968. /* We actually treat it as a short-circuit */
  969. req->reply = rdns_make_reply (req, fake_rep->rcode);
  970. req->reply->entries = fake_rep->result;
  971. req->state = RDNS_REQUEST_FAKE;
  972. }
  973. }
  974. last_name = cur_name;
  975. tlen += clen;
  976. }
  977. else if (last_name == NULL) {
  978. rdns_err ("got NULL as the first name to resolve");
  979. rdns_request_free (req);
  980. return NULL;
  981. }
  982. if (req->state != RDNS_REQUEST_FAKE) {
  983. if (!rdns_format_dns_name (resolver, last_name, clen,
  984. &req->requested_names[cur].name, &olen)) {
  985. rdns_err ("cannot format %s", last_name);
  986. rdns_request_free (req);
  987. return NULL;
  988. }
  989. req->requested_names[cur].len = olen;
  990. }
  991. else {
  992. req->requested_names[cur].len = clen;
  993. }
  994. req->requested_names[cur].type = type;
  995. }
  996. va_end (args);
  997. if (req->state != RDNS_REQUEST_FAKE) {
  998. rdns_allocate_packet (req, tlen);
  999. rdns_make_dns_header (req, queries);
  1000. for (i = 0; i < queries; i++) {
  1001. cur_name = req->requested_names[i].name;
  1002. clen = req->requested_names[i].len;
  1003. type = req->requested_names[i].type;
  1004. if (queries > 1) {
  1005. if (!rdns_add_rr (req, cur_name, clen, type, &comp)) {
  1006. rdns_err ("cannot add rr");
  1007. REF_RELEASE (req);
  1008. rdns_compression_free(comp);
  1009. return NULL;
  1010. }
  1011. } else {
  1012. if (!rdns_add_rr (req, cur_name, clen, type, NULL)) {
  1013. rdns_err ("cannot add rr");
  1014. REF_RELEASE (req);
  1015. rdns_compression_free(comp);
  1016. return NULL;
  1017. }
  1018. }
  1019. }
  1020. rdns_compression_free(comp);
  1021. /* Add EDNS RR */
  1022. rdns_add_edns0 (req);
  1023. req->retransmits = repeats ? repeats : 1;
  1024. req->timeout = timeout;
  1025. req->state = RDNS_REQUEST_NEW;
  1026. }
  1027. req->async = resolver->async;
  1028. serv = rdns_select_request_upstream (resolver, req, false, NULL);
  1029. if (serv == NULL) {
  1030. rdns_warn ("cannot find suitable server for request");
  1031. REF_RELEASE (req);
  1032. return NULL;
  1033. }
  1034. /* Select random IO channel */
  1035. req->io = serv->io_channels[ottery_rand_uint32 () % serv->io_cnt];
  1036. if (req->state == RDNS_REQUEST_FAKE) {
  1037. req->async_event = resolver->async->add_write (resolver->async->data,
  1038. req->io->sock, req);
  1039. }
  1040. else {
  1041. /* Now send request to server */
  1042. do {
  1043. r = rdns_send_request (req, req->io->sock, true);
  1044. if (r == -1) {
  1045. req->retransmits --; /* It must be > 0 */
  1046. if (req->retransmits > 0) {
  1047. if (resolver->ups && serv->ups_elt) {
  1048. resolver->ups->fail (serv->ups_elt, resolver->ups->data,
  1049. "send IO error");
  1050. }
  1051. else {
  1052. UPSTREAM_FAIL (serv, time (NULL));
  1053. }
  1054. serv = rdns_select_request_upstream (resolver, req,
  1055. true, serv);
  1056. if (serv == NULL) {
  1057. rdns_warn ("cannot find suitable server for request");
  1058. REF_RELEASE (req);
  1059. return NULL;
  1060. }
  1061. req->io = serv->io_channels[ottery_rand_uint32 () % serv->io_cnt];
  1062. }
  1063. else {
  1064. rdns_info ("cannot send DNS request: %s", strerror (errno));
  1065. REF_RELEASE (req);
  1066. if (resolver->ups && serv->ups_elt) {
  1067. resolver->ups->fail (serv->ups_elt, resolver->ups->data,
  1068. "send IO error");
  1069. }
  1070. else {
  1071. UPSTREAM_FAIL (serv, time (NULL));
  1072. }
  1073. return NULL;
  1074. }
  1075. }
  1076. else {
  1077. /* All good */
  1078. req->io->uses++;
  1079. break;
  1080. }
  1081. } while (req->retransmits > 0);
  1082. }
  1083. REF_RETAIN (req->io);
  1084. REF_RETAIN (req->resolver);
  1085. return req;
  1086. }
  1087. bool
  1088. rdns_resolver_init (struct rdns_resolver *resolver)
  1089. {
  1090. unsigned int i;
  1091. struct rdns_server *serv;
  1092. struct rdns_io_channel *ioc;
  1093. if (!resolver->async_binded) {
  1094. rdns_err ("no async backend specified");
  1095. return false;
  1096. }
  1097. if (resolver->servers == NULL) {
  1098. rdns_err ("no DNS servers defined");
  1099. return false;
  1100. }
  1101. /* Now init io channels to all servers */
  1102. UPSTREAM_FOREACH (resolver->servers, serv) {
  1103. serv->io_channels = calloc (serv->io_cnt, sizeof (struct rdns_io_channel *));
  1104. if (serv->io_channels == NULL) {
  1105. rdns_err ("cannot allocate memory for the resolver IO channels");
  1106. return false;
  1107. }
  1108. for (i = 0; i < serv->io_cnt; i ++) {
  1109. ioc = rdns_ioc_new(serv, resolver, false);
  1110. if (ioc == NULL) {
  1111. rdns_err ("cannot allocate memory or init the IO channel");
  1112. return false;
  1113. }
  1114. serv->io_channels[i] = ioc;
  1115. }
  1116. int ntcp_channels = 0;
  1117. /*
  1118. * We are more forgiving for TCP IO channels: we can have zero of them
  1119. * if DNS is misconfigured and still be able to resolve stuff
  1120. */
  1121. serv->tcp_io_channels = calloc (serv->tcp_io_cnt, sizeof (struct rdns_io_channel *));
  1122. if (serv->tcp_io_channels == NULL) {
  1123. rdns_err ("cannot allocate memory for the resolver TCP IO channels");
  1124. return false;
  1125. }
  1126. for (i = 0; i < serv->tcp_io_cnt; i ++) {
  1127. ioc = rdns_ioc_new (serv, resolver, true);
  1128. if (ioc == NULL) {
  1129. rdns_err ("cannot allocate memory or init the TCP IO channel");
  1130. continue;
  1131. }
  1132. serv->tcp_io_channels[ntcp_channels++] = ioc;
  1133. }
  1134. serv->tcp_io_cnt = ntcp_channels;
  1135. }
  1136. if (resolver->async->add_periodic) {
  1137. resolver->periodic = resolver->async->add_periodic (resolver->async->data,
  1138. UPSTREAM_REVIVE_TIME, rdns_process_periodic, resolver);
  1139. }
  1140. resolver->initialized = true;
  1141. return true;
  1142. }
  1143. void
  1144. rdns_resolver_register_plugin (struct rdns_resolver *resolver,
  1145. struct rdns_plugin *plugin)
  1146. {
  1147. if (resolver != NULL && plugin != NULL) {
  1148. /* XXX: support only network plugin now, and only a single one */
  1149. if (plugin->type == RDNS_PLUGIN_CURVE) {
  1150. resolver->curve_plugin = plugin;
  1151. }
  1152. }
  1153. }
  1154. void *
  1155. rdns_resolver_add_server (struct rdns_resolver *resolver,
  1156. const char *name, unsigned int port,
  1157. int priority, unsigned int io_cnt)
  1158. {
  1159. struct rdns_server *serv;
  1160. union {
  1161. struct in_addr v4;
  1162. struct in6_addr v6;
  1163. } addr;
  1164. if (inet_pton (AF_INET, name, &addr) == 0 &&
  1165. inet_pton (AF_INET6, name, &addr) == 0) {
  1166. /* Invalid IP */
  1167. return NULL;
  1168. }
  1169. if (io_cnt == 0) {
  1170. return NULL;
  1171. }
  1172. if (port == 0 || port > UINT16_MAX) {
  1173. return NULL;
  1174. }
  1175. serv = calloc (1, sizeof (struct rdns_server));
  1176. if (serv == NULL) {
  1177. return NULL;
  1178. }
  1179. serv->name = strdup (name);
  1180. if (serv->name == NULL) {
  1181. free (serv);
  1182. return NULL;
  1183. }
  1184. serv->io_cnt = io_cnt;
  1185. /* TODO: make it configurable maybe? */
  1186. serv->tcp_io_cnt = default_tcp_io_cnt;
  1187. serv->port = port;
  1188. UPSTREAM_ADD (resolver->servers, serv, priority);
  1189. return serv;
  1190. }
  1191. void
  1192. rdns_resolver_set_logger (struct rdns_resolver *resolver,
  1193. rdns_log_function logger, void *log_data)
  1194. {
  1195. resolver->logger = logger;
  1196. resolver->log_data = log_data;
  1197. }
  1198. void
  1199. rdns_resolver_set_log_level (struct rdns_resolver *resolver,
  1200. enum rdns_log_level level)
  1201. {
  1202. resolver->log_level = level;
  1203. }
  1204. void
  1205. rdns_resolver_set_upstream_lib (struct rdns_resolver *resolver,
  1206. struct rdns_upstream_context *ups_ctx,
  1207. void *ups_data)
  1208. {
  1209. resolver->ups = ups_ctx;
  1210. resolver->ups->data = ups_data;
  1211. }
  1212. void
  1213. rdns_resolver_set_max_io_uses (struct rdns_resolver *resolver,
  1214. uint64_t max_ioc_uses, double check_time)
  1215. {
  1216. if (resolver->refresh_ioc_periodic != NULL) {
  1217. resolver->async->del_periodic (resolver->async->data,
  1218. resolver->refresh_ioc_periodic);
  1219. resolver->refresh_ioc_periodic = NULL;
  1220. }
  1221. resolver->max_ioc_uses = max_ioc_uses;
  1222. if (check_time > 0.0 && resolver->async->add_periodic) {
  1223. resolver->refresh_ioc_periodic =
  1224. resolver->async->add_periodic (resolver->async->data,
  1225. check_time, rdns_process_ioc_refresh, resolver);
  1226. }
  1227. }
  1228. static void
  1229. rdns_resolver_free (struct rdns_resolver *resolver)
  1230. {
  1231. struct rdns_server *serv, *stmp;
  1232. struct rdns_io_channel *ioc;
  1233. unsigned int i;
  1234. if (resolver->initialized) {
  1235. if (resolver->periodic != NULL) {
  1236. resolver->async->del_periodic (resolver->async->data, resolver->periodic);
  1237. }
  1238. if (resolver->refresh_ioc_periodic != NULL) {
  1239. resolver->async->del_periodic (resolver->async->data,
  1240. resolver->refresh_ioc_periodic);
  1241. }
  1242. if (resolver->curve_plugin != NULL && resolver->curve_plugin->dtor != NULL) {
  1243. resolver->curve_plugin->dtor (resolver, resolver->curve_plugin->data);
  1244. }
  1245. /* Stop IO watch on all IO channels */
  1246. UPSTREAM_FOREACH_SAFE (resolver->servers, serv, stmp) {
  1247. for (i = 0; i < serv->io_cnt; i ++) {
  1248. ioc = serv->io_channels[i];
  1249. REF_RELEASE (ioc);
  1250. }
  1251. for (i = 0; i < serv->tcp_io_cnt; i ++) {
  1252. ioc = serv->tcp_io_channels[i];
  1253. REF_RELEASE (ioc);
  1254. }
  1255. UPSTREAM_DEL (resolver->servers, serv);
  1256. free (serv->io_channels);
  1257. free (serv->tcp_io_channels);
  1258. free (serv->name);
  1259. free (serv);
  1260. }
  1261. }
  1262. free (resolver->async);
  1263. free (resolver);
  1264. }
  1265. struct rdns_resolver *
  1266. rdns_resolver_new (int flags)
  1267. {
  1268. struct rdns_resolver *new_resolver;
  1269. new_resolver = calloc (1, sizeof (struct rdns_resolver));
  1270. REF_INIT_RETAIN (new_resolver, rdns_resolver_free);
  1271. new_resolver->logger = rdns_logger_internal;
  1272. new_resolver->log_data = new_resolver;
  1273. new_resolver->flags = flags;
  1274. return new_resolver;
  1275. }
  1276. void
  1277. rdns_resolver_async_bind (struct rdns_resolver *resolver,
  1278. struct rdns_async_context *ctx)
  1279. {
  1280. if (resolver != NULL && ctx != NULL) {
  1281. resolver->async = ctx;
  1282. resolver->async_binded = true;
  1283. }
  1284. }
  1285. void
  1286. rdns_resolver_set_dnssec (struct rdns_resolver *resolver, bool enabled)
  1287. {
  1288. if (resolver) {
  1289. resolver->enable_dnssec = enabled;
  1290. }
  1291. }
  1292. void rdns_resolver_set_fake_reply (struct rdns_resolver *resolver,
  1293. const char *name,
  1294. enum rdns_request_type type,
  1295. enum dns_rcode rcode,
  1296. struct rdns_reply_entry *reply)
  1297. {
  1298. struct rdns_fake_reply *fake_rep;
  1299. struct rdns_fake_reply_idx *srch;
  1300. unsigned len = strlen (name);
  1301. assert (len < MAX_FAKE_NAME);
  1302. srch = malloc (sizeof (*srch) + len);
  1303. srch->len = len;
  1304. srch->type = type;
  1305. memcpy (srch->request, name, len);
  1306. HASH_FIND (hh, resolver->fake_elts, srch, len + sizeof (*srch), fake_rep);
  1307. if (fake_rep) {
  1308. /* Append reply to the existing list */
  1309. fake_rep->rcode = rcode;
  1310. if (reply) {
  1311. DL_CONCAT (fake_rep->result, reply);
  1312. }
  1313. }
  1314. else {
  1315. fake_rep = calloc (1, sizeof (*fake_rep) + len);
  1316. if (fake_rep == NULL) {
  1317. abort ();
  1318. }
  1319. fake_rep->rcode = rcode;
  1320. memcpy (&fake_rep->key, srch, sizeof (*srch) + len);
  1321. if (reply) {
  1322. DL_CONCAT (fake_rep->result, reply);
  1323. }
  1324. HASH_ADD (hh, resolver->fake_elts, key, sizeof (*srch) + len, fake_rep);
  1325. }
  1326. free (srch);
  1327. }