blob: 4bbc6e50b3d8892e0c3ecec41318ae42ee6e570e [file] [log] [blame]
Emeric Brunc9437992021-02-12 19:42:55 +01001/*
2 * Name server resolution
3 *
4 * Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
Emeric Brunc9437992021-02-12 19:42:55 +010014#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <unistd.h>
18
19#include <sys/types.h>
20
Emeric Brun34067662021-06-11 10:48:45 +020021#include <import/ebistree.h>
22
Emeric Brunc9437992021-02-12 19:42:55 +010023#include <haproxy/action.h>
24#include <haproxy/api.h>
Willy Tarreaudb933d62022-05-05 15:39:02 +020025#include <haproxy/applet.h>
Emeric Brunc9437992021-02-12 19:42:55 +010026#include <haproxy/cfgparse.h>
27#include <haproxy/channel.h>
28#include <haproxy/check.h>
29#include <haproxy/cli.h>
30#include <haproxy/dns.h>
31#include <haproxy/errors.h>
32#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010033#include <haproxy/http_rules.h>
34#include <haproxy/log.h>
35#include <haproxy/net_helper.h>
36#include <haproxy/protocol.h>
37#include <haproxy/proxy.h>
38#include <haproxy/resolvers.h>
39#include <haproxy/ring.h>
40#include <haproxy/sample.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020041#include <haproxy/sc_strm.h>
Emeric Brunc9437992021-02-12 19:42:55 +010042#include <haproxy/server.h>
43#include <haproxy/stats.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020044#include <haproxy/stconn.h>
Emeric Brunc9437992021-02-12 19:42:55 +010045#include <haproxy/task.h>
46#include <haproxy/tcp_rules.h>
47#include <haproxy/ticks.h>
48#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020049#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010050#include <haproxy/vars.h>
Willy Tarreaudcb696c2021-10-21 08:18:01 +020051#include <haproxy/xxhash.h>
Emeric Brunc9437992021-02-12 19:42:55 +010052
53
54struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
55struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
56
Willy Tarreauf766ec62021-10-18 16:46:38 +020057static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
Christopher Faulet9ed1a062021-11-02 16:25:05 +010058static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
Emeric Brunc9437992021-02-12 19:42:55 +010059static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
60struct resolvers *curr_resolvers = NULL;
61
62DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
63DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
64DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
65
66static unsigned int resolution_uuid = 1;
67unsigned int resolv_failed_resolutions = 0;
Willy Tarreau0fbc16c2022-09-08 15:07:13 +020068struct task *process_resolvers(struct task *t, void *context, unsigned int state);
Willy Tarreauf766ec62021-10-18 16:46:38 +020069static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau6878f802021-10-20 14:07:31 +020070static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +010071static void enter_resolver_code();
72static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010073
74enum {
Emeric Brunf8642ee2021-10-29 17:59:18 +020075 RSLV_STAT_ID,
76 RSLV_STAT_PID,
77 RSLV_STAT_SENT,
78 RSLV_STAT_SND_ERROR,
79 RSLV_STAT_VALID,
80 RSLV_STAT_UPDATE,
81 RSLV_STAT_CNAME,
82 RSLV_STAT_CNAME_ERROR,
83 RSLV_STAT_ANY_ERR,
84 RSLV_STAT_NX,
85 RSLV_STAT_TIMEOUT,
86 RSLV_STAT_REFUSED,
87 RSLV_STAT_OTHER,
88 RSLV_STAT_INVALID,
89 RSLV_STAT_TOO_BIG,
90 RSLV_STAT_TRUNCATED,
91 RSLV_STAT_OUTDATED,
92 RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +010093};
94
Emeric Brunf8642ee2021-10-29 17:59:18 +020095static struct name_desc resolv_stats[] = {
96 [RSLV_STAT_ID] = { .name = "id", .desc = "ID" },
97 [RSLV_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
98 [RSLV_STAT_SENT] = { .name = "sent", .desc = "Sent" },
99 [RSLV_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
100 [RSLV_STAT_VALID] = { .name = "valid", .desc = "Valid" },
101 [RSLV_STAT_UPDATE] = { .name = "update", .desc = "Update" },
102 [RSLV_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
103 [RSLV_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
104 [RSLV_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
105 [RSLV_STAT_NX] = { .name = "nx", .desc = "NX" },
106 [RSLV_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
107 [RSLV_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
108 [RSLV_STAT_OTHER] = { .name = "other", .desc = "Other" },
109 [RSLV_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
110 [RSLV_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
111 [RSLV_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
112 [RSLV_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
Emeric Brunc9437992021-02-12 19:42:55 +0100113};
114
115static struct dns_counters dns_counters;
116
Emeric Brunf8642ee2021-10-29 17:59:18 +0200117static void resolv_fill_stats(void *d, struct field *stats)
Emeric Brunc9437992021-02-12 19:42:55 +0100118{
119 struct dns_counters *counters = d;
Emeric Brunf8642ee2021-10-29 17:59:18 +0200120 stats[RSLV_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
121 stats[RSLV_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
122 stats[RSLV_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
123 stats[RSLV_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
124 stats[RSLV_STAT_VALID] = mkf_u64(FN_GAUGE, counters->app.resolver.valid);
125 stats[RSLV_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->app.resolver.update);
126 stats[RSLV_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->app.resolver.cname);
127 stats[RSLV_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->app.resolver.cname_error);
128 stats[RSLV_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->app.resolver.any_err);
129 stats[RSLV_STAT_NX] = mkf_u64(FN_GAUGE, counters->app.resolver.nx);
130 stats[RSLV_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->app.resolver.timeout);
131 stats[RSLV_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->app.resolver.refused);
132 stats[RSLV_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->app.resolver.other);
133 stats[RSLV_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->app.resolver.invalid);
134 stats[RSLV_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->app.resolver.too_big);
135 stats[RSLV_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->app.resolver.truncated);
136 stats[RSLV_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +0100137}
138
Emeric Brunf8642ee2021-10-29 17:59:18 +0200139static struct stats_module rslv_stats_module = {
140 .name = "resolvers",
141 .domain_flags = STATS_DOMAIN_RESOLVERS << STATS_DOMAIN,
142 .fill_stats = resolv_fill_stats,
143 .stats = resolv_stats,
144 .stats_count = RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +0100145 .counters = &dns_counters,
146 .counters_size = sizeof(dns_counters),
147 .clearable = 0,
148};
149
Emeric Brunf8642ee2021-10-29 17:59:18 +0200150INITCALL1(STG_REGISTER, stats_register_module, &rslv_stats_module);
Emeric Brunc9437992021-02-12 19:42:55 +0100151
Willy Tarreaudb933d62022-05-05 15:39:02 +0200152/* CLI context used during "show resolvers" */
153struct show_resolvers_ctx {
154 struct resolvers *forced_section;
155 struct resolvers *resolvers;
156 struct dns_nameserver *ns;
157};
158
Emeric Brunc9437992021-02-12 19:42:55 +0100159/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
160 * no match is found.
161 */
162struct resolvers *find_resolvers_by_id(const char *id)
163{
164 struct resolvers *res;
165
166 list_for_each_entry(res, &sec_resolvers, list) {
167 if (strcmp(res->id, id) == 0)
168 return res;
169 }
170 return NULL;
171}
172
Emeric Brunc9437992021-02-12 19:42:55 +0100173/* Returns a pointer on the SRV request matching the name <name> for the proxy
174 * <px>. NULL is returned if no match is found.
175 */
176struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
177{
178 struct resolv_srvrq *srvrq;
179
180 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
181 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
182 return srvrq;
183 }
184 return NULL;
185}
186
187/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
188 * NULL if an error occurred. */
189struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
190{
191 struct proxy *px = srv->proxy;
192 struct resolv_srvrq *srvrq = NULL;
193 int fqdn_len, hostname_dn_len;
194
195 fqdn_len = strlen(fqdn);
Willy Tarreaubf9498a2021-10-14 07:49:49 +0200196 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100197 trash.size);
198 if (hostname_dn_len == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200199 ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100200 proxy_type_str(px), px->id, srv->id, fqdn);
201 goto err;
202 }
203
204 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200205 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100206 proxy_type_str(px), px->id, srv->id);
207 goto err;
208 }
209 srvrq->obj_type = OBJ_TYPE_SRVRQ;
210 srvrq->proxy = px;
211 srvrq->name = strdup(fqdn);
212 srvrq->hostname_dn = strdup(trash.area);
213 srvrq->hostname_dn_len = hostname_dn_len;
214 if (!srvrq->name || !srvrq->hostname_dn) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200215 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100216 proxy_type_str(px), px->id, srv->id);
217 goto err;
218 }
Emeric Brun34067662021-06-11 10:48:45 +0200219 LIST_INIT(&srvrq->attached_servers);
220 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200221 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100222 return srvrq;
223
224 err:
225 if (srvrq) {
226 free(srvrq->name);
227 free(srvrq->hostname_dn);
228 free(srvrq);
229 }
230 return NULL;
231}
232
233
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100234/* finds and return the SRV answer item associated to a requester (whose type is 'server').
235 *
236 * returns NULL in case of error or not found.
237 */
238struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
239{
240 struct resolv_resolution *res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200241 struct eb32_node *eb32;
242 struct server *srv;
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100243
244 if (!requester)
245 return NULL;
246
247 if ((srv = objt_server(requester->owner)) == NULL)
248 return NULL;
249 /* check if the server is managed by a SRV record */
250 if (srv->srvrq == NULL)
251 return NULL;
252
253 res = srv->srvrq->requester->resolution;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200254
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100255 /* search an ANSWER record whose target points to the server's hostname and whose port is
256 * the same as server's svc_port */
Willy Tarreau7893ae12021-10-21 07:39:57 +0200257 for (eb32 = eb32_first(&res->response.answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
258 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
259
Willy Tarreau75cc6532021-10-15 08:53:44 +0200260 if (memcmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100261 (srv->svc_port == item->port))
262 return item;
263 }
264
265 return NULL;
266}
267
Emeric Brunc9437992021-02-12 19:42:55 +0100268/* 2 bytes random generator to generate DNS query ID */
269static inline uint16_t resolv_rnd16(void)
270{
271 if (!resolv_query_id_seed)
272 resolv_query_id_seed = now_ms;
273 resolv_query_id_seed ^= resolv_query_id_seed << 13;
274 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
275 resolv_query_id_seed ^= resolv_query_id_seed << 17;
276 return resolv_query_id_seed;
277}
278
279
280static inline int resolv_resolution_timeout(struct resolv_resolution *res)
281{
282 return res->resolvers->timeout.resolve;
283}
284
285/* Updates a resolvers' task timeout for next wake up and queue it */
286static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
287{
288 struct resolv_resolution *res;
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{
Christopher Fauleteaabf062022-09-27 10:43:24 +0200597 /* Remove the resolution from query_ids tree and from any resolvers list */
598 eb32_delete(&res->qid);
599 res->query_id = 0;
600 res->qid.key = 0;
601
Willy Tarreauf766ec62021-10-18 16:46:38 +0200602 LIST_DEL_INIT(&res->list);
603 LIST_APPEND(&death_row, &res->list);
604}
605
606/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100607 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreauf766ec62021-10-18 16:46:38 +0200608 * needs to defer deletions. Note that some of them are in relation via internal
609 * objects and might cause the deletion of other ones from the same list, so we
610 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
611 * and solely rely on each call to remove the first remaining list element.
612 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100613static void leave_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200614{
615 struct resolv_resolution *res;
616
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100617 recurse--;
618 if (recurse)
619 return;
620
Willy Tarreauf766ec62021-10-18 16:46:38 +0200621 while (!LIST_ISEMPTY(&death_row)) {
622 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
623 resolv_free_resolution(res);
624 }
625
626 /* make sure nobody tries to add anything without having initialized it */
627 death_row = (struct list){ };
628}
629
Christopher Faulet11c6c392021-06-15 16:08:48 +0200630/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
631 * happens when an SRV item is purged or when the server status is considered as
632 * obsolete.
633 *
Willy Tarreauf766ec62021-10-18 16:46:38 +0200634 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100635 * initialized via enter_resolver_code().
Christopher Faulet11c6c392021-06-15 16:08:48 +0200636 */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200637static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet11c6c392021-06-15 16:08:48 +0200638{
Willy Tarreau6878f802021-10-20 14:07:31 +0200639 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200640 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
641 srvrq_update_srv_status(srv, 1);
642 ha_free(&srv->hostname);
643 ha_free(&srv->hostname_dn);
644 srv->hostname_dn_len = 0;
645 memset(&srv->addr, 0, sizeof(srv->addr));
646 srv->svc_port = 0;
647 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet73001ab2021-06-15 16:14:37 +0200648
649 ebpt_delete(&srv->host_dn);
650 ha_free(&srv->host_dn.key);
651
Christopher Faulet11c6c392021-06-15 16:08:48 +0200652 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreauaae73202021-10-19 22:01:36 +0200653 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200654 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Fauletdcac4182021-06-15 16:17:17 +0200655
656 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet11c6c392021-06-15 16:08:48 +0200657}
658
Christopher Fauletdcac4182021-06-15 16:17:17 +0200659/* Takes care to cleanup a server resolution when it is outdated. This only
660 * happens for a server relying on a SRV record.
661 */
662static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
663{
664 struct server *srv = context;
665
666 if (!tick_is_expired(t->expire, now_ms))
667 goto end;
668
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100669 enter_resolver_code();
Christopher Faulete886dd52021-06-18 09:05:49 +0200670 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreauf766ec62021-10-18 16:46:38 +0200671 resolv_srvrq_cleanup_srv(srv);
Christopher Faulete886dd52021-06-18 09:05:49 +0200672 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100673 leave_resolver_code();
Christopher Fauletdcac4182021-06-15 16:17:17 +0200674
675 end:
676 return t;
677}
678
Emeric Brunc9437992021-02-12 19:42:55 +0100679/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100680 * find a corresponding server.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200681 */
Emeric Brunc9437992021-02-12 19:42:55 +0100682static void resolv_check_response(struct resolv_resolution *res)
683{
684 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100685 struct resolv_requester *req;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200686 struct eb32_node *eb32, *eb32_back;
Emeric Brunbd78c912021-06-11 10:08:05 +0200687 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100688 struct resolv_srvrq *srvrq;
689
Willy Tarreau7893ae12021-10-21 07:39:57 +0200690 for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
691 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
Emeric Brunc9437992021-02-12 19:42:55 +0100692 struct resolv_answer_item *ar_item = item->ar_item;
693
694 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100695 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100696 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
697 * item is also obsolete.
698 */
Emeric Brunc9437992021-02-12 19:42:55 +0100699 pool_free(resolv_answer_item_pool, ar_item);
700 item->ar_item = NULL;
701 }
702
703 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100704 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200705 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100706 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200707 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
708 LIST_DEL_INIT(&srv->ip_rec_item);
709 }
710 }
711 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun34067662021-06-11 10:48:45 +0200712 /* Remove any associated server */
Christopher Faulet11c6c392021-06-15 16:08:48 +0200713 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreauf766ec62021-10-18 16:46:38 +0200714 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100715 }
716
Willy Tarreau7893ae12021-10-21 07:39:57 +0200717 eb32_delete(&item->link);
Emeric Brunc9437992021-02-12 19:42:55 +0100718 if (item->ar_item) {
719 pool_free(resolv_answer_item_pool, item->ar_item);
720 item->ar_item = NULL;
721 }
722 pool_free(resolv_answer_item_pool, item);
723 continue;
724 }
725
726 if (item->type != DNS_RTYPE_SRV)
727 continue;
728
729 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100730 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun34067662021-06-11 10:48:45 +0200731 struct ebpt_node *node;
732 char target[DNS_MAX_NAME_SIZE+1];
733
734 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100735 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
736 continue;
737
Emeric Brun34067662021-06-11 10:48:45 +0200738 /* Check if a server already uses that record */
739 srv = NULL;
740 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
741 if (srv->srvrq == srvrq) {
742 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
743 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100744 }
Emeric Brunc9437992021-02-12 19:42:55 +0100745 }
746
Emeric Brun34067662021-06-11 10:48:45 +0200747
748 /* If not empty we try to match a server
749 * in server state file tree with the same hostname
750 */
751 if (!eb_is_empty(&srvrq->named_servers)) {
752 srv = NULL;
753
754 /* convert the key to lookup in lower case */
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200755 for (i = 0 ; item->data.target[i] ; i++)
756 target[i] = tolower(item->data.target[i]);
Christopher Faulet1f923392021-07-22 14:29:26 +0200757 target[i] = 0;
Emeric Brun34067662021-06-11 10:48:45 +0200758
759 node = ebis_lookup(&srvrq->named_servers, target);
760 if (node) {
761 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100762 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun34067662021-06-11 10:48:45 +0200763
764 /* an entry was found with the same hostname
765 * let check this node if the port matches
766 * and try next node if the hostname
767 * is still the same
768 */
769 while (1) {
770 if (srv->svc_port == item->port) {
771 /* server found, we remove it from tree */
772 ebpt_delete(node);
Christopher Faulet73001ab2021-06-15 16:14:37 +0200773 ha_free(&srv->host_dn.key);
Emeric Brun34067662021-06-11 10:48:45 +0200774 goto srv_found;
775 }
776
777 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
778
779 node = ebpt_next(node);
780 if (!node)
781 break;
782
783 srv = ebpt_entry(node, struct server, host_dn);
784 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
785
786 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau75cc6532021-10-15 08:53:44 +0200787 || memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
Emeric Brun34067662021-06-11 10:48:45 +0200788 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
789 break;
790 }
791 }
Emeric Brunc9437992021-02-12 19:42:55 +0100792 }
793 }
Emeric Brun34067662021-06-11 10:48:45 +0200794
795 /* Pick the first server listed in srvrq (those ones don't
796 * have hostname and are free to use)
797 */
798 srv = NULL;
799 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
800 LIST_DEL_INIT(&srv->srv_rec_item);
801 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
802 goto srv_found;
803 }
804 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100805
Emeric Brun34067662021-06-11 10:48:45 +0200806srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100807 /* And update this server, if found (srv is locked here) */
808 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100809 /* re-enable DNS resolution for this server by default */
810 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Fauletdcac4182021-06-15 16:17:17 +0200811 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100812
Emeric Brunc9437992021-02-12 19:42:55 +0100813 /* Check if an Additional Record is associated to this SRV record.
814 * Perform some sanity checks too to ensure the record can be used.
815 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100816 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100817 */
818 if ((item->ar_item != NULL) &&
819 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100820 {
Emeric Brunc9437992021-02-12 19:42:55 +0100821
822 switch (item->ar_item->type) {
823 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200824 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100825 break;
826 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200827 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100828 break;
829 }
830
831 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100832
833 /* Unlink A/AAAA resolution for this server if there is an AR item.
834 * It is usless to perform an extra resolution
835 */
Willy Tarreau6878f802021-10-20 14:07:31 +0200836 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100837 }
838
839 if (!srv->hostname_dn) {
840 const char *msg = NULL;
Willy Tarreau85c15e62021-10-14 08:00:38 +0200841 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100842
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200843 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau85c15e62021-10-14 08:00:38 +0200844 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100845 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
846 continue;
847 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100848 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100849 if (msg)
850 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
851 }
852
Emeric Brun34067662021-06-11 10:48:45 +0200853 if (!LIST_INLIST(&srv->srv_rec_item))
854 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
855
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100856 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
857 /* If there is no AR item responsible of the FQDN resolution,
858 * trigger a dedicated DNS resolution
859 */
860 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
861 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
862 }
863
Christopher Fauletab177ac2021-03-10 15:34:52 +0100864 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100865 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100866
867 srv->svc_port = item->port;
868 srv->flags &= ~SRV_F_MAPPORTS;
869
870 if (!srv->resolv_opts.ignore_weight) {
871 char weight[9];
872 int ha_weight;
873
874 /* DNS weight range if from 0 to 65535
875 * HAProxy weight is from 0 to 256
876 * The rule below ensures that weight 0 is well respected
877 * while allowing a "mapping" from DNS weight into HAProxy's one.
878 */
879 ha_weight = (item->weight + 255) / 256;
880
881 snprintf(weight, sizeof(weight), "%d", ha_weight);
882 server_parse_weight_change_request(srv, weight);
883 }
884 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
885 }
886 }
887 }
888}
889
890/* Validates that the buffer DNS response provided in <resp> and finishing
891 * before <bufend> is valid from a DNS protocol point of view.
892 *
893 * The result is stored in <resolution>' response, buf_response,
894 * response_query_records and response_answer_records members.
895 *
896 * This function returns one of the RSLV_RESP_* code to indicate the type of
897 * error found.
898 */
899static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
900 struct resolv_resolution *resolution, int max_answer_records)
901{
902 unsigned char *reader;
903 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
904 int len, flags, offset;
Emeric Brunc9437992021-02-12 19:42:55 +0100905 int nb_saved_records;
906 struct resolv_query_item *query;
907 struct resolv_answer_item *answer_record, *tmp_record;
908 struct resolv_response *r_res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200909 struct eb32_node *eb32;
Willy Tarreaudcb696c2021-10-21 08:18:01 +0200910 uint32_t key = 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100911 int i, found = 0;
912 int cause = RSLV_RESP_ERROR;
913
914 reader = resp;
915 len = 0;
916 previous_dname = NULL;
917 query = NULL;
918 answer_record = NULL;
919
920 /* Initialization of response buffer and structure */
921 r_res = &resolution->response;
922
923 /* query id */
924 if (reader + 2 >= bufend)
925 goto invalid_resp;
926
927 r_res->header.id = reader[0] * 256 + reader[1];
928 reader += 2;
929
930 /* Flags and rcode are stored over 2 bytes
931 * First byte contains:
932 * - response flag (1 bit)
933 * - opcode (4 bits)
934 * - authoritative (1 bit)
935 * - truncated (1 bit)
936 * - recursion desired (1 bit)
937 */
938 if (reader + 2 >= bufend)
939 goto invalid_resp;
940
941 flags = reader[0] * 256 + reader[1];
942
943 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
944 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
945 cause = RSLV_RESP_NX_DOMAIN;
946 goto return_error;
947 }
948 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
949 cause = RSLV_RESP_REFUSED;
950 goto return_error;
951 }
952 else {
953 cause = RSLV_RESP_ERROR;
954 goto return_error;
955 }
956 }
957
958 /* Move forward 2 bytes for flags */
959 reader += 2;
960
961 /* 2 bytes for question count */
962 if (reader + 2 >= bufend)
963 goto invalid_resp;
964 r_res->header.qdcount = reader[0] * 256 + reader[1];
965 /* (for now) we send one query only, so we expect only one in the
966 * response too */
967 if (r_res->header.qdcount != 1) {
968 cause = RSLV_RESP_QUERY_COUNT_ERROR;
969 goto return_error;
970 }
971
972 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
973 goto invalid_resp;
974 reader += 2;
975
976 /* 2 bytes for answer count */
977 if (reader + 2 >= bufend)
978 goto invalid_resp;
979 r_res->header.ancount = reader[0] * 256 + reader[1];
980 if (r_res->header.ancount == 0) {
981 cause = RSLV_RESP_ANCOUNT_ZERO;
982 goto return_error;
983 }
984
985 /* Check if too many records are announced */
986 if (r_res->header.ancount > max_answer_records)
987 goto invalid_resp;
988 reader += 2;
989
990 /* 2 bytes authority count */
991 if (reader + 2 >= bufend)
992 goto invalid_resp;
993 r_res->header.nscount = reader[0] * 256 + reader[1];
994 reader += 2;
995
996 /* 2 bytes additional count */
997 if (reader + 2 >= bufend)
998 goto invalid_resp;
999 r_res->header.arcount = reader[0] * 256 + reader[1];
1000 reader += 2;
1001
Christopher Fauletc1699f82021-12-01 15:07:26 +01001002 /* Parsing dns queries. For now there is only one query and it exists
1003 * because (qdcount == 1).
1004 */
1005 query = &resolution->response_query_records[0];
Emeric Brunc9437992021-02-12 19:42:55 +01001006
Christopher Fauletc1699f82021-12-01 15:07:26 +01001007 /* Name is a NULL terminated string in our case, since we have
1008 * one query per response and the first one can't be compressed
1009 * (using the 0x0c format) */
1010 offset = 0;
1011 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01001012
Christopher Fauletc1699f82021-12-01 15:07:26 +01001013 if (len == 0)
1014 goto invalid_resp;
Emeric Brunc9437992021-02-12 19:42:55 +01001015
Christopher Fauletc1699f82021-12-01 15:07:26 +01001016 /* Now let's check the query's dname corresponds to the one we sent. */
1017 if (len != resolution->hostname_dn_len ||
1018 memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
1019 cause = RSLV_RESP_WRONG_NAME;
Christopher Fauletaf93d2f2021-12-02 10:05:02 +01001020 goto return_error;
Christopher Fauletc1699f82021-12-01 15:07:26 +01001021 }
Emeric Brunc9437992021-02-12 19:42:55 +01001022
Christopher Fauletc1699f82021-12-01 15:07:26 +01001023 reader += offset;
1024 previous_dname = query->name;
Emeric Brunc9437992021-02-12 19:42:55 +01001025
Christopher Fauletc1699f82021-12-01 15:07:26 +01001026 /* move forward 2 bytes for question type */
1027 if (reader + 2 >= bufend)
1028 goto invalid_resp;
1029 query->type = reader[0] * 256 + reader[1];
1030 reader += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001031
Christopher Fauletc1699f82021-12-01 15:07:26 +01001032 /* move forward 2 bytes for question class */
1033 if (reader + 2 >= bufend)
1034 goto invalid_resp;
1035 query->class = reader[0] * 256 + reader[1];
1036 reader += 2;
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001037
Emeric Brunc9437992021-02-12 19:42:55 +01001038 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001039 * because a TRUNCATED SRV query type response can still be exploited
1040 */
Emeric Brunc9437992021-02-12 19:42:55 +01001041 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1042 cause = RSLV_RESP_TRUNCATED;
1043 goto return_error;
1044 }
1045
1046 /* now parsing response records */
1047 nb_saved_records = 0;
1048 for (i = 0; i < r_res->header.ancount; i++) {
1049 if (reader >= bufend)
1050 goto invalid_resp;
1051
1052 answer_record = pool_alloc(resolv_answer_item_pool);
1053 if (answer_record == NULL)
1054 goto invalid_resp;
1055
1056 /* initialization */
1057 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001058 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001059 LIST_INIT(&answer_record->attached_servers);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001060 answer_record->link.node.leaf_p = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001061
1062 offset = 0;
1063 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1064
1065 if (len == 0)
1066 goto invalid_resp;
1067
1068 /* Check if the current record dname is valid. previous_dname
1069 * points either to queried dname or last CNAME target */
Willy Tarreau75cc6532021-10-15 08:53:44 +02001070 if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001071 if (i == 0) {
1072 /* First record, means a mismatch issue between
1073 * queried dname and dname found in the first
1074 * record */
1075 goto invalid_resp;
1076 }
1077 else {
1078 /* If not the first record, this means we have a
1079 * CNAME resolution error.
1080 */
1081 cause = RSLV_RESP_CNAME_ERROR;
1082 goto return_error;
1083 }
1084
1085 }
1086
1087 memcpy(answer_record->name, tmpname, len);
1088 answer_record->name[len] = 0;
1089
1090 reader += offset;
1091 if (reader >= bufend)
1092 goto invalid_resp;
1093
1094 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1095 if (reader + 2 > bufend)
1096 goto invalid_resp;
1097
1098 answer_record->type = reader[0] * 256 + reader[1];
1099 reader += 2;
1100
1101 /* 2 bytes for class (2) */
1102 if (reader + 2 > bufend)
1103 goto invalid_resp;
1104
1105 answer_record->class = reader[0] * 256 + reader[1];
1106 reader += 2;
1107
1108 /* 4 bytes for ttl (4) */
1109 if (reader + 4 > bufend)
1110 goto invalid_resp;
1111
1112 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1113 + reader[2] * 256 + reader[3];
1114 reader += 4;
1115
1116 /* Now reading data len */
1117 if (reader + 2 > bufend)
1118 goto invalid_resp;
1119
1120 answer_record->data_len = reader[0] * 256 + reader[1];
1121
1122 /* Move forward 2 bytes for data len */
1123 reader += 2;
1124
1125 if (reader + answer_record->data_len > bufend)
1126 goto invalid_resp;
1127
1128 /* Analyzing record content */
1129 switch (answer_record->type) {
1130 case DNS_RTYPE_A:
1131 /* ipv4 is stored on 4 bytes */
1132 if (answer_record->data_len != 4)
1133 goto invalid_resp;
1134
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001135 answer_record->data.in4.sin_family = AF_INET;
1136 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001137 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001138 break;
1139
1140 case DNS_RTYPE_CNAME:
1141 /* Check if this is the last record and update the caller about the status:
1142 * no IP could be found and last record was a CNAME. Could be triggered
1143 * by a wrong query type
1144 *
1145 * + 1 because answer_record_id starts at 0
1146 * while number of answers is an integer and
1147 * starts at 1.
1148 */
1149 if (i + 1 == r_res->header.ancount) {
1150 cause = RSLV_RESP_CNAME_ERROR;
1151 goto return_error;
1152 }
1153
1154 offset = 0;
1155 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1156 if (len == 0)
1157 goto invalid_resp;
1158
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001159 memcpy(answer_record->data.target, tmpname, len);
1160 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001161 key = XXH32(tmpname, len, answer_record->type);
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001162 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001163 break;
1164
1165
1166 case DNS_RTYPE_SRV:
1167 /* Answer must contain :
1168 * - 2 bytes for the priority
1169 * - 2 bytes for the weight
1170 * - 2 bytes for the port
1171 * - the target hostname
1172 */
1173 if (answer_record->data_len <= 6)
1174 goto invalid_resp;
1175
1176 answer_record->priority = read_n16(reader);
1177 reader += sizeof(uint16_t);
1178 answer_record->weight = read_n16(reader);
1179 reader += sizeof(uint16_t);
1180 answer_record->port = read_n16(reader);
1181 reader += sizeof(uint16_t);
1182 offset = 0;
1183 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1184 if (len == 0)
1185 goto invalid_resp;
1186
1187 answer_record->data_len = len;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001188 memcpy(answer_record->data.target, tmpname, len);
1189 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001190 key = XXH32(tmpname, len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001191 if (answer_record->ar_item != NULL) {
1192 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1193 answer_record->ar_item = NULL;
1194 }
1195 break;
1196
1197 case DNS_RTYPE_AAAA:
1198 /* ipv6 is stored on 16 bytes */
1199 if (answer_record->data_len != 16)
1200 goto invalid_resp;
1201
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001202 answer_record->data.in6.sin6_family = AF_INET6;
1203 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001204 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001205 break;
1206
1207 } /* switch (record type) */
1208
1209 /* Increment the counter for number of records saved into our
1210 * local response */
1211 nb_saved_records++;
1212
1213 /* Move forward answer_record->data_len for analyzing next
1214 * record in the response */
1215 reader += ((answer_record->type == DNS_RTYPE_SRV)
1216 ? offset
1217 : answer_record->data_len);
1218
1219 /* Lookup to see if we already had this entry */
1220 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001221
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001222 for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02001223 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001224 if (tmp_record->type != answer_record->type)
1225 continue;
1226
1227 switch(tmp_record->type) {
1228 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001229 if (!memcmp(&answer_record->data.in4.sin_addr,
1230 &tmp_record->data.in4.sin_addr,
1231 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001232 found = 1;
1233 break;
1234
1235 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001236 if (!memcmp(&answer_record->data.in6.sin6_addr,
1237 &tmp_record->data.in6.sin6_addr,
1238 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001239 found = 1;
1240 break;
1241
1242 case DNS_RTYPE_SRV:
1243 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001244 memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
Emeric Brunc9437992021-02-12 19:42:55 +01001245 answer_record->port == tmp_record->port) {
1246 tmp_record->weight = answer_record->weight;
1247 found = 1;
1248 }
1249 break;
1250
1251 default:
1252 break;
1253 }
1254
1255 if (found == 1)
1256 break;
1257 }
1258
1259 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001260 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001261 pool_free(resolv_answer_item_pool, answer_record);
1262 answer_record = NULL;
1263 }
1264 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001265 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001266 answer_record->ar_item = NULL;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001267 answer_record->link.key = key;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001268 eb32_insert(&r_res->answer_tree, &answer_record->link);
Emeric Brunc9437992021-02-12 19:42:55 +01001269 answer_record = NULL;
1270 }
1271 } /* for i 0 to ancount */
1272
1273 /* Save the number of records we really own */
1274 r_res->header.ancount = nb_saved_records;
1275
1276 /* now parsing additional records for SRV queries only */
1277 if (query->type != DNS_RTYPE_SRV)
1278 goto skip_parsing_additional_records;
1279
1280 /* if we find Authority records, just skip them */
1281 for (i = 0; i < r_res->header.nscount; i++) {
1282 offset = 0;
1283 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1284 &offset, 0);
1285 if (len == 0)
1286 continue;
1287
1288 if (reader + offset + 10 >= bufend)
1289 goto invalid_resp;
1290
1291 reader += offset;
1292 /* skip 2 bytes for class */
1293 reader += 2;
1294 /* skip 2 bytes for type */
1295 reader += 2;
1296 /* skip 4 bytes for ttl */
1297 reader += 4;
1298 /* read data len */
1299 len = reader[0] * 256 + reader[1];
1300 reader += 2;
1301
1302 if (reader + len >= bufend)
1303 goto invalid_resp;
1304
1305 reader += len;
1306 }
1307
1308 nb_saved_records = 0;
1309 for (i = 0; i < r_res->header.arcount; i++) {
1310 if (reader >= bufend)
1311 goto invalid_resp;
1312
1313 answer_record = pool_alloc(resolv_answer_item_pool);
1314 if (answer_record == NULL)
1315 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001316 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001317 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001318
1319 offset = 0;
1320 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1321
1322 if (len == 0) {
1323 pool_free(resolv_answer_item_pool, answer_record);
1324 answer_record = NULL;
1325 continue;
1326 }
1327
1328 memcpy(answer_record->name, tmpname, len);
1329 answer_record->name[len] = 0;
1330
1331 reader += offset;
1332 if (reader >= bufend)
1333 goto invalid_resp;
1334
1335 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1336 if (reader + 2 > bufend)
1337 goto invalid_resp;
1338
1339 answer_record->type = reader[0] * 256 + reader[1];
1340 reader += 2;
1341
1342 /* 2 bytes for class (2) */
1343 if (reader + 2 > bufend)
1344 goto invalid_resp;
1345
1346 answer_record->class = reader[0] * 256 + reader[1];
1347 reader += 2;
1348
1349 /* 4 bytes for ttl (4) */
1350 if (reader + 4 > bufend)
1351 goto invalid_resp;
1352
1353 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1354 + reader[2] * 256 + reader[3];
1355 reader += 4;
1356
1357 /* Now reading data len */
1358 if (reader + 2 > bufend)
1359 goto invalid_resp;
1360
1361 answer_record->data_len = reader[0] * 256 + reader[1];
1362
1363 /* Move forward 2 bytes for data len */
1364 reader += 2;
1365
1366 if (reader + answer_record->data_len > bufend)
1367 goto invalid_resp;
1368
1369 /* Analyzing record content */
1370 switch (answer_record->type) {
1371 case DNS_RTYPE_A:
1372 /* ipv4 is stored on 4 bytes */
1373 if (answer_record->data_len != 4)
1374 goto invalid_resp;
1375
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001376 answer_record->data.in4.sin_family = AF_INET;
1377 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001378 break;
1379
1380 case DNS_RTYPE_AAAA:
1381 /* ipv6 is stored on 16 bytes */
1382 if (answer_record->data_len != 16)
1383 goto invalid_resp;
1384
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001385 answer_record->data.in6.sin6_family = AF_INET6;
1386 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001387 break;
1388
1389 default:
1390 pool_free(resolv_answer_item_pool, answer_record);
1391 answer_record = NULL;
1392 continue;
1393
1394 } /* switch (record type) */
1395
1396 /* Increment the counter for number of records saved into our
1397 * local response */
1398 nb_saved_records++;
1399
1400 /* Move forward answer_record->data_len for analyzing next
1401 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001402 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001403
1404 /* Lookup to see if we already had this entry */
1405 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001406
1407 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001408 struct resolv_answer_item *ar_item;
1409
Willy Tarreau7893ae12021-10-21 07:39:57 +02001410 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Christopher Faulet77f86062021-03-10 15:19:57 +01001411 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1412 continue;
1413
1414 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001415 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001416 len != tmp_record->data_len ||
Willy Tarreau75cc6532021-10-15 08:53:44 +02001417 memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001418 continue;
1419
Christopher Faulet77f86062021-03-10 15:19:57 +01001420 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001421 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001422 if (!memcmp(&answer_record->data.in4.sin_addr,
1423 &ar_item->data.in4.sin_addr,
1424 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001425 found = 1;
1426 break;
1427
1428 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001429 if (!memcmp(&answer_record->data.in6.sin6_addr,
1430 &ar_item->data.in6.sin6_addr,
1431 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001432 found = 1;
1433 break;
1434
1435 default:
1436 break;
1437 }
1438
1439 if (found == 1)
1440 break;
1441 }
1442
1443 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001444 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001445 pool_free(resolv_answer_item_pool, answer_record);
1446 answer_record = NULL;
1447 }
1448 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001449 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001450 answer_record->ar_item = NULL;
1451
1452 // looking for the SRV record in the response list linked to this additional record
Willy Tarreau7893ae12021-10-21 07:39:57 +02001453 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
1454 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
1455
Emeric Brunc9437992021-02-12 19:42:55 +01001456 if (tmp_record->type == DNS_RTYPE_SRV &&
1457 tmp_record->ar_item == NULL &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001458 memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001459 /* Always use the received additional record to refresh info */
1460 if (tmp_record->ar_item)
1461 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1462 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001463 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001464 break;
1465 }
1466 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001467 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001468 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001469 answer_record = NULL;
1470 }
Emeric Brunc9437992021-02-12 19:42:55 +01001471 }
1472 } /* for i 0 to arcount */
1473
1474 skip_parsing_additional_records:
1475
1476 /* Save the number of records we really own */
1477 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001478 resolv_check_response(resolution);
1479 return RSLV_RESP_VALID;
1480
1481 invalid_resp:
1482 cause = RSLV_RESP_INVALID;
1483
1484 return_error:
1485 pool_free(resolv_answer_item_pool, answer_record);
1486 return cause;
1487}
1488
1489/* Searches dn_name resolution in resp.
1490 * If existing IP not found, return the first IP matching family_priority,
1491 * otherwise, first ip found
1492 * The following tasks are the responsibility of the caller:
1493 * - <r_res> contains an error free DNS response
1494 * For both cases above, resolv_validate_dns_response is required
1495 * returns one of the RSLV_UPD_* code
1496 */
1497int resolv_get_ip_from_response(struct resolv_response *r_res,
1498 struct resolv_options *resolv_opts, void *currentip,
1499 short currentip_sin_family,
1500 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001501 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001502{
Emeric Brunbd78c912021-06-11 10:08:05 +02001503 struct resolv_answer_item *record, *found_record = NULL;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001504 struct eb32_node *eb32;
Emeric Brunc9437992021-02-12 19:42:55 +01001505 int family_priority;
1506 int currentip_found;
1507 unsigned char *newip4, *newip6;
1508 int currentip_sel;
1509 int j;
1510 int score, max_score;
1511 int allowed_duplicated_ip;
1512
Emeric Brunbd78c912021-06-11 10:08:05 +02001513 /* srv is linked to an alive ip record */
1514 if (owner && LIST_INLIST(&owner->ip_rec_item))
1515 return RSLV_UPD_NO;
1516
Emeric Brunc9437992021-02-12 19:42:55 +01001517 family_priority = resolv_opts->family_prio;
1518 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1519 *newip = newip4 = newip6 = NULL;
1520 currentip_found = 0;
1521 *newip_sin_family = AF_UNSPEC;
1522 max_score = -1;
1523
1524 /* Select an IP regarding configuration preference.
1525 * Top priority is the preferred network ip version,
1526 * second priority is the preferred network.
1527 * the last priority is the currently used IP,
1528 *
1529 * For these three priorities, a score is calculated. The
1530 * weight are:
1531 * 8 - preferred ip version.
1532 * 4 - preferred network.
1533 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1534 * 1 - current ip.
1535 * The result with the biggest score is returned.
1536 */
1537
Willy Tarreau7893ae12021-10-21 07:39:57 +02001538 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001539 void *ip;
1540 unsigned char ip_type;
1541
Willy Tarreau7893ae12021-10-21 07:39:57 +02001542 record = eb32_entry(eb32, typeof(*record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001543 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001544 ip_type = AF_INET;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001545 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001546 }
1547 else if (record->type == DNS_RTYPE_AAAA) {
1548 ip_type = AF_INET6;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001549 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001550 }
1551 else
1552 continue;
1553 score = 0;
1554
1555 /* Check for preferred ip protocol. */
1556 if (ip_type == family_priority)
1557 score += 8;
1558
1559 /* Check for preferred network. */
1560 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1561
1562 /* Compare only the same addresses class. */
1563 if (resolv_opts->pref_net[j].family != ip_type)
1564 continue;
1565
1566 if ((ip_type == AF_INET &&
1567 in_net_ipv4(ip,
1568 &resolv_opts->pref_net[j].mask.in4,
1569 &resolv_opts->pref_net[j].addr.in4)) ||
1570 (ip_type == AF_INET6 &&
1571 in_net_ipv6(ip,
1572 &resolv_opts->pref_net[j].mask.in6,
1573 &resolv_opts->pref_net[j].addr.in6))) {
1574 score += 4;
1575 break;
1576 }
1577 }
1578
1579 /* Check if the IP found in the record is already affected to a
1580 * member of a group. If not, the score should be incremented
1581 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001582 if (owner) {
1583 struct server *srv;
1584 int already_used = 0;
1585
1586 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1587 if (srv == owner)
1588 continue;
1589 if (srv->proxy == owner->proxy) {
1590 already_used = 1;
1591 break;
1592 }
1593 }
1594 if (already_used) {
1595 if (!allowed_duplicated_ip) {
1596 continue;
1597 }
1598 }
1599 else {
1600 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001601 }
1602 } else {
1603 score += 2;
1604 }
1605
1606 /* Check for current ip matching. */
1607 if (ip_type == currentip_sin_family &&
1608 ((currentip_sin_family == AF_INET &&
1609 !memcmp(ip, currentip, 4)) ||
1610 (currentip_sin_family == AF_INET6 &&
1611 !memcmp(ip, currentip, 16)))) {
1612 score++;
1613 currentip_sel = 1;
1614 }
1615 else
1616 currentip_sel = 0;
1617
1618 /* Keep the address if the score is better than the previous
1619 * score. The maximum score is 15, if this value is reached, we
1620 * break the parsing. Implicitly, this score is reached the ip
1621 * selected is the current ip. */
1622 if (score > max_score) {
1623 if (ip_type == AF_INET)
1624 newip4 = ip;
1625 else
1626 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001627 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001628 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001629 if (score == 15) {
1630 /* this was not registered on the current record but it matches
1631 * let's fix it (it may comes from state file */
1632 if (owner)
1633 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001634 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001635 }
Emeric Brunc9437992021-02-12 19:42:55 +01001636 max_score = score;
1637 }
1638 } /* list for each record entries */
1639
1640 /* No IP found in the response */
1641 if (!newip4 && !newip6)
1642 return RSLV_UPD_NO_IP_FOUND;
1643
1644 /* Case when the caller looks first for an IPv4 address */
1645 if (family_priority == AF_INET) {
1646 if (newip4) {
1647 *newip = newip4;
1648 *newip_sin_family = AF_INET;
1649 }
1650 else if (newip6) {
1651 *newip = newip6;
1652 *newip_sin_family = AF_INET6;
1653 }
Emeric Brunc9437992021-02-12 19:42:55 +01001654 }
1655 /* Case when the caller looks first for an IPv6 address */
1656 else if (family_priority == AF_INET6) {
1657 if (newip6) {
1658 *newip = newip6;
1659 *newip_sin_family = AF_INET6;
1660 }
1661 else if (newip4) {
1662 *newip = newip4;
1663 *newip_sin_family = AF_INET;
1664 }
Emeric Brunc9437992021-02-12 19:42:55 +01001665 }
1666 /* Case when the caller have no preference (we prefer IPv6) */
1667 else if (family_priority == AF_UNSPEC) {
1668 if (newip6) {
1669 *newip = newip6;
1670 *newip_sin_family = AF_INET6;
1671 }
1672 else if (newip4) {
1673 *newip = newip4;
1674 *newip_sin_family = AF_INET;
1675 }
Emeric Brunc9437992021-02-12 19:42:55 +01001676 }
1677
Emeric Brunbd78c912021-06-11 10:08:05 +02001678 /* the ip of this record was chosen for the server */
1679 if (owner && found_record) {
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001680 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunbd78c912021-06-11 10:08:05 +02001681 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1682 }
1683
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001684 eb32 = eb32_first(&r_res->answer_tree);
1685 if (eb32) {
Emeric Brunc9437992021-02-12 19:42:55 +01001686 /* Move the first record to the end of the list, for internal
Willy Tarreau7893ae12021-10-21 07:39:57 +02001687 * round robin.
1688 */
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001689 eb32_delete(eb32);
1690 eb32_insert(&r_res->answer_tree, eb32);
Emeric Brunc9437992021-02-12 19:42:55 +01001691 }
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001692
1693 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001694}
1695
Willy Tarreau875ee702021-10-14 08:05:25 +02001696/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001697 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001698 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1699 * null-terminated. <str> must be allocated large enough to contain a full host
1700 * name plus the trailing zero, and the allocated size must be passed in
1701 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001702 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001703 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001704 * <str> (including the terminating null byte).
1705 */
1706int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1707{
1708 char *ptr;
1709 int i, sz;
1710
Willy Tarreau875ee702021-10-14 08:05:25 +02001711 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001712 return -1;
1713
1714 ptr = str;
Willy Tarreau875ee702021-10-14 08:05:25 +02001715 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001716 sz = dn[i];
1717 if (i)
1718 *ptr++ = '.';
Willy Tarreau814889c2021-10-15 07:45:38 +02001719 /* copy the string at i+1 to lower case */
1720 for (; sz > 0; sz--)
1721 *(ptr++) = tolower(dn[++i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001722 }
1723 *ptr++ = '\0';
1724 return (ptr - str);
1725}
1726
1727/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1728 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001729 * <str> contains the input string that is <str_len> bytes long (trailing zero
1730 * not needed). <dn> buffer must be allocated large enough to contain the
1731 * encoded string and a trailing zero, so it must be at least str_len+2, and
1732 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001733 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001734 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001735 * <dn> (excluding the terminating null byte).
1736 */
1737int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1738{
1739 int i, offset;
1740
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001741 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001742 return -1;
1743
1744 /* First byte of dn will be used to store the length of the first
1745 * label */
1746 offset = 0;
1747 for (i = 0; i < str_len; ++i) {
1748 if (str[i] == '.') {
1749 /* 2 or more consecutive dots is invalid */
1750 if (i == offset)
1751 return -1;
1752
1753 /* ignore trailing dot */
Christopher Faulet0a82cf42022-01-28 17:47:57 +01001754 if (i + 1 == str_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001755 break;
Emeric Brunc9437992021-02-12 19:42:55 +01001756
1757 dn[offset] = (i - offset);
1758 offset = i+1;
1759 continue;
1760 }
Willy Tarreau814889c2021-10-15 07:45:38 +02001761 dn[i+1] = tolower(str[i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001762 }
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001763 dn[offset] = i - offset;
Willy Tarreau7b232f12021-10-15 08:09:25 +02001764 dn[i+1] = '\0';
1765 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001766}
1767
1768/* Validates host name:
1769 * - total size
1770 * - each label size individually
1771 * returns:
1772 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1773 * 1 when no error. <err> is left unaffected.
1774 */
1775int resolv_hostname_validation(const char *string, char **err)
1776{
1777 int i;
1778
1779 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1780 if (err)
1781 *err = DNS_TOO_LONG_FQDN;
1782 return 0;
1783 }
1784
1785 while (*string) {
1786 i = 0;
1787 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1788 if (!(*string == '-' || *string == '_' ||
1789 (*string >= 'a' && *string <= 'z') ||
1790 (*string >= 'A' && *string <= 'Z') ||
1791 (*string >= '0' && *string <= '9'))) {
1792 if (err)
1793 *err = DNS_INVALID_CHARACTER;
1794 return 0;
1795 }
1796 i++;
1797 string++;
1798 }
1799
1800 if (!(*string))
1801 break;
1802
1803 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1804 if (err)
1805 *err = DNS_LABEL_TOO_LONG;
1806 return 0;
1807 }
1808
1809 string++;
1810 }
1811 return 1;
1812}
1813
1814/* Picks up an available resolution from the different resolution list
1815 * associated to a resolvers section, in this order:
1816 * 1. check in resolutions.curr for the same hostname and query_type
1817 * 2. check in resolutions.wait for the same hostname and query_type
1818 * 3. Get a new resolution from resolution pool
1819 *
1820 * Returns an available resolution, NULL if none found.
1821 */
1822static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1823 char **hostname_dn, int hostname_dn_len,
1824 int query_type)
1825{
1826 struct resolv_resolution *res;
1827
1828 if (!*hostname_dn)
1829 goto from_pool;
1830
1831 /* Search for same hostname and query type in resolutions.curr */
1832 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1833 if (!res->hostname_dn)
1834 continue;
1835 if ((query_type == res->prefered_query_type) &&
1836 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001837 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001838 return res;
1839 }
1840
1841 /* Search for same hostname and query type in resolutions.wait */
1842 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1843 if (!res->hostname_dn)
1844 continue;
1845 if ((query_type == res->prefered_query_type) &&
1846 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001847 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001848 return res;
1849 }
1850
1851 from_pool:
1852 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001853 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001854 if (res) {
Emeric Brunc9437992021-02-12 19:42:55 +01001855 res->resolvers = resolvers;
1856 res->uuid = resolution_uuid;
1857 res->status = RSLV_STATUS_NONE;
1858 res->step = RSLV_STEP_NONE;
1859 res->last_valid = now_ms;
1860
1861 LIST_INIT(&res->requesters);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001862 res->response.answer_tree = EB_ROOT;
Emeric Brunc9437992021-02-12 19:42:55 +01001863
1864 res->prefered_query_type = query_type;
1865 res->query_type = query_type;
1866 res->hostname_dn = *hostname_dn;
1867 res->hostname_dn_len = hostname_dn_len;
1868
1869 ++resolution_uuid;
1870
1871 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001872 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001873 }
1874 return res;
1875}
1876
Willy Tarreau2acc1602021-10-19 11:16:11 +02001877/* deletes and frees all answer_items from the resolution's answer_list */
1878static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001879{
Willy Tarreau7893ae12021-10-21 07:39:57 +02001880 struct eb32_node *eb32, *eb32_back;
1881 struct resolv_answer_item *item;
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001882
Willy Tarreau7893ae12021-10-21 07:39:57 +02001883 for (eb32 = eb32_first(&resolution->response.answer_tree);
1884 eb32 && (eb32_back = eb32_next(eb32), 1);
1885 eb32 = eb32_back) {
1886 item = eb32_entry(eb32, typeof(*item), link);
1887 eb32_delete(&item->link);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001888 pool_free(resolv_answer_item_pool, item->ar_item);
1889 pool_free(resolv_answer_item_pool, item);
1890 }
1891}
1892
Emeric Brunc9437992021-02-12 19:42:55 +01001893/* Releases a resolution from its requester(s) and move it back to the pool */
1894static void resolv_free_resolution(struct resolv_resolution *resolution)
1895{
1896 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001897
1898 /* clean up configuration */
1899 resolv_reset_resolution(resolution);
1900 resolution->hostname_dn = NULL;
1901 resolution->hostname_dn_len = 0;
1902
1903 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02001904 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001905 req->resolution = NULL;
1906 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001907 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau25e01092021-10-19 11:17:33 +02001908
Willy Tarreauaae73202021-10-19 22:01:36 +02001909 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001910 pool_free(resolv_resolution_pool, resolution);
1911}
1912
Willy Tarreau239675e2021-10-19 11:59:25 +02001913/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1914 * and makes it owned by this obj_type, with the proposed callback and error
1915 * callback. On success, *req is assigned the allocated requester. Returns
1916 * NULL on allocation failure.
1917 */
1918static struct resolv_requester *
1919resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1920 int (*cb)(struct resolv_requester *, struct dns_counters *),
1921 int (*err_cb)(struct resolv_requester *, int))
1922{
1923 struct resolv_requester *tmp;
1924
1925 if (*req)
1926 return *req;
1927
1928 tmp = pool_alloc(resolv_requester_pool);
1929 if (!tmp)
1930 goto end;
1931
1932 LIST_INIT(&tmp->list);
1933 tmp->owner = owner;
1934 tmp->resolution = NULL;
1935 tmp->requester_cb = cb;
1936 tmp->requester_error_cb = err_cb;
1937 *req = tmp;
1938 end:
1939 return tmp;
1940}
1941
Emeric Brunc9437992021-02-12 19:42:55 +01001942/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001943 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001944 */
1945int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1946{
1947 struct resolv_resolution *res = NULL;
1948 struct resolv_requester *req;
1949 struct resolvers *resolvers;
1950 struct server *srv = NULL;
1951 struct resolv_srvrq *srvrq = NULL;
1952 struct stream *stream = NULL;
1953 char **hostname_dn;
1954 int hostname_dn_len, query_type;
1955
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001956 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001957 switch (requester_type) {
1958 case OBJ_TYPE_SERVER:
1959 srv = (struct server *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001960
1961 if (!requester_locked)
1962 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1963
1964 req = resolv_get_requester(&srv->resolv_requester,
1965 &srv->obj_type,
1966 snr_resolution_cb,
1967 snr_resolution_error_cb);
1968
1969 if (!requester_locked)
1970 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1971
1972 if (!req)
1973 goto err;
1974
Emeric Brunc9437992021-02-12 19:42:55 +01001975 hostname_dn = &srv->hostname_dn;
1976 hostname_dn_len = srv->hostname_dn_len;
1977 resolvers = srv->resolvers;
1978 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1979 ? DNS_RTYPE_A
1980 : DNS_RTYPE_AAAA);
1981 break;
1982
1983 case OBJ_TYPE_SRVRQ:
1984 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001985
1986 req = resolv_get_requester(&srvrq->requester,
1987 &srvrq->obj_type,
1988 snr_resolution_cb,
1989 srvrq_resolution_error_cb);
1990 if (!req)
1991 goto err;
1992
Emeric Brunc9437992021-02-12 19:42:55 +01001993 hostname_dn = &srvrq->hostname_dn;
1994 hostname_dn_len = srvrq->hostname_dn_len;
1995 resolvers = srvrq->resolvers;
1996 query_type = DNS_RTYPE_SRV;
1997 break;
1998
1999 case OBJ_TYPE_STREAM:
2000 stream = (struct stream *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02002001
2002 req = resolv_get_requester(&stream->resolv_ctx.requester,
2003 &stream->obj_type,
2004 act_resolution_cb,
2005 act_resolution_error_cb);
2006 if (!req)
2007 goto err;
2008
Emeric Brunc9437992021-02-12 19:42:55 +01002009 hostname_dn = &stream->resolv_ctx.hostname_dn;
2010 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2011 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2012 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2013 ? DNS_RTYPE_A
2014 : DNS_RTYPE_AAAA);
2015 break;
2016 default:
2017 goto err;
2018 }
2019
2020 /* Get a resolution from the resolvers' wait queue or pool */
2021 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2022 goto err;
2023
Willy Tarreau239675e2021-10-19 11:59:25 +02002024 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002025
Willy Tarreau2b718102021-04-21 07:32:39 +02002026 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002027 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002028 return 0;
2029
2030 err:
2031 if (res && LIST_ISEMPTY(&res->requesters))
2032 resolv_free_resolution(res);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002033 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002034 return -1;
2035}
2036
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002037/* This function removes all server/srvrq references on answer items. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002038void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun34067662021-06-11 10:48:45 +02002039{
Willy Tarreau7893ae12021-10-21 07:39:57 +02002040 struct eb32_node *eb32, *eb32_back;
2041 struct resolv_answer_item *item;
Emeric Brun34067662021-06-11 10:48:45 +02002042 struct server *srv, *srvback;
2043 struct resolv_srvrq *srvrq;
2044
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002045 enter_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002046 if ((srv = objt_server(req->owner)) != NULL) {
2047 LIST_DEL_INIT(&srv->ip_rec_item);
2048 }
2049 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02002050 for (eb32 = eb32_first(&res->response.answer_tree);
2051 eb32 && (eb32_back = eb32_next(eb32), 1);
2052 eb32 = eb32_back) {
2053 item = eb32_entry(eb32, typeof(*item), link);
Emeric Brun34067662021-06-11 10:48:45 +02002054 if (item->type == DNS_RTYPE_SRV) {
2055 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet11c6c392021-06-15 16:08:48 +02002056 if (srv->srvrq == srvrq)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002057 resolv_srvrq_cleanup_srv(srv);
Emeric Brun34067662021-06-11 10:48:45 +02002058 }
2059 }
2060 }
2061 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002062 leave_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002063}
2064
Emeric Brunc9437992021-02-12 19:42:55 +01002065/* Removes a requester from a DNS resolution. It takes takes care of all the
2066 * consequences. It also cleans up some parameters from the requester.
2067 */
Willy Tarreau6878f802021-10-20 14:07:31 +02002068static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002069{
2070 struct resolv_resolution *res;
2071 struct resolv_requester *req;
2072
2073 /* Nothing to do */
2074 if (!requester || !requester->resolution)
2075 return;
2076 res = requester->resolution;
2077
2078 /* Clean up the requester */
Willy Tarreauaae73202021-10-19 22:01:36 +02002079 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002080 requester->resolution = NULL;
2081
Christopher Fauletbce6db62021-10-29 10:38:15 +02002082 /* remove ref from the resolution answer item list to the requester */
2083 resolv_detach_from_resolution_answer_items(res, requester);
2084
Emeric Brunc9437992021-02-12 19:42:55 +01002085 /* We need to find another requester linked on this resolution */
2086 if (!LIST_ISEMPTY(&res->requesters))
2087 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2088 else {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002089 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002090 return;
2091 }
2092
2093 /* Move hostname_dn related pointers to the next requester */
2094 switch (obj_type(req->owner)) {
2095 case OBJ_TYPE_SERVER:
2096 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2097 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2098 break;
2099 case OBJ_TYPE_SRVRQ:
2100 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2101 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2102 break;
2103 case OBJ_TYPE_STREAM:
2104 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2105 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2106 break;
2107 default:
2108 res->hostname_dn = NULL;
2109 res->hostname_dn_len = 0;
2110 break;
2111 }
2112}
2113
Willy Tarreauf766ec62021-10-18 16:46:38 +02002114/* The public version of the function above that deals with the death row. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002115void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002116{
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002117 enter_resolver_code();
Willy Tarreau6878f802021-10-20 14:07:31 +02002118 _resolv_unlink_resolution(requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002119 leave_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002120}
2121
Emeric Brunc9437992021-02-12 19:42:55 +01002122/* Called when a network IO is generated on a name server socket for an incoming
2123 * packet. It performs the following actions:
2124 * - check if the packet requires processing (not outdated resolution)
2125 * - ensure the DNS packet received is valid and call requester's callback
2126 * - call requester's error callback if invalid response
2127 * - check the dn_name in the packet against the one sent
2128 */
2129static int resolv_process_responses(struct dns_nameserver *ns)
2130{
2131 struct dns_counters *tmpcounters;
2132 struct resolvers *resolvers;
2133 struct resolv_resolution *res;
Emeric Brunc9437992021-02-12 19:42:55 +01002134 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2135 unsigned char *bufend;
2136 int buflen, dns_resp;
2137 int max_answer_records;
2138 unsigned short query_id;
2139 struct eb32_node *eb;
2140 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002141 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002142
2143 resolvers = ns->parent;
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002144 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002145 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2146
2147 /* process all pending input messages */
2148 while (1) {
2149 /* read message received */
2150 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2151 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2152 break;
2153 }
2154
2155 /* message too big */
2156 if (buflen > resolvers->accepted_payload_size) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002157 ns->counters->app.resolver.too_big++;
Emeric Brunc9437992021-02-12 19:42:55 +01002158 continue;
2159 }
2160
2161 /* initializing variables */
2162 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2163
2164 /* read the query id from the packet (16 bits) */
2165 if (buf + 2 > bufend) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002166 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002167 continue;
2168 }
2169 query_id = resolv_response_get_query_id(buf);
2170
2171 /* search the query_id in the pending resolution tree */
2172 eb = eb32_lookup(&resolvers->query_ids, query_id);
2173 if (eb == NULL) {
2174 /* unknown query id means an outdated response and can be safely ignored */
Emeric Brund174f0e2021-10-29 17:30:41 +02002175 ns->counters->app.resolver.outdated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002176 continue;
2177 }
2178
2179 /* known query id means a resolution in progress */
2180 res = eb32_entry(eb, struct resolv_resolution, qid);
2181 /* number of responses received */
2182 res->nb_responses++;
2183
2184 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2185 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2186
2187 switch (dns_resp) {
2188 case RSLV_RESP_VALID:
2189 break;
2190
2191 case RSLV_RESP_INVALID:
2192 case RSLV_RESP_QUERY_COUNT_ERROR:
2193 case RSLV_RESP_WRONG_NAME:
2194 res->status = RSLV_STATUS_INVALID;
Emeric Brund174f0e2021-10-29 17:30:41 +02002195 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002196 break;
2197
2198 case RSLV_RESP_NX_DOMAIN:
2199 res->status = RSLV_STATUS_NX;
Emeric Brund174f0e2021-10-29 17:30:41 +02002200 ns->counters->app.resolver.nx++;
Emeric Brunc9437992021-02-12 19:42:55 +01002201 break;
2202
2203 case RSLV_RESP_REFUSED:
2204 res->status = RSLV_STATUS_REFUSED;
Emeric Brund174f0e2021-10-29 17:30:41 +02002205 ns->counters->app.resolver.refused++;
Emeric Brunc9437992021-02-12 19:42:55 +01002206 break;
2207
2208 case RSLV_RESP_ANCOUNT_ZERO:
2209 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002210 ns->counters->app.resolver.any_err++;
Emeric Brunc9437992021-02-12 19:42:55 +01002211 break;
2212
2213 case RSLV_RESP_CNAME_ERROR:
2214 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002215 ns->counters->app.resolver.cname_error++;
Emeric Brunc9437992021-02-12 19:42:55 +01002216 break;
2217
2218 case RSLV_RESP_TRUNCATED:
2219 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002220 ns->counters->app.resolver.truncated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002221 break;
2222
2223 case RSLV_RESP_NO_EXPECTED_RECORD:
2224 case RSLV_RESP_ERROR:
2225 case RSLV_RESP_INTERNAL:
2226 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002227 ns->counters->app.resolver.other++;
Emeric Brunc9437992021-02-12 19:42:55 +01002228 break;
2229 }
2230
2231 /* Wait all nameservers response to handle errors */
2232 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2233 continue;
2234
2235 /* Process error codes */
2236 if (dns_resp != RSLV_RESP_VALID) {
2237 if (res->prefered_query_type != res->query_type) {
2238 /* The fallback on the query type was already performed,
2239 * so check the try counter. If it falls to 0, we can
2240 * report an error. Else, wait the next attempt. */
2241 if (!res->try)
2242 goto report_res_error;
2243 }
2244 else {
2245 /* Fallback from A to AAAA or the opposite and re-send
2246 * the resolution immediately. try counter is not
2247 * decremented. */
2248 if (res->prefered_query_type == DNS_RTYPE_A) {
2249 res->query_type = DNS_RTYPE_AAAA;
2250 resolv_send_query(res);
2251 }
2252 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2253 res->query_type = DNS_RTYPE_A;
2254 resolv_send_query(res);
2255 }
2256 }
2257 continue;
2258 }
2259
Emeric Brunc9437992021-02-12 19:42:55 +01002260 /* So the resolution succeeded */
2261 res->status = RSLV_STATUS_VALID;
2262 res->last_valid = now_ms;
Emeric Brund174f0e2021-10-29 17:30:41 +02002263 ns->counters->app.resolver.valid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002264 goto report_res_success;
2265
2266 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002267 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002268 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002269 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2270 if (!keep_answer_items)
2271 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002272 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002273 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002274 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002275 continue;
2276
2277 report_res_success:
2278 /* Only the 1rst requester s managed by the server, others are
2279 * from the cache */
2280 tmpcounters = ns->counters;
2281 list_for_each_entry(req, &res->requesters, list) {
2282 struct server *s = objt_server(req->owner);
2283
2284 if (s)
2285 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2286 req->requester_cb(req, tmpcounters);
2287 if (s)
2288 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2289 tmpcounters = NULL;
2290 }
2291
2292 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002293 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002294 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002295 continue;
2296 }
2297 resolv_update_resolvers_timeout(resolvers);
2298 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002299 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002300 return buflen;
2301}
2302
2303/* Processes DNS resolution. First, it checks the active list to detect expired
2304 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2305 * checks the wait list to trigger new resolutions.
2306 */
Willy Tarreau0fbc16c2022-09-08 15:07:13 +02002307struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002308{
2309 struct resolvers *resolvers = context;
2310 struct resolv_resolution *res, *resback;
2311 int exp;
2312
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002313 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002314 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2315
Willy Tarreauf766ec62021-10-18 16:46:38 +02002316 /* Handle all expired resolutions from the active list. Elements that
2317 * need to be removed will in fact be moved to the death_row. Other
2318 * ones will be handled normally.
2319 */
2320
Willy Tarreauf766ec62021-10-18 16:46:38 +02002321 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2322 while (&res->list != &resolvers->resolutions.curr) {
2323 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2324
Christopher Faulet0efc0992021-03-11 18:09:53 +01002325 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002326 abort_resolution(res);
2327 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002328 continue;
2329 }
2330
Emeric Brunc9437992021-02-12 19:42:55 +01002331 /* When we find the first resolution in the future, then we can
2332 * stop here */
2333 exp = tick_add(res->last_query, resolvers->timeout.retry);
2334 if (!tick_is_expired(exp, now_ms))
2335 break;
2336
2337 /* If current resolution has been tried too many times and
2338 * finishes in timeout we update its status and remove it from
2339 * the list */
2340 if (!res->try) {
2341 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002342 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002343
2344 /* Notify the result to the requesters */
2345 if (!res->nb_responses)
2346 res->status = RSLV_STATUS_TIMEOUT;
2347 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002348 keep_answer_items |= req->requester_error_cb(req, res->status);
2349 if (!keep_answer_items)
2350 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002351
2352 /* Clean up resolution info and remove it from the
2353 * current list */
2354 resolv_reset_resolution(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002355
2356 /* subsequent entries might have been deleted here */
2357 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreauaae73202021-10-19 22:01:36 +02002358 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002359 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002360 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002361 }
2362 else {
2363 /* Otherwise resend the DNS query and requeue the resolution */
2364 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2365 /* No response received (a real timeout) or fallback already done */
2366 res->query_type = res->prefered_query_type;
2367 res->try--;
2368 }
2369 else {
2370 /* Fallback from A to AAAA or the opposite and re-send
2371 * the resolution immediately. try counter is not
2372 * decremented. */
2373 if (res->prefered_query_type == DNS_RTYPE_A)
2374 res->query_type = DNS_RTYPE_AAAA;
2375 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2376 res->query_type = DNS_RTYPE_A;
2377 else
2378 res->try--;
2379 }
2380 resolv_send_query(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002381 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2382 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002383 }
2384 }
2385
2386 /* Handle all resolutions in the wait list */
2387 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002388 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002389 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002390 continue;
2391 }
2392
Emeric Brunc9437992021-02-12 19:42:55 +01002393 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2394 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2395 continue;
2396
2397 if (resolv_run_resolution(res) != 1) {
2398 res->last_resolution = now_ms;
Willy Tarreauaae73202021-10-19 22:01:36 +02002399 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002400 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002401 }
2402 }
Emeric Brunc9437992021-02-12 19:42:55 +01002403 resolv_update_resolvers_timeout(resolvers);
2404 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002405
2406 /* now we can purge all queued deletions */
2407 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002408 return t;
2409}
2410
William Lallemande606c842022-07-18 14:09:58 +02002411
2412/* destroy a resolvers */
2413static void resolvers_destroy(struct resolvers *resolvers)
Emeric Brunc9437992021-02-12 19:42:55 +01002414{
Emeric Brunc9437992021-02-12 19:42:55 +01002415 struct dns_nameserver *ns, *nsback;
2416 struct resolv_resolution *res, *resback;
2417 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01002418
William Lallemande606c842022-07-18 14:09:58 +02002419 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2420 free(ns->id);
2421 free((char *)ns->conf.file);
2422 if (ns->dgram) {
2423 if (ns->dgram->conn.t.sock.fd != -1) {
2424 fd_delete(ns->dgram->conn.t.sock.fd);
2425 close(ns->dgram->conn.t.sock.fd);
Emeric Brun56fc5d92021-02-12 20:05:45 +01002426 }
William Lallemande606c842022-07-18 14:09:58 +02002427 if (ns->dgram->ring_req)
2428 ring_free(ns->dgram->ring_req);
2429 free(ns->dgram);
Emeric Brunc9437992021-02-12 19:42:55 +01002430 }
William Lallemande606c842022-07-18 14:09:58 +02002431 if (ns->stream) {
2432 if (ns->stream->ring_req)
2433 ring_free(ns->stream->ring_req);
2434 if (ns->stream->task_req)
2435 task_destroy(ns->stream->task_req);
2436 if (ns->stream->task_rsp)
2437 task_destroy(ns->stream->task_rsp);
2438 free(ns->stream);
2439 }
2440 LIST_DEL_INIT(&ns->list);
2441 EXTRA_COUNTERS_FREE(ns->extra_counters);
2442 free(ns);
2443 }
Emeric Brunc9437992021-02-12 19:42:55 +01002444
William Lallemande606c842022-07-18 14:09:58 +02002445 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2446 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2447 LIST_DEL_INIT(&req->list);
2448 pool_free(resolv_requester_pool, req);
Emeric Brunc9437992021-02-12 19:42:55 +01002449 }
William Lallemande606c842022-07-18 14:09:58 +02002450 resolv_free_resolution(res);
2451 }
Emeric Brunc9437992021-02-12 19:42:55 +01002452
William Lallemande606c842022-07-18 14:09:58 +02002453 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2454 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2455 LIST_DEL_INIT(&req->list);
2456 pool_free(resolv_requester_pool, req);
Emeric Brunc9437992021-02-12 19:42:55 +01002457 }
William Lallemande606c842022-07-18 14:09:58 +02002458 resolv_free_resolution(res);
2459 }
Emeric Brunc9437992021-02-12 19:42:55 +01002460
William Lallemande606c842022-07-18 14:09:58 +02002461 free_proxy(resolvers->px);
2462 free(resolvers->id);
2463 free((char *)resolvers->conf.file);
2464 task_destroy(resolvers->t);
2465 LIST_DEL_INIT(&resolvers->list);
2466 free(resolvers);
2467}
2468
2469/* Release memory allocated by DNS */
2470static void resolvers_deinit(void)
2471{
2472 struct resolvers *resolvers, *resolversback;
2473 struct resolv_srvrq *srvrq, *srvrqback;
2474
2475 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2476 resolvers_destroy(resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01002477 }
2478
2479 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2480 free(srvrq->name);
2481 free(srvrq->hostname_dn);
Willy Tarreauaae73202021-10-19 22:01:36 +02002482 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002483 free(srvrq);
2484 }
2485}
2486
2487/* Finalizes the DNS configuration by allocating required resources and checking
2488 * live parameters.
William Lallemand866b88b2022-08-24 09:58:31 +02002489 * Returns 0 on success, 1 on error.
Emeric Brunc9437992021-02-12 19:42:55 +01002490 */
2491static int resolvers_finalize_config(void)
2492{
2493 struct resolvers *resolvers;
2494 struct proxy *px;
2495 int err_code = 0;
2496
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002497 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002498
Emeric Brunc9437992021-02-12 19:42:55 +01002499 /* allocate pool of resolution per resolvers */
2500 list_for_each_entry(resolvers, &sec_resolvers, list) {
2501 struct dns_nameserver *ns;
2502 struct task *t;
2503
2504 /* Check if we can create the socket with nameservers info */
2505 list_for_each_entry(ns, &resolvers->nameservers, list) {
2506 int fd;
2507
2508 if (ns->dgram) {
2509 /* Check nameserver info */
2510 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002511 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002512 resolvers->id, ns->id);
2513 err_code |= (ERR_ALERT|ERR_ABORT);
2514 continue;
2515 }
2516 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
William Lallemandb10b1192022-08-24 14:50:32 +02002517 if (!resolvers->conf.implicit) { /* emit a warning only if it was configured manually */
2518 ha_warning("resolvers '%s': can't connect socket for nameserver '%s'.\n",
2519 resolvers->id, ns->id);
2520 }
Emeric Brunc9437992021-02-12 19:42:55 +01002521 close(fd);
William Lallemandc31577f2022-07-26 10:50:09 +02002522 err_code |= ERR_WARN;
Emeric Brunc9437992021-02-12 19:42:55 +01002523 continue;
2524 }
2525 close(fd);
2526 }
2527 }
2528
2529 /* Create the task associated to the resolvers section */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002530 if ((t = task_new_anywhere()) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002531 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002532 err_code |= (ERR_ALERT|ERR_ABORT);
2533 goto err;
2534 }
2535
2536 /* Update task's parameters */
2537 t->process = process_resolvers;
2538 t->context = resolvers;
2539 resolvers->t = t;
2540 task_wakeup(t, TASK_WOKEN_INIT);
2541 }
2542
2543 for (px = proxies_list; px; px = px->next) {
2544 struct server *srv;
2545
Willy Tarreau9b46fb42022-06-10 11:11:44 +02002546 if (px->flags & PR_FL_DISABLED) {
2547 /* must not run and will not work anyway since
2548 * nothing in the proxy is initialized.
2549 */
2550 continue;
2551 }
2552
Emeric Brunc9437992021-02-12 19:42:55 +01002553 for (srv = px->srv; srv; srv = srv->next) {
2554 struct resolvers *resolvers;
2555
2556 if (!srv->resolvers_id)
2557 continue;
2558
2559 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002560 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002561 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2562 err_code |= (ERR_ALERT|ERR_ABORT);
2563 continue;
2564 }
2565 srv->resolvers = resolvers;
Christopher Fauletdcac4182021-06-15 16:17:17 +02002566 srv->srvrq_check = NULL;
2567 if (srv->srvrq) {
2568 if (!srv->srvrq->resolvers) {
2569 srv->srvrq->resolvers = srv->resolvers;
2570 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2571 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
2572 proxy_type_str(px), px->id, srv->id);
2573 err_code |= (ERR_ALERT|ERR_ABORT);
2574 continue;
2575 }
2576 }
Emeric Brunc9437992021-02-12 19:42:55 +01002577
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002578 srv->srvrq_check = task_new_anywhere();
Christopher Fauletdcac4182021-06-15 16:17:17 +02002579 if (!srv->srvrq_check) {
2580 ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002581 proxy_type_str(px), px->id, srv->id);
2582 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Fauletdcac4182021-06-15 16:17:17 +02002583 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002584 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002585 srv->srvrq_check->process = resolv_srvrq_expire_task;
2586 srv->srvrq_check->context = srv;
2587 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002588 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002589 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002590 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002591 proxy_type_str(px), px->id, srv->id);
2592 err_code |= (ERR_ALERT|ERR_ABORT);
2593 continue;
2594 }
Amaury Denoyelledd565202021-08-26 15:35:59 +02002595
2596 srv->flags |= SRV_F_NON_PURGEABLE;
Emeric Brunc9437992021-02-12 19:42:55 +01002597 }
2598 }
2599
2600 if (err_code & (ERR_ALERT|ERR_ABORT))
2601 goto err;
2602
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002603 leave_resolver_code();
William Lallemand866b88b2022-08-24 09:58:31 +02002604 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002605 err:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002606 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002607 resolvers_deinit();
William Lallemand866b88b2022-08-24 09:58:31 +02002608 return 1;
Emeric Brunc9437992021-02-12 19:42:55 +01002609
2610}
2611
Willy Tarreaucaff6312022-05-27 10:17:46 +02002612static int stats_dump_resolv_to_buffer(struct stconn *sc,
Emeric Brunc9437992021-02-12 19:42:55 +01002613 struct dns_nameserver *ns,
2614 struct field *stats, size_t stats_count,
2615 struct list *stat_modules)
2616{
Willy Tarreaucaff6312022-05-27 10:17:46 +02002617 struct appctx *appctx = __sc_appctx(sc);
2618 struct channel *rep = sc_ic(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002619 struct stats_module *mod;
2620 size_t idx = 0;
2621
2622 memset(stats, 0, sizeof(struct field) * stats_count);
2623
2624 list_for_each_entry(mod, stat_modules, list) {
2625 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2626
2627 mod->fill_stats(counters, stats + idx);
2628 idx += mod->stats_count;
2629 }
2630
2631 if (!stats_dump_one_line(stats, idx, appctx))
2632 return 0;
2633
2634 if (!stats_putchk(rep, NULL, &trash))
2635 goto full;
2636
2637 return 1;
2638
2639 full:
Willy Tarreaucaff6312022-05-27 10:17:46 +02002640 sc_have_room(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002641 return 0;
2642}
2643
2644/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2645 * as a pointer to the current nameserver.
2646 */
Willy Tarreaucaff6312022-05-27 10:17:46 +02002647int stats_dump_resolvers(struct stconn *sc,
Emeric Brunc9437992021-02-12 19:42:55 +01002648 struct field *stats, size_t stats_count,
2649 struct list *stat_modules)
2650{
Willy Tarreaucaff6312022-05-27 10:17:46 +02002651 struct appctx *appctx = __sc_appctx(sc);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002652 struct show_stat_ctx *ctx = appctx->svcctx;
Willy Tarreaucaff6312022-05-27 10:17:46 +02002653 struct channel *rep = sc_ic(sc);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002654 struct resolvers *resolver = ctx->obj1;
2655 struct dns_nameserver *ns = ctx->obj2;
Emeric Brunc9437992021-02-12 19:42:55 +01002656
2657 if (!resolver)
2658 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2659
2660 /* dump resolvers */
2661 list_for_each_entry_from(resolver, &sec_resolvers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002662 ctx->obj1 = resolver;
Emeric Brunc9437992021-02-12 19:42:55 +01002663
Willy Tarreau91cefca2022-05-03 17:08:29 +02002664 ns = ctx->obj2 ?
2665 ctx->obj2 :
Emeric Brunc9437992021-02-12 19:42:55 +01002666 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2667
2668 list_for_each_entry_from(ns, &resolver->nameservers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002669 ctx->obj2 = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002670
2671 if (buffer_almost_full(&rep->buf))
2672 goto full;
2673
Willy Tarreaucaff6312022-05-27 10:17:46 +02002674 if (!stats_dump_resolv_to_buffer(sc, ns,
Emeric Brunc9437992021-02-12 19:42:55 +01002675 stats, stats_count,
2676 stat_modules)) {
2677 return 0;
2678 }
2679 }
2680
Willy Tarreau91cefca2022-05-03 17:08:29 +02002681 ctx->obj2 = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002682 }
2683
2684 return 1;
2685
2686 full:
Willy Tarreaucaff6312022-05-27 10:17:46 +02002687 sc_need_room(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002688 return 0;
2689}
2690
2691void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2692{
2693 struct resolvers *resolvers;
2694 struct dns_nameserver *ns;
2695 struct stats_module *mod;
2696 void *counters;
2697
2698 list_for_each_entry(mod, stat_modules, list) {
2699 if (!mod->clearable && !clrall)
2700 continue;
2701
2702 list_for_each_entry(resolvers, &sec_resolvers, list) {
2703 list_for_each_entry(ns, &resolvers->nameservers, list) {
2704 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2705 memcpy(counters, mod->counters, mod->counters_size);
2706 }
2707 }
2708 }
2709
2710}
2711
2712int resolv_allocate_counters(struct list *stat_modules)
2713{
2714 struct stats_module *mod;
2715 struct resolvers *resolvers;
2716 struct dns_nameserver *ns;
2717
2718 list_for_each_entry(resolvers, &sec_resolvers, list) {
2719 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunf8642ee2021-10-29 17:59:18 +02002720 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
Emeric Brunc9437992021-02-12 19:42:55 +01002721 alloc_failed);
2722
2723 list_for_each_entry(mod, stat_modules, list) {
2724 EXTRA_COUNTERS_ADD(mod,
2725 ns->extra_counters,
2726 mod->counters,
2727 mod->counters_size);
2728 }
2729
2730 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2731
2732 list_for_each_entry(mod, stat_modules, list) {
2733 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2734 mod->counters, mod->counters_size);
2735
2736 /* Store the ns counters pointer */
Emeric Brunf8642ee2021-10-29 17:59:18 +02002737 if (strcmp(mod->name, "resolvers") == 0) {
2738 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
Emeric Brunc9437992021-02-12 19:42:55 +01002739 ns->counters->id = ns->id;
2740 ns->counters->pid = resolvers->id;
2741 }
2742 }
2743 }
2744 }
2745
2746 return 1;
2747
2748alloc_failed:
2749 return 0;
2750}
2751
Willy Tarreaudb933d62022-05-05 15:39:02 +02002752/* if an arg is found, it sets the optional resolvers section pointer into a
2753 * show_resolvers_ctx struct pointed to by svcctx, or NULL when dumping all.
2754 */
Emeric Brunc9437992021-02-12 19:42:55 +01002755static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2756{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002757 struct show_resolvers_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Emeric Brunc9437992021-02-12 19:42:55 +01002758 struct resolvers *presolvers;
2759
2760 if (*args[2]) {
2761 list_for_each_entry(presolvers, &sec_resolvers, list) {
2762 if (strcmp(presolvers->id, args[2]) == 0) {
Willy Tarreaudb933d62022-05-05 15:39:02 +02002763 ctx->forced_section = presolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002764 break;
2765 }
2766 }
Willy Tarreaudb933d62022-05-05 15:39:02 +02002767 if (ctx->forced_section == NULL)
Emeric Brunc9437992021-02-12 19:42:55 +01002768 return cli_err(appctx, "Can't find that resolvers section\n");
2769 }
2770 return 0;
2771}
2772
2773/* Dumps counters from all resolvers section and associated name servers. It
2774 * returns 0 if the output buffer is full and it needs to be called again,
Willy Tarreaudb933d62022-05-05 15:39:02 +02002775 * otherwise non-zero. It may limit itself to the resolver pointed to by the
2776 * <resolvers> field of struct show_resolvers_ctx pointed to by <svcctx> if
2777 * it's not null.
Emeric Brunc9437992021-02-12 19:42:55 +01002778 */
2779static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2780{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002781 struct show_resolvers_ctx *ctx = appctx->svcctx;
Willy Tarreaudb933d62022-05-05 15:39:02 +02002782 struct resolvers *resolvers = ctx->resolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002783 struct dns_nameserver *ns;
2784
2785 chunk_reset(&trash);
2786
Willy Tarreau12d52282022-05-05 16:38:13 +02002787 if (LIST_ISEMPTY(&sec_resolvers)) {
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002788 if (applet_putstr(appctx, "No resolvers found\n") == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002789 goto full;
2790 }
2791 else {
2792 if (!resolvers)
2793 resolvers = LIST_ELEM(sec_resolvers.n, typeof(resolvers), list);
Willy Tarreau4e047e72022-05-05 16:00:45 +02002794
Willy Tarreau12d52282022-05-05 16:38:13 +02002795 list_for_each_entry_from(resolvers, &sec_resolvers, list) {
2796 if (ctx->forced_section != NULL && ctx->forced_section != resolvers)
2797 continue;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002798
Willy Tarreau12d52282022-05-05 16:38:13 +02002799 ctx->resolvers = resolvers;
2800 ns = ctx->ns;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002801
Willy Tarreau12d52282022-05-05 16:38:13 +02002802 if (!ns) {
2803 chunk_printf(&trash, "Resolvers section %s\n", resolvers->id);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002804 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002805 goto full;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002806
Willy Tarreau12d52282022-05-05 16:38:13 +02002807 ns = LIST_ELEM(resolvers->nameservers.n, typeof(ns), list);
2808 ctx->ns = ns;
2809 }
Willy Tarreau4e047e72022-05-05 16:00:45 +02002810
Willy Tarreau12d52282022-05-05 16:38:13 +02002811 list_for_each_entry_from(ns, &resolvers->nameservers, list) {
2812 chunk_reset(&trash);
2813 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2814 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2815 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2816 chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
2817 chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
2818 chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
2819 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
2820 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
2821 chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
2822 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
2823 chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
2824 chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
2825 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
2826 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
2827 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
2828 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002829 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002830 goto full;
2831 ctx->ns = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002832 }
Emeric Brunc9437992021-02-12 19:42:55 +01002833
Willy Tarreau12d52282022-05-05 16:38:13 +02002834 ctx->ns = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002835
Willy Tarreau12d52282022-05-05 16:38:13 +02002836 /* was this the only section to dump ? */
2837 if (ctx->forced_section)
2838 break;
2839 }
Emeric Brunc9437992021-02-12 19:42:55 +01002840 }
Willy Tarreau12d52282022-05-05 16:38:13 +02002841
2842 /* done! */
2843 return 1;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002844 full:
2845 /* the output buffer is full, retry later */
Willy Tarreau4e047e72022-05-05 16:00:45 +02002846 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002847}
2848
2849/* register cli keywords */
2850static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002851 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002852 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2853 {{},}
2854 }
2855};
2856
2857INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2858
2859/*
2860 * Prepare <rule> for hostname resolution.
2861 * Returns -1 in case of any allocation failure, 0 if not.
2862 * On error, a global failure counter is also incremented.
2863 */
Willy Tarreau947ae122021-10-14 08:11:48 +02002864static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002865{
2866 char *hostname_dn;
Willy Tarreau947ae122021-10-14 08:11:48 +02002867 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002868 struct buffer *tmp = get_trash_chunk();
2869
2870 if (!hostname)
2871 return 0;
2872
Emeric Brunc9437992021-02-12 19:42:55 +01002873 hostname_dn = tmp->area;
Willy Tarreaubf9498a2021-10-14 07:49:49 +02002874 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002875 hostname_dn, tmp->size);
2876 if (hostname_dn_len == -1)
2877 goto err;
2878
2879
2880 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2881 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2882 if (!stream->resolv_ctx.hostname_dn)
2883 goto err;
2884
2885 return 0;
2886
2887 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002888 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002889 resolv_failed_resolutions += 1;
2890 return -1;
2891}
2892
2893
2894/*
2895 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2896 */
2897enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2898 struct session *sess, struct stream *s, int flags)
2899{
2900 struct resolv_resolution *resolution;
2901 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002902 struct resolv_requester *req;
2903 struct resolvers *resolvers;
2904 struct resolv_resolution *res;
2905 int exp, locked = 0;
2906 enum act_return ret = ACT_RET_CONT;
2907
2908 resolvers = rule->arg.resolv.resolvers;
2909
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002910 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002911
Emeric Brunc9437992021-02-12 19:42:55 +01002912 /* we have a response to our DNS resolution */
2913 use_cache:
2914 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2915 resolution = s->resolv_ctx.requester->resolution;
2916 if (!locked) {
2917 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2918 locked = 1;
2919 }
2920
2921 if (resolution->step == RSLV_STEP_RUNNING)
2922 goto yield;
2923 if (resolution->step == RSLV_STEP_NONE) {
2924 /* We update the variable only if we have a valid response. */
2925 if (resolution->status == RSLV_STATUS_VALID) {
2926 struct sample smp;
2927 short ip_sin_family = 0;
2928 void *ip = NULL;
2929
2930 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2931 0, &ip, &ip_sin_family, NULL);
2932
2933 switch (ip_sin_family) {
2934 case AF_INET:
2935 smp.data.type = SMP_T_IPV4;
2936 memcpy(&smp.data.u.ipv4, ip, 4);
2937 break;
2938 case AF_INET6:
2939 smp.data.type = SMP_T_IPV6;
2940 memcpy(&smp.data.u.ipv6, ip, 16);
2941 break;
2942 default:
2943 ip = NULL;
2944 }
2945
2946 if (ip) {
2947 smp.px = px;
2948 smp.sess = sess;
2949 smp.strm = s;
2950
2951 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2952 }
2953 }
2954 }
2955
2956 goto release_requester;
2957 }
2958
2959 /* need to configure and start a new DNS resolution */
2960 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2961 if (smp == NULL)
2962 goto end;
2963
Willy Tarreau947ae122021-10-14 08:11:48 +02002964 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002965 goto end; /* on error, ignore the action */
2966
2967 s->resolv_ctx.parent = rule;
2968
2969 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2970 locked = 1;
2971
2972 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2973
2974 /* Check if there is a fresh enough response in the cache of our associated resolution */
2975 req = s->resolv_ctx.requester;
2976 if (!req || !req->resolution)
2977 goto release_requester; /* on error, ignore the action */
2978 res = req->resolution;
2979
2980 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2981 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2982 && !tick_is_expired(exp, now_ms)) {
2983 goto use_cache;
2984 }
2985
2986 resolv_trigger_resolution(s->resolv_ctx.requester);
2987
2988 yield:
2989 if (flags & ACT_OPT_FINAL)
2990 goto release_requester;
2991 ret = ACT_RET_YIELD;
2992
2993 end:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002994 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002995 if (locked)
2996 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2997 return ret;
2998
2999 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003000 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01003001 s->resolv_ctx.hostname_dn_len = 0;
3002 if (s->resolv_ctx.requester) {
Willy Tarreau6878f802021-10-20 14:07:31 +02003003 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01003004 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
3005 s->resolv_ctx.requester = NULL;
3006 }
3007 goto end;
3008}
3009
3010static void release_resolv_action(struct act_rule *rule)
3011{
3012 release_sample_expr(rule->arg.resolv.expr);
3013 free(rule->arg.resolv.varname);
3014 free(rule->arg.resolv.resolvers_id);
3015 free(rule->arg.resolv.opts);
3016}
3017
3018
3019/* parse "do-resolve" action
3020 * This action takes the following arguments:
3021 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3022 *
3023 * - <varName> is the variable name where the result of the DNS resolution will be stored
3024 * (mandatory)
3025 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3026 * (mandatory)
3027 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3028 * (optional), defaults to ipv6
3029 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3030 */
3031enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3032{
3033 int cur_arg;
3034 struct sample_expr *expr;
3035 unsigned int where;
3036 const char *beg, *end;
3037
3038 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3039 cur_arg = *orig_arg - 1;
3040
3041 /* locate varName, which is mandatory */
3042 beg = strchr(args[cur_arg], '(');
3043 if (beg == NULL)
3044 goto do_resolve_parse_error;
3045 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3046 end = strchr(beg, ',');
3047 if (end == NULL)
3048 goto do_resolve_parse_error;
3049 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3050 if (rule->arg.resolv.varname == NULL)
3051 goto do_resolve_parse_error;
3052
3053
3054 /* locate resolversSectionName, which is mandatory.
3055 * Since next parameters are optional, the delimiter may be comma ','
3056 * or closing parenthesis ')'
3057 */
3058 beg = end + 1;
3059 end = strchr(beg, ',');
3060 if (end == NULL)
3061 end = strchr(beg, ')');
3062 if (end == NULL)
3063 goto do_resolve_parse_error;
3064 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3065 if (rule->arg.resolv.resolvers_id == NULL)
3066 goto do_resolve_parse_error;
3067
3068
3069 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3070 if (rule->arg.resolv.opts == NULL)
3071 goto do_resolve_parse_error;
3072
3073 /* Default priority is ipv6 */
3074 rule->arg.resolv.opts->family_prio = AF_INET6;
3075
3076 /* optional arguments accepted for now:
3077 * ipv4 or ipv6
3078 */
3079 while (*end != ')') {
3080 beg = end + 1;
3081 end = strchr(beg, ',');
3082 if (end == NULL)
3083 end = strchr(beg, ')');
3084 if (end == NULL)
3085 goto do_resolve_parse_error;
3086
3087 if (strncmp(beg, "ipv4", end - beg) == 0) {
3088 rule->arg.resolv.opts->family_prio = AF_INET;
3089 }
3090 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3091 rule->arg.resolv.opts->family_prio = AF_INET6;
3092 }
3093 else {
3094 goto do_resolve_parse_error;
3095 }
3096 }
3097
3098 cur_arg = cur_arg + 1;
3099
3100 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3101 if (!expr)
3102 goto do_resolve_parse_error;
3103
3104
3105 where = 0;
3106 if (px->cap & PR_CAP_FE)
3107 where |= SMP_VAL_FE_HRQ_HDR;
3108 if (px->cap & PR_CAP_BE)
3109 where |= SMP_VAL_BE_HRQ_HDR;
3110
3111 if (!(expr->fetch->val & where)) {
3112 memprintf(err,
3113 "fetch method '%s' extracts information from '%s', none of which is available here",
3114 args[cur_arg-1], sample_src_names(expr->fetch->use));
3115 free(expr);
3116 return ACT_RET_PRS_ERR;
3117 }
3118 rule->arg.resolv.expr = expr;
3119 rule->action = ACT_CUSTOM;
3120 rule->action_ptr = resolv_action_do_resolve;
3121 *orig_arg = cur_arg;
3122
3123 rule->check_ptr = check_action_do_resolve;
3124 rule->release_ptr = release_resolv_action;
3125
3126 return ACT_RET_PRS_OK;
3127
3128 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003129 ha_free(&rule->arg.resolv.varname);
3130 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003131 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3132 args[cur_arg]);
3133 return ACT_RET_PRS_ERR;
3134}
3135
3136static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003137 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003138 { /* END */ }
3139}};
3140
3141INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3142
3143static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003144 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003145 { /* END */ }
3146}};
3147
3148INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3149
3150/* Check an "http-request do-resolve" action.
3151 *
3152 * The function returns 1 in success case, otherwise, it returns 0 and err is
3153 * filled.
3154 */
3155int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3156{
3157 struct resolvers *resolvers = NULL;
3158
3159 if (rule->arg.resolv.resolvers_id == NULL) {
3160 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3161 return 0;
3162 }
3163
3164 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3165 if (resolvers == NULL) {
3166 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3167 return 0;
3168 }
3169 rule->arg.resolv.resolvers = resolvers;
3170
3171 return 1;
3172}
3173
3174void resolvers_setup_proxy(struct proxy *px)
3175{
3176 px->last_change = now.tv_sec;
3177 px->cap = PR_CAP_FE | PR_CAP_BE;
3178 px->maxconn = 0;
3179 px->conn_retries = 1;
3180 px->timeout.server = TICK_ETERNITY;
3181 px->timeout.client = TICK_ETERNITY;
3182 px->timeout.connect = TICK_ETERNITY;
3183 px->accept = NULL;
3184 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
Emeric Brunc9437992021-02-12 19:42:55 +01003185}
3186
William Lallemand73edfe42022-05-05 17:36:09 +02003187static int parse_resolve_conf(char **errmsg, char **warnmsg)
3188{
3189 struct dns_nameserver *newnameserver = NULL;
3190 const char *whitespace = "\r\n\t ";
3191 char *resolv_line = NULL;
3192 int resolv_linenum = 0;
3193 FILE *f = NULL;
3194 char *address = NULL;
3195 struct sockaddr_storage *sk = NULL;
3196 struct protocol *proto;
3197 int duplicate_name = 0;
3198 int err_code = 0;
3199
3200 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3201 memprintf(errmsg, "out of memory.\n");
3202 err_code |= ERR_ALERT | ERR_FATAL;
3203 goto resolv_out;
3204 }
3205
3206 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3207 if (errmsg)
3208 memprintf(errmsg, "failed to open /etc/resolv.conf.");
3209 err_code |= ERR_ALERT | ERR_FATAL;
3210 goto resolv_out;
3211 }
3212
3213 sk = calloc(1, sizeof(*sk));
3214 if (sk == NULL) {
3215 if (errmsg)
3216 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3217 err_code |= ERR_ALERT | ERR_FATAL;
3218 goto resolv_out;
3219 }
3220
3221 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3222 resolv_linenum++;
3223 if (strncmp(resolv_line, "nameserver", 10) != 0)
3224 continue;
3225
3226 address = strtok(resolv_line + 10, whitespace);
3227 if (address == resolv_line + 10)
3228 continue;
3229
3230 if (address == NULL) {
3231 if (warnmsg)
3232 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3233 *warnmsg ? *warnmsg : "", resolv_linenum);
3234 err_code |= ERR_WARN;
3235 continue;
3236 }
3237
3238 duplicate_name = 0;
3239 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3240 if (strcmp(newnameserver->id, address) == 0) {
3241 if (warnmsg)
3242 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",
3243 *warnmsg ? *warnmsg : "", resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3244 err_code |= ERR_WARN;
3245 duplicate_name = 1;
3246 }
3247 }
3248
3249 if (duplicate_name)
3250 continue;
3251
3252 memset(sk, 0, sizeof(*sk));
3253 if (!str2ip2(address, sk, 1)) {
3254 if (warnmsg)
3255 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3256 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3257 err_code |= ERR_WARN;
3258 continue;
3259 }
3260
3261 set_host_port(sk, 53);
3262
3263 proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
3264 if (!proto || !proto->connect) {
3265 if (warnmsg)
3266 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3267 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3268 err_code |= ERR_WARN;
3269 continue;
3270 }
3271
3272 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3273 if (errmsg)
3274 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3275 err_code |= ERR_ALERT | ERR_FATAL;
3276 goto resolv_out;
3277 }
3278
3279 if (dns_dgram_init(newnameserver, sk) < 0) {
3280 if (errmsg)
3281 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3282 err_code |= ERR_ALERT | ERR_FATAL;
3283 free(newnameserver);
3284 goto resolv_out;
3285 }
3286
3287 newnameserver->conf.file = strdup("/etc/resolv.conf");
3288 if (newnameserver->conf.file == NULL) {
3289 if (errmsg)
3290 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3291 err_code |= ERR_ALERT | ERR_FATAL;
3292 free(newnameserver);
3293 goto resolv_out;
3294 }
3295
3296 newnameserver->id = strdup(address);
3297 if (newnameserver->id == NULL) {
3298 if (errmsg)
3299 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3300 err_code |= ERR_ALERT | ERR_FATAL;
3301 free((char *)newnameserver->conf.file);
3302 free(newnameserver);
3303 goto resolv_out;
3304 }
3305
3306 newnameserver->parent = curr_resolvers;
3307 newnameserver->process_responses = resolv_process_responses;
3308 newnameserver->conf.line = resolv_linenum;
3309 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
3310 }
3311
3312resolv_out:
3313 free(sk);
3314 free(resolv_line);
3315 if (f != NULL)
3316 fclose(f);
3317
3318 return err_code;
3319}
3320
William Lallemande7f57762022-05-05 18:27:48 +02003321static int resolvers_new(struct resolvers **resolvers, const char *id, const char *file, int linenum)
3322{
3323 struct resolvers *r = NULL;
3324 struct proxy *p = NULL;
3325 int err_code = 0;
3326
3327 if ((r = calloc(1, sizeof(*r))) == NULL) {
3328 err_code |= ERR_ALERT | ERR_ABORT;
3329 goto out;
3330 }
3331
3332 /* allocate new proxy to tcp servers */
3333 p = calloc(1, sizeof *p);
3334 if (!p) {
3335 err_code |= ERR_ALERT | ERR_FATAL;
3336 goto out;
3337 }
3338
3339 init_new_proxy(p);
3340 resolvers_setup_proxy(p);
3341 p->parent = r;
3342 p->id = strdup(id);
3343 p->conf.args.file = p->conf.file = strdup(file);
3344 p->conf.args.line = p->conf.line = linenum;
3345 r->px = p;
3346
3347 /* default values */
3348 LIST_APPEND(&sec_resolvers, &r->list);
3349 r->conf.file = strdup(file);
3350 r->conf.line = linenum;
3351 r->id = strdup(id);
3352 r->query_ids = EB_ROOT;
3353 /* default maximum response size */
3354 r->accepted_payload_size = 512;
3355 /* default hold period for nx, other, refuse and timeout is 30s */
3356 r->hold.nx = 30000;
3357 r->hold.other = 30000;
3358 r->hold.refused = 30000;
3359 r->hold.timeout = 30000;
3360 r->hold.obsolete = 0;
3361 /* default hold period for valid is 10s */
3362 r->hold.valid = 10000;
3363 r->timeout.resolve = 1000;
3364 r->timeout.retry = 1000;
3365 r->resolve_retries = 3;
3366 LIST_INIT(&r->nameservers);
3367 LIST_INIT(&r->resolutions.curr);
3368 LIST_INIT(&r->resolutions.wait);
3369 HA_SPIN_INIT(&r->lock);
3370
3371 *resolvers = r;
3372
3373out:
3374 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3375 ha_free(&r);
3376 ha_free(&p);
3377 }
3378
3379 return err_code;
3380}
3381
3382
Emeric Brunc9437992021-02-12 19:42:55 +01003383/*
3384 * Parse a <resolvers> section.
3385 * Returns the error code, 0 if OK, or any combination of :
3386 * - ERR_ABORT: must abort ASAP
3387 * - ERR_FATAL: we can continue parsing but not start the service
3388 * - ERR_WARN: a warning has been emitted
3389 * - ERR_ALERT: an alert has been emitted
3390 * Only the two first ones can stop processing, the two others are just
3391 * indicators.
3392 */
3393int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3394{
3395 const char *err;
3396 int err_code = 0;
3397 char *errmsg = NULL;
William Lallemand106bd292022-05-05 17:20:08 +02003398 char *warnmsg = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01003399
3400 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3401 if (!*args[1]) {
3402 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3403 err_code |= ERR_ALERT | ERR_ABORT;
3404 goto out;
3405 }
3406
3407 err = invalid_char(args[1]);
3408 if (err) {
3409 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3410 file, linenum, *err, args[0], args[1]);
3411 err_code |= ERR_ALERT | ERR_ABORT;
3412 goto out;
3413 }
3414
3415 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3416 /* Error if two resolvers owns the same name */
3417 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3418 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3419 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3420 err_code |= ERR_ALERT | ERR_ABORT;
3421 }
3422 }
3423
William Lallemande7f57762022-05-05 18:27:48 +02003424 err_code |= resolvers_new(&curr_resolvers, args[1], file, linenum);
3425 if (err_code & ERR_ALERT) {
Emeric Brunc9437992021-02-12 19:42:55 +01003426 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
Emeric Brunc9437992021-02-12 19:42:55 +01003427 goto out;
3428 }
3429
Emeric Brunc9437992021-02-12 19:42:55 +01003430 }
3431 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3432 struct dns_nameserver *newnameserver = NULL;
3433 struct sockaddr_storage *sk;
3434 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003435 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003436
3437 if (!*args[2]) {
3438 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3439 file, linenum, args[0]);
3440 err_code |= ERR_ALERT | ERR_FATAL;
3441 goto out;
3442 }
3443
3444 err = invalid_char(args[1]);
3445 if (err) {
3446 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3447 file, linenum, *err, args[1]);
3448 err_code |= ERR_ALERT | ERR_FATAL;
3449 goto out;
3450 }
3451
3452 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3453 /* Error if two resolvers owns the same name */
3454 if (strcmp(newnameserver->id, args[1]) == 0) {
3455 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3456 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3457 err_code |= ERR_ALERT | ERR_FATAL;
3458 }
3459 }
3460
Emeric Brunc8f3e452021-04-07 16:04:54 +02003461 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3462 &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 +01003463 if (!sk) {
3464 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3465 err_code |= ERR_ALERT | ERR_FATAL;
3466 goto out;
3467 }
3468
3469 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3470 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3471 err_code |= ERR_ALERT | ERR_ABORT;
3472 goto out;
3473 }
3474
Willy Tarreau91b47262022-05-20 16:36:46 +02003475 if (proto && proto->xprt_type == PROTO_TYPE_STREAM) {
Emeric Brunc8f3e452021-04-07 16:04:54 +02003476 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3477 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3478 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3479 err_code |= ERR_ABORT;
3480 goto out;
3481 }
3482
3483 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3484 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3485 err_code |= ERR_ALERT|ERR_ABORT;
3486 goto out;
3487 }
3488 }
3489 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003490 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3491 err_code |= ERR_ALERT | ERR_ABORT;
3492 goto out;
3493 }
3494
3495 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3496 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3497 err_code |= ERR_ALERT | ERR_ABORT;
3498 goto out;
3499 }
3500
3501 if ((newnameserver->id = strdup(args[1])) == NULL) {
3502 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3503 err_code |= ERR_ALERT | ERR_ABORT;
3504 goto out;
3505 }
3506
3507 newnameserver->parent = curr_resolvers;
3508 newnameserver->process_responses = resolv_process_responses;
3509 newnameserver->conf.line = linenum;
3510 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003511 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003512 }
3513 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
William Lallemand73edfe42022-05-05 17:36:09 +02003514 err_code |= parse_resolve_conf(&errmsg, &warnmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003515 if (err_code & ERR_WARN) {
3516 indent_msg(&warnmsg, 8);
3517 ha_warning("parsing [%s:%d]: %s\n", file, linenum, warnmsg);
3518 ha_free(&warnmsg);
3519 }
William Lallemand106bd292022-05-05 17:20:08 +02003520 if (err_code & ERR_ALERT) {
3521 indent_msg(&errmsg, 8);
3522 ha_alert("parsing [%s:%d]: %s\n", file, linenum, errmsg);
3523 ha_free(&errmsg);
William Lallemand73edfe42022-05-05 17:36:09 +02003524 goto out;
William Lallemand106bd292022-05-05 17:20:08 +02003525 }
Emeric Brunc9437992021-02-12 19:42:55 +01003526 }
3527 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3528 const char *res;
3529 unsigned int time;
3530
3531 if (!*args[2]) {
3532 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3533 file, linenum, args[0]);
3534 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3535 err_code |= ERR_ALERT | ERR_FATAL;
3536 goto out;
3537 }
3538 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3539 if (res == PARSE_TIME_OVER) {
3540 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3541 file, linenum, args[1], args[0]);
3542 err_code |= ERR_ALERT | ERR_FATAL;
3543 goto out;
3544 }
3545 else if (res == PARSE_TIME_UNDER) {
3546 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3547 file, linenum, args[1], args[0]);
3548 err_code |= ERR_ALERT | ERR_FATAL;
3549 goto out;
3550 }
3551 else if (res) {
3552 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3553 file, linenum, *res, args[0]);
3554 err_code |= ERR_ALERT | ERR_FATAL;
3555 goto out;
3556 }
3557 if (strcmp(args[1], "nx") == 0)
3558 curr_resolvers->hold.nx = time;
3559 else if (strcmp(args[1], "other") == 0)
3560 curr_resolvers->hold.other = time;
3561 else if (strcmp(args[1], "refused") == 0)
3562 curr_resolvers->hold.refused = time;
3563 else if (strcmp(args[1], "timeout") == 0)
3564 curr_resolvers->hold.timeout = time;
3565 else if (strcmp(args[1], "valid") == 0)
3566 curr_resolvers->hold.valid = time;
3567 else if (strcmp(args[1], "obsolete") == 0)
3568 curr_resolvers->hold.obsolete = time;
3569 else {
3570 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3571 file, linenum, args[0], args[1]);
3572 err_code |= ERR_ALERT | ERR_FATAL;
3573 goto out;
3574 }
3575
3576 }
3577 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3578 int i = 0;
3579
3580 if (!*args[1]) {
3581 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3582 file, linenum, args[0]);
3583 err_code |= ERR_ALERT | ERR_FATAL;
3584 goto out;
3585 }
3586
3587 i = atoi(args[1]);
3588 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3589 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3590 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3591 err_code |= ERR_ALERT | ERR_FATAL;
3592 goto out;
3593 }
3594
3595 curr_resolvers->accepted_payload_size = i;
3596 }
3597 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3598 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3599 file, linenum, args[0]);
3600 err_code |= ERR_ALERT | ERR_FATAL;
3601 goto out;
3602 }
3603 else if (strcmp(args[0], "resolve_retries") == 0) {
3604 if (!*args[1]) {
3605 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3606 file, linenum, args[0]);
3607 err_code |= ERR_ALERT | ERR_FATAL;
3608 goto out;
3609 }
3610 curr_resolvers->resolve_retries = atoi(args[1]);
3611 }
3612 else if (strcmp(args[0], "timeout") == 0) {
3613 if (!*args[1]) {
3614 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3615 file, linenum, args[0]);
3616 err_code |= ERR_ALERT | ERR_FATAL;
3617 goto out;
3618 }
3619 else if (strcmp(args[1], "retry") == 0 ||
3620 strcmp(args[1], "resolve") == 0) {
3621 const char *res;
3622 unsigned int tout;
3623
3624 if (!*args[2]) {
3625 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3626 file, linenum, args[0], args[1]);
3627 err_code |= ERR_ALERT | ERR_FATAL;
3628 goto out;
3629 }
3630 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3631 if (res == PARSE_TIME_OVER) {
3632 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3633 file, linenum, args[2], args[0], args[1]);
3634 err_code |= ERR_ALERT | ERR_FATAL;
3635 goto out;
3636 }
3637 else if (res == PARSE_TIME_UNDER) {
3638 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3639 file, linenum, args[2], args[0], args[1]);
3640 err_code |= ERR_ALERT | ERR_FATAL;
3641 goto out;
3642 }
3643 else if (res) {
3644 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3645 file, linenum, *res, args[0], args[1]);
3646 err_code |= ERR_ALERT | ERR_FATAL;
3647 goto out;
3648 }
3649 if (args[1][2] == 't')
3650 curr_resolvers->timeout.retry = tout;
3651 else
3652 curr_resolvers->timeout.resolve = tout;
3653 }
3654 else {
3655 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3656 file, linenum, args[0], args[1]);
3657 err_code |= ERR_ALERT | ERR_FATAL;
3658 goto out;
3659 }
3660 }
3661 else if (*args[0] != 0) {
3662 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3663 err_code |= ERR_ALERT | ERR_FATAL;
3664 goto out;
3665 }
3666
William Lallemand106bd292022-05-05 17:20:08 +02003667out:
Emeric Brunc9437992021-02-12 19:42:55 +01003668 free(errmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003669 free(warnmsg);
Emeric Brunc9437992021-02-12 19:42:55 +01003670 return err_code;
3671}
William Lallemand7867f632022-05-05 19:02:59 +02003672
3673/* try to create a "default" resolvers section which uses "/etc/resolv.conf"
3674 *
3675 * This function is opportunistic and does not try to display errors or warnings.
3676 */
3677int resolvers_create_default()
3678{
3679 int err_code = 0;
3680
William Lallemand6020c4e2022-08-24 11:15:08 +02003681 if (global.mode & MODE_MWORKER_WAIT) /* does not create the section if in wait mode */
3682 return 0;
3683
William Lallemand3bda8072022-07-18 14:12:17 +02003684 /* if the section already exists, do nothing */
William Lallemand7867f632022-05-05 19:02:59 +02003685 if (find_resolvers_by_id("default"))
3686 return 0;
3687
William Lallemand3bda8072022-07-18 14:12:17 +02003688 curr_resolvers = NULL;
William Lallemand7867f632022-05-05 19:02:59 +02003689 err_code |= resolvers_new(&curr_resolvers, "default", "<internal>", 0);
William Lallemand3bda8072022-07-18 14:12:17 +02003690 if (err_code & ERR_CODE)
3691 goto err;
William Lallemandb10b1192022-08-24 14:50:32 +02003692
3693 curr_resolvers->conf.implicit = 1;
3694
William Lallemand3bda8072022-07-18 14:12:17 +02003695 err_code |= parse_resolve_conf(NULL, NULL);
3696 if (err_code & ERR_CODE)
3697 goto err;
3698 /* check if there was any nameserver in the resolvconf file */
3699 if (LIST_ISEMPTY(&curr_resolvers->nameservers)) {
3700 err_code |= ERR_FATAL;
3701 goto err;
3702 }
3703
3704err:
3705 if (err_code & ERR_CODE) {
3706 resolvers_destroy(curr_resolvers);
3707 curr_resolvers = NULL;
3708 }
William Lallemand7867f632022-05-05 19:02:59 +02003709
William Lallemand3bda8072022-07-18 14:12:17 +02003710 /* we never return an error there, we only try to create this section
3711 * if that's possible */
William Lallemand7867f632022-05-05 19:02:59 +02003712 return 0;
3713}
3714
Emeric Brun56fc5d92021-02-12 20:05:45 +01003715int cfg_post_parse_resolvers()
3716{
3717 int err_code = 0;
3718 struct server *srv;
3719
3720 if (curr_resolvers) {
3721
3722 /* prepare forward server descriptors */
3723 if (curr_resolvers->px) {
3724 srv = curr_resolvers->px->srv;
3725 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003726 /* init ssl if needed */
3727 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3728 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3729 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3730 err_code |= ERR_ALERT | ERR_FATAL;
3731 break;
3732 }
3733 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003734 srv = srv->next;
3735 }
3736 }
3737 }
3738 curr_resolvers = NULL;
3739 return err_code;
3740}
Emeric Brunc9437992021-02-12 19:42:55 +01003741
Emeric Brun56fc5d92021-02-12 20:05:45 +01003742REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003743REGISTER_POST_DEINIT(resolvers_deinit);
3744REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);
William Lallemand7867f632022-05-05 19:02:59 +02003745REGISTER_PRE_CHECK(resolvers_create_default);