1// A D-Bus client (PLAN.md, F6c): a connection to a bus over a2// Unix socket, authenticated as the process's user (SASL EXTERNAL), which3// sends method calls, replies, errors and signals and receives them, for4// the accessibility bus and the desktop portal and any program using the5// session or system bus. Calls can wait for their reply; everything else6// arrives through `receive`, which never blocks, the connection's socket7// polled beside a program's own (`fd`).8//9// ```text10// import pkg::alloy::dbus;11//12// fn main() -> i32 {13// var bus = if (Connection::session() is ::Some |move c|) move c else {14// return 1;15// };16// var names = Vector<Value>::empty();17// if (bus.call(&"org.freedesktop.DBus", &"/org/freedesktop/DBus", &"org.freedesktop.DBus",18// &"ListNames", &"", Vector<Value>::empty()) is ::Some |&reply|) {19// ...20// }21// bus.dispose();22// return 0;23// }24// ```25//26// ## How it was built27//28// Notes kept from each stage as it was finished, the sizes and numbers29// of their day; what changed since is in REVIEW.md and the history.30//31// Built in F6c, for AT-SPI and the desktop portal: see pkg::alloy::window's notes.3233import std::string;34import std::vector;35import std::option;36import std::ffi;37import std::dispose;38import std::time;39import std::text;4041import wire;4243extern socket(domain: i32, kind: i32, protocol: i32) -> i32;44extern connect(fd: i32, address: c_pointer, length: u32) -> i32;45extern read(fd: i32, buffer: c_pointer, count: c_size) -> i64;46extern write(fd: i32, buffer: c_pointer, count: c_size) -> i64;47extern close(fd: i32) -> i32;48extern poll(fds: c_pointer, count: u64, timeout: i32) -> i32;49extern getuid() -> u32;50extern getenv(name: c_string) -> c_pointer;5152// A value D-Bus carries. A dict is an array of two-field structs.53exp type Value = enum {54 Byte: u8,55 Boolean: bool,56 Int16: i16,57 Uint16: u16,58 Int32: i32,59 Uint32: u32,60 Int64: i64,61 Uint64: u64,62 Double: f64,63 Text: String,64 ObjectPath: String,65 Signature: String,66 Array: Vector<Value>,67 Struct: Vector<Value>,68 Variant: *Value,69};7071exp fn Value::text(text: &[u8]) -> Value => Value::Text(String::from(&text));7273exp fn Value::path(text: &[u8]) -> Value => Value::ObjectPath(String::from(&text));7475exp fn Value::variant(value: Value) -> Value {76 var inner: *var Value = new move value;77 return Value::Variant(move inner);78}7980// A dict entry, as a two-field struct.81exp fn Value::entry(key: Value, value: Value) -> Value {82 var fields = Vector<Value>::empty();83 fields.push(move key);84 fields.push(move value);85 return Value::Struct(move fields);86}8788// The text a string, object path or signature holds, or empty.89exp fn as_text(self v: &Value) -> &[u8] {90 return match (v) {91 ::Text |&t| &t.view();92 ::ObjectPath |&t| &t.view();93 ::Signature |&t| &t.view();94 ::Variant |&inner| &inner.as_text();95 else &"";96 };97}9899// The number an integer holds, or 0.100exp fn as_integer(self v: &Value) -> i64 {101 return match (v) {102 ::Byte |n| n to i64;103 ::Boolean |b| if (b) 1 else 0;104 ::Int16 |n| n to i64;105 ::Uint16 |n| n to i64;106 ::Int32 |n| n to i64;107 ::Uint32 |n| n to i64;108 ::Int64 |n| n;109 ::Uint64 |n| n as i64;110 ::Variant |&inner| inner.as_integer();111 else 0;112 };113}114115// The items of an array, or none.116exp fn items(self v: &Value) -> &[Value] {117 return match (v) {118 ::Array |&items| &items.view();119 ::Struct |&fields| &fields.view();120 ::Variant |&inner| &inner.items();121 else &[];122 };123}124125// The value under the key in a dict (`a{sv}`), a variant's own value.126exp fn lookup(self v: &Value, key: &[u8]) -> Option<&Value> {127 for (v.items()) |&entry| {128 const pair = &entry.items();129 if (pair.length() == 2 && pair[0].as_text() == key) {130 if (pair[1] is ::Variant |&inner|) {131 return ::Some(&inner);132 }133 return ::Some(&pair[1]);134 }135 }136 return ::None;137}138139// A message's kind, by its number in the header.140exp type MessageKind = enum : u8 {141 Call = 1,142 Return = 2,143 Error = 3,144 Signal = 4,145};146147exp type Message = struct {148 exp kind: MessageKind,149 exp flags: u8, // 1: no reply expected150 exp serial: u32,151 exp path: String,152 exp interface_name: String,153 exp member: String,154 exp error_name: String,155 exp reply_serial: u32,156 exp destination: String,157 exp sender: String,158 exp signature: String,159 exp body: Vector<Value>,160};161162exp fn Message::empty() -> Message => Message {163 .kind = MessageKind::Call,164 .flags = 0,165 .serial = 0,166 .path = String::empty(),167 .interface_name = String::empty(),168 .member = String::empty(),169 .error_name = String::empty(),170 .reply_serial = 0,171 .destination = String::empty(),172 .sender = String::empty(),173 .signature = String::empty(),174 .body = Vector<Value>::empty()175};176177// A method call.178exp fn Message::call(179 destination: &[u8],180 path: &[u8],181 interface_name: &[u8],182 member: &[u8],183 signature: &[u8],184 body: Vector<Value>185) -> Message {186 var m = Message::empty();187 m.destination = String::from(&destination);188 m.path = String::from(&path);189 m.interface_name = String::from(&interface_name);190 m.member = String::from(&member);191 m.signature = String::from(&signature);192 m.body = move body;193 return move m;194}195196// A signal from the object.197exp fn Message::signal(198 path: &[u8],199 interface_name: &[u8],200 member: &[u8],201 signature: &[u8],202 body: Vector<Value>203) -> Message {204 var m = Message::call(&"", &path, &interface_name, &member, &signature, move body);205 m.kind = MessageKind::Signal;206 m.flags = 1;207 return move m;208}209210// The reply to a call.211exp fn reply(self call: &Message, signature: &[u8], body: Vector<Value>) -> Message {212 var m = Message::empty();213 m.kind = MessageKind::Return;214 m.flags = 1;215 m.reply_serial = call.serial;216 m.destination = copy call.sender;217 m.signature = String::from(&signature);218 m.body = move body;219 return move m;220}221222// An error answering a call.223exp fn error(self call: &Message, name: &[u8], text: &[u8]) -> Message {224 var body = Vector<Value>::empty();225 body.push(Value::text(&text));226 var m = call.reply(&"s", move body);227 m.kind = MessageKind::Error;228 m.error_name = String::from(&name);229 return move m;230}231232exp fn is_error(self m: &Message) -> bool => m.kind is ::Error;233234// A connection to a bus.235exp type Connection : Disposable = struct {236 pub fd: i32,237 pub serial: u32,238 exp unique_name: String, // the name the bus gave it239 pub input: Vector<u8>, // bytes read, not yet a whole message240 pub received: Vector<Message>, // whole messages not yet taken241};242243exp fn dispose(self c: &var Connection) {244 if (c.fd >= 0) {245 close(c.fd);246 c.fd = -1;247 }248}249250// The session bus, from DBUS_SESSION_BUS_ADDRESS; none without one.251exp fn Connection::session() -> Option<Connection> {252 const address = getenv(&"DBUS_SESSION_BUS_ADDRESS\0");253 if (address == 0) {254 return ::None;255 }256 return Connection::open(&address.c_text());257}258259// The bus at the address (`unix:path=...` or `unix:abstract=...`, the260// first of several that connects), authenticated and greeted.261exp fn Connection::open(address: &[u8]) -> Option<Connection> {262 var start: u64 = 0;263 while (start < address.length()) {264 const end = if (address.find_byte(';', start) is ::Some |e|) e else address.length();265 if (connect_to(&address[start..end]) is ::Some |move c|) {266 return ::Some(move c);267 }268 start = end + 1;269 }270 return ::None;271}272273fn connect_to(address: &[u8]) -> Option<Connection> {274 if (!address.starts_with(&"unix:")) {275 return ::None;276 }277 var path = String::empty();278 var abstract = false;279 var at: u64 = 5;280 while (at < address.length()) {281 const end = if (address.find_byte(',', at) is ::Some |e|) e else address.length();282 const part = &address[at..end];283 if (part.length() > 5 && part[..5] == "path=") {284 path = unescape(&part[5..]);285 } else if (part.length() > 9 && part[..9] == "abstract=") {286 path = unescape(&part[9..]);287 abstract = true;288 }289 at = end + 1;290 }291 if (path.length() == 0 || path.length() > 107) {292 return ::None;293 }294 // AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC295 const fd = socket(1, 0x80001, 0);296 if (fd < 0) {297 return ::None;298 }299 // sockaddr_un: the family, then the path (an abstract name after a NUL)300 var address_bytes: [u8 : 110] = [0 : 110];301 address_bytes[0] = 1;302 const offset: u64 = if (abstract) 3 else 2;303 address_bytes[offset..offset + path.length()] = path.view();304 const ending: u64 = if (abstract) 0 else 1;305 const length = (offset + path.length() + ending) to u32;306 if (connect(fd, c_pointer::of(&address_bytes[..]), length) != 0) {307 close(fd);308 return ::None;309 }310 var c = Connection {311 .fd = fd,312 .serial = 0,313 .unique_name = String::empty(),314 .input = Vector<u8>::empty(),315 .received = Vector<Message>::empty()316 };317 if (!c.authenticate()) {318 c.dispose();319 return ::None;320 }321 var hello = Message::call(322 &"org.freedesktop.DBus",323 &"/org/freedesktop/DBus",324 &"org.freedesktop.DBus",325 &"Hello",326 &"",327 Vector<Value>::empty()328 );329 if (c.call_message(move hello, 5000) is ::Some |&reply|) {330 if (reply.body.length() > 0) {331 c.unique_name = String::from(&reply.body.get(0).as_text());332 }333 }334 if (c.unique_name.length() == 0) {335 c.dispose();336 return ::None;337 }338 return ::Some(move c);339}340341// An address's value with its %xx escapes undone.342fn unescape(text: &[u8]) -> String {343 var out = String::empty();344 var k: u64 = 0;345 while (k < text.length()) {346 if (text[k] == '%' && k + 2 < text.length()) {347 out.push((hex(text[k + 1]) << 4) | hex(text[k + 2]));348 k += 3;349 } else {350 out.push(text[k]);351 k += 1;352 }353 }354 return move out;355}356357fn hex(c: u8) -> u8 {358 if (c >= '0' && c <= '9') {359 return c - '0';360 }361 if (c >= 'a' && c <= 'f') {362 return c - 'a' + 10;363 }364 return c - 'A' + 10;365}366367// SASL EXTERNAL as the process's user, its id in hexadecimal digits.368fn authenticate(self c: &var Connection) -> bool {369 var line = String::from(&"\0AUTH EXTERNAL ");370 const uid = f"{getuid()}";371 // each of the id's digits as two hexadecimal digits of its code372 const digits = "0123456789abcdef";373 for (uid.view()) |digit| {374 line.push(digits[(digit >> 4) to u64]);375 line.push(digits[(digit & 15) to u64]);376 }377 line.append(&"\r\n");378 if (!c.send_bytes(&line.view())) {379 return false;380 }381 const answer = c.read_line(5000);382 if (answer.length() < 2 || answer.view()[..2] != "OK") {383 return false;384 }385 return c.send_bytes(&"BEGIN\r\n");386}387388// A line the bus sent during authentication, without its CR LF.389fn read_line(self c: &var Connection, timeout: i32) -> String {390 var out = String::empty();391 var byte: [u8 : 1] = [0];392 while (true) {393 if (!c.wait_readable(timeout)) {394 return move out;395 }396 if (read(c.fd, c_pointer::of(&byte[..]), 1) != 1) {397 return move out;398 }399 if (byte[0] == '\n') {400 break;401 }402 if (byte[0] != '\r') {403 out.push(byte[0]);404 }405 }406 return move out;407}408409fn send_bytes(self c: &var Connection, bytes: &[u8]) -> bool {410 var at: u64 = 0;411 while (at < bytes.length()) {412 const written = write(c.fd, c_pointer::of(&bytes[at..]), (bytes.length() - at) to c_size);413 if (written <= 0) {414 return false;415 }416 at += written to u64;417 }418 return true;419}420421// Whether the socket can be read within the milliseconds (-1: forever).422fn wait_readable(self c: &Connection, timeout: i32) -> bool {423 // pollfd: the fd, POLLIN, then what came424 var fds: [u64 : 1] = [c.fd as u32 to u64 | (1 to u64 << 32)];425 return poll(c_pointer::of(&fds[..]), 1, timeout) > 0 && fds[0] >> 48 != 0;426}427428// The socket, for a loop to poll beside its own: when it is readable,429// `receive` takes what came.430exp fn fd(self c: &Connection) -> i32 => c.fd;431432// Sends the message, numbering it; its serial, none when it could not.433exp fn send(self c: &var Connection, message: Message) -> Option<u32> {434 if (c.fd < 0) {435 return ::None;436 }437 var m = move message;438 c.serial += 1;439 m.serial = c.serial;440 if (encode(&m) is ::Some |&bytes| && c.send_bytes(&bytes.view())) {441 return ::Some(m.serial);442 }443 return ::None;444}445446// Calls the method and waits up to 5 seconds for its reply (or error);447// what else arrives meanwhile waits for `receive`.448exp fn call(449 self c: &var Connection,450 destination: &[u8],451 path: &[u8],452 interface_name: &[u8],453 member: &[u8],454 signature: &[u8],455 body: Vector<Value>456) -> Option<Message> {457 return c.call_message(458 Message::call(&destination, &path, &interface_name, &member, &signature, move body),459 5000460 );461}462463exp fn call_message(self c: &var Connection, message: Message, timeout: i32) -> Option<Message> {464 const serial = if (c.send(move message) is ::Some |s|) s else {465 return ::None;466 };467 // a deadline, which other messages arriving meanwhile do not move468 const start = Instant::now();469 while (true) {470 for ([..c.received.length()]) |k| {471 const m = &c.received.get(k);472 if ((m.kind is ::Return || m.kind is ::Error) && m.reply_serial == serial) {473 return ::Some(c.received.remove(k));474 }475 }476 const left = timeout to f64 - start.elapsed().milliseconds();477 if (left <= 0.0) {478 return ::None;479 }480 c.wait_readable(if (left < 100.0) left to i32 + 1 else 100);481 if (!c.read_available()) {482 return ::None;483 }484 }485}486487// The next message received, never waiting; none when none came.488exp fn receive(self c: &var Connection) -> Option<Message> {489 if (c.received.length() == 0 && c.wait_readable(0)) {490 c.read_available();491 }492 return c.received.try_remove(0);493}494495// Whether messages wait to be taken, read already while waiting for a496// reply: a loop polling the socket would not see them.497exp fn has_received(self c: &Connection) -> bool => c.received.length() > 0;498499// Waits up to the milliseconds for a message.500exp fn wait(self c: &var Connection, timeout: i32) -> Option<Message> {501 if (c.received.length() == 0 && c.wait_readable(timeout)) {502 c.read_available();503 }504 return c.received.try_remove(0);505}506507// Reads what the socket has and splits whole messages off; false when508// the bus closed it.509fn read_available(self c: &var Connection) -> bool {510 var buffer: [u8 : 4096] = [0 : 4096];511 while (c.wait_readable(0)) {512 const count = read(c.fd, c_pointer::of(&buffer[..]), 4096);513 if (count <= 0) {514 close(c.fd);515 c.fd = -1;516 return false;517 }518 c.input.append(&buffer[..count to u64]);519 }520 while (message_length(&c.input.view()) is ::Some |length| && length <= c.input.length()) {521 if (decode(&c.input.view()[..length]) is ::Some |move m|) {522 c.received.push(move m);523 }524 var rest = Vector<u8>::from(&c.input.view()[length..]);525 c.input = move rest;526 }527 return true;528}529530// Asks the bus for the messages the match rule selects, as531// `type='signal',interface='org.freedesktop.portal.Request'`.532exp fn add_match(self c: &var Connection, rule: &[u8]) -> bool {533 var body = Vector<Value>::empty();534 body.push(Value::text(&rule));535 const reply = c.call(536 &"org.freedesktop.DBus",537 &"/org/freedesktop/DBus",538 &"org.freedesktop.DBus",539 &"AddMatch",540 &"s",541 move body542 );543 if (reply is ::Some |&r| && !r.is_error()) {544 return true;545 }546 return false;547}548549// Asks the bus for the well-known name; whether this connection owns it.550exp fn request_name(self c: &var Connection, name: &[u8]) -> bool {551 var body = Vector<Value>::empty();552 body.push(Value::text(&name));553 body.push(Value::Uint32(4)); // DBUS_NAME_FLAG_DO_NOT_QUEUE554 if (555 c.call(556 &"org.freedesktop.DBus",557 &"/org/freedesktop/DBus",558 &"org.freedesktop.DBus",559 &"RequestName",560 &"su",561 move body562 ) is ::Some |&r|563 ) {564 return r.body.length() > 0 && r.body.get(0).as_integer() == 1;565 }566 return false;567}568569// A property of an object, through org.freedesktop.DBus.Properties.570exp fn get_property(571 self c: &var Connection,572 destination: &[u8],573 path: &[u8],574 interface_name: &[u8],575 name: &[u8]576) -> Option<Value> {577 var body = Vector<Value>::empty();578 body.push(Value::text(&interface_name));579 body.push(Value::text(&name));580 if (581 c.call(582 &destination,583 &path,584 &"org.freedesktop.DBus.Properties",585 &"Get",586 &"ss",587 move body588 ) is ::Some |move r|589 ) {590 if (!r.is_error() && r.body.length() > 0) {591 var reply = move r;592 if (reply.body.try_remove(0) is ::Some |move v|) {593 if (v is ::Variant |&inner|) {594 return ::Some(copy inner);595 }596 return ::Some(move v);597 }598 }599 }600 return ::None;601}