blob: 7d5ab002f1914d865c072b3340ce4413cbd91ccb [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
25#include <types/global.h>
26#include <types/dns.h>
27#include <types/proto_udp.h>
28
29#include <proto/checks.h>
30#include <proto/dns.h>
31#include <proto/fd.h>
32#include <proto/log.h>
33#include <proto/server.h>
34#include <proto/task.h>
35#include <proto/proto_udp.h>
36
37struct list dns_resolvers = LIST_HEAD_INIT(dns_resolvers);
38struct dns_resolution *resolution = NULL;
39
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +020040/*
41 * pre-allocated memory for maximum record names in a DNS response
42 * Each name is DNS_MAX_NAME_SIZE, we add 1 for the NULL character
43 *
44 * WARNING: this is not thread safe...
45 */
46struct dns_response_packet dns_response;
47struct chunk dns_trash = { };
48struct dns_query_item dns_query_records[DNS_MAX_QUERY_RECORDS];
49struct dns_answer_item dns_answer_records[DNS_MAX_ANSWER_RECORDS];
50
Baptiste Assmann325137d2015-04-13 23:40:55 +020051static int64_t dns_query_id_seed; /* random seed */
52
53/* proto_udp callback functions for a DNS resolution */
54struct dgram_data_cb resolve_dgram_cb = {
55 .recv = dns_resolve_recv,
56 .send = dns_resolve_send,
57};
58
59#if DEBUG
60/*
61 * go through the resolutions associated to a resolvers section and print the ID and hostname in
62 * domain name format
63 * should be used for debug purpose only
64 */
65void dns_print_current_resolutions(struct dns_resolvers *resolvers)
66{
67 list_for_each_entry(resolution, &resolvers->curr_resolution, list) {
68 printf(" resolution %d for %s\n", resolution->query_id, resolution->hostname_dn);
69 }
70}
71#endif
72
73/*
74 * check if there is more than 1 resolution in the resolver's resolution list
75 * return value:
76 * 0: empty list
77 * 1: exactly one entry in the list
78 * 2: more than one entry in the list
79 */
80int dns_check_resolution_queue(struct dns_resolvers *resolvers)
81{
82
83 if (LIST_ISEMPTY(&resolvers->curr_resolution))
84 return 0;
85
86 if ((resolvers->curr_resolution.n) && (resolvers->curr_resolution.n == resolvers->curr_resolution.p))
87 return 1;
88
89 if (! ((resolvers->curr_resolution.n == resolvers->curr_resolution.p)
90 && (&resolvers->curr_resolution != resolvers->curr_resolution.n)))
91 return 2;
92
93 return 0;
94}
95
96/*
97 * reset all parameters of a DNS resolution to 0 (or equivalent)
98 * and clean it up from all associated lists (resolution->qid and resolution->list)
99 */
100void dns_reset_resolution(struct dns_resolution *resolution)
101{
102 /* update resolution status */
103 resolution->step = RSLV_STEP_NONE;
104
105 resolution->try = 0;
106 resolution->try_cname = 0;
107 resolution->last_resolution = now_ms;
108 resolution->nb_responses = 0;
109
110 /* clean up query id */
111 eb32_delete(&resolution->qid);
112 resolution->query_id = 0;
113 resolution->qid.key = 0;
114
115 /* default values */
Thierry Fournierada34842016-02-17 21:25:09 +0100116 if (resolution->opts->family_prio == AF_INET) {
Andrew Hayworthe6a4a322015-10-19 22:29:51 +0000117 resolution->query_type = DNS_RTYPE_A;
118 } else {
119 resolution->query_type = DNS_RTYPE_AAAA;
120 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200121
122 /* the second resolution in the queue becomes the first one */
123 LIST_DEL(&resolution->list);
124}
125
126/*
127 * function called when a network IO is generated on a name server socket for an incoming packet
128 * It performs the following actions:
129 * - check if the packet requires processing (not outdated resolution)
130 * - ensure the DNS packet received is valid and call requester's callback
131 * - call requester's error callback if invalid response
132 */
133void dns_resolve_recv(struct dgram_conn *dgram)
134{
135 struct dns_nameserver *nameserver;
136 struct dns_resolvers *resolvers;
137 struct dns_resolution *resolution;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200138 struct dns_query_item *query;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200139 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
140 unsigned char *bufend;
141 int fd, buflen, ret;
142 unsigned short query_id;
143 struct eb32_node *eb;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200144 struct dns_response_packet *dns_p = &dns_response;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200145
146 fd = dgram->t.sock.fd;
147
148 /* check if ready for reading */
149 if (!fd_recv_ready(fd))
150 return;
151
152 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200153 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200154 return;
155
156 resolvers = nameserver->resolvers;
157
158 /* process all pending input messages */
159 while (1) {
160 /* read message received */
161 memset(buf, '\0', DNS_MAX_UDP_MESSAGE + 1);
162 if ((buflen = recv(fd, (char*)buf , DNS_MAX_UDP_MESSAGE, 0)) < 0) {
163 /* FIXME : for now we consider EAGAIN only */
164 fd_cant_recv(fd);
165 break;
166 }
167
168 /* message too big */
169 if (buflen > DNS_MAX_UDP_MESSAGE) {
170 nameserver->counters.too_big += 1;
171 continue;
172 }
173
174 /* initializing variables */
175 bufend = buf + buflen; /* pointer to mark the end of the buffer */
176
177 /* read the query id from the packet (16 bits) */
178 if (buf + 2 > bufend) {
179 nameserver->counters.invalid += 1;
180 continue;
181 }
182 query_id = dns_response_get_query_id(buf);
183
184 /* search the query_id in the pending resolution tree */
Baptiste Assmann01daef32015-09-02 22:05:24 +0200185 eb = eb32_lookup(&resolvers->query_ids, query_id);
186 if (eb == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200187 /* unknown query id means an outdated response and can be safely ignored */
188 nameserver->counters.outdated += 1;
189 continue;
190 }
191
192 /* known query id means a resolution in prgress */
193 resolution = eb32_entry(eb, struct dns_resolution, qid);
194
195 if (!resolution) {
196 nameserver->counters.outdated += 1;
197 continue;
198 }
199
200 /* number of responses received */
201 resolution->nb_responses += 1;
202
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200203 ret = dns_validate_dns_response(buf, bufend, dns_p);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200204
205 /* treat only errors */
206 switch (ret) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200207 case DNS_RESP_QUERY_COUNT_ERROR:
Baptiste Assmann325137d2015-04-13 23:40:55 +0200208 case DNS_RESP_INVALID:
Baptiste Assmann325137d2015-04-13 23:40:55 +0200209 nameserver->counters.invalid += 1;
210 resolution->requester_error_cb(resolution, DNS_RESP_INVALID);
211 continue;
212
213 case DNS_RESP_ERROR:
214 nameserver->counters.other += 1;
215 resolution->requester_error_cb(resolution, DNS_RESP_ERROR);
216 continue;
217
218 case DNS_RESP_ANCOUNT_ZERO:
219 nameserver->counters.any_err += 1;
220 resolution->requester_error_cb(resolution, DNS_RESP_ANCOUNT_ZERO);
221 continue;
222
223 case DNS_RESP_NX_DOMAIN:
224 nameserver->counters.nx += 1;
225 resolution->requester_error_cb(resolution, DNS_RESP_NX_DOMAIN);
226 continue;
227
228 case DNS_RESP_REFUSED:
229 nameserver->counters.refused += 1;
230 resolution->requester_error_cb(resolution, DNS_RESP_REFUSED);
231 continue;
232
233 case DNS_RESP_CNAME_ERROR:
234 nameserver->counters.cname_error += 1;
235 resolution->requester_error_cb(resolution, DNS_RESP_CNAME_ERROR);
236 continue;
237
Baptiste Assmann0df5d962015-09-02 21:58:32 +0200238 case DNS_RESP_TRUNCATED:
239 nameserver->counters.truncated += 1;
240 resolution->requester_error_cb(resolution, DNS_RESP_TRUNCATED);
241 continue;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200242
243 case DNS_RESP_NO_EXPECTED_RECORD:
244 nameserver->counters.other += 1;
245 resolution->requester_error_cb(resolution, DNS_RESP_NO_EXPECTED_RECORD);
246 continue;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200247 }
248
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200249 /* Now let's check the query's dname corresponds to the one we sent.
250 * We can check only the first query of the list. We send one query at a time
251 * so we get one query in the response */
252 query = LIST_NEXT(&dns_p->query_list, struct dns_query_item *, list);
253 if (query && memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
254 nameserver->counters.other += 1;
255 resolution->requester_error_cb(resolution, DNS_RESP_WRONG_NAME);
256 continue;
257 }
258
Baptiste Assmann37bb3722015-08-07 10:18:32 +0200259 nameserver->counters.valid += 1;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200260 resolution->requester_cb(resolution, nameserver, dns_p);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200261 }
262}
263
264/*
265 * function called when a resolvers network socket is ready to send data
266 * It performs the following actions:
267 */
268void dns_resolve_send(struct dgram_conn *dgram)
269{
270 int fd;
271 struct dns_nameserver *nameserver;
272 struct dns_resolvers *resolvers;
273 struct dns_resolution *resolution;
274
275 fd = dgram->t.sock.fd;
276
277 /* check if ready for sending */
278 if (!fd_send_ready(fd))
279 return;
280
281 /* we don't want/need to be waked up any more for sending */
282 fd_stop_send(fd);
283
284 /* no need to go further if we can't retrieve the nameserver */
Vincent Bernat3c2f2f22016-04-03 13:48:42 +0200285 if ((nameserver = dgram->owner) == NULL)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200286 return;
287
288 resolvers = nameserver->resolvers;
289 resolution = LIST_NEXT(&resolvers->curr_resolution, struct dns_resolution *, list);
290
291 dns_send_query(resolution);
292 dns_update_resolvers_timeout(resolvers);
293}
294
295/*
296 * forge and send a DNS query to resolvers associated to a resolution
297 * It performs the following actions:
298 * returns:
299 * 0 in case of error or safe ignorance
300 * 1 if no error
301 */
302int dns_send_query(struct dns_resolution *resolution)
303{
304 struct dns_resolvers *resolvers;
305 struct dns_nameserver *nameserver;
Erwan Velu5457eb42015-10-15 15:07:26 +0200306 int ret, bufsize, fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200307
308 resolvers = resolution->resolvers;
309
Baptiste Assmann325137d2015-04-13 23:40:55 +0200310 bufsize = dns_build_query(resolution->query_id, resolution->query_type, resolution->hostname_dn,
311 resolution->hostname_dn_len, trash.str, trash.size);
312
313 if (bufsize == -1)
314 return 0;
315
316 list_for_each_entry(nameserver, &resolvers->nameserver_list, list) {
317 fd = nameserver->dgram->t.sock.fd;
318 errno = 0;
319
320 ret = send(fd, trash.str, bufsize, 0);
321
322 if (ret > 0)
323 nameserver->counters.sent += 1;
324
325 if (ret == 0 || errno == EAGAIN) {
326 /* nothing written, let's update the poller that we wanted to send
327 * but we were not able to */
328 fd_want_send(fd);
329 fd_cant_send(fd);
330 }
331 }
332
333 /* update resolution */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200334 resolution->nb_responses = 0;
335 resolution->last_sent_packet = now_ms;
336
337 return 1;
338}
339
340/*
341 * update a resolvers' task timeout for next wake up
342 */
343void dns_update_resolvers_timeout(struct dns_resolvers *resolvers)
344{
345 struct dns_resolution *resolution;
346
347 if (LIST_ISEMPTY(&resolvers->curr_resolution)) {
348 /* no more resolution pending, so no wakeup anymore */
349 resolvers->t->expire = TICK_ETERNITY;
350 }
351 else {
352 resolution = LIST_NEXT(&resolvers->curr_resolution, struct dns_resolution *, list);
353 resolvers->t->expire = tick_add(resolution->last_sent_packet, resolvers->timeout.retry);
354 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200355}
356
357/*
358 * Analyse, re-build and copy the name <name> from the DNS response packet <buffer>.
359 * <name> must point to the 'data_len' information or pointer 'c0' for compressed data.
360 * The result is copied into <dest>, ensuring we don't overflow using <dest_len>
361 * Returns the number of bytes the caller can move forward. If 0 it means an error occured
362 * while parsing the name.
363 * <offset> is the number of bytes the caller could move forward.
364 */
365int dns_read_name(unsigned char *buffer, unsigned char *bufend, unsigned char *name, char *destination, int dest_len, int *offset)
366{
367 int nb_bytes = 0, n = 0;
368 int label_len;
369 unsigned char *reader = name;
370 char *dest = destination;
371
372 while (1) {
373 /* name compression is in use */
374 if ((*reader & 0xc0) == 0xc0) {
375 /* a pointer must point BEFORE current position */
376 if ((buffer + reader[1]) > reader) {
377 goto out_error;
378 }
379
380 n = dns_read_name(buffer, bufend, buffer + reader[1], dest, dest_len - nb_bytes, offset);
381 if (n == 0)
382 goto out_error;
383
384 dest += n;
385 nb_bytes += n;
386 goto out;
387 }
388
389 label_len = *reader;
390 if (label_len == 0)
391 goto out;
392 /* Check if:
393 * - we won't read outside the buffer
394 * - there is enough place in the destination
395 */
396 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
397 goto out_error;
398
399 /* +1 to take label len + label string */
400 label_len += 1;
401
402 memcpy(dest, reader, label_len);
403
404 dest += label_len;
405 nb_bytes += label_len;
406 reader += label_len;
407 }
408
409 out:
410 /* offset computation:
411 * parse from <name> until finding either NULL or a pointer "c0xx"
412 */
413 reader = name;
414 *offset = 0;
415 while (reader < bufend) {
416 if ((reader[0] & 0xc0) == 0xc0) {
417 *offset += 2;
418 break;
419 }
420 else if (*reader == 0) {
421 *offset += 1;
422 break;
423 }
424 *offset += 1;
425 ++reader;
426 }
427
428 return nb_bytes;
429
430 out_error:
431 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200432}
433
434/*
435 * Function to validate that the buffer DNS response provided in <resp> and
436 * finishing before <bufend> is valid from a DNS protocol point of view.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200437 *
438 * The result is stored in the structured pointed by <dns_p>.
439 * It's up to the caller to allocate memory for <dns_p>.
440 *
441 * This function returns one of the DNS_RESP_* code to indicate the type of
442 * error found.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200443 */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200444int dns_validate_dns_response(unsigned char *resp, unsigned char *bufend, struct dns_response_packet *dns_p)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200445{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200446 unsigned char *reader;
447 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
448 int len, flags, offset, ret;
449 int dns_query_record_id, dns_answer_record_id;
450 struct dns_query_item *dns_query;
451 struct dns_answer_item *dns_answer_record;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200452
453 reader = resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200454 len = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200455 previous_dname = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200456
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200457 /* initialization of local buffer */
458 memset(dns_p, '\0', sizeof(struct dns_response_packet));
459 chunk_reset(&dns_trash);
460
461 /* query id */
462 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200463 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200464 dns_p->header.id = reader[0] * 256 + reader[1];
465 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200466
467 /*
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200468 * flags and rcode are stored over 2 bytes
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200469 * First byte contains:
470 * - response flag (1 bit)
471 * - opcode (4 bits)
472 * - authoritative (1 bit)
473 * - truncated (1 bit)
474 * - recursion desired (1 bit)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200475 */
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200476 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200477 return DNS_RESP_INVALID;
478
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200479 flags = reader[0] * 256 + reader[1];
480
481 if (flags & DNS_FLAG_TRUNCATED)
482 return DNS_RESP_TRUNCATED;
483
484 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
485 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200486 return DNS_RESP_NX_DOMAIN;
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200487 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200488 return DNS_RESP_REFUSED;
489
490 return DNS_RESP_ERROR;
491 }
492
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200493 /* move forward 2 bytes for flags */
494 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200495
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200496 /* 2 bytes for question count */
497 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200498 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200499 dns_p->header.qdcount = reader[0] * 256 + reader[1];
500 /* (for now) we send one query only, so we expect only one in the response too */
501 if (dns_p->header.qdcount != 1)
502 return DNS_RESP_QUERY_COUNT_ERROR;
503 if (dns_p->header.qdcount > DNS_MAX_QUERY_RECORDS)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200504 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200505 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200506
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200507 /* 2 bytes for answer count */
508 if (reader + 2 >= bufend)
509 return DNS_RESP_INVALID;
510 dns_p->header.ancount = reader[0] * 256 + reader[1];
511 if (dns_p->header.ancount == 0)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200512 return DNS_RESP_ANCOUNT_ZERO;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200513 /* check if too many records are announced */
514 if (dns_p->header.ancount > DNS_MAX_ANSWER_RECORDS)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200515 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200516 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200517
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200518 /* 2 bytes authority count */
519 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200520 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200521 dns_p->header.nscount = reader[0] * 256 + reader[1];
522 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200523
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200524 /* 2 bytes additional count */
525 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200526 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200527 dns_p->header.arcount = reader[0] * 256 + reader[1];
528 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200529
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200530 /* parsing dns queries */
531 LIST_INIT(&dns_p->query_list);
532 for (dns_query_record_id = 0; dns_query_record_id < dns_p->header.qdcount; dns_query_record_id++) {
533 /* use next pre-allocated dns_query_item after ensuring there is
534 * still one available.
535 * It's then added to our packet query list.
536 */
537 if (dns_query_record_id > DNS_MAX_QUERY_RECORDS)
538 return DNS_RESP_INVALID;
539 dns_query = &dns_query_records[dns_query_record_id];
540 LIST_ADDQ(&dns_p->query_list, &dns_query->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200541
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200542 /* name is a NULL terminated string in our case, since we have
543 * one query per response and the first one can't be compressed
544 * (using the 0x0c format)
545 */
546 offset = 0;
547 len = dns_read_name(resp, bufend, reader, dns_query->name, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200548
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200549 if (len == 0)
550 return DNS_RESP_INVALID;
551
552 reader += offset;
553 previous_dname = dns_query->name;
554
555 /* move forward 2 bytes for question type */
556 if (reader + 2 >= bufend)
557 return DNS_RESP_INVALID;
558 dns_query->type = reader[0] * 256 + reader[1];
559 reader += 2;
560
561 /* move forward 2 bytes for question class */
562 if (reader + 2 >= bufend)
563 return DNS_RESP_INVALID;
564 dns_query->class = reader[0] * 256 + reader[1];
565 reader += 2;
566 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200567
568 /* now parsing response records */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200569 LIST_INIT(&dns_p->answer_list);
570 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 +0200571 if (reader >= bufend)
572 return DNS_RESP_INVALID;
573
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200574 /* pull next response record from the list, if still one available, then add it
575 * to the record list */
576 if (dns_answer_record_id > DNS_MAX_ANSWER_RECORDS)
577 return DNS_RESP_INVALID;
578 dns_answer_record = &dns_answer_records[dns_answer_record_id];
579 LIST_ADDQ(&dns_p->answer_list, &dns_answer_record->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200580
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200581 offset = 0;
582 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200583
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200584 if (len == 0)
585 return DNS_RESP_INVALID;
586
587 /* check if the current record dname is valid.
588 * previous_dname points either to queried dname or last CNAME target
589 */
590 if (memcmp(previous_dname, tmpname, len) != 0) {
591 if (dns_answer_record_id == 0) {
592 /* first record, means a mismatch issue between queried dname
593 * and dname found in the first record */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200594 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200595 } else {
596 /* if not the first record, this means we have a CNAME resolution
597 * error */
598 return DNS_RESP_CNAME_ERROR;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200599 }
600
Baptiste Assmann325137d2015-04-13 23:40:55 +0200601 }
602
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200603 dns_answer_record->name = chunk_newstr(&dns_trash);
604 if (dns_answer_record->name == NULL)
605 return DNS_RESP_INVALID;
Baptiste Assmann5d681ba2015-10-15 15:23:28 +0200606
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200607 ret = chunk_strncat(&dns_trash, tmpname, len);
608 if (ret == 0)
609 return DNS_RESP_INVALID;
Baptiste Assmann2359ff12015-08-07 11:24:05 +0200610
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200611 reader += offset;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200612 if (reader >= bufend)
613 return DNS_RESP_INVALID;
614
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200615 if (reader >= bufend)
616 return DNS_RESP_INVALID;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200617
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200618 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200619 if (reader + 2 > bufend)
620 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200621 dns_answer_record->type = reader[0] * 256 + reader[1];
622 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200623
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200624 /* 2 bytes for class (2) */
625 if (reader + 2 > bufend)
626 return DNS_RESP_INVALID;
627 dns_answer_record->class = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +0200628 reader += 2;
629
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200630 /* 4 bytes for ttl (4) */
631 if (reader + 4 > bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200632 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200633 dns_answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
634 + reader[2] * 256 + reader[3];
635 reader += 4;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200636
637 /* now reading data len */
638 if (reader + 2 > bufend)
639 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200640 dns_answer_record->data_len = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +0200641
642 /* move forward 2 bytes for data len */
643 reader += 2;
644
645 /* analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200646 switch (dns_answer_record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200647 case DNS_RTYPE_A:
648 /* ipv4 is stored on 4 bytes */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200649 if (dns_answer_record->data_len != 4)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200650 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200651 dns_answer_record->address.sa_family = AF_INET;
652 memcpy(&(((struct sockaddr_in *)&dns_answer_record->address)->sin_addr),
653 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200654 break;
655
656 case DNS_RTYPE_CNAME:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200657 /* check if this is the last record and update the caller about the status:
658 * no IP could be found and last record was a CNAME. Could be triggered
659 * by a wrong query type
660 *
661 * + 1 because dns_answer_record_id starts at 0 while number of answers
662 * is an integer and starts at 1.
663 */
664 if (dns_answer_record_id + 1 == dns_p->header.ancount)
665 return DNS_RESP_CNAME_ERROR;
666
667 offset = 0;
668 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset);
669
670 if (len == 0)
671 return DNS_RESP_INVALID;
672
673 dns_answer_record->target = chunk_newstr(&dns_trash);
674 if (dns_answer_record->target == NULL)
675 return DNS_RESP_INVALID;
676
677 ret = chunk_strncat(&dns_trash, tmpname, len);
678 if (ret == 0)
679 return DNS_RESP_INVALID;
680
681 previous_dname = dns_answer_record->target;
682
Baptiste Assmann325137d2015-04-13 23:40:55 +0200683 break;
684
685 case DNS_RTYPE_AAAA:
686 /* ipv6 is stored on 16 bytes */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200687 if (dns_answer_record->data_len != 16)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200688 return DNS_RESP_INVALID;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200689 dns_answer_record->address.sa_family = AF_INET6;
690 memcpy(&(((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr),
691 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200692 break;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200693
Baptiste Assmann325137d2015-04-13 23:40:55 +0200694 } /* switch (record type) */
695
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200696 /* move forward dns_answer_record->data_len for analyzing next record in the response */
697 reader += dns_answer_record->data_len;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200698 } /* for i 0 to ancount */
699
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200700 /* let's add a last \0 to close our last string */
701 ret = chunk_strncat(&dns_trash, "\0", 1);
702 if (ret == 0)
703 return DNS_RESP_INVALID;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200704
Baptiste Assmann325137d2015-04-13 23:40:55 +0200705 return DNS_RESP_VALID;
706}
707
708/*
709 * search dn_name resolution in resp.
710 * If existing IP not found, return the first IP matching family_priority,
711 * otherwise, first ip found
712 * The following tasks are the responsibility of the caller:
713 * - resp contains an error free DNS response
714 * - the response matches the dn_name
715 * For both cases above, dns_validate_dns_response is required
716 * returns one of the DNS_UPD_* code
717 */
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100718#define DNS_MAX_IP_REC 20
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200719int dns_get_ip_from_response(struct dns_response_packet *dns_p,
Thierry Fournierada34842016-02-17 21:25:09 +0100720 struct dns_resolution *resol, void *currentip,
721 short currentip_sin_family,
722 void **newip, short *newip_sin_family)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200723{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200724 struct dns_answer_item *record;
Thierry Fournierada34842016-02-17 21:25:09 +0100725 int family_priority;
726 char *dn_name;
727 int dn_name_len;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200728 int i, cnamelen, currentip_found;
729 unsigned char *cname, *newip4, *newip6;
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100730 struct {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200731 void *ip;
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100732 unsigned char type;
733 } rec[DNS_MAX_IP_REC];
734 int currentip_sel;
735 int j;
736 int rec_nb = 0;
737 int score, max_score;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200738
Thierry Fournierada34842016-02-17 21:25:09 +0100739 family_priority = resol->opts->family_prio;
740 dn_name = resol->hostname_dn;
741 dn_name_len = resol->hostname_dn_len;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200742 cname = *newip = newip4 = newip6 = NULL;
743 cnamelen = currentip_found = 0;
744 *newip_sin_family = AF_UNSPEC;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200745
746 /* now parsing response records */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200747 list_for_each_entry(record, &dns_response.answer_list, list) {
Baptiste Assmanne4c4b7d2015-10-28 02:10:02 +0100748 if (cname) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200749 if (memcmp(record->name, cname, cnamelen) != 0) {
Baptiste Assmanne4c4b7d2015-10-28 02:10:02 +0100750 return DNS_UPD_NAME_ERROR;
751 }
752 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200753 else if (memcmp(record->name, dn_name, dn_name_len) != 0) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200754 return DNS_UPD_NAME_ERROR;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200755 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200756
757 /*
758 * we know the record is either for our server hostname
759 * or a valid CNAME in a crecursion
760 */
761
Baptiste Assmann325137d2015-04-13 23:40:55 +0200762 /* analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200763 switch (record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200764 case DNS_RTYPE_A:
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100765 /* Store IPv4, only if some room is avalaible. */
766 if (rec_nb < DNS_MAX_IP_REC) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200767 rec[rec_nb].ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100768 rec[rec_nb].type = AF_INET;
769 rec_nb++;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200770 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200771 break;
772
773 case DNS_RTYPE_CNAME:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200774 cname = record->target;
775 cnamelen = record->data_len;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200776
Baptiste Assmann325137d2015-04-13 23:40:55 +0200777 break;
778
779 case DNS_RTYPE_AAAA:
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100780 /* Store IPv6, only if some room is avalaible. */
781 if (rec_nb < DNS_MAX_IP_REC) {
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200782 rec[rec_nb].ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100783 rec[rec_nb].type = AF_INET6;
784 rec_nb++;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200785 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200786 break;
787
Baptiste Assmann325137d2015-04-13 23:40:55 +0200788 } /* switch (record type) */
Baptiste Assmannbcbd4912016-04-18 19:42:57 +0200789 } /* list for each record entries */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200790
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100791 /* Select an IP regarding configuration preference.
792 * Top priority is the prefered network ip version,
793 * second priority is the prefered network.
794 * the last priority is the currently used IP,
795 *
796 * For these three priorities, a score is calculated. The
797 * weight are:
798 * 4 - prefered netwok ip version.
799 * 2 - prefered network.
800 * 1 - current ip.
801 * The result with the biggest score is returned.
802 */
803 max_score = -1;
804 for (i = 0; i < rec_nb; i++) {
805
806 score = 0;
807
808 /* Check for prefered ip protocol. */
809 if (rec[i].type == family_priority)
810 score += 4;
811
812 /* Check for prefered network. */
813 for (j = 0; j < resol->opts->pref_net_nb; j++) {
814
815 /* Compare only the same adresses class. */
816 if (resol->opts->pref_net[j].family != rec[i].type)
817 continue;
818
819 if ((rec[i].type == AF_INET &&
Willy Tarreaueec1d382016-07-13 11:59:39 +0200820 in_net_ipv4(rec[i].ip,
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100821 &resol->opts->pref_net[j].mask.in4,
822 &resol->opts->pref_net[j].addr.in4)) ||
823 (rec[i].type == AF_INET6 &&
Willy Tarreaueec1d382016-07-13 11:59:39 +0200824 in_net_ipv6(rec[i].ip,
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100825 &resol->opts->pref_net[j].mask.in6,
826 &resol->opts->pref_net[j].addr.in6))) {
827 score += 2;
828 break;
829 }
830 }
831
832 /* Check for current ip matching. */
833 if (rec[i].type == currentip_sin_family &&
834 ((currentip_sin_family == AF_INET &&
Willy Tarreaueec1d382016-07-13 11:59:39 +0200835 memcmp(rec[i].ip, currentip, 4) == 0) ||
Thierry Fournierac88cfe2016-02-17 22:05:30 +0100836 (currentip_sin_family == AF_INET6 &&
837 memcmp(rec[i].ip, currentip, 16) == 0))) {
838 score += 1;
839 currentip_sel = 1;
840 } else
841 currentip_sel = 0;
842
843 /* Keep the address if the score is better than the previous
844 * score. The maximum score is 7, if this value is reached,
845 * we break the parsing. Implicitly, this score is reached
846 * the ip selected is the current ip.
847 */
848 if (score > max_score) {
849 if (rec[i].type == AF_INET)
850 newip4 = rec[i].ip;
851 else
852 newip6 = rec[i].ip;
853 currentip_found = currentip_sel;
854 if (score == 7)
855 return DNS_UPD_NO;
856 max_score = score;
857 }
858 }
859
Baptiste Assmann325137d2015-04-13 23:40:55 +0200860 /* only CNAMEs in the response, no IP found */
861 if (cname && !newip4 && !newip6) {
862 return DNS_UPD_CNAME;
863 }
864
Baptiste Assmann0453a1d2015-09-09 00:51:08 +0200865 /* no IP found in the response */
866 if (!newip4 && !newip6) {
867 return DNS_UPD_NO_IP_FOUND;
868 }
869
Baptiste Assmann325137d2015-04-13 23:40:55 +0200870 /* case when the caller looks first for an IPv4 address */
871 if (family_priority == AF_INET) {
872 if (newip4) {
873 *newip = newip4;
874 *newip_sin_family = AF_INET;
875 if (currentip_found == 1)
876 return DNS_UPD_NO;
877 return DNS_UPD_SRVIP_NOT_FOUND;
878 }
879 else if (newip6) {
880 *newip = newip6;
881 *newip_sin_family = AF_INET6;
882 if (currentip_found == 1)
883 return DNS_UPD_NO;
884 return DNS_UPD_SRVIP_NOT_FOUND;
885 }
886 }
887 /* case when the caller looks first for an IPv6 address */
888 else if (family_priority == AF_INET6) {
889 if (newip6) {
890 *newip = newip6;
891 *newip_sin_family = AF_INET6;
892 if (currentip_found == 1)
893 return DNS_UPD_NO;
894 return DNS_UPD_SRVIP_NOT_FOUND;
895 }
896 else if (newip4) {
897 *newip = newip4;
898 *newip_sin_family = AF_INET;
899 if (currentip_found == 1)
900 return DNS_UPD_NO;
901 return DNS_UPD_SRVIP_NOT_FOUND;
902 }
903 }
904 /* case when the caller have no preference (we prefer IPv6) */
905 else if (family_priority == AF_UNSPEC) {
906 if (newip6) {
907 *newip = newip6;
908 *newip_sin_family = AF_INET6;
909 if (currentip_found == 1)
910 return DNS_UPD_NO;
911 return DNS_UPD_SRVIP_NOT_FOUND;
912 }
913 else if (newip4) {
914 *newip = newip4;
915 *newip_sin_family = AF_INET;
916 if (currentip_found == 1)
917 return DNS_UPD_NO;
918 return DNS_UPD_SRVIP_NOT_FOUND;
919 }
920 }
921
922 /* no reason why we should change the server's IP address */
923 return DNS_UPD_NO;
924}
925
926/*
927 * returns the query id contained in a DNS response
928 */
Thiago Farinab1af23e2016-01-20 23:46:34 +0100929unsigned short dns_response_get_query_id(unsigned char *resp)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200930{
931 /* read the query id from the response */
932 return resp[0] * 256 + resp[1];
933}
934
935/*
936 * used during haproxy's init phase
937 * parses resolvers sections and initializes:
938 * - task (time events) for each resolvers section
939 * - the datagram layer (network IO events) for each nameserver
940 * returns:
941 * 0 in case of error
942 * 1 when no error
943 */
944int dns_init_resolvers(void)
945{
946 struct dns_resolvers *curr_resolvers;
947 struct dns_nameserver *curnameserver;
948 struct dgram_conn *dgram;
949 struct task *t;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200950 char *dns_trash_str;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200951 int fd;
952
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200953 dns_trash_str = malloc(global.tune.bufsize);
954 if (dns_trash_str == NULL) {
955 Alert("Starting [%s] resolvers: out of memory.\n", curr_resolvers->id);
956 return 0;
957 }
958
959 /* allocate memory for the dns_trash buffer used to temporarily store
960 * the records of the received response */
961 chunk_init(&dns_trash, dns_trash_str, global.tune.bufsize);
962
Baptiste Assmann325137d2015-04-13 23:40:55 +0200963 /* give a first random value to our dns query_id seed */
964 dns_query_id_seed = random();
965
966 /* run through the resolvers section list */
967 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
968 /* create the task associated to the resolvers section */
969 if ((t = task_new()) == NULL) {
970 Alert("Starting [%s] resolvers: out of memory.\n", curr_resolvers->id);
971 return 0;
972 }
973
974 /* update task's parameters */
975 t->process = dns_process_resolve;
976 t->context = curr_resolvers;
977 t->expire = TICK_ETERNITY;
978
979 curr_resolvers->t = t;
980
981 list_for_each_entry(curnameserver, &curr_resolvers->nameserver_list, list) {
Vincent Bernat02779b62016-04-03 13:48:43 +0200982 if ((dgram = calloc(1, sizeof(*dgram))) == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200983 Alert("Starting [%s/%s] nameserver: out of memory.\n", curr_resolvers->id,
984 curnameserver->id);
985 return 0;
986 }
987 /* update datagram's parameters */
988 dgram->owner = (void *)curnameserver;
989 dgram->data = &resolve_dgram_cb;
990
991 /* create network UDP socket for this nameserver */
992 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
993 Alert("Starting [%s/%s] nameserver: can't create socket.\n", curr_resolvers->id,
994 curnameserver->id);
995 free(dgram);
996 dgram = NULL;
997 return 0;
998 }
999
1000 /* "connect" the UDP socket to the name server IP */
Baptiste Assmann8c62c472015-09-21 20:55:08 +02001001 if (connect(fd, (struct sockaddr*)&curnameserver->addr, get_addr_len(&curnameserver->addr)) == -1) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001002 Alert("Starting [%s/%s] nameserver: can't connect socket.\n", curr_resolvers->id,
1003 curnameserver->id);
1004 close(fd);
1005 free(dgram);
1006 dgram = NULL;
1007 return 0;
1008 }
1009
1010 /* make the socket non blocking */
1011 fcntl(fd, F_SETFL, O_NONBLOCK);
1012
1013 /* add the fd in the fd list and update its parameters */
1014 fd_insert(fd);
1015 fdtab[fd].owner = dgram;
1016 fdtab[fd].iocb = dgram_fd_handler;
1017 fd_want_recv(fd);
1018 dgram->t.sock.fd = fd;
1019
1020 /* update nameserver's datagram property */
1021 curnameserver->dgram = dgram;
1022
1023 continue;
1024 }
1025
1026 /* task can be queued */
1027 task_queue(t);
1028 }
1029
1030 return 1;
1031}
1032
1033/*
1034 * Forge a DNS query. It needs the following information from the caller:
1035 * - <query_id>: the DNS query id corresponding to this query
1036 * - <query_type>: DNS_RTYPE_* request DNS record type (A, AAAA, ANY, etc...)
1037 * - <hostname_dn>: hostname in domain name format
1038 * - <hostname_dn_len>: length of <hostname_dn>
1039 * To store the query, the caller must pass a buffer <buf> and its size <bufsize>
1040 *
1041 * the DNS query is stored in <buf>
1042 * returns:
1043 * -1 if <buf> is too short
1044 */
1045int dns_build_query(int query_id, int query_type, char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
1046{
1047 struct dns_header *dns;
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001048 struct dns_question qinfo;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001049 char *ptr, *bufend;
1050
1051 memset(buf, '\0', bufsize);
1052 ptr = buf;
1053 bufend = buf + bufsize;
1054
1055 /* check if there is enough room for DNS headers */
1056 if (ptr + sizeof(struct dns_header) >= bufend)
1057 return -1;
1058
1059 /* set dns query headers */
1060 dns = (struct dns_header *)ptr;
1061 dns->id = (unsigned short) htons(query_id);
Nenad Merdanovic8ab79422016-07-13 14:03:43 +02001062 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 +02001063 dns->qdcount = htons(1); /* 1 question */
1064 dns->ancount = 0;
1065 dns->nscount = 0;
1066 dns->arcount = 0;
1067
1068 /* move forward ptr */
1069 ptr += sizeof(struct dns_header);
1070
1071 /* check if there is enough room for query hostname */
1072 if ((ptr + hostname_dn_len) >= bufend)
1073 return -1;
1074
1075 /* set up query hostname */
1076 memcpy(ptr, hostname_dn, hostname_dn_len);
1077 ptr[hostname_dn_len + 1] = '\0';
1078
1079 /* move forward ptr */
1080 ptr += (hostname_dn_len + 1);
1081
1082 /* check if there is enough room for query hostname*/
1083 if (ptr + sizeof(struct dns_question) >= bufend)
1084 return -1;
1085
1086 /* set up query info (type and class) */
Vincent Bernat9b7125c2016-04-08 22:17:45 +02001087 qinfo.qtype = htons(query_type);
1088 qinfo.qclass = htons(DNS_RCLASS_IN);
1089 memcpy(ptr, &qinfo, sizeof(qinfo));
Baptiste Assmann325137d2015-04-13 23:40:55 +02001090
1091 ptr += sizeof(struct dns_question);
1092
1093 return ptr - buf;
1094}
1095
1096/*
1097 * turn a string into domain name label:
1098 * www.haproxy.org into 3www7haproxy3org
1099 * if dn memory is pre-allocated, you must provide its size in dn_len
1100 * if dn memory isn't allocated, dn_len must be set to 0.
1101 * In the second case, memory will be allocated.
1102 * in case of error, -1 is returned, otherwise, number of bytes copied in dn
1103 */
Willy Tarreau2100b492015-07-22 16:42:43 +02001104char *dns_str_to_dn_label(const char *string, char *dn, int dn_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001105{
1106 char *c, *d;
1107 int i, offset;
1108
1109 /* offset between string size and theorical dn size */
1110 offset = 1;
1111
1112 /*
1113 * first, get the size of the string turned into its domain name version
1114 * This function also validates the string respect the RFC
1115 */
1116 if ((i = dns_str_to_dn_label_len(string)) == -1)
1117 return NULL;
1118
1119 /* yes, so let's check there is enough memory */
1120 if (dn_len < i + offset)
1121 return NULL;
1122
Willy Tarreaud69d6f32015-07-22 16:45:36 +02001123 i = strlen(string);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001124 memcpy(dn + offset, string, i);
1125 dn[i + offset] = '\0';
1126 /* avoid a '\0' at the beginning of dn string which may prevent the for loop
1127 * below from working.
1128 * Actually, this is the reason of the offset. */
1129 dn[0] = '0';
1130
1131 for (c = dn; *c ; ++c) {
1132 /* c points to the first '0' char or a dot, which we don't want to read */
1133 d = c + offset;
1134 i = 0;
1135 while (*d != '.' && *d) {
1136 i++;
1137 d++;
1138 }
1139 *c = i;
1140
1141 c = d - 1; /* because of c++ of the for loop */
1142 }
1143
1144 return dn;
1145}
1146
1147/*
1148 * compute and return the length of <string> it it were translated into domain name
1149 * label:
1150 * www.haproxy.org into 3www7haproxy3org would return 16
1151 * NOTE: add +1 for '\0' when allocating memory ;)
1152 */
1153int dns_str_to_dn_label_len(const char *string)
1154{
1155 return strlen(string) + 1;
1156}
1157
1158/*
1159 * validates host name:
1160 * - total size
1161 * - each label size individually
1162 * returns:
1163 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1164 * 1 when no error. <err> is left unaffected.
1165 */
1166int dns_hostname_validation(const char *string, char **err)
1167{
1168 const char *c, *d;
1169 int i;
1170
1171 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1172 if (err)
1173 *err = DNS_TOO_LONG_FQDN;
1174 return 0;
1175 }
1176
1177 c = string;
1178 while (*c) {
1179 d = c;
1180
1181 i = 0;
1182 while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) {
1183 i++;
1184 if (!((*d == '-') || (*d == '_') ||
1185 ((*d >= 'a') && (*d <= 'z')) ||
1186 ((*d >= 'A') && (*d <= 'Z')) ||
1187 ((*d >= '0') && (*d <= '9')))) {
1188 if (err)
1189 *err = DNS_INVALID_CHARACTER;
1190 return 0;
1191 }
1192 d++;
1193 }
1194
1195 if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) {
1196 if (err)
1197 *err = DNS_LABEL_TOO_LONG;
1198 return 0;
1199 }
1200
1201 if (*d == '\0')
1202 goto out;
1203
1204 c = ++d;
1205 }
1206 out:
1207 return 1;
1208}
1209
1210/*
1211 * 2 bytes random generator to generate DNS query ID
1212 */
1213uint16_t dns_rnd16(void)
1214{
1215 dns_query_id_seed ^= dns_query_id_seed << 13;
1216 dns_query_id_seed ^= dns_query_id_seed >> 7;
1217 dns_query_id_seed ^= dns_query_id_seed << 17;
1218 return dns_query_id_seed;
1219}
1220
1221
1222/*
1223 * function called when a timeout occurs during name resolution process
1224 * if max number of tries is reached, then stop, otherwise, retry.
1225 */
1226struct task *dns_process_resolve(struct task *t)
1227{
1228 struct dns_resolvers *resolvers = t->context;
1229 struct dns_resolution *resolution, *res_back;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001230 int res_preferred_afinet, res_preferred_afinet6;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001231
1232 /* timeout occurs inevitably for the first element of the FIFO queue */
1233 if (LIST_ISEMPTY(&resolvers->curr_resolution)) {
1234 /* no first entry, so wake up was useless */
1235 t->expire = TICK_ETERNITY;
1236 return t;
1237 }
1238
1239 /* look for the first resolution which is not expired */
1240 list_for_each_entry_safe(resolution, res_back, &resolvers->curr_resolution, list) {
1241 /* when we find the first resolution in the future, then we can stop here */
1242 if (tick_is_le(now_ms, resolution->last_sent_packet))
1243 goto out;
1244
1245 /*
1246 * if current resolution has been tried too many times and finishes in timeout
1247 * we update its status and remove it from the list
1248 */
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001249 if (resolution->try <= 0) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001250 /* clean up resolution information and remove from the list */
1251 dns_reset_resolution(resolution);
1252
1253 /* notify the result to the requester */
1254 resolution->requester_error_cb(resolution, DNS_RESP_TIMEOUT);
Baptiste Assmann382824c2016-01-06 01:53:46 +01001255 goto out;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001256 }
1257
Baptiste Assmannf778bb42015-09-09 00:54:38 +02001258 resolution->try -= 1;
1259
Baptiste Assmann6f79aca2016-04-05 21:19:51 +02001260 res_preferred_afinet = resolution->opts->family_prio == AF_INET && resolution->query_type == DNS_RTYPE_A;
1261 res_preferred_afinet6 = resolution->opts->family_prio == AF_INET6 && resolution->query_type == DNS_RTYPE_AAAA;
Baptiste Assmann060e5732016-01-06 02:01:59 +01001262
1263 /* let's change the query type if needed */
1264 if (res_preferred_afinet6) {
1265 /* fallback from AAAA to A */
1266 resolution->query_type = DNS_RTYPE_A;
1267 }
1268 else if (res_preferred_afinet) {
1269 /* fallback from A to AAAA */
1270 resolution->query_type = DNS_RTYPE_AAAA;
1271 }
1272
Baptiste Assmann382824c2016-01-06 01:53:46 +01001273 /* resend the DNS query */
1274 dns_send_query(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001275
Baptiste Assmann382824c2016-01-06 01:53:46 +01001276 /* check if we have more than one resolution in the list */
1277 if (dns_check_resolution_queue(resolvers) > 1) {
1278 /* move the rsolution to the end of the list */
1279 LIST_DEL(&resolution->list);
1280 LIST_ADDQ(&resolvers->curr_resolution, &resolution->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001281 }
1282 }
1283
1284 out:
1285 dns_update_resolvers_timeout(resolvers);
1286 return t;
1287}