blob: aba2d245f7e678c381489a68e4731c44c262c2e2 [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>
Christopher Faulet908628c2022-03-25 16:43:49 +010030#include <haproxy/conn_stream.h>
31#include <haproxy/cs_utils.h>
Emeric Brunc9437992021-02-12 19:42:55 +010032#include <haproxy/dns.h>
33#include <haproxy/errors.h>
34#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010035#include <haproxy/http_rules.h>
36#include <haproxy/log.h>
37#include <haproxy/net_helper.h>
38#include <haproxy/protocol.h>
39#include <haproxy/proxy.h>
40#include <haproxy/resolvers.h>
41#include <haproxy/ring.h>
42#include <haproxy/sample.h>
43#include <haproxy/server.h>
44#include <haproxy/stats.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 Tarreauf766ec62021-10-18 16:46:38 +020068static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
69static 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;
289 int next;
290
291 next = tick_add(now_ms, resolvers->timeout.resolve);
292 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
293 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
294 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 ||
463 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
464 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100465
466 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100467}
468
469
470/* Resets some resolution parameters to initial values and also delete the query
471 * ID from the resolver's tree.
472 */
473static void resolv_reset_resolution(struct resolv_resolution *resolution)
474{
475 /* update resolution status */
476 resolution->step = RSLV_STEP_NONE;
477 resolution->try = 0;
478 resolution->last_resolution = now_ms;
479 resolution->nb_queries = 0;
480 resolution->nb_responses = 0;
481 resolution->query_type = resolution->prefered_query_type;
482
483 /* clean up query id */
484 eb32_delete(&resolution->qid);
485 resolution->query_id = 0;
486 resolution->qid.key = 0;
487}
488
489/* Returns the query id contained in a DNS response */
490static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
491{
492 return resp[0] * 256 + resp[1];
493}
494
495
496/* Analyses, re-builds and copies the name <name> from the DNS response packet
497 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
498 * for compressed data. The result is copied into <dest>, ensuring we don't
499 * overflow using <dest_len> Returns the number of bytes the caller can move
500 * forward. If 0 it means an error occurred while parsing the name. <offset> is
501 * the number of bytes the caller could move forward.
502 */
503int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
504 unsigned char *name, char *destination, int dest_len,
505 int *offset, unsigned int depth)
506{
507 int nb_bytes = 0, n = 0;
508 int label_len;
509 unsigned char *reader = name;
510 char *dest = destination;
511
512 while (1) {
513 if (reader >= bufend)
514 goto err;
515
516 /* Name compression is in use */
517 if ((*reader & 0xc0) == 0xc0) {
518 if (reader + 1 >= bufend)
519 goto err;
520
521 /* Must point BEFORE current position */
522 if ((buffer + reader[1]) > reader)
523 goto err;
524
525 if (depth++ > 100)
526 goto err;
527
528 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
529 dest, dest_len - nb_bytes, offset, depth);
530 if (n == 0)
531 goto err;
532
533 dest += n;
534 nb_bytes += n;
535 goto out;
536 }
537
538 label_len = *reader;
539 if (label_len == 0)
540 goto out;
541
542 /* Check if:
543 * - we won't read outside the buffer
544 * - there is enough place in the destination
545 */
546 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
547 goto err;
548
549 /* +1 to take label len + label string */
550 label_len++;
551
552 memcpy(dest, reader, label_len);
553
554 dest += label_len;
555 nb_bytes += label_len;
556 reader += label_len;
557 }
558
559 out:
560 /* offset computation:
561 * parse from <name> until finding either NULL or a pointer "c0xx"
562 */
563 reader = name;
564 *offset = 0;
565 while (reader < bufend) {
566 if ((reader[0] & 0xc0) == 0xc0) {
567 *offset += 2;
568 break;
569 }
570 else if (*reader == 0) {
571 *offset += 1;
572 break;
573 }
574 *offset += 1;
575 ++reader;
576 }
577 return nb_bytes;
578
579 err:
580 return 0;
581}
582
Willy Tarreauf766ec62021-10-18 16:46:38 +0200583/* Reinitialize the list of aborted resolutions before calling certain
584 * functions relying on it. The list must be processed by calling
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100585 * leave_resolver_code() after operations.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200586 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100587static void enter_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200588{
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100589 if (!recurse)
590 LIST_INIT(&death_row);
591 recurse++;
Willy Tarreauf766ec62021-10-18 16:46:38 +0200592}
593
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100594/* Add a resolution to the death_row. */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200595static void abort_resolution(struct resolv_resolution *res)
596{
597 LIST_DEL_INIT(&res->list);
598 LIST_APPEND(&death_row, &res->list);
599}
600
601/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100602 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreauf766ec62021-10-18 16:46:38 +0200603 * needs to defer deletions. Note that some of them are in relation via internal
604 * objects and might cause the deletion of other ones from the same list, so we
605 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
606 * and solely rely on each call to remove the first remaining list element.
607 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100608static void leave_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200609{
610 struct resolv_resolution *res;
611
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100612 recurse--;
613 if (recurse)
614 return;
615
Willy Tarreauf766ec62021-10-18 16:46:38 +0200616 while (!LIST_ISEMPTY(&death_row)) {
617 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
618 resolv_free_resolution(res);
619 }
620
621 /* make sure nobody tries to add anything without having initialized it */
622 death_row = (struct list){ };
623}
624
Christopher Faulet11c6c392021-06-15 16:08:48 +0200625/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
626 * happens when an SRV item is purged or when the server status is considered as
627 * obsolete.
628 *
Willy Tarreauf766ec62021-10-18 16:46:38 +0200629 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100630 * initialized via enter_resolver_code().
Christopher Faulet11c6c392021-06-15 16:08:48 +0200631 */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200632static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet11c6c392021-06-15 16:08:48 +0200633{
Willy Tarreau6878f802021-10-20 14:07:31 +0200634 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200635 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
636 srvrq_update_srv_status(srv, 1);
637 ha_free(&srv->hostname);
638 ha_free(&srv->hostname_dn);
639 srv->hostname_dn_len = 0;
640 memset(&srv->addr, 0, sizeof(srv->addr));
641 srv->svc_port = 0;
642 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet73001ab2021-06-15 16:14:37 +0200643
644 ebpt_delete(&srv->host_dn);
645 ha_free(&srv->host_dn.key);
646
Christopher Faulet11c6c392021-06-15 16:08:48 +0200647 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreauaae73202021-10-19 22:01:36 +0200648 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200649 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Fauletdcac4182021-06-15 16:17:17 +0200650
651 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet11c6c392021-06-15 16:08:48 +0200652}
653
Christopher Fauletdcac4182021-06-15 16:17:17 +0200654/* Takes care to cleanup a server resolution when it is outdated. This only
655 * happens for a server relying on a SRV record.
656 */
657static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
658{
659 struct server *srv = context;
660
661 if (!tick_is_expired(t->expire, now_ms))
662 goto end;
663
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100664 enter_resolver_code();
Christopher Faulete886dd52021-06-18 09:05:49 +0200665 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreauf766ec62021-10-18 16:46:38 +0200666 resolv_srvrq_cleanup_srv(srv);
Christopher Faulete886dd52021-06-18 09:05:49 +0200667 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100668 leave_resolver_code();
Christopher Fauletdcac4182021-06-15 16:17:17 +0200669
670 end:
671 return t;
672}
673
Emeric Brunc9437992021-02-12 19:42:55 +0100674/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100675 * find a corresponding server.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200676 */
Emeric Brunc9437992021-02-12 19:42:55 +0100677static void resolv_check_response(struct resolv_resolution *res)
678{
679 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100680 struct resolv_requester *req;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200681 struct eb32_node *eb32, *eb32_back;
Emeric Brunbd78c912021-06-11 10:08:05 +0200682 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100683 struct resolv_srvrq *srvrq;
684
Willy Tarreau7893ae12021-10-21 07:39:57 +0200685 for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
686 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
Emeric Brunc9437992021-02-12 19:42:55 +0100687 struct resolv_answer_item *ar_item = item->ar_item;
688
689 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100690 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100691 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
692 * item is also obsolete.
693 */
Emeric Brunc9437992021-02-12 19:42:55 +0100694 pool_free(resolv_answer_item_pool, ar_item);
695 item->ar_item = NULL;
696 }
697
698 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100699 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200700 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100701 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200702 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
703 LIST_DEL_INIT(&srv->ip_rec_item);
704 }
705 }
706 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun34067662021-06-11 10:48:45 +0200707 /* Remove any associated server */
Christopher Faulet11c6c392021-06-15 16:08:48 +0200708 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreauf766ec62021-10-18 16:46:38 +0200709 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100710 }
711
Willy Tarreau7893ae12021-10-21 07:39:57 +0200712 eb32_delete(&item->link);
Emeric Brunc9437992021-02-12 19:42:55 +0100713 if (item->ar_item) {
714 pool_free(resolv_answer_item_pool, item->ar_item);
715 item->ar_item = NULL;
716 }
717 pool_free(resolv_answer_item_pool, item);
718 continue;
719 }
720
721 if (item->type != DNS_RTYPE_SRV)
722 continue;
723
724 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100725 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun34067662021-06-11 10:48:45 +0200726 struct ebpt_node *node;
727 char target[DNS_MAX_NAME_SIZE+1];
728
729 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100730 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
731 continue;
732
Emeric Brun34067662021-06-11 10:48:45 +0200733 /* Check if a server already uses that record */
734 srv = NULL;
735 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
736 if (srv->srvrq == srvrq) {
737 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
738 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100739 }
Emeric Brunc9437992021-02-12 19:42:55 +0100740 }
741
Emeric Brun34067662021-06-11 10:48:45 +0200742
743 /* If not empty we try to match a server
744 * in server state file tree with the same hostname
745 */
746 if (!eb_is_empty(&srvrq->named_servers)) {
747 srv = NULL;
748
749 /* convert the key to lookup in lower case */
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200750 for (i = 0 ; item->data.target[i] ; i++)
751 target[i] = tolower(item->data.target[i]);
Christopher Faulet1f923392021-07-22 14:29:26 +0200752 target[i] = 0;
Emeric Brun34067662021-06-11 10:48:45 +0200753
754 node = ebis_lookup(&srvrq->named_servers, target);
755 if (node) {
756 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100757 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun34067662021-06-11 10:48:45 +0200758
759 /* an entry was found with the same hostname
760 * let check this node if the port matches
761 * and try next node if the hostname
762 * is still the same
763 */
764 while (1) {
765 if (srv->svc_port == item->port) {
766 /* server found, we remove it from tree */
767 ebpt_delete(node);
Christopher Faulet73001ab2021-06-15 16:14:37 +0200768 ha_free(&srv->host_dn.key);
Emeric Brun34067662021-06-11 10:48:45 +0200769 goto srv_found;
770 }
771
772 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
773
774 node = ebpt_next(node);
775 if (!node)
776 break;
777
778 srv = ebpt_entry(node, struct server, host_dn);
779 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
780
781 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau75cc6532021-10-15 08:53:44 +0200782 || memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
Emeric Brun34067662021-06-11 10:48:45 +0200783 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
784 break;
785 }
786 }
Emeric Brunc9437992021-02-12 19:42:55 +0100787 }
788 }
Emeric Brun34067662021-06-11 10:48:45 +0200789
790 /* Pick the first server listed in srvrq (those ones don't
791 * have hostname and are free to use)
792 */
793 srv = NULL;
794 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
795 LIST_DEL_INIT(&srv->srv_rec_item);
796 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
797 goto srv_found;
798 }
799 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100800
Emeric Brun34067662021-06-11 10:48:45 +0200801srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100802 /* And update this server, if found (srv is locked here) */
803 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100804 /* re-enable DNS resolution for this server by default */
805 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Fauletdcac4182021-06-15 16:17:17 +0200806 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100807
Emeric Brunc9437992021-02-12 19:42:55 +0100808 /* Check if an Additional Record is associated to this SRV record.
809 * Perform some sanity checks too to ensure the record can be used.
810 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100811 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100812 */
813 if ((item->ar_item != NULL) &&
814 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100815 {
Emeric Brunc9437992021-02-12 19:42:55 +0100816
817 switch (item->ar_item->type) {
818 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200819 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100820 break;
821 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200822 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100823 break;
824 }
825
826 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100827
828 /* Unlink A/AAAA resolution for this server if there is an AR item.
829 * It is usless to perform an extra resolution
830 */
Willy Tarreau6878f802021-10-20 14:07:31 +0200831 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100832 }
833
834 if (!srv->hostname_dn) {
835 const char *msg = NULL;
Willy Tarreau85c15e62021-10-14 08:00:38 +0200836 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100837
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200838 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau85c15e62021-10-14 08:00:38 +0200839 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100840 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
841 continue;
842 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100843 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100844 if (msg)
845 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
846 }
847
Emeric Brun34067662021-06-11 10:48:45 +0200848 if (!LIST_INLIST(&srv->srv_rec_item))
849 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
850
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100851 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
852 /* If there is no AR item responsible of the FQDN resolution,
853 * trigger a dedicated DNS resolution
854 */
855 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
856 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
857 }
858
Christopher Fauletab177ac2021-03-10 15:34:52 +0100859 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100860 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100861
862 srv->svc_port = item->port;
863 srv->flags &= ~SRV_F_MAPPORTS;
864
865 if (!srv->resolv_opts.ignore_weight) {
866 char weight[9];
867 int ha_weight;
868
869 /* DNS weight range if from 0 to 65535
870 * HAProxy weight is from 0 to 256
871 * The rule below ensures that weight 0 is well respected
872 * while allowing a "mapping" from DNS weight into HAProxy's one.
873 */
874 ha_weight = (item->weight + 255) / 256;
875
876 snprintf(weight, sizeof(weight), "%d", ha_weight);
877 server_parse_weight_change_request(srv, weight);
878 }
879 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
880 }
881 }
882 }
883}
884
885/* Validates that the buffer DNS response provided in <resp> and finishing
886 * before <bufend> is valid from a DNS protocol point of view.
887 *
888 * The result is stored in <resolution>' response, buf_response,
889 * response_query_records and response_answer_records members.
890 *
891 * This function returns one of the RSLV_RESP_* code to indicate the type of
892 * error found.
893 */
894static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
895 struct resolv_resolution *resolution, int max_answer_records)
896{
897 unsigned char *reader;
898 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
899 int len, flags, offset;
Emeric Brunc9437992021-02-12 19:42:55 +0100900 int nb_saved_records;
901 struct resolv_query_item *query;
902 struct resolv_answer_item *answer_record, *tmp_record;
903 struct resolv_response *r_res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200904 struct eb32_node *eb32;
Willy Tarreaudcb696c2021-10-21 08:18:01 +0200905 uint32_t key = 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100906 int i, found = 0;
907 int cause = RSLV_RESP_ERROR;
908
909 reader = resp;
910 len = 0;
911 previous_dname = NULL;
912 query = NULL;
913 answer_record = NULL;
914
915 /* Initialization of response buffer and structure */
916 r_res = &resolution->response;
917
918 /* query id */
919 if (reader + 2 >= bufend)
920 goto invalid_resp;
921
922 r_res->header.id = reader[0] * 256 + reader[1];
923 reader += 2;
924
925 /* Flags and rcode are stored over 2 bytes
926 * First byte contains:
927 * - response flag (1 bit)
928 * - opcode (4 bits)
929 * - authoritative (1 bit)
930 * - truncated (1 bit)
931 * - recursion desired (1 bit)
932 */
933 if (reader + 2 >= bufend)
934 goto invalid_resp;
935
936 flags = reader[0] * 256 + reader[1];
937
938 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
939 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
940 cause = RSLV_RESP_NX_DOMAIN;
941 goto return_error;
942 }
943 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
944 cause = RSLV_RESP_REFUSED;
945 goto return_error;
946 }
947 else {
948 cause = RSLV_RESP_ERROR;
949 goto return_error;
950 }
951 }
952
953 /* Move forward 2 bytes for flags */
954 reader += 2;
955
956 /* 2 bytes for question count */
957 if (reader + 2 >= bufend)
958 goto invalid_resp;
959 r_res->header.qdcount = reader[0] * 256 + reader[1];
960 /* (for now) we send one query only, so we expect only one in the
961 * response too */
962 if (r_res->header.qdcount != 1) {
963 cause = RSLV_RESP_QUERY_COUNT_ERROR;
964 goto return_error;
965 }
966
967 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
968 goto invalid_resp;
969 reader += 2;
970
971 /* 2 bytes for answer count */
972 if (reader + 2 >= bufend)
973 goto invalid_resp;
974 r_res->header.ancount = reader[0] * 256 + reader[1];
975 if (r_res->header.ancount == 0) {
976 cause = RSLV_RESP_ANCOUNT_ZERO;
977 goto return_error;
978 }
979
980 /* Check if too many records are announced */
981 if (r_res->header.ancount > max_answer_records)
982 goto invalid_resp;
983 reader += 2;
984
985 /* 2 bytes authority count */
986 if (reader + 2 >= bufend)
987 goto invalid_resp;
988 r_res->header.nscount = reader[0] * 256 + reader[1];
989 reader += 2;
990
991 /* 2 bytes additional count */
992 if (reader + 2 >= bufend)
993 goto invalid_resp;
994 r_res->header.arcount = reader[0] * 256 + reader[1];
995 reader += 2;
996
Christopher Fauletc1699f82021-12-01 15:07:26 +0100997 /* Parsing dns queries. For now there is only one query and it exists
998 * because (qdcount == 1).
999 */
1000 query = &resolution->response_query_records[0];
Emeric Brunc9437992021-02-12 19:42:55 +01001001
Christopher Fauletc1699f82021-12-01 15:07:26 +01001002 /* Name is a NULL terminated string in our case, since we have
1003 * one query per response and the first one can't be compressed
1004 * (using the 0x0c format) */
1005 offset = 0;
1006 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01001007
Christopher Fauletc1699f82021-12-01 15:07:26 +01001008 if (len == 0)
1009 goto invalid_resp;
Emeric Brunc9437992021-02-12 19:42:55 +01001010
Christopher Fauletc1699f82021-12-01 15:07:26 +01001011 /* Now let's check the query's dname corresponds to the one we sent. */
1012 if (len != resolution->hostname_dn_len ||
1013 memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
1014 cause = RSLV_RESP_WRONG_NAME;
Christopher Fauletaf93d2f2021-12-02 10:05:02 +01001015 goto return_error;
Christopher Fauletc1699f82021-12-01 15:07:26 +01001016 }
Emeric Brunc9437992021-02-12 19:42:55 +01001017
Christopher Fauletc1699f82021-12-01 15:07:26 +01001018 reader += offset;
1019 previous_dname = query->name;
Emeric Brunc9437992021-02-12 19:42:55 +01001020
Christopher Fauletc1699f82021-12-01 15:07:26 +01001021 /* move forward 2 bytes for question type */
1022 if (reader + 2 >= bufend)
1023 goto invalid_resp;
1024 query->type = reader[0] * 256 + reader[1];
1025 reader += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001026
Christopher Fauletc1699f82021-12-01 15:07:26 +01001027 /* move forward 2 bytes for question class */
1028 if (reader + 2 >= bufend)
1029 goto invalid_resp;
1030 query->class = reader[0] * 256 + reader[1];
1031 reader += 2;
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001032
Emeric Brunc9437992021-02-12 19:42:55 +01001033 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001034 * because a TRUNCATED SRV query type response can still be exploited
1035 */
Emeric Brunc9437992021-02-12 19:42:55 +01001036 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1037 cause = RSLV_RESP_TRUNCATED;
1038 goto return_error;
1039 }
1040
1041 /* now parsing response records */
1042 nb_saved_records = 0;
1043 for (i = 0; i < r_res->header.ancount; i++) {
1044 if (reader >= bufend)
1045 goto invalid_resp;
1046
1047 answer_record = pool_alloc(resolv_answer_item_pool);
1048 if (answer_record == NULL)
1049 goto invalid_resp;
1050
1051 /* initialization */
1052 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001053 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001054 LIST_INIT(&answer_record->attached_servers);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001055 answer_record->link.node.leaf_p = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001056
1057 offset = 0;
1058 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1059
1060 if (len == 0)
1061 goto invalid_resp;
1062
1063 /* Check if the current record dname is valid. previous_dname
1064 * points either to queried dname or last CNAME target */
Willy Tarreau75cc6532021-10-15 08:53:44 +02001065 if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001066 if (i == 0) {
1067 /* First record, means a mismatch issue between
1068 * queried dname and dname found in the first
1069 * record */
1070 goto invalid_resp;
1071 }
1072 else {
1073 /* If not the first record, this means we have a
1074 * CNAME resolution error.
1075 */
1076 cause = RSLV_RESP_CNAME_ERROR;
1077 goto return_error;
1078 }
1079
1080 }
1081
1082 memcpy(answer_record->name, tmpname, len);
1083 answer_record->name[len] = 0;
1084
1085 reader += offset;
1086 if (reader >= bufend)
1087 goto invalid_resp;
1088
1089 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1090 if (reader + 2 > bufend)
1091 goto invalid_resp;
1092
1093 answer_record->type = reader[0] * 256 + reader[1];
1094 reader += 2;
1095
1096 /* 2 bytes for class (2) */
1097 if (reader + 2 > bufend)
1098 goto invalid_resp;
1099
1100 answer_record->class = reader[0] * 256 + reader[1];
1101 reader += 2;
1102
1103 /* 4 bytes for ttl (4) */
1104 if (reader + 4 > bufend)
1105 goto invalid_resp;
1106
1107 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1108 + reader[2] * 256 + reader[3];
1109 reader += 4;
1110
1111 /* Now reading data len */
1112 if (reader + 2 > bufend)
1113 goto invalid_resp;
1114
1115 answer_record->data_len = reader[0] * 256 + reader[1];
1116
1117 /* Move forward 2 bytes for data len */
1118 reader += 2;
1119
1120 if (reader + answer_record->data_len > bufend)
1121 goto invalid_resp;
1122
1123 /* Analyzing record content */
1124 switch (answer_record->type) {
1125 case DNS_RTYPE_A:
1126 /* ipv4 is stored on 4 bytes */
1127 if (answer_record->data_len != 4)
1128 goto invalid_resp;
1129
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001130 answer_record->data.in4.sin_family = AF_INET;
1131 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001132 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001133 break;
1134
1135 case DNS_RTYPE_CNAME:
1136 /* Check if this is the last record and update the caller about the status:
1137 * no IP could be found and last record was a CNAME. Could be triggered
1138 * by a wrong query type
1139 *
1140 * + 1 because answer_record_id starts at 0
1141 * while number of answers is an integer and
1142 * starts at 1.
1143 */
1144 if (i + 1 == r_res->header.ancount) {
1145 cause = RSLV_RESP_CNAME_ERROR;
1146 goto return_error;
1147 }
1148
1149 offset = 0;
1150 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1151 if (len == 0)
1152 goto invalid_resp;
1153
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001154 memcpy(answer_record->data.target, tmpname, len);
1155 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001156 key = XXH32(tmpname, len, answer_record->type);
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001157 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001158 break;
1159
1160
1161 case DNS_RTYPE_SRV:
1162 /* Answer must contain :
1163 * - 2 bytes for the priority
1164 * - 2 bytes for the weight
1165 * - 2 bytes for the port
1166 * - the target hostname
1167 */
1168 if (answer_record->data_len <= 6)
1169 goto invalid_resp;
1170
1171 answer_record->priority = read_n16(reader);
1172 reader += sizeof(uint16_t);
1173 answer_record->weight = read_n16(reader);
1174 reader += sizeof(uint16_t);
1175 answer_record->port = read_n16(reader);
1176 reader += sizeof(uint16_t);
1177 offset = 0;
1178 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1179 if (len == 0)
1180 goto invalid_resp;
1181
1182 answer_record->data_len = len;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001183 memcpy(answer_record->data.target, tmpname, len);
1184 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001185 key = XXH32(tmpname, len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001186 if (answer_record->ar_item != NULL) {
1187 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1188 answer_record->ar_item = NULL;
1189 }
1190 break;
1191
1192 case DNS_RTYPE_AAAA:
1193 /* ipv6 is stored on 16 bytes */
1194 if (answer_record->data_len != 16)
1195 goto invalid_resp;
1196
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001197 answer_record->data.in6.sin6_family = AF_INET6;
1198 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001199 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001200 break;
1201
1202 } /* switch (record type) */
1203
1204 /* Increment the counter for number of records saved into our
1205 * local response */
1206 nb_saved_records++;
1207
1208 /* Move forward answer_record->data_len for analyzing next
1209 * record in the response */
1210 reader += ((answer_record->type == DNS_RTYPE_SRV)
1211 ? offset
1212 : answer_record->data_len);
1213
1214 /* Lookup to see if we already had this entry */
1215 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001216
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001217 for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02001218 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001219 if (tmp_record->type != answer_record->type)
1220 continue;
1221
1222 switch(tmp_record->type) {
1223 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001224 if (!memcmp(&answer_record->data.in4.sin_addr,
1225 &tmp_record->data.in4.sin_addr,
1226 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001227 found = 1;
1228 break;
1229
1230 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001231 if (!memcmp(&answer_record->data.in6.sin6_addr,
1232 &tmp_record->data.in6.sin6_addr,
1233 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001234 found = 1;
1235 break;
1236
1237 case DNS_RTYPE_SRV:
1238 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001239 memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
Emeric Brunc9437992021-02-12 19:42:55 +01001240 answer_record->port == tmp_record->port) {
1241 tmp_record->weight = answer_record->weight;
1242 found = 1;
1243 }
1244 break;
1245
1246 default:
1247 break;
1248 }
1249
1250 if (found == 1)
1251 break;
1252 }
1253
1254 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001255 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001256 pool_free(resolv_answer_item_pool, answer_record);
1257 answer_record = NULL;
1258 }
1259 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001260 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001261 answer_record->ar_item = NULL;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001262 answer_record->link.key = key;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001263 eb32_insert(&r_res->answer_tree, &answer_record->link);
Emeric Brunc9437992021-02-12 19:42:55 +01001264 answer_record = NULL;
1265 }
1266 } /* for i 0 to ancount */
1267
1268 /* Save the number of records we really own */
1269 r_res->header.ancount = nb_saved_records;
1270
1271 /* now parsing additional records for SRV queries only */
1272 if (query->type != DNS_RTYPE_SRV)
1273 goto skip_parsing_additional_records;
1274
1275 /* if we find Authority records, just skip them */
1276 for (i = 0; i < r_res->header.nscount; i++) {
1277 offset = 0;
1278 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1279 &offset, 0);
1280 if (len == 0)
1281 continue;
1282
1283 if (reader + offset + 10 >= bufend)
1284 goto invalid_resp;
1285
1286 reader += offset;
1287 /* skip 2 bytes for class */
1288 reader += 2;
1289 /* skip 2 bytes for type */
1290 reader += 2;
1291 /* skip 4 bytes for ttl */
1292 reader += 4;
1293 /* read data len */
1294 len = reader[0] * 256 + reader[1];
1295 reader += 2;
1296
1297 if (reader + len >= bufend)
1298 goto invalid_resp;
1299
1300 reader += len;
1301 }
1302
1303 nb_saved_records = 0;
1304 for (i = 0; i < r_res->header.arcount; i++) {
1305 if (reader >= bufend)
1306 goto invalid_resp;
1307
1308 answer_record = pool_alloc(resolv_answer_item_pool);
1309 if (answer_record == NULL)
1310 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001311 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001312 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001313
1314 offset = 0;
1315 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1316
1317 if (len == 0) {
1318 pool_free(resolv_answer_item_pool, answer_record);
1319 answer_record = NULL;
1320 continue;
1321 }
1322
1323 memcpy(answer_record->name, tmpname, len);
1324 answer_record->name[len] = 0;
1325
1326 reader += offset;
1327 if (reader >= bufend)
1328 goto invalid_resp;
1329
1330 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1331 if (reader + 2 > bufend)
1332 goto invalid_resp;
1333
1334 answer_record->type = reader[0] * 256 + reader[1];
1335 reader += 2;
1336
1337 /* 2 bytes for class (2) */
1338 if (reader + 2 > bufend)
1339 goto invalid_resp;
1340
1341 answer_record->class = reader[0] * 256 + reader[1];
1342 reader += 2;
1343
1344 /* 4 bytes for ttl (4) */
1345 if (reader + 4 > bufend)
1346 goto invalid_resp;
1347
1348 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1349 + reader[2] * 256 + reader[3];
1350 reader += 4;
1351
1352 /* Now reading data len */
1353 if (reader + 2 > bufend)
1354 goto invalid_resp;
1355
1356 answer_record->data_len = reader[0] * 256 + reader[1];
1357
1358 /* Move forward 2 bytes for data len */
1359 reader += 2;
1360
1361 if (reader + answer_record->data_len > bufend)
1362 goto invalid_resp;
1363
1364 /* Analyzing record content */
1365 switch (answer_record->type) {
1366 case DNS_RTYPE_A:
1367 /* ipv4 is stored on 4 bytes */
1368 if (answer_record->data_len != 4)
1369 goto invalid_resp;
1370
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001371 answer_record->data.in4.sin_family = AF_INET;
1372 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001373 break;
1374
1375 case DNS_RTYPE_AAAA:
1376 /* ipv6 is stored on 16 bytes */
1377 if (answer_record->data_len != 16)
1378 goto invalid_resp;
1379
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001380 answer_record->data.in6.sin6_family = AF_INET6;
1381 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001382 break;
1383
1384 default:
1385 pool_free(resolv_answer_item_pool, answer_record);
1386 answer_record = NULL;
1387 continue;
1388
1389 } /* switch (record type) */
1390
1391 /* Increment the counter for number of records saved into our
1392 * local response */
1393 nb_saved_records++;
1394
1395 /* Move forward answer_record->data_len for analyzing next
1396 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001397 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001398
1399 /* Lookup to see if we already had this entry */
1400 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001401
1402 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001403 struct resolv_answer_item *ar_item;
1404
Willy Tarreau7893ae12021-10-21 07:39:57 +02001405 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Christopher Faulet77f86062021-03-10 15:19:57 +01001406 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1407 continue;
1408
1409 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001410 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001411 len != tmp_record->data_len ||
Willy Tarreau75cc6532021-10-15 08:53:44 +02001412 memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001413 continue;
1414
Christopher Faulet77f86062021-03-10 15:19:57 +01001415 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001416 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001417 if (!memcmp(&answer_record->data.in4.sin_addr,
1418 &ar_item->data.in4.sin_addr,
1419 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001420 found = 1;
1421 break;
1422
1423 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001424 if (!memcmp(&answer_record->data.in6.sin6_addr,
1425 &ar_item->data.in6.sin6_addr,
1426 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001427 found = 1;
1428 break;
1429
1430 default:
1431 break;
1432 }
1433
1434 if (found == 1)
1435 break;
1436 }
1437
1438 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001439 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001440 pool_free(resolv_answer_item_pool, answer_record);
1441 answer_record = NULL;
1442 }
1443 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001444 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001445 answer_record->ar_item = NULL;
1446
1447 // looking for the SRV record in the response list linked to this additional record
Willy Tarreau7893ae12021-10-21 07:39:57 +02001448 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
1449 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
1450
Emeric Brunc9437992021-02-12 19:42:55 +01001451 if (tmp_record->type == DNS_RTYPE_SRV &&
1452 tmp_record->ar_item == NULL &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001453 memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001454 /* Always use the received additional record to refresh info */
1455 if (tmp_record->ar_item)
1456 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1457 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001458 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001459 break;
1460 }
1461 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001462 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001463 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001464 answer_record = NULL;
1465 }
Emeric Brunc9437992021-02-12 19:42:55 +01001466 }
1467 } /* for i 0 to arcount */
1468
1469 skip_parsing_additional_records:
1470
1471 /* Save the number of records we really own */
1472 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001473 resolv_check_response(resolution);
1474 return RSLV_RESP_VALID;
1475
1476 invalid_resp:
1477 cause = RSLV_RESP_INVALID;
1478
1479 return_error:
1480 pool_free(resolv_answer_item_pool, answer_record);
1481 return cause;
1482}
1483
1484/* Searches dn_name resolution in resp.
1485 * If existing IP not found, return the first IP matching family_priority,
1486 * otherwise, first ip found
1487 * The following tasks are the responsibility of the caller:
1488 * - <r_res> contains an error free DNS response
1489 * For both cases above, resolv_validate_dns_response is required
1490 * returns one of the RSLV_UPD_* code
1491 */
1492int resolv_get_ip_from_response(struct resolv_response *r_res,
1493 struct resolv_options *resolv_opts, void *currentip,
1494 short currentip_sin_family,
1495 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001496 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001497{
Emeric Brunbd78c912021-06-11 10:08:05 +02001498 struct resolv_answer_item *record, *found_record = NULL;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001499 struct eb32_node *eb32;
Emeric Brunc9437992021-02-12 19:42:55 +01001500 int family_priority;
1501 int currentip_found;
1502 unsigned char *newip4, *newip6;
1503 int currentip_sel;
1504 int j;
1505 int score, max_score;
1506 int allowed_duplicated_ip;
1507
Emeric Brunbd78c912021-06-11 10:08:05 +02001508 /* srv is linked to an alive ip record */
1509 if (owner && LIST_INLIST(&owner->ip_rec_item))
1510 return RSLV_UPD_NO;
1511
Emeric Brunc9437992021-02-12 19:42:55 +01001512 family_priority = resolv_opts->family_prio;
1513 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1514 *newip = newip4 = newip6 = NULL;
1515 currentip_found = 0;
1516 *newip_sin_family = AF_UNSPEC;
1517 max_score = -1;
1518
1519 /* Select an IP regarding configuration preference.
1520 * Top priority is the preferred network ip version,
1521 * second priority is the preferred network.
1522 * the last priority is the currently used IP,
1523 *
1524 * For these three priorities, a score is calculated. The
1525 * weight are:
1526 * 8 - preferred ip version.
1527 * 4 - preferred network.
1528 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1529 * 1 - current ip.
1530 * The result with the biggest score is returned.
1531 */
1532
Willy Tarreau7893ae12021-10-21 07:39:57 +02001533 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001534 void *ip;
1535 unsigned char ip_type;
1536
Willy Tarreau7893ae12021-10-21 07:39:57 +02001537 record = eb32_entry(eb32, typeof(*record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001538 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001539 ip_type = AF_INET;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001540 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001541 }
1542 else if (record->type == DNS_RTYPE_AAAA) {
1543 ip_type = AF_INET6;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001544 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001545 }
1546 else
1547 continue;
1548 score = 0;
1549
1550 /* Check for preferred ip protocol. */
1551 if (ip_type == family_priority)
1552 score += 8;
1553
1554 /* Check for preferred network. */
1555 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1556
1557 /* Compare only the same addresses class. */
1558 if (resolv_opts->pref_net[j].family != ip_type)
1559 continue;
1560
1561 if ((ip_type == AF_INET &&
1562 in_net_ipv4(ip,
1563 &resolv_opts->pref_net[j].mask.in4,
1564 &resolv_opts->pref_net[j].addr.in4)) ||
1565 (ip_type == AF_INET6 &&
1566 in_net_ipv6(ip,
1567 &resolv_opts->pref_net[j].mask.in6,
1568 &resolv_opts->pref_net[j].addr.in6))) {
1569 score += 4;
1570 break;
1571 }
1572 }
1573
1574 /* Check if the IP found in the record is already affected to a
1575 * member of a group. If not, the score should be incremented
1576 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001577 if (owner) {
1578 struct server *srv;
1579 int already_used = 0;
1580
1581 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1582 if (srv == owner)
1583 continue;
1584 if (srv->proxy == owner->proxy) {
1585 already_used = 1;
1586 break;
1587 }
1588 }
1589 if (already_used) {
1590 if (!allowed_duplicated_ip) {
1591 continue;
1592 }
1593 }
1594 else {
1595 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001596 }
1597 } else {
1598 score += 2;
1599 }
1600
1601 /* Check for current ip matching. */
1602 if (ip_type == currentip_sin_family &&
1603 ((currentip_sin_family == AF_INET &&
1604 !memcmp(ip, currentip, 4)) ||
1605 (currentip_sin_family == AF_INET6 &&
1606 !memcmp(ip, currentip, 16)))) {
1607 score++;
1608 currentip_sel = 1;
1609 }
1610 else
1611 currentip_sel = 0;
1612
1613 /* Keep the address if the score is better than the previous
1614 * score. The maximum score is 15, if this value is reached, we
1615 * break the parsing. Implicitly, this score is reached the ip
1616 * selected is the current ip. */
1617 if (score > max_score) {
1618 if (ip_type == AF_INET)
1619 newip4 = ip;
1620 else
1621 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001622 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001623 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001624 if (score == 15) {
1625 /* this was not registered on the current record but it matches
1626 * let's fix it (it may comes from state file */
1627 if (owner)
1628 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001629 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001630 }
Emeric Brunc9437992021-02-12 19:42:55 +01001631 max_score = score;
1632 }
1633 } /* list for each record entries */
1634
1635 /* No IP found in the response */
1636 if (!newip4 && !newip6)
1637 return RSLV_UPD_NO_IP_FOUND;
1638
1639 /* Case when the caller looks first for an IPv4 address */
1640 if (family_priority == AF_INET) {
1641 if (newip4) {
1642 *newip = newip4;
1643 *newip_sin_family = AF_INET;
1644 }
1645 else if (newip6) {
1646 *newip = newip6;
1647 *newip_sin_family = AF_INET6;
1648 }
Emeric Brunc9437992021-02-12 19:42:55 +01001649 }
1650 /* Case when the caller looks first for an IPv6 address */
1651 else if (family_priority == AF_INET6) {
1652 if (newip6) {
1653 *newip = newip6;
1654 *newip_sin_family = AF_INET6;
1655 }
1656 else if (newip4) {
1657 *newip = newip4;
1658 *newip_sin_family = AF_INET;
1659 }
Emeric Brunc9437992021-02-12 19:42:55 +01001660 }
1661 /* Case when the caller have no preference (we prefer IPv6) */
1662 else if (family_priority == AF_UNSPEC) {
1663 if (newip6) {
1664 *newip = newip6;
1665 *newip_sin_family = AF_INET6;
1666 }
1667 else if (newip4) {
1668 *newip = newip4;
1669 *newip_sin_family = AF_INET;
1670 }
Emeric Brunc9437992021-02-12 19:42:55 +01001671 }
1672
Emeric Brunbd78c912021-06-11 10:08:05 +02001673 /* the ip of this record was chosen for the server */
1674 if (owner && found_record) {
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001675 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunbd78c912021-06-11 10:08:05 +02001676 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1677 }
1678
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001679 eb32 = eb32_first(&r_res->answer_tree);
1680 if (eb32) {
Emeric Brunc9437992021-02-12 19:42:55 +01001681 /* Move the first record to the end of the list, for internal
Willy Tarreau7893ae12021-10-21 07:39:57 +02001682 * round robin.
1683 */
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001684 eb32_delete(eb32);
1685 eb32_insert(&r_res->answer_tree, eb32);
Emeric Brunc9437992021-02-12 19:42:55 +01001686 }
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001687
1688 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001689}
1690
Willy Tarreau875ee702021-10-14 08:05:25 +02001691/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001692 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001693 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1694 * null-terminated. <str> must be allocated large enough to contain a full host
1695 * name plus the trailing zero, and the allocated size must be passed in
1696 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001697 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001698 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001699 * <str> (including the terminating null byte).
1700 */
1701int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1702{
1703 char *ptr;
1704 int i, sz;
1705
Willy Tarreau875ee702021-10-14 08:05:25 +02001706 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001707 return -1;
1708
1709 ptr = str;
Willy Tarreau875ee702021-10-14 08:05:25 +02001710 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001711 sz = dn[i];
1712 if (i)
1713 *ptr++ = '.';
Willy Tarreau814889c2021-10-15 07:45:38 +02001714 /* copy the string at i+1 to lower case */
1715 for (; sz > 0; sz--)
1716 *(ptr++) = tolower(dn[++i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001717 }
1718 *ptr++ = '\0';
1719 return (ptr - str);
1720}
1721
1722/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1723 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001724 * <str> contains the input string that is <str_len> bytes long (trailing zero
1725 * not needed). <dn> buffer must be allocated large enough to contain the
1726 * encoded string and a trailing zero, so it must be at least str_len+2, and
1727 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001728 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001729 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001730 * <dn> (excluding the terminating null byte).
1731 */
1732int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1733{
1734 int i, offset;
1735
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001736 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001737 return -1;
1738
1739 /* First byte of dn will be used to store the length of the first
1740 * label */
1741 offset = 0;
1742 for (i = 0; i < str_len; ++i) {
1743 if (str[i] == '.') {
1744 /* 2 or more consecutive dots is invalid */
1745 if (i == offset)
1746 return -1;
1747
1748 /* ignore trailing dot */
Christopher Faulet0a82cf42022-01-28 17:47:57 +01001749 if (i + 1 == str_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001750 break;
Emeric Brunc9437992021-02-12 19:42:55 +01001751
1752 dn[offset] = (i - offset);
1753 offset = i+1;
1754 continue;
1755 }
Willy Tarreau814889c2021-10-15 07:45:38 +02001756 dn[i+1] = tolower(str[i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001757 }
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001758 dn[offset] = i - offset;
Willy Tarreau7b232f12021-10-15 08:09:25 +02001759 dn[i+1] = '\0';
1760 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001761}
1762
1763/* Validates host name:
1764 * - total size
1765 * - each label size individually
1766 * returns:
1767 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1768 * 1 when no error. <err> is left unaffected.
1769 */
1770int resolv_hostname_validation(const char *string, char **err)
1771{
1772 int i;
1773
1774 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1775 if (err)
1776 *err = DNS_TOO_LONG_FQDN;
1777 return 0;
1778 }
1779
1780 while (*string) {
1781 i = 0;
1782 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1783 if (!(*string == '-' || *string == '_' ||
1784 (*string >= 'a' && *string <= 'z') ||
1785 (*string >= 'A' && *string <= 'Z') ||
1786 (*string >= '0' && *string <= '9'))) {
1787 if (err)
1788 *err = DNS_INVALID_CHARACTER;
1789 return 0;
1790 }
1791 i++;
1792 string++;
1793 }
1794
1795 if (!(*string))
1796 break;
1797
1798 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1799 if (err)
1800 *err = DNS_LABEL_TOO_LONG;
1801 return 0;
1802 }
1803
1804 string++;
1805 }
1806 return 1;
1807}
1808
1809/* Picks up an available resolution from the different resolution list
1810 * associated to a resolvers section, in this order:
1811 * 1. check in resolutions.curr for the same hostname and query_type
1812 * 2. check in resolutions.wait for the same hostname and query_type
1813 * 3. Get a new resolution from resolution pool
1814 *
1815 * Returns an available resolution, NULL if none found.
1816 */
1817static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1818 char **hostname_dn, int hostname_dn_len,
1819 int query_type)
1820{
1821 struct resolv_resolution *res;
1822
1823 if (!*hostname_dn)
1824 goto from_pool;
1825
1826 /* Search for same hostname and query type in resolutions.curr */
1827 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1828 if (!res->hostname_dn)
1829 continue;
1830 if ((query_type == res->prefered_query_type) &&
1831 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001832 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001833 return res;
1834 }
1835
1836 /* Search for same hostname and query type in resolutions.wait */
1837 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1838 if (!res->hostname_dn)
1839 continue;
1840 if ((query_type == res->prefered_query_type) &&
1841 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001842 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001843 return res;
1844 }
1845
1846 from_pool:
1847 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001848 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001849 if (res) {
Emeric Brunc9437992021-02-12 19:42:55 +01001850 res->resolvers = resolvers;
1851 res->uuid = resolution_uuid;
1852 res->status = RSLV_STATUS_NONE;
1853 res->step = RSLV_STEP_NONE;
1854 res->last_valid = now_ms;
1855
1856 LIST_INIT(&res->requesters);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001857 res->response.answer_tree = EB_ROOT;
Emeric Brunc9437992021-02-12 19:42:55 +01001858
1859 res->prefered_query_type = query_type;
1860 res->query_type = query_type;
1861 res->hostname_dn = *hostname_dn;
1862 res->hostname_dn_len = hostname_dn_len;
1863
1864 ++resolution_uuid;
1865
1866 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001867 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001868 }
1869 return res;
1870}
1871
Willy Tarreau2acc1602021-10-19 11:16:11 +02001872/* deletes and frees all answer_items from the resolution's answer_list */
1873static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001874{
Willy Tarreau7893ae12021-10-21 07:39:57 +02001875 struct eb32_node *eb32, *eb32_back;
1876 struct resolv_answer_item *item;
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001877
Willy Tarreau7893ae12021-10-21 07:39:57 +02001878 for (eb32 = eb32_first(&resolution->response.answer_tree);
1879 eb32 && (eb32_back = eb32_next(eb32), 1);
1880 eb32 = eb32_back) {
1881 item = eb32_entry(eb32, typeof(*item), link);
1882 eb32_delete(&item->link);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001883 pool_free(resolv_answer_item_pool, item->ar_item);
1884 pool_free(resolv_answer_item_pool, item);
1885 }
1886}
1887
Emeric Brunc9437992021-02-12 19:42:55 +01001888/* Releases a resolution from its requester(s) and move it back to the pool */
1889static void resolv_free_resolution(struct resolv_resolution *resolution)
1890{
1891 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001892
1893 /* clean up configuration */
1894 resolv_reset_resolution(resolution);
1895 resolution->hostname_dn = NULL;
1896 resolution->hostname_dn_len = 0;
1897
1898 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02001899 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001900 req->resolution = NULL;
1901 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001902 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau25e01092021-10-19 11:17:33 +02001903
Willy Tarreauaae73202021-10-19 22:01:36 +02001904 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001905 pool_free(resolv_resolution_pool, resolution);
1906}
1907
Willy Tarreau239675e2021-10-19 11:59:25 +02001908/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1909 * and makes it owned by this obj_type, with the proposed callback and error
1910 * callback. On success, *req is assigned the allocated requester. Returns
1911 * NULL on allocation failure.
1912 */
1913static struct resolv_requester *
1914resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1915 int (*cb)(struct resolv_requester *, struct dns_counters *),
1916 int (*err_cb)(struct resolv_requester *, int))
1917{
1918 struct resolv_requester *tmp;
1919
1920 if (*req)
1921 return *req;
1922
1923 tmp = pool_alloc(resolv_requester_pool);
1924 if (!tmp)
1925 goto end;
1926
1927 LIST_INIT(&tmp->list);
1928 tmp->owner = owner;
1929 tmp->resolution = NULL;
1930 tmp->requester_cb = cb;
1931 tmp->requester_error_cb = err_cb;
1932 *req = tmp;
1933 end:
1934 return tmp;
1935}
1936
Emeric Brunc9437992021-02-12 19:42:55 +01001937/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001938 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001939 */
1940int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1941{
1942 struct resolv_resolution *res = NULL;
1943 struct resolv_requester *req;
1944 struct resolvers *resolvers;
1945 struct server *srv = NULL;
1946 struct resolv_srvrq *srvrq = NULL;
1947 struct stream *stream = NULL;
1948 char **hostname_dn;
1949 int hostname_dn_len, query_type;
1950
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001951 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001952 switch (requester_type) {
1953 case OBJ_TYPE_SERVER:
1954 srv = (struct server *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001955
1956 if (!requester_locked)
1957 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1958
1959 req = resolv_get_requester(&srv->resolv_requester,
1960 &srv->obj_type,
1961 snr_resolution_cb,
1962 snr_resolution_error_cb);
1963
1964 if (!requester_locked)
1965 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1966
1967 if (!req)
1968 goto err;
1969
Emeric Brunc9437992021-02-12 19:42:55 +01001970 hostname_dn = &srv->hostname_dn;
1971 hostname_dn_len = srv->hostname_dn_len;
1972 resolvers = srv->resolvers;
1973 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1974 ? DNS_RTYPE_A
1975 : DNS_RTYPE_AAAA);
1976 break;
1977
1978 case OBJ_TYPE_SRVRQ:
1979 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001980
1981 req = resolv_get_requester(&srvrq->requester,
1982 &srvrq->obj_type,
1983 snr_resolution_cb,
1984 srvrq_resolution_error_cb);
1985 if (!req)
1986 goto err;
1987
Emeric Brunc9437992021-02-12 19:42:55 +01001988 hostname_dn = &srvrq->hostname_dn;
1989 hostname_dn_len = srvrq->hostname_dn_len;
1990 resolvers = srvrq->resolvers;
1991 query_type = DNS_RTYPE_SRV;
1992 break;
1993
1994 case OBJ_TYPE_STREAM:
1995 stream = (struct stream *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001996
1997 req = resolv_get_requester(&stream->resolv_ctx.requester,
1998 &stream->obj_type,
1999 act_resolution_cb,
2000 act_resolution_error_cb);
2001 if (!req)
2002 goto err;
2003
Emeric Brunc9437992021-02-12 19:42:55 +01002004 hostname_dn = &stream->resolv_ctx.hostname_dn;
2005 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2006 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2007 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2008 ? DNS_RTYPE_A
2009 : DNS_RTYPE_AAAA);
2010 break;
2011 default:
2012 goto err;
2013 }
2014
2015 /* Get a resolution from the resolvers' wait queue or pool */
2016 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2017 goto err;
2018
Willy Tarreau239675e2021-10-19 11:59:25 +02002019 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002020
Willy Tarreau2b718102021-04-21 07:32:39 +02002021 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002022 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002023 return 0;
2024
2025 err:
2026 if (res && LIST_ISEMPTY(&res->requesters))
2027 resolv_free_resolution(res);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002028 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002029 return -1;
2030}
2031
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002032/* This function removes all server/srvrq references on answer items. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002033void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun34067662021-06-11 10:48:45 +02002034{
Willy Tarreau7893ae12021-10-21 07:39:57 +02002035 struct eb32_node *eb32, *eb32_back;
2036 struct resolv_answer_item *item;
Emeric Brun34067662021-06-11 10:48:45 +02002037 struct server *srv, *srvback;
2038 struct resolv_srvrq *srvrq;
2039
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002040 enter_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002041 if ((srv = objt_server(req->owner)) != NULL) {
2042 LIST_DEL_INIT(&srv->ip_rec_item);
2043 }
2044 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02002045 for (eb32 = eb32_first(&res->response.answer_tree);
2046 eb32 && (eb32_back = eb32_next(eb32), 1);
2047 eb32 = eb32_back) {
2048 item = eb32_entry(eb32, typeof(*item), link);
Emeric Brun34067662021-06-11 10:48:45 +02002049 if (item->type == DNS_RTYPE_SRV) {
2050 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet11c6c392021-06-15 16:08:48 +02002051 if (srv->srvrq == srvrq)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002052 resolv_srvrq_cleanup_srv(srv);
Emeric Brun34067662021-06-11 10:48:45 +02002053 }
2054 }
2055 }
2056 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002057 leave_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002058}
2059
Emeric Brunc9437992021-02-12 19:42:55 +01002060/* Removes a requester from a DNS resolution. It takes takes care of all the
2061 * consequences. It also cleans up some parameters from the requester.
2062 */
Willy Tarreau6878f802021-10-20 14:07:31 +02002063static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002064{
2065 struct resolv_resolution *res;
2066 struct resolv_requester *req;
2067
2068 /* Nothing to do */
2069 if (!requester || !requester->resolution)
2070 return;
2071 res = requester->resolution;
2072
2073 /* Clean up the requester */
Willy Tarreauaae73202021-10-19 22:01:36 +02002074 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002075 requester->resolution = NULL;
2076
Christopher Fauletbce6db62021-10-29 10:38:15 +02002077 /* remove ref from the resolution answer item list to the requester */
2078 resolv_detach_from_resolution_answer_items(res, requester);
2079
Emeric Brunc9437992021-02-12 19:42:55 +01002080 /* We need to find another requester linked on this resolution */
2081 if (!LIST_ISEMPTY(&res->requesters))
2082 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2083 else {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002084 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002085 return;
2086 }
2087
2088 /* Move hostname_dn related pointers to the next requester */
2089 switch (obj_type(req->owner)) {
2090 case OBJ_TYPE_SERVER:
2091 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2092 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2093 break;
2094 case OBJ_TYPE_SRVRQ:
2095 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2096 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2097 break;
2098 case OBJ_TYPE_STREAM:
2099 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2100 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2101 break;
2102 default:
2103 res->hostname_dn = NULL;
2104 res->hostname_dn_len = 0;
2105 break;
2106 }
2107}
2108
Willy Tarreauf766ec62021-10-18 16:46:38 +02002109/* The public version of the function above that deals with the death row. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002110void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002111{
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002112 enter_resolver_code();
Willy Tarreau6878f802021-10-20 14:07:31 +02002113 _resolv_unlink_resolution(requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002114 leave_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002115}
2116
Emeric Brunc9437992021-02-12 19:42:55 +01002117/* Called when a network IO is generated on a name server socket for an incoming
2118 * packet. It performs the following actions:
2119 * - check if the packet requires processing (not outdated resolution)
2120 * - ensure the DNS packet received is valid and call requester's callback
2121 * - call requester's error callback if invalid response
2122 * - check the dn_name in the packet against the one sent
2123 */
2124static int resolv_process_responses(struct dns_nameserver *ns)
2125{
2126 struct dns_counters *tmpcounters;
2127 struct resolvers *resolvers;
2128 struct resolv_resolution *res;
Emeric Brunc9437992021-02-12 19:42:55 +01002129 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2130 unsigned char *bufend;
2131 int buflen, dns_resp;
2132 int max_answer_records;
2133 unsigned short query_id;
2134 struct eb32_node *eb;
2135 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002136 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002137
2138 resolvers = ns->parent;
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002139 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002140 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2141
2142 /* process all pending input messages */
2143 while (1) {
2144 /* read message received */
2145 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2146 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2147 break;
2148 }
2149
2150 /* message too big */
2151 if (buflen > resolvers->accepted_payload_size) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002152 ns->counters->app.resolver.too_big++;
Emeric Brunc9437992021-02-12 19:42:55 +01002153 continue;
2154 }
2155
2156 /* initializing variables */
2157 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2158
2159 /* read the query id from the packet (16 bits) */
2160 if (buf + 2 > bufend) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002161 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002162 continue;
2163 }
2164 query_id = resolv_response_get_query_id(buf);
2165
2166 /* search the query_id in the pending resolution tree */
2167 eb = eb32_lookup(&resolvers->query_ids, query_id);
2168 if (eb == NULL) {
2169 /* unknown query id means an outdated response and can be safely ignored */
Emeric Brund174f0e2021-10-29 17:30:41 +02002170 ns->counters->app.resolver.outdated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002171 continue;
2172 }
2173
2174 /* known query id means a resolution in progress */
2175 res = eb32_entry(eb, struct resolv_resolution, qid);
2176 /* number of responses received */
2177 res->nb_responses++;
2178
2179 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2180 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2181
2182 switch (dns_resp) {
2183 case RSLV_RESP_VALID:
2184 break;
2185
2186 case RSLV_RESP_INVALID:
2187 case RSLV_RESP_QUERY_COUNT_ERROR:
2188 case RSLV_RESP_WRONG_NAME:
2189 res->status = RSLV_STATUS_INVALID;
Emeric Brund174f0e2021-10-29 17:30:41 +02002190 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002191 break;
2192
2193 case RSLV_RESP_NX_DOMAIN:
2194 res->status = RSLV_STATUS_NX;
Emeric Brund174f0e2021-10-29 17:30:41 +02002195 ns->counters->app.resolver.nx++;
Emeric Brunc9437992021-02-12 19:42:55 +01002196 break;
2197
2198 case RSLV_RESP_REFUSED:
2199 res->status = RSLV_STATUS_REFUSED;
Emeric Brund174f0e2021-10-29 17:30:41 +02002200 ns->counters->app.resolver.refused++;
Emeric Brunc9437992021-02-12 19:42:55 +01002201 break;
2202
2203 case RSLV_RESP_ANCOUNT_ZERO:
2204 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002205 ns->counters->app.resolver.any_err++;
Emeric Brunc9437992021-02-12 19:42:55 +01002206 break;
2207
2208 case RSLV_RESP_CNAME_ERROR:
2209 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002210 ns->counters->app.resolver.cname_error++;
Emeric Brunc9437992021-02-12 19:42:55 +01002211 break;
2212
2213 case RSLV_RESP_TRUNCATED:
2214 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002215 ns->counters->app.resolver.truncated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002216 break;
2217
2218 case RSLV_RESP_NO_EXPECTED_RECORD:
2219 case RSLV_RESP_ERROR:
2220 case RSLV_RESP_INTERNAL:
2221 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002222 ns->counters->app.resolver.other++;
Emeric Brunc9437992021-02-12 19:42:55 +01002223 break;
2224 }
2225
2226 /* Wait all nameservers response to handle errors */
2227 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2228 continue;
2229
2230 /* Process error codes */
2231 if (dns_resp != RSLV_RESP_VALID) {
2232 if (res->prefered_query_type != res->query_type) {
2233 /* The fallback on the query type was already performed,
2234 * so check the try counter. If it falls to 0, we can
2235 * report an error. Else, wait the next attempt. */
2236 if (!res->try)
2237 goto report_res_error;
2238 }
2239 else {
2240 /* Fallback from A to AAAA or the opposite and re-send
2241 * the resolution immediately. try counter is not
2242 * decremented. */
2243 if (res->prefered_query_type == DNS_RTYPE_A) {
2244 res->query_type = DNS_RTYPE_AAAA;
2245 resolv_send_query(res);
2246 }
2247 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2248 res->query_type = DNS_RTYPE_A;
2249 resolv_send_query(res);
2250 }
2251 }
2252 continue;
2253 }
2254
Emeric Brunc9437992021-02-12 19:42:55 +01002255 /* So the resolution succeeded */
2256 res->status = RSLV_STATUS_VALID;
2257 res->last_valid = now_ms;
Emeric Brund174f0e2021-10-29 17:30:41 +02002258 ns->counters->app.resolver.valid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002259 goto report_res_success;
2260
2261 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002262 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002263 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002264 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2265 if (!keep_answer_items)
2266 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002267 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002268 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002269 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002270 continue;
2271
2272 report_res_success:
2273 /* Only the 1rst requester s managed by the server, others are
2274 * from the cache */
2275 tmpcounters = ns->counters;
2276 list_for_each_entry(req, &res->requesters, list) {
2277 struct server *s = objt_server(req->owner);
2278
2279 if (s)
2280 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2281 req->requester_cb(req, tmpcounters);
2282 if (s)
2283 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2284 tmpcounters = NULL;
2285 }
2286
2287 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002288 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002289 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002290 continue;
2291 }
2292 resolv_update_resolvers_timeout(resolvers);
2293 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002294 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002295 return buflen;
2296}
2297
2298/* Processes DNS resolution. First, it checks the active list to detect expired
2299 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2300 * checks the wait list to trigger new resolutions.
2301 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002302static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002303{
2304 struct resolvers *resolvers = context;
2305 struct resolv_resolution *res, *resback;
2306 int exp;
2307
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002308 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002309 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2310
Willy Tarreauf766ec62021-10-18 16:46:38 +02002311 /* Handle all expired resolutions from the active list. Elements that
2312 * need to be removed will in fact be moved to the death_row. Other
2313 * ones will be handled normally.
2314 */
2315
Willy Tarreauf766ec62021-10-18 16:46:38 +02002316 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2317 while (&res->list != &resolvers->resolutions.curr) {
2318 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2319
Christopher Faulet0efc0992021-03-11 18:09:53 +01002320 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002321 abort_resolution(res);
2322 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002323 continue;
2324 }
2325
Emeric Brunc9437992021-02-12 19:42:55 +01002326 /* When we find the first resolution in the future, then we can
2327 * stop here */
2328 exp = tick_add(res->last_query, resolvers->timeout.retry);
2329 if (!tick_is_expired(exp, now_ms))
2330 break;
2331
2332 /* If current resolution has been tried too many times and
2333 * finishes in timeout we update its status and remove it from
2334 * the list */
2335 if (!res->try) {
2336 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002337 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002338
2339 /* Notify the result to the requesters */
2340 if (!res->nb_responses)
2341 res->status = RSLV_STATUS_TIMEOUT;
2342 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002343 keep_answer_items |= req->requester_error_cb(req, res->status);
2344 if (!keep_answer_items)
2345 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002346
2347 /* Clean up resolution info and remove it from the
2348 * current list */
2349 resolv_reset_resolution(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002350
2351 /* subsequent entries might have been deleted here */
2352 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreauaae73202021-10-19 22:01:36 +02002353 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002354 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002355 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002356 }
2357 else {
2358 /* Otherwise resend the DNS query and requeue the resolution */
2359 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2360 /* No response received (a real timeout) or fallback already done */
2361 res->query_type = res->prefered_query_type;
2362 res->try--;
2363 }
2364 else {
2365 /* Fallback from A to AAAA or the opposite and re-send
2366 * the resolution immediately. try counter is not
2367 * decremented. */
2368 if (res->prefered_query_type == DNS_RTYPE_A)
2369 res->query_type = DNS_RTYPE_AAAA;
2370 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2371 res->query_type = DNS_RTYPE_A;
2372 else
2373 res->try--;
2374 }
2375 resolv_send_query(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002376 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2377 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002378 }
2379 }
2380
2381 /* Handle all resolutions in the wait list */
2382 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002383 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002384 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002385 continue;
2386 }
2387
Emeric Brunc9437992021-02-12 19:42:55 +01002388 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2389 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2390 continue;
2391
2392 if (resolv_run_resolution(res) != 1) {
2393 res->last_resolution = now_ms;
Willy Tarreauaae73202021-10-19 22:01:36 +02002394 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002395 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002396 }
2397 }
Emeric Brunc9437992021-02-12 19:42:55 +01002398 resolv_update_resolvers_timeout(resolvers);
2399 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002400
2401 /* now we can purge all queued deletions */
2402 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002403 return t;
2404}
2405
2406/* Release memory allocated by DNS */
2407static void resolvers_deinit(void)
2408{
2409 struct resolvers *resolvers, *resolversback;
2410 struct dns_nameserver *ns, *nsback;
2411 struct resolv_resolution *res, *resback;
2412 struct resolv_requester *req, *reqback;
2413 struct resolv_srvrq *srvrq, *srvrqback;
2414
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002415 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002416 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2417 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2418 free(ns->id);
2419 free((char *)ns->conf.file);
2420 if (ns->dgram) {
2421 if (ns->dgram->conn.t.sock.fd != -1) {
2422 fd_delete(ns->dgram->conn.t.sock.fd);
2423 close(ns->dgram->conn.t.sock.fd);
2424 }
2425 if (ns->dgram->ring_req)
2426 ring_free(ns->dgram->ring_req);
2427 free(ns->dgram);
2428 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002429 if (ns->stream) {
2430 if (ns->stream->ring_req)
2431 ring_free(ns->stream->ring_req);
2432 if (ns->stream->task_req)
2433 task_destroy(ns->stream->task_req);
2434 if (ns->stream->task_rsp)
2435 task_destroy(ns->stream->task_rsp);
2436 free(ns->stream);
2437 }
Willy Tarreauaae73202021-10-19 22:01:36 +02002438 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002439 EXTRA_COUNTERS_FREE(ns->extra_counters);
2440 free(ns);
2441 }
2442
2443 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2444 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002445 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002446 pool_free(resolv_requester_pool, req);
2447 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002448 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002449 }
2450
2451 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2452 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002453 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002454 pool_free(resolv_requester_pool, req);
2455 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002456 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002457 }
2458
Tim Duesterhus0b7031b2022-04-26 23:28:47 +02002459 free_proxy(resolvers->px);
Emeric Brunc9437992021-02-12 19:42:55 +01002460 free(resolvers->id);
2461 free((char *)resolvers->conf.file);
2462 task_destroy(resolvers->t);
Willy Tarreauaae73202021-10-19 22:01:36 +02002463 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002464 free(resolvers);
2465 }
2466
2467 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2468 free(srvrq->name);
2469 free(srvrq->hostname_dn);
Willy Tarreauaae73202021-10-19 22:01:36 +02002470 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002471 free(srvrq);
2472 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002473
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002474 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002475}
2476
2477/* Finalizes the DNS configuration by allocating required resources and checking
2478 * live parameters.
2479 * Returns 0 on success, ERR_* flags otherwise.
2480 */
2481static int resolvers_finalize_config(void)
2482{
2483 struct resolvers *resolvers;
2484 struct proxy *px;
2485 int err_code = 0;
2486
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002487 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002488
Emeric Brunc9437992021-02-12 19:42:55 +01002489 /* allocate pool of resolution per resolvers */
2490 list_for_each_entry(resolvers, &sec_resolvers, list) {
2491 struct dns_nameserver *ns;
2492 struct task *t;
2493
2494 /* Check if we can create the socket with nameservers info */
2495 list_for_each_entry(ns, &resolvers->nameservers, list) {
2496 int fd;
2497
2498 if (ns->dgram) {
2499 /* Check nameserver info */
2500 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002501 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002502 resolvers->id, ns->id);
2503 err_code |= (ERR_ALERT|ERR_ABORT);
2504 continue;
2505 }
2506 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002507 ha_alert("resolvers '%s': can't connect socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002508 resolvers->id, ns->id);
2509 close(fd);
2510 err_code |= (ERR_ALERT|ERR_ABORT);
2511 continue;
2512 }
2513 close(fd);
2514 }
2515 }
2516
2517 /* Create the task associated to the resolvers section */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002518 if ((t = task_new_anywhere()) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002519 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002520 err_code |= (ERR_ALERT|ERR_ABORT);
2521 goto err;
2522 }
2523
2524 /* Update task's parameters */
2525 t->process = process_resolvers;
2526 t->context = resolvers;
2527 resolvers->t = t;
2528 task_wakeup(t, TASK_WOKEN_INIT);
2529 }
2530
2531 for (px = proxies_list; px; px = px->next) {
2532 struct server *srv;
2533
2534 for (srv = px->srv; srv; srv = srv->next) {
2535 struct resolvers *resolvers;
2536
2537 if (!srv->resolvers_id)
2538 continue;
2539
2540 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002541 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002542 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2543 err_code |= (ERR_ALERT|ERR_ABORT);
2544 continue;
2545 }
2546 srv->resolvers = resolvers;
Christopher Fauletdcac4182021-06-15 16:17:17 +02002547 srv->srvrq_check = NULL;
2548 if (srv->srvrq) {
2549 if (!srv->srvrq->resolvers) {
2550 srv->srvrq->resolvers = srv->resolvers;
2551 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2552 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
2553 proxy_type_str(px), px->id, srv->id);
2554 err_code |= (ERR_ALERT|ERR_ABORT);
2555 continue;
2556 }
2557 }
Emeric Brunc9437992021-02-12 19:42:55 +01002558
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002559 srv->srvrq_check = task_new_anywhere();
Christopher Fauletdcac4182021-06-15 16:17:17 +02002560 if (!srv->srvrq_check) {
2561 ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002562 proxy_type_str(px), px->id, srv->id);
2563 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Fauletdcac4182021-06-15 16:17:17 +02002564 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002565 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002566 srv->srvrq_check->process = resolv_srvrq_expire_task;
2567 srv->srvrq_check->context = srv;
2568 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002569 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002570 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002571 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002572 proxy_type_str(px), px->id, srv->id);
2573 err_code |= (ERR_ALERT|ERR_ABORT);
2574 continue;
2575 }
Amaury Denoyelledd565202021-08-26 15:35:59 +02002576
2577 srv->flags |= SRV_F_NON_PURGEABLE;
Emeric Brunc9437992021-02-12 19:42:55 +01002578 }
2579 }
2580
2581 if (err_code & (ERR_ALERT|ERR_ABORT))
2582 goto err;
2583
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002584 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002585 return err_code;
2586 err:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002587 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002588 resolvers_deinit();
2589 return err_code;
2590
2591}
2592
Christopher Faulet908628c2022-03-25 16:43:49 +01002593static int stats_dump_resolv_to_buffer(struct conn_stream *cs,
Emeric Brunc9437992021-02-12 19:42:55 +01002594 struct dns_nameserver *ns,
2595 struct field *stats, size_t stats_count,
2596 struct list *stat_modules)
2597{
Christopher Faulet908628c2022-03-25 16:43:49 +01002598 struct appctx *appctx = __cs_appctx(cs);
2599 struct channel *rep = cs_ic(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002600 struct stats_module *mod;
2601 size_t idx = 0;
2602
2603 memset(stats, 0, sizeof(struct field) * stats_count);
2604
2605 list_for_each_entry(mod, stat_modules, list) {
2606 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2607
2608 mod->fill_stats(counters, stats + idx);
2609 idx += mod->stats_count;
2610 }
2611
2612 if (!stats_dump_one_line(stats, idx, appctx))
2613 return 0;
2614
2615 if (!stats_putchk(rep, NULL, &trash))
2616 goto full;
2617
2618 return 1;
2619
2620 full:
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002621 cs_rx_room_rdy(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002622 return 0;
2623}
2624
2625/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2626 * as a pointer to the current nameserver.
2627 */
Christopher Faulet908628c2022-03-25 16:43:49 +01002628int stats_dump_resolvers(struct conn_stream *cs,
Emeric Brunc9437992021-02-12 19:42:55 +01002629 struct field *stats, size_t stats_count,
2630 struct list *stat_modules)
2631{
Christopher Faulet908628c2022-03-25 16:43:49 +01002632 struct appctx *appctx = __cs_appctx(cs);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002633 struct show_stat_ctx *ctx = appctx->svcctx;
Christopher Faulet908628c2022-03-25 16:43:49 +01002634 struct channel *rep = cs_ic(cs);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002635 struct resolvers *resolver = ctx->obj1;
2636 struct dns_nameserver *ns = ctx->obj2;
Emeric Brunc9437992021-02-12 19:42:55 +01002637
2638 if (!resolver)
2639 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2640
2641 /* dump resolvers */
2642 list_for_each_entry_from(resolver, &sec_resolvers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002643 ctx->obj1 = resolver;
Emeric Brunc9437992021-02-12 19:42:55 +01002644
Willy Tarreau91cefca2022-05-03 17:08:29 +02002645 ns = ctx->obj2 ?
2646 ctx->obj2 :
Emeric Brunc9437992021-02-12 19:42:55 +01002647 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2648
2649 list_for_each_entry_from(ns, &resolver->nameservers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002650 ctx->obj2 = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002651
2652 if (buffer_almost_full(&rep->buf))
2653 goto full;
2654
Christopher Faulet908628c2022-03-25 16:43:49 +01002655 if (!stats_dump_resolv_to_buffer(cs, ns,
Emeric Brunc9437992021-02-12 19:42:55 +01002656 stats, stats_count,
2657 stat_modules)) {
2658 return 0;
2659 }
2660 }
2661
Willy Tarreau91cefca2022-05-03 17:08:29 +02002662 ctx->obj2 = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002663 }
2664
2665 return 1;
2666
2667 full:
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002668 cs_rx_room_blk(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002669 return 0;
2670}
2671
2672void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2673{
2674 struct resolvers *resolvers;
2675 struct dns_nameserver *ns;
2676 struct stats_module *mod;
2677 void *counters;
2678
2679 list_for_each_entry(mod, stat_modules, list) {
2680 if (!mod->clearable && !clrall)
2681 continue;
2682
2683 list_for_each_entry(resolvers, &sec_resolvers, list) {
2684 list_for_each_entry(ns, &resolvers->nameservers, list) {
2685 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2686 memcpy(counters, mod->counters, mod->counters_size);
2687 }
2688 }
2689 }
2690
2691}
2692
2693int resolv_allocate_counters(struct list *stat_modules)
2694{
2695 struct stats_module *mod;
2696 struct resolvers *resolvers;
2697 struct dns_nameserver *ns;
2698
2699 list_for_each_entry(resolvers, &sec_resolvers, list) {
2700 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunf8642ee2021-10-29 17:59:18 +02002701 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
Emeric Brunc9437992021-02-12 19:42:55 +01002702 alloc_failed);
2703
2704 list_for_each_entry(mod, stat_modules, list) {
2705 EXTRA_COUNTERS_ADD(mod,
2706 ns->extra_counters,
2707 mod->counters,
2708 mod->counters_size);
2709 }
2710
2711 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2712
2713 list_for_each_entry(mod, stat_modules, list) {
2714 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2715 mod->counters, mod->counters_size);
2716
2717 /* Store the ns counters pointer */
Emeric Brunf8642ee2021-10-29 17:59:18 +02002718 if (strcmp(mod->name, "resolvers") == 0) {
2719 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
Emeric Brunc9437992021-02-12 19:42:55 +01002720 ns->counters->id = ns->id;
2721 ns->counters->pid = resolvers->id;
2722 }
2723 }
2724 }
2725 }
2726
2727 return 1;
2728
2729alloc_failed:
2730 return 0;
2731}
2732
Willy Tarreaudb933d62022-05-05 15:39:02 +02002733/* if an arg is found, it sets the optional resolvers section pointer into a
2734 * show_resolvers_ctx struct pointed to by svcctx, or NULL when dumping all.
2735 */
Emeric Brunc9437992021-02-12 19:42:55 +01002736static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2737{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002738 struct show_resolvers_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Emeric Brunc9437992021-02-12 19:42:55 +01002739 struct resolvers *presolvers;
2740
2741 if (*args[2]) {
2742 list_for_each_entry(presolvers, &sec_resolvers, list) {
2743 if (strcmp(presolvers->id, args[2]) == 0) {
Willy Tarreaudb933d62022-05-05 15:39:02 +02002744 ctx->forced_section = presolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002745 break;
2746 }
2747 }
Willy Tarreaudb933d62022-05-05 15:39:02 +02002748 if (ctx->forced_section == NULL)
Emeric Brunc9437992021-02-12 19:42:55 +01002749 return cli_err(appctx, "Can't find that resolvers section\n");
2750 }
2751 return 0;
2752}
2753
2754/* Dumps counters from all resolvers section and associated name servers. It
2755 * returns 0 if the output buffer is full and it needs to be called again,
Willy Tarreaudb933d62022-05-05 15:39:02 +02002756 * otherwise non-zero. It may limit itself to the resolver pointed to by the
2757 * <resolvers> field of struct show_resolvers_ctx pointed to by <svcctx> if
2758 * it's not null.
Emeric Brunc9437992021-02-12 19:42:55 +01002759 */
2760static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2761{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002762 struct show_resolvers_ctx *ctx = appctx->svcctx;
Willy Tarreau0698c802022-05-11 14:09:57 +02002763 struct conn_stream *cs = appctx_cs(appctx);
Willy Tarreaudb933d62022-05-05 15:39:02 +02002764 struct resolvers *resolvers = ctx->resolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002765 struct dns_nameserver *ns;
2766
2767 chunk_reset(&trash);
2768
Willy Tarreau12d52282022-05-05 16:38:13 +02002769 if (LIST_ISEMPTY(&sec_resolvers)) {
2770 if (ci_putstr(cs_ic(cs), "No resolvers found\n") == -1)
2771 goto full;
2772 }
2773 else {
2774 if (!resolvers)
2775 resolvers = LIST_ELEM(sec_resolvers.n, typeof(resolvers), list);
Willy Tarreau4e047e72022-05-05 16:00:45 +02002776
Willy Tarreau12d52282022-05-05 16:38:13 +02002777 list_for_each_entry_from(resolvers, &sec_resolvers, list) {
2778 if (ctx->forced_section != NULL && ctx->forced_section != resolvers)
2779 continue;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002780
Willy Tarreau12d52282022-05-05 16:38:13 +02002781 ctx->resolvers = resolvers;
2782 ns = ctx->ns;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002783
Willy Tarreau12d52282022-05-05 16:38:13 +02002784 if (!ns) {
2785 chunk_printf(&trash, "Resolvers section %s\n", resolvers->id);
2786 if (ci_putchk(cs_ic(cs), &trash) == -1)
2787 goto full;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002788
Willy Tarreau12d52282022-05-05 16:38:13 +02002789 ns = LIST_ELEM(resolvers->nameservers.n, typeof(ns), list);
2790 ctx->ns = ns;
2791 }
Willy Tarreau4e047e72022-05-05 16:00:45 +02002792
Willy Tarreau12d52282022-05-05 16:38:13 +02002793 list_for_each_entry_from(ns, &resolvers->nameservers, list) {
2794 chunk_reset(&trash);
2795 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2796 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2797 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2798 chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
2799 chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
2800 chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
2801 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
2802 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
2803 chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
2804 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
2805 chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
2806 chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
2807 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
2808 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
2809 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
2810 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
2811 if (ci_putchk(cs_ic(cs), &trash) == -1)
2812 goto full;
2813 ctx->ns = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002814 }
Emeric Brunc9437992021-02-12 19:42:55 +01002815
Willy Tarreau12d52282022-05-05 16:38:13 +02002816 ctx->ns = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002817
Willy Tarreau12d52282022-05-05 16:38:13 +02002818 /* was this the only section to dump ? */
2819 if (ctx->forced_section)
2820 break;
2821 }
Emeric Brunc9437992021-02-12 19:42:55 +01002822 }
Willy Tarreau12d52282022-05-05 16:38:13 +02002823
2824 /* done! */
2825 return 1;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002826 full:
2827 /* the output buffer is full, retry later */
2828 cs_rx_room_blk(cs);
2829 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002830}
2831
2832/* register cli keywords */
2833static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002834 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002835 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2836 {{},}
2837 }
2838};
2839
2840INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2841
2842/*
2843 * Prepare <rule> for hostname resolution.
2844 * Returns -1 in case of any allocation failure, 0 if not.
2845 * On error, a global failure counter is also incremented.
2846 */
Willy Tarreau947ae122021-10-14 08:11:48 +02002847static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002848{
2849 char *hostname_dn;
Willy Tarreau947ae122021-10-14 08:11:48 +02002850 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002851 struct buffer *tmp = get_trash_chunk();
2852
2853 if (!hostname)
2854 return 0;
2855
Emeric Brunc9437992021-02-12 19:42:55 +01002856 hostname_dn = tmp->area;
Willy Tarreaubf9498a2021-10-14 07:49:49 +02002857 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002858 hostname_dn, tmp->size);
2859 if (hostname_dn_len == -1)
2860 goto err;
2861
2862
2863 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2864 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2865 if (!stream->resolv_ctx.hostname_dn)
2866 goto err;
2867
2868 return 0;
2869
2870 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002871 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002872 resolv_failed_resolutions += 1;
2873 return -1;
2874}
2875
2876
2877/*
2878 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2879 */
2880enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2881 struct session *sess, struct stream *s, int flags)
2882{
2883 struct resolv_resolution *resolution;
2884 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002885 struct resolv_requester *req;
2886 struct resolvers *resolvers;
2887 struct resolv_resolution *res;
2888 int exp, locked = 0;
2889 enum act_return ret = ACT_RET_CONT;
2890
2891 resolvers = rule->arg.resolv.resolvers;
2892
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002893 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002894
Emeric Brunc9437992021-02-12 19:42:55 +01002895 /* we have a response to our DNS resolution */
2896 use_cache:
2897 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2898 resolution = s->resolv_ctx.requester->resolution;
2899 if (!locked) {
2900 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2901 locked = 1;
2902 }
2903
2904 if (resolution->step == RSLV_STEP_RUNNING)
2905 goto yield;
2906 if (resolution->step == RSLV_STEP_NONE) {
2907 /* We update the variable only if we have a valid response. */
2908 if (resolution->status == RSLV_STATUS_VALID) {
2909 struct sample smp;
2910 short ip_sin_family = 0;
2911 void *ip = NULL;
2912
2913 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2914 0, &ip, &ip_sin_family, NULL);
2915
2916 switch (ip_sin_family) {
2917 case AF_INET:
2918 smp.data.type = SMP_T_IPV4;
2919 memcpy(&smp.data.u.ipv4, ip, 4);
2920 break;
2921 case AF_INET6:
2922 smp.data.type = SMP_T_IPV6;
2923 memcpy(&smp.data.u.ipv6, ip, 16);
2924 break;
2925 default:
2926 ip = NULL;
2927 }
2928
2929 if (ip) {
2930 smp.px = px;
2931 smp.sess = sess;
2932 smp.strm = s;
2933
2934 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2935 }
2936 }
2937 }
2938
2939 goto release_requester;
2940 }
2941
2942 /* need to configure and start a new DNS resolution */
2943 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2944 if (smp == NULL)
2945 goto end;
2946
Willy Tarreau947ae122021-10-14 08:11:48 +02002947 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002948 goto end; /* on error, ignore the action */
2949
2950 s->resolv_ctx.parent = rule;
2951
2952 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2953 locked = 1;
2954
2955 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2956
2957 /* Check if there is a fresh enough response in the cache of our associated resolution */
2958 req = s->resolv_ctx.requester;
2959 if (!req || !req->resolution)
2960 goto release_requester; /* on error, ignore the action */
2961 res = req->resolution;
2962
2963 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2964 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2965 && !tick_is_expired(exp, now_ms)) {
2966 goto use_cache;
2967 }
2968
2969 resolv_trigger_resolution(s->resolv_ctx.requester);
2970
2971 yield:
2972 if (flags & ACT_OPT_FINAL)
2973 goto release_requester;
2974 ret = ACT_RET_YIELD;
2975
2976 end:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002977 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002978 if (locked)
2979 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2980 return ret;
2981
2982 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002983 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002984 s->resolv_ctx.hostname_dn_len = 0;
2985 if (s->resolv_ctx.requester) {
Willy Tarreau6878f802021-10-20 14:07:31 +02002986 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01002987 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2988 s->resolv_ctx.requester = NULL;
2989 }
2990 goto end;
2991}
2992
2993static void release_resolv_action(struct act_rule *rule)
2994{
2995 release_sample_expr(rule->arg.resolv.expr);
2996 free(rule->arg.resolv.varname);
2997 free(rule->arg.resolv.resolvers_id);
2998 free(rule->arg.resolv.opts);
2999}
3000
3001
3002/* parse "do-resolve" action
3003 * This action takes the following arguments:
3004 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3005 *
3006 * - <varName> is the variable name where the result of the DNS resolution will be stored
3007 * (mandatory)
3008 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3009 * (mandatory)
3010 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3011 * (optional), defaults to ipv6
3012 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3013 */
3014enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3015{
3016 int cur_arg;
3017 struct sample_expr *expr;
3018 unsigned int where;
3019 const char *beg, *end;
3020
3021 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3022 cur_arg = *orig_arg - 1;
3023
3024 /* locate varName, which is mandatory */
3025 beg = strchr(args[cur_arg], '(');
3026 if (beg == NULL)
3027 goto do_resolve_parse_error;
3028 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3029 end = strchr(beg, ',');
3030 if (end == NULL)
3031 goto do_resolve_parse_error;
3032 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3033 if (rule->arg.resolv.varname == NULL)
3034 goto do_resolve_parse_error;
3035
3036
3037 /* locate resolversSectionName, which is mandatory.
3038 * Since next parameters are optional, the delimiter may be comma ','
3039 * or closing parenthesis ')'
3040 */
3041 beg = end + 1;
3042 end = strchr(beg, ',');
3043 if (end == NULL)
3044 end = strchr(beg, ')');
3045 if (end == NULL)
3046 goto do_resolve_parse_error;
3047 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3048 if (rule->arg.resolv.resolvers_id == NULL)
3049 goto do_resolve_parse_error;
3050
3051
3052 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3053 if (rule->arg.resolv.opts == NULL)
3054 goto do_resolve_parse_error;
3055
3056 /* Default priority is ipv6 */
3057 rule->arg.resolv.opts->family_prio = AF_INET6;
3058
3059 /* optional arguments accepted for now:
3060 * ipv4 or ipv6
3061 */
3062 while (*end != ')') {
3063 beg = end + 1;
3064 end = strchr(beg, ',');
3065 if (end == NULL)
3066 end = strchr(beg, ')');
3067 if (end == NULL)
3068 goto do_resolve_parse_error;
3069
3070 if (strncmp(beg, "ipv4", end - beg) == 0) {
3071 rule->arg.resolv.opts->family_prio = AF_INET;
3072 }
3073 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3074 rule->arg.resolv.opts->family_prio = AF_INET6;
3075 }
3076 else {
3077 goto do_resolve_parse_error;
3078 }
3079 }
3080
3081 cur_arg = cur_arg + 1;
3082
3083 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3084 if (!expr)
3085 goto do_resolve_parse_error;
3086
3087
3088 where = 0;
3089 if (px->cap & PR_CAP_FE)
3090 where |= SMP_VAL_FE_HRQ_HDR;
3091 if (px->cap & PR_CAP_BE)
3092 where |= SMP_VAL_BE_HRQ_HDR;
3093
3094 if (!(expr->fetch->val & where)) {
3095 memprintf(err,
3096 "fetch method '%s' extracts information from '%s', none of which is available here",
3097 args[cur_arg-1], sample_src_names(expr->fetch->use));
3098 free(expr);
3099 return ACT_RET_PRS_ERR;
3100 }
3101 rule->arg.resolv.expr = expr;
3102 rule->action = ACT_CUSTOM;
3103 rule->action_ptr = resolv_action_do_resolve;
3104 *orig_arg = cur_arg;
3105
3106 rule->check_ptr = check_action_do_resolve;
3107 rule->release_ptr = release_resolv_action;
3108
3109 return ACT_RET_PRS_OK;
3110
3111 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003112 ha_free(&rule->arg.resolv.varname);
3113 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003114 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3115 args[cur_arg]);
3116 return ACT_RET_PRS_ERR;
3117}
3118
3119static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003120 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003121 { /* END */ }
3122}};
3123
3124INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3125
3126static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003127 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003128 { /* END */ }
3129}};
3130
3131INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3132
3133/* Check an "http-request do-resolve" action.
3134 *
3135 * The function returns 1 in success case, otherwise, it returns 0 and err is
3136 * filled.
3137 */
3138int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3139{
3140 struct resolvers *resolvers = NULL;
3141
3142 if (rule->arg.resolv.resolvers_id == NULL) {
3143 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3144 return 0;
3145 }
3146
3147 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3148 if (resolvers == NULL) {
3149 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3150 return 0;
3151 }
3152 rule->arg.resolv.resolvers = resolvers;
3153
3154 return 1;
3155}
3156
3157void resolvers_setup_proxy(struct proxy *px)
3158{
3159 px->last_change = now.tv_sec;
3160 px->cap = PR_CAP_FE | PR_CAP_BE;
3161 px->maxconn = 0;
3162 px->conn_retries = 1;
3163 px->timeout.server = TICK_ETERNITY;
3164 px->timeout.client = TICK_ETERNITY;
3165 px->timeout.connect = TICK_ETERNITY;
3166 px->accept = NULL;
3167 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
Emeric Brunc9437992021-02-12 19:42:55 +01003168}
3169
William Lallemand73edfe42022-05-05 17:36:09 +02003170static int parse_resolve_conf(char **errmsg, char **warnmsg)
3171{
3172 struct dns_nameserver *newnameserver = NULL;
3173 const char *whitespace = "\r\n\t ";
3174 char *resolv_line = NULL;
3175 int resolv_linenum = 0;
3176 FILE *f = NULL;
3177 char *address = NULL;
3178 struct sockaddr_storage *sk = NULL;
3179 struct protocol *proto;
3180 int duplicate_name = 0;
3181 int err_code = 0;
3182
3183 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3184 memprintf(errmsg, "out of memory.\n");
3185 err_code |= ERR_ALERT | ERR_FATAL;
3186 goto resolv_out;
3187 }
3188
3189 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3190 if (errmsg)
3191 memprintf(errmsg, "failed to open /etc/resolv.conf.");
3192 err_code |= ERR_ALERT | ERR_FATAL;
3193 goto resolv_out;
3194 }
3195
3196 sk = calloc(1, sizeof(*sk));
3197 if (sk == NULL) {
3198 if (errmsg)
3199 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3200 err_code |= ERR_ALERT | ERR_FATAL;
3201 goto resolv_out;
3202 }
3203
3204 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3205 resolv_linenum++;
3206 if (strncmp(resolv_line, "nameserver", 10) != 0)
3207 continue;
3208
3209 address = strtok(resolv_line + 10, whitespace);
3210 if (address == resolv_line + 10)
3211 continue;
3212
3213 if (address == NULL) {
3214 if (warnmsg)
3215 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3216 *warnmsg ? *warnmsg : "", resolv_linenum);
3217 err_code |= ERR_WARN;
3218 continue;
3219 }
3220
3221 duplicate_name = 0;
3222 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3223 if (strcmp(newnameserver->id, address) == 0) {
3224 if (warnmsg)
3225 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",
3226 *warnmsg ? *warnmsg : "", resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3227 err_code |= ERR_WARN;
3228 duplicate_name = 1;
3229 }
3230 }
3231
3232 if (duplicate_name)
3233 continue;
3234
3235 memset(sk, 0, sizeof(*sk));
3236 if (!str2ip2(address, sk, 1)) {
3237 if (warnmsg)
3238 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3239 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3240 err_code |= ERR_WARN;
3241 continue;
3242 }
3243
3244 set_host_port(sk, 53);
3245
3246 proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
3247 if (!proto || !proto->connect) {
3248 if (warnmsg)
3249 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3250 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3251 err_code |= ERR_WARN;
3252 continue;
3253 }
3254
3255 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3256 if (errmsg)
3257 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3258 err_code |= ERR_ALERT | ERR_FATAL;
3259 goto resolv_out;
3260 }
3261
3262 if (dns_dgram_init(newnameserver, sk) < 0) {
3263 if (errmsg)
3264 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3265 err_code |= ERR_ALERT | ERR_FATAL;
3266 free(newnameserver);
3267 goto resolv_out;
3268 }
3269
3270 newnameserver->conf.file = strdup("/etc/resolv.conf");
3271 if (newnameserver->conf.file == NULL) {
3272 if (errmsg)
3273 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3274 err_code |= ERR_ALERT | ERR_FATAL;
3275 free(newnameserver);
3276 goto resolv_out;
3277 }
3278
3279 newnameserver->id = strdup(address);
3280 if (newnameserver->id == NULL) {
3281 if (errmsg)
3282 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3283 err_code |= ERR_ALERT | ERR_FATAL;
3284 free((char *)newnameserver->conf.file);
3285 free(newnameserver);
3286 goto resolv_out;
3287 }
3288
3289 newnameserver->parent = curr_resolvers;
3290 newnameserver->process_responses = resolv_process_responses;
3291 newnameserver->conf.line = resolv_linenum;
3292 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
3293 }
3294
3295resolv_out:
3296 free(sk);
3297 free(resolv_line);
3298 if (f != NULL)
3299 fclose(f);
3300
3301 return err_code;
3302}
3303
William Lallemande7f57762022-05-05 18:27:48 +02003304static int resolvers_new(struct resolvers **resolvers, const char *id, const char *file, int linenum)
3305{
3306 struct resolvers *r = NULL;
3307 struct proxy *p = NULL;
3308 int err_code = 0;
3309
3310 if ((r = calloc(1, sizeof(*r))) == NULL) {
3311 err_code |= ERR_ALERT | ERR_ABORT;
3312 goto out;
3313 }
3314
3315 /* allocate new proxy to tcp servers */
3316 p = calloc(1, sizeof *p);
3317 if (!p) {
3318 err_code |= ERR_ALERT | ERR_FATAL;
3319 goto out;
3320 }
3321
3322 init_new_proxy(p);
3323 resolvers_setup_proxy(p);
3324 p->parent = r;
3325 p->id = strdup(id);
3326 p->conf.args.file = p->conf.file = strdup(file);
3327 p->conf.args.line = p->conf.line = linenum;
3328 r->px = p;
3329
3330 /* default values */
3331 LIST_APPEND(&sec_resolvers, &r->list);
3332 r->conf.file = strdup(file);
3333 r->conf.line = linenum;
3334 r->id = strdup(id);
3335 r->query_ids = EB_ROOT;
3336 /* default maximum response size */
3337 r->accepted_payload_size = 512;
3338 /* default hold period for nx, other, refuse and timeout is 30s */
3339 r->hold.nx = 30000;
3340 r->hold.other = 30000;
3341 r->hold.refused = 30000;
3342 r->hold.timeout = 30000;
3343 r->hold.obsolete = 0;
3344 /* default hold period for valid is 10s */
3345 r->hold.valid = 10000;
3346 r->timeout.resolve = 1000;
3347 r->timeout.retry = 1000;
3348 r->resolve_retries = 3;
3349 LIST_INIT(&r->nameservers);
3350 LIST_INIT(&r->resolutions.curr);
3351 LIST_INIT(&r->resolutions.wait);
3352 HA_SPIN_INIT(&r->lock);
3353
3354 *resolvers = r;
3355
3356out:
3357 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3358 ha_free(&r);
3359 ha_free(&p);
3360 }
3361
3362 return err_code;
3363}
3364
3365
Emeric Brunc9437992021-02-12 19:42:55 +01003366/*
3367 * Parse a <resolvers> section.
3368 * Returns the error code, 0 if OK, or any combination of :
3369 * - ERR_ABORT: must abort ASAP
3370 * - ERR_FATAL: we can continue parsing but not start the service
3371 * - ERR_WARN: a warning has been emitted
3372 * - ERR_ALERT: an alert has been emitted
3373 * Only the two first ones can stop processing, the two others are just
3374 * indicators.
3375 */
3376int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3377{
3378 const char *err;
3379 int err_code = 0;
3380 char *errmsg = NULL;
William Lallemand106bd292022-05-05 17:20:08 +02003381 char *warnmsg = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01003382
3383 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3384 if (!*args[1]) {
3385 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3386 err_code |= ERR_ALERT | ERR_ABORT;
3387 goto out;
3388 }
3389
3390 err = invalid_char(args[1]);
3391 if (err) {
3392 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3393 file, linenum, *err, args[0], args[1]);
3394 err_code |= ERR_ALERT | ERR_ABORT;
3395 goto out;
3396 }
3397
3398 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3399 /* Error if two resolvers owns the same name */
3400 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3401 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3402 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3403 err_code |= ERR_ALERT | ERR_ABORT;
3404 }
3405 }
3406
William Lallemande7f57762022-05-05 18:27:48 +02003407 err_code |= resolvers_new(&curr_resolvers, args[1], file, linenum);
3408 if (err_code & ERR_ALERT) {
Emeric Brunc9437992021-02-12 19:42:55 +01003409 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
Emeric Brunc9437992021-02-12 19:42:55 +01003410 goto out;
3411 }
3412
Emeric Brunc9437992021-02-12 19:42:55 +01003413 }
3414 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3415 struct dns_nameserver *newnameserver = NULL;
3416 struct sockaddr_storage *sk;
3417 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003418 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003419
3420 if (!*args[2]) {
3421 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3422 file, linenum, args[0]);
3423 err_code |= ERR_ALERT | ERR_FATAL;
3424 goto out;
3425 }
3426
3427 err = invalid_char(args[1]);
3428 if (err) {
3429 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3430 file, linenum, *err, args[1]);
3431 err_code |= ERR_ALERT | ERR_FATAL;
3432 goto out;
3433 }
3434
3435 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3436 /* Error if two resolvers owns the same name */
3437 if (strcmp(newnameserver->id, args[1]) == 0) {
3438 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3439 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3440 err_code |= ERR_ALERT | ERR_FATAL;
3441 }
3442 }
3443
Emeric Brunc8f3e452021-04-07 16:04:54 +02003444 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3445 &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 +01003446 if (!sk) {
3447 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3448 err_code |= ERR_ALERT | ERR_FATAL;
3449 goto out;
3450 }
3451
3452 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3453 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3454 err_code |= ERR_ALERT | ERR_ABORT;
3455 goto out;
3456 }
3457
Emeric Brunc8f3e452021-04-07 16:04:54 +02003458 if (proto && proto->ctrl_type == SOCK_STREAM) {
3459 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3460 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3461 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3462 err_code |= ERR_ABORT;
3463 goto out;
3464 }
3465
3466 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3467 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3468 err_code |= ERR_ALERT|ERR_ABORT;
3469 goto out;
3470 }
3471 }
3472 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003473 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3474 err_code |= ERR_ALERT | ERR_ABORT;
3475 goto out;
3476 }
3477
3478 if ((newnameserver->conf.file = strdup(file)) == 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
3484 if ((newnameserver->id = strdup(args[1])) == NULL) {
3485 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3486 err_code |= ERR_ALERT | ERR_ABORT;
3487 goto out;
3488 }
3489
3490 newnameserver->parent = curr_resolvers;
3491 newnameserver->process_responses = resolv_process_responses;
3492 newnameserver->conf.line = linenum;
3493 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003494 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003495 }
3496 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
William Lallemand73edfe42022-05-05 17:36:09 +02003497 err_code |= parse_resolve_conf(&errmsg, &warnmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003498 if (err_code & ERR_WARN) {
3499 indent_msg(&warnmsg, 8);
3500 ha_warning("parsing [%s:%d]: %s\n", file, linenum, warnmsg);
3501 ha_free(&warnmsg);
3502 }
William Lallemand106bd292022-05-05 17:20:08 +02003503 if (err_code & ERR_ALERT) {
3504 indent_msg(&errmsg, 8);
3505 ha_alert("parsing [%s:%d]: %s\n", file, linenum, errmsg);
3506 ha_free(&errmsg);
William Lallemand73edfe42022-05-05 17:36:09 +02003507 goto out;
William Lallemand106bd292022-05-05 17:20:08 +02003508 }
Emeric Brunc9437992021-02-12 19:42:55 +01003509 }
3510 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3511 const char *res;
3512 unsigned int time;
3513
3514 if (!*args[2]) {
3515 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3516 file, linenum, args[0]);
3517 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3518 err_code |= ERR_ALERT | ERR_FATAL;
3519 goto out;
3520 }
3521 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3522 if (res == PARSE_TIME_OVER) {
3523 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3524 file, linenum, args[1], args[0]);
3525 err_code |= ERR_ALERT | ERR_FATAL;
3526 goto out;
3527 }
3528 else if (res == PARSE_TIME_UNDER) {
3529 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3530 file, linenum, args[1], args[0]);
3531 err_code |= ERR_ALERT | ERR_FATAL;
3532 goto out;
3533 }
3534 else if (res) {
3535 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3536 file, linenum, *res, args[0]);
3537 err_code |= ERR_ALERT | ERR_FATAL;
3538 goto out;
3539 }
3540 if (strcmp(args[1], "nx") == 0)
3541 curr_resolvers->hold.nx = time;
3542 else if (strcmp(args[1], "other") == 0)
3543 curr_resolvers->hold.other = time;
3544 else if (strcmp(args[1], "refused") == 0)
3545 curr_resolvers->hold.refused = time;
3546 else if (strcmp(args[1], "timeout") == 0)
3547 curr_resolvers->hold.timeout = time;
3548 else if (strcmp(args[1], "valid") == 0)
3549 curr_resolvers->hold.valid = time;
3550 else if (strcmp(args[1], "obsolete") == 0)
3551 curr_resolvers->hold.obsolete = time;
3552 else {
3553 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3554 file, linenum, args[0], args[1]);
3555 err_code |= ERR_ALERT | ERR_FATAL;
3556 goto out;
3557 }
3558
3559 }
3560 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3561 int i = 0;
3562
3563 if (!*args[1]) {
3564 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3565 file, linenum, args[0]);
3566 err_code |= ERR_ALERT | ERR_FATAL;
3567 goto out;
3568 }
3569
3570 i = atoi(args[1]);
3571 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3572 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3573 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3574 err_code |= ERR_ALERT | ERR_FATAL;
3575 goto out;
3576 }
3577
3578 curr_resolvers->accepted_payload_size = i;
3579 }
3580 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3581 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3582 file, linenum, args[0]);
3583 err_code |= ERR_ALERT | ERR_FATAL;
3584 goto out;
3585 }
3586 else if (strcmp(args[0], "resolve_retries") == 0) {
3587 if (!*args[1]) {
3588 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3589 file, linenum, args[0]);
3590 err_code |= ERR_ALERT | ERR_FATAL;
3591 goto out;
3592 }
3593 curr_resolvers->resolve_retries = atoi(args[1]);
3594 }
3595 else if (strcmp(args[0], "timeout") == 0) {
3596 if (!*args[1]) {
3597 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3598 file, linenum, args[0]);
3599 err_code |= ERR_ALERT | ERR_FATAL;
3600 goto out;
3601 }
3602 else if (strcmp(args[1], "retry") == 0 ||
3603 strcmp(args[1], "resolve") == 0) {
3604 const char *res;
3605 unsigned int tout;
3606
3607 if (!*args[2]) {
3608 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3609 file, linenum, args[0], args[1]);
3610 err_code |= ERR_ALERT | ERR_FATAL;
3611 goto out;
3612 }
3613 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3614 if (res == PARSE_TIME_OVER) {
3615 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3616 file, linenum, args[2], args[0], args[1]);
3617 err_code |= ERR_ALERT | ERR_FATAL;
3618 goto out;
3619 }
3620 else if (res == PARSE_TIME_UNDER) {
3621 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3622 file, linenum, args[2], args[0], args[1]);
3623 err_code |= ERR_ALERT | ERR_FATAL;
3624 goto out;
3625 }
3626 else if (res) {
3627 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3628 file, linenum, *res, args[0], args[1]);
3629 err_code |= ERR_ALERT | ERR_FATAL;
3630 goto out;
3631 }
3632 if (args[1][2] == 't')
3633 curr_resolvers->timeout.retry = tout;
3634 else
3635 curr_resolvers->timeout.resolve = tout;
3636 }
3637 else {
3638 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3639 file, linenum, args[0], args[1]);
3640 err_code |= ERR_ALERT | ERR_FATAL;
3641 goto out;
3642 }
3643 }
3644 else if (*args[0] != 0) {
3645 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3646 err_code |= ERR_ALERT | ERR_FATAL;
3647 goto out;
3648 }
3649
William Lallemand106bd292022-05-05 17:20:08 +02003650out:
Emeric Brunc9437992021-02-12 19:42:55 +01003651 free(errmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003652 free(warnmsg);
Emeric Brunc9437992021-02-12 19:42:55 +01003653 return err_code;
3654}
William Lallemand7867f632022-05-05 19:02:59 +02003655
3656/* try to create a "default" resolvers section which uses "/etc/resolv.conf"
3657 *
3658 * This function is opportunistic and does not try to display errors or warnings.
3659 */
3660int resolvers_create_default()
3661{
3662 int err_code = 0;
3663
3664 if (find_resolvers_by_id("default"))
3665 return 0;
3666
3667 err_code |= resolvers_new(&curr_resolvers, "default", "<internal>", 0);
3668 if (!(err_code & ERR_CODE))
3669 err_code |= parse_resolve_conf(NULL, NULL);
3670
3671 return 0;
3672}
3673
Emeric Brun56fc5d92021-02-12 20:05:45 +01003674int cfg_post_parse_resolvers()
3675{
3676 int err_code = 0;
3677 struct server *srv;
3678
3679 if (curr_resolvers) {
3680
3681 /* prepare forward server descriptors */
3682 if (curr_resolvers->px) {
3683 srv = curr_resolvers->px->srv;
3684 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003685 /* init ssl if needed */
3686 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3687 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3688 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3689 err_code |= ERR_ALERT | ERR_FATAL;
3690 break;
3691 }
3692 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003693 srv = srv->next;
3694 }
3695 }
3696 }
3697 curr_resolvers = NULL;
3698 return err_code;
3699}
Emeric Brunc9437992021-02-12 19:42:55 +01003700
Emeric Brun56fc5d92021-02-12 20:05:45 +01003701REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003702REGISTER_POST_DEINIT(resolvers_deinit);
3703REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);
William Lallemand7867f632022-05-05 19:02:59 +02003704REGISTER_PRE_CHECK(resolvers_create_default);