blob: 5542b17c6f87f0c3fdf8bfc17f329f395439dfca [file] [log] [blame]
Baptiste Assmann325137d2015-04-13 23:40:55 +02001/*
2 * Name server resolution
3 *
4 * Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
14#include <fcntl.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19
20#include <sys/types.h>
21
22#include <common/time.h>
23#include <common/ticks.h>
24
William Lallemand69e96442016-11-19 00:58:54 +010025#include <types/applet.h>
26#include <types/cli.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020027#include <types/global.h>
28#include <types/dns.h>
29#include <types/proto_udp.h>
William Lallemand69e96442016-11-19 00:58:54 +010030#include <types/stats.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020031
William Lallemand69e96442016-11-19 00:58:54 +010032#include <proto/channel.h>
33#include <proto/cli.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020034#include <proto/checks.h>
35#include <proto/dns.h>
36#include <proto/fd.h>
37#include <proto/log.h>
38#include <proto/server.h>
39#include <proto/task.h>
40#include <proto/proto_udp.h>
William Lallemand69e96442016-11-19 00:58:54 +010041#include <proto/stream_interface.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020042
43struct list dns_resolvers = LIST_HEAD_INIT(dns_resolvers);
44struct dns_resolution *resolution = NULL;
45
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +020046/*
47 * pre-allocated memory for maximum record names in a DNS response
48 * Each name is DNS_MAX_NAME_SIZE, we add 1 for the NULL character
49 *
50 * WARNING: this is not thread safe...
51 */
52struct dns_response_packet dns_response;
53struct chunk dns_trash = { };
54struct dns_query_item dns_query_records[DNS_MAX_QUERY_RECORDS];
55struct dns_answer_item dns_answer_records[DNS_MAX_ANSWER_RECORDS];
56
Baptiste Assmann325137d2015-04-13 23:40:55 +020057static int64_t dns_query_id_seed; /* random seed */
58
59/* proto_udp callback functions for a DNS resolution */
60struct dgram_data_cb resolve_dgram_cb = {
61 .recv = dns_resolve_recv,
62 .send = dns_resolve_send,
63};
64
65#if DEBUG
66/*
67 * go through the resolutions associated to a resolvers section and print the ID and hostname in
68 * domain name format
69 * should be used for debug purpose only
70 */
71void dns_print_current_resolutions(struct dns_resolvers *resolvers)
72{
73 list_for_each_entry(resolution, &resolvers->curr_resolution, list) {
74 printf(" resolution %d for %s\n", resolution->query_id, resolution->hostname_dn);
75 }
76}
77#endif
78
79/*
80 * check if there is more than 1 resolution in the resolver's resolution list
81 * return value:
82 * 0: empty list
83 * 1: exactly one entry in the list
84 * 2: more than one entry in the list
85 */
86int dns_check_resolution_queue(struct dns_resolvers *resolvers)
87{
88
89 if (LIST_ISEMPTY(&resolvers->curr_resolution))
90 return 0;
91
92 if ((resolvers->curr_resolution.n) && (resolvers->curr_resolution.n == resolvers->curr_resolution.p))
93 return 1;
94
95 if (! ((resolvers->curr_resolution.n == resolvers->curr_resolution.p)
96 && (&resolvers->curr_resolution != resolvers->curr_resolution.n)))
97 return 2;
98
99 return 0;
100}
101
102/*
103 * reset all parameters of a DNS resolution to 0 (or equivalent)
104 * and clean it up from all associated lists (resolution->qid and resolution->list)
105 */
106void dns_reset_resolution(struct dns_resolution *resolution)
107{
108 /* update resolution status */
109 resolution->step = RSLV_STEP_NONE;
110
111 resolution->try = 0;
112 resolution->try_cname = 0;
113 resolution->last_resolution = now_ms;
114 resolution->nb_responses = 0;
115
116 /* clean up query id */
117 eb32_delete(&resolution->qid);
118 resolution->query_id = 0;
119 resolution->qid.key = 0;
120
121 /* default values */
Thierry Fournierada34842016-02-17 21:25:09 +0100122 if (resolution->opts->family_prio == AF_INET) {
Andrew Hayworthe6a4a322015-10-19 22:29:51 +0000123 resolution->query_type = DNS_RTYPE_A;
124 } else {
125 resolution->query_type = DNS_RTYPE_AAAA;
126 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200127
128 /* the second resolution in the queue becomes the first one */
129 LIST_DEL(&resolution->list);
130}
131
132/*
133 * function called when a network IO is generated on a name server socket for an incoming packet
134 * It performs the following actions:
135 * - check if the packet requires processing (not outdated resolution)
136 * - ensure the DNS packet received is valid and call requester's callback
137 * - call requester's error callback if invalid response
Baptiste Assmann3cf7f982016-04-17 22:43:26 +0200138 * - check the dn_name in the packet against the one sent
Baptiste Assmann325137d2015-04-13 23:40:55 +0200139 */
140void dns_resolve_recv(struct dgram_conn *dgram)
141{
142 struct dns_nameserver *nameserver;
143 struct dns_resolvers *resolvers;
144 struct dns_resolution *resolution;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200145 struct dns_query_item *query;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200146 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
147 unsigned char *bufend;
148 int fd, buflen, ret;
149 unsigned short query_id;
150 struct eb32_node *eb;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200151 struct dns_response_packet *dns_p = &dns_response;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200152
153 fd = dgram->t.sock.fd;
154
155 /* check if ready for reading */
156 if (!fd_recv_ready(fd))
157 return;
158
159 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200160 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200161 return;
162
163 resolvers = nameserver->resolvers;
164
165 /* process all pending input messages */
166 while (1) {
167 /* read message received */
168 memset(buf, '\0', DNS_MAX_UDP_MESSAGE + 1);
169 if ((buflen = recv(fd, (char*)buf , DNS_MAX_UDP_MESSAGE, 0)) < 0) {
170 /* FIXME : for now we consider EAGAIN only */
171 fd_cant_recv(fd);
172 break;
173 }
174
175 /* message too big */
176 if (buflen > DNS_MAX_UDP_MESSAGE) {
177 nameserver->counters.too_big += 1;
178 continue;
179 }
180
181 /* initializing variables */
182 bufend = buf + buflen; /* pointer to mark the end of the buffer */
183
184 /* read the query id from the packet (16 bits) */
185 if (buf + 2 > bufend) {
186 nameserver->counters.invalid += 1;
187 continue;
188 }
189 query_id = dns_response_get_query_id(buf);
190
191 /* search the query_id in the pending resolution tree */
Baptiste Assmann01daef32015-09-02 22:05:24 +0200192 eb = eb32_lookup(&resolvers->query_ids, query_id);
193 if (eb == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200194 /* unknown query id means an outdated response and can be safely ignored */
195 nameserver->counters.outdated += 1;
196 continue;
197 }
198
199 /* known query id means a resolution in prgress */
200 resolution = eb32_entry(eb, struct dns_resolution, qid);
201
202 if (!resolution) {
203 nameserver->counters.outdated += 1;
204 continue;
205 }
206
207 /* number of responses received */
208 resolution->nb_responses += 1;
209
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200210 ret = dns_validate_dns_response(buf, bufend, dns_p);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200211
212 /* treat only errors */
213 switch (ret) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200214 case DNS_RESP_QUERY_COUNT_ERROR:
Baptiste Assmann325137d2015-04-13 23:40:55 +0200215 case DNS_RESP_INVALID:
Baptiste Assmann325137d2015-04-13 23:40:55 +0200216 nameserver->counters.invalid += 1;
217 resolution->requester_error_cb(resolution, DNS_RESP_INVALID);
218 continue;
219
220 case DNS_RESP_ERROR:
221 nameserver->counters.other += 1;
222 resolution->requester_error_cb(resolution, DNS_RESP_ERROR);
223 continue;
224
225 case DNS_RESP_ANCOUNT_ZERO:
226 nameserver->counters.any_err += 1;
227 resolution->requester_error_cb(resolution, DNS_RESP_ANCOUNT_ZERO);
228 continue;
229
230 case DNS_RESP_NX_DOMAIN:
231 nameserver->counters.nx += 1;
232 resolution->requester_error_cb(resolution, DNS_RESP_NX_DOMAIN);
233 continue;
234
235 case DNS_RESP_REFUSED:
236 nameserver->counters.refused += 1;
237 resolution->requester_error_cb(resolution, DNS_RESP_REFUSED);
238 continue;
239
240 case DNS_RESP_CNAME_ERROR:
241 nameserver->counters.cname_error += 1;
242 resolution->requester_error_cb(resolution, DNS_RESP_CNAME_ERROR);
243 continue;
244
Baptiste Assmann0df5d962015-09-02 21:58:32 +0200245 case DNS_RESP_TRUNCATED:
246 nameserver->counters.truncated += 1;
247 resolution->requester_error_cb(resolution, DNS_RESP_TRUNCATED);
248 continue;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200249
250 case DNS_RESP_NO_EXPECTED_RECORD:
251 nameserver->counters.other += 1;
252 resolution->requester_error_cb(resolution, DNS_RESP_NO_EXPECTED_RECORD);
253 continue;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200254 }
255
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200256 /* Now let's check the query's dname corresponds to the one we sent.
257 * We can check only the first query of the list. We send one query at a time
258 * so we get one query in the response */
259 query = LIST_NEXT(&dns_p->query_list, struct dns_query_item *, list);
260 if (query && memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
261 nameserver->counters.other += 1;
262 resolution->requester_error_cb(resolution, DNS_RESP_WRONG_NAME);
263 continue;
264 }
265
Baptiste Assmann37bb3722015-08-07 10:18:32 +0200266 nameserver->counters.valid += 1;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200267 resolution->requester_cb(resolution, nameserver, dns_p);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200268 }
269}
270
271/*
272 * function called when a resolvers network socket is ready to send data
273 * It performs the following actions:
274 */
275void dns_resolve_send(struct dgram_conn *dgram)
276{
277 int fd;
278 struct dns_nameserver *nameserver;
279 struct dns_resolvers *resolvers;
280 struct dns_resolution *resolution;
281
282 fd = dgram->t.sock.fd;
283
284 /* check if ready for sending */
285 if (!fd_send_ready(fd))
286 return;
287
288 /* we don't want/need to be waked up any more for sending */
289 fd_stop_send(fd);
290
291 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200292 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200293 return;
294
295 resolvers = nameserver->resolvers;
296 resolution = LIST_NEXT(&resolvers->curr_resolution, struct dns_resolution *, list);
297
298 dns_send_query(resolution);
299 dns_update_resolvers_timeout(resolvers);
300}
301
302/*
303 * forge and send a DNS query to resolvers associated to a resolution
304 * It performs the following actions:
305 * returns:
306 * 0 in case of error or safe ignorance
307 * 1 if no error
308 */
309int dns_send_query(struct dns_resolution *resolution)
310{
311 struct dns_resolvers *resolvers;
312 struct dns_nameserver *nameserver;
Erwan Velu5457eb42015-10-15 15:07:26 +0200313 int ret, bufsize, fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200314
315 resolvers = resolution->resolvers;
316
Baptiste Assmann325137d2015-04-13 23:40:55 +0200317 bufsize = dns_build_query(resolution->query_id, resolution->query_type, resolution->hostname_dn,
318 resolution->hostname_dn_len, trash.str, trash.size);
319
320 if (bufsize == -1)
321 return 0;
322
323 list_for_each_entry(nameserver, &resolvers->nameserver_list, list) {
324 fd = nameserver->dgram->t.sock.fd;
325 errno = 0;
326
327 ret = send(fd, trash.str, bufsize, 0);
328
329 if (ret > 0)
330 nameserver->counters.sent += 1;
331
332 if (ret == 0 || errno == EAGAIN) {
333 /* nothing written, let's update the poller that we wanted to send
334 * but we were not able to */
335 fd_want_send(fd);
336 fd_cant_send(fd);
337 }
338 }
339
340 /* update resolution */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200341 resolution->nb_responses = 0;
342 resolution->last_sent_packet = now_ms;
343
344 return 1;
345}
346
347/*
348 * update a resolvers' task timeout for next wake up
349 */
350void dns_update_resolvers_timeout(struct dns_resolvers *resolvers)
351{
352 struct dns_resolution *resolution;
353
354 if (LIST_ISEMPTY(&resolvers->curr_resolution)) {
355 /* no more resolution pending, so no wakeup anymore */
356 resolvers->t->expire = TICK_ETERNITY;
357 }
358 else {
359 resolution = LIST_NEXT(&resolvers->curr_resolution, struct dns_resolution *, list);
360 resolvers->t->expire = tick_add(resolution->last_sent_packet, resolvers->timeout.retry);
361 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200362}
363
364/*
365 * Analyse, re-build and copy the name <name> from the DNS response packet <buffer>.
366 * <name> must point to the 'data_len' information or pointer 'c0' for compressed data.
367 * The result is copied into <dest>, ensuring we don't overflow using <dest_len>
368 * Returns the number of bytes the caller can move forward. If 0 it means an error occured
369 * while parsing the name.
370 * <offset> is the number of bytes the caller could move forward.
371 */
372int dns_read_name(unsigned char *buffer, unsigned char *bufend, unsigned char *name, char *destination, int dest_len, int *offset)
373{
374 int nb_bytes = 0, n = 0;
375 int label_len;
376 unsigned char *reader = name;
377 char *dest = destination;
378
379 while (1) {
380 /* name compression is in use */
381 if ((*reader & 0xc0) == 0xc0) {
382 /* a pointer must point BEFORE current position */
383 if ((buffer + reader[1]) > reader) {
384 goto out_error;
385 }
386
387 n = dns_read_name(buffer, bufend, buffer + reader[1], dest, dest_len - nb_bytes, offset);
388 if (n == 0)
389 goto out_error;
390
391 dest += n;
392 nb_bytes += n;
393 goto out;
394 }
395
396 label_len = *reader;
397 if (label_len == 0)
398 goto out;
399 /* Check if:
400 * - we won't read outside the buffer
401 * - there is enough place in the destination
402 */
403 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
404 goto out_error;
405
406 /* +1 to take label len + label string */
407 label_len += 1;
408
409 memcpy(dest, reader, label_len);
410
411 dest += label_len;
412 nb_bytes += label_len;
413 reader += label_len;
414 }
415
416 out:
417 /* offset computation:
418 * parse from <name> until finding either NULL or a pointer "c0xx"
419 */
420 reader = name;
421 *offset = 0;
422 while (reader < bufend) {
423 if ((reader[0] & 0xc0) == 0xc0) {
424 *offset += 2;
425 break;
426 }
427 else if (*reader == 0) {
428 *offset += 1;
429 break;
430 }
431 *offset += 1;
432 ++reader;
433 }
434
435 return nb_bytes;
436
437 out_error:
438 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200439}
440
441/*
442 * Function to validate that the buffer DNS response provided in <resp> and
443 * finishing before <bufend> is valid from a DNS protocol point of view.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200444 *
445 * The result is stored in the structured pointed by <dns_p>.
446 * It's up to the caller to allocate memory for <dns_p>.
447 *
448 * This function returns one of the DNS_RESP_* code to indicate the type of
449 * error found.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200450 */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200451int dns_validate_dns_response(unsigned char *resp, unsigned char *bufend, struct dns_response_packet *dns_p)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200452{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200453 unsigned char *reader;
454 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
455 int len, flags, offset, ret;
456 int dns_query_record_id, dns_answer_record_id;
457 struct dns_query_item *dns_query;
458 struct dns_answer_item *dns_answer_record;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200459
460 reader = resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200461 len = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200462 previous_dname = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200463
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200464 /* initialization of local buffer */
465 memset(dns_p, '\0', sizeof(struct dns_response_packet));
466 chunk_reset(&dns_trash);
467
468 /* query id */
469 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200470 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200471 dns_p->header.id = reader[0] * 256 + reader[1];
472 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200473
474 /*
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200475 * flags and rcode are stored over 2 bytes
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200476 * First byte contains:
477 * - response flag (1 bit)
478 * - opcode (4 bits)
479 * - authoritative (1 bit)
480 * - truncated (1 bit)
481 * - recursion desired (1 bit)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200482 */
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200483 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200484 return DNS_RESP_INVALID;
485
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200486 flags = reader[0] * 256 + reader[1];
487
488 if (flags & DNS_FLAG_TRUNCATED)
489 return DNS_RESP_TRUNCATED;
490
491 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
492 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200493 return DNS_RESP_NX_DOMAIN;
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200494 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200495 return DNS_RESP_REFUSED;
496
497 return DNS_RESP_ERROR;
498 }
499
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200500 /* move forward 2 bytes for flags */
501 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200502
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200503 /* 2 bytes for question count */
504 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200505 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200506 dns_p->header.qdcount = reader[0] * 256 + reader[1];
507 /* (for now) we send one query only, so we expect only one in the response too */
508 if (dns_p->header.qdcount != 1)
509 return DNS_RESP_QUERY_COUNT_ERROR;
510 if (dns_p->header.qdcount > DNS_MAX_QUERY_RECORDS)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200511 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200512 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200513
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200514 /* 2 bytes for answer count */
515 if (reader + 2 >= bufend)
516 return DNS_RESP_INVALID;
517 dns_p->header.ancount = reader[0] * 256 + reader[1];
518 if (dns_p->header.ancount == 0)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200519 return DNS_RESP_ANCOUNT_ZERO;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200520 /* check if too many records are announced */
521 if (dns_p->header.ancount > DNS_MAX_ANSWER_RECORDS)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200522 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200523 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200524
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200525 /* 2 bytes authority count */
526 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200527 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200528 dns_p->header.nscount = reader[0] * 256 + reader[1];
529 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200530
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200531 /* 2 bytes additional count */
532 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200533 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200534 dns_p->header.arcount = reader[0] * 256 + reader[1];
535 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200536
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200537 /* parsing dns queries */
538 LIST_INIT(&dns_p->query_list);
539 for (dns_query_record_id = 0; dns_query_record_id < dns_p->header.qdcount; dns_query_record_id++) {
540 /* use next pre-allocated dns_query_item after ensuring there is
541 * still one available.
542 * It's then added to our packet query list.
543 */
544 if (dns_query_record_id > DNS_MAX_QUERY_RECORDS)
545 return DNS_RESP_INVALID;
546 dns_query = &dns_query_records[dns_query_record_id];
547 LIST_ADDQ(&dns_p->query_list, &dns_query->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200548
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200549 /* name is a NULL terminated string in our case, since we have
550 * one query per response and the first one can't be compressed
551 * (using the 0x0c format)
552 */
553 offset = 0;
554 len = dns_read_name(resp, bufend, reader, dns_query->name, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200555
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200556 if (len == 0)
557 return DNS_RESP_INVALID;
558
559 reader += offset;
560 previous_dname = dns_query->name;
561
562 /* move forward 2 bytes for question type */
563 if (reader + 2 >= bufend)
564 return DNS_RESP_INVALID;
565 dns_query->type = reader[0] * 256 + reader[1];
566 reader += 2;
567
568 /* move forward 2 bytes for question class */
569 if (reader + 2 >= bufend)
570 return DNS_RESP_INVALID;
571 dns_query->class = reader[0] * 256 + reader[1];
572 reader += 2;
573 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200574
575 /* now parsing response records */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200576 LIST_INIT(&dns_p->answer_list);
577 for (dns_answer_record_id = 0; dns_answer_record_id < dns_p->header.ancount; dns_answer_record_id++) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200578 if (reader >= bufend)
579 return DNS_RESP_INVALID;
580
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200581 /* pull next response record from the list, if still one available, then add it
582 * to the record list */
583 if (dns_answer_record_id > DNS_MAX_ANSWER_RECORDS)
584 return DNS_RESP_INVALID;
585 dns_answer_record = &dns_answer_records[dns_answer_record_id];
586 LIST_ADDQ(&dns_p->answer_list, &dns_answer_record->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200587
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200588 offset = 0;
589 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200590
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200591 if (len == 0)
592 return DNS_RESP_INVALID;
593
594 /* check if the current record dname is valid.
595 * previous_dname points either to queried dname or last CNAME target
596 */
597 if (memcmp(previous_dname, tmpname, len) != 0) {
598 if (dns_answer_record_id == 0) {
599 /* first record, means a mismatch issue between queried dname
600 * and dname found in the first record */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200601 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200602 } else {
603 /* if not the first record, this means we have a CNAME resolution
604 * error */
605 return DNS_RESP_CNAME_ERROR;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200606 }
607
Baptiste Assmann325137d2015-04-13 23:40:55 +0200608 }
609
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200610 dns_answer_record->name = chunk_newstr(&dns_trash);
611 if (dns_answer_record->name == NULL)
612 return DNS_RESP_INVALID;
Baptiste Assmann5d681ba2015-10-15 15:23:28 +0200613
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200614 ret = chunk_strncat(&dns_trash, tmpname, len);
615 if (ret == 0)
616 return DNS_RESP_INVALID;
Baptiste Assmann2359ff12015-08-07 11:24:05 +0200617
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200618 reader += offset;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200619 if (reader >= bufend)
620 return DNS_RESP_INVALID;
621
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200622 if (reader >= bufend)
623 return DNS_RESP_INVALID;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200624
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200625 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200626 if (reader + 2 > bufend)
627 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200628 dns_answer_record->type = reader[0] * 256 + reader[1];
629 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200630
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200631 /* 2 bytes for class (2) */
632 if (reader + 2 > bufend)
633 return DNS_RESP_INVALID;
634 dns_answer_record->class = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +0200635 reader += 2;
636
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200637 /* 4 bytes for ttl (4) */
638 if (reader + 4 > bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200639 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200640 dns_answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
641 + reader[2] * 256 + reader[3];
642 reader += 4;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200643
644 /* now reading data len */
645 if (reader + 2 > bufend)
646 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200647 dns_answer_record->data_len = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +0200648
649 /* move forward 2 bytes for data len */
650 reader += 2;
651
652 /* analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200653 switch (dns_answer_record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200654 case DNS_RTYPE_A:
655 /* ipv4 is stored on 4 bytes */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200656 if (dns_answer_record->data_len != 4)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200657 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200658 dns_answer_record->address.sa_family = AF_INET;
659 memcpy(&(((struct sockaddr_in *)&dns_answer_record->address)->sin_addr),
660 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200661 break;
662
663 case DNS_RTYPE_CNAME:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200664 /* check if this is the last record and update the caller about the status:
665 * no IP could be found and last record was a CNAME. Could be triggered
666 * by a wrong query type
667 *
668 * + 1 because dns_answer_record_id starts at 0 while number of answers
669 * is an integer and starts at 1.
670 */
671 if (dns_answer_record_id + 1 == dns_p->header.ancount)
672 return DNS_RESP_CNAME_ERROR;
673
674 offset = 0;
675 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
676
677 if (len == 0)
678 return DNS_RESP_INVALID;
679
680 dns_answer_record->target = chunk_newstr(&dns_trash);
681 if (dns_answer_record->target == NULL)
682 return DNS_RESP_INVALID;
683
684 ret = chunk_strncat(&dns_trash, tmpname, len);
685 if (ret == 0)
686 return DNS_RESP_INVALID;
687
688 previous_dname = dns_answer_record->target;
689
Baptiste Assmann325137d2015-04-13 23:40:55 +0200690 break;
691
692 case DNS_RTYPE_AAAA:
693 /* ipv6 is stored on 16 bytes */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200694 if (dns_answer_record->data_len != 16)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200695 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200696 dns_answer_record->address.sa_family = AF_INET6;
697 memcpy(&(((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr),
698 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200699 break;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200700
Baptiste Assmann325137d2015-04-13 23:40:55 +0200701 } /* switch (record type) */
702
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200703 /* move forward dns_answer_record->data_len for analyzing next record in the response */
704 reader += dns_answer_record->data_len;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200705 } /* for i 0 to ancount */
706
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200707 /* let's add a last \0 to close our last string */
708 ret = chunk_strncat(&dns_trash, "\0", 1);
709 if (ret == 0)
710 return DNS_RESP_INVALID;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200711
Baptiste Assmann325137d2015-04-13 23:40:55 +0200712 return DNS_RESP_VALID;
713}
714
715/*
716 * search dn_name resolution in resp.
717 * If existing IP not found, return the first IP matching family_priority,
718 * otherwise, first ip found
719 * The following tasks are the responsibility of the caller:
Baptiste Assmann3cf7f982016-04-17 22:43:26 +0200720 * - <dns_p> contains an error free DNS response
Baptiste Assmann325137d2015-04-13 23:40:55 +0200721 * For both cases above, dns_validate_dns_response is required
722 * returns one of the DNS_UPD_* code
723 */
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100724#define DNS_MAX_IP_REC 20
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200725int dns_get_ip_from_response(struct dns_response_packet *dns_p,
Thierry Fournierada34842016-02-17 21:25:09 +0100726 struct dns_resolution *resol, void *currentip,
727 short currentip_sin_family,
728 void **newip, short *newip_sin_family)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200729{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200730 struct dns_answer_item *record;
Thierry Fournierada34842016-02-17 21:25:09 +0100731 int family_priority;
Baptiste Assmann3cf7f982016-04-17 22:43:26 +0200732 int i, currentip_found;
733 unsigned char *newip4, *newip6;
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100734 struct {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200735 void *ip;
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100736 unsigned char type;
737 } rec[DNS_MAX_IP_REC];
738 int currentip_sel;
739 int j;
740 int rec_nb = 0;
741 int score, max_score;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200742
Thierry Fournierada34842016-02-17 21:25:09 +0100743 family_priority = resol->opts->family_prio;
Baptiste Assmann3cf7f982016-04-17 22:43:26 +0200744 *newip = newip4 = newip6 = NULL;
745 currentip_found = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200746 *newip_sin_family = AF_UNSPEC;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200747
748 /* now parsing response records */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200749 list_for_each_entry(record, &dns_response.answer_list, list) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200750 /* analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200751 switch (record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200752 case DNS_RTYPE_A:
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100753 /* Store IPv4, only if some room is avalaible. */
754 if (rec_nb < DNS_MAX_IP_REC) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200755 rec[rec_nb].ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100756 rec[rec_nb].type = AF_INET;
757 rec_nb++;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200758 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200759 break;
760
Baptiste Assmann3cf7f982016-04-17 22:43:26 +0200761 /* we're looking for IPs only. CNAME validation is done when
762 * parsing the response buffer for the first time */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200763 case DNS_RTYPE_CNAME:
Baptiste Assmann325137d2015-04-13 23:40:55 +0200764 break;
765
766 case DNS_RTYPE_AAAA:
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100767 /* Store IPv6, only if some room is avalaible. */
768 if (rec_nb < DNS_MAX_IP_REC) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200769 rec[rec_nb].ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100770 rec[rec_nb].type = AF_INET6;
771 rec_nb++;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200772 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200773 break;
774
Baptiste Assmann325137d2015-04-13 23:40:55 +0200775 } /* switch (record type) */
Baptiste Assmannbcbd4912016-04-18 19:42:57 +0200776 } /* list for each record entries */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200777
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100778 /* Select an IP regarding configuration preference.
779 * Top priority is the prefered network ip version,
780 * second priority is the prefered network.
781 * the last priority is the currently used IP,
782 *
783 * For these three priorities, a score is calculated. The
784 * weight are:
785 * 4 - prefered netwok ip version.
786 * 2 - prefered network.
787 * 1 - current ip.
788 * The result with the biggest score is returned.
789 */
790 max_score = -1;
791 for (i = 0; i < rec_nb; i++) {
792
793 score = 0;
794
795 /* Check for prefered ip protocol. */
796 if (rec[i].type == family_priority)
797 score += 4;
798
799 /* Check for prefered network. */
800 for (j = 0; j < resol->opts->pref_net_nb; j++) {
801
802 /* Compare only the same adresses class. */
803 if (resol->opts->pref_net[j].family != rec[i].type)
804 continue;
805
806 if ((rec[i].type == AF_INET &&
Willy Tarreaueec1d382016-07-13 11:59:39 +0200807 in_net_ipv4(rec[i].ip,
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100808 &resol->opts->pref_net[j].mask.in4,
809 &resol->opts->pref_net[j].addr.in4)) ||
810 (rec[i].type == AF_INET6 &&
Willy Tarreaueec1d382016-07-13 11:59:39 +0200811 in_net_ipv6(rec[i].ip,
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100812 &resol->opts->pref_net[j].mask.in6,
813 &resol->opts->pref_net[j].addr.in6))) {
814 score += 2;
815 break;
816 }
817 }
818
819 /* Check for current ip matching. */
820 if (rec[i].type == currentip_sin_family &&
821 ((currentip_sin_family == AF_INET &&
Willy Tarreaueec1d382016-07-13 11:59:39 +0200822 memcmp(rec[i].ip, currentip, 4) == 0) ||
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100823 (currentip_sin_family == AF_INET6 &&
824 memcmp(rec[i].ip, currentip, 16) == 0))) {
825 score += 1;
826 currentip_sel = 1;
827 } else
828 currentip_sel = 0;
829
830 /* Keep the address if the score is better than the previous
831 * score. The maximum score is 7, if this value is reached,
832 * we break the parsing. Implicitly, this score is reached
833 * the ip selected is the current ip.
834 */
835 if (score > max_score) {
836 if (rec[i].type == AF_INET)
837 newip4 = rec[i].ip;
838 else
839 newip6 = rec[i].ip;
840 currentip_found = currentip_sel;
841 if (score == 7)
842 return DNS_UPD_NO;
843 max_score = score;
844 }
845 }
846
Baptiste Assmann0453a1d2015-09-09 00:51:08 +0200847 /* no IP found in the response */
848 if (!newip4 && !newip6) {
849 return DNS_UPD_NO_IP_FOUND;
850 }
851
Baptiste Assmann325137d2015-04-13 23:40:55 +0200852 /* case when the caller looks first for an IPv4 address */
853 if (family_priority == AF_INET) {
854 if (newip4) {
855 *newip = newip4;
856 *newip_sin_family = AF_INET;
857 if (currentip_found == 1)
858 return DNS_UPD_NO;
859 return DNS_UPD_SRVIP_NOT_FOUND;
860 }
861 else if (newip6) {
862 *newip = newip6;
863 *newip_sin_family = AF_INET6;
864 if (currentip_found == 1)
865 return DNS_UPD_NO;
866 return DNS_UPD_SRVIP_NOT_FOUND;
867 }
868 }
869 /* case when the caller looks first for an IPv6 address */
870 else if (family_priority == AF_INET6) {
871 if (newip6) {
872 *newip = newip6;
873 *newip_sin_family = AF_INET6;
874 if (currentip_found == 1)
875 return DNS_UPD_NO;
876 return DNS_UPD_SRVIP_NOT_FOUND;
877 }
878 else if (newip4) {
879 *newip = newip4;
880 *newip_sin_family = AF_INET;
881 if (currentip_found == 1)
882 return DNS_UPD_NO;
883 return DNS_UPD_SRVIP_NOT_FOUND;
884 }
885 }
886 /* case when the caller have no preference (we prefer IPv6) */
887 else if (family_priority == AF_UNSPEC) {
888 if (newip6) {
889 *newip = newip6;
890 *newip_sin_family = AF_INET6;
891 if (currentip_found == 1)
892 return DNS_UPD_NO;
893 return DNS_UPD_SRVIP_NOT_FOUND;
894 }
895 else if (newip4) {
896 *newip = newip4;
897 *newip_sin_family = AF_INET;
898 if (currentip_found == 1)
899 return DNS_UPD_NO;
900 return DNS_UPD_SRVIP_NOT_FOUND;
901 }
902 }
903
904 /* no reason why we should change the server's IP address */
905 return DNS_UPD_NO;
906}
907
908/*
909 * returns the query id contained in a DNS response
910 */
Thiago Farinab1af23e2016-01-20 23:46:34 +0100911unsigned short dns_response_get_query_id(unsigned char *resp)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200912{
913 /* read the query id from the response */
914 return resp[0] * 256 + resp[1];
915}
916
917/*
918 * used during haproxy's init phase
919 * parses resolvers sections and initializes:
920 * - task (time events) for each resolvers section
921 * - the datagram layer (network IO events) for each nameserver
Baptiste Assmann5cd1b922017-02-02 22:44:15 +0100922 * It takes one argument:
923 * - close_first takes 2 values: 0 or 1. If 1, the connection is closed first.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200924 * returns:
925 * 0 in case of error
926 * 1 when no error
927 */
Baptiste Assmann5cd1b922017-02-02 22:44:15 +0100928int dns_init_resolvers(int close_socket)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200929{
930 struct dns_resolvers *curr_resolvers;
931 struct dns_nameserver *curnameserver;
932 struct dgram_conn *dgram;
933 struct task *t;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200934 char *dns_trash_str;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200935 int fd;
936
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200937 dns_trash_str = malloc(global.tune.bufsize);
938 if (dns_trash_str == NULL) {
Willy Tarreauc3d8cd42016-10-01 09:20:32 +0200939 Alert("Starting resolvers: out of memory.\n");
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200940 return 0;
941 }
942
943 /* allocate memory for the dns_trash buffer used to temporarily store
944 * the records of the received response */
945 chunk_init(&dns_trash, dns_trash_str, global.tune.bufsize);
946
Baptiste Assmann325137d2015-04-13 23:40:55 +0200947 /* give a first random value to our dns query_id seed */
948 dns_query_id_seed = random();
949
950 /* run through the resolvers section list */
951 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
952 /* create the task associated to the resolvers section */
953 if ((t = task_new()) == NULL) {
954 Alert("Starting [%s] resolvers: out of memory.\n", curr_resolvers->id);
955 return 0;
956 }
957
958 /* update task's parameters */
959 t->process = dns_process_resolve;
960 t->context = curr_resolvers;
961 t->expire = TICK_ETERNITY;
962
963 curr_resolvers->t = t;
964
965 list_for_each_entry(curnameserver, &curr_resolvers->nameserver_list, list) {
Baptiste Assmann5cd1b922017-02-02 22:44:15 +0100966 dgram = NULL;
967
968 if (close_socket == 1) {
969 if (curnameserver->dgram) {
970 close(curnameserver->dgram->t.sock.fd);
971 memset(curnameserver->dgram, '\0', sizeof(*dgram));
972 dgram = curnameserver->dgram;
973 }
974 }
975
976 /* allocate memory only if it has not already been allocated
977 * by a previous call to this function */
978 if (!dgram && (dgram = calloc(1, sizeof(*dgram))) == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200979 Alert("Starting [%s/%s] nameserver: out of memory.\n", curr_resolvers->id,
980 curnameserver->id);
981 return 0;
982 }
983 /* update datagram's parameters */
984 dgram->owner = (void *)curnameserver;
985 dgram->data = &resolve_dgram_cb;
986
987 /* create network UDP socket for this nameserver */
988 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
989 Alert("Starting [%s/%s] nameserver: can't create socket.\n", curr_resolvers->id,
990 curnameserver->id);
991 free(dgram);
992 dgram = NULL;
993 return 0;
994 }
995
996 /* "connect" the UDP socket to the name server IP */
Baptiste Assmann8c62c472015-09-21 20:55:08 +0200997 if (connect(fd, (struct sockaddr*)&curnameserver->addr, get_addr_len(&curnameserver->addr)) == -1) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200998 Alert("Starting [%s/%s] nameserver: can't connect socket.\n", curr_resolvers->id,
999 curnameserver->id);
1000 close(fd);
1001 free(dgram);
1002 dgram = NULL;
1003 return 0;
1004 }
1005
1006 /* make the socket non blocking */
1007 fcntl(fd, F_SETFL, O_NONBLOCK);
1008
1009 /* add the fd in the fd list and update its parameters */
1010 fd_insert(fd);
1011 fdtab[fd].owner = dgram;
1012 fdtab[fd].iocb = dgram_fd_handler;
1013 fd_want_recv(fd);
1014 dgram->t.sock.fd = fd;
1015
1016 /* update nameserver's datagram property */
1017 curnameserver->dgram = dgram;
1018
1019 continue;
1020 }
1021
1022 /* task can be queued */
1023 task_queue(t);
1024 }
1025
1026 return 1;
1027}
1028
1029/*
1030 * Forge a DNS query. It needs the following information from the caller:
1031 * - <query_id>: the DNS query id corresponding to this query
1032 * - <query_type>: DNS_RTYPE_* request DNS record type (A, AAAA, ANY, etc...)
1033 * - <hostname_dn>: hostname in domain name format
1034 * - <hostname_dn_len>: length of <hostname_dn>
1035 * To store the query, the caller must pass a buffer <buf> and its size <bufsize>
1036 *
1037 * the DNS query is stored in <buf>
1038 * returns:
1039 * -1 if <buf> is too short
1040 */
1041int dns_build_query(int query_id, int query_type, char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
1042{
1043 struct dns_header *dns;
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001044 struct dns_question qinfo;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001045 char *ptr, *bufend;
1046
1047 memset(buf, '\0', bufsize);
1048 ptr = buf;
1049 bufend = buf + bufsize;
1050
1051 /* check if there is enough room for DNS headers */
1052 if (ptr + sizeof(struct dns_header) >= bufend)
1053 return -1;
1054
1055 /* set dns query headers */
1056 dns = (struct dns_header *)ptr;
1057 dns->id = (unsigned short) htons(query_id);
Nenad Merdanovic8ab79422016-07-13 14:03:43 +02001058 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 +02001059 dns->qdcount = htons(1); /* 1 question */
1060 dns->ancount = 0;
1061 dns->nscount = 0;
1062 dns->arcount = 0;
1063
1064 /* move forward ptr */
1065 ptr += sizeof(struct dns_header);
1066
1067 /* check if there is enough room for query hostname */
1068 if ((ptr + hostname_dn_len) >= bufend)
1069 return -1;
1070
1071 /* set up query hostname */
1072 memcpy(ptr, hostname_dn, hostname_dn_len);
1073 ptr[hostname_dn_len + 1] = '\0';
1074
1075 /* move forward ptr */
1076 ptr += (hostname_dn_len + 1);
1077
1078 /* check if there is enough room for query hostname*/
1079 if (ptr + sizeof(struct dns_question) >= bufend)
1080 return -1;
1081
1082 /* set up query info (type and class) */
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001083 qinfo.qtype = htons(query_type);
1084 qinfo.qclass = htons(DNS_RCLASS_IN);
1085 memcpy(ptr, &qinfo, sizeof(qinfo));
Baptiste Assmann325137d2015-04-13 23:40:55 +02001086
1087 ptr += sizeof(struct dns_question);
1088
1089 return ptr - buf;
1090}
1091
1092/*
1093 * turn a string into domain name label:
1094 * www.haproxy.org into 3www7haproxy3org
1095 * if dn memory is pre-allocated, you must provide its size in dn_len
1096 * if dn memory isn't allocated, dn_len must be set to 0.
1097 * In the second case, memory will be allocated.
1098 * in case of error, -1 is returned, otherwise, number of bytes copied in dn
1099 */
Willy Tarreau2100b492015-07-22 16:42:43 +02001100char *dns_str_to_dn_label(const char *string, char *dn, int dn_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001101{
1102 char *c, *d;
1103 int i, offset;
1104
1105 /* offset between string size and theorical dn size */
1106 offset = 1;
1107
1108 /*
1109 * first, get the size of the string turned into its domain name version
1110 * This function also validates the string respect the RFC
1111 */
1112 if ((i = dns_str_to_dn_label_len(string)) == -1)
1113 return NULL;
1114
1115 /* yes, so let's check there is enough memory */
1116 if (dn_len < i + offset)
1117 return NULL;
1118
Willy Tarreaud69d6f32015-07-22 16:45:36 +02001119 i = strlen(string);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001120 memcpy(dn + offset, string, i);
1121 dn[i + offset] = '\0';
1122 /* avoid a '\0' at the beginning of dn string which may prevent the for loop
1123 * below from working.
1124 * Actually, this is the reason of the offset. */
1125 dn[0] = '0';
1126
1127 for (c = dn; *c ; ++c) {
1128 /* c points to the first '0' char or a dot, which we don't want to read */
1129 d = c + offset;
1130 i = 0;
1131 while (*d != '.' && *d) {
1132 i++;
1133 d++;
1134 }
1135 *c = i;
1136
1137 c = d - 1; /* because of c++ of the for loop */
1138 }
1139
1140 return dn;
1141}
1142
1143/*
1144 * compute and return the length of <string> it it were translated into domain name
1145 * label:
1146 * www.haproxy.org into 3www7haproxy3org would return 16
1147 * NOTE: add +1 for '\0' when allocating memory ;)
1148 */
1149int dns_str_to_dn_label_len(const char *string)
1150{
1151 return strlen(string) + 1;
1152}
1153
1154/*
1155 * validates host name:
1156 * - total size
1157 * - each label size individually
1158 * returns:
1159 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1160 * 1 when no error. <err> is left unaffected.
1161 */
1162int dns_hostname_validation(const char *string, char **err)
1163{
1164 const char *c, *d;
1165 int i;
1166
1167 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1168 if (err)
1169 *err = DNS_TOO_LONG_FQDN;
1170 return 0;
1171 }
1172
1173 c = string;
1174 while (*c) {
1175 d = c;
1176
1177 i = 0;
1178 while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) {
1179 i++;
1180 if (!((*d == '-') || (*d == '_') ||
1181 ((*d >= 'a') && (*d <= 'z')) ||
1182 ((*d >= 'A') && (*d <= 'Z')) ||
1183 ((*d >= '0') && (*d <= '9')))) {
1184 if (err)
1185 *err = DNS_INVALID_CHARACTER;
1186 return 0;
1187 }
1188 d++;
1189 }
1190
1191 if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) {
1192 if (err)
1193 *err = DNS_LABEL_TOO_LONG;
1194 return 0;
1195 }
1196
1197 if (*d == '\0')
1198 goto out;
1199
1200 c = ++d;
1201 }
1202 out:
1203 return 1;
1204}
1205
1206/*
1207 * 2 bytes random generator to generate DNS query ID
1208 */
1209uint16_t dns_rnd16(void)
1210{
1211 dns_query_id_seed ^= dns_query_id_seed << 13;
1212 dns_query_id_seed ^= dns_query_id_seed >> 7;
1213 dns_query_id_seed ^= dns_query_id_seed << 17;
1214 return dns_query_id_seed;
1215}
1216
1217
1218/*
1219 * function called when a timeout occurs during name resolution process
1220 * if max number of tries is reached, then stop, otherwise, retry.
1221 */
1222struct task *dns_process_resolve(struct task *t)
1223{
1224 struct dns_resolvers *resolvers = t->context;
1225 struct dns_resolution *resolution, *res_back;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001226 int res_preferred_afinet, res_preferred_afinet6;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001227
1228 /* timeout occurs inevitably for the first element of the FIFO queue */
1229 if (LIST_ISEMPTY(&resolvers->curr_resolution)) {
1230 /* no first entry, so wake up was useless */
1231 t->expire = TICK_ETERNITY;
1232 return t;
1233 }
1234
1235 /* look for the first resolution which is not expired */
1236 list_for_each_entry_safe(resolution, res_back, &resolvers->curr_resolution, list) {
1237 /* when we find the first resolution in the future, then we can stop here */
1238 if (tick_is_le(now_ms, resolution->last_sent_packet))
1239 goto out;
1240
1241 /*
1242 * if current resolution has been tried too many times and finishes in timeout
1243 * we update its status and remove it from the list
1244 */
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001245 if (resolution->try <= 0) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001246 /* clean up resolution information and remove from the list */
1247 dns_reset_resolution(resolution);
1248
1249 /* notify the result to the requester */
1250 resolution->requester_error_cb(resolution, DNS_RESP_TIMEOUT);
Baptiste Assmann382824c2016-01-06 01:53:46 +01001251 goto out;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001252 }
1253
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001254 resolution->try -= 1;
1255
Baptiste Assmann6f79aca2016-04-05 21:19:51 +02001256 res_preferred_afinet = resolution->opts->family_prio == AF_INET && resolution->query_type == DNS_RTYPE_A;
1257 res_preferred_afinet6 = resolution->opts->family_prio == AF_INET6 && resolution->query_type == DNS_RTYPE_AAAA;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001258
1259 /* let's change the query type if needed */
1260 if (res_preferred_afinet6) {
1261 /* fallback from AAAA to A */
1262 resolution->query_type = DNS_RTYPE_A;
1263 }
1264 else if (res_preferred_afinet) {
1265 /* fallback from A to AAAA */
1266 resolution->query_type = DNS_RTYPE_AAAA;
1267 }
1268
Baptiste Assmann382824c2016-01-06 01:53:46 +01001269 /* resend the DNS query */
1270 dns_send_query(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001271
Baptiste Assmann382824c2016-01-06 01:53:46 +01001272 /* check if we have more than one resolution in the list */
1273 if (dns_check_resolution_queue(resolvers) > 1) {
1274 /* move the rsolution to the end of the list */
1275 LIST_DEL(&resolution->list);
1276 LIST_ADDQ(&resolvers->curr_resolution, &resolution->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001277 }
1278 }
1279
1280 out:
1281 dns_update_resolvers_timeout(resolvers);
1282 return t;
1283}
William Lallemand69e96442016-11-19 00:58:54 +01001284
Willy Tarreau777b5602016-12-16 18:06:26 +01001285/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
William Lallemand69e96442016-11-19 00:58:54 +01001286static int cli_parse_stat_resolvers(char **args, struct appctx *appctx, void *private)
1287{
1288 struct dns_resolvers *presolvers;
1289
1290 if (*args[3]) {
William Lallemand69e96442016-11-19 00:58:54 +01001291 list_for_each_entry(presolvers, &dns_resolvers, list) {
1292 if (strcmp(presolvers->id, args[3]) == 0) {
Willy Tarreau777b5602016-12-16 18:06:26 +01001293 appctx->ctx.cli.p0 = presolvers;
William Lallemand69e96442016-11-19 00:58:54 +01001294 break;
1295 }
1296 }
Willy Tarreau777b5602016-12-16 18:06:26 +01001297 if (appctx->ctx.cli.p0 == NULL) {
William Lallemand69e96442016-11-19 00:58:54 +01001298 appctx->ctx.cli.msg = "Can't find that resolvers section\n";
Willy Tarreau3b6e5472016-11-24 15:53:53 +01001299 appctx->st0 = CLI_ST_PRINT;
William Lallemand69e96442016-11-19 00:58:54 +01001300 return 1;
1301 }
1302 }
Willy Tarreau3067bfa2016-12-05 14:50:15 +01001303 return 0;
William Lallemand69e96442016-11-19 00:58:54 +01001304}
1305
Willy Tarreau777b5602016-12-16 18:06:26 +01001306/* This function dumps counters from all resolvers section and associated name
1307 * servers. It returns 0 if the output buffer is full and it needs to be called
1308 * again, otherwise non-zero. It may limit itself to the resolver pointed to by
1309 * <cli.p0> if it's not null.
William Lallemand69e96442016-11-19 00:58:54 +01001310 */
1311static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
1312{
1313 struct stream_interface *si = appctx->owner;
1314 struct dns_resolvers *presolvers;
1315 struct dns_nameserver *pnameserver;
1316
1317 chunk_reset(&trash);
1318
1319 switch (appctx->st2) {
1320 case STAT_ST_INIT:
1321 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
1322 /* fall through */
1323
1324 case STAT_ST_LIST:
1325 if (LIST_ISEMPTY(&dns_resolvers)) {
1326 chunk_appendf(&trash, "No resolvers found\n");
1327 }
1328 else {
1329 list_for_each_entry(presolvers, &dns_resolvers, list) {
Willy Tarreau777b5602016-12-16 18:06:26 +01001330 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != presolvers)
William Lallemand69e96442016-11-19 00:58:54 +01001331 continue;
1332
1333 chunk_appendf(&trash, "Resolvers section %s\n", presolvers->id);
1334 list_for_each_entry(pnameserver, &presolvers->nameserver_list, list) {
1335 chunk_appendf(&trash, " nameserver %s:\n", pnameserver->id);
1336 chunk_appendf(&trash, " sent: %ld\n", pnameserver->counters.sent);
1337 chunk_appendf(&trash, " valid: %ld\n", pnameserver->counters.valid);
1338 chunk_appendf(&trash, " update: %ld\n", pnameserver->counters.update);
1339 chunk_appendf(&trash, " cname: %ld\n", pnameserver->counters.cname);
1340 chunk_appendf(&trash, " cname_error: %ld\n", pnameserver->counters.cname_error);
1341 chunk_appendf(&trash, " any_err: %ld\n", pnameserver->counters.any_err);
1342 chunk_appendf(&trash, " nx: %ld\n", pnameserver->counters.nx);
1343 chunk_appendf(&trash, " timeout: %ld\n", pnameserver->counters.timeout);
1344 chunk_appendf(&trash, " refused: %ld\n", pnameserver->counters.refused);
1345 chunk_appendf(&trash, " other: %ld\n", pnameserver->counters.other);
1346 chunk_appendf(&trash, " invalid: %ld\n", pnameserver->counters.invalid);
1347 chunk_appendf(&trash, " too_big: %ld\n", pnameserver->counters.too_big);
1348 chunk_appendf(&trash, " truncated: %ld\n", pnameserver->counters.truncated);
1349 chunk_appendf(&trash, " outdated: %ld\n", pnameserver->counters.outdated);
1350 }
1351 }
1352 }
1353
1354 /* display response */
1355 if (bi_putchk(si_ic(si), &trash) == -1) {
1356 /* let's try again later from this session. We add ourselves into
1357 * this session's users so that it can remove us upon termination.
1358 */
1359 si->flags |= SI_FL_WAIT_ROOM;
1360 return 0;
1361 }
1362
1363 appctx->st2 = STAT_ST_FIN;
1364 /* fall through */
1365
1366 default:
1367 appctx->st2 = STAT_ST_FIN;
1368 return 1;
1369 }
1370}
1371
1372/* register cli keywords */
1373static struct cli_kw_list cli_kws = {{ },{
1374 { { "show", "stat", "resolvers", NULL }, "show stat resolvers [id]: dumps counters from all resolvers section and\n"
1375 " associated name servers",
1376 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
1377 {{},}
1378}};
1379
1380
1381__attribute__((constructor))
1382static void __dns_init(void)
1383{
1384 cli_register_kw(&cli_kws);
1385}
1386