blob: f06618244156729fe3f9d3b119ce4e3f3ffb9b44 [file] [log] [blame]
Emeric Brunc9437992021-02-12 19:42:55 +01001/*
2 * Name server resolution
3 *
4 * Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
14#include <fcntl.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19
20#include <sys/types.h>
21
Emeric Brun34067662021-06-11 10:48:45 +020022#include <import/ebistree.h>
23
Emeric Brunc9437992021-02-12 19:42:55 +010024#include <haproxy/action.h>
25#include <haproxy/api.h>
26#include <haproxy/cfgparse.h>
27#include <haproxy/channel.h>
28#include <haproxy/check.h>
29#include <haproxy/cli.h>
Christopher Faulet908628c2022-03-25 16:43:49 +010030#include <haproxy/conn_stream.h>
31#include <haproxy/cs_utils.h>
Emeric Brunc9437992021-02-12 19:42:55 +010032#include <haproxy/dns.h>
33#include <haproxy/errors.h>
34#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010035#include <haproxy/http_rules.h>
36#include <haproxy/log.h>
37#include <haproxy/net_helper.h>
38#include <haproxy/protocol.h>
39#include <haproxy/proxy.h>
40#include <haproxy/resolvers.h>
41#include <haproxy/ring.h>
42#include <haproxy/sample.h>
43#include <haproxy/server.h>
44#include <haproxy/stats.h>
45#include <haproxy/stream_interface.h>
46#include <haproxy/task.h>
47#include <haproxy/tcp_rules.h>
48#include <haproxy/ticks.h>
49#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020050#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010051#include <haproxy/vars.h>
Willy Tarreaudcb696c2021-10-21 08:18:01 +020052#include <haproxy/xxhash.h>
Emeric Brunc9437992021-02-12 19:42:55 +010053
54
55struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
56struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
57
Willy Tarreauf766ec62021-10-18 16:46:38 +020058static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
Christopher Faulet9ed1a062021-11-02 16:25:05 +010059static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
Emeric Brunc9437992021-02-12 19:42:55 +010060static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
61struct resolvers *curr_resolvers = NULL;
62
63DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
64DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
65DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
66
67static unsigned int resolution_uuid = 1;
68unsigned int resolv_failed_resolutions = 0;
Willy Tarreauf766ec62021-10-18 16:46:38 +020069static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
70static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau6878f802021-10-20 14:07:31 +020071static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +010072static void enter_resolver_code();
73static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010074
75enum {
Emeric Brunf8642ee2021-10-29 17:59:18 +020076 RSLV_STAT_ID,
77 RSLV_STAT_PID,
78 RSLV_STAT_SENT,
79 RSLV_STAT_SND_ERROR,
80 RSLV_STAT_VALID,
81 RSLV_STAT_UPDATE,
82 RSLV_STAT_CNAME,
83 RSLV_STAT_CNAME_ERROR,
84 RSLV_STAT_ANY_ERR,
85 RSLV_STAT_NX,
86 RSLV_STAT_TIMEOUT,
87 RSLV_STAT_REFUSED,
88 RSLV_STAT_OTHER,
89 RSLV_STAT_INVALID,
90 RSLV_STAT_TOO_BIG,
91 RSLV_STAT_TRUNCATED,
92 RSLV_STAT_OUTDATED,
93 RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +010094};
95
Emeric Brunf8642ee2021-10-29 17:59:18 +020096static struct name_desc resolv_stats[] = {
97 [RSLV_STAT_ID] = { .name = "id", .desc = "ID" },
98 [RSLV_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
99 [RSLV_STAT_SENT] = { .name = "sent", .desc = "Sent" },
100 [RSLV_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
101 [RSLV_STAT_VALID] = { .name = "valid", .desc = "Valid" },
102 [RSLV_STAT_UPDATE] = { .name = "update", .desc = "Update" },
103 [RSLV_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
104 [RSLV_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
105 [RSLV_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
106 [RSLV_STAT_NX] = { .name = "nx", .desc = "NX" },
107 [RSLV_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
108 [RSLV_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
109 [RSLV_STAT_OTHER] = { .name = "other", .desc = "Other" },
110 [RSLV_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
111 [RSLV_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
112 [RSLV_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
113 [RSLV_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
Emeric Brunc9437992021-02-12 19:42:55 +0100114};
115
116static struct dns_counters dns_counters;
117
Emeric Brunf8642ee2021-10-29 17:59:18 +0200118static void resolv_fill_stats(void *d, struct field *stats)
Emeric Brunc9437992021-02-12 19:42:55 +0100119{
120 struct dns_counters *counters = d;
Emeric Brunf8642ee2021-10-29 17:59:18 +0200121 stats[RSLV_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
122 stats[RSLV_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
123 stats[RSLV_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
124 stats[RSLV_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
125 stats[RSLV_STAT_VALID] = mkf_u64(FN_GAUGE, counters->app.resolver.valid);
126 stats[RSLV_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->app.resolver.update);
127 stats[RSLV_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->app.resolver.cname);
128 stats[RSLV_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->app.resolver.cname_error);
129 stats[RSLV_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->app.resolver.any_err);
130 stats[RSLV_STAT_NX] = mkf_u64(FN_GAUGE, counters->app.resolver.nx);
131 stats[RSLV_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->app.resolver.timeout);
132 stats[RSLV_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->app.resolver.refused);
133 stats[RSLV_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->app.resolver.other);
134 stats[RSLV_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->app.resolver.invalid);
135 stats[RSLV_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->app.resolver.too_big);
136 stats[RSLV_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->app.resolver.truncated);
137 stats[RSLV_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +0100138}
139
Emeric Brunf8642ee2021-10-29 17:59:18 +0200140static struct stats_module rslv_stats_module = {
141 .name = "resolvers",
142 .domain_flags = STATS_DOMAIN_RESOLVERS << STATS_DOMAIN,
143 .fill_stats = resolv_fill_stats,
144 .stats = resolv_stats,
145 .stats_count = RSLV_STAT_END,
Emeric Brunc9437992021-02-12 19:42:55 +0100146 .counters = &dns_counters,
147 .counters_size = sizeof(dns_counters),
148 .clearable = 0,
149};
150
Emeric Brunf8642ee2021-10-29 17:59:18 +0200151INITCALL1(STG_REGISTER, stats_register_module, &rslv_stats_module);
Emeric Brunc9437992021-02-12 19:42:55 +0100152
153/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
154 * no match is found.
155 */
156struct resolvers *find_resolvers_by_id(const char *id)
157{
158 struct resolvers *res;
159
160 list_for_each_entry(res, &sec_resolvers, list) {
161 if (strcmp(res->id, id) == 0)
162 return res;
163 }
164 return NULL;
165}
166
Emeric Brunc9437992021-02-12 19:42:55 +0100167/* Returns a pointer on the SRV request matching the name <name> for the proxy
168 * <px>. NULL is returned if no match is found.
169 */
170struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
171{
172 struct resolv_srvrq *srvrq;
173
174 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
175 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
176 return srvrq;
177 }
178 return NULL;
179}
180
181/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
182 * NULL if an error occurred. */
183struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
184{
185 struct proxy *px = srv->proxy;
186 struct resolv_srvrq *srvrq = NULL;
187 int fqdn_len, hostname_dn_len;
188
189 fqdn_len = strlen(fqdn);
Willy Tarreaubf9498a2021-10-14 07:49:49 +0200190 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100191 trash.size);
192 if (hostname_dn_len == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200193 ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100194 proxy_type_str(px), px->id, srv->id, fqdn);
195 goto err;
196 }
197
198 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200199 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100200 proxy_type_str(px), px->id, srv->id);
201 goto err;
202 }
203 srvrq->obj_type = OBJ_TYPE_SRVRQ;
204 srvrq->proxy = px;
205 srvrq->name = strdup(fqdn);
206 srvrq->hostname_dn = strdup(trash.area);
207 srvrq->hostname_dn_len = hostname_dn_len;
208 if (!srvrq->name || !srvrq->hostname_dn) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200209 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100210 proxy_type_str(px), px->id, srv->id);
211 goto err;
212 }
Emeric Brun34067662021-06-11 10:48:45 +0200213 LIST_INIT(&srvrq->attached_servers);
214 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200215 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100216 return srvrq;
217
218 err:
219 if (srvrq) {
220 free(srvrq->name);
221 free(srvrq->hostname_dn);
222 free(srvrq);
223 }
224 return NULL;
225}
226
227
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100228/* finds and return the SRV answer item associated to a requester (whose type is 'server').
229 *
230 * returns NULL in case of error or not found.
231 */
232struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
233{
234 struct resolv_resolution *res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200235 struct eb32_node *eb32;
236 struct server *srv;
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100237
238 if (!requester)
239 return NULL;
240
241 if ((srv = objt_server(requester->owner)) == NULL)
242 return NULL;
243 /* check if the server is managed by a SRV record */
244 if (srv->srvrq == NULL)
245 return NULL;
246
247 res = srv->srvrq->requester->resolution;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200248
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100249 /* search an ANSWER record whose target points to the server's hostname and whose port is
250 * the same as server's svc_port */
Willy Tarreau7893ae12021-10-21 07:39:57 +0200251 for (eb32 = eb32_first(&res->response.answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
252 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
253
Willy Tarreau75cc6532021-10-15 08:53:44 +0200254 if (memcmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100255 (srv->svc_port == item->port))
256 return item;
257 }
258
259 return NULL;
260}
261
Emeric Brunc9437992021-02-12 19:42:55 +0100262/* 2 bytes random generator to generate DNS query ID */
263static inline uint16_t resolv_rnd16(void)
264{
265 if (!resolv_query_id_seed)
266 resolv_query_id_seed = now_ms;
267 resolv_query_id_seed ^= resolv_query_id_seed << 13;
268 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
269 resolv_query_id_seed ^= resolv_query_id_seed << 17;
270 return resolv_query_id_seed;
271}
272
273
274static inline int resolv_resolution_timeout(struct resolv_resolution *res)
275{
276 return res->resolvers->timeout.resolve;
277}
278
279/* Updates a resolvers' task timeout for next wake up and queue it */
280static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
281{
282 struct resolv_resolution *res;
283 int next;
284
285 next = tick_add(now_ms, resolvers->timeout.resolve);
286 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
287 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
288 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
289 }
290
291 list_for_each_entry(res, &resolvers->resolutions.wait, list)
292 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
293
294 resolvers->t->expire = next;
295 task_queue(resolvers->t);
296}
297
298/* Forges a DNS query. It needs the following information from the caller:
299 * - <query_id> : the DNS query id corresponding to this query
300 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
301 * - <hostname_dn> : hostname in domain name format
302 * - <hostname_dn_len> : length of <hostname_dn>
303 *
304 * To store the query, the caller must pass a buffer <buf> and its size
305 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
306 * too short.
307 */
308static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
309 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
310{
311 struct dns_header dns_hdr;
312 struct dns_question qinfo;
313 struct dns_additional_record edns;
314 char *p = buf;
315
316 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
317 return -1;
318
319 memset(buf, 0, bufsize);
320
321 /* Set dns query headers */
322 dns_hdr.id = (unsigned short) htons(query_id);
323 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
324 dns_hdr.qdcount = htons(1); /* 1 question */
325 dns_hdr.ancount = 0;
326 dns_hdr.nscount = 0;
327 dns_hdr.arcount = htons(1);
328 memcpy(p, &dns_hdr, sizeof(dns_hdr));
329 p += sizeof(dns_hdr);
330
331 /* Set up query hostname */
332 memcpy(p, hostname_dn, hostname_dn_len);
333 p += hostname_dn_len;
334 *p++ = 0;
335
336 /* Set up query info (type and class) */
337 qinfo.qtype = htons(query_type);
338 qinfo.qclass = htons(DNS_RCLASS_IN);
339 memcpy(p, &qinfo, sizeof(qinfo));
340 p += sizeof(qinfo);
341
342 /* Set the DNS extension */
343 edns.name = 0;
344 edns.type = htons(DNS_RTYPE_OPT);
345 edns.udp_payload_size = htons(accepted_payload_size);
346 edns.extension = 0;
347 edns.data_length = 0;
348 memcpy(p, &edns, sizeof(edns));
349 p += sizeof(edns);
350
351 return (p - buf);
352}
353
354/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
Emeric Brun0161d322021-10-29 16:44:49 +0200355 * success or -1 if trash buffer is not large enough to build a valid query.
Emeric Brunc9437992021-02-12 19:42:55 +0100356 */
357static int resolv_send_query(struct resolv_resolution *resolution)
358{
359 struct resolvers *resolvers = resolution->resolvers;
360 struct dns_nameserver *ns;
361 int len;
362
363 /* Update resolution */
364 resolution->nb_queries = 0;
365 resolution->nb_responses = 0;
366 resolution->last_query = now_ms;
367
368 len = resolv_build_query(resolution->query_id, resolution->query_type,
369 resolvers->accepted_payload_size,
370 resolution->hostname_dn, resolution->hostname_dn_len,
371 trash.area, trash.size);
Emeric Brun0161d322021-10-29 16:44:49 +0200372 if (len < 0) {
373 send_log(NULL, LOG_NOTICE,
374 "can not build the query message for %s, in resolvers %s.\n",
375 resolution->hostname_dn, resolvers->id);
376 return -1;
377 }
Emeric Brunc9437992021-02-12 19:42:55 +0100378
379 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunc37caab2021-10-29 16:28:33 +0200380 if (dns_send_nameserver(ns, trash.area, len) >= 0)
Emeric Brunc9437992021-02-12 19:42:55 +0100381 resolution->nb_queries++;
382 }
383
384 /* Push the resolution at the end of the active list */
Willy Tarreauaae73202021-10-19 22:01:36 +0200385 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200386 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100387 return 0;
388}
389
390/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
391 * skipped and -1 if an error occurred.
392 */
393static int
394resolv_run_resolution(struct resolv_resolution *resolution)
395{
396 struct resolvers *resolvers = resolution->resolvers;
397 int query_id, i;
398
399 /* Avoid sending requests for resolutions that don't yet have an
400 * hostname, ie resolutions linked to servers that do not yet have an
401 * fqdn */
402 if (!resolution->hostname_dn)
403 return 0;
404
405 /* Check if a resolution has already been started for this server return
406 * directly to avoid resolution pill up. */
407 if (resolution->step != RSLV_STEP_NONE)
408 return 0;
409
410 /* Generates a new query id. We try at most 100 times to find a free
411 * query id */
412 for (i = 0; i < 100; ++i) {
413 query_id = resolv_rnd16();
414 if (!eb32_lookup(&resolvers->query_ids, query_id))
415 break;
416 query_id = -1;
417 }
418 if (query_id == -1) {
419 send_log(NULL, LOG_NOTICE,
420 "could not generate a query id for %s, in resolvers %s.\n",
421 resolution->hostname_dn, resolvers->id);
422 return -1;
423 }
424
425 /* Update resolution parameters */
426 resolution->query_id = query_id;
427 resolution->qid.key = query_id;
428 resolution->step = RSLV_STEP_RUNNING;
429 resolution->query_type = resolution->prefered_query_type;
430 resolution->try = resolvers->resolve_retries;
431 eb32_insert(&resolvers->query_ids, &resolution->qid);
432
433 /* Send the DNS query */
434 resolution->try -= 1;
435 resolv_send_query(resolution);
436 return 1;
437}
438
439/* Performs a name resolution for the requester <req> */
440void resolv_trigger_resolution(struct resolv_requester *req)
441{
442 struct resolvers *resolvers;
443 struct resolv_resolution *res;
444 int exp;
445
446 if (!req || !req->resolution)
447 return;
448 res = req->resolution;
449 resolvers = res->resolvers;
450
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100451 enter_resolver_code();
452
Emeric Brunc9437992021-02-12 19:42:55 +0100453 /* The resolution must not be triggered yet. Use the cached response, if
454 * valid */
455 exp = tick_add(res->last_resolution, resolvers->hold.valid);
456 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
457 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
458 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100459
460 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100461}
462
463
464/* Resets some resolution parameters to initial values and also delete the query
465 * ID from the resolver's tree.
466 */
467static void resolv_reset_resolution(struct resolv_resolution *resolution)
468{
469 /* update resolution status */
470 resolution->step = RSLV_STEP_NONE;
471 resolution->try = 0;
472 resolution->last_resolution = now_ms;
473 resolution->nb_queries = 0;
474 resolution->nb_responses = 0;
475 resolution->query_type = resolution->prefered_query_type;
476
477 /* clean up query id */
478 eb32_delete(&resolution->qid);
479 resolution->query_id = 0;
480 resolution->qid.key = 0;
481}
482
483/* Returns the query id contained in a DNS response */
484static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
485{
486 return resp[0] * 256 + resp[1];
487}
488
489
490/* Analyses, re-builds and copies the name <name> from the DNS response packet
491 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
492 * for compressed data. The result is copied into <dest>, ensuring we don't
493 * overflow using <dest_len> Returns the number of bytes the caller can move
494 * forward. If 0 it means an error occurred while parsing the name. <offset> is
495 * the number of bytes the caller could move forward.
496 */
497int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
498 unsigned char *name, char *destination, int dest_len,
499 int *offset, unsigned int depth)
500{
501 int nb_bytes = 0, n = 0;
502 int label_len;
503 unsigned char *reader = name;
504 char *dest = destination;
505
506 while (1) {
507 if (reader >= bufend)
508 goto err;
509
510 /* Name compression is in use */
511 if ((*reader & 0xc0) == 0xc0) {
512 if (reader + 1 >= bufend)
513 goto err;
514
515 /* Must point BEFORE current position */
516 if ((buffer + reader[1]) > reader)
517 goto err;
518
519 if (depth++ > 100)
520 goto err;
521
522 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
523 dest, dest_len - nb_bytes, offset, depth);
524 if (n == 0)
525 goto err;
526
527 dest += n;
528 nb_bytes += n;
529 goto out;
530 }
531
532 label_len = *reader;
533 if (label_len == 0)
534 goto out;
535
536 /* Check if:
537 * - we won't read outside the buffer
538 * - there is enough place in the destination
539 */
540 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
541 goto err;
542
543 /* +1 to take label len + label string */
544 label_len++;
545
546 memcpy(dest, reader, label_len);
547
548 dest += label_len;
549 nb_bytes += label_len;
550 reader += label_len;
551 }
552
553 out:
554 /* offset computation:
555 * parse from <name> until finding either NULL or a pointer "c0xx"
556 */
557 reader = name;
558 *offset = 0;
559 while (reader < bufend) {
560 if ((reader[0] & 0xc0) == 0xc0) {
561 *offset += 2;
562 break;
563 }
564 else if (*reader == 0) {
565 *offset += 1;
566 break;
567 }
568 *offset += 1;
569 ++reader;
570 }
571 return nb_bytes;
572
573 err:
574 return 0;
575}
576
Willy Tarreauf766ec62021-10-18 16:46:38 +0200577/* Reinitialize the list of aborted resolutions before calling certain
578 * functions relying on it. The list must be processed by calling
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100579 * leave_resolver_code() after operations.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200580 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100581static void enter_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200582{
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100583 if (!recurse)
584 LIST_INIT(&death_row);
585 recurse++;
Willy Tarreauf766ec62021-10-18 16:46:38 +0200586}
587
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100588/* Add a resolution to the death_row. */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200589static void abort_resolution(struct resolv_resolution *res)
590{
591 LIST_DEL_INIT(&res->list);
592 LIST_APPEND(&death_row, &res->list);
593}
594
595/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100596 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreauf766ec62021-10-18 16:46:38 +0200597 * needs to defer deletions. Note that some of them are in relation via internal
598 * objects and might cause the deletion of other ones from the same list, so we
599 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
600 * and solely rely on each call to remove the first remaining list element.
601 */
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100602static void leave_resolver_code()
Willy Tarreauf766ec62021-10-18 16:46:38 +0200603{
604 struct resolv_resolution *res;
605
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100606 recurse--;
607 if (recurse)
608 return;
609
Willy Tarreauf766ec62021-10-18 16:46:38 +0200610 while (!LIST_ISEMPTY(&death_row)) {
611 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
612 resolv_free_resolution(res);
613 }
614
615 /* make sure nobody tries to add anything without having initialized it */
616 death_row = (struct list){ };
617}
618
Christopher Faulet11c6c392021-06-15 16:08:48 +0200619/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
620 * happens when an SRV item is purged or when the server status is considered as
621 * obsolete.
622 *
Willy Tarreauf766ec62021-10-18 16:46:38 +0200623 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100624 * initialized via enter_resolver_code().
Christopher Faulet11c6c392021-06-15 16:08:48 +0200625 */
Willy Tarreauf766ec62021-10-18 16:46:38 +0200626static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet11c6c392021-06-15 16:08:48 +0200627{
Willy Tarreau6878f802021-10-20 14:07:31 +0200628 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200629 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
630 srvrq_update_srv_status(srv, 1);
631 ha_free(&srv->hostname);
632 ha_free(&srv->hostname_dn);
633 srv->hostname_dn_len = 0;
634 memset(&srv->addr, 0, sizeof(srv->addr));
635 srv->svc_port = 0;
636 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet73001ab2021-06-15 16:14:37 +0200637
638 ebpt_delete(&srv->host_dn);
639 ha_free(&srv->host_dn.key);
640
Christopher Faulet11c6c392021-06-15 16:08:48 +0200641 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreauaae73202021-10-19 22:01:36 +0200642 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet11c6c392021-06-15 16:08:48 +0200643 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Fauletdcac4182021-06-15 16:17:17 +0200644
645 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet11c6c392021-06-15 16:08:48 +0200646}
647
Christopher Fauletdcac4182021-06-15 16:17:17 +0200648/* Takes care to cleanup a server resolution when it is outdated. This only
649 * happens for a server relying on a SRV record.
650 */
651static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
652{
653 struct server *srv = context;
654
655 if (!tick_is_expired(t->expire, now_ms))
656 goto end;
657
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100658 enter_resolver_code();
Christopher Faulete886dd52021-06-18 09:05:49 +0200659 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreauf766ec62021-10-18 16:46:38 +0200660 resolv_srvrq_cleanup_srv(srv);
Christopher Faulete886dd52021-06-18 09:05:49 +0200661 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100662 leave_resolver_code();
Christopher Fauletdcac4182021-06-15 16:17:17 +0200663
664 end:
665 return t;
666}
667
Emeric Brunc9437992021-02-12 19:42:55 +0100668/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet9ed1a062021-11-02 16:25:05 +0100669 * find a corresponding server.
Willy Tarreauf766ec62021-10-18 16:46:38 +0200670 */
Emeric Brunc9437992021-02-12 19:42:55 +0100671static void resolv_check_response(struct resolv_resolution *res)
672{
673 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100674 struct resolv_requester *req;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200675 struct eb32_node *eb32, *eb32_back;
Emeric Brunbd78c912021-06-11 10:08:05 +0200676 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100677 struct resolv_srvrq *srvrq;
678
Willy Tarreau7893ae12021-10-21 07:39:57 +0200679 for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
680 struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
Emeric Brunc9437992021-02-12 19:42:55 +0100681 struct resolv_answer_item *ar_item = item->ar_item;
682
683 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100684 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100685 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
686 * item is also obsolete.
687 */
Emeric Brunc9437992021-02-12 19:42:55 +0100688 pool_free(resolv_answer_item_pool, ar_item);
689 item->ar_item = NULL;
690 }
691
692 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100693 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200694 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100695 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200696 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
697 LIST_DEL_INIT(&srv->ip_rec_item);
698 }
699 }
700 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun34067662021-06-11 10:48:45 +0200701 /* Remove any associated server */
Christopher Faulet11c6c392021-06-15 16:08:48 +0200702 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreauf766ec62021-10-18 16:46:38 +0200703 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100704 }
705
Willy Tarreau7893ae12021-10-21 07:39:57 +0200706 eb32_delete(&item->link);
Emeric Brunc9437992021-02-12 19:42:55 +0100707 if (item->ar_item) {
708 pool_free(resolv_answer_item_pool, item->ar_item);
709 item->ar_item = NULL;
710 }
711 pool_free(resolv_answer_item_pool, item);
712 continue;
713 }
714
715 if (item->type != DNS_RTYPE_SRV)
716 continue;
717
718 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100719 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun34067662021-06-11 10:48:45 +0200720 struct ebpt_node *node;
721 char target[DNS_MAX_NAME_SIZE+1];
722
723 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100724 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
725 continue;
726
Emeric Brun34067662021-06-11 10:48:45 +0200727 /* Check if a server already uses that record */
728 srv = NULL;
729 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
730 if (srv->srvrq == srvrq) {
731 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
732 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100733 }
Emeric Brunc9437992021-02-12 19:42:55 +0100734 }
735
Emeric Brun34067662021-06-11 10:48:45 +0200736
737 /* If not empty we try to match a server
738 * in server state file tree with the same hostname
739 */
740 if (!eb_is_empty(&srvrq->named_servers)) {
741 srv = NULL;
742
743 /* convert the key to lookup in lower case */
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200744 for (i = 0 ; item->data.target[i] ; i++)
745 target[i] = tolower(item->data.target[i]);
Christopher Faulet1f923392021-07-22 14:29:26 +0200746 target[i] = 0;
Emeric Brun34067662021-06-11 10:48:45 +0200747
748 node = ebis_lookup(&srvrq->named_servers, target);
749 if (node) {
750 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100751 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun34067662021-06-11 10:48:45 +0200752
753 /* an entry was found with the same hostname
754 * let check this node if the port matches
755 * and try next node if the hostname
756 * is still the same
757 */
758 while (1) {
759 if (srv->svc_port == item->port) {
760 /* server found, we remove it from tree */
761 ebpt_delete(node);
Christopher Faulet73001ab2021-06-15 16:14:37 +0200762 ha_free(&srv->host_dn.key);
Emeric Brun34067662021-06-11 10:48:45 +0200763 goto srv_found;
764 }
765
766 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
767
768 node = ebpt_next(node);
769 if (!node)
770 break;
771
772 srv = ebpt_entry(node, struct server, host_dn);
773 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
774
775 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau75cc6532021-10-15 08:53:44 +0200776 || memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
Emeric Brun34067662021-06-11 10:48:45 +0200777 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
778 break;
779 }
780 }
Emeric Brunc9437992021-02-12 19:42:55 +0100781 }
782 }
Emeric Brun34067662021-06-11 10:48:45 +0200783
784 /* Pick the first server listed in srvrq (those ones don't
785 * have hostname and are free to use)
786 */
787 srv = NULL;
788 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
789 LIST_DEL_INIT(&srv->srv_rec_item);
790 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
791 goto srv_found;
792 }
793 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100794
Emeric Brun34067662021-06-11 10:48:45 +0200795srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100796 /* And update this server, if found (srv is locked here) */
797 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100798 /* re-enable DNS resolution for this server by default */
799 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Fauletdcac4182021-06-15 16:17:17 +0200800 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100801
Emeric Brunc9437992021-02-12 19:42:55 +0100802 /* Check if an Additional Record is associated to this SRV record.
803 * Perform some sanity checks too to ensure the record can be used.
804 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100805 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100806 */
807 if ((item->ar_item != NULL) &&
808 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100809 {
Emeric Brunc9437992021-02-12 19:42:55 +0100810
811 switch (item->ar_item->type) {
812 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200813 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100814 break;
815 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200816 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100817 break;
818 }
819
820 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100821
822 /* Unlink A/AAAA resolution for this server if there is an AR item.
823 * It is usless to perform an extra resolution
824 */
Willy Tarreau6878f802021-10-20 14:07:31 +0200825 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100826 }
827
828 if (!srv->hostname_dn) {
829 const char *msg = NULL;
Willy Tarreau85c15e62021-10-14 08:00:38 +0200830 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100831
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +0200832 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau85c15e62021-10-14 08:00:38 +0200833 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100834 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
835 continue;
836 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100837 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100838 if (msg)
839 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
840 }
841
Emeric Brun34067662021-06-11 10:48:45 +0200842 if (!LIST_INLIST(&srv->srv_rec_item))
843 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
844
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100845 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
846 /* If there is no AR item responsible of the FQDN resolution,
847 * trigger a dedicated DNS resolution
848 */
849 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
850 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
851 }
852
Christopher Fauletab177ac2021-03-10 15:34:52 +0100853 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100854 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100855
856 srv->svc_port = item->port;
857 srv->flags &= ~SRV_F_MAPPORTS;
858
859 if (!srv->resolv_opts.ignore_weight) {
860 char weight[9];
861 int ha_weight;
862
863 /* DNS weight range if from 0 to 65535
864 * HAProxy weight is from 0 to 256
865 * The rule below ensures that weight 0 is well respected
866 * while allowing a "mapping" from DNS weight into HAProxy's one.
867 */
868 ha_weight = (item->weight + 255) / 256;
869
870 snprintf(weight, sizeof(weight), "%d", ha_weight);
871 server_parse_weight_change_request(srv, weight);
872 }
873 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
874 }
875 }
876 }
877}
878
879/* Validates that the buffer DNS response provided in <resp> and finishing
880 * before <bufend> is valid from a DNS protocol point of view.
881 *
882 * The result is stored in <resolution>' response, buf_response,
883 * response_query_records and response_answer_records members.
884 *
885 * This function returns one of the RSLV_RESP_* code to indicate the type of
886 * error found.
887 */
888static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
889 struct resolv_resolution *resolution, int max_answer_records)
890{
891 unsigned char *reader;
892 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
893 int len, flags, offset;
Emeric Brunc9437992021-02-12 19:42:55 +0100894 int nb_saved_records;
895 struct resolv_query_item *query;
896 struct resolv_answer_item *answer_record, *tmp_record;
897 struct resolv_response *r_res;
Willy Tarreau7893ae12021-10-21 07:39:57 +0200898 struct eb32_node *eb32;
Willy Tarreaudcb696c2021-10-21 08:18:01 +0200899 uint32_t key = 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100900 int i, found = 0;
901 int cause = RSLV_RESP_ERROR;
902
903 reader = resp;
904 len = 0;
905 previous_dname = NULL;
906 query = NULL;
907 answer_record = NULL;
908
909 /* Initialization of response buffer and structure */
910 r_res = &resolution->response;
911
912 /* query id */
913 if (reader + 2 >= bufend)
914 goto invalid_resp;
915
916 r_res->header.id = reader[0] * 256 + reader[1];
917 reader += 2;
918
919 /* Flags and rcode are stored over 2 bytes
920 * First byte contains:
921 * - response flag (1 bit)
922 * - opcode (4 bits)
923 * - authoritative (1 bit)
924 * - truncated (1 bit)
925 * - recursion desired (1 bit)
926 */
927 if (reader + 2 >= bufend)
928 goto invalid_resp;
929
930 flags = reader[0] * 256 + reader[1];
931
932 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
933 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
934 cause = RSLV_RESP_NX_DOMAIN;
935 goto return_error;
936 }
937 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
938 cause = RSLV_RESP_REFUSED;
939 goto return_error;
940 }
941 else {
942 cause = RSLV_RESP_ERROR;
943 goto return_error;
944 }
945 }
946
947 /* Move forward 2 bytes for flags */
948 reader += 2;
949
950 /* 2 bytes for question count */
951 if (reader + 2 >= bufend)
952 goto invalid_resp;
953 r_res->header.qdcount = reader[0] * 256 + reader[1];
954 /* (for now) we send one query only, so we expect only one in the
955 * response too */
956 if (r_res->header.qdcount != 1) {
957 cause = RSLV_RESP_QUERY_COUNT_ERROR;
958 goto return_error;
959 }
960
961 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
962 goto invalid_resp;
963 reader += 2;
964
965 /* 2 bytes for answer count */
966 if (reader + 2 >= bufend)
967 goto invalid_resp;
968 r_res->header.ancount = reader[0] * 256 + reader[1];
969 if (r_res->header.ancount == 0) {
970 cause = RSLV_RESP_ANCOUNT_ZERO;
971 goto return_error;
972 }
973
974 /* Check if too many records are announced */
975 if (r_res->header.ancount > max_answer_records)
976 goto invalid_resp;
977 reader += 2;
978
979 /* 2 bytes authority count */
980 if (reader + 2 >= bufend)
981 goto invalid_resp;
982 r_res->header.nscount = reader[0] * 256 + reader[1];
983 reader += 2;
984
985 /* 2 bytes additional count */
986 if (reader + 2 >= bufend)
987 goto invalid_resp;
988 r_res->header.arcount = reader[0] * 256 + reader[1];
989 reader += 2;
990
Christopher Fauletc1699f82021-12-01 15:07:26 +0100991 /* Parsing dns queries. For now there is only one query and it exists
992 * because (qdcount == 1).
993 */
994 query = &resolution->response_query_records[0];
Emeric Brunc9437992021-02-12 19:42:55 +0100995
Christopher Fauletc1699f82021-12-01 15:07:26 +0100996 /* Name is a NULL terminated string in our case, since we have
997 * one query per response and the first one can't be compressed
998 * (using the 0x0c format) */
999 offset = 0;
1000 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01001001
Christopher Fauletc1699f82021-12-01 15:07:26 +01001002 if (len == 0)
1003 goto invalid_resp;
Emeric Brunc9437992021-02-12 19:42:55 +01001004
Christopher Fauletc1699f82021-12-01 15:07:26 +01001005 /* Now let's check the query's dname corresponds to the one we sent. */
1006 if (len != resolution->hostname_dn_len ||
1007 memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
1008 cause = RSLV_RESP_WRONG_NAME;
Christopher Fauletaf93d2f2021-12-02 10:05:02 +01001009 goto return_error;
Christopher Fauletc1699f82021-12-01 15:07:26 +01001010 }
Emeric Brunc9437992021-02-12 19:42:55 +01001011
Christopher Fauletc1699f82021-12-01 15:07:26 +01001012 reader += offset;
1013 previous_dname = query->name;
Emeric Brunc9437992021-02-12 19:42:55 +01001014
Christopher Fauletc1699f82021-12-01 15:07:26 +01001015 /* move forward 2 bytes for question type */
1016 if (reader + 2 >= bufend)
1017 goto invalid_resp;
1018 query->type = reader[0] * 256 + reader[1];
1019 reader += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001020
Christopher Fauletc1699f82021-12-01 15:07:26 +01001021 /* move forward 2 bytes for question class */
1022 if (reader + 2 >= bufend)
1023 goto invalid_resp;
1024 query->class = reader[0] * 256 + reader[1];
1025 reader += 2;
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001026
Emeric Brunc9437992021-02-12 19:42:55 +01001027 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau10c1a8c2021-10-20 17:29:28 +02001028 * because a TRUNCATED SRV query type response can still be exploited
1029 */
Emeric Brunc9437992021-02-12 19:42:55 +01001030 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1031 cause = RSLV_RESP_TRUNCATED;
1032 goto return_error;
1033 }
1034
1035 /* now parsing response records */
1036 nb_saved_records = 0;
1037 for (i = 0; i < r_res->header.ancount; i++) {
1038 if (reader >= bufend)
1039 goto invalid_resp;
1040
1041 answer_record = pool_alloc(resolv_answer_item_pool);
1042 if (answer_record == NULL)
1043 goto invalid_resp;
1044
1045 /* initialization */
1046 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001047 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001048 LIST_INIT(&answer_record->attached_servers);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001049 answer_record->link.node.leaf_p = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001050
1051 offset = 0;
1052 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1053
1054 if (len == 0)
1055 goto invalid_resp;
1056
1057 /* Check if the current record dname is valid. previous_dname
1058 * points either to queried dname or last CNAME target */
Willy Tarreau75cc6532021-10-15 08:53:44 +02001059 if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001060 if (i == 0) {
1061 /* First record, means a mismatch issue between
1062 * queried dname and dname found in the first
1063 * record */
1064 goto invalid_resp;
1065 }
1066 else {
1067 /* If not the first record, this means we have a
1068 * CNAME resolution error.
1069 */
1070 cause = RSLV_RESP_CNAME_ERROR;
1071 goto return_error;
1072 }
1073
1074 }
1075
1076 memcpy(answer_record->name, tmpname, len);
1077 answer_record->name[len] = 0;
1078
1079 reader += offset;
1080 if (reader >= bufend)
1081 goto invalid_resp;
1082
1083 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1084 if (reader + 2 > bufend)
1085 goto invalid_resp;
1086
1087 answer_record->type = reader[0] * 256 + reader[1];
1088 reader += 2;
1089
1090 /* 2 bytes for class (2) */
1091 if (reader + 2 > bufend)
1092 goto invalid_resp;
1093
1094 answer_record->class = reader[0] * 256 + reader[1];
1095 reader += 2;
1096
1097 /* 4 bytes for ttl (4) */
1098 if (reader + 4 > bufend)
1099 goto invalid_resp;
1100
1101 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1102 + reader[2] * 256 + reader[3];
1103 reader += 4;
1104
1105 /* Now reading data len */
1106 if (reader + 2 > bufend)
1107 goto invalid_resp;
1108
1109 answer_record->data_len = reader[0] * 256 + reader[1];
1110
1111 /* Move forward 2 bytes for data len */
1112 reader += 2;
1113
1114 if (reader + answer_record->data_len > bufend)
1115 goto invalid_resp;
1116
1117 /* Analyzing record content */
1118 switch (answer_record->type) {
1119 case DNS_RTYPE_A:
1120 /* ipv4 is stored on 4 bytes */
1121 if (answer_record->data_len != 4)
1122 goto invalid_resp;
1123
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001124 answer_record->data.in4.sin_family = AF_INET;
1125 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001126 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001127 break;
1128
1129 case DNS_RTYPE_CNAME:
1130 /* Check if this is the last record and update the caller about the status:
1131 * no IP could be found and last record was a CNAME. Could be triggered
1132 * by a wrong query type
1133 *
1134 * + 1 because answer_record_id starts at 0
1135 * while number of answers is an integer and
1136 * starts at 1.
1137 */
1138 if (i + 1 == r_res->header.ancount) {
1139 cause = RSLV_RESP_CNAME_ERROR;
1140 goto return_error;
1141 }
1142
1143 offset = 0;
1144 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1145 if (len == 0)
1146 goto invalid_resp;
1147
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001148 memcpy(answer_record->data.target, tmpname, len);
1149 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001150 key = XXH32(tmpname, len, answer_record->type);
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001151 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001152 break;
1153
1154
1155 case DNS_RTYPE_SRV:
1156 /* Answer must contain :
1157 * - 2 bytes for the priority
1158 * - 2 bytes for the weight
1159 * - 2 bytes for the port
1160 * - the target hostname
1161 */
1162 if (answer_record->data_len <= 6)
1163 goto invalid_resp;
1164
1165 answer_record->priority = read_n16(reader);
1166 reader += sizeof(uint16_t);
1167 answer_record->weight = read_n16(reader);
1168 reader += sizeof(uint16_t);
1169 answer_record->port = read_n16(reader);
1170 reader += sizeof(uint16_t);
1171 offset = 0;
1172 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1173 if (len == 0)
1174 goto invalid_resp;
1175
1176 answer_record->data_len = len;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001177 memcpy(answer_record->data.target, tmpname, len);
1178 answer_record->data.target[len] = 0;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001179 key = XXH32(tmpname, len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001180 if (answer_record->ar_item != NULL) {
1181 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1182 answer_record->ar_item = NULL;
1183 }
1184 break;
1185
1186 case DNS_RTYPE_AAAA:
1187 /* ipv6 is stored on 16 bytes */
1188 if (answer_record->data_len != 16)
1189 goto invalid_resp;
1190
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001191 answer_record->data.in6.sin6_family = AF_INET6;
1192 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001193 key = XXH32(reader, answer_record->data_len, answer_record->type);
Emeric Brunc9437992021-02-12 19:42:55 +01001194 break;
1195
1196 } /* switch (record type) */
1197
1198 /* Increment the counter for number of records saved into our
1199 * local response */
1200 nb_saved_records++;
1201
1202 /* Move forward answer_record->data_len for analyzing next
1203 * record in the response */
1204 reader += ((answer_record->type == DNS_RTYPE_SRV)
1205 ? offset
1206 : answer_record->data_len);
1207
1208 /* Lookup to see if we already had this entry */
1209 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001210
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001211 for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02001212 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001213 if (tmp_record->type != answer_record->type)
1214 continue;
1215
1216 switch(tmp_record->type) {
1217 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001218 if (!memcmp(&answer_record->data.in4.sin_addr,
1219 &tmp_record->data.in4.sin_addr,
1220 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001221 found = 1;
1222 break;
1223
1224 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001225 if (!memcmp(&answer_record->data.in6.sin6_addr,
1226 &tmp_record->data.in6.sin6_addr,
1227 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001228 found = 1;
1229 break;
1230
1231 case DNS_RTYPE_SRV:
1232 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001233 memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
Emeric Brunc9437992021-02-12 19:42:55 +01001234 answer_record->port == tmp_record->port) {
1235 tmp_record->weight = answer_record->weight;
1236 found = 1;
1237 }
1238 break;
1239
1240 default:
1241 break;
1242 }
1243
1244 if (found == 1)
1245 break;
1246 }
1247
1248 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001249 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001250 pool_free(resolv_answer_item_pool, answer_record);
1251 answer_record = NULL;
1252 }
1253 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001254 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001255 answer_record->ar_item = NULL;
Willy Tarreaudcb696c2021-10-21 08:18:01 +02001256 answer_record->link.key = key;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001257 eb32_insert(&r_res->answer_tree, &answer_record->link);
Emeric Brunc9437992021-02-12 19:42:55 +01001258 answer_record = NULL;
1259 }
1260 } /* for i 0 to ancount */
1261
1262 /* Save the number of records we really own */
1263 r_res->header.ancount = nb_saved_records;
1264
1265 /* now parsing additional records for SRV queries only */
1266 if (query->type != DNS_RTYPE_SRV)
1267 goto skip_parsing_additional_records;
1268
1269 /* if we find Authority records, just skip them */
1270 for (i = 0; i < r_res->header.nscount; i++) {
1271 offset = 0;
1272 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1273 &offset, 0);
1274 if (len == 0)
1275 continue;
1276
1277 if (reader + offset + 10 >= bufend)
1278 goto invalid_resp;
1279
1280 reader += offset;
1281 /* skip 2 bytes for class */
1282 reader += 2;
1283 /* skip 2 bytes for type */
1284 reader += 2;
1285 /* skip 4 bytes for ttl */
1286 reader += 4;
1287 /* read data len */
1288 len = reader[0] * 256 + reader[1];
1289 reader += 2;
1290
1291 if (reader + len >= bufend)
1292 goto invalid_resp;
1293
1294 reader += len;
1295 }
1296
1297 nb_saved_records = 0;
1298 for (i = 0; i < r_res->header.arcount; i++) {
1299 if (reader >= bufend)
1300 goto invalid_resp;
1301
1302 answer_record = pool_alloc(resolv_answer_item_pool);
1303 if (answer_record == NULL)
1304 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001305 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001306 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001307
1308 offset = 0;
1309 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1310
1311 if (len == 0) {
1312 pool_free(resolv_answer_item_pool, answer_record);
1313 answer_record = NULL;
1314 continue;
1315 }
1316
1317 memcpy(answer_record->name, tmpname, len);
1318 answer_record->name[len] = 0;
1319
1320 reader += offset;
1321 if (reader >= bufend)
1322 goto invalid_resp;
1323
1324 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1325 if (reader + 2 > bufend)
1326 goto invalid_resp;
1327
1328 answer_record->type = reader[0] * 256 + reader[1];
1329 reader += 2;
1330
1331 /* 2 bytes for class (2) */
1332 if (reader + 2 > bufend)
1333 goto invalid_resp;
1334
1335 answer_record->class = reader[0] * 256 + reader[1];
1336 reader += 2;
1337
1338 /* 4 bytes for ttl (4) */
1339 if (reader + 4 > bufend)
1340 goto invalid_resp;
1341
1342 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1343 + reader[2] * 256 + reader[3];
1344 reader += 4;
1345
1346 /* Now reading data len */
1347 if (reader + 2 > bufend)
1348 goto invalid_resp;
1349
1350 answer_record->data_len = reader[0] * 256 + reader[1];
1351
1352 /* Move forward 2 bytes for data len */
1353 reader += 2;
1354
1355 if (reader + answer_record->data_len > bufend)
1356 goto invalid_resp;
1357
1358 /* Analyzing record content */
1359 switch (answer_record->type) {
1360 case DNS_RTYPE_A:
1361 /* ipv4 is stored on 4 bytes */
1362 if (answer_record->data_len != 4)
1363 goto invalid_resp;
1364
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001365 answer_record->data.in4.sin_family = AF_INET;
1366 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001367 break;
1368
1369 case DNS_RTYPE_AAAA:
1370 /* ipv6 is stored on 16 bytes */
1371 if (answer_record->data_len != 16)
1372 goto invalid_resp;
1373
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001374 answer_record->data.in6.sin6_family = AF_INET6;
1375 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001376 break;
1377
1378 default:
1379 pool_free(resolv_answer_item_pool, answer_record);
1380 answer_record = NULL;
1381 continue;
1382
1383 } /* switch (record type) */
1384
1385 /* Increment the counter for number of records saved into our
1386 * local response */
1387 nb_saved_records++;
1388
1389 /* Move forward answer_record->data_len for analyzing next
1390 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001391 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001392
1393 /* Lookup to see if we already had this entry */
1394 found = 0;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001395
1396 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001397 struct resolv_answer_item *ar_item;
1398
Willy Tarreau7893ae12021-10-21 07:39:57 +02001399 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
Christopher Faulet77f86062021-03-10 15:19:57 +01001400 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1401 continue;
1402
1403 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001404 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001405 len != tmp_record->data_len ||
Willy Tarreau75cc6532021-10-15 08:53:44 +02001406 memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001407 continue;
1408
Christopher Faulet77f86062021-03-10 15:19:57 +01001409 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001410 case DNS_RTYPE_A:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001411 if (!memcmp(&answer_record->data.in4.sin_addr,
1412 &ar_item->data.in4.sin_addr,
1413 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001414 found = 1;
1415 break;
1416
1417 case DNS_RTYPE_AAAA:
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001418 if (!memcmp(&answer_record->data.in6.sin6_addr,
1419 &ar_item->data.in6.sin6_addr,
1420 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001421 found = 1;
1422 break;
1423
1424 default:
1425 break;
1426 }
1427
1428 if (found == 1)
1429 break;
1430 }
1431
1432 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001433 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001434 pool_free(resolv_answer_item_pool, answer_record);
1435 answer_record = NULL;
1436 }
1437 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001438 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001439 answer_record->ar_item = NULL;
1440
1441 // looking for the SRV record in the response list linked to this additional record
Willy Tarreau7893ae12021-10-21 07:39:57 +02001442 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
1443 tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
1444
Emeric Brunc9437992021-02-12 19:42:55 +01001445 if (tmp_record->type == DNS_RTYPE_SRV &&
1446 tmp_record->ar_item == NULL &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001447 memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01001448 /* Always use the received additional record to refresh info */
1449 if (tmp_record->ar_item)
1450 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1451 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001452 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001453 break;
1454 }
1455 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001456 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001457 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001458 answer_record = NULL;
1459 }
Emeric Brunc9437992021-02-12 19:42:55 +01001460 }
1461 } /* for i 0 to arcount */
1462
1463 skip_parsing_additional_records:
1464
1465 /* Save the number of records we really own */
1466 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001467 resolv_check_response(resolution);
1468 return RSLV_RESP_VALID;
1469
1470 invalid_resp:
1471 cause = RSLV_RESP_INVALID;
1472
1473 return_error:
1474 pool_free(resolv_answer_item_pool, answer_record);
1475 return cause;
1476}
1477
1478/* Searches dn_name resolution in resp.
1479 * If existing IP not found, return the first IP matching family_priority,
1480 * otherwise, first ip found
1481 * The following tasks are the responsibility of the caller:
1482 * - <r_res> contains an error free DNS response
1483 * For both cases above, resolv_validate_dns_response is required
1484 * returns one of the RSLV_UPD_* code
1485 */
1486int resolv_get_ip_from_response(struct resolv_response *r_res,
1487 struct resolv_options *resolv_opts, void *currentip,
1488 short currentip_sin_family,
1489 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001490 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001491{
Emeric Brunbd78c912021-06-11 10:08:05 +02001492 struct resolv_answer_item *record, *found_record = NULL;
Willy Tarreau7893ae12021-10-21 07:39:57 +02001493 struct eb32_node *eb32;
Emeric Brunc9437992021-02-12 19:42:55 +01001494 int family_priority;
1495 int currentip_found;
1496 unsigned char *newip4, *newip6;
1497 int currentip_sel;
1498 int j;
1499 int score, max_score;
1500 int allowed_duplicated_ip;
1501
Emeric Brunbd78c912021-06-11 10:08:05 +02001502 /* srv is linked to an alive ip record */
1503 if (owner && LIST_INLIST(&owner->ip_rec_item))
1504 return RSLV_UPD_NO;
1505
Emeric Brunc9437992021-02-12 19:42:55 +01001506 family_priority = resolv_opts->family_prio;
1507 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1508 *newip = newip4 = newip6 = NULL;
1509 currentip_found = 0;
1510 *newip_sin_family = AF_UNSPEC;
1511 max_score = -1;
1512
1513 /* Select an IP regarding configuration preference.
1514 * Top priority is the preferred network ip version,
1515 * second priority is the preferred network.
1516 * the last priority is the currently used IP,
1517 *
1518 * For these three priorities, a score is calculated. The
1519 * weight are:
1520 * 8 - preferred ip version.
1521 * 4 - preferred network.
1522 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1523 * 1 - current ip.
1524 * The result with the biggest score is returned.
1525 */
1526
Willy Tarreau7893ae12021-10-21 07:39:57 +02001527 for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001528 void *ip;
1529 unsigned char ip_type;
1530
Willy Tarreau7893ae12021-10-21 07:39:57 +02001531 record = eb32_entry(eb32, typeof(*record), link);
Emeric Brunc9437992021-02-12 19:42:55 +01001532 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001533 ip_type = AF_INET;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001534 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001535 }
1536 else if (record->type == DNS_RTYPE_AAAA) {
1537 ip_type = AF_INET6;
Willy Tarreaucc8fd4c2021-10-14 22:52:04 +02001538 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001539 }
1540 else
1541 continue;
1542 score = 0;
1543
1544 /* Check for preferred ip protocol. */
1545 if (ip_type == family_priority)
1546 score += 8;
1547
1548 /* Check for preferred network. */
1549 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1550
1551 /* Compare only the same addresses class. */
1552 if (resolv_opts->pref_net[j].family != ip_type)
1553 continue;
1554
1555 if ((ip_type == AF_INET &&
1556 in_net_ipv4(ip,
1557 &resolv_opts->pref_net[j].mask.in4,
1558 &resolv_opts->pref_net[j].addr.in4)) ||
1559 (ip_type == AF_INET6 &&
1560 in_net_ipv6(ip,
1561 &resolv_opts->pref_net[j].mask.in6,
1562 &resolv_opts->pref_net[j].addr.in6))) {
1563 score += 4;
1564 break;
1565 }
1566 }
1567
1568 /* Check if the IP found in the record is already affected to a
1569 * member of a group. If not, the score should be incremented
1570 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001571 if (owner) {
1572 struct server *srv;
1573 int already_used = 0;
1574
1575 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1576 if (srv == owner)
1577 continue;
1578 if (srv->proxy == owner->proxy) {
1579 already_used = 1;
1580 break;
1581 }
1582 }
1583 if (already_used) {
1584 if (!allowed_duplicated_ip) {
1585 continue;
1586 }
1587 }
1588 else {
1589 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001590 }
1591 } else {
1592 score += 2;
1593 }
1594
1595 /* Check for current ip matching. */
1596 if (ip_type == currentip_sin_family &&
1597 ((currentip_sin_family == AF_INET &&
1598 !memcmp(ip, currentip, 4)) ||
1599 (currentip_sin_family == AF_INET6 &&
1600 !memcmp(ip, currentip, 16)))) {
1601 score++;
1602 currentip_sel = 1;
1603 }
1604 else
1605 currentip_sel = 0;
1606
1607 /* Keep the address if the score is better than the previous
1608 * score. The maximum score is 15, if this value is reached, we
1609 * break the parsing. Implicitly, this score is reached the ip
1610 * selected is the current ip. */
1611 if (score > max_score) {
1612 if (ip_type == AF_INET)
1613 newip4 = ip;
1614 else
1615 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001616 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001617 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001618 if (score == 15) {
1619 /* this was not registered on the current record but it matches
1620 * let's fix it (it may comes from state file */
1621 if (owner)
1622 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001623 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001624 }
Emeric Brunc9437992021-02-12 19:42:55 +01001625 max_score = score;
1626 }
1627 } /* list for each record entries */
1628
1629 /* No IP found in the response */
1630 if (!newip4 && !newip6)
1631 return RSLV_UPD_NO_IP_FOUND;
1632
1633 /* Case when the caller looks first for an IPv4 address */
1634 if (family_priority == AF_INET) {
1635 if (newip4) {
1636 *newip = newip4;
1637 *newip_sin_family = AF_INET;
1638 }
1639 else if (newip6) {
1640 *newip = newip6;
1641 *newip_sin_family = AF_INET6;
1642 }
Emeric Brunc9437992021-02-12 19:42:55 +01001643 }
1644 /* Case when the caller looks first for an IPv6 address */
1645 else if (family_priority == AF_INET6) {
1646 if (newip6) {
1647 *newip = newip6;
1648 *newip_sin_family = AF_INET6;
1649 }
1650 else if (newip4) {
1651 *newip = newip4;
1652 *newip_sin_family = AF_INET;
1653 }
Emeric Brunc9437992021-02-12 19:42:55 +01001654 }
1655 /* Case when the caller have no preference (we prefer IPv6) */
1656 else if (family_priority == AF_UNSPEC) {
1657 if (newip6) {
1658 *newip = newip6;
1659 *newip_sin_family = AF_INET6;
1660 }
1661 else if (newip4) {
1662 *newip = newip4;
1663 *newip_sin_family = AF_INET;
1664 }
Emeric Brunc9437992021-02-12 19:42:55 +01001665 }
1666
Emeric Brunbd78c912021-06-11 10:08:05 +02001667 /* the ip of this record was chosen for the server */
1668 if (owner && found_record) {
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001669 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunbd78c912021-06-11 10:08:05 +02001670 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1671 }
1672
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001673 eb32 = eb32_first(&r_res->answer_tree);
1674 if (eb32) {
Emeric Brunc9437992021-02-12 19:42:55 +01001675 /* Move the first record to the end of the list, for internal
Willy Tarreau7893ae12021-10-21 07:39:57 +02001676 * round robin.
1677 */
Willy Tarreaudbb0bb52021-10-22 08:34:14 +02001678 eb32_delete(eb32);
1679 eb32_insert(&r_res->answer_tree, eb32);
Emeric Brunc9437992021-02-12 19:42:55 +01001680 }
Christopher Fauletd7bb2342021-06-24 15:16:48 +02001681
1682 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001683}
1684
Willy Tarreau875ee702021-10-14 08:05:25 +02001685/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001686 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001687 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1688 * null-terminated. <str> must be allocated large enough to contain a full host
1689 * name plus the trailing zero, and the allocated size must be passed in
1690 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001691 *
Willy Tarreau875ee702021-10-14 08:05:25 +02001692 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001693 * <str> (including the terminating null byte).
1694 */
1695int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1696{
1697 char *ptr;
1698 int i, sz;
1699
Willy Tarreau875ee702021-10-14 08:05:25 +02001700 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001701 return -1;
1702
1703 ptr = str;
Willy Tarreau875ee702021-10-14 08:05:25 +02001704 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001705 sz = dn[i];
1706 if (i)
1707 *ptr++ = '.';
Willy Tarreau814889c2021-10-15 07:45:38 +02001708 /* copy the string at i+1 to lower case */
1709 for (; sz > 0; sz--)
1710 *(ptr++) = tolower(dn[++i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001711 }
1712 *ptr++ = '\0';
1713 return (ptr - str);
1714}
1715
1716/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1717 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001718 * <str> contains the input string that is <str_len> bytes long (trailing zero
1719 * not needed). <dn> buffer must be allocated large enough to contain the
1720 * encoded string and a trailing zero, so it must be at least str_len+2, and
1721 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001722 *
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001723 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001724 * <dn> (excluding the terminating null byte).
1725 */
1726int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1727{
1728 int i, offset;
1729
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001730 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001731 return -1;
1732
1733 /* First byte of dn will be used to store the length of the first
1734 * label */
1735 offset = 0;
1736 for (i = 0; i < str_len; ++i) {
1737 if (str[i] == '.') {
1738 /* 2 or more consecutive dots is invalid */
1739 if (i == offset)
1740 return -1;
1741
1742 /* ignore trailing dot */
Christopher Faulet0a82cf42022-01-28 17:47:57 +01001743 if (i + 1 == str_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001744 break;
Emeric Brunc9437992021-02-12 19:42:55 +01001745
1746 dn[offset] = (i - offset);
1747 offset = i+1;
1748 continue;
1749 }
Willy Tarreau814889c2021-10-15 07:45:38 +02001750 dn[i+1] = tolower(str[i]);
Emeric Brunc9437992021-02-12 19:42:55 +01001751 }
Willy Tarreaubf9498a2021-10-14 07:49:49 +02001752 dn[offset] = i - offset;
Willy Tarreau7b232f12021-10-15 08:09:25 +02001753 dn[i+1] = '\0';
1754 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001755}
1756
1757/* Validates host name:
1758 * - total size
1759 * - each label size individually
1760 * returns:
1761 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1762 * 1 when no error. <err> is left unaffected.
1763 */
1764int resolv_hostname_validation(const char *string, char **err)
1765{
1766 int i;
1767
1768 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1769 if (err)
1770 *err = DNS_TOO_LONG_FQDN;
1771 return 0;
1772 }
1773
1774 while (*string) {
1775 i = 0;
1776 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1777 if (!(*string == '-' || *string == '_' ||
1778 (*string >= 'a' && *string <= 'z') ||
1779 (*string >= 'A' && *string <= 'Z') ||
1780 (*string >= '0' && *string <= '9'))) {
1781 if (err)
1782 *err = DNS_INVALID_CHARACTER;
1783 return 0;
1784 }
1785 i++;
1786 string++;
1787 }
1788
1789 if (!(*string))
1790 break;
1791
1792 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1793 if (err)
1794 *err = DNS_LABEL_TOO_LONG;
1795 return 0;
1796 }
1797
1798 string++;
1799 }
1800 return 1;
1801}
1802
1803/* Picks up an available resolution from the different resolution list
1804 * associated to a resolvers section, in this order:
1805 * 1. check in resolutions.curr for the same hostname and query_type
1806 * 2. check in resolutions.wait for the same hostname and query_type
1807 * 3. Get a new resolution from resolution pool
1808 *
1809 * Returns an available resolution, NULL if none found.
1810 */
1811static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1812 char **hostname_dn, int hostname_dn_len,
1813 int query_type)
1814{
1815 struct resolv_resolution *res;
1816
1817 if (!*hostname_dn)
1818 goto from_pool;
1819
1820 /* Search for same hostname and query type in resolutions.curr */
1821 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1822 if (!res->hostname_dn)
1823 continue;
1824 if ((query_type == res->prefered_query_type) &&
1825 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001826 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001827 return res;
1828 }
1829
1830 /* Search for same hostname and query type in resolutions.wait */
1831 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1832 if (!res->hostname_dn)
1833 continue;
1834 if ((query_type == res->prefered_query_type) &&
1835 hostname_dn_len == res->hostname_dn_len &&
Willy Tarreau75cc6532021-10-15 08:53:44 +02001836 memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
Emeric Brunc9437992021-02-12 19:42:55 +01001837 return res;
1838 }
1839
1840 from_pool:
1841 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001842 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001843 if (res) {
Emeric Brunc9437992021-02-12 19:42:55 +01001844 res->resolvers = resolvers;
1845 res->uuid = resolution_uuid;
1846 res->status = RSLV_STATUS_NONE;
1847 res->step = RSLV_STEP_NONE;
1848 res->last_valid = now_ms;
1849
1850 LIST_INIT(&res->requesters);
Willy Tarreau7893ae12021-10-21 07:39:57 +02001851 res->response.answer_tree = EB_ROOT;
Emeric Brunc9437992021-02-12 19:42:55 +01001852
1853 res->prefered_query_type = query_type;
1854 res->query_type = query_type;
1855 res->hostname_dn = *hostname_dn;
1856 res->hostname_dn_len = hostname_dn_len;
1857
1858 ++resolution_uuid;
1859
1860 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001861 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001862 }
1863 return res;
1864}
1865
Willy Tarreau2acc1602021-10-19 11:16:11 +02001866/* deletes and frees all answer_items from the resolution's answer_list */
1867static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001868{
Willy Tarreau7893ae12021-10-21 07:39:57 +02001869 struct eb32_node *eb32, *eb32_back;
1870 struct resolv_answer_item *item;
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001871
Willy Tarreau7893ae12021-10-21 07:39:57 +02001872 for (eb32 = eb32_first(&resolution->response.answer_tree);
1873 eb32 && (eb32_back = eb32_next(eb32), 1);
1874 eb32 = eb32_back) {
1875 item = eb32_entry(eb32, typeof(*item), link);
1876 eb32_delete(&item->link);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001877 pool_free(resolv_answer_item_pool, item->ar_item);
1878 pool_free(resolv_answer_item_pool, item);
1879 }
1880}
1881
Emeric Brunc9437992021-02-12 19:42:55 +01001882/* Releases a resolution from its requester(s) and move it back to the pool */
1883static void resolv_free_resolution(struct resolv_resolution *resolution)
1884{
1885 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001886
1887 /* clean up configuration */
1888 resolv_reset_resolution(resolution);
1889 resolution->hostname_dn = NULL;
1890 resolution->hostname_dn_len = 0;
1891
1892 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02001893 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001894 req->resolution = NULL;
1895 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001896 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau25e01092021-10-19 11:17:33 +02001897
Willy Tarreauaae73202021-10-19 22:01:36 +02001898 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001899 pool_free(resolv_resolution_pool, resolution);
1900}
1901
Willy Tarreau239675e2021-10-19 11:59:25 +02001902/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1903 * and makes it owned by this obj_type, with the proposed callback and error
1904 * callback. On success, *req is assigned the allocated requester. Returns
1905 * NULL on allocation failure.
1906 */
1907static struct resolv_requester *
1908resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1909 int (*cb)(struct resolv_requester *, struct dns_counters *),
1910 int (*err_cb)(struct resolv_requester *, int))
1911{
1912 struct resolv_requester *tmp;
1913
1914 if (*req)
1915 return *req;
1916
1917 tmp = pool_alloc(resolv_requester_pool);
1918 if (!tmp)
1919 goto end;
1920
1921 LIST_INIT(&tmp->list);
1922 tmp->owner = owner;
1923 tmp->resolution = NULL;
1924 tmp->requester_cb = cb;
1925 tmp->requester_error_cb = err_cb;
1926 *req = tmp;
1927 end:
1928 return tmp;
1929}
1930
Emeric Brunc9437992021-02-12 19:42:55 +01001931/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001932 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001933 */
1934int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1935{
1936 struct resolv_resolution *res = NULL;
1937 struct resolv_requester *req;
1938 struct resolvers *resolvers;
1939 struct server *srv = NULL;
1940 struct resolv_srvrq *srvrq = NULL;
1941 struct stream *stream = NULL;
1942 char **hostname_dn;
1943 int hostname_dn_len, query_type;
1944
Christopher Faulet9ed1a062021-11-02 16:25:05 +01001945 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001946 switch (requester_type) {
1947 case OBJ_TYPE_SERVER:
1948 srv = (struct server *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001949
1950 if (!requester_locked)
1951 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1952
1953 req = resolv_get_requester(&srv->resolv_requester,
1954 &srv->obj_type,
1955 snr_resolution_cb,
1956 snr_resolution_error_cb);
1957
1958 if (!requester_locked)
1959 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1960
1961 if (!req)
1962 goto err;
1963
Emeric Brunc9437992021-02-12 19:42:55 +01001964 hostname_dn = &srv->hostname_dn;
1965 hostname_dn_len = srv->hostname_dn_len;
1966 resolvers = srv->resolvers;
1967 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1968 ? DNS_RTYPE_A
1969 : DNS_RTYPE_AAAA);
1970 break;
1971
1972 case OBJ_TYPE_SRVRQ:
1973 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001974
1975 req = resolv_get_requester(&srvrq->requester,
1976 &srvrq->obj_type,
1977 snr_resolution_cb,
1978 srvrq_resolution_error_cb);
1979 if (!req)
1980 goto err;
1981
Emeric Brunc9437992021-02-12 19:42:55 +01001982 hostname_dn = &srvrq->hostname_dn;
1983 hostname_dn_len = srvrq->hostname_dn_len;
1984 resolvers = srvrq->resolvers;
1985 query_type = DNS_RTYPE_SRV;
1986 break;
1987
1988 case OBJ_TYPE_STREAM:
1989 stream = (struct stream *)requester;
Willy Tarreau239675e2021-10-19 11:59:25 +02001990
1991 req = resolv_get_requester(&stream->resolv_ctx.requester,
1992 &stream->obj_type,
1993 act_resolution_cb,
1994 act_resolution_error_cb);
1995 if (!req)
1996 goto err;
1997
Emeric Brunc9437992021-02-12 19:42:55 +01001998 hostname_dn = &stream->resolv_ctx.hostname_dn;
1999 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2000 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2001 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2002 ? DNS_RTYPE_A
2003 : DNS_RTYPE_AAAA);
2004 break;
2005 default:
2006 goto err;
2007 }
2008
2009 /* Get a resolution from the resolvers' wait queue or pool */
2010 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2011 goto err;
2012
Willy Tarreau239675e2021-10-19 11:59:25 +02002013 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002014
Willy Tarreau2b718102021-04-21 07:32:39 +02002015 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002016 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002017 return 0;
2018
2019 err:
2020 if (res && LIST_ISEMPTY(&res->requesters))
2021 resolv_free_resolution(res);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002022 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002023 return -1;
2024}
2025
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002026/* This function removes all server/srvrq references on answer items. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002027void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun34067662021-06-11 10:48:45 +02002028{
Willy Tarreau7893ae12021-10-21 07:39:57 +02002029 struct eb32_node *eb32, *eb32_back;
2030 struct resolv_answer_item *item;
Emeric Brun34067662021-06-11 10:48:45 +02002031 struct server *srv, *srvback;
2032 struct resolv_srvrq *srvrq;
2033
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002034 enter_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002035 if ((srv = objt_server(req->owner)) != NULL) {
2036 LIST_DEL_INIT(&srv->ip_rec_item);
2037 }
2038 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
Willy Tarreau7893ae12021-10-21 07:39:57 +02002039 for (eb32 = eb32_first(&res->response.answer_tree);
2040 eb32 && (eb32_back = eb32_next(eb32), 1);
2041 eb32 = eb32_back) {
2042 item = eb32_entry(eb32, typeof(*item), link);
Emeric Brun34067662021-06-11 10:48:45 +02002043 if (item->type == DNS_RTYPE_SRV) {
2044 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet11c6c392021-06-15 16:08:48 +02002045 if (srv->srvrq == srvrq)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002046 resolv_srvrq_cleanup_srv(srv);
Emeric Brun34067662021-06-11 10:48:45 +02002047 }
2048 }
2049 }
2050 }
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002051 leave_resolver_code();
Emeric Brun34067662021-06-11 10:48:45 +02002052}
2053
Emeric Brunc9437992021-02-12 19:42:55 +01002054/* Removes a requester from a DNS resolution. It takes takes care of all the
2055 * consequences. It also cleans up some parameters from the requester.
2056 */
Willy Tarreau6878f802021-10-20 14:07:31 +02002057static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002058{
2059 struct resolv_resolution *res;
2060 struct resolv_requester *req;
2061
2062 /* Nothing to do */
2063 if (!requester || !requester->resolution)
2064 return;
2065 res = requester->resolution;
2066
2067 /* Clean up the requester */
Willy Tarreauaae73202021-10-19 22:01:36 +02002068 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002069 requester->resolution = NULL;
2070
Christopher Fauletbce6db62021-10-29 10:38:15 +02002071 /* remove ref from the resolution answer item list to the requester */
2072 resolv_detach_from_resolution_answer_items(res, requester);
2073
Emeric Brunc9437992021-02-12 19:42:55 +01002074 /* We need to find another requester linked on this resolution */
2075 if (!LIST_ISEMPTY(&res->requesters))
2076 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2077 else {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002078 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002079 return;
2080 }
2081
2082 /* Move hostname_dn related pointers to the next requester */
2083 switch (obj_type(req->owner)) {
2084 case OBJ_TYPE_SERVER:
2085 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2086 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2087 break;
2088 case OBJ_TYPE_SRVRQ:
2089 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2090 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2091 break;
2092 case OBJ_TYPE_STREAM:
2093 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2094 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2095 break;
2096 default:
2097 res->hostname_dn = NULL;
2098 res->hostname_dn_len = 0;
2099 break;
2100 }
2101}
2102
Willy Tarreauf766ec62021-10-18 16:46:38 +02002103/* The public version of the function above that deals with the death row. */
Willy Tarreau6878f802021-10-20 14:07:31 +02002104void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreauf766ec62021-10-18 16:46:38 +02002105{
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002106 enter_resolver_code();
Willy Tarreau6878f802021-10-20 14:07:31 +02002107 _resolv_unlink_resolution(requester);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002108 leave_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002109}
2110
Emeric Brunc9437992021-02-12 19:42:55 +01002111/* Called when a network IO is generated on a name server socket for an incoming
2112 * packet. It performs the following actions:
2113 * - check if the packet requires processing (not outdated resolution)
2114 * - ensure the DNS packet received is valid and call requester's callback
2115 * - call requester's error callback if invalid response
2116 * - check the dn_name in the packet against the one sent
2117 */
2118static int resolv_process_responses(struct dns_nameserver *ns)
2119{
2120 struct dns_counters *tmpcounters;
2121 struct resolvers *resolvers;
2122 struct resolv_resolution *res;
Emeric Brunc9437992021-02-12 19:42:55 +01002123 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2124 unsigned char *bufend;
2125 int buflen, dns_resp;
2126 int max_answer_records;
2127 unsigned short query_id;
2128 struct eb32_node *eb;
2129 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002130 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002131
2132 resolvers = ns->parent;
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002133 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002134 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2135
2136 /* process all pending input messages */
2137 while (1) {
2138 /* read message received */
2139 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2140 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2141 break;
2142 }
2143
2144 /* message too big */
2145 if (buflen > resolvers->accepted_payload_size) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002146 ns->counters->app.resolver.too_big++;
Emeric Brunc9437992021-02-12 19:42:55 +01002147 continue;
2148 }
2149
2150 /* initializing variables */
2151 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2152
2153 /* read the query id from the packet (16 bits) */
2154 if (buf + 2 > bufend) {
Emeric Brund174f0e2021-10-29 17:30:41 +02002155 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002156 continue;
2157 }
2158 query_id = resolv_response_get_query_id(buf);
2159
2160 /* search the query_id in the pending resolution tree */
2161 eb = eb32_lookup(&resolvers->query_ids, query_id);
2162 if (eb == NULL) {
2163 /* unknown query id means an outdated response and can be safely ignored */
Emeric Brund174f0e2021-10-29 17:30:41 +02002164 ns->counters->app.resolver.outdated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002165 continue;
2166 }
2167
2168 /* known query id means a resolution in progress */
2169 res = eb32_entry(eb, struct resolv_resolution, qid);
2170 /* number of responses received */
2171 res->nb_responses++;
2172
2173 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2174 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2175
2176 switch (dns_resp) {
2177 case RSLV_RESP_VALID:
2178 break;
2179
2180 case RSLV_RESP_INVALID:
2181 case RSLV_RESP_QUERY_COUNT_ERROR:
2182 case RSLV_RESP_WRONG_NAME:
2183 res->status = RSLV_STATUS_INVALID;
Emeric Brund174f0e2021-10-29 17:30:41 +02002184 ns->counters->app.resolver.invalid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002185 break;
2186
2187 case RSLV_RESP_NX_DOMAIN:
2188 res->status = RSLV_STATUS_NX;
Emeric Brund174f0e2021-10-29 17:30:41 +02002189 ns->counters->app.resolver.nx++;
Emeric Brunc9437992021-02-12 19:42:55 +01002190 break;
2191
2192 case RSLV_RESP_REFUSED:
2193 res->status = RSLV_STATUS_REFUSED;
Emeric Brund174f0e2021-10-29 17:30:41 +02002194 ns->counters->app.resolver.refused++;
Emeric Brunc9437992021-02-12 19:42:55 +01002195 break;
2196
2197 case RSLV_RESP_ANCOUNT_ZERO:
2198 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002199 ns->counters->app.resolver.any_err++;
Emeric Brunc9437992021-02-12 19:42:55 +01002200 break;
2201
2202 case RSLV_RESP_CNAME_ERROR:
2203 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002204 ns->counters->app.resolver.cname_error++;
Emeric Brunc9437992021-02-12 19:42:55 +01002205 break;
2206
2207 case RSLV_RESP_TRUNCATED:
2208 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002209 ns->counters->app.resolver.truncated++;
Emeric Brunc9437992021-02-12 19:42:55 +01002210 break;
2211
2212 case RSLV_RESP_NO_EXPECTED_RECORD:
2213 case RSLV_RESP_ERROR:
2214 case RSLV_RESP_INTERNAL:
2215 res->status = RSLV_STATUS_OTHER;
Emeric Brund174f0e2021-10-29 17:30:41 +02002216 ns->counters->app.resolver.other++;
Emeric Brunc9437992021-02-12 19:42:55 +01002217 break;
2218 }
2219
2220 /* Wait all nameservers response to handle errors */
2221 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2222 continue;
2223
2224 /* Process error codes */
2225 if (dns_resp != RSLV_RESP_VALID) {
2226 if (res->prefered_query_type != res->query_type) {
2227 /* The fallback on the query type was already performed,
2228 * so check the try counter. If it falls to 0, we can
2229 * report an error. Else, wait the next attempt. */
2230 if (!res->try)
2231 goto report_res_error;
2232 }
2233 else {
2234 /* Fallback from A to AAAA or the opposite and re-send
2235 * the resolution immediately. try counter is not
2236 * decremented. */
2237 if (res->prefered_query_type == DNS_RTYPE_A) {
2238 res->query_type = DNS_RTYPE_AAAA;
2239 resolv_send_query(res);
2240 }
2241 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2242 res->query_type = DNS_RTYPE_A;
2243 resolv_send_query(res);
2244 }
2245 }
2246 continue;
2247 }
2248
Emeric Brunc9437992021-02-12 19:42:55 +01002249 /* So the resolution succeeded */
2250 res->status = RSLV_STATUS_VALID;
2251 res->last_valid = now_ms;
Emeric Brund174f0e2021-10-29 17:30:41 +02002252 ns->counters->app.resolver.valid++;
Emeric Brunc9437992021-02-12 19:42:55 +01002253 goto report_res_success;
2254
2255 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002256 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002257 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002258 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2259 if (!keep_answer_items)
2260 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002261 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002262 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002263 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002264 continue;
2265
2266 report_res_success:
2267 /* Only the 1rst requester s managed by the server, others are
2268 * from the cache */
2269 tmpcounters = ns->counters;
2270 list_for_each_entry(req, &res->requesters, list) {
2271 struct server *s = objt_server(req->owner);
2272
2273 if (s)
2274 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2275 req->requester_cb(req, tmpcounters);
2276 if (s)
2277 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2278 tmpcounters = NULL;
2279 }
2280
2281 resolv_reset_resolution(res);
Willy Tarreauaae73202021-10-19 22:01:36 +02002282 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002283 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002284 continue;
2285 }
2286 resolv_update_resolvers_timeout(resolvers);
2287 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002288 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002289 return buflen;
2290}
2291
2292/* Processes DNS resolution. First, it checks the active list to detect expired
2293 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2294 * checks the wait list to trigger new resolutions.
2295 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002296static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002297{
2298 struct resolvers *resolvers = context;
2299 struct resolv_resolution *res, *resback;
2300 int exp;
2301
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002302 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002303 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2304
Willy Tarreauf766ec62021-10-18 16:46:38 +02002305 /* Handle all expired resolutions from the active list. Elements that
2306 * need to be removed will in fact be moved to the death_row. Other
2307 * ones will be handled normally.
2308 */
2309
Willy Tarreauf766ec62021-10-18 16:46:38 +02002310 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2311 while (&res->list != &resolvers->resolutions.curr) {
2312 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2313
Christopher Faulet0efc0992021-03-11 18:09:53 +01002314 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002315 abort_resolution(res);
2316 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002317 continue;
2318 }
2319
Emeric Brunc9437992021-02-12 19:42:55 +01002320 /* When we find the first resolution in the future, then we can
2321 * stop here */
2322 exp = tick_add(res->last_query, resolvers->timeout.retry);
2323 if (!tick_is_expired(exp, now_ms))
2324 break;
2325
2326 /* If current resolution has been tried too many times and
2327 * finishes in timeout we update its status and remove it from
2328 * the list */
2329 if (!res->try) {
2330 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002331 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002332
2333 /* Notify the result to the requesters */
2334 if (!res->nb_responses)
2335 res->status = RSLV_STATUS_TIMEOUT;
2336 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002337 keep_answer_items |= req->requester_error_cb(req, res->status);
2338 if (!keep_answer_items)
2339 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002340
2341 /* Clean up resolution info and remove it from the
2342 * current list */
2343 resolv_reset_resolution(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002344
2345 /* subsequent entries might have been deleted here */
2346 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreauaae73202021-10-19 22:01:36 +02002347 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002348 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002349 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002350 }
2351 else {
2352 /* Otherwise resend the DNS query and requeue the resolution */
2353 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2354 /* No response received (a real timeout) or fallback already done */
2355 res->query_type = res->prefered_query_type;
2356 res->try--;
2357 }
2358 else {
2359 /* Fallback from A to AAAA or the opposite and re-send
2360 * the resolution immediately. try counter is not
2361 * decremented. */
2362 if (res->prefered_query_type == DNS_RTYPE_A)
2363 res->query_type = DNS_RTYPE_AAAA;
2364 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2365 res->query_type = DNS_RTYPE_A;
2366 else
2367 res->try--;
2368 }
2369 resolv_send_query(res);
Willy Tarreauf766ec62021-10-18 16:46:38 +02002370 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2371 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002372 }
2373 }
2374
2375 /* Handle all resolutions in the wait list */
2376 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002377 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreauf766ec62021-10-18 16:46:38 +02002378 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002379 continue;
2380 }
2381
Emeric Brunc9437992021-02-12 19:42:55 +01002382 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2383 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2384 continue;
2385
2386 if (resolv_run_resolution(res) != 1) {
2387 res->last_resolution = now_ms;
Willy Tarreauaae73202021-10-19 22:01:36 +02002388 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002389 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002390 }
2391 }
Emeric Brunc9437992021-02-12 19:42:55 +01002392 resolv_update_resolvers_timeout(resolvers);
2393 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002394
2395 /* now we can purge all queued deletions */
2396 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002397 return t;
2398}
2399
2400/* Release memory allocated by DNS */
2401static void resolvers_deinit(void)
2402{
2403 struct resolvers *resolvers, *resolversback;
2404 struct dns_nameserver *ns, *nsback;
2405 struct resolv_resolution *res, *resback;
2406 struct resolv_requester *req, *reqback;
2407 struct resolv_srvrq *srvrq, *srvrqback;
2408
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002409 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002410 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2411 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2412 free(ns->id);
2413 free((char *)ns->conf.file);
2414 if (ns->dgram) {
2415 if (ns->dgram->conn.t.sock.fd != -1) {
2416 fd_delete(ns->dgram->conn.t.sock.fd);
2417 close(ns->dgram->conn.t.sock.fd);
2418 }
2419 if (ns->dgram->ring_req)
2420 ring_free(ns->dgram->ring_req);
2421 free(ns->dgram);
2422 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002423 if (ns->stream) {
2424 if (ns->stream->ring_req)
2425 ring_free(ns->stream->ring_req);
2426 if (ns->stream->task_req)
2427 task_destroy(ns->stream->task_req);
2428 if (ns->stream->task_rsp)
2429 task_destroy(ns->stream->task_rsp);
2430 free(ns->stream);
2431 }
Willy Tarreauaae73202021-10-19 22:01:36 +02002432 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002433 EXTRA_COUNTERS_FREE(ns->extra_counters);
2434 free(ns);
2435 }
2436
2437 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2438 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002439 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002440 pool_free(resolv_requester_pool, req);
2441 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002442 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002443 }
2444
2445 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2446 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreauaae73202021-10-19 22:01:36 +02002447 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002448 pool_free(resolv_requester_pool, req);
2449 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002450 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002451 }
2452
2453 free(resolvers->id);
2454 free((char *)resolvers->conf.file);
2455 task_destroy(resolvers->t);
Willy Tarreauaae73202021-10-19 22:01:36 +02002456 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002457 free(resolvers);
2458 }
2459
2460 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2461 free(srvrq->name);
2462 free(srvrq->hostname_dn);
Willy Tarreauaae73202021-10-19 22:01:36 +02002463 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002464 free(srvrq);
2465 }
Willy Tarreauf766ec62021-10-18 16:46:38 +02002466
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002467 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002468}
2469
2470/* Finalizes the DNS configuration by allocating required resources and checking
2471 * live parameters.
2472 * Returns 0 on success, ERR_* flags otherwise.
2473 */
2474static int resolvers_finalize_config(void)
2475{
2476 struct resolvers *resolvers;
2477 struct proxy *px;
2478 int err_code = 0;
2479
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002480 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002481
Emeric Brunc9437992021-02-12 19:42:55 +01002482 /* allocate pool of resolution per resolvers */
2483 list_for_each_entry(resolvers, &sec_resolvers, list) {
2484 struct dns_nameserver *ns;
2485 struct task *t;
2486
2487 /* Check if we can create the socket with nameservers info */
2488 list_for_each_entry(ns, &resolvers->nameservers, list) {
2489 int fd;
2490
2491 if (ns->dgram) {
2492 /* Check nameserver info */
2493 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002494 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002495 resolvers->id, ns->id);
2496 err_code |= (ERR_ALERT|ERR_ABORT);
2497 continue;
2498 }
2499 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 +02002500 ha_alert("resolvers '%s': can't connect socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002501 resolvers->id, ns->id);
2502 close(fd);
2503 err_code |= (ERR_ALERT|ERR_ABORT);
2504 continue;
2505 }
2506 close(fd);
2507 }
2508 }
2509
2510 /* Create the task associated to the resolvers section */
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002511 if ((t = task_new_anywhere()) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002512 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002513 err_code |= (ERR_ALERT|ERR_ABORT);
2514 goto err;
2515 }
2516
2517 /* Update task's parameters */
2518 t->process = process_resolvers;
2519 t->context = resolvers;
2520 resolvers->t = t;
2521 task_wakeup(t, TASK_WOKEN_INIT);
2522 }
2523
2524 for (px = proxies_list; px; px = px->next) {
2525 struct server *srv;
2526
2527 for (srv = px->srv; srv; srv = srv->next) {
2528 struct resolvers *resolvers;
2529
2530 if (!srv->resolvers_id)
2531 continue;
2532
2533 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002534 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002535 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2536 err_code |= (ERR_ALERT|ERR_ABORT);
2537 continue;
2538 }
2539 srv->resolvers = resolvers;
Christopher Fauletdcac4182021-06-15 16:17:17 +02002540 srv->srvrq_check = NULL;
2541 if (srv->srvrq) {
2542 if (!srv->srvrq->resolvers) {
2543 srv->srvrq->resolvers = srv->resolvers;
2544 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2545 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
2546 proxy_type_str(px), px->id, srv->id);
2547 err_code |= (ERR_ALERT|ERR_ABORT);
2548 continue;
2549 }
2550 }
Emeric Brunc9437992021-02-12 19:42:55 +01002551
Willy Tarreaubeeabf52021-10-01 18:23:30 +02002552 srv->srvrq_check = task_new_anywhere();
Christopher Fauletdcac4182021-06-15 16:17:17 +02002553 if (!srv->srvrq_check) {
2554 ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002555 proxy_type_str(px), px->id, srv->id);
2556 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Fauletdcac4182021-06-15 16:17:17 +02002557 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002558 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002559 srv->srvrq_check->process = resolv_srvrq_expire_task;
2560 srv->srvrq_check->context = srv;
2561 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002562 }
Christopher Fauletdcac4182021-06-15 16:17:17 +02002563 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002564 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002565 proxy_type_str(px), px->id, srv->id);
2566 err_code |= (ERR_ALERT|ERR_ABORT);
2567 continue;
2568 }
Amaury Denoyelledd565202021-08-26 15:35:59 +02002569
2570 srv->flags |= SRV_F_NON_PURGEABLE;
Emeric Brunc9437992021-02-12 19:42:55 +01002571 }
2572 }
2573
2574 if (err_code & (ERR_ALERT|ERR_ABORT))
2575 goto err;
2576
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002577 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002578 return err_code;
2579 err:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002580 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002581 resolvers_deinit();
2582 return err_code;
2583
2584}
2585
Christopher Faulet908628c2022-03-25 16:43:49 +01002586static int stats_dump_resolv_to_buffer(struct conn_stream *cs,
Emeric Brunc9437992021-02-12 19:42:55 +01002587 struct dns_nameserver *ns,
2588 struct field *stats, size_t stats_count,
2589 struct list *stat_modules)
2590{
Christopher Faulet908628c2022-03-25 16:43:49 +01002591 struct appctx *appctx = __cs_appctx(cs);
2592 struct channel *rep = cs_ic(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002593 struct stats_module *mod;
2594 size_t idx = 0;
2595
2596 memset(stats, 0, sizeof(struct field) * stats_count);
2597
2598 list_for_each_entry(mod, stat_modules, list) {
2599 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2600
2601 mod->fill_stats(counters, stats + idx);
2602 idx += mod->stats_count;
2603 }
2604
2605 if (!stats_dump_one_line(stats, idx, appctx))
2606 return 0;
2607
2608 if (!stats_putchk(rep, NULL, &trash))
2609 goto full;
2610
2611 return 1;
2612
2613 full:
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002614 cs_rx_room_rdy(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002615 return 0;
2616}
2617
2618/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2619 * as a pointer to the current nameserver.
2620 */
Christopher Faulet908628c2022-03-25 16:43:49 +01002621int stats_dump_resolvers(struct conn_stream *cs,
Emeric Brunc9437992021-02-12 19:42:55 +01002622 struct field *stats, size_t stats_count,
2623 struct list *stat_modules)
2624{
Christopher Faulet908628c2022-03-25 16:43:49 +01002625 struct appctx *appctx = __cs_appctx(cs);
2626 struct channel *rep = cs_ic(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002627 struct resolvers *resolver = appctx->ctx.stats.obj1;
2628 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2629
2630 if (!resolver)
2631 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2632
2633 /* dump resolvers */
2634 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2635 appctx->ctx.stats.obj1 = resolver;
2636
2637 ns = appctx->ctx.stats.obj2 ?
2638 appctx->ctx.stats.obj2 :
2639 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2640
2641 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2642 appctx->ctx.stats.obj2 = ns;
2643
2644 if (buffer_almost_full(&rep->buf))
2645 goto full;
2646
Christopher Faulet908628c2022-03-25 16:43:49 +01002647 if (!stats_dump_resolv_to_buffer(cs, ns,
Emeric Brunc9437992021-02-12 19:42:55 +01002648 stats, stats_count,
2649 stat_modules)) {
2650 return 0;
2651 }
2652 }
2653
2654 appctx->ctx.stats.obj2 = NULL;
2655 }
2656
2657 return 1;
2658
2659 full:
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002660 cs_rx_room_blk(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002661 return 0;
2662}
2663
2664void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2665{
2666 struct resolvers *resolvers;
2667 struct dns_nameserver *ns;
2668 struct stats_module *mod;
2669 void *counters;
2670
2671 list_for_each_entry(mod, stat_modules, list) {
2672 if (!mod->clearable && !clrall)
2673 continue;
2674
2675 list_for_each_entry(resolvers, &sec_resolvers, list) {
2676 list_for_each_entry(ns, &resolvers->nameservers, list) {
2677 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2678 memcpy(counters, mod->counters, mod->counters_size);
2679 }
2680 }
2681 }
2682
2683}
2684
2685int resolv_allocate_counters(struct list *stat_modules)
2686{
2687 struct stats_module *mod;
2688 struct resolvers *resolvers;
2689 struct dns_nameserver *ns;
2690
2691 list_for_each_entry(resolvers, &sec_resolvers, list) {
2692 list_for_each_entry(ns, &resolvers->nameservers, list) {
Emeric Brunf8642ee2021-10-29 17:59:18 +02002693 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
Emeric Brunc9437992021-02-12 19:42:55 +01002694 alloc_failed);
2695
2696 list_for_each_entry(mod, stat_modules, list) {
2697 EXTRA_COUNTERS_ADD(mod,
2698 ns->extra_counters,
2699 mod->counters,
2700 mod->counters_size);
2701 }
2702
2703 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2704
2705 list_for_each_entry(mod, stat_modules, list) {
2706 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2707 mod->counters, mod->counters_size);
2708
2709 /* Store the ns counters pointer */
Emeric Brunf8642ee2021-10-29 17:59:18 +02002710 if (strcmp(mod->name, "resolvers") == 0) {
2711 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
Emeric Brunc9437992021-02-12 19:42:55 +01002712 ns->counters->id = ns->id;
2713 ns->counters->pid = resolvers->id;
2714 }
2715 }
2716 }
2717 }
2718
2719 return 1;
2720
2721alloc_failed:
2722 return 0;
2723}
2724
2725/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2726static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2727{
2728 struct resolvers *presolvers;
2729
2730 if (*args[2]) {
2731 list_for_each_entry(presolvers, &sec_resolvers, list) {
2732 if (strcmp(presolvers->id, args[2]) == 0) {
2733 appctx->ctx.cli.p0 = presolvers;
2734 break;
2735 }
2736 }
2737 if (appctx->ctx.cli.p0 == NULL)
2738 return cli_err(appctx, "Can't find that resolvers section\n");
2739 }
2740 return 0;
2741}
2742
2743/* Dumps counters from all resolvers section and associated name servers. It
2744 * returns 0 if the output buffer is full and it needs to be called again,
2745 * otherwise non-zero. It may limit itself to the resolver pointed to by
2746 * <cli.p0> if it's not null.
2747 */
2748static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2749{
Christopher Faulet908628c2022-03-25 16:43:49 +01002750 struct conn_stream *cs = appctx->owner;
Emeric Brunc9437992021-02-12 19:42:55 +01002751 struct resolvers *resolvers;
2752 struct dns_nameserver *ns;
2753
2754 chunk_reset(&trash);
2755
2756 switch (appctx->st2) {
2757 case STAT_ST_INIT:
2758 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2759 /* fall through */
2760
2761 case STAT_ST_LIST:
2762 if (LIST_ISEMPTY(&sec_resolvers)) {
2763 chunk_appendf(&trash, "No resolvers found\n");
2764 }
2765 else {
2766 list_for_each_entry(resolvers, &sec_resolvers, list) {
2767 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2768 continue;
2769
2770 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2771 list_for_each_entry(ns, &resolvers->nameservers, list) {
2772 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2773 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2774 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
Emeric Brund174f0e2021-10-29 17:30:41 +02002775 chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
2776 chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
2777 chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
2778 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
2779 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
2780 chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
2781 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
2782 chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
2783 chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
2784 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
2785 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
2786 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
2787 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
Emeric Brunc9437992021-02-12 19:42:55 +01002788 }
2789 chunk_appendf(&trash, "\n");
2790 }
2791 }
2792
2793 /* display response */
Christopher Faulet908628c2022-03-25 16:43:49 +01002794 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +01002795 /* let's try again later from this session. We add ourselves into
2796 * this session's users so that it can remove us upon termination.
2797 */
Christopher Fauleta0bdec32022-04-04 07:51:21 +02002798 cs_rx_room_blk(cs);
Emeric Brunc9437992021-02-12 19:42:55 +01002799 return 0;
2800 }
2801 /* fall through */
2802
2803 default:
2804 appctx->st2 = STAT_ST_FIN;
2805 return 1;
2806 }
2807}
2808
2809/* register cli keywords */
2810static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002811 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002812 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2813 {{},}
2814 }
2815};
2816
2817INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2818
2819/*
2820 * Prepare <rule> for hostname resolution.
2821 * Returns -1 in case of any allocation failure, 0 if not.
2822 * On error, a global failure counter is also incremented.
2823 */
Willy Tarreau947ae122021-10-14 08:11:48 +02002824static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002825{
2826 char *hostname_dn;
Willy Tarreau947ae122021-10-14 08:11:48 +02002827 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002828 struct buffer *tmp = get_trash_chunk();
2829
2830 if (!hostname)
2831 return 0;
2832
Emeric Brunc9437992021-02-12 19:42:55 +01002833 hostname_dn = tmp->area;
Willy Tarreaubf9498a2021-10-14 07:49:49 +02002834 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002835 hostname_dn, tmp->size);
2836 if (hostname_dn_len == -1)
2837 goto err;
2838
2839
2840 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2841 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2842 if (!stream->resolv_ctx.hostname_dn)
2843 goto err;
2844
2845 return 0;
2846
2847 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002848 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002849 resolv_failed_resolutions += 1;
2850 return -1;
2851}
2852
2853
2854/*
2855 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2856 */
2857enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2858 struct session *sess, struct stream *s, int flags)
2859{
2860 struct resolv_resolution *resolution;
2861 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002862 struct resolv_requester *req;
2863 struct resolvers *resolvers;
2864 struct resolv_resolution *res;
2865 int exp, locked = 0;
2866 enum act_return ret = ACT_RET_CONT;
2867
2868 resolvers = rule->arg.resolv.resolvers;
2869
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002870 enter_resolver_code();
Willy Tarreauf766ec62021-10-18 16:46:38 +02002871
Emeric Brunc9437992021-02-12 19:42:55 +01002872 /* we have a response to our DNS resolution */
2873 use_cache:
2874 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2875 resolution = s->resolv_ctx.requester->resolution;
2876 if (!locked) {
2877 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2878 locked = 1;
2879 }
2880
2881 if (resolution->step == RSLV_STEP_RUNNING)
2882 goto yield;
2883 if (resolution->step == RSLV_STEP_NONE) {
2884 /* We update the variable only if we have a valid response. */
2885 if (resolution->status == RSLV_STATUS_VALID) {
2886 struct sample smp;
2887 short ip_sin_family = 0;
2888 void *ip = NULL;
2889
2890 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2891 0, &ip, &ip_sin_family, NULL);
2892
2893 switch (ip_sin_family) {
2894 case AF_INET:
2895 smp.data.type = SMP_T_IPV4;
2896 memcpy(&smp.data.u.ipv4, ip, 4);
2897 break;
2898 case AF_INET6:
2899 smp.data.type = SMP_T_IPV6;
2900 memcpy(&smp.data.u.ipv6, ip, 16);
2901 break;
2902 default:
2903 ip = NULL;
2904 }
2905
2906 if (ip) {
2907 smp.px = px;
2908 smp.sess = sess;
2909 smp.strm = s;
2910
2911 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2912 }
2913 }
2914 }
2915
2916 goto release_requester;
2917 }
2918
2919 /* need to configure and start a new DNS resolution */
2920 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2921 if (smp == NULL)
2922 goto end;
2923
Willy Tarreau947ae122021-10-14 08:11:48 +02002924 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002925 goto end; /* on error, ignore the action */
2926
2927 s->resolv_ctx.parent = rule;
2928
2929 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2930 locked = 1;
2931
2932 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2933
2934 /* Check if there is a fresh enough response in the cache of our associated resolution */
2935 req = s->resolv_ctx.requester;
2936 if (!req || !req->resolution)
2937 goto release_requester; /* on error, ignore the action */
2938 res = req->resolution;
2939
2940 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2941 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2942 && !tick_is_expired(exp, now_ms)) {
2943 goto use_cache;
2944 }
2945
2946 resolv_trigger_resolution(s->resolv_ctx.requester);
2947
2948 yield:
2949 if (flags & ACT_OPT_FINAL)
2950 goto release_requester;
2951 ret = ACT_RET_YIELD;
2952
2953 end:
Christopher Faulet9ed1a062021-11-02 16:25:05 +01002954 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002955 if (locked)
2956 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2957 return ret;
2958
2959 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002960 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002961 s->resolv_ctx.hostname_dn_len = 0;
2962 if (s->resolv_ctx.requester) {
Willy Tarreau6878f802021-10-20 14:07:31 +02002963 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01002964 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2965 s->resolv_ctx.requester = NULL;
2966 }
2967 goto end;
2968}
2969
2970static void release_resolv_action(struct act_rule *rule)
2971{
2972 release_sample_expr(rule->arg.resolv.expr);
2973 free(rule->arg.resolv.varname);
2974 free(rule->arg.resolv.resolvers_id);
2975 free(rule->arg.resolv.opts);
2976}
2977
2978
2979/* parse "do-resolve" action
2980 * This action takes the following arguments:
2981 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
2982 *
2983 * - <varName> is the variable name where the result of the DNS resolution will be stored
2984 * (mandatory)
2985 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
2986 * (mandatory)
2987 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
2988 * (optional), defaults to ipv6
2989 * - <expr> is an HAProxy expression used to fetch the name to be resolved
2990 */
2991enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
2992{
2993 int cur_arg;
2994 struct sample_expr *expr;
2995 unsigned int where;
2996 const char *beg, *end;
2997
2998 /* orig_arg points to the first argument, but we need to analyse the command itself first */
2999 cur_arg = *orig_arg - 1;
3000
3001 /* locate varName, which is mandatory */
3002 beg = strchr(args[cur_arg], '(');
3003 if (beg == NULL)
3004 goto do_resolve_parse_error;
3005 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3006 end = strchr(beg, ',');
3007 if (end == NULL)
3008 goto do_resolve_parse_error;
3009 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3010 if (rule->arg.resolv.varname == NULL)
3011 goto do_resolve_parse_error;
3012
3013
3014 /* locate resolversSectionName, which is mandatory.
3015 * Since next parameters are optional, the delimiter may be comma ','
3016 * or closing parenthesis ')'
3017 */
3018 beg = end + 1;
3019 end = strchr(beg, ',');
3020 if (end == NULL)
3021 end = strchr(beg, ')');
3022 if (end == NULL)
3023 goto do_resolve_parse_error;
3024 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3025 if (rule->arg.resolv.resolvers_id == NULL)
3026 goto do_resolve_parse_error;
3027
3028
3029 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3030 if (rule->arg.resolv.opts == NULL)
3031 goto do_resolve_parse_error;
3032
3033 /* Default priority is ipv6 */
3034 rule->arg.resolv.opts->family_prio = AF_INET6;
3035
3036 /* optional arguments accepted for now:
3037 * ipv4 or ipv6
3038 */
3039 while (*end != ')') {
3040 beg = end + 1;
3041 end = strchr(beg, ',');
3042 if (end == NULL)
3043 end = strchr(beg, ')');
3044 if (end == NULL)
3045 goto do_resolve_parse_error;
3046
3047 if (strncmp(beg, "ipv4", end - beg) == 0) {
3048 rule->arg.resolv.opts->family_prio = AF_INET;
3049 }
3050 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3051 rule->arg.resolv.opts->family_prio = AF_INET6;
3052 }
3053 else {
3054 goto do_resolve_parse_error;
3055 }
3056 }
3057
3058 cur_arg = cur_arg + 1;
3059
3060 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3061 if (!expr)
3062 goto do_resolve_parse_error;
3063
3064
3065 where = 0;
3066 if (px->cap & PR_CAP_FE)
3067 where |= SMP_VAL_FE_HRQ_HDR;
3068 if (px->cap & PR_CAP_BE)
3069 where |= SMP_VAL_BE_HRQ_HDR;
3070
3071 if (!(expr->fetch->val & where)) {
3072 memprintf(err,
3073 "fetch method '%s' extracts information from '%s', none of which is available here",
3074 args[cur_arg-1], sample_src_names(expr->fetch->use));
3075 free(expr);
3076 return ACT_RET_PRS_ERR;
3077 }
3078 rule->arg.resolv.expr = expr;
3079 rule->action = ACT_CUSTOM;
3080 rule->action_ptr = resolv_action_do_resolve;
3081 *orig_arg = cur_arg;
3082
3083 rule->check_ptr = check_action_do_resolve;
3084 rule->release_ptr = release_resolv_action;
3085
3086 return ACT_RET_PRS_OK;
3087
3088 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003089 ha_free(&rule->arg.resolv.varname);
3090 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003091 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3092 args[cur_arg]);
3093 return ACT_RET_PRS_ERR;
3094}
3095
3096static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003097 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003098 { /* END */ }
3099}};
3100
3101INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3102
3103static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003104 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003105 { /* END */ }
3106}};
3107
3108INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3109
3110/* Check an "http-request do-resolve" action.
3111 *
3112 * The function returns 1 in success case, otherwise, it returns 0 and err is
3113 * filled.
3114 */
3115int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3116{
3117 struct resolvers *resolvers = NULL;
3118
3119 if (rule->arg.resolv.resolvers_id == NULL) {
3120 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3121 return 0;
3122 }
3123
3124 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3125 if (resolvers == NULL) {
3126 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3127 return 0;
3128 }
3129 rule->arg.resolv.resolvers = resolvers;
3130
3131 return 1;
3132}
3133
3134void resolvers_setup_proxy(struct proxy *px)
3135{
3136 px->last_change = now.tv_sec;
3137 px->cap = PR_CAP_FE | PR_CAP_BE;
3138 px->maxconn = 0;
3139 px->conn_retries = 1;
3140 px->timeout.server = TICK_ETERNITY;
3141 px->timeout.client = TICK_ETERNITY;
3142 px->timeout.connect = TICK_ETERNITY;
3143 px->accept = NULL;
3144 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
Emeric Brunc9437992021-02-12 19:42:55 +01003145}
3146
3147/*
3148 * Parse a <resolvers> section.
3149 * Returns the error code, 0 if OK, or any combination of :
3150 * - ERR_ABORT: must abort ASAP
3151 * - ERR_FATAL: we can continue parsing but not start the service
3152 * - ERR_WARN: a warning has been emitted
3153 * - ERR_ALERT: an alert has been emitted
3154 * Only the two first ones can stop processing, the two others are just
3155 * indicators.
3156 */
3157int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3158{
3159 const char *err;
3160 int err_code = 0;
3161 char *errmsg = NULL;
3162 struct proxy *p;
3163
3164 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3165 if (!*args[1]) {
3166 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3167 err_code |= ERR_ALERT | ERR_ABORT;
3168 goto out;
3169 }
3170
3171 err = invalid_char(args[1]);
3172 if (err) {
3173 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3174 file, linenum, *err, args[0], args[1]);
3175 err_code |= ERR_ALERT | ERR_ABORT;
3176 goto out;
3177 }
3178
3179 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3180 /* Error if two resolvers owns the same name */
3181 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3182 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3183 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3184 err_code |= ERR_ALERT | ERR_ABORT;
3185 }
3186 }
3187
3188 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3189 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3190 err_code |= ERR_ALERT | ERR_ABORT;
3191 goto out;
3192 }
3193
3194 /* allocate new proxy to tcp servers */
3195 p = calloc(1, sizeof *p);
3196 if (!p) {
3197 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3198 err_code |= ERR_ALERT | ERR_FATAL;
3199 goto out;
3200 }
3201
3202 init_new_proxy(p);
3203 resolvers_setup_proxy(p);
3204 p->parent = curr_resolvers;
3205 p->id = strdup(args[1]);
3206 p->conf.args.file = p->conf.file = strdup(file);
3207 p->conf.args.line = p->conf.line = linenum;
3208 curr_resolvers->px = p;
3209
3210 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003211 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003212 curr_resolvers->conf.file = strdup(file);
3213 curr_resolvers->conf.line = linenum;
3214 curr_resolvers->id = strdup(args[1]);
3215 curr_resolvers->query_ids = EB_ROOT;
3216 /* default maximum response size */
3217 curr_resolvers->accepted_payload_size = 512;
3218 /* default hold period for nx, other, refuse and timeout is 30s */
3219 curr_resolvers->hold.nx = 30000;
3220 curr_resolvers->hold.other = 30000;
3221 curr_resolvers->hold.refused = 30000;
3222 curr_resolvers->hold.timeout = 30000;
3223 curr_resolvers->hold.obsolete = 0;
3224 /* default hold period for valid is 10s */
3225 curr_resolvers->hold.valid = 10000;
3226 curr_resolvers->timeout.resolve = 1000;
3227 curr_resolvers->timeout.retry = 1000;
3228 curr_resolvers->resolve_retries = 3;
3229 LIST_INIT(&curr_resolvers->nameservers);
3230 LIST_INIT(&curr_resolvers->resolutions.curr);
3231 LIST_INIT(&curr_resolvers->resolutions.wait);
3232 HA_SPIN_INIT(&curr_resolvers->lock);
3233 }
3234 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3235 struct dns_nameserver *newnameserver = NULL;
3236 struct sockaddr_storage *sk;
3237 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003238 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003239
3240 if (!*args[2]) {
3241 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3242 file, linenum, args[0]);
3243 err_code |= ERR_ALERT | ERR_FATAL;
3244 goto out;
3245 }
3246
3247 err = invalid_char(args[1]);
3248 if (err) {
3249 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3250 file, linenum, *err, args[1]);
3251 err_code |= ERR_ALERT | ERR_FATAL;
3252 goto out;
3253 }
3254
3255 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3256 /* Error if two resolvers owns the same name */
3257 if (strcmp(newnameserver->id, args[1]) == 0) {
3258 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3259 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3260 err_code |= ERR_ALERT | ERR_FATAL;
3261 }
3262 }
3263
Emeric Brunc8f3e452021-04-07 16:04:54 +02003264 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3265 &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 +01003266 if (!sk) {
3267 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3268 err_code |= ERR_ALERT | ERR_FATAL;
3269 goto out;
3270 }
3271
3272 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3273 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3274 err_code |= ERR_ALERT | ERR_ABORT;
3275 goto out;
3276 }
3277
Emeric Brunc8f3e452021-04-07 16:04:54 +02003278 if (proto && proto->ctrl_type == SOCK_STREAM) {
3279 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3280 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3281 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3282 err_code |= ERR_ABORT;
3283 goto out;
3284 }
3285
3286 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3287 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3288 err_code |= ERR_ALERT|ERR_ABORT;
3289 goto out;
3290 }
3291 }
3292 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003293 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3294 err_code |= ERR_ALERT | ERR_ABORT;
3295 goto out;
3296 }
3297
3298 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3299 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3300 err_code |= ERR_ALERT | ERR_ABORT;
3301 goto out;
3302 }
3303
3304 if ((newnameserver->id = strdup(args[1])) == NULL) {
3305 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3306 err_code |= ERR_ALERT | ERR_ABORT;
3307 goto out;
3308 }
3309
3310 newnameserver->parent = curr_resolvers;
3311 newnameserver->process_responses = resolv_process_responses;
3312 newnameserver->conf.line = linenum;
3313 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003314 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003315 }
3316 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3317 struct dns_nameserver *newnameserver = NULL;
3318 const char *whitespace = "\r\n\t ";
3319 char *resolv_line = NULL;
3320 int resolv_linenum = 0;
3321 FILE *f = NULL;
3322 char *address = NULL;
3323 struct sockaddr_storage *sk = NULL;
3324 struct protocol *proto;
3325 int duplicate_name = 0;
3326
3327 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3328 ha_alert("parsing [%s:%d] : out of memory.\n",
3329 file, linenum);
3330 err_code |= ERR_ALERT | ERR_FATAL;
3331 goto resolv_out;
3332 }
3333
3334 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3335 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3336 file, linenum);
3337 err_code |= ERR_ALERT | ERR_FATAL;
3338 goto resolv_out;
3339 }
3340
3341 sk = calloc(1, sizeof(*sk));
3342 if (sk == NULL) {
3343 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3344 resolv_linenum);
3345 err_code |= ERR_ALERT | ERR_FATAL;
3346 goto resolv_out;
3347 }
3348
3349 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3350 resolv_linenum++;
3351 if (strncmp(resolv_line, "nameserver", 10) != 0)
3352 continue;
3353
3354 address = strtok(resolv_line + 10, whitespace);
3355 if (address == resolv_line + 10)
3356 continue;
3357
3358 if (address == NULL) {
3359 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3360 resolv_linenum);
3361 err_code |= ERR_WARN;
3362 continue;
3363 }
3364
3365 duplicate_name = 0;
3366 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3367 if (strcmp(newnameserver->id, address) == 0) {
3368 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",
3369 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3370 err_code |= ERR_WARN;
3371 duplicate_name = 1;
3372 }
3373 }
3374
3375 if (duplicate_name)
3376 continue;
3377
3378 memset(sk, 0, sizeof(*sk));
3379 if (!str2ip2(address, sk, 1)) {
3380 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3381 resolv_linenum, address);
3382 err_code |= ERR_WARN;
3383 continue;
3384 }
3385
3386 set_host_port(sk, 53);
3387
Willy Tarreau14e7f292021-10-27 17:41:07 +02003388 proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01003389 if (!proto || !proto->connect) {
3390 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3391 resolv_linenum, address);
3392 err_code |= ERR_WARN;
3393 continue;
3394 }
3395
3396 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3397 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3398 err_code |= ERR_ALERT | ERR_FATAL;
3399 goto resolv_out;
3400 }
3401
3402 if (dns_dgram_init(newnameserver, sk) < 0) {
3403 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3404 err_code |= ERR_ALERT | ERR_FATAL;
3405 free(newnameserver);
3406 goto resolv_out;
3407 }
3408
3409 newnameserver->conf.file = strdup("/etc/resolv.conf");
3410 if (newnameserver->conf.file == NULL) {
3411 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3412 err_code |= ERR_ALERT | ERR_FATAL;
3413 free(newnameserver);
3414 goto resolv_out;
3415 }
3416
3417 newnameserver->id = strdup(address);
3418 if (newnameserver->id == NULL) {
3419 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3420 err_code |= ERR_ALERT | ERR_FATAL;
3421 free((char *)newnameserver->conf.file);
3422 free(newnameserver);
3423 goto resolv_out;
3424 }
3425
3426 newnameserver->parent = curr_resolvers;
3427 newnameserver->process_responses = resolv_process_responses;
3428 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003429 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003430 }
3431
3432resolv_out:
3433 free(sk);
3434 free(resolv_line);
3435 if (f != NULL)
3436 fclose(f);
3437 }
3438 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3439 const char *res;
3440 unsigned int time;
3441
3442 if (!*args[2]) {
3443 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3444 file, linenum, args[0]);
3445 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3446 err_code |= ERR_ALERT | ERR_FATAL;
3447 goto out;
3448 }
3449 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3450 if (res == PARSE_TIME_OVER) {
3451 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3452 file, linenum, args[1], args[0]);
3453 err_code |= ERR_ALERT | ERR_FATAL;
3454 goto out;
3455 }
3456 else if (res == PARSE_TIME_UNDER) {
3457 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3458 file, linenum, args[1], args[0]);
3459 err_code |= ERR_ALERT | ERR_FATAL;
3460 goto out;
3461 }
3462 else if (res) {
3463 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3464 file, linenum, *res, args[0]);
3465 err_code |= ERR_ALERT | ERR_FATAL;
3466 goto out;
3467 }
3468 if (strcmp(args[1], "nx") == 0)
3469 curr_resolvers->hold.nx = time;
3470 else if (strcmp(args[1], "other") == 0)
3471 curr_resolvers->hold.other = time;
3472 else if (strcmp(args[1], "refused") == 0)
3473 curr_resolvers->hold.refused = time;
3474 else if (strcmp(args[1], "timeout") == 0)
3475 curr_resolvers->hold.timeout = time;
3476 else if (strcmp(args[1], "valid") == 0)
3477 curr_resolvers->hold.valid = time;
3478 else if (strcmp(args[1], "obsolete") == 0)
3479 curr_resolvers->hold.obsolete = time;
3480 else {
3481 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3482 file, linenum, args[0], args[1]);
3483 err_code |= ERR_ALERT | ERR_FATAL;
3484 goto out;
3485 }
3486
3487 }
3488 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3489 int i = 0;
3490
3491 if (!*args[1]) {
3492 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3493 file, linenum, args[0]);
3494 err_code |= ERR_ALERT | ERR_FATAL;
3495 goto out;
3496 }
3497
3498 i = atoi(args[1]);
3499 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3500 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3501 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3502 err_code |= ERR_ALERT | ERR_FATAL;
3503 goto out;
3504 }
3505
3506 curr_resolvers->accepted_payload_size = i;
3507 }
3508 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3509 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3510 file, linenum, args[0]);
3511 err_code |= ERR_ALERT | ERR_FATAL;
3512 goto out;
3513 }
3514 else if (strcmp(args[0], "resolve_retries") == 0) {
3515 if (!*args[1]) {
3516 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3517 file, linenum, args[0]);
3518 err_code |= ERR_ALERT | ERR_FATAL;
3519 goto out;
3520 }
3521 curr_resolvers->resolve_retries = atoi(args[1]);
3522 }
3523 else if (strcmp(args[0], "timeout") == 0) {
3524 if (!*args[1]) {
3525 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3526 file, linenum, args[0]);
3527 err_code |= ERR_ALERT | ERR_FATAL;
3528 goto out;
3529 }
3530 else if (strcmp(args[1], "retry") == 0 ||
3531 strcmp(args[1], "resolve") == 0) {
3532 const char *res;
3533 unsigned int tout;
3534
3535 if (!*args[2]) {
3536 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3537 file, linenum, args[0], args[1]);
3538 err_code |= ERR_ALERT | ERR_FATAL;
3539 goto out;
3540 }
3541 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3542 if (res == PARSE_TIME_OVER) {
3543 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3544 file, linenum, args[2], args[0], args[1]);
3545 err_code |= ERR_ALERT | ERR_FATAL;
3546 goto out;
3547 }
3548 else if (res == PARSE_TIME_UNDER) {
3549 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3550 file, linenum, args[2], args[0], args[1]);
3551 err_code |= ERR_ALERT | ERR_FATAL;
3552 goto out;
3553 }
3554 else if (res) {
3555 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3556 file, linenum, *res, args[0], args[1]);
3557 err_code |= ERR_ALERT | ERR_FATAL;
3558 goto out;
3559 }
3560 if (args[1][2] == 't')
3561 curr_resolvers->timeout.retry = tout;
3562 else
3563 curr_resolvers->timeout.resolve = tout;
3564 }
3565 else {
3566 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3567 file, linenum, args[0], args[1]);
3568 err_code |= ERR_ALERT | ERR_FATAL;
3569 goto out;
3570 }
3571 }
3572 else if (*args[0] != 0) {
3573 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3574 err_code |= ERR_ALERT | ERR_FATAL;
3575 goto out;
3576 }
3577
3578 out:
3579 free(errmsg);
3580 return err_code;
3581}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003582int cfg_post_parse_resolvers()
3583{
3584 int err_code = 0;
3585 struct server *srv;
3586
3587 if (curr_resolvers) {
3588
3589 /* prepare forward server descriptors */
3590 if (curr_resolvers->px) {
3591 srv = curr_resolvers->px->srv;
3592 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003593 /* init ssl if needed */
3594 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3595 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3596 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3597 err_code |= ERR_ALERT | ERR_FATAL;
3598 break;
3599 }
3600 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003601 srv = srv->next;
3602 }
3603 }
3604 }
3605 curr_resolvers = NULL;
3606 return err_code;
3607}
Emeric Brunc9437992021-02-12 19:42:55 +01003608
Emeric Brun56fc5d92021-02-12 20:05:45 +01003609REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003610REGISTER_POST_DEINIT(resolvers_deinit);
3611REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);