blob: 012fcede4f9a4e513dc2a02449ba82113ba44c0a [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
922 * returns:
923 * 0 in case of error
924 * 1 when no error
925 */
926int dns_init_resolvers(void)
927{
928 struct dns_resolvers *curr_resolvers;
929 struct dns_nameserver *curnameserver;
930 struct dgram_conn *dgram;
931 struct task *t;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200932 char *dns_trash_str;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200933 int fd;
934
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200935 dns_trash_str = malloc(global.tune.bufsize);
936 if (dns_trash_str == NULL) {
Willy Tarreauc3d8cd42016-10-01 09:20:32 +0200937 Alert("Starting resolvers: out of memory.\n");
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200938 return 0;
939 }
940
941 /* allocate memory for the dns_trash buffer used to temporarily store
942 * the records of the received response */
943 chunk_init(&dns_trash, dns_trash_str, global.tune.bufsize);
944
Baptiste Assmann325137d2015-04-13 23:40:55 +0200945 /* give a first random value to our dns query_id seed */
946 dns_query_id_seed = random();
947
948 /* run through the resolvers section list */
949 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
950 /* create the task associated to the resolvers section */
951 if ((t = task_new()) == NULL) {
952 Alert("Starting [%s] resolvers: out of memory.\n", curr_resolvers->id);
953 return 0;
954 }
955
956 /* update task's parameters */
957 t->process = dns_process_resolve;
958 t->context = curr_resolvers;
959 t->expire = TICK_ETERNITY;
960
961 curr_resolvers->t = t;
962
963 list_for_each_entry(curnameserver, &curr_resolvers->nameserver_list, list) {
Vincent Bernat02779b62016-04-03 13:48:43 +0200964 if ((dgram = calloc(1, sizeof(*dgram))) == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200965 Alert("Starting [%s/%s] nameserver: out of memory.\n", curr_resolvers->id,
966 curnameserver->id);
967 return 0;
968 }
969 /* update datagram's parameters */
970 dgram->owner = (void *)curnameserver;
971 dgram->data = &resolve_dgram_cb;
972
973 /* create network UDP socket for this nameserver */
974 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
975 Alert("Starting [%s/%s] nameserver: can't create socket.\n", curr_resolvers->id,
976 curnameserver->id);
977 free(dgram);
978 dgram = NULL;
979 return 0;
980 }
981
982 /* "connect" the UDP socket to the name server IP */
Baptiste Assmann8c62c472015-09-21 20:55:08 +0200983 if (connect(fd, (struct sockaddr*)&curnameserver->addr, get_addr_len(&curnameserver->addr)) == -1) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200984 Alert("Starting [%s/%s] nameserver: can't connect socket.\n", curr_resolvers->id,
985 curnameserver->id);
986 close(fd);
987 free(dgram);
988 dgram = NULL;
989 return 0;
990 }
991
992 /* make the socket non blocking */
993 fcntl(fd, F_SETFL, O_NONBLOCK);
994
995 /* add the fd in the fd list and update its parameters */
996 fd_insert(fd);
997 fdtab[fd].owner = dgram;
998 fdtab[fd].iocb = dgram_fd_handler;
999 fd_want_recv(fd);
1000 dgram->t.sock.fd = fd;
1001
1002 /* update nameserver's datagram property */
1003 curnameserver->dgram = dgram;
1004
1005 continue;
1006 }
1007
1008 /* task can be queued */
1009 task_queue(t);
1010 }
1011
1012 return 1;
1013}
1014
1015/*
1016 * Forge a DNS query. It needs the following information from the caller:
1017 * - <query_id>: the DNS query id corresponding to this query
1018 * - <query_type>: DNS_RTYPE_* request DNS record type (A, AAAA, ANY, etc...)
1019 * - <hostname_dn>: hostname in domain name format
1020 * - <hostname_dn_len>: length of <hostname_dn>
1021 * To store the query, the caller must pass a buffer <buf> and its size <bufsize>
1022 *
1023 * the DNS query is stored in <buf>
1024 * returns:
1025 * -1 if <buf> is too short
1026 */
1027int dns_build_query(int query_id, int query_type, char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
1028{
1029 struct dns_header *dns;
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001030 struct dns_question qinfo;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001031 char *ptr, *bufend;
1032
1033 memset(buf, '\0', bufsize);
1034 ptr = buf;
1035 bufend = buf + bufsize;
1036
1037 /* check if there is enough room for DNS headers */
1038 if (ptr + sizeof(struct dns_header) >= bufend)
1039 return -1;
1040
1041 /* set dns query headers */
1042 dns = (struct dns_header *)ptr;
1043 dns->id = (unsigned short) htons(query_id);
Nenad Merdanovic8ab79422016-07-13 14:03:43 +02001044 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 +02001045 dns->qdcount = htons(1); /* 1 question */
1046 dns->ancount = 0;
1047 dns->nscount = 0;
1048 dns->arcount = 0;
1049
1050 /* move forward ptr */
1051 ptr += sizeof(struct dns_header);
1052
1053 /* check if there is enough room for query hostname */
1054 if ((ptr + hostname_dn_len) >= bufend)
1055 return -1;
1056
1057 /* set up query hostname */
1058 memcpy(ptr, hostname_dn, hostname_dn_len);
1059 ptr[hostname_dn_len + 1] = '\0';
1060
1061 /* move forward ptr */
1062 ptr += (hostname_dn_len + 1);
1063
1064 /* check if there is enough room for query hostname*/
1065 if (ptr + sizeof(struct dns_question) >= bufend)
1066 return -1;
1067
1068 /* set up query info (type and class) */
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001069 qinfo.qtype = htons(query_type);
1070 qinfo.qclass = htons(DNS_RCLASS_IN);
1071 memcpy(ptr, &qinfo, sizeof(qinfo));
Baptiste Assmann325137d2015-04-13 23:40:55 +02001072
1073 ptr += sizeof(struct dns_question);
1074
1075 return ptr - buf;
1076}
1077
1078/*
1079 * turn a string into domain name label:
1080 * www.haproxy.org into 3www7haproxy3org
1081 * if dn memory is pre-allocated, you must provide its size in dn_len
1082 * if dn memory isn't allocated, dn_len must be set to 0.
1083 * In the second case, memory will be allocated.
1084 * in case of error, -1 is returned, otherwise, number of bytes copied in dn
1085 */
Willy Tarreau2100b492015-07-22 16:42:43 +02001086char *dns_str_to_dn_label(const char *string, char *dn, int dn_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001087{
1088 char *c, *d;
1089 int i, offset;
1090
1091 /* offset between string size and theorical dn size */
1092 offset = 1;
1093
1094 /*
1095 * first, get the size of the string turned into its domain name version
1096 * This function also validates the string respect the RFC
1097 */
1098 if ((i = dns_str_to_dn_label_len(string)) == -1)
1099 return NULL;
1100
1101 /* yes, so let's check there is enough memory */
1102 if (dn_len < i + offset)
1103 return NULL;
1104
Willy Tarreaud69d6f32015-07-22 16:45:36 +02001105 i = strlen(string);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001106 memcpy(dn + offset, string, i);
1107 dn[i + offset] = '\0';
1108 /* avoid a '\0' at the beginning of dn string which may prevent the for loop
1109 * below from working.
1110 * Actually, this is the reason of the offset. */
1111 dn[0] = '0';
1112
1113 for (c = dn; *c ; ++c) {
1114 /* c points to the first '0' char or a dot, which we don't want to read */
1115 d = c + offset;
1116 i = 0;
1117 while (*d != '.' && *d) {
1118 i++;
1119 d++;
1120 }
1121 *c = i;
1122
1123 c = d - 1; /* because of c++ of the for loop */
1124 }
1125
1126 return dn;
1127}
1128
1129/*
1130 * compute and return the length of <string> it it were translated into domain name
1131 * label:
1132 * www.haproxy.org into 3www7haproxy3org would return 16
1133 * NOTE: add +1 for '\0' when allocating memory ;)
1134 */
1135int dns_str_to_dn_label_len(const char *string)
1136{
1137 return strlen(string) + 1;
1138}
1139
1140/*
1141 * validates host name:
1142 * - total size
1143 * - each label size individually
1144 * returns:
1145 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1146 * 1 when no error. <err> is left unaffected.
1147 */
1148int dns_hostname_validation(const char *string, char **err)
1149{
1150 const char *c, *d;
1151 int i;
1152
1153 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1154 if (err)
1155 *err = DNS_TOO_LONG_FQDN;
1156 return 0;
1157 }
1158
1159 c = string;
1160 while (*c) {
1161 d = c;
1162
1163 i = 0;
1164 while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) {
1165 i++;
1166 if (!((*d == '-') || (*d == '_') ||
1167 ((*d >= 'a') && (*d <= 'z')) ||
1168 ((*d >= 'A') && (*d <= 'Z')) ||
1169 ((*d >= '0') && (*d <= '9')))) {
1170 if (err)
1171 *err = DNS_INVALID_CHARACTER;
1172 return 0;
1173 }
1174 d++;
1175 }
1176
1177 if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) {
1178 if (err)
1179 *err = DNS_LABEL_TOO_LONG;
1180 return 0;
1181 }
1182
1183 if (*d == '\0')
1184 goto out;
1185
1186 c = ++d;
1187 }
1188 out:
1189 return 1;
1190}
1191
1192/*
1193 * 2 bytes random generator to generate DNS query ID
1194 */
1195uint16_t dns_rnd16(void)
1196{
1197 dns_query_id_seed ^= dns_query_id_seed << 13;
1198 dns_query_id_seed ^= dns_query_id_seed >> 7;
1199 dns_query_id_seed ^= dns_query_id_seed << 17;
1200 return dns_query_id_seed;
1201}
1202
1203
1204/*
1205 * function called when a timeout occurs during name resolution process
1206 * if max number of tries is reached, then stop, otherwise, retry.
1207 */
1208struct task *dns_process_resolve(struct task *t)
1209{
1210 struct dns_resolvers *resolvers = t->context;
1211 struct dns_resolution *resolution, *res_back;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001212 int res_preferred_afinet, res_preferred_afinet6;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001213
1214 /* timeout occurs inevitably for the first element of the FIFO queue */
1215 if (LIST_ISEMPTY(&resolvers->curr_resolution)) {
1216 /* no first entry, so wake up was useless */
1217 t->expire = TICK_ETERNITY;
1218 return t;
1219 }
1220
1221 /* look for the first resolution which is not expired */
1222 list_for_each_entry_safe(resolution, res_back, &resolvers->curr_resolution, list) {
1223 /* when we find the first resolution in the future, then we can stop here */
1224 if (tick_is_le(now_ms, resolution->last_sent_packet))
1225 goto out;
1226
1227 /*
1228 * if current resolution has been tried too many times and finishes in timeout
1229 * we update its status and remove it from the list
1230 */
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001231 if (resolution->try <= 0) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001232 /* clean up resolution information and remove from the list */
1233 dns_reset_resolution(resolution);
1234
1235 /* notify the result to the requester */
1236 resolution->requester_error_cb(resolution, DNS_RESP_TIMEOUT);
Baptiste Assmann382824c2016-01-06 01:53:46 +01001237 goto out;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001238 }
1239
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001240 resolution->try -= 1;
1241
Baptiste Assmann6f79aca2016-04-05 21:19:51 +02001242 res_preferred_afinet = resolution->opts->family_prio == AF_INET && resolution->query_type == DNS_RTYPE_A;
1243 res_preferred_afinet6 = resolution->opts->family_prio == AF_INET6 && resolution->query_type == DNS_RTYPE_AAAA;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001244
1245 /* let's change the query type if needed */
1246 if (res_preferred_afinet6) {
1247 /* fallback from AAAA to A */
1248 resolution->query_type = DNS_RTYPE_A;
1249 }
1250 else if (res_preferred_afinet) {
1251 /* fallback from A to AAAA */
1252 resolution->query_type = DNS_RTYPE_AAAA;
1253 }
1254
Baptiste Assmann382824c2016-01-06 01:53:46 +01001255 /* resend the DNS query */
1256 dns_send_query(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001257
Baptiste Assmann382824c2016-01-06 01:53:46 +01001258 /* check if we have more than one resolution in the list */
1259 if (dns_check_resolution_queue(resolvers) > 1) {
1260 /* move the rsolution to the end of the list */
1261 LIST_DEL(&resolution->list);
1262 LIST_ADDQ(&resolvers->curr_resolution, &resolution->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001263 }
1264 }
1265
1266 out:
1267 dns_update_resolvers_timeout(resolvers);
1268 return t;
1269}
William Lallemand69e96442016-11-19 00:58:54 +01001270
1271static int cli_parse_stat_resolvers(char **args, struct appctx *appctx, void *private)
1272{
1273 struct dns_resolvers *presolvers;
1274
1275 if (*args[3]) {
1276 appctx->ctx.resolvers.ptr = NULL;
1277 list_for_each_entry(presolvers, &dns_resolvers, list) {
1278 if (strcmp(presolvers->id, args[3]) == 0) {
1279 appctx->ctx.resolvers.ptr = presolvers;
1280 break;
1281 }
1282 }
1283 if (appctx->ctx.resolvers.ptr == NULL) {
1284 appctx->ctx.cli.msg = "Can't find that resolvers section\n";
Willy Tarreau3b6e5472016-11-24 15:53:53 +01001285 appctx->st0 = CLI_ST_PRINT;
William Lallemand69e96442016-11-19 00:58:54 +01001286 return 1;
1287 }
1288 }
Willy Tarreau3067bfa2016-12-05 14:50:15 +01001289 return 0;
William Lallemand69e96442016-11-19 00:58:54 +01001290}
1291
1292/* This function dumps counters from all resolvers section and associated name servers.
1293 * It returns 0 if the output buffer is full and it needs
1294 * to be called again, otherwise non-zero.
1295 */
1296static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
1297{
1298 struct stream_interface *si = appctx->owner;
1299 struct dns_resolvers *presolvers;
1300 struct dns_nameserver *pnameserver;
1301
1302 chunk_reset(&trash);
1303
1304 switch (appctx->st2) {
1305 case STAT_ST_INIT:
1306 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
1307 /* fall through */
1308
1309 case STAT_ST_LIST:
1310 if (LIST_ISEMPTY(&dns_resolvers)) {
1311 chunk_appendf(&trash, "No resolvers found\n");
1312 }
1313 else {
1314 list_for_each_entry(presolvers, &dns_resolvers, list) {
1315 if (appctx->ctx.resolvers.ptr != NULL && appctx->ctx.resolvers.ptr != presolvers)
1316 continue;
1317
1318 chunk_appendf(&trash, "Resolvers section %s\n", presolvers->id);
1319 list_for_each_entry(pnameserver, &presolvers->nameserver_list, list) {
1320 chunk_appendf(&trash, " nameserver %s:\n", pnameserver->id);
1321 chunk_appendf(&trash, " sent: %ld\n", pnameserver->counters.sent);
1322 chunk_appendf(&trash, " valid: %ld\n", pnameserver->counters.valid);
1323 chunk_appendf(&trash, " update: %ld\n", pnameserver->counters.update);
1324 chunk_appendf(&trash, " cname: %ld\n", pnameserver->counters.cname);
1325 chunk_appendf(&trash, " cname_error: %ld\n", pnameserver->counters.cname_error);
1326 chunk_appendf(&trash, " any_err: %ld\n", pnameserver->counters.any_err);
1327 chunk_appendf(&trash, " nx: %ld\n", pnameserver->counters.nx);
1328 chunk_appendf(&trash, " timeout: %ld\n", pnameserver->counters.timeout);
1329 chunk_appendf(&trash, " refused: %ld\n", pnameserver->counters.refused);
1330 chunk_appendf(&trash, " other: %ld\n", pnameserver->counters.other);
1331 chunk_appendf(&trash, " invalid: %ld\n", pnameserver->counters.invalid);
1332 chunk_appendf(&trash, " too_big: %ld\n", pnameserver->counters.too_big);
1333 chunk_appendf(&trash, " truncated: %ld\n", pnameserver->counters.truncated);
1334 chunk_appendf(&trash, " outdated: %ld\n", pnameserver->counters.outdated);
1335 }
1336 }
1337 }
1338
1339 /* display response */
1340 if (bi_putchk(si_ic(si), &trash) == -1) {
1341 /* let's try again later from this session. We add ourselves into
1342 * this session's users so that it can remove us upon termination.
1343 */
1344 si->flags |= SI_FL_WAIT_ROOM;
1345 return 0;
1346 }
1347
1348 appctx->st2 = STAT_ST_FIN;
1349 /* fall through */
1350
1351 default:
1352 appctx->st2 = STAT_ST_FIN;
1353 return 1;
1354 }
1355}
1356
1357/* register cli keywords */
1358static struct cli_kw_list cli_kws = {{ },{
1359 { { "show", "stat", "resolvers", NULL }, "show stat resolvers [id]: dumps counters from all resolvers section and\n"
1360 " associated name servers",
1361 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
1362 {{},}
1363}};
1364
1365
1366__attribute__((constructor))
1367static void __dns_init(void)
1368{
1369 cli_register_kw(&cli_kws);
1370}
1371