Atv0.1.3Repositorysigil-dbus
Document

sigil-dbus

dbus-sensitive-dictionary-reply takes a public setting name, a public field name and owned UTF-8 bytes. It returns one string secret in a{sa{sv}}, for example a NetworkManager SecretAgent reply. As with dbus-sensitive-reply, the input and final encoded frame are cleared after send, cancellation, validation failure or transport failure. The value is usable once. This does not clear runtime, kernel, daemon or caller-created copies.

The receive transport clears its owned socket chunks and completed frames after decoding, including rejected frames, and clears an incomplete frame on close. String decoding also clears its temporary UTF-8 bytevector. Returned strings and bytevectors remain caller-owned; an agent receiving credentials in ordinary method arguments must clear those decoded values after inspecting them.

A pure Sigil D-Bus client and object-service library. Requires public Sigil 0.23.1 on Unix. Uses Sigil's socket and cooperative scheduler APIs; there is no libdbus or sd-bus dependency and no native extension in this package.

Version 0.1.3 adds reply sender pinning for unique destinations and optional exact success-signature validation.

Client

(import (sigil dbus))

(define connection (dbus-connect-session))
(display
  (dbus-call connection
    "org.freedesktop.DBus" "/org/freedesktop/DBus"
    "org.freedesktop.DBus" "ListNames" "" '()))
(newline)
(dbus-close! connection)

dbus-connect-session reads DBUS_SESSION_BUS_ADDRESS. dbus-connect-system reads DBUS_SYSTEM_BUS_ADDRESS, falling back to unix:path=/var/run/dbus/system_bus_socket. Both accept address:, uid:, timeout-ms: (default 25000), and max-bytes: (default 16 MiB). dbus-connect address accepts the other three options. All authenticate with SASL EXTERNAL and perform Hello before returning. The UID defaults to the result of the system id -u command; pass uid: to avoid that command. Connections are never automatically reconnected.

Address lists and percent-escaped unix:path= addresses are supported. Sigil 0.23.1 has no public abstract Unix socket connector. An unix:abstract= entry produces a clear error and the next address is tried. Use a pathname address when configuring a bus. This is a known transport limitation, not transparent abstract-socket support.

dbus-call connection destination path interface member signature arguments returns a list of output arguments, or a dbus-error value for a remote error or timeout. Its keyword options are timeout-ms:, flags: and reply-signature:. Transport or local validation failures raise exceptions. Check dbus-error?, then dbus-error-name and dbus-error-message. A timeout has the name org.freedesktop.DBus.Error.NoReply.

For a security-sensitive call, resolve and authenticate the unique destination first, then pass reply-signature: to dbus-call or dbus-call-async. This requires a unique destination (or the bus daemon) and validates the exact successful-reply wire signature; a mismatch returns InvalidSignature. Calls to unique destinations and the bus daemon also pin the reply sender, even without this option. A foreign sender cannot complete them by matching a reply serial. Authenticated bus-daemon error replies still terminate the call. Calls to other well-known names retain their existing body-only behavior; they do not establish a persistent owner identity.

Inside (with-async ...), calls park only their calling fiber. For multiple outstanding calls, dbus-call-async takes the same arguments and returns a pending value; dbus-await waits for it. Replies are matched by serial, so completion order can differ from send order. dbus-pending-ready? reports completion after a pump/await. dbus-pump! connection timeout-ms: 100 handles one incoming message and expires calls. dbus-run! pumps until closed. There is no hidden background reader: services and signal-only clients must run a pump, usually in (go (dbus-run! connection)). Call dbus-close! to release the socket and resolve outstanding calls as Disconnected.

dbus-connection-fd returns the live native descriptor, or #f after close. The connection retains ownership: use it only for readiness waits, never read, write, or close it directly. After readiness, dbus-pump! with timeout-ms: 0 processes one available frame without waiting; partial frames remain buffered for the next readiness notification. A caller with pending calls must also wake for their deadlines. Cancel a wait before closing its connection or reusing descriptors.

Export a service

(import (sigil dbus) (sigil async))

(with-async
  (let ((connection (dbus-connect-session)))
    (dbus-export! connection "/org/example/Greeter"
      (list
        (dbus-interface "org.example.Greeter"
          methods:
          (list (dbus-method "Greet" "s" "s"
                  (lambda (name) (list (string-append "Hello, " name)))))
          properties:
          (list (dbus-property "Version" "s" (lambda () "1.0"))))))
    (unless (equal? 1 (dbus-request-name! connection "org.example.Greeter"))
      (error "Service name is unavailable"))
    (dbus-run! connection)))

Call it with:

dbus-send --session --print-reply --dest=org.example.Greeter \
  /org/example/Greeter org.example.Greeter.Greet string:World
busctl --user get-property org.example.Greeter /org/example/Greeter \
  org.example.Greeter Version

dbus-method name input-signature output-signature handler passes decoded input arguments positionally. Return a list of output arguments, including '() for no output, or (dbus-error "org.example.Error.Refused" "reason"). Exceptions and invalid handler output become org.freedesktop.DBus.Error.Failed replies. Handlers may yield inside with-async. Exported methods require an explicit interface on incoming calls. The library suppresses replies to NO_REPLY_EXPECTED calls.

dbus-property name signature getter setter: setter takes a zero-argument getter and optional one-argument setter. A missing getter creates a write-only property. A missing setter creates a read-only property. Setters may return a dbus-error; other return values are ignored. Successful Properties.Set emits PropertiesChanged using the getter's current value, or invalidates a write-only property. For application-side changes, call dbus-properties-changed! connection path interface changed-alist invalidated: names. Get, Set, GetAll, generated introspection XML, and Peer.Ping are provided automatically. dbus-unexport! connection path removes an object. dbus-introspect connection path returns its generated XML.

Declare signals in dbus-interface with signals: (list (dbus-signal "Changed" "u")). Send using dbus-send-signal! connection path interface member signature arguments, optionally with destination: for a unicast signal.

Names and signals

dbus-request-name! connection name flags: flags returns the bus's numeric RequestName result (1 primary owner, 2 queued, 3 exists, 4 already owner), or a dbus-error. Default flags are dbus-do-not-queue. Add flag values dbus-allow-replacement (1), dbus-replace-existing (2), and dbus-do-not-queue (4) as needed. dbus-release-name! returns ReleaseName's numeric result. dbus-owned-names reflects NameAcquired/NameLost messages already processed by the pump; dbus-unique-name is set by Hello.

(define subscription
  (dbus-subscribe! connection
    (list (cons 'sender "org.freedesktop.DBus")
          (cons 'interface "org.freedesktop.DBus")
          (cons 'member "NameOwnerChanged"))
    (lambda (message) (display (dbus-message-body message)))))
;; Pump the connection to receive callbacks, then:
(dbus-unsubscribe! connection subscription)

Subscription keys are sender, interface, member, path, destination, and arg0. AddMatch/RemoveMatch are handled for you. Subscription setup accepts timeout-ms: for one total budget and await: for a cancelable pending-call waiter (default dbus-await). A failed setup removes possible late matches with no reply wait, using cleanup-timeout-ms: (default 10ms). Unsubscribe detaches the local callback immediately, even on failure; it accepts the same timeout and await options. With wait?: #f, it sends bounded no-reply removals instead of waiting for acknowledgments. Remote cleanup is best effort if the connection fails; closing it releases its remaining daemon matches. Well-known senders are resolved and followed across ownership changes. Callbacks receive a complete message and may inspect dbus-message-body, dbus-message-signature, and dbus-message-field. Exceptions in signal callbacks are contained.

Value mapping and wire API

D-Bus typeSigil representation
y n q i u x tExact integer in the type's range, including full 64-bit endpoints
b#t or #f
dReal number, encoded as IEEE-754 double
s o gString; object paths and signatures are validated
ayBytevector (a byte list is also accepted when writing)
Other arraysList of elements
Struct (…)List of fields
Dictionary a{kv}Alist of dotted (key . value) pairs
Variant v(dbus-variant signature value), exactly one complete type
hUnsigned wire index only; descriptor transfer is not negotiated

For example, a{sv} is (list (cons "urgency" (dbus-variant "y" 2))). An array of structs uses a list of lists. Method bodies always have an additional outer list for the method's arguments. There is no implicit signature inference.

dbus-marshal signature arguments and dbus-unmarshal signature bytes encode/decode bare bodies. Both accept endianness: 'little or 'big; writing defaults to native order. Unmarshalling also accepts max-values: (default 1000000). Both accept max-bytes:. dbus-encode-message and dbus-decode-message handle complete frames; dbus-frame-size validates a 16-byte prefix before frame allocation. Header fields are an alist from numeric field code to typed variant; the body signature has its own slot. Unknown nonzero header fields and message types can be decoded.

Input checks enforce the specification's 128 MiB message and 64 MiB array ceilings, 255-byte signatures, 32 nested arrays, 32 nested structs/dict entries, and a combined depth of 64 including variants. The lower connection default of 16 MiB and decoded-value budget bound allocations from untrusted peers. UTF-8, padding, booleans, required headers, duplicates, and lengths are checked. Partial frames are retained across pump timeouts. There are at most 1024 outstanding calls/subscriptions and 64 concurrent callbacks per connection. At capacity, method calls receive LimitsExceeded; excess signal callbacks are dropped. UNIX_FD transfer is not supported: live messages declaring transferred descriptors are rejected.

The reference is the D-Bus specification, especially marshalling, message format, and standard interfaces.

Tests

dbus-method accepts with-message: #t to prepend the incoming D-Bus message to the handler's arguments. Use its bus-assigned sender (header field 7) and object path (field 1) when authorizing an agent request. Validate the sender against the current unique service owner, rather than a well-known name.

Method handlers with output signature s may return (dbus-sensitive-reply bytes) instead of the usual argument list. This transfers ownership of a UTF-8 bytevector immediately. Do not retain a second copy or modify it afterward. A reply is usable once; call dbus-sensitive-reply-clear! to discard it before returning it.

Sensitive replies validate without decoding to a string and write directly into a single secret-bearing frame. The input and frame are overwritten on success, send failure, invalid output, and suppressed replies. This covers only those owned buffers. It does not erase copies previously made by the caller, operating system, bus daemon, recipient, runtime, or debugger. Avoid converting secrets from strings or logging handler inputs/results. This does not guarantee that a password never lingers in process memory.

sigil --no-auto-compile -L src eval -f test/test-wire.sgl
sigil --no-auto-compile -L src eval -f test/test-sensitive.sgl
sigil -L src test/test-readiness.sgl
sigil -L src test/test-pinned-replies.sgl
scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-integration.sgl
scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-transport.sgl

Tests need dbus-daemon, dbus-send, and busctl. The integration fixture creates and cleans up a disposable session bus; it directs both session and system entry points to that bus, without accessing the host's system bus. Each suite is intended to finish in under a minute. Tests cover wire round trips and golden bytes, malformed/over-limit input, EXTERNAL/Hello/ListNames, services, notifications-shaped arguments, properties/signals/introspection, timeouts, serial matching, ownership, and external clients. Controlled peers also exercise fragmented/coalesced frames, partial EOF, advertised oversize frames, and bounded writes under backpressure.

BSD-3-Clause; see LICENSE.