|
| 1 | +//! `net_vpn` — host VPN connection state. |
| 2 | +//! |
| 3 | +//! An interface is treated as a VPN tunnel when its `netdev` type is `Tunnel` / `Ppp`, or its |
| 4 | +//! name starts with one of the common VPN-driver prefixes (`tun` / `utun` / `wg` / `ipsec` / …). |
| 5 | +//! Name-prefix detection is the load-bearing path on Linux because WireGuard and OpenVPN-tun |
| 6 | +//! devices report as `Ether`, not `Tunnel`, in `/sys/class/net` and would otherwise slip past |
| 7 | +//! the `if_type` check. |
| 8 | +
|
| 9 | +use async_trait::async_trait; |
| 10 | + |
| 11 | +use crate::payload::{ |
| 12 | + BadgeData, Body, EntriesData, Entry, MarkdownTextBlockData, Payload, Status, TextBlockData, |
| 13 | + TextData, |
| 14 | +}; |
| 15 | +use crate::render::Shape; |
| 16 | + |
| 17 | +use super::super::{FetchContext, FetchError, Fetcher, Safety}; |
| 18 | +use super::{NetIface, payload, snapshot}; |
| 19 | + |
| 20 | +const SHAPES: &[Shape] = &[ |
| 21 | + Shape::Badge, |
| 22 | + Shape::Text, |
| 23 | + Shape::TextBlock, |
| 24 | + Shape::MarkdownTextBlock, |
| 25 | + Shape::Entries, |
| 26 | +]; |
| 27 | + |
| 28 | +/// Interface-name prefixes that identify a VPN tunnel even when `netdev` doesn't classify the |
| 29 | +/// `if_type` as `Tunnel`. Covers the userspace tun drivers (`tun*` / `utun*`) plus the kernel |
| 30 | +/// modules from the major commercial / FOSS VPN stacks. |
| 31 | +const VPN_NAME_PREFIXES: &[&str] = &[ |
| 32 | + "tun", "utun", "wg", "ipsec", "nordlynx", "proton", "tap", "gpd", "cscotun", |
| 33 | +]; |
| 34 | + |
| 35 | +pub struct NetVpn; |
| 36 | + |
| 37 | +#[async_trait] |
| 38 | +impl Fetcher for NetVpn { |
| 39 | + fn name(&self) -> &str { |
| 40 | + "net_vpn" |
| 41 | + } |
| 42 | + fn safety(&self) -> Safety { |
| 43 | + Safety::Safe |
| 44 | + } |
| 45 | + fn description(&self) -> &'static str { |
| 46 | + "Whether this host is currently routing through a VPN tunnel. `Badge` (default) is a \ |
| 47 | + connected / disconnected pill — `disconnected` is `Warn`, since the widget exists \ |
| 48 | + because the user wants to know when the tunnel is *down*. `Text` names the active VPN \ |
| 49 | + interface and its address; `TextBlock` / `MarkdownTextBlock` / `Entries` list every \ |
| 50 | + active tunnel. Detects `netdev` `Tunnel` / `Ppp` types plus name-prefix fallback for \ |
| 51 | + WireGuard, OpenVPN-tun, IPsec, NordLynx, ProtonVPN, Cisco AnyConnect, and GlobalProtect." |
| 52 | + } |
| 53 | + fn refresh_interval(&self) -> u64 { |
| 54 | + 60 |
| 55 | + } |
| 56 | + fn shapes(&self) -> &[Shape] { |
| 57 | + SHAPES |
| 58 | + } |
| 59 | + fn sample_body(&self, shape: Shape) -> Option<Body> { |
| 60 | + body_for_shape(&sample_snapshot(), shape) |
| 61 | + } |
| 62 | + async fn fetch(&self, ctx: &FetchContext) -> Result<Payload, FetchError> { |
| 63 | + let ifaces = snapshot(); |
| 64 | + let shape = ctx.shape.unwrap_or(Shape::Badge); |
| 65 | + Ok(payload( |
| 66 | + body_for_shape(&ifaces, shape).unwrap_or_else(|| Body::Badge(vpn_badge(&[]))), |
| 67 | + )) |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +fn body_for_shape(ifaces: &[NetIface], shape: Shape) -> Option<Body> { |
| 72 | + let vpns = active_vpns(ifaces); |
| 73 | + Some(match shape { |
| 74 | + Shape::Badge => Body::Badge(vpn_badge(&vpns)), |
| 75 | + Shape::Text => Body::Text(TextData { |
| 76 | + value: headline(&vpns), |
| 77 | + }), |
| 78 | + Shape::TextBlock => Body::TextBlock(TextBlockData { |
| 79 | + lines: vpns.iter().map(|i| row_line(i)).collect(), |
| 80 | + }), |
| 81 | + Shape::MarkdownTextBlock => Body::MarkdownTextBlock(MarkdownTextBlockData { |
| 82 | + value: vpns |
| 83 | + .iter() |
| 84 | + .map(|i| format!("- **{}** {}", i.name, addr_summary(i))) |
| 85 | + .collect::<Vec<_>>() |
| 86 | + .join("\n"), |
| 87 | + }), |
| 88 | + Shape::Entries => Body::Entries(EntriesData { |
| 89 | + items: vpns |
| 90 | + .iter() |
| 91 | + .map(|i| Entry { |
| 92 | + key: i.name.clone(), |
| 93 | + value: Some(addr_summary(i)), |
| 94 | + status: Some(Status::Ok), |
| 95 | + }) |
| 96 | + .collect(), |
| 97 | + }), |
| 98 | + _ => return None, |
| 99 | + }) |
| 100 | +} |
| 101 | + |
| 102 | +fn active_vpns(ifaces: &[NetIface]) -> Vec<&NetIface> { |
| 103 | + ifaces |
| 104 | + .iter() |
| 105 | + .filter(|i| is_vpn(i) && i.up && (!i.ipv4.is_empty() || !i.ipv6.is_empty())) |
| 106 | + .collect() |
| 107 | +} |
| 108 | + |
| 109 | +fn is_vpn(i: &NetIface) -> bool { |
| 110 | + if i.loopback { |
| 111 | + return false; |
| 112 | + } |
| 113 | + if i.kind == "Tunnel" || i.kind == "Ppp" { |
| 114 | + return true; |
| 115 | + } |
| 116 | + VPN_NAME_PREFIXES.iter().any(|p| i.name.starts_with(p)) |
| 117 | +} |
| 118 | + |
| 119 | +fn headline(vpns: &[&NetIface]) -> String { |
| 120 | + match vpns.first() { |
| 121 | + None => "VPN: off".into(), |
| 122 | + Some(i) => format!("VPN: {} · {}", i.name, addr_summary(i)), |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +fn row_line(i: &NetIface) -> String { |
| 127 | + format!("{} {}", i.name, addr_summary(i)) |
| 128 | +} |
| 129 | + |
| 130 | +fn addr_summary(i: &NetIface) -> String { |
| 131 | + [ |
| 132 | + i.ipv4.first().map(ToString::to_string), |
| 133 | + i.ipv6.first().map(ToString::to_string), |
| 134 | + ] |
| 135 | + .into_iter() |
| 136 | + .flatten() |
| 137 | + .collect::<Vec<_>>() |
| 138 | + .join(" · ") |
| 139 | +} |
| 140 | + |
| 141 | +/// `disconnected` is `Warn`, not `Ok`: a user who configured this widget cares about the tunnel |
| 142 | +/// being up, so the absence is the noteworthy state worth a glance flag (mirrors `net_proxy`'s |
| 143 | +/// "proxied is the surprise" stance, with the direction flipped). |
| 144 | +fn vpn_badge(vpns: &[&NetIface]) -> BadgeData { |
| 145 | + if vpns.is_empty() { |
| 146 | + BadgeData { |
| 147 | + status: Status::Warn, |
| 148 | + label: "disconnected".into(), |
| 149 | + } |
| 150 | + } else if vpns.len() == 1 { |
| 151 | + BadgeData { |
| 152 | + status: Status::Ok, |
| 153 | + label: format!("connected · {}", vpns[0].name), |
| 154 | + } |
| 155 | + } else { |
| 156 | + BadgeData { |
| 157 | + status: Status::Ok, |
| 158 | + label: format!("connected · {} tunnels", vpns.len()), |
| 159 | + } |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +fn sample_snapshot() -> Vec<NetIface> { |
| 164 | + vec![ |
| 165 | + NetIface { |
| 166 | + name: "lo".into(), |
| 167 | + kind: "Loopback".into(), |
| 168 | + mac: None, |
| 169 | + ipv4: vec![std::net::Ipv4Addr::LOCALHOST], |
| 170 | + ipv6: vec![], |
| 171 | + up: true, |
| 172 | + loopback: true, |
| 173 | + is_default: false, |
| 174 | + mtu: Some(65536), |
| 175 | + rx_bytes: 0, |
| 176 | + tx_bytes: 0, |
| 177 | + }, |
| 178 | + NetIface { |
| 179 | + name: "eth0".into(), |
| 180 | + kind: "Ethernet".into(), |
| 181 | + mac: Some("aa:bb:cc:dd:ee:ff".into()), |
| 182 | + ipv4: vec![std::net::Ipv4Addr::new(192, 168, 1, 24)], |
| 183 | + ipv6: vec![], |
| 184 | + up: true, |
| 185 | + loopback: false, |
| 186 | + is_default: true, |
| 187 | + mtu: Some(1500), |
| 188 | + rx_bytes: 0, |
| 189 | + tx_bytes: 0, |
| 190 | + }, |
| 191 | + NetIface { |
| 192 | + name: "tun0".into(), |
| 193 | + kind: "Tunnel".into(), |
| 194 | + mac: None, |
| 195 | + ipv4: vec![std::net::Ipv4Addr::new(10, 8, 0, 5)], |
| 196 | + ipv6: vec![], |
| 197 | + up: true, |
| 198 | + loopback: false, |
| 199 | + is_default: false, |
| 200 | + mtu: Some(1380), |
| 201 | + rx_bytes: 0, |
| 202 | + tx_bytes: 0, |
| 203 | + }, |
| 204 | + ] |
| 205 | +} |
| 206 | + |
| 207 | +#[cfg(test)] |
| 208 | +mod tests { |
| 209 | + use super::super::tests::iface; |
| 210 | + use super::*; |
| 211 | + |
| 212 | + fn vpn_iface(name: &str, kind: &str, ipv4: &[&str]) -> NetIface { |
| 213 | + let mut i = iface(name, ipv4, true); |
| 214 | + i.kind = kind.into(); |
| 215 | + i.loopback = false; |
| 216 | + i |
| 217 | + } |
| 218 | + |
| 219 | + #[test] |
| 220 | + fn body_for_shape_covers_every_supported_shape() { |
| 221 | + let snap = sample_snapshot(); |
| 222 | + for &shape in SHAPES { |
| 223 | + let body = body_for_shape(&snap, shape).unwrap(); |
| 224 | + assert_eq!(crate::render::shape_of(&body), shape); |
| 225 | + } |
| 226 | + assert!(body_for_shape(&snap, Shape::Ratio).is_none()); |
| 227 | + assert!(body_for_shape(&snap, Shape::Bars).is_none()); |
| 228 | + assert!(body_for_shape(&snap, Shape::Timeline).is_none()); |
| 229 | + } |
| 230 | + |
| 231 | + #[test] |
| 232 | + fn is_vpn_recognises_kind_and_name_prefixes() { |
| 233 | + assert!(is_vpn(&vpn_iface("tun0", "Ethernet", &["10.0.0.1"]))); |
| 234 | + assert!(is_vpn(&vpn_iface("utun3", "Ethernet", &["10.0.0.1"]))); |
| 235 | + assert!(is_vpn(&vpn_iface("wg0", "Ethernet", &["10.0.0.1"]))); |
| 236 | + assert!(is_vpn(&vpn_iface("ipsec0", "Ethernet", &["10.0.0.1"]))); |
| 237 | + assert!(is_vpn(&vpn_iface("nordlynx", "Ethernet", &["10.0.0.1"]))); |
| 238 | + assert!(is_vpn(&vpn_iface("anything", "Tunnel", &["10.0.0.1"]))); |
| 239 | + assert!(is_vpn(&vpn_iface("anything", "Ppp", &["10.0.0.1"]))); |
| 240 | + |
| 241 | + assert!(!is_vpn(&vpn_iface("eth0", "Ethernet", &["10.0.0.1"]))); |
| 242 | + assert!(!is_vpn(&vpn_iface( |
| 243 | + "wlan0", |
| 244 | + "Wireless IEEE 802.11", |
| 245 | + &["10.0.0.1"] |
| 246 | + ))); |
| 247 | + let lo = iface("lo", &["127.0.0.1"], true); |
| 248 | + assert!(!is_vpn(&lo)); |
| 249 | + } |
| 250 | + |
| 251 | + #[test] |
| 252 | + fn active_vpns_requires_up_and_addressed() { |
| 253 | + let down_vpn = { |
| 254 | + let mut i = vpn_iface("tun0", "Tunnel", &["10.8.0.5"]); |
| 255 | + i.up = false; |
| 256 | + i |
| 257 | + }; |
| 258 | + let no_addr_vpn = vpn_iface("wg0", "Ethernet", &[]); |
| 259 | + let live = vpn_iface("utun1", "Ethernet", &["10.99.0.2"]); |
| 260 | + let snap = vec![down_vpn, no_addr_vpn, live]; |
| 261 | + let vpns = active_vpns(&snap); |
| 262 | + assert_eq!(vpns.len(), 1); |
| 263 | + assert_eq!(vpns[0].name, "utun1"); |
| 264 | + } |
| 265 | + |
| 266 | + #[test] |
| 267 | + fn badge_distinguishes_disconnected_single_and_multi() { |
| 268 | + let none: Vec<&NetIface> = vec![]; |
| 269 | + let b0 = vpn_badge(&none); |
| 270 | + assert_eq!(b0.status, Status::Warn); |
| 271 | + assert_eq!(b0.label, "disconnected"); |
| 272 | + |
| 273 | + let one = vpn_iface("tun0", "Tunnel", &["10.0.0.1"]); |
| 274 | + let b1 = vpn_badge(&[&one]); |
| 275 | + assert_eq!(b1.status, Status::Ok); |
| 276 | + assert!(b1.label.contains("tun0")); |
| 277 | + |
| 278 | + let a = vpn_iface("tun0", "Tunnel", &["10.0.0.1"]); |
| 279 | + let b = vpn_iface("wg0", "Ethernet", &["10.99.0.2"]); |
| 280 | + let b2 = vpn_badge(&[&a, &b]); |
| 281 | + assert!(b2.label.contains("2 tunnels")); |
| 282 | + } |
| 283 | + |
| 284 | + #[test] |
| 285 | + fn headline_names_first_active_tunnel_then_falls_back_to_off() { |
| 286 | + let snap = sample_snapshot(); |
| 287 | + let vpns = active_vpns(&snap); |
| 288 | + let h = headline(&vpns); |
| 289 | + assert!(h.starts_with("VPN: tun0")); |
| 290 | + assert!(h.contains("10.8.0.5")); |
| 291 | + |
| 292 | + let nothing = vec![iface("eth0", &["10.0.0.1"], true)]; |
| 293 | + let vpns_none = active_vpns(¬hing); |
| 294 | + assert_eq!(headline(&vpns_none), "VPN: off"); |
| 295 | + } |
| 296 | + |
| 297 | + #[test] |
| 298 | + fn entries_carry_status_ok_for_every_active_tunnel() { |
| 299 | + let snap = vec![ |
| 300 | + vpn_iface("tun0", "Tunnel", &["10.8.0.5"]), |
| 301 | + vpn_iface("wg0", "Ethernet", &["10.99.0.2"]), |
| 302 | + ]; |
| 303 | + let Body::Entries(e) = body_for_shape(&snap, Shape::Entries).unwrap() else { |
| 304 | + panic!("expected entries"); |
| 305 | + }; |
| 306 | + assert_eq!(e.items.len(), 2); |
| 307 | + assert!(e.items.iter().all(|i| i.status == Some(Status::Ok))); |
| 308 | + } |
| 309 | + |
| 310 | + #[test] |
| 311 | + fn addr_summary_joins_v4_and_v6_when_both_present() { |
| 312 | + let mut i = vpn_iface("tun0", "Tunnel", &["10.0.0.1"]); |
| 313 | + i.ipv6 = vec!["fd00::1".parse().unwrap()]; |
| 314 | + let s = addr_summary(&i); |
| 315 | + assert!(s.contains("10.0.0.1")); |
| 316 | + assert!(s.contains("fd00::1")); |
| 317 | + } |
| 318 | + |
| 319 | + #[tokio::test] |
| 320 | + async fn fetch_emits_the_requested_shape() { |
| 321 | + for &shape in SHAPES { |
| 322 | + let ctx = FetchContext { |
| 323 | + shape: Some(shape), |
| 324 | + ..Default::default() |
| 325 | + }; |
| 326 | + let body = NetVpn.fetch(&ctx).await.unwrap().body; |
| 327 | + // On a CI host with no VPN, every shape still resolves — just empty multi-row shapes. |
| 328 | + assert_eq!(crate::render::shape_of(&body), shape); |
| 329 | + } |
| 330 | + } |
| 331 | + |
| 332 | + #[test] |
| 333 | + fn fetcher_contract_metadata() { |
| 334 | + assert_eq!(NetVpn.name(), "net_vpn"); |
| 335 | + assert_eq!(NetVpn.safety(), Safety::Safe); |
| 336 | + assert_eq!(NetVpn.default_shape(), Shape::Badge); |
| 337 | + assert!(NetVpn.option_schemas().is_empty()); |
| 338 | + let description = NetVpn.description(); |
| 339 | + assert!(description.contains("Badge"), "{description}"); |
| 340 | + assert!(description.contains("VPN"), "{description}"); |
| 341 | + for &shape in SHAPES { |
| 342 | + assert!(NetVpn.sample_body(shape).is_some()); |
| 343 | + } |
| 344 | + assert!(NetVpn.sample_body(Shape::Ratio).is_none()); |
| 345 | + } |
| 346 | +} |
0 commit comments