Commit971eb167Recorded25 Oct 2026Repositorysigil-dbus

Implement pure Sigil D-Bus client and object services

Changed
 .gitignore                    |   3 ++
 LICENSE                       |  28 +++++++++++++++
 README.md                     | 196 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 examples/list-names.sgl       |  12 +++++++
 examples/service.sgl          |  25 +++++++++++++
 package.sgl                   |  12 +++++++
 scripts/with-test-bus.sh      |  25 +++++++++++++
 src/sigil/dbus.sgl            |  19 ++++++++++
 src/sigil/dbus/connection.sgl | 320 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/dbus/message.sgl    | 130 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/dbus/service.sgl    | 231 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/dbus/transport.sgl  | 204 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/dbus/types.sgl      | 140 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/dbus/wire.sgl       | 305 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-integration.sgl     | 199 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-transport.sgl       |  95 ++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-wire.sgl            | 155 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 17 files changed, 2099 insertions(+)
Diff
.gitignoreadded
@@ -0,0 +1,3 @@
+1
/build/
+2
/.sigil/
+3
/sigil.lock
LICENSEadded
@@ -0,0 +1,28 @@
+1
BSD 3-Clause License
+2
+3
Copyright (c) 2026, David Wilson
+4
All rights reserved.
+5
+6
Redistribution and use in source and binary forms, with or without
+7
modification, are permitted provided that the following conditions are met:
+8
+9
1. Redistributions of source code must retain the above copyright notice,
+10
this list of conditions and the following disclaimer.
+11
2. Redistributions in binary form must reproduce the above copyright notice,
+12
this list of conditions and the following disclaimer in the documentation
+13
and/or other materials provided with the distribution.
+14
3. Neither the name of the copyright holder nor the names of its contributors
+15
may be used to endorse or promote products derived from this software
+16
without specific prior written permission.
+17
+18
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+19
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+20
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+21
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+22
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+23
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+24
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+25
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+26
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+27
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+28
README.mdadded
@@ -0,0 +1,196 @@
+1
# sigil-dbus
+2
+3
A pure Sigil D-Bus client and object-service library. Requires public Sigil
+4
0.23.1 on Unix. Uses Sigil's socket and cooperative scheduler APIs; there is
+5
no libdbus or sd-bus dependency and no native extension in this package.
+6
+7
## Client
+8
+9
```scheme
+10
(import (sigil dbus))
+11
+12
(define connection (dbus-connect-session))
+13
(display
+14
(dbus-call connection
+15
"org.freedesktop.DBus" "/org/freedesktop/DBus"
+16
"org.freedesktop.DBus" "ListNames" "" '()))
+17
(newline)
+18
(dbus-close! connection)
+19
```
+20
+21
`dbus-connect-session` reads `DBUS_SESSION_BUS_ADDRESS`.
+22
`dbus-connect-system` reads `DBUS_SYSTEM_BUS_ADDRESS`, falling back to
+23
`unix:path=/var/run/dbus/system_bus_socket`. Both accept `address:`, `uid:`,
+24
`timeout-ms:` (default 25000), and `max-bytes:` (default 16 MiB).
+25
`dbus-connect address` accepts the other three options. All authenticate
+26
with SASL EXTERNAL and perform Hello before returning. The UID defaults to
+27
the result of the system `id -u` command; pass `uid:` to avoid that command.
+28
Connections are never automatically reconnected.
+29
+30
Address lists and percent-escaped `unix:path=` addresses are supported.
+31
**Sigil 0.23.1 has no public abstract Unix socket connector.** An
+32
`unix:abstract=` entry produces a clear error and the next address is tried.
+33
Use a pathname address when configuring a bus. This is a known transport
+34
limitation, not transparent abstract-socket support.
+35
+36
`dbus-call connection destination path interface member signature arguments`
+37
returns a list of output arguments, or a `dbus-error` value for a remote error
+38
or timeout. Its keyword options are `timeout-ms:` and `flags:`. Transport or
+39
local validation failures raise exceptions. Check `dbus-error?`, then
+40
`dbus-error-name` and `dbus-error-message`. A timeout has the name
+41
`org.freedesktop.DBus.Error.NoReply`.
+42
+43
Inside `(with-async ...)`, calls park only their calling fiber. For multiple
+44
outstanding calls, `dbus-call-async` takes the same arguments and returns a
+45
pending value; `dbus-await` waits for it. Replies are matched by serial, so
+46
completion order can differ from send order. `dbus-pending-ready?` reports
+47
completion after a pump/await. `dbus-pump! connection timeout-ms: 100` handles
+48
one incoming message and expires calls. `dbus-run!` pumps until closed.
+49
There is no hidden background reader: services and signal-only clients must
+50
run a pump, usually in `(go (dbus-run! connection))`. Call `dbus-close!` to
+51
release the socket and resolve outstanding calls as Disconnected.
+52
+53
## Export a service
+54
+55
```scheme
+56
(import (sigil dbus) (sigil async))
+57
+58
(with-async
+59
(let ((connection (dbus-connect-session)))
+60
(dbus-export! connection "/org/example/Greeter"
+61
(list
+62
(dbus-interface "org.example.Greeter"
+63
methods:
+64
(list (dbus-method "Greet" "s" "s"
+65
(lambda (name) (list (string-append "Hello, " name)))))
+66
properties:
+67
(list (dbus-property "Version" "s" (lambda () "1.0"))))))
+68
(unless (equal? 1 (dbus-request-name! connection "org.example.Greeter"))
+69
(error "Service name is unavailable"))
+70
(dbus-run! connection)))
+71
```
+72
+73
Call it with:
+74
+75
```sh
+76
dbus-send --session --print-reply --dest=org.example.Greeter \
+77
/org/example/Greeter org.example.Greeter.Greet string:World
+78
busctl --user get-property org.example.Greeter /org/example/Greeter \
+79
org.example.Greeter Version
+80
```
+81
+82
`dbus-method name input-signature output-signature handler` passes decoded
+83
input arguments positionally. Return a list of output arguments, including
+84
`'()` for no output, or `(dbus-error "org.example.Error.Refused" "reason")`.
+85
Exceptions and invalid handler output become `org.freedesktop.DBus.Error.Failed`
+86
replies. Handlers may yield inside `with-async`. Exported methods require an
+87
explicit interface on incoming calls. The library suppresses replies to
+88
NO_REPLY_EXPECTED calls.
+89
+90
`dbus-property name signature getter setter: setter` takes a zero-argument
+91
getter and optional one-argument setter. A missing getter creates a
+92
write-only property. A missing setter creates a read-only property. Setters
+93
may return a `dbus-error`; other return values are ignored. Successful
+94
Properties.Set emits PropertiesChanged using the getter's current value, or
+95
invalidates a write-only property. For application-side changes, call
+96
`dbus-properties-changed! connection path interface changed-alist
+97
invalidated: names`. Get, Set, GetAll, generated introspection XML, and
+98
Peer.Ping are provided automatically. `dbus-unexport! connection path` removes
+99
an object. `dbus-introspect connection path` returns its generated XML.
+100
+101
Declare signals in `dbus-interface` with
+102
`signals: (list (dbus-signal "Changed" "u"))`. Send using
+103
`dbus-send-signal! connection path interface member signature arguments`,
+104
optionally with `destination:` for a unicast signal.
+105
+106
## Names and signals
+107
+108
`dbus-request-name! connection name flags: flags` returns the bus's numeric
+109
RequestName result (1 primary owner, 2 queued, 3 exists, 4 already owner), or
+110
a `dbus-error`. Default flags are `dbus-do-not-queue`. Add flag values
+111
`dbus-allow-replacement` (1), `dbus-replace-existing` (2), and
+112
`dbus-do-not-queue` (4) as needed. `dbus-release-name!` returns ReleaseName's
+113
numeric result. `dbus-owned-names` reflects NameAcquired/NameLost messages
+114
already processed by the pump; `dbus-unique-name` is set by Hello.
+115
+116
```scheme
+117
(define subscription
+118
(dbus-subscribe! connection
+119
(list (cons 'sender "org.freedesktop.DBus")
+120
(cons 'interface "org.freedesktop.DBus")
+121
(cons 'member "NameOwnerChanged"))
+122
(lambda (message) (display (dbus-message-body message)))))
+123
;; Pump the connection to receive callbacks, then:
+124
(dbus-unsubscribe! connection subscription)
+125
```
+126
+127
Subscription keys are `sender`, `interface`, `member`, `path`, `destination`,
+128
and `arg0`. AddMatch/RemoveMatch are handled for you. Well-known senders are
+129
resolved and followed across ownership changes. Callbacks receive a complete
+130
message and may inspect `dbus-message-body`, `dbus-message-signature`, and
+131
`dbus-message-field`. Exceptions in signal callbacks are contained.
+132
+133
## Value mapping and wire API
+134
+135
| D-Bus type | Sigil representation |
+136
| --- | --- |
+137
| `y n q i u x t` | Exact integer in the type's range, including full 64-bit endpoints |
+138
| `b` | `#t` or `#f` |
+139
| `d` | Real number, encoded as IEEE-754 double |
+140
| `s o g` | String; object paths and signatures are validated |
+141
| `ay` | Bytevector (a byte list is also accepted when writing) |
+142
| Other arrays | List of elements |
+143
| Struct `(…)` | List of fields |
+144
| Dictionary `a{kv}` | Alist of dotted `(key . value)` pairs |
+145
| Variant `v` | `(dbus-variant signature value)`, exactly one complete type |
+146
| `h` | Unsigned wire index only; descriptor transfer is not negotiated |
+147
+148
For example, `a{sv}` is
+149
`(list (cons "urgency" (dbus-variant "y" 2)))`. An array of structs uses a
+150
list of lists. Method bodies always have an additional outer list for the
+151
method's arguments. There is no implicit signature inference.
+152
+153
`dbus-marshal signature arguments` and `dbus-unmarshal signature bytes`
+154
encode/decode bare bodies. Both accept `endianness: 'little` or `'big`;
+155
writing defaults to native order. Unmarshalling also accepts `max-values:`
+156
(default 1000000). Both accept `max-bytes:`. `dbus-encode-message` and
+157
`dbus-decode-message` handle complete frames; `dbus-frame-size` validates a
+158
16-byte prefix before frame allocation. Header fields are an alist from
+159
numeric field code to typed variant; the body signature has its own slot.
+160
Unknown nonzero header fields and message types can be decoded.
+161
+162
Input checks enforce the specification's 128 MiB message and 64 MiB array
+163
ceilings, 255-byte signatures, 32 nested arrays, 32 nested structs/dict
+164
entries, and a combined depth of 64 including variants. The lower connection
+165
default of 16 MiB and decoded-value budget bound allocations from untrusted
+166
peers. UTF-8, padding, booleans, required headers, duplicates, and lengths
+167
are checked. Partial frames are retained across pump timeouts. There are at
+168
most 1024 outstanding calls/subscriptions and 64 concurrent callbacks per
+169
connection. At capacity, method calls receive LimitsExceeded; excess signal
+170
callbacks are dropped. UNIX_FD transfer is not supported: live messages
+171
declaring transferred descriptors are rejected.
+172
+173
The reference is the [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html),
+174
especially [marshalling](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling),
+175
[message format](https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-messages),
+176
and [standard interfaces](https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces).
+177
+178
## Tests
+179
+180
```sh
+181
sigil --no-auto-compile -L src eval -f test/test-wire.sgl
+182
scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-integration.sgl
+183
scripts/with-test-bus.sh sigil --no-auto-compile -L src eval -f test/test-transport.sgl
+184
```
+185
+186
Tests need `dbus-daemon`, `dbus-send`, and `busctl`. The integration fixture
+187
creates and cleans up a disposable session bus; it directs both session and
+188
system entry points to that bus, without accessing the host's system bus.
+189
Each suite is intended to finish in under a minute. Tests cover wire round
+190
trips and golden bytes, malformed/over-limit input, EXTERNAL/Hello/ListNames,
+191
services, notifications-shaped arguments, properties/signals/introspection,
+192
timeouts, serial matching, ownership, and external clients.
+193
Controlled peers also exercise fragmented/coalesced frames, partial EOF,
+194
advertised oversize frames, and bounded writes under backpressure.
+195
+196
BSD-3-Clause; see [LICENSE](LICENSE).
examples/list-names.sgladded
@@ -0,0 +1,12 @@
+1
(import (sigil dbus))
+2
+3
(define connection (dbus-connect-session))
+4
(dynamic-wind
+5
(lambda () #t)
+6
(lambda ()
+7
(display
+8
(dbus-call connection
+9
"org.freedesktop.DBus" "/org/freedesktop/DBus"
+10
"org.freedesktop.DBus" "ListNames" "" '()))
+11
(newline))
+12
(lambda () (dbus-close! connection)))
examples/service.sgladded
@@ -0,0 +1,25 @@
+1
(import (sigil dbus) (sigil async))
+2
+3
(with-async
+4
(let ((connection (dbus-connect-session)) (count 0))
+5
(dbus-export! connection "/org/example/Counter"
+6
(list
+7
(dbus-interface "org.example.Counter"
+8
methods:
+9
(list
+10
(dbus-method "Increment" "u" "u"
+11
(lambda (amount)
+12
(set! count (+ count amount))
+13
(dbus-properties-changed! connection "/org/example/Counter"
+14
"org.example.Counter" (list (cons "Count" (dbus-variant "u" count))))
+15
(list count))))
+16
properties:
+17
(list (dbus-property "Count" "u" (lambda () count))))))
+18
(let ((result (dbus-request-name! connection "org.example.Counter")))
+19
(unless (or (equal? result 1) (equal? result 4))
+20
(dbus-close! connection)
+21
(error "Could not acquire service name" result)))
+22
(dynamic-wind
+23
(lambda () #t)
+24
(lambda () (dbus-run! connection))
+25
(lambda () (dbus-close! connection)))))
package.sgladded
@@ -0,0 +1,12 @@
+1
(package
+2
name: "sigil-dbus"
+3
version: "0.1.0"
+4
sigil: "0.23.1"
+5
description: "Pure Sigil D-Bus wire protocol, clients, and object services"
+6
license: "BSD-3-Clause"
+7
entry: '(sigil dbus)
+8
dependencies: (list
+9
(from-git url: "codeberg:sigil/sigil" package: "sigil-stdlib" version: "0.23.1"))
+10
dev-dependencies: (list
+11
(from-git url: "codeberg:sigil/sigil" package: "sigil-test" version: "0.23.1")
+12
(from-git url: "codeberg:sigil/sigil" package: "sigil-test-runner" version: "0.23.1")))
scripts/with-test-bus.shadded
@@ -0,0 +1,25 @@
+1
#!/usr/bin/env bash
+2
set -euo pipefail
+3
bus_dir=$(mktemp -d)
+4
bus_pid=
+5
cleanup() {
+6
if [[ -n "$bus_pid" ]]; then
+7
kill "$bus_pid" 2>/dev/null || true
+8
wait "$bus_pid" 2>/dev/null || true
+9
fi
+10
rm -rf "$bus_dir"
+11
}
+12
trap cleanup EXIT
+13
trap 'exit 130' INT TERM
+14
dbus-daemon --session --nofork --nopidfile --address="unix:path=$bus_dir/bus" --print-address=1 > "$bus_dir/address" &
+15
bus_pid=$!
+16
for ((i=0; i<100; i++)); do
+17
[[ -s "$bus_dir/address" ]] && break
+18
kill -0 "$bus_pid"
+19
sleep 0.01
+20
done
+21
export DBUS_SESSION_BUS_ADDRESS
+22
DBUS_SESSION_BUS_ADDRESS=$(head -1 "$bus_dir/address")
+23
export DBUS_SYSTEM_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS"
+24
export DBUS_TEST_DIRECTORY="$bus_dir"
+25
"$@"
src/sigil/dbus.sgladded
@@ -0,0 +1,19 @@
+1
(define-library (sigil dbus)
+2
(import (sigil dbus types) (sigil dbus wire) (sigil dbus message)
+3
(sigil dbus connection) (sigil dbus service))
+4
(export
+5
dbus-variant dbus-variant? dbus-variant-signature dbus-variant-value
+6
dbus-error dbus-error? dbus-error-name dbus-error-message
+7
dbus-parse-signature dbus-marshal dbus-unmarshal dbus-native-endianness
+8
dbus-max-message-size dbus-max-array-size
+9
dbus-connect dbus-connect-session dbus-connect-system dbus-close! dbus-closed?
+10
dbus-unique-name dbus-owned-names dbus-call dbus-call-async dbus-await
+11
dbus-pending? dbus-pending-ready? dbus-pump! dbus-run!
+12
dbus-request-name! dbus-release-name! dbus-allow-replacement
+13
dbus-replace-existing dbus-do-not-queue dbus-subscribe! dbus-unsubscribe!
+14
dbus-send-signal! dbus-method dbus-property dbus-signal dbus-interface
+15
dbus-export! dbus-unexport! dbus-introspect dbus-properties-changed!
+16
dbus-message dbus-message? dbus-message-type dbus-message-flags
+17
dbus-message-serial dbus-message-fields dbus-message-signature
+18
dbus-message-body dbus-message-field dbus-encode-message dbus-decode-message
+19
dbus-frame-size))
src/sigil/dbus/connection.sgladded
@@ -0,0 +1,320 @@
+1
(define-library (sigil dbus connection)
+2
(import (sigil dbus types) (sigil dbus message) (sigil dbus transport)
+3
(sigil dbus wire) (sigil async) (sigil process) (sigil string))
+4
(export dbus-connect dbus-connect-session dbus-connect-system dbus-close!
+5
dbus-closed? dbus-unique-name dbus-owned-names dbus-call dbus-call-async
+6
dbus-await dbus-pending? dbus-pending-ready? dbus-pump! dbus-run!
+7
dbus-request-name! dbus-release-name! dbus-subscribe! dbus-unsubscribe!
+8
dbus-send-signal! dbus-send-reply! dbus-set-dispatcher!
+9
dbus-connection-objects dbus-set-connection-objects!
+10
dbus-allow-replacement dbus-replace-existing dbus-do-not-queue)
+11
(begin
+12
(define dbus-allow-replacement 1)
+13
(define dbus-replace-existing 2)
+14
(define dbus-do-not-queue 4)
+15
(define bus-name "org.freedesktop.DBus")
+16
(define bus-path "/org/freedesktop/DBus")
+17
+18
;; Connection slots: transport, next serial, pending calls, subscriptions,
+19
;; method dispatcher, unique name, owned names, read lock, active callbacks.
+20
;; No hidden reader fiber: await, pump, and run cooperate on this lock.
+21
(define (dbus-closed? c) (dbus-transport-closed? (vector-ref c 0)))
+22
(define (dbus-unique-name c) (vector-ref c 5))
+23
(define (dbus-owned-names c) (vector-ref c 6))
+24
(define (dbus-set-dispatcher! c dispatcher) (vector-set! c 4 dispatcher))
+25
(define (dbus-connection-objects c) (vector-ref c 9))
+26
(define (dbus-set-connection-objects! c objects) (vector-set! c 9 objects))
+27
+28
(define (remove-if predicate items)
+29
(cond ((null? items) '())
+30
((predicate (car items)) (remove-if predicate (cdr items)))
+31
(else (cons (car items) (remove-if predicate (cdr items))))))
+32
+33
(define (dbus-close! c)
+34
(dbus-close-transport! (vector-ref c 0))
+35
(for-each
+36
(lambda (pending)
+37
(unless (dbus-pending-ready? pending)
+38
(vector-set! pending 4 (dbus-error "org.freedesktop.DBus.Error.Disconnected"
+39
"Connection closed"))
+40
(vector-set! pending 3 #t)))
+41
(vector-ref c 2))
+42
(vector-set! c 2 '())
+43
(vector-set! c 6 '())
+44
(vector-set! c 3 '())
+45
(vector-set! c 9 '())
+46
(vector-set! c 4 #f))
+47
+48
(define (next-serial! c)
+49
(let ((serial (vector-ref c 1)))
+50
(when (> serial 4294967295)
+51
;; Avoid reusing a serial while a late reply may still exist.
+52
(error "D-Bus serial space exhausted; create a new connection"))
+53
(vector-set! c 1 (+ serial 1))
+54
serial))
+55
+56
(define (send-message! c m timeout-ms)
+57
(let ((bytes (dbus-encode-message m)))
+58
(guard (e (else (dbus-close! c) (raise e)))
+59
(dbus-transport-write! (vector-ref c 0) bytes timeout-ms: timeout-ms))))
+60
+61
(define (dbus-connect address (keys: (uid #f) (timeout-ms 25000) (max-bytes 16777216)))
+62
(let ((c (vector (dbus-open-transport address uid: uid timeout-ms: timeout-ms max-bytes: max-bytes)
+63
1 '() '() #f #f '() #f 0 '())))
+64
(guard (e (else (dbus-close! c) (raise e)))
+65
(let ((reply (dbus-call c bus-name bus-path bus-name "Hello" "" '() timeout-ms: timeout-ms)))
+66
(when (dbus-error? reply) (raise reply))
+67
(unless (and (= 1 (length reply)) (dbus-bus-name? (car reply)))
+68
(error "Invalid D-Bus Hello reply"))
+69
(vector-set! c 5 (car reply))
+70
c))))
+71
+72
(define (dbus-connect-session (keys: (address (getenv "DBUS_SESSION_BUS_ADDRESS"))
+73
(uid #f) (timeout-ms 25000) (max-bytes 16777216)))
+74
(unless address (error "DBUS_SESSION_BUS_ADDRESS is not set"))
+75
(dbus-connect address uid: uid timeout-ms: timeout-ms max-bytes: max-bytes))
+76
+77
(define (dbus-connect-system (keys: (address (or (getenv "DBUS_SYSTEM_BUS_ADDRESS")
+78
"unix:path=/var/run/dbus/system_bus_socket"))
+79
(uid #f) (timeout-ms 25000) (max-bytes 16777216)))
+80
(dbus-connect address uid: uid timeout-ms: timeout-ms max-bytes: max-bytes))
+81
+82
;; Pending slots: connection, serial, deadline, ready?, result.
+83
(define (dbus-pending? p)
+84
(and (vector? p) (= 5 (vector-length p)) (vector? (vector-ref p 0))))
+85
(define (dbus-pending-ready? p) (vector-ref p 3))
+86
+87
(define (expire! c)
+88
(when (dbus-closed? c) (dbus-close! c))
+89
(for-each
+90
(lambda (p)
+91
(when (and (not (dbus-pending-ready? p))
+92
(<= (dbus-remaining-ms (vector-ref p 2)) 0))
+93
(vector-set! p 4 (dbus-error "org.freedesktop.DBus.Error.NoReply" "Method call timed out"))
+94
(vector-set! p 3 #t)))
+95
(vector-ref c 2))
+96
(vector-set! c 2 (remove-if dbus-pending-ready? (vector-ref c 2))))
+97
+98
(define (dbus-call-async c destination path interface member signature values
+99
(keys: (timeout-ms 25000) (flags 0)))
+100
(when (dbus-closed? c) (error "D-Bus connection closed"))
+101
(expire! c)
+102
(when (>= (length (vector-ref c 2)) 1024) (error "Too many outstanding D-Bus calls"))
+103
(when (odd? flags) (error "Use a reply-expecting call with this API"))
+104
(let* ((serial (next-serial! c))
+105
(pending (vector c serial (dbus-deadline timeout-ms) #f #f))
+106
(fields (append
+107
(list (cons 1 (dbus-variant "o" path)) (cons 3 (dbus-variant "s" member)))
+108
(if interface (list (cons 2 (dbus-variant "s" interface))) '())
+109
(if destination (list (cons 6 (dbus-variant "s" destination))) '()))))
+110
(vector-set! c 2 (cons pending (vector-ref c 2)))
+111
(guard (e (else (dbus-close! c) (raise e)))
+112
(send-message! c (dbus-message 1 serial fields signature values flags: flags) timeout-ms))
+113
pending))
+114
+115
(define (dbus-await pending)
+116
(let ((c (vector-ref pending 0)))
+117
(let loop ()
+118
(expire! c)
+119
(if (dbus-pending-ready? pending)
+120
(vector-ref pending 4)
+121
(begin
+122
(dbus-pump! c timeout-ms: (min 50 (dbus-remaining-ms (vector-ref pending 2))))
+123
(loop))))))
+124
+125
(define (dbus-call c destination path interface member signature values
+126
(keys: (timeout-ms 25000) (flags 0)))
+127
(dbus-await (dbus-call-async c destination path interface member signature values
+128
timeout-ms: timeout-ms flags: flags)))
+129
+130
(define (dbus-request-name! c name (keys: (flags dbus-do-not-queue)))
+131
(unless (and (integer? flags) (<= 0 flags 7)) (error "Invalid D-Bus name flags"))
+132
(let ((reply (dbus-call c bus-name bus-path bus-name "RequestName" "su" (list name flags))))
+133
(if (dbus-error? reply) reply (car reply))))
+134
+135
(define (dbus-release-name! c name)
+136
(let ((reply (dbus-call c bus-name bus-path bus-name "ReleaseName" "s" (list name))))
+137
(if (dbus-error? reply) reply (car reply))))
+138
+139
(define (dbus-send-signal! c path interface member signature values (keys: (destination #f)))
+140
(send-message! c
+141
(dbus-message 4 (next-serial! c)
+142
(append (list (cons 1 (dbus-variant "o" path)) (cons 2 (dbus-variant "s" interface))
+143
(cons 3 (dbus-variant "s" member)))
+144
(if destination (list (cons 6 (dbus-variant "s" destination))) '()))
+145
signature values)
+146
25000))
+147
+148
(define (dbus-send-reply! c call signature result)
+149
(unless (odd? (dbus-message-flags call))
+150
(let ((fields (list (cons 5 (dbus-variant "u" (dbus-message-serial call)))))
+151
(sender (dbus-message-field call 7)))
+152
(when sender (set! fields (cons (cons 6 (dbus-variant "s" sender)) fields)))
+153
(if (dbus-error? result)
+154
(send-message! c
+155
(dbus-message 3 (next-serial! c)
+156
(cons (cons 4 (dbus-variant "s" (dbus-error-name result))) fields)
+157
"s" (list (dbus-error-message result))) 25000)
+158
(send-message! c (dbus-message 2 (next-serial! c) fields signature result) 25000)))))
+159
+160
(define (quote-match value)
+161
(unless (string? value) (error "D-Bus match values must be strings"))
+162
(string-append "'"
+163
(apply string-append
+164
(map (lambda (c) (if (char=? c #\') "'\\''" (string c))) (string->list value))) "'"))
+165
+166
(define (match-rule matches)
+167
(string-append "type='signal'"
+168
(apply string-append
+169
(map (lambda (entry)
+170
(unless (memq (car entry) '(sender interface member path destination arg0))
+171
(error "Unsupported D-Bus subscription key"))
+172
(string-append "," (symbol->string (car entry)) "=" (quote-match (cdr entry))))
+173
matches))))
+174
+175
(define (matches? matches message owner)
+176
(let loop ((rest matches))
+177
(or (null? rest)
+178
(let* ((entry (car rest))
+179
(actual (case (car entry)
+180
((sender) (dbus-message-field message 7))
+181
((interface) (dbus-message-field message 2))
+182
((member) (dbus-message-field message 3))
+183
((path) (dbus-message-field message 1))
+184
((destination) (dbus-message-field message 6))
+185
((arg0) (and (pair? (dbus-message-body message))
+186
(car (dbus-message-body message)))))))
+187
(and (equal? actual (if (eq? 'sender (car entry)) owner (cdr entry)))
+188
(loop (cdr rest)))))))
+189
+190
(define (dbus-subscribe! c matches handler)
+191
(when (>= (length (vector-ref c 3)) 1024) (error "Too many D-Bus subscriptions"))
+192
(let* ((rule (match-rule matches))
+193
(sender (assoc 'sender matches))
+194
(well-known? (and sender (not (string=? bus-name (cdr sender)))
+195
(not (string-starts-with? (cdr sender) ":"))))
+196
(owner-rule (and well-known?
+197
(match-rule (list (cons 'sender bus-name) (cons 'interface bus-name)
+198
(cons 'member "NameOwnerChanged") (cons 'arg0 (cdr sender))))))
+199
(token (vector matches handler rule owner-rule (and sender (cdr sender))))
+200
(owner-added? #f)
+201
(reply (dbus-call c bus-name bus-path bus-name "AddMatch" "s" (list rule))))
+202
(if (dbus-error? reply)
+203
reply
+204
(guard (e (else
+205
(dbus-call c bus-name bus-path bus-name "RemoveMatch" "s" (list rule))
+206
(when owner-added?
+207
(dbus-call c bus-name bus-path bus-name "RemoveMatch" "s" (list owner-rule)))
+208
(raise e)))
+209
(when well-known?
+210
(let ((added (dbus-call c bus-name bus-path bus-name "AddMatch" "s" (list owner-rule))))
+211
(when (dbus-error? added) (raise added))
+212
(set! owner-added? #t))
+213
(let ((owner (dbus-call c bus-name bus-path bus-name "GetNameOwner" "s" (list (cdr sender)))))
+214
(vector-set! token 4 (and (not (dbus-error? owner)) (car owner)))))
+215
(vector-set! c 3 (cons token (vector-ref c 3)))
+216
token))))
+217
+218
(define (dbus-unsubscribe! c token)
+219
(when (memq token (vector-ref c 3))
+220
(let ((reply (dbus-call c bus-name bus-path bus-name "RemoveMatch" "s"
+221
(list (vector-ref token 2)))))
+222
(unless (dbus-error? reply)
+223
(when (vector-ref token 3)
+224
(dbus-call c bus-name bus-path bus-name "RemoveMatch" "s" (list (vector-ref token 3))))
+225
(vector-set! c 3 (remove-if (lambda (s) (eq? s token)) (vector-ref c 3)))))))
+226
+227
(define (safe-callback c thunk)
+228
(when (< (vector-ref c 8) 64)
+229
(vector-set! c 8 (+ 1 (vector-ref c 8)))
+230
(let ((run (lambda ()
+231
(dynamic-wind
+232
(lambda () #t)
+233
(lambda () (guard (e (else #f)) (thunk)))
+234
(lambda () (vector-set! c 8 (- (vector-ref c 8) 1)))))))
+235
(if (current-scheduler) (go (run)) (run)))))
+236
+237
(define (dispatch! c message)
+238
(case (dbus-message-type message)
+239
((2 3)
+240
(let ((serial (dbus-message-field message 5)))
+241
(for-each
+242
(lambda (p)
+243
(when (= serial (vector-ref p 1))
+244
(vector-set! p 4
+245
(if (= 3 (dbus-message-type message))
+246
(dbus-error (dbus-message-field message 4)
+247
(if (and (pair? (dbus-message-body message))
+248
(string? (car (dbus-message-body message))))
+249
(car (dbus-message-body message)) "Remote method error"))
+250
(dbus-message-body message)))
+251
(vector-set! p 3 #t)))
+252
(vector-ref c 2))
+253
(expire! c)))
+254
((4)
+255
(when (and (equal? bus-name (dbus-message-field message 7))
+256
(equal? bus-path (dbus-message-field message 1))
+257
(equal? bus-name (dbus-message-field message 2))
+258
(equal? "NameOwnerChanged" (dbus-message-field message 3))
+259
(string=? "sss" (dbus-message-signature message)))
+260
(let ((args (dbus-message-body message)))
+261
(for-each
+262
(lambda (subscription)
+263
(let ((sender (assoc 'sender (vector-ref subscription 0))))
+264
(when (and (vector-ref subscription 3) sender (string=? (cdr sender) (car args)))
+265
(vector-set! subscription 4 (caddr args)))))
+266
(vector-ref c 3))))
+267
(when (and (equal? bus-name (dbus-message-field message 7))
+268
(equal? bus-path (dbus-message-field message 1))
+269
(equal? bus-name (dbus-message-field message 2))
+270
(string=? "s" (dbus-message-signature message)))
+271
(let ((name (car (dbus-message-body message))))
+272
(cond
+273
((equal? "NameAcquired" (dbus-message-field message 3))
+274
(unless (member name (vector-ref c 6))
+275
(vector-set! c 6 (cons name (vector-ref c 6)))))
+276
((equal? "NameLost" (dbus-message-field message 3))
+277
(vector-set! c 6 (remove-if (lambda (n) (string=? n name)) (vector-ref c 6)))))))
+278
(for-each
+279
(lambda (subscription)
+280
(when (matches? (vector-ref subscription 0) message (vector-ref subscription 4))
+281
(safe-callback c (lambda () ((vector-ref subscription 1) message)))))
+282
(vector-ref c 3)))
+283
((1)
+284
(if (>= (vector-ref c 8) 64)
+285
(dbus-send-reply! c message ""
+286
(dbus-error "org.freedesktop.DBus.Error.LimitsExceeded" "Too many active handlers"))
+287
(safe-callback c
+288
(lambda ()
+289
(if (vector-ref c 4)
+290
((vector-ref c 4) c message)
+291
(dbus-send-reply! c message ""
+292
(dbus-error "org.freedesktop.DBus.Error.UnknownObject" "No exported object")))))))))
+293
+294
(define (dbus-pump! c (keys: (timeout-ms 100)))
+295
(expire! c)
+296
(cond
+297
((dbus-closed? c) #f)
+298
((vector-ref c 7) (sleep (min 0.001 (/ timeout-ms 1000))) #f)
+299
(else
+300
(let ((message
+301
(dynamic-wind
+302
(lambda () (vector-set! c 7 #t))
+303
(lambda ()
+304
(guard (e (else (if (dbus-closed? c) #f
+305
(begin (dbus-close! c) (raise e)))))
+306
(dbus-transport-read! (vector-ref c 0) timeout-ms: timeout-ms)))
+307
(lambda () (vector-set! c 7 #f)))))
+308
(when message
+309
(when (and (dbus-message-field message 9) (> (dbus-message-field message 9) 0))
+310
(dbus-close! c)
+311
(error "D-Bus Unix file descriptors were not negotiated"))
+312
(dispatch! c message))
+313
(expire! c)
+314
message))))
+315
+316
(define (dbus-run! c)
+317
(let loop ()
+318
(unless (dbus-closed? c)
+319
(dbus-pump! c)
+320
(loop))))))
src/sigil/dbus/message.sgladded
@@ -0,0 +1,130 @@
+1
(define-library (sigil dbus message)
+2
(import (sigil dbus types) (sigil dbus wire))
+3
(export dbus-message dbus-message? dbus-message-type dbus-message-flags
+4
dbus-message-serial dbus-message-fields dbus-message-signature
+5
dbus-message-body dbus-message-field dbus-encode-message dbus-decode-message
+6
dbus-frame-size)
+7
(begin
+8
;; Specification: Message Format, header field codes 1 through 9.
+9
;; All fields are explicitly typed variants; unknown codes are retained.
+10
(define field-types '((1 . "o") (2 . "s") (3 . "s") (4 . "s")
+11
(5 . "u") (6 . "s") (7 . "s") (8 . "g") (9 . "u")))
+12
+13
(define (dbus-message type serial fields signature body (keys: (flags 0)))
+14
(vector 'dbus-message type flags serial fields signature body))
+15
(define (dbus-message? m)
+16
(and (vector? m) (= 7 (vector-length m)) (eq? 'dbus-message (vector-ref m 0))))
+17
(define (dbus-message-type m) (vector-ref m 1))
+18
(define (dbus-message-flags m) (vector-ref m 2))
+19
(define (dbus-message-serial m) (vector-ref m 3))
+20
(define (dbus-message-fields m) (vector-ref m 4))
+21
(define (dbus-message-signature m) (vector-ref m 5))
+22
(define (dbus-message-body m) (vector-ref m 6))
+23
(define (dbus-message-field m code)
+24
(let ((entry (assv code (dbus-message-fields m))))
+25
(and entry (dbus-variant-value (cdr entry)))))
+26
+27
(define (validate m)
+28
(unless (and (integer? (dbus-message-type m)) (< 0 (dbus-message-type m) 256)
+29
(integer? (dbus-message-serial m))
+30
(<= 1 (dbus-message-serial m) 4294967295)
+31
(integer? (dbus-message-flags m)) (<= 0 (dbus-message-flags m) 255))
+32
(error "Invalid D-Bus message header"))
+33
(let loop ((fields (dbus-message-fields m)) (seen '()))
+34
(unless (null? fields)
+35
(let* ((entry (car fields)) (code (car entry)) (value (cdr entry))
+36
(known (assv code field-types)))
+37
(unless (and (integer? code) (<= 1 code 255) (dbus-variant? value))
+38
(error "Invalid D-Bus header field"))
+39
(when (memv code seen) (error "Duplicate D-Bus header field"))
+40
(when (and known (not (string=? (cdr known) (dbus-variant-signature value))))
+41
(error "D-Bus header field has wrong type"))
+42
(loop (cdr fields) (cons code seen)))))
+43
(for-each
+44
(lambda (entry)
+45
(let ((value (dbus-message-field m (car entry))))
+46
(when (and value (not ((cdr entry) value)))
+47
(error "Invalid D-Bus header field name" (car entry)))))
+48
(list (cons 1 dbus-object-path?) (cons 2 dbus-interface-name?)
+49
(cons 3 dbus-member-name?) (cons 4 dbus-interface-name?)
+50
(cons 6 dbus-bus-name?) (cons 7 dbus-bus-name?)
+51
(cons 5 (lambda (value) (> value 0)))))
+52
(for-each
+53
(lambda (code)
+54
(unless (dbus-message-field m code) (error "Missing required D-Bus header field" code)))
+55
(case (dbus-message-type m)
+56
((1) '(1 3)) ((2) '(5)) ((3) '(4 5)) ((4) '(1 2 3)) (else '()))))
+57
+58
(define (dbus-encode-message m (keys: (endianness dbus-native-endianness)
+59
(max-bytes dbus-max-message-size)))
+60
(validate m)
+61
(when (assv 8 (dbus-message-fields m))
+62
(error "Supply message signature separately from header fields"))
+63
(let* ((body (dbus-marshal (dbus-message-signature m) (dbus-message-body m)
+64
endianness: endianness max-bytes: max-bytes))
+65
(fields (append (dbus-message-fields m)
+66
(if (string=? "" (dbus-message-signature m)) '()
+67
(list (cons 8 (dbus-variant "g" (dbus-message-signature m)))))))
+68
(state (wire-writer endianness (min max-bytes dbus-max-message-size))))
+69
(wire-uint! state (if (eq? endianness 'little) 108 66) 1)
+70
(wire-uint! state (dbus-message-type m) 1)
+71
(wire-uint! state (dbus-message-flags m) 1)
+72
(wire-uint! state 1 1)
+73
(wire-uint! state (bytevector-length body) 4)
+74
(wire-uint! state (dbus-message-serial m) 4)
+75
(wire-put! state '(array (struct #\y #\v))
+76
(map (lambda (entry) (list (car entry) (cdr entry))) fields) 0 0 0)
+77
(wire-align! state 8)
+78
(let ((header (wire-finish state)))
+79
(when (> (+ (bytevector-length header) (bytevector-length body)) max-bytes)
+80
(error "D-Bus message byte limit"))
+81
(bytevector-append header body))))
+82
+83
;; This must run on the fixed 16-byte prefix before allocating a frame.
+84
(define (dbus-frame-size prefix (keys: (max-bytes dbus-max-message-size)))
+85
(unless (>= (bytevector-length prefix) 16) (error "Truncated D-Bus fixed header"))
+86
(let* ((order (case (bytevector-u8-ref prefix 0)
+87
((108) 'little) ((66) 'big) (else (error "Invalid D-Bus byte order"))))
+88
(state (wire-reader (bytevector-copy prefix 0 16) order 16 8)))
+89
(unless (= 1 (bytevector-u8-ref prefix 3)) (error "Unsupported D-Bus protocol version"))
+90
(when (= 0 (bytevector-u8-ref prefix 1)) (error "Invalid D-Bus message type"))
+91
(vector-set! state 1 4)
+92
(let* ((body-size (wire-read-uint! state 4))
+93
(serial (wire-read-uint! state 4))
+94
(fields-size (wire-read-uint! state 4))
+95
(header-end (+ 16 fields-size))
+96
(total (+ header-end (modulo (- header-end) 8) body-size)))
+97
(when (= serial 0) (error "D-Bus serial must be nonzero"))
+98
(unless (and (<= fields-size dbus-max-array-size)
+99
(<= total max-bytes dbus-max-message-size))
+100
(error "D-Bus frame byte limit"))
+101
total)))
+102
+103
(define (dbus-decode-message bytes (keys: (max-bytes dbus-max-message-size)
+104
(max-values 1000000)))
+105
(unless (= (bytevector-length bytes) (dbus-frame-size bytes max-bytes: max-bytes))
+106
(error "D-Bus frame length mismatch"))
+107
(let* ((order (if (= 108 (bytevector-u8-ref bytes 0)) 'little 'big))
+108
(state (wire-reader bytes order max-bytes max-values)))
+109
(vector-set! state 1 8)
+110
(let* ((serial (wire-read-uint! state 4))
+111
(fields (map (lambda (entry) (cons (car entry) (cadr entry)))
+112
(wire-get! state '(array (struct #\y #\v)) 0 0 0)))
+113
(signature-entry (assv 8 fields))
+114
(signature (if signature-entry (dbus-variant-value (cdr signature-entry)) ""))
+115
(m (dbus-message (bytevector-u8-ref bytes 1) serial fields signature '()
+116
flags: (bytevector-u8-ref bytes 2))))
+117
(validate m)
+118
(dbus-parse-signature signature)
+119
(wire-align! state 8)
+120
(let ((body (map (lambda (type) (wire-get! state type 0 0 0))
+121
(dbus-parse-signature signature))))
+122
(unless (= (wire-position state) (bytevector-length bytes))
+123
(error "Trailing D-Bus message bytes"))
+124
;; Signature is represented once, outside the public field table.
+125
(vector-set! m 4 (let loop ((rest fields))
+126
(cond ((null? rest) '())
+127
((= 8 (caar rest)) (loop (cdr rest)))
+128
(else (cons (car rest) (loop (cdr rest)))))))
+129
(vector-set! m 6 body)
+130
m))))))
src/sigil/dbus/service.sgladded
@@ -0,0 +1,231 @@
+1
(define-library (sigil dbus service)
+2
(import (sigil dbus types) (sigil dbus wire) (sigil dbus message)
+3
(sigil dbus connection) (sigil string))
+4
(export dbus-method dbus-property dbus-signal dbus-interface
+5
dbus-export! dbus-unexport! dbus-introspect dbus-properties-changed!)
+6
(begin
+7
(define properties-interface "org.freedesktop.DBus.Properties")
+8
(define introspect-interface "org.freedesktop.DBus.Introspectable")
+9
(define peer-interface "org.freedesktop.DBus.Peer")
+10
+11
(define (dbus-method name input output handler)
+12
(unless (and (dbus-member-name? name) (procedure? handler))
+13
(error "Invalid D-Bus method descriptor"))
+14
(dbus-parse-signature input)
+15
(dbus-parse-signature output)
+16
(vector name input output handler))
+17
+18
(define (dbus-property name signature getter (keys: (setter #f)))
+19
(unless (and (dbus-member-name? name)
+20
(= 1 (length (dbus-parse-signature signature)))
+21
(or (not getter) (procedure? getter))
+22
(or (not setter) (procedure? setter))
+23
(or getter setter))
+24
(error "Invalid D-Bus property descriptor"))
+25
(vector name signature getter setter))
+26
+27
(define (dbus-signal name signature)
+28
(unless (dbus-member-name? name) (error "Invalid D-Bus signal name"))
+29
(dbus-parse-signature signature)
+30
(vector name signature))
+31
+32
(define (unique-members! members)
+33
(let loop ((rest members) (seen '()))
+34
(unless (null? rest)
+35
(let ((name (vector-ref (car rest) 0)))
+36
(when (member name seen) (error "Duplicate D-Bus interface member" name))
+37
(loop (cdr rest) (cons name seen))))))
+38
+39
(define (dbus-interface name (keys: (methods '()) (properties '()) (signals '())))
+40
(unless (dbus-interface-name? name) (error "Invalid D-Bus interface name"))
+41
(for-each unique-members! (list methods properties signals))
+42
(vector name methods properties signals))
+43
+44
(define (find-named name descriptors)
+45
(cond ((null? descriptors) #f)
+46
((equal? name (vector-ref (car descriptors) 0)) (car descriptors))
+47
(else (find-named name (cdr descriptors)))))
+48
+49
(define (dbus-export! c path interfaces)
+50
(unless (dbus-object-path? path) (error "Invalid D-Bus export path"))
+51
(unique-members! interfaces)
+52
(when (assoc path (dbus-connection-objects c)) (error "D-Bus path already exported"))
+53
(for-each
+54
(lambda (interface)
+55
(when (member (vector-ref interface 0)
+56
(list properties-interface introspect-interface peer-interface))
+57
(error "Standard D-Bus interfaces are provided automatically")))
+58
interfaces)
+59
(dbus-set-connection-objects! c (cons (cons path interfaces) (dbus-connection-objects c)))
+60
(dbus-set-dispatcher! c dispatch-call!)
+61
#t)
+62
+63
(define (dbus-unexport! c path)
+64
(dbus-set-connection-objects! c
+65
(let loop ((objects (dbus-connection-objects c)))
+66
(cond ((null? objects) '())
+67
((string=? path (caar objects)) (loop (cdr objects)))
+68
(else (cons (car objects) (loop (cdr objects))))))))
+69
+70
(define (xml text)
+71
(apply string-append
+72
(map (lambda (c)
+73
(case c ((#\&) "&amp;") ((#\<) "&lt;") ((#\>) "&gt;")
+74
((#\") "&quot;") ((#\') "&apos;") (else (string c))))
+75
(string->list text))))
+76
+77
(define (arguments-xml signature direction)
+78
(apply string-append
+79
(map (lambda (type)
+80
(string-append "<arg type=\"" (xml (dbus-type-signature type)) "\""
+81
(if direction (string-append " direction=\"" direction "\"") "") "/>"))
+82
(dbus-parse-signature signature))))
+83
+84
(define (interface-xml interface)
+85
(string-append
+86
"<interface name=\"" (xml (vector-ref interface 0)) "\">"
+87
(apply string-append
+88
(map (lambda (method)
+89
(string-append "<method name=\"" (xml (vector-ref method 0)) "\">"
+90
(arguments-xml (vector-ref method 1) "in")
+91
(arguments-xml (vector-ref method 2) "out") "</method>"))
+92
(vector-ref interface 1)))
+93
(apply string-append
+94
(map (lambda (property)
+95
(string-append "<property name=\"" (xml (vector-ref property 0))
+96
"\" type=\"" (xml (vector-ref property 1)) "\" access=\""
+97
(cond ((and (vector-ref property 2) (vector-ref property 3)) "readwrite")
+98
((vector-ref property 2) "read") (else "write"))
+99
"\"><annotation name=\"org.freedesktop.DBus.Property.EmitsChangedSignal\" value=\"true\"/></property>"))
+100
(vector-ref interface 2)))
+101
(apply string-append
+102
(map (lambda (signal)
+103
(string-append "<signal name=\"" (xml (vector-ref signal 0)) "\">"
+104
(arguments-xml (vector-ref signal 1) #f) "</signal>"))
+105
(vector-ref interface 3)))
+106
"</interface>"))
+107
+108
(define (standard-interfaces)
+109
(list
+110
(dbus-interface peer-interface methods: (list (dbus-method "Ping" "" "" (lambda () '()))))
+111
(dbus-interface introspect-interface methods: (list (dbus-method "Introspect" "" "s" (lambda () '()))))
+112
(dbus-interface properties-interface
+113
methods: (list (dbus-method "Get" "ss" "v" (lambda () '()))
+114
(dbus-method "Set" "ssv" "" (lambda () '()))
+115
(dbus-method "GetAll" "s" "a{sv}" (lambda () '())))
+116
signals: (list (dbus-signal "PropertiesChanged" "sa{sv}as")))))
+117
+118
(define (dbus-introspect c path)
+119
(let ((object (assoc path (dbus-connection-objects c))))
+120
(unless object (error "Unknown D-Bus object path"))
+121
(string-append "<node name=\"" (xml path) "\">"
+122
(apply string-append (map interface-xml (append (cdr object) (standard-interfaces))))
+123
"</node>")))
+124
+125
(define (failure name message)
+126
(raise (dbus-error (string-append "org.freedesktop.DBus.Error." name) message)))
+127
+128
(define (expect-signature call expected)
+129
(unless (string=? expected (dbus-message-signature call))
+130
(failure "InvalidArgs" "Method input signature does not match")))
+131
+132
(define (property-interface object name)
+133
(or (find-named name (cdr object)) (failure "UnknownInterface" "No such property interface")))
+134
+135
(define (lookup-property interface name)
+136
(or (find-named name (vector-ref interface 2)) (failure "UnknownProperty" "No such property")))
+137
+138
(define (get-property property)
+139
(unless (vector-ref property 2) (failure "AccessDenied" "Property is not readable"))
+140
(let ((value ((vector-ref property 2))))
+141
(when (dbus-error? value) (raise value))
+142
(dbus-variant (vector-ref property 1) value)))
+143
+144
(define (dbus-properties-changed! c path interface-name changed (keys: (invalidated '())))
+145
(let* ((object (or (assoc path (dbus-connection-objects c))
+146
(error "Unknown D-Bus object path")))
+147
(interface (property-interface object interface-name)))
+148
(for-each
+149
(lambda (entry)
+150
(let ((property (lookup-property interface (car entry))))
+151
(unless (and (dbus-variant? (cdr entry))
+152
(string=? (vector-ref property 1) (dbus-variant-signature (cdr entry))))
+153
(error "PropertiesChanged signature mismatch"))))
+154
changed)
+155
(for-each (lambda (name) (lookup-property interface name)) invalidated)
+156
(dbus-send-signal! c path properties-interface "PropertiesChanged" "sa{sv}as"
+157
(list interface-name changed invalidated))))
+158
+159
(define (dispatch-properties c object call)
+160
(let ((member (dbus-message-field call 3)) (args (dbus-message-body call)))
+161
(cond
+162
((string=? member "Get")
+163
(expect-signature call "ss")
+164
(let* ((interface (property-interface object (car args)))
+165
(property (lookup-property interface (cadr args))))
+166
(cons "v" (list (get-property property)))))
+167
((string=? member "GetAll")
+168
(expect-signature call "s")
+169
(let ((interface (property-interface object (car args))))
+170
(cons "a{sv}"
+171
(list (let loop ((properties (vector-ref interface 2)))
+172
(cond ((null? properties) '())
+173
((not (vector-ref (car properties) 2)) (loop (cdr properties)))
+174
(else (cons (cons (vector-ref (car properties) 0)
+175
(get-property (car properties)))
+176
(loop (cdr properties))))))))))
+177
((string=? member "Set")
+178
(expect-signature call "ssv")
+179
(let* ((interface (property-interface object (car args)))
+180
(property (lookup-property interface (cadr args)))
+181
(typed-value (caddr args)))
+182
(unless (vector-ref property 3) (failure "PropertyReadOnly" "Property is read-only"))
+183
(unless (string=? (vector-ref property 1) (dbus-variant-signature typed-value))
+184
(failure "InvalidArgs" "Property variant has wrong type"))
+185
(let ((result ((vector-ref property 3) (dbus-variant-value typed-value))))
+186
(when (dbus-error? result) (raise result)))
+187
(dbus-properties-changed! c (car object) (car args)
+188
(if (vector-ref property 2)
+189
(list (cons (cadr args) (get-property property))) '())
+190
invalidated: (if (vector-ref property 2) '() (list (cadr args))))
+191
(cons "" '())))
+192
(else (failure "UnknownMethod" "No such Properties method")))))
+193
+194
(define (invoke c call)
+195
(let* ((path (dbus-message-field call 1))
+196
(object (or (assoc path (dbus-connection-objects c))
+197
(failure "UnknownObject" "No such object")))
+198
(interface-name (dbus-message-field call 2))
+199
(member (dbus-message-field call 3)))
+200
(cond
+201
((equal? interface-name peer-interface)
+202
(unless (string=? member "Ping") (failure "UnknownMethod" "No such Peer method"))
+203
(expect-signature call "")
+204
(cons "" '()))
+205
((equal? interface-name introspect-interface)
+206
(unless (string=? member "Introspect") (failure "UnknownMethod" "No such introspection method"))
+207
(expect-signature call "")
+208
(cons "s" (list (dbus-introspect c path))))
+209
((equal? interface-name properties-interface) (dispatch-properties c object call))
+210
(else
+211
(let* ((interface (or (find-named interface-name (cdr object))
+212
(failure "UnknownInterface" "Specify an exported interface")))
+213
(method (or (find-named member (vector-ref interface 1))
+214
(failure "UnknownMethod" "No such method"))))
+215
(expect-signature call (vector-ref method 1))
+216
(let ((result (apply (vector-ref method 3) (dbus-message-body call))))
+217
(when (dbus-error? result) (raise result))
+218
(cons (vector-ref method 2) result)))))))
+219
+220
(define (dispatch-call! c call)
+221
(let ((reply
+222
(guard (e (else (if (dbus-error? e) e
+223
(dbus-error "org.freedesktop.DBus.Error.Failed" "Method handler failed"))))
+224
(let ((reply (invoke c call)))
+225
;; Validate handler output while exceptions can still turn
+226
;; into a single Failed reply; never emit a partial frame.
+227
(dbus-marshal (car reply) (cdr reply))
+228
reply))))
+229
(if (dbus-error? reply)
+230
(dbus-send-reply! c call "" reply)
+231
(dbus-send-reply! c call (car reply) (cdr reply)))))))
src/sigil/dbus/transport.sgladded
@@ -0,0 +1,204 @@
+1
(define-library (sigil dbus transport)
+2
(import (sigil socket) (sigil async) (sigil time) (sigil process)
+3
(sigil string) (sigil io) (sigil dbus message))
+4
(export dbus-open-transport dbus-close-transport! dbus-transport-read!
+5
dbus-transport-write! dbus-transport-closed? dbus-parse-address
+6
dbus-deadline dbus-remaining-ms)
+7
(begin
+8
(define (dbus-deadline timeout-ms)
+9
(unless (and (real? timeout-ms) (<= 0 timeout-ms 3600000))
+10
(error "D-Bus timeout must be between 0 and 3600000 milliseconds"))
+11
(+ (current-jiffy) (* (/ timeout-ms 1000) (jiffies-per-second))))
+12
+13
(define (dbus-remaining-ms deadline)
+14
(max 0 (* 1000 (/ (- deadline (current-jiffy)) (jiffies-per-second)))))
+15
+16
(define (percent-decode value)
+17
(let* ((bytes (string->utf8 value)) (n (bytevector-length bytes))
+18
(result (make-bytevector n)))
+19
(let loop ((i 0) (j 0))
+20
(if (= i n)
+21
(let ((text (utf8->string (bytevector-copy result 0 j))))
+22
(when (string-index text (integer->char 0)) (error "NUL in D-Bus address"))
+23
text)
+24
(let ((byte (bytevector-u8-ref bytes i)))
+25
(if (= byte 37)
+26
(begin
+27
(when (> (+ i 3) n) (error "Truncated D-Bus address escape"))
+28
(for-each
+29
(lambda (index)
+30
(let ((digit (bytevector-u8-ref bytes index)))
+31
(unless (or (<= 48 digit 57) (<= 65 digit 70) (<= 97 digit 102))
+32
(error "Invalid D-Bus address escape"))))
+33
(list (+ i 1) (+ i 2)))
+34
(let ((decoded (string->number
+35
(utf8->string (bytevector-copy bytes (+ i 1) (+ i 3))) 16)))
+36
(unless (and decoded (integer? decoded) (<= 0 decoded 255))
+37
(error "Invalid D-Bus address escape"))
+38
(bytevector-u8-set! result j decoded)
+39
(loop (+ i 3) (+ j 1))))
+40
(begin
+41
(bytevector-u8-set! result j byte)
+42
(loop (+ i 1) (+ j 1)))))))))
+43
+44
(define (dbus-parse-address address)
+45
(map
+46
(lambda (entry)
+47
(let ((colon (string-index entry #\:)))
+48
(unless colon (error "Invalid D-Bus address"))
+49
(cons (substring entry 0 colon)
+50
(map
+51
(lambda (part)
+52
(let ((equals (string-index part #\=)))
+53
(unless equals (error "Invalid D-Bus address option"))
+54
(cons (substring part 0 equals)
+55
(percent-decode (substring part (+ equals 1) (string-length part))))))
+56
(string-split (substring entry (+ colon 1) (string-length entry)) ",")))))
+57
(string-split address ";")))
+58
+59
;; Transport: socket, partial frame, filled bytes, fixed-header?, max bytes,
+60
;; write lock. One reader is coordinated by the connection's pump.
+61
(define (dbus-transport-closed? transport)
+62
(socket-closed? (vector-ref transport 0)))
+63
+64
(define (dbus-close-transport! transport)
+65
(socket-close (vector-ref transport 0)))
+66
+67
(define (dbus-transport-write! transport bytes (keys: (timeout-ms 25000)))
+68
(let ((deadline (dbus-deadline timeout-ms)) (sock (vector-ref transport 0)))
+69
(let acquire ()
+70
(when (dbus-transport-closed? transport) (error "D-Bus connection closed"))
+71
(when (<= (dbus-remaining-ms deadline) 0) (error "D-Bus write timeout"))
+72
(when (vector-ref transport 5)
+73
(sleep 0.001)
+74
(acquire)))
+75
(vector-set! transport 5 #t)
+76
(dynamic-wind
+77
(lambda () #t)
+78
(lambda ()
+79
(guard (e (else (dbus-close-transport! transport) (raise e)))
+80
(let loop ((offset 0))
+81
(when (< offset (bytevector-length bytes))
+82
(when (<= (dbus-remaining-ms deadline) 0) (error "D-Bus write timeout"))
+83
;; Public socket-write returns #f for EAGAIN as well as
+84
;; other send errors. Retry with a bounded cooperative wait.
+85
(let ((sent (socket-write sock bytes offset
+86
(min (bytevector-length bytes) (+ offset 65536)))))
+87
(if (or (not sent) (= sent 0))
+88
(begin (sleep 0.001) (loop offset))
+89
(loop (+ offset sent))))))))
+90
(lambda () (vector-set! transport 5 #f)))))
+91
+92
(define (read-byte-until sock deadline)
+93
(let loop ()
+94
(when (<= (dbus-remaining-ms deadline) 0) (error "D-Bus authentication timeout"))
+95
(let ((bytes (socket-read-bytevector sock 1)))
+96
(cond
+97
((not bytes) (error "D-Bus authentication read failed"))
+98
((eof-object? bytes) (error "D-Bus authentication EOF"))
+99
((= 0 (bytevector-length bytes))
+100
(await-readable-any (list sock) timeout-ms: (dbus-remaining-ms deadline))
+101
(loop))
+102
(else (bytevector-u8-ref bytes 0))))))
+103
+104
(define (auth-line sock deadline)
+105
(let loop ((bytes '()) (length 0))
+106
(when (>= length 4096) (error "Oversized D-Bus authentication line"))
+107
(let ((byte (read-byte-until sock deadline)))
+108
(if (= byte 10)
+109
(begin
+110
(unless (and (pair? bytes) (= 13 (car bytes)))
+111
(error "Invalid D-Bus authentication line ending"))
+112
(utf8->string (apply bytevector (reverse (cdr bytes)))))
+113
(loop (cons byte bytes) (+ length 1))))))
+114
+115
(define (authenticate! transport uid timeout-ms guid)
+116
(let* ((sock (vector-ref transport 0)) (deadline (dbus-deadline timeout-ms))
+117
(identity (if uid (number->string uid) (process-output->string "id" "-u")))
+118
(hex (apply string-append
+119
(map (lambda (c)
+120
(let ((h (number->string (char->integer c) 16)))
+121
(if (= 1 (string-length h)) (string-append "0" h) h)))
+122
(string->list identity)))))
+123
(unless (and (> (string-length identity) 0)
+124
(let loop ((cs (string->list identity)))
+125
(or (null? cs)
+126
(and (char<=? #\0 (car cs)) (char<=? (car cs) #\9)
+127
(loop (cdr cs))))))
+128
(error "Invalid EXTERNAL authorization identity"))
+129
;; Specification: Special credentials-passing NUL and EXTERNAL.
+130
(dbus-transport-write! transport
+131
(bytevector-append (bytevector 0) (string->utf8 (string-append "AUTH EXTERNAL " hex "\r\n")))
+132
timeout-ms: (dbus-remaining-ms deadline))
+133
(let ((reply (auth-line sock deadline)))
+134
(unless (and (= 35 (string-length reply)) (string-starts-with? reply "OK "))
+135
(error "D-Bus EXTERNAL authentication rejected" reply))
+136
(when (and guid (not (string=? guid (substring reply 3 35))))
+137
(error "D-Bus server GUID mismatch")))
+138
;; No descriptor passing is negotiated; h values remain wire indices.
+139
(dbus-transport-write! transport (string->utf8 "BEGIN\r\n")
+140
timeout-ms: (dbus-remaining-ms deadline))))
+141
+142
(define (dbus-open-transport address (keys: (uid #f) (timeout-ms 25000)
+143
(max-bytes 16777216)))
+144
(unless (<= 16 max-bytes 134217728) (error "Invalid D-Bus frame limit"))
+145
(let loop ((addresses (dbus-parse-address address)) (last-error #f))
+146
(when (null? addresses)
+147
(if last-error (raise last-error) (error "No supported D-Bus address")))
+148
(let* ((entry (car addresses)) (path (assoc "path" (cdr entry)))
+149
(abstract (assoc "abstract" (cdr entry))) (guid (assoc "guid" (cdr entry))))
+150
(cond
+151
((not (string=? "unix" (car entry))) (loop (cdr addresses) last-error))
+152
(abstract
+153
(loop (cdr addresses)
+154
(dbus-address-error)))
+155
((not path) (loop (cdr addresses) last-error))
+156
(else
+157
(let ((attempt
+158
(guard (e (else (cons #f e)))
+159
(let ((sock (unix-connect (cdr path) timeout-ms: timeout-ms)))
+160
(unless sock (error "Cannot connect to D-Bus Unix socket"))
+161
(socket-set-non-blocking! sock #t)
+162
(let ((transport (vector sock (make-bytevector 16) 0 #t max-bytes #f)))
+163
(guard (e (else (socket-close sock) (raise e)))
+164
(authenticate! transport uid timeout-ms (and guid (cdr guid)))
+165
(cons #t transport)))))))
+166
(if (car attempt) (cdr attempt) (loop (cdr addresses) (cdr attempt)))))))))
+167
+168
(define (dbus-address-error)
+169
(guard (e (else e))
+170
(error "unix:abstract requires abstract socket support in Sigil's public socket API")))
+171
+172
(define (dbus-transport-read! transport (keys: (timeout-ms 100)))
+173
(let ((deadline (dbus-deadline timeout-ms)) (sock (vector-ref transport 0)))
+174
(let loop ()
+175
(when (dbus-transport-closed? transport) (error "D-Bus connection closed"))
+176
(let* ((buffer (vector-ref transport 1)) (used (vector-ref transport 2))
+177
(remaining (- (bytevector-length buffer) used)))
+178
(cond
+179
((= remaining 0)
+180
(if (vector-ref transport 3)
+181
(let* ((size (dbus-frame-size buffer max-bytes: (vector-ref transport 4)))
+182
(frame (make-bytevector size)))
+183
(bytevector-copy! frame 0 buffer)
+184
(vector-set! transport 1 frame)
+185
(vector-set! transport 3 #f)
+186
(loop))
+187
(begin
+188
(vector-set! transport 1 (make-bytevector 16))
+189
(vector-set! transport 2 0)
+190
(vector-set! transport 3 #t)
+191
(dbus-decode-message buffer max-bytes: (vector-ref transport 4)))))
+192
((<= (dbus-remaining-ms deadline) 0) #f)
+193
(else
+194
(let ((chunk (socket-read-bytevector sock (min remaining 65536))))
+195
(cond
+196
((not chunk) (error "D-Bus socket read failed"))
+197
((eof-object? chunk) (error "D-Bus connection EOF"))
+198
((= 0 (bytevector-length chunk))
+199
(await-readable-any (list sock) timeout-ms: (dbus-remaining-ms deadline))
+200
(loop))
+201
(else
+202
(bytevector-copy! buffer used chunk)
+203
(vector-set! transport 2 (+ used (bytevector-length chunk)))
+204
(loop))))))))))))
src/sigil/dbus/types.sgladded
@@ -0,0 +1,140 @@
+1
(define-library (sigil dbus types)
+2
(export dbus-variant dbus-variant? dbus-variant-signature dbus-variant-value
+3
dbus-error dbus-error? dbus-error-name dbus-error-message
+4
dbus-parse-signature dbus-type-signature dbus-type-alignment
+5
dbus-object-path? dbus-interface-name? dbus-member-name? dbus-bus-name?)
+6
(begin
+7
(define (dbus-variant signature value)
+8
(unless (= 1 (length (dbus-parse-signature signature)))
+9
(error "D-Bus variant requires one complete type"))
+10
(vector 'dbus-variant signature value))
+11
+12
(define (dbus-variant? value)
+13
(and (vector? value)
+14
(= 3 (vector-length value))
+15
(eq? 'dbus-variant (vector-ref value 0))))
+16
+17
(define (dbus-variant-signature value) (vector-ref value 1))
+18
(define (dbus-variant-value value) (vector-ref value 2))
+19
+20
(define (dbus-error name message)
+21
(unless (dbus-interface-name? name)
+22
(error "Invalid D-Bus error name" name))
+23
(vector 'dbus-error name message))
+24
+25
(define (dbus-error? value)
+26
(and (vector? value)
+27
(= 3 (vector-length value))
+28
(eq? 'dbus-error (vector-ref value 0))))
+29
+30
(define (dbus-error-name value) (vector-ref value 1))
+31
(define (dbus-error-message value) (vector-ref value 2))
+32
+33
(define (ascii-letter? c)
+34
(or (and (char<=? #\a c) (char<=? c #\z)) (and (char<=? #\A c) (char<=? c #\Z))))
+35
+36
(define (digit? c) (and (char<=? #\0 c) (char<=? c #\9)))
+37
+38
(define (component? s allow-digit? allow-hyphen?)
+39
(and (> (string-length s) 0)
+40
(or allow-digit? (not (digit? (string-ref s 0))))
+41
(let loop ((i 0))
+42
(or (= i (string-length s))
+43
(let ((c (string-ref s i)))
+44
(and (or (ascii-letter? c) (digit? c) (char=? c #\_)
+45
(and allow-hyphen? (char=? c #\-)))
+46
(loop (+ i 1))))))))
+47
+48
(define (split-components s separator)
+49
(let loop ((i 0) (start 0) (parts '()))
+50
(cond
+51
((= i (string-length s))
+52
(reverse (cons (substring s start i) parts)))
+53
((char=? separator (string-ref s i))
+54
(loop (+ i 1) (+ i 1) (cons (substring s start i) parts)))
+55
(else (loop (+ i 1) start parts)))))
+56
+57
(define (components? parts digit? hyphen?)
+58
(or (null? parts)
+59
(and (component? (car parts) digit? hyphen?)
+60
(components? (cdr parts) digit? hyphen?))))
+61
+62
(define (dbus-object-path? s)
+63
(and (string? s) (> (string-length s) 0)
+64
(char=? #\/ (string-ref s 0))
+65
(or (string=? s "/")
+66
(components? (split-components (substring s 1 (string-length s)) #\/) #t #f))))
+67
+68
(define (dbus-member-name? s)
+69
(and (string? s) (<= (string-length s) 255)
+70
(component? s #f #f)))
+71
+72
(define (dbus-interface-name? s)
+73
(and (string? s) (<= (string-length s) 255)
+74
(let ((parts (split-components s #\.)))
+75
(and (> (length parts) 1) (components? parts #f #f)))))
+76
+77
(define (dbus-bus-name? s)
+78
(and (string? s) (> (string-length s) 0) (<= (string-length s) 255)
+79
(let* ((unique? (char=? #\: (string-ref s 0)))
+80
(parts (split-components (if unique? (substring s 1 (string-length s)) s) #\.)))
+81
(and (> (length parts) 1) (components? parts unique? #t)))))
+82
+83
;; D-Bus specification: Valid Signatures. Separate array/struct budgets
+84
;; are 32 each; dict entries are only legal as array elements.
+85
(define (dbus-parse-signature signature)
+86
(unless (and (string? signature) (<= (string-length signature) 255))
+87
(error "Invalid or oversized D-Bus signature"))
+88
(let ((i 0) (n (string-length signature)))
+89
(define (parse arrays structs dict-ok?)
+90
(when (or (>= i n) (> arrays 32) (> structs 32))
+91
(error "Truncated or deeply nested D-Bus signature"))
+92
(let ((c (string-ref signature i)))
+93
(set! i (+ i 1))
+94
(cond
+95
((memv c '(#\y #\b #\n #\q #\i #\u #\x #\t #\d #\s #\o #\g #\h #\v)) c)
+96
((char=? c #\a) (list 'array (parse (+ arrays 1) structs #t)))
+97
((or (char=? c #\() (char=? c #\{))
+98
(when (and (char=? c #\{) (not dict-ok?))
+99
(error "D-Bus dict entry outside array"))
+100
(when (>= structs 32) (error "D-Bus struct nesting limit"))
+101
(let ((end (if (char=? c #\() #\) #\})))
+102
(let loop ((members '()))
+103
(when (>= i n) (error "Unclosed D-Bus container"))
+104
(if (char=? end (string-ref signature i))
+105
(begin
+106
(set! i (+ i 1))
+107
(let ((members (reverse members)))
+108
(when (null? members) (error "Empty D-Bus struct"))
+109
(when (and (char=? c #\{)
+110
(or (not (= 2 (length members)))
+111
(not (char? (car members)))
+112
(char=? #\v (car members))))
+113
(error "Invalid D-Bus dictionary entry"))
+114
(cons (if (char=? c #\() 'struct 'dict) members)))
+115
(loop (cons (parse arrays (+ structs 1) #f) members))))))
+116
(else (error "Invalid D-Bus type code" c)))))
+117
(let loop ((types '()))
+118
(if (= i n)
+119
(reverse types)
+120
(loop (cons (parse 0 0 #f) types))))))
+121
+122
(define (dbus-type-signature type)
+123
(if (char? type)
+124
(string type)
+125
(case (car type)
+126
((array) (string-append "a" (dbus-type-signature (cadr type))))
+127
(else
+128
(string-append
+129
(if (eq? 'struct (car type)) "(" "{")
+130
(apply string-append (map dbus-type-signature (cdr type)))
+131
(if (eq? 'struct (car type)) ")" "}"))))))
+132
+133
(define (dbus-type-alignment type)
+134
(if (pair? type)
+135
(if (eq? 'array (car type)) 4 8)
+136
(cond
+137
((memv type '(#\y #\g #\v)) 1)
+138
((memv type '(#\n #\q)) 2)
+139
((memv type '(#\x #\t #\d)) 8)
+140
(else 4))))))
src/sigil/dbus/wire.sgladded
@@ -0,0 +1,305 @@
+1
(define-library (sigil dbus wire)
+2
(import (sigil dbus types) (sigil io))
+3
(export dbus-marshal dbus-unmarshal dbus-native-endianness
+4
dbus-max-message-size dbus-max-array-size
+5
wire-writer wire-reader wire-position wire-align! wire-put! wire-get!
+6
wire-uint! wire-read-uint! wire-finish wire-check! wire-limit!)
+7
(begin
+8
;; Specification: Message Format and Marshalling Containers.
+9
(define dbus-max-message-size 134217728)
+10
(define dbus-max-array-size 67108864)
+11
(define dbus-native-endianness
+12
(let ((bytes (make-bytevector 8 0)))
+13
(bytevector-ieee-double-set! bytes 0 1.0 'native)
+14
(if (= 0 (bytevector-u8-ref bytes 0)) 'little 'big)))
+15
+16
;; State: storage, cursor, byte order, byte limit, remaining value budget,
+17
;; writer?. Grow writers geometrically; check reader bounds before copies.
+18
(define (wire-writer order limit)
+19
(check-order order)
+20
(vector (make-bytevector (min 256 limit) 0) 0 order limit 1000000 #t))
+21
+22
(define (wire-reader bytes order limit budget)
+23
(check-order order)
+24
(unless (<= (bytevector-length bytes) limit dbus-max-message-size)
+25
(error "D-Bus message exceeds byte limit"))
+26
(vector bytes 0 order (bytevector-length bytes) budget #f))
+27
+28
(define (check-order order)
+29
(unless (memq order '(little big)) (error "Invalid D-Bus byte order")))
+30
+31
(define (wire-position state) (vector-ref state 1))
+32
(define (wire-limit! state limit) (vector-set! state 3 limit))
+33
+34
(define (wire-check! state count)
+35
(let ((end (+ (wire-position state) count)))
+36
(unless (<= end (vector-ref state 3))
+37
(error "Truncated or oversized D-Bus value"))
+38
(when (and (vector-ref state 5)
+39
(> end (bytevector-length (vector-ref state 0))))
+40
(let ((next (make-bytevector
+41
(min (vector-ref state 3)
+42
(max end (* 2 (bytevector-length (vector-ref state 0)))))
+43
0)))
+44
(bytevector-copy! next 0 (vector-ref state 0) 0 (wire-position state))
+45
(vector-set! state 0 next)))))
+46
+47
(define (byte! state byte)
+48
(wire-check! state 1)
+49
(bytevector-u8-set! (vector-ref state 0) (wire-position state) byte)
+50
(vector-set! state 1 (+ 1 (wire-position state))))
+51
+52
(define (read-byte! state)
+53
(wire-check! state 1)
+54
(let ((byte (bytevector-u8-ref (vector-ref state 0) (wire-position state))))
+55
(vector-set! state 1 (+ 1 (wire-position state)))
+56
byte))
+57
+58
;; Specification: Byte Order and Alignment. Alignment is relative to the
+59
;; beginning of the message, and padding bytes MUST be zero.
+60
(define (wire-align! state alignment)
+61
(let ((padding (modulo (- (wire-position state)) alignment)))
+62
(wire-check! state padding)
+63
(let loop ((n padding))
+64
(unless (= n 0)
+65
(if (vector-ref state 5)
+66
(byte! state 0)
+67
(unless (= 0 (read-byte! state))
+68
(error "Nonzero D-Bus padding")))
+69
(loop (- n 1))))))
+70
+71
(define (wire-uint! state value width)
+72
(unless (and (integer? value) (exact? value) (<= 0 value)
+73
(< value (expt 256 width)))
+74
(error "D-Bus integer outside its type range" value))
+75
(let loop ((i 0))
+76
(when (< i width)
+77
(let ((shift (if (eq? 'little (vector-ref state 2)) i (- width i 1))))
+78
(byte! state (modulo (quotient value (expt 256 shift)) 256)))
+79
(loop (+ i 1)))))
+80
+81
(define (wire-read-uint! state width)
+82
(wire-check! state width)
+83
(let loop ((i 0) (result 0))
+84
(if (= i width)
+85
result
+86
(let ((byte (read-byte! state)))
+87
(loop (+ i 1)
+88
(if (eq? 'little (vector-ref state 2))
+89
(+ result (* byte (expt 256 i)))
+90
(+ (* result 256) byte)))))))
+91
+92
(define (put-bytes! state bytes)
+93
(let ((n (bytevector-length bytes)))
+94
(wire-check! state n)
+95
(bytevector-copy! (vector-ref state 0) (wire-position state) bytes)
+96
(vector-set! state 1 (+ n (wire-position state)))))
+97
+98
(define (wire-finish state)
+99
(bytevector-copy (vector-ref state 0) 0 (wire-position state)))
+100
+101
(define (check-text text type)
+102
(unless (string? text) (error "D-Bus text requires a string"))
+103
(when (and (char=? type #\o) (not (dbus-object-path? text)))
+104
(error "Invalid D-Bus object path" text))
+105
(when (char=? type #\g) (dbus-parse-signature text)))
+106
+107
(define (check-utf8 bytes)
+108
(let ((n (bytevector-length bytes)))
+109
(let loop ((i 0))
+110
(when (< i n)
+111
(let* ((first (bytevector-u8-ref bytes i))
+112
(width (cond ((< first 128) 1)
+113
((<= 194 first 223) 2)
+114
((<= 224 first 239) 3)
+115
((<= 240 first 244) 4)
+116
(else (error "Invalid D-Bus UTF-8 leading byte")))))
+117
(when (= first 0) (error "NUL in D-Bus string"))
+118
(when (> (+ i width) n) (error "Truncated D-Bus UTF-8"))
+119
(let continuation ((j 1))
+120
(when (< j width)
+121
(unless (<= 128 (bytevector-u8-ref bytes (+ i j)) 191)
+122
(error "Invalid D-Bus UTF-8 continuation"))
+123
(continuation (+ j 1))))
+124
(when (> width 1)
+125
(let ((second (bytevector-u8-ref bytes (+ i 1))))
+126
(when (or (and (= first 224) (< second 160))
+127
(and (= first 237) (>= second 160))
+128
(and (= first 240) (< second 144))
+129
(and (= first 244) (> second 143)))
+130
(error "Non-scalar or overlong D-Bus UTF-8"))))
+131
(loop (+ i width)))))))
+132
+133
(define (put-text! state text type)
+134
(check-text text type)
+135
(let ((bytes (string->utf8 text)))
+136
(check-utf8 bytes)
+137
(wire-uint! state (bytevector-length bytes) (if (char=? type #\g) 1 4))
+138
(put-bytes! state bytes)
+139
(byte! state 0)))
+140
+141
(define (read-text! state type)
+142
(let ((n (wire-read-uint! state (if (char=? type #\g) 1 4))))
+143
(wire-check! state (+ n 1))
+144
(let* ((start (wire-position state))
+145
(bytes (bytevector-copy (vector-ref state 0) start (+ start n)))
+146
(checked (check-utf8 bytes))
+147
(text (utf8->string bytes)))
+148
(vector-set! state 1 (+ start n))
+149
(unless (= 0 (read-byte! state)) (error "Missing D-Bus string terminator"))
+150
(check-text text type)
+151
text)))
+152
+153
(define (integer-width type)
+154
(cond
+155
((char=? type #\y) 1)
+156
((memv type '(#\n #\q)) 2)
+157
((memv type '(#\x #\t)) 8)
+158
(else 4)))
+159
+160
(define (signed? type) (memv type '(#\n #\i #\x)))
+161
+162
(define (check-depth depth arrays structs)
+163
(when (or (> depth 64) (> arrays 32) (> structs 32))
+164
(error "D-Bus container nesting limit")))
+165
+166
(define (wire-put! state type value depth arrays structs)
+167
(check-depth depth arrays structs)
+168
(wire-align! state (dbus-type-alignment type))
+169
(cond
+170
((pair? type)
+171
(case (car type)
+172
((array)
+173
(when (>= arrays 32) (error "D-Bus array nesting limit"))
+174
(let* ((element (cadr type))
+175
(length-at (wire-position state)))
+176
(wire-uint! state 0 4)
+177
(wire-align! state (dbus-type-alignment element))
+178
(let ((start (wire-position state)))
+179
(if (and (eqv? element #\y) (bytevector? value))
+180
(put-bytes! state value)
+181
(begin
+182
(unless (list? value) (error "D-Bus array requires a list"))
+183
(for-each
+184
(lambda (item)
+185
(wire-put! state element item (+ depth 1) (+ arrays 1) structs))
+186
value)))
+187
(let ((end (wire-position state)))
+188
(when (> (- end start) dbus-max-array-size)
+189
(error "D-Bus array byte limit"))
+190
(vector-set! state 1 length-at)
+191
(wire-uint! state (- end start) 4)
+192
(vector-set! state 1 end)))))
+193
(else
+194
(when (>= structs 32) (error "D-Bus struct nesting limit"))
+195
(let ((members (if (eq? 'dict (car type))
+196
(begin
+197
(unless (pair? value) (error "D-Bus dict entry requires a pair"))
+198
(list (car value) (cdr value)))
+199
value)))
+200
(unless (and (list? members) (= (length members) (length (cdr type))))
+201
(error "D-Bus struct arity mismatch"))
+202
(for-each
+203
(lambda (t v) (wire-put! state t v (+ depth 1) arrays (+ structs 1)))
+204
(cdr type) members)))))
+205
((char=? type #\v)
+206
(unless (dbus-variant? value) (error "D-Bus variant requires an explicit signature"))
+207
(put-text! state (dbus-variant-signature value) #\g)
+208
(wire-put! state (car (dbus-parse-signature (dbus-variant-signature value)))
+209
(dbus-variant-value value) (+ depth 1) arrays structs))
+210
((memv type '(#\s #\o #\g)) (put-text! state value type))
+211
((char=? type #\b)
+212
(unless (boolean? value) (error "D-Bus boolean requires #t or #f"))
+213
(wire-uint! state (if value 1 0) 4))
+214
((char=? type #\d)
+215
(unless (real? value) (error "D-Bus double requires a real number"))
+216
(wire-check! state 8)
+217
(bytevector-ieee-double-set! (vector-ref state 0) (wire-position state)
+218
value (vector-ref state 2))
+219
(vector-set! state 1 (+ 8 (wire-position state))))
+220
(else
+221
(let* ((width (integer-width type)) (modulus (expt 256 width)))
+222
(when (signed? type)
+223
(unless (and (integer? value) (exact? value)
+224
(<= (- (quotient modulus 2)) value)
+225
(< value (quotient modulus 2)))
+226
(error "Signed D-Bus integer outside its type range"))
+227
(set! value (modulo value modulus)))
+228
(wire-uint! state value width)))))
+229
+230
(define (wire-get! state type depth arrays structs)
+231
(check-depth depth arrays structs)
+232
(when (<= (vector-ref state 4) 0) (error "D-Bus decoded value budget exceeded"))
+233
(vector-set! state 4 (- (vector-ref state 4) 1))
+234
(wire-align! state (dbus-type-alignment type))
+235
(cond
+236
((pair? type)
+237
(case (car type)
+238
((array)
+239
(when (>= arrays 32) (error "D-Bus array nesting limit"))
+240
(let ((n (wire-read-uint! state 4)) (element (cadr type)))
+241
(when (> n dbus-max-array-size) (error "D-Bus array byte limit"))
+242
(wire-align! state (dbus-type-alignment element))
+243
(wire-check! state n)
+244
(let ((end (+ (wire-position state) n)) (old-limit (vector-ref state 3)))
+245
(wire-limit! state end)
+246
(let ((result
+247
(if (eqv? element #\y)
+248
(let ((bytes (bytevector-copy (vector-ref state 0) (wire-position state) end)))
+249
(vector-set! state 1 end)
+250
bytes)
+251
(let loop ((items '()))
+252
(if (= end (wire-position state))
+253
(reverse items)
+254
(loop (cons (wire-get! state element (+ depth 1) (+ arrays 1) structs)
+255
items)))))))
+256
(wire-limit! state old-limit)
+257
result))))
+258
(else
+259
(when (>= structs 32) (error "D-Bus struct nesting limit"))
+260
(let ((members
+261
(map (lambda (t) (wire-get! state t (+ depth 1) arrays (+ structs 1)))
+262
(cdr type))))
+263
(if (eq? 'dict (car type)) (cons (car members) (cadr members)) members)))))
+264
((char=? type #\v)
+265
(let* ((signature (read-text! state #\g))
+266
(types (dbus-parse-signature signature)))
+267
(unless (= 1 (length types)) (error "Invalid D-Bus variant signature"))
+268
(dbus-variant signature (wire-get! state (car types) (+ depth 1) arrays structs))))
+269
((memv type '(#\s #\o #\g)) (read-text! state type))
+270
((char=? type #\b)
+271
(let ((value (wire-read-uint! state 4)))
+272
(unless (or (= value 0) (= value 1)) (error "Invalid D-Bus boolean"))
+273
(= value 1)))
+274
((char=? type #\d)
+275
(wire-check! state 8)
+276
(let ((value (bytevector-ieee-double-ref (vector-ref state 0) (wire-position state)
+277
(vector-ref state 2))))
+278
(vector-set! state 1 (+ 8 (wire-position state)))
+279
value))
+280
(else
+281
(let* ((width (integer-width type))
+282
(value (wire-read-uint! state width))
+283
(modulus (expt 256 width)))
+284
(if (and (signed? type) (>= value (quotient modulus 2)))
+285
(- value modulus)
+286
value)))))
+287
+288
(define (dbus-marshal signature values
+289
(keys: (endianness dbus-native-endianness)
+290
(max-bytes dbus-max-message-size)))
+291
(let ((types (dbus-parse-signature signature))
+292
(state (wire-writer endianness (min max-bytes dbus-max-message-size))))
+293
(unless (= (length types) (length values)) (error "D-Bus body arity mismatch"))
+294
(for-each (lambda (type value) (wire-put! state type value 0 0 0)) types values)
+295
(wire-finish state)))
+296
+297
(define (dbus-unmarshal signature bytes
+298
(keys: (endianness dbus-native-endianness)
+299
(max-bytes dbus-max-message-size) (max-values 1000000)))
+300
(let* ((state (wire-reader bytes endianness max-bytes max-values))
+301
(values (map (lambda (type) (wire-get! state type 0 0 0))
+302
(dbus-parse-signature signature))))
+303
(unless (= (wire-position state) (bytevector-length bytes))
+304
(error "Trailing bytes after D-Bus body"))
+305
values))))
test/test-integration.sgladded
@@ -0,0 +1,199 @@
+1
(import (sigil dbus) (sigil async) (sigil process) (sigil string)
+2
(sigil time) (sigil test))
+3
+4
(define bus "org.freedesktop.DBus")
+5
(define bus-path "/org/freedesktop/DBus")
+6
(define service-name "org.example.SigilTest")
+7
(define path "/org/example/Test")
+8
(define iface "org.example.Test")
+9
(define props "org.freedesktop.DBus.Properties")
+10
+11
(with-async
+12
(let ((server (dbus-connect-session)) (client (dbus-connect-system))
+13
(counter 7) (seen '()) (ownership-events '()))
+14
(dynamic-wind
+15
(lambda () #t)
+16
(lambda ()
+17
(dbus-export! server path
+18
(list
+19
(dbus-interface iface
+20
methods:
+21
(list
+22
(dbus-method "Echo" "s" "s" (lambda (s) (list s)))
+23
(dbus-method "Notify" "susssasa{sv}i" "u"
+24
(lambda (app replaces icon summary body actions hints timeout)
+25
(list (if (= 0 replaces) 42 replaces))))
+26
(dbus-method "Fail" "" ""
+27
(lambda () (dbus-error "org.example.Error.Refused" "refused")))
+28
(dbus-method "Throw" "" "" (lambda () (error "broken handler")))
+29
(dbus-method "BadOutput" "" "u" (lambda () '("wrong")))
+30
(dbus-method "Slow" "u" "u" (lambda (delay) (sleep (/ delay 1000)) (list delay))))
+31
properties:
+32
(list (dbus-property "Counter" "u" (lambda () counter)
+33
setter: (lambda (value) (set! counter value)))
+34
(dbus-property "ReadOnly" "s" (lambda () "fixed")))
+35
signals: (list (dbus-signal "Changed" "u")))))
+36
(go (dbus-run! server))
+37
(test-group "real bus and service"
+38
(test "session and system entry points authenticate"
+39
(assert-true (string-starts-with? (dbus-unique-name server) ":"))
+40
(assert-true (string-starts-with? (dbus-unique-name client) ":")))
+41
(test "ListNames"
+42
(assert-true (member (dbus-unique-name client)
+43
(car (dbus-call client bus bus-path bus "ListNames" "" '())))))
+44
(test "address fallback"
+45
(let ((extra (dbus-connect-session
+46
address: (string-append "unix:path=/nonexistent/dbus;"
+47
(getenv "DBUS_SESSION_BUS_ADDRESS")))))
+48
(assert-true (string-starts-with? (dbus-unique-name extra) ":"))
+49
(dbus-close! extra)))
+50
(test "wrong GUID is rejected"
+51
(assert-error (dbus-connect-session timeout-ms: 500
+52
address: (string-append
+53
(car (string-split (getenv "DBUS_SESSION_BUS_ADDRESS") ",guid="))
+54
",guid=00000000000000000000000000000000"))))
+55
(test "RequestName"
+56
(assert-equal 1 (dbus-request-name! server service-name flags: dbus-allow-replacement)))
+57
(test "NameAcquired tracks ownership"
+58
(dbus-call server bus bus-path bus "ListNames" "" '())
+59
(assert-true (member service-name (dbus-owned-names server))))
+60
(test "method call"
+61
(assert-equal '("hello") (dbus-call client service-name path iface "Echo" "s" '("hello"))))
+62
(test "notifications argument types"
+63
(assert-equal '(42)
+64
(dbus-call client service-name path iface "Notify" "susssasa{sv}i"
+65
(list "app" 0 "" "summary" "body" '("default" "Open")
+66
(list (cons "urgency" (dbus-variant "y" 2))) -1))))
+67
(test "large payload handles partial writes"
+68
(let ((payload (make-string 131072 #\x)))
+69
(assert-equal (list payload)
+70
(dbus-call client service-name path iface "Echo" "s" (list payload) timeout-ms: 5000))))
+71
(test "custom method error"
+72
(assert-equal "org.example.Error.Refused"
+73
(dbus-error-name (dbus-call client service-name path iface "Fail" "" '()))))
+74
(test "handler exception becomes Failed"
+75
(assert-equal "org.freedesktop.DBus.Error.Failed"
+76
(dbus-error-name (dbus-call client service-name path iface "Throw" "" '()))))
+77
(test "bad handler output becomes Failed"
+78
(assert-equal "org.freedesktop.DBus.Error.Failed"
+79
(dbus-error-name (dbus-call client service-name path iface "BadOutput" "" '()))))
+80
(test "handler survives previous exceptions"
+81
(assert-equal '("still alive")
+82
(dbus-call client service-name path iface "Echo" "s" '("still alive"))))
+83
(test "unknown method"
+84
(assert-equal "org.freedesktop.DBus.Error.UnknownMethod"
+85
(dbus-error-name (dbus-call client service-name path iface "Missing" "" '()))))
+86
(test "unknown object"
+87
(assert-equal "org.freedesktop.DBus.Error.UnknownObject"
+88
(dbus-error-name (dbus-call client service-name "/missing" iface "Echo" "s" '("a")))))
+89
(test "unknown interface"
+90
(assert-equal "org.freedesktop.DBus.Error.UnknownInterface"
+91
(dbus-error-name (dbus-call client service-name path "org.example.Missing" "Echo" "s" '("a")))))
+92
(test "incorrect input signature"
+93
(assert-equal "org.freedesktop.DBus.Error.InvalidArgs"
+94
(dbus-error-name (dbus-call client service-name path iface "Echo" "i" '(1)))))
+95
(test "Peer.Ping"
+96
(assert-equal '() (dbus-call client service-name path "org.freedesktop.DBus.Peer" "Ping" "" '())))
+97
(test "Get property"
+98
(assert-equal (list (dbus-variant "u" 7))
+99
(dbus-call client service-name path props "Get" "ss" (list iface "Counter"))))
+100
(test "GetAll properties"
+101
(assert-equal
+102
(list (list (cons "Counter" (dbus-variant "u" 7)) (cons "ReadOnly" (dbus-variant "s" "fixed"))))
+103
(dbus-call client service-name path props "GetAll" "s" (list iface))))
+104
(test "subscribe and Set emits PropertiesChanged"
+105
(let ((token (dbus-subscribe! client
+106
(list (cons 'interface props) (cons 'member "PropertiesChanged") (cons 'path path))
+107
(lambda (message) (set! seen (cons (dbus-message-body message) seen))))))
+108
(assert-false (dbus-error? token))
+109
(assert-equal '() (dbus-call client service-name path props "Set" "ssv"
+110
(list iface "Counter" (dbus-variant "u" 8))))
+111
(let loop ((n 0))
+112
(when (and (null? seen) (< n 20)) (dbus-pump! client timeout-ms: 5) (sleep 0.001) (loop (+ n 1))))
+113
(assert-equal (list iface (list (cons "Counter" (dbus-variant "u" 8))) '()) (car seen))
+114
(dbus-unsubscribe! client token)))
+115
(test "read-only property"
+116
(assert-equal "org.freedesktop.DBus.Error.PropertyReadOnly"
+117
(dbus-error-name (dbus-call client service-name path props "Set" "ssv"
+118
(list iface "ReadOnly" (dbus-variant "s" "x"))))))
+119
(test "property variant type"
+120
(assert-equal "org.freedesktop.DBus.Error.InvalidArgs"
+121
(dbus-error-name (dbus-call client service-name path props "Set" "ssv"
+122
(list iface "Counter" (dbus-variant "s" "x"))))))
+123
(test "well-known sender and overlapping subscriptions"
+124
(let* ((matched 0) (other 0)
+125
(token (dbus-subscribe! client
+126
(list (cons 'sender service-name) (cons 'interface iface) (cons 'member "Changed"))
+127
(lambda (m) (set! matched (+ matched 1)))))
+128
(other-token (dbus-subscribe! client
+129
(list (cons 'sender (dbus-unique-name client))
+130
(cons 'interface iface) (cons 'member "Changed"))
+131
(lambda (m) (set! other (+ other 1))))))
+132
(dbus-send-signal! server path iface "Changed" "u" '(9))
+133
(let loop ((n 0))
+134
(when (and (= matched 0) (< n 20))
+135
(dbus-pump! client timeout-ms: 5) (sleep 0.001) (loop (+ n 1))))
+136
(assert-equal 1 matched)
+137
(assert-equal 0 other)
+138
(dbus-unsubscribe! client token)
+139
(dbus-send-signal! server path iface "Changed" "u" '(10))
+140
(dbus-call client bus bus-path bus "ListNames" "" '())
+141
(assert-equal 1 matched)
+142
(dbus-unsubscribe! client other-token)))
+143
(test "unknown property"
+144
(assert-equal "org.freedesktop.DBus.Error.UnknownProperty"
+145
(dbus-error-name (dbus-call client service-name path props "Get" "ss" (list iface "Missing")))))
+146
(test "introspection XML"
+147
(let ((xml (car (dbus-call client service-name path "org.freedesktop.DBus.Introspectable"
+148
"Introspect" "" '()))))
+149
(assert-true (string-contains? xml "method name=\"Echo\""))
+150
(assert-true (string-contains? xml "property name=\"Counter\" type=\"u\" access=\"readwrite\""))
+151
(assert-true (string-contains? xml "signal name=\"Changed\""))))
+152
(test "out of order async replies"
+153
(let ((slow (dbus-call-async client service-name path iface "Slow" "u" '(30)))
+154
(fast (dbus-call-async client service-name path iface "Echo" "s" '("fast"))))
+155
(assert-equal '("fast") (dbus-await fast))
+156
(assert-false (dbus-pending-ready? slow))
+157
(assert-equal '(30) (dbus-await slow))))
+158
(test "method timeout and late reply isolation"
+159
(assert-equal "org.freedesktop.DBus.Error.NoReply"
+160
(dbus-error-name (dbus-call client service-name path iface "Slow" "u" '(30) timeout-ms: 5)))
+161
(assert-equal '("after timeout")
+162
(dbus-call client service-name path iface "Echo" "s" '("after timeout"))))
+163
(test "dbus-send interoperates"
+164
(assert-true
+165
(string-contains?
+166
(process-output->string "dbus-send" "--session" "--print-reply" "--dest=org.example.SigilTest"
+167
path "org.example.Test.Echo" "string:external") "external")))
+168
(test "busctl interoperates"
+169
(assert-true
+170
(string-contains?
+171
(process-output->string "busctl" (string-append "--address=" (getenv "DBUS_SESSION_BUS_ADDRESS"))
+172
"call" service-name path iface "Echo" "s" "busctl") "busctl")))
+173
(test "busctl property access"
+174
(assert-true
+175
(string-contains?
+176
(process-output->string "busctl" (string-append "--address=" (getenv "DBUS_SESSION_BUS_ADDRESS"))
+177
"get-property" service-name path iface "Counter") "8")))
+178
(test "NameOwnerChanged and replacement flags"
+179
(let ((token (dbus-subscribe! client
+180
(list (cons 'interface bus) (cons 'member "NameOwnerChanged")
+181
(cons 'arg0 service-name))
+182
(lambda (m) (set! ownership-events (cons (dbus-message-body m) ownership-events))))))
+183
(assert-equal 3 (dbus-request-name! client service-name flags: dbus-do-not-queue))
+184
(assert-equal 1 (dbus-request-name! client service-name flags: (+ dbus-replace-existing dbus-do-not-queue)))
+185
(let loop ((n 0))
+186
(when (and (null? ownership-events) (< n 20))
+187
(dbus-pump! client timeout-ms: 5) (sleep 0.001) (loop (+ n 1))))
+188
(assert-equal (list service-name (dbus-unique-name server) (dbus-unique-name client))
+189
(car ownership-events))
+190
(dbus-call server bus bus-path bus "ListNames" "" '())
+191
(assert-false (member service-name (dbus-owned-names server)))
+192
(dbus-unsubscribe! client token)))
+193
(test "ReleaseName" (assert-equal 1 (dbus-release-name! client service-name)))
+194
(test "disconnect resolves pending calls"
+195
(let ((p (dbus-call-async client bus bus-path bus "ListNames" "" '())))
+196
(dbus-close! client)
+197
(assert-equal "org.freedesktop.DBus.Error.Disconnected" (dbus-error-name (dbus-await p))))))
+198
(unless (run-tests) (exit 1)))
+199
(lambda () (dbus-close! client) (dbus-close! server)))))
test/test-transport.sgladded
@@ -0,0 +1,95 @@
+1
(import (sigil dbus) (sigil dbus transport) (sigil socket)
+2
(sigil async) (sigil process) (sigil io) (sigil test))
+3
+4
;; A controlled peer exercises fragmentation and hostile framing without a
+5
;; bus daemon rewriting or rejecting the deliberately malformed messages.
+6
(define (peer-line socket)
+7
(let loop ((bytes '()))
+8
(let ((chunk (socket-read-bytevector socket 1)))
+9
(cond
+10
((eof-object? chunk) (error "Unexpected test peer EOF"))
+11
((= 0 (bytevector-length chunk)) (await-readable socket) (loop bytes))
+12
((= 10 (bytevector-u8-ref chunk 0)) (reverse bytes))
+13
(else (loop (cons (bytevector-u8-ref chunk 0) bytes)))))))
+14
+15
(define (peer-send socket bytes start end)
+16
(let loop ((offset start))
+17
(when (< offset end)
+18
(let ((n (socket-write socket bytes offset end)))
+19
(if (and n (> n 0))
+20
(loop (+ offset n))
+21
(begin (await-writable socket) (loop offset)))))))
+22
+23
(define (with-peer name handler client)
+24
(let* ((path (string-append (getenv "DBUS_TEST_DIRECTORY") "/" name))
+25
(listener (unix-listen path)) (peer #f) (transport #f) (peer-error #f) (peer-done #f))
+26
(unless listener (error "Cannot create test peer"))
+27
(socket-set-non-blocking! listener #t)
+28
(go
+29
(guard (e (else (set! peer-error e)))
+30
(await-readable listener)
+31
(set! peer (tcp-accept listener))
+32
(socket-set-non-blocking! peer #t)
+33
(peer-line peer)
+34
(socket-write peer (string->utf8 "OK 00000000000000000000000000000000\r\n"))
+35
(peer-line peer)
+36
(handler peer))
+37
(set! peer-done #t))
+38
(dynamic-wind
+39
(lambda () #t)
+40
(lambda ()
+41
(set! transport (dbus-open-transport (string-append "unix:path=" path) max-bytes: 1024))
+42
(client transport)
+43
(let loop () (unless peer-done (sleep 0.001) (loop)))
+44
(when peer-error (raise peer-error)))
+45
(lambda ()
+46
(when transport (dbus-close-transport! transport))
+47
(when peer (socket-close peer))
+48
(socket-close listener)))))
+49
+50
(define (reply text)
+51
(dbus-encode-message
+52
(dbus-message 2 1 (list (cons 5 (dbus-variant "u" 9))) "s" (list text))))
+53
+54
(with-async
+55
(test-group "stream transport"
+56
(test "fragmented fixed header and body survive read timeouts"
+57
(let ((bytes (reply "fragmented")))
+58
(with-peer "fragments"
+59
(lambda (peer)
+60
(peer-send peer bytes 0 3)
+61
(sleep 0.02)
+62
(peer-send peer bytes 3 16)
+63
(sleep 0.02)
+64
(peer-send peer bytes 16 (- (bytevector-length bytes) 2))
+65
(sleep 0.02)
+66
(peer-send peer bytes (- (bytevector-length bytes) 2) (bytevector-length bytes)))
+67
(lambda (transport)
+68
(assert-false (dbus-transport-read! transport timeout-ms: 5))
+69
(assert-equal '("fragmented")
+70
(dbus-message-body (dbus-transport-read! transport timeout-ms: 300)))))))
+71
(test "coalesced messages keep separate boundaries"
+72
(with-peer "coalesced"
+73
(lambda (peer)
+74
(let ((bytes (bytevector-append (reply "one") (reply "two"))))
+75
(peer-send peer bytes 0 (bytevector-length bytes))))
+76
(lambda (transport)
+77
(assert-equal '("one") (dbus-message-body (dbus-transport-read! transport)))
+78
(assert-equal '("two") (dbus-message-body (dbus-transport-read! transport))))))
+79
(test "oversized advertised frame rejected before its body arrives"
+80
(with-peer "oversized"
+81
(lambda (peer)
+82
(let ((prefix (bytevector 108 2 0 1 0 0 0 127 1 0 0 0 0 0 0 0)))
+83
(peer-send peer prefix 0 16)))
+84
(lambda (transport) (assert-error (dbus-transport-read! transport)))))
+85
(test "write backpressure has a deadline and closes partial frames"
+86
(with-peer "backpressure"
+87
(lambda (peer) (sleep 0.05))
+88
(lambda (transport)
+89
(assert-error (dbus-transport-write! transport (make-bytevector 1048576 1) timeout-ms: 5))
+90
(assert-true (dbus-transport-closed? transport)))))
+91
(test "EOF in partial fixed header is a clean error"
+92
(with-peer "eof"
+93
(lambda (peer) (socket-write peer (bytevector 108 2)) (socket-close peer))
+94
(lambda (transport) (assert-error (dbus-transport-read! transport))))))
+95
(unless (run-tests) (exit 1)))
test/test-wire.sgladded
@@ -0,0 +1,155 @@
+1
(import (sigil dbus) (sigil dbus types) (sigil dbus transport)
+2
(sigil test) (sigil process))
+3
+4
(test-group "wire round trips"
+5
(for-each
+6
(lambda (order)
+7
(for-each
+8
(lambda (entry)
+9
(let ((signature (car entry)) (values (cdr entry)))
+10
(test (string-append signature " / " (symbol->string order))
+11
(assert-equal values
+12
(dbus-unmarshal signature (dbus-marshal signature values endianness: order)
+13
endianness: order)))))
+14
(list
+15
(cons "" '())
+16
(cons "y" '(255)) (cons "b" '(#t)) (cons "b" '(#f))
+17
(cons "nqiu" (list -32768 65535 -2147483648 4294967295))
+18
(cons "xt" (list -9223372036854775808 18446744073709551615))
+19
(cons "xt" (list 9223372036854775807 0))
+20
(cons "d" '(1.25)) (cons "d" '(-0.5))
+21
(cons "sog" '("héλ🙂" "/org/example/Test" "a{sv}(it)"))
+22
(cons "h" '(123))
+23
(cons "ay" (list (bytevector 0 128 255)))
+24
(cons "ai" '((-1 0 1)))
+25
(cons "aai" '((() (1 2) (3))))
+26
(cons "(y(is)at)" (list (list 1 (list -4 "text") (list 0 18446744073709551615))))
+27
(cons "a{sv}" (list (list (cons "title" (dbus-variant "s" "hi"))
+28
(cons "urgent" (dbus-variant "b" #t)))))
+29
(cons "a{iv}" (list (list (cons -2 (dbus-variant "(si)" (list "two" 2))))))
+30
(cons "v" (list (dbus-variant "v" (dbus-variant "s" "nested")) ))
+31
(cons "yat" (list 9 '()))
+32
(cons "ya(xt)" (list 9 '())))))
+33
'(little big)))
+34
+35
;; Golden bytes derived from specification sections Marshalling Basic Types
+36
;; and Marshalling Containers (not produced by the implementation under test).
+37
(test-group "golden vectors"
+38
(test "UINT32 0x01020304 little"
+39
(assert-equal (bytevector 4 3 2 1) (dbus-marshal "u" (list 16909060) endianness: 'little)))
+40
(test "UINT32 0x01020304 big"
+41
(assert-equal (bytevector 1 2 3 4) (dbus-marshal "u" (list 16909060) endianness: 'big)))
+42
(test "BOOLEAN alignment after BYTE"
+43
(assert-equal (bytevector 7 0 0 0 1 0 0 0)
+44
(dbus-marshal "yb" (list 7 #t) endianness: 'little)))
+45
(test "STRING foo"
+46
(assert-equal (bytevector 3 0 0 0 102 111 111 0)
+47
(dbus-marshal "s" (list "foo") endianness: 'little)))
+48
(test "SIGNATURE a{sv}"
+49
(assert-equal (bytevector 5 97 123 115 118 125 0)
+50
(dbus-marshal "g" (list "a{sv}"))))
+51
(test "VARIANT containing UINT32"
+52
(assert-equal (bytevector 1 117 0 0 4 3 2 1)
+53
(dbus-marshal "v" (list (dbus-variant "u" 16909060)) endianness: 'little)))
+54
(test "empty UINT64 array includes element alignment"
+55
(assert-equal (bytevector 0 0 0 0 0 0 0 0) (dbus-marshal "at" (list '()))))
+56
(test "array length excludes initial alignment"
+57
(assert-equal (bytevector 8 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0)
+58
(dbus-marshal "at" (list (list 1)) endianness: 'little)))
+59
(test "DOUBLE 1.0 big"
+60
(assert-equal (bytevector 63 240 0 0 0 0 0 0)
+61
(dbus-marshal "d" '(1.0) endianness: 'big))))
+62
+63
(test-group "malformed and limits"
+64
(for-each
+65
(lambda (signature)
+66
(test (string-append "signature " signature)
+67
(assert-error (dbus-parse-signature signature))))
+68
'("a" "(" "()" "{ss}" "a{vs}" "a{sss}" "a{(i)s}" "a{}" "a{sa}" "r" "e" "m" "i)" "(i" "a{ss"))
+69
(test "signature length limit" (assert-error (dbus-parse-signature (make-string 256 #\i))))
+70
(test "array depth limit" (assert-error (dbus-parse-signature (string-append (make-string 33 #\a) "i"))))
+71
(test "struct depth limit"
+72
(assert-error (dbus-parse-signature (string-append (make-string 33 #\() "i" (make-string 33 #\))))))
+73
(test "dynamic variant depth"
+74
(let ((value (dbus-variant "i" 1)))
+75
(do ((i 0 (+ i 1))) ((= i 65)) (set! value (dbus-variant "v" value)))
+76
(assert-error (dbus-marshal "v" (list value)))))
+77
(for-each
+78
(lambda (entry)
+79
(test (string-append "range " (car entry))
+80
(assert-error (dbus-marshal (car entry) (list (cdr entry))))))
+81
(list (cons "y" 256) (cons "q" -1) (cons "n" 32768) (cons "i" -2147483649)
+82
(cons "t" 18446744073709551616) (cons "x" -9223372036854775809)
+83
(cons "b" 1) (cons "u" 1.0)))
+84
(test "body arity" (assert-error (dbus-marshal "ii" '(1))))
+85
(test "struct arity" (assert-error (dbus-marshal "(ii)" '((1)))))
+86
(test "missing boolean bytes" (assert-error (dbus-unmarshal "b" (bytevector 1))))
+87
(test "invalid boolean" (assert-error (dbus-unmarshal "b" (bytevector 2 0 0 0) endianness: 'little)))
+88
(test "nonzero alignment" (assert-error (dbus-unmarshal "yu" (bytevector 1 0 1 0 0 0 0 0))))
+89
(test "trailing data" (assert-error (dbus-unmarshal "y" (bytevector 0 0))))
+90
(test "oversized string before allocation"
+91
(assert-error (dbus-unmarshal "s" (bytevector 255 255 255 127) endianness: 'little)))
+92
(test "oversized array before allocation"
+93
(assert-error (dbus-unmarshal "ay" (bytevector 1 0 0 4) endianness: 'little)))
+94
(test "array length ends inside element"
+95
(assert-error (dbus-unmarshal "ai" (bytevector 3 0 0 0 1 0 0) endianness: 'little)))
+96
(test "string terminator" (assert-error (dbus-unmarshal "s" (bytevector 1 0 0 0 97 1))))
+97
(test "embedded NUL" (assert-error (dbus-unmarshal "s" (bytevector 1 0 0 0 0 0))))
+98
(test "empty variant signature" (assert-error (dbus-unmarshal "v" (bytevector 0 0))))
+99
(test "multiple variant types" (assert-error (dbus-unmarshal "v" (bytevector 2 105 105 0))))
+100
(test "invalid object path" (assert-error (dbus-marshal "o" '("/bad//path"))))
+101
(test "value budget" (assert-error (dbus-unmarshal "ai" (dbus-marshal "ai" '((1 2 3))) max-values: 3)))
+102
(test "byte budget" (assert-error (dbus-marshal "s" '("a long string") max-bytes: 8)))
+103
(for-each
+104
(lambda (bytes)
+105
(test "invalid UTF-8"
+106
(let ((n (bytevector-length bytes)))
+107
(assert-error
+108
(dbus-unmarshal "s"
+109
(bytevector-append (bytevector n 0 0 0) bytes (bytevector 0)) endianness: 'little)))))
+110
(list (bytevector 128) (bytevector 192 128) (bytevector 224 128 128)
+111
(bytevector 237 160 128) (bytevector 244 144 128 128) (bytevector 240 159)
+112
(bytevector 194 65))))
+113
+114
(define (call-message)
+115
(dbus-message 1 123 (list (cons 1 (dbus-variant "o" "/org/example/Test"))
+116
(cons 2 (dbus-variant "s" "org.example.Test"))
+117
(cons 3 (dbus-variant "s" "Echo"))
+118
(cons 42 (dbus-variant "(is)" (list 9 "extension")) ))
+119
"s" '("hello")))
+120
+121
(test-group "messages and names"
+122
(for-each
+123
(lambda (order)
+124
(test "complete message round trip"
+125
(assert-equal (call-message)
+126
(dbus-decode-message (dbus-encode-message (call-message) endianness: order)))))
+127
'(little big))
+128
(for-each
+129
(lambda (change)
+130
(test "invalid fixed prefix"
+131
(let ((bytes (dbus-encode-message (call-message) endianness: 'little)))
+132
(bytevector-u8-set! bytes (car change) (cdr change))
+133
(assert-error (dbus-decode-message bytes)))))
+134
'((0 . 0) (1 . 0) (3 . 2) (4 . 255) (8 . 0) (15 . 127)))
+135
(test "message size limit"
+136
(assert-error (dbus-frame-size (dbus-encode-message (call-message)) max-bytes: 16)))
+137
(test "duplicate header fields"
+138
(assert-error (dbus-encode-message
+139
(dbus-message 2 1 (list (cons 5 (dbus-variant "u" 1)) (cons 5 (dbus-variant "u" 2))) "" '()))))
+140
(test "wrong header type"
+141
(assert-error (dbus-encode-message (dbus-message 2 1 (list (cons 5 (dbus-variant "s" "one"))) "" '()))))
+142
(test "missing required header" (assert-error (dbus-encode-message (dbus-message 1 1 '() "" '()))))
+143
(test "names"
+144
(assert-true (dbus-bus-name? ":1.0"))
+145
(assert-false (dbus-interface-name? "1.bad"))
+146
(assert-false (dbus-member-name? "bad.name"))
+147
(assert-true (dbus-object-path? "/")))
+148
(test "escaped addresses"
+149
(assert-equal '(("unix" ("path" . "/tmp/a,b")))
+150
(dbus-parse-address "unix:path=/tmp/a%2cb")))
+151
(test "bad address escape" (assert-error (dbus-parse-address "unix:path=%xx")))
+152
(test "address escape requires two hex digits" (assert-error (dbus-parse-address "unix:path=%+a")))
+153
(test "address NUL" (assert-error (dbus-parse-address "unix:path=%00"))))
+154
+155
(unless (run-tests) (exit 1))