blob: 70459edc0cea84c2e1b38dfda6e4adf598e22522 [file] [log] [blame]
Emeric Brunc9437992021-02-12 19:42:55 +01001/*
2 * Name server resolution
3 *
4 * Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#include <errno.h>
14#include <fcntl.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19
20#include <sys/types.h>
21
Emeric Brun0c4a8a32021-06-11 10:48:45 +020022#include <import/ebistree.h>
23
Emeric Brunc9437992021-02-12 19:42:55 +010024#include <haproxy/action.h>
25#include <haproxy/api.h>
26#include <haproxy/cfgparse.h>
27#include <haproxy/channel.h>
28#include <haproxy/check.h>
29#include <haproxy/cli.h>
30#include <haproxy/dns.h>
31#include <haproxy/errors.h>
32#include <haproxy/fd.h>
Emeric Brunc9437992021-02-12 19:42:55 +010033#include <haproxy/http_rules.h>
34#include <haproxy/log.h>
35#include <haproxy/net_helper.h>
36#include <haproxy/protocol.h>
37#include <haproxy/proxy.h>
38#include <haproxy/resolvers.h>
39#include <haproxy/ring.h>
40#include <haproxy/sample.h>
41#include <haproxy/server.h>
42#include <haproxy/stats.h>
43#include <haproxy/stream_interface.h>
44#include <haproxy/task.h>
45#include <haproxy/tcp_rules.h>
46#include <haproxy/ticks.h>
47#include <haproxy/time.h>
Willy Tarreauca14dd52021-05-08 12:59:47 +020048#include <haproxy/tools.h>
Emeric Brunc9437992021-02-12 19:42:55 +010049#include <haproxy/vars.h>
50
51
52struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
53struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
54
55static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
56struct resolvers *curr_resolvers = NULL;
57
58DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
59DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
60DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
61
62static unsigned int resolution_uuid = 1;
63unsigned int resolv_failed_resolutions = 0;
64
65enum {
66 DNS_STAT_ID,
67 DNS_STAT_PID,
68 DNS_STAT_SENT,
69 DNS_STAT_SND_ERROR,
70 DNS_STAT_VALID,
71 DNS_STAT_UPDATE,
72 DNS_STAT_CNAME,
73 DNS_STAT_CNAME_ERROR,
74 DNS_STAT_ANY_ERR,
75 DNS_STAT_NX,
76 DNS_STAT_TIMEOUT,
77 DNS_STAT_REFUSED,
78 DNS_STAT_OTHER,
79 DNS_STAT_INVALID,
80 DNS_STAT_TOO_BIG,
81 DNS_STAT_TRUNCATED,
82 DNS_STAT_OUTDATED,
83 DNS_STAT_END,
84};
85
86static struct name_desc dns_stats[] = {
87 [DNS_STAT_ID] = { .name = "id", .desc = "ID" },
88 [DNS_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
89 [DNS_STAT_SENT] = { .name = "sent", .desc = "Sent" },
90 [DNS_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
91 [DNS_STAT_VALID] = { .name = "valid", .desc = "Valid" },
92 [DNS_STAT_UPDATE] = { .name = "update", .desc = "Update" },
93 [DNS_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
94 [DNS_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
95 [DNS_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
96 [DNS_STAT_NX] = { .name = "nx", .desc = "NX" },
97 [DNS_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
98 [DNS_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
99 [DNS_STAT_OTHER] = { .name = "other", .desc = "Other" },
100 [DNS_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
101 [DNS_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
102 [DNS_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
103 [DNS_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
104};
105
106static struct dns_counters dns_counters;
107
108static void dns_fill_stats(void *d, struct field *stats)
109{
110 struct dns_counters *counters = d;
111 stats[DNS_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
112 stats[DNS_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
113 stats[DNS_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
114 stats[DNS_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
115 stats[DNS_STAT_VALID] = mkf_u64(FN_GAUGE, counters->valid);
116 stats[DNS_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->update);
117 stats[DNS_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->cname);
118 stats[DNS_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->cname_error);
119 stats[DNS_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->any_err);
120 stats[DNS_STAT_NX] = mkf_u64(FN_GAUGE, counters->nx);
121 stats[DNS_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->timeout);
122 stats[DNS_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->refused);
123 stats[DNS_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->other);
124 stats[DNS_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->invalid);
125 stats[DNS_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->too_big);
126 stats[DNS_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->truncated);
127 stats[DNS_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->outdated);
128}
129
130static struct stats_module dns_stats_module = {
131 .name = "dns",
132 .domain_flags = STATS_DOMAIN_DNS << STATS_DOMAIN,
133 .fill_stats = dns_fill_stats,
134 .stats = dns_stats,
135 .stats_count = DNS_STAT_END,
136 .counters = &dns_counters,
137 .counters_size = sizeof(dns_counters),
138 .clearable = 0,
139};
140
141INITCALL1(STG_REGISTER, stats_register_module, &dns_stats_module);
142
143/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
144 * no match is found.
145 */
146struct resolvers *find_resolvers_by_id(const char *id)
147{
148 struct resolvers *res;
149
150 list_for_each_entry(res, &sec_resolvers, list) {
151 if (strcmp(res->id, id) == 0)
152 return res;
153 }
154 return NULL;
155}
156
157/* Compare hostnames in a case-insensitive way .
158 * Returns 0 if they are the same, non-zero otherwise
159 */
160static __inline int resolv_hostname_cmp(const char *name1, const char *name2, int len)
161{
162 int i;
163
164 for (i = 0; i < len; i++)
165 if (tolower((unsigned char)name1[i]) != tolower((unsigned char)name2[i]))
166 return -1;
167 return 0;
168}
169
170/* Returns a pointer on the SRV request matching the name <name> for the proxy
171 * <px>. NULL is returned if no match is found.
172 */
173struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
174{
175 struct resolv_srvrq *srvrq;
176
177 list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
178 if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
179 return srvrq;
180 }
181 return NULL;
182}
183
184/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
185 * NULL if an error occurred. */
186struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
187{
188 struct proxy *px = srv->proxy;
189 struct resolv_srvrq *srvrq = NULL;
190 int fqdn_len, hostname_dn_len;
191
192 fqdn_len = strlen(fqdn);
Willy Tarreauc1c765f2021-10-14 07:49:49 +0200193 hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
Emeric Brunc9437992021-02-12 19:42:55 +0100194 trash.size);
195 if (hostname_dn_len == -1) {
196 ha_alert("config : %s '%s', server '%s': failed to parse FQDN '%s'\n",
197 proxy_type_str(px), px->id, srv->id, fqdn);
198 goto err;
199 }
200
201 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
202 ha_alert("config : %s '%s', server '%s': out of memory\n",
203 proxy_type_str(px), px->id, srv->id);
204 goto err;
205 }
206 srvrq->obj_type = OBJ_TYPE_SRVRQ;
207 srvrq->proxy = px;
208 srvrq->name = strdup(fqdn);
209 srvrq->hostname_dn = strdup(trash.area);
210 srvrq->hostname_dn_len = hostname_dn_len;
211 if (!srvrq->name || !srvrq->hostname_dn) {
212 ha_alert("config : %s '%s', server '%s': out of memory\n",
213 proxy_type_str(px), px->id, srv->id);
214 goto err;
215 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200216 LIST_INIT(&srvrq->attached_servers);
217 srvrq->named_servers = EB_ROOT;
Willy Tarreau2b718102021-04-21 07:32:39 +0200218 LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100219 return srvrq;
220
221 err:
222 if (srvrq) {
223 free(srvrq->name);
224 free(srvrq->hostname_dn);
225 free(srvrq);
226 }
227 return NULL;
228}
229
230
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100231/* finds and return the SRV answer item associated to a requester (whose type is 'server').
232 *
233 * returns NULL in case of error or not found.
234 */
235struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
236{
237 struct resolv_resolution *res;
238 struct resolv_answer_item *item;
239 struct server *srv;
240
241 if (!requester)
242 return NULL;
243
244 if ((srv = objt_server(requester->owner)) == NULL)
245 return NULL;
246 /* check if the server is managed by a SRV record */
247 if (srv->srvrq == NULL)
248 return NULL;
249
250 res = srv->srvrq->requester->resolution;
251 /* search an ANSWER record whose target points to the server's hostname and whose port is
252 * the same as server's svc_port */
253 list_for_each_entry(item, &res->response.answer_list, list) {
Willy Tarreau20a02372021-10-14 22:52:04 +0200254 if (resolv_hostname_cmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
Baptiste Assmann6a8d11d2021-03-10 12:22:18 +0100255 (srv->svc_port == item->port))
256 return item;
257 }
258
259 return NULL;
260}
261
Emeric Brunc9437992021-02-12 19:42:55 +0100262/* 2 bytes random generator to generate DNS query ID */
263static inline uint16_t resolv_rnd16(void)
264{
265 if (!resolv_query_id_seed)
266 resolv_query_id_seed = now_ms;
267 resolv_query_id_seed ^= resolv_query_id_seed << 13;
268 resolv_query_id_seed ^= resolv_query_id_seed >> 7;
269 resolv_query_id_seed ^= resolv_query_id_seed << 17;
270 return resolv_query_id_seed;
271}
272
273
274static inline int resolv_resolution_timeout(struct resolv_resolution *res)
275{
276 return res->resolvers->timeout.resolve;
277}
278
279/* Updates a resolvers' task timeout for next wake up and queue it */
280static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
281{
282 struct resolv_resolution *res;
283 int next;
284
285 next = tick_add(now_ms, resolvers->timeout.resolve);
286 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
287 res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
288 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
289 }
290
291 list_for_each_entry(res, &resolvers->resolutions.wait, list)
292 next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
293
294 resolvers->t->expire = next;
295 task_queue(resolvers->t);
296}
297
298/* Forges a DNS query. It needs the following information from the caller:
299 * - <query_id> : the DNS query id corresponding to this query
300 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
301 * - <hostname_dn> : hostname in domain name format
302 * - <hostname_dn_len> : length of <hostname_dn>
303 *
304 * To store the query, the caller must pass a buffer <buf> and its size
305 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
306 * too short.
307 */
308static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
309 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
310{
311 struct dns_header dns_hdr;
312 struct dns_question qinfo;
313 struct dns_additional_record edns;
314 char *p = buf;
315
316 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
317 return -1;
318
319 memset(buf, 0, bufsize);
320
321 /* Set dns query headers */
322 dns_hdr.id = (unsigned short) htons(query_id);
323 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
324 dns_hdr.qdcount = htons(1); /* 1 question */
325 dns_hdr.ancount = 0;
326 dns_hdr.nscount = 0;
327 dns_hdr.arcount = htons(1);
328 memcpy(p, &dns_hdr, sizeof(dns_hdr));
329 p += sizeof(dns_hdr);
330
331 /* Set up query hostname */
332 memcpy(p, hostname_dn, hostname_dn_len);
333 p += hostname_dn_len;
334 *p++ = 0;
335
336 /* Set up query info (type and class) */
337 qinfo.qtype = htons(query_type);
338 qinfo.qclass = htons(DNS_RCLASS_IN);
339 memcpy(p, &qinfo, sizeof(qinfo));
340 p += sizeof(qinfo);
341
342 /* Set the DNS extension */
343 edns.name = 0;
344 edns.type = htons(DNS_RTYPE_OPT);
345 edns.udp_payload_size = htons(accepted_payload_size);
346 edns.extension = 0;
347 edns.data_length = 0;
348 memcpy(p, &edns, sizeof(edns));
349 p += sizeof(edns);
350
351 return (p - buf);
352}
353
354/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
355 * success, -1 otherwise.
356 */
357static int resolv_send_query(struct resolv_resolution *resolution)
358{
359 struct resolvers *resolvers = resolution->resolvers;
360 struct dns_nameserver *ns;
361 int len;
362
363 /* Update resolution */
364 resolution->nb_queries = 0;
365 resolution->nb_responses = 0;
366 resolution->last_query = now_ms;
367
368 len = resolv_build_query(resolution->query_id, resolution->query_type,
369 resolvers->accepted_payload_size,
370 resolution->hostname_dn, resolution->hostname_dn_len,
371 trash.area, trash.size);
372
373 list_for_each_entry(ns, &resolvers->nameservers, list) {
374 if (len < 0) {
375 ns->counters->snd_error++;
376 continue;
377 }
378
379 if (dns_send_nameserver(ns, trash.area, len) < 0)
380 ns->counters->snd_error++;
381 else
382 resolution->nb_queries++;
383 }
384
385 /* Push the resolution at the end of the active list */
Willy Tarreau2b718102021-04-21 07:32:39 +0200386 LIST_DELETE(&resolution->list);
387 LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100388 return 0;
389}
390
391/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
392 * skipped and -1 if an error occurred.
393 */
394static int
395resolv_run_resolution(struct resolv_resolution *resolution)
396{
397 struct resolvers *resolvers = resolution->resolvers;
398 int query_id, i;
399
400 /* Avoid sending requests for resolutions that don't yet have an
401 * hostname, ie resolutions linked to servers that do not yet have an
402 * fqdn */
403 if (!resolution->hostname_dn)
404 return 0;
405
406 /* Check if a resolution has already been started for this server return
407 * directly to avoid resolution pill up. */
408 if (resolution->step != RSLV_STEP_NONE)
409 return 0;
410
411 /* Generates a new query id. We try at most 100 times to find a free
412 * query id */
413 for (i = 0; i < 100; ++i) {
414 query_id = resolv_rnd16();
415 if (!eb32_lookup(&resolvers->query_ids, query_id))
416 break;
417 query_id = -1;
418 }
419 if (query_id == -1) {
420 send_log(NULL, LOG_NOTICE,
421 "could not generate a query id for %s, in resolvers %s.\n",
422 resolution->hostname_dn, resolvers->id);
423 return -1;
424 }
425
426 /* Update resolution parameters */
427 resolution->query_id = query_id;
428 resolution->qid.key = query_id;
429 resolution->step = RSLV_STEP_RUNNING;
430 resolution->query_type = resolution->prefered_query_type;
431 resolution->try = resolvers->resolve_retries;
432 eb32_insert(&resolvers->query_ids, &resolution->qid);
433
434 /* Send the DNS query */
435 resolution->try -= 1;
436 resolv_send_query(resolution);
437 return 1;
438}
439
440/* Performs a name resolution for the requester <req> */
441void resolv_trigger_resolution(struct resolv_requester *req)
442{
443 struct resolvers *resolvers;
444 struct resolv_resolution *res;
445 int exp;
446
447 if (!req || !req->resolution)
448 return;
449 res = req->resolution;
450 resolvers = res->resolvers;
451
452 /* The resolution must not be triggered yet. Use the cached response, if
453 * valid */
454 exp = tick_add(res->last_resolution, resolvers->hold.valid);
455 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
456 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
457 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
458}
459
460
461/* Resets some resolution parameters to initial values and also delete the query
462 * ID from the resolver's tree.
463 */
464static void resolv_reset_resolution(struct resolv_resolution *resolution)
465{
466 /* update resolution status */
467 resolution->step = RSLV_STEP_NONE;
468 resolution->try = 0;
469 resolution->last_resolution = now_ms;
470 resolution->nb_queries = 0;
471 resolution->nb_responses = 0;
472 resolution->query_type = resolution->prefered_query_type;
473
474 /* clean up query id */
475 eb32_delete(&resolution->qid);
476 resolution->query_id = 0;
477 resolution->qid.key = 0;
478}
479
480/* Returns the query id contained in a DNS response */
481static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
482{
483 return resp[0] * 256 + resp[1];
484}
485
486
487/* Analyses, re-builds and copies the name <name> from the DNS response packet
488 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
489 * for compressed data. The result is copied into <dest>, ensuring we don't
490 * overflow using <dest_len> Returns the number of bytes the caller can move
491 * forward. If 0 it means an error occurred while parsing the name. <offset> is
492 * the number of bytes the caller could move forward.
493 */
494int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
495 unsigned char *name, char *destination, int dest_len,
496 int *offset, unsigned int depth)
497{
498 int nb_bytes = 0, n = 0;
499 int label_len;
500 unsigned char *reader = name;
501 char *dest = destination;
502
503 while (1) {
504 if (reader >= bufend)
505 goto err;
506
507 /* Name compression is in use */
508 if ((*reader & 0xc0) == 0xc0) {
509 if (reader + 1 >= bufend)
510 goto err;
511
512 /* Must point BEFORE current position */
513 if ((buffer + reader[1]) > reader)
514 goto err;
515
516 if (depth++ > 100)
517 goto err;
518
519 n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
520 dest, dest_len - nb_bytes, offset, depth);
521 if (n == 0)
522 goto err;
523
524 dest += n;
525 nb_bytes += n;
526 goto out;
527 }
528
529 label_len = *reader;
530 if (label_len == 0)
531 goto out;
532
533 /* Check if:
534 * - we won't read outside the buffer
535 * - there is enough place in the destination
536 */
537 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
538 goto err;
539
540 /* +1 to take label len + label string */
541 label_len++;
542
543 memcpy(dest, reader, label_len);
544
545 dest += label_len;
546 nb_bytes += label_len;
547 reader += label_len;
548 }
549
550 out:
551 /* offset computation:
552 * parse from <name> until finding either NULL or a pointer "c0xx"
553 */
554 reader = name;
555 *offset = 0;
556 while (reader < bufend) {
557 if ((reader[0] & 0xc0) == 0xc0) {
558 *offset += 2;
559 break;
560 }
561 else if (*reader == 0) {
562 *offset += 1;
563 break;
564 }
565 *offset += 1;
566 ++reader;
567 }
568 return nb_bytes;
569
570 err:
571 return 0;
572}
573
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200574/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
575 * happens when an SRV item is purged or when the server status is considered as
576 * obsolete.
577 *
578 * Must be called with the DNS lock held.
579 */
Willy Tarreau3223d852021-10-18 16:49:14 +0200580static void resolv_srvrq_cleanup_srv(struct server *srv, int safe)
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200581{
Willy Tarreau3223d852021-10-18 16:49:14 +0200582 resolv_unlink_resolution(srv->resolv_requester, safe);
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200583 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
584 srvrq_update_srv_status(srv, 1);
585 ha_free(&srv->hostname);
586 ha_free(&srv->hostname_dn);
587 srv->hostname_dn_len = 0;
588 memset(&srv->addr, 0, sizeof(srv->addr));
589 srv->svc_port = 0;
590 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Fauleta62d9742021-06-15 16:14:37 +0200591
592 ebpt_delete(&srv->host_dn);
593 ha_free(&srv->host_dn.key);
594
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200595 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
596 LIST_DELETE(&srv->srv_rec_item);
597 LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200598
599 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200600}
601
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200602/* Takes care to cleanup a server resolution when it is outdated. This only
603 * happens for a server relying on a SRV record.
604 */
605static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
606{
607 struct server *srv = context;
608
609 if (!tick_is_expired(t->expire, now_ms))
610 goto end;
611
Christopher Faulet152b50c2021-06-18 09:05:49 +0200612 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Willy Tarreau3223d852021-10-18 16:49:14 +0200613 resolv_srvrq_cleanup_srv(srv, 0);
Christopher Faulet152b50c2021-06-18 09:05:49 +0200614 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200615
616 end:
617 return t;
618}
619
Emeric Brunc9437992021-02-12 19:42:55 +0100620/* Checks for any obsolete record, also identify any SRV request, and try to
621 * find a corresponding server.
622*/
623static void resolv_check_response(struct resolv_resolution *res)
624{
625 struct resolvers *resolvers = res->resolvers;
Christopher Fauletdb31b442021-03-11 18:19:41 +0100626 struct resolv_requester *req;
Emeric Brunc9437992021-02-12 19:42:55 +0100627 struct resolv_answer_item *item, *itemback;
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200628 struct server *srv, *srvback;
Emeric Brunc9437992021-02-12 19:42:55 +0100629 struct resolv_srvrq *srvrq;
630
631 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
632 struct resolv_answer_item *ar_item = item->ar_item;
633
634 /* clean up obsolete Additional record */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100635 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100636 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
637 * item is also obsolete.
638 */
Emeric Brunc9437992021-02-12 19:42:55 +0100639 pool_free(resolv_answer_item_pool, ar_item);
640 item->ar_item = NULL;
641 }
642
643 /* Remove obsolete items */
Christopher Faulet55c1c402021-03-11 09:36:05 +0100644 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200645 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Emeric Brunc9437992021-02-12 19:42:55 +0100646 /* Remove any associated server */
Emeric Brunf9ca5d82021-06-11 10:08:05 +0200647 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
648 LIST_DEL_INIT(&srv->ip_rec_item);
649 }
650 }
651 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200652 /* Remove any associated server */
Christopher Faulet5f8ccff2021-06-15 16:08:48 +0200653 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
Willy Tarreau3223d852021-10-18 16:49:14 +0200654 resolv_srvrq_cleanup_srv(srv, 0);
Emeric Brunc9437992021-02-12 19:42:55 +0100655 }
656
Willy Tarreau2b718102021-04-21 07:32:39 +0200657 LIST_DELETE(&item->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100658 if (item->ar_item) {
659 pool_free(resolv_answer_item_pool, item->ar_item);
660 item->ar_item = NULL;
661 }
662 pool_free(resolv_answer_item_pool, item);
663 continue;
664 }
665
666 if (item->type != DNS_RTYPE_SRV)
667 continue;
668
669 /* Now process SRV records */
Christopher Fauletdb31b442021-03-11 18:19:41 +0100670 list_for_each_entry(req, &res->requesters, list) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200671 struct ebpt_node *node;
672 char target[DNS_MAX_NAME_SIZE+1];
673
674 int i;
Emeric Brunc9437992021-02-12 19:42:55 +0100675 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
676 continue;
677
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200678 /* Check if a server already uses that record */
679 srv = NULL;
680 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
681 if (srv->srvrq == srvrq) {
682 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
683 goto srv_found;
Emeric Brunc9437992021-02-12 19:42:55 +0100684 }
Emeric Brunc9437992021-02-12 19:42:55 +0100685 }
686
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200687
688 /* If not empty we try to match a server
689 * in server state file tree with the same hostname
690 */
691 if (!eb_is_empty(&srvrq->named_servers)) {
692 srv = NULL;
693
694 /* convert the key to lookup in lower case */
Willy Tarreau20a02372021-10-14 22:52:04 +0200695 for (i = 0 ; item->data.target[i] ; i++)
696 target[i] = tolower(item->data.target[i]);
Christopher Fauletc20d6422021-07-22 14:29:26 +0200697 target[i] = 0;
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200698
699 node = ebis_lookup(&srvrq->named_servers, target);
700 if (node) {
701 srv = ebpt_entry(node, struct server, host_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100702 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200703
704 /* an entry was found with the same hostname
705 * let check this node if the port matches
706 * and try next node if the hostname
707 * is still the same
708 */
709 while (1) {
710 if (srv->svc_port == item->port) {
711 /* server found, we remove it from tree */
712 ebpt_delete(node);
Christopher Fauleta62d9742021-06-15 16:14:37 +0200713 ha_free(&srv->host_dn.key);
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200714 goto srv_found;
715 }
716
717 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
718
719 node = ebpt_next(node);
720 if (!node)
721 break;
722
723 srv = ebpt_entry(node, struct server, host_dn);
724 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
725
726 if ((item->data_len != srv->hostname_dn_len)
Willy Tarreau20a02372021-10-14 22:52:04 +0200727 || resolv_hostname_cmp(srv->hostname_dn, item->data.target, item->data_len)) {
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200728 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
729 break;
730 }
731 }
Emeric Brunc9437992021-02-12 19:42:55 +0100732 }
733 }
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200734
735 /* Pick the first server listed in srvrq (those ones don't
736 * have hostname and are free to use)
737 */
738 srv = NULL;
739 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
740 LIST_DEL_INIT(&srv->srv_rec_item);
741 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
742 goto srv_found;
743 }
744 srv = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +0100745
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200746srv_found:
Emeric Brunc9437992021-02-12 19:42:55 +0100747 /* And update this server, if found (srv is locked here) */
748 if (srv) {
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100749 /* re-enable DNS resolution for this server by default */
750 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Faulet2c0f5272021-06-15 16:17:17 +0200751 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100752
Emeric Brunc9437992021-02-12 19:42:55 +0100753 /* Check if an Additional Record is associated to this SRV record.
754 * Perform some sanity checks too to ensure the record can be used.
755 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100756 * it to the server. And DNS resolution is disabled for this server.
Emeric Brunc9437992021-02-12 19:42:55 +0100757 */
758 if ((item->ar_item != NULL) &&
759 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100760 {
Emeric Brunc9437992021-02-12 19:42:55 +0100761
762 switch (item->ar_item->type) {
763 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +0200764 srv_update_addr(srv, &item->ar_item->data.in4.sin_addr, AF_INET, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100765 break;
766 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +0200767 srv_update_addr(srv, &item->ar_item->data.in6.sin6_addr, AF_INET6, "DNS additional record");
Emeric Brunc9437992021-02-12 19:42:55 +0100768 break;
769 }
770
771 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100772
773 /* Unlink A/AAAA resolution for this server if there is an AR item.
774 * It is usless to perform an extra resolution
775 */
Christopher Faulet0efc0992021-03-11 18:09:53 +0100776 resolv_unlink_resolution(srv->resolv_requester, 0);
Emeric Brunc9437992021-02-12 19:42:55 +0100777 }
778
779 if (!srv->hostname_dn) {
780 const char *msg = NULL;
Willy Tarreau2859c162021-10-14 08:00:38 +0200781 char hostname[DNS_MAX_NAME_SIZE+1];
Emeric Brunc9437992021-02-12 19:42:55 +0100782
Willy Tarreau20a02372021-10-14 22:52:04 +0200783 if (resolv_dn_label_to_str(item->data.target, item->data_len,
Willy Tarreau2859c162021-10-14 08:00:38 +0200784 hostname, sizeof(hostname)) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +0100785 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
786 continue;
787 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100788 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100789 if (msg)
790 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
791 }
792
Emeric Brun0c4a8a32021-06-11 10:48:45 +0200793 if (!LIST_INLIST(&srv->srv_rec_item))
794 LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
795
Christopher Faulet3e0600f2021-03-10 18:38:37 +0100796 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
797 /* If there is no AR item responsible of the FQDN resolution,
798 * trigger a dedicated DNS resolution
799 */
800 if (!srv->resolv_requester || !srv->resolv_requester->resolution)
801 resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
802 }
803
Christopher Fauletab177ac2021-03-10 15:34:52 +0100804 /* Update the server status */
Christopher Faulet6b117ae2021-03-11 18:06:23 +0100805 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100806
807 srv->svc_port = item->port;
808 srv->flags &= ~SRV_F_MAPPORTS;
809
810 if (!srv->resolv_opts.ignore_weight) {
811 char weight[9];
812 int ha_weight;
813
814 /* DNS weight range if from 0 to 65535
815 * HAProxy weight is from 0 to 256
816 * The rule below ensures that weight 0 is well respected
817 * while allowing a "mapping" from DNS weight into HAProxy's one.
818 */
819 ha_weight = (item->weight + 255) / 256;
820
821 snprintf(weight, sizeof(weight), "%d", ha_weight);
822 server_parse_weight_change_request(srv, weight);
823 }
824 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
825 }
826 }
827 }
828}
829
830/* Validates that the buffer DNS response provided in <resp> and finishing
831 * before <bufend> is valid from a DNS protocol point of view.
832 *
833 * The result is stored in <resolution>' response, buf_response,
834 * response_query_records and response_answer_records members.
835 *
836 * This function returns one of the RSLV_RESP_* code to indicate the type of
837 * error found.
838 */
839static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
840 struct resolv_resolution *resolution, int max_answer_records)
841{
842 unsigned char *reader;
843 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
844 int len, flags, offset;
845 int query_record_id;
846 int nb_saved_records;
847 struct resolv_query_item *query;
848 struct resolv_answer_item *answer_record, *tmp_record;
849 struct resolv_response *r_res;
850 int i, found = 0;
851 int cause = RSLV_RESP_ERROR;
852
853 reader = resp;
854 len = 0;
855 previous_dname = NULL;
856 query = NULL;
857 answer_record = NULL;
858
859 /* Initialization of response buffer and structure */
860 r_res = &resolution->response;
861
862 /* query id */
863 if (reader + 2 >= bufend)
864 goto invalid_resp;
865
866 r_res->header.id = reader[0] * 256 + reader[1];
867 reader += 2;
868
869 /* Flags and rcode are stored over 2 bytes
870 * First byte contains:
871 * - response flag (1 bit)
872 * - opcode (4 bits)
873 * - authoritative (1 bit)
874 * - truncated (1 bit)
875 * - recursion desired (1 bit)
876 */
877 if (reader + 2 >= bufend)
878 goto invalid_resp;
879
880 flags = reader[0] * 256 + reader[1];
881
882 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
883 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
884 cause = RSLV_RESP_NX_DOMAIN;
885 goto return_error;
886 }
887 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
888 cause = RSLV_RESP_REFUSED;
889 goto return_error;
890 }
891 else {
892 cause = RSLV_RESP_ERROR;
893 goto return_error;
894 }
895 }
896
897 /* Move forward 2 bytes for flags */
898 reader += 2;
899
900 /* 2 bytes for question count */
901 if (reader + 2 >= bufend)
902 goto invalid_resp;
903 r_res->header.qdcount = reader[0] * 256 + reader[1];
904 /* (for now) we send one query only, so we expect only one in the
905 * response too */
906 if (r_res->header.qdcount != 1) {
907 cause = RSLV_RESP_QUERY_COUNT_ERROR;
908 goto return_error;
909 }
910
911 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
912 goto invalid_resp;
913 reader += 2;
914
915 /* 2 bytes for answer count */
916 if (reader + 2 >= bufend)
917 goto invalid_resp;
918 r_res->header.ancount = reader[0] * 256 + reader[1];
919 if (r_res->header.ancount == 0) {
920 cause = RSLV_RESP_ANCOUNT_ZERO;
921 goto return_error;
922 }
923
924 /* Check if too many records are announced */
925 if (r_res->header.ancount > max_answer_records)
926 goto invalid_resp;
927 reader += 2;
928
929 /* 2 bytes authority count */
930 if (reader + 2 >= bufend)
931 goto invalid_resp;
932 r_res->header.nscount = reader[0] * 256 + reader[1];
933 reader += 2;
934
935 /* 2 bytes additional count */
936 if (reader + 2 >= bufend)
937 goto invalid_resp;
938 r_res->header.arcount = reader[0] * 256 + reader[1];
939 reader += 2;
940
941 /* Parsing dns queries */
Willy Tarreau51128f82021-10-19 11:17:33 +0200942 BUG_ON(!LIST_ISEMPTY(&r_res->query_list));
Emeric Brunc9437992021-02-12 19:42:55 +0100943 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
944 /* Use next pre-allocated resolv_query_item after ensuring there is
945 * still one available.
946 * It's then added to our packet query list. */
947 if (query_record_id > DNS_MAX_QUERY_RECORDS)
948 goto invalid_resp;
949 query = &resolution->response_query_records[query_record_id];
Willy Tarreau2b718102021-04-21 07:32:39 +0200950 LIST_APPEND(&r_res->query_list, &query->list);
Emeric Brunc9437992021-02-12 19:42:55 +0100951
952 /* Name is a NULL terminated string in our case, since we have
953 * one query per response and the first one can't be compressed
954 * (using the 0x0c format) */
955 offset = 0;
956 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
957
958 if (len == 0)
959 goto invalid_resp;
960
961 reader += offset;
962 previous_dname = query->name;
963
964 /* move forward 2 bytes for question type */
965 if (reader + 2 >= bufend)
966 goto invalid_resp;
967 query->type = reader[0] * 256 + reader[1];
968 reader += 2;
969
970 /* move forward 2 bytes for question class */
971 if (reader + 2 >= bufend)
972 goto invalid_resp;
973 query->class = reader[0] * 256 + reader[1];
974 reader += 2;
975 }
976
Willy Tarreau3a8897f2021-10-20 17:29:28 +0200977 /* Let's just make gcc happy. The tests above make it clear that
978 * qdcount==1 hence that we necessarily enter into the loop at least
979 * once, but gcc seems to be having difficulties following it and
980 * warns about the risk of NULL dereference at the next line, even
981 * if a BUG_ON(!query) is used.
982 */
983 ALREADY_CHECKED(query);
984
Emeric Brunc9437992021-02-12 19:42:55 +0100985 /* TRUNCATED flag must be checked after we could read the query type
Willy Tarreau3a8897f2021-10-20 17:29:28 +0200986 * because a TRUNCATED SRV query type response can still be exploited
987 */
Emeric Brunc9437992021-02-12 19:42:55 +0100988 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
989 cause = RSLV_RESP_TRUNCATED;
990 goto return_error;
991 }
992
993 /* now parsing response records */
994 nb_saved_records = 0;
995 for (i = 0; i < r_res->header.ancount; i++) {
996 if (reader >= bufend)
997 goto invalid_resp;
998
999 answer_record = pool_alloc(resolv_answer_item_pool);
1000 if (answer_record == NULL)
1001 goto invalid_resp;
1002
1003 /* initialization */
1004 answer_record->ar_item = NULL;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001005 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001006 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001007
1008 offset = 0;
1009 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1010
1011 if (len == 0)
1012 goto invalid_resp;
1013
1014 /* Check if the current record dname is valid. previous_dname
1015 * points either to queried dname or last CNAME target */
1016 if (query->type != DNS_RTYPE_SRV && resolv_hostname_cmp(previous_dname, tmpname, len) != 0) {
1017 if (i == 0) {
1018 /* First record, means a mismatch issue between
1019 * queried dname and dname found in the first
1020 * record */
1021 goto invalid_resp;
1022 }
1023 else {
1024 /* If not the first record, this means we have a
1025 * CNAME resolution error.
1026 */
1027 cause = RSLV_RESP_CNAME_ERROR;
1028 goto return_error;
1029 }
1030
1031 }
1032
1033 memcpy(answer_record->name, tmpname, len);
1034 answer_record->name[len] = 0;
1035
1036 reader += offset;
1037 if (reader >= bufend)
1038 goto invalid_resp;
1039
1040 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1041 if (reader + 2 > bufend)
1042 goto invalid_resp;
1043
1044 answer_record->type = reader[0] * 256 + reader[1];
1045 reader += 2;
1046
1047 /* 2 bytes for class (2) */
1048 if (reader + 2 > bufend)
1049 goto invalid_resp;
1050
1051 answer_record->class = reader[0] * 256 + reader[1];
1052 reader += 2;
1053
1054 /* 4 bytes for ttl (4) */
1055 if (reader + 4 > bufend)
1056 goto invalid_resp;
1057
1058 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1059 + reader[2] * 256 + reader[3];
1060 reader += 4;
1061
1062 /* Now reading data len */
1063 if (reader + 2 > bufend)
1064 goto invalid_resp;
1065
1066 answer_record->data_len = reader[0] * 256 + reader[1];
1067
1068 /* Move forward 2 bytes for data len */
1069 reader += 2;
1070
1071 if (reader + answer_record->data_len > bufend)
1072 goto invalid_resp;
1073
1074 /* Analyzing record content */
1075 switch (answer_record->type) {
1076 case DNS_RTYPE_A:
1077 /* ipv4 is stored on 4 bytes */
1078 if (answer_record->data_len != 4)
1079 goto invalid_resp;
1080
Willy Tarreau20a02372021-10-14 22:52:04 +02001081 answer_record->data.in4.sin_family = AF_INET;
1082 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001083 break;
1084
1085 case DNS_RTYPE_CNAME:
1086 /* Check if this is the last record and update the caller about the status:
1087 * no IP could be found and last record was a CNAME. Could be triggered
1088 * by a wrong query type
1089 *
1090 * + 1 because answer_record_id starts at 0
1091 * while number of answers is an integer and
1092 * starts at 1.
1093 */
1094 if (i + 1 == r_res->header.ancount) {
1095 cause = RSLV_RESP_CNAME_ERROR;
1096 goto return_error;
1097 }
1098
1099 offset = 0;
1100 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1101 if (len == 0)
1102 goto invalid_resp;
1103
Willy Tarreau20a02372021-10-14 22:52:04 +02001104 memcpy(answer_record->data.target, tmpname, len);
1105 answer_record->data.target[len] = 0;
1106 previous_dname = answer_record->data.target;
Emeric Brunc9437992021-02-12 19:42:55 +01001107 break;
1108
1109
1110 case DNS_RTYPE_SRV:
1111 /* Answer must contain :
1112 * - 2 bytes for the priority
1113 * - 2 bytes for the weight
1114 * - 2 bytes for the port
1115 * - the target hostname
1116 */
1117 if (answer_record->data_len <= 6)
1118 goto invalid_resp;
1119
1120 answer_record->priority = read_n16(reader);
1121 reader += sizeof(uint16_t);
1122 answer_record->weight = read_n16(reader);
1123 reader += sizeof(uint16_t);
1124 answer_record->port = read_n16(reader);
1125 reader += sizeof(uint16_t);
1126 offset = 0;
1127 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1128 if (len == 0)
1129 goto invalid_resp;
1130
1131 answer_record->data_len = len;
Willy Tarreau20a02372021-10-14 22:52:04 +02001132 memcpy(answer_record->data.target, tmpname, len);
1133 answer_record->data.target[len] = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01001134 if (answer_record->ar_item != NULL) {
1135 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1136 answer_record->ar_item = NULL;
1137 }
1138 break;
1139
1140 case DNS_RTYPE_AAAA:
1141 /* ipv6 is stored on 16 bytes */
1142 if (answer_record->data_len != 16)
1143 goto invalid_resp;
1144
Willy Tarreau20a02372021-10-14 22:52:04 +02001145 answer_record->data.in6.sin6_family = AF_INET6;
1146 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001147 break;
1148
1149 } /* switch (record type) */
1150
1151 /* Increment the counter for number of records saved into our
1152 * local response */
1153 nb_saved_records++;
1154
1155 /* Move forward answer_record->data_len for analyzing next
1156 * record in the response */
1157 reader += ((answer_record->type == DNS_RTYPE_SRV)
1158 ? offset
1159 : answer_record->data_len);
1160
1161 /* Lookup to see if we already had this entry */
1162 found = 0;
1163 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1164 if (tmp_record->type != answer_record->type)
1165 continue;
1166
1167 switch(tmp_record->type) {
1168 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001169 if (!memcmp(&answer_record->data.in4.sin_addr,
1170 &tmp_record->data.in4.sin_addr,
1171 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001172 found = 1;
1173 break;
1174
1175 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001176 if (!memcmp(&answer_record->data.in6.sin6_addr,
1177 &tmp_record->data.in6.sin6_addr,
1178 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001179 found = 1;
1180 break;
1181
1182 case DNS_RTYPE_SRV:
1183 if (answer_record->data_len == tmp_record->data_len &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001184 !resolv_hostname_cmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) &&
Emeric Brunc9437992021-02-12 19:42:55 +01001185 answer_record->port == tmp_record->port) {
1186 tmp_record->weight = answer_record->weight;
1187 found = 1;
1188 }
1189 break;
1190
1191 default:
1192 break;
1193 }
1194
1195 if (found == 1)
1196 break;
1197 }
1198
1199 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001200 tmp_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001201 pool_free(resolv_answer_item_pool, answer_record);
1202 answer_record = NULL;
1203 }
1204 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001205 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001206 answer_record->ar_item = NULL;
Willy Tarreau2b718102021-04-21 07:32:39 +02001207 LIST_APPEND(&r_res->answer_list, &answer_record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001208 answer_record = NULL;
1209 }
1210 } /* for i 0 to ancount */
1211
1212 /* Save the number of records we really own */
1213 r_res->header.ancount = nb_saved_records;
1214
1215 /* now parsing additional records for SRV queries only */
1216 if (query->type != DNS_RTYPE_SRV)
1217 goto skip_parsing_additional_records;
1218
1219 /* if we find Authority records, just skip them */
1220 for (i = 0; i < r_res->header.nscount; i++) {
1221 offset = 0;
1222 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1223 &offset, 0);
1224 if (len == 0)
1225 continue;
1226
1227 if (reader + offset + 10 >= bufend)
1228 goto invalid_resp;
1229
1230 reader += offset;
1231 /* skip 2 bytes for class */
1232 reader += 2;
1233 /* skip 2 bytes for type */
1234 reader += 2;
1235 /* skip 4 bytes for ttl */
1236 reader += 4;
1237 /* read data len */
1238 len = reader[0] * 256 + reader[1];
1239 reader += 2;
1240
1241 if (reader + len >= bufend)
1242 goto invalid_resp;
1243
1244 reader += len;
1245 }
1246
1247 nb_saved_records = 0;
1248 for (i = 0; i < r_res->header.arcount; i++) {
1249 if (reader >= bufend)
1250 goto invalid_resp;
1251
1252 answer_record = pool_alloc(resolv_answer_item_pool);
1253 if (answer_record == NULL)
1254 goto invalid_resp;
Christopher Faulet55c1c402021-03-11 09:36:05 +01001255 answer_record->last_seen = TICK_ETERNITY;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001256 LIST_INIT(&answer_record->attached_servers);
Emeric Brunc9437992021-02-12 19:42:55 +01001257
1258 offset = 0;
1259 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1260
1261 if (len == 0) {
1262 pool_free(resolv_answer_item_pool, answer_record);
1263 answer_record = NULL;
1264 continue;
1265 }
1266
1267 memcpy(answer_record->name, tmpname, len);
1268 answer_record->name[len] = 0;
1269
1270 reader += offset;
1271 if (reader >= bufend)
1272 goto invalid_resp;
1273
1274 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1275 if (reader + 2 > bufend)
1276 goto invalid_resp;
1277
1278 answer_record->type = reader[0] * 256 + reader[1];
1279 reader += 2;
1280
1281 /* 2 bytes for class (2) */
1282 if (reader + 2 > bufend)
1283 goto invalid_resp;
1284
1285 answer_record->class = reader[0] * 256 + reader[1];
1286 reader += 2;
1287
1288 /* 4 bytes for ttl (4) */
1289 if (reader + 4 > bufend)
1290 goto invalid_resp;
1291
1292 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1293 + reader[2] * 256 + reader[3];
1294 reader += 4;
1295
1296 /* Now reading data len */
1297 if (reader + 2 > bufend)
1298 goto invalid_resp;
1299
1300 answer_record->data_len = reader[0] * 256 + reader[1];
1301
1302 /* Move forward 2 bytes for data len */
1303 reader += 2;
1304
1305 if (reader + answer_record->data_len > bufend)
1306 goto invalid_resp;
1307
1308 /* Analyzing record content */
1309 switch (answer_record->type) {
1310 case DNS_RTYPE_A:
1311 /* ipv4 is stored on 4 bytes */
1312 if (answer_record->data_len != 4)
1313 goto invalid_resp;
1314
Willy Tarreau20a02372021-10-14 22:52:04 +02001315 answer_record->data.in4.sin_family = AF_INET;
1316 memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001317 break;
1318
1319 case DNS_RTYPE_AAAA:
1320 /* ipv6 is stored on 16 bytes */
1321 if (answer_record->data_len != 16)
1322 goto invalid_resp;
1323
Willy Tarreau20a02372021-10-14 22:52:04 +02001324 answer_record->data.in6.sin6_family = AF_INET6;
1325 memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
Emeric Brunc9437992021-02-12 19:42:55 +01001326 break;
1327
1328 default:
1329 pool_free(resolv_answer_item_pool, answer_record);
1330 answer_record = NULL;
1331 continue;
1332
1333 } /* switch (record type) */
1334
1335 /* Increment the counter for number of records saved into our
1336 * local response */
1337 nb_saved_records++;
1338
1339 /* Move forward answer_record->data_len for analyzing next
1340 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001341 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001342
1343 /* Lookup to see if we already had this entry */
1344 found = 0;
1345 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001346 struct resolv_answer_item *ar_item;
1347
1348 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1349 continue;
1350
1351 ar_item = tmp_record->ar_item;
Christopher Faulete8674c72021-03-12 16:42:45 +01001352 if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
Christopher Faulet77f86062021-03-10 15:19:57 +01001353 len != tmp_record->data_len ||
Willy Tarreau20a02372021-10-14 22:52:04 +02001354 resolv_hostname_cmp(answer_record->name, tmp_record->data.target, tmp_record->data_len))
Emeric Brunc9437992021-02-12 19:42:55 +01001355 continue;
1356
Christopher Faulet77f86062021-03-10 15:19:57 +01001357 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001358 case DNS_RTYPE_A:
Willy Tarreau20a02372021-10-14 22:52:04 +02001359 if (!memcmp(&answer_record->data.in4.sin_addr,
1360 &ar_item->data.in4.sin_addr,
1361 sizeof(answer_record->data.in4.sin_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001362 found = 1;
1363 break;
1364
1365 case DNS_RTYPE_AAAA:
Willy Tarreau20a02372021-10-14 22:52:04 +02001366 if (!memcmp(&answer_record->data.in6.sin6_addr,
1367 &ar_item->data.in6.sin6_addr,
1368 sizeof(answer_record->data.in6.sin6_addr)))
Emeric Brunc9437992021-02-12 19:42:55 +01001369 found = 1;
1370 break;
1371
1372 default:
1373 break;
1374 }
1375
1376 if (found == 1)
1377 break;
1378 }
1379
1380 if (found == 1) {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001381 tmp_record->ar_item->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001382 pool_free(resolv_answer_item_pool, answer_record);
1383 answer_record = NULL;
1384 }
1385 else {
Christopher Faulet55c1c402021-03-11 09:36:05 +01001386 answer_record->last_seen = now_ms;
Emeric Brunc9437992021-02-12 19:42:55 +01001387 answer_record->ar_item = NULL;
1388
1389 // looking for the SRV record in the response list linked to this additional record
1390 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1391 if (tmp_record->type == DNS_RTYPE_SRV &&
1392 tmp_record->ar_item == NULL &&
Willy Tarreau20a02372021-10-14 22:52:04 +02001393 !resolv_hostname_cmp(tmp_record->data.target, answer_record->name, tmp_record->data_len)) {
Emeric Brunc9437992021-02-12 19:42:55 +01001394 /* Always use the received additional record to refresh info */
1395 if (tmp_record->ar_item)
1396 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1397 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001398 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001399 break;
1400 }
1401 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001402 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001403 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001404 answer_record = NULL;
1405 }
Emeric Brunc9437992021-02-12 19:42:55 +01001406 }
1407 } /* for i 0 to arcount */
1408
1409 skip_parsing_additional_records:
1410
1411 /* Save the number of records we really own */
1412 r_res->header.arcount = nb_saved_records;
Emeric Brunc9437992021-02-12 19:42:55 +01001413 resolv_check_response(resolution);
1414 return RSLV_RESP_VALID;
1415
1416 invalid_resp:
1417 cause = RSLV_RESP_INVALID;
1418
1419 return_error:
1420 pool_free(resolv_answer_item_pool, answer_record);
1421 return cause;
1422}
1423
1424/* Searches dn_name resolution in resp.
1425 * If existing IP not found, return the first IP matching family_priority,
1426 * otherwise, first ip found
1427 * The following tasks are the responsibility of the caller:
1428 * - <r_res> contains an error free DNS response
1429 * For both cases above, resolv_validate_dns_response is required
1430 * returns one of the RSLV_UPD_* code
1431 */
1432int resolv_get_ip_from_response(struct resolv_response *r_res,
1433 struct resolv_options *resolv_opts, void *currentip,
1434 short currentip_sin_family,
1435 void **newip, short *newip_sin_family,
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001436 struct server *owner)
Emeric Brunc9437992021-02-12 19:42:55 +01001437{
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001438 struct resolv_answer_item *record, *found_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001439 int family_priority;
1440 int currentip_found;
1441 unsigned char *newip4, *newip6;
1442 int currentip_sel;
1443 int j;
1444 int score, max_score;
1445 int allowed_duplicated_ip;
1446
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001447 /* srv is linked to an alive ip record */
1448 if (owner && LIST_INLIST(&owner->ip_rec_item))
1449 return RSLV_UPD_NO;
1450
Emeric Brunc9437992021-02-12 19:42:55 +01001451 family_priority = resolv_opts->family_prio;
1452 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1453 *newip = newip4 = newip6 = NULL;
1454 currentip_found = 0;
1455 *newip_sin_family = AF_UNSPEC;
1456 max_score = -1;
1457
1458 /* Select an IP regarding configuration preference.
1459 * Top priority is the preferred network ip version,
1460 * second priority is the preferred network.
1461 * the last priority is the currently used IP,
1462 *
1463 * For these three priorities, a score is calculated. The
1464 * weight are:
1465 * 8 - preferred ip version.
1466 * 4 - preferred network.
1467 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1468 * 1 - current ip.
1469 * The result with the biggest score is returned.
1470 */
1471
1472 list_for_each_entry(record, &r_res->answer_list, list) {
1473 void *ip;
1474 unsigned char ip_type;
1475
1476 if (record->type == DNS_RTYPE_A) {
Emeric Brunc9437992021-02-12 19:42:55 +01001477 ip_type = AF_INET;
Willy Tarreau20a02372021-10-14 22:52:04 +02001478 ip = &record->data.in4.sin_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001479 }
1480 else if (record->type == DNS_RTYPE_AAAA) {
1481 ip_type = AF_INET6;
Willy Tarreau20a02372021-10-14 22:52:04 +02001482 ip = &record->data.in6.sin6_addr;
Emeric Brunc9437992021-02-12 19:42:55 +01001483 }
1484 else
1485 continue;
1486 score = 0;
1487
1488 /* Check for preferred ip protocol. */
1489 if (ip_type == family_priority)
1490 score += 8;
1491
1492 /* Check for preferred network. */
1493 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1494
1495 /* Compare only the same addresses class. */
1496 if (resolv_opts->pref_net[j].family != ip_type)
1497 continue;
1498
1499 if ((ip_type == AF_INET &&
1500 in_net_ipv4(ip,
1501 &resolv_opts->pref_net[j].mask.in4,
1502 &resolv_opts->pref_net[j].addr.in4)) ||
1503 (ip_type == AF_INET6 &&
1504 in_net_ipv6(ip,
1505 &resolv_opts->pref_net[j].mask.in6,
1506 &resolv_opts->pref_net[j].addr.in6))) {
1507 score += 4;
1508 break;
1509 }
1510 }
1511
1512 /* Check if the IP found in the record is already affected to a
1513 * member of a group. If not, the score should be incremented
1514 * by 2. */
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001515 if (owner) {
1516 struct server *srv;
1517 int already_used = 0;
1518
1519 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1520 if (srv == owner)
1521 continue;
1522 if (srv->proxy == owner->proxy) {
1523 already_used = 1;
1524 break;
1525 }
1526 }
1527 if (already_used) {
1528 if (!allowed_duplicated_ip) {
1529 continue;
1530 }
1531 }
1532 else {
1533 score += 2;
Emeric Brunc9437992021-02-12 19:42:55 +01001534 }
1535 } else {
1536 score += 2;
1537 }
1538
1539 /* Check for current ip matching. */
1540 if (ip_type == currentip_sin_family &&
1541 ((currentip_sin_family == AF_INET &&
1542 !memcmp(ip, currentip, 4)) ||
1543 (currentip_sin_family == AF_INET6 &&
1544 !memcmp(ip, currentip, 16)))) {
1545 score++;
1546 currentip_sel = 1;
1547 }
1548 else
1549 currentip_sel = 0;
1550
1551 /* Keep the address if the score is better than the previous
1552 * score. The maximum score is 15, if this value is reached, we
1553 * break the parsing. Implicitly, this score is reached the ip
1554 * selected is the current ip. */
1555 if (score > max_score) {
1556 if (ip_type == AF_INET)
1557 newip4 = ip;
1558 else
1559 newip6 = ip;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001560 found_record = record;
Emeric Brunc9437992021-02-12 19:42:55 +01001561 currentip_found = currentip_sel;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001562 if (score == 15) {
1563 /* this was not registered on the current record but it matches
1564 * let's fix it (it may comes from state file */
1565 if (owner)
1566 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
Emeric Brunc9437992021-02-12 19:42:55 +01001567 return RSLV_UPD_NO;
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001568 }
Emeric Brunc9437992021-02-12 19:42:55 +01001569 max_score = score;
1570 }
1571 } /* list for each record entries */
1572
1573 /* No IP found in the response */
1574 if (!newip4 && !newip6)
1575 return RSLV_UPD_NO_IP_FOUND;
1576
1577 /* Case when the caller looks first for an IPv4 address */
1578 if (family_priority == AF_INET) {
1579 if (newip4) {
1580 *newip = newip4;
1581 *newip_sin_family = AF_INET;
1582 }
1583 else if (newip6) {
1584 *newip = newip6;
1585 *newip_sin_family = AF_INET6;
1586 }
Emeric Brunc9437992021-02-12 19:42:55 +01001587 }
1588 /* Case when the caller looks first for an IPv6 address */
1589 else if (family_priority == AF_INET6) {
1590 if (newip6) {
1591 *newip = newip6;
1592 *newip_sin_family = AF_INET6;
1593 }
1594 else if (newip4) {
1595 *newip = newip4;
1596 *newip_sin_family = AF_INET;
1597 }
Emeric Brunc9437992021-02-12 19:42:55 +01001598 }
1599 /* Case when the caller have no preference (we prefer IPv6) */
1600 else if (family_priority == AF_UNSPEC) {
1601 if (newip6) {
1602 *newip = newip6;
1603 *newip_sin_family = AF_INET6;
1604 }
1605 else if (newip4) {
1606 *newip = newip4;
1607 *newip_sin_family = AF_INET;
1608 }
Emeric Brunc9437992021-02-12 19:42:55 +01001609 }
1610
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001611 /* the ip of this record was chosen for the server */
1612 if (owner && found_record) {
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001613 LIST_DEL_INIT(&owner->ip_rec_item);
Emeric Brunf9ca5d82021-06-11 10:08:05 +02001614 LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
1615 }
1616
Emeric Brunc9437992021-02-12 19:42:55 +01001617 list_for_each_entry(record, &r_res->answer_list, list) {
1618 /* Move the first record to the end of the list, for internal
1619 * round robin */
Willy Tarreau2b718102021-04-21 07:32:39 +02001620 LIST_DELETE(&record->list);
1621 LIST_APPEND(&r_res->answer_list, &record->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001622 break;
1623 }
Christopher Faulet2558d5a2021-06-24 15:16:48 +02001624
1625 return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
Emeric Brunc9437992021-02-12 19:42:55 +01001626}
1627
Willy Tarreauca0170b2021-10-14 08:05:25 +02001628/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
Emeric Brunc9437992021-02-12 19:42:55 +01001629 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001630 * <dn> contains the input label of <dn_len> bytes long and does not need to be
1631 * null-terminated. <str> must be allocated large enough to contain a full host
1632 * name plus the trailing zero, and the allocated size must be passed in
1633 * <str_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001634 *
Willy Tarreauca0170b2021-10-14 08:05:25 +02001635 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001636 * <str> (including the terminating null byte).
1637 */
1638int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1639{
1640 char *ptr;
1641 int i, sz;
1642
Willy Tarreauca0170b2021-10-14 08:05:25 +02001643 if (str_len < dn_len)
Emeric Brunc9437992021-02-12 19:42:55 +01001644 return -1;
1645
1646 ptr = str;
Willy Tarreauca0170b2021-10-14 08:05:25 +02001647 for (i = 0; i < dn_len; ++i) {
Emeric Brunc9437992021-02-12 19:42:55 +01001648 sz = dn[i];
1649 if (i)
1650 *ptr++ = '.';
1651 memcpy(ptr, dn+i+1, sz);
1652 ptr += sz;
1653 i += sz;
1654 }
1655 *ptr++ = '\0';
1656 return (ptr - str);
1657}
1658
1659/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1660 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001661 * <str> contains the input string that is <str_len> bytes long (trailing zero
1662 * not needed). <dn> buffer must be allocated large enough to contain the
1663 * encoded string and a trailing zero, so it must be at least str_len+2, and
1664 * this allocated buffer size must be passed in <dn_len>.
Emeric Brunc9437992021-02-12 19:42:55 +01001665 *
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001666 * In case of error, -1 is returned, otherwise, the number of bytes copied in
Emeric Brunc9437992021-02-12 19:42:55 +01001667 * <dn> (excluding the terminating null byte).
1668 */
1669int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1670{
1671 int i, offset;
1672
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001673 if (dn_len < str_len + 2)
Emeric Brunc9437992021-02-12 19:42:55 +01001674 return -1;
1675
1676 /* First byte of dn will be used to store the length of the first
1677 * label */
1678 offset = 0;
1679 for (i = 0; i < str_len; ++i) {
1680 if (str[i] == '.') {
1681 /* 2 or more consecutive dots is invalid */
1682 if (i == offset)
1683 return -1;
1684
1685 /* ignore trailing dot */
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001686 if (i + 1 == str_len) {
Emeric Brunc9437992021-02-12 19:42:55 +01001687 i++;
1688 break;
1689 }
1690
1691 dn[offset] = (i - offset);
1692 offset = i+1;
1693 continue;
1694 }
1695 dn[i+1] = str[i];
1696 }
Willy Tarreauc1c765f2021-10-14 07:49:49 +02001697 dn[offset] = i - offset;
Willy Tarreau68c7b362021-10-15 08:09:25 +02001698 dn[i+1] = '\0';
1699 return i+1;
Emeric Brunc9437992021-02-12 19:42:55 +01001700}
1701
1702/* Validates host name:
1703 * - total size
1704 * - each label size individually
1705 * returns:
1706 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1707 * 1 when no error. <err> is left unaffected.
1708 */
1709int resolv_hostname_validation(const char *string, char **err)
1710{
1711 int i;
1712
1713 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1714 if (err)
1715 *err = DNS_TOO_LONG_FQDN;
1716 return 0;
1717 }
1718
1719 while (*string) {
1720 i = 0;
1721 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1722 if (!(*string == '-' || *string == '_' ||
1723 (*string >= 'a' && *string <= 'z') ||
1724 (*string >= 'A' && *string <= 'Z') ||
1725 (*string >= '0' && *string <= '9'))) {
1726 if (err)
1727 *err = DNS_INVALID_CHARACTER;
1728 return 0;
1729 }
1730 i++;
1731 string++;
1732 }
1733
1734 if (!(*string))
1735 break;
1736
1737 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1738 if (err)
1739 *err = DNS_LABEL_TOO_LONG;
1740 return 0;
1741 }
1742
1743 string++;
1744 }
1745 return 1;
1746}
1747
1748/* Picks up an available resolution from the different resolution list
1749 * associated to a resolvers section, in this order:
1750 * 1. check in resolutions.curr for the same hostname and query_type
1751 * 2. check in resolutions.wait for the same hostname and query_type
1752 * 3. Get a new resolution from resolution pool
1753 *
1754 * Returns an available resolution, NULL if none found.
1755 */
1756static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1757 char **hostname_dn, int hostname_dn_len,
1758 int query_type)
1759{
1760 struct resolv_resolution *res;
1761
1762 if (!*hostname_dn)
1763 goto from_pool;
1764
1765 /* Search for same hostname and query type in resolutions.curr */
1766 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1767 if (!res->hostname_dn)
1768 continue;
1769 if ((query_type == res->prefered_query_type) &&
1770 hostname_dn_len == res->hostname_dn_len &&
1771 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1772 return res;
1773 }
1774
1775 /* Search for same hostname and query type in resolutions.wait */
1776 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1777 if (!res->hostname_dn)
1778 continue;
1779 if ((query_type == res->prefered_query_type) &&
1780 hostname_dn_len == res->hostname_dn_len &&
1781 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1782 return res;
1783 }
1784
1785 from_pool:
1786 /* No resolution could be found, so let's allocate a new one */
Willy Tarreau70490eb2021-03-22 21:08:50 +01001787 res = pool_zalloc(resolv_resolution_pool);
Emeric Brunc9437992021-02-12 19:42:55 +01001788 if (res) {
Willy Tarreau51128f82021-10-19 11:17:33 +02001789 int i;
1790
Emeric Brunc9437992021-02-12 19:42:55 +01001791 res->resolvers = resolvers;
1792 res->uuid = resolution_uuid;
1793 res->status = RSLV_STATUS_NONE;
1794 res->step = RSLV_STEP_NONE;
1795 res->last_valid = now_ms;
1796
1797 LIST_INIT(&res->requesters);
Willy Tarreau51128f82021-10-19 11:17:33 +02001798 LIST_INIT(&res->response.query_list);
Emeric Brunc9437992021-02-12 19:42:55 +01001799 LIST_INIT(&res->response.answer_list);
1800
Willy Tarreau51128f82021-10-19 11:17:33 +02001801 for (i = 0; i < DNS_MAX_QUERY_RECORDS; i++)
1802 LIST_INIT(&res->response_query_records[i].list);
1803
Emeric Brunc9437992021-02-12 19:42:55 +01001804 res->prefered_query_type = query_type;
1805 res->query_type = query_type;
1806 res->hostname_dn = *hostname_dn;
1807 res->hostname_dn_len = hostname_dn_len;
1808
1809 ++resolution_uuid;
1810
1811 /* Move the resolution to the resolvers wait queue */
Willy Tarreau2b718102021-04-21 07:32:39 +02001812 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001813 }
1814 return res;
1815}
1816
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001817void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
1818{
1819 struct resolv_answer_item *item, *itemback;
1820
1821 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001822 LIST_DELETE(&item->list);
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001823 pool_free(resolv_answer_item_pool, item->ar_item);
1824 pool_free(resolv_answer_item_pool, item);
1825 }
1826}
1827
Willy Tarreau51128f82021-10-19 11:17:33 +02001828/* deletes all query_items from the resolution's query_list */
1829static void resolv_purge_resolution_query_items(struct resolv_resolution *resolution)
1830{
1831 struct resolv_query_item *item, *itemback;
1832
1833 list_for_each_entry_safe(item, itemback, &resolution->response.query_list, list)
1834 LIST_DEL_INIT(&item->list);
1835}
1836
Emeric Brunc9437992021-02-12 19:42:55 +01001837/* Releases a resolution from its requester(s) and move it back to the pool */
1838static void resolv_free_resolution(struct resolv_resolution *resolution)
1839{
1840 struct resolv_requester *req, *reqback;
Emeric Brunc9437992021-02-12 19:42:55 +01001841
1842 /* clean up configuration */
1843 resolv_reset_resolution(resolution);
1844 resolution->hostname_dn = NULL;
1845 resolution->hostname_dn_len = 0;
1846
1847 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001848 LIST_DELETE(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001849 req->resolution = NULL;
1850 }
Christopher Faulet1dec5c72021-03-10 14:40:39 +01001851 resolv_purge_resolution_answer_records(resolution);
Willy Tarreau51128f82021-10-19 11:17:33 +02001852 resolv_purge_resolution_query_items(resolution);
1853
Willy Tarreau2b718102021-04-21 07:32:39 +02001854 LIST_DELETE(&resolution->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001855 pool_free(resolv_resolution_pool, resolution);
1856}
1857
1858/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
1859 * on success, -1 otherwise.
1860 */
1861int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1862{
1863 struct resolv_resolution *res = NULL;
1864 struct resolv_requester *req;
1865 struct resolvers *resolvers;
1866 struct server *srv = NULL;
1867 struct resolv_srvrq *srvrq = NULL;
1868 struct stream *stream = NULL;
1869 char **hostname_dn;
1870 int hostname_dn_len, query_type;
1871
1872 switch (requester_type) {
1873 case OBJ_TYPE_SERVER:
1874 srv = (struct server *)requester;
1875 hostname_dn = &srv->hostname_dn;
1876 hostname_dn_len = srv->hostname_dn_len;
1877 resolvers = srv->resolvers;
1878 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1879 ? DNS_RTYPE_A
1880 : DNS_RTYPE_AAAA);
1881 break;
1882
1883 case OBJ_TYPE_SRVRQ:
1884 srvrq = (struct resolv_srvrq *)requester;
1885 hostname_dn = &srvrq->hostname_dn;
1886 hostname_dn_len = srvrq->hostname_dn_len;
1887 resolvers = srvrq->resolvers;
1888 query_type = DNS_RTYPE_SRV;
1889 break;
1890
1891 case OBJ_TYPE_STREAM:
1892 stream = (struct stream *)requester;
1893 hostname_dn = &stream->resolv_ctx.hostname_dn;
1894 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
1895 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
1896 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
1897 ? DNS_RTYPE_A
1898 : DNS_RTYPE_AAAA);
1899 break;
1900 default:
1901 goto err;
1902 }
1903
1904 /* Get a resolution from the resolvers' wait queue or pool */
1905 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
1906 goto err;
1907
1908 if (srv) {
1909 if (!requester_locked)
1910 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1911 if (srv->resolv_requester == NULL) {
1912 if ((req = pool_alloc(resolv_requester_pool)) == NULL) {
1913 if (!requester_locked)
1914 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1915 goto err;
1916 }
1917 req->owner = &srv->obj_type;
1918 srv->resolv_requester = req;
1919 }
1920 else
1921 req = srv->resolv_requester;
1922 if (!requester_locked)
1923 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1924
1925 req->requester_cb = snr_resolution_cb;
1926 req->requester_error_cb = snr_resolution_error_cb;
1927 }
1928 else if (srvrq) {
1929 if (srvrq->requester == NULL) {
1930 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1931 goto err;
1932 req->owner = &srvrq->obj_type;
1933 srvrq->requester = req;
1934 }
1935 else
1936 req = srvrq->requester;
1937
1938 req->requester_cb = snr_resolution_cb;
Baptiste Assmannb4badf72020-11-19 22:38:33 +01001939 req->requester_error_cb = srvrq_resolution_error_cb;
Emeric Brunc9437992021-02-12 19:42:55 +01001940 }
1941 else if (stream) {
1942 if (stream->resolv_ctx.requester == NULL) {
1943 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1944 goto err;
1945 req->owner = &stream->obj_type;
1946 stream->resolv_ctx.requester = req;
1947 }
1948 else
1949 req = stream->resolv_ctx.requester;
1950
1951 req->requester_cb = act_resolution_cb;
1952 req->requester_error_cb = act_resolution_error_cb;
1953 }
1954 else
1955 goto err;
1956
1957 req->resolution = res;
1958
Willy Tarreau2b718102021-04-21 07:32:39 +02001959 LIST_APPEND(&res->requesters, &req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01001960 return 0;
1961
1962 err:
1963 if (res && LIST_ISEMPTY(&res->requesters))
1964 resolv_free_resolution(res);
1965 return -1;
1966}
1967
Emeric Brun0c4a8a32021-06-11 10:48:45 +02001968/* This function removes all server/srvrq references on answer items
1969 * if <safe> is set to 1, in case of srvrq, sub server resquesters unlink
1970 * is called using safe == 1 to make it usable into callbacks
1971 */
1972void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req, int safe)
1973{
1974 struct resolv_answer_item *item, *itemback;
1975 struct server *srv, *srvback;
1976 struct resolv_srvrq *srvrq;
1977
1978 if ((srv = objt_server(req->owner)) != NULL) {
1979 LIST_DEL_INIT(&srv->ip_rec_item);
1980 }
1981 else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
1982 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
1983 if (item->type == DNS_RTYPE_SRV) {
1984 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Faulet5f8ccff2021-06-15 16:08:48 +02001985 if (srv->srvrq == srvrq)
Willy Tarreau3223d852021-10-18 16:49:14 +02001986 resolv_srvrq_cleanup_srv(srv, safe);
Emeric Brun0c4a8a32021-06-11 10:48:45 +02001987 }
1988 }
1989 }
1990 }
1991}
1992
Emeric Brunc9437992021-02-12 19:42:55 +01001993/* Removes a requester from a DNS resolution. It takes takes care of all the
1994 * consequences. It also cleans up some parameters from the requester.
Christopher Faulet0efc0992021-03-11 18:09:53 +01001995 * if <safe> is set to 1, the corresponding resolution is not released.
Emeric Brunc9437992021-02-12 19:42:55 +01001996 */
Christopher Faulet0efc0992021-03-11 18:09:53 +01001997void resolv_unlink_resolution(struct resolv_requester *requester, int safe)
Emeric Brunc9437992021-02-12 19:42:55 +01001998{
1999 struct resolv_resolution *res;
2000 struct resolv_requester *req;
2001
2002 /* Nothing to do */
2003 if (!requester || !requester->resolution)
2004 return;
2005 res = requester->resolution;
2006
Emeric Brunf9ca5d82021-06-11 10:08:05 +02002007 /* remove ref from the resolution answer item list to the requester */
Emeric Brun0c4a8a32021-06-11 10:48:45 +02002008 resolv_detach_from_resolution_answer_items(res, requester, safe);
Emeric Brunf9ca5d82021-06-11 10:08:05 +02002009
Emeric Brunc9437992021-02-12 19:42:55 +01002010 /* Clean up the requester */
Willy Tarreau2b718102021-04-21 07:32:39 +02002011 LIST_DELETE(&requester->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002012 requester->resolution = NULL;
2013
2014 /* We need to find another requester linked on this resolution */
2015 if (!LIST_ISEMPTY(&res->requesters))
2016 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
2017 else {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002018 if (safe) {
2019 /* Don't release it yet. */
2020 resolv_reset_resolution(res);
2021 res->hostname_dn = NULL;
2022 res->hostname_dn_len = 0;
2023 resolv_purge_resolution_answer_records(res);
2024 return;
2025 }
2026
Emeric Brunc9437992021-02-12 19:42:55 +01002027 resolv_free_resolution(res);
2028 return;
2029 }
2030
2031 /* Move hostname_dn related pointers to the next requester */
2032 switch (obj_type(req->owner)) {
2033 case OBJ_TYPE_SERVER:
2034 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2035 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
2036 break;
2037 case OBJ_TYPE_SRVRQ:
2038 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
2039 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
2040 break;
2041 case OBJ_TYPE_STREAM:
2042 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
2043 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
2044 break;
2045 default:
2046 res->hostname_dn = NULL;
2047 res->hostname_dn_len = 0;
2048 break;
2049 }
2050}
2051
2052/* Called when a network IO is generated on a name server socket for an incoming
2053 * packet. It performs the following actions:
2054 * - check if the packet requires processing (not outdated resolution)
2055 * - ensure the DNS packet received is valid and call requester's callback
2056 * - call requester's error callback if invalid response
2057 * - check the dn_name in the packet against the one sent
2058 */
2059static int resolv_process_responses(struct dns_nameserver *ns)
2060{
2061 struct dns_counters *tmpcounters;
2062 struct resolvers *resolvers;
2063 struct resolv_resolution *res;
2064 struct resolv_query_item *query;
2065 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2066 unsigned char *bufend;
2067 int buflen, dns_resp;
2068 int max_answer_records;
2069 unsigned short query_id;
2070 struct eb32_node *eb;
2071 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002072 int keep_answer_items;
Emeric Brunc9437992021-02-12 19:42:55 +01002073
2074 resolvers = ns->parent;
2075 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2076
2077 /* process all pending input messages */
2078 while (1) {
2079 /* read message received */
2080 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2081 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
2082 break;
2083 }
2084
2085 /* message too big */
2086 if (buflen > resolvers->accepted_payload_size) {
2087 ns->counters->too_big++;
2088 continue;
2089 }
2090
2091 /* initializing variables */
2092 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2093
2094 /* read the query id from the packet (16 bits) */
2095 if (buf + 2 > bufend) {
2096 ns->counters->invalid++;
2097 continue;
2098 }
2099 query_id = resolv_response_get_query_id(buf);
2100
2101 /* search the query_id in the pending resolution tree */
2102 eb = eb32_lookup(&resolvers->query_ids, query_id);
2103 if (eb == NULL) {
2104 /* unknown query id means an outdated response and can be safely ignored */
2105 ns->counters->outdated++;
2106 continue;
2107 }
2108
2109 /* known query id means a resolution in progress */
2110 res = eb32_entry(eb, struct resolv_resolution, qid);
2111 /* number of responses received */
2112 res->nb_responses++;
2113
2114 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2115 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
2116
2117 switch (dns_resp) {
2118 case RSLV_RESP_VALID:
2119 break;
2120
2121 case RSLV_RESP_INVALID:
2122 case RSLV_RESP_QUERY_COUNT_ERROR:
2123 case RSLV_RESP_WRONG_NAME:
2124 res->status = RSLV_STATUS_INVALID;
2125 ns->counters->invalid++;
2126 break;
2127
2128 case RSLV_RESP_NX_DOMAIN:
2129 res->status = RSLV_STATUS_NX;
2130 ns->counters->nx++;
2131 break;
2132
2133 case RSLV_RESP_REFUSED:
2134 res->status = RSLV_STATUS_REFUSED;
2135 ns->counters->refused++;
2136 break;
2137
2138 case RSLV_RESP_ANCOUNT_ZERO:
2139 res->status = RSLV_STATUS_OTHER;
2140 ns->counters->any_err++;
2141 break;
2142
2143 case RSLV_RESP_CNAME_ERROR:
2144 res->status = RSLV_STATUS_OTHER;
2145 ns->counters->cname_error++;
2146 break;
2147
2148 case RSLV_RESP_TRUNCATED:
2149 res->status = RSLV_STATUS_OTHER;
2150 ns->counters->truncated++;
2151 break;
2152
2153 case RSLV_RESP_NO_EXPECTED_RECORD:
2154 case RSLV_RESP_ERROR:
2155 case RSLV_RESP_INTERNAL:
2156 res->status = RSLV_STATUS_OTHER;
2157 ns->counters->other++;
2158 break;
2159 }
2160
2161 /* Wait all nameservers response to handle errors */
2162 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
2163 continue;
2164
2165 /* Process error codes */
2166 if (dns_resp != RSLV_RESP_VALID) {
2167 if (res->prefered_query_type != res->query_type) {
2168 /* The fallback on the query type was already performed,
2169 * so check the try counter. If it falls to 0, we can
2170 * report an error. Else, wait the next attempt. */
2171 if (!res->try)
2172 goto report_res_error;
2173 }
2174 else {
2175 /* Fallback from A to AAAA or the opposite and re-send
2176 * the resolution immediately. try counter is not
2177 * decremented. */
2178 if (res->prefered_query_type == DNS_RTYPE_A) {
2179 res->query_type = DNS_RTYPE_AAAA;
2180 resolv_send_query(res);
2181 }
2182 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2183 res->query_type = DNS_RTYPE_A;
2184 resolv_send_query(res);
2185 }
2186 }
2187 continue;
2188 }
2189
2190 /* Now let's check the query's dname corresponds to the one we
2191 * sent. We can check only the first query of the list. We send
Willy Tarreau51128f82021-10-19 11:17:33 +02002192 * one query at a time so we get one query in the response.
2193 */
2194 if (!LIST_ISEMPTY(&res->response.query_list)) {
2195 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
2196 LIST_DEL_INIT(&query->list);
2197 if (resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
2198 dns_resp = RSLV_RESP_WRONG_NAME;
2199 ns->counters->other++;
2200 goto report_res_error;
2201 }
Emeric Brunc9437992021-02-12 19:42:55 +01002202 }
2203
2204 /* So the resolution succeeded */
2205 res->status = RSLV_STATUS_VALID;
2206 res->last_valid = now_ms;
2207 ns->counters->valid++;
2208 goto report_res_success;
2209
2210 report_res_error:
Emeric Brun43839d02021-06-10 15:25:25 +02002211 keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002212 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002213 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2214 if (!keep_answer_items)
2215 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002216 resolv_reset_resolution(res);
Willy Tarreau2b718102021-04-21 07:32:39 +02002217 LIST_DELETE(&res->list);
2218 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002219 continue;
2220
2221 report_res_success:
2222 /* Only the 1rst requester s managed by the server, others are
2223 * from the cache */
2224 tmpcounters = ns->counters;
2225 list_for_each_entry(req, &res->requesters, list) {
2226 struct server *s = objt_server(req->owner);
2227
2228 if (s)
2229 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2230 req->requester_cb(req, tmpcounters);
2231 if (s)
2232 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2233 tmpcounters = NULL;
2234 }
2235
2236 resolv_reset_resolution(res);
Willy Tarreau2b718102021-04-21 07:32:39 +02002237 LIST_DELETE(&res->list);
2238 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002239 continue;
2240 }
2241 resolv_update_resolvers_timeout(resolvers);
2242 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2243
2244 return buflen;
2245}
2246
2247/* Processes DNS resolution. First, it checks the active list to detect expired
2248 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2249 * checks the wait list to trigger new resolutions.
2250 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002251static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002252{
2253 struct resolvers *resolvers = context;
2254 struct resolv_resolution *res, *resback;
2255 int exp;
2256
2257 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2258
2259 /* Handle all expired resolutions from the active list */
2260 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002261 if (LIST_ISEMPTY(&res->requesters)) {
2262 resolv_free_resolution(res);
2263 continue;
2264 }
2265
Emeric Brunc9437992021-02-12 19:42:55 +01002266 /* When we find the first resolution in the future, then we can
2267 * stop here */
2268 exp = tick_add(res->last_query, resolvers->timeout.retry);
2269 if (!tick_is_expired(exp, now_ms))
2270 break;
2271
2272 /* If current resolution has been tried too many times and
2273 * finishes in timeout we update its status and remove it from
2274 * the list */
2275 if (!res->try) {
2276 struct resolv_requester *req;
Emeric Brun43839d02021-06-10 15:25:25 +02002277 int keep_answer_items = 0;
Emeric Brunc9437992021-02-12 19:42:55 +01002278
2279 /* Notify the result to the requesters */
2280 if (!res->nb_responses)
2281 res->status = RSLV_STATUS_TIMEOUT;
2282 list_for_each_entry(req, &res->requesters, list)
Emeric Brun43839d02021-06-10 15:25:25 +02002283 keep_answer_items |= req->requester_error_cb(req, res->status);
2284 if (!keep_answer_items)
2285 resolv_purge_resolution_answer_records(res);
Emeric Brunc9437992021-02-12 19:42:55 +01002286
2287 /* Clean up resolution info and remove it from the
2288 * current list */
2289 resolv_reset_resolution(res);
Willy Tarreau2b718102021-04-21 07:32:39 +02002290 LIST_DELETE(&res->list);
2291 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002292 }
2293 else {
2294 /* Otherwise resend the DNS query and requeue the resolution */
2295 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2296 /* No response received (a real timeout) or fallback already done */
2297 res->query_type = res->prefered_query_type;
2298 res->try--;
2299 }
2300 else {
2301 /* Fallback from A to AAAA or the opposite and re-send
2302 * the resolution immediately. try counter is not
2303 * decremented. */
2304 if (res->prefered_query_type == DNS_RTYPE_A)
2305 res->query_type = DNS_RTYPE_AAAA;
2306 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2307 res->query_type = DNS_RTYPE_A;
2308 else
2309 res->try--;
2310 }
2311 resolv_send_query(res);
2312 }
2313 }
2314
2315 /* Handle all resolutions in the wait list */
2316 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002317 if (LIST_ISEMPTY(&res->requesters)) {
2318 resolv_free_resolution(res);
2319 continue;
2320 }
2321
Emeric Brunc9437992021-02-12 19:42:55 +01002322 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2323 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2324 continue;
2325
2326 if (resolv_run_resolution(res) != 1) {
2327 res->last_resolution = now_ms;
Willy Tarreau2b718102021-04-21 07:32:39 +02002328 LIST_DELETE(&res->list);
2329 LIST_APPEND(&resolvers->resolutions.wait, &res->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002330 }
2331 }
2332
2333 resolv_update_resolvers_timeout(resolvers);
2334 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2335 return t;
2336}
2337
2338/* Release memory allocated by DNS */
2339static void resolvers_deinit(void)
2340{
2341 struct resolvers *resolvers, *resolversback;
2342 struct dns_nameserver *ns, *nsback;
2343 struct resolv_resolution *res, *resback;
2344 struct resolv_requester *req, *reqback;
2345 struct resolv_srvrq *srvrq, *srvrqback;
2346
2347 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2348 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2349 free(ns->id);
2350 free((char *)ns->conf.file);
2351 if (ns->dgram) {
2352 if (ns->dgram->conn.t.sock.fd != -1) {
2353 fd_delete(ns->dgram->conn.t.sock.fd);
2354 close(ns->dgram->conn.t.sock.fd);
2355 }
2356 if (ns->dgram->ring_req)
2357 ring_free(ns->dgram->ring_req);
2358 free(ns->dgram);
2359 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002360 if (ns->stream) {
2361 if (ns->stream->ring_req)
2362 ring_free(ns->stream->ring_req);
2363 if (ns->stream->task_req)
2364 task_destroy(ns->stream->task_req);
2365 if (ns->stream->task_rsp)
2366 task_destroy(ns->stream->task_rsp);
2367 free(ns->stream);
2368 }
Willy Tarreau2b718102021-04-21 07:32:39 +02002369 LIST_DELETE(&ns->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002370 EXTRA_COUNTERS_FREE(ns->extra_counters);
2371 free(ns);
2372 }
2373
2374 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2375 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002376 LIST_DELETE(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002377 pool_free(resolv_requester_pool, req);
2378 }
2379 resolv_free_resolution(res);
2380 }
2381
2382 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2383 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02002384 LIST_DELETE(&req->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002385 pool_free(resolv_requester_pool, req);
2386 }
2387 resolv_free_resolution(res);
2388 }
2389
2390 free(resolvers->id);
2391 free((char *)resolvers->conf.file);
2392 task_destroy(resolvers->t);
Willy Tarreau2b718102021-04-21 07:32:39 +02002393 LIST_DELETE(&resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002394 free(resolvers);
2395 }
2396
2397 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2398 free(srvrq->name);
2399 free(srvrq->hostname_dn);
Willy Tarreau2b718102021-04-21 07:32:39 +02002400 LIST_DELETE(&srvrq->list);
Emeric Brunc9437992021-02-12 19:42:55 +01002401 free(srvrq);
2402 }
2403}
2404
2405/* Finalizes the DNS configuration by allocating required resources and checking
2406 * live parameters.
2407 * Returns 0 on success, ERR_* flags otherwise.
2408 */
2409static int resolvers_finalize_config(void)
2410{
2411 struct resolvers *resolvers;
2412 struct proxy *px;
2413 int err_code = 0;
2414
2415 /* allocate pool of resolution per resolvers */
2416 list_for_each_entry(resolvers, &sec_resolvers, list) {
2417 struct dns_nameserver *ns;
2418 struct task *t;
2419
2420 /* Check if we can create the socket with nameservers info */
2421 list_for_each_entry(ns, &resolvers->nameservers, list) {
2422 int fd;
2423
2424 if (ns->dgram) {
2425 /* Check nameserver info */
2426 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
2427 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2428 resolvers->id, ns->id);
2429 err_code |= (ERR_ALERT|ERR_ABORT);
2430 continue;
2431 }
2432 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
2433 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2434 resolvers->id, ns->id);
2435 close(fd);
2436 err_code |= (ERR_ALERT|ERR_ABORT);
2437 continue;
2438 }
2439 close(fd);
2440 }
2441 }
2442
2443 /* Create the task associated to the resolvers section */
2444 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2445 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
2446 err_code |= (ERR_ALERT|ERR_ABORT);
2447 goto err;
2448 }
2449
2450 /* Update task's parameters */
2451 t->process = process_resolvers;
2452 t->context = resolvers;
2453 resolvers->t = t;
2454 task_wakeup(t, TASK_WOKEN_INIT);
2455 }
2456
2457 for (px = proxies_list; px; px = px->next) {
2458 struct server *srv;
2459
2460 for (srv = px->srv; srv; srv = srv->next) {
2461 struct resolvers *resolvers;
2462
2463 if (!srv->resolvers_id)
2464 continue;
2465
2466 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
2467 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2468 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2469 err_code |= (ERR_ALERT|ERR_ABORT);
2470 continue;
2471 }
2472 srv->resolvers = resolvers;
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002473 srv->srvrq_check = NULL;
2474 if (srv->srvrq) {
2475 if (!srv->srvrq->resolvers) {
2476 srv->srvrq->resolvers = srv->resolvers;
2477 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2478 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2479 proxy_type_str(px), px->id, srv->id);
2480 err_code |= (ERR_ALERT|ERR_ABORT);
2481 continue;
2482 }
2483 }
Emeric Brunc9437992021-02-12 19:42:55 +01002484
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002485 srv->srvrq_check = task_new(MAX_THREADS_MASK);
2486 if (!srv->srvrq_check) {
2487 ha_alert("config: %s '%s' : unable to create SRVRQ task for server '%s'.\n",
Emeric Brunc9437992021-02-12 19:42:55 +01002488 proxy_type_str(px), px->id, srv->id);
2489 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002490 goto err;
Emeric Brunc9437992021-02-12 19:42:55 +01002491 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002492 srv->srvrq_check->process = resolv_srvrq_expire_task;
2493 srv->srvrq_check->context = srv;
2494 srv->srvrq_check->expire = TICK_ETERNITY;
Emeric Brunc9437992021-02-12 19:42:55 +01002495 }
Christopher Faulet2c0f5272021-06-15 16:17:17 +02002496 else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Emeric Brunc9437992021-02-12 19:42:55 +01002497 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2498 proxy_type_str(px), px->id, srv->id);
2499 err_code |= (ERR_ALERT|ERR_ABORT);
2500 continue;
2501 }
2502 }
2503 }
2504
2505 if (err_code & (ERR_ALERT|ERR_ABORT))
2506 goto err;
2507
2508 return err_code;
2509 err:
2510 resolvers_deinit();
2511 return err_code;
2512
2513}
2514
2515static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2516 struct dns_nameserver *ns,
2517 struct field *stats, size_t stats_count,
2518 struct list *stat_modules)
2519{
2520 struct appctx *appctx = __objt_appctx(si->end);
2521 struct channel *rep = si_ic(si);
2522 struct stats_module *mod;
2523 size_t idx = 0;
2524
2525 memset(stats, 0, sizeof(struct field) * stats_count);
2526
2527 list_for_each_entry(mod, stat_modules, list) {
2528 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2529
2530 mod->fill_stats(counters, stats + idx);
2531 idx += mod->stats_count;
2532 }
2533
2534 if (!stats_dump_one_line(stats, idx, appctx))
2535 return 0;
2536
2537 if (!stats_putchk(rep, NULL, &trash))
2538 goto full;
2539
2540 return 1;
2541
2542 full:
2543 si_rx_room_rdy(si);
2544 return 0;
2545}
2546
2547/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2548 * as a pointer to the current nameserver.
2549 */
2550int stats_dump_resolvers(struct stream_interface *si,
2551 struct field *stats, size_t stats_count,
2552 struct list *stat_modules)
2553{
2554 struct appctx *appctx = __objt_appctx(si->end);
2555 struct channel *rep = si_ic(si);
2556 struct resolvers *resolver = appctx->ctx.stats.obj1;
2557 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2558
2559 if (!resolver)
2560 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2561
2562 /* dump resolvers */
2563 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2564 appctx->ctx.stats.obj1 = resolver;
2565
2566 ns = appctx->ctx.stats.obj2 ?
2567 appctx->ctx.stats.obj2 :
2568 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2569
2570 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2571 appctx->ctx.stats.obj2 = ns;
2572
2573 if (buffer_almost_full(&rep->buf))
2574 goto full;
2575
2576 if (!stats_dump_resolv_to_buffer(si, ns,
2577 stats, stats_count,
2578 stat_modules)) {
2579 return 0;
2580 }
2581 }
2582
2583 appctx->ctx.stats.obj2 = NULL;
2584 }
2585
2586 return 1;
2587
2588 full:
2589 si_rx_room_blk(si);
2590 return 0;
2591}
2592
2593void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2594{
2595 struct resolvers *resolvers;
2596 struct dns_nameserver *ns;
2597 struct stats_module *mod;
2598 void *counters;
2599
2600 list_for_each_entry(mod, stat_modules, list) {
2601 if (!mod->clearable && !clrall)
2602 continue;
2603
2604 list_for_each_entry(resolvers, &sec_resolvers, list) {
2605 list_for_each_entry(ns, &resolvers->nameservers, list) {
2606 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2607 memcpy(counters, mod->counters, mod->counters_size);
2608 }
2609 }
2610 }
2611
2612}
2613
2614int resolv_allocate_counters(struct list *stat_modules)
2615{
2616 struct stats_module *mod;
2617 struct resolvers *resolvers;
2618 struct dns_nameserver *ns;
2619
2620 list_for_each_entry(resolvers, &sec_resolvers, list) {
2621 list_for_each_entry(ns, &resolvers->nameservers, list) {
2622 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2623 alloc_failed);
2624
2625 list_for_each_entry(mod, stat_modules, list) {
2626 EXTRA_COUNTERS_ADD(mod,
2627 ns->extra_counters,
2628 mod->counters,
2629 mod->counters_size);
2630 }
2631
2632 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2633
2634 list_for_each_entry(mod, stat_modules, list) {
2635 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2636 mod->counters, mod->counters_size);
2637
2638 /* Store the ns counters pointer */
2639 if (strcmp(mod->name, "dns") == 0) {
2640 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2641 ns->counters->id = ns->id;
2642 ns->counters->pid = resolvers->id;
2643 }
2644 }
2645 }
2646 }
2647
2648 return 1;
2649
2650alloc_failed:
2651 return 0;
2652}
2653
2654/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2655static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2656{
2657 struct resolvers *presolvers;
2658
2659 if (*args[2]) {
2660 list_for_each_entry(presolvers, &sec_resolvers, list) {
2661 if (strcmp(presolvers->id, args[2]) == 0) {
2662 appctx->ctx.cli.p0 = presolvers;
2663 break;
2664 }
2665 }
2666 if (appctx->ctx.cli.p0 == NULL)
2667 return cli_err(appctx, "Can't find that resolvers section\n");
2668 }
2669 return 0;
2670}
2671
2672/* Dumps counters from all resolvers section and associated name servers. It
2673 * returns 0 if the output buffer is full and it needs to be called again,
2674 * otherwise non-zero. It may limit itself to the resolver pointed to by
2675 * <cli.p0> if it's not null.
2676 */
2677static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2678{
2679 struct stream_interface *si = appctx->owner;
2680 struct resolvers *resolvers;
2681 struct dns_nameserver *ns;
2682
2683 chunk_reset(&trash);
2684
2685 switch (appctx->st2) {
2686 case STAT_ST_INIT:
2687 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2688 /* fall through */
2689
2690 case STAT_ST_LIST:
2691 if (LIST_ISEMPTY(&sec_resolvers)) {
2692 chunk_appendf(&trash, "No resolvers found\n");
2693 }
2694 else {
2695 list_for_each_entry(resolvers, &sec_resolvers, list) {
2696 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2697 continue;
2698
2699 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2700 list_for_each_entry(ns, &resolvers->nameservers, list) {
2701 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2702 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2703 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2704 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2705 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2706 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2707 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2708 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2709 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2710 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2711 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2712 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2713 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2714 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2715 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2716 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
2717 }
2718 chunk_appendf(&trash, "\n");
2719 }
2720 }
2721
2722 /* display response */
2723 if (ci_putchk(si_ic(si), &trash) == -1) {
2724 /* let's try again later from this session. We add ourselves into
2725 * this session's users so that it can remove us upon termination.
2726 */
2727 si_rx_room_blk(si);
2728 return 0;
2729 }
2730 /* fall through */
2731
2732 default:
2733 appctx->st2 = STAT_ST_FIN;
2734 return 1;
2735 }
2736}
2737
2738/* register cli keywords */
2739static struct cli_kw_list cli_kws = {{ }, {
Willy Tarreaub205bfd2021-05-07 11:38:37 +02002740 { { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
Emeric Brunc9437992021-02-12 19:42:55 +01002741 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2742 {{},}
2743 }
2744};
2745
2746INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2747
2748/*
2749 * Prepare <rule> for hostname resolution.
2750 * Returns -1 in case of any allocation failure, 0 if not.
2751 * On error, a global failure counter is also incremented.
2752 */
Willy Tarreaua13a6102021-10-14 08:11:48 +02002753static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
Emeric Brunc9437992021-02-12 19:42:55 +01002754{
2755 char *hostname_dn;
Willy Tarreaua13a6102021-10-14 08:11:48 +02002756 int hostname_dn_len;
Emeric Brunc9437992021-02-12 19:42:55 +01002757 struct buffer *tmp = get_trash_chunk();
2758
2759 if (!hostname)
2760 return 0;
2761
Emeric Brunc9437992021-02-12 19:42:55 +01002762 hostname_dn = tmp->area;
Willy Tarreauc1c765f2021-10-14 07:49:49 +02002763 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
Emeric Brunc9437992021-02-12 19:42:55 +01002764 hostname_dn, tmp->size);
2765 if (hostname_dn_len == -1)
2766 goto err;
2767
2768
2769 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2770 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2771 if (!stream->resolv_ctx.hostname_dn)
2772 goto err;
2773
2774 return 0;
2775
2776 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002777 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002778 resolv_failed_resolutions += 1;
2779 return -1;
2780}
2781
2782
2783/*
2784 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2785 */
2786enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2787 struct session *sess, struct stream *s, int flags)
2788{
2789 struct resolv_resolution *resolution;
2790 struct sample *smp;
Emeric Brunc9437992021-02-12 19:42:55 +01002791 struct resolv_requester *req;
2792 struct resolvers *resolvers;
2793 struct resolv_resolution *res;
2794 int exp, locked = 0;
2795 enum act_return ret = ACT_RET_CONT;
2796
2797 resolvers = rule->arg.resolv.resolvers;
2798
2799 /* we have a response to our DNS resolution */
2800 use_cache:
2801 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2802 resolution = s->resolv_ctx.requester->resolution;
2803 if (!locked) {
2804 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2805 locked = 1;
2806 }
2807
2808 if (resolution->step == RSLV_STEP_RUNNING)
2809 goto yield;
2810 if (resolution->step == RSLV_STEP_NONE) {
2811 /* We update the variable only if we have a valid response. */
2812 if (resolution->status == RSLV_STATUS_VALID) {
2813 struct sample smp;
2814 short ip_sin_family = 0;
2815 void *ip = NULL;
2816
2817 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2818 0, &ip, &ip_sin_family, NULL);
2819
2820 switch (ip_sin_family) {
2821 case AF_INET:
2822 smp.data.type = SMP_T_IPV4;
2823 memcpy(&smp.data.u.ipv4, ip, 4);
2824 break;
2825 case AF_INET6:
2826 smp.data.type = SMP_T_IPV6;
2827 memcpy(&smp.data.u.ipv6, ip, 16);
2828 break;
2829 default:
2830 ip = NULL;
2831 }
2832
2833 if (ip) {
2834 smp.px = px;
2835 smp.sess = sess;
2836 smp.strm = s;
2837
2838 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2839 }
2840 }
2841 }
2842
2843 goto release_requester;
2844 }
2845
2846 /* need to configure and start a new DNS resolution */
2847 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2848 if (smp == NULL)
2849 goto end;
2850
Willy Tarreaua13a6102021-10-14 08:11:48 +02002851 if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
Emeric Brunc9437992021-02-12 19:42:55 +01002852 goto end; /* on error, ignore the action */
2853
2854 s->resolv_ctx.parent = rule;
2855
2856 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2857 locked = 1;
2858
2859 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2860
2861 /* Check if there is a fresh enough response in the cache of our associated resolution */
2862 req = s->resolv_ctx.requester;
2863 if (!req || !req->resolution)
2864 goto release_requester; /* on error, ignore the action */
2865 res = req->resolution;
2866
2867 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2868 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2869 && !tick_is_expired(exp, now_ms)) {
2870 goto use_cache;
2871 }
2872
2873 resolv_trigger_resolution(s->resolv_ctx.requester);
2874
2875 yield:
2876 if (flags & ACT_OPT_FINAL)
2877 goto release_requester;
2878 ret = ACT_RET_YIELD;
2879
2880 end:
2881 if (locked)
2882 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2883 return ret;
2884
2885 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002886 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002887 s->resolv_ctx.hostname_dn_len = 0;
2888 if (s->resolv_ctx.requester) {
Christopher Faulet0efc0992021-03-11 18:09:53 +01002889 resolv_unlink_resolution(s->resolv_ctx.requester, 0);
Emeric Brunc9437992021-02-12 19:42:55 +01002890 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2891 s->resolv_ctx.requester = NULL;
2892 }
2893 goto end;
2894}
2895
2896static void release_resolv_action(struct act_rule *rule)
2897{
2898 release_sample_expr(rule->arg.resolv.expr);
2899 free(rule->arg.resolv.varname);
2900 free(rule->arg.resolv.resolvers_id);
2901 free(rule->arg.resolv.opts);
2902}
2903
2904
2905/* parse "do-resolve" action
2906 * This action takes the following arguments:
2907 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
2908 *
2909 * - <varName> is the variable name where the result of the DNS resolution will be stored
2910 * (mandatory)
2911 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
2912 * (mandatory)
2913 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
2914 * (optional), defaults to ipv6
2915 * - <expr> is an HAProxy expression used to fetch the name to be resolved
2916 */
2917enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
2918{
2919 int cur_arg;
2920 struct sample_expr *expr;
2921 unsigned int where;
2922 const char *beg, *end;
2923
2924 /* orig_arg points to the first argument, but we need to analyse the command itself first */
2925 cur_arg = *orig_arg - 1;
2926
2927 /* locate varName, which is mandatory */
2928 beg = strchr(args[cur_arg], '(');
2929 if (beg == NULL)
2930 goto do_resolve_parse_error;
2931 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
2932 end = strchr(beg, ',');
2933 if (end == NULL)
2934 goto do_resolve_parse_error;
2935 rule->arg.resolv.varname = my_strndup(beg, end - beg);
2936 if (rule->arg.resolv.varname == NULL)
2937 goto do_resolve_parse_error;
2938
2939
2940 /* locate resolversSectionName, which is mandatory.
2941 * Since next parameters are optional, the delimiter may be comma ','
2942 * or closing parenthesis ')'
2943 */
2944 beg = end + 1;
2945 end = strchr(beg, ',');
2946 if (end == NULL)
2947 end = strchr(beg, ')');
2948 if (end == NULL)
2949 goto do_resolve_parse_error;
2950 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
2951 if (rule->arg.resolv.resolvers_id == NULL)
2952 goto do_resolve_parse_error;
2953
2954
2955 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
2956 if (rule->arg.resolv.opts == NULL)
2957 goto do_resolve_parse_error;
2958
2959 /* Default priority is ipv6 */
2960 rule->arg.resolv.opts->family_prio = AF_INET6;
2961
2962 /* optional arguments accepted for now:
2963 * ipv4 or ipv6
2964 */
2965 while (*end != ')') {
2966 beg = end + 1;
2967 end = strchr(beg, ',');
2968 if (end == NULL)
2969 end = strchr(beg, ')');
2970 if (end == NULL)
2971 goto do_resolve_parse_error;
2972
2973 if (strncmp(beg, "ipv4", end - beg) == 0) {
2974 rule->arg.resolv.opts->family_prio = AF_INET;
2975 }
2976 else if (strncmp(beg, "ipv6", end - beg) == 0) {
2977 rule->arg.resolv.opts->family_prio = AF_INET6;
2978 }
2979 else {
2980 goto do_resolve_parse_error;
2981 }
2982 }
2983
2984 cur_arg = cur_arg + 1;
2985
2986 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
2987 if (!expr)
2988 goto do_resolve_parse_error;
2989
2990
2991 where = 0;
2992 if (px->cap & PR_CAP_FE)
2993 where |= SMP_VAL_FE_HRQ_HDR;
2994 if (px->cap & PR_CAP_BE)
2995 where |= SMP_VAL_BE_HRQ_HDR;
2996
2997 if (!(expr->fetch->val & where)) {
2998 memprintf(err,
2999 "fetch method '%s' extracts information from '%s', none of which is available here",
3000 args[cur_arg-1], sample_src_names(expr->fetch->use));
3001 free(expr);
3002 return ACT_RET_PRS_ERR;
3003 }
3004 rule->arg.resolv.expr = expr;
3005 rule->action = ACT_CUSTOM;
3006 rule->action_ptr = resolv_action_do_resolve;
3007 *orig_arg = cur_arg;
3008
3009 rule->check_ptr = check_action_do_resolve;
3010 rule->release_ptr = release_resolv_action;
3011
3012 return ACT_RET_PRS_OK;
3013
3014 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003015 ha_free(&rule->arg.resolv.varname);
3016 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01003017 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3018 args[cur_arg]);
3019 return ACT_RET_PRS_ERR;
3020}
3021
3022static struct action_kw_list http_req_kws = { { }, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003023 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003024 { /* END */ }
3025}};
3026
3027INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3028
3029static struct action_kw_list tcp_req_cont_actions = {ILH, {
Amaury Denoyellee4a617c2021-05-06 15:33:09 +02003030 { "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
Emeric Brunc9437992021-02-12 19:42:55 +01003031 { /* END */ }
3032}};
3033
3034INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3035
3036/* Check an "http-request do-resolve" action.
3037 *
3038 * The function returns 1 in success case, otherwise, it returns 0 and err is
3039 * filled.
3040 */
3041int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3042{
3043 struct resolvers *resolvers = NULL;
3044
3045 if (rule->arg.resolv.resolvers_id == NULL) {
3046 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3047 return 0;
3048 }
3049
3050 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
3051 if (resolvers == NULL) {
3052 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
3053 return 0;
3054 }
3055 rule->arg.resolv.resolvers = resolvers;
3056
3057 return 1;
3058}
3059
3060void resolvers_setup_proxy(struct proxy *px)
3061{
3062 px->last_change = now.tv_sec;
3063 px->cap = PR_CAP_FE | PR_CAP_BE;
3064 px->maxconn = 0;
3065 px->conn_retries = 1;
3066 px->timeout.server = TICK_ETERNITY;
3067 px->timeout.client = TICK_ETERNITY;
3068 px->timeout.connect = TICK_ETERNITY;
3069 px->accept = NULL;
3070 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
3071 px->bind_proc = 0; /* will be filled by users */
3072}
3073
3074/*
3075 * Parse a <resolvers> section.
3076 * Returns the error code, 0 if OK, or any combination of :
3077 * - ERR_ABORT: must abort ASAP
3078 * - ERR_FATAL: we can continue parsing but not start the service
3079 * - ERR_WARN: a warning has been emitted
3080 * - ERR_ALERT: an alert has been emitted
3081 * Only the two first ones can stop processing, the two others are just
3082 * indicators.
3083 */
3084int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
3085{
3086 const char *err;
3087 int err_code = 0;
3088 char *errmsg = NULL;
3089 struct proxy *p;
3090
3091 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
3092 if (!*args[1]) {
3093 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
3094 err_code |= ERR_ALERT | ERR_ABORT;
3095 goto out;
3096 }
3097
3098 err = invalid_char(args[1]);
3099 if (err) {
3100 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
3101 file, linenum, *err, args[0], args[1]);
3102 err_code |= ERR_ALERT | ERR_ABORT;
3103 goto out;
3104 }
3105
3106 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
3107 /* Error if two resolvers owns the same name */
3108 if (strcmp(curr_resolvers->id, args[1]) == 0) {
3109 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
3110 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
3111 err_code |= ERR_ALERT | ERR_ABORT;
3112 }
3113 }
3114
3115 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
3116 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3117 err_code |= ERR_ALERT | ERR_ABORT;
3118 goto out;
3119 }
3120
3121 /* allocate new proxy to tcp servers */
3122 p = calloc(1, sizeof *p);
3123 if (!p) {
3124 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3125 err_code |= ERR_ALERT | ERR_FATAL;
3126 goto out;
3127 }
3128
3129 init_new_proxy(p);
3130 resolvers_setup_proxy(p);
3131 p->parent = curr_resolvers;
3132 p->id = strdup(args[1]);
3133 p->conf.args.file = p->conf.file = strdup(file);
3134 p->conf.args.line = p->conf.line = linenum;
3135 curr_resolvers->px = p;
3136
3137 /* default values */
Willy Tarreau2b718102021-04-21 07:32:39 +02003138 LIST_APPEND(&sec_resolvers, &curr_resolvers->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003139 curr_resolvers->conf.file = strdup(file);
3140 curr_resolvers->conf.line = linenum;
3141 curr_resolvers->id = strdup(args[1]);
3142 curr_resolvers->query_ids = EB_ROOT;
3143 /* default maximum response size */
3144 curr_resolvers->accepted_payload_size = 512;
3145 /* default hold period for nx, other, refuse and timeout is 30s */
3146 curr_resolvers->hold.nx = 30000;
3147 curr_resolvers->hold.other = 30000;
3148 curr_resolvers->hold.refused = 30000;
3149 curr_resolvers->hold.timeout = 30000;
3150 curr_resolvers->hold.obsolete = 0;
3151 /* default hold period for valid is 10s */
3152 curr_resolvers->hold.valid = 10000;
3153 curr_resolvers->timeout.resolve = 1000;
3154 curr_resolvers->timeout.retry = 1000;
3155 curr_resolvers->resolve_retries = 3;
3156 LIST_INIT(&curr_resolvers->nameservers);
3157 LIST_INIT(&curr_resolvers->resolutions.curr);
3158 LIST_INIT(&curr_resolvers->resolutions.wait);
3159 HA_SPIN_INIT(&curr_resolvers->lock);
3160 }
3161 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
3162 struct dns_nameserver *newnameserver = NULL;
3163 struct sockaddr_storage *sk;
3164 int port1, port2;
Emeric Brunc8f3e452021-04-07 16:04:54 +02003165 struct protocol *proto;
Emeric Brunc9437992021-02-12 19:42:55 +01003166
3167 if (!*args[2]) {
3168 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
3169 file, linenum, args[0]);
3170 err_code |= ERR_ALERT | ERR_FATAL;
3171 goto out;
3172 }
3173
3174 err = invalid_char(args[1]);
3175 if (err) {
3176 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
3177 file, linenum, *err, args[1]);
3178 err_code |= ERR_ALERT | ERR_FATAL;
3179 goto out;
3180 }
3181
3182 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3183 /* Error if two resolvers owns the same name */
3184 if (strcmp(newnameserver->id, args[1]) == 0) {
3185 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3186 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
3187 err_code |= ERR_ALERT | ERR_FATAL;
3188 }
3189 }
3190
Emeric Brunc8f3e452021-04-07 16:04:54 +02003191 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto,
3192 &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 +01003193 if (!sk) {
3194 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
3195 err_code |= ERR_ALERT | ERR_FATAL;
3196 goto out;
3197 }
3198
3199 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3200 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3201 err_code |= ERR_ALERT | ERR_ABORT;
3202 goto out;
3203 }
3204
Emeric Brunc8f3e452021-04-07 16:04:54 +02003205 if (proto && proto->ctrl_type == SOCK_STREAM) {
3206 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
3207 SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
3208 if (err_code & (ERR_FATAL|ERR_ABORT)) {
3209 err_code |= ERR_ABORT;
3210 goto out;
3211 }
3212
3213 if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
3214 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3215 err_code |= ERR_ALERT|ERR_ABORT;
3216 goto out;
3217 }
3218 }
3219 else if (dns_dgram_init(newnameserver, sk) < 0) {
Emeric Brunc9437992021-02-12 19:42:55 +01003220 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3221 err_code |= ERR_ALERT | ERR_ABORT;
3222 goto out;
3223 }
3224
3225 if ((newnameserver->conf.file = strdup(file)) == NULL) {
3226 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3227 err_code |= ERR_ALERT | ERR_ABORT;
3228 goto out;
3229 }
3230
3231 if ((newnameserver->id = strdup(args[1])) == NULL) {
3232 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
3233 err_code |= ERR_ALERT | ERR_ABORT;
3234 goto out;
3235 }
3236
3237 newnameserver->parent = curr_resolvers;
3238 newnameserver->process_responses = resolv_process_responses;
3239 newnameserver->conf.line = linenum;
3240 /* the nameservers are linked backward first */
Willy Tarreau2b718102021-04-21 07:32:39 +02003241 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003242 }
3243 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3244 struct dns_nameserver *newnameserver = NULL;
3245 const char *whitespace = "\r\n\t ";
3246 char *resolv_line = NULL;
3247 int resolv_linenum = 0;
3248 FILE *f = NULL;
3249 char *address = NULL;
3250 struct sockaddr_storage *sk = NULL;
3251 struct protocol *proto;
3252 int duplicate_name = 0;
3253
3254 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3255 ha_alert("parsing [%s:%d] : out of memory.\n",
3256 file, linenum);
3257 err_code |= ERR_ALERT | ERR_FATAL;
3258 goto resolv_out;
3259 }
3260
3261 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3262 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3263 file, linenum);
3264 err_code |= ERR_ALERT | ERR_FATAL;
3265 goto resolv_out;
3266 }
3267
3268 sk = calloc(1, sizeof(*sk));
3269 if (sk == NULL) {
3270 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3271 resolv_linenum);
3272 err_code |= ERR_ALERT | ERR_FATAL;
3273 goto resolv_out;
3274 }
3275
3276 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3277 resolv_linenum++;
3278 if (strncmp(resolv_line, "nameserver", 10) != 0)
3279 continue;
3280
3281 address = strtok(resolv_line + 10, whitespace);
3282 if (address == resolv_line + 10)
3283 continue;
3284
3285 if (address == NULL) {
3286 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3287 resolv_linenum);
3288 err_code |= ERR_WARN;
3289 continue;
3290 }
3291
3292 duplicate_name = 0;
3293 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3294 if (strcmp(newnameserver->id, address) == 0) {
3295 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",
3296 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3297 err_code |= ERR_WARN;
3298 duplicate_name = 1;
3299 }
3300 }
3301
3302 if (duplicate_name)
3303 continue;
3304
3305 memset(sk, 0, sizeof(*sk));
3306 if (!str2ip2(address, sk, 1)) {
3307 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3308 resolv_linenum, address);
3309 err_code |= ERR_WARN;
3310 continue;
3311 }
3312
3313 set_host_port(sk, 53);
3314
3315 proto = protocol_by_family(sk->ss_family);
3316 if (!proto || !proto->connect) {
3317 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3318 resolv_linenum, address);
3319 err_code |= ERR_WARN;
3320 continue;
3321 }
3322
3323 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3324 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3325 err_code |= ERR_ALERT | ERR_FATAL;
3326 goto resolv_out;
3327 }
3328
3329 if (dns_dgram_init(newnameserver, sk) < 0) {
3330 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3331 err_code |= ERR_ALERT | ERR_FATAL;
3332 free(newnameserver);
3333 goto resolv_out;
3334 }
3335
3336 newnameserver->conf.file = strdup("/etc/resolv.conf");
3337 if (newnameserver->conf.file == NULL) {
3338 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3339 err_code |= ERR_ALERT | ERR_FATAL;
3340 free(newnameserver);
3341 goto resolv_out;
3342 }
3343
3344 newnameserver->id = strdup(address);
3345 if (newnameserver->id == NULL) {
3346 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3347 err_code |= ERR_ALERT | ERR_FATAL;
3348 free((char *)newnameserver->conf.file);
3349 free(newnameserver);
3350 goto resolv_out;
3351 }
3352
3353 newnameserver->parent = curr_resolvers;
3354 newnameserver->process_responses = resolv_process_responses;
3355 newnameserver->conf.line = resolv_linenum;
Willy Tarreau2b718102021-04-21 07:32:39 +02003356 LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
Emeric Brunc9437992021-02-12 19:42:55 +01003357 }
3358
3359resolv_out:
3360 free(sk);
3361 free(resolv_line);
3362 if (f != NULL)
3363 fclose(f);
3364 }
3365 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3366 const char *res;
3367 unsigned int time;
3368
3369 if (!*args[2]) {
3370 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3371 file, linenum, args[0]);
3372 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3373 err_code |= ERR_ALERT | ERR_FATAL;
3374 goto out;
3375 }
3376 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3377 if (res == PARSE_TIME_OVER) {
3378 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3379 file, linenum, args[1], args[0]);
3380 err_code |= ERR_ALERT | ERR_FATAL;
3381 goto out;
3382 }
3383 else if (res == PARSE_TIME_UNDER) {
3384 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3385 file, linenum, args[1], args[0]);
3386 err_code |= ERR_ALERT | ERR_FATAL;
3387 goto out;
3388 }
3389 else if (res) {
3390 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3391 file, linenum, *res, args[0]);
3392 err_code |= ERR_ALERT | ERR_FATAL;
3393 goto out;
3394 }
3395 if (strcmp(args[1], "nx") == 0)
3396 curr_resolvers->hold.nx = time;
3397 else if (strcmp(args[1], "other") == 0)
3398 curr_resolvers->hold.other = time;
3399 else if (strcmp(args[1], "refused") == 0)
3400 curr_resolvers->hold.refused = time;
3401 else if (strcmp(args[1], "timeout") == 0)
3402 curr_resolvers->hold.timeout = time;
3403 else if (strcmp(args[1], "valid") == 0)
3404 curr_resolvers->hold.valid = time;
3405 else if (strcmp(args[1], "obsolete") == 0)
3406 curr_resolvers->hold.obsolete = time;
3407 else {
3408 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3409 file, linenum, args[0], args[1]);
3410 err_code |= ERR_ALERT | ERR_FATAL;
3411 goto out;
3412 }
3413
3414 }
3415 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3416 int i = 0;
3417
3418 if (!*args[1]) {
3419 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3420 file, linenum, args[0]);
3421 err_code |= ERR_ALERT | ERR_FATAL;
3422 goto out;
3423 }
3424
3425 i = atoi(args[1]);
3426 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3427 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3428 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3429 err_code |= ERR_ALERT | ERR_FATAL;
3430 goto out;
3431 }
3432
3433 curr_resolvers->accepted_payload_size = i;
3434 }
3435 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3436 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3437 file, linenum, args[0]);
3438 err_code |= ERR_ALERT | ERR_FATAL;
3439 goto out;
3440 }
3441 else if (strcmp(args[0], "resolve_retries") == 0) {
3442 if (!*args[1]) {
3443 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3444 file, linenum, args[0]);
3445 err_code |= ERR_ALERT | ERR_FATAL;
3446 goto out;
3447 }
3448 curr_resolvers->resolve_retries = atoi(args[1]);
3449 }
3450 else if (strcmp(args[0], "timeout") == 0) {
3451 if (!*args[1]) {
3452 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3453 file, linenum, args[0]);
3454 err_code |= ERR_ALERT | ERR_FATAL;
3455 goto out;
3456 }
3457 else if (strcmp(args[1], "retry") == 0 ||
3458 strcmp(args[1], "resolve") == 0) {
3459 const char *res;
3460 unsigned int tout;
3461
3462 if (!*args[2]) {
3463 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3464 file, linenum, args[0], args[1]);
3465 err_code |= ERR_ALERT | ERR_FATAL;
3466 goto out;
3467 }
3468 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3469 if (res == PARSE_TIME_OVER) {
3470 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3471 file, linenum, args[2], args[0], args[1]);
3472 err_code |= ERR_ALERT | ERR_FATAL;
3473 goto out;
3474 }
3475 else if (res == PARSE_TIME_UNDER) {
3476 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3477 file, linenum, args[2], args[0], args[1]);
3478 err_code |= ERR_ALERT | ERR_FATAL;
3479 goto out;
3480 }
3481 else if (res) {
3482 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3483 file, linenum, *res, args[0], args[1]);
3484 err_code |= ERR_ALERT | ERR_FATAL;
3485 goto out;
3486 }
3487 if (args[1][2] == 't')
3488 curr_resolvers->timeout.retry = tout;
3489 else
3490 curr_resolvers->timeout.resolve = tout;
3491 }
3492 else {
3493 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3494 file, linenum, args[0], args[1]);
3495 err_code |= ERR_ALERT | ERR_FATAL;
3496 goto out;
3497 }
3498 }
3499 else if (*args[0] != 0) {
3500 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3501 err_code |= ERR_ALERT | ERR_FATAL;
3502 goto out;
3503 }
3504
3505 out:
3506 free(errmsg);
3507 return err_code;
3508}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003509int cfg_post_parse_resolvers()
3510{
3511 int err_code = 0;
3512 struct server *srv;
3513
3514 if (curr_resolvers) {
3515
3516 /* prepare forward server descriptors */
3517 if (curr_resolvers->px) {
3518 srv = curr_resolvers->px->srv;
3519 while (srv) {
Emeric Brun56fc5d92021-02-12 20:05:45 +01003520 /* init ssl if needed */
3521 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3522 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3523 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3524 err_code |= ERR_ALERT | ERR_FATAL;
3525 break;
3526 }
3527 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01003528 srv = srv->next;
3529 }
3530 }
3531 }
3532 curr_resolvers = NULL;
3533 return err_code;
3534}
Emeric Brunc9437992021-02-12 19:42:55 +01003535
Emeric Brun56fc5d92021-02-12 20:05:45 +01003536REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003537REGISTER_POST_DEINIT(resolvers_deinit);
3538REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);