blob: 73968917c240e19cceefbab0b7313194daf27c1a [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 Tarreauf766ec62021-10-18 16:46:38 +020068static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
69static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau6878f802021-10-20 14:07:31 +020070static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +010071static void enter_resolver_code();
72static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010073
74enum {
Emeric Brunf8642ee2021-10-29 17:59:18 +020075 RSLV_STAT_ID,
76 RSLV_STAT_PID,
77 RSLV_STAT_SENT,
78 RSLV_STAT_SND_ERROR,
79 RSLV_STAT_VALID,
80 RSLV_STAT_UPDATE,
81 RSLV_STAT_CNAME,
82 RSLV_STAT_CNAME_ERROR,
83 RSLV_STAT_ANY_ERR,
84 RSLV_STAT_NX,
85 RSLV_STAT_TIMEOUT,
86 RSLV_STAT_REFUSED,
87 RSLV_STAT_OTHER,
88 RSLV_STAT_INVALID,
89 RSLV_STAT_TOO_BIG,
90 RSLV_STAT_TRUNCATED,
91 RSLV_STAT_OUTDATED,
92 RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +010093};
94
Emeric Brunf8642ee2021-10-29 17:59:18 +020095static struct name_desc resolv_stats[] = {
96 [RSLV_STAT_ID] = { .name = "id", .desc = "ID" },
97 [RSLV_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
98 [RSLV_STAT_SENT] = { .name = "sent", .desc = "Sent" },
99 [RSLV_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
100 [RSLV_STAT_VALID] = { .name = "valid", .desc = "Valid" },
101 [RSLV_STAT_UPDATE] = { .name = "update", .desc = "Update" },
102 [RSLV_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
103 [RSLV_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
104 [RSLV_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
105 [RSLV_STAT_NX] = { .name = "nx", .desc = "NX" },
106 [RSLV_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
107 [RSLV_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
108 [RSLV_STAT_OTHER] = { .name = "other", .desc = "Other" },
109 [RSLV_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
110 [RSLV_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
111 [RSLV_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
112 [RSLV_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
Emeric Brunc9437992021-02-12 19:42:55 +0100113};
114
115static struct dns_counters dns_counters;
116
Emeric Brunf8642ee2021-10-29 17:59:18 +0200117static void resolv_fill_stats(void *d, struct field *stats)
Emeric Brunc9437992021-02-12 19:42:55 +0100118{
119 struct dns_counters *counters = d;
Emeric Brunf8642ee2021-10-29 17:59:18 +0200120 stats[RSLV_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
121 stats[RSLV_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
122 stats[RSLV_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
123 stats[RSLV_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
124 stats[RSLV_STAT_VALID] = mkf_u64(FN_GAUGE, counters->app.resolver.valid);
125 stats[RSLV_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->app.resolver.update);
126 stats[RSLV_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->app.resolver.cname);
127 stats[RSLV_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->app.resolver.cname_error);
128 stats[RSLV_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->app.resolver.any_err);
129 stats[RSLV_STAT_NX] = mkf_u64(FN_GAUGE, counters->app.resolver.nx);
130 stats[RSLV_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->app.resolver.timeout);
131 stats[RSLV_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->app.resolver.refused);
132 stats[RSLV_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->app.resolver.other);
133 stats[RSLV_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->app.resolver.invalid);
134 stats[RSLV_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->app.resolver.too_big);
135 stats[RSLV_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->app.resolver.truncated);
136 stats[RSLV_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +0100137}
138
Emeric Brunf8642ee2021-10-29 17:59:18 +0200139static struct stats_module rslv_stats_module = {
140 .name = "resolvers",
141 .domain_flags = STATS_DOMAIN_RESOLVERS << STATS_DOMAIN,
142 .fill_stats = resolv_fill_stats,
143 .stats = resolv_stats,
144 .stats_count = RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +0100145 .counters = &dns_counters,
146 .counters_size = sizeof(dns_counters),
147 .clearable = 0,
148};
149
Emeric Brunf8642ee2021-10-29 17:59:18 +0200150INITCALL1(STG_REGISTER, stats_register_module, &rslv_stats_module);
Emeric Brunc9437992021-02-12 19:42:55 +0100151
Willy Tarreaudb933d62022-05-05 15:39:02 +0200152/* CLI context used during "show resolvers" */
153struct show_resolvers_ctx {
154 struct resolvers *forced_section;
155 struct resolvers *resolvers;
156 struct dns_nameserver *ns;
157};
158
Emeric Brunc9437992021-02-12 19:42:55 +0100159/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
160 * no match is found.
161 */
162struct resolvers *find_resolvers_by_id(const char *id)
163{
164 struct resolvers *res;
165
166 list_for_each_entry(res, &sec_resolvers, list) {
167 if (strcmp(res->id, id) == 0)
168 return res;
169 }
170 return NULL;
171}
172
Emeric Brunc9437992021-02-12 19:42:55 +0100173/* Returns a pointer on the SRV request matching the name <name> for the proxy
174 * <px>. NULL is returned if no match is found.
175 */
176struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
177{
178 struct resolv_srvrq *srvrq;
179
180 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
181 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
182 return srvrq;
183 }
184 return NULL;
185}
186
187/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
188 * NULL if an error occurred. */
189struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
190{
191 struct proxy *px = srv->proxy;
192 struct resolv_srvrq *srvrq = NULL;
193 int fqdn_len, hostname_dn_len;
194
195 fqdn_len = strlen(fqdn);
Willy Tarreaubf9498a2021-10-14 07:49:49 +0200196 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100197 trash.size);
198 if (hostname_dn_len == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200199 ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100200 proxy_type_str(px), px->id, srv->id, fqdn);
201 goto err;
202 }
203
204 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200205 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100206 proxy_type_str(px), px->id, srv->id);
207 goto err;
208 }
209 srvrq->obj_type = OBJ_TYPE_SRVRQ;
210 srvrq->proxy = px;
211 srvrq->name = strdup(fqdn);
212 srvrq->hostname_dn = strdup(trash.area);
213 srvrq->hostname_dn_len = hostname_dn_len;
214 if (!srvrq->name || !srvrq->hostname_dn) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200215 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100216 proxy_type_str(px), px->id, srv->id);
217 goto err;
218 }
Emeric Brun34067662021-06-11 10:48:45 +0200219 LIST_INIT(&srvrq->attached_servers);
220 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200221 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100222 return srvrq;
223
224 err:
225 if (srvrq) {
226 free(srvrq->name);
227 free(srvrq->hostname_dn);
228 free(srvrq);
229 }
230 return NULL;
231}
232
233
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100234/* finds and return the SRV answer item associated to a requester (whose type is 'server').
235 *
236 * returns NULL in case of error or not found.
237 */
238struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
239{
240 struct resolv_resolution *res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200241 struct eb32_node *eb32;
242 struct server *srv;
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100243
244 if (!requester)
245 return NULL;
246
247 if ((srv = objt_server(requester->owner)) == NULL)
248 return NULL;
249 /* check if the server is managed by a SRV record */
250 if (srv->srvrq == NULL)
251 return NULL;
252
253 res = srv->srvrq->requester->resolution;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200254
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100255 /* search an ANSWER record whose target points to the server's hostname and whose port is
256 * the same as server's svc_port */
Willy Tarreau7893ae12021-10-21 07:39:57 +0200257 for (eb32 = eb32_first(&res->response.answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
258 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
259
Willy Tarreau75cc6532021-10-15 08:53:44 +0200260 if (memcmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100261 (srv->svc_port == item->port))
262 return item;
263 }
264
265 return NULL;
266}
267
Emeric Brunc9437992021-02-12 19:42:55 +0100268/* 2 bytes random generator to generate DNS query ID */
269static inline uint16_t resolv_rnd16(void)
270{
271 if (!resolv_query_id_seed)
272 resolv_query_id_seed = now_ms;
273 resolv_query_id_seed ^= resolv_query_id_seed << 13;
274 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
275 resolv_query_id_seed ^= resolv_query_id_seed << 17;
276 return resolv_query_id_seed;
277}
278
279
280static inline int resolv_resolution_timeout(struct resolv_resolution *res)
281{
282 return res->resolvers->timeout.resolve;
283}
284
285/* Updates a resolvers' task timeout for next wake up and queue it */
286static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
287{
288 struct resolv_resolution *res;
289 int next;
290
291 next = tick_add(now_ms, resolvers->timeout.resolve);
292 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
293 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
294 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
295 }
296
297 list_for_each_entry(res, &resolvers->resolutions.wait, list)
298 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
299
300 resolvers->t->expire = next;
301 task_queue(resolvers->t);
302}
303
304/* Forges a DNS query. It needs the following information from the caller:
305 * - <query_id> : the DNS query id corresponding to this query
306 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
307 * - <hostname_dn> : hostname in domain name format
308 * - <hostname_dn_len> : length of <hostname_dn>
309 *
310 * To store the query, the caller must pass a buffer <buf> and its size
311 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
312 * too short.
313 */
314static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
315 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
316{
317 struct dns_header dns_hdr;
318 struct dns_question qinfo;
319 struct dns_additional_record edns;
320 char *p = buf;
321
322 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
323 return -1;
324
325 memset(buf, 0, bufsize);
326
327 /* Set dns query headers */
328 dns_hdr.id = (unsigned short) htons(query_id);
329 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
330 dns_hdr.qdcount = htons(1); /* 1 question */
331 dns_hdr.ancount = 0;
332 dns_hdr.nscount = 0;
333 dns_hdr.arcount = htons(1);
334 memcpy(p, &dns_hdr, sizeof(dns_hdr));
335 p += sizeof(dns_hdr);
336
337 /* Set up query hostname */
338 memcpy(p, hostname_dn, hostname_dn_len);
339 p += hostname_dn_len;
340 *p++ = 0;
341
342 /* Set up query info (type and class) */
343 qinfo.qtype = htons(query_type);
344 qinfo.qclass = htons(DNS_RCLASS_IN);
345 memcpy(p, &qinfo, sizeof(qinfo));
346 p += sizeof(qinfo);
347
348 /* Set the DNS extension */
349 edns.name = 0;
350 edns.type = htons(DNS_RTYPE_OPT);
351 edns.udp_payload_size = htons(accepted_payload_size);
352 edns.extension = 0;
353 edns.data_length = 0;
354 memcpy(p, &edns, sizeof(edns));
355 p += sizeof(edns);
356
357 return (p - buf);
358}
359
360/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
Emeric Brun0161d322021-10-29 16:44:49 +0200361 * success or -1 if trash buffer is not large enough to build a valid query.
Emeric Brunc9437992021-02-12 19:42:55 +0100362 */
363static int resolv_send_query(struct resolv_resolution *resolution)
364{
365 struct resolvers *resolvers = resolution->resolvers;
366 struct dns_nameserver *ns;
367 int len;
368
369 /* Update resolution */
370 resolution->nb_queries = 0;
371 resolution->nb_responses = 0;
372 resolution->last_query = now_ms;
373
374 len = resolv_build_query(resolution->query_id, resolution->query_type,
375 resolvers->accepted_payload_size,
376 resolution->hostname_dn, resolution->hostname_dn_len,
377 trash.area, trash.size);
Emeric Brun0161d322021-10-29 16:44:49 +0200378 if (len < 0) {
379 send_log(NULL, LOG_NOTICE,
380 "can not build the query message for %s, in resolvers %s.\n",
381 resolution->hostname_dn, resolvers->id);
382 return -1;
383 }
Emeric Brunc9437992021-02-12 19:42:55 +0100384
385 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunc37caab2021-10-29 16:28:33 +0200386 if (dns_send_nameserver(ns, trash.area, len) >= 0)
Emeric Brunc9437992021-02-12 19:42:55 +0100387 resolution->nb_queries++;
388 }
389
390 /* Push the resolution at the end of the active list */
Willy Tarreauaae73202021-10-19 22:01:36 +0200391 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200392 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100393 return 0;
394}
395
396/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
397 * skipped and -1 if an error occurred.
398 */
399static int
400resolv_run_resolution(struct resolv_resolution *resolution)
401{
402 struct resolvers *resolvers = resolution->resolvers;
403 int query_id, i;
404
405 /* Avoid sending requests for resolutions that don't yet have an
406 * hostname, ie resolutions linked to servers that do not yet have an
407 * fqdn */
408 if (!resolution->hostname_dn)
409 return 0;
410
411 /* Check if a resolution has already been started for this server return
412 * directly to avoid resolution pill up. */
413 if (resolution->step != RSLV_STEP_NONE)
414 return 0;
415
416 /* Generates a new query id. We try at most 100 times to find a free
417 * query id */
418 for (i = 0; i < 100; ++i) {
419 query_id = resolv_rnd16();
420 if (!eb32_lookup(&resolvers->query_ids, query_id))
421 break;
422 query_id = -1;
423 }
424 if (query_id == -1) {
425 send_log(NULL, LOG_NOTICE,
426 "could not generate a query id for %s, in resolvers %s.\n",
427 resolution->hostname_dn, resolvers->id);
428 return -1;
429 }
430
431 /* Update resolution parameters */
432 resolution->query_id = query_id;
433 resolution->qid.key = query_id;
434 resolution->step = RSLV_STEP_RUNNING;
435 resolution->query_type = resolution->prefered_query_type;
436 resolution->try = resolvers->resolve_retries;
437 eb32_insert(&resolvers->query_ids, &resolution->qid);
438
439 /* Send the DNS query */
440 resolution->try -= 1;
441 resolv_send_query(resolution);
442 return 1;
443}
444
445/* Performs a name resolution for the requester <req> */
446void resolv_trigger_resolution(struct resolv_requester *req)
447{
448 struct resolvers *resolvers;
449 struct resolv_resolution *res;
450 int exp;
451
452 if (!req || !req->resolution)
453 return;
454 res = req->resolution;
455 resolvers = res->resolvers;
456
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100457 enter_resolver_code();
458
Emeric Brunc9437992021-02-12 19:42:55 +0100459 /* The resolution must not be triggered yet. Use the cached response, if
460 * valid */
461 exp = tick_add(res->last_resolution, resolvers->hold.valid);
462 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
463 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
464 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100465
466 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100467}
468
469
470/* Resets some resolution parameters to initial values and also delete the query
471 * ID from the resolver's tree.
472 */
473static void resolv_reset_resolution(struct resolv_resolution *resolution)
474{
475 /* update resolution status */
476 resolution->step = RSLV_STEP_NONE;
477 resolution->try = 0;
478 resolution->last_resolution = now_ms;
479 resolution->nb_queries = 0;
480 resolution->nb_responses = 0;
481 resolution->query_type = resolution->prefered_query_type;
482
483 /* clean up query id */
484 eb32_delete(&resolution->qid);
485 resolution->query_id = 0;
486 resolution->qid.key = 0;
487}
488
489/* Returns the query id contained in a DNS response */
490static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
491{
492 return resp[0] * 256 + resp[1];
493}
494
495
496/* Analyses, re-builds and copies the name <name> from the DNS response packet
497 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
498 * for compressed data. The result is copied into <dest>, ensuring we don't
499 * overflow using <dest_len> Returns the number of bytes the caller can move
500 * forward. If 0 it means an error occurred while parsing the name. <offset> is
501 * the number of bytes the caller could move forward.
502 */
503int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
504 unsigned char *name, char *destination, int dest_len,
505 int *offset, unsigned int depth)
506{
507 int nb_bytes = 0, n = 0;
508 int label_len;
509 unsigned char *reader = name;
510 char *dest = destination;
511
512 while (1) {
513 if (reader >= bufend)
514 goto err;
515
516 /* Name compression is in use */
517 if ((*reader & 0xc0) == 0xc0) {
518 if (reader + 1 >= bufend)
519 goto err;
520
521 /* Must point BEFORE current position */
522 if ((buffer + reader[1]) > reader)
523 goto err;
524
525 if (depth++ > 100)
526 goto err;
527
528 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
529 dest, dest_len - nb_bytes, offset, depth);
530 if (n == 0)
531 goto err;
532
533 dest += n;
534 nb_bytes += n;
535 goto out;
536 }
537
538 label_len = *reader;
539 if (label_len == 0)
540 goto out;
541
542 /* Check if:
543 * - we won't read outside the buffer
544 * - there is enough place in the destination
545 */
546 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
547 goto err;
548
549 /* +1 to take label len + label string */
550 label_len++;
551
552 memcpy(dest, reader, label_len);
553
554 dest += label_len;
555 nb_bytes += label_len;
556 reader += label_len;
557 }
558
559 out:
560 /* offset computation:
561 * parse from <name> until finding either NULL or a pointer "c0xx"
562 */
563 reader = name;
564 *offset = 0;
565 while (reader < bufend) {
566 if ((reader[0] & 0xc0) == 0xc0) {
567 *offset += 2;
568 break;
569 }
570 else if (*reader == 0) {
571 *offset += 1;
572 break;
573 }
574 *offset += 1;
575 ++reader;
576 }
577 return nb_bytes;
578
579 err:
580 return 0;
581}
582
Willy Tarreauf766ec62021-10-18 16:46:38 +0200583/* Reinitialize the list of aborted resolutions before calling certain
584 * functions relying on it. The list must be processed by calling
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100585 * leave_resolver_code() after operations.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200586 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100587static void enter_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200588{
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100589 if (!recurse)
590 LIST_INIT(&death_row);
591 recurse++;
Willy Tarreauf766ec62021-10-18 16:46:38 +0200592}
593
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100594/* Add a resolution to the death_row. */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200595static void abort_resolution(struct resolv_resolution *res)
596{
597 LIST_DEL_INIT(&res->list);
598 LIST_APPEND(&death_row, &res->list);
599}
600
601/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100602 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreauf766ec62021-10-18 16:46:38 +0200603 * needs to defer deletions. Note that some of them are in relation via internal
604 * objects and might cause the deletion of other ones from the same list, so we
605 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
606 * and solely rely on each call to remove the first remaining list element.
607 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100608static void leave_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200609{
610 struct resolv_resolution *res;
611
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100612 recurse--;
613 if (recurse)
614 return;
615
Willy Tarreauf766ec62021-10-18 16:46:38 +0200616 while (!LIST_ISEMPTY(&death_row)) {
617 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
618 resolv_free_resolution(res);
619 }
620
621 /* make sure nobody tries to add anything without having initialized it */
622 death_row = (struct list){ };
623}
624
Christopher Faulet11c6c392021-06-15 16:08:48 +0200625/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
626 * happens when an SRV item is purged or when the server status is considered as
627 * obsolete.
628 *
Willy Tarreauf766ec62021-10-18 16:46:38 +0200629 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100630 * initialized via enter_resolver_code().
Christopher Faulet11c6c392021-06-15 16:08:48 +0200631 */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200632static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet11c6c392021-06-15 16:08:48 +0200633{
Willy Tarreau6878f802021-10-20 14:07:31 +0200634 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200635 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
636 srvrq_update_srv_status(srv, 1);
637 ha_free(&srv->hostname);
638 ha_free(&srv->hostname_dn);
639 srv->hostname_dn_len = 0;
640 memset(&srv->addr, 0, sizeof(srv->addr));
641 srv->svc_port = 0;
642 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet73001ab2021-06-15 16:14:37 +0200643
644 ebpt_delete(&srv->host_dn);
645 ha_free(&srv->host_dn.key);
646
Christopher Faulet11c6c392021-06-15 16:08:48 +0200647 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreauaae73202021-10-19 22:01:36 +0200648 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200649 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Fauletdcac4182021-06-15 16:17:17 +0200650
651 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet11c6c392021-06-15 16:08:48 +0200652}
653
Christopher Fauletdcac4182021-06-15 16:17:17 +0200654/* Takes care to cleanup a server resolution when it is outdated. This only
655 * happens for a server relying on a SRV record.
656 */
657static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
658{
659 struct server *srv = context;
660
661 if (!tick_is_expired(t->expire, now_ms))
662 goto end;
663
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100664 enter_resolver_code();
Christopher Faulete886dd52021-06-18 09:05:49 +0200665 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreauf766ec62021-10-18 16:46:38 +0200666 resolv_srvrq_cleanup_srv(srv);
Christopher Faulete886dd52021-06-18 09:05:49 +0200667 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100668 leave_resolver_code();
Christopher Fauletdcac4182021-06-15 16:17:17 +0200669
670 end:
671 return t;
672}
673
Emeric Brunc9437992021-02-12 19:42:55 +0100674/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100675 * find a corresponding server.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200676 */
Emeric Brunc9437992021-02-12 19:42:55 +0100677static void resolv_check_response(struct resolv_resolution *res)
678{
679 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100680 struct resolv_requester *req;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200681 struct eb32_node *eb32, *eb32_back;
Emeric Brunbd78c912021-06-11 10:08:05 +0200682 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100683 struct resolv_srvrq *srvrq;
684
Willy Tarreau7893ae12021-10-21 07:39:57 +0200685 for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
686 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
Emeric Brunc9437992021-02-12 19:42:55 +0100687 struct resolv_answer_item *ar_item = item->ar_item;
688
689 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100690 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100691 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
692 * item is also obsolete.
693 */
Emeric Brunc9437992021-02-12 19:42:55 +0100694 pool_free(resolv_answer_item_pool, ar_item);
695 item->ar_item = NULL;
696 }
697
698 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100699 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200700 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100701 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200702 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
703 LIST_DEL_INIT(&srv->ip_rec_item);
704 }
705 }
706 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun34067662021-06-11 10:48:45 +0200707 /* Remove any associated server */
Christopher Faulet11c6c392021-06-15 16:08:48 +0200708 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreauf766ec62021-10-18 16:46:38 +0200709 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100710 }
711
Willy Tarreau7893ae12021-10-21 07:39:57 +0200712 eb32_delete(&item->link);
Emeric Brunc9437992021-02-12 19:42:55 +0100713 if (item->ar_item) {
714 pool_free(resolv_answer_item_pool, item->ar_item);
715 item->ar_item = NULL;
716 }
717 pool_free(resolv_answer_item_pool, item);
718 continue;
719 }
720
721 if (item->type != DNS_RTYPE_SRV)
722 continue;
723
724 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100725 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun34067662021-06-11 10:48:45 +0200726 struct ebpt_node *node;
727 char target[DNS_MAX_NAME_SIZE+1];
728
729 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100730 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
731 continue;
732
Emeric Brun34067662021-06-11 10:48:45 +0200733 /* Check if a server already uses that record */
734 srv = NULL;
735 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
736 if (srv->srvrq == srvrq) {
737 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
738 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100739 }
Emeric Brunc9437992021-02-12 19:42:55 +0100740 }
741
Emeric Brun34067662021-06-11 10:48:45 +0200742
743 /* If not empty we try to match a server
744 * in server state file tree with the same hostname
745 */
746 if (!eb_is_empty(&srvrq->named_servers)) {
747 srv = NULL;
748
749 /* convert the key to lookup in lower case */
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200750 for (i = 0 ; item->data.target[i] ; i++)
751 target[i] = tolower(item->data.target[i]);
Christopher Faulet1f923392021-07-22 14:29:26 +0200752 target[i] = 0;
Emeric Brun34067662021-06-11 10:48:45 +0200753
754 node = ebis_lookup(&srvrq->named_servers, target);
755 if (node) {
756 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100757 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun34067662021-06-11 10:48:45 +0200758
759 /* an entry was found with the same hostname
760 * let check this node if the port matches
761 * and try next node if the hostname
762 * is still the same
763 */
764 while (1) {
765 if (srv->svc_port == item->port) {
766 /* server found, we remove it from tree */
767 ebpt_delete(node);
Christopher Faulet73001ab2021-06-15 16:14:37 +0200768 ha_free(&srv->host_dn.key);
Emeric Brun34067662021-06-11 10:48:45 +0200769 goto srv_found;
770 }
771
772 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
773
774 node = ebpt_next(node);
775 if (!node)
776 break;
777
778 srv = ebpt_entry(node, struct server, host_dn);
779 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
780
781 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau75cc6532021-10-15 08:53:44 +0200782 || memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
Emeric Brun34067662021-06-11 10:48:45 +0200783 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
784 break;
785 }
786 }
Emeric Brunc9437992021-02-12 19:42:55 +0100787 }
788 }
Emeric Brun34067662021-06-11 10:48:45 +0200789
790 /* Pick the first server listed in srvrq (those ones don't
791 * have hostname and are free to use)
792 */
793 srv = NULL;
794 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
795 LIST_DEL_INIT(&srv->srv_rec_item);
796 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
797 goto srv_found;
798 }
799 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100800
Emeric Brun34067662021-06-11 10:48:45 +0200801srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100802 /* And update this server, if found (srv is locked here) */
803 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100804 /* re-enable DNS resolution for this server by default */
805 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Fauletdcac4182021-06-15 16:17:17 +0200806 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100807
Emeric Brunc9437992021-02-12 19:42:55 +0100808 /* Check if an Additional Record is associated to this SRV record.
809 * Perform some sanity checks too to ensure the record can be used.
810 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100811 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100812 */
813 if ((item->ar_item != NULL) &&
814 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100815 {
Emeric Brunc9437992021-02-12 19:42:55 +0100816
817 switch (item->ar_item->type) {
818 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200819 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100820 break;
821 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200822 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100823 break;
824 }
825
826 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100827
828 /* Unlink A/AAAA resolution for this server if there is an AR item.
829 * It is usless to perform an extra resolution
830 */
Willy Tarreau6878f802021-10-20 14:07:31 +0200831 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100832 }
833
834 if (!srv->hostname_dn) {
835 const char *msg = NULL;
Willy Tarreau85c15e62021-10-14 08:00:38 +0200836 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100837
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200838 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau85c15e62021-10-14 08:00:38 +0200839 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100840 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
841 continue;
842 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100843 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100844 if (msg)
845 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
846 }
847
Emeric Brun34067662021-06-11 10:48:45 +0200848 if (!LIST_INLIST(&srv->srv_rec_item))
849 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
850
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100851 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
852 /* If there is no AR item responsible of the FQDN resolution,
853 * trigger a dedicated DNS resolution
854 */
855 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
856 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
857 }
858
Christopher Fauletab177ac2021-03-10 15:34:52 +0100859 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100860 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100861
862 srv->svc_port = item->port;
863 srv->flags &= ~SRV_F_MAPPORTS;
864
865 if (!srv->resolv_opts.ignore_weight) {
866 char weight[9];
867 int ha_weight;
868
869 /* DNS weight range if from 0 to 65535
870 * HAProxy weight is from 0 to 256
871 * The rule below ensures that weight 0 is well respected
872 * while allowing a "mapping" from DNS weight into HAProxy's one.
873 */
874 ha_weight = (item->weight + 255) / 256;
875
876 snprintf(weight, sizeof(weight), "%d", ha_weight);
877 server_parse_weight_change_request(srv, weight);
878 }
879 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
880 }
881 }
882 }
883}
884
885/* Validates that the buffer DNS response provided in <resp> and finishing
886 * before <bufend> is valid from a DNS protocol point of view.
887 *
888 * The result is stored in <resolution>' response, buf_response,
889 * response_query_records and response_answer_records members.
890 *
891 * This function returns one of the RSLV_RESP_* code to indicate the type of
892 * error found.
893 */
894static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
895 struct resolv_resolution *resolution, int max_answer_records)
896{
897 unsigned char *reader;
898 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
899 int len, flags, offset;
Emeric Brunc9437992021-02-12 19:42:55 +0100900 int nb_saved_records;
901 struct resolv_query_item *query;
902 struct resolv_answer_item *answer_record, *tmp_record;
903 struct resolv_response *r_res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200904 struct eb32_node *eb32;
Willy Tarreaudcb696c2021-10-21 08:18:01 +0200905 uint32_t key = 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100906 int i, found = 0;
907 int cause = RSLV_RESP_ERROR;
908
909 reader = resp;
910 len = 0;
911 previous_dname = NULL;
912 query = NULL;
913 answer_record = NULL;
914
915 /* Initialization of response buffer and structure */
916 r_res = &resolution->response;
917
918 /* query id */
919 if (reader + 2 >= bufend)
920 goto invalid_resp;
921
922 r_res->header.id = reader[0] * 256 + reader[1];
923 reader += 2;
924
925 /* Flags and rcode are stored over 2 bytes
926 * First byte contains:
927 * - response flag (1 bit)
928 * - opcode (4 bits)
929 * - authoritative (1 bit)
930 * - truncated (1 bit)
931 * - recursion desired (1 bit)
932 */
933 if (reader + 2 >= bufend)
934 goto invalid_resp;
935
936 flags = reader[0] * 256 + reader[1];
937
938 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
939 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
940 cause = RSLV_RESP_NX_DOMAIN;
941 goto return_error;
942 }
943 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
944 cause = RSLV_RESP_REFUSED;
945 goto return_error;
946 }
947 else {
948 cause = RSLV_RESP_ERROR;
949 goto return_error;
950 }
951 }
952
953 /* Move forward 2 bytes for flags */
954 reader += 2;
955
956 /* 2 bytes for question count */
957 if (reader + 2 >= bufend)
958 goto invalid_resp;
959 r_res->header.qdcount = reader[0] * 256 + reader[1];
960 /* (for now) we send one query only, so we expect only one in the
961 * response too */
962 if (r_res->header.qdcount != 1) {
963 cause = RSLV_RESP_QUERY_COUNT_ERROR;
964 goto return_error;
965 }
966
967 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
968 goto invalid_resp;
969 reader += 2;
970
971 /* 2 bytes for answer count */
972 if (reader + 2 >= bufend)
973 goto invalid_resp;
974 r_res->header.ancount = reader[0] * 256 + reader[1];
975 if (r_res->header.ancount == 0) {
976 cause = RSLV_RESP_ANCOUNT_ZERO;
977 goto return_error;
978 }
979
980 /* Check if too many records are announced */
981 if (r_res->header.ancount > max_answer_records)
982 goto invalid_resp;
983 reader += 2;
984
985 /* 2 bytes authority count */
986 if (reader + 2 >= bufend)
987 goto invalid_resp;
988 r_res->header.nscount = reader[0] * 256 + reader[1];
989 reader += 2;
990
991 /* 2 bytes additional count */
992 if (reader + 2 >= bufend)
993 goto invalid_resp;
994 r_res->header.arcount = reader[0] * 256 + reader[1];
995 reader += 2;
996
Christopher Fauletc1699f82021-12-01 15:07:26 +0100997 /* Parsing dns queries. For now there is only one query and it exists
998 * because (qdcount == 1).
999 */
1000 query = &resolution->response_query_records[0];
Emeric Brunc9437992021-02-12 19:42:55 +01001001
Christopher Fauletc1699f82021-12-01 15:07:26 +01001002 /* Name is a NULL terminated string in our case, since we have
1003 * one query per response and the first one can't be compressed
1004 * (using the 0x0c format) */
1005 offset = 0;
1006 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01001007
Christopher Fauletc1699f82021-12-01 15:07:26 +01001008 if (len == 0)
1009 goto invalid_resp;
Emeric Brunc9437992021-02-12 19:42:55 +01001010
Christopher Fauletc1699f82021-12-01 15:07:26 +01001011 /* Now let's check the query's dname corresponds to the one we sent. */
1012 if (len != resolution->hostname_dn_len ||
1013 memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
1014 cause = RSLV_RESP_WRONG_NAME;
Christopher Fauletaf93d2f2021-12-02 10:05:02 +01001015 goto return_error;
Christopher Fauletc1699f82021-12-01 15:07:26 +01001016 }
Emeric Brunc9437992021-02-12 19:42:55 +01001017
Christopher Fauletc1699f82021-12-01 15:07:26 +01001018 reader += offset;
1019 previous_dname = query->name;
Emeric Brunc9437992021-02-12 19:42:55 +01001020
Christopher Fauletc1699f82021-12-01 15:07:26 +01001021 /* move forward 2 bytes for question type */
1022 if (reader + 2 >= bufend)
1023 goto invalid_resp;
1024 query->type = reader[0] * 256 + reader[1];
1025 reader += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001026
Christopher Fauletc1699f82021-12-01 15:07:26 +01001027 /* move forward 2 bytes for question class */
1028 if (reader + 2 >= bufend)
1029 goto invalid_resp;
1030 query->class = reader[0] * 256 + reader[1];
1031 reader += 2;
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001032
Emeric Brunc9437992021-02-12 19:42:55 +01001033 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001034 * because a TRUNCATED SRV query type response can still be exploited
1035 */
Emeric Brunc9437992021-02-12 19:42:55 +01001036 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1037 cause = RSLV_RESP_TRUNCATED;
1038 goto return_error;
1039 }
1040
1041 /* now parsing response records */
1042 nb_saved_records = 0;
1043 for (i = 0; i < r_res->header.ancount; i++) {
1044 if (reader >= bufend)
1045 goto invalid_resp;
1046
1047 answer_record = pool_alloc(resolv_answer_item_pool);
1048 if (answer_record == NULL)
1049 goto invalid_resp;
1050
1051 /* initialization */
1052 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001053 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001054 LIST_INIT(&answer_record->attached_servers);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001055 answer_record->link.node.leaf_p = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001056
1057 offset = 0;
1058 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1059
1060 if (len == 0)
1061 goto invalid_resp;
1062
1063 /* Check if the current record dname is valid. previous_dname
1064 * points either to queried dname or last CNAME target */
Willy Tarreau75cc6532021-10-15 08:53:44 +02001065 if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001066 if (i == 0) {
1067 /* First record, means a mismatch issue between
1068 * queried dname and dname found in the first
1069 * record */
1070 goto invalid_resp;
1071 }
1072 else {
1073 /* If not the first record, this means we have a
1074 * CNAME resolution error.
1075 */
1076 cause = RSLV_RESP_CNAME_ERROR;
1077 goto return_error;
1078 }
1079
1080 }
1081
1082 memcpy(answer_record->name, tmpname, len);
1083 answer_record->name[len] = 0;
1084
1085 reader += offset;
1086 if (reader >= bufend)
1087 goto invalid_resp;
1088
1089 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1090 if (reader + 2 > bufend)
1091 goto invalid_resp;
1092
1093 answer_record->type = reader[0] * 256 + reader[1];
1094 reader += 2;
1095
1096 /* 2 bytes for class (2) */
1097 if (reader + 2 > bufend)
1098 goto invalid_resp;
1099
1100 answer_record->class = reader[0] * 256 + reader[1];
1101 reader += 2;
1102
1103 /* 4 bytes for ttl (4) */
1104 if (reader + 4 > bufend)
1105 goto invalid_resp;
1106
1107 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1108 + reader[2] * 256 + reader[3];
1109 reader += 4;
1110
1111 /* Now reading data len */
1112 if (reader + 2 > bufend)
1113 goto invalid_resp;
1114
1115 answer_record->data_len = reader[0] * 256 + reader[1];
1116
1117 /* Move forward 2 bytes for data len */
1118 reader += 2;
1119
1120 if (reader + answer_record->data_len > bufend)
1121 goto invalid_resp;
1122
1123 /* Analyzing record content */
1124 switch (answer_record->type) {
1125 case DNS_RTYPE_A:
1126 /* ipv4 is stored on 4 bytes */
1127 if (answer_record->data_len != 4)
1128 goto invalid_resp;
1129
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001130 answer_record->data.in4.sin_family = AF_INET;
1131 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001132 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001133 break;
1134
1135 case DNS_RTYPE_CNAME:
1136 /* Check if this is the last record and update the caller about the status:
1137 * no IP could be found and last record was a CNAME. Could be triggered
1138 * by a wrong query type
1139 *
1140 * + 1 because answer_record_id starts at 0
1141 * while number of answers is an integer and
1142 * starts at 1.
1143 */
1144 if (i + 1 == r_res->header.ancount) {
1145 cause = RSLV_RESP_CNAME_ERROR;
1146 goto return_error;
1147 }
1148
1149 offset = 0;
1150 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1151 if (len == 0)
1152 goto invalid_resp;
1153
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001154 memcpy(answer_record->data.target, tmpname, len);
1155 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001156 key = XXH32(tmpname, len, answer_record->type);
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001157 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001158 break;
1159
1160
1161 case DNS_RTYPE_SRV:
1162 /* Answer must contain :
1163 * - 2 bytes for the priority
1164 * - 2 bytes for the weight
1165 * - 2 bytes for the port
1166 * - the target hostname
1167 */
1168 if (answer_record->data_len <= 6)
1169 goto invalid_resp;
1170
1171 answer_record->priority = read_n16(reader);
1172 reader += sizeof(uint16_t);
1173 answer_record->weight = read_n16(reader);
1174 reader += sizeof(uint16_t);
1175 answer_record->port = read_n16(reader);
1176 reader += sizeof(uint16_t);
1177 offset = 0;
1178 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1179 if (len == 0)
1180 goto invalid_resp;
1181
1182 answer_record->data_len = len;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001183 memcpy(answer_record->data.target, tmpname, len);
1184 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001185 key = XXH32(tmpname, len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001186 if (answer_record->ar_item != NULL) {
1187 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1188 answer_record->ar_item = NULL;
1189 }
1190 break;
1191
1192 case DNS_RTYPE_AAAA:
1193 /* ipv6 is stored on 16 bytes */
1194 if (answer_record->data_len != 16)
1195 goto invalid_resp;
1196
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001197 answer_record->data.in6.sin6_family = AF_INET6;
1198 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001199 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001200 break;
1201
1202 } /* switch (record type) */
1203
1204 /* Increment the counter for number of records saved into our
1205 * local response */
1206 nb_saved_records++;
1207
1208 /* Move forward answer_record->data_len for analyzing next
1209 * record in the response */
1210 reader += ((answer_record->type == DNS_RTYPE_SRV)
1211 ? offset
1212 : answer_record->data_len);
1213
1214 /* Lookup to see if we already had this entry */
1215 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001216
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001217 for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02001218 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001219 if (tmp_record->type != answer_record->type)
1220 continue;
1221
1222 switch(tmp_record->type) {
1223 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001224 if (!memcmp(&answer_record->data.in4.sin_addr,
1225 &tmp_record->data.in4.sin_addr,
1226 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001227 found = 1;
1228 break;
1229
1230 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001231 if (!memcmp(&answer_record->data.in6.sin6_addr,
1232 &tmp_record->data.in6.sin6_addr,
1233 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001234 found = 1;
1235 break;
1236
1237 case DNS_RTYPE_SRV:
1238 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001239 memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
Emeric Brunc9437992021-02-12 19:42:55 +01001240 answer_record->port == tmp_record->port) {
1241 tmp_record->weight = answer_record->weight;
1242 found = 1;
1243 }
1244 break;
1245
1246 default:
1247 break;
1248 }
1249
1250 if (found == 1)
1251 break;
1252 }
1253
1254 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001255 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001256 pool_free(resolv_answer_item_pool, answer_record);
1257 answer_record = NULL;
1258 }
1259 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001260 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001261 answer_record->ar_item = NULL;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001262 answer_record->link.key = key;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001263 eb32_insert(&r_res->answer_tree, &answer_record->link);
Emeric Brunc9437992021-02-12 19:42:55 +01001264 answer_record = NULL;
1265 }
1266 } /* for i 0 to ancount */
1267
1268 /* Save the number of records we really own */
1269 r_res->header.ancount = nb_saved_records;
1270
1271 /* now parsing additional records for SRV queries only */
1272 if (query->type != DNS_RTYPE_SRV)
1273 goto skip_parsing_additional_records;
1274
1275 /* if we find Authority records, just skip them */
1276 for (i = 0; i < r_res->header.nscount; i++) {
1277 offset = 0;
1278 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1279 &offset, 0);
1280 if (len == 0)
1281 continue;
1282
1283 if (reader + offset + 10 >= bufend)
1284 goto invalid_resp;
1285
1286 reader += offset;
1287 /* skip 2 bytes for class */
1288 reader += 2;
1289 /* skip 2 bytes for type */
1290 reader += 2;
1291 /* skip 4 bytes for ttl */
1292 reader += 4;
1293 /* read data len */
1294 len = reader[0] * 256 + reader[1];
1295 reader += 2;
1296
1297 if (reader + len >= bufend)
1298 goto invalid_resp;
1299
1300 reader += len;
1301 }
1302
1303 nb_saved_records = 0;
1304 for (i = 0; i < r_res->header.arcount; i++) {
1305 if (reader >= bufend)
1306 goto invalid_resp;
1307
1308 answer_record = pool_alloc(resolv_answer_item_pool);
1309 if (answer_record == NULL)
1310 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001311 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001312 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001313
1314 offset = 0;
1315 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1316
1317 if (len == 0) {
1318 pool_free(resolv_answer_item_pool, answer_record);
1319 answer_record = NULL;
1320 continue;
1321 }
1322
1323 memcpy(answer_record->name, tmpname, len);
1324 answer_record->name[len] = 0;
1325
1326 reader += offset;
1327 if (reader >= bufend)
1328 goto invalid_resp;
1329
1330 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1331 if (reader + 2 > bufend)
1332 goto invalid_resp;
1333
1334 answer_record->type = reader[0] * 256 + reader[1];
1335 reader += 2;
1336
1337 /* 2 bytes for class (2) */
1338 if (reader + 2 > bufend)
1339 goto invalid_resp;
1340
1341 answer_record->class = reader[0] * 256 + reader[1];
1342 reader += 2;
1343
1344 /* 4 bytes for ttl (4) */
1345 if (reader + 4 > bufend)
1346 goto invalid_resp;
1347
1348 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1349 + reader[2] * 256 + reader[3];
1350 reader += 4;
1351
1352 /* Now reading data len */
1353 if (reader + 2 > bufend)
1354 goto invalid_resp;
1355
1356 answer_record->data_len = reader[0] * 256 + reader[1];
1357
1358 /* Move forward 2 bytes for data len */
1359 reader += 2;
1360
1361 if (reader + answer_record->data_len > bufend)
1362 goto invalid_resp;
1363
1364 /* Analyzing record content */
1365 switch (answer_record->type) {
1366 case DNS_RTYPE_A:
1367 /* ipv4 is stored on 4 bytes */
1368 if (answer_record->data_len != 4)
1369 goto invalid_resp;
1370
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001371 answer_record->data.in4.sin_family = AF_INET;
1372 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001373 break;
1374
1375 case DNS_RTYPE_AAAA:
1376 /* ipv6 is stored on 16 bytes */
1377 if (answer_record->data_len != 16)
1378 goto invalid_resp;
1379
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001380 answer_record->data.in6.sin6_family = AF_INET6;
1381 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001382 break;
1383
1384 default:
1385 pool_free(resolv_answer_item_pool, answer_record);
1386 answer_record = NULL;
1387 continue;
1388
1389 } /* switch (record type) */
1390
1391 /* Increment the counter for number of records saved into our
1392 * local response */
1393 nb_saved_records++;
1394
1395 /* Move forward answer_record->data_len for analyzing next
1396 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001397 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001398
1399 /* Lookup to see if we already had this entry */
1400 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001401
1402 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001403 struct resolv_answer_item *ar_item;
1404
Willy Tarreau7893ae12021-10-21 07:39:57 +02001405 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Christopher Faulet77f86062021-03-10 15:19:57 +01001406 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1407 continue;
1408
1409 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001410 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001411 len != tmp_record->data_len ||
Willy Tarreau75cc6532021-10-15 08:53:44 +02001412 memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001413 continue;
1414
Christopher Faulet77f86062021-03-10 15:19:57 +01001415 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001416 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001417 if (!memcmp(&answer_record->data.in4.sin_addr,
1418 &ar_item->data.in4.sin_addr,
1419 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001420 found = 1;
1421 break;
1422
1423 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001424 if (!memcmp(&answer_record->data.in6.sin6_addr,
1425 &ar_item->data.in6.sin6_addr,
1426 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001427 found = 1;
1428 break;
1429
1430 default:
1431 break;
1432 }
1433
1434 if (found == 1)
1435 break;
1436 }
1437
1438 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001439 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001440 pool_free(resolv_answer_item_pool, answer_record);
1441 answer_record = NULL;
1442 }
1443 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001444 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001445 answer_record->ar_item = NULL;
1446
1447 // looking for the SRV record in the response list linked to this additional record
Willy Tarreau7893ae12021-10-21 07:39:57 +02001448 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
1449 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
1450
Emeric Brunc9437992021-02-12 19:42:55 +01001451 if (tmp_record->type == DNS_RTYPE_SRV &&
1452 tmp_record->ar_item == NULL &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001453 memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001454 /* Always use the received additional record to refresh info */
1455 if (tmp_record->ar_item)
1456 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1457 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001458 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001459 break;
1460 }
1461 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001462 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001463 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001464 answer_record = NULL;
1465 }
Emeric Brunc9437992021-02-12 19:42:55 +01001466 }
1467 } /* for i 0 to arcount */
1468
1469 skip_parsing_additional_records:
1470
1471 /* Save the number of records we really own */
1472 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001473 resolv_check_response(resolution);
1474 return RSLV_RESP_VALID;
1475
1476 invalid_resp:
1477 cause = RSLV_RESP_INVALID;
1478
1479 return_error:
1480 pool_free(resolv_answer_item_pool, answer_record);
1481 return cause;
1482}
1483
1484/* Searches dn_name resolution in resp.
1485 * If existing IP not found, return the first IP matching family_priority,
1486 * otherwise, first ip found
1487 * The following tasks are the responsibility of the caller:
1488 * - <r_res> contains an error free DNS response
1489 * For both cases above, resolv_validate_dns_response is required
1490 * returns one of the RSLV_UPD_* code
1491 */
1492int resolv_get_ip_from_response(struct resolv_response *r_res,
1493 struct resolv_options *resolv_opts, void *currentip,
1494 short currentip_sin_family,
1495 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001496 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001497{
Emeric Brunbd78c912021-06-11 10:08:05 +02001498 struct resolv_answer_item *record, *found_record = NULL;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001499 struct eb32_node *eb32;
Emeric Brunc9437992021-02-12 19:42:55 +01001500 int family_priority;
1501 int currentip_found;
1502 unsigned char *newip4, *newip6;
1503 int currentip_sel;
1504 int j;
1505 int score, max_score;
1506 int allowed_duplicated_ip;
1507
Emeric Brunbd78c912021-06-11 10:08:05 +02001508 /* srv is linked to an alive ip record */
1509 if (owner && LIST_INLIST(&owner->ip_rec_item))
1510 return RSLV_UPD_NO;
1511
Emeric Brunc9437992021-02-12 19:42:55 +01001512 family_priority = resolv_opts->family_prio;
1513 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1514 *newip = newip4 = newip6 = NULL;
1515 currentip_found = 0;
1516 *newip_sin_family = AF_UNSPEC;
1517 max_score = -1;
1518
1519 /* Select an IP regarding configuration preference.
1520 * Top priority is the preferred network ip version,
1521 * second priority is the preferred network.
1522 * the last priority is the currently used IP,
1523 *
1524 * For these three priorities, a score is calculated. The
1525 * weight are:
1526 * 8 - preferred ip version.
1527 * 4 - preferred network.
1528 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1529 * 1 - current ip.
1530 * The result with the biggest score is returned.
1531 */
1532
Willy Tarreau7893ae12021-10-21 07:39:57 +02001533 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001534 void *ip;
1535 unsigned char ip_type;
1536
Willy Tarreau7893ae12021-10-21 07:39:57 +02001537 record = eb32_entry(eb32, typeof(*record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001538 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001539 ip_type = AF_INET;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001540 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001541 }
1542 else if (record->type == DNS_RTYPE_AAAA) {
1543 ip_type = AF_INET6;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001544 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001545 }
1546 else
1547 continue;
1548 score = 0;
1549
1550 /* Check for preferred ip protocol. */
1551 if (ip_type == family_priority)
1552 score += 8;
1553
1554 /* Check for preferred network. */
1555 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1556
1557 /* Compare only the same addresses class. */
1558 if (resolv_opts->pref_net[j].family != ip_type)
1559 continue;
1560
1561 if ((ip_type == AF_INET &&
1562 in_net_ipv4(ip,
1563 &resolv_opts->pref_net[j].mask.in4,
1564 &resolv_opts->pref_net[j].addr.in4)) ||
1565 (ip_type == AF_INET6 &&
1566 in_net_ipv6(ip,
1567 &resolv_opts->pref_net[j].mask.in6,
1568 &resolv_opts->pref_net[j].addr.in6))) {
1569 score += 4;
1570 break;
1571 }
1572 }
1573
1574 /* Check if the IP found in the record is already affected to a
1575 * member of a group. If not, the score should be incremented
1576 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001577 if (owner) {
1578 struct server *srv;
1579 int already_used = 0;
1580
1581 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1582 if (srv == owner)
1583 continue;
1584 if (srv->proxy == owner->proxy) {
1585 already_used = 1;
1586 break;
1587 }
1588 }
1589 if (already_used) {
1590 if (!allowed_duplicated_ip) {
1591 continue;
1592 }
1593 }
1594 else {
1595 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001596 }
1597 } else {
1598 score += 2;
1599 }
1600
1601 /* Check for current ip matching. */
1602 if (ip_type == currentip_sin_family &&
1603 ((currentip_sin_family == AF_INET &&
1604 !memcmp(ip, currentip, 4)) ||
1605 (currentip_sin_family == AF_INET6 &&
1606 !memcmp(ip, currentip, 16)))) {
1607 score++;
1608 currentip_sel = 1;
1609 }
1610 else
1611 currentip_sel = 0;
1612
1613 /* Keep the address if the score is better than the previous
1614 * score. The maximum score is 15, if this value is reached, we
1615 * break the parsing. Implicitly, this score is reached the ip
1616 * selected is the current ip. */
1617 if (score > max_score) {
1618 if (ip_type == AF_INET)
1619 newip4 = ip;
1620 else
1621 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001622 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001623 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001624 if (score == 15) {
1625 /* this was not registered on the current record but it matches
1626 * let's fix it (it may comes from state file */
1627 if (owner)
1628 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001629 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001630 }
Emeric Brunc9437992021-02-12 19:42:55 +01001631 max_score = score;
1632 }
1633 } /* list for each record entries */
1634
1635 /* No IP found in the response */
1636 if (!newip4 && !newip6)
1637 return RSLV_UPD_NO_IP_FOUND;
1638
1639 /* Case when the caller looks first for an IPv4 address */
1640 if (family_priority == AF_INET) {
1641 if (newip4) {
1642 *newip = newip4;
1643 *newip_sin_family = AF_INET;
1644 }
1645 else if (newip6) {
1646 *newip = newip6;
1647 *newip_sin_family = AF_INET6;
1648 }
Emeric Brunc9437992021-02-12 19:42:55 +01001649 }
1650 /* Case when the caller looks first for an IPv6 address */
1651 else if (family_priority == AF_INET6) {
1652 if (newip6) {
1653 *newip = newip6;
1654 *newip_sin_family = AF_INET6;
1655 }
1656 else if (newip4) {
1657 *newip = newip4;
1658 *newip_sin_family = AF_INET;
1659 }
Emeric Brunc9437992021-02-12 19:42:55 +01001660 }
1661 /* Case when the caller have no preference (we prefer IPv6) */
1662 else if (family_priority == AF_UNSPEC) {
1663 if (newip6) {
1664 *newip = newip6;
1665 *newip_sin_family = AF_INET6;
1666 }
1667 else if (newip4) {
1668 *newip = newip4;
1669 *newip_sin_family = AF_INET;
1670 }
Emeric Brunc9437992021-02-12 19:42:55 +01001671 }
1672
Emeric Brunbd78c912021-06-11 10:08:05 +02001673 /* the ip of this record was chosen for the server */
1674 if (owner && found_record) {
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001675 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunbd78c912021-06-11 10:08:05 +02001676 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1677 }
1678
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001679 eb32 = eb32_first(&r_res->answer_tree);
1680 if (eb32) {
Emeric Brunc9437992021-02-12 19:42:55 +01001681 /* Move the first record to the end of the list, for internal
Willy Tarreau7893ae12021-10-21 07:39:57 +02001682 * round robin.
1683 */
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001684 eb32_delete(eb32);
1685 eb32_insert(&r_res->answer_tree, eb32);
Emeric Brunc9437992021-02-12 19:42:55 +01001686 }
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001687
1688 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001689}
1690
Willy Tarreau875ee702021-10-14 08:05:25 +02001691/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001692 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001693 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1694 * null-terminated. <str> must be allocated large enough to contain a full host
1695 * name plus the trailing zero, and the allocated size must be passed in
1696 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001697 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001698 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001699 * <str> (including the terminating null byte).
1700 */
1701int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1702{
1703 char *ptr;
1704 int i, sz;
1705
Willy Tarreau875ee702021-10-14 08:05:25 +02001706 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001707 return -1;
1708
1709 ptr = str;
Willy Tarreau875ee702021-10-14 08:05:25 +02001710 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001711 sz = dn[i];
1712 if (i)
1713 *ptr++ = '.';
Willy Tarreau814889c2021-10-15 07:45:38 +02001714 /* copy the string at i+1 to lower case */
1715 for (; sz > 0; sz--)
1716 *(ptr++) = tolower(dn[++i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001717 }
1718 *ptr++ = '\0';
1719 return (ptr - str);
1720}
1721
1722/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1723 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001724 * <str> contains the input string that is <str_len> bytes long (trailing zero
1725 * not needed). <dn> buffer must be allocated large enough to contain the
1726 * encoded string and a trailing zero, so it must be at least str_len+2, and
1727 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001728 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001729 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001730 * <dn> (excluding the terminating null byte).
1731 */
1732int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1733{
1734 int i, offset;
1735
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001736 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001737 return -1;
1738
1739 /* First byte of dn will be used to store the length of the first
1740 * label */
1741 offset = 0;
1742 for (i = 0; i < str_len; ++i) {
1743 if (str[i] == '.') {
1744 /* 2 or more consecutive dots is invalid */
1745 if (i == offset)
1746 return -1;
1747
1748 /* ignore trailing dot */
Christopher Faulet0a82cf42022-01-28 17:47:57 +01001749 if (i + 1 == str_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001750 break;
Emeric Brunc9437992021-02-12 19:42:55 +01001751
1752 dn[offset] = (i - offset);
1753 offset = i+1;
1754 continue;
1755 }
Willy Tarreau814889c2021-10-15 07:45:38 +02001756 dn[i+1] = tolower(str[i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001757 }
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001758 dn[offset] = i - offset;
Willy Tarreau7b232f12021-10-15 08:09:25 +02001759 dn[i+1] = '\0';
1760 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001761}
1762
1763/* Validates host name:
1764 * - total size
1765 * - each label size individually
1766 * returns:
1767 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1768 * 1 when no error. <err> is left unaffected.
1769 */
1770int resolv_hostname_validation(const char *string, char **err)
1771{
1772 int i;
1773
1774 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1775 if (err)
1776 *err = DNS_TOO_LONG_FQDN;
1777 return 0;
1778 }
1779
1780 while (*string) {
1781 i = 0;
1782 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1783 if (!(*string == '-' || *string == '_' ||
1784 (*string >= 'a' && *string <= 'z') ||
1785 (*string >= 'A' && *string <= 'Z') ||
1786 (*string >= '0' && *string <= '9'))) {
1787 if (err)
1788 *err = DNS_INVALID_CHARACTER;
1789 return 0;
1790 }
1791 i++;
1792 string++;
1793 }
1794
1795 if (!(*string))
1796 break;
1797
1798 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1799 if (err)
1800 *err = DNS_LABEL_TOO_LONG;
1801 return 0;
1802 }
1803
1804 string++;
1805 }
1806 return 1;
1807}
1808
1809/* Picks up an available resolution from the different resolution list
1810 * associated to a resolvers section, in this order:
1811 * 1. check in resolutions.curr for the same hostname and query_type
1812 * 2. check in resolutions.wait for the same hostname and query_type
1813 * 3. Get a new resolution from resolution pool
1814 *
1815 * Returns an available resolution, NULL if none found.
1816 */
1817static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1818 char **hostname_dn, int hostname_dn_len,
1819 int query_type)
1820{
1821 struct resolv_resolution *res;
1822
1823 if (!*hostname_dn)
1824 goto from_pool;
1825
1826 /* Search for same hostname and query type in resolutions.curr */
1827 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1828 if (!res->hostname_dn)
1829 continue;
1830 if ((query_type == res->prefered_query_type) &&
1831 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001832 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001833 return res;
1834 }
1835
1836 /* Search for same hostname and query type in resolutions.wait */
1837 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1838 if (!res->hostname_dn)
1839 continue;
1840 if ((query_type == res->prefered_query_type) &&
1841 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001842 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001843 return res;
1844 }
1845
1846 from_pool:
1847 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001848 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001849 if (res) {
Emeric Brunc9437992021-02-12 19:42:55 +01001850 res->resolvers = resolvers;
1851 res->uuid = resolution_uuid;
1852 res->status = RSLV_STATUS_NONE;
1853 res->step = RSLV_STEP_NONE;
1854 res->last_valid = now_ms;
1855
1856 LIST_INIT(&res->requesters);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001857 res->response.answer_tree = EB_ROOT;
Emeric Brunc9437992021-02-12 19:42:55 +01001858
1859 res->prefered_query_type = query_type;
1860 res->query_type = query_type;
1861 res->hostname_dn = *hostname_dn;
1862 res->hostname_dn_len = hostname_dn_len;
1863
1864 ++resolution_uuid;
1865
1866 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001867 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001868 }
1869 return res;
1870}
1871
Willy Tarreau2acc1602021-10-19 11:16:11 +02001872/* deletes and frees all answer_items from the resolution's answer_list */
1873static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001874{
Willy Tarreau7893ae12021-10-21 07:39:57 +02001875 struct eb32_node *eb32, *eb32_back;
1876 struct resolv_answer_item *item;
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001877
Willy Tarreau7893ae12021-10-21 07:39:57 +02001878 for (eb32 = eb32_first(&resolution->response.answer_tree);
1879 eb32 && (eb32_back = eb32_next(eb32), 1);
1880 eb32 = eb32_back) {
1881 item = eb32_entry(eb32, typeof(*item), link);
1882 eb32_delete(&item->link);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001883 pool_free(resolv_answer_item_pool, item->ar_item);
1884 pool_free(resolv_answer_item_pool, item);
1885 }
1886}
1887
Emeric Brunc9437992021-02-12 19:42:55 +01001888/* Releases a resolution from its requester(s) and move it back to the pool */
1889static void resolv_free_resolution(struct resolv_resolution *resolution)
1890{
1891 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001892
1893 /* clean up configuration */
1894 resolv_reset_resolution(resolution);
1895 resolution->hostname_dn = NULL;
1896 resolution->hostname_dn_len = 0;
1897
1898 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02001899 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001900 req->resolution = NULL;
1901 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001902 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau25e01092021-10-19 11:17:33 +02001903
Willy Tarreauaae73202021-10-19 22:01:36 +02001904 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001905 pool_free(resolv_resolution_pool, resolution);
1906}
1907
Willy Tarreau239675e2021-10-19 11:59:25 +02001908/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1909 * and makes it owned by this obj_type, with the proposed callback and error
1910 * callback. On success, *req is assigned the allocated requester. Returns
1911 * NULL on allocation failure.
1912 */
1913static struct resolv_requester *
1914resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1915 int (*cb)(struct resolv_requester *, struct dns_counters *),
1916 int (*err_cb)(struct resolv_requester *, int))
1917{
1918 struct resolv_requester *tmp;
1919
1920 if (*req)
1921 return *req;
1922
1923 tmp = pool_alloc(resolv_requester_pool);
1924 if (!tmp)
1925 goto end;
1926
1927 LIST_INIT(&tmp->list);
1928 tmp->owner = owner;
1929 tmp->resolution = NULL;
1930 tmp->requester_cb = cb;
1931 tmp->requester_error_cb = err_cb;
1932 *req = tmp;
1933 end:
1934 return tmp;
1935}
1936
Emeric Brunc9437992021-02-12 19:42:55 +01001937/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001938 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001939 */
1940int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1941{
1942 struct resolv_resolution *res = NULL;
1943 struct resolv_requester *req;
1944 struct resolvers *resolvers;
1945 struct server *srv = NULL;
1946 struct resolv_srvrq *srvrq = NULL;
1947 struct stream *stream = NULL;
1948 char **hostname_dn;
1949 int hostname_dn_len, query_type;
1950
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001951 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001952 switch (requester_type) {
1953 case OBJ_TYPE_SERVER:
1954 srv = (struct server *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001955
1956 if (!requester_locked)
1957 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1958
1959 req = resolv_get_requester(&srv->resolv_requester,
1960 &srv->obj_type,
1961 snr_resolution_cb,
1962 snr_resolution_error_cb);
1963
1964 if (!requester_locked)
1965 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1966
1967 if (!req)
1968 goto err;
1969
Emeric Brunc9437992021-02-12 19:42:55 +01001970 hostname_dn = &srv->hostname_dn;
1971 hostname_dn_len = srv->hostname_dn_len;
1972 resolvers = srv->resolvers;
1973 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1974 ? DNS_RTYPE_A
1975 : DNS_RTYPE_AAAA);
1976 break;
1977
1978 case OBJ_TYPE_SRVRQ:
1979 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001980
1981 req = resolv_get_requester(&srvrq->requester,
1982 &srvrq->obj_type,
1983 snr_resolution_cb,
1984 srvrq_resolution_error_cb);
1985 if (!req)
1986 goto err;
1987
Emeric Brunc9437992021-02-12 19:42:55 +01001988 hostname_dn = &srvrq->hostname_dn;
1989 hostname_dn_len = srvrq->hostname_dn_len;
1990 resolvers = srvrq->resolvers;
1991 query_type = DNS_RTYPE_SRV;
1992 break;
1993
1994 case OBJ_TYPE_STREAM:
1995 stream = (struct stream *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001996
1997 req = resolv_get_requester(&stream->resolv_ctx.requester,
1998 &stream->obj_type,
1999 act_resolution_cb,
2000 act_resolution_error_cb);
2001 if (!req)
2002 goto err;
2003
Emeric Brunc9437992021-02-12 19:42:55 +01002004 hostname_dn = &stream->resolv_ctx.hostname_dn;
2005 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2006 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2007 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2008 ? DNS_RTYPE_A
2009 : DNS_RTYPE_AAAA);
2010 break;
2011 default:
2012 goto err;
2013 }
2014
2015 /* Get a resolution from the resolvers' wait queue or pool */
2016 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2017 goto err;
2018
Willy Tarreau239675e2021-10-19 11:59:25 +02002019 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002020
Willy Tarreau2b718102021-04-21 07:32:39 +02002021 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002022 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002023 return 0;
2024
2025 err:
2026 if (res && LIST_ISEMPTY(&res->requesters))
2027 resolv_free_resolution(res);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002028 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002029 return -1;
2030}
2031
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002032/* This function removes all server/srvrq references on answer items. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002033void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun34067662021-06-11 10:48:45 +02002034{
Willy Tarreau7893ae12021-10-21 07:39:57 +02002035 struct eb32_node *eb32, *eb32_back;
2036 struct resolv_answer_item *item;
Emeric Brun34067662021-06-11 10:48:45 +02002037 struct server *srv, *srvback;
2038 struct resolv_srvrq *srvrq;
2039
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002040 enter_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002041 if ((srv = objt_server(req->owner)) != NULL) {
2042 LIST_DEL_INIT(&srv->ip_rec_item);
2043 }
2044 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02002045 for (eb32 = eb32_first(&res->response.answer_tree);
2046 eb32 && (eb32_back = eb32_next(eb32), 1);
2047 eb32 = eb32_back) {
2048 item = eb32_entry(eb32, typeof(*item), link);
Emeric Brun34067662021-06-11 10:48:45 +02002049 if (item->type == DNS_RTYPE_SRV) {
2050 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet11c6c392021-06-15 16:08:48 +02002051 if (srv->srvrq == srvrq)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002052 resolv_srvrq_cleanup_srv(srv);
Emeric Brun34067662021-06-11 10:48:45 +02002053 }
2054 }
2055 }
2056 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002057 leave_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002058}
2059
Emeric Brunc9437992021-02-12 19:42:55 +01002060/* Removes a requester from a DNS resolution. It takes takes care of all the
2061 * consequences. It also cleans up some parameters from the requester.
2062 */
Willy Tarreau6878f802021-10-20 14:07:31 +02002063static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002064{
2065 struct resolv_resolution *res;
2066 struct resolv_requester *req;
2067
2068 /* Nothing to do */
2069 if (!requester || !requester->resolution)
2070 return;
2071 res = requester->resolution;
2072
2073 /* Clean up the requester */
Willy Tarreauaae73202021-10-19 22:01:36 +02002074 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002075 requester->resolution = NULL;
2076
Christopher Fauletbce6db62021-10-29 10:38:15 +02002077 /* remove ref from the resolution answer item list to the requester */
2078 resolv_detach_from_resolution_answer_items(res, requester);
2079
Emeric Brunc9437992021-02-12 19:42:55 +01002080 /* We need to find another requester linked on this resolution */
2081 if (!LIST_ISEMPTY(&res->requesters))
2082 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2083 else {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002084 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002085 return;
2086 }
2087
2088 /* Move hostname_dn related pointers to the next requester */
2089 switch (obj_type(req->owner)) {
2090 case OBJ_TYPE_SERVER:
2091 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2092 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2093 break;
2094 case OBJ_TYPE_SRVRQ:
2095 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2096 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2097 break;
2098 case OBJ_TYPE_STREAM:
2099 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2100 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2101 break;
2102 default:
2103 res->hostname_dn = NULL;
2104 res->hostname_dn_len = 0;
2105 break;
2106 }
2107}
2108
Willy Tarreauf766ec62021-10-18 16:46:38 +02002109/* The public version of the function above that deals with the death row. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002110void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002111{
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002112 enter_resolver_code();
Willy Tarreau6878f802021-10-20 14:07:31 +02002113 _resolv_unlink_resolution(requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002114 leave_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002115}
2116
Emeric Brunc9437992021-02-12 19:42:55 +01002117/* Called when a network IO is generated on a name server socket for an incoming
2118 * packet. It performs the following actions:
2119 * - check if the packet requires processing (not outdated resolution)
2120 * - ensure the DNS packet received is valid and call requester's callback
2121 * - call requester's error callback if invalid response
2122 * - check the dn_name in the packet against the one sent
2123 */
2124static int resolv_process_responses(struct dns_nameserver *ns)
2125{
2126 struct dns_counters *tmpcounters;
2127 struct resolvers *resolvers;
2128 struct resolv_resolution *res;
Emeric Brunc9437992021-02-12 19:42:55 +01002129 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2130 unsigned char *bufend;
2131 int buflen, dns_resp;
2132 int max_answer_records;
2133 unsigned short query_id;
2134 struct eb32_node *eb;
2135 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002136 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002137
2138 resolvers = ns->parent;
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002139 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002140 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2141
2142 /* process all pending input messages */
2143 while (1) {
2144 /* read message received */
2145 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2146 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2147 break;
2148 }
2149
2150 /* message too big */
2151 if (buflen > resolvers->accepted_payload_size) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002152 ns->counters->app.resolver.too_big++;
Emeric Brunc9437992021-02-12 19:42:55 +01002153 continue;
2154 }
2155
2156 /* initializing variables */
2157 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2158
2159 /* read the query id from the packet (16 bits) */
2160 if (buf + 2 > bufend) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002161 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002162 continue;
2163 }
2164 query_id = resolv_response_get_query_id(buf);
2165
2166 /* search the query_id in the pending resolution tree */
2167 eb = eb32_lookup(&resolvers->query_ids, query_id);
2168 if (eb == NULL) {
2169 /* unknown query id means an outdated response and can be safely ignored */
Emeric Brund174f0e2021-10-29 17:30:41 +02002170 ns->counters->app.resolver.outdated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002171 continue;
2172 }
2173
2174 /* known query id means a resolution in progress */
2175 res = eb32_entry(eb, struct resolv_resolution, qid);
2176 /* number of responses received */
2177 res->nb_responses++;
2178
2179 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2180 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2181
2182 switch (dns_resp) {
2183 case RSLV_RESP_VALID:
2184 break;
2185
2186 case RSLV_RESP_INVALID:
2187 case RSLV_RESP_QUERY_COUNT_ERROR:
2188 case RSLV_RESP_WRONG_NAME:
2189 res->status = RSLV_STATUS_INVALID;
Emeric Brund174f0e2021-10-29 17:30:41 +02002190 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002191 break;
2192
2193 case RSLV_RESP_NX_DOMAIN:
2194 res->status = RSLV_STATUS_NX;
Emeric Brund174f0e2021-10-29 17:30:41 +02002195 ns->counters->app.resolver.nx++;
Emeric Brunc9437992021-02-12 19:42:55 +01002196 break;
2197
2198 case RSLV_RESP_REFUSED:
2199 res->status = RSLV_STATUS_REFUSED;
Emeric Brund174f0e2021-10-29 17:30:41 +02002200 ns->counters->app.resolver.refused++;
Emeric Brunc9437992021-02-12 19:42:55 +01002201 break;
2202
2203 case RSLV_RESP_ANCOUNT_ZERO:
2204 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002205 ns->counters->app.resolver.any_err++;
Emeric Brunc9437992021-02-12 19:42:55 +01002206 break;
2207
2208 case RSLV_RESP_CNAME_ERROR:
2209 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002210 ns->counters->app.resolver.cname_error++;
Emeric Brunc9437992021-02-12 19:42:55 +01002211 break;
2212
2213 case RSLV_RESP_TRUNCATED:
2214 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002215 ns->counters->app.resolver.truncated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002216 break;
2217
2218 case RSLV_RESP_NO_EXPECTED_RECORD:
2219 case RSLV_RESP_ERROR:
2220 case RSLV_RESP_INTERNAL:
2221 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002222 ns->counters->app.resolver.other++;
Emeric Brunc9437992021-02-12 19:42:55 +01002223 break;
2224 }
2225
2226 /* Wait all nameservers response to handle errors */
2227 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2228 continue;
2229
2230 /* Process error codes */
2231 if (dns_resp != RSLV_RESP_VALID) {
2232 if (res->prefered_query_type != res->query_type) {
2233 /* The fallback on the query type was already performed,
2234 * so check the try counter. If it falls to 0, we can
2235 * report an error. Else, wait the next attempt. */
2236 if (!res->try)
2237 goto report_res_error;
2238 }
2239 else {
2240 /* Fallback from A to AAAA or the opposite and re-send
2241 * the resolution immediately. try counter is not
2242 * decremented. */
2243 if (res->prefered_query_type == DNS_RTYPE_A) {
2244 res->query_type = DNS_RTYPE_AAAA;
2245 resolv_send_query(res);
2246 }
2247 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2248 res->query_type = DNS_RTYPE_A;
2249 resolv_send_query(res);
2250 }
2251 }
2252 continue;
2253 }
2254
Emeric Brunc9437992021-02-12 19:42:55 +01002255 /* So the resolution succeeded */
2256 res->status = RSLV_STATUS_VALID;
2257 res->last_valid = now_ms;
Emeric Brund174f0e2021-10-29 17:30:41 +02002258 ns->counters->app.resolver.valid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002259 goto report_res_success;
2260
2261 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002262 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002263 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002264 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2265 if (!keep_answer_items)
2266 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002267 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002268 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002269 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002270 continue;
2271
2272 report_res_success:
2273 /* Only the 1rst requester s managed by the server, others are
2274 * from the cache */
2275 tmpcounters = ns->counters;
2276 list_for_each_entry(req, &res->requesters, list) {
2277 struct server *s = objt_server(req->owner);
2278
2279 if (s)
2280 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2281 req->requester_cb(req, tmpcounters);
2282 if (s)
2283 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2284 tmpcounters = NULL;
2285 }
2286
2287 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002288 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002289 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002290 continue;
2291 }
2292 resolv_update_resolvers_timeout(resolvers);
2293 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002294 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002295 return buflen;
2296}
2297
2298/* Processes DNS resolution. First, it checks the active list to detect expired
2299 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2300 * checks the wait list to trigger new resolutions.
2301 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002302static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002303{
2304 struct resolvers *resolvers = context;
2305 struct resolv_resolution *res, *resback;
2306 int exp;
2307
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002308 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002309 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2310
Willy Tarreauf766ec62021-10-18 16:46:38 +02002311 /* Handle all expired resolutions from the active list. Elements that
2312 * need to be removed will in fact be moved to the death_row. Other
2313 * ones will be handled normally.
2314 */
2315
Willy Tarreauf766ec62021-10-18 16:46:38 +02002316 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2317 while (&res->list != &resolvers->resolutions.curr) {
2318 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2319
Christopher Faulet0efc0992021-03-11 18:09:53 +01002320 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002321 abort_resolution(res);
2322 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002323 continue;
2324 }
2325
Emeric Brunc9437992021-02-12 19:42:55 +01002326 /* When we find the first resolution in the future, then we can
2327 * stop here */
2328 exp = tick_add(res->last_query, resolvers->timeout.retry);
2329 if (!tick_is_expired(exp, now_ms))
2330 break;
2331
2332 /* If current resolution has been tried too many times and
2333 * finishes in timeout we update its status and remove it from
2334 * the list */
2335 if (!res->try) {
2336 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002337 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002338
2339 /* Notify the result to the requesters */
2340 if (!res->nb_responses)
2341 res->status = RSLV_STATUS_TIMEOUT;
2342 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002343 keep_answer_items |= req->requester_error_cb(req, res->status);
2344 if (!keep_answer_items)
2345 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002346
2347 /* Clean up resolution info and remove it from the
2348 * current list */
2349 resolv_reset_resolution(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002350
2351 /* subsequent entries might have been deleted here */
2352 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreauaae73202021-10-19 22:01:36 +02002353 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002354 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002355 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002356 }
2357 else {
2358 /* Otherwise resend the DNS query and requeue the resolution */
2359 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2360 /* No response received (a real timeout) or fallback already done */
2361 res->query_type = res->prefered_query_type;
2362 res->try--;
2363 }
2364 else {
2365 /* Fallback from A to AAAA or the opposite and re-send
2366 * the resolution immediately. try counter is not
2367 * decremented. */
2368 if (res->prefered_query_type == DNS_RTYPE_A)
2369 res->query_type = DNS_RTYPE_AAAA;
2370 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2371 res->query_type = DNS_RTYPE_A;
2372 else
2373 res->try--;
2374 }
2375 resolv_send_query(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002376 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2377 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002378 }
2379 }
2380
2381 /* Handle all resolutions in the wait list */
2382 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002383 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002384 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002385 continue;
2386 }
2387
Emeric Brunc9437992021-02-12 19:42:55 +01002388 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2389 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2390 continue;
2391
2392 if (resolv_run_resolution(res) != 1) {
2393 res->last_resolution = now_ms;
Willy Tarreauaae73202021-10-19 22:01:36 +02002394 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002395 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002396 }
2397 }
Emeric Brunc9437992021-02-12 19:42:55 +01002398 resolv_update_resolvers_timeout(resolvers);
2399 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002400
2401 /* now we can purge all queued deletions */
2402 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002403 return t;
2404}
2405
2406/* Release memory allocated by DNS */
2407static void resolvers_deinit(void)
2408{
2409 struct resolvers *resolvers, *resolversback;
2410 struct dns_nameserver *ns, *nsback;
2411 struct resolv_resolution *res, *resback;
2412 struct resolv_requester *req, *reqback;
2413 struct resolv_srvrq *srvrq, *srvrqback;
2414
2415 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2416 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2417 free(ns->id);
2418 free((char *)ns->conf.file);
2419 if (ns->dgram) {
2420 if (ns->dgram->conn.t.sock.fd != -1) {
2421 fd_delete(ns->dgram->conn.t.sock.fd);
2422 close(ns->dgram->conn.t.sock.fd);
2423 }
2424 if (ns->dgram->ring_req)
2425 ring_free(ns->dgram->ring_req);
2426 free(ns->dgram);
2427 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002428 if (ns->stream) {
2429 if (ns->stream->ring_req)
2430 ring_free(ns->stream->ring_req);
2431 if (ns->stream->task_req)
2432 task_destroy(ns->stream->task_req);
2433 if (ns->stream->task_rsp)
2434 task_destroy(ns->stream->task_rsp);
2435 free(ns->stream);
2436 }
Willy Tarreauaae73202021-10-19 22:01:36 +02002437 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002438 EXTRA_COUNTERS_FREE(ns->extra_counters);
2439 free(ns);
2440 }
2441
2442 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2443 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002444 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002445 pool_free(resolv_requester_pool, req);
2446 }
Christopher Faulet4315d172022-05-24 18:10:42 +02002447 resolv_free_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002448 }
2449
2450 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2451 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002452 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002453 pool_free(resolv_requester_pool, req);
2454 }
Christopher Faulet4315d172022-05-24 18:10:42 +02002455 resolv_free_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002456 }
2457
Tim Duesterhus0b7031b2022-04-26 23:28:47 +02002458 free_proxy(resolvers->px);
Emeric Brunc9437992021-02-12 19:42:55 +01002459 free(resolvers->id);
2460 free((char *)resolvers->conf.file);
2461 task_destroy(resolvers->t);
Willy Tarreauaae73202021-10-19 22:01:36 +02002462 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002463 free(resolvers);
2464 }
2465
2466 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2467 free(srvrq->name);
2468 free(srvrq->hostname_dn);
Willy Tarreauaae73202021-10-19 22:01:36 +02002469 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002470 free(srvrq);
2471 }
2472}
2473
2474/* Finalizes the DNS configuration by allocating required resources and checking
2475 * live parameters.
2476 * Returns 0 on success, ERR_* flags otherwise.
2477 */
2478static int resolvers_finalize_config(void)
2479{
2480 struct resolvers *resolvers;
2481 struct proxy *px;
2482 int err_code = 0;
2483
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002484 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002485
Emeric Brunc9437992021-02-12 19:42:55 +01002486 /* allocate pool of resolution per resolvers */
2487 list_for_each_entry(resolvers, &sec_resolvers, list) {
2488 struct dns_nameserver *ns;
2489 struct task *t;
2490
2491 /* Check if we can create the socket with nameservers info */
2492 list_for_each_entry(ns, &resolvers->nameservers, list) {
2493 int fd;
2494
2495 if (ns->dgram) {
2496 /* Check nameserver info */
2497 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002498 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002499 resolvers->id, ns->id);
2500 err_code |= (ERR_ALERT|ERR_ABORT);
2501 continue;
2502 }
2503 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002504 ha_alert("resolvers '%s': can't connect socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002505 resolvers->id, ns->id);
2506 close(fd);
2507 err_code |= (ERR_ALERT|ERR_ABORT);
2508 continue;
2509 }
2510 close(fd);
2511 }
2512 }
2513
2514 /* Create the task associated to the resolvers section */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002515 if ((t = task_new_anywhere()) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002516 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002517 err_code |= (ERR_ALERT|ERR_ABORT);
2518 goto err;
2519 }
2520
2521 /* Update task's parameters */
2522 t->process = process_resolvers;
2523 t->context = resolvers;
2524 resolvers->t = t;
2525 task_wakeup(t, TASK_WOKEN_INIT);
2526 }
2527
2528 for (px = proxies_list; px; px = px->next) {
2529 struct server *srv;
2530
2531 for (srv = px->srv; srv; srv = srv->next) {
2532 struct resolvers *resolvers;
2533
2534 if (!srv->resolvers_id)
2535 continue;
2536
2537 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002538 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002539 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2540 err_code |= (ERR_ALERT|ERR_ABORT);
2541 continue;
2542 }
2543 srv->resolvers = resolvers;
Christopher Fauletdcac4182021-06-15 16:17:17 +02002544 srv->srvrq_check = NULL;
2545 if (srv->srvrq) {
2546 if (!srv->srvrq->resolvers) {
2547 srv->srvrq->resolvers = srv->resolvers;
2548 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2549 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
2550 proxy_type_str(px), px->id, srv->id);
2551 err_code |= (ERR_ALERT|ERR_ABORT);
2552 continue;
2553 }
2554 }
Emeric Brunc9437992021-02-12 19:42:55 +01002555
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002556 srv->srvrq_check = task_new_anywhere();
Christopher Fauletdcac4182021-06-15 16:17:17 +02002557 if (!srv->srvrq_check) {
2558 ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002559 proxy_type_str(px), px->id, srv->id);
2560 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Fauletdcac4182021-06-15 16:17:17 +02002561 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002562 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002563 srv->srvrq_check->process = resolv_srvrq_expire_task;
2564 srv->srvrq_check->context = srv;
2565 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002566 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002567 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002568 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002569 proxy_type_str(px), px->id, srv->id);
2570 err_code |= (ERR_ALERT|ERR_ABORT);
2571 continue;
2572 }
Amaury Denoyelledd565202021-08-26 15:35:59 +02002573
2574 srv->flags |= SRV_F_NON_PURGEABLE;
Emeric Brunc9437992021-02-12 19:42:55 +01002575 }
2576 }
2577
2578 if (err_code & (ERR_ALERT|ERR_ABORT))
2579 goto err;
2580
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002581 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002582 return err_code;
2583 err:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002584 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002585 resolvers_deinit();
2586 return err_code;
2587
2588}
2589
Willy Tarreaucaff6312022-05-27 10:17:46 +02002590static int stats_dump_resolv_to_buffer(struct stconn *sc,
Emeric Brunc9437992021-02-12 19:42:55 +01002591 struct dns_nameserver *ns,
2592 struct field *stats, size_t stats_count,
2593 struct list *stat_modules)
2594{
Willy Tarreaucaff6312022-05-27 10:17:46 +02002595 struct appctx *appctx = __sc_appctx(sc);
2596 struct channel *rep = sc_ic(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002597 struct stats_module *mod;
2598 size_t idx = 0;
2599
2600 memset(stats, 0, sizeof(struct field) * stats_count);
2601
2602 list_for_each_entry(mod, stat_modules, list) {
2603 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2604
2605 mod->fill_stats(counters, stats + idx);
2606 idx += mod->stats_count;
2607 }
2608
2609 if (!stats_dump_one_line(stats, idx, appctx))
2610 return 0;
2611
2612 if (!stats_putchk(rep, NULL, &trash))
2613 goto full;
2614
2615 return 1;
2616
2617 full:
Willy Tarreaucaff6312022-05-27 10:17:46 +02002618 sc_have_room(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002619 return 0;
2620}
2621
2622/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2623 * as a pointer to the current nameserver.
2624 */
Willy Tarreaucaff6312022-05-27 10:17:46 +02002625int stats_dump_resolvers(struct stconn *sc,
Emeric Brunc9437992021-02-12 19:42:55 +01002626 struct field *stats, size_t stats_count,
2627 struct list *stat_modules)
2628{
Willy Tarreaucaff6312022-05-27 10:17:46 +02002629 struct appctx *appctx = __sc_appctx(sc);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002630 struct show_stat_ctx *ctx = appctx->svcctx;
Willy Tarreaucaff6312022-05-27 10:17:46 +02002631 struct channel *rep = sc_ic(sc);
Willy Tarreau91cefca2022-05-03 17:08:29 +02002632 struct resolvers *resolver = ctx->obj1;
2633 struct dns_nameserver *ns = ctx->obj2;
Emeric Brunc9437992021-02-12 19:42:55 +01002634
2635 if (!resolver)
2636 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2637
2638 /* dump resolvers */
2639 list_for_each_entry_from(resolver, &sec_resolvers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002640 ctx->obj1 = resolver;
Emeric Brunc9437992021-02-12 19:42:55 +01002641
Willy Tarreau91cefca2022-05-03 17:08:29 +02002642 ns = ctx->obj2 ?
2643 ctx->obj2 :
Emeric Brunc9437992021-02-12 19:42:55 +01002644 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2645
2646 list_for_each_entry_from(ns, &resolver->nameservers, list) {
Willy Tarreau91cefca2022-05-03 17:08:29 +02002647 ctx->obj2 = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002648
2649 if (buffer_almost_full(&rep->buf))
2650 goto full;
2651
Willy Tarreaucaff6312022-05-27 10:17:46 +02002652 if (!stats_dump_resolv_to_buffer(sc, ns,
Emeric Brunc9437992021-02-12 19:42:55 +01002653 stats, stats_count,
2654 stat_modules)) {
2655 return 0;
2656 }
2657 }
2658
Willy Tarreau91cefca2022-05-03 17:08:29 +02002659 ctx->obj2 = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002660 }
2661
2662 return 1;
2663
2664 full:
Willy Tarreaucaff6312022-05-27 10:17:46 +02002665 sc_need_room(sc);
Emeric Brunc9437992021-02-12 19:42:55 +01002666 return 0;
2667}
2668
2669void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2670{
2671 struct resolvers *resolvers;
2672 struct dns_nameserver *ns;
2673 struct stats_module *mod;
2674 void *counters;
2675
2676 list_for_each_entry(mod, stat_modules, list) {
2677 if (!mod->clearable && !clrall)
2678 continue;
2679
2680 list_for_each_entry(resolvers, &sec_resolvers, list) {
2681 list_for_each_entry(ns, &resolvers->nameservers, list) {
2682 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2683 memcpy(counters, mod->counters, mod->counters_size);
2684 }
2685 }
2686 }
2687
2688}
2689
2690int resolv_allocate_counters(struct list *stat_modules)
2691{
2692 struct stats_module *mod;
2693 struct resolvers *resolvers;
2694 struct dns_nameserver *ns;
2695
2696 list_for_each_entry(resolvers, &sec_resolvers, list) {
2697 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunf8642ee2021-10-29 17:59:18 +02002698 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
Emeric Brunc9437992021-02-12 19:42:55 +01002699 alloc_failed);
2700
2701 list_for_each_entry(mod, stat_modules, list) {
2702 EXTRA_COUNTERS_ADD(mod,
2703 ns->extra_counters,
2704 mod->counters,
2705 mod->counters_size);
2706 }
2707
2708 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2709
2710 list_for_each_entry(mod, stat_modules, list) {
2711 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2712 mod->counters, mod->counters_size);
2713
2714 /* Store the ns counters pointer */
Emeric Brunf8642ee2021-10-29 17:59:18 +02002715 if (strcmp(mod->name, "resolvers") == 0) {
2716 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
Emeric Brunc9437992021-02-12 19:42:55 +01002717 ns->counters->id = ns->id;
2718 ns->counters->pid = resolvers->id;
2719 }
2720 }
2721 }
2722 }
2723
2724 return 1;
2725
2726alloc_failed:
2727 return 0;
2728}
2729
Willy Tarreaudb933d62022-05-05 15:39:02 +02002730/* if an arg is found, it sets the optional resolvers section pointer into a
2731 * show_resolvers_ctx struct pointed to by svcctx, or NULL when dumping all.
2732 */
Emeric Brunc9437992021-02-12 19:42:55 +01002733static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2734{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002735 struct show_resolvers_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
Emeric Brunc9437992021-02-12 19:42:55 +01002736 struct resolvers *presolvers;
2737
2738 if (*args[2]) {
2739 list_for_each_entry(presolvers, &sec_resolvers, list) {
2740 if (strcmp(presolvers->id, args[2]) == 0) {
Willy Tarreaudb933d62022-05-05 15:39:02 +02002741 ctx->forced_section = presolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002742 break;
2743 }
2744 }
Willy Tarreaudb933d62022-05-05 15:39:02 +02002745 if (ctx->forced_section == NULL)
Emeric Brunc9437992021-02-12 19:42:55 +01002746 return cli_err(appctx, "Can't find that resolvers section\n");
2747 }
2748 return 0;
2749}
2750
2751/* Dumps counters from all resolvers section and associated name servers. It
2752 * returns 0 if the output buffer is full and it needs to be called again,
Willy Tarreaudb933d62022-05-05 15:39:02 +02002753 * otherwise non-zero. It may limit itself to the resolver pointed to by the
2754 * <resolvers> field of struct show_resolvers_ctx pointed to by <svcctx> if
2755 * it's not null.
Emeric Brunc9437992021-02-12 19:42:55 +01002756 */
2757static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2758{
Willy Tarreaudb933d62022-05-05 15:39:02 +02002759 struct show_resolvers_ctx *ctx = appctx->svcctx;
Willy Tarreaudb933d62022-05-05 15:39:02 +02002760 struct resolvers *resolvers = ctx->resolvers;
Emeric Brunc9437992021-02-12 19:42:55 +01002761 struct dns_nameserver *ns;
2762
2763 chunk_reset(&trash);
2764
Willy Tarreau12d52282022-05-05 16:38:13 +02002765 if (LIST_ISEMPTY(&sec_resolvers)) {
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002766 if (applet_putstr(appctx, "No resolvers found\n") == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002767 goto full;
2768 }
2769 else {
2770 if (!resolvers)
2771 resolvers = LIST_ELEM(sec_resolvers.n, typeof(resolvers), list);
Willy Tarreau4e047e72022-05-05 16:00:45 +02002772
Willy Tarreau12d52282022-05-05 16:38:13 +02002773 list_for_each_entry_from(resolvers, &sec_resolvers, list) {
2774 if (ctx->forced_section != NULL && ctx->forced_section != resolvers)
2775 continue;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002776
Willy Tarreau12d52282022-05-05 16:38:13 +02002777 ctx->resolvers = resolvers;
2778 ns = ctx->ns;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002779
Willy Tarreau12d52282022-05-05 16:38:13 +02002780 if (!ns) {
2781 chunk_printf(&trash, "Resolvers section %s\n", resolvers->id);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002782 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002783 goto full;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002784
Willy Tarreau12d52282022-05-05 16:38:13 +02002785 ns = LIST_ELEM(resolvers->nameservers.n, typeof(ns), list);
2786 ctx->ns = ns;
2787 }
Willy Tarreau4e047e72022-05-05 16:00:45 +02002788
Willy Tarreau12d52282022-05-05 16:38:13 +02002789 list_for_each_entry_from(ns, &resolvers->nameservers, list) {
2790 chunk_reset(&trash);
2791 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2792 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2793 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2794 chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
2795 chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
2796 chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
2797 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
2798 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
2799 chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
2800 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
2801 chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
2802 chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
2803 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
2804 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
2805 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
2806 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
Willy Tarreaud0a06d52022-05-18 15:07:19 +02002807 if (applet_putchk(appctx, &trash) == -1)
Willy Tarreau12d52282022-05-05 16:38:13 +02002808 goto full;
2809 ctx->ns = ns;
Emeric Brunc9437992021-02-12 19:42:55 +01002810 }
Emeric Brunc9437992021-02-12 19:42:55 +01002811
Willy Tarreau12d52282022-05-05 16:38:13 +02002812 ctx->ns = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01002813
Willy Tarreau12d52282022-05-05 16:38:13 +02002814 /* was this the only section to dump ? */
2815 if (ctx->forced_section)
2816 break;
2817 }
Emeric Brunc9437992021-02-12 19:42:55 +01002818 }
Willy Tarreau12d52282022-05-05 16:38:13 +02002819
2820 /* done! */
2821 return 1;
Willy Tarreau4e047e72022-05-05 16:00:45 +02002822 full:
2823 /* the output buffer is full, retry later */
Willy Tarreau4e047e72022-05-05 16:00:45 +02002824 return 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002825}
2826
2827/* register cli keywords */
2828static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002829 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002830 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2831 {{},}
2832 }
2833};
2834
2835INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2836
2837/*
2838 * Prepare <rule> for hostname resolution.
2839 * Returns -1 in case of any allocation failure, 0 if not.
2840 * On error, a global failure counter is also incremented.
2841 */
Willy Tarreau947ae122021-10-14 08:11:48 +02002842static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002843{
2844 char *hostname_dn;
Willy Tarreau947ae122021-10-14 08:11:48 +02002845 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002846 struct buffer *tmp = get_trash_chunk();
2847
2848 if (!hostname)
2849 return 0;
2850
Emeric Brunc9437992021-02-12 19:42:55 +01002851 hostname_dn = tmp->area;
Willy Tarreaubf9498a2021-10-14 07:49:49 +02002852 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002853 hostname_dn, tmp->size);
2854 if (hostname_dn_len == -1)
2855 goto err;
2856
2857
2858 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2859 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2860 if (!stream->resolv_ctx.hostname_dn)
2861 goto err;
2862
2863 return 0;
2864
2865 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002866 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002867 resolv_failed_resolutions += 1;
2868 return -1;
2869}
2870
2871
2872/*
2873 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2874 */
2875enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2876 struct session *sess, struct stream *s, int flags)
2877{
2878 struct resolv_resolution *resolution;
2879 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002880 struct resolv_requester *req;
2881 struct resolvers *resolvers;
2882 struct resolv_resolution *res;
2883 int exp, locked = 0;
2884 enum act_return ret = ACT_RET_CONT;
2885
2886 resolvers = rule->arg.resolv.resolvers;
2887
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002888 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002889
Emeric Brunc9437992021-02-12 19:42:55 +01002890 /* we have a response to our DNS resolution */
2891 use_cache:
2892 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2893 resolution = s->resolv_ctx.requester->resolution;
2894 if (!locked) {
2895 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2896 locked = 1;
2897 }
2898
2899 if (resolution->step == RSLV_STEP_RUNNING)
2900 goto yield;
2901 if (resolution->step == RSLV_STEP_NONE) {
2902 /* We update the variable only if we have a valid response. */
2903 if (resolution->status == RSLV_STATUS_VALID) {
2904 struct sample smp;
2905 short ip_sin_family = 0;
2906 void *ip = NULL;
2907
2908 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2909 0, &ip, &ip_sin_family, NULL);
2910
2911 switch (ip_sin_family) {
2912 case AF_INET:
2913 smp.data.type = SMP_T_IPV4;
2914 memcpy(&smp.data.u.ipv4, ip, 4);
2915 break;
2916 case AF_INET6:
2917 smp.data.type = SMP_T_IPV6;
2918 memcpy(&smp.data.u.ipv6, ip, 16);
2919 break;
2920 default:
2921 ip = NULL;
2922 }
2923
2924 if (ip) {
2925 smp.px = px;
2926 smp.sess = sess;
2927 smp.strm = s;
2928
2929 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2930 }
2931 }
2932 }
2933
2934 goto release_requester;
2935 }
2936
2937 /* need to configure and start a new DNS resolution */
2938 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2939 if (smp == NULL)
2940 goto end;
2941
Willy Tarreau947ae122021-10-14 08:11:48 +02002942 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002943 goto end; /* on error, ignore the action */
2944
2945 s->resolv_ctx.parent = rule;
2946
2947 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2948 locked = 1;
2949
2950 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2951
2952 /* Check if there is a fresh enough response in the cache of our associated resolution */
2953 req = s->resolv_ctx.requester;
2954 if (!req || !req->resolution)
2955 goto release_requester; /* on error, ignore the action */
2956 res = req->resolution;
2957
2958 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2959 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2960 && !tick_is_expired(exp, now_ms)) {
2961 goto use_cache;
2962 }
2963
2964 resolv_trigger_resolution(s->resolv_ctx.requester);
2965
2966 yield:
2967 if (flags & ACT_OPT_FINAL)
2968 goto release_requester;
2969 ret = ACT_RET_YIELD;
2970
2971 end:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002972 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002973 if (locked)
2974 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2975 return ret;
2976
2977 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002978 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002979 s->resolv_ctx.hostname_dn_len = 0;
2980 if (s->resolv_ctx.requester) {
Willy Tarreau6878f802021-10-20 14:07:31 +02002981 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01002982 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2983 s->resolv_ctx.requester = NULL;
2984 }
2985 goto end;
2986}
2987
2988static void release_resolv_action(struct act_rule *rule)
2989{
2990 release_sample_expr(rule->arg.resolv.expr);
2991 free(rule->arg.resolv.varname);
2992 free(rule->arg.resolv.resolvers_id);
2993 free(rule->arg.resolv.opts);
2994}
2995
2996
2997/* parse "do-resolve" action
2998 * This action takes the following arguments:
2999 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3000 *
3001 * - <varName> is the variable name where the result of the DNS resolution will be stored
3002 * (mandatory)
3003 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3004 * (mandatory)
3005 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3006 * (optional), defaults to ipv6
3007 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3008 */
3009enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3010{
3011 int cur_arg;
3012 struct sample_expr *expr;
3013 unsigned int where;
3014 const char *beg, *end;
3015
3016 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3017 cur_arg = *orig_arg - 1;
3018
3019 /* locate varName, which is mandatory */
3020 beg = strchr(args[cur_arg], '(');
3021 if (beg == NULL)
3022 goto do_resolve_parse_error;
3023 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3024 end = strchr(beg, ',');
3025 if (end == NULL)
3026 goto do_resolve_parse_error;
3027 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3028 if (rule->arg.resolv.varname == NULL)
3029 goto do_resolve_parse_error;
3030
3031
3032 /* locate resolversSectionName, which is mandatory.
3033 * Since next parameters are optional, the delimiter may be comma ','
3034 * or closing parenthesis ')'
3035 */
3036 beg = end + 1;
3037 end = strchr(beg, ',');
3038 if (end == NULL)
3039 end = strchr(beg, ')');
3040 if (end == NULL)
3041 goto do_resolve_parse_error;
3042 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3043 if (rule->arg.resolv.resolvers_id == NULL)
3044 goto do_resolve_parse_error;
3045
3046
3047 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3048 if (rule->arg.resolv.opts == NULL)
3049 goto do_resolve_parse_error;
3050
3051 /* Default priority is ipv6 */
3052 rule->arg.resolv.opts->family_prio = AF_INET6;
3053
3054 /* optional arguments accepted for now:
3055 * ipv4 or ipv6
3056 */
3057 while (*end != ')') {
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
3065 if (strncmp(beg, "ipv4", end - beg) == 0) {
3066 rule->arg.resolv.opts->family_prio = AF_INET;
3067 }
3068 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3069 rule->arg.resolv.opts->family_prio = AF_INET6;
3070 }
3071 else {
3072 goto do_resolve_parse_error;
3073 }
3074 }
3075
3076 cur_arg = cur_arg + 1;
3077
3078 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3079 if (!expr)
3080 goto do_resolve_parse_error;
3081
3082
3083 where = 0;
3084 if (px->cap & PR_CAP_FE)
3085 where |= SMP_VAL_FE_HRQ_HDR;
3086 if (px->cap & PR_CAP_BE)
3087 where |= SMP_VAL_BE_HRQ_HDR;
3088
3089 if (!(expr->fetch->val & where)) {
3090 memprintf(err,
3091 "fetch method '%s' extracts information from '%s', none of which is available here",
3092 args[cur_arg-1], sample_src_names(expr->fetch->use));
3093 free(expr);
3094 return ACT_RET_PRS_ERR;
3095 }
3096 rule->arg.resolv.expr = expr;
3097 rule->action = ACT_CUSTOM;
3098 rule->action_ptr = resolv_action_do_resolve;
3099 *orig_arg = cur_arg;
3100
3101 rule->check_ptr = check_action_do_resolve;
3102 rule->release_ptr = release_resolv_action;
3103
3104 return ACT_RET_PRS_OK;
3105
3106 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003107 ha_free(&rule->arg.resolv.varname);
3108 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003109 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3110 args[cur_arg]);
3111 return ACT_RET_PRS_ERR;
3112}
3113
3114static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003115 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003116 { /* END */ }
3117}};
3118
3119INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3120
3121static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003122 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003123 { /* END */ }
3124}};
3125
3126INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3127
3128/* Check an "http-request do-resolve" action.
3129 *
3130 * The function returns 1 in success case, otherwise, it returns 0 and err is
3131 * filled.
3132 */
3133int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3134{
3135 struct resolvers *resolvers = NULL;
3136
3137 if (rule->arg.resolv.resolvers_id == NULL) {
3138 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3139 return 0;
3140 }
3141
3142 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3143 if (resolvers == NULL) {
3144 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3145 return 0;
3146 }
3147 rule->arg.resolv.resolvers = resolvers;
3148
3149 return 1;
3150}
3151
3152void resolvers_setup_proxy(struct proxy *px)
3153{
3154 px->last_change = now.tv_sec;
3155 px->cap = PR_CAP_FE | PR_CAP_BE;
3156 px->maxconn = 0;
3157 px->conn_retries = 1;
3158 px->timeout.server = TICK_ETERNITY;
3159 px->timeout.client = TICK_ETERNITY;
3160 px->timeout.connect = TICK_ETERNITY;
3161 px->accept = NULL;
3162 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
Emeric Brunc9437992021-02-12 19:42:55 +01003163}
3164
William Lallemand73edfe42022-05-05 17:36:09 +02003165static int parse_resolve_conf(char **errmsg, char **warnmsg)
3166{
3167 struct dns_nameserver *newnameserver = NULL;
3168 const char *whitespace = "\r\n\t ";
3169 char *resolv_line = NULL;
3170 int resolv_linenum = 0;
3171 FILE *f = NULL;
3172 char *address = NULL;
3173 struct sockaddr_storage *sk = NULL;
3174 struct protocol *proto;
3175 int duplicate_name = 0;
3176 int err_code = 0;
3177
3178 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3179 memprintf(errmsg, "out of memory.\n");
3180 err_code |= ERR_ALERT | ERR_FATAL;
3181 goto resolv_out;
3182 }
3183
3184 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3185 if (errmsg)
3186 memprintf(errmsg, "failed to open /etc/resolv.conf.");
3187 err_code |= ERR_ALERT | ERR_FATAL;
3188 goto resolv_out;
3189 }
3190
3191 sk = calloc(1, sizeof(*sk));
3192 if (sk == NULL) {
3193 if (errmsg)
3194 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3195 err_code |= ERR_ALERT | ERR_FATAL;
3196 goto resolv_out;
3197 }
3198
3199 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3200 resolv_linenum++;
3201 if (strncmp(resolv_line, "nameserver", 10) != 0)
3202 continue;
3203
3204 address = strtok(resolv_line + 10, whitespace);
3205 if (address == resolv_line + 10)
3206 continue;
3207
3208 if (address == NULL) {
3209 if (warnmsg)
3210 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3211 *warnmsg ? *warnmsg : "", resolv_linenum);
3212 err_code |= ERR_WARN;
3213 continue;
3214 }
3215
3216 duplicate_name = 0;
3217 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3218 if (strcmp(newnameserver->id, address) == 0) {
3219 if (warnmsg)
3220 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",
3221 *warnmsg ? *warnmsg : "", resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3222 err_code |= ERR_WARN;
3223 duplicate_name = 1;
3224 }
3225 }
3226
3227 if (duplicate_name)
3228 continue;
3229
3230 memset(sk, 0, sizeof(*sk));
3231 if (!str2ip2(address, sk, 1)) {
3232 if (warnmsg)
3233 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3234 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3235 err_code |= ERR_WARN;
3236 continue;
3237 }
3238
3239 set_host_port(sk, 53);
3240
3241 proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
3242 if (!proto || !proto->connect) {
3243 if (warnmsg)
3244 memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3245 *warnmsg ? *warnmsg : "", resolv_linenum, address);
3246 err_code |= ERR_WARN;
3247 continue;
3248 }
3249
3250 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3251 if (errmsg)
3252 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3253 err_code |= ERR_ALERT | ERR_FATAL;
3254 goto resolv_out;
3255 }
3256
3257 if (dns_dgram_init(newnameserver, sk) < 0) {
3258 if (errmsg)
3259 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3260 err_code |= ERR_ALERT | ERR_FATAL;
3261 free(newnameserver);
3262 goto resolv_out;
3263 }
3264
3265 newnameserver->conf.file = strdup("/etc/resolv.conf");
3266 if (newnameserver->conf.file == NULL) {
3267 if (errmsg)
3268 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3269 err_code |= ERR_ALERT | ERR_FATAL;
3270 free(newnameserver);
3271 goto resolv_out;
3272 }
3273
3274 newnameserver->id = strdup(address);
3275 if (newnameserver->id == NULL) {
3276 if (errmsg)
3277 memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
3278 err_code |= ERR_ALERT | ERR_FATAL;
3279 free((char *)newnameserver->conf.file);
3280 free(newnameserver);
3281 goto resolv_out;
3282 }
3283
3284 newnameserver->parent = curr_resolvers;
3285 newnameserver->process_responses = resolv_process_responses;
3286 newnameserver->conf.line = resolv_linenum;
3287 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
3288 }
3289
3290resolv_out:
3291 free(sk);
3292 free(resolv_line);
3293 if (f != NULL)
3294 fclose(f);
3295
3296 return err_code;
3297}
3298
William Lallemande7f57762022-05-05 18:27:48 +02003299static int resolvers_new(struct resolvers **resolvers, const char *id, const char *file, int linenum)
3300{
3301 struct resolvers *r = NULL;
3302 struct proxy *p = NULL;
3303 int err_code = 0;
3304
3305 if ((r = calloc(1, sizeof(*r))) == NULL) {
3306 err_code |= ERR_ALERT | ERR_ABORT;
3307 goto out;
3308 }
3309
3310 /* allocate new proxy to tcp servers */
3311 p = calloc(1, sizeof *p);
3312 if (!p) {
3313 err_code |= ERR_ALERT | ERR_FATAL;
3314 goto out;
3315 }
3316
3317 init_new_proxy(p);
3318 resolvers_setup_proxy(p);
3319 p->parent = r;
3320 p->id = strdup(id);
3321 p->conf.args.file = p->conf.file = strdup(file);
3322 p->conf.args.line = p->conf.line = linenum;
3323 r->px = p;
3324
3325 /* default values */
3326 LIST_APPEND(&sec_resolvers, &r->list);
3327 r->conf.file = strdup(file);
3328 r->conf.line = linenum;
3329 r->id = strdup(id);
3330 r->query_ids = EB_ROOT;
3331 /* default maximum response size */
3332 r->accepted_payload_size = 512;
3333 /* default hold period for nx, other, refuse and timeout is 30s */
3334 r->hold.nx = 30000;
3335 r->hold.other = 30000;
3336 r->hold.refused = 30000;
3337 r->hold.timeout = 30000;
3338 r->hold.obsolete = 0;
3339 /* default hold period for valid is 10s */
3340 r->hold.valid = 10000;
3341 r->timeout.resolve = 1000;
3342 r->timeout.retry = 1000;
3343 r->resolve_retries = 3;
3344 LIST_INIT(&r->nameservers);
3345 LIST_INIT(&r->resolutions.curr);
3346 LIST_INIT(&r->resolutions.wait);
3347 HA_SPIN_INIT(&r->lock);
3348
3349 *resolvers = r;
3350
3351out:
3352 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3353 ha_free(&r);
3354 ha_free(&p);
3355 }
3356
3357 return err_code;
3358}
3359
3360
Emeric Brunc9437992021-02-12 19:42:55 +01003361/*
3362 * Parse a <resolvers> section.
3363 * Returns the error code, 0 if OK, or any combination of :
3364 * - ERR_ABORT: must abort ASAP
3365 * - ERR_FATAL: we can continue parsing but not start the service
3366 * - ERR_WARN: a warning has been emitted
3367 * - ERR_ALERT: an alert has been emitted
3368 * Only the two first ones can stop processing, the two others are just
3369 * indicators.
3370 */
3371int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3372{
3373 const char *err;
3374 int err_code = 0;
3375 char *errmsg = NULL;
William Lallemand106bd292022-05-05 17:20:08 +02003376 char *warnmsg = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01003377
3378 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3379 if (!*args[1]) {
3380 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3381 err_code |= ERR_ALERT | ERR_ABORT;
3382 goto out;
3383 }
3384
3385 err = invalid_char(args[1]);
3386 if (err) {
3387 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3388 file, linenum, *err, args[0], args[1]);
3389 err_code |= ERR_ALERT | ERR_ABORT;
3390 goto out;
3391 }
3392
3393 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3394 /* Error if two resolvers owns the same name */
3395 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3396 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3397 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3398 err_code |= ERR_ALERT | ERR_ABORT;
3399 }
3400 }
3401
William Lallemande7f57762022-05-05 18:27:48 +02003402 err_code |= resolvers_new(&curr_resolvers, args[1], file, linenum);
3403 if (err_code & ERR_ALERT) {
Emeric Brunc9437992021-02-12 19:42:55 +01003404 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
Emeric Brunc9437992021-02-12 19:42:55 +01003405 goto out;
3406 }
3407
Emeric Brunc9437992021-02-12 19:42:55 +01003408 }
3409 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3410 struct dns_nameserver *newnameserver = NULL;
3411 struct sockaddr_storage *sk;
3412 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003413 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003414
3415 if (!*args[2]) {
3416 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3417 file, linenum, args[0]);
3418 err_code |= ERR_ALERT | ERR_FATAL;
3419 goto out;
3420 }
3421
3422 err = invalid_char(args[1]);
3423 if (err) {
3424 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3425 file, linenum, *err, args[1]);
3426 err_code |= ERR_ALERT | ERR_FATAL;
3427 goto out;
3428 }
3429
3430 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3431 /* Error if two resolvers owns the same name */
3432 if (strcmp(newnameserver->id, args[1]) == 0) {
3433 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3434 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3435 err_code |= ERR_ALERT | ERR_FATAL;
3436 }
3437 }
3438
Emeric Brunc8f3e452021-04-07 16:04:54 +02003439 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3440 &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 +01003441 if (!sk) {
3442 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3443 err_code |= ERR_ALERT | ERR_FATAL;
3444 goto out;
3445 }
3446
3447 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3448 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3449 err_code |= ERR_ALERT | ERR_ABORT;
3450 goto out;
3451 }
3452
Willy Tarreau91b47262022-05-20 16:36:46 +02003453 if (proto && proto->xprt_type == PROTO_TYPE_STREAM) {
Emeric Brunc8f3e452021-04-07 16:04:54 +02003454 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3455 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3456 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3457 err_code |= ERR_ABORT;
3458 goto out;
3459 }
3460
3461 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3462 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3463 err_code |= ERR_ALERT|ERR_ABORT;
3464 goto out;
3465 }
3466 }
3467 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003468 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3469 err_code |= ERR_ALERT | ERR_ABORT;
3470 goto out;
3471 }
3472
3473 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3474 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3475 err_code |= ERR_ALERT | ERR_ABORT;
3476 goto out;
3477 }
3478
3479 if ((newnameserver->id = strdup(args[1])) == NULL) {
3480 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3481 err_code |= ERR_ALERT | ERR_ABORT;
3482 goto out;
3483 }
3484
3485 newnameserver->parent = curr_resolvers;
3486 newnameserver->process_responses = resolv_process_responses;
3487 newnameserver->conf.line = linenum;
3488 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003489 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003490 }
3491 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
William Lallemand73edfe42022-05-05 17:36:09 +02003492 err_code |= parse_resolve_conf(&errmsg, &warnmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003493 if (err_code & ERR_WARN) {
3494 indent_msg(&warnmsg, 8);
3495 ha_warning("parsing [%s:%d]: %s\n", file, linenum, warnmsg);
3496 ha_free(&warnmsg);
3497 }
William Lallemand106bd292022-05-05 17:20:08 +02003498 if (err_code & ERR_ALERT) {
3499 indent_msg(&errmsg, 8);
3500 ha_alert("parsing [%s:%d]: %s\n", file, linenum, errmsg);
3501 ha_free(&errmsg);
William Lallemand73edfe42022-05-05 17:36:09 +02003502 goto out;
William Lallemand106bd292022-05-05 17:20:08 +02003503 }
Emeric Brunc9437992021-02-12 19:42:55 +01003504 }
3505 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3506 const char *res;
3507 unsigned int time;
3508
3509 if (!*args[2]) {
3510 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3511 file, linenum, args[0]);
3512 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3513 err_code |= ERR_ALERT | ERR_FATAL;
3514 goto out;
3515 }
3516 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3517 if (res == PARSE_TIME_OVER) {
3518 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3519 file, linenum, args[1], args[0]);
3520 err_code |= ERR_ALERT | ERR_FATAL;
3521 goto out;
3522 }
3523 else if (res == PARSE_TIME_UNDER) {
3524 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3525 file, linenum, args[1], args[0]);
3526 err_code |= ERR_ALERT | ERR_FATAL;
3527 goto out;
3528 }
3529 else if (res) {
3530 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3531 file, linenum, *res, args[0]);
3532 err_code |= ERR_ALERT | ERR_FATAL;
3533 goto out;
3534 }
3535 if (strcmp(args[1], "nx") == 0)
3536 curr_resolvers->hold.nx = time;
3537 else if (strcmp(args[1], "other") == 0)
3538 curr_resolvers->hold.other = time;
3539 else if (strcmp(args[1], "refused") == 0)
3540 curr_resolvers->hold.refused = time;
3541 else if (strcmp(args[1], "timeout") == 0)
3542 curr_resolvers->hold.timeout = time;
3543 else if (strcmp(args[1], "valid") == 0)
3544 curr_resolvers->hold.valid = time;
3545 else if (strcmp(args[1], "obsolete") == 0)
3546 curr_resolvers->hold.obsolete = time;
3547 else {
3548 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3549 file, linenum, args[0], args[1]);
3550 err_code |= ERR_ALERT | ERR_FATAL;
3551 goto out;
3552 }
3553
3554 }
3555 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3556 int i = 0;
3557
3558 if (!*args[1]) {
3559 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3560 file, linenum, args[0]);
3561 err_code |= ERR_ALERT | ERR_FATAL;
3562 goto out;
3563 }
3564
3565 i = atoi(args[1]);
3566 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3567 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3568 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3569 err_code |= ERR_ALERT | ERR_FATAL;
3570 goto out;
3571 }
3572
3573 curr_resolvers->accepted_payload_size = i;
3574 }
3575 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3576 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3577 file, linenum, args[0]);
3578 err_code |= ERR_ALERT | ERR_FATAL;
3579 goto out;
3580 }
3581 else if (strcmp(args[0], "resolve_retries") == 0) {
3582 if (!*args[1]) {
3583 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3584 file, linenum, args[0]);
3585 err_code |= ERR_ALERT | ERR_FATAL;
3586 goto out;
3587 }
3588 curr_resolvers->resolve_retries = atoi(args[1]);
3589 }
3590 else if (strcmp(args[0], "timeout") == 0) {
3591 if (!*args[1]) {
3592 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3593 file, linenum, args[0]);
3594 err_code |= ERR_ALERT | ERR_FATAL;
3595 goto out;
3596 }
3597 else if (strcmp(args[1], "retry") == 0 ||
3598 strcmp(args[1], "resolve") == 0) {
3599 const char *res;
3600 unsigned int tout;
3601
3602 if (!*args[2]) {
3603 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3604 file, linenum, args[0], args[1]);
3605 err_code |= ERR_ALERT | ERR_FATAL;
3606 goto out;
3607 }
3608 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3609 if (res == PARSE_TIME_OVER) {
3610 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3611 file, linenum, args[2], args[0], args[1]);
3612 err_code |= ERR_ALERT | ERR_FATAL;
3613 goto out;
3614 }
3615 else if (res == PARSE_TIME_UNDER) {
3616 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3617 file, linenum, args[2], args[0], args[1]);
3618 err_code |= ERR_ALERT | ERR_FATAL;
3619 goto out;
3620 }
3621 else if (res) {
3622 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3623 file, linenum, *res, args[0], args[1]);
3624 err_code |= ERR_ALERT | ERR_FATAL;
3625 goto out;
3626 }
3627 if (args[1][2] == 't')
3628 curr_resolvers->timeout.retry = tout;
3629 else
3630 curr_resolvers->timeout.resolve = tout;
3631 }
3632 else {
3633 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3634 file, linenum, args[0], args[1]);
3635 err_code |= ERR_ALERT | ERR_FATAL;
3636 goto out;
3637 }
3638 }
3639 else if (*args[0] != 0) {
3640 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3641 err_code |= ERR_ALERT | ERR_FATAL;
3642 goto out;
3643 }
3644
William Lallemand106bd292022-05-05 17:20:08 +02003645out:
Emeric Brunc9437992021-02-12 19:42:55 +01003646 free(errmsg);
William Lallemand106bd292022-05-05 17:20:08 +02003647 free(warnmsg);
Emeric Brunc9437992021-02-12 19:42:55 +01003648 return err_code;
3649}
William Lallemand7867f632022-05-05 19:02:59 +02003650
3651/* try to create a "default" resolvers section which uses "/etc/resolv.conf"
3652 *
3653 * This function is opportunistic and does not try to display errors or warnings.
3654 */
3655int resolvers_create_default()
3656{
3657 int err_code = 0;
3658
3659 if (find_resolvers_by_id("default"))
3660 return 0;
3661
3662 err_code |= resolvers_new(&curr_resolvers, "default", "<internal>", 0);
3663 if (!(err_code & ERR_CODE))
3664 err_code |= parse_resolve_conf(NULL, NULL);
3665
3666 return 0;
3667}
3668
Emeric Brun56fc5d92021-02-12 20:05:45 +01003669int cfg_post_parse_resolvers()
3670{
3671 int err_code = 0;
3672 struct server *srv;
3673
3674 if (curr_resolvers) {
3675
3676 /* prepare forward server descriptors */
3677 if (curr_resolvers->px) {
3678 srv = curr_resolvers->px->srv;
3679 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003680 /* init ssl if needed */
3681 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3682 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3683 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3684 err_code |= ERR_ALERT | ERR_FATAL;
3685 break;
3686 }
3687 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003688 srv = srv->next;
3689 }
3690 }
3691 }
3692 curr_resolvers = NULL;
3693 return err_code;
3694}
Emeric Brunc9437992021-02-12 19:42:55 +01003695
Emeric Brun56fc5d92021-02-12 20:05:45 +01003696REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003697REGISTER_POST_DEINIT(resolvers_deinit);
3698REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);
William Lallemand7867f632022-05-05 19:02:59 +02003699REGISTER_PRE_CHECK(resolvers_create_default);