blob: db20a074e0af3b02848d10a4875554c690ccda59 [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 */
Christopher Faulet7a3a5362021-11-02 16:25:05 +010056static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
Emeric Brunc9437992021-02-12 19:42:55 +010057static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
58struct resolvers *curr_resolvers = NULL;
59
60DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
61DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
62DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
63
64static unsigned int resolution_uuid = 1;
65unsigned int resolv_failed_resolutions = 0;
Willy Tarreau20751652021-10-18 16:46:38 +020066static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
67static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau33360872021-10-20 14:07:31 +020068static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet7a3a5362021-11-02 16:25:05 +010069static void enter_resolver_code();
70static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010071
72enum {
73 DNS_STAT_ID,
74 DNS_STAT_PID,
75 DNS_STAT_SENT,
76 DNS_STAT_SND_ERROR,
77 DNS_STAT_VALID,
78 DNS_STAT_UPDATE,
79 DNS_STAT_CNAME,
80 DNS_STAT_CNAME_ERROR,
81 DNS_STAT_ANY_ERR,
82 DNS_STAT_NX,
83 DNS_STAT_TIMEOUT,
84 DNS_STAT_REFUSED,
85 DNS_STAT_OTHER,
86 DNS_STAT_INVALID,
87 DNS_STAT_TOO_BIG,
88 DNS_STAT_TRUNCATED,
89 DNS_STAT_OUTDATED,
90 DNS_STAT_END,
91};
92
93static struct name_desc dns_stats[] = {
94 [DNS_STAT_ID] = { .name = "id", .desc = "ID" },
95 [DNS_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
96 [DNS_STAT_SENT] = { .name = "sent", .desc = "Sent" },
97 [DNS_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
98 [DNS_STAT_VALID] = { .name = "valid", .desc = "Valid" },
99 [DNS_STAT_UPDATE] = { .name = "update", .desc = "Update" },
100 [DNS_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
101 [DNS_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
102 [DNS_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
103 [DNS_STAT_NX] = { .name = "nx", .desc = "NX" },
104 [DNS_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
105 [DNS_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
106 [DNS_STAT_OTHER] = { .name = "other", .desc = "Other" },
107 [DNS_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
108 [DNS_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
109 [DNS_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
110 [DNS_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
111};
112
113static struct dns_counters dns_counters;
114
115static void dns_fill_stats(void *d, struct field *stats)
116{
117 struct dns_counters *counters = d;
118 stats[DNS_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
119 stats[DNS_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
120 stats[DNS_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
121 stats[DNS_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
122 stats[DNS_STAT_VALID] = mkf_u64(FN_GAUGE, counters->valid);
123 stats[DNS_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->update);
124 stats[DNS_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->cname);
125 stats[DNS_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->cname_error);
126 stats[DNS_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->any_err);
127 stats[DNS_STAT_NX] = mkf_u64(FN_GAUGE, counters->nx);
128 stats[DNS_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->timeout);
129 stats[DNS_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->refused);
130 stats[DNS_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->other);
131 stats[DNS_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->invalid);
132 stats[DNS_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->too_big);
133 stats[DNS_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->truncated);
134 stats[DNS_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->outdated);
135}
136
137static struct stats_module dns_stats_module = {
138 .name = "dns",
139 .domain_flags = STATS_DOMAIN_DNS << STATS_DOMAIN,
140 .fill_stats = dns_fill_stats,
141 .stats = dns_stats,
142 .stats_count = DNS_STAT_END,
143 .counters = &dns_counters,
144 .counters_size = sizeof(dns_counters),
145 .clearable = 0,
146};
147
148INITCALL1(STG_REGISTER, stats_register_module, &dns_stats_module);
149
150/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
151 * no match is found.
152 */
153struct resolvers *find_resolvers_by_id(const char *id)
154{
155 struct resolvers *res;
156
157 list_for_each_entry(res, &sec_resolvers, list) {
158 if (strcmp(res->id, id) == 0)
159 return res;
160 }
161 return NULL;
162}
163
164/* Compare hostnames in a case-insensitive way .
165 * Returns 0 if they are the same, non-zero otherwise
166 */
167static __inline int resolv_hostname_cmp(const char *name1, const char *name2, int len)
168{
169 int i;
170
171 for (i = 0; i < len; i++)
172 if (tolower((unsigned char)name1[i]) != tolower((unsigned char)name2[i]))
173 return -1;
174 return 0;
175}
176
177/* Returns a pointer on the SRV request matching the name <name> for the proxy
178 * <px>. NULL is returned if no match is found.
179 */
180struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
181{
182 struct resolv_srvrq *srvrq;
183
184 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
185 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
186 return srvrq;
187 }
188 return NULL;
189}
190
191/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
192 * NULL if an error occurred. */
193struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
194{
195 struct proxy *px = srv->proxy;
196 struct resolv_srvrq *srvrq = NULL;
197 int fqdn_len, hostname_dn_len;
198
199 fqdn_len = strlen(fqdn);
Willy Tarreauc1c765f2021-10-14 07:49:49 +0200200 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100201 trash.size);
202 if (hostname_dn_len == -1) {
203 ha_alert("config : %s '%s', server '%s': failed to parse FQDN '%s'\n",
204 proxy_type_str(px), px->id, srv->id, fqdn);
205 goto err;
206 }
207
208 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
209 ha_alert("config : %s '%s', server '%s': out of memory\n",
210 proxy_type_str(px), px->id, srv->id);
211 goto err;
212 }
213 srvrq->obj_type = OBJ_TYPE_SRVRQ;
214 srvrq->proxy = px;
215 srvrq->name = strdup(fqdn);
216 srvrq->hostname_dn = strdup(trash.area);
217 srvrq->hostname_dn_len = hostname_dn_len;
218 if (!srvrq->name || !srvrq->hostname_dn) {
219 ha_alert("config : %s '%s', server '%s': out of memory\n",
220 proxy_type_str(px), px->id, srv->id);
221 goto err;
222 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200223 LIST_INIT(&srvrq->attached_servers);
224 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200225 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100226 return srvrq;
227
228 err:
229 if (srvrq) {
230 free(srvrq->name);
231 free(srvrq->hostname_dn);
232 free(srvrq);
233 }
234 return NULL;
235}
236
237
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100238/* finds and return the SRV answer item associated to a requester (whose type is 'server').
239 *
240 * returns NULL in case of error or not found.
241 */
242struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
243{
244 struct resolv_resolution *res;
245 struct resolv_answer_item *item;
246 struct server *srv;
247
248 if (!requester)
249 return NULL;
250
251 if ((srv = objt_server(requester->owner)) == NULL)
252 return NULL;
253 /* check if the server is managed by a SRV record */
254 if (srv->srvrq == NULL)
255 return NULL;
256
257 res = srv->srvrq->requester->resolution;
258 /* search an ANSWER record whose target points to the server's hostname and whose port is
259 * the same as server's svc_port */
260 list_for_each_entry(item, &res->response.answer_list, list) {
Willy Tarreau20a02372021-10-14 22:52:04 +0200261 if (resolv_hostname_cmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100262 (srv->svc_port == item->port))
263 return item;
264 }
265
266 return NULL;
267}
268
Emeric Brunc9437992021-02-12 19:42:55 +0100269/* 2 bytes random generator to generate DNS query ID */
270static inline uint16_t resolv_rnd16(void)
271{
272 if (!resolv_query_id_seed)
273 resolv_query_id_seed = now_ms;
274 resolv_query_id_seed ^= resolv_query_id_seed << 13;
275 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
276 resolv_query_id_seed ^= resolv_query_id_seed << 17;
277 return resolv_query_id_seed;
278}
279
280
281static inline int resolv_resolution_timeout(struct resolv_resolution *res)
282{
283 return res->resolvers->timeout.resolve;
284}
285
286/* Updates a resolvers' task timeout for next wake up and queue it */
287static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
288{
289 struct resolv_resolution *res;
290 int next;
291
292 next = tick_add(now_ms, resolvers->timeout.resolve);
293 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
294 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
295 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
296 }
297
298 list_for_each_entry(res, &resolvers->resolutions.wait, list)
299 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
300
301 resolvers->t->expire = next;
302 task_queue(resolvers->t);
303}
304
305/* Forges a DNS query. It needs the following information from the caller:
306 * - <query_id> : the DNS query id corresponding to this query
307 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
308 * - <hostname_dn> : hostname in domain name format
309 * - <hostname_dn_len> : length of <hostname_dn>
310 *
311 * To store the query, the caller must pass a buffer <buf> and its size
312 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
313 * too short.
314 */
315static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
316 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
317{
318 struct dns_header dns_hdr;
319 struct dns_question qinfo;
320 struct dns_additional_record edns;
321 char *p = buf;
322
323 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
324 return -1;
325
326 memset(buf, 0, bufsize);
327
328 /* Set dns query headers */
329 dns_hdr.id = (unsigned short) htons(query_id);
330 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
331 dns_hdr.qdcount = htons(1); /* 1 question */
332 dns_hdr.ancount = 0;
333 dns_hdr.nscount = 0;
334 dns_hdr.arcount = htons(1);
335 memcpy(p, &dns_hdr, sizeof(dns_hdr));
336 p += sizeof(dns_hdr);
337
338 /* Set up query hostname */
339 memcpy(p, hostname_dn, hostname_dn_len);
340 p += hostname_dn_len;
341 *p++ = 0;
342
343 /* Set up query info (type and class) */
344 qinfo.qtype = htons(query_type);
345 qinfo.qclass = htons(DNS_RCLASS_IN);
346 memcpy(p, &qinfo, sizeof(qinfo));
347 p += sizeof(qinfo);
348
349 /* Set the DNS extension */
350 edns.name = 0;
351 edns.type = htons(DNS_RTYPE_OPT);
352 edns.udp_payload_size = htons(accepted_payload_size);
353 edns.extension = 0;
354 edns.data_length = 0;
355 memcpy(p, &edns, sizeof(edns));
356 p += sizeof(edns);
357
358 return (p - buf);
359}
360
361/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
362 * success, -1 otherwise.
363 */
364static int resolv_send_query(struct resolv_resolution *resolution)
365{
366 struct resolvers *resolvers = resolution->resolvers;
367 struct dns_nameserver *ns;
368 int len;
369
370 /* Update resolution */
371 resolution->nb_queries = 0;
372 resolution->nb_responses = 0;
373 resolution->last_query = now_ms;
374
375 len = resolv_build_query(resolution->query_id, resolution->query_type,
376 resolvers->accepted_payload_size,
377 resolution->hostname_dn, resolution->hostname_dn_len,
378 trash.area, trash.size);
379
380 list_for_each_entry(ns, &resolvers->nameservers, list) {
381 if (len < 0) {
382 ns->counters->snd_error++;
383 continue;
384 }
385
386 if (dns_send_nameserver(ns, trash.area, len) < 0)
387 ns->counters->snd_error++;
388 else
389 resolution->nb_queries++;
390 }
391
392 /* Push the resolution at the end of the active list */
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200393 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200394 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100395 return 0;
396}
397
398/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
399 * skipped and -1 if an error occurred.
400 */
401static int
402resolv_run_resolution(struct resolv_resolution *resolution)
403{
404 struct resolvers *resolvers = resolution->resolvers;
405 int query_id, i;
406
407 /* Avoid sending requests for resolutions that don't yet have an
408 * hostname, ie resolutions linked to servers that do not yet have an
409 * fqdn */
410 if (!resolution->hostname_dn)
411 return 0;
412
413 /* Check if a resolution has already been started for this server return
414 * directly to avoid resolution pill up. */
415 if (resolution->step != RSLV_STEP_NONE)
416 return 0;
417
418 /* Generates a new query id. We try at most 100 times to find a free
419 * query id */
420 for (i = 0; i < 100; ++i) {
421 query_id = resolv_rnd16();
422 if (!eb32_lookup(&resolvers->query_ids, query_id))
423 break;
424 query_id = -1;
425 }
426 if (query_id == -1) {
427 send_log(NULL, LOG_NOTICE,
428 "could not generate a query id for %s, in resolvers %s.\n",
429 resolution->hostname_dn, resolvers->id);
430 return -1;
431 }
432
433 /* Update resolution parameters */
434 resolution->query_id = query_id;
435 resolution->qid.key = query_id;
436 resolution->step = RSLV_STEP_RUNNING;
437 resolution->query_type = resolution->prefered_query_type;
438 resolution->try = resolvers->resolve_retries;
439 eb32_insert(&resolvers->query_ids, &resolution->qid);
440
441 /* Send the DNS query */
442 resolution->try -= 1;
443 resolv_send_query(resolution);
444 return 1;
445}
446
447/* Performs a name resolution for the requester <req> */
448void resolv_trigger_resolution(struct resolv_requester *req)
449{
450 struct resolvers *resolvers;
451 struct resolv_resolution *res;
452 int exp;
453
454 if (!req || !req->resolution)
455 return;
456 res = req->resolution;
457 resolvers = res->resolvers;
458
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100459 enter_resolver_code();
460
Emeric Brunc9437992021-02-12 19:42:55 +0100461 /* The resolution must not be triggered yet. Use the cached response, if
462 * valid */
463 exp = tick_add(res->last_resolution, resolvers->hold.valid);
464 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
465 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
466 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100467
468 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100469}
470
471
472/* Resets some resolution parameters to initial values and also delete the query
473 * ID from the resolver's tree.
474 */
475static void resolv_reset_resolution(struct resolv_resolution *resolution)
476{
477 /* update resolution status */
478 resolution->step = RSLV_STEP_NONE;
479 resolution->try = 0;
480 resolution->last_resolution = now_ms;
481 resolution->nb_queries = 0;
482 resolution->nb_responses = 0;
483 resolution->query_type = resolution->prefered_query_type;
484
485 /* clean up query id */
486 eb32_delete(&resolution->qid);
487 resolution->query_id = 0;
488 resolution->qid.key = 0;
489}
490
491/* Returns the query id contained in a DNS response */
492static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
493{
494 return resp[0] * 256 + resp[1];
495}
496
497
498/* Analyses, re-builds and copies the name <name> from the DNS response packet
499 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
500 * for compressed data. The result is copied into <dest>, ensuring we don't
501 * overflow using <dest_len> Returns the number of bytes the caller can move
502 * forward. If 0 it means an error occurred while parsing the name. <offset> is
503 * the number of bytes the caller could move forward.
504 */
505int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
506 unsigned char *name, char *destination, int dest_len,
507 int *offset, unsigned int depth)
508{
509 int nb_bytes = 0, n = 0;
510 int label_len;
511 unsigned char *reader = name;
512 char *dest = destination;
513
514 while (1) {
515 if (reader >= bufend)
516 goto err;
517
518 /* Name compression is in use */
519 if ((*reader & 0xc0) == 0xc0) {
520 if (reader + 1 >= bufend)
521 goto err;
522
523 /* Must point BEFORE current position */
524 if ((buffer + reader[1]) > reader)
525 goto err;
526
527 if (depth++ > 100)
528 goto err;
529
530 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
531 dest, dest_len - nb_bytes, offset, depth);
532 if (n == 0)
533 goto err;
534
535 dest += n;
536 nb_bytes += n;
537 goto out;
538 }
539
540 label_len = *reader;
541 if (label_len == 0)
542 goto out;
543
544 /* Check if:
545 * - we won't read outside the buffer
546 * - there is enough place in the destination
547 */
548 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
549 goto err;
550
551 /* +1 to take label len + label string */
552 label_len++;
553
554 memcpy(dest, reader, label_len);
555
556 dest += label_len;
557 nb_bytes += label_len;
558 reader += label_len;
559 }
560
561 out:
562 /* offset computation:
563 * parse from <name> until finding either NULL or a pointer "c0xx"
564 */
565 reader = name;
566 *offset = 0;
567 while (reader < bufend) {
568 if ((reader[0] & 0xc0) == 0xc0) {
569 *offset += 2;
570 break;
571 }
572 else if (*reader == 0) {
573 *offset += 1;
574 break;
575 }
576 *offset += 1;
577 ++reader;
578 }
579 return nb_bytes;
580
581 err:
582 return 0;
583}
584
Willy Tarreau20751652021-10-18 16:46:38 +0200585/* Reinitialize the list of aborted resolutions before calling certain
586 * functions relying on it. The list must be processed by calling
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100587 * leave_resolver_code() after operations.
Willy Tarreau20751652021-10-18 16:46:38 +0200588 */
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100589static void enter_resolver_code()
Willy Tarreau20751652021-10-18 16:46:38 +0200590{
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100591 if (!recurse)
592 LIST_INIT(&death_row);
593 recurse++;
Willy Tarreau20751652021-10-18 16:46:38 +0200594}
595
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100596/* Add a resolution to the death_row. */
Willy Tarreau20751652021-10-18 16:46:38 +0200597static void abort_resolution(struct resolv_resolution *res)
598{
599 LIST_DEL_INIT(&res->list);
600 LIST_APPEND(&death_row, &res->list);
601}
602
603/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100604 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreau20751652021-10-18 16:46:38 +0200605 * needs to defer deletions. Note that some of them are in relation via internal
606 * objects and might cause the deletion of other ones from the same list, so we
607 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
608 * and solely rely on each call to remove the first remaining list element.
609 */
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100610static void leave_resolver_code()
Willy Tarreau20751652021-10-18 16:46:38 +0200611{
612 struct resolv_resolution *res;
613
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100614 recurse--;
615 if (recurse)
616 return;
617
Willy Tarreau20751652021-10-18 16:46:38 +0200618 while (!LIST_ISEMPTY(&death_row)) {
619 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
620 resolv_free_resolution(res);
621 }
622
623 /* make sure nobody tries to add anything without having initialized it */
624 death_row = (struct list){ };
625}
626
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200627/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
628 * happens when an SRV item is purged or when the server status is considered as
629 * obsolete.
630 *
Willy Tarreau20751652021-10-18 16:46:38 +0200631 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100632 * initialized via enter_resolver_code().
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200633 */
Willy Tarreau20751652021-10-18 16:46:38 +0200634static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200635{
Willy Tarreau33360872021-10-20 14:07:31 +0200636 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200637 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
638 srvrq_update_srv_status(srv, 1);
639 ha_free(&srv->hostname);
640 ha_free(&srv->hostname_dn);
641 srv->hostname_dn_len = 0;
642 memset(&srv->addr, 0, sizeof(srv->addr));
643 srv->svc_port = 0;
644 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Fauleta62d9742021-06-15 16:14:37 +0200645
646 ebpt_delete(&srv->host_dn);
647 ha_free(&srv->host_dn.key);
648
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200649 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200650 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200651 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200652
653 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200654}
655
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200656/* Takes care to cleanup a server resolution when it is outdated. This only
657 * happens for a server relying on a SRV record.
658 */
659static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
660{
661 struct server *srv = context;
662
663 if (!tick_is_expired(t->expire, now_ms))
664 goto end;
665
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100666 enter_resolver_code();
Christopher Faulet152b50c2021-06-18 09:05:49 +0200667 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreau20751652021-10-18 16:46:38 +0200668 resolv_srvrq_cleanup_srv(srv);
Christopher Faulet152b50c2021-06-18 09:05:49 +0200669 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100670 leave_resolver_code();
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200671
672 end:
673 return t;
674}
675
Emeric Brunc9437992021-02-12 19:42:55 +0100676/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100677 * find a corresponding server.
Willy Tarreau20751652021-10-18 16:46:38 +0200678 */
Emeric Brunc9437992021-02-12 19:42:55 +0100679static void resolv_check_response(struct resolv_resolution *res)
680{
681 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100682 struct resolv_requester *req;
Emeric Brunc9437992021-02-12 19:42:55 +0100683 struct resolv_answer_item *item, *itemback;
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200684 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100685 struct resolv_srvrq *srvrq;
686
687 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
688 struct resolv_answer_item *ar_item = item->ar_item;
689
690 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100691 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100692 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
693 * item is also obsolete.
694 */
Emeric Brunc9437992021-02-12 19:42:55 +0100695 pool_free(resolv_answer_item_pool, ar_item);
696 item->ar_item = NULL;
697 }
698
699 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100700 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200701 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100702 /* Remove any associated server */
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200703 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
704 LIST_DEL_INIT(&srv->ip_rec_item);
705 }
706 }
707 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200708 /* Remove any associated server */
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200709 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreau20751652021-10-18 16:46:38 +0200710 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100711 }
712
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200713 LIST_DEL_INIT(&item->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100714 if (item->ar_item) {
715 pool_free(resolv_answer_item_pool, item->ar_item);
716 item->ar_item = NULL;
717 }
718 pool_free(resolv_answer_item_pool, item);
719 continue;
720 }
721
722 if (item->type != DNS_RTYPE_SRV)
723 continue;
724
725 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100726 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200727 struct ebpt_node *node;
728 char target[DNS_MAX_NAME_SIZE+1];
729
730 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100731 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
732 continue;
733
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200734 /* Check if a server already uses that record */
735 srv = NULL;
736 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
737 if (srv->srvrq == srvrq) {
738 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
739 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100740 }
Emeric Brunc9437992021-02-12 19:42:55 +0100741 }
742
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200743
744 /* If not empty we try to match a server
745 * in server state file tree with the same hostname
746 */
747 if (!eb_is_empty(&srvrq->named_servers)) {
748 srv = NULL;
749
750 /* convert the key to lookup in lower case */
Willy Tarreau20a02372021-10-14 22:52:04 +0200751 for (i = 0 ; item->data.target[i] ; i++)
752 target[i] = tolower(item->data.target[i]);
Christopher Fauletc20d6422021-07-22 14:29:26 +0200753 target[i] = 0;
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200754
755 node = ebis_lookup(&srvrq->named_servers, target);
756 if (node) {
757 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100758 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200759
760 /* an entry was found with the same hostname
761 * let check this node if the port matches
762 * and try next node if the hostname
763 * is still the same
764 */
765 while (1) {
766 if (srv->svc_port == item->port) {
767 /* server found, we remove it from tree */
768 ebpt_delete(node);
Christopher Fauleta62d9742021-06-15 16:14:37 +0200769 ha_free(&srv->host_dn.key);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200770 goto srv_found;
771 }
772
773 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
774
775 node = ebpt_next(node);
776 if (!node)
777 break;
778
779 srv = ebpt_entry(node, struct server, host_dn);
780 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
781
782 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau20a02372021-10-14 22:52:04 +0200783 || resolv_hostname_cmp(srv->hostname_dn, item->data.target, item->data_len)) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200784 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
785 break;
786 }
787 }
Emeric Brunc9437992021-02-12 19:42:55 +0100788 }
789 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200790
791 /* Pick the first server listed in srvrq (those ones don't
792 * have hostname and are free to use)
793 */
794 srv = NULL;
795 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
796 LIST_DEL_INIT(&srv->srv_rec_item);
797 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
798 goto srv_found;
799 }
800 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100801
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200802srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100803 /* And update this server, if found (srv is locked here) */
804 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100805 /* re-enable DNS resolution for this server by default */
806 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200807 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100808
Emeric Brunc9437992021-02-12 19:42:55 +0100809 /* Check if an Additional Record is associated to this SRV record.
810 * Perform some sanity checks too to ensure the record can be used.
811 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100812 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100813 */
814 if ((item->ar_item != NULL) &&
815 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100816 {
Emeric Brunc9437992021-02-12 19:42:55 +0100817
818 switch (item->ar_item->type) {
819 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +0200820 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100821 break;
822 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +0200823 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100824 break;
825 }
826
827 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100828
829 /* Unlink A/AAAA resolution for this server if there is an AR item.
830 * It is usless to perform an extra resolution
831 */
Willy Tarreau33360872021-10-20 14:07:31 +0200832 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100833 }
834
835 if (!srv->hostname_dn) {
836 const char *msg = NULL;
Willy Tarreau2859c162021-10-14 08:00:38 +0200837 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100838
Willy Tarreau20a02372021-10-14 22:52:04 +0200839 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau2859c162021-10-14 08:00:38 +0200840 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100841 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
842 continue;
843 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100844 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100845 if (msg)
846 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
847 }
848
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200849 if (!LIST_INLIST(&srv->srv_rec_item))
850 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
851
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100852 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
853 /* If there is no AR item responsible of the FQDN resolution,
854 * trigger a dedicated DNS resolution
855 */
856 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
857 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
858 }
859
Christopher Fauletab177ac2021-03-10 15:34:52 +0100860 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100861 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100862
863 srv->svc_port = item->port;
864 srv->flags &= ~SRV_F_MAPPORTS;
865
866 if (!srv->resolv_opts.ignore_weight) {
867 char weight[9];
868 int ha_weight;
869
870 /* DNS weight range if from 0 to 65535
871 * HAProxy weight is from 0 to 256
872 * The rule below ensures that weight 0 is well respected
873 * while allowing a "mapping" from DNS weight into HAProxy's one.
874 */
875 ha_weight = (item->weight + 255) / 256;
876
877 snprintf(weight, sizeof(weight), "%d", ha_weight);
878 server_parse_weight_change_request(srv, weight);
879 }
880 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
881 }
882 }
883 }
884}
885
886/* Validates that the buffer DNS response provided in <resp> and finishing
887 * before <bufend> is valid from a DNS protocol point of view.
888 *
889 * The result is stored in <resolution>' response, buf_response,
890 * response_query_records and response_answer_records members.
891 *
892 * This function returns one of the RSLV_RESP_* code to indicate the type of
893 * error found.
894 */
895static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
896 struct resolv_resolution *resolution, int max_answer_records)
897{
898 unsigned char *reader;
899 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
900 int len, flags, offset;
901 int query_record_id;
902 int nb_saved_records;
903 struct resolv_query_item *query;
904 struct resolv_answer_item *answer_record, *tmp_record;
905 struct resolv_response *r_res;
906 int i, found = 0;
907 int cause = RSLV_RESP_ERROR;
908
909 reader = resp;
910 len = 0;
911 previous_dname = NULL;
912 query = NULL;
913 answer_record = NULL;
914
915 /* Initialization of response buffer and structure */
916 r_res = &resolution->response;
917
918 /* query id */
919 if (reader + 2 >= bufend)
920 goto invalid_resp;
921
922 r_res->header.id = reader[0] * 256 + reader[1];
923 reader += 2;
924
925 /* Flags and rcode are stored over 2 bytes
926 * First byte contains:
927 * - response flag (1 bit)
928 * - opcode (4 bits)
929 * - authoritative (1 bit)
930 * - truncated (1 bit)
931 * - recursion desired (1 bit)
932 */
933 if (reader + 2 >= bufend)
934 goto invalid_resp;
935
936 flags = reader[0] * 256 + reader[1];
937
938 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
939 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
940 cause = RSLV_RESP_NX_DOMAIN;
941 goto return_error;
942 }
943 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
944 cause = RSLV_RESP_REFUSED;
945 goto return_error;
946 }
947 else {
948 cause = RSLV_RESP_ERROR;
949 goto return_error;
950 }
951 }
952
953 /* Move forward 2 bytes for flags */
954 reader += 2;
955
956 /* 2 bytes for question count */
957 if (reader + 2 >= bufend)
958 goto invalid_resp;
959 r_res->header.qdcount = reader[0] * 256 + reader[1];
960 /* (for now) we send one query only, so we expect only one in the
961 * response too */
962 if (r_res->header.qdcount != 1) {
963 cause = RSLV_RESP_QUERY_COUNT_ERROR;
964 goto return_error;
965 }
966
967 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
968 goto invalid_resp;
969 reader += 2;
970
971 /* 2 bytes for answer count */
972 if (reader + 2 >= bufend)
973 goto invalid_resp;
974 r_res->header.ancount = reader[0] * 256 + reader[1];
975 if (r_res->header.ancount == 0) {
976 cause = RSLV_RESP_ANCOUNT_ZERO;
977 goto return_error;
978 }
979
980 /* Check if too many records are announced */
981 if (r_res->header.ancount > max_answer_records)
982 goto invalid_resp;
983 reader += 2;
984
985 /* 2 bytes authority count */
986 if (reader + 2 >= bufend)
987 goto invalid_resp;
988 r_res->header.nscount = reader[0] * 256 + reader[1];
989 reader += 2;
990
991 /* 2 bytes additional count */
992 if (reader + 2 >= bufend)
993 goto invalid_resp;
994 r_res->header.arcount = reader[0] * 256 + reader[1];
995 reader += 2;
996
997 /* Parsing dns queries */
Willy Tarreau51128f82021-10-19 11:17:33 +0200998 BUG_ON(!LIST_ISEMPTY(&r_res->query_list));
Emeric Brunc9437992021-02-12 19:42:55 +0100999 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
1000 /* Use next pre-allocated resolv_query_item after ensuring there is
1001 * still one available.
1002 * It's then added to our packet query list. */
1003 if (query_record_id > DNS_MAX_QUERY_RECORDS)
1004 goto invalid_resp;
1005 query = &resolution->response_query_records[query_record_id];
Willy Tarreau2b718102021-04-21 07:32:39 +02001006 LIST_APPEND(&r_res->query_list, &query->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001007
1008 /* Name is a NULL terminated string in our case, since we have
1009 * one query per response and the first one can't be compressed
1010 * (using the 0x0c format) */
1011 offset = 0;
1012 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
1013
1014 if (len == 0)
1015 goto invalid_resp;
1016
1017 reader += offset;
1018 previous_dname = query->name;
1019
1020 /* move forward 2 bytes for question type */
1021 if (reader + 2 >= bufend)
1022 goto invalid_resp;
1023 query->type = reader[0] * 256 + reader[1];
1024 reader += 2;
1025
1026 /* move forward 2 bytes for question class */
1027 if (reader + 2 >= bufend)
1028 goto invalid_resp;
1029 query->class = reader[0] * 256 + reader[1];
1030 reader += 2;
1031 }
1032
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001033 /* Let's just make gcc happy. The tests above make it clear that
1034 * qdcount==1 hence that we necessarily enter into the loop at least
1035 * once, but gcc seems to be having difficulties following it and
1036 * warns about the risk of NULL dereference at the next line, even
1037 * if a BUG_ON(!query) is used.
1038 */
1039 ALREADY_CHECKED(query);
1040
Emeric Brunc9437992021-02-12 19:42:55 +01001041 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001042 * because a TRUNCATED SRV query type response can still be exploited
1043 */
Emeric Brunc9437992021-02-12 19:42:55 +01001044 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1045 cause = RSLV_RESP_TRUNCATED;
1046 goto return_error;
1047 }
1048
1049 /* now parsing response records */
1050 nb_saved_records = 0;
1051 for (i = 0; i < r_res->header.ancount; i++) {
1052 if (reader >= bufend)
1053 goto invalid_resp;
1054
1055 answer_record = pool_alloc(resolv_answer_item_pool);
1056 if (answer_record == NULL)
1057 goto invalid_resp;
1058
1059 /* initialization */
1060 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001061 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001062 LIST_INIT(&answer_record->attached_servers);
Willy Tarreaua2373e82021-10-19 11:29:21 +02001063 LIST_INIT(&answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001064
1065 offset = 0;
1066 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1067
1068 if (len == 0)
1069 goto invalid_resp;
1070
1071 /* Check if the current record dname is valid. previous_dname
1072 * points either to queried dname or last CNAME target */
1073 if (query->type != DNS_RTYPE_SRV && resolv_hostname_cmp(previous_dname, tmpname, len) != 0) {
1074 if (i == 0) {
1075 /* First record, means a mismatch issue between
1076 * queried dname and dname found in the first
1077 * record */
1078 goto invalid_resp;
1079 }
1080 else {
1081 /* If not the first record, this means we have a
1082 * CNAME resolution error.
1083 */
1084 cause = RSLV_RESP_CNAME_ERROR;
1085 goto return_error;
1086 }
1087
1088 }
1089
1090 memcpy(answer_record->name, tmpname, len);
1091 answer_record->name[len] = 0;
1092
1093 reader += offset;
1094 if (reader >= bufend)
1095 goto invalid_resp;
1096
1097 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1098 if (reader + 2 > bufend)
1099 goto invalid_resp;
1100
1101 answer_record->type = reader[0] * 256 + reader[1];
1102 reader += 2;
1103
1104 /* 2 bytes for class (2) */
1105 if (reader + 2 > bufend)
1106 goto invalid_resp;
1107
1108 answer_record->class = reader[0] * 256 + reader[1];
1109 reader += 2;
1110
1111 /* 4 bytes for ttl (4) */
1112 if (reader + 4 > bufend)
1113 goto invalid_resp;
1114
1115 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1116 + reader[2] * 256 + reader[3];
1117 reader += 4;
1118
1119 /* Now reading data len */
1120 if (reader + 2 > bufend)
1121 goto invalid_resp;
1122
1123 answer_record->data_len = reader[0] * 256 + reader[1];
1124
1125 /* Move forward 2 bytes for data len */
1126 reader += 2;
1127
1128 if (reader + answer_record->data_len > bufend)
1129 goto invalid_resp;
1130
1131 /* Analyzing record content */
1132 switch (answer_record->type) {
1133 case DNS_RTYPE_A:
1134 /* ipv4 is stored on 4 bytes */
1135 if (answer_record->data_len != 4)
1136 goto invalid_resp;
1137
Willy Tarreau20a02372021-10-14 22:52:04 +02001138 answer_record->data.in4.sin_family = AF_INET;
1139 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001140 break;
1141
1142 case DNS_RTYPE_CNAME:
1143 /* Check if this is the last record and update the caller about the status:
1144 * no IP could be found and last record was a CNAME. Could be triggered
1145 * by a wrong query type
1146 *
1147 * + 1 because answer_record_id starts at 0
1148 * while number of answers is an integer and
1149 * starts at 1.
1150 */
1151 if (i + 1 == r_res->header.ancount) {
1152 cause = RSLV_RESP_CNAME_ERROR;
1153 goto return_error;
1154 }
1155
1156 offset = 0;
1157 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1158 if (len == 0)
1159 goto invalid_resp;
1160
Willy Tarreau20a02372021-10-14 22:52:04 +02001161 memcpy(answer_record->data.target, tmpname, len);
1162 answer_record->data.target[len] = 0;
1163 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001164 break;
1165
1166
1167 case DNS_RTYPE_SRV:
1168 /* Answer must contain :
1169 * - 2 bytes for the priority
1170 * - 2 bytes for the weight
1171 * - 2 bytes for the port
1172 * - the target hostname
1173 */
1174 if (answer_record->data_len <= 6)
1175 goto invalid_resp;
1176
1177 answer_record->priority = read_n16(reader);
1178 reader += sizeof(uint16_t);
1179 answer_record->weight = read_n16(reader);
1180 reader += sizeof(uint16_t);
1181 answer_record->port = read_n16(reader);
1182 reader += sizeof(uint16_t);
1183 offset = 0;
1184 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1185 if (len == 0)
1186 goto invalid_resp;
1187
1188 answer_record->data_len = len;
Willy Tarreau20a02372021-10-14 22:52:04 +02001189 memcpy(answer_record->data.target, tmpname, len);
1190 answer_record->data.target[len] = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01001191 if (answer_record->ar_item != NULL) {
1192 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1193 answer_record->ar_item = NULL;
1194 }
1195 break;
1196
1197 case DNS_RTYPE_AAAA:
1198 /* ipv6 is stored on 16 bytes */
1199 if (answer_record->data_len != 16)
1200 goto invalid_resp;
1201
Willy Tarreau20a02372021-10-14 22:52:04 +02001202 answer_record->data.in6.sin6_family = AF_INET6;
1203 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001204 break;
1205
1206 } /* switch (record type) */
1207
1208 /* Increment the counter for number of records saved into our
1209 * local response */
1210 nb_saved_records++;
1211
1212 /* Move forward answer_record->data_len for analyzing next
1213 * record in the response */
1214 reader += ((answer_record->type == DNS_RTYPE_SRV)
1215 ? offset
1216 : answer_record->data_len);
1217
1218 /* Lookup to see if we already had this entry */
1219 found = 0;
1220 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1221 if (tmp_record->type != answer_record->type)
1222 continue;
1223
1224 switch(tmp_record->type) {
1225 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001226 if (!memcmp(&answer_record->data.in4.sin_addr,
1227 &tmp_record->data.in4.sin_addr,
1228 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001229 found = 1;
1230 break;
1231
1232 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001233 if (!memcmp(&answer_record->data.in6.sin6_addr,
1234 &tmp_record->data.in6.sin6_addr,
1235 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001236 found = 1;
1237 break;
1238
1239 case DNS_RTYPE_SRV:
1240 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001241 !resolv_hostname_cmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) &&
Emeric Brunc9437992021-02-12 19:42:55 +01001242 answer_record->port == tmp_record->port) {
1243 tmp_record->weight = answer_record->weight;
1244 found = 1;
1245 }
1246 break;
1247
1248 default:
1249 break;
1250 }
1251
1252 if (found == 1)
1253 break;
1254 }
1255
1256 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001257 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001258 pool_free(resolv_answer_item_pool, answer_record);
1259 answer_record = NULL;
1260 }
1261 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001262 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001263 answer_record->ar_item = NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +02001264 LIST_APPEND(&r_res->answer_list, &answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001265 answer_record = NULL;
1266 }
1267 } /* for i 0 to ancount */
1268
1269 /* Save the number of records we really own */
1270 r_res->header.ancount = nb_saved_records;
1271
1272 /* now parsing additional records for SRV queries only */
1273 if (query->type != DNS_RTYPE_SRV)
1274 goto skip_parsing_additional_records;
1275
1276 /* if we find Authority records, just skip them */
1277 for (i = 0; i < r_res->header.nscount; i++) {
1278 offset = 0;
1279 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1280 &offset, 0);
1281 if (len == 0)
1282 continue;
1283
1284 if (reader + offset + 10 >= bufend)
1285 goto invalid_resp;
1286
1287 reader += offset;
1288 /* skip 2 bytes for class */
1289 reader += 2;
1290 /* skip 2 bytes for type */
1291 reader += 2;
1292 /* skip 4 bytes for ttl */
1293 reader += 4;
1294 /* read data len */
1295 len = reader[0] * 256 + reader[1];
1296 reader += 2;
1297
1298 if (reader + len >= bufend)
1299 goto invalid_resp;
1300
1301 reader += len;
1302 }
1303
1304 nb_saved_records = 0;
1305 for (i = 0; i < r_res->header.arcount; i++) {
1306 if (reader >= bufend)
1307 goto invalid_resp;
1308
1309 answer_record = pool_alloc(resolv_answer_item_pool);
1310 if (answer_record == NULL)
1311 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001312 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001313 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001314
1315 offset = 0;
1316 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1317
1318 if (len == 0) {
1319 pool_free(resolv_answer_item_pool, answer_record);
1320 answer_record = NULL;
1321 continue;
1322 }
1323
1324 memcpy(answer_record->name, tmpname, len);
1325 answer_record->name[len] = 0;
1326
1327 reader += offset;
1328 if (reader >= bufend)
1329 goto invalid_resp;
1330
1331 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1332 if (reader + 2 > bufend)
1333 goto invalid_resp;
1334
1335 answer_record->type = reader[0] * 256 + reader[1];
1336 reader += 2;
1337
1338 /* 2 bytes for class (2) */
1339 if (reader + 2 > bufend)
1340 goto invalid_resp;
1341
1342 answer_record->class = reader[0] * 256 + reader[1];
1343 reader += 2;
1344
1345 /* 4 bytes for ttl (4) */
1346 if (reader + 4 > bufend)
1347 goto invalid_resp;
1348
1349 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1350 + reader[2] * 256 + reader[3];
1351 reader += 4;
1352
1353 /* Now reading data len */
1354 if (reader + 2 > bufend)
1355 goto invalid_resp;
1356
1357 answer_record->data_len = reader[0] * 256 + reader[1];
1358
1359 /* Move forward 2 bytes for data len */
1360 reader += 2;
1361
1362 if (reader + answer_record->data_len > bufend)
1363 goto invalid_resp;
1364
1365 /* Analyzing record content */
1366 switch (answer_record->type) {
1367 case DNS_RTYPE_A:
1368 /* ipv4 is stored on 4 bytes */
1369 if (answer_record->data_len != 4)
1370 goto invalid_resp;
1371
Willy Tarreau20a02372021-10-14 22:52:04 +02001372 answer_record->data.in4.sin_family = AF_INET;
1373 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001374 break;
1375
1376 case DNS_RTYPE_AAAA:
1377 /* ipv6 is stored on 16 bytes */
1378 if (answer_record->data_len != 16)
1379 goto invalid_resp;
1380
Willy Tarreau20a02372021-10-14 22:52:04 +02001381 answer_record->data.in6.sin6_family = AF_INET6;
1382 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001383 break;
1384
1385 default:
1386 pool_free(resolv_answer_item_pool, answer_record);
1387 answer_record = NULL;
1388 continue;
1389
1390 } /* switch (record type) */
1391
1392 /* Increment the counter for number of records saved into our
1393 * local response */
1394 nb_saved_records++;
1395
1396 /* Move forward answer_record->data_len for analyzing next
1397 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001398 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001399
1400 /* Lookup to see if we already had this entry */
1401 found = 0;
1402 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001403 struct resolv_answer_item *ar_item;
1404
1405 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1406 continue;
1407
1408 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001409 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001410 len != tmp_record->data_len ||
Willy Tarreau20a02372021-10-14 22:52:04 +02001411 resolv_hostname_cmp(answer_record->name, tmp_record->data.target, tmp_record->data_len))
Emeric Brunc9437992021-02-12 19:42:55 +01001412 continue;
1413
Christopher Faulet77f86062021-03-10 15:19:57 +01001414 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001415 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001416 if (!memcmp(&answer_record->data.in4.sin_addr,
1417 &ar_item->data.in4.sin_addr,
1418 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001419 found = 1;
1420 break;
1421
1422 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001423 if (!memcmp(&answer_record->data.in6.sin6_addr,
1424 &ar_item->data.in6.sin6_addr,
1425 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001426 found = 1;
1427 break;
1428
1429 default:
1430 break;
1431 }
1432
1433 if (found == 1)
1434 break;
1435 }
1436
1437 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001438 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001439 pool_free(resolv_answer_item_pool, answer_record);
1440 answer_record = NULL;
1441 }
1442 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001443 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001444 answer_record->ar_item = NULL;
1445
1446 // looking for the SRV record in the response list linked to this additional record
1447 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1448 if (tmp_record->type == DNS_RTYPE_SRV &&
1449 tmp_record->ar_item == NULL &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001450 !resolv_hostname_cmp(tmp_record->data.target, answer_record->name, tmp_record->data_len)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001451 /* Always use the received additional record to refresh info */
1452 if (tmp_record->ar_item)
1453 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1454 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001455 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001456 break;
1457 }
1458 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001459 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001460 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001461 answer_record = NULL;
1462 }
Emeric Brunc9437992021-02-12 19:42:55 +01001463 }
1464 } /* for i 0 to arcount */
1465
1466 skip_parsing_additional_records:
1467
1468 /* Save the number of records we really own */
1469 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001470 resolv_check_response(resolution);
1471 return RSLV_RESP_VALID;
1472
1473 invalid_resp:
1474 cause = RSLV_RESP_INVALID;
1475
1476 return_error:
1477 pool_free(resolv_answer_item_pool, answer_record);
1478 return cause;
1479}
1480
1481/* Searches dn_name resolution in resp.
1482 * If existing IP not found, return the first IP matching family_priority,
1483 * otherwise, first ip found
1484 * The following tasks are the responsibility of the caller:
1485 * - <r_res> contains an error free DNS response
1486 * For both cases above, resolv_validate_dns_response is required
1487 * returns one of the RSLV_UPD_* code
1488 */
1489int resolv_get_ip_from_response(struct resolv_response *r_res,
1490 struct resolv_options *resolv_opts, void *currentip,
1491 short currentip_sin_family,
1492 void **newip, short *newip_sin_family,
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001493 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001494{
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001495 struct resolv_answer_item *record, *found_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001496 int family_priority;
1497 int currentip_found;
1498 unsigned char *newip4, *newip6;
1499 int currentip_sel;
1500 int j;
1501 int score, max_score;
1502 int allowed_duplicated_ip;
1503
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001504 /* srv is linked to an alive ip record */
1505 if (owner && LIST_INLIST(&owner->ip_rec_item))
1506 return RSLV_UPD_NO;
1507
Emeric Brunc9437992021-02-12 19:42:55 +01001508 family_priority = resolv_opts->family_prio;
1509 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1510 *newip = newip4 = newip6 = NULL;
1511 currentip_found = 0;
1512 *newip_sin_family = AF_UNSPEC;
1513 max_score = -1;
1514
1515 /* Select an IP regarding configuration preference.
1516 * Top priority is the preferred network ip version,
1517 * second priority is the preferred network.
1518 * the last priority is the currently used IP,
1519 *
1520 * For these three priorities, a score is calculated. The
1521 * weight are:
1522 * 8 - preferred ip version.
1523 * 4 - preferred network.
1524 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1525 * 1 - current ip.
1526 * The result with the biggest score is returned.
1527 */
1528
1529 list_for_each_entry(record, &r_res->answer_list, list) {
1530 void *ip;
1531 unsigned char ip_type;
1532
1533 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001534 ip_type = AF_INET;
Willy Tarreau20a02372021-10-14 22:52:04 +02001535 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001536 }
1537 else if (record->type == DNS_RTYPE_AAAA) {
1538 ip_type = AF_INET6;
Willy Tarreau20a02372021-10-14 22:52:04 +02001539 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001540 }
1541 else
1542 continue;
1543 score = 0;
1544
1545 /* Check for preferred ip protocol. */
1546 if (ip_type == family_priority)
1547 score += 8;
1548
1549 /* Check for preferred network. */
1550 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1551
1552 /* Compare only the same addresses class. */
1553 if (resolv_opts->pref_net[j].family != ip_type)
1554 continue;
1555
1556 if ((ip_type == AF_INET &&
1557 in_net_ipv4(ip,
1558 &resolv_opts->pref_net[j].mask.in4,
1559 &resolv_opts->pref_net[j].addr.in4)) ||
1560 (ip_type == AF_INET6 &&
1561 in_net_ipv6(ip,
1562 &resolv_opts->pref_net[j].mask.in6,
1563 &resolv_opts->pref_net[j].addr.in6))) {
1564 score += 4;
1565 break;
1566 }
1567 }
1568
1569 /* Check if the IP found in the record is already affected to a
1570 * member of a group. If not, the score should be incremented
1571 * by 2. */
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001572 if (owner) {
1573 struct server *srv;
1574 int already_used = 0;
1575
1576 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1577 if (srv == owner)
1578 continue;
1579 if (srv->proxy == owner->proxy) {
1580 already_used = 1;
1581 break;
1582 }
1583 }
1584 if (already_used) {
1585 if (!allowed_duplicated_ip) {
1586 continue;
1587 }
1588 }
1589 else {
1590 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001591 }
1592 } else {
1593 score += 2;
1594 }
1595
1596 /* Check for current ip matching. */
1597 if (ip_type == currentip_sin_family &&
1598 ((currentip_sin_family == AF_INET &&
1599 !memcmp(ip, currentip, 4)) ||
1600 (currentip_sin_family == AF_INET6 &&
1601 !memcmp(ip, currentip, 16)))) {
1602 score++;
1603 currentip_sel = 1;
1604 }
1605 else
1606 currentip_sel = 0;
1607
1608 /* Keep the address if the score is better than the previous
1609 * score. The maximum score is 15, if this value is reached, we
1610 * break the parsing. Implicitly, this score is reached the ip
1611 * selected is the current ip. */
1612 if (score > max_score) {
1613 if (ip_type == AF_INET)
1614 newip4 = ip;
1615 else
1616 newip6 = ip;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001617 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001618 currentip_found = currentip_sel;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001619 if (score == 15) {
1620 /* this was not registered on the current record but it matches
1621 * let's fix it (it may comes from state file */
1622 if (owner)
1623 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001624 return RSLV_UPD_NO;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001625 }
Emeric Brunc9437992021-02-12 19:42:55 +01001626 max_score = score;
1627 }
1628 } /* list for each record entries */
1629
1630 /* No IP found in the response */
1631 if (!newip4 && !newip6)
1632 return RSLV_UPD_NO_IP_FOUND;
1633
1634 /* Case when the caller looks first for an IPv4 address */
1635 if (family_priority == AF_INET) {
1636 if (newip4) {
1637 *newip = newip4;
1638 *newip_sin_family = AF_INET;
1639 }
1640 else if (newip6) {
1641 *newip = newip6;
1642 *newip_sin_family = AF_INET6;
1643 }
Emeric Brunc9437992021-02-12 19:42:55 +01001644 }
1645 /* Case when the caller looks first for an IPv6 address */
1646 else if (family_priority == AF_INET6) {
1647 if (newip6) {
1648 *newip = newip6;
1649 *newip_sin_family = AF_INET6;
1650 }
1651 else if (newip4) {
1652 *newip = newip4;
1653 *newip_sin_family = AF_INET;
1654 }
Emeric Brunc9437992021-02-12 19:42:55 +01001655 }
1656 /* Case when the caller have no preference (we prefer IPv6) */
1657 else if (family_priority == AF_UNSPEC) {
1658 if (newip6) {
1659 *newip = newip6;
1660 *newip_sin_family = AF_INET6;
1661 }
1662 else if (newip4) {
1663 *newip = newip4;
1664 *newip_sin_family = AF_INET;
1665 }
Emeric Brunc9437992021-02-12 19:42:55 +01001666 }
1667
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001668 /* the ip of this record was chosen for the server */
1669 if (owner && found_record) {
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001670 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001671 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1672 }
1673
Emeric Brunc9437992021-02-12 19:42:55 +01001674 list_for_each_entry(record, &r_res->answer_list, list) {
1675 /* Move the first record to the end of the list, for internal
1676 * round robin */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001677 LIST_DEL_INIT(&record->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02001678 LIST_APPEND(&r_res->answer_list, &record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001679 break;
1680 }
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001681
1682 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001683}
1684
Willy Tarreauca0170b2021-10-14 08:05:25 +02001685/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001686 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001687 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1688 * null-terminated. <str> must be allocated large enough to contain a full host
1689 * name plus the trailing zero, and the allocated size must be passed in
1690 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001691 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001692 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001693 * <str> (including the terminating null byte).
1694 */
1695int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1696{
1697 char *ptr;
1698 int i, sz;
1699
Willy Tarreauca0170b2021-10-14 08:05:25 +02001700 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001701 return -1;
1702
1703 ptr = str;
Willy Tarreauca0170b2021-10-14 08:05:25 +02001704 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001705 sz = dn[i];
1706 if (i)
1707 *ptr++ = '.';
1708 memcpy(ptr, dn+i+1, sz);
1709 ptr += sz;
1710 i += sz;
1711 }
1712 *ptr++ = '\0';
1713 return (ptr - str);
1714}
1715
1716/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1717 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001718 * <str> contains the input string that is <str_len> bytes long (trailing zero
1719 * not needed). <dn> buffer must be allocated large enough to contain the
1720 * encoded string and a trailing zero, so it must be at least str_len+2, and
1721 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001722 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001723 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001724 * <dn> (excluding the terminating null byte).
1725 */
1726int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1727{
1728 int i, offset;
1729
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001730 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001731 return -1;
1732
1733 /* First byte of dn will be used to store the length of the first
1734 * label */
1735 offset = 0;
1736 for (i = 0; i < str_len; ++i) {
1737 if (str[i] == '.') {
1738 /* 2 or more consecutive dots is invalid */
1739 if (i == offset)
1740 return -1;
1741
1742 /* ignore trailing dot */
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001743 if (i + 1 == str_len) {
Emeric Brunc9437992021-02-12 19:42:55 +01001744 i++;
1745 break;
1746 }
1747
1748 dn[offset] = (i - offset);
1749 offset = i+1;
1750 continue;
1751 }
1752 dn[i+1] = str[i];
1753 }
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001754 dn[offset] = i - offset;
Willy Tarreau68c7b362021-10-15 08:09:25 +02001755 dn[i+1] = '\0';
1756 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001757}
1758
1759/* Validates host name:
1760 * - total size
1761 * - each label size individually
1762 * returns:
1763 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1764 * 1 when no error. <err> is left unaffected.
1765 */
1766int resolv_hostname_validation(const char *string, char **err)
1767{
1768 int i;
1769
1770 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1771 if (err)
1772 *err = DNS_TOO_LONG_FQDN;
1773 return 0;
1774 }
1775
1776 while (*string) {
1777 i = 0;
1778 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1779 if (!(*string == '-' || *string == '_' ||
1780 (*string >= 'a' && *string <= 'z') ||
1781 (*string >= 'A' && *string <= 'Z') ||
1782 (*string >= '0' && *string <= '9'))) {
1783 if (err)
1784 *err = DNS_INVALID_CHARACTER;
1785 return 0;
1786 }
1787 i++;
1788 string++;
1789 }
1790
1791 if (!(*string))
1792 break;
1793
1794 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1795 if (err)
1796 *err = DNS_LABEL_TOO_LONG;
1797 return 0;
1798 }
1799
1800 string++;
1801 }
1802 return 1;
1803}
1804
1805/* Picks up an available resolution from the different resolution list
1806 * associated to a resolvers section, in this order:
1807 * 1. check in resolutions.curr for the same hostname and query_type
1808 * 2. check in resolutions.wait for the same hostname and query_type
1809 * 3. Get a new resolution from resolution pool
1810 *
1811 * Returns an available resolution, NULL if none found.
1812 */
1813static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1814 char **hostname_dn, int hostname_dn_len,
1815 int query_type)
1816{
1817 struct resolv_resolution *res;
1818
1819 if (!*hostname_dn)
1820 goto from_pool;
1821
1822 /* Search for same hostname and query type in resolutions.curr */
1823 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1824 if (!res->hostname_dn)
1825 continue;
1826 if ((query_type == res->prefered_query_type) &&
1827 hostname_dn_len == res->hostname_dn_len &&
1828 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1829 return res;
1830 }
1831
1832 /* Search for same hostname and query type in resolutions.wait */
1833 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1834 if (!res->hostname_dn)
1835 continue;
1836 if ((query_type == res->prefered_query_type) &&
1837 hostname_dn_len == res->hostname_dn_len &&
1838 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1839 return res;
1840 }
1841
1842 from_pool:
1843 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001844 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001845 if (res) {
Willy Tarreau51128f82021-10-19 11:17:33 +02001846 int i;
1847
Emeric Brunc9437992021-02-12 19:42:55 +01001848 res->resolvers = resolvers;
1849 res->uuid = resolution_uuid;
1850 res->status = RSLV_STATUS_NONE;
1851 res->step = RSLV_STEP_NONE;
1852 res->last_valid = now_ms;
1853
1854 LIST_INIT(&res->requesters);
Willy Tarreau51128f82021-10-19 11:17:33 +02001855 LIST_INIT(&res->response.query_list);
Emeric Brunc9437992021-02-12 19:42:55 +01001856 LIST_INIT(&res->response.answer_list);
1857
Willy Tarreau51128f82021-10-19 11:17:33 +02001858 for (i = 0; i < DNS_MAX_QUERY_RECORDS; i++)
1859 LIST_INIT(&res->response_query_records[i].list);
1860
Emeric Brunc9437992021-02-12 19:42:55 +01001861 res->prefered_query_type = query_type;
1862 res->query_type = query_type;
1863 res->hostname_dn = *hostname_dn;
1864 res->hostname_dn_len = hostname_dn_len;
1865
1866 ++resolution_uuid;
1867
1868 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001869 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001870 }
1871 return res;
1872}
1873
Willy Tarreauaab75932021-10-19 11:16:11 +02001874/* deletes and frees all answer_items from the resolution's answer_list */
1875static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001876{
1877 struct resolv_answer_item *item, *itemback;
1878
1879 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001880 LIST_DEL_INIT(&item->list);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001881 pool_free(resolv_answer_item_pool, item->ar_item);
1882 pool_free(resolv_answer_item_pool, item);
1883 }
1884}
1885
Willy Tarreau51128f82021-10-19 11:17:33 +02001886/* deletes all query_items from the resolution's query_list */
1887static void resolv_purge_resolution_query_items(struct resolv_resolution *resolution)
1888{
1889 struct resolv_query_item *item, *itemback;
1890
1891 list_for_each_entry_safe(item, itemback, &resolution->response.query_list, list)
1892 LIST_DEL_INIT(&item->list);
1893}
1894
Emeric Brunc9437992021-02-12 19:42:55 +01001895/* Releases a resolution from its requester(s) and move it back to the pool */
1896static void resolv_free_resolution(struct resolv_resolution *resolution)
1897{
1898 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001899
1900 /* clean up configuration */
1901 resolv_reset_resolution(resolution);
1902 resolution->hostname_dn = NULL;
1903 resolution->hostname_dn_len = 0;
1904
1905 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001906 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001907 req->resolution = NULL;
1908 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001909 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau51128f82021-10-19 11:17:33 +02001910 resolv_purge_resolution_query_items(resolution);
1911
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001912 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001913 pool_free(resolv_resolution_pool, resolution);
1914}
1915
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001916/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1917 * and makes it owned by this obj_type, with the proposed callback and error
1918 * callback. On success, *req is assigned the allocated requester. Returns
1919 * NULL on allocation failure.
1920 */
1921static struct resolv_requester *
1922resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1923 int (*cb)(struct resolv_requester *, struct dns_counters *),
1924 int (*err_cb)(struct resolv_requester *, int))
1925{
1926 struct resolv_requester *tmp;
1927
1928 if (*req)
1929 return *req;
1930
1931 tmp = pool_alloc(resolv_requester_pool);
1932 if (!tmp)
1933 goto end;
1934
1935 LIST_INIT(&tmp->list);
1936 tmp->owner = owner;
1937 tmp->resolution = NULL;
1938 tmp->requester_cb = cb;
1939 tmp->requester_error_cb = err_cb;
1940 *req = tmp;
1941 end:
1942 return tmp;
1943}
1944
Emeric Brunc9437992021-02-12 19:42:55 +01001945/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet7a3a5362021-11-02 16:25:05 +01001946 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001947 */
1948int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1949{
1950 struct resolv_resolution *res = NULL;
1951 struct resolv_requester *req;
1952 struct resolvers *resolvers;
1953 struct server *srv = NULL;
1954 struct resolv_srvrq *srvrq = NULL;
1955 struct stream *stream = NULL;
1956 char **hostname_dn;
1957 int hostname_dn_len, query_type;
1958
Christopher Faulet7a3a5362021-11-02 16:25:05 +01001959 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001960 switch (requester_type) {
1961 case OBJ_TYPE_SERVER:
1962 srv = (struct server *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001963
1964 if (!requester_locked)
1965 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1966
1967 req = resolv_get_requester(&srv->resolv_requester,
1968 &srv->obj_type,
1969 snr_resolution_cb,
1970 snr_resolution_error_cb);
1971
1972 if (!requester_locked)
1973 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1974
1975 if (!req)
1976 goto err;
1977
Emeric Brunc9437992021-02-12 19:42:55 +01001978 hostname_dn = &srv->hostname_dn;
1979 hostname_dn_len = srv->hostname_dn_len;
1980 resolvers = srv->resolvers;
1981 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1982 ? DNS_RTYPE_A
1983 : DNS_RTYPE_AAAA);
1984 break;
1985
1986 case OBJ_TYPE_SRVRQ:
1987 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001988
1989 req = resolv_get_requester(&srvrq->requester,
1990 &srvrq->obj_type,
1991 snr_resolution_cb,
1992 srvrq_resolution_error_cb);
1993 if (!req)
1994 goto err;
1995
Emeric Brunc9437992021-02-12 19:42:55 +01001996 hostname_dn = &srvrq->hostname_dn;
1997 hostname_dn_len = srvrq->hostname_dn_len;
1998 resolvers = srvrq->resolvers;
1999 query_type = DNS_RTYPE_SRV;
2000 break;
2001
2002 case OBJ_TYPE_STREAM:
2003 stream = (struct stream *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02002004
2005 req = resolv_get_requester(&stream->resolv_ctx.requester,
2006 &stream->obj_type,
2007 act_resolution_cb,
2008 act_resolution_error_cb);
2009 if (!req)
2010 goto err;
2011
Emeric Brunc9437992021-02-12 19:42:55 +01002012 hostname_dn = &stream->resolv_ctx.hostname_dn;
2013 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2014 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2015 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2016 ? DNS_RTYPE_A
2017 : DNS_RTYPE_AAAA);
2018 break;
2019 default:
2020 goto err;
2021 }
2022
2023 /* Get a resolution from the resolvers' wait queue or pool */
2024 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2025 goto err;
2026
Willy Tarreau4d7ca912021-10-19 11:59:25 +02002027 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002028
Willy Tarreau2b718102021-04-21 07:32:39 +02002029 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002030 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002031 return 0;
2032
2033 err:
2034 if (res && LIST_ISEMPTY(&res->requesters))
2035 resolv_free_resolution(res);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002036 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002037 return -1;
2038}
2039
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002040/* This function removes all server/srvrq references on answer items. */
Willy Tarreau33360872021-10-20 14:07:31 +02002041void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002042{
2043 struct resolv_answer_item *item, *itemback;
2044 struct server *srv, *srvback;
2045 struct resolv_srvrq *srvrq;
2046
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002047 enter_resolver_code();
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002048 if ((srv = objt_server(req->owner)) != NULL) {
2049 LIST_DEL_INIT(&srv->ip_rec_item);
2050 }
2051 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
2052 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
2053 if (item->type == DNS_RTYPE_SRV) {
2054 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet5f8ccff2021-06-15 16:08:48 +02002055 if (srv->srvrq == srvrq)
Willy Tarreau20751652021-10-18 16:46:38 +02002056 resolv_srvrq_cleanup_srv(srv);
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002057 }
2058 }
2059 }
2060 }
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002061 leave_resolver_code();
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002062}
2063
Emeric Brunc9437992021-02-12 19:42:55 +01002064/* Removes a requester from a DNS resolution. It takes takes care of all the
2065 * consequences. It also cleans up some parameters from the requester.
2066 */
Willy Tarreau33360872021-10-20 14:07:31 +02002067static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002068{
2069 struct resolv_resolution *res;
2070 struct resolv_requester *req;
2071
2072 /* Nothing to do */
2073 if (!requester || !requester->resolution)
2074 return;
2075 res = requester->resolution;
2076
2077 /* Clean up the requester */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002078 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002079 requester->resolution = NULL;
2080
Christopher Faulete7e0e4b2021-10-29 10:38:15 +02002081 /* remove ref from the resolution answer item list to the requester */
2082 resolv_detach_from_resolution_answer_items(res, requester);
2083
Emeric Brunc9437992021-02-12 19:42:55 +01002084 /* We need to find another requester linked on this resolution */
2085 if (!LIST_ISEMPTY(&res->requesters))
2086 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2087 else {
Willy Tarreau20751652021-10-18 16:46:38 +02002088 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002089 return;
2090 }
2091
2092 /* Move hostname_dn related pointers to the next requester */
2093 switch (obj_type(req->owner)) {
2094 case OBJ_TYPE_SERVER:
2095 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2096 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2097 break;
2098 case OBJ_TYPE_SRVRQ:
2099 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2100 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2101 break;
2102 case OBJ_TYPE_STREAM:
2103 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2104 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2105 break;
2106 default:
2107 res->hostname_dn = NULL;
2108 res->hostname_dn_len = 0;
2109 break;
2110 }
2111}
2112
Willy Tarreau20751652021-10-18 16:46:38 +02002113/* The public version of the function above that deals with the death row. */
Willy Tarreau33360872021-10-20 14:07:31 +02002114void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreau20751652021-10-18 16:46:38 +02002115{
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002116 enter_resolver_code();
Willy Tarreau33360872021-10-20 14:07:31 +02002117 _resolv_unlink_resolution(requester);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002118 leave_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002119}
2120
Emeric Brunc9437992021-02-12 19:42:55 +01002121/* Called when a network IO is generated on a name server socket for an incoming
2122 * packet. It performs the following actions:
2123 * - check if the packet requires processing (not outdated resolution)
2124 * - ensure the DNS packet received is valid and call requester's callback
2125 * - call requester's error callback if invalid response
2126 * - check the dn_name in the packet against the one sent
2127 */
2128static int resolv_process_responses(struct dns_nameserver *ns)
2129{
2130 struct dns_counters *tmpcounters;
2131 struct resolvers *resolvers;
2132 struct resolv_resolution *res;
2133 struct resolv_query_item *query;
2134 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2135 unsigned char *bufend;
2136 int buflen, dns_resp;
2137 int max_answer_records;
2138 unsigned short query_id;
2139 struct eb32_node *eb;
2140 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002141 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002142
2143 resolvers = ns->parent;
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002144 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002145 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2146
2147 /* process all pending input messages */
2148 while (1) {
2149 /* read message received */
2150 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2151 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2152 break;
2153 }
2154
2155 /* message too big */
2156 if (buflen > resolvers->accepted_payload_size) {
2157 ns->counters->too_big++;
2158 continue;
2159 }
2160
2161 /* initializing variables */
2162 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2163
2164 /* read the query id from the packet (16 bits) */
2165 if (buf + 2 > bufend) {
2166 ns->counters->invalid++;
2167 continue;
2168 }
2169 query_id = resolv_response_get_query_id(buf);
2170
2171 /* search the query_id in the pending resolution tree */
2172 eb = eb32_lookup(&resolvers->query_ids, query_id);
2173 if (eb == NULL) {
2174 /* unknown query id means an outdated response and can be safely ignored */
2175 ns->counters->outdated++;
2176 continue;
2177 }
2178
2179 /* known query id means a resolution in progress */
2180 res = eb32_entry(eb, struct resolv_resolution, qid);
2181 /* number of responses received */
2182 res->nb_responses++;
2183
2184 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2185 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2186
2187 switch (dns_resp) {
2188 case RSLV_RESP_VALID:
2189 break;
2190
2191 case RSLV_RESP_INVALID:
2192 case RSLV_RESP_QUERY_COUNT_ERROR:
2193 case RSLV_RESP_WRONG_NAME:
2194 res->status = RSLV_STATUS_INVALID;
2195 ns->counters->invalid++;
2196 break;
2197
2198 case RSLV_RESP_NX_DOMAIN:
2199 res->status = RSLV_STATUS_NX;
2200 ns->counters->nx++;
2201 break;
2202
2203 case RSLV_RESP_REFUSED:
2204 res->status = RSLV_STATUS_REFUSED;
2205 ns->counters->refused++;
2206 break;
2207
2208 case RSLV_RESP_ANCOUNT_ZERO:
2209 res->status = RSLV_STATUS_OTHER;
2210 ns->counters->any_err++;
2211 break;
2212
2213 case RSLV_RESP_CNAME_ERROR:
2214 res->status = RSLV_STATUS_OTHER;
2215 ns->counters->cname_error++;
2216 break;
2217
2218 case RSLV_RESP_TRUNCATED:
2219 res->status = RSLV_STATUS_OTHER;
2220 ns->counters->truncated++;
2221 break;
2222
2223 case RSLV_RESP_NO_EXPECTED_RECORD:
2224 case RSLV_RESP_ERROR:
2225 case RSLV_RESP_INTERNAL:
2226 res->status = RSLV_STATUS_OTHER;
2227 ns->counters->other++;
2228 break;
2229 }
2230
2231 /* Wait all nameservers response to handle errors */
2232 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2233 continue;
2234
2235 /* Process error codes */
2236 if (dns_resp != RSLV_RESP_VALID) {
2237 if (res->prefered_query_type != res->query_type) {
2238 /* The fallback on the query type was already performed,
2239 * so check the try counter. If it falls to 0, we can
2240 * report an error. Else, wait the next attempt. */
2241 if (!res->try)
2242 goto report_res_error;
2243 }
2244 else {
2245 /* Fallback from A to AAAA or the opposite and re-send
2246 * the resolution immediately. try counter is not
2247 * decremented. */
2248 if (res->prefered_query_type == DNS_RTYPE_A) {
2249 res->query_type = DNS_RTYPE_AAAA;
2250 resolv_send_query(res);
2251 }
2252 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2253 res->query_type = DNS_RTYPE_A;
2254 resolv_send_query(res);
2255 }
2256 }
2257 continue;
2258 }
2259
2260 /* Now let's check the query's dname corresponds to the one we
2261 * sent. We can check only the first query of the list. We send
Willy Tarreau51128f82021-10-19 11:17:33 +02002262 * one query at a time so we get one query in the response.
2263 */
2264 if (!LIST_ISEMPTY(&res->response.query_list)) {
2265 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
2266 LIST_DEL_INIT(&query->list);
2267 if (resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
2268 dns_resp = RSLV_RESP_WRONG_NAME;
2269 ns->counters->other++;
2270 goto report_res_error;
2271 }
Emeric Brunc9437992021-02-12 19:42:55 +01002272 }
2273
2274 /* So the resolution succeeded */
2275 res->status = RSLV_STATUS_VALID;
2276 res->last_valid = now_ms;
2277 ns->counters->valid++;
2278 goto report_res_success;
2279
2280 report_res_error:
Emeric Brun43839d02021-06-10 15:25:25 +02002281 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002282 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002283 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2284 if (!keep_answer_items)
2285 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002286 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002287 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002288 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002289 continue;
2290
2291 report_res_success:
2292 /* Only the 1rst requester s managed by the server, others are
2293 * from the cache */
2294 tmpcounters = ns->counters;
2295 list_for_each_entry(req, &res->requesters, list) {
2296 struct server *s = objt_server(req->owner);
2297
2298 if (s)
2299 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2300 req->requester_cb(req, tmpcounters);
2301 if (s)
2302 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2303 tmpcounters = NULL;
2304 }
2305
2306 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002307 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002308 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002309 continue;
2310 }
2311 resolv_update_resolvers_timeout(resolvers);
2312 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002313 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002314 return buflen;
2315}
2316
2317/* Processes DNS resolution. First, it checks the active list to detect expired
2318 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2319 * checks the wait list to trigger new resolutions.
2320 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002321static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002322{
2323 struct resolvers *resolvers = context;
2324 struct resolv_resolution *res, *resback;
2325 int exp;
2326
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002327 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002328 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2329
Willy Tarreau20751652021-10-18 16:46:38 +02002330 /* Handle all expired resolutions from the active list. Elements that
2331 * need to be removed will in fact be moved to the death_row. Other
2332 * ones will be handled normally.
2333 */
2334
Willy Tarreau20751652021-10-18 16:46:38 +02002335 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2336 while (&res->list != &resolvers->resolutions.curr) {
2337 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2338
Christopher Faulet0efc0992021-03-11 18:09:53 +01002339 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002340 abort_resolution(res);
2341 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002342 continue;
2343 }
2344
Emeric Brunc9437992021-02-12 19:42:55 +01002345 /* When we find the first resolution in the future, then we can
2346 * stop here */
2347 exp = tick_add(res->last_query, resolvers->timeout.retry);
2348 if (!tick_is_expired(exp, now_ms))
2349 break;
2350
2351 /* If current resolution has been tried too many times and
2352 * finishes in timeout we update its status and remove it from
2353 * the list */
2354 if (!res->try) {
2355 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002356 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002357
2358 /* Notify the result to the requesters */
2359 if (!res->nb_responses)
2360 res->status = RSLV_STATUS_TIMEOUT;
2361 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002362 keep_answer_items |= req->requester_error_cb(req, res->status);
2363 if (!keep_answer_items)
2364 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002365
2366 /* Clean up resolution info and remove it from the
2367 * current list */
2368 resolv_reset_resolution(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002369
2370 /* subsequent entries might have been deleted here */
2371 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002372 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002373 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreau20751652021-10-18 16:46:38 +02002374 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002375 }
2376 else {
2377 /* Otherwise resend the DNS query and requeue the resolution */
2378 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2379 /* No response received (a real timeout) or fallback already done */
2380 res->query_type = res->prefered_query_type;
2381 res->try--;
2382 }
2383 else {
2384 /* Fallback from A to AAAA or the opposite and re-send
2385 * the resolution immediately. try counter is not
2386 * decremented. */
2387 if (res->prefered_query_type == DNS_RTYPE_A)
2388 res->query_type = DNS_RTYPE_AAAA;
2389 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2390 res->query_type = DNS_RTYPE_A;
2391 else
2392 res->try--;
2393 }
2394 resolv_send_query(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002395 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2396 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002397 }
2398 }
2399
2400 /* Handle all resolutions in the wait list */
2401 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002402 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002403 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002404 continue;
2405 }
2406
Emeric Brunc9437992021-02-12 19:42:55 +01002407 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2408 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2409 continue;
2410
2411 if (resolv_run_resolution(res) != 1) {
2412 res->last_resolution = now_ms;
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002413 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002414 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002415 }
2416 }
Emeric Brunc9437992021-02-12 19:42:55 +01002417 resolv_update_resolvers_timeout(resolvers);
2418 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002419
2420 /* now we can purge all queued deletions */
2421 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002422 return t;
2423}
2424
2425/* Release memory allocated by DNS */
2426static void resolvers_deinit(void)
2427{
2428 struct resolvers *resolvers, *resolversback;
2429 struct dns_nameserver *ns, *nsback;
2430 struct resolv_resolution *res, *resback;
2431 struct resolv_requester *req, *reqback;
2432 struct resolv_srvrq *srvrq, *srvrqback;
2433
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002434 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002435 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2436 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2437 free(ns->id);
2438 free((char *)ns->conf.file);
2439 if (ns->dgram) {
2440 if (ns->dgram->conn.t.sock.fd != -1) {
2441 fd_delete(ns->dgram->conn.t.sock.fd);
2442 close(ns->dgram->conn.t.sock.fd);
2443 }
2444 if (ns->dgram->ring_req)
2445 ring_free(ns->dgram->ring_req);
2446 free(ns->dgram);
2447 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002448 if (ns->stream) {
2449 if (ns->stream->ring_req)
2450 ring_free(ns->stream->ring_req);
2451 if (ns->stream->task_req)
2452 task_destroy(ns->stream->task_req);
2453 if (ns->stream->task_rsp)
2454 task_destroy(ns->stream->task_rsp);
2455 free(ns->stream);
2456 }
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002457 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002458 EXTRA_COUNTERS_FREE(ns->extra_counters);
2459 free(ns);
2460 }
2461
2462 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2463 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002464 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002465 pool_free(resolv_requester_pool, req);
2466 }
Willy Tarreau20751652021-10-18 16:46:38 +02002467 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002468 }
2469
2470 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2471 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002472 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002473 pool_free(resolv_requester_pool, req);
2474 }
Willy Tarreau20751652021-10-18 16:46:38 +02002475 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002476 }
2477
2478 free(resolvers->id);
2479 free((char *)resolvers->conf.file);
2480 task_destroy(resolvers->t);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002481 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002482 free(resolvers);
2483 }
2484
2485 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2486 free(srvrq->name);
2487 free(srvrq->hostname_dn);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002488 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002489 free(srvrq);
2490 }
Willy Tarreau20751652021-10-18 16:46:38 +02002491
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002492 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002493}
2494
2495/* Finalizes the DNS configuration by allocating required resources and checking
2496 * live parameters.
2497 * Returns 0 on success, ERR_* flags otherwise.
2498 */
2499static int resolvers_finalize_config(void)
2500{
2501 struct resolvers *resolvers;
2502 struct proxy *px;
2503 int err_code = 0;
2504
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002505 enter_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002506
Emeric Brunc9437992021-02-12 19:42:55 +01002507 /* allocate pool of resolution per resolvers */
2508 list_for_each_entry(resolvers, &sec_resolvers, list) {
2509 struct dns_nameserver *ns;
2510 struct task *t;
2511
2512 /* Check if we can create the socket with nameservers info */
2513 list_for_each_entry(ns, &resolvers->nameservers, list) {
2514 int fd;
2515
2516 if (ns->dgram) {
2517 /* Check nameserver info */
2518 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
2519 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2520 resolvers->id, ns->id);
2521 err_code |= (ERR_ALERT|ERR_ABORT);
2522 continue;
2523 }
2524 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
2525 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2526 resolvers->id, ns->id);
2527 close(fd);
2528 err_code |= (ERR_ALERT|ERR_ABORT);
2529 continue;
2530 }
2531 close(fd);
2532 }
2533 }
2534
2535 /* Create the task associated to the resolvers section */
2536 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2537 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
2538 err_code |= (ERR_ALERT|ERR_ABORT);
2539 goto err;
2540 }
2541
2542 /* Update task's parameters */
2543 t->process = process_resolvers;
2544 t->context = resolvers;
2545 resolvers->t = t;
2546 task_wakeup(t, TASK_WOKEN_INIT);
2547 }
2548
2549 for (px = proxies_list; px; px = px->next) {
2550 struct server *srv;
2551
2552 for (srv = px->srv; srv; srv = srv->next) {
2553 struct resolvers *resolvers;
2554
2555 if (!srv->resolvers_id)
2556 continue;
2557
2558 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
2559 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2560 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2561 err_code |= (ERR_ALERT|ERR_ABORT);
2562 continue;
2563 }
2564 srv->resolvers = resolvers;
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002565 srv->srvrq_check = NULL;
2566 if (srv->srvrq) {
2567 if (!srv->srvrq->resolvers) {
2568 srv->srvrq->resolvers = srv->resolvers;
2569 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2570 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2571 proxy_type_str(px), px->id, srv->id);
2572 err_code |= (ERR_ALERT|ERR_ABORT);
2573 continue;
2574 }
2575 }
Emeric Brunc9437992021-02-12 19:42:55 +01002576
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002577 srv->srvrq_check = task_new(MAX_THREADS_MASK);
2578 if (!srv->srvrq_check) {
2579 ha_alert("config: %s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002580 proxy_type_str(px), px->id, srv->id);
2581 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002582 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002583 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002584 srv->srvrq_check->process = resolv_srvrq_expire_task;
2585 srv->srvrq_check->context = srv;
2586 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002587 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002588 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +01002589 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2590 proxy_type_str(px), px->id, srv->id);
2591 err_code |= (ERR_ALERT|ERR_ABORT);
2592 continue;
2593 }
2594 }
2595 }
2596
2597 if (err_code & (ERR_ALERT|ERR_ABORT))
2598 goto err;
2599
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002600 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002601 return err_code;
2602 err:
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002603 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002604 resolvers_deinit();
2605 return err_code;
2606
2607}
2608
2609static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2610 struct dns_nameserver *ns,
2611 struct field *stats, size_t stats_count,
2612 struct list *stat_modules)
2613{
2614 struct appctx *appctx = __objt_appctx(si->end);
2615 struct channel *rep = si_ic(si);
2616 struct stats_module *mod;
2617 size_t idx = 0;
2618
2619 memset(stats, 0, sizeof(struct field) * stats_count);
2620
2621 list_for_each_entry(mod, stat_modules, list) {
2622 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2623
2624 mod->fill_stats(counters, stats + idx);
2625 idx += mod->stats_count;
2626 }
2627
2628 if (!stats_dump_one_line(stats, idx, appctx))
2629 return 0;
2630
2631 if (!stats_putchk(rep, NULL, &trash))
2632 goto full;
2633
2634 return 1;
2635
2636 full:
2637 si_rx_room_rdy(si);
2638 return 0;
2639}
2640
2641/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2642 * as a pointer to the current nameserver.
2643 */
2644int stats_dump_resolvers(struct stream_interface *si,
2645 struct field *stats, size_t stats_count,
2646 struct list *stat_modules)
2647{
2648 struct appctx *appctx = __objt_appctx(si->end);
2649 struct channel *rep = si_ic(si);
2650 struct resolvers *resolver = appctx->ctx.stats.obj1;
2651 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2652
2653 if (!resolver)
2654 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2655
2656 /* dump resolvers */
2657 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2658 appctx->ctx.stats.obj1 = resolver;
2659
2660 ns = appctx->ctx.stats.obj2 ?
2661 appctx->ctx.stats.obj2 :
2662 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2663
2664 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2665 appctx->ctx.stats.obj2 = ns;
2666
2667 if (buffer_almost_full(&rep->buf))
2668 goto full;
2669
2670 if (!stats_dump_resolv_to_buffer(si, ns,
2671 stats, stats_count,
2672 stat_modules)) {
2673 return 0;
2674 }
2675 }
2676
2677 appctx->ctx.stats.obj2 = NULL;
2678 }
2679
2680 return 1;
2681
2682 full:
2683 si_rx_room_blk(si);
2684 return 0;
2685}
2686
2687void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2688{
2689 struct resolvers *resolvers;
2690 struct dns_nameserver *ns;
2691 struct stats_module *mod;
2692 void *counters;
2693
2694 list_for_each_entry(mod, stat_modules, list) {
2695 if (!mod->clearable && !clrall)
2696 continue;
2697
2698 list_for_each_entry(resolvers, &sec_resolvers, list) {
2699 list_for_each_entry(ns, &resolvers->nameservers, list) {
2700 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2701 memcpy(counters, mod->counters, mod->counters_size);
2702 }
2703 }
2704 }
2705
2706}
2707
2708int resolv_allocate_counters(struct list *stat_modules)
2709{
2710 struct stats_module *mod;
2711 struct resolvers *resolvers;
2712 struct dns_nameserver *ns;
2713
2714 list_for_each_entry(resolvers, &sec_resolvers, list) {
2715 list_for_each_entry(ns, &resolvers->nameservers, list) {
2716 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2717 alloc_failed);
2718
2719 list_for_each_entry(mod, stat_modules, list) {
2720 EXTRA_COUNTERS_ADD(mod,
2721 ns->extra_counters,
2722 mod->counters,
2723 mod->counters_size);
2724 }
2725
2726 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2727
2728 list_for_each_entry(mod, stat_modules, list) {
2729 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2730 mod->counters, mod->counters_size);
2731
2732 /* Store the ns counters pointer */
2733 if (strcmp(mod->name, "dns") == 0) {
2734 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2735 ns->counters->id = ns->id;
2736 ns->counters->pid = resolvers->id;
2737 }
2738 }
2739 }
2740 }
2741
2742 return 1;
2743
2744alloc_failed:
2745 return 0;
2746}
2747
2748/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2749static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2750{
2751 struct resolvers *presolvers;
2752
2753 if (*args[2]) {
2754 list_for_each_entry(presolvers, &sec_resolvers, list) {
2755 if (strcmp(presolvers->id, args[2]) == 0) {
2756 appctx->ctx.cli.p0 = presolvers;
2757 break;
2758 }
2759 }
2760 if (appctx->ctx.cli.p0 == NULL)
2761 return cli_err(appctx, "Can't find that resolvers section\n");
2762 }
2763 return 0;
2764}
2765
2766/* Dumps counters from all resolvers section and associated name servers. It
2767 * returns 0 if the output buffer is full and it needs to be called again,
2768 * otherwise non-zero. It may limit itself to the resolver pointed to by
2769 * <cli.p0> if it's not null.
2770 */
2771static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2772{
2773 struct stream_interface *si = appctx->owner;
2774 struct resolvers *resolvers;
2775 struct dns_nameserver *ns;
2776
2777 chunk_reset(&trash);
2778
2779 switch (appctx->st2) {
2780 case STAT_ST_INIT:
2781 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2782 /* fall through */
2783
2784 case STAT_ST_LIST:
2785 if (LIST_ISEMPTY(&sec_resolvers)) {
2786 chunk_appendf(&trash, "No resolvers found\n");
2787 }
2788 else {
2789 list_for_each_entry(resolvers, &sec_resolvers, list) {
2790 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2791 continue;
2792
2793 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2794 list_for_each_entry(ns, &resolvers->nameservers, list) {
2795 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2796 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2797 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2798 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2799 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2800 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2801 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2802 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2803 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2804 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2805 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2806 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2807 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2808 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2809 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2810 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
2811 }
2812 chunk_appendf(&trash, "\n");
2813 }
2814 }
2815
2816 /* display response */
2817 if (ci_putchk(si_ic(si), &trash) == -1) {
2818 /* let's try again later from this session. We add ourselves into
2819 * this session's users so that it can remove us upon termination.
2820 */
2821 si_rx_room_blk(si);
2822 return 0;
2823 }
2824 /* fall through */
2825
2826 default:
2827 appctx->st2 = STAT_ST_FIN;
2828 return 1;
2829 }
2830}
2831
2832/* register cli keywords */
2833static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002834 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002835 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2836 {{},}
2837 }
2838};
2839
2840INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2841
2842/*
2843 * Prepare <rule> for hostname resolution.
2844 * Returns -1 in case of any allocation failure, 0 if not.
2845 * On error, a global failure counter is also incremented.
2846 */
Willy Tarreaua13a6102021-10-14 08:11:48 +02002847static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002848{
2849 char *hostname_dn;
Willy Tarreaua13a6102021-10-14 08:11:48 +02002850 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002851 struct buffer *tmp = get_trash_chunk();
2852
2853 if (!hostname)
2854 return 0;
2855
Emeric Brunc9437992021-02-12 19:42:55 +01002856 hostname_dn = tmp->area;
Willy Tarreauc1c765f2021-10-14 07:49:49 +02002857 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002858 hostname_dn, tmp->size);
2859 if (hostname_dn_len == -1)
2860 goto err;
2861
2862
2863 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2864 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2865 if (!stream->resolv_ctx.hostname_dn)
2866 goto err;
2867
2868 return 0;
2869
2870 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002871 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002872 resolv_failed_resolutions += 1;
2873 return -1;
2874}
2875
2876
2877/*
2878 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2879 */
2880enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2881 struct session *sess, struct stream *s, int flags)
2882{
2883 struct resolv_resolution *resolution;
2884 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002885 struct resolv_requester *req;
2886 struct resolvers *resolvers;
2887 struct resolv_resolution *res;
2888 int exp, locked = 0;
2889 enum act_return ret = ACT_RET_CONT;
2890
2891 resolvers = rule->arg.resolv.resolvers;
2892
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002893 enter_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002894
Emeric Brunc9437992021-02-12 19:42:55 +01002895 /* we have a response to our DNS resolution */
2896 use_cache:
2897 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2898 resolution = s->resolv_ctx.requester->resolution;
2899 if (!locked) {
2900 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2901 locked = 1;
2902 }
2903
2904 if (resolution->step == RSLV_STEP_RUNNING)
2905 goto yield;
2906 if (resolution->step == RSLV_STEP_NONE) {
2907 /* We update the variable only if we have a valid response. */
2908 if (resolution->status == RSLV_STATUS_VALID) {
2909 struct sample smp;
2910 short ip_sin_family = 0;
2911 void *ip = NULL;
2912
2913 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2914 0, &ip, &ip_sin_family, NULL);
2915
2916 switch (ip_sin_family) {
2917 case AF_INET:
2918 smp.data.type = SMP_T_IPV4;
2919 memcpy(&smp.data.u.ipv4, ip, 4);
2920 break;
2921 case AF_INET6:
2922 smp.data.type = SMP_T_IPV6;
2923 memcpy(&smp.data.u.ipv6, ip, 16);
2924 break;
2925 default:
2926 ip = NULL;
2927 }
2928
2929 if (ip) {
2930 smp.px = px;
2931 smp.sess = sess;
2932 smp.strm = s;
2933
2934 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2935 }
2936 }
2937 }
2938
2939 goto release_requester;
2940 }
2941
2942 /* need to configure and start a new DNS resolution */
2943 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2944 if (smp == NULL)
2945 goto end;
2946
Willy Tarreaua13a6102021-10-14 08:11:48 +02002947 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002948 goto end; /* on error, ignore the action */
2949
2950 s->resolv_ctx.parent = rule;
2951
2952 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2953 locked = 1;
2954
2955 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2956
2957 /* Check if there is a fresh enough response in the cache of our associated resolution */
2958 req = s->resolv_ctx.requester;
2959 if (!req || !req->resolution)
2960 goto release_requester; /* on error, ignore the action */
2961 res = req->resolution;
2962
2963 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2964 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2965 && !tick_is_expired(exp, now_ms)) {
2966 goto use_cache;
2967 }
2968
2969 resolv_trigger_resolution(s->resolv_ctx.requester);
2970
2971 yield:
2972 if (flags & ACT_OPT_FINAL)
2973 goto release_requester;
2974 ret = ACT_RET_YIELD;
2975
2976 end:
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002977 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002978 if (locked)
2979 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2980 return ret;
2981
2982 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002983 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002984 s->resolv_ctx.hostname_dn_len = 0;
2985 if (s->resolv_ctx.requester) {
Willy Tarreau33360872021-10-20 14:07:31 +02002986 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01002987 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2988 s->resolv_ctx.requester = NULL;
2989 }
2990 goto end;
2991}
2992
2993static void release_resolv_action(struct act_rule *rule)
2994{
2995 release_sample_expr(rule->arg.resolv.expr);
2996 free(rule->arg.resolv.varname);
2997 free(rule->arg.resolv.resolvers_id);
2998 free(rule->arg.resolv.opts);
2999}
3000
3001
3002/* parse "do-resolve" action
3003 * This action takes the following arguments:
3004 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3005 *
3006 * - <varName> is the variable name where the result of the DNS resolution will be stored
3007 * (mandatory)
3008 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3009 * (mandatory)
3010 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3011 * (optional), defaults to ipv6
3012 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3013 */
3014enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3015{
3016 int cur_arg;
3017 struct sample_expr *expr;
3018 unsigned int where;
3019 const char *beg, *end;
3020
3021 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3022 cur_arg = *orig_arg - 1;
3023
3024 /* locate varName, which is mandatory */
3025 beg = strchr(args[cur_arg], '(');
3026 if (beg == NULL)
3027 goto do_resolve_parse_error;
3028 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3029 end = strchr(beg, ',');
3030 if (end == NULL)
3031 goto do_resolve_parse_error;
3032 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3033 if (rule->arg.resolv.varname == NULL)
3034 goto do_resolve_parse_error;
3035
3036
3037 /* locate resolversSectionName, which is mandatory.
3038 * Since next parameters are optional, the delimiter may be comma ','
3039 * or closing parenthesis ')'
3040 */
3041 beg = end + 1;
3042 end = strchr(beg, ',');
3043 if (end == NULL)
3044 end = strchr(beg, ')');
3045 if (end == NULL)
3046 goto do_resolve_parse_error;
3047 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3048 if (rule->arg.resolv.resolvers_id == NULL)
3049 goto do_resolve_parse_error;
3050
3051
3052 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3053 if (rule->arg.resolv.opts == NULL)
3054 goto do_resolve_parse_error;
3055
3056 /* Default priority is ipv6 */
3057 rule->arg.resolv.opts->family_prio = AF_INET6;
3058
3059 /* optional arguments accepted for now:
3060 * ipv4 or ipv6
3061 */
3062 while (*end != ')') {
3063 beg = end + 1;
3064 end = strchr(beg, ',');
3065 if (end == NULL)
3066 end = strchr(beg, ')');
3067 if (end == NULL)
3068 goto do_resolve_parse_error;
3069
3070 if (strncmp(beg, "ipv4", end - beg) == 0) {
3071 rule->arg.resolv.opts->family_prio = AF_INET;
3072 }
3073 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3074 rule->arg.resolv.opts->family_prio = AF_INET6;
3075 }
3076 else {
3077 goto do_resolve_parse_error;
3078 }
3079 }
3080
3081 cur_arg = cur_arg + 1;
3082
3083 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3084 if (!expr)
3085 goto do_resolve_parse_error;
3086
3087
3088 where = 0;
3089 if (px->cap & PR_CAP_FE)
3090 where |= SMP_VAL_FE_HRQ_HDR;
3091 if (px->cap & PR_CAP_BE)
3092 where |= SMP_VAL_BE_HRQ_HDR;
3093
3094 if (!(expr->fetch->val & where)) {
3095 memprintf(err,
3096 "fetch method '%s' extracts information from '%s', none of which is available here",
3097 args[cur_arg-1], sample_src_names(expr->fetch->use));
3098 free(expr);
3099 return ACT_RET_PRS_ERR;
3100 }
3101 rule->arg.resolv.expr = expr;
3102 rule->action = ACT_CUSTOM;
3103 rule->action_ptr = resolv_action_do_resolve;
3104 *orig_arg = cur_arg;
3105
3106 rule->check_ptr = check_action_do_resolve;
3107 rule->release_ptr = release_resolv_action;
3108
3109 return ACT_RET_PRS_OK;
3110
3111 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003112 ha_free(&rule->arg.resolv.varname);
3113 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003114 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3115 args[cur_arg]);
3116 return ACT_RET_PRS_ERR;
3117}
3118
3119static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003120 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003121 { /* END */ }
3122}};
3123
3124INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3125
3126static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003127 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003128 { /* END */ }
3129}};
3130
3131INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3132
3133/* Check an "http-request do-resolve" action.
3134 *
3135 * The function returns 1 in success case, otherwise, it returns 0 and err is
3136 * filled.
3137 */
3138int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3139{
3140 struct resolvers *resolvers = NULL;
3141
3142 if (rule->arg.resolv.resolvers_id == NULL) {
3143 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3144 return 0;
3145 }
3146
3147 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3148 if (resolvers == NULL) {
3149 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3150 return 0;
3151 }
3152 rule->arg.resolv.resolvers = resolvers;
3153
3154 return 1;
3155}
3156
3157void resolvers_setup_proxy(struct proxy *px)
3158{
3159 px->last_change = now.tv_sec;
3160 px->cap = PR_CAP_FE | PR_CAP_BE;
3161 px->maxconn = 0;
3162 px->conn_retries = 1;
3163 px->timeout.server = TICK_ETERNITY;
3164 px->timeout.client = TICK_ETERNITY;
3165 px->timeout.connect = TICK_ETERNITY;
3166 px->accept = NULL;
3167 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
3168 px->bind_proc = 0; /* will be filled by users */
3169}
3170
3171/*
3172 * Parse a <resolvers> section.
3173 * Returns the error code, 0 if OK, or any combination of :
3174 * - ERR_ABORT: must abort ASAP
3175 * - ERR_FATAL: we can continue parsing but not start the service
3176 * - ERR_WARN: a warning has been emitted
3177 * - ERR_ALERT: an alert has been emitted
3178 * Only the two first ones can stop processing, the two others are just
3179 * indicators.
3180 */
3181int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3182{
3183 const char *err;
3184 int err_code = 0;
3185 char *errmsg = NULL;
3186 struct proxy *p;
3187
3188 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3189 if (!*args[1]) {
3190 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3191 err_code |= ERR_ALERT | ERR_ABORT;
3192 goto out;
3193 }
3194
3195 err = invalid_char(args[1]);
3196 if (err) {
3197 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3198 file, linenum, *err, args[0], args[1]);
3199 err_code |= ERR_ALERT | ERR_ABORT;
3200 goto out;
3201 }
3202
3203 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3204 /* Error if two resolvers owns the same name */
3205 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3206 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3207 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3208 err_code |= ERR_ALERT | ERR_ABORT;
3209 }
3210 }
3211
3212 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3213 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3214 err_code |= ERR_ALERT | ERR_ABORT;
3215 goto out;
3216 }
3217
3218 /* allocate new proxy to tcp servers */
3219 p = calloc(1, sizeof *p);
3220 if (!p) {
3221 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3222 err_code |= ERR_ALERT | ERR_FATAL;
3223 goto out;
3224 }
3225
3226 init_new_proxy(p);
3227 resolvers_setup_proxy(p);
3228 p->parent = curr_resolvers;
3229 p->id = strdup(args[1]);
3230 p->conf.args.file = p->conf.file = strdup(file);
3231 p->conf.args.line = p->conf.line = linenum;
3232 curr_resolvers->px = p;
3233
3234 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003235 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003236 curr_resolvers->conf.file = strdup(file);
3237 curr_resolvers->conf.line = linenum;
3238 curr_resolvers->id = strdup(args[1]);
3239 curr_resolvers->query_ids = EB_ROOT;
3240 /* default maximum response size */
3241 curr_resolvers->accepted_payload_size = 512;
3242 /* default hold period for nx, other, refuse and timeout is 30s */
3243 curr_resolvers->hold.nx = 30000;
3244 curr_resolvers->hold.other = 30000;
3245 curr_resolvers->hold.refused = 30000;
3246 curr_resolvers->hold.timeout = 30000;
3247 curr_resolvers->hold.obsolete = 0;
3248 /* default hold period for valid is 10s */
3249 curr_resolvers->hold.valid = 10000;
3250 curr_resolvers->timeout.resolve = 1000;
3251 curr_resolvers->timeout.retry = 1000;
3252 curr_resolvers->resolve_retries = 3;
3253 LIST_INIT(&curr_resolvers->nameservers);
3254 LIST_INIT(&curr_resolvers->resolutions.curr);
3255 LIST_INIT(&curr_resolvers->resolutions.wait);
3256 HA_SPIN_INIT(&curr_resolvers->lock);
3257 }
3258 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3259 struct dns_nameserver *newnameserver = NULL;
3260 struct sockaddr_storage *sk;
3261 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003262 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003263
3264 if (!*args[2]) {
3265 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3266 file, linenum, args[0]);
3267 err_code |= ERR_ALERT | ERR_FATAL;
3268 goto out;
3269 }
3270
3271 err = invalid_char(args[1]);
3272 if (err) {
3273 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3274 file, linenum, *err, args[1]);
3275 err_code |= ERR_ALERT | ERR_FATAL;
3276 goto out;
3277 }
3278
3279 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3280 /* Error if two resolvers owns the same name */
3281 if (strcmp(newnameserver->id, args[1]) == 0) {
3282 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3283 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3284 err_code |= ERR_ALERT | ERR_FATAL;
3285 }
3286 }
3287
Emeric Brunc8f3e452021-04-07 16:04:54 +02003288 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3289 &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 +01003290 if (!sk) {
3291 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3292 err_code |= ERR_ALERT | ERR_FATAL;
3293 goto out;
3294 }
3295
3296 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3297 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3298 err_code |= ERR_ALERT | ERR_ABORT;
3299 goto out;
3300 }
3301
Emeric Brunc8f3e452021-04-07 16:04:54 +02003302 if (proto && proto->ctrl_type == SOCK_STREAM) {
3303 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3304 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3305 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3306 err_code |= ERR_ABORT;
3307 goto out;
3308 }
3309
3310 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3311 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3312 err_code |= ERR_ALERT|ERR_ABORT;
3313 goto out;
3314 }
3315 }
3316 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003317 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3318 err_code |= ERR_ALERT | ERR_ABORT;
3319 goto out;
3320 }
3321
3322 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3323 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3324 err_code |= ERR_ALERT | ERR_ABORT;
3325 goto out;
3326 }
3327
3328 if ((newnameserver->id = strdup(args[1])) == NULL) {
3329 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3330 err_code |= ERR_ALERT | ERR_ABORT;
3331 goto out;
3332 }
3333
3334 newnameserver->parent = curr_resolvers;
3335 newnameserver->process_responses = resolv_process_responses;
3336 newnameserver->conf.line = linenum;
3337 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003338 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003339 }
3340 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3341 struct dns_nameserver *newnameserver = NULL;
3342 const char *whitespace = "\r\n\t ";
3343 char *resolv_line = NULL;
3344 int resolv_linenum = 0;
3345 FILE *f = NULL;
3346 char *address = NULL;
3347 struct sockaddr_storage *sk = NULL;
3348 struct protocol *proto;
3349 int duplicate_name = 0;
3350
3351 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3352 ha_alert("parsing [%s:%d] : out of memory.\n",
3353 file, linenum);
3354 err_code |= ERR_ALERT | ERR_FATAL;
3355 goto resolv_out;
3356 }
3357
3358 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3359 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3360 file, linenum);
3361 err_code |= ERR_ALERT | ERR_FATAL;
3362 goto resolv_out;
3363 }
3364
3365 sk = calloc(1, sizeof(*sk));
3366 if (sk == NULL) {
3367 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3368 resolv_linenum);
3369 err_code |= ERR_ALERT | ERR_FATAL;
3370 goto resolv_out;
3371 }
3372
3373 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3374 resolv_linenum++;
3375 if (strncmp(resolv_line, "nameserver", 10) != 0)
3376 continue;
3377
3378 address = strtok(resolv_line + 10, whitespace);
3379 if (address == resolv_line + 10)
3380 continue;
3381
3382 if (address == NULL) {
3383 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3384 resolv_linenum);
3385 err_code |= ERR_WARN;
3386 continue;
3387 }
3388
3389 duplicate_name = 0;
3390 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3391 if (strcmp(newnameserver->id, address) == 0) {
3392 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",
3393 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3394 err_code |= ERR_WARN;
3395 duplicate_name = 1;
3396 }
3397 }
3398
3399 if (duplicate_name)
3400 continue;
3401
3402 memset(sk, 0, sizeof(*sk));
3403 if (!str2ip2(address, sk, 1)) {
3404 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3405 resolv_linenum, address);
3406 err_code |= ERR_WARN;
3407 continue;
3408 }
3409
3410 set_host_port(sk, 53);
3411
3412 proto = protocol_by_family(sk->ss_family);
3413 if (!proto || !proto->connect) {
3414 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3415 resolv_linenum, address);
3416 err_code |= ERR_WARN;
3417 continue;
3418 }
3419
3420 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3421 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3422 err_code |= ERR_ALERT | ERR_FATAL;
3423 goto resolv_out;
3424 }
3425
3426 if (dns_dgram_init(newnameserver, sk) < 0) {
3427 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3428 err_code |= ERR_ALERT | ERR_FATAL;
3429 free(newnameserver);
3430 goto resolv_out;
3431 }
3432
3433 newnameserver->conf.file = strdup("/etc/resolv.conf");
3434 if (newnameserver->conf.file == NULL) {
3435 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3436 err_code |= ERR_ALERT | ERR_FATAL;
3437 free(newnameserver);
3438 goto resolv_out;
3439 }
3440
3441 newnameserver->id = strdup(address);
3442 if (newnameserver->id == NULL) {
3443 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3444 err_code |= ERR_ALERT | ERR_FATAL;
3445 free((char *)newnameserver->conf.file);
3446 free(newnameserver);
3447 goto resolv_out;
3448 }
3449
3450 newnameserver->parent = curr_resolvers;
3451 newnameserver->process_responses = resolv_process_responses;
3452 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003453 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003454 }
3455
3456resolv_out:
3457 free(sk);
3458 free(resolv_line);
3459 if (f != NULL)
3460 fclose(f);
3461 }
3462 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3463 const char *res;
3464 unsigned int time;
3465
3466 if (!*args[2]) {
3467 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3468 file, linenum, args[0]);
3469 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3470 err_code |= ERR_ALERT | ERR_FATAL;
3471 goto out;
3472 }
3473 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3474 if (res == PARSE_TIME_OVER) {
3475 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3476 file, linenum, args[1], args[0]);
3477 err_code |= ERR_ALERT | ERR_FATAL;
3478 goto out;
3479 }
3480 else if (res == PARSE_TIME_UNDER) {
3481 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3482 file, linenum, args[1], args[0]);
3483 err_code |= ERR_ALERT | ERR_FATAL;
3484 goto out;
3485 }
3486 else if (res) {
3487 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3488 file, linenum, *res, args[0]);
3489 err_code |= ERR_ALERT | ERR_FATAL;
3490 goto out;
3491 }
3492 if (strcmp(args[1], "nx") == 0)
3493 curr_resolvers->hold.nx = time;
3494 else if (strcmp(args[1], "other") == 0)
3495 curr_resolvers->hold.other = time;
3496 else if (strcmp(args[1], "refused") == 0)
3497 curr_resolvers->hold.refused = time;
3498 else if (strcmp(args[1], "timeout") == 0)
3499 curr_resolvers->hold.timeout = time;
3500 else if (strcmp(args[1], "valid") == 0)
3501 curr_resolvers->hold.valid = time;
3502 else if (strcmp(args[1], "obsolete") == 0)
3503 curr_resolvers->hold.obsolete = time;
3504 else {
3505 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3506 file, linenum, args[0], args[1]);
3507 err_code |= ERR_ALERT | ERR_FATAL;
3508 goto out;
3509 }
3510
3511 }
3512 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3513 int i = 0;
3514
3515 if (!*args[1]) {
3516 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3517 file, linenum, args[0]);
3518 err_code |= ERR_ALERT | ERR_FATAL;
3519 goto out;
3520 }
3521
3522 i = atoi(args[1]);
3523 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3524 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3525 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3526 err_code |= ERR_ALERT | ERR_FATAL;
3527 goto out;
3528 }
3529
3530 curr_resolvers->accepted_payload_size = i;
3531 }
3532 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3533 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3534 file, linenum, args[0]);
3535 err_code |= ERR_ALERT | ERR_FATAL;
3536 goto out;
3537 }
3538 else if (strcmp(args[0], "resolve_retries") == 0) {
3539 if (!*args[1]) {
3540 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3541 file, linenum, args[0]);
3542 err_code |= ERR_ALERT | ERR_FATAL;
3543 goto out;
3544 }
3545 curr_resolvers->resolve_retries = atoi(args[1]);
3546 }
3547 else if (strcmp(args[0], "timeout") == 0) {
3548 if (!*args[1]) {
3549 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3550 file, linenum, args[0]);
3551 err_code |= ERR_ALERT | ERR_FATAL;
3552 goto out;
3553 }
3554 else if (strcmp(args[1], "retry") == 0 ||
3555 strcmp(args[1], "resolve") == 0) {
3556 const char *res;
3557 unsigned int tout;
3558
3559 if (!*args[2]) {
3560 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3561 file, linenum, args[0], args[1]);
3562 err_code |= ERR_ALERT | ERR_FATAL;
3563 goto out;
3564 }
3565 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3566 if (res == PARSE_TIME_OVER) {
3567 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3568 file, linenum, args[2], args[0], args[1]);
3569 err_code |= ERR_ALERT | ERR_FATAL;
3570 goto out;
3571 }
3572 else if (res == PARSE_TIME_UNDER) {
3573 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3574 file, linenum, args[2], args[0], args[1]);
3575 err_code |= ERR_ALERT | ERR_FATAL;
3576 goto out;
3577 }
3578 else if (res) {
3579 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3580 file, linenum, *res, args[0], args[1]);
3581 err_code |= ERR_ALERT | ERR_FATAL;
3582 goto out;
3583 }
3584 if (args[1][2] == 't')
3585 curr_resolvers->timeout.retry = tout;
3586 else
3587 curr_resolvers->timeout.resolve = tout;
3588 }
3589 else {
3590 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3591 file, linenum, args[0], args[1]);
3592 err_code |= ERR_ALERT | ERR_FATAL;
3593 goto out;
3594 }
3595 }
3596 else if (*args[0] != 0) {
3597 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3598 err_code |= ERR_ALERT | ERR_FATAL;
3599 goto out;
3600 }
3601
3602 out:
3603 free(errmsg);
3604 return err_code;
3605}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003606int cfg_post_parse_resolvers()
3607{
3608 int err_code = 0;
3609 struct server *srv;
3610
3611 if (curr_resolvers) {
3612
3613 /* prepare forward server descriptors */
3614 if (curr_resolvers->px) {
3615 srv = curr_resolvers->px->srv;
3616 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003617 /* init ssl if needed */
3618 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3619 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3620 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3621 err_code |= ERR_ALERT | ERR_FATAL;
3622 break;
3623 }
3624 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003625 srv = srv->next;
3626 }
3627 }
3628 }
3629 curr_resolvers = NULL;
3630 return err_code;
3631}
Emeric Brunc9437992021-02-12 19:42:55 +01003632
Emeric Brun56fc5d92021-02-12 20:05:45 +01003633REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003634REGISTER_POST_DEINIT(resolvers_deinit);
3635REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);