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