Files
chandra/compositor/network/nm.mbt
T
Claude 1f4b686087
CI / test (push) Failing after 18s
Network module: Wi-Fi and wired status, connect to Wi-Fi networks, Wi-Fi and airplane switches
- New `network` panel module (in the default panel, before the battery and the clock): signal bars and the
  Wi-Fi network's name, a plug when wired, crossed-out bars offline or in airplane mode. Its
  popup shows the status and the last action's outcome ("Couldn't connect to X: wrong
  password?"), switches for Wi-Fi and airplane mode, and the networks in range (strongest
  access point per name, the one in use first). Click a saved or open network to connect, a new
  secured one to type its password in a field under it (Enter or Connect), the one in use to
  disconnect, or "Forget" on a saved one. Opening the popup asks for a scan.
- compositor/network: NetworkManager over D-Bus through a small D-Bus client of our own
  (wire format, EXTERNAL auth, async calls) on the existing @sys socket calls, so neither host
  needed new imports. One ObjectManager.GetManagedObjects + GetAll every 2 s; GetSettings once
  per saved connection; RequestScan, Device.Disconnect, WirelessEnabled / WwanEnabled,
  ActivateConnection (saved), AddAndActivateConnection (new: open, WPA/WPA2 PSK, WPA3 SAE) and
  Settings.Connection.Delete. Without NetworkManager it falls back to read-only status from
  /proc/net/dev, /proc/net/wireless and /sys/class/net (no network names there), and looks for
  NetworkManager again every 30 s.
- New `network` capability (wit/capabilities.wit): status, wifi-networks, scan, connect,
  disconnect, forget, set-wifi-enabled, set-airplane-mode. Served from host tables 8/9 and a
  `network(network-request)` request by the wasmer/wasmtime stub (compositor/wasm), host-wasm
  and the MoonBit wasmhost. The stub's build_list learned bool fields; request strings are
  wiped after use (Wi-Fi passwords).
- Running out of module instances now says "too many modules loaded".
- Deferred: VPN, hotspot, hidden networks, WEP and 802.1X (enterprise) networks, IP settings,
  mobile broadband beyond the airplane switch, D-Bus signals (state is polled).
- Tests: D-Bus wire format (incl. the well-known Hello bytes), NetworkManager objects -> status
  and list, security settings, /proc parsing; the module through the shell against a fake
  backend (list, connect/forget/disconnect, password entry, switches, read-only); a host-wasm
  test; and scripts/test-network-dbus.sh, which runs the backend against python-dbusmock's
  NetworkManager on a private bus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hizqNXcNDuef3gxa7D
2026-11-25 20:02:36 +00:00

640 lines
18 KiB
MoonBit

///| NetworkManager over D-Bus (org.freedesktop.NetworkManager). Every couple of seconds one
/// ObjectManager.GetManagedObjects call fetches the devices, access points and active connections,
/// plus Properties.GetAll on the manager; saved connections' Wi-Fi names are read once each with
/// GetSettings. Actions are plain method calls: RequestScan, Device.Disconnect, setting
/// WirelessEnabled / WwanEnabled, ActivateConnection (a saved network), AddAndActivateConnection
/// (a new one, WPA/WPA3 personal with a password, or open) and Settings.Connection.Delete. All of
/// it is asynchronous: nothing waits for NetworkManager except the first connect.
///|
let nm_name : String = "org.freedesktop.NetworkManager"
///|
let nm_path : String = "/org/freedesktop/NetworkManager"
///|
let props_iface : String = "org.freedesktop.DBus.Properties"
///|
let dev_iface : String = "org.freedesktop.NetworkManager.Device"
///|
let wifi_iface : String = "org.freedesktop.NetworkManager.Device.Wireless"
///|
let ap_iface : String = "org.freedesktop.NetworkManager.AccessPoint"
///|
let active_iface : String = "org.freedesktop.NetworkManager.Connection.Active"
///|
let setting_iface : String = "org.freedesktop.NetworkManager.Settings.Connection"
///| NetworkManager device types and states we look at.
let dev_type_ethernet : Int = 1
///|
let dev_type_wifi : Int = 2
///| NM_DEVICE_STATE_*: 30 disconnected, 40-90 on the way (prepare ... secondaries), 100 activated,
/// 120 failed.
let dev_state_disconnected : Int = 30
///|
let dev_state_activated : Int = 100
///|
let dev_state_failed : Int = 120
///| NM_DEVICE_STATE_REASON_NO_SECRETS: the password was wrong or missing.
let reason_no_secrets : Int = 7
// ---- reading replies ----
///| Unwrap variants.
fn plain(v : DValue) -> DValue {
match v {
Variant(x) => plain(x)
_ => v
}
}
///|
fn as_str(v : DValue?) -> String {
match v.map(plain) {
Some(Str(s)) | Some(Path(s)) => s
_ => ""
}
}
///|
fn as_int(v : DValue?) -> Int {
match v.map(plain) {
Some(U32(x)) => x.reinterpret_as_int()
Some(I32(x)) | Some(Byte(x)) => x
_ => 0
}
}
///|
fn as_bool(v : DValue?) -> Bool {
match v.map(plain) {
Some(Bool(b)) => b
_ => false
}
}
///|
fn as_paths(v : DValue?) -> Array[String] {
match v.map(plain) {
Some(Arr(_, items)) =>
items.filter_map(it => match it {
Path(p) => Some(p)
_ => None
})
_ => []
}
}
///| An a{s?} dict as a map (values with their variants unwrapped).
pub fn dict_map(v : DValue) -> Map[String, DValue] {
let m : Map[String, DValue] = {}
if plain(v) is Arr(_, items) {
for it in items {
if it is Entry(k, x) {
match k {
Str(s) | Path(s) => m.set(s, plain(x))
_ => ()
}
}
}
}
m
}
///| GetManagedObjects' a{oa{sa{sv}}}: path -> interface -> property -> value.
pub fn objects_map(v : DValue) -> Map[String, Map[String, Map[String, DValue]]] {
let out : Map[String, Map[String, Map[String, DValue]]] = {}
if v is Arr(_, objs) {
for o in objs {
if o is Entry(Path(p), ifaces) {
let im : Map[String, Map[String, DValue]] = {}
if ifaces is Arr(_, items) {
for it in items {
if it is Entry(Str(name), props) {
im.set(name, dict_map(props))
}
}
}
out.set(p, im)
}
}
}
out
}
///| The Wi-Fi name in a saved connection's GetSettings reply (a{sa{sv}}), "" if it isn't Wi-Fi.
pub fn settings_ssid(v : DValue) -> String {
let groups = dict_map(v)
match groups.get("802-11-wireless") {
Some(w) => dict_map(w).get("ssid").map(x => x.bytes_text()).unwrap_or("")
None => ""
}
}
// ---- turning NetworkManager's objects into what the panel shows ----
///| An access point we could connect to.
pub(all) struct NmAp {
path : String
ssid : String
signal : Int
flags : Int
wpa : Int
rsn : Int
} derive(Eq, Debug)
///| What NetworkManager's state means for the panel.
pub(all) struct NmView {
status : NetStatus
networks : Array[WifiNetwork]
/// The Wi-Fi device ("" for none), its state and the reason for it.
wifi_dev : String
wifi_state : Int
wifi_reason : Int
/// The strongest access point for each network name.
aps : Map[String, NmAp]
}
///|
fn prop(
objs : Map[String, Map[String, Map[String, DValue]]],
path : String,
iface : String,
name : String,
) -> DValue? {
objs.get(path).bind(o => o.get(iface)).bind(p => p.get(name))
}
///| Build the view from the manager's properties (`root`), the managed objects and the saved
/// connections' Wi-Fi names (settings path -> name).
pub fn nm_view(
root : Map[String, DValue],
objs : Map[String, Map[String, Map[String, DValue]]],
saved : Map[String, String],
) -> NmView {
let wifi_on = as_bool(root.get("WirelessEnabled"))
let wwan_on = as_bool(root.get("WwanEnabled"))
let networking = root.get("NetworkingEnabled").map(x => as_bool(Some(x))).unwrap_or(true)
let nm_state = as_int(root.get("State"))
// The Wi-Fi device: the first one, preferring one that is in use.
let mut wifi_dev = ""
for path, ifaces in objs {
if as_int(ifaces.get(dev_iface).bind(d => d.get("DeviceType"))) == dev_type_wifi {
let busy = as_str(prop(objs, path, dev_iface, "ActiveConnection")) != "/" &&
as_str(prop(objs, path, dev_iface, "ActiveConnection")) != ""
if wifi_dev == "" || busy {
wifi_dev = path
}
}
}
let ap_of = fn(path : String) -> NmAp {
{
path,
ssid: prop(objs, path, ap_iface, "Ssid").map(x => x.bytes_text()).unwrap_or(""),
signal: as_int(prop(objs, path, ap_iface, "Strength")),
flags: as_int(prop(objs, path, ap_iface, "Flags")),
wpa: as_int(prop(objs, path, ap_iface, "WpaFlags")),
rsn: as_int(prop(objs, path, ap_iface, "RsnFlags")),
}
}
let active_ap = as_str(prop(objs, wifi_dev, wifi_iface, "ActiveAccessPoint"))
let active = if active_ap != "" && active_ap != "/" { Some(ap_of(active_ap)) } else { None }
// Networks in range: one entry per name, its strongest access point.
let aps : Map[String, NmAp] = {}
for p in as_paths(prop(objs, wifi_dev, wifi_iface, "AccessPoints")) {
let ap = ap_of(p)
if ap.ssid == "" {
continue // hidden networks
}
match aps.get(ap.ssid) {
Some(o) if o.signal >= ap.signal => ()
_ => aps.set(ap.ssid, ap)
}
}
let saved_names : Map[String, Bool] = {}
for _, n in saved {
if n != "" {
saved_names.set(n, true)
}
}
let active_ssid = match active {
Some(a) => a.ssid
None => ""
}
let networks : Array[WifiNetwork] = []
for name, ap in aps {
networks.push({
ssid: name,
signal: ap.signal,
secured: (ap.flags & 1) != 0 || ap.wpa != 0 || ap.rsn != 0,
active: name == active_ssid,
saved: saved_names.contains(name),
})
}
networks.sort_by((a, b) => if a.active != b.active {
if a.active { -1 } else { 1 }
} else if a.signal != b.signal {
b.signal - a.signal
} else {
a.ssid.compare(b.ssid)
})
// The connection the default route goes through.
let primary = as_str(root.get("PrimaryConnection"))
let mut state = NetState::Offline
let mut name = ""
let mut signal = 0
if networking && primary != "" && primary != "/" {
let devs = as_paths(prop(objs, primary, active_iface, "Devices"))
let dtype = match devs {
[d, ..] => as_int(prop(objs, d, dev_iface, "DeviceType"))
[] => 0
}
let ctype = as_str(prop(objs, primary, active_iface, "Type"))
if dtype == dev_type_wifi || ctype == "802-11-wireless" {
state = Wifi
match active {
Some(a) => {
name = a.ssid
signal = a.signal
}
None => name = as_str(prop(objs, primary, active_iface, "Id"))
}
} else {
state = Wired
name = as_str(prop(objs, primary, active_iface, "Id"))
}
}
// Activating (NM_STATE_CONNECTING, or a connection on its way) while nothing else is up.
if state == Offline && networking {
let activating = as_str(root.get("ActivatingConnection"))
if nm_state == 40 || (activating != "" && activating != "/") {
state = Connecting
name = as_str(prop(objs, activating, active_iface, "Id"))
}
}
let (wstate, wreason) = match prop(objs, wifi_dev, dev_iface, "StateReason") {
Some(Struct([U32(s), U32(r)])) => (s.reinterpret_as_int(), r.reinterpret_as_int())
_ => (as_int(prop(objs, wifi_dev, dev_iface, "State")), 0)
}
{
status: {
state,
name,
signal,
message: "",
wifi_enabled: wifi_on,
airplane: !wifi_on && !wwan_on,
managed: true,
has_wifi: wifi_dev != "",
},
networks: if wifi_on && wifi_dev != "" { networks } else { [] },
wifi_dev,
wifi_state: wstate,
wifi_reason: wreason,
aps,
}
}
///| The 802-11-wireless-security settings for a new connection to `ap`: Ok(None) for an open
/// network, Err(why) for one we can't set up here.
pub fn security_for(ap : NmAp, password : String) -> Result[DValue?, String] {
let ap_psk = 0x100
let ap_8021x = 0x200
let ap_sae = 0x400
let km = ap.wpa | ap.rsn
if km == 0 && (ap.flags & 1) == 0 {
return Ok(None)
}
if km == 0 {
return Err("WEP networks aren't supported")
}
if (km & (ap_psk | ap_sae)) == 0 && (km & ap_8021x) != 0 {
return Err("Enterprise (802.1X) networks aren't supported yet")
}
if password == "" {
return Err("A password is needed")
}
let key_mgmt = if (km & ap_psk) == 0 && (km & ap_sae) != 0 { "sae" } else { "wpa-psk" }
Ok(Some(dict("v", [("key-mgmt", Variant(Str(key_mgmt))), ("psk", Variant(Str(password)))])))
}
// ---- the backend ----
///| Talks to NetworkManager.
pub struct NmBackend {
bus : DBus
mut root : Map[String, DValue]
mut objs : Map[String, Map[String, Map[String, DValue]]]
/// Saved connection path -> its Wi-Fi name ("" for other kinds, or while it is being read).
saved : Map[String, String]
mut view : NmView
mut next_refresh : UInt64
mut inflight : Int
mut message : String
mut message_until : UInt64
/// A connection being made: the network, until when we watch it, and whether the device got
/// on its way (so a later disconnected state means it failed).
mut pending : String
mut pending_until : UInt64
mut pending_seen : Bool
mut now : UInt64
mut gone : Bool
}
///| How often to re-read NetworkManager.
let refresh_ms : UInt64 = 2000UL
///| Connect to NetworkManager on the system bus; None when it isn't running.
pub fn NmBackend::connect() -> NmBackend? {
let bus = match DBus::open(system_bus_path()) {
Some(b) => b
None => return None
}
// Is NetworkManager there at all? (A bus without it would only give errors.)
let has = bus.call_sync(
DMessage::call(
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", [
Str(nm_name),
],
),
1000,
)
match has.map(m => m.body) {
Some([Bool(true), ..]) => ()
_ => {
bus.close()
return None
}
}
Some({
bus,
root: {},
objs: {},
saved: {},
view: nm_view({}, {}, {}),
next_refresh: 0UL,
inflight: 0,
message: "",
message_until: 0UL,
pending: "",
pending_until: 0UL,
pending_seen: false,
now: 0UL,
gone: false,
})
}
///|
fn NmBackend::say(self : NmBackend, s : String) -> Unit {
self.message = s
self.message_until = self.now + 8000UL
}
///| Turn an error reply into something to show.
fn nm_error(m : DMessage) -> String {
let n = m.error_name
if n.has_suffix("PermissionDenied") || n.has_suffix("AccessDenied") {
"Not allowed: " + m.error_text()
} else {
m.error_text()
}
}
///|
fn NmBackend::nm_call(
self : NmBackend,
path : String,
iface : String,
meth : String,
args : Array[DValue],
on_ok? : (DMessage) -> Unit = _ => (),
) -> Unit {
ignore(
self.bus.call(DMessage::call(nm_name, path, iface, meth, args), on_reply=m => if m.mtype ==
error_reply {
if m.error_name == "org.freedesktop.DBus.Error.ServiceUnknown" ||
m.error_name == "org.freedesktop.DBus.Error.NameHasNoOwner" {
self.gone = true
} else {
self.say(nm_error(m))
}
} else {
on_ok(m)
}),
)
}
///| Ask for fresh state.
fn NmBackend::refresh(self : NmBackend) -> Unit {
self.inflight = 2
let done = fn() {
self.inflight = self.inflight - 1
if self.inflight <= 0 {
self.recompute()
}
}
ignore(
self.bus.call(
DMessage::call(nm_name, nm_path, props_iface, "GetAll", [Str(nm_name)]),
on_reply=m => {
match (m.mtype, m.body) {
(2, [d, ..]) => self.root = dict_map(d)
_ =>
if m.error_name.has_prefix("org.freedesktop.DBus.Error.ServiceUnknown") ||
m.error_name.has_prefix("org.freedesktop.DBus.Error.NameHasNoOwner") {
self.gone = true
}
}
done()
},
),
)
ignore(
self.bus.call(
DMessage::call(
nm_name, "/org/freedesktop", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", [],
),
on_reply=m => {
match (m.mtype, m.body) {
(2, [o, ..]) => self.objs = objects_map(o)
_ => ()
}
done()
},
),
)
}
///| Recompute the view, read the names of newly seen saved connections, and follow a connection
/// being made.
fn NmBackend::recompute(self : NmBackend) -> Unit {
// Saved connections: forget deleted ones, read new ones.
let present : Map[String, Bool] = {}
for path, ifaces in self.objs {
if ifaces.contains(setting_iface) {
present.set(path, true)
if !self.saved.contains(path) {
self.saved.set(path, "")
self.nm_call(path, setting_iface, "GetSettings", [], on_ok=m => match m.body {
[s, ..] => {
self.saved.set(path, settings_ssid(s))
self.view = nm_view(self.root, self.objs, self.saved)
}
_ => ()
})
}
}
}
let gone_paths = self.saved.keys().filter(p => !present.contains(p)).collect()
for p in gone_paths {
self.saved.remove(p)
}
self.view = nm_view(self.root, self.objs, self.saved)
if self.pending != "" {
let v = self.view
if v.status.state == Wifi && v.status.name == self.pending {
self.say("Connected to " + self.pending)
self.pending = ""
} else if v.wifi_state > dev_state_disconnected && v.wifi_state < dev_state_activated {
self.pending_seen = true
} else if self.pending_seen &&
(v.wifi_state == dev_state_failed || v.wifi_state <= dev_state_disconnected) {
self.say(
"Couldn't connect to " +
self.pending +
(if v.wifi_reason == reason_no_secrets { ": wrong password?" } else { "" }),
)
self.pending = ""
} else if self.now > self.pending_until {
self.say("Couldn't connect to " + self.pending)
self.pending = ""
}
}
}
///|
pub impl NetBackend for NmBackend with tick(self, now) {
self.now = now
self.bus.pump()
if !self.bus.alive {
self.gone = true
return
}
if self.inflight <= 0 && now >= self.next_refresh {
self.next_refresh = now + (if self.pending != "" { 1000UL } else { refresh_ms })
self.refresh()
}
if self.message != "" && now > self.message_until && self.pending == "" {
self.message = ""
}
}
///|
pub impl NetBackend for NmBackend with status(self) {
let s = self.view.status
let msg = if self.pending != "" && self.message == "" {
"Connecting to " + self.pending + "..."
} else {
self.message
}
{ ..s, message: msg }
}
///|
pub impl NetBackend for NmBackend with networks(self) {
self.view.networks
}
///|
pub impl NetBackend for NmBackend with close(self) {
self.bus.close()
}
///|
pub impl NetBackend for NmBackend with alive(self) {
!self.gone && self.bus.alive
}
///|
fn NmBackend::set_prop(self : NmBackend, name : String, v : DValue) -> Unit {
self.nm_call(nm_path, props_iface, "Set", [Str(nm_name), Str(name), Variant(v)])
}
///|
pub impl NetBackend for NmBackend with act(self, a) {
let dev = self.view.wifi_dev
self.next_refresh = self.now + 300UL // show the outcome soon
match a {
Scan =>
if dev != "" {
// Scanning too often is refused; that isn't worth a message.
ignore(self.bus.call(DMessage::call(nm_name, dev, wifi_iface, "RequestScan", [dict("v", [])])))
}
Disconnect =>
if dev != "" {
self.pending = ""
self.nm_call(dev, dev_iface, "Disconnect", [])
}
SetWifi(on) => self.set_prop("WirelessEnabled", Bool(on))
SetAirplane(on) => {
self.set_prop("WirelessEnabled", Bool(!on))
self.set_prop("WwanEnabled", Bool(!on))
}
Connect(ssid, password) => {
if dev == "" {
self.say("No Wi-Fi device")
return
}
let saved = self.saved.iter().filter(e => e.1 == ssid).map(e => e.0).collect()
let start = fn() {
self.pending = ssid
self.pending_seen = false
self.pending_until = self.now + 45000UL
self.message = ""
}
if saved.length() > 0 && password == "" {
start()
self.nm_call(nm_path, nm_name, "ActivateConnection", [Path(saved[0]), Path(dev), Path("/")])
return
}
match self.view.aps.get(ssid) {
None => self.say(ssid + " is out of range")
Some(ap) =>
match security_for(ap, password) {
Err(why) => self.say(why)
Ok(sec) => {
let groups = [("802-11-wireless", dict("v", [("ssid", Variant(byte_array(ssid)))]))]
match sec {
Some(s) => groups.push(("802-11-wireless-security", s))
None => ()
}
start()
self.nm_call(nm_path, nm_name, "AddAndActivateConnection", [
dict("a{sv}", groups),
Path(dev),
Path(ap.path),
])
}
}
}
}
Forget(ssid) =>
for path, name in self.saved {
if name == ssid {
self.nm_call(path, setting_iface, "Delete", [], on_ok=_ => self.say("Forgot " + ssid))
}
}
}
}