///| 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 } }