1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <fcntl.h>
4 #include <netinet/in.h>
5 #include <poll.h>
6 #include <sys/ioctl.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10 
11 #include "af-list.h"
12 #include "alloc-util.h"
13 #include "bus-polkit.h"
14 #include "dirent-util.h"
15 #include "dns-domain.h"
16 #include "event-util.h"
17 #include "fd-util.h"
18 #include "fileio.h"
19 #include "hostname-util.h"
20 #include "idn-util.h"
21 #include "io-util.h"
22 #include "missing_network.h"
23 #include "missing_socket.h"
24 #include "netlink-util.h"
25 #include "ordered-set.h"
26 #include "parse-util.h"
27 #include "random-util.h"
28 #include "resolved-bus.h"
29 #include "resolved-conf.h"
30 #include "resolved-dns-stub.h"
31 #include "resolved-dnssd.h"
32 #include "resolved-etc-hosts.h"
33 #include "resolved-llmnr.h"
34 #include "resolved-manager.h"
35 #include "resolved-mdns.h"
36 #include "resolved-resolv-conf.h"
37 #include "resolved-util.h"
38 #include "resolved-varlink.h"
39 #include "socket-util.h"
40 #include "string-table.h"
41 #include "string-util.h"
42 #include "utf8.h"
43 
44 #define SEND_TIMEOUT_USEC (200 * USEC_PER_MSEC)
45 
manager_process_link(sd_netlink * rtnl,sd_netlink_message * mm,void * userdata)46 static int manager_process_link(sd_netlink *rtnl, sd_netlink_message *mm, void *userdata) {
47         Manager *m = userdata;
48         uint16_t type;
49         Link *l;
50         int ifindex, r;
51 
52         assert(rtnl);
53         assert(m);
54         assert(mm);
55 
56         r = sd_netlink_message_get_type(mm, &type);
57         if (r < 0)
58                 goto fail;
59 
60         r = sd_rtnl_message_link_get_ifindex(mm, &ifindex);
61         if (r < 0)
62                 goto fail;
63 
64         l = hashmap_get(m->links, INT_TO_PTR(ifindex));
65 
66         switch (type) {
67 
68         case RTM_NEWLINK:{
69                 bool is_new = !l;
70 
71                 if (!l) {
72                         r = link_new(m, &l, ifindex);
73                         if (r < 0)
74                                 goto fail;
75                 }
76 
77                 r = link_process_rtnl(l, mm);
78                 if (r < 0)
79                         goto fail;
80 
81                 r = link_update(l);
82                 if (r < 0)
83                         goto fail;
84 
85                 if (is_new)
86                         log_debug("Found new link %i/%s", ifindex, l->ifname);
87 
88                 break;
89         }
90 
91         case RTM_DELLINK:
92                 if (l) {
93                         log_debug("Removing link %i/%s", l->ifindex, l->ifname);
94                         link_remove_user(l);
95                         link_free(l);
96                 }
97 
98                 break;
99         }
100 
101         return 0;
102 
103 fail:
104         log_warning_errno(r, "Failed to process RTNL link message: %m");
105         return 0;
106 }
107 
manager_process_address(sd_netlink * rtnl,sd_netlink_message * mm,void * userdata)108 static int manager_process_address(sd_netlink *rtnl, sd_netlink_message *mm, void *userdata) {
109         Manager *m = userdata;
110         union in_addr_union address;
111         uint16_t type;
112         int r, ifindex, family;
113         LinkAddress *a;
114         Link *l;
115 
116         assert(rtnl);
117         assert(mm);
118         assert(m);
119 
120         r = sd_netlink_message_get_type(mm, &type);
121         if (r < 0)
122                 goto fail;
123 
124         r = sd_rtnl_message_addr_get_ifindex(mm, &ifindex);
125         if (r < 0)
126                 goto fail;
127 
128         l = hashmap_get(m->links, INT_TO_PTR(ifindex));
129         if (!l)
130                 return 0;
131 
132         r = sd_rtnl_message_addr_get_family(mm, &family);
133         if (r < 0)
134                 goto fail;
135 
136         switch (family) {
137 
138         case AF_INET:
139                 r = sd_netlink_message_read_in_addr(mm, IFA_LOCAL, &address.in);
140                 if (r < 0) {
141                         r = sd_netlink_message_read_in_addr(mm, IFA_ADDRESS, &address.in);
142                         if (r < 0)
143                                 goto fail;
144                 }
145 
146                 break;
147 
148         case AF_INET6:
149                 r = sd_netlink_message_read_in6_addr(mm, IFA_LOCAL, &address.in6);
150                 if (r < 0) {
151                         r = sd_netlink_message_read_in6_addr(mm, IFA_ADDRESS, &address.in6);
152                         if (r < 0)
153                                 goto fail;
154                 }
155 
156                 break;
157 
158         default:
159                 return 0;
160         }
161 
162         a = link_find_address(l, family, &address);
163 
164         switch (type) {
165 
166         case RTM_NEWADDR:
167 
168                 if (!a) {
169                         r = link_address_new(l, &a, family, &address);
170                         if (r < 0)
171                                 return r;
172                 }
173 
174                 r = link_address_update_rtnl(a, mm);
175                 if (r < 0)
176                         return r;
177 
178                 break;
179 
180         case RTM_DELADDR:
181                 link_address_free(a);
182                 break;
183         }
184 
185         return 0;
186 
187 fail:
188         log_warning_errno(r, "Failed to process RTNL address message: %m");
189         return 0;
190 }
191 
manager_rtnl_listen(Manager * m)192 static int manager_rtnl_listen(Manager *m) {
193         _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL;
194         sd_netlink_message *i;
195         int r;
196 
197         assert(m);
198 
199         /* First, subscribe to interfaces coming and going */
200         r = sd_netlink_open(&m->rtnl);
201         if (r < 0)
202                 return r;
203 
204         r = sd_netlink_attach_event(m->rtnl, m->event, SD_EVENT_PRIORITY_IMPORTANT);
205         if (r < 0)
206                 return r;
207 
208         r = sd_netlink_add_match(m->rtnl, NULL, RTM_NEWLINK, manager_process_link, NULL, m, "resolve-NEWLINK");
209         if (r < 0)
210                 return r;
211 
212         r = sd_netlink_add_match(m->rtnl, NULL, RTM_DELLINK, manager_process_link, NULL, m, "resolve-DELLINK");
213         if (r < 0)
214                 return r;
215 
216         r = sd_netlink_add_match(m->rtnl, NULL, RTM_NEWADDR, manager_process_address, NULL, m, "resolve-NEWADDR");
217         if (r < 0)
218                 return r;
219 
220         r = sd_netlink_add_match(m->rtnl, NULL, RTM_DELADDR, manager_process_address, NULL, m, "resolve-DELADDR");
221         if (r < 0)
222                 return r;
223 
224         /* Then, enumerate all links */
225         r = sd_rtnl_message_new_link(m->rtnl, &req, RTM_GETLINK, 0);
226         if (r < 0)
227                 return r;
228 
229         r = sd_netlink_message_request_dump(req, true);
230         if (r < 0)
231                 return r;
232 
233         r = sd_netlink_call(m->rtnl, req, 0, &reply);
234         if (r < 0)
235                 return r;
236 
237         for (i = reply; i; i = sd_netlink_message_next(i)) {
238                 r = manager_process_link(m->rtnl, i, m);
239                 if (r < 0)
240                         return r;
241         }
242 
243         req = sd_netlink_message_unref(req);
244         reply = sd_netlink_message_unref(reply);
245 
246         /* Finally, enumerate all addresses, too */
247         r = sd_rtnl_message_new_addr(m->rtnl, &req, RTM_GETADDR, 0, AF_UNSPEC);
248         if (r < 0)
249                 return r;
250 
251         r = sd_netlink_message_request_dump(req, true);
252         if (r < 0)
253                 return r;
254 
255         r = sd_netlink_call(m->rtnl, req, 0, &reply);
256         if (r < 0)
257                 return r;
258 
259         for (i = reply; i; i = sd_netlink_message_next(i)) {
260                 r = manager_process_address(m->rtnl, i, m);
261                 if (r < 0)
262                         return r;
263         }
264 
265         return r;
266 }
267 
on_network_event(sd_event_source * s,int fd,uint32_t revents,void * userdata)268 static int on_network_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
269         Manager *m = userdata;
270         Link *l;
271         int r;
272 
273         assert(m);
274 
275         sd_network_monitor_flush(m->network_monitor);
276 
277         HASHMAP_FOREACH(l, m->links) {
278                 r = link_update(l);
279                 if (r < 0)
280                         log_warning_errno(r, "Failed to update monitor information for %i: %m", l->ifindex);
281         }
282 
283         (void) manager_write_resolv_conf(m);
284         (void) manager_send_changed(m, "DNS");
285 
286         return 0;
287 }
288 
manager_network_monitor_listen(Manager * m)289 static int manager_network_monitor_listen(Manager *m) {
290         int r, fd, events;
291 
292         assert(m);
293 
294         r = sd_network_monitor_new(&m->network_monitor, NULL);
295         if (r < 0)
296                 return r;
297 
298         fd = sd_network_monitor_get_fd(m->network_monitor);
299         if (fd < 0)
300                 return fd;
301 
302         events = sd_network_monitor_get_events(m->network_monitor);
303         if (events < 0)
304                 return events;
305 
306         r = sd_event_add_io(m->event, &m->network_event_source, fd, events, &on_network_event, m);
307         if (r < 0)
308                 return r;
309 
310         r = sd_event_source_set_priority(m->network_event_source, SD_EVENT_PRIORITY_IMPORTANT+5);
311         if (r < 0)
312                 return r;
313 
314         (void) sd_event_source_set_description(m->network_event_source, "network-monitor");
315 
316         return 0;
317 }
318 
319 static int manager_clock_change_listen(Manager *m);
320 
on_clock_change(sd_event_source * source,int fd,uint32_t revents,void * userdata)321 static int on_clock_change(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
322         Manager *m = userdata;
323 
324         assert(m);
325 
326         /* The clock has changed, let's flush all caches. Why that? That's because DNSSEC validation takes
327          * the system clock into consideration, and if the clock changes the old validations might have been
328          * wrong. Let's redo all validation with the new, correct time.
329          *
330          * (Also, this is triggered after system suspend, which is also a good reason to drop caches, since
331          * we might be connected to a different network now without this being visible in a dropped link
332          * carrier or so.) */
333 
334         log_info("Clock change detected. Flushing caches.");
335         manager_flush_caches(m, LOG_DEBUG /* downgrade the functions own log message, since we already logged here at LOG_INFO level */);
336 
337         /* The clock change timerfd is unusable after it triggered once, create a new one. */
338         return manager_clock_change_listen(m);
339 }
340 
manager_clock_change_listen(Manager * m)341 static int manager_clock_change_listen(Manager *m) {
342         int r;
343 
344         assert(m);
345 
346         m->clock_change_event_source = sd_event_source_disable_unref(m->clock_change_event_source);
347 
348         r = event_add_time_change(m->event, &m->clock_change_event_source, on_clock_change, m);
349         if (r < 0)
350                 return log_error_errno(r, "Failed to create clock change event source: %m");
351 
352         return 0;
353 }
354 
determine_hostnames(char ** full_hostname,char ** llmnr_hostname,char ** mdns_hostname)355 static int determine_hostnames(char **full_hostname, char **llmnr_hostname, char **mdns_hostname) {
356         _cleanup_free_ char *h = NULL, *n = NULL;
357         int r;
358 
359         assert(full_hostname);
360         assert(llmnr_hostname);
361         assert(mdns_hostname);
362 
363         r = resolve_system_hostname(&h, &n);
364         if (r < 0)
365                 return r;
366 
367         r = dns_name_concat(n, "local", 0, mdns_hostname);
368         if (r < 0)
369                 return log_error_errno(r, "Failed to determine mDNS hostname: %m");
370 
371         *llmnr_hostname = TAKE_PTR(n);
372         *full_hostname = TAKE_PTR(h);
373 
374         return 0;
375 }
376 
fallback_hostname(void)377 static char* fallback_hostname(void) {
378 
379         /* Determine the fall back hostname. For exposing this system to the outside world, we cannot have it
380          * to be "localhost" even if that's the default hostname. In this case, let's revert to "linux"
381          * instead. */
382 
383         _cleanup_free_ char *n = get_default_hostname();
384         if (!n)
385                 return NULL;
386 
387         if (is_localhost(n))
388                 return strdup("linux");
389 
390         return TAKE_PTR(n);
391 }
392 
make_fallback_hostnames(char ** full_hostname,char ** llmnr_hostname,char ** mdns_hostname)393 static int make_fallback_hostnames(char **full_hostname, char **llmnr_hostname, char **mdns_hostname) {
394         _cleanup_free_ char *h = NULL, *n = NULL, *m = NULL;
395         char label[DNS_LABEL_MAX];
396         const char *p;
397         int r;
398 
399         assert(full_hostname);
400         assert(llmnr_hostname);
401         assert(mdns_hostname);
402 
403         p = h = fallback_hostname();
404         if (!h)
405                 return log_oom();
406 
407         r = dns_label_unescape(&p, label, sizeof label, 0);
408         if (r < 0)
409                 return log_error_errno(r, "Failed to unescape fallback hostname: %m");
410 
411         assert(r > 0); /* The fallback hostname must have at least one label */
412 
413         r = dns_label_escape_new(label, r, &n);
414         if (r < 0)
415                 return log_error_errno(r, "Failed to escape fallback hostname: %m");
416 
417         r = dns_name_concat(n, "local", 0, &m);
418         if (r < 0)
419                 return log_error_errno(r, "Failed to concatenate mDNS hostname: %m");
420 
421         *llmnr_hostname = TAKE_PTR(n);
422         *mdns_hostname = TAKE_PTR(m);
423         *full_hostname = TAKE_PTR(h);
424 
425         return 0;
426 }
427 
on_hostname_change(sd_event_source * es,int fd,uint32_t revents,void * userdata)428 static int on_hostname_change(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
429         _cleanup_free_ char *full_hostname = NULL, *llmnr_hostname = NULL, *mdns_hostname = NULL;
430         Manager *m = userdata;
431         bool llmnr_hostname_changed;
432         int r;
433 
434         assert(m);
435 
436         r = determine_hostnames(&full_hostname, &llmnr_hostname, &mdns_hostname);
437         if (r < 0) {
438                 log_warning_errno(r, "Failed to determine the local hostname and LLMNR/mDNS names, ignoring: %m");
439                 return 0; /* ignore invalid hostnames */
440         }
441 
442         llmnr_hostname_changed = !streq(llmnr_hostname, m->llmnr_hostname);
443         if (streq(full_hostname, m->full_hostname) &&
444             !llmnr_hostname_changed &&
445             streq(mdns_hostname, m->mdns_hostname))
446                 return 0;
447 
448         log_info("System hostname changed to '%s'.", full_hostname);
449 
450         free_and_replace(m->full_hostname, full_hostname);
451         free_and_replace(m->llmnr_hostname, llmnr_hostname);
452         free_and_replace(m->mdns_hostname, mdns_hostname);
453 
454         manager_refresh_rrs(m);
455         (void) manager_send_changed(m, "LLMNRHostname");
456 
457         return 0;
458 }
459 
manager_watch_hostname(Manager * m)460 static int manager_watch_hostname(Manager *m) {
461         int r;
462 
463         assert(m);
464 
465         m->hostname_fd = open("/proc/sys/kernel/hostname",
466                               O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
467         if (m->hostname_fd < 0) {
468                 log_warning_errno(errno, "Failed to watch hostname: %m");
469                 return 0;
470         }
471 
472         r = sd_event_add_io(m->event, &m->hostname_event_source, m->hostname_fd, 0, on_hostname_change, m);
473         if (r < 0) {
474                 if (r == -EPERM)
475                         /* kernels prior to 3.2 don't support polling this file. Ignore the failure. */
476                         m->hostname_fd = safe_close(m->hostname_fd);
477                 else
478                         return log_error_errno(r, "Failed to add hostname event source: %m");
479         }
480 
481         (void) sd_event_source_set_description(m->hostname_event_source, "hostname");
482 
483         r = determine_hostnames(&m->full_hostname, &m->llmnr_hostname, &m->mdns_hostname);
484         if (r < 0) {
485                 _cleanup_free_ char *d = NULL;
486 
487                 d = fallback_hostname();
488                 if (!d)
489                         return log_oom();
490 
491                 log_info("Defaulting to hostname '%s'.", d);
492 
493                 r = make_fallback_hostnames(&m->full_hostname, &m->llmnr_hostname, &m->mdns_hostname);
494                 if (r < 0)
495                         return r;
496         } else
497                 log_info("Using system hostname '%s'.", m->full_hostname);
498 
499         return 0;
500 }
501 
manager_sigusr1(sd_event_source * s,const struct signalfd_siginfo * si,void * userdata)502 static int manager_sigusr1(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
503         _cleanup_free_ char *buffer = NULL;
504         _cleanup_fclose_ FILE *f = NULL;
505         Manager *m = userdata;
506         size_t size = 0;
507         Link *l;
508 
509         assert(s);
510         assert(si);
511         assert(m);
512 
513         f = open_memstream_unlocked(&buffer, &size);
514         if (!f)
515                 return log_oom();
516 
517         LIST_FOREACH(scopes, scope, m->dns_scopes)
518                 dns_scope_dump(scope, f);
519 
520         LIST_FOREACH(servers, server, m->dns_servers)
521                 dns_server_dump(server, f);
522         LIST_FOREACH(servers, server, m->fallback_dns_servers)
523                 dns_server_dump(server, f);
524         HASHMAP_FOREACH(l, m->links)
525                 LIST_FOREACH(servers, server, l->dns_servers)
526                         dns_server_dump(server, f);
527 
528         if (fflush_and_check(f) < 0)
529                 return log_oom();
530 
531         log_dump(LOG_INFO, buffer);
532         return 0;
533 }
534 
manager_sigusr2(sd_event_source * s,const struct signalfd_siginfo * si,void * userdata)535 static int manager_sigusr2(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
536         Manager *m = userdata;
537 
538         assert(s);
539         assert(si);
540         assert(m);
541 
542         manager_flush_caches(m, LOG_INFO);
543 
544         return 0;
545 }
546 
manager_sigrtmin1(sd_event_source * s,const struct signalfd_siginfo * si,void * userdata)547 static int manager_sigrtmin1(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
548         Manager *m = userdata;
549 
550         assert(s);
551         assert(si);
552         assert(m);
553 
554         manager_reset_server_features(m);
555         return 0;
556 }
557 
manager_new(Manager ** ret)558 int manager_new(Manager **ret) {
559         _cleanup_(manager_freep) Manager *m = NULL;
560         int r;
561 
562         assert(ret);
563 
564         m = new(Manager, 1);
565         if (!m)
566                 return -ENOMEM;
567 
568         *m = (Manager) {
569                 .llmnr_ipv4_udp_fd = -1,
570                 .llmnr_ipv6_udp_fd = -1,
571                 .llmnr_ipv4_tcp_fd = -1,
572                 .llmnr_ipv6_tcp_fd = -1,
573                 .mdns_ipv4_fd = -1,
574                 .mdns_ipv6_fd = -1,
575                 .hostname_fd = -1,
576 
577                 .llmnr_support = DEFAULT_LLMNR_MODE,
578                 .mdns_support = DEFAULT_MDNS_MODE,
579                 .dnssec_mode = DEFAULT_DNSSEC_MODE,
580                 .dns_over_tls_mode = DEFAULT_DNS_OVER_TLS_MODE,
581                 .enable_cache = DNS_CACHE_MODE_YES,
582                 .dns_stub_listener_mode = DNS_STUB_LISTENER_YES,
583                 .read_resolv_conf = true,
584                 .need_builtin_fallbacks = true,
585                 .etc_hosts_last = USEC_INFINITY,
586                 .read_etc_hosts = true,
587         };
588 
589         r = dns_trust_anchor_load(&m->trust_anchor);
590         if (r < 0)
591                 return r;
592 
593         r = manager_parse_config_file(m);
594         if (r < 0)
595                 log_warning_errno(r, "Failed to parse configuration file: %m");
596 
597 #if ENABLE_DNS_OVER_TLS
598         r = dnstls_manager_init(m);
599         if (r < 0)
600                 return r;
601 #endif
602 
603         r = sd_event_default(&m->event);
604         if (r < 0)
605                 return r;
606 
607         (void) sd_event_add_signal(m->event, NULL, SIGTERM, NULL,  NULL);
608         (void) sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
609 
610         (void) sd_event_set_watchdog(m->event, true);
611 
612         r = manager_watch_hostname(m);
613         if (r < 0)
614                 return r;
615 
616         r = dnssd_load(m);
617         if (r < 0)
618                 log_warning_errno(r, "Failed to load DNS-SD configuration files: %m");
619 
620         r = dns_scope_new(m, &m->unicast_scope, NULL, DNS_PROTOCOL_DNS, AF_UNSPEC);
621         if (r < 0)
622                 return r;
623 
624         r = manager_network_monitor_listen(m);
625         if (r < 0)
626                 return r;
627 
628         r = manager_rtnl_listen(m);
629         if (r < 0)
630                 return r;
631 
632         r = manager_clock_change_listen(m);
633         if (r < 0)
634                 return r;
635 
636         r = manager_connect_bus(m);
637         if (r < 0)
638                 return r;
639 
640         (void) sd_event_add_signal(m->event, &m->sigusr1_event_source, SIGUSR1, manager_sigusr1, m);
641         (void) sd_event_add_signal(m->event, &m->sigusr2_event_source, SIGUSR2, manager_sigusr2, m);
642         (void) sd_event_add_signal(m->event, &m->sigrtmin1_event_source, SIGRTMIN+1, manager_sigrtmin1, m);
643 
644         manager_cleanup_saved_user(m);
645 
646         *ret = TAKE_PTR(m);
647 
648         return 0;
649 }
650 
manager_start(Manager * m)651 int manager_start(Manager *m) {
652         int r;
653 
654         assert(m);
655 
656         r = manager_dns_stub_start(m);
657         if (r < 0)
658                 return r;
659 
660         r = manager_varlink_init(m);
661         if (r < 0)
662                 return r;
663 
664         return 0;
665 }
666 
manager_free(Manager * m)667 Manager *manager_free(Manager *m) {
668         Link *l;
669         DnssdService *s;
670 
671         if (!m)
672                 return NULL;
673 
674         dns_server_unlink_all(m->dns_servers);
675         dns_server_unlink_all(m->fallback_dns_servers);
676         dns_search_domain_unlink_all(m->search_domains);
677 
678         while ((l = hashmap_first(m->links)))
679                link_free(l);
680 
681         while (m->dns_queries)
682                 dns_query_free(m->dns_queries);
683 
684         m->stub_queries_by_packet = hashmap_free(m->stub_queries_by_packet);
685 
686         dns_scope_free(m->unicast_scope);
687 
688         /* At this point only orphaned streams should remain. All others should have been freed already by their
689          * owners */
690         while (m->dns_streams)
691                 dns_stream_unref(m->dns_streams);
692 
693 #if ENABLE_DNS_OVER_TLS
694         dnstls_manager_free(m);
695 #endif
696 
697         hashmap_free(m->links);
698         hashmap_free(m->dns_transactions);
699 
700         sd_event_source_unref(m->network_event_source);
701         sd_network_monitor_unref(m->network_monitor);
702 
703         sd_netlink_unref(m->rtnl);
704         sd_event_source_unref(m->rtnl_event_source);
705         sd_event_source_unref(m->clock_change_event_source);
706 
707         manager_llmnr_stop(m);
708         manager_mdns_stop(m);
709         manager_dns_stub_stop(m);
710         manager_varlink_done(m);
711 
712         manager_socket_graveyard_clear(m);
713 
714         ordered_set_free(m->dns_extra_stub_listeners);
715 
716         bus_verify_polkit_async_registry_free(m->polkit_registry);
717 
718         sd_bus_flush_close_unref(m->bus);
719 
720         sd_event_source_unref(m->sigusr1_event_source);
721         sd_event_source_unref(m->sigusr2_event_source);
722         sd_event_source_unref(m->sigrtmin1_event_source);
723 
724         dns_resource_key_unref(m->llmnr_host_ipv4_key);
725         dns_resource_key_unref(m->llmnr_host_ipv6_key);
726         dns_resource_key_unref(m->mdns_host_ipv4_key);
727         dns_resource_key_unref(m->mdns_host_ipv6_key);
728 
729         sd_event_source_unref(m->hostname_event_source);
730         safe_close(m->hostname_fd);
731 
732         sd_event_unref(m->event);
733 
734         free(m->full_hostname);
735         free(m->llmnr_hostname);
736         free(m->mdns_hostname);
737 
738         while ((s = hashmap_first(m->dnssd_services)))
739                dnssd_service_free(s);
740         hashmap_free(m->dnssd_services);
741 
742         dns_trust_anchor_flush(&m->trust_anchor);
743         manager_etc_hosts_flush(m);
744 
745         return mfree(m);
746 }
747 
manager_recv(Manager * m,int fd,DnsProtocol protocol,DnsPacket ** ret)748 int manager_recv(Manager *m, int fd, DnsProtocol protocol, DnsPacket **ret) {
749         _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
750         CMSG_BUFFER_TYPE(CMSG_SPACE(MAXSIZE(struct in_pktinfo, struct in6_pktinfo))
751                          + CMSG_SPACE(int) /* ttl/hoplimit */
752                          + EXTRA_CMSG_SPACE /* kernel appears to require extra buffer space */) control;
753         union sockaddr_union sa;
754         struct iovec iov;
755         struct msghdr mh = {
756                 .msg_name = &sa.sa,
757                 .msg_namelen = sizeof(sa),
758                 .msg_iov = &iov,
759                 .msg_iovlen = 1,
760                 .msg_control = &control,
761                 .msg_controllen = sizeof(control),
762         };
763         struct cmsghdr *cmsg;
764         ssize_t ms, l;
765         int r;
766 
767         assert(m);
768         assert(fd >= 0);
769         assert(ret);
770 
771         ms = next_datagram_size_fd(fd);
772         if (ms < 0)
773                 return ms;
774 
775         r = dns_packet_new(&p, protocol, ms, DNS_PACKET_SIZE_MAX);
776         if (r < 0)
777                 return r;
778 
779         iov = IOVEC_MAKE(DNS_PACKET_DATA(p), p->allocated);
780 
781         l = recvmsg_safe(fd, &mh, 0);
782         if (l < 0) {
783                 if (ERRNO_IS_TRANSIENT(l))
784                         return 0;
785                 return l;
786         }
787         if (l == 0)
788                 return 0;
789 
790         assert(!(mh.msg_flags & MSG_TRUNC));
791 
792         p->size = (size_t) l;
793 
794         p->family = sa.sa.sa_family;
795         p->ipproto = IPPROTO_UDP;
796         if (p->family == AF_INET) {
797                 p->sender.in = sa.in.sin_addr;
798                 p->sender_port = be16toh(sa.in.sin_port);
799         } else if (p->family == AF_INET6) {
800                 p->sender.in6 = sa.in6.sin6_addr;
801                 p->sender_port = be16toh(sa.in6.sin6_port);
802                 p->ifindex = sa.in6.sin6_scope_id;
803         } else
804                 return -EAFNOSUPPORT;
805 
806         p->timestamp = now(CLOCK_BOOTTIME);
807 
808         CMSG_FOREACH(cmsg, &mh) {
809 
810                 if (cmsg->cmsg_level == IPPROTO_IPV6) {
811                         assert(p->family == AF_INET6);
812 
813                         switch (cmsg->cmsg_type) {
814 
815                         case IPV6_PKTINFO: {
816                                 struct in6_pktinfo *i = (struct in6_pktinfo*) CMSG_DATA(cmsg);
817 
818                                 if (p->ifindex <= 0)
819                                         p->ifindex = i->ipi6_ifindex;
820 
821                                 p->destination.in6 = i->ipi6_addr;
822                                 break;
823                         }
824 
825                         case IPV6_HOPLIMIT:
826                                 p->ttl = *(int *) CMSG_DATA(cmsg);
827                                 break;
828 
829                         case IPV6_RECVFRAGSIZE:
830                                 p->fragsize = *(int *) CMSG_DATA(cmsg);
831                                 break;
832                         }
833                 } else if (cmsg->cmsg_level == IPPROTO_IP) {
834                         assert(p->family == AF_INET);
835 
836                         switch (cmsg->cmsg_type) {
837 
838                         case IP_PKTINFO: {
839                                 struct in_pktinfo *i = (struct in_pktinfo*) CMSG_DATA(cmsg);
840 
841                                 if (p->ifindex <= 0)
842                                         p->ifindex = i->ipi_ifindex;
843 
844                                 p->destination.in = i->ipi_addr;
845                                 break;
846                         }
847 
848                         case IP_TTL:
849                                 p->ttl = *(int *) CMSG_DATA(cmsg);
850                                 break;
851 
852                         case IP_RECVFRAGSIZE:
853                                 p->fragsize = *(int *) CMSG_DATA(cmsg);
854                                 break;
855                         }
856                 }
857         }
858 
859         /* The Linux kernel sets the interface index to the loopback
860          * device if the packet came from the local host since it
861          * avoids the routing table in such a case. Let's unset the
862          * interface index in such a case. */
863         if (p->ifindex == LOOPBACK_IFINDEX)
864                 p->ifindex = 0;
865 
866         if (protocol != DNS_PROTOCOL_DNS) {
867                 /* If we don't know the interface index still, we look for the
868                  * first local interface with a matching address. Yuck! */
869                 if (p->ifindex <= 0)
870                         p->ifindex = manager_find_ifindex(m, p->family, &p->destination);
871         }
872 
873         if (DEBUG_LOGGING) {
874                 _cleanup_free_ char *sender_address = NULL, *destination_address = NULL;
875 
876                 (void) in_addr_to_string(p->family, &p->sender, &sender_address);
877                 (void) in_addr_to_string(p->family, &p->destination, &destination_address);
878 
879                 log_debug("Received %s UDP packet of size %zu, ifindex=%i, ttl=%i, fragsize=%zu, sender=%s, destination=%s",
880                           dns_protocol_to_string(protocol), p->size, p->ifindex, p->ttl, p->fragsize,
881                           strna(sender_address), strna(destination_address));
882         }
883 
884         *ret = TAKE_PTR(p);
885         return 1;
886 }
887 
sendmsg_loop(int fd,struct msghdr * mh,int flags)888 static int sendmsg_loop(int fd, struct msghdr *mh, int flags) {
889         int r;
890 
891         assert(fd >= 0);
892         assert(mh);
893 
894         for (;;) {
895                 if (sendmsg(fd, mh, flags) >= 0)
896                         return 0;
897 
898                 if (errno == EINTR)
899                         continue;
900 
901                 if (errno != EAGAIN)
902                         return -errno;
903 
904                 r = fd_wait_for_event(fd, POLLOUT, SEND_TIMEOUT_USEC);
905                 if (r < 0)
906                         return r;
907                 if (r == 0)
908                         return -ETIMEDOUT;
909         }
910 }
911 
write_loop(int fd,void * message,size_t length)912 static int write_loop(int fd, void *message, size_t length) {
913         int r;
914 
915         assert(fd >= 0);
916         assert(message);
917 
918         for (;;) {
919                 if (write(fd, message, length) >= 0)
920                         return 0;
921 
922                 if (errno == EINTR)
923                         continue;
924 
925                 if (errno != EAGAIN)
926                         return -errno;
927 
928                 r = fd_wait_for_event(fd, POLLOUT, SEND_TIMEOUT_USEC);
929                 if (r < 0)
930                         return r;
931                 if (r == 0)
932                         return -ETIMEDOUT;
933         }
934 }
935 
manager_write(Manager * m,int fd,DnsPacket * p)936 int manager_write(Manager *m, int fd, DnsPacket *p) {
937         int r;
938 
939         log_debug("Sending %s%s packet with id %" PRIu16 " of size %zu.",
940                   DNS_PACKET_TC(p) ? "truncated (!) " : "",
941                   DNS_PACKET_QR(p) ? "response" : "query",
942                   DNS_PACKET_ID(p),
943                   p->size);
944 
945         r = write_loop(fd, DNS_PACKET_DATA(p), p->size);
946         if (r < 0)
947                 return r;
948 
949         return 0;
950 }
951 
manager_ipv4_send(Manager * m,int fd,int ifindex,const struct in_addr * destination,uint16_t port,const struct in_addr * source,DnsPacket * p)952 static int manager_ipv4_send(
953                 Manager *m,
954                 int fd,
955                 int ifindex,
956                 const struct in_addr *destination,
957                 uint16_t port,
958                 const struct in_addr *source,
959                 DnsPacket *p) {
960 
961         CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct in_pktinfo))) control = {};
962         union sockaddr_union sa;
963         struct iovec iov;
964         struct msghdr mh = {
965                 .msg_iov = &iov,
966                 .msg_iovlen = 1,
967                 .msg_name = &sa.sa,
968                 .msg_namelen = sizeof(sa.in),
969         };
970 
971         assert(m);
972         assert(fd >= 0);
973         assert(destination);
974         assert(port > 0);
975         assert(p);
976 
977         iov = IOVEC_MAKE(DNS_PACKET_DATA(p), p->size);
978 
979         sa = (union sockaddr_union) {
980                 .in.sin_family = AF_INET,
981                 .in.sin_addr = *destination,
982                 .in.sin_port = htobe16(port),
983         };
984 
985         if (ifindex > 0) {
986                 struct cmsghdr *cmsg;
987                 struct in_pktinfo *pi;
988 
989                 mh.msg_control = &control;
990                 mh.msg_controllen = sizeof(control);
991 
992                 cmsg = CMSG_FIRSTHDR(&mh);
993                 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
994                 cmsg->cmsg_level = IPPROTO_IP;
995                 cmsg->cmsg_type = IP_PKTINFO;
996 
997                 pi = (struct in_pktinfo*) CMSG_DATA(cmsg);
998                 pi->ipi_ifindex = ifindex;
999 
1000                 if (source)
1001                         pi->ipi_spec_dst = *source;
1002         }
1003 
1004         return sendmsg_loop(fd, &mh, 0);
1005 }
1006 
manager_ipv6_send(Manager * m,int fd,int ifindex,const struct in6_addr * destination,uint16_t port,const struct in6_addr * source,DnsPacket * p)1007 static int manager_ipv6_send(
1008                 Manager *m,
1009                 int fd,
1010                 int ifindex,
1011                 const struct in6_addr *destination,
1012                 uint16_t port,
1013                 const struct in6_addr *source,
1014                 DnsPacket *p) {
1015 
1016         CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct in6_pktinfo))) control = {};
1017         union sockaddr_union sa;
1018         struct iovec iov;
1019         struct msghdr mh = {
1020                 .msg_iov = &iov,
1021                 .msg_iovlen = 1,
1022                 .msg_name = &sa.sa,
1023                 .msg_namelen = sizeof(sa.in6),
1024         };
1025 
1026         assert(m);
1027         assert(fd >= 0);
1028         assert(destination);
1029         assert(port > 0);
1030         assert(p);
1031 
1032         iov = IOVEC_MAKE(DNS_PACKET_DATA(p), p->size);
1033 
1034         sa = (union sockaddr_union) {
1035                 .in6.sin6_family = AF_INET6,
1036                 .in6.sin6_addr = *destination,
1037                 .in6.sin6_port = htobe16(port),
1038                 .in6.sin6_scope_id = ifindex,
1039         };
1040 
1041         if (ifindex > 0) {
1042                 struct cmsghdr *cmsg;
1043                 struct in6_pktinfo *pi;
1044 
1045                 mh.msg_control = &control;
1046                 mh.msg_controllen = sizeof(control);
1047 
1048                 cmsg = CMSG_FIRSTHDR(&mh);
1049                 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
1050                 cmsg->cmsg_level = IPPROTO_IPV6;
1051                 cmsg->cmsg_type = IPV6_PKTINFO;
1052 
1053                 pi = (struct in6_pktinfo*) CMSG_DATA(cmsg);
1054                 pi->ipi6_ifindex = ifindex;
1055 
1056                 if (source)
1057                         pi->ipi6_addr = *source;
1058         }
1059 
1060         return sendmsg_loop(fd, &mh, 0);
1061 }
1062 
manager_send(Manager * m,int fd,int ifindex,int family,const union in_addr_union * destination,uint16_t port,const union in_addr_union * source,DnsPacket * p)1063 int manager_send(
1064                 Manager *m,
1065                 int fd,
1066                 int ifindex,
1067                 int family,
1068                 const union in_addr_union *destination,
1069                 uint16_t port,
1070                 const union in_addr_union *source,
1071                 DnsPacket *p) {
1072 
1073         assert(m);
1074         assert(fd >= 0);
1075         assert(destination);
1076         assert(port > 0);
1077         assert(p);
1078 
1079         log_debug("Sending %s%s packet with id %" PRIu16 " on interface %i/%s of size %zu.",
1080                   DNS_PACKET_TC(p) ? "truncated (!) " : "",
1081                   DNS_PACKET_QR(p) ? "response" : "query",
1082                   DNS_PACKET_ID(p),
1083                   ifindex, af_to_name(family),
1084                   p->size);
1085 
1086         if (family == AF_INET)
1087                 return manager_ipv4_send(m, fd, ifindex, &destination->in, port, source ? &source->in : NULL, p);
1088         if (family == AF_INET6)
1089                 return manager_ipv6_send(m, fd, ifindex, &destination->in6, port, source ? &source->in6 : NULL, p);
1090 
1091         return -EAFNOSUPPORT;
1092 }
1093 
manager_find_mtu(Manager * m)1094 uint32_t manager_find_mtu(Manager *m) {
1095         uint32_t mtu = 0;
1096         Link *l;
1097 
1098         /* If we don't know on which link a DNS packet would be delivered, let's find the largest MTU that
1099          * works on all interfaces we know of that have an IP address associated */
1100 
1101         HASHMAP_FOREACH(l, m->links) {
1102                 /* Let's filter out links without IP addresses (e.g. AF_CAN links and suchlike) */
1103                 if (!l->addresses)
1104                         continue;
1105 
1106                 /* Safety check: MTU shorter than what we need for the absolutely shortest DNS request? Then
1107                  * let's ignore this link. */
1108                 if (l->mtu < MIN(UDP4_PACKET_HEADER_SIZE + DNS_PACKET_HEADER_SIZE,
1109                                  UDP6_PACKET_HEADER_SIZE + DNS_PACKET_HEADER_SIZE))
1110                         continue;
1111 
1112                 if (mtu <= 0 || l->mtu < mtu)
1113                         mtu = l->mtu;
1114         }
1115 
1116         if (mtu == 0) /* found nothing? then let's assume the typical Ethernet MTU for lack of anything more precise */
1117                 return 1500;
1118 
1119         return mtu;
1120 }
1121 
manager_find_ifindex(Manager * m,int family,const union in_addr_union * in_addr)1122 int manager_find_ifindex(Manager *m, int family, const union in_addr_union *in_addr) {
1123         LinkAddress *a;
1124 
1125         assert(m);
1126 
1127         if (!IN_SET(family, AF_INET, AF_INET6))
1128                 return 0;
1129 
1130         if (!in_addr)
1131                 return 0;
1132 
1133         a = manager_find_link_address(m, family, in_addr);
1134         if (a)
1135                 return a->link->ifindex;
1136 
1137         return 0;
1138 }
1139 
manager_refresh_rrs(Manager * m)1140 void manager_refresh_rrs(Manager *m) {
1141         Link *l;
1142         DnssdService *s;
1143 
1144         assert(m);
1145 
1146         m->llmnr_host_ipv4_key = dns_resource_key_unref(m->llmnr_host_ipv4_key);
1147         m->llmnr_host_ipv6_key = dns_resource_key_unref(m->llmnr_host_ipv6_key);
1148         m->mdns_host_ipv4_key = dns_resource_key_unref(m->mdns_host_ipv4_key);
1149         m->mdns_host_ipv6_key = dns_resource_key_unref(m->mdns_host_ipv6_key);
1150 
1151         HASHMAP_FOREACH(l, m->links)
1152                 link_add_rrs(l, true);
1153 
1154         if (m->mdns_support == RESOLVE_SUPPORT_YES)
1155                 HASHMAP_FOREACH(s, m->dnssd_services)
1156                         if (dnssd_update_rrs(s) < 0)
1157                                 log_warning("Failed to refresh DNS-SD service '%s'", s->name);
1158 
1159         HASHMAP_FOREACH(l, m->links)
1160                 link_add_rrs(l, false);
1161 }
1162 
manager_next_random_name(const char * old,char ** ret_new)1163 static int manager_next_random_name(const char *old, char **ret_new) {
1164         const char *p;
1165         uint64_t u, a;
1166         char *n;
1167 
1168         p = strchr(old, 0);
1169         assert(p);
1170 
1171         while (p > old) {
1172                 if (!strchr(DIGITS, p[-1]))
1173                         break;
1174 
1175                 p--;
1176         }
1177 
1178         if (*p == 0 || safe_atou64(p, &u) < 0 || u <= 0)
1179                 u = 1;
1180 
1181         /* Add a random number to the old value. This way we can avoid
1182          * that two hosts pick the same hostname, win on IPv4 and lose
1183          * on IPv6 (or vice versa), and pick the same hostname
1184          * replacement hostname, ad infinitum. We still want the
1185          * numbers to go up monotonically, hence we just add a random
1186          * value 1..10 */
1187 
1188         random_bytes(&a, sizeof(a));
1189         u += 1 + a % 10;
1190 
1191         if (asprintf(&n, "%.*s%" PRIu64, (int) (p - old), old, u) < 0)
1192                 return -ENOMEM;
1193 
1194         *ret_new = n;
1195 
1196         return 0;
1197 }
1198 
manager_next_hostname(Manager * m)1199 int manager_next_hostname(Manager *m) {
1200         _cleanup_free_ char *h = NULL, *k = NULL;
1201         int r;
1202 
1203         assert(m);
1204 
1205         r = manager_next_random_name(m->llmnr_hostname, &h);
1206         if (r < 0)
1207                 return r;
1208 
1209         r = dns_name_concat(h, "local", 0, &k);
1210         if (r < 0)
1211                 return r;
1212 
1213         log_info("Hostname conflict, changing published hostname from '%s' to '%s'.", m->llmnr_hostname, h);
1214 
1215         free_and_replace(m->llmnr_hostname, h);
1216         free_and_replace(m->mdns_hostname, k);
1217 
1218         manager_refresh_rrs(m);
1219         (void) manager_send_changed(m, "LLMNRHostname");
1220 
1221         return 0;
1222 }
1223 
manager_find_link_address(Manager * m,int family,const union in_addr_union * in_addr)1224 LinkAddress* manager_find_link_address(Manager *m, int family, const union in_addr_union *in_addr) {
1225         Link *l;
1226 
1227         assert(m);
1228 
1229         if (!IN_SET(family, AF_INET, AF_INET6))
1230                 return NULL;
1231 
1232         if (!in_addr)
1233                 return NULL;
1234 
1235         HASHMAP_FOREACH(l, m->links) {
1236                 LinkAddress *a;
1237 
1238                 a = link_find_address(l, family, in_addr);
1239                 if (a)
1240                         return a;
1241         }
1242 
1243         return NULL;
1244 }
1245 
manager_packet_from_local_address(Manager * m,DnsPacket * p)1246 bool manager_packet_from_local_address(Manager *m, DnsPacket *p) {
1247         assert(m);
1248         assert(p);
1249 
1250         /* Let's see if this packet comes from an IP address we have on any local interface */
1251 
1252         return !!manager_find_link_address(m, p->family, &p->sender);
1253 }
1254 
manager_packet_from_our_transaction(Manager * m,DnsPacket * p)1255 bool manager_packet_from_our_transaction(Manager *m, DnsPacket *p) {
1256         DnsTransaction *t;
1257 
1258         assert(m);
1259         assert(p);
1260 
1261         /* Let's see if we have a transaction with a query message with the exact same binary contents as the
1262          * one we just got. If so, it's almost definitely a packet loop of some kind. */
1263 
1264         t = hashmap_get(m->dns_transactions, UINT_TO_PTR(DNS_PACKET_ID(p)));
1265         if (!t)
1266                 return false;
1267 
1268         return t->sent && dns_packet_equal(t->sent, p);
1269 }
1270 
manager_find_scope(Manager * m,DnsPacket * p)1271 DnsScope* manager_find_scope(Manager *m, DnsPacket *p) {
1272         Link *l;
1273 
1274         assert(m);
1275         assert(p);
1276 
1277         l = hashmap_get(m->links, INT_TO_PTR(p->ifindex));
1278         if (!l)
1279                 return NULL;
1280 
1281         switch (p->protocol) {
1282         case DNS_PROTOCOL_LLMNR:
1283                 if (p->family == AF_INET)
1284                         return l->llmnr_ipv4_scope;
1285                 else if (p->family == AF_INET6)
1286                         return l->llmnr_ipv6_scope;
1287 
1288                 break;
1289 
1290         case DNS_PROTOCOL_MDNS:
1291                 if (p->family == AF_INET)
1292                         return l->mdns_ipv4_scope;
1293                 else if (p->family == AF_INET6)
1294                         return l->mdns_ipv6_scope;
1295 
1296                 break;
1297 
1298         default:
1299                 break;
1300         }
1301 
1302         return NULL;
1303 }
1304 
manager_verify_all(Manager * m)1305 void manager_verify_all(Manager *m) {
1306         assert(m);
1307 
1308         LIST_FOREACH(scopes, s, m->dns_scopes)
1309                 dns_zone_verify_all(&s->zone);
1310 }
1311 
manager_is_own_hostname(Manager * m,const char * name)1312 int manager_is_own_hostname(Manager *m, const char *name) {
1313         int r;
1314 
1315         assert(m);
1316         assert(name);
1317 
1318         if (m->llmnr_hostname) {
1319                 r = dns_name_equal(name, m->llmnr_hostname);
1320                 if (r != 0)
1321                         return r;
1322         }
1323 
1324         if (m->mdns_hostname) {
1325                 r = dns_name_equal(name, m->mdns_hostname);
1326                 if (r != 0)
1327                         return r;
1328         }
1329 
1330         if (m->full_hostname)
1331                 return dns_name_equal(name, m->full_hostname);
1332 
1333         return 0;
1334 }
1335 
manager_compile_dns_servers(Manager * m,OrderedSet ** dns)1336 int manager_compile_dns_servers(Manager *m, OrderedSet **dns) {
1337         Link *l;
1338         int r;
1339 
1340         assert(m);
1341         assert(dns);
1342 
1343         r = ordered_set_ensure_allocated(dns, &dns_server_hash_ops);
1344         if (r < 0)
1345                 return r;
1346 
1347         /* First add the system-wide servers and domains */
1348         LIST_FOREACH(servers, s, m->dns_servers) {
1349                 r = ordered_set_put(*dns, s);
1350                 if (r == -EEXIST)
1351                         continue;
1352                 if (r < 0)
1353                         return r;
1354         }
1355 
1356         /* Then, add the per-link servers */
1357         HASHMAP_FOREACH(l, m->links) {
1358                 LIST_FOREACH(servers, s, l->dns_servers) {
1359                         r = ordered_set_put(*dns, s);
1360                         if (r == -EEXIST)
1361                                 continue;
1362                         if (r < 0)
1363                                 return r;
1364                 }
1365         }
1366 
1367         /* If we found nothing, add the fallback servers */
1368         if (ordered_set_isempty(*dns)) {
1369                 LIST_FOREACH(servers, s, m->fallback_dns_servers) {
1370                         r = ordered_set_put(*dns, s);
1371                         if (r == -EEXIST)
1372                                 continue;
1373                         if (r < 0)
1374                                 return r;
1375                 }
1376         }
1377 
1378         return 0;
1379 }
1380 
1381 /* filter_route is a tri-state:
1382  *   < 0: no filtering
1383  *   = 0 or false: return only domains which should be used for searching
1384  *   > 0 or true: return only domains which are for routing only
1385  */
manager_compile_search_domains(Manager * m,OrderedSet ** domains,int filter_route)1386 int manager_compile_search_domains(Manager *m, OrderedSet **domains, int filter_route) {
1387         Link *l;
1388         int r;
1389 
1390         assert(m);
1391         assert(domains);
1392 
1393         r = ordered_set_ensure_allocated(domains, &dns_name_hash_ops);
1394         if (r < 0)
1395                 return r;
1396 
1397         LIST_FOREACH(domains, d, m->search_domains) {
1398 
1399                 if (filter_route >= 0 &&
1400                     d->route_only != !!filter_route)
1401                         continue;
1402 
1403                 r = ordered_set_put(*domains, d->name);
1404                 if (r == -EEXIST)
1405                         continue;
1406                 if (r < 0)
1407                         return r;
1408         }
1409 
1410         HASHMAP_FOREACH(l, m->links) {
1411 
1412                 LIST_FOREACH(domains, d, l->search_domains) {
1413 
1414                         if (filter_route >= 0 &&
1415                             d->route_only != !!filter_route)
1416                                 continue;
1417 
1418                         r = ordered_set_put(*domains, d->name);
1419                         if (r == -EEXIST)
1420                                 continue;
1421                         if (r < 0)
1422                                 return r;
1423                 }
1424         }
1425 
1426         return 0;
1427 }
1428 
manager_get_dnssec_mode(Manager * m)1429 DnssecMode manager_get_dnssec_mode(Manager *m) {
1430         assert(m);
1431 
1432         if (m->dnssec_mode != _DNSSEC_MODE_INVALID)
1433                 return m->dnssec_mode;
1434 
1435         return DNSSEC_NO;
1436 }
1437 
manager_dnssec_supported(Manager * m)1438 bool manager_dnssec_supported(Manager *m) {
1439         DnsServer *server;
1440         Link *l;
1441 
1442         assert(m);
1443 
1444         if (manager_get_dnssec_mode(m) == DNSSEC_NO)
1445                 return false;
1446 
1447         server = manager_get_dns_server(m);
1448         if (server && !dns_server_dnssec_supported(server))
1449                 return false;
1450 
1451         HASHMAP_FOREACH(l, m->links)
1452                 if (!link_dnssec_supported(l))
1453                         return false;
1454 
1455         return true;
1456 }
1457 
manager_get_dns_over_tls_mode(Manager * m)1458 DnsOverTlsMode manager_get_dns_over_tls_mode(Manager *m) {
1459         assert(m);
1460 
1461         if (m->dns_over_tls_mode != _DNS_OVER_TLS_MODE_INVALID)
1462                 return m->dns_over_tls_mode;
1463 
1464         return DNS_OVER_TLS_NO;
1465 }
1466 
manager_dnssec_verdict(Manager * m,DnssecVerdict verdict,const DnsResourceKey * key)1467 void manager_dnssec_verdict(Manager *m, DnssecVerdict verdict, const DnsResourceKey *key) {
1468 
1469         assert(verdict >= 0);
1470         assert(verdict < _DNSSEC_VERDICT_MAX);
1471 
1472         if (DEBUG_LOGGING) {
1473                 char s[DNS_RESOURCE_KEY_STRING_MAX];
1474 
1475                 log_debug("Found verdict for lookup %s: %s",
1476                           dns_resource_key_to_string(key, s, sizeof s),
1477                           dnssec_verdict_to_string(verdict));
1478         }
1479 
1480         m->n_dnssec_verdict[verdict]++;
1481 }
1482 
manager_routable(Manager * m)1483 bool manager_routable(Manager *m) {
1484         Link *l;
1485 
1486         assert(m);
1487 
1488         /* Returns true if the host has at least one interface with a routable address (regardless if IPv4 or IPv6) */
1489 
1490         HASHMAP_FOREACH(l, m->links)
1491                 if (link_relevant(l, AF_UNSPEC, false))
1492                         return true;
1493 
1494         return false;
1495 }
1496 
manager_flush_caches(Manager * m,int log_level)1497 void manager_flush_caches(Manager *m, int log_level) {
1498         assert(m);
1499 
1500         LIST_FOREACH(scopes, scope, m->dns_scopes)
1501                 dns_cache_flush(&scope->cache);
1502 
1503         log_full(log_level, "Flushed all caches.");
1504 }
1505 
manager_reset_server_features(Manager * m)1506 void manager_reset_server_features(Manager *m) {
1507         Link *l;
1508 
1509         dns_server_reset_features_all(m->dns_servers);
1510         dns_server_reset_features_all(m->fallback_dns_servers);
1511 
1512         HASHMAP_FOREACH(l, m->links)
1513                 dns_server_reset_features_all(l->dns_servers);
1514 
1515         log_info("Resetting learnt feature levels on all servers.");
1516 }
1517 
manager_cleanup_saved_user(Manager * m)1518 void manager_cleanup_saved_user(Manager *m) {
1519         _cleanup_closedir_ DIR *d = NULL;
1520 
1521         assert(m);
1522 
1523         /* Clean up all saved per-link files in /run/systemd/resolve/netif/ that don't have a matching interface
1524          * anymore. These files are created to persist settings pushed in by the user via the bus, so that resolved can
1525          * be restarted without losing this data. */
1526 
1527         d = opendir("/run/systemd/resolve/netif/");
1528         if (!d) {
1529                 if (errno == ENOENT)
1530                         return;
1531 
1532                 log_warning_errno(errno, "Failed to open interface directory: %m");
1533                 return;
1534         }
1535 
1536         FOREACH_DIRENT_ALL(de, d, log_error_errno(errno, "Failed to read interface directory: %m")) {
1537                 _cleanup_free_ char *p = NULL;
1538                 int ifindex;
1539                 Link *l;
1540 
1541                 if (!IN_SET(de->d_type, DT_UNKNOWN, DT_REG))
1542                         continue;
1543 
1544                 if (dot_or_dot_dot(de->d_name))
1545                         continue;
1546 
1547                 ifindex = parse_ifindex(de->d_name);
1548                 if (ifindex < 0) /* Probably some temporary file from a previous run. Delete it */
1549                         goto rm;
1550 
1551                 l = hashmap_get(m->links, INT_TO_PTR(ifindex));
1552                 if (!l) /* link vanished */
1553                         goto rm;
1554 
1555                 if (l->is_managed) /* now managed by networkd, hence the bus settings are useless */
1556                         goto rm;
1557 
1558                 continue;
1559 
1560         rm:
1561                 p = path_join("/run/systemd/resolve/netif", de->d_name);
1562                 if (!p) {
1563                         log_oom();
1564                         return;
1565                 }
1566 
1567                 (void) unlink(p);
1568         }
1569 }
1570 
manager_next_dnssd_names(Manager * m)1571 bool manager_next_dnssd_names(Manager *m) {
1572         DnssdService *s;
1573         bool tried = false;
1574         int r;
1575 
1576         assert(m);
1577 
1578         HASHMAP_FOREACH(s, m->dnssd_services) {
1579                 _cleanup_free_ char * new_name = NULL;
1580 
1581                 if (!s->withdrawn)
1582                         continue;
1583 
1584                 r = manager_next_random_name(s->name_template, &new_name);
1585                 if (r < 0) {
1586                         log_warning_errno(r, "Failed to get new name for service '%s': %m", s->name);
1587                         continue;
1588                 }
1589 
1590                 free_and_replace(s->name_template, new_name);
1591 
1592                 s->withdrawn = false;
1593 
1594                 tried = true;
1595         }
1596 
1597         if (tried)
1598                 manager_refresh_rrs(m);
1599 
1600         return tried;
1601 }
1602 
manager_server_is_stub(Manager * m,DnsServer * s)1603 bool manager_server_is_stub(Manager *m, DnsServer *s) {
1604         DnsStubListenerExtra *l;
1605 
1606         assert(m);
1607         assert(s);
1608 
1609         /* Safety check: we generally already skip the main stub when parsing configuration. But let's be
1610          * extra careful, and check here again */
1611         if (s->family == AF_INET &&
1612             s->address.in.s_addr == htobe32(INADDR_DNS_STUB) &&
1613             dns_server_port(s) == 53)
1614                 return true;
1615 
1616         /* Main reason to call this is to check server data against the extra listeners, and filter things
1617          * out. */
1618         ORDERED_SET_FOREACH(l, m->dns_extra_stub_listeners)
1619                 if (s->family == l->family &&
1620                     in_addr_equal(s->family, &s->address, &l->address) &&
1621                     dns_server_port(s) == dns_stub_listener_extra_port(l))
1622                         return true;
1623 
1624         return false;
1625 }
1626 
socket_disable_pmtud(int fd,int af)1627 int socket_disable_pmtud(int fd, int af) {
1628         int r;
1629 
1630         assert(fd >= 0);
1631 
1632         if (af == AF_UNSPEC) {
1633                 r = socket_get_family(fd, &af);
1634                 if (r < 0)
1635                         return r;
1636         }
1637 
1638         switch (af) {
1639 
1640         case AF_INET: {
1641                 /* Turn off path MTU discovery, let's rather fragment on the way than to open us up against
1642                  * PMTU forgery vulnerabilities.
1643                  *
1644                  * There appears to be no documentation about IP_PMTUDISC_OMIT, but it has the effect that
1645                  * the "Don't Fragment" bit in the IPv4 header is turned off, thus enforcing fragmentation if
1646                  * our datagram size exceeds the MTU of a router in the path, and turning off path MTU
1647                  * discovery.
1648                  *
1649                  * This helps mitigating the PMTUD vulnerability described here:
1650                  *
1651                  * https://blog.apnic.net/2019/07/12/its-time-to-consider-avoiding-ip-fragmentation-in-the-dns/
1652                  *
1653                  * Similar logic is in place in most DNS servers.
1654                  *
1655                  * There are multiple conflicting goals: we want to allow the largest datagrams possible (for
1656                  * efficiency reasons), but not have fragmentation (for security reasons), nor use PMTUD (for
1657                  * security reasons, too). Our strategy to deal with this is: use large packets, turn off
1658                  * PMTUD, but watch fragmentation taking place, and then size our packets to the max of the
1659                  * fragments seen — and if we need larger packets always go to TCP.
1660                  */
1661 
1662                 r = setsockopt_int(fd, IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_OMIT);
1663                 if (r < 0)
1664                         return r;
1665 
1666                 return 0;
1667         }
1668 
1669         case AF_INET6: {
1670                 /* On IPv6 fragmentation only is done by the sender — never by routers on the path. PMTUD is
1671                  * mandatory. If we want to turn off PMTUD, the only way is by sending with minimal MTU only,
1672                  * so that we apply maximum fragmentation locally already, and thus PMTUD doesn't happen
1673                  * because there's nothing that could be fragmented further anymore. */
1674 
1675                 r = setsockopt_int(fd, IPPROTO_IPV6, IPV6_MTU, IPV6_MIN_MTU);
1676                 if (r < 0)
1677                         return r;
1678 
1679                 return 0;
1680         }
1681 
1682         default:
1683                 return -EAFNOSUPPORT;
1684         }
1685 }
1686