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 38KB

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