blob: 456b121b454621d8dff503a228c29117544f61f5 [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>
Emeric Brunc9437992021-02-12 19:42:55 +010014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <unistd.h>
18
19#include <sys/types.h>
20
Emeric Brun34067662021-06-11 10:48:45 +020021#include <import/ebistree.h>
22
Emeric Brunc9437992021-02-12 19:42:55 +010023#include <haproxy/action.h>
24#include <haproxy/api.h>
Willy Tarreaudb933d62022-05-05 15:39:02 +020025#include <haproxy/applet.h>
Emeric Brunc9437992021-02-12 19:42:55 +010026#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>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020041#include <haproxy/sc_strm.h>
Emeric Brunc9437992021-02-12 19:42:55 +010042#include <haproxy/server.h>
43#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020044#include <haproxy/stconn.h>
Emeric Brunc9437992021-02-12 19:42:55 +010045#include <haproxy/task.h>
46#include <haproxy/tcp_rules.h>
47#include <haproxy/ticks.h>
48#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020049#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010050#include <haproxy/vars.h>
Willy Tarreaudcb696c2021-10-21 08:18:01 +020051#include <haproxy/xxhash.h>
Emeric Brunc9437992021-02-12 19:42:55 +010052
53
54struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
55struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
56
Willy Tarreauf766ec62021-10-18 16:46:38 +020057static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
Christopher Faulet9ed1a062021-11-02 16:25:05 +010058static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
Emeric Brunc9437992021-02-12 19:42:55 +010059static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
60struct resolvers *curr_resolvers = NULL;
61
62DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
63DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
64DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
65
66static unsigned int resolution_uuid = 1;
67unsigned int resolv_failed_resolutions = 0;
Willy Tarreau0fbc16c2022-09-08 15:07:13 +020068struct task *process_resolvers(struct task *t, void *context, unsigned int state);
Willy Tarreauf766ec62021-10-18 16:46:38 +020069static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau6878f802021-10-20 14:07:31 +020070static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +010071static void enter_resolver_code();
72static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010073
74enum {
Emeric Brunf8642ee2021-10-29 17:59:18 +020075 RSLV_STAT_ID,
76 RSLV_STAT_PID,
77 RSLV_STAT_SENT,
78 RSLV_STAT_SND_ERROR,
79 RSLV_STAT_VALID,
80 RSLV_STAT_UPDATE,
81 RSLV_STAT_CNAME,
82 RSLV_STAT_CNAME_ERROR,
83 RSLV_STAT_ANY_ERR,
84 RSLV_STAT_NX,
85 RSLV_STAT_TIMEOUT,
86 RSLV_STAT_REFUSED,
87 RSLV_STAT_OTHER,
88 RSLV_STAT_INVALID,
89 RSLV_STAT_TOO_BIG,
90 RSLV_STAT_TRUNCATED,
91 RSLV_STAT_OUTDATED,
92 RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +010093};
94
Emeric Brunf8642ee2021-10-29 17:59:18 +020095static struct name_desc resolv_stats[] = {
96 [RSLV_STAT_ID] = { .name = "id", .desc = "ID" },
97 [RSLV_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
98 [RSLV_STAT_SENT] = { .name = "sent", .desc = "Sent" },
99 [RSLV_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
100 [RSLV_STAT_VALID] = { .name = "valid", .desc = "Valid" },
101 [RSLV_STAT_UPDATE] = { .name = "update", .desc = "Update" },
102 [RSLV_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
103 [RSLV_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
104 [RSLV_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
105 [RSLV_STAT_NX] = { .name = "nx", .desc = "NX" },
106 [RSLV_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
107 [RSLV_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
108 [RSLV_STAT_OTHER] = { .name = "other", .desc = "Other" },
109 [RSLV_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
110 [RSLV_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
111 [RSLV_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
112 [RSLV_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
Emeric Brunc9437992021-02-12 19:42:55 +0100113};
114
115static struct dns_counters dns_counters;
116
Emeric Brunf8642ee2021-10-29 17:59:18 +0200117static void resolv_fill_stats(void *d, struct field *stats)
Emeric Brunc9437992021-02-12 19:42:55 +0100118{
119 struct dns_counters *counters = d;
Emeric Brunf8642ee2021-10-29 17:59:18 +0200120 stats[RSLV_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
121 stats[RSLV_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
122 stats[RSLV_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
123 stats[RSLV_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
124 stats[RSLV_STAT_VALID] = mkf_u64(FN_GAUGE, counters->app.resolver.valid);
125 stats[RSLV_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->app.resolver.update);
126 stats[RSLV_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->app.resolver.cname);
127 stats[RSLV_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->app.resolver.cname_error);
128 stats[RSLV_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->app.resolver.any_err);
129 stats[RSLV_STAT_NX] = mkf_u64(FN_GAUGE, counters->app.resolver.nx);
130 stats[RSLV_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->app.resolver.timeout);
131 stats[RSLV_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->app.resolver.refused);
132 stats[RSLV_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->app.resolver.other);
133 stats[RSLV_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->app.resolver.invalid);
134 stats[RSLV_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->app.resolver.too_big);
135 stats[RSLV_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->app.resolver.truncated);
136 stats[RSLV_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +0100137}
138
Emeric Brunf8642ee2021-10-29 17:59:18 +0200139static struct stats_module rslv_stats_module = {
140 .name = "resolvers",
141 .domain_flags = STATS_DOMAIN_RESOLVERS << STATS_DOMAIN,
142 .fill_stats = resolv_fill_stats,
143 .stats = resolv_stats,
144 .stats_count = RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +0100145 .counters = &dns_counters,
146 .counters_size = sizeof(dns_counters),
147 .clearable = 0,
148};
149
Emeric Brunf8642ee2021-10-29 17:59:18 +0200150INITCALL1(STG_REGISTER, stats_register_module, &rslv_stats_module);
Emeric Brunc9437992021-02-12 19:42:55 +0100151
Willy Tarreaudb933d62022-05-05 15:39:02 +0200152/* CLI context used during "show resolvers" */
153struct show_resolvers_ctx {
154 struct resolvers *forced_section;
155 struct resolvers *resolvers;
156 struct dns_nameserver *ns;
157};
158
Emeric Brunc9437992021-02-12 19:42:55 +0100159/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
160 * no match is found.
161 */
162struct resolvers *find_resolvers_by_id(const char *id)
163{
164 struct resolvers *res;
165
166 list_for_each_entry(res, &sec_resolvers, list) {
167 if (strcmp(res->id, id) == 0)
168 return res;
169 }
170 return NULL;
171}
172
Emeric Brunc9437992021-02-12 19:42:55 +0100173/* Returns a pointer on the SRV request matching the name <name> for the proxy
174 * <px>. NULL is returned if no match is found.
175 */
176struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
177{
178 struct resolv_srvrq *srvrq;
179
180 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
181 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
182 return srvrq;
183 }
184 return NULL;
185}
186
187/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
188 * NULL if an error occurred. */
189struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
190{
191 struct proxy *px = srv->proxy;
192 struct resolv_srvrq *srvrq = NULL;
193 int fqdn_len, hostname_dn_len;
194
195 fqdn_len = strlen(fqdn);
Willy Tarreaubf9498a2021-10-14 07:49:49 +0200196 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100197 trash.size);
198 if (hostname_dn_len == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200199 ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100200 proxy_type_str(px), px->id, srv->id, fqdn);
201 goto err;
202 }
203
204 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200205 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100206 proxy_type_str(px), px->id, srv->id);
207 goto err;
208 }
209 srvrq->obj_type = OBJ_TYPE_SRVRQ;
210 srvrq->proxy = px;
211 srvrq->name = strdup(fqdn);
212 srvrq->hostname_dn = strdup(trash.area);
213 srvrq->hostname_dn_len = hostname_dn_len;
214 if (!srvrq->name || !srvrq->hostname_dn) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200215 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100216 proxy_type_str(px), px->id, srv->id);
217 goto err;
218 }
Emeric Brun34067662021-06-11 10:48:45 +0200219 LIST_INIT(&srvrq->attached_servers);
220 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200221 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100222 return srvrq;
223
224 err:
225 if (srvrq) {
226 free(srvrq->name);
227 free(srvrq->hostname_dn);
228 free(srvrq);
229 }
230 return NULL;
231}
232
233
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100234/* finds and return the SRV answer item associated to a requester (whose type is 'server').
235 *
236 * returns NULL in case of error or not found.
237 */
238struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
239{
240 struct resolv_resolution *res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200241 struct eb32_node *eb32;
242 struct server *srv;
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100243
244 if (!requester)
245 return NULL;
246
247 if ((srv = objt_server(requester->owner)) == NULL)
248 return NULL;
249 /* check if the server is managed by a SRV record */
250 if (srv->srvrq == NULL)
251 return NULL;
252
253 res = srv->srvrq->requester->resolution;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200254
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100255 /* search an ANSWER record whose target points to the server's hostname and whose port is
256 * the same as server's svc_port */
Willy Tarreau7893ae12021-10-21 07:39:57 +0200257 for (eb32 = eb32_first(&res->response.answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
258 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
259
Willy Tarreau75cc6532021-10-15 08:53:44 +0200260 if (memcmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100261 (srv->svc_port == item->port))
262 return item;
263 }
264
265 return NULL;
266}
267
Emeric Brunc9437992021-02-12 19:42:55 +0100268/* 2 bytes random generator to generate DNS query ID */
269static inline uint16_t resolv_rnd16(void)
270{
271 if (!resolv_query_id_seed)
272 resolv_query_id_seed = now_ms;
273 resolv_query_id_seed ^= resolv_query_id_seed << 13;
274 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
275 resolv_query_id_seed ^= resolv_query_id_seed << 17;
276 return resolv_query_id_seed;
277}
278
279
280static inline int resolv_resolution_timeout(struct resolv_resolution *res)
281{
282 return res->resolvers->timeout.resolve;
283}
284
285/* Updates a resolvers' task timeout for next wake up and queue it */
286static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
287{
288 struct resolv_resolution *res;
Willy Tarreaufdecaf62022-11-21 19:15:22 +0100289 int next = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +0100290
Emeric Brunc9437992021-02-12 19:42:55 +0100291 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
292 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
Willy Tarreaufdecaf62022-11-21 19:15:22 +0100293 next = tick_add(now_ms, resolvers->timeout.resolve);
Emeric Brunc9437992021-02-12 19:42:55 +0100294 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
295 }
296
297 list_for_each_entry(res, &resolvers->resolutions.wait, list)
298 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
299
300 resolvers->t->expire = next;
301 task_queue(resolvers->t);
302}
303
304/* Forges a DNS query. It needs the following information from the caller:
305 * - <query_id> : the DNS query id corresponding to this query
306 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
307 * - <hostname_dn> : hostname in domain name format
308 * - <hostname_dn_len> : length of <hostname_dn>
309 *
310 * To store the query, the caller must pass a buffer <buf> and its size
311 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
312 * too short.
313 */
314static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
315 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
316{
317 struct dns_header dns_hdr;
318 struct dns_question qinfo;
319 struct dns_additional_record edns;
320 char *p = buf;
321
322 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
323 return -1;
324
325 memset(buf, 0, bufsize);
326
327 /* Set dns query headers */
328 dns_hdr.id = (unsigned short) htons(query_id);
329 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
330 dns_hdr.qdcount = htons(1); /* 1 question */
331 dns_hdr.ancount = 0;
332 dns_hdr.nscount = 0;
333 dns_hdr.arcount = htons(1);
334 memcpy(p, &dns_hdr, sizeof(dns_hdr));
335 p += sizeof(dns_hdr);
336
337 /* Set up query hostname */
338 memcpy(p, hostname_dn, hostname_dn_len);
339 p += hostname_dn_len;
340 *p++ = 0;
341
342 /* Set up query info (type and class) */
343 qinfo.qtype = htons(query_type);
344 qinfo.qclass = htons(DNS_RCLASS_IN);
345 memcpy(p, &qinfo, sizeof(qinfo));
346 p += sizeof(qinfo);
347
348 /* Set the DNS extension */
349 edns.name = 0;
350 edns.type = htons(DNS_RTYPE_OPT);
351 edns.udp_payload_size = htons(accepted_payload_size);
352 edns.extension = 0;
353 edns.data_length = 0;
354 memcpy(p, &edns, sizeof(edns));
355 p += sizeof(edns);
356
357 return (p - buf);
358}
359
360/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
Emeric Brun0161d322021-10-29 16:44:49 +0200361 * success or -1 if trash buffer is not large enough to build a valid query.
Emeric Brunc9437992021-02-12 19:42:55 +0100362 */
363static int resolv_send_query(struct resolv_resolution *resolution)
364{
365 struct resolvers *resolvers = resolution->resolvers;
366 struct dns_nameserver *ns;
367 int len;
368
369 /* Update resolution */
370 resolution->nb_queries = 0;
371 resolution->nb_responses = 0;
372 resolution->last_query = now_ms;
373
374 len = resolv_build_query(resolution->query_id, resolution->query_type,
375 resolvers->accepted_payload_size,
376 resolution->hostname_dn, resolution->hostname_dn_len,
377 trash.area, trash.size);
Emeric Brun0161d322021-10-29 16:44:49 +0200378 if (len < 0) {
379 send_log(NULL, LOG_NOTICE,
380 "can not build the query message for %s, in resolvers %s.\n",
381 resolution->hostname_dn, resolvers->id);
382 return -1;
383 }
Emeric Brunc9437992021-02-12 19:42:55 +0100384
385 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunc37caab2021-10-29 16:28:33 +0200386 if (dns_send_nameserver(ns, trash.area, len) >= 0)
Emeric Brunc9437992021-02-12 19:42:55 +0100387 resolution->nb_queries++;
388 }
389
390 /* Push the resolution at the end of the active list */
Willy Tarreauaae73202021-10-19 22:01:36 +0200391 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200392 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100393 return 0;
394}
395
396/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
397 * skipped and -1 if an error occurred.
398 */
399static int
400resolv_run_resolution(struct resolv_resolution *resolution)
401{
402 struct resolvers *resolvers = resolution->resolvers;
403 int query_id, i;
404
405 /* Avoid sending requests for resolutions that don't yet have an
406 * hostname, ie resolutions linked to servers that do not yet have an
407 * fqdn */
408 if (!resolution->hostname_dn)
409 return 0;
410
411 /* Check if a resolution has already been started for this server return
412 * directly to avoid resolution pill up. */
413 if (resolution->step != RSLV_STEP_NONE)
414 return 0;
415
416 /* Generates a new query id. We try at most 100 times to find a free
417 * query id */
418 for (i = 0; i < 100; ++i) {
419 query_id = resolv_rnd16();
420 if (!eb32_lookup(&resolvers->query_ids, query_id))
421 break;
422 query_id = -1;
423 }
424 if (query_id == -1) {
425 send_log(NULL, LOG_NOTICE,
426 "could not generate a query id for %s, in resolvers %s.\n",
427 resolution->hostname_dn, resolvers->id);
428 return -1;
429 }
430
431 /* Update resolution parameters */
432 resolution->query_id = query_id;
433 resolution->qid.key = query_id;
434 resolution->step = RSLV_STEP_RUNNING;
435 resolution->query_type = resolution->prefered_query_type;
436 resolution->try = resolvers->resolve_retries;
437 eb32_insert(&resolvers->query_ids, &resolution->qid);
438
439 /* Send the DNS query */
440 resolution->try -= 1;
441 resolv_send_query(resolution);
442 return 1;
443}
444
445/* Performs a name resolution for the requester <req> */
446void resolv_trigger_resolution(struct resolv_requester *req)
447{
448 struct resolvers *resolvers;
449 struct resolv_resolution *res;
450 int exp;
451
452 if (!req || !req->resolution)
453 return;
454 res = req->resolution;
455 resolvers = res->resolvers;
456
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100457 enter_resolver_code();
458
Emeric Brunc9437992021-02-12 19:42:55 +0100459 /* The resolution must not be triggered yet. Use the cached response, if
460 * valid */
461 exp = tick_add(res->last_resolution, resolvers->hold.valid);
462 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
Christopher Faulet68a61b62022-10-24 08:59:59 +0200463 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms))) {
464 /* If the resolution is not running and the requester is a
465 * server, reset the resoltion timer to force a quick
466 * resolution.
467 */
468 if (res->step == RSLV_STEP_NONE &&
469 (obj_type(req->owner) == OBJ_TYPE_SERVER ||
470 obj_type(req->owner) == OBJ_TYPE_SRVRQ))
471 res->last_resolution = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +0100472 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet68a61b62022-10-24 08:59:59 +0200473 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100474
475 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100476}
477
478
479/* Resets some resolution parameters to initial values and also delete the query
480 * ID from the resolver's tree.
481 */
482static void resolv_reset_resolution(struct resolv_resolution *resolution)
483{
484 /* update resolution status */
485 resolution->step = RSLV_STEP_NONE;
486 resolution->try = 0;
487 resolution->last_resolution = now_ms;
488 resolution->nb_queries = 0;
489 resolution->nb_responses = 0;
490 resolution->query_type = resolution->prefered_query_type;
491
492 /* clean up query id */
493 eb32_delete(&resolution->qid);
494 resolution->query_id = 0;
495 resolution->qid.key = 0;
496}
497
498/* Returns the query id contained in a DNS response */
499static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
500{
501 return resp[0] * 256 + resp[1];
502}
503
504
505/* Analyses, re-builds and copies the name <name> from the DNS response packet
506 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
507 * for compressed data. The result is copied into <dest>, ensuring we don't
508 * overflow using <dest_len> Returns the number of bytes the caller can move
509 * forward. If 0 it means an error occurred while parsing the name. <offset> is
510 * the number of bytes the caller could move forward.
511 */
512int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
513 unsigned char *name, char *destination, int dest_len,
514 int *offset, unsigned int depth)
515{
516 int nb_bytes = 0, n = 0;
517 int label_len;
518 unsigned char *reader = name;
519 char *dest = destination;
520
521 while (1) {
522 if (reader >= bufend)
523 goto err;
524
525 /* Name compression is in use */
526 if ((*reader & 0xc0) == 0xc0) {
527 if (reader + 1 >= bufend)
528 goto err;
529
530 /* Must point BEFORE current position */
531 if ((buffer + reader[1]) > reader)
532 goto err;
533
534 if (depth++ > 100)
535 goto err;
536
537 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
538 dest, dest_len - nb_bytes, offset, depth);
539 if (n == 0)
540 goto err;
541
542 dest += n;
543 nb_bytes += n;
544 goto out;
545 }
546
547 label_len = *reader;
548 if (label_len == 0)
549 goto out;
550
551 /* Check if:
552 * - we won't read outside the buffer
553 * - there is enough place in the destination
554 */
555 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
556 goto err;
557
558 /* +1 to take label len + label string */
559 label_len++;
560
561 memcpy(dest, reader, label_len);
562
563 dest += label_len;
564 nb_bytes += label_len;
565 reader += label_len;
566 }
567
568 out:
569 /* offset computation:
570 * parse from <name> until finding either NULL or a pointer "c0xx"
571 */
572 reader = name;
573 *offset = 0;
574 while (reader < bufend) {
575 if ((reader[0] & 0xc0) == 0xc0) {
576 *offset += 2;
577 break;
578 }
579 else if (*reader == 0) {
580 *offset += 1;
581 break;
582 }
583 *offset += 1;
584 ++reader;
585 }
586 return nb_bytes;
587
588 err:
589 return 0;
590}
591
Willy Tarreauf766ec62021-10-18 16:46:38 +0200592/* Reinitialize the list of aborted resolutions before calling certain
593 * functions relying on it. The list must be processed by calling
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100594 * leave_resolver_code() after operations.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200595 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100596static void enter_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200597{
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100598 if (!recurse)
599 LIST_INIT(&death_row);
600 recurse++;
Willy Tarreauf766ec62021-10-18 16:46:38 +0200601}
602
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100603/* Add a resolution to the death_row. */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200604static void abort_resolution(struct resolv_resolution *res)
605{
Christopher Fauleteaabf062022-09-27 10:43:24 +0200606 /* Remove the resolution from query_ids tree and from any resolvers list */
607 eb32_delete(&res->qid);
608 res->query_id = 0;
609 res->qid.key = 0;
610
Willy Tarreauf766ec62021-10-18 16:46:38 +0200611 LIST_DEL_INIT(&res->list);
612 LIST_APPEND(&death_row, &res->list);
613}
614
615/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100616 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreauf766ec62021-10-18 16:46:38 +0200617 * needs to defer deletions. Note that some of them are in relation via internal
618 * objects and might cause the deletion of other ones from the same list, so we
619 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
620 * and solely rely on each call to remove the first remaining list element.
621 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100622static void leave_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200623{
624 struct resolv_resolution *res;
625
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100626 recurse--;
627 if (recurse)
628 return;
629
Willy Tarreauf766ec62021-10-18 16:46:38 +0200630 while (!LIST_ISEMPTY(&death_row)) {
631 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
632 resolv_free_resolution(res);
633 }
634
635 /* make sure nobody tries to add anything without having initialized it */
636 death_row = (struct list){ };
637}
638
Christopher Faulet11c6c392021-06-15 16:08:48 +0200639/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
640 * happens when an SRV item is purged or when the server status is considered as
641 * obsolete.
642 *
Willy Tarreauf766ec62021-10-18 16:46:38 +0200643 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100644 * initialized via enter_resolver_code().
Christopher Faulet11c6c392021-06-15 16:08:48 +0200645 */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200646static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet11c6c392021-06-15 16:08:48 +0200647{
Willy Tarreau6878f802021-10-20 14:07:31 +0200648 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200649 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
650 srvrq_update_srv_status(srv, 1);
651 ha_free(&srv->hostname);
652 ha_free(&srv->hostname_dn);
653 srv->hostname_dn_len = 0;
654 memset(&srv->addr, 0, sizeof(srv->addr));
655 srv->svc_port = 0;
656 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet73001ab2021-06-15 16:14:37 +0200657
658 ebpt_delete(&srv->host_dn);
659 ha_free(&srv->host_dn.key);
660
Christopher Faulet11c6c392021-06-15 16:08:48 +0200661 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreauaae73202021-10-19 22:01:36 +0200662 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200663 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Fauletdcac4182021-06-15 16:17:17 +0200664
665 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet11c6c392021-06-15 16:08:48 +0200666}
667
Christopher Fauletdcac4182021-06-15 16:17:17 +0200668/* Takes care to cleanup a server resolution when it is outdated. This only
669 * happens for a server relying on a SRV record.
670 */
671static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
672{
673 struct server *srv = context;
674
675 if (!tick_is_expired(t->expire, now_ms))
676 goto end;
677
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100678 enter_resolver_code();
Christopher Faulete886dd52021-06-18 09:05:49 +0200679 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreauf766ec62021-10-18 16:46:38 +0200680 resolv_srvrq_cleanup_srv(srv);
Christopher Faulete886dd52021-06-18 09:05:49 +0200681 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100682 leave_resolver_code();
Christopher Fauletdcac4182021-06-15 16:17:17 +0200683
684 end:
685 return t;
686}
687
Emeric Brunc9437992021-02-12 19:42:55 +0100688/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100689 * find a corresponding server.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200690 */
Emeric Brunc9437992021-02-12 19:42:55 +0100691static void resolv_check_response(struct resolv_resolution *res)
692{
693 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100694 struct resolv_requester *req;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200695 struct eb32_node *eb32, *eb32_back;
Emeric Brunbd78c912021-06-11 10:08:05 +0200696 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100697 struct resolv_srvrq *srvrq;
698
Willy Tarreau7893ae12021-10-21 07:39:57 +0200699 for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
700 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
Emeric Brunc9437992021-02-12 19:42:55 +0100701 struct resolv_answer_item *ar_item = item->ar_item;
702
703 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100704 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100705 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
706 * item is also obsolete.
707 */
Emeric Brunc9437992021-02-12 19:42:55 +0100708 pool_free(resolv_answer_item_pool, ar_item);
709 item->ar_item = NULL;
710 }
711
712 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100713 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200714 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100715 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200716 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
717 LIST_DEL_INIT(&srv->ip_rec_item);
718 }
719 }
720 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun34067662021-06-11 10:48:45 +0200721 /* Remove any associated server */
Christopher Faulet11c6c392021-06-15 16:08:48 +0200722 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreauf766ec62021-10-18 16:46:38 +0200723 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100724 }
725
Willy Tarreau7893ae12021-10-21 07:39:57 +0200726 eb32_delete(&item->link);
Emeric Brunc9437992021-02-12 19:42:55 +0100727 if (item->ar_item) {
728 pool_free(resolv_answer_item_pool, item->ar_item);
729 item->ar_item = NULL;
730 }
731 pool_free(resolv_answer_item_pool, item);
732 continue;
733 }
734
735 if (item->type != DNS_RTYPE_SRV)
736 continue;
737
738 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100739 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun34067662021-06-11 10:48:45 +0200740 struct ebpt_node *node;
741 char target[DNS_MAX_NAME_SIZE+1];
742
743 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100744 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
745 continue;
746
Emeric Brun34067662021-06-11 10:48:45 +0200747 /* Check if a server already uses that record */
748 srv = NULL;
749 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
750 if (srv->srvrq == srvrq) {
751 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
752 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100753 }
Emeric Brunc9437992021-02-12 19:42:55 +0100754 }
755
Emeric Brun34067662021-06-11 10:48:45 +0200756
757 /* If not empty we try to match a server
758 * in server state file tree with the same hostname
759 */
760 if (!eb_is_empty(&srvrq->named_servers)) {
761 srv = NULL;
762
763 /* convert the key to lookup in lower case */
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200764 for (i = 0 ; item->data.target[i] ; i++)
765 target[i] = tolower(item->data.target[i]);
Christopher Faulet1f923392021-07-22 14:29:26 +0200766 target[i] = 0;
Emeric Brun34067662021-06-11 10:48:45 +0200767
768 node = ebis_lookup(&srvrq->named_servers, target);
769 if (node) {
770 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100771 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun34067662021-06-11 10:48:45 +0200772
773 /* an entry was found with the same hostname
774 * let check this node if the port matches
775 * and try next node if the hostname
776 * is still the same
777 */
778 while (1) {
779 if (srv->svc_port == item->port) {
780 /* server found, we remove it from tree */
781 ebpt_delete(node);
Christopher Faulet73001ab2021-06-15 16:14:37 +0200782 ha_free(&srv->host_dn.key);
Emeric Brun34067662021-06-11 10:48:45 +0200783 goto srv_found;
784 }
785
786 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
787
788 node = ebpt_next(node);
789 if (!node)
790 break;
791
792 srv = ebpt_entry(node, struct server, host_dn);
793 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
794
795 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau75cc6532021-10-15 08:53:44 +0200796 || memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
Emeric Brun34067662021-06-11 10:48:45 +0200797 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
798 break;
799 }
800 }
Emeric Brunc9437992021-02-12 19:42:55 +0100801 }
802 }
Emeric Brun34067662021-06-11 10:48:45 +0200803
804 /* Pick the first server listed in srvrq (those ones don't
805 * have hostname and are free to use)
806 */
807 srv = NULL;
808 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
809 LIST_DEL_INIT(&srv->srv_rec_item);
810 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
811 goto srv_found;
812 }
813 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100814
Emeric Brun34067662021-06-11 10:48:45 +0200815srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100816 /* And update this server, if found (srv is locked here) */
817 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100818 /* re-enable DNS resolution for this server by default */
819 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Fauletdcac4182021-06-15 16:17:17 +0200820 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100821
Christopher Faulet2364b392022-11-03 16:41:46 +0100822 srv->svc_port = item->port;
823 srv->flags &= ~SRV_F_MAPPORTS;
824
Emeric Brunc9437992021-02-12 19:42:55 +0100825 /* Check if an Additional Record is associated to this SRV record.
826 * Perform some sanity checks too to ensure the record can be used.
827 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100828 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100829 */
830 if ((item->ar_item != NULL) &&
831 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100832 {
Emeric Brunc9437992021-02-12 19:42:55 +0100833
834 switch (item->ar_item->type) {
835 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200836 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100837 break;
838 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200839 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100840 break;
841 }
842
843 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100844
845 /* Unlink A/AAAA resolution for this server if there is an AR item.
846 * It is usless to perform an extra resolution
847 */
Willy Tarreau6878f802021-10-20 14:07:31 +0200848 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100849 }
850
851 if (!srv->hostname_dn) {
852 const char *msg = NULL;
Willy Tarreau85c15e62021-10-14 08:00:38 +0200853 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100854
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200855 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau85c15e62021-10-14 08:00:38 +0200856 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100857 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
858 continue;
859 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100860 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100861 if (msg)
862 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
863 }
864
Emeric Brun34067662021-06-11 10:48:45 +0200865 if (!LIST_INLIST(&srv->srv_rec_item))
866 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
867
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100868 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
869 /* If there is no AR item responsible of the FQDN resolution,
870 * trigger a dedicated DNS resolution
871 */
872 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
873 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
874 }
875
Christopher Fauletab177ac2021-03-10 15:34:52 +0100876 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100877 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100878
Emeric Brunc9437992021-02-12 19:42:55 +0100879 if (!srv->resolv_opts.ignore_weight) {
880 char weight[9];
881 int ha_weight;
882
883 /* DNS weight range if from 0 to 65535
884 * HAProxy weight is from 0 to 256
885 * The rule below ensures that weight 0 is well respected
886 * while allowing a "mapping" from DNS weight into HAProxy's one.
887 */
888 ha_weight = (item->weight + 255) / 256;
889
890 snprintf(weight, sizeof(weight), "%d", ha_weight);
891 server_parse_weight_change_request(srv, weight);
892 }
893 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
894 }
895 }
896 }
897}
898
899/* Validates that the buffer DNS response provided in <resp> and finishing
900 * before <bufend> is valid from a DNS protocol point of view.
901 *
902 * The result is stored in <resolution>' response, buf_response,
903 * response_query_records and response_answer_records members.
904 *
905 * This function returns one of the RSLV_RESP_* code to indicate the type of
906 * error found.
907 */
908static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
909 struct resolv_resolution *resolution, int max_answer_records)
910{
911 unsigned char *reader;
912 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
913 int len, flags, offset;
Emeric Brunc9437992021-02-12 19:42:55 +0100914 int nb_saved_records;
915 struct resolv_query_item *query;
916 struct resolv_answer_item *answer_record, *tmp_record;
917 struct resolv_response *r_res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200918 struct eb32_node *eb32;
Willy Tarreaudcb696c2021-10-21 08:18:01 +0200919 uint32_t key = 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100920 int i, found = 0;
921 int cause = RSLV_RESP_ERROR;
922
923 reader = resp;
924 len = 0;
925 previous_dname = NULL;
926 query = NULL;
927 answer_record = NULL;
928
929 /* Initialization of response buffer and structure */
930 r_res = &resolution->response;
931
932 /* query id */
933 if (reader + 2 >= bufend)
934 goto invalid_resp;
935
936 r_res->header.id = reader[0] * 256 + reader[1];
937 reader += 2;
938
939 /* Flags and rcode are stored over 2 bytes
940 * First byte contains:
941 * - response flag (1 bit)
942 * - opcode (4 bits)
943 * - authoritative (1 bit)
944 * - truncated (1 bit)
945 * - recursion desired (1 bit)
946 */
947 if (reader + 2 >= bufend)
948 goto invalid_resp;
949
950 flags = reader[0] * 256 + reader[1];
951
952 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
953 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
954 cause = RSLV_RESP_NX_DOMAIN;
955 goto return_error;
956 }
957 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
958 cause = RSLV_RESP_REFUSED;
959 goto return_error;
960 }
961 else {
962 cause = RSLV_RESP_ERROR;
963 goto return_error;
964 }
965 }
966
967 /* Move forward 2 bytes for flags */
968 reader += 2;
969
970 /* 2 bytes for question count */
971 if (reader + 2 >= bufend)
972 goto invalid_resp;
973 r_res->header.qdcount = reader[0] * 256 + reader[1];
974 /* (for now) we send one query only, so we expect only one in the
975 * response too */
976 if (r_res->header.qdcount != 1) {
977 cause = RSLV_RESP_QUERY_COUNT_ERROR;
978 goto return_error;
979 }
980
981 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
982 goto invalid_resp;
983 reader += 2;
984
985 /* 2 bytes for answer count */
986 if (reader + 2 >= bufend)
987 goto invalid_resp;
988 r_res->header.ancount = reader[0] * 256 + reader[1];
989 if (r_res->header.ancount == 0) {
990 cause = RSLV_RESP_ANCOUNT_ZERO;
991 goto return_error;
992 }
993
994 /* Check if too many records are announced */
995 if (r_res->header.ancount > max_answer_records)
996 goto invalid_resp;
997 reader += 2;
998
999 /* 2 bytes authority count */
1000 if (reader + 2 >= bufend)
1001 goto invalid_resp;
1002 r_res->header.nscount = reader[0] * 256 + reader[1];
1003 reader += 2;
1004
1005 /* 2 bytes additional count */
1006 if (reader + 2 >= bufend)
1007 goto invalid_resp;
1008 r_res->header.arcount = reader[0] * 256 + reader[1];
1009 reader += 2;
1010
Christopher Fauletc1699f82021-12-01 15:07:26 +01001011 /* Parsing dns queries. For now there is only one query and it exists
1012 * because (qdcount == 1).
1013 */
1014 query = &resolution->response_query_records[0];
Emeric Brunc9437992021-02-12 19:42:55 +01001015
Christopher Fauletc1699f82021-12-01 15:07:26 +01001016 /* Name is a NULL terminated string in our case, since we have
1017 * one query per response and the first one can't be compressed
1018 * (using the 0x0c format) */
1019 offset = 0;
1020 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01001021
Christopher Fauletc1699f82021-12-01 15:07:26 +01001022 if (len == 0)
1023 goto invalid_resp;
Emeric Brunc9437992021-02-12 19:42:55 +01001024
Christopher Fauletc1699f82021-12-01 15:07:26 +01001025 /* Now let's check the query's dname corresponds to the one we sent. */
1026 if (len != resolution->hostname_dn_len ||
1027 memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
1028 cause = RSLV_RESP_WRONG_NAME;
Christopher Fauletaf93d2f2021-12-02 10:05:02 +01001029 goto return_error;
Christopher Fauletc1699f82021-12-01 15:07:26 +01001030 }
Emeric Brunc9437992021-02-12 19:42:55 +01001031
Christopher Fauletc1699f82021-12-01 15:07:26 +01001032 reader += offset;
1033 previous_dname = query->name;
Emeric Brunc9437992021-02-12 19:42:55 +01001034
Christopher Fauletc1699f82021-12-01 15:07:26 +01001035 /* move forward 2 bytes for question type */
1036 if (reader + 2 >= bufend)
1037 goto invalid_resp;
1038 query->type = reader[0] * 256 + reader[1];
1039 reader += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001040
Christopher Fauletc1699f82021-12-01 15:07:26 +01001041 /* move forward 2 bytes for question class */
1042 if (reader + 2 >= bufend)
1043 goto invalid_resp;
1044 query->class = reader[0] * 256 + reader[1];
1045 reader += 2;
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001046
Emeric Brunc9437992021-02-12 19:42:55 +01001047 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001048 * because a TRUNCATED SRV query type response can still be exploited
1049 */
Emeric Brunc9437992021-02-12 19:42:55 +01001050 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1051 cause = RSLV_RESP_TRUNCATED;
1052 goto return_error;
1053 }
1054
1055 /* now parsing response records */
1056 nb_saved_records = 0;
1057 for (i = 0; i < r_res->header.ancount; i++) {
1058 if (reader >= bufend)
1059 goto invalid_resp;
1060
1061 answer_record = pool_alloc(resolv_answer_item_pool);
1062 if (answer_record == NULL)
1063 goto invalid_resp;
1064
1065 /* initialization */
1066 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001067 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001068 LIST_INIT(&answer_record->attached_servers);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001069 answer_record->link.node.leaf_p = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001070
1071 offset = 0;
1072 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1073
1074 if (len == 0)
1075 goto invalid_resp;
1076
1077 /* Check if the current record dname is valid. previous_dname
1078 * points either to queried dname or last CNAME target */
Willy Tarreau75cc6532021-10-15 08:53:44 +02001079 if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001080 if (i == 0) {
1081 /* First record, means a mismatch issue between
1082 * queried dname and dname found in the first
1083 * record */
1084 goto invalid_resp;
1085 }
1086 else {
1087 /* If not the first record, this means we have a
1088 * CNAME resolution error.
1089 */
1090 cause = RSLV_RESP_CNAME_ERROR;
1091 goto return_error;
1092 }
1093
1094 }
1095
1096 memcpy(answer_record->name, tmpname, len);
1097 answer_record->name[len] = 0;
1098
1099 reader += offset;
1100 if (reader >= bufend)
1101 goto invalid_resp;
1102
1103 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1104 if (reader + 2 > bufend)
1105 goto invalid_resp;
1106
1107 answer_record->type = reader[0] * 256 + reader[1];
1108 reader += 2;
1109
1110 /* 2 bytes for class (2) */
1111 if (reader + 2 > bufend)
1112 goto invalid_resp;
1113
1114 answer_record->class = reader[0] * 256 + reader[1];
1115 reader += 2;
1116
1117 /* 4 bytes for ttl (4) */
1118 if (reader + 4 > bufend)
1119 goto invalid_resp;
1120
1121 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1122 + reader[2] * 256 + reader[3];
1123 reader += 4;
1124
1125 /* Now reading data len */
1126 if (reader + 2 > bufend)
1127 goto invalid_resp;
1128
1129 answer_record->data_len = reader[0] * 256 + reader[1];
1130
1131 /* Move forward 2 bytes for data len */
1132 reader += 2;
1133
1134 if (reader + answer_record->data_len > bufend)
1135 goto invalid_resp;
1136
1137 /* Analyzing record content */
1138 switch (answer_record->type) {
1139 case DNS_RTYPE_A:
1140 /* ipv4 is stored on 4 bytes */
1141 if (answer_record->data_len != 4)
1142 goto invalid_resp;
1143
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001144 answer_record->data.in4.sin_family = AF_INET;
1145 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001146 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001147 break;
1148
1149 case DNS_RTYPE_CNAME:
1150 /* Check if this is the last record and update the caller about the status:
1151 * no IP could be found and last record was a CNAME. Could be triggered
1152 * by a wrong query type
1153 *
1154 * + 1 because answer_record_id starts at 0
1155 * while number of answers is an integer and
1156 * starts at 1.
1157 */
1158 if (i + 1 == r_res->header.ancount) {
1159 cause = RSLV_RESP_CNAME_ERROR;
1160 goto return_error;
1161 }
1162
1163 offset = 0;
1164 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1165 if (len == 0)
1166 goto invalid_resp;
1167
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001168 memcpy(answer_record->data.target, tmpname, len);
1169 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001170 key = XXH32(tmpname, len, answer_record->type);
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001171 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001172 break;
1173
1174
1175 case DNS_RTYPE_SRV:
1176 /* Answer must contain :
1177 * - 2 bytes for the priority
1178 * - 2 bytes for the weight
1179 * - 2 bytes for the port
1180 * - the target hostname
1181 */
1182 if (answer_record->data_len <= 6)
1183 goto invalid_resp;
1184
1185 answer_record->priority = read_n16(reader);
1186 reader += sizeof(uint16_t);
1187 answer_record->weight = read_n16(reader);
1188 reader += sizeof(uint16_t);
1189 answer_record->port = read_n16(reader);
1190 reader += sizeof(uint16_t);
1191 offset = 0;
1192 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1193 if (len == 0)
1194 goto invalid_resp;
1195
1196 answer_record->data_len = len;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001197 memcpy(answer_record->data.target, tmpname, len);
1198 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001199 key = XXH32(tmpname, len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001200 if (answer_record->ar_item != NULL) {
1201 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1202 answer_record->ar_item = NULL;
1203 }
1204 break;
1205
1206 case DNS_RTYPE_AAAA:
1207 /* ipv6 is stored on 16 bytes */
1208 if (answer_record->data_len != 16)
1209 goto invalid_resp;
1210
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001211 answer_record->data.in6.sin6_family = AF_INET6;
1212 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001213 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001214 break;
1215
1216 } /* switch (record type) */
1217
1218 /* Increment the counter for number of records saved into our
1219 * local response */
1220 nb_saved_records++;
1221
1222 /* Move forward answer_record->data_len for analyzing next
1223 * record in the response */
1224 reader += ((answer_record->type == DNS_RTYPE_SRV)
1225 ? offset
1226 : answer_record->data_len);
1227
1228 /* Lookup to see if we already had this entry */
1229 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001230
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001231 for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02001232 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001233 if (tmp_record->type != answer_record->type)
1234 continue;
1235
1236 switch(tmp_record->type) {
1237 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001238 if (!memcmp(&answer_record->data.in4.sin_addr,
1239 &tmp_record->data.in4.sin_addr,
1240 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001241 found = 1;
1242 break;
1243
1244 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001245 if (!memcmp(&answer_record->data.in6.sin6_addr,
1246 &tmp_record->data.in6.sin6_addr,
1247 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001248 found = 1;
1249 break;
1250
1251 case DNS_RTYPE_SRV:
1252 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001253 memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
Emeric Brunc9437992021-02-12 19:42:55 +01001254 answer_record->port == tmp_record->port) {
1255 tmp_record->weight = answer_record->weight;
1256 found = 1;
1257 }
1258 break;
1259
1260 default:
1261 break;
1262 }
1263
1264 if (found == 1)
1265 break;
1266 }
1267
1268 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001269 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001270 pool_free(resolv_answer_item_pool, answer_record);
1271 answer_record = NULL;
1272 }
1273 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001274 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001275 answer_record->ar_item = NULL;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001276 answer_record->link.key = key;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001277 eb32_insert(&r_res->answer_tree, &answer_record->link);
Emeric Brunc9437992021-02-12 19:42:55 +01001278 answer_record = NULL;
1279 }
1280 } /* for i 0 to ancount */
1281
1282 /* Save the number of records we really own */
1283 r_res->header.ancount = nb_saved_records;
1284
1285 /* now parsing additional records for SRV queries only */
1286 if (query->type != DNS_RTYPE_SRV)
1287 goto skip_parsing_additional_records;
1288
1289 /* if we find Authority records, just skip them */
1290 for (i = 0; i < r_res->header.nscount; i++) {
1291 offset = 0;
1292 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1293 &offset, 0);
1294 if (len == 0)
1295 continue;
1296
1297 if (reader + offset + 10 >= bufend)
1298 goto invalid_resp;
1299
1300 reader += offset;
1301 /* skip 2 bytes for class */
1302 reader += 2;
1303 /* skip 2 bytes for type */
1304 reader += 2;
1305 /* skip 4 bytes for ttl */
1306 reader += 4;
1307 /* read data len */
1308 len = reader[0] * 256 + reader[1];
1309 reader += 2;
1310
1311 if (reader + len >= bufend)
1312 goto invalid_resp;
1313
1314 reader += len;
1315 }
1316
1317 nb_saved_records = 0;
1318 for (i = 0; i < r_res->header.arcount; i++) {
1319 if (reader >= bufend)
1320 goto invalid_resp;
1321
1322 answer_record = pool_alloc(resolv_answer_item_pool);
1323 if (answer_record == NULL)
1324 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001325 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001326 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001327
1328 offset = 0;
1329 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1330
1331 if (len == 0) {
1332 pool_free(resolv_answer_item_pool, answer_record);
1333 answer_record = NULL;
1334 continue;
1335 }
1336
1337 memcpy(answer_record->name, tmpname, len);
1338 answer_record->name[len] = 0;
1339
1340 reader += offset;
1341 if (reader >= bufend)
1342 goto invalid_resp;
1343
1344 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1345 if (reader + 2 > bufend)
1346 goto invalid_resp;
1347
1348 answer_record->type = reader[0] * 256 + reader[1];
1349 reader += 2;
1350
1351 /* 2 bytes for class (2) */
1352 if (reader + 2 > bufend)
1353 goto invalid_resp;
1354
1355 answer_record->class = reader[0] * 256 + reader[1];
1356 reader += 2;
1357
1358 /* 4 bytes for ttl (4) */
1359 if (reader + 4 > bufend)
1360 goto invalid_resp;
1361
1362 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1363 + reader[2] * 256 + reader[3];
1364 reader += 4;
1365
1366 /* Now reading data len */
1367 if (reader + 2 > bufend)
1368 goto invalid_resp;
1369
1370 answer_record->data_len = reader[0] * 256 + reader[1];
1371
1372 /* Move forward 2 bytes for data len */
1373 reader += 2;
1374
1375 if (reader + answer_record->data_len > bufend)
1376 goto invalid_resp;
1377
1378 /* Analyzing record content */
1379 switch (answer_record->type) {
1380 case DNS_RTYPE_A:
1381 /* ipv4 is stored on 4 bytes */
1382 if (answer_record->data_len != 4)
1383 goto invalid_resp;
1384
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001385 answer_record->data.in4.sin_family = AF_INET;
1386 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001387 break;
1388
1389 case DNS_RTYPE_AAAA:
1390 /* ipv6 is stored on 16 bytes */
1391 if (answer_record->data_len != 16)
1392 goto invalid_resp;
1393
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001394 answer_record->data.in6.sin6_family = AF_INET6;
1395 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001396 break;
1397
1398 default:
1399 pool_free(resolv_answer_item_pool, answer_record);
1400 answer_record = NULL;
1401 continue;
1402
1403 } /* switch (record type) */
1404
1405 /* Increment the counter for number of records saved into our
1406 * local response */
1407 nb_saved_records++;
1408
1409 /* Move forward answer_record->data_len for analyzing next
1410 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001411 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001412
1413 /* Lookup to see if we already had this entry */
1414 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001415
1416 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001417 struct resolv_answer_item *ar_item;
1418
Willy Tarreau7893ae12021-10-21 07:39:57 +02001419 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Christopher Faulet77f86062021-03-10 15:19:57 +01001420 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1421 continue;
1422
1423 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001424 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001425 len != tmp_record->data_len ||
Willy Tarreau75cc6532021-10-15 08:53:44 +02001426 memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001427 continue;
1428
Christopher Faulet77f86062021-03-10 15:19:57 +01001429 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001430 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001431 if (!memcmp(&answer_record->data.in4.sin_addr,
1432 &ar_item->data.in4.sin_addr,
1433 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001434 found = 1;
1435 break;
1436
1437 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001438 if (!memcmp(&answer_record->data.in6.sin6_addr,
1439 &ar_item->data.in6.sin6_addr,
1440 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001441 found = 1;
1442 break;
1443
1444 default:
1445 break;
1446 }
1447
1448 if (found == 1)
1449 break;
1450 }
1451
1452 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001453 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001454 pool_free(resolv_answer_item_pool, answer_record);
1455 answer_record = NULL;
1456 }
1457 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001458 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001459 answer_record->ar_item = NULL;
1460
1461 // looking for the SRV record in the response list linked to this additional record
Willy Tarreau7893ae12021-10-21 07:39:57 +02001462 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
1463 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
1464
Emeric Brunc9437992021-02-12 19:42:55 +01001465 if (tmp_record->type == DNS_RTYPE_SRV &&
1466 tmp_record->ar_item == NULL &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001467 memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001468 /* Always use the received additional record to refresh info */
1469 if (tmp_record->ar_item)
1470 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1471 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001472 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001473 break;
1474 }
1475 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001476 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001477 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001478 answer_record = NULL;
1479 }
Emeric Brunc9437992021-02-12 19:42:55 +01001480 }
1481 } /* for i 0 to arcount */
1482
1483 skip_parsing_additional_records:
1484
1485 /* Save the number of records we really own */
1486 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001487 resolv_check_response(resolution);
1488 return RSLV_RESP_VALID;
1489
1490 invalid_resp:
1491 cause = RSLV_RESP_INVALID;
1492
1493 return_error:
1494 pool_free(resolv_answer_item_pool, answer_record);
1495 return cause;
1496}
1497
1498/* Searches dn_name resolution in resp.
1499 * If existing IP not found, return the first IP matching family_priority,
1500 * otherwise, first ip found
1501 * The following tasks are the responsibility of the caller:
1502 * - <r_res> contains an error free DNS response
1503 * For both cases above, resolv_validate_dns_response is required
1504 * returns one of the RSLV_UPD_* code
1505 */
1506int resolv_get_ip_from_response(struct resolv_response *r_res,
1507 struct resolv_options *resolv_opts, void *currentip,
1508 short currentip_sin_family,
1509 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001510 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001511{
Emeric Brunbd78c912021-06-11 10:08:05 +02001512 struct resolv_answer_item *record, *found_record = NULL;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001513 struct eb32_node *eb32;
Emeric Brunc9437992021-02-12 19:42:55 +01001514 int family_priority;
1515 int currentip_found;
1516 unsigned char *newip4, *newip6;
1517 int currentip_sel;
1518 int j;
1519 int score, max_score;
1520 int allowed_duplicated_ip;
1521
Emeric Brunbd78c912021-06-11 10:08:05 +02001522 /* srv is linked to an alive ip record */
1523 if (owner && LIST_INLIST(&owner->ip_rec_item))
1524 return RSLV_UPD_NO;
1525
Emeric Brunc9437992021-02-12 19:42:55 +01001526 family_priority = resolv_opts->family_prio;
1527 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1528 *newip = newip4 = newip6 = NULL;
1529 currentip_found = 0;
1530 *newip_sin_family = AF_UNSPEC;
1531 max_score = -1;
1532
1533 /* Select an IP regarding configuration preference.
1534 * Top priority is the preferred network ip version,
1535 * second priority is the preferred network.
1536 * the last priority is the currently used IP,
1537 *
1538 * For these three priorities, a score is calculated. The
1539 * weight are:
1540 * 8 - preferred ip version.
1541 * 4 - preferred network.
1542 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1543 * 1 - current ip.
1544 * The result with the biggest score is returned.
1545 */
1546
Willy Tarreau7893ae12021-10-21 07:39:57 +02001547 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001548 void *ip;
1549 unsigned char ip_type;
1550
Willy Tarreau7893ae12021-10-21 07:39:57 +02001551 record = eb32_entry(eb32, typeof(*record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001552 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001553 ip_type = AF_INET;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001554 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001555 }
1556 else if (record->type == DNS_RTYPE_AAAA) {
1557 ip_type = AF_INET6;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001558 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001559 }
1560 else
1561 continue;
1562 score = 0;
1563
1564 /* Check for preferred ip protocol. */
1565 if (ip_type == family_priority)
1566 score += 8;
1567
1568 /* Check for preferred network. */
1569 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1570
1571 /* Compare only the same addresses class. */
1572 if (resolv_opts->pref_net[j].family != ip_type)
1573 continue;
1574
1575 if ((ip_type == AF_INET &&
1576 in_net_ipv4(ip,
1577 &resolv_opts->pref_net[j].mask.in4,
1578 &resolv_opts->pref_net[j].addr.in4)) ||
1579 (ip_type == AF_INET6 &&
1580 in_net_ipv6(ip,
1581 &resolv_opts->pref_net[j].mask.in6,
1582 &resolv_opts->pref_net[j].addr.in6))) {
1583 score += 4;
1584 break;
1585 }
1586 }
1587
1588 /* Check if the IP found in the record is already affected to a
1589 * member of a group. If not, the score should be incremented
1590 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001591 if (owner) {
1592 struct server *srv;
1593 int already_used = 0;
1594
1595 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1596 if (srv == owner)
1597 continue;
1598 if (srv->proxy == owner->proxy) {
1599 already_used = 1;
1600 break;
1601 }
1602 }
1603 if (already_used) {
1604 if (!allowed_duplicated_ip) {
1605 continue;
1606 }
1607 }
1608 else {
1609 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001610 }
1611 } else {
1612 score += 2;
1613 }
1614
1615 /* Check for current ip matching. */
1616 if (ip_type == currentip_sin_family &&
1617 ((currentip_sin_family == AF_INET &&
1618 !memcmp(ip, currentip, 4)) ||
1619 (currentip_sin_family == AF_INET6 &&
1620 !memcmp(ip, currentip, 16)))) {
1621 score++;
1622 currentip_sel = 1;
1623 }
1624 else
1625 currentip_sel = 0;
1626
1627 /* Keep the address if the score is better than the previous
1628 * score. The maximum score is 15, if this value is reached, we
1629 * break the parsing. Implicitly, this score is reached the ip
1630 * selected is the current ip. */
1631 if (score > max_score) {
1632 if (ip_type == AF_INET)
1633 newip4 = ip;
1634 else
1635 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001636 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001637 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001638 if (score == 15) {
1639 /* this was not registered on the current record but it matches
1640 * let's fix it (it may comes from state file */
1641 if (owner)
1642 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001643 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001644 }
Emeric Brunc9437992021-02-12 19:42:55 +01001645 max_score = score;
1646 }
1647 } /* list for each record entries */
1648
1649 /* No IP found in the response */
1650 if (!newip4 && !newip6)
1651 return RSLV_UPD_NO_IP_FOUND;
1652
1653 /* Case when the caller looks first for an IPv4 address */
1654 if (family_priority == AF_INET) {
1655 if (newip4) {
1656 *newip = newip4;
1657 *newip_sin_family = AF_INET;
1658 }
1659 else if (newip6) {
1660 *newip = newip6;
1661 *newip_sin_family = AF_INET6;
1662 }
Emeric Brunc9437992021-02-12 19:42:55 +01001663 }
1664 /* Case when the caller looks first for an IPv6 address */
1665 else if (family_priority == AF_INET6) {
1666 if (newip6) {
1667 *newip = newip6;
1668 *newip_sin_family = AF_INET6;
1669 }
1670 else if (newip4) {
1671 *newip = newip4;
1672 *newip_sin_family = AF_INET;
1673 }
Emeric Brunc9437992021-02-12 19:42:55 +01001674 }
1675 /* Case when the caller have no preference (we prefer IPv6) */
1676 else if (family_priority == AF_UNSPEC) {
1677 if (newip6) {
1678 *newip = newip6;
1679 *newip_sin_family = AF_INET6;
1680 }
1681 else if (newip4) {
1682 *newip = newip4;
1683 *newip_sin_family = AF_INET;
1684 }
Emeric Brunc9437992021-02-12 19:42:55 +01001685 }
1686
Emeric Brunbd78c912021-06-11 10:08:05 +02001687 /* the ip of this record was chosen for the server */
1688 if (owner && found_record) {
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001689 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunbd78c912021-06-11 10:08:05 +02001690 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1691 }
1692
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001693 eb32 = eb32_first(&r_res->answer_tree);
1694 if (eb32) {
Emeric Brunc9437992021-02-12 19:42:55 +01001695 /* Move the first record to the end of the list, for internal
Willy Tarreau7893ae12021-10-21 07:39:57 +02001696 * round robin.
1697 */
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001698 eb32_delete(eb32);
1699 eb32_insert(&r_res->answer_tree, eb32);
Emeric Brunc9437992021-02-12 19:42:55 +01001700 }
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001701
1702 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001703}
1704
Willy Tarreau875ee702021-10-14 08:05:25 +02001705/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001706 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001707 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1708 * null-terminated. <str> must be allocated large enough to contain a full host
1709 * name plus the trailing zero, and the allocated size must be passed in
1710 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001711 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001712 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001713 * <str> (including the terminating null byte).
1714 */
1715int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1716{
1717 char *ptr;
1718 int i, sz;
1719
Willy Tarreau875ee702021-10-14 08:05:25 +02001720 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001721 return -1;
1722
1723 ptr = str;
Willy Tarreau875ee702021-10-14 08:05:25 +02001724 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001725 sz = dn[i];
1726 if (i)
1727 *ptr++ = '.';
Willy Tarreau814889c2021-10-15 07:45:38 +02001728 /* copy the string at i+1 to lower case */
1729 for (; sz > 0; sz--)
1730 *(ptr++) = tolower(dn[++i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001731 }
1732 *ptr++ = '\0';
1733 return (ptr - str);
1734}
1735
1736/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1737 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001738 * <str> contains the input string that is <str_len> bytes long (trailing zero
1739 * not needed). <dn> buffer must be allocated large enough to contain the
1740 * encoded string and a trailing zero, so it must be at least str_len+2, and
1741 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001742 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001743 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001744 * <dn> (excluding the terminating null byte).
1745 */
1746int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1747{
1748 int i, offset;
1749
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001750 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001751 return -1;
1752
1753 /* First byte of dn will be used to store the length of the first
1754 * label */
1755 offset = 0;
1756 for (i = 0; i < str_len; ++i) {
1757 if (str[i] == '.') {
1758 /* 2 or more consecutive dots is invalid */
1759 if (i == offset)
1760 return -1;
1761
1762 /* ignore trailing dot */
Christopher Faulet0a82cf42022-01-28 17:47:57 +01001763 if (i + 1 == str_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001764 break;
Emeric Brunc9437992021-02-12 19:42:55 +01001765
1766 dn[offset] = (i - offset);
1767 offset = i+1;
1768 continue;
1769 }
Willy Tarreau814889c2021-10-15 07:45:38 +02001770 dn[i+1] = tolower(str[i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001771 }
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001772 dn[offset] = i - offset;
Willy Tarreau7b232f12021-10-15 08:09:25 +02001773 dn[i+1] = '\0';
1774 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001775}
1776
1777/* Validates host name:
1778 * - total size
1779 * - each label size individually
1780 * returns:
1781 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1782 * 1 when no error. <err> is left unaffected.
1783 */
1784int resolv_hostname_validation(const char *string, char **err)
1785{
1786 int i;
1787
1788 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1789 if (err)
1790 *err = DNS_TOO_LONG_FQDN;
1791 return 0;
1792 }
1793
1794 while (*string) {
1795 i = 0;
1796 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1797 if (!(*string == '-' || *string == '_' ||
1798 (*string >= 'a' && *string <= 'z') ||
1799 (*string >= 'A' && *string <= 'Z') ||
1800 (*string >= '0' && *string <= '9'))) {
1801 if (err)
1802 *err = DNS_INVALID_CHARACTER;
1803 return 0;
1804 }
1805 i++;
1806 string++;
1807 }
1808
1809 if (!(*string))
1810 break;
1811
1812 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1813 if (err)
1814 *err = DNS_LABEL_TOO_LONG;
1815 return 0;
1816 }
1817
1818 string++;
1819 }
1820 return 1;
1821}
1822
1823/* Picks up an available resolution from the different resolution list
1824 * associated to a resolvers section, in this order:
1825 * 1. check in resolutions.curr for the same hostname and query_type
1826 * 2. check in resolutions.wait for the same hostname and query_type
1827 * 3. Get a new resolution from resolution pool
1828 *
1829 * Returns an available resolution, NULL if none found.
1830 */
1831static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1832 char **hostname_dn, int hostname_dn_len,
1833 int query_type)
1834{
1835 struct resolv_resolution *res;
1836
1837 if (!*hostname_dn)
1838 goto from_pool;
1839
1840 /* Search for same hostname and query type in resolutions.curr */
1841 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1842 if (!res->hostname_dn)
1843 continue;
1844 if ((query_type == res->prefered_query_type) &&
1845 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001846 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001847 return res;
1848 }
1849
1850 /* Search for same hostname and query type in resolutions.wait */
1851 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1852 if (!res->hostname_dn)
1853 continue;
1854 if ((query_type == res->prefered_query_type) &&
1855 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001856 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001857 return res;
1858 }
1859
1860 from_pool:
1861 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001862 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001863 if (res) {
Emeric Brunc9437992021-02-12 19:42:55 +01001864 res->resolvers = resolvers;
1865 res->uuid = resolution_uuid;
1866 res->status = RSLV_STATUS_NONE;
1867 res->step = RSLV_STEP_NONE;
1868 res->last_valid = now_ms;
1869
1870 LIST_INIT(&res->requesters);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001871 res->response.answer_tree = EB_ROOT;
Emeric Brunc9437992021-02-12 19:42:55 +01001872
1873 res->prefered_query_type = query_type;
1874 res->query_type = query_type;
1875 res->hostname_dn = *hostname_dn;
1876 res->hostname_dn_len = hostname_dn_len;
1877
1878 ++resolution_uuid;
1879
1880 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001881 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001882 }
1883 return res;
1884}
1885
Willy Tarreau2acc1602021-10-19 11:16:11 +02001886/* deletes and frees all answer_items from the resolution's answer_list */
1887static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001888{
Willy Tarreau7893ae12021-10-21 07:39:57 +02001889 struct eb32_node *eb32, *eb32_back;
1890 struct resolv_answer_item *item;
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001891
Willy Tarreau7893ae12021-10-21 07:39:57 +02001892 for (eb32 = eb32_first(&resolution->response.answer_tree);
1893 eb32 && (eb32_back = eb32_next(eb32), 1);
1894 eb32 = eb32_back) {
1895 item = eb32_entry(eb32, typeof(*item), link);
1896 eb32_delete(&item->link);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001897 pool_free(resolv_answer_item_pool, item->ar_item);
1898 pool_free(resolv_answer_item_pool, item);
1899 }
1900}
1901
Emeric Brunc9437992021-02-12 19:42:55 +01001902/* Releases a resolution from its requester(s) and move it back to the pool */
1903static void resolv_free_resolution(struct resolv_resolution *resolution)
1904{
1905 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001906
1907 /* clean up configuration */
1908 resolv_reset_resolution(resolution);
1909 resolution->hostname_dn = NULL;
1910 resolution->hostname_dn_len = 0;
1911
1912 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02001913 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001914 req->resolution = NULL;
1915 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001916 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau25e01092021-10-19 11:17:33 +02001917
Willy Tarreauaae73202021-10-19 22:01:36 +02001918 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001919 pool_free(resolv_resolution_pool, resolution);
1920}
1921
Willy Tarreau239675e2021-10-19 11:59:25 +02001922/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1923 * and makes it owned by this obj_type, with the proposed callback and error
1924 * callback. On success, *req is assigned the allocated requester. Returns
1925 * NULL on allocation failure.
1926 */
1927static struct resolv_requester *
1928resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1929 int (*cb)(struct resolv_requester *, struct dns_counters *),
1930 int (*err_cb)(struct resolv_requester *, int))
1931{
1932 struct resolv_requester *tmp;
1933
1934 if (*req)
1935 return *req;
1936
1937 tmp = pool_alloc(resolv_requester_pool);
1938 if (!tmp)
1939 goto end;
1940
1941 LIST_INIT(&tmp->list);
1942 tmp->owner = owner;
1943 tmp->resolution = NULL;
1944 tmp->requester_cb = cb;
1945 tmp->requester_error_cb = err_cb;
1946 *req = tmp;
1947 end:
1948 return tmp;
1949}
1950
Emeric Brunc9437992021-02-12 19:42:55 +01001951/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001952 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001953 */
1954int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1955{
1956 struct resolv_resolution *res = NULL;
1957 struct resolv_requester *req;
1958 struct resolvers *resolvers;
1959 struct server *srv = NULL;
1960 struct resolv_srvrq *srvrq = NULL;
1961 struct stream *stream = NULL;
1962 char **hostname_dn;
1963 int hostname_dn_len, query_type;
1964
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001965 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001966 switch (requester_type) {
1967 case OBJ_TYPE_SERVER:
1968 srv = (struct server *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001969
1970 if (!requester_locked)
1971 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1972
1973 req = resolv_get_requester(&srv->resolv_requester,
1974 &srv->obj_type,
1975 snr_resolution_cb,
1976 snr_resolution_error_cb);
1977
1978 if (!requester_locked)
1979 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1980
1981 if (!req)
1982 goto err;
1983
Emeric Brunc9437992021-02-12 19:42:55 +01001984 hostname_dn = &srv->hostname_dn;
1985 hostname_dn_len = srv->hostname_dn_len;
1986 resolvers = srv->resolvers;
1987 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1988 ? DNS_RTYPE_A
1989 : DNS_RTYPE_AAAA);
1990 break;
1991
1992 case OBJ_TYPE_SRVRQ:
1993 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001994
1995 req = resolv_get_requester(&srvrq->requester,
1996 &srvrq->obj_type,
1997 snr_resolution_cb,
1998 srvrq_resolution_error_cb);
1999 if (!req)
2000 goto err;
2001
Emeric Brunc9437992021-02-12 19:42:55 +01002002 hostname_dn = &srvrq->hostname_dn;
2003 hostname_dn_len = srvrq->hostname_dn_len;
2004 resolvers = srvrq->resolvers;
2005 query_type = DNS_RTYPE_SRV;
2006 break;
2007
2008 case OBJ_TYPE_STREAM:
2009 stream = (struct stream *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02002010
2011 req = resolv_get_requester(&stream->resolv_ctx.requester,
2012 &stream->obj_type,
2013 act_resolution_cb,
2014 act_resolution_error_cb);
2015 if (!req)
2016 goto err;
2017
Emeric Brunc9437992021-02-12 19:42:55 +01002018 hostname_dn = &stream->resolv_ctx.hostname_dn;
2019 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2020 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2021 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2022 ? DNS_RTYPE_A
2023 : DNS_RTYPE_AAAA);
2024 break;
2025 default:
2026 goto err;
2027 }
2028
2029 /* Get a resolution from the resolvers' wait queue or pool */
2030 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2031 goto err;
2032
Willy Tarreau239675e2021-10-19 11:59:25 +02002033 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002034
Willy Tarreau2b718102021-04-21 07:32:39 +02002035 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002036 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002037 return 0;
2038
2039 err:
2040 if (res && LIST_ISEMPTY(&res->requesters))
2041 resolv_free_resolution(res);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002042 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002043 return -1;
2044}
2045
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002046/* This function removes all server/srvrq references on answer items. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002047void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun34067662021-06-11 10:48:45 +02002048{
Willy Tarreau7893ae12021-10-21 07:39:57 +02002049 struct eb32_node *eb32, *eb32_back;
2050 struct resolv_answer_item *item;
Emeric Brun34067662021-06-11 10:48:45 +02002051 struct server *srv, *srvback;
2052 struct resolv_srvrq *srvrq;
2053
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002054 enter_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002055 if ((srv = objt_server(req->owner)) != NULL) {
2056 LIST_DEL_INIT(&srv->ip_rec_item);
2057 }
2058 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02002059 for (eb32 = eb32_first(&res->response.answer_tree);
2060 eb32 && (eb32_back = eb32_next(eb32), 1);
2061 eb32 = eb32_back) {
2062 item = eb32_entry(eb32, typeof(*item), link);
Emeric Brun34067662021-06-11 10:48:45 +02002063 if (item->type == DNS_RTYPE_SRV) {
2064 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet11c6c392021-06-15 16:08:48 +02002065 if (srv->srvrq == srvrq)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002066 resolv_srvrq_cleanup_srv(srv);
Emeric Brun34067662021-06-11 10:48:45 +02002067 }
2068 }
2069 }
2070 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002071 leave_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002072}
2073
Emeric Brunc9437992021-02-12 19:42:55 +01002074/* Removes a requester from a DNS resolution. It takes takes care of all the
2075 * consequences. It also cleans up some parameters from the requester.
2076 */
Willy Tarreau6878f802021-10-20 14:07:31 +02002077static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002078{
2079 struct resolv_resolution *res;
2080 struct resolv_requester *req;
2081
2082 /* Nothing to do */
2083 if (!requester || !requester->resolution)
2084 return;
2085 res = requester->resolution;
2086
2087 /* Clean up the requester */
Willy Tarreauaae73202021-10-19 22:01:36 +02002088 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002089 requester->resolution = NULL;
2090
Christopher Fauletbce6db62021-10-29 10:38:15 +02002091 /* remove ref from the resolution answer item list to the requester */
2092 resolv_detach_from_resolution_answer_items(res, requester);
2093
Emeric Brunc9437992021-02-12 19:42:55 +01002094 /* We need to find another requester linked on this resolution */
2095 if (!LIST_ISEMPTY(&res->requesters))
2096 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2097 else {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002098 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002099 return;
2100 }
2101
2102 /* Move hostname_dn related pointers to the next requester */
2103 switch (obj_type(req->owner)) {
2104 case OBJ_TYPE_SERVER:
2105 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2106 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2107 break;
2108 case OBJ_TYPE_SRVRQ:
2109 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2110 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2111 break;
2112 case OBJ_TYPE_STREAM:
2113 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2114 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2115 break;
2116 default:
2117 res->hostname_dn = NULL;
2118 res->hostname_dn_len = 0;
2119 break;
2120 }
2121}
2122
Willy Tarreauf766ec62021-10-18 16:46:38 +02002123/* The public version of the function above that deals with the death row. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002124void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002125{
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002126 enter_resolver_code();
Willy Tarreau6878f802021-10-20 14:07:31 +02002127 _resolv_unlink_resolution(requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002128 leave_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002129}
2130
Emeric Brunc9437992021-02-12 19:42:55 +01002131/* Called when a network IO is generated on a name server socket for an incoming
2132 * packet. It performs the following actions:
2133 * - check if the packet requires processing (not outdated resolution)
2134 * - ensure the DNS packet received is valid and call requester's callback
2135 * - call requester's error callback if invalid response
2136 * - check the dn_name in the packet against the one sent
2137 */
2138static int resolv_process_responses(struct dns_nameserver *ns)
2139{
2140 struct dns_counters *tmpcounters;
2141 struct resolvers *resolvers;
2142 struct resolv_resolution *res;
Emeric Brunc9437992021-02-12 19:42:55 +01002143 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2144 unsigned char *bufend;
2145 int buflen, dns_resp;
2146 int max_answer_records;
2147 unsigned short query_id;
2148 struct eb32_node *eb;
2149 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002150 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002151
2152 resolvers = ns->parent;
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002153 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002154 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2155
2156 /* process all pending input messages */
2157 while (1) {
2158 /* read message received */
2159 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2160 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2161 break;
2162 }
2163
2164 /* message too big */
2165 if (buflen > resolvers->accepted_payload_size) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002166 ns->counters->app.resolver.too_big++;
Emeric Brunc9437992021-02-12 19:42:55 +01002167 continue;
2168 }
2169
2170 /* initializing variables */
2171 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2172
2173 /* read the query id from the packet (16 bits) */
2174 if (buf + 2 > bufend) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002175 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002176 continue;
2177 }
2178 query_id = resolv_response_get_query_id(buf);
2179
2180 /* search the query_id in the pending resolution tree */
2181 eb = eb32_lookup(&resolvers->query_ids, query_id);
2182 if (eb == NULL) {
2183 /* unknown query id means an outdated response and can be safely ignored */
Emeric Brund174f0e2021-10-29 17:30:41 +02002184 ns->counters->app.resolver.outdated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002185 continue;
2186 }
2187
2188 /* known query id means a resolution in progress */
2189 res = eb32_entry(eb, struct resolv_resolution, qid);
2190 /* number of responses received */
2191 res->nb_responses++;
2192
2193 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2194 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2195
2196 switch (dns_resp) {
2197 case RSLV_RESP_VALID:
2198 break;
2199
2200 case RSLV_RESP_INVALID:
2201 case RSLV_RESP_QUERY_COUNT_ERROR:
2202 case RSLV_RESP_WRONG_NAME:
2203 res->status = RSLV_STATUS_INVALID;
Emeric Brund174f0e2021-10-29 17:30:41 +02002204 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002205 break;
2206
2207 case RSLV_RESP_NX_DOMAIN:
2208 res->status = RSLV_STATUS_NX;
Emeric Brund174f0e2021-10-29 17:30:41 +02002209 ns->counters->app.resolver.nx++;
Emeric Brunc9437992021-02-12 19:42:55 +01002210 break;
2211
2212 case RSLV_RESP_REFUSED:
2213 res->status = RSLV_STATUS_REFUSED;
Emeric Brund174f0e2021-10-29 17:30:41 +02002214 ns->counters->app.resolver.refused++;
Emeric Brunc9437992021-02-12 19:42:55 +01002215 break;
2216
2217 case RSLV_RESP_ANCOUNT_ZERO:
2218 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002219 ns->counters->app.resolver.any_err++;
Emeric Brunc9437992021-02-12 19:42:55 +01002220 break;
2221
2222 case RSLV_RESP_CNAME_ERROR:
2223 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002224 ns->counters->app.resolver.cname_error++;
Emeric Brunc9437992021-02-12 19:42:55 +01002225 break;
2226
2227 case RSLV_RESP_TRUNCATED:
2228 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002229 ns->counters->app.resolver.truncated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002230 break;
2231
2232 case RSLV_RESP_NO_EXPECTED_RECORD:
2233 case RSLV_RESP_ERROR:
2234 case RSLV_RESP_INTERNAL:
2235 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002236 ns->counters->app.resolver.other++;
Emeric Brunc9437992021-02-12 19:42:55 +01002237 break;
2238 }
2239
2240 /* Wait all nameservers response to handle errors */
2241 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2242 continue;
2243
2244 /* Process error codes */
2245 if (dns_resp != RSLV_RESP_VALID) {
2246 if (res->prefered_query_type != res->query_type) {
2247 /* The fallback on the query type was already performed,
2248 * so check the try counter. If it falls to 0, we can
2249 * report an error. Else, wait the next attempt. */
2250 if (!res->try)
2251 goto report_res_error;
2252 }
2253 else {
2254 /* Fallback from A to AAAA or the opposite and re-send
2255 * the resolution immediately. try counter is not
2256 * decremented. */
2257 if (res->prefered_query_type == DNS_RTYPE_A) {
2258 res->query_type = DNS_RTYPE_AAAA;
2259 resolv_send_query(res);
2260 }
2261 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2262 res->query_type = DNS_RTYPE_A;
2263 resolv_send_query(res);
2264 }
2265 }
2266 continue;
2267 }
2268
Emeric Brunc9437992021-02-12 19:42:55 +01002269 /* So the resolution succeeded */
2270 res->status = RSLV_STATUS_VALID;
2271 res->last_valid = now_ms;
Emeric Brund174f0e2021-10-29 17:30:41 +02002272 ns->counters->app.resolver.valid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002273 goto report_res_success;
2274
2275 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002276 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002277 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002278 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2279 if (!keep_answer_items)
2280 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002281 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002282 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002283 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002284 continue;
2285
2286 report_res_success:
2287 /* Only the 1rst requester s managed by the server, others are
2288 * from the cache */
2289 tmpcounters = ns->counters;
2290 list_for_each_entry(req, &res->requesters, list) {
2291 struct server *s = objt_server(req->owner);
2292
2293 if (s)
2294 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2295 req->requester_cb(req, tmpcounters);
2296 if (s)
2297 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2298 tmpcounters = NULL;
2299 }
2300
2301 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002302 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002303 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002304 continue;
2305 }
2306 resolv_update_resolvers_timeout(resolvers);
2307 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002308 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002309 return buflen;
2310}
2311
2312/* Processes DNS resolution. First, it checks the active list to detect expired
2313 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2314 * checks the wait list to trigger new resolutions.
2315 */
Willy Tarreau0fbc16c2022-09-08 15:07:13 +02002316struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002317{
2318 struct resolvers *resolvers = context;
2319 struct resolv_resolution *res, *resback;
2320 int exp;
2321
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002322 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002323 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2324
Willy Tarreauf766ec62021-10-18 16:46:38 +02002325 /* Handle all expired resolutions from the active list. Elements that
2326 * need to be removed will in fact be moved to the death_row. Other
2327 * ones will be handled normally.
2328 */
2329
Willy Tarreauf766ec62021-10-18 16:46:38 +02002330 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2331 while (&res->list != &resolvers->resolutions.curr) {
2332 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2333
Christopher Faulet0efc0992021-03-11 18:09:53 +01002334 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002335 abort_resolution(res);
2336 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002337 continue;
2338 }
2339
Emeric Brunc9437992021-02-12 19:42:55 +01002340 /* When we find the first resolution in the future, then we can
2341 * stop here */
2342 exp = tick_add(res->last_query, resolvers->timeout.retry);
2343 if (!tick_is_expired(exp, now_ms))
2344 break;
2345
2346 /* If current resolution has been tried too many times and
2347 * finishes in timeout we update its status and remove it from
2348 * the list */
2349 if (!res->try) {
2350 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002351 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002352
2353 /* Notify the result to the requesters */
2354 if (!res->nb_responses)
2355 res->status = RSLV_STATUS_TIMEOUT;
2356 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002357 keep_answer_items |= req->requester_error_cb(req, res->status);
2358 if (!keep_answer_items)
2359 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002360
2361 /* Clean up resolution info and remove it from the
2362 * current list */
2363 resolv_reset_resolution(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002364
2365 /* subsequent entries might have been deleted here */
2366 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreauaae73202021-10-19 22:01:36 +02002367 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002368 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002369 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002370 }
2371 else {
2372 /* Otherwise resend the DNS query and requeue the resolution */
2373 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2374 /* No response received (a real timeout) or fallback already done */
2375 res->query_type = res->prefered_query_type;
2376 res->try--;
2377 }
2378 else {
2379 /* Fallback from A to AAAA or the opposite and re-send
2380 * the resolution immediately. try counter is not
2381 * decremented. */
2382 if (res->prefered_query_type == DNS_RTYPE_A)
2383 res->query_type = DNS_RTYPE_AAAA;
2384 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2385 res->query_type = DNS_RTYPE_A;
2386 else
2387 res->try--;
2388 }
2389 resolv_send_query(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002390 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2391 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002392 }
2393 }
2394
2395 /* Handle all resolutions in the wait list */
2396 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002397 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002398 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002399 continue;
2400 }
2401
Emeric Brunc9437992021-02-12 19:42:55 +01002402 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2403 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2404 continue;
2405
2406 if (resolv_run_resolution(res) != 1) {
2407 res->last_resolution = now_ms;
Willy Tarreauaae73202021-10-19 22:01:36 +02002408 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002409 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002410 }
2411 }
Emeric Brunc9437992021-02-12 19:42:55 +01002412 resolv_update_resolvers_timeout(resolvers);
2413 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002414
2415 /* now we can purge all queued deletions */
2416 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002417 return t;
2418}
2419
William Lallemande606c842022-07-18 14:09:58 +02002420
2421/* destroy a resolvers */
2422static void resolvers_destroy(struct resolvers *resolvers)
Emeric Brunc9437992021-02-12 19:42:55 +01002423{
Emeric Brunc9437992021-02-12 19:42:55 +01002424 struct dns_nameserver *ns, *nsback;
2425 struct resolv_resolution *res, *resback;
2426 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01002427
William Lallemande606c842022-07-18 14:09:58 +02002428 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2429 free(ns->id);
2430 free((char *)ns->conf.file);
2431 if (ns->dgram) {
2432 if (ns->dgram->conn.t.sock.fd != -1) {
2433 fd_delete(ns->dgram->conn.t.sock.fd);
2434 close(ns->dgram->conn.t.sock.fd);
Emeric Brun56fc5d92021-02-12 20:05:45 +01002435 }
William Lallemande606c842022-07-18 14:09:58 +02002436 if (ns->dgram->ring_req)
2437 ring_free(ns->dgram->ring_req);
2438 free(ns->dgram);
Emeric Brunc9437992021-02-12 19:42:55 +01002439 }
William Lallemande606c842022-07-18 14:09:58 +02002440 if (ns->stream) {
2441 if (ns->stream->ring_req)
2442 ring_free(ns->stream->ring_req);
2443 if (ns->stream->task_req)
2444 task_destroy(ns->stream->task_req);
2445 if (ns->stream->task_rsp)
2446 task_destroy(ns->stream->task_rsp);
2447 free(ns->stream);
2448 }
2449 LIST_DEL_INIT(&ns->list);
2450 EXTRA_COUNTERS_FREE(ns->extra_counters);
2451 free(ns);
2452 }
Emeric Brunc9437992021-02-12 19:42:55 +01002453
William Lallemande606c842022-07-18 14:09:58 +02002454 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2455 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2456 LIST_DEL_INIT(&req->list);
2457 pool_free(resolv_requester_pool, req);
Emeric Brunc9437992021-02-12 19:42:55 +01002458 }
William Lallemande606c842022-07-18 14:09:58 +02002459 resolv_free_resolution(res);
2460 }
Emeric Brunc9437992021-02-12 19:42:55 +01002461
William Lallemande606c842022-07-18 14:09:58 +02002462 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2463 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2464 LIST_DEL_INIT(&req->list);
2465 pool_free(resolv_requester_pool, req);
Emeric Brunc9437992021-02-12 19:42:55 +01002466 }
William Lallemande606c842022-07-18 14:09:58 +02002467 resolv_free_resolution(res);
2468 }
Emeric Brunc9437992021-02-12 19:42:55 +01002469
William Lallemande606c842022-07-18 14:09:58 +02002470 free_proxy(resolvers->px);
2471 free(resolvers->id);
2472 free((char *)resolvers->conf.file);
2473 task_destroy(resolvers->t);
2474 LIST_DEL_INIT(&resolvers->list);
2475 free(resolvers);
2476}
2477
2478/* Release memory allocated by DNS */
2479static void resolvers_deinit(void)
2480{
2481 struct resolvers *resolvers, *resolversback;
2482 struct resolv_srvrq *srvrq, *srvrqback;
2483
2484 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2485 resolvers_destroy(resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01002486 }
2487
2488 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2489 free(srvrq->name);
2490 free(srvrq->hostname_dn);
Willy Tarreauaae73202021-10-19 22:01:36 +02002491 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002492 free(srvrq);
2493 }
2494}
2495
2496/* Finalizes the DNS configuration by allocating required resources and checking
2497 * live parameters.
William Lallemand866b88b2022-08-24 09:58:31 +02002498 * Returns 0 on success, 1 on error.
Emeric Brunc9437992021-02-12 19:42:55 +01002499 */
2500static int resolvers_finalize_config(void)
2501{
2502 struct resolvers *resolvers;
2503 struct proxy *px;
2504 int err_code = 0;
2505
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002506 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002507
Emeric Brunc9437992021-02-12 19:42:55 +01002508 /* allocate pool of resolution per resolvers */
2509 list_for_each_entry(resolvers, &sec_resolvers, list) {
2510 struct dns_nameserver *ns;
2511 struct task *t;
2512
2513 /* Check if we can create the socket with nameservers info */
2514 list_for_each_entry(ns, &resolvers->nameservers, list) {
2515 int fd;
2516
2517 if (ns->dgram) {
2518 /* Check nameserver info */
2519 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002520 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002521 resolvers->id, ns->id);
2522 err_code |= (ERR_ALERT|ERR_ABORT);
2523 continue;
2524 }
2525 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
William Lallemandb10b1192022-08-24 14:50:32 +02002526 if (!resolvers->conf.implicit) { /* emit a warning only if it was configured manually */
2527 ha_warning("resolvers '%s': can't connect socket for nameserver '%s'.\n",
2528 resolvers->id, ns->id);
2529 }
Emeric Brunc9437992021-02-12 19:42:55 +01002530 close(fd);
William Lallemandc31577f2022-07-26 10:50:09 +02002531 err_code |= ERR_WARN;
Emeric Brunc9437992021-02-12 19:42:55 +01002532 continue;
2533 }
2534 close(fd);
2535 }
2536 }
2537
2538 /* Create the task associated to the resolvers section */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002539 if ((t = task_new_anywhere()) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002540 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002541 err_code |= (ERR_ALERT|ERR_ABORT);
2542 goto err;
2543 }
2544
2545 /* Update task's parameters */
2546 t->process = process_resolvers;
2547 t->context = resolvers;
2548 resolvers->t = t;
2549 task_wakeup(t, TASK_WOKEN_INIT);
2550 }
2551
2552 for (px = proxies_list; px; px = px->next) {
2553 struct server *srv;
2554
Willy Tarreau9b46fb42022-06-10 11:11:44 +02002555 if (px->flags & PR_FL_DISABLED) {
2556 /* must not run and will not work anyway since
2557 * nothing in the proxy is initialized.
2558 */
2559 continue;
2560 }
2561
Emeric Brunc9437992021-02-12 19:42:55 +01002562 for (srv = px->srv; srv; srv = srv->next) {
2563 struct resolvers *resolvers;
2564
2565 if (!srv->resolvers_id)
2566 continue;
2567
2568 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002569 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002570 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2571 err_code |= (ERR_ALERT|ERR_ABORT);
2572 continue;
2573 }
2574 srv->resolvers = resolvers;
Christopher Fauletdcac4182021-06-15 16:17:17 +02002575 srv->srvrq_check = NULL;
2576 if (srv->srvrq) {
2577 if (!srv->srvrq->resolvers) {
2578 srv->srvrq->resolvers = srv->resolvers;
2579 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2580 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
2581 proxy_type_str(px), px->id, srv->id);
2582 err_code |= (ERR_ALERT|ERR_ABORT);
2583 continue;
2584 }
2585 }
Emeric Brunc9437992021-02-12 19:42:55 +01002586
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002587 srv->srvrq_check = task_new_anywhere();
Christopher Fauletdcac4182021-06-15 16:17:17 +02002588 if (!srv->srvrq_check) {
2589 ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002590 proxy_type_str(px), px->id, srv->id);
2591 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Fauletdcac4182021-06-15 16:17:17 +02002592 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002593 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002594 srv->srvrq_check->process = resolv_srvrq_expire_task;
2595 srv->srvrq_check->context = srv;
2596 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002597 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002598 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002599 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002600 proxy_type_str(px), px->id, srv->id);
2601 err_code |= (ERR_ALERT|ERR_ABORT);
2602 continue;
2603 }
Amaury Denoyelledd565202021-08-26 15:35:59 +02002604
2605 srv->flags |= SRV_F_NON_PURGEABLE;
Emeric Brunc9437992021-02-12 19:42:55 +01002606 }
2607 }
2608
2609 if (err_code & (ERR_ALERT|ERR_ABORT))
2610 goto err;
2611
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002612 leave_resolver_code();
William Lallemand866b88b2022-08-24 09:58:31 +02002613 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002614 err:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002615 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002616 resolvers_deinit();
William Lallemand866b88b2022-08-24 09:58:31 +02002617 return 1;
Emeric Brunc9437992021-02-12 19:42:55 +01002618
2619}
2620
Willy Tarreaucaff6312022-05-27 10:17:46 +02002621static int stats_dump_resolv_to_buffer(struct stconn *sc,
Emeric Brunc9437992021-02-12 19:42:55 +01002622 struct dns_nameserver *ns,
2623 struct field *stats, size_t stats_count,
2624 struct list *stat_modules)
2625{
Willy Tarreaucaff6312022-05-27 10:17:46 +02002626 struct appctx *appctx = __sc_appctx(sc);
2627 struct channel *rep = sc_ic(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002628 struct stats_module *mod;
2629 size_t idx = 0;
2630
2631 memset(stats, 0, sizeof(struct field) * stats_count);
2632
2633 list_for_each_entry(mod, stat_modules, list) {
2634 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2635
2636 mod->fill_stats(counters, stats + idx);
2637 idx += mod->stats_count;
2638 }
2639
2640 if (!stats_dump_one_line(stats, idx, appctx))
2641 return 0;
2642
2643 if (!stats_putchk(rep, NULL, &trash))
2644 goto full;
2645
2646 return 1;
2647
2648 full:
Willy Tarreaucaff6312022-05-27 10:17:46 +02002649 sc_have_room(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002650 return 0;
2651}
2652
2653/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2654 * as a pointer to the current nameserver.
2655 */
Willy Tarreaucaff6312022-05-27 10:17:46 +02002656int stats_dump_resolvers(struct stconn *sc,
Emeric Brunc9437992021-02-12 19:42:55 +01002657 struct field *stats, size_t stats_count,
2658 struct list *stat_modules)
2659{
Willy Tarreaucaff6312022-05-27 10:17:46 +02002660 struct appctx *appctx = __sc_appctx(sc);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002661 struct show_stat_ctx *ctx = appctx->svcctx;
Willy Tarreaucaff6312022-05-27 10:17:46 +02002662 struct channel *rep = sc_ic(sc);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002663 struct resolvers *resolver = ctx->obj1;
2664 struct dns_nameserver *ns = ctx->obj2;
Emeric Brunc9437992021-02-12 19:42:55 +01002665
2666 if (!resolver)
2667 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2668
2669 /* dump resolvers */
2670 list_for_each_entry_from(resolver, &sec_resolvers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002671 ctx->obj1 = resolver;
Emeric Brunc9437992021-02-12 19:42:55 +01002672
Willy Tarreau91cefca2022-05-03 17:08:29 +02002673 ns = ctx->obj2 ?
2674 ctx->obj2 :
Emeric Brunc9437992021-02-12 19:42:55 +01002675 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2676
2677 list_for_each_entry_from(ns, &resolver->nameservers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002678 ctx->obj2 = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002679
2680 if (buffer_almost_full(&rep->buf))
2681 goto full;
2682
Willy Tarreaucaff6312022-05-27 10:17:46 +02002683 if (!stats_dump_resolv_to_buffer(sc, ns,
Emeric Brunc9437992021-02-12 19:42:55 +01002684 stats, stats_count,
2685 stat_modules)) {
2686 return 0;
2687 }
2688 }
2689
Willy Tarreau91cefca2022-05-03 17:08:29 +02002690 ctx->obj2 = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002691 }
2692
2693 return 1;
2694
2695 full:
Willy Tarreaucaff6312022-05-27 10:17:46 +02002696 sc_need_room(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002697 return 0;
2698}
2699
2700void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2701{
2702 struct resolvers *resolvers;
2703 struct dns_nameserver *ns;
2704 struct stats_module *mod;
2705 void *counters;
2706
2707 list_for_each_entry(mod, stat_modules, list) {
2708 if (!mod->clearable && !clrall)
2709 continue;
2710
2711 list_for_each_entry(resolvers, &sec_resolvers, list) {
2712 list_for_each_entry(ns, &resolvers->nameservers, list) {
2713 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2714 memcpy(counters, mod->counters, mod->counters_size);
2715 }
2716 }
2717 }
2718
2719}
2720
2721int resolv_allocate_counters(struct list *stat_modules)
2722{
2723 struct stats_module *mod;
2724 struct resolvers *resolvers;
2725 struct dns_nameserver *ns;
2726
2727 list_for_each_entry(resolvers, &sec_resolvers, list) {
2728 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunf8642ee2021-10-29 17:59:18 +02002729 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
Emeric Brunc9437992021-02-12 19:42:55 +01002730 alloc_failed);
2731
2732 list_for_each_entry(mod, stat_modules, list) {
2733 EXTRA_COUNTERS_ADD(mod,
2734 ns->extra_counters,
2735 mod->counters,
2736 mod->counters_size);
2737 }
2738
2739 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2740
2741 list_for_each_entry(mod, stat_modules, list) {
2742 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2743 mod->counters, mod->counters_size);
2744
2745 /* Store the ns counters pointer */
Emeric Brunf8642ee2021-10-29 17:59:18 +02002746 if (strcmp(mod->name, "resolvers") == 0) {
2747 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
Emeric Brunc9437992021-02-12 19:42:55 +01002748 ns->counters->id = ns->id;
2749 ns->counters->pid = resolvers->id;
2750 }
2751 }
2752 }
2753 }
2754
2755 return 1;
2756
2757alloc_failed:
2758 return 0;
2759}
2760
Willy Tarreaudb933d62022-05-05 15:39:02 +02002761/* if an arg is found, it sets the optional resolvers section pointer into a
2762 * show_resolvers_ctx struct pointed to by svcctx, or NULL when dumping all.
2763 */
Emeric Brunc9437992021-02-12 19:42:55 +01002764static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2765{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002766 struct show_resolvers_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Emeric Brunc9437992021-02-12 19:42:55 +01002767 struct resolvers *presolvers;
2768
2769 if (*args[2]) {
2770 list_for_each_entry(presolvers, &sec_resolvers, list) {
2771 if (strcmp(presolvers->id, args[2]) == 0) {
Willy Tarreaudb933d62022-05-05 15:39:02 +02002772 ctx->forced_section = presolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002773 break;
2774 }
2775 }
Willy Tarreaudb933d62022-05-05 15:39:02 +02002776 if (ctx->forced_section == NULL)
Emeric Brunc9437992021-02-12 19:42:55 +01002777 return cli_err(appctx, "Can't find that resolvers section\n");
2778 }
2779 return 0;
2780}
2781
2782/* Dumps counters from all resolvers section and associated name servers. It
2783 * returns 0 if the output buffer is full and it needs to be called again,
Willy Tarreaudb933d62022-05-05 15:39:02 +02002784 * otherwise non-zero. It may limit itself to the resolver pointed to by the
2785 * <resolvers> field of struct show_resolvers_ctx pointed to by <svcctx> if
2786 * it's not null.
Emeric Brunc9437992021-02-12 19:42:55 +01002787 */
2788static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2789{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002790 struct show_resolvers_ctx *ctx = appctx->svcctx;
Willy Tarreaudb933d62022-05-05 15:39:02 +02002791 struct resolvers *resolvers = ctx->resolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002792 struct dns_nameserver *ns;
2793
2794 chunk_reset(&trash);
2795
Willy Tarreau12d52282022-05-05 16:38:13 +02002796 if (LIST_ISEMPTY(&sec_resolvers)) {
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002797 if (applet_putstr(appctx, "No resolvers found\n") == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002798 goto full;
2799 }
2800 else {
2801 if (!resolvers)
2802 resolvers = LIST_ELEM(sec_resolvers.n, typeof(resolvers), list);
Willy Tarreau4e047e72022-05-05 16:00:45 +02002803
Willy Tarreau12d52282022-05-05 16:38:13 +02002804 list_for_each_entry_from(resolvers, &sec_resolvers, list) {
2805 if (ctx->forced_section != NULL && ctx->forced_section != resolvers)
2806 continue;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002807
Willy Tarreau12d52282022-05-05 16:38:13 +02002808 ctx->resolvers = resolvers;
2809 ns = ctx->ns;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002810
Willy Tarreau12d52282022-05-05 16:38:13 +02002811 if (!ns) {
2812 chunk_printf(&trash, "Resolvers section %s\n", resolvers->id);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002813 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002814 goto full;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002815
Willy Tarreau12d52282022-05-05 16:38:13 +02002816 ns = LIST_ELEM(resolvers->nameservers.n, typeof(ns), list);
2817 ctx->ns = ns;
2818 }
Willy Tarreau4e047e72022-05-05 16:00:45 +02002819
Willy Tarreau12d52282022-05-05 16:38:13 +02002820 list_for_each_entry_from(ns, &resolvers->nameservers, list) {
2821 chunk_reset(&trash);
2822 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2823 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2824 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2825 chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
2826 chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
2827 chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
2828 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
2829 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
2830 chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
2831 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
2832 chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
2833 chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
2834 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
2835 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
2836 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
2837 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002838 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002839 goto full;
2840 ctx->ns = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002841 }
Emeric Brunc9437992021-02-12 19:42:55 +01002842
Willy Tarreau12d52282022-05-05 16:38:13 +02002843 ctx->ns = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002844
Willy Tarreau12d52282022-05-05 16:38:13 +02002845 /* was this the only section to dump ? */
2846 if (ctx->forced_section)
2847 break;
2848 }
Emeric Brunc9437992021-02-12 19:42:55 +01002849 }
Willy Tarreau12d52282022-05-05 16:38:13 +02002850
2851 /* done! */
2852 return 1;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002853 full:
2854 /* the output buffer is full, retry later */
Willy Tarreau4e047e72022-05-05 16:00:45 +02002855 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002856}
2857
2858/* register cli keywords */
2859static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002860 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002861 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2862 {{},}
2863 }
2864};
2865
2866INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2867
2868/*
2869 * Prepare <rule> for hostname resolution.
2870 * Returns -1 in case of any allocation failure, 0 if not.
2871 * On error, a global failure counter is also incremented.
2872 */
Willy Tarreau947ae122021-10-14 08:11:48 +02002873static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002874{
2875 char *hostname_dn;
Willy Tarreau947ae122021-10-14 08:11:48 +02002876 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002877 struct buffer *tmp = get_trash_chunk();
2878
2879 if (!hostname)
2880 return 0;
2881
Emeric Brunc9437992021-02-12 19:42:55 +01002882 hostname_dn = tmp->area;
Willy Tarreaubf9498a2021-10-14 07:49:49 +02002883 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002884 hostname_dn, tmp->size);
2885 if (hostname_dn_len == -1)
2886 goto err;
2887
2888
2889 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2890 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2891 if (!stream->resolv_ctx.hostname_dn)
2892 goto err;
2893
2894 return 0;
2895
2896 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002897 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002898 resolv_failed_resolutions += 1;
2899 return -1;
2900}
2901
2902
2903/*
2904 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2905 */
2906enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2907 struct session *sess, struct stream *s, int flags)
2908{
2909 struct resolv_resolution *resolution;
2910 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002911 struct resolv_requester *req;
2912 struct resolvers *resolvers;
2913 struct resolv_resolution *res;
2914 int exp, locked = 0;
2915 enum act_return ret = ACT_RET_CONT;
2916
2917 resolvers = rule->arg.resolv.resolvers;
2918
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002919 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002920
Emeric Brunc9437992021-02-12 19:42:55 +01002921 /* we have a response to our DNS resolution */
2922 use_cache:
2923 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2924 resolution = s->resolv_ctx.requester->resolution;
2925 if (!locked) {
2926 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2927 locked = 1;
2928 }
2929
2930 if (resolution->step == RSLV_STEP_RUNNING)
2931 goto yield;
2932 if (resolution->step == RSLV_STEP_NONE) {
2933 /* We update the variable only if we have a valid response. */
2934 if (resolution->status == RSLV_STATUS_VALID) {
2935 struct sample smp;
2936 short ip_sin_family = 0;
2937 void *ip = NULL;
2938
2939 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2940 0, &ip, &ip_sin_family, NULL);
2941
2942 switch (ip_sin_family) {
2943 case AF_INET:
2944 smp.data.type = SMP_T_IPV4;
2945 memcpy(&smp.data.u.ipv4, ip, 4);
2946 break;
2947 case AF_INET6:
2948 smp.data.type = SMP_T_IPV6;
2949 memcpy(&smp.data.u.ipv6, ip, 16);
2950 break;
2951 default:
2952 ip = NULL;
2953 }
2954
2955 if (ip) {
2956 smp.px = px;
2957 smp.sess = sess;
2958 smp.strm = s;
2959
2960 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2961 }
2962 }
2963 }
2964
2965 goto release_requester;
2966 }
2967
2968 /* need to configure and start a new DNS resolution */
2969 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2970 if (smp == NULL)
2971 goto end;
2972
Willy Tarreau947ae122021-10-14 08:11:48 +02002973 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002974 goto end; /* on error, ignore the action */
2975
2976 s->resolv_ctx.parent = rule;
2977
2978 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2979 locked = 1;
2980
2981 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2982
2983 /* Check if there is a fresh enough response in the cache of our associated resolution */
2984 req = s->resolv_ctx.requester;
2985 if (!req || !req->resolution)
2986 goto release_requester; /* on error, ignore the action */
2987 res = req->resolution;
2988
2989 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2990 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2991 && !tick_is_expired(exp, now_ms)) {
2992 goto use_cache;
2993 }
2994
2995 resolv_trigger_resolution(s->resolv_ctx.requester);
2996
2997 yield:
2998 if (flags & ACT_OPT_FINAL)
2999 goto release_requester;
3000 ret = ACT_RET_YIELD;
3001
3002 end:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01003003 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01003004 if (locked)
3005 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
3006 return ret;
3007
3008 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003009 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01003010 s->resolv_ctx.hostname_dn_len = 0;
3011 if (s->resolv_ctx.requester) {
Willy Tarreau6878f802021-10-20 14:07:31 +02003012 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01003013 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
3014 s->resolv_ctx.requester = NULL;
3015 }
3016 goto end;
3017}
3018
3019static void release_resolv_action(struct act_rule *rule)
3020{
3021 release_sample_expr(rule->arg.resolv.expr);
3022 free(rule->arg.resolv.varname);
3023 free(rule->arg.resolv.resolvers_id);
3024 free(rule->arg.resolv.opts);
3025}
3026
3027
3028/* parse "do-resolve" action
3029 * This action takes the following arguments:
3030 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3031 *
3032 * - <varName> is the variable name where the result of the DNS resolution will be stored
3033 * (mandatory)
3034 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3035 * (mandatory)
3036 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3037 * (optional), defaults to ipv6
3038 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3039 */
3040enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3041{
3042 int cur_arg;
3043 struct sample_expr *expr;
3044 unsigned int where;
3045 const char *beg, *end;
3046
3047 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3048 cur_arg = *orig_arg - 1;
3049
3050 /* locate varName, which is mandatory */
3051 beg = strchr(args[cur_arg], '(');
3052 if (beg == NULL)
3053 goto do_resolve_parse_error;
3054 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3055 end = strchr(beg, ',');
3056 if (end == NULL)
3057 goto do_resolve_parse_error;
3058 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3059 if (rule->arg.resolv.varname == NULL)
3060 goto do_resolve_parse_error;
3061
3062
3063 /* locate resolversSectionName, which is mandatory.
3064 * Since next parameters are optional, the delimiter may be comma ','
3065 * or closing parenthesis ')'
3066 */
3067 beg = end + 1;
3068 end = strchr(beg, ',');
3069 if (end == NULL)
3070 end = strchr(beg, ')');
3071 if (end == NULL)
3072 goto do_resolve_parse_error;
3073 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3074 if (rule->arg.resolv.resolvers_id == NULL)
3075 goto do_resolve_parse_error;
3076
3077
3078 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3079 if (rule->arg.resolv.opts == NULL)
3080 goto do_resolve_parse_error;
3081
3082 /* Default priority is ipv6 */
3083 rule->arg.resolv.opts->family_prio = AF_INET6;
3084
3085 /* optional arguments accepted for now:
3086 * ipv4 or ipv6
3087 */
3088 while (*end != ')') {
3089 beg = end + 1;
3090 end = strchr(beg, ',');
3091 if (end == NULL)
3092 end = strchr(beg, ')');
3093 if (end == NULL)
3094 goto do_resolve_parse_error;
3095
3096 if (strncmp(beg, "ipv4", end - beg) == 0) {
3097 rule->arg.resolv.opts->family_prio = AF_INET;
3098 }
3099 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3100 rule->arg.resolv.opts->family_prio = AF_INET6;
3101 }
3102 else {
3103 goto do_resolve_parse_error;
3104 }
3105 }
3106
3107 cur_arg = cur_arg + 1;
3108
3109 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3110 if (!expr)
3111 goto do_resolve_parse_error;
3112
3113
3114 where = 0;
3115 if (px->cap & PR_CAP_FE)
3116 where |= SMP_VAL_FE_HRQ_HDR;
3117 if (px->cap & PR_CAP_BE)
3118 where |= SMP_VAL_BE_HRQ_HDR;
3119
3120 if (!(expr->fetch->val & where)) {
3121 memprintf(err,
3122 "fetch method '%s' extracts information from '%s', none of which is available here",
3123 args[cur_arg-1], sample_src_names(expr->fetch->use));
3124 free(expr);
3125 return ACT_RET_PRS_ERR;
3126 }
3127 rule->arg.resolv.expr = expr;
3128 rule->action = ACT_CUSTOM;
3129 rule->action_ptr = resolv_action_do_resolve;
3130 *orig_arg = cur_arg;
3131
3132 rule->check_ptr = check_action_do_resolve;
3133 rule->release_ptr = release_resolv_action;
3134
3135 return ACT_RET_PRS_OK;
3136
3137 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003138 ha_free(&rule->arg.resolv.varname);
3139 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003140 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3141 args[cur_arg]);
3142 return ACT_RET_PRS_ERR;
3143}
3144
3145static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003146 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003147 { /* END */ }
3148}};
3149
3150INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3151
3152static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003153 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003154 { /* END */ }
3155}};
3156
3157INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3158
3159/* Check an "http-request do-resolve" action.
3160 *
3161 * The function returns 1 in success case, otherwise, it returns 0 and err is
3162 * filled.
3163 */
3164int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3165{
3166 struct resolvers *resolvers = NULL;
3167
3168 if (rule->arg.resolv.resolvers_id == NULL) {
3169 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3170 return 0;
3171 }
3172
3173 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3174 if (resolvers == NULL) {
3175 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3176 return 0;
3177 }
3178 rule->arg.resolv.resolvers = resolvers;
3179
3180 return 1;
3181}
3182
3183void resolvers_setup_proxy(struct proxy *px)
3184{
3185 px->last_change = now.tv_sec;
3186 px->cap = PR_CAP_FE | PR_CAP_BE;
3187 px->maxconn = 0;
3188 px->conn_retries = 1;
3189 px->timeout.server = TICK_ETERNITY;
3190 px->timeout.client = TICK_ETERNITY;
3191 px->timeout.connect = TICK_ETERNITY;
3192 px->accept = NULL;
3193 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
Emeric Brunc9437992021-02-12 19:42:55 +01003194}
3195
William Lallemand73edfe42022-05-05 17:36:09 +02003196static int parse_resolve_conf(char **errmsg, char **warnmsg)
3197{
3198 struct dns_nameserver *newnameserver = NULL;
3199 const char *whitespace = "\r\n\t ";
3200 char *resolv_line = NULL;
3201 int resolv_linenum = 0;
3202 FILE *f = NULL;
3203 char *address = NULL;
3204 struct sockaddr_storage *sk = NULL;
3205 struct protocol *proto;
3206 int duplicate_name = 0;
3207 int err_code = 0;
3208
3209 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3210 memprintf(errmsg, "out of memory.\n");
3211 err_code |= ERR_ALERT | ERR_FATAL;
3212 goto resolv_out;
3213 }
3214
3215 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3216 if (errmsg)
3217 memprintf(errmsg, "failed to open /etc/resolv.conf.");
3218 err_code |= ERR_ALERT | ERR_FATAL;
3219 goto resolv_out;
3220 }
3221
3222 sk = calloc(1, sizeof(*sk));
3223 if (sk == NULL) {
3224 if (errmsg)
3225 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3226 err_code |= ERR_ALERT | ERR_FATAL;
3227 goto resolv_out;
3228 }
3229
3230 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3231 resolv_linenum++;
3232 if (strncmp(resolv_line, "nameserver", 10) != 0)
3233 continue;
3234
3235 address = strtok(resolv_line + 10, whitespace);
3236 if (address == resolv_line + 10)
3237 continue;
3238
3239 if (address == NULL) {
3240 if (warnmsg)
3241 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3242 *warnmsg ? *warnmsg : "", resolv_linenum);
3243 err_code |= ERR_WARN;
3244 continue;
3245 }
3246
3247 duplicate_name = 0;
3248 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3249 if (strcmp(newnameserver->id, address) == 0) {
3250 if (warnmsg)
3251 memprintf(warnmsg, "%sParsing [/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",
3252 *warnmsg ? *warnmsg : "", resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3253 err_code |= ERR_WARN;
3254 duplicate_name = 1;
3255 }
3256 }
3257
3258 if (duplicate_name)
3259 continue;
3260
3261 memset(sk, 0, sizeof(*sk));
3262 if (!str2ip2(address, sk, 1)) {
3263 if (warnmsg)
3264 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3265 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3266 err_code |= ERR_WARN;
3267 continue;
3268 }
3269
3270 set_host_port(sk, 53);
3271
3272 proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
3273 if (!proto || !proto->connect) {
3274 if (warnmsg)
3275 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3276 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3277 err_code |= ERR_WARN;
3278 continue;
3279 }
3280
3281 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3282 if (errmsg)
3283 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3284 err_code |= ERR_ALERT | ERR_FATAL;
3285 goto resolv_out;
3286 }
3287
3288 if (dns_dgram_init(newnameserver, sk) < 0) {
3289 if (errmsg)
3290 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3291 err_code |= ERR_ALERT | ERR_FATAL;
3292 free(newnameserver);
3293 goto resolv_out;
3294 }
3295
3296 newnameserver->conf.file = strdup("/etc/resolv.conf");
3297 if (newnameserver->conf.file == NULL) {
3298 if (errmsg)
3299 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3300 err_code |= ERR_ALERT | ERR_FATAL;
3301 free(newnameserver);
3302 goto resolv_out;
3303 }
3304
3305 newnameserver->id = strdup(address);
3306 if (newnameserver->id == NULL) {
3307 if (errmsg)
3308 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3309 err_code |= ERR_ALERT | ERR_FATAL;
3310 free((char *)newnameserver->conf.file);
3311 free(newnameserver);
3312 goto resolv_out;
3313 }
3314
3315 newnameserver->parent = curr_resolvers;
3316 newnameserver->process_responses = resolv_process_responses;
3317 newnameserver->conf.line = resolv_linenum;
3318 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
3319 }
3320
3321resolv_out:
3322 free(sk);
3323 free(resolv_line);
3324 if (f != NULL)
3325 fclose(f);
3326
3327 return err_code;
3328}
3329
William Lallemande7f57762022-05-05 18:27:48 +02003330static int resolvers_new(struct resolvers **resolvers, const char *id, const char *file, int linenum)
3331{
3332 struct resolvers *r = NULL;
3333 struct proxy *p = NULL;
3334 int err_code = 0;
3335
3336 if ((r = calloc(1, sizeof(*r))) == NULL) {
3337 err_code |= ERR_ALERT | ERR_ABORT;
3338 goto out;
3339 }
3340
3341 /* allocate new proxy to tcp servers */
3342 p = calloc(1, sizeof *p);
3343 if (!p) {
3344 err_code |= ERR_ALERT | ERR_FATAL;
3345 goto out;
3346 }
3347
3348 init_new_proxy(p);
3349 resolvers_setup_proxy(p);
3350 p->parent = r;
3351 p->id = strdup(id);
3352 p->conf.args.file = p->conf.file = strdup(file);
3353 p->conf.args.line = p->conf.line = linenum;
3354 r->px = p;
3355
3356 /* default values */
3357 LIST_APPEND(&sec_resolvers, &r->list);
3358 r->conf.file = strdup(file);
3359 r->conf.line = linenum;
3360 r->id = strdup(id);
3361 r->query_ids = EB_ROOT;
3362 /* default maximum response size */
3363 r->accepted_payload_size = 512;
3364 /* default hold period for nx, other, refuse and timeout is 30s */
3365 r->hold.nx = 30000;
3366 r->hold.other = 30000;
3367 r->hold.refused = 30000;
3368 r->hold.timeout = 30000;
3369 r->hold.obsolete = 0;
3370 /* default hold period for valid is 10s */
3371 r->hold.valid = 10000;
3372 r->timeout.resolve = 1000;
3373 r->timeout.retry = 1000;
3374 r->resolve_retries = 3;
3375 LIST_INIT(&r->nameservers);
3376 LIST_INIT(&r->resolutions.curr);
3377 LIST_INIT(&r->resolutions.wait);
3378 HA_SPIN_INIT(&r->lock);
3379
3380 *resolvers = r;
3381
3382out:
3383 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3384 ha_free(&r);
3385 ha_free(&p);
3386 }
3387
3388 return err_code;
3389}
3390
3391
Emeric Brunc9437992021-02-12 19:42:55 +01003392/*
3393 * Parse a <resolvers> section.
3394 * Returns the error code, 0 if OK, or any combination of :
3395 * - ERR_ABORT: must abort ASAP
3396 * - ERR_FATAL: we can continue parsing but not start the service
3397 * - ERR_WARN: a warning has been emitted
3398 * - ERR_ALERT: an alert has been emitted
3399 * Only the two first ones can stop processing, the two others are just
3400 * indicators.
3401 */
3402int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3403{
3404 const char *err;
3405 int err_code = 0;
3406 char *errmsg = NULL;
William Lallemand106bd292022-05-05 17:20:08 +02003407 char *warnmsg = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01003408
3409 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3410 if (!*args[1]) {
3411 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3412 err_code |= ERR_ALERT | ERR_ABORT;
3413 goto out;
3414 }
3415
3416 err = invalid_char(args[1]);
3417 if (err) {
3418 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3419 file, linenum, *err, args[0], args[1]);
3420 err_code |= ERR_ALERT | ERR_ABORT;
3421 goto out;
3422 }
3423
3424 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3425 /* Error if two resolvers owns the same name */
3426 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3427 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3428 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3429 err_code |= ERR_ALERT | ERR_ABORT;
3430 }
3431 }
3432
William Lallemande7f57762022-05-05 18:27:48 +02003433 err_code |= resolvers_new(&curr_resolvers, args[1], file, linenum);
3434 if (err_code & ERR_ALERT) {
Emeric Brunc9437992021-02-12 19:42:55 +01003435 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
Emeric Brunc9437992021-02-12 19:42:55 +01003436 goto out;
3437 }
3438
Emeric Brunc9437992021-02-12 19:42:55 +01003439 }
3440 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3441 struct dns_nameserver *newnameserver = NULL;
3442 struct sockaddr_storage *sk;
3443 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003444 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003445
3446 if (!*args[2]) {
3447 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3448 file, linenum, args[0]);
3449 err_code |= ERR_ALERT | ERR_FATAL;
3450 goto out;
3451 }
3452
3453 err = invalid_char(args[1]);
3454 if (err) {
3455 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3456 file, linenum, *err, args[1]);
3457 err_code |= ERR_ALERT | ERR_FATAL;
3458 goto out;
3459 }
3460
3461 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3462 /* Error if two resolvers owns the same name */
3463 if (strcmp(newnameserver->id, args[1]) == 0) {
3464 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3465 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3466 err_code |= ERR_ALERT | ERR_FATAL;
3467 }
3468 }
3469
Emeric Brunc8f3e452021-04-07 16:04:54 +02003470 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3471 &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 +01003472 if (!sk) {
3473 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3474 err_code |= ERR_ALERT | ERR_FATAL;
3475 goto out;
3476 }
3477
3478 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3479 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3480 err_code |= ERR_ALERT | ERR_ABORT;
3481 goto out;
3482 }
3483
Willy Tarreau91b47262022-05-20 16:36:46 +02003484 if (proto && proto->xprt_type == PROTO_TYPE_STREAM) {
Emeric Brunc8f3e452021-04-07 16:04:54 +02003485 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3486 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3487 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3488 err_code |= ERR_ABORT;
3489 goto out;
3490 }
3491
3492 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3493 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3494 err_code |= ERR_ALERT|ERR_ABORT;
3495 goto out;
3496 }
3497 }
3498 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003499 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3500 err_code |= ERR_ALERT | ERR_ABORT;
3501 goto out;
3502 }
3503
3504 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3505 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3506 err_code |= ERR_ALERT | ERR_ABORT;
3507 goto out;
3508 }
3509
3510 if ((newnameserver->id = strdup(args[1])) == NULL) {
3511 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3512 err_code |= ERR_ALERT | ERR_ABORT;
3513 goto out;
3514 }
3515
3516 newnameserver->parent = curr_resolvers;
3517 newnameserver->process_responses = resolv_process_responses;
3518 newnameserver->conf.line = linenum;
3519 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003520 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003521 }
3522 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
William Lallemand73edfe42022-05-05 17:36:09 +02003523 err_code |= parse_resolve_conf(&errmsg, &warnmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003524 if (err_code & ERR_WARN) {
3525 indent_msg(&warnmsg, 8);
3526 ha_warning("parsing [%s:%d]: %s\n", file, linenum, warnmsg);
3527 ha_free(&warnmsg);
3528 }
William Lallemand106bd292022-05-05 17:20:08 +02003529 if (err_code & ERR_ALERT) {
3530 indent_msg(&errmsg, 8);
3531 ha_alert("parsing [%s:%d]: %s\n", file, linenum, errmsg);
3532 ha_free(&errmsg);
William Lallemand73edfe42022-05-05 17:36:09 +02003533 goto out;
William Lallemand106bd292022-05-05 17:20:08 +02003534 }
Emeric Brunc9437992021-02-12 19:42:55 +01003535 }
3536 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3537 const char *res;
3538 unsigned int time;
3539
3540 if (!*args[2]) {
3541 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3542 file, linenum, args[0]);
3543 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3544 err_code |= ERR_ALERT | ERR_FATAL;
3545 goto out;
3546 }
3547 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3548 if (res == PARSE_TIME_OVER) {
3549 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3550 file, linenum, args[1], args[0]);
3551 err_code |= ERR_ALERT | ERR_FATAL;
3552 goto out;
3553 }
3554 else if (res == PARSE_TIME_UNDER) {
3555 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3556 file, linenum, args[1], args[0]);
3557 err_code |= ERR_ALERT | ERR_FATAL;
3558 goto out;
3559 }
3560 else if (res) {
3561 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3562 file, linenum, *res, args[0]);
3563 err_code |= ERR_ALERT | ERR_FATAL;
3564 goto out;
3565 }
3566 if (strcmp(args[1], "nx") == 0)
3567 curr_resolvers->hold.nx = time;
3568 else if (strcmp(args[1], "other") == 0)
3569 curr_resolvers->hold.other = time;
3570 else if (strcmp(args[1], "refused") == 0)
3571 curr_resolvers->hold.refused = time;
3572 else if (strcmp(args[1], "timeout") == 0)
3573 curr_resolvers->hold.timeout = time;
3574 else if (strcmp(args[1], "valid") == 0)
3575 curr_resolvers->hold.valid = time;
3576 else if (strcmp(args[1], "obsolete") == 0)
3577 curr_resolvers->hold.obsolete = time;
3578 else {
3579 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3580 file, linenum, args[0], args[1]);
3581 err_code |= ERR_ALERT | ERR_FATAL;
3582 goto out;
3583 }
3584
3585 }
3586 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3587 int i = 0;
3588
3589 if (!*args[1]) {
3590 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3591 file, linenum, args[0]);
3592 err_code |= ERR_ALERT | ERR_FATAL;
3593 goto out;
3594 }
3595
3596 i = atoi(args[1]);
3597 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3598 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3599 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3600 err_code |= ERR_ALERT | ERR_FATAL;
3601 goto out;
3602 }
3603
3604 curr_resolvers->accepted_payload_size = i;
3605 }
3606 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3607 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3608 file, linenum, args[0]);
3609 err_code |= ERR_ALERT | ERR_FATAL;
3610 goto out;
3611 }
3612 else if (strcmp(args[0], "resolve_retries") == 0) {
3613 if (!*args[1]) {
3614 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3615 file, linenum, args[0]);
3616 err_code |= ERR_ALERT | ERR_FATAL;
3617 goto out;
3618 }
3619 curr_resolvers->resolve_retries = atoi(args[1]);
3620 }
3621 else if (strcmp(args[0], "timeout") == 0) {
3622 if (!*args[1]) {
3623 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3624 file, linenum, args[0]);
3625 err_code |= ERR_ALERT | ERR_FATAL;
3626 goto out;
3627 }
3628 else if (strcmp(args[1], "retry") == 0 ||
3629 strcmp(args[1], "resolve") == 0) {
3630 const char *res;
3631 unsigned int tout;
3632
3633 if (!*args[2]) {
3634 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3635 file, linenum, args[0], args[1]);
3636 err_code |= ERR_ALERT | ERR_FATAL;
3637 goto out;
3638 }
3639 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3640 if (res == PARSE_TIME_OVER) {
3641 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3642 file, linenum, args[2], args[0], args[1]);
3643 err_code |= ERR_ALERT | ERR_FATAL;
3644 goto out;
3645 }
3646 else if (res == PARSE_TIME_UNDER) {
3647 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3648 file, linenum, args[2], args[0], args[1]);
3649 err_code |= ERR_ALERT | ERR_FATAL;
3650 goto out;
3651 }
3652 else if (res) {
3653 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3654 file, linenum, *res, args[0], args[1]);
3655 err_code |= ERR_ALERT | ERR_FATAL;
3656 goto out;
3657 }
3658 if (args[1][2] == 't')
3659 curr_resolvers->timeout.retry = tout;
3660 else
3661 curr_resolvers->timeout.resolve = tout;
3662 }
3663 else {
3664 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3665 file, linenum, args[0], args[1]);
3666 err_code |= ERR_ALERT | ERR_FATAL;
3667 goto out;
3668 }
3669 }
3670 else if (*args[0] != 0) {
3671 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3672 err_code |= ERR_ALERT | ERR_FATAL;
3673 goto out;
3674 }
3675
William Lallemand106bd292022-05-05 17:20:08 +02003676out:
Emeric Brunc9437992021-02-12 19:42:55 +01003677 free(errmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003678 free(warnmsg);
Emeric Brunc9437992021-02-12 19:42:55 +01003679 return err_code;
3680}
William Lallemand7867f632022-05-05 19:02:59 +02003681
3682/* try to create a "default" resolvers section which uses "/etc/resolv.conf"
3683 *
3684 * This function is opportunistic and does not try to display errors or warnings.
3685 */
3686int resolvers_create_default()
3687{
3688 int err_code = 0;
3689
William Lallemand6020c4e2022-08-24 11:15:08 +02003690 if (global.mode & MODE_MWORKER_WAIT) /* does not create the section if in wait mode */
3691 return 0;
3692
William Lallemand3bda8072022-07-18 14:12:17 +02003693 /* if the section already exists, do nothing */
William Lallemand7867f632022-05-05 19:02:59 +02003694 if (find_resolvers_by_id("default"))
3695 return 0;
3696
William Lallemand3bda8072022-07-18 14:12:17 +02003697 curr_resolvers = NULL;
William Lallemand7867f632022-05-05 19:02:59 +02003698 err_code |= resolvers_new(&curr_resolvers, "default", "<internal>", 0);
William Lallemand3bda8072022-07-18 14:12:17 +02003699 if (err_code & ERR_CODE)
3700 goto err;
William Lallemandb10b1192022-08-24 14:50:32 +02003701
3702 curr_resolvers->conf.implicit = 1;
3703
William Lallemand3bda8072022-07-18 14:12:17 +02003704 err_code |= parse_resolve_conf(NULL, NULL);
3705 if (err_code & ERR_CODE)
3706 goto err;
3707 /* check if there was any nameserver in the resolvconf file */
3708 if (LIST_ISEMPTY(&curr_resolvers->nameservers)) {
3709 err_code |= ERR_FATAL;
3710 goto err;
3711 }
3712
3713err:
3714 if (err_code & ERR_CODE) {
3715 resolvers_destroy(curr_resolvers);
3716 curr_resolvers = NULL;
3717 }
William Lallemand7867f632022-05-05 19:02:59 +02003718
William Lallemand3bda8072022-07-18 14:12:17 +02003719 /* we never return an error there, we only try to create this section
3720 * if that's possible */
William Lallemand7867f632022-05-05 19:02:59 +02003721 return 0;
3722}
3723
Emeric Brun56fc5d92021-02-12 20:05:45 +01003724int cfg_post_parse_resolvers()
3725{
3726 int err_code = 0;
3727 struct server *srv;
3728
3729 if (curr_resolvers) {
3730
3731 /* prepare forward server descriptors */
3732 if (curr_resolvers->px) {
3733 srv = curr_resolvers->px->srv;
3734 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003735 /* init ssl if needed */
3736 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3737 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3738 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3739 err_code |= ERR_ALERT | ERR_FATAL;
3740 break;
3741 }
3742 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003743 srv = srv->next;
3744 }
3745 }
3746 }
3747 curr_resolvers = NULL;
3748 return err_code;
3749}
Emeric Brunc9437992021-02-12 19:42:55 +01003750
Emeric Brun56fc5d92021-02-12 20:05:45 +01003751REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003752REGISTER_POST_DEINIT(resolvers_deinit);
3753REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);
William Lallemand7867f632022-05-05 19:02:59 +02003754REGISTER_PRE_CHECK(resolvers_create_default);