blob: dbb473e29f6adf25b781e637afb26451d8ac4ba5 [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>
Olivier Houchard8da5f982017-08-04 18:35:36 +020024#include <common/net_helper.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020025
Baptiste Assmannfa4a6632017-05-04 09:05:00 +020026#include <import/lru.h>
27#include <import/xxhash.h>
28
William Lallemand69e96442016-11-19 00:58:54 +010029#include <types/applet.h>
30#include <types/cli.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020031#include <types/global.h>
32#include <types/dns.h>
33#include <types/proto_udp.h>
William Lallemand69e96442016-11-19 00:58:54 +010034#include <types/stats.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020035
William Lallemand69e96442016-11-19 00:58:54 +010036#include <proto/channel.h>
37#include <proto/cli.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020038#include <proto/checks.h>
39#include <proto/dns.h>
40#include <proto/fd.h>
41#include <proto/log.h>
42#include <proto/server.h>
43#include <proto/task.h>
44#include <proto/proto_udp.h>
William Lallemand69e96442016-11-19 00:58:54 +010045#include <proto/stream_interface.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020046
47struct list dns_resolvers = LIST_HEAD_INIT(dns_resolvers);
48struct dns_resolution *resolution = NULL;
49
50static int64_t dns_query_id_seed; /* random seed */
51
Baptiste Assmannfa4a6632017-05-04 09:05:00 +020052static struct lru64_head *dns_lru_tree;
53static int dns_cache_size = 1024; /* arbitrary DNS cache size */
54
Olivier Houcharda8c6db82017-07-06 18:46:47 +020055static struct pool_head *dns_answer_item_pool;
56
Baptiste Assmann325137d2015-04-13 23:40:55 +020057/* proto_udp callback functions for a DNS resolution */
58struct dgram_data_cb resolve_dgram_cb = {
59 .recv = dns_resolve_recv,
60 .send = dns_resolve_send,
61};
62
Baptiste Assmann201c07f2017-05-22 15:17:15 +020063/* local function prototypes */
64static int dns_run_resolution(struct dns_requester *requester);
65
Baptiste Assmann325137d2015-04-13 23:40:55 +020066#if DEBUG
67/*
68 * go through the resolutions associated to a resolvers section and print the ID and hostname in
69 * domain name format
70 * should be used for debug purpose only
71 */
72void dns_print_current_resolutions(struct dns_resolvers *resolvers)
73{
Baptiste Assmann201c07f2017-05-22 15:17:15 +020074 list_for_each_entry(resolution, &resolvers->resolution.curr, list) {
Baptiste Assmann325137d2015-04-13 23:40:55 +020075 printf(" resolution %d for %s\n", resolution->query_id, resolution->hostname_dn);
76 }
77}
78#endif
79
Baptiste Assmann201c07f2017-05-22 15:17:15 +020080void dump_dns_config()
81{
82 struct dns_resolvers *curr_resolvers = NULL;
83 struct dns_nameserver *curr_nameserver = NULL;
84 struct dns_resolution *curr_resolution = NULL;
85 struct dns_requester *curr_requester = NULL;
86
87 printf("===============\n");
88 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
89 printf("Resolvers: %s\n", curr_resolvers->id);
90
91 printf(" nameservers:\n");
92 list_for_each_entry(curr_nameserver, &curr_resolvers->nameserver_list, list) {
93 printf(" %s\n", curr_nameserver->id);
94 }
95
96/*
97 printf(" resolution.pool list:\n");
98 list_for_each_entry(curr_resolution, &curr_resolvers->resolution.pool, list) {
99 printf(" %p\n", curr_resolution);
100 }
101*/
102
103 printf(" resolution.wait list:\n");
104 list_for_each_entry(curr_resolution, &curr_resolvers->resolution.wait, list) {
105 printf(" %p %s\n", curr_resolution, curr_resolution->hostname_dn);
106 printf(" requester.wait list:\n");
107 list_for_each_entry(curr_requester, &curr_resolution->requester.wait, list) {
Baptiste Assmanna644aa82017-08-12 11:16:55 +0200108 switch (obj_type(curr_requester->requester)) {
109 case OBJ_TYPE_SERVER:
110 printf(" %p SRV %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
111 break;
112 case OBJ_TYPE_SRVRQ:
113 printf(" %p SRVRQ %s %d\n", curr_requester, objt_dns_srvrq(curr_requester->requester)->name, curr_requester->prefered_query_type);
114 break;
115 case OBJ_TYPE_NONE:
116 default:
117 ;;
118 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200119 }
120 printf(" requester.curr list:\n");
121 list_for_each_entry(curr_requester, &curr_resolution->requester.curr, list) {
Baptiste Assmanna644aa82017-08-12 11:16:55 +0200122 switch (obj_type(curr_requester->requester)) {
123 case OBJ_TYPE_SERVER:
124 printf(" %p SRV %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
125 break;
126 case OBJ_TYPE_SRVRQ:
127 printf(" %p SRVRQ %s %d\n", curr_requester, objt_dns_srvrq(curr_requester->requester)->name, curr_requester->prefered_query_type);
128 break;
129 case OBJ_TYPE_NONE:
130 default:
131 ;;
132 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200133 }
134 }
135 printf(" resolution.curr list:\n");
136 list_for_each_entry(curr_resolution, &curr_resolvers->resolution.curr, list) {
137 printf(" %p %s\n", curr_resolution, curr_resolution->hostname_dn);
138 printf(" requester.wait list:\n");
139 list_for_each_entry(curr_requester, &curr_resolution->requester.wait, list) {
Baptiste Assmanna644aa82017-08-12 11:16:55 +0200140 switch (obj_type(curr_requester->requester)) {
141 case OBJ_TYPE_SERVER:
142 printf(" %p SRV %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
143 break;
144 case OBJ_TYPE_SRVRQ:
145 printf(" %p SRVRQ %s %d\n", curr_requester, objt_dns_srvrq(curr_requester->requester)->name, curr_requester->prefered_query_type);
146 break;
147 case OBJ_TYPE_NONE:
148 default:
149 ;;
150 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200151 }
152 printf(" requester.curr list:\n");
153 list_for_each_entry(curr_requester, &curr_resolution->requester.curr, list) {
Baptiste Assmanna644aa82017-08-12 11:16:55 +0200154 switch (obj_type(curr_requester->requester)) {
155 case OBJ_TYPE_SERVER:
156 printf(" %p SRV %s %d\n", curr_requester, objt_server(curr_requester->requester)->id, curr_requester->prefered_query_type);
157 break;
158 case OBJ_TYPE_SRVRQ:
159 printf(" %p SRVRQ %s %d\n", curr_requester, objt_dns_srvrq(curr_requester->requester)->name, curr_requester->prefered_query_type);
160 break;
161 case OBJ_TYPE_NONE:
162 default:
163 ;;
164 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200165 }
166 }
167 }
168
169 printf("===============\n");
170}
171
172/*
173 * Initiates a new name resolution:
174 * - generates a query id
175 * - configure the resolution structure
176 * - startup the resolvers task if required
177 *
178 * returns:
179 * - 0 if everything started properly
180 * - -1 in case of error or if resolution already running
181 */
182int dns_trigger_resolution(struct dns_resolution *resolution)
183{
184 struct dns_requester *requester = NULL, *tmprequester;
185 struct dns_resolvers *resolvers = NULL;
Baptiste Assmannf5f71302017-08-21 13:21:48 +0200186 int inter, valid_period;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200187
188 /* process the element of the wait queue */
189 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.wait, list) {
190 inter = 0;
191
192 switch (obj_type(requester->requester)) {
193 case OBJ_TYPE_SERVER:
Baptiste Assmannf5f71302017-08-21 13:21:48 +0200194 valid_period = objt_server(requester->requester)->check.inter;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200195 resolvers = objt_server(requester->requester)->resolvers;
196 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200197 case OBJ_TYPE_SRVRQ:
Baptiste Assmannf5f71302017-08-21 13:21:48 +0200198 valid_period = objt_dns_srvrq(requester->requester)->inter;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200199 resolvers = objt_dns_srvrq(requester->requester)->resolvers;
200 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200201 case OBJ_TYPE_NONE:
202 default:
203 return -1;
204 }
205
Baptiste Assmannf5f71302017-08-21 13:21:48 +0200206 if (resolvers->hold.valid < valid_period)
207 inter = resolvers->hold.valid;
208 else
209 inter = valid_period;
210
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200211 /* if data is fresh enough, let's use it */
212 if (!tick_is_expired(tick_add(resolution->last_resolution, inter), now_ms)) {
213 /* we only use cache if the response there is valid.
214 * If not valid, we run the resolution and move the requester to
215 * the run queue. */
216 if (resolution->status != RSLV_STATUS_VALID) {
217 LIST_DEL(&requester->list);
218 LIST_ADDQ(&resolution->requester.curr, &requester->list);
219 dns_run_resolution(requester);
220 continue;
221 }
222
223 requester->requester_cb(requester, NULL);
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200224 resolvers = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200225 }
226 else {
227 LIST_DEL(&requester->list);
228 LIST_ADDQ(&resolution->requester.curr, &requester->list);
229 dns_run_resolution(requester);
230 }
231 }
232
233 if (resolvers)
234 dns_update_resolvers_timeout(resolvers);
235
236 return 0;
237}
238
Baptiste Assmann325137d2015-04-13 23:40:55 +0200239/*
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200240 * Prepare and send a DNS resolution.
241 *
242 * Return code:
243 * - 0 if no error occured
244 * - -1 in case of error
245 */
246static int
247dns_run_resolution(struct dns_requester *requester)
248{
249 struct dns_resolution *resolution;
250 struct dns_resolvers *resolvers;
251 int query_id, query_type, i;
252 struct proxy *proxy;
253
254 resolution = NULL;
255 resolvers = NULL;
256 proxy = NULL;
257 query_type = -1;
258 switch (obj_type(requester->requester)) {
259 case OBJ_TYPE_SERVER:
260 resolution = objt_server(requester->requester)->resolution;
261 resolvers = objt_server(requester->requester)->resolvers;
262 proxy = objt_server(requester->requester)->proxy;
263 query_type = requester->prefered_query_type;
264 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200265 case OBJ_TYPE_SRVRQ:
266 resolution = objt_dns_srvrq(requester->requester)->resolution;
267 resolvers = objt_dns_srvrq(requester->requester)->resolvers;
268 proxy = objt_dns_srvrq(requester->requester)->proxy;
269 query_type = DNS_RTYPE_SRV;
270 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200271 case OBJ_TYPE_NONE:
272 default:
273 return -1;
274 }
275
276 /*
Olivier Houchard8da5f982017-08-04 18:35:36 +0200277 * Avoid sending requests for resolutions that don't yet have
278 * an hostname, ie resolutions linked to servers that do not yet
279 * have an fqdn
280 */
281 if (!resolution->hostname_dn)
282 return 0;
283
284 /*
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200285 * check if a resolution has already been started for this server
286 * return directly to avoid resolution pill up.
287 */
288 if (resolution->step != RSLV_STEP_NONE)
289 return 0;
290
291 /* generates a query id */
292 i = 0;
293 do {
294 query_id = dns_rnd16();
295 /* we do try only 100 times to find a free query id */
296 if (i++ > 100) {
297 chunk_printf(&trash, "could not generate a query id for %s, in resolvers %s",
298 resolution->hostname_dn, resolvers->id);
299
300 if (proxy)
301 send_log(proxy, LOG_NOTICE, "%s.\n", trash.str);
302 return -1;
303 }
304 } while (eb32_lookup(&resolvers->query_ids, query_id));
305
306 /* move the resolution into the run queue */
307 LIST_DEL(&resolution->list);
308 LIST_ADDQ(&resolvers->resolution.curr, &resolution->list);
309
310 /* now update resolution parameters */
311 resolution->query_id = query_id;
312 resolution->qid.key = query_id;
313 resolution->step = RSLV_STEP_RUNNING;
314 resolution->query_type = query_type;
315 resolution->try = resolvers->resolve_retries;
316 resolution->try_cname = 0;
317 resolution->nb_responses = 0;
318 eb32_insert(&resolvers->query_ids, &resolution->qid);
319
320 dns_send_query(resolution);
321 resolution->try -= 1;
322
323 /* update wakeup date if this resolution is the only one in the FIFO list */
324 if (dns_check_resolution_queue(resolvers) == 1) {
325 /* update task timeout */
326 dns_update_resolvers_timeout(resolvers);
327 task_queue(resolvers->t);
328 }
329
330 return 0;
331}
332
333/*
Baptiste Assmann325137d2015-04-13 23:40:55 +0200334 * check if there is more than 1 resolution in the resolver's resolution list
335 * return value:
336 * 0: empty list
337 * 1: exactly one entry in the list
338 * 2: more than one entry in the list
339 */
340int dns_check_resolution_queue(struct dns_resolvers *resolvers)
341{
342
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200343 if (LIST_ISEMPTY(&resolvers->resolution.curr))
Baptiste Assmann325137d2015-04-13 23:40:55 +0200344 return 0;
345
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200346 if ((resolvers->resolution.curr.n) && (resolvers->resolution.curr.n == resolvers->resolution.curr.p))
Baptiste Assmann325137d2015-04-13 23:40:55 +0200347 return 1;
348
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200349 if (! ((resolvers->resolution.curr.n == resolvers->resolution.curr.p)
350 && (&resolvers->resolution.curr != resolvers->resolution.curr.n)))
Baptiste Assmann325137d2015-04-13 23:40:55 +0200351 return 2;
352
353 return 0;
354}
355
356/*
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200357 * reset some resolution parameters to initial values and also delete the
358 * query ID from the resolver's tree.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200359 */
360void dns_reset_resolution(struct dns_resolution *resolution)
361{
362 /* update resolution status */
363 resolution->step = RSLV_STEP_NONE;
364
365 resolution->try = 0;
366 resolution->try_cname = 0;
367 resolution->last_resolution = now_ms;
368 resolution->nb_responses = 0;
369
370 /* clean up query id */
371 eb32_delete(&resolution->qid);
372 resolution->query_id = 0;
373 resolution->qid.key = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200374}
375
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200376static inline void free_dns_answer_item(struct dns_answer_item *item)
377{
378 pool_free2(dns_answer_item_pool, item);
379}
380
381
Baptiste Assmann325137d2015-04-13 23:40:55 +0200382/*
383 * function called when a network IO is generated on a name server socket for an incoming packet
384 * It performs the following actions:
385 * - check if the packet requires processing (not outdated resolution)
386 * - ensure the DNS packet received is valid and call requester's callback
387 * - call requester's error callback if invalid response
Baptiste Assmann3cf7f982016-04-17 22:43:26 +0200388 * - check the dn_name in the packet against the one sent
Baptiste Assmann325137d2015-04-13 23:40:55 +0200389 */
390void dns_resolve_recv(struct dgram_conn *dgram)
391{
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200392 struct dns_nameserver *nameserver, *tmpnameserver;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200393 struct dns_resolvers *resolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200394 struct dns_resolution *resolution = NULL;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200395 struct dns_query_item *query;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200396 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
397 unsigned char *bufend;
William Lallemandcc9b94a2017-06-08 19:30:39 +0200398 int fd, buflen, dns_resp, need_resend = 0;
Baptiste Assmann9d8dbbc2017-08-18 23:35:08 +0200399 int max_answer_records = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200400 unsigned short query_id;
401 struct eb32_node *eb;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200402 struct lru64 *lru = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200403 struct dns_requester *requester = NULL, *tmprequester = NULL;
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200404 struct dns_answer_item *item1, *item2 = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200405
406 fd = dgram->t.sock.fd;
407
408 /* check if ready for reading */
409 if (!fd_recv_ready(fd))
410 return;
411
412 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200413 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200414 return;
415
416 resolvers = nameserver->resolvers;
417
418 /* process all pending input messages */
419 while (1) {
Olivier Houchard8da5f982017-08-04 18:35:36 +0200420 int removed_reso = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200421 /* read message received */
Baptiste Assmann9d8dbbc2017-08-18 23:35:08 +0200422 memset(buf, '\0', resolvers->accepted_payload_size + 1);
423 if ((buflen = recv(fd, (char*)buf , resolvers->accepted_payload_size + 1, 0)) < 0) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200424 /* FIXME : for now we consider EAGAIN only */
425 fd_cant_recv(fd);
426 break;
427 }
428
429 /* message too big */
Baptiste Assmann9d8dbbc2017-08-18 23:35:08 +0200430 if (buflen > resolvers->accepted_payload_size) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200431 nameserver->counters.too_big += 1;
432 continue;
433 }
434
435 /* initializing variables */
436 bufend = buf + buflen; /* pointer to mark the end of the buffer */
437
438 /* read the query id from the packet (16 bits) */
439 if (buf + 2 > bufend) {
440 nameserver->counters.invalid += 1;
441 continue;
442 }
443 query_id = dns_response_get_query_id(buf);
444
445 /* search the query_id in the pending resolution tree */
Baptiste Assmann01daef32015-09-02 22:05:24 +0200446 eb = eb32_lookup(&resolvers->query_ids, query_id);
447 if (eb == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200448 /* unknown query id means an outdated response and can be safely ignored */
449 nameserver->counters.outdated += 1;
450 continue;
451 }
452
453 /* known query id means a resolution in prgress */
454 resolution = eb32_entry(eb, struct dns_resolution, qid);
455
456 if (!resolution) {
457 nameserver->counters.outdated += 1;
458 continue;
459 }
460
461 /* number of responses received */
462 resolution->nb_responses += 1;
463
Baptiste Assmann9d8dbbc2017-08-18 23:35:08 +0200464
465 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
466 dns_resp = dns_validate_dns_response(buf, bufend, resolution, max_answer_records);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200467
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200468 switch (dns_resp) {
469 case DNS_RESP_VALID:
470 need_resend = 0;
471 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200472
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200473 case DNS_RESP_INVALID:
474 case DNS_RESP_QUERY_COUNT_ERROR:
475 case DNS_RESP_WRONG_NAME:
476 if (resolution->status != RSLV_STATUS_INVALID) {
477 resolution->status = RSLV_STATUS_INVALID;
478 resolution->last_status_change = now_ms;
479 }
480 nameserver->counters.invalid += 1;
481 need_resend = 0;
482 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200483
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200484 case DNS_RESP_ANCOUNT_ZERO:
485 if (resolution->status != RSLV_STATUS_OTHER) {
486 resolution->status = RSLV_STATUS_OTHER;
487 resolution->last_status_change = now_ms;
488 }
489 nameserver->counters.any_err += 1;
490 need_resend = 1;
491 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200492
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200493 case DNS_RESP_NX_DOMAIN:
494 if (resolution->status != RSLV_STATUS_NX) {
495 resolution->status = RSLV_STATUS_NX;
496 resolution->last_status_change = now_ms;
497 }
498 nameserver->counters.nx += 1;
499 need_resend = 0;
500 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200501
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200502 case DNS_RESP_REFUSED:
503 if (resolution->status != RSLV_STATUS_REFUSED) {
504 resolution->status = RSLV_STATUS_REFUSED;
505 resolution->last_status_change = now_ms;
506 }
507 nameserver->counters.refused += 1;
508 need_resend = 0;
509 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200510
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200511 case DNS_RESP_CNAME_ERROR:
512 if (resolution->status != RSLV_STATUS_OTHER) {
513 resolution->status = RSLV_STATUS_OTHER;
514 resolution->last_status_change = now_ms;
515 }
516 nameserver->counters.cname_error += 1;
517 need_resend = 1;
518 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200519
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200520 case DNS_RESP_TRUNCATED:
521 if (resolution->status != RSLV_STATUS_OTHER) {
522 resolution->status = RSLV_STATUS_OTHER;
523 resolution->last_status_change = now_ms;
524 }
525 nameserver->counters.truncated += 1;
526 need_resend = 1;
527 break;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200528
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200529 case DNS_RESP_NO_EXPECTED_RECORD:
530 if (resolution->status != RSLV_STATUS_OTHER) {
531 resolution->status = RSLV_STATUS_OTHER;
532 resolution->last_status_change = now_ms;
533 }
534 nameserver->counters.other += 1;
535 need_resend = 1;
536 break;
537
538 case DNS_RESP_ERROR:
539 case DNS_RESP_INTERNAL:
540 if (resolution->status != RSLV_STATUS_OTHER) {
541 resolution->status = RSLV_STATUS_OTHER;
542 resolution->last_status_change = now_ms;
543 }
544 nameserver->counters.other += 1;
545 need_resend = 1;
546 break;
547 }
548
Olivier Houchard8da5f982017-08-04 18:35:36 +0200549 /* Check for any obsolete record, also identify any SRV request, and try to find a corresponding server */
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200550 list_for_each_entry_safe(item1, item2, &resolution->response.answer_list,
551 list) {
552 if (item1->last_seen + nameserver->resolvers->hold.obsolete / 1000 < now.tv_sec) {
553 LIST_DEL(&item1->list);
Olivier Houchard8da5f982017-08-04 18:35:36 +0200554 if (item1->type == DNS_RTYPE_SRV && !LIST_ISEMPTY(&resolution->requester.curr)) {
555 struct dns_srvrq *srvrq;
556
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200557 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
558 srvrq = objt_dns_srvrq(requester->requester);
559 /* We're removing an obsolete entry, remove any associated server */
560 if (srvrq) {
561 struct server *srv;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200562
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200563 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
564 if (srv->srvrq == srvrq &&
565 item1->data_len ==
566 srv->hostname_dn_len &&
567 !memcmp(srv->hostname_dn, item1->target, item1->data_len) &&
568 srv->svc_port == item1->port) {
569 snr_update_srv_status(srv, 1);
570 free(srv->hostname);
571 srv->hostname = NULL;
572 srv->hostname_dn_len = 0;
573 free(srv->hostname_dn);
574 srv->hostname_dn = NULL;
Baptiste Assmann747359e2017-08-14 10:37:46 +0200575 srv_free_from_resolution(srv);
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200576 }
Olivier Houchard8da5f982017-08-04 18:35:36 +0200577 }
578 }
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200579 } /* end of list_for_each(requester) */
Olivier Houchard8da5f982017-08-04 18:35:36 +0200580 }
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200581 free_dns_answer_item(item1);
Olivier Houchard8da5f982017-08-04 18:35:36 +0200582 continue;
583 }
584 if (item1->type == DNS_RTYPE_SRV) {
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200585 struct server *srv = NULL;
586 struct dns_srvrq *srvrq = NULL;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200587
588 if (LIST_ISEMPTY(&resolution->requester.curr))
589 continue;
590
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200591 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
592 srvrq = objt_dns_srvrq(requester->requester);
593 if (!srvrq)
594 continue;
595 /* Check if a server already uses that hostname */
596 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
597 if (srv->srvrq == srvrq &&
598 item1->data_len == srv->hostname_dn_len &&
599 !memcmp(srv->hostname_dn, item1->target, item1->data_len) &&
600 srv->svc_port == item1->port) {
601 if (srv->uweight != item1->weight) {
602 char weight[9];
603
604 snprintf(weight, sizeof(weight),
605 "%d", item1->weight);
606 server_parse_weight_change_request(srv, weight);
607
608 }
609
610 break;
611 }
612 }
613 /* If not, try to find a server that is down */
614 if (!srv) {
615 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
616
617 if (srv->srvrq == srvrq &&
618 !srv->hostname_dn)
619 break;
620 }
621 if (srv) {
Olivier Houchard8da5f982017-08-04 18:35:36 +0200622 char weight[9];
Baptiste Assmanne2d03d22017-08-18 23:36:07 +0200623 const char *msg = NULL;
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200624 char hostname[DNS_MAX_NAME_SIZE];
625
626 if (item1->data_len > DNS_MAX_NAME_SIZE)
627 continue;
628 dns_dn_label_to_str(item1->target, hostname, item1->data_len);
Baptiste Assmanne2d03d22017-08-18 23:36:07 +0200629 msg = update_server_fqdn(srv, hostname, "SRV record");
630 if (msg)
631 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
632
Baptiste Assmann7d2a1262017-08-14 16:38:29 +0200633 srv->svc_port = item1->port;
634 srv->flags &= ~SRV_F_MAPPORTS;
635 if ((srv->check.state & CHK_ST_CONFIGURED) && !(srv->flags & SRV_F_CHECKPORT))
636 srv->check.port = item1->port;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200637 snprintf(weight, sizeof(weight),
638 "%d", item1->weight);
639 server_parse_weight_change_request(srv, weight);
Olivier Houchard8da5f982017-08-04 18:35:36 +0200640 }
Olivier Houchard8da5f982017-08-04 18:35:36 +0200641 }
Olivier Houchard8da5f982017-08-04 18:35:36 +0200642 }
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200643 }
644 }
Olivier Houchard8da5f982017-08-04 18:35:36 +0200645 if (removed_reso)
646 goto next_packet;
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200647
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200648 /* some error codes trigger a re-send of the query, but switching the
649 * query type.
650 * This is the case for the following error codes:
651 * DNS_RESP_ANCOUNT_ZERO
652 * DNS_RESP_TRUNCATED
653 * DNS_RESP_ERROR
654 * DNS_RESP_INTERNAL
655 * DNS_RESP_NO_EXPECTED_RECORD
656 * DNS_RESP_CNAME_ERROR
657 */
658 if (need_resend) {
659 int family_prio;
660 int res_preferred_afinet, res_preferred_afinet6;
661
662 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
663 switch (obj_type(requester->requester)) {
664 case OBJ_TYPE_SERVER:
665 family_prio = objt_server(requester->requester)->dns_opts.family_prio;
666 break;
667 case OBJ_TYPE_NONE:
668 default:
669 family_prio = AF_INET6;
670 }
671 res_preferred_afinet = family_prio == AF_INET && resolution->query_type == DNS_RTYPE_A;
672 res_preferred_afinet6 = family_prio == AF_INET6 && resolution->query_type == DNS_RTYPE_AAAA;
673 if ((res_preferred_afinet || res_preferred_afinet6)
674 || (resolution->try > 0)) {
675 /* let's change the query type */
676 if (res_preferred_afinet6) {
677 /* fallback from AAAA to A */
678 resolution->query_type = DNS_RTYPE_A;
679 }
680 else if (res_preferred_afinet) {
681 /* fallback from A to AAAA */
682 resolution->query_type = DNS_RTYPE_AAAA;
683 }
684 else {
685 resolution->try -= 1;
686 if (family_prio == AF_INET) {
687 resolution->query_type = DNS_RTYPE_A;
688 } else {
689 resolution->query_type = DNS_RTYPE_AAAA;
690 }
691 }
692
693 dns_send_query(resolution);
694 /*
695 * move the resolution to the last element of the FIFO queue
696 * and update timeout wakeup based on the new first entry
697 */
698 if (dns_check_resolution_queue(resolvers) > 1) {
699 /* second resolution becomes first one */
700 LIST_DEL(&resolution->list);
701 /* ex first resolution goes to the end of the queue */
702 LIST_ADDQ(&resolvers->resolution.curr, &resolution->list);
703 }
704
705 dns_update_resolvers_timeout(resolvers);
706 goto next_packet;
707 }
708
709 /* if we're there, this means that we already ran out of chances to re-send
710 * the query */
711 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
712 requester->requester_error_cb(requester, dns_resp);
713 }
714 goto next_packet;
715 }
716
717 /* now processing those error codes only:
718 * DNS_RESP_NX_DOMAIN
719 * DNS_RESP_REFUSED
720 */
721 if (dns_resp != DNS_RESP_VALID) {
722 /* now parse list of requesters currently waiting for this resolution */
723 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
724 requester->requester_error_cb(requester, dns_resp);
725
726 /* we can move the requester the wait queue */
727 LIST_DEL(&requester->list);
728 LIST_ADDQ(&resolution->requester.wait, &requester->list);
729 }
730 goto next_packet;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200731 }
732
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200733 /* Now let's check the query's dname corresponds to the one we sent.
734 * We can check only the first query of the list. We send one query at a time
735 * so we get one query in the response */
Baptiste Assmann729c9012017-05-22 15:13:10 +0200736 query = LIST_NEXT(&resolution->response.query_list, struct dns_query_item *, list);
Olivier Houchard8da5f982017-08-04 18:35:36 +0200737 if (!resolution->hostname_dn)
738 abort();
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200739 if (query && memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
740 nameserver->counters.other += 1;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200741 /* now parse list of requesters currently waiting for this resolution */
742 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
743 requester->requester_error_cb(requester, DNS_RESP_WRONG_NAME);
744 /* we can move the requester the wait queue */
745 LIST_DEL(&requester->list);
746 LIST_ADDQ(&resolution->requester.wait, &requester->list);
747 }
748 goto next_packet;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200749 }
750
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200751 /* no errors, we can save the response in the cache */
752 if (dns_lru_tree) {
753 unsigned long long seed = 1;
754 struct chunk *buf = get_trash_chunk();
755 struct chunk *tmp = NULL;
756
757 chunk_reset(buf);
758 tmp = dns_cache_key(resolution->query_type, resolution->hostname_dn,
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200759 resolution->hostname_dn_len, buf);
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200760 if (!tmp) {
761 nameserver->counters.other += 1;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200762 /* now parse list of requesters currently waiting for this resolution */
763 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
764 requester->requester_error_cb(requester, DNS_RESP_ERROR);
765 /* we can move the requester the wait queue */
766 LIST_DEL(&requester->list);
767 LIST_ADDQ(&resolution->requester.wait, &requester->list);
768 }
769 goto next_packet;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200770 }
771
772 lru = lru64_get(XXH64(buf->str, buf->len, seed),
773 dns_lru_tree, nameserver->resolvers, 1);
774
775 lru64_commit(lru, resolution, nameserver->resolvers, 1, NULL);
776 }
777
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200778 if (resolution->status != RSLV_STATUS_VALID) {
779 resolution->status = RSLV_STATUS_VALID;
780 resolution->last_status_change = now_ms;
781 }
782
Baptiste Assmann37bb3722015-08-07 10:18:32 +0200783 nameserver->counters.valid += 1;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200784 /* now parse list of requesters currently waiting for this resolution */
785 tmpnameserver = nameserver;
786 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
787 requester->requester_cb(requester, tmpnameserver);
788 /* we can move the requester the wait queue */
789 LIST_DEL(&requester->list);
790 LIST_ADDQ(&resolution->requester.wait, &requester->list);
791 /* first response is managed by the server, others are from the cache */
792 tmpnameserver = NULL;
793 }
794
795 next_packet:
796 /* resolution may be NULL when we receive an ICMP unreachable packet */
797 if (resolution && LIST_ISEMPTY(&resolution->requester.curr)) {
798 /* move the resolution into the wait queue */
799 LIST_DEL(&resolution->list);
800 LIST_ADDQ(&resolvers->resolution.wait, &resolution->list);
801 /* update last resolution date and time */
802 resolution->last_resolution = now_ms;
803 /* reset current status flag */
804 resolution->step = RSLV_STEP_NONE;
805 /* reset values */
806 dns_reset_resolution(resolution);
807 }
808
809 } // end of while "packets" loop
810
811 dns_update_resolvers_timeout(nameserver->resolvers);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200812}
813
814/*
815 * function called when a resolvers network socket is ready to send data
816 * It performs the following actions:
817 */
818void dns_resolve_send(struct dgram_conn *dgram)
819{
820 int fd;
821 struct dns_nameserver *nameserver;
822 struct dns_resolvers *resolvers;
823 struct dns_resolution *resolution;
824
825 fd = dgram->t.sock.fd;
826
827 /* check if ready for sending */
828 if (!fd_send_ready(fd))
829 return;
830
831 /* we don't want/need to be waked up any more for sending */
832 fd_stop_send(fd);
833
834 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200835 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200836 return;
837
838 resolvers = nameserver->resolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200839 resolution = LIST_NEXT(&resolvers->resolution.curr, struct dns_resolution *, list);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200840
841 dns_send_query(resolution);
842 dns_update_resolvers_timeout(resolvers);
843}
844
845/*
846 * forge and send a DNS query to resolvers associated to a resolution
847 * It performs the following actions:
848 * returns:
849 * 0 in case of error or safe ignorance
850 * 1 if no error
851 */
852int dns_send_query(struct dns_resolution *resolution)
853{
Baptiste Assmann42746372017-05-03 12:12:02 +0200854 struct dns_resolvers *resolvers = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200855 struct dns_nameserver *nameserver;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200856 struct dns_requester *requester = NULL;
Erwan Velu5457eb42015-10-15 15:07:26 +0200857 int ret, bufsize, fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200858
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200859 /* nothing to do */
860 if (LIST_ISEMPTY(&resolution->requester.curr))
861 return 0;
862
863 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
864
865 switch (obj_type(requester->requester)) {
866 case OBJ_TYPE_SERVER:
867 resolvers = objt_server(requester->requester)->resolvers;
868 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200869 case OBJ_TYPE_SRVRQ:
870 resolvers = objt_dns_srvrq(requester->requester)->resolvers;
871 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200872 case OBJ_TYPE_NONE:
873 default:
874 return 0;
875 }
Baptiste Assmann42746372017-05-03 12:12:02 +0200876
877 if (!resolvers)
878 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200879
Baptiste Assmann2af08fe2017-08-14 00:13:01 +0200880 bufsize = dns_build_query(resolution->query_id, resolution->query_type, resolvers->accepted_payload_size,
881 resolution->hostname_dn, resolution->hostname_dn_len, trash.str, trash.size);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200882
883 if (bufsize == -1)
884 return 0;
885
886 list_for_each_entry(nameserver, &resolvers->nameserver_list, list) {
887 fd = nameserver->dgram->t.sock.fd;
888 errno = 0;
889
890 ret = send(fd, trash.str, bufsize, 0);
891
892 if (ret > 0)
893 nameserver->counters.sent += 1;
894
895 if (ret == 0 || errno == EAGAIN) {
896 /* nothing written, let's update the poller that we wanted to send
897 * but we were not able to */
898 fd_want_send(fd);
899 fd_cant_send(fd);
900 }
901 }
902
903 /* update resolution */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200904 resolution->nb_responses = 0;
905 resolution->last_sent_packet = now_ms;
906
907 return 1;
908}
909
910/*
911 * update a resolvers' task timeout for next wake up
912 */
913void dns_update_resolvers_timeout(struct dns_resolvers *resolvers)
914{
915 struct dns_resolution *resolution;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200916 struct dns_requester *requester;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200917
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200918 if ((LIST_ISEMPTY(&resolvers->resolution.curr)) && (LIST_ISEMPTY(&resolvers->resolution.wait))) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200919 resolvers->t->expire = TICK_ETERNITY;
920 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200921 else if (!LIST_ISEMPTY(&resolvers->resolution.curr)) {
922 resolution = LIST_NEXT(&resolvers->resolution.curr, struct dns_resolution *, list);
923 if (!resolvers->t->expire || tick_is_le(resolvers->t->expire, tick_add(resolution->last_sent_packet, resolvers->timeout.retry))) {
924 resolvers->t->expire = tick_add(resolution->last_sent_packet, resolvers->timeout.retry);
925 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200926 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200927 else if (!LIST_ISEMPTY(&resolvers->resolution.wait)) {
928 int valid_period, inter, need_wakeup;
929 struct dns_resolution *res_back;
930 need_wakeup = 0;
931 list_for_each_entry_safe(resolution, res_back, &resolvers->resolution.wait, list) {
932 valid_period = 0;
933 inter = 0;
934
935 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
936
937 switch (obj_type(requester->requester)) {
938 case OBJ_TYPE_SERVER:
939 valid_period = objt_server(requester->requester)->check.inter;
940 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200941 case OBJ_TYPE_SRVRQ:
942 valid_period = objt_dns_srvrq(requester->requester)->inter;
943 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200944 case OBJ_TYPE_NONE:
945 default:
946 continue;
947 }
948
949 if (resolvers->hold.valid < valid_period)
950 inter = resolvers->hold.valid;
951 else
952 inter = valid_period;
953
954 if (tick_is_expired(tick_add(resolution->last_resolution, inter), now_ms)) {
955 switch (obj_type(requester->requester)) {
956 case OBJ_TYPE_SERVER:
957 dns_trigger_resolution(objt_server(requester->requester)->resolution);
958 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +0200959 case OBJ_TYPE_SRVRQ:
960 dns_trigger_resolution(objt_dns_srvrq(requester->requester)->resolution);
961 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200962 case OBJ_TYPE_NONE:
963 default:
964 ;;
965 }
966 }
967 else {
968 need_wakeup = 1;
969 }
970 }
971 /* in such case, we wake up in 1s */
972 if (need_wakeup) {
973 int r = 1000;
974
975 resolution = LIST_NEXT(&resolvers->resolution.wait, struct dns_resolution *, list);
976 if (tick_is_le(resolvers->t->expire, tick_add(now_ms, r)))
977 resolvers->t->expire = tick_add(now_ms, r);
978 resolvers->t->expire = tick_add(now_ms, 1000);
979 }
980 }
981
982 task_queue(resolvers->t);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200983}
984
985/*
986 * Analyse, re-build and copy the name <name> from the DNS response packet <buffer>.
987 * <name> must point to the 'data_len' information or pointer 'c0' for compressed data.
988 * The result is copied into <dest>, ensuring we don't overflow using <dest_len>
989 * Returns the number of bytes the caller can move forward. If 0 it means an error occured
990 * while parsing the name.
991 * <offset> is the number of bytes the caller could move forward.
992 */
993int dns_read_name(unsigned char *buffer, unsigned char *bufend, unsigned char *name, char *destination, int dest_len, int *offset)
994{
995 int nb_bytes = 0, n = 0;
996 int label_len;
997 unsigned char *reader = name;
998 char *dest = destination;
999
1000 while (1) {
1001 /* name compression is in use */
1002 if ((*reader & 0xc0) == 0xc0) {
1003 /* a pointer must point BEFORE current position */
1004 if ((buffer + reader[1]) > reader) {
1005 goto out_error;
1006 }
1007
1008 n = dns_read_name(buffer, bufend, buffer + reader[1], dest, dest_len - nb_bytes, offset);
1009 if (n == 0)
1010 goto out_error;
1011
1012 dest += n;
1013 nb_bytes += n;
1014 goto out;
1015 }
1016
1017 label_len = *reader;
1018 if (label_len == 0)
1019 goto out;
1020 /* Check if:
1021 * - we won't read outside the buffer
1022 * - there is enough place in the destination
1023 */
1024 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
1025 goto out_error;
1026
1027 /* +1 to take label len + label string */
1028 label_len += 1;
1029
1030 memcpy(dest, reader, label_len);
1031
1032 dest += label_len;
1033 nb_bytes += label_len;
1034 reader += label_len;
1035 }
1036
1037 out:
1038 /* offset computation:
1039 * parse from <name> until finding either NULL or a pointer "c0xx"
1040 */
1041 reader = name;
1042 *offset = 0;
1043 while (reader < bufend) {
1044 if ((reader[0] & 0xc0) == 0xc0) {
1045 *offset += 2;
1046 break;
1047 }
1048 else if (*reader == 0) {
1049 *offset += 1;
1050 break;
1051 }
1052 *offset += 1;
1053 ++reader;
1054 }
1055
1056 return nb_bytes;
1057
1058 out_error:
1059 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001060}
1061
1062/*
1063 * Function to validate that the buffer DNS response provided in <resp> and
1064 * finishing before <bufend> is valid from a DNS protocol point of view.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001065 *
Baptiste Assmann729c9012017-05-22 15:13:10 +02001066 * The result is stored in <resolution>' response, buf_response, response_query_records
1067 * and response_answer_records members.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001068 *
1069 * This function returns one of the DNS_RESP_* code to indicate the type of
1070 * error found.
Baptiste Assmann325137d2015-04-13 23:40:55 +02001071 */
Baptiste Assmann9d8dbbc2017-08-18 23:35:08 +02001072int dns_validate_dns_response(unsigned char *resp, unsigned char *bufend, struct dns_resolution *resolution, int max_answer_records)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001073{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001074 unsigned char *reader;
1075 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001076 int len, flags, offset;
1077 int dns_query_record_id;
Baptiste Assmann69fce672017-05-04 08:37:45 +02001078 int nb_saved_records;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001079 struct dns_query_item *dns_query;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001080 struct dns_answer_item *dns_answer_record, *tmp_record;
Baptiste Assmann729c9012017-05-22 15:13:10 +02001081 struct dns_response_packet *dns_p;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001082 int found = 0;
Olivier Houchard8da5f982017-08-04 18:35:36 +02001083 int i;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001084
1085 reader = resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001086 len = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001087 previous_dname = NULL;
Baptiste Assmann251abb92017-08-11 09:58:27 +02001088 dns_query = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001089
Baptiste Assmann729c9012017-05-22 15:13:10 +02001090 /* initialization of response buffer and structure */
1091 dns_p = &resolution->response;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001092
1093 /* query id */
1094 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001095 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001096 dns_p->header.id = reader[0] * 256 + reader[1];
1097 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001098
1099 /*
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001100 * flags and rcode are stored over 2 bytes
Baptiste Assmann3440f0d2015-09-02 22:08:38 +02001101 * First byte contains:
1102 * - response flag (1 bit)
1103 * - opcode (4 bits)
1104 * - authoritative (1 bit)
1105 * - truncated (1 bit)
1106 * - recursion desired (1 bit)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001107 */
Baptiste Assmann3440f0d2015-09-02 22:08:38 +02001108 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001109 return DNS_RESP_INVALID;
1110
Baptiste Assmann3440f0d2015-09-02 22:08:38 +02001111 flags = reader[0] * 256 + reader[1];
1112
Baptiste Assmann3440f0d2015-09-02 22:08:38 +02001113 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
1114 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001115 return DNS_RESP_NX_DOMAIN;
Baptiste Assmann3440f0d2015-09-02 22:08:38 +02001116 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001117 return DNS_RESP_REFUSED;
1118
1119 return DNS_RESP_ERROR;
1120 }
1121
Baptiste Assmann3440f0d2015-09-02 22:08:38 +02001122 /* move forward 2 bytes for flags */
1123 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001124
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001125 /* 2 bytes for question count */
1126 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001127 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001128 dns_p->header.qdcount = reader[0] * 256 + reader[1];
1129 /* (for now) we send one query only, so we expect only one in the response too */
1130 if (dns_p->header.qdcount != 1)
1131 return DNS_RESP_QUERY_COUNT_ERROR;
1132 if (dns_p->header.qdcount > DNS_MAX_QUERY_RECORDS)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001133 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001134 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001135
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001136 /* 2 bytes for answer count */
1137 if (reader + 2 >= bufend)
1138 return DNS_RESP_INVALID;
1139 dns_p->header.ancount = reader[0] * 256 + reader[1];
1140 if (dns_p->header.ancount == 0)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001141 return DNS_RESP_ANCOUNT_ZERO;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001142 /* check if too many records are announced */
Baptiste Assmann9d8dbbc2017-08-18 23:35:08 +02001143 if (dns_p->header.ancount > max_answer_records)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001144 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001145 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001146
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001147 /* 2 bytes authority count */
1148 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001149 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001150 dns_p->header.nscount = reader[0] * 256 + reader[1];
1151 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001152
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001153 /* 2 bytes additional count */
1154 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001155 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001156 dns_p->header.arcount = reader[0] * 256 + reader[1];
1157 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001158
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001159 /* parsing dns queries */
1160 LIST_INIT(&dns_p->query_list);
1161 for (dns_query_record_id = 0; dns_query_record_id < dns_p->header.qdcount; dns_query_record_id++) {
1162 /* use next pre-allocated dns_query_item after ensuring there is
1163 * still one available.
1164 * It's then added to our packet query list.
1165 */
1166 if (dns_query_record_id > DNS_MAX_QUERY_RECORDS)
1167 return DNS_RESP_INVALID;
Baptiste Assmann729c9012017-05-22 15:13:10 +02001168 dns_query = &resolution->response_query_records[dns_query_record_id];
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001169 LIST_ADDQ(&dns_p->query_list, &dns_query->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001170
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001171 /* name is a NULL terminated string in our case, since we have
1172 * one query per response and the first one can't be compressed
1173 * (using the 0x0c format)
1174 */
1175 offset = 0;
1176 len = dns_read_name(resp, bufend, reader, dns_query->name, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001177
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001178 if (len == 0)
1179 return DNS_RESP_INVALID;
1180
1181 reader += offset;
1182 previous_dname = dns_query->name;
1183
1184 /* move forward 2 bytes for question type */
1185 if (reader + 2 >= bufend)
1186 return DNS_RESP_INVALID;
1187 dns_query->type = reader[0] * 256 + reader[1];
1188 reader += 2;
1189
1190 /* move forward 2 bytes for question class */
1191 if (reader + 2 >= bufend)
1192 return DNS_RESP_INVALID;
1193 dns_query->class = reader[0] * 256 + reader[1];
1194 reader += 2;
1195 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001196
Baptiste Assmann251abb92017-08-11 09:58:27 +02001197 /* TRUNCATED flag must be checked after we could read the query type
1198 * because a TRUNCATED SRV query type response can still be exploited
1199 */
1200 if (dns_query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED)
1201 return DNS_RESP_TRUNCATED;
1202
Baptiste Assmann325137d2015-04-13 23:40:55 +02001203 /* now parsing response records */
Baptiste Assmann69fce672017-05-04 08:37:45 +02001204 nb_saved_records = 0;
Olivier Houchard8da5f982017-08-04 18:35:36 +02001205 for (i = 0; i < dns_p->header.ancount; i++) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001206 if (reader >= bufend)
1207 return DNS_RESP_INVALID;
1208
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001209 dns_answer_record = pool_alloc2(dns_answer_item_pool);
1210 if (dns_answer_record == NULL)
1211 return (DNS_RESP_INVALID);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001212
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001213 offset = 0;
1214 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001215
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001216 if (len == 0) {
1217 free_dns_answer_item(dns_answer_record);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001218 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001219 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001220
1221 /* check if the current record dname is valid.
1222 * previous_dname points either to queried dname or last CNAME target
1223 */
Baptiste Assmannddc8ce62017-08-11 10:31:22 +02001224 if (dns_query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001225 free_dns_answer_item(dns_answer_record);
1226 if (i == 0) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001227 /* first record, means a mismatch issue between queried dname
1228 * and dname found in the first record */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001229 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001230 } else {
1231 /* if not the first record, this means we have a CNAME resolution
1232 * error */
1233 return DNS_RESP_CNAME_ERROR;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001234 }
1235
Baptiste Assmann325137d2015-04-13 23:40:55 +02001236 }
1237
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001238 memcpy(dns_answer_record->name, tmpname, len);
1239 dns_answer_record->name[len] = 0;
Baptiste Assmann2359ff12015-08-07 11:24:05 +02001240
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001241 reader += offset;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001242 if (reader >= bufend) {
1243 free_dns_answer_item(dns_answer_record);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001244 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001245 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001246
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001247 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001248 if (reader + 2 > bufend) {
1249 free_dns_answer_item(dns_answer_record);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001250 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001251 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001252 dns_answer_record->type = reader[0] * 256 + reader[1];
1253 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001254
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001255 /* 2 bytes for class (2) */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001256 if (reader + 2 > bufend) {
1257 free_dns_answer_item(dns_answer_record);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001258 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001259 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001260 dns_answer_record->class = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +02001261 reader += 2;
1262
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001263 /* 4 bytes for ttl (4) */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001264 if (reader + 4 > bufend) {
1265 free_dns_answer_item(dns_answer_record);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001266 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001267 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001268 dns_answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1269 + reader[2] * 256 + reader[3];
1270 reader += 4;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001271
1272 /* now reading data len */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001273 if (reader + 2 > bufend) {
1274 free_dns_answer_item(dns_answer_record);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001275 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001276 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001277 dns_answer_record->data_len = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +02001278
1279 /* move forward 2 bytes for data len */
1280 reader += 2;
1281
1282 /* analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001283 switch (dns_answer_record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001284 case DNS_RTYPE_A:
1285 /* ipv4 is stored on 4 bytes */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001286 if (dns_answer_record->data_len != 4) {
1287 free_dns_answer_item(dns_answer_record);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001288 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001289 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001290 dns_answer_record->address.sa_family = AF_INET;
1291 memcpy(&(((struct sockaddr_in *)&dns_answer_record->address)->sin_addr),
1292 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001293 break;
1294
1295 case DNS_RTYPE_CNAME:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001296 /* check if this is the last record and update the caller about the status:
1297 * no IP could be found and last record was a CNAME. Could be triggered
1298 * by a wrong query type
1299 *
1300 * + 1 because dns_answer_record_id starts at 0 while number of answers
1301 * is an integer and starts at 1.
1302 */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001303 if (i + 1 == dns_p->header.ancount) {
1304 free_dns_answer_item(dns_answer_record);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001305 return DNS_RESP_CNAME_ERROR;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001306 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001307
1308 offset = 0;
1309 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
1310
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001311 if (len == 0) {
1312 free_dns_answer_item(dns_answer_record);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001313 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001314 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001315
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001316 memcpy(dns_answer_record->target, tmpname, len);
1317 dns_answer_record->target[len] = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001318
1319 previous_dname = dns_answer_record->target;
1320
Baptiste Assmann325137d2015-04-13 23:40:55 +02001321 break;
1322
Olivier Houchard8da5f982017-08-04 18:35:36 +02001323
1324 case DNS_RTYPE_SRV:
1325 /*
1326 * Answer must contain :
1327 * - 2 bytes for the priority
1328 * - 2 bytes for the weight
1329 * - 2 bytes for the port
1330 * - the target hostname
1331 */
1332 if (dns_answer_record->data_len <= 6) {
1333 free_dns_answer_item(dns_answer_record);
1334 return DNS_RESP_INVALID;
1335 }
Willy Tarreaud5370e12017-09-19 14:59:52 +02001336 dns_answer_record->priority = read_n16(reader);
Olivier Houchard8da5f982017-08-04 18:35:36 +02001337 reader += sizeof(uint16_t);
Willy Tarreaud5370e12017-09-19 14:59:52 +02001338 dns_answer_record->weight = read_n16(reader);
Olivier Houchard8da5f982017-08-04 18:35:36 +02001339 reader += sizeof(uint16_t);
Willy Tarreaud5370e12017-09-19 14:59:52 +02001340 dns_answer_record->port = read_n16(reader);
Olivier Houchard8da5f982017-08-04 18:35:36 +02001341 reader += sizeof(uint16_t);
1342 offset = 0;
1343 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
1344 if (len == 0) {
1345 free_dns_answer_item(dns_answer_record);
1346 return DNS_RESP_INVALID;
1347 }
Olivier Houchard8da5f982017-08-04 18:35:36 +02001348 dns_answer_record->data_len = len;
1349 memcpy(dns_answer_record->target, tmpname, len);
1350 dns_answer_record->target[len] = 0;
1351 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001352 case DNS_RTYPE_AAAA:
1353 /* ipv6 is stored on 16 bytes */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001354 if (dns_answer_record->data_len != 16) {
1355 free_dns_answer_item(dns_answer_record);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001356 return DNS_RESP_INVALID;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001357 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001358 dns_answer_record->address.sa_family = AF_INET6;
1359 memcpy(&(((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr),
1360 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001361 break;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001362
Baptiste Assmann325137d2015-04-13 23:40:55 +02001363 } /* switch (record type) */
1364
Baptiste Assmann69fce672017-05-04 08:37:45 +02001365 /* increment the counter for number of records saved into our local response */
1366 nb_saved_records += 1;
1367
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001368 /* move forward dns_answer_record->data_len for analyzing next record in the response */
Baptiste Assmann63a28112017-08-11 10:37:20 +02001369 if (dns_answer_record->type == DNS_RTYPE_SRV)
1370 reader += offset;
1371 else
1372 reader += dns_answer_record->data_len;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001373
1374 /* Lookup to see if we already had this entry */
1375
Olivier Houchard8da5f982017-08-04 18:35:36 +02001376 found = 0;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001377 list_for_each_entry(tmp_record, &dns_p->answer_list, list) {
1378 if (tmp_record->type != dns_answer_record->type)
1379 continue;
1380 switch (tmp_record->type) {
1381 case DNS_RTYPE_A:
1382 if (!memcmp(&((struct sockaddr_in *)&dns_answer_record->address)->sin_addr,
1383 &((struct sockaddr_in *)&tmp_record->address)->sin_addr, sizeof(in_addr_t)))
1384 found = 1;
1385 break;
1386 case DNS_RTYPE_AAAA:
1387 if (!memcmp(&((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr,
1388 &((struct sockaddr_in6 *)&tmp_record->address)->sin6_addr, sizeof(struct in6_addr)))
1389 found = 1;
1390 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02001391 case DNS_RTYPE_SRV:
1392 if (dns_answer_record->data_len == tmp_record->data_len &&
1393 !memcmp(dns_answer_record->target,
1394 tmp_record->target, dns_answer_record->data_len) &&
1395 dns_answer_record->port == tmp_record->port) {
1396 tmp_record->weight = dns_answer_record->weight;
1397 found = 1;
1398 }
1399 break;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001400 default:
1401 break;
1402 }
1403 if (found == 1)
1404 break;
1405 }
1406 if (found == 1) {
1407 tmp_record->last_seen = now.tv_sec;
1408 free_dns_answer_item(dns_answer_record);
1409 } else {
1410 dns_answer_record->last_seen = now.tv_sec;
1411 LIST_ADDQ(&dns_p->answer_list, &dns_answer_record->list);
1412 }
1413
Baptiste Assmann325137d2015-04-13 23:40:55 +02001414 } /* for i 0 to ancount */
1415
Baptiste Assmann96972bc2015-09-09 00:46:58 +02001416
Baptiste Assmann69fce672017-05-04 08:37:45 +02001417 /* save the number of records we really own */
1418 dns_p->header.ancount = nb_saved_records;
1419
Baptiste Assmann325137d2015-04-13 23:40:55 +02001420 return DNS_RESP_VALID;
1421}
1422
1423/*
1424 * search dn_name resolution in resp.
1425 * If existing IP not found, return the first IP matching family_priority,
1426 * otherwise, first ip found
1427 * The following tasks are the responsibility of the caller:
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001428 * - <dns_p> contains an error free DNS response
Baptiste Assmann325137d2015-04-13 23:40:55 +02001429 * For both cases above, dns_validate_dns_response is required
1430 * returns one of the DNS_UPD_* code
1431 */
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001432#define DNS_MAX_IP_REC 20
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001433int dns_get_ip_from_response(struct dns_response_packet *dns_p,
Baptiste Assmann42746372017-05-03 12:12:02 +02001434 struct dns_options *dns_opts, void *currentip,
Thierry Fournierada34842016-02-17 21:25:09 +01001435 short currentip_sin_family,
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001436 void **newip, short *newip_sin_family,
1437 void *owner)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001438{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001439 struct dns_answer_item *record;
Thierry Fournierada34842016-02-17 21:25:09 +01001440 int family_priority;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001441 int currentip_found;
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001442 unsigned char *newip4, *newip6;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001443 int currentip_sel;
1444 int j;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001445 int score, max_score;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001446
Baptiste Assmann42746372017-05-03 12:12:02 +02001447 family_priority = dns_opts->family_prio;
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001448 *newip = newip4 = newip6 = NULL;
1449 currentip_found = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001450 *newip_sin_family = AF_UNSPEC;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001451 max_score = -1;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001452
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001453 /* Select an IP regarding configuration preference.
1454 * Top priority is the prefered network ip version,
1455 * second priority is the prefered network.
1456 * the last priority is the currently used IP,
1457 *
1458 * For these three priorities, a score is calculated. The
1459 * weight are:
Baptistefc725902016-12-26 23:21:08 +01001460 * 8 - prefered netwok ip version.
1461 * 4 - prefered network.
1462 * 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 +01001463 * 1 - current ip.
1464 * The result with the biggest score is returned.
1465 */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001466
1467 list_for_each_entry(record, &dns_p->answer_list, list) {
1468 void *ip;
1469 unsigned char ip_type;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001470
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001471 if (record->type == DNS_RTYPE_A) {
1472 ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
1473 ip_type = AF_INET;
1474 } else if (record->type == DNS_RTYPE_AAAA) {
1475 ip_type = AF_INET6;
1476 ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
1477 } else
1478 continue;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001479 score = 0;
1480
1481 /* Check for prefered ip protocol. */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001482 if (ip_type == family_priority)
Baptistefc725902016-12-26 23:21:08 +01001483 score += 8;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001484
1485 /* Check for prefered network. */
Baptiste Assmann42746372017-05-03 12:12:02 +02001486 for (j = 0; j < dns_opts->pref_net_nb; j++) {
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001487
1488 /* Compare only the same adresses class. */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001489 if (dns_opts->pref_net[j].family != ip_type)
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001490 continue;
1491
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001492 if ((ip_type == AF_INET &&
1493 in_net_ipv4(ip,
Baptiste Assmann42746372017-05-03 12:12:02 +02001494 &dns_opts->pref_net[j].mask.in4,
1495 &dns_opts->pref_net[j].addr.in4)) ||
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001496 (ip_type == AF_INET6 &&
1497 in_net_ipv6(ip,
Baptiste Assmann42746372017-05-03 12:12:02 +02001498 &dns_opts->pref_net[j].mask.in6,
1499 &dns_opts->pref_net[j].addr.in6))) {
Baptistefc725902016-12-26 23:21:08 +01001500 score += 4;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001501 break;
1502 }
1503 }
1504
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001505 /* Check if the IP found in the record is already affected to a member of a group.
1506 * If yes, the score should be incremented by 2.
1507 */
1508 if (owner) {
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001509 if (snr_check_ip_callback(owner, ip, &ip_type))
1510 {
1511 continue;
1512 }
Baptistefc725902016-12-26 23:21:08 +01001513 }
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001514 /* Check for current ip matching. */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001515 if (ip_type == currentip_sin_family &&
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001516 ((currentip_sin_family == AF_INET &&
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001517 memcmp(ip, currentip, 4) == 0) ||
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001518 (currentip_sin_family == AF_INET6 &&
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001519 memcmp(ip, currentip, 16) == 0))) {
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001520 score += 1;
1521 currentip_sel = 1;
1522 } else
1523 currentip_sel = 0;
1524
Baptistefc725902016-12-26 23:21:08 +01001525
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001526 /* Keep the address if the score is better than the previous
Baptistefc725902016-12-26 23:21:08 +01001527 * score. The maximum score is 15, if this value is reached,
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001528 * we break the parsing. Implicitly, this score is reached
1529 * the ip selected is the current ip.
1530 */
1531 if (score > max_score) {
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001532 if (ip_type == AF_INET)
1533 newip4 = ip;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001534 else
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001535 newip6 = ip;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001536 currentip_found = currentip_sel;
Baptistefc725902016-12-26 23:21:08 +01001537 if (score == 15)
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001538 return DNS_UPD_NO;
1539 max_score = score;
1540 }
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001541
1542
1543 } /* list for each record entries */
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001544
Baptiste Assmann0453a1d2015-09-09 00:51:08 +02001545 /* no IP found in the response */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001546 if (!newip4 && !newip6)
Baptiste Assmann0453a1d2015-09-09 00:51:08 +02001547 return DNS_UPD_NO_IP_FOUND;
Baptiste Assmann0453a1d2015-09-09 00:51:08 +02001548
Baptiste Assmann325137d2015-04-13 23:40:55 +02001549 /* case when the caller looks first for an IPv4 address */
1550 if (family_priority == AF_INET) {
1551 if (newip4) {
1552 *newip = newip4;
1553 *newip_sin_family = AF_INET;
1554 if (currentip_found == 1)
1555 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001556 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001557 }
1558 else if (newip6) {
1559 *newip = newip6;
1560 *newip_sin_family = AF_INET6;
1561 if (currentip_found == 1)
1562 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001563 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001564 }
1565 }
1566 /* case when the caller looks first for an IPv6 address */
1567 else if (family_priority == AF_INET6) {
1568 if (newip6) {
1569 *newip = newip6;
1570 *newip_sin_family = AF_INET6;
1571 if (currentip_found == 1)
1572 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001573 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001574 }
1575 else if (newip4) {
1576 *newip = newip4;
1577 *newip_sin_family = AF_INET;
1578 if (currentip_found == 1)
1579 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001580 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001581 }
1582 }
1583 /* case when the caller have no preference (we prefer IPv6) */
1584 else if (family_priority == AF_UNSPEC) {
1585 if (newip6) {
1586 *newip = newip6;
1587 *newip_sin_family = AF_INET6;
1588 if (currentip_found == 1)
1589 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001590 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001591 }
1592 else if (newip4) {
1593 *newip = newip4;
1594 *newip_sin_family = AF_INET;
1595 if (currentip_found == 1)
1596 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001597 goto return_DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001598 }
1599 }
1600
1601 /* no reason why we should change the server's IP address */
1602 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001603
1604 return_DNS_UPD_SRVIP_NOT_FOUND:
1605 list_for_each_entry(record, &dns_p->answer_list, list) {
1606 /* move the first record to the end of the list, for internal round robin */
1607 if (record) {
1608 LIST_DEL(&record->list);
1609 LIST_ADDQ(&dns_p->answer_list, &record->list);
1610 break;
1611 }
1612 }
1613 return DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001614}
1615
1616/*
1617 * returns the query id contained in a DNS response
1618 */
Thiago Farinab1af23e2016-01-20 23:46:34 +01001619unsigned short dns_response_get_query_id(unsigned char *resp)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001620{
1621 /* read the query id from the response */
1622 return resp[0] * 256 + resp[1];
1623}
1624
1625/*
1626 * used during haproxy's init phase
1627 * parses resolvers sections and initializes:
1628 * - task (time events) for each resolvers section
1629 * - the datagram layer (network IO events) for each nameserver
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001630 * It takes one argument:
1631 * - close_first takes 2 values: 0 or 1. If 1, the connection is closed first.
Baptiste Assmann325137d2015-04-13 23:40:55 +02001632 * returns:
1633 * 0 in case of error
1634 * 1 when no error
1635 */
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001636int dns_init_resolvers(int close_socket)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001637{
1638 struct dns_resolvers *curr_resolvers;
1639 struct dns_nameserver *curnameserver;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001640 struct dns_resolution *resolution, *res_back;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001641 struct dgram_conn *dgram;
1642 struct task *t;
1643 int fd;
1644
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02001645 /* initialize our DNS resolution cache */
1646 dns_lru_tree = lru64_new(dns_cache_size);
1647
Baptiste Assmann325137d2015-04-13 23:40:55 +02001648 /* give a first random value to our dns query_id seed */
1649 dns_query_id_seed = random();
1650
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001651 /* Initialize the answer items pool */
1652 dns_answer_item_pool = create_pool("dns_answer_item",
1653 sizeof(struct dns_answer_item), MEM_F_SHARED);
1654 if (dns_answer_item_pool == NULL) {
1655 Alert("Failed to create the dns answer items pool");
1656 return 0;
1657 }
1658
Baptiste Assmann325137d2015-04-13 23:40:55 +02001659 /* run through the resolvers section list */
1660 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
1661 /* create the task associated to the resolvers section */
1662 if ((t = task_new()) == NULL) {
1663 Alert("Starting [%s] resolvers: out of memory.\n", curr_resolvers->id);
1664 return 0;
1665 }
1666
1667 /* update task's parameters */
1668 t->process = dns_process_resolve;
1669 t->context = curr_resolvers;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001670
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001671 /* no need to keep the new task if one is already affected to our resolvers
1672 * section */
1673 if (!curr_resolvers->t)
1674 curr_resolvers->t = t;
1675 else
1676 task_free(t);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001677
1678 list_for_each_entry(curnameserver, &curr_resolvers->nameserver_list, list) {
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001679 dgram = NULL;
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001680
1681 if (close_socket == 1) {
1682 if (curnameserver->dgram) {
Frédéric Lécaille64920532017-05-12 09:57:15 +02001683 fd_delete(curnameserver->dgram->t.sock.fd);
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001684 memset(curnameserver->dgram, '\0', sizeof(*dgram));
1685 dgram = curnameserver->dgram;
1686 }
1687 }
1688
1689 /* allocate memory only if it has not already been allocated
1690 * by a previous call to this function */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001691
Baptiste Assmann5cd1b922017-02-02 22:44:15 +01001692 if (!dgram && (dgram = calloc(1, sizeof(*dgram))) == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001693 Alert("Starting [%s/%s] nameserver: out of memory.\n", curr_resolvers->id,
1694 curnameserver->id);
1695 return 0;
1696 }
1697 /* update datagram's parameters */
1698 dgram->owner = (void *)curnameserver;
1699 dgram->data = &resolve_dgram_cb;
1700
1701 /* create network UDP socket for this nameserver */
Frédéric Lécaille5e5bc9f2017-04-11 08:46:37 +02001702 if ((fd = socket(curnameserver->addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001703 Alert("Starting [%s/%s] nameserver: can't create socket.\n", curr_resolvers->id,
1704 curnameserver->id);
1705 free(dgram);
1706 dgram = NULL;
1707 return 0;
1708 }
1709
1710 /* "connect" the UDP socket to the name server IP */
Baptiste Assmann8c62c472015-09-21 20:55:08 +02001711 if (connect(fd, (struct sockaddr*)&curnameserver->addr, get_addr_len(&curnameserver->addr)) == -1) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001712 Alert("Starting [%s/%s] nameserver: can't connect socket.\n", curr_resolvers->id,
1713 curnameserver->id);
1714 close(fd);
1715 free(dgram);
1716 dgram = NULL;
1717 return 0;
1718 }
1719
1720 /* make the socket non blocking */
1721 fcntl(fd, F_SETFL, O_NONBLOCK);
1722
1723 /* add the fd in the fd list and update its parameters */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001724 fdtab[fd].owner = dgram;
1725 fdtab[fd].iocb = dgram_fd_handler;
Christopher Faulet576c5aa2017-09-05 09:51:57 +02001726 fd_insert(fd);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001727 fd_want_recv(fd);
1728 dgram->t.sock.fd = fd;
1729
1730 /* update nameserver's datagram property */
1731 curnameserver->dgram = dgram;
1732
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001733 continue;
1734 }
1735
1736 if (close_socket == 0)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001737 continue;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001738
1739 /* now, we can trigger DNS resolution */
1740 list_for_each_entry_safe(resolution, res_back, &curr_resolvers->resolution.wait, list) {
1741 /* if there is no requester in the wait queue, no need to trigger the resolution */
1742 if (LIST_ISEMPTY(&resolution->requester.wait))
1743 continue;
1744
1745 dns_trigger_resolution(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001746 }
1747
1748 /* task can be queued */
1749 task_queue(t);
1750 }
1751
1752 return 1;
1753}
1754
1755/*
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001756 * Allocate a pool of resolution to a resolvers section.
1757 * Each resolution is associated with a UUID.
1758 *
1759 * Return code:
1760 * - 0 if everything went smoothly
1761 * - -1 if an error occured
1762 */
1763int dns_alloc_resolution_pool(struct dns_resolvers *resolvers)
1764{
1765 int i;
1766 struct dns_resolution *resolution;
1767
1768 /* return if a pool has already been set for this resolvers */
1769 if (!LIST_ISEMPTY(&resolvers->resolution.pool)) {
1770 return 0;
1771 }
1772
1773 for (i = 0; i < resolvers->resolution_pool_size; i++) {
1774 resolution = dns_alloc_resolution();
1775 if (!resolution) {
1776 Alert("Starting [%s] resolvers: can't allocate memory for DNS resolution pool.\n", resolvers->id);
1777 return -1;
1778 }
1779 resolution->uuid = i;
1780 LIST_ADDQ(&resolvers->resolution.pool, &resolution->list);
1781 }
1782
1783 return 0;
1784}
1785
1786/*
Baptiste Assmann325137d2015-04-13 23:40:55 +02001787 * Forge a DNS query. It needs the following information from the caller:
1788 * - <query_id>: the DNS query id corresponding to this query
1789 * - <query_type>: DNS_RTYPE_* request DNS record type (A, AAAA, ANY, etc...)
1790 * - <hostname_dn>: hostname in domain name format
1791 * - <hostname_dn_len>: length of <hostname_dn>
1792 * To store the query, the caller must pass a buffer <buf> and its size <bufsize>
1793 *
1794 * the DNS query is stored in <buf>
1795 * returns:
1796 * -1 if <buf> is too short
1797 */
Baptiste Assmann2af08fe2017-08-14 00:13:01 +02001798int dns_build_query(int query_id, int query_type, unsigned int accepted_payload_size, char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001799{
1800 struct dns_header *dns;
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001801 struct dns_question qinfo;
Baptiste Assmann2af08fe2017-08-14 00:13:01 +02001802 struct dns_additional_record edns;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001803 char *ptr, *bufend;
1804
1805 memset(buf, '\0', bufsize);
1806 ptr = buf;
1807 bufend = buf + bufsize;
1808
1809 /* check if there is enough room for DNS headers */
1810 if (ptr + sizeof(struct dns_header) >= bufend)
1811 return -1;
1812
1813 /* set dns query headers */
1814 dns = (struct dns_header *)ptr;
1815 dns->id = (unsigned short) htons(query_id);
Nenad Merdanovic8ab79422016-07-13 14:03:43 +02001816 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 +02001817 dns->qdcount = htons(1); /* 1 question */
1818 dns->ancount = 0;
1819 dns->nscount = 0;
Baptiste Assmann2af08fe2017-08-14 00:13:01 +02001820 dns->arcount = htons(1);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001821
1822 /* move forward ptr */
1823 ptr += sizeof(struct dns_header);
1824
1825 /* check if there is enough room for query hostname */
1826 if ((ptr + hostname_dn_len) >= bufend)
1827 return -1;
1828
1829 /* set up query hostname */
1830 memcpy(ptr, hostname_dn, hostname_dn_len);
1831 ptr[hostname_dn_len + 1] = '\0';
1832
1833 /* move forward ptr */
1834 ptr += (hostname_dn_len + 1);
1835
1836 /* check if there is enough room for query hostname*/
1837 if (ptr + sizeof(struct dns_question) >= bufend)
1838 return -1;
1839
1840 /* set up query info (type and class) */
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001841 qinfo.qtype = htons(query_type);
1842 qinfo.qclass = htons(DNS_RCLASS_IN);
1843 memcpy(ptr, &qinfo, sizeof(qinfo));
Baptiste Assmann325137d2015-04-13 23:40:55 +02001844
1845 ptr += sizeof(struct dns_question);
1846
Baptiste Assmann2af08fe2017-08-14 00:13:01 +02001847 /* check if there is enough room for additional records */
1848 if (ptr + sizeof(edns) >= bufend)
1849 return -1;
1850
1851 /* set the DNS extension */
1852 edns.name = 0;
1853 edns.type = htons(DNS_RTYPE_OPT);
1854 edns.udp_payload_size = htons(accepted_payload_size);
1855 edns.extension = 0;
1856 edns.data_length = 0;
1857 memcpy(ptr, &edns, sizeof(edns));
1858 ptr += sizeof(edns);
1859
Baptiste Assmann325137d2015-04-13 23:40:55 +02001860 return ptr - buf;
1861}
1862
Olivier Houchard8da5f982017-08-04 18:35:36 +02001863/* Turn a domain name label into a string */
1864void dns_dn_label_to_str(char *dn, char *str, int dn_len)
1865{
1866 int remain_size = 0;
1867 int i;
1868
1869 for (i = 0; i < dn_len; i++) {
1870 if (remain_size == 0) {
1871 remain_size = dn[i];
1872 if (i != 0) {
1873 str[i - 1] = '.';
1874
1875 }
1876 } else {
1877 str[i - 1] = dn[i];
1878 remain_size--;
1879 }
1880 }
1881 str[dn_len - 1] = 0;
1882
1883}
1884
Baptiste Assmann325137d2015-04-13 23:40:55 +02001885/*
1886 * turn a string into domain name label:
1887 * www.haproxy.org into 3www7haproxy3org
1888 * if dn memory is pre-allocated, you must provide its size in dn_len
1889 * if dn memory isn't allocated, dn_len must be set to 0.
1890 * In the second case, memory will be allocated.
1891 * in case of error, -1 is returned, otherwise, number of bytes copied in dn
1892 */
Willy Tarreau2100b492015-07-22 16:42:43 +02001893char *dns_str_to_dn_label(const char *string, char *dn, int dn_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001894{
1895 char *c, *d;
1896 int i, offset;
1897
1898 /* offset between string size and theorical dn size */
1899 offset = 1;
1900
1901 /*
1902 * first, get the size of the string turned into its domain name version
1903 * This function also validates the string respect the RFC
1904 */
1905 if ((i = dns_str_to_dn_label_len(string)) == -1)
1906 return NULL;
1907
1908 /* yes, so let's check there is enough memory */
1909 if (dn_len < i + offset)
1910 return NULL;
1911
Willy Tarreaud69d6f32015-07-22 16:45:36 +02001912 i = strlen(string);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001913 memcpy(dn + offset, string, i);
1914 dn[i + offset] = '\0';
1915 /* avoid a '\0' at the beginning of dn string which may prevent the for loop
1916 * below from working.
1917 * Actually, this is the reason of the offset. */
1918 dn[0] = '0';
1919
1920 for (c = dn; *c ; ++c) {
1921 /* c points to the first '0' char or a dot, which we don't want to read */
1922 d = c + offset;
1923 i = 0;
1924 while (*d != '.' && *d) {
1925 i++;
1926 d++;
1927 }
1928 *c = i;
1929
1930 c = d - 1; /* because of c++ of the for loop */
1931 }
1932
1933 return dn;
1934}
1935
1936/*
1937 * compute and return the length of <string> it it were translated into domain name
1938 * label:
1939 * www.haproxy.org into 3www7haproxy3org would return 16
1940 * NOTE: add +1 for '\0' when allocating memory ;)
1941 */
1942int dns_str_to_dn_label_len(const char *string)
1943{
1944 return strlen(string) + 1;
1945}
1946
1947/*
1948 * validates host name:
1949 * - total size
1950 * - each label size individually
1951 * returns:
1952 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1953 * 1 when no error. <err> is left unaffected.
1954 */
1955int dns_hostname_validation(const char *string, char **err)
1956{
1957 const char *c, *d;
1958 int i;
1959
1960 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1961 if (err)
1962 *err = DNS_TOO_LONG_FQDN;
1963 return 0;
1964 }
1965
1966 c = string;
1967 while (*c) {
1968 d = c;
1969
1970 i = 0;
1971 while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) {
1972 i++;
1973 if (!((*d == '-') || (*d == '_') ||
1974 ((*d >= 'a') && (*d <= 'z')) ||
1975 ((*d >= 'A') && (*d <= 'Z')) ||
1976 ((*d >= '0') && (*d <= '9')))) {
1977 if (err)
1978 *err = DNS_INVALID_CHARACTER;
1979 return 0;
1980 }
1981 d++;
1982 }
1983
1984 if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) {
1985 if (err)
1986 *err = DNS_LABEL_TOO_LONG;
1987 return 0;
1988 }
1989
1990 if (*d == '\0')
1991 goto out;
1992
1993 c = ++d;
1994 }
1995 out:
1996 return 1;
1997}
1998
1999/*
2000 * 2 bytes random generator to generate DNS query ID
2001 */
2002uint16_t dns_rnd16(void)
2003{
2004 dns_query_id_seed ^= dns_query_id_seed << 13;
2005 dns_query_id_seed ^= dns_query_id_seed >> 7;
2006 dns_query_id_seed ^= dns_query_id_seed << 17;
2007 return dns_query_id_seed;
2008}
2009
2010
2011/*
2012 * function called when a timeout occurs during name resolution process
2013 * if max number of tries is reached, then stop, otherwise, retry.
2014 */
2015struct task *dns_process_resolve(struct task *t)
2016{
2017 struct dns_resolvers *resolvers = t->context;
2018 struct dns_resolution *resolution, *res_back;
Baptiste Assmann060e5732016-01-06 02:01:59 +01002019 int res_preferred_afinet, res_preferred_afinet6;
Baptiste Assmann42746372017-05-03 12:12:02 +02002020 struct dns_options *dns_opts = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002021
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002022 /* if both there is no resolution in the run queue, we can re-schedule a wake up */
2023 if (LIST_ISEMPTY(&resolvers->resolution.curr)) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02002024 /* no first entry, so wake up was useless */
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002025 dns_update_resolvers_timeout(resolvers);
Baptiste Assmann325137d2015-04-13 23:40:55 +02002026 return t;
2027 }
2028
2029 /* look for the first resolution which is not expired */
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002030 list_for_each_entry_safe(resolution, res_back, &resolvers->resolution.curr, list) {
2031 struct dns_requester *requester = NULL;
2032
Baptiste Assmann325137d2015-04-13 23:40:55 +02002033 /* when we find the first resolution in the future, then we can stop here */
2034 if (tick_is_le(now_ms, resolution->last_sent_packet))
2035 goto out;
2036
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002037 if (LIST_ISEMPTY(&resolution->requester.curr))
2038 goto out;
2039
Baptiste Assmann325137d2015-04-13 23:40:55 +02002040 /*
2041 * if current resolution has been tried too many times and finishes in timeout
2042 * we update its status and remove it from the list
2043 */
Baptiste Assmannf778bb42015-09-09 00:54:38 +02002044 if (resolution->try <= 0) {
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002045 struct dns_requester *tmprequester;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002046 /* clean up resolution information and remove from the list */
2047 dns_reset_resolution(resolution);
2048
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002049 LIST_DEL(&resolution->list);
2050 LIST_ADDQ(&resolvers->resolution.wait, &resolution->list);
2051
2052 if (resolution->status != RSLV_STATUS_TIMEOUT) {
2053 resolution->status = RSLV_STATUS_TIMEOUT;
2054 resolution->last_status_change = now_ms;
2055 }
2056
2057 /* notify the result to the requesters */
2058 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
2059 requester->requester_error_cb(requester, DNS_RESP_TIMEOUT);
2060 LIST_DEL(&requester->list);
2061 LIST_ADDQ(&resolution->requester.wait, &requester->list);
2062 }
Baptiste Assmanne70bc052017-08-21 16:51:09 +02002063
2064 /* this might be triggered by too big UDP packets dropped
2065 * somewhere on the network, so lowering the accepted_payload_size
2066 * announced */
2067 if (resolvers->accepted_payload_size > 1280)
2068 resolvers->accepted_payload_size = 1280;
Baptiste Assmann382824c2016-01-06 01:53:46 +01002069 goto out;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002070 }
2071
Baptiste Assmannf778bb42015-09-09 00:54:38 +02002072 resolution->try -= 1;
2073
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002074 /* running queue is empty, nothing to do but wait */
2075 if (LIST_ISEMPTY(&resolution->requester.curr))
2076 goto out;
2077
2078 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
2079
2080 switch (obj_type(requester->requester)) {
2081 case OBJ_TYPE_SERVER:
2082 dns_opts = &(objt_server(requester->requester)->dns_opts);
Olivier Houchard8da5f982017-08-04 18:35:36 +02002083 res_preferred_afinet = dns_opts->family_prio == AF_INET && resolution->query_type == DNS_RTYPE_A;
2084 res_preferred_afinet6 = dns_opts->family_prio == AF_INET6 && resolution->query_type == DNS_RTYPE_AAAA;
2085
2086 /* let's change the query type if needed */
2087 if (res_preferred_afinet6) {
2088 /* fallback from AAAA to A */
2089 resolution->query_type = DNS_RTYPE_A;
2090 }
2091 else if (res_preferred_afinet) {
2092 /* fallback from A to AAAA */
2093 resolution->query_type = DNS_RTYPE_AAAA;
2094 }
2095
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002096 break;
2097
Olivier Houchard8da5f982017-08-04 18:35:36 +02002098 case OBJ_TYPE_SRVRQ:
2099 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002100 case OBJ_TYPE_NONE:
2101 default:
2102 /* clean up resolution information and remove from the list */
2103 dns_reset_resolution(resolution);
2104
2105 LIST_DEL(&resolution->list);
2106 LIST_ADDQ(&resolvers->resolution.wait, &resolution->list);
2107
2108 /* notify the result to the requester */
2109 requester->requester_error_cb(requester, DNS_RESP_INTERNAL);
2110 goto out;
2111 }
Baptiste Assmann42746372017-05-03 12:12:02 +02002112
Baptiste Assmann382824c2016-01-06 01:53:46 +01002113 /* resend the DNS query */
2114 dns_send_query(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02002115
Baptiste Assmann382824c2016-01-06 01:53:46 +01002116 /* check if we have more than one resolution in the list */
2117 if (dns_check_resolution_queue(resolvers) > 1) {
2118 /* move the rsolution to the end of the list */
2119 LIST_DEL(&resolution->list);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002120 LIST_ADDQ(&resolvers->resolution.curr, &resolution->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02002121 }
2122 }
2123
2124 out:
2125 dns_update_resolvers_timeout(resolvers);
2126 return t;
2127}
William Lallemand69e96442016-11-19 00:58:54 +01002128
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002129/*
2130 * build a dns cache key composed as follow:
2131 * <query type>#<hostname in domain name format>
2132 * and store it into <str>.
2133 * It's up to the caller to allocate <buf> and to reset it.
2134 * The function returns NULL in case of error (IE <buf> too small) or a pointer
2135 * to buf if successful
2136 */
2137struct chunk *
2138dns_cache_key(int query_type, char *hostname_dn, int hostname_dn_len, struct chunk *buf)
2139{
2140 int len, size;
2141 char *str;
2142
2143 str = buf->str;
2144 len = buf->len;
2145 size = buf->size;
2146
2147 switch (query_type) {
2148 case DNS_RTYPE_A:
2149 if (len + 1 > size)
2150 return NULL;
2151 memcpy(&str[len], "A", 1);
2152 len += 1;
2153 break;
2154 case DNS_RTYPE_AAAA:
2155 if (len + 4 > size)
2156 return NULL;
2157 memcpy(&str[len], "AAAA", 4);
2158 len += 4;
2159 break;
2160 default:
2161 return NULL;
2162 }
2163
2164 if (len + 1 > size)
2165 return NULL;
2166 memcpy(&str[len], "#", 1);
2167 len += 1;
2168
2169 if (len + hostname_dn_len + 1 > size) // +1 for trailing zero
2170 return NULL;
2171 memcpy(&str[len], hostname_dn, hostname_dn_len);
2172 len += hostname_dn_len;
2173 str[len] = '\0';
2174
2175 return buf;
2176}
2177
2178/*
2179 * returns a pointer to a cache entry which may still be considered as up to date
2180 * by the caller.
2181 * returns NULL if no entry can be found or if the data found is outdated.
2182 */
2183struct lru64 *
2184dns_cache_lookup(int query_type, char *hostname_dn, int hostname_dn_len, int valid_period, void *cache_domain) {
2185 struct lru64 *elem = NULL;
2186 struct dns_resolution *resolution = NULL;
2187 struct dns_resolvers *resolvers = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002188 struct dns_requester *requester = NULL;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002189 int inter = 0;
2190 struct chunk *buf = get_trash_chunk();
2191 struct chunk *tmp = NULL;
2192
2193 if (!dns_lru_tree)
2194 return NULL;
2195
2196 chunk_reset(buf);
2197 tmp = dns_cache_key(query_type, hostname_dn, hostname_dn_len, buf);
2198 if (tmp == NULL)
2199 return NULL;
2200
2201 elem = lru64_lookup(XXH64(buf->str, buf->len, 1), dns_lru_tree, cache_domain, 1);
2202
2203 if (!elem || !elem->data)
2204 return NULL;
2205
2206 resolution = elem->data;
2207
2208 /* since we can change the fqdn of a server at run time, it may happen that
2209 * we got an innacurate elem.
2210 * This is because resolution->hostname_dn points to (owner)->hostname_dn (which
2211 * may be changed at run time)
2212 */
2213 if ((hostname_dn_len == resolution->hostname_dn_len) &&
2214 (memcmp(hostname_dn, resolution->hostname_dn, hostname_dn_len) != 0)) {
2215 return NULL;
2216 }
2217
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002218 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
2219
2220 switch (obj_type(requester->requester)) {
2221 case OBJ_TYPE_SERVER:
2222 resolvers = objt_server(requester->requester)->resolvers;
2223 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002224 case OBJ_TYPE_SRVRQ:
2225 resolvers = objt_dns_srvrq(requester->requester)->resolvers;
2226 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002227 case OBJ_TYPE_NONE:
2228 default:
2229 return NULL;
2230 }
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002231
2232 if (!resolvers)
2233 return NULL;
2234
2235 if (resolvers->hold.valid < valid_period)
2236 inter = resolvers->hold.valid;
2237 else
2238 inter = valid_period;
2239
2240 if (!tick_is_expired(tick_add(resolution->last_resolution, inter), now_ms))
2241 return elem;
2242
2243 return NULL;
2244}
2245
Willy Tarreau777b5602016-12-16 18:06:26 +01002246/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
William Lallemand69e96442016-11-19 00:58:54 +01002247static int cli_parse_stat_resolvers(char **args, struct appctx *appctx, void *private)
2248{
2249 struct dns_resolvers *presolvers;
2250
2251 if (*args[3]) {
William Lallemand69e96442016-11-19 00:58:54 +01002252 list_for_each_entry(presolvers, &dns_resolvers, list) {
2253 if (strcmp(presolvers->id, args[3]) == 0) {
Willy Tarreau777b5602016-12-16 18:06:26 +01002254 appctx->ctx.cli.p0 = presolvers;
William Lallemand69e96442016-11-19 00:58:54 +01002255 break;
2256 }
2257 }
Willy Tarreau777b5602016-12-16 18:06:26 +01002258 if (appctx->ctx.cli.p0 == NULL) {
Andjelko Iharosc3680ec2017-07-20 16:49:14 +02002259 appctx->ctx.cli.severity = LOG_ERR;
William Lallemand69e96442016-11-19 00:58:54 +01002260 appctx->ctx.cli.msg = "Can't find that resolvers section\n";
Willy Tarreau3b6e5472016-11-24 15:53:53 +01002261 appctx->st0 = CLI_ST_PRINT;
William Lallemand69e96442016-11-19 00:58:54 +01002262 return 1;
2263 }
2264 }
Willy Tarreau3067bfa2016-12-05 14:50:15 +01002265 return 0;
William Lallemand69e96442016-11-19 00:58:54 +01002266}
2267
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002268/*
2269 * if <resolution> is provided, then the function skips the memory allocation part.
2270 * It does the linking only.
2271 *
2272 * if <resolution> is NULL, the function links a dns resolution to a requester:
2273 * - it allocates memory for the struct requester used to link
2274 * the resolution to the requester
2275 * - it configures the resolution if this is the first requester to be linked to it
2276 * - it updates the requester with a pointer to the resolution
2277 *
2278 * Return code:
2279 * - 0 if everything happened smoothly
2280 * - -1 if an error occured. Of course, no resolution is linked to the requester
2281 */
2282int dns_link_resolution(void *requester, int requester_type, struct dns_resolution *resolution)
2283{
2284 struct dns_resolution *tmpresolution = NULL;
2285 struct dns_requester *tmprequester = NULL;
2286 struct dns_resolvers *resolvers = NULL;
2287 char *hostname_dn = NULL;
2288 int new_resolution;
2289
Olivier Houchard8da5f982017-08-04 18:35:36 +02002290
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002291 if (!resolution) {
2292 tmprequester = calloc(1, sizeof(*tmprequester));
2293 if (!tmprequester)
2294 return -1;
2295
2296 switch (requester_type) {
2297 case OBJ_TYPE_SERVER:
2298 tmprequester->requester = &((struct server *)requester)->obj_type;
2299 hostname_dn = objt_server(tmprequester->requester)->hostname_dn;
2300 resolvers = objt_server(tmprequester->requester)->resolvers;
2301 switch (objt_server(tmprequester->requester)->dns_opts.family_prio) {
2302 case AF_INET:
2303 tmprequester->prefered_query_type = DNS_RTYPE_A;
2304 break;
2305 default:
2306 tmprequester->prefered_query_type = DNS_RTYPE_AAAA;
2307 }
2308
2309 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002310 case OBJ_TYPE_SRVRQ:
2311 tmprequester->requester = &((struct dns_srvrq *)requester)->obj_type;
2312 hostname_dn = objt_dns_srvrq(requester)->hostname_dn;
2313 resolvers = objt_dns_srvrq(requester)->resolvers;
2314 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002315 case OBJ_TYPE_NONE:
2316 default:
2317 free(tmprequester);
2318 return -1;
2319 }
2320
2321 /* get a resolution from the resolvers' wait queue or pool */
2322 tmpresolution = dns_resolution_list_get(resolvers, hostname_dn, tmprequester->prefered_query_type);
2323 if (!tmpresolution) {
2324 free(tmprequester);
2325 return -1;
2326 }
2327 }
2328 else {
2329 tmpresolution = resolution;
2330
2331 switch (requester_type) {
2332 case OBJ_TYPE_SERVER:
2333 tmprequester = ((struct server *)requester)->dns_requester;
2334 resolvers = ((struct server *)requester)->resolvers;
2335 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002336 case OBJ_TYPE_SRVRQ:
2337 tmprequester = objt_dns_srvrq(requester)->dns_requester;
2338 resolvers = objt_dns_srvrq(requester)->resolvers;
2339 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002340 case OBJ_TYPE_NONE:
2341 default:
2342 return -1;
2343 }
2344 }
2345
2346 /* flag this resolution as NEW if applicable (not already linked to any requester).
2347 * this is required to decide which parameters we have to update on the resolution.
2348 * If new, it means we pulled up the resolution from the resolvers' pool.
2349 */
2350 if (LIST_ISEMPTY(&tmpresolution->requester.wait)) {
2351 new_resolution = 1;
2352 }
2353 else
2354 new_resolution = 0;
2355
2356 /* those parameters are related to the requester type */
2357 switch (obj_type(tmprequester->requester)) {
2358 case OBJ_TYPE_SERVER:
2359 /* some parameters should be set only if the resolution is brand new */
2360 if (new_resolution) {
2361 tmpresolution->query_type = tmprequester->prefered_query_type;
2362 tmpresolution->hostname_dn = objt_server(tmprequester->requester)->hostname_dn;
2363 tmpresolution->hostname_dn_len = objt_server(tmprequester->requester)->hostname_dn_len;
2364 }
2365
2366 /* update requester as well, only if we just allocated it */
2367 objt_server(tmprequester->requester)->resolution = tmpresolution;
2368 if (!resolution) {
2369 tmprequester->requester_cb = snr_resolution_cb;
2370 tmprequester->requester_error_cb = snr_resolution_error_cb;
2371 objt_server(tmprequester->requester)->dns_requester = tmprequester;
2372 }
2373 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002374 case OBJ_TYPE_SRVRQ:
2375 /* some parameters should be set only if the resolution is brand new */
2376 if (new_resolution) {
2377 tmpresolution->query_type = DNS_RTYPE_SRV;
2378 tmpresolution->hostname_dn = objt_dns_srvrq(tmprequester->requester)->hostname_dn;
2379 tmpresolution->hostname_dn_len = objt_dns_srvrq(tmprequester->requester)->hostname_dn_len;
2380 }
2381
2382 /* update requester as well, only if we just allocated it */
2383 objt_dns_srvrq(tmprequester->requester)->resolution = tmpresolution;
2384 if (!resolution) {
2385 tmprequester->requester_cb = snr_resolution_cb;
2386 tmprequester->requester_error_cb = snr_resolution_error_cb;
2387 objt_dns_srvrq(tmprequester->requester)->dns_requester = tmprequester;
2388 }
2389 break;
2390
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002391 case OBJ_TYPE_NONE:
2392 default:
2393 free(tmprequester);
2394 return -1;
2395 }
2396
2397 /* update some parameters only if this is a brand new resolution */
2398 if (new_resolution) {
2399 /* move the resolution to the requesters' wait queue */
2400 LIST_DEL(&tmpresolution->list);
2401 LIST_ADDQ(&resolvers->resolution.wait, &tmpresolution->list);
2402
2403 tmpresolution->status = RSLV_STATUS_NONE;
2404 tmpresolution->step = RSLV_STEP_NONE;
2405 tmpresolution->revision = 1;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02002406 LIST_INIT(&tmpresolution->response.answer_list);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002407 }
2408
2409 /* add the requester to the resolution's wait queue */
2410 if (resolution)
2411 LIST_DEL(&tmprequester->list);
2412 LIST_ADDQ(&tmpresolution->requester.wait, &tmprequester->list);
2413
2414 return 0;
2415}
2416
2417/*
2418 * pick up an available resolution from the different resolution list associated to a resolvers section,
2419 * in this order:
2420 * 1. check in resolution.curr for the same hostname and query_type
2421 * 2. check in resolution.wait for the same hostname and query_type
2422 * 3. take an available resolution from resolution.pool
2423 *
2424 * return an available resolution, NULL if none found.
2425 */
2426struct dns_resolution *dns_resolution_list_get(struct dns_resolvers *resolvers, char *hostname_dn, int query_type)
2427{
2428 struct dns_resolution *resolution, *tmpresolution;
2429 struct dns_requester *requester;
2430
Olivier Houchard8da5f982017-08-04 18:35:36 +02002431 if (hostname_dn) {
2432 /* search for same hostname and query type in resolution.curr */
2433 list_for_each_entry_safe(resolution, tmpresolution, &resolvers->resolution.curr, list) {
2434 requester = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002435
Olivier Houchard8da5f982017-08-04 18:35:36 +02002436 if (!LIST_ISEMPTY(&resolution->requester.wait))
2437 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
2438 else if (!LIST_ISEMPTY(&resolution->requester.curr))
2439 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002440
Olivier Houchard8da5f982017-08-04 18:35:36 +02002441 if (!requester)
2442 continue;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002443
Olivier Houchard8da5f982017-08-04 18:35:36 +02002444 if ((query_type == requester->prefered_query_type) &&
2445 (resolution->hostname_dn &&
2446 strcmp(hostname_dn, resolution->hostname_dn) == 0)) {
2447 return resolution;
2448 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002449 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002450
Olivier Houchard8da5f982017-08-04 18:35:36 +02002451 /* search for same hostname and query type in resolution.wait */
2452 list_for_each_entry_safe(resolution, tmpresolution, &resolvers->resolution.wait, list) {
2453 requester = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002454
Olivier Houchard8da5f982017-08-04 18:35:36 +02002455 if (!LIST_ISEMPTY(&resolution->requester.wait))
2456 requester = LIST_NEXT(&resolution->requester.wait, struct dns_requester *, list);
2457 else if (!LIST_ISEMPTY(&resolution->requester.curr))
2458 requester = LIST_NEXT(&resolution->requester.curr, struct dns_requester *, list);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002459
Olivier Houchard8da5f982017-08-04 18:35:36 +02002460 if (!requester)
2461 continue;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002462
Olivier Houchard8da5f982017-08-04 18:35:36 +02002463 if ((query_type == requester->prefered_query_type) &&
2464 (resolution->hostname_dn &&
2465 strcmp(hostname_dn, resolution->hostname_dn) == 0)) {
2466 return resolution;
2467 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002468 }
2469 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002470 /* take the first one (hopefully) from the pool */
2471 list_for_each_entry_safe(resolution, tmpresolution, &resolvers->resolution.pool, list) {
2472 if (LIST_ISEMPTY(&resolution->requester.wait)) {
2473 return resolution;
2474 }
2475 }
2476
2477 return NULL;
2478}
2479
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002480/* This function allocates memory for a DNS resolution structure.
2481 * It's up to the caller to set the parameters
2482 * Returns a pointer to the structure resolution or NULL if memory could
2483 * not be allocated.
2484 */
2485struct dns_resolution *dns_alloc_resolution(void)
2486{
2487 struct dns_resolution *resolution = NULL;
Baptiste Assmann729c9012017-05-22 15:13:10 +02002488 char *buffer = NULL;
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002489
2490 resolution = calloc(1, sizeof(*resolution));
Baptiste Assmann729c9012017-05-22 15:13:10 +02002491 buffer = calloc(1, global.tune.bufsize);
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002492
Baptiste Assmann729c9012017-05-22 15:13:10 +02002493 if (!resolution || !buffer) {
2494 free(buffer);
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002495 free(resolution);
2496 return NULL;
2497 }
2498
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002499 LIST_INIT(&resolution->requester.wait);
2500 LIST_INIT(&resolution->requester.curr);
Baptiste Assmann729c9012017-05-22 15:13:10 +02002501
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002502 return resolution;
2503}
2504
2505/* This function free the memory allocated to a DNS resolution */
2506void dns_free_resolution(struct dns_resolution *resolution)
2507{
2508 free(resolution);
2509
2510 return;
2511}
2512
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002513/* this function free a resolution from its requester(s) and move it back to the pool */
2514void dns_resolution_free(struct dns_resolvers *resolvers, struct dns_resolution *resolution)
2515{
2516 struct dns_requester *requester, *tmprequester;
2517
2518 /* clean up configuration */
2519 dns_reset_resolution(resolution);
2520 resolution->hostname_dn = NULL;
2521 resolution->hostname_dn_len = 0;
2522
2523 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.wait, list) {
2524 LIST_DEL(&requester->list);
2525 }
2526 list_for_each_entry_safe(requester, tmprequester, &resolution->requester.curr, list) {
2527 LIST_DEL(&requester->list);
2528 }
2529
2530 LIST_DEL(&resolution->list);
2531 LIST_ADDQ(&resolvers->resolution.pool, &resolution->list);
2532
2533 return;
2534}
2535
2536/*
2537 * this function remove a requester from a resolution
2538 * and takes care of all the consequences.
2539 * It also cleans up some parameters from the requester
2540 */
2541void dns_rm_requester_from_resolution(struct dns_requester *requester, struct dns_resolution *resolution)
2542{
2543 char *hostname_dn;
2544 struct dns_requester *tmprequester;
2545
2546 /* resolution is still used by other requesters, we need to move
2547 * some pointers to an other requester if needed
2548 */
2549 switch (obj_type(requester->requester)) {
2550 case OBJ_TYPE_SERVER:
2551 hostname_dn = objt_server(requester->requester)->hostname_dn;
2552 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002553 case OBJ_TYPE_SRVRQ:
2554 hostname_dn = objt_dns_srvrq(requester->requester)->hostname_dn;
2555 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002556 case OBJ_TYPE_NONE:
2557 default:
2558 hostname_dn = NULL;
2559 break;
2560 }
2561
2562 if (resolution->hostname_dn != hostname_dn)
2563 return;
2564
2565 /* First, we need to find this other requester */
2566 tmprequester = NULL;
2567 list_for_each_entry(tmprequester, &resolution->requester.wait, list) {
2568 if (tmprequester != requester)
2569 break;
2570 }
2571 if (!tmprequester) {
2572 /* if we can't find it in wait queue, let's get one in run queue */
2573 list_for_each_entry(tmprequester, &resolution->requester.curr, list) {
2574 if (tmprequester != requester)
2575 break;
2576 }
2577 }
2578
2579 /* move hostname_dn related pointers to the next requester */
2580 switch (obj_type(tmprequester->requester)) {
2581 case OBJ_TYPE_SERVER:
2582 resolution->hostname_dn = objt_server(tmprequester->requester)->hostname_dn;
2583 resolution->hostname_dn_len = objt_server(tmprequester->requester)->hostname_dn_len;
2584 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002585 case OBJ_TYPE_SRVRQ:
2586 resolution->hostname_dn = objt_dns_srvrq(tmprequester->requester)->hostname_dn;
2587 resolution->hostname_dn_len = objt_dns_srvrq(tmprequester->requester)->hostname_dn_len;
2588 break;
2589
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002590 case OBJ_TYPE_NONE:
2591 default:
2592 ;;
2593 }
2594
2595
2596 /* clean up the requester */
2597 LIST_DEL(&requester->list);
2598 switch (obj_type(requester->requester)) {
2599 case OBJ_TYPE_SERVER:
2600 objt_server(requester->requester)->resolution = NULL;
2601 break;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002602 case OBJ_TYPE_SRVRQ:
2603 objt_dns_srvrq(requester->requester)->resolution = NULL;
2604 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002605 case OBJ_TYPE_NONE:
2606 default:
2607 ;;
2608 }
2609}
2610
Willy Tarreau777b5602016-12-16 18:06:26 +01002611/* This function dumps counters from all resolvers section and associated name
2612 * servers. It returns 0 if the output buffer is full and it needs to be called
2613 * again, otherwise non-zero. It may limit itself to the resolver pointed to by
2614 * <cli.p0> if it's not null.
William Lallemand69e96442016-11-19 00:58:54 +01002615 */
2616static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2617{
2618 struct stream_interface *si = appctx->owner;
2619 struct dns_resolvers *presolvers;
2620 struct dns_nameserver *pnameserver;
2621
2622 chunk_reset(&trash);
2623
2624 switch (appctx->st2) {
2625 case STAT_ST_INIT:
2626 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2627 /* fall through */
2628
2629 case STAT_ST_LIST:
2630 if (LIST_ISEMPTY(&dns_resolvers)) {
2631 chunk_appendf(&trash, "No resolvers found\n");
2632 }
2633 else {
2634 list_for_each_entry(presolvers, &dns_resolvers, list) {
Willy Tarreau777b5602016-12-16 18:06:26 +01002635 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != presolvers)
William Lallemand69e96442016-11-19 00:58:54 +01002636 continue;
2637
2638 chunk_appendf(&trash, "Resolvers section %s\n", presolvers->id);
2639 list_for_each_entry(pnameserver, &presolvers->nameserver_list, list) {
2640 chunk_appendf(&trash, " nameserver %s:\n", pnameserver->id);
2641 chunk_appendf(&trash, " sent: %ld\n", pnameserver->counters.sent);
2642 chunk_appendf(&trash, " valid: %ld\n", pnameserver->counters.valid);
2643 chunk_appendf(&trash, " update: %ld\n", pnameserver->counters.update);
2644 chunk_appendf(&trash, " cname: %ld\n", pnameserver->counters.cname);
2645 chunk_appendf(&trash, " cname_error: %ld\n", pnameserver->counters.cname_error);
2646 chunk_appendf(&trash, " any_err: %ld\n", pnameserver->counters.any_err);
2647 chunk_appendf(&trash, " nx: %ld\n", pnameserver->counters.nx);
2648 chunk_appendf(&trash, " timeout: %ld\n", pnameserver->counters.timeout);
2649 chunk_appendf(&trash, " refused: %ld\n", pnameserver->counters.refused);
2650 chunk_appendf(&trash, " other: %ld\n", pnameserver->counters.other);
2651 chunk_appendf(&trash, " invalid: %ld\n", pnameserver->counters.invalid);
2652 chunk_appendf(&trash, " too_big: %ld\n", pnameserver->counters.too_big);
2653 chunk_appendf(&trash, " truncated: %ld\n", pnameserver->counters.truncated);
2654 chunk_appendf(&trash, " outdated: %ld\n", pnameserver->counters.outdated);
2655 }
2656 }
2657 }
2658
2659 /* display response */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002660 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand69e96442016-11-19 00:58:54 +01002661 /* let's try again later from this session. We add ourselves into
2662 * this session's users so that it can remove us upon termination.
2663 */
2664 si->flags |= SI_FL_WAIT_ROOM;
2665 return 0;
2666 }
2667
2668 appctx->st2 = STAT_ST_FIN;
2669 /* fall through */
2670
2671 default:
2672 appctx->st2 = STAT_ST_FIN;
2673 return 1;
2674 }
2675}
2676
2677/* register cli keywords */
2678static struct cli_kw_list cli_kws = {{ },{
2679 { { "show", "stat", "resolvers", NULL }, "show stat resolvers [id]: dumps counters from all resolvers section and\n"
2680 " associated name servers",
2681 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2682 {{},}
2683}};
2684
2685
2686__attribute__((constructor))
2687static void __dns_init(void)
2688{
2689 cli_register_kw(&cli_kws);
2690}
2691