blob: 2394db52281a1f3b46703859684a787ddae30cdb [file] [log] [blame]
Baptiste Assmann325137d2015-04-13 23:40:55 +02001/*
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 Brun32131d42021-06-11 10:48:45 +020022#include <import/ebistree.h>
23
Willy Tarreau122eba92020-06-04 10:15:32 +020024#include <haproxy/action.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020025#include <haproxy/api.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020026#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020027#include <haproxy/channel.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020028#include <haproxy/check.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020029#include <haproxy/cli.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020030#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020031#include <haproxy/dns.h>
Willy Tarreau8d366972020-05-27 16:10:29 +020032#include <haproxy/errors.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020033#include <haproxy/fd.h>
34#include <haproxy/global.h>
Willy Tarreauc761f842020-06-04 11:40:28 +020035#include <haproxy/http_rules.h>
Willy Tarreauaeed4a82020-06-04 22:01:04 +020036#include <haproxy/log.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020037#include <haproxy/net_helper.h>
Willy Tarreaua264d962020-06-04 22:29:18 +020038#include <haproxy/proxy.h>
Willy Tarreaue6ce10b2020-06-04 15:33:47 +020039#include <haproxy/sample.h>
Willy Tarreau1e56f922020-06-04 23:20:13 +020040#include <haproxy/server.h>
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +020041#include <haproxy/stats.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020042#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020043#include <haproxy/task.h>
Willy Tarreau8b550af2020-06-04 17:42:48 +020044#include <haproxy/tcp_rules.h>
Willy Tarreauc2f7c582020-06-02 18:15:32 +020045#include <haproxy/ticks.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020046#include <haproxy/time.h>
Willy Tarreaua1718922020-06-04 16:25:31 +020047#include <haproxy/vars.h>
Baptiste Assmann325137d2015-04-13 23:40:55 +020048
Baptiste Assmann325137d2015-04-13 23:40:55 +020049
Christopher Faulet67957bd2017-09-27 11:00:59 +020050struct list dns_resolvers = LIST_HEAD_INIT(dns_resolvers);
51struct list dns_srvrq_list = LIST_HEAD_INIT(dns_srvrq_list);
Baptiste Assmann325137d2015-04-13 23:40:55 +020052
Tim Duesterhusfcac33d2020-01-18 02:04:12 +010053static THREAD_LOCAL uint64_t dns_query_id_seed = 0; /* random seed */
Willy Tarreau8ceae722018-11-26 11:58:30 +010054
55DECLARE_STATIC_POOL(dns_answer_item_pool, "dns_answer_item", sizeof(struct dns_answer_item));
56DECLARE_STATIC_POOL(dns_resolution_pool, "dns_resolution", sizeof(struct dns_resolution));
Baptiste Assmanndfd35fd2019-01-21 08:18:09 +010057DECLARE_POOL(dns_requester_pool, "dns_requester", sizeof(struct dns_requester));
Willy Tarreau8ceae722018-11-26 11:58:30 +010058
Christopher Faulet67957bd2017-09-27 11:00:59 +020059static unsigned int resolution_uuid = 1;
Baptiste Assmann333939c2019-01-21 08:34:50 +010060unsigned int dns_failed_resolutions = 0;
Baptiste Assmann201c07f2017-05-22 15:17:15 +020061
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +020062enum {
63 DNS_STAT_ID,
64 DNS_STAT_SND_ERROR,
65 DNS_STAT_VALID,
66 DNS_STAT_UPDATE,
67 DNS_STAT_CNAME,
68 DNS_STAT_CNAME_ERROR,
69 DNS_STAT_ANY_ERR,
70 DNS_STAT_NX,
71 DNS_STAT_TIMEOUT,
72 DNS_STAT_REFUSED,
73 DNS_STAT_OTHER,
74 DNS_STAT_INVALID,
75 DNS_STAT_TOO_BIG,
76 DNS_STAT_TRUNCATED,
77 DNS_STAT_OUTDATED,
78 DNS_STAT_END,
79};
80
81static struct name_desc dns_stats[] = {
82 [DNS_STAT_ID] = { .name = "id", .desc = "ID" },
83 [DNS_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
84 [DNS_STAT_VALID] = { .name = "valid", .desc = "Valid" },
85 [DNS_STAT_UPDATE] = { .name = "update", .desc = "Update" },
86 [DNS_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
87 [DNS_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
88 [DNS_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
89 [DNS_STAT_NX] = { .name = "nx", .desc = "NX" },
90 [DNS_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
91 [DNS_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
92 [DNS_STAT_OTHER] = { .name = "other", .desc = "Other" },
93 [DNS_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
94 [DNS_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
95 [DNS_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
96 [DNS_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
97};
98
99static struct dns_counters dns_counters;
100
101static void dns_fill_stats(void *d, struct field *stats)
102{
103 struct dns_counters *counters = d;
104 stats[DNS_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
105 stats[DNS_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
106 stats[DNS_STAT_VALID] = mkf_u64(FN_GAUGE, counters->valid);
107 stats[DNS_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->update);
108 stats[DNS_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->cname);
109 stats[DNS_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->cname_error);
110 stats[DNS_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->any_err);
111 stats[DNS_STAT_NX] = mkf_u64(FN_GAUGE, counters->nx);
112 stats[DNS_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->timeout);
113 stats[DNS_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->refused);
114 stats[DNS_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->other);
115 stats[DNS_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->invalid);
116 stats[DNS_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->too_big);
117 stats[DNS_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->truncated);
118 stats[DNS_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->outdated);
119}
120
121static struct stats_module dns_stats_module = {
122 .name = "dns",
123 .domain_flags = STATS_DOMAIN_DNS << STATS_DOMAIN,
124 .fill_stats = dns_fill_stats,
125 .stats = dns_stats,
126 .stats_count = DNS_STAT_END,
127 .counters = &dns_counters,
128 .counters_size = sizeof(dns_counters),
129 .clearable = 0,
130};
131
132INITCALL1(STG_REGISTER, stats_register_module, &dns_stats_module);
133
Christopher Faulet67957bd2017-09-27 11:00:59 +0200134/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
135 * no match is found.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200136 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200137struct dns_resolvers *find_resolvers_by_id(const char *id)
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200138{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200139 struct dns_resolvers *res;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200140
Christopher Faulet67957bd2017-09-27 11:00:59 +0200141 list_for_each_entry(res, &dns_resolvers, list) {
142 if (!strcmp(res->id, id))
143 return res;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200144 }
Christopher Faulet67957bd2017-09-27 11:00:59 +0200145 return NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200146}
147
Olivier Houchardb17b8842020-04-01 18:30:27 +0200148/* Compare hostnames in a case-insensitive way .
149 * Returns 0 if they are the same, non-zero otherwise
150 */
151static __inline int dns_hostname_cmp(const char *name1, const char *name2, int len)
152{
153 int i;
154
155 for (i = 0; i < len; i++)
Willy Tarreauf278eec2020-07-05 21:46:32 +0200156 if (tolower((unsigned char)name1[i]) != tolower((unsigned char)name2[i]))
Olivier Houchardb17b8842020-04-01 18:30:27 +0200157 return -1;
158 return 0;
159}
160
Christopher Faulet67957bd2017-09-27 11:00:59 +0200161/* Returns a pointer on the SRV request matching the name <name> for the proxy
162 * <px>. NULL is returned if no match is found.
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200163 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200164struct dns_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200165{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200166 struct dns_srvrq *srvrq;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200167
Christopher Faulet67957bd2017-09-27 11:00:59 +0200168 list_for_each_entry(srvrq, &dns_srvrq_list, list) {
169 if (srvrq->proxy == px && !strcmp(srvrq->name, name))
170 return srvrq;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200171 }
Christopher Faulet67957bd2017-09-27 11:00:59 +0200172 return NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200173}
174
Christopher Faulet67957bd2017-09-27 11:00:59 +0200175/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
176 * NULL if an error occurred. */
177struct dns_srvrq *new_dns_srvrq(struct server *srv, char *fqdn)
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200178{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200179 struct proxy *px = srv->proxy;
180 struct dns_srvrq *srvrq = NULL;
181 int fqdn_len, hostname_dn_len;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200182
Christopher Faulet67957bd2017-09-27 11:00:59 +0200183 fqdn_len = strlen(fqdn);
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200184 hostname_dn_len = dns_str_to_dn_label(fqdn, fqdn_len + 1, trash.area,
185 trash.size);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200186 if (hostname_dn_len == -1) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100187 ha_alert("config : %s '%s', server '%s': failed to parse FQDN '%s'\n",
188 proxy_type_str(px), px->id, srv->id, fqdn);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200189 goto err;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200190 }
191
Christopher Faulet67957bd2017-09-27 11:00:59 +0200192 if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100193 ha_alert("config : %s '%s', server '%s': out of memory\n",
194 proxy_type_str(px), px->id, srv->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200195 goto err;
196 }
197 srvrq->obj_type = OBJ_TYPE_SRVRQ;
198 srvrq->proxy = px;
199 srvrq->name = strdup(fqdn);
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200200 srvrq->hostname_dn = strdup(trash.area);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200201 srvrq->hostname_dn_len = hostname_dn_len;
202 if (!srvrq->name || !srvrq->hostname_dn) {
Christopher Faulet767a84b2017-11-24 16:50:31 +0100203 ha_alert("config : %s '%s', server '%s': out of memory\n",
204 proxy_type_str(px), px->id, srv->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200205 goto err;
206 }
Emeric Brun32131d42021-06-11 10:48:45 +0200207 LIST_INIT(&srvrq->attached_servers);
208 srvrq->named_servers = EB_ROOT;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200209 LIST_ADDQ(&dns_srvrq_list, &srvrq->list);
210 return srvrq;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200211
Christopher Faulet67957bd2017-09-27 11:00:59 +0200212 err:
213 if (srvrq) {
214 free(srvrq->name);
215 free(srvrq->hostname_dn);
216 free(srvrq);
217 }
218 return NULL;
219}
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200220
Baptiste Assmann99348c32021-03-10 12:22:18 +0100221/* finds and return the SRV answer item associated to a requester (whose type is 'server').
222 *
223 * returns NULL in case of error or not found.
224 */
225struct dns_answer_item *find_srvrq_answer_record(const struct dns_requester *requester)
226{
227 struct dns_resolution *res;
228 struct dns_answer_item *item;
229 struct server *srv;
230
231 if (!requester)
232 return NULL;
233
234 if ((srv = objt_server(requester->owner)) == NULL)
235 return NULL;
236 /* check if the server is managed by a SRV record */
237 if (srv->srvrq == NULL)
238 return NULL;
239
240 res = srv->srvrq->dns_requester->resolution;
241 /* search an ANSWER record whose target points to the server's hostname and whose port is
242 * the same as server's svc_port */
243 list_for_each_entry(item, &res->response.answer_list, list) {
244 if (dns_hostname_cmp(srv->hostname_dn, item->target, srv->hostname_dn_len) == 0 &&
245 (srv->svc_port == item->port))
246 return item;
247 }
248
249 return NULL;
250}
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200251
Christopher Faulet67957bd2017-09-27 11:00:59 +0200252/* 2 bytes random generator to generate DNS query ID */
253static inline uint16_t dns_rnd16(void)
254{
Christopher Fauletb2812a62017-10-04 16:17:58 +0200255 if (!dns_query_id_seed)
256 dns_query_id_seed = now_ms;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200257 dns_query_id_seed ^= dns_query_id_seed << 13;
258 dns_query_id_seed ^= dns_query_id_seed >> 7;
259 dns_query_id_seed ^= dns_query_id_seed << 17;
260 return dns_query_id_seed;
261}
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200262
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200263
Christopher Faulet67957bd2017-09-27 11:00:59 +0200264static inline int dns_resolution_timeout(struct dns_resolution *res)
265{
Baptiste Assmannf50e1ac2019-11-07 11:02:18 +0100266 return res->resolvers->timeout.resolve;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200267}
268
Christopher Faulet67957bd2017-09-27 11:00:59 +0200269/* Updates a resolvers' task timeout for next wake up and queue it */
270static void dns_update_resolvers_timeout(struct dns_resolvers *resolvers)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200271{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200272 struct dns_resolution *res;
273 int next;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200274
Christopher Faulet67957bd2017-09-27 11:00:59 +0200275 next = tick_add(now_ms, resolvers->timeout.resolve);
276 if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
277 res = LIST_NEXT(&resolvers->resolutions.curr, struct dns_resolution *, list);
278 next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
279 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200280
Christopher Faulet67957bd2017-09-27 11:00:59 +0200281 list_for_each_entry(res, &resolvers->resolutions.wait, list)
282 next = MIN(next, tick_add(res->last_resolution, dns_resolution_timeout(res)));
Baptiste Assmann325137d2015-04-13 23:40:55 +0200283
Christopher Faulet67957bd2017-09-27 11:00:59 +0200284 resolvers->t->expire = next;
285 task_queue(resolvers->t);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200286}
287
Christopher Faulet67957bd2017-09-27 11:00:59 +0200288/* Opens an UDP socket on the namesaver's IP/Port, if required. Returns 0 on
289 * success, -1 otherwise.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200290 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200291static int dns_connect_namesaver(struct dns_nameserver *ns)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200292{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200293 struct dgram_conn *dgram = ns->dgram;
294 int fd;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200295
Christopher Faulet67957bd2017-09-27 11:00:59 +0200296 /* Already connected */
297 if (dgram->t.sock.fd != -1)
298 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200299
Christopher Faulet67957bd2017-09-27 11:00:59 +0200300 /* Create an UDP socket and connect it on the nameserver's IP/Port */
301 if ((fd = socket(ns->addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
302 send_log(NULL, LOG_WARNING,
303 "DNS : resolvers '%s': can't create socket for nameserver '%s'.\n",
304 ns->resolvers->id, ns->id);
305 return -1;
306 }
307 if (connect(fd, (struct sockaddr*)&ns->addr, get_addr_len(&ns->addr)) == -1) {
308 send_log(NULL, LOG_WARNING,
309 "DNS : resolvers '%s': can't connect socket for nameserver '%s'.\n",
310 ns->resolvers->id, ns->id);
311 close(fd);
312 return -1;
313 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200314
Christopher Faulet67957bd2017-09-27 11:00:59 +0200315 /* Make the socket non blocking */
316 fcntl(fd, F_SETFL, O_NONBLOCK);
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200317
Christopher Faulet67957bd2017-09-27 11:00:59 +0200318 /* Add the fd in the fd list and update its parameters */
319 dgram->t.sock.fd = fd;
Willy Tarreaua9786b62018-01-25 07:22:13 +0100320 fd_insert(fd, dgram, dgram_fd_handler, MAX_THREADS_MASK);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200321 fd_want_recv(fd);
322 return 0;
323}
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200324
Christopher Faulet67957bd2017-09-27 11:00:59 +0200325/* Forges a DNS query. It needs the following information from the caller:
326 * - <query_id> : the DNS query id corresponding to this query
327 * - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
328 * - <hostname_dn> : hostname in domain name format
329 * - <hostname_dn_len> : length of <hostname_dn>
330 *
331 * To store the query, the caller must pass a buffer <buf> and its size
332 * <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
333 * too short.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200334 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200335static int dns_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
336 char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200337{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200338 struct dns_header dns_hdr;
339 struct dns_question qinfo;
340 struct dns_additional_record edns;
341 char *p = buf;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200342
Christopher Faulet67957bd2017-09-27 11:00:59 +0200343 if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
344 return -1;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200345
Christopher Faulet67957bd2017-09-27 11:00:59 +0200346 memset(buf, 0, bufsize);
Baptiste Assmannfa4a6632017-05-04 09:05:00 +0200347
Christopher Faulet67957bd2017-09-27 11:00:59 +0200348 /* Set dns query headers */
349 dns_hdr.id = (unsigned short) htons(query_id);
350 dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
351 dns_hdr.qdcount = htons(1); /* 1 question */
352 dns_hdr.ancount = 0;
353 dns_hdr.nscount = 0;
354 dns_hdr.arcount = htons(1);
355 memcpy(p, &dns_hdr, sizeof(dns_hdr));
356 p += sizeof(dns_hdr);
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200357
Christopher Faulet67957bd2017-09-27 11:00:59 +0200358 /* Set up query hostname */
359 memcpy(p, hostname_dn, hostname_dn_len);
360 p += hostname_dn_len;
361 *p++ = 0;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200362
Christopher Faulet67957bd2017-09-27 11:00:59 +0200363 /* Set up query info (type and class) */
364 qinfo.qtype = htons(query_type);
365 qinfo.qclass = htons(DNS_RCLASS_IN);
366 memcpy(p, &qinfo, sizeof(qinfo));
367 p += sizeof(qinfo);
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200368
Christopher Faulet67957bd2017-09-27 11:00:59 +0200369 /* Set the DNS extension */
370 edns.name = 0;
371 edns.type = htons(DNS_RTYPE_OPT);
372 edns.udp_payload_size = htons(accepted_payload_size);
373 edns.extension = 0;
374 edns.data_length = 0;
375 memcpy(p, &edns, sizeof(edns));
376 p += sizeof(edns);
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200377
Christopher Faulet67957bd2017-09-27 11:00:59 +0200378 return (p - buf);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200379}
380
Christopher Faulet67957bd2017-09-27 11:00:59 +0200381/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
382 * success, -1 otherwise.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200383 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200384static int dns_send_query(struct dns_resolution *resolution)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200385{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200386 struct dns_resolvers *resolvers = resolution->resolvers;
387 struct dns_nameserver *ns;
Willy Tarreau0eae6322019-12-20 11:18:54 +0100388 int len;
389
390 /* Update resolution */
391 resolution->nb_queries = 0;
392 resolution->nb_responses = 0;
393 resolution->last_query = now_ms;
394
395 len = dns_build_query(resolution->query_id, resolution->query_type,
396 resolvers->accepted_payload_size,
397 resolution->hostname_dn, resolution->hostname_dn_len,
398 trash.area, trash.size);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200399
Christopher Faulet67957bd2017-09-27 11:00:59 +0200400 list_for_each_entry(ns, &resolvers->nameservers, list) {
401 int fd = ns->dgram->t.sock.fd;
Willy Tarreau0eae6322019-12-20 11:18:54 +0100402 int ret;
403
Christopher Faulet67957bd2017-09-27 11:00:59 +0200404 if (fd == -1) {
405 if (dns_connect_namesaver(ns) == -1)
406 continue;
407 fd = ns->dgram->t.sock.fd;
408 resolvers->nb_nameservers++;
409 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200410
Willy Tarreau0eae6322019-12-20 11:18:54 +0100411 if (len < 0)
412 goto snd_error;
413
414 ret = send(fd, trash.area, len, 0);
415 if (ret == len) {
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +0200416 ns->counters->sent++;
Willy Tarreau0eae6322019-12-20 11:18:54 +0100417 resolution->nb_queries++;
418 continue;
419 }
Emeric Brun751872e2021-05-04 18:16:53 +0200420 else if (ret == -1) {
421 if (errno == EAGAIN) {
422 /* retry once the socket is ready */
423 fd_cant_send(fd);
424 continue;
425 }
Willy Tarreau0eae6322019-12-20 11:18:54 +0100426
Emeric Brun751872e2021-05-04 18:16:53 +0200427 /* purge the fd and set sock.fd to -1
428 * to create a new one during next
429 * send_query attempt to the same
430 * nameserver
431 */
432 fd_delete(fd);
433 ns->dgram->t.sock.fd = -1;
Willy Tarreau0eae6322019-12-20 11:18:54 +0100434 }
435
436 snd_error:
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +0200437 ns->counters->snd_error++;
Willy Tarreau0eae6322019-12-20 11:18:54 +0100438 resolution->nb_queries++;
439 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200440
Christopher Faulet67957bd2017-09-27 11:00:59 +0200441 /* Push the resolution at the end of the active list */
442 LIST_DEL(&resolution->list);
443 LIST_ADDQ(&resolvers->resolutions.curr, &resolution->list);
444 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200445}
446
Christopher Faulet67957bd2017-09-27 11:00:59 +0200447/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
448 * skipped and -1 if an error occurred.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200449 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200450static int
451dns_run_resolution(struct dns_resolution *resolution)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200452{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200453 struct dns_resolvers *resolvers = resolution->resolvers;
454 int query_id, i;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200455
Christopher Faulet67957bd2017-09-27 11:00:59 +0200456 /* Avoid sending requests for resolutions that don't yet have an
457 * hostname, ie resolutions linked to servers that do not yet have an
458 * fqdn */
459 if (!resolution->hostname_dn)
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200460 return 0;
461
Christopher Faulet67957bd2017-09-27 11:00:59 +0200462 /* Check if a resolution has already been started for this server return
463 * directly to avoid resolution pill up. */
464 if (resolution->step != RSLV_STEP_NONE)
465 return 0;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200466
Christopher Faulet67957bd2017-09-27 11:00:59 +0200467 /* Generates a new query id. We try at most 100 times to find a free
468 * query id */
469 for (i = 0; i < 100; ++i) {
470 query_id = dns_rnd16();
471 if (!eb32_lookup(&resolvers->query_ids, query_id))
Olivier Houchard8da5f982017-08-04 18:35:36 +0200472 break;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200473 query_id = -1;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200474 }
Christopher Faulet67957bd2017-09-27 11:00:59 +0200475 if (query_id == -1) {
476 send_log(NULL, LOG_NOTICE,
477 "could not generate a query id for %s, in resolvers %s.\n",
478 resolution->hostname_dn, resolvers->id);
479 return -1;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200480 }
481
Christopher Faulet67957bd2017-09-27 11:00:59 +0200482 /* Update resolution parameters */
483 resolution->query_id = query_id;
484 resolution->qid.key = query_id;
485 resolution->step = RSLV_STEP_RUNNING;
486 resolution->query_type = resolution->prefered_query_type;
487 resolution->try = resolvers->resolve_retries;
488 eb32_insert(&resolvers->query_ids, &resolution->qid);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200489
Christopher Faulet67957bd2017-09-27 11:00:59 +0200490 /* Send the DNS query */
491 resolution->try -= 1;
492 dns_send_query(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +0200493 return 1;
494}
495
Christopher Faulet67957bd2017-09-27 11:00:59 +0200496/* Performs a name resolution for the requester <req> */
497void dns_trigger_resolution(struct dns_requester *req)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200498{
Christopher Faulet67957bd2017-09-27 11:00:59 +0200499 struct dns_resolvers *resolvers;
500 struct dns_resolution *res;
501 int exp;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200502
Christopher Faulet67957bd2017-09-27 11:00:59 +0200503 if (!req || !req->resolution)
504 return;
505 res = req->resolution;
506 resolvers = res->resolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200507
Christopher Faulet67957bd2017-09-27 11:00:59 +0200508 /* The resolution must not be triggered yet. Use the cached response, if
509 * valid */
510 exp = tick_add(res->last_resolution, resolvers->hold.valid);
Olivier Houchardf3d9e602018-05-22 18:40:07 +0200511 if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
512 !tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
513 task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200514}
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200515
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200516
Christopher Faulet67957bd2017-09-27 11:00:59 +0200517/* Resets some resolution parameters to initial values and also delete the query
518 * ID from the resolver's tree.
519 */
520static void dns_reset_resolution(struct dns_resolution *resolution)
521{
522 /* update resolution status */
523 resolution->step = RSLV_STEP_NONE;
524 resolution->try = 0;
525 resolution->last_resolution = now_ms;
526 resolution->nb_queries = 0;
527 resolution->nb_responses = 0;
528 resolution->query_type = resolution->prefered_query_type;
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200529
Christopher Faulet67957bd2017-09-27 11:00:59 +0200530 /* clean up query id */
531 eb32_delete(&resolution->qid);
532 resolution->query_id = 0;
533 resolution->qid.key = 0;
534}
Baptiste Assmann201c07f2017-05-22 15:17:15 +0200535
Christopher Faulet67957bd2017-09-27 11:00:59 +0200536/* Returns the query id contained in a DNS response */
537static inline unsigned short dns_response_get_query_id(unsigned char *resp)
538{
539 return resp[0] * 256 + resp[1];
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200540}
541
Christopher Faulet67957bd2017-09-27 11:00:59 +0200542
543/* Analyses, re-builds and copies the name <name> from the DNS response packet
544 * <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
545 * for compressed data. The result is copied into <dest>, ensuring we don't
546 * overflow using <dest_len> Returns the number of bytes the caller can move
547 * forward. If 0 it means an error occurred while parsing the name. <offset> is
548 * the number of bytes the caller could move forward.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200549 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200550int dns_read_name(unsigned char *buffer, unsigned char *bufend,
551 unsigned char *name, char *destination, int dest_len,
Remi Gacogne58df5ae2018-12-05 17:52:54 +0100552 int *offset, unsigned int depth)
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200553{
554 int nb_bytes = 0, n = 0;
555 int label_len;
556 unsigned char *reader = name;
557 char *dest = destination;
558
559 while (1) {
Remi Gacogne2d19fbc2018-12-05 17:55:10 +0100560 if (reader >= bufend)
561 goto err;
562
Christopher Faulet67957bd2017-09-27 11:00:59 +0200563 /* Name compression is in use */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200564 if ((*reader & 0xc0) == 0xc0) {
Remi Gacogne2d19fbc2018-12-05 17:55:10 +0100565 if (reader + 1 >= bufend)
566 goto err;
567
Christopher Faulet67957bd2017-09-27 11:00:59 +0200568 /* Must point BEFORE current position */
569 if ((buffer + reader[1]) > reader)
570 goto err;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200571
Remi Gacogne58df5ae2018-12-05 17:52:54 +0100572 if (depth++ > 100)
573 goto err;
574
Nikhil Agrawal2fa66c32018-12-20 10:50:59 +0530575 n = dns_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
Remi Gacogne58df5ae2018-12-05 17:52:54 +0100576 dest, dest_len - nb_bytes, offset, depth);
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200577 if (n == 0)
Christopher Faulet67957bd2017-09-27 11:00:59 +0200578 goto err;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200579
Christopher Faulet67957bd2017-09-27 11:00:59 +0200580 dest += n;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200581 nb_bytes += n;
582 goto out;
583 }
584
585 label_len = *reader;
586 if (label_len == 0)
587 goto out;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200588
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200589 /* Check if:
590 * - we won't read outside the buffer
591 * - there is enough place in the destination
592 */
593 if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
Christopher Faulet67957bd2017-09-27 11:00:59 +0200594 goto err;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200595
596 /* +1 to take label len + label string */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200597 label_len++;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200598
599 memcpy(dest, reader, label_len);
600
Christopher Faulet67957bd2017-09-27 11:00:59 +0200601 dest += label_len;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200602 nb_bytes += label_len;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200603 reader += label_len;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200604 }
605
Christopher Faulet67957bd2017-09-27 11:00:59 +0200606 out:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200607 /* offset computation:
608 * parse from <name> until finding either NULL or a pointer "c0xx"
609 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200610 reader = name;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200611 *offset = 0;
612 while (reader < bufend) {
613 if ((reader[0] & 0xc0) == 0xc0) {
614 *offset += 2;
615 break;
616 }
617 else if (*reader == 0) {
618 *offset += 1;
619 break;
620 }
621 *offset += 1;
622 ++reader;
623 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200624 return nb_bytes;
625
Christopher Faulet67957bd2017-09-27 11:00:59 +0200626 err:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200627 return 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200628}
629
Christopher Fauletcab96e12021-06-15 16:08:48 +0200630/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
631 * happens when an SRV item is purged or when the server status is considered as
632 * obsolete.
633 *
634 * Must be called with the DNS lock held.
635 */
636static void dns_srvrq_cleanup_srv(struct server *srv)
637{
638 dns_unlink_resolution(srv->dns_requester, 0);
639 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
640 srvrq_update_srv_status(srv, 1);
641 free(srv->hostname);
642 free(srv->hostname_dn);
643 srv->hostname = NULL;
644 srv->hostname_dn = NULL;
645 srv->hostname_dn_len = 0;
646 memset(&srv->addr, 0, sizeof(srv->addr));
647 srv->svc_port = 0;
648 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet172c3802021-06-15 16:14:37 +0200649
650 ebpt_delete(&srv->host_dn);
651 free(srv->host_dn.key);
652 srv->host_dn.key = NULL;
653
Christopher Fauletcab96e12021-06-15 16:08:48 +0200654 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
655 LIST_DEL(&srv->srv_rec_item);
656 LIST_ADDQ(&srv->srvrq->attached_servers, &srv->srv_rec_item);
Christopher Faulet25fbca42021-06-15 16:17:17 +0200657
658 srv->srvrq_check->expire = TICK_ETERNITY;
659}
660
661/* Takes care to cleanup a server resolution when it is outdated. This only
662 * happens for a server relying on a SRV record.
663 */
664static struct task *dns_srvrq_expire_task(struct task *t, void *context, unsigned short state)
665{
666 struct server *srv = context;
667
668 if (!tick_is_expired(t->expire, now_ms))
669 goto end;
670
671 HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers);
672 dns_srvrq_cleanup_srv(srv);
673 HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers);
674
675 end:
676 return t;
Christopher Fauletcab96e12021-06-15 16:08:48 +0200677}
678
Christopher Faulet67957bd2017-09-27 11:00:59 +0200679/* Checks for any obsolete record, also identify any SRV request, and try to
680 * find a corresponding server.
681*/
682static void dns_check_dns_response(struct dns_resolution *res)
683{
684 struct dns_resolvers *resolvers = res->resolvers;
685 struct dns_requester *req, *reqback;
686 struct dns_answer_item *item, *itemback;
Emeric Brunca8e3552021-06-11 10:08:05 +0200687 struct server *srv, *srvback;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200688 struct dns_srvrq *srvrq;
689
690 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
Christopher Faulet5a891752020-09-08 10:06:01 +0200691 struct dns_answer_item *ar_item = item->ar_item;
692
693 /* clean up obsolete Additional record */
Christopher Faulet8b6d5b02021-03-11 09:36:05 +0100694 if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
Christopher Faulet02cf7b72021-03-10 18:38:37 +0100695 /* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
696 * item is also obsolete.
697 */
Christopher Faulet5a891752020-09-08 10:06:01 +0200698 pool_free(dns_answer_item_pool, ar_item);
699 item->ar_item = NULL;
700 }
Christopher Faulet67957bd2017-09-27 11:00:59 +0200701
702 /* Remove obsolete items */
Christopher Faulet8b6d5b02021-03-11 09:36:05 +0100703 if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
Emeric Brunca8e3552021-06-11 10:08:05 +0200704 if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
Christopher Faulet67957bd2017-09-27 11:00:59 +0200705 /* Remove any associated server */
Emeric Brunca8e3552021-06-11 10:08:05 +0200706 list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
707 LIST_DEL_INIT(&srv->ip_rec_item);
708 }
709 }
710 else if (item->type == DNS_RTYPE_SRV) {
Emeric Brun32131d42021-06-11 10:48:45 +0200711 /* Remove any associated server */
Christopher Fauletcab96e12021-06-15 16:08:48 +0200712 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
713 dns_srvrq_cleanup_srv(srv);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200714 }
715
Christopher Faulet67957bd2017-09-27 11:00:59 +0200716 LIST_DEL(&item->list);
Christopher Faulet5a891752020-09-08 10:06:01 +0200717 if (item->ar_item) {
718 pool_free(dns_answer_item_pool, item->ar_item);
719 item->ar_item = NULL;
720 }
Willy Tarreaubafbe012017-11-24 17:34:44 +0100721 pool_free(dns_answer_item_pool, item);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200722 continue;
723 }
724
725 if (item->type != DNS_RTYPE_SRV)
726 continue;
727
728 /* Now process SRV records */
729 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
Emeric Brun32131d42021-06-11 10:48:45 +0200730 struct ebpt_node *node;
731 char target[DNS_MAX_NAME_SIZE+1];
732
733 int i;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200734 if ((srvrq = objt_dns_srvrq(req->owner)) == NULL)
735 continue;
736
Emeric Brun32131d42021-06-11 10:48:45 +0200737 /* Check if a server already uses that record */
738 srv = NULL;
739 list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
740 if (srv->srvrq == srvrq) {
741 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
742 goto srv_found;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200743 }
744 }
Christopher Faulet67957bd2017-09-27 11:00:59 +0200745
Emeric Brun32131d42021-06-11 10:48:45 +0200746
747 /* If not empty we try to match a server
748 * in server state file tree with the same hostname
749 */
750 if (!eb_is_empty(&srvrq->named_servers)) {
751 srv = NULL;
752
753 /* convert the key to lookup in lower case */
754 for (i = 0 ; item->target[i] ; i++)
755 target[i] = tolower(item->target[i]);
756
757 node = ebis_lookup(&srvrq->named_servers, target);
758 if (node) {
759 srv = ebpt_entry(node, struct server, host_dn);
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200760 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Emeric Brun32131d42021-06-11 10:48:45 +0200761
762 /* an entry was found with the same hostname
763 * let check this node if the port matches
764 * and try next node if the hostname
765 * is still the same
766 */
767 while (1) {
768 if (srv->svc_port == item->port) {
769 /* server found, we remove it from tree */
770 ebpt_delete(node);
771 free(srv->host_dn.key);
Christopher Faulet172c3802021-06-15 16:14:37 +0200772 srv->host_dn.key = NULL;
Emeric Brun32131d42021-06-11 10:48:45 +0200773 goto srv_found;
774 }
775
776 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
777
778 node = ebpt_next(node);
779 if (!node)
780 break;
781
782 srv = ebpt_entry(node, struct server, host_dn);
783 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
784
785 if ((item->data_len != srv->hostname_dn_len)
786 || dns_hostname_cmp(srv->hostname_dn, item->target, item->data_len)) {
787 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
788 break;
789 }
790 }
Olivier Houchard55dcdf42017-11-06 15:15:04 +0100791 }
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200792 }
Emeric Brun32131d42021-06-11 10:48:45 +0200793
794 /* Pick the first server listed in srvrq (those ones don't
795 * have hostname and are free to use)
796 */
797 srv = NULL;
798 list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
799 LIST_DEL_INIT(&srv->srv_rec_item);
800 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
801 goto srv_found;
802 }
803 srv = NULL;
Baptiste Assmann13a92322019-06-07 09:40:55 +0200804
Emeric Brun32131d42021-06-11 10:48:45 +0200805srv_found:
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200806 /* And update this server, if found (srv is locked here) */
807 if (srv) {
Christopher Faulet02cf7b72021-03-10 18:38:37 +0100808 /* re-enable DNS resolution for this server by default */
809 srv->flags &= ~SRV_F_NO_RESOLUTION;
Christopher Faulet25fbca42021-06-15 16:17:17 +0200810 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet02cf7b72021-03-10 18:38:37 +0100811
Baptiste Assmann13a92322019-06-07 09:40:55 +0200812 /* Check if an Additional Record is associated to this SRV record.
813 * Perform some sanity checks too to ensure the record can be used.
814 * If all fine, we simply pick up the IP address found and associate
Christopher Faulet02cf7b72021-03-10 18:38:37 +0100815 * it to the server. And DNS resolution is disabled for this server.
Baptiste Assmann13a92322019-06-07 09:40:55 +0200816 */
817 if ((item->ar_item != NULL) &&
818 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
Christopher Faulet02cf7b72021-03-10 18:38:37 +0100819 {
Baptiste Assmann13a92322019-06-07 09:40:55 +0200820
821 switch (item->ar_item->type) {
822 case DNS_RTYPE_A:
Baptiste Assmanncde83032020-08-04 10:54:14 +0200823 update_server_addr(srv, &(((struct sockaddr_in*)&item->ar_item->address)->sin_addr), AF_INET, "DNS additional record");
Baptiste Assmann13a92322019-06-07 09:40:55 +0200824 break;
825 case DNS_RTYPE_AAAA:
Baptiste Assmanncde83032020-08-04 10:54:14 +0200826 update_server_addr(srv, &(((struct sockaddr_in6*)&item->ar_item->address)->sin6_addr), AF_INET6, "DNS additional record");
Baptiste Assmann13a92322019-06-07 09:40:55 +0200827 break;
828 }
829
830 srv->flags |= SRV_F_NO_RESOLUTION;
Christopher Faulet02cf7b72021-03-10 18:38:37 +0100831
832 /* Unlink A/AAAA resolution for this server if there is an AR item.
833 * It is usless to perform an extra resolution
834 */
Christopher Faulet119ec522021-03-11 18:09:53 +0100835 dns_unlink_resolution(srv->dns_requester, 0);
Baptiste Assmann13a92322019-06-07 09:40:55 +0200836 }
837
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200838 if (!srv->hostname_dn) {
839 const char *msg = NULL;
840 char hostname[DNS_MAX_NAME_SIZE];
841
842 if (dns_dn_label_to_str(item->target, item->data_len+1,
843 hostname, DNS_MAX_NAME_SIZE) == -1) {
844 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
845 continue;
846 }
847 msg = update_server_fqdn(srv, hostname, "SRV record", 1);
848 if (msg)
849 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
850 }
Christopher Faulet67957bd2017-09-27 11:00:59 +0200851
Emeric Brun32131d42021-06-11 10:48:45 +0200852 if (!LIST_ADDED(&srv->srv_rec_item))
853 LIST_ADDQ(&item->attached_servers, &srv->srv_rec_item);
854
Christopher Faulet02cf7b72021-03-10 18:38:37 +0100855 if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
856 /* If there is no AR item responsible of the FQDN resolution,
857 * trigger a dedicated DNS resolution
858 */
859 if (!srv->dns_requester || !srv->dns_requester->resolution)
860 dns_link_resolution(srv, OBJ_TYPE_SERVER, 1);
861 }
862
Christopher Faulet1ec90772021-03-10 15:34:52 +0100863 /* Update the server status */
Christopher Faulet07cb0e12021-03-11 18:06:23 +0100864 srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Baptiste Assmann87138c32020-08-04 10:57:21 +0200865
Christopher Faulet67957bd2017-09-27 11:00:59 +0200866 srv->svc_port = item->port;
867 srv->flags &= ~SRV_F_MAPPORTS;
868 if ((srv->check.state & CHK_ST_CONFIGURED) &&
869 !(srv->flags & SRV_F_CHECKPORT))
870 srv->check.port = item->port;
Olivier Houchard2ec2db92018-01-08 16:28:57 +0100871
Daniel Corbettf8716912019-11-17 09:48:56 -0500872 if (!srv->dns_opts.ignore_weight) {
Christopher Fauletd6c6b5f2020-09-08 10:27:24 +0200873 char weight[9];
874 int ha_weight;
875
Daniel Corbettf8716912019-11-17 09:48:56 -0500876 /* DNS weight range if from 0 to 65535
877 * HAProxy weight is from 0 to 256
878 * The rule below ensures that weight 0 is well respected
879 * while allowing a "mapping" from DNS weight into HAProxy's one.
880 */
881 ha_weight = (item->weight + 255) / 256;
Olivier Houchard2ec2db92018-01-08 16:28:57 +0100882
Daniel Corbettf8716912019-11-17 09:48:56 -0500883 snprintf(weight, sizeof(weight), "%d", ha_weight);
884 server_parse_weight_change_request(srv, weight);
885 }
Christopher Faulet2a944ee2017-11-07 10:42:54 +0100886 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +0200887 }
888 }
889 }
890}
891
892/* Validates that the buffer DNS response provided in <resp> and finishing
893 * before <bufend> is valid from a DNS protocol point of view.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200894 *
Christopher Faulet67957bd2017-09-27 11:00:59 +0200895 * The result is stored in <resolution>' response, buf_response,
896 * response_query_records and response_answer_records members.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200897 *
898 * This function returns one of the DNS_RESP_* code to indicate the type of
899 * error found.
Baptiste Assmann325137d2015-04-13 23:40:55 +0200900 */
Christopher Faulet67957bd2017-09-27 11:00:59 +0200901static int dns_validate_dns_response(unsigned char *resp, unsigned char *bufend,
902 struct dns_resolution *resolution, int max_answer_records)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200903{
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200904 unsigned char *reader;
905 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200906 int len, flags, offset;
907 int dns_query_record_id;
Baptiste Assmann69fce672017-05-04 08:37:45 +0200908 int nb_saved_records;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200909 struct dns_query_item *dns_query;
Olivier Houcharda8c6db82017-07-06 18:46:47 +0200910 struct dns_answer_item *dns_answer_record, *tmp_record;
Baptiste Assmann729c9012017-05-22 15:13:10 +0200911 struct dns_response_packet *dns_p;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200912 int i, found = 0;
Willy Tarreau963f7012020-07-22 17:00:45 +0200913 int cause = DNS_RESP_ERROR;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200914
Christopher Faulet67957bd2017-09-27 11:00:59 +0200915 reader = resp;
916 len = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200917 previous_dname = NULL;
Christopher Faulet67957bd2017-09-27 11:00:59 +0200918 dns_query = NULL;
Willy Tarreau963f7012020-07-22 17:00:45 +0200919 dns_answer_record = NULL;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200920
Christopher Faulet67957bd2017-09-27 11:00:59 +0200921 /* Initialization of response buffer and structure */
Baptiste Assmann729c9012017-05-22 15:13:10 +0200922 dns_p = &resolution->response;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200923
924 /* query id */
925 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +0200926 goto invalid_resp;
927
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200928 dns_p->header.id = reader[0] * 256 + reader[1];
929 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200930
Christopher Faulet67957bd2017-09-27 11:00:59 +0200931 /* Flags and rcode are stored over 2 bytes
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200932 * First byte contains:
933 * - response flag (1 bit)
934 * - opcode (4 bits)
935 * - authoritative (1 bit)
936 * - truncated (1 bit)
937 * - recursion desired (1 bit)
Baptiste Assmann325137d2015-04-13 23:40:55 +0200938 */
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200939 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +0200940 goto invalid_resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200941
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200942 flags = reader[0] * 256 + reader[1];
943
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200944 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
Willy Tarreau963f7012020-07-22 17:00:45 +0200945 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
946 cause = DNS_RESP_NX_DOMAIN;
947 goto return_error;
948 }
949 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
950 cause = DNS_RESP_REFUSED;
951 goto return_error;
952 }
953 else {
954 cause = DNS_RESP_ERROR;
955 goto return_error;
956 }
Baptiste Assmann325137d2015-04-13 23:40:55 +0200957 }
958
Christopher Faulet67957bd2017-09-27 11:00:59 +0200959 /* Move forward 2 bytes for flags */
Baptiste Assmann3440f0d2015-09-02 22:08:38 +0200960 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200961
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200962 /* 2 bytes for question count */
963 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +0200964 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200965 dns_p->header.qdcount = reader[0] * 256 + reader[1];
Christopher Faulet67957bd2017-09-27 11:00:59 +0200966 /* (for now) we send one query only, so we expect only one in the
967 * response too */
Willy Tarreau963f7012020-07-22 17:00:45 +0200968 if (dns_p->header.qdcount != 1) {
969 cause = DNS_RESP_QUERY_COUNT_ERROR;
970 goto return_error;
971 }
972
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200973 if (dns_p->header.qdcount > DNS_MAX_QUERY_RECORDS)
Willy Tarreau963f7012020-07-22 17:00:45 +0200974 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200975 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200976
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200977 /* 2 bytes for answer count */
978 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +0200979 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200980 dns_p->header.ancount = reader[0] * 256 + reader[1];
Willy Tarreau963f7012020-07-22 17:00:45 +0200981 if (dns_p->header.ancount == 0) {
982 cause = DNS_RESP_ANCOUNT_ZERO;
983 goto return_error;
984 }
985
Christopher Faulet67957bd2017-09-27 11:00:59 +0200986 /* Check if too many records are announced */
Baptiste Assmann9d8dbbc2017-08-18 23:35:08 +0200987 if (dns_p->header.ancount > max_answer_records)
Willy Tarreau963f7012020-07-22 17:00:45 +0200988 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200989 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200990
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200991 /* 2 bytes authority count */
992 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +0200993 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200994 dns_p->header.nscount = reader[0] * 256 + reader[1];
995 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +0200996
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +0200997 /* 2 bytes additional count */
998 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +0200999 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001000 dns_p->header.arcount = reader[0] * 256 + reader[1];
1001 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001002
Christopher Faulet67957bd2017-09-27 11:00:59 +02001003 /* Parsing dns queries */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001004 LIST_INIT(&dns_p->query_list);
1005 for (dns_query_record_id = 0; dns_query_record_id < dns_p->header.qdcount; dns_query_record_id++) {
Christopher Faulet67957bd2017-09-27 11:00:59 +02001006 /* Use next pre-allocated dns_query_item after ensuring there is
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001007 * still one available.
Christopher Faulet67957bd2017-09-27 11:00:59 +02001008 * It's then added to our packet query list. */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001009 if (dns_query_record_id > DNS_MAX_QUERY_RECORDS)
Willy Tarreau963f7012020-07-22 17:00:45 +02001010 goto invalid_resp;
Baptiste Assmann729c9012017-05-22 15:13:10 +02001011 dns_query = &resolution->response_query_records[dns_query_record_id];
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001012 LIST_ADDQ(&dns_p->query_list, &dns_query->list);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001013
Christopher Faulet67957bd2017-09-27 11:00:59 +02001014 /* Name is a NULL terminated string in our case, since we have
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001015 * one query per response and the first one can't be compressed
Christopher Faulet67957bd2017-09-27 11:00:59 +02001016 * (using the 0x0c format) */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001017 offset = 0;
Remi Gacogne58df5ae2018-12-05 17:52:54 +01001018 len = dns_read_name(resp, bufend, reader, dns_query->name, DNS_MAX_NAME_SIZE, &offset, 0);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001019
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001020 if (len == 0)
Willy Tarreau963f7012020-07-22 17:00:45 +02001021 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001022
1023 reader += offset;
1024 previous_dname = dns_query->name;
1025
1026 /* move forward 2 bytes for question type */
1027 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +02001028 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001029 dns_query->type = reader[0] * 256 + reader[1];
1030 reader += 2;
1031
1032 /* move forward 2 bytes for question class */
1033 if (reader + 2 >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +02001034 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001035 dns_query->class = reader[0] * 256 + reader[1];
1036 reader += 2;
1037 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001038
Baptiste Assmann251abb92017-08-11 09:58:27 +02001039 /* TRUNCATED flag must be checked after we could read the query type
Christopher Faulet67957bd2017-09-27 11:00:59 +02001040 * because a TRUNCATED SRV query type response can still be exploited */
Willy Tarreau963f7012020-07-22 17:00:45 +02001041 if (dns_query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
1042 cause = DNS_RESP_TRUNCATED;
1043 goto return_error;
1044 }
Baptiste Assmann251abb92017-08-11 09:58:27 +02001045
Baptiste Assmann325137d2015-04-13 23:40:55 +02001046 /* now parsing response records */
Baptiste Assmann69fce672017-05-04 08:37:45 +02001047 nb_saved_records = 0;
Olivier Houchard8da5f982017-08-04 18:35:36 +02001048 for (i = 0; i < dns_p->header.ancount; i++) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001049 if (reader >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +02001050 goto invalid_resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001051
Willy Tarreaubafbe012017-11-24 17:34:44 +01001052 dns_answer_record = pool_alloc(dns_answer_item_pool);
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001053 if (dns_answer_record == NULL)
Willy Tarreau963f7012020-07-22 17:00:45 +02001054 goto invalid_resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001055
Baptiste Assmann155bc682021-01-15 17:01:24 +01001056 /* initialization */
1057 dns_answer_record->ar_item = NULL;
Christopher Faulet8b6d5b02021-03-11 09:36:05 +01001058 dns_answer_record->last_seen = TICK_ETERNITY;
Emeric Brunca8e3552021-06-11 10:08:05 +02001059 LIST_INIT(&dns_answer_record->attached_servers);
Baptiste Assmann155bc682021-01-15 17:01:24 +01001060
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001061 offset = 0;
Remi Gacogne58df5ae2018-12-05 17:52:54 +01001062 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001063
Willy Tarreau963f7012020-07-22 17:00:45 +02001064 if (len == 0)
1065 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001066
Christopher Faulet67957bd2017-09-27 11:00:59 +02001067 /* Check if the current record dname is valid. previous_dname
1068 * points either to queried dname or last CNAME target */
Olivier Houchardb17b8842020-04-01 18:30:27 +02001069 if (dns_query->type != DNS_RTYPE_SRV && dns_hostname_cmp(previous_dname, tmpname, len) != 0) {
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001070 if (i == 0) {
Christopher Faulet67957bd2017-09-27 11:00:59 +02001071 /* First record, means a mismatch issue between
1072 * queried dname and dname found in the first
1073 * record */
Willy Tarreau963f7012020-07-22 17:00:45 +02001074 goto invalid_resp;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001075 }
1076 else {
1077 /* If not the first record, this means we have a
Willy Tarreau963f7012020-07-22 17:00:45 +02001078 * CNAME resolution error.
1079 */
1080 cause = DNS_RESP_CNAME_ERROR;
1081 goto return_error;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001082 }
1083
Baptiste Assmann325137d2015-04-13 23:40:55 +02001084 }
1085
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001086 memcpy(dns_answer_record->name, tmpname, len);
1087 dns_answer_record->name[len] = 0;
Baptiste Assmann2359ff12015-08-07 11:24:05 +02001088
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001089 reader += offset;
Willy Tarreau963f7012020-07-22 17:00:45 +02001090 if (reader >= bufend)
1091 goto invalid_resp;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001092
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001093 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
Willy Tarreau963f7012020-07-22 17:00:45 +02001094 if (reader + 2 > bufend)
1095 goto invalid_resp;
1096
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001097 dns_answer_record->type = reader[0] * 256 + reader[1];
1098 reader += 2;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001099
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001100 /* 2 bytes for class (2) */
Willy Tarreau963f7012020-07-22 17:00:45 +02001101 if (reader + 2 > bufend)
1102 goto invalid_resp;
1103
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001104 dns_answer_record->class = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +02001105 reader += 2;
1106
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001107 /* 4 bytes for ttl (4) */
Willy Tarreau963f7012020-07-22 17:00:45 +02001108 if (reader + 4 > bufend)
1109 goto invalid_resp;
1110
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001111 dns_answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1112 + reader[2] * 256 + reader[3];
1113 reader += 4;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001114
Christopher Faulet67957bd2017-09-27 11:00:59 +02001115 /* Now reading data len */
Willy Tarreau963f7012020-07-22 17:00:45 +02001116 if (reader + 2 > bufend)
1117 goto invalid_resp;
1118
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001119 dns_answer_record->data_len = reader[0] * 256 + reader[1];
Baptiste Assmann325137d2015-04-13 23:40:55 +02001120
Christopher Faulet67957bd2017-09-27 11:00:59 +02001121 /* Move forward 2 bytes for data len */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001122 reader += 2;
1123
Willy Tarreau963f7012020-07-22 17:00:45 +02001124 if (reader + dns_answer_record->data_len > bufend)
1125 goto invalid_resp;
Remi Gacogneefbbdf72018-12-05 17:56:29 +01001126
Christopher Faulet67957bd2017-09-27 11:00:59 +02001127 /* Analyzing record content */
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001128 switch (dns_answer_record->type) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001129 case DNS_RTYPE_A:
1130 /* ipv4 is stored on 4 bytes */
Willy Tarreau963f7012020-07-22 17:00:45 +02001131 if (dns_answer_record->data_len != 4)
1132 goto invalid_resp;
1133
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001134 dns_answer_record->address.sa_family = AF_INET;
1135 memcpy(&(((struct sockaddr_in *)&dns_answer_record->address)->sin_addr),
1136 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001137 break;
1138
1139 case DNS_RTYPE_CNAME:
Christopher Faulet67957bd2017-09-27 11:00:59 +02001140 /* Check if this is the last record and update the caller about the status:
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001141 * no IP could be found and last record was a CNAME. Could be triggered
1142 * by a wrong query type
1143 *
Christopher Faulet67957bd2017-09-27 11:00:59 +02001144 * + 1 because dns_answer_record_id starts at 0
1145 * while number of answers is an integer and
1146 * starts at 1.
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001147 */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001148 if (i + 1 == dns_p->header.ancount) {
Willy Tarreau963f7012020-07-22 17:00:45 +02001149 cause = DNS_RESP_CNAME_ERROR;
1150 goto return_error;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001151 }
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001152
1153 offset = 0;
Remi Gacogne58df5ae2018-12-05 17:52:54 +01001154 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
Willy Tarreau963f7012020-07-22 17:00:45 +02001155 if (len == 0)
1156 goto invalid_resp;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001157
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001158 memcpy(dns_answer_record->target, tmpname, len);
1159 dns_answer_record->target[len] = 0;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001160 previous_dname = dns_answer_record->target;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001161 break;
1162
Olivier Houchard8da5f982017-08-04 18:35:36 +02001163
1164 case DNS_RTYPE_SRV:
Christopher Faulet67957bd2017-09-27 11:00:59 +02001165 /* Answer must contain :
Olivier Houchard8da5f982017-08-04 18:35:36 +02001166 * - 2 bytes for the priority
1167 * - 2 bytes for the weight
1168 * - 2 bytes for the port
1169 * - the target hostname
1170 */
Willy Tarreau963f7012020-07-22 17:00:45 +02001171 if (dns_answer_record->data_len <= 6)
1172 goto invalid_resp;
1173
Willy Tarreaud5370e12017-09-19 14:59:52 +02001174 dns_answer_record->priority = read_n16(reader);
Olivier Houchard8da5f982017-08-04 18:35:36 +02001175 reader += sizeof(uint16_t);
Willy Tarreaud5370e12017-09-19 14:59:52 +02001176 dns_answer_record->weight = read_n16(reader);
Olivier Houchard8da5f982017-08-04 18:35:36 +02001177 reader += sizeof(uint16_t);
Willy Tarreaud5370e12017-09-19 14:59:52 +02001178 dns_answer_record->port = read_n16(reader);
Olivier Houchard8da5f982017-08-04 18:35:36 +02001179 reader += sizeof(uint16_t);
1180 offset = 0;
Remi Gacogne58df5ae2018-12-05 17:52:54 +01001181 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
Willy Tarreau963f7012020-07-22 17:00:45 +02001182 if (len == 0)
1183 goto invalid_resp;
1184
Olivier Houchard8da5f982017-08-04 18:35:36 +02001185 dns_answer_record->data_len = len;
1186 memcpy(dns_answer_record->target, tmpname, len);
1187 dns_answer_record->target[len] = 0;
Baptiste Assmann155bc682021-01-15 17:01:24 +01001188 if (dns_answer_record->ar_item != NULL) {
1189 pool_free(dns_answer_item_pool, dns_answer_record->ar_item);
1190 dns_answer_record->ar_item = NULL;
1191 }
Olivier Houchard8da5f982017-08-04 18:35:36 +02001192 break;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001193
Baptiste Assmann325137d2015-04-13 23:40:55 +02001194 case DNS_RTYPE_AAAA:
1195 /* ipv6 is stored on 16 bytes */
Willy Tarreau963f7012020-07-22 17:00:45 +02001196 if (dns_answer_record->data_len != 16)
1197 goto invalid_resp;
1198
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001199 dns_answer_record->address.sa_family = AF_INET6;
1200 memcpy(&(((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr),
1201 reader, dns_answer_record->data_len);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001202 break;
Baptiste Assmannc1ce5f32016-05-14 11:26:22 +02001203
Baptiste Assmann325137d2015-04-13 23:40:55 +02001204 } /* switch (record type) */
1205
Christopher Faulet67957bd2017-09-27 11:00:59 +02001206 /* Increment the counter for number of records saved into our
1207 * local response */
1208 nb_saved_records++;
Baptiste Assmann69fce672017-05-04 08:37:45 +02001209
Christopher Faulet67957bd2017-09-27 11:00:59 +02001210 /* Move forward dns_answer_record->data_len for analyzing next
1211 * record in the response */
1212 reader += ((dns_answer_record->type == DNS_RTYPE_SRV)
1213 ? offset
1214 : dns_answer_record->data_len);
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001215
1216 /* Lookup to see if we already had this entry */
Olivier Houchard8da5f982017-08-04 18:35:36 +02001217 found = 0;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001218 list_for_each_entry(tmp_record, &dns_p->answer_list, list) {
1219 if (tmp_record->type != dns_answer_record->type)
1220 continue;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001221
1222 switch(tmp_record->type) {
1223 case DNS_RTYPE_A:
1224 if (!memcmp(&((struct sockaddr_in *)&dns_answer_record->address)->sin_addr,
1225 &((struct sockaddr_in *)&tmp_record->address)->sin_addr,
1226 sizeof(in_addr_t)))
1227 found = 1;
1228 break;
1229
1230 case DNS_RTYPE_AAAA:
1231 if (!memcmp(&((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr,
1232 &((struct sockaddr_in6 *)&tmp_record->address)->sin6_addr,
1233 sizeof(struct in6_addr)))
1234 found = 1;
1235 break;
1236
Olivier Houchard8da5f982017-08-04 18:35:36 +02001237 case DNS_RTYPE_SRV:
1238 if (dns_answer_record->data_len == tmp_record->data_len &&
Olivier Houchardb17b8842020-04-01 18:30:27 +02001239 !dns_hostname_cmp(dns_answer_record->target, tmp_record->target, dns_answer_record->data_len) &&
Olivier Houchard8da5f982017-08-04 18:35:36 +02001240 dns_answer_record->port == tmp_record->port) {
1241 tmp_record->weight = dns_answer_record->weight;
1242 found = 1;
1243 }
1244 break;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001245
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001246 default:
1247 break;
1248 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001249
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001250 if (found == 1)
1251 break;
1252 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001253
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001254 if (found == 1) {
Christopher Faulet8b6d5b02021-03-11 09:36:05 +01001255 tmp_record->last_seen = now_ms;
Willy Tarreaubafbe012017-11-24 17:34:44 +01001256 pool_free(dns_answer_item_pool, dns_answer_record);
Willy Tarreau963f7012020-07-22 17:00:45 +02001257 dns_answer_record = NULL;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001258 }
1259 else {
Christopher Faulet8b6d5b02021-03-11 09:36:05 +01001260 dns_answer_record->last_seen = now_ms;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001261 dns_answer_record->ar_item = NULL;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001262 LIST_ADDQ(&dns_p->answer_list, &dns_answer_record->list);
Willy Tarreau963f7012020-07-22 17:00:45 +02001263 dns_answer_record = NULL;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001264 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001265 } /* for i 0 to ancount */
1266
Christopher Faulet67957bd2017-09-27 11:00:59 +02001267 /* Save the number of records we really own */
Baptiste Assmann69fce672017-05-04 08:37:45 +02001268 dns_p->header.ancount = nb_saved_records;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001269
Baptiste Assmann37950c82020-02-19 01:08:51 +01001270 /* now parsing additional records for SRV queries only */
1271 if (dns_query->type != DNS_RTYPE_SRV)
1272 goto skip_parsing_additional_records;
Willy Tarreau963f7012020-07-22 17:00:45 +02001273
Jerome Magnin4002f8d2020-07-26 12:13:12 +02001274 /* if we find Authority records, just skip them */
1275 for (i = 0; i < dns_p->header.nscount; i++) {
1276 offset = 0;
1277 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1278 &offset, 0);
1279 if (len == 0)
1280 continue;
1281
1282 if (reader + offset + 10 >= bufend)
1283 goto invalid_resp;
1284
1285 reader += offset;
1286 /* skip 2 bytes for class */
1287 reader += 2;
1288 /* skip 2 bytes for type */
1289 reader += 2;
1290 /* skip 4 bytes for ttl */
1291 reader += 4;
1292 /* read data len */
1293 len = reader[0] * 256 + reader[1];
1294 reader += 2;
1295
1296 if (reader + len >= bufend)
1297 goto invalid_resp;
1298
1299 reader += len;
1300 }
1301
Baptiste Assmann13a92322019-06-07 09:40:55 +02001302 nb_saved_records = 0;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001303 for (i = 0; i < dns_p->header.arcount; i++) {
1304 if (reader >= bufend)
Willy Tarreau963f7012020-07-22 17:00:45 +02001305 goto invalid_resp;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001306
1307 dns_answer_record = pool_alloc(dns_answer_item_pool);
1308 if (dns_answer_record == NULL)
Willy Tarreau963f7012020-07-22 17:00:45 +02001309 goto invalid_resp;
Christopher Faulet8b6d5b02021-03-11 09:36:05 +01001310 dns_answer_record->last_seen = TICK_ETERNITY;
Emeric Brunca8e3552021-06-11 10:08:05 +02001311 LIST_INIT(&dns_answer_record->attached_servers);
Baptiste Assmann13a92322019-06-07 09:40:55 +02001312
1313 offset = 0;
1314 len = dns_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1315
1316 if (len == 0) {
1317 pool_free(dns_answer_item_pool, dns_answer_record);
Willy Tarreau963f7012020-07-22 17:00:45 +02001318 dns_answer_record = NULL;
Baptiste Assmann37950c82020-02-19 01:08:51 +01001319 continue;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001320 }
1321
1322 memcpy(dns_answer_record->name, tmpname, len);
1323 dns_answer_record->name[len] = 0;
1324
1325 reader += offset;
Willy Tarreau963f7012020-07-22 17:00:45 +02001326 if (reader >= bufend)
1327 goto invalid_resp;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001328
1329 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
Willy Tarreau963f7012020-07-22 17:00:45 +02001330 if (reader + 2 > bufend)
1331 goto invalid_resp;
1332
Baptiste Assmann13a92322019-06-07 09:40:55 +02001333 dns_answer_record->type = reader[0] * 256 + reader[1];
1334 reader += 2;
1335
1336 /* 2 bytes for class (2) */
Willy Tarreau963f7012020-07-22 17:00:45 +02001337 if (reader + 2 > bufend)
1338 goto invalid_resp;
1339
Baptiste Assmann13a92322019-06-07 09:40:55 +02001340 dns_answer_record->class = reader[0] * 256 + reader[1];
1341 reader += 2;
1342
1343 /* 4 bytes for ttl (4) */
Willy Tarreau963f7012020-07-22 17:00:45 +02001344 if (reader + 4 > bufend)
1345 goto invalid_resp;
1346
Baptiste Assmann13a92322019-06-07 09:40:55 +02001347 dns_answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1348 + reader[2] * 256 + reader[3];
1349 reader += 4;
1350
1351 /* Now reading data len */
Willy Tarreau963f7012020-07-22 17:00:45 +02001352 if (reader + 2 > bufend)
1353 goto invalid_resp;
1354
Baptiste Assmann13a92322019-06-07 09:40:55 +02001355 dns_answer_record->data_len = reader[0] * 256 + reader[1];
1356
1357 /* Move forward 2 bytes for data len */
1358 reader += 2;
1359
Willy Tarreau963f7012020-07-22 17:00:45 +02001360 if (reader + dns_answer_record->data_len > bufend)
1361 goto invalid_resp;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001362
1363 /* Analyzing record content */
1364 switch (dns_answer_record->type) {
1365 case DNS_RTYPE_A:
1366 /* ipv4 is stored on 4 bytes */
Willy Tarreau963f7012020-07-22 17:00:45 +02001367 if (dns_answer_record->data_len != 4)
1368 goto invalid_resp;
1369
Baptiste Assmann13a92322019-06-07 09:40:55 +02001370 dns_answer_record->address.sa_family = AF_INET;
1371 memcpy(&(((struct sockaddr_in *)&dns_answer_record->address)->sin_addr),
1372 reader, dns_answer_record->data_len);
1373 break;
1374
1375 case DNS_RTYPE_AAAA:
1376 /* ipv6 is stored on 16 bytes */
Willy Tarreau963f7012020-07-22 17:00:45 +02001377 if (dns_answer_record->data_len != 16)
1378 goto invalid_resp;
1379
Baptiste Assmann13a92322019-06-07 09:40:55 +02001380 dns_answer_record->address.sa_family = AF_INET6;
1381 memcpy(&(((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr),
1382 reader, dns_answer_record->data_len);
1383 break;
1384
1385 default:
1386 pool_free(dns_answer_item_pool, dns_answer_record);
Willy Tarreau963f7012020-07-22 17:00:45 +02001387 dns_answer_record = NULL;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001388 continue;
1389
1390 } /* switch (record type) */
1391
1392 /* Increment the counter for number of records saved into our
1393 * local response */
1394 nb_saved_records++;
1395
1396 /* Move forward dns_answer_record->data_len for analyzing next
1397 * record in the response */
Christopher Fauletb8e92812021-03-10 15:19:57 +01001398 reader += dns_answer_record->data_len;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001399
1400 /* Lookup to see if we already had this entry */
1401 found = 0;
1402 list_for_each_entry(tmp_record, &dns_p->answer_list, list) {
Christopher Fauletb8e92812021-03-10 15:19:57 +01001403 struct dns_answer_item *ar_item;
1404
1405 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1406 continue;
1407
1408 ar_item = tmp_record->ar_item;
Christopher Faulet27c8d7a2021-03-12 16:42:45 +01001409 if (ar_item->type != dns_answer_record->type || ar_item->last_seen == now_ms ||
Christopher Fauletb8e92812021-03-10 15:19:57 +01001410 len != tmp_record->data_len ||
1411 dns_hostname_cmp(dns_answer_record->name, tmp_record->target, tmp_record->data_len))
Baptiste Assmann13a92322019-06-07 09:40:55 +02001412 continue;
1413
Christopher Fauletb8e92812021-03-10 15:19:57 +01001414 switch(ar_item->type) {
Baptiste Assmann13a92322019-06-07 09:40:55 +02001415 case DNS_RTYPE_A:
1416 if (!memcmp(&((struct sockaddr_in *)&dns_answer_record->address)->sin_addr,
Christopher Fauletb8e92812021-03-10 15:19:57 +01001417 &((struct sockaddr_in *)&ar_item->address)->sin_addr,
Baptiste Assmann13a92322019-06-07 09:40:55 +02001418 sizeof(in_addr_t)))
1419 found = 1;
1420 break;
1421
1422 case DNS_RTYPE_AAAA:
1423 if (!memcmp(&((struct sockaddr_in6 *)&dns_answer_record->address)->sin6_addr,
Christopher Fauletb8e92812021-03-10 15:19:57 +01001424 &((struct sockaddr_in6 *)&ar_item->address)->sin6_addr,
Baptiste Assmann13a92322019-06-07 09:40:55 +02001425 sizeof(struct in6_addr)))
1426 found = 1;
1427 break;
1428
1429 default:
1430 break;
1431 }
1432
1433 if (found == 1)
1434 break;
1435 }
1436
1437 if (found == 1) {
Christopher Faulet8b6d5b02021-03-11 09:36:05 +01001438 tmp_record->ar_item->last_seen = now_ms;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001439 pool_free(dns_answer_item_pool, dns_answer_record);
Willy Tarreau963f7012020-07-22 17:00:45 +02001440 dns_answer_record = NULL;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001441 }
1442 else {
Christopher Faulet8b6d5b02021-03-11 09:36:05 +01001443 dns_answer_record->last_seen = now_ms;
Baptiste Assmann13a92322019-06-07 09:40:55 +02001444 dns_answer_record->ar_item = NULL;
1445
1446 // looking for the SRV record in the response list linked to this additional record
1447 list_for_each_entry(tmp_record, &dns_p->answer_list, list) {
Christopher Faulet5a891752020-09-08 10:06:01 +02001448 if (tmp_record->type == DNS_RTYPE_SRV &&
Baptiste Assmann155bc682021-01-15 17:01:24 +01001449 tmp_record->ar_item == NULL &&
Christopher Faulet5a891752020-09-08 10:06:01 +02001450 !dns_hostname_cmp(tmp_record->target, dns_answer_record->name, tmp_record->data_len)) {
1451 /* Always use the received additional record to refresh info */
Christopher Faulet5a891752020-09-08 10:06:01 +02001452 tmp_record->ar_item = dns_answer_record;
Christopher Fauletd67f8bb2021-02-23 11:59:19 +01001453 dns_answer_record = NULL;
Christopher Faulet5a891752020-09-08 10:06:01 +02001454 break;
1455 }
Baptiste Assmann13a92322019-06-07 09:40:55 +02001456 }
Christopher Fauletd67f8bb2021-02-23 11:59:19 +01001457 if (dns_answer_record) {
Christopher Faulet5a891752020-09-08 10:06:01 +02001458 pool_free(dns_answer_item_pool, dns_answer_record);
Christopher Fauletd67f8bb2021-02-23 11:59:19 +01001459 dns_answer_record = NULL;
1460 }
Baptiste Assmann13a92322019-06-07 09:40:55 +02001461 }
1462 } /* for i 0 to arcount */
1463
Baptiste Assmann37950c82020-02-19 01:08:51 +01001464 skip_parsing_additional_records:
1465
Baptiste Assmann13a92322019-06-07 09:40:55 +02001466 /* Save the number of records we really own */
1467 dns_p->header.arcount = nb_saved_records;
1468
Christopher Faulet67957bd2017-09-27 11:00:59 +02001469 dns_check_dns_response(resolution);
Baptiste Assmann325137d2015-04-13 23:40:55 +02001470 return DNS_RESP_VALID;
Willy Tarreau963f7012020-07-22 17:00:45 +02001471
1472 invalid_resp:
1473 cause = DNS_RESP_INVALID;
1474
1475 return_error:
1476 pool_free(dns_answer_item_pool, dns_answer_record);
1477 return cause;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001478}
1479
Christopher Faulet67957bd2017-09-27 11:00:59 +02001480/* Searches dn_name resolution in resp.
Baptiste Assmann325137d2015-04-13 23:40:55 +02001481 * If existing IP not found, return the first IP matching family_priority,
1482 * otherwise, first ip found
1483 * The following tasks are the responsibility of the caller:
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001484 * - <dns_p> contains an error free DNS response
Baptiste Assmann325137d2015-04-13 23:40:55 +02001485 * For both cases above, dns_validate_dns_response is required
1486 * returns one of the DNS_UPD_* code
1487 */
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001488int dns_get_ip_from_response(struct dns_response_packet *dns_p,
Baptiste Assmann42746372017-05-03 12:12:02 +02001489 struct dns_options *dns_opts, void *currentip,
Thierry Fournierada34842016-02-17 21:25:09 +01001490 short currentip_sin_family,
Baptiste Assmannfb7091e2017-05-03 15:43:12 +02001491 void **newip, short *newip_sin_family,
Emeric Brunca8e3552021-06-11 10:08:05 +02001492 struct server *owner)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001493{
Emeric Brunca8e3552021-06-11 10:08:05 +02001494 struct dns_answer_item *record, *found_record = NULL;
Thierry Fournierada34842016-02-17 21:25:09 +01001495 int family_priority;
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001496 int currentip_found;
Baptiste Assmann3cf7f982016-04-17 22:43:26 +02001497 unsigned char *newip4, *newip6;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001498 int currentip_sel;
1499 int j;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001500 int score, max_score;
Baptiste Assmann8e2d9432018-06-22 15:04:43 +02001501 int allowed_duplicated_ip;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001502
Emeric Brunca8e3552021-06-11 10:08:05 +02001503 /* srv is linked to an alive ip record */
1504 if (owner && LIST_ADDED(&owner->ip_rec_item))
1505 return DNS_UPD_NO;
1506
Christopher Faulet67957bd2017-09-27 11:00:59 +02001507 family_priority = dns_opts->family_prio;
Baptiste Assmann8e2d9432018-06-22 15:04:43 +02001508 allowed_duplicated_ip = dns_opts->accept_duplicate_ip;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001509 *newip = newip4 = newip6 = NULL;
1510 currentip_found = 0;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001511 *newip_sin_family = AF_UNSPEC;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001512 max_score = -1;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001513
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001514 /* Select an IP regarding configuration preference.
Joseph Herlant42cf6392018-11-15 10:33:28 -08001515 * Top priority is the preferred network ip version,
1516 * second priority is the preferred network.
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001517 * the last priority is the currently used IP,
1518 *
1519 * For these three priorities, a score is calculated. The
1520 * weight are:
Joseph Herlant42cf6392018-11-15 10:33:28 -08001521 * 8 - preferred ip version.
1522 * 4 - preferred network.
Baptistefc725902016-12-26 23:21:08 +01001523 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001524 * 1 - current ip.
1525 * The result with the biggest score is returned.
1526 */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001527
1528 list_for_each_entry(record, &dns_p->answer_list, list) {
1529 void *ip;
1530 unsigned char ip_type;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001531
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001532 if (record->type == DNS_RTYPE_A) {
1533 ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
1534 ip_type = AF_INET;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001535 }
1536 else if (record->type == DNS_RTYPE_AAAA) {
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001537 ip_type = AF_INET6;
1538 ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
Christopher Faulet67957bd2017-09-27 11:00:59 +02001539 }
1540 else
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001541 continue;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001542 score = 0;
1543
Joseph Herlant42cf6392018-11-15 10:33:28 -08001544 /* Check for preferred ip protocol. */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001545 if (ip_type == family_priority)
Baptistefc725902016-12-26 23:21:08 +01001546 score += 8;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001547
Joseph Herlant42cf6392018-11-15 10:33:28 -08001548 /* Check for preferred network. */
Baptiste Assmann42746372017-05-03 12:12:02 +02001549 for (j = 0; j < dns_opts->pref_net_nb; j++) {
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001550
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05001551 /* Compare only the same addresses class. */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001552 if (dns_opts->pref_net[j].family != ip_type)
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001553 continue;
1554
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001555 if ((ip_type == AF_INET &&
1556 in_net_ipv4(ip,
Baptiste Assmann42746372017-05-03 12:12:02 +02001557 &dns_opts->pref_net[j].mask.in4,
1558 &dns_opts->pref_net[j].addr.in4)) ||
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001559 (ip_type == AF_INET6 &&
1560 in_net_ipv6(ip,
Baptiste Assmann42746372017-05-03 12:12:02 +02001561 &dns_opts->pref_net[j].mask.in6,
1562 &dns_opts->pref_net[j].addr.in6))) {
Baptistefc725902016-12-26 23:21:08 +01001563 score += 4;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001564 break;
1565 }
1566 }
1567
Christopher Faulet67957bd2017-09-27 11:00:59 +02001568 /* Check if the IP found in the record is already affected to a
Baptiste Assmann84221b42018-06-22 13:03:50 +02001569 * member of a group. If not, the score should be incremented
Christopher Faulet67957bd2017-09-27 11:00:59 +02001570 * by 2. */
Emeric Brunca8e3552021-06-11 10:08:05 +02001571 if (owner) {
1572 struct server *srv;
1573 int already_used = 0;
1574
1575 list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
1576 if (srv == owner)
1577 continue;
1578 if (srv->proxy == owner->proxy) {
1579 already_used = 1;
1580 break;
1581 }
1582 }
1583 if (already_used) {
1584 if (!allowed_duplicated_ip) {
1585 continue;
1586 }
1587 }
1588 else {
1589 score += 2;
1590 }
Baptiste Assmann84221b42018-06-22 13:03:50 +02001591 } else {
1592 score += 2;
1593 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001594
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001595 /* Check for current ip matching. */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001596 if (ip_type == currentip_sin_family &&
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001597 ((currentip_sin_family == AF_INET &&
Christopher Faulet67957bd2017-09-27 11:00:59 +02001598 !memcmp(ip, currentip, 4)) ||
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001599 (currentip_sin_family == AF_INET6 &&
Christopher Faulet67957bd2017-09-27 11:00:59 +02001600 !memcmp(ip, currentip, 16)))) {
1601 score++;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001602 currentip_sel = 1;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001603 }
1604 else
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001605 currentip_sel = 0;
1606
1607 /* Keep the address if the score is better than the previous
Christopher Faulet67957bd2017-09-27 11:00:59 +02001608 * score. The maximum score is 15, if this value is reached, we
1609 * break the parsing. Implicitly, this score is reached the ip
1610 * selected is the current ip. */
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001611 if (score > max_score) {
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001612 if (ip_type == AF_INET)
1613 newip4 = ip;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001614 else
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001615 newip6 = ip;
Emeric Brunca8e3552021-06-11 10:08:05 +02001616 found_record = record;
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001617 currentip_found = currentip_sel;
Emeric Brunca8e3552021-06-11 10:08:05 +02001618 if (score == 15) {
1619 /* this was not registered on the current record but it matches
1620 * let's fix it (it may comes from state file */
1621 if (owner)
1622 LIST_ADDQ(&found_record->attached_servers, &owner->ip_rec_item);
1623 return DNS_UPD_NO;
1624 }
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001625 max_score = score;
1626 }
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001627 } /* list for each record entries */
Thierry Fournierac88cfe2016-02-17 22:05:30 +01001628
Christopher Faulet67957bd2017-09-27 11:00:59 +02001629 /* No IP found in the response */
Olivier Houcharda8c6db82017-07-06 18:46:47 +02001630 if (!newip4 && !newip6)
Baptiste Assmann0453a1d2015-09-09 00:51:08 +02001631 return DNS_UPD_NO_IP_FOUND;
Baptiste Assmann0453a1d2015-09-09 00:51:08 +02001632
Christopher Faulet67957bd2017-09-27 11:00:59 +02001633 /* Case when the caller looks first for an IPv4 address */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001634 if (family_priority == AF_INET) {
1635 if (newip4) {
1636 *newip = newip4;
1637 *newip_sin_family = AF_INET;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001638 }
1639 else if (newip6) {
1640 *newip = newip6;
1641 *newip_sin_family = AF_INET6;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001642 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001643 if (!currentip_found)
1644 goto not_found;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001645 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001646 /* Case when the caller looks first for an IPv6 address */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001647 else if (family_priority == AF_INET6) {
1648 if (newip6) {
1649 *newip = newip6;
1650 *newip_sin_family = AF_INET6;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001651 }
1652 else if (newip4) {
1653 *newip = newip4;
1654 *newip_sin_family = AF_INET;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001655 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001656 if (!currentip_found)
1657 goto not_found;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001658 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001659 /* Case when the caller have no preference (we prefer IPv6) */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001660 else if (family_priority == AF_UNSPEC) {
1661 if (newip6) {
1662 *newip = newip6;
1663 *newip_sin_family = AF_INET6;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001664 }
1665 else if (newip4) {
1666 *newip = newip4;
1667 *newip_sin_family = AF_INET;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001668 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001669 if (!currentip_found)
1670 goto not_found;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001671 }
1672
Christopher Faulet67957bd2017-09-27 11:00:59 +02001673 /* No reason why we should change the server's IP address */
Baptiste Assmann325137d2015-04-13 23:40:55 +02001674 return DNS_UPD_NO;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001675
Christopher Faulet67957bd2017-09-27 11:00:59 +02001676 not_found:
Emeric Brunca8e3552021-06-11 10:08:05 +02001677
1678 /* the ip of this record was chosen for the server */
1679 if (owner && found_record) {
1680 LIST_ADDQ(&found_record->attached_servers, &owner->ip_rec_item);
1681 }
1682
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001683 list_for_each_entry(record, &dns_p->answer_list, list) {
Christopher Faulet67957bd2017-09-27 11:00:59 +02001684 /* Move the first record to the end of the list, for internal
1685 * round robin */
1686 LIST_DEL(&record->list);
1687 LIST_ADDQ(&dns_p->answer_list, &record->list);
1688 break;
Baptiste Assmann8ea0bcc2017-05-04 08:24:11 +02001689 }
1690 return DNS_UPD_SRVIP_NOT_FOUND;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001691}
1692
Christopher Faulet67957bd2017-09-27 11:00:59 +02001693/* Turns a domain name label into a string.
Baptiste Assmann201c07f2017-05-22 15:17:15 +02001694 *
Christopher Faulet67957bd2017-09-27 11:00:59 +02001695 * <dn> must be a null-terminated string. <dn_len> must include the terminating
1696 * null byte. <str> must be allocated and its size must be passed in <str_len>.
Baptiste Assmann325137d2015-04-13 23:40:55 +02001697 *
Christopher Faulet67957bd2017-09-27 11:00:59 +02001698 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1699 * <str> (including the terminating null byte).
Baptiste Assmann325137d2015-04-13 23:40:55 +02001700 */
Christopher Faulet67957bd2017-09-27 11:00:59 +02001701int dns_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001702{
Christopher Faulet67957bd2017-09-27 11:00:59 +02001703 char *ptr;
1704 int i, sz;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001705
Christopher Faulet67957bd2017-09-27 11:00:59 +02001706 if (str_len < dn_len - 1)
Baptiste Assmann2af08fe2017-08-14 00:13:01 +02001707 return -1;
1708
Christopher Faulet67957bd2017-09-27 11:00:59 +02001709 ptr = str;
1710 for (i = 0; i < dn_len-1; ++i) {
1711 sz = dn[i];
1712 if (i)
1713 *ptr++ = '.';
1714 memcpy(ptr, dn+i+1, sz);
1715 ptr += sz;
1716 i += sz;
Olivier Houchard8da5f982017-08-04 18:35:36 +02001717 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001718 *ptr++ = '\0';
1719 return (ptr - str);
Olivier Houchard8da5f982017-08-04 18:35:36 +02001720}
1721
Christopher Faulet67957bd2017-09-27 11:00:59 +02001722/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1723 *
1724 * <str> must be a null-terminated string. <str_len> must include the
1725 * terminating null byte. <dn> buffer must be allocated and its size must be
1726 * passed in <dn_len>.
1727 *
1728 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1729 * <dn> (excluding the terminating null byte).
Baptiste Assmann325137d2015-04-13 23:40:55 +02001730 */
Christopher Faulet67957bd2017-09-27 11:00:59 +02001731int dns_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001732{
Baptiste Assmann325137d2015-04-13 23:40:55 +02001733 int i, offset;
1734
Christopher Faulet67957bd2017-09-27 11:00:59 +02001735 if (dn_len < str_len + 1)
1736 return -1;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001737
Christopher Faulet67957bd2017-09-27 11:00:59 +02001738 /* First byte of dn will be used to store the length of the first
1739 * label */
1740 offset = 0;
1741 for (i = 0; i < str_len; ++i) {
1742 if (str[i] == '.') {
1743 /* 2 or more consecutive dots is invalid */
1744 if (i == offset)
1745 return -1;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001746
Lukas Tribus81725b82020-02-27 15:47:24 +01001747 /* ignore trailing dot */
1748 if (i + 2 == str_len) {
1749 i++;
1750 break;
1751 }
1752
Christopher Faulet67957bd2017-09-27 11:00:59 +02001753 dn[offset] = (i - offset);
1754 offset = i+1;
1755 continue;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001756 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001757 dn[i+1] = str[i];
Baptiste Assmann325137d2015-04-13 23:40:55 +02001758 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001759 dn[offset] = (i - offset - 1);
1760 dn[i] = '\0';
1761 return i;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001762}
1763
Christopher Faulet67957bd2017-09-27 11:00:59 +02001764/* Validates host name:
Baptiste Assmann325137d2015-04-13 23:40:55 +02001765 * - total size
1766 * - each label size individually
1767 * returns:
1768 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1769 * 1 when no error. <err> is left unaffected.
1770 */
1771int dns_hostname_validation(const char *string, char **err)
1772{
Baptiste Assmann325137d2015-04-13 23:40:55 +02001773 int i;
1774
1775 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1776 if (err)
1777 *err = DNS_TOO_LONG_FQDN;
1778 return 0;
1779 }
1780
William Dauchyaecd5dc2020-01-26 19:52:34 +01001781 while (*string) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001782 i = 0;
William Dauchyaecd5dc2020-01-26 19:52:34 +01001783 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1784 if (!(*string == '-' || *string == '_' ||
1785 (*string >= 'a' && *string <= 'z') ||
1786 (*string >= 'A' && *string <= 'Z') ||
1787 (*string >= '0' && *string <= '9'))) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001788 if (err)
1789 *err = DNS_INVALID_CHARACTER;
1790 return 0;
1791 }
William Dauchyaecd5dc2020-01-26 19:52:34 +01001792 i++;
1793 string++;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001794 }
1795
William Dauchyaecd5dc2020-01-26 19:52:34 +01001796 if (!(*string))
1797 break;
1798
1799 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
Baptiste Assmann325137d2015-04-13 23:40:55 +02001800 if (err)
1801 *err = DNS_LABEL_TOO_LONG;
1802 return 0;
1803 }
1804
William Dauchyaecd5dc2020-01-26 19:52:34 +01001805 string++;
Baptiste Assmann325137d2015-04-13 23:40:55 +02001806 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02001807 return 1;
1808}
1809
Christopher Faulet67957bd2017-09-27 11:00:59 +02001810/* Picks up an available resolution from the different resolution list
1811 * associated to a resolvers section, in this order:
1812 * 1. check in resolutions.curr for the same hostname and query_type
1813 * 2. check in resolutions.wait for the same hostname and query_type
1814 * 3. Get a new resolution from resolution pool
1815 *
1816 * Returns an available resolution, NULL if none found.
Baptiste Assmann325137d2015-04-13 23:40:55 +02001817 */
Christopher Faulet67957bd2017-09-27 11:00:59 +02001818static struct dns_resolution *dns_pick_resolution(struct dns_resolvers *resolvers,
1819 char **hostname_dn, int hostname_dn_len,
1820 int query_type)
Baptiste Assmann325137d2015-04-13 23:40:55 +02001821{
Christopher Faulet67957bd2017-09-27 11:00:59 +02001822 struct dns_resolution *res;
1823
1824 if (!*hostname_dn)
1825 goto from_pool;
1826
1827 /* Search for same hostname and query type in resolutions.curr */
1828 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1829 if (!res->hostname_dn)
1830 continue;
1831 if ((query_type == res->prefered_query_type) &&
1832 hostname_dn_len == res->hostname_dn_len &&
Olivier Houchardb17b8842020-04-01 18:30:27 +02001833 !dns_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
Christopher Faulet67957bd2017-09-27 11:00:59 +02001834 return res;
1835 }
1836
1837 /* Search for same hostname and query type in resolutions.wait */
1838 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1839 if (!res->hostname_dn)
1840 continue;
1841 if ((query_type == res->prefered_query_type) &&
1842 hostname_dn_len == res->hostname_dn_len &&
Olivier Houchardb17b8842020-04-01 18:30:27 +02001843 !dns_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
Christopher Faulet67957bd2017-09-27 11:00:59 +02001844 return res;
1845 }
1846
1847 from_pool:
1848 /* No resolution could be found, so let's allocate a new one */
Willy Tarreaubafbe012017-11-24 17:34:44 +01001849 res = pool_alloc(dns_resolution_pool);
Christopher Faulet67957bd2017-09-27 11:00:59 +02001850 if (res) {
1851 memset(res, 0, sizeof(*res));
1852 res->resolvers = resolvers;
1853 res->uuid = resolution_uuid;
1854 res->status = RSLV_STATUS_NONE;
1855 res->step = RSLV_STEP_NONE;
1856 res->last_valid = now_ms;
1857
1858 LIST_INIT(&res->requesters);
1859 LIST_INIT(&res->response.answer_list);
1860
1861 res->prefered_query_type = query_type;
1862 res->query_type = query_type;
1863 res->hostname_dn = *hostname_dn;
1864 res->hostname_dn_len = hostname_dn_len;
1865
1866 ++resolution_uuid;
1867
1868 /* Move the resolution to the resolvers wait queue */
1869 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
1870 }
1871 return res;
1872}
1873
Christopher Faulet656b4272021-03-10 14:40:39 +01001874void dns_purge_resolution_answer_records(struct dns_resolution *resolution)
1875{
1876 struct dns_answer_item *item, *itemback;
1877
1878 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
1879 LIST_DEL(&item->list);
1880 pool_free(dns_answer_item_pool, item->ar_item);
1881 pool_free(dns_answer_item_pool, item);
1882 }
1883}
1884
Christopher Faulet67957bd2017-09-27 11:00:59 +02001885/* Releases a resolution from its requester(s) and move it back to the pool */
1886static void dns_free_resolution(struct dns_resolution *resolution)
1887{
1888 struct dns_requester *req, *reqback;
1889
1890 /* clean up configuration */
1891 dns_reset_resolution(resolution);
1892 resolution->hostname_dn = NULL;
1893 resolution->hostname_dn_len = 0;
1894
1895 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
1896 LIST_DEL(&req->list);
1897 req->resolution = NULL;
1898 }
Christopher Faulet656b4272021-03-10 14:40:39 +01001899 dns_purge_resolution_answer_records(resolution);
Christopher Faulet67957bd2017-09-27 11:00:59 +02001900 LIST_DEL(&resolution->list);
Willy Tarreaubafbe012017-11-24 17:34:44 +01001901 pool_free(dns_resolution_pool, resolution);
Christopher Faulet67957bd2017-09-27 11:00:59 +02001902}
1903
1904/* Links a requester (a server or a dns_srvrq) with a resolution. It returns 0
1905 * on success, -1 otherwise.
1906 */
Olivier Houchard55dcdf42017-11-06 15:15:04 +01001907int dns_link_resolution(void *requester, int requester_type, int requester_locked)
Christopher Faulet67957bd2017-09-27 11:00:59 +02001908{
1909 struct dns_resolution *res = NULL;
1910 struct dns_requester *req;
1911 struct dns_resolvers *resolvers;
1912 struct server *srv = NULL;
1913 struct dns_srvrq *srvrq = NULL;
Baptiste Assmann333939c2019-01-21 08:34:50 +01001914 struct stream *stream = NULL;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001915 char **hostname_dn;
1916 int hostname_dn_len, query_type;
1917
1918 switch (requester_type) {
1919 case OBJ_TYPE_SERVER:
1920 srv = (struct server *)requester;
1921 hostname_dn = &srv->hostname_dn;
1922 hostname_dn_len = srv->hostname_dn_len;
1923 resolvers = srv->resolvers;
1924 query_type = ((srv->dns_opts.family_prio == AF_INET)
1925 ? DNS_RTYPE_A
1926 : DNS_RTYPE_AAAA);
1927 break;
1928
1929 case OBJ_TYPE_SRVRQ:
1930 srvrq = (struct dns_srvrq *)requester;
1931 hostname_dn = &srvrq->hostname_dn;
1932 hostname_dn_len = srvrq->hostname_dn_len;
1933 resolvers = srvrq->resolvers;
1934 query_type = DNS_RTYPE_SRV;
1935 break;
1936
Baptiste Assmann333939c2019-01-21 08:34:50 +01001937 case OBJ_TYPE_STREAM:
1938 stream = (struct stream *)requester;
1939 hostname_dn = &stream->dns_ctx.hostname_dn;
1940 hostname_dn_len = stream->dns_ctx.hostname_dn_len;
1941 resolvers = stream->dns_ctx.parent->arg.dns.resolvers;
Christopher Fauleta4168432020-01-24 18:08:42 +01001942 query_type = ((stream->dns_ctx.parent->arg.dns.dns_opts->family_prio == AF_INET)
Baptiste Assmann333939c2019-01-21 08:34:50 +01001943 ? DNS_RTYPE_A
1944 : DNS_RTYPE_AAAA);
1945 break;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001946 default:
1947 goto err;
1948 }
1949
1950 /* Get a resolution from the resolvers' wait queue or pool */
1951 if ((res = dns_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
1952 goto err;
1953
1954 if (srv) {
Olivier Houchard55dcdf42017-11-06 15:15:04 +01001955 if (!requester_locked)
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001956 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +02001957 if (srv->dns_requester == NULL) {
Baptiste Assmanndfd35fd2019-01-21 08:18:09 +01001958 if ((req = pool_alloc(dns_requester_pool)) == NULL) {
Olivier Houchard55dcdf42017-11-06 15:15:04 +01001959 if (!requester_locked)
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001960 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +02001961 goto err;
Willy Tarreau5ec84572017-11-05 10:35:57 +01001962 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02001963 req->owner = &srv->obj_type;
1964 srv->dns_requester = req;
1965 }
1966 else
1967 req = srv->dns_requester;
Olivier Houchard55dcdf42017-11-06 15:15:04 +01001968 if (!requester_locked)
Christopher Faulet2a944ee2017-11-07 10:42:54 +01001969 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
Baptiste Assmanndb4c8522018-01-30 08:08:04 +01001970
1971 req->requester_cb = snr_resolution_cb;
1972 req->requester_error_cb = snr_resolution_error_cb;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001973 }
1974 else if (srvrq) {
1975 if (srvrq->dns_requester == NULL) {
Baptiste Assmanndfd35fd2019-01-21 08:18:09 +01001976 if ((req = pool_alloc(dns_requester_pool)) == NULL)
Christopher Faulet67957bd2017-09-27 11:00:59 +02001977 goto err;
1978 req->owner = &srvrq->obj_type;
1979 srvrq->dns_requester = req;
1980 }
1981 else
1982 req = srvrq->dns_requester;
Baptiste Assmanndb4c8522018-01-30 08:08:04 +01001983
1984 req->requester_cb = snr_resolution_cb;
Baptiste Assmann826060e2020-11-19 22:38:33 +01001985 req->requester_error_cb = srvrq_resolution_error_cb;
Christopher Faulet67957bd2017-09-27 11:00:59 +02001986 }
Baptiste Assmann333939c2019-01-21 08:34:50 +01001987 else if (stream) {
1988 if (stream->dns_ctx.dns_requester == NULL) {
1989 if ((req = pool_alloc(dns_requester_pool)) == NULL)
1990 goto err;
1991 req->owner = &stream->obj_type;
1992 stream->dns_ctx.dns_requester = req;
1993 }
1994 else
1995 req = stream->dns_ctx.dns_requester;
1996
1997 req->requester_cb = act_resolution_cb;
1998 req->requester_error_cb = act_resolution_error_cb;
1999 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002000 else
2001 goto err;
2002
2003 req->resolution = res;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002004
2005 LIST_ADDQ(&res->requesters, &req->list);
2006 return 0;
2007
2008 err:
2009 if (res && LIST_ISEMPTY(&res->requesters))
2010 dns_free_resolution(res);
2011 return -1;
2012}
2013
Emeric Brun32131d42021-06-11 10:48:45 +02002014/* This function removes all server/srvrq references on answer items
2015 * if <safe> is set to 1, in case of srvrq, sub server resquesters unlink
2016 * is called using safe == 1 to make it usable into callbacks
2017 */
2018void dns_detach_from_resolution_answer_items(struct dns_resolution *res, struct dns_requester *req, int safe)
2019{
2020 struct dns_answer_item *item, *itemback;
2021 struct server *srv, *srvback;
2022 struct dns_srvrq *srvrq;
2023
2024 if ((srv = objt_server(req->owner)) != NULL) {
2025 LIST_DEL_INIT(&srv->ip_rec_item);
2026 }
2027 else if ((srvrq = objt_dns_srvrq(req->owner)) != NULL) {
2028 list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
2029 if (item->type == DNS_RTYPE_SRV) {
2030 list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
Christopher Fauletcab96e12021-06-15 16:08:48 +02002031 if (srv->srvrq == srvrq)
2032 dns_srvrq_cleanup_srv(srv);
Emeric Brun32131d42021-06-11 10:48:45 +02002033 }
2034 }
2035 }
2036 }
2037}
2038
2039
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05002040/* Removes a requester from a DNS resolution. It takes takes care of all the
Christopher Faulet67957bd2017-09-27 11:00:59 +02002041 * consequences. It also cleans up some parameters from the requester.
Christopher Faulet119ec522021-03-11 18:09:53 +01002042 * if <safe> is set to 1, the corresponding resolution is not released.
Christopher Faulet67957bd2017-09-27 11:00:59 +02002043 */
Christopher Faulet119ec522021-03-11 18:09:53 +01002044void dns_unlink_resolution(struct dns_requester *requester, int safe)
Christopher Faulet67957bd2017-09-27 11:00:59 +02002045{
2046 struct dns_resolution *res;
2047 struct dns_requester *req;
2048
2049 /* Nothing to do */
2050 if (!requester || !requester->resolution)
2051 return;
2052 res = requester->resolution;
2053
Emeric Brunca8e3552021-06-11 10:08:05 +02002054 /* remove ref from the resolution answer item list to the requester */
Emeric Brun32131d42021-06-11 10:48:45 +02002055 dns_detach_from_resolution_answer_items(res, requester, safe);
Emeric Brunca8e3552021-06-11 10:08:05 +02002056
Christopher Faulet67957bd2017-09-27 11:00:59 +02002057 /* Clean up the requester */
2058 LIST_DEL(&requester->list);
2059 requester->resolution = NULL;
2060
2061 /* We need to find another requester linked on this resolution */
2062 if (!LIST_ISEMPTY(&res->requesters))
2063 req = LIST_NEXT(&res->requesters, struct dns_requester *, list);
2064 else {
Christopher Faulet119ec522021-03-11 18:09:53 +01002065 if (safe) {
2066 /* Don't release it yet. */
2067 dns_reset_resolution(res);
2068 res->hostname_dn = NULL;
2069 res->hostname_dn_len = 0;
2070 dns_purge_resolution_answer_records(res);
2071 return;
2072 }
2073
Christopher Faulet67957bd2017-09-27 11:00:59 +02002074 dns_free_resolution(res);
2075 return;
2076 }
2077
2078 /* Move hostname_dn related pointers to the next requester */
2079 switch (obj_type(req->owner)) {
2080 case OBJ_TYPE_SERVER:
Willy Tarreau433c16f2018-09-20 11:15:27 +02002081 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
2082 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002083 break;
2084 case OBJ_TYPE_SRVRQ:
Willy Tarreau433c16f2018-09-20 11:15:27 +02002085 res->hostname_dn = __objt_dns_srvrq(req->owner)->hostname_dn;
2086 res->hostname_dn_len = __objt_dns_srvrq(req->owner)->hostname_dn_len;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002087 break;
Baptiste Assmann333939c2019-01-21 08:34:50 +01002088 case OBJ_TYPE_STREAM:
2089 res->hostname_dn = __objt_stream(req->owner)->dns_ctx.hostname_dn;
2090 res->hostname_dn_len = __objt_stream(req->owner)->dns_ctx.hostname_dn_len;
2091 break;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002092 default:
2093 res->hostname_dn = NULL;
2094 res->hostname_dn_len = 0;
2095 break;
2096 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02002097}
2098
Christopher Faulet67957bd2017-09-27 11:00:59 +02002099/* Called when a network IO is generated on a name server socket for an incoming
2100 * packet. It performs the following actions:
2101 * - check if the packet requires processing (not outdated resolution)
2102 * - ensure the DNS packet received is valid and call requester's callback
2103 * - call requester's error callback if invalid response
2104 * - check the dn_name in the packet against the one sent
2105 */
2106static void dns_resolve_recv(struct dgram_conn *dgram)
2107{
2108 struct dns_nameserver *ns, *tmpns;
2109 struct dns_resolvers *resolvers;
2110 struct dns_resolution *res;
2111 struct dns_query_item *query;
2112 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
2113 unsigned char *bufend;
2114 int fd, buflen, dns_resp;
2115 int max_answer_records;
2116 unsigned short query_id;
2117 struct eb32_node *eb;
2118 struct dns_requester *req;
Emeric Bruna8b60f22021-06-10 15:25:25 +02002119 int keep_answer_items;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002120
2121 fd = dgram->t.sock.fd;
2122
2123 /* check if ready for reading */
2124 if (!fd_recv_ready(fd))
2125 return;
2126
2127 /* no need to go further if we can't retrieve the nameserver */
Willy Tarreau1c759952019-12-10 18:38:09 +01002128 if ((ns = dgram->owner) == NULL) {
2129 _HA_ATOMIC_AND(&fdtab[fd].ev, ~(FD_POLL_HUP|FD_POLL_ERR));
2130 fd_stop_recv(fd);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002131 return;
Willy Tarreau1c759952019-12-10 18:38:09 +01002132 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002133
2134 resolvers = ns->resolvers;
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002135 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002136
2137 /* process all pending input messages */
Willy Tarreau1c759952019-12-10 18:38:09 +01002138 while (fd_recv_ready(fd)) {
Christopher Faulet67957bd2017-09-27 11:00:59 +02002139 /* read message received */
2140 memset(buf, '\0', resolvers->accepted_payload_size + 1);
2141 if ((buflen = recv(fd, (char*)buf , resolvers->accepted_payload_size + 1, 0)) < 0) {
Willy Tarreau1c759952019-12-10 18:38:09 +01002142 /* FIXME : for now we consider EAGAIN only, but at
2143 * least we purge sticky errors that would cause us to
2144 * be called in loops.
2145 */
2146 _HA_ATOMIC_AND(&fdtab[fd].ev, ~(FD_POLL_HUP|FD_POLL_ERR));
Christopher Faulet67957bd2017-09-27 11:00:59 +02002147 fd_cant_recv(fd);
2148 break;
2149 }
2150
2151 /* message too big */
2152 if (buflen > resolvers->accepted_payload_size) {
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002153 ns->counters->too_big++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002154 continue;
2155 }
2156
2157 /* initializing variables */
2158 bufend = buf + buflen; /* pointer to mark the end of the buffer */
2159
2160 /* read the query id from the packet (16 bits) */
2161 if (buf + 2 > bufend) {
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002162 ns->counters->invalid++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002163 continue;
2164 }
2165 query_id = dns_response_get_query_id(buf);
2166
2167 /* search the query_id in the pending resolution tree */
2168 eb = eb32_lookup(&resolvers->query_ids, query_id);
2169 if (eb == NULL) {
2170 /* unknown query id means an outdated response and can be safely ignored */
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002171 ns->counters->outdated++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002172 continue;
2173 }
2174
William Dauchybe8a3872019-11-27 23:32:41 +01002175 /* known query id means a resolution in progress */
Christopher Faulet67957bd2017-09-27 11:00:59 +02002176 res = eb32_entry(eb, struct dns_resolution, qid);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002177 /* number of responses received */
2178 res->nb_responses++;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002179
Christopher Faulet67957bd2017-09-27 11:00:59 +02002180 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
2181 dns_resp = dns_validate_dns_response(buf, bufend, res, max_answer_records);
Baptiste Assmann325137d2015-04-13 23:40:55 +02002182
Christopher Faulet67957bd2017-09-27 11:00:59 +02002183 switch (dns_resp) {
2184 case DNS_RESP_VALID:
2185 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002186
Christopher Faulet67957bd2017-09-27 11:00:59 +02002187 case DNS_RESP_INVALID:
2188 case DNS_RESP_QUERY_COUNT_ERROR:
2189 case DNS_RESP_WRONG_NAME:
2190 res->status = RSLV_STATUS_INVALID;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002191 ns->counters->invalid++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002192 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002193
Christopher Faulet67957bd2017-09-27 11:00:59 +02002194 case DNS_RESP_NX_DOMAIN:
2195 res->status = RSLV_STATUS_NX;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002196 ns->counters->nx++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002197 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002198
Christopher Faulet67957bd2017-09-27 11:00:59 +02002199 case DNS_RESP_REFUSED:
2200 res->status = RSLV_STATUS_REFUSED;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002201 ns->counters->refused++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002202 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002203
Christopher Faulet67957bd2017-09-27 11:00:59 +02002204 case DNS_RESP_ANCOUNT_ZERO:
2205 res->status = RSLV_STATUS_OTHER;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002206 ns->counters->any_err++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002207 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002208
Christopher Faulet67957bd2017-09-27 11:00:59 +02002209 case DNS_RESP_CNAME_ERROR:
2210 res->status = RSLV_STATUS_OTHER;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002211 ns->counters->cname_error++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002212 break;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002213
Christopher Faulet67957bd2017-09-27 11:00:59 +02002214 case DNS_RESP_TRUNCATED:
2215 res->status = RSLV_STATUS_OTHER;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002216 ns->counters->truncated++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002217 break;
Baptiste Assmanne70bc052017-08-21 16:51:09 +02002218
Christopher Faulet67957bd2017-09-27 11:00:59 +02002219 case DNS_RESP_NO_EXPECTED_RECORD:
2220 case DNS_RESP_ERROR:
2221 case DNS_RESP_INTERNAL:
2222 res->status = RSLV_STATUS_OTHER;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002223 ns->counters->other++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002224 break;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002225 }
2226
Christopher Faulet67957bd2017-09-27 11:00:59 +02002227 /* Wait all nameservers response to handle errors */
2228 if (dns_resp != DNS_RESP_VALID && res->nb_responses < resolvers->nb_nameservers)
2229 continue;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002230
Christopher Faulet67957bd2017-09-27 11:00:59 +02002231 /* Process error codes */
2232 if (dns_resp != DNS_RESP_VALID) {
2233 if (res->prefered_query_type != res->query_type) {
2234 /* The fallback on the query type was already performed,
2235 * so check the try counter. If it falls to 0, we can
2236 * report an error. Else, wait the next attempt. */
2237 if (!res->try)
2238 goto report_res_error;
2239 }
2240 else {
2241 /* Fallback from A to AAAA or the opposite and re-send
2242 * the resolution immediately. try counter is not
2243 * decremented. */
2244 if (res->prefered_query_type == DNS_RTYPE_A) {
2245 res->query_type = DNS_RTYPE_AAAA;
2246 dns_send_query(res);
Olivier Houchard8da5f982017-08-04 18:35:36 +02002247 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002248 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
2249 res->query_type = DNS_RTYPE_A;
2250 dns_send_query(res);
Olivier Houchard8da5f982017-08-04 18:35:36 +02002251 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002252 }
2253 continue;
2254 }
Olivier Houchard8da5f982017-08-04 18:35:36 +02002255
Christopher Faulet67957bd2017-09-27 11:00:59 +02002256 /* Now let's check the query's dname corresponds to the one we
2257 * sent. We can check only the first query of the list. We send
2258 * one query at a time so we get one query in the response */
2259 query = LIST_NEXT(&res->response.query_list, struct dns_query_item *, list);
Olivier Houchardb17b8842020-04-01 18:30:27 +02002260 if (query && dns_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
Christopher Faulet67957bd2017-09-27 11:00:59 +02002261 dns_resp = DNS_RESP_WRONG_NAME;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002262 ns->counters->other++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002263 goto report_res_error;
2264 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002265
Christopher Faulet67957bd2017-09-27 11:00:59 +02002266 /* So the resolution succeeded */
2267 res->status = RSLV_STATUS_VALID;
2268 res->last_valid = now_ms;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002269 ns->counters->valid++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002270 goto report_res_success;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002271
Christopher Faulet67957bd2017-09-27 11:00:59 +02002272 report_res_error:
Emeric Bruna8b60f22021-06-10 15:25:25 +02002273 keep_answer_items = 0;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002274 list_for_each_entry(req, &res->requesters, list)
Emeric Bruna8b60f22021-06-10 15:25:25 +02002275 keep_answer_items |= req->requester_error_cb(req, dns_resp);
2276 if (!keep_answer_items)
2277 dns_purge_resolution_answer_records(res);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002278 dns_reset_resolution(res);
2279 LIST_DEL(&res->list);
2280 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2281 continue;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002282
Christopher Faulet67957bd2017-09-27 11:00:59 +02002283 report_res_success:
2284 /* Only the 1rst requester s managed by the server, others are
2285 * from the cache */
2286 tmpns = ns;
2287 list_for_each_entry(req, &res->requesters, list) {
Olivier Houchard28381072017-11-06 17:30:28 +01002288 struct server *s = objt_server(req->owner);
2289
2290 if (s)
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002291 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002292 req->requester_cb(req, tmpns);
Olivier Houchard28381072017-11-06 17:30:28 +01002293 if (s)
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002294 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002295 tmpns = NULL;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002296 }
Baptiste Assmann42746372017-05-03 12:12:02 +02002297
Christopher Faulet67957bd2017-09-27 11:00:59 +02002298 dns_reset_resolution(res);
2299 LIST_DEL(&res->list);
2300 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2301 continue;
Baptiste Assmann325137d2015-04-13 23:40:55 +02002302 }
Baptiste Assmann325137d2015-04-13 23:40:55 +02002303 dns_update_resolvers_timeout(resolvers);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002304 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Baptiste Assmann325137d2015-04-13 23:40:55 +02002305}
William Lallemand69e96442016-11-19 00:58:54 +01002306
Christopher Faulet67957bd2017-09-27 11:00:59 +02002307/* Called when a resolvers network socket is ready to send data */
2308static void dns_resolve_send(struct dgram_conn *dgram)
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002309{
Christopher Faulet67957bd2017-09-27 11:00:59 +02002310 struct dns_resolvers *resolvers;
2311 struct dns_nameserver *ns;
2312 struct dns_resolution *res;
2313 int fd;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002314
Christopher Faulet67957bd2017-09-27 11:00:59 +02002315 fd = dgram->t.sock.fd;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002316
Christopher Faulet67957bd2017-09-27 11:00:59 +02002317 /* check if ready for sending */
2318 if (!fd_send_ready(fd))
2319 return;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002320
Christopher Faulet67957bd2017-09-27 11:00:59 +02002321 /* we don't want/need to be waked up any more for sending */
2322 fd_stop_send(fd);
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002323
Christopher Faulet67957bd2017-09-27 11:00:59 +02002324 /* no need to go further if we can't retrieve the nameserver */
2325 if ((ns = dgram->owner) == NULL)
2326 return;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002327
Christopher Faulet67957bd2017-09-27 11:00:59 +02002328 resolvers = ns->resolvers;
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002329 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
Christopher Fauletb2812a62017-10-04 16:17:58 +02002330
Christopher Faulet67957bd2017-09-27 11:00:59 +02002331 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
Willy Tarreauf6ee9dc2018-08-22 04:52:02 +02002332 int ret, len;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002333
Christopher Faulet67957bd2017-09-27 11:00:59 +02002334 if (res->nb_queries == resolvers->nb_nameservers)
2335 continue;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002336
Emeric Brun079c6092021-06-17 18:23:04 +02002337 /* if fd was detected broken by previous send */
2338 if (fd == -1)
2339 goto snd_error;
2340
Willy Tarreauf6ee9dc2018-08-22 04:52:02 +02002341 len = dns_build_query(res->query_id, res->query_type,
2342 resolvers->accepted_payload_size,
2343 res->hostname_dn, res->hostname_dn_len,
2344 trash.area, trash.size);
2345 if (len == -1)
Christopher Faulet67957bd2017-09-27 11:00:59 +02002346 goto snd_error;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002347
Willy Tarreauf6ee9dc2018-08-22 04:52:02 +02002348 ret = send(fd, trash.area, len, 0);
Willy Tarreau0eae6322019-12-20 11:18:54 +01002349 if (ret != len) {
Emeric Brun751872e2021-05-04 18:16:53 +02002350 if (ret == -1) {
2351 if (errno == EAGAIN) {
2352 /* retry once the socket is ready */
2353 fd_cant_send(fd);
2354 continue;
2355 }
2356
2357 /* purge the fd and set sock.fd to -1
2358 * to create a new one during next
2359 * send_query attempt to the same
2360 * nameserver
2361 */
2362 fd_delete(fd);
Emeric Brun079c6092021-06-17 18:23:04 +02002363 fd = dgram->t.sock.fd = -1;
Willy Tarreau0eae6322019-12-20 11:18:54 +01002364 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002365 goto snd_error;
Willy Tarreau0eae6322019-12-20 11:18:54 +01002366 }
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002367
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002368 ns->counters->sent++;
2369
Christopher Faulet67957bd2017-09-27 11:00:59 +02002370 res->nb_queries++;
2371 continue;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002372
Christopher Faulet67957bd2017-09-27 11:00:59 +02002373 snd_error:
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002374 ns->counters->snd_error++;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002375 res->nb_queries++;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002376 }
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002377 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002378}
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002379
Christopher Faulet67957bd2017-09-27 11:00:59 +02002380/* Processes DNS resolution. First, it checks the active list to detect expired
2381 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2382 * checks the wait list to trigger new resolutions.
2383 */
Olivier Houchard9f6af332018-05-25 14:04:04 +02002384static struct task *dns_process_resolvers(struct task *t, void *context, unsigned short state)
Christopher Faulet67957bd2017-09-27 11:00:59 +02002385{
Olivier Houchard9f6af332018-05-25 14:04:04 +02002386 struct dns_resolvers *resolvers = context;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002387 struct dns_resolution *res, *resback;
2388 int exp;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002389
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002390 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
Christopher Fauletb2812a62017-10-04 16:17:58 +02002391
Christopher Faulet67957bd2017-09-27 11:00:59 +02002392 /* Handle all expired resolutions from the active list */
2393 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
Christopher Faulet119ec522021-03-11 18:09:53 +01002394 if (LIST_ISEMPTY(&res->requesters)) {
2395 dns_free_resolution(res);
2396 continue;
2397 }
2398
Christopher Faulet67957bd2017-09-27 11:00:59 +02002399 /* When we find the first resolution in the future, then we can
2400 * stop here */
2401 exp = tick_add(res->last_query, resolvers->timeout.retry);
2402 if (!tick_is_expired(exp, now_ms))
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002403 break;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002404
Christopher Faulet67957bd2017-09-27 11:00:59 +02002405 /* If current resolution has been tried too many times and
2406 * finishes in timeout we update its status and remove it from
2407 * the list */
2408 if (!res->try) {
2409 struct dns_requester *req;
Emeric Bruna8b60f22021-06-10 15:25:25 +02002410 int keep_answer_items = 0;
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002411
Christopher Faulet67957bd2017-09-27 11:00:59 +02002412 /* Notify the result to the requesters */
2413 if (!res->nb_responses)
2414 res->status = RSLV_STATUS_TIMEOUT;
2415 list_for_each_entry(req, &res->requesters, list)
Emeric Bruna8b60f22021-06-10 15:25:25 +02002416 keep_answer_items |= req->requester_error_cb(req, res->status);
2417 if (!keep_answer_items)
2418 dns_purge_resolution_answer_records(res);
Baptiste Assmannfa4a6632017-05-04 09:05:00 +02002419
Christopher Faulet67957bd2017-09-27 11:00:59 +02002420 /* Clean up resolution info and remove it from the
2421 * current list */
2422 dns_reset_resolution(res);
2423 LIST_DEL(&res->list);
2424 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
William Lallemand69e96442016-11-19 00:58:54 +01002425 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002426 else {
2427 /* Otherwise resend the DNS query and requeue the resolution */
2428 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2429 /* No response received (a real timeout) or fallback already done */
2430 res->query_type = res->prefered_query_type;
2431 res->try--;
2432 }
2433 else {
2434 /* Fallback from A to AAAA or the opposite and re-send
2435 * the resolution immediately. try counter is not
2436 * decremented. */
2437 if (res->prefered_query_type == DNS_RTYPE_A)
2438 res->query_type = DNS_RTYPE_AAAA;
2439 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2440 res->query_type = DNS_RTYPE_A;
2441 else
2442 res->try--;
2443 }
2444 dns_send_query(res);
William Lallemand69e96442016-11-19 00:58:54 +01002445 }
2446 }
William Lallemand69e96442016-11-19 00:58:54 +01002447
Christopher Faulet67957bd2017-09-27 11:00:59 +02002448 /* Handle all resolutions in the wait list */
2449 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
Christopher Faulet119ec522021-03-11 18:09:53 +01002450 if (LIST_ISEMPTY(&res->requesters)) {
2451 dns_free_resolution(res);
2452 continue;
2453 }
2454
Christopher Faulet67957bd2017-09-27 11:00:59 +02002455 exp = tick_add(res->last_resolution, dns_resolution_timeout(res));
2456 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2457 continue;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002458
Christopher Faulet67957bd2017-09-27 11:00:59 +02002459 if (dns_run_resolution(res) != 1) {
2460 res->last_resolution = now_ms;
2461 LIST_DEL(&res->list);
2462 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002463 }
2464 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002465
Christopher Faulet67957bd2017-09-27 11:00:59 +02002466 dns_update_resolvers_timeout(resolvers);
Christopher Faulet2a944ee2017-11-07 10:42:54 +01002467 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002468 return t;
2469}
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002470
Christopher Faulet67957bd2017-09-27 11:00:59 +02002471/* proto_udp callback functions for a DNS resolution */
2472struct dgram_data_cb resolve_dgram_cb = {
2473 .recv = dns_resolve_recv,
2474 .send = dns_resolve_send,
2475};
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002476
Christopher Faulet67957bd2017-09-27 11:00:59 +02002477/* Release memory allocated by DNS */
2478static void dns_deinit(void)
2479{
2480 struct dns_resolvers *resolvers, *resolversback;
2481 struct dns_nameserver *ns, *nsback;
2482 struct dns_resolution *res, *resback;
2483 struct dns_requester *req, *reqback;
2484 struct dns_srvrq *srvrq, *srvrqback;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002485
Christopher Faulet67957bd2017-09-27 11:00:59 +02002486 list_for_each_entry_safe(resolvers, resolversback, &dns_resolvers, list) {
2487 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2488 free(ns->id);
2489 free((char *)ns->conf.file);
2490 if (ns->dgram && ns->dgram->t.sock.fd != -1)
2491 fd_delete(ns->dgram->t.sock.fd);
2492 free(ns->dgram);
2493 LIST_DEL(&ns->list);
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002494 EXTRA_COUNTERS_FREE(ns->extra_counters);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002495 free(ns);
2496 }
2497
2498 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2499 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2500 LIST_DEL(&req->list);
Baptiste Assmanndfd35fd2019-01-21 08:18:09 +01002501 pool_free(dns_requester_pool, req);
Olivier Houchard8da5f982017-08-04 18:35:36 +02002502 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002503 dns_free_resolution(res);
2504 }
Olivier Houchard8da5f982017-08-04 18:35:36 +02002505
Christopher Faulet67957bd2017-09-27 11:00:59 +02002506 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2507 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2508 LIST_DEL(&req->list);
Baptiste Assmanndfd35fd2019-01-21 08:18:09 +01002509 pool_free(dns_requester_pool, req);
Olivier Houchard8da5f982017-08-04 18:35:36 +02002510 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002511 dns_free_resolution(res);
2512 }
Olivier Houchard8da5f982017-08-04 18:35:36 +02002513
Christopher Faulet67957bd2017-09-27 11:00:59 +02002514 free(resolvers->id);
2515 free((char *)resolvers->conf.file);
Olivier Houchard3f795f72019-04-17 22:51:06 +02002516 task_destroy(resolvers->t);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002517 LIST_DEL(&resolvers->list);
2518 free(resolvers);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002519 }
2520
Christopher Faulet67957bd2017-09-27 11:00:59 +02002521 list_for_each_entry_safe(srvrq, srvrqback, &dns_srvrq_list, list) {
2522 free(srvrq->name);
2523 free(srvrq->hostname_dn);
2524 LIST_DEL(&srvrq->list);
2525 free(srvrq);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002526 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002527}
2528
Christopher Faulet67957bd2017-09-27 11:00:59 +02002529/* Finalizes the DNS configuration by allocating required resources and checking
2530 * live parameters.
2531 * Returns 0 on success, ERR_* flags otherwise.
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002532 */
Christopher Faulet67957bd2017-09-27 11:00:59 +02002533static int dns_finalize_config(void)
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002534{
Christopher Faulet67957bd2017-09-27 11:00:59 +02002535 struct dns_resolvers *resolvers;
2536 struct proxy *px;
2537 int err_code = 0;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002538
Christopher Faulet67957bd2017-09-27 11:00:59 +02002539 /* allocate pool of resolution per resolvers */
2540 list_for_each_entry(resolvers, &dns_resolvers, list) {
2541 struct dns_nameserver *ns;
2542 struct task *t;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002543
Christopher Faulet67957bd2017-09-27 11:00:59 +02002544 /* Check if we can create the socket with nameservers info */
2545 list_for_each_entry(ns, &resolvers->nameservers, list) {
2546 struct dgram_conn *dgram = NULL;
2547 int fd;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002548
Christopher Faulet67957bd2017-09-27 11:00:59 +02002549 /* Check nameserver info */
2550 if ((fd = socket(ns->addr.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002551 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2552 resolvers->id, ns->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002553 err_code |= (ERR_ALERT|ERR_ABORT);
Olivier Houchard8da5f982017-08-04 18:35:36 +02002554 continue;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002555 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002556 if (connect(fd, (struct sockaddr*)&ns->addr, get_addr_len(&ns->addr)) == -1) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002557 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2558 resolvers->id, ns->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002559 close(fd);
2560 err_code |= (ERR_ALERT|ERR_ABORT);
Olivier Houchard8da5f982017-08-04 18:35:36 +02002561 continue;
Olivier Houchard8da5f982017-08-04 18:35:36 +02002562 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002563 close(fd);
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002564
Christopher Faulet67957bd2017-09-27 11:00:59 +02002565 /* Create dgram structure that will hold the UPD socket
2566 * and attach it on the current nameserver */
2567 if ((dgram = calloc(1, sizeof(*dgram))) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002568 ha_alert("config: resolvers '%s' : out of memory.\n",
2569 resolvers->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002570 err_code |= (ERR_ALERT|ERR_ABORT);
2571 goto err;
2572 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002573
Christopher Faulet67957bd2017-09-27 11:00:59 +02002574 /* Leave dgram partially initialized, no FD attached for
2575 * now. */
2576 dgram->owner = ns;
2577 dgram->data = &resolve_dgram_cb;
2578 dgram->t.sock.fd = -1;
2579 ns->dgram = dgram;
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002580
2581 /* Store the ns counters pointer */
2582 if (ns->extra_counters) {
2583 ns->counters = EXTRA_COUNTERS_GET(ns->extra_counters, &dns_stats_module);
2584 ns->counters->id = ns->id;
2585 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002586 }
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002587
Christopher Faulet67957bd2017-09-27 11:00:59 +02002588 /* Create the task associated to the resolvers section */
Emeric Brunc60def82017-09-27 14:59:38 +02002589 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002590 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002591 err_code |= (ERR_ALERT|ERR_ABORT);
2592 goto err;
2593 }
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002594
Christopher Faulet67957bd2017-09-27 11:00:59 +02002595 /* Update task's parameters */
2596 t->process = dns_process_resolvers;
2597 t->context = resolvers;
2598 resolvers->t = t;
2599 task_wakeup(t, TASK_WOKEN_INIT);
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002600 }
2601
Olivier Houchardfbc74e82017-11-24 16:54:05 +01002602 for (px = proxies_list; px; px = px->next) {
Christopher Faulet67957bd2017-09-27 11:00:59 +02002603 struct server *srv;
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002604
Christopher Faulet67957bd2017-09-27 11:00:59 +02002605 for (srv = px->srv; srv; srv = srv->next) {
2606 struct dns_resolvers *resolvers;
Baptiste Assmann81ed1a02017-05-03 10:11:44 +02002607
Christopher Faulet67957bd2017-09-27 11:00:59 +02002608 if (!srv->resolvers_id)
2609 continue;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002610
Christopher Faulet67957bd2017-09-27 11:00:59 +02002611 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002612 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2613 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002614 err_code |= (ERR_ALERT|ERR_ABORT);
2615 continue;
2616 }
2617 srv->resolvers = resolvers;
Christopher Faulet25fbca42021-06-15 16:17:17 +02002618 srv->srvrq_check = NULL;
2619 if (srv->srvrq) {
2620 if (!srv->srvrq->resolvers) {
2621 srv->srvrq->resolvers = srv->resolvers;
2622 if (dns_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2623 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2624 proxy_type_str(px), px->id, srv->id);
2625 err_code |= (ERR_ALERT|ERR_ABORT);
2626 continue;
2627 }
2628 }
2629 srv->srvrq_check = task_new(MAX_THREADS_MASK);
2630 if (!srv->srvrq_check) {
2631 ha_alert("config: %s '%s' : unable to create SRVRQ task for server '%s'.\n",
Christopher Faulet767a84b2017-11-24 16:50:31 +01002632 proxy_type_str(px), px->id, srv->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002633 err_code |= (ERR_ALERT|ERR_ABORT);
Christopher Faulet25fbca42021-06-15 16:17:17 +02002634 goto err;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002635 }
Christopher Faulet25fbca42021-06-15 16:17:17 +02002636 srv->srvrq_check->process = dns_srvrq_expire_task;
2637 srv->srvrq_check->context = srv;
2638 srv->srvrq_check->expire = TICK_ETERNITY;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002639 }
Christopher Faulet25fbca42021-06-15 16:17:17 +02002640 else if (dns_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
Christopher Faulet767a84b2017-11-24 16:50:31 +01002641 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2642 proxy_type_str(px), px->id, srv->id);
Christopher Faulet67957bd2017-09-27 11:00:59 +02002643 err_code |= (ERR_ALERT|ERR_ABORT);
2644 continue;
2645 }
2646 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002647 }
2648
Christopher Faulet67957bd2017-09-27 11:00:59 +02002649 if (err_code & (ERR_ALERT|ERR_ABORT))
2650 goto err;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002651
Christopher Faulet67957bd2017-09-27 11:00:59 +02002652 return err_code;
2653 err:
2654 dns_deinit();
2655 return err_code;
2656
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002657}
2658
2659static int stats_dump_dns_to_buffer(struct stream_interface *si,
2660 struct dns_nameserver *ns,
2661 struct field *stats, size_t stats_count,
2662 struct list *stat_modules)
2663{
2664 struct appctx *appctx = __objt_appctx(si->end);
2665 struct channel *rep = si_ic(si);
2666 struct stats_module *mod;
2667 size_t idx = 0;
2668
2669 memset(stats, 0, sizeof(struct field) * stats_count);
2670
2671 list_for_each_entry(mod, stat_modules, list) {
2672 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2673
2674 mod->fill_stats(counters, stats + idx);
2675 idx += mod->stats_count;
2676 }
2677
2678 if (!stats_dump_one_line(stats, idx, appctx))
2679 return 0;
2680
2681 if (!stats_putchk(rep, NULL, &trash))
2682 goto full;
2683
2684 return 1;
2685
2686 full:
2687 si_rx_room_rdy(si);
2688 return 0;
2689}
2690
2691/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2692 * as a pointer to the current nameserver.
2693 */
2694int stats_dump_dns(struct stream_interface *si,
2695 struct field *stats, size_t stats_count,
2696 struct list *stat_modules)
2697{
2698 struct appctx *appctx = __objt_appctx(si->end);
2699 struct channel *rep = si_ic(si);
2700 struct dns_resolvers *resolver = appctx->ctx.stats.obj1;
2701 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2702
2703 if (!resolver)
2704 resolver = LIST_NEXT(&dns_resolvers, struct dns_resolvers *, list);
2705
2706 /* dump resolvers */
2707 list_for_each_entry_from(resolver, &dns_resolvers, list) {
2708 appctx->ctx.stats.obj1 = resolver;
2709
2710 ns = appctx->ctx.stats.obj2 ?
2711 appctx->ctx.stats.obj2 :
2712 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2713
2714 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2715 appctx->ctx.stats.obj2 = ns;
2716
2717 if (buffer_almost_full(&rep->buf))
2718 goto full;
2719
2720 if (!stats_dump_dns_to_buffer(si, ns,
2721 stats, stats_count,
2722 stat_modules)) {
2723 return 0;
2724 }
2725 }
2726
2727 appctx->ctx.stats.obj2 = NULL;
2728 }
2729
2730 return 1;
2731
2732 full:
2733 si_rx_room_blk(si);
2734 return 0;
2735}
2736
2737void dns_stats_clear_counters(int clrall, struct list *stat_modules)
2738{
2739 struct dns_resolvers *resolvers;
2740 struct dns_nameserver *ns;
2741 struct stats_module *mod;
2742 void *counters;
2743
2744 list_for_each_entry(mod, stat_modules, list) {
2745 if (!mod->clearable && !clrall)
2746 continue;
2747
2748 list_for_each_entry(resolvers, &dns_resolvers, list) {
2749 list_for_each_entry(ns, &resolvers->nameservers, list) {
2750 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2751 memcpy(counters, mod->counters, mod->counters_size);
2752 }
2753 }
2754 }
2755
2756}
2757
2758int dns_allocate_counters(struct list *stat_modules)
2759{
2760 struct stats_module *mod;
2761 struct dns_resolvers *resolvers;
2762 struct dns_nameserver *ns;
2763
2764 list_for_each_entry(resolvers, &dns_resolvers, list) {
2765 list_for_each_entry(ns, &resolvers->nameservers, list) {
2766 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2767 alloc_failed);
2768
2769 list_for_each_entry(mod, stat_modules, list) {
2770 EXTRA_COUNTERS_ADD(mod,
2771 ns->extra_counters,
2772 mod->counters,
2773 mod->counters_size);
2774 }
2775
2776 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2777
2778 list_for_each_entry(mod, stat_modules, list) {
2779 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2780 mod->counters, mod->counters_size);
2781
2782 /* Store the ns counters pointer */
2783 if (!strcmp(mod->name, "dns")) {
2784 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2785 ns->counters->id = ns->id;
2786 }
2787 }
2788 }
2789 }
2790
2791 return 1;
2792
2793alloc_failed:
2794 return 0;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002795}
2796
Christopher Faulet67957bd2017-09-27 11:00:59 +02002797/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
Aurélien Nephtaliabbf6072018-04-18 13:26:46 +02002798static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002799{
Christopher Faulet67957bd2017-09-27 11:00:59 +02002800 struct dns_resolvers *presolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002801
Christopher Faulet67957bd2017-09-27 11:00:59 +02002802 if (*args[2]) {
2803 list_for_each_entry(presolvers, &dns_resolvers, list) {
2804 if (strcmp(presolvers->id, args[2]) == 0) {
2805 appctx->ctx.cli.p0 = presolvers;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002806 break;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002807 }
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002808 }
Willy Tarreau9d008692019-08-09 11:21:01 +02002809 if (appctx->ctx.cli.p0 == NULL)
2810 return cli_err(appctx, "Can't find that resolvers section\n");
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002811 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002812 return 0;
Baptiste Assmann201c07f2017-05-22 15:17:15 +02002813}
2814
Christopher Faulet67957bd2017-09-27 11:00:59 +02002815/* Dumps counters from all resolvers section and associated name servers. It
2816 * returns 0 if the output buffer is full and it needs to be called again,
2817 * otherwise non-zero. It may limit itself to the resolver pointed to by
Willy Tarreau777b5602016-12-16 18:06:26 +01002818 * <cli.p0> if it's not null.
William Lallemand69e96442016-11-19 00:58:54 +01002819 */
2820static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2821{
2822 struct stream_interface *si = appctx->owner;
Christopher Faulet67957bd2017-09-27 11:00:59 +02002823 struct dns_resolvers *resolvers;
2824 struct dns_nameserver *ns;
William Lallemand69e96442016-11-19 00:58:54 +01002825
2826 chunk_reset(&trash);
2827
2828 switch (appctx->st2) {
2829 case STAT_ST_INIT:
2830 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2831 /* fall through */
2832
2833 case STAT_ST_LIST:
2834 if (LIST_ISEMPTY(&dns_resolvers)) {
2835 chunk_appendf(&trash, "No resolvers found\n");
2836 }
2837 else {
Christopher Faulet67957bd2017-09-27 11:00:59 +02002838 list_for_each_entry(resolvers, &dns_resolvers, list) {
2839 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
William Lallemand69e96442016-11-19 00:58:54 +01002840 continue;
2841
Christopher Faulet67957bd2017-09-27 11:00:59 +02002842 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2843 list_for_each_entry(ns, &resolvers->nameservers, list) {
2844 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
Amaury Denoyellefbd0bc92020-10-05 11:49:46 +02002845 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2846 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2847 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2848 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2849 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2850 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2851 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2852 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2853 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2854 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2855 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2856 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2857 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2858 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2859 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
William Lallemand69e96442016-11-19 00:58:54 +01002860 }
Christopher Faulet67957bd2017-09-27 11:00:59 +02002861 chunk_appendf(&trash, "\n");
William Lallemand69e96442016-11-19 00:58:54 +01002862 }
2863 }
2864
2865 /* display response */
Willy Tarreau06d80a92017-10-19 14:32:15 +02002866 if (ci_putchk(si_ic(si), &trash) == -1) {
William Lallemand69e96442016-11-19 00:58:54 +01002867 /* let's try again later from this session. We add ourselves into
2868 * this session's users so that it can remove us upon termination.
2869 */
Willy Tarreaudb398432018-11-15 11:08:52 +01002870 si_rx_room_blk(si);
William Lallemand69e96442016-11-19 00:58:54 +01002871 return 0;
2872 }
William Lallemand69e96442016-11-19 00:58:54 +01002873 /* fall through */
2874
2875 default:
2876 appctx->st2 = STAT_ST_FIN;
2877 return 1;
2878 }
2879}
2880
2881/* register cli keywords */
Christopher Fauletff88efb2017-10-03 16:00:57 +02002882static struct cli_kw_list cli_kws = {{ }, {
2883 { { "show", "resolvers", NULL }, "show resolvers [id]: dumps counters from all resolvers section and\n"
2884 " associated name servers",
2885 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2886 {{},}
2887 }
2888};
William Lallemand69e96442016-11-19 00:58:54 +01002889
Willy Tarreau0108d902018-11-25 19:14:37 +01002890INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemand69e96442016-11-19 00:58:54 +01002891
Baptiste Assmann333939c2019-01-21 08:34:50 +01002892/*
2893 * Prepare <rule> for hostname resolution.
2894 * Returns -1 in case of any allocation failure, 0 if not.
2895 * On error, a global failure counter is also incremented.
2896 */
2897static int action_prepare_for_resolution(struct stream *stream, const char *hostname)
2898{
2899 char *hostname_dn;
2900 int hostname_len, hostname_dn_len;
2901 struct buffer *tmp = get_trash_chunk();
2902
2903 if (!hostname)
2904 return 0;
2905
2906 hostname_len = strlen(hostname);
2907 hostname_dn = tmp->area;
2908 hostname_dn_len = dns_str_to_dn_label(hostname, hostname_len + 1,
2909 hostname_dn, tmp->size);
2910 if (hostname_dn_len == -1)
2911 goto err;
2912
2913
2914 stream->dns_ctx.hostname_dn = strdup(hostname_dn);
2915 stream->dns_ctx.hostname_dn_len = hostname_dn_len;
2916 if (!stream->dns_ctx.hostname_dn)
2917 goto err;
2918
2919 return 0;
2920
2921 err:
2922 free(stream->dns_ctx.hostname_dn); stream->dns_ctx.hostname_dn = NULL;
2923 dns_failed_resolutions += 1;
2924 return -1;
2925}
2926
2927
2928/*
2929 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2930 */
2931enum act_return dns_action_do_resolve(struct act_rule *rule, struct proxy *px,
2932 struct session *sess, struct stream *s, int flags)
2933{
Baptiste Assmann333939c2019-01-21 08:34:50 +01002934 struct dns_resolution *resolution;
Willy Tarreau45726fd2019-07-17 10:38:45 +02002935 struct sample *smp;
2936 char *fqdn;
Baptiste Assmann7264dfe2019-10-30 16:06:53 +01002937 struct dns_requester *req;
2938 struct dns_resolvers *resolvers;
2939 struct dns_resolution *res;
Christopher Faulet5098a082020-07-22 11:46:32 +02002940 int exp, locked = 0;
2941 enum act_return ret = ACT_RET_CONT;
2942
2943 resolvers = rule->arg.dns.resolvers;
Baptiste Assmann333939c2019-01-21 08:34:50 +01002944
2945 /* we have a response to our DNS resolution */
Baptiste Assmann7264dfe2019-10-30 16:06:53 +01002946 use_cache:
Baptiste Assmann333939c2019-01-21 08:34:50 +01002947 if (s->dns_ctx.dns_requester && s->dns_ctx.dns_requester->resolution != NULL) {
2948 resolution = s->dns_ctx.dns_requester->resolution;
Christopher Faulet5098a082020-07-22 11:46:32 +02002949 if (!locked) {
2950 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2951 locked = 1;
2952 }
2953
Christopher Faulet385101e2020-07-28 10:21:54 +02002954 if (resolution->step == RSLV_STEP_RUNNING)
2955 goto yield;
Baptiste Assmann333939c2019-01-21 08:34:50 +01002956 if (resolution->step == RSLV_STEP_NONE) {
2957 /* We update the variable only if we have a valid response. */
2958 if (resolution->status == RSLV_STATUS_VALID) {
2959 struct sample smp;
2960 short ip_sin_family = 0;
2961 void *ip = NULL;
2962
Christopher Fauleta4168432020-01-24 18:08:42 +01002963 dns_get_ip_from_response(&resolution->response, rule->arg.dns.dns_opts, NULL,
Baptiste Assmann333939c2019-01-21 08:34:50 +01002964 0, &ip, &ip_sin_family, NULL);
2965
2966 switch (ip_sin_family) {
2967 case AF_INET:
2968 smp.data.type = SMP_T_IPV4;
2969 memcpy(&smp.data.u.ipv4, ip, 4);
2970 break;
2971 case AF_INET6:
2972 smp.data.type = SMP_T_IPV6;
2973 memcpy(&smp.data.u.ipv6, ip, 16);
2974 break;
2975 default:
2976 ip = NULL;
2977 }
2978
2979 if (ip) {
2980 smp.px = px;
2981 smp.sess = sess;
2982 smp.strm = s;
2983
2984 vars_set_by_name(rule->arg.dns.varname, strlen(rule->arg.dns.varname), &smp);
2985 }
2986 }
2987 }
2988
Christopher Faulet385101e2020-07-28 10:21:54 +02002989 goto release_requester;
Baptiste Assmann333939c2019-01-21 08:34:50 +01002990 }
2991
2992 /* need to configure and start a new DNS resolution */
Willy Tarreau45726fd2019-07-17 10:38:45 +02002993 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.dns.expr, SMP_T_STR);
2994 if (smp == NULL)
Christopher Faulet5098a082020-07-22 11:46:32 +02002995 goto end;
Baptiste Assmann333939c2019-01-21 08:34:50 +01002996
Willy Tarreau45726fd2019-07-17 10:38:45 +02002997 fqdn = smp->data.u.str.area;
2998 if (action_prepare_for_resolution(s, fqdn) == -1)
Christopher Faulet5098a082020-07-22 11:46:32 +02002999 goto end; /* on error, ignore the action */
Baptiste Assmann333939c2019-01-21 08:34:50 +01003000
Willy Tarreau45726fd2019-07-17 10:38:45 +02003001 s->dns_ctx.parent = rule;
Christopher Faulet5098a082020-07-22 11:46:32 +02003002
3003 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
3004 locked = 1;
3005
Willy Tarreau45726fd2019-07-17 10:38:45 +02003006 dns_link_resolution(s, OBJ_TYPE_STREAM, 0);
Baptiste Assmann7264dfe2019-10-30 16:06:53 +01003007
3008 /* Check if there is a fresh enough response in the cache of our associated resolution */
3009 req = s->dns_ctx.dns_requester;
Christopher Faulet385101e2020-07-28 10:21:54 +02003010 if (!req || !req->resolution)
3011 goto release_requester; /* on error, ignore the action */
Christopher Faulet5098a082020-07-22 11:46:32 +02003012 res = req->resolution;
Baptiste Assmann7264dfe2019-10-30 16:06:53 +01003013
3014 exp = tick_add(res->last_resolution, resolvers->hold.valid);
3015 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
Christopher Faulet385101e2020-07-28 10:21:54 +02003016 && !tick_is_expired(exp, now_ms)) {
Baptiste Assmann7264dfe2019-10-30 16:06:53 +01003017 goto use_cache;
3018 }
3019
Willy Tarreau45726fd2019-07-17 10:38:45 +02003020 dns_trigger_resolution(s->dns_ctx.dns_requester);
Christopher Faulet385101e2020-07-28 10:21:54 +02003021
3022 yield:
3023 if (flags & ACT_OPT_FINAL)
3024 goto release_requester;
Christopher Faulet5098a082020-07-22 11:46:32 +02003025 ret = ACT_RET_YIELD;
3026
3027 end:
3028 if (locked)
3029 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
3030 return ret;
Christopher Faulet385101e2020-07-28 10:21:54 +02003031
3032 release_requester:
3033 free(s->dns_ctx.hostname_dn);
3034 s->dns_ctx.hostname_dn = NULL;
3035 s->dns_ctx.hostname_dn_len = 0;
3036 if (s->dns_ctx.dns_requester) {
Christopher Faulet119ec522021-03-11 18:09:53 +01003037 dns_unlink_resolution(s->dns_ctx.dns_requester, 0);
Christopher Faulet385101e2020-07-28 10:21:54 +02003038 pool_free(dns_requester_pool, s->dns_ctx.dns_requester);
3039 s->dns_ctx.dns_requester = NULL;
3040 }
3041 goto end;
Baptiste Assmann333939c2019-01-21 08:34:50 +01003042}
3043
Christopher Faulet3b2bb632020-01-24 18:12:58 +01003044static void release_dns_action(struct act_rule *rule)
3045{
3046 release_sample_expr(rule->arg.dns.expr);
3047 free(rule->arg.dns.varname);
3048 free(rule->arg.dns.resolvers_id);
3049 free(rule->arg.dns.dns_opts);
3050}
3051
Baptiste Assmann333939c2019-01-21 08:34:50 +01003052
3053/* parse "do-resolve" action
3054 * This action takes the following arguments:
3055 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
3056 *
3057 * - <varName> is the variable name where the result of the DNS resolution will be stored
3058 * (mandatory)
3059 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
3060 * (mandatory)
3061 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
3062 * (optional), defaults to ipv6
3063 * - <expr> is an HAProxy expression used to fetch the name to be resolved
3064 */
3065enum act_parse_ret dns_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
3066{
3067 int cur_arg;
3068 struct sample_expr *expr;
3069 unsigned int where;
3070 const char *beg, *end;
3071
3072 /* orig_arg points to the first argument, but we need to analyse the command itself first */
3073 cur_arg = *orig_arg - 1;
3074
3075 /* locate varName, which is mandatory */
3076 beg = strchr(args[cur_arg], '(');
3077 if (beg == NULL)
3078 goto do_resolve_parse_error;
3079 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
3080 end = strchr(beg, ',');
3081 if (end == NULL)
3082 goto do_resolve_parse_error;
3083 rule->arg.dns.varname = my_strndup(beg, end - beg);
3084 if (rule->arg.dns.varname == NULL)
3085 goto do_resolve_parse_error;
3086
3087
3088 /* locate resolversSectionName, which is mandatory.
3089 * Since next parameters are optional, the delimiter may be comma ','
3090 * or closing parenthesis ')'
3091 */
3092 beg = end + 1;
3093 end = strchr(beg, ',');
3094 if (end == NULL)
3095 end = strchr(beg, ')');
3096 if (end == NULL)
3097 goto do_resolve_parse_error;
3098 rule->arg.dns.resolvers_id = my_strndup(beg, end - beg);
3099 if (rule->arg.dns.resolvers_id == NULL)
3100 goto do_resolve_parse_error;
3101
3102
Christopher Fauleta4168432020-01-24 18:08:42 +01003103 rule->arg.dns.dns_opts = calloc(1, sizeof(*rule->arg.dns.dns_opts));
3104 if (rule->arg.dns.dns_opts == NULL)
3105 goto do_resolve_parse_error;
3106
Baptiste Assmann333939c2019-01-21 08:34:50 +01003107 /* Default priority is ipv6 */
Christopher Fauleta4168432020-01-24 18:08:42 +01003108 rule->arg.dns.dns_opts->family_prio = AF_INET6;
Baptiste Assmann333939c2019-01-21 08:34:50 +01003109
3110 /* optional arguments accepted for now:
3111 * ipv4 or ipv6
3112 */
3113 while (*end != ')') {
3114 beg = end + 1;
3115 end = strchr(beg, ',');
3116 if (end == NULL)
3117 end = strchr(beg, ')');
3118 if (end == NULL)
3119 goto do_resolve_parse_error;
3120
3121 if (strncmp(beg, "ipv4", end - beg) == 0) {
Christopher Fauleta4168432020-01-24 18:08:42 +01003122 rule->arg.dns.dns_opts->family_prio = AF_INET;
Baptiste Assmann333939c2019-01-21 08:34:50 +01003123 }
3124 else if (strncmp(beg, "ipv6", end - beg) == 0) {
Christopher Fauleta4168432020-01-24 18:08:42 +01003125 rule->arg.dns.dns_opts->family_prio = AF_INET6;
Baptiste Assmann333939c2019-01-21 08:34:50 +01003126 }
3127 else {
3128 goto do_resolve_parse_error;
3129 }
3130 }
3131
3132 cur_arg = cur_arg + 1;
3133
Willy Tarreaue3b57bf2020-02-14 16:50:14 +01003134 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
Baptiste Assmann333939c2019-01-21 08:34:50 +01003135 if (!expr)
3136 goto do_resolve_parse_error;
3137
3138
3139 where = 0;
3140 if (px->cap & PR_CAP_FE)
3141 where |= SMP_VAL_FE_HRQ_HDR;
3142 if (px->cap & PR_CAP_BE)
3143 where |= SMP_VAL_BE_HRQ_HDR;
3144
3145 if (!(expr->fetch->val & where)) {
3146 memprintf(err,
3147 "fetch method '%s' extracts information from '%s', none of which is available here",
3148 args[cur_arg-1], sample_src_names(expr->fetch->use));
3149 free(expr);
3150 return ACT_RET_PRS_ERR;
3151 }
3152 rule->arg.dns.expr = expr;
3153 rule->action = ACT_CUSTOM;
3154 rule->action_ptr = dns_action_do_resolve;
3155 *orig_arg = cur_arg;
3156
3157 rule->check_ptr = check_action_do_resolve;
Christopher Faulet3b2bb632020-01-24 18:12:58 +01003158 rule->release_ptr = release_dns_action;
Baptiste Assmann333939c2019-01-21 08:34:50 +01003159
3160 return ACT_RET_PRS_OK;
3161
3162 do_resolve_parse_error:
3163 free(rule->arg.dns.varname); rule->arg.dns.varname = NULL;
3164 free(rule->arg.dns.resolvers_id); rule->arg.dns.resolvers_id = NULL;
3165 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
3166 args[cur_arg]);
3167 return ACT_RET_PRS_ERR;
3168}
3169
3170static struct action_kw_list http_req_kws = { { }, {
3171 { "do-resolve", dns_parse_do_resolve, 1 },
3172 { /* END */ }
3173}};
3174
3175INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
3176
3177static struct action_kw_list tcp_req_cont_actions = {ILH, {
3178 { "do-resolve", dns_parse_do_resolve, 1 },
3179 { /* END */ }
3180}};
3181
3182INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
3183
3184/* Check an "http-request do-resolve" action.
3185 *
3186 * The function returns 1 in success case, otherwise, it returns 0 and err is
3187 * filled.
3188 */
3189int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
3190{
3191 struct dns_resolvers *resolvers = NULL;
3192
3193 if (rule->arg.dns.resolvers_id == NULL) {
3194 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
3195 return 0;
3196 }
3197
3198 resolvers = find_resolvers_by_id(rule->arg.dns.resolvers_id);
3199 if (resolvers == NULL) {
3200 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.dns.resolvers_id);
3201 return 0;
3202 }
3203 rule->arg.dns.resolvers = resolvers;
3204
3205 return 1;
3206}
3207
Willy Tarreau172f5ce2018-11-26 11:21:50 +01003208REGISTER_POST_DEINIT(dns_deinit);
Willy Tarreaue6552512018-11-26 11:33:13 +01003209REGISTER_CONFIG_POSTPARSER("dns runtime resolver", dns_finalize_config);