Skip to main content

retch_sysinfo/
network.rs

1// SPDX-FileCopyrightText: 2026 Ken Tobias
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4//! Network interface detection, IP resolution, Wi-Fi, and related helpers.
5
6use owo_colors::OwoColorize;
7use sysinfo::Networks;
8
9/// Detects the local IP address and active network interface name.
10pub fn detect_active_interface_and_local_ip() -> (Option<String>, Option<String>) {
11    let local_ip = std::net::UdpSocket::bind("0.0.0.0:0")
12        .ok()
13        .and_then(|socket| {
14            socket.connect("8.8.8.8:53").ok()?;
15            socket.local_addr().ok().map(|addr| addr.ip().to_string())
16        });
17
18    let active_interface = {
19        #[cfg(target_os = "linux")]
20        {
21            let native_iface = std::fs::read_to_string("/proc/net/route")
22                .ok()
23                .and_then(|content| parse_proc_net_route(&content));
24
25            native_iface.or_else(|| {
26                std::process::Command::new("ip")
27                    .args(["route", "show", "default"])
28                    .output()
29                    .ok()
30                    .and_then(|o| String::from_utf8(o.stdout).ok())
31                    .and_then(|s| {
32                        s.split_whitespace()
33                            .position(|w| w == "dev")
34                            .and_then(|i| s.split_whitespace().nth(i + 1))
35                            .map(|s| s.to_string())
36                    })
37            })
38        }
39        #[cfg(target_os = "macos")]
40        {
41            std::process::Command::new("route")
42                .args(["-n", "get", "default"])
43                .output()
44                .ok()
45                .and_then(|o| String::from_utf8(o.stdout).ok())
46                .and_then(|s| {
47                    s.lines()
48                        .find(|l| l.contains("interface:"))
49                        .and_then(|l| l.split_whitespace().last())
50                        .map(|s| s.to_string())
51                })
52        }
53        #[cfg(target_os = "windows")]
54        {
55            // Identify the active (default-route) interface as the adapter whose
56            // assigned IPs include the outbound `local_ip` we just resolved via the
57            // UDP-connect trick. This avoids spawning PowerShell `Get-NetRoute`,
58            // which costs ~1s of startup on Windows and dominated `--short` runtime.
59            // sysinfo already exposes per-interface IPs on Windows (see
60            // `detect_networks`), so no process spawn or extra API call is needed.
61            local_ip
62                .as_deref()
63                .and_then(|ip| ip.parse::<std::net::IpAddr>().ok())
64                .and_then(|target| {
65                    let networks = Networks::new_with_refreshed_list();
66                    match_active_interface(
67                        networks.iter().map(|(name, data)| {
68                            (
69                                name.to_string(),
70                                data.ip_networks().iter().map(|n| n.addr).collect(),
71                            )
72                        }),
73                        target,
74                    )
75                })
76        }
77        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
78        {
79            None
80        }
81    };
82
83    (local_ip, active_interface)
84}
85
86/// Returns the name of the interface whose assigned IPs include `local_ip`.
87///
88/// Used on Windows to identify the active (default-route) interface without a
89/// slow `Get-NetRoute` PowerShell spawn: the outbound local IP the OS picks to
90/// reach the internet uniquely belongs to the adapter carrying the default
91/// route, so matching it against each adapter's IP set yields the same answer.
92#[cfg(any(target_os = "windows", test))]
93fn match_active_interface(
94    ifaces: impl Iterator<Item = (String, Vec<std::net::IpAddr>)>,
95    local_ip: std::net::IpAddr,
96) -> Option<String> {
97    ifaces
98        .into_iter()
99        .find(|(_, ips)| ips.contains(&local_ip))
100        .map(|(name, _)| name)
101}
102
103/// Fetches the public IP address via an external service (best-effort, 2s timeout).
104pub fn detect_public_ip() -> Option<String> {
105    std::process::Command::new("curl")
106        .args(["-s", "--max-time", "2", "https://api.ipify.org"])
107        .output()
108        .ok()
109        .and_then(|o| String::from_utf8(o.stdout).ok())
110        .map(|s| s.trim().to_string())
111        .filter(|s| !s.is_empty())
112}
113
114/// Builds the formatted list of network interfaces with IP addresses and RX/TX stats.
115pub fn detect_networks(active_interface: Option<&str>, local_ip: Option<&str>) -> Vec<String> {
116    Networks::new_with_refreshed_list()
117        .iter()
118        .map(|(name, data)| {
119            let rx = format_bytes(data.total_received());
120            let tx = format_bytes(data.total_transmitted());
121            let is_up = data.operational_state() == sysinfo::InterfaceOperationalState::Up
122                || data.total_received() > 0
123                || data.total_transmitted() > 0;
124            let status = if is_up {
125                "Up".green().to_string()
126            } else {
127                "Down".red().to_string()
128            };
129
130            let mut ipv4_addresses = Vec::new();
131            let mut ipv6_addresses = Vec::new();
132
133            if is_up {
134                for ip_net in data.ip_networks() {
135                    let ip = ip_net.addr;
136                    let name_lower = name.to_lowercase();
137                    let is_loopback_iface =
138                        name_lower.starts_with("lo") || name_lower.contains("loopback");
139                    if ip.is_loopback() && !is_loopback_iface {
140                        continue;
141                    }
142                    match ip {
143                        std::net::IpAddr::V4(v4) => {
144                            ipv4_addresses.push(v4.to_string());
145                        }
146                        std::net::IpAddr::V6(v6) => {
147                            if !v6.is_unicast_link_local() {
148                                ipv6_addresses.push(v6.to_string());
149                            }
150                        }
151                    }
152                }
153
154                // Fallback to active interface UDP-resolved local IP if no IPs detected by sysinfo
155                if ipv4_addresses.is_empty() && ipv6_addresses.is_empty() {
156                    if let (Some(active), Some(ip)) = (active_interface, local_ip) {
157                        if name == active {
158                            ipv4_addresses.push(ip.to_string());
159                        }
160                    }
161                }
162            }
163
164            let ip_str = if !ipv4_addresses.is_empty() || !ipv6_addresses.is_empty() {
165                let mut combined = Vec::new();
166                if !ipv4_addresses.is_empty() {
167                    combined.push(ipv4_addresses.join(", "));
168                }
169                if !ipv6_addresses.is_empty() {
170                    combined.push(ipv6_addresses.join(", "));
171                }
172                format!(" ({})", combined.join(", "))
173            } else {
174                String::new()
175            };
176
177            format!("{}{} [{}] RX: {} TX: {}", name, ip_str, status, rx, tx)
178        })
179        .collect()
180}
181
182/// Formats a byte count into human-readable form (KB, MB, GB, etc.)
183pub fn format_bytes(bytes: u64) -> String {
184    const KB: u64 = 1024;
185    const MB: u64 = KB * 1024;
186    const GB: u64 = MB * 1024;
187
188    if bytes >= GB {
189        format!("{:.1} GB", bytes as f64 / GB as f64)
190    } else if bytes >= MB {
191        format!("{:.1} MB", bytes as f64 / MB as f64)
192    } else if bytes >= KB {
193        format!("{:.1} KB", bytes as f64 / KB as f64)
194    } else {
195        format!("{} B", bytes)
196    }
197}
198
199/// Looks up a PCI vendor name from `/usr/share/hwdata/pci.ids` (or fallback paths).
200///
201/// `vendor_id` should be a lowercase hex string without the `0x` prefix.
202pub fn lookup_pci_vendor(vendor_id: &str) -> Option<String> {
203    let vendor_id = vendor_id.trim_start_matches("0x").to_lowercase();
204    let paths = ["/usr/share/hwdata/pci.ids", "/usr/share/misc/pci.ids"];
205    for path in &paths {
206        if let Ok(content) = std::fs::read_to_string(path) {
207            for line in content.lines() {
208                if line.starts_with('#') || line.is_empty() {
209                    continue;
210                }
211                if !line.starts_with('\t') {
212                    let parts: Vec<&str> = line.split_whitespace().collect();
213                    if parts.len() >= 2 && parts[0].to_lowercase() == vendor_id {
214                        let name = line.strip_prefix(parts[0]).unwrap().trim();
215                        return Some(name.to_string());
216                    }
217                }
218            }
219        }
220    }
221    None
222}
223
224/// Detects the connected Wi-Fi network and link parameters.
225pub fn detect_wifi() -> Option<String> {
226    #[cfg(target_os = "linux")]
227    {
228        let mut wifi_interface = None;
229        if let Ok(entries) = std::fs::read_dir("/sys/class/net") {
230            for entry in entries.filter_map(|e| e.ok()) {
231                let path = entry.path();
232                if path.join("wireless").exists() || path.join("phy80211").exists() {
233                    wifi_interface = Some(entry.file_name().to_string_lossy().to_string());
234                    break;
235                }
236            }
237        }
238
239        if let Some(ref iface) = wifi_interface {
240            if let Ok(output) = std::process::Command::new("iw")
241                .args(["dev", iface, "link"])
242                .output()
243            {
244                if let Ok(stdout) = String::from_utf8(output.stdout) {
245                    let (ssid, links) = parse_iw_link_output(&stdout);
246                    if let Some(s) = ssid {
247                        let card_model = get_wifi_card_model(iface);
248                        let prefix = if let Some(m) = card_model {
249                            format!("{} [{}] - ", m, iface)
250                        } else {
251                            format!("[{}] - ", iface)
252                        };
253
254                        if !links.is_empty() {
255                            let mut link_strs = Vec::new();
256                            for link in links {
257                                let freq_str = link.freq.map(|f| {
258                                    let ghz_mhz = if f >= 1000.0 {
259                                        format!("{:.1} GHz", f / 1000.0)
260                                    } else {
261                                        format!("{} MHz", f)
262                                    };
263                                    if let Some(ch) = freq_to_channel(f) {
264                                        format!("{} ch{}", ghz_mhz, ch)
265                                    } else {
266                                        ghz_mhz
267                                    }
268                                });
269
270                                let mut rx_tx = Vec::new();
271                                if let Some(rx) = link.rx_rate {
272                                    if rx != "0"
273                                        && !rx.starts_with("0 ")
274                                        && rx != "0 Mbps"
275                                        && rx != "0 MBit/s"
276                                    {
277                                        rx_tx.push(format!("↓{}", clean_rate(&rx)));
278                                    }
279                                }
280                                if let Some(tx) = link.tx_rate {
281                                    if tx != "0"
282                                        && !tx.starts_with("0 ")
283                                        && tx != "0 Mbps"
284                                        && tx != "0 MBit/s"
285                                    {
286                                        rx_tx.push(format!("↑{}", clean_rate(&tx)));
287                                    }
288                                }
289
290                                match (freq_str, rx_tx.is_empty()) {
291                                    (Some(f), false) => {
292                                        link_strs.push(format!("{} [{}]", f, rx_tx.join(" ")))
293                                    }
294                                    (Some(f), true) => link_strs.push(f),
295                                    (None, false) => link_strs.push(rx_tx.join(" ")),
296                                    _ => {}
297                                }
298                            }
299                            if !link_strs.is_empty() {
300                                return Some(format!(
301                                    "{}{}{} ({})",
302                                    prefix,
303                                    s,
304                                    "",
305                                    link_strs.join(", ")
306                                ));
307                            } else {
308                                return Some(format!("{}{}", prefix, s));
309                            }
310                        }
311                        return Some(format!("{}{}", prefix, s));
312                    }
313                }
314            }
315        }
316
317        // Fallback to nmcli (using --rescan no to avoid slow hardware channel scans)
318        if let Ok(output) = std::process::Command::new("nmcli")
319            .args([
320                "-t",
321                "-f",
322                "active,ssid,rate",
323                "device",
324                "wifi",
325                "list",
326                "--rescan",
327                "no",
328            ])
329            .output()
330        {
331            if let Ok(stdout) = String::from_utf8(output.stdout) {
332                for line in stdout.lines() {
333                    let line = line.trim();
334                    if let Some(rest) = line.strip_prefix("yes:") {
335                        if let Some(colon_idx) = rest.rfind(':') {
336                            let ssid = &rest[..colon_idx];
337                            let rate = rest[colon_idx + 1..].trim();
338                            if !ssid.is_empty() {
339                                if !rate.is_empty()
340                                    && rate != "0"
341                                    && !rate.starts_with("0 ")
342                                    && rate != "0 Mbit/s"
343                                    && rate != "0 Mbps"
344                                {
345                                    return Some(format!("{} ({})", ssid, clean_rate(rate)));
346                                } else {
347                                    return Some(ssid.to_string());
348                                }
349                            }
350                        } else if !rest.is_empty() {
351                            return Some(rest.to_string());
352                        }
353                    }
354                }
355            }
356        }
357
358        // Fallback to iwgetid
359        if let Ok(output) = std::process::Command::new("iwgetid").arg("-r").output() {
360            if let Ok(stdout) = String::from_utf8(output.stdout) {
361                let ssid = stdout.trim();
362                if !ssid.is_empty() {
363                    return Some(ssid.to_string());
364                }
365            }
366        }
367        None
368    }
369
370    #[cfg(target_os = "macos")]
371    {
372        crate::macos_ffi::get_wifi_info().map(|(ssid, rate)| match rate {
373            Some(r) if r > 0 => format!("{} (↑{} Mbps)", ssid, r),
374            _ => ssid,
375        })
376    }
377
378    #[cfg(target_os = "windows")]
379    {
380        if let Ok(output) = std::process::Command::new("netsh")
381            .args(["wlan", "show", "interfaces"])
382            .output()
383        {
384            if let Ok(stdout) = String::from_utf8(output.stdout) {
385                return parse_netsh_output(&stdout);
386            }
387        }
388        None
389    }
390
391    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
392    {
393        None
394    }
395}
396
397#[cfg(any(target_os = "linux", test))]
398pub fn parse_proc_net_route(content: &str) -> Option<String> {
399    for line in content.lines().skip(1) {
400        let parts: Vec<&str> = line.split_whitespace().collect();
401        if parts.len() >= 8 {
402            let dest = parts[1];
403            let mask = parts[7];
404            if dest == "00000000" && mask == "00000000" {
405                return Some(parts[0].to_string());
406            }
407        }
408    }
409    None
410}
411
412#[allow(
413    clippy::manual_is_multiple_of,
414    clippy::manual_range_contains,
415    dead_code
416)]
417fn freq_to_channel(freq_mhz: f64) -> Option<u32> {
418    let freq = freq_mhz.round() as u32;
419    if freq >= 2412 && freq <= 2472 {
420        Some((freq - 2407) / 5)
421    } else if freq == 2484 {
422        Some(14)
423    } else if freq >= 5160 && freq <= 5885 {
424        if (freq - 5000) % 5 == 0 {
425            Some((freq - 5000) / 5)
426        } else {
427            None
428        }
429    } else if freq >= 5955 && freq <= 7115 {
430        if (freq - 5950) % 5 == 0 {
431            Some((freq - 5950) / 5)
432        } else {
433            None
434        }
435    } else {
436        None
437    }
438}
439
440#[allow(dead_code)]
441fn get_wifi_card_model(iface: &str) -> Option<String> {
442    let vendor = std::fs::read_to_string(format!("/sys/class/net/{}/device/vendor", iface)).ok()?;
443    let device = std::fs::read_to_string(format!("/sys/class/net/{}/device/device", iface)).ok()?;
444    let vendor_clean = vendor.trim().trim_start_matches("0x").to_lowercase();
445    let device_clean = device.trim().trim_start_matches("0x").to_lowercase();
446
447    let vendor_name = lookup_pci_vendor(&vendor_clean);
448    let model_name = crate::gpu::lookup_pci_device(&vendor_clean, &device_clean);
449
450    match (vendor_name, model_name) {
451        (Some(v), Some(m)) => {
452            let v_clean = v.replace(", Inc.", "").replace(" Corporation", "");
453            if m.to_lowercase().contains(&v_clean.to_lowercase())
454                || m.to_lowercase().contains(
455                    &v_clean
456                        .split_whitespace()
457                        .next()
458                        .unwrap_or("")
459                        .to_lowercase(),
460                )
461            {
462                Some(m)
463            } else {
464                Some(format!("{} {}", v_clean, m))
465            }
466        }
467        (None, Some(m)) => Some(m),
468        _ => None,
469    }
470}
471
472#[allow(dead_code)]
473fn clean_rate(rate: &str) -> String {
474    rate.replace("MBit/s", "Mbps")
475        .replace("GBit/s", "Gbps")
476        .replace("Bit/s", "bps")
477}
478
479#[derive(Debug, Clone)]
480pub struct WifiLink {
481    pub freq: Option<f64>,
482    pub rx_rate: Option<String>,
483    pub tx_rate: Option<String>,
484}
485
486#[allow(dead_code)]
487pub fn parse_iw_link_output(stdout: &str) -> (Option<String>, Vec<WifiLink>) {
488    let mut ssid = None;
489    let mut links = Vec::new();
490    let mut current_link = None;
491
492    for line in stdout.lines() {
493        let trimmed = line.trim();
494        if trimmed.starts_with("Connected to") || trimmed.starts_with("link") {
495            if let Some(link) = current_link.take() {
496                links.push(link);
497            }
498            current_link = Some(WifiLink {
499                freq: None,
500                rx_rate: None,
501                tx_rate: None,
502            });
503        } else if trimmed.starts_with("SSID:") {
504            ssid = Some(trimmed.strip_prefix("SSID:").unwrap().trim().to_string());
505        } else if trimmed.starts_with("freq:") {
506            if let Some(ref mut link) = current_link {
507                let freq_str = trimmed.strip_prefix("freq:").unwrap().trim();
508                link.freq = freq_str.parse::<f64>().ok();
509            }
510        } else if trimmed.starts_with("rx bitrate:") {
511            if let Some(ref mut link) = current_link {
512                let rx_str = trimmed.strip_prefix("rx bitrate:").unwrap().trim();
513                let rate = rx_str
514                    .split_whitespace()
515                    .take(2)
516                    .collect::<Vec<&str>>()
517                    .join(" ");
518                link.rx_rate = Some(rate);
519            }
520        } else if trimmed.starts_with("tx bitrate:") {
521            if let Some(ref mut link) = current_link {
522                let tx_str = trimmed.strip_prefix("tx bitrate:").unwrap().trim();
523                let rate = tx_str
524                    .split_whitespace()
525                    .take(2)
526                    .collect::<Vec<&str>>()
527                    .join(" ");
528                link.tx_rate = Some(rate);
529            }
530        }
531    }
532    if let Some(link) = current_link {
533        links.push(link);
534    }
535    (ssid, links)
536}
537
538#[allow(dead_code)]
539pub fn parse_netsh_output(stdout: &str) -> Option<String> {
540    let mut ssid = None;
541    let mut rx = None;
542    let mut tx = None;
543    let mut band = None;
544    for line in stdout.lines() {
545        let trimmed = line.trim();
546        if trimmed.starts_with("SSID") {
547            if let Some(idx) = trimmed.find(':') {
548                let val = trimmed[idx + 1..].trim().to_string();
549                if !val.is_empty() {
550                    ssid = Some(val);
551                }
552            }
553        } else if trimmed.starts_with("Receive rate (Mbps)") {
554            if let Some(idx) = trimmed.find(':') {
555                let val = trimmed[idx + 1..].trim().to_string();
556                if !val.is_empty() {
557                    rx = Some(val);
558                }
559            }
560        } else if trimmed.starts_with("Transmit rate (Mbps)") {
561            if let Some(idx) = trimmed.find(':') {
562                let val = trimmed[idx + 1..].trim().to_string();
563                if !val.is_empty() {
564                    tx = Some(val);
565                }
566            }
567        } else if trimmed.starts_with("Band") {
568            if let Some(idx) = trimmed.find(':') {
569                let val = trimmed[idx + 1..].trim().to_string();
570                if !val.is_empty() {
571                    band = Some(val);
572                }
573            }
574        }
575    }
576    if let Some(s) = ssid {
577        let mut rate_strs = Vec::new();
578        if let Some(rx_val) = rx {
579            if rx_val != "0" {
580                rate_strs.push(format!("↓{} Mbps", rx_val));
581            }
582        }
583        if let Some(tx_val) = tx {
584            if tx_val != "0" {
585                rate_strs.push(format!("↑{} Mbps", tx_val));
586            }
587        }
588        let info = match (band, rate_strs.is_empty()) {
589            (Some(b), false) => format!("{} [{}]", b, rate_strs.join(" ")),
590            (Some(b), true) => b,
591            (None, false) => rate_strs.join(" "),
592            _ => String::new(),
593        };
594        if !info.is_empty() {
595            Some(format!("{} ({})", s, info))
596        } else {
597            Some(s)
598        }
599    } else {
600        None
601    }
602}
603
604/// Returns the list of configured DNS nameserver addresses.
605///
606/// Linux/macOS: parses `nameserver` lines from `/etc/resolv.conf`.
607/// Windows: runs PowerShell `Get-DnsClientServerAddress`.
608/// Returns an empty `Vec` if nothing is found.
609pub fn detect_dns() -> Vec<String> {
610    #[cfg(any(target_os = "linux", target_os = "macos"))]
611    {
612        if let Ok(content) = std::fs::read_to_string("/etc/resolv.conf") {
613            return parse_resolv_conf(&content);
614        }
615    }
616    #[cfg(target_os = "windows")]
617    {
618        if let Ok(output) = std::process::Command::new("powershell")
619            .args([
620                "-Command",
621                "Get-DnsClientServerAddress -AddressFamily IPv4 | Select-Object -ExpandProperty ServerAddresses | Sort-Object -Unique",
622            ])
623            .output()
624        {
625            if let Ok(stdout) = String::from_utf8(output.stdout) {
626                let servers: Vec<String> = stdout
627                    .lines()
628                    .map(|l| l.trim().to_string())
629                    .filter(|l| !l.is_empty())
630                    .collect();
631                if !servers.is_empty() {
632                    return servers;
633                }
634            }
635        }
636    }
637    Vec::new()
638}
639
640#[cfg(any(target_os = "linux", target_os = "macos", test))]
641pub fn parse_resolv_conf(content: &str) -> Vec<String> {
642    content
643        .lines()
644        .filter_map(|line| {
645            let line = line.trim();
646            if line.starts_with('#') || line.starts_with(';') {
647                return None;
648            }
649            let mut parts = line.split_whitespace();
650            if parts.next()? == "nameserver" {
651                parts.next().map(|s| s.to_string())
652            } else {
653                None
654            }
655        })
656        .collect()
657}
658
659/// Returns the configured DNS domain name.
660///
661/// On **Linux**, the domain of the link carrying the IP default route wins (see
662/// [`resolve_default_route_domain`]). `/etc/resolv.conf` is only a fallback there, because
663/// under systemd-resolved it is the stub file whose `search` list is the *merged* set of
664/// every link's domains — so its first entry is frequently a VPN's domain rather than the
665/// default route's. On **macOS**, `/etc/resolv.conf` is written by configd from the primary
666/// network service, so it is read directly. On **Windows**, queries the primary DNS domain
667/// via `GetComputerNameExW` (`ComputerNameDnsDomain`).
668///
669/// Returns `None` when no domain is configured (e.g. a workgroup machine, or a default-route
670/// link with no DNS domain of its own) or the source is unavailable.
671pub fn detect_domain() -> Option<String> {
672    #[cfg(target_os = "linux")]
673    {
674        // Ask systemd-resolved what the *default-route* link's domain is. When it manages
675        // that link its answer is authoritative — including "no domain" — so we must not
676        // fall through to resolv.conf's merged list, which is what leaks a VPN's domain.
677        if let (Some(iface), Some(status)) = (default_route_interface(), resolvectl_status()) {
678            if let DefaultRouteDomain::Managed(domain) =
679                resolve_default_route_domain(&parse_resolvectl_domains(status), &iface)
680            {
681                return domain;
682            }
683        }
684        read_resolv_conf_domain()
685    }
686    #[cfg(target_os = "macos")]
687    {
688        read_resolv_conf_domain()
689    }
690    #[cfg(target_os = "windows")]
691    {
692        detect_domain_windows()
693    }
694    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
695    {
696        None
697    }
698}
699
700/// Reads the `domain`/`search` fallback from `/etc/resolv.conf`.
701#[cfg(any(target_os = "linux", target_os = "macos"))]
702fn read_resolv_conf_domain() -> Option<String> {
703    std::fs::read_to_string("/etc/resolv.conf")
704        .ok()
705        .and_then(|content| parse_domain_from_resolv_conf(&content))
706}
707
708/// Returns the interface carrying the IP default route, from `/proc/net/route`.
709///
710/// Deliberately the *routing table*, not resolvectl's `Default Route:` field — that field is
711/// systemd-resolved's DNS-routing flag (may this link's servers answer arbitrary queries)
712/// and is commonly `yes` for a VPN link and the physical link simultaneously, so it cannot
713/// identify the default route.
714#[cfg(target_os = "linux")]
715fn default_route_interface() -> Option<String> {
716    std::fs::read_to_string("/proc/net/route")
717        .ok()
718        .and_then(|content| parse_proc_net_route(&content))
719}
720
721/// Cached output of `resolvectl status --no-pager`, or `None` if it is unavailable.
722#[cfg(target_os = "linux")]
723static RESOLVECTL_STATUS: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
724
725/// Runs `resolvectl status --no-pager` at most once per process and caches the output.
726///
727/// Both the `domain` and `domain-search` fields need it, and they are collected
728/// sequentially; retch is a short-lived one-shot process, so a process-lifetime cache
729/// cannot go stale and saves a second ~5 ms spawn in `--full`.
730#[cfg(target_os = "linux")]
731fn resolvectl_status() -> Option<&'static str> {
732    RESOLVECTL_STATUS
733        .get_or_init(|| {
734            let output = std::process::Command::new("resolvectl")
735                .args(["status", "--no-pager"])
736                .output()
737                .ok()?;
738            if !output.status.success() {
739                return None;
740            }
741            Some(String::from_utf8_lossy(&output.stdout).into_owned())
742        })
743        .as_deref()
744}
745
746/// Windows: returns the host's primary DNS domain via `GetComputerNameExW`.
747///
748/// Uses the two-call size-probing convention: a first call with a null buffer
749/// reports the required length, the second fills the buffer. A workgroup
750/// (non-domain-joined) host reports an empty DNS domain, which
751/// [`clean_domain`] maps to `None`.
752#[cfg(target_os = "windows")]
753fn detect_domain_windows() -> Option<String> {
754    use std::os::windows::ffi::OsStringExt;
755
756    // COMPUTER_NAME_FORMAT::ComputerNameDnsDomain
757    const COMPUTER_NAME_DNS_DOMAIN: i32 = 2;
758
759    // kernel32 is linked by default on the MSVC target.
760    extern "system" {
761        fn GetComputerNameExW(name_type: i32, lp_buffer: *mut u16, n_size: *mut u32) -> i32;
762    }
763
764    // First call: null buffer + size 0 asks the OS for the required length
765    // (in wide chars, including the trailing NUL). It fails and sets `size`.
766    let mut size: u32 = 0;
767    // SAFETY: the null-buffer / zero-size form is the documented size probe;
768    // the OS only writes the required length back through `size`.
769    unsafe {
770        GetComputerNameExW(COMPUTER_NAME_DNS_DOMAIN, std::ptr::null_mut(), &mut size);
771    }
772    if size == 0 {
773        return None;
774    }
775
776    let mut buf = vec![0u16; size as usize];
777    // SAFETY: `buf` has `size` wide chars of capacity; `size` is passed by
778    // pointer so the OS reports the final length (excluding the NUL). The call
779    // writes at most `size` code units.
780    let ok = unsafe { GetComputerNameExW(COMPUTER_NAME_DNS_DOMAIN, buf.as_mut_ptr(), &mut size) };
781    if ok == 0 {
782        return None;
783    }
784
785    let s = std::ffi::OsString::from_wide(&buf[..size as usize])
786        .to_string_lossy()
787        .into_owned();
788    clean_domain(&s)
789}
790
791/// Trims a raw domain string and maps the empty string to `None`.
792///
793/// A non-domain-joined Windows host reports an empty DNS domain; treat that as
794/// "no domain configured" rather than surfacing an empty value.
795#[cfg(any(target_os = "windows", test))]
796fn clean_domain(raw: &str) -> Option<String> {
797    let trimmed = raw.trim();
798    if trimmed.is_empty() {
799        None
800    } else {
801        Some(trimmed.to_string())
802    }
803}
804
805/// Returns per-interface DNS search domain lists.
806///
807/// On Linux, tries `resolvectl status --no-pager` first and parses per-link
808/// DNS Domain / DNS Search Domains entries. Falls back to the global `search`
809/// list from `/etc/resolv.conf` when resolvectl is unavailable.
810/// On macOS, reads the global `search` list from `/etc/resolv.conf`.
811pub fn detect_domain_search() -> Vec<String> {
812    #[cfg(target_os = "linux")]
813    {
814        // Shares the one cached `resolvectl` spawn with `detect_domain`.
815        if let Some(status) = resolvectl_status() {
816            let result = parse_resolvectl_search(status);
817            if !result.is_empty() {
818                return result;
819            }
820        }
821        if let Ok(content) = std::fs::read_to_string("/etc/resolv.conf") {
822            return format_global_search_domains(&parse_search_from_resolv_conf(&content));
823        }
824    }
825    #[cfg(target_os = "macos")]
826    {
827        if let Ok(content) = std::fs::read_to_string("/etc/resolv.conf") {
828            return format_global_search_domains(&parse_search_from_resolv_conf(&content));
829        }
830    }
831    Vec::new()
832}
833
834/// Scope label for search domains that carry no per-interface attribution.
835///
836/// `/etc/resolv.conf`'s `search` list is a single global list — it does not say which link
837/// each domain came from — so it is labelled honestly rather than attributed to an
838/// interface, which would be a fabrication on a multi-homed host.
839#[cfg(any(target_os = "linux", target_os = "macos", test))]
840const GLOBAL_SEARCH_SCOPE: &str = "global";
841
842/// Renders a scope-less (global) search-domain list in the same shape as the per-link
843/// resolvectl path: one entry of `"<scope>: a, b"`.
844///
845/// Without this the `Domain Search` field had no stable shape, and the difference was
846/// *source*-driven rather than platform-driven — the same OS flipped format depending on
847/// whether systemd-resolved was reachable. In CI, Ubuntu on a bare runner rendered
848/// `eth0: example.com` (resolvectl) while the very same Ubuntu inside a container rendered a
849/// bare `example.com` (this fallback), and Fedora — always containerised — looked
850/// permanently "different from Ubuntu" for no platform reason at all.
851///
852/// Two things were inconsistent, not just the prefix: the resolvectl path returns **one entry
853/// per interface** with domains joined by `", "`, whereas the raw fallback returned **one
854/// entry per domain**, and the display prints one line per entry — so a host with
855/// `search a b c` emitted three separate bare `Domain Search:` lines. Both are normalised
856/// here.
857#[cfg(any(target_os = "linux", target_os = "macos", test))]
858pub fn format_global_search_domains(domains: &[String]) -> Vec<String> {
859    if domains.is_empty() {
860        Vec::new()
861    } else {
862        vec![format!("{}: {}", GLOBAL_SEARCH_SCOPE, domains.join(", "))]
863    }
864}
865
866/// Parses the `domain` directive (or first `search` entry as fallback) from
867/// `/etc/resolv.conf` content.
868#[cfg(any(target_os = "linux", target_os = "macos", test))]
869pub fn parse_domain_from_resolv_conf(content: &str) -> Option<String> {
870    let mut first_search: Option<String> = None;
871    for line in content.lines() {
872        let line = line.trim();
873        if line.starts_with('#') || line.starts_with(';') {
874            continue;
875        }
876        let mut parts = line.split_whitespace();
877        match parts.next() {
878            Some("domain") => {
879                if let Some(d) = parts.next() {
880                    return Some(d.to_string());
881                }
882            }
883            Some("search") if first_search.is_none() => {
884                if let Some(d) = parts.next() {
885                    first_search = Some(d.to_string());
886                }
887            }
888            _ => {}
889        }
890    }
891    first_search
892}
893
894/// Parses all entries from the `search` directive in `/etc/resolv.conf` content.
895#[cfg(any(target_os = "linux", target_os = "macos", test))]
896pub fn parse_search_from_resolv_conf(content: &str) -> Vec<String> {
897    for line in content.lines() {
898        let line = line.trim();
899        if line.starts_with('#') || line.starts_with(';') {
900            continue;
901        }
902        let mut parts = line.split_whitespace();
903        if parts.next() == Some("search") {
904            let domains: Vec<String> = parts.map(|s| s.to_string()).collect();
905            if !domains.is_empty() {
906                return domains;
907            }
908        }
909    }
910    Vec::new()
911}
912
913/// One link's DNS search domains, as reported by `resolvectl status`.
914#[derive(Debug, Clone, Default, PartialEq, Eq)]
915#[cfg(any(target_os = "linux", test))]
916pub struct LinkDomains {
917    /// Interface name, e.g. `wlp194s0`.
918    pub interface: String,
919    /// Search domains in report order, with routing-only (`~`-prefixed) entries removed.
920    /// Empty means systemd-resolved manages this link but it has no search domain.
921    pub search: Vec<String>,
922}
923
924/// DNS search domains from `resolvectl status`, split by scope.
925#[derive(Debug, Clone, Default, PartialEq, Eq)]
926#[cfg(any(target_os = "linux", test))]
927pub struct ResolvectlDomains {
928    /// Domains from the `Global` section (e.g. `resolved.conf`'s `Domains=`), which belong
929    /// to no particular interface.
930    pub global: Vec<String>,
931    /// One entry per `Link N (iface)` section, in report order.
932    pub links: Vec<LinkDomains>,
933}
934
935/// Outcome of looking up the default-route link in [`ResolvectlDomains`].
936#[derive(Debug, Clone, PartialEq, Eq)]
937#[cfg(any(target_os = "linux", test))]
938pub enum DefaultRouteDomain {
939    /// systemd-resolved manages the link, so its answer is authoritative. `None` means the
940    /// link genuinely has no domain — the caller must **not** fall back to the merged
941    /// `/etc/resolv.conf` search list, which would resurrect another link's (e.g. a VPN's)
942    /// domain.
943    Managed(Option<String>),
944    /// The link has no section in the resolvectl output, so systemd-resolved has no opinion
945    /// about it; the caller should fall back to `/etc/resolv.conf`.
946    Unmanaged,
947}
948
949/// Picks the domain to display for `interface` from parsed resolvectl output.
950///
951/// Prefers the link's own first search domain, then a `Global` domain (interface-independent,
952/// so it cannot be another link's). Never returns a *different* link's domain — that is the
953/// whole point: the default route's domain must win over a VPN's.
954#[cfg(any(target_os = "linux", test))]
955pub fn resolve_default_route_domain(
956    domains: &ResolvectlDomains,
957    interface: &str,
958) -> DefaultRouteDomain {
959    match domains.links.iter().find(|l| l.interface == interface) {
960        Some(link) => DefaultRouteDomain::Managed(
961            link.search
962                .first()
963                .or_else(|| domains.global.first())
964                .cloned(),
965        ),
966        None => DefaultRouteDomain::Unmanaged,
967    }
968}
969
970/// Parses `resolvectl status --no-pager` output into per-scope DNS search domains.
971///
972/// Handles the two shapes that tripped up the previous single-line parser:
973/// - **Wrapped values.** resolvectl right-aligns labels and continues long values on
974///   following indented, label-less lines; those continuations were silently dropped.
975/// - **Routing-only domains.** systemd prefixes a domain with `~` when it should only
976///   *route* queries to that link, never be appended as a search suffix. Every `~` entry is
977///   excluded (the old code special-cased only the exact catch-all `~.`).
978///
979/// Sections are recognised by content (`Global`, `Link N (iface)`) rather than by indentation,
980/// since resolvectl's exact column padding varies with the longest label present. A `Link`
981/// header always creates an entry, even with no domain line, so callers can distinguish
982/// "managed, no domain" from "not managed at all".
983#[cfg(any(target_os = "linux", test))]
984pub fn parse_resolvectl_domains(content: &str) -> ResolvectlDomains {
985    let mut out = ResolvectlDomains::default();
986    // `None` = the Global section, `Some(iface)` = that link's section.
987    let mut section: Option<String> = None;
988    // True while consuming the (possibly wrapped) value of a DNS domain field.
989    let mut in_domain_value = false;
990
991    for line in content.lines() {
992        let trimmed = line.trim();
993        if trimmed.is_empty() {
994            in_domain_value = false;
995            continue;
996        }
997
998        // "Link N (iface)" starts a link section. Checked before the continuation branch
999        // below, since a header carries no colon either.
1000        if let Some(iface) = trimmed
1001            .strip_prefix("Link ")
1002            .and_then(|rest| rest.split_once('('))
1003            .and_then(|(_, rest)| rest.split_once(')'))
1004            .map(|(iface, _)| iface)
1005        {
1006            in_domain_value = false;
1007            section = Some(iface.to_string());
1008            // Record the link even if it never reports a domain.
1009            if !out.links.iter().any(|l| l.interface == iface) {
1010                out.links.push(LinkDomains {
1011                    interface: iface.to_string(),
1012                    search: Vec::new(),
1013                });
1014            }
1015            continue;
1016        }
1017
1018        if trimmed == "Global" {
1019            in_domain_value = false;
1020            section = None;
1021            continue;
1022        }
1023
1024        if let Some(value) = trimmed
1025            .strip_prefix("DNS Domain:")
1026            .or_else(|| trimmed.strip_prefix("DNS Search Domains:"))
1027        {
1028            in_domain_value = true;
1029            push_resolvectl_domains(&mut out, section.as_deref(), value);
1030            continue;
1031        }
1032
1033        // A wrapped continuation of the domain value carries no `label:` of its own, and
1034        // domain names cannot contain ':' — so any colon means a new field has started.
1035        if in_domain_value && !trimmed.contains(':') {
1036            push_resolvectl_domains(&mut out, section.as_deref(), trimmed);
1037            continue;
1038        }
1039        in_domain_value = false;
1040    }
1041    out
1042}
1043
1044/// Appends whitespace-separated domains from one resolvectl value fragment to `section`,
1045/// dropping systemd routing-only (`~`-prefixed) entries.
1046#[cfg(any(target_os = "linux", test))]
1047fn push_resolvectl_domains(out: &mut ResolvectlDomains, section: Option<&str>, value: &str) {
1048    let domains = value
1049        .split_whitespace()
1050        .filter(|d| !d.starts_with('~'))
1051        .map(|d| d.to_string());
1052    match section {
1053        Some(iface) => match out.links.iter_mut().find(|l| l.interface == iface) {
1054            Some(link) => link.search.extend(domains),
1055            None => out.links.push(LinkDomains {
1056                interface: iface.to_string(),
1057                search: domains.collect(),
1058            }),
1059        },
1060        None => out.global.extend(domains),
1061    }
1062}
1063
1064/// Parses `resolvectl status --no-pager` output into per-interface search domain strings.
1065///
1066/// Formats [`parse_resolvectl_domains`] as `"wlan0: home.local"` entries, one per link,
1067/// skipping links with no search domain of their own.
1068#[cfg(any(target_os = "linux", test))]
1069pub fn parse_resolvectl_search(content: &str) -> Vec<String> {
1070    parse_resolvectl_domains(content)
1071        .links
1072        .into_iter()
1073        .filter(|link| !link.search.is_empty())
1074        .map(|link| format!("{}: {}", link.interface, link.search.join(", ")))
1075        .collect()
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080    use super::*;
1081
1082    #[test]
1083    fn test_clean_domain() {
1084        // Normal domain passes through.
1085        assert_eq!(
1086            clean_domain("corp.example.com"),
1087            Some("corp.example.com".to_string())
1088        );
1089        // Surrounding whitespace is trimmed.
1090        assert_eq!(
1091            clean_domain("  example.org \n"),
1092            Some("example.org".to_string())
1093        );
1094        // A workgroup host reports an empty domain -> None (not Some("")).
1095        assert_eq!(clean_domain(""), None);
1096        assert_eq!(clean_domain("   "), None);
1097    }
1098
1099    #[test]
1100    fn test_match_active_interface() {
1101        use std::net::IpAddr;
1102        let target: IpAddr = "192.168.1.50".parse().unwrap();
1103        let ifaces = vec![
1104            ("lo".to_string(), vec!["127.0.0.1".parse().unwrap()]),
1105            (
1106                "Ethernet".to_string(),
1107                vec!["192.168.1.50".parse().unwrap(), "fe80::1".parse().unwrap()],
1108            ),
1109            ("Wi-Fi".to_string(), vec!["10.0.0.2".parse().unwrap()]),
1110        ];
1111        // Matches the adapter that actually holds the outbound local IP.
1112        assert_eq!(
1113            match_active_interface(ifaces.into_iter(), target),
1114            Some("Ethernet".to_string())
1115        );
1116
1117        // No adapter holds the target IP -> None (e.g. offline / unresolved).
1118        let orphan: IpAddr = "8.8.8.8".parse().unwrap();
1119        let ifaces2 = vec![(
1120            "lo".to_string(),
1121            vec!["127.0.0.1".parse::<IpAddr>().unwrap()],
1122        )];
1123        assert_eq!(match_active_interface(ifaces2.into_iter(), orphan), None);
1124    }
1125
1126    #[test]
1127    fn test_format_bytes() {
1128        assert_eq!(format_bytes(500), "500 B");
1129        assert_eq!(format_bytes(1024), "1.0 KB");
1130        assert_eq!(format_bytes(1024 * 1024), "1.0 MB");
1131        assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB");
1132        assert_eq!(format_bytes(1536), "1.5 KB");
1133    }
1134
1135    #[test]
1136    fn test_parse_proc_net_route() {
1137        let sample =
1138            "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\
1139                      wlan0\t0000A8C0\t00000000\t0001\t0\t0\t600\t0000FFFF\t0\t0\t0\n\
1140                      wlan0\t00000000\t0100A8C0\t0003\t0\t0\t600\t00000000\t0\t0\t0\n";
1141        assert_eq!(parse_proc_net_route(sample), Some("wlan0".to_string()));
1142
1143        let sample_no_default =
1144            "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\
1145                                 wlan0\t0000A8C0\t00000000\t0001\t0\t0\t600\t0000FFFF\t0\t0\t0\n";
1146        assert_eq!(parse_proc_net_route(sample_no_default), None);
1147    }
1148
1149    #[test]
1150    fn test_parse_netsh_output() {
1151        let sample = "    Name                   : Wi-Fi\n    State                  : connected\n    SSID                   : Office_Wi-Fi\n    Receive rate (Mbps)    : 433\n    Transmit rate (Mbps)   : 866\n    Band                   : 5 GHz\n";
1152        assert_eq!(
1153            parse_netsh_output(sample),
1154            Some("Office_Wi-Fi (5 GHz [↓433 Mbps ↑866 Mbps])".to_string())
1155        );
1156    }
1157
1158    #[test]
1159    fn test_parse_iw_link_output() {
1160        let sample = "Connected to 84:78:48:dc:97:23 (on wlp2s0)\n        SSID: OfficeNet\n        freq: 6135.0\n        rx bitrate: 6.0 MBit/s\n        tx bitrate: 864.6 MBit/s 160MHz HE-MCS 4\n";
1161        let (ssid, links) = parse_iw_link_output(sample);
1162        assert_eq!(ssid, Some("OfficeNet".to_string()));
1163        assert_eq!(links.len(), 1);
1164        assert_eq!(links[0].freq, Some(6135.0));
1165        assert_eq!(links[0].rx_rate, Some("6.0 MBit/s".to_string()));
1166        assert_eq!(links[0].tx_rate, Some("864.6 MBit/s".to_string()));
1167
1168        // MLO multi-link mock output
1169        let sample_mlo = "Connected to aa:bb:cc:dd:ee:ff (on wlan0)\n        SSID: HomeWiFi\n        freq: 5180.0\n        rx bitrate: 866.0 MBit/s\n        tx bitrate: 866.0 MBit/s\nConnected to aa:bb:cc:dd:ee:01 (on wlan0)\n        freq: 6135.0\n        rx bitrate: 1200.0 MBit/s\n        tx bitrate: 1200.0 MBit/s\n";
1170        let (ssid_mlo, links_mlo) = parse_iw_link_output(sample_mlo);
1171        assert_eq!(ssid_mlo, Some("HomeWiFi".to_string()));
1172        assert_eq!(links_mlo.len(), 2);
1173        assert_eq!(links_mlo[0].freq, Some(5180.0));
1174        assert_eq!(links_mlo[1].freq, Some(6135.0));
1175    }
1176
1177    #[test]
1178    fn test_parse_resolv_conf() {
1179        let sample = "# Generated by NetworkManager\ndomain home\nsearch home\nnameserver 192.168.1.1\nnameserver 8.8.8.8\n; comment\nnameserver 2001:db8::1\n";
1180        assert_eq!(
1181            parse_resolv_conf(sample),
1182            vec!["192.168.1.1", "8.8.8.8", "2001:db8::1"]
1183        );
1184
1185        let empty = "# no nameservers\nsearch local\n";
1186        assert_eq!(parse_resolv_conf(empty), Vec::<String>::new());
1187    }
1188
1189    #[test]
1190    fn test_parse_domain_from_resolv_conf_domain_directive() {
1191        let s = "# test\ndomain example.com\nsearch fallback.com\nnameserver 1.1.1.1\n";
1192        assert_eq!(
1193            parse_domain_from_resolv_conf(s),
1194            Some("example.com".to_string())
1195        );
1196    }
1197
1198    #[test]
1199    fn test_parse_domain_from_resolv_conf_search_fallback() {
1200        let s = "# no domain directive\nsearch local.lan other.lan\nnameserver 1.1.1.1\n";
1201        assert_eq!(
1202            parse_domain_from_resolv_conf(s),
1203            Some("local.lan".to_string())
1204        );
1205    }
1206
1207    #[test]
1208    fn test_parse_domain_from_resolv_conf_none() {
1209        let s = "# no domain or search\nnameserver 1.1.1.1\n";
1210        assert_eq!(parse_domain_from_resolv_conf(s), None);
1211    }
1212
1213    #[test]
1214    fn test_parse_search_from_resolv_conf() {
1215        let s = "search home.local corp.example.com\nnameserver 1.1.1.1\n";
1216        assert_eq!(
1217            parse_search_from_resolv_conf(s),
1218            vec!["home.local", "corp.example.com"]
1219        );
1220    }
1221
1222    #[test]
1223    fn test_parse_resolvectl_search_basic() {
1224        let sample = "Global\n\
1225            Link 2 (lo)\n\
1226              Current Scopes: none\n\
1227            Link 3 (wlan0)\n\
1228              Current Scopes: DNS\n\
1229              DNS Domain: home.local\n\
1230            Link 4 (eth0)\n\
1231              Current Scopes: DNS\n\
1232              DNS Search Domains: corp.example.com internal.net\n";
1233        let result = parse_resolvectl_search(sample);
1234        assert_eq!(
1235            result,
1236            vec!["wlan0: home.local", "eth0: corp.example.com, internal.net"]
1237        );
1238    }
1239
1240    #[test]
1241    fn test_parse_resolvectl_search_skips_routing_domain() {
1242        let sample = "Link 2 (wlan0)\n  DNS Domain: ~.\nLink 3 (eth0)\n  DNS Domain: corp.net\n";
1243        let result = parse_resolvectl_search(sample);
1244        assert_eq!(result, vec!["eth0: corp.net"]);
1245    }
1246
1247    #[test]
1248    fn test_parse_resolvectl_search_empty() {
1249        let sample = "Global\n  DNS Servers: 1.1.1.1\n";
1250        assert!(parse_resolvectl_search(sample).is_empty());
1251    }
1252
1253    // ── domain selection: default route vs. VPN ───────────────────────────────
1254
1255    /// Verbatim `resolvectl status --no-pager` output from the reported machine: a NetBird
1256    /// VPN (`wt0`, split tunnel) alongside the Wi-Fi default route (`wlp194s0`). Note that
1257    /// **both** links report `Default Route: yes` — that is systemd-resolved's DNS-routing
1258    /// flag, not the IP default route — and that `wt0`'s DNS Domain value wraps onto a
1259    /// continuation line.
1260    const RESOLVECTL_VPN_SAMPLE: &str = concat!(
1261        "Global\n",
1262        "         Protocols: LLMNR=resolve -mDNS -DNSOverTLS DNSSEC=no/unsupported\n",
1263        "  resolv.conf mode: stub\n",
1264        "\n",
1265        "Link 2 (wlp194s0)\n",
1266        "    Current Scopes: DNS LLMNR/IPv4 LLMNR/IPv6\n",
1267        "         Protocols: +DefaultRoute LLMNR=resolve -mDNS -DNSOverTLS\n",
1268        "                    DNSSEC=no/unsupported\n",
1269        "Current DNS Server: 192.168.86.1\n",
1270        "       DNS Servers: 192.168.86.1\n",
1271        "        DNS Domain: lan\n",
1272        "     Default Route: yes\n",
1273        "\n",
1274        "Link 3 (wt0)\n",
1275        "    Current Scopes: DNS\n",
1276        "         Protocols: +DefaultRoute LLMNR=resolve -mDNS -DNSOverTLS\n",
1277        "                    DNSSEC=no/unsupported\n",
1278        "Current DNS Server: 100.101.32.155\n",
1279        "       DNS Servers: 100.101.32.155\n",
1280        "        DNS Domain: netbird.cloud ~gammatile.com ~101.100.in-addr.arpa\n",
1281        "                    ~f.f.0.0.3.2.b.5.b.c.8.5.7.f.d.f.ip6.arpa ~.\n",
1282        "     Default Route: yes\n",
1283    );
1284
1285    #[test]
1286    fn test_domain_prefers_default_route_over_vpn() {
1287        // The reported bug: resolv.conf's merged "search netbird.cloud lan" put the VPN
1288        // first, so the Domain field showed netbird.cloud. Keyed on the default-route
1289        // interface, the answer is the Wi-Fi link's own domain.
1290        let parsed = parse_resolvectl_domains(RESOLVECTL_VPN_SAMPLE);
1291        assert_eq!(
1292            resolve_default_route_domain(&parsed, "wlp194s0"),
1293            DefaultRouteDomain::Managed(Some("lan".to_string()))
1294        );
1295    }
1296
1297    #[test]
1298    fn test_domain_reports_vpn_when_vpn_is_the_default_route() {
1299        // Full-tunnel case: if the VPN *is* the default route, its domain is correct.
1300        let parsed = parse_resolvectl_domains(RESOLVECTL_VPN_SAMPLE);
1301        assert_eq!(
1302            resolve_default_route_domain(&parsed, "wt0"),
1303            DefaultRouteDomain::Managed(Some("netbird.cloud".to_string()))
1304        );
1305    }
1306
1307    #[test]
1308    fn test_domain_routing_only_entries_are_not_domains() {
1309        // Every `~`-prefixed entry is routing-only, never a search suffix — so a link whose
1310        // only entries are `~`-prefixed has no domain (and must not yield "~gammatile.com").
1311        let parsed = parse_resolvectl_domains(RESOLVECTL_VPN_SAMPLE);
1312        let wt0 = parsed.links.iter().find(|l| l.interface == "wt0").unwrap();
1313        assert_eq!(wt0.search, vec!["netbird.cloud"]);
1314        assert!(wt0.search.iter().all(|d| !d.starts_with('~')));
1315
1316        let routing_only = "Link 5 (tun0)\n        DNS Domain: ~corp.example.com ~.\n";
1317        let parsed = parse_resolvectl_domains(routing_only);
1318        assert_eq!(
1319            resolve_default_route_domain(&parsed, "tun0"),
1320            DefaultRouteDomain::Managed(None)
1321        );
1322    }
1323
1324    #[test]
1325    fn test_parse_resolvectl_domains_reads_wrapped_continuation_lines() {
1326        // Regression: the old parser read only the first line of a wrapped value, silently
1327        // dropping the rest. Here the continuation carries a real search domain.
1328        let sample = concat!(
1329            "Link 2 (eth0)\n",
1330            "        DNS Domain: one.example.com two.example.com\n",
1331            "                    three.example.com ~routing.example.com\n",
1332            "     Default Route: yes\n",
1333        );
1334        let parsed = parse_resolvectl_domains(sample);
1335        assert_eq!(
1336            parsed.links[0].search,
1337            vec!["one.example.com", "two.example.com", "three.example.com"]
1338        );
1339        // The following `label: value` line must end the value, not join it.
1340        assert!(!parsed.links[0].search.iter().any(|d| d.contains("yes")));
1341    }
1342
1343    #[test]
1344    fn test_parse_resolvectl_domains_ignores_other_wrapped_fields() {
1345        // `Protocols:` also wraps; its continuation must not be mistaken for a domain.
1346        let sample = concat!(
1347            "Link 2 (eth0)\n",
1348            "         Protocols: +DefaultRoute LLMNR=resolve -mDNS -DNSOverTLS\n",
1349            "                    DNSSEC=no/unsupported\n",
1350            "        DNS Domain: real.example.com\n",
1351        );
1352        let parsed = parse_resolvectl_domains(sample);
1353        assert_eq!(parsed.links[0].search, vec!["real.example.com"]);
1354    }
1355
1356    #[test]
1357    fn test_domain_unmanaged_link_falls_back() {
1358        // A default-route interface systemd-resolved knows nothing about: the caller should
1359        // fall back to /etc/resolv.conf rather than borrow another link's domain.
1360        let parsed = parse_resolvectl_domains(RESOLVECTL_VPN_SAMPLE);
1361        assert_eq!(
1362            resolve_default_route_domain(&parsed, "ppp0"),
1363            DefaultRouteDomain::Unmanaged
1364        );
1365    }
1366
1367    #[test]
1368    fn test_domain_managed_without_domain_does_not_borrow_from_other_links() {
1369        // wlp194s0 is managed but has no domain of its own; the VPN's domain must NOT be
1370        // substituted (that is the bug). With no Global domain either, the answer is "none".
1371        let sample = concat!(
1372            "Link 2 (wlp194s0)\n",
1373            "     Default Route: yes\n",
1374            "Link 3 (wt0)\n",
1375            "        DNS Domain: netbird.cloud\n",
1376        );
1377        let parsed = parse_resolvectl_domains(sample);
1378        assert_eq!(
1379            resolve_default_route_domain(&parsed, "wlp194s0"),
1380            DefaultRouteDomain::Managed(None)
1381        );
1382    }
1383
1384    #[test]
1385    fn test_domain_falls_back_to_global_but_not_to_another_link() {
1386        // A Global domain (resolved.conf `Domains=`) belongs to no interface, so it is a
1387        // legitimate answer when the default-route link has none of its own.
1388        let sample = concat!(
1389            "Global\n",
1390            "        DNS Domain: corp.example.com\n",
1391            "Link 2 (wlp194s0)\n",
1392            "     Default Route: yes\n",
1393            "Link 3 (wt0)\n",
1394            "        DNS Domain: netbird.cloud\n",
1395        );
1396        let parsed = parse_resolvectl_domains(sample);
1397        assert_eq!(parsed.global, vec!["corp.example.com"]);
1398        assert_eq!(
1399            resolve_default_route_domain(&parsed, "wlp194s0"),
1400            DefaultRouteDomain::Managed(Some("corp.example.com".to_string()))
1401        );
1402    }
1403
1404    #[test]
1405    fn test_parse_resolvectl_domains_merges_both_domain_labels() {
1406        // A link reporting both labels yields one merged entry, not two.
1407        let sample = concat!(
1408            "Link 2 (eth0)\n",
1409            "        DNS Domain: a.example.com\n",
1410            "DNS Search Domains: b.example.com\n",
1411        );
1412        let parsed = parse_resolvectl_domains(sample);
1413        assert_eq!(parsed.links.len(), 1);
1414        assert_eq!(
1415            parsed.links[0].search,
1416            vec!["a.example.com", "b.example.com"]
1417        );
1418        assert_eq!(
1419            parse_resolvectl_search(sample),
1420            vec!["eth0: a.example.com, b.example.com"]
1421        );
1422    }
1423
1424    // ── Domain Search: one shape regardless of source ─────────────────────────
1425
1426    #[test]
1427    fn test_global_search_domains_match_per_link_shape() {
1428        // The fallback must render like the resolvectl path — "<scope>: a, b" — so the field
1429        // has one shape. Regression for the CI inconsistency where the same OS flipped format
1430        // depending on whether systemd-resolved was reachable (bare runner vs. container).
1431        let per_link = parse_resolvectl_search("Link 2 (eth0)\n  DNS Domain: a.example.com\n");
1432        assert_eq!(per_link, vec!["eth0: a.example.com"]);
1433
1434        let global = format_global_search_domains(&["a.example.com".to_string()]);
1435        assert_eq!(global, vec!["global: a.example.com"]);
1436
1437        // Same structural shape: exactly one entry, "<scope>: <domains>".
1438        assert_eq!(per_link.len(), global.len());
1439        for entry in per_link.iter().chain(global.iter()) {
1440            let (scope, domains) = entry.split_once(": ").expect("entry must carry a scope");
1441            assert!(!scope.is_empty() && !domains.is_empty());
1442        }
1443    }
1444
1445    #[test]
1446    fn test_global_search_domains_group_into_one_entry() {
1447        // The raw resolv.conf parse yields one element per domain, and the display prints one
1448        // line per element — so `search a b c` used to emit three bare `Domain Search:` lines
1449        // while resolvectl emitted one per interface. Now it is a single grouped entry.
1450        let parsed = parse_search_from_resolv_conf("search a.example.com b.example.com c.net\n");
1451        assert_eq!(parsed.len(), 3); // parser stays faithful to the file
1452        assert_eq!(
1453            format_global_search_domains(&parsed),
1454            vec!["global: a.example.com, b.example.com, c.net"]
1455        );
1456    }
1457
1458    #[test]
1459    fn test_global_search_domains_empty_yields_no_line() {
1460        // No search list -> no entry at all, so the field stays hidden (unchanged behaviour).
1461        assert!(format_global_search_domains(&[]).is_empty());
1462        assert!(format_global_search_domains(&parse_search_from_resolv_conf(
1463            "nameserver 1.1.1.1\n"
1464        ))
1465        .is_empty());
1466    }
1467
1468    #[test]
1469    fn test_default_route_interface_selection_matches_routing_table() {
1470        // The routing table is the source of truth for "default route" — not resolvectl's
1471        // per-link `Default Route:` flag, which is `yes` for both links in the VPN sample.
1472        // Real /proc/net/route from the reported machine: only wlp194s0 has dest+mask 0.
1473        let proc_net_route = concat!(
1474            "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n",
1475            "wlp194s0\t00000000\t0156A8C0\t0003\t0\t0\t100\t00000000\t0\t0\t0\n",
1476            "wt0\t00006564\t00000000\t0001\t0\t0\t0\t0000FFFF\t0\t0\t0\n",
1477            "wlp194s0\t0056A8C0\t00000000\t0001\t0\t0\t100\t00FFFFFF\t0\t0\t0\n",
1478        );
1479        assert_eq!(
1480            parse_proc_net_route(proc_net_route),
1481            Some("wlp194s0".to_string())
1482        );
1483    }
1484}