1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include "alloc-util.h"
4 #include "dns-domain.h"
5 #include "dns-type.h"
6 #include "event-util.h"
7 #include "hostname-util.h"
8 #include "local-addresses.h"
9 #include "resolved-dns-query.h"
10 #include "resolved-dns-synthesize.h"
11 #include "resolved-etc-hosts.h"
12 #include "string-util.h"
13 
14 #define QUERIES_MAX 2048
15 #define AUXILIARY_QUERIES_MAX 64
16 #define CNAME_REDIRECTS_MAX 16
17 
18 assert_cc(AUXILIARY_QUERIES_MAX < UINT8_MAX);
19 assert_cc(CNAME_REDIRECTS_MAX < UINT8_MAX);
20 
dns_query_candidate_new(DnsQueryCandidate ** ret,DnsQuery * q,DnsScope * s)21 static int dns_query_candidate_new(DnsQueryCandidate **ret, DnsQuery *q, DnsScope *s) {
22         DnsQueryCandidate *c;
23 
24         assert(ret);
25         assert(q);
26         assert(s);
27 
28         c = new(DnsQueryCandidate, 1);
29         if (!c)
30                 return -ENOMEM;
31 
32         *c = (DnsQueryCandidate) {
33                 .n_ref = 1,
34                 .query = q,
35                 .scope = s,
36         };
37 
38         LIST_PREPEND(candidates_by_query, q->candidates, c);
39         LIST_PREPEND(candidates_by_scope, s->query_candidates, c);
40 
41         *ret = c;
42         return 0;
43 }
44 
dns_query_candidate_stop(DnsQueryCandidate * c)45 static void dns_query_candidate_stop(DnsQueryCandidate *c) {
46         DnsTransaction *t;
47 
48         assert(c);
49 
50         /* Detach all the DnsTransactions attached to this query */
51 
52         while ((t = set_steal_first(c->transactions))) {
53                 set_remove(t->notify_query_candidates, c);
54                 set_remove(t->notify_query_candidates_done, c);
55                 dns_transaction_gc(t);
56         }
57 }
58 
dns_query_candidate_unlink(DnsQueryCandidate * c)59 static DnsQueryCandidate* dns_query_candidate_unlink(DnsQueryCandidate *c) {
60         assert(c);
61 
62         /* Detach this DnsQueryCandidate from the Query and Scope objects */
63 
64         if (c->query) {
65                 LIST_REMOVE(candidates_by_query, c->query->candidates, c);
66                 c->query = NULL;
67         }
68 
69         if (c->scope) {
70                 LIST_REMOVE(candidates_by_scope, c->scope->query_candidates, c);
71                 c->scope = NULL;
72         }
73 
74         return c;
75 }
76 
dns_query_candidate_free(DnsQueryCandidate * c)77 static DnsQueryCandidate* dns_query_candidate_free(DnsQueryCandidate *c) {
78         if (!c)
79                 return NULL;
80 
81         dns_query_candidate_stop(c);
82         dns_query_candidate_unlink(c);
83 
84         set_free(c->transactions);
85         dns_search_domain_unref(c->search_domain);
86 
87         return mfree(c);
88 }
89 
90 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(DnsQueryCandidate, dns_query_candidate, dns_query_candidate_free);
91 
dns_query_candidate_next_search_domain(DnsQueryCandidate * c)92 static int dns_query_candidate_next_search_domain(DnsQueryCandidate *c) {
93         DnsSearchDomain *next;
94 
95         assert(c);
96 
97         if (c->search_domain && c->search_domain->linked)
98                 next = c->search_domain->domains_next;
99         else
100                 next = dns_scope_get_search_domains(c->scope);
101 
102         for (;;) {
103                 if (!next) /* We hit the end of the list */
104                         return 0;
105 
106                 if (!next->route_only)
107                         break;
108 
109                 /* Skip over route-only domains */
110                 next = next->domains_next;
111         }
112 
113         dns_search_domain_unref(c->search_domain);
114         c->search_domain = dns_search_domain_ref(next);
115 
116         return 1;
117 }
118 
dns_query_candidate_add_transaction(DnsQueryCandidate * c,DnsResourceKey * key,DnsPacket * bypass)119 static int dns_query_candidate_add_transaction(
120                 DnsQueryCandidate *c,
121                 DnsResourceKey *key,
122                 DnsPacket *bypass) {
123 
124         _cleanup_(dns_transaction_gcp) DnsTransaction *t = NULL;
125         int r;
126 
127         assert(c);
128         assert(c->query); /* We shan't add transactions to a candidate that has been detached already */
129 
130         if (key) {
131                 /* Regular lookup with a resource key */
132                 assert(!bypass);
133 
134                 t = dns_scope_find_transaction(c->scope, key, c->query->flags);
135                 if (!t) {
136                         r = dns_transaction_new(&t, c->scope, key, NULL, c->query->flags);
137                         if (r < 0)
138                                 return r;
139                 } else if (set_contains(c->transactions, t))
140                         return 0;
141         } else {
142                 /* "Bypass" lookup with a query packet */
143                 assert(bypass);
144 
145                 r = dns_transaction_new(&t, c->scope, NULL, bypass, c->query->flags);
146                 if (r < 0)
147                         return r;
148         }
149 
150         r = set_ensure_allocated(&t->notify_query_candidates_done, NULL);
151         if (r < 0)
152                 return r;
153 
154         r = set_ensure_put(&t->notify_query_candidates, NULL, c);
155         if (r < 0)
156                 return r;
157 
158         r = set_ensure_put(&c->transactions, NULL, t);
159         if (r < 0) {
160                 (void) set_remove(t->notify_query_candidates, c);
161                 return r;
162         }
163 
164         TAKE_PTR(t);
165         return 1;
166 }
167 
dns_query_candidate_go(DnsQueryCandidate * c)168 static int dns_query_candidate_go(DnsQueryCandidate *c) {
169         _unused_ _cleanup_(dns_query_candidate_unrefp) DnsQueryCandidate *keep_c = NULL;
170         DnsTransaction *t;
171         int r;
172         unsigned n = 0;
173 
174         assert(c);
175 
176         /* Let's keep a reference to the query while we're operating */
177         keep_c = dns_query_candidate_ref(c);
178 
179         /* Start the transactions that are not started yet */
180         SET_FOREACH(t, c->transactions) {
181                 if (t->state != DNS_TRANSACTION_NULL)
182                         continue;
183 
184                 r = dns_transaction_go(t);
185                 if (r < 0)
186                         return r;
187 
188                 n++;
189         }
190 
191         /* If there was nothing to start, then let's proceed immediately */
192         if (n == 0)
193                 dns_query_candidate_notify(c);
194 
195         return 0;
196 }
197 
dns_query_candidate_state(DnsQueryCandidate * c)198 static DnsTransactionState dns_query_candidate_state(DnsQueryCandidate *c) {
199         DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
200         DnsTransaction *t;
201 
202         assert(c);
203 
204         if (c->error_code != 0)
205                 return DNS_TRANSACTION_ERRNO;
206 
207         SET_FOREACH(t, c->transactions)
208 
209                 switch (t->state) {
210 
211                 case DNS_TRANSACTION_NULL:
212                         /* If there's a NULL transaction pending, then
213                          * this means not all transactions where
214                          * started yet, and we were called from within
215                          * the stackframe that is supposed to start
216                          * remaining transactions. In this case,
217                          * simply claim the candidate is pending. */
218 
219                 case DNS_TRANSACTION_PENDING:
220                 case DNS_TRANSACTION_VALIDATING:
221                         /* If there's one transaction currently in
222                          * VALIDATING state, then this means there's
223                          * also one in PENDING state, hence we can
224                          * return PENDING immediately. */
225                         return DNS_TRANSACTION_PENDING;
226 
227                 case DNS_TRANSACTION_SUCCESS:
228                         state = t->state;
229                         break;
230 
231                 default:
232                         if (state != DNS_TRANSACTION_SUCCESS)
233                                 state = t->state;
234 
235                         break;
236                 }
237 
238         return state;
239 }
240 
dns_query_candidate_setup_transactions(DnsQueryCandidate * c)241 static int dns_query_candidate_setup_transactions(DnsQueryCandidate *c) {
242         DnsQuestion *question;
243         DnsResourceKey *key;
244         int n = 0, r;
245 
246         assert(c);
247         assert(c->query); /* We shan't add transactions to a candidate that has been detached already */
248 
249         dns_query_candidate_stop(c);
250 
251         if (c->query->question_bypass) {
252                 /* If this is a bypass query, then pass the original query packet along to the transaction */
253 
254                 assert(dns_question_size(c->query->question_bypass->question) == 1);
255 
256                 if (!dns_scope_good_key(c->scope, dns_question_first_key(c->query->question_bypass->question)))
257                         return 0;
258 
259                 r = dns_query_candidate_add_transaction(c, NULL, c->query->question_bypass);
260                 if (r < 0)
261                         goto fail;
262 
263                 return 1;
264         }
265 
266         question = dns_query_question_for_protocol(c->query, c->scope->protocol);
267 
268         /* Create one transaction per question key */
269         DNS_QUESTION_FOREACH(key, question) {
270                 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *new_key = NULL;
271                 DnsResourceKey *qkey;
272 
273                 if (c->search_domain) {
274                         r = dns_resource_key_new_append_suffix(&new_key, key, c->search_domain->name);
275                         if (r < 0)
276                                 goto fail;
277 
278                         qkey = new_key;
279                 } else
280                         qkey = key;
281 
282                 if (!dns_scope_good_key(c->scope, qkey))
283                         continue;
284 
285                 r = dns_query_candidate_add_transaction(c, qkey, NULL);
286                 if (r < 0)
287                         goto fail;
288 
289                 n++;
290         }
291 
292         return n;
293 
294 fail:
295         dns_query_candidate_stop(c);
296         return r;
297 }
298 
dns_query_candidate_notify(DnsQueryCandidate * c)299 void dns_query_candidate_notify(DnsQueryCandidate *c) {
300         DnsTransactionState state;
301         int r;
302 
303         assert(c);
304 
305         if (!c->query) /* This candidate has been abandoned, do nothing. */
306                 return;
307 
308         state = dns_query_candidate_state(c);
309 
310         if (DNS_TRANSACTION_IS_LIVE(state))
311                 return;
312 
313         if (state != DNS_TRANSACTION_SUCCESS && c->search_domain) {
314 
315                 r = dns_query_candidate_next_search_domain(c);
316                 if (r < 0)
317                         goto fail;
318 
319                 if (r > 0) {
320                         /* OK, there's another search domain to try, let's do so. */
321 
322                         r = dns_query_candidate_setup_transactions(c);
323                         if (r < 0)
324                                 goto fail;
325 
326                         if (r > 0) {
327                                 /* New transactions where queued. Start them and wait */
328 
329                                 r = dns_query_candidate_go(c);
330                                 if (r < 0)
331                                         goto fail;
332 
333                                 return;
334                         }
335                 }
336 
337         }
338 
339         dns_query_ready(c->query);
340         return;
341 
342 fail:
343         c->error_code = log_warning_errno(r, "Failed to follow search domains: %m");
344         dns_query_ready(c->query);
345 }
346 
dns_query_stop(DnsQuery * q)347 static void dns_query_stop(DnsQuery *q) {
348         assert(q);
349 
350         event_source_disable(q->timeout_event_source);
351 
352         LIST_FOREACH(candidates_by_query, c, q->candidates)
353                 dns_query_candidate_stop(c);
354 }
355 
dns_query_unlink_candidates(DnsQuery * q)356 static void dns_query_unlink_candidates(DnsQuery *q) {
357         assert(q);
358 
359         while (q->candidates)
360                 /* Here we drop *our* references to each of the candidates. If we had the only reference, the
361                  * DnsQueryCandidate object will be freed. */
362                 dns_query_candidate_unref(dns_query_candidate_unlink(q->candidates));
363 }
364 
dns_query_reset_answer(DnsQuery * q)365 static void dns_query_reset_answer(DnsQuery *q) {
366         assert(q);
367 
368         q->answer = dns_answer_unref(q->answer);
369         q->answer_rcode = 0;
370         q->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
371         q->answer_errno = 0;
372         q->answer_query_flags = 0;
373         q->answer_protocol = _DNS_PROTOCOL_INVALID;
374         q->answer_family = AF_UNSPEC;
375         q->answer_search_domain = dns_search_domain_unref(q->answer_search_domain);
376         q->answer_full_packet = dns_packet_unref(q->answer_full_packet);
377 }
378 
dns_query_free(DnsQuery * q)379 DnsQuery *dns_query_free(DnsQuery *q) {
380         if (!q)
381                 return NULL;
382 
383         q->timeout_event_source = sd_event_source_disable_unref(q->timeout_event_source);
384 
385         while (q->auxiliary_queries)
386                 dns_query_free(q->auxiliary_queries);
387 
388         if (q->auxiliary_for) {
389                 assert(q->auxiliary_for->n_auxiliary_queries > 0);
390                 q->auxiliary_for->n_auxiliary_queries--;
391                 LIST_REMOVE(auxiliary_queries, q->auxiliary_for->auxiliary_queries, q);
392         }
393 
394         dns_query_unlink_candidates(q);
395 
396         dns_question_unref(q->question_idna);
397         dns_question_unref(q->question_utf8);
398         dns_packet_unref(q->question_bypass);
399 
400         dns_query_reset_answer(q);
401 
402         sd_bus_message_unref(q->bus_request);
403         sd_bus_track_unref(q->bus_track);
404 
405         if (q->varlink_request) {
406                 varlink_set_userdata(q->varlink_request, NULL);
407                 varlink_unref(q->varlink_request);
408         }
409 
410         if (q->request_packet)
411                 hashmap_remove_value(q->stub_listener_extra ?
412                                      q->stub_listener_extra->queries_by_packet :
413                                      q->manager->stub_queries_by_packet,
414                                      q->request_packet,
415                                      q);
416 
417         dns_packet_unref(q->request_packet);
418         dns_answer_unref(q->reply_answer);
419         dns_answer_unref(q->reply_authoritative);
420         dns_answer_unref(q->reply_additional);
421 
422         if (q->request_stream) {
423                 /* Detach the stream from our query, in case something else keeps a reference to it. */
424                 (void) set_remove(q->request_stream->queries, q);
425                 q->request_stream = dns_stream_unref(q->request_stream);
426         }
427 
428         free(q->request_address_string);
429 
430         if (q->manager) {
431                 LIST_REMOVE(queries, q->manager->dns_queries, q);
432                 q->manager->n_dns_queries--;
433         }
434 
435         return mfree(q);
436 }
437 
dns_query_new(Manager * m,DnsQuery ** ret,DnsQuestion * question_utf8,DnsQuestion * question_idna,DnsPacket * question_bypass,int ifindex,uint64_t flags)438 int dns_query_new(
439                 Manager *m,
440                 DnsQuery **ret,
441                 DnsQuestion *question_utf8,
442                 DnsQuestion *question_idna,
443                 DnsPacket *question_bypass,
444                 int ifindex,
445                 uint64_t flags) {
446 
447         _cleanup_(dns_query_freep) DnsQuery *q = NULL;
448         char key_str[DNS_RESOURCE_KEY_STRING_MAX];
449         DnsResourceKey *key;
450         int r;
451 
452         assert(m);
453 
454         if (question_bypass) {
455                 /* It's either a "bypass" query, or a regular one, but can't be both. */
456                 if (question_utf8 || question_idna)
457                         return -EINVAL;
458 
459         } else {
460                 bool good = false;
461 
462                 /* This (primarily) checks two things:
463                  *
464                  * 1. That the question is not empty
465                  * 2. That all RR keys in the question objects are for the same domain
466                  *
467                  * Or in other words, a single DnsQuery object may be used to look up A+AAAA combination for
468                  * the same domain name, or SRV+TXT (for DNS-SD services), but not for unrelated lookups. */
469 
470                 if (dns_question_size(question_utf8) > 0) {
471                         r = dns_question_is_valid_for_query(question_utf8);
472                         if (r < 0)
473                                 return r;
474                         if (r == 0)
475                                 return -EINVAL;
476 
477                         good = true;
478                 }
479 
480                 /* If the IDNA and UTF8 questions are the same, merge their references */
481                 r = dns_question_is_equal(question_idna, question_utf8);
482                 if (r < 0)
483                         return r;
484                 if (r > 0)
485                         question_idna = question_utf8;
486                 else {
487                         if (dns_question_size(question_idna) > 0) {
488                                 r = dns_question_is_valid_for_query(question_idna);
489                                 if (r < 0)
490                                         return r;
491                                 if (r == 0)
492                                         return -EINVAL;
493 
494                                 good = true;
495                         }
496                 }
497 
498                 if (!good) /* don't allow empty queries */
499                         return -EINVAL;
500         }
501 
502         if (m->n_dns_queries >= QUERIES_MAX)
503                 return -EBUSY;
504 
505         q = new(DnsQuery, 1);
506         if (!q)
507                 return -ENOMEM;
508 
509         *q = (DnsQuery) {
510                 .question_utf8 = dns_question_ref(question_utf8),
511                 .question_idna = dns_question_ref(question_idna),
512                 .question_bypass = dns_packet_ref(question_bypass),
513                 .ifindex = ifindex,
514                 .flags = flags,
515                 .answer_dnssec_result = _DNSSEC_RESULT_INVALID,
516                 .answer_protocol = _DNS_PROTOCOL_INVALID,
517                 .answer_family = AF_UNSPEC,
518         };
519 
520         if (question_bypass) {
521                 DNS_QUESTION_FOREACH(key, question_bypass->question)
522                         log_debug("Looking up bypass packet for %s.",
523                                   dns_resource_key_to_string(key, key_str, sizeof key_str));
524         } else {
525                 /* First dump UTF8 question */
526                 DNS_QUESTION_FOREACH(key, question_utf8)
527                         log_debug("Looking up RR for %s.",
528                                   dns_resource_key_to_string(key, key_str, sizeof key_str));
529 
530                 /* And then dump the IDNA question, but only what hasn't been dumped already through the UTF8 question. */
531                 DNS_QUESTION_FOREACH(key, question_idna) {
532                         r = dns_question_contains_key(question_utf8, key);
533                         if (r < 0)
534                                 return r;
535                         if (r > 0)
536                                 continue;
537 
538                         log_debug("Looking up IDNA RR for %s.",
539                                   dns_resource_key_to_string(key, key_str, sizeof key_str));
540                 }
541         }
542 
543         LIST_PREPEND(queries, m->dns_queries, q);
544         m->n_dns_queries++;
545         q->manager = m;
546 
547         if (ret)
548                 *ret = q;
549 
550         TAKE_PTR(q);
551         return 0;
552 }
553 
dns_query_make_auxiliary(DnsQuery * q,DnsQuery * auxiliary_for)554 int dns_query_make_auxiliary(DnsQuery *q, DnsQuery *auxiliary_for) {
555         assert(q);
556         assert(auxiliary_for);
557 
558         /* Ensure that the query is not auxiliary yet, and
559          * nothing else is auxiliary to it either */
560         assert(!q->auxiliary_for);
561         assert(!q->auxiliary_queries);
562 
563         /* Ensure that the unit we shall be made auxiliary for isn't
564          * auxiliary itself */
565         assert(!auxiliary_for->auxiliary_for);
566 
567         if (auxiliary_for->n_auxiliary_queries >= AUXILIARY_QUERIES_MAX)
568                 return -EAGAIN;
569 
570         LIST_PREPEND(auxiliary_queries, auxiliary_for->auxiliary_queries, q);
571         q->auxiliary_for = auxiliary_for;
572 
573         auxiliary_for->n_auxiliary_queries++;
574         return 0;
575 }
576 
dns_query_complete(DnsQuery * q,DnsTransactionState state)577 void dns_query_complete(DnsQuery *q, DnsTransactionState state) {
578         assert(q);
579         assert(!DNS_TRANSACTION_IS_LIVE(state));
580         assert(DNS_TRANSACTION_IS_LIVE(q->state));
581 
582         /* Note that this call might invalidate the query. Callers should hence not attempt to access the
583          * query or transaction after calling this function. */
584 
585         q->state = state;
586 
587         dns_query_stop(q);
588         if (q->complete)
589                 q->complete(q);
590 }
591 
on_query_timeout(sd_event_source * s,usec_t usec,void * userdata)592 static int on_query_timeout(sd_event_source *s, usec_t usec, void *userdata) {
593         DnsQuery *q = userdata;
594 
595         assert(s);
596         assert(q);
597 
598         dns_query_complete(q, DNS_TRANSACTION_TIMEOUT);
599         return 0;
600 }
601 
dns_query_add_candidate(DnsQuery * q,DnsScope * s)602 static int dns_query_add_candidate(DnsQuery *q, DnsScope *s) {
603         _cleanup_(dns_query_candidate_unrefp) DnsQueryCandidate *c = NULL;
604         int r;
605 
606         assert(q);
607         assert(s);
608 
609         r = dns_query_candidate_new(&c, q, s);
610         if (r < 0)
611                 return r;
612 
613         /* If this a single-label domain on DNS, we might append a suitable search domain first. */
614         if (!FLAGS_SET(q->flags, SD_RESOLVED_NO_SEARCH) &&
615             dns_scope_name_wants_search_domain(s, dns_question_first_name(q->question_idna))) {
616                 /* OK, we want a search domain now. Let's find one for this scope */
617 
618                 r = dns_query_candidate_next_search_domain(c);
619                 if (r < 0)
620                         return r;
621         }
622 
623         r = dns_query_candidate_setup_transactions(c);
624         if (r < 0)
625                 return r;
626 
627         TAKE_PTR(c);
628         return 0;
629 }
630 
dns_query_synthesize_reply(DnsQuery * q,DnsTransactionState * state)631 static int dns_query_synthesize_reply(DnsQuery *q, DnsTransactionState *state) {
632         _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
633         int r;
634 
635         assert(q);
636         assert(state);
637 
638         /* Tries to synthesize localhost RR replies (and others) where appropriate. Note that this is done *after* the
639          * the normal lookup finished. The data from the network hence takes precedence over the data we
640          * synthesize. (But note that many scopes refuse to resolve certain domain names) */
641 
642         if (!IN_SET(*state,
643                     DNS_TRANSACTION_RCODE_FAILURE,
644                     DNS_TRANSACTION_NO_SERVERS,
645                     DNS_TRANSACTION_TIMEOUT,
646                     DNS_TRANSACTION_ATTEMPTS_MAX_REACHED,
647                     DNS_TRANSACTION_NETWORK_DOWN,
648                     DNS_TRANSACTION_NOT_FOUND))
649                 return 0;
650 
651         if (FLAGS_SET(q->flags, SD_RESOLVED_NO_SYNTHESIZE))
652                 return 0;
653 
654         r = dns_synthesize_answer(
655                         q->manager,
656                         q->question_bypass ? q->question_bypass->question : q->question_utf8,
657                         q->ifindex,
658                         &answer);
659         if (r == -ENXIO) {
660                 /* If we get ENXIO this tells us to generate NXDOMAIN unconditionally. */
661 
662                 dns_query_reset_answer(q);
663                 q->answer_rcode = DNS_RCODE_NXDOMAIN;
664                 q->answer_protocol = dns_synthesize_protocol(q->flags);
665                 q->answer_family = dns_synthesize_family(q->flags);
666                 q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
667                 *state = DNS_TRANSACTION_RCODE_FAILURE;
668 
669                 return 0;
670         }
671         if (r <= 0)
672                 return r;
673 
674         dns_query_reset_answer(q);
675 
676         q->answer = TAKE_PTR(answer);
677         q->answer_rcode = DNS_RCODE_SUCCESS;
678         q->answer_protocol = dns_synthesize_protocol(q->flags);
679         q->answer_family = dns_synthesize_family(q->flags);
680         q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
681 
682         *state = DNS_TRANSACTION_SUCCESS;
683 
684         return 1;
685 }
686 
dns_query_try_etc_hosts(DnsQuery * q)687 static int dns_query_try_etc_hosts(DnsQuery *q) {
688         _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
689         int r;
690 
691         assert(q);
692 
693         /* Looks in /etc/hosts for matching entries. Note that this is done *before* the normal lookup is
694          * done. The data from /etc/hosts hence takes precedence over the network. */
695 
696         if (FLAGS_SET(q->flags, SD_RESOLVED_NO_SYNTHESIZE))
697                 return 0;
698 
699         r = manager_etc_hosts_lookup(
700                         q->manager,
701                         q->question_bypass ? q->question_bypass->question : q->question_utf8,
702                         &answer);
703         if (r <= 0)
704                 return r;
705 
706         dns_query_reset_answer(q);
707 
708         q->answer = TAKE_PTR(answer);
709         q->answer_rcode = DNS_RCODE_SUCCESS;
710         q->answer_protocol = dns_synthesize_protocol(q->flags);
711         q->answer_family = dns_synthesize_family(q->flags);
712         q->answer_query_flags = SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL|SD_RESOLVED_SYNTHETIC;
713 
714         return 1;
715 }
716 
dns_query_go(DnsQuery * q)717 int dns_query_go(DnsQuery *q) {
718         DnsScopeMatch found = DNS_SCOPE_NO;
719         DnsScope *first = NULL;
720         int r;
721 
722         assert(q);
723 
724         if (q->state != DNS_TRANSACTION_NULL)
725                 return 0;
726 
727         r = dns_query_try_etc_hosts(q);
728         if (r < 0)
729                 return r;
730         if (r > 0) {
731                 dns_query_complete(q, DNS_TRANSACTION_SUCCESS);
732                 return 1;
733         }
734 
735         LIST_FOREACH(scopes, s, q->manager->dns_scopes) {
736                 DnsScopeMatch match;
737 
738                 match = dns_scope_good_domain(s, q);
739                 assert(match >= 0);
740                 if (match > found) { /* Does this match better? If so, remember how well it matched, and the first one
741                                       * that matches this well */
742                         found = match;
743                         first = s;
744                 }
745         }
746 
747         if (found == DNS_SCOPE_NO) {
748                 DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
749 
750                 r = dns_query_synthesize_reply(q, &state);
751                 if (r < 0)
752                         return r;
753 
754                 dns_query_complete(q, state);
755                 return 1;
756         }
757 
758         r = dns_query_add_candidate(q, first);
759         if (r < 0)
760                 goto fail;
761 
762         LIST_FOREACH(scopes, s, first->scopes_next) {
763                 DnsScopeMatch match;
764 
765                 match = dns_scope_good_domain(s, q);
766                 assert(match >= 0);
767                 if (match < found)
768                         continue;
769 
770                 r = dns_query_add_candidate(q, s);
771                 if (r < 0)
772                         goto fail;
773         }
774 
775         dns_query_reset_answer(q);
776 
777         r = event_reset_time_relative(
778                         q->manager->event,
779                         &q->timeout_event_source,
780                         CLOCK_BOOTTIME,
781                         SD_RESOLVED_QUERY_TIMEOUT_USEC,
782                         0, on_query_timeout, q,
783                         0, "query-timeout", true);
784         if (r < 0)
785                 goto fail;
786 
787         q->state = DNS_TRANSACTION_PENDING;
788         q->block_ready++;
789 
790         /* Start the transactions */
791         LIST_FOREACH(candidates_by_query, c, q->candidates) {
792                 r = dns_query_candidate_go(c);
793                 if (r < 0) {
794                         q->block_ready--;
795                         goto fail;
796                 }
797         }
798 
799         q->block_ready--;
800         dns_query_ready(q);
801 
802         return 1;
803 
804 fail:
805         dns_query_stop(q);
806         return r;
807 }
808 
dns_query_accept(DnsQuery * q,DnsQueryCandidate * c)809 static void dns_query_accept(DnsQuery *q, DnsQueryCandidate *c) {
810         DnsTransactionState state = DNS_TRANSACTION_NO_SERVERS;
811         bool has_authenticated = false, has_non_authenticated = false, has_confidential = false, has_non_confidential = false;
812         DnssecResult dnssec_result_authenticated = _DNSSEC_RESULT_INVALID, dnssec_result_non_authenticated = _DNSSEC_RESULT_INVALID;
813         DnsTransaction *t;
814         int r;
815 
816         assert(q);
817 
818         if (!c) {
819                 r = dns_query_synthesize_reply(q, &state);
820                 if (r < 0)
821                         goto fail;
822 
823                 dns_query_complete(q, state);
824                 return;
825         }
826 
827         if (c->error_code != 0) {
828                 /* If the candidate had an error condition of its own, start with that. */
829                 state = DNS_TRANSACTION_ERRNO;
830                 q->answer = dns_answer_unref(q->answer);
831                 q->answer_rcode = 0;
832                 q->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
833                 q->answer_query_flags = 0;
834                 q->answer_errno = c->error_code;
835                 q->answer_full_packet = dns_packet_unref(q->answer_full_packet);
836         }
837 
838         SET_FOREACH(t, c->transactions) {
839 
840                 switch (t->state) {
841 
842                 case DNS_TRANSACTION_SUCCESS: {
843                         /* We found a successful reply, merge it into the answer */
844 
845                         if (state == DNS_TRANSACTION_SUCCESS) {
846                                 r = dns_answer_extend(&q->answer, t->answer);
847                                 if (r < 0)
848                                         goto fail;
849 
850                                 q->answer_query_flags |= dns_transaction_source_to_query_flags(t->answer_source);
851                         } else {
852                                 /* Override non-successful previous answers */
853                                 DNS_ANSWER_REPLACE(q->answer, dns_answer_ref(t->answer));
854                                 q->answer_query_flags = dns_transaction_source_to_query_flags(t->answer_source);
855                         }
856 
857                         q->answer_rcode = t->answer_rcode;
858                         q->answer_errno = 0;
859 
860                         DNS_PACKET_REPLACE(q->answer_full_packet, dns_packet_ref(t->received));
861 
862                         if (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED)) {
863                                 has_authenticated = true;
864                                 dnssec_result_authenticated = t->answer_dnssec_result;
865                         } else {
866                                 has_non_authenticated = true;
867                                 dnssec_result_non_authenticated = t->answer_dnssec_result;
868                         }
869 
870                         if (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL))
871                                 has_confidential = true;
872                         else
873                                 has_non_confidential = true;
874 
875                         state = DNS_TRANSACTION_SUCCESS;
876                         break;
877                 }
878 
879                 case DNS_TRANSACTION_NULL:
880                 case DNS_TRANSACTION_PENDING:
881                 case DNS_TRANSACTION_VALIDATING:
882                 case DNS_TRANSACTION_ABORTED:
883                         /* Ignore transactions that didn't complete */
884                         continue;
885 
886                 default:
887                         /* Any kind of failure? Store the data away, if there's nothing stored yet. */
888                         if (state == DNS_TRANSACTION_SUCCESS)
889                                 continue;
890 
891                         /* If there's already an authenticated negative reply stored, then prefer that over any unauthenticated one */
892                         if (FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) &&
893                             !FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
894                                 continue;
895 
896                         DNS_ANSWER_REPLACE(q->answer, dns_answer_ref(t->answer));
897                         q->answer_rcode = t->answer_rcode;
898                         q->answer_dnssec_result = t->answer_dnssec_result;
899                         q->answer_query_flags = t->answer_query_flags | dns_transaction_source_to_query_flags(t->answer_source);
900                         q->answer_errno = t->answer_errno;
901                         DNS_PACKET_REPLACE(q->answer_full_packet, dns_packet_ref(t->received));
902 
903                         state = t->state;
904                         break;
905                 }
906         }
907 
908         if (state == DNS_TRANSACTION_SUCCESS) {
909                 SET_FLAG(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED, has_authenticated && !has_non_authenticated);
910                 SET_FLAG(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL, has_confidential && !has_non_confidential);
911                 q->answer_dnssec_result = FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) ? dnssec_result_authenticated : dnssec_result_non_authenticated;
912         }
913 
914         q->answer_protocol = c->scope->protocol;
915         q->answer_family = c->scope->family;
916 
917         dns_search_domain_unref(q->answer_search_domain);
918         q->answer_search_domain = dns_search_domain_ref(c->search_domain);
919 
920         r = dns_query_synthesize_reply(q, &state);
921         if (r < 0)
922                 goto fail;
923 
924         dns_query_complete(q, state);
925         return;
926 
927 fail:
928         q->answer_errno = -r;
929         dns_query_complete(q, DNS_TRANSACTION_ERRNO);
930 }
931 
dns_query_ready(DnsQuery * q)932 void dns_query_ready(DnsQuery *q) {
933         DnsQueryCandidate *bad = NULL;
934         bool pending = false;
935 
936         assert(q);
937         assert(DNS_TRANSACTION_IS_LIVE(q->state));
938 
939         /* Note that this call might invalidate the query. Callers
940          * should hence not attempt to access the query or transaction
941          * after calling this function, unless the block_ready
942          * counter was explicitly bumped before doing so. */
943 
944         if (q->block_ready > 0)
945                 return;
946 
947         LIST_FOREACH(candidates_by_query, c, q->candidates) {
948                 DnsTransactionState state;
949 
950                 state = dns_query_candidate_state(c);
951                 switch (state) {
952 
953                 case DNS_TRANSACTION_SUCCESS:
954                         /* One of the candidates is successful,
955                          * let's use it, and copy its data out */
956                         dns_query_accept(q, c);
957                         return;
958 
959                 case DNS_TRANSACTION_NULL:
960                 case DNS_TRANSACTION_PENDING:
961                 case DNS_TRANSACTION_VALIDATING:
962                         /* One of the candidates is still going on,
963                          * let's maybe wait for it */
964                         pending = true;
965                         break;
966 
967                 default:
968                         /* Any kind of failure */
969                         bad = c;
970                         break;
971                 }
972         }
973 
974         if (pending)
975                 return;
976 
977         dns_query_accept(q, bad);
978 }
979 
dns_query_cname_redirect(DnsQuery * q,const DnsResourceRecord * cname)980 static int dns_query_cname_redirect(DnsQuery *q, const DnsResourceRecord *cname) {
981         _cleanup_(dns_question_unrefp) DnsQuestion *nq_idna = NULL, *nq_utf8 = NULL;
982         int r, k;
983 
984         assert(q);
985 
986         if (q->n_cname_redirects >= CNAME_REDIRECTS_MAX)
987                 return -ELOOP;
988         q->n_cname_redirects++;
989 
990         r = dns_question_cname_redirect(q->question_idna, cname, &nq_idna);
991         if (r < 0)
992                 return r;
993         if (r > 0)
994                 log_debug("Following CNAME/DNAME %s → %s.", dns_question_first_name(q->question_idna), dns_question_first_name(nq_idna));
995 
996         k = dns_question_is_equal(q->question_idna, q->question_utf8);
997         if (k < 0)
998                 return k;
999         if (k > 0) {
1000                 /* Same question? Shortcut new question generation */
1001                 nq_utf8 = dns_question_ref(nq_idna);
1002                 k = r;
1003         } else {
1004                 k = dns_question_cname_redirect(q->question_utf8, cname, &nq_utf8);
1005                 if (k < 0)
1006                         return k;
1007                 if (k > 0)
1008                         log_debug("Following UTF8 CNAME/DNAME %s → %s.", dns_question_first_name(q->question_utf8), dns_question_first_name(nq_utf8));
1009         }
1010 
1011         if (r == 0 && k == 0) /* No actual cname happened? */
1012                 return -ELOOP;
1013 
1014         if (q->answer_protocol == DNS_PROTOCOL_DNS)
1015                 /* Don't permit CNAME redirects from unicast DNS to LLMNR or MulticastDNS, so that global resources
1016                  * cannot invade the local namespace. The opposite way we permit: local names may redirect to global
1017                  * ones. */
1018                 q->flags &= ~(SD_RESOLVED_LLMNR|SD_RESOLVED_MDNS); /* mask away the local protocols */
1019 
1020         /* Turn off searching for the new name */
1021         q->flags |= SD_RESOLVED_NO_SEARCH;
1022 
1023         dns_question_unref(q->question_idna);
1024         q->question_idna = TAKE_PTR(nq_idna);
1025 
1026         dns_question_unref(q->question_utf8);
1027         q->question_utf8 = TAKE_PTR(nq_utf8);
1028 
1029         dns_query_unlink_candidates(q);
1030 
1031         /* Note that we do *not* reset the answer here, because the answer we previously got might already
1032          * include everything we need, let's check that first */
1033 
1034         q->state = DNS_TRANSACTION_NULL;
1035 
1036         return 0;
1037 }
1038 
dns_query_process_cname_one(DnsQuery * q)1039 int dns_query_process_cname_one(DnsQuery *q) {
1040         _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *cname = NULL;
1041         DnsQuestion *question;
1042         DnsResourceRecord *rr;
1043         bool full_match = true;
1044         DnsResourceKey *k;
1045         int r;
1046 
1047         assert(q);
1048 
1049         /* Processes a CNAME redirect if there's one. Returns one of three values:
1050          *
1051          * CNAME_QUERY_MATCH   → direct RR match, caller should just use the RRs in this answer (and not
1052          *                       bother with any CNAME/DNAME stuff)
1053          *
1054          * CNAME_QUERY_NOMATCH → no match at all, neither direct nor CNAME/DNAME, caller might decide to
1055          *                       restart query or take things as NODATA reply.
1056          *
1057          * CNAME_QUERY_CNAME   → no direct RR match, but a CNAME/DNAME match that we now followed for one step.
1058          *
1059          * The function might also return a failure, in particular -ELOOP if we encountered too many
1060          * CNAMEs/DNAMEs in a chain or if following CNAMEs/DNAMEs was turned off.
1061          *
1062          * Note that this function doesn't actually restart the query. The caller can decide to do that in
1063          * case of CNAME_QUERY_CNAME, though. */
1064 
1065         if (!IN_SET(q->state, DNS_TRANSACTION_SUCCESS, DNS_TRANSACTION_NULL))
1066                 return DNS_QUERY_NOMATCH;
1067 
1068         question = dns_query_question_for_protocol(q, q->answer_protocol);
1069 
1070         /* Small reminder: our question will consist of one or more RR keys that match in name, but not in
1071          * record type. Specifically, when we do an address lookup the question will typically consist of one
1072          * A and one AAAA key lookup for the same domain name. When we get a response from a server we need
1073          * to check if the answer answers all our questions to use it. Note that a response of CNAME/DNAME
1074          * can answer both an A and the AAAA question for us, but an A/AAAA response only the relevant
1075          * type.
1076          *
1077          * Hence we first check of the answers we collected are sufficient to answer all our questions
1078          * directly. If one question wasn't answered we go on, waiting for more replies. However, if there's
1079          * a CNAME/DNAME response we use it, and redirect to it, regardless if it was a response to the A or
1080          * the AAAA query. */
1081 
1082         DNS_QUESTION_FOREACH(k, question) {
1083                 bool match = false;
1084 
1085                 DNS_ANSWER_FOREACH(rr, q->answer) {
1086                         r = dns_resource_key_match_rr(k, rr, DNS_SEARCH_DOMAIN_NAME(q->answer_search_domain));
1087                         if (r < 0)
1088                                 return r;
1089                         if (r > 0) {
1090                                 match = true; /* Yay, we found an RR that matches the key we are looking for */
1091                                 break;
1092                         }
1093                 }
1094 
1095                 if (!match) {
1096                         /* Hmm. :-( there's no response for this key. This doesn't match. */
1097                         full_match = false;
1098                         break;
1099                 }
1100         }
1101 
1102         if (full_match)
1103                 return DNS_QUERY_MATCH; /* The answer can answer our question in full, no need to follow CNAMEs/DNAMEs */
1104 
1105         /* Let's see if there is a CNAME/DNAME to match. This case is simpler: we accept the CNAME/DNAME that
1106          * matches any of our questions. */
1107         DNS_ANSWER_FOREACH(rr, q->answer) {
1108                 r = dns_question_matches_cname_or_dname(question, rr, DNS_SEARCH_DOMAIN_NAME(q->answer_search_domain));
1109                 if (r < 0)
1110                         return r;
1111                 if (r > 0 && !cname)
1112                         cname = dns_resource_record_ref(rr);
1113         }
1114 
1115         if (!cname)
1116                 return DNS_QUERY_NOMATCH; /* No match and no CNAME/DNAME to follow */
1117 
1118         if (q->flags & SD_RESOLVED_NO_CNAME)
1119                 return -ELOOP;
1120 
1121         if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED))
1122                 q->previous_redirect_unauthenticated = true;
1123         if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL))
1124                 q->previous_redirect_non_confidential = true;
1125         if (!FLAGS_SET(q->answer_query_flags, SD_RESOLVED_SYNTHETIC))
1126                 q->previous_redirect_non_synthetic = true;
1127 
1128         /* OK, let's actually follow the CNAME */
1129         r = dns_query_cname_redirect(q, cname);
1130         if (r < 0)
1131                 return r;
1132 
1133         return DNS_QUERY_CNAME; /* Tell caller that we did a single CNAME/DNAME redirection step */
1134 }
1135 
dns_query_process_cname_many(DnsQuery * q)1136 int dns_query_process_cname_many(DnsQuery *q) {
1137         int r;
1138 
1139         assert(q);
1140 
1141         /* Follows CNAMEs through the current packet: as long as the current packet can fulfill our
1142          * redirected CNAME queries we keep going, and restart the query once the current packet isn't good
1143          * enough anymore. It's a wrapper around dns_query_process_cname_one() and returns the same values,
1144          * but with extended semantics. Specifically:
1145          *
1146          * DNS_QUERY_MATCH   → as above
1147          *
1148          * DNS_QUERY_CNAME   → we ran into a CNAME/DNAME redirect that we could not answer from the current
1149          *                     message, and thus restarted the query to resolve it.
1150          *
1151          * DNS_QUERY_NOMATCH → we reached the end of CNAME/DNAME chain, and there are no direct matches nor a
1152          *                     CNAME/DNAME match. i.e. this is a NODATA case.
1153          *
1154          * Note that this function will restart the query for the caller if needed, and that's the case
1155          * DNS_QUERY_CNAME is returned.
1156          */
1157 
1158         r = dns_query_process_cname_one(q);
1159         if (r != DNS_QUERY_CNAME)
1160                 return r; /* The first redirect is special: if it doesn't answer the question that's no
1161                            * reason to restart the query, we just accept this as a NODATA answer. */
1162 
1163         for (;;) {
1164                 r = dns_query_process_cname_one(q);
1165                 if (r < 0 || r == DNS_QUERY_MATCH)
1166                         return r;
1167                 if (r == DNS_QUERY_NOMATCH) {
1168                         /* OK, so we followed one or more CNAME/DNAME RR but the existing packet can't answer
1169                          * this. Let's restart the query hence, with the new question. Why the different
1170                          * handling than the first chain element? Because if the server answers a direct
1171                          * question with an empty answer then this is a NODATA response. But if it responds
1172                          * with a CNAME chain that ultimately is incomplete (i.e. a non-empty but truncated
1173                          * CNAME chain) then we better follow up ourselves and ask for the rest of the
1174                          * chain. This is particular relevant since our cache will store CNAME/DNAME
1175                          * redirects that we learnt about for lookups of certain DNS types, but later on we
1176                          * can reuse this data even for other DNS types, but in that case need to follow up
1177                          * with the final lookup of the chain ourselves with the RR type we ourselves are
1178                          * interested in. */
1179                         r = dns_query_go(q);
1180                         if (r < 0)
1181                                 return r;
1182 
1183                         return DNS_QUERY_CNAME;
1184                 }
1185 
1186                 /* So we found a CNAME that the existing packet already answers, again via a CNAME, let's
1187                  * continue going then. */
1188                 assert(r == DNS_QUERY_CNAME);
1189         }
1190 }
1191 
dns_query_question_for_protocol(DnsQuery * q,DnsProtocol protocol)1192 DnsQuestion* dns_query_question_for_protocol(DnsQuery *q, DnsProtocol protocol) {
1193         assert(q);
1194 
1195         if (q->question_bypass)
1196                 return q->question_bypass->question;
1197 
1198         switch (protocol) {
1199 
1200         case DNS_PROTOCOL_DNS:
1201                 return q->question_idna;
1202 
1203         case DNS_PROTOCOL_MDNS:
1204         case DNS_PROTOCOL_LLMNR:
1205                 return q->question_utf8;
1206 
1207         default:
1208                 return NULL;
1209         }
1210 }
1211 
dns_query_string(DnsQuery * q)1212 const char *dns_query_string(DnsQuery *q) {
1213         const char *name;
1214         int r;
1215 
1216         /* Returns a somewhat useful human-readable lookup key string for this query */
1217 
1218         if (q->question_bypass)
1219                 return dns_question_first_name(q->question_bypass->question);
1220 
1221         if (q->request_address_string)
1222                 return q->request_address_string;
1223 
1224         if (q->request_address_valid) {
1225                 r = in_addr_to_string(q->request_family, &q->request_address, &q->request_address_string);
1226                 if (r >= 0)
1227                         return q->request_address_string;
1228         }
1229 
1230         name = dns_question_first_name(q->question_utf8);
1231         if (name)
1232                 return name;
1233 
1234         return dns_question_first_name(q->question_idna);
1235 }
1236 
dns_query_fully_authenticated(DnsQuery * q)1237 bool dns_query_fully_authenticated(DnsQuery *q) {
1238         assert(q);
1239 
1240         return FLAGS_SET(q->answer_query_flags, SD_RESOLVED_AUTHENTICATED) && !q->previous_redirect_unauthenticated;
1241 }
1242 
dns_query_fully_confidential(DnsQuery * q)1243 bool dns_query_fully_confidential(DnsQuery *q) {
1244         assert(q);
1245 
1246         return FLAGS_SET(q->answer_query_flags, SD_RESOLVED_CONFIDENTIAL) && !q->previous_redirect_non_confidential;
1247 }
1248 
dns_query_fully_authoritative(DnsQuery * q)1249 bool dns_query_fully_authoritative(DnsQuery *q) {
1250         assert(q);
1251 
1252         /* We are authoritative for everything synthetic (except if a previous CNAME/DNAME) wasn't
1253          * synthetic. (Note: SD_RESOLVED_SYNTHETIC is reset on each CNAME/DNAME, hence the explicit check for
1254          * previous synthetic DNAME/CNAME redirections.) */
1255         if ((q->answer_query_flags & SD_RESOLVED_SYNTHETIC) && !q->previous_redirect_non_synthetic)
1256                 return true;
1257 
1258         /* We are also authoritative for everything coming only from the trust anchor and the local
1259          * zones. (Note: the SD_RESOLVED_FROM_xyz flags we merge on each redirect, hence no need to
1260          * explicitly check previous redirects here.) */
1261         return (q->answer_query_flags & SD_RESOLVED_FROM_MASK & ~(SD_RESOLVED_FROM_TRUST_ANCHOR | SD_RESOLVED_FROM_ZONE)) == 0;
1262 }
1263