1:255.13-alt1
[systemd_ALT.git] / src / resolve / resolved-dns-query.c
blob16334c6300a44c68d17f08bf1ac87a2cc50cf6e4
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include "alloc-util.h"
4 #include "dns-domain.h"
5 #include "dns-type.h"
6 #include "event-util.h"
7 #include "glyph-util.h"
8 #include "hostname-util.h"
9 #include "local-addresses.h"
10 #include "resolved-dns-query.h"
11 #include "resolved-dns-synthesize.h"
12 #include "resolved-etc-hosts.h"
13 #include "string-util.h"
15 #define QUERIES_MAX 2048
16 #define AUXILIARY_QUERIES_MAX 64
17 #define CNAME_REDIRECTS_MAX 16
19 assert_cc(AUXILIARY_QUERIES_MAX < UINT8_MAX);
20 assert_cc(CNAME_REDIRECTS_MAX < UINT8_MAX);
22 static int dns_query_candidate_new(DnsQueryCandidate **ret, DnsQuery *q, DnsScope *s) {
23 DnsQueryCandidate *c;
25 assert(ret);
26 assert(q);
27 assert(s);
29 c = new(DnsQueryCandidate, 1);
30 if (!c)
31 return -ENOMEM;
33 *c = (DnsQueryCandidate) {
34 .n_ref = 1,
35 .query = q,
36 .scope = s,
39 LIST_PREPEND(candidates_by_query, q->candidates, c);
40 LIST_PREPEND(candidates_by_scope, s->query_candidates, c);
42 *ret = c;
43 return 0;
46 static void dns_query_candidate_stop(DnsQueryCandidate *c) {
47 DnsTransaction *t;
49 assert(c);
51 /* Detach all the DnsTransactions attached to this query */
53 while ((t = set_steal_first(c->transactions))) {
54 set_remove(t->notify_query_candidates, c);
55 set_remove(t->notify_query_candidates_done, c);
56 dns_transaction_gc(t);
60 static void dns_query_candidate_abandon(DnsQueryCandidate *c) {
61 DnsTransaction *t;
63 assert(c);
65 /* Abandon all the DnsTransactions attached to this query */
67 while ((t = set_steal_first(c->transactions))) {
68 t->wait_for_answer = true;
69 set_remove(t->notify_query_candidates, c);
70 set_remove(t->notify_query_candidates_done, c);
71 dns_transaction_gc(t);
75 static DnsQueryCandidate* dns_query_candidate_unlink(DnsQueryCandidate *c) {
76 assert(c);
78 /* Detach this DnsQueryCandidate from the Query and Scope objects */
80 if (c->query) {
81 LIST_REMOVE(candidates_by_query, c->query->candidates, c);
82 c->query = NULL;
85 if (c->scope) {
86 LIST_REMOVE(candidates_by_scope, c->scope->query_candidates, c);
87 c->scope = NULL;
90 return c;
93 static DnsQueryCandidate* dns_query_candidate_free(DnsQueryCandidate *c) {
94 if (!c)
95 return NULL;
97 dns_query_candidate_stop(c);
98 dns_query_candidate_unlink(c);
100 set_free(c->transactions);
101 dns_search_domain_unref(c->search_domain);
103 return mfree(c);
106 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(DnsQueryCandidate, dns_query_candidate, dns_query_candidate_free);
108 static int dns_query_candidate_next_search_domain(DnsQueryCandidate *c) {
109 DnsSearchDomain *next;
111 assert(c);
113 if (c->search_domain && c->search_domain->linked)
114 next = c->search_domain->domains_next;
115 else
116 next = dns_scope_get_search_domains(c->scope);
118 for (;;) {
119 if (!next) /* We hit the end of the list */
120 return 0;
122 if (!next->route_only)
123 break;
125 /* Skip over route-only domains */
126 next = next->domains_next;
129 dns_search_domain_unref(c->search_domain);
130 c->search_domain = dns_search_domain_ref(next);
132 return 1;
135 static int dns_query_candidate_add_transaction(
136 DnsQueryCandidate *c,
137 DnsResourceKey *key,
138 DnsPacket *bypass) {
140 _cleanup_(dns_transaction_gcp) DnsTransaction *t = NULL;
141 int r;
143 assert(c);
144 assert(c->query); /* We shan't add transactions to a candidate that has been detached already */
146 if (key) {
147 /* Regular lookup with a resource key */
148 assert(!bypass);
150 t = dns_scope_find_transaction(c->scope, key, c->query->flags);
151 if (!t) {
152 r = dns_transaction_new(&t, c->scope, key, NULL, c->query->flags);
153 if (r < 0)
154 return r;
155 } else if (set_contains(c->transactions, t))
156 return 0;
157 } else {
158 /* "Bypass" lookup with a query packet */
159 assert(bypass);
161 r = dns_transaction_new(&t, c->scope, NULL, bypass, c->query->flags);
162 if (r < 0)
163 return r;
166 r = set_ensure_allocated(&t->notify_query_candidates_done, NULL);
167 if (r < 0)
168 return r;
170 r = set_ensure_put(&t->notify_query_candidates, NULL, c);
171 if (r < 0)
172 return r;
174 r = set_ensure_put(&c->transactions, NULL, t);
175 if (r < 0) {
176 (void) set_remove(t->notify_query_candidates, c);
177 return r;
180 TAKE_PTR(t);
181 return 1;
184 static int dns_query_candidate_go(DnsQueryCandidate *c) {
185 _unused_ _cleanup_(dns_query_candidate_unrefp) DnsQueryCandidate *keep_c = NULL;
186 DnsTransaction *t;
187 int r;
188 unsigned n = 0;
190 assert(c);
192 /* Let's keep a reference to the query while we're operating */
193 keep_c = dns_query_candidate_ref(c);
195 /* Start the transactions that are not started yet */
196 SET_FOREACH(t, c->transactions) {
197 if (t->state != DNS_TRANSACTION_NULL)
198 continue;
200 r = dns_transaction_go(t);
201 if (r < 0)
202 return r;
204 n++;
207 /* If there was nothing to start, then let's proceed immediately */
208 if (n == 0)
209 dns_query_candidate_notify(c);
211 return 0;
214 static DnsTransactionState dns_query_candidate_state(DnsQueryCandidate *c) {
215 DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
216 DnsTransaction *t;
218 assert(c);
220 if (c->error_code != 0)
221 return DNS_TRANSACTION_ERRNO;
223 SET_FOREACH(t, c->transactions)
225 switch (t->state) {
227 case DNS_TRANSACTION_NULL:
228 /* If there's a NULL transaction pending, then
229 * this means not all transactions where
230 * started yet, and we were called from within
231 * the stackframe that is supposed to start
232 * remaining transactions. In this case,
233 * simply claim the candidate is pending. */
235 case DNS_TRANSACTION_PENDING:
236 case DNS_TRANSACTION_VALIDATING:
237 /* If there's one transaction currently in
238 * VALIDATING state, then this means there's
239 * also one in PENDING state, hence we can
240 * return PENDING immediately. */
241 return DNS_TRANSACTION_PENDING;
243 case DNS_TRANSACTION_SUCCESS:
244 state = t->state;
245 break;
247 default:
248 if (state != DNS_TRANSACTION_SUCCESS)
249 state = t->state;
251 break;
254 return state;
257 static int dns_query_candidate_setup_transactions(DnsQueryCandidate *c) {
258 DnsQuestion *question;
259 DnsResourceKey *key;
260 int n = 0, r;
262 assert(c);
263 assert(c->query); /* We shan't add transactions to a candidate that has been detached already */
265 dns_query_candidate_stop(c);
267 if (c->query->question_bypass) {
268 /* If this is a bypass query, then pass the original query packet along to the transaction */
270 assert(dns_question_size(c->query->question_bypass->question) == 1);
272 if (!dns_scope_good_key(c->scope, dns_question_first_key(c->query->question_bypass->question)))
273 return 0;
275 r = dns_query_candidate_add_transaction(c, NULL, c->query->question_bypass);
276 if (r < 0)
277 goto fail;
279 return 1;
282 question = dns_query_question_for_protocol(c->query, c->scope->protocol);
284 /* Create one transaction per question key */
285 DNS_QUESTION_FOREACH(key, question) {
286 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *new_key = NULL;
287 DnsResourceKey *qkey;
289 if (c->search_domain) {
290 r = dns_resource_key_new_append_suffix(&new_key, key, c->search_domain->name);
291 if (r < 0)
292 goto fail;
294 qkey = new_key;
295 } else
296 qkey = key;
298 if (!dns_scope_good_key(c->scope, qkey))
299 continue;
301 r = dns_query_candidate_add_transaction(c, qkey, NULL);
302 if (r < 0)
303 goto fail;
305 n++;
308 return n;
310 fail:
311 dns_query_candidate_stop(c);
312 return r;
315 void dns_query_candidate_notify(DnsQueryCandidate *c) {
316 DnsTransactionState state;
317 int r;
319 assert(c);
321 if (!c->query) /* This candidate has been abandoned, do nothing. */
322 return;
324 state = dns_query_candidate_state(c);
326 if (DNS_TRANSACTION_IS_LIVE(state))
327 return;
329 if (state != DNS_TRANSACTION_SUCCESS && c->search_domain) {
331 r = dns_query_candidate_next_search_domain(c);
332 if (r < 0)
333 goto fail;
335 if (r > 0) {
336 /* OK, there's another search domain to try, let's do so. */
338 r = dns_query_candidate_setup_transactions(c);
339 if (r < 0)
340 goto fail;
342 if (r > 0) {
343 /* New transactions where queued. Start them and wait */
345 r = dns_query_candidate_go(c);
346 if (r < 0)
347 goto fail;
349 return;
355 dns_query_ready(c->query);
356 return;
358 fail:
359 c->error_code = log_warning_errno(r, "Failed to follow search domains: %m");
360 dns_query_ready(c->query);
363 static void dns_query_stop(DnsQuery *q) {
364 assert(q);
366 event_source_disable(q->timeout_event_source);
368 LIST_FOREACH(candidates_by_query, c, q->candidates)
369 dns_query_candidate_stop(c);
372 static void dns_query_abandon(DnsQuery *q) {
373 assert(q);
375 /* Thankfully transactions have their own timeouts */
376 event_source_disable(q->timeout_event_source);
378 LIST_FOREACH(candidates_by_query, c, q->candidates)
379 dns_query_candidate_abandon(c);
382 static void dns_query_unlink_candidates(DnsQuery *q) {
383 assert(q);
385 while (q->candidates)
386 /* Here we drop *our* references to each of the candidates. If we had the only reference, the
387 * DnsQueryCandidate object will be freed. */
388 dns_query_candidate_unref(dns_query_candidate_unlink(q->candidates));
391 static void dns_query_reset_answer(DnsQuery *q) {
392 assert(q);
394 q->answer = dns_answer_unref(q->answer);
395 q->answer_rcode = 0;
396 q->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
397 q->answer_errno = 0;
398 q->answer_query_flags = 0;
399 q->answer_protocol = _DNS_PROTOCOL_INVALID;
400 q->answer_family = AF_UNSPEC;
401 q->answer_search_domain = dns_search_domain_unref(q->answer_search_domain);
402 q->answer_full_packet = dns_packet_unref(q->answer_full_packet);
405 DnsQuery *dns_query_free(DnsQuery *q) {
406 if (!q)
407 return NULL;
409 q->timeout_event_source = sd_event_source_disable_unref(q->timeout_event_source);
411 while (q->auxiliary_queries)
412 dns_query_free(q->auxiliary_queries);
414 if (q->auxiliary_for) {
415 assert(q->auxiliary_for->n_auxiliary_queries > 0);
416 q->auxiliary_for->n_auxiliary_queries--;
417 LIST_REMOVE(auxiliary_queries, q->auxiliary_for->auxiliary_queries, q);
420 dns_query_unlink_candidates(q);
422 dns_question_unref(q->question_idna);
423 dns_question_unref(q->question_utf8);
424 dns_packet_unref(q->question_bypass);
425 dns_question_unref(q->collected_questions);
427 dns_query_reset_answer(q);
429 sd_bus_message_unref(q->bus_request);
430 sd_bus_track_unref(q->bus_track);
432 if (q->varlink_request) {
433 varlink_set_userdata(q->varlink_request, NULL);
434 varlink_unref(q->varlink_request);
437 if (q->request_packet)
438 hashmap_remove_value(q->stub_listener_extra ?
439 q->stub_listener_extra->queries_by_packet :
440 q->manager->stub_queries_by_packet,
441 q->request_packet,
444 dns_packet_unref(q->request_packet);
445 dns_answer_unref(q->reply_answer);
446 dns_answer_unref(q->reply_authoritative);
447 dns_answer_unref(q->reply_additional);
449 if (q->request_stream) {
450 /* Detach the stream from our query, in case something else keeps a reference to it. */
451 (void) set_remove(q->request_stream->queries, q);
452 q->request_stream = dns_stream_unref(q->request_stream);
455 free(q->request_address_string);
457 if (q->manager) {
458 LIST_REMOVE(queries, q->manager->dns_queries, q);
459 q->manager->n_dns_queries--;
462 return mfree(q);
465 int dns_query_new(
466 Manager *m,
467 DnsQuery **ret,
468 DnsQuestion *question_utf8,
469 DnsQuestion *question_idna,
470 DnsPacket *question_bypass,
471 int ifindex,
472 uint64_t flags) {
474 _cleanup_(dns_query_freep) DnsQuery *q = NULL;
475 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
476 DnsResourceKey *key;
477 int r;
479 assert(m);
481 if (question_bypass) {
482 /* It's either a "bypass" query, or a regular one, but can't be both. */
483 if (question_utf8 || question_idna)
484 return -EINVAL;
486 } else {
487 bool good = false;
489 /* This (primarily) checks two things:
491 * 1. That the question is not empty
492 * 2. That all RR keys in the question objects are for the same domain
494 * Or in other words, a single DnsQuery object may be used to look up A+AAAA combination for
495 * the same domain name, or SRV+TXT (for DNS-SD services), but not for unrelated lookups. */
497 if (dns_question_size(question_utf8) > 0) {
498 r = dns_question_is_valid_for_query(question_utf8);
499 if (r < 0)
500 return r;
501 if (r == 0)
502 return -EINVAL;
504 good = true;
507 /* If the IDNA and UTF8 questions are the same, merge their references */
508 r = dns_question_is_equal(question_idna, question_utf8);
509 if (r < 0)
510 return r;
511 if (r > 0)
512 question_idna = question_utf8;
513 else {
514 if (dns_question_size(question_idna) > 0) {
515 r = dns_question_is_valid_for_query(question_idna);
516 if (r < 0)
517 return r;
518 if (r == 0)
519 return -EINVAL;
521 good = true;
525 if (!good) /* don't allow empty queries */
526 return -EINVAL;
529 if (m->n_dns_queries >= QUERIES_MAX)
530 return -EBUSY;
532 q = new(DnsQuery, 1);
533 if (!q)
534 return -ENOMEM;
536 *q = (DnsQuery) {
537 .question_utf8 = dns_question_ref(question_utf8),
538 .question_idna = dns_question_ref(question_idna),
539 .question_bypass = dns_packet_ref(question_bypass),
540 .ifindex = ifindex,
541 .flags = flags,
542 .answer_dnssec_result = _DNSSEC_RESULT_INVALID,
543 .answer_protocol = _DNS_PROTOCOL_INVALID,
544 .answer_family = AF_UNSPEC,
547 if (question_bypass) {
548 DNS_QUESTION_FOREACH(key, question_bypass->question)
549 log_debug("Looking up bypass packet for %s.",
550 dns_resource_key_to_string(key, key_str, sizeof key_str));
551 } else {
552 /* First dump UTF8 question */
553 DNS_QUESTION_FOREACH(key, question_utf8)
554 log_debug("Looking up RR for %s.",
555 dns_resource_key_to_string(key, key_str, sizeof key_str));
557 /* And then dump the IDNA question, but only what hasn't been dumped already through the UTF8 question. */
558 DNS_QUESTION_FOREACH(key, question_idna) {
559 r = dns_question_contains_key(question_utf8, key);
560 if (r < 0)
561 return r;
562 if (r > 0)
563 continue;
565 log_debug("Looking up IDNA RR for %s.",
566 dns_resource_key_to_string(key, key_str, sizeof key_str));
570 LIST_PREPEND(queries, m->dns_queries, q);
571 m->n_dns_queries++;
572 q->manager = m;
574 if (ret)
575 *ret = q;
577 TAKE_PTR(q);
578 return 0;
581 int dns_query_make_auxiliary(DnsQuery *q, DnsQuery *auxiliary_for) {
582 assert(q);
583 assert(auxiliary_for);
585 /* Ensure that the query is not auxiliary yet, and
586 * nothing else is auxiliary to it either */
587 assert(!q->auxiliary_for);
588 assert(!q->auxiliary_queries);
590 /* Ensure that the unit we shall be made auxiliary for isn't
591 * auxiliary itself */
592 assert(!auxiliary_for->auxiliary_for);
594 if (auxiliary_for->n_auxiliary_queries >= AUXILIARY_QUERIES_MAX)
595 return -EAGAIN;
597 LIST_PREPEND(auxiliary_queries, auxiliary_for->auxiliary_queries, q);
598 q->auxiliary_for = auxiliary_for;
600 auxiliary_for->n_auxiliary_queries++;
601 return 0;
604 void dns_query_complete(DnsQuery *q, DnsTransactionState state) {
605 assert(q);
606 assert(!DNS_TRANSACTION_IS_LIVE(state));
607 assert(DNS_TRANSACTION_IS_LIVE(q->state));
609 /* Note that this call might invalidate the query. Callers should hence not attempt to access the
610 * query or transaction after calling this function. */
612 q->state = state;
614 (void) manager_monitor_send(q->manager, q->state, q->answer_rcode, q->answer_errno, q->question_idna, q->question_utf8, q->question_bypass, q->collected_questions, q->answer);
616 dns_query_abandon(q);
617 if (q->complete)
618 q->complete(q);
621 static int on_query_timeout(sd_event_source *s, usec_t usec, void *userdata) {
622 DnsQuery *q = ASSERT_PTR(userdata);
624 assert(s);
626 dns_query_complete(q, DNS_TRANSACTION_TIMEOUT);
627 return 0;
630 static int dns_query_add_candidate(DnsQuery *q, DnsScope *s) {
631 _cleanup_(dns_query_candidate_unrefp) DnsQueryCandidate *c = NULL;
632 int r;
634 assert(q);
635 assert(s);
637 r = dns_query_candidate_new(&c, q, s);
638 if (r < 0)
639 return r;
641 /* If this a single-label domain on DNS, we might append a suitable search domain first. */
642 if (!FLAGS_SET(q->flags, SD_RESOLVED_NO_SEARCH) &&
643 dns_scope_name_wants_search_domain(s, dns_question_first_name(q->question_idna))) {
644 /* OK, we want a search domain now. Let's find one for this scope */
646 r = dns_query_candidate_next_search_domain(c);
647 if (r < 0)
648 return r;
651 r = dns_query_candidate_setup_transactions(c);
652 if (r < 0)
653 return r;
655 TAKE_PTR(c);
656 return 0;
659 static int dns_query_synthesize_reply(DnsQuery *q, DnsTransactionState *state) {
660 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
661 int r;
663 assert(q);
664 assert(state);
666 /* Tries to synthesize localhost RR replies (and others) where appropriate. Note that this is done *after* the
667 * the normal lookup finished. The data from the network hence takes precedence over the data we
668 * synthesize. (But note that many scopes refuse to resolve certain domain names) */
670 if (!IN_SET(*state,
671 DNS_TRANSACTION_RCODE_FAILURE,
672 DNS_TRANSACTION_NO_SERVERS,
673 DNS_TRANSACTION_TIMEOUT,
674 DNS_TRANSACTION_ATTEMPTS_MAX_REACHED,
675 DNS_TRANSACTION_NETWORK_DOWN,
676 DNS_TRANSACTION_NOT_FOUND))
677 return 0;
679 if (FLAGS_SET(q->flags, SD_RESOLVED_NO_SYNTHESIZE))
680 return 0;
682 r = dns_synthesize_answer(
683 q->manager,
684 q->question_bypass ? q->question_bypass->question : q->question_utf8,
685 q->ifindex,
686 &answer);
687 if (r == -ENXIO) {
688 /* If we get ENXIO this tells us to generate NXDOMAIN unconditionally. */
690 dns_query_reset_answer(q);
691 q->answer_rcode = DNS_RCODE_NXDOMAIN;
692 q->answer_protocol = dns_synthesize_protocol(q->flags);
693 q->answer_family = dns_synthesize_family(q->flags);
694 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
695 *state = DNS_TRANSACTION_RCODE_FAILURE;
697 return 0;
699 if (r <= 0)
700 return r;
702 dns_query_reset_answer(q);
704 q->answer = TAKE_PTR(answer);
705 q->answer_rcode = DNS_RCODE_SUCCESS;
706 q->answer_protocol = dns_synthesize_protocol(q->flags);
707 q->answer_family = dns_synthesize_family(q->flags);
708 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
710 *state = DNS_TRANSACTION_SUCCESS;
712 return 1;
715 static int dns_query_try_etc_hosts(DnsQuery *q) {
716 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
717 int r;
719 assert(q);
721 /* Looks in /etc/hosts for matching entries. Note that this is done *before* the normal lookup is
722 * done. The data from /etc/hosts hence takes precedence over the network. */
724 if (FLAGS_SET(q->flags, SD_RESOLVED_NO_SYNTHESIZE))
725 return 0;
727 r = manager_etc_hosts_lookup(
728 q->manager,
729 q->question_bypass ? q->question_bypass->question : q->question_utf8,
730 &answer);
731 if (r <= 0)
732 return r;
734 dns_query_reset_answer(q);
736 q->answer = TAKE_PTR(answer);
737 q->answer_rcode = DNS_RCODE_SUCCESS;
738 q->answer_protocol = dns_synthesize_protocol(q->flags);
739 q->answer_family = dns_synthesize_family(q->flags);
740 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
742 return 1;
745 int dns_query_go(DnsQuery *q) {
746 DnsScopeMatch found = DNS_SCOPE_NO;
747 DnsScope *first = NULL;
748 int r;
750 assert(q);
752 if (q->state != DNS_TRANSACTION_NULL)
753 return 0;
755 r = dns_query_try_etc_hosts(q);
756 if (r < 0)
757 return r;
758 if (r > 0) {
759 dns_query_complete(q, DNS_TRANSACTION_SUCCESS);
760 return 1;
763 LIST_FOREACH(scopes, s, q->manager->dns_scopes) {
764 DnsScopeMatch match;
766 match = dns_scope_good_domain(s, q);
767 assert(match >= 0);
768 if (match > found) { /* Does this match better? If so, remember how well it matched, and the first one
769 * that matches this well */
770 found = match;
771 first = s;
775 if (found == DNS_SCOPE_NO) {
776 DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
778 r = dns_query_synthesize_reply(q, &state);
779 if (r < 0)
780 return r;
782 dns_query_complete(q, state);
783 return 1;
786 r = dns_query_add_candidate(q, first);
787 if (r < 0)
788 goto fail;
790 LIST_FOREACH(scopes, s, first->scopes_next) {
791 DnsScopeMatch match;
793 match = dns_scope_good_domain(s, q);
794 assert(match >= 0);
795 if (match < found)
796 continue;
798 r = dns_query_add_candidate(q, s);
799 if (r < 0)
800 goto fail;
803 dns_query_reset_answer(q);
805 r = event_reset_time_relative(
806 q->manager->event,
807 &q->timeout_event_source,
808 CLOCK_BOOTTIME,
809 SD_RESOLVED_QUERY_TIMEOUT_USEC,
810 0, on_query_timeout, q,
811 0, "query-timeout", true);
812 if (r < 0)
813 goto fail;
815 q->state = DNS_TRANSACTION_PENDING;
816 q->block_ready++;
818 /* Start the transactions */
819 LIST_FOREACH(candidates_by_query, c, q->candidates) {
820 r = dns_query_candidate_go(c);
821 if (r < 0) {
822 q->block_ready--;
823 goto fail;
827 q->block_ready--;
828 dns_query_ready(q);
830 return 1;
832 fail:
833 dns_query_stop(q);
834 return r;
837 static void dns_query_accept(DnsQuery *q, DnsQueryCandidate *c) {
838 DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
839 bool has_authenticated = false, has_non_authenticated = false, has_confidential = false, has_non_confidential = false;
840 DnssecResult dnssec_result_authenticated = _DNSSEC_RESULT_INVALID, dnssec_result_non_authenticated = _DNSSEC_RESULT_INVALID;
841 DnsTransaction *t;
842 int r;
844 assert(q);
846 if (!c) {
847 r = dns_query_synthesize_reply(q, &state);
848 if (r < 0)
849 goto fail;
851 dns_query_complete(q, state);
852 return;
855 if (c->error_code != 0) {
856 /* If the candidate had an error condition of its own, start with that. */
857 state = DNS_TRANSACTION_ERRNO;
858 q->answer = dns_answer_unref(q->answer);
859 q->answer_rcode = 0;
860 q->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
861 q->answer_query_flags = 0;
862 q->answer_errno = c->error_code;
863 q->answer_full_packet = dns_packet_unref(q->answer_full_packet);
866 SET_FOREACH(t, c->transactions) {
868 switch (t->state) {
870 case DNS_TRANSACTION_SUCCESS: {
871 /* We found a successful reply, merge it into the answer */
873 if (state == DNS_TRANSACTION_SUCCESS) {
874 r = dns_answer_extend(&q->answer, t->answer);
875 if (r < 0)
876 goto fail;
878 q->answer_query_flags |= dns_transaction_source_to_query_flags(t->answer_source);
879 } else {
880 /* Override non-successful previous answers */
881 DNS_ANSWER_REPLACE(q->answer, dns_answer_ref(t->answer));
882 q->answer_query_flags = dns_transaction_source_to_query_flags(t->answer_source);
885 q->answer_rcode = t->answer_rcode;
886 q->answer_errno = 0;
888 DNS_PACKET_REPLACE(q->answer_full_packet, dns_packet_ref(t->received));
890 if (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED)) {
891 has_authenticated = true;
892 dnssec_result_authenticated = t->answer_dnssec_result;
893 } else {
894 has_non_authenticated = true;
895 dnssec_result_non_authenticated = t->answer_dnssec_result;
898 if (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL))
899 has_confidential = true;
900 else
901 has_non_confidential = true;
903 state = DNS_TRANSACTION_SUCCESS;
904 break;
907 case DNS_TRANSACTION_NULL:
908 case DNS_TRANSACTION_PENDING:
909 case DNS_TRANSACTION_VALIDATING:
910 case DNS_TRANSACTION_ABORTED:
911 /* Ignore transactions that didn't complete */
912 continue;
914 default:
915 /* Any kind of failure? Store the data away, if there's nothing stored yet. */
916 if (state == DNS_TRANSACTION_SUCCESS)
917 continue;
919 /* If there's already an authenticated negative reply stored, then prefer that over any unauthenticated one */
920 if (FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) &&
921 !FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
922 continue;
924 DNS_ANSWER_REPLACE(q->answer, dns_answer_ref(t->answer));
925 q->answer_rcode = t->answer_rcode;
926 q->answer_dnssec_result = t->answer_dnssec_result;
927 q->answer_query_flags = t->answer_query_flags | dns_transaction_source_to_query_flags(t->answer_source);
928 q->answer_errno = t->answer_errno;
929 DNS_PACKET_REPLACE(q->answer_full_packet, dns_packet_ref(t->received));
931 state = t->state;
932 break;
936 if (state == DNS_TRANSACTION_SUCCESS) {
937 SET_FLAG(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED, has_authenticated && !has_non_authenticated);
938 SET_FLAG(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL, has_confidential && !has_non_confidential);
939 q->answer_dnssec_result = FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) ? dnssec_result_authenticated : dnssec_result_non_authenticated;
942 q->answer_protocol = c->scope->protocol;
943 q->answer_family = c->scope->family;
945 dns_search_domain_unref(q->answer_search_domain);
946 q->answer_search_domain = dns_search_domain_ref(c->search_domain);
948 r = dns_query_synthesize_reply(q, &state);
949 if (r < 0)
950 goto fail;
952 dns_query_complete(q, state);
953 return;
955 fail:
956 q->answer_errno = -r;
957 dns_query_complete(q, DNS_TRANSACTION_ERRNO);
960 void dns_query_ready(DnsQuery *q) {
961 DnsQueryCandidate *bad = NULL;
962 bool pending = false;
964 assert(q);
965 assert(DNS_TRANSACTION_IS_LIVE(q->state));
967 /* Note that this call might invalidate the query. Callers
968 * should hence not attempt to access the query or transaction
969 * after calling this function, unless the block_ready
970 * counter was explicitly bumped before doing so. */
972 if (q->block_ready > 0)
973 return;
975 LIST_FOREACH(candidates_by_query, c, q->candidates) {
976 DnsTransactionState state;
978 state = dns_query_candidate_state(c);
979 switch (state) {
981 case DNS_TRANSACTION_SUCCESS:
982 /* One of the candidates is successful,
983 * let's use it, and copy its data out */
984 dns_query_accept(q, c);
985 return;
987 case DNS_TRANSACTION_NULL:
988 case DNS_TRANSACTION_PENDING:
989 case DNS_TRANSACTION_VALIDATING:
990 /* One of the candidates is still going on,
991 * let's maybe wait for it */
992 pending = true;
993 break;
995 default:
996 /* Any kind of failure */
997 bad = c;
998 break;
1002 if (pending)
1003 return;
1005 dns_query_accept(q, bad);
1008 static int dns_query_collect_question(DnsQuery *q, DnsQuestion *question) {
1009 _cleanup_(dns_question_unrefp) DnsQuestion *merged = NULL;
1010 int r;
1012 assert(q);
1014 if (dns_question_size(question) == 0)
1015 return 0;
1017 /* When redirecting, save the first element in the chain, for informational purposes when monitoring */
1018 r = dns_question_merge(q->collected_questions, question, &merged);
1019 if (r < 0)
1020 return r;
1022 dns_question_unref(q->collected_questions);
1023 q->collected_questions = TAKE_PTR(merged);
1025 return 0;
1028 static int dns_query_cname_redirect(DnsQuery *q, const DnsResourceRecord *cname) {
1029 _cleanup_(dns_question_unrefp) DnsQuestion *nq_idna = NULL, *nq_utf8 = NULL;
1030 int r, k;
1032 assert(q);
1034 if (q->n_cname_redirects >= CNAME_REDIRECTS_MAX)
1035 return -ELOOP;
1036 q->n_cname_redirects++;
1038 r = dns_question_cname_redirect(q->question_idna, cname, &nq_idna);
1039 if (r < 0)
1040 return r;
1041 if (r > 0)
1042 log_debug("Following CNAME/DNAME %s %s %s.",
1043 dns_question_first_name(q->question_idna),
1044 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT),
1045 dns_question_first_name(nq_idna));
1047 k = dns_question_is_equal(q->question_idna, q->question_utf8);
1048 if (k < 0)
1049 return k;
1050 if (k > 0) {
1051 /* Same question? Shortcut new question generation */
1052 nq_utf8 = dns_question_ref(nq_idna);
1053 k = r;
1054 } else {
1055 k = dns_question_cname_redirect(q->question_utf8, cname, &nq_utf8);
1056 if (k < 0)
1057 return k;
1058 if (k > 0)
1059 log_debug("Following UTF8 CNAME/DNAME %s %s %s.",
1060 dns_question_first_name(q->question_utf8),
1061 special_glyph(SPECIAL_GLYPH_ARROW_RIGHT),
1062 dns_question_first_name(nq_utf8));
1065 if (r == 0 && k == 0) /* No actual cname happened? */
1066 return -ELOOP;
1068 if (q->answer_protocol == DNS_PROTOCOL_DNS)
1069 /* Don't permit CNAME redirects from unicast DNS to LLMNR or MulticastDNS, so that global resources
1070 * cannot invade the local namespace. The opposite way we permit: local names may redirect to global
1071 * ones. */
1072 q->flags &= ~(SD_RESOLVED_LLMNR|SD_RESOLVED_MDNS); /* mask away the local protocols */
1074 /* Turn off searching for the new name */
1075 q->flags |= SD_RESOLVED_NO_SEARCH;
1077 r = dns_query_collect_question(q, q->question_idna);
1078 if (r < 0)
1079 return r;
1080 r = dns_query_collect_question(q, q->question_utf8);
1081 if (r < 0)
1082 return r;
1084 /* Install the redirected question */
1085 dns_question_unref(q->question_idna);
1086 q->question_idna = TAKE_PTR(nq_idna);
1088 dns_question_unref(q->question_utf8);
1089 q->question_utf8 = TAKE_PTR(nq_utf8);
1091 dns_query_unlink_candidates(q);
1093 /* Note that we do *not* reset the answer here, because the answer we previously got might already
1094 * include everything we need, let's check that first */
1096 q->state = DNS_TRANSACTION_NULL;
1098 return 0;
1101 int dns_query_process_cname_one(DnsQuery *q) {
1102 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *cname = NULL;
1103 DnsQuestion *question;
1104 DnsResourceRecord *rr;
1105 bool full_match = true;
1106 DnsResourceKey *k;
1107 int r;
1109 assert(q);
1111 /* Processes a CNAME redirect if there's one. Returns one of three values:
1113 * CNAME_QUERY_MATCH → direct RR match, caller should just use the RRs in this answer (and not
1114 * bother with any CNAME/DNAME stuff)
1116 * CNAME_QUERY_NOMATCH → no match at all, neither direct nor CNAME/DNAME, caller might decide to
1117 * restart query or take things as NODATA reply.
1119 * CNAME_QUERY_CNAME → no direct RR match, but a CNAME/DNAME match that we now followed for one step.
1121 * The function might also return a failure, in particular -ELOOP if we encountered too many
1122 * CNAMEs/DNAMEs in a chain or if following CNAMEs/DNAMEs was turned off.
1124 * Note that this function doesn't actually restart the query. The caller can decide to do that in
1125 * case of CNAME_QUERY_CNAME, though. */
1127 if (!IN_SET(q->state, DNS_TRANSACTION_SUCCESS, DNS_TRANSACTION_NULL))
1128 return DNS_QUERY_NOMATCH;
1130 question = dns_query_question_for_protocol(q, q->answer_protocol);
1132 /* Small reminder: our question will consist of one or more RR keys that match in name, but not in
1133 * record type. Specifically, when we do an address lookup the question will typically consist of one
1134 * A and one AAAA key lookup for the same domain name. When we get a response from a server we need
1135 * to check if the answer answers all our questions to use it. Note that a response of CNAME/DNAME
1136 * can answer both an A and the AAAA question for us, but an A/AAAA response only the relevant
1137 * type.
1139 * Hence we first check of the answers we collected are sufficient to answer all our questions
1140 * directly. If one question wasn't answered we go on, waiting for more replies. However, if there's
1141 * a CNAME/DNAME response we use it, and redirect to it, regardless if it was a response to the A or
1142 * the AAAA query. */
1144 DNS_QUESTION_FOREACH(k, question) {
1145 bool match = false;
1147 DNS_ANSWER_FOREACH(rr, q->answer) {
1148 r = dns_resource_key_match_rr(k, rr, DNS_SEARCH_DOMAIN_NAME(q->answer_search_domain));
1149 if (r < 0)
1150 return r;
1151 if (r > 0) {
1152 match = true; /* Yay, we found an RR that matches the key we are looking for */
1153 break;
1157 if (!match) {
1158 /* Hmm. :-( there's no response for this key. This doesn't match. */
1159 full_match = false;
1160 break;
1164 if (full_match)
1165 return DNS_QUERY_MATCH; /* The answer can answer our question in full, no need to follow CNAMEs/DNAMEs */
1167 /* Let's see if there is a CNAME/DNAME to match. This case is simpler: we accept the CNAME/DNAME that
1168 * matches any of our questions. */
1169 DNS_ANSWER_FOREACH(rr, q->answer) {
1170 r = dns_question_matches_cname_or_dname(question, rr, DNS_SEARCH_DOMAIN_NAME(q->answer_search_domain));
1171 if (r < 0)
1172 return r;
1173 if (r > 0 && !cname)
1174 cname = dns_resource_record_ref(rr);
1177 if (!cname)
1178 return DNS_QUERY_NOMATCH; /* No match and no CNAME/DNAME to follow */
1180 if (q->flags & SD_RESOLVED_NO_CNAME)
1181 return -ELOOP;
1183 if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
1184 q->previous_redirect_unauthenticated = true;
1185 if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL))
1186 q->previous_redirect_non_confidential = true;
1187 if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_SYNTHETIC))
1188 q->previous_redirect_non_synthetic = true;
1190 /* OK, let's actually follow the CNAME */
1191 r = dns_query_cname_redirect(q, cname);
1192 if (r < 0)
1193 return r;
1195 return DNS_QUERY_CNAME; /* Tell caller that we did a single CNAME/DNAME redirection step */
1198 int dns_query_process_cname_many(DnsQuery *q) {
1199 int r;
1201 assert(q);
1203 /* Follows CNAMEs through the current packet: as long as the current packet can fulfill our
1204 * redirected CNAME queries we keep going, and restart the query once the current packet isn't good
1205 * enough anymore. It's a wrapper around dns_query_process_cname_one() and returns the same values,
1206 * but with extended semantics. Specifically:
1208 * DNS_QUERY_MATCH → as above
1210 * DNS_QUERY_CNAME → we ran into a CNAME/DNAME redirect that we could not answer from the current
1211 * message, and thus restarted the query to resolve it.
1213 * DNS_QUERY_NOMATCH → we reached the end of CNAME/DNAME chain, and there are no direct matches nor a
1214 * CNAME/DNAME match. i.e. this is a NODATA case.
1216 * Note that this function will restart the query for the caller if needed, and that's the case
1217 * DNS_QUERY_CNAME is returned.
1220 r = dns_query_process_cname_one(q);
1221 if (r != DNS_QUERY_CNAME)
1222 return r; /* The first redirect is special: if it doesn't answer the question that's no
1223 * reason to restart the query, we just accept this as a NODATA answer. */
1225 for (;;) {
1226 r = dns_query_process_cname_one(q);
1227 if (r < 0 || r == DNS_QUERY_MATCH)
1228 return r;
1229 if (r == DNS_QUERY_NOMATCH) {
1230 /* OK, so we followed one or more CNAME/DNAME RR but the existing packet can't answer
1231 * this. Let's restart the query hence, with the new question. Why the different
1232 * handling than the first chain element? Because if the server answers a direct
1233 * question with an empty answer then this is a NODATA response. But if it responds
1234 * with a CNAME chain that ultimately is incomplete (i.e. a non-empty but truncated
1235 * CNAME chain) then we better follow up ourselves and ask for the rest of the
1236 * chain. This is particular relevant since our cache will store CNAME/DNAME
1237 * redirects that we learnt about for lookups of certain DNS types, but later on we
1238 * can reuse this data even for other DNS types, but in that case need to follow up
1239 * with the final lookup of the chain ourselves with the RR type we ourselves are
1240 * interested in. */
1241 r = dns_query_go(q);
1242 if (r < 0)
1243 return r;
1245 return DNS_QUERY_CNAME;
1248 /* So we found a CNAME that the existing packet already answers, again via a CNAME, let's
1249 * continue going then. */
1250 assert(r == DNS_QUERY_CNAME);
1254 DnsQuestion* dns_query_question_for_protocol(DnsQuery *q, DnsProtocol protocol) {
1255 assert(q);
1257 if (q->question_bypass)
1258 return q->question_bypass->question;
1260 switch (protocol) {
1262 case DNS_PROTOCOL_DNS:
1263 return q->question_idna;
1265 case DNS_PROTOCOL_MDNS:
1266 case DNS_PROTOCOL_LLMNR:
1267 return q->question_utf8;
1269 default:
1270 return NULL;
1274 const char *dns_query_string(DnsQuery *q) {
1275 const char *name;
1276 int r;
1278 /* Returns a somewhat useful human-readable lookup key string for this query */
1280 if (q->question_bypass)
1281 return dns_question_first_name(q->question_bypass->question);
1283 if (q->request_address_string)
1284 return q->request_address_string;
1286 if (q->request_address_valid) {
1287 r = in_addr_to_string(q->request_family, &q->request_address, &q->request_address_string);
1288 if (r >= 0)
1289 return q->request_address_string;
1292 name = dns_question_first_name(q->question_utf8);
1293 if (name)
1294 return name;
1296 return dns_question_first_name(q->question_idna);
1299 bool dns_query_fully_authenticated(DnsQuery *q) {
1300 assert(q);
1302 return FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) && !q->previous_redirect_unauthenticated;
1305 bool dns_query_fully_confidential(DnsQuery *q) {
1306 assert(q);
1308 return FLAGS_SET(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL) && !q->previous_redirect_non_confidential;
1311 bool dns_query_fully_authoritative(DnsQuery *q) {
1312 assert(q);
1314 /* We are authoritative for everything synthetic (except if a previous CNAME/DNAME) wasn't
1315 * synthetic. (Note: SD_RESOLVED_SYNTHETIC is reset on each CNAME/DNAME, hence the explicit check for
1316 * previous synthetic DNAME/CNAME redirections.) */
1317 if ((q->answer_query_flags & SD_RESOLVED_SYNTHETIC) && !q->previous_redirect_non_synthetic)
1318 return true;
1320 /* We are also authoritative for everything coming only from the trust anchor and the local
1321 * zones. (Note: the SD_RESOLVED_FROM_xyz flags we merge on each redirect, hence no need to
1322 * explicitly check previous redirects here.) */
1323 return (q->answer_query_flags & SD_RESOLVED_FROM_MASK & ~(SD_RESOLVED_FROM_TRUST_ANCHOR | SD_RESOLVED_FROM_ZONE)) == 0;