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