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