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