Debian Codegraph @

src/resolve/resolved-dns-query.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-bus.h"
4 #include "sd-varlink.h"
5
6 #include "alloc-util.h"
7 #include "dns-answer.h"
8 #include "dns-domain.h"
9 #include "dns-packet.h"
10 #include "dns-question.h"
11 #include "dns-rr.h"
12 #include "dns-type.h"
13 #include "event-util.h"
14 #include "glyph-util.h"
15 #include "log.h"
16 #include "resolved-dns-query.h"
17 #include "resolved-dns-scope.h"
18 #include "resolved-dns-search-domain.h"
19 #include "resolved-dns-synthesize.h"
20 #include "resolved-dns-transaction.h"
21 #include "resolved-etc-hosts.h"
22 #include "resolved-hook.h"
23 #include "resolved-manager.h"
24 #include "resolved-static-records.h"
25 #include "resolved-timeouts.h"
26 #include "set.h"
27 #include "string-util.h"
28
29 #define QUERIES_MAX 2048
30 #define AUXILIARY_QUERIES_MAX 64
31 #define CNAME_REDIRECTS_MAX 16
32
33 assert_cc(AUXILIARY_QUERIES_MAX < UINT8_MAX);
34 assert_cc(CNAME_REDIRECTS_MAX < UINT8_MAX);
35
36 static int dns_query_candidate_new(DnsQueryCandidate **ret, DnsQuery *q, DnsScope *s) {
37 DnsQueryCandidate *c;
38
39 assert(ret);
40 assert(q);
41 assert(s);
42
43 c = new(DnsQueryCandidate, 1);
44 if (!c)
45 return -ENOMEM;
46
47 *c = (DnsQueryCandidate) {
48 .n_ref = 1,
49 .query = q,
50 .scope = s,
51 };
52
53 LIST_PREPEND(candidates_by_query, q->candidates, c);
54 LIST_PREPEND(candidates_by_scope, s->query_candidates, c);
55
56 *ret = c;
57 return 0;
58 }
59
60 static void dns_query_candidate_stop(DnsQueryCandidate *c) {
61 DnsTransaction *t;
62
63 assert(c);
64
65 (void) event_source_disable(c->timeout_event_source);
66
67 /* Detach all the DnsTransactions attached to this query */
68
69 while ((t = set_steal_first(c->transactions))) {
70 set_remove(t->notify_query_candidates, c);
71 set_remove(t->notify_query_candidates_done, c);
72 dns_transaction_gc(t);
73 }
74 }
75
76 static void dns_query_candidate_abandon(DnsQueryCandidate *c) {
77 DnsTransaction *t;
78
79 assert(c);
80
81 (void) event_source_disable(c->timeout_event_source);
82
83 /* Abandon all the DnsTransactions attached to this query */
84
85 while ((t = set_steal_first(c->transactions))) {
86 t->wait_for_answer = true;
87 set_remove(t->notify_query_candidates, c);
88 set_remove(t->notify_query_candidates_done, c);
89 dns_transaction_gc(t);
90 }
91 }
92
93 static DnsQueryCandidate* dns_query_candidate_unlink(DnsQueryCandidate *c) {
94 assert(c);
95
96 /* Detach this DnsQueryCandidate from the Query and Scope objects */
97
98 if (c->query) {
99 LIST_REMOVE(candidates_by_query, c->query->candidates, c);
100 c->query = NULL;
101 }
102
103 if (c->scope) {
104 LIST_REMOVE(candidates_by_scope, c->scope->query_candidates, c);
105 c->scope = NULL;
106 }
107
108 return c;
109 }
110
111 static DnsQueryCandidate* dns_query_candidate_free(DnsQueryCandidate *c) {
112 if (!c)
113 return NULL;
114
115 c->timeout_event_source = sd_event_source_disable_unref(c->timeout_event_source);
116
117 dns_query_candidate_stop(c);
118 dns_query_candidate_unlink(c);
119
120 set_free(c->transactions);
121 dns_search_domain_unref(c->search_domain);
122
123 return mfree(c);
124 }
125
126 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(DnsQueryCandidate, dns_query_candidate, dns_query_candidate_free);
127
128 static int dns_query_candidate_next_search_domain(DnsQueryCandidate *c) {
129 DnsSearchDomain *next;
130
131 assert(c);
132
133 if (c->search_domain && c->search_domain->linked)
134 next = c->search_domain->domains_next;
135 else
136 next = dns_scope_get_search_domains(c->scope);
137
138 for (;;) {
139 if (!next) /* We hit the end of the list */
140 return 0;
141
142 if (!next->route_only)
143 break;
144
145 /* Skip over route-only domains */
146 next = next->domains_next;
147 }
148
149 dns_search_domain_unref(c->search_domain);
150 c->search_domain = dns_search_domain_ref(next);
151
152 return 1;
153 }
154
155 static int dns_query_candidate_add_transaction(
156 DnsQueryCandidate *c,
157 DnsResourceKey *key,
158 DnsPacket *bypass) {
159
160 _cleanup_(dns_transaction_gcp) DnsTransaction *t = NULL;
161 int r;
162
163 assert(c);
164 assert(c->query); /* We shan't add transactions to a candidate that has been detached already */
165
166 if (key) {
167 /* Regular lookup with a resource key */
168 assert(!bypass);
169
170 t = dns_scope_find_transaction(c->scope, key, c->query->flags);
171 if (!t) {
172 r = dns_transaction_new(&t, c->scope, key, NULL, c->query->flags);
173 if (r < 0)
174 return r;
175 } else if (set_contains(c->transactions, t))
176 return 0;
177 } else {
178 /* "Bypass" lookup with a query packet */
179 assert(bypass);
180
181 r = dns_transaction_new(&t, c->scope, NULL, bypass, c->query->flags);
182 if (r < 0)
183 return r;
184 }
185
186 r = set_ensure_allocated(&t->notify_query_candidates_done, NULL);
187 if (r < 0)
188 return r;
189
190 r = set_ensure_put(&t->notify_query_candidates, NULL, c);
191 if (r < 0)
192 return r;
193
194 r = set_ensure_put(&c->transactions, NULL, t);
195 if (r < 0) {
196 (void) set_remove(t->notify_query_candidates, c);
197 return r;
198 }
199
200 TAKE_PTR(t);
201 return 1;
202 }
203
204 static int dns_query_candidate_go(DnsQueryCandidate *c) {
205 _unused_ _cleanup_(dns_query_candidate_unrefp) DnsQueryCandidate *keep_c = NULL;
206 DnsTransaction *t;
207 int r;
208 unsigned n = 0;
209
210 assert(c);
211
212 /* Let's keep a reference to the query while we're operating */
213 keep_c = dns_query_candidate_ref(c);
214
215 uint64_t generation = c->generation;
216
217 /* Start the transactions that are not started yet */
218 SET_FOREACH(t, c->transactions) {
219 if (t->state != DNS_TRANSACTION_NULL)
220 continue;
221
222 r = dns_transaction_go(t);
223 if (r < 0)
224 return r;
225
226 if (c->generation != generation)
227 /* The transaction has been completed, and dns_transaction_complete() ->
228 * dns_query_candidate_notify() has been already called. Moreover, the query
229 * candidate has been regenerated, and the query should be already restarted.
230 * Let's exit from the loop now. */
231 return 0;
232
233 n++;
234 }
235
236 /* If there was nothing to start, then let's proceed immediately */
237 if (n == 0)
238 dns_query_candidate_notify(c);
239
240 return 0;
241 }
242
243 static DnsTransactionState dns_query_candidate_state(DnsQueryCandidate *c) {
244 DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
245 DnsTransaction *t;
246
247 assert(c);
248
249 if (c->error_code != 0)
250 return DNS_TRANSACTION_ERRNO;
251
252 SET_FOREACH(t, c->transactions)
253
254 switch (t->state) {
255
256 case DNS_TRANSACTION_NULL:
257 /* If there's a NULL transaction pending, then
258 * this means not all transactions where
259 * started yet, and we were called from within
260 * the stackframe that is supposed to start
261 * remaining transactions. In this case,
262 * simply claim the candidate is pending. */
263
264 case DNS_TRANSACTION_PENDING:
265 case DNS_TRANSACTION_VALIDATING:
266 /* If there's one transaction currently in
267 * VALIDATING state, then this means there's
268 * also one in PENDING state, hence we can
269 * return PENDING immediately. */
270 return DNS_TRANSACTION_PENDING;
271
272 case DNS_TRANSACTION_SUCCESS:
273 state = t->state;
274 break;
275
276 default:
277 if (state != DNS_TRANSACTION_SUCCESS)
278 state = t->state;
279 }
280
281 return state;
282 }
283
284 static int dns_query_candidate_setup_transactions(DnsQueryCandidate *c) {
285 DnsQuestion *question;
286 DnsResourceKey *key;
287 int n = 0, r;
288
289 assert(c);
290 assert(c->query); /* We shan't add transactions to a candidate that has been detached already */
291
292 dns_query_candidate_stop(c);
293
294 c->generation++;
295
296 if (c->query->question_bypass) {
297 /* If this is a bypass query, then pass the original query packet along to the transaction */
298
299 assert(dns_question_size(c->query->question_bypass->question) == 1);
300
301 if (!dns_scope_good_key(c->scope, dns_question_first_key(c->query->question_bypass->question)))
302 return 0;
303
304 r = dns_query_candidate_add_transaction(c, NULL, c->query->question_bypass);
305 if (r < 0)
306 goto fail;
307
308 return 1;
309 }
310
311 question = dns_query_question_for_protocol(c->query, c->scope->protocol);
312
313 /* Create one transaction per question key */
314 DNS_QUESTION_FOREACH(key, question) {
315 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *new_key = NULL;
316 DnsResourceKey *qkey;
317
318 if (c->search_domain) {
319 r = dns_resource_key_new_append_suffix(&new_key, key, c->search_domain->name);
320 if (r < 0)
321 goto fail;
322
323 qkey = new_key;
324 } else
325 qkey = key;
326
327 if (!dns_scope_good_key(c->scope, qkey))
328 continue;
329
330 r = dns_query_candidate_add_transaction(c, qkey, NULL);
331 if (r < 0)
332 goto fail;
333
334 n++;
335 }
336
337 return n;
338
339 fail:
340 dns_query_candidate_stop(c);
341 return r;
342 }
343
344 static void dns_query_accept(DnsQuery *q, DnsQueryCandidate *c);
345
346 static int on_candidate_timeout(sd_event_source *s, usec_t usec, void *userdata) {
347 DnsQueryCandidate *c = userdata;
348
349 assert(s);
350 assert(c);
351
352 log_debug("Accepting incomplete query candidate after expedited timeout on partial success.");
353 dns_query_accept(c->query, c);
354
355 return 0;
356 }
357
358 static bool dns_query_candidate_has_partially_succeeded(DnsQueryCandidate *c) {
359 DnsTransaction *t;
360
361 SET_FOREACH(t, c->transactions)
362 if (t->state == DNS_TRANSACTION_SUCCESS)
363 return true;
364
365 return false;
366 }
367
368 void dns_query_candidate_notify(DnsQueryCandidate *c) {
369 DnsTransactionState state;
370 int r;
371
372 assert(c);
373
374 if (!c->query) /* This candidate has been abandoned, do nothing. */
375 return;
376
377 state = dns_query_candidate_state(c);
378
379 if (DNS_TRANSACTION_IS_LIVE(state)) {
380 if (dns_query_candidate_has_partially_succeeded(c))
381 (void) event_reset_time_relative(
382 c->query->manager->event,
383 &c->timeout_event_source,
384 CLOCK_BOOTTIME,
385 CANDIDATE_EXPEDITED_TIMEOUT_USEC, /* accuracy= */ 0,
386 on_candidate_timeout, c,
387 /* priority= */ 0, "candidate-timeout",
388 /* force_reset= */ false);
389
390 return;
391 }
392
393 if (state != DNS_TRANSACTION_SUCCESS && c->search_domain) {
394
395 (void) event_source_disable(c->timeout_event_source);
396
397 r = dns_query_candidate_next_search_domain(c);
398 if (r < 0)
399 goto fail;
400
401 if (r > 0) {
402 /* OK, there's another search domain to try, let's do so. */
403
404 r = dns_query_candidate_setup_transactions(c);
405 if (r < 0)
406 goto fail;
407
408 if (r > 0) {
409 /* New transactions have been queued. Start them and wait */
410
411 r = dns_query_candidate_go(c);
412 if (r < 0)
413 goto fail;
414
415 return;
416 }
417 }
418
419 }
420
421 dns_query_ready(c->query);
422 return;
423
424 fail:
425 c->error_code = log_warning_errno(r, "Failed to follow search domains: %m");
426 dns_query_ready(c->query);
427 }
428
429 static void dns_query_stop(DnsQuery *q) {
430 assert(q);
431
432 event_source_disable(q->timeout_event_source);
433
434 LIST_FOREACH(candidates_by_query, c, q->candidates)
435 dns_query_candidate_stop(c);
436 }
437
438 static void dns_query_abandon(DnsQuery *q) {
439 assert(q);
440
441 /* Thankfully transactions have their own timeouts */
442 event_source_disable(q->timeout_event_source);
443
444 LIST_FOREACH(candidates_by_query, c, q->candidates)
445 dns_query_candidate_abandon(c);
446 }
447
448 static void dns_query_unlink_candidates(DnsQuery *q) {
449 assert(q);
450
451 while (q->candidates)
452 /* Here we drop *our* references to each of the candidates. If we had the only reference, the
453 * DnsQueryCandidate object will be freed. */
454 dns_query_candidate_unref(dns_query_candidate_unlink(q->candidates));
455 }
456
457 static void dns_query_reset_answer(DnsQuery *q) {
458 assert(q);
459
460 q->answer = dns_answer_unref(q->answer);
461 q->answer_rcode = 0;
462 q->answer_ede_rcode = _DNS_EDE_RCODE_INVALID;
463 q->answer_ede_msg = mfree(q->answer_ede_msg);
464 q->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
465 q->answer_errno = 0;
466 q->answer_query_flags = 0;
467 q->answer_protocol = _DNS_PROTOCOL_INVALID;
468 q->answer_family = AF_UNSPEC;
469 q->answer_search_domain = dns_search_domain_unref(q->answer_search_domain);
470 q->answer_full_packet = dns_packet_unref(q->answer_full_packet);
471 }
472
473 DnsQuery *dns_query_free(DnsQuery *q) {
474 if (!q)
475 return NULL;
476
477 q->timeout_event_source = sd_event_source_disable_unref(q->timeout_event_source);
478
479 while (q->auxiliary_queries)
480 dns_query_free(q->auxiliary_queries);
481
482 if (q->auxiliary_for) {
483 assert(q->auxiliary_for->n_auxiliary_queries > 0);
484 q->auxiliary_for->n_auxiliary_queries--;
485 LIST_REMOVE(auxiliary_queries, q->auxiliary_for->auxiliary_queries, q);
486 }
487
488 dns_query_unlink_candidates(q);
489
490 dns_question_unref(q->question_idna);
491 dns_question_unref(q->question_utf8);
492 dns_packet_unref(q->question_bypass);
493 dns_question_unref(q->collected_questions);
494
495 dns_query_reset_answer(q);
496
497 sd_bus_message_unref(q->bus_request);
498 sd_bus_track_unref(q->bus_track);
499
500 if (q->varlink_request) {
501 sd_varlink_set_userdata(q->varlink_request, NULL);
502 sd_varlink_unref(q->varlink_request);
503 }
504
505 if (q->request_packet)
506 hashmap_remove_value(q->stub_listener_extra ?
507 q->stub_listener_extra->queries_by_packet :
508 q->manager->stub_queries_by_packet,
509 q->request_packet,
510 q);
511
512 dns_packet_unref(q->request_packet);
513 dns_answer_unref(q->reply_answer);
514 dns_answer_unref(q->reply_authoritative);
515 dns_answer_unref(q->reply_additional);
516
517 if (q->request_stream) {
518 /* Detach the stream from our query, in case something else keeps a reference to it. */
519 (void) set_remove(q->request_stream->queries, q);
520 q->request_stream = dns_stream_unref(q->request_stream);
521 }
522
523 free(q->request_address_string);
524
525 dnssd_discovered_service_unref(q->dnsservice_request);
526
527 dns_service_browser_unref(q->service_browser_request);
528
529 hook_query_free(q->hook_query);
530
531 if (q->manager) {
532 LIST_REMOVE(queries, q->manager->dns_queries, q);
533 q->manager->n_dns_queries--;
534 }
535
536 return mfree(q);
537 }
538
539 typedef enum RefuseRecordTypeResult {
540 REFUSE_BAD,
541 REFUSE_GOOD,
542 REFUSE_PARTIAL,
543 } RefuseRecordTypeResult;
544
545 static RefuseRecordTypeResult test_refuse_record_types(Set *refuse_record_types, DnsQuestion *question) {
546 bool has_good = false, has_bad = false;
547 DnsResourceKey *key;
548
549 DNS_QUESTION_FOREACH(key, question)
550 if (set_contains(refuse_record_types, INT_TO_PTR(key->type)))
551 has_bad = true;
552 else
553 has_good = true;
554
555 if (has_bad && !has_good)
556 return REFUSE_BAD;
557 if (!has_bad) {
558 assert(has_good); /* The question should have at least one key. */
559 return REFUSE_GOOD;
560 }
561
562 return REFUSE_PARTIAL;
563 }
564
565 static int manager_validate_and_mangle_question(Manager *manager, DnsQuestion **question, DnsQuestion **ret_allocated) {
566 int r;
567
568 assert(manager);
569 assert(question);
570 assert(ret_allocated);
571
572 if (dns_question_isempty(*question)) {
573 *ret_allocated = NULL;
574 return 0;
575 }
576
577 if (set_isempty(manager->refuse_record_types)) {
578 *ret_allocated = NULL;
579 return 0; /* No filtering configured. Let's shortcut. */
580 }
581
582 RefuseRecordTypeResult result = test_refuse_record_types(manager->refuse_record_types, *question);
583 if (result == REFUSE_BAD)
584 return -ENOANO; /* All bad, refuse. */
585 if (result == REFUSE_GOOD) {
586 *ret_allocated = NULL;
587 return 0; /* All good. Not necessary to filter. */
588 }
589
590 assert(result == REFUSE_PARTIAL);
591
592 /* Mangle the question suppressing bad entries, leaving good entries */
593 _cleanup_(dns_question_unrefp) DnsQuestion *new_question = dns_question_new(dns_question_size(*question));
594 if (!new_question)
595 return -ENOMEM;
596
597 DnsQuestionItem *item;
598 DNS_QUESTION_FOREACH_ITEM(item, *question) {
599 if (set_contains(manager->refuse_record_types, INT_TO_PTR(item->key->type)))
600 continue;
601 r = dns_question_add_raw(new_question, item->key, item->flags);
602 if (r < 0)
603 return r;
604 }
605
606 *question = new_question;
607 *ret_allocated = TAKE_PTR(new_question);
608 return 0;
609 }
610
611 int dns_query_new(
612 Manager *m,
613 DnsQuery **ret,
614 DnsQuestion *question_utf8,
615 DnsQuestion *question_idna,
616 DnsPacket *question_bypass,
617 int ifindex,
618 uint64_t flags) {
619
620 _cleanup_(dns_query_freep) DnsQuery *q = NULL;
621 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
622 DnsResourceKey *key;
623 int r;
624
625 assert(m);
626
627 /* Check for records that is refused and refuse query for the records if matched in configuration */
628 _unused_ _cleanup_(dns_question_unrefp) DnsQuestion *filtered_question_utf8 = NULL;
629 r = manager_validate_and_mangle_question(m, &question_utf8, &filtered_question_utf8);
630 if (r < 0)
631 return r;
632
633 _unused_ _cleanup_(dns_question_unrefp) DnsQuestion *filtered_question_idna = NULL;
634 r = manager_validate_and_mangle_question(m, &question_idna, &filtered_question_idna);
635 if (r < 0)
636 return r;
637
638 if (question_bypass) {
639 /* It's either a "bypass" query, or a regular one, but can't be both. */
640 if (question_utf8 || question_idna)
641 return -EINVAL;
642
643 assert(dns_question_size(question_bypass->question) == 1);
644
645 /* In bypass mode we'll never mangle the question, but only deny or allow. (In bypass mode
646 * there's only going to be one entry in the query, hence there's no point in mangling
647 * questions, i.e. leaving some entries in and removing others.) */
648 if (test_refuse_record_types(m->refuse_record_types, question_bypass->question) != REFUSE_GOOD)
649 return -ENOANO;
650 } else {
651 bool good = false;
652
653 /* This (primarily) checks two things:
654 *
655 * 1. That the question is not empty
656 * 2. That all RR keys in the question objects are for the same domain
657 *
658 * Or in other words, a single DnsQuery object may be used to look up A+AAAA combination for
659 * the same domain name, or SRV+TXT (for DNS-SD services), but not for unrelated lookups. */
660
661 if (dns_question_size(question_utf8) > 0) {
662 r = dns_question_is_valid_for_query(question_utf8);
663 if (r < 0)
664 return r;
665 if (r == 0)
666 return -EINVAL;
667
668 good = true;
669 }
670
671 /* If the IDNA and UTF8 questions are the same, merge their references */
672 r = dns_question_is_equal(question_idna, question_utf8);
673 if (r < 0)
674 return r;
675 if (r > 0)
676 question_idna = question_utf8;
677 else {
678 if (dns_question_size(question_idna) > 0) {
679 r = dns_question_is_valid_for_query(question_idna);
680 if (r < 0)
681 return r;
682 if (r == 0)
683 return -EINVAL;
684
685 good = true;
686 }
687 }
688
689 if (!good) /* don't allow empty queries */
690 return -EINVAL;
691 }
692
693 if (m->n_dns_queries >= QUERIES_MAX)
694 return -EBUSY;
695
696 q = new(DnsQuery, 1);
697 if (!q)
698 return -ENOMEM;
699
700 *q = (DnsQuery) {
701 .question_utf8 = dns_question_ref(question_utf8),
702 .question_idna = dns_question_ref(question_idna),
703 .question_bypass = dns_packet_ref(question_bypass),
704 .ifindex = ifindex,
705 .flags = flags,
706 .answer_ede_rcode = _DNS_EDE_RCODE_INVALID,
707 .answer_dnssec_result = _DNSSEC_RESULT_INVALID,
708 .answer_protocol = _DNS_PROTOCOL_INVALID,
709 .answer_family = AF_UNSPEC,
710 };
711
712 if (question_bypass) {
713 DNS_QUESTION_FOREACH(key, question_bypass->question)
714 log_debug("Looking up bypass packet for %s.",
715 dns_resource_key_to_string(key, key_str, sizeof key_str));
716 } else {
717 /* First dump UTF8 question */
718 DNS_QUESTION_FOREACH(key, question_utf8)
719 log_debug("Looking up RR for %s.",
720 dns_resource_key_to_string(key, key_str, sizeof key_str));
721
722 /* And then dump the IDNA question, but only what hasn't been dumped already through the UTF8 question. */
723 DNS_QUESTION_FOREACH(key, question_idna) {
724 r = dns_question_contains_key(question_utf8, key);
725 if (r < 0)
726 return r;
727 if (r > 0)
728 continue;
729
730 log_debug("Looking up IDNA RR for %s.",
731 dns_resource_key_to_string(key, key_str, sizeof key_str));
732 }
733 }
734
735 LIST_PREPEND(queries, m->dns_queries, q);
736 m->n_dns_queries++;
737 q->manager = m;
738
739 if (ret)
740 *ret = q;
741
742 TAKE_PTR(q);
743 return 0;
744 }
745
746 int dns_query_make_auxiliary(DnsQuery *q, DnsQuery *auxiliary_for) {
747 assert(q);
748 assert(auxiliary_for);
749
750 /* Ensure that the query is not auxiliary yet, and
751 * nothing else is auxiliary to it either */
752 assert(!q->auxiliary_for);
753 assert(!q->auxiliary_queries);
754
755 /* Ensure that the unit we shall be made auxiliary for isn't
756 * auxiliary itself */
757 assert(!auxiliary_for->auxiliary_for);
758
759 if (auxiliary_for->n_auxiliary_queries >= AUXILIARY_QUERIES_MAX)
760 return -EAGAIN;
761
762 LIST_PREPEND(auxiliary_queries, auxiliary_for->auxiliary_queries, q);
763 q->auxiliary_for = auxiliary_for;
764
765 auxiliary_for->n_auxiliary_queries++;
766 return 0;
767 }
768
769 void dns_query_complete(DnsQuery *q, DnsTransactionState state) {
770 assert(q);
771 assert(!DNS_TRANSACTION_IS_LIVE(state));
772 assert(DNS_TRANSACTION_IS_LIVE(q->state));
773
774 /* Note that this call might invalidate the query. Callers should hence not attempt to access the
775 * query or transaction after calling this function. */
776
777 q->state = state;
778
779 (void) manager_monitor_send(q->manager, q);
780
781 dns_query_abandon(q);
782 if (q->complete)
783 q->complete(q);
784 }
785
786 static int on_query_timeout(sd_event_source *s, usec_t usec, void *userdata) {
787 DnsQuery *q = ASSERT_PTR(userdata);
788
789 assert(s);
790
791 dns_query_complete(q, DNS_TRANSACTION_TIMEOUT);
792 return 0;
793 }
794
795 static int dns_query_add_candidate(DnsQuery *q, DnsScope *s) {
796 _cleanup_(dns_query_candidate_unrefp) DnsQueryCandidate *c = NULL;
797 int r;
798
799 assert(q);
800 assert(s);
801
802 r = dns_query_candidate_new(&c, q, s);
803 if (r < 0)
804 return r;
805
806 /* If this a single-label domain on DNS, we might append a suitable search domain first. */
807 if (!FLAGS_SET(q->flags, SD_RESOLVED_NO_SEARCH) &&
808 dns_scope_name_wants_search_domain(s, dns_question_first_name(q->question_idna))) {
809 /* OK, we want a search domain now. Let's find one for this scope */
810
811 r = dns_query_candidate_next_search_domain(c);
812 if (r < 0)
813 return r;
814 }
815
816 r = dns_query_candidate_setup_transactions(c);
817 if (r < 0)
818 return r;
819
820 TAKE_PTR(c);
821 return 0;
822 }
823
824 static int dns_query_synthesize_reply(DnsQuery *q, DnsTransactionState *state) {
825 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
826 int r;
827
828 assert(q);
829 assert(state);
830
831 /* Tries to synthesize localhost RR replies (and others) where appropriate. Note that this is done *after* the
832 * the normal lookup finished. The data from the network hence takes precedence over the data we
833 * synthesize. (But note that many scopes refuse to resolve certain domain names) */
834
835 if (!IN_SET(*state,
836 DNS_TRANSACTION_RCODE_FAILURE,
837 DNS_TRANSACTION_NO_SERVERS,
838 DNS_TRANSACTION_TIMEOUT,
839 DNS_TRANSACTION_ATTEMPTS_MAX_REACHED,
840 DNS_TRANSACTION_NETWORK_DOWN,
841 DNS_TRANSACTION_NOT_FOUND))
842 return 0;
843
844 if (FLAGS_SET(q->flags, SD_RESOLVED_NO_SYNTHESIZE))
845 return 0;
846
847 r = dns_synthesize_answer(
848 q->manager,
849 q->question_bypass ? q->question_bypass->question : q->question_utf8,
850 q->ifindex,
851 &answer);
852 if (r == -ENXIO) {
853 /* If we get ENXIO this tells us to generate NXDOMAIN unconditionally. */
854
855 dns_query_reset_answer(q);
856 q->answer_rcode = DNS_RCODE_NXDOMAIN;
857 q->answer_protocol = dns_synthesize_protocol(q->flags);
858 q->answer_family = dns_synthesize_family(q->flags);
859 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
860 *state = DNS_TRANSACTION_RCODE_FAILURE;
861
862 log_debug("Found synthetic NXDOMAIN response.");
863
864 return 0;
865 }
866 if (r <= 0)
867 return r;
868
869 dns_query_reset_answer(q);
870
871 q->answer = TAKE_PTR(answer);
872 q->answer_rcode = DNS_RCODE_SUCCESS;
873 q->answer_protocol = dns_synthesize_protocol(q->flags);
874 q->answer_family = dns_synthesize_family(q->flags);
875 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
876
877 *state = DNS_TRANSACTION_SUCCESS;
878
879 log_debug("Found synthetic success response.");
880
881 return 1;
882 }
883
884 static int dns_query_try_etc_hosts(DnsQuery *q) {
885 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
886 int r;
887
888 assert(q);
889
890 /* Looks in /etc/hosts for matching entries. Note that this is done *before* the normal lookup is
891 * done. The data from /etc/hosts hence takes precedence over the network. */
892
893 if (FLAGS_SET(q->flags, SD_RESOLVED_NO_SYNTHESIZE))
894 return 0;
895
896 r = manager_etc_hosts_lookup(
897 q->manager,
898 q->question_bypass ? q->question_bypass->question : q->question_utf8,
899 &answer);
900 if (r <= 0)
901 return r;
902
903 dns_query_reset_answer(q);
904
905 q->answer = TAKE_PTR(answer);
906 q->answer_rcode = DNS_RCODE_SUCCESS;
907 q->answer_protocol = dns_synthesize_protocol(q->flags);
908 q->answer_family = dns_synthesize_family(q->flags);
909 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
910
911 return 1;
912 }
913
914 static int dns_query_try_static_records(DnsQuery *q) {
915 int r;
916
917 assert(q);
918
919 if (FLAGS_SET(q->flags, SD_RESOLVED_NO_SYNTHESIZE))
920 return 0;
921
922 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
923 r = manager_static_records_lookup(
924 q->manager,
925 q->question_bypass ? q->question_bypass->question : q->question_utf8,
926 &answer);
927 if (r <= 0)
928 return r;
929
930 dns_query_reset_answer(q);
931
932 q->answer = TAKE_PTR(answer);
933 q->answer_rcode = DNS_RCODE_SUCCESS;
934 q->answer_protocol = dns_synthesize_protocol(q->flags);
935 q->answer_family = dns_synthesize_family(q->flags);
936 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
937
938 return 1;
939 }
940
941 static int dns_query_go_scopes(DnsQuery *q) {
942 int r;
943
944 assert(q);
945 assert(!q->hook_query);
946 assert(q->state == DNS_TRANSACTION_NULL);
947
948 /* Start the lookup via the scopes */
949
950 DnsScopeMatch found = DNS_SCOPE_NO;
951 DnsScope *first = NULL;
952 LIST_FOREACH(scopes, s, q->manager->dns_scopes) {
953 DnsScopeMatch match;
954
955 match = dns_scope_good_domain(s, q, q->flags);
956 assert(match >= 0);
957 if (match > found) { /* Does this match better? If so, remember how well it matched, and the first one
958 * that matches this well */
959 found = match;
960 first = s;
961 }
962 }
963
964 if (found == DNS_SCOPE_NO) {
965 DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
966
967 r = dns_query_synthesize_reply(q, &state);
968 if (r < 0)
969 return r;
970
971 dns_query_complete(q, state);
972 return 1;
973 }
974
975 r = dns_query_add_candidate(q, first);
976 if (r < 0)
977 goto fail;
978
979 LIST_FOREACH(scopes, s, first->scopes_next) {
980 DnsScopeMatch match;
981
982 match = dns_scope_good_domain(s, q, q->flags);
983 assert(match >= 0);
984 if (match < found)
985 continue;
986
987 r = dns_query_add_candidate(q, s);
988 if (r < 0)
989 goto fail;
990 }
991
992 dns_query_reset_answer(q);
993
994 r = event_reset_time_relative(
995 q->manager->event,
996 &q->timeout_event_source,
997 CLOCK_BOOTTIME,
998 SD_RESOLVED_QUERY_TIMEOUT_USEC,
999 0, on_query_timeout, q,
1000 0, "query-timeout", true);
1001 if (r < 0)
1002 goto fail;
1003
1004 q->state = DNS_TRANSACTION_PENDING;
1005 q->block_ready++;
1006
1007 /* Start the transactions */
1008 LIST_FOREACH(candidates_by_query, c, q->candidates) {
1009 r = dns_query_candidate_go(c);
1010 if (r < 0) {
1011 q->block_ready--;
1012 goto fail;
1013 }
1014 }
1015
1016 q->block_ready--;
1017 dns_query_ready(q);
1018
1019 return 1;
1020
1021 fail:
1022 dns_query_stop(q);
1023 return r;
1024 }
1025
1026 static void on_hook_complete(HookQuery *hq, int rcode, DnsAnswer *answer, void *userdata) {
1027 DnsQuery *q = ASSERT_PTR(userdata);
1028 int r;
1029
1030 assert(hq);
1031 assert(q->hook_query == hq);
1032 assert(q->state == DNS_TRANSACTION_NULL);
1033
1034 q->hook_query = hook_query_free(q->hook_query);
1035 TAKE_PTR(hq);
1036
1037 if (rcode < 0) {
1038 log_debug("Hook yielded no results, proceeding.");
1039 r = dns_query_go_scopes(q);
1040 if (r < 0) {
1041 dns_query_reset_answer(q);
1042 q->answer_errno = r;
1043 dns_query_complete(q, DNS_TRANSACTION_ERRNO);
1044 }
1045
1046 return;
1047 }
1048
1049 dns_query_reset_answer(q);
1050
1051 q->answer = dns_answer_ref(answer);
1052 q->answer_rcode = rcode;
1053 q->answer_protocol = dns_synthesize_protocol(q->flags);
1054 q->answer_family = dns_synthesize_family(q->flags);
1055 q->answer_query_flags = SD_RESOLVED_FROM_HOOK;
1056 dns_query_complete(q, rcode == DNS_RCODE_SUCCESS ? DNS_TRANSACTION_SUCCESS : DNS_TRANSACTION_RCODE_FAILURE);
1057 }
1058
1059 int dns_query_go(DnsQuery *q) {
1060 int r;
1061
1062 assert(q);
1063
1064 /* Already ongoing? Then suppress */
1065 if (q->hook_query ||
1066 q->state != DNS_TRANSACTION_NULL)
1067 return 0;
1068
1069 r = dns_query_try_static_records(q);
1070 if (r < 0)
1071 return r;
1072 if (r > 0) {
1073 dns_query_complete(q, DNS_TRANSACTION_SUCCESS);
1074 return 1;
1075 }
1076
1077 r = dns_query_try_etc_hosts(q);
1078 if (r < 0)
1079 return r;
1080 if (r > 0) {
1081 dns_query_complete(q, DNS_TRANSACTION_SUCCESS);
1082 return 1;
1083 }
1084
1085 r = manager_hook_query(
1086 q->manager,
1087 q->question_bypass ? q->question_bypass->question : q->question_idna,
1088 q->question_bypass ? q->question_bypass->question : q->question_utf8,
1089 on_hook_complete,
1090 q,
1091 &q->hook_query);
1092 if (r < 0)
1093 return r;
1094 if (r > 0) /* hook calls are pending */
1095 return 0;
1096
1097 return dns_query_go_scopes(q);
1098 }
1099
1100 static void dns_query_accept(DnsQuery *q, DnsQueryCandidate *c) {
1101 DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
1102 bool has_authenticated = false, has_non_authenticated = false, has_confidential = false, has_non_confidential = false;
1103 DnssecResult dnssec_result_authenticated = _DNSSEC_RESULT_INVALID, dnssec_result_non_authenticated = _DNSSEC_RESULT_INVALID;
1104 DnsTransaction *t;
1105 int r;
1106
1107 assert(q);
1108
1109 if (!c) {
1110 r = dns_query_synthesize_reply(q, &state);
1111 if (r < 0)
1112 goto fail;
1113
1114 dns_query_complete(q, state);
1115 return;
1116 }
1117
1118 if (c->error_code != 0) {
1119 /* If the candidate had an error condition of its own, start with that. */
1120 state = DNS_TRANSACTION_ERRNO;
1121 q->answer = dns_answer_unref(q->answer);
1122 q->answer_rcode = 0;
1123 q->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
1124 q->answer_query_flags = 0;
1125 q->answer_errno = c->error_code;
1126 q->answer_full_packet = dns_packet_unref(q->answer_full_packet);
1127 }
1128
1129 SET_FOREACH(t, c->transactions) {
1130
1131 switch (t->state) {
1132
1133 case DNS_TRANSACTION_SUCCESS: {
1134 /* We found a successful reply, merge it into the answer */
1135
1136 if (state == DNS_TRANSACTION_SUCCESS) {
1137 r = dns_answer_extend(&q->answer, t->answer);
1138 if (r < 0)
1139 goto fail;
1140
1141 q->answer_query_flags |= dns_transaction_source_to_query_flags(t->answer_source);
1142 } else {
1143 /* Override non-successful previous answers */
1144 DNS_ANSWER_REPLACE(q->answer, dns_answer_ref(t->answer));
1145 q->answer_query_flags = dns_transaction_source_to_query_flags(t->answer_source);
1146 }
1147
1148 q->answer_rcode = t->answer_rcode;
1149 q->answer_errno = 0;
1150
1151 DNS_PACKET_REPLACE(q->answer_full_packet, dns_packet_ref(t->received));
1152
1153 if (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED)) {
1154 has_authenticated = true;
1155 dnssec_result_authenticated = t->answer_dnssec_result;
1156 } else {
1157 has_non_authenticated = true;
1158 dnssec_result_non_authenticated = t->answer_dnssec_result;
1159 }
1160
1161 if (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL))
1162 has_confidential = true;
1163 else
1164 has_non_confidential = true;
1165
1166 state = DNS_TRANSACTION_SUCCESS;
1167 break;
1168 }
1169
1170 case DNS_TRANSACTION_NULL:
1171 case DNS_TRANSACTION_PENDING:
1172 case DNS_TRANSACTION_VALIDATING:
1173 case DNS_TRANSACTION_ABORTED:
1174 /* Ignore transactions that didn't complete */
1175 continue;
1176
1177 default:
1178 /* Any kind of failure? Store the data away, if there's nothing stored yet. */
1179 if (state == DNS_TRANSACTION_SUCCESS)
1180 continue;
1181
1182 /* If there's already an authenticated negative reply stored, then prefer that over any unauthenticated one */
1183 if (FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) &&
1184 !FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
1185 continue;
1186
1187 DNS_ANSWER_REPLACE(q->answer, dns_answer_ref(t->answer));
1188 q->answer_rcode = t->answer_rcode;
1189 q->answer_ede_rcode = t->answer_ede_rcode;
1190 r = free_and_strdup_warn(&q->answer_ede_msg, t->answer_ede_msg);
1191 if (r < 0)
1192 goto fail;
1193 q->answer_dnssec_result = t->answer_dnssec_result;
1194 q->answer_query_flags = t->answer_query_flags | dns_transaction_source_to_query_flags(t->answer_source);
1195 q->answer_errno = t->answer_errno;
1196 DNS_PACKET_REPLACE(q->answer_full_packet, dns_packet_ref(t->received));
1197
1198 state = t->state;
1199 }
1200 }
1201
1202 if (state == DNS_TRANSACTION_SUCCESS) {
1203 SET_FLAG(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED, has_authenticated && !has_non_authenticated);
1204 SET_FLAG(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL, has_confidential && !has_non_confidential);
1205 q->answer_dnssec_result = FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) ? dnssec_result_authenticated : dnssec_result_non_authenticated;
1206 }
1207
1208 q->answer_protocol = c->scope->protocol;
1209 q->answer_family = c->scope->family;
1210
1211 dns_search_domain_unref(q->answer_search_domain);
1212 q->answer_search_domain = dns_search_domain_ref(c->search_domain);
1213
1214 r = dns_query_synthesize_reply(q, &state);
1215 if (r < 0)
1216 goto fail;
1217
1218 dns_query_complete(q, state);
1219 return;
1220
1221 fail:
1222 q->answer_errno = -r;
1223 dns_query_complete(q, DNS_TRANSACTION_ERRNO);
1224 }
1225
1226 void dns_query_ready(DnsQuery *q) {
1227 DnsQueryCandidate *bad = NULL;
1228 bool pending = false;
1229
1230 assert(q);
1231 assert(DNS_TRANSACTION_IS_LIVE(q->state));
1232
1233 /* Note that this call might invalidate the query. Callers
1234 * should hence not attempt to access the query or transaction
1235 * after calling this function, unless the block_ready
1236 * counter was explicitly bumped before doing so. */
1237
1238 if (q->hook_query)
1239 return;
1240
1241 if (q->block_ready > 0)
1242 return;
1243
1244 LIST_FOREACH(candidates_by_query, c, q->candidates) {
1245 DnsTransactionState state;
1246
1247 state = dns_query_candidate_state(c);
1248 switch (state) {
1249
1250 case DNS_TRANSACTION_SUCCESS:
1251 /* One of the candidates is successful,
1252 * let's use it, and copy its data out */
1253 dns_query_accept(q, c);
1254 return;
1255
1256 case DNS_TRANSACTION_NULL:
1257 case DNS_TRANSACTION_PENDING:
1258 case DNS_TRANSACTION_VALIDATING:
1259 /* One of the candidates is still going on,
1260 * let's maybe wait for it */
1261 pending = true;
1262 break;
1263
1264 default:
1265 /* Any kind of failure: save the most recent error, as long as we never saved one
1266 * before or our current one is "conclusive" in the sense that we definitely did a
1267 * lookup, and thus have a real answer (which might be a failure, but is still *some*
1268 * answer). */
1269
1270 if (!bad || !IN_SET(state, DNS_TRANSACTION_NO_SERVERS, DNS_TRANSACTION_NETWORK_DOWN, DNS_TRANSACTION_NO_SOURCE))
1271 bad = c;
1272 break;
1273 }
1274 }
1275
1276 if (pending)
1277 return;
1278
1279 dns_query_accept(q, bad);
1280 }
1281
1282 static int dns_query_collect_question(DnsQuery *q, DnsQuestion *question) {
1283 _cleanup_(dns_question_unrefp) DnsQuestion *merged = NULL;
1284 int r;
1285
1286 assert(q);
1287
1288 if (dns_question_size(question) == 0)
1289 return 0;
1290
1291 /* When redirecting, save the first element in the chain, for informational purposes when monitoring */
1292 r = dns_question_merge(q->collected_questions, question, &merged);
1293 if (r < 0)
1294 return r;
1295
1296 dns_question_unref(q->collected_questions);
1297 q->collected_questions = TAKE_PTR(merged);
1298
1299 return 0;
1300 }
1301
1302 static int dns_query_cname_redirect(DnsQuery *q, const DnsResourceRecord *cname) {
1303 _cleanup_(dns_question_unrefp) DnsQuestion *nq_idna = NULL, *nq_utf8 = NULL;
1304 int r, k;
1305
1306 assert(q);
1307
1308 if (q->n_cname_redirects >= CNAME_REDIRECTS_MAX)
1309 return -ELOOP;
1310 q->n_cname_redirects++;
1311
1312 r = dns_question_cname_redirect(q->question_idna, cname, &nq_idna);
1313 if (r < 0)
1314 return r;
1315 if (r > 0)
1316 log_debug("Following CNAME/DNAME %s %s %s.",
1317 dns_question_first_name(q->question_idna),
1318 glyph(GLYPH_ARROW_RIGHT),
1319 dns_question_first_name(nq_idna));
1320
1321 k = dns_question_is_equal(q->question_idna, q->question_utf8);
1322 if (k < 0)
1323 return k;
1324 if (k > 0) {
1325 /* Same question? Shortcut new question generation */
1326 nq_utf8 = dns_question_ref(nq_idna);
1327 k = r;
1328 } else {
1329 k = dns_question_cname_redirect(q->question_utf8, cname, &nq_utf8);
1330 if (k < 0)
1331 return k;
1332 if (k > 0)
1333 log_debug("Following UTF8 CNAME/DNAME %s %s %s.",
1334 dns_question_first_name(q->question_utf8),
1335 glyph(GLYPH_ARROW_RIGHT),
1336 dns_question_first_name(nq_utf8));
1337 }
1338
1339 if (r == 0 && k == 0) /* No actual cname happened? */
1340 return -ELOOP;
1341
1342 if (q->answer_protocol == DNS_PROTOCOL_DNS)
1343 /* Don't permit CNAME redirects from unicast DNS to LLMNR or MulticastDNS, so that global resources
1344 * cannot invade the local namespace. The opposite way we permit: local names may redirect to global
1345 * ones. */
1346 q->flags &= ~(SD_RESOLVED_LLMNR|SD_RESOLVED_MDNS); /* mask away the local protocols */
1347
1348 /* Turn off searching for the new name */
1349 q->flags |= SD_RESOLVED_NO_SEARCH;
1350
1351 r = dns_query_collect_question(q, q->question_idna);
1352 if (r < 0)
1353 return r;
1354 r = dns_query_collect_question(q, q->question_utf8);
1355 if (r < 0)
1356 return r;
1357
1358 /* Install the redirected question */
1359 dns_question_unref(q->question_idna);
1360 q->question_idna = TAKE_PTR(nq_idna);
1361
1362 dns_question_unref(q->question_utf8);
1363 q->question_utf8 = TAKE_PTR(nq_utf8);
1364
1365 dns_query_unlink_candidates(q);
1366
1367 /* Note that we do *not* reset the answer here, because the answer we previously got might already
1368 * include everything we need, let's check that first */
1369
1370 q->state = DNS_TRANSACTION_NULL;
1371
1372 return 0;
1373 }
1374
1375 int dns_query_process_cname_one(DnsQuery *q) {
1376 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *cname = NULL;
1377 DnsQuestion *question;
1378 DnsResourceRecord *rr;
1379 bool full_match = true;
1380 DnsResourceKey *k;
1381 int r;
1382
1383 assert(q);
1384
1385 /* Processes a CNAME redirect if there's one. Returns one of three values:
1386 *
1387 * CNAME_QUERY_MATCH → direct RR match, caller should just use the RRs in this answer (and not
1388 * bother with any CNAME/DNAME stuff)
1389 *
1390 * CNAME_QUERY_NOMATCH → no match at all, neither direct nor CNAME/DNAME, caller might decide to
1391 * restart query or take things as NODATA reply.
1392 *
1393 * CNAME_QUERY_CNAME → no direct RR match, but a CNAME/DNAME match that we now followed for one step.
1394 *
1395 * The function might also return a failure, in particular -ELOOP if we encountered too many
1396 * CNAMEs/DNAMEs in a chain or if following CNAMEs/DNAMEs was turned off.
1397 *
1398 * Note that this function doesn't actually restart the query. The caller can decide to do that in
1399 * case of CNAME_QUERY_CNAME, though. */
1400
1401 if (!IN_SET(q->state, DNS_TRANSACTION_SUCCESS, DNS_TRANSACTION_NULL))
1402 return DNS_QUERY_NOMATCH;
1403
1404 question = dns_query_question_for_protocol(q, q->answer_protocol);
1405
1406 /* Small reminder: our question will consist of one or more RR keys that match in name, but not in
1407 * record type. Specifically, when we do an address lookup the question will typically consist of one
1408 * A and one AAAA key lookup for the same domain name. When we get a response from a server we need
1409 * to check if the answer answers all our questions to use it. Note that a response of CNAME/DNAME
1410 * can answer both an A and the AAAA question for us, but an A/AAAA response only the relevant
1411 * type.
1412 *
1413 * Hence we first check of the answers we collected are sufficient to answer all our questions
1414 * directly. If one question wasn't answered we go on, waiting for more replies. However, if there's
1415 * a CNAME/DNAME response we use it, and redirect to it, regardless if it was a response to the A or
1416 * the AAAA query. */
1417
1418 DNS_QUESTION_FOREACH(k, question) {
1419 bool match = false;
1420
1421 DNS_ANSWER_FOREACH(rr, q->answer) {
1422 r = dns_resource_key_match_rr(k, rr, DNS_SEARCH_DOMAIN_NAME(q->answer_search_domain));
1423 if (r < 0)
1424 return r;
1425 if (r > 0) {
1426 match = true; /* Yay, we found an RR that matches the key we are looking for */
1427 break;
1428 }
1429 }
1430
1431 if (!match) {
1432 /* Hmm. :-( there's no response for this key. This doesn't match. */
1433 full_match = false;
1434 break;
1435 }
1436 }
1437
1438 if (full_match)
1439 return DNS_QUERY_MATCH; /* The answer can answer our question in full, no need to follow CNAMEs/DNAMEs */
1440
1441 /* Let's see if there is a CNAME/DNAME to match. This case is simpler: we accept the CNAME/DNAME that
1442 * matches any of our questions. */
1443 DNS_ANSWER_FOREACH(rr, q->answer) {
1444 r = dns_question_matches_cname_or_dname(question, rr, DNS_SEARCH_DOMAIN_NAME(q->answer_search_domain));
1445 if (r < 0)
1446 return r;
1447 if (r > 0 && !cname)
1448 cname = dns_resource_record_ref(rr);
1449 }
1450
1451 if (!cname)
1452 return DNS_QUERY_NOMATCH; /* No match and no CNAME/DNAME to follow */
1453
1454 if (q->flags & SD_RESOLVED_NO_CNAME)
1455 return -ELOOP;
1456
1457 if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
1458 q->previous_redirect_unauthenticated = true;
1459 if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL))
1460 q->previous_redirect_non_confidential = true;
1461 if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_SYNTHETIC))
1462 q->previous_redirect_non_synthetic = true;
1463
1464 /* OK, let's actually follow the CNAME */
1465 r = dns_query_cname_redirect(q, cname);
1466 if (r < 0)
1467 return r;
1468
1469 return DNS_QUERY_CNAME; /* Tell caller that we did a single CNAME/DNAME redirection step */
1470 }
1471
1472 int dns_query_process_cname_many(DnsQuery *q) {
1473 int r;
1474
1475 assert(q);
1476
1477 /* Follows CNAMEs through the current packet: as long as the current packet can fulfill our
1478 * redirected CNAME queries we keep going, and restart the query once the current packet isn't good
1479 * enough anymore. It's a wrapper around dns_query_process_cname_one() and returns the same values,
1480 * but with extended semantics. Specifically:
1481 *
1482 * DNS_QUERY_MATCH → as above
1483 *
1484 * DNS_QUERY_CNAME → we ran into a CNAME/DNAME redirect that we could not answer from the current
1485 * message, and thus restarted the query to resolve it.
1486 *
1487 * DNS_QUERY_NOMATCH → we reached the end of CNAME/DNAME chain, and there are no direct matches nor a
1488 * CNAME/DNAME match. i.e. this is a NODATA case.
1489 *
1490 * Note that this function will restart the query for the caller if needed, and that's the case
1491 * DNS_QUERY_CNAME is returned.
1492 */
1493
1494 r = dns_query_process_cname_one(q);
1495 if (r != DNS_QUERY_CNAME)
1496 return r; /* The first redirect is special: if it doesn't answer the question that's no
1497 * reason to restart the query, we just accept this as a NODATA answer. */
1498
1499 for (;;) {
1500 r = dns_query_process_cname_one(q);
1501 if (r < 0 || r == DNS_QUERY_MATCH)
1502 return r;
1503 if (r == DNS_QUERY_NOMATCH) {
1504 /* OK, so we followed one or more CNAME/DNAME RR but the existing packet can't answer
1505 * this. Let's restart the query hence, with the new question. Why the different
1506 * handling than the first chain element? Because if the server answers a direct
1507 * question with an empty answer then this is a NODATA response. But if it responds
1508 * with a CNAME chain that ultimately is incomplete (i.e. a non-empty but truncated
1509 * CNAME chain) then we better follow up ourselves and ask for the rest of the
1510 * chain. This is particular relevant since our cache will store CNAME/DNAME
1511 * redirects that we learnt about for lookups of certain DNS types, but later on we
1512 * can reuse this data even for other DNS types, but in that case need to follow up
1513 * with the final lookup of the chain ourselves with the RR type we ourselves are
1514 * interested in. */
1515 r = dns_query_go(q);
1516 if (r < 0)
1517 return r;
1518
1519 return DNS_QUERY_CNAME;
1520 }
1521
1522 /* So we found a CNAME that the existing packet already answers, again via a CNAME, let's
1523 * continue going then. */
1524 assert(r == DNS_QUERY_CNAME);
1525 }
1526 }
1527
1528 DnsQuestion* dns_query_question_for_protocol(DnsQuery *q, DnsProtocol protocol) {
1529 assert(q);
1530
1531 if (q->question_bypass)
1532 return q->question_bypass->question;
1533
1534 switch (protocol) {
1535
1536 case DNS_PROTOCOL_DNS:
1537 return q->question_idna;
1538
1539 case DNS_PROTOCOL_MDNS:
1540 case DNS_PROTOCOL_LLMNR:
1541 return q->question_utf8;
1542
1543 default:
1544 return NULL;
1545 }
1546 }
1547
1548 const char* dns_query_string(DnsQuery *q) {
1549 const char *name;
1550 int r;
1551
1552 /* Returns a somewhat useful human-readable lookup key string for this query */
1553
1554 if (q->question_bypass)
1555 return dns_question_first_name(q->question_bypass->question);
1556
1557 if (q->request_address_string)
1558 return q->request_address_string;
1559
1560 if (q->request_address_valid) {
1561 r = in_addr_to_string(q->request_family, &q->request_address, &q->request_address_string);
1562 if (r >= 0)
1563 return q->request_address_string;
1564 }
1565
1566 name = dns_question_first_name(q->question_utf8);
1567 if (name)
1568 return name;
1569
1570 return dns_question_first_name(q->question_idna);
1571 }
1572
1573 bool dns_query_fully_authenticated(DnsQuery *q) {
1574 assert(q);
1575
1576 return FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) && !q->previous_redirect_unauthenticated;
1577 }
1578
1579 bool dns_query_fully_confidential(DnsQuery *q) {
1580 assert(q);
1581
1582 return FLAGS_SET(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL) && !q->previous_redirect_non_confidential;
1583 }
1584
1585 bool dns_query_fully_authoritative(DnsQuery *q) {
1586 assert(q);
1587
1588 /* We are authoritative for everything synthetic (except if a previous CNAME/DNAME) wasn't
1589 * synthetic. (Note: SD_RESOLVED_SYNTHETIC is reset on each CNAME/DNAME, hence the explicit check for
1590 * previous synthetic DNAME/CNAME redirections.) */
1591 if ((q->answer_query_flags & SD_RESOLVED_SYNTHETIC) && !q->previous_redirect_non_synthetic)
1592 return true;
1593
1594 /* We are also authoritative for everything coming only from the trust anchor and the local
1595 * zones. (Note: the SD_RESOLVED_FROM_xyz flags we merge on each redirect, hence no need to
1596 * explicitly check previous redirects here.) */
1597 return (q->answer_query_flags & SD_RESOLVED_FROM_MASK & ~(SD_RESOLVED_FROM_TRUST_ANCHOR | SD_RESOLVED_FROM_ZONE)) == 0;
1598 }
1599
1600 int validate_and_mangle_query_flags(
1601 Manager *manager,
1602 uint64_t *flags,
1603 const char *name,
1604 uint64_t ok) {
1605
1606 assert(manager);
1607 assert(flags);
1608
1609 /* Checks that the client supplied interface index and flags parameter actually are valid and make
1610 * sense in our method call context. Specifically:
1611 *
1612 * 1. Checks that the interface index is either 0 (meaning *all* interfaces) or positive
1613 *
1614 * 2. Only the protocols flags and a bunch of NO_XYZ flags are set, at most. Plus additional flags
1615 * specific to our method, passed in the "ok" parameter.
1616 *
1617 * 3. If zero protocol flags are specified it is automatically turned into *all* protocols. This way
1618 * clients can simply pass 0 as flags and all will work as it should. They can also use this so
1619 * that clients don't have to know all the protocols resolved implements, but can just specify 0
1620 * to mean "all supported protocols".
1621 */
1622
1623 if (*flags & ~(SD_RESOLVED_PROTOCOLS_ALL|
1624 SD_RESOLVED_NO_CNAME|
1625 SD_RESOLVED_NO_VALIDATE|
1626 SD_RESOLVED_NO_SYNTHESIZE|
1627 SD_RESOLVED_NO_CACHE|
1628 SD_RESOLVED_NO_ZONE|
1629 SD_RESOLVED_NO_TRUST_ANCHOR|
1630 SD_RESOLVED_NO_NETWORK|
1631 SD_RESOLVED_NO_STALE|
1632 SD_RESOLVED_RELAX_SINGLE_LABEL|
1633 ok))
1634 return -EINVAL;
1635
1636 if ((*flags & SD_RESOLVED_PROTOCOLS_ALL) == 0) /* If no protocol is enabled, enable all */
1637 *flags |= SD_RESOLVED_PROTOCOLS_ALL;
1638
1639 /* Imply SD_RESOLVED_NO_SEARCH if permitted and name is dot suffixed. */
1640 if (name && FLAGS_SET(ok, SD_RESOLVED_NO_SEARCH) && dns_name_dot_suffixed(name) > 0)
1641 *flags |= SD_RESOLVED_NO_SEARCH;
1642
1643 /* If both A and AAAA are refused, set SD_RESOLVED_NO_ADDRESS flag if it is allowed. */
1644 if (set_contains(manager->refuse_record_types, INT_TO_PTR(DNS_TYPE_A)) &&
1645 set_contains(manager->refuse_record_types, INT_TO_PTR(DNS_TYPE_AAAA)) &&
1646 FLAGS_SET(ok, SD_RESOLVED_NO_ADDRESS))
1647 *flags |= SD_RESOLVED_NO_ADDRESS;
1648
1649 /* Similarly, if TXT is refused, set SD_RESOLVED_NO_TXT flag if it is allowed. */
1650 if (set_contains(manager->refuse_record_types, INT_TO_PTR(DNS_TYPE_TXT)) &&
1651 FLAGS_SET(ok, SD_RESOLVED_NO_TXT))
1652 *flags |= SD_RESOLVED_NO_TXT;
1653
1654 return 0;
1655 }
1656
1657 uint64_t dns_query_reply_flags_make(DnsQuery *q) {
1658 assert(q);
1659
1660 return SD_RESOLVED_FLAGS_MAKE(q->answer_protocol,
1661 q->answer_family,
1662 dns_query_fully_authenticated(q),
1663 dns_query_fully_confidential(q)) |
1664 (q->answer_query_flags & (SD_RESOLVED_FROM_MASK|SD_RESOLVED_SYNTHETIC));
1665 }