Skip to main content

crabshell_services/
network.rs

1//! Network devices, Wi-Fi networks and saved connections from
2//! NetworkManager, on the system bus.
3
4mod saved;
5#[cfg(test)]
6mod tests;
7mod write;
8
9use std::cell::{Cell, RefCell};
10use std::cmp::Ordering;
11use std::collections::btree_map::Entry;
12use std::collections::{BTreeMap, HashMap};
13use std::panic::Location;
14use std::rc::Rc;
15use std::sync::Once;
16use std::time::{Duration, Instant};
17
18use calloop::RegistrationToken;
19use calloop::timer::TimeoutAction;
20use crabshell_reactive::{Owner, ReadSignal, Signal};
21use crabshell_ui::Cx;
22use serde_json::Value as Json;
23use zbus::{Array, Connection, Message, ObjectPath, OwnedObjectPath, Variant};
24
25pub use saved::SavedConnection;
26use saved::{SAVED, SETTINGS, SETTINGS_PATH, SavedConnections};
27
28use crate::Shared;
29use crate::dbus::{self, CALL_TIMEOUT, Daemon, OBJECT_MANAGER, PROPERTIES, Props, set_changed};
30
31const NM: &str = "org.freedesktop.NetworkManager";
32const NM_PATH: &str = "/org/freedesktop/NetworkManager";
33/// Where NetworkManager's object manager is.
34const ROOT: &str = "/org/freedesktop";
35const DEVICE: &str = "org.freedesktop.NetworkManager.Device";
36const WIRELESS: &str = "org.freedesktop.NetworkManager.Device.Wireless";
37const WIRED: &str = "org.freedesktop.NetworkManager.Device.Wired";
38const ACCESS_POINT: &str = "org.freedesktop.NetworkManager.AccessPoint";
39const ACTIVE: &str = "org.freedesktop.NetworkManager.Connection.Active";
40const IP4: &str = "org.freedesktop.NetworkManager.IP4Config";
41
42/// The most devices kept, and the most active connections, about one a
43/// device. A host running containers has a virtual device for each.
44const MAX_DEVICES: usize = 64;
45/// The most access points kept: a scan in a city finds hundreds.
46const MAX_ACCESS_POINTS: usize = 512;
47/// The longest SSID 802.11 allows, in bytes.
48const MAX_SSID: usize = 32;
49
50/// NetworkManager's `DeviceType` for loopback, left out of the list.
51const LOOPBACK: u32 = 32;
52/// NetworkManager's `State` for a device it doesn't manage, left out.
53const UNMANAGED: u32 = 10;
54/// NetworkManager's `State` for a device that can't connect, as Wi-Fi
55/// that is off, which isn't asked to scan.
56const UNAVAILABLE: u32 = 20;
57const ACTIVATED: u32 = 100;
58const FAILED: u32 = 120;
59/// The `InterfaceFlags` bit for a link, from NetworkManager 1.22, which
60/// takes over from `Device.Wired.Carrier`.
61const CARRIER: u32 = 0x10000;
62/// The `Flags` bit for an access point that asks for a key, as WEP does.
63const PRIVACY: u32 = 0x1;
64/// The key managements in an access point's `WpaFlags` and `RsnFlags`,
65/// from NetworkManager's `NM80211ApSecurityFlags`.
66const KEY_MGMT_PSK: u32 = 0x100;
67const KEY_MGMT_802_1X: u32 = 0x200;
68const KEY_MGMT_SAE: u32 = 0x400;
69/// Enhanced Open, and its transition mode.
70const KEY_MGMT_OWE: u32 = 0x800 | 0x1000;
71const KEY_MGMT_SUITE_B_192: u32 = 0x2000;
72/// The most objects kept, so a flood can't take the memory.
73const MAX_OBJECTS: usize = 4096;
74/// How often a scanner asks for a scan, about as often as NetworkManager
75/// allows one.
76const SCAN_PERIOD: Duration = Duration::from_secs(10);
77
78#[cfg(test)]
79thread_local! {
80  /// A test's own period, so it needn't wait 10 s for each scan.
81  static TEST_SCAN_PERIOD: Cell<Duration> = const { Cell::new(SCAN_PERIOD) };
82}
83
84#[cfg(not(test))]
85fn scan_period() -> Duration {
86  SCAN_PERIOD
87}
88
89#[cfg(test)]
90fn scan_period() -> Duration {
91  TEST_SCAN_PERIOD.with(Cell::get)
92}
93/// The error NetworkManager answers a scan with right after another, or
94/// while the device connects.
95const NOT_ALLOWED: &str = "org.freedesktop.NetworkManager.Device.NotAllowed";
96
97/// What a network device is, from NetworkManager's `DeviceType`.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum NetworkKind {
100  /// A cable.
101  Ethernet,
102  /// Wi-Fi.
103  Wifi,
104  /// Anything else, such as a bridge or a VPN's tunnel.
105  Other,
106}
107
108/// How a network device is doing, from NetworkManager's `State`.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum NetworkState {
111  /// Connected.
112  Connected,
113  /// On its way to connected: from preparing to waiting on secondary
114  /// connections.
115  Connecting,
116  /// Going down, as when told to disconnect or before connecting
117  /// elsewhere.
118  Disconnecting,
119  /// Ready but not connected, or failed to connect.
120  Disconnected,
121  /// Not ready, as with Wi-Fi off or no cable in, or a state not known.
122  Unavailable,
123}
124
125/// How far the host reaches, from NetworkManager's `Connectivity`.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub enum Connectivity {
128  /// Not known: NetworkManager isn't running, its checks are off, or
129  /// they haven't run yet.
130  Unknown,
131  /// On no network at all.
132  None,
133  /// Behind a captive portal, which wants a sign-in in a browser first.
134  Portal,
135  /// On a network, but not reaching the internet.
136  Limited,
137  /// Reaching the internet.
138  Full,
139}
140
141/// Why a device's last try to connect failed, from the reason
142/// NetworkManager gave with its `Failed` state.
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub enum ConnectionFailReason {
145  /// It needed secrets, such as a Wi-Fi password, and got none.
146  NoSecrets,
147  /// The Wi-Fi supplicant failed, or its settings did.
148  WifiClientFailed,
149  /// The Wi-Fi supplicant disconnected.
150  WifiClientDisconnected,
151  /// The Wi-Fi network took too long to let it in, as with a wrong
152  /// password.
153  WifiAuthTimeout,
154  /// The Wi-Fi network wasn't found.
155  WifiNetworkLost,
156  /// Any other reason, such as DHCP getting no address.
157  Unknown,
158}
159
160/// What a Wi-Fi device does, from NetworkManager's `NM80211Mode`.
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162pub enum WifiMode {
163  /// Not known, and for a device that isn't Wi-Fi.
164  Unknown,
165  /// Part of an ad-hoc network, with no access point.
166  AdHoc,
167  /// A station that joins networks, the usual mode.
168  Station,
169  /// An access point of its own, as a hotspot.
170  AccessPoint,
171  /// An 802.11s mesh point.
172  Mesh,
173}
174
175/// How a Wi-Fi network is secured, from its access point's flags.
176///
177/// Dynamic WEP and LEAP look the same as WEP from an access point, so
178/// all three show as [`Wep`](Self::Wep).
179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
180pub enum WifiSecurity {
181  /// No encryption.
182  Open,
183  /// WEP.
184  Wep,
185  /// WPA with a password.
186  WpaPsk,
187  /// WPA with 802.1X, as an enterprise network.
188  WpaEap,
189  /// WPA2 with a password.
190  Wpa2Psk,
191  /// WPA2 with 802.1X.
192  Wpa2Eap,
193  /// WPA3 with a password, also for a network that takes WPA2's too.
194  Sae,
195  /// Enhanced Open: encrypted, with no password.
196  Owe,
197  /// WPA3 Enterprise's 192-bit mode.
198  Wpa3SuiteB192,
199  /// Flags this doesn't know.
200  Unknown,
201}
202
203/// A network device NetworkManager manages, other than loopback.
204#[derive(Clone, Debug, PartialEq)]
205pub struct NetworkDevice {
206  /// NetworkManager's object path for it, which names it while it exists.
207  pub path: String,
208  /// Its interface, such as `wlan0`.
209  pub interface: String,
210  /// What it is.
211  pub kind: NetworkKind,
212  /// How it is doing.
213  pub state: NetworkState,
214  /// The name of its active connection, or `""`.
215  pub connection: String,
216  /// The uuid of its active connection's saved one, as
217  /// [`SavedConnection::uuid`], or `""`.
218  pub connection_uuid: String,
219  /// Its hardware address, such as `52:54:00:12:34:56`, or `""`.
220  pub hw_address: String,
221  /// Its first IPv4 address, such as `192.168.1.5`, or `""` while it has
222  /// none.
223  pub ipv4_address: String,
224  /// Why its last try to connect failed, kept until it tries again.
225  /// `None` if it hasn't failed since the shell started following it.
226  pub fail_reason: Option<ConnectionFailReason>,
227  /// What it does, for a Wi-Fi device; `Unknown` for any other.
228  pub wifi_mode: WifiMode,
229  /// For a wired device, its link's speed in Mb/s; 0 when not known, and
230  /// for any other device.
231  pub link_speed: u32,
232  /// For a wired device, whether a cable is in, from the carrier bit of
233  /// `InterfaceFlags`, or `Carrier` before NetworkManager 1.22; `false`
234  /// for any other.
235  pub has_link: bool,
236}
237
238impl NetworkDevice {
239  fn from_props(path: String, object: &Object, objects: &BTreeMap<String, Object>) -> Option<Self> {
240    let props = object.device.as_ref()?;
241    let active = dbus::get::<&ObjectPath>(props, "ActiveConnection")
242      .and_then(|at| objects.get(at.as_str())?.active.as_ref());
243    let ip4 = dbus::get::<&ObjectPath>(props, "Ip4Config")
244      .and_then(|at| objects.get(at.as_str())?.ip4.as_ref());
245    let wifi_mode = object
246      .wireless
247      .as_ref()
248      .and_then(|w| dbus::get::<u32>(w, "Mode"));
249    let wired = object.wired.as_ref();
250    Some(NetworkDevice {
251      path,
252      interface: dbus::text(props, "Interface"),
253      kind: match dbus::get::<u32>(props, "DeviceType") {
254        Some(1) => NetworkKind::Ethernet,
255        Some(2) => NetworkKind::Wifi,
256        _ => NetworkKind::Other,
257      },
258      state: match dbus::get::<u32>(props, "State") {
259        Some(ACTIVATED) => NetworkState::Connected,
260        Some(40..=90) => NetworkState::Connecting,
261        Some(110) => NetworkState::Disconnecting,
262        Some(30 | FAILED) => NetworkState::Disconnected,
263        _ => NetworkState::Unavailable,
264      },
265      connection: active.map_or(String::new(), |active| dbus::text(active, "Id")),
266      connection_uuid: active.map_or(String::new(), |active| dbus::text(active, "Uuid")),
267      hw_address: dbus::text(props, "HwAddress"),
268      ipv4_address: ip4.and_then(first_address).unwrap_or_default(),
269      fail_reason: object.failure,
270      wifi_mode: match wifi_mode {
271        Some(1) => WifiMode::AdHoc,
272        Some(2) => WifiMode::Station,
273        Some(3) => WifiMode::AccessPoint,
274        Some(4) => WifiMode::Mesh,
275        _ => WifiMode::Unknown,
276      },
277      link_speed: wired.and_then(|w| dbus::get(w, "Speed")).unwrap_or(0),
278      has_link: wired
279        .and_then(|wired| {
280          let flags = dbus::get::<u32>(props, "InterfaceFlags");
281          let carrier = flags.map(|flags| flags & CARRIER != 0);
282          carrier.or_else(|| dbus::get(wired, "Carrier"))
283        })
284        .unwrap_or(false),
285    })
286  }
287}
288
289/// A Wi-Fi network a device sees.
290#[derive(Clone, Debug, PartialEq)]
291pub struct WifiNetwork {
292  /// Its name, at most 32 bytes, with bytes that aren't UTF-8 shown as
293  /// `�`.
294  pub ssid: String,
295  /// How strong its strongest access point is, from 0 to 100.
296  pub strength: u8,
297  /// Whether it asks for a key: any [`security`](Self::security) but
298  /// `Open`, `Owe` and `Unknown`.
299  pub secured: bool,
300  /// How its strongest access point is secured.
301  pub security: WifiSecurity,
302  /// Whether the device is connected to it, through any of its access
303  /// points.
304  pub connected: bool,
305  /// The path of the device that sees it.
306  pub device: String,
307  /// The path of its strongest access point.
308  pub access_point: String,
309}
310
311/// Networking from NetworkManager, from `cx.network()`. Cloning it is
312/// cheap.
313#[derive(Clone)]
314pub struct Network {
315  service: Option<Rc<NetworkService>>,
316  /// The context that asked, which a [`Scanner`] lives as long as.
317  owner: Owner,
318  wifi_enabled: ReadSignal<bool>,
319  connectivity: ReadSignal<Connectivity>,
320  devices: ReadSignal<Vec<NetworkDevice>>,
321  wifi_networks: ReadSignal<Vec<WifiNetwork>>,
322  saved_connections: ReadSignal<Vec<SavedConnection>>,
323}
324
325impl Network {
326  /// Whether Wi-Fi is on. `false` while NetworkManager isn't running.
327  pub fn wifi_enabled(&self) -> ReadSignal<bool> {
328    self.wifi_enabled
329  }
330
331  /// How far the host reaches, from NetworkManager's own checks.
332  /// `Unknown` while it isn't running.
333  pub fn connectivity(&self) -> ReadSignal<Connectivity> {
334    self.connectivity
335  }
336
337  /// Every device but loopback and those NetworkManager doesn't manage,
338  /// in NetworkManager's numbering. Empty while it isn't running.
339  pub fn devices(&self) -> ReadSignal<Vec<NetworkDevice>> {
340    self.devices
341  }
342
343  /// The Wi-Fi networks each device sees, one per name and device,
344  /// strongest first. Hidden networks are left out. Empty while
345  /// NetworkManager isn't running.
346  pub fn wifi_networks(&self) -> ReadSignal<Vec<WifiNetwork>> {
347    self.wifi_networks
348  }
349
350  /// Asks every Wi-Fi device that is on to look for networks now and
351  /// every 10 s after, while the context that called `cx.network()` lives,
352  /// so call it inside the popup that shows the networks. Scanners share
353  /// one timer. NetworkManager's refusal of a scan too soon after another
354  /// is logged only at debug.
355  #[track_caller]
356  pub fn scanner(&self) -> Scanner {
357    if self.owner.is_disposed() {
358      let at = Location::caller();
359      tracing::warn!("Network::scanner (called at {at}) on a context that is gone does nothing");
360    } else if let Some(service) = &self.service {
361      service.add_scanner(self.owner);
362    }
363    Scanner { _private: () }
364  }
365
366  /// Turns Wi-Fi on or off.
367  pub fn set_wifi_enabled(&self, enabled: bool) {
368    let body = (NM, "WirelessEnabled", Variant::from(enabled));
369    self.call(NM_PATH, PROPERTIES, "Set", body);
370  }
371
372  /// Asks the Wi-Fi device at `device`, its path, to look for networks.
373  /// NetworkManager refuses a scan right after another, and that is
374  /// logged.
375  pub fn scan(&self, device: &str) {
376    let options = HashMap::<&str, Variant<'static>>::new();
377    self.call(device, WIRELESS, "RequestScan", options);
378  }
379
380  /// Connects `network`'s device to it. Without a password,
381  /// NetworkManager uses a connection saved for it, and refuses if it has
382  /// none. With one, it saves a new WPA connection and uses that. A
383  /// refusal is logged, never the password.
384  pub fn connect(&self, network: &WifiNetwork, password: Option<&str>) {
385    let paths = (
386      ObjectPath::try_from(network.device.clone()),
387      ObjectPath::try_from(network.access_point.clone()),
388    );
389    let (Ok(device), Ok(at)) = paths else {
390      return tracing::info!(network.ssid, "no such Wi-Fi network; nothing sent");
391    };
392    let Some(password) = password else {
393      return self.activate(network, device, at);
394    };
395    // The access point's own bytes: `ssid` may have lost some.
396    let ssid = self
397      .service
398      .as_ref()
399      .and_then(|service| {
400        let state = service.state.borrow();
401        let object = state.as_ref()?.objects.get(&network.access_point)?;
402        Some(ssid(object.access_point.as_ref()?))
403      })
404      .unwrap_or_else(|| network.ssid.clone().into_bytes());
405    let wireless = HashMap::from([("ssid", Variant::from(ssid))]);
406    // NetworkManager picks the key management, WPA2 or WPA3, from the
407    // access point.
408    let security = HashMap::from([("psk", Variant::from(password.to_owned()))]);
409    let settings = HashMap::from([
410      ("802-11-wireless", wireless),
411      ("802-11-wireless-security", security),
412    ]);
413    let body = (settings, device, at);
414    self.call(NM_PATH, NM, "AddAndActivateConnection", body);
415  }
416
417  /// Connects through a saved connection NetworkManager picks, and for
418  /// an open network with none, through a new one.
419  fn activate(&self, network: &WifiNetwork, device: ObjectPath<'static>, at: ObjectPath<'static>) {
420    let Some((shared, connection)) = self.bus("ActivateConnection") else {
421      return;
422    };
423    let (spawner, open) = (Rc::clone(&shared), !network.secured);
424    let ssid = network.ssid.clone().into_bytes();
425    let ssid = self
426      .service
427      .as_ref()
428      .and_then(|service| {
429        let state = service.state.borrow();
430        let object = state.as_ref()?.objects.get(&network.access_point)?;
431        Some(self::ssid(object.access_point.as_ref()?))
432      })
433      .unwrap_or(ssid);
434    spawner.spawn(async move {
435      let pick = ObjectPath::from_static_str_unchecked("/");
436      let body = (pick, &device, &at);
437      let call = connection.call_method(Some(NM), NM_PATH, Some(NM), "ActivateConnection", &body);
438      let Err(error) = shared.timeout(CALL_TIMEOUT, call).await else {
439        return;
440      };
441      if !open {
442        return tracing::warn!(%error, "no saved connection for that network");
443      }
444      let wireless = HashMap::from([("ssid", Variant::from(ssid))]);
445      let settings = HashMap::from([("802-11-wireless", wireless)]);
446      let body = (settings, &device, &at);
447      let method = "AddAndActivateConnection";
448      let call = connection.call_method(Some(NM), NM_PATH, Some(NM), method, &body);
449      if let Err(error) = shared.timeout(CALL_TIMEOUT, call).await {
450        tracing::warn!(%error, method, "NetworkManager refused it");
451      }
452    });
453  }
454
455  /// Disconnects the device at `device`, until it is connected again.
456  pub fn disconnect(&self, device: &str) {
457    self.call(device, DEVICE, "Disconnect", ());
458  }
459
460  /// The connections NetworkManager saved, in its numbering, at most
461  /// 256. NetworkManager is asked for them on the first call and
462  /// followed from then on, so a config that never lists them reads
463  /// none. Empty while it isn't running.
464  pub fn saved_connections(&self) -> ReadSignal<Vec<SavedConnection>> {
465    let saved = self.service.as_ref().and_then(|service| {
466      let state = service.state.borrow();
467      Some(Rc::clone(&state.as_ref()?.saved))
468    });
469    if let Some(saved) = saved {
470      saved.follow();
471    }
472    self.saved_connections
473  }
474
475  /// Deletes the saved connection `uuid` names, so NetworkManager
476  /// forgets that network. A refusal is logged.
477  pub fn forget(&self, uuid: &str) {
478    self.call_saved(uuid, "Delete", ());
479  }
480
481  /// Takes the secrets, such as a Wi-Fi password, out of the saved
482  /// connection `uuid` names, so NetworkManager asks for them next time.
483  /// A refusal is logged.
484  pub fn clear_secrets(&self, uuid: &str) {
485    self.call_saved(uuid, "ClearSecrets", ());
486  }
487
488  /// Saves a new connection with `settings`, by group and name as
489  /// [`SavedConnection::settings`] holds them. Secrets such as a Wi-Fi
490  /// `psk` may come too. An SSID or a hardware address may come as text.
491  /// A value of a shape NetworkManager has no type for, or a refusal, is
492  /// logged, never the settings.
493  ///
494  /// ```no_run
495  /// # use crabshell_services::Network;
496  /// fn save_cafe(network: &Network, password: &str) {
497  ///   network.add_connection(&serde_json::json!({
498  ///     "connection": { "id": "cafe", "type": "802-11-wireless" },
499  ///     "802-11-wireless": { "ssid": "cafe" },
500  ///     "802-11-wireless-security": { "key-mgmt": "wpa-psk", "psk": password },
501  ///   }));
502  /// }
503  /// ```
504  pub fn add_connection(&self, settings: &Json) {
505    if let Some(settings) = typed(settings, "AddConnection") {
506      self.call(SETTINGS_PATH, SETTINGS, "AddConnection", settings);
507    }
508  }
509
510  /// Replaces the settings of the saved connection `uuid` names with
511  /// `settings`, as [`add_connection`](Self::add_connection) takes them.
512  /// Those left out go back to NetworkManager's defaults. NetworkManager
513  /// keeps the saved secrets when `settings` carries none, and drops them
514  /// all once it carries any, so a new `psk` alone on an 802.1X connection
515  /// drops its other passwords.
516  pub fn update_connection(&self, uuid: &str, settings: &Json) {
517    if let Some(settings) = typed(settings, "Update") {
518      self.call_saved(uuid, "Update", settings);
519    }
520  }
521
522  /// Calls `method` with `body` on the saved connection `uuid` names, and
523  /// logs a refusal, without the body.
524  fn call_saved<B>(&self, uuid: &str, method: &'static str, body: B)
525  where
526    B: serde::Serialize + zbus::DynamicType + 'static,
527  {
528    let Some((shared, connection)) = self.bus(method) else {
529      return;
530    };
531    let (spawner, uuid) = (Rc::clone(&shared), uuid.to_owned());
532    spawner.spawn(async move {
533      let called = async {
534        let find = "GetConnectionByUuid";
535        let call = connection.call_method(Some(NM), SETTINGS_PATH, Some(SETTINGS), find, &uuid);
536        let reply = shared.timeout(CALL_TIMEOUT, call).await?;
537        let path = reply.body().deserialize::<OwnedObjectPath>()?;
538        let call = connection.call_method(Some(NM), path.as_str(), Some(SAVED), method, &body);
539        shared.timeout(CALL_TIMEOUT, call).await.map(drop)
540      };
541      if let Err(error) = called.await {
542        tracing::warn!(%error, uuid, method, "NetworkManager refused it");
543      }
544    });
545  }
546
547  /// Calls `method` on NetworkManager's object at `path`, and logs a
548  /// refusal, without the body.
549  fn call<B>(&self, path: &str, interface: &'static str, method: &'static str, body: B)
550  where
551    B: serde::Serialize + zbus::DynamicType + 'static,
552  {
553    let Some((shared, connection)) = self.bus(method) else {
554      return;
555    };
556    let (spawner, path) = (Rc::clone(&shared), path.to_owned());
557    spawner.spawn(async move {
558      let call = connection.call_method(Some(NM), path.as_str(), Some(interface), method, &body);
559      if let Err(error) = shared.timeout(CALL_TIMEOUT, call).await {
560        tracing::warn!(%error, path, method, "NetworkManager refused it");
561      }
562    });
563  }
564
565  /// What a call to `method` goes through, or `None`, which is logged,
566  /// while NetworkManager isn't running.
567  fn bus(&self, method: &str) -> Option<(Rc<Shared>, Connection)> {
568    let service = self.service.as_ref()?;
569    let state = service.state.borrow();
570    let Some(connection) = state.as_ref().and_then(|state| state.connection.clone()) else {
571      tracing::info!(method, "NetworkManager isn't running; nothing sent");
572      return None;
573    };
574    Some((Rc::clone(&service.shared), connection))
575  }
576}
577
578/// What [`Network::scanner`] gives: networks are scanned for while the
579/// context that asked lives. It has nothing to call.
580#[derive(Clone, Copy, Debug)]
581pub struct Scanner {
582  _private: (),
583}
584
585/// Takes a scanner away when its context goes.
586struct Unscan(Rc<NetworkService>);
587
588impl Drop for Unscan {
589  fn drop(&mut self) {
590    let service = &self.0;
591    service.scanners.set(service.scanners.get() - 1);
592    if service.scanners.get() > 0 {
593      return;
594    }
595    if let (Some(timer), Some(event_loop)) =
596      (service.scan_timer.take(), service.shared.event_loop())
597    {
598      event_loop.remove(timer);
599    }
600  }
601}
602
603/// `settings` typed for `method`, or `None`, logged by the property it
604/// stopped at, never its value.
605fn typed(settings: &Json, method: &str) -> Option<write::Typed> {
606  write::typed(settings)
607    .inspect_err(|error| {
608      tracing::warn!(
609        error,
610        method,
611        "settings NetworkManager can't take; nothing sent"
612      )
613    })
614    .ok()
615}
616
617/// `cx.network()`.
618pub(crate) fn network(cx: &Cx) -> Network {
619  let Some(service) = cx.service::<NetworkService>() else {
620    static LOGGED: Once = Once::new();
621    LOGGED.call_once(|| {
622      tracing::warn!("cx.network() needs the services the shell provides; it stays empty");
623    });
624    return Network {
625      service: None,
626      owner: cx.owner(),
627      wifi_enabled: cx.signal(false).read_only(),
628      connectivity: cx.signal(Connectivity::Unknown).read_only(),
629      devices: cx.signal(Vec::new()).read_only(),
630      wifi_networks: cx.signal(Vec::new()).read_only(),
631      saved_connections: cx.signal(Vec::new()).read_only(),
632    };
633  };
634  service.start(cx.owner())
635}
636
637/// NetworkManager for one shell, followed from the first ask.
638pub(crate) struct NetworkService {
639  shared: Rc<Shared>,
640  state: RefCell<Option<State>>,
641  /// How many scanners live, and the timer they share while any does.
642  scanners: Cell<usize>,
643  scan_timer: Cell<Option<RegistrationToken>>,
644}
645
646struct State {
647  wifi_enabled: Signal<bool>,
648  connectivity: Signal<Connectivity>,
649  devices: Signal<Vec<NetworkDevice>>,
650  wifi_networks: Signal<Vec<WifiNetwork>>,
651  /// The saved connections, followed apart once a config lists them.
652  saved: Rc<SavedConnections>,
653  /// NetworkManager's objects that this service reads, by path.
654  objects: BTreeMap<String, Object>,
655  /// The bus, while NetworkManager runs, for the methods.
656  connection: Option<Connection>,
657  generation: u64,
658}
659
660impl State {
661  /// The handle a config gets.
662  fn network(&self, service: &Rc<NetworkService>, owner: Owner) -> Network {
663    Network {
664      service: Some(Rc::clone(service)),
665      owner,
666      wifi_enabled: self.wifi_enabled.read_only(),
667      connectivity: self.connectivity.read_only(),
668      devices: self.devices.read_only(),
669      wifi_networks: self.wifi_networks.read_only(),
670      saved_connections: self.saved.list.read_only(),
671    }
672  }
673}
674
675/// The interfaces this service reads on one of NetworkManager's objects.
676/// An object is kept while it has one other than `wireless` and `wired`.
677#[derive(Default)]
678struct Object {
679  manager: Option<Props>,
680  device: Option<Props>,
681  wireless: Option<Props>,
682  wired: Option<Props>,
683  access_point: Option<Props>,
684  active: Option<Props>,
685  ip4: Option<Props>,
686  /// A device's last failure, which its `StateReason` forgets as it moves
687  /// on.
688  failure: Option<ConnectionFailReason>,
689}
690
691impl Object {
692  /// Where `interface`'s properties go, or `None` for one this service
693  /// doesn't read.
694  fn slot(&mut self, interface: &str) -> Option<&mut Option<Props>> {
695    match interface {
696      NM => Some(&mut self.manager),
697      DEVICE => Some(&mut self.device),
698      WIRELESS => Some(&mut self.wireless),
699      WIRED => Some(&mut self.wired),
700      ACCESS_POINT => Some(&mut self.access_point),
701      ACTIVE => Some(&mut self.active),
702      IP4 => Some(&mut self.ip4),
703      _ => None,
704    }
705  }
706
707  fn kept(&self) -> bool {
708    self.manager.is_some()
709      || self.device.is_some()
710      || self.access_point.is_some()
711      || self.active.is_some()
712      || self.ip4.is_some()
713  }
714
715  /// Notes a device's failure from its `StateReason`, and forgets it once
716  /// the device tries again.
717  fn note_failure(&mut self) {
718    let Some(device) = &self.device else {
719      return;
720    };
721    // `(uu)`, the state and the reason the device went into it.
722    let reason = device.get("StateReason");
723    let reason = reason.and_then(|reason| <(u32, u32)>::try_from(&**reason).ok());
724    if let Some((FAILED, reason)) = reason {
725      self.failure = Some(fail_reason(reason));
726    }
727    if let Some(40..=ACTIVATED) = dbus::get::<u32>(device, "State") {
728      self.failure = None;
729    }
730  }
731}
732
733/// What NetworkManager's `NMDeviceStateReason` `reason` says about a
734/// failure.
735fn fail_reason(reason: u32) -> ConnectionFailReason {
736  match reason {
737    7 => ConnectionFailReason::NoSecrets,
738    8 => ConnectionFailReason::WifiClientDisconnected,
739    // The supplicant's settings failed, or the supplicant did.
740    9 | 10 => ConnectionFailReason::WifiClientFailed,
741    11 => ConnectionFailReason::WifiAuthTimeout,
742    53 => ConnectionFailReason::WifiNetworkLost,
743    _ => ConnectionFailReason::Unknown,
744  }
745}
746
747/// Orders NetworkManager's paths by the number that ends them, so
748/// `Devices/2` comes before `Devices/10`.
749fn by_number(a: &str, b: &str) -> Ordering {
750  (a.len(), a).cmp(&(b.len(), b))
751}
752
753/// An access point's SSID, cut to 802.11's 32 bytes. Empty for one that
754/// isn't an `ay`.
755fn ssid(props: &Props) -> Vec<u8> {
756  let bytes = dbus::get::<&Array>(props, "Ssid");
757  let bytes = bytes.iter().flat_map(|bytes| bytes.inner());
758  let bytes = bytes.map_while(|byte| match byte {
759    Variant::U8(byte) => Some(*byte),
760    _ => None,
761  });
762  bytes.take(MAX_SSID).collect()
763}
764
765/// The first address in an IPv4 config's `AddressData`, an `aa{sv}`.
766fn first_address(props: &Props) -> Option<String> {
767  let Variant::Dict(address) = dbus::get::<&Array>(props, "AddressData")?.inner().first()? else {
768    return None;
769  };
770  let address = address.iter().find_map(|(key, value)| match (key, value) {
771    (Variant::Str(key), Variant::Variant(value)) if key.as_str() == "address" => Some(value),
772    _ => None,
773  });
774  match &**address? {
775    Variant::Str(address) => Some(address.as_str().to_owned()),
776    _ => None,
777  }
778}
779
780/// The object paths in the `ao` property `name`.
781fn paths<'a>(props: &'a Props, name: &str) -> impl Iterator<Item = &'a str> {
782  let paths = dbus::get::<&Array>(props, name);
783  paths
784    .into_iter()
785    .flat_map(|paths| paths.inner())
786    .filter_map(|path| match path {
787      Variant::ObjectPath(path) => Some(path.as_str()),
788      _ => None,
789    })
790}
791
792/// Gives the object at `path` `interfaces`. Past [`MAX_OBJECTS`] a new
793/// one is left out; which are shown is decided as they are.
794fn add(objects: &mut BTreeMap<String, Object>, path: String, interfaces: HashMap<String, Props>) {
795  if objects.len() >= MAX_OBJECTS && !objects.contains_key(&path) {
796    return tracing::debug!(path, "too many network objects; leaving one out");
797  }
798  let mut object = objects.remove(&path).unwrap_or_default();
799  for (interface, props) in interfaces {
800    if let Some(slot) = object.slot(&interface) {
801      *slot = Some(props);
802    }
803  }
804  object.note_failure();
805  if object.kept() {
806    objects.insert(path, object);
807  }
808}
809
810/// How the access point `point` is secured, from the strongest key
811/// management it offers: RSN's before WPA's, a password before 802.1X,
812/// as one will do, and SAE before a WPA2 password. Enhanced Open comes
813/// after those, and then WEP, whose privacy bit is all that marks it.
814fn security(point: &Props) -> WifiSecurity {
815  let flags = |name| dbus::get::<u32>(point, name).unwrap_or(0);
816  let (wpa, rsn) = (flags("WpaFlags"), flags("RsnFlags"));
817  let strongest_first = [
818    (rsn, KEY_MGMT_SUITE_B_192, WifiSecurity::Wpa3SuiteB192),
819    (rsn, KEY_MGMT_SAE, WifiSecurity::Sae),
820    (rsn, KEY_MGMT_PSK, WifiSecurity::Wpa2Psk),
821    (rsn, KEY_MGMT_802_1X, WifiSecurity::Wpa2Eap),
822    (wpa, KEY_MGMT_PSK, WifiSecurity::WpaPsk),
823    (wpa, KEY_MGMT_802_1X, WifiSecurity::WpaEap),
824    (rsn, KEY_MGMT_OWE, WifiSecurity::Owe),
825  ];
826  let offered = strongest_first
827    .into_iter()
828    .find(|(flags, key, _)| flags & key != 0);
829  match offered {
830    Some((_, _, security)) => security,
831    None if wpa != 0 || rsn != 0 => WifiSecurity::Unknown,
832    None if flags("Flags") & PRIVACY != 0 => WifiSecurity::Wep,
833    None => WifiSecurity::Open,
834  }
835}
836
837/// Whether a network secured as `security` asks for a key. Enhanced
838/// Open encrypts without one.
839fn secured(security: WifiSecurity) -> bool {
840  !matches!(
841    security,
842    WifiSecurity::Open | WifiSecurity::Owe | WifiSecurity::Unknown
843  )
844}
845
846/// The properties this service reads, by interface: a change to any
847/// other, such as an access point's `LastSeen` on each scan, shows
848/// nothing new.
849fn read(interface: &str, name: &str) -> bool {
850  match interface {
851    NM => matches!(name, "WirelessEnabled" | "Connectivity"),
852    DEVICE => matches!(
853      name,
854      "Interface"
855        | "DeviceType"
856        | "State"
857        | "StateReason"
858        | "ActiveConnection"
859        | "InterfaceFlags"
860        | "HwAddress"
861        | "Ip4Config"
862    ),
863    WIRELESS => matches!(name, "AccessPoints" | "ActiveAccessPoint" | "Mode"),
864    WIRED => matches!(name, "Speed" | "Carrier"),
865    ACCESS_POINT => matches!(
866      name,
867      "Ssid" | "Strength" | "Flags" | "WpaFlags" | "RsnFlags"
868    ),
869    ACTIVE => matches!(name, "Id" | "Uuid"),
870    IP4 => name == "AddressData",
871    _ => false,
872  }
873}
874
875/// The networks each Wi-Fi device in `objects` sees: the strongest access
876/// point per SSID and device, strongest first.
877fn wifi_networks(objects: &BTreeMap<String, Object>) -> Vec<WifiNetwork> {
878  let mut best = BTreeMap::<(&str, Vec<u8>), WifiNetwork>::new();
879  for (path, object) in objects {
880    let (Some(device), Some(wireless)) = (&object.device, &object.wireless) else {
881      continue;
882    };
883    let on = dbus::get::<u32>(device, "State") == Some(ACTIVATED);
884    let active = dbus::get::<&ObjectPath>(wireless, "ActiveAccessPoint");
885    let active = active.map(|at| at.as_str());
886    for at in paths(wireless, "AccessPoints") {
887      let Some(point) = objects
888        .get(at)
889        .and_then(|object| object.access_point.as_ref())
890      else {
891        continue;
892      };
893      let ssid = ssid(point);
894      // Hidden: empty, or NUL bytes standing in for its length.
895      if ssid.iter().all(|byte| *byte == 0) {
896        continue;
897      }
898      let security = self::security(point);
899      let network = WifiNetwork {
900        ssid: String::from_utf8_lossy(&ssid).into_owned(),
901        strength: dbus::get::<u8>(point, "Strength").unwrap_or(0).min(100),
902        secured: secured(security),
903        security,
904        connected: on && active == Some(at),
905        device: path.clone(),
906        access_point: at.to_owned(),
907      };
908      match best.entry((path, ssid)) {
909        Entry::Vacant(entry) => {
910          entry.insert(network);
911        }
912        Entry::Occupied(mut entry) => {
913          let connected = entry.get().connected || network.connected;
914          if network.strength > entry.get().strength {
915            entry.insert(network);
916          }
917          entry.get_mut().connected = connected;
918        }
919      }
920    }
921  }
922  let mut networks = best.into_values().collect::<Vec<_>>();
923  networks.sort_by(|a, b| {
924    let ties = || (&a.ssid, &a.device).cmp(&(&b.ssid, &b.device));
925    b.strength.cmp(&a.strength).then_with(ties)
926  });
927  networks.truncate(MAX_ACCESS_POINTS);
928  networks
929}
930
931impl NetworkService {
932  pub(crate) fn new(shared: Rc<Shared>) -> NetworkService {
933    NetworkService {
934      shared,
935      state: RefCell::new(None),
936      scanners: Cell::new(0),
937      scan_timer: Cell::new(None),
938    }
939  }
940
941  fn start(self: &Rc<Self>, owner: Owner) -> Network {
942    if let Some(state) = &*self.state.borrow() {
943      return state.network(self, owner);
944    }
945    let root = &self.shared.root;
946    let state = State {
947      wifi_enabled: root.signal(false),
948      connectivity: root.signal(Connectivity::Unknown),
949      devices: root.signal(Vec::new()),
950      wifi_networks: root.signal(Vec::new()),
951      saved: SavedConnections::new(Rc::clone(&self.shared)),
952      objects: BTreeMap::new(),
953      connection: None,
954      generation: 0,
955    };
956    let network = state.network(self, owner);
957    *self.state.borrow_mut() = Some(state);
958    match self.shared.config.system_bus.clone() {
959      Some(address) => {
960        let follow = dbus::follow(Rc::clone(&self.shared), Rc::clone(self), address);
961        self.shared.spawn(follow);
962      }
963      None => tracing::info!("no system bus, so there is no networking"),
964    }
965    network
966  }
967
968  /// Adds a scanner that lives as long as `owner`, scanning at once and
969  /// starting the timer if it is the first.
970  fn add_scanner(self: &Rc<Self>, owner: Owner) {
971    if self.scanners.replace(self.scanners.get() + 1) == 0 {
972      self.scan();
973      let weak = Rc::downgrade(self);
974      let tick = Box::new(move || {
975        let Some(service) = weak.upgrade() else {
976          return TimeoutAction::Drop;
977        };
978        service.scan();
979        TimeoutAction::ToDuration(scan_period())
980      });
981      let event_loop = self.shared.event_loop();
982      let timer = event_loop
983        .and_then(|event_loop| event_loop.insert_timer(Instant::now() + scan_period(), tick));
984      self.scan_timer.set(timer);
985    }
986    owner.signal(Unscan(Rc::clone(self)));
987  }
988
989  /// Asks each Wi-Fi device that is on to scan.
990  fn scan(&self) {
991    let (devices, connection) = {
992      let state = self.state.borrow();
993      let Some((state, connection)) = state
994        .as_ref()
995        .and_then(|state| Some((state, state.connection.clone()?)))
996      else {
997        return;
998      };
999      let on = |object: &Object| {
1000        let device = object.device.as_ref();
1001        let state = device.and_then(|device| dbus::get::<u32>(device, "State"));
1002        object.wireless.is_some() && state.is_some_and(|state| state > UNAVAILABLE)
1003      };
1004      let devices = state.objects.iter().filter(|(_, object)| on(object));
1005      (
1006        devices.map(|(path, _)| path.clone()).collect::<Vec<_>>(),
1007        connection,
1008      )
1009    };
1010    for device in devices {
1011      let (shared, connection) = (Rc::clone(&self.shared), connection.clone());
1012      self.shared.spawn(async move {
1013        let options = HashMap::<&str, Variant<'static>>::new();
1014        let call = connection.call_method(
1015          Some(NM),
1016          device.as_str(),
1017          Some(WIRELESS),
1018          "RequestScan",
1019          &options,
1020        );
1021        match shared.timeout(CALL_TIMEOUT, call).await {
1022          Ok(_) => {}
1023          Err(zbus::Error::MethodError(name, ..)) if name.as_str() == NOT_ALLOWED => {
1024            tracing::debug!(device, "NetworkManager scans later");
1025          }
1026          Err(error) => tracing::warn!(%error, device, "NetworkManager refused a scan"),
1027        }
1028      });
1029    }
1030  }
1031
1032  /// Shows Wi-Fi, connectivity, the devices and the networks as they are
1033  /// now. Each is set only if it changed, since a scan changes much that
1034  /// none shows.
1035  fn publish(&self) {
1036    // Set apart from the borrow, since effects may ask for more.
1037    let shown = self.state.borrow().as_ref().map(|state| {
1038      let objects = &state.objects;
1039      let manager = objects
1040        .get(NM_PATH)
1041        .and_then(|object| object.manager.as_ref());
1042      let enabled = manager.and_then(|props| dbus::get(props, "WirelessEnabled"));
1043      let connectivity = match manager.and_then(|props| dbus::get::<u32>(props, "Connectivity")) {
1044        Some(1) => Connectivity::None,
1045        Some(2) => Connectivity::Portal,
1046        Some(3) => Connectivity::Limited,
1047        Some(4) => Connectivity::Full,
1048        _ => Connectivity::Unknown,
1049      };
1050      let mut devices = objects
1051        .iter()
1052        .filter_map(|(path, object)| {
1053          let props = object.device.as_ref()?;
1054          let kind = dbus::get::<u32>(props, "DeviceType");
1055          let state = dbus::get::<u32>(props, "State");
1056          if kind == Some(LOOPBACK) || state == Some(UNMANAGED) {
1057            return None;
1058          }
1059          NetworkDevice::from_props(path.clone(), object, objects)
1060        })
1061        .collect::<Vec<_>>();
1062      devices.sort_by(|a, b| by_number(&a.path, &b.path));
1063      devices.truncate(MAX_DEVICES);
1064      let shown = (
1065        enabled.unwrap_or(false),
1066        connectivity,
1067        devices,
1068        wifi_networks(objects),
1069      );
1070      let signals = (
1071        state.wifi_enabled,
1072        state.connectivity,
1073        state.devices,
1074        state.wifi_networks,
1075      );
1076      (signals, shown)
1077    });
1078    if let Some((signals, shown)) = shown {
1079      set_changed(signals.0, shown.0);
1080      set_changed(signals.1, shown.1);
1081      set_changed(signals.2, shown.2);
1082      set_changed(signals.3, shown.3);
1083    }
1084  }
1085}
1086
1087impl Daemon for NetworkService {
1088  const NAME: &'static str = NM;
1089
1090  /// Only what this service reads: NetworkManager also broadcasts IP and
1091  /// DHCP settings, statistics and saved connections, which would each
1092  /// wake the shell for nothing.
1093  fn rules() -> Vec<String> {
1094    let mut rules = vec![format!(
1095      "type='signal',sender='{NM}',path='{ROOT}',interface='{OBJECT_MANAGER}'"
1096    )];
1097    rules.extend(
1098      [NM, DEVICE, WIRELESS, WIRED, ACCESS_POINT, ACTIVE, IP4].map(|interface| {
1099        format!(
1100          "type='signal',sender='{NM}',interface='{PROPERTIES}',member='PropertiesChanged',\
1101         arg0='{interface}'"
1102        )
1103      }),
1104    );
1105    rules
1106  }
1107
1108  fn alive(&self) -> bool {
1109    let state = self.state.borrow();
1110    state
1111      .as_ref()
1112      .is_some_and(|state| state.devices.try_with(|_| ()).is_some())
1113  }
1114
1115  fn clear(&self) -> u64 {
1116    let generation = {
1117      let mut state = self.state.borrow_mut();
1118      let Some(state) = state.as_mut() else {
1119        return 0;
1120      };
1121      state.objects.clear();
1122      state.connection = None;
1123      state.generation += 1;
1124      state.generation
1125    };
1126    self.publish();
1127    generation
1128  }
1129
1130  async fn read(self: Rc<Self>, connection: Connection, generation: u64) {
1131    let call = connection.call_method(
1132      Some(NM),
1133      ROOT,
1134      Some(OBJECT_MANAGER),
1135      "GetManagedObjects",
1136      &(),
1137    );
1138    let read = async {
1139      let reply = self.shared.timeout(CALL_TIMEOUT, call).await?;
1140      reply
1141        .body()
1142        .deserialize::<HashMap<OwnedObjectPath, HashMap<String, Props>>>()
1143    };
1144    let managed = match read.await {
1145      Ok(managed) => managed,
1146      Err(error) => return tracing::warn!(%error, "couldn't read NetworkManager"),
1147    };
1148    // By number, so the caps keep the oldest objects, the same every time.
1149    let mut managed = managed
1150      .into_iter()
1151      .map(|(path, interfaces)| (path.as_str().to_owned(), interfaces))
1152      .collect::<Vec<_>>();
1153    managed.sort_by(|(a, _), (b, _)| by_number(a, b));
1154    {
1155      let mut state = self.state.borrow_mut();
1156      let Some(state) = state
1157        .as_mut()
1158        .filter(|state| state.generation == generation)
1159      else {
1160        return;
1161      };
1162      state.objects.clear();
1163      for (path, interfaces) in managed {
1164        add(&mut state.objects, path, interfaces);
1165      }
1166      state.connection = Some(connection);
1167    }
1168    self.publish();
1169    // A scanner made before NetworkManager was read scans now, not a
1170    // period later.
1171    if self.scanners.get() > 0 {
1172      self.scan();
1173    }
1174  }
1175
1176  fn signal(self: &Rc<Self>, _: &Connection, message: &Message) {
1177    if let Some((path, interface, changed, dropped)) = dbus::properties_changed(message) {
1178      {
1179        let mut state = self.state.borrow_mut();
1180        let object = state
1181          .as_mut()
1182          .and_then(|state| state.objects.get_mut(&path));
1183        let Some(object) = object else {
1184          return;
1185        };
1186        let Some(props) = object.slot(&interface).and_then(Option::as_mut) else {
1187          return;
1188        };
1189        let shown = changed
1190          .keys()
1191          .chain(&dropped)
1192          .any(|name| read(&interface, name));
1193        dbus::apply(props, changed, dropped);
1194        object.note_failure();
1195        if !shown {
1196          return;
1197        }
1198      }
1199      return self.publish();
1200    }
1201    let header = message.header();
1202    if header.interface().map(|interface| interface.as_str()) != Some(OBJECT_MANAGER) {
1203      return;
1204    }
1205    let body = message.body();
1206    {
1207      let mut state = self.state.borrow_mut();
1208      let Some(state) = state.as_mut() else {
1209        return;
1210      };
1211      match header.member().map(|member| member.as_str()) {
1212        Some("InterfacesAdded") => {
1213          let Ok((path, interfaces)) =
1214            body.deserialize::<(OwnedObjectPath, HashMap<String, Props>)>()
1215          else {
1216            return;
1217          };
1218          add(&mut state.objects, path.as_str().to_owned(), interfaces);
1219        }
1220        Some("InterfacesRemoved") => {
1221          let Ok((path, interfaces)) = body.deserialize::<(OwnedObjectPath, Vec<String>)>() else {
1222            return;
1223          };
1224          let Some(object) = state.objects.get_mut(path.as_str()) else {
1225            return;
1226          };
1227          for interface in interfaces {
1228            if let Some(slot) = object.slot(&interface) {
1229              *slot = None;
1230            }
1231          }
1232          if !object.kept() {
1233            state.objects.remove(path.as_str());
1234          }
1235        }
1236        _ => return,
1237      }
1238    }
1239    self.publish();
1240  }
1241}