blob: ef60bd6f3c9a0c901eb778ca84668b6a605bae14 [file] [log] [blame]
Emeric Brunc9437992021-02-12 19:42:55 +01001/*
2 * Name server resolution
3 *
4 * Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
14#include <fcntl.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19
20#include <sys/types.h>
21
Emeric Brun34067662021-06-11 10:48:45 +020022#include <import/ebistree.h>
23
Emeric Brunc9437992021-02-12 19:42:55 +010024#include <haproxy/action.h>
25#include <haproxy/api.h>
26#include <haproxy/cfgparse.h>
27#include <haproxy/channel.h>
28#include <haproxy/check.h>
29#include <haproxy/cli.h>
Christopher Faulet908628c2022-03-25 16:43:49 +010030#include <haproxy/conn_stream.h>
31#include <haproxy/cs_utils.h>
Emeric Brunc9437992021-02-12 19:42:55 +010032#include <haproxy/dns.h>
33#include <haproxy/errors.h>
34#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010035#include <haproxy/http_rules.h>
36#include <haproxy/log.h>
37#include <haproxy/net_helper.h>
38#include <haproxy/protocol.h>
39#include <haproxy/proxy.h>
40#include <haproxy/resolvers.h>
41#include <haproxy/ring.h>
42#include <haproxy/sample.h>
43#include <haproxy/server.h>
44#include <haproxy/stats.h>
Emeric Brunc9437992021-02-12 19:42:55 +010045#include <haproxy/task.h>
46#include <haproxy/tcp_rules.h>
47#include <haproxy/ticks.h>
48#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020049#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010050#include <haproxy/vars.h>
Willy Tarreaudcb696c2021-10-21 08:18:01 +020051#include <haproxy/xxhash.h>
Emeric Brunc9437992021-02-12 19:42:55 +010052
53
54struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
55struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
56
Willy Tarreauf766ec62021-10-18 16:46:38 +020057static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
Christopher Faulet9ed1a062021-11-02 16:25:05 +010058static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
Emeric Brunc9437992021-02-12 19:42:55 +010059static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
60struct resolvers *curr_resolvers = NULL;
61
62DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
63DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
64DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
65
66static unsigned int resolution_uuid = 1;
67unsigned int resolv_failed_resolutions = 0;
Willy Tarreauf766ec62021-10-18 16:46:38 +020068static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
69static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau6878f802021-10-20 14:07:31 +020070static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +010071static void enter_resolver_code();
72static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010073
74enum {
Emeric Brunf8642ee2021-10-29 17:59:18 +020075 RSLV_STAT_ID,
76 RSLV_STAT_PID,
77 RSLV_STAT_SENT,
78 RSLV_STAT_SND_ERROR,
79 RSLV_STAT_VALID,
80 RSLV_STAT_UPDATE,
81 RSLV_STAT_CNAME,
82 RSLV_STAT_CNAME_ERROR,
83 RSLV_STAT_ANY_ERR,
84 RSLV_STAT_NX,
85 RSLV_STAT_TIMEOUT,
86 RSLV_STAT_REFUSED,
87 RSLV_STAT_OTHER,
88 RSLV_STAT_INVALID,
89 RSLV_STAT_TOO_BIG,
90 RSLV_STAT_TRUNCATED,
91 RSLV_STAT_OUTDATED,
92 RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +010093};
94
Emeric Brunf8642ee2021-10-29 17:59:18 +020095static struct name_desc resolv_stats[] = {
96 [RSLV_STAT_ID] = { .name = "id", .desc = "ID" },
97 [RSLV_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
98 [RSLV_STAT_SENT] = { .name = "sent", .desc = "Sent" },
99 [RSLV_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
100 [RSLV_STAT_VALID] = { .name = "valid", .desc = "Valid" },
101 [RSLV_STAT_UPDATE] = { .name = "update", .desc = "Update" },
102 [RSLV_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
103 [RSLV_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
104 [RSLV_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
105 [RSLV_STAT_NX] = { .name = "nx", .desc = "NX" },
106 [RSLV_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
107 [RSLV_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
108 [RSLV_STAT_OTHER] = { .name = "other", .desc = "Other" },
109 [RSLV_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
110 [RSLV_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
111 [RSLV_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
112 [RSLV_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
Emeric Brunc9437992021-02-12 19:42:55 +0100113};
114
115static struct dns_counters dns_counters;
116
Emeric Brunf8642ee2021-10-29 17:59:18 +0200117static void resolv_fill_stats(void *d, struct field *stats)
Emeric Brunc9437992021-02-12 19:42:55 +0100118{
119 struct dns_counters *counters = d;
Emeric Brunf8642ee2021-10-29 17:59:18 +0200120 stats[RSLV_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
121 stats[RSLV_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
122 stats[RSLV_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
123 stats[RSLV_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
124 stats[RSLV_STAT_VALID] = mkf_u64(FN_GAUGE, counters->app.resolver.valid);
125 stats[RSLV_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->app.resolver.update);
126 stats[RSLV_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->app.resolver.cname);
127 stats[RSLV_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->app.resolver.cname_error);
128 stats[RSLV_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->app.resolver.any_err);
129 stats[RSLV_STAT_NX] = mkf_u64(FN_GAUGE, counters->app.resolver.nx);
130 stats[RSLV_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->app.resolver.timeout);
131 stats[RSLV_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->app.resolver.refused);
132 stats[RSLV_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->app.resolver.other);
133 stats[RSLV_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->app.resolver.invalid);
134 stats[RSLV_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->app.resolver.too_big);
135 stats[RSLV_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->app.resolver.truncated);
136 stats[RSLV_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +0100137}
138
Emeric Brunf8642ee2021-10-29 17:59:18 +0200139static struct stats_module rslv_stats_module = {
140 .name = "resolvers",
141 .domain_flags = STATS_DOMAIN_RESOLVERS << STATS_DOMAIN,
142 .fill_stats = resolv_fill_stats,
143 .stats = resolv_stats,
144 .stats_count = RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +0100145 .counters = &dns_counters,
146 .counters_size = sizeof(dns_counters),
147 .clearable = 0,
148};
149
Emeric Brunf8642ee2021-10-29 17:59:18 +0200150INITCALL1(STG_REGISTER, stats_register_module, &rslv_stats_module);
Emeric Brunc9437992021-02-12 19:42:55 +0100151
152/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
153 * no match is found.
154 */
155struct resolvers *find_resolvers_by_id(const char *id)
156{
157 struct resolvers *res;
158
159 list_for_each_entry(res, &sec_resolvers, list) {
160 if (strcmp(res->id, id) == 0)
161 return res;
162 }
163 return NULL;
164}
165
Emeric Brunc9437992021-02-12 19:42:55 +0100166/* Returns a pointer on the SRV request matching the name <name> for the proxy
167 * <px>. NULL is returned if no match is found.
168 */
169struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
170{
171 struct resolv_srvrq *srvrq;
172
173 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
174 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
175 return srvrq;
176 }
177 return NULL;
178}
179
180/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
181 * NULL if an error occurred. */
182struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
183{
184 struct proxy *px = srv->proxy;
185 struct resolv_srvrq *srvrq = NULL;
186 int fqdn_len, hostname_dn_len;
187
188 fqdn_len = strlen(fqdn);
Willy Tarreaubf9498a2021-10-14 07:49:49 +0200189 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100190 trash.size);
191 if (hostname_dn_len == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200192 ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100193 proxy_type_str(px), px->id, srv->id, fqdn);
194 goto err;
195 }
196
197 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200198 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100199 proxy_type_str(px), px->id, srv->id);
200 goto err;
201 }
202 srvrq->obj_type = OBJ_TYPE_SRVRQ;
203 srvrq->proxy = px;
204 srvrq->name = strdup(fqdn);
205 srvrq->hostname_dn = strdup(trash.area);
206 srvrq->hostname_dn_len = hostname_dn_len;
207 if (!srvrq->name || !srvrq->hostname_dn) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200208 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100209 proxy_type_str(px), px->id, srv->id);
210 goto err;
211 }
Emeric Brun34067662021-06-11 10:48:45 +0200212 LIST_INIT(&srvrq->attached_servers);
213 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200214 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100215 return srvrq;
216
217 err:
218 if (srvrq) {
219 free(srvrq->name);
220 free(srvrq->hostname_dn);
221 free(srvrq);
222 }
223 return NULL;
224}
225
226
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100227/* finds and return the SRV answer item associated to a requester (whose type is 'server').
228 *
229 * returns NULL in case of error or not found.
230 */
231struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
232{
233 struct resolv_resolution *res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200234 struct eb32_node *eb32;
235 struct server *srv;
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100236
237 if (!requester)
238 return NULL;
239
240 if ((srv = objt_server(requester->owner)) == NULL)
241 return NULL;
242 /* check if the server is managed by a SRV record */
243 if (srv->srvrq == NULL)
244 return NULL;
245
246 res = srv->srvrq->requester->resolution;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200247
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100248 /* search an ANSWER record whose target points to the server's hostname and whose port is
249 * the same as server's svc_port */
Willy Tarreau7893ae12021-10-21 07:39:57 +0200250 for (eb32 = eb32_first(&res->response.answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
251 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
252
Willy Tarreau75cc6532021-10-15 08:53:44 +0200253 if (memcmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100254 (srv->svc_port == item->port))
255 return item;
256 }
257
258 return NULL;
259}
260
Emeric Brunc9437992021-02-12 19:42:55 +0100261/* 2 bytes random generator to generate DNS query ID */
262static inline uint16_t resolv_rnd16(void)
263{
264 if (!resolv_query_id_seed)
265 resolv_query_id_seed = now_ms;
266 resolv_query_id_seed ^= resolv_query_id_seed << 13;
267 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
268 resolv_query_id_seed ^= resolv_query_id_seed << 17;
269 return resolv_query_id_seed;
270}
271
272
273static inline int resolv_resolution_timeout(struct resolv_resolution *res)
274{
275 return res->resolvers->timeout.resolve;
276}
277
278/* Updates a resolvers' task timeout for next wake up and queue it */
279static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
280{
281 struct resolv_resolution *res;
282 int next;
283
284 next = tick_add(now_ms, resolvers->timeout.resolve);
285 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
286 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
287 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
288 }
289
290 list_for_each_entry(res, &resolvers->resolutions.wait, list)
291 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
292
293 resolvers->t->expire = next;
294 task_queue(resolvers->t);
295}
296
297/* Forges a DNS query. It needs the following information from the caller:
298 * - <query_id> : the DNS query id corresponding to this query
299 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
300 * - <hostname_dn> : hostname in domain name format
301 * - <hostname_dn_len> : length of <hostname_dn>
302 *
303 * To store the query, the caller must pass a buffer <buf> and its size
304 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
305 * too short.
306 */
307static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
308 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
309{
310 struct dns_header dns_hdr;
311 struct dns_question qinfo;
312 struct dns_additional_record edns;
313 char *p = buf;
314
315 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
316 return -1;
317
318 memset(buf, 0, bufsize);
319
320 /* Set dns query headers */
321 dns_hdr.id = (unsigned short) htons(query_id);
322 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
323 dns_hdr.qdcount = htons(1); /* 1 question */
324 dns_hdr.ancount = 0;
325 dns_hdr.nscount = 0;
326 dns_hdr.arcount = htons(1);
327 memcpy(p, &dns_hdr, sizeof(dns_hdr));
328 p += sizeof(dns_hdr);
329
330 /* Set up query hostname */
331 memcpy(p, hostname_dn, hostname_dn_len);
332 p += hostname_dn_len;
333 *p++ = 0;
334
335 /* Set up query info (type and class) */
336 qinfo.qtype = htons(query_type);
337 qinfo.qclass = htons(DNS_RCLASS_IN);
338 memcpy(p, &qinfo, sizeof(qinfo));
339 p += sizeof(qinfo);
340
341 /* Set the DNS extension */
342 edns.name = 0;
343 edns.type = htons(DNS_RTYPE_OPT);
344 edns.udp_payload_size = htons(accepted_payload_size);
345 edns.extension = 0;
346 edns.data_length = 0;
347 memcpy(p, &edns, sizeof(edns));
348 p += sizeof(edns);
349
350 return (p - buf);
351}
352
353/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
Emeric Brun0161d322021-10-29 16:44:49 +0200354 * success or -1 if trash buffer is not large enough to build a valid query.
Emeric Brunc9437992021-02-12 19:42:55 +0100355 */
356static int resolv_send_query(struct resolv_resolution *resolution)
357{
358 struct resolvers *resolvers = resolution->resolvers;
359 struct dns_nameserver *ns;
360 int len;
361
362 /* Update resolution */
363 resolution->nb_queries = 0;
364 resolution->nb_responses = 0;
365 resolution->last_query = now_ms;
366
367 len = resolv_build_query(resolution->query_id, resolution->query_type,
368 resolvers->accepted_payload_size,
369 resolution->hostname_dn, resolution->hostname_dn_len,
370 trash.area, trash.size);
Emeric Brun0161d322021-10-29 16:44:49 +0200371 if (len < 0) {
372 send_log(NULL, LOG_NOTICE,
373 "can not build the query message for %s, in resolvers %s.\n",
374 resolution->hostname_dn, resolvers->id);
375 return -1;
376 }
Emeric Brunc9437992021-02-12 19:42:55 +0100377
378 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunc37caab2021-10-29 16:28:33 +0200379 if (dns_send_nameserver(ns, trash.area, len) >= 0)
Emeric Brunc9437992021-02-12 19:42:55 +0100380 resolution->nb_queries++;
381 }
382
383 /* Push the resolution at the end of the active list */
Willy Tarreauaae73202021-10-19 22:01:36 +0200384 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200385 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100386 return 0;
387}
388
389/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
390 * skipped and -1 if an error occurred.
391 */
392static int
393resolv_run_resolution(struct resolv_resolution *resolution)
394{
395 struct resolvers *resolvers = resolution->resolvers;
396 int query_id, i;
397
398 /* Avoid sending requests for resolutions that don't yet have an
399 * hostname, ie resolutions linked to servers that do not yet have an
400 * fqdn */
401 if (!resolution->hostname_dn)
402 return 0;
403
404 /* Check if a resolution has already been started for this server return
405 * directly to avoid resolution pill up. */
406 if (resolution->step != RSLV_STEP_NONE)
407 return 0;
408
409 /* Generates a new query id. We try at most 100 times to find a free
410 * query id */
411 for (i = 0; i < 100; ++i) {
412 query_id = resolv_rnd16();
413 if (!eb32_lookup(&resolvers->query_ids, query_id))
414 break;
415 query_id = -1;
416 }
417 if (query_id == -1) {
418 send_log(NULL, LOG_NOTICE,
419 "could not generate a query id for %s, in resolvers %s.\n",
420 resolution->hostname_dn, resolvers->id);
421 return -1;
422 }
423
424 /* Update resolution parameters */
425 resolution->query_id = query_id;
426 resolution->qid.key = query_id;
427 resolution->step = RSLV_STEP_RUNNING;
428 resolution->query_type = resolution->prefered_query_type;
429 resolution->try = resolvers->resolve_retries;
430 eb32_insert(&resolvers->query_ids, &resolution->qid);
431
432 /* Send the DNS query */
433 resolution->try -= 1;
434 resolv_send_query(resolution);
435 return 1;
436}
437
438/* Performs a name resolution for the requester <req> */
439void resolv_trigger_resolution(struct resolv_requester *req)
440{
441 struct resolvers *resolvers;
442 struct resolv_resolution *res;
443 int exp;
444
445 if (!req || !req->resolution)
446 return;
447 res = req->resolution;
448 resolvers = res->resolvers;
449
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100450 enter_resolver_code();
451
Emeric Brunc9437992021-02-12 19:42:55 +0100452 /* The resolution must not be triggered yet. Use the cached response, if
453 * valid */
454 exp = tick_add(res->last_resolution, resolvers->hold.valid);
455 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
456 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
457 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100458
459 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100460}
461
462
463/* Resets some resolution parameters to initial values and also delete the query
464 * ID from the resolver's tree.
465 */
466static void resolv_reset_resolution(struct resolv_resolution *resolution)
467{
468 /* update resolution status */
469 resolution->step = RSLV_STEP_NONE;
470 resolution->try = 0;
471 resolution->last_resolution = now_ms;
472 resolution->nb_queries = 0;
473 resolution->nb_responses = 0;
474 resolution->query_type = resolution->prefered_query_type;
475
476 /* clean up query id */
477 eb32_delete(&resolution->qid);
478 resolution->query_id = 0;
479 resolution->qid.key = 0;
480}
481
482/* Returns the query id contained in a DNS response */
483static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
484{
485 return resp[0] * 256 + resp[1];
486}
487
488
489/* Analyses, re-builds and copies the name <name> from the DNS response packet
490 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
491 * for compressed data. The result is copied into <dest>, ensuring we don't
492 * overflow using <dest_len> Returns the number of bytes the caller can move
493 * forward. If 0 it means an error occurred while parsing the name. <offset> is
494 * the number of bytes the caller could move forward.
495 */
496int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
497 unsigned char *name, char *destination, int dest_len,
498 int *offset, unsigned int depth)
499{
500 int nb_bytes = 0, n = 0;
501 int label_len;
502 unsigned char *reader = name;
503 char *dest = destination;
504
505 while (1) {
506 if (reader >= bufend)
507 goto err;
508
509 /* Name compression is in use */
510 if ((*reader & 0xc0) == 0xc0) {
511 if (reader + 1 >= bufend)
512 goto err;
513
514 /* Must point BEFORE current position */
515 if ((buffer + reader[1]) > reader)
516 goto err;
517
518 if (depth++ > 100)
519 goto err;
520
521 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
522 dest, dest_len - nb_bytes, offset, depth);
523 if (n == 0)
524 goto err;
525
526 dest += n;
527 nb_bytes += n;
528 goto out;
529 }
530
531 label_len = *reader;
532 if (label_len == 0)
533 goto out;
534
535 /* Check if:
536 * - we won't read outside the buffer
537 * - there is enough place in the destination
538 */
539 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
540 goto err;
541
542 /* +1 to take label len + label string */
543 label_len++;
544
545 memcpy(dest, reader, label_len);
546
547 dest += label_len;
548 nb_bytes += label_len;
549 reader += label_len;
550 }
551
552 out:
553 /* offset computation:
554 * parse from <name> until finding either NULL or a pointer "c0xx"
555 */
556 reader = name;
557 *offset = 0;
558 while (reader < bufend) {
559 if ((reader[0] & 0xc0) == 0xc0) {
560 *offset += 2;
561 break;
562 }
563 else if (*reader == 0) {
564 *offset += 1;
565 break;
566 }
567 *offset += 1;
568 ++reader;
569 }
570 return nb_bytes;
571
572 err:
573 return 0;
574}
575
Willy Tarreauf766ec62021-10-18 16:46:38 +0200576/* Reinitialize the list of aborted resolutions before calling certain
577 * functions relying on it. The list must be processed by calling
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100578 * leave_resolver_code() after operations.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200579 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100580static void enter_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200581{
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100582 if (!recurse)
583 LIST_INIT(&death_row);
584 recurse++;
Willy Tarreauf766ec62021-10-18 16:46:38 +0200585}
586
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100587/* Add a resolution to the death_row. */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200588static void abort_resolution(struct resolv_resolution *res)
589{
590 LIST_DEL_INIT(&res->list);
591 LIST_APPEND(&death_row, &res->list);
592}
593
594/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100595 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreauf766ec62021-10-18 16:46:38 +0200596 * needs to defer deletions. Note that some of them are in relation via internal
597 * objects and might cause the deletion of other ones from the same list, so we
598 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
599 * and solely rely on each call to remove the first remaining list element.
600 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100601static void leave_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200602{
603 struct resolv_resolution *res;
604
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100605 recurse--;
606 if (recurse)
607 return;
608
Willy Tarreauf766ec62021-10-18 16:46:38 +0200609 while (!LIST_ISEMPTY(&death_row)) {
610 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
611 resolv_free_resolution(res);
612 }
613
614 /* make sure nobody tries to add anything without having initialized it */
615 death_row = (struct list){ };
616}
617
Christopher Faulet11c6c392021-06-15 16:08:48 +0200618/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
619 * happens when an SRV item is purged or when the server status is considered as
620 * obsolete.
621 *
Willy Tarreauf766ec62021-10-18 16:46:38 +0200622 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100623 * initialized via enter_resolver_code().
Christopher Faulet11c6c392021-06-15 16:08:48 +0200624 */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200625static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet11c6c392021-06-15 16:08:48 +0200626{
Willy Tarreau6878f802021-10-20 14:07:31 +0200627 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200628 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
629 srvrq_update_srv_status(srv, 1);
630 ha_free(&srv->hostname);
631 ha_free(&srv->hostname_dn);
632 srv->hostname_dn_len = 0;
633 memset(&srv->addr, 0, sizeof(srv->addr));
634 srv->svc_port = 0;
635 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet73001ab2021-06-15 16:14:37 +0200636
637 ebpt_delete(&srv->host_dn);
638 ha_free(&srv->host_dn.key);
639
Christopher Faulet11c6c392021-06-15 16:08:48 +0200640 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreauaae73202021-10-19 22:01:36 +0200641 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200642 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Fauletdcac4182021-06-15 16:17:17 +0200643
644 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet11c6c392021-06-15 16:08:48 +0200645}
646
Christopher Fauletdcac4182021-06-15 16:17:17 +0200647/* Takes care to cleanup a server resolution when it is outdated. This only
648 * happens for a server relying on a SRV record.
649 */
650static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
651{
652 struct server *srv = context;
653
654 if (!tick_is_expired(t->expire, now_ms))
655 goto end;
656
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100657 enter_resolver_code();
Christopher Faulete886dd52021-06-18 09:05:49 +0200658 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreauf766ec62021-10-18 16:46:38 +0200659 resolv_srvrq_cleanup_srv(srv);
Christopher Faulete886dd52021-06-18 09:05:49 +0200660 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100661 leave_resolver_code();
Christopher Fauletdcac4182021-06-15 16:17:17 +0200662
663 end:
664 return t;
665}
666
Emeric Brunc9437992021-02-12 19:42:55 +0100667/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100668 * find a corresponding server.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200669 */
Emeric Brunc9437992021-02-12 19:42:55 +0100670static void resolv_check_response(struct resolv_resolution *res)
671{
672 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100673 struct resolv_requester *req;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200674 struct eb32_node *eb32, *eb32_back;
Emeric Brunbd78c912021-06-11 10:08:05 +0200675 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100676 struct resolv_srvrq *srvrq;
677
Willy Tarreau7893ae12021-10-21 07:39:57 +0200678 for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
679 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
Emeric Brunc9437992021-02-12 19:42:55 +0100680 struct resolv_answer_item *ar_item = item->ar_item;
681
682 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100683 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100684 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
685 * item is also obsolete.
686 */
Emeric Brunc9437992021-02-12 19:42:55 +0100687 pool_free(resolv_answer_item_pool, ar_item);
688 item->ar_item = NULL;
689 }
690
691 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100692 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200693 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100694 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200695 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
696 LIST_DEL_INIT(&srv->ip_rec_item);
697 }
698 }
699 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun34067662021-06-11 10:48:45 +0200700 /* Remove any associated server */
Christopher Faulet11c6c392021-06-15 16:08:48 +0200701 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreauf766ec62021-10-18 16:46:38 +0200702 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100703 }
704
Willy Tarreau7893ae12021-10-21 07:39:57 +0200705 eb32_delete(&item->link);
Emeric Brunc9437992021-02-12 19:42:55 +0100706 if (item->ar_item) {
707 pool_free(resolv_answer_item_pool, item->ar_item);
708 item->ar_item = NULL;
709 }
710 pool_free(resolv_answer_item_pool, item);
711 continue;
712 }
713
714 if (item->type != DNS_RTYPE_SRV)
715 continue;
716
717 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100718 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun34067662021-06-11 10:48:45 +0200719 struct ebpt_node *node;
720 char target[DNS_MAX_NAME_SIZE+1];
721
722 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100723 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
724 continue;
725
Emeric Brun34067662021-06-11 10:48:45 +0200726 /* Check if a server already uses that record */
727 srv = NULL;
728 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
729 if (srv->srvrq == srvrq) {
730 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
731 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100732 }
Emeric Brunc9437992021-02-12 19:42:55 +0100733 }
734
Emeric Brun34067662021-06-11 10:48:45 +0200735
736 /* If not empty we try to match a server
737 * in server state file tree with the same hostname
738 */
739 if (!eb_is_empty(&srvrq->named_servers)) {
740 srv = NULL;
741
742 /* convert the key to lookup in lower case */
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200743 for (i = 0 ; item->data.target[i] ; i++)
744 target[i] = tolower(item->data.target[i]);
Christopher Faulet1f923392021-07-22 14:29:26 +0200745 target[i] = 0;
Emeric Brun34067662021-06-11 10:48:45 +0200746
747 node = ebis_lookup(&srvrq->named_servers, target);
748 if (node) {
749 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100750 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun34067662021-06-11 10:48:45 +0200751
752 /* an entry was found with the same hostname
753 * let check this node if the port matches
754 * and try next node if the hostname
755 * is still the same
756 */
757 while (1) {
758 if (srv->svc_port == item->port) {
759 /* server found, we remove it from tree */
760 ebpt_delete(node);
Christopher Faulet73001ab2021-06-15 16:14:37 +0200761 ha_free(&srv->host_dn.key);
Emeric Brun34067662021-06-11 10:48:45 +0200762 goto srv_found;
763 }
764
765 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
766
767 node = ebpt_next(node);
768 if (!node)
769 break;
770
771 srv = ebpt_entry(node, struct server, host_dn);
772 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
773
774 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau75cc6532021-10-15 08:53:44 +0200775 || memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
Emeric Brun34067662021-06-11 10:48:45 +0200776 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
777 break;
778 }
779 }
Emeric Brunc9437992021-02-12 19:42:55 +0100780 }
781 }
Emeric Brun34067662021-06-11 10:48:45 +0200782
783 /* Pick the first server listed in srvrq (those ones don't
784 * have hostname and are free to use)
785 */
786 srv = NULL;
787 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
788 LIST_DEL_INIT(&srv->srv_rec_item);
789 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
790 goto srv_found;
791 }
792 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100793
Emeric Brun34067662021-06-11 10:48:45 +0200794srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100795 /* And update this server, if found (srv is locked here) */
796 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100797 /* re-enable DNS resolution for this server by default */
798 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Fauletdcac4182021-06-15 16:17:17 +0200799 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100800
Emeric Brunc9437992021-02-12 19:42:55 +0100801 /* Check if an Additional Record is associated to this SRV record.
802 * Perform some sanity checks too to ensure the record can be used.
803 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100804 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100805 */
806 if ((item->ar_item != NULL) &&
807 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100808 {
Emeric Brunc9437992021-02-12 19:42:55 +0100809
810 switch (item->ar_item->type) {
811 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200812 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100813 break;
814 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200815 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100816 break;
817 }
818
819 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100820
821 /* Unlink A/AAAA resolution for this server if there is an AR item.
822 * It is usless to perform an extra resolution
823 */
Willy Tarreau6878f802021-10-20 14:07:31 +0200824 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100825 }
826
827 if (!srv->hostname_dn) {
828 const char *msg = NULL;
Willy Tarreau85c15e62021-10-14 08:00:38 +0200829 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100830
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200831 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau85c15e62021-10-14 08:00:38 +0200832 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100833 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
834 continue;
835 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100836 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100837 if (msg)
838 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
839 }
840
Emeric Brun34067662021-06-11 10:48:45 +0200841 if (!LIST_INLIST(&srv->srv_rec_item))
842 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
843
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100844 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
845 /* If there is no AR item responsible of the FQDN resolution,
846 * trigger a dedicated DNS resolution
847 */
848 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
849 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
850 }
851
Christopher Fauletab177ac2021-03-10 15:34:52 +0100852 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100853 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100854
855 srv->svc_port = item->port;
856 srv->flags &= ~SRV_F_MAPPORTS;
857
858 if (!srv->resolv_opts.ignore_weight) {
859 char weight[9];
860 int ha_weight;
861
862 /* DNS weight range if from 0 to 65535
863 * HAProxy weight is from 0 to 256
864 * The rule below ensures that weight 0 is well respected
865 * while allowing a "mapping" from DNS weight into HAProxy's one.
866 */
867 ha_weight = (item->weight + 255) / 256;
868
869 snprintf(weight, sizeof(weight), "%d", ha_weight);
870 server_parse_weight_change_request(srv, weight);
871 }
872 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
873 }
874 }
875 }
876}
877
878/* Validates that the buffer DNS response provided in <resp> and finishing
879 * before <bufend> is valid from a DNS protocol point of view.
880 *
881 * The result is stored in <resolution>' response, buf_response,
882 * response_query_records and response_answer_records members.
883 *
884 * This function returns one of the RSLV_RESP_* code to indicate the type of
885 * error found.
886 */
887static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
888 struct resolv_resolution *resolution, int max_answer_records)
889{
890 unsigned char *reader;
891 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
892 int len, flags, offset;
Emeric Brunc9437992021-02-12 19:42:55 +0100893 int nb_saved_records;
894 struct resolv_query_item *query;
895 struct resolv_answer_item *answer_record, *tmp_record;
896 struct resolv_response *r_res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200897 struct eb32_node *eb32;
Willy Tarreaudcb696c2021-10-21 08:18:01 +0200898 uint32_t key = 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100899 int i, found = 0;
900 int cause = RSLV_RESP_ERROR;
901
902 reader = resp;
903 len = 0;
904 previous_dname = NULL;
905 query = NULL;
906 answer_record = NULL;
907
908 /* Initialization of response buffer and structure */
909 r_res = &resolution->response;
910
911 /* query id */
912 if (reader + 2 >= bufend)
913 goto invalid_resp;
914
915 r_res->header.id = reader[0] * 256 + reader[1];
916 reader += 2;
917
918 /* Flags and rcode are stored over 2 bytes
919 * First byte contains:
920 * - response flag (1 bit)
921 * - opcode (4 bits)
922 * - authoritative (1 bit)
923 * - truncated (1 bit)
924 * - recursion desired (1 bit)
925 */
926 if (reader + 2 >= bufend)
927 goto invalid_resp;
928
929 flags = reader[0] * 256 + reader[1];
930
931 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
932 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
933 cause = RSLV_RESP_NX_DOMAIN;
934 goto return_error;
935 }
936 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
937 cause = RSLV_RESP_REFUSED;
938 goto return_error;
939 }
940 else {
941 cause = RSLV_RESP_ERROR;
942 goto return_error;
943 }
944 }
945
946 /* Move forward 2 bytes for flags */
947 reader += 2;
948
949 /* 2 bytes for question count */
950 if (reader + 2 >= bufend)
951 goto invalid_resp;
952 r_res->header.qdcount = reader[0] * 256 + reader[1];
953 /* (for now) we send one query only, so we expect only one in the
954 * response too */
955 if (r_res->header.qdcount != 1) {
956 cause = RSLV_RESP_QUERY_COUNT_ERROR;
957 goto return_error;
958 }
959
960 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
961 goto invalid_resp;
962 reader += 2;
963
964 /* 2 bytes for answer count */
965 if (reader + 2 >= bufend)
966 goto invalid_resp;
967 r_res->header.ancount = reader[0] * 256 + reader[1];
968 if (r_res->header.ancount == 0) {
969 cause = RSLV_RESP_ANCOUNT_ZERO;
970 goto return_error;
971 }
972
973 /* Check if too many records are announced */
974 if (r_res->header.ancount > max_answer_records)
975 goto invalid_resp;
976 reader += 2;
977
978 /* 2 bytes authority count */
979 if (reader + 2 >= bufend)
980 goto invalid_resp;
981 r_res->header.nscount = reader[0] * 256 + reader[1];
982 reader += 2;
983
984 /* 2 bytes additional count */
985 if (reader + 2 >= bufend)
986 goto invalid_resp;
987 r_res->header.arcount = reader[0] * 256 + reader[1];
988 reader += 2;
989
Christopher Fauletc1699f82021-12-01 15:07:26 +0100990 /* Parsing dns queries. For now there is only one query and it exists
991 * because (qdcount == 1).
992 */
993 query = &resolution->response_query_records[0];
Emeric Brunc9437992021-02-12 19:42:55 +0100994
Christopher Fauletc1699f82021-12-01 15:07:26 +0100995 /* Name is a NULL terminated string in our case, since we have
996 * one query per response and the first one can't be compressed
997 * (using the 0x0c format) */
998 offset = 0;
999 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01001000
Christopher Fauletc1699f82021-12-01 15:07:26 +01001001 if (len == 0)
1002 goto invalid_resp;
Emeric Brunc9437992021-02-12 19:42:55 +01001003
Christopher Fauletc1699f82021-12-01 15:07:26 +01001004 /* Now let's check the query's dname corresponds to the one we sent. */
1005 if (len != resolution->hostname_dn_len ||
1006 memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
1007 cause = RSLV_RESP_WRONG_NAME;
Christopher Fauletaf93d2f2021-12-02 10:05:02 +01001008 goto return_error;
Christopher Fauletc1699f82021-12-01 15:07:26 +01001009 }
Emeric Brunc9437992021-02-12 19:42:55 +01001010
Christopher Fauletc1699f82021-12-01 15:07:26 +01001011 reader += offset;
1012 previous_dname = query->name;
Emeric Brunc9437992021-02-12 19:42:55 +01001013
Christopher Fauletc1699f82021-12-01 15:07:26 +01001014 /* move forward 2 bytes for question type */
1015 if (reader + 2 >= bufend)
1016 goto invalid_resp;
1017 query->type = reader[0] * 256 + reader[1];
1018 reader += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001019
Christopher Fauletc1699f82021-12-01 15:07:26 +01001020 /* move forward 2 bytes for question class */
1021 if (reader + 2 >= bufend)
1022 goto invalid_resp;
1023 query->class = reader[0] * 256 + reader[1];
1024 reader += 2;
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001025
Emeric Brunc9437992021-02-12 19:42:55 +01001026 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001027 * because a TRUNCATED SRV query type response can still be exploited
1028 */
Emeric Brunc9437992021-02-12 19:42:55 +01001029 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1030 cause = RSLV_RESP_TRUNCATED;
1031 goto return_error;
1032 }
1033
1034 /* now parsing response records */
1035 nb_saved_records = 0;
1036 for (i = 0; i < r_res->header.ancount; i++) {
1037 if (reader >= bufend)
1038 goto invalid_resp;
1039
1040 answer_record = pool_alloc(resolv_answer_item_pool);
1041 if (answer_record == NULL)
1042 goto invalid_resp;
1043
1044 /* initialization */
1045 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001046 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001047 LIST_INIT(&answer_record->attached_servers);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001048 answer_record->link.node.leaf_p = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001049
1050 offset = 0;
1051 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1052
1053 if (len == 0)
1054 goto invalid_resp;
1055
1056 /* Check if the current record dname is valid. previous_dname
1057 * points either to queried dname or last CNAME target */
Willy Tarreau75cc6532021-10-15 08:53:44 +02001058 if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001059 if (i == 0) {
1060 /* First record, means a mismatch issue between
1061 * queried dname and dname found in the first
1062 * record */
1063 goto invalid_resp;
1064 }
1065 else {
1066 /* If not the first record, this means we have a
1067 * CNAME resolution error.
1068 */
1069 cause = RSLV_RESP_CNAME_ERROR;
1070 goto return_error;
1071 }
1072
1073 }
1074
1075 memcpy(answer_record->name, tmpname, len);
1076 answer_record->name[len] = 0;
1077
1078 reader += offset;
1079 if (reader >= bufend)
1080 goto invalid_resp;
1081
1082 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1083 if (reader + 2 > bufend)
1084 goto invalid_resp;
1085
1086 answer_record->type = reader[0] * 256 + reader[1];
1087 reader += 2;
1088
1089 /* 2 bytes for class (2) */
1090 if (reader + 2 > bufend)
1091 goto invalid_resp;
1092
1093 answer_record->class = reader[0] * 256 + reader[1];
1094 reader += 2;
1095
1096 /* 4 bytes for ttl (4) */
1097 if (reader + 4 > bufend)
1098 goto invalid_resp;
1099
1100 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1101 + reader[2] * 256 + reader[3];
1102 reader += 4;
1103
1104 /* Now reading data len */
1105 if (reader + 2 > bufend)
1106 goto invalid_resp;
1107
1108 answer_record->data_len = reader[0] * 256 + reader[1];
1109
1110 /* Move forward 2 bytes for data len */
1111 reader += 2;
1112
1113 if (reader + answer_record->data_len > bufend)
1114 goto invalid_resp;
1115
1116 /* Analyzing record content */
1117 switch (answer_record->type) {
1118 case DNS_RTYPE_A:
1119 /* ipv4 is stored on 4 bytes */
1120 if (answer_record->data_len != 4)
1121 goto invalid_resp;
1122
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001123 answer_record->data.in4.sin_family = AF_INET;
1124 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001125 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001126 break;
1127
1128 case DNS_RTYPE_CNAME:
1129 /* Check if this is the last record and update the caller about the status:
1130 * no IP could be found and last record was a CNAME. Could be triggered
1131 * by a wrong query type
1132 *
1133 * + 1 because answer_record_id starts at 0
1134 * while number of answers is an integer and
1135 * starts at 1.
1136 */
1137 if (i + 1 == r_res->header.ancount) {
1138 cause = RSLV_RESP_CNAME_ERROR;
1139 goto return_error;
1140 }
1141
1142 offset = 0;
1143 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1144 if (len == 0)
1145 goto invalid_resp;
1146
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001147 memcpy(answer_record->data.target, tmpname, len);
1148 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001149 key = XXH32(tmpname, len, answer_record->type);
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001150 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001151 break;
1152
1153
1154 case DNS_RTYPE_SRV:
1155 /* Answer must contain :
1156 * - 2 bytes for the priority
1157 * - 2 bytes for the weight
1158 * - 2 bytes for the port
1159 * - the target hostname
1160 */
1161 if (answer_record->data_len <= 6)
1162 goto invalid_resp;
1163
1164 answer_record->priority = read_n16(reader);
1165 reader += sizeof(uint16_t);
1166 answer_record->weight = read_n16(reader);
1167 reader += sizeof(uint16_t);
1168 answer_record->port = read_n16(reader);
1169 reader += sizeof(uint16_t);
1170 offset = 0;
1171 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1172 if (len == 0)
1173 goto invalid_resp;
1174
1175 answer_record->data_len = len;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001176 memcpy(answer_record->data.target, tmpname, len);
1177 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001178 key = XXH32(tmpname, len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001179 if (answer_record->ar_item != NULL) {
1180 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1181 answer_record->ar_item = NULL;
1182 }
1183 break;
1184
1185 case DNS_RTYPE_AAAA:
1186 /* ipv6 is stored on 16 bytes */
1187 if (answer_record->data_len != 16)
1188 goto invalid_resp;
1189
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001190 answer_record->data.in6.sin6_family = AF_INET6;
1191 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001192 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001193 break;
1194
1195 } /* switch (record type) */
1196
1197 /* Increment the counter for number of records saved into our
1198 * local response */
1199 nb_saved_records++;
1200
1201 /* Move forward answer_record->data_len for analyzing next
1202 * record in the response */
1203 reader += ((answer_record->type == DNS_RTYPE_SRV)
1204 ? offset
1205 : answer_record->data_len);
1206
1207 /* Lookup to see if we already had this entry */
1208 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001209
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001210 for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02001211 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001212 if (tmp_record->type != answer_record->type)
1213 continue;
1214
1215 switch(tmp_record->type) {
1216 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001217 if (!memcmp(&answer_record->data.in4.sin_addr,
1218 &tmp_record->data.in4.sin_addr,
1219 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001220 found = 1;
1221 break;
1222
1223 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001224 if (!memcmp(&answer_record->data.in6.sin6_addr,
1225 &tmp_record->data.in6.sin6_addr,
1226 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001227 found = 1;
1228 break;
1229
1230 case DNS_RTYPE_SRV:
1231 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001232 memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
Emeric Brunc9437992021-02-12 19:42:55 +01001233 answer_record->port == tmp_record->port) {
1234 tmp_record->weight = answer_record->weight;
1235 found = 1;
1236 }
1237 break;
1238
1239 default:
1240 break;
1241 }
1242
1243 if (found == 1)
1244 break;
1245 }
1246
1247 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001248 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001249 pool_free(resolv_answer_item_pool, answer_record);
1250 answer_record = NULL;
1251 }
1252 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001253 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001254 answer_record->ar_item = NULL;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001255 answer_record->link.key = key;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001256 eb32_insert(&r_res->answer_tree, &answer_record->link);
Emeric Brunc9437992021-02-12 19:42:55 +01001257 answer_record = NULL;
1258 }
1259 } /* for i 0 to ancount */
1260
1261 /* Save the number of records we really own */
1262 r_res->header.ancount = nb_saved_records;
1263
1264 /* now parsing additional records for SRV queries only */
1265 if (query->type != DNS_RTYPE_SRV)
1266 goto skip_parsing_additional_records;
1267
1268 /* if we find Authority records, just skip them */
1269 for (i = 0; i < r_res->header.nscount; i++) {
1270 offset = 0;
1271 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1272 &offset, 0);
1273 if (len == 0)
1274 continue;
1275
1276 if (reader + offset + 10 >= bufend)
1277 goto invalid_resp;
1278
1279 reader += offset;
1280 /* skip 2 bytes for class */
1281 reader += 2;
1282 /* skip 2 bytes for type */
1283 reader += 2;
1284 /* skip 4 bytes for ttl */
1285 reader += 4;
1286 /* read data len */
1287 len = reader[0] * 256 + reader[1];
1288 reader += 2;
1289
1290 if (reader + len >= bufend)
1291 goto invalid_resp;
1292
1293 reader += len;
1294 }
1295
1296 nb_saved_records = 0;
1297 for (i = 0; i < r_res->header.arcount; i++) {
1298 if (reader >= bufend)
1299 goto invalid_resp;
1300
1301 answer_record = pool_alloc(resolv_answer_item_pool);
1302 if (answer_record == NULL)
1303 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001304 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001305 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001306
1307 offset = 0;
1308 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1309
1310 if (len == 0) {
1311 pool_free(resolv_answer_item_pool, answer_record);
1312 answer_record = NULL;
1313 continue;
1314 }
1315
1316 memcpy(answer_record->name, tmpname, len);
1317 answer_record->name[len] = 0;
1318
1319 reader += offset;
1320 if (reader >= bufend)
1321 goto invalid_resp;
1322
1323 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1324 if (reader + 2 > bufend)
1325 goto invalid_resp;
1326
1327 answer_record->type = reader[0] * 256 + reader[1];
1328 reader += 2;
1329
1330 /* 2 bytes for class (2) */
1331 if (reader + 2 > bufend)
1332 goto invalid_resp;
1333
1334 answer_record->class = reader[0] * 256 + reader[1];
1335 reader += 2;
1336
1337 /* 4 bytes for ttl (4) */
1338 if (reader + 4 > bufend)
1339 goto invalid_resp;
1340
1341 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1342 + reader[2] * 256 + reader[3];
1343 reader += 4;
1344
1345 /* Now reading data len */
1346 if (reader + 2 > bufend)
1347 goto invalid_resp;
1348
1349 answer_record->data_len = reader[0] * 256 + reader[1];
1350
1351 /* Move forward 2 bytes for data len */
1352 reader += 2;
1353
1354 if (reader + answer_record->data_len > bufend)
1355 goto invalid_resp;
1356
1357 /* Analyzing record content */
1358 switch (answer_record->type) {
1359 case DNS_RTYPE_A:
1360 /* ipv4 is stored on 4 bytes */
1361 if (answer_record->data_len != 4)
1362 goto invalid_resp;
1363
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001364 answer_record->data.in4.sin_family = AF_INET;
1365 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001366 break;
1367
1368 case DNS_RTYPE_AAAA:
1369 /* ipv6 is stored on 16 bytes */
1370 if (answer_record->data_len != 16)
1371 goto invalid_resp;
1372
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001373 answer_record->data.in6.sin6_family = AF_INET6;
1374 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001375 break;
1376
1377 default:
1378 pool_free(resolv_answer_item_pool, answer_record);
1379 answer_record = NULL;
1380 continue;
1381
1382 } /* switch (record type) */
1383
1384 /* Increment the counter for number of records saved into our
1385 * local response */
1386 nb_saved_records++;
1387
1388 /* Move forward answer_record->data_len for analyzing next
1389 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001390 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001391
1392 /* Lookup to see if we already had this entry */
1393 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001394
1395 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001396 struct resolv_answer_item *ar_item;
1397
Willy Tarreau7893ae12021-10-21 07:39:57 +02001398 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Christopher Faulet77f86062021-03-10 15:19:57 +01001399 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1400 continue;
1401
1402 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001403 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001404 len != tmp_record->data_len ||
Willy Tarreau75cc6532021-10-15 08:53:44 +02001405 memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001406 continue;
1407
Christopher Faulet77f86062021-03-10 15:19:57 +01001408 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001409 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001410 if (!memcmp(&answer_record->data.in4.sin_addr,
1411 &ar_item->data.in4.sin_addr,
1412 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001413 found = 1;
1414 break;
1415
1416 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001417 if (!memcmp(&answer_record->data.in6.sin6_addr,
1418 &ar_item->data.in6.sin6_addr,
1419 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001420 found = 1;
1421 break;
1422
1423 default:
1424 break;
1425 }
1426
1427 if (found == 1)
1428 break;
1429 }
1430
1431 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001432 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001433 pool_free(resolv_answer_item_pool, answer_record);
1434 answer_record = NULL;
1435 }
1436 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001437 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001438 answer_record->ar_item = NULL;
1439
1440 // looking for the SRV record in the response list linked to this additional record
Willy Tarreau7893ae12021-10-21 07:39:57 +02001441 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
1442 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
1443
Emeric Brunc9437992021-02-12 19:42:55 +01001444 if (tmp_record->type == DNS_RTYPE_SRV &&
1445 tmp_record->ar_item == NULL &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001446 memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001447 /* Always use the received additional record to refresh info */
1448 if (tmp_record->ar_item)
1449 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1450 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001451 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001452 break;
1453 }
1454 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001455 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001456 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001457 answer_record = NULL;
1458 }
Emeric Brunc9437992021-02-12 19:42:55 +01001459 }
1460 } /* for i 0 to arcount */
1461
1462 skip_parsing_additional_records:
1463
1464 /* Save the number of records we really own */
1465 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001466 resolv_check_response(resolution);
1467 return RSLV_RESP_VALID;
1468
1469 invalid_resp:
1470 cause = RSLV_RESP_INVALID;
1471
1472 return_error:
1473 pool_free(resolv_answer_item_pool, answer_record);
1474 return cause;
1475}
1476
1477/* Searches dn_name resolution in resp.
1478 * If existing IP not found, return the first IP matching family_priority,
1479 * otherwise, first ip found
1480 * The following tasks are the responsibility of the caller:
1481 * - <r_res> contains an error free DNS response
1482 * For both cases above, resolv_validate_dns_response is required
1483 * returns one of the RSLV_UPD_* code
1484 */
1485int resolv_get_ip_from_response(struct resolv_response *r_res,
1486 struct resolv_options *resolv_opts, void *currentip,
1487 short currentip_sin_family,
1488 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001489 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001490{
Emeric Brunbd78c912021-06-11 10:08:05 +02001491 struct resolv_answer_item *record, *found_record = NULL;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001492 struct eb32_node *eb32;
Emeric Brunc9437992021-02-12 19:42:55 +01001493 int family_priority;
1494 int currentip_found;
1495 unsigned char *newip4, *newip6;
1496 int currentip_sel;
1497 int j;
1498 int score, max_score;
1499 int allowed_duplicated_ip;
1500
Emeric Brunbd78c912021-06-11 10:08:05 +02001501 /* srv is linked to an alive ip record */
1502 if (owner && LIST_INLIST(&owner->ip_rec_item))
1503 return RSLV_UPD_NO;
1504
Emeric Brunc9437992021-02-12 19:42:55 +01001505 family_priority = resolv_opts->family_prio;
1506 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1507 *newip = newip4 = newip6 = NULL;
1508 currentip_found = 0;
1509 *newip_sin_family = AF_UNSPEC;
1510 max_score = -1;
1511
1512 /* Select an IP regarding configuration preference.
1513 * Top priority is the preferred network ip version,
1514 * second priority is the preferred network.
1515 * the last priority is the currently used IP,
1516 *
1517 * For these three priorities, a score is calculated. The
1518 * weight are:
1519 * 8 - preferred ip version.
1520 * 4 - preferred network.
1521 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1522 * 1 - current ip.
1523 * The result with the biggest score is returned.
1524 */
1525
Willy Tarreau7893ae12021-10-21 07:39:57 +02001526 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001527 void *ip;
1528 unsigned char ip_type;
1529
Willy Tarreau7893ae12021-10-21 07:39:57 +02001530 record = eb32_entry(eb32, typeof(*record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001531 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001532 ip_type = AF_INET;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001533 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001534 }
1535 else if (record->type == DNS_RTYPE_AAAA) {
1536 ip_type = AF_INET6;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001537 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001538 }
1539 else
1540 continue;
1541 score = 0;
1542
1543 /* Check for preferred ip protocol. */
1544 if (ip_type == family_priority)
1545 score += 8;
1546
1547 /* Check for preferred network. */
1548 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1549
1550 /* Compare only the same addresses class. */
1551 if (resolv_opts->pref_net[j].family != ip_type)
1552 continue;
1553
1554 if ((ip_type == AF_INET &&
1555 in_net_ipv4(ip,
1556 &resolv_opts->pref_net[j].mask.in4,
1557 &resolv_opts->pref_net[j].addr.in4)) ||
1558 (ip_type == AF_INET6 &&
1559 in_net_ipv6(ip,
1560 &resolv_opts->pref_net[j].mask.in6,
1561 &resolv_opts->pref_net[j].addr.in6))) {
1562 score += 4;
1563 break;
1564 }
1565 }
1566
1567 /* Check if the IP found in the record is already affected to a
1568 * member of a group. If not, the score should be incremented
1569 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001570 if (owner) {
1571 struct server *srv;
1572 int already_used = 0;
1573
1574 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1575 if (srv == owner)
1576 continue;
1577 if (srv->proxy == owner->proxy) {
1578 already_used = 1;
1579 break;
1580 }
1581 }
1582 if (already_used) {
1583 if (!allowed_duplicated_ip) {
1584 continue;
1585 }
1586 }
1587 else {
1588 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001589 }
1590 } else {
1591 score += 2;
1592 }
1593
1594 /* Check for current ip matching. */
1595 if (ip_type == currentip_sin_family &&
1596 ((currentip_sin_family == AF_INET &&
1597 !memcmp(ip, currentip, 4)) ||
1598 (currentip_sin_family == AF_INET6 &&
1599 !memcmp(ip, currentip, 16)))) {
1600 score++;
1601 currentip_sel = 1;
1602 }
1603 else
1604 currentip_sel = 0;
1605
1606 /* Keep the address if the score is better than the previous
1607 * score. The maximum score is 15, if this value is reached, we
1608 * break the parsing. Implicitly, this score is reached the ip
1609 * selected is the current ip. */
1610 if (score > max_score) {
1611 if (ip_type == AF_INET)
1612 newip4 = ip;
1613 else
1614 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001615 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001616 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001617 if (score == 15) {
1618 /* this was not registered on the current record but it matches
1619 * let's fix it (it may comes from state file */
1620 if (owner)
1621 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001622 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001623 }
Emeric Brunc9437992021-02-12 19:42:55 +01001624 max_score = score;
1625 }
1626 } /* list for each record entries */
1627
1628 /* No IP found in the response */
1629 if (!newip4 && !newip6)
1630 return RSLV_UPD_NO_IP_FOUND;
1631
1632 /* Case when the caller looks first for an IPv4 address */
1633 if (family_priority == AF_INET) {
1634 if (newip4) {
1635 *newip = newip4;
1636 *newip_sin_family = AF_INET;
1637 }
1638 else if (newip6) {
1639 *newip = newip6;
1640 *newip_sin_family = AF_INET6;
1641 }
Emeric Brunc9437992021-02-12 19:42:55 +01001642 }
1643 /* Case when the caller looks first for an IPv6 address */
1644 else if (family_priority == AF_INET6) {
1645 if (newip6) {
1646 *newip = newip6;
1647 *newip_sin_family = AF_INET6;
1648 }
1649 else if (newip4) {
1650 *newip = newip4;
1651 *newip_sin_family = AF_INET;
1652 }
Emeric Brunc9437992021-02-12 19:42:55 +01001653 }
1654 /* Case when the caller have no preference (we prefer IPv6) */
1655 else if (family_priority == AF_UNSPEC) {
1656 if (newip6) {
1657 *newip = newip6;
1658 *newip_sin_family = AF_INET6;
1659 }
1660 else if (newip4) {
1661 *newip = newip4;
1662 *newip_sin_family = AF_INET;
1663 }
Emeric Brunc9437992021-02-12 19:42:55 +01001664 }
1665
Emeric Brunbd78c912021-06-11 10:08:05 +02001666 /* the ip of this record was chosen for the server */
1667 if (owner && found_record) {
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001668 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunbd78c912021-06-11 10:08:05 +02001669 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1670 }
1671
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001672 eb32 = eb32_first(&r_res->answer_tree);
1673 if (eb32) {
Emeric Brunc9437992021-02-12 19:42:55 +01001674 /* Move the first record to the end of the list, for internal
Willy Tarreau7893ae12021-10-21 07:39:57 +02001675 * round robin.
1676 */
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001677 eb32_delete(eb32);
1678 eb32_insert(&r_res->answer_tree, eb32);
Emeric Brunc9437992021-02-12 19:42:55 +01001679 }
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001680
1681 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001682}
1683
Willy Tarreau875ee702021-10-14 08:05:25 +02001684/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001685 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001686 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1687 * null-terminated. <str> must be allocated large enough to contain a full host
1688 * name plus the trailing zero, and the allocated size must be passed in
1689 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001690 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001691 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001692 * <str> (including the terminating null byte).
1693 */
1694int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1695{
1696 char *ptr;
1697 int i, sz;
1698
Willy Tarreau875ee702021-10-14 08:05:25 +02001699 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001700 return -1;
1701
1702 ptr = str;
Willy Tarreau875ee702021-10-14 08:05:25 +02001703 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001704 sz = dn[i];
1705 if (i)
1706 *ptr++ = '.';
Willy Tarreau814889c2021-10-15 07:45:38 +02001707 /* copy the string at i+1 to lower case */
1708 for (; sz > 0; sz--)
1709 *(ptr++) = tolower(dn[++i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001710 }
1711 *ptr++ = '\0';
1712 return (ptr - str);
1713}
1714
1715/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1716 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001717 * <str> contains the input string that is <str_len> bytes long (trailing zero
1718 * not needed). <dn> buffer must be allocated large enough to contain the
1719 * encoded string and a trailing zero, so it must be at least str_len+2, and
1720 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001721 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001722 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001723 * <dn> (excluding the terminating null byte).
1724 */
1725int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1726{
1727 int i, offset;
1728
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001729 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001730 return -1;
1731
1732 /* First byte of dn will be used to store the length of the first
1733 * label */
1734 offset = 0;
1735 for (i = 0; i < str_len; ++i) {
1736 if (str[i] == '.') {
1737 /* 2 or more consecutive dots is invalid */
1738 if (i == offset)
1739 return -1;
1740
1741 /* ignore trailing dot */
Christopher Faulet0a82cf42022-01-28 17:47:57 +01001742 if (i + 1 == str_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001743 break;
Emeric Brunc9437992021-02-12 19:42:55 +01001744
1745 dn[offset] = (i - offset);
1746 offset = i+1;
1747 continue;
1748 }
Willy Tarreau814889c2021-10-15 07:45:38 +02001749 dn[i+1] = tolower(str[i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001750 }
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001751 dn[offset] = i - offset;
Willy Tarreau7b232f12021-10-15 08:09:25 +02001752 dn[i+1] = '\0';
1753 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001754}
1755
1756/* Validates host name:
1757 * - total size
1758 * - each label size individually
1759 * returns:
1760 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1761 * 1 when no error. <err> is left unaffected.
1762 */
1763int resolv_hostname_validation(const char *string, char **err)
1764{
1765 int i;
1766
1767 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1768 if (err)
1769 *err = DNS_TOO_LONG_FQDN;
1770 return 0;
1771 }
1772
1773 while (*string) {
1774 i = 0;
1775 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1776 if (!(*string == '-' || *string == '_' ||
1777 (*string >= 'a' && *string <= 'z') ||
1778 (*string >= 'A' && *string <= 'Z') ||
1779 (*string >= '0' && *string <= '9'))) {
1780 if (err)
1781 *err = DNS_INVALID_CHARACTER;
1782 return 0;
1783 }
1784 i++;
1785 string++;
1786 }
1787
1788 if (!(*string))
1789 break;
1790
1791 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1792 if (err)
1793 *err = DNS_LABEL_TOO_LONG;
1794 return 0;
1795 }
1796
1797 string++;
1798 }
1799 return 1;
1800}
1801
1802/* Picks up an available resolution from the different resolution list
1803 * associated to a resolvers section, in this order:
1804 * 1. check in resolutions.curr for the same hostname and query_type
1805 * 2. check in resolutions.wait for the same hostname and query_type
1806 * 3. Get a new resolution from resolution pool
1807 *
1808 * Returns an available resolution, NULL if none found.
1809 */
1810static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1811 char **hostname_dn, int hostname_dn_len,
1812 int query_type)
1813{
1814 struct resolv_resolution *res;
1815
1816 if (!*hostname_dn)
1817 goto from_pool;
1818
1819 /* Search for same hostname and query type in resolutions.curr */
1820 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1821 if (!res->hostname_dn)
1822 continue;
1823 if ((query_type == res->prefered_query_type) &&
1824 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001825 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001826 return res;
1827 }
1828
1829 /* Search for same hostname and query type in resolutions.wait */
1830 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1831 if (!res->hostname_dn)
1832 continue;
1833 if ((query_type == res->prefered_query_type) &&
1834 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001835 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001836 return res;
1837 }
1838
1839 from_pool:
1840 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001841 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001842 if (res) {
Emeric Brunc9437992021-02-12 19:42:55 +01001843 res->resolvers = resolvers;
1844 res->uuid = resolution_uuid;
1845 res->status = RSLV_STATUS_NONE;
1846 res->step = RSLV_STEP_NONE;
1847 res->last_valid = now_ms;
1848
1849 LIST_INIT(&res->requesters);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001850 res->response.answer_tree = EB_ROOT;
Emeric Brunc9437992021-02-12 19:42:55 +01001851
1852 res->prefered_query_type = query_type;
1853 res->query_type = query_type;
1854 res->hostname_dn = *hostname_dn;
1855 res->hostname_dn_len = hostname_dn_len;
1856
1857 ++resolution_uuid;
1858
1859 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001860 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001861 }
1862 return res;
1863}
1864
Willy Tarreau2acc1602021-10-19 11:16:11 +02001865/* deletes and frees all answer_items from the resolution's answer_list */
1866static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001867{
Willy Tarreau7893ae12021-10-21 07:39:57 +02001868 struct eb32_node *eb32, *eb32_back;
1869 struct resolv_answer_item *item;
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001870
Willy Tarreau7893ae12021-10-21 07:39:57 +02001871 for (eb32 = eb32_first(&resolution->response.answer_tree);
1872 eb32 && (eb32_back = eb32_next(eb32), 1);
1873 eb32 = eb32_back) {
1874 item = eb32_entry(eb32, typeof(*item), link);
1875 eb32_delete(&item->link);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001876 pool_free(resolv_answer_item_pool, item->ar_item);
1877 pool_free(resolv_answer_item_pool, item);
1878 }
1879}
1880
Emeric Brunc9437992021-02-12 19:42:55 +01001881/* Releases a resolution from its requester(s) and move it back to the pool */
1882static void resolv_free_resolution(struct resolv_resolution *resolution)
1883{
1884 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001885
1886 /* clean up configuration */
1887 resolv_reset_resolution(resolution);
1888 resolution->hostname_dn = NULL;
1889 resolution->hostname_dn_len = 0;
1890
1891 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02001892 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001893 req->resolution = NULL;
1894 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001895 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau25e01092021-10-19 11:17:33 +02001896
Willy Tarreauaae73202021-10-19 22:01:36 +02001897 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001898 pool_free(resolv_resolution_pool, resolution);
1899}
1900
Willy Tarreau239675e2021-10-19 11:59:25 +02001901/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1902 * and makes it owned by this obj_type, with the proposed callback and error
1903 * callback. On success, *req is assigned the allocated requester. Returns
1904 * NULL on allocation failure.
1905 */
1906static struct resolv_requester *
1907resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1908 int (*cb)(struct resolv_requester *, struct dns_counters *),
1909 int (*err_cb)(struct resolv_requester *, int))
1910{
1911 struct resolv_requester *tmp;
1912
1913 if (*req)
1914 return *req;
1915
1916 tmp = pool_alloc(resolv_requester_pool);
1917 if (!tmp)
1918 goto end;
1919
1920 LIST_INIT(&tmp->list);
1921 tmp->owner = owner;
1922 tmp->resolution = NULL;
1923 tmp->requester_cb = cb;
1924 tmp->requester_error_cb = err_cb;
1925 *req = tmp;
1926 end:
1927 return tmp;
1928}
1929
Emeric Brunc9437992021-02-12 19:42:55 +01001930/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001931 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001932 */
1933int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1934{
1935 struct resolv_resolution *res = NULL;
1936 struct resolv_requester *req;
1937 struct resolvers *resolvers;
1938 struct server *srv = NULL;
1939 struct resolv_srvrq *srvrq = NULL;
1940 struct stream *stream = NULL;
1941 char **hostname_dn;
1942 int hostname_dn_len, query_type;
1943
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001944 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001945 switch (requester_type) {
1946 case OBJ_TYPE_SERVER:
1947 srv = (struct server *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001948
1949 if (!requester_locked)
1950 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1951
1952 req = resolv_get_requester(&srv->resolv_requester,
1953 &srv->obj_type,
1954 snr_resolution_cb,
1955 snr_resolution_error_cb);
1956
1957 if (!requester_locked)
1958 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1959
1960 if (!req)
1961 goto err;
1962
Emeric Brunc9437992021-02-12 19:42:55 +01001963 hostname_dn = &srv->hostname_dn;
1964 hostname_dn_len = srv->hostname_dn_len;
1965 resolvers = srv->resolvers;
1966 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1967 ? DNS_RTYPE_A
1968 : DNS_RTYPE_AAAA);
1969 break;
1970
1971 case OBJ_TYPE_SRVRQ:
1972 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001973
1974 req = resolv_get_requester(&srvrq->requester,
1975 &srvrq->obj_type,
1976 snr_resolution_cb,
1977 srvrq_resolution_error_cb);
1978 if (!req)
1979 goto err;
1980
Emeric Brunc9437992021-02-12 19:42:55 +01001981 hostname_dn = &srvrq->hostname_dn;
1982 hostname_dn_len = srvrq->hostname_dn_len;
1983 resolvers = srvrq->resolvers;
1984 query_type = DNS_RTYPE_SRV;
1985 break;
1986
1987 case OBJ_TYPE_STREAM:
1988 stream = (struct stream *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001989
1990 req = resolv_get_requester(&stream->resolv_ctx.requester,
1991 &stream->obj_type,
1992 act_resolution_cb,
1993 act_resolution_error_cb);
1994 if (!req)
1995 goto err;
1996
Emeric Brunc9437992021-02-12 19:42:55 +01001997 hostname_dn = &stream->resolv_ctx.hostname_dn;
1998 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
1999 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2000 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2001 ? DNS_RTYPE_A
2002 : DNS_RTYPE_AAAA);
2003 break;
2004 default:
2005 goto err;
2006 }
2007
2008 /* Get a resolution from the resolvers' wait queue or pool */
2009 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2010 goto err;
2011
Willy Tarreau239675e2021-10-19 11:59:25 +02002012 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002013
Willy Tarreau2b718102021-04-21 07:32:39 +02002014 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002015 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002016 return 0;
2017
2018 err:
2019 if (res && LIST_ISEMPTY(&res->requesters))
2020 resolv_free_resolution(res);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002021 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002022 return -1;
2023}
2024
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002025/* This function removes all server/srvrq references on answer items. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002026void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun34067662021-06-11 10:48:45 +02002027{
Willy Tarreau7893ae12021-10-21 07:39:57 +02002028 struct eb32_node *eb32, *eb32_back;
2029 struct resolv_answer_item *item;
Emeric Brun34067662021-06-11 10:48:45 +02002030 struct server *srv, *srvback;
2031 struct resolv_srvrq *srvrq;
2032
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002033 enter_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002034 if ((srv = objt_server(req->owner)) != NULL) {
2035 LIST_DEL_INIT(&srv->ip_rec_item);
2036 }
2037 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02002038 for (eb32 = eb32_first(&res->response.answer_tree);
2039 eb32 && (eb32_back = eb32_next(eb32), 1);
2040 eb32 = eb32_back) {
2041 item = eb32_entry(eb32, typeof(*item), link);
Emeric Brun34067662021-06-11 10:48:45 +02002042 if (item->type == DNS_RTYPE_SRV) {
2043 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet11c6c392021-06-15 16:08:48 +02002044 if (srv->srvrq == srvrq)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002045 resolv_srvrq_cleanup_srv(srv);
Emeric Brun34067662021-06-11 10:48:45 +02002046 }
2047 }
2048 }
2049 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002050 leave_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002051}
2052
Emeric Brunc9437992021-02-12 19:42:55 +01002053/* Removes a requester from a DNS resolution. It takes takes care of all the
2054 * consequences. It also cleans up some parameters from the requester.
2055 */
Willy Tarreau6878f802021-10-20 14:07:31 +02002056static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002057{
2058 struct resolv_resolution *res;
2059 struct resolv_requester *req;
2060
2061 /* Nothing to do */
2062 if (!requester || !requester->resolution)
2063 return;
2064 res = requester->resolution;
2065
2066 /* Clean up the requester */
Willy Tarreauaae73202021-10-19 22:01:36 +02002067 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002068 requester->resolution = NULL;
2069
Christopher Fauletbce6db62021-10-29 10:38:15 +02002070 /* remove ref from the resolution answer item list to the requester */
2071 resolv_detach_from_resolution_answer_items(res, requester);
2072
Emeric Brunc9437992021-02-12 19:42:55 +01002073 /* We need to find another requester linked on this resolution */
2074 if (!LIST_ISEMPTY(&res->requesters))
2075 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2076 else {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002077 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002078 return;
2079 }
2080
2081 /* Move hostname_dn related pointers to the next requester */
2082 switch (obj_type(req->owner)) {
2083 case OBJ_TYPE_SERVER:
2084 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2085 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2086 break;
2087 case OBJ_TYPE_SRVRQ:
2088 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2089 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2090 break;
2091 case OBJ_TYPE_STREAM:
2092 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2093 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2094 break;
2095 default:
2096 res->hostname_dn = NULL;
2097 res->hostname_dn_len = 0;
2098 break;
2099 }
2100}
2101
Willy Tarreauf766ec62021-10-18 16:46:38 +02002102/* The public version of the function above that deals with the death row. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002103void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002104{
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002105 enter_resolver_code();
Willy Tarreau6878f802021-10-20 14:07:31 +02002106 _resolv_unlink_resolution(requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002107 leave_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002108}
2109
Emeric Brunc9437992021-02-12 19:42:55 +01002110/* Called when a network IO is generated on a name server socket for an incoming
2111 * packet. It performs the following actions:
2112 * - check if the packet requires processing (not outdated resolution)
2113 * - ensure the DNS packet received is valid and call requester's callback
2114 * - call requester's error callback if invalid response
2115 * - check the dn_name in the packet against the one sent
2116 */
2117static int resolv_process_responses(struct dns_nameserver *ns)
2118{
2119 struct dns_counters *tmpcounters;
2120 struct resolvers *resolvers;
2121 struct resolv_resolution *res;
Emeric Brunc9437992021-02-12 19:42:55 +01002122 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2123 unsigned char *bufend;
2124 int buflen, dns_resp;
2125 int max_answer_records;
2126 unsigned short query_id;
2127 struct eb32_node *eb;
2128 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002129 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002130
2131 resolvers = ns->parent;
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002132 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002133 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2134
2135 /* process all pending input messages */
2136 while (1) {
2137 /* read message received */
2138 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2139 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2140 break;
2141 }
2142
2143 /* message too big */
2144 if (buflen > resolvers->accepted_payload_size) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002145 ns->counters->app.resolver.too_big++;
Emeric Brunc9437992021-02-12 19:42:55 +01002146 continue;
2147 }
2148
2149 /* initializing variables */
2150 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2151
2152 /* read the query id from the packet (16 bits) */
2153 if (buf + 2 > bufend) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002154 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002155 continue;
2156 }
2157 query_id = resolv_response_get_query_id(buf);
2158
2159 /* search the query_id in the pending resolution tree */
2160 eb = eb32_lookup(&resolvers->query_ids, query_id);
2161 if (eb == NULL) {
2162 /* unknown query id means an outdated response and can be safely ignored */
Emeric Brund174f0e2021-10-29 17:30:41 +02002163 ns->counters->app.resolver.outdated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002164 continue;
2165 }
2166
2167 /* known query id means a resolution in progress */
2168 res = eb32_entry(eb, struct resolv_resolution, qid);
2169 /* number of responses received */
2170 res->nb_responses++;
2171
2172 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2173 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2174
2175 switch (dns_resp) {
2176 case RSLV_RESP_VALID:
2177 break;
2178
2179 case RSLV_RESP_INVALID:
2180 case RSLV_RESP_QUERY_COUNT_ERROR:
2181 case RSLV_RESP_WRONG_NAME:
2182 res->status = RSLV_STATUS_INVALID;
Emeric Brund174f0e2021-10-29 17:30:41 +02002183 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002184 break;
2185
2186 case RSLV_RESP_NX_DOMAIN:
2187 res->status = RSLV_STATUS_NX;
Emeric Brund174f0e2021-10-29 17:30:41 +02002188 ns->counters->app.resolver.nx++;
Emeric Brunc9437992021-02-12 19:42:55 +01002189 break;
2190
2191 case RSLV_RESP_REFUSED:
2192 res->status = RSLV_STATUS_REFUSED;
Emeric Brund174f0e2021-10-29 17:30:41 +02002193 ns->counters->app.resolver.refused++;
Emeric Brunc9437992021-02-12 19:42:55 +01002194 break;
2195
2196 case RSLV_RESP_ANCOUNT_ZERO:
2197 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002198 ns->counters->app.resolver.any_err++;
Emeric Brunc9437992021-02-12 19:42:55 +01002199 break;
2200
2201 case RSLV_RESP_CNAME_ERROR:
2202 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002203 ns->counters->app.resolver.cname_error++;
Emeric Brunc9437992021-02-12 19:42:55 +01002204 break;
2205
2206 case RSLV_RESP_TRUNCATED:
2207 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002208 ns->counters->app.resolver.truncated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002209 break;
2210
2211 case RSLV_RESP_NO_EXPECTED_RECORD:
2212 case RSLV_RESP_ERROR:
2213 case RSLV_RESP_INTERNAL:
2214 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002215 ns->counters->app.resolver.other++;
Emeric Brunc9437992021-02-12 19:42:55 +01002216 break;
2217 }
2218
2219 /* Wait all nameservers response to handle errors */
2220 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2221 continue;
2222
2223 /* Process error codes */
2224 if (dns_resp != RSLV_RESP_VALID) {
2225 if (res->prefered_query_type != res->query_type) {
2226 /* The fallback on the query type was already performed,
2227 * so check the try counter. If it falls to 0, we can
2228 * report an error. Else, wait the next attempt. */
2229 if (!res->try)
2230 goto report_res_error;
2231 }
2232 else {
2233 /* Fallback from A to AAAA or the opposite and re-send
2234 * the resolution immediately. try counter is not
2235 * decremented. */
2236 if (res->prefered_query_type == DNS_RTYPE_A) {
2237 res->query_type = DNS_RTYPE_AAAA;
2238 resolv_send_query(res);
2239 }
2240 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2241 res->query_type = DNS_RTYPE_A;
2242 resolv_send_query(res);
2243 }
2244 }
2245 continue;
2246 }
2247
Emeric Brunc9437992021-02-12 19:42:55 +01002248 /* So the resolution succeeded */
2249 res->status = RSLV_STATUS_VALID;
2250 res->last_valid = now_ms;
Emeric Brund174f0e2021-10-29 17:30:41 +02002251 ns->counters->app.resolver.valid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002252 goto report_res_success;
2253
2254 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002255 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002256 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002257 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2258 if (!keep_answer_items)
2259 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002260 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002261 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002262 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002263 continue;
2264
2265 report_res_success:
2266 /* Only the 1rst requester s managed by the server, others are
2267 * from the cache */
2268 tmpcounters = ns->counters;
2269 list_for_each_entry(req, &res->requesters, list) {
2270 struct server *s = objt_server(req->owner);
2271
2272 if (s)
2273 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2274 req->requester_cb(req, tmpcounters);
2275 if (s)
2276 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2277 tmpcounters = NULL;
2278 }
2279
2280 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002281 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002282 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002283 continue;
2284 }
2285 resolv_update_resolvers_timeout(resolvers);
2286 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002287 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002288 return buflen;
2289}
2290
2291/* Processes DNS resolution. First, it checks the active list to detect expired
2292 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2293 * checks the wait list to trigger new resolutions.
2294 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002295static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002296{
2297 struct resolvers *resolvers = context;
2298 struct resolv_resolution *res, *resback;
2299 int exp;
2300
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002301 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002302 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2303
Willy Tarreauf766ec62021-10-18 16:46:38 +02002304 /* Handle all expired resolutions from the active list. Elements that
2305 * need to be removed will in fact be moved to the death_row. Other
2306 * ones will be handled normally.
2307 */
2308
Willy Tarreauf766ec62021-10-18 16:46:38 +02002309 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2310 while (&res->list != &resolvers->resolutions.curr) {
2311 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2312
Christopher Faulet0efc0992021-03-11 18:09:53 +01002313 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002314 abort_resolution(res);
2315 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002316 continue;
2317 }
2318
Emeric Brunc9437992021-02-12 19:42:55 +01002319 /* When we find the first resolution in the future, then we can
2320 * stop here */
2321 exp = tick_add(res->last_query, resolvers->timeout.retry);
2322 if (!tick_is_expired(exp, now_ms))
2323 break;
2324
2325 /* If current resolution has been tried too many times and
2326 * finishes in timeout we update its status and remove it from
2327 * the list */
2328 if (!res->try) {
2329 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002330 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002331
2332 /* Notify the result to the requesters */
2333 if (!res->nb_responses)
2334 res->status = RSLV_STATUS_TIMEOUT;
2335 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002336 keep_answer_items |= req->requester_error_cb(req, res->status);
2337 if (!keep_answer_items)
2338 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002339
2340 /* Clean up resolution info and remove it from the
2341 * current list */
2342 resolv_reset_resolution(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002343
2344 /* subsequent entries might have been deleted here */
2345 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreauaae73202021-10-19 22:01:36 +02002346 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002347 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002348 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002349 }
2350 else {
2351 /* Otherwise resend the DNS query and requeue the resolution */
2352 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2353 /* No response received (a real timeout) or fallback already done */
2354 res->query_type = res->prefered_query_type;
2355 res->try--;
2356 }
2357 else {
2358 /* Fallback from A to AAAA or the opposite and re-send
2359 * the resolution immediately. try counter is not
2360 * decremented. */
2361 if (res->prefered_query_type == DNS_RTYPE_A)
2362 res->query_type = DNS_RTYPE_AAAA;
2363 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2364 res->query_type = DNS_RTYPE_A;
2365 else
2366 res->try--;
2367 }
2368 resolv_send_query(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002369 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2370 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002371 }
2372 }
2373
2374 /* Handle all resolutions in the wait list */
2375 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002376 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002377 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002378 continue;
2379 }
2380
Emeric Brunc9437992021-02-12 19:42:55 +01002381 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2382 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2383 continue;
2384
2385 if (resolv_run_resolution(res) != 1) {
2386 res->last_resolution = now_ms;
Willy Tarreauaae73202021-10-19 22:01:36 +02002387 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002388 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002389 }
2390 }
Emeric Brunc9437992021-02-12 19:42:55 +01002391 resolv_update_resolvers_timeout(resolvers);
2392 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002393
2394 /* now we can purge all queued deletions */
2395 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002396 return t;
2397}
2398
2399/* Release memory allocated by DNS */
2400static void resolvers_deinit(void)
2401{
2402 struct resolvers *resolvers, *resolversback;
2403 struct dns_nameserver *ns, *nsback;
2404 struct resolv_resolution *res, *resback;
2405 struct resolv_requester *req, *reqback;
2406 struct resolv_srvrq *srvrq, *srvrqback;
2407
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002408 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002409 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2410 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2411 free(ns->id);
2412 free((char *)ns->conf.file);
2413 if (ns->dgram) {
2414 if (ns->dgram->conn.t.sock.fd != -1) {
2415 fd_delete(ns->dgram->conn.t.sock.fd);
2416 close(ns->dgram->conn.t.sock.fd);
2417 }
2418 if (ns->dgram->ring_req)
2419 ring_free(ns->dgram->ring_req);
2420 free(ns->dgram);
2421 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002422 if (ns->stream) {
2423 if (ns->stream->ring_req)
2424 ring_free(ns->stream->ring_req);
2425 if (ns->stream->task_req)
2426 task_destroy(ns->stream->task_req);
2427 if (ns->stream->task_rsp)
2428 task_destroy(ns->stream->task_rsp);
2429 free(ns->stream);
2430 }
Willy Tarreauaae73202021-10-19 22:01:36 +02002431 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002432 EXTRA_COUNTERS_FREE(ns->extra_counters);
2433 free(ns);
2434 }
2435
2436 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2437 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002438 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002439 pool_free(resolv_requester_pool, req);
2440 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002441 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002442 }
2443
2444 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2445 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002446 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002447 pool_free(resolv_requester_pool, req);
2448 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002449 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002450 }
2451
2452 free(resolvers->id);
2453 free((char *)resolvers->conf.file);
2454 task_destroy(resolvers->t);
Willy Tarreauaae73202021-10-19 22:01:36 +02002455 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002456 free(resolvers);
2457 }
2458
2459 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2460 free(srvrq->name);
2461 free(srvrq->hostname_dn);
Willy Tarreauaae73202021-10-19 22:01:36 +02002462 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002463 free(srvrq);
2464 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002465
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002466 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002467}
2468
2469/* Finalizes the DNS configuration by allocating required resources and checking
2470 * live parameters.
2471 * Returns 0 on success, ERR_* flags otherwise.
2472 */
2473static int resolvers_finalize_config(void)
2474{
2475 struct resolvers *resolvers;
2476 struct proxy *px;
2477 int err_code = 0;
2478
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002479 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002480
Emeric Brunc9437992021-02-12 19:42:55 +01002481 /* allocate pool of resolution per resolvers */
2482 list_for_each_entry(resolvers, &sec_resolvers, list) {
2483 struct dns_nameserver *ns;
2484 struct task *t;
2485
2486 /* Check if we can create the socket with nameservers info */
2487 list_for_each_entry(ns, &resolvers->nameservers, list) {
2488 int fd;
2489
2490 if (ns->dgram) {
2491 /* Check nameserver info */
2492 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002493 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002494 resolvers->id, ns->id);
2495 err_code |= (ERR_ALERT|ERR_ABORT);
2496 continue;
2497 }
2498 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 +02002499 ha_alert("resolvers '%s': can't connect socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002500 resolvers->id, ns->id);
2501 close(fd);
2502 err_code |= (ERR_ALERT|ERR_ABORT);
2503 continue;
2504 }
2505 close(fd);
2506 }
2507 }
2508
2509 /* Create the task associated to the resolvers section */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002510 if ((t = task_new_anywhere()) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002511 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002512 err_code |= (ERR_ALERT|ERR_ABORT);
2513 goto err;
2514 }
2515
2516 /* Update task's parameters */
2517 t->process = process_resolvers;
2518 t->context = resolvers;
2519 resolvers->t = t;
2520 task_wakeup(t, TASK_WOKEN_INIT);
2521 }
2522
2523 for (px = proxies_list; px; px = px->next) {
2524 struct server *srv;
2525
2526 for (srv = px->srv; srv; srv = srv->next) {
2527 struct resolvers *resolvers;
2528
2529 if (!srv->resolvers_id)
2530 continue;
2531
2532 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002533 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002534 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2535 err_code |= (ERR_ALERT|ERR_ABORT);
2536 continue;
2537 }
2538 srv->resolvers = resolvers;
Christopher Fauletdcac4182021-06-15 16:17:17 +02002539 srv->srvrq_check = NULL;
2540 if (srv->srvrq) {
2541 if (!srv->srvrq->resolvers) {
2542 srv->srvrq->resolvers = srv->resolvers;
2543 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2544 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
2545 proxy_type_str(px), px->id, srv->id);
2546 err_code |= (ERR_ALERT|ERR_ABORT);
2547 continue;
2548 }
2549 }
Emeric Brunc9437992021-02-12 19:42:55 +01002550
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002551 srv->srvrq_check = task_new_anywhere();
Christopher Fauletdcac4182021-06-15 16:17:17 +02002552 if (!srv->srvrq_check) {
2553 ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002554 proxy_type_str(px), px->id, srv->id);
2555 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Fauletdcac4182021-06-15 16:17:17 +02002556 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002557 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002558 srv->srvrq_check->process = resolv_srvrq_expire_task;
2559 srv->srvrq_check->context = srv;
2560 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002561 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002562 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002563 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002564 proxy_type_str(px), px->id, srv->id);
2565 err_code |= (ERR_ALERT|ERR_ABORT);
2566 continue;
2567 }
Amaury Denoyelledd565202021-08-26 15:35:59 +02002568
2569 srv->flags |= SRV_F_NON_PURGEABLE;
Emeric Brunc9437992021-02-12 19:42:55 +01002570 }
2571 }
2572
2573 if (err_code & (ERR_ALERT|ERR_ABORT))
2574 goto err;
2575
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002576 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002577 return err_code;
2578 err:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002579 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002580 resolvers_deinit();
2581 return err_code;
2582
2583}
2584
Christopher Faulet908628c2022-03-25 16:43:49 +01002585static int stats_dump_resolv_to_buffer(struct conn_stream *cs,
Emeric Brunc9437992021-02-12 19:42:55 +01002586 struct dns_nameserver *ns,
2587 struct field *stats, size_t stats_count,
2588 struct list *stat_modules)
2589{
Christopher Faulet908628c2022-03-25 16:43:49 +01002590 struct appctx *appctx = __cs_appctx(cs);
2591 struct channel *rep = cs_ic(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002592 struct stats_module *mod;
2593 size_t idx = 0;
2594
2595 memset(stats, 0, sizeof(struct field) * stats_count);
2596
2597 list_for_each_entry(mod, stat_modules, list) {
2598 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2599
2600 mod->fill_stats(counters, stats + idx);
2601 idx += mod->stats_count;
2602 }
2603
2604 if (!stats_dump_one_line(stats, idx, appctx))
2605 return 0;
2606
2607 if (!stats_putchk(rep, NULL, &trash))
2608 goto full;
2609
2610 return 1;
2611
2612 full:
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002613 cs_rx_room_rdy(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002614 return 0;
2615}
2616
2617/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2618 * as a pointer to the current nameserver.
2619 */
Christopher Faulet908628c2022-03-25 16:43:49 +01002620int stats_dump_resolvers(struct conn_stream *cs,
Emeric Brunc9437992021-02-12 19:42:55 +01002621 struct field *stats, size_t stats_count,
2622 struct list *stat_modules)
2623{
Christopher Faulet908628c2022-03-25 16:43:49 +01002624 struct appctx *appctx = __cs_appctx(cs);
2625 struct channel *rep = cs_ic(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002626 struct resolvers *resolver = appctx->ctx.stats.obj1;
2627 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2628
2629 if (!resolver)
2630 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2631
2632 /* dump resolvers */
2633 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2634 appctx->ctx.stats.obj1 = resolver;
2635
2636 ns = appctx->ctx.stats.obj2 ?
2637 appctx->ctx.stats.obj2 :
2638 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2639
2640 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2641 appctx->ctx.stats.obj2 = ns;
2642
2643 if (buffer_almost_full(&rep->buf))
2644 goto full;
2645
Christopher Faulet908628c2022-03-25 16:43:49 +01002646 if (!stats_dump_resolv_to_buffer(cs, ns,
Emeric Brunc9437992021-02-12 19:42:55 +01002647 stats, stats_count,
2648 stat_modules)) {
2649 return 0;
2650 }
2651 }
2652
2653 appctx->ctx.stats.obj2 = NULL;
2654 }
2655
2656 return 1;
2657
2658 full:
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002659 cs_rx_room_blk(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002660 return 0;
2661}
2662
2663void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2664{
2665 struct resolvers *resolvers;
2666 struct dns_nameserver *ns;
2667 struct stats_module *mod;
2668 void *counters;
2669
2670 list_for_each_entry(mod, stat_modules, list) {
2671 if (!mod->clearable && !clrall)
2672 continue;
2673
2674 list_for_each_entry(resolvers, &sec_resolvers, list) {
2675 list_for_each_entry(ns, &resolvers->nameservers, list) {
2676 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2677 memcpy(counters, mod->counters, mod->counters_size);
2678 }
2679 }
2680 }
2681
2682}
2683
2684int resolv_allocate_counters(struct list *stat_modules)
2685{
2686 struct stats_module *mod;
2687 struct resolvers *resolvers;
2688 struct dns_nameserver *ns;
2689
2690 list_for_each_entry(resolvers, &sec_resolvers, list) {
2691 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunf8642ee2021-10-29 17:59:18 +02002692 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
Emeric Brunc9437992021-02-12 19:42:55 +01002693 alloc_failed);
2694
2695 list_for_each_entry(mod, stat_modules, list) {
2696 EXTRA_COUNTERS_ADD(mod,
2697 ns->extra_counters,
2698 mod->counters,
2699 mod->counters_size);
2700 }
2701
2702 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2703
2704 list_for_each_entry(mod, stat_modules, list) {
2705 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2706 mod->counters, mod->counters_size);
2707
2708 /* Store the ns counters pointer */
Emeric Brunf8642ee2021-10-29 17:59:18 +02002709 if (strcmp(mod->name, "resolvers") == 0) {
2710 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
Emeric Brunc9437992021-02-12 19:42:55 +01002711 ns->counters->id = ns->id;
2712 ns->counters->pid = resolvers->id;
2713 }
2714 }
2715 }
2716 }
2717
2718 return 1;
2719
2720alloc_failed:
2721 return 0;
2722}
2723
2724/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2725static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2726{
2727 struct resolvers *presolvers;
2728
2729 if (*args[2]) {
2730 list_for_each_entry(presolvers, &sec_resolvers, list) {
2731 if (strcmp(presolvers->id, args[2]) == 0) {
2732 appctx->ctx.cli.p0 = presolvers;
2733 break;
2734 }
2735 }
2736 if (appctx->ctx.cli.p0 == NULL)
2737 return cli_err(appctx, "Can't find that resolvers section\n");
2738 }
2739 return 0;
2740}
2741
2742/* Dumps counters from all resolvers section and associated name servers. It
2743 * returns 0 if the output buffer is full and it needs to be called again,
2744 * otherwise non-zero. It may limit itself to the resolver pointed to by
2745 * <cli.p0> if it's not null.
2746 */
2747static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2748{
Christopher Faulet908628c2022-03-25 16:43:49 +01002749 struct conn_stream *cs = appctx->owner;
Emeric Brunc9437992021-02-12 19:42:55 +01002750 struct resolvers *resolvers;
2751 struct dns_nameserver *ns;
2752
2753 chunk_reset(&trash);
2754
2755 switch (appctx->st2) {
2756 case STAT_ST_INIT:
2757 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2758 /* fall through */
2759
2760 case STAT_ST_LIST:
2761 if (LIST_ISEMPTY(&sec_resolvers)) {
2762 chunk_appendf(&trash, "No resolvers found\n");
2763 }
2764 else {
2765 list_for_each_entry(resolvers, &sec_resolvers, list) {
2766 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2767 continue;
2768
2769 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2770 list_for_each_entry(ns, &resolvers->nameservers, list) {
2771 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2772 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2773 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
Emeric Brund174f0e2021-10-29 17:30:41 +02002774 chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
2775 chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
2776 chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
2777 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
2778 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
2779 chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
2780 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
2781 chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
2782 chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
2783 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
2784 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
2785 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
2786 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +01002787 }
2788 chunk_appendf(&trash, "\n");
2789 }
2790 }
2791
2792 /* display response */
Christopher Faulet908628c2022-03-25 16:43:49 +01002793 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +01002794 /* let's try again later from this session. We add ourselves into
2795 * this session's users so that it can remove us upon termination.
2796 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002797 cs_rx_room_blk(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002798 return 0;
2799 }
2800 /* fall through */
2801
2802 default:
2803 appctx->st2 = STAT_ST_FIN;
2804 return 1;
2805 }
2806}
2807
2808/* register cli keywords */
2809static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002810 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002811 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2812 {{},}
2813 }
2814};
2815
2816INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2817
2818/*
2819 * Prepare <rule> for hostname resolution.
2820 * Returns -1 in case of any allocation failure, 0 if not.
2821 * On error, a global failure counter is also incremented.
2822 */
Willy Tarreau947ae122021-10-14 08:11:48 +02002823static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002824{
2825 char *hostname_dn;
Willy Tarreau947ae122021-10-14 08:11:48 +02002826 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002827 struct buffer *tmp = get_trash_chunk();
2828
2829 if (!hostname)
2830 return 0;
2831
Emeric Brunc9437992021-02-12 19:42:55 +01002832 hostname_dn = tmp->area;
Willy Tarreaubf9498a2021-10-14 07:49:49 +02002833 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002834 hostname_dn, tmp->size);
2835 if (hostname_dn_len == -1)
2836 goto err;
2837
2838
2839 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2840 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2841 if (!stream->resolv_ctx.hostname_dn)
2842 goto err;
2843
2844 return 0;
2845
2846 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002847 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002848 resolv_failed_resolutions += 1;
2849 return -1;
2850}
2851
2852
2853/*
2854 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2855 */
2856enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2857 struct session *sess, struct stream *s, int flags)
2858{
2859 struct resolv_resolution *resolution;
2860 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002861 struct resolv_requester *req;
2862 struct resolvers *resolvers;
2863 struct resolv_resolution *res;
2864 int exp, locked = 0;
2865 enum act_return ret = ACT_RET_CONT;
2866
2867 resolvers = rule->arg.resolv.resolvers;
2868
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002869 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002870
Emeric Brunc9437992021-02-12 19:42:55 +01002871 /* we have a response to our DNS resolution */
2872 use_cache:
2873 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2874 resolution = s->resolv_ctx.requester->resolution;
2875 if (!locked) {
2876 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2877 locked = 1;
2878 }
2879
2880 if (resolution->step == RSLV_STEP_RUNNING)
2881 goto yield;
2882 if (resolution->step == RSLV_STEP_NONE) {
2883 /* We update the variable only if we have a valid response. */
2884 if (resolution->status == RSLV_STATUS_VALID) {
2885 struct sample smp;
2886 short ip_sin_family = 0;
2887 void *ip = NULL;
2888
2889 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2890 0, &ip, &ip_sin_family, NULL);
2891
2892 switch (ip_sin_family) {
2893 case AF_INET:
2894 smp.data.type = SMP_T_IPV4;
2895 memcpy(&smp.data.u.ipv4, ip, 4);
2896 break;
2897 case AF_INET6:
2898 smp.data.type = SMP_T_IPV6;
2899 memcpy(&smp.data.u.ipv6, ip, 16);
2900 break;
2901 default:
2902 ip = NULL;
2903 }
2904
2905 if (ip) {
2906 smp.px = px;
2907 smp.sess = sess;
2908 smp.strm = s;
2909
2910 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2911 }
2912 }
2913 }
2914
2915 goto release_requester;
2916 }
2917
2918 /* need to configure and start a new DNS resolution */
2919 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2920 if (smp == NULL)
2921 goto end;
2922
Willy Tarreau947ae122021-10-14 08:11:48 +02002923 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002924 goto end; /* on error, ignore the action */
2925
2926 s->resolv_ctx.parent = rule;
2927
2928 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2929 locked = 1;
2930
2931 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2932
2933 /* Check if there is a fresh enough response in the cache of our associated resolution */
2934 req = s->resolv_ctx.requester;
2935 if (!req || !req->resolution)
2936 goto release_requester; /* on error, ignore the action */
2937 res = req->resolution;
2938
2939 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2940 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2941 && !tick_is_expired(exp, now_ms)) {
2942 goto use_cache;
2943 }
2944
2945 resolv_trigger_resolution(s->resolv_ctx.requester);
2946
2947 yield:
2948 if (flags & ACT_OPT_FINAL)
2949 goto release_requester;
2950 ret = ACT_RET_YIELD;
2951
2952 end:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002953 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002954 if (locked)
2955 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2956 return ret;
2957
2958 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002959 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002960 s->resolv_ctx.hostname_dn_len = 0;
2961 if (s->resolv_ctx.requester) {
Willy Tarreau6878f802021-10-20 14:07:31 +02002962 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01002963 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2964 s->resolv_ctx.requester = NULL;
2965 }
2966 goto end;
2967}
2968
2969static void release_resolv_action(struct act_rule *rule)
2970{
2971 release_sample_expr(rule->arg.resolv.expr);
2972 free(rule->arg.resolv.varname);
2973 free(rule->arg.resolv.resolvers_id);
2974 free(rule->arg.resolv.opts);
2975}
2976
2977
2978/* parse "do-resolve" action
2979 * This action takes the following arguments:
2980 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
2981 *
2982 * - <varName> is the variable name where the result of the DNS resolution will be stored
2983 * (mandatory)
2984 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
2985 * (mandatory)
2986 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
2987 * (optional), defaults to ipv6
2988 * - <expr> is an HAProxy expression used to fetch the name to be resolved
2989 */
2990enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
2991{
2992 int cur_arg;
2993 struct sample_expr *expr;
2994 unsigned int where;
2995 const char *beg, *end;
2996
2997 /* orig_arg points to the first argument, but we need to analyse the command itself first */
2998 cur_arg = *orig_arg - 1;
2999
3000 /* locate varName, which is mandatory */
3001 beg = strchr(args[cur_arg], '(');
3002 if (beg == NULL)
3003 goto do_resolve_parse_error;
3004 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3005 end = strchr(beg, ',');
3006 if (end == NULL)
3007 goto do_resolve_parse_error;
3008 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3009 if (rule->arg.resolv.varname == NULL)
3010 goto do_resolve_parse_error;
3011
3012
3013 /* locate resolversSectionName, which is mandatory.
3014 * Since next parameters are optional, the delimiter may be comma ','
3015 * or closing parenthesis ')'
3016 */
3017 beg = end + 1;
3018 end = strchr(beg, ',');
3019 if (end == NULL)
3020 end = strchr(beg, ')');
3021 if (end == NULL)
3022 goto do_resolve_parse_error;
3023 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3024 if (rule->arg.resolv.resolvers_id == NULL)
3025 goto do_resolve_parse_error;
3026
3027
3028 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3029 if (rule->arg.resolv.opts == NULL)
3030 goto do_resolve_parse_error;
3031
3032 /* Default priority is ipv6 */
3033 rule->arg.resolv.opts->family_prio = AF_INET6;
3034
3035 /* optional arguments accepted for now:
3036 * ipv4 or ipv6
3037 */
3038 while (*end != ')') {
3039 beg = end + 1;
3040 end = strchr(beg, ',');
3041 if (end == NULL)
3042 end = strchr(beg, ')');
3043 if (end == NULL)
3044 goto do_resolve_parse_error;
3045
3046 if (strncmp(beg, "ipv4", end - beg) == 0) {
3047 rule->arg.resolv.opts->family_prio = AF_INET;
3048 }
3049 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3050 rule->arg.resolv.opts->family_prio = AF_INET6;
3051 }
3052 else {
3053 goto do_resolve_parse_error;
3054 }
3055 }
3056
3057 cur_arg = cur_arg + 1;
3058
3059 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3060 if (!expr)
3061 goto do_resolve_parse_error;
3062
3063
3064 where = 0;
3065 if (px->cap & PR_CAP_FE)
3066 where |= SMP_VAL_FE_HRQ_HDR;
3067 if (px->cap & PR_CAP_BE)
3068 where |= SMP_VAL_BE_HRQ_HDR;
3069
3070 if (!(expr->fetch->val & where)) {
3071 memprintf(err,
3072 "fetch method '%s' extracts information from '%s', none of which is available here",
3073 args[cur_arg-1], sample_src_names(expr->fetch->use));
3074 free(expr);
3075 return ACT_RET_PRS_ERR;
3076 }
3077 rule->arg.resolv.expr = expr;
3078 rule->action = ACT_CUSTOM;
3079 rule->action_ptr = resolv_action_do_resolve;
3080 *orig_arg = cur_arg;
3081
3082 rule->check_ptr = check_action_do_resolve;
3083 rule->release_ptr = release_resolv_action;
3084
3085 return ACT_RET_PRS_OK;
3086
3087 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003088 ha_free(&rule->arg.resolv.varname);
3089 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003090 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3091 args[cur_arg]);
3092 return ACT_RET_PRS_ERR;
3093}
3094
3095static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003096 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003097 { /* END */ }
3098}};
3099
3100INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3101
3102static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003103 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003104 { /* END */ }
3105}};
3106
3107INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3108
3109/* Check an "http-request do-resolve" action.
3110 *
3111 * The function returns 1 in success case, otherwise, it returns 0 and err is
3112 * filled.
3113 */
3114int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3115{
3116 struct resolvers *resolvers = NULL;
3117
3118 if (rule->arg.resolv.resolvers_id == NULL) {
3119 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3120 return 0;
3121 }
3122
3123 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3124 if (resolvers == NULL) {
3125 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3126 return 0;
3127 }
3128 rule->arg.resolv.resolvers = resolvers;
3129
3130 return 1;
3131}
3132
3133void resolvers_setup_proxy(struct proxy *px)
3134{
3135 px->last_change = now.tv_sec;
3136 px->cap = PR_CAP_FE | PR_CAP_BE;
3137 px->maxconn = 0;
3138 px->conn_retries = 1;
3139 px->timeout.server = TICK_ETERNITY;
3140 px->timeout.client = TICK_ETERNITY;
3141 px->timeout.connect = TICK_ETERNITY;
3142 px->accept = NULL;
3143 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
Emeric Brunc9437992021-02-12 19:42:55 +01003144}
3145
3146/*
3147 * Parse a <resolvers> section.
3148 * Returns the error code, 0 if OK, or any combination of :
3149 * - ERR_ABORT: must abort ASAP
3150 * - ERR_FATAL: we can continue parsing but not start the service
3151 * - ERR_WARN: a warning has been emitted
3152 * - ERR_ALERT: an alert has been emitted
3153 * Only the two first ones can stop processing, the two others are just
3154 * indicators.
3155 */
3156int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3157{
3158 const char *err;
3159 int err_code = 0;
3160 char *errmsg = NULL;
3161 struct proxy *p;
3162
3163 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3164 if (!*args[1]) {
3165 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3166 err_code |= ERR_ALERT | ERR_ABORT;
3167 goto out;
3168 }
3169
3170 err = invalid_char(args[1]);
3171 if (err) {
3172 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3173 file, linenum, *err, args[0], args[1]);
3174 err_code |= ERR_ALERT | ERR_ABORT;
3175 goto out;
3176 }
3177
3178 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3179 /* Error if two resolvers owns the same name */
3180 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3181 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3182 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3183 err_code |= ERR_ALERT | ERR_ABORT;
3184 }
3185 }
3186
3187 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3188 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3189 err_code |= ERR_ALERT | ERR_ABORT;
3190 goto out;
3191 }
3192
3193 /* allocate new proxy to tcp servers */
3194 p = calloc(1, sizeof *p);
3195 if (!p) {
3196 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3197 err_code |= ERR_ALERT | ERR_FATAL;
3198 goto out;
3199 }
3200
3201 init_new_proxy(p);
3202 resolvers_setup_proxy(p);
3203 p->parent = curr_resolvers;
3204 p->id = strdup(args[1]);
3205 p->conf.args.file = p->conf.file = strdup(file);
3206 p->conf.args.line = p->conf.line = linenum;
3207 curr_resolvers->px = p;
3208
3209 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003210 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003211 curr_resolvers->conf.file = strdup(file);
3212 curr_resolvers->conf.line = linenum;
3213 curr_resolvers->id = strdup(args[1]);
3214 curr_resolvers->query_ids = EB_ROOT;
3215 /* default maximum response size */
3216 curr_resolvers->accepted_payload_size = 512;
3217 /* default hold period for nx, other, refuse and timeout is 30s */
3218 curr_resolvers->hold.nx = 30000;
3219 curr_resolvers->hold.other = 30000;
3220 curr_resolvers->hold.refused = 30000;
3221 curr_resolvers->hold.timeout = 30000;
3222 curr_resolvers->hold.obsolete = 0;
3223 /* default hold period for valid is 10s */
3224 curr_resolvers->hold.valid = 10000;
3225 curr_resolvers->timeout.resolve = 1000;
3226 curr_resolvers->timeout.retry = 1000;
3227 curr_resolvers->resolve_retries = 3;
3228 LIST_INIT(&curr_resolvers->nameservers);
3229 LIST_INIT(&curr_resolvers->resolutions.curr);
3230 LIST_INIT(&curr_resolvers->resolutions.wait);
3231 HA_SPIN_INIT(&curr_resolvers->lock);
3232 }
3233 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3234 struct dns_nameserver *newnameserver = NULL;
3235 struct sockaddr_storage *sk;
3236 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003237 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003238
3239 if (!*args[2]) {
3240 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3241 file, linenum, args[0]);
3242 err_code |= ERR_ALERT | ERR_FATAL;
3243 goto out;
3244 }
3245
3246 err = invalid_char(args[1]);
3247 if (err) {
3248 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3249 file, linenum, *err, args[1]);
3250 err_code |= ERR_ALERT | ERR_FATAL;
3251 goto out;
3252 }
3253
3254 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3255 /* Error if two resolvers owns the same name */
3256 if (strcmp(newnameserver->id, args[1]) == 0) {
3257 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3258 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3259 err_code |= ERR_ALERT | ERR_FATAL;
3260 }
3261 }
3262
Emeric Brunc8f3e452021-04-07 16:04:54 +02003263 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3264 &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 +01003265 if (!sk) {
3266 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3267 err_code |= ERR_ALERT | ERR_FATAL;
3268 goto out;
3269 }
3270
3271 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3272 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3273 err_code |= ERR_ALERT | ERR_ABORT;
3274 goto out;
3275 }
3276
Emeric Brunc8f3e452021-04-07 16:04:54 +02003277 if (proto && proto->ctrl_type == SOCK_STREAM) {
3278 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3279 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3280 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3281 err_code |= ERR_ABORT;
3282 goto out;
3283 }
3284
3285 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3286 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3287 err_code |= ERR_ALERT|ERR_ABORT;
3288 goto out;
3289 }
3290 }
3291 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003292 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3293 err_code |= ERR_ALERT | ERR_ABORT;
3294 goto out;
3295 }
3296
3297 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3298 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3299 err_code |= ERR_ALERT | ERR_ABORT;
3300 goto out;
3301 }
3302
3303 if ((newnameserver->id = strdup(args[1])) == NULL) {
3304 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3305 err_code |= ERR_ALERT | ERR_ABORT;
3306 goto out;
3307 }
3308
3309 newnameserver->parent = curr_resolvers;
3310 newnameserver->process_responses = resolv_process_responses;
3311 newnameserver->conf.line = linenum;
3312 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003313 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003314 }
3315 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3316 struct dns_nameserver *newnameserver = NULL;
3317 const char *whitespace = "\r\n\t ";
3318 char *resolv_line = NULL;
3319 int resolv_linenum = 0;
3320 FILE *f = NULL;
3321 char *address = NULL;
3322 struct sockaddr_storage *sk = NULL;
3323 struct protocol *proto;
3324 int duplicate_name = 0;
3325
3326 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3327 ha_alert("parsing [%s:%d] : out of memory.\n",
3328 file, linenum);
3329 err_code |= ERR_ALERT | ERR_FATAL;
3330 goto resolv_out;
3331 }
3332
3333 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3334 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3335 file, linenum);
3336 err_code |= ERR_ALERT | ERR_FATAL;
3337 goto resolv_out;
3338 }
3339
3340 sk = calloc(1, sizeof(*sk));
3341 if (sk == NULL) {
3342 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3343 resolv_linenum);
3344 err_code |= ERR_ALERT | ERR_FATAL;
3345 goto resolv_out;
3346 }
3347
3348 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3349 resolv_linenum++;
3350 if (strncmp(resolv_line, "nameserver", 10) != 0)
3351 continue;
3352
3353 address = strtok(resolv_line + 10, whitespace);
3354 if (address == resolv_line + 10)
3355 continue;
3356
3357 if (address == NULL) {
3358 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3359 resolv_linenum);
3360 err_code |= ERR_WARN;
3361 continue;
3362 }
3363
3364 duplicate_name = 0;
3365 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3366 if (strcmp(newnameserver->id, address) == 0) {
3367 ha_warning("Parsing [/etc/resolv.conf:%d] : generated name for /etc/resolv.conf nameserver '%s' conflicts with another nameserver (declared at %s:%d), it appears to be a duplicate and will be excluded.\n",
3368 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3369 err_code |= ERR_WARN;
3370 duplicate_name = 1;
3371 }
3372 }
3373
3374 if (duplicate_name)
3375 continue;
3376
3377 memset(sk, 0, sizeof(*sk));
3378 if (!str2ip2(address, sk, 1)) {
3379 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3380 resolv_linenum, address);
3381 err_code |= ERR_WARN;
3382 continue;
3383 }
3384
3385 set_host_port(sk, 53);
3386
Willy Tarreau14e7f292021-10-27 17:41:07 +02003387 proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01003388 if (!proto || !proto->connect) {
3389 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3390 resolv_linenum, address);
3391 err_code |= ERR_WARN;
3392 continue;
3393 }
3394
3395 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3396 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3397 err_code |= ERR_ALERT | ERR_FATAL;
3398 goto resolv_out;
3399 }
3400
3401 if (dns_dgram_init(newnameserver, sk) < 0) {
3402 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3403 err_code |= ERR_ALERT | ERR_FATAL;
3404 free(newnameserver);
3405 goto resolv_out;
3406 }
3407
3408 newnameserver->conf.file = strdup("/etc/resolv.conf");
3409 if (newnameserver->conf.file == NULL) {
3410 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3411 err_code |= ERR_ALERT | ERR_FATAL;
3412 free(newnameserver);
3413 goto resolv_out;
3414 }
3415
3416 newnameserver->id = strdup(address);
3417 if (newnameserver->id == NULL) {
3418 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3419 err_code |= ERR_ALERT | ERR_FATAL;
3420 free((char *)newnameserver->conf.file);
3421 free(newnameserver);
3422 goto resolv_out;
3423 }
3424
3425 newnameserver->parent = curr_resolvers;
3426 newnameserver->process_responses = resolv_process_responses;
3427 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003428 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003429 }
3430
3431resolv_out:
3432 free(sk);
3433 free(resolv_line);
3434 if (f != NULL)
3435 fclose(f);
3436 }
3437 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3438 const char *res;
3439 unsigned int time;
3440
3441 if (!*args[2]) {
3442 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3443 file, linenum, args[0]);
3444 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3445 err_code |= ERR_ALERT | ERR_FATAL;
3446 goto out;
3447 }
3448 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3449 if (res == PARSE_TIME_OVER) {
3450 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3451 file, linenum, args[1], args[0]);
3452 err_code |= ERR_ALERT | ERR_FATAL;
3453 goto out;
3454 }
3455 else if (res == PARSE_TIME_UNDER) {
3456 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3457 file, linenum, args[1], args[0]);
3458 err_code |= ERR_ALERT | ERR_FATAL;
3459 goto out;
3460 }
3461 else if (res) {
3462 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3463 file, linenum, *res, args[0]);
3464 err_code |= ERR_ALERT | ERR_FATAL;
3465 goto out;
3466 }
3467 if (strcmp(args[1], "nx") == 0)
3468 curr_resolvers->hold.nx = time;
3469 else if (strcmp(args[1], "other") == 0)
3470 curr_resolvers->hold.other = time;
3471 else if (strcmp(args[1], "refused") == 0)
3472 curr_resolvers->hold.refused = time;
3473 else if (strcmp(args[1], "timeout") == 0)
3474 curr_resolvers->hold.timeout = time;
3475 else if (strcmp(args[1], "valid") == 0)
3476 curr_resolvers->hold.valid = time;
3477 else if (strcmp(args[1], "obsolete") == 0)
3478 curr_resolvers->hold.obsolete = time;
3479 else {
3480 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3481 file, linenum, args[0], args[1]);
3482 err_code |= ERR_ALERT | ERR_FATAL;
3483 goto out;
3484 }
3485
3486 }
3487 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3488 int i = 0;
3489
3490 if (!*args[1]) {
3491 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3492 file, linenum, args[0]);
3493 err_code |= ERR_ALERT | ERR_FATAL;
3494 goto out;
3495 }
3496
3497 i = atoi(args[1]);
3498 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3499 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3500 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3501 err_code |= ERR_ALERT | ERR_FATAL;
3502 goto out;
3503 }
3504
3505 curr_resolvers->accepted_payload_size = i;
3506 }
3507 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3508 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3509 file, linenum, args[0]);
3510 err_code |= ERR_ALERT | ERR_FATAL;
3511 goto out;
3512 }
3513 else if (strcmp(args[0], "resolve_retries") == 0) {
3514 if (!*args[1]) {
3515 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3516 file, linenum, args[0]);
3517 err_code |= ERR_ALERT | ERR_FATAL;
3518 goto out;
3519 }
3520 curr_resolvers->resolve_retries = atoi(args[1]);
3521 }
3522 else if (strcmp(args[0], "timeout") == 0) {
3523 if (!*args[1]) {
3524 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3525 file, linenum, args[0]);
3526 err_code |= ERR_ALERT | ERR_FATAL;
3527 goto out;
3528 }
3529 else if (strcmp(args[1], "retry") == 0 ||
3530 strcmp(args[1], "resolve") == 0) {
3531 const char *res;
3532 unsigned int tout;
3533
3534 if (!*args[2]) {
3535 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3536 file, linenum, args[0], args[1]);
3537 err_code |= ERR_ALERT | ERR_FATAL;
3538 goto out;
3539 }
3540 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3541 if (res == PARSE_TIME_OVER) {
3542 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3543 file, linenum, args[2], args[0], args[1]);
3544 err_code |= ERR_ALERT | ERR_FATAL;
3545 goto out;
3546 }
3547 else if (res == PARSE_TIME_UNDER) {
3548 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3549 file, linenum, args[2], args[0], args[1]);
3550 err_code |= ERR_ALERT | ERR_FATAL;
3551 goto out;
3552 }
3553 else if (res) {
3554 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3555 file, linenum, *res, args[0], args[1]);
3556 err_code |= ERR_ALERT | ERR_FATAL;
3557 goto out;
3558 }
3559 if (args[1][2] == 't')
3560 curr_resolvers->timeout.retry = tout;
3561 else
3562 curr_resolvers->timeout.resolve = tout;
3563 }
3564 else {
3565 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3566 file, linenum, args[0], args[1]);
3567 err_code |= ERR_ALERT | ERR_FATAL;
3568 goto out;
3569 }
3570 }
3571 else if (*args[0] != 0) {
3572 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3573 err_code |= ERR_ALERT | ERR_FATAL;
3574 goto out;
3575 }
3576
3577 out:
3578 free(errmsg);
3579 return err_code;
3580}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003581int cfg_post_parse_resolvers()
3582{
3583 int err_code = 0;
3584 struct server *srv;
3585
3586 if (curr_resolvers) {
3587
3588 /* prepare forward server descriptors */
3589 if (curr_resolvers->px) {
3590 srv = curr_resolvers->px->srv;
3591 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003592 /* init ssl if needed */
3593 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3594 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3595 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3596 err_code |= ERR_ALERT | ERR_FATAL;
3597 break;
3598 }
3599 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003600 srv = srv->next;
3601 }
3602 }
3603 }
3604 curr_resolvers = NULL;
3605 return err_code;
3606}
Emeric Brunc9437992021-02-12 19:42:55 +01003607
Emeric Brun56fc5d92021-02-12 20:05:45 +01003608REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003609REGISTER_POST_DEINIT(resolvers_deinit);
3610REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);