blob: 5f5b48f394a9e9e0a299668949cbd10d21115a3a [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
Emeric Brun9267ed82021-10-29 16:44:49 +0200362 * success or -1 if trash buffer is not large enough to build a valid query.
Emeric Brunc9437992021-02-12 19:42:55 +0100363 */
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);
Emeric Brun9267ed82021-10-29 16:44:49 +0200379 if (len < 0) {
380 send_log(NULL, LOG_NOTICE,
381 "can not build the query message for %s, in resolvers %s.\n",
382 resolution->hostname_dn, resolvers->id);
383 return -1;
384 }
Emeric Brunc9437992021-02-12 19:42:55 +0100385
386 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brun2fa8f072021-10-29 16:28:33 +0200387 if (dns_send_nameserver(ns, trash.area, len) >= 0)
Emeric Brunc9437992021-02-12 19:42:55 +0100388 resolution->nb_queries++;
389 }
390
391 /* Push the resolution at the end of the active list */
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200392 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200393 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100394 return 0;
395}
396
397/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
398 * skipped and -1 if an error occurred.
399 */
400static int
401resolv_run_resolution(struct resolv_resolution *resolution)
402{
403 struct resolvers *resolvers = resolution->resolvers;
404 int query_id, i;
405
406 /* Avoid sending requests for resolutions that don't yet have an
407 * hostname, ie resolutions linked to servers that do not yet have an
408 * fqdn */
409 if (!resolution->hostname_dn)
410 return 0;
411
412 /* Check if a resolution has already been started for this server return
413 * directly to avoid resolution pill up. */
414 if (resolution->step != RSLV_STEP_NONE)
415 return 0;
416
417 /* Generates a new query id. We try at most 100 times to find a free
418 * query id */
419 for (i = 0; i < 100; ++i) {
420 query_id = resolv_rnd16();
421 if (!eb32_lookup(&resolvers->query_ids, query_id))
422 break;
423 query_id = -1;
424 }
425 if (query_id == -1) {
426 send_log(NULL, LOG_NOTICE,
427 "could not generate a query id for %s, in resolvers %s.\n",
428 resolution->hostname_dn, resolvers->id);
429 return -1;
430 }
431
432 /* Update resolution parameters */
433 resolution->query_id = query_id;
434 resolution->qid.key = query_id;
435 resolution->step = RSLV_STEP_RUNNING;
436 resolution->query_type = resolution->prefered_query_type;
437 resolution->try = resolvers->resolve_retries;
438 eb32_insert(&resolvers->query_ids, &resolution->qid);
439
440 /* Send the DNS query */
441 resolution->try -= 1;
442 resolv_send_query(resolution);
443 return 1;
444}
445
446/* Performs a name resolution for the requester <req> */
447void resolv_trigger_resolution(struct resolv_requester *req)
448{
449 struct resolvers *resolvers;
450 struct resolv_resolution *res;
451 int exp;
452
453 if (!req || !req->resolution)
454 return;
455 res = req->resolution;
456 resolvers = res->resolvers;
457
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100458 enter_resolver_code();
459
Emeric Brunc9437992021-02-12 19:42:55 +0100460 /* The resolution must not be triggered yet. Use the cached response, if
461 * valid */
462 exp = tick_add(res->last_resolution, resolvers->hold.valid);
463 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
464 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
465 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100466
467 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100468}
469
470
471/* Resets some resolution parameters to initial values and also delete the query
472 * ID from the resolver's tree.
473 */
474static void resolv_reset_resolution(struct resolv_resolution *resolution)
475{
476 /* update resolution status */
477 resolution->step = RSLV_STEP_NONE;
478 resolution->try = 0;
479 resolution->last_resolution = now_ms;
480 resolution->nb_queries = 0;
481 resolution->nb_responses = 0;
482 resolution->query_type = resolution->prefered_query_type;
483
484 /* clean up query id */
485 eb32_delete(&resolution->qid);
486 resolution->query_id = 0;
487 resolution->qid.key = 0;
488}
489
490/* Returns the query id contained in a DNS response */
491static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
492{
493 return resp[0] * 256 + resp[1];
494}
495
496
497/* Analyses, re-builds and copies the name <name> from the DNS response packet
498 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
499 * for compressed data. The result is copied into <dest>, ensuring we don't
500 * overflow using <dest_len> Returns the number of bytes the caller can move
501 * forward. If 0 it means an error occurred while parsing the name. <offset> is
502 * the number of bytes the caller could move forward.
503 */
504int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
505 unsigned char *name, char *destination, int dest_len,
506 int *offset, unsigned int depth)
507{
508 int nb_bytes = 0, n = 0;
509 int label_len;
510 unsigned char *reader = name;
511 char *dest = destination;
512
513 while (1) {
514 if (reader >= bufend)
515 goto err;
516
517 /* Name compression is in use */
518 if ((*reader & 0xc0) == 0xc0) {
519 if (reader + 1 >= bufend)
520 goto err;
521
522 /* Must point BEFORE current position */
523 if ((buffer + reader[1]) > reader)
524 goto err;
525
526 if (depth++ > 100)
527 goto err;
528
529 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
530 dest, dest_len - nb_bytes, offset, depth);
531 if (n == 0)
532 goto err;
533
534 dest += n;
535 nb_bytes += n;
536 goto out;
537 }
538
539 label_len = *reader;
540 if (label_len == 0)
541 goto out;
542
543 /* Check if:
544 * - we won't read outside the buffer
545 * - there is enough place in the destination
546 */
547 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
548 goto err;
549
550 /* +1 to take label len + label string */
551 label_len++;
552
553 memcpy(dest, reader, label_len);
554
555 dest += label_len;
556 nb_bytes += label_len;
557 reader += label_len;
558 }
559
560 out:
561 /* offset computation:
562 * parse from <name> until finding either NULL or a pointer "c0xx"
563 */
564 reader = name;
565 *offset = 0;
566 while (reader < bufend) {
567 if ((reader[0] & 0xc0) == 0xc0) {
568 *offset += 2;
569 break;
570 }
571 else if (*reader == 0) {
572 *offset += 1;
573 break;
574 }
575 *offset += 1;
576 ++reader;
577 }
578 return nb_bytes;
579
580 err:
581 return 0;
582}
583
Willy Tarreau20751652021-10-18 16:46:38 +0200584/* Reinitialize the list of aborted resolutions before calling certain
585 * functions relying on it. The list must be processed by calling
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100586 * leave_resolver_code() after operations.
Willy Tarreau20751652021-10-18 16:46:38 +0200587 */
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100588static void enter_resolver_code()
Willy Tarreau20751652021-10-18 16:46:38 +0200589{
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100590 if (!recurse)
591 LIST_INIT(&death_row);
592 recurse++;
Willy Tarreau20751652021-10-18 16:46:38 +0200593}
594
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100595/* Add a resolution to the death_row. */
Willy Tarreau20751652021-10-18 16:46:38 +0200596static void abort_resolution(struct resolv_resolution *res)
597{
598 LIST_DEL_INIT(&res->list);
599 LIST_APPEND(&death_row, &res->list);
600}
601
602/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100603 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreau20751652021-10-18 16:46:38 +0200604 * needs to defer deletions. Note that some of them are in relation via internal
605 * objects and might cause the deletion of other ones from the same list, so we
606 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
607 * and solely rely on each call to remove the first remaining list element.
608 */
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100609static void leave_resolver_code()
Willy Tarreau20751652021-10-18 16:46:38 +0200610{
611 struct resolv_resolution *res;
612
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100613 recurse--;
614 if (recurse)
615 return;
616
Willy Tarreau20751652021-10-18 16:46:38 +0200617 while (!LIST_ISEMPTY(&death_row)) {
618 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
619 resolv_free_resolution(res);
620 }
621
622 /* make sure nobody tries to add anything without having initialized it */
623 death_row = (struct list){ };
624}
625
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200626/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
627 * happens when an SRV item is purged or when the server status is considered as
628 * obsolete.
629 *
Willy Tarreau20751652021-10-18 16:46:38 +0200630 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100631 * initialized via enter_resolver_code().
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200632 */
Willy Tarreau20751652021-10-18 16:46:38 +0200633static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200634{
Willy Tarreau33360872021-10-20 14:07:31 +0200635 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200636 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
637 srvrq_update_srv_status(srv, 1);
638 ha_free(&srv->hostname);
639 ha_free(&srv->hostname_dn);
640 srv->hostname_dn_len = 0;
641 memset(&srv->addr, 0, sizeof(srv->addr));
642 srv->svc_port = 0;
643 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Fauleta62d9742021-06-15 16:14:37 +0200644
645 ebpt_delete(&srv->host_dn);
646 ha_free(&srv->host_dn.key);
647
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200648 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200649 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200650 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200651
652 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200653}
654
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200655/* Takes care to cleanup a server resolution when it is outdated. This only
656 * happens for a server relying on a SRV record.
657 */
658static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
659{
660 struct server *srv = context;
661
662 if (!tick_is_expired(t->expire, now_ms))
663 goto end;
664
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100665 enter_resolver_code();
Christopher Faulet152b50c2021-06-18 09:05:49 +0200666 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreau20751652021-10-18 16:46:38 +0200667 resolv_srvrq_cleanup_srv(srv);
Christopher Faulet152b50c2021-06-18 09:05:49 +0200668 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100669 leave_resolver_code();
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200670
671 end:
672 return t;
673}
674
Emeric Brunc9437992021-02-12 19:42:55 +0100675/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100676 * find a corresponding server.
Willy Tarreau20751652021-10-18 16:46:38 +0200677 */
Emeric Brunc9437992021-02-12 19:42:55 +0100678static void resolv_check_response(struct resolv_resolution *res)
679{
680 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100681 struct resolv_requester *req;
Emeric Brunc9437992021-02-12 19:42:55 +0100682 struct resolv_answer_item *item, *itemback;
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200683 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100684 struct resolv_srvrq *srvrq;
685
686 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
687 struct resolv_answer_item *ar_item = item->ar_item;
688
689 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100690 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100691 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
692 * item is also obsolete.
693 */
Emeric Brunc9437992021-02-12 19:42:55 +0100694 pool_free(resolv_answer_item_pool, ar_item);
695 item->ar_item = NULL;
696 }
697
698 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100699 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200700 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100701 /* Remove any associated server */
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200702 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
703 LIST_DEL_INIT(&srv->ip_rec_item);
704 }
705 }
706 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200707 /* Remove any associated server */
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200708 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreau20751652021-10-18 16:46:38 +0200709 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100710 }
711
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200712 LIST_DEL_INIT(&item->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100713 if (item->ar_item) {
714 pool_free(resolv_answer_item_pool, item->ar_item);
715 item->ar_item = NULL;
716 }
717 pool_free(resolv_answer_item_pool, item);
718 continue;
719 }
720
721 if (item->type != DNS_RTYPE_SRV)
722 continue;
723
724 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100725 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200726 struct ebpt_node *node;
727 char target[DNS_MAX_NAME_SIZE+1];
728
729 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100730 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
731 continue;
732
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200733 /* Check if a server already uses that record */
734 srv = NULL;
735 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
736 if (srv->srvrq == srvrq) {
737 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
738 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100739 }
Emeric Brunc9437992021-02-12 19:42:55 +0100740 }
741
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200742
743 /* If not empty we try to match a server
744 * in server state file tree with the same hostname
745 */
746 if (!eb_is_empty(&srvrq->named_servers)) {
747 srv = NULL;
748
749 /* convert the key to lookup in lower case */
Willy Tarreau20a02372021-10-14 22:52:04 +0200750 for (i = 0 ; item->data.target[i] ; i++)
751 target[i] = tolower(item->data.target[i]);
Christopher Fauletc20d6422021-07-22 14:29:26 +0200752 target[i] = 0;
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200753
754 node = ebis_lookup(&srvrq->named_servers, target);
755 if (node) {
756 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100757 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200758
759 /* an entry was found with the same hostname
760 * let check this node if the port matches
761 * and try next node if the hostname
762 * is still the same
763 */
764 while (1) {
765 if (srv->svc_port == item->port) {
766 /* server found, we remove it from tree */
767 ebpt_delete(node);
Christopher Fauleta62d9742021-06-15 16:14:37 +0200768 ha_free(&srv->host_dn.key);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200769 goto srv_found;
770 }
771
772 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
773
774 node = ebpt_next(node);
775 if (!node)
776 break;
777
778 srv = ebpt_entry(node, struct server, host_dn);
779 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
780
781 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau20a02372021-10-14 22:52:04 +0200782 || resolv_hostname_cmp(srv->hostname_dn, item->data.target, item->data_len)) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200783 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
784 break;
785 }
786 }
Emeric Brunc9437992021-02-12 19:42:55 +0100787 }
788 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200789
790 /* Pick the first server listed in srvrq (those ones don't
791 * have hostname and are free to use)
792 */
793 srv = NULL;
794 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
795 LIST_DEL_INIT(&srv->srv_rec_item);
796 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
797 goto srv_found;
798 }
799 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100800
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200801srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100802 /* And update this server, if found (srv is locked here) */
803 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100804 /* re-enable DNS resolution for this server by default */
805 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200806 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100807
Emeric Brunc9437992021-02-12 19:42:55 +0100808 /* Check if an Additional Record is associated to this SRV record.
809 * Perform some sanity checks too to ensure the record can be used.
810 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100811 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100812 */
813 if ((item->ar_item != NULL) &&
814 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100815 {
Emeric Brunc9437992021-02-12 19:42:55 +0100816
817 switch (item->ar_item->type) {
818 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +0200819 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100820 break;
821 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +0200822 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100823 break;
824 }
825
826 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100827
828 /* Unlink A/AAAA resolution for this server if there is an AR item.
829 * It is usless to perform an extra resolution
830 */
Willy Tarreau33360872021-10-20 14:07:31 +0200831 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100832 }
833
834 if (!srv->hostname_dn) {
835 const char *msg = NULL;
Willy Tarreau2859c162021-10-14 08:00:38 +0200836 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100837
Willy Tarreau20a02372021-10-14 22:52:04 +0200838 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau2859c162021-10-14 08:00:38 +0200839 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100840 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
841 continue;
842 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100843 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100844 if (msg)
845 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
846 }
847
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200848 if (!LIST_INLIST(&srv->srv_rec_item))
849 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
850
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100851 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
852 /* If there is no AR item responsible of the FQDN resolution,
853 * trigger a dedicated DNS resolution
854 */
855 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
856 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
857 }
858
Christopher Fauletab177ac2021-03-10 15:34:52 +0100859 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100860 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100861
862 srv->svc_port = item->port;
863 srv->flags &= ~SRV_F_MAPPORTS;
864
865 if (!srv->resolv_opts.ignore_weight) {
866 char weight[9];
867 int ha_weight;
868
869 /* DNS weight range if from 0 to 65535
870 * HAProxy weight is from 0 to 256
871 * The rule below ensures that weight 0 is well respected
872 * while allowing a "mapping" from DNS weight into HAProxy's one.
873 */
874 ha_weight = (item->weight + 255) / 256;
875
876 snprintf(weight, sizeof(weight), "%d", ha_weight);
877 server_parse_weight_change_request(srv, weight);
878 }
879 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
880 }
881 }
882 }
883}
884
885/* Validates that the buffer DNS response provided in <resp> and finishing
886 * before <bufend> is valid from a DNS protocol point of view.
887 *
888 * The result is stored in <resolution>' response, buf_response,
889 * response_query_records and response_answer_records members.
890 *
891 * This function returns one of the RSLV_RESP_* code to indicate the type of
892 * error found.
893 */
894static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
895 struct resolv_resolution *resolution, int max_answer_records)
896{
897 unsigned char *reader;
898 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
899 int len, flags, offset;
900 int query_record_id;
901 int nb_saved_records;
902 struct resolv_query_item *query;
903 struct resolv_answer_item *answer_record, *tmp_record;
904 struct resolv_response *r_res;
905 int i, found = 0;
906 int cause = RSLV_RESP_ERROR;
907
908 reader = resp;
909 len = 0;
910 previous_dname = NULL;
911 query = NULL;
912 answer_record = NULL;
913
914 /* Initialization of response buffer and structure */
915 r_res = &resolution->response;
916
917 /* query id */
918 if (reader + 2 >= bufend)
919 goto invalid_resp;
920
921 r_res->header.id = reader[0] * 256 + reader[1];
922 reader += 2;
923
924 /* Flags and rcode are stored over 2 bytes
925 * First byte contains:
926 * - response flag (1 bit)
927 * - opcode (4 bits)
928 * - authoritative (1 bit)
929 * - truncated (1 bit)
930 * - recursion desired (1 bit)
931 */
932 if (reader + 2 >= bufend)
933 goto invalid_resp;
934
935 flags = reader[0] * 256 + reader[1];
936
937 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
938 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
939 cause = RSLV_RESP_NX_DOMAIN;
940 goto return_error;
941 }
942 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
943 cause = RSLV_RESP_REFUSED;
944 goto return_error;
945 }
946 else {
947 cause = RSLV_RESP_ERROR;
948 goto return_error;
949 }
950 }
951
952 /* Move forward 2 bytes for flags */
953 reader += 2;
954
955 /* 2 bytes for question count */
956 if (reader + 2 >= bufend)
957 goto invalid_resp;
958 r_res->header.qdcount = reader[0] * 256 + reader[1];
959 /* (for now) we send one query only, so we expect only one in the
960 * response too */
961 if (r_res->header.qdcount != 1) {
962 cause = RSLV_RESP_QUERY_COUNT_ERROR;
963 goto return_error;
964 }
965
966 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
967 goto invalid_resp;
968 reader += 2;
969
970 /* 2 bytes for answer count */
971 if (reader + 2 >= bufend)
972 goto invalid_resp;
973 r_res->header.ancount = reader[0] * 256 + reader[1];
974 if (r_res->header.ancount == 0) {
975 cause = RSLV_RESP_ANCOUNT_ZERO;
976 goto return_error;
977 }
978
979 /* Check if too many records are announced */
980 if (r_res->header.ancount > max_answer_records)
981 goto invalid_resp;
982 reader += 2;
983
984 /* 2 bytes authority count */
985 if (reader + 2 >= bufend)
986 goto invalid_resp;
987 r_res->header.nscount = reader[0] * 256 + reader[1];
988 reader += 2;
989
990 /* 2 bytes additional count */
991 if (reader + 2 >= bufend)
992 goto invalid_resp;
993 r_res->header.arcount = reader[0] * 256 + reader[1];
994 reader += 2;
995
996 /* Parsing dns queries */
Willy Tarreau51128f82021-10-19 11:17:33 +0200997 BUG_ON(!LIST_ISEMPTY(&r_res->query_list));
Emeric Brunc9437992021-02-12 19:42:55 +0100998 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
999 /* Use next pre-allocated resolv_query_item after ensuring there is
1000 * still one available.
1001 * It's then added to our packet query list. */
1002 if (query_record_id > DNS_MAX_QUERY_RECORDS)
1003 goto invalid_resp;
1004 query = &resolution->response_query_records[query_record_id];
Willy Tarreau2b718102021-04-21 07:32:39 +02001005 LIST_APPEND(&r_res->query_list, &query->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001006
1007 /* Name is a NULL terminated string in our case, since we have
1008 * one query per response and the first one can't be compressed
1009 * (using the 0x0c format) */
1010 offset = 0;
1011 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
1012
1013 if (len == 0)
1014 goto invalid_resp;
1015
1016 reader += offset;
1017 previous_dname = query->name;
1018
1019 /* move forward 2 bytes for question type */
1020 if (reader + 2 >= bufend)
1021 goto invalid_resp;
1022 query->type = reader[0] * 256 + reader[1];
1023 reader += 2;
1024
1025 /* move forward 2 bytes for question class */
1026 if (reader + 2 >= bufend)
1027 goto invalid_resp;
1028 query->class = reader[0] * 256 + reader[1];
1029 reader += 2;
1030 }
1031
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001032 /* Let's just make gcc happy. The tests above make it clear that
1033 * qdcount==1 hence that we necessarily enter into the loop at least
1034 * once, but gcc seems to be having difficulties following it and
1035 * warns about the risk of NULL dereference at the next line, even
1036 * if a BUG_ON(!query) is used.
1037 */
1038 ALREADY_CHECKED(query);
1039
Emeric Brunc9437992021-02-12 19:42:55 +01001040 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001041 * because a TRUNCATED SRV query type response can still be exploited
1042 */
Emeric Brunc9437992021-02-12 19:42:55 +01001043 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1044 cause = RSLV_RESP_TRUNCATED;
1045 goto return_error;
1046 }
1047
1048 /* now parsing response records */
1049 nb_saved_records = 0;
1050 for (i = 0; i < r_res->header.ancount; i++) {
1051 if (reader >= bufend)
1052 goto invalid_resp;
1053
1054 answer_record = pool_alloc(resolv_answer_item_pool);
1055 if (answer_record == NULL)
1056 goto invalid_resp;
1057
1058 /* initialization */
1059 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001060 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001061 LIST_INIT(&answer_record->attached_servers);
Willy Tarreaua2373e82021-10-19 11:29:21 +02001062 LIST_INIT(&answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001063
1064 offset = 0;
1065 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1066
1067 if (len == 0)
1068 goto invalid_resp;
1069
1070 /* Check if the current record dname is valid. previous_dname
1071 * points either to queried dname or last CNAME target */
1072 if (query->type != DNS_RTYPE_SRV && resolv_hostname_cmp(previous_dname, tmpname, len) != 0) {
1073 if (i == 0) {
1074 /* First record, means a mismatch issue between
1075 * queried dname and dname found in the first
1076 * record */
1077 goto invalid_resp;
1078 }
1079 else {
1080 /* If not the first record, this means we have a
1081 * CNAME resolution error.
1082 */
1083 cause = RSLV_RESP_CNAME_ERROR;
1084 goto return_error;
1085 }
1086
1087 }
1088
1089 memcpy(answer_record->name, tmpname, len);
1090 answer_record->name[len] = 0;
1091
1092 reader += offset;
1093 if (reader >= bufend)
1094 goto invalid_resp;
1095
1096 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1097 if (reader + 2 > bufend)
1098 goto invalid_resp;
1099
1100 answer_record->type = reader[0] * 256 + reader[1];
1101 reader += 2;
1102
1103 /* 2 bytes for class (2) */
1104 if (reader + 2 > bufend)
1105 goto invalid_resp;
1106
1107 answer_record->class = reader[0] * 256 + reader[1];
1108 reader += 2;
1109
1110 /* 4 bytes for ttl (4) */
1111 if (reader + 4 > bufend)
1112 goto invalid_resp;
1113
1114 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1115 + reader[2] * 256 + reader[3];
1116 reader += 4;
1117
1118 /* Now reading data len */
1119 if (reader + 2 > bufend)
1120 goto invalid_resp;
1121
1122 answer_record->data_len = reader[0] * 256 + reader[1];
1123
1124 /* Move forward 2 bytes for data len */
1125 reader += 2;
1126
1127 if (reader + answer_record->data_len > bufend)
1128 goto invalid_resp;
1129
1130 /* Analyzing record content */
1131 switch (answer_record->type) {
1132 case DNS_RTYPE_A:
1133 /* ipv4 is stored on 4 bytes */
1134 if (answer_record->data_len != 4)
1135 goto invalid_resp;
1136
Willy Tarreau20a02372021-10-14 22:52:04 +02001137 answer_record->data.in4.sin_family = AF_INET;
1138 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001139 break;
1140
1141 case DNS_RTYPE_CNAME:
1142 /* Check if this is the last record and update the caller about the status:
1143 * no IP could be found and last record was a CNAME. Could be triggered
1144 * by a wrong query type
1145 *
1146 * + 1 because answer_record_id starts at 0
1147 * while number of answers is an integer and
1148 * starts at 1.
1149 */
1150 if (i + 1 == r_res->header.ancount) {
1151 cause = RSLV_RESP_CNAME_ERROR;
1152 goto return_error;
1153 }
1154
1155 offset = 0;
1156 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1157 if (len == 0)
1158 goto invalid_resp;
1159
Willy Tarreau20a02372021-10-14 22:52:04 +02001160 memcpy(answer_record->data.target, tmpname, len);
1161 answer_record->data.target[len] = 0;
1162 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001163 break;
1164
1165
1166 case DNS_RTYPE_SRV:
1167 /* Answer must contain :
1168 * - 2 bytes for the priority
1169 * - 2 bytes for the weight
1170 * - 2 bytes for the port
1171 * - the target hostname
1172 */
1173 if (answer_record->data_len <= 6)
1174 goto invalid_resp;
1175
1176 answer_record->priority = read_n16(reader);
1177 reader += sizeof(uint16_t);
1178 answer_record->weight = read_n16(reader);
1179 reader += sizeof(uint16_t);
1180 answer_record->port = read_n16(reader);
1181 reader += sizeof(uint16_t);
1182 offset = 0;
1183 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1184 if (len == 0)
1185 goto invalid_resp;
1186
1187 answer_record->data_len = len;
Willy Tarreau20a02372021-10-14 22:52:04 +02001188 memcpy(answer_record->data.target, tmpname, len);
1189 answer_record->data.target[len] = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01001190 if (answer_record->ar_item != NULL) {
1191 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1192 answer_record->ar_item = NULL;
1193 }
1194 break;
1195
1196 case DNS_RTYPE_AAAA:
1197 /* ipv6 is stored on 16 bytes */
1198 if (answer_record->data_len != 16)
1199 goto invalid_resp;
1200
Willy Tarreau20a02372021-10-14 22:52:04 +02001201 answer_record->data.in6.sin6_family = AF_INET6;
1202 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001203 break;
1204
1205 } /* switch (record type) */
1206
1207 /* Increment the counter for number of records saved into our
1208 * local response */
1209 nb_saved_records++;
1210
1211 /* Move forward answer_record->data_len for analyzing next
1212 * record in the response */
1213 reader += ((answer_record->type == DNS_RTYPE_SRV)
1214 ? offset
1215 : answer_record->data_len);
1216
1217 /* Lookup to see if we already had this entry */
1218 found = 0;
1219 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1220 if (tmp_record->type != answer_record->type)
1221 continue;
1222
1223 switch(tmp_record->type) {
1224 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001225 if (!memcmp(&answer_record->data.in4.sin_addr,
1226 &tmp_record->data.in4.sin_addr,
1227 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001228 found = 1;
1229 break;
1230
1231 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001232 if (!memcmp(&answer_record->data.in6.sin6_addr,
1233 &tmp_record->data.in6.sin6_addr,
1234 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001235 found = 1;
1236 break;
1237
1238 case DNS_RTYPE_SRV:
1239 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001240 !resolv_hostname_cmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) &&
Emeric Brunc9437992021-02-12 19:42:55 +01001241 answer_record->port == tmp_record->port) {
1242 tmp_record->weight = answer_record->weight;
1243 found = 1;
1244 }
1245 break;
1246
1247 default:
1248 break;
1249 }
1250
1251 if (found == 1)
1252 break;
1253 }
1254
1255 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001256 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001257 pool_free(resolv_answer_item_pool, answer_record);
1258 answer_record = NULL;
1259 }
1260 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001261 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001262 answer_record->ar_item = NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +02001263 LIST_APPEND(&r_res->answer_list, &answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001264 answer_record = NULL;
1265 }
1266 } /* for i 0 to ancount */
1267
1268 /* Save the number of records we really own */
1269 r_res->header.ancount = nb_saved_records;
1270
1271 /* now parsing additional records for SRV queries only */
1272 if (query->type != DNS_RTYPE_SRV)
1273 goto skip_parsing_additional_records;
1274
1275 /* if we find Authority records, just skip them */
1276 for (i = 0; i < r_res->header.nscount; i++) {
1277 offset = 0;
1278 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1279 &offset, 0);
1280 if (len == 0)
1281 continue;
1282
1283 if (reader + offset + 10 >= bufend)
1284 goto invalid_resp;
1285
1286 reader += offset;
1287 /* skip 2 bytes for class */
1288 reader += 2;
1289 /* skip 2 bytes for type */
1290 reader += 2;
1291 /* skip 4 bytes for ttl */
1292 reader += 4;
1293 /* read data len */
1294 len = reader[0] * 256 + reader[1];
1295 reader += 2;
1296
1297 if (reader + len >= bufend)
1298 goto invalid_resp;
1299
1300 reader += len;
1301 }
1302
1303 nb_saved_records = 0;
1304 for (i = 0; i < r_res->header.arcount; i++) {
1305 if (reader >= bufend)
1306 goto invalid_resp;
1307
1308 answer_record = pool_alloc(resolv_answer_item_pool);
1309 if (answer_record == NULL)
1310 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001311 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001312 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001313
1314 offset = 0;
1315 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1316
1317 if (len == 0) {
1318 pool_free(resolv_answer_item_pool, answer_record);
1319 answer_record = NULL;
1320 continue;
1321 }
1322
1323 memcpy(answer_record->name, tmpname, len);
1324 answer_record->name[len] = 0;
1325
1326 reader += offset;
1327 if (reader >= bufend)
1328 goto invalid_resp;
1329
1330 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1331 if (reader + 2 > bufend)
1332 goto invalid_resp;
1333
1334 answer_record->type = reader[0] * 256 + reader[1];
1335 reader += 2;
1336
1337 /* 2 bytes for class (2) */
1338 if (reader + 2 > bufend)
1339 goto invalid_resp;
1340
1341 answer_record->class = reader[0] * 256 + reader[1];
1342 reader += 2;
1343
1344 /* 4 bytes for ttl (4) */
1345 if (reader + 4 > bufend)
1346 goto invalid_resp;
1347
1348 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1349 + reader[2] * 256 + reader[3];
1350 reader += 4;
1351
1352 /* Now reading data len */
1353 if (reader + 2 > bufend)
1354 goto invalid_resp;
1355
1356 answer_record->data_len = reader[0] * 256 + reader[1];
1357
1358 /* Move forward 2 bytes for data len */
1359 reader += 2;
1360
1361 if (reader + answer_record->data_len > bufend)
1362 goto invalid_resp;
1363
1364 /* Analyzing record content */
1365 switch (answer_record->type) {
1366 case DNS_RTYPE_A:
1367 /* ipv4 is stored on 4 bytes */
1368 if (answer_record->data_len != 4)
1369 goto invalid_resp;
1370
Willy Tarreau20a02372021-10-14 22:52:04 +02001371 answer_record->data.in4.sin_family = AF_INET;
1372 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001373 break;
1374
1375 case DNS_RTYPE_AAAA:
1376 /* ipv6 is stored on 16 bytes */
1377 if (answer_record->data_len != 16)
1378 goto invalid_resp;
1379
Willy Tarreau20a02372021-10-14 22:52:04 +02001380 answer_record->data.in6.sin6_family = AF_INET6;
1381 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001382 break;
1383
1384 default:
1385 pool_free(resolv_answer_item_pool, answer_record);
1386 answer_record = NULL;
1387 continue;
1388
1389 } /* switch (record type) */
1390
1391 /* Increment the counter for number of records saved into our
1392 * local response */
1393 nb_saved_records++;
1394
1395 /* Move forward answer_record->data_len for analyzing next
1396 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001397 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001398
1399 /* Lookup to see if we already had this entry */
1400 found = 0;
1401 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001402 struct resolv_answer_item *ar_item;
1403
1404 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1405 continue;
1406
1407 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001408 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001409 len != tmp_record->data_len ||
Willy Tarreau20a02372021-10-14 22:52:04 +02001410 resolv_hostname_cmp(answer_record->name, tmp_record->data.target, tmp_record->data_len))
Emeric Brunc9437992021-02-12 19:42:55 +01001411 continue;
1412
Christopher Faulet77f86062021-03-10 15:19:57 +01001413 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001414 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001415 if (!memcmp(&answer_record->data.in4.sin_addr,
1416 &ar_item->data.in4.sin_addr,
1417 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001418 found = 1;
1419 break;
1420
1421 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001422 if (!memcmp(&answer_record->data.in6.sin6_addr,
1423 &ar_item->data.in6.sin6_addr,
1424 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001425 found = 1;
1426 break;
1427
1428 default:
1429 break;
1430 }
1431
1432 if (found == 1)
1433 break;
1434 }
1435
1436 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001437 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001438 pool_free(resolv_answer_item_pool, answer_record);
1439 answer_record = NULL;
1440 }
1441 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001442 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001443 answer_record->ar_item = NULL;
1444
1445 // looking for the SRV record in the response list linked to this additional record
1446 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1447 if (tmp_record->type == DNS_RTYPE_SRV &&
1448 tmp_record->ar_item == NULL &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001449 !resolv_hostname_cmp(tmp_record->data.target, answer_record->name, tmp_record->data_len)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001450 /* Always use the received additional record to refresh info */
1451 if (tmp_record->ar_item)
1452 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1453 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001454 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001455 break;
1456 }
1457 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001458 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001459 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001460 answer_record = NULL;
1461 }
Emeric Brunc9437992021-02-12 19:42:55 +01001462 }
1463 } /* for i 0 to arcount */
1464
1465 skip_parsing_additional_records:
1466
1467 /* Save the number of records we really own */
1468 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001469 resolv_check_response(resolution);
1470 return RSLV_RESP_VALID;
1471
1472 invalid_resp:
1473 cause = RSLV_RESP_INVALID;
1474
1475 return_error:
Christopher Faulet67f6af52021-12-01 10:18:08 +01001476 if (query)
1477 LIST_DEL_INIT(&query->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001478 pool_free(resolv_answer_item_pool, answer_record);
1479 return cause;
1480}
1481
1482/* Searches dn_name resolution in resp.
1483 * If existing IP not found, return the first IP matching family_priority,
1484 * otherwise, first ip found
1485 * The following tasks are the responsibility of the caller:
1486 * - <r_res> contains an error free DNS response
1487 * For both cases above, resolv_validate_dns_response is required
1488 * returns one of the RSLV_UPD_* code
1489 */
1490int resolv_get_ip_from_response(struct resolv_response *r_res,
1491 struct resolv_options *resolv_opts, void *currentip,
1492 short currentip_sin_family,
1493 void **newip, short *newip_sin_family,
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001494 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001495{
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001496 struct resolv_answer_item *record, *found_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001497 int family_priority;
1498 int currentip_found;
1499 unsigned char *newip4, *newip6;
1500 int currentip_sel;
1501 int j;
1502 int score, max_score;
1503 int allowed_duplicated_ip;
1504
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001505 /* srv is linked to an alive ip record */
1506 if (owner && LIST_INLIST(&owner->ip_rec_item))
1507 return RSLV_UPD_NO;
1508
Emeric Brunc9437992021-02-12 19:42:55 +01001509 family_priority = resolv_opts->family_prio;
1510 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1511 *newip = newip4 = newip6 = NULL;
1512 currentip_found = 0;
1513 *newip_sin_family = AF_UNSPEC;
1514 max_score = -1;
1515
1516 /* Select an IP regarding configuration preference.
1517 * Top priority is the preferred network ip version,
1518 * second priority is the preferred network.
1519 * the last priority is the currently used IP,
1520 *
1521 * For these three priorities, a score is calculated. The
1522 * weight are:
1523 * 8 - preferred ip version.
1524 * 4 - preferred network.
1525 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1526 * 1 - current ip.
1527 * The result with the biggest score is returned.
1528 */
1529
1530 list_for_each_entry(record, &r_res->answer_list, list) {
1531 void *ip;
1532 unsigned char ip_type;
1533
1534 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001535 ip_type = AF_INET;
Willy Tarreau20a02372021-10-14 22:52:04 +02001536 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001537 }
1538 else if (record->type == DNS_RTYPE_AAAA) {
1539 ip_type = AF_INET6;
Willy Tarreau20a02372021-10-14 22:52:04 +02001540 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001541 }
1542 else
1543 continue;
1544 score = 0;
1545
1546 /* Check for preferred ip protocol. */
1547 if (ip_type == family_priority)
1548 score += 8;
1549
1550 /* Check for preferred network. */
1551 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1552
1553 /* Compare only the same addresses class. */
1554 if (resolv_opts->pref_net[j].family != ip_type)
1555 continue;
1556
1557 if ((ip_type == AF_INET &&
1558 in_net_ipv4(ip,
1559 &resolv_opts->pref_net[j].mask.in4,
1560 &resolv_opts->pref_net[j].addr.in4)) ||
1561 (ip_type == AF_INET6 &&
1562 in_net_ipv6(ip,
1563 &resolv_opts->pref_net[j].mask.in6,
1564 &resolv_opts->pref_net[j].addr.in6))) {
1565 score += 4;
1566 break;
1567 }
1568 }
1569
1570 /* Check if the IP found in the record is already affected to a
1571 * member of a group. If not, the score should be incremented
1572 * by 2. */
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001573 if (owner) {
1574 struct server *srv;
1575 int already_used = 0;
1576
1577 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1578 if (srv == owner)
1579 continue;
1580 if (srv->proxy == owner->proxy) {
1581 already_used = 1;
1582 break;
1583 }
1584 }
1585 if (already_used) {
1586 if (!allowed_duplicated_ip) {
1587 continue;
1588 }
1589 }
1590 else {
1591 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001592 }
1593 } else {
1594 score += 2;
1595 }
1596
1597 /* Check for current ip matching. */
1598 if (ip_type == currentip_sin_family &&
1599 ((currentip_sin_family == AF_INET &&
1600 !memcmp(ip, currentip, 4)) ||
1601 (currentip_sin_family == AF_INET6 &&
1602 !memcmp(ip, currentip, 16)))) {
1603 score++;
1604 currentip_sel = 1;
1605 }
1606 else
1607 currentip_sel = 0;
1608
1609 /* Keep the address if the score is better than the previous
1610 * score. The maximum score is 15, if this value is reached, we
1611 * break the parsing. Implicitly, this score is reached the ip
1612 * selected is the current ip. */
1613 if (score > max_score) {
1614 if (ip_type == AF_INET)
1615 newip4 = ip;
1616 else
1617 newip6 = ip;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001618 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001619 currentip_found = currentip_sel;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001620 if (score == 15) {
1621 /* this was not registered on the current record but it matches
1622 * let's fix it (it may comes from state file */
1623 if (owner)
1624 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001625 return RSLV_UPD_NO;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001626 }
Emeric Brunc9437992021-02-12 19:42:55 +01001627 max_score = score;
1628 }
1629 } /* list for each record entries */
1630
1631 /* No IP found in the response */
1632 if (!newip4 && !newip6)
1633 return RSLV_UPD_NO_IP_FOUND;
1634
1635 /* Case when the caller looks first for an IPv4 address */
1636 if (family_priority == AF_INET) {
1637 if (newip4) {
1638 *newip = newip4;
1639 *newip_sin_family = AF_INET;
1640 }
1641 else if (newip6) {
1642 *newip = newip6;
1643 *newip_sin_family = AF_INET6;
1644 }
Emeric Brunc9437992021-02-12 19:42:55 +01001645 }
1646 /* Case when the caller looks first for an IPv6 address */
1647 else if (family_priority == AF_INET6) {
1648 if (newip6) {
1649 *newip = newip6;
1650 *newip_sin_family = AF_INET6;
1651 }
1652 else if (newip4) {
1653 *newip = newip4;
1654 *newip_sin_family = AF_INET;
1655 }
Emeric Brunc9437992021-02-12 19:42:55 +01001656 }
1657 /* Case when the caller have no preference (we prefer IPv6) */
1658 else if (family_priority == AF_UNSPEC) {
1659 if (newip6) {
1660 *newip = newip6;
1661 *newip_sin_family = AF_INET6;
1662 }
1663 else if (newip4) {
1664 *newip = newip4;
1665 *newip_sin_family = AF_INET;
1666 }
Emeric Brunc9437992021-02-12 19:42:55 +01001667 }
1668
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001669 /* the ip of this record was chosen for the server */
1670 if (owner && found_record) {
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001671 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001672 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1673 }
1674
Emeric Brunc9437992021-02-12 19:42:55 +01001675 list_for_each_entry(record, &r_res->answer_list, list) {
1676 /* Move the first record to the end of the list, for internal
1677 * round robin */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001678 LIST_DEL_INIT(&record->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02001679 LIST_APPEND(&r_res->answer_list, &record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001680 break;
1681 }
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001682
1683 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001684}
1685
Willy Tarreauca0170b2021-10-14 08:05:25 +02001686/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001687 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001688 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1689 * null-terminated. <str> must be allocated large enough to contain a full host
1690 * name plus the trailing zero, and the allocated size must be passed in
1691 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001692 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001693 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001694 * <str> (including the terminating null byte).
1695 */
1696int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1697{
1698 char *ptr;
1699 int i, sz;
1700
Willy Tarreauca0170b2021-10-14 08:05:25 +02001701 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001702 return -1;
1703
1704 ptr = str;
Willy Tarreauca0170b2021-10-14 08:05:25 +02001705 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001706 sz = dn[i];
1707 if (i)
1708 *ptr++ = '.';
1709 memcpy(ptr, dn+i+1, sz);
1710 ptr += sz;
1711 i += sz;
1712 }
1713 *ptr++ = '\0';
1714 return (ptr - str);
1715}
1716
1717/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1718 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001719 * <str> contains the input string that is <str_len> bytes long (trailing zero
1720 * not needed). <dn> buffer must be allocated large enough to contain the
1721 * encoded string and a trailing zero, so it must be at least str_len+2, and
1722 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001723 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001724 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001725 * <dn> (excluding the terminating null byte).
1726 */
1727int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1728{
1729 int i, offset;
1730
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001731 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001732 return -1;
1733
1734 /* First byte of dn will be used to store the length of the first
1735 * label */
1736 offset = 0;
1737 for (i = 0; i < str_len; ++i) {
1738 if (str[i] == '.') {
1739 /* 2 or more consecutive dots is invalid */
1740 if (i == offset)
1741 return -1;
1742
1743 /* ignore trailing dot */
Christopher Faulet5c3e6862022-01-28 17:47:57 +01001744 if (i + 1 == str_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001745 break;
Emeric Brunc9437992021-02-12 19:42:55 +01001746
1747 dn[offset] = (i - offset);
1748 offset = i+1;
1749 continue;
1750 }
1751 dn[i+1] = str[i];
1752 }
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001753 dn[offset] = i - offset;
Willy Tarreau68c7b362021-10-15 08:09:25 +02001754 dn[i+1] = '\0';
1755 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001756}
1757
1758/* Validates host name:
1759 * - total size
1760 * - each label size individually
1761 * returns:
1762 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1763 * 1 when no error. <err> is left unaffected.
1764 */
1765int resolv_hostname_validation(const char *string, char **err)
1766{
1767 int i;
1768
1769 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1770 if (err)
1771 *err = DNS_TOO_LONG_FQDN;
1772 return 0;
1773 }
1774
1775 while (*string) {
1776 i = 0;
1777 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1778 if (!(*string == '-' || *string == '_' ||
1779 (*string >= 'a' && *string <= 'z') ||
1780 (*string >= 'A' && *string <= 'Z') ||
1781 (*string >= '0' && *string <= '9'))) {
1782 if (err)
1783 *err = DNS_INVALID_CHARACTER;
1784 return 0;
1785 }
1786 i++;
1787 string++;
1788 }
1789
1790 if (!(*string))
1791 break;
1792
1793 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1794 if (err)
1795 *err = DNS_LABEL_TOO_LONG;
1796 return 0;
1797 }
1798
1799 string++;
1800 }
1801 return 1;
1802}
1803
1804/* Picks up an available resolution from the different resolution list
1805 * associated to a resolvers section, in this order:
1806 * 1. check in resolutions.curr for the same hostname and query_type
1807 * 2. check in resolutions.wait for the same hostname and query_type
1808 * 3. Get a new resolution from resolution pool
1809 *
1810 * Returns an available resolution, NULL if none found.
1811 */
1812static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1813 char **hostname_dn, int hostname_dn_len,
1814 int query_type)
1815{
1816 struct resolv_resolution *res;
1817
1818 if (!*hostname_dn)
1819 goto from_pool;
1820
1821 /* Search for same hostname and query type in resolutions.curr */
1822 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1823 if (!res->hostname_dn)
1824 continue;
1825 if ((query_type == res->prefered_query_type) &&
1826 hostname_dn_len == res->hostname_dn_len &&
1827 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1828 return res;
1829 }
1830
1831 /* Search for same hostname and query type in resolutions.wait */
1832 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1833 if (!res->hostname_dn)
1834 continue;
1835 if ((query_type == res->prefered_query_type) &&
1836 hostname_dn_len == res->hostname_dn_len &&
1837 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1838 return res;
1839 }
1840
1841 from_pool:
1842 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001843 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001844 if (res) {
Willy Tarreau51128f82021-10-19 11:17:33 +02001845 int i;
1846
Emeric Brunc9437992021-02-12 19:42:55 +01001847 res->resolvers = resolvers;
1848 res->uuid = resolution_uuid;
1849 res->status = RSLV_STATUS_NONE;
1850 res->step = RSLV_STEP_NONE;
1851 res->last_valid = now_ms;
1852
1853 LIST_INIT(&res->requesters);
Willy Tarreau51128f82021-10-19 11:17:33 +02001854 LIST_INIT(&res->response.query_list);
Emeric Brunc9437992021-02-12 19:42:55 +01001855 LIST_INIT(&res->response.answer_list);
1856
Willy Tarreau51128f82021-10-19 11:17:33 +02001857 for (i = 0; i < DNS_MAX_QUERY_RECORDS; i++)
1858 LIST_INIT(&res->response_query_records[i].list);
1859
Emeric Brunc9437992021-02-12 19:42:55 +01001860 res->prefered_query_type = query_type;
1861 res->query_type = query_type;
1862 res->hostname_dn = *hostname_dn;
1863 res->hostname_dn_len = hostname_dn_len;
1864
1865 ++resolution_uuid;
1866
1867 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001868 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001869 }
1870 return res;
1871}
1872
Willy Tarreauaab75932021-10-19 11:16:11 +02001873/* deletes and frees all answer_items from the resolution's answer_list */
1874static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001875{
1876 struct resolv_answer_item *item, *itemback;
1877
1878 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001879 LIST_DEL_INIT(&item->list);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001880 pool_free(resolv_answer_item_pool, item->ar_item);
1881 pool_free(resolv_answer_item_pool, item);
1882 }
1883}
1884
Willy Tarreau51128f82021-10-19 11:17:33 +02001885/* deletes all query_items from the resolution's query_list */
1886static void resolv_purge_resolution_query_items(struct resolv_resolution *resolution)
1887{
1888 struct resolv_query_item *item, *itemback;
1889
1890 list_for_each_entry_safe(item, itemback, &resolution->response.query_list, list)
1891 LIST_DEL_INIT(&item->list);
1892}
1893
Emeric Brunc9437992021-02-12 19:42:55 +01001894/* Releases a resolution from its requester(s) and move it back to the pool */
1895static void resolv_free_resolution(struct resolv_resolution *resolution)
1896{
1897 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001898
1899 /* clean up configuration */
1900 resolv_reset_resolution(resolution);
1901 resolution->hostname_dn = NULL;
1902 resolution->hostname_dn_len = 0;
1903
1904 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001905 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001906 req->resolution = NULL;
1907 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001908 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau51128f82021-10-19 11:17:33 +02001909 resolv_purge_resolution_query_items(resolution);
1910
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001911 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001912 pool_free(resolv_resolution_pool, resolution);
1913}
1914
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001915/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1916 * and makes it owned by this obj_type, with the proposed callback and error
1917 * callback. On success, *req is assigned the allocated requester. Returns
1918 * NULL on allocation failure.
1919 */
1920static struct resolv_requester *
1921resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1922 int (*cb)(struct resolv_requester *, struct dns_counters *),
1923 int (*err_cb)(struct resolv_requester *, int))
1924{
1925 struct resolv_requester *tmp;
1926
1927 if (*req)
1928 return *req;
1929
1930 tmp = pool_alloc(resolv_requester_pool);
1931 if (!tmp)
1932 goto end;
1933
1934 LIST_INIT(&tmp->list);
1935 tmp->owner = owner;
1936 tmp->resolution = NULL;
1937 tmp->requester_cb = cb;
1938 tmp->requester_error_cb = err_cb;
1939 *req = tmp;
1940 end:
1941 return tmp;
1942}
1943
Emeric Brunc9437992021-02-12 19:42:55 +01001944/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet7a3a5362021-11-02 16:25:05 +01001945 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001946 */
1947int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1948{
1949 struct resolv_resolution *res = NULL;
1950 struct resolv_requester *req;
1951 struct resolvers *resolvers;
1952 struct server *srv = NULL;
1953 struct resolv_srvrq *srvrq = NULL;
1954 struct stream *stream = NULL;
1955 char **hostname_dn;
1956 int hostname_dn_len, query_type;
1957
Christopher Faulet7a3a5362021-11-02 16:25:05 +01001958 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001959 switch (requester_type) {
1960 case OBJ_TYPE_SERVER:
1961 srv = (struct server *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001962
1963 if (!requester_locked)
1964 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1965
1966 req = resolv_get_requester(&srv->resolv_requester,
1967 &srv->obj_type,
1968 snr_resolution_cb,
1969 snr_resolution_error_cb);
1970
1971 if (!requester_locked)
1972 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1973
1974 if (!req)
1975 goto err;
1976
Emeric Brunc9437992021-02-12 19:42:55 +01001977 hostname_dn = &srv->hostname_dn;
1978 hostname_dn_len = srv->hostname_dn_len;
1979 resolvers = srv->resolvers;
1980 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1981 ? DNS_RTYPE_A
1982 : DNS_RTYPE_AAAA);
1983 break;
1984
1985 case OBJ_TYPE_SRVRQ:
1986 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001987
1988 req = resolv_get_requester(&srvrq->requester,
1989 &srvrq->obj_type,
1990 snr_resolution_cb,
1991 srvrq_resolution_error_cb);
1992 if (!req)
1993 goto err;
1994
Emeric Brunc9437992021-02-12 19:42:55 +01001995 hostname_dn = &srvrq->hostname_dn;
1996 hostname_dn_len = srvrq->hostname_dn_len;
1997 resolvers = srvrq->resolvers;
1998 query_type = DNS_RTYPE_SRV;
1999 break;
2000
2001 case OBJ_TYPE_STREAM:
2002 stream = (struct stream *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02002003
2004 req = resolv_get_requester(&stream->resolv_ctx.requester,
2005 &stream->obj_type,
2006 act_resolution_cb,
2007 act_resolution_error_cb);
2008 if (!req)
2009 goto err;
2010
Emeric Brunc9437992021-02-12 19:42:55 +01002011 hostname_dn = &stream->resolv_ctx.hostname_dn;
2012 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2013 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2014 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2015 ? DNS_RTYPE_A
2016 : DNS_RTYPE_AAAA);
2017 break;
2018 default:
2019 goto err;
2020 }
2021
2022 /* Get a resolution from the resolvers' wait queue or pool */
2023 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2024 goto err;
2025
Willy Tarreau4d7ca912021-10-19 11:59:25 +02002026 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002027
Willy Tarreau2b718102021-04-21 07:32:39 +02002028 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002029 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002030 return 0;
2031
2032 err:
2033 if (res && LIST_ISEMPTY(&res->requesters))
2034 resolv_free_resolution(res);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002035 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002036 return -1;
2037}
2038
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002039/* This function removes all server/srvrq references on answer items. */
Willy Tarreau33360872021-10-20 14:07:31 +02002040void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002041{
2042 struct resolv_answer_item *item, *itemback;
2043 struct server *srv, *srvback;
2044 struct resolv_srvrq *srvrq;
2045
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002046 enter_resolver_code();
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002047 if ((srv = objt_server(req->owner)) != NULL) {
2048 LIST_DEL_INIT(&srv->ip_rec_item);
2049 }
2050 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
2051 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
2052 if (item->type == DNS_RTYPE_SRV) {
2053 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet5f8ccff2021-06-15 16:08:48 +02002054 if (srv->srvrq == srvrq)
Willy Tarreau20751652021-10-18 16:46:38 +02002055 resolv_srvrq_cleanup_srv(srv);
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002056 }
2057 }
2058 }
2059 }
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002060 leave_resolver_code();
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002061}
2062
Emeric Brunc9437992021-02-12 19:42:55 +01002063/* Removes a requester from a DNS resolution. It takes takes care of all the
2064 * consequences. It also cleans up some parameters from the requester.
2065 */
Willy Tarreau33360872021-10-20 14:07:31 +02002066static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002067{
2068 struct resolv_resolution *res;
2069 struct resolv_requester *req;
2070
2071 /* Nothing to do */
2072 if (!requester || !requester->resolution)
2073 return;
2074 res = requester->resolution;
2075
2076 /* Clean up the requester */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002077 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002078 requester->resolution = NULL;
2079
Christopher Faulete7e0e4b2021-10-29 10:38:15 +02002080 /* remove ref from the resolution answer item list to the requester */
2081 resolv_detach_from_resolution_answer_items(res, requester);
2082
Emeric Brunc9437992021-02-12 19:42:55 +01002083 /* We need to find another requester linked on this resolution */
2084 if (!LIST_ISEMPTY(&res->requesters))
2085 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2086 else {
Willy Tarreau20751652021-10-18 16:46:38 +02002087 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002088 return;
2089 }
2090
2091 /* Move hostname_dn related pointers to the next requester */
2092 switch (obj_type(req->owner)) {
2093 case OBJ_TYPE_SERVER:
2094 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2095 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2096 break;
2097 case OBJ_TYPE_SRVRQ:
2098 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2099 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2100 break;
2101 case OBJ_TYPE_STREAM:
2102 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2103 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2104 break;
2105 default:
2106 res->hostname_dn = NULL;
2107 res->hostname_dn_len = 0;
2108 break;
2109 }
2110}
2111
Willy Tarreau20751652021-10-18 16:46:38 +02002112/* The public version of the function above that deals with the death row. */
Willy Tarreau33360872021-10-20 14:07:31 +02002113void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreau20751652021-10-18 16:46:38 +02002114{
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002115 enter_resolver_code();
Willy Tarreau33360872021-10-20 14:07:31 +02002116 _resolv_unlink_resolution(requester);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002117 leave_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002118}
2119
Emeric Brunc9437992021-02-12 19:42:55 +01002120/* Called when a network IO is generated on a name server socket for an incoming
2121 * packet. It performs the following actions:
2122 * - check if the packet requires processing (not outdated resolution)
2123 * - ensure the DNS packet received is valid and call requester's callback
2124 * - call requester's error callback if invalid response
2125 * - check the dn_name in the packet against the one sent
2126 */
2127static int resolv_process_responses(struct dns_nameserver *ns)
2128{
2129 struct dns_counters *tmpcounters;
2130 struct resolvers *resolvers;
2131 struct resolv_resolution *res;
2132 struct resolv_query_item *query;
2133 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2134 unsigned char *bufend;
2135 int buflen, dns_resp;
2136 int max_answer_records;
2137 unsigned short query_id;
2138 struct eb32_node *eb;
2139 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002140 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002141
2142 resolvers = ns->parent;
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002143 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002144 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2145
2146 /* process all pending input messages */
2147 while (1) {
2148 /* read message received */
2149 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2150 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2151 break;
2152 }
2153
2154 /* message too big */
2155 if (buflen > resolvers->accepted_payload_size) {
2156 ns->counters->too_big++;
2157 continue;
2158 }
2159
2160 /* initializing variables */
2161 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2162
2163 /* read the query id from the packet (16 bits) */
2164 if (buf + 2 > bufend) {
2165 ns->counters->invalid++;
2166 continue;
2167 }
2168 query_id = resolv_response_get_query_id(buf);
2169
2170 /* search the query_id in the pending resolution tree */
2171 eb = eb32_lookup(&resolvers->query_ids, query_id);
2172 if (eb == NULL) {
2173 /* unknown query id means an outdated response and can be safely ignored */
2174 ns->counters->outdated++;
2175 continue;
2176 }
2177
2178 /* known query id means a resolution in progress */
2179 res = eb32_entry(eb, struct resolv_resolution, qid);
2180 /* number of responses received */
2181 res->nb_responses++;
2182
2183 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2184 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2185
2186 switch (dns_resp) {
2187 case RSLV_RESP_VALID:
2188 break;
2189
2190 case RSLV_RESP_INVALID:
2191 case RSLV_RESP_QUERY_COUNT_ERROR:
2192 case RSLV_RESP_WRONG_NAME:
2193 res->status = RSLV_STATUS_INVALID;
2194 ns->counters->invalid++;
2195 break;
2196
2197 case RSLV_RESP_NX_DOMAIN:
2198 res->status = RSLV_STATUS_NX;
2199 ns->counters->nx++;
2200 break;
2201
2202 case RSLV_RESP_REFUSED:
2203 res->status = RSLV_STATUS_REFUSED;
2204 ns->counters->refused++;
2205 break;
2206
2207 case RSLV_RESP_ANCOUNT_ZERO:
2208 res->status = RSLV_STATUS_OTHER;
2209 ns->counters->any_err++;
2210 break;
2211
2212 case RSLV_RESP_CNAME_ERROR:
2213 res->status = RSLV_STATUS_OTHER;
2214 ns->counters->cname_error++;
2215 break;
2216
2217 case RSLV_RESP_TRUNCATED:
2218 res->status = RSLV_STATUS_OTHER;
2219 ns->counters->truncated++;
2220 break;
2221
2222 case RSLV_RESP_NO_EXPECTED_RECORD:
2223 case RSLV_RESP_ERROR:
2224 case RSLV_RESP_INTERNAL:
2225 res->status = RSLV_STATUS_OTHER;
2226 ns->counters->other++;
2227 break;
2228 }
2229
2230 /* Wait all nameservers response to handle errors */
2231 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2232 continue;
2233
2234 /* Process error codes */
2235 if (dns_resp != RSLV_RESP_VALID) {
2236 if (res->prefered_query_type != res->query_type) {
2237 /* The fallback on the query type was already performed,
2238 * so check the try counter. If it falls to 0, we can
2239 * report an error. Else, wait the next attempt. */
2240 if (!res->try)
2241 goto report_res_error;
2242 }
2243 else {
2244 /* Fallback from A to AAAA or the opposite and re-send
2245 * the resolution immediately. try counter is not
2246 * decremented. */
2247 if (res->prefered_query_type == DNS_RTYPE_A) {
2248 res->query_type = DNS_RTYPE_AAAA;
2249 resolv_send_query(res);
2250 }
2251 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2252 res->query_type = DNS_RTYPE_A;
2253 resolv_send_query(res);
2254 }
2255 }
2256 continue;
2257 }
2258
2259 /* Now let's check the query's dname corresponds to the one we
2260 * sent. We can check only the first query of the list. We send
Willy Tarreau51128f82021-10-19 11:17:33 +02002261 * one query at a time so we get one query in the response.
2262 */
2263 if (!LIST_ISEMPTY(&res->response.query_list)) {
2264 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
2265 LIST_DEL_INIT(&query->list);
2266 if (resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
2267 dns_resp = RSLV_RESP_WRONG_NAME;
2268 ns->counters->other++;
2269 goto report_res_error;
2270 }
Emeric Brunc9437992021-02-12 19:42:55 +01002271 }
2272
2273 /* So the resolution succeeded */
2274 res->status = RSLV_STATUS_VALID;
2275 res->last_valid = now_ms;
2276 ns->counters->valid++;
2277 goto report_res_success;
2278
2279 report_res_error:
Emeric Brun43839d02021-06-10 15:25:25 +02002280 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002281 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002282 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2283 if (!keep_answer_items)
2284 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002285 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002286 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002287 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002288 continue;
2289
2290 report_res_success:
2291 /* Only the 1rst requester s managed by the server, others are
2292 * from the cache */
2293 tmpcounters = ns->counters;
2294 list_for_each_entry(req, &res->requesters, list) {
2295 struct server *s = objt_server(req->owner);
2296
2297 if (s)
2298 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2299 req->requester_cb(req, tmpcounters);
2300 if (s)
2301 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2302 tmpcounters = NULL;
2303 }
2304
2305 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002306 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002307 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002308 continue;
2309 }
2310 resolv_update_resolvers_timeout(resolvers);
2311 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002312 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002313 return buflen;
2314}
2315
2316/* Processes DNS resolution. First, it checks the active list to detect expired
2317 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2318 * checks the wait list to trigger new resolutions.
2319 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002320static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002321{
2322 struct resolvers *resolvers = context;
2323 struct resolv_resolution *res, *resback;
2324 int exp;
2325
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002326 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002327 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2328
Willy Tarreau20751652021-10-18 16:46:38 +02002329 /* Handle all expired resolutions from the active list. Elements that
2330 * need to be removed will in fact be moved to the death_row. Other
2331 * ones will be handled normally.
2332 */
2333
Willy Tarreau20751652021-10-18 16:46:38 +02002334 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2335 while (&res->list != &resolvers->resolutions.curr) {
2336 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2337
Christopher Faulet0efc0992021-03-11 18:09:53 +01002338 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002339 abort_resolution(res);
2340 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002341 continue;
2342 }
2343
Emeric Brunc9437992021-02-12 19:42:55 +01002344 /* When we find the first resolution in the future, then we can
2345 * stop here */
2346 exp = tick_add(res->last_query, resolvers->timeout.retry);
2347 if (!tick_is_expired(exp, now_ms))
2348 break;
2349
2350 /* If current resolution has been tried too many times and
2351 * finishes in timeout we update its status and remove it from
2352 * the list */
2353 if (!res->try) {
2354 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002355 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002356
2357 /* Notify the result to the requesters */
2358 if (!res->nb_responses)
2359 res->status = RSLV_STATUS_TIMEOUT;
2360 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002361 keep_answer_items |= req->requester_error_cb(req, res->status);
2362 if (!keep_answer_items)
2363 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002364
2365 /* Clean up resolution info and remove it from the
2366 * current list */
2367 resolv_reset_resolution(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002368
2369 /* subsequent entries might have been deleted here */
2370 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002371 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002372 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreau20751652021-10-18 16:46:38 +02002373 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002374 }
2375 else {
2376 /* Otherwise resend the DNS query and requeue the resolution */
2377 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2378 /* No response received (a real timeout) or fallback already done */
2379 res->query_type = res->prefered_query_type;
2380 res->try--;
2381 }
2382 else {
2383 /* Fallback from A to AAAA or the opposite and re-send
2384 * the resolution immediately. try counter is not
2385 * decremented. */
2386 if (res->prefered_query_type == DNS_RTYPE_A)
2387 res->query_type = DNS_RTYPE_AAAA;
2388 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2389 res->query_type = DNS_RTYPE_A;
2390 else
2391 res->try--;
2392 }
2393 resolv_send_query(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002394 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2395 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002396 }
2397 }
2398
2399 /* Handle all resolutions in the wait list */
2400 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002401 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002402 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002403 continue;
2404 }
2405
Emeric Brunc9437992021-02-12 19:42:55 +01002406 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2407 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2408 continue;
2409
2410 if (resolv_run_resolution(res) != 1) {
2411 res->last_resolution = now_ms;
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002412 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002413 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002414 }
2415 }
Emeric Brunc9437992021-02-12 19:42:55 +01002416 resolv_update_resolvers_timeout(resolvers);
2417 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002418
2419 /* now we can purge all queued deletions */
2420 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002421 return t;
2422}
2423
2424/* Release memory allocated by DNS */
2425static void resolvers_deinit(void)
2426{
2427 struct resolvers *resolvers, *resolversback;
2428 struct dns_nameserver *ns, *nsback;
2429 struct resolv_resolution *res, *resback;
2430 struct resolv_requester *req, *reqback;
2431 struct resolv_srvrq *srvrq, *srvrqback;
2432
2433 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2434 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2435 free(ns->id);
2436 free((char *)ns->conf.file);
2437 if (ns->dgram) {
2438 if (ns->dgram->conn.t.sock.fd != -1) {
2439 fd_delete(ns->dgram->conn.t.sock.fd);
2440 close(ns->dgram->conn.t.sock.fd);
2441 }
2442 if (ns->dgram->ring_req)
2443 ring_free(ns->dgram->ring_req);
2444 free(ns->dgram);
2445 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002446 if (ns->stream) {
2447 if (ns->stream->ring_req)
2448 ring_free(ns->stream->ring_req);
2449 if (ns->stream->task_req)
2450 task_destroy(ns->stream->task_req);
2451 if (ns->stream->task_rsp)
2452 task_destroy(ns->stream->task_rsp);
2453 free(ns->stream);
2454 }
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002455 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002456 EXTRA_COUNTERS_FREE(ns->extra_counters);
2457 free(ns);
2458 }
2459
2460 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2461 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002462 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002463 pool_free(resolv_requester_pool, req);
2464 }
Christopher Faulet53df5172022-05-24 18:10:42 +02002465 resolv_free_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002466 }
2467
2468 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2469 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002470 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002471 pool_free(resolv_requester_pool, req);
2472 }
Christopher Faulet53df5172022-05-24 18:10:42 +02002473 resolv_free_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002474 }
2475
Tim Duesterhus7c718222022-04-26 23:28:47 +02002476 free_proxy(resolvers->px);
Emeric Brunc9437992021-02-12 19:42:55 +01002477 free(resolvers->id);
2478 free((char *)resolvers->conf.file);
2479 task_destroy(resolvers->t);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002480 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002481 free(resolvers);
2482 }
2483
2484 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2485 free(srvrq->name);
2486 free(srvrq->hostname_dn);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002487 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002488 free(srvrq);
2489 }
2490}
2491
2492/* Finalizes the DNS configuration by allocating required resources and checking
2493 * live parameters.
William Lallemand15bdf582022-08-24 09:58:31 +02002494 * Returns 0 on success, 1 on error.
Emeric Brunc9437992021-02-12 19:42:55 +01002495 */
2496static int resolvers_finalize_config(void)
2497{
2498 struct resolvers *resolvers;
2499 struct proxy *px;
2500 int err_code = 0;
2501
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002502 enter_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002503
Emeric Brunc9437992021-02-12 19:42:55 +01002504 /* allocate pool of resolution per resolvers */
2505 list_for_each_entry(resolvers, &sec_resolvers, list) {
2506 struct dns_nameserver *ns;
2507 struct task *t;
2508
2509 /* Check if we can create the socket with nameservers info */
2510 list_for_each_entry(ns, &resolvers->nameservers, list) {
2511 int fd;
2512
2513 if (ns->dgram) {
2514 /* Check nameserver info */
2515 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
2516 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2517 resolvers->id, ns->id);
2518 err_code |= (ERR_ALERT|ERR_ABORT);
2519 continue;
2520 }
2521 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
2522 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2523 resolvers->id, ns->id);
2524 close(fd);
2525 err_code |= (ERR_ALERT|ERR_ABORT);
2526 continue;
2527 }
2528 close(fd);
2529 }
2530 }
2531
2532 /* Create the task associated to the resolvers section */
2533 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2534 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
2535 err_code |= (ERR_ALERT|ERR_ABORT);
2536 goto err;
2537 }
2538
2539 /* Update task's parameters */
2540 t->process = process_resolvers;
2541 t->context = resolvers;
2542 resolvers->t = t;
2543 task_wakeup(t, TASK_WOKEN_INIT);
2544 }
2545
2546 for (px = proxies_list; px; px = px->next) {
2547 struct server *srv;
2548
Willy Tarreau2da308e2022-06-10 11:11:44 +02002549 if (px->disabled) {
2550 /* must not run and will not work anyway since
2551 * nothing in the proxy is initialized.
2552 */
2553 continue;
2554 }
2555
Emeric Brunc9437992021-02-12 19:42:55 +01002556 for (srv = px->srv; srv; srv = srv->next) {
2557 struct resolvers *resolvers;
2558
2559 if (!srv->resolvers_id)
2560 continue;
2561
2562 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
2563 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2564 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2565 err_code |= (ERR_ALERT|ERR_ABORT);
2566 continue;
2567 }
2568 srv->resolvers = resolvers;
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002569 srv->srvrq_check = NULL;
2570 if (srv->srvrq) {
2571 if (!srv->srvrq->resolvers) {
2572 srv->srvrq->resolvers = srv->resolvers;
2573 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2574 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2575 proxy_type_str(px), px->id, srv->id);
2576 err_code |= (ERR_ALERT|ERR_ABORT);
2577 continue;
2578 }
2579 }
Emeric Brunc9437992021-02-12 19:42:55 +01002580
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002581 srv->srvrq_check = task_new(MAX_THREADS_MASK);
2582 if (!srv->srvrq_check) {
2583 ha_alert("config: %s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002584 proxy_type_str(px), px->id, srv->id);
2585 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002586 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002587 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002588 srv->srvrq_check->process = resolv_srvrq_expire_task;
2589 srv->srvrq_check->context = srv;
2590 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002591 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002592 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +01002593 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2594 proxy_type_str(px), px->id, srv->id);
2595 err_code |= (ERR_ALERT|ERR_ABORT);
2596 continue;
2597 }
2598 }
2599 }
2600
2601 if (err_code & (ERR_ALERT|ERR_ABORT))
2602 goto err;
2603
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002604 leave_resolver_code();
William Lallemand15bdf582022-08-24 09:58:31 +02002605 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002606 err:
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002607 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002608 resolvers_deinit();
William Lallemand15bdf582022-08-24 09:58:31 +02002609 return 1;
Emeric Brunc9437992021-02-12 19:42:55 +01002610
2611}
2612
2613static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2614 struct dns_nameserver *ns,
2615 struct field *stats, size_t stats_count,
2616 struct list *stat_modules)
2617{
2618 struct appctx *appctx = __objt_appctx(si->end);
2619 struct channel *rep = si_ic(si);
2620 struct stats_module *mod;
2621 size_t idx = 0;
2622
2623 memset(stats, 0, sizeof(struct field) * stats_count);
2624
2625 list_for_each_entry(mod, stat_modules, list) {
2626 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2627
2628 mod->fill_stats(counters, stats + idx);
2629 idx += mod->stats_count;
2630 }
2631
2632 if (!stats_dump_one_line(stats, idx, appctx))
2633 return 0;
2634
2635 if (!stats_putchk(rep, NULL, &trash))
2636 goto full;
2637
2638 return 1;
2639
2640 full:
2641 si_rx_room_rdy(si);
2642 return 0;
2643}
2644
2645/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2646 * as a pointer to the current nameserver.
2647 */
2648int stats_dump_resolvers(struct stream_interface *si,
2649 struct field *stats, size_t stats_count,
2650 struct list *stat_modules)
2651{
2652 struct appctx *appctx = __objt_appctx(si->end);
2653 struct channel *rep = si_ic(si);
2654 struct resolvers *resolver = appctx->ctx.stats.obj1;
2655 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2656
2657 if (!resolver)
2658 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2659
2660 /* dump resolvers */
2661 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2662 appctx->ctx.stats.obj1 = resolver;
2663
2664 ns = appctx->ctx.stats.obj2 ?
2665 appctx->ctx.stats.obj2 :
2666 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2667
2668 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2669 appctx->ctx.stats.obj2 = ns;
2670
2671 if (buffer_almost_full(&rep->buf))
2672 goto full;
2673
2674 if (!stats_dump_resolv_to_buffer(si, ns,
2675 stats, stats_count,
2676 stat_modules)) {
2677 return 0;
2678 }
2679 }
2680
2681 appctx->ctx.stats.obj2 = NULL;
2682 }
2683
2684 return 1;
2685
2686 full:
2687 si_rx_room_blk(si);
2688 return 0;
2689}
2690
2691void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2692{
2693 struct resolvers *resolvers;
2694 struct dns_nameserver *ns;
2695 struct stats_module *mod;
2696 void *counters;
2697
2698 list_for_each_entry(mod, stat_modules, list) {
2699 if (!mod->clearable && !clrall)
2700 continue;
2701
2702 list_for_each_entry(resolvers, &sec_resolvers, list) {
2703 list_for_each_entry(ns, &resolvers->nameservers, list) {
2704 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2705 memcpy(counters, mod->counters, mod->counters_size);
2706 }
2707 }
2708 }
2709
2710}
2711
2712int resolv_allocate_counters(struct list *stat_modules)
2713{
2714 struct stats_module *mod;
2715 struct resolvers *resolvers;
2716 struct dns_nameserver *ns;
2717
2718 list_for_each_entry(resolvers, &sec_resolvers, list) {
2719 list_for_each_entry(ns, &resolvers->nameservers, list) {
2720 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2721 alloc_failed);
2722
2723 list_for_each_entry(mod, stat_modules, list) {
2724 EXTRA_COUNTERS_ADD(mod,
2725 ns->extra_counters,
2726 mod->counters,
2727 mod->counters_size);
2728 }
2729
2730 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2731
2732 list_for_each_entry(mod, stat_modules, list) {
2733 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2734 mod->counters, mod->counters_size);
2735
2736 /* Store the ns counters pointer */
2737 if (strcmp(mod->name, "dns") == 0) {
2738 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2739 ns->counters->id = ns->id;
2740 ns->counters->pid = resolvers->id;
2741 }
2742 }
2743 }
2744 }
2745
2746 return 1;
2747
2748alloc_failed:
2749 return 0;
2750}
2751
2752/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2753static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2754{
2755 struct resolvers *presolvers;
2756
2757 if (*args[2]) {
2758 list_for_each_entry(presolvers, &sec_resolvers, list) {
2759 if (strcmp(presolvers->id, args[2]) == 0) {
2760 appctx->ctx.cli.p0 = presolvers;
2761 break;
2762 }
2763 }
2764 if (appctx->ctx.cli.p0 == NULL)
2765 return cli_err(appctx, "Can't find that resolvers section\n");
2766 }
2767 return 0;
2768}
2769
2770/* Dumps counters from all resolvers section and associated name servers. It
2771 * returns 0 if the output buffer is full and it needs to be called again,
2772 * otherwise non-zero. It may limit itself to the resolver pointed to by
Willy Tarreau5c556222022-05-05 16:00:45 +02002773 * <cli.p0> if it's not null, and takes the current resolver section from p1
2774 * and the current resolver from p2.
Emeric Brunc9437992021-02-12 19:42:55 +01002775 */
2776static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2777{
2778 struct stream_interface *si = appctx->owner;
Willy Tarreau5c556222022-05-05 16:00:45 +02002779 struct resolvers *resolvers = appctx->ctx.cli.p1;
Emeric Brunc9437992021-02-12 19:42:55 +01002780 struct dns_nameserver *ns;
2781
2782 chunk_reset(&trash);
2783
2784 switch (appctx->st2) {
2785 case STAT_ST_INIT:
2786 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2787 /* fall through */
2788
2789 case STAT_ST_LIST:
2790 if (LIST_ISEMPTY(&sec_resolvers)) {
Willy Tarreau5c556222022-05-05 16:00:45 +02002791 if (ci_putstr(si_ic(si), "No resolvers found\n") == -1)
2792 goto full;
Emeric Brunc9437992021-02-12 19:42:55 +01002793 }
2794 else {
Willy Tarreau5c556222022-05-05 16:00:45 +02002795 if (!resolvers)
2796 resolvers = LIST_ELEM(sec_resolvers.n, typeof(resolvers), list);
2797
2798 list_for_each_entry_from(resolvers, &sec_resolvers, list) {
Emeric Brunc9437992021-02-12 19:42:55 +01002799 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2800 continue;
2801
Willy Tarreau5c556222022-05-05 16:00:45 +02002802 appctx->ctx.cli.p1 = resolvers;
2803 ns = appctx->ctx.cli.p2;
2804
2805 if (!ns) {
2806 chunk_printf(&trash, "Resolvers section %s\n", resolvers->id);
2807 if (ci_putchk(si_ic(si), &trash) == -1)
2808 goto full;
2809
2810 ns = LIST_ELEM(resolvers->nameservers.n, typeof(ns), list);
2811 appctx->ctx.cli.p2 = ns;
2812 }
2813
2814 list_for_each_entry_from(ns, &resolvers->nameservers, list) {
2815 chunk_reset(&trash);
Emeric Brunc9437992021-02-12 19:42:55 +01002816 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2817 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2818 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2819 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2820 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2821 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2822 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2823 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2824 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2825 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2826 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2827 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2828 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2829 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2830 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2831 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
Willy Tarreau5c556222022-05-05 16:00:45 +02002832 if (ci_putchk(si_ic(si), &trash) == -1)
2833 goto full;
2834 appctx->ctx.cli.p2 = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002835 }
Willy Tarreau5c556222022-05-05 16:00:45 +02002836
2837 appctx->ctx.cli.p2 = NULL;
2838
2839 /* was this the only section to dump ? */
2840 if (appctx->ctx.cli.p0)
2841 break;
Emeric Brunc9437992021-02-12 19:42:55 +01002842 }
2843 }
2844
Emeric Brunc9437992021-02-12 19:42:55 +01002845 /* fall through */
2846
2847 default:
2848 appctx->st2 = STAT_ST_FIN;
2849 return 1;
2850 }
Willy Tarreau5c556222022-05-05 16:00:45 +02002851 full:
2852 /* the output buffer is full, retry later */
2853 si_rx_room_blk(si);
2854 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002855}
2856
2857/* register cli keywords */
2858static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002859 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002860 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2861 {{},}
2862 }
2863};
2864
2865INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2866
2867/*
2868 * Prepare <rule> for hostname resolution.
2869 * Returns -1 in case of any allocation failure, 0 if not.
2870 * On error, a global failure counter is also incremented.
2871 */
Willy Tarreaua13a6102021-10-14 08:11:48 +02002872static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002873{
2874 char *hostname_dn;
Willy Tarreaua13a6102021-10-14 08:11:48 +02002875 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002876 struct buffer *tmp = get_trash_chunk();
2877
2878 if (!hostname)
2879 return 0;
2880
Emeric Brunc9437992021-02-12 19:42:55 +01002881 hostname_dn = tmp->area;
Willy Tarreauc1c765f2021-10-14 07:49:49 +02002882 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002883 hostname_dn, tmp->size);
2884 if (hostname_dn_len == -1)
2885 goto err;
2886
2887
2888 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2889 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2890 if (!stream->resolv_ctx.hostname_dn)
2891 goto err;
2892
2893 return 0;
2894
2895 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002896 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002897 resolv_failed_resolutions += 1;
2898 return -1;
2899}
2900
2901
2902/*
2903 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2904 */
2905enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2906 struct session *sess, struct stream *s, int flags)
2907{
2908 struct resolv_resolution *resolution;
2909 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002910 struct resolv_requester *req;
2911 struct resolvers *resolvers;
2912 struct resolv_resolution *res;
2913 int exp, locked = 0;
2914 enum act_return ret = ACT_RET_CONT;
2915
2916 resolvers = rule->arg.resolv.resolvers;
2917
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002918 enter_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002919
Emeric Brunc9437992021-02-12 19:42:55 +01002920 /* we have a response to our DNS resolution */
2921 use_cache:
2922 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2923 resolution = s->resolv_ctx.requester->resolution;
2924 if (!locked) {
2925 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2926 locked = 1;
2927 }
2928
2929 if (resolution->step == RSLV_STEP_RUNNING)
2930 goto yield;
2931 if (resolution->step == RSLV_STEP_NONE) {
2932 /* We update the variable only if we have a valid response. */
2933 if (resolution->status == RSLV_STATUS_VALID) {
2934 struct sample smp;
2935 short ip_sin_family = 0;
2936 void *ip = NULL;
2937
2938 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2939 0, &ip, &ip_sin_family, NULL);
2940
2941 switch (ip_sin_family) {
2942 case AF_INET:
2943 smp.data.type = SMP_T_IPV4;
2944 memcpy(&smp.data.u.ipv4, ip, 4);
2945 break;
2946 case AF_INET6:
2947 smp.data.type = SMP_T_IPV6;
2948 memcpy(&smp.data.u.ipv6, ip, 16);
2949 break;
2950 default:
2951 ip = NULL;
2952 }
2953
2954 if (ip) {
2955 smp.px = px;
2956 smp.sess = sess;
2957 smp.strm = s;
2958
2959 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2960 }
2961 }
2962 }
2963
2964 goto release_requester;
2965 }
2966
2967 /* need to configure and start a new DNS resolution */
2968 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2969 if (smp == NULL)
2970 goto end;
2971
Willy Tarreaua13a6102021-10-14 08:11:48 +02002972 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002973 goto end; /* on error, ignore the action */
2974
2975 s->resolv_ctx.parent = rule;
2976
2977 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2978 locked = 1;
2979
2980 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2981
2982 /* Check if there is a fresh enough response in the cache of our associated resolution */
2983 req = s->resolv_ctx.requester;
2984 if (!req || !req->resolution)
2985 goto release_requester; /* on error, ignore the action */
2986 res = req->resolution;
2987
2988 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2989 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2990 && !tick_is_expired(exp, now_ms)) {
2991 goto use_cache;
2992 }
2993
2994 resolv_trigger_resolution(s->resolv_ctx.requester);
2995
2996 yield:
2997 if (flags & ACT_OPT_FINAL)
2998 goto release_requester;
2999 ret = ACT_RET_YIELD;
3000
3001 end:
Christopher Faulet7a3a5362021-11-02 16:25:05 +01003002 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01003003 if (locked)
3004 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
3005 return ret;
3006
3007 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003008 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01003009 s->resolv_ctx.hostname_dn_len = 0;
3010 if (s->resolv_ctx.requester) {
Willy Tarreau33360872021-10-20 14:07:31 +02003011 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01003012 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
3013 s->resolv_ctx.requester = NULL;
3014 }
3015 goto end;
3016}
3017
3018static void release_resolv_action(struct act_rule *rule)
3019{
3020 release_sample_expr(rule->arg.resolv.expr);
3021 free(rule->arg.resolv.varname);
3022 free(rule->arg.resolv.resolvers_id);
3023 free(rule->arg.resolv.opts);
3024}
3025
3026
3027/* parse "do-resolve" action
3028 * This action takes the following arguments:
3029 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3030 *
3031 * - <varName> is the variable name where the result of the DNS resolution will be stored
3032 * (mandatory)
3033 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3034 * (mandatory)
3035 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3036 * (optional), defaults to ipv6
3037 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3038 */
3039enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3040{
3041 int cur_arg;
3042 struct sample_expr *expr;
3043 unsigned int where;
3044 const char *beg, *end;
3045
3046 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3047 cur_arg = *orig_arg - 1;
3048
3049 /* locate varName, which is mandatory */
3050 beg = strchr(args[cur_arg], '(');
3051 if (beg == NULL)
3052 goto do_resolve_parse_error;
3053 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3054 end = strchr(beg, ',');
3055 if (end == NULL)
3056 goto do_resolve_parse_error;
3057 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3058 if (rule->arg.resolv.varname == NULL)
3059 goto do_resolve_parse_error;
3060
3061
3062 /* locate resolversSectionName, which is mandatory.
3063 * Since next parameters are optional, the delimiter may be comma ','
3064 * or closing parenthesis ')'
3065 */
3066 beg = end + 1;
3067 end = strchr(beg, ',');
3068 if (end == NULL)
3069 end = strchr(beg, ')');
3070 if (end == NULL)
3071 goto do_resolve_parse_error;
3072 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3073 if (rule->arg.resolv.resolvers_id == NULL)
3074 goto do_resolve_parse_error;
3075
3076
3077 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3078 if (rule->arg.resolv.opts == NULL)
3079 goto do_resolve_parse_error;
3080
3081 /* Default priority is ipv6 */
3082 rule->arg.resolv.opts->family_prio = AF_INET6;
3083
3084 /* optional arguments accepted for now:
3085 * ipv4 or ipv6
3086 */
3087 while (*end != ')') {
3088 beg = end + 1;
3089 end = strchr(beg, ',');
3090 if (end == NULL)
3091 end = strchr(beg, ')');
3092 if (end == NULL)
3093 goto do_resolve_parse_error;
3094
3095 if (strncmp(beg, "ipv4", end - beg) == 0) {
3096 rule->arg.resolv.opts->family_prio = AF_INET;
3097 }
3098 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3099 rule->arg.resolv.opts->family_prio = AF_INET6;
3100 }
3101 else {
3102 goto do_resolve_parse_error;
3103 }
3104 }
3105
3106 cur_arg = cur_arg + 1;
3107
3108 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3109 if (!expr)
3110 goto do_resolve_parse_error;
3111
3112
3113 where = 0;
3114 if (px->cap & PR_CAP_FE)
3115 where |= SMP_VAL_FE_HRQ_HDR;
3116 if (px->cap & PR_CAP_BE)
3117 where |= SMP_VAL_BE_HRQ_HDR;
3118
3119 if (!(expr->fetch->val & where)) {
3120 memprintf(err,
3121 "fetch method '%s' extracts information from '%s', none of which is available here",
3122 args[cur_arg-1], sample_src_names(expr->fetch->use));
3123 free(expr);
3124 return ACT_RET_PRS_ERR;
3125 }
3126 rule->arg.resolv.expr = expr;
3127 rule->action = ACT_CUSTOM;
3128 rule->action_ptr = resolv_action_do_resolve;
3129 *orig_arg = cur_arg;
3130
3131 rule->check_ptr = check_action_do_resolve;
3132 rule->release_ptr = release_resolv_action;
3133
3134 return ACT_RET_PRS_OK;
3135
3136 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003137 ha_free(&rule->arg.resolv.varname);
3138 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003139 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3140 args[cur_arg]);
3141 return ACT_RET_PRS_ERR;
3142}
3143
3144static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003145 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003146 { /* END */ }
3147}};
3148
3149INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3150
3151static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003152 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003153 { /* END */ }
3154}};
3155
3156INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3157
3158/* Check an "http-request do-resolve" action.
3159 *
3160 * The function returns 1 in success case, otherwise, it returns 0 and err is
3161 * filled.
3162 */
3163int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3164{
3165 struct resolvers *resolvers = NULL;
3166
3167 if (rule->arg.resolv.resolvers_id == NULL) {
3168 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3169 return 0;
3170 }
3171
3172 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3173 if (resolvers == NULL) {
3174 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3175 return 0;
3176 }
3177 rule->arg.resolv.resolvers = resolvers;
3178
3179 return 1;
3180}
3181
3182void resolvers_setup_proxy(struct proxy *px)
3183{
3184 px->last_change = now.tv_sec;
3185 px->cap = PR_CAP_FE | PR_CAP_BE;
3186 px->maxconn = 0;
3187 px->conn_retries = 1;
3188 px->timeout.server = TICK_ETERNITY;
3189 px->timeout.client = TICK_ETERNITY;
3190 px->timeout.connect = TICK_ETERNITY;
3191 px->accept = NULL;
3192 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
3193 px->bind_proc = 0; /* will be filled by users */
3194}
3195
3196/*
3197 * Parse a <resolvers> section.
3198 * Returns the error code, 0 if OK, or any combination of :
3199 * - ERR_ABORT: must abort ASAP
3200 * - ERR_FATAL: we can continue parsing but not start the service
3201 * - ERR_WARN: a warning has been emitted
3202 * - ERR_ALERT: an alert has been emitted
3203 * Only the two first ones can stop processing, the two others are just
3204 * indicators.
3205 */
3206int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3207{
3208 const char *err;
3209 int err_code = 0;
3210 char *errmsg = NULL;
3211 struct proxy *p;
3212
3213 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3214 if (!*args[1]) {
3215 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3216 err_code |= ERR_ALERT | ERR_ABORT;
3217 goto out;
3218 }
3219
3220 err = invalid_char(args[1]);
3221 if (err) {
3222 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3223 file, linenum, *err, args[0], args[1]);
3224 err_code |= ERR_ALERT | ERR_ABORT;
3225 goto out;
3226 }
3227
3228 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3229 /* Error if two resolvers owns the same name */
3230 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3231 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3232 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3233 err_code |= ERR_ALERT | ERR_ABORT;
3234 }
3235 }
3236
3237 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3238 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3239 err_code |= ERR_ALERT | ERR_ABORT;
3240 goto out;
3241 }
3242
3243 /* allocate new proxy to tcp servers */
3244 p = calloc(1, sizeof *p);
3245 if (!p) {
3246 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3247 err_code |= ERR_ALERT | ERR_FATAL;
3248 goto out;
3249 }
3250
3251 init_new_proxy(p);
3252 resolvers_setup_proxy(p);
3253 p->parent = curr_resolvers;
3254 p->id = strdup(args[1]);
3255 p->conf.args.file = p->conf.file = strdup(file);
3256 p->conf.args.line = p->conf.line = linenum;
3257 curr_resolvers->px = p;
3258
3259 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003260 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003261 curr_resolvers->conf.file = strdup(file);
3262 curr_resolvers->conf.line = linenum;
3263 curr_resolvers->id = strdup(args[1]);
3264 curr_resolvers->query_ids = EB_ROOT;
3265 /* default maximum response size */
3266 curr_resolvers->accepted_payload_size = 512;
3267 /* default hold period for nx, other, refuse and timeout is 30s */
3268 curr_resolvers->hold.nx = 30000;
3269 curr_resolvers->hold.other = 30000;
3270 curr_resolvers->hold.refused = 30000;
3271 curr_resolvers->hold.timeout = 30000;
3272 curr_resolvers->hold.obsolete = 0;
3273 /* default hold period for valid is 10s */
3274 curr_resolvers->hold.valid = 10000;
3275 curr_resolvers->timeout.resolve = 1000;
3276 curr_resolvers->timeout.retry = 1000;
3277 curr_resolvers->resolve_retries = 3;
3278 LIST_INIT(&curr_resolvers->nameservers);
3279 LIST_INIT(&curr_resolvers->resolutions.curr);
3280 LIST_INIT(&curr_resolvers->resolutions.wait);
3281 HA_SPIN_INIT(&curr_resolvers->lock);
3282 }
3283 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3284 struct dns_nameserver *newnameserver = NULL;
3285 struct sockaddr_storage *sk;
3286 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003287 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003288
3289 if (!*args[2]) {
3290 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3291 file, linenum, args[0]);
3292 err_code |= ERR_ALERT | ERR_FATAL;
3293 goto out;
3294 }
3295
3296 err = invalid_char(args[1]);
3297 if (err) {
3298 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3299 file, linenum, *err, args[1]);
3300 err_code |= ERR_ALERT | ERR_FATAL;
3301 goto out;
3302 }
3303
3304 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3305 /* Error if two resolvers owns the same name */
3306 if (strcmp(newnameserver->id, args[1]) == 0) {
3307 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3308 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3309 err_code |= ERR_ALERT | ERR_FATAL;
3310 }
3311 }
3312
Emeric Brunc8f3e452021-04-07 16:04:54 +02003313 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3314 &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 +01003315 if (!sk) {
3316 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3317 err_code |= ERR_ALERT | ERR_FATAL;
3318 goto out;
3319 }
3320
3321 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3322 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3323 err_code |= ERR_ALERT | ERR_ABORT;
3324 goto out;
3325 }
3326
Emeric Brunc8f3e452021-04-07 16:04:54 +02003327 if (proto && proto->ctrl_type == SOCK_STREAM) {
3328 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3329 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3330 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3331 err_code |= ERR_ABORT;
3332 goto out;
3333 }
3334
3335 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3336 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3337 err_code |= ERR_ALERT|ERR_ABORT;
3338 goto out;
3339 }
3340 }
3341 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003342 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3343 err_code |= ERR_ALERT | ERR_ABORT;
3344 goto out;
3345 }
3346
3347 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3348 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3349 err_code |= ERR_ALERT | ERR_ABORT;
3350 goto out;
3351 }
3352
3353 if ((newnameserver->id = strdup(args[1])) == NULL) {
3354 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3355 err_code |= ERR_ALERT | ERR_ABORT;
3356 goto out;
3357 }
3358
3359 newnameserver->parent = curr_resolvers;
3360 newnameserver->process_responses = resolv_process_responses;
3361 newnameserver->conf.line = linenum;
3362 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003363 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003364 }
3365 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3366 struct dns_nameserver *newnameserver = NULL;
3367 const char *whitespace = "\r\n\t ";
3368 char *resolv_line = NULL;
3369 int resolv_linenum = 0;
3370 FILE *f = NULL;
3371 char *address = NULL;
3372 struct sockaddr_storage *sk = NULL;
3373 struct protocol *proto;
3374 int duplicate_name = 0;
3375
3376 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3377 ha_alert("parsing [%s:%d] : out of memory.\n",
3378 file, linenum);
3379 err_code |= ERR_ALERT | ERR_FATAL;
3380 goto resolv_out;
3381 }
3382
3383 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3384 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3385 file, linenum);
3386 err_code |= ERR_ALERT | ERR_FATAL;
3387 goto resolv_out;
3388 }
3389
3390 sk = calloc(1, sizeof(*sk));
3391 if (sk == NULL) {
3392 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3393 resolv_linenum);
3394 err_code |= ERR_ALERT | ERR_FATAL;
3395 goto resolv_out;
3396 }
3397
3398 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3399 resolv_linenum++;
3400 if (strncmp(resolv_line, "nameserver", 10) != 0)
3401 continue;
3402
3403 address = strtok(resolv_line + 10, whitespace);
3404 if (address == resolv_line + 10)
3405 continue;
3406
3407 if (address == NULL) {
3408 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3409 resolv_linenum);
3410 err_code |= ERR_WARN;
3411 continue;
3412 }
3413
3414 duplicate_name = 0;
3415 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3416 if (strcmp(newnameserver->id, address) == 0) {
3417 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",
3418 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3419 err_code |= ERR_WARN;
3420 duplicate_name = 1;
3421 }
3422 }
3423
3424 if (duplicate_name)
3425 continue;
3426
3427 memset(sk, 0, sizeof(*sk));
3428 if (!str2ip2(address, sk, 1)) {
3429 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3430 resolv_linenum, address);
3431 err_code |= ERR_WARN;
3432 continue;
3433 }
3434
3435 set_host_port(sk, 53);
3436
3437 proto = protocol_by_family(sk->ss_family);
3438 if (!proto || !proto->connect) {
3439 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3440 resolv_linenum, address);
3441 err_code |= ERR_WARN;
3442 continue;
3443 }
3444
3445 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3446 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3447 err_code |= ERR_ALERT | ERR_FATAL;
3448 goto resolv_out;
3449 }
3450
3451 if (dns_dgram_init(newnameserver, sk) < 0) {
3452 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3453 err_code |= ERR_ALERT | ERR_FATAL;
3454 free(newnameserver);
3455 goto resolv_out;
3456 }
3457
3458 newnameserver->conf.file = strdup("/etc/resolv.conf");
3459 if (newnameserver->conf.file == NULL) {
3460 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3461 err_code |= ERR_ALERT | ERR_FATAL;
3462 free(newnameserver);
3463 goto resolv_out;
3464 }
3465
3466 newnameserver->id = strdup(address);
3467 if (newnameserver->id == NULL) {
3468 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3469 err_code |= ERR_ALERT | ERR_FATAL;
3470 free((char *)newnameserver->conf.file);
3471 free(newnameserver);
3472 goto resolv_out;
3473 }
3474
3475 newnameserver->parent = curr_resolvers;
3476 newnameserver->process_responses = resolv_process_responses;
3477 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003478 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003479 }
3480
3481resolv_out:
3482 free(sk);
3483 free(resolv_line);
3484 if (f != NULL)
3485 fclose(f);
3486 }
3487 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3488 const char *res;
3489 unsigned int time;
3490
3491 if (!*args[2]) {
3492 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3493 file, linenum, args[0]);
3494 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3495 err_code |= ERR_ALERT | ERR_FATAL;
3496 goto out;
3497 }
3498 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3499 if (res == PARSE_TIME_OVER) {
3500 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3501 file, linenum, args[1], args[0]);
3502 err_code |= ERR_ALERT | ERR_FATAL;
3503 goto out;
3504 }
3505 else if (res == PARSE_TIME_UNDER) {
3506 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3507 file, linenum, args[1], args[0]);
3508 err_code |= ERR_ALERT | ERR_FATAL;
3509 goto out;
3510 }
3511 else if (res) {
3512 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3513 file, linenum, *res, args[0]);
3514 err_code |= ERR_ALERT | ERR_FATAL;
3515 goto out;
3516 }
3517 if (strcmp(args[1], "nx") == 0)
3518 curr_resolvers->hold.nx = time;
3519 else if (strcmp(args[1], "other") == 0)
3520 curr_resolvers->hold.other = time;
3521 else if (strcmp(args[1], "refused") == 0)
3522 curr_resolvers->hold.refused = time;
3523 else if (strcmp(args[1], "timeout") == 0)
3524 curr_resolvers->hold.timeout = time;
3525 else if (strcmp(args[1], "valid") == 0)
3526 curr_resolvers->hold.valid = time;
3527 else if (strcmp(args[1], "obsolete") == 0)
3528 curr_resolvers->hold.obsolete = time;
3529 else {
3530 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3531 file, linenum, args[0], args[1]);
3532 err_code |= ERR_ALERT | ERR_FATAL;
3533 goto out;
3534 }
3535
3536 }
3537 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3538 int i = 0;
3539
3540 if (!*args[1]) {
3541 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3542 file, linenum, args[0]);
3543 err_code |= ERR_ALERT | ERR_FATAL;
3544 goto out;
3545 }
3546
3547 i = atoi(args[1]);
3548 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3549 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3550 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3551 err_code |= ERR_ALERT | ERR_FATAL;
3552 goto out;
3553 }
3554
3555 curr_resolvers->accepted_payload_size = i;
3556 }
3557 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3558 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3559 file, linenum, args[0]);
3560 err_code |= ERR_ALERT | ERR_FATAL;
3561 goto out;
3562 }
3563 else if (strcmp(args[0], "resolve_retries") == 0) {
3564 if (!*args[1]) {
3565 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3566 file, linenum, args[0]);
3567 err_code |= ERR_ALERT | ERR_FATAL;
3568 goto out;
3569 }
3570 curr_resolvers->resolve_retries = atoi(args[1]);
3571 }
3572 else if (strcmp(args[0], "timeout") == 0) {
3573 if (!*args[1]) {
3574 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3575 file, linenum, args[0]);
3576 err_code |= ERR_ALERT | ERR_FATAL;
3577 goto out;
3578 }
3579 else if (strcmp(args[1], "retry") == 0 ||
3580 strcmp(args[1], "resolve") == 0) {
3581 const char *res;
3582 unsigned int tout;
3583
3584 if (!*args[2]) {
3585 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3586 file, linenum, args[0], args[1]);
3587 err_code |= ERR_ALERT | ERR_FATAL;
3588 goto out;
3589 }
3590 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3591 if (res == PARSE_TIME_OVER) {
3592 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3593 file, linenum, args[2], args[0], args[1]);
3594 err_code |= ERR_ALERT | ERR_FATAL;
3595 goto out;
3596 }
3597 else if (res == PARSE_TIME_UNDER) {
3598 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3599 file, linenum, args[2], args[0], args[1]);
3600 err_code |= ERR_ALERT | ERR_FATAL;
3601 goto out;
3602 }
3603 else if (res) {
3604 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3605 file, linenum, *res, args[0], args[1]);
3606 err_code |= ERR_ALERT | ERR_FATAL;
3607 goto out;
3608 }
3609 if (args[1][2] == 't')
3610 curr_resolvers->timeout.retry = tout;
3611 else
3612 curr_resolvers->timeout.resolve = tout;
3613 }
3614 else {
3615 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3616 file, linenum, args[0], args[1]);
3617 err_code |= ERR_ALERT | ERR_FATAL;
3618 goto out;
3619 }
3620 }
3621 else if (*args[0] != 0) {
3622 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3623 err_code |= ERR_ALERT | ERR_FATAL;
3624 goto out;
3625 }
3626
3627 out:
3628 free(errmsg);
3629 return err_code;
3630}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003631int cfg_post_parse_resolvers()
3632{
3633 int err_code = 0;
3634 struct server *srv;
3635
3636 if (curr_resolvers) {
3637
3638 /* prepare forward server descriptors */
3639 if (curr_resolvers->px) {
3640 srv = curr_resolvers->px->srv;
3641 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003642 /* init ssl if needed */
3643 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3644 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3645 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3646 err_code |= ERR_ALERT | ERR_FATAL;
3647 break;
3648 }
3649 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003650 srv = srv->next;
3651 }
3652 }
3653 }
3654 curr_resolvers = NULL;
3655 return err_code;
3656}
Emeric Brunc9437992021-02-12 19:42:55 +01003657
Emeric Brun56fc5d92021-02-12 20:05:45 +01003658REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003659REGISTER_POST_DEINIT(resolvers_deinit);
3660REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);