blob: 6af6fc5136e7465da64a7431610db6befd5e2b62 [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;
1241 break;
1242 }
1243 }
1244 if (tmp_record->ar_item != answer_record)
1245 pool_free(resolv_answer_item_pool, answer_record);
1246 answer_record = NULL;
1247 }
1248 } /* for i 0 to arcount */
1249
1250 skip_parsing_additional_records:
1251
1252 /* Save the number of records we really own */
1253 r_res->header.arcount = nb_saved_records;
1254
1255 resolv_check_response(resolution);
1256 return RSLV_RESP_VALID;
1257
1258 invalid_resp:
1259 cause = RSLV_RESP_INVALID;
1260
1261 return_error:
1262 pool_free(resolv_answer_item_pool, answer_record);
1263 return cause;
1264}
1265
1266/* Searches dn_name resolution in resp.
1267 * If existing IP not found, return the first IP matching family_priority,
1268 * otherwise, first ip found
1269 * The following tasks are the responsibility of the caller:
1270 * - <r_res> contains an error free DNS response
1271 * For both cases above, resolv_validate_dns_response is required
1272 * returns one of the RSLV_UPD_* code
1273 */
1274int resolv_get_ip_from_response(struct resolv_response *r_res,
1275 struct resolv_options *resolv_opts, void *currentip,
1276 short currentip_sin_family,
1277 void **newip, short *newip_sin_family,
1278 void *owner)
1279{
1280 struct resolv_answer_item *record;
1281 int family_priority;
1282 int currentip_found;
1283 unsigned char *newip4, *newip6;
1284 int currentip_sel;
1285 int j;
1286 int score, max_score;
1287 int allowed_duplicated_ip;
1288
1289 family_priority = resolv_opts->family_prio;
1290 allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
1291 *newip = newip4 = newip6 = NULL;
1292 currentip_found = 0;
1293 *newip_sin_family = AF_UNSPEC;
1294 max_score = -1;
1295
1296 /* Select an IP regarding configuration preference.
1297 * Top priority is the preferred network ip version,
1298 * second priority is the preferred network.
1299 * the last priority is the currently used IP,
1300 *
1301 * For these three priorities, a score is calculated. The
1302 * weight are:
1303 * 8 - preferred ip version.
1304 * 4 - preferred network.
1305 * 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
1306 * 1 - current ip.
1307 * The result with the biggest score is returned.
1308 */
1309
1310 list_for_each_entry(record, &r_res->answer_list, list) {
1311 void *ip;
1312 unsigned char ip_type;
1313
1314 if (record->type == DNS_RTYPE_A) {
1315 ip = &(((struct sockaddr_in *)&record->address)->sin_addr);
1316 ip_type = AF_INET;
1317 }
1318 else if (record->type == DNS_RTYPE_AAAA) {
1319 ip_type = AF_INET6;
1320 ip = &(((struct sockaddr_in6 *)&record->address)->sin6_addr);
1321 }
1322 else
1323 continue;
1324 score = 0;
1325
1326 /* Check for preferred ip protocol. */
1327 if (ip_type == family_priority)
1328 score += 8;
1329
1330 /* Check for preferred network. */
1331 for (j = 0; j < resolv_opts->pref_net_nb; j++) {
1332
1333 /* Compare only the same addresses class. */
1334 if (resolv_opts->pref_net[j].family != ip_type)
1335 continue;
1336
1337 if ((ip_type == AF_INET &&
1338 in_net_ipv4(ip,
1339 &resolv_opts->pref_net[j].mask.in4,
1340 &resolv_opts->pref_net[j].addr.in4)) ||
1341 (ip_type == AF_INET6 &&
1342 in_net_ipv6(ip,
1343 &resolv_opts->pref_net[j].mask.in6,
1344 &resolv_opts->pref_net[j].addr.in6))) {
1345 score += 4;
1346 break;
1347 }
1348 }
1349
1350 /* Check if the IP found in the record is already affected to a
1351 * member of a group. If not, the score should be incremented
1352 * by 2. */
1353 if (owner && snr_check_ip_callback(owner, ip, &ip_type)) {
1354 if (!allowed_duplicated_ip) {
1355 continue;
1356 }
1357 } else {
1358 score += 2;
1359 }
1360
1361 /* Check for current ip matching. */
1362 if (ip_type == currentip_sin_family &&
1363 ((currentip_sin_family == AF_INET &&
1364 !memcmp(ip, currentip, 4)) ||
1365 (currentip_sin_family == AF_INET6 &&
1366 !memcmp(ip, currentip, 16)))) {
1367 score++;
1368 currentip_sel = 1;
1369 }
1370 else
1371 currentip_sel = 0;
1372
1373 /* Keep the address if the score is better than the previous
1374 * score. The maximum score is 15, if this value is reached, we
1375 * break the parsing. Implicitly, this score is reached the ip
1376 * selected is the current ip. */
1377 if (score > max_score) {
1378 if (ip_type == AF_INET)
1379 newip4 = ip;
1380 else
1381 newip6 = ip;
1382 currentip_found = currentip_sel;
1383 if (score == 15)
1384 return RSLV_UPD_NO;
1385 max_score = score;
1386 }
1387 } /* list for each record entries */
1388
1389 /* No IP found in the response */
1390 if (!newip4 && !newip6)
1391 return RSLV_UPD_NO_IP_FOUND;
1392
1393 /* Case when the caller looks first for an IPv4 address */
1394 if (family_priority == AF_INET) {
1395 if (newip4) {
1396 *newip = newip4;
1397 *newip_sin_family = AF_INET;
1398 }
1399 else if (newip6) {
1400 *newip = newip6;
1401 *newip_sin_family = AF_INET6;
1402 }
1403 if (!currentip_found)
1404 goto not_found;
1405 }
1406 /* Case when the caller looks first for an IPv6 address */
1407 else if (family_priority == AF_INET6) {
1408 if (newip6) {
1409 *newip = newip6;
1410 *newip_sin_family = AF_INET6;
1411 }
1412 else if (newip4) {
1413 *newip = newip4;
1414 *newip_sin_family = AF_INET;
1415 }
1416 if (!currentip_found)
1417 goto not_found;
1418 }
1419 /* Case when the caller have no preference (we prefer IPv6) */
1420 else if (family_priority == AF_UNSPEC) {
1421 if (newip6) {
1422 *newip = newip6;
1423 *newip_sin_family = AF_INET6;
1424 }
1425 else if (newip4) {
1426 *newip = newip4;
1427 *newip_sin_family = AF_INET;
1428 }
1429 if (!currentip_found)
1430 goto not_found;
1431 }
1432
1433 /* No reason why we should change the server's IP address */
1434 return RSLV_UPD_NO;
1435
1436 not_found:
1437 list_for_each_entry(record, &r_res->answer_list, list) {
1438 /* Move the first record to the end of the list, for internal
1439 * round robin */
1440 LIST_DEL(&record->list);
1441 LIST_ADDQ(&r_res->answer_list, &record->list);
1442 break;
1443 }
1444 return RSLV_UPD_SRVIP_NOT_FOUND;
1445}
1446
1447/* Turns a domain name label into a string.
1448 *
1449 * <dn> must be a null-terminated string. <dn_len> must include the terminating
1450 * null byte. <str> must be allocated and its size must be passed in <str_len>.
1451 *
1452 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1453 * <str> (including the terminating null byte).
1454 */
1455int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
1456{
1457 char *ptr;
1458 int i, sz;
1459
1460 if (str_len < dn_len - 1)
1461 return -1;
1462
1463 ptr = str;
1464 for (i = 0; i < dn_len-1; ++i) {
1465 sz = dn[i];
1466 if (i)
1467 *ptr++ = '.';
1468 memcpy(ptr, dn+i+1, sz);
1469 ptr += sz;
1470 i += sz;
1471 }
1472 *ptr++ = '\0';
1473 return (ptr - str);
1474}
1475
1476/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
1477 *
1478 * <str> must be a null-terminated string. <str_len> must include the
1479 * terminating null byte. <dn> buffer must be allocated and its size must be
1480 * passed in <dn_len>.
1481 *
1482 * In case of error, -1 is returned, otherwise, the number of bytes copied in
1483 * <dn> (excluding the terminating null byte).
1484 */
1485int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
1486{
1487 int i, offset;
1488
1489 if (dn_len < str_len + 1)
1490 return -1;
1491
1492 /* First byte of dn will be used to store the length of the first
1493 * label */
1494 offset = 0;
1495 for (i = 0; i < str_len; ++i) {
1496 if (str[i] == '.') {
1497 /* 2 or more consecutive dots is invalid */
1498 if (i == offset)
1499 return -1;
1500
1501 /* ignore trailing dot */
1502 if (i + 2 == str_len) {
1503 i++;
1504 break;
1505 }
1506
1507 dn[offset] = (i - offset);
1508 offset = i+1;
1509 continue;
1510 }
1511 dn[i+1] = str[i];
1512 }
1513 dn[offset] = (i - offset - 1);
1514 dn[i] = '\0';
1515 return i;
1516}
1517
1518/* Validates host name:
1519 * - total size
1520 * - each label size individually
1521 * returns:
1522 * 0 in case of error. If <err> is not NULL, an error message is stored there.
1523 * 1 when no error. <err> is left unaffected.
1524 */
1525int resolv_hostname_validation(const char *string, char **err)
1526{
1527 int i;
1528
1529 if (strlen(string) > DNS_MAX_NAME_SIZE) {
1530 if (err)
1531 *err = DNS_TOO_LONG_FQDN;
1532 return 0;
1533 }
1534
1535 while (*string) {
1536 i = 0;
1537 while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
1538 if (!(*string == '-' || *string == '_' ||
1539 (*string >= 'a' && *string <= 'z') ||
1540 (*string >= 'A' && *string <= 'Z') ||
1541 (*string >= '0' && *string <= '9'))) {
1542 if (err)
1543 *err = DNS_INVALID_CHARACTER;
1544 return 0;
1545 }
1546 i++;
1547 string++;
1548 }
1549
1550 if (!(*string))
1551 break;
1552
1553 if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
1554 if (err)
1555 *err = DNS_LABEL_TOO_LONG;
1556 return 0;
1557 }
1558
1559 string++;
1560 }
1561 return 1;
1562}
1563
1564/* Picks up an available resolution from the different resolution list
1565 * associated to a resolvers section, in this order:
1566 * 1. check in resolutions.curr for the same hostname and query_type
1567 * 2. check in resolutions.wait for the same hostname and query_type
1568 * 3. Get a new resolution from resolution pool
1569 *
1570 * Returns an available resolution, NULL if none found.
1571 */
1572static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
1573 char **hostname_dn, int hostname_dn_len,
1574 int query_type)
1575{
1576 struct resolv_resolution *res;
1577
1578 if (!*hostname_dn)
1579 goto from_pool;
1580
1581 /* Search for same hostname and query type in resolutions.curr */
1582 list_for_each_entry(res, &resolvers->resolutions.curr, list) {
1583 if (!res->hostname_dn)
1584 continue;
1585 if ((query_type == res->prefered_query_type) &&
1586 hostname_dn_len == res->hostname_dn_len &&
1587 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1588 return res;
1589 }
1590
1591 /* Search for same hostname and query type in resolutions.wait */
1592 list_for_each_entry(res, &resolvers->resolutions.wait, list) {
1593 if (!res->hostname_dn)
1594 continue;
1595 if ((query_type == res->prefered_query_type) &&
1596 hostname_dn_len == res->hostname_dn_len &&
1597 !resolv_hostname_cmp(*hostname_dn, res->hostname_dn, hostname_dn_len))
1598 return res;
1599 }
1600
1601 from_pool:
1602 /* No resolution could be found, so let's allocate a new one */
1603 res = pool_alloc(resolv_resolution_pool);
1604 if (res) {
1605 memset(res, 0, sizeof(*res));
1606 res->resolvers = resolvers;
1607 res->uuid = resolution_uuid;
1608 res->status = RSLV_STATUS_NONE;
1609 res->step = RSLV_STEP_NONE;
1610 res->last_valid = now_ms;
1611
1612 LIST_INIT(&res->requesters);
1613 LIST_INIT(&res->response.answer_list);
1614
1615 res->prefered_query_type = query_type;
1616 res->query_type = query_type;
1617 res->hostname_dn = *hostname_dn;
1618 res->hostname_dn_len = hostname_dn_len;
1619
1620 ++resolution_uuid;
1621
1622 /* Move the resolution to the resolvers wait queue */
1623 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
1624 }
1625 return res;
1626}
1627
1628/* Releases a resolution from its requester(s) and move it back to the pool */
1629static void resolv_free_resolution(struct resolv_resolution *resolution)
1630{
1631 struct resolv_requester *req, *reqback;
1632 struct resolv_answer_item *item, *itemback;
1633
1634 /* clean up configuration */
1635 resolv_reset_resolution(resolution);
1636 resolution->hostname_dn = NULL;
1637 resolution->hostname_dn_len = 0;
1638
1639 list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
1640 LIST_DEL(&req->list);
1641 req->resolution = NULL;
1642 }
1643
1644 list_for_each_entry_safe(item, itemback, &resolution->response.answer_list, list) {
1645 LIST_DEL(&item->list);
1646 if (item->ar_item) {
1647 pool_free(resolv_answer_item_pool, item->ar_item);
1648 item->ar_item = NULL;
1649 }
1650 pool_free(resolv_answer_item_pool, item);
1651 }
1652
1653 LIST_DEL(&resolution->list);
1654 pool_free(resolv_resolution_pool, resolution);
1655}
1656
1657/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
1658 * on success, -1 otherwise.
1659 */
1660int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
1661{
1662 struct resolv_resolution *res = NULL;
1663 struct resolv_requester *req;
1664 struct resolvers *resolvers;
1665 struct server *srv = NULL;
1666 struct resolv_srvrq *srvrq = NULL;
1667 struct stream *stream = NULL;
1668 char **hostname_dn;
1669 int hostname_dn_len, query_type;
1670
1671 switch (requester_type) {
1672 case OBJ_TYPE_SERVER:
1673 srv = (struct server *)requester;
1674 hostname_dn = &srv->hostname_dn;
1675 hostname_dn_len = srv->hostname_dn_len;
1676 resolvers = srv->resolvers;
1677 query_type = ((srv->resolv_opts.family_prio == AF_INET)
1678 ? DNS_RTYPE_A
1679 : DNS_RTYPE_AAAA);
1680 break;
1681
1682 case OBJ_TYPE_SRVRQ:
1683 srvrq = (struct resolv_srvrq *)requester;
1684 hostname_dn = &srvrq->hostname_dn;
1685 hostname_dn_len = srvrq->hostname_dn_len;
1686 resolvers = srvrq->resolvers;
1687 query_type = DNS_RTYPE_SRV;
1688 break;
1689
1690 case OBJ_TYPE_STREAM:
1691 stream = (struct stream *)requester;
1692 hostname_dn = &stream->resolv_ctx.hostname_dn;
1693 hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
1694 resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
1695 query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
1696 ? DNS_RTYPE_A
1697 : DNS_RTYPE_AAAA);
1698 break;
1699 default:
1700 goto err;
1701 }
1702
1703 /* Get a resolution from the resolvers' wait queue or pool */
1704 if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
1705 goto err;
1706
1707 if (srv) {
1708 if (!requester_locked)
1709 HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
1710 if (srv->resolv_requester == NULL) {
1711 if ((req = pool_alloc(resolv_requester_pool)) == NULL) {
1712 if (!requester_locked)
1713 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1714 goto err;
1715 }
1716 req->owner = &srv->obj_type;
1717 srv->resolv_requester = req;
1718 }
1719 else
1720 req = srv->resolv_requester;
1721 if (!requester_locked)
1722 HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
1723
1724 req->requester_cb = snr_resolution_cb;
1725 req->requester_error_cb = snr_resolution_error_cb;
1726 }
1727 else if (srvrq) {
1728 if (srvrq->requester == NULL) {
1729 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1730 goto err;
1731 req->owner = &srvrq->obj_type;
1732 srvrq->requester = req;
1733 }
1734 else
1735 req = srvrq->requester;
1736
1737 req->requester_cb = snr_resolution_cb;
1738 req->requester_error_cb = snr_resolution_error_cb;
1739 }
1740 else if (stream) {
1741 if (stream->resolv_ctx.requester == NULL) {
1742 if ((req = pool_alloc(resolv_requester_pool)) == NULL)
1743 goto err;
1744 req->owner = &stream->obj_type;
1745 stream->resolv_ctx.requester = req;
1746 }
1747 else
1748 req = stream->resolv_ctx.requester;
1749
1750 req->requester_cb = act_resolution_cb;
1751 req->requester_error_cb = act_resolution_error_cb;
1752 }
1753 else
1754 goto err;
1755
1756 req->resolution = res;
1757
1758 LIST_ADDQ(&res->requesters, &req->list);
1759 return 0;
1760
1761 err:
1762 if (res && LIST_ISEMPTY(&res->requesters))
1763 resolv_free_resolution(res);
1764 return -1;
1765}
1766
1767/* Removes a requester from a DNS resolution. It takes takes care of all the
1768 * consequences. It also cleans up some parameters from the requester.
1769 */
1770void resolv_unlink_resolution(struct resolv_requester *requester)
1771{
1772 struct resolv_resolution *res;
1773 struct resolv_requester *req;
1774
1775 /* Nothing to do */
1776 if (!requester || !requester->resolution)
1777 return;
1778 res = requester->resolution;
1779
1780 /* Clean up the requester */
1781 LIST_DEL(&requester->list);
1782 requester->resolution = NULL;
1783
1784 /* We need to find another requester linked on this resolution */
1785 if (!LIST_ISEMPTY(&res->requesters))
1786 req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
1787 else {
1788 resolv_free_resolution(res);
1789 return;
1790 }
1791
1792 /* Move hostname_dn related pointers to the next requester */
1793 switch (obj_type(req->owner)) {
1794 case OBJ_TYPE_SERVER:
1795 res->hostname_dn = __objt_server(req->owner)->hostname_dn;
1796 res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
1797 break;
1798 case OBJ_TYPE_SRVRQ:
1799 res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
1800 res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
1801 break;
1802 case OBJ_TYPE_STREAM:
1803 res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
1804 res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
1805 break;
1806 default:
1807 res->hostname_dn = NULL;
1808 res->hostname_dn_len = 0;
1809 break;
1810 }
1811}
1812
1813/* Called when a network IO is generated on a name server socket for an incoming
1814 * packet. It performs the following actions:
1815 * - check if the packet requires processing (not outdated resolution)
1816 * - ensure the DNS packet received is valid and call requester's callback
1817 * - call requester's error callback if invalid response
1818 * - check the dn_name in the packet against the one sent
1819 */
1820static int resolv_process_responses(struct dns_nameserver *ns)
1821{
1822 struct dns_counters *tmpcounters;
1823 struct resolvers *resolvers;
1824 struct resolv_resolution *res;
1825 struct resolv_query_item *query;
1826 unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
1827 unsigned char *bufend;
1828 int buflen, dns_resp;
1829 int max_answer_records;
1830 unsigned short query_id;
1831 struct eb32_node *eb;
1832 struct resolv_requester *req;
1833
1834 resolvers = ns->parent;
1835 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
1836
1837 /* process all pending input messages */
1838 while (1) {
1839 /* read message received */
1840 memset(buf, '\0', resolvers->accepted_payload_size + 1);
1841 if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
1842 break;
1843 }
1844
1845 /* message too big */
1846 if (buflen > resolvers->accepted_payload_size) {
1847 ns->counters->too_big++;
1848 continue;
1849 }
1850
1851 /* initializing variables */
1852 bufend = buf + buflen; /* pointer to mark the end of the buffer */
1853
1854 /* read the query id from the packet (16 bits) */
1855 if (buf + 2 > bufend) {
1856 ns->counters->invalid++;
1857 continue;
1858 }
1859 query_id = resolv_response_get_query_id(buf);
1860
1861 /* search the query_id in the pending resolution tree */
1862 eb = eb32_lookup(&resolvers->query_ids, query_id);
1863 if (eb == NULL) {
1864 /* unknown query id means an outdated response and can be safely ignored */
1865 ns->counters->outdated++;
1866 continue;
1867 }
1868
1869 /* known query id means a resolution in progress */
1870 res = eb32_entry(eb, struct resolv_resolution, qid);
1871 /* number of responses received */
1872 res->nb_responses++;
1873
1874 max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
1875 dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
1876
1877 switch (dns_resp) {
1878 case RSLV_RESP_VALID:
1879 break;
1880
1881 case RSLV_RESP_INVALID:
1882 case RSLV_RESP_QUERY_COUNT_ERROR:
1883 case RSLV_RESP_WRONG_NAME:
1884 res->status = RSLV_STATUS_INVALID;
1885 ns->counters->invalid++;
1886 break;
1887
1888 case RSLV_RESP_NX_DOMAIN:
1889 res->status = RSLV_STATUS_NX;
1890 ns->counters->nx++;
1891 break;
1892
1893 case RSLV_RESP_REFUSED:
1894 res->status = RSLV_STATUS_REFUSED;
1895 ns->counters->refused++;
1896 break;
1897
1898 case RSLV_RESP_ANCOUNT_ZERO:
1899 res->status = RSLV_STATUS_OTHER;
1900 ns->counters->any_err++;
1901 break;
1902
1903 case RSLV_RESP_CNAME_ERROR:
1904 res->status = RSLV_STATUS_OTHER;
1905 ns->counters->cname_error++;
1906 break;
1907
1908 case RSLV_RESP_TRUNCATED:
1909 res->status = RSLV_STATUS_OTHER;
1910 ns->counters->truncated++;
1911 break;
1912
1913 case RSLV_RESP_NO_EXPECTED_RECORD:
1914 case RSLV_RESP_ERROR:
1915 case RSLV_RESP_INTERNAL:
1916 res->status = RSLV_STATUS_OTHER;
1917 ns->counters->other++;
1918 break;
1919 }
1920
1921 /* Wait all nameservers response to handle errors */
1922 if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
1923 continue;
1924
1925 /* Process error codes */
1926 if (dns_resp != RSLV_RESP_VALID) {
1927 if (res->prefered_query_type != res->query_type) {
1928 /* The fallback on the query type was already performed,
1929 * so check the try counter. If it falls to 0, we can
1930 * report an error. Else, wait the next attempt. */
1931 if (!res->try)
1932 goto report_res_error;
1933 }
1934 else {
1935 /* Fallback from A to AAAA or the opposite and re-send
1936 * the resolution immediately. try counter is not
1937 * decremented. */
1938 if (res->prefered_query_type == DNS_RTYPE_A) {
1939 res->query_type = DNS_RTYPE_AAAA;
1940 resolv_send_query(res);
1941 }
1942 else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
1943 res->query_type = DNS_RTYPE_A;
1944 resolv_send_query(res);
1945 }
1946 }
1947 continue;
1948 }
1949
1950 /* Now let's check the query's dname corresponds to the one we
1951 * sent. We can check only the first query of the list. We send
1952 * one query at a time so we get one query in the response */
1953 query = LIST_NEXT(&res->response.query_list, struct resolv_query_item *, list);
1954 if (query && resolv_hostname_cmp(query->name, res->hostname_dn, res->hostname_dn_len) != 0) {
1955 dns_resp = RSLV_RESP_WRONG_NAME;
1956 ns->counters->other++;
1957 goto report_res_error;
1958 }
1959
1960 /* So the resolution succeeded */
1961 res->status = RSLV_STATUS_VALID;
1962 res->last_valid = now_ms;
1963 ns->counters->valid++;
1964 goto report_res_success;
1965
1966 report_res_error:
1967 list_for_each_entry(req, &res->requesters, list)
1968 req->requester_error_cb(req, dns_resp);
1969 resolv_reset_resolution(res);
1970 LIST_DEL(&res->list);
1971 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
1972 continue;
1973
1974 report_res_success:
1975 /* Only the 1rst requester s managed by the server, others are
1976 * from the cache */
1977 tmpcounters = ns->counters;
1978 list_for_each_entry(req, &res->requesters, list) {
1979 struct server *s = objt_server(req->owner);
1980
1981 if (s)
1982 HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
1983 req->requester_cb(req, tmpcounters);
1984 if (s)
1985 HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
1986 tmpcounters = NULL;
1987 }
1988
1989 resolv_reset_resolution(res);
1990 LIST_DEL(&res->list);
1991 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
1992 continue;
1993 }
1994 resolv_update_resolvers_timeout(resolvers);
1995 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
1996
1997 return buflen;
1998}
1999
2000/* Processes DNS resolution. First, it checks the active list to detect expired
2001 * resolutions and retry them if possible. Else a timeout is reported. Then, it
2002 * checks the wait list to trigger new resolutions.
2003 */
2004static struct task *process_resolvers(struct task *t, void *context, unsigned short state)
2005{
2006 struct resolvers *resolvers = context;
2007 struct resolv_resolution *res, *resback;
2008 int exp;
2009
2010 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2011
2012 /* Handle all expired resolutions from the active list */
2013 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2014 /* When we find the first resolution in the future, then we can
2015 * stop here */
2016 exp = tick_add(res->last_query, resolvers->timeout.retry);
2017 if (!tick_is_expired(exp, now_ms))
2018 break;
2019
2020 /* If current resolution has been tried too many times and
2021 * finishes in timeout we update its status and remove it from
2022 * the list */
2023 if (!res->try) {
2024 struct resolv_requester *req;
2025
2026 /* Notify the result to the requesters */
2027 if (!res->nb_responses)
2028 res->status = RSLV_STATUS_TIMEOUT;
2029 list_for_each_entry(req, &res->requesters, list)
2030 req->requester_error_cb(req, res->status);
2031
2032 /* Clean up resolution info and remove it from the
2033 * current list */
2034 resolv_reset_resolution(res);
2035 LIST_DEL(&res->list);
2036 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2037 }
2038 else {
2039 /* Otherwise resend the DNS query and requeue the resolution */
2040 if (!res->nb_responses || res->prefered_query_type != res->query_type) {
2041 /* No response received (a real timeout) or fallback already done */
2042 res->query_type = res->prefered_query_type;
2043 res->try--;
2044 }
2045 else {
2046 /* Fallback from A to AAAA or the opposite and re-send
2047 * the resolution immediately. try counter is not
2048 * decremented. */
2049 if (res->prefered_query_type == DNS_RTYPE_A)
2050 res->query_type = DNS_RTYPE_AAAA;
2051 else if (res->prefered_query_type == DNS_RTYPE_AAAA)
2052 res->query_type = DNS_RTYPE_A;
2053 else
2054 res->try--;
2055 }
2056 resolv_send_query(res);
2057 }
2058 }
2059
2060 /* Handle all resolutions in the wait list */
2061 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2062 exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
2063 if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
2064 continue;
2065
2066 if (resolv_run_resolution(res) != 1) {
2067 res->last_resolution = now_ms;
2068 LIST_DEL(&res->list);
2069 LIST_ADDQ(&resolvers->resolutions.wait, &res->list);
2070 }
2071 }
2072
2073 resolv_update_resolvers_timeout(resolvers);
2074 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2075 return t;
2076}
2077
2078/* Release memory allocated by DNS */
2079static void resolvers_deinit(void)
2080{
2081 struct resolvers *resolvers, *resolversback;
2082 struct dns_nameserver *ns, *nsback;
2083 struct resolv_resolution *res, *resback;
2084 struct resolv_requester *req, *reqback;
2085 struct resolv_srvrq *srvrq, *srvrqback;
2086
2087 list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
2088 list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
2089 free(ns->id);
2090 free((char *)ns->conf.file);
2091 if (ns->dgram) {
2092 if (ns->dgram->conn.t.sock.fd != -1) {
2093 fd_delete(ns->dgram->conn.t.sock.fd);
2094 close(ns->dgram->conn.t.sock.fd);
2095 }
2096 if (ns->dgram->ring_req)
2097 ring_free(ns->dgram->ring_req);
2098 free(ns->dgram);
2099 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002100 if (ns->stream) {
2101 if (ns->stream->ring_req)
2102 ring_free(ns->stream->ring_req);
2103 if (ns->stream->task_req)
2104 task_destroy(ns->stream->task_req);
2105 if (ns->stream->task_rsp)
2106 task_destroy(ns->stream->task_rsp);
2107 free(ns->stream);
2108 }
Emeric Brunc9437992021-02-12 19:42:55 +01002109 LIST_DEL(&ns->list);
2110 EXTRA_COUNTERS_FREE(ns->extra_counters);
2111 free(ns);
2112 }
2113
2114 list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
2115 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2116 LIST_DEL(&req->list);
2117 pool_free(resolv_requester_pool, req);
2118 }
2119 resolv_free_resolution(res);
2120 }
2121
2122 list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
2123 list_for_each_entry_safe(req, reqback, &res->requesters, list) {
2124 LIST_DEL(&req->list);
2125 pool_free(resolv_requester_pool, req);
2126 }
2127 resolv_free_resolution(res);
2128 }
2129
2130 free(resolvers->id);
2131 free((char *)resolvers->conf.file);
2132 task_destroy(resolvers->t);
2133 LIST_DEL(&resolvers->list);
2134 free(resolvers);
2135 }
2136
2137 list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
2138 free(srvrq->name);
2139 free(srvrq->hostname_dn);
2140 LIST_DEL(&srvrq->list);
2141 free(srvrq);
2142 }
2143}
2144
2145/* Finalizes the DNS configuration by allocating required resources and checking
2146 * live parameters.
2147 * Returns 0 on success, ERR_* flags otherwise.
2148 */
2149static int resolvers_finalize_config(void)
2150{
2151 struct resolvers *resolvers;
2152 struct proxy *px;
2153 int err_code = 0;
2154
2155 /* allocate pool of resolution per resolvers */
2156 list_for_each_entry(resolvers, &sec_resolvers, list) {
2157 struct dns_nameserver *ns;
2158 struct task *t;
2159
2160 /* Check if we can create the socket with nameservers info */
2161 list_for_each_entry(ns, &resolvers->nameservers, list) {
2162 int fd;
2163
2164 if (ns->dgram) {
2165 /* Check nameserver info */
2166 if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
2167 ha_alert("config : resolvers '%s': can't create socket for nameserver '%s'.\n",
2168 resolvers->id, ns->id);
2169 err_code |= (ERR_ALERT|ERR_ABORT);
2170 continue;
2171 }
2172 if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
2173 ha_alert("config : resolvers '%s': can't connect socket for nameserver '%s'.\n",
2174 resolvers->id, ns->id);
2175 close(fd);
2176 err_code |= (ERR_ALERT|ERR_ABORT);
2177 continue;
2178 }
2179 close(fd);
2180 }
2181 }
2182
2183 /* Create the task associated to the resolvers section */
2184 if ((t = task_new(MAX_THREADS_MASK)) == NULL) {
2185 ha_alert("config : resolvers '%s' : out of memory.\n", resolvers->id);
2186 err_code |= (ERR_ALERT|ERR_ABORT);
2187 goto err;
2188 }
2189
2190 /* Update task's parameters */
2191 t->process = process_resolvers;
2192 t->context = resolvers;
2193 resolvers->t = t;
2194 task_wakeup(t, TASK_WOKEN_INIT);
2195 }
2196
2197 for (px = proxies_list; px; px = px->next) {
2198 struct server *srv;
2199
2200 for (srv = px->srv; srv; srv = srv->next) {
2201 struct resolvers *resolvers;
2202
2203 if (!srv->resolvers_id)
2204 continue;
2205
2206 if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
2207 ha_alert("config : %s '%s', server '%s': unable to find required resolvers '%s'\n",
2208 proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
2209 err_code |= (ERR_ALERT|ERR_ABORT);
2210 continue;
2211 }
2212 srv->resolvers = resolvers;
2213
2214 if (srv->srvrq && !srv->srvrq->resolvers) {
2215 srv->srvrq->resolvers = srv->resolvers;
2216 if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
2217 ha_alert("config : %s '%s' : unable to set DNS resolution for server '%s'.\n",
2218 proxy_type_str(px), px->id, srv->id);
2219 err_code |= (ERR_ALERT|ERR_ABORT);
2220 continue;
2221 }
2222 }
2223 if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
2224 ha_alert("config : %s '%s', unable to set DNS resolution for server '%s'.\n",
2225 proxy_type_str(px), px->id, srv->id);
2226 err_code |= (ERR_ALERT|ERR_ABORT);
2227 continue;
2228 }
2229 }
2230 }
2231
2232 if (err_code & (ERR_ALERT|ERR_ABORT))
2233 goto err;
2234
2235 return err_code;
2236 err:
2237 resolvers_deinit();
2238 return err_code;
2239
2240}
2241
2242static int stats_dump_resolv_to_buffer(struct stream_interface *si,
2243 struct dns_nameserver *ns,
2244 struct field *stats, size_t stats_count,
2245 struct list *stat_modules)
2246{
2247 struct appctx *appctx = __objt_appctx(si->end);
2248 struct channel *rep = si_ic(si);
2249 struct stats_module *mod;
2250 size_t idx = 0;
2251
2252 memset(stats, 0, sizeof(struct field) * stats_count);
2253
2254 list_for_each_entry(mod, stat_modules, list) {
2255 struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2256
2257 mod->fill_stats(counters, stats + idx);
2258 idx += mod->stats_count;
2259 }
2260
2261 if (!stats_dump_one_line(stats, idx, appctx))
2262 return 0;
2263
2264 if (!stats_putchk(rep, NULL, &trash))
2265 goto full;
2266
2267 return 1;
2268
2269 full:
2270 si_rx_room_rdy(si);
2271 return 0;
2272}
2273
2274/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
2275 * as a pointer to the current nameserver.
2276 */
2277int stats_dump_resolvers(struct stream_interface *si,
2278 struct field *stats, size_t stats_count,
2279 struct list *stat_modules)
2280{
2281 struct appctx *appctx = __objt_appctx(si->end);
2282 struct channel *rep = si_ic(si);
2283 struct resolvers *resolver = appctx->ctx.stats.obj1;
2284 struct dns_nameserver *ns = appctx->ctx.stats.obj2;
2285
2286 if (!resolver)
2287 resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
2288
2289 /* dump resolvers */
2290 list_for_each_entry_from(resolver, &sec_resolvers, list) {
2291 appctx->ctx.stats.obj1 = resolver;
2292
2293 ns = appctx->ctx.stats.obj2 ?
2294 appctx->ctx.stats.obj2 :
2295 LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
2296
2297 list_for_each_entry_from(ns, &resolver->nameservers, list) {
2298 appctx->ctx.stats.obj2 = ns;
2299
2300 if (buffer_almost_full(&rep->buf))
2301 goto full;
2302
2303 if (!stats_dump_resolv_to_buffer(si, ns,
2304 stats, stats_count,
2305 stat_modules)) {
2306 return 0;
2307 }
2308 }
2309
2310 appctx->ctx.stats.obj2 = NULL;
2311 }
2312
2313 return 1;
2314
2315 full:
2316 si_rx_room_blk(si);
2317 return 0;
2318}
2319
2320void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
2321{
2322 struct resolvers *resolvers;
2323 struct dns_nameserver *ns;
2324 struct stats_module *mod;
2325 void *counters;
2326
2327 list_for_each_entry(mod, stat_modules, list) {
2328 if (!mod->clearable && !clrall)
2329 continue;
2330
2331 list_for_each_entry(resolvers, &sec_resolvers, list) {
2332 list_for_each_entry(ns, &resolvers->nameservers, list) {
2333 counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
2334 memcpy(counters, mod->counters, mod->counters_size);
2335 }
2336 }
2337 }
2338
2339}
2340
2341int resolv_allocate_counters(struct list *stat_modules)
2342{
2343 struct stats_module *mod;
2344 struct resolvers *resolvers;
2345 struct dns_nameserver *ns;
2346
2347 list_for_each_entry(resolvers, &sec_resolvers, list) {
2348 list_for_each_entry(ns, &resolvers->nameservers, list) {
2349 EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_DNS,
2350 alloc_failed);
2351
2352 list_for_each_entry(mod, stat_modules, list) {
2353 EXTRA_COUNTERS_ADD(mod,
2354 ns->extra_counters,
2355 mod->counters,
2356 mod->counters_size);
2357 }
2358
2359 EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
2360
2361 list_for_each_entry(mod, stat_modules, list) {
2362 memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
2363 mod->counters, mod->counters_size);
2364
2365 /* Store the ns counters pointer */
2366 if (strcmp(mod->name, "dns") == 0) {
2367 ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_DNS];
2368 ns->counters->id = ns->id;
2369 ns->counters->pid = resolvers->id;
2370 }
2371 }
2372 }
2373 }
2374
2375 return 1;
2376
2377alloc_failed:
2378 return 0;
2379}
2380
2381/* if an arg is found, it sets the resolvers section pointer into cli.p0 */
2382static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
2383{
2384 struct resolvers *presolvers;
2385
2386 if (*args[2]) {
2387 list_for_each_entry(presolvers, &sec_resolvers, list) {
2388 if (strcmp(presolvers->id, args[2]) == 0) {
2389 appctx->ctx.cli.p0 = presolvers;
2390 break;
2391 }
2392 }
2393 if (appctx->ctx.cli.p0 == NULL)
2394 return cli_err(appctx, "Can't find that resolvers section\n");
2395 }
2396 return 0;
2397}
2398
2399/* Dumps counters from all resolvers section and associated name servers. It
2400 * returns 0 if the output buffer is full and it needs to be called again,
2401 * otherwise non-zero. It may limit itself to the resolver pointed to by
2402 * <cli.p0> if it's not null.
2403 */
2404static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
2405{
2406 struct stream_interface *si = appctx->owner;
2407 struct resolvers *resolvers;
2408 struct dns_nameserver *ns;
2409
2410 chunk_reset(&trash);
2411
2412 switch (appctx->st2) {
2413 case STAT_ST_INIT:
2414 appctx->st2 = STAT_ST_LIST; /* let's start producing data */
2415 /* fall through */
2416
2417 case STAT_ST_LIST:
2418 if (LIST_ISEMPTY(&sec_resolvers)) {
2419 chunk_appendf(&trash, "No resolvers found\n");
2420 }
2421 else {
2422 list_for_each_entry(resolvers, &sec_resolvers, list) {
2423 if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers)
2424 continue;
2425
2426 chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id);
2427 list_for_each_entry(ns, &resolvers->nameservers, list) {
2428 chunk_appendf(&trash, " nameserver %s:\n", ns->id);
2429 chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
2430 chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
2431 chunk_appendf(&trash, " valid: %lld\n", ns->counters->valid);
2432 chunk_appendf(&trash, " update: %lld\n", ns->counters->update);
2433 chunk_appendf(&trash, " cname: %lld\n", ns->counters->cname);
2434 chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->cname_error);
2435 chunk_appendf(&trash, " any_err: %lld\n", ns->counters->any_err);
2436 chunk_appendf(&trash, " nx: %lld\n", ns->counters->nx);
2437 chunk_appendf(&trash, " timeout: %lld\n", ns->counters->timeout);
2438 chunk_appendf(&trash, " refused: %lld\n", ns->counters->refused);
2439 chunk_appendf(&trash, " other: %lld\n", ns->counters->other);
2440 chunk_appendf(&trash, " invalid: %lld\n", ns->counters->invalid);
2441 chunk_appendf(&trash, " too_big: %lld\n", ns->counters->too_big);
2442 chunk_appendf(&trash, " truncated: %lld\n", ns->counters->truncated);
2443 chunk_appendf(&trash, " outdated: %lld\n", ns->counters->outdated);
2444 }
2445 chunk_appendf(&trash, "\n");
2446 }
2447 }
2448
2449 /* display response */
2450 if (ci_putchk(si_ic(si), &trash) == -1) {
2451 /* let's try again later from this session. We add ourselves into
2452 * this session's users so that it can remove us upon termination.
2453 */
2454 si_rx_room_blk(si);
2455 return 0;
2456 }
2457 /* fall through */
2458
2459 default:
2460 appctx->st2 = STAT_ST_FIN;
2461 return 1;
2462 }
2463}
2464
2465/* register cli keywords */
2466static struct cli_kw_list cli_kws = {{ }, {
2467 { { "show", "resolvers", NULL }, "show resolvers [id]: dumps counters from all resolvers section and\n"
2468 " associated name servers",
2469 cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
2470 {{},}
2471 }
2472};
2473
2474INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
2475
2476/*
2477 * Prepare <rule> for hostname resolution.
2478 * Returns -1 in case of any allocation failure, 0 if not.
2479 * On error, a global failure counter is also incremented.
2480 */
2481static int action_prepare_for_resolution(struct stream *stream, const char *hostname)
2482{
2483 char *hostname_dn;
2484 int hostname_len, hostname_dn_len;
2485 struct buffer *tmp = get_trash_chunk();
2486
2487 if (!hostname)
2488 return 0;
2489
2490 hostname_len = strlen(hostname);
2491 hostname_dn = tmp->area;
2492 hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len + 1,
2493 hostname_dn, tmp->size);
2494 if (hostname_dn_len == -1)
2495 goto err;
2496
2497
2498 stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
2499 stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
2500 if (!stream->resolv_ctx.hostname_dn)
2501 goto err;
2502
2503 return 0;
2504
2505 err:
2506 free(stream->resolv_ctx.hostname_dn); stream->resolv_ctx.hostname_dn = NULL;
2507 resolv_failed_resolutions += 1;
2508 return -1;
2509}
2510
2511
2512/*
2513 * Execute the "do-resolution" action. May be called from {tcp,http}request.
2514 */
2515enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
2516 struct session *sess, struct stream *s, int flags)
2517{
2518 struct resolv_resolution *resolution;
2519 struct sample *smp;
2520 char *fqdn;
2521 struct resolv_requester *req;
2522 struct resolvers *resolvers;
2523 struct resolv_resolution *res;
2524 int exp, locked = 0;
2525 enum act_return ret = ACT_RET_CONT;
2526
2527 resolvers = rule->arg.resolv.resolvers;
2528
2529 /* we have a response to our DNS resolution */
2530 use_cache:
2531 if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
2532 resolution = s->resolv_ctx.requester->resolution;
2533 if (!locked) {
2534 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2535 locked = 1;
2536 }
2537
2538 if (resolution->step == RSLV_STEP_RUNNING)
2539 goto yield;
2540 if (resolution->step == RSLV_STEP_NONE) {
2541 /* We update the variable only if we have a valid response. */
2542 if (resolution->status == RSLV_STATUS_VALID) {
2543 struct sample smp;
2544 short ip_sin_family = 0;
2545 void *ip = NULL;
2546
2547 resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
2548 0, &ip, &ip_sin_family, NULL);
2549
2550 switch (ip_sin_family) {
2551 case AF_INET:
2552 smp.data.type = SMP_T_IPV4;
2553 memcpy(&smp.data.u.ipv4, ip, 4);
2554 break;
2555 case AF_INET6:
2556 smp.data.type = SMP_T_IPV6;
2557 memcpy(&smp.data.u.ipv6, ip, 16);
2558 break;
2559 default:
2560 ip = NULL;
2561 }
2562
2563 if (ip) {
2564 smp.px = px;
2565 smp.sess = sess;
2566 smp.strm = s;
2567
2568 vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
2569 }
2570 }
2571 }
2572
2573 goto release_requester;
2574 }
2575
2576 /* need to configure and start a new DNS resolution */
2577 smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
2578 if (smp == NULL)
2579 goto end;
2580
2581 fqdn = smp->data.u.str.area;
2582 if (action_prepare_for_resolution(s, fqdn) == -1)
2583 goto end; /* on error, ignore the action */
2584
2585 s->resolv_ctx.parent = rule;
2586
2587 HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
2588 locked = 1;
2589
2590 resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
2591
2592 /* Check if there is a fresh enough response in the cache of our associated resolution */
2593 req = s->resolv_ctx.requester;
2594 if (!req || !req->resolution)
2595 goto release_requester; /* on error, ignore the action */
2596 res = req->resolution;
2597
2598 exp = tick_add(res->last_resolution, resolvers->hold.valid);
2599 if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
2600 && !tick_is_expired(exp, now_ms)) {
2601 goto use_cache;
2602 }
2603
2604 resolv_trigger_resolution(s->resolv_ctx.requester);
2605
2606 yield:
2607 if (flags & ACT_OPT_FINAL)
2608 goto release_requester;
2609 ret = ACT_RET_YIELD;
2610
2611 end:
2612 if (locked)
2613 HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
2614 return ret;
2615
2616 release_requester:
2617 free(s->resolv_ctx.hostname_dn);
2618 s->resolv_ctx.hostname_dn = NULL;
2619 s->resolv_ctx.hostname_dn_len = 0;
2620 if (s->resolv_ctx.requester) {
2621 resolv_unlink_resolution(s->resolv_ctx.requester);
2622 pool_free(resolv_requester_pool, s->resolv_ctx.requester);
2623 s->resolv_ctx.requester = NULL;
2624 }
2625 goto end;
2626}
2627
2628static void release_resolv_action(struct act_rule *rule)
2629{
2630 release_sample_expr(rule->arg.resolv.expr);
2631 free(rule->arg.resolv.varname);
2632 free(rule->arg.resolv.resolvers_id);
2633 free(rule->arg.resolv.opts);
2634}
2635
2636
2637/* parse "do-resolve" action
2638 * This action takes the following arguments:
2639 * do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
2640 *
2641 * - <varName> is the variable name where the result of the DNS resolution will be stored
2642 * (mandatory)
2643 * - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
2644 * (mandatory)
2645 * - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
2646 * (optional), defaults to ipv6
2647 * - <expr> is an HAProxy expression used to fetch the name to be resolved
2648 */
2649enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
2650{
2651 int cur_arg;
2652 struct sample_expr *expr;
2653 unsigned int where;
2654 const char *beg, *end;
2655
2656 /* orig_arg points to the first argument, but we need to analyse the command itself first */
2657 cur_arg = *orig_arg - 1;
2658
2659 /* locate varName, which is mandatory */
2660 beg = strchr(args[cur_arg], '(');
2661 if (beg == NULL)
2662 goto do_resolve_parse_error;
2663 beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
2664 end = strchr(beg, ',');
2665 if (end == NULL)
2666 goto do_resolve_parse_error;
2667 rule->arg.resolv.varname = my_strndup(beg, end - beg);
2668 if (rule->arg.resolv.varname == NULL)
2669 goto do_resolve_parse_error;
2670
2671
2672 /* locate resolversSectionName, which is mandatory.
2673 * Since next parameters are optional, the delimiter may be comma ','
2674 * or closing parenthesis ')'
2675 */
2676 beg = end + 1;
2677 end = strchr(beg, ',');
2678 if (end == NULL)
2679 end = strchr(beg, ')');
2680 if (end == NULL)
2681 goto do_resolve_parse_error;
2682 rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
2683 if (rule->arg.resolv.resolvers_id == NULL)
2684 goto do_resolve_parse_error;
2685
2686
2687 rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
2688 if (rule->arg.resolv.opts == NULL)
2689 goto do_resolve_parse_error;
2690
2691 /* Default priority is ipv6 */
2692 rule->arg.resolv.opts->family_prio = AF_INET6;
2693
2694 /* optional arguments accepted for now:
2695 * ipv4 or ipv6
2696 */
2697 while (*end != ')') {
2698 beg = end + 1;
2699 end = strchr(beg, ',');
2700 if (end == NULL)
2701 end = strchr(beg, ')');
2702 if (end == NULL)
2703 goto do_resolve_parse_error;
2704
2705 if (strncmp(beg, "ipv4", end - beg) == 0) {
2706 rule->arg.resolv.opts->family_prio = AF_INET;
2707 }
2708 else if (strncmp(beg, "ipv6", end - beg) == 0) {
2709 rule->arg.resolv.opts->family_prio = AF_INET6;
2710 }
2711 else {
2712 goto do_resolve_parse_error;
2713 }
2714 }
2715
2716 cur_arg = cur_arg + 1;
2717
2718 expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
2719 if (!expr)
2720 goto do_resolve_parse_error;
2721
2722
2723 where = 0;
2724 if (px->cap & PR_CAP_FE)
2725 where |= SMP_VAL_FE_HRQ_HDR;
2726 if (px->cap & PR_CAP_BE)
2727 where |= SMP_VAL_BE_HRQ_HDR;
2728
2729 if (!(expr->fetch->val & where)) {
2730 memprintf(err,
2731 "fetch method '%s' extracts information from '%s', none of which is available here",
2732 args[cur_arg-1], sample_src_names(expr->fetch->use));
2733 free(expr);
2734 return ACT_RET_PRS_ERR;
2735 }
2736 rule->arg.resolv.expr = expr;
2737 rule->action = ACT_CUSTOM;
2738 rule->action_ptr = resolv_action_do_resolve;
2739 *orig_arg = cur_arg;
2740
2741 rule->check_ptr = check_action_do_resolve;
2742 rule->release_ptr = release_resolv_action;
2743
2744 return ACT_RET_PRS_OK;
2745
2746 do_resolve_parse_error:
2747 free(rule->arg.resolv.varname); rule->arg.resolv.varname = NULL;
2748 free(rule->arg.resolv.resolvers_id); rule->arg.resolv.resolvers_id = NULL;
2749 memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
2750 args[cur_arg]);
2751 return ACT_RET_PRS_ERR;
2752}
2753
2754static struct action_kw_list http_req_kws = { { }, {
2755 { "do-resolve", resolv_parse_do_resolve, 1 },
2756 { /* END */ }
2757}};
2758
2759INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
2760
2761static struct action_kw_list tcp_req_cont_actions = {ILH, {
2762 { "do-resolve", resolv_parse_do_resolve, 1 },
2763 { /* END */ }
2764}};
2765
2766INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
2767
2768/* Check an "http-request do-resolve" action.
2769 *
2770 * The function returns 1 in success case, otherwise, it returns 0 and err is
2771 * filled.
2772 */
2773int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
2774{
2775 struct resolvers *resolvers = NULL;
2776
2777 if (rule->arg.resolv.resolvers_id == NULL) {
2778 memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
2779 return 0;
2780 }
2781
2782 resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
2783 if (resolvers == NULL) {
2784 memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
2785 return 0;
2786 }
2787 rule->arg.resolv.resolvers = resolvers;
2788
2789 return 1;
2790}
2791
2792void resolvers_setup_proxy(struct proxy *px)
2793{
2794 px->last_change = now.tv_sec;
2795 px->cap = PR_CAP_FE | PR_CAP_BE;
2796 px->maxconn = 0;
2797 px->conn_retries = 1;
2798 px->timeout.server = TICK_ETERNITY;
2799 px->timeout.client = TICK_ETERNITY;
2800 px->timeout.connect = TICK_ETERNITY;
2801 px->accept = NULL;
2802 px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
2803 px->bind_proc = 0; /* will be filled by users */
2804}
2805
2806/*
2807 * Parse a <resolvers> section.
2808 * Returns the error code, 0 if OK, or any combination of :
2809 * - ERR_ABORT: must abort ASAP
2810 * - ERR_FATAL: we can continue parsing but not start the service
2811 * - ERR_WARN: a warning has been emitted
2812 * - ERR_ALERT: an alert has been emitted
2813 * Only the two first ones can stop processing, the two others are just
2814 * indicators.
2815 */
2816int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
2817{
2818 const char *err;
2819 int err_code = 0;
2820 char *errmsg = NULL;
2821 struct proxy *p;
2822
2823 if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
2824 if (!*args[1]) {
2825 ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
2826 err_code |= ERR_ALERT | ERR_ABORT;
2827 goto out;
2828 }
2829
2830 err = invalid_char(args[1]);
2831 if (err) {
2832 ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
2833 file, linenum, *err, args[0], args[1]);
2834 err_code |= ERR_ALERT | ERR_ABORT;
2835 goto out;
2836 }
2837
2838 list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
2839 /* Error if two resolvers owns the same name */
2840 if (strcmp(curr_resolvers->id, args[1]) == 0) {
2841 ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
2842 file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
2843 err_code |= ERR_ALERT | ERR_ABORT;
2844 }
2845 }
2846
2847 if ((curr_resolvers = calloc(1, sizeof(*curr_resolvers))) == NULL) {
2848 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2849 err_code |= ERR_ALERT | ERR_ABORT;
2850 goto out;
2851 }
2852
2853 /* allocate new proxy to tcp servers */
2854 p = calloc(1, sizeof *p);
2855 if (!p) {
2856 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2857 err_code |= ERR_ALERT | ERR_FATAL;
2858 goto out;
2859 }
2860
2861 init_new_proxy(p);
2862 resolvers_setup_proxy(p);
2863 p->parent = curr_resolvers;
2864 p->id = strdup(args[1]);
2865 p->conf.args.file = p->conf.file = strdup(file);
2866 p->conf.args.line = p->conf.line = linenum;
2867 curr_resolvers->px = p;
2868
2869 /* default values */
2870 LIST_ADDQ(&sec_resolvers, &curr_resolvers->list);
2871 curr_resolvers->conf.file = strdup(file);
2872 curr_resolvers->conf.line = linenum;
2873 curr_resolvers->id = strdup(args[1]);
2874 curr_resolvers->query_ids = EB_ROOT;
2875 /* default maximum response size */
2876 curr_resolvers->accepted_payload_size = 512;
2877 /* default hold period for nx, other, refuse and timeout is 30s */
2878 curr_resolvers->hold.nx = 30000;
2879 curr_resolvers->hold.other = 30000;
2880 curr_resolvers->hold.refused = 30000;
2881 curr_resolvers->hold.timeout = 30000;
2882 curr_resolvers->hold.obsolete = 0;
2883 /* default hold period for valid is 10s */
2884 curr_resolvers->hold.valid = 10000;
2885 curr_resolvers->timeout.resolve = 1000;
2886 curr_resolvers->timeout.retry = 1000;
2887 curr_resolvers->resolve_retries = 3;
2888 LIST_INIT(&curr_resolvers->nameservers);
2889 LIST_INIT(&curr_resolvers->resolutions.curr);
2890 LIST_INIT(&curr_resolvers->resolutions.wait);
2891 HA_SPIN_INIT(&curr_resolvers->lock);
2892 }
Emeric Brun56fc5d92021-02-12 20:05:45 +01002893 else if (strcmp(args[0],"server") == 0) {
2894 err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL, 1, 0, 1);
2895 }
Emeric Brunc9437992021-02-12 19:42:55 +01002896 else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
2897 struct dns_nameserver *newnameserver = NULL;
2898 struct sockaddr_storage *sk;
2899 int port1, port2;
2900
2901 if (!*args[2]) {
2902 ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
2903 file, linenum, args[0]);
2904 err_code |= ERR_ALERT | ERR_FATAL;
2905 goto out;
2906 }
2907
2908 err = invalid_char(args[1]);
2909 if (err) {
2910 ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
2911 file, linenum, *err, args[1]);
2912 err_code |= ERR_ALERT | ERR_FATAL;
2913 goto out;
2914 }
2915
2916 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
2917 /* Error if two resolvers owns the same name */
2918 if (strcmp(newnameserver->id, args[1]) == 0) {
2919 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
2920 file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
2921 err_code |= ERR_ALERT | ERR_FATAL;
2922 }
2923 }
2924
2925 sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, NULL,
2926 &errmsg, NULL, NULL, PA_O_RESOLVE | PA_O_PORT_OK | PA_O_PORT_MAND | PA_O_DGRAM);
2927 if (!sk) {
2928 ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
2929 err_code |= ERR_ALERT | ERR_FATAL;
2930 goto out;
2931 }
2932
2933 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
2934 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2935 err_code |= ERR_ALERT | ERR_ABORT;
2936 goto out;
2937 }
2938
2939 if (dns_dgram_init(newnameserver, sk) < 0) {
2940 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2941 err_code |= ERR_ALERT | ERR_ABORT;
2942 goto out;
2943 }
2944
2945 if ((newnameserver->conf.file = strdup(file)) == NULL) {
2946 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2947 err_code |= ERR_ALERT | ERR_ABORT;
2948 goto out;
2949 }
2950
2951 if ((newnameserver->id = strdup(args[1])) == NULL) {
2952 ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
2953 err_code |= ERR_ALERT | ERR_ABORT;
2954 goto out;
2955 }
2956
2957 newnameserver->parent = curr_resolvers;
2958 newnameserver->process_responses = resolv_process_responses;
2959 newnameserver->conf.line = linenum;
2960 /* the nameservers are linked backward first */
2961 LIST_ADDQ(&curr_resolvers->nameservers, &newnameserver->list);
2962 }
2963 else if (strcmp(args[0], "parse-resolv-conf") == 0) {
2964 struct dns_nameserver *newnameserver = NULL;
2965 const char *whitespace = "\r\n\t ";
2966 char *resolv_line = NULL;
2967 int resolv_linenum = 0;
2968 FILE *f = NULL;
2969 char *address = NULL;
2970 struct sockaddr_storage *sk = NULL;
2971 struct protocol *proto;
2972 int duplicate_name = 0;
2973
2974 if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
2975 ha_alert("parsing [%s:%d] : out of memory.\n",
2976 file, linenum);
2977 err_code |= ERR_ALERT | ERR_FATAL;
2978 goto resolv_out;
2979 }
2980
2981 if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
2982 ha_alert("parsing [%s:%d] : failed to open /etc/resolv.conf.\n",
2983 file, linenum);
2984 err_code |= ERR_ALERT | ERR_FATAL;
2985 goto resolv_out;
2986 }
2987
2988 sk = calloc(1, sizeof(*sk));
2989 if (sk == NULL) {
2990 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n",
2991 resolv_linenum);
2992 err_code |= ERR_ALERT | ERR_FATAL;
2993 goto resolv_out;
2994 }
2995
2996 while (fgets(resolv_line, LINESIZE, f) != NULL) {
2997 resolv_linenum++;
2998 if (strncmp(resolv_line, "nameserver", 10) != 0)
2999 continue;
3000
3001 address = strtok(resolv_line + 10, whitespace);
3002 if (address == resolv_line + 10)
3003 continue;
3004
3005 if (address == NULL) {
3006 ha_warning("parsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
3007 resolv_linenum);
3008 err_code |= ERR_WARN;
3009 continue;
3010 }
3011
3012 duplicate_name = 0;
3013 list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
3014 if (strcmp(newnameserver->id, address) == 0) {
3015 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",
3016 resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
3017 err_code |= ERR_WARN;
3018 duplicate_name = 1;
3019 }
3020 }
3021
3022 if (duplicate_name)
3023 continue;
3024
3025 memset(sk, 0, sizeof(*sk));
3026 if (!str2ip2(address, sk, 1)) {
3027 ha_warning("parsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
3028 resolv_linenum, address);
3029 err_code |= ERR_WARN;
3030 continue;
3031 }
3032
3033 set_host_port(sk, 53);
3034
3035 proto = protocol_by_family(sk->ss_family);
3036 if (!proto || !proto->connect) {
3037 ha_warning("parsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
3038 resolv_linenum, address);
3039 err_code |= ERR_WARN;
3040 continue;
3041 }
3042
3043 if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
3044 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3045 err_code |= ERR_ALERT | ERR_FATAL;
3046 goto resolv_out;
3047 }
3048
3049 if (dns_dgram_init(newnameserver, sk) < 0) {
3050 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3051 err_code |= ERR_ALERT | ERR_FATAL;
3052 free(newnameserver);
3053 goto resolv_out;
3054 }
3055
3056 newnameserver->conf.file = strdup("/etc/resolv.conf");
3057 if (newnameserver->conf.file == NULL) {
3058 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3059 err_code |= ERR_ALERT | ERR_FATAL;
3060 free(newnameserver);
3061 goto resolv_out;
3062 }
3063
3064 newnameserver->id = strdup(address);
3065 if (newnameserver->id == NULL) {
3066 ha_alert("parsing [/etc/resolv.conf:%d] : out of memory.\n", resolv_linenum);
3067 err_code |= ERR_ALERT | ERR_FATAL;
3068 free((char *)newnameserver->conf.file);
3069 free(newnameserver);
3070 goto resolv_out;
3071 }
3072
3073 newnameserver->parent = curr_resolvers;
3074 newnameserver->process_responses = resolv_process_responses;
3075 newnameserver->conf.line = resolv_linenum;
3076 LIST_ADDQ(&curr_resolvers->nameservers, &newnameserver->list);
3077 }
3078
3079resolv_out:
3080 free(sk);
3081 free(resolv_line);
3082 if (f != NULL)
3083 fclose(f);
3084 }
3085 else if (strcmp(args[0], "hold") == 0) { /* hold periods */
3086 const char *res;
3087 unsigned int time;
3088
3089 if (!*args[2]) {
3090 ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
3091 file, linenum, args[0]);
3092 ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
3093 err_code |= ERR_ALERT | ERR_FATAL;
3094 goto out;
3095 }
3096 res = parse_time_err(args[2], &time, TIME_UNIT_MS);
3097 if (res == PARSE_TIME_OVER) {
3098 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
3099 file, linenum, args[1], args[0]);
3100 err_code |= ERR_ALERT | ERR_FATAL;
3101 goto out;
3102 }
3103 else if (res == PARSE_TIME_UNDER) {
3104 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
3105 file, linenum, args[1], args[0]);
3106 err_code |= ERR_ALERT | ERR_FATAL;
3107 goto out;
3108 }
3109 else if (res) {
3110 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
3111 file, linenum, *res, args[0]);
3112 err_code |= ERR_ALERT | ERR_FATAL;
3113 goto out;
3114 }
3115 if (strcmp(args[1], "nx") == 0)
3116 curr_resolvers->hold.nx = time;
3117 else if (strcmp(args[1], "other") == 0)
3118 curr_resolvers->hold.other = time;
3119 else if (strcmp(args[1], "refused") == 0)
3120 curr_resolvers->hold.refused = time;
3121 else if (strcmp(args[1], "timeout") == 0)
3122 curr_resolvers->hold.timeout = time;
3123 else if (strcmp(args[1], "valid") == 0)
3124 curr_resolvers->hold.valid = time;
3125 else if (strcmp(args[1], "obsolete") == 0)
3126 curr_resolvers->hold.obsolete = time;
3127 else {
3128 ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
3129 file, linenum, args[0], args[1]);
3130 err_code |= ERR_ALERT | ERR_FATAL;
3131 goto out;
3132 }
3133
3134 }
3135 else if (strcmp(args[0], "accepted_payload_size") == 0) {
3136 int i = 0;
3137
3138 if (!*args[1]) {
3139 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3140 file, linenum, args[0]);
3141 err_code |= ERR_ALERT | ERR_FATAL;
3142 goto out;
3143 }
3144
3145 i = atoi(args[1]);
3146 if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
3147 ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
3148 file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
3149 err_code |= ERR_ALERT | ERR_FATAL;
3150 goto out;
3151 }
3152
3153 curr_resolvers->accepted_payload_size = i;
3154 }
3155 else if (strcmp(args[0], "resolution_pool_size") == 0) {
3156 ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
3157 file, linenum, args[0]);
3158 err_code |= ERR_ALERT | ERR_FATAL;
3159 goto out;
3160 }
3161 else if (strcmp(args[0], "resolve_retries") == 0) {
3162 if (!*args[1]) {
3163 ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
3164 file, linenum, args[0]);
3165 err_code |= ERR_ALERT | ERR_FATAL;
3166 goto out;
3167 }
3168 curr_resolvers->resolve_retries = atoi(args[1]);
3169 }
3170 else if (strcmp(args[0], "timeout") == 0) {
3171 if (!*args[1]) {
3172 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
3173 file, linenum, args[0]);
3174 err_code |= ERR_ALERT | ERR_FATAL;
3175 goto out;
3176 }
3177 else if (strcmp(args[1], "retry") == 0 ||
3178 strcmp(args[1], "resolve") == 0) {
3179 const char *res;
3180 unsigned int tout;
3181
3182 if (!*args[2]) {
3183 ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
3184 file, linenum, args[0], args[1]);
3185 err_code |= ERR_ALERT | ERR_FATAL;
3186 goto out;
3187 }
3188 res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
3189 if (res == PARSE_TIME_OVER) {
3190 ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
3191 file, linenum, args[2], args[0], args[1]);
3192 err_code |= ERR_ALERT | ERR_FATAL;
3193 goto out;
3194 }
3195 else if (res == PARSE_TIME_UNDER) {
3196 ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
3197 file, linenum, args[2], args[0], args[1]);
3198 err_code |= ERR_ALERT | ERR_FATAL;
3199 goto out;
3200 }
3201 else if (res) {
3202 ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
3203 file, linenum, *res, args[0], args[1]);
3204 err_code |= ERR_ALERT | ERR_FATAL;
3205 goto out;
3206 }
3207 if (args[1][2] == 't')
3208 curr_resolvers->timeout.retry = tout;
3209 else
3210 curr_resolvers->timeout.resolve = tout;
3211 }
3212 else {
3213 ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
3214 file, linenum, args[0], args[1]);
3215 err_code |= ERR_ALERT | ERR_FATAL;
3216 goto out;
3217 }
3218 }
3219 else if (*args[0] != 0) {
3220 ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
3221 err_code |= ERR_ALERT | ERR_FATAL;
3222 goto out;
3223 }
3224
3225 out:
3226 free(errmsg);
3227 return err_code;
3228}
Emeric Brun56fc5d92021-02-12 20:05:45 +01003229int cfg_post_parse_resolvers()
3230{
3231 int err_code = 0;
3232 struct server *srv;
3233
3234 if (curr_resolvers) {
3235
3236 /* prepare forward server descriptors */
3237 if (curr_resolvers->px) {
3238 srv = curr_resolvers->px->srv;
3239 while (srv) {
3240 struct dns_nameserver *ns;
3241
3242 list_for_each_entry(ns, &curr_resolvers->nameservers, list) {
3243 /* Error if two resolvers owns the same name */
3244 if (strcmp(ns->id, srv->id) == 0) {
3245 ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
3246 srv->conf.file, srv->conf.line, srv->id, ns->conf.file, ns->conf.line);
3247 err_code |= ERR_ALERT | ERR_FATAL;
3248 break;
3249 }
3250 }
3251
3252 /* init ssl if needed */
3253 if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
3254 if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
3255 ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3256 err_code |= ERR_ALERT | ERR_FATAL;
3257 break;
3258 }
3259 }
3260
3261 /* allocate nameserver */
3262 ns = calloc(1, sizeof(*ns));
3263 if (!ns) {
3264 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3265 err_code |= ERR_ALERT | ERR_FATAL;
3266 break;
3267 }
3268
3269 if (dns_stream_init(ns, srv) < 0) {
3270 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3271 err_code |= ERR_ALERT|ERR_ABORT;
3272 break;
3273 }
3274
3275 ns->conf.file = strdup(srv->conf.file);
3276 if (!ns->conf.file) {
3277 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3278 err_code |= ERR_ALERT|ERR_ABORT;
3279 break;
3280 }
3281 ns->id = strdup(srv->id);
3282 if (!ns->id) {
3283 ha_alert("memory allocation error initializing tcp server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
3284 err_code |= ERR_ALERT|ERR_ABORT;
3285 break;
3286 }
3287 ns->conf.line = srv->conf.line;
3288 ns->process_responses = resolv_process_responses;
3289 ns->parent = curr_resolvers;
3290 LIST_ADDQ(&curr_resolvers->nameservers, &ns->list);
3291 srv = srv->next;
3292 }
3293 }
3294 }
3295 curr_resolvers = NULL;
3296 return err_code;
3297}
Emeric Brunc9437992021-02-12 19:42:55 +01003298
Emeric Brun56fc5d92021-02-12 20:05:45 +01003299REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
Emeric Brunc9437992021-02-12 19:42:55 +01003300REGISTER_POST_DEINIT(resolvers_deinit);
3301REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);