blob: cb7de6ab678b77d038b03afdf9e3b57540af3a16 [file] [log] [blame]
Baptiste Assmann325137d2015-04-13 23:40:55 +02001/*
2 * Name server resolution
3 *
4 * Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
14#include <fcntl.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19
20#include <sys/types.h>
21
22#include <common/time.h>
23#include <common/ticks.h>
24
Baptiste Assmannfa4a6632017-05-04 09:05:00 +020025#include <import/lru.h>
26#include <import/xxhash.h>
27
William Lallemand69e96442016-11-19 00:58:54 +010028#include <types/applet.h>
29#include <types/cli.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020030#include <types/global.h>
31#include <types/dns.h>
32#include <types/proto_udp.h>
William Lallemand69e96442016-11-19 00:58:54 +010033#include <types/stats.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020034
William Lallemand69e96442016-11-19 00:58:54 +010035#include <proto/channel.h>
36#include <proto/cli.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020037#include <proto/checks.h>
38#include <proto/dns.h>
39#include <proto/fd.h>
40#include <proto/log.h>
41#include <proto/server.h>
42#include <proto/task.h>
43#include <proto/proto_udp.h>
William Lallemand69e96442016-11-19 00:58:54 +010044#include <proto/stream_interface.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020045
46struct list dns_resolvers = LIST_HEAD_INIT(dns_resolvers);
47struct dns_resolution *resolution = NULL;
48
49static int64_t dns_query_id_seed; /* random seed */
50
Baptiste Assmannfa4a6632017-05-04 09:05:00 +020051static struct lru64_head *dns_lru_tree;
52static int dns_cache_size = 1024; /* arbitrary DNS cache size */
53
Baptiste Assmann325137d2015-04-13 23:40:55 +020054/* proto_udp callback functions for a DNS resolution */
55struct dgram_data_cb resolve_dgram_cb = {
56 .recv = dns_resolve_recv,
57 .send = dns_resolve_send,
58};
59
Baptiste Assmann201c07f2017-05-22 15:17:15 +020060/* local function prototypes */
61static int dns_run_resolution(struct dns_requester *requester);
62
Baptiste Assmann325137d2015-04-13 23:40:55 +020063#if DEBUG
64/*
65 * go through the resolutions associated to a resolvers section and print the ID and hostname in
66 * domain name format
67 * should be used for debug purpose only
68 */
69void dns_print_current_resolutions(struct dns_resolvers *resolvers)
70{
Baptiste Assmann201c07f2017-05-22 15:17:15 +020071 list_for_each_entry(resolution, &resolvers->resolution.curr, list) {
Baptiste Assmann325137d2015-04-13 23:40:55 +020072 printf(" resolution %d for %s\n", resolution->query_id, resolution->hostname_dn);
73 }
74}
75#endif
76
Baptiste Assmann201c07f2017-05-22 15:17:15 +020077void dump_dns_config()
78{
79 struct dns_resolvers *curr_resolvers = NULL;
80 struct dns_nameserver *curr_nameserver = NULL;
81 struct dns_resolution *curr_resolution = NULL;
82 struct dns_requester *curr_requester = NULL;
83
84 printf("===============\n");
85 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
86 printf("Resolvers: %s\n", curr_resolvers->id);
87
88 printf(" nameservers:\n");
89 list_for_each_entry(curr_nameserver, &curr_resolvers->nameserver_list, list) {
90 printf(" %s\n", curr_nameserver->id);
91 }
92
93/*
94 printf(" resolution.pool list:\n");
95 list_for_each_entry(curr_resolution, &curr_resolvers->resolution.pool, list) {
96 printf(" %p\n", curr_resolution);
97 }
98*/
99
100 printf(" resolution.wait list:\n");
101 list_for_each_entry(curr_resolution, &curr_resolvers->resolution.wait, list) {
102 printf(" %p %s\n", curr_resolution, curr_resolution->hostname_dn);
103 printf(" requester.wait list:\n");
104 list_for_each_entry(curr_requester, &curr_resolution->requester.wait, list) {
105 printf(" %p %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
106 }
107 printf(" requester.curr list:\n");
108 list_for_each_entry(curr_requester, &curr_resolution->requester.curr, list) {
109 printf(" %p %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
110 }
111 }
112 printf(" resolution.curr list:\n");
113 list_for_each_entry(curr_resolution, &curr_resolvers->resolution.curr, list) {
114 printf(" %p %s\n", curr_resolution, curr_resolution->hostname_dn);
115 printf(" requester.wait list:\n");
116 list_for_each_entry(curr_requester, &curr_resolution->requester.wait, list) {
117 printf(" %p %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
118 }
119 printf(" requester.curr list:\n");
120 list_for_each_entry(curr_requester, &curr_resolution->requester.curr, list) {
121 printf(" %p %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
122 }
123 }
124 }
125
126 printf("===============\n");
127}
128
129/*
130 * Initiates a new name resolution:
131 * - generates a query id
132 * - configure the resolution structure
133 * - startup the resolvers task if required
134 *
135 * returns:
136 * - 0 if everything started properly
137 * - -1 in case of error or if resolution already running
138 */
139int dns_trigger_resolution(struct dns_resolution *resolution)
140{
141 struct dns_requester *requester = NULL, *tmprequester;
142 struct dns_resolvers *resolvers = NULL;
143 int inter;
144
145 /* process the element of the wait queue */
146 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.wait, list) {
147 inter = 0;
148
149 switch (obj_type(requester->requester)) {
150 case OBJ_TYPE_SERVER:
151 inter = objt_server(requester->requester)->check.inter;
152 resolvers = objt_server(requester->requester)->resolvers;
153 break;
154 case OBJ_TYPE_NONE:
155 default:
156 return -1;
157 }
158
159 /* if data is fresh enough, let's use it */
160 if (!tick_is_expired(tick_add(resolution->last_resolution, inter), now_ms)) {
161 /* we only use cache if the response there is valid.
162 * If not valid, we run the resolution and move the requester to
163 * the run queue. */
164 if (resolution->status != RSLV_STATUS_VALID) {
165 LIST_DEL(&requester->list);
166 LIST_ADDQ(&resolution->requester.curr, &requester->list);
167 dns_run_resolution(requester);
168 continue;
169 }
170
171 requester->requester_cb(requester, NULL);
172 }
173 else {
174 LIST_DEL(&requester->list);
175 LIST_ADDQ(&resolution->requester.curr, &requester->list);
176 dns_run_resolution(requester);
177 }
178 }
179
180 if (resolvers)
181 dns_update_resolvers_timeout(resolvers);
182
183 return 0;
184}
185
Baptiste Assmann325137d2015-04-13 23:40:55 +0200186/*
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200187 * Prepare and send a DNS resolution.
188 *
189 * Return code:
190 * - 0 if no error occured
191 * - -1 in case of error
192 */
193static int
194dns_run_resolution(struct dns_requester *requester)
195{
196 struct dns_resolution *resolution;
197 struct dns_resolvers *resolvers;
198 int query_id, query_type, i;
199 struct proxy *proxy;
200
201 resolution = NULL;
202 resolvers = NULL;
203 proxy = NULL;
204 query_type = -1;
205 switch (obj_type(requester->requester)) {
206 case OBJ_TYPE_SERVER:
207 resolution = objt_server(requester->requester)->resolution;
208 resolvers = objt_server(requester->requester)->resolvers;
209 proxy = objt_server(requester->requester)->proxy;
210 query_type = requester->prefered_query_type;
211 break;
212 case OBJ_TYPE_NONE:
213 default:
214 return -1;
215 }
216
217 /*
218 * check if a resolution has already been started for this server
219 * return directly to avoid resolution pill up.
220 */
221 if (resolution->step != RSLV_STEP_NONE)
222 return 0;
223
224 /* generates a query id */
225 i = 0;
226 do {
227 query_id = dns_rnd16();
228 /* we do try only 100 times to find a free query id */
229 if (i++ > 100) {
230 chunk_printf(&trash, "could not generate a query id for %s, in resolvers %s",
231 resolution->hostname_dn, resolvers->id);
232
233 if (proxy)
234 send_log(proxy, LOG_NOTICE, "%s.\n", trash.str);
235 return -1;
236 }
237 } while (eb32_lookup(&resolvers->query_ids, query_id));
238
239 /* move the resolution into the run queue */
240 LIST_DEL(&resolution->list);
241 LIST_ADDQ(&resolvers->resolution.curr, &resolution->list);
242
243 /* now update resolution parameters */
244 resolution->query_id = query_id;
245 resolution->qid.key = query_id;
246 resolution->step = RSLV_STEP_RUNNING;
247 resolution->query_type = query_type;
248 resolution->try = resolvers->resolve_retries;
249 resolution->try_cname = 0;
250 resolution->nb_responses = 0;
251 eb32_insert(&resolvers->query_ids, &resolution->qid);
252
253 dns_send_query(resolution);
254 resolution->try -= 1;
255
256 /* update wakeup date if this resolution is the only one in the FIFO list */
257 if (dns_check_resolution_queue(resolvers) == 1) {
258 /* update task timeout */
259 dns_update_resolvers_timeout(resolvers);
260 task_queue(resolvers->t);
261 }
262
263 return 0;
264}
265
266/*
Baptiste Assmann325137d2015-04-13 23:40:55 +0200267 * check if there is more than 1 resolution in the resolver's resolution list
268 * return value:
269 * 0: empty list
270 * 1: exactly one entry in the list
271 * 2: more than one entry in the list
272 */
273int dns_check_resolution_queue(struct dns_resolvers *resolvers)
274{
275
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200276 if (LIST_ISEMPTY(&resolvers->resolution.curr))
Baptiste Assmann325137d2015-04-13 23:40:55 +0200277 return 0;
278
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200279 if ((resolvers->resolution.curr.n) && (resolvers->resolution.curr.n == resolvers->resolution.curr.p))
Baptiste Assmann325137d2015-04-13 23:40:55 +0200280 return 1;
281
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200282 if (! ((resolvers->resolution.curr.n == resolvers->resolution.curr.p)
283 && (&resolvers->resolution.curr != resolvers->resolution.curr.n)))
Baptiste Assmann325137d2015-04-13 23:40:55 +0200284 return 2;
285
286 return 0;
287}
288
289/*
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200290 * reset some resolution parameters to initial values and also delete the
291 * query ID from the resolver's tree.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200292 */
293void dns_reset_resolution(struct dns_resolution *resolution)
294{
295 /* update resolution status */
296 resolution->step = RSLV_STEP_NONE;
297
298 resolution->try = 0;
299 resolution->try_cname = 0;
300 resolution->last_resolution = now_ms;
301 resolution->nb_responses = 0;
302
303 /* clean up query id */
304 eb32_delete(&resolution->qid);
305 resolution->query_id = 0;
306 resolution->qid.key = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200307}
308
309/*
310 * function called when a network IO is generated on a name server socket for an incoming packet
311 * It performs the following actions:
312 * - check if the packet requires processing (not outdated resolution)
313 * - ensure the DNS packet received is valid and call requester's callback
314 * - call requester's error callback if invalid response
Baptiste Assmann3cf7f982016-04-17 22:43:26 +0200315 * - check the dn_name in the packet against the one sent
Baptiste Assmann325137d2015-04-13 23:40:55 +0200316 */
317void dns_resolve_recv(struct dgram_conn *dgram)
318{
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200319 struct dns_nameserver *nameserver, *tmpnameserver;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200320 struct dns_resolvers *resolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200321 struct dns_resolution *resolution = NULL;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200322 struct dns_query_item *query;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200323 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
324 unsigned char *bufend;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200325 int fd, buflen, dns_resp, need_resend;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200326 unsigned short query_id;
327 struct eb32_node *eb;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200328 struct lru64 *lru = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200329 struct dns_requester *requester = NULL, *tmprequester = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200330
331 fd = dgram->t.sock.fd;
332
333 /* check if ready for reading */
334 if (!fd_recv_ready(fd))
335 return;
336
337 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200338 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200339 return;
340
341 resolvers = nameserver->resolvers;
342
343 /* process all pending input messages */
344 while (1) {
345 /* read message received */
346 memset(buf, '\0', DNS_MAX_UDP_MESSAGE + 1);
347 if ((buflen = recv(fd, (char*)buf , DNS_MAX_UDP_MESSAGE, 0)) < 0) {
348 /* FIXME : for now we consider EAGAIN only */
349 fd_cant_recv(fd);
350 break;
351 }
352
353 /* message too big */
354 if (buflen > DNS_MAX_UDP_MESSAGE) {
355 nameserver->counters.too_big += 1;
356 continue;
357 }
358
359 /* initializing variables */
360 bufend = buf + buflen; /* pointer to mark the end of the buffer */
361
362 /* read the query id from the packet (16 bits) */
363 if (buf + 2 > bufend) {
364 nameserver->counters.invalid += 1;
365 continue;
366 }
367 query_id = dns_response_get_query_id(buf);
368
369 /* search the query_id in the pending resolution tree */
Baptiste Assmann01daef32015-09-02 22:05:24 +0200370 eb = eb32_lookup(&resolvers->query_ids, query_id);
371 if (eb == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200372 /* unknown query id means an outdated response and can be safely ignored */
373 nameserver->counters.outdated += 1;
374 continue;
375 }
376
377 /* known query id means a resolution in prgress */
378 resolution = eb32_entry(eb, struct dns_resolution, qid);
379
380 if (!resolution) {
381 nameserver->counters.outdated += 1;
382 continue;
383 }
384
385 /* number of responses received */
386 resolution->nb_responses += 1;
387
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200388 dns_resp = dns_validate_dns_response(buf, bufend, resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200389
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200390 /* treat errors first
391 * need_resend flag could be set to 0 by default before the 'switch' and then
392 * set to 1 only where needed, but I think it's better this way to make people
393 * aware they have to think twice how to set this flag when updating this portion
394 * of the code
395 */
396 switch (dns_resp) {
397 case DNS_RESP_VALID:
398 need_resend = 0;
399 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200400
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200401 case DNS_RESP_INVALID:
402 case DNS_RESP_QUERY_COUNT_ERROR:
403 case DNS_RESP_WRONG_NAME:
404 if (resolution->status != RSLV_STATUS_INVALID) {
405 resolution->status = RSLV_STATUS_INVALID;
406 resolution->last_status_change = now_ms;
407 }
408 nameserver->counters.invalid += 1;
409 need_resend = 0;
410 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200411
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200412 case DNS_RESP_ANCOUNT_ZERO:
413 if (resolution->status != RSLV_STATUS_OTHER) {
414 resolution->status = RSLV_STATUS_OTHER;
415 resolution->last_status_change = now_ms;
416 }
417 nameserver->counters.any_err += 1;
418 need_resend = 1;
419 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200420
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200421 case DNS_RESP_NX_DOMAIN:
422 if (resolution->status != RSLV_STATUS_NX) {
423 resolution->status = RSLV_STATUS_NX;
424 resolution->last_status_change = now_ms;
425 }
426 nameserver->counters.nx += 1;
427 need_resend = 0;
428 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200429
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200430 case DNS_RESP_REFUSED:
431 if (resolution->status != RSLV_STATUS_REFUSED) {
432 resolution->status = RSLV_STATUS_REFUSED;
433 resolution->last_status_change = now_ms;
434 }
435 nameserver->counters.refused += 1;
436 need_resend = 0;
437 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200438
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200439 case DNS_RESP_CNAME_ERROR:
440 if (resolution->status != RSLV_STATUS_OTHER) {
441 resolution->status = RSLV_STATUS_OTHER;
442 resolution->last_status_change = now_ms;
443 }
444 nameserver->counters.cname_error += 1;
445 need_resend = 1;
446 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200447
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200448 case DNS_RESP_TRUNCATED:
449 if (resolution->status != RSLV_STATUS_OTHER) {
450 resolution->status = RSLV_STATUS_OTHER;
451 resolution->last_status_change = now_ms;
452 }
453 nameserver->counters.truncated += 1;
454 need_resend = 1;
455 break;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200456
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200457 case DNS_RESP_NO_EXPECTED_RECORD:
458 if (resolution->status != RSLV_STATUS_OTHER) {
459 resolution->status = RSLV_STATUS_OTHER;
460 resolution->last_status_change = now_ms;
461 }
462 nameserver->counters.other += 1;
463 need_resend = 1;
464 break;
465
466 case DNS_RESP_ERROR:
467 case DNS_RESP_INTERNAL:
468 if (resolution->status != RSLV_STATUS_OTHER) {
469 resolution->status = RSLV_STATUS_OTHER;
470 resolution->last_status_change = now_ms;
471 }
472 nameserver->counters.other += 1;
473 need_resend = 1;
474 break;
475 }
476
477 /* some error codes trigger a re-send of the query, but switching the
478 * query type.
479 * This is the case for the following error codes:
480 * DNS_RESP_ANCOUNT_ZERO
481 * DNS_RESP_TRUNCATED
482 * DNS_RESP_ERROR
483 * DNS_RESP_INTERNAL
484 * DNS_RESP_NO_EXPECTED_RECORD
485 * DNS_RESP_CNAME_ERROR
486 */
487 if (need_resend) {
488 int family_prio;
489 int res_preferred_afinet, res_preferred_afinet6;
490
491 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
492 switch (obj_type(requester->requester)) {
493 case OBJ_TYPE_SERVER:
494 family_prio = objt_server(requester->requester)->dns_opts.family_prio;
495 break;
496 case OBJ_TYPE_NONE:
497 default:
498 family_prio = AF_INET6;
499 }
500 res_preferred_afinet = family_prio == AF_INET && resolution->query_type == DNS_RTYPE_A;
501 res_preferred_afinet6 = family_prio == AF_INET6 && resolution->query_type == DNS_RTYPE_AAAA;
502 if ((res_preferred_afinet || res_preferred_afinet6)
503 || (resolution->try > 0)) {
504 /* let's change the query type */
505 if (res_preferred_afinet6) {
506 /* fallback from AAAA to A */
507 resolution->query_type = DNS_RTYPE_A;
508 }
509 else if (res_preferred_afinet) {
510 /* fallback from A to AAAA */
511 resolution->query_type = DNS_RTYPE_AAAA;
512 }
513 else {
514 resolution->try -= 1;
515 if (family_prio == AF_INET) {
516 resolution->query_type = DNS_RTYPE_A;
517 } else {
518 resolution->query_type = DNS_RTYPE_AAAA;
519 }
520 }
521
522 dns_send_query(resolution);
523 /*
524 * move the resolution to the last element of the FIFO queue
525 * and update timeout wakeup based on the new first entry
526 */
527 if (dns_check_resolution_queue(resolvers) > 1) {
528 /* second resolution becomes first one */
529 LIST_DEL(&resolution->list);
530 /* ex first resolution goes to the end of the queue */
531 LIST_ADDQ(&resolvers->resolution.curr, &resolution->list);
532 }
533
534 dns_update_resolvers_timeout(resolvers);
535 goto next_packet;
536 }
537
538 /* if we're there, this means that we already ran out of chances to re-send
539 * the query */
540 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
541 requester->requester_error_cb(requester, dns_resp);
542 }
543 goto next_packet;
544 }
545
546 /* now processing those error codes only:
547 * DNS_RESP_NX_DOMAIN
548 * DNS_RESP_REFUSED
549 */
550 if (dns_resp != DNS_RESP_VALID) {
551 /* now parse list of requesters currently waiting for this resolution */
552 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
553 requester->requester_error_cb(requester, dns_resp);
554
555 /* we can move the requester the wait queue */
556 LIST_DEL(&requester->list);
557 LIST_ADDQ(&resolution->requester.wait, &requester->list);
558 }
559 goto next_packet;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200560 }
561
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200562 /* Now let's check the query's dname corresponds to the one we sent.
563 * We can check only the first query of the list. We send one query at a time
564 * so we get one query in the response */
Baptiste Assmann729c9012017-05-22 15:13:10 +0200565 query = LIST_NEXT(&resolution->response.query_list, struct dns_query_item *, list);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200566 if (query && memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
567 nameserver->counters.other += 1;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200568 /* now parse list of requesters currently waiting for this resolution */
569 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
570 requester->requester_error_cb(requester, DNS_RESP_WRONG_NAME);
571 /* we can move the requester the wait queue */
572 LIST_DEL(&requester->list);
573 LIST_ADDQ(&resolution->requester.wait, &requester->list);
574 }
575 goto next_packet;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200576 }
577
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200578 /* no errors, we can save the response in the cache */
579 if (dns_lru_tree) {
580 unsigned long long seed = 1;
581 struct chunk *buf = get_trash_chunk();
582 struct chunk *tmp = NULL;
583
584 chunk_reset(buf);
585 tmp = dns_cache_key(resolution->query_type, resolution->hostname_dn,
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200586 resolution->hostname_dn_len, buf);
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200587 if (!tmp) {
588 nameserver->counters.other += 1;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200589 /* now parse list of requesters currently waiting for this resolution */
590 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
591 requester->requester_error_cb(requester, DNS_RESP_ERROR);
592 /* we can move the requester the wait queue */
593 LIST_DEL(&requester->list);
594 LIST_ADDQ(&resolution->requester.wait, &requester->list);
595 }
596 goto next_packet;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200597 }
598
599 lru = lru64_get(XXH64(buf->str, buf->len, seed),
600 dns_lru_tree, nameserver->resolvers, 1);
601
602 lru64_commit(lru, resolution, nameserver->resolvers, 1, NULL);
603 }
604
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200605 if (resolution->status != RSLV_STATUS_VALID) {
606 resolution->status = RSLV_STATUS_VALID;
607 resolution->last_status_change = now_ms;
608 }
609
Baptiste Assmann37bb3722015-08-07 10:18:32 +0200610 nameserver->counters.valid += 1;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200611 /* now parse list of requesters currently waiting for this resolution */
612 tmpnameserver = nameserver;
613 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
614 requester->requester_cb(requester, tmpnameserver);
615 /* we can move the requester the wait queue */
616 LIST_DEL(&requester->list);
617 LIST_ADDQ(&resolution->requester.wait, &requester->list);
618 /* first response is managed by the server, others are from the cache */
619 tmpnameserver = NULL;
620 }
621
622 next_packet:
623 /* resolution may be NULL when we receive an ICMP unreachable packet */
624 if (resolution && LIST_ISEMPTY(&resolution->requester.curr)) {
625 /* move the resolution into the wait queue */
626 LIST_DEL(&resolution->list);
627 LIST_ADDQ(&resolvers->resolution.wait, &resolution->list);
628 /* update last resolution date and time */
629 resolution->last_resolution = now_ms;
630 /* reset current status flag */
631 resolution->step = RSLV_STEP_NONE;
632 /* reset values */
633 dns_reset_resolution(resolution);
634 }
635
636 } // end of while "packets" loop
637
638 dns_update_resolvers_timeout(nameserver->resolvers);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200639}
640
641/*
642 * function called when a resolvers network socket is ready to send data
643 * It performs the following actions:
644 */
645void dns_resolve_send(struct dgram_conn *dgram)
646{
647 int fd;
648 struct dns_nameserver *nameserver;
649 struct dns_resolvers *resolvers;
650 struct dns_resolution *resolution;
651
652 fd = dgram->t.sock.fd;
653
654 /* check if ready for sending */
655 if (!fd_send_ready(fd))
656 return;
657
658 /* we don't want/need to be waked up any more for sending */
659 fd_stop_send(fd);
660
661 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200662 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200663 return;
664
665 resolvers = nameserver->resolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200666 resolution = LIST_NEXT(&resolvers->resolution.curr, struct dns_resolution *, list);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200667
668 dns_send_query(resolution);
669 dns_update_resolvers_timeout(resolvers);
670}
671
672/*
673 * forge and send a DNS query to resolvers associated to a resolution
674 * It performs the following actions:
675 * returns:
676 * 0 in case of error or safe ignorance
677 * 1 if no error
678 */
679int dns_send_query(struct dns_resolution *resolution)
680{
Baptiste Assmann42746372017-05-03 12:12:02 +0200681 struct dns_resolvers *resolvers = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200682 struct dns_nameserver *nameserver;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200683 struct dns_requester *requester = NULL;
Erwan Velu5457eb42015-10-15 15:07:26 +0200684 int ret, bufsize, fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200685
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200686 /* nothing to do */
687 if (LIST_ISEMPTY(&resolution->requester.curr))
688 return 0;
689
690 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
691
692 switch (obj_type(requester->requester)) {
693 case OBJ_TYPE_SERVER:
694 resolvers = objt_server(requester->requester)->resolvers;
695 break;
696 case OBJ_TYPE_NONE:
697 default:
698 return 0;
699 }
Baptiste Assmann42746372017-05-03 12:12:02 +0200700
701 if (!resolvers)
702 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200703
Baptiste Assmann325137d2015-04-13 23:40:55 +0200704 bufsize = dns_build_query(resolution->query_id, resolution->query_type, resolution->hostname_dn,
705 resolution->hostname_dn_len, trash.str, trash.size);
706
707 if (bufsize == -1)
708 return 0;
709
710 list_for_each_entry(nameserver, &resolvers->nameserver_list, list) {
711 fd = nameserver->dgram->t.sock.fd;
712 errno = 0;
713
714 ret = send(fd, trash.str, bufsize, 0);
715
716 if (ret > 0)
717 nameserver->counters.sent += 1;
718
719 if (ret == 0 || errno == EAGAIN) {
720 /* nothing written, let's update the poller that we wanted to send
721 * but we were not able to */
722 fd_want_send(fd);
723 fd_cant_send(fd);
724 }
725 }
726
727 /* update resolution */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200728 resolution->nb_responses = 0;
729 resolution->last_sent_packet = now_ms;
730
731 return 1;
732}
733
734/*
735 * update a resolvers' task timeout for next wake up
736 */
737void dns_update_resolvers_timeout(struct dns_resolvers *resolvers)
738{
739 struct dns_resolution *resolution;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200740 struct dns_requester *requester;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200741
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200742 if ((LIST_ISEMPTY(&resolvers->resolution.curr)) && (LIST_ISEMPTY(&resolvers->resolution.wait))) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200743 resolvers->t->expire = TICK_ETERNITY;
744 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200745 else if (!LIST_ISEMPTY(&resolvers->resolution.curr)) {
746 resolution = LIST_NEXT(&resolvers->resolution.curr, struct dns_resolution *, list);
747 if (!resolvers->t->expire || tick_is_le(resolvers->t->expire, tick_add(resolution->last_sent_packet, resolvers->timeout.retry))) {
748 resolvers->t->expire = tick_add(resolution->last_sent_packet, resolvers->timeout.retry);
749 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200750 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200751 else if (!LIST_ISEMPTY(&resolvers->resolution.wait)) {
752 int valid_period, inter, need_wakeup;
753 struct dns_resolution *res_back;
754 need_wakeup = 0;
755 list_for_each_entry_safe(resolution, res_back, &resolvers->resolution.wait, list) {
756 valid_period = 0;
757 inter = 0;
758
759 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
760
761 switch (obj_type(requester->requester)) {
762 case OBJ_TYPE_SERVER:
763 valid_period = objt_server(requester->requester)->check.inter;
764 break;
765 case OBJ_TYPE_NONE:
766 default:
767 continue;
768 }
769
770 if (resolvers->hold.valid < valid_period)
771 inter = resolvers->hold.valid;
772 else
773 inter = valid_period;
774
775 if (tick_is_expired(tick_add(resolution->last_resolution, inter), now_ms)) {
776 switch (obj_type(requester->requester)) {
777 case OBJ_TYPE_SERVER:
778 dns_trigger_resolution(objt_server(requester->requester)->resolution);
779 break;
780 case OBJ_TYPE_NONE:
781 default:
782 ;;
783 }
784 }
785 else {
786 need_wakeup = 1;
787 }
788 }
789 /* in such case, we wake up in 1s */
790 if (need_wakeup) {
791 int r = 1000;
792
793 resolution = LIST_NEXT(&resolvers->resolution.wait, struct dns_resolution *, list);
794 if (tick_is_le(resolvers->t->expire, tick_add(now_ms, r)))
795 resolvers->t->expire = tick_add(now_ms, r);
796 resolvers->t->expire = tick_add(now_ms, 1000);
797 }
798 }
799
800 task_queue(resolvers->t);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200801}
802
803/*
804 * Analyse, re-build and copy the name <name> from the DNS response packet <buffer>.
805 * <name> must point to the 'data_len' information or pointer 'c0' for compressed data.
806 * The result is copied into <dest>, ensuring we don't overflow using <dest_len>
807 * Returns the number of bytes the caller can move forward. If 0 it means an error occured
808 * while parsing the name.
809 * <offset> is the number of bytes the caller could move forward.
810 */
811int dns_read_name(unsigned char *buffer, unsigned char *bufend, unsigned char *name, char *destination, int dest_len, int *offset)
812{
813 int nb_bytes = 0, n = 0;
814 int label_len;
815 unsigned char *reader = name;
816 char *dest = destination;
817
818 while (1) {
819 /* name compression is in use */
820 if ((*reader & 0xc0) == 0xc0) {
821 /* a pointer must point BEFORE current position */
822 if ((buffer + reader[1]) > reader) {
823 goto out_error;
824 }
825
826 n = dns_read_name(buffer, bufend, buffer + reader[1], dest, dest_len - nb_bytes, offset);
827 if (n == 0)
828 goto out_error;
829
830 dest += n;
831 nb_bytes += n;
832 goto out;
833 }
834
835 label_len = *reader;
836 if (label_len == 0)
837 goto out;
838 /* Check if:
839 * - we won't read outside the buffer
840 * - there is enough place in the destination
841 */
842 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
843 goto out_error;
844
845 /* +1 to take label len + label string */
846 label_len += 1;
847
848 memcpy(dest, reader, label_len);
849
850 dest += label_len;
851 nb_bytes += label_len;
852 reader += label_len;
853 }
854
855 out:
856 /* offset computation:
857 * parse from <name> until finding either NULL or a pointer "c0xx"
858 */
859 reader = name;
860 *offset = 0;
861 while (reader < bufend) {
862 if ((reader[0] & 0xc0) == 0xc0) {
863 *offset += 2;
864 break;
865 }
866 else if (*reader == 0) {
867 *offset += 1;
868 break;
869 }
870 *offset += 1;
871 ++reader;
872 }
873
874 return nb_bytes;
875
876 out_error:
877 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200878}
879
880/*
881 * Function to validate that the buffer DNS response provided in <resp> and
882 * finishing before <bufend> is valid from a DNS protocol point of view.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200883 *
Baptiste Assmann729c9012017-05-22 15:13:10 +0200884 * The result is stored in <resolution>' response, buf_response, response_query_records
885 * and response_answer_records members.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200886 *
887 * This function returns one of the DNS_RESP_* code to indicate the type of
888 * error found.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200889 */
Baptiste Assmann729c9012017-05-22 15:13:10 +0200890int dns_validate_dns_response(unsigned char *resp, unsigned char *bufend, struct dns_resolution *resolution)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200891{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200892 unsigned char *reader;
893 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
894 int len, flags, offset, ret;
895 int dns_query_record_id, dns_answer_record_id;
Baptiste Assmann69fce672017-05-04 08:37:45 +0200896 int nb_saved_records;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200897 struct dns_query_item *dns_query;
898 struct dns_answer_item *dns_answer_record;
Baptiste Assmann729c9012017-05-22 15:13:10 +0200899 struct dns_response_packet *dns_p;
900 struct chunk *dns_response_buffer;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200901
902 reader = resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200903 len = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200904 previous_dname = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200905
Baptiste Assmann729c9012017-05-22 15:13:10 +0200906 /* initialization of response buffer and structure */
907 dns_p = &resolution->response;
908 dns_response_buffer = &resolution->response_buffer;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200909 memset(dns_p, '\0', sizeof(struct dns_response_packet));
Baptiste Assmann729c9012017-05-22 15:13:10 +0200910 chunk_reset(dns_response_buffer);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200911
912 /* query id */
913 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200914 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200915 dns_p->header.id = reader[0] * 256 + reader[1];
916 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200917
918 /*
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200919 * flags and rcode are stored over 2 bytes
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200920 * First byte contains:
921 * - response flag (1 bit)
922 * - opcode (4 bits)
923 * - authoritative (1 bit)
924 * - truncated (1 bit)
925 * - recursion desired (1 bit)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200926 */
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200927 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200928 return DNS_RESP_INVALID;
929
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200930 flags = reader[0] * 256 + reader[1];
931
932 if (flags & DNS_FLAG_TRUNCATED)
933 return DNS_RESP_TRUNCATED;
934
935 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
936 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200937 return DNS_RESP_NX_DOMAIN;
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200938 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200939 return DNS_RESP_REFUSED;
940
941 return DNS_RESP_ERROR;
942 }
943
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200944 /* move forward 2 bytes for flags */
945 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200946
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200947 /* 2 bytes for question count */
948 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200949 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200950 dns_p->header.qdcount = reader[0] * 256 + reader[1];
951 /* (for now) we send one query only, so we expect only one in the response too */
952 if (dns_p->header.qdcount != 1)
953 return DNS_RESP_QUERY_COUNT_ERROR;
954 if (dns_p->header.qdcount > DNS_MAX_QUERY_RECORDS)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200955 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200956 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200957
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200958 /* 2 bytes for answer count */
959 if (reader + 2 >= bufend)
960 return DNS_RESP_INVALID;
961 dns_p->header.ancount = reader[0] * 256 + reader[1];
962 if (dns_p->header.ancount == 0)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200963 return DNS_RESP_ANCOUNT_ZERO;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200964 /* check if too many records are announced */
965 if (dns_p->header.ancount > DNS_MAX_ANSWER_RECORDS)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200966 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200967 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200968
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200969 /* 2 bytes authority count */
970 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200971 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200972 dns_p->header.nscount = reader[0] * 256 + reader[1];
973 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200974
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200975 /* 2 bytes additional count */
976 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200977 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200978 dns_p->header.arcount = reader[0] * 256 + reader[1];
979 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200980
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200981 /* parsing dns queries */
982 LIST_INIT(&dns_p->query_list);
983 for (dns_query_record_id = 0; dns_query_record_id < dns_p->header.qdcount; dns_query_record_id++) {
984 /* use next pre-allocated dns_query_item after ensuring there is
985 * still one available.
986 * It's then added to our packet query list.
987 */
988 if (dns_query_record_id > DNS_MAX_QUERY_RECORDS)
989 return DNS_RESP_INVALID;
Baptiste Assmann729c9012017-05-22 15:13:10 +0200990 dns_query = &resolution->response_query_records[dns_query_record_id];
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200991 LIST_ADDQ(&dns_p->query_list, &dns_query->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200992
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200993 /* name is a NULL terminated string in our case, since we have
994 * one query per response and the first one can't be compressed
995 * (using the 0x0c format)
996 */
997 offset = 0;
998 len = dns_read_name(resp, bufend, reader, dns_query->name, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200999
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001000 if (len == 0)
1001 return DNS_RESP_INVALID;
1002
1003 reader += offset;
1004 previous_dname = dns_query->name;
1005
1006 /* move forward 2 bytes for question type */
1007 if (reader + 2 >= bufend)
1008 return DNS_RESP_INVALID;
1009 dns_query->type = reader[0] * 256 + reader[1];
1010 reader += 2;
1011
1012 /* move forward 2 bytes for question class */
1013 if (reader + 2 >= bufend)
1014 return DNS_RESP_INVALID;
1015 dns_query->class = reader[0] * 256 + reader[1];
1016 reader += 2;
1017 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001018
1019 /* now parsing response records */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001020 LIST_INIT(&dns_p->answer_list);
Baptiste Assmann69fce672017-05-04 08:37:45 +02001021 nb_saved_records = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001022 for (dns_answer_record_id = 0; dns_answer_record_id < dns_p->header.ancount; dns_answer_record_id++) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001023 if (reader >= bufend)
1024 return DNS_RESP_INVALID;
1025
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001026 /* pull next response record from the list, if still one available, then add it
1027 * to the record list */
1028 if (dns_answer_record_id > DNS_MAX_ANSWER_RECORDS)
1029 return DNS_RESP_INVALID;
Baptiste Assmann729c9012017-05-22 15:13:10 +02001030 dns_answer_record = &resolution->response_answer_records[dns_answer_record_id];
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001031 LIST_ADDQ(&dns_p->answer_list, &dns_answer_record->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001032
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001033 offset = 0;
1034 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001035
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001036 if (len == 0)
1037 return DNS_RESP_INVALID;
1038
1039 /* check if the current record dname is valid.
1040 * previous_dname points either to queried dname or last CNAME target
1041 */
1042 if (memcmp(previous_dname, tmpname, len) != 0) {
1043 if (dns_answer_record_id == 0) {
1044 /* first record, means a mismatch issue between queried dname
1045 * and dname found in the first record */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001046 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001047 } else {
1048 /* if not the first record, this means we have a CNAME resolution
1049 * error */
1050 return DNS_RESP_CNAME_ERROR;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001051 }
1052
Baptiste Assmann325137d2015-04-13 23:40:55 +02001053 }
1054
Baptiste Assmann729c9012017-05-22 15:13:10 +02001055 dns_answer_record->name = chunk_newstr(dns_response_buffer);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001056 if (dns_answer_record->name == NULL)
1057 return DNS_RESP_INVALID;
Baptiste Assmann5d681ba2015-10-15 15:23:28 +02001058
Baptiste Assmann729c9012017-05-22 15:13:10 +02001059 ret = chunk_strncat(dns_response_buffer, tmpname, len);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001060 if (ret == 0)
1061 return DNS_RESP_INVALID;
Baptiste Assmann2359ff12015-08-07 11:24:05 +02001062
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001063 reader += offset;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001064 if (reader >= bufend)
1065 return DNS_RESP_INVALID;
1066
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001067 if (reader >= bufend)
1068 return DNS_RESP_INVALID;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001069
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001070 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001071 if (reader + 2 > bufend)
1072 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001073 dns_answer_record->type = reader[0] * 256 + reader[1];
1074 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001075
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001076 /* 2 bytes for class (2) */
1077 if (reader + 2 > bufend)
1078 return DNS_RESP_INVALID;
1079 dns_answer_record->class = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +02001080 reader += 2;
1081
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001082 /* 4 bytes for ttl (4) */
1083 if (reader + 4 > bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001084 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001085 dns_answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1086 + reader[2] * 256 + reader[3];
1087 reader += 4;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001088
1089 /* now reading data len */
1090 if (reader + 2 > bufend)
1091 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001092 dns_answer_record->data_len = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +02001093
1094 /* move forward 2 bytes for data len */
1095 reader += 2;
1096
1097 /* analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001098 switch (dns_answer_record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001099 case DNS_RTYPE_A:
1100 /* ipv4 is stored on 4 bytes */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001101 if (dns_answer_record->data_len != 4)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001102 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001103 dns_answer_record->address.sa_family = AF_INET;
1104 memcpy(&(((struct sockaddr_in *)&dns_answer_record->address)->sin_addr),
1105 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001106 break;
1107
1108 case DNS_RTYPE_CNAME:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001109 /* check if this is the last record and update the caller about the status:
1110 * no IP could be found and last record was a CNAME. Could be triggered
1111 * by a wrong query type
1112 *
1113 * + 1 because dns_answer_record_id starts at 0 while number of answers
1114 * is an integer and starts at 1.
1115 */
1116 if (dns_answer_record_id + 1 == dns_p->header.ancount)
1117 return DNS_RESP_CNAME_ERROR;
1118
1119 offset = 0;
1120 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
1121
1122 if (len == 0)
1123 return DNS_RESP_INVALID;
1124
Baptiste Assmann729c9012017-05-22 15:13:10 +02001125 dns_answer_record->target = chunk_newstr(dns_response_buffer);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001126 if (dns_answer_record->target == NULL)
1127 return DNS_RESP_INVALID;
1128
Baptiste Assmann729c9012017-05-22 15:13:10 +02001129 ret = chunk_strncat(dns_response_buffer, tmpname, len);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001130 if (ret == 0)
1131 return DNS_RESP_INVALID;
1132
1133 previous_dname = dns_answer_record->target;
1134
Baptiste Assmann325137d2015-04-13 23:40:55 +02001135 break;
1136
1137 case DNS_RTYPE_AAAA:
1138 /* ipv6 is stored on 16 bytes */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001139 if (dns_answer_record->data_len != 16)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001140 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001141 dns_answer_record->address.sa_family = AF_INET6;
1142 memcpy(&(((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr),
1143 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001144 break;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001145
Baptiste Assmann325137d2015-04-13 23:40:55 +02001146 } /* switch (record type) */
1147
Baptiste Assmann69fce672017-05-04 08:37:45 +02001148 /* increment the counter for number of records saved into our local response */
1149 nb_saved_records += 1;
1150
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001151 /* move forward dns_answer_record->data_len for analyzing next record in the response */
1152 reader += dns_answer_record->data_len;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001153 } /* for i 0 to ancount */
1154
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001155 /* let's add a last \0 to close our last string */
Baptiste Assmann729c9012017-05-22 15:13:10 +02001156 ret = chunk_strncat(dns_response_buffer, "\0", 1);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001157 if (ret == 0)
1158 return DNS_RESP_INVALID;
Baptiste Assmann96972bc2015-09-09 00:46:58 +02001159
Baptiste Assmann69fce672017-05-04 08:37:45 +02001160 /* save the number of records we really own */
1161 dns_p->header.ancount = nb_saved_records;
1162
Baptiste Assmann325137d2015-04-13 23:40:55 +02001163 return DNS_RESP_VALID;
1164}
1165
1166/*
1167 * search dn_name resolution in resp.
1168 * If existing IP not found, return the first IP matching family_priority,
1169 * otherwise, first ip found
1170 * The following tasks are the responsibility of the caller:
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001171 * - <dns_p> contains an error free DNS response
Baptiste Assmann325137d2015-04-13 23:40:55 +02001172 * For both cases above, dns_validate_dns_response is required
1173 * returns one of the DNS_UPD_* code
1174 */
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001175#define DNS_MAX_IP_REC 20
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001176int dns_get_ip_from_response(struct dns_response_packet *dns_p,
Baptiste Assmann42746372017-05-03 12:12:02 +02001177 struct dns_options *dns_opts, void *currentip,
Thierry Fournierada34842016-02-17 21:25:09 +01001178 short currentip_sin_family,
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001179 void **newip, short *newip_sin_family,
1180 void *owner)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001181{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001182 struct dns_answer_item *record;
Thierry Fournierada34842016-02-17 21:25:09 +01001183 int family_priority;
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001184 int i, currentip_found;
1185 unsigned char *newip4, *newip6;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001186 struct {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001187 void *ip;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001188 unsigned char type;
1189 } rec[DNS_MAX_IP_REC];
1190 int currentip_sel;
1191 int j;
1192 int rec_nb = 0;
1193 int score, max_score;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001194
Baptiste Assmann42746372017-05-03 12:12:02 +02001195 family_priority = dns_opts->family_prio;
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001196 *newip = newip4 = newip6 = NULL;
1197 currentip_found = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001198 *newip_sin_family = AF_UNSPEC;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001199
1200 /* now parsing response records */
Baptiste Assmann729c9012017-05-22 15:13:10 +02001201 list_for_each_entry(record, &dns_p->answer_list, list) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001202 /* analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001203 switch (record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001204 case DNS_RTYPE_A:
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001205 /* Store IPv4, only if some room is avalaible. */
1206 if (rec_nb < DNS_MAX_IP_REC) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001207 rec[rec_nb].ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001208 rec[rec_nb].type = AF_INET;
1209 rec_nb++;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001210 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001211 break;
1212
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001213 /* we're looking for IPs only. CNAME validation is done when
1214 * parsing the response buffer for the first time */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001215 case DNS_RTYPE_CNAME:
Baptiste Assmann325137d2015-04-13 23:40:55 +02001216 break;
1217
1218 case DNS_RTYPE_AAAA:
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001219 /* Store IPv6, only if some room is avalaible. */
1220 if (rec_nb < DNS_MAX_IP_REC) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001221 rec[rec_nb].ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001222 rec[rec_nb].type = AF_INET6;
1223 rec_nb++;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001224 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001225 break;
1226
Baptiste Assmann325137d2015-04-13 23:40:55 +02001227 } /* switch (record type) */
Baptiste Assmannbcbd4912016-04-18 19:42:57 +02001228 } /* list for each record entries */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001229
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001230 /* Select an IP regarding configuration preference.
1231 * Top priority is the prefered network ip version,
1232 * second priority is the prefered network.
1233 * the last priority is the currently used IP,
1234 *
1235 * For these three priorities, a score is calculated. The
1236 * weight are:
Baptistefc725902016-12-26 23:21:08 +01001237 * 8 - prefered netwok ip version.
1238 * 4 - prefered network.
1239 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001240 * 1 - current ip.
1241 * The result with the biggest score is returned.
1242 */
1243 max_score = -1;
1244 for (i = 0; i < rec_nb; i++) {
Baptistefc725902016-12-26 23:21:08 +01001245 int record_ip_already_affected = 0;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001246
1247 score = 0;
1248
1249 /* Check for prefered ip protocol. */
1250 if (rec[i].type == family_priority)
Baptistefc725902016-12-26 23:21:08 +01001251 score += 8;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001252
1253 /* Check for prefered network. */
Baptiste Assmann42746372017-05-03 12:12:02 +02001254 for (j = 0; j < dns_opts->pref_net_nb; j++) {
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001255
1256 /* Compare only the same adresses class. */
Baptiste Assmann42746372017-05-03 12:12:02 +02001257 if (dns_opts->pref_net[j].family != rec[i].type)
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001258 continue;
1259
1260 if ((rec[i].type == AF_INET &&
Willy Tarreaueec1d382016-07-13 11:59:39 +02001261 in_net_ipv4(rec[i].ip,
Baptiste Assmann42746372017-05-03 12:12:02 +02001262 &dns_opts->pref_net[j].mask.in4,
1263 &dns_opts->pref_net[j].addr.in4)) ||
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001264 (rec[i].type == AF_INET6 &&
Willy Tarreaueec1d382016-07-13 11:59:39 +02001265 in_net_ipv6(rec[i].ip,
Baptiste Assmann42746372017-05-03 12:12:02 +02001266 &dns_opts->pref_net[j].mask.in6,
1267 &dns_opts->pref_net[j].addr.in6))) {
Baptistefc725902016-12-26 23:21:08 +01001268 score += 4;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001269 break;
1270 }
1271 }
1272
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001273 /* Check if the IP found in the record is already affected to a member of a group.
1274 * If yes, the score should be incremented by 2.
1275 */
1276 if (owner) {
1277 if (snr_check_ip_callback(owner, rec[i].ip, &rec[i].type))
Baptistefc725902016-12-26 23:21:08 +01001278 record_ip_already_affected = 1;
Baptistefc725902016-12-26 23:21:08 +01001279 }
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001280 if (record_ip_already_affected == 0)
Baptistefc725902016-12-26 23:21:08 +01001281 score += 2;
1282
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001283 /* Check for current ip matching. */
1284 if (rec[i].type == currentip_sin_family &&
1285 ((currentip_sin_family == AF_INET &&
Willy Tarreaueec1d382016-07-13 11:59:39 +02001286 memcmp(rec[i].ip, currentip, 4) == 0) ||
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001287 (currentip_sin_family == AF_INET6 &&
1288 memcmp(rec[i].ip, currentip, 16) == 0))) {
1289 score += 1;
1290 currentip_sel = 1;
1291 } else
1292 currentip_sel = 0;
1293
Baptistefc725902016-12-26 23:21:08 +01001294
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001295 /* Keep the address if the score is better than the previous
Baptistefc725902016-12-26 23:21:08 +01001296 * score. The maximum score is 15, if this value is reached,
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001297 * we break the parsing. Implicitly, this score is reached
1298 * the ip selected is the current ip.
1299 */
1300 if (score > max_score) {
1301 if (rec[i].type == AF_INET)
1302 newip4 = rec[i].ip;
1303 else
1304 newip6 = rec[i].ip;
1305 currentip_found = currentip_sel;
Baptistefc725902016-12-26 23:21:08 +01001306 if (score == 15)
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001307 return DNS_UPD_NO;
1308 max_score = score;
1309 }
1310 }
1311
Baptiste Assmann0453a1d2015-09-09 00:51:08 +02001312 /* no IP found in the response */
1313 if (!newip4 && !newip6) {
1314 return DNS_UPD_NO_IP_FOUND;
1315 }
1316
Baptiste Assmann325137d2015-04-13 23:40:55 +02001317 /* case when the caller looks first for an IPv4 address */
1318 if (family_priority == AF_INET) {
1319 if (newip4) {
1320 *newip = newip4;
1321 *newip_sin_family = AF_INET;
1322 if (currentip_found == 1)
1323 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001324 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001325 }
1326 else if (newip6) {
1327 *newip = newip6;
1328 *newip_sin_family = AF_INET6;
1329 if (currentip_found == 1)
1330 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001331 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001332 }
1333 }
1334 /* case when the caller looks first for an IPv6 address */
1335 else if (family_priority == AF_INET6) {
1336 if (newip6) {
1337 *newip = newip6;
1338 *newip_sin_family = AF_INET6;
1339 if (currentip_found == 1)
1340 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001341 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001342 }
1343 else if (newip4) {
1344 *newip = newip4;
1345 *newip_sin_family = AF_INET;
1346 if (currentip_found == 1)
1347 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001348 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001349 }
1350 }
1351 /* case when the caller have no preference (we prefer IPv6) */
1352 else if (family_priority == AF_UNSPEC) {
1353 if (newip6) {
1354 *newip = newip6;
1355 *newip_sin_family = AF_INET6;
1356 if (currentip_found == 1)
1357 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001358 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001359 }
1360 else if (newip4) {
1361 *newip = newip4;
1362 *newip_sin_family = AF_INET;
1363 if (currentip_found == 1)
1364 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001365 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001366 }
1367 }
1368
1369 /* no reason why we should change the server's IP address */
1370 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001371
1372 return_DNS_UPD_SRVIP_NOT_FOUND:
1373 list_for_each_entry(record, &dns_p->answer_list, list) {
1374 /* move the first record to the end of the list, for internal round robin */
1375 if (record) {
1376 LIST_DEL(&record->list);
1377 LIST_ADDQ(&dns_p->answer_list, &record->list);
1378 break;
1379 }
1380 }
1381 return DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001382}
1383
1384/*
1385 * returns the query id contained in a DNS response
1386 */
Thiago Farinab1af23e2016-01-20 23:46:34 +01001387unsigned short dns_response_get_query_id(unsigned char *resp)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001388{
1389 /* read the query id from the response */
1390 return resp[0] * 256 + resp[1];
1391}
1392
1393/*
1394 * used during haproxy's init phase
1395 * parses resolvers sections and initializes:
1396 * - task (time events) for each resolvers section
1397 * - the datagram layer (network IO events) for each nameserver
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001398 * It takes one argument:
1399 * - close_first takes 2 values: 0 or 1. If 1, the connection is closed first.
Baptiste Assmann325137d2015-04-13 23:40:55 +02001400 * returns:
1401 * 0 in case of error
1402 * 1 when no error
1403 */
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001404int dns_init_resolvers(int close_socket)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001405{
1406 struct dns_resolvers *curr_resolvers;
1407 struct dns_nameserver *curnameserver;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001408 struct dns_resolution *resolution, *res_back;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001409 struct dgram_conn *dgram;
1410 struct task *t;
1411 int fd;
1412
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02001413 /* initialize our DNS resolution cache */
1414 dns_lru_tree = lru64_new(dns_cache_size);
1415
Baptiste Assmann325137d2015-04-13 23:40:55 +02001416 /* give a first random value to our dns query_id seed */
1417 dns_query_id_seed = random();
1418
1419 /* run through the resolvers section list */
1420 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
1421 /* create the task associated to the resolvers section */
1422 if ((t = task_new()) == NULL) {
1423 Alert("Starting [%s] resolvers: out of memory.\n", curr_resolvers->id);
1424 return 0;
1425 }
1426
1427 /* update task's parameters */
1428 t->process = dns_process_resolve;
1429 t->context = curr_resolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001430 t->expire = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001431
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001432 /* no need to keep the new task if one is already affected to our resolvers
1433 * section */
1434 if (!curr_resolvers->t)
1435 curr_resolvers->t = t;
1436 else
1437 task_free(t);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001438
1439 list_for_each_entry(curnameserver, &curr_resolvers->nameserver_list, list) {
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001440 dgram = NULL;
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001441
1442 if (close_socket == 1) {
1443 if (curnameserver->dgram) {
Frédéric Lécaille64920532017-05-12 09:57:15 +02001444 fd_delete(curnameserver->dgram->t.sock.fd);
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001445 memset(curnameserver->dgram, '\0', sizeof(*dgram));
1446 dgram = curnameserver->dgram;
1447 }
1448 }
1449
1450 /* allocate memory only if it has not already been allocated
1451 * by a previous call to this function */
1452 if (!dgram && (dgram = calloc(1, sizeof(*dgram))) == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001453 Alert("Starting [%s/%s] nameserver: out of memory.\n", curr_resolvers->id,
1454 curnameserver->id);
1455 return 0;
1456 }
1457 /* update datagram's parameters */
1458 dgram->owner = (void *)curnameserver;
1459 dgram->data = &resolve_dgram_cb;
1460
1461 /* create network UDP socket for this nameserver */
Frédéric Lécaille5e5bc9f2017-04-11 08:46:37 +02001462 if ((fd = socket(curnameserver->addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001463 Alert("Starting [%s/%s] nameserver: can't create socket.\n", curr_resolvers->id,
1464 curnameserver->id);
1465 free(dgram);
1466 dgram = NULL;
1467 return 0;
1468 }
1469
1470 /* "connect" the UDP socket to the name server IP */
Baptiste Assmann8c62c472015-09-21 20:55:08 +02001471 if (connect(fd, (struct sockaddr*)&curnameserver->addr, get_addr_len(&curnameserver->addr)) == -1) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001472 Alert("Starting [%s/%s] nameserver: can't connect socket.\n", curr_resolvers->id,
1473 curnameserver->id);
1474 close(fd);
1475 free(dgram);
1476 dgram = NULL;
1477 return 0;
1478 }
1479
1480 /* make the socket non blocking */
1481 fcntl(fd, F_SETFL, O_NONBLOCK);
1482
1483 /* add the fd in the fd list and update its parameters */
1484 fd_insert(fd);
1485 fdtab[fd].owner = dgram;
1486 fdtab[fd].iocb = dgram_fd_handler;
1487 fd_want_recv(fd);
1488 dgram->t.sock.fd = fd;
1489
1490 /* update nameserver's datagram property */
1491 curnameserver->dgram = dgram;
1492
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001493 continue;
1494 }
1495
1496 if (close_socket == 0)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001497 continue;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001498
1499 /* now, we can trigger DNS resolution */
1500 list_for_each_entry_safe(resolution, res_back, &curr_resolvers->resolution.wait, list) {
1501 /* if there is no requester in the wait queue, no need to trigger the resolution */
1502 if (LIST_ISEMPTY(&resolution->requester.wait))
1503 continue;
1504
1505 dns_trigger_resolution(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001506 }
1507
1508 /* task can be queued */
1509 task_queue(t);
1510 }
1511
1512 return 1;
1513}
1514
1515/*
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001516 * Allocate a pool of resolution to a resolvers section.
1517 * Each resolution is associated with a UUID.
1518 *
1519 * Return code:
1520 * - 0 if everything went smoothly
1521 * - -1 if an error occured
1522 */
1523int dns_alloc_resolution_pool(struct dns_resolvers *resolvers)
1524{
1525 int i;
1526 struct dns_resolution *resolution;
1527
1528 /* return if a pool has already been set for this resolvers */
1529 if (!LIST_ISEMPTY(&resolvers->resolution.pool)) {
1530 return 0;
1531 }
1532
1533 for (i = 0; i < resolvers->resolution_pool_size; i++) {
1534 resolution = dns_alloc_resolution();
1535 if (!resolution) {
1536 Alert("Starting [%s] resolvers: can't allocate memory for DNS resolution pool.\n", resolvers->id);
1537 return -1;
1538 }
1539 resolution->uuid = i;
1540 LIST_ADDQ(&resolvers->resolution.pool, &resolution->list);
1541 }
1542
1543 return 0;
1544}
1545
1546/*
Baptiste Assmann325137d2015-04-13 23:40:55 +02001547 * Forge a DNS query. It needs the following information from the caller:
1548 * - <query_id>: the DNS query id corresponding to this query
1549 * - <query_type>: DNS_RTYPE_* request DNS record type (A, AAAA, ANY, etc...)
1550 * - <hostname_dn>: hostname in domain name format
1551 * - <hostname_dn_len>: length of <hostname_dn>
1552 * To store the query, the caller must pass a buffer <buf> and its size <bufsize>
1553 *
1554 * the DNS query is stored in <buf>
1555 * returns:
1556 * -1 if <buf> is too short
1557 */
1558int dns_build_query(int query_id, int query_type, char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
1559{
1560 struct dns_header *dns;
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001561 struct dns_question qinfo;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001562 char *ptr, *bufend;
1563
1564 memset(buf, '\0', bufsize);
1565 ptr = buf;
1566 bufend = buf + bufsize;
1567
1568 /* check if there is enough room for DNS headers */
1569 if (ptr + sizeof(struct dns_header) >= bufend)
1570 return -1;
1571
1572 /* set dns query headers */
1573 dns = (struct dns_header *)ptr;
1574 dns->id = (unsigned short) htons(query_id);
Nenad Merdanovic8ab79422016-07-13 14:03:43 +02001575 dns->flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001576 dns->qdcount = htons(1); /* 1 question */
1577 dns->ancount = 0;
1578 dns->nscount = 0;
1579 dns->arcount = 0;
1580
1581 /* move forward ptr */
1582 ptr += sizeof(struct dns_header);
1583
1584 /* check if there is enough room for query hostname */
1585 if ((ptr + hostname_dn_len) >= bufend)
1586 return -1;
1587
1588 /* set up query hostname */
1589 memcpy(ptr, hostname_dn, hostname_dn_len);
1590 ptr[hostname_dn_len + 1] = '\0';
1591
1592 /* move forward ptr */
1593 ptr += (hostname_dn_len + 1);
1594
1595 /* check if there is enough room for query hostname*/
1596 if (ptr + sizeof(struct dns_question) >= bufend)
1597 return -1;
1598
1599 /* set up query info (type and class) */
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001600 qinfo.qtype = htons(query_type);
1601 qinfo.qclass = htons(DNS_RCLASS_IN);
1602 memcpy(ptr, &qinfo, sizeof(qinfo));
Baptiste Assmann325137d2015-04-13 23:40:55 +02001603
1604 ptr += sizeof(struct dns_question);
1605
1606 return ptr - buf;
1607}
1608
1609/*
1610 * turn a string into domain name label:
1611 * www.haproxy.org into 3www7haproxy3org
1612 * if dn memory is pre-allocated, you must provide its size in dn_len
1613 * if dn memory isn't allocated, dn_len must be set to 0.
1614 * In the second case, memory will be allocated.
1615 * in case of error, -1 is returned, otherwise, number of bytes copied in dn
1616 */
Willy Tarreau2100b492015-07-22 16:42:43 +02001617char *dns_str_to_dn_label(const char *string, char *dn, int dn_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001618{
1619 char *c, *d;
1620 int i, offset;
1621
1622 /* offset between string size and theorical dn size */
1623 offset = 1;
1624
1625 /*
1626 * first, get the size of the string turned into its domain name version
1627 * This function also validates the string respect the RFC
1628 */
1629 if ((i = dns_str_to_dn_label_len(string)) == -1)
1630 return NULL;
1631
1632 /* yes, so let's check there is enough memory */
1633 if (dn_len < i + offset)
1634 return NULL;
1635
Willy Tarreaud69d6f32015-07-22 16:45:36 +02001636 i = strlen(string);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001637 memcpy(dn + offset, string, i);
1638 dn[i + offset] = '\0';
1639 /* avoid a '\0' at the beginning of dn string which may prevent the for loop
1640 * below from working.
1641 * Actually, this is the reason of the offset. */
1642 dn[0] = '0';
1643
1644 for (c = dn; *c ; ++c) {
1645 /* c points to the first '0' char or a dot, which we don't want to read */
1646 d = c + offset;
1647 i = 0;
1648 while (*d != '.' && *d) {
1649 i++;
1650 d++;
1651 }
1652 *c = i;
1653
1654 c = d - 1; /* because of c++ of the for loop */
1655 }
1656
1657 return dn;
1658}
1659
1660/*
1661 * compute and return the length of <string> it it were translated into domain name
1662 * label:
1663 * www.haproxy.org into 3www7haproxy3org would return 16
1664 * NOTE: add +1 for '\0' when allocating memory ;)
1665 */
1666int dns_str_to_dn_label_len(const char *string)
1667{
1668 return strlen(string) + 1;
1669}
1670
1671/*
1672 * validates host name:
1673 * - total size
1674 * - each label size individually
1675 * returns:
1676 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1677 * 1 when no error. <err> is left unaffected.
1678 */
1679int dns_hostname_validation(const char *string, char **err)
1680{
1681 const char *c, *d;
1682 int i;
1683
1684 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1685 if (err)
1686 *err = DNS_TOO_LONG_FQDN;
1687 return 0;
1688 }
1689
1690 c = string;
1691 while (*c) {
1692 d = c;
1693
1694 i = 0;
1695 while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) {
1696 i++;
1697 if (!((*d == '-') || (*d == '_') ||
1698 ((*d >= 'a') && (*d <= 'z')) ||
1699 ((*d >= 'A') && (*d <= 'Z')) ||
1700 ((*d >= '0') && (*d <= '9')))) {
1701 if (err)
1702 *err = DNS_INVALID_CHARACTER;
1703 return 0;
1704 }
1705 d++;
1706 }
1707
1708 if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) {
1709 if (err)
1710 *err = DNS_LABEL_TOO_LONG;
1711 return 0;
1712 }
1713
1714 if (*d == '\0')
1715 goto out;
1716
1717 c = ++d;
1718 }
1719 out:
1720 return 1;
1721}
1722
1723/*
1724 * 2 bytes random generator to generate DNS query ID
1725 */
1726uint16_t dns_rnd16(void)
1727{
1728 dns_query_id_seed ^= dns_query_id_seed << 13;
1729 dns_query_id_seed ^= dns_query_id_seed >> 7;
1730 dns_query_id_seed ^= dns_query_id_seed << 17;
1731 return dns_query_id_seed;
1732}
1733
1734
1735/*
1736 * function called when a timeout occurs during name resolution process
1737 * if max number of tries is reached, then stop, otherwise, retry.
1738 */
1739struct task *dns_process_resolve(struct task *t)
1740{
1741 struct dns_resolvers *resolvers = t->context;
1742 struct dns_resolution *resolution, *res_back;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001743 int res_preferred_afinet, res_preferred_afinet6;
Baptiste Assmann42746372017-05-03 12:12:02 +02001744 struct dns_options *dns_opts = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001745
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001746 /* if both there is no resolution in the run queue, we can re-schedule a wake up */
1747 if (LIST_ISEMPTY(&resolvers->resolution.curr)) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001748 /* no first entry, so wake up was useless */
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001749 dns_update_resolvers_timeout(resolvers);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001750 return t;
1751 }
1752
1753 /* look for the first resolution which is not expired */
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001754 list_for_each_entry_safe(resolution, res_back, &resolvers->resolution.curr, list) {
1755 struct dns_requester *requester = NULL;
1756
Baptiste Assmann325137d2015-04-13 23:40:55 +02001757 /* when we find the first resolution in the future, then we can stop here */
1758 if (tick_is_le(now_ms, resolution->last_sent_packet))
1759 goto out;
1760
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001761 if (LIST_ISEMPTY(&resolution->requester.curr))
1762 goto out;
1763
Baptiste Assmann325137d2015-04-13 23:40:55 +02001764 /*
1765 * if current resolution has been tried too many times and finishes in timeout
1766 * we update its status and remove it from the list
1767 */
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001768 if (resolution->try <= 0) {
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001769 struct dns_requester *tmprequester;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001770 /* clean up resolution information and remove from the list */
1771 dns_reset_resolution(resolution);
1772
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001773 LIST_DEL(&resolution->list);
1774 LIST_ADDQ(&resolvers->resolution.wait, &resolution->list);
1775
1776 if (resolution->status != RSLV_STATUS_TIMEOUT) {
1777 resolution->status = RSLV_STATUS_TIMEOUT;
1778 resolution->last_status_change = now_ms;
1779 }
1780
1781 /* notify the result to the requesters */
1782 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
1783 requester->requester_error_cb(requester, DNS_RESP_TIMEOUT);
1784 LIST_DEL(&requester->list);
1785 LIST_ADDQ(&resolution->requester.wait, &requester->list);
1786 }
Baptiste Assmann382824c2016-01-06 01:53:46 +01001787 goto out;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001788 }
1789
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001790 resolution->try -= 1;
1791
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001792 /* running queue is empty, nothing to do but wait */
1793 if (LIST_ISEMPTY(&resolution->requester.curr))
1794 goto out;
1795
1796 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
1797
1798 switch (obj_type(requester->requester)) {
1799 case OBJ_TYPE_SERVER:
1800 dns_opts = &(objt_server(requester->requester)->dns_opts);
1801 break;
1802
1803 case OBJ_TYPE_NONE:
1804 default:
1805 /* clean up resolution information and remove from the list */
1806 dns_reset_resolution(resolution);
1807
1808 LIST_DEL(&resolution->list);
1809 LIST_ADDQ(&resolvers->resolution.wait, &resolution->list);
1810
1811 /* notify the result to the requester */
1812 requester->requester_error_cb(requester, DNS_RESP_INTERNAL);
1813 goto out;
1814 }
Baptiste Assmann42746372017-05-03 12:12:02 +02001815
1816 res_preferred_afinet = dns_opts->family_prio == AF_INET && resolution->query_type == DNS_RTYPE_A;
1817 res_preferred_afinet6 = dns_opts->family_prio == AF_INET6 && resolution->query_type == DNS_RTYPE_AAAA;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001818
1819 /* let's change the query type if needed */
1820 if (res_preferred_afinet6) {
1821 /* fallback from AAAA to A */
1822 resolution->query_type = DNS_RTYPE_A;
1823 }
1824 else if (res_preferred_afinet) {
1825 /* fallback from A to AAAA */
1826 resolution->query_type = DNS_RTYPE_AAAA;
1827 }
1828
Baptiste Assmann382824c2016-01-06 01:53:46 +01001829 /* resend the DNS query */
1830 dns_send_query(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001831
Baptiste Assmann382824c2016-01-06 01:53:46 +01001832 /* check if we have more than one resolution in the list */
1833 if (dns_check_resolution_queue(resolvers) > 1) {
1834 /* move the rsolution to the end of the list */
1835 LIST_DEL(&resolution->list);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001836 LIST_ADDQ(&resolvers->resolution.curr, &resolution->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001837 }
1838 }
1839
1840 out:
1841 dns_update_resolvers_timeout(resolvers);
1842 return t;
1843}
William Lallemand69e96442016-11-19 00:58:54 +01001844
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02001845/*
1846 * build a dns cache key composed as follow:
1847 * <query type>#<hostname in domain name format>
1848 * and store it into <str>.
1849 * It's up to the caller to allocate <buf> and to reset it.
1850 * The function returns NULL in case of error (IE <buf> too small) or a pointer
1851 * to buf if successful
1852 */
1853struct chunk *
1854dns_cache_key(int query_type, char *hostname_dn, int hostname_dn_len, struct chunk *buf)
1855{
1856 int len, size;
1857 char *str;
1858
1859 str = buf->str;
1860 len = buf->len;
1861 size = buf->size;
1862
1863 switch (query_type) {
1864 case DNS_RTYPE_A:
1865 if (len + 1 > size)
1866 return NULL;
1867 memcpy(&str[len], "A", 1);
1868 len += 1;
1869 break;
1870 case DNS_RTYPE_AAAA:
1871 if (len + 4 > size)
1872 return NULL;
1873 memcpy(&str[len], "AAAA", 4);
1874 len += 4;
1875 break;
1876 default:
1877 return NULL;
1878 }
1879
1880 if (len + 1 > size)
1881 return NULL;
1882 memcpy(&str[len], "#", 1);
1883 len += 1;
1884
1885 if (len + hostname_dn_len + 1 > size) // +1 for trailing zero
1886 return NULL;
1887 memcpy(&str[len], hostname_dn, hostname_dn_len);
1888 len += hostname_dn_len;
1889 str[len] = '\0';
1890
1891 return buf;
1892}
1893
1894/*
1895 * returns a pointer to a cache entry which may still be considered as up to date
1896 * by the caller.
1897 * returns NULL if no entry can be found or if the data found is outdated.
1898 */
1899struct lru64 *
1900dns_cache_lookup(int query_type, char *hostname_dn, int hostname_dn_len, int valid_period, void *cache_domain) {
1901 struct lru64 *elem = NULL;
1902 struct dns_resolution *resolution = NULL;
1903 struct dns_resolvers *resolvers = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001904 struct dns_requester *requester = NULL;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02001905 int inter = 0;
1906 struct chunk *buf = get_trash_chunk();
1907 struct chunk *tmp = NULL;
1908
1909 if (!dns_lru_tree)
1910 return NULL;
1911
1912 chunk_reset(buf);
1913 tmp = dns_cache_key(query_type, hostname_dn, hostname_dn_len, buf);
1914 if (tmp == NULL)
1915 return NULL;
1916
1917 elem = lru64_lookup(XXH64(buf->str, buf->len, 1), dns_lru_tree, cache_domain, 1);
1918
1919 if (!elem || !elem->data)
1920 return NULL;
1921
1922 resolution = elem->data;
1923
1924 /* since we can change the fqdn of a server at run time, it may happen that
1925 * we got an innacurate elem.
1926 * This is because resolution->hostname_dn points to (owner)->hostname_dn (which
1927 * may be changed at run time)
1928 */
1929 if ((hostname_dn_len == resolution->hostname_dn_len) &&
1930 (memcmp(hostname_dn, resolution->hostname_dn, hostname_dn_len) != 0)) {
1931 return NULL;
1932 }
1933
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001934 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
1935
1936 switch (obj_type(requester->requester)) {
1937 case OBJ_TYPE_SERVER:
1938 resolvers = objt_server(requester->requester)->resolvers;
1939 break;
1940 case OBJ_TYPE_NONE:
1941 default:
1942 return NULL;
1943 }
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02001944
1945 if (!resolvers)
1946 return NULL;
1947
1948 if (resolvers->hold.valid < valid_period)
1949 inter = resolvers->hold.valid;
1950 else
1951 inter = valid_period;
1952
1953 if (!tick_is_expired(tick_add(resolution->last_resolution, inter), now_ms))
1954 return elem;
1955
1956 return NULL;
1957}
1958
Willy Tarreau777b5602016-12-16 18:06:26 +01001959/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
William Lallemand69e96442016-11-19 00:58:54 +01001960static int cli_parse_stat_resolvers(char **args, struct appctx *appctx, void *private)
1961{
1962 struct dns_resolvers *presolvers;
1963
1964 if (*args[3]) {
William Lallemand69e96442016-11-19 00:58:54 +01001965 list_for_each_entry(presolvers, &dns_resolvers, list) {
1966 if (strcmp(presolvers->id, args[3]) == 0) {
Willy Tarreau777b5602016-12-16 18:06:26 +01001967 appctx->ctx.cli.p0 = presolvers;
William Lallemand69e96442016-11-19 00:58:54 +01001968 break;
1969 }
1970 }
Willy Tarreau777b5602016-12-16 18:06:26 +01001971 if (appctx->ctx.cli.p0 == NULL) {
William Lallemand69e96442016-11-19 00:58:54 +01001972 appctx->ctx.cli.msg = "Can't find that resolvers section\n";
Willy Tarreau3b6e5472016-11-24 15:53:53 +01001973 appctx->st0 = CLI_ST_PRINT;
William Lallemand69e96442016-11-19 00:58:54 +01001974 return 1;
1975 }
1976 }
Willy Tarreau3067bfa2016-12-05 14:50:15 +01001977 return 0;
William Lallemand69e96442016-11-19 00:58:54 +01001978}
1979
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001980/*
1981 * if <resolution> is provided, then the function skips the memory allocation part.
1982 * It does the linking only.
1983 *
1984 * if <resolution> is NULL, the function links a dns resolution to a requester:
1985 * - it allocates memory for the struct requester used to link
1986 * the resolution to the requester
1987 * - it configures the resolution if this is the first requester to be linked to it
1988 * - it updates the requester with a pointer to the resolution
1989 *
1990 * Return code:
1991 * - 0 if everything happened smoothly
1992 * - -1 if an error occured. Of course, no resolution is linked to the requester
1993 */
1994int dns_link_resolution(void *requester, int requester_type, struct dns_resolution *resolution)
1995{
1996 struct dns_resolution *tmpresolution = NULL;
1997 struct dns_requester *tmprequester = NULL;
1998 struct dns_resolvers *resolvers = NULL;
1999 char *hostname_dn = NULL;
2000 int new_resolution;
2001
2002 if (!resolution) {
2003 tmprequester = calloc(1, sizeof(*tmprequester));
2004 if (!tmprequester)
2005 return -1;
2006
2007 switch (requester_type) {
2008 case OBJ_TYPE_SERVER:
2009 tmprequester->requester = &((struct server *)requester)->obj_type;
2010 hostname_dn = objt_server(tmprequester->requester)->hostname_dn;
2011 resolvers = objt_server(tmprequester->requester)->resolvers;
2012 switch (objt_server(tmprequester->requester)->dns_opts.family_prio) {
2013 case AF_INET:
2014 tmprequester->prefered_query_type = DNS_RTYPE_A;
2015 break;
2016 default:
2017 tmprequester->prefered_query_type = DNS_RTYPE_AAAA;
2018 }
2019
2020 break;
2021 case OBJ_TYPE_NONE:
2022 default:
2023 free(tmprequester);
2024 return -1;
2025 }
2026
2027 /* get a resolution from the resolvers' wait queue or pool */
2028 tmpresolution = dns_resolution_list_get(resolvers, hostname_dn, tmprequester->prefered_query_type);
2029 if (!tmpresolution) {
2030 free(tmprequester);
2031 return -1;
2032 }
2033 }
2034 else {
2035 tmpresolution = resolution;
2036
2037 switch (requester_type) {
2038 case OBJ_TYPE_SERVER:
2039 tmprequester = ((struct server *)requester)->dns_requester;
2040 resolvers = ((struct server *)requester)->resolvers;
2041 break;
2042 case OBJ_TYPE_NONE:
2043 default:
2044 return -1;
2045 }
2046 }
2047
2048 /* flag this resolution as NEW if applicable (not already linked to any requester).
2049 * this is required to decide which parameters we have to update on the resolution.
2050 * If new, it means we pulled up the resolution from the resolvers' pool.
2051 */
2052 if (LIST_ISEMPTY(&tmpresolution->requester.wait)) {
2053 new_resolution = 1;
2054 }
2055 else
2056 new_resolution = 0;
2057
2058 /* those parameters are related to the requester type */
2059 switch (obj_type(tmprequester->requester)) {
2060 case OBJ_TYPE_SERVER:
2061 /* some parameters should be set only if the resolution is brand new */
2062 if (new_resolution) {
2063 tmpresolution->query_type = tmprequester->prefered_query_type;
2064 tmpresolution->hostname_dn = objt_server(tmprequester->requester)->hostname_dn;
2065 tmpresolution->hostname_dn_len = objt_server(tmprequester->requester)->hostname_dn_len;
2066 }
2067
2068 /* update requester as well, only if we just allocated it */
2069 objt_server(tmprequester->requester)->resolution = tmpresolution;
2070 if (!resolution) {
2071 tmprequester->requester_cb = snr_resolution_cb;
2072 tmprequester->requester_error_cb = snr_resolution_error_cb;
2073 objt_server(tmprequester->requester)->dns_requester = tmprequester;
2074 }
2075 break;
2076 case OBJ_TYPE_NONE:
2077 default:
2078 free(tmprequester);
2079 return -1;
2080 }
2081
2082 /* update some parameters only if this is a brand new resolution */
2083 if (new_resolution) {
2084 /* move the resolution to the requesters' wait queue */
2085 LIST_DEL(&tmpresolution->list);
2086 LIST_ADDQ(&resolvers->resolution.wait, &tmpresolution->list);
2087
2088 tmpresolution->status = RSLV_STATUS_NONE;
2089 tmpresolution->step = RSLV_STEP_NONE;
2090 tmpresolution->revision = 1;
2091 }
2092
2093 /* add the requester to the resolution's wait queue */
2094 if (resolution)
2095 LIST_DEL(&tmprequester->list);
2096 LIST_ADDQ(&tmpresolution->requester.wait, &tmprequester->list);
2097
2098 return 0;
2099}
2100
2101/*
2102 * pick up an available resolution from the different resolution list associated to a resolvers section,
2103 * in this order:
2104 * 1. check in resolution.curr for the same hostname and query_type
2105 * 2. check in resolution.wait for the same hostname and query_type
2106 * 3. take an available resolution from resolution.pool
2107 *
2108 * return an available resolution, NULL if none found.
2109 */
2110struct dns_resolution *dns_resolution_list_get(struct dns_resolvers *resolvers, char *hostname_dn, int query_type)
2111{
2112 struct dns_resolution *resolution, *tmpresolution;
2113 struct dns_requester *requester;
2114
2115 /* search for same hostname and query type in resolution.curr */
2116 list_for_each_entry_safe(resolution, tmpresolution, &resolvers->resolution.curr, list) {
2117 requester = NULL;
2118
2119 if (!LIST_ISEMPTY(&resolution->requester.wait))
2120 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
2121 else if (!LIST_ISEMPTY(&resolution->requester.curr))
2122 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
2123
2124 if (!requester)
2125 continue;
2126
2127 if ((query_type == requester->prefered_query_type) &&
2128 (strcmp(hostname_dn, resolution->hostname_dn) == 0)) {
2129 return resolution;
2130 }
2131 }
2132
2133 /* search for same hostname and query type in resolution.wait */
2134 list_for_each_entry_safe(resolution, tmpresolution, &resolvers->resolution.wait, list) {
2135 requester = NULL;
2136
2137 if (!LIST_ISEMPTY(&resolution->requester.wait))
2138 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
2139 else if (!LIST_ISEMPTY(&resolution->requester.curr))
2140 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
2141
2142 if (!requester)
2143 continue;
2144
2145 if ((query_type == requester->prefered_query_type) &&
2146 (strcmp(hostname_dn, resolution->hostname_dn) == 0)) {
2147 return resolution;
2148 }
2149 }
2150
2151 /* take the first one (hopefully) from the pool */
2152 list_for_each_entry_safe(resolution, tmpresolution, &resolvers->resolution.pool, list) {
2153 if (LIST_ISEMPTY(&resolution->requester.wait)) {
2154 return resolution;
2155 }
2156 }
2157
2158 return NULL;
2159}
2160
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002161/* This function allocates memory for a DNS resolution structure.
2162 * It's up to the caller to set the parameters
2163 * Returns a pointer to the structure resolution or NULL if memory could
2164 * not be allocated.
2165 */
2166struct dns_resolution *dns_alloc_resolution(void)
2167{
2168 struct dns_resolution *resolution = NULL;
Baptiste Assmann729c9012017-05-22 15:13:10 +02002169 char *buffer = NULL;
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002170
2171 resolution = calloc(1, sizeof(*resolution));
Baptiste Assmann729c9012017-05-22 15:13:10 +02002172 buffer = calloc(1, global.tune.bufsize);
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002173
Baptiste Assmann729c9012017-05-22 15:13:10 +02002174 if (!resolution || !buffer) {
2175 free(buffer);
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002176 free(resolution);
2177 return NULL;
2178 }
2179
Baptiste Assmann729c9012017-05-22 15:13:10 +02002180 chunk_init(&resolution->response_buffer, buffer, global.tune.bufsize);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002181 LIST_INIT(&resolution->requester.wait);
2182 LIST_INIT(&resolution->requester.curr);
Baptiste Assmann729c9012017-05-22 15:13:10 +02002183
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002184 return resolution;
2185}
2186
2187/* This function free the memory allocated to a DNS resolution */
2188void dns_free_resolution(struct dns_resolution *resolution)
2189{
Baptiste Assmann729c9012017-05-22 15:13:10 +02002190 chunk_destroy(&resolution->response_buffer);
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002191 free(resolution);
2192
2193 return;
2194}
2195
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002196/* this function free a resolution from its requester(s) and move it back to the pool */
2197void dns_resolution_free(struct dns_resolvers *resolvers, struct dns_resolution *resolution)
2198{
2199 struct dns_requester *requester, *tmprequester;
2200
2201 /* clean up configuration */
2202 dns_reset_resolution(resolution);
2203 resolution->hostname_dn = NULL;
2204 resolution->hostname_dn_len = 0;
2205
2206 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.wait, list) {
2207 LIST_DEL(&requester->list);
2208 }
2209 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
2210 LIST_DEL(&requester->list);
2211 }
2212
2213 LIST_DEL(&resolution->list);
2214 LIST_ADDQ(&resolvers->resolution.pool, &resolution->list);
2215
2216 return;
2217}
2218
2219/*
2220 * this function remove a requester from a resolution
2221 * and takes care of all the consequences.
2222 * It also cleans up some parameters from the requester
2223 */
2224void dns_rm_requester_from_resolution(struct dns_requester *requester, struct dns_resolution *resolution)
2225{
2226 char *hostname_dn;
2227 struct dns_requester *tmprequester;
2228
2229 /* resolution is still used by other requesters, we need to move
2230 * some pointers to an other requester if needed
2231 */
2232 switch (obj_type(requester->requester)) {
2233 case OBJ_TYPE_SERVER:
2234 hostname_dn = objt_server(requester->requester)->hostname_dn;
2235 break;
2236 case OBJ_TYPE_NONE:
2237 default:
2238 hostname_dn = NULL;
2239 break;
2240 }
2241
2242 if (resolution->hostname_dn != hostname_dn)
2243 return;
2244
2245 /* First, we need to find this other requester */
2246 tmprequester = NULL;
2247 list_for_each_entry(tmprequester, &resolution->requester.wait, list) {
2248 if (tmprequester != requester)
2249 break;
2250 }
2251 if (!tmprequester) {
2252 /* if we can't find it in wait queue, let's get one in run queue */
2253 list_for_each_entry(tmprequester, &resolution->requester.curr, list) {
2254 if (tmprequester != requester)
2255 break;
2256 }
2257 }
2258
2259 /* move hostname_dn related pointers to the next requester */
2260 switch (obj_type(tmprequester->requester)) {
2261 case OBJ_TYPE_SERVER:
2262 resolution->hostname_dn = objt_server(tmprequester->requester)->hostname_dn;
2263 resolution->hostname_dn_len = objt_server(tmprequester->requester)->hostname_dn_len;
2264 break;
2265 case OBJ_TYPE_NONE:
2266 default:
2267 ;;
2268 }
2269
2270
2271 /* clean up the requester */
2272 LIST_DEL(&requester->list);
2273 switch (obj_type(requester->requester)) {
2274 case OBJ_TYPE_SERVER:
2275 objt_server(requester->requester)->resolution = NULL;
2276 break;
2277 case OBJ_TYPE_NONE:
2278 default:
2279 ;;
2280 }
2281}
2282
Willy Tarreau777b5602016-12-16 18:06:26 +01002283/* This function dumps counters from all resolvers section and associated name
2284 * servers. It returns 0 if the output buffer is full and it needs to be called
2285 * again, otherwise non-zero. It may limit itself to the resolver pointed to by
2286 * <cli.p0> if it's not null.
William Lallemand69e96442016-11-19 00:58:54 +01002287 */
2288static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2289{
2290 struct stream_interface *si = appctx->owner;
2291 struct dns_resolvers *presolvers;
2292 struct dns_nameserver *pnameserver;
2293
2294 chunk_reset(&trash);
2295
2296 switch (appctx->st2) {
2297 case STAT_ST_INIT:
2298 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2299 /* fall through */
2300
2301 case STAT_ST_LIST:
2302 if (LIST_ISEMPTY(&dns_resolvers)) {
2303 chunk_appendf(&trash, "No resolvers found\n");
2304 }
2305 else {
2306 list_for_each_entry(presolvers, &dns_resolvers, list) {
Willy Tarreau777b5602016-12-16 18:06:26 +01002307 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != presolvers)
William Lallemand69e96442016-11-19 00:58:54 +01002308 continue;
2309
2310 chunk_appendf(&trash, "Resolvers section %s\n", presolvers->id);
2311 list_for_each_entry(pnameserver, &presolvers->nameserver_list, list) {
2312 chunk_appendf(&trash, " nameserver %s:\n", pnameserver->id);
2313 chunk_appendf(&trash, " sent: %ld\n", pnameserver->counters.sent);
2314 chunk_appendf(&trash, " valid: %ld\n", pnameserver->counters.valid);
2315 chunk_appendf(&trash, " update: %ld\n", pnameserver->counters.update);
2316 chunk_appendf(&trash, " cname: %ld\n", pnameserver->counters.cname);
2317 chunk_appendf(&trash, " cname_error: %ld\n", pnameserver->counters.cname_error);
2318 chunk_appendf(&trash, " any_err: %ld\n", pnameserver->counters.any_err);
2319 chunk_appendf(&trash, " nx: %ld\n", pnameserver->counters.nx);
2320 chunk_appendf(&trash, " timeout: %ld\n", pnameserver->counters.timeout);
2321 chunk_appendf(&trash, " refused: %ld\n", pnameserver->counters.refused);
2322 chunk_appendf(&trash, " other: %ld\n", pnameserver->counters.other);
2323 chunk_appendf(&trash, " invalid: %ld\n", pnameserver->counters.invalid);
2324 chunk_appendf(&trash, " too_big: %ld\n", pnameserver->counters.too_big);
2325 chunk_appendf(&trash, " truncated: %ld\n", pnameserver->counters.truncated);
2326 chunk_appendf(&trash, " outdated: %ld\n", pnameserver->counters.outdated);
2327 }
2328 }
2329 }
2330
2331 /* display response */
2332 if (bi_putchk(si_ic(si), &trash) == -1) {
2333 /* let's try again later from this session. We add ourselves into
2334 * this session's users so that it can remove us upon termination.
2335 */
2336 si->flags |= SI_FL_WAIT_ROOM;
2337 return 0;
2338 }
2339
2340 appctx->st2 = STAT_ST_FIN;
2341 /* fall through */
2342
2343 default:
2344 appctx->st2 = STAT_ST_FIN;
2345 return 1;
2346 }
2347}
2348
2349/* register cli keywords */
2350static struct cli_kw_list cli_kws = {{ },{
2351 { { "show", "stat", "resolvers", NULL }, "show stat resolvers [id]: dumps counters from all resolvers section and\n"
2352 " associated name servers",
2353 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2354 {{},}
2355}};
2356
2357
2358__attribute__((constructor))
2359static void __dns_init(void)
2360{
2361 cli_register_kw(&cli_kws);
2362}
2363