blob: 66712dd98a6411a22d52e0dc7d4f62613dfd650a [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;
576 struct resolv_requester *req, *reqback;
577 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 */
585 if (ar_item && (ar_item->last_seen + resolvers->hold.obsolete / 1000) < now.tv_sec) {
586 pool_free(resolv_answer_item_pool, ar_item);
587 item->ar_item = NULL;
588 }
589
590 /* Remove obsolete items */
591 if ((item->last_seen + resolvers->hold.obsolete / 1000) < now.tv_sec) {
592 if (item->type != DNS_RTYPE_SRV)
593 goto rm_obselete_item;
594
595 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
596 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
597 continue;
598
599 /* Remove any associated server */
600 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
601 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
602 if (srv->srvrq == srvrq && srv->svc_port == item->port &&
603 item->data_len == srv->hostname_dn_len &&
604 !resolv_hostname_cmp(srv->hostname_dn, item->target, item->data_len)) {
Christopher Fauletbca680b2021-03-10 21:33:21 +0100605 resolv_unlink_resolution(srv->resolv_requester);
Emeric Brunc9437992021-02-12 19:42:55 +0100606 snr_update_srv_status(srv, 1);
Willy Tarreau61cfdf42021-02-20 10:46:51 +0100607 ha_free(&srv->hostname);
608 ha_free(&srv->hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +0100609 srv->hostname_dn_len = 0;
Christopher Faulet52d4d302021-02-23 12:24:09 +0100610 memset(&srv->addr, 0, sizeof(srv->addr));
611 srv->svc_port = 0;
Emeric Brunc9437992021-02-12 19:42:55 +0100612 }
613 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
614 }
615 }
616
617 rm_obselete_item:
618 LIST_DEL(&item->list);
619 if (item->ar_item) {
620 pool_free(resolv_answer_item_pool, item->ar_item);
621 item->ar_item = NULL;
622 }
623 pool_free(resolv_answer_item_pool, item);
624 continue;
625 }
626
627 if (item->type != DNS_RTYPE_SRV)
628 continue;
629
630 /* Now process SRV records */
631 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
632 if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
633 continue;
634
635 /* Check if a server already uses that hostname */
636 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
637 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
638 if (srv->srvrq == srvrq && srv->svc_port == item->port &&
639 item->data_len == srv->hostname_dn_len &&
640 !resolv_hostname_cmp(srv->hostname_dn, item->target, item->data_len)) {
641 break;
642 }
643 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
644 }
645
646 /* If not, try to find a server with undefined hostname */
647 if (!srv) {
648 for (srv = srvrq->proxy->srv; srv != NULL; srv = srv->next) {
649 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
650 if (srv->srvrq == srvrq && !srv->hostname_dn)
651 break;
652 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
653 }
654 }
655
656 /* And update this server, if found (srv is locked here) */
657 if (srv) {
658 /* Check if an Additional Record is associated to this SRV record.
659 * Perform some sanity checks too to ensure the record can be used.
660 * If all fine, we simply pick up the IP address found and associate
661 * it to the server.
662 */
663 if ((item->ar_item != NULL) &&
664 (item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
665 {
666
667 switch (item->ar_item->type) {
668 case DNS_RTYPE_A:
Christopher Faulet69beaa92021-02-16 12:07:47 +0100669 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 +0100670 break;
671 case DNS_RTYPE_AAAA:
Christopher Faulet69beaa92021-02-16 12:07:47 +0100672 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 +0100673 break;
674 }
675
676 srv->flags |= SRV_F_NO_RESOLUTION;
677 }
678
679 if (!srv->hostname_dn) {
680 const char *msg = NULL;
681 char hostname[DNS_MAX_NAME_SIZE];
682
683 if (resolv_dn_label_to_str(item->target, item->data_len+1,
684 hostname, DNS_MAX_NAME_SIZE) == -1) {
685 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
686 continue;
687 }
Christopher Faulet69beaa92021-02-16 12:07:47 +0100688 msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
Emeric Brunc9437992021-02-12 19:42:55 +0100689 if (msg)
690 send_log(srv->proxy, LOG_NOTICE, "%s", msg);
691 }
692
Christopher Fauletab177ac2021-03-10 15:34:52 +0100693 /* Update the server status */
694 snr_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
Emeric Brunc9437992021-02-12 19:42:55 +0100695
696 srv->svc_port = item->port;
697 srv->flags &= ~SRV_F_MAPPORTS;
698
699 if (!srv->resolv_opts.ignore_weight) {
700 char weight[9];
701 int ha_weight;
702
703 /* DNS weight range if from 0 to 65535
704 * HAProxy weight is from 0 to 256
705 * The rule below ensures that weight 0 is well respected
706 * while allowing a "mapping" from DNS weight into HAProxy's one.
707 */
708 ha_weight = (item->weight + 255) / 256;
709
710 snprintf(weight, sizeof(weight), "%d", ha_weight);
711 server_parse_weight_change_request(srv, weight);
712 }
713 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
714 }
715 }
716 }
717}
718
719/* Validates that the buffer DNS response provided in <resp> and finishing
720 * before <bufend> is valid from a DNS protocol point of view.
721 *
722 * The result is stored in <resolution>' response, buf_response,
723 * response_query_records and response_answer_records members.
724 *
725 * This function returns one of the RSLV_RESP_* code to indicate the type of
726 * error found.
727 */
728static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
729 struct resolv_resolution *resolution, int max_answer_records)
730{
731 unsigned char *reader;
732 char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
733 int len, flags, offset;
734 int query_record_id;
735 int nb_saved_records;
736 struct resolv_query_item *query;
737 struct resolv_answer_item *answer_record, *tmp_record;
738 struct resolv_response *r_res;
739 int i, found = 0;
740 int cause = RSLV_RESP_ERROR;
741
742 reader = resp;
743 len = 0;
744 previous_dname = NULL;
745 query = NULL;
746 answer_record = NULL;
747
748 /* Initialization of response buffer and structure */
749 r_res = &resolution->response;
750
751 /* query id */
752 if (reader + 2 >= bufend)
753 goto invalid_resp;
754
755 r_res->header.id = reader[0] * 256 + reader[1];
756 reader += 2;
757
758 /* Flags and rcode are stored over 2 bytes
759 * First byte contains:
760 * - response flag (1 bit)
761 * - opcode (4 bits)
762 * - authoritative (1 bit)
763 * - truncated (1 bit)
764 * - recursion desired (1 bit)
765 */
766 if (reader + 2 >= bufend)
767 goto invalid_resp;
768
769 flags = reader[0] * 256 + reader[1];
770
771 if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
772 if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
773 cause = RSLV_RESP_NX_DOMAIN;
774 goto return_error;
775 }
776 else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
777 cause = RSLV_RESP_REFUSED;
778 goto return_error;
779 }
780 else {
781 cause = RSLV_RESP_ERROR;
782 goto return_error;
783 }
784 }
785
786 /* Move forward 2 bytes for flags */
787 reader += 2;
788
789 /* 2 bytes for question count */
790 if (reader + 2 >= bufend)
791 goto invalid_resp;
792 r_res->header.qdcount = reader[0] * 256 + reader[1];
793 /* (for now) we send one query only, so we expect only one in the
794 * response too */
795 if (r_res->header.qdcount != 1) {
796 cause = RSLV_RESP_QUERY_COUNT_ERROR;
797 goto return_error;
798 }
799
800 if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
801 goto invalid_resp;
802 reader += 2;
803
804 /* 2 bytes for answer count */
805 if (reader + 2 >= bufend)
806 goto invalid_resp;
807 r_res->header.ancount = reader[0] * 256 + reader[1];
808 if (r_res->header.ancount == 0) {
809 cause = RSLV_RESP_ANCOUNT_ZERO;
810 goto return_error;
811 }
812
813 /* Check if too many records are announced */
814 if (r_res->header.ancount > max_answer_records)
815 goto invalid_resp;
816 reader += 2;
817
818 /* 2 bytes authority count */
819 if (reader + 2 >= bufend)
820 goto invalid_resp;
821 r_res->header.nscount = reader[0] * 256 + reader[1];
822 reader += 2;
823
824 /* 2 bytes additional count */
825 if (reader + 2 >= bufend)
826 goto invalid_resp;
827 r_res->header.arcount = reader[0] * 256 + reader[1];
828 reader += 2;
829
830 /* Parsing dns queries */
831 LIST_INIT(&r_res->query_list);
832 for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
833 /* Use next pre-allocated resolv_query_item after ensuring there is
834 * still one available.
835 * It's then added to our packet query list. */
836 if (query_record_id > DNS_MAX_QUERY_RECORDS)
837 goto invalid_resp;
838 query = &resolution->response_query_records[query_record_id];
839 LIST_ADDQ(&r_res->query_list, &query->list);
840
841 /* Name is a NULL terminated string in our case, since we have
842 * one query per response and the first one can't be compressed
843 * (using the 0x0c format) */
844 offset = 0;
845 len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
846
847 if (len == 0)
848 goto invalid_resp;
849
850 reader += offset;
851 previous_dname = query->name;
852
853 /* move forward 2 bytes for question type */
854 if (reader + 2 >= bufend)
855 goto invalid_resp;
856 query->type = reader[0] * 256 + reader[1];
857 reader += 2;
858
859 /* move forward 2 bytes for question class */
860 if (reader + 2 >= bufend)
861 goto invalid_resp;
862 query->class = reader[0] * 256 + reader[1];
863 reader += 2;
864 }
865
866 /* TRUNCATED flag must be checked after we could read the query type
867 * because a TRUNCATED SRV query type response can still be exploited */
868 if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
869 cause = RSLV_RESP_TRUNCATED;
870 goto return_error;
871 }
872
873 /* now parsing response records */
874 nb_saved_records = 0;
875 for (i = 0; i < r_res->header.ancount; i++) {
876 if (reader >= bufend)
877 goto invalid_resp;
878
879 answer_record = pool_alloc(resolv_answer_item_pool);
880 if (answer_record == NULL)
881 goto invalid_resp;
882
883 /* initialization */
884 answer_record->ar_item = NULL;
885
886 offset = 0;
887 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
888
889 if (len == 0)
890 goto invalid_resp;
891
892 /* Check if the current record dname is valid. previous_dname
893 * points either to queried dname or last CNAME target */
894 if (query->type != DNS_RTYPE_SRV && resolv_hostname_cmp(previous_dname, tmpname, len) != 0) {
895 if (i == 0) {
896 /* First record, means a mismatch issue between
897 * queried dname and dname found in the first
898 * record */
899 goto invalid_resp;
900 }
901 else {
902 /* If not the first record, this means we have a
903 * CNAME resolution error.
904 */
905 cause = RSLV_RESP_CNAME_ERROR;
906 goto return_error;
907 }
908
909 }
910
911 memcpy(answer_record->name, tmpname, len);
912 answer_record->name[len] = 0;
913
914 reader += offset;
915 if (reader >= bufend)
916 goto invalid_resp;
917
918 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
919 if (reader + 2 > bufend)
920 goto invalid_resp;
921
922 answer_record->type = reader[0] * 256 + reader[1];
923 reader += 2;
924
925 /* 2 bytes for class (2) */
926 if (reader + 2 > bufend)
927 goto invalid_resp;
928
929 answer_record->class = reader[0] * 256 + reader[1];
930 reader += 2;
931
932 /* 4 bytes for ttl (4) */
933 if (reader + 4 > bufend)
934 goto invalid_resp;
935
936 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
937 + reader[2] * 256 + reader[3];
938 reader += 4;
939
940 /* Now reading data len */
941 if (reader + 2 > bufend)
942 goto invalid_resp;
943
944 answer_record->data_len = reader[0] * 256 + reader[1];
945
946 /* Move forward 2 bytes for data len */
947 reader += 2;
948
949 if (reader + answer_record->data_len > bufend)
950 goto invalid_resp;
951
952 /* Analyzing record content */
953 switch (answer_record->type) {
954 case DNS_RTYPE_A:
955 /* ipv4 is stored on 4 bytes */
956 if (answer_record->data_len != 4)
957 goto invalid_resp;
958
959 answer_record->address.sa_family = AF_INET;
960 memcpy(&(((struct sockaddr_in *)&answer_record->address)->sin_addr),
961 reader, answer_record->data_len);
962 break;
963
964 case DNS_RTYPE_CNAME:
965 /* Check if this is the last record and update the caller about the status:
966 * no IP could be found and last record was a CNAME. Could be triggered
967 * by a wrong query type
968 *
969 * + 1 because answer_record_id starts at 0
970 * while number of answers is an integer and
971 * starts at 1.
972 */
973 if (i + 1 == r_res->header.ancount) {
974 cause = RSLV_RESP_CNAME_ERROR;
975 goto return_error;
976 }
977
978 offset = 0;
979 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
980 if (len == 0)
981 goto invalid_resp;
982
983 memcpy(answer_record->target, tmpname, len);
984 answer_record->target[len] = 0;
985 previous_dname = answer_record->target;
986 break;
987
988
989 case DNS_RTYPE_SRV:
990 /* Answer must contain :
991 * - 2 bytes for the priority
992 * - 2 bytes for the weight
993 * - 2 bytes for the port
994 * - the target hostname
995 */
996 if (answer_record->data_len <= 6)
997 goto invalid_resp;
998
999 answer_record->priority = read_n16(reader);
1000 reader += sizeof(uint16_t);
1001 answer_record->weight = read_n16(reader);
1002 reader += sizeof(uint16_t);
1003 answer_record->port = read_n16(reader);
1004 reader += sizeof(uint16_t);
1005 offset = 0;
1006 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1007 if (len == 0)
1008 goto invalid_resp;
1009
1010 answer_record->data_len = len;
1011 memcpy(answer_record->target, tmpname, len);
1012 answer_record->target[len] = 0;
1013 if (answer_record->ar_item != NULL) {
1014 pool_free(resolv_answer_item_pool, answer_record->ar_item);
1015 answer_record->ar_item = NULL;
1016 }
1017 break;
1018
1019 case DNS_RTYPE_AAAA:
1020 /* ipv6 is stored on 16 bytes */
1021 if (answer_record->data_len != 16)
1022 goto invalid_resp;
1023
1024 answer_record->address.sa_family = AF_INET6;
1025 memcpy(&(((struct sockaddr_in6 *)&answer_record->address)->sin6_addr),
1026 reader, answer_record->data_len);
1027 break;
1028
1029 } /* switch (record type) */
1030
1031 /* Increment the counter for number of records saved into our
1032 * local response */
1033 nb_saved_records++;
1034
1035 /* Move forward answer_record->data_len for analyzing next
1036 * record in the response */
1037 reader += ((answer_record->type == DNS_RTYPE_SRV)
1038 ? offset
1039 : answer_record->data_len);
1040
1041 /* Lookup to see if we already had this entry */
1042 found = 0;
1043 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1044 if (tmp_record->type != answer_record->type)
1045 continue;
1046
1047 switch(tmp_record->type) {
1048 case DNS_RTYPE_A:
1049 if (!memcmp(&((struct sockaddr_in *)&answer_record->address)->sin_addr,
1050 &((struct sockaddr_in *)&tmp_record->address)->sin_addr,
1051 sizeof(in_addr_t)))
1052 found = 1;
1053 break;
1054
1055 case DNS_RTYPE_AAAA:
1056 if (!memcmp(&((struct sockaddr_in6 *)&answer_record->address)->sin6_addr,
1057 &((struct sockaddr_in6 *)&tmp_record->address)->sin6_addr,
1058 sizeof(struct in6_addr)))
1059 found = 1;
1060 break;
1061
1062 case DNS_RTYPE_SRV:
1063 if (answer_record->data_len == tmp_record->data_len &&
1064 !resolv_hostname_cmp(answer_record->target, tmp_record->target, answer_record->data_len) &&
1065 answer_record->port == tmp_record->port) {
1066 tmp_record->weight = answer_record->weight;
1067 found = 1;
1068 }
1069 break;
1070
1071 default:
1072 break;
1073 }
1074
1075 if (found == 1)
1076 break;
1077 }
1078
1079 if (found == 1) {
Christopher Faulet5037c062021-03-10 15:54:14 +01001080 tmp_record->last_seen = now.tv_sec;
Emeric Brunc9437992021-02-12 19:42:55 +01001081 pool_free(resolv_answer_item_pool, answer_record);
1082 answer_record = NULL;
1083 }
1084 else {
1085 answer_record->last_seen = now.tv_sec;
1086 answer_record->ar_item = NULL;
1087 LIST_ADDQ(&r_res->answer_list, &answer_record->list);
1088 answer_record = NULL;
1089 }
1090 } /* for i 0 to ancount */
1091
1092 /* Save the number of records we really own */
1093 r_res->header.ancount = nb_saved_records;
1094
1095 /* now parsing additional records for SRV queries only */
1096 if (query->type != DNS_RTYPE_SRV)
1097 goto skip_parsing_additional_records;
1098
1099 /* if we find Authority records, just skip them */
1100 for (i = 0; i < r_res->header.nscount; i++) {
1101 offset = 0;
1102 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
1103 &offset, 0);
1104 if (len == 0)
1105 continue;
1106
1107 if (reader + offset + 10 >= bufend)
1108 goto invalid_resp;
1109
1110 reader += offset;
1111 /* skip 2 bytes for class */
1112 reader += 2;
1113 /* skip 2 bytes for type */
1114 reader += 2;
1115 /* skip 4 bytes for ttl */
1116 reader += 4;
1117 /* read data len */
1118 len = reader[0] * 256 + reader[1];
1119 reader += 2;
1120
1121 if (reader + len >= bufend)
1122 goto invalid_resp;
1123
1124 reader += len;
1125 }
1126
1127 nb_saved_records = 0;
1128 for (i = 0; i < r_res->header.arcount; i++) {
1129 if (reader >= bufend)
1130 goto invalid_resp;
1131
1132 answer_record = pool_alloc(resolv_answer_item_pool);
1133 if (answer_record == NULL)
1134 goto invalid_resp;
1135
1136 offset = 0;
1137 len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
1138
1139 if (len == 0) {
1140 pool_free(resolv_answer_item_pool, answer_record);
1141 answer_record = NULL;
1142 continue;
1143 }
1144
1145 memcpy(answer_record->name, tmpname, len);
1146 answer_record->name[len] = 0;
1147
1148 reader += offset;
1149 if (reader >= bufend)
1150 goto invalid_resp;
1151
1152 /* 2 bytes for record type (A, AAAA, CNAME, etc...) */
1153 if (reader + 2 > bufend)
1154 goto invalid_resp;
1155
1156 answer_record->type = reader[0] * 256 + reader[1];
1157 reader += 2;
1158
1159 /* 2 bytes for class (2) */
1160 if (reader + 2 > bufend)
1161 goto invalid_resp;
1162
1163 answer_record->class = reader[0] * 256 + reader[1];
1164 reader += 2;
1165
1166 /* 4 bytes for ttl (4) */
1167 if (reader + 4 > bufend)
1168 goto invalid_resp;
1169
1170 answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
1171 + reader[2] * 256 + reader[3];
1172 reader += 4;
1173
1174 /* Now reading data len */
1175 if (reader + 2 > bufend)
1176 goto invalid_resp;
1177
1178 answer_record->data_len = reader[0] * 256 + reader[1];
1179
1180 /* Move forward 2 bytes for data len */
1181 reader += 2;
1182
1183 if (reader + answer_record->data_len > bufend)
1184 goto invalid_resp;
1185
1186 /* Analyzing record content */
1187 switch (answer_record->type) {
1188 case DNS_RTYPE_A:
1189 /* ipv4 is stored on 4 bytes */
1190 if (answer_record->data_len != 4)
1191 goto invalid_resp;
1192
1193 answer_record->address.sa_family = AF_INET;
1194 memcpy(&(((struct sockaddr_in *)&answer_record->address)->sin_addr),
1195 reader, answer_record->data_len);
1196 break;
1197
1198 case DNS_RTYPE_AAAA:
1199 /* ipv6 is stored on 16 bytes */
1200 if (answer_record->data_len != 16)
1201 goto invalid_resp;
1202
1203 answer_record->address.sa_family = AF_INET6;
1204 memcpy(&(((struct sockaddr_in6 *)&answer_record->address)->sin6_addr),
1205 reader, answer_record->data_len);
1206 break;
1207
1208 default:
1209 pool_free(resolv_answer_item_pool, answer_record);
1210 answer_record = NULL;
1211 continue;
1212
1213 } /* switch (record type) */
1214
1215 /* Increment the counter for number of records saved into our
1216 * local response */
1217 nb_saved_records++;
1218
1219 /* Move forward answer_record->data_len for analyzing next
1220 * record in the response */
Christopher Faulet77f86062021-03-10 15:19:57 +01001221 reader += answer_record->data_len;
Emeric Brunc9437992021-02-12 19:42:55 +01001222
1223 /* Lookup to see if we already had this entry */
1224 found = 0;
1225 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001226 struct resolv_answer_item *ar_item;
1227
1228 if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
1229 continue;
1230
1231 ar_item = tmp_record->ar_item;
1232 if (ar_item->type != answer_record->type ||
1233 len != tmp_record->data_len ||
1234 resolv_hostname_cmp(answer_record->name, tmp_record->target, tmp_record->data_len))
Emeric Brunc9437992021-02-12 19:42:55 +01001235 continue;
1236
Christopher Faulet77f86062021-03-10 15:19:57 +01001237 switch(ar_item->type) {
Emeric Brunc9437992021-02-12 19:42:55 +01001238 case DNS_RTYPE_A:
1239 if (!memcmp(&((struct sockaddr_in *)&answer_record->address)->sin_addr,
Christopher Faulet77f86062021-03-10 15:19:57 +01001240 &((struct sockaddr_in *)&ar_item->address)->sin_addr,
Emeric Brunc9437992021-02-12 19:42:55 +01001241 sizeof(in_addr_t)))
1242 found = 1;
1243 break;
1244
1245 case DNS_RTYPE_AAAA:
1246 if (!memcmp(&((struct sockaddr_in6 *)&answer_record->address)->sin6_addr,
Christopher Faulet77f86062021-03-10 15:19:57 +01001247 &((struct sockaddr_in6 *)&ar_item->address)->sin6_addr,
Emeric Brunc9437992021-02-12 19:42:55 +01001248 sizeof(struct in6_addr)))
1249 found = 1;
1250 break;
1251
1252 default:
1253 break;
1254 }
1255
1256 if (found == 1)
1257 break;
1258 }
1259
1260 if (found == 1) {
Christopher Faulet77f86062021-03-10 15:19:57 +01001261 tmp_record->ar_item->last_seen = now.tv_sec;
Emeric Brunc9437992021-02-12 19:42:55 +01001262 pool_free(resolv_answer_item_pool, answer_record);
1263 answer_record = NULL;
1264 }
1265 else {
1266 answer_record->last_seen = now.tv_sec;
1267 answer_record->ar_item = NULL;
1268
1269 // looking for the SRV record in the response list linked to this additional record
1270 list_for_each_entry(tmp_record, &r_res->answer_list, list) {
1271 if (tmp_record->type == DNS_RTYPE_SRV &&
1272 tmp_record->ar_item == NULL &&
1273 !resolv_hostname_cmp(tmp_record->target, answer_record->name, tmp_record->data_len)) {
1274 /* Always use the received additional record to refresh info */
1275 if (tmp_record->ar_item)
1276 pool_free(resolv_answer_item_pool, tmp_record->ar_item);
1277 tmp_record->ar_item = answer_record;
Christopher Faulet9c246a42021-02-23 11:59:19 +01001278 answer_record = NULL;
Emeric Brunc9437992021-02-12 19:42:55 +01001279 break;
1280 }
1281 }
Christopher Faulet9c246a42021-02-23 11:59:19 +01001282 if (answer_record) {
Emeric Brunc9437992021-02-12 19:42:55 +01001283 pool_free(resolv_answer_item_pool, answer_record);
Christopher Faulet9c246a42021-02-23 11:59:19 +01001284 answer_record = NULL;
1285 }
Emeric Brunc9437992021-02-12 19:42:55 +01001286 }
1287 } /* for i 0 to arcount */
1288
1289 skip_parsing_additional_records:
1290
1291 /* Save the number of records we really own */
1292 r_res->header.arcount = nb_saved_records;
1293
1294 resolv_check_response(resolution);
1295 return RSLV_RESP_VALID;
1296
1297 invalid_resp:
1298 cause = RSLV_RESP_INVALID;
1299
1300 return_error:
1301 pool_free(resolv_answer_item_pool, answer_record);
1302 return cause;
1303}
1304
1305/* Searches dn_name resolution in resp.
1306 * If existing IP not found, return the first IP matching family_priority,
1307 * otherwise, first ip found
1308 * The following tasks are the responsibility of the caller:
1309 * - <r_res> contains an error free DNS response
1310 * For both cases above, resolv_validate_dns_response is required
1311 * returns one of the RSLV_UPD_* code
1312 */
1313int resolv_get_ip_from_response(struct resolv_response *r_res,
1314 struct resolv_options *resolv_opts, void *currentip,
1315 short currentip_sin_family,
1316 void **newip, short *newip_sin_family,
1317 void *owner)
1318{
1319 struct resolv_answer_item *record;
1320 int family_priority;
1321 int currentip_found;
1322 unsigned char *newip4, *newip6;
1323 int currentip_sel;
1324 int j;
1325 int score, max_score;
1326 int allowed_duplicated_ip;
1327
1328 family_priority = resolv_opts->family_prio;
1329 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1330 *newip = newip4 = newip6 = NULL;
1331 currentip_found = 0;
1332 *newip_sin_family = AF_UNSPEC;
1333 max_score = -1;
1334
1335 /* Select an IP regarding configuration preference.
1336 * Top priority is the preferred network ip version,
1337 * second priority is the preferred network.
1338 * the last priority is the currently used IP,
1339 *
1340 * For these three priorities, a score is calculated. The
1341 * weight are:
1342 * 8 - preferred ip version.
1343 * 4 - preferred network.
1344 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1345 * 1 - current ip.
1346 * The result with the biggest score is returned.
1347 */
1348
1349 list_for_each_entry(record, &r_res->answer_list, list) {
1350 void *ip;
1351 unsigned char ip_type;
1352
1353 if (record->type == DNS_RTYPE_A) {
1354 ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
1355 ip_type = AF_INET;
1356 }
1357 else if (record->type == DNS_RTYPE_AAAA) {
1358 ip_type = AF_INET6;
1359 ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
1360 }
1361 else
1362 continue;
1363 score = 0;
1364
1365 /* Check for preferred ip protocol. */
1366 if (ip_type == family_priority)
1367 score += 8;
1368
1369 /* Check for preferred network. */
1370 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1371
1372 /* Compare only the same addresses class. */
1373 if (resolv_opts->pref_net[j].family != ip_type)
1374 continue;
1375
1376 if ((ip_type == AF_INET &&
1377 in_net_ipv4(ip,
1378 &resolv_opts->pref_net[j].mask.in4,
1379 &resolv_opts->pref_net[j].addr.in4)) ||
1380 (ip_type == AF_INET6 &&
1381 in_net_ipv6(ip,
1382 &resolv_opts->pref_net[j].mask.in6,
1383 &resolv_opts->pref_net[j].addr.in6))) {
1384 score += 4;
1385 break;
1386 }
1387 }
1388
1389 /* Check if the IP found in the record is already affected to a
1390 * member of a group. If not, the score should be incremented
1391 * by 2. */
1392 if (owner && snr_check_ip_callback(owner, ip, &ip_type)) {
1393 if (!allowed_duplicated_ip) {
1394 continue;
1395 }
1396 } else {
1397 score += 2;
1398 }
1399
1400 /* Check for current ip matching. */
1401 if (ip_type == currentip_sin_family &&
1402 ((currentip_sin_family == AF_INET &&
1403 !memcmp(ip, currentip, 4)) ||
1404 (currentip_sin_family == AF_INET6 &&
1405 !memcmp(ip, currentip, 16)))) {
1406 score++;
1407 currentip_sel = 1;
1408 }
1409 else
1410 currentip_sel = 0;
1411
1412 /* Keep the address if the score is better than the previous
1413 * score. The maximum score is 15, if this value is reached, we
1414 * break the parsing. Implicitly, this score is reached the ip
1415 * selected is the current ip. */
1416 if (score > max_score) {
1417 if (ip_type == AF_INET)
1418 newip4 = ip;
1419 else
1420 newip6 = ip;
1421 currentip_found = currentip_sel;
1422 if (score == 15)
1423 return RSLV_UPD_NO;
1424 max_score = score;
1425 }
1426 } /* list for each record entries */
1427
1428 /* No IP found in the response */
1429 if (!newip4 && !newip6)
1430 return RSLV_UPD_NO_IP_FOUND;
1431
1432 /* Case when the caller looks first for an IPv4 address */
1433 if (family_priority == AF_INET) {
1434 if (newip4) {
1435 *newip = newip4;
1436 *newip_sin_family = AF_INET;
1437 }
1438 else if (newip6) {
1439 *newip = newip6;
1440 *newip_sin_family = AF_INET6;
1441 }
1442 if (!currentip_found)
1443 goto not_found;
1444 }
1445 /* Case when the caller looks first for an IPv6 address */
1446 else if (family_priority == AF_INET6) {
1447 if (newip6) {
1448 *newip = newip6;
1449 *newip_sin_family = AF_INET6;
1450 }
1451 else if (newip4) {
1452 *newip = newip4;
1453 *newip_sin_family = AF_INET;
1454 }
1455 if (!currentip_found)
1456 goto not_found;
1457 }
1458 /* Case when the caller have no preference (we prefer IPv6) */
1459 else if (family_priority == AF_UNSPEC) {
1460 if (newip6) {
1461 *newip = newip6;
1462 *newip_sin_family = AF_INET6;
1463 }
1464 else if (newip4) {
1465 *newip = newip4;
1466 *newip_sin_family = AF_INET;
1467 }
1468 if (!currentip_found)
1469 goto not_found;
1470 }
1471
1472 /* No reason why we should change the server's IP address */
1473 return RSLV_UPD_NO;
1474
1475 not_found:
1476 list_for_each_entry(record, &r_res->answer_list, list) {
1477 /* Move the first record to the end of the list, for internal
1478 * round robin */
1479 LIST_DEL(&record->list);
1480 LIST_ADDQ(&r_res->answer_list, &record->list);
1481 break;
1482 }
1483 return RSLV_UPD_SRVIP_NOT_FOUND;
1484}
1485
1486/* Turns a domain name label into a string.
1487 *
1488 * <dn> must be a null-terminated string. <dn_len> must include the terminating
1489 * null byte. <str> must be allocated and its size must be passed in <str_len>.
1490 *
1491 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1492 * <str> (including the terminating null byte).
1493 */
1494int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1495{
1496 char *ptr;
1497 int i, sz;
1498
1499 if (str_len < dn_len - 1)
1500 return -1;
1501
1502 ptr = str;
1503 for (i = 0; i < dn_len-1; ++i) {
1504 sz = dn[i];
1505 if (i)
1506 *ptr++ = '.';
1507 memcpy(ptr, dn+i+1, sz);
1508 ptr += sz;
1509 i += sz;
1510 }
1511 *ptr++ = '\0';
1512 return (ptr - str);
1513}
1514
1515/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1516 *
1517 * <str> must be a null-terminated string. <str_len> must include the
1518 * terminating null byte. <dn> buffer must be allocated and its size must be
1519 * passed in <dn_len>.
1520 *
1521 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1522 * <dn> (excluding the terminating null byte).
1523 */
1524int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1525{
1526 int i, offset;
1527
1528 if (dn_len < str_len + 1)
1529 return -1;
1530
1531 /* First byte of dn will be used to store the length of the first
1532 * label */
1533 offset = 0;
1534 for (i = 0; i < str_len; ++i) {
1535 if (str[i] == '.') {
1536 /* 2 or more consecutive dots is invalid */
1537 if (i == offset)
1538 return -1;
1539
1540 /* ignore trailing dot */
1541 if (i + 2 == str_len) {
1542 i++;
1543 break;
1544 }
1545
1546 dn[offset] = (i - offset);
1547 offset = i+1;
1548 continue;
1549 }
1550 dn[i+1] = str[i];
1551 }
1552 dn[offset] = (i - offset - 1);
1553 dn[i] = '\0';
1554 return i;
1555}
1556
1557/* Validates host name:
1558 * - total size
1559 * - each label size individually
1560 * returns:
1561 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1562 * 1 when no error. <err> is left unaffected.
1563 */
1564int resolv_hostname_validation(const char *string, char **err)
1565{
1566 int i;
1567
1568 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1569 if (err)
1570 *err = DNS_TOO_LONG_FQDN;
1571 return 0;
1572 }
1573
1574 while (*string) {
1575 i = 0;
1576 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1577 if (!(*string == '-' || *string == '_' ||
1578 (*string >= 'a' && *string <= 'z') ||
1579 (*string >= 'A' && *string <= 'Z') ||
1580 (*string >= '0' && *string <= '9'))) {
1581 if (err)
1582 *err = DNS_INVALID_CHARACTER;
1583 return 0;
1584 }
1585 i++;
1586 string++;
1587 }
1588
1589 if (!(*string))
1590 break;
1591
1592 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1593 if (err)
1594 *err = DNS_LABEL_TOO_LONG;
1595 return 0;
1596 }
1597
1598 string++;
1599 }
1600 return 1;
1601}
1602
1603/* Picks up an available resolution from the different resolution list
1604 * associated to a resolvers section, in this order:
1605 * 1. check in resolutions.curr for the same hostname and query_type
1606 * 2. check in resolutions.wait for the same hostname and query_type
1607 * 3. Get a new resolution from resolution pool
1608 *
1609 * Returns an available resolution, NULL if none found.
1610 */
1611static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1612 char **hostname_dn, int hostname_dn_len,
1613 int query_type)
1614{
1615 struct resolv_resolution *res;
1616
1617 if (!*hostname_dn)
1618 goto from_pool;
1619
1620 /* Search for same hostname and query type in resolutions.curr */
1621 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1622 if (!res->hostname_dn)
1623 continue;
1624 if ((query_type == res->prefered_query_type) &&
1625 hostname_dn_len == res->hostname_dn_len &&
1626 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1627 return res;
1628 }
1629
1630 /* Search for same hostname and query type in resolutions.wait */
1631 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1632 if (!res->hostname_dn)
1633 continue;
1634 if ((query_type == res->prefered_query_type) &&
1635 hostname_dn_len == res->hostname_dn_len &&
1636 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1637 return res;
1638 }
1639
1640 from_pool:
1641 /* No resolution could be found, so let's allocate a new one */
1642 res = pool_alloc(resolv_resolution_pool);
1643 if (res) {
1644 memset(res, 0, sizeof(*res));
1645 res->resolvers = resolvers;
1646 res->uuid = resolution_uuid;
1647 res->status = RSLV_STATUS_NONE;
1648 res->step = RSLV_STEP_NONE;
1649 res->last_valid = now_ms;
1650
1651 LIST_INIT(&res->requesters);
1652 LIST_INIT(&res->response.answer_list);
1653
1654 res->prefered_query_type = query_type;
1655 res->query_type = query_type;
1656 res->hostname_dn = *hostname_dn;
1657 res->hostname_dn_len = hostname_dn_len;
1658
1659 ++resolution_uuid;
1660
1661 /* Move the resolution to the resolvers wait queue */
1662 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
1663 }
1664 return res;
1665}
1666
1667/* Releases a resolution from its requester(s) and move it back to the pool */
1668static void resolv_free_resolution(struct resolv_resolution *resolution)
1669{
1670 struct resolv_requester *req, *reqback;
1671 struct resolv_answer_item *item, *itemback;
1672
1673 /* clean up configuration */
1674 resolv_reset_resolution(resolution);
1675 resolution->hostname_dn = NULL;
1676 resolution->hostname_dn_len = 0;
1677
1678 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
1679 LIST_DEL(&req->list);
1680 req->resolution = NULL;
1681 }
1682
1683 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
1684 LIST_DEL(&item->list);
1685 if (item->ar_item) {
1686 pool_free(resolv_answer_item_pool, item->ar_item);
1687 item->ar_item = NULL;
1688 }
1689 pool_free(resolv_answer_item_pool, item);
1690 }
1691
1692 LIST_DEL(&resolution->list);
1693 pool_free(resolv_resolution_pool, resolution);
1694}
1695
1696/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
1697 * on success, -1 otherwise.
1698 */
1699int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1700{
1701 struct resolv_resolution *res = NULL;
1702 struct resolv_requester *req;
1703 struct resolvers *resolvers;
1704 struct server *srv = NULL;
1705 struct resolv_srvrq *srvrq = NULL;
1706 struct stream *stream = NULL;
1707 char **hostname_dn;
1708 int hostname_dn_len, query_type;
1709
1710 switch (requester_type) {
1711 case OBJ_TYPE_SERVER:
1712 srv = (struct server *)requester;
1713 hostname_dn = &srv->hostname_dn;
1714 hostname_dn_len = srv->hostname_dn_len;
1715 resolvers = srv->resolvers;
1716 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1717 ? DNS_RTYPE_A
1718 : DNS_RTYPE_AAAA);
1719 break;
1720
1721 case OBJ_TYPE_SRVRQ:
1722 srvrq = (struct resolv_srvrq *)requester;
1723 hostname_dn = &srvrq->hostname_dn;
1724 hostname_dn_len = srvrq->hostname_dn_len;
1725 resolvers = srvrq->resolvers;
1726 query_type = DNS_RTYPE_SRV;
1727 break;
1728
1729 case OBJ_TYPE_STREAM:
1730 stream = (struct stream *)requester;
1731 hostname_dn = &stream->resolv_ctx.hostname_dn;
1732 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
1733 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
1734 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
1735 ? DNS_RTYPE_A
1736 : DNS_RTYPE_AAAA);
1737 break;
1738 default:
1739 goto err;
1740 }
1741
1742 /* Get a resolution from the resolvers' wait queue or pool */
1743 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
1744 goto err;
1745
1746 if (srv) {
1747 if (!requester_locked)
1748 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1749 if (srv->resolv_requester == NULL) {
1750 if ((req = pool_alloc(resolv_requester_pool)) == NULL) {
1751 if (!requester_locked)
1752 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1753 goto err;
1754 }
1755 req->owner = &srv->obj_type;
1756 srv->resolv_requester = req;
1757 }
1758 else
1759 req = srv->resolv_requester;
1760 if (!requester_locked)
1761 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1762
1763 req->requester_cb = snr_resolution_cb;
1764 req->requester_error_cb = snr_resolution_error_cb;
1765 }
1766 else if (srvrq) {
1767 if (srvrq->requester == NULL) {
1768 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1769 goto err;
1770 req->owner = &srvrq->obj_type;
1771 srvrq->requester = req;
1772 }
1773 else
1774 req = srvrq->requester;
1775
1776 req->requester_cb = snr_resolution_cb;
Baptiste Assmannb4badf72020-11-19 22:38:33 +01001777 req->requester_error_cb = srvrq_resolution_error_cb;
Emeric Brunc9437992021-02-12 19:42:55 +01001778 }
1779 else if (stream) {
1780 if (stream->resolv_ctx.requester == NULL) {
1781 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1782 goto err;
1783 req->owner = &stream->obj_type;
1784 stream->resolv_ctx.requester = req;
1785 }
1786 else
1787 req = stream->resolv_ctx.requester;
1788
1789 req->requester_cb = act_resolution_cb;
1790 req->requester_error_cb = act_resolution_error_cb;
1791 }
1792 else
1793 goto err;
1794
1795 req->resolution = res;
1796
1797 LIST_ADDQ(&res->requesters, &req->list);
1798 return 0;
1799
1800 err:
1801 if (res && LIST_ISEMPTY(&res->requesters))
1802 resolv_free_resolution(res);
1803 return -1;
1804}
1805
1806/* Removes a requester from a DNS resolution. It takes takes care of all the
1807 * consequences. It also cleans up some parameters from the requester.
1808 */
1809void resolv_unlink_resolution(struct resolv_requester *requester)
1810{
1811 struct resolv_resolution *res;
1812 struct resolv_requester *req;
1813
1814 /* Nothing to do */
1815 if (!requester || !requester->resolution)
1816 return;
1817 res = requester->resolution;
1818
1819 /* Clean up the requester */
1820 LIST_DEL(&requester->list);
1821 requester->resolution = NULL;
1822
1823 /* We need to find another requester linked on this resolution */
1824 if (!LIST_ISEMPTY(&res->requesters))
1825 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
1826 else {
1827 resolv_free_resolution(res);
1828 return;
1829 }
1830
1831 /* Move hostname_dn related pointers to the next requester */
1832 switch (obj_type(req->owner)) {
1833 case OBJ_TYPE_SERVER:
1834 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
1835 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
1836 break;
1837 case OBJ_TYPE_SRVRQ:
1838 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
1839 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
1840 break;
1841 case OBJ_TYPE_STREAM:
1842 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
1843 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
1844 break;
1845 default:
1846 res->hostname_dn = NULL;
1847 res->hostname_dn_len = 0;
1848 break;
1849 }
1850}
1851
1852/* Called when a network IO is generated on a name server socket for an incoming
1853 * packet. It performs the following actions:
1854 * - check if the packet requires processing (not outdated resolution)
1855 * - ensure the DNS packet received is valid and call requester's callback
1856 * - call requester's error callback if invalid response
1857 * - check the dn_name in the packet against the one sent
1858 */
1859static int resolv_process_responses(struct dns_nameserver *ns)
1860{
1861 struct dns_counters *tmpcounters;
1862 struct resolvers *resolvers;
1863 struct resolv_resolution *res;
1864 struct resolv_query_item *query;
1865 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
1866 unsigned char *bufend;
1867 int buflen, dns_resp;
1868 int max_answer_records;
1869 unsigned short query_id;
1870 struct eb32_node *eb;
1871 struct resolv_requester *req;
1872
1873 resolvers = ns->parent;
1874 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
1875
1876 /* process all pending input messages */
1877 while (1) {
1878 /* read message received */
1879 memset(buf, '\0', resolvers->accepted_payload_size + 1);
1880 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
1881 break;
1882 }
1883
1884 /* message too big */
1885 if (buflen > resolvers->accepted_payload_size) {
1886 ns->counters->too_big++;
1887 continue;
1888 }
1889
1890 /* initializing variables */
1891 bufend = buf + buflen; /* pointer to mark the end of the buffer */
1892
1893 /* read the query id from the packet (16 bits) */
1894 if (buf + 2 > bufend) {
1895 ns->counters->invalid++;
1896 continue;
1897 }
1898 query_id = resolv_response_get_query_id(buf);
1899
1900 /* search the query_id in the pending resolution tree */
1901 eb = eb32_lookup(&resolvers->query_ids, query_id);
1902 if (eb == NULL) {
1903 /* unknown query id means an outdated response and can be safely ignored */
1904 ns->counters->outdated++;
1905 continue;
1906 }
1907
1908 /* known query id means a resolution in progress */
1909 res = eb32_entry(eb, struct resolv_resolution, qid);
1910 /* number of responses received */
1911 res->nb_responses++;
1912
1913 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
1914 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
1915
1916 switch (dns_resp) {
1917 case RSLV_RESP_VALID:
1918 break;
1919
1920 case RSLV_RESP_INVALID:
1921 case RSLV_RESP_QUERY_COUNT_ERROR:
1922 case RSLV_RESP_WRONG_NAME:
1923 res->status = RSLV_STATUS_INVALID;
1924 ns->counters->invalid++;
1925 break;
1926
1927 case RSLV_RESP_NX_DOMAIN:
1928 res->status = RSLV_STATUS_NX;
1929 ns->counters->nx++;
1930 break;
1931
1932 case RSLV_RESP_REFUSED:
1933 res->status = RSLV_STATUS_REFUSED;
1934 ns->counters->refused++;
1935 break;
1936
1937 case RSLV_RESP_ANCOUNT_ZERO:
1938 res->status = RSLV_STATUS_OTHER;
1939 ns->counters->any_err++;
1940 break;
1941
1942 case RSLV_RESP_CNAME_ERROR:
1943 res->status = RSLV_STATUS_OTHER;
1944 ns->counters->cname_error++;
1945 break;
1946
1947 case RSLV_RESP_TRUNCATED:
1948 res->status = RSLV_STATUS_OTHER;
1949 ns->counters->truncated++;
1950 break;
1951
1952 case RSLV_RESP_NO_EXPECTED_RECORD:
1953 case RSLV_RESP_ERROR:
1954 case RSLV_RESP_INTERNAL:
1955 res->status = RSLV_STATUS_OTHER;
1956 ns->counters->other++;
1957 break;
1958 }
1959
1960 /* Wait all nameservers response to handle errors */
1961 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
1962 continue;
1963
1964 /* Process error codes */
1965 if (dns_resp != RSLV_RESP_VALID) {
1966 if (res->prefered_query_type != res->query_type) {
1967 /* The fallback on the query type was already performed,
1968 * so check the try counter. If it falls to 0, we can
1969 * report an error. Else, wait the next attempt. */
1970 if (!res->try)
1971 goto report_res_error;
1972 }
1973 else {
1974 /* Fallback from A to AAAA or the opposite and re-send
1975 * the resolution immediately. try counter is not
1976 * decremented. */
1977 if (res->prefered_query_type == DNS_RTYPE_A) {
1978 res->query_type = DNS_RTYPE_AAAA;
1979 resolv_send_query(res);
1980 }
1981 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
1982 res->query_type = DNS_RTYPE_A;
1983 resolv_send_query(res);
1984 }
1985 }
1986 continue;
1987 }
1988
1989 /* Now let's check the query's dname corresponds to the one we
1990 * sent. We can check only the first query of the list. We send
1991 * one query at a time so we get one query in the response */
1992 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
1993 if (query && resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
1994 dns_resp = RSLV_RESP_WRONG_NAME;
1995 ns->counters->other++;
1996 goto report_res_error;
1997 }
1998
1999 /* So the resolution succeeded */
2000 res->status = RSLV_STATUS_VALID;
2001 res->last_valid = now_ms;
2002 ns->counters->valid++;
2003 goto report_res_success;
2004
2005 report_res_error:
2006 list_for_each_entry(req, &res->requesters, list)
2007 req->requester_error_cb(req, dns_resp);
2008 resolv_reset_resolution(res);
2009 LIST_DEL(&res->list);
2010 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2011 continue;
2012
2013 report_res_success:
2014 /* Only the 1rst requester s managed by the server, others are
2015 * from the cache */
2016 tmpcounters = ns->counters;
2017 list_for_each_entry(req, &res->requesters, list) {
2018 struct server *s = objt_server(req->owner);
2019
2020 if (s)
2021 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
2022 req->requester_cb(req, tmpcounters);
2023 if (s)
2024 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
2025 tmpcounters = NULL;
2026 }
2027
2028 resolv_reset_resolution(res);
2029 LIST_DEL(&res->list);
2030 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2031 continue;
2032 }
2033 resolv_update_resolvers_timeout(resolvers);
2034 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2035
2036 return buflen;
2037}
2038
2039/* Processes DNS resolution. First, it checks the active list to detect expired
2040 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2041 * checks the wait list to trigger new resolutions.
2042 */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002043static struct task *process_resolvers(struct task *t, void *context, unsigned int state)
Emeric Brunc9437992021-02-12 19:42:55 +01002044{
2045 struct resolvers *resolvers = context;
2046 struct resolv_resolution *res, *resback;
2047 int exp;
2048
2049 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2050
2051 /* Handle all expired resolutions from the active list */
2052 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2053 /* When we find the first resolution in the future, then we can
2054 * stop here */
2055 exp = tick_add(res->last_query, resolvers->timeout.retry);
2056 if (!tick_is_expired(exp, now_ms))
2057 break;
2058
2059 /* If current resolution has been tried too many times and
2060 * finishes in timeout we update its status and remove it from
2061 * the list */
2062 if (!res->try) {
2063 struct resolv_requester *req;
2064
2065 /* Notify the result to the requesters */
2066 if (!res->nb_responses)
2067 res->status = RSLV_STATUS_TIMEOUT;
2068 list_for_each_entry(req, &res->requesters, list)
2069 req->requester_error_cb(req, res->status);
2070
2071 /* Clean up resolution info and remove it from the
2072 * current list */
2073 resolv_reset_resolution(res);
2074 LIST_DEL(&res->list);
2075 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2076 }
2077 else {
2078 /* Otherwise resend the DNS query and requeue the resolution */
2079 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2080 /* No response received (a real timeout) or fallback already done */
2081 res->query_type = res->prefered_query_type;
2082 res->try--;
2083 }
2084 else {
2085 /* Fallback from A to AAAA or the opposite and re-send
2086 * the resolution immediately. try counter is not
2087 * decremented. */
2088 if (res->prefered_query_type == DNS_RTYPE_A)
2089 res->query_type = DNS_RTYPE_AAAA;
2090 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2091 res->query_type = DNS_RTYPE_A;
2092 else
2093 res->try--;
2094 }
2095 resolv_send_query(res);
2096 }
2097 }
2098
2099 /* Handle all resolutions in the wait list */
2100 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2101 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2102 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2103 continue;
2104
2105 if (resolv_run_resolution(res) != 1) {
2106 res->last_resolution = now_ms;
2107 LIST_DEL(&res->list);
2108 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2109 }
2110 }
2111
2112 resolv_update_resolvers_timeout(resolvers);
2113 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2114 return t;
2115}
2116
2117/* Release memory allocated by DNS */
2118static void resolvers_deinit(void)
2119{
2120 struct resolvers *resolvers, *resolversback;
2121 struct dns_nameserver *ns, *nsback;
2122 struct resolv_resolution *res, *resback;
2123 struct resolv_requester *req, *reqback;
2124 struct resolv_srvrq *srvrq, *srvrqback;
2125
2126 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2127 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2128 free(ns->id);
2129 free((char *)ns->conf.file);
2130 if (ns->dgram) {
2131 if (ns->dgram->conn.t.sock.fd != -1) {
2132 fd_delete(ns->dgram->conn.t.sock.fd);
2133 close(ns->dgram->conn.t.sock.fd);
2134 }
2135 if (ns->dgram->ring_req)
2136 ring_free(ns->dgram->ring_req);
2137 free(ns->dgram);
2138 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002139 if (ns->stream) {
2140 if (ns->stream->ring_req)
2141 ring_free(ns->stream->ring_req);
2142 if (ns->stream->task_req)
2143 task_destroy(ns->stream->task_req);
2144 if (ns->stream->task_rsp)
2145 task_destroy(ns->stream->task_rsp);
2146 free(ns->stream);
2147 }
Emeric Brunc9437992021-02-12 19:42:55 +01002148 LIST_DEL(&ns->list);
2149 EXTRA_COUNTERS_FREE(ns->extra_counters);
2150 free(ns);
2151 }
2152
2153 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2154 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2155 LIST_DEL(&req->list);
2156 pool_free(resolv_requester_pool, req);
2157 }
2158 resolv_free_resolution(res);
2159 }
2160
2161 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2162 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2163 LIST_DEL(&req->list);
2164 pool_free(resolv_requester_pool, req);
2165 }
2166 resolv_free_resolution(res);
2167 }
2168
2169 free(resolvers->id);
2170 free((char *)resolvers->conf.file);
2171 task_destroy(resolvers->t);
2172 LIST_DEL(&resolvers->list);
2173 free(resolvers);
2174 }
2175
2176 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2177 free(srvrq->name);
2178 free(srvrq->hostname_dn);
2179 LIST_DEL(&srvrq->list);
2180 free(srvrq);
2181 }
2182}
2183
2184/* Finalizes the DNS configuration by allocating required resources and checking
2185 * live parameters.
2186 * Returns 0 on success, ERR_* flags otherwise.
2187 */
2188static int resolvers_finalize_config(void)
2189{
2190 struct resolvers *resolvers;
2191 struct proxy *px;
2192 int err_code = 0;
2193
2194 /* allocate pool of resolution per resolvers */
2195 list_for_each_entry(resolvers, &sec_resolvers, list) {
2196 struct dns_nameserver *ns;
2197 struct task *t;
2198
2199 /* Check if we can create the socket with nameservers info */
2200 list_for_each_entry(ns, &resolvers->nameservers, list) {
2201 int fd;
2202
2203 if (ns->dgram) {
2204 /* Check nameserver info */
2205 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
2206 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2207 resolvers->id, ns->id);
2208 err_code |= (ERR_ALERT|ERR_ABORT);
2209 continue;
2210 }
2211 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
2212 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2213 resolvers->id, ns->id);
2214 close(fd);
2215 err_code |= (ERR_ALERT|ERR_ABORT);
2216 continue;
2217 }
2218 close(fd);
2219 }
2220 }
2221
2222 /* Create the task associated to the resolvers section */
2223 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2224 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
2225 err_code |= (ERR_ALERT|ERR_ABORT);
2226 goto err;
2227 }
2228
2229 /* Update task's parameters */
2230 t->process = process_resolvers;
2231 t->context = resolvers;
2232 resolvers->t = t;
2233 task_wakeup(t, TASK_WOKEN_INIT);
2234 }
2235
2236 for (px = proxies_list; px; px = px->next) {
2237 struct server *srv;
2238
2239 for (srv = px->srv; srv; srv = srv->next) {
2240 struct resolvers *resolvers;
2241
2242 if (!srv->resolvers_id)
2243 continue;
2244
2245 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
2246 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2247 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2248 err_code |= (ERR_ALERT|ERR_ABORT);
2249 continue;
2250 }
2251 srv->resolvers = resolvers;
2252
2253 if (srv->srvrq && !srv->srvrq->resolvers) {
2254 srv->srvrq->resolvers = srv->resolvers;
2255 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2256 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2257 proxy_type_str(px), px->id, srv->id);
2258 err_code |= (ERR_ALERT|ERR_ABORT);
2259 continue;
2260 }
2261 }
2262 if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
2263 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2264 proxy_type_str(px), px->id, srv->id);
2265 err_code |= (ERR_ALERT|ERR_ABORT);
2266 continue;
2267 }
2268 }
2269 }
2270
2271 if (err_code & (ERR_ALERT|ERR_ABORT))
2272 goto err;
2273
2274 return err_code;
2275 err:
2276 resolvers_deinit();
2277 return err_code;
2278
2279}
2280
2281static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2282 struct dns_nameserver *ns,
2283 struct field *stats, size_t stats_count,
2284 struct list *stat_modules)
2285{
2286 struct appctx *appctx = __objt_appctx(si->end);
2287 struct channel *rep = si_ic(si);
2288 struct stats_module *mod;
2289 size_t idx = 0;
2290
2291 memset(stats, 0, sizeof(struct field) * stats_count);
2292
2293 list_for_each_entry(mod, stat_modules, list) {
2294 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2295
2296 mod->fill_stats(counters, stats + idx);
2297 idx += mod->stats_count;
2298 }
2299
2300 if (!stats_dump_one_line(stats, idx, appctx))
2301 return 0;
2302
2303 if (!stats_putchk(rep, NULL, &trash))
2304 goto full;
2305
2306 return 1;
2307
2308 full:
2309 si_rx_room_rdy(si);
2310 return 0;
2311}
2312
2313/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2314 * as a pointer to the current nameserver.
2315 */
2316int stats_dump_resolvers(struct stream_interface *si,
2317 struct field *stats, size_t stats_count,
2318 struct list *stat_modules)
2319{
2320 struct appctx *appctx = __objt_appctx(si->end);
2321 struct channel *rep = si_ic(si);
2322 struct resolvers *resolver = appctx->ctx.stats.obj1;
2323 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2324
2325 if (!resolver)
2326 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2327
2328 /* dump resolvers */
2329 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2330 appctx->ctx.stats.obj1 = resolver;
2331
2332 ns = appctx->ctx.stats.obj2 ?
2333 appctx->ctx.stats.obj2 :
2334 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2335
2336 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2337 appctx->ctx.stats.obj2 = ns;
2338
2339 if (buffer_almost_full(&rep->buf))
2340 goto full;
2341
2342 if (!stats_dump_resolv_to_buffer(si, ns,
2343 stats, stats_count,
2344 stat_modules)) {
2345 return 0;
2346 }
2347 }
2348
2349 appctx->ctx.stats.obj2 = NULL;
2350 }
2351
2352 return 1;
2353
2354 full:
2355 si_rx_room_blk(si);
2356 return 0;
2357}
2358
2359void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2360{
2361 struct resolvers *resolvers;
2362 struct dns_nameserver *ns;
2363 struct stats_module *mod;
2364 void *counters;
2365
2366 list_for_each_entry(mod, stat_modules, list) {
2367 if (!mod->clearable && !clrall)
2368 continue;
2369
2370 list_for_each_entry(resolvers, &sec_resolvers, list) {
2371 list_for_each_entry(ns, &resolvers->nameservers, list) {
2372 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2373 memcpy(counters, mod->counters, mod->counters_size);
2374 }
2375 }
2376 }
2377
2378}
2379
2380int resolv_allocate_counters(struct list *stat_modules)
2381{
2382 struct stats_module *mod;
2383 struct resolvers *resolvers;
2384 struct dns_nameserver *ns;
2385
2386 list_for_each_entry(resolvers, &sec_resolvers, list) {
2387 list_for_each_entry(ns, &resolvers->nameservers, list) {
2388 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2389 alloc_failed);
2390
2391 list_for_each_entry(mod, stat_modules, list) {
2392 EXTRA_COUNTERS_ADD(mod,
2393 ns->extra_counters,
2394 mod->counters,
2395 mod->counters_size);
2396 }
2397
2398 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2399
2400 list_for_each_entry(mod, stat_modules, list) {
2401 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2402 mod->counters, mod->counters_size);
2403
2404 /* Store the ns counters pointer */
2405 if (strcmp(mod->name, "dns") == 0) {
2406 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2407 ns->counters->id = ns->id;
2408 ns->counters->pid = resolvers->id;
2409 }
2410 }
2411 }
2412 }
2413
2414 return 1;
2415
2416alloc_failed:
2417 return 0;
2418}
2419
2420/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2421static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2422{
2423 struct resolvers *presolvers;
2424
2425 if (*args[2]) {
2426 list_for_each_entry(presolvers, &sec_resolvers, list) {
2427 if (strcmp(presolvers->id, args[2]) == 0) {
2428 appctx->ctx.cli.p0 = presolvers;
2429 break;
2430 }
2431 }
2432 if (appctx->ctx.cli.p0 == NULL)
2433 return cli_err(appctx, "Can't find that resolvers section\n");
2434 }
2435 return 0;
2436}
2437
2438/* Dumps counters from all resolvers section and associated name servers. It
2439 * returns 0 if the output buffer is full and it needs to be called again,
2440 * otherwise non-zero. It may limit itself to the resolver pointed to by
2441 * <cli.p0> if it's not null.
2442 */
2443static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2444{
2445 struct stream_interface *si = appctx->owner;
2446 struct resolvers *resolvers;
2447 struct dns_nameserver *ns;
2448
2449 chunk_reset(&trash);
2450
2451 switch (appctx->st2) {
2452 case STAT_ST_INIT:
2453 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2454 /* fall through */
2455
2456 case STAT_ST_LIST:
2457 if (LIST_ISEMPTY(&sec_resolvers)) {
2458 chunk_appendf(&trash, "No resolvers found\n");
2459 }
2460 else {
2461 list_for_each_entry(resolvers, &sec_resolvers, list) {
2462 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2463 continue;
2464
2465 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2466 list_for_each_entry(ns, &resolvers->nameservers, list) {
2467 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2468 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2469 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2470 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2471 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2472 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2473 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2474 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2475 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2476 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2477 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2478 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2479 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2480 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2481 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2482 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
2483 }
2484 chunk_appendf(&trash, "\n");
2485 }
2486 }
2487
2488 /* display response */
2489 if (ci_putchk(si_ic(si), &trash) == -1) {
2490 /* let's try again later from this session. We add ourselves into
2491 * this session's users so that it can remove us upon termination.
2492 */
2493 si_rx_room_blk(si);
2494 return 0;
2495 }
2496 /* fall through */
2497
2498 default:
2499 appctx->st2 = STAT_ST_FIN;
2500 return 1;
2501 }
2502}
2503
2504/* register cli keywords */
2505static struct cli_kw_list cli_kws = {{ }, {
2506 { { "show", "resolvers", NULL }, "show resolvers [id]: dumps counters from all resolvers section and\n"
2507 " associated name servers",
2508 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2509 {{},}
2510 }
2511};
2512
2513INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2514
2515/*
2516 * Prepare <rule> for hostname resolution.
2517 * Returns -1 in case of any allocation failure, 0 if not.
2518 * On error, a global failure counter is also incremented.
2519 */
2520static int action_prepare_for_resolution(struct stream *stream, const char *hostname)
2521{
2522 char *hostname_dn;
2523 int hostname_len, hostname_dn_len;
2524 struct buffer *tmp = get_trash_chunk();
2525
2526 if (!hostname)
2527 return 0;
2528
2529 hostname_len = strlen(hostname);
2530 hostname_dn = tmp->area;
2531 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len + 1,
2532 hostname_dn, tmp->size);
2533 if (hostname_dn_len == -1)
2534 goto err;
2535
2536
2537 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2538 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2539 if (!stream->resolv_ctx.hostname_dn)
2540 goto err;
2541
2542 return 0;
2543
2544 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002545 ha_free(&stream->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002546 resolv_failed_resolutions += 1;
2547 return -1;
2548}
2549
2550
2551/*
2552 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2553 */
2554enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2555 struct session *sess, struct stream *s, int flags)
2556{
2557 struct resolv_resolution *resolution;
2558 struct sample *smp;
2559 char *fqdn;
2560 struct resolv_requester *req;
2561 struct resolvers *resolvers;
2562 struct resolv_resolution *res;
2563 int exp, locked = 0;
2564 enum act_return ret = ACT_RET_CONT;
2565
2566 resolvers = rule->arg.resolv.resolvers;
2567
2568 /* we have a response to our DNS resolution */
2569 use_cache:
2570 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2571 resolution = s->resolv_ctx.requester->resolution;
2572 if (!locked) {
2573 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2574 locked = 1;
2575 }
2576
2577 if (resolution->step == RSLV_STEP_RUNNING)
2578 goto yield;
2579 if (resolution->step == RSLV_STEP_NONE) {
2580 /* We update the variable only if we have a valid response. */
2581 if (resolution->status == RSLV_STATUS_VALID) {
2582 struct sample smp;
2583 short ip_sin_family = 0;
2584 void *ip = NULL;
2585
2586 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2587 0, &ip, &ip_sin_family, NULL);
2588
2589 switch (ip_sin_family) {
2590 case AF_INET:
2591 smp.data.type = SMP_T_IPV4;
2592 memcpy(&smp.data.u.ipv4, ip, 4);
2593 break;
2594 case AF_INET6:
2595 smp.data.type = SMP_T_IPV6;
2596 memcpy(&smp.data.u.ipv6, ip, 16);
2597 break;
2598 default:
2599 ip = NULL;
2600 }
2601
2602 if (ip) {
2603 smp.px = px;
2604 smp.sess = sess;
2605 smp.strm = s;
2606
2607 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2608 }
2609 }
2610 }
2611
2612 goto release_requester;
2613 }
2614
2615 /* need to configure and start a new DNS resolution */
2616 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2617 if (smp == NULL)
2618 goto end;
2619
2620 fqdn = smp->data.u.str.area;
2621 if (action_prepare_for_resolution(s, fqdn) == -1)
2622 goto end; /* on error, ignore the action */
2623
2624 s->resolv_ctx.parent = rule;
2625
2626 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2627 locked = 1;
2628
2629 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2630
2631 /* Check if there is a fresh enough response in the cache of our associated resolution */
2632 req = s->resolv_ctx.requester;
2633 if (!req || !req->resolution)
2634 goto release_requester; /* on error, ignore the action */
2635 res = req->resolution;
2636
2637 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2638 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2639 && !tick_is_expired(exp, now_ms)) {
2640 goto use_cache;
2641 }
2642
2643 resolv_trigger_resolution(s->resolv_ctx.requester);
2644
2645 yield:
2646 if (flags & ACT_OPT_FINAL)
2647 goto release_requester;
2648 ret = ACT_RET_YIELD;
2649
2650 end:
2651 if (locked)
2652 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2653 return ret;
2654
2655 release_requester:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002656 ha_free(&s->resolv_ctx.hostname_dn);
Emeric Brunc9437992021-02-12 19:42:55 +01002657 s->resolv_ctx.hostname_dn_len = 0;
2658 if (s->resolv_ctx.requester) {
2659 resolv_unlink_resolution(s->resolv_ctx.requester);
2660 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2661 s->resolv_ctx.requester = NULL;
2662 }
2663 goto end;
2664}
2665
2666static void release_resolv_action(struct act_rule *rule)
2667{
2668 release_sample_expr(rule->arg.resolv.expr);
2669 free(rule->arg.resolv.varname);
2670 free(rule->arg.resolv.resolvers_id);
2671 free(rule->arg.resolv.opts);
2672}
2673
2674
2675/* parse "do-resolve" action
2676 * This action takes the following arguments:
2677 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
2678 *
2679 * - <varName> is the variable name where the result of the DNS resolution will be stored
2680 * (mandatory)
2681 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
2682 * (mandatory)
2683 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
2684 * (optional), defaults to ipv6
2685 * - <expr> is an HAProxy expression used to fetch the name to be resolved
2686 */
2687enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
2688{
2689 int cur_arg;
2690 struct sample_expr *expr;
2691 unsigned int where;
2692 const char *beg, *end;
2693
2694 /* orig_arg points to the first argument, but we need to analyse the command itself first */
2695 cur_arg = *orig_arg - 1;
2696
2697 /* locate varName, which is mandatory */
2698 beg = strchr(args[cur_arg], '(');
2699 if (beg == NULL)
2700 goto do_resolve_parse_error;
2701 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
2702 end = strchr(beg, ',');
2703 if (end == NULL)
2704 goto do_resolve_parse_error;
2705 rule->arg.resolv.varname = my_strndup(beg, end - beg);
2706 if (rule->arg.resolv.varname == NULL)
2707 goto do_resolve_parse_error;
2708
2709
2710 /* locate resolversSectionName, which is mandatory.
2711 * Since next parameters are optional, the delimiter may be comma ','
2712 * or closing parenthesis ')'
2713 */
2714 beg = end + 1;
2715 end = strchr(beg, ',');
2716 if (end == NULL)
2717 end = strchr(beg, ')');
2718 if (end == NULL)
2719 goto do_resolve_parse_error;
2720 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
2721 if (rule->arg.resolv.resolvers_id == NULL)
2722 goto do_resolve_parse_error;
2723
2724
2725 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
2726 if (rule->arg.resolv.opts == NULL)
2727 goto do_resolve_parse_error;
2728
2729 /* Default priority is ipv6 */
2730 rule->arg.resolv.opts->family_prio = AF_INET6;
2731
2732 /* optional arguments accepted for now:
2733 * ipv4 or ipv6
2734 */
2735 while (*end != ')') {
2736 beg = end + 1;
2737 end = strchr(beg, ',');
2738 if (end == NULL)
2739 end = strchr(beg, ')');
2740 if (end == NULL)
2741 goto do_resolve_parse_error;
2742
2743 if (strncmp(beg, "ipv4", end - beg) == 0) {
2744 rule->arg.resolv.opts->family_prio = AF_INET;
2745 }
2746 else if (strncmp(beg, "ipv6", end - beg) == 0) {
2747 rule->arg.resolv.opts->family_prio = AF_INET6;
2748 }
2749 else {
2750 goto do_resolve_parse_error;
2751 }
2752 }
2753
2754 cur_arg = cur_arg + 1;
2755
2756 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
2757 if (!expr)
2758 goto do_resolve_parse_error;
2759
2760
2761 where = 0;
2762 if (px->cap & PR_CAP_FE)
2763 where |= SMP_VAL_FE_HRQ_HDR;
2764 if (px->cap & PR_CAP_BE)
2765 where |= SMP_VAL_BE_HRQ_HDR;
2766
2767 if (!(expr->fetch->val & where)) {
2768 memprintf(err,
2769 "fetch method '%s' extracts information from '%s', none of which is available here",
2770 args[cur_arg-1], sample_src_names(expr->fetch->use));
2771 free(expr);
2772 return ACT_RET_PRS_ERR;
2773 }
2774 rule->arg.resolv.expr = expr;
2775 rule->action = ACT_CUSTOM;
2776 rule->action_ptr = resolv_action_do_resolve;
2777 *orig_arg = cur_arg;
2778
2779 rule->check_ptr = check_action_do_resolve;
2780 rule->release_ptr = release_resolv_action;
2781
2782 return ACT_RET_PRS_OK;
2783
2784 do_resolve_parse_error:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002785 ha_free(&rule->arg.resolv.varname);
2786 ha_free(&rule->arg.resolv.resolvers_id);
Emeric Brunc9437992021-02-12 19:42:55 +01002787 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
2788 args[cur_arg]);
2789 return ACT_RET_PRS_ERR;
2790}
2791
2792static struct action_kw_list http_req_kws = { { }, {
2793 { "do-resolve", resolv_parse_do_resolve, 1 },
2794 { /* END */ }
2795}};
2796
2797INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
2798
2799static struct action_kw_list tcp_req_cont_actions = {ILH, {
2800 { "do-resolve", resolv_parse_do_resolve, 1 },
2801 { /* END */ }
2802}};
2803
2804INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
2805
2806/* Check an "http-request do-resolve" action.
2807 *
2808 * The function returns 1 in success case, otherwise, it returns 0 and err is
2809 * filled.
2810 */
2811int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
2812{
2813 struct resolvers *resolvers = NULL;
2814
2815 if (rule->arg.resolv.resolvers_id == NULL) {
2816 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
2817 return 0;
2818 }
2819
2820 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
2821 if (resolvers == NULL) {
2822 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
2823 return 0;
2824 }
2825 rule->arg.resolv.resolvers = resolvers;
2826
2827 return 1;
2828}
2829
2830void resolvers_setup_proxy(struct proxy *px)
2831{
2832 px->last_change = now.tv_sec;
2833 px->cap = PR_CAP_FE | PR_CAP_BE;
2834 px->maxconn = 0;
2835 px->conn_retries = 1;
2836 px->timeout.server = TICK_ETERNITY;
2837 px->timeout.client = TICK_ETERNITY;
2838 px->timeout.connect = TICK_ETERNITY;
2839 px->accept = NULL;
2840 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
2841 px->bind_proc = 0; /* will be filled by users */
2842}
2843
2844/*
2845 * Parse a <resolvers> section.
2846 * Returns the error code, 0 if OK, or any combination of :
2847 * - ERR_ABORT: must abort ASAP
2848 * - ERR_FATAL: we can continue parsing but not start the service
2849 * - ERR_WARN: a warning has been emitted
2850 * - ERR_ALERT: an alert has been emitted
2851 * Only the two first ones can stop processing, the two others are just
2852 * indicators.
2853 */
2854int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
2855{
2856 const char *err;
2857 int err_code = 0;
2858 char *errmsg = NULL;
2859 struct proxy *p;
2860
2861 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
2862 if (!*args[1]) {
2863 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
2864 err_code |= ERR_ALERT | ERR_ABORT;
2865 goto out;
2866 }
2867
2868 err = invalid_char(args[1]);
2869 if (err) {
2870 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
2871 file, linenum, *err, args[0], args[1]);
2872 err_code |= ERR_ALERT | ERR_ABORT;
2873 goto out;
2874 }
2875
2876 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
2877 /* Error if two resolvers owns the same name */
2878 if (strcmp(curr_resolvers->id, args[1]) == 0) {
2879 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
2880 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
2881 err_code |= ERR_ALERT | ERR_ABORT;
2882 }
2883 }
2884
2885 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
2886 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2887 err_code |= ERR_ALERT | ERR_ABORT;
2888 goto out;
2889 }
2890
2891 /* allocate new proxy to tcp servers */
2892 p = calloc(1, sizeof *p);
2893 if (!p) {
2894 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2895 err_code |= ERR_ALERT | ERR_FATAL;
2896 goto out;
2897 }
2898
2899 init_new_proxy(p);
2900 resolvers_setup_proxy(p);
2901 p->parent = curr_resolvers;
2902 p->id = strdup(args[1]);
2903 p->conf.args.file = p->conf.file = strdup(file);
2904 p->conf.args.line = p->conf.line = linenum;
2905 curr_resolvers->px = p;
2906
2907 /* default values */
2908 LIST_ADDQ(&sec_resolvers, &curr_resolvers->list);
2909 curr_resolvers->conf.file = strdup(file);
2910 curr_resolvers->conf.line = linenum;
2911 curr_resolvers->id = strdup(args[1]);
2912 curr_resolvers->query_ids = EB_ROOT;
2913 /* default maximum response size */
2914 curr_resolvers->accepted_payload_size = 512;
2915 /* default hold period for nx, other, refuse and timeout is 30s */
2916 curr_resolvers->hold.nx = 30000;
2917 curr_resolvers->hold.other = 30000;
2918 curr_resolvers->hold.refused = 30000;
2919 curr_resolvers->hold.timeout = 30000;
2920 curr_resolvers->hold.obsolete = 0;
2921 /* default hold period for valid is 10s */
2922 curr_resolvers->hold.valid = 10000;
2923 curr_resolvers->timeout.resolve = 1000;
2924 curr_resolvers->timeout.retry = 1000;
2925 curr_resolvers->resolve_retries = 3;
2926 LIST_INIT(&curr_resolvers->nameservers);
2927 LIST_INIT(&curr_resolvers->resolutions.curr);
2928 LIST_INIT(&curr_resolvers->resolutions.wait);
2929 HA_SPIN_INIT(&curr_resolvers->lock);
2930 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002931 else if (strcmp(args[0],"server") == 0) {
2932 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL, 1, 0, 1);
2933 }
Emeric Brunc9437992021-02-12 19:42:55 +01002934 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
2935 struct dns_nameserver *newnameserver = NULL;
2936 struct sockaddr_storage *sk;
2937 int port1, port2;
2938
2939 if (!*args[2]) {
2940 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
2941 file, linenum, args[0]);
2942 err_code |= ERR_ALERT | ERR_FATAL;
2943 goto out;
2944 }
2945
2946 err = invalid_char(args[1]);
2947 if (err) {
2948 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
2949 file, linenum, *err, args[1]);
2950 err_code |= ERR_ALERT | ERR_FATAL;
2951 goto out;
2952 }
2953
2954 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
2955 /* Error if two resolvers owns the same name */
2956 if (strcmp(newnameserver->id, args[1]) == 0) {
2957 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
2958 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
2959 err_code |= ERR_ALERT | ERR_FATAL;
2960 }
2961 }
2962
2963 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, NULL,
2964 &errmsg, NULL, NULL, PA_O_RESOLVE | PA_O_PORT_OK | PA_O_PORT_MAND | PA_O_DGRAM);
2965 if (!sk) {
2966 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
2967 err_code |= ERR_ALERT | ERR_FATAL;
2968 goto out;
2969 }
2970
2971 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
2972 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2973 err_code |= ERR_ALERT | ERR_ABORT;
2974 goto out;
2975 }
2976
2977 if (dns_dgram_init(newnameserver, sk) < 0) {
2978 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2979 err_code |= ERR_ALERT | ERR_ABORT;
2980 goto out;
2981 }
2982
2983 if ((newnameserver->conf.file = strdup(file)) == NULL) {
2984 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2985 err_code |= ERR_ALERT | ERR_ABORT;
2986 goto out;
2987 }
2988
2989 if ((newnameserver->id = strdup(args[1])) == NULL) {
2990 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2991 err_code |= ERR_ALERT | ERR_ABORT;
2992 goto out;
2993 }
2994
2995 newnameserver->parent = curr_resolvers;
2996 newnameserver->process_responses = resolv_process_responses;
2997 newnameserver->conf.line = linenum;
2998 /* the nameservers are linked backward first */
2999 LIST_ADDQ(&curr_resolvers->nameservers, &newnameserver->list);
3000 }
3001 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
3002 struct dns_nameserver *newnameserver = NULL;
3003 const char *whitespace = "\r\n\t ";
3004 char *resolv_line = NULL;
3005 int resolv_linenum = 0;
3006 FILE *f = NULL;
3007 char *address = NULL;
3008 struct sockaddr_storage *sk = NULL;
3009 struct protocol *proto;
3010 int duplicate_name = 0;
3011
3012 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
3013 ha_alert("parsing [%s:%d] : out of memory.\n",
3014 file, linenum);
3015 err_code |= ERR_ALERT | ERR_FATAL;
3016 goto resolv_out;
3017 }
3018
3019 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
3020 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
3021 file, linenum);
3022 err_code |= ERR_ALERT | ERR_FATAL;
3023 goto resolv_out;
3024 }
3025
3026 sk = calloc(1, sizeof(*sk));
3027 if (sk == NULL) {
3028 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
3029 resolv_linenum);
3030 err_code |= ERR_ALERT | ERR_FATAL;
3031 goto resolv_out;
3032 }
3033
3034 while (fgets(resolv_line, LINESIZE, f) != NULL) {
3035 resolv_linenum++;
3036 if (strncmp(resolv_line, "nameserver", 10) != 0)
3037 continue;
3038
3039 address = strtok(resolv_line + 10, whitespace);
3040 if (address == resolv_line + 10)
3041 continue;
3042
3043 if (address == NULL) {
3044 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3045 resolv_linenum);
3046 err_code |= ERR_WARN;
3047 continue;
3048 }
3049
3050 duplicate_name = 0;
3051 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3052 if (strcmp(newnameserver->id, address) == 0) {
3053 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",
3054 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3055 err_code |= ERR_WARN;
3056 duplicate_name = 1;
3057 }
3058 }
3059
3060 if (duplicate_name)
3061 continue;
3062
3063 memset(sk, 0, sizeof(*sk));
3064 if (!str2ip2(address, sk, 1)) {
3065 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3066 resolv_linenum, address);
3067 err_code |= ERR_WARN;
3068 continue;
3069 }
3070
3071 set_host_port(sk, 53);
3072
3073 proto = protocol_by_family(sk->ss_family);
3074 if (!proto || !proto->connect) {
3075 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3076 resolv_linenum, address);
3077 err_code |= ERR_WARN;
3078 continue;
3079 }
3080
3081 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3082 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3083 err_code |= ERR_ALERT | ERR_FATAL;
3084 goto resolv_out;
3085 }
3086
3087 if (dns_dgram_init(newnameserver, sk) < 0) {
3088 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3089 err_code |= ERR_ALERT | ERR_FATAL;
3090 free(newnameserver);
3091 goto resolv_out;
3092 }
3093
3094 newnameserver->conf.file = strdup("/etc/resolv.conf");
3095 if (newnameserver->conf.file == NULL) {
3096 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3097 err_code |= ERR_ALERT | ERR_FATAL;
3098 free(newnameserver);
3099 goto resolv_out;
3100 }
3101
3102 newnameserver->id = strdup(address);
3103 if (newnameserver->id == NULL) {
3104 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3105 err_code |= ERR_ALERT | ERR_FATAL;
3106 free((char *)newnameserver->conf.file);
3107 free(newnameserver);
3108 goto resolv_out;
3109 }
3110
3111 newnameserver->parent = curr_resolvers;
3112 newnameserver->process_responses = resolv_process_responses;
3113 newnameserver->conf.line = resolv_linenum;
3114 LIST_ADDQ(&curr_resolvers->nameservers, &newnameserver->list);
3115 }
3116
3117resolv_out:
3118 free(sk);
3119 free(resolv_line);
3120 if (f != NULL)
3121 fclose(f);
3122 }
3123 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3124 const char *res;
3125 unsigned int time;
3126
3127 if (!*args[2]) {
3128 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3129 file, linenum, args[0]);
3130 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3131 err_code |= ERR_ALERT | ERR_FATAL;
3132 goto out;
3133 }
3134 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3135 if (res == PARSE_TIME_OVER) {
3136 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3137 file, linenum, args[1], args[0]);
3138 err_code |= ERR_ALERT | ERR_FATAL;
3139 goto out;
3140 }
3141 else if (res == PARSE_TIME_UNDER) {
3142 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3143 file, linenum, args[1], args[0]);
3144 err_code |= ERR_ALERT | ERR_FATAL;
3145 goto out;
3146 }
3147 else if (res) {
3148 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3149 file, linenum, *res, args[0]);
3150 err_code |= ERR_ALERT | ERR_FATAL;
3151 goto out;
3152 }
3153 if (strcmp(args[1], "nx") == 0)
3154 curr_resolvers->hold.nx = time;
3155 else if (strcmp(args[1], "other") == 0)
3156 curr_resolvers->hold.other = time;
3157 else if (strcmp(args[1], "refused") == 0)
3158 curr_resolvers->hold.refused = time;
3159 else if (strcmp(args[1], "timeout") == 0)
3160 curr_resolvers->hold.timeout = time;
3161 else if (strcmp(args[1], "valid") == 0)
3162 curr_resolvers->hold.valid = time;
3163 else if (strcmp(args[1], "obsolete") == 0)
3164 curr_resolvers->hold.obsolete = time;
3165 else {
3166 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3167 file, linenum, args[0], args[1]);
3168 err_code |= ERR_ALERT | ERR_FATAL;
3169 goto out;
3170 }
3171
3172 }
3173 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3174 int i = 0;
3175
3176 if (!*args[1]) {
3177 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3178 file, linenum, args[0]);
3179 err_code |= ERR_ALERT | ERR_FATAL;
3180 goto out;
3181 }
3182
3183 i = atoi(args[1]);
3184 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3185 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3186 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3187 err_code |= ERR_ALERT | ERR_FATAL;
3188 goto out;
3189 }
3190
3191 curr_resolvers->accepted_payload_size = i;
3192 }
3193 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3194 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3195 file, linenum, args[0]);
3196 err_code |= ERR_ALERT | ERR_FATAL;
3197 goto out;
3198 }
3199 else if (strcmp(args[0], "resolve_retries") == 0) {
3200 if (!*args[1]) {
3201 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3202 file, linenum, args[0]);
3203 err_code |= ERR_ALERT | ERR_FATAL;
3204 goto out;
3205 }
3206 curr_resolvers->resolve_retries = atoi(args[1]);
3207 }
3208 else if (strcmp(args[0], "timeout") == 0) {
3209 if (!*args[1]) {
3210 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3211 file, linenum, args[0]);
3212 err_code |= ERR_ALERT | ERR_FATAL;
3213 goto out;
3214 }
3215 else if (strcmp(args[1], "retry") == 0 ||
3216 strcmp(args[1], "resolve") == 0) {
3217 const char *res;
3218 unsigned int tout;
3219
3220 if (!*args[2]) {
3221 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3222 file, linenum, args[0], args[1]);
3223 err_code |= ERR_ALERT | ERR_FATAL;
3224 goto out;
3225 }
3226 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3227 if (res == PARSE_TIME_OVER) {
3228 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3229 file, linenum, args[2], args[0], args[1]);
3230 err_code |= ERR_ALERT | ERR_FATAL;
3231 goto out;
3232 }
3233 else if (res == PARSE_TIME_UNDER) {
3234 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3235 file, linenum, args[2], args[0], args[1]);
3236 err_code |= ERR_ALERT | ERR_FATAL;
3237 goto out;
3238 }
3239 else if (res) {
3240 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3241 file, linenum, *res, args[0], args[1]);
3242 err_code |= ERR_ALERT | ERR_FATAL;
3243 goto out;
3244 }
3245 if (args[1][2] == 't')
3246 curr_resolvers->timeout.retry = tout;
3247 else
3248 curr_resolvers->timeout.resolve = tout;
3249 }
3250 else {
3251 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3252 file, linenum, args[0], args[1]);
3253 err_code |= ERR_ALERT | ERR_FATAL;
3254 goto out;
3255 }
3256 }
3257 else if (*args[0] != 0) {
3258 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3259 err_code |= ERR_ALERT | ERR_FATAL;
3260 goto out;
3261 }
3262
3263 out:
3264 free(errmsg);
3265 return err_code;
3266}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003267int cfg_post_parse_resolvers()
3268{
3269 int err_code = 0;
3270 struct server *srv;
3271
3272 if (curr_resolvers) {
3273
3274 /* prepare forward server descriptors */
3275 if (curr_resolvers->px) {
3276 srv = curr_resolvers->px->srv;
3277 while (srv) {
3278 struct dns_nameserver *ns;
3279
3280 list_for_each_entry(ns, &curr_resolvers->nameservers, list) {
3281 /* Error if two resolvers owns the same name */
3282 if (strcmp(ns->id, srv->id) == 0) {
3283 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3284 srv->conf.file, srv->conf.line, srv->id, ns->conf.file, ns->conf.line);
3285 err_code |= ERR_ALERT | ERR_FATAL;
3286 break;
3287 }
3288 }
3289
3290 /* init ssl if needed */
3291 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3292 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3293 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3294 err_code |= ERR_ALERT | ERR_FATAL;
3295 break;
3296 }
3297 }
3298
3299 /* allocate nameserver */
3300 ns = calloc(1, sizeof(*ns));
3301 if (!ns) {
3302 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3303 err_code |= ERR_ALERT | ERR_FATAL;
3304 break;
3305 }
3306
3307 if (dns_stream_init(ns, srv) < 0) {
3308 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3309 err_code |= ERR_ALERT|ERR_ABORT;
3310 break;
3311 }
3312
3313 ns->conf.file = strdup(srv->conf.file);
3314 if (!ns->conf.file) {
3315 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3316 err_code |= ERR_ALERT|ERR_ABORT;
3317 break;
3318 }
3319 ns->id = strdup(srv->id);
3320 if (!ns->id) {
3321 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3322 err_code |= ERR_ALERT|ERR_ABORT;
3323 break;
3324 }
3325 ns->conf.line = srv->conf.line;
3326 ns->process_responses = resolv_process_responses;
3327 ns->parent = curr_resolvers;
3328 LIST_ADDQ(&curr_resolvers->nameservers, &ns->list);
3329 srv = srv->next;
3330 }
3331 }
3332 }
3333 curr_resolvers = NULL;
3334 return err_code;
3335}
Emeric Brunc9437992021-02-12 19:42:55 +01003336
Emeric Brun56fc5d92021-02-12 20:05:45 +01003337REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003338REGISTER_POST_DEINIT(resolvers_deinit);
3339REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);