AtlatestRepositorysigil-dbus
1# sigil-dbus
2
3`dbus-sensitive-dictionary-reply` takes a public setting name, a public field
4name and owned UTF-8 bytes. It returns one string secret in `a{sa{sv}}`, for
5example a NetworkManager SecretAgent reply. As with `dbus-sensitive-reply`,
6the input and final encoded frame are cleared after send, cancellation,
7validation failure or transport failure. The value is usable once. This
8does not clear runtime, kernel, daemon or caller-created copies.
9
10The receive transport clears its owned socket chunks and completed frames after
11decoding, including rejected frames, and clears an incomplete frame on close.
12String decoding also clears its temporary UTF-8 bytevector. Returned strings
13and bytevectors remain caller-owned; an agent receiving credentials in ordinary
14method arguments must clear those decoded values after inspecting them.
16A pure Sigil D-Bus client and object-service library. Requires public Sigil
170.23.1 on Unix. Uses Sigil's socket and cooperative scheduler APIs; there is
18no libdbus or sd-bus dependency and no native extension in this package.
20Version 0.1.3 adds reply sender pinning for unique destinations and optional
21exact success-signature validation.
23## Client
25```scheme
26(import (sigil dbus))
28(define connection (dbus-connect-session))
29(display
30 (dbus-call connection
31 "org.freedesktop.DBus" "/org/freedesktop/DBus"
32 "org.freedesktop.DBus" "ListNames" "" '()))
33(newline)
34(dbus-close! connection)
35```
37`dbus-connect-session` reads `DBUS_SESSION_BUS_ADDRESS`.
38`dbus-connect-system` reads `DBUS_SYSTEM_BUS_ADDRESS`, falling back to
39`unix:path=/var/run/dbus/system_bus_socket`. Both accept `address:`, `uid:`,
40`timeout-ms:` (default 25000), and `max-bytes:` (default 16 MiB).
41`dbus-connect address` accepts the other three options. All authenticate
42with SASL EXTERNAL and perform Hello before returning. The UID defaults to
43the result of the system `id -u` command; pass `uid:` to avoid that command.
44Connections are never automatically reconnected.
46Address lists and percent-escaped `unix:path=` addresses are supported.
47**Sigil 0.23.1 has no public abstract Unix socket connector.** An
48`unix:abstract=` entry produces a clear error and the next address is tried.
49Use a pathname address when configuring a bus. This is a known transport
50limitation, not transparent abstract-socket support.
52`dbus-call connection destination path interface member signature arguments`
53returns a list of output arguments, or a `dbus-error` value for a remote error
54or timeout. Its keyword options are `timeout-ms:`, `flags:` and `reply-signature:`. Transport or
55local validation failures raise exceptions. Check `dbus-error?`, then
56`dbus-error-name` and `dbus-error-message`. A timeout has the name
57`org.freedesktop.DBus.Error.NoReply`.
59For a security-sensitive call, resolve and authenticate the unique destination
60first, then pass `reply-signature:` to `dbus-call` or `dbus-call-async`. This
61requires a unique destination (or the bus daemon) and validates the exact
62successful-reply wire signature; a mismatch returns InvalidSignature. Calls to
63unique destinations and the bus daemon also pin the reply sender, even without
64this option. A foreign sender cannot complete them by matching a reply serial.
65Authenticated bus-daemon error replies still terminate the call. Calls to other
66well-known names retain their existing body-only behavior; they do not establish
67a persistent owner identity.
69Inside `(with-async ...)`, calls park only their calling fiber. For multiple
70outstanding calls, `dbus-call-async` takes the same arguments and returns a
71pending value; `dbus-await` waits for it. Replies are matched by serial, so
72completion order can differ from send order. `dbus-pending-ready?` reports
73completion after a pump/await. `dbus-pump! connection timeout-ms: 100` handles
74one incoming message and expires calls. `dbus-run!` pumps until closed.
75There is no hidden background reader: services and signal-only clients must
76run a pump, usually in `(go (dbus-run! connection))`. Call `dbus-close!` to
77release the socket and resolve outstanding calls as Disconnected.
79`dbus-connection-fd` returns the live native descriptor, or `#f` after close.
80The connection retains ownership: use it only for readiness waits, never
81read, write, or close it directly. After readiness, `dbus-pump!` with
82`timeout-ms: 0` processes one available frame without waiting; partial frames
83remain buffered for the next readiness notification. A caller with pending
84calls must also wake for their deadlines. Cancel a wait before closing its
85connection or reusing descriptors.
87## Export a service
89```scheme
90(import (sigil dbus) (sigil async))
92(with-async
93 (let ((connection (dbus-connect-session)))
94 (dbus-export! connection "/org/example/Greeter"
95 (list
96 (dbus-interface "org.example.Greeter"
97 methods:
98 (list (dbus-method "Greet" "s" "s"
99 (lambda (name) (list (string-append "Hello, " name)))))
100 properties:
101 (list (dbus-property "Version" "s" (lambda () "1.0"))))))
102 (unless (equal? 1 (dbus-request-name! connection "org.example.Greeter"))
103 (error "Service name is unavailable"))
104 (dbus-run! connection)))
105```
107Call it with:
109```sh
110dbus-send --session --print-reply --dest=org.example.Greeter \
111 /org/example/Greeter org.example.Greeter.Greet string:World
112busctl --user get-property org.example.Greeter /org/example/Greeter \
113 org.example.Greeter Version
114```
116`dbus-method name input-signature output-signature handler` passes decoded
117input arguments positionally. Return a list of output arguments, including
118`'()` for no output, or `(dbus-error "org.example.Error.Refused" "reason")`.
119Exceptions and invalid handler output become `org.freedesktop.DBus.Error.Failed`
120replies. Handlers may yield inside `with-async`. Exported methods require an
121explicit interface on incoming calls. The library suppresses replies to
122NO_REPLY_EXPECTED calls.
124`dbus-property name signature getter setter: setter` takes a zero-argument
125getter and optional one-argument setter. A missing getter creates a
126write-only property. A missing setter creates a read-only property. Setters
127may return a `dbus-error`; other return values are ignored. Successful
128Properties.Set emits PropertiesChanged using the getter's current value, or
129invalidates a write-only property. For application-side changes, call
130`dbus-properties-changed! connection path interface changed-alist
131invalidated: names`. Get, Set, GetAll, generated introspection XML, and
132Peer.Ping are provided automatically. `dbus-unexport! connection path` removes
133an object. `dbus-introspect connection path` returns its generated XML.
135Declare signals in `dbus-interface` with
136`signals: (list (dbus-signal "Changed" "u"))`. Send using
137`dbus-send-signal! connection path interface member signature arguments`,
138optionally with `destination:` for a unicast signal.
140## Names and signals
142`dbus-request-name! connection name flags: flags` returns the bus's numeric
143RequestName result (1 primary owner, 2 queued, 3 exists, 4 already owner), or
144a `dbus-error`. Default flags are `dbus-do-not-queue`. Add flag values
145`dbus-allow-replacement` (1), `dbus-replace-existing` (2), and
146`dbus-do-not-queue` (4) as needed. `dbus-release-name!` returns ReleaseName's
147numeric result. `dbus-owned-names` reflects NameAcquired/NameLost messages
148already processed by the pump; `dbus-unique-name` is set by Hello.
150```scheme
151(define subscription
152 (dbus-subscribe! connection
153 (list (cons 'sender "org.freedesktop.DBus")
154 (cons 'interface "org.freedesktop.DBus")
155 (cons 'member "NameOwnerChanged"))
156 (lambda (message) (display (dbus-message-body message)))))
157;; Pump the connection to receive callbacks, then:
158(dbus-unsubscribe! connection subscription)
159```
161Subscription keys are `sender`, `interface`, `member`, `path`, `destination`,
162and `arg0`. AddMatch/RemoveMatch are handled for you. Subscription setup accepts
163`timeout-ms:` for one total budget and `await:` for a cancelable pending-call
164waiter (default `dbus-await`). A failed setup removes possible late matches with
165no reply wait, using `cleanup-timeout-ms:` (default 10ms). Unsubscribe detaches
166the local callback immediately, even on failure; it accepts the same timeout
167and await options. With `wait?: #f`, it sends bounded no-reply removals instead
168of waiting for acknowledgments. Remote cleanup is best effort if the connection
169fails; closing it releases its remaining daemon matches. Well-known senders are
170resolved and followed across ownership changes. Callbacks receive a complete
171message and may inspect `dbus-message-body`, `dbus-message-signature`, and
172`dbus-message-field`. Exceptions in signal callbacks are contained.
174## Value mapping and wire API
176| D-Bus type | Sigil representation |
177| --- | --- |
178| `y n q i u x t` | Exact integer in the type's range, including full 64-bit endpoints |
179| `b` | `#t` or `#f` |
180| `d` | Real number, encoded as IEEE-754 double |
181| `s o g` | String; object paths and signatures are validated |
182| `ay` | Bytevector (a byte list is also accepted when writing) |
183| Other arrays | List of elements |
184| Struct `(…)` | List of fields |
185| Dictionary `a{kv}` | Alist of dotted `(key . value)` pairs |
186| Variant `v` | `(dbus-variant signature value)`, exactly one complete type |
187| `h` | Unsigned wire index only; descriptor transfer is not negotiated |
189For example, `a{sv}` is
190`(list (cons "urgency" (dbus-variant "y" 2)))`. An array of structs uses a
191list of lists. Method bodies always have an additional outer list for the
192method's arguments. There is no implicit signature inference.
194`dbus-marshal signature arguments` and `dbus-unmarshal signature bytes`
195encode/decode bare bodies. Both accept `endianness: 'little` or `'big`;
196writing defaults to native order. Unmarshalling also accepts `max-values:`
197(default 1000000). Both accept `max-bytes:`. `dbus-encode-message` and
198`dbus-decode-message` handle complete frames; `dbus-frame-size` validates a
19916-byte prefix before frame allocation. Header fields are an alist from
200numeric field code to typed variant; the body signature has its own slot.
201Unknown nonzero header fields and message types can be decoded.
203Input checks enforce the specification's 128 MiB message and 64 MiB array
204ceilings, 255-byte signatures, 32 nested arrays, 32 nested structs/dict
205entries, and a combined depth of 64 including variants. The lower connection
206default of 16 MiB and decoded-value budget bound allocations from untrusted
207peers. UTF-8, padding, booleans, required headers, duplicates, and lengths
208are checked. Partial frames are retained across pump timeouts. There are at
209most 1024 outstanding calls/subscriptions and 64 concurrent callbacks per
210connection. At capacity, method calls receive LimitsExceeded; excess signal
211callbacks are dropped. UNIX_FD transfer is not supported: live messages
212declaring transferred descriptors are rejected.
214The reference is the [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html),
215especially [marshalling](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling),
216[message format](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-messages),
217and [standard interfaces](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces).
219## Tests
221`dbus-method` accepts `with-message: #t` to prepend the incoming D-Bus message
222to the handler's arguments. Use its bus-assigned sender (header field 7) and
223object path (field 1) when authorizing an agent request. Validate the sender
224against the current unique service owner, rather than a well-known name.
226Method handlers with output signature `s` may return
227`(dbus-sensitive-reply bytes)` instead of the usual argument list. This
228transfers ownership of a UTF-8 bytevector immediately. Do not retain a second
229copy or modify it afterward. A reply is usable once; call
230`dbus-sensitive-reply-clear!` to discard it before returning it.
232Sensitive replies validate without decoding to a string and write directly
233into a single secret-bearing frame. The input and frame are overwritten on
234success, send failure, invalid output, and suppressed replies. This covers
235only those owned buffers. It does not erase copies previously made by the
236caller, operating system, bus daemon, recipient, runtime, or debugger. Avoid
237converting secrets from strings or logging handler inputs/results.
238This does not guarantee that a password never lingers in process memory.
240```sh
241sigil --no-auto-compile -L src eval -f test/test-wire.sgl
242sigil --no-auto-compile -L src eval -f test/test-sensitive.sgl
243sigil -L src test/test-readiness.sgl
244sigil -L src test/test-pinned-replies.sgl
245scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-integration.sgl
246scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-transport.sgl
247```
249Tests need `dbus-daemon`, `dbus-send`, and `busctl`. The integration fixture
250creates and cleans up a disposable session bus; it directs both session and
251system entry points to that bus, without accessing the host's system bus.
252Each suite is intended to finish in under a minute. Tests cover wire round
253trips and golden bytes, malformed/over-limit input, EXTERNAL/Hello/ListNames,
254services, notifications-shaped arguments, properties/signals/introspection,
255timeouts, serial matching, ownership, and external clients.
256Controlled peers also exercise fragmented/coalesced frames, partial EOF,
257advertised oversize frames, and bounded writes under backpressure.
259BSD-3-Clause; see [LICENSE](LICENSE).