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            std::process::Command::new("powershell")
56                .args(["-Command", "Get-NetRoute -DestinationPrefix 0.0.0.0/0 | Select-Object -First 1 -ExpandProperty InterfaceAlias"])
57                .output()
58                .ok()
59                .and_then(|o| String::from_utf8(o.stdout).ok())
60                .map(|s| s.trim().to_string())
61                .filter(|s| !s.is_empty())
62        }
63        #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
64        {
65            None
66        }
67    };
68
69    (local_ip, active_interface)
70}
71
72/// Fetches the public IP address via an external service (best-effort, 2s timeout).
73pub fn detect_public_ip() -> Option<String> {
74    std::process::Command::new("curl")
75        .args(["-s", "--max-time", "2", "https://api.ipify.org"])
76        .output()
77        .ok()
78        .and_then(|o| String::from_utf8(o.stdout).ok())
79        .map(|s| s.trim().to_string())
80        .filter(|s| !s.is_empty())
81}
82
83/// Builds the formatted list of network interfaces with IP addresses and RX/TX stats.
84pub fn detect_networks(active_interface: Option<&str>, local_ip: Option<&str>) -> Vec<String> {
85    Networks::new_with_refreshed_list()
86        .iter()
87        .map(|(name, data)| {
88            let rx = format_bytes(data.total_received());
89            let tx = format_bytes(data.total_transmitted());
90            let is_up = data.operational_state() == sysinfo::InterfaceOperationalState::Up
91                || data.total_received() > 0
92                || data.total_transmitted() > 0;
93            let status = if is_up {
94                "Up".green().to_string()
95            } else {
96                "Down".red().to_string()
97            };
98
99            let mut ipv4_addresses = Vec::new();
100            let mut ipv6_addresses = Vec::new();
101
102            if is_up {
103                for ip_net in data.ip_networks() {
104                    let ip = ip_net.addr;
105                    let name_lower = name.to_lowercase();
106                    let is_loopback_iface =
107                        name_lower.starts_with("lo") || name_lower.contains("loopback");
108                    if ip.is_loopback() && !is_loopback_iface {
109                        continue;
110                    }
111                    match ip {
112                        std::net::IpAddr::V4(v4) => {
113                            ipv4_addresses.push(v4.to_string());
114                        }
115                        std::net::IpAddr::V6(v6) => {
116                            if !v6.is_unicast_link_local() {
117                                ipv6_addresses.push(v6.to_string());
118                            }
119                        }
120                    }
121                }
122
123                // Fallback to active interface UDP-resolved local IP if no IPs detected by sysinfo
124                if ipv4_addresses.is_empty() && ipv6_addresses.is_empty() {
125                    if let (Some(active), Some(ip)) = (active_interface, local_ip) {
126                        if name == active {
127                            ipv4_addresses.push(ip.to_string());
128                        }
129                    }
130                }
131            }
132
133            let ip_str = if !ipv4_addresses.is_empty() || !ipv6_addresses.is_empty() {
134                let mut combined = Vec::new();
135                if !ipv4_addresses.is_empty() {
136                    combined.push(ipv4_addresses.join(", "));
137                }
138                if !ipv6_addresses.is_empty() {
139                    combined.push(ipv6_addresses.join(", "));
140                }
141                format!(" ({})", combined.join(", "))
142            } else {
143                String::new()
144            };
145
146            format!("{}{} [{}] RX: {} TX: {}", name, ip_str, status, rx, tx)
147        })
148        .collect()
149}
150
151/// Formats a byte count into human-readable form (KB, MB, GB, etc.)
152pub fn format_bytes(bytes: u64) -> String {
153    const KB: u64 = 1024;
154    const MB: u64 = KB * 1024;
155    const GB: u64 = MB * 1024;
156
157    if bytes >= GB {
158        format!("{:.1} GB", bytes as f64 / GB as f64)
159    } else if bytes >= MB {
160        format!("{:.1} MB", bytes as f64 / MB as f64)
161    } else if bytes >= KB {
162        format!("{:.1} KB", bytes as f64 / KB as f64)
163    } else {
164        format!("{} B", bytes)
165    }
166}
167
168/// Looks up a PCI vendor name from `/usr/share/hwdata/pci.ids` (or fallback paths).
169///
170/// `vendor_id` should be a lowercase hex string without the `0x` prefix.
171pub fn lookup_pci_vendor(vendor_id: &str) -> Option<String> {
172    let vendor_id = vendor_id.trim_start_matches("0x").to_lowercase();
173    let paths = ["/usr/share/hwdata/pci.ids", "/usr/share/misc/pci.ids"];
174    for path in &paths {
175        if let Ok(content) = std::fs::read_to_string(path) {
176            for line in content.lines() {
177                if line.starts_with('#') || line.is_empty() {
178                    continue;
179                }
180                if !line.starts_with('\t') {
181                    let parts: Vec<&str> = line.split_whitespace().collect();
182                    if parts.len() >= 2 && parts[0].to_lowercase() == vendor_id {
183                        let name = line.strip_prefix(parts[0]).unwrap().trim();
184                        return Some(name.to_string());
185                    }
186                }
187            }
188        }
189    }
190    None
191}
192
193/// Detects the connected Wi-Fi network and link parameters.
194pub fn detect_wifi() -> Option<String> {
195    #[cfg(target_os = "linux")]
196    {
197        let mut wifi_interface = None;
198        if let Ok(entries) = std::fs::read_dir("/sys/class/net") {
199            for entry in entries.filter_map(|e| e.ok()) {
200                let path = entry.path();
201                if path.join("wireless").exists() || path.join("phy80211").exists() {
202                    wifi_interface = Some(entry.file_name().to_string_lossy().to_string());
203                    break;
204                }
205            }
206        }
207
208        if let Some(ref iface) = wifi_interface {
209            if let Ok(output) = std::process::Command::new("iw")
210                .args(["dev", iface, "link"])
211                .output()
212            {
213                if let Ok(stdout) = String::from_utf8(output.stdout) {
214                    let (ssid, links) = parse_iw_link_output(&stdout);
215                    if let Some(s) = ssid {
216                        let card_model = get_wifi_card_model(iface);
217                        let prefix = if let Some(m) = card_model {
218                            format!("{} [{}] - ", m, iface)
219                        } else {
220                            format!("[{}] - ", iface)
221                        };
222
223                        if !links.is_empty() {
224                            let mut link_strs = Vec::new();
225                            for link in links {
226                                let freq_str = link.freq.map(|f| {
227                                    let ghz_mhz = if f >= 1000.0 {
228                                        format!("{:.1} GHz", f / 1000.0)
229                                    } else {
230                                        format!("{} MHz", f)
231                                    };
232                                    if let Some(ch) = freq_to_channel(f) {
233                                        format!("{} ch{}", ghz_mhz, ch)
234                                    } else {
235                                        ghz_mhz
236                                    }
237                                });
238
239                                let mut rx_tx = Vec::new();
240                                if let Some(rx) = link.rx_rate {
241                                    if rx != "0"
242                                        && !rx.starts_with("0 ")
243                                        && rx != "0 Mbps"
244                                        && rx != "0 MBit/s"
245                                    {
246                                        rx_tx.push(format!("↓{}", clean_rate(&rx)));
247                                    }
248                                }
249                                if let Some(tx) = link.tx_rate {
250                                    if tx != "0"
251                                        && !tx.starts_with("0 ")
252                                        && tx != "0 Mbps"
253                                        && tx != "0 MBit/s"
254                                    {
255                                        rx_tx.push(format!("↑{}", clean_rate(&tx)));
256                                    }
257                                }
258
259                                match (freq_str, rx_tx.is_empty()) {
260                                    (Some(f), false) => {
261                                        link_strs.push(format!("{} [{}]", f, rx_tx.join(" ")))
262                                    }
263                                    (Some(f), true) => link_strs.push(f),
264                                    (None, false) => link_strs.push(rx_tx.join(" ")),
265                                    _ => {}
266                                }
267                            }
268                            if !link_strs.is_empty() {
269                                return Some(format!(
270                                    "{}{}{} ({})",
271                                    prefix,
272                                    s,
273                                    "",
274                                    link_strs.join(", ")
275                                ));
276                            } else {
277                                return Some(format!("{}{}", prefix, s));
278                            }
279                        }
280                        return Some(format!("{}{}", prefix, s));
281                    }
282                }
283            }
284        }
285
286        // Fallback to nmcli
287        if let Ok(output) = std::process::Command::new("nmcli")
288            .args(["-t", "-f", "active,ssid,rate", "dev", "wifi"])
289            .output()
290        {
291            if let Ok(stdout) = String::from_utf8(output.stdout) {
292                for line in stdout.lines() {
293                    let line = line.trim();
294                    if let Some(rest) = line.strip_prefix("yes:") {
295                        if let Some(colon_idx) = rest.rfind(':') {
296                            let ssid = &rest[..colon_idx];
297                            let rate = rest[colon_idx + 1..].trim();
298                            if !ssid.is_empty() {
299                                if !rate.is_empty()
300                                    && rate != "0"
301                                    && !rate.starts_with("0 ")
302                                    && rate != "0 Mbit/s"
303                                    && rate != "0 Mbps"
304                                {
305                                    return Some(format!("{} ({})", ssid, clean_rate(rate)));
306                                } else {
307                                    return Some(ssid.to_string());
308                                }
309                            }
310                        } else if !rest.is_empty() {
311                            return Some(rest.to_string());
312                        }
313                    }
314                }
315            }
316        }
317
318        // Fallback to iwgetid
319        if let Ok(output) = std::process::Command::new("iwgetid").arg("-r").output() {
320            if let Ok(stdout) = String::from_utf8(output.stdout) {
321                let ssid = stdout.trim();
322                if !ssid.is_empty() {
323                    return Some(ssid.to_string());
324                }
325            }
326        }
327        None
328    }
329
330    #[cfg(target_os = "macos")]
331    {
332        crate::macos_ffi::get_wifi_info().map(|(ssid, rate)| match rate {
333            Some(r) if r > 0 => format!("{} (↑{} Mbps)", ssid, r),
334            _ => ssid,
335        })
336    }
337
338    #[cfg(target_os = "windows")]
339    {
340        if let Ok(output) = std::process::Command::new("netsh")
341            .args(["wlan", "show", "interfaces"])
342            .output()
343        {
344            if let Ok(stdout) = String::from_utf8(output.stdout) {
345                return parse_netsh_output(&stdout);
346            }
347        }
348        None
349    }
350
351    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
352    {
353        None
354    }
355}
356
357#[cfg(any(target_os = "linux", test))]
358pub fn parse_proc_net_route(content: &str) -> Option<String> {
359    for line in content.lines().skip(1) {
360        let parts: Vec<&str> = line.split_whitespace().collect();
361        if parts.len() >= 8 {
362            let dest = parts[1];
363            let mask = parts[7];
364            if dest == "00000000" && mask == "00000000" {
365                return Some(parts[0].to_string());
366            }
367        }
368    }
369    None
370}
371
372#[allow(
373    clippy::manual_is_multiple_of,
374    clippy::manual_range_contains,
375    dead_code
376)]
377fn freq_to_channel(freq_mhz: f64) -> Option<u32> {
378    let freq = freq_mhz.round() as u32;
379    if freq >= 2412 && freq <= 2472 {
380        Some((freq - 2407) / 5)
381    } else if freq == 2484 {
382        Some(14)
383    } else if freq >= 5160 && freq <= 5885 {
384        if (freq - 5000) % 5 == 0 {
385            Some((freq - 5000) / 5)
386        } else {
387            None
388        }
389    } else if freq >= 5955 && freq <= 7115 {
390        if (freq - 5950) % 5 == 0 {
391            Some((freq - 5950) / 5)
392        } else {
393            None
394        }
395    } else {
396        None
397    }
398}
399
400#[allow(dead_code)]
401fn get_wifi_card_model(iface: &str) -> Option<String> {
402    let vendor = std::fs::read_to_string(format!("/sys/class/net/{}/device/vendor", iface)).ok()?;
403    let device = std::fs::read_to_string(format!("/sys/class/net/{}/device/device", iface)).ok()?;
404    let vendor_clean = vendor.trim().trim_start_matches("0x").to_lowercase();
405    let device_clean = device.trim().trim_start_matches("0x").to_lowercase();
406
407    let vendor_name = lookup_pci_vendor(&vendor_clean);
408    let model_name = crate::gpu::lookup_pci_device(&vendor_clean, &device_clean);
409
410    match (vendor_name, model_name) {
411        (Some(v), Some(m)) => {
412            let v_clean = v.replace(", Inc.", "").replace(" Corporation", "");
413            if m.to_lowercase().contains(&v_clean.to_lowercase())
414                || m.to_lowercase().contains(
415                    &v_clean
416                        .split_whitespace()
417                        .next()
418                        .unwrap_or("")
419                        .to_lowercase(),
420                )
421            {
422                Some(m)
423            } else {
424                Some(format!("{} {}", v_clean, m))
425            }
426        }
427        (None, Some(m)) => Some(m),
428        _ => None,
429    }
430}
431
432#[allow(dead_code)]
433fn clean_rate(rate: &str) -> String {
434    rate.replace("MBit/s", "Mbps")
435        .replace("GBit/s", "Gbps")
436        .replace("Bit/s", "bps")
437}
438
439#[derive(Debug, Clone)]
440pub struct WifiLink {
441    pub freq: Option<f64>,
442    pub rx_rate: Option<String>,
443    pub tx_rate: Option<String>,
444}
445
446#[allow(dead_code)]
447pub fn parse_iw_link_output(stdout: &str) -> (Option<String>, Vec<WifiLink>) {
448    let mut ssid = None;
449    let mut links = Vec::new();
450    let mut current_link = None;
451
452    for line in stdout.lines() {
453        let trimmed = line.trim();
454        if trimmed.starts_with("Connected to") || trimmed.starts_with("link") {
455            if let Some(link) = current_link.take() {
456                links.push(link);
457            }
458            current_link = Some(WifiLink {
459                freq: None,
460                rx_rate: None,
461                tx_rate: None,
462            });
463        } else if trimmed.starts_with("SSID:") {
464            ssid = Some(trimmed.strip_prefix("SSID:").unwrap().trim().to_string());
465        } else if trimmed.starts_with("freq:") {
466            if let Some(ref mut link) = current_link {
467                let freq_str = trimmed.strip_prefix("freq:").unwrap().trim();
468                link.freq = freq_str.parse::<f64>().ok();
469            }
470        } else if trimmed.starts_with("rx bitrate:") {
471            if let Some(ref mut link) = current_link {
472                let rx_str = trimmed.strip_prefix("rx bitrate:").unwrap().trim();
473                let rate = rx_str
474                    .split_whitespace()
475                    .take(2)
476                    .collect::<Vec<&str>>()
477                    .join(" ");
478                link.rx_rate = Some(rate);
479            }
480        } else if trimmed.starts_with("tx bitrate:") {
481            if let Some(ref mut link) = current_link {
482                let tx_str = trimmed.strip_prefix("tx bitrate:").unwrap().trim();
483                let rate = tx_str
484                    .split_whitespace()
485                    .take(2)
486                    .collect::<Vec<&str>>()
487                    .join(" ");
488                link.tx_rate = Some(rate);
489            }
490        }
491    }
492    if let Some(link) = current_link {
493        links.push(link);
494    }
495    (ssid, links)
496}
497
498#[allow(dead_code)]
499pub fn parse_netsh_output(stdout: &str) -> Option<String> {
500    let mut ssid = None;
501    let mut rx = None;
502    let mut tx = None;
503    let mut band = None;
504    for line in stdout.lines() {
505        let trimmed = line.trim();
506        if trimmed.starts_with("SSID") {
507            if let Some(idx) = trimmed.find(':') {
508                let val = trimmed[idx + 1..].trim().to_string();
509                if !val.is_empty() {
510                    ssid = Some(val);
511                }
512            }
513        } else if trimmed.starts_with("Receive rate (Mbps)") {
514            if let Some(idx) = trimmed.find(':') {
515                let val = trimmed[idx + 1..].trim().to_string();
516                if !val.is_empty() {
517                    rx = Some(val);
518                }
519            }
520        } else if trimmed.starts_with("Transmit rate (Mbps)") {
521            if let Some(idx) = trimmed.find(':') {
522                let val = trimmed[idx + 1..].trim().to_string();
523                if !val.is_empty() {
524                    tx = Some(val);
525                }
526            }
527        } else if trimmed.starts_with("Band") {
528            if let Some(idx) = trimmed.find(':') {
529                let val = trimmed[idx + 1..].trim().to_string();
530                if !val.is_empty() {
531                    band = Some(val);
532                }
533            }
534        }
535    }
536    if let Some(s) = ssid {
537        let mut rate_strs = Vec::new();
538        if let Some(rx_val) = rx {
539            if rx_val != "0" {
540                rate_strs.push(format!("↓{} Mbps", rx_val));
541            }
542        }
543        if let Some(tx_val) = tx {
544            if tx_val != "0" {
545                rate_strs.push(format!("↑{} Mbps", tx_val));
546            }
547        }
548        let info = match (band, rate_strs.is_empty()) {
549            (Some(b), false) => format!("{} [{}]", b, rate_strs.join(" ")),
550            (Some(b), true) => b,
551            (None, false) => rate_strs.join(" "),
552            _ => String::new(),
553        };
554        if !info.is_empty() {
555            Some(format!("{} ({})", s, info))
556        } else {
557            Some(s)
558        }
559    } else {
560        None
561    }
562}
563
564#[cfg(test)]
565mod tests {
566    use super::*;
567
568    #[test]
569    fn test_format_bytes() {
570        assert_eq!(format_bytes(500), "500 B");
571        assert_eq!(format_bytes(1024), "1.0 KB");
572        assert_eq!(format_bytes(1024 * 1024), "1.0 MB");
573        assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB");
574        assert_eq!(format_bytes(1536), "1.5 KB");
575    }
576
577    #[test]
578    fn test_parse_proc_net_route() {
579        let sample =
580            "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\
581                      wlan0\t0000A8C0\t00000000\t0001\t0\t0\t600\t0000FFFF\t0\t0\t0\n\
582                      wlan0\t00000000\t0100A8C0\t0003\t0\t0\t600\t00000000\t0\t0\t0\n";
583        assert_eq!(parse_proc_net_route(sample), Some("wlan0".to_string()));
584
585        let sample_no_default =
586            "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\
587                                 wlan0\t0000A8C0\t00000000\t0001\t0\t0\t600\t0000FFFF\t0\t0\t0\n";
588        assert_eq!(parse_proc_net_route(sample_no_default), None);
589    }
590
591    #[test]
592    fn test_parse_netsh_output() {
593        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";
594        assert_eq!(
595            parse_netsh_output(sample),
596            Some("Office_Wi-Fi (5 GHz [↓433 Mbps ↑866 Mbps])".to_string())
597        );
598    }
599
600    #[test]
601    fn test_parse_iw_link_output() {
602        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";
603        let (ssid, links) = parse_iw_link_output(sample);
604        assert_eq!(ssid, Some("OfficeNet".to_string()));
605        assert_eq!(links.len(), 1);
606        assert_eq!(links[0].freq, Some(6135.0));
607        assert_eq!(links[0].rx_rate, Some("6.0 MBit/s".to_string()));
608        assert_eq!(links[0].tx_rate, Some("864.6 MBit/s".to_string()));
609
610        // MLO multi-link mock output
611        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";
612        let (ssid_mlo, links_mlo) = parse_iw_link_output(sample_mlo);
613        assert_eq!(ssid_mlo, Some("HomeWiFi".to_string()));
614        assert_eq!(links_mlo.len(), 2);
615        assert_eq!(links_mlo[0].freq, Some(5180.0));
616        assert_eq!(links_mlo[1].freq, Some(6135.0));
617    }
618}