blob: 88642403ca4be66f3cb95d01df48bd56a0a788ad [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
22#include <haproxy/action.h>
23#include <haproxy/api.h>
24#include <haproxy/cfgparse.h>
25#include <haproxy/channel.h>
26#include <haproxy/check.h>
27#include <haproxy/cli.h>
28#include <haproxy/dns.h>
29#include <haproxy/errors.h>
30#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010031#include <haproxy/http_rules.h>
32#include <haproxy/log.h>
33#include <haproxy/net_helper.h>
34#include <haproxy/protocol.h>
35#include <haproxy/proxy.h>
36#include <haproxy/resolvers.h>
37#include <haproxy/ring.h>
38#include <haproxy/sample.h>
39#include <haproxy/server.h>
40#include <haproxy/stats.h>
41#include <haproxy/stream_interface.h>
42#include <haproxy/task.h>
43#include <haproxy/tcp_rules.h>
44#include <haproxy/ticks.h>
45#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020046#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010047#include <haproxy/vars.h>
48
49
50struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
51struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
52
53static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
54struct resolvers *curr_resolvers = NULL;
55
56DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
57DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
58DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
59
60static unsigned int resolution_uuid = 1;
61unsigned int resolv_failed_resolutions = 0;
62
63enum {
64 DNS_STAT_ID,
65 DNS_STAT_PID,
66 DNS_STAT_SENT,
67 DNS_STAT_SND_ERROR,
68 DNS_STAT_VALID,
69 DNS_STAT_UPDATE,
70 DNS_STAT_CNAME,
71 DNS_STAT_CNAME_ERROR,
72 DNS_STAT_ANY_ERR,
73 DNS_STAT_NX,
74 DNS_STAT_TIMEOUT,
75 DNS_STAT_REFUSED,
76 DNS_STAT_OTHER,
77 DNS_STAT_INVALID,
78 DNS_STAT_TOO_BIG,
79 DNS_STAT_TRUNCATED,
80 DNS_STAT_OUTDATED,
81 DNS_STAT_END,
82};
83
84static struct name_desc dns_stats[] = {
85 [DNS_STAT_ID] = { .name = "id", .desc = "ID" },
86 [DNS_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
87 [DNS_STAT_SENT] = { .name = "sent", .desc = "Sent" },
88 [DNS_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
89 [DNS_STAT_VALID] = { .name = "valid", .desc = "Valid" },
90 [DNS_STAT_UPDATE] = { .name = "update", .desc = "Update" },
91 [DNS_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
92 [DNS_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
93 [DNS_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
94 [DNS_STAT_NX] = { .name = "nx", .desc = "NX" },
95 [DNS_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
96 [DNS_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
97 [DNS_STAT_OTHER] = { .name = "other", .desc = "Other" },
98 [DNS_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
99 [DNS_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
100 [DNS_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
101 [DNS_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
102};
103
104static struct dns_counters dns_counters;
105
106static void dns_fill_stats(void *d, struct field *stats)
107{
108 struct dns_counters *counters = d;
109 stats[DNS_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
110 stats[DNS_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
111 stats[DNS_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
112 stats[DNS_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
113 stats[DNS_STAT_VALID] = mkf_u64(FN_GAUGE, counters->valid);
114 stats[DNS_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->update);
115 stats[DNS_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->cname);
116 stats[DNS_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->cname_error);
117 stats[DNS_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->any_err);
118 stats[DNS_STAT_NX] = mkf_u64(FN_GAUGE, counters->nx);
119 stats[DNS_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->timeout);
120 stats[DNS_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->refused);
121 stats[DNS_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->other);
122 stats[DNS_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->invalid);
123 stats[DNS_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->too_big);
124 stats[DNS_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->truncated);
125 stats[DNS_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->outdated);
126}
127
128static struct stats_module dns_stats_module = {
129 .name = "dns",
130 .domain_flags = STATS_DOMAIN_DNS << STATS_DOMAIN,
131 .fill_stats = dns_fill_stats,
132 .stats = dns_stats,
133 .stats_count = DNS_STAT_END,
134 .counters = &dns_counters,
135 .counters_size = sizeof(dns_counters),
136 .clearable = 0,
137};
138
139INITCALL1(STG_REGISTER, stats_register_module, &dns_stats_module);
140
141/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
142 * no match is found.
143 */
144struct resolvers *find_resolvers_by_id(const char *id)
145{
146 struct resolvers *res;
147
148 list_for_each_entry(res, &sec_resolvers, list) {
149 if (strcmp(res->id, id) == 0)
150 return res;
151 }
152 return NULL;
153}
154
155/* Compare hostnames in a case-insensitive way .
156 * Returns 0 if they are the same, non-zero otherwise
157 */
158static __inline int resolv_hostname_cmp(const char *name1, const char *name2, int len)
159{
160 int i;
161
162 for (i = 0; i < len; i++)
163 if (tolower((unsigned char)name1[i]) != tolower((unsigned char)name2[i]))
164 return -1;
165 return 0;
166}
167
168/* Returns a pointer on the SRV request matching the name <name> for the proxy
169 * <px>. NULL is returned if no match is found.
170 */
171struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
172{
173 struct resolv_srvrq *srvrq;
174
175 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
176 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
177 return srvrq;
178 }
179 return NULL;
180}
181
182/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
183 * NULL if an error occurred. */
184struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
185{
186 struct proxy *px = srv->proxy;
187 struct resolv_srvrq *srvrq = NULL;
188 int fqdn_len, hostname_dn_len;
189
190 fqdn_len = strlen(fqdn);
191 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len + 1, trash.area,
192 trash.size);
193 if (hostname_dn_len == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200194 ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100195 proxy_type_str(px), px->id, srv->id, fqdn);
196 goto err;
197 }
198
199 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200200 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100201 proxy_type_str(px), px->id, srv->id);
202 goto err;
203 }
204 srvrq->obj_type = OBJ_TYPE_SRVRQ;
205 srvrq->proxy = px;
206 srvrq->name = strdup(fqdn);
207 srvrq->hostname_dn = strdup(trash.area);
208 srvrq->hostname_dn_len = hostname_dn_len;
209 if (!srvrq->name || !srvrq->hostname_dn) {
Amaury Denoyelle11124302021-06-04 18:22:08 +0200210 ha_alert("%s '%s', server '%s': out of memory\n",
Emeric Brunc9437992021-02-12 19:42:55 +0100211 proxy_type_str(px), px->id, srv->id);
212 goto err;
213 }
Willy Tarreau2b718102021-04-21 07:32:39 +0200214 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100215 return srvrq;
216
217 err:
218 if (srvrq) {
219 free(srvrq->name);
220 free(srvrq->hostname_dn);
221 free(srvrq);
222 }
223 return NULL;
224}
225
226
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100227/* finds and return the SRV answer item associated to a requester (whose type is 'server').
228 *
229 * returns NULL in case of error or not found.
230 */
231struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
232{
233 struct resolv_resolution *res;
234 struct resolv_answer_item *item;
235 struct server *srv;
236
237 if (!requester)
238 return NULL;
239
240 if ((srv = objt_server(requester->owner)) == NULL)
241 return NULL;
242 /* check if the server is managed by a SRV record */
243 if (srv->srvrq == NULL)
244 return NULL;
245
246 res = srv->srvrq->requester->resolution;
247 /* search an ANSWER record whose target points to the server's hostname and whose port is
248 * the same as server's svc_port */
249 list_for_each_entry(item, &res->response.answer_list, list) {
250 if (resolv_hostname_cmp(srv->hostname_dn, item->target, srv->hostname_dn_len) == 0 &&
251 (srv->svc_port == item->port))
252 return item;
253 }
254
255 return NULL;
256}
257
Emeric Brunc9437992021-02-12 19:42:55 +0100258/* 2 bytes random generator to generate DNS query ID */
259static inline uint16_t resolv_rnd16(void)
260{
261 if (!resolv_query_id_seed)
262 resolv_query_id_seed = now_ms;
263 resolv_query_id_seed ^= resolv_query_id_seed << 13;
264 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
265 resolv_query_id_seed ^= resolv_query_id_seed << 17;
266 return resolv_query_id_seed;
267}
268
269
270static inline int resolv_resolution_timeout(struct resolv_resolution *res)
271{
272 return res->resolvers->timeout.resolve;
273}
274
275/* Updates a resolvers' task timeout for next wake up and queue it */
276static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
277{
278 struct resolv_resolution *res;
279 int next;
280
281 next = tick_add(now_ms, resolvers->timeout.resolve);
282 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
283 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
284 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
285 }
286
287 list_for_each_entry(res, &resolvers->resolutions.wait, list)
288 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
289
290 resolvers->t->expire = next;
291 task_queue(resolvers->t);
292}
293
294/* Forges a DNS query. It needs the following information from the caller:
295 * - <query_id> : the DNS query id corresponding to this query
296 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
297 * - <hostname_dn> : hostname in domain name format
298 * - <hostname_dn_len> : length of <hostname_dn>
299 *
300 * To store the query, the caller must pass a buffer <buf> and its size
301 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
302 * too short.
303 */
304static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
305 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
306{
307 struct dns_header dns_hdr;
308 struct dns_question qinfo;
309 struct dns_additional_record edns;
310 char *p = buf;
311
312 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
313 return -1;
314
315 memset(buf, 0, bufsize);
316
317 /* Set dns query headers */
318 dns_hdr.id = (unsigned short) htons(query_id);
319 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
320 dns_hdr.qdcount = htons(1); /* 1 question */
321 dns_hdr.ancount = 0;
322 dns_hdr.nscount = 0;
323 dns_hdr.arcount = htons(1);
324 memcpy(p, &dns_hdr, sizeof(dns_hdr));
325 p += sizeof(dns_hdr);
326
327 /* Set up query hostname */
328 memcpy(p, hostname_dn, hostname_dn_len);
329 p += hostname_dn_len;
330 *p++ = 0;
331
332 /* Set up query info (type and class) */
333 qinfo.qtype = htons(query_type);
334 qinfo.qclass = htons(DNS_RCLASS_IN);
335 memcpy(p, &qinfo, sizeof(qinfo));
336 p += sizeof(qinfo);
337
338 /* Set the DNS extension */
339 edns.name = 0;
340 edns.type = htons(DNS_RTYPE_OPT);
341 edns.udp_payload_size = htons(accepted_payload_size);
342 edns.extension = 0;
343 edns.data_length = 0;
344 memcpy(p, &edns, sizeof(edns));
345 p += sizeof(edns);
346
347 return (p - buf);
348}
349
350/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
351 * success, -1 otherwise.
352 */
353static int resolv_send_query(struct resolv_resolution *resolution)
354{
355 struct resolvers *resolvers = resolution->resolvers;
356 struct dns_nameserver *ns;
357 int len;
358
359 /* Update resolution */
360 resolution->nb_queries = 0;
361 resolution->nb_responses = 0;
362 resolution->last_query = now_ms;
363
364 len = resolv_build_query(resolution->query_id, resolution->query_type,
365 resolvers->accepted_payload_size,
366 resolution->hostname_dn, resolution->hostname_dn_len,
367 trash.area, trash.size);
368
369 list_for_each_entry(ns, &resolvers->nameservers, list) {
370 if (len < 0) {
371 ns->counters->snd_error++;
372 continue;
373 }
374
375 if (dns_send_nameserver(ns, trash.area, len) < 0)
376 ns->counters->snd_error++;
377 else
378 resolution->nb_queries++;
379 }
380
381 /* Push the resolution at the end of the active list */
Willy Tarreau2b718102021-04-21 07:32:39 +0200382 LIST_DELETE(&resolution->list);
383 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100384 return 0;
385}
386
387/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
388 * skipped and -1 if an error occurred.
389 */
390static int
391resolv_run_resolution(struct resolv_resolution *resolution)
392{
393 struct resolvers *resolvers = resolution->resolvers;
394 int query_id, i;
395
396 /* Avoid sending requests for resolutions that don't yet have an
397 * hostname, ie resolutions linked to servers that do not yet have an
398 * fqdn */
399 if (!resolution->hostname_dn)
400 return 0;
401
402 /* Check if a resolution has already been started for this server return
403 * directly to avoid resolution pill up. */
404 if (resolution->step != RSLV_STEP_NONE)
405 return 0;
406
407 /* Generates a new query id. We try at most 100 times to find a free
408 * query id */
409 for (i = 0; i < 100; ++i) {
410 query_id = resolv_rnd16();
411 if (!eb32_lookup(&resolvers->query_ids, query_id))
412 break;
413 query_id = -1;
414 }
415 if (query_id == -1) {
416 send_log(NULL, LOG_NOTICE,
417 "could not generate a query id for %s, in resolvers %s.\n",
418 resolution->hostname_dn, resolvers->id);
419 return -1;
420 }
421
422 /* Update resolution parameters */
423 resolution->query_id = query_id;
424 resolution->qid.key = query_id;
425 resolution->step = RSLV_STEP_RUNNING;
426 resolution->query_type = resolution->prefered_query_type;
427 resolution->try = resolvers->resolve_retries;
428 eb32_insert(&resolvers->query_ids, &resolution->qid);
429
430 /* Send the DNS query */
431 resolution->try -= 1;
432 resolv_send_query(resolution);
433 return 1;
434}
435
436/* Performs a name resolution for the requester <req> */
437void resolv_trigger_resolution(struct resolv_requester *req)
438{
439 struct resolvers *resolvers;
440 struct resolv_resolution *res;
441 int exp;
442
443 if (!req || !req->resolution)
444 return;
445 res = req->resolution;
446 resolvers = res->resolvers;
447
448 /* The resolution must not be triggered yet. Use the cached response, if
449 * valid */
450 exp = tick_add(res->last_resolution, resolvers->hold.valid);
451 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
452 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
453 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
454}
455
456
457/* Resets some resolution parameters to initial values and also delete the query
458 * ID from the resolver's tree.
459 */
460static void resolv_reset_resolution(struct resolv_resolution *resolution)
461{
462 /* update resolution status */
463 resolution->step = RSLV_STEP_NONE;
464 resolution->try = 0;
465 resolution->last_resolution = now_ms;
466 resolution->nb_queries = 0;
467 resolution->nb_responses = 0;
468 resolution->query_type = resolution->prefered_query_type;
469
470 /* clean up query id */
471 eb32_delete(&resolution->qid);
472 resolution->query_id = 0;
473 resolution->qid.key = 0;
474}
475
476/* Returns the query id contained in a DNS response */
477static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
478{
479 return resp[0] * 256 + resp[1];
480}
481
482
483/* Analyses, re-builds and copies the name <name> from the DNS response packet
484 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
485 * for compressed data. The result is copied into <dest>, ensuring we don't
486 * overflow using <dest_len> Returns the number of bytes the caller can move
487 * forward. If 0 it means an error occurred while parsing the name. <offset> is
488 * the number of bytes the caller could move forward.
489 */
490int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
491 unsigned char *name, char *destination, int dest_len,
492 int *offset, unsigned int depth)
493{
494 int nb_bytes = 0, n = 0;
495 int label_len;
496 unsigned char *reader = name;
497 char *dest = destination;
498
499 while (1) {
500 if (reader >= bufend)
501 goto err;
502
503 /* Name compression is in use */
504 if ((*reader & 0xc0) == 0xc0) {
505 if (reader + 1 >= bufend)
506 goto err;
507
508 /* Must point BEFORE current position */
509 if ((buffer + reader[1]) > reader)
510 goto err;
511
512 if (depth++ > 100)
513 goto err;
514
515 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
516 dest, dest_len - nb_bytes, offset, depth);
517 if (n == 0)
518 goto err;
519
520 dest += n;
521 nb_bytes += n;
522 goto out;
523 }
524
525 label_len = *reader;
526 if (label_len == 0)
527 goto out;
528
529 /* Check if:
530 * - we won't read outside the buffer
531 * - there is enough place in the destination
532 */
533 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
534 goto err;
535
536 /* +1 to take label len + label string */
537 label_len++;
538
539 memcpy(dest, reader, label_len);
540
541 dest += label_len;
542 nb_bytes += label_len;
543 reader += label_len;
544 }
545
546 out:
547 /* offset computation:
548 * parse from <name> until finding either NULL or a pointer "c0xx"
549 */
550 reader = name;
551 *offset = 0;
552 while (reader < bufend) {
553 if ((reader[0] & 0xc0) == 0xc0) {
554 *offset += 2;
555 break;
556 }
557 else if (*reader == 0) {
558 *offset += 1;
559 break;
560 }
561 *offset += 1;
562 ++reader;
563 }
564 return nb_bytes;
565
566 err:
567 return 0;
568}
569
570/* Checks for any obsolete record, also identify any SRV request, and try to
571 * find a corresponding server.
572*/
573static void resolv_check_response(struct resolv_resolution *res)
574{
575 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100576 struct resolv_requester *req;
Emeric Brunc9437992021-02-12 19:42:55 +0100577 struct resolv_answer_item *item, *itemback;
Emeric Brunbd78c912021-06-11 10:08:05 +0200578 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100579 struct resolv_srvrq *srvrq;
580
581 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
582 struct resolv_answer_item *ar_item = item->ar_item;
583
584 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100585 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100586 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
587 * item is also obsolete.
588 */
Emeric Brunc9437992021-02-12 19:42:55 +0100589 pool_free(resolv_answer_item_pool, ar_item);
590 item->ar_item = NULL;
591 }
592
593 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100594 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunbd78c912021-06-11 10:08:05 +0200595 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100596 /* Remove any associated server */
Emeric Brunbd78c912021-06-11 10:08:05 +0200597 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
598 LIST_DEL_INIT(&srv->ip_rec_item);
599 }
600 }
601 else if (item->type == DNS_RTYPE_SRV) {
602 list_for_each_entry(req, &res->requesters, list) {
603 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
604 continue;
605
606 /* Remove any associated server */
607 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
608 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
609 if (srv->srvrq == srvrq && srv->svc_port == item->port &&
610 item->data_len == srv->hostname_dn_len &&
611 !resolv_hostname_cmp(srv->hostname_dn, item->target, item->data_len)) {
612 resolv_unlink_resolution(srv->resolv_requester, 0);
613 srvrq_update_srv_status(srv, 1);
614 ha_free(&srv->hostname);
615 ha_free(&srv->hostname_dn);
616 srv->hostname_dn_len = 0;
617 memset(&srv->addr, 0, sizeof(srv->addr));
618 srv->svc_port = 0;
619 }
620 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Emeric Brunc9437992021-02-12 19:42:55 +0100621 }
Emeric Brunc9437992021-02-12 19:42:55 +0100622 }
623 }
624
Willy Tarreau2b718102021-04-21 07:32:39 +0200625 LIST_DELETE(&item->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100626 if (item->ar_item) {
627 pool_free(resolv_answer_item_pool, item->ar_item);
628 item->ar_item = NULL;
629 }
630 pool_free(resolv_answer_item_pool, item);
631 continue;
632 }
633
634 if (item->type != DNS_RTYPE_SRV)
635 continue;
636
637 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100638 list_for_each_entry(req, &res->requesters, list) {
Emeric Brunc9437992021-02-12 19:42:55 +0100639 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
640 continue;
641
642 /* Check if a server already uses that hostname */
643 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
644 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
645 if (srv->srvrq == srvrq && srv->svc_port == item->port &&
646 item->data_len == srv->hostname_dn_len &&
647 !resolv_hostname_cmp(srv->hostname_dn, item->target, item->data_len)) {
648 break;
649 }
650 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
651 }
652
653 /* If not, try to find a server with undefined hostname */
654 if (!srv) {
655 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
656 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
657 if (srv->srvrq == srvrq && !srv->hostname_dn)
658 break;
659 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
660 }
661 }
662
663 /* And update this server, if found (srv is locked here) */
664 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100665 /* re-enable DNS resolution for this server by default */
666 srv->flags &= ~SRV_F_NO_RESOLUTION;
667
Emeric Brunc9437992021-02-12 19:42:55 +0100668 /* Check if an Additional Record is associated to this SRV record.
669 * Perform some sanity checks too to ensure the record can be used.
670 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100671 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100672 */
673 if ((item->ar_item != NULL) &&
674 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100675 {
Emeric Brunc9437992021-02-12 19:42:55 +0100676
677 switch (item->ar_item->type) {
678 case DNS_RTYPE_A:
Christopher Faulet69beaa92021-02-16 12:07:47 +0100679 srv_update_addr(srv, &(((struct sockaddr_in*)&item->ar_item->address)->sin_addr), AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100680 break;
681 case DNS_RTYPE_AAAA:
Christopher Faulet69beaa92021-02-16 12:07:47 +0100682 srv_update_addr(srv, &(((struct sockaddr_in6*)&item->ar_item->address)->sin6_addr), AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100683 break;
684 }
685
686 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100687
688 /* Unlink A/AAAA resolution for this server if there is an AR item.
689 * It is usless to perform an extra resolution
690 */
Christopher Faulet0efc0992021-03-11 18:09:53 +0100691 resolv_unlink_resolution(srv->resolv_requester, 0);
Emeric Brunc9437992021-02-12 19:42:55 +0100692 }
693
694 if (!srv->hostname_dn) {
695 const char *msg = NULL;
696 char hostname[DNS_MAX_NAME_SIZE];
697
698 if (resolv_dn_label_to_str(item->target, item->data_len+1,
699 hostname, DNS_MAX_NAME_SIZE) == -1) {
700 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
701 continue;
702 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100703 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100704 if (msg)
705 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
706 }
707
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100708 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
709 /* If there is no AR item responsible of the FQDN resolution,
710 * trigger a dedicated DNS resolution
711 */
712 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
713 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
714 }
715
Christopher Fauletab177ac2021-03-10 15:34:52 +0100716 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100717 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100718
719 srv->svc_port = item->port;
720 srv->flags &= ~SRV_F_MAPPORTS;
721
722 if (!srv->resolv_opts.ignore_weight) {
723 char weight[9];
724 int ha_weight;
725
726 /* DNS weight range if from 0 to 65535
727 * HAProxy weight is from 0 to 256
728 * The rule below ensures that weight 0 is well respected
729 * while allowing a "mapping" from DNS weight into HAProxy's one.
730 */
731 ha_weight = (item->weight + 255) / 256;
732
733 snprintf(weight, sizeof(weight), "%d", ha_weight);
734 server_parse_weight_change_request(srv, weight);
735 }
736 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
737 }
738 }
739 }
740}
741
742/* Validates that the buffer DNS response provided in <resp> and finishing
743 * before <bufend> is valid from a DNS protocol point of view.
744 *
745 * The result is stored in <resolution>' response, buf_response,
746 * response_query_records and response_answer_records members.
747 *
748 * This function returns one of the RSLV_RESP_* code to indicate the type of
749 * error found.
750 */
751static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
752 struct resolv_resolution *resolution, int max_answer_records)
753{
754 unsigned char *reader;
755 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
756 int len, flags, offset;
757 int query_record_id;
758 int nb_saved_records;
759 struct resolv_query_item *query;
760 struct resolv_answer_item *answer_record, *tmp_record;
761 struct resolv_response *r_res;
762 int i, found = 0;
763 int cause = RSLV_RESP_ERROR;
764
765 reader = resp;
766 len = 0;
767 previous_dname = NULL;
768 query = NULL;
769 answer_record = NULL;
770
771 /* Initialization of response buffer and structure */
772 r_res = &resolution->response;
773
774 /* query id */
775 if (reader + 2 >= bufend)
776 goto invalid_resp;
777
778 r_res->header.id = reader[0] * 256 + reader[1];
779 reader += 2;
780
781 /* Flags and rcode are stored over 2 bytes
782 * First byte contains:
783 * - response flag (1 bit)
784 * - opcode (4 bits)
785 * - authoritative (1 bit)
786 * - truncated (1 bit)
787 * - recursion desired (1 bit)
788 */
789 if (reader + 2 >= bufend)
790 goto invalid_resp;
791
792 flags = reader[0] * 256 + reader[1];
793
794 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
795 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
796 cause = RSLV_RESP_NX_DOMAIN;
797 goto return_error;
798 }
799 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
800 cause = RSLV_RESP_REFUSED;
801 goto return_error;
802 }
803 else {
804 cause = RSLV_RESP_ERROR;
805 goto return_error;
806 }
807 }
808
809 /* Move forward 2 bytes for flags */
810 reader += 2;
811
812 /* 2 bytes for question count */
813 if (reader + 2 >= bufend)
814 goto invalid_resp;
815 r_res->header.qdcount = reader[0] * 256 + reader[1];
816 /* (for now) we send one query only, so we expect only one in the
817 * response too */
818 if (r_res->header.qdcount != 1) {
819 cause = RSLV_RESP_QUERY_COUNT_ERROR;
820 goto return_error;
821 }
822
823 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
824 goto invalid_resp;
825 reader += 2;
826
827 /* 2 bytes for answer count */
828 if (reader + 2 >= bufend)
829 goto invalid_resp;
830 r_res->header.ancount = reader[0] * 256 + reader[1];
831 if (r_res->header.ancount == 0) {
832 cause = RSLV_RESP_ANCOUNT_ZERO;
833 goto return_error;
834 }
835
836 /* Check if too many records are announced */
837 if (r_res->header.ancount > max_answer_records)
838 goto invalid_resp;
839 reader += 2;
840
841 /* 2 bytes authority count */
842 if (reader + 2 >= bufend)
843 goto invalid_resp;
844 r_res->header.nscount = reader[0] * 256 + reader[1];
845 reader += 2;
846
847 /* 2 bytes additional count */
848 if (reader + 2 >= bufend)
849 goto invalid_resp;
850 r_res->header.arcount = reader[0] * 256 + reader[1];
851 reader += 2;
852
853 /* Parsing dns queries */
854 LIST_INIT(&r_res->query_list);
855 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
856 /* Use next pre-allocated resolv_query_item after ensuring there is
857 * still one available.
858 * It's then added to our packet query list. */
859 if (query_record_id > DNS_MAX_QUERY_RECORDS)
860 goto invalid_resp;
861 query = &resolution->response_query_records[query_record_id];
Willy Tarreau2b718102021-04-21 07:32:39 +0200862 LIST_APPEND(&r_res->query_list, &query->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100863
864 /* Name is a NULL terminated string in our case, since we have
865 * one query per response and the first one can't be compressed
866 * (using the 0x0c format) */
867 offset = 0;
868 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
869
870 if (len == 0)
871 goto invalid_resp;
872
873 reader += offset;
874 previous_dname = query->name;
875
876 /* move forward 2 bytes for question type */
877 if (reader + 2 >= bufend)
878 goto invalid_resp;
879 query->type = reader[0] * 256 + reader[1];
880 reader += 2;
881
882 /* move forward 2 bytes for question class */
883 if (reader + 2 >= bufend)
884 goto invalid_resp;
885 query->class = reader[0] * 256 + reader[1];
886 reader += 2;
887 }
888
889 /* TRUNCATED flag must be checked after we could read the query type
890 * because a TRUNCATED SRV query type response can still be exploited */
891 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
892 cause = RSLV_RESP_TRUNCATED;
893 goto return_error;
894 }
895
896 /* now parsing response records */
897 nb_saved_records = 0;
898 for (i = 0; i < r_res->header.ancount; i++) {
899 if (reader >= bufend)
900 goto invalid_resp;
901
902 answer_record = pool_alloc(resolv_answer_item_pool);
903 if (answer_record == NULL)
904 goto invalid_resp;
905
906 /* initialization */
907 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +0100908 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +0200909 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +0100910
911 offset = 0;
912 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
913
914 if (len == 0)
915 goto invalid_resp;
916
917 /* Check if the current record dname is valid. previous_dname
918 * points either to queried dname or last CNAME target */
919 if (query->type != DNS_RTYPE_SRV && resolv_hostname_cmp(previous_dname, tmpname, len) != 0) {
920 if (i == 0) {
921 /* First record, means a mismatch issue between
922 * queried dname and dname found in the first
923 * record */
924 goto invalid_resp;
925 }
926 else {
927 /* If not the first record, this means we have a
928 * CNAME resolution error.
929 */
930 cause = RSLV_RESP_CNAME_ERROR;
931 goto return_error;
932 }
933
934 }
935
936 memcpy(answer_record->name, tmpname, len);
937 answer_record->name[len] = 0;
938
939 reader += offset;
940 if (reader >= bufend)
941 goto invalid_resp;
942
943 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
944 if (reader + 2 > bufend)
945 goto invalid_resp;
946
947 answer_record->type = reader[0] * 256 + reader[1];
948 reader += 2;
949
950 /* 2 bytes for class (2) */
951 if (reader + 2 > bufend)
952 goto invalid_resp;
953
954 answer_record->class = reader[0] * 256 + reader[1];
955 reader += 2;
956
957 /* 4 bytes for ttl (4) */
958 if (reader + 4 > bufend)
959 goto invalid_resp;
960
961 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
962 + reader[2] * 256 + reader[3];
963 reader += 4;
964
965 /* Now reading data len */
966 if (reader + 2 > bufend)
967 goto invalid_resp;
968
969 answer_record->data_len = reader[0] * 256 + reader[1];
970
971 /* Move forward 2 bytes for data len */
972 reader += 2;
973
974 if (reader + answer_record->data_len > bufend)
975 goto invalid_resp;
976
977 /* Analyzing record content */
978 switch (answer_record->type) {
979 case DNS_RTYPE_A:
980 /* ipv4 is stored on 4 bytes */
981 if (answer_record->data_len != 4)
982 goto invalid_resp;
983
984 answer_record->address.sa_family = AF_INET;
985 memcpy(&(((struct sockaddr_in *)&answer_record->address)->sin_addr),
986 reader, answer_record->data_len);
987 break;
988
989 case DNS_RTYPE_CNAME:
990 /* Check if this is the last record and update the caller about the status:
991 * no IP could be found and last record was a CNAME. Could be triggered
992 * by a wrong query type
993 *
994 * + 1 because answer_record_id starts at 0
995 * while number of answers is an integer and
996 * starts at 1.
997 */
998 if (i + 1 == r_res->header.ancount) {
999 cause = RSLV_RESP_CNAME_ERROR;
1000 goto return_error;
1001 }
1002
1003 offset = 0;
1004 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1005 if (len == 0)
1006 goto invalid_resp;
1007
1008 memcpy(answer_record->target, tmpname, len);
1009 answer_record->target[len] = 0;
1010 previous_dname = answer_record->target;
1011 break;
1012
1013
1014 case DNS_RTYPE_SRV:
1015 /* Answer must contain :
1016 * - 2 bytes for the priority
1017 * - 2 bytes for the weight
1018 * - 2 bytes for the port
1019 * - the target hostname
1020 */
1021 if (answer_record->data_len <= 6)
1022 goto invalid_resp;
1023
1024 answer_record->priority = read_n16(reader);
1025 reader += sizeof(uint16_t);
1026 answer_record->weight = read_n16(reader);
1027 reader += sizeof(uint16_t);
1028 answer_record->port = read_n16(reader);
1029 reader += sizeof(uint16_t);
1030 offset = 0;
1031 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1032 if (len == 0)
1033 goto invalid_resp;
1034
1035 answer_record->data_len = len;
1036 memcpy(answer_record->target, tmpname, len);
1037 answer_record->target[len] = 0;
1038 if (answer_record->ar_item != NULL) {
1039 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1040 answer_record->ar_item = NULL;
1041 }
1042 break;
1043
1044 case DNS_RTYPE_AAAA:
1045 /* ipv6 is stored on 16 bytes */
1046 if (answer_record->data_len != 16)
1047 goto invalid_resp;
1048
1049 answer_record->address.sa_family = AF_INET6;
1050 memcpy(&(((struct sockaddr_in6 *)&answer_record->address)->sin6_addr),
1051 reader, answer_record->data_len);
1052 break;
1053
1054 } /* switch (record type) */
1055
1056 /* Increment the counter for number of records saved into our
1057 * local response */
1058 nb_saved_records++;
1059
1060 /* Move forward answer_record->data_len for analyzing next
1061 * record in the response */
1062 reader += ((answer_record->type == DNS_RTYPE_SRV)
1063 ? offset
1064 : answer_record->data_len);
1065
1066 /* Lookup to see if we already had this entry */
1067 found = 0;
1068 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1069 if (tmp_record->type != answer_record->type)
1070 continue;
1071
1072 switch(tmp_record->type) {
1073 case DNS_RTYPE_A:
1074 if (!memcmp(&((struct sockaddr_in *)&answer_record->address)->sin_addr,
1075 &((struct sockaddr_in *)&tmp_record->address)->sin_addr,
1076 sizeof(in_addr_t)))
1077 found = 1;
1078 break;
1079
1080 case DNS_RTYPE_AAAA:
1081 if (!memcmp(&((struct sockaddr_in6 *)&answer_record->address)->sin6_addr,
1082 &((struct sockaddr_in6 *)&tmp_record->address)->sin6_addr,
1083 sizeof(struct in6_addr)))
1084 found = 1;
1085 break;
1086
1087 case DNS_RTYPE_SRV:
1088 if (answer_record->data_len == tmp_record->data_len &&
1089 !resolv_hostname_cmp(answer_record->target, tmp_record->target, answer_record->data_len) &&
1090 answer_record->port == tmp_record->port) {
1091 tmp_record->weight = answer_record->weight;
1092 found = 1;
1093 }
1094 break;
1095
1096 default:
1097 break;
1098 }
1099
1100 if (found == 1)
1101 break;
1102 }
1103
1104 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001105 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001106 pool_free(resolv_answer_item_pool, answer_record);
1107 answer_record = NULL;
1108 }
1109 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001110 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001111 answer_record->ar_item = NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +02001112 LIST_APPEND(&r_res->answer_list, &answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001113 answer_record = NULL;
1114 }
1115 } /* for i 0 to ancount */
1116
1117 /* Save the number of records we really own */
1118 r_res->header.ancount = nb_saved_records;
1119
1120 /* now parsing additional records for SRV queries only */
1121 if (query->type != DNS_RTYPE_SRV)
1122 goto skip_parsing_additional_records;
1123
1124 /* if we find Authority records, just skip them */
1125 for (i = 0; i < r_res->header.nscount; i++) {
1126 offset = 0;
1127 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1128 &offset, 0);
1129 if (len == 0)
1130 continue;
1131
1132 if (reader + offset + 10 >= bufend)
1133 goto invalid_resp;
1134
1135 reader += offset;
1136 /* skip 2 bytes for class */
1137 reader += 2;
1138 /* skip 2 bytes for type */
1139 reader += 2;
1140 /* skip 4 bytes for ttl */
1141 reader += 4;
1142 /* read data len */
1143 len = reader[0] * 256 + reader[1];
1144 reader += 2;
1145
1146 if (reader + len >= bufend)
1147 goto invalid_resp;
1148
1149 reader += len;
1150 }
1151
1152 nb_saved_records = 0;
1153 for (i = 0; i < r_res->header.arcount; i++) {
1154 if (reader >= bufend)
1155 goto invalid_resp;
1156
1157 answer_record = pool_alloc(resolv_answer_item_pool);
1158 if (answer_record == NULL)
1159 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001160 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunbd78c912021-06-11 10:08:05 +02001161 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001162
1163 offset = 0;
1164 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1165
1166 if (len == 0) {
1167 pool_free(resolv_answer_item_pool, answer_record);
1168 answer_record = NULL;
1169 continue;
1170 }
1171
1172 memcpy(answer_record->name, tmpname, len);
1173 answer_record->name[len] = 0;
1174
1175 reader += offset;
1176 if (reader >= bufend)
1177 goto invalid_resp;
1178
1179 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1180 if (reader + 2 > bufend)
1181 goto invalid_resp;
1182
1183 answer_record->type = reader[0] * 256 + reader[1];
1184 reader += 2;
1185
1186 /* 2 bytes for class (2) */
1187 if (reader + 2 > bufend)
1188 goto invalid_resp;
1189
1190 answer_record->class = reader[0] * 256 + reader[1];
1191 reader += 2;
1192
1193 /* 4 bytes for ttl (4) */
1194 if (reader + 4 > bufend)
1195 goto invalid_resp;
1196
1197 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1198 + reader[2] * 256 + reader[3];
1199 reader += 4;
1200
1201 /* Now reading data len */
1202 if (reader + 2 > bufend)
1203 goto invalid_resp;
1204
1205 answer_record->data_len = reader[0] * 256 + reader[1];
1206
1207 /* Move forward 2 bytes for data len */
1208 reader += 2;
1209
1210 if (reader + answer_record->data_len > bufend)
1211 goto invalid_resp;
1212
1213 /* Analyzing record content */
1214 switch (answer_record->type) {
1215 case DNS_RTYPE_A:
1216 /* ipv4 is stored on 4 bytes */
1217 if (answer_record->data_len != 4)
1218 goto invalid_resp;
1219
1220 answer_record->address.sa_family = AF_INET;
1221 memcpy(&(((struct sockaddr_in *)&answer_record->address)->sin_addr),
1222 reader, answer_record->data_len);
1223 break;
1224
1225 case DNS_RTYPE_AAAA:
1226 /* ipv6 is stored on 16 bytes */
1227 if (answer_record->data_len != 16)
1228 goto invalid_resp;
1229
1230 answer_record->address.sa_family = AF_INET6;
1231 memcpy(&(((struct sockaddr_in6 *)&answer_record->address)->sin6_addr),
1232 reader, answer_record->data_len);
1233 break;
1234
1235 default:
1236 pool_free(resolv_answer_item_pool, answer_record);
1237 answer_record = NULL;
1238 continue;
1239
1240 } /* switch (record type) */
1241
1242 /* Increment the counter for number of records saved into our
1243 * local response */
1244 nb_saved_records++;
1245
1246 /* Move forward answer_record->data_len for analyzing next
1247 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001248 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001249
1250 /* Lookup to see if we already had this entry */
1251 found = 0;
1252 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001253 struct resolv_answer_item *ar_item;
1254
1255 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1256 continue;
1257
1258 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001259 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001260 len != tmp_record->data_len ||
1261 resolv_hostname_cmp(answer_record->name, tmp_record->target, tmp_record->data_len))
Emeric Brunc9437992021-02-12 19:42:55 +01001262 continue;
1263
Christopher Faulet77f86062021-03-10 15:19:57 +01001264 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001265 case DNS_RTYPE_A:
1266 if (!memcmp(&((struct sockaddr_in *)&answer_record->address)->sin_addr,
Christopher Faulet77f86062021-03-10 15:19:57 +01001267 &((struct sockaddr_in *)&ar_item->address)->sin_addr,
Emeric Brunc9437992021-02-12 19:42:55 +01001268 sizeof(in_addr_t)))
1269 found = 1;
1270 break;
1271
1272 case DNS_RTYPE_AAAA:
1273 if (!memcmp(&((struct sockaddr_in6 *)&answer_record->address)->sin6_addr,
Christopher Faulet77f86062021-03-10 15:19:57 +01001274 &((struct sockaddr_in6 *)&ar_item->address)->sin6_addr,
Emeric Brunc9437992021-02-12 19:42:55 +01001275 sizeof(struct in6_addr)))
1276 found = 1;
1277 break;
1278
1279 default:
1280 break;
1281 }
1282
1283 if (found == 1)
1284 break;
1285 }
1286
1287 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001288 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001289 pool_free(resolv_answer_item_pool, answer_record);
1290 answer_record = NULL;
1291 }
1292 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001293 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001294 answer_record->ar_item = NULL;
1295
1296 // looking for the SRV record in the response list linked to this additional record
1297 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1298 if (tmp_record->type == DNS_RTYPE_SRV &&
1299 tmp_record->ar_item == NULL &&
1300 !resolv_hostname_cmp(tmp_record->target, answer_record->name, tmp_record->data_len)) {
1301 /* Always use the received additional record to refresh info */
1302 if (tmp_record->ar_item)
1303 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1304 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001305 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001306 break;
1307 }
1308 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001309 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001310 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001311 answer_record = NULL;
1312 }
Emeric Brunc9437992021-02-12 19:42:55 +01001313 }
1314 } /* for i 0 to arcount */
1315
1316 skip_parsing_additional_records:
1317
1318 /* Save the number of records we really own */
1319 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001320 resolv_check_response(resolution);
1321 return RSLV_RESP_VALID;
1322
1323 invalid_resp:
1324 cause = RSLV_RESP_INVALID;
1325
1326 return_error:
1327 pool_free(resolv_answer_item_pool, answer_record);
1328 return cause;
1329}
1330
1331/* Searches dn_name resolution in resp.
1332 * If existing IP not found, return the first IP matching family_priority,
1333 * otherwise, first ip found
1334 * The following tasks are the responsibility of the caller:
1335 * - <r_res> contains an error free DNS response
1336 * For both cases above, resolv_validate_dns_response is required
1337 * returns one of the RSLV_UPD_* code
1338 */
1339int resolv_get_ip_from_response(struct resolv_response *r_res,
1340 struct resolv_options *resolv_opts, void *currentip,
1341 short currentip_sin_family,
1342 void **newip, short *newip_sin_family,
Emeric Brunbd78c912021-06-11 10:08:05 +02001343 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001344{
Emeric Brunbd78c912021-06-11 10:08:05 +02001345 struct resolv_answer_item *record, *found_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001346 int family_priority;
1347 int currentip_found;
1348 unsigned char *newip4, *newip6;
1349 int currentip_sel;
1350 int j;
1351 int score, max_score;
1352 int allowed_duplicated_ip;
1353
Emeric Brunbd78c912021-06-11 10:08:05 +02001354 /* srv is linked to an alive ip record */
1355 if (owner && LIST_INLIST(&owner->ip_rec_item))
1356 return RSLV_UPD_NO;
1357
Emeric Brunc9437992021-02-12 19:42:55 +01001358 family_priority = resolv_opts->family_prio;
1359 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1360 *newip = newip4 = newip6 = NULL;
1361 currentip_found = 0;
1362 *newip_sin_family = AF_UNSPEC;
1363 max_score = -1;
1364
1365 /* Select an IP regarding configuration preference.
1366 * Top priority is the preferred network ip version,
1367 * second priority is the preferred network.
1368 * the last priority is the currently used IP,
1369 *
1370 * For these three priorities, a score is calculated. The
1371 * weight are:
1372 * 8 - preferred ip version.
1373 * 4 - preferred network.
1374 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1375 * 1 - current ip.
1376 * The result with the biggest score is returned.
1377 */
1378
1379 list_for_each_entry(record, &r_res->answer_list, list) {
1380 void *ip;
1381 unsigned char ip_type;
1382
1383 if (record->type == DNS_RTYPE_A) {
1384 ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
1385 ip_type = AF_INET;
1386 }
1387 else if (record->type == DNS_RTYPE_AAAA) {
1388 ip_type = AF_INET6;
1389 ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
1390 }
1391 else
1392 continue;
1393 score = 0;
1394
1395 /* Check for preferred ip protocol. */
1396 if (ip_type == family_priority)
1397 score += 8;
1398
1399 /* Check for preferred network. */
1400 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1401
1402 /* Compare only the same addresses class. */
1403 if (resolv_opts->pref_net[j].family != ip_type)
1404 continue;
1405
1406 if ((ip_type == AF_INET &&
1407 in_net_ipv4(ip,
1408 &resolv_opts->pref_net[j].mask.in4,
1409 &resolv_opts->pref_net[j].addr.in4)) ||
1410 (ip_type == AF_INET6 &&
1411 in_net_ipv6(ip,
1412 &resolv_opts->pref_net[j].mask.in6,
1413 &resolv_opts->pref_net[j].addr.in6))) {
1414 score += 4;
1415 break;
1416 }
1417 }
1418
1419 /* Check if the IP found in the record is already affected to a
1420 * member of a group. If not, the score should be incremented
1421 * by 2. */
Emeric Brunbd78c912021-06-11 10:08:05 +02001422 if (owner) {
1423 struct server *srv;
1424 int already_used = 0;
1425
1426 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1427 if (srv == owner)
1428 continue;
1429 if (srv->proxy == owner->proxy) {
1430 already_used = 1;
1431 break;
1432 }
1433 }
1434 if (already_used) {
1435 if (!allowed_duplicated_ip) {
1436 continue;
1437 }
1438 }
1439 else {
1440 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001441 }
1442 } else {
1443 score += 2;
1444 }
1445
1446 /* Check for current ip matching. */
1447 if (ip_type == currentip_sin_family &&
1448 ((currentip_sin_family == AF_INET &&
1449 !memcmp(ip, currentip, 4)) ||
1450 (currentip_sin_family == AF_INET6 &&
1451 !memcmp(ip, currentip, 16)))) {
1452 score++;
1453 currentip_sel = 1;
1454 }
1455 else
1456 currentip_sel = 0;
1457
1458 /* Keep the address if the score is better than the previous
1459 * score. The maximum score is 15, if this value is reached, we
1460 * break the parsing. Implicitly, this score is reached the ip
1461 * selected is the current ip. */
1462 if (score > max_score) {
1463 if (ip_type == AF_INET)
1464 newip4 = ip;
1465 else
1466 newip6 = ip;
Emeric Brunbd78c912021-06-11 10:08:05 +02001467 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001468 currentip_found = currentip_sel;
Emeric Brunbd78c912021-06-11 10:08:05 +02001469 if (score == 15) {
1470 /* this was not registered on the current record but it matches
1471 * let's fix it (it may comes from state file */
1472 if (owner)
1473 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001474 return RSLV_UPD_NO;
Emeric Brunbd78c912021-06-11 10:08:05 +02001475 }
Emeric Brunc9437992021-02-12 19:42:55 +01001476 max_score = score;
1477 }
1478 } /* list for each record entries */
1479
1480 /* No IP found in the response */
1481 if (!newip4 && !newip6)
1482 return RSLV_UPD_NO_IP_FOUND;
1483
1484 /* Case when the caller looks first for an IPv4 address */
1485 if (family_priority == AF_INET) {
1486 if (newip4) {
1487 *newip = newip4;
1488 *newip_sin_family = AF_INET;
1489 }
1490 else if (newip6) {
1491 *newip = newip6;
1492 *newip_sin_family = AF_INET6;
1493 }
1494 if (!currentip_found)
1495 goto not_found;
1496 }
1497 /* Case when the caller looks first for an IPv6 address */
1498 else if (family_priority == AF_INET6) {
1499 if (newip6) {
1500 *newip = newip6;
1501 *newip_sin_family = AF_INET6;
1502 }
1503 else if (newip4) {
1504 *newip = newip4;
1505 *newip_sin_family = AF_INET;
1506 }
1507 if (!currentip_found)
1508 goto not_found;
1509 }
1510 /* Case when the caller have no preference (we prefer IPv6) */
1511 else if (family_priority == AF_UNSPEC) {
1512 if (newip6) {
1513 *newip = newip6;
1514 *newip_sin_family = AF_INET6;
1515 }
1516 else if (newip4) {
1517 *newip = newip4;
1518 *newip_sin_family = AF_INET;
1519 }
1520 if (!currentip_found)
1521 goto not_found;
1522 }
1523
1524 /* No reason why we should change the server's IP address */
1525 return RSLV_UPD_NO;
1526
1527 not_found:
Emeric Brunbd78c912021-06-11 10:08:05 +02001528
1529 /* the ip of this record was chosen for the server */
1530 if (owner && found_record) {
1531 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1532 }
1533
Emeric Brunc9437992021-02-12 19:42:55 +01001534 list_for_each_entry(record, &r_res->answer_list, list) {
1535 /* Move the first record to the end of the list, for internal
1536 * round robin */
Willy Tarreau2b718102021-04-21 07:32:39 +02001537 LIST_DELETE(&record->list);
1538 LIST_APPEND(&r_res->answer_list, &record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001539 break;
1540 }
1541 return RSLV_UPD_SRVIP_NOT_FOUND;
1542}
1543
1544/* Turns a domain name label into a string.
1545 *
1546 * <dn> must be a null-terminated string. <dn_len> must include the terminating
1547 * null byte. <str> must be allocated and its size must be passed in <str_len>.
1548 *
1549 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1550 * <str> (including the terminating null byte).
1551 */
1552int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1553{
1554 char *ptr;
1555 int i, sz;
1556
1557 if (str_len < dn_len - 1)
1558 return -1;
1559
1560 ptr = str;
1561 for (i = 0; i < dn_len-1; ++i) {
1562 sz = dn[i];
1563 if (i)
1564 *ptr++ = '.';
1565 memcpy(ptr, dn+i+1, sz);
1566 ptr += sz;
1567 i += sz;
1568 }
1569 *ptr++ = '\0';
1570 return (ptr - str);
1571}
1572
1573/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1574 *
1575 * <str> must be a null-terminated string. <str_len> must include the
1576 * terminating null byte. <dn> buffer must be allocated and its size must be
1577 * passed in <dn_len>.
1578 *
1579 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1580 * <dn> (excluding the terminating null byte).
1581 */
1582int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1583{
1584 int i, offset;
1585
1586 if (dn_len < str_len + 1)
1587 return -1;
1588
1589 /* First byte of dn will be used to store the length of the first
1590 * label */
1591 offset = 0;
1592 for (i = 0; i < str_len; ++i) {
1593 if (str[i] == '.') {
1594 /* 2 or more consecutive dots is invalid */
1595 if (i == offset)
1596 return -1;
1597
1598 /* ignore trailing dot */
1599 if (i + 2 == str_len) {
1600 i++;
1601 break;
1602 }
1603
1604 dn[offset] = (i - offset);
1605 offset = i+1;
1606 continue;
1607 }
1608 dn[i+1] = str[i];
1609 }
1610 dn[offset] = (i - offset - 1);
1611 dn[i] = '\0';
1612 return i;
1613}
1614
1615/* Validates host name:
1616 * - total size
1617 * - each label size individually
1618 * returns:
1619 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1620 * 1 when no error. <err> is left unaffected.
1621 */
1622int resolv_hostname_validation(const char *string, char **err)
1623{
1624 int i;
1625
1626 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1627 if (err)
1628 *err = DNS_TOO_LONG_FQDN;
1629 return 0;
1630 }
1631
1632 while (*string) {
1633 i = 0;
1634 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1635 if (!(*string == '-' || *string == '_' ||
1636 (*string >= 'a' && *string <= 'z') ||
1637 (*string >= 'A' && *string <= 'Z') ||
1638 (*string >= '0' && *string <= '9'))) {
1639 if (err)
1640 *err = DNS_INVALID_CHARACTER;
1641 return 0;
1642 }
1643 i++;
1644 string++;
1645 }
1646
1647 if (!(*string))
1648 break;
1649
1650 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1651 if (err)
1652 *err = DNS_LABEL_TOO_LONG;
1653 return 0;
1654 }
1655
1656 string++;
1657 }
1658 return 1;
1659}
1660
1661/* Picks up an available resolution from the different resolution list
1662 * associated to a resolvers section, in this order:
1663 * 1. check in resolutions.curr for the same hostname and query_type
1664 * 2. check in resolutions.wait for the same hostname and query_type
1665 * 3. Get a new resolution from resolution pool
1666 *
1667 * Returns an available resolution, NULL if none found.
1668 */
1669static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1670 char **hostname_dn, int hostname_dn_len,
1671 int query_type)
1672{
1673 struct resolv_resolution *res;
1674
1675 if (!*hostname_dn)
1676 goto from_pool;
1677
1678 /* Search for same hostname and query type in resolutions.curr */
1679 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1680 if (!res->hostname_dn)
1681 continue;
1682 if ((query_type == res->prefered_query_type) &&
1683 hostname_dn_len == res->hostname_dn_len &&
1684 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1685 return res;
1686 }
1687
1688 /* Search for same hostname and query type in resolutions.wait */
1689 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1690 if (!res->hostname_dn)
1691 continue;
1692 if ((query_type == res->prefered_query_type) &&
1693 hostname_dn_len == res->hostname_dn_len &&
1694 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1695 return res;
1696 }
1697
1698 from_pool:
1699 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001700 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001701 if (res) {
Emeric Brunc9437992021-02-12 19:42:55 +01001702 res->resolvers = resolvers;
1703 res->uuid = resolution_uuid;
1704 res->status = RSLV_STATUS_NONE;
1705 res->step = RSLV_STEP_NONE;
1706 res->last_valid = now_ms;
1707
1708 LIST_INIT(&res->requesters);
1709 LIST_INIT(&res->response.answer_list);
1710
1711 res->prefered_query_type = query_type;
1712 res->query_type = query_type;
1713 res->hostname_dn = *hostname_dn;
1714 res->hostname_dn_len = hostname_dn_len;
1715
1716 ++resolution_uuid;
1717
1718 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001719 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001720 }
1721 return res;
1722}
1723
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001724void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
1725{
1726 struct resolv_answer_item *item, *itemback;
1727
1728 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001729 LIST_DELETE(&item->list);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001730 pool_free(resolv_answer_item_pool, item->ar_item);
1731 pool_free(resolv_answer_item_pool, item);
1732 }
1733}
1734
Emeric Brunc9437992021-02-12 19:42:55 +01001735/* Releases a resolution from its requester(s) and move it back to the pool */
1736static void resolv_free_resolution(struct resolv_resolution *resolution)
1737{
1738 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001739
1740 /* clean up configuration */
1741 resolv_reset_resolution(resolution);
1742 resolution->hostname_dn = NULL;
1743 resolution->hostname_dn_len = 0;
1744
1745 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001746 LIST_DELETE(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001747 req->resolution = NULL;
1748 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001749 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau2b718102021-04-21 07:32:39 +02001750 LIST_DELETE(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001751 pool_free(resolv_resolution_pool, resolution);
1752}
1753
1754/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
1755 * on success, -1 otherwise.
1756 */
1757int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1758{
1759 struct resolv_resolution *res = NULL;
1760 struct resolv_requester *req;
1761 struct resolvers *resolvers;
1762 struct server *srv = NULL;
1763 struct resolv_srvrq *srvrq = NULL;
1764 struct stream *stream = NULL;
1765 char **hostname_dn;
1766 int hostname_dn_len, query_type;
1767
1768 switch (requester_type) {
1769 case OBJ_TYPE_SERVER:
1770 srv = (struct server *)requester;
1771 hostname_dn = &srv->hostname_dn;
1772 hostname_dn_len = srv->hostname_dn_len;
1773 resolvers = srv->resolvers;
1774 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1775 ? DNS_RTYPE_A
1776 : DNS_RTYPE_AAAA);
1777 break;
1778
1779 case OBJ_TYPE_SRVRQ:
1780 srvrq = (struct resolv_srvrq *)requester;
1781 hostname_dn = &srvrq->hostname_dn;
1782 hostname_dn_len = srvrq->hostname_dn_len;
1783 resolvers = srvrq->resolvers;
1784 query_type = DNS_RTYPE_SRV;
1785 break;
1786
1787 case OBJ_TYPE_STREAM:
1788 stream = (struct stream *)requester;
1789 hostname_dn = &stream->resolv_ctx.hostname_dn;
1790 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
1791 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
1792 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
1793 ? DNS_RTYPE_A
1794 : DNS_RTYPE_AAAA);
1795 break;
1796 default:
1797 goto err;
1798 }
1799
1800 /* Get a resolution from the resolvers' wait queue or pool */
1801 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
1802 goto err;
1803
1804 if (srv) {
1805 if (!requester_locked)
1806 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1807 if (srv->resolv_requester == NULL) {
1808 if ((req = pool_alloc(resolv_requester_pool)) == NULL) {
1809 if (!requester_locked)
1810 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1811 goto err;
1812 }
1813 req->owner = &srv->obj_type;
1814 srv->resolv_requester = req;
1815 }
1816 else
1817 req = srv->resolv_requester;
1818 if (!requester_locked)
1819 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1820
1821 req->requester_cb = snr_resolution_cb;
1822 req->requester_error_cb = snr_resolution_error_cb;
1823 }
1824 else if (srvrq) {
1825 if (srvrq->requester == NULL) {
1826 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1827 goto err;
1828 req->owner = &srvrq->obj_type;
1829 srvrq->requester = req;
1830 }
1831 else
1832 req = srvrq->requester;
1833
1834 req->requester_cb = snr_resolution_cb;
Baptiste Assmannb4badf72020-11-19 22:38:33 +01001835 req->requester_error_cb = srvrq_resolution_error_cb;
Emeric Brunc9437992021-02-12 19:42:55 +01001836 }
1837 else if (stream) {
1838 if (stream->resolv_ctx.requester == NULL) {
1839 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1840 goto err;
1841 req->owner = &stream->obj_type;
1842 stream->resolv_ctx.requester = req;
1843 }
1844 else
1845 req = stream->resolv_ctx.requester;
1846
1847 req->requester_cb = act_resolution_cb;
1848 req->requester_error_cb = act_resolution_error_cb;
1849 }
1850 else
1851 goto err;
1852
1853 req->resolution = res;
1854
Willy Tarreau2b718102021-04-21 07:32:39 +02001855 LIST_APPEND(&res->requesters, &req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001856 return 0;
1857
1858 err:
1859 if (res && LIST_ISEMPTY(&res->requesters))
1860 resolv_free_resolution(res);
1861 return -1;
1862}
1863
1864/* Removes a requester from a DNS resolution. It takes takes care of all the
1865 * consequences. It also cleans up some parameters from the requester.
Christopher Faulet0efc0992021-03-11 18:09:53 +01001866 * if <safe> is set to 1, the corresponding resolution is not released.
Emeric Brunc9437992021-02-12 19:42:55 +01001867 */
Christopher Faulet0efc0992021-03-11 18:09:53 +01001868void resolv_unlink_resolution(struct resolv_requester *requester, int safe)
Emeric Brunc9437992021-02-12 19:42:55 +01001869{
1870 struct resolv_resolution *res;
1871 struct resolv_requester *req;
Emeric Brunbd78c912021-06-11 10:08:05 +02001872 struct server *srv;
Emeric Brunc9437992021-02-12 19:42:55 +01001873
1874 /* Nothing to do */
1875 if (!requester || !requester->resolution)
1876 return;
1877 res = requester->resolution;
1878
Emeric Brunbd78c912021-06-11 10:08:05 +02001879 /* remove ref from the resolution answer item list to the requester */
1880 if ((srv = objt_server(requester->owner)) != NULL) {
1881 LIST_DEL_INIT(&srv->ip_rec_item);
1882 }
1883
Emeric Brunc9437992021-02-12 19:42:55 +01001884 /* Clean up the requester */
Willy Tarreau2b718102021-04-21 07:32:39 +02001885 LIST_DELETE(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001886 requester->resolution = NULL;
1887
1888 /* We need to find another requester linked on this resolution */
1889 if (!LIST_ISEMPTY(&res->requesters))
1890 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
1891 else {
Christopher Faulet0efc0992021-03-11 18:09:53 +01001892 if (safe) {
1893 /* Don't release it yet. */
1894 resolv_reset_resolution(res);
1895 res->hostname_dn = NULL;
1896 res->hostname_dn_len = 0;
1897 resolv_purge_resolution_answer_records(res);
1898 return;
1899 }
1900
Emeric Brunc9437992021-02-12 19:42:55 +01001901 resolv_free_resolution(res);
1902 return;
1903 }
1904
1905 /* Move hostname_dn related pointers to the next requester */
1906 switch (obj_type(req->owner)) {
1907 case OBJ_TYPE_SERVER:
1908 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
1909 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
1910 break;
1911 case OBJ_TYPE_SRVRQ:
1912 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
1913 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
1914 break;
1915 case OBJ_TYPE_STREAM:
1916 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
1917 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
1918 break;
1919 default:
1920 res->hostname_dn = NULL;
1921 res->hostname_dn_len = 0;
1922 break;
1923 }
1924}
1925
1926/* Called when a network IO is generated on a name server socket for an incoming
1927 * packet. It performs the following actions:
1928 * - check if the packet requires processing (not outdated resolution)
1929 * - ensure the DNS packet received is valid and call requester's callback
1930 * - call requester's error callback if invalid response
1931 * - check the dn_name in the packet against the one sent
1932 */
1933static int resolv_process_responses(struct dns_nameserver *ns)
1934{
1935 struct dns_counters *tmpcounters;
1936 struct resolvers *resolvers;
1937 struct resolv_resolution *res;
1938 struct resolv_query_item *query;
1939 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
1940 unsigned char *bufend;
1941 int buflen, dns_resp;
1942 int max_answer_records;
1943 unsigned short query_id;
1944 struct eb32_node *eb;
1945 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02001946 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01001947
1948 resolvers = ns->parent;
1949 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
1950
1951 /* process all pending input messages */
1952 while (1) {
1953 /* read message received */
1954 memset(buf, '\0', resolvers->accepted_payload_size + 1);
1955 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
1956 break;
1957 }
1958
1959 /* message too big */
1960 if (buflen > resolvers->accepted_payload_size) {
1961 ns->counters->too_big++;
1962 continue;
1963 }
1964
1965 /* initializing variables */
1966 bufend = buf + buflen; /* pointer to mark the end of the buffer */
1967
1968 /* read the query id from the packet (16 bits) */
1969 if (buf + 2 > bufend) {
1970 ns->counters->invalid++;
1971 continue;
1972 }
1973 query_id = resolv_response_get_query_id(buf);
1974
1975 /* search the query_id in the pending resolution tree */
1976 eb = eb32_lookup(&resolvers->query_ids, query_id);
1977 if (eb == NULL) {
1978 /* unknown query id means an outdated response and can be safely ignored */
1979 ns->counters->outdated++;
1980 continue;
1981 }
1982
1983 /* known query id means a resolution in progress */
1984 res = eb32_entry(eb, struct resolv_resolution, qid);
1985 /* number of responses received */
1986 res->nb_responses++;
1987
1988 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
1989 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
1990
1991 switch (dns_resp) {
1992 case RSLV_RESP_VALID:
1993 break;
1994
1995 case RSLV_RESP_INVALID:
1996 case RSLV_RESP_QUERY_COUNT_ERROR:
1997 case RSLV_RESP_WRONG_NAME:
1998 res->status = RSLV_STATUS_INVALID;
1999 ns->counters->invalid++;
2000 break;
2001
2002 case RSLV_RESP_NX_DOMAIN:
2003 res->status = RSLV_STATUS_NX;
2004 ns->counters->nx++;
2005 break;
2006
2007 case RSLV_RESP_REFUSED:
2008 res->status = RSLV_STATUS_REFUSED;
2009 ns->counters->refused++;
2010 break;
2011
2012 case RSLV_RESP_ANCOUNT_ZERO:
2013 res->status = RSLV_STATUS_OTHER;
2014 ns->counters->any_err++;
2015 break;
2016
2017 case RSLV_RESP_CNAME_ERROR:
2018 res->status = RSLV_STATUS_OTHER;
2019 ns->counters->cname_error++;
2020 break;
2021
2022 case RSLV_RESP_TRUNCATED:
2023 res->status = RSLV_STATUS_OTHER;
2024 ns->counters->truncated++;
2025 break;
2026
2027 case RSLV_RESP_NO_EXPECTED_RECORD:
2028 case RSLV_RESP_ERROR:
2029 case RSLV_RESP_INTERNAL:
2030 res->status = RSLV_STATUS_OTHER;
2031 ns->counters->other++;
2032 break;
2033 }
2034
2035 /* Wait all nameservers response to handle errors */
2036 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2037 continue;
2038
2039 /* Process error codes */
2040 if (dns_resp != RSLV_RESP_VALID) {
2041 if (res->prefered_query_type != res->query_type) {
2042 /* The fallback on the query type was already performed,
2043 * so check the try counter. If it falls to 0, we can
2044 * report an error. Else, wait the next attempt. */
2045 if (!res->try)
2046 goto report_res_error;
2047 }
2048 else {
2049 /* Fallback from A to AAAA or the opposite and re-send
2050 * the resolution immediately. try counter is not
2051 * decremented. */
2052 if (res->prefered_query_type == DNS_RTYPE_A) {
2053 res->query_type = DNS_RTYPE_AAAA;
2054 resolv_send_query(res);
2055 }
2056 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2057 res->query_type = DNS_RTYPE_A;
2058 resolv_send_query(res);
2059 }
2060 }
2061 continue;
2062 }
2063
2064 /* Now let's check the query's dname corresponds to the one we
2065 * sent. We can check only the first query of the list. We send
2066 * one query at a time so we get one query in the response */
2067 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
2068 if (query && resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
2069 dns_resp = RSLV_RESP_WRONG_NAME;
2070 ns->counters->other++;
2071 goto report_res_error;
2072 }
2073
2074 /* So the resolution succeeded */
2075 res->status = RSLV_STATUS_VALID;
2076 res->last_valid = now_ms;
2077 ns->counters->valid++;
2078 goto report_res_success;
2079
2080 report_res_error:
Emeric Brun12ca6582021-06-10 15:25:25 +02002081 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002082 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002083 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2084 if (!keep_answer_items)
2085 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002086 resolv_reset_resolution(res);
Willy Tarreau2b718102021-04-21 07:32:39 +02002087 LIST_DELETE(&res->list);
2088 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002089 continue;
2090
2091 report_res_success:
2092 /* Only the 1rst requester s managed by the server, others are
2093 * from the cache */
2094 tmpcounters = ns->counters;
2095 list_for_each_entry(req, &res->requesters, list) {
2096 struct server *s = objt_server(req->owner);
2097
2098 if (s)
2099 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2100 req->requester_cb(req, tmpcounters);
2101 if (s)
2102 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2103 tmpcounters = NULL;
2104 }
2105
2106 resolv_reset_resolution(res);
Willy Tarreau2b718102021-04-21 07:32:39 +02002107 LIST_DELETE(&res->list);
2108 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002109 continue;
2110 }
2111 resolv_update_resolvers_timeout(resolvers);
2112 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2113
2114 return buflen;
2115}
2116
2117/* Processes DNS resolution. First, it checks the active list to detect expired
2118 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2119 * checks the wait list to trigger new resolutions.
2120 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002121static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002122{
2123 struct resolvers *resolvers = context;
2124 struct resolv_resolution *res, *resback;
2125 int exp;
2126
2127 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2128
2129 /* Handle all expired resolutions from the active list */
2130 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002131 if (LIST_ISEMPTY(&res->requesters)) {
2132 resolv_free_resolution(res);
2133 continue;
2134 }
2135
Emeric Brunc9437992021-02-12 19:42:55 +01002136 /* When we find the first resolution in the future, then we can
2137 * stop here */
2138 exp = tick_add(res->last_query, resolvers->timeout.retry);
2139 if (!tick_is_expired(exp, now_ms))
2140 break;
2141
2142 /* If current resolution has been tried too many times and
2143 * finishes in timeout we update its status and remove it from
2144 * the list */
2145 if (!res->try) {
2146 struct resolv_requester *req;
Emeric Brun12ca6582021-06-10 15:25:25 +02002147 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002148
2149 /* Notify the result to the requesters */
2150 if (!res->nb_responses)
2151 res->status = RSLV_STATUS_TIMEOUT;
2152 list_for_each_entry(req, &res->requesters, list)
Emeric Brun12ca6582021-06-10 15:25:25 +02002153 keep_answer_items |= req->requester_error_cb(req, res->status);
2154 if (!keep_answer_items)
2155 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002156
2157 /* Clean up resolution info and remove it from the
2158 * current list */
2159 resolv_reset_resolution(res);
Willy Tarreau2b718102021-04-21 07:32:39 +02002160 LIST_DELETE(&res->list);
2161 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002162 }
2163 else {
2164 /* Otherwise resend the DNS query and requeue the resolution */
2165 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2166 /* No response received (a real timeout) or fallback already done */
2167 res->query_type = res->prefered_query_type;
2168 res->try--;
2169 }
2170 else {
2171 /* Fallback from A to AAAA or the opposite and re-send
2172 * the resolution immediately. try counter is not
2173 * decremented. */
2174 if (res->prefered_query_type == DNS_RTYPE_A)
2175 res->query_type = DNS_RTYPE_AAAA;
2176 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2177 res->query_type = DNS_RTYPE_A;
2178 else
2179 res->try--;
2180 }
2181 resolv_send_query(res);
2182 }
2183 }
2184
2185 /* Handle all resolutions in the wait list */
2186 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002187 if (LIST_ISEMPTY(&res->requesters)) {
2188 resolv_free_resolution(res);
2189 continue;
2190 }
2191
Emeric Brunc9437992021-02-12 19:42:55 +01002192 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2193 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2194 continue;
2195
2196 if (resolv_run_resolution(res) != 1) {
2197 res->last_resolution = now_ms;
Willy Tarreau2b718102021-04-21 07:32:39 +02002198 LIST_DELETE(&res->list);
2199 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002200 }
2201 }
2202
2203 resolv_update_resolvers_timeout(resolvers);
2204 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2205 return t;
2206}
2207
2208/* Release memory allocated by DNS */
2209static void resolvers_deinit(void)
2210{
2211 struct resolvers *resolvers, *resolversback;
2212 struct dns_nameserver *ns, *nsback;
2213 struct resolv_resolution *res, *resback;
2214 struct resolv_requester *req, *reqback;
2215 struct resolv_srvrq *srvrq, *srvrqback;
2216
2217 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2218 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2219 free(ns->id);
2220 free((char *)ns->conf.file);
2221 if (ns->dgram) {
2222 if (ns->dgram->conn.t.sock.fd != -1) {
2223 fd_delete(ns->dgram->conn.t.sock.fd);
2224 close(ns->dgram->conn.t.sock.fd);
2225 }
2226 if (ns->dgram->ring_req)
2227 ring_free(ns->dgram->ring_req);
2228 free(ns->dgram);
2229 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002230 if (ns->stream) {
2231 if (ns->stream->ring_req)
2232 ring_free(ns->stream->ring_req);
2233 if (ns->stream->task_req)
2234 task_destroy(ns->stream->task_req);
2235 if (ns->stream->task_rsp)
2236 task_destroy(ns->stream->task_rsp);
2237 free(ns->stream);
2238 }
Willy Tarreau2b718102021-04-21 07:32:39 +02002239 LIST_DELETE(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002240 EXTRA_COUNTERS_FREE(ns->extra_counters);
2241 free(ns);
2242 }
2243
2244 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2245 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002246 LIST_DELETE(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002247 pool_free(resolv_requester_pool, req);
2248 }
2249 resolv_free_resolution(res);
2250 }
2251
2252 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2253 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002254 LIST_DELETE(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002255 pool_free(resolv_requester_pool, req);
2256 }
2257 resolv_free_resolution(res);
2258 }
2259
2260 free(resolvers->id);
2261 free((char *)resolvers->conf.file);
2262 task_destroy(resolvers->t);
Willy Tarreau2b718102021-04-21 07:32:39 +02002263 LIST_DELETE(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002264 free(resolvers);
2265 }
2266
2267 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2268 free(srvrq->name);
2269 free(srvrq->hostname_dn);
Willy Tarreau2b718102021-04-21 07:32:39 +02002270 LIST_DELETE(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002271 free(srvrq);
2272 }
2273}
2274
2275/* Finalizes the DNS configuration by allocating required resources and checking
2276 * live parameters.
2277 * Returns 0 on success, ERR_* flags otherwise.
2278 */
2279static int resolvers_finalize_config(void)
2280{
2281 struct resolvers *resolvers;
2282 struct proxy *px;
2283 int err_code = 0;
2284
2285 /* allocate pool of resolution per resolvers */
2286 list_for_each_entry(resolvers, &sec_resolvers, list) {
2287 struct dns_nameserver *ns;
2288 struct task *t;
2289
2290 /* Check if we can create the socket with nameservers info */
2291 list_for_each_entry(ns, &resolvers->nameservers, list) {
2292 int fd;
2293
2294 if (ns->dgram) {
2295 /* Check nameserver info */
2296 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002297 ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002298 resolvers->id, ns->id);
2299 err_code |= (ERR_ALERT|ERR_ABORT);
2300 continue;
2301 }
2302 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002303 ha_alert("resolvers '%s': can't connect socket for nameserver '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002304 resolvers->id, ns->id);
2305 close(fd);
2306 err_code |= (ERR_ALERT|ERR_ABORT);
2307 continue;
2308 }
2309 close(fd);
2310 }
2311 }
2312
2313 /* Create the task associated to the resolvers section */
2314 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002315 ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
Emeric Brunc9437992021-02-12 19:42:55 +01002316 err_code |= (ERR_ALERT|ERR_ABORT);
2317 goto err;
2318 }
2319
2320 /* Update task's parameters */
2321 t->process = process_resolvers;
2322 t->context = resolvers;
2323 resolvers->t = t;
2324 task_wakeup(t, TASK_WOKEN_INIT);
2325 }
2326
2327 for (px = proxies_list; px; px = px->next) {
2328 struct server *srv;
2329
2330 for (srv = px->srv; srv; srv = srv->next) {
2331 struct resolvers *resolvers;
2332
2333 if (!srv->resolvers_id)
2334 continue;
2335
2336 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002337 ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002338 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2339 err_code |= (ERR_ALERT|ERR_ABORT);
2340 continue;
2341 }
2342 srv->resolvers = resolvers;
2343
2344 if (srv->srvrq && !srv->srvrq->resolvers) {
2345 srv->srvrq->resolvers = srv->resolvers;
2346 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002347 ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002348 proxy_type_str(px), px->id, srv->id);
2349 err_code |= (ERR_ALERT|ERR_ABORT);
2350 continue;
2351 }
2352 }
Christopher Fauletd83a6df2021-03-12 10:23:05 +01002353 if (!srv->srvrq && resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Amaury Denoyelle11124302021-06-04 18:22:08 +02002354 ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002355 proxy_type_str(px), px->id, srv->id);
2356 err_code |= (ERR_ALERT|ERR_ABORT);
2357 continue;
2358 }
2359 }
2360 }
2361
2362 if (err_code & (ERR_ALERT|ERR_ABORT))
2363 goto err;
2364
2365 return err_code;
2366 err:
2367 resolvers_deinit();
2368 return err_code;
2369
2370}
2371
2372static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2373 struct dns_nameserver *ns,
2374 struct field *stats, size_t stats_count,
2375 struct list *stat_modules)
2376{
2377 struct appctx *appctx = __objt_appctx(si->end);
2378 struct channel *rep = si_ic(si);
2379 struct stats_module *mod;
2380 size_t idx = 0;
2381
2382 memset(stats, 0, sizeof(struct field) * stats_count);
2383
2384 list_for_each_entry(mod, stat_modules, list) {
2385 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2386
2387 mod->fill_stats(counters, stats + idx);
2388 idx += mod->stats_count;
2389 }
2390
2391 if (!stats_dump_one_line(stats, idx, appctx))
2392 return 0;
2393
2394 if (!stats_putchk(rep, NULL, &trash))
2395 goto full;
2396
2397 return 1;
2398
2399 full:
2400 si_rx_room_rdy(si);
2401 return 0;
2402}
2403
2404/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2405 * as a pointer to the current nameserver.
2406 */
2407int stats_dump_resolvers(struct stream_interface *si,
2408 struct field *stats, size_t stats_count,
2409 struct list *stat_modules)
2410{
2411 struct appctx *appctx = __objt_appctx(si->end);
2412 struct channel *rep = si_ic(si);
2413 struct resolvers *resolver = appctx->ctx.stats.obj1;
2414 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2415
2416 if (!resolver)
2417 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2418
2419 /* dump resolvers */
2420 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2421 appctx->ctx.stats.obj1 = resolver;
2422
2423 ns = appctx->ctx.stats.obj2 ?
2424 appctx->ctx.stats.obj2 :
2425 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2426
2427 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2428 appctx->ctx.stats.obj2 = ns;
2429
2430 if (buffer_almost_full(&rep->buf))
2431 goto full;
2432
2433 if (!stats_dump_resolv_to_buffer(si, ns,
2434 stats, stats_count,
2435 stat_modules)) {
2436 return 0;
2437 }
2438 }
2439
2440 appctx->ctx.stats.obj2 = NULL;
2441 }
2442
2443 return 1;
2444
2445 full:
2446 si_rx_room_blk(si);
2447 return 0;
2448}
2449
2450void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2451{
2452 struct resolvers *resolvers;
2453 struct dns_nameserver *ns;
2454 struct stats_module *mod;
2455 void *counters;
2456
2457 list_for_each_entry(mod, stat_modules, list) {
2458 if (!mod->clearable && !clrall)
2459 continue;
2460
2461 list_for_each_entry(resolvers, &sec_resolvers, list) {
2462 list_for_each_entry(ns, &resolvers->nameservers, list) {
2463 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2464 memcpy(counters, mod->counters, mod->counters_size);
2465 }
2466 }
2467 }
2468
2469}
2470
2471int resolv_allocate_counters(struct list *stat_modules)
2472{
2473 struct stats_module *mod;
2474 struct resolvers *resolvers;
2475 struct dns_nameserver *ns;
2476
2477 list_for_each_entry(resolvers, &sec_resolvers, list) {
2478 list_for_each_entry(ns, &resolvers->nameservers, list) {
2479 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2480 alloc_failed);
2481
2482 list_for_each_entry(mod, stat_modules, list) {
2483 EXTRA_COUNTERS_ADD(mod,
2484 ns->extra_counters,
2485 mod->counters,
2486 mod->counters_size);
2487 }
2488
2489 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2490
2491 list_for_each_entry(mod, stat_modules, list) {
2492 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2493 mod->counters, mod->counters_size);
2494
2495 /* Store the ns counters pointer */
2496 if (strcmp(mod->name, "dns") == 0) {
2497 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2498 ns->counters->id = ns->id;
2499 ns->counters->pid = resolvers->id;
2500 }
2501 }
2502 }
2503 }
2504
2505 return 1;
2506
2507alloc_failed:
2508 return 0;
2509}
2510
2511/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2512static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2513{
2514 struct resolvers *presolvers;
2515
2516 if (*args[2]) {
2517 list_for_each_entry(presolvers, &sec_resolvers, list) {
2518 if (strcmp(presolvers->id, args[2]) == 0) {
2519 appctx->ctx.cli.p0 = presolvers;
2520 break;
2521 }
2522 }
2523 if (appctx->ctx.cli.p0 == NULL)
2524 return cli_err(appctx, "Can't find that resolvers section\n");
2525 }
2526 return 0;
2527}
2528
2529/* Dumps counters from all resolvers section and associated name servers. It
2530 * returns 0 if the output buffer is full and it needs to be called again,
2531 * otherwise non-zero. It may limit itself to the resolver pointed to by
2532 * <cli.p0> if it's not null.
2533 */
2534static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2535{
2536 struct stream_interface *si = appctx->owner;
2537 struct resolvers *resolvers;
2538 struct dns_nameserver *ns;
2539
2540 chunk_reset(&trash);
2541
2542 switch (appctx->st2) {
2543 case STAT_ST_INIT:
2544 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2545 /* fall through */
2546
2547 case STAT_ST_LIST:
2548 if (LIST_ISEMPTY(&sec_resolvers)) {
2549 chunk_appendf(&trash, "No resolvers found\n");
2550 }
2551 else {
2552 list_for_each_entry(resolvers, &sec_resolvers, list) {
2553 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2554 continue;
2555
2556 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2557 list_for_each_entry(ns, &resolvers->nameservers, list) {
2558 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2559 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2560 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2561 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2562 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2563 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2564 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2565 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2566 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2567 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2568 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2569 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2570 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2571 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2572 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2573 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
2574 }
2575 chunk_appendf(&trash, "\n");
2576 }
2577 }
2578
2579 /* display response */
2580 if (ci_putchk(si_ic(si), &trash) == -1) {
2581 /* let's try again later from this session. We add ourselves into
2582 * this session's users so that it can remove us upon termination.
2583 */
2584 si_rx_room_blk(si);
2585 return 0;
2586 }
2587 /* fall through */
2588
2589 default:
2590 appctx->st2 = STAT_ST_FIN;
2591 return 1;
2592 }
2593}
2594
2595/* register cli keywords */
2596static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002597 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002598 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2599 {{},}
2600 }
2601};
2602
2603INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2604
2605/*
2606 * Prepare <rule> for hostname resolution.
2607 * Returns -1 in case of any allocation failure, 0 if not.
2608 * On error, a global failure counter is also incremented.
2609 */
2610static int action_prepare_for_resolution(struct stream *stream, const char *hostname)
2611{
2612 char *hostname_dn;
2613 int hostname_len, hostname_dn_len;
2614 struct buffer *tmp = get_trash_chunk();
2615
2616 if (!hostname)
2617 return 0;
2618
2619 hostname_len = strlen(hostname);
2620 hostname_dn = tmp->area;
2621 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len + 1,
2622 hostname_dn, tmp->size);
2623 if (hostname_dn_len == -1)
2624 goto err;
2625
2626
2627 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2628 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2629 if (!stream->resolv_ctx.hostname_dn)
2630 goto err;
2631
2632 return 0;
2633
2634 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002635 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002636 resolv_failed_resolutions += 1;
2637 return -1;
2638}
2639
2640
2641/*
2642 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2643 */
2644enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2645 struct session *sess, struct stream *s, int flags)
2646{
2647 struct resolv_resolution *resolution;
2648 struct sample *smp;
2649 char *fqdn;
2650 struct resolv_requester *req;
2651 struct resolvers *resolvers;
2652 struct resolv_resolution *res;
2653 int exp, locked = 0;
2654 enum act_return ret = ACT_RET_CONT;
2655
2656 resolvers = rule->arg.resolv.resolvers;
2657
2658 /* we have a response to our DNS resolution */
2659 use_cache:
2660 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2661 resolution = s->resolv_ctx.requester->resolution;
2662 if (!locked) {
2663 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2664 locked = 1;
2665 }
2666
2667 if (resolution->step == RSLV_STEP_RUNNING)
2668 goto yield;
2669 if (resolution->step == RSLV_STEP_NONE) {
2670 /* We update the variable only if we have a valid response. */
2671 if (resolution->status == RSLV_STATUS_VALID) {
2672 struct sample smp;
2673 short ip_sin_family = 0;
2674 void *ip = NULL;
2675
2676 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2677 0, &ip, &ip_sin_family, NULL);
2678
2679 switch (ip_sin_family) {
2680 case AF_INET:
2681 smp.data.type = SMP_T_IPV4;
2682 memcpy(&smp.data.u.ipv4, ip, 4);
2683 break;
2684 case AF_INET6:
2685 smp.data.type = SMP_T_IPV6;
2686 memcpy(&smp.data.u.ipv6, ip, 16);
2687 break;
2688 default:
2689 ip = NULL;
2690 }
2691
2692 if (ip) {
2693 smp.px = px;
2694 smp.sess = sess;
2695 smp.strm = s;
2696
2697 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2698 }
2699 }
2700 }
2701
2702 goto release_requester;
2703 }
2704
2705 /* need to configure and start a new DNS resolution */
2706 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2707 if (smp == NULL)
2708 goto end;
2709
2710 fqdn = smp->data.u.str.area;
2711 if (action_prepare_for_resolution(s, fqdn) == -1)
2712 goto end; /* on error, ignore the action */
2713
2714 s->resolv_ctx.parent = rule;
2715
2716 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2717 locked = 1;
2718
2719 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2720
2721 /* Check if there is a fresh enough response in the cache of our associated resolution */
2722 req = s->resolv_ctx.requester;
2723 if (!req || !req->resolution)
2724 goto release_requester; /* on error, ignore the action */
2725 res = req->resolution;
2726
2727 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2728 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2729 && !tick_is_expired(exp, now_ms)) {
2730 goto use_cache;
2731 }
2732
2733 resolv_trigger_resolution(s->resolv_ctx.requester);
2734
2735 yield:
2736 if (flags & ACT_OPT_FINAL)
2737 goto release_requester;
2738 ret = ACT_RET_YIELD;
2739
2740 end:
2741 if (locked)
2742 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2743 return ret;
2744
2745 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002746 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002747 s->resolv_ctx.hostname_dn_len = 0;
2748 if (s->resolv_ctx.requester) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002749 resolv_unlink_resolution(s->resolv_ctx.requester, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01002750 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2751 s->resolv_ctx.requester = NULL;
2752 }
2753 goto end;
2754}
2755
2756static void release_resolv_action(struct act_rule *rule)
2757{
2758 release_sample_expr(rule->arg.resolv.expr);
2759 free(rule->arg.resolv.varname);
2760 free(rule->arg.resolv.resolvers_id);
2761 free(rule->arg.resolv.opts);
2762}
2763
2764
2765/* parse "do-resolve" action
2766 * This action takes the following arguments:
2767 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
2768 *
2769 * - <varName> is the variable name where the result of the DNS resolution will be stored
2770 * (mandatory)
2771 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
2772 * (mandatory)
2773 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
2774 * (optional), defaults to ipv6
2775 * - <expr> is an HAProxy expression used to fetch the name to be resolved
2776 */
2777enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
2778{
2779 int cur_arg;
2780 struct sample_expr *expr;
2781 unsigned int where;
2782 const char *beg, *end;
2783
2784 /* orig_arg points to the first argument, but we need to analyse the command itself first */
2785 cur_arg = *orig_arg - 1;
2786
2787 /* locate varName, which is mandatory */
2788 beg = strchr(args[cur_arg], '(');
2789 if (beg == NULL)
2790 goto do_resolve_parse_error;
2791 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
2792 end = strchr(beg, ',');
2793 if (end == NULL)
2794 goto do_resolve_parse_error;
2795 rule->arg.resolv.varname = my_strndup(beg, end - beg);
2796 if (rule->arg.resolv.varname == NULL)
2797 goto do_resolve_parse_error;
2798
2799
2800 /* locate resolversSectionName, which is mandatory.
2801 * Since next parameters are optional, the delimiter may be comma ','
2802 * or closing parenthesis ')'
2803 */
2804 beg = end + 1;
2805 end = strchr(beg, ',');
2806 if (end == NULL)
2807 end = strchr(beg, ')');
2808 if (end == NULL)
2809 goto do_resolve_parse_error;
2810 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
2811 if (rule->arg.resolv.resolvers_id == NULL)
2812 goto do_resolve_parse_error;
2813
2814
2815 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
2816 if (rule->arg.resolv.opts == NULL)
2817 goto do_resolve_parse_error;
2818
2819 /* Default priority is ipv6 */
2820 rule->arg.resolv.opts->family_prio = AF_INET6;
2821
2822 /* optional arguments accepted for now:
2823 * ipv4 or ipv6
2824 */
2825 while (*end != ')') {
2826 beg = end + 1;
2827 end = strchr(beg, ',');
2828 if (end == NULL)
2829 end = strchr(beg, ')');
2830 if (end == NULL)
2831 goto do_resolve_parse_error;
2832
2833 if (strncmp(beg, "ipv4", end - beg) == 0) {
2834 rule->arg.resolv.opts->family_prio = AF_INET;
2835 }
2836 else if (strncmp(beg, "ipv6", end - beg) == 0) {
2837 rule->arg.resolv.opts->family_prio = AF_INET6;
2838 }
2839 else {
2840 goto do_resolve_parse_error;
2841 }
2842 }
2843
2844 cur_arg = cur_arg + 1;
2845
2846 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
2847 if (!expr)
2848 goto do_resolve_parse_error;
2849
2850
2851 where = 0;
2852 if (px->cap & PR_CAP_FE)
2853 where |= SMP_VAL_FE_HRQ_HDR;
2854 if (px->cap & PR_CAP_BE)
2855 where |= SMP_VAL_BE_HRQ_HDR;
2856
2857 if (!(expr->fetch->val & where)) {
2858 memprintf(err,
2859 "fetch method '%s' extracts information from '%s', none of which is available here",
2860 args[cur_arg-1], sample_src_names(expr->fetch->use));
2861 free(expr);
2862 return ACT_RET_PRS_ERR;
2863 }
2864 rule->arg.resolv.expr = expr;
2865 rule->action = ACT_CUSTOM;
2866 rule->action_ptr = resolv_action_do_resolve;
2867 *orig_arg = cur_arg;
2868
2869 rule->check_ptr = check_action_do_resolve;
2870 rule->release_ptr = release_resolv_action;
2871
2872 return ACT_RET_PRS_OK;
2873
2874 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002875 ha_free(&rule->arg.resolv.varname);
2876 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01002877 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
2878 args[cur_arg]);
2879 return ACT_RET_PRS_ERR;
2880}
2881
2882static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02002883 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01002884 { /* END */ }
2885}};
2886
2887INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
2888
2889static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02002890 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01002891 { /* END */ }
2892}};
2893
2894INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
2895
2896/* Check an "http-request do-resolve" action.
2897 *
2898 * The function returns 1 in success case, otherwise, it returns 0 and err is
2899 * filled.
2900 */
2901int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
2902{
2903 struct resolvers *resolvers = NULL;
2904
2905 if (rule->arg.resolv.resolvers_id == NULL) {
2906 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
2907 return 0;
2908 }
2909
2910 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
2911 if (resolvers == NULL) {
2912 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
2913 return 0;
2914 }
2915 rule->arg.resolv.resolvers = resolvers;
2916
2917 return 1;
2918}
2919
2920void resolvers_setup_proxy(struct proxy *px)
2921{
2922 px->last_change = now.tv_sec;
2923 px->cap = PR_CAP_FE | PR_CAP_BE;
2924 px->maxconn = 0;
2925 px->conn_retries = 1;
2926 px->timeout.server = TICK_ETERNITY;
2927 px->timeout.client = TICK_ETERNITY;
2928 px->timeout.connect = TICK_ETERNITY;
2929 px->accept = NULL;
2930 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
2931 px->bind_proc = 0; /* will be filled by users */
2932}
2933
2934/*
2935 * Parse a <resolvers> section.
2936 * Returns the error code, 0 if OK, or any combination of :
2937 * - ERR_ABORT: must abort ASAP
2938 * - ERR_FATAL: we can continue parsing but not start the service
2939 * - ERR_WARN: a warning has been emitted
2940 * - ERR_ALERT: an alert has been emitted
2941 * Only the two first ones can stop processing, the two others are just
2942 * indicators.
2943 */
2944int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
2945{
2946 const char *err;
2947 int err_code = 0;
2948 char *errmsg = NULL;
2949 struct proxy *p;
2950
2951 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
2952 if (!*args[1]) {
2953 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
2954 err_code |= ERR_ALERT | ERR_ABORT;
2955 goto out;
2956 }
2957
2958 err = invalid_char(args[1]);
2959 if (err) {
2960 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
2961 file, linenum, *err, args[0], args[1]);
2962 err_code |= ERR_ALERT | ERR_ABORT;
2963 goto out;
2964 }
2965
2966 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
2967 /* Error if two resolvers owns the same name */
2968 if (strcmp(curr_resolvers->id, args[1]) == 0) {
2969 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
2970 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
2971 err_code |= ERR_ALERT | ERR_ABORT;
2972 }
2973 }
2974
2975 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
2976 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2977 err_code |= ERR_ALERT | ERR_ABORT;
2978 goto out;
2979 }
2980
2981 /* allocate new proxy to tcp servers */
2982 p = calloc(1, sizeof *p);
2983 if (!p) {
2984 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2985 err_code |= ERR_ALERT | ERR_FATAL;
2986 goto out;
2987 }
2988
2989 init_new_proxy(p);
2990 resolvers_setup_proxy(p);
2991 p->parent = curr_resolvers;
2992 p->id = strdup(args[1]);
2993 p->conf.args.file = p->conf.file = strdup(file);
2994 p->conf.args.line = p->conf.line = linenum;
2995 curr_resolvers->px = p;
2996
2997 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02002998 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002999 curr_resolvers->conf.file = strdup(file);
3000 curr_resolvers->conf.line = linenum;
3001 curr_resolvers->id = strdup(args[1]);
3002 curr_resolvers->query_ids = EB_ROOT;
3003 /* default maximum response size */
3004 curr_resolvers->accepted_payload_size = 512;
3005 /* default hold period for nx, other, refuse and timeout is 30s */
3006 curr_resolvers->hold.nx = 30000;
3007 curr_resolvers->hold.other = 30000;
3008 curr_resolvers->hold.refused = 30000;
3009 curr_resolvers->hold.timeout = 30000;
3010 curr_resolvers->hold.obsolete = 0;
3011 /* default hold period for valid is 10s */
3012 curr_resolvers->hold.valid = 10000;
3013 curr_resolvers->timeout.resolve = 1000;
3014 curr_resolvers->timeout.retry = 1000;
3015 curr_resolvers->resolve_retries = 3;
3016 LIST_INIT(&curr_resolvers->nameservers);
3017 LIST_INIT(&curr_resolvers->resolutions.curr);
3018 LIST_INIT(&curr_resolvers->resolutions.wait);
3019 HA_SPIN_INIT(&curr_resolvers->lock);
3020 }
3021 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3022 struct dns_nameserver *newnameserver = NULL;
3023 struct sockaddr_storage *sk;
3024 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003025 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003026
3027 if (!*args[2]) {
3028 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3029 file, linenum, args[0]);
3030 err_code |= ERR_ALERT | ERR_FATAL;
3031 goto out;
3032 }
3033
3034 err = invalid_char(args[1]);
3035 if (err) {
3036 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3037 file, linenum, *err, args[1]);
3038 err_code |= ERR_ALERT | ERR_FATAL;
3039 goto out;
3040 }
3041
3042 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3043 /* Error if two resolvers owns the same name */
3044 if (strcmp(newnameserver->id, args[1]) == 0) {
3045 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3046 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3047 err_code |= ERR_ALERT | ERR_FATAL;
3048 }
3049 }
3050
Emeric Brunc8f3e452021-04-07 16:04:54 +02003051 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3052 &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 +01003053 if (!sk) {
3054 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3055 err_code |= ERR_ALERT | ERR_FATAL;
3056 goto out;
3057 }
3058
3059 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3060 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3061 err_code |= ERR_ALERT | ERR_ABORT;
3062 goto out;
3063 }
3064
Emeric Brunc8f3e452021-04-07 16:04:54 +02003065 if (proto && proto->ctrl_type == SOCK_STREAM) {
3066 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3067 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3068 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3069 err_code |= ERR_ABORT;
3070 goto out;
3071 }
3072
3073 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3074 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3075 err_code |= ERR_ALERT|ERR_ABORT;
3076 goto out;
3077 }
3078 }
3079 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003080 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3081 err_code |= ERR_ALERT | ERR_ABORT;
3082 goto out;
3083 }
3084
3085 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3086 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3087 err_code |= ERR_ALERT | ERR_ABORT;
3088 goto out;
3089 }
3090
3091 if ((newnameserver->id = strdup(args[1])) == NULL) {
3092 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3093 err_code |= ERR_ALERT | ERR_ABORT;
3094 goto out;
3095 }
3096
3097 newnameserver->parent = curr_resolvers;
3098 newnameserver->process_responses = resolv_process_responses;
3099 newnameserver->conf.line = linenum;
3100 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003101 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003102 }
3103 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3104 struct dns_nameserver *newnameserver = NULL;
3105 const char *whitespace = "\r\n\t ";
3106 char *resolv_line = NULL;
3107 int resolv_linenum = 0;
3108 FILE *f = NULL;
3109 char *address = NULL;
3110 struct sockaddr_storage *sk = NULL;
3111 struct protocol *proto;
3112 int duplicate_name = 0;
3113
3114 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3115 ha_alert("parsing [%s:%d] : out of memory.\n",
3116 file, linenum);
3117 err_code |= ERR_ALERT | ERR_FATAL;
3118 goto resolv_out;
3119 }
3120
3121 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3122 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3123 file, linenum);
3124 err_code |= ERR_ALERT | ERR_FATAL;
3125 goto resolv_out;
3126 }
3127
3128 sk = calloc(1, sizeof(*sk));
3129 if (sk == NULL) {
3130 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3131 resolv_linenum);
3132 err_code |= ERR_ALERT | ERR_FATAL;
3133 goto resolv_out;
3134 }
3135
3136 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3137 resolv_linenum++;
3138 if (strncmp(resolv_line, "nameserver", 10) != 0)
3139 continue;
3140
3141 address = strtok(resolv_line + 10, whitespace);
3142 if (address == resolv_line + 10)
3143 continue;
3144
3145 if (address == NULL) {
3146 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3147 resolv_linenum);
3148 err_code |= ERR_WARN;
3149 continue;
3150 }
3151
3152 duplicate_name = 0;
3153 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3154 if (strcmp(newnameserver->id, address) == 0) {
3155 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",
3156 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3157 err_code |= ERR_WARN;
3158 duplicate_name = 1;
3159 }
3160 }
3161
3162 if (duplicate_name)
3163 continue;
3164
3165 memset(sk, 0, sizeof(*sk));
3166 if (!str2ip2(address, sk, 1)) {
3167 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3168 resolv_linenum, address);
3169 err_code |= ERR_WARN;
3170 continue;
3171 }
3172
3173 set_host_port(sk, 53);
3174
3175 proto = protocol_by_family(sk->ss_family);
3176 if (!proto || !proto->connect) {
3177 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3178 resolv_linenum, address);
3179 err_code |= ERR_WARN;
3180 continue;
3181 }
3182
3183 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3184 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3185 err_code |= ERR_ALERT | ERR_FATAL;
3186 goto resolv_out;
3187 }
3188
3189 if (dns_dgram_init(newnameserver, sk) < 0) {
3190 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3191 err_code |= ERR_ALERT | ERR_FATAL;
3192 free(newnameserver);
3193 goto resolv_out;
3194 }
3195
3196 newnameserver->conf.file = strdup("/etc/resolv.conf");
3197 if (newnameserver->conf.file == NULL) {
3198 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3199 err_code |= ERR_ALERT | ERR_FATAL;
3200 free(newnameserver);
3201 goto resolv_out;
3202 }
3203
3204 newnameserver->id = strdup(address);
3205 if (newnameserver->id == NULL) {
3206 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3207 err_code |= ERR_ALERT | ERR_FATAL;
3208 free((char *)newnameserver->conf.file);
3209 free(newnameserver);
3210 goto resolv_out;
3211 }
3212
3213 newnameserver->parent = curr_resolvers;
3214 newnameserver->process_responses = resolv_process_responses;
3215 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003216 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003217 }
3218
3219resolv_out:
3220 free(sk);
3221 free(resolv_line);
3222 if (f != NULL)
3223 fclose(f);
3224 }
3225 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3226 const char *res;
3227 unsigned int time;
3228
3229 if (!*args[2]) {
3230 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3231 file, linenum, args[0]);
3232 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3233 err_code |= ERR_ALERT | ERR_FATAL;
3234 goto out;
3235 }
3236 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3237 if (res == PARSE_TIME_OVER) {
3238 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3239 file, linenum, args[1], args[0]);
3240 err_code |= ERR_ALERT | ERR_FATAL;
3241 goto out;
3242 }
3243 else if (res == PARSE_TIME_UNDER) {
3244 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3245 file, linenum, args[1], args[0]);
3246 err_code |= ERR_ALERT | ERR_FATAL;
3247 goto out;
3248 }
3249 else if (res) {
3250 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3251 file, linenum, *res, args[0]);
3252 err_code |= ERR_ALERT | ERR_FATAL;
3253 goto out;
3254 }
3255 if (strcmp(args[1], "nx") == 0)
3256 curr_resolvers->hold.nx = time;
3257 else if (strcmp(args[1], "other") == 0)
3258 curr_resolvers->hold.other = time;
3259 else if (strcmp(args[1], "refused") == 0)
3260 curr_resolvers->hold.refused = time;
3261 else if (strcmp(args[1], "timeout") == 0)
3262 curr_resolvers->hold.timeout = time;
3263 else if (strcmp(args[1], "valid") == 0)
3264 curr_resolvers->hold.valid = time;
3265 else if (strcmp(args[1], "obsolete") == 0)
3266 curr_resolvers->hold.obsolete = time;
3267 else {
3268 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3269 file, linenum, args[0], args[1]);
3270 err_code |= ERR_ALERT | ERR_FATAL;
3271 goto out;
3272 }
3273
3274 }
3275 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3276 int i = 0;
3277
3278 if (!*args[1]) {
3279 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3280 file, linenum, args[0]);
3281 err_code |= ERR_ALERT | ERR_FATAL;
3282 goto out;
3283 }
3284
3285 i = atoi(args[1]);
3286 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3287 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3288 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3289 err_code |= ERR_ALERT | ERR_FATAL;
3290 goto out;
3291 }
3292
3293 curr_resolvers->accepted_payload_size = i;
3294 }
3295 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3296 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3297 file, linenum, args[0]);
3298 err_code |= ERR_ALERT | ERR_FATAL;
3299 goto out;
3300 }
3301 else if (strcmp(args[0], "resolve_retries") == 0) {
3302 if (!*args[1]) {
3303 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3304 file, linenum, args[0]);
3305 err_code |= ERR_ALERT | ERR_FATAL;
3306 goto out;
3307 }
3308 curr_resolvers->resolve_retries = atoi(args[1]);
3309 }
3310 else if (strcmp(args[0], "timeout") == 0) {
3311 if (!*args[1]) {
3312 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3313 file, linenum, args[0]);
3314 err_code |= ERR_ALERT | ERR_FATAL;
3315 goto out;
3316 }
3317 else if (strcmp(args[1], "retry") == 0 ||
3318 strcmp(args[1], "resolve") == 0) {
3319 const char *res;
3320 unsigned int tout;
3321
3322 if (!*args[2]) {
3323 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3324 file, linenum, args[0], args[1]);
3325 err_code |= ERR_ALERT | ERR_FATAL;
3326 goto out;
3327 }
3328 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3329 if (res == PARSE_TIME_OVER) {
3330 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3331 file, linenum, args[2], args[0], args[1]);
3332 err_code |= ERR_ALERT | ERR_FATAL;
3333 goto out;
3334 }
3335 else if (res == PARSE_TIME_UNDER) {
3336 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3337 file, linenum, args[2], args[0], args[1]);
3338 err_code |= ERR_ALERT | ERR_FATAL;
3339 goto out;
3340 }
3341 else if (res) {
3342 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3343 file, linenum, *res, args[0], args[1]);
3344 err_code |= ERR_ALERT | ERR_FATAL;
3345 goto out;
3346 }
3347 if (args[1][2] == 't')
3348 curr_resolvers->timeout.retry = tout;
3349 else
3350 curr_resolvers->timeout.resolve = tout;
3351 }
3352 else {
3353 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3354 file, linenum, args[0], args[1]);
3355 err_code |= ERR_ALERT | ERR_FATAL;
3356 goto out;
3357 }
3358 }
3359 else if (*args[0] != 0) {
3360 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3361 err_code |= ERR_ALERT | ERR_FATAL;
3362 goto out;
3363 }
3364
3365 out:
3366 free(errmsg);
3367 return err_code;
3368}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003369int cfg_post_parse_resolvers()
3370{
3371 int err_code = 0;
3372 struct server *srv;
3373
3374 if (curr_resolvers) {
3375
3376 /* prepare forward server descriptors */
3377 if (curr_resolvers->px) {
3378 srv = curr_resolvers->px->srv;
3379 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003380 /* init ssl if needed */
3381 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3382 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3383 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3384 err_code |= ERR_ALERT | ERR_FATAL;
3385 break;
3386 }
3387 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003388 srv = srv->next;
3389 }
3390 }
3391 }
3392 curr_resolvers = NULL;
3393 return err_code;
3394}
Emeric Brunc9437992021-02-12 19:42:55 +01003395
Emeric Brun56fc5d92021-02-12 20:05:45 +01003396REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003397REGISTER_POST_DEINIT(resolvers_deinit);
3398REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);