blob: d002f1b93919b6f27d2bb809e2c5528074287555 [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
40static int64_t dns_query_id_seed; /* random seed */
41
42/* proto_udp callback functions for a DNS resolution */
43struct dgram_data_cb resolve_dgram_cb = {
44 .recv = dns_resolve_recv,
45 .send = dns_resolve_send,
46};
47
48#if DEBUG
49/*
50 * go through the resolutions associated to a resolvers section and print the ID and hostname in
51 * domain name format
52 * should be used for debug purpose only
53 */
54void dns_print_current_resolutions(struct dns_resolvers *resolvers)
55{
56 list_for_each_entry(resolution, &resolvers->curr_resolution, list) {
57 printf(" resolution %d for %s\n", resolution->query_id, resolution->hostname_dn);
58 }
59}
60#endif
61
62/*
63 * check if there is more than 1 resolution in the resolver's resolution list
64 * return value:
65 * 0: empty list
66 * 1: exactly one entry in the list
67 * 2: more than one entry in the list
68 */
69int dns_check_resolution_queue(struct dns_resolvers *resolvers)
70{
71
72 if (LIST_ISEMPTY(&resolvers->curr_resolution))
73 return 0;
74
75 if ((resolvers->curr_resolution.n) && (resolvers->curr_resolution.n == resolvers->curr_resolution.p))
76 return 1;
77
78 if (! ((resolvers->curr_resolution.n == resolvers->curr_resolution.p)
79 && (&resolvers->curr_resolution != resolvers->curr_resolution.n)))
80 return 2;
81
82 return 0;
83}
84
85/*
86 * reset all parameters of a DNS resolution to 0 (or equivalent)
87 * and clean it up from all associated lists (resolution->qid and resolution->list)
88 */
89void dns_reset_resolution(struct dns_resolution *resolution)
90{
91 /* update resolution status */
92 resolution->step = RSLV_STEP_NONE;
93
94 resolution->try = 0;
95 resolution->try_cname = 0;
96 resolution->last_resolution = now_ms;
97 resolution->nb_responses = 0;
98
99 /* clean up query id */
100 eb32_delete(&resolution->qid);
101 resolution->query_id = 0;
102 resolution->qid.key = 0;
103
104 /* default values */
105 resolution->query_type = DNS_RTYPE_ANY;
106
107 /* the second resolution in the queue becomes the first one */
108 LIST_DEL(&resolution->list);
109}
110
111/*
112 * function called when a network IO is generated on a name server socket for an incoming packet
113 * It performs the following actions:
114 * - check if the packet requires processing (not outdated resolution)
115 * - ensure the DNS packet received is valid and call requester's callback
116 * - call requester's error callback if invalid response
117 */
118void dns_resolve_recv(struct dgram_conn *dgram)
119{
120 struct dns_nameserver *nameserver;
121 struct dns_resolvers *resolvers;
122 struct dns_resolution *resolution;
123 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
124 unsigned char *bufend;
125 int fd, buflen, ret;
126 unsigned short query_id;
127 struct eb32_node *eb;
128
129 fd = dgram->t.sock.fd;
130
131 /* check if ready for reading */
132 if (!fd_recv_ready(fd))
133 return;
134
135 /* no need to go further if we can't retrieve the nameserver */
136 if ((nameserver = (struct dns_nameserver *)dgram->owner) == NULL)
137 return;
138
139 resolvers = nameserver->resolvers;
140
141 /* process all pending input messages */
142 while (1) {
143 /* read message received */
144 memset(buf, '\0', DNS_MAX_UDP_MESSAGE + 1);
145 if ((buflen = recv(fd, (char*)buf , DNS_MAX_UDP_MESSAGE, 0)) < 0) {
146 /* FIXME : for now we consider EAGAIN only */
147 fd_cant_recv(fd);
148 break;
149 }
150
151 /* message too big */
152 if (buflen > DNS_MAX_UDP_MESSAGE) {
153 nameserver->counters.too_big += 1;
154 continue;
155 }
156
157 /* initializing variables */
158 bufend = buf + buflen; /* pointer to mark the end of the buffer */
159
160 /* read the query id from the packet (16 bits) */
161 if (buf + 2 > bufend) {
162 nameserver->counters.invalid += 1;
163 continue;
164 }
165 query_id = dns_response_get_query_id(buf);
166
167 /* search the query_id in the pending resolution tree */
Baptiste Assmann01daef32015-09-02 22:05:24 +0200168 eb = eb32_lookup(&resolvers->query_ids, query_id);
169 if (eb == NULL) {
Baptiste Assmann325137d2015-04-13 23:40:55 +0200170 /* unknown query id means an outdated response and can be safely ignored */
171 nameserver->counters.outdated += 1;
172 continue;
173 }
174
175 /* known query id means a resolution in prgress */
176 resolution = eb32_entry(eb, struct dns_resolution, qid);
177
178 if (!resolution) {
179 nameserver->counters.outdated += 1;
180 continue;
181 }
182
183 /* number of responses received */
184 resolution->nb_responses += 1;
185
186 ret = dns_validate_dns_response(buf, bufend, resolution->hostname_dn, resolution->hostname_dn_len);
187
188 /* treat only errors */
189 switch (ret) {
190 case DNS_RESP_INVALID:
191 case DNS_RESP_WRONG_NAME:
192 nameserver->counters.invalid += 1;
193 resolution->requester_error_cb(resolution, DNS_RESP_INVALID);
194 continue;
195
196 case DNS_RESP_ERROR:
197 nameserver->counters.other += 1;
198 resolution->requester_error_cb(resolution, DNS_RESP_ERROR);
199 continue;
200
201 case DNS_RESP_ANCOUNT_ZERO:
202 nameserver->counters.any_err += 1;
203 resolution->requester_error_cb(resolution, DNS_RESP_ANCOUNT_ZERO);
204 continue;
205
206 case DNS_RESP_NX_DOMAIN:
207 nameserver->counters.nx += 1;
208 resolution->requester_error_cb(resolution, DNS_RESP_NX_DOMAIN);
209 continue;
210
211 case DNS_RESP_REFUSED:
212 nameserver->counters.refused += 1;
213 resolution->requester_error_cb(resolution, DNS_RESP_REFUSED);
214 continue;
215
216 case DNS_RESP_CNAME_ERROR:
217 nameserver->counters.cname_error += 1;
218 resolution->requester_error_cb(resolution, DNS_RESP_CNAME_ERROR);
219 continue;
220
Baptiste Assmann0df5d962015-09-02 21:58:32 +0200221 case DNS_RESP_TRUNCATED:
222 nameserver->counters.truncated += 1;
223 resolution->requester_error_cb(resolution, DNS_RESP_TRUNCATED);
224 continue;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200225
226 case DNS_RESP_NO_EXPECTED_RECORD:
227 nameserver->counters.other += 1;
228 resolution->requester_error_cb(resolution, DNS_RESP_NO_EXPECTED_RECORD);
229 continue;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200230 }
231
Baptiste Assmann37bb3722015-08-07 10:18:32 +0200232 nameserver->counters.valid += 1;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200233 resolution->requester_cb(resolution, nameserver, buf, buflen);
234 }
235}
236
237/*
238 * function called when a resolvers network socket is ready to send data
239 * It performs the following actions:
240 */
241void dns_resolve_send(struct dgram_conn *dgram)
242{
243 int fd;
244 struct dns_nameserver *nameserver;
245 struct dns_resolvers *resolvers;
246 struct dns_resolution *resolution;
247
248 fd = dgram->t.sock.fd;
249
250 /* check if ready for sending */
251 if (!fd_send_ready(fd))
252 return;
253
254 /* we don't want/need to be waked up any more for sending */
255 fd_stop_send(fd);
256
257 /* no need to go further if we can't retrieve the nameserver */
258 if ((nameserver = (struct dns_nameserver *)dgram->owner) == NULL)
259 return;
260
261 resolvers = nameserver->resolvers;
262 resolution = LIST_NEXT(&resolvers->curr_resolution, struct dns_resolution *, list);
263
264 dns_send_query(resolution);
265 dns_update_resolvers_timeout(resolvers);
266}
267
268/*
269 * forge and send a DNS query to resolvers associated to a resolution
270 * It performs the following actions:
271 * returns:
272 * 0 in case of error or safe ignorance
273 * 1 if no error
274 */
275int dns_send_query(struct dns_resolution *resolution)
276{
277 struct dns_resolvers *resolvers;
278 struct dns_nameserver *nameserver;
279 int ret, send_error, bufsize, fd;
280
281 resolvers = resolution->resolvers;
282
283 ret = send_error = 0;
284 bufsize = dns_build_query(resolution->query_id, resolution->query_type, resolution->hostname_dn,
285 resolution->hostname_dn_len, trash.str, trash.size);
286
287 if (bufsize == -1)
288 return 0;
289
290 list_for_each_entry(nameserver, &resolvers->nameserver_list, list) {
291 fd = nameserver->dgram->t.sock.fd;
292 errno = 0;
293
294 ret = send(fd, trash.str, bufsize, 0);
295
296 if (ret > 0)
297 nameserver->counters.sent += 1;
298
299 if (ret == 0 || errno == EAGAIN) {
300 /* nothing written, let's update the poller that we wanted to send
301 * but we were not able to */
302 fd_want_send(fd);
303 fd_cant_send(fd);
304 }
305 }
306
307 /* update resolution */
308 resolution->try += 1;
309 resolution->nb_responses = 0;
310 resolution->last_sent_packet = now_ms;
311
312 return 1;
313}
314
315/*
316 * update a resolvers' task timeout for next wake up
317 */
318void dns_update_resolvers_timeout(struct dns_resolvers *resolvers)
319{
320 struct dns_resolution *resolution;
321
322 if (LIST_ISEMPTY(&resolvers->curr_resolution)) {
323 /* no more resolution pending, so no wakeup anymore */
324 resolvers->t->expire = TICK_ETERNITY;
325 }
326 else {
327 resolution = LIST_NEXT(&resolvers->curr_resolution, struct dns_resolution *, list);
328 resolvers->t->expire = tick_add(resolution->last_sent_packet, resolvers->timeout.retry);
329 }
330}
331
332/*
333 * Function to validate that the buffer DNS response provided in <resp> and
334 * finishing before <bufend> is valid from a DNS protocol point of view.
335 * The caller can also ask the function to check if the response contains data
336 * for a domain name <dn_name> whose length is <dn_name_len> returns one of the
337 * DNS_RESP_* code.
338 */
339int dns_validate_dns_response(unsigned char *resp, unsigned char *bufend, char *dn_name, int dn_name_len)
340{
341 unsigned char *reader, *cname, *ptr;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200342 int i, len, flags, type, ancount, cnamelen, expected_record;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200343
344 reader = resp;
345 cname = NULL;
346 cnamelen = 0;
347 len = 0;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200348 expected_record = 0; /* flag to report if at least one expected record type is found in the response.
349 * For now, only records containing an IP address (A and AAAA) are
350 * considered as expected.
351 * Later, this function may be updated to let the caller decide what type
352 * of record is expected to consider the response as valid. (SRV or TXT types)
353 */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200354
355 /* move forward 2 bytes for the query id */
356 reader += 2;
357 if (reader >= bufend)
358 return DNS_RESP_INVALID;
359
360 /*
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200361 * flags are stored over 2 bytes
362 * First byte contains:
363 * - response flag (1 bit)
364 * - opcode (4 bits)
365 * - authoritative (1 bit)
366 * - truncated (1 bit)
367 * - recursion desired (1 bit)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200368 */
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200369 if (reader + 2 >= bufend)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200370 return DNS_RESP_INVALID;
371
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200372 flags = reader[0] * 256 + reader[1];
373
374 if (flags & DNS_FLAG_TRUNCATED)
375 return DNS_RESP_TRUNCATED;
376
377 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
378 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200379 return DNS_RESP_NX_DOMAIN;
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200380 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200381 return DNS_RESP_REFUSED;
382
383 return DNS_RESP_ERROR;
384 }
385
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200386 /* move forward 2 bytes for flags */
387 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200388 if (reader >= bufend)
389 return DNS_RESP_INVALID;
390
391 /* move forward 2 bytes for question count */
392 reader += 2;
393 if (reader >= bufend)
394 return DNS_RESP_INVALID;
395
396 /* analyzing answer count */
397 if (reader + 2 > bufend)
398 return DNS_RESP_INVALID;
399 ancount = reader[0] * 256 + reader[1];
400
401 if (ancount == 0)
402 return DNS_RESP_ANCOUNT_ZERO;
403
404 /* move forward 2 bytes for answer count */
405 reader += 2;
406 if (reader >= bufend)
407 return DNS_RESP_INVALID;
408
409 /* move forward 4 bytes authority and additional count */
410 reader += 4;
411 if (reader >= bufend)
412 return DNS_RESP_INVALID;
413
414 /* check if the name can stand in response */
415 if (dn_name && ((reader + dn_name_len + 1) > bufend))
416 return DNS_RESP_INVALID;
417
418 /* check hostname */
419 if (dn_name && (memcmp(reader, dn_name, dn_name_len) != 0))
420 return DNS_RESP_WRONG_NAME;
421
422 /* move forward hostname len bytes + 1 for NULL byte */
423 if (dn_name) {
424 reader = reader + dn_name_len + 1;
425 }
426 else {
427 ptr = reader;
428 while (*ptr) {
429 ptr++;
430 if (ptr >= bufend)
431 return DNS_RESP_INVALID;
432 }
433 reader = ptr + 1;
434 }
435
436 /* move forward 4 bytes for question type and question class */
437 reader += 4;
438 if (reader >= bufend)
439 return DNS_RESP_INVALID;
440
441 /* now parsing response records */
442 for (i = 1; i <= ancount; i++) {
443 if (reader >= bufend)
444 return DNS_RESP_INVALID;
445
446 /*
447 * name can be a pointer, so move forward reader cursor accordingly
448 * if 1st byte is '11XXXXXX', it means name is a pointer
449 * and 2nd byte gives the offset from resp where the hostname can
450 * be found
451 */
452 if ((*reader & 0xc0) == 0xc0) {
453 /*
454 * pointer, hostname can be found at resp + *(reader + 1)
455 */
456 if (reader + 1 > bufend)
457 return DNS_RESP_INVALID;
458
459 ptr = resp + *(reader + 1);
460
461 /* check if the pointer points inside the buffer */
462 if (ptr >= bufend)
463 return DNS_RESP_INVALID;
464 }
465 else {
466 /*
467 * name is a string which starts at first byte
468 * checking against last cname when recursing through the response
469 */
470 /* look for the end of the string and ensure it's in the buffer */
471 ptr = reader;
472 len = 0;
473 while (*ptr) {
474 ++len;
475 ++ptr;
476 if (ptr >= bufend)
477 return DNS_RESP_INVALID;
478 }
479
480 /* if cname is set, it means a CNAME recursion is in progress */
481 ptr = reader;
482 }
483
484 /* ptr now points to the name */
Baptiste Assmann2359ff12015-08-07 11:24:05 +0200485 if ((*reader & 0xc0) != 0xc0) {
486 /* if cname is set, it means a CNAME recursion is in progress */
Baptiste Assmann325137d2015-04-13 23:40:55 +0200487 if (cname) {
Baptiste Assmann2359ff12015-08-07 11:24:05 +0200488 /* check if the name can stand in response */
489 if ((reader + cnamelen) > bufend)
490 return DNS_RESP_INVALID;
491 /* compare cname and current name */
492 if (memcmp(ptr, cname, cnamelen) != 0)
493 return DNS_RESP_CNAME_ERROR;
494
Baptiste Assmann325137d2015-04-13 23:40:55 +0200495 cname = reader;
496 cnamelen = dns_str_to_dn_label_len((const char *)cname);
497
498 /* move forward cnamelen bytes + NULL byte */
499 reader += (cnamelen + 1);
500 }
Baptiste Assmann2359ff12015-08-07 11:24:05 +0200501 /* compare server hostname to current name */
502 else if (dn_name) {
503 /* check if the name can stand in response */
504 if ((reader + dn_name_len) > bufend)
505 return DNS_RESP_INVALID;
506 if (memcmp(ptr, dn_name, dn_name_len) != 0)
507 return DNS_RESP_WRONG_NAME;
508 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200509 else {
510 reader += (len + 1);
511 }
512 }
Baptiste Assmann2359ff12015-08-07 11:24:05 +0200513 else {
514 /* shortname in progress */
515 /* move forward 2 bytes for information pointer and address pointer */
516 reader += 2;
517 }
518
Baptiste Assmann325137d2015-04-13 23:40:55 +0200519 if (reader >= bufend)
520 return DNS_RESP_INVALID;
521
522 /*
523 * we know the record is either for our server hostname
524 * or a valid CNAME in a crecursion
525 */
526
527 /* now reading record type (A, AAAA, CNAME, etc...) */
528 if (reader + 2 > bufend)
529 return DNS_RESP_INVALID;
530 type = reader[0] * 256 + reader[1];
531
532 /* move forward 2 bytes for type (2) */
533 reader += 2;
534
535 /* move forward 6 bytes for class (2) and ttl (4) */
536 reader += 6;
537 if (reader >= bufend)
538 return DNS_RESP_INVALID;
539
540 /* now reading data len */
541 if (reader + 2 > bufend)
542 return DNS_RESP_INVALID;
543 len = reader[0] * 256 + reader[1];
544
545 /* move forward 2 bytes for data len */
546 reader += 2;
547
548 /* analyzing record content */
549 switch (type) {
550 case DNS_RTYPE_A:
551 /* ipv4 is stored on 4 bytes */
552 if (len != 4)
553 return DNS_RESP_INVALID;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200554 expected_record = 1;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200555 break;
556
557 case DNS_RTYPE_CNAME:
558 cname = reader;
559 cnamelen = len;
560 break;
561
562 case DNS_RTYPE_AAAA:
563 /* ipv6 is stored on 16 bytes */
564 if (len != 16)
565 return DNS_RESP_INVALID;
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200566 expected_record = 1;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200567 break;
568 } /* switch (record type) */
569
570 /* move forward len for analyzing next record in the response */
571 reader += len;
572 } /* for i 0 to ancount */
573
Baptiste Assmann96972bc2015-09-09 00:46:58 +0200574 if (expected_record == 0)
575 return DNS_RESP_NO_EXPECTED_RECORD;
576
Baptiste Assmann325137d2015-04-13 23:40:55 +0200577 return DNS_RESP_VALID;
578}
579
580/*
581 * search dn_name resolution in resp.
582 * If existing IP not found, return the first IP matching family_priority,
583 * otherwise, first ip found
584 * The following tasks are the responsibility of the caller:
585 * - resp contains an error free DNS response
586 * - the response matches the dn_name
587 * For both cases above, dns_validate_dns_response is required
588 * returns one of the DNS_UPD_* code
589 */
590int dns_get_ip_from_response(unsigned char *resp, unsigned char *resp_end,
591 char *dn_name, int dn_name_len, void *currentip, short currentip_sin_family,
592 int family_priority, void **newip, short *newip_sin_family)
593{
594 int i, ancount, cnamelen, type, data_len, currentip_found;
595 unsigned char *reader, *cname, *ptr, *newip4, *newip6;
596
597 cname = *newip = newip4 = newip6 = NULL;
598 cnamelen = currentip_found = 0;
599 *newip_sin_family = AF_UNSPEC;
600 ancount = (((struct dns_header *)resp)->ancount);
601 ancount = *(resp + 7);
602
603 /* bypass DNS response header */
604 reader = resp + sizeof(struct dns_header);
605
606 /* bypass DNS query section */
607 /* move forward hostname len bytes + 1 for NULL byte */
608 reader = reader + dn_name_len + 1;
609
610 /* move forward 4 bytes for question type and question class */
611 reader += 4;
612
613 /* now parsing response records */
614 for (i = 1; i <= ancount; i++) {
615 /*
616 * name can be a pointer, so move forward reader cursor accordingly
617 * if 1st byte is '11XXXXXX', it means name is a pointer
618 * and 2nd byte gives the offset from buf where the hostname can
619 * be found
620 */
621 if ((*reader & 0xc0) == 0xc0)
622 ptr = resp + *(reader + 1);
623 else
624 ptr = reader;
625
626 if (cname && memcmp(ptr, cname, cnamelen))
627 return DNS_UPD_NAME_ERROR;
628 else if (memcmp(ptr, dn_name, dn_name_len))
629 return DNS_UPD_NAME_ERROR;
630
631 if ((*reader & 0xc0) == 0xc0) {
632 /* move forward 2 bytes for information pointer and address pointer */
633 reader += 2;
634 }
635 else {
636 if (cname) {
637 cname = reader;
638 cnamelen = dns_str_to_dn_label_len((char *)cname);
639
640 /* move forward cnamelen bytes + NULL byte */
641 reader += (cnamelen + 1);
642 }
643 else {
644 /* move forward dn_name_len bytes + NULL byte */
645 reader += (dn_name_len + 1);
646 }
647 }
648
649 /*
650 * we know the record is either for our server hostname
651 * or a valid CNAME in a crecursion
652 */
653
654 /* now reading record type (A, AAAA, CNAME, etc...) */
655 type = reader[0] * 256 + reader[1];
656
657 /* move forward 2 bytes for type (2) */
658 reader += 2;
659
660 /* move forward 6 bytes for class (2) and ttl (4) */
661 reader += 6;
662
663 /* now reading data len */
664 data_len = reader[0] * 256 + reader[1];
665
666 /* move forward 2 bytes for data len */
667 reader += 2;
668
669 /* analyzing record content */
670 switch (type) {
671 case DNS_RTYPE_A:
672 /* check if current reccord's IP is the same as server one's */
673 if ((currentip_sin_family == AF_INET)
674 && (*(uint32_t *)reader == *(uint32_t *)currentip)) {
675 currentip_found = 1;
676 newip4 = reader;
677 /* we can stop now if server's family preference is IPv4
678 * and its current IP is found in the response list */
679 if (family_priority == AF_INET)
680 return DNS_UPD_NO; /* DNS_UPD matrix #1 */
681 }
682 else if (!newip4) {
683 newip4 = reader;
684 }
685
686 /* move forward data_len for analyzing next record in the response */
687 reader += data_len;
688 break;
689
690 case DNS_RTYPE_CNAME:
691 cname = reader;
692 cnamelen = data_len;
693
694 reader += data_len;
695 break;
696
697 case DNS_RTYPE_AAAA:
698 /* check if current record's IP is the same as server's one */
699 if ((currentip_sin_family == AF_INET6) && (memcmp(reader, currentip, 16) == 0)) {
700 currentip_found = 1;
701 newip6 = reader;
702 /* we can stop now if server's preference is IPv6 or is not
703 * set (which implies we prioritize IPv6 over IPv4 */
704 if (family_priority == AF_INET6)
705 return DNS_UPD_NO;
706 }
707 else if (!newip6) {
708 newip6 = reader;
709 }
710
711 /* move forward data_len for analyzing next record in the response */
712 reader += data_len;
713 break;
714
715 default:
716 /* not supported record type */
717 /* move forward data_len for analyzing next record in the response */
718 reader += data_len;
719 } /* switch (record type) */
720 } /* for i 0 to ancount */
721
722 /* only CNAMEs in the response, no IP found */
723 if (cname && !newip4 && !newip6) {
724 return DNS_UPD_CNAME;
725 }
726
Baptiste Assmann0453a1d2015-09-09 00:51:08 +0200727 /* no IP found in the response */
728 if (!newip4 && !newip6) {
729 return DNS_UPD_NO_IP_FOUND;
730 }
731
Baptiste Assmann325137d2015-04-13 23:40:55 +0200732 /* case when the caller looks first for an IPv4 address */
733 if (family_priority == AF_INET) {
734 if (newip4) {
735 *newip = newip4;
736 *newip_sin_family = AF_INET;
737 if (currentip_found == 1)
738 return DNS_UPD_NO;
739 return DNS_UPD_SRVIP_NOT_FOUND;
740 }
741 else if (newip6) {
742 *newip = newip6;
743 *newip_sin_family = AF_INET6;
744 if (currentip_found == 1)
745 return DNS_UPD_NO;
746 return DNS_UPD_SRVIP_NOT_FOUND;
747 }
748 }
749 /* case when the caller looks first for an IPv6 address */
750 else if (family_priority == AF_INET6) {
751 if (newip6) {
752 *newip = newip6;
753 *newip_sin_family = AF_INET6;
754 if (currentip_found == 1)
755 return DNS_UPD_NO;
756 return DNS_UPD_SRVIP_NOT_FOUND;
757 }
758 else if (newip4) {
759 *newip = newip4;
760 *newip_sin_family = AF_INET;
761 if (currentip_found == 1)
762 return DNS_UPD_NO;
763 return DNS_UPD_SRVIP_NOT_FOUND;
764 }
765 }
766 /* case when the caller have no preference (we prefer IPv6) */
767 else if (family_priority == AF_UNSPEC) {
768 if (newip6) {
769 *newip = newip6;
770 *newip_sin_family = AF_INET6;
771 if (currentip_found == 1)
772 return DNS_UPD_NO;
773 return DNS_UPD_SRVIP_NOT_FOUND;
774 }
775 else if (newip4) {
776 *newip = newip4;
777 *newip_sin_family = AF_INET;
778 if (currentip_found == 1)
779 return DNS_UPD_NO;
780 return DNS_UPD_SRVIP_NOT_FOUND;
781 }
782 }
783
784 /* no reason why we should change the server's IP address */
785 return DNS_UPD_NO;
786}
787
788/*
789 * returns the query id contained in a DNS response
790 */
791int dns_response_get_query_id(unsigned char *resp)
792{
793 /* read the query id from the response */
794 return resp[0] * 256 + resp[1];
795}
796
797/*
798 * used during haproxy's init phase
799 * parses resolvers sections and initializes:
800 * - task (time events) for each resolvers section
801 * - the datagram layer (network IO events) for each nameserver
802 * returns:
803 * 0 in case of error
804 * 1 when no error
805 */
806int dns_init_resolvers(void)
807{
808 struct dns_resolvers *curr_resolvers;
809 struct dns_nameserver *curnameserver;
810 struct dgram_conn *dgram;
811 struct task *t;
812 int fd;
813
814 /* give a first random value to our dns query_id seed */
815 dns_query_id_seed = random();
816
817 /* run through the resolvers section list */
818 list_for_each_entry(curr_resolvers, &dns_resolvers, list) {
819 /* create the task associated to the resolvers section */
820 if ((t = task_new()) == NULL) {
821 Alert("Starting [%s] resolvers: out of memory.\n", curr_resolvers->id);
822 return 0;
823 }
824
825 /* update task's parameters */
826 t->process = dns_process_resolve;
827 t->context = curr_resolvers;
828 t->expire = TICK_ETERNITY;
829
830 curr_resolvers->t = t;
831
832 list_for_each_entry(curnameserver, &curr_resolvers->nameserver_list, list) {
833 if ((dgram = calloc(1, sizeof(struct dgram_conn))) == NULL) {
834 Alert("Starting [%s/%s] nameserver: out of memory.\n", curr_resolvers->id,
835 curnameserver->id);
836 return 0;
837 }
838 /* update datagram's parameters */
839 dgram->owner = (void *)curnameserver;
840 dgram->data = &resolve_dgram_cb;
841
842 /* create network UDP socket for this nameserver */
843 if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
844 Alert("Starting [%s/%s] nameserver: can't create socket.\n", curr_resolvers->id,
845 curnameserver->id);
846 free(dgram);
847 dgram = NULL;
848 return 0;
849 }
850
851 /* "connect" the UDP socket to the name server IP */
852 if (connect(fd, (struct sockaddr*)&curnameserver->addr, sizeof(curnameserver->addr)) == -1) {
853 Alert("Starting [%s/%s] nameserver: can't connect socket.\n", curr_resolvers->id,
854 curnameserver->id);
855 close(fd);
856 free(dgram);
857 dgram = NULL;
858 return 0;
859 }
860
861 /* make the socket non blocking */
862 fcntl(fd, F_SETFL, O_NONBLOCK);
863
864 /* add the fd in the fd list and update its parameters */
865 fd_insert(fd);
866 fdtab[fd].owner = dgram;
867 fdtab[fd].iocb = dgram_fd_handler;
868 fd_want_recv(fd);
869 dgram->t.sock.fd = fd;
870
871 /* update nameserver's datagram property */
872 curnameserver->dgram = dgram;
873
874 continue;
875 }
876
877 /* task can be queued */
878 task_queue(t);
879 }
880
881 return 1;
882}
883
884/*
885 * Forge a DNS query. It needs the following information from the caller:
886 * - <query_id>: the DNS query id corresponding to this query
887 * - <query_type>: DNS_RTYPE_* request DNS record type (A, AAAA, ANY, etc...)
888 * - <hostname_dn>: hostname in domain name format
889 * - <hostname_dn_len>: length of <hostname_dn>
890 * To store the query, the caller must pass a buffer <buf> and its size <bufsize>
891 *
892 * the DNS query is stored in <buf>
893 * returns:
894 * -1 if <buf> is too short
895 */
896int dns_build_query(int query_id, int query_type, char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
897{
898 struct dns_header *dns;
899 struct dns_question *qinfo;
900 char *ptr, *bufend;
901
902 memset(buf, '\0', bufsize);
903 ptr = buf;
904 bufend = buf + bufsize;
905
906 /* check if there is enough room for DNS headers */
907 if (ptr + sizeof(struct dns_header) >= bufend)
908 return -1;
909
910 /* set dns query headers */
911 dns = (struct dns_header *)ptr;
912 dns->id = (unsigned short) htons(query_id);
913 dns->qr = 0; /* query */
914 dns->opcode = 0;
915 dns->aa = 0;
916 dns->tc = 0;
917 dns->rd = 1; /* recursion desired */
918 dns->ra = 0;
919 dns->z = 0;
920 dns->rcode = 0;
921 dns->qdcount = htons(1); /* 1 question */
922 dns->ancount = 0;
923 dns->nscount = 0;
924 dns->arcount = 0;
925
926 /* move forward ptr */
927 ptr += sizeof(struct dns_header);
928
929 /* check if there is enough room for query hostname */
930 if ((ptr + hostname_dn_len) >= bufend)
931 return -1;
932
933 /* set up query hostname */
934 memcpy(ptr, hostname_dn, hostname_dn_len);
935 ptr[hostname_dn_len + 1] = '\0';
936
937 /* move forward ptr */
938 ptr += (hostname_dn_len + 1);
939
940 /* check if there is enough room for query hostname*/
941 if (ptr + sizeof(struct dns_question) >= bufend)
942 return -1;
943
944 /* set up query info (type and class) */
945 qinfo = (struct dns_question *)ptr;
946 qinfo->qtype = htons(query_type);
947 qinfo->qclass = htons(DNS_RCLASS_IN);
948
949 ptr += sizeof(struct dns_question);
950
951 return ptr - buf;
952}
953
954/*
955 * turn a string into domain name label:
956 * www.haproxy.org into 3www7haproxy3org
957 * if dn memory is pre-allocated, you must provide its size in dn_len
958 * if dn memory isn't allocated, dn_len must be set to 0.
959 * In the second case, memory will be allocated.
960 * in case of error, -1 is returned, otherwise, number of bytes copied in dn
961 */
Willy Tarreau2100b492015-07-22 16:42:43 +0200962char *dns_str_to_dn_label(const char *string, char *dn, int dn_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200963{
964 char *c, *d;
965 int i, offset;
966
967 /* offset between string size and theorical dn size */
968 offset = 1;
969
970 /*
971 * first, get the size of the string turned into its domain name version
972 * This function also validates the string respect the RFC
973 */
974 if ((i = dns_str_to_dn_label_len(string)) == -1)
975 return NULL;
976
977 /* yes, so let's check there is enough memory */
978 if (dn_len < i + offset)
979 return NULL;
980
Willy Tarreaud69d6f32015-07-22 16:45:36 +0200981 i = strlen(string);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200982 memcpy(dn + offset, string, i);
983 dn[i + offset] = '\0';
984 /* avoid a '\0' at the beginning of dn string which may prevent the for loop
985 * below from working.
986 * Actually, this is the reason of the offset. */
987 dn[0] = '0';
988
989 for (c = dn; *c ; ++c) {
990 /* c points to the first '0' char or a dot, which we don't want to read */
991 d = c + offset;
992 i = 0;
993 while (*d != '.' && *d) {
994 i++;
995 d++;
996 }
997 *c = i;
998
999 c = d - 1; /* because of c++ of the for loop */
1000 }
1001
1002 return dn;
1003}
1004
1005/*
1006 * compute and return the length of <string> it it were translated into domain name
1007 * label:
1008 * www.haproxy.org into 3www7haproxy3org would return 16
1009 * NOTE: add +1 for '\0' when allocating memory ;)
1010 */
1011int dns_str_to_dn_label_len(const char *string)
1012{
1013 return strlen(string) + 1;
1014}
1015
1016/*
1017 * validates host name:
1018 * - total size
1019 * - each label size individually
1020 * returns:
1021 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1022 * 1 when no error. <err> is left unaffected.
1023 */
1024int dns_hostname_validation(const char *string, char **err)
1025{
1026 const char *c, *d;
1027 int i;
1028
1029 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1030 if (err)
1031 *err = DNS_TOO_LONG_FQDN;
1032 return 0;
1033 }
1034
1035 c = string;
1036 while (*c) {
1037 d = c;
1038
1039 i = 0;
1040 while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) {
1041 i++;
1042 if (!((*d == '-') || (*d == '_') ||
1043 ((*d >= 'a') && (*d <= 'z')) ||
1044 ((*d >= 'A') && (*d <= 'Z')) ||
1045 ((*d >= '0') && (*d <= '9')))) {
1046 if (err)
1047 *err = DNS_INVALID_CHARACTER;
1048 return 0;
1049 }
1050 d++;
1051 }
1052
1053 if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) {
1054 if (err)
1055 *err = DNS_LABEL_TOO_LONG;
1056 return 0;
1057 }
1058
1059 if (*d == '\0')
1060 goto out;
1061
1062 c = ++d;
1063 }
1064 out:
1065 return 1;
1066}
1067
1068/*
1069 * 2 bytes random generator to generate DNS query ID
1070 */
1071uint16_t dns_rnd16(void)
1072{
1073 dns_query_id_seed ^= dns_query_id_seed << 13;
1074 dns_query_id_seed ^= dns_query_id_seed >> 7;
1075 dns_query_id_seed ^= dns_query_id_seed << 17;
1076 return dns_query_id_seed;
1077}
1078
1079
1080/*
1081 * function called when a timeout occurs during name resolution process
1082 * if max number of tries is reached, then stop, otherwise, retry.
1083 */
1084struct task *dns_process_resolve(struct task *t)
1085{
1086 struct dns_resolvers *resolvers = t->context;
1087 struct dns_resolution *resolution, *res_back;
1088
1089 /* timeout occurs inevitably for the first element of the FIFO queue */
1090 if (LIST_ISEMPTY(&resolvers->curr_resolution)) {
1091 /* no first entry, so wake up was useless */
1092 t->expire = TICK_ETERNITY;
1093 return t;
1094 }
1095
1096 /* look for the first resolution which is not expired */
1097 list_for_each_entry_safe(resolution, res_back, &resolvers->curr_resolution, list) {
1098 /* when we find the first resolution in the future, then we can stop here */
1099 if (tick_is_le(now_ms, resolution->last_sent_packet))
1100 goto out;
1101
1102 /*
1103 * if current resolution has been tried too many times and finishes in timeout
1104 * we update its status and remove it from the list
1105 */
1106 if (resolution->try >= resolvers->resolve_retries) {
1107 /* clean up resolution information and remove from the list */
1108 dns_reset_resolution(resolution);
1109
1110 /* notify the result to the requester */
1111 resolution->requester_error_cb(resolution, DNS_RESP_TIMEOUT);
1112 }
1113
1114 /* check current resolution status */
1115 if (resolution->step == RSLV_STEP_RUNNING) {
1116 /* resend the DNS query */
1117 dns_send_query(resolution);
1118
1119 /* check if we have more than one resolution in the list */
1120 if (dns_check_resolution_queue(resolvers) > 1) {
1121 /* move the rsolution to the end of the list */
1122 LIST_DEL(&resolution->list);
1123 LIST_ADDQ(&resolvers->curr_resolution, &resolution->list);
1124 }
1125 }
1126 }
1127
1128 out:
1129 dns_update_resolvers_timeout(resolvers);
1130 return t;
1131}