AtlatestRepositorysigil-dbus
sigil-dbus / treeREADME.md
1
# sigil-dbus3
`dbus-sensitive-dictionary-reply` takes a public setting name, a public field4
name and owned UTF-8 bytes. It returns one string secret in `a{sa{sv}}`, for5
example a NetworkManager SecretAgent reply. As with `dbus-sensitive-reply`,6
the input and final encoded frame are cleared after send, cancellation,7
validation failure or transport failure. The value is usable once. This8
does not clear runtime, kernel, daemon or caller-created copies.10
The receive transport clears its owned socket chunks and completed frames after11
decoding, including rejected frames, and clears an incomplete frame on close.12
String decoding also clears its temporary UTF-8 bytevector. Returned strings13
and bytevectors remain caller-owned; an agent receiving credentials in ordinary14
method arguments must clear those decoded values after inspecting them.16
A pure Sigil D-Bus client and object-service library. Requires public Sigil17
0.23.1 on Unix. Uses Sigil's socket and cooperative scheduler APIs; there is18
no libdbus or sd-bus dependency and no native extension in this package.20
Version 0.1.3 adds reply sender pinning for unique destinations and optional21
exact success-signature validation.23
## Client25
```scheme26
(import (sigil dbus))28
(define connection (dbus-connect-session))29
(display30
(dbus-call connection31
"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 to39
`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 authenticate42
with SASL EXTERNAL and perform Hello before returning. The UID defaults to43
the result of the system `id -u` command; pass `uid:` to avoid that command.44
Connections are never automatically reconnected.46
Address lists and percent-escaped `unix:path=` addresses are supported.47
**Sigil 0.23.1 has no public abstract Unix socket connector.** An48
`unix:abstract=` entry produces a clear error and the next address is tried.49
Use a pathname address when configuring a bus. This is a known transport50
limitation, not transparent abstract-socket support.52
`dbus-call connection destination path interface member signature arguments`53
returns a list of output arguments, or a `dbus-error` value for a remote error54
or timeout. Its keyword options are `timeout-ms:`, `flags:` and `reply-signature:`. Transport or55
local validation failures raise exceptions. Check `dbus-error?`, then56
`dbus-error-name` and `dbus-error-message`. A timeout has the name57
`org.freedesktop.DBus.Error.NoReply`.59
For a security-sensitive call, resolve and authenticate the unique destination60
first, then pass `reply-signature:` to `dbus-call` or `dbus-call-async`. This61
requires a unique destination (or the bus daemon) and validates the exact62
successful-reply wire signature; a mismatch returns InvalidSignature. Calls to63
unique destinations and the bus daemon also pin the reply sender, even without64
this option. A foreign sender cannot complete them by matching a reply serial.65
Authenticated bus-daemon error replies still terminate the call. Calls to other66
well-known names retain their existing body-only behavior; they do not establish67
a persistent owner identity.69
Inside `(with-async ...)`, calls park only their calling fiber. For multiple70
outstanding calls, `dbus-call-async` takes the same arguments and returns a71
pending value; `dbus-await` waits for it. Replies are matched by serial, so72
completion order can differ from send order. `dbus-pending-ready?` reports73
completion after a pump/await. `dbus-pump! connection timeout-ms: 100` handles74
one incoming message and expires calls. `dbus-run!` pumps until closed.75
There is no hidden background reader: services and signal-only clients must76
run a pump, usually in `(go (dbus-run! connection))`. Call `dbus-close!` to77
release the socket and resolve outstanding calls as Disconnected.79
`dbus-connection-fd` returns the live native descriptor, or `#f` after close.80
The connection retains ownership: use it only for readiness waits, never81
read, write, or close it directly. After readiness, `dbus-pump!` with82
`timeout-ms: 0` processes one available frame without waiting; partial frames83
remain buffered for the next readiness notification. A caller with pending84
calls must also wake for their deadlines. Cancel a wait before closing its85
connection or reusing descriptors.87
## Export a service89
```scheme90
(import (sigil dbus) (sigil async))92
(with-async93
(let ((connection (dbus-connect-session)))94
(dbus-export! connection "/org/example/Greeter"95
(list96
(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
```107
Call it with:109
```sh110
dbus-send --session --print-reply --dest=org.example.Greeter \111
/org/example/Greeter org.example.Greeter.Greet string:World112
busctl --user get-property org.example.Greeter /org/example/Greeter \113
org.example.Greeter Version114
```116
`dbus-method name input-signature output-signature handler` passes decoded117
input arguments positionally. Return a list of output arguments, including118
`'()` for no output, or `(dbus-error "org.example.Error.Refused" "reason")`.119
Exceptions and invalid handler output become `org.freedesktop.DBus.Error.Failed`120
replies. Handlers may yield inside `with-async`. Exported methods require an121
explicit interface on incoming calls. The library suppresses replies to122
NO_REPLY_EXPECTED calls.124
`dbus-property name signature getter setter: setter` takes a zero-argument125
getter and optional one-argument setter. A missing getter creates a126
write-only property. A missing setter creates a read-only property. Setters127
may return a `dbus-error`; other return values are ignored. Successful128
Properties.Set emits PropertiesChanged using the getter's current value, or129
invalidates a write-only property. For application-side changes, call130
`dbus-properties-changed! connection path interface changed-alist131
invalidated: names`. Get, Set, GetAll, generated introspection XML, and132
Peer.Ping are provided automatically. `dbus-unexport! connection path` removes133
an object. `dbus-introspect connection path` returns its generated XML.135
Declare signals in `dbus-interface` with136
`signals: (list (dbus-signal "Changed" "u"))`. Send using137
`dbus-send-signal! connection path interface member signature arguments`,138
optionally with `destination:` for a unicast signal.140
## Names and signals142
`dbus-request-name! connection name flags: flags` returns the bus's numeric143
RequestName result (1 primary owner, 2 queued, 3 exists, 4 already owner), or144
a `dbus-error`. Default flags are `dbus-do-not-queue`. Add flag values145
`dbus-allow-replacement` (1), `dbus-replace-existing` (2), and146
`dbus-do-not-queue` (4) as needed. `dbus-release-name!` returns ReleaseName's147
numeric result. `dbus-owned-names` reflects NameAcquired/NameLost messages148
already processed by the pump; `dbus-unique-name` is set by Hello.150
```scheme151
(define subscription152
(dbus-subscribe! connection153
(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
```161
Subscription keys are `sender`, `interface`, `member`, `path`, `destination`,162
and `arg0`. AddMatch/RemoveMatch are handled for you. Subscription setup accepts163
`timeout-ms:` for one total budget and `await:` for a cancelable pending-call164
waiter (default `dbus-await`). A failed setup removes possible late matches with165
no reply wait, using `cleanup-timeout-ms:` (default 10ms). Unsubscribe detaches166
the local callback immediately, even on failure; it accepts the same timeout167
and await options. With `wait?: #f`, it sends bounded no-reply removals instead168
of waiting for acknowledgments. Remote cleanup is best effort if the connection169
fails; closing it releases its remaining daemon matches. Well-known senders are170
resolved and followed across ownership changes. Callbacks receive a complete171
message and may inspect `dbus-message-body`, `dbus-message-signature`, and172
`dbus-message-field`. Exceptions in signal callbacks are contained.174
## Value mapping and wire API176
| 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 |189
For example, `a{sv}` is190
`(list (cons "urgency" (dbus-variant "y" 2)))`. An array of structs uses a191
list of lists. Method bodies always have an additional outer list for the192
method's arguments. There is no implicit signature inference.194
`dbus-marshal signature arguments` and `dbus-unmarshal signature bytes`195
encode/decode bare bodies. Both accept `endianness: 'little` or `'big`;196
writing defaults to native order. Unmarshalling also accepts `max-values:`197
(default 1000000). Both accept `max-bytes:`. `dbus-encode-message` and198
`dbus-decode-message` handle complete frames; `dbus-frame-size` validates a199
16-byte prefix before frame allocation. Header fields are an alist from200
numeric field code to typed variant; the body signature has its own slot.201
Unknown nonzero header fields and message types can be decoded.203
Input checks enforce the specification's 128 MiB message and 64 MiB array204
ceilings, 255-byte signatures, 32 nested arrays, 32 nested structs/dict205
entries, and a combined depth of 64 including variants. The lower connection206
default of 16 MiB and decoded-value budget bound allocations from untrusted207
peers. UTF-8, padding, booleans, required headers, duplicates, and lengths208
are checked. Partial frames are retained across pump timeouts. There are at209
most 1024 outstanding calls/subscriptions and 64 concurrent callbacks per210
connection. At capacity, method calls receive LimitsExceeded; excess signal211
callbacks are dropped. UNIX_FD transfer is not supported: live messages212
declaring transferred descriptors are rejected.214
The reference is the [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html),215
especially [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),217
and [standard interfaces](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces).219
## Tests221
`dbus-method` accepts `with-message: #t` to prepend the incoming D-Bus message222
to the handler's arguments. Use its bus-assigned sender (header field 7) and223
object path (field 1) when authorizing an agent request. Validate the sender224
against the current unique service owner, rather than a well-known name.226
Method handlers with output signature `s` may return227
`(dbus-sensitive-reply bytes)` instead of the usual argument list. This228
transfers ownership of a UTF-8 bytevector immediately. Do not retain a second229
copy or modify it afterward. A reply is usable once; call230
`dbus-sensitive-reply-clear!` to discard it before returning it.232
Sensitive replies validate without decoding to a string and write directly233
into a single secret-bearing frame. The input and frame are overwritten on234
success, send failure, invalid output, and suppressed replies. This covers235
only those owned buffers. It does not erase copies previously made by the236
caller, operating system, bus daemon, recipient, runtime, or debugger. Avoid237
converting secrets from strings or logging handler inputs/results.238
This does not guarantee that a password never lingers in process memory.240
```sh241
sigil --no-auto-compile -L src eval -f test/test-wire.sgl242
sigil --no-auto-compile -L src eval -f test/test-sensitive.sgl243
sigil -L src test/test-readiness.sgl244
sigil -L src test/test-pinned-replies.sgl245
scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-integration.sgl246
scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-transport.sgl247
```249
Tests need `dbus-daemon`, `dbus-send`, and `busctl`. The integration fixture250
creates and cleans up a disposable session bus; it directs both session and251
system entry points to that bus, without accessing the host's system bus.252
Each suite is intended to finish in under a minute. Tests cover wire round253
trips and golden bytes, malformed/over-limit input, EXTERNAL/Hello/ListNames,254
services, notifications-shaped arguments, properties/signals/introspection,255
timeouts, serial matching, ownership, and external clients.256
Controlled peers also exercise fragmented/coalesced frames, partial EOF,257
advertised oversize frames, and bounded writes under backpressure.259
BSD-3-Clause; see [LICENSE](LICENSE).