blob: dac24f709a36c3b3897f7c9e0d825518d7fc2a53 [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 Brun0c4a8a32021-06-11 10:48:45 +020022#include <import/ebistree.h>
23
Emeric Brunc9437992021-02-12 19:42:55 +010024#include <haproxy/action.h>
25#include <haproxy/api.h>
26#include <haproxy/cfgparse.h>
27#include <haproxy/channel.h>
28#include <haproxy/check.h>
29#include <haproxy/cli.h>
30#include <haproxy/dns.h>
31#include <haproxy/errors.h>
32#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010033#include <haproxy/http_rules.h>
34#include <haproxy/log.h>
35#include <haproxy/net_helper.h>
36#include <haproxy/protocol.h>
37#include <haproxy/proxy.h>
38#include <haproxy/resolvers.h>
39#include <haproxy/ring.h>
40#include <haproxy/sample.h>
41#include <haproxy/server.h>
42#include <haproxy/stats.h>
43#include <haproxy/stream_interface.h>
44#include <haproxy/task.h>
45#include <haproxy/tcp_rules.h>
46#include <haproxy/ticks.h>
47#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020048#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010049#include <haproxy/vars.h>
50
51
52struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
53struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
54
Willy Tarreau20751652021-10-18 16:46:38 +020055static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
Christopher Faulet7a3a5362021-11-02 16:25:05 +010056static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
Emeric Brunc9437992021-02-12 19:42:55 +010057static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
58struct resolvers *curr_resolvers = NULL;
59
60DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
61DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
62DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
63
64static unsigned int resolution_uuid = 1;
65unsigned int resolv_failed_resolutions = 0;
Willy Tarreau20751652021-10-18 16:46:38 +020066static struct task *process_resolvers(struct task *t, void *context, unsigned int state);
67static void resolv_free_resolution(struct resolv_resolution *resolution);
Willy Tarreau33360872021-10-20 14:07:31 +020068static void _resolv_unlink_resolution(struct resolv_requester *requester);
Christopher Faulet7a3a5362021-11-02 16:25:05 +010069static void enter_resolver_code();
70static void leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +010071
72enum {
73 DNS_STAT_ID,
74 DNS_STAT_PID,
75 DNS_STAT_SENT,
76 DNS_STAT_SND_ERROR,
77 DNS_STAT_VALID,
78 DNS_STAT_UPDATE,
79 DNS_STAT_CNAME,
80 DNS_STAT_CNAME_ERROR,
81 DNS_STAT_ANY_ERR,
82 DNS_STAT_NX,
83 DNS_STAT_TIMEOUT,
84 DNS_STAT_REFUSED,
85 DNS_STAT_OTHER,
86 DNS_STAT_INVALID,
87 DNS_STAT_TOO_BIG,
88 DNS_STAT_TRUNCATED,
89 DNS_STAT_OUTDATED,
90 DNS_STAT_END,
91};
92
93static struct name_desc dns_stats[] = {
94 [DNS_STAT_ID] = { .name = "id", .desc = "ID" },
95 [DNS_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
96 [DNS_STAT_SENT] = { .name = "sent", .desc = "Sent" },
97 [DNS_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
98 [DNS_STAT_VALID] = { .name = "valid", .desc = "Valid" },
99 [DNS_STAT_UPDATE] = { .name = "update", .desc = "Update" },
100 [DNS_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
101 [DNS_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
102 [DNS_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
103 [DNS_STAT_NX] = { .name = "nx", .desc = "NX" },
104 [DNS_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
105 [DNS_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
106 [DNS_STAT_OTHER] = { .name = "other", .desc = "Other" },
107 [DNS_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
108 [DNS_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
109 [DNS_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
110 [DNS_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
111};
112
113static struct dns_counters dns_counters;
114
115static void dns_fill_stats(void *d, struct field *stats)
116{
117 struct dns_counters *counters = d;
118 stats[DNS_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
119 stats[DNS_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
120 stats[DNS_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
121 stats[DNS_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
122 stats[DNS_STAT_VALID] = mkf_u64(FN_GAUGE, counters->valid);
123 stats[DNS_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->update);
124 stats[DNS_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->cname);
125 stats[DNS_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->cname_error);
126 stats[DNS_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->any_err);
127 stats[DNS_STAT_NX] = mkf_u64(FN_GAUGE, counters->nx);
128 stats[DNS_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->timeout);
129 stats[DNS_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->refused);
130 stats[DNS_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->other);
131 stats[DNS_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->invalid);
132 stats[DNS_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->too_big);
133 stats[DNS_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->truncated);
134 stats[DNS_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->outdated);
135}
136
137static struct stats_module dns_stats_module = {
138 .name = "dns",
139 .domain_flags = STATS_DOMAIN_DNS << STATS_DOMAIN,
140 .fill_stats = dns_fill_stats,
141 .stats = dns_stats,
142 .stats_count = DNS_STAT_END,
143 .counters = &dns_counters,
144 .counters_size = sizeof(dns_counters),
145 .clearable = 0,
146};
147
148INITCALL1(STG_REGISTER, stats_register_module, &dns_stats_module);
149
150/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
151 * no match is found.
152 */
153struct resolvers *find_resolvers_by_id(const char *id)
154{
155 struct resolvers *res;
156
157 list_for_each_entry(res, &sec_resolvers, list) {
158 if (strcmp(res->id, id) == 0)
159 return res;
160 }
161 return NULL;
162}
163
164/* Compare hostnames in a case-insensitive way .
165 * Returns 0 if they are the same, non-zero otherwise
166 */
167static __inline int resolv_hostname_cmp(const char *name1, const char *name2, int len)
168{
169 int i;
170
171 for (i = 0; i < len; i++)
172 if (tolower((unsigned char)name1[i]) != tolower((unsigned char)name2[i]))
173 return -1;
174 return 0;
175}
176
177/* Returns a pointer on the SRV request matching the name <name> for the proxy
178 * <px>. NULL is returned if no match is found.
179 */
180struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
181{
182 struct resolv_srvrq *srvrq;
183
184 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
185 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
186 return srvrq;
187 }
188 return NULL;
189}
190
191/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
192 * NULL if an error occurred. */
193struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
194{
195 struct proxy *px = srv->proxy;
196 struct resolv_srvrq *srvrq = NULL;
197 int fqdn_len, hostname_dn_len;
198
199 fqdn_len = strlen(fqdn);
Willy Tarreauc1c765f2021-10-14 07:49:49 +0200200 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100201 trash.size);
202 if (hostname_dn_len == -1) {
203 ha_alert("config : %s '%s', server '%s': failed to parse FQDN '%s'\n",
204 proxy_type_str(px), px->id, srv->id, fqdn);
205 goto err;
206 }
207
208 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
209 ha_alert("config : %s '%s', server '%s': out of memory\n",
210 proxy_type_str(px), px->id, srv->id);
211 goto err;
212 }
213 srvrq->obj_type = OBJ_TYPE_SRVRQ;
214 srvrq->proxy = px;
215 srvrq->name = strdup(fqdn);
216 srvrq->hostname_dn = strdup(trash.area);
217 srvrq->hostname_dn_len = hostname_dn_len;
218 if (!srvrq->name || !srvrq->hostname_dn) {
219 ha_alert("config : %s '%s', server '%s': out of memory\n",
220 proxy_type_str(px), px->id, srv->id);
221 goto err;
222 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200223 LIST_INIT(&srvrq->attached_servers);
224 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200225 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100226 return srvrq;
227
228 err:
229 if (srvrq) {
230 free(srvrq->name);
231 free(srvrq->hostname_dn);
232 free(srvrq);
233 }
234 return NULL;
235}
236
237
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100238/* finds and return the SRV answer item associated to a requester (whose type is 'server').
239 *
240 * returns NULL in case of error or not found.
241 */
242struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
243{
244 struct resolv_resolution *res;
245 struct resolv_answer_item *item;
246 struct server *srv;
247
248 if (!requester)
249 return NULL;
250
251 if ((srv = objt_server(requester->owner)) == NULL)
252 return NULL;
253 /* check if the server is managed by a SRV record */
254 if (srv->srvrq == NULL)
255 return NULL;
256
257 res = srv->srvrq->requester->resolution;
258 /* search an ANSWER record whose target points to the server's hostname and whose port is
259 * the same as server's svc_port */
260 list_for_each_entry(item, &res->response.answer_list, list) {
Willy Tarreau20a02372021-10-14 22:52:04 +0200261 if (resolv_hostname_cmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100262 (srv->svc_port == item->port))
263 return item;
264 }
265
266 return NULL;
267}
268
Emeric Brunc9437992021-02-12 19:42:55 +0100269/* 2 bytes random generator to generate DNS query ID */
270static inline uint16_t resolv_rnd16(void)
271{
272 if (!resolv_query_id_seed)
273 resolv_query_id_seed = now_ms;
274 resolv_query_id_seed ^= resolv_query_id_seed << 13;
275 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
276 resolv_query_id_seed ^= resolv_query_id_seed << 17;
277 return resolv_query_id_seed;
278}
279
280
281static inline int resolv_resolution_timeout(struct resolv_resolution *res)
282{
283 return res->resolvers->timeout.resolve;
284}
285
286/* Updates a resolvers' task timeout for next wake up and queue it */
287static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
288{
289 struct resolv_resolution *res;
290 int next;
291
292 next = tick_add(now_ms, resolvers->timeout.resolve);
293 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
294 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
295 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
296 }
297
298 list_for_each_entry(res, &resolvers->resolutions.wait, list)
299 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
300
301 resolvers->t->expire = next;
302 task_queue(resolvers->t);
303}
304
305/* Forges a DNS query. It needs the following information from the caller:
306 * - <query_id> : the DNS query id corresponding to this query
307 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
308 * - <hostname_dn> : hostname in domain name format
309 * - <hostname_dn_len> : length of <hostname_dn>
310 *
311 * To store the query, the caller must pass a buffer <buf> and its size
312 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
313 * too short.
314 */
315static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
316 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
317{
318 struct dns_header dns_hdr;
319 struct dns_question qinfo;
320 struct dns_additional_record edns;
321 char *p = buf;
322
323 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
324 return -1;
325
326 memset(buf, 0, bufsize);
327
328 /* Set dns query headers */
329 dns_hdr.id = (unsigned short) htons(query_id);
330 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
331 dns_hdr.qdcount = htons(1); /* 1 question */
332 dns_hdr.ancount = 0;
333 dns_hdr.nscount = 0;
334 dns_hdr.arcount = htons(1);
335 memcpy(p, &dns_hdr, sizeof(dns_hdr));
336 p += sizeof(dns_hdr);
337
338 /* Set up query hostname */
339 memcpy(p, hostname_dn, hostname_dn_len);
340 p += hostname_dn_len;
341 *p++ = 0;
342
343 /* Set up query info (type and class) */
344 qinfo.qtype = htons(query_type);
345 qinfo.qclass = htons(DNS_RCLASS_IN);
346 memcpy(p, &qinfo, sizeof(qinfo));
347 p += sizeof(qinfo);
348
349 /* Set the DNS extension */
350 edns.name = 0;
351 edns.type = htons(DNS_RTYPE_OPT);
352 edns.udp_payload_size = htons(accepted_payload_size);
353 edns.extension = 0;
354 edns.data_length = 0;
355 memcpy(p, &edns, sizeof(edns));
356 p += sizeof(edns);
357
358 return (p - buf);
359}
360
361/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
362 * success, -1 otherwise.
363 */
364static int resolv_send_query(struct resolv_resolution *resolution)
365{
366 struct resolvers *resolvers = resolution->resolvers;
367 struct dns_nameserver *ns;
368 int len;
369
370 /* Update resolution */
371 resolution->nb_queries = 0;
372 resolution->nb_responses = 0;
373 resolution->last_query = now_ms;
374
375 len = resolv_build_query(resolution->query_id, resolution->query_type,
376 resolvers->accepted_payload_size,
377 resolution->hostname_dn, resolution->hostname_dn_len,
378 trash.area, trash.size);
379
380 list_for_each_entry(ns, &resolvers->nameservers, list) {
381 if (len < 0) {
382 ns->counters->snd_error++;
383 continue;
384 }
385
Emeric Brun2fa8f072021-10-29 16:28:33 +0200386 if (dns_send_nameserver(ns, trash.area, len) >= 0)
Emeric Brunc9437992021-02-12 19:42:55 +0100387 resolution->nb_queries++;
388 }
389
390 /* Push the resolution at the end of the active list */
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200391 LIST_DEL_INIT(&resolution->list);
Willy Tarreau2b718102021-04-21 07:32:39 +0200392 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100393 return 0;
394}
395
396/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
397 * skipped and -1 if an error occurred.
398 */
399static int
400resolv_run_resolution(struct resolv_resolution *resolution)
401{
402 struct resolvers *resolvers = resolution->resolvers;
403 int query_id, i;
404
405 /* Avoid sending requests for resolutions that don't yet have an
406 * hostname, ie resolutions linked to servers that do not yet have an
407 * fqdn */
408 if (!resolution->hostname_dn)
409 return 0;
410
411 /* Check if a resolution has already been started for this server return
412 * directly to avoid resolution pill up. */
413 if (resolution->step != RSLV_STEP_NONE)
414 return 0;
415
416 /* Generates a new query id. We try at most 100 times to find a free
417 * query id */
418 for (i = 0; i < 100; ++i) {
419 query_id = resolv_rnd16();
420 if (!eb32_lookup(&resolvers->query_ids, query_id))
421 break;
422 query_id = -1;
423 }
424 if (query_id == -1) {
425 send_log(NULL, LOG_NOTICE,
426 "could not generate a query id for %s, in resolvers %s.\n",
427 resolution->hostname_dn, resolvers->id);
428 return -1;
429 }
430
431 /* Update resolution parameters */
432 resolution->query_id = query_id;
433 resolution->qid.key = query_id;
434 resolution->step = RSLV_STEP_RUNNING;
435 resolution->query_type = resolution->prefered_query_type;
436 resolution->try = resolvers->resolve_retries;
437 eb32_insert(&resolvers->query_ids, &resolution->qid);
438
439 /* Send the DNS query */
440 resolution->try -= 1;
441 resolv_send_query(resolution);
442 return 1;
443}
444
445/* Performs a name resolution for the requester <req> */
446void resolv_trigger_resolution(struct resolv_requester *req)
447{
448 struct resolvers *resolvers;
449 struct resolv_resolution *res;
450 int exp;
451
452 if (!req || !req->resolution)
453 return;
454 res = req->resolution;
455 resolvers = res->resolvers;
456
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100457 enter_resolver_code();
458
Emeric Brunc9437992021-02-12 19:42:55 +0100459 /* The resolution must not be triggered yet. Use the cached response, if
460 * valid */
461 exp = tick_add(res->last_resolution, resolvers->hold.valid);
462 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
463 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
464 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100465
466 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +0100467}
468
469
470/* Resets some resolution parameters to initial values and also delete the query
471 * ID from the resolver's tree.
472 */
473static void resolv_reset_resolution(struct resolv_resolution *resolution)
474{
475 /* update resolution status */
476 resolution->step = RSLV_STEP_NONE;
477 resolution->try = 0;
478 resolution->last_resolution = now_ms;
479 resolution->nb_queries = 0;
480 resolution->nb_responses = 0;
481 resolution->query_type = resolution->prefered_query_type;
482
483 /* clean up query id */
484 eb32_delete(&resolution->qid);
485 resolution->query_id = 0;
486 resolution->qid.key = 0;
487}
488
489/* Returns the query id contained in a DNS response */
490static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
491{
492 return resp[0] * 256 + resp[1];
493}
494
495
496/* Analyses, re-builds and copies the name <name> from the DNS response packet
497 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
498 * for compressed data. The result is copied into <dest>, ensuring we don't
499 * overflow using <dest_len> Returns the number of bytes the caller can move
500 * forward. If 0 it means an error occurred while parsing the name. <offset> is
501 * the number of bytes the caller could move forward.
502 */
503int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
504 unsigned char *name, char *destination, int dest_len,
505 int *offset, unsigned int depth)
506{
507 int nb_bytes = 0, n = 0;
508 int label_len;
509 unsigned char *reader = name;
510 char *dest = destination;
511
512 while (1) {
513 if (reader >= bufend)
514 goto err;
515
516 /* Name compression is in use */
517 if ((*reader & 0xc0) == 0xc0) {
518 if (reader + 1 >= bufend)
519 goto err;
520
521 /* Must point BEFORE current position */
522 if ((buffer + reader[1]) > reader)
523 goto err;
524
525 if (depth++ > 100)
526 goto err;
527
528 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
529 dest, dest_len - nb_bytes, offset, depth);
530 if (n == 0)
531 goto err;
532
533 dest += n;
534 nb_bytes += n;
535 goto out;
536 }
537
538 label_len = *reader;
539 if (label_len == 0)
540 goto out;
541
542 /* Check if:
543 * - we won't read outside the buffer
544 * - there is enough place in the destination
545 */
546 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
547 goto err;
548
549 /* +1 to take label len + label string */
550 label_len++;
551
552 memcpy(dest, reader, label_len);
553
554 dest += label_len;
555 nb_bytes += label_len;
556 reader += label_len;
557 }
558
559 out:
560 /* offset computation:
561 * parse from <name> until finding either NULL or a pointer "c0xx"
562 */
563 reader = name;
564 *offset = 0;
565 while (reader < bufend) {
566 if ((reader[0] & 0xc0) == 0xc0) {
567 *offset += 2;
568 break;
569 }
570 else if (*reader == 0) {
571 *offset += 1;
572 break;
573 }
574 *offset += 1;
575 ++reader;
576 }
577 return nb_bytes;
578
579 err:
580 return 0;
581}
582
Willy Tarreau20751652021-10-18 16:46:38 +0200583/* Reinitialize the list of aborted resolutions before calling certain
584 * functions relying on it. The list must be processed by calling
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100585 * leave_resolver_code() after operations.
Willy Tarreau20751652021-10-18 16:46:38 +0200586 */
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100587static void enter_resolver_code()
Willy Tarreau20751652021-10-18 16:46:38 +0200588{
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100589 if (!recurse)
590 LIST_INIT(&death_row);
591 recurse++;
Willy Tarreau20751652021-10-18 16:46:38 +0200592}
593
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100594/* Add a resolution to the death_row. */
Willy Tarreau20751652021-10-18 16:46:38 +0200595static void abort_resolution(struct resolv_resolution *res)
596{
597 LIST_DEL_INIT(&res->list);
598 LIST_APPEND(&death_row, &res->list);
599}
600
601/* This releases any aborted resolution found in the death row. It is mandatory
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100602 * to call enter_resolver_code() first before the function (or loop) that
Willy Tarreau20751652021-10-18 16:46:38 +0200603 * needs to defer deletions. Note that some of them are in relation via internal
604 * objects and might cause the deletion of other ones from the same list, so we
605 * must absolutely not use a list_for_each_entry_safe() nor any such thing here,
606 * and solely rely on each call to remove the first remaining list element.
607 */
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100608static void leave_resolver_code()
Willy Tarreau20751652021-10-18 16:46:38 +0200609{
610 struct resolv_resolution *res;
611
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100612 recurse--;
613 if (recurse)
614 return;
615
Willy Tarreau20751652021-10-18 16:46:38 +0200616 while (!LIST_ISEMPTY(&death_row)) {
617 res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
618 resolv_free_resolution(res);
619 }
620
621 /* make sure nobody tries to add anything without having initialized it */
622 death_row = (struct list){ };
623}
624
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200625/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
626 * happens when an SRV item is purged or when the server status is considered as
627 * obsolete.
628 *
Willy Tarreau20751652021-10-18 16:46:38 +0200629 * Must be called with the DNS lock held, and with the death_row already
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100630 * initialized via enter_resolver_code().
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200631 */
Willy Tarreau20751652021-10-18 16:46:38 +0200632static void resolv_srvrq_cleanup_srv(struct server *srv)
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200633{
Willy Tarreau33360872021-10-20 14:07:31 +0200634 _resolv_unlink_resolution(srv->resolv_requester);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200635 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
636 srvrq_update_srv_status(srv, 1);
637 ha_free(&srv->hostname);
638 ha_free(&srv->hostname_dn);
639 srv->hostname_dn_len = 0;
640 memset(&srv->addr, 0, sizeof(srv->addr));
641 srv->svc_port = 0;
642 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Fauleta62d9742021-06-15 16:14:37 +0200643
644 ebpt_delete(&srv->host_dn);
645 ha_free(&srv->host_dn.key);
646
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200647 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200648 LIST_DEL_INIT(&srv->srv_rec_item);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200649 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200650
651 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200652}
653
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200654/* Takes care to cleanup a server resolution when it is outdated. This only
655 * happens for a server relying on a SRV record.
656 */
657static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
658{
659 struct server *srv = context;
660
661 if (!tick_is_expired(t->expire, now_ms))
662 goto end;
663
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100664 enter_resolver_code();
Christopher Faulet152b50c2021-06-18 09:05:49 +0200665 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreau20751652021-10-18 16:46:38 +0200666 resolv_srvrq_cleanup_srv(srv);
Christopher Faulet152b50c2021-06-18 09:05:49 +0200667 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100668 leave_resolver_code();
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200669
670 end:
671 return t;
672}
673
Emeric Brunc9437992021-02-12 19:42:55 +0100674/* Checks for any obsolete record, also identify any SRV request, and try to
Christopher Faulet7a3a5362021-11-02 16:25:05 +0100675 * find a corresponding server.
Willy Tarreau20751652021-10-18 16:46:38 +0200676 */
Emeric Brunc9437992021-02-12 19:42:55 +0100677static void resolv_check_response(struct resolv_resolution *res)
678{
679 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100680 struct resolv_requester *req;
Emeric Brunc9437992021-02-12 19:42:55 +0100681 struct resolv_answer_item *item, *itemback;
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200682 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100683 struct resolv_srvrq *srvrq;
684
685 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
686 struct resolv_answer_item *ar_item = item->ar_item;
687
688 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100689 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100690 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
691 * item is also obsolete.
692 */
Emeric Brunc9437992021-02-12 19:42:55 +0100693 pool_free(resolv_answer_item_pool, ar_item);
694 item->ar_item = NULL;
695 }
696
697 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100698 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200699 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100700 /* Remove any associated server */
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200701 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
702 LIST_DEL_INIT(&srv->ip_rec_item);
703 }
704 }
705 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200706 /* Remove any associated server */
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200707 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreau20751652021-10-18 16:46:38 +0200708 resolv_srvrq_cleanup_srv(srv);
Emeric Brunc9437992021-02-12 19:42:55 +0100709 }
710
Willy Tarreau8c3c5232021-10-19 22:01:36 +0200711 LIST_DEL_INIT(&item->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100712 if (item->ar_item) {
713 pool_free(resolv_answer_item_pool, item->ar_item);
714 item->ar_item = NULL;
715 }
716 pool_free(resolv_answer_item_pool, item);
717 continue;
718 }
719
720 if (item->type != DNS_RTYPE_SRV)
721 continue;
722
723 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100724 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200725 struct ebpt_node *node;
726 char target[DNS_MAX_NAME_SIZE+1];
727
728 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100729 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
730 continue;
731
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200732 /* Check if a server already uses that record */
733 srv = NULL;
734 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
735 if (srv->srvrq == srvrq) {
736 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
737 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100738 }
Emeric Brunc9437992021-02-12 19:42:55 +0100739 }
740
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200741
742 /* If not empty we try to match a server
743 * in server state file tree with the same hostname
744 */
745 if (!eb_is_empty(&srvrq->named_servers)) {
746 srv = NULL;
747
748 /* convert the key to lookup in lower case */
Willy Tarreau20a02372021-10-14 22:52:04 +0200749 for (i = 0 ; item->data.target[i] ; i++)
750 target[i] = tolower(item->data.target[i]);
Christopher Fauletc20d6422021-07-22 14:29:26 +0200751 target[i] = 0;
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200752
753 node = ebis_lookup(&srvrq->named_servers, target);
754 if (node) {
755 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100756 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200757
758 /* an entry was found with the same hostname
759 * let check this node if the port matches
760 * and try next node if the hostname
761 * is still the same
762 */
763 while (1) {
764 if (srv->svc_port == item->port) {
765 /* server found, we remove it from tree */
766 ebpt_delete(node);
Christopher Fauleta62d9742021-06-15 16:14:37 +0200767 ha_free(&srv->host_dn.key);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200768 goto srv_found;
769 }
770
771 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
772
773 node = ebpt_next(node);
774 if (!node)
775 break;
776
777 srv = ebpt_entry(node, struct server, host_dn);
778 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
779
780 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau20a02372021-10-14 22:52:04 +0200781 || resolv_hostname_cmp(srv->hostname_dn, item->data.target, item->data_len)) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200782 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
783 break;
784 }
785 }
Emeric Brunc9437992021-02-12 19:42:55 +0100786 }
787 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200788
789 /* Pick the first server listed in srvrq (those ones don't
790 * have hostname and are free to use)
791 */
792 srv = NULL;
793 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
794 LIST_DEL_INIT(&srv->srv_rec_item);
795 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
796 goto srv_found;
797 }
798 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100799
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200800srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100801 /* And update this server, if found (srv is locked here) */
802 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100803 /* re-enable DNS resolution for this server by default */
804 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200805 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100806
Emeric Brunc9437992021-02-12 19:42:55 +0100807 /* Check if an Additional Record is associated to this SRV record.
808 * Perform some sanity checks too to ensure the record can be used.
809 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100810 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100811 */
812 if ((item->ar_item != NULL) &&
813 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100814 {
Emeric Brunc9437992021-02-12 19:42:55 +0100815
816 switch (item->ar_item->type) {
817 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +0200818 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100819 break;
820 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +0200821 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100822 break;
823 }
824
825 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100826
827 /* Unlink A/AAAA resolution for this server if there is an AR item.
828 * It is usless to perform an extra resolution
829 */
Willy Tarreau33360872021-10-20 14:07:31 +0200830 _resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100831 }
832
833 if (!srv->hostname_dn) {
834 const char *msg = NULL;
Willy Tarreau2859c162021-10-14 08:00:38 +0200835 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100836
Willy Tarreau20a02372021-10-14 22:52:04 +0200837 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau2859c162021-10-14 08:00:38 +0200838 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100839 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
840 continue;
841 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100842 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100843 if (msg)
844 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
845 }
846
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200847 if (!LIST_INLIST(&srv->srv_rec_item))
848 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
849
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100850 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
851 /* If there is no AR item responsible of the FQDN resolution,
852 * trigger a dedicated DNS resolution
853 */
854 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
855 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
856 }
857
Christopher Fauletab177ac2021-03-10 15:34:52 +0100858 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100859 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100860
861 srv->svc_port = item->port;
862 srv->flags &= ~SRV_F_MAPPORTS;
863
864 if (!srv->resolv_opts.ignore_weight) {
865 char weight[9];
866 int ha_weight;
867
868 /* DNS weight range if from 0 to 65535
869 * HAProxy weight is from 0 to 256
870 * The rule below ensures that weight 0 is well respected
871 * while allowing a "mapping" from DNS weight into HAProxy's one.
872 */
873 ha_weight = (item->weight + 255) / 256;
874
875 snprintf(weight, sizeof(weight), "%d", ha_weight);
876 server_parse_weight_change_request(srv, weight);
877 }
878 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
879 }
880 }
881 }
882}
883
884/* Validates that the buffer DNS response provided in <resp> and finishing
885 * before <bufend> is valid from a DNS protocol point of view.
886 *
887 * The result is stored in <resolution>' response, buf_response,
888 * response_query_records and response_answer_records members.
889 *
890 * This function returns one of the RSLV_RESP_* code to indicate the type of
891 * error found.
892 */
893static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
894 struct resolv_resolution *resolution, int max_answer_records)
895{
896 unsigned char *reader;
897 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
898 int len, flags, offset;
899 int query_record_id;
900 int nb_saved_records;
901 struct resolv_query_item *query;
902 struct resolv_answer_item *answer_record, *tmp_record;
903 struct resolv_response *r_res;
904 int i, found = 0;
905 int cause = RSLV_RESP_ERROR;
906
907 reader = resp;
908 len = 0;
909 previous_dname = NULL;
910 query = NULL;
911 answer_record = NULL;
912
913 /* Initialization of response buffer and structure */
914 r_res = &resolution->response;
915
916 /* query id */
917 if (reader + 2 >= bufend)
918 goto invalid_resp;
919
920 r_res->header.id = reader[0] * 256 + reader[1];
921 reader += 2;
922
923 /* Flags and rcode are stored over 2 bytes
924 * First byte contains:
925 * - response flag (1 bit)
926 * - opcode (4 bits)
927 * - authoritative (1 bit)
928 * - truncated (1 bit)
929 * - recursion desired (1 bit)
930 */
931 if (reader + 2 >= bufend)
932 goto invalid_resp;
933
934 flags = reader[0] * 256 + reader[1];
935
936 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
937 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
938 cause = RSLV_RESP_NX_DOMAIN;
939 goto return_error;
940 }
941 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
942 cause = RSLV_RESP_REFUSED;
943 goto return_error;
944 }
945 else {
946 cause = RSLV_RESP_ERROR;
947 goto return_error;
948 }
949 }
950
951 /* Move forward 2 bytes for flags */
952 reader += 2;
953
954 /* 2 bytes for question count */
955 if (reader + 2 >= bufend)
956 goto invalid_resp;
957 r_res->header.qdcount = reader[0] * 256 + reader[1];
958 /* (for now) we send one query only, so we expect only one in the
959 * response too */
960 if (r_res->header.qdcount != 1) {
961 cause = RSLV_RESP_QUERY_COUNT_ERROR;
962 goto return_error;
963 }
964
965 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
966 goto invalid_resp;
967 reader += 2;
968
969 /* 2 bytes for answer count */
970 if (reader + 2 >= bufend)
971 goto invalid_resp;
972 r_res->header.ancount = reader[0] * 256 + reader[1];
973 if (r_res->header.ancount == 0) {
974 cause = RSLV_RESP_ANCOUNT_ZERO;
975 goto return_error;
976 }
977
978 /* Check if too many records are announced */
979 if (r_res->header.ancount > max_answer_records)
980 goto invalid_resp;
981 reader += 2;
982
983 /* 2 bytes authority count */
984 if (reader + 2 >= bufend)
985 goto invalid_resp;
986 r_res->header.nscount = reader[0] * 256 + reader[1];
987 reader += 2;
988
989 /* 2 bytes additional count */
990 if (reader + 2 >= bufend)
991 goto invalid_resp;
992 r_res->header.arcount = reader[0] * 256 + reader[1];
993 reader += 2;
994
995 /* Parsing dns queries */
Willy Tarreau51128f82021-10-19 11:17:33 +0200996 BUG_ON(!LIST_ISEMPTY(&r_res->query_list));
Emeric Brunc9437992021-02-12 19:42:55 +0100997 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
998 /* Use next pre-allocated resolv_query_item after ensuring there is
999 * still one available.
1000 * It's then added to our packet query list. */
1001 if (query_record_id > DNS_MAX_QUERY_RECORDS)
1002 goto invalid_resp;
1003 query = &resolution->response_query_records[query_record_id];
Willy Tarreau2b718102021-04-21 07:32:39 +02001004 LIST_APPEND(&r_res->query_list, &query->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001005
1006 /* Name is a NULL terminated string in our case, since we have
1007 * one query per response and the first one can't be compressed
1008 * (using the 0x0c format) */
1009 offset = 0;
1010 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
1011
1012 if (len == 0)
1013 goto invalid_resp;
1014
1015 reader += offset;
1016 previous_dname = query->name;
1017
1018 /* move forward 2 bytes for question type */
1019 if (reader + 2 >= bufend)
1020 goto invalid_resp;
1021 query->type = reader[0] * 256 + reader[1];
1022 reader += 2;
1023
1024 /* move forward 2 bytes for question class */
1025 if (reader + 2 >= bufend)
1026 goto invalid_resp;
1027 query->class = reader[0] * 256 + reader[1];
1028 reader += 2;
1029 }
1030
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001031 /* Let's just make gcc happy. The tests above make it clear that
1032 * qdcount==1 hence that we necessarily enter into the loop at least
1033 * once, but gcc seems to be having difficulties following it and
1034 * warns about the risk of NULL dereference at the next line, even
1035 * if a BUG_ON(!query) is used.
1036 */
1037 ALREADY_CHECKED(query);
1038
Emeric Brunc9437992021-02-12 19:42:55 +01001039 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau3a8897f2021-10-20 17:29:28 +02001040 * because a TRUNCATED SRV query type response can still be exploited
1041 */
Emeric Brunc9437992021-02-12 19:42:55 +01001042 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1043 cause = RSLV_RESP_TRUNCATED;
1044 goto return_error;
1045 }
1046
1047 /* now parsing response records */
1048 nb_saved_records = 0;
1049 for (i = 0; i < r_res->header.ancount; i++) {
1050 if (reader >= bufend)
1051 goto invalid_resp;
1052
1053 answer_record = pool_alloc(resolv_answer_item_pool);
1054 if (answer_record == NULL)
1055 goto invalid_resp;
1056
1057 /* initialization */
1058 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001059 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001060 LIST_INIT(&answer_record->attached_servers);
Willy Tarreaua2373e82021-10-19 11:29:21 +02001061 LIST_INIT(&answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001062
1063 offset = 0;
1064 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1065
1066 if (len == 0)
1067 goto invalid_resp;
1068
1069 /* Check if the current record dname is valid. previous_dname
1070 * points either to queried dname or last CNAME target */
1071 if (query->type != DNS_RTYPE_SRV && resolv_hostname_cmp(previous_dname, tmpname, len) != 0) {
1072 if (i == 0) {
1073 /* First record, means a mismatch issue between
1074 * queried dname and dname found in the first
1075 * record */
1076 goto invalid_resp;
1077 }
1078 else {
1079 /* If not the first record, this means we have a
1080 * CNAME resolution error.
1081 */
1082 cause = RSLV_RESP_CNAME_ERROR;
1083 goto return_error;
1084 }
1085
1086 }
1087
1088 memcpy(answer_record->name, tmpname, len);
1089 answer_record->name[len] = 0;
1090
1091 reader += offset;
1092 if (reader >= bufend)
1093 goto invalid_resp;
1094
1095 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1096 if (reader + 2 > bufend)
1097 goto invalid_resp;
1098
1099 answer_record->type = reader[0] * 256 + reader[1];
1100 reader += 2;
1101
1102 /* 2 bytes for class (2) */
1103 if (reader + 2 > bufend)
1104 goto invalid_resp;
1105
1106 answer_record->class = reader[0] * 256 + reader[1];
1107 reader += 2;
1108
1109 /* 4 bytes for ttl (4) */
1110 if (reader + 4 > bufend)
1111 goto invalid_resp;
1112
1113 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1114 + reader[2] * 256 + reader[3];
1115 reader += 4;
1116
1117 /* Now reading data len */
1118 if (reader + 2 > bufend)
1119 goto invalid_resp;
1120
1121 answer_record->data_len = reader[0] * 256 + reader[1];
1122
1123 /* Move forward 2 bytes for data len */
1124 reader += 2;
1125
1126 if (reader + answer_record->data_len > bufend)
1127 goto invalid_resp;
1128
1129 /* Analyzing record content */
1130 switch (answer_record->type) {
1131 case DNS_RTYPE_A:
1132 /* ipv4 is stored on 4 bytes */
1133 if (answer_record->data_len != 4)
1134 goto invalid_resp;
1135
Willy Tarreau20a02372021-10-14 22:52:04 +02001136 answer_record->data.in4.sin_family = AF_INET;
1137 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001138 break;
1139
1140 case DNS_RTYPE_CNAME:
1141 /* Check if this is the last record and update the caller about the status:
1142 * no IP could be found and last record was a CNAME. Could be triggered
1143 * by a wrong query type
1144 *
1145 * + 1 because answer_record_id starts at 0
1146 * while number of answers is an integer and
1147 * starts at 1.
1148 */
1149 if (i + 1 == r_res->header.ancount) {
1150 cause = RSLV_RESP_CNAME_ERROR;
1151 goto return_error;
1152 }
1153
1154 offset = 0;
1155 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1156 if (len == 0)
1157 goto invalid_resp;
1158
Willy Tarreau20a02372021-10-14 22:52:04 +02001159 memcpy(answer_record->data.target, tmpname, len);
1160 answer_record->data.target[len] = 0;
1161 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001162 break;
1163
1164
1165 case DNS_RTYPE_SRV:
1166 /* Answer must contain :
1167 * - 2 bytes for the priority
1168 * - 2 bytes for the weight
1169 * - 2 bytes for the port
1170 * - the target hostname
1171 */
1172 if (answer_record->data_len <= 6)
1173 goto invalid_resp;
1174
1175 answer_record->priority = read_n16(reader);
1176 reader += sizeof(uint16_t);
1177 answer_record->weight = read_n16(reader);
1178 reader += sizeof(uint16_t);
1179 answer_record->port = read_n16(reader);
1180 reader += sizeof(uint16_t);
1181 offset = 0;
1182 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1183 if (len == 0)
1184 goto invalid_resp;
1185
1186 answer_record->data_len = len;
Willy Tarreau20a02372021-10-14 22:52:04 +02001187 memcpy(answer_record->data.target, tmpname, len);
1188 answer_record->data.target[len] = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01001189 if (answer_record->ar_item != NULL) {
1190 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1191 answer_record->ar_item = NULL;
1192 }
1193 break;
1194
1195 case DNS_RTYPE_AAAA:
1196 /* ipv6 is stored on 16 bytes */
1197 if (answer_record->data_len != 16)
1198 goto invalid_resp;
1199
Willy Tarreau20a02372021-10-14 22:52:04 +02001200 answer_record->data.in6.sin6_family = AF_INET6;
1201 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001202 break;
1203
1204 } /* switch (record type) */
1205
1206 /* Increment the counter for number of records saved into our
1207 * local response */
1208 nb_saved_records++;
1209
1210 /* Move forward answer_record->data_len for analyzing next
1211 * record in the response */
1212 reader += ((answer_record->type == DNS_RTYPE_SRV)
1213 ? offset
1214 : answer_record->data_len);
1215
1216 /* Lookup to see if we already had this entry */
1217 found = 0;
1218 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1219 if (tmp_record->type != answer_record->type)
1220 continue;
1221
1222 switch(tmp_record->type) {
1223 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001224 if (!memcmp(&answer_record->data.in4.sin_addr,
1225 &tmp_record->data.in4.sin_addr,
1226 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001227 found = 1;
1228 break;
1229
1230 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001231 if (!memcmp(&answer_record->data.in6.sin6_addr,
1232 &tmp_record->data.in6.sin6_addr,
1233 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001234 found = 1;
1235 break;
1236
1237 case DNS_RTYPE_SRV:
1238 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001239 !resolv_hostname_cmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) &&
Emeric Brunc9437992021-02-12 19:42:55 +01001240 answer_record->port == tmp_record->port) {
1241 tmp_record->weight = answer_record->weight;
1242 found = 1;
1243 }
1244 break;
1245
1246 default:
1247 break;
1248 }
1249
1250 if (found == 1)
1251 break;
1252 }
1253
1254 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001255 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001256 pool_free(resolv_answer_item_pool, answer_record);
1257 answer_record = NULL;
1258 }
1259 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001260 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001261 answer_record->ar_item = NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +02001262 LIST_APPEND(&r_res->answer_list, &answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001263 answer_record = NULL;
1264 }
1265 } /* for i 0 to ancount */
1266
1267 /* Save the number of records we really own */
1268 r_res->header.ancount = nb_saved_records;
1269
1270 /* now parsing additional records for SRV queries only */
1271 if (query->type != DNS_RTYPE_SRV)
1272 goto skip_parsing_additional_records;
1273
1274 /* if we find Authority records, just skip them */
1275 for (i = 0; i < r_res->header.nscount; i++) {
1276 offset = 0;
1277 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1278 &offset, 0);
1279 if (len == 0)
1280 continue;
1281
1282 if (reader + offset + 10 >= bufend)
1283 goto invalid_resp;
1284
1285 reader += offset;
1286 /* skip 2 bytes for class */
1287 reader += 2;
1288 /* skip 2 bytes for type */
1289 reader += 2;
1290 /* skip 4 bytes for ttl */
1291 reader += 4;
1292 /* read data len */
1293 len = reader[0] * 256 + reader[1];
1294 reader += 2;
1295
1296 if (reader + len >= bufend)
1297 goto invalid_resp;
1298
1299 reader += len;
1300 }
1301
1302 nb_saved_records = 0;
1303 for (i = 0; i < r_res->header.arcount; i++) {
1304 if (reader >= bufend)
1305 goto invalid_resp;
1306
1307 answer_record = pool_alloc(resolv_answer_item_pool);
1308 if (answer_record == NULL)
1309 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001310 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001311 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001312
1313 offset = 0;
1314 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1315
1316 if (len == 0) {
1317 pool_free(resolv_answer_item_pool, answer_record);
1318 answer_record = NULL;
1319 continue;
1320 }
1321
1322 memcpy(answer_record->name, tmpname, len);
1323 answer_record->name[len] = 0;
1324
1325 reader += offset;
1326 if (reader >= bufend)
1327 goto invalid_resp;
1328
1329 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1330 if (reader + 2 > bufend)
1331 goto invalid_resp;
1332
1333 answer_record->type = reader[0] * 256 + reader[1];
1334 reader += 2;
1335
1336 /* 2 bytes for class (2) */
1337 if (reader + 2 > bufend)
1338 goto invalid_resp;
1339
1340 answer_record->class = reader[0] * 256 + reader[1];
1341 reader += 2;
1342
1343 /* 4 bytes for ttl (4) */
1344 if (reader + 4 > bufend)
1345 goto invalid_resp;
1346
1347 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1348 + reader[2] * 256 + reader[3];
1349 reader += 4;
1350
1351 /* Now reading data len */
1352 if (reader + 2 > bufend)
1353 goto invalid_resp;
1354
1355 answer_record->data_len = reader[0] * 256 + reader[1];
1356
1357 /* Move forward 2 bytes for data len */
1358 reader += 2;
1359
1360 if (reader + answer_record->data_len > bufend)
1361 goto invalid_resp;
1362
1363 /* Analyzing record content */
1364 switch (answer_record->type) {
1365 case DNS_RTYPE_A:
1366 /* ipv4 is stored on 4 bytes */
1367 if (answer_record->data_len != 4)
1368 goto invalid_resp;
1369
Willy Tarreau20a02372021-10-14 22:52:04 +02001370 answer_record->data.in4.sin_family = AF_INET;
1371 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001372 break;
1373
1374 case DNS_RTYPE_AAAA:
1375 /* ipv6 is stored on 16 bytes */
1376 if (answer_record->data_len != 16)
1377 goto invalid_resp;
1378
Willy Tarreau20a02372021-10-14 22:52:04 +02001379 answer_record->data.in6.sin6_family = AF_INET6;
1380 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001381 break;
1382
1383 default:
1384 pool_free(resolv_answer_item_pool, answer_record);
1385 answer_record = NULL;
1386 continue;
1387
1388 } /* switch (record type) */
1389
1390 /* Increment the counter for number of records saved into our
1391 * local response */
1392 nb_saved_records++;
1393
1394 /* Move forward answer_record->data_len for analyzing next
1395 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001396 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001397
1398 /* Lookup to see if we already had this entry */
1399 found = 0;
1400 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001401 struct resolv_answer_item *ar_item;
1402
1403 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1404 continue;
1405
1406 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001407 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001408 len != tmp_record->data_len ||
Willy Tarreau20a02372021-10-14 22:52:04 +02001409 resolv_hostname_cmp(answer_record->name, tmp_record->data.target, tmp_record->data_len))
Emeric Brunc9437992021-02-12 19:42:55 +01001410 continue;
1411
Christopher Faulet77f86062021-03-10 15:19:57 +01001412 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001413 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001414 if (!memcmp(&answer_record->data.in4.sin_addr,
1415 &ar_item->data.in4.sin_addr,
1416 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001417 found = 1;
1418 break;
1419
1420 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001421 if (!memcmp(&answer_record->data.in6.sin6_addr,
1422 &ar_item->data.in6.sin6_addr,
1423 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001424 found = 1;
1425 break;
1426
1427 default:
1428 break;
1429 }
1430
1431 if (found == 1)
1432 break;
1433 }
1434
1435 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001436 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001437 pool_free(resolv_answer_item_pool, answer_record);
1438 answer_record = NULL;
1439 }
1440 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001441 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001442 answer_record->ar_item = NULL;
1443
1444 // looking for the SRV record in the response list linked to this additional record
1445 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1446 if (tmp_record->type == DNS_RTYPE_SRV &&
1447 tmp_record->ar_item == NULL &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001448 !resolv_hostname_cmp(tmp_record->data.target, answer_record->name, tmp_record->data_len)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001449 /* Always use the received additional record to refresh info */
1450 if (tmp_record->ar_item)
1451 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1452 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001453 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001454 break;
1455 }
1456 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001457 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001458 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001459 answer_record = NULL;
1460 }
Emeric Brunc9437992021-02-12 19:42:55 +01001461 }
1462 } /* for i 0 to arcount */
1463
1464 skip_parsing_additional_records:
1465
1466 /* Save the number of records we really own */
1467 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001468 resolv_check_response(resolution);
1469 return RSLV_RESP_VALID;
1470
1471 invalid_resp:
1472 cause = RSLV_RESP_INVALID;
1473
1474 return_error:
1475 pool_free(resolv_answer_item_pool, answer_record);
1476 return cause;
1477}
1478
1479/* Searches dn_name resolution in resp.
1480 * If existing IP not found, return the first IP matching family_priority,
1481 * otherwise, first ip found
1482 * The following tasks are the responsibility of the caller:
1483 * - <r_res> contains an error free DNS response
1484 * For both cases above, resolv_validate_dns_response is required
1485 * returns one of the RSLV_UPD_* code
1486 */
1487int resolv_get_ip_from_response(struct resolv_response *r_res,
1488 struct resolv_options *resolv_opts, void *currentip,
1489 short currentip_sin_family,
1490 void **newip, short *newip_sin_family,
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001491 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001492{
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001493 struct resolv_answer_item *record, *found_record = NULL;
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 Brunf9ca5d82021-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
1527 list_for_each_entry(record, &r_res->answer_list, list) {
1528 void *ip;
1529 unsigned char ip_type;
1530
1531 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001532 ip_type = AF_INET;
Willy Tarreau20a02372021-10-14 22:52:04 +02001533 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001534 }
1535 else if (record->type == DNS_RTYPE_AAAA) {
1536 ip_type = AF_INET6;
Willy Tarreau20a02372021-10-14 22:52:04 +02001537 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001538 }
1539 else
1540 continue;
1541 score = 0;
1542
1543 /* Check for preferred ip protocol. */
1544 if (ip_type == family_priority)
1545 score += 8;
1546
1547 /* Check for preferred network. */
1548 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1549
1550 /* Compare only the same addresses class. */
1551 if (resolv_opts->pref_net[j].family != ip_type)
1552 continue;
1553
1554 if ((ip_type == AF_INET &&
1555 in_net_ipv4(ip,
1556 &resolv_opts->pref_net[j].mask.in4,
1557 &resolv_opts->pref_net[j].addr.in4)) ||
1558 (ip_type == AF_INET6 &&
1559 in_net_ipv6(ip,
1560 &resolv_opts->pref_net[j].mask.in6,
1561 &resolv_opts->pref_net[j].addr.in6))) {
1562 score += 4;
1563 break;
1564 }
1565 }
1566
1567 /* Check if the IP found in the record is already affected to a
1568 * member of a group. If not, the score should be incremented
1569 * by 2. */
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001570 if (owner) {
1571 struct server *srv;
1572 int already_used = 0;
1573
1574 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1575 if (srv == owner)
1576 continue;
1577 if (srv->proxy == owner->proxy) {
1578 already_used = 1;
1579 break;
1580 }
1581 }
1582 if (already_used) {
1583 if (!allowed_duplicated_ip) {
1584 continue;
1585 }
1586 }
1587 else {
1588 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001589 }
1590 } else {
1591 score += 2;
1592 }
1593
1594 /* Check for current ip matching. */
1595 if (ip_type == currentip_sin_family &&
1596 ((currentip_sin_family == AF_INET &&
1597 !memcmp(ip, currentip, 4)) ||
1598 (currentip_sin_family == AF_INET6 &&
1599 !memcmp(ip, currentip, 16)))) {
1600 score++;
1601 currentip_sel = 1;
1602 }
1603 else
1604 currentip_sel = 0;
1605
1606 /* Keep the address if the score is better than the previous
1607 * score. The maximum score is 15, if this value is reached, we
1608 * break the parsing. Implicitly, this score is reached the ip
1609 * selected is the current ip. */
1610 if (score > max_score) {
1611 if (ip_type == AF_INET)
1612 newip4 = ip;
1613 else
1614 newip6 = ip;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001615 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001616 currentip_found = currentip_sel;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001617 if (score == 15) {
1618 /* this was not registered on the current record but it matches
1619 * let's fix it (it may comes from state file */
1620 if (owner)
1621 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001622 return RSLV_UPD_NO;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001623 }
Emeric Brunc9437992021-02-12 19:42:55 +01001624 max_score = score;
1625 }
1626 } /* list for each record entries */
1627
1628 /* No IP found in the response */
1629 if (!newip4 && !newip6)
1630 return RSLV_UPD_NO_IP_FOUND;
1631
1632 /* Case when the caller looks first for an IPv4 address */
1633 if (family_priority == AF_INET) {
1634 if (newip4) {
1635 *newip = newip4;
1636 *newip_sin_family = AF_INET;
1637 }
1638 else if (newip6) {
1639 *newip = newip6;
1640 *newip_sin_family = AF_INET6;
1641 }
Emeric Brunc9437992021-02-12 19:42:55 +01001642 }
1643 /* Case when the caller looks first for an IPv6 address */
1644 else if (family_priority == AF_INET6) {
1645 if (newip6) {
1646 *newip = newip6;
1647 *newip_sin_family = AF_INET6;
1648 }
1649 else if (newip4) {
1650 *newip = newip4;
1651 *newip_sin_family = AF_INET;
1652 }
Emeric Brunc9437992021-02-12 19:42:55 +01001653 }
1654 /* Case when the caller have no preference (we prefer IPv6) */
1655 else if (family_priority == AF_UNSPEC) {
1656 if (newip6) {
1657 *newip = newip6;
1658 *newip_sin_family = AF_INET6;
1659 }
1660 else if (newip4) {
1661 *newip = newip4;
1662 *newip_sin_family = AF_INET;
1663 }
Emeric Brunc9437992021-02-12 19:42:55 +01001664 }
1665
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001666 /* the ip of this record was chosen for the server */
1667 if (owner && found_record) {
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001668 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001669 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1670 }
1671
Emeric Brunc9437992021-02-12 19:42:55 +01001672 list_for_each_entry(record, &r_res->answer_list, list) {
1673 /* Move the first record to the end of the list, for internal
1674 * round robin */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001675 LIST_DEL_INIT(&record->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02001676 LIST_APPEND(&r_res->answer_list, &record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001677 break;
1678 }
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001679
1680 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001681}
1682
Willy Tarreauca0170b2021-10-14 08:05:25 +02001683/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001684 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001685 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1686 * null-terminated. <str> must be allocated large enough to contain a full host
1687 * name plus the trailing zero, and the allocated size must be passed in
1688 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001689 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001690 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001691 * <str> (including the terminating null byte).
1692 */
1693int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1694{
1695 char *ptr;
1696 int i, sz;
1697
Willy Tarreauca0170b2021-10-14 08:05:25 +02001698 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001699 return -1;
1700
1701 ptr = str;
Willy Tarreauca0170b2021-10-14 08:05:25 +02001702 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001703 sz = dn[i];
1704 if (i)
1705 *ptr++ = '.';
1706 memcpy(ptr, dn+i+1, sz);
1707 ptr += sz;
1708 i += sz;
1709 }
1710 *ptr++ = '\0';
1711 return (ptr - str);
1712}
1713
1714/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1715 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001716 * <str> contains the input string that is <str_len> bytes long (trailing zero
1717 * not needed). <dn> buffer must be allocated large enough to contain the
1718 * encoded string and a trailing zero, so it must be at least str_len+2, and
1719 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001720 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001721 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001722 * <dn> (excluding the terminating null byte).
1723 */
1724int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1725{
1726 int i, offset;
1727
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001728 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001729 return -1;
1730
1731 /* First byte of dn will be used to store the length of the first
1732 * label */
1733 offset = 0;
1734 for (i = 0; i < str_len; ++i) {
1735 if (str[i] == '.') {
1736 /* 2 or more consecutive dots is invalid */
1737 if (i == offset)
1738 return -1;
1739
1740 /* ignore trailing dot */
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001741 if (i + 1 == str_len) {
Emeric Brunc9437992021-02-12 19:42:55 +01001742 i++;
1743 break;
1744 }
1745
1746 dn[offset] = (i - offset);
1747 offset = i+1;
1748 continue;
1749 }
1750 dn[i+1] = str[i];
1751 }
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001752 dn[offset] = i - offset;
Willy Tarreau68c7b362021-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 &&
1826 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1827 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 &&
1836 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1837 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) {
Willy Tarreau51128f82021-10-19 11:17:33 +02001844 int i;
1845
Emeric Brunc9437992021-02-12 19:42:55 +01001846 res->resolvers = resolvers;
1847 res->uuid = resolution_uuid;
1848 res->status = RSLV_STATUS_NONE;
1849 res->step = RSLV_STEP_NONE;
1850 res->last_valid = now_ms;
1851
1852 LIST_INIT(&res->requesters);
Willy Tarreau51128f82021-10-19 11:17:33 +02001853 LIST_INIT(&res->response.query_list);
Emeric Brunc9437992021-02-12 19:42:55 +01001854 LIST_INIT(&res->response.answer_list);
1855
Willy Tarreau51128f82021-10-19 11:17:33 +02001856 for (i = 0; i < DNS_MAX_QUERY_RECORDS; i++)
1857 LIST_INIT(&res->response_query_records[i].list);
1858
Emeric Brunc9437992021-02-12 19:42:55 +01001859 res->prefered_query_type = query_type;
1860 res->query_type = query_type;
1861 res->hostname_dn = *hostname_dn;
1862 res->hostname_dn_len = hostname_dn_len;
1863
1864 ++resolution_uuid;
1865
1866 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001867 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001868 }
1869 return res;
1870}
1871
Willy Tarreauaab75932021-10-19 11:16:11 +02001872/* deletes and frees all answer_items from the resolution's answer_list */
1873static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001874{
1875 struct resolv_answer_item *item, *itemback;
1876
1877 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001878 LIST_DEL_INIT(&item->list);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001879 pool_free(resolv_answer_item_pool, item->ar_item);
1880 pool_free(resolv_answer_item_pool, item);
1881 }
1882}
1883
Willy Tarreau51128f82021-10-19 11:17:33 +02001884/* deletes all query_items from the resolution's query_list */
1885static void resolv_purge_resolution_query_items(struct resolv_resolution *resolution)
1886{
1887 struct resolv_query_item *item, *itemback;
1888
1889 list_for_each_entry_safe(item, itemback, &resolution->response.query_list, list)
1890 LIST_DEL_INIT(&item->list);
1891}
1892
Emeric Brunc9437992021-02-12 19:42:55 +01001893/* Releases a resolution from its requester(s) and move it back to the pool */
1894static void resolv_free_resolution(struct resolv_resolution *resolution)
1895{
1896 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001897
1898 /* clean up configuration */
1899 resolv_reset_resolution(resolution);
1900 resolution->hostname_dn = NULL;
1901 resolution->hostname_dn_len = 0;
1902
1903 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001904 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001905 req->resolution = NULL;
1906 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001907 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau51128f82021-10-19 11:17:33 +02001908 resolv_purge_resolution_query_items(resolution);
1909
Willy Tarreau8c3c5232021-10-19 22:01:36 +02001910 LIST_DEL_INIT(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001911 pool_free(resolv_resolution_pool, resolution);
1912}
1913
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001914/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
1915 * and makes it owned by this obj_type, with the proposed callback and error
1916 * callback. On success, *req is assigned the allocated requester. Returns
1917 * NULL on allocation failure.
1918 */
1919static struct resolv_requester *
1920resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
1921 int (*cb)(struct resolv_requester *, struct dns_counters *),
1922 int (*err_cb)(struct resolv_requester *, int))
1923{
1924 struct resolv_requester *tmp;
1925
1926 if (*req)
1927 return *req;
1928
1929 tmp = pool_alloc(resolv_requester_pool);
1930 if (!tmp)
1931 goto end;
1932
1933 LIST_INIT(&tmp->list);
1934 tmp->owner = owner;
1935 tmp->resolution = NULL;
1936 tmp->requester_cb = cb;
1937 tmp->requester_error_cb = err_cb;
1938 *req = tmp;
1939 end:
1940 return tmp;
1941}
1942
Emeric Brunc9437992021-02-12 19:42:55 +01001943/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
Christopher Faulet7a3a5362021-11-02 16:25:05 +01001944 * on success, -1 otherwise.
Emeric Brunc9437992021-02-12 19:42:55 +01001945 */
1946int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1947{
1948 struct resolv_resolution *res = NULL;
1949 struct resolv_requester *req;
1950 struct resolvers *resolvers;
1951 struct server *srv = NULL;
1952 struct resolv_srvrq *srvrq = NULL;
1953 struct stream *stream = NULL;
1954 char **hostname_dn;
1955 int hostname_dn_len, query_type;
1956
Christopher Faulet7a3a5362021-11-02 16:25:05 +01001957 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01001958 switch (requester_type) {
1959 case OBJ_TYPE_SERVER:
1960 srv = (struct server *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001961
1962 if (!requester_locked)
1963 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1964
1965 req = resolv_get_requester(&srv->resolv_requester,
1966 &srv->obj_type,
1967 snr_resolution_cb,
1968 snr_resolution_error_cb);
1969
1970 if (!requester_locked)
1971 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1972
1973 if (!req)
1974 goto err;
1975
Emeric Brunc9437992021-02-12 19:42:55 +01001976 hostname_dn = &srv->hostname_dn;
1977 hostname_dn_len = srv->hostname_dn_len;
1978 resolvers = srv->resolvers;
1979 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1980 ? DNS_RTYPE_A
1981 : DNS_RTYPE_AAAA);
1982 break;
1983
1984 case OBJ_TYPE_SRVRQ:
1985 srvrq = (struct resolv_srvrq *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02001986
1987 req = resolv_get_requester(&srvrq->requester,
1988 &srvrq->obj_type,
1989 snr_resolution_cb,
1990 srvrq_resolution_error_cb);
1991 if (!req)
1992 goto err;
1993
Emeric Brunc9437992021-02-12 19:42:55 +01001994 hostname_dn = &srvrq->hostname_dn;
1995 hostname_dn_len = srvrq->hostname_dn_len;
1996 resolvers = srvrq->resolvers;
1997 query_type = DNS_RTYPE_SRV;
1998 break;
1999
2000 case OBJ_TYPE_STREAM:
2001 stream = (struct stream *)requester;
Willy Tarreau4d7ca912021-10-19 11:59:25 +02002002
2003 req = resolv_get_requester(&stream->resolv_ctx.requester,
2004 &stream->obj_type,
2005 act_resolution_cb,
2006 act_resolution_error_cb);
2007 if (!req)
2008 goto err;
2009
Emeric Brunc9437992021-02-12 19:42:55 +01002010 hostname_dn = &stream->resolv_ctx.hostname_dn;
2011 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
2012 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
2013 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
2014 ? DNS_RTYPE_A
2015 : DNS_RTYPE_AAAA);
2016 break;
2017 default:
2018 goto err;
2019 }
2020
2021 /* Get a resolution from the resolvers' wait queue or pool */
2022 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
2023 goto err;
2024
Willy Tarreau4d7ca912021-10-19 11:59:25 +02002025 req->resolution = res;
Emeric Brunc9437992021-02-12 19:42:55 +01002026
Willy Tarreau2b718102021-04-21 07:32:39 +02002027 LIST_APPEND(&res->requesters, &req->list);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002028 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002029 return 0;
2030
2031 err:
2032 if (res && LIST_ISEMPTY(&res->requesters))
2033 resolv_free_resolution(res);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002034 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002035 return -1;
2036}
2037
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002038/* This function removes all server/srvrq references on answer items. */
Willy Tarreau33360872021-10-20 14:07:31 +02002039void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002040{
2041 struct resolv_answer_item *item, *itemback;
2042 struct server *srv, *srvback;
2043 struct resolv_srvrq *srvrq;
2044
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002045 enter_resolver_code();
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002046 if ((srv = objt_server(req->owner)) != NULL) {
2047 LIST_DEL_INIT(&srv->ip_rec_item);
2048 }
2049 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
2050 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
2051 if (item->type == DNS_RTYPE_SRV) {
2052 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet5f8ccff2021-06-15 16:08:48 +02002053 if (srv->srvrq == srvrq)
Willy Tarreau20751652021-10-18 16:46:38 +02002054 resolv_srvrq_cleanup_srv(srv);
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002055 }
2056 }
2057 }
2058 }
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002059 leave_resolver_code();
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002060}
2061
Emeric Brunc9437992021-02-12 19:42:55 +01002062/* Removes a requester from a DNS resolution. It takes takes care of all the
2063 * consequences. It also cleans up some parameters from the requester.
2064 */
Willy Tarreau33360872021-10-20 14:07:31 +02002065static void _resolv_unlink_resolution(struct resolv_requester *requester)
Emeric Brunc9437992021-02-12 19:42:55 +01002066{
2067 struct resolv_resolution *res;
2068 struct resolv_requester *req;
2069
2070 /* Nothing to do */
2071 if (!requester || !requester->resolution)
2072 return;
2073 res = requester->resolution;
2074
2075 /* Clean up the requester */
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002076 LIST_DEL_INIT(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002077 requester->resolution = NULL;
2078
Christopher Faulete7e0e4b2021-10-29 10:38:15 +02002079 /* remove ref from the resolution answer item list to the requester */
2080 resolv_detach_from_resolution_answer_items(res, requester);
2081
Emeric Brunc9437992021-02-12 19:42:55 +01002082 /* We need to find another requester linked on this resolution */
2083 if (!LIST_ISEMPTY(&res->requesters))
2084 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2085 else {
Willy Tarreau20751652021-10-18 16:46:38 +02002086 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002087 return;
2088 }
2089
2090 /* Move hostname_dn related pointers to the next requester */
2091 switch (obj_type(req->owner)) {
2092 case OBJ_TYPE_SERVER:
2093 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2094 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2095 break;
2096 case OBJ_TYPE_SRVRQ:
2097 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2098 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2099 break;
2100 case OBJ_TYPE_STREAM:
2101 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2102 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2103 break;
2104 default:
2105 res->hostname_dn = NULL;
2106 res->hostname_dn_len = 0;
2107 break;
2108 }
2109}
2110
Willy Tarreau20751652021-10-18 16:46:38 +02002111/* The public version of the function above that deals with the death row. */
Willy Tarreau33360872021-10-20 14:07:31 +02002112void resolv_unlink_resolution(struct resolv_requester *requester)
Willy Tarreau20751652021-10-18 16:46:38 +02002113{
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002114 enter_resolver_code();
Willy Tarreau33360872021-10-20 14:07:31 +02002115 _resolv_unlink_resolution(requester);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002116 leave_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002117}
2118
Emeric Brunc9437992021-02-12 19:42:55 +01002119/* Called when a network IO is generated on a name server socket for an incoming
2120 * packet. It performs the following actions:
2121 * - check if the packet requires processing (not outdated resolution)
2122 * - ensure the DNS packet received is valid and call requester's callback
2123 * - call requester's error callback if invalid response
2124 * - check the dn_name in the packet against the one sent
2125 */
2126static int resolv_process_responses(struct dns_nameserver *ns)
2127{
2128 struct dns_counters *tmpcounters;
2129 struct resolvers *resolvers;
2130 struct resolv_resolution *res;
2131 struct resolv_query_item *query;
2132 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2133 unsigned char *bufend;
2134 int buflen, dns_resp;
2135 int max_answer_records;
2136 unsigned short query_id;
2137 struct eb32_node *eb;
2138 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002139 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002140
2141 resolvers = ns->parent;
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002142 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002143 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2144
2145 /* process all pending input messages */
2146 while (1) {
2147 /* read message received */
2148 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2149 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2150 break;
2151 }
2152
2153 /* message too big */
2154 if (buflen > resolvers->accepted_payload_size) {
2155 ns->counters->too_big++;
2156 continue;
2157 }
2158
2159 /* initializing variables */
2160 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2161
2162 /* read the query id from the packet (16 bits) */
2163 if (buf + 2 > bufend) {
2164 ns->counters->invalid++;
2165 continue;
2166 }
2167 query_id = resolv_response_get_query_id(buf);
2168
2169 /* search the query_id in the pending resolution tree */
2170 eb = eb32_lookup(&resolvers->query_ids, query_id);
2171 if (eb == NULL) {
2172 /* unknown query id means an outdated response and can be safely ignored */
2173 ns->counters->outdated++;
2174 continue;
2175 }
2176
2177 /* known query id means a resolution in progress */
2178 res = eb32_entry(eb, struct resolv_resolution, qid);
2179 /* number of responses received */
2180 res->nb_responses++;
2181
2182 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2183 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2184
2185 switch (dns_resp) {
2186 case RSLV_RESP_VALID:
2187 break;
2188
2189 case RSLV_RESP_INVALID:
2190 case RSLV_RESP_QUERY_COUNT_ERROR:
2191 case RSLV_RESP_WRONG_NAME:
2192 res->status = RSLV_STATUS_INVALID;
2193 ns->counters->invalid++;
2194 break;
2195
2196 case RSLV_RESP_NX_DOMAIN:
2197 res->status = RSLV_STATUS_NX;
2198 ns->counters->nx++;
2199 break;
2200
2201 case RSLV_RESP_REFUSED:
2202 res->status = RSLV_STATUS_REFUSED;
2203 ns->counters->refused++;
2204 break;
2205
2206 case RSLV_RESP_ANCOUNT_ZERO:
2207 res->status = RSLV_STATUS_OTHER;
2208 ns->counters->any_err++;
2209 break;
2210
2211 case RSLV_RESP_CNAME_ERROR:
2212 res->status = RSLV_STATUS_OTHER;
2213 ns->counters->cname_error++;
2214 break;
2215
2216 case RSLV_RESP_TRUNCATED:
2217 res->status = RSLV_STATUS_OTHER;
2218 ns->counters->truncated++;
2219 break;
2220
2221 case RSLV_RESP_NO_EXPECTED_RECORD:
2222 case RSLV_RESP_ERROR:
2223 case RSLV_RESP_INTERNAL:
2224 res->status = RSLV_STATUS_OTHER;
2225 ns->counters->other++;
2226 break;
2227 }
2228
2229 /* Wait all nameservers response to handle errors */
2230 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2231 continue;
2232
2233 /* Process error codes */
2234 if (dns_resp != RSLV_RESP_VALID) {
2235 if (res->prefered_query_type != res->query_type) {
2236 /* The fallback on the query type was already performed,
2237 * so check the try counter. If it falls to 0, we can
2238 * report an error. Else, wait the next attempt. */
2239 if (!res->try)
2240 goto report_res_error;
2241 }
2242 else {
2243 /* Fallback from A to AAAA or the opposite and re-send
2244 * the resolution immediately. try counter is not
2245 * decremented. */
2246 if (res->prefered_query_type == DNS_RTYPE_A) {
2247 res->query_type = DNS_RTYPE_AAAA;
2248 resolv_send_query(res);
2249 }
2250 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2251 res->query_type = DNS_RTYPE_A;
2252 resolv_send_query(res);
2253 }
2254 }
2255 continue;
2256 }
2257
2258 /* Now let's check the query's dname corresponds to the one we
2259 * sent. We can check only the first query of the list. We send
Willy Tarreau51128f82021-10-19 11:17:33 +02002260 * one query at a time so we get one query in the response.
2261 */
2262 if (!LIST_ISEMPTY(&res->response.query_list)) {
2263 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
2264 LIST_DEL_INIT(&query->list);
2265 if (resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
2266 dns_resp = RSLV_RESP_WRONG_NAME;
2267 ns->counters->other++;
2268 goto report_res_error;
2269 }
Emeric Brunc9437992021-02-12 19:42:55 +01002270 }
2271
2272 /* So the resolution succeeded */
2273 res->status = RSLV_STATUS_VALID;
2274 res->last_valid = now_ms;
2275 ns->counters->valid++;
2276 goto report_res_success;
2277
2278 report_res_error:
Emeric Brun43839d02021-06-10 15:25:25 +02002279 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002280 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002281 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2282 if (!keep_answer_items)
2283 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002284 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002285 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002286 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002287 continue;
2288
2289 report_res_success:
2290 /* Only the 1rst requester s managed by the server, others are
2291 * from the cache */
2292 tmpcounters = ns->counters;
2293 list_for_each_entry(req, &res->requesters, list) {
2294 struct server *s = objt_server(req->owner);
2295
2296 if (s)
2297 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2298 req->requester_cb(req, tmpcounters);
2299 if (s)
2300 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2301 tmpcounters = NULL;
2302 }
2303
2304 resolv_reset_resolution(res);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002305 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002306 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002307 continue;
2308 }
2309 resolv_update_resolvers_timeout(resolvers);
2310 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002311 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002312 return buflen;
2313}
2314
2315/* Processes DNS resolution. First, it checks the active list to detect expired
2316 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2317 * checks the wait list to trigger new resolutions.
2318 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002319static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002320{
2321 struct resolvers *resolvers = context;
2322 struct resolv_resolution *res, *resback;
2323 int exp;
2324
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002325 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002326 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2327
Willy Tarreau20751652021-10-18 16:46:38 +02002328 /* Handle all expired resolutions from the active list. Elements that
2329 * need to be removed will in fact be moved to the death_row. Other
2330 * ones will be handled normally.
2331 */
2332
Willy Tarreau20751652021-10-18 16:46:38 +02002333 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
2334 while (&res->list != &resolvers->resolutions.curr) {
2335 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2336
Christopher Faulet0efc0992021-03-11 18:09:53 +01002337 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002338 abort_resolution(res);
2339 res = resback;
Christopher Faulet0efc0992021-03-11 18:09:53 +01002340 continue;
2341 }
2342
Emeric Brunc9437992021-02-12 19:42:55 +01002343 /* When we find the first resolution in the future, then we can
2344 * stop here */
2345 exp = tick_add(res->last_query, resolvers->timeout.retry);
2346 if (!tick_is_expired(exp, now_ms))
2347 break;
2348
2349 /* If current resolution has been tried too many times and
2350 * finishes in timeout we update its status and remove it from
2351 * the list */
2352 if (!res->try) {
2353 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002354 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002355
2356 /* Notify the result to the requesters */
2357 if (!res->nb_responses)
2358 res->status = RSLV_STATUS_TIMEOUT;
2359 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002360 keep_answer_items |= req->requester_error_cb(req, res->status);
2361 if (!keep_answer_items)
2362 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002363
2364 /* Clean up resolution info and remove it from the
2365 * current list */
2366 resolv_reset_resolution(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002367
2368 /* subsequent entries might have been deleted here */
2369 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002370 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002371 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Willy Tarreau20751652021-10-18 16:46:38 +02002372 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002373 }
2374 else {
2375 /* Otherwise resend the DNS query and requeue the resolution */
2376 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2377 /* No response received (a real timeout) or fallback already done */
2378 res->query_type = res->prefered_query_type;
2379 res->try--;
2380 }
2381 else {
2382 /* Fallback from A to AAAA or the opposite and re-send
2383 * the resolution immediately. try counter is not
2384 * decremented. */
2385 if (res->prefered_query_type == DNS_RTYPE_A)
2386 res->query_type = DNS_RTYPE_AAAA;
2387 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2388 res->query_type = DNS_RTYPE_A;
2389 else
2390 res->try--;
2391 }
2392 resolv_send_query(res);
Willy Tarreau20751652021-10-18 16:46:38 +02002393 resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
2394 res = resback;
Emeric Brunc9437992021-02-12 19:42:55 +01002395 }
2396 }
2397
2398 /* Handle all resolutions in the wait list */
2399 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002400 if (LIST_ISEMPTY(&res->requesters)) {
Willy Tarreau20751652021-10-18 16:46:38 +02002401 abort_resolution(res);
Christopher Faulet0efc0992021-03-11 18:09:53 +01002402 continue;
2403 }
2404
Emeric Brunc9437992021-02-12 19:42:55 +01002405 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2406 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2407 continue;
2408
2409 if (resolv_run_resolution(res) != 1) {
2410 res->last_resolution = now_ms;
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002411 LIST_DEL_INIT(&res->list);
Willy Tarreau2b718102021-04-21 07:32:39 +02002412 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002413 }
2414 }
Emeric Brunc9437992021-02-12 19:42:55 +01002415 resolv_update_resolvers_timeout(resolvers);
2416 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002417
2418 /* now we can purge all queued deletions */
2419 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002420 return t;
2421}
2422
2423/* Release memory allocated by DNS */
2424static void resolvers_deinit(void)
2425{
2426 struct resolvers *resolvers, *resolversback;
2427 struct dns_nameserver *ns, *nsback;
2428 struct resolv_resolution *res, *resback;
2429 struct resolv_requester *req, *reqback;
2430 struct resolv_srvrq *srvrq, *srvrqback;
2431
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002432 enter_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002433 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2434 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2435 free(ns->id);
2436 free((char *)ns->conf.file);
2437 if (ns->dgram) {
2438 if (ns->dgram->conn.t.sock.fd != -1) {
2439 fd_delete(ns->dgram->conn.t.sock.fd);
2440 close(ns->dgram->conn.t.sock.fd);
2441 }
2442 if (ns->dgram->ring_req)
2443 ring_free(ns->dgram->ring_req);
2444 free(ns->dgram);
2445 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002446 if (ns->stream) {
2447 if (ns->stream->ring_req)
2448 ring_free(ns->stream->ring_req);
2449 if (ns->stream->task_req)
2450 task_destroy(ns->stream->task_req);
2451 if (ns->stream->task_rsp)
2452 task_destroy(ns->stream->task_rsp);
2453 free(ns->stream);
2454 }
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002455 LIST_DEL_INIT(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002456 EXTRA_COUNTERS_FREE(ns->extra_counters);
2457 free(ns);
2458 }
2459
2460 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2461 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002462 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002463 pool_free(resolv_requester_pool, req);
2464 }
Willy Tarreau20751652021-10-18 16:46:38 +02002465 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002466 }
2467
2468 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2469 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002470 LIST_DEL_INIT(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002471 pool_free(resolv_requester_pool, req);
2472 }
Willy Tarreau20751652021-10-18 16:46:38 +02002473 abort_resolution(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002474 }
2475
2476 free(resolvers->id);
2477 free((char *)resolvers->conf.file);
2478 task_destroy(resolvers->t);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002479 LIST_DEL_INIT(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002480 free(resolvers);
2481 }
2482
2483 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2484 free(srvrq->name);
2485 free(srvrq->hostname_dn);
Willy Tarreau8c3c5232021-10-19 22:01:36 +02002486 LIST_DEL_INIT(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002487 free(srvrq);
2488 }
Willy Tarreau20751652021-10-18 16:46:38 +02002489
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002490 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002491}
2492
2493/* Finalizes the DNS configuration by allocating required resources and checking
2494 * live parameters.
2495 * Returns 0 on success, ERR_* flags otherwise.
2496 */
2497static int resolvers_finalize_config(void)
2498{
2499 struct resolvers *resolvers;
2500 struct proxy *px;
2501 int err_code = 0;
2502
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002503 enter_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002504
Emeric Brunc9437992021-02-12 19:42:55 +01002505 /* allocate pool of resolution per resolvers */
2506 list_for_each_entry(resolvers, &sec_resolvers, list) {
2507 struct dns_nameserver *ns;
2508 struct task *t;
2509
2510 /* Check if we can create the socket with nameservers info */
2511 list_for_each_entry(ns, &resolvers->nameservers, list) {
2512 int fd;
2513
2514 if (ns->dgram) {
2515 /* Check nameserver info */
2516 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
2517 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2518 resolvers->id, ns->id);
2519 err_code |= (ERR_ALERT|ERR_ABORT);
2520 continue;
2521 }
2522 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
2523 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2524 resolvers->id, ns->id);
2525 close(fd);
2526 err_code |= (ERR_ALERT|ERR_ABORT);
2527 continue;
2528 }
2529 close(fd);
2530 }
2531 }
2532
2533 /* Create the task associated to the resolvers section */
2534 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2535 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
2536 err_code |= (ERR_ALERT|ERR_ABORT);
2537 goto err;
2538 }
2539
2540 /* Update task's parameters */
2541 t->process = process_resolvers;
2542 t->context = resolvers;
2543 resolvers->t = t;
2544 task_wakeup(t, TASK_WOKEN_INIT);
2545 }
2546
2547 for (px = proxies_list; px; px = px->next) {
2548 struct server *srv;
2549
2550 for (srv = px->srv; srv; srv = srv->next) {
2551 struct resolvers *resolvers;
2552
2553 if (!srv->resolvers_id)
2554 continue;
2555
2556 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
2557 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2558 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2559 err_code |= (ERR_ALERT|ERR_ABORT);
2560 continue;
2561 }
2562 srv->resolvers = resolvers;
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002563 srv->srvrq_check = NULL;
2564 if (srv->srvrq) {
2565 if (!srv->srvrq->resolvers) {
2566 srv->srvrq->resolvers = srv->resolvers;
2567 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2568 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2569 proxy_type_str(px), px->id, srv->id);
2570 err_code |= (ERR_ALERT|ERR_ABORT);
2571 continue;
2572 }
2573 }
Emeric Brunc9437992021-02-12 19:42:55 +01002574
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002575 srv->srvrq_check = task_new(MAX_THREADS_MASK);
2576 if (!srv->srvrq_check) {
2577 ha_alert("config: %s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002578 proxy_type_str(px), px->id, srv->id);
2579 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002580 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002581 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002582 srv->srvrq_check->process = resolv_srvrq_expire_task;
2583 srv->srvrq_check->context = srv;
2584 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002585 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002586 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +01002587 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2588 proxy_type_str(px), px->id, srv->id);
2589 err_code |= (ERR_ALERT|ERR_ABORT);
2590 continue;
2591 }
2592 }
2593 }
2594
2595 if (err_code & (ERR_ALERT|ERR_ABORT))
2596 goto err;
2597
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002598 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002599 return err_code;
2600 err:
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002601 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002602 resolvers_deinit();
2603 return err_code;
2604
2605}
2606
2607static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2608 struct dns_nameserver *ns,
2609 struct field *stats, size_t stats_count,
2610 struct list *stat_modules)
2611{
2612 struct appctx *appctx = __objt_appctx(si->end);
2613 struct channel *rep = si_ic(si);
2614 struct stats_module *mod;
2615 size_t idx = 0;
2616
2617 memset(stats, 0, sizeof(struct field) * stats_count);
2618
2619 list_for_each_entry(mod, stat_modules, list) {
2620 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2621
2622 mod->fill_stats(counters, stats + idx);
2623 idx += mod->stats_count;
2624 }
2625
2626 if (!stats_dump_one_line(stats, idx, appctx))
2627 return 0;
2628
2629 if (!stats_putchk(rep, NULL, &trash))
2630 goto full;
2631
2632 return 1;
2633
2634 full:
2635 si_rx_room_rdy(si);
2636 return 0;
2637}
2638
2639/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2640 * as a pointer to the current nameserver.
2641 */
2642int stats_dump_resolvers(struct stream_interface *si,
2643 struct field *stats, size_t stats_count,
2644 struct list *stat_modules)
2645{
2646 struct appctx *appctx = __objt_appctx(si->end);
2647 struct channel *rep = si_ic(si);
2648 struct resolvers *resolver = appctx->ctx.stats.obj1;
2649 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2650
2651 if (!resolver)
2652 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2653
2654 /* dump resolvers */
2655 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2656 appctx->ctx.stats.obj1 = resolver;
2657
2658 ns = appctx->ctx.stats.obj2 ?
2659 appctx->ctx.stats.obj2 :
2660 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2661
2662 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2663 appctx->ctx.stats.obj2 = ns;
2664
2665 if (buffer_almost_full(&rep->buf))
2666 goto full;
2667
2668 if (!stats_dump_resolv_to_buffer(si, ns,
2669 stats, stats_count,
2670 stat_modules)) {
2671 return 0;
2672 }
2673 }
2674
2675 appctx->ctx.stats.obj2 = NULL;
2676 }
2677
2678 return 1;
2679
2680 full:
2681 si_rx_room_blk(si);
2682 return 0;
2683}
2684
2685void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2686{
2687 struct resolvers *resolvers;
2688 struct dns_nameserver *ns;
2689 struct stats_module *mod;
2690 void *counters;
2691
2692 list_for_each_entry(mod, stat_modules, list) {
2693 if (!mod->clearable && !clrall)
2694 continue;
2695
2696 list_for_each_entry(resolvers, &sec_resolvers, list) {
2697 list_for_each_entry(ns, &resolvers->nameservers, list) {
2698 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2699 memcpy(counters, mod->counters, mod->counters_size);
2700 }
2701 }
2702 }
2703
2704}
2705
2706int resolv_allocate_counters(struct list *stat_modules)
2707{
2708 struct stats_module *mod;
2709 struct resolvers *resolvers;
2710 struct dns_nameserver *ns;
2711
2712 list_for_each_entry(resolvers, &sec_resolvers, list) {
2713 list_for_each_entry(ns, &resolvers->nameservers, list) {
2714 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2715 alloc_failed);
2716
2717 list_for_each_entry(mod, stat_modules, list) {
2718 EXTRA_COUNTERS_ADD(mod,
2719 ns->extra_counters,
2720 mod->counters,
2721 mod->counters_size);
2722 }
2723
2724 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2725
2726 list_for_each_entry(mod, stat_modules, list) {
2727 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2728 mod->counters, mod->counters_size);
2729
2730 /* Store the ns counters pointer */
2731 if (strcmp(mod->name, "dns") == 0) {
2732 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2733 ns->counters->id = ns->id;
2734 ns->counters->pid = resolvers->id;
2735 }
2736 }
2737 }
2738 }
2739
2740 return 1;
2741
2742alloc_failed:
2743 return 0;
2744}
2745
2746/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2747static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2748{
2749 struct resolvers *presolvers;
2750
2751 if (*args[2]) {
2752 list_for_each_entry(presolvers, &sec_resolvers, list) {
2753 if (strcmp(presolvers->id, args[2]) == 0) {
2754 appctx->ctx.cli.p0 = presolvers;
2755 break;
2756 }
2757 }
2758 if (appctx->ctx.cli.p0 == NULL)
2759 return cli_err(appctx, "Can't find that resolvers section\n");
2760 }
2761 return 0;
2762}
2763
2764/* Dumps counters from all resolvers section and associated name servers. It
2765 * returns 0 if the output buffer is full and it needs to be called again,
2766 * otherwise non-zero. It may limit itself to the resolver pointed to by
2767 * <cli.p0> if it's not null.
2768 */
2769static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2770{
2771 struct stream_interface *si = appctx->owner;
2772 struct resolvers *resolvers;
2773 struct dns_nameserver *ns;
2774
2775 chunk_reset(&trash);
2776
2777 switch (appctx->st2) {
2778 case STAT_ST_INIT:
2779 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2780 /* fall through */
2781
2782 case STAT_ST_LIST:
2783 if (LIST_ISEMPTY(&sec_resolvers)) {
2784 chunk_appendf(&trash, "No resolvers found\n");
2785 }
2786 else {
2787 list_for_each_entry(resolvers, &sec_resolvers, list) {
2788 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2789 continue;
2790
2791 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2792 list_for_each_entry(ns, &resolvers->nameservers, list) {
2793 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2794 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2795 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2796 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2797 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2798 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2799 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2800 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2801 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2802 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2803 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2804 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2805 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2806 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2807 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2808 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
2809 }
2810 chunk_appendf(&trash, "\n");
2811 }
2812 }
2813
2814 /* display response */
2815 if (ci_putchk(si_ic(si), &trash) == -1) {
2816 /* let's try again later from this session. We add ourselves into
2817 * this session's users so that it can remove us upon termination.
2818 */
2819 si_rx_room_blk(si);
2820 return 0;
2821 }
2822 /* fall through */
2823
2824 default:
2825 appctx->st2 = STAT_ST_FIN;
2826 return 1;
2827 }
2828}
2829
2830/* register cli keywords */
2831static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002832 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002833 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2834 {{},}
2835 }
2836};
2837
2838INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2839
2840/*
2841 * Prepare <rule> for hostname resolution.
2842 * Returns -1 in case of any allocation failure, 0 if not.
2843 * On error, a global failure counter is also incremented.
2844 */
Willy Tarreaua13a6102021-10-14 08:11:48 +02002845static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002846{
2847 char *hostname_dn;
Willy Tarreaua13a6102021-10-14 08:11:48 +02002848 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002849 struct buffer *tmp = get_trash_chunk();
2850
2851 if (!hostname)
2852 return 0;
2853
Emeric Brunc9437992021-02-12 19:42:55 +01002854 hostname_dn = tmp->area;
Willy Tarreauc1c765f2021-10-14 07:49:49 +02002855 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002856 hostname_dn, tmp->size);
2857 if (hostname_dn_len == -1)
2858 goto err;
2859
2860
2861 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2862 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2863 if (!stream->resolv_ctx.hostname_dn)
2864 goto err;
2865
2866 return 0;
2867
2868 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002869 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002870 resolv_failed_resolutions += 1;
2871 return -1;
2872}
2873
2874
2875/*
2876 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2877 */
2878enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2879 struct session *sess, struct stream *s, int flags)
2880{
2881 struct resolv_resolution *resolution;
2882 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002883 struct resolv_requester *req;
2884 struct resolvers *resolvers;
2885 struct resolv_resolution *res;
2886 int exp, locked = 0;
2887 enum act_return ret = ACT_RET_CONT;
2888
2889 resolvers = rule->arg.resolv.resolvers;
2890
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002891 enter_resolver_code();
Willy Tarreau20751652021-10-18 16:46:38 +02002892
Emeric Brunc9437992021-02-12 19:42:55 +01002893 /* we have a response to our DNS resolution */
2894 use_cache:
2895 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2896 resolution = s->resolv_ctx.requester->resolution;
2897 if (!locked) {
2898 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2899 locked = 1;
2900 }
2901
2902 if (resolution->step == RSLV_STEP_RUNNING)
2903 goto yield;
2904 if (resolution->step == RSLV_STEP_NONE) {
2905 /* We update the variable only if we have a valid response. */
2906 if (resolution->status == RSLV_STATUS_VALID) {
2907 struct sample smp;
2908 short ip_sin_family = 0;
2909 void *ip = NULL;
2910
2911 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2912 0, &ip, &ip_sin_family, NULL);
2913
2914 switch (ip_sin_family) {
2915 case AF_INET:
2916 smp.data.type = SMP_T_IPV4;
2917 memcpy(&smp.data.u.ipv4, ip, 4);
2918 break;
2919 case AF_INET6:
2920 smp.data.type = SMP_T_IPV6;
2921 memcpy(&smp.data.u.ipv6, ip, 16);
2922 break;
2923 default:
2924 ip = NULL;
2925 }
2926
2927 if (ip) {
2928 smp.px = px;
2929 smp.sess = sess;
2930 smp.strm = s;
2931
2932 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2933 }
2934 }
2935 }
2936
2937 goto release_requester;
2938 }
2939
2940 /* need to configure and start a new DNS resolution */
2941 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2942 if (smp == NULL)
2943 goto end;
2944
Willy Tarreaua13a6102021-10-14 08:11:48 +02002945 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002946 goto end; /* on error, ignore the action */
2947
2948 s->resolv_ctx.parent = rule;
2949
2950 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2951 locked = 1;
2952
2953 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2954
2955 /* Check if there is a fresh enough response in the cache of our associated resolution */
2956 req = s->resolv_ctx.requester;
2957 if (!req || !req->resolution)
2958 goto release_requester; /* on error, ignore the action */
2959 res = req->resolution;
2960
2961 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2962 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2963 && !tick_is_expired(exp, now_ms)) {
2964 goto use_cache;
2965 }
2966
2967 resolv_trigger_resolution(s->resolv_ctx.requester);
2968
2969 yield:
2970 if (flags & ACT_OPT_FINAL)
2971 goto release_requester;
2972 ret = ACT_RET_YIELD;
2973
2974 end:
Christopher Faulet7a3a5362021-11-02 16:25:05 +01002975 leave_resolver_code();
Emeric Brunc9437992021-02-12 19:42:55 +01002976 if (locked)
2977 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2978 return ret;
2979
2980 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002981 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002982 s->resolv_ctx.hostname_dn_len = 0;
2983 if (s->resolv_ctx.requester) {
Willy Tarreau33360872021-10-20 14:07:31 +02002984 _resolv_unlink_resolution(s->resolv_ctx.requester);
Emeric Brunc9437992021-02-12 19:42:55 +01002985 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2986 s->resolv_ctx.requester = NULL;
2987 }
2988 goto end;
2989}
2990
2991static void release_resolv_action(struct act_rule *rule)
2992{
2993 release_sample_expr(rule->arg.resolv.expr);
2994 free(rule->arg.resolv.varname);
2995 free(rule->arg.resolv.resolvers_id);
2996 free(rule->arg.resolv.opts);
2997}
2998
2999
3000/* parse "do-resolve" action
3001 * This action takes the following arguments:
3002 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3003 *
3004 * - <varName> is the variable name where the result of the DNS resolution will be stored
3005 * (mandatory)
3006 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3007 * (mandatory)
3008 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3009 * (optional), defaults to ipv6
3010 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3011 */
3012enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3013{
3014 int cur_arg;
3015 struct sample_expr *expr;
3016 unsigned int where;
3017 const char *beg, *end;
3018
3019 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3020 cur_arg = *orig_arg - 1;
3021
3022 /* locate varName, which is mandatory */
3023 beg = strchr(args[cur_arg], '(');
3024 if (beg == NULL)
3025 goto do_resolve_parse_error;
3026 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3027 end = strchr(beg, ',');
3028 if (end == NULL)
3029 goto do_resolve_parse_error;
3030 rule->arg.resolv.varname = my_strndup(beg, end - beg);
3031 if (rule->arg.resolv.varname == NULL)
3032 goto do_resolve_parse_error;
3033
3034
3035 /* locate resolversSectionName, which is mandatory.
3036 * Since next parameters are optional, the delimiter may be comma ','
3037 * or closing parenthesis ')'
3038 */
3039 beg = end + 1;
3040 end = strchr(beg, ',');
3041 if (end == NULL)
3042 end = strchr(beg, ')');
3043 if (end == NULL)
3044 goto do_resolve_parse_error;
3045 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
3046 if (rule->arg.resolv.resolvers_id == NULL)
3047 goto do_resolve_parse_error;
3048
3049
3050 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
3051 if (rule->arg.resolv.opts == NULL)
3052 goto do_resolve_parse_error;
3053
3054 /* Default priority is ipv6 */
3055 rule->arg.resolv.opts->family_prio = AF_INET6;
3056
3057 /* optional arguments accepted for now:
3058 * ipv4 or ipv6
3059 */
3060 while (*end != ')') {
3061 beg = end + 1;
3062 end = strchr(beg, ',');
3063 if (end == NULL)
3064 end = strchr(beg, ')');
3065 if (end == NULL)
3066 goto do_resolve_parse_error;
3067
3068 if (strncmp(beg, "ipv4", end - beg) == 0) {
3069 rule->arg.resolv.opts->family_prio = AF_INET;
3070 }
3071 else if (strncmp(beg, "ipv6", end - beg) == 0) {
3072 rule->arg.resolv.opts->family_prio = AF_INET6;
3073 }
3074 else {
3075 goto do_resolve_parse_error;
3076 }
3077 }
3078
3079 cur_arg = cur_arg + 1;
3080
3081 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
3082 if (!expr)
3083 goto do_resolve_parse_error;
3084
3085
3086 where = 0;
3087 if (px->cap & PR_CAP_FE)
3088 where |= SMP_VAL_FE_HRQ_HDR;
3089 if (px->cap & PR_CAP_BE)
3090 where |= SMP_VAL_BE_HRQ_HDR;
3091
3092 if (!(expr->fetch->val & where)) {
3093 memprintf(err,
3094 "fetch method '%s' extracts information from '%s', none of which is available here",
3095 args[cur_arg-1], sample_src_names(expr->fetch->use));
3096 free(expr);
3097 return ACT_RET_PRS_ERR;
3098 }
3099 rule->arg.resolv.expr = expr;
3100 rule->action = ACT_CUSTOM;
3101 rule->action_ptr = resolv_action_do_resolve;
3102 *orig_arg = cur_arg;
3103
3104 rule->check_ptr = check_action_do_resolve;
3105 rule->release_ptr = release_resolv_action;
3106
3107 return ACT_RET_PRS_OK;
3108
3109 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003110 ha_free(&rule->arg.resolv.varname);
3111 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003112 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3113 args[cur_arg]);
3114 return ACT_RET_PRS_ERR;
3115}
3116
3117static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003118 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003119 { /* END */ }
3120}};
3121
3122INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3123
3124static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003125 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003126 { /* END */ }
3127}};
3128
3129INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3130
3131/* Check an "http-request do-resolve" action.
3132 *
3133 * The function returns 1 in success case, otherwise, it returns 0 and err is
3134 * filled.
3135 */
3136int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3137{
3138 struct resolvers *resolvers = NULL;
3139
3140 if (rule->arg.resolv.resolvers_id == NULL) {
3141 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3142 return 0;
3143 }
3144
3145 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3146 if (resolvers == NULL) {
3147 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3148 return 0;
3149 }
3150 rule->arg.resolv.resolvers = resolvers;
3151
3152 return 1;
3153}
3154
3155void resolvers_setup_proxy(struct proxy *px)
3156{
3157 px->last_change = now.tv_sec;
3158 px->cap = PR_CAP_FE | PR_CAP_BE;
3159 px->maxconn = 0;
3160 px->conn_retries = 1;
3161 px->timeout.server = TICK_ETERNITY;
3162 px->timeout.client = TICK_ETERNITY;
3163 px->timeout.connect = TICK_ETERNITY;
3164 px->accept = NULL;
3165 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
3166 px->bind_proc = 0; /* will be filled by users */
3167}
3168
3169/*
3170 * Parse a <resolvers> section.
3171 * Returns the error code, 0 if OK, or any combination of :
3172 * - ERR_ABORT: must abort ASAP
3173 * - ERR_FATAL: we can continue parsing but not start the service
3174 * - ERR_WARN: a warning has been emitted
3175 * - ERR_ALERT: an alert has been emitted
3176 * Only the two first ones can stop processing, the two others are just
3177 * indicators.
3178 */
3179int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3180{
3181 const char *err;
3182 int err_code = 0;
3183 char *errmsg = NULL;
3184 struct proxy *p;
3185
3186 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3187 if (!*args[1]) {
3188 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3189 err_code |= ERR_ALERT | ERR_ABORT;
3190 goto out;
3191 }
3192
3193 err = invalid_char(args[1]);
3194 if (err) {
3195 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3196 file, linenum, *err, args[0], args[1]);
3197 err_code |= ERR_ALERT | ERR_ABORT;
3198 goto out;
3199 }
3200
3201 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3202 /* Error if two resolvers owns the same name */
3203 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3204 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3205 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3206 err_code |= ERR_ALERT | ERR_ABORT;
3207 }
3208 }
3209
3210 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3211 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3212 err_code |= ERR_ALERT | ERR_ABORT;
3213 goto out;
3214 }
3215
3216 /* allocate new proxy to tcp servers */
3217 p = calloc(1, sizeof *p);
3218 if (!p) {
3219 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3220 err_code |= ERR_ALERT | ERR_FATAL;
3221 goto out;
3222 }
3223
3224 init_new_proxy(p);
3225 resolvers_setup_proxy(p);
3226 p->parent = curr_resolvers;
3227 p->id = strdup(args[1]);
3228 p->conf.args.file = p->conf.file = strdup(file);
3229 p->conf.args.line = p->conf.line = linenum;
3230 curr_resolvers->px = p;
3231
3232 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003233 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003234 curr_resolvers->conf.file = strdup(file);
3235 curr_resolvers->conf.line = linenum;
3236 curr_resolvers->id = strdup(args[1]);
3237 curr_resolvers->query_ids = EB_ROOT;
3238 /* default maximum response size */
3239 curr_resolvers->accepted_payload_size = 512;
3240 /* default hold period for nx, other, refuse and timeout is 30s */
3241 curr_resolvers->hold.nx = 30000;
3242 curr_resolvers->hold.other = 30000;
3243 curr_resolvers->hold.refused = 30000;
3244 curr_resolvers->hold.timeout = 30000;
3245 curr_resolvers->hold.obsolete = 0;
3246 /* default hold period for valid is 10s */
3247 curr_resolvers->hold.valid = 10000;
3248 curr_resolvers->timeout.resolve = 1000;
3249 curr_resolvers->timeout.retry = 1000;
3250 curr_resolvers->resolve_retries = 3;
3251 LIST_INIT(&curr_resolvers->nameservers);
3252 LIST_INIT(&curr_resolvers->resolutions.curr);
3253 LIST_INIT(&curr_resolvers->resolutions.wait);
3254 HA_SPIN_INIT(&curr_resolvers->lock);
3255 }
3256 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3257 struct dns_nameserver *newnameserver = NULL;
3258 struct sockaddr_storage *sk;
3259 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003260 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003261
3262 if (!*args[2]) {
3263 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3264 file, linenum, args[0]);
3265 err_code |= ERR_ALERT | ERR_FATAL;
3266 goto out;
3267 }
3268
3269 err = invalid_char(args[1]);
3270 if (err) {
3271 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3272 file, linenum, *err, args[1]);
3273 err_code |= ERR_ALERT | ERR_FATAL;
3274 goto out;
3275 }
3276
3277 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3278 /* Error if two resolvers owns the same name */
3279 if (strcmp(newnameserver->id, args[1]) == 0) {
3280 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3281 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3282 err_code |= ERR_ALERT | ERR_FATAL;
3283 }
3284 }
3285
Emeric Brunc8f3e452021-04-07 16:04:54 +02003286 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3287 &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 +01003288 if (!sk) {
3289 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3290 err_code |= ERR_ALERT | ERR_FATAL;
3291 goto out;
3292 }
3293
3294 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3295 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3296 err_code |= ERR_ALERT | ERR_ABORT;
3297 goto out;
3298 }
3299
Emeric Brunc8f3e452021-04-07 16:04:54 +02003300 if (proto && proto->ctrl_type == SOCK_STREAM) {
3301 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3302 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3303 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3304 err_code |= ERR_ABORT;
3305 goto out;
3306 }
3307
3308 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3309 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3310 err_code |= ERR_ALERT|ERR_ABORT;
3311 goto out;
3312 }
3313 }
3314 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003315 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3316 err_code |= ERR_ALERT | ERR_ABORT;
3317 goto out;
3318 }
3319
3320 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3321 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3322 err_code |= ERR_ALERT | ERR_ABORT;
3323 goto out;
3324 }
3325
3326 if ((newnameserver->id = strdup(args[1])) == NULL) {
3327 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3328 err_code |= ERR_ALERT | ERR_ABORT;
3329 goto out;
3330 }
3331
3332 newnameserver->parent = curr_resolvers;
3333 newnameserver->process_responses = resolv_process_responses;
3334 newnameserver->conf.line = linenum;
3335 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003336 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003337 }
3338 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3339 struct dns_nameserver *newnameserver = NULL;
3340 const char *whitespace = "\r\n\t ";
3341 char *resolv_line = NULL;
3342 int resolv_linenum = 0;
3343 FILE *f = NULL;
3344 char *address = NULL;
3345 struct sockaddr_storage *sk = NULL;
3346 struct protocol *proto;
3347 int duplicate_name = 0;
3348
3349 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3350 ha_alert("parsing [%s:%d] : out of memory.\n",
3351 file, linenum);
3352 err_code |= ERR_ALERT | ERR_FATAL;
3353 goto resolv_out;
3354 }
3355
3356 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3357 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3358 file, linenum);
3359 err_code |= ERR_ALERT | ERR_FATAL;
3360 goto resolv_out;
3361 }
3362
3363 sk = calloc(1, sizeof(*sk));
3364 if (sk == NULL) {
3365 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3366 resolv_linenum);
3367 err_code |= ERR_ALERT | ERR_FATAL;
3368 goto resolv_out;
3369 }
3370
3371 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3372 resolv_linenum++;
3373 if (strncmp(resolv_line, "nameserver", 10) != 0)
3374 continue;
3375
3376 address = strtok(resolv_line + 10, whitespace);
3377 if (address == resolv_line + 10)
3378 continue;
3379
3380 if (address == NULL) {
3381 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3382 resolv_linenum);
3383 err_code |= ERR_WARN;
3384 continue;
3385 }
3386
3387 duplicate_name = 0;
3388 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3389 if (strcmp(newnameserver->id, address) == 0) {
3390 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",
3391 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3392 err_code |= ERR_WARN;
3393 duplicate_name = 1;
3394 }
3395 }
3396
3397 if (duplicate_name)
3398 continue;
3399
3400 memset(sk, 0, sizeof(*sk));
3401 if (!str2ip2(address, sk, 1)) {
3402 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3403 resolv_linenum, address);
3404 err_code |= ERR_WARN;
3405 continue;
3406 }
3407
3408 set_host_port(sk, 53);
3409
3410 proto = protocol_by_family(sk->ss_family);
3411 if (!proto || !proto->connect) {
3412 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3413 resolv_linenum, address);
3414 err_code |= ERR_WARN;
3415 continue;
3416 }
3417
3418 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3419 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3420 err_code |= ERR_ALERT | ERR_FATAL;
3421 goto resolv_out;
3422 }
3423
3424 if (dns_dgram_init(newnameserver, sk) < 0) {
3425 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3426 err_code |= ERR_ALERT | ERR_FATAL;
3427 free(newnameserver);
3428 goto resolv_out;
3429 }
3430
3431 newnameserver->conf.file = strdup("/etc/resolv.conf");
3432 if (newnameserver->conf.file == NULL) {
3433 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3434 err_code |= ERR_ALERT | ERR_FATAL;
3435 free(newnameserver);
3436 goto resolv_out;
3437 }
3438
3439 newnameserver->id = strdup(address);
3440 if (newnameserver->id == NULL) {
3441 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3442 err_code |= ERR_ALERT | ERR_FATAL;
3443 free((char *)newnameserver->conf.file);
3444 free(newnameserver);
3445 goto resolv_out;
3446 }
3447
3448 newnameserver->parent = curr_resolvers;
3449 newnameserver->process_responses = resolv_process_responses;
3450 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003451 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003452 }
3453
3454resolv_out:
3455 free(sk);
3456 free(resolv_line);
3457 if (f != NULL)
3458 fclose(f);
3459 }
3460 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3461 const char *res;
3462 unsigned int time;
3463
3464 if (!*args[2]) {
3465 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3466 file, linenum, args[0]);
3467 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3468 err_code |= ERR_ALERT | ERR_FATAL;
3469 goto out;
3470 }
3471 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3472 if (res == PARSE_TIME_OVER) {
3473 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3474 file, linenum, args[1], args[0]);
3475 err_code |= ERR_ALERT | ERR_FATAL;
3476 goto out;
3477 }
3478 else if (res == PARSE_TIME_UNDER) {
3479 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3480 file, linenum, args[1], args[0]);
3481 err_code |= ERR_ALERT | ERR_FATAL;
3482 goto out;
3483 }
3484 else if (res) {
3485 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3486 file, linenum, *res, args[0]);
3487 err_code |= ERR_ALERT | ERR_FATAL;
3488 goto out;
3489 }
3490 if (strcmp(args[1], "nx") == 0)
3491 curr_resolvers->hold.nx = time;
3492 else if (strcmp(args[1], "other") == 0)
3493 curr_resolvers->hold.other = time;
3494 else if (strcmp(args[1], "refused") == 0)
3495 curr_resolvers->hold.refused = time;
3496 else if (strcmp(args[1], "timeout") == 0)
3497 curr_resolvers->hold.timeout = time;
3498 else if (strcmp(args[1], "valid") == 0)
3499 curr_resolvers->hold.valid = time;
3500 else if (strcmp(args[1], "obsolete") == 0)
3501 curr_resolvers->hold.obsolete = time;
3502 else {
3503 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3504 file, linenum, args[0], args[1]);
3505 err_code |= ERR_ALERT | ERR_FATAL;
3506 goto out;
3507 }
3508
3509 }
3510 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3511 int i = 0;
3512
3513 if (!*args[1]) {
3514 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3515 file, linenum, args[0]);
3516 err_code |= ERR_ALERT | ERR_FATAL;
3517 goto out;
3518 }
3519
3520 i = atoi(args[1]);
3521 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3522 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3523 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3524 err_code |= ERR_ALERT | ERR_FATAL;
3525 goto out;
3526 }
3527
3528 curr_resolvers->accepted_payload_size = i;
3529 }
3530 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3531 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3532 file, linenum, args[0]);
3533 err_code |= ERR_ALERT | ERR_FATAL;
3534 goto out;
3535 }
3536 else if (strcmp(args[0], "resolve_retries") == 0) {
3537 if (!*args[1]) {
3538 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3539 file, linenum, args[0]);
3540 err_code |= ERR_ALERT | ERR_FATAL;
3541 goto out;
3542 }
3543 curr_resolvers->resolve_retries = atoi(args[1]);
3544 }
3545 else if (strcmp(args[0], "timeout") == 0) {
3546 if (!*args[1]) {
3547 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3548 file, linenum, args[0]);
3549 err_code |= ERR_ALERT | ERR_FATAL;
3550 goto out;
3551 }
3552 else if (strcmp(args[1], "retry") == 0 ||
3553 strcmp(args[1], "resolve") == 0) {
3554 const char *res;
3555 unsigned int tout;
3556
3557 if (!*args[2]) {
3558 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3559 file, linenum, args[0], args[1]);
3560 err_code |= ERR_ALERT | ERR_FATAL;
3561 goto out;
3562 }
3563 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3564 if (res == PARSE_TIME_OVER) {
3565 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3566 file, linenum, args[2], args[0], args[1]);
3567 err_code |= ERR_ALERT | ERR_FATAL;
3568 goto out;
3569 }
3570 else if (res == PARSE_TIME_UNDER) {
3571 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3572 file, linenum, args[2], args[0], args[1]);
3573 err_code |= ERR_ALERT | ERR_FATAL;
3574 goto out;
3575 }
3576 else if (res) {
3577 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3578 file, linenum, *res, args[0], args[1]);
3579 err_code |= ERR_ALERT | ERR_FATAL;
3580 goto out;
3581 }
3582 if (args[1][2] == 't')
3583 curr_resolvers->timeout.retry = tout;
3584 else
3585 curr_resolvers->timeout.resolve = tout;
3586 }
3587 else {
3588 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3589 file, linenum, args[0], args[1]);
3590 err_code |= ERR_ALERT | ERR_FATAL;
3591 goto out;
3592 }
3593 }
3594 else if (*args[0] != 0) {
3595 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3596 err_code |= ERR_ALERT | ERR_FATAL;
3597 goto out;
3598 }
3599
3600 out:
3601 free(errmsg);
3602 return err_code;
3603}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003604int cfg_post_parse_resolvers()
3605{
3606 int err_code = 0;
3607 struct server *srv;
3608
3609 if (curr_resolvers) {
3610
3611 /* prepare forward server descriptors */
3612 if (curr_resolvers->px) {
3613 srv = curr_resolvers->px->srv;
3614 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003615 /* init ssl if needed */
3616 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3617 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3618 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3619 err_code |= ERR_ALERT | ERR_FATAL;
3620 break;
3621 }
3622 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003623 srv = srv->next;
3624 }
3625 }
3626 }
3627 curr_resolvers = NULL;
3628 return err_code;
3629}
Emeric Brunc9437992021-02-12 19:42:55 +01003630
Emeric Brun56fc5d92021-02-12 20:05:45 +01003631REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003632REGISTER_POST_DEINIT(resolvers_deinit);
3633REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);