Network module: Wi-Fi and wired status, connect to Wi-Fi networks, Wi-Fi and airplane switches
CI / test (push) Failing after 18s

- 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
This commit is contained in:
Claude committed 2026-11-25 20:02:36 +00:00
1 parent 88915842c2
commit 1f4b686087
43 files changed
+4101 -32

No files matched your search

+818
View File
@@ -0,0 +1,818 @@
///| A minimal D-Bus client: the wire format (marshalling, messages) and a connection to the system
/// bus over the compositor's own socket calls (@sys.unix_connect / sendmsg / recvmsg / poll_read),
/// so it needs nothing new from either host. Enough for NetworkManager (nm.mbt): method calls and
/// their replies, no signals, no fd passing. Calls are asynchronous: `call` sends, `pump` reads what
/// has arrived without blocking and runs each reply's handler.
///| A D-Bus value. Arrays carry their element signature (needed to marshal an empty one); a dict
/// is an array of `Entry`.
pub(all) enum DValue {
Byte(Int)
Bool(Bool)
I32(Int)
U32(UInt)
I64(Int64)
U64(UInt64)
F64(Double)
Str(String)
Path(String)
Sig(String)
Fd(Int)
Arr(String, Array[DValue])
Struct(Array[DValue])
Entry(DValue, DValue)
Variant(DValue)
} derive(Eq, Debug)
///| The signature of one value.
pub fn DValue::sig(self : DValue) -> String {
match self {
Byte(_) => "y"
Bool(_) => "b"
I32(_) => "i"
U32(_) => "u"
I64(_) => "x"
U64(_) => "t"
F64(_) => "d"
Str(_) => "s"
Path(_) => "o"
Sig(_) => "g"
Fd(_) => "h"
Arr(e, _) => "a" + e
Struct(fs) => {
let sb = StringBuilder::new()
sb.write_char('(')
for f in fs {
sb.write_string(f.sig())
}
sb.write_char(')')
sb.to_string()
}
Entry(k, v) => "{" + k.sig() + v.sig() + "}"
Variant(_) => "v"
}
}
///| A string-keyed dict (a{s?}) from pairs; `vsig` is the value signature.
pub fn dict(vsig : String, pairs : Array[(String, DValue)]) -> DValue {
Arr("{s" + vsig + "}", pairs.map(p => Entry(Str(p.0), p.1)))
}
///| Bytes (ay) from a string's UTF-8.
pub fn byte_array(s : String) -> DValue {
let b = utf8_bytes(s)
let items : Array[DValue] = []
for i = 0; i < b.length(); i = i + 1 {
items.push(Byte(b[i].to_int()))
}
Arr("y", items)
}
///| The string an `ay` holds (lossy UTF-8), "" for anything else.
pub fn DValue::bytes_text(self : DValue) -> String {
match self {
Arr("y", items) => {
let b : Array[Byte] = []
for it in items {
if it is Byte(x) {
b.push(x.to_byte())
}
}
@utf8.decode_lossy(Bytes::from_array(b))
}
_ => ""
}
}
///|
fn utf8_bytes(s : String) -> Bytes {
@utf8.encode(s)
}
///| Alignment of the type starting with `c`.
fn align_of(c : Char) -> Int {
match c {
'y' | 'g' | 'v' => 1
'n' | 'q' => 2
'x' | 't' | 'd' | '(' | '{' => 8
_ => 4
}
}
// ---- marshalling ----
///|
priv struct Writer {
buf : Array[Byte]
}
///|
fn Writer::pad(self : Writer, n : Int) -> Unit {
while self.buf.length() % n != 0 {
self.buf.push(b'\x00')
}
}
///|
fn Writer::u8(self : Writer, v : Int) -> Unit {
self.buf.push((v & 0xFF).to_byte())
}
///|
fn Writer::u32(self : Writer, v : Int) -> Unit {
self.pad(4)
for k = 0; k < 4; k = k + 1 {
self.buf.push(((v >> (8 * k)) & 0xFF).to_byte())
}
}
///|
fn Writer::u64(self : Writer, v : UInt64) -> Unit {
self.pad(8)
for k = 0; k < 8; k = k + 1 {
self.buf.push(((v >> (8 * k)) & 0xFFUL).to_byte())
}
}
///|
fn Writer::raw(self : Writer, b : Bytes) -> Unit {
for i = 0; i < b.length(); i = i + 1 {
self.buf.push(b[i])
}
}
///|
fn Writer::value(self : Writer, v : DValue) -> Unit {
match v {
Byte(x) => self.u8(x)
Bool(b) => self.u32(if b { 1 } else { 0 })
I32(x) => self.u32(x)
U32(x) => self.u32(x.reinterpret_as_int())
Fd(x) => self.u32(x)
I64(x) => self.u64(x.reinterpret_as_uint64())
U64(x) => self.u64(x)
F64(d) => self.u64(d.reinterpret_as_uint64())
Str(s) | Path(s) => {
let b = utf8_bytes(s)
self.u32(b.length())
self.raw(b)
self.u8(0)
}
Sig(s) => {
let b = utf8_bytes(s)
self.u8(b.length())
self.raw(b)
self.u8(0)
}
Arr(esig, items) => {
self.pad(4)
let at = self.buf.length()
self.u32(0)
let mut first = 'y'
for c in esig {
first = c
break
}
self.pad(align_of(first))
let start = self.buf.length()
for it in items {
self.value(it)
}
let n = self.buf.length() - start
for k = 0; k < 4; k = k + 1 {
self.buf[at + k] = ((n >> (8 * k)) & 0xFF).to_byte()
}
}
Struct(fs) => {
self.pad(8)
for f in fs {
self.value(f)
}
}
Entry(k, x) => {
self.pad(8)
self.value(k)
self.value(x)
}
Variant(inner) => {
self.value(Sig(inner.sig()))
self.value(inner)
}
}
}
///| Message types.
pub let method_call : Int = 1
///|
pub let method_return : Int = 2
///|
pub let error_reply : Int = 3
///|
pub let signal_msg : Int = 4
///| A message, received or to send.
pub(all) struct DMessage {
mtype : Int
serial : Int
reply_serial : Int
path : String
iface : String
meth : String
error_name : String
dest : String
sig : String
body : Array[DValue]
} derive(Debug)
///| A method call to send.
pub fn DMessage::call(
dest : String,
path : String,
iface : String,
meth : String,
args : Array[DValue],
) -> DMessage {
let sb = StringBuilder::new()
for a in args {
sb.write_string(a.sig())
}
{
mtype: method_call,
serial: 0,
reply_serial: 0,
path,
iface,
meth,
error_name: "",
dest,
sig: sb.to_string(),
body: args,
}
}
///| The wire bytes of `m` with serial `serial` (little-endian).
pub fn DMessage::encode(self : DMessage, serial : Int) -> Bytes {
let body = { buf: [] }
for a in self.body {
body.value(a)
}
let fields : Array[DValue] = []
let field = fn(code : Int, v : DValue) { fields.push(Struct([Byte(code), Variant(v)])) }
if self.path != "" {
field(1, Path(self.path))
}
if self.iface != "" {
field(2, Str(self.iface))
}
if self.meth != "" {
field(3, Str(self.meth))
}
if self.error_name != "" {
field(4, Str(self.error_name))
}
if self.reply_serial != 0 {
field(5, U32(self.reply_serial.reinterpret_as_uint()))
}
if self.dest != "" {
field(6, Str(self.dest))
}
if self.sig != "" {
field(8, Sig(self.sig))
}
let w = { buf: [] }
w.u8('l'.to_int())
w.u8(self.mtype)
w.u8(0)
w.u8(1)
w.u32(body.buf.length())
w.u32(serial)
w.value(Arr("(yv)", fields))
w.pad(8)
for b in body.buf {
w.buf.push(b)
}
Bytes::from_array(w.buf)
}
// ---- unmarshalling ----
///| Reads values out of a whole message (offsets are from its start, as alignment is).
priv struct Reader {
data : Array[Byte]
mut pos : Int
le : Bool
mut bad : Bool
}
///|
fn Reader::align(self : Reader, n : Int) -> Unit {
while self.pos % n != 0 {
self.pos = self.pos + 1
}
if self.pos > self.data.length() {
self.bad = true
}
}
///|
fn Reader::bytes(self : Reader, n : Int) -> Int {
if n < 0 || self.pos + n > self.data.length() {
self.bad = true
self.pos = self.data.length()
return -1
}
let at = self.pos
self.pos = self.pos + n
at
}
///|
fn Reader::u8(self : Reader) -> Int {
let at = self.bytes(1)
if at < 0 { 0 } else { self.data[at].to_int() }
}
///|
fn Reader::uint(self : Reader, size : Int) -> UInt64 {
self.align(size)
let at = self.bytes(size)
if at < 0 {
return 0UL
}
let mut v = 0UL
for k = 0; k < size; k = k + 1 {
let b = self.data[if self.le { at + k } else { at + size - 1 - k }].to_uint64()
v = v | (b << (8 * k))
}
v
}
///|
fn Reader::u32(self : Reader) -> Int {
self.uint(4).to_int()
}
///|
fn Reader::text(self : Reader, n : Int) -> String {
let at = self.bytes(n)
if at < 0 {
return ""
}
let b = Array::makei(n, i => self.data[at + i])
ignore(self.bytes(1)) // the NUL
@utf8.decode_lossy(Bytes::from_array(b))
}
///| The end of the single complete type starting at `i` in `sig` (exclusive), or -1.
fn type_end(sig : Array[Char], i : Int) -> Int {
if i >= sig.length() {
return -1
}
match sig[i] {
'a' => type_end(sig, i + 1)
'(' | '{' => {
let close = if sig[i] == '(' { ')' } else { '}' }
let mut j = i + 1
while j < sig.length() && sig[j] != close {
j = type_end(sig, j)
if j < 0 {
return -1
}
}
if j < sig.length() { j + 1 } else { -1 }
}
_ => i + 1
}
}
///|
fn chars(s : String) -> Array[Char] {
let a : Array[Char] = []
for c in s {
a.push(c)
}
a
}
///|
fn sub(sig : Array[Char], from : Int, to : Int) -> String {
String::from_array(sig[from:to].to_owned())
}
///| Read the values of signature `sig` (a sequence of complete types).
fn Reader::values(self : Reader, sig : Array[Char], from : Int, to : Int) -> Array[DValue] {
let out : Array[DValue] = []
let mut i = from
while i < to && !self.bad {
let e = type_end(sig, i)
if e < 0 || e > to {
self.bad = true
break
}
out.push(self.value(sig, i))
i = e
}
out
}
///| Read one value of the complete type at `sig[i]`.
fn Reader::value(self : Reader, sig : Array[Char], i : Int) -> DValue {
if self.bad {
return Byte(0)
}
match sig[i] {
'y' => Byte(self.u8())
'b' => Bool(self.u32() != 0)
'n' => {
let v = self.uint(2).to_int()
I32(if v >= 0x8000 { v - 0x10000 } else { v })
}
'q' => U32(self.uint(2).to_uint())
'i' => I32(self.u32())
'u' => U32(self.uint(4).to_uint())
'h' => Fd(self.u32())
'x' => I64(self.uint(8).reinterpret_as_int64())
't' => U64(self.uint(8))
'd' => F64(self.uint(8).reinterpret_as_double())
's' => Str(self.text(self.u32()))
'o' => Path(self.text(self.u32()))
'g' => Sig(self.text(self.u8()))
'v' => {
let s = chars(self.text(self.u8()))
if s.length() == 0 || type_end(s, 0) != s.length() {
self.bad = true
return Byte(0)
}
Variant(self.value(s, 0))
}
'a' => {
let n = self.u32()
let e = type_end(sig, i + 1)
if e < 0 {
self.bad = true
return Byte(0)
}
self.align(align_of(sig[i + 1]))
let end = self.pos + n
if n < 0 || end > self.data.length() {
self.bad = true
return Byte(0)
}
let items : Array[DValue] = []
while self.pos < end && !self.bad {
items.push(self.value(sig, i + 1))
}
Arr(sub(sig, i + 1, e), items)
}
'(' => {
self.align(8)
let e = type_end(sig, i)
if e < 0 {
self.bad = true
return Byte(0)
}
Struct(self.values(sig, i + 1, e - 1))
}
'{' => {
self.align(8)
let ke = type_end(sig, i + 1)
if ke < 0 || type_end(sig, ke) < 0 {
self.bad = true
return Byte(0)
}
let k = self.value(sig, i + 1)
let v = self.value(sig, ke)
Entry(k, v)
}
_ => {
self.bad = true
Byte(0)
}
}
}
///| Total length of the message at the start of `buf`, or -1 when its fixed header isn't in yet.
pub fn message_length(buf : Array[Byte]) -> Int {
if buf.length() < 16 {
return -1
}
let le = buf[0] == b'l'
let rd = fn(at : Int) {
let mut v = 0
for k = 0; k < 4; k = k + 1 {
let b = buf[if le { at + k } else { at + 3 - k }].to_int()
v = v | (b << (8 * k))
}
v
}
let body = rd(4)
let fields = rd(12)
let hdr = (16 + fields + 7) / 8 * 8
hdr + body
}
///| Parse one whole message; None when it is malformed.
pub fn decode(data : Array[Byte]) -> DMessage? {
if data.length() < 16 {
return None
}
let r = { data, pos: 12, le: data[0] == b'l', bad: false }
let mtype = data[1].to_int()
let serial = {
r.pos = 8
let s = r.u32()
r.pos = 12
s
}
let fields = r.value(chars("a(yv)"), 0)
r.align(8)
if r.bad {
return None
}
let mut path = ""
let mut iface = ""
let mut meth = ""
let mut error_name = ""
let mut reply_serial = 0
let mut dest = ""
let mut sig = ""
if fields is Arr(_, items) {
for f in items {
match f {
Struct([Byte(code), Variant(v)]) =>
match (code, v) {
(1, Path(s)) => path = s
(2, Str(s)) => iface = s
(3, Str(s)) => meth = s
(4, Str(s)) => error_name = s
(5, U32(n)) => reply_serial = n.reinterpret_as_int()
(6, Str(s)) => dest = s
(8, Sig(s)) => sig = s
_ => ()
}
_ => ()
}
}
}
let sc = chars(sig)
let body = r.values(sc, 0, sc.length())
if r.bad {
return None
}
Some({ mtype, serial, reply_serial, path, iface, meth, error_name, dest, sig, body })
}
// ---- the connection ----
///| A connection to a message bus.
pub struct DBus {
fd : Int
inbuf : Array[Byte]
mut serial : Int
pending : Map[Int, (DMessage) -> Unit]
mut alive : Bool
}
///| The system bus socket: $DBUS_SYSTEM_BUS_ADDRESS when it is a unix:path= address, else the
/// standard path.
pub fn system_bus_path() -> String {
let addr = @sys.getenv("DBUS_SYSTEM_BUS_ADDRESS")
let pre = "unix:path="
if addr.has_prefix(pre) {
let rest = addr[pre.length():].to_string()
match rest.find(",") {
Some(i) => rest[:i].to_string()
None => rest
}
} else {
"/run/dbus/system_bus_socket"
}
}
///| Our uid, from /proc/self/status, as the decimal string EXTERNAL authentication sends ("" if
/// unknown).
fn own_uid() -> String {
let st = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status"))
for line in st.split("\n") {
if line.has_prefix("Uid:") {
for f in line[4:].split("\t") {
let t = f.trim(chars=" ").to_string()
if t != "" {
return t
}
}
}
}
""
}
///| Hex of `s`'s ASCII bytes (how SASL EXTERNAL sends the uid).
fn hex_ascii(s : String) -> String {
let digits = "0123456789abcdef"
let sb = StringBuilder::new()
for c in s {
let v = c.to_int()
sb.write_char(digits.get_char(v >> 4).unwrap_or('0'))
sb.write_char(digits.get_char(v & 15).unwrap_or('0'))
}
sb.to_string()
}
///|
fn send_text(fd : Int, s : String) -> Bool {
let b = utf8_bytes(s)
@sys.sendmsg_fd(fd, b, -1) == b.length()
}
///| Read into `into` until it holds a "\r\n"-terminated line; the line (without it), with the
/// bytes after it left in `into`. None on timeout or a closed socket.
fn read_line(fd : Int, into : Array[Byte], timeout_ms : Int) -> String? {
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
let deadline = @sys.monotonic_ms() + timeout_ms.to_uint64()
while true {
for i = 0; i + 1 < into.length(); i = i + 1 {
if into[i] == b'\r' && into[i + 1] == b'\n' {
let line = @utf8.decode_lossy(Bytes::from_array(into[:i].to_array()))
let rest = into[i + 2:].to_array()
into.clear()
into.append(rest)
return Some(line)
}
}
let now = @sys.monotonic_ms()
if now >= deadline || @sys.poll_read(fd, (deadline - now).to_int()) <= 0 {
return None
}
let (n, extra) = @sys.recvmsg_fd(fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n <= 0 {
return None
}
for i = 0; i < n; i = i + 1 {
into.push(buf[i])
}
}
None
}
///| Connect to the bus at `path`, authenticate (EXTERNAL) and say Hello. None when there is no
/// bus or it refuses us. Blocks for at most about a second.
pub fn DBus::open(path : String) -> DBus? {
let fd = @sys.unix_connect(path)
if fd < 0 {
return None
}
let fail = fn() {
@sys.close_fd(fd)
None
}
let inbuf : Array[Byte] = []
let uid = own_uid()
// The leading NUL is the credentials byte every client sends first.
let auth = if uid == "" {
"\u{0}AUTH EXTERNAL\r\n"
} else {
"\u{0}AUTH EXTERNAL " + hex_ascii(uid) + "\r\n"
}
if !send_text(fd, auth) {
return fail()
}
let mut ok = false
for _round = 0; _round < 3 && !ok; _round = _round + 1 {
match read_line(fd, inbuf, 1000) {
Some(l) if l.has_prefix("OK") => ok = true
Some(l) if l.has_prefix("DATA") => if !send_text(fd, "DATA\r\n") { return fail() }
_ => return fail()
}
}
if !ok || !send_text(fd, "BEGIN\r\n") {
return fail()
}
let bus = { fd, inbuf, serial: 0, pending: {}, alive: true }
let hello = bus.call_sync(
DMessage::call(
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello", [],
),
1000,
)
match hello {
Some(m) if m.mtype == method_return => Some(bus)
_ => {
bus.close()
None
}
}
}
///|
pub fn DBus::close(self : DBus) -> Unit {
if self.alive {
self.alive = false
@sys.close_fd(self.fd)
}
self.pending.clear()
}
///| Send `m`; `on_reply` runs from a later `pump` with its reply (or error). The serial.
pub fn DBus::call(self : DBus, m : DMessage, on_reply? : (DMessage) -> Unit) -> Int {
if !self.alive {
return 0
}
self.serial = self.serial + 1
let s = self.serial
let b = m.encode(s)
if @sys.sendmsg_fd(self.fd, b, -1) != b.length() {
self.close()
return 0
}
match on_reply {
Some(f) => self.pending.set(s, f)
None => ()
}
s
}
///| Read whatever has arrived (waiting up to `timeout_ms`) and run reply handlers. Signals and
/// calls to us are dropped.
pub fn DBus::pump(self : DBus, timeout_ms? : Int = 0) -> Unit {
if !self.alive {
return
}
let buf : FixedArray[Byte] = FixedArray::make(65536, b'\x00')
let mut wait = timeout_ms
while self.alive && @sys.poll_read(self.fd, wait) > 0 {
wait = 0
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break
}
if n <= 0 {
self.close()
return
}
for i = 0; i < n; i = i + 1 {
self.inbuf.push(buf[i])
}
}
self.dispatch()
}
///| Run the handlers of the whole messages in the buffer.
fn DBus::dispatch(self : DBus) -> Unit {
while true {
let len = message_length(self.inbuf)
if len < 0 || len > self.inbuf.length() {
break
}
let msg = self.inbuf[:len].to_array()
let rest = self.inbuf[len:].to_array()
self.inbuf.clear()
self.inbuf.append(rest)
match decode(msg) {
Some(m) if m.mtype == method_return || m.mtype == error_reply =>
match self.pending.get(m.reply_serial) {
Some(f) => {
self.pending.remove(m.reply_serial)
f(m)
}
None => ()
}
_ => ()
}
}
}
///| Send `m` and wait up to `timeout_ms` for its reply.
pub fn DBus::call_sync(self : DBus, m : DMessage, timeout_ms : Int) -> DMessage? {
let got : Ref[DMessage?] = { val: None }
let s = self.call(m, on_reply=r => got.val = Some(r))
if s == 0 {
return None
}
let deadline = @sys.monotonic_ms() + timeout_ms.to_uint64()
while got.val is None && self.alive {
let now = @sys.monotonic_ms()
if now >= deadline {
self.pending.remove(s)
break
}
self.pump(timeout_ms=(deadline - now).to_int())
}
got.val
}
///| The first string in an error reply's body (its message), else the error name.
pub fn DMessage::error_text(self : DMessage) -> String {
match self.body {
[Str(s), ..] => s
_ => self.error_name
}
}
+47
View File
@@ -0,0 +1,47 @@
///| A backend for tests: it serves whatever status and network list it is given and records the
/// actions it receives (switching Wi-Fi off empties the list, as NetworkManager's would).
pub(all) struct FakeNet {
mut status : NetStatus
mut networks : Array[WifiNetwork]
actions : Array[NetAction]
mut ticks : Int
}
///|
pub fn FakeNet::new(status : NetStatus, networks : Array[WifiNetwork]) -> FakeNet {
{ status, networks, actions: [], ticks: 0 }
}
///|
pub impl NetBackend for FakeNet with tick(self, _now) {
self.ticks = self.ticks + 1
}
///|
pub impl NetBackend for FakeNet with status(self) {
self.status
}
///|
pub impl NetBackend for FakeNet with networks(self) {
if self.status.wifi_enabled {
self.networks
} else {
[]
}
}
///|
pub impl NetBackend for FakeNet with act(self, a) {
self.actions.push(a)
match a {
SetWifi(on) => self.status = { ..self.status, wifi_enabled: on }
SetAirplane(on) => self.status = { ..self.status, airplane: on, wifi_enabled: !on }
_ => ()
}
}
///|
pub impl NetBackend for FakeNet with alive(_self) {
true
}
+188
View File
@@ -0,0 +1,188 @@
///| Network status and control for the `network` capability (the network panel module). The shell
/// owns a `NetService`; it picks a backend: NetworkManager over D-Bus (nm.mbt) when it answers,
/// else read-only status from /sys/class/net and /proc/net (sysfs.mbt), trying NetworkManager
/// again now and then. Tests plug in their own backend.
///| How the machine is connected now.
pub(all) enum NetState {
Offline
Wired
Wifi
Connecting
} derive(Eq, Debug)
///| The number the capability uses: 0 offline, 1 wired, 2 Wi-Fi, 3 connecting.
pub fn NetState::code(self : NetState) -> Int {
match self {
Offline => 0
Wired => 1
Wifi => 2
Connecting => 3
}
}
///| What the panel shows.
pub(all) struct NetStatus {
state : NetState
/// The Wi-Fi network's name, else the connection's (e.g. "Wired connection 1"); "" offline.
name : String
/// Signal of the Wi-Fi network in use, 0..100 (0 when not on Wi-Fi).
signal : Int
/// Something to tell the user: an action's outcome or why it failed ("" for nothing).
message : String
wifi_enabled : Bool
airplane : Bool
/// The network can be changed from here (NetworkManager answers); false: status only.
managed : Bool
/// There is a Wi-Fi device.
has_wifi : Bool
} derive(Eq, Debug)
///|
pub fn NetStatus::offline() -> NetStatus {
{
state: Offline,
name: "",
signal: 0,
message: "",
wifi_enabled: false,
airplane: false,
managed: false,
has_wifi: false,
}
}
///| A Wi-Fi network in range.
pub(all) struct WifiNetwork {
ssid : String
signal : Int
secured : Bool
/// The one in use.
active : Bool
/// There is a saved connection for it (no password needed).
saved : Bool
} derive(Eq, Debug)
///| What the module can ask for.
pub(all) enum NetAction {
Scan
Disconnect
SetWifi(Bool)
SetAirplane(Bool)
/// Connect to the network named `ssid`: a saved one as saved, a new one with `password`
/// ("" for an open network).
Connect(String, String)
/// Delete the saved connections for a network.
Forget(String)
} derive(Eq, Debug)
///| The capability's action codes (wit/host/plasmoids.wit `network-request`): 0 scan,
/// 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode off/on, 6 connect, 7 forget.
pub fn NetAction::from_code(code : Int, ssid : String, password : String) -> NetAction? {
match code {
0 => Some(Scan)
1 => Some(Disconnect)
2 => Some(SetWifi(false))
3 => Some(SetWifi(true))
4 => Some(SetAirplane(false))
5 => Some(SetAirplane(true))
6 => if ssid == "" { None } else { Some(Connect(ssid, password)) }
7 => if ssid == "" { None } else { Some(Forget(ssid)) }
_ => None
}
}
///| Where status comes from and where actions go.
pub(open) trait NetBackend {
/// Called every frame with monotonic ms: read replies, refresh when due.
tick(Self, UInt64) -> Unit
status(Self) -> NetStatus
networks(Self) -> Array[WifiNetwork]
act(Self, NetAction) -> Unit
/// False once the backend stopped working (NetworkManager went away).
alive(Self) -> Bool
/// Let go of what it holds (a bus connection).
close(Self) -> Unit = _
}
///|
impl NetBackend with close(_self) {
()
}
///| The network service the shell holds.
pub struct NetService {
mut backend : &NetBackend
mut on_nm : Bool
mut retry_at : UInt64
/// Look for NetworkManager (false with a test backend).
probe : Bool
}
///| How often to look for NetworkManager again while it isn't there.
let nm_retry_ms : UInt64 = 30000UL
///| NetworkManager if it answers, else /sys status.
pub fn NetService::new() -> NetService {
match NmBackend::connect() {
Some(nm) => { backend: nm as &NetBackend, on_nm: true, retry_at: 0UL, probe: true }
None => {
backend: SysfsBackend::new() as &NetBackend,
on_nm: false,
retry_at: @sys.monotonic_ms() + nm_retry_ms,
probe: true,
}
}
}
///| A service over `b` (tests).
pub fn NetService::with_backend(b : &NetBackend) -> NetService {
{ backend: b, on_nm: false, retry_at: 0UL, probe: false }
}
///|
pub fn NetService::tick(self : NetService, now : UInt64) -> Unit {
self.backend.tick(now)
if self.on_nm && !self.backend.alive() {
self.backend.close()
self.backend = SysfsBackend::new() as &NetBackend
self.on_nm = false
self.retry_at = now + nm_retry_ms
self.backend.tick(now)
} else if !self.on_nm && self.probe && now >= self.retry_at {
self.retry_at = now + nm_retry_ms
match NmBackend::connect() {
Some(nm) => {
self.backend = nm as &NetBackend
self.on_nm = true
self.backend.tick(now)
}
None => ()
}
}
}
///| Whether this service looks for NetworkManager (false with a test backend).
pub fn NetService::probe(self : NetService) -> Bool {
self.probe
}
///| Let go of the bus connection.
pub fn NetService::close(self : NetService) -> Unit {
self.backend.close()
}
///|
pub fn NetService::status(self : NetService) -> NetStatus {
self.backend.status()
}
///|
pub fn NetService::networks(self : NetService) -> Array[WifiNetwork] {
self.backend.networks()
}
///|
pub fn NetService::act(self : NetService, a : NetAction) -> Unit {
self.backend.act(a)
}
+9
View File
@@ -0,0 +1,9 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/encoding/utf8" @utf8,
"chandra/desktop/compositor/sys" @sys,
}
supported_targets = "+native+wasm"
warnings = "-44"
+388
View File
@@ -0,0 +1,388 @@
///|
fn hello() -> DMessage {
DMessage::call(
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello", [],
)
}
///|
test "a Hello call has the well-known wire bytes" {
let b = hello().encode(1)
// l, method call, no flags, version 1; empty body; serial 1; 109 bytes of header fields.
let head = [
b'l', b'\x01', b'\x00', b'\x01', b'\x00', b'\x00', b'\x00', b'\x00', b'\x01', b'\x00', b'\x00',
b'\x00', b'\x6d', b'\x00', b'\x00', b'\x00',
]
for i = 0; i < head.length(); i = i + 1 {
assert_eq(b[i], head[i])
}
assert_eq(b.length(), 128)
assert_eq(message_length(b.to_array()), 128)
assert_eq(message_length(b.to_array()[:15].to_array()), -1)
}
///|
test "calls round-trip through the wire format" {
let args = [
dict("a{sv}", [
("802-11-wireless", dict("v", [("ssid", Variant(byte_array("Café")))])),
(
"802-11-wireless-security",
dict("v", [("key-mgmt", Variant(Str("wpa-psk"))), ("psk", Variant(Str("hunter22")))]),
),
]),
Path("/org/freedesktop/NetworkManager/Devices/3"),
Path("/"),
Struct([U32(100U), U32(7U)]),
I64(-5L),
Bool(true),
Arr("s", []),
]
let m = DMessage::call(
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager",
"AddAndActivateConnection", args,
)
assert_eq(m.sig, "a{sa{sv}}oo(uu)xbas")
let back = decode(m.encode(42).to_array()).unwrap()
assert_eq(back.serial, 42)
assert_eq(back.meth, "AddAndActivateConnection")
assert_eq(back.dest, "org.freedesktop.NetworkManager")
assert_eq(back.sig, m.sig)
assert_eq(back.body, args)
let groups = dict_map(back.body[0])
assert_eq(dict_map(groups.get("802-11-wireless").unwrap()).get("ssid").unwrap().bytes_text(), "Café")
assert_eq(settings_ssid(back.body[0]), "Café")
}
///|
test "malformed messages are refused" {
let b = hello().encode(1).to_array()
b[12] = b'\xff' // a header field array longer than the message
assert_eq(decode(b) is None, true)
assert_eq(decode([b'l', b'\x01']) is None, true)
}
///| A NetworkManager as GetManagedObjects / GetAll would describe it: Wi-Fi connected to "Home",
/// two more networks in range (one twice), an Ethernet device unplugged, one saved connection.
fn sample_objects() -> (Map[String, DValue], Map[String, Map[String, Map[String, DValue]]]) {
let nm = "/org/freedesktop/NetworkManager"
let obj = fn(ifaces : Array[(String, Array[(String, DValue)])]) {
Arr("{sa{sv}}", ifaces.map(i => Entry(Str(i.0), dict("v", i.1.map(p => (p.0, Variant(p.1)))))))
}
let ap = fn(ssid : String, strength : Int, flags : Int, wpa : Int, rsn : Int) {
obj([
(
ap_iface,
[
("Ssid", byte_array(ssid)),
("Strength", Byte(strength)),
("Flags", U32(flags.reinterpret_as_uint())),
("WpaFlags", U32(wpa.reinterpret_as_uint())),
("RsnFlags", U32(rsn.reinterpret_as_uint())),
],
),
])
}
let objects = Arr("{oa{sa{sv}}}", [
Entry(
Path(nm + "/Devices/1"),
obj([
(
dev_iface,
[
("DeviceType", U32(1U)),
("State", U32(20U)),
("Interface", Str("enp3s0")),
("ActiveConnection", Path("/")),
],
),
]),
),
Entry(
Path(nm + "/Devices/2"),
obj([
(
dev_iface,
[
("DeviceType", U32(2U)),
("State", U32(100U)),
("StateReason", Struct([U32(100U), U32(0U)])),
("Interface", Str("wlan0")),
("ActiveConnection", Path(nm + "/ActiveConnection/5")),
],
),
(
wifi_iface,
[
("ActiveAccessPoint", Path(nm + "/AccessPoint/10")),
(
"AccessPoints",
Arr("o", [
Path(nm + "/AccessPoint/10"),
Path(nm + "/AccessPoint/11"),
Path(nm + "/AccessPoint/12"),
Path(nm + "/AccessPoint/13"),
Path(nm + "/AccessPoint/14"),
]),
),
],
),
]),
),
Entry(Path(nm + "/AccessPoint/10"), ap("Home", 72, 1, 0, 0x188)),
Entry(Path(nm + "/AccessPoint/11"), ap("Cafe", 40, 0, 0, 0)),
Entry(Path(nm + "/AccessPoint/12"), ap("Office", 30, 1, 0, 0x188)),
Entry(Path(nm + "/AccessPoint/13"), ap("Office", 55, 1, 0, 0x188)),
Entry(Path(nm + "/AccessPoint/14"), ap("", 90, 1, 0, 0x188)),
Entry(
Path(nm + "/ActiveConnection/5"),
obj([
(
active_iface,
[
("Id", Str("Home")),
("Type", Str("802-11-wireless")),
("Devices", Arr("o", [Path(nm + "/Devices/2")])),
],
),
]),
),
Entry(Path(nm + "/Settings/1"), obj([(setting_iface, [("Unsaved", Bool(false))])])),
])
let root = dict("v", [
("State", Variant(U32(70U))),
("PrimaryConnection", Variant(Path(nm + "/ActiveConnection/5"))),
("ActivatingConnection", Variant(Path("/"))),
("WirelessEnabled", Variant(Bool(true))),
("WwanEnabled", Variant(Bool(true))),
("NetworkingEnabled", Variant(Bool(true))),
])
// Through the wire and back, as a reply would arrive.
let reply = fn(v : DValue) {
let m = { ..DMessage::call("", "", "", "", [v]), mtype: method_return, reply_serial: 3 }
decode(m.encode(9).to_array()).unwrap().body[0]
}
(dict_map(reply(root)), objects_map(reply(objects)))
}
///|
test "NetworkManager's objects become the panel's status and network list" {
let (root, objs) = sample_objects()
let saved = { "/org/freedesktop/NetworkManager/Settings/1": "Office" }
let v = nm_view(root, objs, saved)
assert_eq(v.status.state, Wifi)
assert_eq(v.status.name, "Home")
assert_eq(v.status.signal, 72)
assert_eq(v.status.wifi_enabled, true)
assert_eq(v.status.airplane, false)
assert_eq(v.status.has_wifi, true)
assert_eq(v.wifi_dev, "/org/freedesktop/NetworkManager/Devices/2")
assert_eq(v.wifi_state, 100)
// The one in use first, then by signal; the strongest "Office"; no hidden network.
assert_eq(v.networks.map(n => n.ssid), ["Home", "Office", "Cafe"])
assert_eq(v.networks[0].active, true)
assert_eq(v.networks[1], { ssid: "Office", signal: 55, secured: true, active: false, saved: true })
assert_eq(v.networks[2].secured, false)
assert_eq(v.aps.get("Office").unwrap().path, "/org/freedesktop/NetworkManager/AccessPoint/13")
}
///|
test "wired, connecting, Wi-Fi off and airplane mode" {
let (root, objs) = sample_objects()
let nm = "/org/freedesktop/NetworkManager"
// Ethernet becomes the primary connection.
let conn : Map[String, Map[String, DValue]] = {}
conn.set(active_iface, {
"Id": Str("Wired connection 1"),
"Type": Str("802-3-ethernet"),
"Devices": Arr("o", [Path(nm + "/Devices/1")]),
})
objs.set(nm + "/ActiveConnection/6", conn)
root.set("PrimaryConnection", Path(nm + "/ActiveConnection/6"))
let v = nm_view(root, objs, {})
assert_eq(v.status.state, Wired)
assert_eq(v.status.name, "Wired connection 1")
assert_eq(v.status.signal, 0)
// Nothing up yet, a connection on its way.
root.set("PrimaryConnection", Path("/"))
root.set("State", U32(40U))
root.set("ActivatingConnection", Path(nm + "/ActiveConnection/6"))
let c = nm_view(root, objs, {}).status
assert_eq(c.state, Connecting)
assert_eq(c.name, "Wired connection 1")
// Wi-Fi off: no list; airplane mode is Wi-Fi and mobile broadband both off.
root.set("WirelessEnabled", Bool(false))
let off = nm_view(root, objs, {})
assert_eq(off.networks.length(), 0)
assert_eq(off.status.wifi_enabled, false)
assert_eq(off.status.airplane, false)
root.set("WwanEnabled", Bool(false))
assert_eq(nm_view(root, objs, {}).status.airplane, true)
// Networking off altogether.
root.set("NetworkingEnabled", Bool(false))
assert_eq(nm_view(root, objs, {}).status.state, Offline)
}
///|
test "security settings for new networks" {
let ap = fn(flags : Int, wpa : Int, rsn : Int) {
{ path: "/ap", ssid: "x", signal: 50, flags, wpa, rsn }
}
assert_eq(security_for(ap(0, 0, 0), ""), Ok(None))
assert_eq(security_for(ap(1, 0, 0), "k"), Err("WEP networks aren't supported"))
assert_eq(security_for(ap(1, 0, 0x200), "k"), Err("Enterprise (802.1X) networks aren't supported yet"))
assert_eq(security_for(ap(1, 0, 0x188), ""), Err("A password is needed"))
let psk = security_for(ap(1, 0, 0x188), "secret").unwrap().unwrap()
assert_eq(dict_map(psk).get("key-mgmt"), Some(Str("wpa-psk")))
assert_eq(dict_map(psk).get("psk"), Some(Str("secret")))
let sae = security_for(ap(1, 0, 0x400), "secret").unwrap().unwrap()
assert_eq(dict_map(sae).get("key-mgmt"), Some(Str("sae")))
}
///|
test "status from /proc/net and /sys/class/net" {
let dev = "Inter-| Receive | Transmit\n face |bytes packets errs\n lo: 100 1 0\n eth0: 5 1 0\nwlan0: 7 1 0\ndocker0: 1 1 0\n"
assert_eq(proc_net_dev_names(dev), ["lo", "eth0", "wlan0", "docker0"])
let wl = "Inter-| sta-| Quality | Discarded packets\n face | tus | link level noise | nwid crypt\nwlan0: 0000 49. -61. -256 0 0\n"
assert_eq(proc_net_wireless(wl), { "wlan0": 70 })
let eth = { name: "eth0", wireless: false, physical: true, up: false, quality: -1 }
let wlan = { name: "wlan0", wireless: true, physical: true, up: true, quality: 70 }
let docker = { name: "docker0", wireless: false, physical: false, up: true, quality: -1 }
let s = sysfs_status([eth, wlan, docker])
assert_eq(s.state, Wifi)
assert_eq(s.name, "wlan0")
assert_eq(s.signal, 70)
assert_eq(s.managed, false)
assert_eq(s.has_wifi, true)
assert_eq(sysfs_status([{ ..eth, up: true }, wlan]).state, Wired)
assert_eq(sysfs_status([eth, docker]).state, Offline)
}
///|
test "action codes" {
assert_eq(NetAction::from_code(0, "", ""), Some(Scan))
assert_eq(NetAction::from_code(3, "", ""), Some(SetWifi(true)))
assert_eq(NetAction::from_code(5, "", ""), Some(SetAirplane(true)))
assert_eq(NetAction::from_code(6, "Home", "pw"), Some(Connect("Home", "pw")))
assert_eq(NetAction::from_code(6, "", "pw"), None)
assert_eq(NetAction::from_code(7, "Home", ""), Some(Forget("Home")))
assert_eq(NetAction::from_code(9, "", ""), None)
}
///| Call a python-dbusmock method (scripts/test-network-dbus.sh runs the mock NetworkManager).
fn mock_call(bus : DBus, path : String, meth : String, args : Array[DValue]) -> DMessage {
let r = bus.call_sync(DMessage::call(nm_name, path, "org.freedesktop.DBus.Mock", meth, args), 2000).unwrap()
if r.mtype == error_reply {
abort(meth + ": " + r.error_text())
}
r
}
///| Tick `nm` until `ok` holds (or 5 s pass).
fn settle(nm : NmBackend, ok : (NmBackend) -> Bool) -> Bool {
let until = @sys.monotonic_ms() + 5000UL
while @sys.monotonic_ms() < until {
NetBackend::tick(nm, @sys.monotonic_ms())
if nm.inflight <= 0 && ok(nm) {
return true
}
@sys.sleep_ms(20)
}
false
}
///| Against a real bus: auth, Hello, framing, and the NetworkManager calls, with python-dbusmock's
/// NetworkManager template standing in. Skipped unless CHANDRA_NM_E2E=1 (the script sets it).
test "NetworkManager over a real bus (python-dbusmock)" {
if @sys.getenv("CHANDRA_NM_E2E") != "1" {
return
}
let bus = DBus::open(system_bus_path()).unwrap()
let mock = "/org/freedesktop"
let s = fn(m : DMessage) {
match m.body {
[Str(x), ..] => x
_ => abort("no path")
}
}
let dev = s(mock_call(bus, mock, "AddWiFiDevice", [Str("wifi0"), Str("wlan0"), I32(100)]))
let ap1 = s(
mock_call(bus, mock, "AddAccessPoint", [
Str(dev),
Str("ap1"),
Str("Home"),
Str("00:11:22:33:44:55"),
U32(2U),
U32(2437U),
U32(54000U),
Byte(72),
U32(0x100U),
]),
)
ignore(
mock_call(bus, mock, "AddAccessPoint", [
Str(dev),
Str("ap2"),
Str("Cafe"),
Str("00:11:22:33:44:66"),
U32(2U),
U32(2412U),
U32(54000U),
Byte(40),
U32(0U),
]),
)
let con = s(mock_call(bus, mock, "AddWiFiConnection", [Str(dev), Str("con1"), Str("Home"), Str("wpa-psk")]))
let act = s(
mock_call(bus, mock, "AddActiveConnection", [Arr("s", [Str(dev)]), Str(con), Str(ap1), Str("act1"), U32(2U)]),
)
ignore(mock_call(bus, nm_path, "AddProperty", [Str(nm_name), Str("PrimaryConnection"), Variant(Path(act))]))
ignore(mock_call(bus, dev, "AddProperty", [Str(wifi_iface), Str("ActiveAccessPoint"), Variant(Path(ap1))]))
ignore(mock_call(bus, mock, "SetProperty", [Str(nm_path), Str(nm_name), Str("WwanEnabled"), Variant(Bool(true))]))
let nm = NmBackend::connect().unwrap()
assert_eq(
settle(nm, n => NetBackend::status(n).state == Wifi && NetBackend::networks(n).length() == 2 && NetBackend::networks(n)[0].saved),
true,
)
assert_eq(NetBackend::status(nm).name, "Home")
assert_eq(NetBackend::status(nm).signal, 72)
assert_eq(NetBackend::status(nm).managed, true)
assert_eq(
NetBackend::networks(nm),
[
{ ssid: "Home", signal: 72, secured: true, active: true, saved: true },
{ ssid: "Cafe", signal: 40, secured: false, active: false, saved: false },
],
)
// Wi-Fi off and on again; airplane mode.
NetBackend::act(nm, SetWifi(false))
assert_eq(settle(nm, n => !NetBackend::status(n).wifi_enabled && NetBackend::networks(n).length() == 0), true)
assert_eq(NetBackend::status(nm).airplane, false)
NetBackend::act(nm, SetAirplane(true))
assert_eq(settle(nm, n => NetBackend::status(n).airplane), true)
NetBackend::act(nm, SetAirplane(false))
assert_eq(settle(nm, n => NetBackend::status(n).wifi_enabled && !NetBackend::status(n).airplane), true)
// A new open network: AddAndActivateConnection makes a saved connection for it.
NetBackend::act(nm, Scan)
NetBackend::act(nm, Connect("Cafe", ""))
assert_eq(settle(nm, n => NetBackend::networks(n).iter().any(w => w.ssid == "Cafe" && w.saved)), true)
// A secured one with no password is refused here, before NetworkManager.
ignore(mock_call(bus, mock, "AddAccessPoint", [
Str(dev),
Str("ap3"),
Str("Office"),
Str("00:11:22:33:44:77"),
U32(2U),
U32(5180U),
U32(54000U),
Byte(30),
U32(0x100U),
]))
assert_eq(settle(nm, n => NetBackend::networks(n).length() == 3), true)
NetBackend::act(nm, Connect("Office", ""))
assert_eq(NetBackend::status(nm).message, "A password is needed")
// Forget deletes the saved connection.
NetBackend::act(nm, Forget("Cafe"))
assert_eq(settle(nm, n => NetBackend::networks(n).iter().any(w => w.ssid == "Cafe" && !w.saved)), true)
bus.close()
}
+639
View File
@@ -0,0 +1,639 @@
///| 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))
}
}
}
}
+146
View File
@@ -0,0 +1,146 @@
///| Read-only status without NetworkManager: interfaces from /proc/net/dev, whether each is a
/// physical Ethernet or Wi-Fi device and up from /sys/class/net/<if>, and Wi-Fi link quality from
/// /proc/net/wireless. The network's name isn't there (that needs nl80211), so the interface's
/// name stands in. Nothing can be changed.
///| One interface's state, as read.
pub(all) struct IfState {
name : String
wireless : Bool
physical : Bool
up : Bool
/// Link quality 0..100 (Wi-Fi), -1 unknown.
quality : Int
} derive(Eq, Debug)
///|
fn read_text(path : String) -> String {
@utf8.decode_lossy(@sys.read_proc_bytes(path)).trim(chars=" \n\t").to_string()
}
///| Interface names in /proc/net/dev.
pub fn proc_net_dev_names(text : String) -> Array[String] {
let out : Array[String] = []
for line in text.split("\n") {
match line.find(":") {
Some(i) => {
let name = line[:i].trim(chars=" ").to_string()
if name != "" && !name.contains("|") {
out.push(name)
}
}
None => ()
}
}
out
}
///| Link quality per interface from /proc/net/wireless ("wlan0: 0000 54. -56. -256 ..."),
/// scaled from the usual 0..70 to 0..100.
pub fn proc_net_wireless(text : String) -> Map[String, Int] {
let out : Map[String, Int] = {}
for line in text.split("\n") {
match line.find(":") {
Some(i) => {
let name = line[:i].trim(chars=" ").to_string()
let rest = line[i + 1:].to_string()
let fs = rest.split(" ").filter(f => f != "").map(f => f.to_string()).collect()
if name != "" && fs.length() >= 2 && !name.contains("|") {
let mut q = 0
for c in fs[1] {
if c >= '0' && c <= '9' {
q = q * 10 + (c.to_int() - 48)
} else {
break
}
}
out.set(name, if q >= 70 { 100 } else { q * 100 / 70 })
}
}
None => ()
}
}
out
}
///| What the interfaces say about the connection: Ethernet up wins, then Wi-Fi up.
pub fn sysfs_status(ifs : Array[IfState]) -> NetStatus {
let has_wifi = ifs.iter().any(i => i.wireless)
let base = { ..NetStatus::offline(), has_wifi, wifi_enabled: has_wifi }
for i in ifs {
if i.up && i.physical && !i.wireless {
return { ..base, state: Wired, name: i.name }
}
}
for i in ifs {
if i.up && i.wireless {
return { ..base, state: Wifi, name: i.name, signal: if i.quality < 0 { 0 } else { i.quality } }
}
}
base
}
///| The read-only backend.
pub struct SysfsBackend {
mut status : NetStatus
mut next : UInt64
}
///|
pub fn SysfsBackend::new() -> SysfsBackend {
{ status: NetStatus::offline(), next: 0UL }
}
///| Read the interfaces now.
pub fn read_interfaces() -> Array[IfState] {
let quality = proc_net_wireless(read_text("/proc/net/wireless"))
let out : Array[IfState] = []
for name in proc_net_dev_names(read_text("/proc/net/dev")) {
if name == "lo" {
continue
}
let base = "/sys/class/net/" + name
let wireless = quality.contains(name) || read_text(base + "/phy80211/name") != ""
// Physical devices have a device link (veth, bridges, docker0, tun don't).
let physical = read_text(base + "/device/uevent") != ""
let oper = read_text(base + "/operstate")
let carrier = read_text(base + "/carrier")
out.push({
name,
wireless,
physical,
up: oper == "up" || (oper == "unknown" && carrier == "1"),
quality: quality.get(name).unwrap_or(-1),
})
}
out
}
///|
pub impl NetBackend for SysfsBackend with tick(self, now) {
if now >= self.next {
self.next = now + 3000UL
let s = sysfs_status(read_interfaces())
self.status = { ..s, message: "NetworkManager isn't running: status only" }
}
}
///|
pub impl NetBackend for SysfsBackend with status(self) {
self.status
}
///|
pub impl NetBackend for SysfsBackend with networks(_self) {
[]
}
///|
pub impl NetBackend for SysfsBackend with act(_self, _a) {
()
}
///|
pub impl NetBackend for SysfsBackend with alive(_self) {
true
}