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