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