blob: 852c3d53823bdeb5367cd359661405ab9a4bfdac [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>
30#include <haproxy/dns.h>
31#include <haproxy/errors.h>
32#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010033#include <haproxy/http_rules.h>
34#include <haproxy/log.h>
35#include <haproxy/net_helper.h>
36#include <haproxy/protocol.h>
37#include <haproxy/proxy.h>
38#include <haproxy/resolvers.h>
39#include <haproxy/ring.h>
40#include <haproxy/sample.h>
41#include <haproxy/server.h>
42#include <haproxy/stats.h>
43#include <haproxy/stream_interface.h>
44#include <haproxy/task.h>
45#include <haproxy/tcp_rules.h>
46#include <haproxy/ticks.h>
47#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020048#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010049#include <haproxy/vars.h>
Willy Tarreaudcb696c2021-10-21 08:18:01 +020050#include <haproxy/xxhash.h>
Emeric Brunc9437992021-02-12 19:42:55 +010051
52
53struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
54struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
55
Willy Tarreauf766ec62021-10-18 16:46:38 +020056static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
Christopher Faulet9ed1a062021-11-02 16:25:05 +010057static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
Emeric Brunc9437992021-02-12 19:42:55 +010058static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
59struct resolvers *curr_resolvers = NULL;
60
61DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
62DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
63DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
64
65static unsigned int resolution_uuid = 1;
66unsigned int resolv_failed_resolutions = 0;
Willy Tarreauf766ec62021-10-18 16:46:38 +020067static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
68static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau6878f802021-10-20 14:07:31 +020069static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +010070static void enter_resolver_code();
71static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010072
73enum {
Emeric Brunf8642ee2021-10-29 17:59:18 +020074 RSLV_STAT_ID,
75 RSLV_STAT_PID,
76 RSLV_STAT_SENT,
77 RSLV_STAT_SND_ERROR,
78 RSLV_STAT_VALID,
79 RSLV_STAT_UPDATE,
80 RSLV_STAT_CNAME,
81 RSLV_STAT_CNAME_ERROR,
82 RSLV_STAT_ANY_ERR,
83 RSLV_STAT_NX,
84 RSLV_STAT_TIMEOUT,
85 RSLV_STAT_REFUSED,
86 RSLV_STAT_OTHER,
87 RSLV_STAT_INVALID,
88 RSLV_STAT_TOO_BIG,
89 RSLV_STAT_TRUNCATED,
90 RSLV_STAT_OUTDATED,
91 RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +010092};
93
Emeric Brunf8642ee2021-10-29 17:59:18 +020094static struct name_desc resolv_stats[] = {
95 [RSLV_STAT_ID] = { .name = "id", .desc = "ID" },
96 [RSLV_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
97 [RSLV_STAT_SENT] = { .name = "sent", .desc = "Sent" },
98 [RSLV_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
99 [RSLV_STAT_VALID] = { .name = "valid", .desc = "Valid" },
100 [RSLV_STAT_UPDATE] = { .name = "update", .desc = "Update" },
101 [RSLV_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
102 [RSLV_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
103 [RSLV_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
104 [RSLV_STAT_NX] = { .name = "nx", .desc = "NX" },
105 [RSLV_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
106 [RSLV_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
107 [RSLV_STAT_OTHER] = { .name = "other", .desc = "Other" },
108 [RSLV_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
109 [RSLV_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
110 [RSLV_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
111 [RSLV_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
Emeric Brunc9437992021-02-12 19:42:55 +0100112};
113
114static struct dns_counters dns_counters;
115
Emeric Brunf8642ee2021-10-29 17:59:18 +0200116static void resolv_fill_stats(void *d, struct field *stats)
Emeric Brunc9437992021-02-12 19:42:55 +0100117{
118 struct dns_counters *counters = d;
Emeric Brunf8642ee2021-10-29 17:59:18 +0200119 stats[RSLV_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
120 stats[RSLV_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
121 stats[RSLV_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
122 stats[RSLV_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
123 stats[RSLV_STAT_VALID] = mkf_u64(FN_GAUGE, counters->app.resolver.valid);
124 stats[RSLV_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->app.resolver.update);
125 stats[RSLV_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->app.resolver.cname);
126 stats[RSLV_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->app.resolver.cname_error);
127 stats[RSLV_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->app.resolver.any_err);
128 stats[RSLV_STAT_NX] = mkf_u64(FN_GAUGE, counters->app.resolver.nx);
129 stats[RSLV_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->app.resolver.timeout);
130 stats[RSLV_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->app.resolver.refused);
131 stats[RSLV_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->app.resolver.other);
132 stats[RSLV_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->app.resolver.invalid);
133 stats[RSLV_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->app.resolver.too_big);
134 stats[RSLV_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->app.resolver.truncated);
135 stats[RSLV_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +0100136}
137
Emeric Brunf8642ee2021-10-29 17:59:18 +0200138static struct stats_module rslv_stats_module = {
139 .name = "resolvers",
140 .domain_flags = STATS_DOMAIN_RESOLVERS << STATS_DOMAIN,
141 .fill_stats = resolv_fill_stats,
142 .stats = resolv_stats,
143 .stats_count = RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +0100144 .counters = &dns_counters,
145 .counters_size = sizeof(dns_counters),
146 .clearable = 0,
147};
148
Emeric Brunf8642ee2021-10-29 17:59:18 +0200149INITCALL1(STG_REGISTER, stats_register_module, &rslv_stats_module);
Emeric Brunc9437992021-02-12 19:42:55 +0100150
151/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
152 * no match is found.
153 */
154struct resolvers *find_resolvers_by_id(const char *id)
155{
156 struct resolvers *res;
157
158 list_for_each_entry(res, &sec_resolvers, list) {
159 if (strcmp(res->id, id) == 0)
160 return res;
161 }
162 return NULL;
163}
164
Emeric Brunc9437992021-02-12 19:42:55 +0100165/* Returns a pointer on the SRV request matching the name <name> for the proxy
166 * <px>. NULL is returned if no match is found.
167 */
168struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
169{
170 struct resolv_srvrq *srvrq;
171
172 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
173 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
174 return srvrq;
175 }
176 return NULL;
177}
178
179/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
180 * NULL if an error occurred. */
181struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
182{
183 struct proxy *px = srv->proxy;
184 struct resolv_srvrq *srvrq = NULL;
185 int fqdn_len, hostname_dn_len;
186
187 fqdn_len = strlen(fqdn);
Willy Tarreaubf9498a2021-10-14 07:49:49 +0200188 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100189 trash.size);
190 if (hostname_dn_len == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200191 ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100192 proxy_type_str(px), px->id, srv->id, fqdn);
193 goto err;
194 }
195
196 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200197 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100198 proxy_type_str(px), px->id, srv->id);
199 goto err;
200 }
201 srvrq->obj_type = OBJ_TYPE_SRVRQ;
202 srvrq->proxy = px;
203 srvrq->name = strdup(fqdn);
204 srvrq->hostname_dn = strdup(trash.area);
205 srvrq->hostname_dn_len = hostname_dn_len;
206 if (!srvrq->name || !srvrq->hostname_dn) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200207 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100208 proxy_type_str(px), px->id, srv->id);
209 goto err;
210 }
Emeric Brun34067662021-06-11 10:48:45 +0200211 LIST_INIT(&srvrq->attached_servers);
212 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200213 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100214 return srvrq;
215
216 err:
217 if (srvrq) {
218 free(srvrq->name);
219 free(srvrq->hostname_dn);
220 free(srvrq);
221 }
222 return NULL;
223}
224
225
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100226/* finds and return the SRV answer item associated to a requester (whose type is 'server').
227 *
228 * returns NULL in case of error or not found.
229 */
230struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
231{
232 struct resolv_resolution *res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200233 struct eb32_node *eb32;
234 struct server *srv;
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100235
236 if (!requester)
237 return NULL;
238
239 if ((srv = objt_server(requester->owner)) == NULL)
240 return NULL;
241 /* check if the server is managed by a SRV record */
242 if (srv->srvrq == NULL)
243 return NULL;
244
245 res = srv->srvrq->requester->resolution;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200246
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100247 /* search an ANSWER record whose target points to the server's hostname and whose port is
248 * the same as server's svc_port */
Willy Tarreau7893ae12021-10-21 07:39:57 +0200249 for (eb32 = eb32_first(&res->response.answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
250 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
251
Willy Tarreau75cc6532021-10-15 08:53:44 +0200252 if (memcmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100253 (srv->svc_port == item->port))
254 return item;
255 }
256
257 return NULL;
258}
259
Emeric Brunc9437992021-02-12 19:42:55 +0100260/* 2 bytes random generator to generate DNS query ID */
261static inline uint16_t resolv_rnd16(void)
262{
263 if (!resolv_query_id_seed)
264 resolv_query_id_seed = now_ms;
265 resolv_query_id_seed ^= resolv_query_id_seed << 13;
266 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
267 resolv_query_id_seed ^= resolv_query_id_seed << 17;
268 return resolv_query_id_seed;
269}
270
271
272static inline int resolv_resolution_timeout(struct resolv_resolution *res)
273{
274 return res->resolvers->timeout.resolve;
275}
276
277/* Updates a resolvers' task timeout for next wake up and queue it */
278static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
279{
280 struct resolv_resolution *res;
281 int next;
282
283 next = tick_add(now_ms, resolvers->timeout.resolve);
284 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
285 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
286 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
287 }
288
289 list_for_each_entry(res, &resolvers->resolutions.wait, list)
290 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
291
292 resolvers->t->expire = next;
293 task_queue(resolvers->t);
294}
295
296/* Forges a DNS query. It needs the following information from the caller:
297 * - <query_id> : the DNS query id corresponding to this query
298 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
299 * - <hostname_dn> : hostname in domain name format
300 * - <hostname_dn_len> : length of <hostname_dn>
301 *
302 * To store the query, the caller must pass a buffer <buf> and its size
303 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
304 * too short.
305 */
306static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
307 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
308{
309 struct dns_header dns_hdr;
310 struct dns_question qinfo;
311 struct dns_additional_record edns;
312 char *p = buf;
313
314 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
315 return -1;
316
317 memset(buf, 0, bufsize);
318
319 /* Set dns query headers */
320 dns_hdr.id = (unsigned short) htons(query_id);
321 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
322 dns_hdr.qdcount = htons(1); /* 1 question */
323 dns_hdr.ancount = 0;
324 dns_hdr.nscount = 0;
325 dns_hdr.arcount = htons(1);
326 memcpy(p, &dns_hdr, sizeof(dns_hdr));
327 p += sizeof(dns_hdr);
328
329 /* Set up query hostname */
330 memcpy(p, hostname_dn, hostname_dn_len);
331 p += hostname_dn_len;
332 *p++ = 0;
333
334 /* Set up query info (type and class) */
335 qinfo.qtype = htons(query_type);
336 qinfo.qclass = htons(DNS_RCLASS_IN);
337 memcpy(p, &qinfo, sizeof(qinfo));
338 p += sizeof(qinfo);
339
340 /* Set the DNS extension */
341 edns.name = 0;
342 edns.type = htons(DNS_RTYPE_OPT);
343 edns.udp_payload_size = htons(accepted_payload_size);
344 edns.extension = 0;
345 edns.data_length = 0;
346 memcpy(p, &edns, sizeof(edns));
347 p += sizeof(edns);
348
349 return (p - buf);
350}
351
352/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
Emeric Brun0161d322021-10-29 16:44:49 +0200353 * success or -1 if trash buffer is not large enough to build a valid query.
Emeric Brunc9437992021-02-12 19:42:55 +0100354 */
355static int resolv_send_query(struct resolv_resolution *resolution)
356{
357 struct resolvers *resolvers = resolution->resolvers;
358 struct dns_nameserver *ns;
359 int len;
360
361 /* Update resolution */
362 resolution->nb_queries = 0;
363 resolution->nb_responses = 0;
364 resolution->last_query = now_ms;
365
366 len = resolv_build_query(resolution->query_id, resolution->query_type,
367 resolvers->accepted_payload_size,
368 resolution->hostname_dn, resolution->hostname_dn_len,
369 trash.area, trash.size);
Emeric Brun0161d322021-10-29 16:44:49 +0200370 if (len < 0) {
371 send_log(NULL, LOG_NOTICE,
372 "can not build the query message for %s, in resolvers %s.\n",
373 resolution->hostname_dn, resolvers->id);
374 return -1;
375 }
Emeric Brunc9437992021-02-12 19:42:55 +0100376
377 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunc37caab2021-10-29 16:28:33 +0200378 if (dns_send_nameserver(ns, trash.area, len) >= 0)
Emeric Brunc9437992021-02-12 19:42:55 +0100379 resolution->nb_queries++;
380 }
381
382 /* Push the resolution at the end of the active list */
Willy Tarreauaae73202021-10-19 22:01:36 +0200383 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200384 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100385 return 0;
386}
387
388/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
389 * skipped and -1 if an error occurred.
390 */
391static int
392resolv_run_resolution(struct resolv_resolution *resolution)
393{
394 struct resolvers *resolvers = resolution->resolvers;
395 int query_id, i;
396
397 /* Avoid sending requests for resolutions that don't yet have an
398 * hostname, ie resolutions linked to servers that do not yet have an
399 * fqdn */
400 if (!resolution->hostname_dn)
401 return 0;
402
403 /* Check if a resolution has already been started for this server return
404 * directly to avoid resolution pill up. */
405 if (resolution->step != RSLV_STEP_NONE)
406 return 0;
407
408 /* Generates a new query id. We try at most 100 times to find a free
409 * query id */
410 for (i = 0; i < 100; ++i) {
411 query_id = resolv_rnd16();
412 if (!eb32_lookup(&resolvers->query_ids, query_id))
413 break;
414 query_id = -1;
415 }
416 if (query_id == -1) {
417 send_log(NULL, LOG_NOTICE,
418 "could not generate a query id for %s, in resolvers %s.\n",
419 resolution->hostname_dn, resolvers->id);
420 return -1;
421 }
422
423 /* Update resolution parameters */
424 resolution->query_id = query_id;
425 resolution->qid.key = query_id;
426 resolution->step = RSLV_STEP_RUNNING;
427 resolution->query_type = resolution->prefered_query_type;
428 resolution->try = resolvers->resolve_retries;
429 eb32_insert(&resolvers->query_ids, &resolution->qid);
430
431 /* Send the DNS query */
432 resolution->try -= 1;
433 resolv_send_query(resolution);
434 return 1;
435}
436
437/* Performs a name resolution for the requester <req> */
438void resolv_trigger_resolution(struct resolv_requester *req)
439{
440 struct resolvers *resolvers;
441 struct resolv_resolution *res;
442 int exp;
443
444 if (!req || !req->resolution)
445 return;
446 res = req->resolution;
447 resolvers = res->resolvers;
448
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100449 enter_resolver_code();
450
Emeric Brunc9437992021-02-12 19:42:55 +0100451 /* The resolution must not be triggered yet. Use the cached response, if
452 * valid */
453 exp = tick_add(res->last_resolution, resolvers->hold.valid);
454 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
455 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
456 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100457
458 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100459}
460
461
462/* Resets some resolution parameters to initial values and also delete the query
463 * ID from the resolver's tree.
464 */
465static void resolv_reset_resolution(struct resolv_resolution *resolution)
466{
467 /* update resolution status */
468 resolution->step = RSLV_STEP_NONE;
469 resolution->try = 0;
470 resolution->last_resolution = now_ms;
471 resolution->nb_queries = 0;
472 resolution->nb_responses = 0;
473 resolution->query_type = resolution->prefered_query_type;
474
475 /* clean up query id */
476 eb32_delete(&resolution->qid);
477 resolution->query_id = 0;
478 resolution->qid.key = 0;
479}
480
481/* Returns the query id contained in a DNS response */
482static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
483{
484 return resp[0] * 256 + resp[1];
485}
486
487
488/* Analyses, re-builds and copies the name <name> from the DNS response packet
489 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
490 * for compressed data. The result is copied into <dest>, ensuring we don't
491 * overflow using <dest_len> Returns the number of bytes the caller can move
492 * forward. If 0 it means an error occurred while parsing the name. <offset> is
493 * the number of bytes the caller could move forward.
494 */
495int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
496 unsigned char *name, char *destination, int dest_len,
497 int *offset, unsigned int depth)
498{
499 int nb_bytes = 0, n = 0;
500 int label_len;
501 unsigned char *reader = name;
502 char *dest = destination;
503
504 while (1) {
505 if (reader >= bufend)
506 goto err;
507
508 /* Name compression is in use */
509 if ((*reader & 0xc0) == 0xc0) {
510 if (reader + 1 >= bufend)
511 goto err;
512
513 /* Must point BEFORE current position */
514 if ((buffer + reader[1]) > reader)
515 goto err;
516
517 if (depth++ > 100)
518 goto err;
519
520 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
521 dest, dest_len - nb_bytes, offset, depth);
522 if (n == 0)
523 goto err;
524
525 dest += n;
526 nb_bytes += n;
527 goto out;
528 }
529
530 label_len = *reader;
531 if (label_len == 0)
532 goto out;
533
534 /* Check if:
535 * - we won't read outside the buffer
536 * - there is enough place in the destination
537 */
538 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
539 goto err;
540
541 /* +1 to take label len + label string */
542 label_len++;
543
544 memcpy(dest, reader, label_len);
545
546 dest += label_len;
547 nb_bytes += label_len;
548 reader += label_len;
549 }
550
551 out:
552 /* offset computation:
553 * parse from <name> until finding either NULL or a pointer "c0xx"
554 */
555 reader = name;
556 *offset = 0;
557 while (reader < bufend) {
558 if ((reader[0] & 0xc0) == 0xc0) {
559 *offset += 2;
560 break;
561 }
562 else if (*reader == 0) {
563 *offset += 1;
564 break;
565 }
566 *offset += 1;
567 ++reader;
568 }
569 return nb_bytes;
570
571 err:
572 return 0;
573}
574
Willy Tarreauf766ec62021-10-18 16:46:38 +0200575/* Reinitialize the list of aborted resolutions before calling certain
576 * functions relying on it. The list must be processed by calling
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100577 * leave_resolver_code() after operations.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200578 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100579static void enter_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200580{
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100581 if (!recurse)
582 LIST_INIT(&death_row);
583 recurse++;
Willy Tarreauf766ec62021-10-18 16:46:38 +0200584}
585
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100586/* Add a resolution to the death_row. */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200587static void abort_resolution(struct resolv_resolution *res)
588{
589 LIST_DEL_INIT(&res->list);
590 LIST_APPEND(&death_row, &res->list);
591}
592
593/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100594 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreauf766ec62021-10-18 16:46:38 +0200595 * needs to defer deletions. Note that some of them are in relation via internal
596 * objects and might cause the deletion of other ones from the same list, so we
597 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
598 * and solely rely on each call to remove the first remaining list element.
599 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100600static void leave_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200601{
602 struct resolv_resolution *res;
603
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100604 recurse--;
605 if (recurse)
606 return;
607
Willy Tarreauf766ec62021-10-18 16:46:38 +0200608 while (!LIST_ISEMPTY(&death_row)) {
609 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
610 resolv_free_resolution(res);
611 }
612
613 /* make sure nobody tries to add anything without having initialized it */
614 death_row = (struct list){ };
615}
616
Christopher Faulet11c6c392021-06-15 16:08:48 +0200617/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
618 * happens when an SRV item is purged or when the server status is considered as
619 * obsolete.
620 *
Willy Tarreauf766ec62021-10-18 16:46:38 +0200621 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100622 * initialized via enter_resolver_code().
Christopher Faulet11c6c392021-06-15 16:08:48 +0200623 */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200624static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet11c6c392021-06-15 16:08:48 +0200625{
Willy Tarreau6878f802021-10-20 14:07:31 +0200626 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200627 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
628 srvrq_update_srv_status(srv, 1);
629 ha_free(&srv->hostname);
630 ha_free(&srv->hostname_dn);
631 srv->hostname_dn_len = 0;
632 memset(&srv->addr, 0, sizeof(srv->addr));
633 srv->svc_port = 0;
634 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet73001ab2021-06-15 16:14:37 +0200635
636 ebpt_delete(&srv->host_dn);
637 ha_free(&srv->host_dn.key);
638
Christopher Faulet11c6c392021-06-15 16:08:48 +0200639 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreauaae73202021-10-19 22:01:36 +0200640 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200641 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Fauletdcac4182021-06-15 16:17:17 +0200642
643 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet11c6c392021-06-15 16:08:48 +0200644}
645
Christopher Fauletdcac4182021-06-15 16:17:17 +0200646/* Takes care to cleanup a server resolution when it is outdated. This only
647 * happens for a server relying on a SRV record.
648 */
649static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
650{
651 struct server *srv = context;
652
653 if (!tick_is_expired(t->expire, now_ms))
654 goto end;
655
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100656 enter_resolver_code();
Christopher Faulete886dd52021-06-18 09:05:49 +0200657 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreauf766ec62021-10-18 16:46:38 +0200658 resolv_srvrq_cleanup_srv(srv);
Christopher Faulete886dd52021-06-18 09:05:49 +0200659 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100660 leave_resolver_code();
Christopher Fauletdcac4182021-06-15 16:17:17 +0200661
662 end:
663 return t;
664}
665
Emeric Brunc9437992021-02-12 19:42:55 +0100666/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100667 * find a corresponding server.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200668 */
Emeric Brunc9437992021-02-12 19:42:55 +0100669static void resolv_check_response(struct resolv_resolution *res)
670{
671 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100672 struct resolv_requester *req;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200673 struct eb32_node *eb32, *eb32_back;
Emeric Brunbd78c912021-06-11 10:08:05 +0200674 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100675 struct resolv_srvrq *srvrq;
676
Willy Tarreau7893ae12021-10-21 07:39:57 +0200677 for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
678 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
Emeric Brunc9437992021-02-12 19:42:55 +0100679 struct resolv_answer_item *ar_item = item->ar_item;
680
681 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100682 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100683 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
684 * item is also obsolete.
685 */
Emeric Brunc9437992021-02-12 19:42:55 +0100686 pool_free(resolv_answer_item_pool, ar_item);
687 item->ar_item = NULL;
688 }
689
690 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100691 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200692 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100693 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200694 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
695 LIST_DEL_INIT(&srv->ip_rec_item);
696 }
697 }
698 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun34067662021-06-11 10:48:45 +0200699 /* Remove any associated server */
Christopher Faulet11c6c392021-06-15 16:08:48 +0200700 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreauf766ec62021-10-18 16:46:38 +0200701 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100702 }
703
Willy Tarreau7893ae12021-10-21 07:39:57 +0200704 eb32_delete(&item->link);
Emeric Brunc9437992021-02-12 19:42:55 +0100705 if (item->ar_item) {
706 pool_free(resolv_answer_item_pool, item->ar_item);
707 item->ar_item = NULL;
708 }
709 pool_free(resolv_answer_item_pool, item);
710 continue;
711 }
712
713 if (item->type != DNS_RTYPE_SRV)
714 continue;
715
716 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100717 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun34067662021-06-11 10:48:45 +0200718 struct ebpt_node *node;
719 char target[DNS_MAX_NAME_SIZE+1];
720
721 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100722 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
723 continue;
724
Emeric Brun34067662021-06-11 10:48:45 +0200725 /* Check if a server already uses that record */
726 srv = NULL;
727 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
728 if (srv->srvrq == srvrq) {
729 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
730 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100731 }
Emeric Brunc9437992021-02-12 19:42:55 +0100732 }
733
Emeric Brun34067662021-06-11 10:48:45 +0200734
735 /* If not empty we try to match a server
736 * in server state file tree with the same hostname
737 */
738 if (!eb_is_empty(&srvrq->named_servers)) {
739 srv = NULL;
740
741 /* convert the key to lookup in lower case */
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200742 for (i = 0 ; item->data.target[i] ; i++)
743 target[i] = tolower(item->data.target[i]);
Christopher Faulet1f923392021-07-22 14:29:26 +0200744 target[i] = 0;
Emeric Brun34067662021-06-11 10:48:45 +0200745
746 node = ebis_lookup(&srvrq->named_servers, target);
747 if (node) {
748 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100749 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun34067662021-06-11 10:48:45 +0200750
751 /* an entry was found with the same hostname
752 * let check this node if the port matches
753 * and try next node if the hostname
754 * is still the same
755 */
756 while (1) {
757 if (srv->svc_port == item->port) {
758 /* server found, we remove it from tree */
759 ebpt_delete(node);
Christopher Faulet73001ab2021-06-15 16:14:37 +0200760 ha_free(&srv->host_dn.key);
Emeric Brun34067662021-06-11 10:48:45 +0200761 goto srv_found;
762 }
763
764 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
765
766 node = ebpt_next(node);
767 if (!node)
768 break;
769
770 srv = ebpt_entry(node, struct server, host_dn);
771 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
772
773 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau75cc6532021-10-15 08:53:44 +0200774 || memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
Emeric Brun34067662021-06-11 10:48:45 +0200775 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
776 break;
777 }
778 }
Emeric Brunc9437992021-02-12 19:42:55 +0100779 }
780 }
Emeric Brun34067662021-06-11 10:48:45 +0200781
782 /* Pick the first server listed in srvrq (those ones don't
783 * have hostname and are free to use)
784 */
785 srv = NULL;
786 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
787 LIST_DEL_INIT(&srv->srv_rec_item);
788 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
789 goto srv_found;
790 }
791 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100792
Emeric Brun34067662021-06-11 10:48:45 +0200793srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100794 /* And update this server, if found (srv is locked here) */
795 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100796 /* re-enable DNS resolution for this server by default */
797 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Fauletdcac4182021-06-15 16:17:17 +0200798 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100799
Emeric Brunc9437992021-02-12 19:42:55 +0100800 /* Check if an Additional Record is associated to this SRV record.
801 * Perform some sanity checks too to ensure the record can be used.
802 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100803 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100804 */
805 if ((item->ar_item != NULL) &&
806 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100807 {
Emeric Brunc9437992021-02-12 19:42:55 +0100808
809 switch (item->ar_item->type) {
810 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200811 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100812 break;
813 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200814 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100815 break;
816 }
817
818 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100819
820 /* Unlink A/AAAA resolution for this server if there is an AR item.
821 * It is usless to perform an extra resolution
822 */
Willy Tarreau6878f802021-10-20 14:07:31 +0200823 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100824 }
825
826 if (!srv->hostname_dn) {
827 const char *msg = NULL;
Willy Tarreau85c15e62021-10-14 08:00:38 +0200828 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100829
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200830 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau85c15e62021-10-14 08:00:38 +0200831 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100832 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
833 continue;
834 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100835 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100836 if (msg)
837 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
838 }
839
Emeric Brun34067662021-06-11 10:48:45 +0200840 if (!LIST_INLIST(&srv->srv_rec_item))
841 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
842
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100843 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
844 /* If there is no AR item responsible of the FQDN resolution,
845 * trigger a dedicated DNS resolution
846 */
847 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
848 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
849 }
850
Christopher Fauletab177ac2021-03-10 15:34:52 +0100851 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100852 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100853
854 srv->svc_port = item->port;
855 srv->flags &= ~SRV_F_MAPPORTS;
856
857 if (!srv->resolv_opts.ignore_weight) {
858 char weight[9];
859 int ha_weight;
860
861 /* DNS weight range if from 0 to 65535
862 * HAProxy weight is from 0 to 256
863 * The rule below ensures that weight 0 is well respected
864 * while allowing a "mapping" from DNS weight into HAProxy's one.
865 */
866 ha_weight = (item->weight + 255) / 256;
867
868 snprintf(weight, sizeof(weight), "%d", ha_weight);
869 server_parse_weight_change_request(srv, weight);
870 }
871 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
872 }
873 }
874 }
875}
876
877/* Validates that the buffer DNS response provided in <resp> and finishing
878 * before <bufend> is valid from a DNS protocol point of view.
879 *
880 * The result is stored in <resolution>' response, buf_response,
881 * response_query_records and response_answer_records members.
882 *
883 * This function returns one of the RSLV_RESP_* code to indicate the type of
884 * error found.
885 */
886static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
887 struct resolv_resolution *resolution, int max_answer_records)
888{
889 unsigned char *reader;
890 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
891 int len, flags, offset;
892 int query_record_id;
893 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
990 /* Parsing dns queries */
Willy Tarreau25e01092021-10-19 11:17:33 +0200991 BUG_ON(!LIST_ISEMPTY(&r_res->query_list));
Emeric Brunc9437992021-02-12 19:42:55 +0100992 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
993 /* Use next pre-allocated resolv_query_item after ensuring there is
994 * still one available.
995 * It's then added to our packet query list. */
996 if (query_record_id > DNS_MAX_QUERY_RECORDS)
997 goto invalid_resp;
998 query = &resolution->response_query_records[query_record_id];
Willy Tarreau2b718102021-04-21 07:32:39 +0200999 LIST_APPEND(&r_res->query_list, &query->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001000
1001 /* Name is a NULL terminated string in our case, since we have
1002 * one query per response and the first one can't be compressed
1003 * (using the 0x0c format) */
1004 offset = 0;
1005 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
1006
1007 if (len == 0)
1008 goto invalid_resp;
1009
1010 reader += offset;
1011 previous_dname = query->name;
1012
1013 /* move forward 2 bytes for question type */
1014 if (reader + 2 >= bufend)
1015 goto invalid_resp;
1016 query->type = reader[0] * 256 + reader[1];
1017 reader += 2;
1018
1019 /* move forward 2 bytes for question class */
1020 if (reader + 2 >= bufend)
1021 goto invalid_resp;
1022 query->class = reader[0] * 256 + reader[1];
1023 reader += 2;
1024 }
1025
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001026 /* Let's just make gcc happy. The tests above make it clear that
1027 * qdcount==1 hence that we necessarily enter into the loop at least
1028 * once, but gcc seems to be having difficulties following it and
1029 * warns about the risk of NULL dereference at the next line, even
1030 * if a BUG_ON(!query) is used.
1031 */
1032 ALREADY_CHECKED(query);
1033
Emeric Brunc9437992021-02-12 19:42:55 +01001034 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001035 * because a TRUNCATED SRV query type response can still be exploited
1036 */
Emeric Brunc9437992021-02-12 19:42:55 +01001037 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1038 cause = RSLV_RESP_TRUNCATED;
1039 goto return_error;
1040 }
1041
1042 /* now parsing response records */
1043 nb_saved_records = 0;
1044 for (i = 0; i < r_res->header.ancount; i++) {
1045 if (reader >= bufend)
1046 goto invalid_resp;
1047
1048 answer_record = pool_alloc(resolv_answer_item_pool);
1049 if (answer_record == NULL)
1050 goto invalid_resp;
1051
1052 /* initialization */
1053 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001054 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001055 LIST_INIT(&answer_record->attached_servers);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001056 answer_record->link.node.leaf_p = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001057
1058 offset = 0;
1059 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1060
1061 if (len == 0)
1062 goto invalid_resp;
1063
1064 /* Check if the current record dname is valid. previous_dname
1065 * points either to queried dname or last CNAME target */
Willy Tarreau75cc6532021-10-15 08:53:44 +02001066 if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001067 if (i == 0) {
1068 /* First record, means a mismatch issue between
1069 * queried dname and dname found in the first
1070 * record */
1071 goto invalid_resp;
1072 }
1073 else {
1074 /* If not the first record, this means we have a
1075 * CNAME resolution error.
1076 */
1077 cause = RSLV_RESP_CNAME_ERROR;
1078 goto return_error;
1079 }
1080
1081 }
1082
1083 memcpy(answer_record->name, tmpname, len);
1084 answer_record->name[len] = 0;
1085
1086 reader += offset;
1087 if (reader >= bufend)
1088 goto invalid_resp;
1089
1090 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1091 if (reader + 2 > bufend)
1092 goto invalid_resp;
1093
1094 answer_record->type = reader[0] * 256 + reader[1];
1095 reader += 2;
1096
1097 /* 2 bytes for class (2) */
1098 if (reader + 2 > bufend)
1099 goto invalid_resp;
1100
1101 answer_record->class = reader[0] * 256 + reader[1];
1102 reader += 2;
1103
1104 /* 4 bytes for ttl (4) */
1105 if (reader + 4 > bufend)
1106 goto invalid_resp;
1107
1108 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1109 + reader[2] * 256 + reader[3];
1110 reader += 4;
1111
1112 /* Now reading data len */
1113 if (reader + 2 > bufend)
1114 goto invalid_resp;
1115
1116 answer_record->data_len = reader[0] * 256 + reader[1];
1117
1118 /* Move forward 2 bytes for data len */
1119 reader += 2;
1120
1121 if (reader + answer_record->data_len > bufend)
1122 goto invalid_resp;
1123
1124 /* Analyzing record content */
1125 switch (answer_record->type) {
1126 case DNS_RTYPE_A:
1127 /* ipv4 is stored on 4 bytes */
1128 if (answer_record->data_len != 4)
1129 goto invalid_resp;
1130
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001131 answer_record->data.in4.sin_family = AF_INET;
1132 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001133 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001134 break;
1135
1136 case DNS_RTYPE_CNAME:
1137 /* Check if this is the last record and update the caller about the status:
1138 * no IP could be found and last record was a CNAME. Could be triggered
1139 * by a wrong query type
1140 *
1141 * + 1 because answer_record_id starts at 0
1142 * while number of answers is an integer and
1143 * starts at 1.
1144 */
1145 if (i + 1 == r_res->header.ancount) {
1146 cause = RSLV_RESP_CNAME_ERROR;
1147 goto return_error;
1148 }
1149
1150 offset = 0;
1151 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1152 if (len == 0)
1153 goto invalid_resp;
1154
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001155 memcpy(answer_record->data.target, tmpname, len);
1156 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001157 key = XXH32(tmpname, len, answer_record->type);
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001158 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001159 break;
1160
1161
1162 case DNS_RTYPE_SRV:
1163 /* Answer must contain :
1164 * - 2 bytes for the priority
1165 * - 2 bytes for the weight
1166 * - 2 bytes for the port
1167 * - the target hostname
1168 */
1169 if (answer_record->data_len <= 6)
1170 goto invalid_resp;
1171
1172 answer_record->priority = read_n16(reader);
1173 reader += sizeof(uint16_t);
1174 answer_record->weight = read_n16(reader);
1175 reader += sizeof(uint16_t);
1176 answer_record->port = read_n16(reader);
1177 reader += sizeof(uint16_t);
1178 offset = 0;
1179 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1180 if (len == 0)
1181 goto invalid_resp;
1182
1183 answer_record->data_len = len;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001184 memcpy(answer_record->data.target, tmpname, len);
1185 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001186 key = XXH32(tmpname, len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001187 if (answer_record->ar_item != NULL) {
1188 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1189 answer_record->ar_item = NULL;
1190 }
1191 break;
1192
1193 case DNS_RTYPE_AAAA:
1194 /* ipv6 is stored on 16 bytes */
1195 if (answer_record->data_len != 16)
1196 goto invalid_resp;
1197
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001198 answer_record->data.in6.sin6_family = AF_INET6;
1199 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001200 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001201 break;
1202
1203 } /* switch (record type) */
1204
1205 /* Increment the counter for number of records saved into our
1206 * local response */
1207 nb_saved_records++;
1208
1209 /* Move forward answer_record->data_len for analyzing next
1210 * record in the response */
1211 reader += ((answer_record->type == DNS_RTYPE_SRV)
1212 ? offset
1213 : answer_record->data_len);
1214
1215 /* Lookup to see if we already had this entry */
1216 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001217
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001218 for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02001219 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001220 if (tmp_record->type != answer_record->type)
1221 continue;
1222
1223 switch(tmp_record->type) {
1224 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001225 if (!memcmp(&answer_record->data.in4.sin_addr,
1226 &tmp_record->data.in4.sin_addr,
1227 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001228 found = 1;
1229 break;
1230
1231 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001232 if (!memcmp(&answer_record->data.in6.sin6_addr,
1233 &tmp_record->data.in6.sin6_addr,
1234 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001235 found = 1;
1236 break;
1237
1238 case DNS_RTYPE_SRV:
1239 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001240 memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
Emeric Brunc9437992021-02-12 19:42:55 +01001241 answer_record->port == tmp_record->port) {
1242 tmp_record->weight = answer_record->weight;
1243 found = 1;
1244 }
1245 break;
1246
1247 default:
1248 break;
1249 }
1250
1251 if (found == 1)
1252 break;
1253 }
1254
1255 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001256 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001257 pool_free(resolv_answer_item_pool, answer_record);
1258 answer_record = NULL;
1259 }
1260 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001261 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001262 answer_record->ar_item = NULL;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001263 answer_record->link.key = key;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001264 eb32_insert(&r_res->answer_tree, &answer_record->link);
Emeric Brunc9437992021-02-12 19:42:55 +01001265 answer_record = NULL;
1266 }
1267 } /* for i 0 to ancount */
1268
1269 /* Save the number of records we really own */
1270 r_res->header.ancount = nb_saved_records;
1271
1272 /* now parsing additional records for SRV queries only */
1273 if (query->type != DNS_RTYPE_SRV)
1274 goto skip_parsing_additional_records;
1275
1276 /* if we find Authority records, just skip them */
1277 for (i = 0; i < r_res->header.nscount; i++) {
1278 offset = 0;
1279 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1280 &offset, 0);
1281 if (len == 0)
1282 continue;
1283
1284 if (reader + offset + 10 >= bufend)
1285 goto invalid_resp;
1286
1287 reader += offset;
1288 /* skip 2 bytes for class */
1289 reader += 2;
1290 /* skip 2 bytes for type */
1291 reader += 2;
1292 /* skip 4 bytes for ttl */
1293 reader += 4;
1294 /* read data len */
1295 len = reader[0] * 256 + reader[1];
1296 reader += 2;
1297
1298 if (reader + len >= bufend)
1299 goto invalid_resp;
1300
1301 reader += len;
1302 }
1303
1304 nb_saved_records = 0;
1305 for (i = 0; i < r_res->header.arcount; i++) {
1306 if (reader >= bufend)
1307 goto invalid_resp;
1308
1309 answer_record = pool_alloc(resolv_answer_item_pool);
1310 if (answer_record == NULL)
1311 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001312 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001313 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001314
1315 offset = 0;
1316 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1317
1318 if (len == 0) {
1319 pool_free(resolv_answer_item_pool, answer_record);
1320 answer_record = NULL;
1321 continue;
1322 }
1323
1324 memcpy(answer_record->name, tmpname, len);
1325 answer_record->name[len] = 0;
1326
1327 reader += offset;
1328 if (reader >= bufend)
1329 goto invalid_resp;
1330
1331 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1332 if (reader + 2 > bufend)
1333 goto invalid_resp;
1334
1335 answer_record->type = reader[0] * 256 + reader[1];
1336 reader += 2;
1337
1338 /* 2 bytes for class (2) */
1339 if (reader + 2 > bufend)
1340 goto invalid_resp;
1341
1342 answer_record->class = reader[0] * 256 + reader[1];
1343 reader += 2;
1344
1345 /* 4 bytes for ttl (4) */
1346 if (reader + 4 > bufend)
1347 goto invalid_resp;
1348
1349 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1350 + reader[2] * 256 + reader[3];
1351 reader += 4;
1352
1353 /* Now reading data len */
1354 if (reader + 2 > bufend)
1355 goto invalid_resp;
1356
1357 answer_record->data_len = reader[0] * 256 + reader[1];
1358
1359 /* Move forward 2 bytes for data len */
1360 reader += 2;
1361
1362 if (reader + answer_record->data_len > bufend)
1363 goto invalid_resp;
1364
1365 /* Analyzing record content */
1366 switch (answer_record->type) {
1367 case DNS_RTYPE_A:
1368 /* ipv4 is stored on 4 bytes */
1369 if (answer_record->data_len != 4)
1370 goto invalid_resp;
1371
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001372 answer_record->data.in4.sin_family = AF_INET;
1373 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001374 break;
1375
1376 case DNS_RTYPE_AAAA:
1377 /* ipv6 is stored on 16 bytes */
1378 if (answer_record->data_len != 16)
1379 goto invalid_resp;
1380
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001381 answer_record->data.in6.sin6_family = AF_INET6;
1382 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001383 break;
1384
1385 default:
1386 pool_free(resolv_answer_item_pool, answer_record);
1387 answer_record = NULL;
1388 continue;
1389
1390 } /* switch (record type) */
1391
1392 /* Increment the counter for number of records saved into our
1393 * local response */
1394 nb_saved_records++;
1395
1396 /* Move forward answer_record->data_len for analyzing next
1397 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001398 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001399
1400 /* Lookup to see if we already had this entry */
1401 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001402
1403 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001404 struct resolv_answer_item *ar_item;
1405
Willy Tarreau7893ae12021-10-21 07:39:57 +02001406 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Christopher Faulet77f86062021-03-10 15:19:57 +01001407 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1408 continue;
1409
1410 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001411 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001412 len != tmp_record->data_len ||
Willy Tarreau75cc6532021-10-15 08:53:44 +02001413 memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001414 continue;
1415
Christopher Faulet77f86062021-03-10 15:19:57 +01001416 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001417 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001418 if (!memcmp(&answer_record->data.in4.sin_addr,
1419 &ar_item->data.in4.sin_addr,
1420 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001421 found = 1;
1422 break;
1423
1424 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001425 if (!memcmp(&answer_record->data.in6.sin6_addr,
1426 &ar_item->data.in6.sin6_addr,
1427 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001428 found = 1;
1429 break;
1430
1431 default:
1432 break;
1433 }
1434
1435 if (found == 1)
1436 break;
1437 }
1438
1439 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001440 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001441 pool_free(resolv_answer_item_pool, answer_record);
1442 answer_record = NULL;
1443 }
1444 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001445 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001446 answer_record->ar_item = NULL;
1447
1448 // looking for the SRV record in the response list linked to this additional record
Willy Tarreau7893ae12021-10-21 07:39:57 +02001449 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
1450 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
1451
Emeric Brunc9437992021-02-12 19:42:55 +01001452 if (tmp_record->type == DNS_RTYPE_SRV &&
1453 tmp_record->ar_item == NULL &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001454 memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001455 /* Always use the received additional record to refresh info */
1456 if (tmp_record->ar_item)
1457 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1458 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001459 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001460 break;
1461 }
1462 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001463 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001464 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001465 answer_record = NULL;
1466 }
Emeric Brunc9437992021-02-12 19:42:55 +01001467 }
1468 } /* for i 0 to arcount */
1469
1470 skip_parsing_additional_records:
1471
1472 /* Save the number of records we really own */
1473 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001474 resolv_check_response(resolution);
1475 return RSLV_RESP_VALID;
1476
1477 invalid_resp:
1478 cause = RSLV_RESP_INVALID;
1479
1480 return_error:
1481 pool_free(resolv_answer_item_pool, answer_record);
1482 return cause;
1483}
1484
1485/* Searches dn_name resolution in resp.
1486 * If existing IP not found, return the first IP matching family_priority,
1487 * otherwise, first ip found
1488 * The following tasks are the responsibility of the caller:
1489 * - <r_res> contains an error free DNS response
1490 * For both cases above, resolv_validate_dns_response is required
1491 * returns one of the RSLV_UPD_* code
1492 */
1493int resolv_get_ip_from_response(struct resolv_response *r_res,
1494 struct resolv_options *resolv_opts, void *currentip,
1495 short currentip_sin_family,
1496 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001497 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001498{
Emeric Brunbd78c912021-06-11 10:08:05 +02001499 struct resolv_answer_item *record, *found_record = NULL;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001500 struct eb32_node *eb32;
Emeric Brunc9437992021-02-12 19:42:55 +01001501 int family_priority;
1502 int currentip_found;
1503 unsigned char *newip4, *newip6;
1504 int currentip_sel;
1505 int j;
1506 int score, max_score;
1507 int allowed_duplicated_ip;
1508
Emeric Brunbd78c912021-06-11 10:08:05 +02001509 /* srv is linked to an alive ip record */
1510 if (owner && LIST_INLIST(&owner->ip_rec_item))
1511 return RSLV_UPD_NO;
1512
Emeric Brunc9437992021-02-12 19:42:55 +01001513 family_priority = resolv_opts->family_prio;
1514 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1515 *newip = newip4 = newip6 = NULL;
1516 currentip_found = 0;
1517 *newip_sin_family = AF_UNSPEC;
1518 max_score = -1;
1519
1520 /* Select an IP regarding configuration preference.
1521 * Top priority is the preferred network ip version,
1522 * second priority is the preferred network.
1523 * the last priority is the currently used IP,
1524 *
1525 * For these three priorities, a score is calculated. The
1526 * weight are:
1527 * 8 - preferred ip version.
1528 * 4 - preferred network.
1529 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1530 * 1 - current ip.
1531 * The result with the biggest score is returned.
1532 */
1533
Willy Tarreau7893ae12021-10-21 07:39:57 +02001534 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001535 void *ip;
1536 unsigned char ip_type;
1537
Willy Tarreau7893ae12021-10-21 07:39:57 +02001538 record = eb32_entry(eb32, typeof(*record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001539 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001540 ip_type = AF_INET;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001541 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001542 }
1543 else if (record->type == DNS_RTYPE_AAAA) {
1544 ip_type = AF_INET6;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001545 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001546 }
1547 else
1548 continue;
1549 score = 0;
1550
1551 /* Check for preferred ip protocol. */
1552 if (ip_type == family_priority)
1553 score += 8;
1554
1555 /* Check for preferred network. */
1556 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1557
1558 /* Compare only the same addresses class. */
1559 if (resolv_opts->pref_net[j].family != ip_type)
1560 continue;
1561
1562 if ((ip_type == AF_INET &&
1563 in_net_ipv4(ip,
1564 &resolv_opts->pref_net[j].mask.in4,
1565 &resolv_opts->pref_net[j].addr.in4)) ||
1566 (ip_type == AF_INET6 &&
1567 in_net_ipv6(ip,
1568 &resolv_opts->pref_net[j].mask.in6,
1569 &resolv_opts->pref_net[j].addr.in6))) {
1570 score += 4;
1571 break;
1572 }
1573 }
1574
1575 /* Check if the IP found in the record is already affected to a
1576 * member of a group. If not, the score should be incremented
1577 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001578 if (owner) {
1579 struct server *srv;
1580 int already_used = 0;
1581
1582 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1583 if (srv == owner)
1584 continue;
1585 if (srv->proxy == owner->proxy) {
1586 already_used = 1;
1587 break;
1588 }
1589 }
1590 if (already_used) {
1591 if (!allowed_duplicated_ip) {
1592 continue;
1593 }
1594 }
1595 else {
1596 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001597 }
1598 } else {
1599 score += 2;
1600 }
1601
1602 /* Check for current ip matching. */
1603 if (ip_type == currentip_sin_family &&
1604 ((currentip_sin_family == AF_INET &&
1605 !memcmp(ip, currentip, 4)) ||
1606 (currentip_sin_family == AF_INET6 &&
1607 !memcmp(ip, currentip, 16)))) {
1608 score++;
1609 currentip_sel = 1;
1610 }
1611 else
1612 currentip_sel = 0;
1613
1614 /* Keep the address if the score is better than the previous
1615 * score. The maximum score is 15, if this value is reached, we
1616 * break the parsing. Implicitly, this score is reached the ip
1617 * selected is the current ip. */
1618 if (score > max_score) {
1619 if (ip_type == AF_INET)
1620 newip4 = ip;
1621 else
1622 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001623 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001624 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001625 if (score == 15) {
1626 /* this was not registered on the current record but it matches
1627 * let's fix it (it may comes from state file */
1628 if (owner)
1629 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001630 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001631 }
Emeric Brunc9437992021-02-12 19:42:55 +01001632 max_score = score;
1633 }
1634 } /* list for each record entries */
1635
1636 /* No IP found in the response */
1637 if (!newip4 && !newip6)
1638 return RSLV_UPD_NO_IP_FOUND;
1639
1640 /* Case when the caller looks first for an IPv4 address */
1641 if (family_priority == AF_INET) {
1642 if (newip4) {
1643 *newip = newip4;
1644 *newip_sin_family = AF_INET;
1645 }
1646 else if (newip6) {
1647 *newip = newip6;
1648 *newip_sin_family = AF_INET6;
1649 }
Emeric Brunc9437992021-02-12 19:42:55 +01001650 }
1651 /* Case when the caller looks first for an IPv6 address */
1652 else if (family_priority == AF_INET6) {
1653 if (newip6) {
1654 *newip = newip6;
1655 *newip_sin_family = AF_INET6;
1656 }
1657 else if (newip4) {
1658 *newip = newip4;
1659 *newip_sin_family = AF_INET;
1660 }
Emeric Brunc9437992021-02-12 19:42:55 +01001661 }
1662 /* Case when the caller have no preference (we prefer IPv6) */
1663 else if (family_priority == AF_UNSPEC) {
1664 if (newip6) {
1665 *newip = newip6;
1666 *newip_sin_family = AF_INET6;
1667 }
1668 else if (newip4) {
1669 *newip = newip4;
1670 *newip_sin_family = AF_INET;
1671 }
Emeric Brunc9437992021-02-12 19:42:55 +01001672 }
1673
Emeric Brunbd78c912021-06-11 10:08:05 +02001674 /* the ip of this record was chosen for the server */
1675 if (owner && found_record) {
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001676 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunbd78c912021-06-11 10:08:05 +02001677 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1678 }
1679
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001680 eb32 = eb32_first(&r_res->answer_tree);
1681 if (eb32) {
Emeric Brunc9437992021-02-12 19:42:55 +01001682 /* Move the first record to the end of the list, for internal
Willy Tarreau7893ae12021-10-21 07:39:57 +02001683 * round robin.
1684 */
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001685 eb32_delete(eb32);
1686 eb32_insert(&r_res->answer_tree, eb32);
Emeric Brunc9437992021-02-12 19:42:55 +01001687 }
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001688
1689 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001690}
1691
Willy Tarreau875ee702021-10-14 08:05:25 +02001692/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001693 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001694 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1695 * null-terminated. <str> must be allocated large enough to contain a full host
1696 * name plus the trailing zero, and the allocated size must be passed in
1697 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001698 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001699 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001700 * <str> (including the terminating null byte).
1701 */
1702int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1703{
1704 char *ptr;
1705 int i, sz;
1706
Willy Tarreau875ee702021-10-14 08:05:25 +02001707 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001708 return -1;
1709
1710 ptr = str;
Willy Tarreau875ee702021-10-14 08:05:25 +02001711 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001712 sz = dn[i];
1713 if (i)
1714 *ptr++ = '.';
Willy Tarreau814889c2021-10-15 07:45:38 +02001715 /* copy the string at i+1 to lower case */
1716 for (; sz > 0; sz--)
1717 *(ptr++) = tolower(dn[++i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001718 }
1719 *ptr++ = '\0';
1720 return (ptr - str);
1721}
1722
1723/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1724 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001725 * <str> contains the input string that is <str_len> bytes long (trailing zero
1726 * not needed). <dn> buffer must be allocated large enough to contain the
1727 * encoded string and a trailing zero, so it must be at least str_len+2, and
1728 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001729 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001730 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001731 * <dn> (excluding the terminating null byte).
1732 */
1733int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1734{
1735 int i, offset;
1736
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001737 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001738 return -1;
1739
1740 /* First byte of dn will be used to store the length of the first
1741 * label */
1742 offset = 0;
1743 for (i = 0; i < str_len; ++i) {
1744 if (str[i] == '.') {
1745 /* 2 or more consecutive dots is invalid */
1746 if (i == offset)
1747 return -1;
1748
1749 /* ignore trailing dot */
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001750 if (i + 1 == str_len) {
Emeric Brunc9437992021-02-12 19:42:55 +01001751 i++;
1752 break;
1753 }
1754
1755 dn[offset] = (i - offset);
1756 offset = i+1;
1757 continue;
1758 }
Willy Tarreau814889c2021-10-15 07:45:38 +02001759 dn[i+1] = tolower(str[i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001760 }
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001761 dn[offset] = i - offset;
Willy Tarreau7b232f12021-10-15 08:09:25 +02001762 dn[i+1] = '\0';
1763 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001764}
1765
1766/* Validates host name:
1767 * - total size
1768 * - each label size individually
1769 * returns:
1770 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1771 * 1 when no error. <err> is left unaffected.
1772 */
1773int resolv_hostname_validation(const char *string, char **err)
1774{
1775 int i;
1776
1777 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1778 if (err)
1779 *err = DNS_TOO_LONG_FQDN;
1780 return 0;
1781 }
1782
1783 while (*string) {
1784 i = 0;
1785 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1786 if (!(*string == '-' || *string == '_' ||
1787 (*string >= 'a' && *string <= 'z') ||
1788 (*string >= 'A' && *string <= 'Z') ||
1789 (*string >= '0' && *string <= '9'))) {
1790 if (err)
1791 *err = DNS_INVALID_CHARACTER;
1792 return 0;
1793 }
1794 i++;
1795 string++;
1796 }
1797
1798 if (!(*string))
1799 break;
1800
1801 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1802 if (err)
1803 *err = DNS_LABEL_TOO_LONG;
1804 return 0;
1805 }
1806
1807 string++;
1808 }
1809 return 1;
1810}
1811
1812/* Picks up an available resolution from the different resolution list
1813 * associated to a resolvers section, in this order:
1814 * 1. check in resolutions.curr for the same hostname and query_type
1815 * 2. check in resolutions.wait for the same hostname and query_type
1816 * 3. Get a new resolution from resolution pool
1817 *
1818 * Returns an available resolution, NULL if none found.
1819 */
1820static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1821 char **hostname_dn, int hostname_dn_len,
1822 int query_type)
1823{
1824 struct resolv_resolution *res;
1825
1826 if (!*hostname_dn)
1827 goto from_pool;
1828
1829 /* Search for same hostname and query type in resolutions.curr */
1830 list_for_each_entry(res, &resolvers->resolutions.curr, 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 /* Search for same hostname and query type in resolutions.wait */
1840 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1841 if (!res->hostname_dn)
1842 continue;
1843 if ((query_type == res->prefered_query_type) &&
1844 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001845 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001846 return res;
1847 }
1848
1849 from_pool:
1850 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001851 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001852 if (res) {
Willy Tarreau25e01092021-10-19 11:17:33 +02001853 int i;
1854
Emeric Brunc9437992021-02-12 19:42:55 +01001855 res->resolvers = resolvers;
1856 res->uuid = resolution_uuid;
1857 res->status = RSLV_STATUS_NONE;
1858 res->step = RSLV_STEP_NONE;
1859 res->last_valid = now_ms;
1860
1861 LIST_INIT(&res->requesters);
Willy Tarreau25e01092021-10-19 11:17:33 +02001862 LIST_INIT(&res->response.query_list);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001863 res->response.answer_tree = EB_ROOT;
Emeric Brunc9437992021-02-12 19:42:55 +01001864
Willy Tarreau25e01092021-10-19 11:17:33 +02001865 for (i = 0; i < DNS_MAX_QUERY_RECORDS; i++)
1866 LIST_INIT(&res->response_query_records[i].list);
1867
Emeric Brunc9437992021-02-12 19:42:55 +01001868 res->prefered_query_type = query_type;
1869 res->query_type = query_type;
1870 res->hostname_dn = *hostname_dn;
1871 res->hostname_dn_len = hostname_dn_len;
1872
1873 ++resolution_uuid;
1874
1875 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001876 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001877 }
1878 return res;
1879}
1880
Willy Tarreau2acc1602021-10-19 11:16:11 +02001881/* deletes and frees all answer_items from the resolution's answer_list */
1882static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001883{
Willy Tarreau7893ae12021-10-21 07:39:57 +02001884 struct eb32_node *eb32, *eb32_back;
1885 struct resolv_answer_item *item;
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001886
Willy Tarreau7893ae12021-10-21 07:39:57 +02001887 for (eb32 = eb32_first(&resolution->response.answer_tree);
1888 eb32 && (eb32_back = eb32_next(eb32), 1);
1889 eb32 = eb32_back) {
1890 item = eb32_entry(eb32, typeof(*item), link);
1891 eb32_delete(&item->link);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001892 pool_free(resolv_answer_item_pool, item->ar_item);
1893 pool_free(resolv_answer_item_pool, item);
1894 }
1895}
1896
Willy Tarreau25e01092021-10-19 11:17:33 +02001897/* deletes all query_items from the resolution's query_list */
1898static void resolv_purge_resolution_query_items(struct resolv_resolution *resolution)
1899{
1900 struct resolv_query_item *item, *itemback;
1901
1902 list_for_each_entry_safe(item, itemback, &resolution->response.query_list, list)
1903 LIST_DEL_INIT(&item->list);
1904}
1905
Emeric Brunc9437992021-02-12 19:42:55 +01001906/* Releases a resolution from its requester(s) and move it back to the pool */
1907static void resolv_free_resolution(struct resolv_resolution *resolution)
1908{
1909 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001910
1911 /* clean up configuration */
1912 resolv_reset_resolution(resolution);
1913 resolution->hostname_dn = NULL;
1914 resolution->hostname_dn_len = 0;
1915
1916 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02001917 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001918 req->resolution = NULL;
1919 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001920 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau25e01092021-10-19 11:17:33 +02001921 resolv_purge_resolution_query_items(resolution);
1922
Willy Tarreauaae73202021-10-19 22:01:36 +02001923 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001924 pool_free(resolv_resolution_pool, resolution);
1925}
1926
Willy Tarreau239675e2021-10-19 11:59:25 +02001927/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1928 * and makes it owned by this obj_type, with the proposed callback and error
1929 * callback. On success, *req is assigned the allocated requester. Returns
1930 * NULL on allocation failure.
1931 */
1932static struct resolv_requester *
1933resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1934 int (*cb)(struct resolv_requester *, struct dns_counters *),
1935 int (*err_cb)(struct resolv_requester *, int))
1936{
1937 struct resolv_requester *tmp;
1938
1939 if (*req)
1940 return *req;
1941
1942 tmp = pool_alloc(resolv_requester_pool);
1943 if (!tmp)
1944 goto end;
1945
1946 LIST_INIT(&tmp->list);
1947 tmp->owner = owner;
1948 tmp->resolution = NULL;
1949 tmp->requester_cb = cb;
1950 tmp->requester_error_cb = err_cb;
1951 *req = tmp;
1952 end:
1953 return tmp;
1954}
1955
Emeric Brunc9437992021-02-12 19:42:55 +01001956/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001957 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001958 */
1959int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1960{
1961 struct resolv_resolution *res = NULL;
1962 struct resolv_requester *req;
1963 struct resolvers *resolvers;
1964 struct server *srv = NULL;
1965 struct resolv_srvrq *srvrq = NULL;
1966 struct stream *stream = NULL;
1967 char **hostname_dn;
1968 int hostname_dn_len, query_type;
1969
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001970 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001971 switch (requester_type) {
1972 case OBJ_TYPE_SERVER:
1973 srv = (struct server *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001974
1975 if (!requester_locked)
1976 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1977
1978 req = resolv_get_requester(&srv->resolv_requester,
1979 &srv->obj_type,
1980 snr_resolution_cb,
1981 snr_resolution_error_cb);
1982
1983 if (!requester_locked)
1984 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1985
1986 if (!req)
1987 goto err;
1988
Emeric Brunc9437992021-02-12 19:42:55 +01001989 hostname_dn = &srv->hostname_dn;
1990 hostname_dn_len = srv->hostname_dn_len;
1991 resolvers = srv->resolvers;
1992 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1993 ? DNS_RTYPE_A
1994 : DNS_RTYPE_AAAA);
1995 break;
1996
1997 case OBJ_TYPE_SRVRQ:
1998 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001999
2000 req = resolv_get_requester(&srvrq->requester,
2001 &srvrq->obj_type,
2002 snr_resolution_cb,
2003 srvrq_resolution_error_cb);
2004 if (!req)
2005 goto err;
2006
Emeric Brunc9437992021-02-12 19:42:55 +01002007 hostname_dn = &srvrq->hostname_dn;
2008 hostname_dn_len = srvrq->hostname_dn_len;
2009 resolvers = srvrq->resolvers;
2010 query_type = DNS_RTYPE_SRV;
2011 break;
2012
2013 case OBJ_TYPE_STREAM:
2014 stream = (struct stream *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02002015
2016 req = resolv_get_requester(&stream->resolv_ctx.requester,
2017 &stream->obj_type,
2018 act_resolution_cb,
2019 act_resolution_error_cb);
2020 if (!req)
2021 goto err;
2022
Emeric Brunc9437992021-02-12 19:42:55 +01002023 hostname_dn = &stream->resolv_ctx.hostname_dn;
2024 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2025 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2026 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2027 ? DNS_RTYPE_A
2028 : DNS_RTYPE_AAAA);
2029 break;
2030 default:
2031 goto err;
2032 }
2033
2034 /* Get a resolution from the resolvers' wait queue or pool */
2035 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2036 goto err;
2037
Willy Tarreau239675e2021-10-19 11:59:25 +02002038 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002039
Willy Tarreau2b718102021-04-21 07:32:39 +02002040 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002041 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002042 return 0;
2043
2044 err:
2045 if (res && LIST_ISEMPTY(&res->requesters))
2046 resolv_free_resolution(res);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002047 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002048 return -1;
2049}
2050
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002051/* This function removes all server/srvrq references on answer items. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002052void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun34067662021-06-11 10:48:45 +02002053{
Willy Tarreau7893ae12021-10-21 07:39:57 +02002054 struct eb32_node *eb32, *eb32_back;
2055 struct resolv_answer_item *item;
Emeric Brun34067662021-06-11 10:48:45 +02002056 struct server *srv, *srvback;
2057 struct resolv_srvrq *srvrq;
2058
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002059 enter_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002060 if ((srv = objt_server(req->owner)) != NULL) {
2061 LIST_DEL_INIT(&srv->ip_rec_item);
2062 }
2063 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02002064 for (eb32 = eb32_first(&res->response.answer_tree);
2065 eb32 && (eb32_back = eb32_next(eb32), 1);
2066 eb32 = eb32_back) {
2067 item = eb32_entry(eb32, typeof(*item), link);
Emeric Brun34067662021-06-11 10:48:45 +02002068 if (item->type == DNS_RTYPE_SRV) {
2069 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet11c6c392021-06-15 16:08:48 +02002070 if (srv->srvrq == srvrq)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002071 resolv_srvrq_cleanup_srv(srv);
Emeric Brun34067662021-06-11 10:48:45 +02002072 }
2073 }
2074 }
2075 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002076 leave_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002077}
2078
Emeric Brunc9437992021-02-12 19:42:55 +01002079/* Removes a requester from a DNS resolution. It takes takes care of all the
2080 * consequences. It also cleans up some parameters from the requester.
2081 */
Willy Tarreau6878f802021-10-20 14:07:31 +02002082static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002083{
2084 struct resolv_resolution *res;
2085 struct resolv_requester *req;
2086
2087 /* Nothing to do */
2088 if (!requester || !requester->resolution)
2089 return;
2090 res = requester->resolution;
2091
2092 /* Clean up the requester */
Willy Tarreauaae73202021-10-19 22:01:36 +02002093 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002094 requester->resolution = NULL;
2095
Christopher Fauletbce6db62021-10-29 10:38:15 +02002096 /* remove ref from the resolution answer item list to the requester */
2097 resolv_detach_from_resolution_answer_items(res, requester);
2098
Emeric Brunc9437992021-02-12 19:42:55 +01002099 /* We need to find another requester linked on this resolution */
2100 if (!LIST_ISEMPTY(&res->requesters))
2101 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2102 else {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002103 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002104 return;
2105 }
2106
2107 /* Move hostname_dn related pointers to the next requester */
2108 switch (obj_type(req->owner)) {
2109 case OBJ_TYPE_SERVER:
2110 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2111 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2112 break;
2113 case OBJ_TYPE_SRVRQ:
2114 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2115 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2116 break;
2117 case OBJ_TYPE_STREAM:
2118 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2119 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2120 break;
2121 default:
2122 res->hostname_dn = NULL;
2123 res->hostname_dn_len = 0;
2124 break;
2125 }
2126}
2127
Willy Tarreauf766ec62021-10-18 16:46:38 +02002128/* The public version of the function above that deals with the death row. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002129void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002130{
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002131 enter_resolver_code();
Willy Tarreau6878f802021-10-20 14:07:31 +02002132 _resolv_unlink_resolution(requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002133 leave_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002134}
2135
Emeric Brunc9437992021-02-12 19:42:55 +01002136/* Called when a network IO is generated on a name server socket for an incoming
2137 * packet. It performs the following actions:
2138 * - check if the packet requires processing (not outdated resolution)
2139 * - ensure the DNS packet received is valid and call requester's callback
2140 * - call requester's error callback if invalid response
2141 * - check the dn_name in the packet against the one sent
2142 */
2143static int resolv_process_responses(struct dns_nameserver *ns)
2144{
2145 struct dns_counters *tmpcounters;
2146 struct resolvers *resolvers;
2147 struct resolv_resolution *res;
2148 struct resolv_query_item *query;
2149 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2150 unsigned char *bufend;
2151 int buflen, dns_resp;
2152 int max_answer_records;
2153 unsigned short query_id;
2154 struct eb32_node *eb;
2155 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002156 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002157
2158 resolvers = ns->parent;
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002159 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002160 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2161
2162 /* process all pending input messages */
2163 while (1) {
2164 /* read message received */
2165 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2166 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2167 break;
2168 }
2169
2170 /* message too big */
2171 if (buflen > resolvers->accepted_payload_size) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002172 ns->counters->app.resolver.too_big++;
Emeric Brunc9437992021-02-12 19:42:55 +01002173 continue;
2174 }
2175
2176 /* initializing variables */
2177 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2178
2179 /* read the query id from the packet (16 bits) */
2180 if (buf + 2 > bufend) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002181 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002182 continue;
2183 }
2184 query_id = resolv_response_get_query_id(buf);
2185
2186 /* search the query_id in the pending resolution tree */
2187 eb = eb32_lookup(&resolvers->query_ids, query_id);
2188 if (eb == NULL) {
2189 /* unknown query id means an outdated response and can be safely ignored */
Emeric Brund174f0e2021-10-29 17:30:41 +02002190 ns->counters->app.resolver.outdated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002191 continue;
2192 }
2193
2194 /* known query id means a resolution in progress */
2195 res = eb32_entry(eb, struct resolv_resolution, qid);
2196 /* number of responses received */
2197 res->nb_responses++;
2198
2199 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2200 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2201
2202 switch (dns_resp) {
2203 case RSLV_RESP_VALID:
2204 break;
2205
2206 case RSLV_RESP_INVALID:
2207 case RSLV_RESP_QUERY_COUNT_ERROR:
2208 case RSLV_RESP_WRONG_NAME:
2209 res->status = RSLV_STATUS_INVALID;
Emeric Brund174f0e2021-10-29 17:30:41 +02002210 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002211 break;
2212
2213 case RSLV_RESP_NX_DOMAIN:
2214 res->status = RSLV_STATUS_NX;
Emeric Brund174f0e2021-10-29 17:30:41 +02002215 ns->counters->app.resolver.nx++;
Emeric Brunc9437992021-02-12 19:42:55 +01002216 break;
2217
2218 case RSLV_RESP_REFUSED:
2219 res->status = RSLV_STATUS_REFUSED;
Emeric Brund174f0e2021-10-29 17:30:41 +02002220 ns->counters->app.resolver.refused++;
Emeric Brunc9437992021-02-12 19:42:55 +01002221 break;
2222
2223 case RSLV_RESP_ANCOUNT_ZERO:
2224 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002225 ns->counters->app.resolver.any_err++;
Emeric Brunc9437992021-02-12 19:42:55 +01002226 break;
2227
2228 case RSLV_RESP_CNAME_ERROR:
2229 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002230 ns->counters->app.resolver.cname_error++;
Emeric Brunc9437992021-02-12 19:42:55 +01002231 break;
2232
2233 case RSLV_RESP_TRUNCATED:
2234 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002235 ns->counters->app.resolver.truncated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002236 break;
2237
2238 case RSLV_RESP_NO_EXPECTED_RECORD:
2239 case RSLV_RESP_ERROR:
2240 case RSLV_RESP_INTERNAL:
2241 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002242 ns->counters->app.resolver.other++;
Emeric Brunc9437992021-02-12 19:42:55 +01002243 break;
2244 }
2245
2246 /* Wait all nameservers response to handle errors */
2247 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2248 continue;
2249
2250 /* Process error codes */
2251 if (dns_resp != RSLV_RESP_VALID) {
2252 if (res->prefered_query_type != res->query_type) {
2253 /* The fallback on the query type was already performed,
2254 * so check the try counter. If it falls to 0, we can
2255 * report an error. Else, wait the next attempt. */
2256 if (!res->try)
2257 goto report_res_error;
2258 }
2259 else {
2260 /* Fallback from A to AAAA or the opposite and re-send
2261 * the resolution immediately. try counter is not
2262 * decremented. */
2263 if (res->prefered_query_type == DNS_RTYPE_A) {
2264 res->query_type = DNS_RTYPE_AAAA;
2265 resolv_send_query(res);
2266 }
2267 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2268 res->query_type = DNS_RTYPE_A;
2269 resolv_send_query(res);
2270 }
2271 }
2272 continue;
2273 }
2274
2275 /* Now let's check the query's dname corresponds to the one we
2276 * sent. We can check only the first query of the list. We send
Willy Tarreau25e01092021-10-19 11:17:33 +02002277 * one query at a time so we get one query in the response.
2278 */
2279 if (!LIST_ISEMPTY(&res->response.query_list)) {
2280 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
2281 LIST_DEL_INIT(&query->list);
2282 if (memcmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
2283 dns_resp = RSLV_RESP_WRONG_NAME;
Emeric Brund174f0e2021-10-29 17:30:41 +02002284 ns->counters->app.resolver.other++;
Willy Tarreau25e01092021-10-19 11:17:33 +02002285 goto report_res_error;
2286 }
Emeric Brunc9437992021-02-12 19:42:55 +01002287 }
2288
2289 /* So the resolution succeeded */
2290 res->status = RSLV_STATUS_VALID;
2291 res->last_valid = now_ms;
Emeric Brund174f0e2021-10-29 17:30:41 +02002292 ns->counters->app.resolver.valid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002293 goto report_res_success;
2294
2295 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002296 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002297 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002298 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2299 if (!keep_answer_items)
2300 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002301 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002302 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002303 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002304 continue;
2305
2306 report_res_success:
2307 /* Only the 1rst requester s managed by the server, others are
2308 * from the cache */
2309 tmpcounters = ns->counters;
2310 list_for_each_entry(req, &res->requesters, list) {
2311 struct server *s = objt_server(req->owner);
2312
2313 if (s)
2314 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2315 req->requester_cb(req, tmpcounters);
2316 if (s)
2317 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2318 tmpcounters = NULL;
2319 }
2320
2321 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002322 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002323 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002324 continue;
2325 }
2326 resolv_update_resolvers_timeout(resolvers);
2327 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002328 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002329 return buflen;
2330}
2331
2332/* Processes DNS resolution. First, it checks the active list to detect expired
2333 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2334 * checks the wait list to trigger new resolutions.
2335 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002336static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002337{
2338 struct resolvers *resolvers = context;
2339 struct resolv_resolution *res, *resback;
2340 int exp;
2341
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002342 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002343 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2344
Willy Tarreauf766ec62021-10-18 16:46:38 +02002345 /* Handle all expired resolutions from the active list. Elements that
2346 * need to be removed will in fact be moved to the death_row. Other
2347 * ones will be handled normally.
2348 */
2349
Willy Tarreauf766ec62021-10-18 16:46:38 +02002350 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2351 while (&res->list != &resolvers->resolutions.curr) {
2352 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2353
Christopher Faulet0efc0992021-03-11 18:09:53 +01002354 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002355 abort_resolution(res);
2356 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002357 continue;
2358 }
2359
Emeric Brunc9437992021-02-12 19:42:55 +01002360 /* When we find the first resolution in the future, then we can
2361 * stop here */
2362 exp = tick_add(res->last_query, resolvers->timeout.retry);
2363 if (!tick_is_expired(exp, now_ms))
2364 break;
2365
2366 /* If current resolution has been tried too many times and
2367 * finishes in timeout we update its status and remove it from
2368 * the list */
2369 if (!res->try) {
2370 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002371 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002372
2373 /* Notify the result to the requesters */
2374 if (!res->nb_responses)
2375 res->status = RSLV_STATUS_TIMEOUT;
2376 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002377 keep_answer_items |= req->requester_error_cb(req, res->status);
2378 if (!keep_answer_items)
2379 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002380
2381 /* Clean up resolution info and remove it from the
2382 * current list */
2383 resolv_reset_resolution(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002384
2385 /* subsequent entries might have been deleted here */
2386 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
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);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002389 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002390 }
2391 else {
2392 /* Otherwise resend the DNS query and requeue the resolution */
2393 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2394 /* No response received (a real timeout) or fallback already done */
2395 res->query_type = res->prefered_query_type;
2396 res->try--;
2397 }
2398 else {
2399 /* Fallback from A to AAAA or the opposite and re-send
2400 * the resolution immediately. try counter is not
2401 * decremented. */
2402 if (res->prefered_query_type == DNS_RTYPE_A)
2403 res->query_type = DNS_RTYPE_AAAA;
2404 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2405 res->query_type = DNS_RTYPE_A;
2406 else
2407 res->try--;
2408 }
2409 resolv_send_query(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002410 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2411 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002412 }
2413 }
2414
2415 /* Handle all resolutions in the wait list */
2416 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002417 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002418 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002419 continue;
2420 }
2421
Emeric Brunc9437992021-02-12 19:42:55 +01002422 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2423 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2424 continue;
2425
2426 if (resolv_run_resolution(res) != 1) {
2427 res->last_resolution = now_ms;
Willy Tarreauaae73202021-10-19 22:01:36 +02002428 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002429 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002430 }
2431 }
Emeric Brunc9437992021-02-12 19:42:55 +01002432 resolv_update_resolvers_timeout(resolvers);
2433 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002434
2435 /* now we can purge all queued deletions */
2436 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002437 return t;
2438}
2439
2440/* Release memory allocated by DNS */
2441static void resolvers_deinit(void)
2442{
2443 struct resolvers *resolvers, *resolversback;
2444 struct dns_nameserver *ns, *nsback;
2445 struct resolv_resolution *res, *resback;
2446 struct resolv_requester *req, *reqback;
2447 struct resolv_srvrq *srvrq, *srvrqback;
2448
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002449 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002450 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2451 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2452 free(ns->id);
2453 free((char *)ns->conf.file);
2454 if (ns->dgram) {
2455 if (ns->dgram->conn.t.sock.fd != -1) {
2456 fd_delete(ns->dgram->conn.t.sock.fd);
2457 close(ns->dgram->conn.t.sock.fd);
2458 }
2459 if (ns->dgram->ring_req)
2460 ring_free(ns->dgram->ring_req);
2461 free(ns->dgram);
2462 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002463 if (ns->stream) {
2464 if (ns->stream->ring_req)
2465 ring_free(ns->stream->ring_req);
2466 if (ns->stream->task_req)
2467 task_destroy(ns->stream->task_req);
2468 if (ns->stream->task_rsp)
2469 task_destroy(ns->stream->task_rsp);
2470 free(ns->stream);
2471 }
Willy Tarreauaae73202021-10-19 22:01:36 +02002472 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002473 EXTRA_COUNTERS_FREE(ns->extra_counters);
2474 free(ns);
2475 }
2476
2477 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2478 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002479 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002480 pool_free(resolv_requester_pool, req);
2481 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002482 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002483 }
2484
2485 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2486 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002487 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002488 pool_free(resolv_requester_pool, req);
2489 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002490 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002491 }
2492
2493 free(resolvers->id);
2494 free((char *)resolvers->conf.file);
2495 task_destroy(resolvers->t);
Willy Tarreauaae73202021-10-19 22:01:36 +02002496 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002497 free(resolvers);
2498 }
2499
2500 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2501 free(srvrq->name);
2502 free(srvrq->hostname_dn);
Willy Tarreauaae73202021-10-19 22:01:36 +02002503 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002504 free(srvrq);
2505 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002506
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002507 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002508}
2509
2510/* Finalizes the DNS configuration by allocating required resources and checking
2511 * live parameters.
2512 * Returns 0 on success, ERR_* flags otherwise.
2513 */
2514static int resolvers_finalize_config(void)
2515{
2516 struct resolvers *resolvers;
2517 struct proxy *px;
2518 int err_code = 0;
2519
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002520 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002521
Emeric Brunc9437992021-02-12 19:42:55 +01002522 /* allocate pool of resolution per resolvers */
2523 list_for_each_entry(resolvers, &sec_resolvers, list) {
2524 struct dns_nameserver *ns;
2525 struct task *t;
2526
2527 /* Check if we can create the socket with nameservers info */
2528 list_for_each_entry(ns, &resolvers->nameservers, list) {
2529 int fd;
2530
2531 if (ns->dgram) {
2532 /* Check nameserver info */
2533 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002534 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002535 resolvers->id, ns->id);
2536 err_code |= (ERR_ALERT|ERR_ABORT);
2537 continue;
2538 }
2539 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 +02002540 ha_alert("resolvers '%s': can't connect socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002541 resolvers->id, ns->id);
2542 close(fd);
2543 err_code |= (ERR_ALERT|ERR_ABORT);
2544 continue;
2545 }
2546 close(fd);
2547 }
2548 }
2549
2550 /* Create the task associated to the resolvers section */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002551 if ((t = task_new_anywhere()) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002552 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002553 err_code |= (ERR_ALERT|ERR_ABORT);
2554 goto err;
2555 }
2556
2557 /* Update task's parameters */
2558 t->process = process_resolvers;
2559 t->context = resolvers;
2560 resolvers->t = t;
2561 task_wakeup(t, TASK_WOKEN_INIT);
2562 }
2563
2564 for (px = proxies_list; px; px = px->next) {
2565 struct server *srv;
2566
2567 for (srv = px->srv; srv; srv = srv->next) {
2568 struct resolvers *resolvers;
2569
2570 if (!srv->resolvers_id)
2571 continue;
2572
2573 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002574 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002575 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2576 err_code |= (ERR_ALERT|ERR_ABORT);
2577 continue;
2578 }
2579 srv->resolvers = resolvers;
Christopher Fauletdcac4182021-06-15 16:17:17 +02002580 srv->srvrq_check = NULL;
2581 if (srv->srvrq) {
2582 if (!srv->srvrq->resolvers) {
2583 srv->srvrq->resolvers = srv->resolvers;
2584 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2585 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
2586 proxy_type_str(px), px->id, srv->id);
2587 err_code |= (ERR_ALERT|ERR_ABORT);
2588 continue;
2589 }
2590 }
Emeric Brunc9437992021-02-12 19:42:55 +01002591
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002592 srv->srvrq_check = task_new_anywhere();
Christopher Fauletdcac4182021-06-15 16:17:17 +02002593 if (!srv->srvrq_check) {
2594 ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002595 proxy_type_str(px), px->id, srv->id);
2596 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Fauletdcac4182021-06-15 16:17:17 +02002597 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002598 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002599 srv->srvrq_check->process = resolv_srvrq_expire_task;
2600 srv->srvrq_check->context = srv;
2601 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002602 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002603 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002604 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002605 proxy_type_str(px), px->id, srv->id);
2606 err_code |= (ERR_ALERT|ERR_ABORT);
2607 continue;
2608 }
Amaury Denoyelledd565202021-08-26 15:35:59 +02002609
2610 srv->flags |= SRV_F_NON_PURGEABLE;
Emeric Brunc9437992021-02-12 19:42:55 +01002611 }
2612 }
2613
2614 if (err_code & (ERR_ALERT|ERR_ABORT))
2615 goto err;
2616
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002617 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002618 return err_code;
2619 err:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002620 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002621 resolvers_deinit();
2622 return err_code;
2623
2624}
2625
2626static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2627 struct dns_nameserver *ns,
2628 struct field *stats, size_t stats_count,
2629 struct list *stat_modules)
2630{
2631 struct appctx *appctx = __objt_appctx(si->end);
2632 struct channel *rep = si_ic(si);
2633 struct stats_module *mod;
2634 size_t idx = 0;
2635
2636 memset(stats, 0, sizeof(struct field) * stats_count);
2637
2638 list_for_each_entry(mod, stat_modules, list) {
2639 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2640
2641 mod->fill_stats(counters, stats + idx);
2642 idx += mod->stats_count;
2643 }
2644
2645 if (!stats_dump_one_line(stats, idx, appctx))
2646 return 0;
2647
2648 if (!stats_putchk(rep, NULL, &trash))
2649 goto full;
2650
2651 return 1;
2652
2653 full:
2654 si_rx_room_rdy(si);
2655 return 0;
2656}
2657
2658/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2659 * as a pointer to the current nameserver.
2660 */
2661int stats_dump_resolvers(struct stream_interface *si,
2662 struct field *stats, size_t stats_count,
2663 struct list *stat_modules)
2664{
2665 struct appctx *appctx = __objt_appctx(si->end);
2666 struct channel *rep = si_ic(si);
2667 struct resolvers *resolver = appctx->ctx.stats.obj1;
2668 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2669
2670 if (!resolver)
2671 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2672
2673 /* dump resolvers */
2674 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2675 appctx->ctx.stats.obj1 = resolver;
2676
2677 ns = appctx->ctx.stats.obj2 ?
2678 appctx->ctx.stats.obj2 :
2679 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2680
2681 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2682 appctx->ctx.stats.obj2 = ns;
2683
2684 if (buffer_almost_full(&rep->buf))
2685 goto full;
2686
2687 if (!stats_dump_resolv_to_buffer(si, ns,
2688 stats, stats_count,
2689 stat_modules)) {
2690 return 0;
2691 }
2692 }
2693
2694 appctx->ctx.stats.obj2 = NULL;
2695 }
2696
2697 return 1;
2698
2699 full:
2700 si_rx_room_blk(si);
2701 return 0;
2702}
2703
2704void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2705{
2706 struct resolvers *resolvers;
2707 struct dns_nameserver *ns;
2708 struct stats_module *mod;
2709 void *counters;
2710
2711 list_for_each_entry(mod, stat_modules, list) {
2712 if (!mod->clearable && !clrall)
2713 continue;
2714
2715 list_for_each_entry(resolvers, &sec_resolvers, list) {
2716 list_for_each_entry(ns, &resolvers->nameservers, list) {
2717 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2718 memcpy(counters, mod->counters, mod->counters_size);
2719 }
2720 }
2721 }
2722
2723}
2724
2725int resolv_allocate_counters(struct list *stat_modules)
2726{
2727 struct stats_module *mod;
2728 struct resolvers *resolvers;
2729 struct dns_nameserver *ns;
2730
2731 list_for_each_entry(resolvers, &sec_resolvers, list) {
2732 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunf8642ee2021-10-29 17:59:18 +02002733 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
Emeric Brunc9437992021-02-12 19:42:55 +01002734 alloc_failed);
2735
2736 list_for_each_entry(mod, stat_modules, list) {
2737 EXTRA_COUNTERS_ADD(mod,
2738 ns->extra_counters,
2739 mod->counters,
2740 mod->counters_size);
2741 }
2742
2743 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2744
2745 list_for_each_entry(mod, stat_modules, list) {
2746 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2747 mod->counters, mod->counters_size);
2748
2749 /* Store the ns counters pointer */
Emeric Brunf8642ee2021-10-29 17:59:18 +02002750 if (strcmp(mod->name, "resolvers") == 0) {
2751 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
Emeric Brunc9437992021-02-12 19:42:55 +01002752 ns->counters->id = ns->id;
2753 ns->counters->pid = resolvers->id;
2754 }
2755 }
2756 }
2757 }
2758
2759 return 1;
2760
2761alloc_failed:
2762 return 0;
2763}
2764
2765/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2766static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2767{
2768 struct resolvers *presolvers;
2769
2770 if (*args[2]) {
2771 list_for_each_entry(presolvers, &sec_resolvers, list) {
2772 if (strcmp(presolvers->id, args[2]) == 0) {
2773 appctx->ctx.cli.p0 = presolvers;
2774 break;
2775 }
2776 }
2777 if (appctx->ctx.cli.p0 == NULL)
2778 return cli_err(appctx, "Can't find that resolvers section\n");
2779 }
2780 return 0;
2781}
2782
2783/* Dumps counters from all resolvers section and associated name servers. It
2784 * returns 0 if the output buffer is full and it needs to be called again,
2785 * otherwise non-zero. It may limit itself to the resolver pointed to by
2786 * <cli.p0> if it's not null.
2787 */
2788static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2789{
2790 struct stream_interface *si = appctx->owner;
2791 struct resolvers *resolvers;
2792 struct dns_nameserver *ns;
2793
2794 chunk_reset(&trash);
2795
2796 switch (appctx->st2) {
2797 case STAT_ST_INIT:
2798 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2799 /* fall through */
2800
2801 case STAT_ST_LIST:
2802 if (LIST_ISEMPTY(&sec_resolvers)) {
2803 chunk_appendf(&trash, "No resolvers found\n");
2804 }
2805 else {
2806 list_for_each_entry(resolvers, &sec_resolvers, list) {
2807 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2808 continue;
2809
2810 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2811 list_for_each_entry(ns, &resolvers->nameservers, list) {
2812 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2813 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2814 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
Emeric Brund174f0e2021-10-29 17:30:41 +02002815 chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
2816 chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
2817 chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
2818 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
2819 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
2820 chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
2821 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
2822 chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
2823 chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
2824 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
2825 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
2826 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
2827 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +01002828 }
2829 chunk_appendf(&trash, "\n");
2830 }
2831 }
2832
2833 /* display response */
2834 if (ci_putchk(si_ic(si), &trash) == -1) {
2835 /* let's try again later from this session. We add ourselves into
2836 * this session's users so that it can remove us upon termination.
2837 */
2838 si_rx_room_blk(si);
2839 return 0;
2840 }
2841 /* fall through */
2842
2843 default:
2844 appctx->st2 = STAT_ST_FIN;
2845 return 1;
2846 }
2847}
2848
2849/* register cli keywords */
2850static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002851 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002852 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2853 {{},}
2854 }
2855};
2856
2857INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2858
2859/*
2860 * Prepare <rule> for hostname resolution.
2861 * Returns -1 in case of any allocation failure, 0 if not.
2862 * On error, a global failure counter is also incremented.
2863 */
Willy Tarreau947ae122021-10-14 08:11:48 +02002864static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002865{
2866 char *hostname_dn;
Willy Tarreau947ae122021-10-14 08:11:48 +02002867 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002868 struct buffer *tmp = get_trash_chunk();
2869
2870 if (!hostname)
2871 return 0;
2872
Emeric Brunc9437992021-02-12 19:42:55 +01002873 hostname_dn = tmp->area;
Willy Tarreaubf9498a2021-10-14 07:49:49 +02002874 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002875 hostname_dn, tmp->size);
2876 if (hostname_dn_len == -1)
2877 goto err;
2878
2879
2880 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2881 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2882 if (!stream->resolv_ctx.hostname_dn)
2883 goto err;
2884
2885 return 0;
2886
2887 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002888 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002889 resolv_failed_resolutions += 1;
2890 return -1;
2891}
2892
2893
2894/*
2895 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2896 */
2897enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2898 struct session *sess, struct stream *s, int flags)
2899{
2900 struct resolv_resolution *resolution;
2901 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002902 struct resolv_requester *req;
2903 struct resolvers *resolvers;
2904 struct resolv_resolution *res;
2905 int exp, locked = 0;
2906 enum act_return ret = ACT_RET_CONT;
2907
2908 resolvers = rule->arg.resolv.resolvers;
2909
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002910 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002911
Emeric Brunc9437992021-02-12 19:42:55 +01002912 /* we have a response to our DNS resolution */
2913 use_cache:
2914 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2915 resolution = s->resolv_ctx.requester->resolution;
2916 if (!locked) {
2917 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2918 locked = 1;
2919 }
2920
2921 if (resolution->step == RSLV_STEP_RUNNING)
2922 goto yield;
2923 if (resolution->step == RSLV_STEP_NONE) {
2924 /* We update the variable only if we have a valid response. */
2925 if (resolution->status == RSLV_STATUS_VALID) {
2926 struct sample smp;
2927 short ip_sin_family = 0;
2928 void *ip = NULL;
2929
2930 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2931 0, &ip, &ip_sin_family, NULL);
2932
2933 switch (ip_sin_family) {
2934 case AF_INET:
2935 smp.data.type = SMP_T_IPV4;
2936 memcpy(&smp.data.u.ipv4, ip, 4);
2937 break;
2938 case AF_INET6:
2939 smp.data.type = SMP_T_IPV6;
2940 memcpy(&smp.data.u.ipv6, ip, 16);
2941 break;
2942 default:
2943 ip = NULL;
2944 }
2945
2946 if (ip) {
2947 smp.px = px;
2948 smp.sess = sess;
2949 smp.strm = s;
2950
2951 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2952 }
2953 }
2954 }
2955
2956 goto release_requester;
2957 }
2958
2959 /* need to configure and start a new DNS resolution */
2960 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2961 if (smp == NULL)
2962 goto end;
2963
Willy Tarreau947ae122021-10-14 08:11:48 +02002964 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002965 goto end; /* on error, ignore the action */
2966
2967 s->resolv_ctx.parent = rule;
2968
2969 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2970 locked = 1;
2971
2972 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2973
2974 /* Check if there is a fresh enough response in the cache of our associated resolution */
2975 req = s->resolv_ctx.requester;
2976 if (!req || !req->resolution)
2977 goto release_requester; /* on error, ignore the action */
2978 res = req->resolution;
2979
2980 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2981 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2982 && !tick_is_expired(exp, now_ms)) {
2983 goto use_cache;
2984 }
2985
2986 resolv_trigger_resolution(s->resolv_ctx.requester);
2987
2988 yield:
2989 if (flags & ACT_OPT_FINAL)
2990 goto release_requester;
2991 ret = ACT_RET_YIELD;
2992
2993 end:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002994 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002995 if (locked)
2996 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2997 return ret;
2998
2999 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003000 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01003001 s->resolv_ctx.hostname_dn_len = 0;
3002 if (s->resolv_ctx.requester) {
Willy Tarreau6878f802021-10-20 14:07:31 +02003003 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01003004 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
3005 s->resolv_ctx.requester = NULL;
3006 }
3007 goto end;
3008}
3009
3010static void release_resolv_action(struct act_rule *rule)
3011{
3012 release_sample_expr(rule->arg.resolv.expr);
3013 free(rule->arg.resolv.varname);
3014 free(rule->arg.resolv.resolvers_id);
3015 free(rule->arg.resolv.opts);
3016}
3017
3018
3019/* parse "do-resolve" action
3020 * This action takes the following arguments:
3021 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3022 *
3023 * - <varName> is the variable name where the result of the DNS resolution will be stored
3024 * (mandatory)
3025 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3026 * (mandatory)
3027 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3028 * (optional), defaults to ipv6
3029 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3030 */
3031enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3032{
3033 int cur_arg;
3034 struct sample_expr *expr;
3035 unsigned int where;
3036 const char *beg, *end;
3037
3038 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3039 cur_arg = *orig_arg - 1;
3040
3041 /* locate varName, which is mandatory */
3042 beg = strchr(args[cur_arg], '(');
3043 if (beg == NULL)
3044 goto do_resolve_parse_error;
3045 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3046 end = strchr(beg, ',');
3047 if (end == NULL)
3048 goto do_resolve_parse_error;
3049 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3050 if (rule->arg.resolv.varname == NULL)
3051 goto do_resolve_parse_error;
3052
3053
3054 /* locate resolversSectionName, which is mandatory.
3055 * Since next parameters are optional, the delimiter may be comma ','
3056 * or closing parenthesis ')'
3057 */
3058 beg = end + 1;
3059 end = strchr(beg, ',');
3060 if (end == NULL)
3061 end = strchr(beg, ')');
3062 if (end == NULL)
3063 goto do_resolve_parse_error;
3064 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3065 if (rule->arg.resolv.resolvers_id == NULL)
3066 goto do_resolve_parse_error;
3067
3068
3069 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3070 if (rule->arg.resolv.opts == NULL)
3071 goto do_resolve_parse_error;
3072
3073 /* Default priority is ipv6 */
3074 rule->arg.resolv.opts->family_prio = AF_INET6;
3075
3076 /* optional arguments accepted for now:
3077 * ipv4 or ipv6
3078 */
3079 while (*end != ')') {
3080 beg = end + 1;
3081 end = strchr(beg, ',');
3082 if (end == NULL)
3083 end = strchr(beg, ')');
3084 if (end == NULL)
3085 goto do_resolve_parse_error;
3086
3087 if (strncmp(beg, "ipv4", end - beg) == 0) {
3088 rule->arg.resolv.opts->family_prio = AF_INET;
3089 }
3090 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3091 rule->arg.resolv.opts->family_prio = AF_INET6;
3092 }
3093 else {
3094 goto do_resolve_parse_error;
3095 }
3096 }
3097
3098 cur_arg = cur_arg + 1;
3099
3100 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3101 if (!expr)
3102 goto do_resolve_parse_error;
3103
3104
3105 where = 0;
3106 if (px->cap & PR_CAP_FE)
3107 where |= SMP_VAL_FE_HRQ_HDR;
3108 if (px->cap & PR_CAP_BE)
3109 where |= SMP_VAL_BE_HRQ_HDR;
3110
3111 if (!(expr->fetch->val & where)) {
3112 memprintf(err,
3113 "fetch method '%s' extracts information from '%s', none of which is available here",
3114 args[cur_arg-1], sample_src_names(expr->fetch->use));
3115 free(expr);
3116 return ACT_RET_PRS_ERR;
3117 }
3118 rule->arg.resolv.expr = expr;
3119 rule->action = ACT_CUSTOM;
3120 rule->action_ptr = resolv_action_do_resolve;
3121 *orig_arg = cur_arg;
3122
3123 rule->check_ptr = check_action_do_resolve;
3124 rule->release_ptr = release_resolv_action;
3125
3126 return ACT_RET_PRS_OK;
3127
3128 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003129 ha_free(&rule->arg.resolv.varname);
3130 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003131 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3132 args[cur_arg]);
3133 return ACT_RET_PRS_ERR;
3134}
3135
3136static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003137 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003138 { /* END */ }
3139}};
3140
3141INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3142
3143static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003144 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003145 { /* END */ }
3146}};
3147
3148INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3149
3150/* Check an "http-request do-resolve" action.
3151 *
3152 * The function returns 1 in success case, otherwise, it returns 0 and err is
3153 * filled.
3154 */
3155int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3156{
3157 struct resolvers *resolvers = NULL;
3158
3159 if (rule->arg.resolv.resolvers_id == NULL) {
3160 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3161 return 0;
3162 }
3163
3164 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3165 if (resolvers == NULL) {
3166 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3167 return 0;
3168 }
3169 rule->arg.resolv.resolvers = resolvers;
3170
3171 return 1;
3172}
3173
3174void resolvers_setup_proxy(struct proxy *px)
3175{
3176 px->last_change = now.tv_sec;
3177 px->cap = PR_CAP_FE | PR_CAP_BE;
3178 px->maxconn = 0;
3179 px->conn_retries = 1;
3180 px->timeout.server = TICK_ETERNITY;
3181 px->timeout.client = TICK_ETERNITY;
3182 px->timeout.connect = TICK_ETERNITY;
3183 px->accept = NULL;
3184 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
Emeric Brunc9437992021-02-12 19:42:55 +01003185}
3186
3187/*
3188 * Parse a <resolvers> section.
3189 * Returns the error code, 0 if OK, or any combination of :
3190 * - ERR_ABORT: must abort ASAP
3191 * - ERR_FATAL: we can continue parsing but not start the service
3192 * - ERR_WARN: a warning has been emitted
3193 * - ERR_ALERT: an alert has been emitted
3194 * Only the two first ones can stop processing, the two others are just
3195 * indicators.
3196 */
3197int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3198{
3199 const char *err;
3200 int err_code = 0;
3201 char *errmsg = NULL;
3202 struct proxy *p;
3203
3204 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3205 if (!*args[1]) {
3206 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3207 err_code |= ERR_ALERT | ERR_ABORT;
3208 goto out;
3209 }
3210
3211 err = invalid_char(args[1]);
3212 if (err) {
3213 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3214 file, linenum, *err, args[0], args[1]);
3215 err_code |= ERR_ALERT | ERR_ABORT;
3216 goto out;
3217 }
3218
3219 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3220 /* Error if two resolvers owns the same name */
3221 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3222 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3223 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3224 err_code |= ERR_ALERT | ERR_ABORT;
3225 }
3226 }
3227
3228 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3229 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3230 err_code |= ERR_ALERT | ERR_ABORT;
3231 goto out;
3232 }
3233
3234 /* allocate new proxy to tcp servers */
3235 p = calloc(1, sizeof *p);
3236 if (!p) {
3237 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3238 err_code |= ERR_ALERT | ERR_FATAL;
3239 goto out;
3240 }
3241
3242 init_new_proxy(p);
3243 resolvers_setup_proxy(p);
3244 p->parent = curr_resolvers;
3245 p->id = strdup(args[1]);
3246 p->conf.args.file = p->conf.file = strdup(file);
3247 p->conf.args.line = p->conf.line = linenum;
3248 curr_resolvers->px = p;
3249
3250 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003251 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003252 curr_resolvers->conf.file = strdup(file);
3253 curr_resolvers->conf.line = linenum;
3254 curr_resolvers->id = strdup(args[1]);
3255 curr_resolvers->query_ids = EB_ROOT;
3256 /* default maximum response size */
3257 curr_resolvers->accepted_payload_size = 512;
3258 /* default hold period for nx, other, refuse and timeout is 30s */
3259 curr_resolvers->hold.nx = 30000;
3260 curr_resolvers->hold.other = 30000;
3261 curr_resolvers->hold.refused = 30000;
3262 curr_resolvers->hold.timeout = 30000;
3263 curr_resolvers->hold.obsolete = 0;
3264 /* default hold period for valid is 10s */
3265 curr_resolvers->hold.valid = 10000;
3266 curr_resolvers->timeout.resolve = 1000;
3267 curr_resolvers->timeout.retry = 1000;
3268 curr_resolvers->resolve_retries = 3;
3269 LIST_INIT(&curr_resolvers->nameservers);
3270 LIST_INIT(&curr_resolvers->resolutions.curr);
3271 LIST_INIT(&curr_resolvers->resolutions.wait);
3272 HA_SPIN_INIT(&curr_resolvers->lock);
3273 }
3274 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3275 struct dns_nameserver *newnameserver = NULL;
3276 struct sockaddr_storage *sk;
3277 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003278 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003279
3280 if (!*args[2]) {
3281 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3282 file, linenum, args[0]);
3283 err_code |= ERR_ALERT | ERR_FATAL;
3284 goto out;
3285 }
3286
3287 err = invalid_char(args[1]);
3288 if (err) {
3289 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3290 file, linenum, *err, args[1]);
3291 err_code |= ERR_ALERT | ERR_FATAL;
3292 goto out;
3293 }
3294
3295 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3296 /* Error if two resolvers owns the same name */
3297 if (strcmp(newnameserver->id, args[1]) == 0) {
3298 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3299 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3300 err_code |= ERR_ALERT | ERR_FATAL;
3301 }
3302 }
3303
Emeric Brunc8f3e452021-04-07 16:04:54 +02003304 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3305 &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 +01003306 if (!sk) {
3307 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3308 err_code |= ERR_ALERT | ERR_FATAL;
3309 goto out;
3310 }
3311
3312 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3313 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3314 err_code |= ERR_ALERT | ERR_ABORT;
3315 goto out;
3316 }
3317
Emeric Brunc8f3e452021-04-07 16:04:54 +02003318 if (proto && proto->ctrl_type == SOCK_STREAM) {
3319 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3320 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3321 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3322 err_code |= ERR_ABORT;
3323 goto out;
3324 }
3325
3326 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3327 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3328 err_code |= ERR_ALERT|ERR_ABORT;
3329 goto out;
3330 }
3331 }
3332 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003333 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3334 err_code |= ERR_ALERT | ERR_ABORT;
3335 goto out;
3336 }
3337
3338 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3339 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3340 err_code |= ERR_ALERT | ERR_ABORT;
3341 goto out;
3342 }
3343
3344 if ((newnameserver->id = strdup(args[1])) == NULL) {
3345 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3346 err_code |= ERR_ALERT | ERR_ABORT;
3347 goto out;
3348 }
3349
3350 newnameserver->parent = curr_resolvers;
3351 newnameserver->process_responses = resolv_process_responses;
3352 newnameserver->conf.line = linenum;
3353 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003354 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003355 }
3356 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3357 struct dns_nameserver *newnameserver = NULL;
3358 const char *whitespace = "\r\n\t ";
3359 char *resolv_line = NULL;
3360 int resolv_linenum = 0;
3361 FILE *f = NULL;
3362 char *address = NULL;
3363 struct sockaddr_storage *sk = NULL;
3364 struct protocol *proto;
3365 int duplicate_name = 0;
3366
3367 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3368 ha_alert("parsing [%s:%d] : out of memory.\n",
3369 file, linenum);
3370 err_code |= ERR_ALERT | ERR_FATAL;
3371 goto resolv_out;
3372 }
3373
3374 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3375 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3376 file, linenum);
3377 err_code |= ERR_ALERT | ERR_FATAL;
3378 goto resolv_out;
3379 }
3380
3381 sk = calloc(1, sizeof(*sk));
3382 if (sk == NULL) {
3383 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3384 resolv_linenum);
3385 err_code |= ERR_ALERT | ERR_FATAL;
3386 goto resolv_out;
3387 }
3388
3389 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3390 resolv_linenum++;
3391 if (strncmp(resolv_line, "nameserver", 10) != 0)
3392 continue;
3393
3394 address = strtok(resolv_line + 10, whitespace);
3395 if (address == resolv_line + 10)
3396 continue;
3397
3398 if (address == NULL) {
3399 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3400 resolv_linenum);
3401 err_code |= ERR_WARN;
3402 continue;
3403 }
3404
3405 duplicate_name = 0;
3406 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3407 if (strcmp(newnameserver->id, address) == 0) {
3408 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",
3409 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3410 err_code |= ERR_WARN;
3411 duplicate_name = 1;
3412 }
3413 }
3414
3415 if (duplicate_name)
3416 continue;
3417
3418 memset(sk, 0, sizeof(*sk));
3419 if (!str2ip2(address, sk, 1)) {
3420 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3421 resolv_linenum, address);
3422 err_code |= ERR_WARN;
3423 continue;
3424 }
3425
3426 set_host_port(sk, 53);
3427
Willy Tarreau14e7f292021-10-27 17:41:07 +02003428 proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01003429 if (!proto || !proto->connect) {
3430 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3431 resolv_linenum, address);
3432 err_code |= ERR_WARN;
3433 continue;
3434 }
3435
3436 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3437 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3438 err_code |= ERR_ALERT | ERR_FATAL;
3439 goto resolv_out;
3440 }
3441
3442 if (dns_dgram_init(newnameserver, sk) < 0) {
3443 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3444 err_code |= ERR_ALERT | ERR_FATAL;
3445 free(newnameserver);
3446 goto resolv_out;
3447 }
3448
3449 newnameserver->conf.file = strdup("/etc/resolv.conf");
3450 if (newnameserver->conf.file == NULL) {
3451 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3452 err_code |= ERR_ALERT | ERR_FATAL;
3453 free(newnameserver);
3454 goto resolv_out;
3455 }
3456
3457 newnameserver->id = strdup(address);
3458 if (newnameserver->id == NULL) {
3459 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3460 err_code |= ERR_ALERT | ERR_FATAL;
3461 free((char *)newnameserver->conf.file);
3462 free(newnameserver);
3463 goto resolv_out;
3464 }
3465
3466 newnameserver->parent = curr_resolvers;
3467 newnameserver->process_responses = resolv_process_responses;
3468 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003469 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003470 }
3471
3472resolv_out:
3473 free(sk);
3474 free(resolv_line);
3475 if (f != NULL)
3476 fclose(f);
3477 }
3478 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3479 const char *res;
3480 unsigned int time;
3481
3482 if (!*args[2]) {
3483 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3484 file, linenum, args[0]);
3485 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3486 err_code |= ERR_ALERT | ERR_FATAL;
3487 goto out;
3488 }
3489 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3490 if (res == PARSE_TIME_OVER) {
3491 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3492 file, linenum, args[1], args[0]);
3493 err_code |= ERR_ALERT | ERR_FATAL;
3494 goto out;
3495 }
3496 else if (res == PARSE_TIME_UNDER) {
3497 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3498 file, linenum, args[1], args[0]);
3499 err_code |= ERR_ALERT | ERR_FATAL;
3500 goto out;
3501 }
3502 else if (res) {
3503 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3504 file, linenum, *res, args[0]);
3505 err_code |= ERR_ALERT | ERR_FATAL;
3506 goto out;
3507 }
3508 if (strcmp(args[1], "nx") == 0)
3509 curr_resolvers->hold.nx = time;
3510 else if (strcmp(args[1], "other") == 0)
3511 curr_resolvers->hold.other = time;
3512 else if (strcmp(args[1], "refused") == 0)
3513 curr_resolvers->hold.refused = time;
3514 else if (strcmp(args[1], "timeout") == 0)
3515 curr_resolvers->hold.timeout = time;
3516 else if (strcmp(args[1], "valid") == 0)
3517 curr_resolvers->hold.valid = time;
3518 else if (strcmp(args[1], "obsolete") == 0)
3519 curr_resolvers->hold.obsolete = time;
3520 else {
3521 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3522 file, linenum, args[0], args[1]);
3523 err_code |= ERR_ALERT | ERR_FATAL;
3524 goto out;
3525 }
3526
3527 }
3528 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3529 int i = 0;
3530
3531 if (!*args[1]) {
3532 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3533 file, linenum, args[0]);
3534 err_code |= ERR_ALERT | ERR_FATAL;
3535 goto out;
3536 }
3537
3538 i = atoi(args[1]);
3539 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3540 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3541 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3542 err_code |= ERR_ALERT | ERR_FATAL;
3543 goto out;
3544 }
3545
3546 curr_resolvers->accepted_payload_size = i;
3547 }
3548 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3549 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3550 file, linenum, args[0]);
3551 err_code |= ERR_ALERT | ERR_FATAL;
3552 goto out;
3553 }
3554 else if (strcmp(args[0], "resolve_retries") == 0) {
3555 if (!*args[1]) {
3556 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3557 file, linenum, args[0]);
3558 err_code |= ERR_ALERT | ERR_FATAL;
3559 goto out;
3560 }
3561 curr_resolvers->resolve_retries = atoi(args[1]);
3562 }
3563 else if (strcmp(args[0], "timeout") == 0) {
3564 if (!*args[1]) {
3565 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3566 file, linenum, args[0]);
3567 err_code |= ERR_ALERT | ERR_FATAL;
3568 goto out;
3569 }
3570 else if (strcmp(args[1], "retry") == 0 ||
3571 strcmp(args[1], "resolve") == 0) {
3572 const char *res;
3573 unsigned int tout;
3574
3575 if (!*args[2]) {
3576 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3577 file, linenum, args[0], args[1]);
3578 err_code |= ERR_ALERT | ERR_FATAL;
3579 goto out;
3580 }
3581 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3582 if (res == PARSE_TIME_OVER) {
3583 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3584 file, linenum, args[2], args[0], args[1]);
3585 err_code |= ERR_ALERT | ERR_FATAL;
3586 goto out;
3587 }
3588 else if (res == PARSE_TIME_UNDER) {
3589 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3590 file, linenum, args[2], args[0], args[1]);
3591 err_code |= ERR_ALERT | ERR_FATAL;
3592 goto out;
3593 }
3594 else if (res) {
3595 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3596 file, linenum, *res, args[0], args[1]);
3597 err_code |= ERR_ALERT | ERR_FATAL;
3598 goto out;
3599 }
3600 if (args[1][2] == 't')
3601 curr_resolvers->timeout.retry = tout;
3602 else
3603 curr_resolvers->timeout.resolve = tout;
3604 }
3605 else {
3606 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3607 file, linenum, args[0], args[1]);
3608 err_code |= ERR_ALERT | ERR_FATAL;
3609 goto out;
3610 }
3611 }
3612 else if (*args[0] != 0) {
3613 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3614 err_code |= ERR_ALERT | ERR_FATAL;
3615 goto out;
3616 }
3617
3618 out:
3619 free(errmsg);
3620 return err_code;
3621}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003622int cfg_post_parse_resolvers()
3623{
3624 int err_code = 0;
3625 struct server *srv;
3626
3627 if (curr_resolvers) {
3628
3629 /* prepare forward server descriptors */
3630 if (curr_resolvers->px) {
3631 srv = curr_resolvers->px->srv;
3632 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003633 /* init ssl if needed */
3634 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3635 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3636 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3637 err_code |= ERR_ALERT | ERR_FATAL;
3638 break;
3639 }
3640 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003641 srv = srv->next;
3642 }
3643 }
3644 }
3645 curr_resolvers = NULL;
3646 return err_code;
3647}
Emeric Brunc9437992021-02-12 19:42:55 +01003648
Emeric Brun56fc5d92021-02-12 20:05:45 +01003649REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003650REGISTER_POST_DEINIT(resolvers_deinit);
3651REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);