blob: d9ca2b0c9a5c83e53fe6f4ae6216976e30e0fa13 [file] [log] [blame]
Emeric Brunc9437992021-02-12 19:42:55 +01001/*
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
Emeric Brun0c4a8a32021-06-11 10:48:45 +020022#include <import/ebistree.h>
23
Emeric Brunc9437992021-02-12 19:42:55 +010024#include <haproxy/action.h>
25#include <haproxy/api.h>
26#include <haproxy/cfgparse.h>
27#include <haproxy/channel.h>
28#include <haproxy/check.h>
29#include <haproxy/cli.h>
30#include <haproxy/dns.h>
31#include <haproxy/errors.h>
32#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010033#include <haproxy/http_rules.h>
34#include <haproxy/log.h>
35#include <haproxy/net_helper.h>
36#include <haproxy/protocol.h>
37#include <haproxy/proxy.h>
38#include <haproxy/resolvers.h>
39#include <haproxy/ring.h>
40#include <haproxy/sample.h>
41#include <haproxy/server.h>
42#include <haproxy/stats.h>
43#include <haproxy/stream_interface.h>
44#include <haproxy/task.h>
45#include <haproxy/tcp_rules.h>
46#include <haproxy/ticks.h>
47#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020048#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010049#include <haproxy/vars.h>
50
51
52struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
53struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
54
Willy Tarreau20751652021-10-18 16:46:38 +020055static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
Emeric Brunc9437992021-02-12 19:42:55 +010056static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
57struct resolvers *curr_resolvers = NULL;
58
59DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
60DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
61DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
62
63static unsigned int resolution_uuid = 1;
64unsigned int resolv_failed_resolutions = 0;
Willy Tarreau20751652021-10-18 16:46:38 +020065static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
66static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau33360872021-10-20 14:07:31 +020067static void _resolv_unlink_resolution(struct resolv_requester *requester);
Emeric Brunc9437992021-02-12 19:42:55 +010068
69enum {
70 DNS_STAT_ID,
71 DNS_STAT_PID,
72 DNS_STAT_SENT,
73 DNS_STAT_SND_ERROR,
74 DNS_STAT_VALID,
75 DNS_STAT_UPDATE,
76 DNS_STAT_CNAME,
77 DNS_STAT_CNAME_ERROR,
78 DNS_STAT_ANY_ERR,
79 DNS_STAT_NX,
80 DNS_STAT_TIMEOUT,
81 DNS_STAT_REFUSED,
82 DNS_STAT_OTHER,
83 DNS_STAT_INVALID,
84 DNS_STAT_TOO_BIG,
85 DNS_STAT_TRUNCATED,
86 DNS_STAT_OUTDATED,
87 DNS_STAT_END,
88};
89
90static struct name_desc dns_stats[] = {
91 [DNS_STAT_ID] = { .name = "id", .desc = "ID" },
92 [DNS_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
93 [DNS_STAT_SENT] = { .name = "sent", .desc = "Sent" },
94 [DNS_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
95 [DNS_STAT_VALID] = { .name = "valid", .desc = "Valid" },
96 [DNS_STAT_UPDATE] = { .name = "update", .desc = "Update" },
97 [DNS_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
98 [DNS_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
99 [DNS_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
100 [DNS_STAT_NX] = { .name = "nx", .desc = "NX" },
101 [DNS_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
102 [DNS_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
103 [DNS_STAT_OTHER] = { .name = "other", .desc = "Other" },
104 [DNS_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
105 [DNS_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
106 [DNS_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
107 [DNS_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
108};
109
110static struct dns_counters dns_counters;
111
112static void dns_fill_stats(void *d, struct field *stats)
113{
114 struct dns_counters *counters = d;
115 stats[DNS_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
116 stats[DNS_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
117 stats[DNS_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
118 stats[DNS_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
119 stats[DNS_STAT_VALID] = mkf_u64(FN_GAUGE, counters->valid);
120 stats[DNS_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->update);
121 stats[DNS_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->cname);
122 stats[DNS_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->cname_error);
123 stats[DNS_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->any_err);
124 stats[DNS_STAT_NX] = mkf_u64(FN_GAUGE, counters->nx);
125 stats[DNS_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->timeout);
126 stats[DNS_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->refused);
127 stats[DNS_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->other);
128 stats[DNS_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->invalid);
129 stats[DNS_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->too_big);
130 stats[DNS_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->truncated);
131 stats[DNS_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->outdated);
132}
133
134static struct stats_module dns_stats_module = {
135 .name = "dns",
136 .domain_flags = STATS_DOMAIN_DNS << STATS_DOMAIN,
137 .fill_stats = dns_fill_stats,
138 .stats = dns_stats,
139 .stats_count = DNS_STAT_END,
140 .counters = &dns_counters,
141 .counters_size = sizeof(dns_counters),
142 .clearable = 0,
143};
144
145INITCALL1(STG_REGISTER, stats_register_module, &dns_stats_module);
146
147/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
148 * no match is found.
149 */
150struct resolvers *find_resolvers_by_id(const char *id)
151{
152 struct resolvers *res;
153
154 list_for_each_entry(res, &sec_resolvers, list) {
155 if (strcmp(res->id, id) == 0)
156 return res;
157 }
158 return NULL;
159}
160
161/* Compare hostnames in a case-insensitive way .
162 * Returns 0 if they are the same, non-zero otherwise
163 */
164static __inline int resolv_hostname_cmp(const char *name1, const char *name2, int len)
165{
166 int i;
167
168 for (i = 0; i < len; i++)
169 if (tolower((unsigned char)name1[i]) != tolower((unsigned char)name2[i]))
170 return -1;
171 return 0;
172}
173
174/* Returns a pointer on the SRV request matching the name <name> for the proxy
175 * <px>. NULL is returned if no match is found.
176 */
177struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
178{
179 struct resolv_srvrq *srvrq;
180
181 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
182 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
183 return srvrq;
184 }
185 return NULL;
186}
187
188/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
189 * NULL if an error occurred. */
190struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
191{
192 struct proxy *px = srv->proxy;
193 struct resolv_srvrq *srvrq = NULL;
194 int fqdn_len, hostname_dn_len;
195
196 fqdn_len = strlen(fqdn);
Willy Tarreauc1c765f2021-10-14 07:49:49 +0200197 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100198 trash.size);
199 if (hostname_dn_len == -1) {
200 ha_alert("config : %s '%s', server '%s': failed to parse FQDN '%s'\n",
201 proxy_type_str(px), px->id, srv->id, fqdn);
202 goto err;
203 }
204
205 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
206 ha_alert("config : %s '%s', server '%s': out of memory\n",
207 proxy_type_str(px), px->id, srv->id);
208 goto err;
209 }
210 srvrq->obj_type = OBJ_TYPE_SRVRQ;
211 srvrq->proxy = px;
212 srvrq->name = strdup(fqdn);
213 srvrq->hostname_dn = strdup(trash.area);
214 srvrq->hostname_dn_len = hostname_dn_len;
215 if (!srvrq->name || !srvrq->hostname_dn) {
216 ha_alert("config : %s '%s', server '%s': out of memory\n",
217 proxy_type_str(px), px->id, srv->id);
218 goto err;
219 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200220 LIST_INIT(&srvrq->attached_servers);
221 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200222 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100223 return srvrq;
224
225 err:
226 if (srvrq) {
227 free(srvrq->name);
228 free(srvrq->hostname_dn);
229 free(srvrq);
230 }
231 return NULL;
232}
233
234
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100235/* finds and return the SRV answer item associated to a requester (whose type is 'server').
236 *
237 * returns NULL in case of error or not found.
238 */
239struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
240{
241 struct resolv_resolution *res;
242 struct resolv_answer_item *item;
243 struct server *srv;
244
245 if (!requester)
246 return NULL;
247
248 if ((srv = objt_server(requester->owner)) == NULL)
249 return NULL;
250 /* check if the server is managed by a SRV record */
251 if (srv->srvrq == NULL)
252 return NULL;
253
254 res = srv->srvrq->requester->resolution;
255 /* search an ANSWER record whose target points to the server's hostname and whose port is
256 * the same as server's svc_port */
257 list_for_each_entry(item, &res->response.answer_list, list) {
Willy Tarreau20a02372021-10-14 22:52:04 +0200258 if (resolv_hostname_cmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100259 (srv->svc_port == item->port))
260 return item;
261 }
262
263 return NULL;
264}
265
Emeric Brunc9437992021-02-12 19:42:55 +0100266/* 2 bytes random generator to generate DNS query ID */
267static inline uint16_t resolv_rnd16(void)
268{
269 if (!resolv_query_id_seed)
270 resolv_query_id_seed = now_ms;
271 resolv_query_id_seed ^= resolv_query_id_seed << 13;
272 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
273 resolv_query_id_seed ^= resolv_query_id_seed << 17;
274 return resolv_query_id_seed;
275}
276
277
278static inline int resolv_resolution_timeout(struct resolv_resolution *res)
279{
280 return res->resolvers->timeout.resolve;
281}
282
283/* Updates a resolvers' task timeout for next wake up and queue it */
284static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
285{
286 struct resolv_resolution *res;
287 int next;
288
289 next = tick_add(now_ms, resolvers->timeout.resolve);
290 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
291 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
292 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
293 }
294
295 list_for_each_entry(res, &resolvers->resolutions.wait, list)
296 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
297
298 resolvers->t->expire = next;
299 task_queue(resolvers->t);
300}
301
302/* Forges a DNS query. It needs the following information from the caller:
303 * - <query_id> : the DNS query id corresponding to this query
304 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
305 * - <hostname_dn> : hostname in domain name format
306 * - <hostname_dn_len> : length of <hostname_dn>
307 *
308 * To store the query, the caller must pass a buffer <buf> and its size
309 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
310 * too short.
311 */
312static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
313 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
314{
315 struct dns_header dns_hdr;
316 struct dns_question qinfo;
317 struct dns_additional_record edns;
318 char *p = buf;
319
320 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
321 return -1;
322
323 memset(buf, 0, bufsize);
324
325 /* Set dns query headers */
326 dns_hdr.id = (unsigned short) htons(query_id);
327 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
328 dns_hdr.qdcount = htons(1); /* 1 question */
329 dns_hdr.ancount = 0;
330 dns_hdr.nscount = 0;
331 dns_hdr.arcount = htons(1);
332 memcpy(p, &dns_hdr, sizeof(dns_hdr));
333 p += sizeof(dns_hdr);
334
335 /* Set up query hostname */
336 memcpy(p, hostname_dn, hostname_dn_len);
337 p += hostname_dn_len;
338 *p++ = 0;
339
340 /* Set up query info (type and class) */
341 qinfo.qtype = htons(query_type);
342 qinfo.qclass = htons(DNS_RCLASS_IN);
343 memcpy(p, &qinfo, sizeof(qinfo));
344 p += sizeof(qinfo);
345
346 /* Set the DNS extension */
347 edns.name = 0;
348 edns.type = htons(DNS_RTYPE_OPT);
349 edns.udp_payload_size = htons(accepted_payload_size);
350 edns.extension = 0;
351 edns.data_length = 0;
352 memcpy(p, &edns, sizeof(edns));
353 p += sizeof(edns);
354
355 return (p - buf);
356}
357
358/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
359 * success, -1 otherwise.
360 */
361static int resolv_send_query(struct resolv_resolution *resolution)
362{
363 struct resolvers *resolvers = resolution->resolvers;
364 struct dns_nameserver *ns;
365 int len;
366
367 /* Update resolution */
368 resolution->nb_queries = 0;
369 resolution->nb_responses = 0;
370 resolution->last_query = now_ms;
371
372 len = resolv_build_query(resolution->query_id, resolution->query_type,
373 resolvers->accepted_payload_size,
374 resolution->hostname_dn, resolution->hostname_dn_len,
375 trash.area, trash.size);
376
377 list_for_each_entry(ns, &resolvers->nameservers, list) {
378 if (len < 0) {
379 ns->counters->snd_error++;
380 continue;
381 }
382
383 if (dns_send_nameserver(ns, trash.area, len) < 0)
384 ns->counters->snd_error++;
385 else
386 resolution->nb_queries++;
387 }
388
389 /* Push the resolution at the end of the active list */
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200390 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200391 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100392 return 0;
393}
394
395/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
396 * skipped and -1 if an error occurred.
397 */
398static int
399resolv_run_resolution(struct resolv_resolution *resolution)
400{
401 struct resolvers *resolvers = resolution->resolvers;
402 int query_id, i;
403
404 /* Avoid sending requests for resolutions that don't yet have an
405 * hostname, ie resolutions linked to servers that do not yet have an
406 * fqdn */
407 if (!resolution->hostname_dn)
408 return 0;
409
410 /* Check if a resolution has already been started for this server return
411 * directly to avoid resolution pill up. */
412 if (resolution->step != RSLV_STEP_NONE)
413 return 0;
414
415 /* Generates a new query id. We try at most 100 times to find a free
416 * query id */
417 for (i = 0; i < 100; ++i) {
418 query_id = resolv_rnd16();
419 if (!eb32_lookup(&resolvers->query_ids, query_id))
420 break;
421 query_id = -1;
422 }
423 if (query_id == -1) {
424 send_log(NULL, LOG_NOTICE,
425 "could not generate a query id for %s, in resolvers %s.\n",
426 resolution->hostname_dn, resolvers->id);
427 return -1;
428 }
429
430 /* Update resolution parameters */
431 resolution->query_id = query_id;
432 resolution->qid.key = query_id;
433 resolution->step = RSLV_STEP_RUNNING;
434 resolution->query_type = resolution->prefered_query_type;
435 resolution->try = resolvers->resolve_retries;
436 eb32_insert(&resolvers->query_ids, &resolution->qid);
437
438 /* Send the DNS query */
439 resolution->try -= 1;
440 resolv_send_query(resolution);
441 return 1;
442}
443
444/* Performs a name resolution for the requester <req> */
445void resolv_trigger_resolution(struct resolv_requester *req)
446{
447 struct resolvers *resolvers;
448 struct resolv_resolution *res;
449 int exp;
450
451 if (!req || !req->resolution)
452 return;
453 res = req->resolution;
454 resolvers = res->resolvers;
455
456 /* The resolution must not be triggered yet. Use the cached response, if
457 * valid */
458 exp = tick_add(res->last_resolution, resolvers->hold.valid);
459 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
460 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
461 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
462}
463
464
465/* Resets some resolution parameters to initial values and also delete the query
466 * ID from the resolver's tree.
467 */
468static void resolv_reset_resolution(struct resolv_resolution *resolution)
469{
470 /* update resolution status */
471 resolution->step = RSLV_STEP_NONE;
472 resolution->try = 0;
473 resolution->last_resolution = now_ms;
474 resolution->nb_queries = 0;
475 resolution->nb_responses = 0;
476 resolution->query_type = resolution->prefered_query_type;
477
478 /* clean up query id */
479 eb32_delete(&resolution->qid);
480 resolution->query_id = 0;
481 resolution->qid.key = 0;
482}
483
484/* Returns the query id contained in a DNS response */
485static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
486{
487 return resp[0] * 256 + resp[1];
488}
489
490
491/* Analyses, re-builds and copies the name <name> from the DNS response packet
492 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
493 * for compressed data. The result is copied into <dest>, ensuring we don't
494 * overflow using <dest_len> Returns the number of bytes the caller can move
495 * forward. If 0 it means an error occurred while parsing the name. <offset> is
496 * the number of bytes the caller could move forward.
497 */
498int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
499 unsigned char *name, char *destination, int dest_len,
500 int *offset, unsigned int depth)
501{
502 int nb_bytes = 0, n = 0;
503 int label_len;
504 unsigned char *reader = name;
505 char *dest = destination;
506
507 while (1) {
508 if (reader >= bufend)
509 goto err;
510
511 /* Name compression is in use */
512 if ((*reader & 0xc0) == 0xc0) {
513 if (reader + 1 >= bufend)
514 goto err;
515
516 /* Must point BEFORE current position */
517 if ((buffer + reader[1]) > reader)
518 goto err;
519
520 if (depth++ > 100)
521 goto err;
522
523 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
524 dest, dest_len - nb_bytes, offset, depth);
525 if (n == 0)
526 goto err;
527
528 dest += n;
529 nb_bytes += n;
530 goto out;
531 }
532
533 label_len = *reader;
534 if (label_len == 0)
535 goto out;
536
537 /* Check if:
538 * - we won't read outside the buffer
539 * - there is enough place in the destination
540 */
541 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
542 goto err;
543
544 /* +1 to take label len + label string */
545 label_len++;
546
547 memcpy(dest, reader, label_len);
548
549 dest += label_len;
550 nb_bytes += label_len;
551 reader += label_len;
552 }
553
554 out:
555 /* offset computation:
556 * parse from <name> until finding either NULL or a pointer "c0xx"
557 */
558 reader = name;
559 *offset = 0;
560 while (reader < bufend) {
561 if ((reader[0] & 0xc0) == 0xc0) {
562 *offset += 2;
563 break;
564 }
565 else if (*reader == 0) {
566 *offset += 1;
567 break;
568 }
569 *offset += 1;
570 ++reader;
571 }
572 return nb_bytes;
573
574 err:
575 return 0;
576}
577
Willy Tarreau20751652021-10-18 16:46:38 +0200578/* Reinitialize the list of aborted resolutions before calling certain
579 * functions relying on it. The list must be processed by calling
580 * free_aborted_resolutions() after operations.
581 */
582static void init_aborted_resolutions()
583{
584 LIST_INIT(&death_row);
585}
586
587static void abort_resolution(struct resolv_resolution *res)
588{
589 LIST_DEL_INIT(&res->list);
590 LIST_APPEND(&death_row, &res->list);
591}
592
593/* This releases any aborted resolution found in the death row. It is mandatory
594 * to call init_aborted_resolutions() first before the function (or loop) that
595 * needs to defer deletions. Note that some of them are in relation via internal
596 * objects and might cause the deletion of other ones from the same list, so we
597 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
598 * and solely rely on each call to remove the first remaining list element.
599 */
600static void free_aborted_resolutions()
601{
602 struct resolv_resolution *res;
603
604 while (!LIST_ISEMPTY(&death_row)) {
605 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
606 resolv_free_resolution(res);
607 }
608
609 /* make sure nobody tries to add anything without having initialized it */
610 death_row = (struct list){ };
611}
612
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200613/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
614 * happens when an SRV item is purged or when the server status is considered as
615 * obsolete.
616 *
Willy Tarreau20751652021-10-18 16:46:38 +0200617 * Must be called with the DNS lock held, and with the death_row already
618 * initialized via init_aborted_resolutions().
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200619 */
Willy Tarreau20751652021-10-18 16:46:38 +0200620static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200621{
Willy Tarreau33360872021-10-20 14:07:31 +0200622 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200623 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
624 srvrq_update_srv_status(srv, 1);
625 ha_free(&srv->hostname);
626 ha_free(&srv->hostname_dn);
627 srv->hostname_dn_len = 0;
628 memset(&srv->addr, 0, sizeof(srv->addr));
629 srv->svc_port = 0;
630 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Fauleta62d9742021-06-15 16:14:37 +0200631
632 ebpt_delete(&srv->host_dn);
633 ha_free(&srv->host_dn.key);
634
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200635 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200636 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200637 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200638
639 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200640}
641
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200642/* Takes care to cleanup a server resolution when it is outdated. This only
643 * happens for a server relying on a SRV record.
644 */
645static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
646{
647 struct server *srv = context;
648
649 if (!tick_is_expired(t->expire, now_ms))
650 goto end;
651
Christopher Faulet152b50c2021-06-18 09:05:49 +0200652 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreau20751652021-10-18 16:46:38 +0200653 init_aborted_resolutions();
654 resolv_srvrq_cleanup_srv(srv);
655 free_aborted_resolutions();
Christopher Faulet152b50c2021-06-18 09:05:49 +0200656 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200657
658 end:
659 return t;
660}
661
Emeric Brunc9437992021-02-12 19:42:55 +0100662/* Checks for any obsolete record, also identify any SRV request, and try to
Willy Tarreau20751652021-10-18 16:46:38 +0200663 * find a corresponding server. Must be called with the death_row already
664 * initialized via init_aborted_resolutions().
665 */
Emeric Brunc9437992021-02-12 19:42:55 +0100666static void resolv_check_response(struct resolv_resolution *res)
667{
668 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100669 struct resolv_requester *req;
Emeric Brunc9437992021-02-12 19:42:55 +0100670 struct resolv_answer_item *item, *itemback;
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200671 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100672 struct resolv_srvrq *srvrq;
673
674 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
675 struct resolv_answer_item *ar_item = item->ar_item;
676
677 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100678 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100679 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
680 * item is also obsolete.
681 */
Emeric Brunc9437992021-02-12 19:42:55 +0100682 pool_free(resolv_answer_item_pool, ar_item);
683 item->ar_item = NULL;
684 }
685
686 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100687 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200688 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100689 /* Remove any associated server */
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200690 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
691 LIST_DEL_INIT(&srv->ip_rec_item);
692 }
693 }
694 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200695 /* Remove any associated server */
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200696 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreau20751652021-10-18 16:46:38 +0200697 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100698 }
699
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200700 LIST_DEL_INIT(&item->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100701 if (item->ar_item) {
702 pool_free(resolv_answer_item_pool, item->ar_item);
703 item->ar_item = NULL;
704 }
705 pool_free(resolv_answer_item_pool, item);
706 continue;
707 }
708
709 if (item->type != DNS_RTYPE_SRV)
710 continue;
711
712 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100713 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200714 struct ebpt_node *node;
715 char target[DNS_MAX_NAME_SIZE+1];
716
717 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100718 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
719 continue;
720
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200721 /* Check if a server already uses that record */
722 srv = NULL;
723 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
724 if (srv->srvrq == srvrq) {
725 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
726 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100727 }
Emeric Brunc9437992021-02-12 19:42:55 +0100728 }
729
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200730
731 /* If not empty we try to match a server
732 * in server state file tree with the same hostname
733 */
734 if (!eb_is_empty(&srvrq->named_servers)) {
735 srv = NULL;
736
737 /* convert the key to lookup in lower case */
Willy Tarreau20a02372021-10-14 22:52:04 +0200738 for (i = 0 ; item->data.target[i] ; i++)
739 target[i] = tolower(item->data.target[i]);
Christopher Fauletc20d6422021-07-22 14:29:26 +0200740 target[i] = 0;
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200741
742 node = ebis_lookup(&srvrq->named_servers, target);
743 if (node) {
744 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100745 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200746
747 /* an entry was found with the same hostname
748 * let check this node if the port matches
749 * and try next node if the hostname
750 * is still the same
751 */
752 while (1) {
753 if (srv->svc_port == item->port) {
754 /* server found, we remove it from tree */
755 ebpt_delete(node);
Christopher Fauleta62d9742021-06-15 16:14:37 +0200756 ha_free(&srv->host_dn.key);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200757 goto srv_found;
758 }
759
760 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
761
762 node = ebpt_next(node);
763 if (!node)
764 break;
765
766 srv = ebpt_entry(node, struct server, host_dn);
767 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
768
769 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau20a02372021-10-14 22:52:04 +0200770 || resolv_hostname_cmp(srv->hostname_dn, item->data.target, item->data_len)) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200771 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
772 break;
773 }
774 }
Emeric Brunc9437992021-02-12 19:42:55 +0100775 }
776 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200777
778 /* Pick the first server listed in srvrq (those ones don't
779 * have hostname and are free to use)
780 */
781 srv = NULL;
782 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
783 LIST_DEL_INIT(&srv->srv_rec_item);
784 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
785 goto srv_found;
786 }
787 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100788
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200789srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100790 /* And update this server, if found (srv is locked here) */
791 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100792 /* re-enable DNS resolution for this server by default */
793 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200794 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100795
Emeric Brunc9437992021-02-12 19:42:55 +0100796 /* Check if an Additional Record is associated to this SRV record.
797 * Perform some sanity checks too to ensure the record can be used.
798 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100799 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100800 */
801 if ((item->ar_item != NULL) &&
802 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100803 {
Emeric Brunc9437992021-02-12 19:42:55 +0100804
805 switch (item->ar_item->type) {
806 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +0200807 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100808 break;
809 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +0200810 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100811 break;
812 }
813
814 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100815
816 /* Unlink A/AAAA resolution for this server if there is an AR item.
817 * It is usless to perform an extra resolution
818 */
Willy Tarreau33360872021-10-20 14:07:31 +0200819 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100820 }
821
822 if (!srv->hostname_dn) {
823 const char *msg = NULL;
Willy Tarreau2859c162021-10-14 08:00:38 +0200824 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100825
Willy Tarreau20a02372021-10-14 22:52:04 +0200826 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau2859c162021-10-14 08:00:38 +0200827 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100828 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
829 continue;
830 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100831 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100832 if (msg)
833 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
834 }
835
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200836 if (!LIST_INLIST(&srv->srv_rec_item))
837 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
838
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100839 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
840 /* If there is no AR item responsible of the FQDN resolution,
841 * trigger a dedicated DNS resolution
842 */
843 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
844 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
845 }
846
Christopher Fauletab177ac2021-03-10 15:34:52 +0100847 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100848 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100849
850 srv->svc_port = item->port;
851 srv->flags &= ~SRV_F_MAPPORTS;
852
853 if (!srv->resolv_opts.ignore_weight) {
854 char weight[9];
855 int ha_weight;
856
857 /* DNS weight range if from 0 to 65535
858 * HAProxy weight is from 0 to 256
859 * The rule below ensures that weight 0 is well respected
860 * while allowing a "mapping" from DNS weight into HAProxy's one.
861 */
862 ha_weight = (item->weight + 255) / 256;
863
864 snprintf(weight, sizeof(weight), "%d", ha_weight);
865 server_parse_weight_change_request(srv, weight);
866 }
867 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
868 }
869 }
870 }
871}
872
873/* Validates that the buffer DNS response provided in <resp> and finishing
874 * before <bufend> is valid from a DNS protocol point of view.
875 *
876 * The result is stored in <resolution>' response, buf_response,
877 * response_query_records and response_answer_records members.
878 *
879 * This function returns one of the RSLV_RESP_* code to indicate the type of
880 * error found.
881 */
882static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
883 struct resolv_resolution *resolution, int max_answer_records)
884{
885 unsigned char *reader;
886 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
887 int len, flags, offset;
888 int query_record_id;
889 int nb_saved_records;
890 struct resolv_query_item *query;
891 struct resolv_answer_item *answer_record, *tmp_record;
892 struct resolv_response *r_res;
893 int i, found = 0;
894 int cause = RSLV_RESP_ERROR;
895
896 reader = resp;
897 len = 0;
898 previous_dname = NULL;
899 query = NULL;
900 answer_record = NULL;
901
902 /* Initialization of response buffer and structure */
903 r_res = &resolution->response;
904
905 /* query id */
906 if (reader + 2 >= bufend)
907 goto invalid_resp;
908
909 r_res->header.id = reader[0] * 256 + reader[1];
910 reader += 2;
911
912 /* Flags and rcode are stored over 2 bytes
913 * First byte contains:
914 * - response flag (1 bit)
915 * - opcode (4 bits)
916 * - authoritative (1 bit)
917 * - truncated (1 bit)
918 * - recursion desired (1 bit)
919 */
920 if (reader + 2 >= bufend)
921 goto invalid_resp;
922
923 flags = reader[0] * 256 + reader[1];
924
925 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
926 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
927 cause = RSLV_RESP_NX_DOMAIN;
928 goto return_error;
929 }
930 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
931 cause = RSLV_RESP_REFUSED;
932 goto return_error;
933 }
934 else {
935 cause = RSLV_RESP_ERROR;
936 goto return_error;
937 }
938 }
939
940 /* Move forward 2 bytes for flags */
941 reader += 2;
942
943 /* 2 bytes for question count */
944 if (reader + 2 >= bufend)
945 goto invalid_resp;
946 r_res->header.qdcount = reader[0] * 256 + reader[1];
947 /* (for now) we send one query only, so we expect only one in the
948 * response too */
949 if (r_res->header.qdcount != 1) {
950 cause = RSLV_RESP_QUERY_COUNT_ERROR;
951 goto return_error;
952 }
953
954 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
955 goto invalid_resp;
956 reader += 2;
957
958 /* 2 bytes for answer count */
959 if (reader + 2 >= bufend)
960 goto invalid_resp;
961 r_res->header.ancount = reader[0] * 256 + reader[1];
962 if (r_res->header.ancount == 0) {
963 cause = RSLV_RESP_ANCOUNT_ZERO;
964 goto return_error;
965 }
966
967 /* Check if too many records are announced */
968 if (r_res->header.ancount > max_answer_records)
969 goto invalid_resp;
970 reader += 2;
971
972 /* 2 bytes authority count */
973 if (reader + 2 >= bufend)
974 goto invalid_resp;
975 r_res->header.nscount = reader[0] * 256 + reader[1];
976 reader += 2;
977
978 /* 2 bytes additional count */
979 if (reader + 2 >= bufend)
980 goto invalid_resp;
981 r_res->header.arcount = reader[0] * 256 + reader[1];
982 reader += 2;
983
984 /* Parsing dns queries */
Willy Tarreau51128f82021-10-19 11:17:33 +0200985 BUG_ON(!LIST_ISEMPTY(&r_res->query_list));
Emeric Brunc9437992021-02-12 19:42:55 +0100986 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
987 /* Use next pre-allocated resolv_query_item after ensuring there is
988 * still one available.
989 * It's then added to our packet query list. */
990 if (query_record_id > DNS_MAX_QUERY_RECORDS)
991 goto invalid_resp;
992 query = &resolution->response_query_records[query_record_id];
Willy Tarreau2b718102021-04-21 07:32:39 +0200993 LIST_APPEND(&r_res->query_list, &query->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100994
995 /* Name is a NULL terminated string in our case, since we have
996 * one query per response and the first one can't be compressed
997 * (using the 0x0c format) */
998 offset = 0;
999 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
1000
1001 if (len == 0)
1002 goto invalid_resp;
1003
1004 reader += offset;
1005 previous_dname = query->name;
1006
1007 /* move forward 2 bytes for question type */
1008 if (reader + 2 >= bufend)
1009 goto invalid_resp;
1010 query->type = reader[0] * 256 + reader[1];
1011 reader += 2;
1012
1013 /* move forward 2 bytes for question class */
1014 if (reader + 2 >= bufend)
1015 goto invalid_resp;
1016 query->class = reader[0] * 256 + reader[1];
1017 reader += 2;
1018 }
1019
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001020 /* Let's just make gcc happy. The tests above make it clear that
1021 * qdcount==1 hence that we necessarily enter into the loop at least
1022 * once, but gcc seems to be having difficulties following it and
1023 * warns about the risk of NULL dereference at the next line, even
1024 * if a BUG_ON(!query) is used.
1025 */
1026 ALREADY_CHECKED(query);
1027
Emeric Brunc9437992021-02-12 19:42:55 +01001028 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001029 * because a TRUNCATED SRV query type response can still be exploited
1030 */
Emeric Brunc9437992021-02-12 19:42:55 +01001031 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1032 cause = RSLV_RESP_TRUNCATED;
1033 goto return_error;
1034 }
1035
1036 /* now parsing response records */
1037 nb_saved_records = 0;
1038 for (i = 0; i < r_res->header.ancount; i++) {
1039 if (reader >= bufend)
1040 goto invalid_resp;
1041
1042 answer_record = pool_alloc(resolv_answer_item_pool);
1043 if (answer_record == NULL)
1044 goto invalid_resp;
1045
1046 /* initialization */
1047 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001048 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001049 LIST_INIT(&answer_record->attached_servers);
Willy Tarreaua2373e82021-10-19 11:29:21 +02001050 LIST_INIT(&answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001051
1052 offset = 0;
1053 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1054
1055 if (len == 0)
1056 goto invalid_resp;
1057
1058 /* Check if the current record dname is valid. previous_dname
1059 * points either to queried dname or last CNAME target */
1060 if (query->type != DNS_RTYPE_SRV && resolv_hostname_cmp(previous_dname, tmpname, len) != 0) {
1061 if (i == 0) {
1062 /* First record, means a mismatch issue between
1063 * queried dname and dname found in the first
1064 * record */
1065 goto invalid_resp;
1066 }
1067 else {
1068 /* If not the first record, this means we have a
1069 * CNAME resolution error.
1070 */
1071 cause = RSLV_RESP_CNAME_ERROR;
1072 goto return_error;
1073 }
1074
1075 }
1076
1077 memcpy(answer_record->name, tmpname, len);
1078 answer_record->name[len] = 0;
1079
1080 reader += offset;
1081 if (reader >= bufend)
1082 goto invalid_resp;
1083
1084 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1085 if (reader + 2 > bufend)
1086 goto invalid_resp;
1087
1088 answer_record->type = reader[0] * 256 + reader[1];
1089 reader += 2;
1090
1091 /* 2 bytes for class (2) */
1092 if (reader + 2 > bufend)
1093 goto invalid_resp;
1094
1095 answer_record->class = reader[0] * 256 + reader[1];
1096 reader += 2;
1097
1098 /* 4 bytes for ttl (4) */
1099 if (reader + 4 > bufend)
1100 goto invalid_resp;
1101
1102 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1103 + reader[2] * 256 + reader[3];
1104 reader += 4;
1105
1106 /* Now reading data len */
1107 if (reader + 2 > bufend)
1108 goto invalid_resp;
1109
1110 answer_record->data_len = reader[0] * 256 + reader[1];
1111
1112 /* Move forward 2 bytes for data len */
1113 reader += 2;
1114
1115 if (reader + answer_record->data_len > bufend)
1116 goto invalid_resp;
1117
1118 /* Analyzing record content */
1119 switch (answer_record->type) {
1120 case DNS_RTYPE_A:
1121 /* ipv4 is stored on 4 bytes */
1122 if (answer_record->data_len != 4)
1123 goto invalid_resp;
1124
Willy Tarreau20a02372021-10-14 22:52:04 +02001125 answer_record->data.in4.sin_family = AF_INET;
1126 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001127 break;
1128
1129 case DNS_RTYPE_CNAME:
1130 /* Check if this is the last record and update the caller about the status:
1131 * no IP could be found and last record was a CNAME. Could be triggered
1132 * by a wrong query type
1133 *
1134 * + 1 because answer_record_id starts at 0
1135 * while number of answers is an integer and
1136 * starts at 1.
1137 */
1138 if (i + 1 == r_res->header.ancount) {
1139 cause = RSLV_RESP_CNAME_ERROR;
1140 goto return_error;
1141 }
1142
1143 offset = 0;
1144 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1145 if (len == 0)
1146 goto invalid_resp;
1147
Willy Tarreau20a02372021-10-14 22:52:04 +02001148 memcpy(answer_record->data.target, tmpname, len);
1149 answer_record->data.target[len] = 0;
1150 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001151 break;
1152
1153
1154 case DNS_RTYPE_SRV:
1155 /* Answer must contain :
1156 * - 2 bytes for the priority
1157 * - 2 bytes for the weight
1158 * - 2 bytes for the port
1159 * - the target hostname
1160 */
1161 if (answer_record->data_len <= 6)
1162 goto invalid_resp;
1163
1164 answer_record->priority = read_n16(reader);
1165 reader += sizeof(uint16_t);
1166 answer_record->weight = read_n16(reader);
1167 reader += sizeof(uint16_t);
1168 answer_record->port = read_n16(reader);
1169 reader += sizeof(uint16_t);
1170 offset = 0;
1171 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1172 if (len == 0)
1173 goto invalid_resp;
1174
1175 answer_record->data_len = len;
Willy Tarreau20a02372021-10-14 22:52:04 +02001176 memcpy(answer_record->data.target, tmpname, len);
1177 answer_record->data.target[len] = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01001178 if (answer_record->ar_item != NULL) {
1179 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1180 answer_record->ar_item = NULL;
1181 }
1182 break;
1183
1184 case DNS_RTYPE_AAAA:
1185 /* ipv6 is stored on 16 bytes */
1186 if (answer_record->data_len != 16)
1187 goto invalid_resp;
1188
Willy Tarreau20a02372021-10-14 22:52:04 +02001189 answer_record->data.in6.sin6_family = AF_INET6;
1190 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001191 break;
1192
1193 } /* switch (record type) */
1194
1195 /* Increment the counter for number of records saved into our
1196 * local response */
1197 nb_saved_records++;
1198
1199 /* Move forward answer_record->data_len for analyzing next
1200 * record in the response */
1201 reader += ((answer_record->type == DNS_RTYPE_SRV)
1202 ? offset
1203 : answer_record->data_len);
1204
1205 /* Lookup to see if we already had this entry */
1206 found = 0;
1207 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1208 if (tmp_record->type != answer_record->type)
1209 continue;
1210
1211 switch(tmp_record->type) {
1212 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001213 if (!memcmp(&answer_record->data.in4.sin_addr,
1214 &tmp_record->data.in4.sin_addr,
1215 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001216 found = 1;
1217 break;
1218
1219 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001220 if (!memcmp(&answer_record->data.in6.sin6_addr,
1221 &tmp_record->data.in6.sin6_addr,
1222 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001223 found = 1;
1224 break;
1225
1226 case DNS_RTYPE_SRV:
1227 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001228 !resolv_hostname_cmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) &&
Emeric Brunc9437992021-02-12 19:42:55 +01001229 answer_record->port == tmp_record->port) {
1230 tmp_record->weight = answer_record->weight;
1231 found = 1;
1232 }
1233 break;
1234
1235 default:
1236 break;
1237 }
1238
1239 if (found == 1)
1240 break;
1241 }
1242
1243 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001244 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001245 pool_free(resolv_answer_item_pool, answer_record);
1246 answer_record = NULL;
1247 }
1248 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001249 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001250 answer_record->ar_item = NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +02001251 LIST_APPEND(&r_res->answer_list, &answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001252 answer_record = NULL;
1253 }
1254 } /* for i 0 to ancount */
1255
1256 /* Save the number of records we really own */
1257 r_res->header.ancount = nb_saved_records;
1258
1259 /* now parsing additional records for SRV queries only */
1260 if (query->type != DNS_RTYPE_SRV)
1261 goto skip_parsing_additional_records;
1262
1263 /* if we find Authority records, just skip them */
1264 for (i = 0; i < r_res->header.nscount; i++) {
1265 offset = 0;
1266 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1267 &offset, 0);
1268 if (len == 0)
1269 continue;
1270
1271 if (reader + offset + 10 >= bufend)
1272 goto invalid_resp;
1273
1274 reader += offset;
1275 /* skip 2 bytes for class */
1276 reader += 2;
1277 /* skip 2 bytes for type */
1278 reader += 2;
1279 /* skip 4 bytes for ttl */
1280 reader += 4;
1281 /* read data len */
1282 len = reader[0] * 256 + reader[1];
1283 reader += 2;
1284
1285 if (reader + len >= bufend)
1286 goto invalid_resp;
1287
1288 reader += len;
1289 }
1290
1291 nb_saved_records = 0;
1292 for (i = 0; i < r_res->header.arcount; i++) {
1293 if (reader >= bufend)
1294 goto invalid_resp;
1295
1296 answer_record = pool_alloc(resolv_answer_item_pool);
1297 if (answer_record == NULL)
1298 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001299 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001300 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001301
1302 offset = 0;
1303 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1304
1305 if (len == 0) {
1306 pool_free(resolv_answer_item_pool, answer_record);
1307 answer_record = NULL;
1308 continue;
1309 }
1310
1311 memcpy(answer_record->name, tmpname, len);
1312 answer_record->name[len] = 0;
1313
1314 reader += offset;
1315 if (reader >= bufend)
1316 goto invalid_resp;
1317
1318 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1319 if (reader + 2 > bufend)
1320 goto invalid_resp;
1321
1322 answer_record->type = reader[0] * 256 + reader[1];
1323 reader += 2;
1324
1325 /* 2 bytes for class (2) */
1326 if (reader + 2 > bufend)
1327 goto invalid_resp;
1328
1329 answer_record->class = reader[0] * 256 + reader[1];
1330 reader += 2;
1331
1332 /* 4 bytes for ttl (4) */
1333 if (reader + 4 > bufend)
1334 goto invalid_resp;
1335
1336 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1337 + reader[2] * 256 + reader[3];
1338 reader += 4;
1339
1340 /* Now reading data len */
1341 if (reader + 2 > bufend)
1342 goto invalid_resp;
1343
1344 answer_record->data_len = reader[0] * 256 + reader[1];
1345
1346 /* Move forward 2 bytes for data len */
1347 reader += 2;
1348
1349 if (reader + answer_record->data_len > bufend)
1350 goto invalid_resp;
1351
1352 /* Analyzing record content */
1353 switch (answer_record->type) {
1354 case DNS_RTYPE_A:
1355 /* ipv4 is stored on 4 bytes */
1356 if (answer_record->data_len != 4)
1357 goto invalid_resp;
1358
Willy Tarreau20a02372021-10-14 22:52:04 +02001359 answer_record->data.in4.sin_family = AF_INET;
1360 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001361 break;
1362
1363 case DNS_RTYPE_AAAA:
1364 /* ipv6 is stored on 16 bytes */
1365 if (answer_record->data_len != 16)
1366 goto invalid_resp;
1367
Willy Tarreau20a02372021-10-14 22:52:04 +02001368 answer_record->data.in6.sin6_family = AF_INET6;
1369 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001370 break;
1371
1372 default:
1373 pool_free(resolv_answer_item_pool, answer_record);
1374 answer_record = NULL;
1375 continue;
1376
1377 } /* switch (record type) */
1378
1379 /* Increment the counter for number of records saved into our
1380 * local response */
1381 nb_saved_records++;
1382
1383 /* Move forward answer_record->data_len for analyzing next
1384 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001385 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001386
1387 /* Lookup to see if we already had this entry */
1388 found = 0;
1389 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001390 struct resolv_answer_item *ar_item;
1391
1392 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1393 continue;
1394
1395 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001396 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001397 len != tmp_record->data_len ||
Willy Tarreau20a02372021-10-14 22:52:04 +02001398 resolv_hostname_cmp(answer_record->name, tmp_record->data.target, tmp_record->data_len))
Emeric Brunc9437992021-02-12 19:42:55 +01001399 continue;
1400
Christopher Faulet77f86062021-03-10 15:19:57 +01001401 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001402 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001403 if (!memcmp(&answer_record->data.in4.sin_addr,
1404 &ar_item->data.in4.sin_addr,
1405 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001406 found = 1;
1407 break;
1408
1409 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001410 if (!memcmp(&answer_record->data.in6.sin6_addr,
1411 &ar_item->data.in6.sin6_addr,
1412 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001413 found = 1;
1414 break;
1415
1416 default:
1417 break;
1418 }
1419
1420 if (found == 1)
1421 break;
1422 }
1423
1424 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001425 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001426 pool_free(resolv_answer_item_pool, answer_record);
1427 answer_record = NULL;
1428 }
1429 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001430 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001431 answer_record->ar_item = NULL;
1432
1433 // looking for the SRV record in the response list linked to this additional record
1434 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1435 if (tmp_record->type == DNS_RTYPE_SRV &&
1436 tmp_record->ar_item == NULL &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001437 !resolv_hostname_cmp(tmp_record->data.target, answer_record->name, tmp_record->data_len)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001438 /* Always use the received additional record to refresh info */
1439 if (tmp_record->ar_item)
1440 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1441 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001442 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001443 break;
1444 }
1445 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001446 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001447 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001448 answer_record = NULL;
1449 }
Emeric Brunc9437992021-02-12 19:42:55 +01001450 }
1451 } /* for i 0 to arcount */
1452
1453 skip_parsing_additional_records:
1454
1455 /* Save the number of records we really own */
1456 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001457 resolv_check_response(resolution);
1458 return RSLV_RESP_VALID;
1459
1460 invalid_resp:
1461 cause = RSLV_RESP_INVALID;
1462
1463 return_error:
1464 pool_free(resolv_answer_item_pool, answer_record);
1465 return cause;
1466}
1467
1468/* Searches dn_name resolution in resp.
1469 * If existing IP not found, return the first IP matching family_priority,
1470 * otherwise, first ip found
1471 * The following tasks are the responsibility of the caller:
1472 * - <r_res> contains an error free DNS response
1473 * For both cases above, resolv_validate_dns_response is required
1474 * returns one of the RSLV_UPD_* code
1475 */
1476int resolv_get_ip_from_response(struct resolv_response *r_res,
1477 struct resolv_options *resolv_opts, void *currentip,
1478 short currentip_sin_family,
1479 void **newip, short *newip_sin_family,
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001480 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001481{
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001482 struct resolv_answer_item *record, *found_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001483 int family_priority;
1484 int currentip_found;
1485 unsigned char *newip4, *newip6;
1486 int currentip_sel;
1487 int j;
1488 int score, max_score;
1489 int allowed_duplicated_ip;
1490
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001491 /* srv is linked to an alive ip record */
1492 if (owner && LIST_INLIST(&owner->ip_rec_item))
1493 return RSLV_UPD_NO;
1494
Emeric Brunc9437992021-02-12 19:42:55 +01001495 family_priority = resolv_opts->family_prio;
1496 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1497 *newip = newip4 = newip6 = NULL;
1498 currentip_found = 0;
1499 *newip_sin_family = AF_UNSPEC;
1500 max_score = -1;
1501
1502 /* Select an IP regarding configuration preference.
1503 * Top priority is the preferred network ip version,
1504 * second priority is the preferred network.
1505 * the last priority is the currently used IP,
1506 *
1507 * For these three priorities, a score is calculated. The
1508 * weight are:
1509 * 8 - preferred ip version.
1510 * 4 - preferred network.
1511 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1512 * 1 - current ip.
1513 * The result with the biggest score is returned.
1514 */
1515
1516 list_for_each_entry(record, &r_res->answer_list, list) {
1517 void *ip;
1518 unsigned char ip_type;
1519
1520 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001521 ip_type = AF_INET;
Willy Tarreau20a02372021-10-14 22:52:04 +02001522 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001523 }
1524 else if (record->type == DNS_RTYPE_AAAA) {
1525 ip_type = AF_INET6;
Willy Tarreau20a02372021-10-14 22:52:04 +02001526 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001527 }
1528 else
1529 continue;
1530 score = 0;
1531
1532 /* Check for preferred ip protocol. */
1533 if (ip_type == family_priority)
1534 score += 8;
1535
1536 /* Check for preferred network. */
1537 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1538
1539 /* Compare only the same addresses class. */
1540 if (resolv_opts->pref_net[j].family != ip_type)
1541 continue;
1542
1543 if ((ip_type == AF_INET &&
1544 in_net_ipv4(ip,
1545 &resolv_opts->pref_net[j].mask.in4,
1546 &resolv_opts->pref_net[j].addr.in4)) ||
1547 (ip_type == AF_INET6 &&
1548 in_net_ipv6(ip,
1549 &resolv_opts->pref_net[j].mask.in6,
1550 &resolv_opts->pref_net[j].addr.in6))) {
1551 score += 4;
1552 break;
1553 }
1554 }
1555
1556 /* Check if the IP found in the record is already affected to a
1557 * member of a group. If not, the score should be incremented
1558 * by 2. */
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001559 if (owner) {
1560 struct server *srv;
1561 int already_used = 0;
1562
1563 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1564 if (srv == owner)
1565 continue;
1566 if (srv->proxy == owner->proxy) {
1567 already_used = 1;
1568 break;
1569 }
1570 }
1571 if (already_used) {
1572 if (!allowed_duplicated_ip) {
1573 continue;
1574 }
1575 }
1576 else {
1577 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001578 }
1579 } else {
1580 score += 2;
1581 }
1582
1583 /* Check for current ip matching. */
1584 if (ip_type == currentip_sin_family &&
1585 ((currentip_sin_family == AF_INET &&
1586 !memcmp(ip, currentip, 4)) ||
1587 (currentip_sin_family == AF_INET6 &&
1588 !memcmp(ip, currentip, 16)))) {
1589 score++;
1590 currentip_sel = 1;
1591 }
1592 else
1593 currentip_sel = 0;
1594
1595 /* Keep the address if the score is better than the previous
1596 * score. The maximum score is 15, if this value is reached, we
1597 * break the parsing. Implicitly, this score is reached the ip
1598 * selected is the current ip. */
1599 if (score > max_score) {
1600 if (ip_type == AF_INET)
1601 newip4 = ip;
1602 else
1603 newip6 = ip;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001604 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001605 currentip_found = currentip_sel;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001606 if (score == 15) {
1607 /* this was not registered on the current record but it matches
1608 * let's fix it (it may comes from state file */
1609 if (owner)
1610 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001611 return RSLV_UPD_NO;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001612 }
Emeric Brunc9437992021-02-12 19:42:55 +01001613 max_score = score;
1614 }
1615 } /* list for each record entries */
1616
1617 /* No IP found in the response */
1618 if (!newip4 && !newip6)
1619 return RSLV_UPD_NO_IP_FOUND;
1620
1621 /* Case when the caller looks first for an IPv4 address */
1622 if (family_priority == AF_INET) {
1623 if (newip4) {
1624 *newip = newip4;
1625 *newip_sin_family = AF_INET;
1626 }
1627 else if (newip6) {
1628 *newip = newip6;
1629 *newip_sin_family = AF_INET6;
1630 }
Emeric Brunc9437992021-02-12 19:42:55 +01001631 }
1632 /* Case when the caller looks first for an IPv6 address */
1633 else if (family_priority == AF_INET6) {
1634 if (newip6) {
1635 *newip = newip6;
1636 *newip_sin_family = AF_INET6;
1637 }
1638 else if (newip4) {
1639 *newip = newip4;
1640 *newip_sin_family = AF_INET;
1641 }
Emeric Brunc9437992021-02-12 19:42:55 +01001642 }
1643 /* Case when the caller have no preference (we prefer IPv6) */
1644 else if (family_priority == AF_UNSPEC) {
1645 if (newip6) {
1646 *newip = newip6;
1647 *newip_sin_family = AF_INET6;
1648 }
1649 else if (newip4) {
1650 *newip = newip4;
1651 *newip_sin_family = AF_INET;
1652 }
Emeric Brunc9437992021-02-12 19:42:55 +01001653 }
1654
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001655 /* the ip of this record was chosen for the server */
1656 if (owner && found_record) {
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001657 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001658 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1659 }
1660
Emeric Brunc9437992021-02-12 19:42:55 +01001661 list_for_each_entry(record, &r_res->answer_list, list) {
1662 /* Move the first record to the end of the list, for internal
1663 * round robin */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001664 LIST_DEL_INIT(&record->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02001665 LIST_APPEND(&r_res->answer_list, &record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001666 break;
1667 }
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001668
1669 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001670}
1671
Willy Tarreauca0170b2021-10-14 08:05:25 +02001672/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001673 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001674 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1675 * null-terminated. <str> must be allocated large enough to contain a full host
1676 * name plus the trailing zero, and the allocated size must be passed in
1677 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001678 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001679 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001680 * <str> (including the terminating null byte).
1681 */
1682int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1683{
1684 char *ptr;
1685 int i, sz;
1686
Willy Tarreauca0170b2021-10-14 08:05:25 +02001687 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001688 return -1;
1689
1690 ptr = str;
Willy Tarreauca0170b2021-10-14 08:05:25 +02001691 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001692 sz = dn[i];
1693 if (i)
1694 *ptr++ = '.';
1695 memcpy(ptr, dn+i+1, sz);
1696 ptr += sz;
1697 i += sz;
1698 }
1699 *ptr++ = '\0';
1700 return (ptr - str);
1701}
1702
1703/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1704 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001705 * <str> contains the input string that is <str_len> bytes long (trailing zero
1706 * not needed). <dn> buffer must be allocated large enough to contain the
1707 * encoded string and a trailing zero, so it must be at least str_len+2, and
1708 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001709 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001710 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001711 * <dn> (excluding the terminating null byte).
1712 */
1713int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1714{
1715 int i, offset;
1716
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001717 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001718 return -1;
1719
1720 /* First byte of dn will be used to store the length of the first
1721 * label */
1722 offset = 0;
1723 for (i = 0; i < str_len; ++i) {
1724 if (str[i] == '.') {
1725 /* 2 or more consecutive dots is invalid */
1726 if (i == offset)
1727 return -1;
1728
1729 /* ignore trailing dot */
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001730 if (i + 1 == str_len) {
Emeric Brunc9437992021-02-12 19:42:55 +01001731 i++;
1732 break;
1733 }
1734
1735 dn[offset] = (i - offset);
1736 offset = i+1;
1737 continue;
1738 }
1739 dn[i+1] = str[i];
1740 }
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001741 dn[offset] = i - offset;
Willy Tarreau68c7b362021-10-15 08:09:25 +02001742 dn[i+1] = '\0';
1743 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001744}
1745
1746/* Validates host name:
1747 * - total size
1748 * - each label size individually
1749 * returns:
1750 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1751 * 1 when no error. <err> is left unaffected.
1752 */
1753int resolv_hostname_validation(const char *string, char **err)
1754{
1755 int i;
1756
1757 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1758 if (err)
1759 *err = DNS_TOO_LONG_FQDN;
1760 return 0;
1761 }
1762
1763 while (*string) {
1764 i = 0;
1765 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1766 if (!(*string == '-' || *string == '_' ||
1767 (*string >= 'a' && *string <= 'z') ||
1768 (*string >= 'A' && *string <= 'Z') ||
1769 (*string >= '0' && *string <= '9'))) {
1770 if (err)
1771 *err = DNS_INVALID_CHARACTER;
1772 return 0;
1773 }
1774 i++;
1775 string++;
1776 }
1777
1778 if (!(*string))
1779 break;
1780
1781 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1782 if (err)
1783 *err = DNS_LABEL_TOO_LONG;
1784 return 0;
1785 }
1786
1787 string++;
1788 }
1789 return 1;
1790}
1791
1792/* Picks up an available resolution from the different resolution list
1793 * associated to a resolvers section, in this order:
1794 * 1. check in resolutions.curr for the same hostname and query_type
1795 * 2. check in resolutions.wait for the same hostname and query_type
1796 * 3. Get a new resolution from resolution pool
1797 *
1798 * Returns an available resolution, NULL if none found.
1799 */
1800static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1801 char **hostname_dn, int hostname_dn_len,
1802 int query_type)
1803{
1804 struct resolv_resolution *res;
1805
1806 if (!*hostname_dn)
1807 goto from_pool;
1808
1809 /* Search for same hostname and query type in resolutions.curr */
1810 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1811 if (!res->hostname_dn)
1812 continue;
1813 if ((query_type == res->prefered_query_type) &&
1814 hostname_dn_len == res->hostname_dn_len &&
1815 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1816 return res;
1817 }
1818
1819 /* Search for same hostname and query type in resolutions.wait */
1820 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1821 if (!res->hostname_dn)
1822 continue;
1823 if ((query_type == res->prefered_query_type) &&
1824 hostname_dn_len == res->hostname_dn_len &&
1825 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1826 return res;
1827 }
1828
1829 from_pool:
1830 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001831 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001832 if (res) {
Willy Tarreau51128f82021-10-19 11:17:33 +02001833 int i;
1834
Emeric Brunc9437992021-02-12 19:42:55 +01001835 res->resolvers = resolvers;
1836 res->uuid = resolution_uuid;
1837 res->status = RSLV_STATUS_NONE;
1838 res->step = RSLV_STEP_NONE;
1839 res->last_valid = now_ms;
1840
1841 LIST_INIT(&res->requesters);
Willy Tarreau51128f82021-10-19 11:17:33 +02001842 LIST_INIT(&res->response.query_list);
Emeric Brunc9437992021-02-12 19:42:55 +01001843 LIST_INIT(&res->response.answer_list);
1844
Willy Tarreau51128f82021-10-19 11:17:33 +02001845 for (i = 0; i < DNS_MAX_QUERY_RECORDS; i++)
1846 LIST_INIT(&res->response_query_records[i].list);
1847
Emeric Brunc9437992021-02-12 19:42:55 +01001848 res->prefered_query_type = query_type;
1849 res->query_type = query_type;
1850 res->hostname_dn = *hostname_dn;
1851 res->hostname_dn_len = hostname_dn_len;
1852
1853 ++resolution_uuid;
1854
1855 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001856 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001857 }
1858 return res;
1859}
1860
Willy Tarreauaab75932021-10-19 11:16:11 +02001861/* deletes and frees all answer_items from the resolution's answer_list */
1862static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001863{
1864 struct resolv_answer_item *item, *itemback;
1865
1866 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001867 LIST_DEL_INIT(&item->list);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001868 pool_free(resolv_answer_item_pool, item->ar_item);
1869 pool_free(resolv_answer_item_pool, item);
1870 }
1871}
1872
Willy Tarreau51128f82021-10-19 11:17:33 +02001873/* deletes all query_items from the resolution's query_list */
1874static void resolv_purge_resolution_query_items(struct resolv_resolution *resolution)
1875{
1876 struct resolv_query_item *item, *itemback;
1877
1878 list_for_each_entry_safe(item, itemback, &resolution->response.query_list, list)
1879 LIST_DEL_INIT(&item->list);
1880}
1881
Emeric Brunc9437992021-02-12 19:42:55 +01001882/* Releases a resolution from its requester(s) and move it back to the pool */
1883static void resolv_free_resolution(struct resolv_resolution *resolution)
1884{
1885 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001886
1887 /* clean up configuration */
1888 resolv_reset_resolution(resolution);
1889 resolution->hostname_dn = NULL;
1890 resolution->hostname_dn_len = 0;
1891
1892 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001893 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001894 req->resolution = NULL;
1895 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001896 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau51128f82021-10-19 11:17:33 +02001897 resolv_purge_resolution_query_items(resolution);
1898
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001899 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001900 pool_free(resolv_resolution_pool, resolution);
1901}
1902
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001903/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1904 * and makes it owned by this obj_type, with the proposed callback and error
1905 * callback. On success, *req is assigned the allocated requester. Returns
1906 * NULL on allocation failure.
1907 */
1908static struct resolv_requester *
1909resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1910 int (*cb)(struct resolv_requester *, struct dns_counters *),
1911 int (*err_cb)(struct resolv_requester *, int))
1912{
1913 struct resolv_requester *tmp;
1914
1915 if (*req)
1916 return *req;
1917
1918 tmp = pool_alloc(resolv_requester_pool);
1919 if (!tmp)
1920 goto end;
1921
1922 LIST_INIT(&tmp->list);
1923 tmp->owner = owner;
1924 tmp->resolution = NULL;
1925 tmp->requester_cb = cb;
1926 tmp->requester_error_cb = err_cb;
1927 *req = tmp;
1928 end:
1929 return tmp;
1930}
1931
Emeric Brunc9437992021-02-12 19:42:55 +01001932/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Willy Tarreau20751652021-10-18 16:46:38 +02001933 * on success, -1 otherwise. Must be called with the death_row already initialized
1934 * via init_aborted_resolutions().
Emeric Brunc9437992021-02-12 19:42:55 +01001935 */
1936int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1937{
1938 struct resolv_resolution *res = NULL;
1939 struct resolv_requester *req;
1940 struct resolvers *resolvers;
1941 struct server *srv = NULL;
1942 struct resolv_srvrq *srvrq = NULL;
1943 struct stream *stream = NULL;
1944 char **hostname_dn;
1945 int hostname_dn_len, query_type;
1946
1947 switch (requester_type) {
1948 case OBJ_TYPE_SERVER:
1949 srv = (struct server *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001950
1951 if (!requester_locked)
1952 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1953
1954 req = resolv_get_requester(&srv->resolv_requester,
1955 &srv->obj_type,
1956 snr_resolution_cb,
1957 snr_resolution_error_cb);
1958
1959 if (!requester_locked)
1960 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1961
1962 if (!req)
1963 goto err;
1964
Emeric Brunc9437992021-02-12 19:42:55 +01001965 hostname_dn = &srv->hostname_dn;
1966 hostname_dn_len = srv->hostname_dn_len;
1967 resolvers = srv->resolvers;
1968 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1969 ? DNS_RTYPE_A
1970 : DNS_RTYPE_AAAA);
1971 break;
1972
1973 case OBJ_TYPE_SRVRQ:
1974 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001975
1976 req = resolv_get_requester(&srvrq->requester,
1977 &srvrq->obj_type,
1978 snr_resolution_cb,
1979 srvrq_resolution_error_cb);
1980 if (!req)
1981 goto err;
1982
Emeric Brunc9437992021-02-12 19:42:55 +01001983 hostname_dn = &srvrq->hostname_dn;
1984 hostname_dn_len = srvrq->hostname_dn_len;
1985 resolvers = srvrq->resolvers;
1986 query_type = DNS_RTYPE_SRV;
1987 break;
1988
1989 case OBJ_TYPE_STREAM:
1990 stream = (struct stream *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001991
1992 req = resolv_get_requester(&stream->resolv_ctx.requester,
1993 &stream->obj_type,
1994 act_resolution_cb,
1995 act_resolution_error_cb);
1996 if (!req)
1997 goto err;
1998
Emeric Brunc9437992021-02-12 19:42:55 +01001999 hostname_dn = &stream->resolv_ctx.hostname_dn;
2000 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2001 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2002 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2003 ? DNS_RTYPE_A
2004 : DNS_RTYPE_AAAA);
2005 break;
2006 default:
2007 goto err;
2008 }
2009
2010 /* Get a resolution from the resolvers' wait queue or pool */
2011 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2012 goto err;
2013
Willy Tarreau4d7ca912021-10-19 11:59:25 +02002014 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002015
Willy Tarreau2b718102021-04-21 07:32:39 +02002016 LIST_APPEND(&res->requesters, &req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002017 return 0;
2018
2019 err:
2020 if (res && LIST_ISEMPTY(&res->requesters))
2021 resolv_free_resolution(res);
2022 return -1;
2023}
2024
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002025/* This function removes all server/srvrq references on answer items
2026 * if <safe> is set to 1, in case of srvrq, sub server resquesters unlink
Willy Tarreau20751652021-10-18 16:46:38 +02002027 * is called using safe == 1 to make it usable into callbacks. Must be called
2028 * with the death_row already initialized via init_aborted_resolutions().
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002029 */
Willy Tarreau33360872021-10-20 14:07:31 +02002030void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002031{
2032 struct resolv_answer_item *item, *itemback;
2033 struct server *srv, *srvback;
2034 struct resolv_srvrq *srvrq;
2035
2036 if ((srv = objt_server(req->owner)) != NULL) {
2037 LIST_DEL_INIT(&srv->ip_rec_item);
2038 }
2039 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
2040 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
2041 if (item->type == DNS_RTYPE_SRV) {
2042 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet5f8ccff2021-06-15 16:08:48 +02002043 if (srv->srvrq == srvrq)
Willy Tarreau20751652021-10-18 16:46:38 +02002044 resolv_srvrq_cleanup_srv(srv);
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002045 }
2046 }
2047 }
2048 }
2049}
2050
Emeric Brunc9437992021-02-12 19:42:55 +01002051/* Removes a requester from a DNS resolution. It takes takes care of all the
2052 * consequences. It also cleans up some parameters from the requester.
Willy Tarreau20751652021-10-18 16:46:38 +02002053 * if <safe> is set to 1, the corresponding resolution is not released. Must be
2054 * called with the death_row already initialized via init_aborted_resolutions().
Emeric Brunc9437992021-02-12 19:42:55 +01002055 */
Willy Tarreau33360872021-10-20 14:07:31 +02002056static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002057{
2058 struct resolv_resolution *res;
2059 struct resolv_requester *req;
2060
2061 /* Nothing to do */
2062 if (!requester || !requester->resolution)
2063 return;
2064 res = requester->resolution;
2065
Emeric Brunf9ca5d82021-06-11 10:08:05 +02002066 /* remove ref from the resolution answer item list to the requester */
Willy Tarreau33360872021-10-20 14:07:31 +02002067 resolv_detach_from_resolution_answer_items(res, requester);
Emeric Brunf9ca5d82021-06-11 10:08:05 +02002068
Emeric Brunc9437992021-02-12 19:42:55 +01002069 /* Clean up the requester */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002070 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002071 requester->resolution = NULL;
2072
2073 /* We need to find another requester linked on this resolution */
2074 if (!LIST_ISEMPTY(&res->requesters))
2075 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2076 else {
Willy Tarreau20751652021-10-18 16:46:38 +02002077 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002078 return;
2079 }
2080
2081 /* Move hostname_dn related pointers to the next requester */
2082 switch (obj_type(req->owner)) {
2083 case OBJ_TYPE_SERVER:
2084 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2085 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2086 break;
2087 case OBJ_TYPE_SRVRQ:
2088 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2089 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2090 break;
2091 case OBJ_TYPE_STREAM:
2092 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2093 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2094 break;
2095 default:
2096 res->hostname_dn = NULL;
2097 res->hostname_dn_len = 0;
2098 break;
2099 }
2100}
2101
Willy Tarreau20751652021-10-18 16:46:38 +02002102/* The public version of the function above that deals with the death row. */
Willy Tarreau33360872021-10-20 14:07:31 +02002103void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreau20751652021-10-18 16:46:38 +02002104{
2105 init_aborted_resolutions();
Willy Tarreau33360872021-10-20 14:07:31 +02002106 _resolv_unlink_resolution(requester);
Willy Tarreau20751652021-10-18 16:46:38 +02002107 free_aborted_resolutions();
2108}
2109
Emeric Brunc9437992021-02-12 19:42:55 +01002110/* Called when a network IO is generated on a name server socket for an incoming
2111 * packet. It performs the following actions:
2112 * - check if the packet requires processing (not outdated resolution)
2113 * - ensure the DNS packet received is valid and call requester's callback
2114 * - call requester's error callback if invalid response
2115 * - check the dn_name in the packet against the one sent
Willy Tarreau20751652021-10-18 16:46:38 +02002116 *
2117 * Must be called with the death_row already initialized via init_aborted_resolutions().
Emeric Brunc9437992021-02-12 19:42:55 +01002118 */
2119static int resolv_process_responses(struct dns_nameserver *ns)
2120{
2121 struct dns_counters *tmpcounters;
2122 struct resolvers *resolvers;
2123 struct resolv_resolution *res;
2124 struct resolv_query_item *query;
2125 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2126 unsigned char *bufend;
2127 int buflen, dns_resp;
2128 int max_answer_records;
2129 unsigned short query_id;
2130 struct eb32_node *eb;
2131 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002132 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002133
2134 resolvers = ns->parent;
2135 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2136
2137 /* process all pending input messages */
2138 while (1) {
2139 /* read message received */
2140 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2141 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2142 break;
2143 }
2144
2145 /* message too big */
2146 if (buflen > resolvers->accepted_payload_size) {
2147 ns->counters->too_big++;
2148 continue;
2149 }
2150
2151 /* initializing variables */
2152 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2153
2154 /* read the query id from the packet (16 bits) */
2155 if (buf + 2 > bufend) {
2156 ns->counters->invalid++;
2157 continue;
2158 }
2159 query_id = resolv_response_get_query_id(buf);
2160
2161 /* search the query_id in the pending resolution tree */
2162 eb = eb32_lookup(&resolvers->query_ids, query_id);
2163 if (eb == NULL) {
2164 /* unknown query id means an outdated response and can be safely ignored */
2165 ns->counters->outdated++;
2166 continue;
2167 }
2168
2169 /* known query id means a resolution in progress */
2170 res = eb32_entry(eb, struct resolv_resolution, qid);
2171 /* number of responses received */
2172 res->nb_responses++;
2173
2174 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2175 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2176
2177 switch (dns_resp) {
2178 case RSLV_RESP_VALID:
2179 break;
2180
2181 case RSLV_RESP_INVALID:
2182 case RSLV_RESP_QUERY_COUNT_ERROR:
2183 case RSLV_RESP_WRONG_NAME:
2184 res->status = RSLV_STATUS_INVALID;
2185 ns->counters->invalid++;
2186 break;
2187
2188 case RSLV_RESP_NX_DOMAIN:
2189 res->status = RSLV_STATUS_NX;
2190 ns->counters->nx++;
2191 break;
2192
2193 case RSLV_RESP_REFUSED:
2194 res->status = RSLV_STATUS_REFUSED;
2195 ns->counters->refused++;
2196 break;
2197
2198 case RSLV_RESP_ANCOUNT_ZERO:
2199 res->status = RSLV_STATUS_OTHER;
2200 ns->counters->any_err++;
2201 break;
2202
2203 case RSLV_RESP_CNAME_ERROR:
2204 res->status = RSLV_STATUS_OTHER;
2205 ns->counters->cname_error++;
2206 break;
2207
2208 case RSLV_RESP_TRUNCATED:
2209 res->status = RSLV_STATUS_OTHER;
2210 ns->counters->truncated++;
2211 break;
2212
2213 case RSLV_RESP_NO_EXPECTED_RECORD:
2214 case RSLV_RESP_ERROR:
2215 case RSLV_RESP_INTERNAL:
2216 res->status = RSLV_STATUS_OTHER;
2217 ns->counters->other++;
2218 break;
2219 }
2220
2221 /* Wait all nameservers response to handle errors */
2222 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2223 continue;
2224
2225 /* Process error codes */
2226 if (dns_resp != RSLV_RESP_VALID) {
2227 if (res->prefered_query_type != res->query_type) {
2228 /* The fallback on the query type was already performed,
2229 * so check the try counter. If it falls to 0, we can
2230 * report an error. Else, wait the next attempt. */
2231 if (!res->try)
2232 goto report_res_error;
2233 }
2234 else {
2235 /* Fallback from A to AAAA or the opposite and re-send
2236 * the resolution immediately. try counter is not
2237 * decremented. */
2238 if (res->prefered_query_type == DNS_RTYPE_A) {
2239 res->query_type = DNS_RTYPE_AAAA;
2240 resolv_send_query(res);
2241 }
2242 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2243 res->query_type = DNS_RTYPE_A;
2244 resolv_send_query(res);
2245 }
2246 }
2247 continue;
2248 }
2249
2250 /* Now let's check the query's dname corresponds to the one we
2251 * sent. We can check only the first query of the list. We send
Willy Tarreau51128f82021-10-19 11:17:33 +02002252 * one query at a time so we get one query in the response.
2253 */
2254 if (!LIST_ISEMPTY(&res->response.query_list)) {
2255 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
2256 LIST_DEL_INIT(&query->list);
2257 if (resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
2258 dns_resp = RSLV_RESP_WRONG_NAME;
2259 ns->counters->other++;
2260 goto report_res_error;
2261 }
Emeric Brunc9437992021-02-12 19:42:55 +01002262 }
2263
2264 /* So the resolution succeeded */
2265 res->status = RSLV_STATUS_VALID;
2266 res->last_valid = now_ms;
2267 ns->counters->valid++;
2268 goto report_res_success;
2269
2270 report_res_error:
Emeric Brun43839d02021-06-10 15:25:25 +02002271 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002272 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002273 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2274 if (!keep_answer_items)
2275 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002276 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002277 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002278 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002279 continue;
2280
2281 report_res_success:
2282 /* Only the 1rst requester s managed by the server, others are
2283 * from the cache */
2284 tmpcounters = ns->counters;
2285 list_for_each_entry(req, &res->requesters, list) {
2286 struct server *s = objt_server(req->owner);
2287
2288 if (s)
2289 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2290 req->requester_cb(req, tmpcounters);
2291 if (s)
2292 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2293 tmpcounters = NULL;
2294 }
2295
2296 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002297 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002298 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002299 continue;
2300 }
2301 resolv_update_resolvers_timeout(resolvers);
2302 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2303
2304 return buflen;
2305}
2306
2307/* Processes DNS resolution. First, it checks the active list to detect expired
2308 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2309 * checks the wait list to trigger new resolutions.
2310 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002311static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002312{
2313 struct resolvers *resolvers = context;
2314 struct resolv_resolution *res, *resback;
2315 int exp;
2316
2317 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2318
Willy Tarreau20751652021-10-18 16:46:38 +02002319 /* Handle all expired resolutions from the active list. Elements that
2320 * need to be removed will in fact be moved to the death_row. Other
2321 * ones will be handled normally.
2322 */
2323
2324 init_aborted_resolutions();
2325 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2326 while (&res->list != &resolvers->resolutions.curr) {
2327 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2328
Christopher Faulet0efc0992021-03-11 18:09:53 +01002329 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002330 abort_resolution(res);
2331 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002332 continue;
2333 }
2334
Emeric Brunc9437992021-02-12 19:42:55 +01002335 /* When we find the first resolution in the future, then we can
2336 * stop here */
2337 exp = tick_add(res->last_query, resolvers->timeout.retry);
2338 if (!tick_is_expired(exp, now_ms))
2339 break;
2340
2341 /* If current resolution has been tried too many times and
2342 * finishes in timeout we update its status and remove it from
2343 * the list */
2344 if (!res->try) {
2345 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002346 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002347
2348 /* Notify the result to the requesters */
2349 if (!res->nb_responses)
2350 res->status = RSLV_STATUS_TIMEOUT;
2351 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002352 keep_answer_items |= req->requester_error_cb(req, res->status);
2353 if (!keep_answer_items)
2354 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002355
2356 /* Clean up resolution info and remove it from the
2357 * current list */
2358 resolv_reset_resolution(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002359
2360 /* subsequent entries might have been deleted here */
2361 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002362 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002363 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreau20751652021-10-18 16:46:38 +02002364 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002365 }
2366 else {
2367 /* Otherwise resend the DNS query and requeue the resolution */
2368 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2369 /* No response received (a real timeout) or fallback already done */
2370 res->query_type = res->prefered_query_type;
2371 res->try--;
2372 }
2373 else {
2374 /* Fallback from A to AAAA or the opposite and re-send
2375 * the resolution immediately. try counter is not
2376 * decremented. */
2377 if (res->prefered_query_type == DNS_RTYPE_A)
2378 res->query_type = DNS_RTYPE_AAAA;
2379 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2380 res->query_type = DNS_RTYPE_A;
2381 else
2382 res->try--;
2383 }
2384 resolv_send_query(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002385 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2386 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002387 }
2388 }
2389
2390 /* Handle all resolutions in the wait list */
2391 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002392 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002393 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002394 continue;
2395 }
2396
Emeric Brunc9437992021-02-12 19:42:55 +01002397 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2398 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2399 continue;
2400
2401 if (resolv_run_resolution(res) != 1) {
2402 res->last_resolution = now_ms;
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002403 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002404 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002405 }
2406 }
2407
Willy Tarreau20751652021-10-18 16:46:38 +02002408 /* now we can purge all queued deletions */
2409 free_aborted_resolutions();
2410
Emeric Brunc9437992021-02-12 19:42:55 +01002411 resolv_update_resolvers_timeout(resolvers);
2412 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2413 return t;
2414}
2415
2416/* Release memory allocated by DNS */
2417static void resolvers_deinit(void)
2418{
2419 struct resolvers *resolvers, *resolversback;
2420 struct dns_nameserver *ns, *nsback;
2421 struct resolv_resolution *res, *resback;
2422 struct resolv_requester *req, *reqback;
2423 struct resolv_srvrq *srvrq, *srvrqback;
2424
Willy Tarreau20751652021-10-18 16:46:38 +02002425 init_aborted_resolutions();
Emeric Brunc9437992021-02-12 19:42:55 +01002426 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2427 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2428 free(ns->id);
2429 free((char *)ns->conf.file);
2430 if (ns->dgram) {
2431 if (ns->dgram->conn.t.sock.fd != -1) {
2432 fd_delete(ns->dgram->conn.t.sock.fd);
2433 close(ns->dgram->conn.t.sock.fd);
2434 }
2435 if (ns->dgram->ring_req)
2436 ring_free(ns->dgram->ring_req);
2437 free(ns->dgram);
2438 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002439 if (ns->stream) {
2440 if (ns->stream->ring_req)
2441 ring_free(ns->stream->ring_req);
2442 if (ns->stream->task_req)
2443 task_destroy(ns->stream->task_req);
2444 if (ns->stream->task_rsp)
2445 task_destroy(ns->stream->task_rsp);
2446 free(ns->stream);
2447 }
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002448 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002449 EXTRA_COUNTERS_FREE(ns->extra_counters);
2450 free(ns);
2451 }
2452
2453 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2454 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002455 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002456 pool_free(resolv_requester_pool, req);
2457 }
Willy Tarreau20751652021-10-18 16:46:38 +02002458 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002459 }
2460
2461 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2462 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002463 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002464 pool_free(resolv_requester_pool, req);
2465 }
Willy Tarreau20751652021-10-18 16:46:38 +02002466 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002467 }
2468
2469 free(resolvers->id);
2470 free((char *)resolvers->conf.file);
2471 task_destroy(resolvers->t);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002472 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002473 free(resolvers);
2474 }
2475
2476 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2477 free(srvrq->name);
2478 free(srvrq->hostname_dn);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002479 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002480 free(srvrq);
2481 }
Willy Tarreau20751652021-10-18 16:46:38 +02002482
2483 free_aborted_resolutions();
Emeric Brunc9437992021-02-12 19:42:55 +01002484}
2485
2486/* Finalizes the DNS configuration by allocating required resources and checking
2487 * live parameters.
2488 * Returns 0 on success, ERR_* flags otherwise.
2489 */
2490static int resolvers_finalize_config(void)
2491{
2492 struct resolvers *resolvers;
2493 struct proxy *px;
2494 int err_code = 0;
2495
Willy Tarreau20751652021-10-18 16:46:38 +02002496 init_aborted_resolutions();
2497
Emeric Brunc9437992021-02-12 19:42:55 +01002498 /* allocate pool of resolution per resolvers */
2499 list_for_each_entry(resolvers, &sec_resolvers, list) {
2500 struct dns_nameserver *ns;
2501 struct task *t;
2502
2503 /* Check if we can create the socket with nameservers info */
2504 list_for_each_entry(ns, &resolvers->nameservers, list) {
2505 int fd;
2506
2507 if (ns->dgram) {
2508 /* Check nameserver info */
2509 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
2510 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2511 resolvers->id, ns->id);
2512 err_code |= (ERR_ALERT|ERR_ABORT);
2513 continue;
2514 }
2515 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
2516 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2517 resolvers->id, ns->id);
2518 close(fd);
2519 err_code |= (ERR_ALERT|ERR_ABORT);
2520 continue;
2521 }
2522 close(fd);
2523 }
2524 }
2525
2526 /* Create the task associated to the resolvers section */
2527 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2528 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
2529 err_code |= (ERR_ALERT|ERR_ABORT);
2530 goto err;
2531 }
2532
2533 /* Update task's parameters */
2534 t->process = process_resolvers;
2535 t->context = resolvers;
2536 resolvers->t = t;
2537 task_wakeup(t, TASK_WOKEN_INIT);
2538 }
2539
2540 for (px = proxies_list; px; px = px->next) {
2541 struct server *srv;
2542
2543 for (srv = px->srv; srv; srv = srv->next) {
2544 struct resolvers *resolvers;
2545
2546 if (!srv->resolvers_id)
2547 continue;
2548
2549 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
2550 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2551 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2552 err_code |= (ERR_ALERT|ERR_ABORT);
2553 continue;
2554 }
2555 srv->resolvers = resolvers;
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002556 srv->srvrq_check = NULL;
2557 if (srv->srvrq) {
2558 if (!srv->srvrq->resolvers) {
2559 srv->srvrq->resolvers = srv->resolvers;
2560 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2561 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2562 proxy_type_str(px), px->id, srv->id);
2563 err_code |= (ERR_ALERT|ERR_ABORT);
2564 continue;
2565 }
2566 }
Emeric Brunc9437992021-02-12 19:42:55 +01002567
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002568 srv->srvrq_check = task_new(MAX_THREADS_MASK);
2569 if (!srv->srvrq_check) {
2570 ha_alert("config: %s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002571 proxy_type_str(px), px->id, srv->id);
2572 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002573 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002574 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002575 srv->srvrq_check->process = resolv_srvrq_expire_task;
2576 srv->srvrq_check->context = srv;
2577 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002578 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002579 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +01002580 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2581 proxy_type_str(px), px->id, srv->id);
2582 err_code |= (ERR_ALERT|ERR_ABORT);
2583 continue;
2584 }
2585 }
2586 }
2587
2588 if (err_code & (ERR_ALERT|ERR_ABORT))
2589 goto err;
2590
Willy Tarreau20751652021-10-18 16:46:38 +02002591 free_aborted_resolutions();
Emeric Brunc9437992021-02-12 19:42:55 +01002592 return err_code;
2593 err:
Willy Tarreau20751652021-10-18 16:46:38 +02002594 free_aborted_resolutions();
Emeric Brunc9437992021-02-12 19:42:55 +01002595 resolvers_deinit();
2596 return err_code;
2597
2598}
2599
2600static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2601 struct dns_nameserver *ns,
2602 struct field *stats, size_t stats_count,
2603 struct list *stat_modules)
2604{
2605 struct appctx *appctx = __objt_appctx(si->end);
2606 struct channel *rep = si_ic(si);
2607 struct stats_module *mod;
2608 size_t idx = 0;
2609
2610 memset(stats, 0, sizeof(struct field) * stats_count);
2611
2612 list_for_each_entry(mod, stat_modules, list) {
2613 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2614
2615 mod->fill_stats(counters, stats + idx);
2616 idx += mod->stats_count;
2617 }
2618
2619 if (!stats_dump_one_line(stats, idx, appctx))
2620 return 0;
2621
2622 if (!stats_putchk(rep, NULL, &trash))
2623 goto full;
2624
2625 return 1;
2626
2627 full:
2628 si_rx_room_rdy(si);
2629 return 0;
2630}
2631
2632/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2633 * as a pointer to the current nameserver.
2634 */
2635int stats_dump_resolvers(struct stream_interface *si,
2636 struct field *stats, size_t stats_count,
2637 struct list *stat_modules)
2638{
2639 struct appctx *appctx = __objt_appctx(si->end);
2640 struct channel *rep = si_ic(si);
2641 struct resolvers *resolver = appctx->ctx.stats.obj1;
2642 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2643
2644 if (!resolver)
2645 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2646
2647 /* dump resolvers */
2648 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2649 appctx->ctx.stats.obj1 = resolver;
2650
2651 ns = appctx->ctx.stats.obj2 ?
2652 appctx->ctx.stats.obj2 :
2653 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2654
2655 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2656 appctx->ctx.stats.obj2 = ns;
2657
2658 if (buffer_almost_full(&rep->buf))
2659 goto full;
2660
2661 if (!stats_dump_resolv_to_buffer(si, ns,
2662 stats, stats_count,
2663 stat_modules)) {
2664 return 0;
2665 }
2666 }
2667
2668 appctx->ctx.stats.obj2 = NULL;
2669 }
2670
2671 return 1;
2672
2673 full:
2674 si_rx_room_blk(si);
2675 return 0;
2676}
2677
2678void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2679{
2680 struct resolvers *resolvers;
2681 struct dns_nameserver *ns;
2682 struct stats_module *mod;
2683 void *counters;
2684
2685 list_for_each_entry(mod, stat_modules, list) {
2686 if (!mod->clearable && !clrall)
2687 continue;
2688
2689 list_for_each_entry(resolvers, &sec_resolvers, list) {
2690 list_for_each_entry(ns, &resolvers->nameservers, list) {
2691 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2692 memcpy(counters, mod->counters, mod->counters_size);
2693 }
2694 }
2695 }
2696
2697}
2698
2699int resolv_allocate_counters(struct list *stat_modules)
2700{
2701 struct stats_module *mod;
2702 struct resolvers *resolvers;
2703 struct dns_nameserver *ns;
2704
2705 list_for_each_entry(resolvers, &sec_resolvers, list) {
2706 list_for_each_entry(ns, &resolvers->nameservers, list) {
2707 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2708 alloc_failed);
2709
2710 list_for_each_entry(mod, stat_modules, list) {
2711 EXTRA_COUNTERS_ADD(mod,
2712 ns->extra_counters,
2713 mod->counters,
2714 mod->counters_size);
2715 }
2716
2717 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2718
2719 list_for_each_entry(mod, stat_modules, list) {
2720 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2721 mod->counters, mod->counters_size);
2722
2723 /* Store the ns counters pointer */
2724 if (strcmp(mod->name, "dns") == 0) {
2725 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2726 ns->counters->id = ns->id;
2727 ns->counters->pid = resolvers->id;
2728 }
2729 }
2730 }
2731 }
2732
2733 return 1;
2734
2735alloc_failed:
2736 return 0;
2737}
2738
2739/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2740static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2741{
2742 struct resolvers *presolvers;
2743
2744 if (*args[2]) {
2745 list_for_each_entry(presolvers, &sec_resolvers, list) {
2746 if (strcmp(presolvers->id, args[2]) == 0) {
2747 appctx->ctx.cli.p0 = presolvers;
2748 break;
2749 }
2750 }
2751 if (appctx->ctx.cli.p0 == NULL)
2752 return cli_err(appctx, "Can't find that resolvers section\n");
2753 }
2754 return 0;
2755}
2756
2757/* Dumps counters from all resolvers section and associated name servers. It
2758 * returns 0 if the output buffer is full and it needs to be called again,
2759 * otherwise non-zero. It may limit itself to the resolver pointed to by
2760 * <cli.p0> if it's not null.
2761 */
2762static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2763{
2764 struct stream_interface *si = appctx->owner;
2765 struct resolvers *resolvers;
2766 struct dns_nameserver *ns;
2767
2768 chunk_reset(&trash);
2769
2770 switch (appctx->st2) {
2771 case STAT_ST_INIT:
2772 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2773 /* fall through */
2774
2775 case STAT_ST_LIST:
2776 if (LIST_ISEMPTY(&sec_resolvers)) {
2777 chunk_appendf(&trash, "No resolvers found\n");
2778 }
2779 else {
2780 list_for_each_entry(resolvers, &sec_resolvers, list) {
2781 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2782 continue;
2783
2784 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2785 list_for_each_entry(ns, &resolvers->nameservers, list) {
2786 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2787 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2788 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2789 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2790 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2791 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2792 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2793 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2794 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2795 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2796 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2797 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2798 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2799 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2800 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2801 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
2802 }
2803 chunk_appendf(&trash, "\n");
2804 }
2805 }
2806
2807 /* display response */
2808 if (ci_putchk(si_ic(si), &trash) == -1) {
2809 /* let's try again later from this session. We add ourselves into
2810 * this session's users so that it can remove us upon termination.
2811 */
2812 si_rx_room_blk(si);
2813 return 0;
2814 }
2815 /* fall through */
2816
2817 default:
2818 appctx->st2 = STAT_ST_FIN;
2819 return 1;
2820 }
2821}
2822
2823/* register cli keywords */
2824static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002825 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002826 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2827 {{},}
2828 }
2829};
2830
2831INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2832
2833/*
2834 * Prepare <rule> for hostname resolution.
2835 * Returns -1 in case of any allocation failure, 0 if not.
2836 * On error, a global failure counter is also incremented.
2837 */
Willy Tarreaua13a6102021-10-14 08:11:48 +02002838static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002839{
2840 char *hostname_dn;
Willy Tarreaua13a6102021-10-14 08:11:48 +02002841 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002842 struct buffer *tmp = get_trash_chunk();
2843
2844 if (!hostname)
2845 return 0;
2846
Emeric Brunc9437992021-02-12 19:42:55 +01002847 hostname_dn = tmp->area;
Willy Tarreauc1c765f2021-10-14 07:49:49 +02002848 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002849 hostname_dn, tmp->size);
2850 if (hostname_dn_len == -1)
2851 goto err;
2852
2853
2854 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2855 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2856 if (!stream->resolv_ctx.hostname_dn)
2857 goto err;
2858
2859 return 0;
2860
2861 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002862 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002863 resolv_failed_resolutions += 1;
2864 return -1;
2865}
2866
2867
2868/*
2869 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2870 */
2871enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2872 struct session *sess, struct stream *s, int flags)
2873{
2874 struct resolv_resolution *resolution;
2875 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002876 struct resolv_requester *req;
2877 struct resolvers *resolvers;
2878 struct resolv_resolution *res;
2879 int exp, locked = 0;
2880 enum act_return ret = ACT_RET_CONT;
2881
2882 resolvers = rule->arg.resolv.resolvers;
2883
Willy Tarreau20751652021-10-18 16:46:38 +02002884 init_aborted_resolutions();
2885
Emeric Brunc9437992021-02-12 19:42:55 +01002886 /* we have a response to our DNS resolution */
2887 use_cache:
2888 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2889 resolution = s->resolv_ctx.requester->resolution;
2890 if (!locked) {
2891 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2892 locked = 1;
2893 }
2894
2895 if (resolution->step == RSLV_STEP_RUNNING)
2896 goto yield;
2897 if (resolution->step == RSLV_STEP_NONE) {
2898 /* We update the variable only if we have a valid response. */
2899 if (resolution->status == RSLV_STATUS_VALID) {
2900 struct sample smp;
2901 short ip_sin_family = 0;
2902 void *ip = NULL;
2903
2904 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2905 0, &ip, &ip_sin_family, NULL);
2906
2907 switch (ip_sin_family) {
2908 case AF_INET:
2909 smp.data.type = SMP_T_IPV4;
2910 memcpy(&smp.data.u.ipv4, ip, 4);
2911 break;
2912 case AF_INET6:
2913 smp.data.type = SMP_T_IPV6;
2914 memcpy(&smp.data.u.ipv6, ip, 16);
2915 break;
2916 default:
2917 ip = NULL;
2918 }
2919
2920 if (ip) {
2921 smp.px = px;
2922 smp.sess = sess;
2923 smp.strm = s;
2924
2925 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2926 }
2927 }
2928 }
2929
2930 goto release_requester;
2931 }
2932
2933 /* need to configure and start a new DNS resolution */
2934 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2935 if (smp == NULL)
2936 goto end;
2937
Willy Tarreaua13a6102021-10-14 08:11:48 +02002938 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002939 goto end; /* on error, ignore the action */
2940
2941 s->resolv_ctx.parent = rule;
2942
2943 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2944 locked = 1;
2945
2946 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2947
2948 /* Check if there is a fresh enough response in the cache of our associated resolution */
2949 req = s->resolv_ctx.requester;
2950 if (!req || !req->resolution)
2951 goto release_requester; /* on error, ignore the action */
2952 res = req->resolution;
2953
2954 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2955 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2956 && !tick_is_expired(exp, now_ms)) {
2957 goto use_cache;
2958 }
2959
2960 resolv_trigger_resolution(s->resolv_ctx.requester);
2961
2962 yield:
2963 if (flags & ACT_OPT_FINAL)
2964 goto release_requester;
2965 ret = ACT_RET_YIELD;
2966
2967 end:
Willy Tarreau20751652021-10-18 16:46:38 +02002968 free_aborted_resolutions();
Emeric Brunc9437992021-02-12 19:42:55 +01002969 if (locked)
2970 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2971 return ret;
2972
2973 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002974 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002975 s->resolv_ctx.hostname_dn_len = 0;
2976 if (s->resolv_ctx.requester) {
Willy Tarreau33360872021-10-20 14:07:31 +02002977 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01002978 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2979 s->resolv_ctx.requester = NULL;
2980 }
2981 goto end;
2982}
2983
2984static void release_resolv_action(struct act_rule *rule)
2985{
2986 release_sample_expr(rule->arg.resolv.expr);
2987 free(rule->arg.resolv.varname);
2988 free(rule->arg.resolv.resolvers_id);
2989 free(rule->arg.resolv.opts);
2990}
2991
2992
2993/* parse "do-resolve" action
2994 * This action takes the following arguments:
2995 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
2996 *
2997 * - <varName> is the variable name where the result of the DNS resolution will be stored
2998 * (mandatory)
2999 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3000 * (mandatory)
3001 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3002 * (optional), defaults to ipv6
3003 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3004 */
3005enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3006{
3007 int cur_arg;
3008 struct sample_expr *expr;
3009 unsigned int where;
3010 const char *beg, *end;
3011
3012 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3013 cur_arg = *orig_arg - 1;
3014
3015 /* locate varName, which is mandatory */
3016 beg = strchr(args[cur_arg], '(');
3017 if (beg == NULL)
3018 goto do_resolve_parse_error;
3019 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3020 end = strchr(beg, ',');
3021 if (end == NULL)
3022 goto do_resolve_parse_error;
3023 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3024 if (rule->arg.resolv.varname == NULL)
3025 goto do_resolve_parse_error;
3026
3027
3028 /* locate resolversSectionName, which is mandatory.
3029 * Since next parameters are optional, the delimiter may be comma ','
3030 * or closing parenthesis ')'
3031 */
3032 beg = end + 1;
3033 end = strchr(beg, ',');
3034 if (end == NULL)
3035 end = strchr(beg, ')');
3036 if (end == NULL)
3037 goto do_resolve_parse_error;
3038 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3039 if (rule->arg.resolv.resolvers_id == NULL)
3040 goto do_resolve_parse_error;
3041
3042
3043 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3044 if (rule->arg.resolv.opts == NULL)
3045 goto do_resolve_parse_error;
3046
3047 /* Default priority is ipv6 */
3048 rule->arg.resolv.opts->family_prio = AF_INET6;
3049
3050 /* optional arguments accepted for now:
3051 * ipv4 or ipv6
3052 */
3053 while (*end != ')') {
3054 beg = end + 1;
3055 end = strchr(beg, ',');
3056 if (end == NULL)
3057 end = strchr(beg, ')');
3058 if (end == NULL)
3059 goto do_resolve_parse_error;
3060
3061 if (strncmp(beg, "ipv4", end - beg) == 0) {
3062 rule->arg.resolv.opts->family_prio = AF_INET;
3063 }
3064 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3065 rule->arg.resolv.opts->family_prio = AF_INET6;
3066 }
3067 else {
3068 goto do_resolve_parse_error;
3069 }
3070 }
3071
3072 cur_arg = cur_arg + 1;
3073
3074 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3075 if (!expr)
3076 goto do_resolve_parse_error;
3077
3078
3079 where = 0;
3080 if (px->cap & PR_CAP_FE)
3081 where |= SMP_VAL_FE_HRQ_HDR;
3082 if (px->cap & PR_CAP_BE)
3083 where |= SMP_VAL_BE_HRQ_HDR;
3084
3085 if (!(expr->fetch->val & where)) {
3086 memprintf(err,
3087 "fetch method '%s' extracts information from '%s', none of which is available here",
3088 args[cur_arg-1], sample_src_names(expr->fetch->use));
3089 free(expr);
3090 return ACT_RET_PRS_ERR;
3091 }
3092 rule->arg.resolv.expr = expr;
3093 rule->action = ACT_CUSTOM;
3094 rule->action_ptr = resolv_action_do_resolve;
3095 *orig_arg = cur_arg;
3096
3097 rule->check_ptr = check_action_do_resolve;
3098 rule->release_ptr = release_resolv_action;
3099
3100 return ACT_RET_PRS_OK;
3101
3102 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003103 ha_free(&rule->arg.resolv.varname);
3104 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003105 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3106 args[cur_arg]);
3107 return ACT_RET_PRS_ERR;
3108}
3109
3110static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003111 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003112 { /* END */ }
3113}};
3114
3115INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3116
3117static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003118 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003119 { /* END */ }
3120}};
3121
3122INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3123
3124/* Check an "http-request do-resolve" action.
3125 *
3126 * The function returns 1 in success case, otherwise, it returns 0 and err is
3127 * filled.
3128 */
3129int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3130{
3131 struct resolvers *resolvers = NULL;
3132
3133 if (rule->arg.resolv.resolvers_id == NULL) {
3134 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3135 return 0;
3136 }
3137
3138 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3139 if (resolvers == NULL) {
3140 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3141 return 0;
3142 }
3143 rule->arg.resolv.resolvers = resolvers;
3144
3145 return 1;
3146}
3147
3148void resolvers_setup_proxy(struct proxy *px)
3149{
3150 px->last_change = now.tv_sec;
3151 px->cap = PR_CAP_FE | PR_CAP_BE;
3152 px->maxconn = 0;
3153 px->conn_retries = 1;
3154 px->timeout.server = TICK_ETERNITY;
3155 px->timeout.client = TICK_ETERNITY;
3156 px->timeout.connect = TICK_ETERNITY;
3157 px->accept = NULL;
3158 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
3159 px->bind_proc = 0; /* will be filled by users */
3160}
3161
3162/*
3163 * Parse a <resolvers> section.
3164 * Returns the error code, 0 if OK, or any combination of :
3165 * - ERR_ABORT: must abort ASAP
3166 * - ERR_FATAL: we can continue parsing but not start the service
3167 * - ERR_WARN: a warning has been emitted
3168 * - ERR_ALERT: an alert has been emitted
3169 * Only the two first ones can stop processing, the two others are just
3170 * indicators.
3171 */
3172int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3173{
3174 const char *err;
3175 int err_code = 0;
3176 char *errmsg = NULL;
3177 struct proxy *p;
3178
3179 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3180 if (!*args[1]) {
3181 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3182 err_code |= ERR_ALERT | ERR_ABORT;
3183 goto out;
3184 }
3185
3186 err = invalid_char(args[1]);
3187 if (err) {
3188 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3189 file, linenum, *err, args[0], args[1]);
3190 err_code |= ERR_ALERT | ERR_ABORT;
3191 goto out;
3192 }
3193
3194 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3195 /* Error if two resolvers owns the same name */
3196 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3197 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3198 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3199 err_code |= ERR_ALERT | ERR_ABORT;
3200 }
3201 }
3202
3203 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3204 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3205 err_code |= ERR_ALERT | ERR_ABORT;
3206 goto out;
3207 }
3208
3209 /* allocate new proxy to tcp servers */
3210 p = calloc(1, sizeof *p);
3211 if (!p) {
3212 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3213 err_code |= ERR_ALERT | ERR_FATAL;
3214 goto out;
3215 }
3216
3217 init_new_proxy(p);
3218 resolvers_setup_proxy(p);
3219 p->parent = curr_resolvers;
3220 p->id = strdup(args[1]);
3221 p->conf.args.file = p->conf.file = strdup(file);
3222 p->conf.args.line = p->conf.line = linenum;
3223 curr_resolvers->px = p;
3224
3225 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003226 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003227 curr_resolvers->conf.file = strdup(file);
3228 curr_resolvers->conf.line = linenum;
3229 curr_resolvers->id = strdup(args[1]);
3230 curr_resolvers->query_ids = EB_ROOT;
3231 /* default maximum response size */
3232 curr_resolvers->accepted_payload_size = 512;
3233 /* default hold period for nx, other, refuse and timeout is 30s */
3234 curr_resolvers->hold.nx = 30000;
3235 curr_resolvers->hold.other = 30000;
3236 curr_resolvers->hold.refused = 30000;
3237 curr_resolvers->hold.timeout = 30000;
3238 curr_resolvers->hold.obsolete = 0;
3239 /* default hold period for valid is 10s */
3240 curr_resolvers->hold.valid = 10000;
3241 curr_resolvers->timeout.resolve = 1000;
3242 curr_resolvers->timeout.retry = 1000;
3243 curr_resolvers->resolve_retries = 3;
3244 LIST_INIT(&curr_resolvers->nameservers);
3245 LIST_INIT(&curr_resolvers->resolutions.curr);
3246 LIST_INIT(&curr_resolvers->resolutions.wait);
3247 HA_SPIN_INIT(&curr_resolvers->lock);
3248 }
3249 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3250 struct dns_nameserver *newnameserver = NULL;
3251 struct sockaddr_storage *sk;
3252 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003253 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003254
3255 if (!*args[2]) {
3256 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3257 file, linenum, args[0]);
3258 err_code |= ERR_ALERT | ERR_FATAL;
3259 goto out;
3260 }
3261
3262 err = invalid_char(args[1]);
3263 if (err) {
3264 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3265 file, linenum, *err, args[1]);
3266 err_code |= ERR_ALERT | ERR_FATAL;
3267 goto out;
3268 }
3269
3270 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3271 /* Error if two resolvers owns the same name */
3272 if (strcmp(newnameserver->id, args[1]) == 0) {
3273 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3274 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3275 err_code |= ERR_ALERT | ERR_FATAL;
3276 }
3277 }
3278
Emeric Brunc8f3e452021-04-07 16:04:54 +02003279 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3280 &errmsg, NULL, NULL, PA_O_RESOLVE | PA_O_PORT_OK | PA_O_PORT_MAND | PA_O_DGRAM | PA_O_STREAM | PA_O_DEFAULT_DGRAM);
Emeric Brunc9437992021-02-12 19:42:55 +01003281 if (!sk) {
3282 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3283 err_code |= ERR_ALERT | ERR_FATAL;
3284 goto out;
3285 }
3286
3287 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3288 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3289 err_code |= ERR_ALERT | ERR_ABORT;
3290 goto out;
3291 }
3292
Emeric Brunc8f3e452021-04-07 16:04:54 +02003293 if (proto && proto->ctrl_type == SOCK_STREAM) {
3294 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3295 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3296 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3297 err_code |= ERR_ABORT;
3298 goto out;
3299 }
3300
3301 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3302 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3303 err_code |= ERR_ALERT|ERR_ABORT;
3304 goto out;
3305 }
3306 }
3307 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003308 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3309 err_code |= ERR_ALERT | ERR_ABORT;
3310 goto out;
3311 }
3312
3313 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3314 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3315 err_code |= ERR_ALERT | ERR_ABORT;
3316 goto out;
3317 }
3318
3319 if ((newnameserver->id = strdup(args[1])) == NULL) {
3320 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3321 err_code |= ERR_ALERT | ERR_ABORT;
3322 goto out;
3323 }
3324
3325 newnameserver->parent = curr_resolvers;
3326 newnameserver->process_responses = resolv_process_responses;
3327 newnameserver->conf.line = linenum;
3328 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003329 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003330 }
3331 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3332 struct dns_nameserver *newnameserver = NULL;
3333 const char *whitespace = "\r\n\t ";
3334 char *resolv_line = NULL;
3335 int resolv_linenum = 0;
3336 FILE *f = NULL;
3337 char *address = NULL;
3338 struct sockaddr_storage *sk = NULL;
3339 struct protocol *proto;
3340 int duplicate_name = 0;
3341
3342 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3343 ha_alert("parsing [%s:%d] : out of memory.\n",
3344 file, linenum);
3345 err_code |= ERR_ALERT | ERR_FATAL;
3346 goto resolv_out;
3347 }
3348
3349 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3350 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3351 file, linenum);
3352 err_code |= ERR_ALERT | ERR_FATAL;
3353 goto resolv_out;
3354 }
3355
3356 sk = calloc(1, sizeof(*sk));
3357 if (sk == NULL) {
3358 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3359 resolv_linenum);
3360 err_code |= ERR_ALERT | ERR_FATAL;
3361 goto resolv_out;
3362 }
3363
3364 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3365 resolv_linenum++;
3366 if (strncmp(resolv_line, "nameserver", 10) != 0)
3367 continue;
3368
3369 address = strtok(resolv_line + 10, whitespace);
3370 if (address == resolv_line + 10)
3371 continue;
3372
3373 if (address == NULL) {
3374 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3375 resolv_linenum);
3376 err_code |= ERR_WARN;
3377 continue;
3378 }
3379
3380 duplicate_name = 0;
3381 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3382 if (strcmp(newnameserver->id, address) == 0) {
3383 ha_warning("Parsing [/etc/resolv.conf:%d] : generated name for /etc/resolv.conf nameserver '%s' conflicts with another nameserver (declared at %s:%d), it appears to be a duplicate and will be excluded.\n",
3384 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3385 err_code |= ERR_WARN;
3386 duplicate_name = 1;
3387 }
3388 }
3389
3390 if (duplicate_name)
3391 continue;
3392
3393 memset(sk, 0, sizeof(*sk));
3394 if (!str2ip2(address, sk, 1)) {
3395 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3396 resolv_linenum, address);
3397 err_code |= ERR_WARN;
3398 continue;
3399 }
3400
3401 set_host_port(sk, 53);
3402
3403 proto = protocol_by_family(sk->ss_family);
3404 if (!proto || !proto->connect) {
3405 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3406 resolv_linenum, address);
3407 err_code |= ERR_WARN;
3408 continue;
3409 }
3410
3411 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3412 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3413 err_code |= ERR_ALERT | ERR_FATAL;
3414 goto resolv_out;
3415 }
3416
3417 if (dns_dgram_init(newnameserver, sk) < 0) {
3418 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3419 err_code |= ERR_ALERT | ERR_FATAL;
3420 free(newnameserver);
3421 goto resolv_out;
3422 }
3423
3424 newnameserver->conf.file = strdup("/etc/resolv.conf");
3425 if (newnameserver->conf.file == NULL) {
3426 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3427 err_code |= ERR_ALERT | ERR_FATAL;
3428 free(newnameserver);
3429 goto resolv_out;
3430 }
3431
3432 newnameserver->id = strdup(address);
3433 if (newnameserver->id == NULL) {
3434 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3435 err_code |= ERR_ALERT | ERR_FATAL;
3436 free((char *)newnameserver->conf.file);
3437 free(newnameserver);
3438 goto resolv_out;
3439 }
3440
3441 newnameserver->parent = curr_resolvers;
3442 newnameserver->process_responses = resolv_process_responses;
3443 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003444 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003445 }
3446
3447resolv_out:
3448 free(sk);
3449 free(resolv_line);
3450 if (f != NULL)
3451 fclose(f);
3452 }
3453 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3454 const char *res;
3455 unsigned int time;
3456
3457 if (!*args[2]) {
3458 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3459 file, linenum, args[0]);
3460 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3461 err_code |= ERR_ALERT | ERR_FATAL;
3462 goto out;
3463 }
3464 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3465 if (res == PARSE_TIME_OVER) {
3466 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3467 file, linenum, args[1], args[0]);
3468 err_code |= ERR_ALERT | ERR_FATAL;
3469 goto out;
3470 }
3471 else if (res == PARSE_TIME_UNDER) {
3472 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3473 file, linenum, args[1], args[0]);
3474 err_code |= ERR_ALERT | ERR_FATAL;
3475 goto out;
3476 }
3477 else if (res) {
3478 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3479 file, linenum, *res, args[0]);
3480 err_code |= ERR_ALERT | ERR_FATAL;
3481 goto out;
3482 }
3483 if (strcmp(args[1], "nx") == 0)
3484 curr_resolvers->hold.nx = time;
3485 else if (strcmp(args[1], "other") == 0)
3486 curr_resolvers->hold.other = time;
3487 else if (strcmp(args[1], "refused") == 0)
3488 curr_resolvers->hold.refused = time;
3489 else if (strcmp(args[1], "timeout") == 0)
3490 curr_resolvers->hold.timeout = time;
3491 else if (strcmp(args[1], "valid") == 0)
3492 curr_resolvers->hold.valid = time;
3493 else if (strcmp(args[1], "obsolete") == 0)
3494 curr_resolvers->hold.obsolete = time;
3495 else {
3496 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3497 file, linenum, args[0], args[1]);
3498 err_code |= ERR_ALERT | ERR_FATAL;
3499 goto out;
3500 }
3501
3502 }
3503 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3504 int i = 0;
3505
3506 if (!*args[1]) {
3507 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3508 file, linenum, args[0]);
3509 err_code |= ERR_ALERT | ERR_FATAL;
3510 goto out;
3511 }
3512
3513 i = atoi(args[1]);
3514 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3515 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3516 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3517 err_code |= ERR_ALERT | ERR_FATAL;
3518 goto out;
3519 }
3520
3521 curr_resolvers->accepted_payload_size = i;
3522 }
3523 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3524 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3525 file, linenum, args[0]);
3526 err_code |= ERR_ALERT | ERR_FATAL;
3527 goto out;
3528 }
3529 else if (strcmp(args[0], "resolve_retries") == 0) {
3530 if (!*args[1]) {
3531 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3532 file, linenum, args[0]);
3533 err_code |= ERR_ALERT | ERR_FATAL;
3534 goto out;
3535 }
3536 curr_resolvers->resolve_retries = atoi(args[1]);
3537 }
3538 else if (strcmp(args[0], "timeout") == 0) {
3539 if (!*args[1]) {
3540 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3541 file, linenum, args[0]);
3542 err_code |= ERR_ALERT | ERR_FATAL;
3543 goto out;
3544 }
3545 else if (strcmp(args[1], "retry") == 0 ||
3546 strcmp(args[1], "resolve") == 0) {
3547 const char *res;
3548 unsigned int tout;
3549
3550 if (!*args[2]) {
3551 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3552 file, linenum, args[0], args[1]);
3553 err_code |= ERR_ALERT | ERR_FATAL;
3554 goto out;
3555 }
3556 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3557 if (res == PARSE_TIME_OVER) {
3558 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3559 file, linenum, args[2], args[0], args[1]);
3560 err_code |= ERR_ALERT | ERR_FATAL;
3561 goto out;
3562 }
3563 else if (res == PARSE_TIME_UNDER) {
3564 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3565 file, linenum, args[2], args[0], args[1]);
3566 err_code |= ERR_ALERT | ERR_FATAL;
3567 goto out;
3568 }
3569 else if (res) {
3570 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3571 file, linenum, *res, args[0], args[1]);
3572 err_code |= ERR_ALERT | ERR_FATAL;
3573 goto out;
3574 }
3575 if (args[1][2] == 't')
3576 curr_resolvers->timeout.retry = tout;
3577 else
3578 curr_resolvers->timeout.resolve = tout;
3579 }
3580 else {
3581 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3582 file, linenum, args[0], args[1]);
3583 err_code |= ERR_ALERT | ERR_FATAL;
3584 goto out;
3585 }
3586 }
3587 else if (*args[0] != 0) {
3588 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3589 err_code |= ERR_ALERT | ERR_FATAL;
3590 goto out;
3591 }
3592
3593 out:
3594 free(errmsg);
3595 return err_code;
3596}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003597int cfg_post_parse_resolvers()
3598{
3599 int err_code = 0;
3600 struct server *srv;
3601
3602 if (curr_resolvers) {
3603
3604 /* prepare forward server descriptors */
3605 if (curr_resolvers->px) {
3606 srv = curr_resolvers->px->srv;
3607 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003608 /* init ssl if needed */
3609 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3610 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3611 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3612 err_code |= ERR_ALERT | ERR_FATAL;
3613 break;
3614 }
3615 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003616 srv = srv->next;
3617 }
3618 }
3619 }
3620 curr_resolvers = NULL;
3621 return err_code;
3622}
Emeric Brunc9437992021-02-12 19:42:55 +01003623
Emeric Brun56fc5d92021-02-12 20:05:45 +01003624REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003625REGISTER_POST_DEINIT(resolvers_deinit);
3626REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);