@clothespin/pi-pippi 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +415 -2
- package/approvals.ts +552 -0
- package/ble.ts +1062 -0
- package/bluez.ts +962 -0
- package/bridge.ts +1759 -0
- package/claims.ts +453 -0
- package/index.ts +827 -0
- package/package.json +53 -4
- package/protocol.ts +593 -0
- package/simulate.ts +249 -0
- package/state.ts +91 -0
- package/transport.ts +183 -0
- package/usage.ts +959 -0
package/bluez.ts
ADDED
|
@@ -0,0 +1,962 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The slice of D-Bus this bridge needs, and nothing more.
|
|
3
|
+
*
|
|
4
|
+
* BLE on Linux is BlueZ, and BlueZ is a D-Bus service. The alternative was a
|
|
5
|
+
* Python worker holding a `bleak` client (see git history), which cost a second
|
|
6
|
+
* runtime on the machine, a stdio control protocol between the two halves of one
|
|
7
|
+
* program, and a class of bug where the bridge could not tell that its worker's
|
|
8
|
+
* ATT channel had vanished. What it needs from the bus is small and fixed:
|
|
9
|
+
*
|
|
10
|
+
* method calls Hello, GetManagedObjects, Get/Set, Connect, Disconnect,
|
|
11
|
+
* StartNotify, WriteValue, Start/StopDiscovery
|
|
12
|
+
* one match rule PropertiesChanged plus ObjectManager's Added/Removed
|
|
13
|
+
*
|
|
14
|
+
* so this file implements the wire protocol rather than depending on a library:
|
|
15
|
+
* `EXTERNAL` auth over the system bus socket, the eleven-byte message header
|
|
16
|
+
* plus padded body, and a marshaller for exactly the signatures BlueZ uses here.
|
|
17
|
+
* Anything else it refuses loudly instead of guessing.
|
|
18
|
+
*
|
|
19
|
+
* Two properties of the bus are load-bearing for the rest of the bridge and are
|
|
20
|
+
* easy to get wrong from the other side:
|
|
21
|
+
*
|
|
22
|
+
* - A notification subscription belongs to the *connection*. A short-lived
|
|
23
|
+
* process that calls `StartNotify` and exits leaves `Notifying: false` and
|
|
24
|
+
* the device never sends again, which is why driving `busctl` cannot work as
|
|
25
|
+
* the data path: the process that subscribes must be the process that writes,
|
|
26
|
+
* for as long as the link matters.
|
|
27
|
+
* - A `WriteValue` reply means the ATT write was confirmed by the device, which
|
|
28
|
+
* is the flow control the device's 2048-byte RX ring depends on. An accepted
|
|
29
|
+
* write with no reply path would silently overflow it.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { EventEmitter } from "node:events";
|
|
33
|
+
import * as net from "node:net";
|
|
34
|
+
|
|
35
|
+
const HEADER_FIXSIZE = 12;
|
|
36
|
+
const PROTOCOL_VERSION = 1;
|
|
37
|
+
/** The greeting is local; anything slower than this is a broken bus. */
|
|
38
|
+
const GREETING_TIMEOUT_MS = 5_000;
|
|
39
|
+
|
|
40
|
+
// Message types (D-Bus spec 3.1).
|
|
41
|
+
const METHOD_CALL = 1;
|
|
42
|
+
const METHOD_RETURN = 2;
|
|
43
|
+
const ERROR = 3;
|
|
44
|
+
const SIGNAL = 4;
|
|
45
|
+
|
|
46
|
+
// Header field codes (D-Bus spec 3.1.1).
|
|
47
|
+
const F_PATH = 1;
|
|
48
|
+
const F_INTERFACE = 2;
|
|
49
|
+
const F_MEMBER = 3;
|
|
50
|
+
const F_ERROR_NAME = 4;
|
|
51
|
+
const F_REPLY_SERIAL = 5;
|
|
52
|
+
const F_DESTINATION = 6;
|
|
53
|
+
const F_SENDER = 7;
|
|
54
|
+
const F_SIGNATURE = 8;
|
|
55
|
+
|
|
56
|
+
export type BusValue = unknown;
|
|
57
|
+
|
|
58
|
+
export interface SignalMatch {
|
|
59
|
+
path?: string;
|
|
60
|
+
interface?: string;
|
|
61
|
+
member?: string;
|
|
62
|
+
sender?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface Incoming {
|
|
66
|
+
/**
|
|
67
|
+
* Set when the header parsed but the body did not. The reply still has to end the
|
|
68
|
+
* wait it started: a caller that is merely never answered waits out its timeout
|
|
69
|
+
* and looks like a radio problem.
|
|
70
|
+
*/
|
|
71
|
+
decodeError?: Error;
|
|
72
|
+
type: number;
|
|
73
|
+
serial: number;
|
|
74
|
+
replySerial?: number;
|
|
75
|
+
path?: string;
|
|
76
|
+
interface?: string;
|
|
77
|
+
member?: string;
|
|
78
|
+
sender?: string;
|
|
79
|
+
errorName?: string;
|
|
80
|
+
signature: string;
|
|
81
|
+
/** Values in signature order, variants unwrapped to their value. */
|
|
82
|
+
body: BusValue[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface CallOptions {
|
|
86
|
+
path: string;
|
|
87
|
+
interface: string;
|
|
88
|
+
member: string;
|
|
89
|
+
destination: string;
|
|
90
|
+
/** D-Bus signature of the arguments; omit for no arguments. */
|
|
91
|
+
signature?: string;
|
|
92
|
+
args?: BusValue[];
|
|
93
|
+
timeoutMs?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Alignment of the first byte of a value of this type. */
|
|
97
|
+
/**
|
|
98
|
+
* Wire alignment, straight off the spec table. The bus aligns relative to the start
|
|
99
|
+
* of the message, and a value whose alignment this file gets wrong still round
|
|
100
|
+
* trips through this file -- it just disagrees with every other implementation,
|
|
101
|
+
* which looks like a hung reply. `b` is 4, not 1. An array is 4 (its length field)
|
|
102
|
+
* even when its entries align to 8, and a variant is 1 whatever it holds.
|
|
103
|
+
*/
|
|
104
|
+
function alignment(type: string): number {
|
|
105
|
+
switch (type) {
|
|
106
|
+
case "y":
|
|
107
|
+
case "g":
|
|
108
|
+
case "v":
|
|
109
|
+
return 1;
|
|
110
|
+
case "n":
|
|
111
|
+
case "q":
|
|
112
|
+
return 2;
|
|
113
|
+
case "x":
|
|
114
|
+
case "t":
|
|
115
|
+
case "d":
|
|
116
|
+
return 8;
|
|
117
|
+
case "b":
|
|
118
|
+
case "i":
|
|
119
|
+
case "u":
|
|
120
|
+
case "h":
|
|
121
|
+
case "s":
|
|
122
|
+
case "o":
|
|
123
|
+
return 4;
|
|
124
|
+
default:
|
|
125
|
+
return type.startsWith("a") ? 4 : 8; // arrays by their length; structs and entries by 8
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
class Writer {
|
|
130
|
+
private readonly chunks: Buffer[] = [];
|
|
131
|
+
private used = 0;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* `base` is where these bytes will sit inside the message. Alignment is a
|
|
135
|
+
* property of the message, not of the value being written, and an array body is
|
|
136
|
+
* assembled in a writer of its own -- without a base, the first entry of an
|
|
137
|
+
* array pads against zero instead of against the message, and every entry after
|
|
138
|
+
* it is read out of the wrong place.
|
|
139
|
+
*/
|
|
140
|
+
private readonly base: number;
|
|
141
|
+
|
|
142
|
+
constructor(base = 0) {
|
|
143
|
+
this.base = base;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
get offset(): number {
|
|
147
|
+
return this.base + this.used;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private push(buffer: Buffer): void {
|
|
151
|
+
this.chunks.push(buffer);
|
|
152
|
+
this.used += buffer.length;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
pad(to: number): void {
|
|
156
|
+
// Not (offset + to - 1): that adds a whole unit whenever offset is already
|
|
157
|
+
// aligned, so every field lands with padding in front of it.
|
|
158
|
+
const aligned = Math.ceil(this.offset / to) * to;
|
|
159
|
+
if (aligned > this.offset) this.push(Buffer.alloc(aligned - this.offset));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
byte(value: number): void {
|
|
163
|
+
this.push(Buffer.from([value & 0xff]));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
fixed(value: number, size: number, signed = false): void {
|
|
167
|
+
const buffer = Buffer.alloc(size);
|
|
168
|
+
if (signed) buffer.writeIntLE(value, 0, size);
|
|
169
|
+
else buffer.writeUIntLE(value >>> 0, 0, size);
|
|
170
|
+
this.push(buffer);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
raw(buffer: Buffer): void {
|
|
174
|
+
this.push(buffer);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
string(value: string): void {
|
|
178
|
+
const bytes = Buffer.from(value, "utf8");
|
|
179
|
+
this.fixed(bytes.length, 4);
|
|
180
|
+
this.push(bytes);
|
|
181
|
+
this.byte(0);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
signature(value: string): void {
|
|
185
|
+
const bytes = Buffer.from(value, "utf8");
|
|
186
|
+
this.byte(bytes.length);
|
|
187
|
+
this.push(bytes);
|
|
188
|
+
this.byte(0);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
toBuffer(): Buffer {
|
|
192
|
+
return Buffer.concat(this.chunks, this.used);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Cursor over a message body or header field array. */
|
|
197
|
+
class Reader {
|
|
198
|
+
private buffer: Buffer;
|
|
199
|
+
private at: number;
|
|
200
|
+
|
|
201
|
+
constructor(buffer: Buffer, at = 0) {
|
|
202
|
+
this.buffer = buffer;
|
|
203
|
+
this.at = at;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
get offset(): number {
|
|
207
|
+
return this.at;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
align(to: number): void {
|
|
211
|
+
const aligned = Math.ceil(this.at / to) * to;
|
|
212
|
+
if (aligned > this.buffer.length) throw new Error(`dbus: short message (align ${to})`);
|
|
213
|
+
this.at = aligned;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
byte(): number {
|
|
217
|
+
const value = this.buffer.readUInt8(this.at);
|
|
218
|
+
this.at += 1;
|
|
219
|
+
return value;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
fixed(size: number, signed = false): number {
|
|
223
|
+
const value = signed
|
|
224
|
+
? this.buffer.readIntLE(this.at, size)
|
|
225
|
+
: this.buffer.readUIntLE(this.at, size);
|
|
226
|
+
this.at += size;
|
|
227
|
+
return value;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
string(): string {
|
|
231
|
+
const length = this.fixed(4);
|
|
232
|
+
const value = this.buffer.toString("utf8", this.at, this.at + length);
|
|
233
|
+
this.at += length + 1; // trailing NUL
|
|
234
|
+
return value;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
signature(): string {
|
|
238
|
+
const length = this.byte();
|
|
239
|
+
const value = this.buffer.toString("ascii", this.at, this.at + length);
|
|
240
|
+
this.at += length + 1;
|
|
241
|
+
return value;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
bytes(count: number): Buffer {
|
|
245
|
+
const value = this.buffer.subarray(this.at, this.at + count);
|
|
246
|
+
this.at += count;
|
|
247
|
+
return value;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Split `a{sv}` / `(ii)s` style signatures into top-level types. */
|
|
252
|
+
/**
|
|
253
|
+
* Signature parsing. `scanType` is the only place that knows about nesting:
|
|
254
|
+
* counting braces separately for the writer and the reader is how a nested dict
|
|
255
|
+
* (`a{oa{sa{sv}}}`, what GetManagedObjects answers) got read past its end.
|
|
256
|
+
*/
|
|
257
|
+
function scanType(signature: string, from: number): [string, number] {
|
|
258
|
+
const open = signature[from]!;
|
|
259
|
+
if (open !== "{" && open !== "(") return [open, from + 1];
|
|
260
|
+
const close = open === "{" ? "}" : ")";
|
|
261
|
+
let depth = 0;
|
|
262
|
+
let index = from;
|
|
263
|
+
for (; index < signature.length; index += 1) {
|
|
264
|
+
const char = signature[index]!;
|
|
265
|
+
if (char === open) depth += 1;
|
|
266
|
+
else if (char === close) {
|
|
267
|
+
depth -= 1;
|
|
268
|
+
if (depth === 0) {
|
|
269
|
+
index += 1;
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return [signature.slice(from, index), index];
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Top-level types of a signature, containers intact. */
|
|
278
|
+
function splitTop(signature: string): string[] {
|
|
279
|
+
const out: string[] = [];
|
|
280
|
+
let index = 0;
|
|
281
|
+
while (index < signature.length) {
|
|
282
|
+
if (signature[index] === "a") {
|
|
283
|
+
const [element, next] = scanType(signature, index + 1);
|
|
284
|
+
out.push(`a${element}`);
|
|
285
|
+
index = next;
|
|
286
|
+
} else {
|
|
287
|
+
const [type, next] = scanType(signature, index);
|
|
288
|
+
out.push(type);
|
|
289
|
+
index = next;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** `a{kv}` -> [key, value]. */
|
|
296
|
+
function splitDict(arrayType: string): [string, string] {
|
|
297
|
+
const types = splitTop(arrayType.slice(2, -1));
|
|
298
|
+
if (types.length !== 2) throw new Error(`dbus: bad dict type ${arrayType}`);
|
|
299
|
+
return [types[0]!, types[1]!];
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Members of a struct type `(..)`. */
|
|
303
|
+
function membersOf(structType: string): string[] {
|
|
304
|
+
return splitTop(structType.slice(1, -1));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** The element type of an array type `aX`. */
|
|
308
|
+
function elementType(arrayType: string): string {
|
|
309
|
+
const [element] = scanType(arrayType, 1);
|
|
310
|
+
return element;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Structs and dict entries align to 8, whatever they hold. */
|
|
314
|
+
const CONTAINER_ALIGN = 8;
|
|
315
|
+
|
|
316
|
+
export function marshal(signature: string, values: BusValue[]): Buffer {
|
|
317
|
+
const types = splitTop(signature);
|
|
318
|
+
if (types.length !== values.length) {
|
|
319
|
+
throw new Error(`dbus: ${signature} wants ${types.length} args, got ${values.length}`);
|
|
320
|
+
}
|
|
321
|
+
const writer = new Writer();
|
|
322
|
+
types.forEach((type, index) => writeValue(writer, type, values[index]));
|
|
323
|
+
return writer.toBuffer();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function writeValue(writer: Writer, type: string, value: BusValue): void {
|
|
327
|
+
writer.pad(alignment(type));
|
|
328
|
+
switch (type) {
|
|
329
|
+
case "y":
|
|
330
|
+
writer.byte(Number(value) & 0xff);
|
|
331
|
+
return;
|
|
332
|
+
case "b":
|
|
333
|
+
writer.fixed(value ? 1 : 0, 4);
|
|
334
|
+
return;
|
|
335
|
+
case "n":
|
|
336
|
+
writer.fixed(Number(value), 2, true);
|
|
337
|
+
return;
|
|
338
|
+
case "q":
|
|
339
|
+
writer.fixed(Number(value), 2);
|
|
340
|
+
return;
|
|
341
|
+
case "i":
|
|
342
|
+
writer.fixed(Number(value), 4, true);
|
|
343
|
+
return;
|
|
344
|
+
case "u":
|
|
345
|
+
writer.fixed(Number(value), 4);
|
|
346
|
+
return;
|
|
347
|
+
case "x":
|
|
348
|
+
writer.fixed(Number(value), 8, true);
|
|
349
|
+
return;
|
|
350
|
+
case "t":
|
|
351
|
+
writer.fixed(Number(value), 8);
|
|
352
|
+
return;
|
|
353
|
+
case "h":
|
|
354
|
+
// An index into the message's fd array; nothing here passes fd-backed data.
|
|
355
|
+
writer.fixed(Number(value), 4);
|
|
356
|
+
return;
|
|
357
|
+
case "s":
|
|
358
|
+
case "o":
|
|
359
|
+
writer.string(String(value));
|
|
360
|
+
return;
|
|
361
|
+
case "g":
|
|
362
|
+
writer.signature(String(value));
|
|
363
|
+
return;
|
|
364
|
+
case "v": {
|
|
365
|
+
const [inner, encoded] = variantOf(value);
|
|
366
|
+
writer.signature(inner);
|
|
367
|
+
writeValue(writer, inner, encoded);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
default:
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
if (type.startsWith("a{")) {
|
|
374
|
+
const [keyType, valueType] = splitDict(type);
|
|
375
|
+
const entries = value as Record<string, BusValue> | Map<string, BusValue>;
|
|
376
|
+
const pairs: [BusValue, BusValue][] =
|
|
377
|
+
entries instanceof Map ? [...entries.entries()] : Object.entries(entries ?? {});
|
|
378
|
+
// The declared size of an array is its elements and nothing else -- not its
|
|
379
|
+
// length field, and not the padding that gets the first element onto its own
|
|
380
|
+
// boundary. A dict-entry array therefore reserves up to 7 bytes that belong to
|
|
381
|
+
// no entry, which is only visible in the byte count, and the broker checks the
|
|
382
|
+
// byte count: get it wrong and it drops the connection without a reply
|
|
383
|
+
// (`Peer :1.NNNN is being disconnected as it sent a message with an invalid
|
|
384
|
+
// body` -- journalctl is the only place that says so).
|
|
385
|
+
const body = new Writer(alignTo(writer.offset + 4, CONTAINER_ALIGN));
|
|
386
|
+
for (const [key, item] of pairs) {
|
|
387
|
+
body.pad(CONTAINER_ALIGN);
|
|
388
|
+
writeValue(body, keyType, key);
|
|
389
|
+
writeValue(body, valueType, item);
|
|
390
|
+
}
|
|
391
|
+
const bytes = body.toBuffer();
|
|
392
|
+
writer.fixed(bytes.length, 4);
|
|
393
|
+
writer.pad(CONTAINER_ALIGN);
|
|
394
|
+
writer.raw(bytes);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (type.startsWith("a")) {
|
|
398
|
+
const element = elementType(type);
|
|
399
|
+
const align = alignment(element);
|
|
400
|
+
const body = new Writer(alignTo(writer.offset + 4, align));
|
|
401
|
+
for (const item of toIterable(value)) writeValue(body, element, item);
|
|
402
|
+
const bytes = body.toBuffer();
|
|
403
|
+
writer.fixed(bytes.length, 4);
|
|
404
|
+
writer.pad(align);
|
|
405
|
+
writer.raw(bytes);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (type.startsWith("(")) {
|
|
409
|
+
const members = membersOf(type);
|
|
410
|
+
const items = toIterable(value);
|
|
411
|
+
members.forEach((member, index) => writeValue(writer, member, items[index]));
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
throw new Error(`dbus: cannot marshal type ${type}`);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function toIterable(value: BusValue): BusValue[] {
|
|
418
|
+
if (Buffer.isBuffer(value)) return [...value.values()];
|
|
419
|
+
if (Array.isArray(value)) return value;
|
|
420
|
+
if (value instanceof Map) return [...value.values()];
|
|
421
|
+
return Array.from(value as Iterable<BusValue>);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* A variant needs the type the caller means. Bare strings and booleans are the
|
|
426
|
+
* common case and almost always right; everything else says so explicitly with
|
|
427
|
+
* `variant("as", [...])`, because guessing an array's element type is how a
|
|
428
|
+
* discovery filter silently stops filtering.
|
|
429
|
+
*/
|
|
430
|
+
function variantOf(value: BusValue): [string, BusValue] {
|
|
431
|
+
if (isVariant(value)) return [value.sig, value.value];
|
|
432
|
+
if (typeof value === "string") return ["s", value];
|
|
433
|
+
if (typeof value === "boolean") return ["b", value];
|
|
434
|
+
if (Buffer.isBuffer(value)) return ["ay", value];
|
|
435
|
+
if (Number.isInteger(value)) return ["i", value];
|
|
436
|
+
throw new Error(`dbus: cannot infer a variant for ${typeof value}`);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
export type Variant = { sig: string; value: BusValue };
|
|
440
|
+
|
|
441
|
+
export function variant(sig: string, value: BusValue): Variant {
|
|
442
|
+
return { sig, value };
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function isVariant(value: BusValue): value is Variant {
|
|
446
|
+
return typeof value === "object" && value !== null && "sig" in (value as Variant) && "value" in (value as Variant);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Decode `signature`'s worth of values out of a message body.
|
|
451
|
+
*
|
|
452
|
+
* No base offset is needed: a body always begins 8-aligned in the message, so
|
|
453
|
+
* body-relative and message-relative alignment agree for everything D-Bus can ask
|
|
454
|
+
* for here.
|
|
455
|
+
*/
|
|
456
|
+
export function unmarshal(buffer: Buffer, signature: string): BusValue[] {
|
|
457
|
+
const reader = new Reader(buffer);
|
|
458
|
+
return splitTop(signature).map((type) => readValue(reader, type));
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
function readValue(reader: Reader, type: string): BusValue {
|
|
463
|
+
reader.align(alignment(type));
|
|
464
|
+
switch (type) {
|
|
465
|
+
case "y":
|
|
466
|
+
return reader.byte();
|
|
467
|
+
case "b":
|
|
468
|
+
return reader.fixed(4) !== 0;
|
|
469
|
+
case "n":
|
|
470
|
+
return reader.fixed(2, true);
|
|
471
|
+
case "q":
|
|
472
|
+
return reader.fixed(2);
|
|
473
|
+
case "i":
|
|
474
|
+
return reader.fixed(4, true);
|
|
475
|
+
case "u":
|
|
476
|
+
return reader.fixed(4);
|
|
477
|
+
case "x":
|
|
478
|
+
return reader.fixed(8, true);
|
|
479
|
+
case "t":
|
|
480
|
+
return reader.fixed(8);
|
|
481
|
+
case "h":
|
|
482
|
+
return reader.fixed(4);
|
|
483
|
+
case "s":
|
|
484
|
+
return reader.string();
|
|
485
|
+
case "o":
|
|
486
|
+
return reader.string();
|
|
487
|
+
case "g":
|
|
488
|
+
return reader.signature();
|
|
489
|
+
case "v": {
|
|
490
|
+
// The signature first, then the value aligned the way that type alone
|
|
491
|
+
// requires -- `q` inside a variant is 2, not 4.
|
|
492
|
+
return readValue(reader, reader.signature());
|
|
493
|
+
}
|
|
494
|
+
default:
|
|
495
|
+
break;
|
|
496
|
+
}
|
|
497
|
+
if (type.startsWith("a{")) {
|
|
498
|
+
const [keyType, valueType] = splitDict(type);
|
|
499
|
+
const length = reader.fixed(4);
|
|
500
|
+
// The padding after the length belongs to the array but to no entry, so the
|
|
501
|
+
// end has to be measured after it -- see the same note in writeValue.
|
|
502
|
+
reader.align(CONTAINER_ALIGN);
|
|
503
|
+
const end = reader.offset + length;
|
|
504
|
+
const out: Record<string, BusValue> = {};
|
|
505
|
+
while (reader.offset < end) {
|
|
506
|
+
reader.align(CONTAINER_ALIGN);
|
|
507
|
+
const key = readValue(reader, keyType);
|
|
508
|
+
const value = readValue(reader, valueType);
|
|
509
|
+
out[String(key)] = value;
|
|
510
|
+
}
|
|
511
|
+
return out;
|
|
512
|
+
}
|
|
513
|
+
if (type.startsWith("a")) {
|
|
514
|
+
const element = elementType(type);
|
|
515
|
+
const length = reader.fixed(4);
|
|
516
|
+
reader.align(alignment(element));
|
|
517
|
+
const end = reader.offset + length;
|
|
518
|
+
if (element === "y") return reader.bytes(length);
|
|
519
|
+
const out: BusValue[] = [];
|
|
520
|
+
while (reader.offset < end) out.push(readValue(reader, element));
|
|
521
|
+
return out;
|
|
522
|
+
}
|
|
523
|
+
if (type.startsWith("(")) {
|
|
524
|
+
const members = membersOf(type.slice(1, -1));
|
|
525
|
+
return members.map((member) => readValue(reader, member));
|
|
526
|
+
}
|
|
527
|
+
throw new Error(`dbus: cannot unmarshal type ${type}`);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
export interface BluezBusOptions {
|
|
531
|
+
/** Default: $DBUS_SYSTEM_BUS_ADDRESS, then /run/dbus/system_bus_socket. */
|
|
532
|
+
address?: string;
|
|
533
|
+
/** Match rule additions are async; keep them for teardown. */
|
|
534
|
+
onLog?: (level: "info" | "warn" | "error", message: string) => void;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* One connection to the system bus.
|
|
539
|
+
*
|
|
540
|
+
* The bridge needs exactly one, for the life of the transport, because it is the
|
|
541
|
+
* connection that holds the BLE notification subscription.
|
|
542
|
+
*/
|
|
543
|
+
export class BluezBus extends EventEmitter {
|
|
544
|
+
private socket?: net.Socket;
|
|
545
|
+
private inbox: Buffer = Buffer.alloc(0);
|
|
546
|
+
private serial = 0;
|
|
547
|
+
/** Auth greeting in flight; carries the bytes that arrived past its newline. */
|
|
548
|
+
private auth?: { resolve: () => void; reject: (error: Error) => void; buffer: Buffer; anonymous?: boolean };
|
|
549
|
+
private readonly pending = new Map<
|
|
550
|
+
number,
|
|
551
|
+
{ resolve: (message: Incoming) => void; reject: (error: Error) => void; timer?: NodeJS.Timeout }
|
|
552
|
+
>();
|
|
553
|
+
private readonly rules = new Set<string>();
|
|
554
|
+
private connected?: Promise<void>;
|
|
555
|
+
private closing = false;
|
|
556
|
+
|
|
557
|
+
/** Our unique name on the bus, from the greeting (`:1.42`). */
|
|
558
|
+
uniqueName = "";
|
|
559
|
+
|
|
560
|
+
private readonly address: string;
|
|
561
|
+
private readonly onLog?: (level: "info" | "warn" | "error", message: string) => void;
|
|
562
|
+
|
|
563
|
+
constructor(options: BluezBusOptions = {}) {
|
|
564
|
+
super();
|
|
565
|
+
this.address = options.address ?? systemBusAddress();
|
|
566
|
+
this.onLog = options.onLog;
|
|
567
|
+
// A bus that dies must not take pi with it.
|
|
568
|
+
super.on("error", () => {});
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
get alive(): boolean {
|
|
572
|
+
return this.socket !== undefined && !this.closing;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
async connect(): Promise<void> {
|
|
576
|
+
if (this.connected) return this.connected;
|
|
577
|
+
// Reopening is allowed: close() latches `closing` to stop the reconnect machinery,
|
|
578
|
+
// but a client that hangs up and dials again is normal, and leaving the latch set
|
|
579
|
+
// would make every later call answer "not connected" on a live socket.
|
|
580
|
+
this.closing = false;
|
|
581
|
+
// `greet` runs inside the memoized connect promise, so it has to use the
|
|
582
|
+
// non-reentrant path; calling `call` here would await the promise it is part of.
|
|
583
|
+
this.connected = this.openSocket().then(() => this.greet());
|
|
584
|
+
return this.connected.catch((error: unknown) => {
|
|
585
|
+
this.connected = undefined;
|
|
586
|
+
throw error;
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Hello is not optional: a connection that opens with any other message is closed
|
|
592
|
+
* by the bus without a reply, which looks like a hung call. It also hands back our
|
|
593
|
+
* unique name, which is how a signal from ourselves is told apart from another
|
|
594
|
+
* session's.
|
|
595
|
+
*/
|
|
596
|
+
private async greet(): Promise<void> {
|
|
597
|
+
const reply = await this.callNow({
|
|
598
|
+
destination: "org.freedesktop.DBus",
|
|
599
|
+
path: "/org/freedesktop/DBus",
|
|
600
|
+
interface: "org.freedesktop.DBus",
|
|
601
|
+
member: "Hello",
|
|
602
|
+
timeoutMs: GREETING_TIMEOUT_MS,
|
|
603
|
+
});
|
|
604
|
+
this.uniqueName = String(reply.body[0] ?? "");
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
private openSocket(): Promise<void> {
|
|
608
|
+
return new Promise<void>((resolve, reject) => {
|
|
609
|
+
const socket = net.connect(this.address);
|
|
610
|
+
socket.once("error", (error) => reject(withPrefix(error, `dbus connect ${this.address}`)));
|
|
611
|
+
socket.once("connect", () => {
|
|
612
|
+
socket.off("error", reject);
|
|
613
|
+
this.socket = socket;
|
|
614
|
+
this.auth = { resolve, reject, buffer: Buffer.alloc(0) };
|
|
615
|
+
// The overload set types this chunk as `string | Buffer`; a socket we never
|
|
616
|
+
// put into string mode only ever yields Buffers.
|
|
617
|
+
socket.on("data", (chunk: Buffer) => this.onSocketData(chunk));
|
|
618
|
+
socket.on("close", () => this.onClosed("connection closed"));
|
|
619
|
+
socket.on("error", (error) => this.onLog?.("warn", `dbus: ${error.message}`));
|
|
620
|
+
// NUL byte first, then EXTERNAL with our uid in hex: the spec's "same user
|
|
621
|
+
// as the socket" proof, which the kernel confirms out of band through
|
|
622
|
+
// SO_PEERCRED. ANONYMOUS is the fallback for a bus configured to allow it.
|
|
623
|
+
// `process.getuid()` is a function, not a property: reading a property that
|
|
624
|
+
// is not there would authenticate as uid 0, which the bus refuses.
|
|
625
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : 0;
|
|
626
|
+
const request = `AUTH EXTERNAL ${Buffer.from(String(uid)).toString("hex")}\r\n`;
|
|
627
|
+
socket.write(Buffer.concat([Buffer.from([0]), Buffer.from(request, "latin1")]));
|
|
628
|
+
});
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* An auth reply and a real message can arrive in one read -- the bus has nothing
|
|
634
|
+
* to wait for after `BEGIN`. Swallowing the greeting as a frame, or dropping the
|
|
635
|
+
* message that rode in with "OK", both surface later as a call that never
|
|
636
|
+
* answers, so the bytes past the greeting go to the frame parser.
|
|
637
|
+
*/
|
|
638
|
+
private onSocketData(chunk: Buffer): void {
|
|
639
|
+
const auth = this.auth;
|
|
640
|
+
if (!auth) {
|
|
641
|
+
this.onData(chunk);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
auth.buffer = Buffer.concat([auth.buffer, chunk]);
|
|
645
|
+
for (;;) {
|
|
646
|
+
const end = auth.buffer.indexOf("\r\n");
|
|
647
|
+
if (end < 0) return;
|
|
648
|
+
const line = auth.buffer.subarray(0, end).toString("latin1");
|
|
649
|
+
const rest = auth.buffer.subarray(end + 2);
|
|
650
|
+
if (line.startsWith("OK ")) {
|
|
651
|
+
this.auth = undefined;
|
|
652
|
+
this.socket?.write("BEGIN\r\n");
|
|
653
|
+
auth.resolve();
|
|
654
|
+
if (rest.length > 0) this.onData(rest);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (line.startsWith("REJECTED")) {
|
|
658
|
+
if (auth.anonymous) {
|
|
659
|
+
this.auth = undefined;
|
|
660
|
+
auth.reject(new Error(`dbus auth rejected: ${line}`));
|
|
661
|
+
this.socket?.destroy();
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
auth.anonymous = true;
|
|
665
|
+
auth.buffer = rest;
|
|
666
|
+
this.socket?.write(`AUTH ANONYMOUS ${Buffer.from("pi-pippi").toString("hex")}\r\n`);
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
auth.buffer = rest;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
private onClosed(reason: string): void {
|
|
674
|
+
this.socket = undefined;
|
|
675
|
+
this.connected = undefined;
|
|
676
|
+
for (const [, waiter] of this.pending) {
|
|
677
|
+
if (waiter.timer) clearTimeout(waiter.timer);
|
|
678
|
+
waiter.reject(new Error(`dbus: ${reason}`));
|
|
679
|
+
}
|
|
680
|
+
this.pending.clear();
|
|
681
|
+
if (!this.closing) this.emit("disconnected", reason);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
private onData(chunk: Buffer): void {
|
|
685
|
+
debug(`recv ${chunk.length} bytes: ${hex(chunk)}`);
|
|
686
|
+
this.inbox = this.inbox.length === 0 ? chunk : Buffer.concat([this.inbox, chunk]);
|
|
687
|
+
for (;;) {
|
|
688
|
+
if (this.inbox.length < HEADER_FIXSIZE) return;
|
|
689
|
+
const bodyLength = this.inbox.readUInt32LE(4);
|
|
690
|
+
const arrayLength = this.inbox.readUInt32LE(12);
|
|
691
|
+
const arrayEnd = 16 + align8(arrayLength);
|
|
692
|
+
const total = arrayEnd + bodyLength;
|
|
693
|
+
if (this.inbox.length < total) return;
|
|
694
|
+
const raw = this.inbox.subarray(0, total);
|
|
695
|
+
this.inbox = this.inbox.subarray(total);
|
|
696
|
+
let message: Incoming;
|
|
697
|
+
try {
|
|
698
|
+
message = parseMessage(raw);
|
|
699
|
+
} catch (error) {
|
|
700
|
+
// A frame this library cannot read is its own bug, and the connection is
|
|
701
|
+
// still good: drop it, keep the session, say so loudly.
|
|
702
|
+
this.onLog?.("error", `dbus: ${error instanceof Error ? error.message : String(error)}`);
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
debug(
|
|
706
|
+
`frame type=${message.type} serial=${message.serial} reply=${message.replySerial ?? "-"} sig=${message.signature || "-"} member=${message.member ?? "-"}`,
|
|
707
|
+
);
|
|
708
|
+
if (message.decodeError) this.failDecoded(message);
|
|
709
|
+
else this.dispatch(message);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** A reply whose body was unreadable: fail the wait, do not resolve it empty. */
|
|
714
|
+
private failDecoded(message: Incoming): void {
|
|
715
|
+
const error = message.decodeError ?? new Error("dbus: unreadable reply");
|
|
716
|
+
this.onLog?.("error", `dbus: ${error.message}`);
|
|
717
|
+
if (message.replySerial === undefined) return;
|
|
718
|
+
const waiter = this.pending.get(message.replySerial);
|
|
719
|
+
if (!waiter) return;
|
|
720
|
+
this.pending.delete(message.replySerial);
|
|
721
|
+
if (waiter.timer) clearTimeout(waiter.timer);
|
|
722
|
+
waiter.reject(error);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
private dispatch(message: Incoming): void {
|
|
726
|
+
if (message.replySerial !== undefined) {
|
|
727
|
+
const waiter = this.pending.get(message.replySerial);
|
|
728
|
+
if (!waiter) return;
|
|
729
|
+
this.pending.delete(message.replySerial);
|
|
730
|
+
if (waiter.timer) clearTimeout(waiter.timer);
|
|
731
|
+
if (message.type === ERROR) {
|
|
732
|
+
const text = message.body.map(String).filter(Boolean).join(": ");
|
|
733
|
+
waiter.reject(new DBusError(message.errorName ?? "org.freedesktop.DBus.Error.Failed", text || message.errorName || "dbus error", message));
|
|
734
|
+
} else {
|
|
735
|
+
waiter.resolve(message);
|
|
736
|
+
}
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
if (message.type === SIGNAL) this.emit("signal", message);
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
async call(options: CallOptions): Promise<Incoming> {
|
|
743
|
+
// Always await connect(), never just check it: the socket exists before the
|
|
744
|
+
// greeting is finished, and a call written before BEGIN is a protocol
|
|
745
|
+
// violation the bus answers by hanging up.
|
|
746
|
+
await this.connect();
|
|
747
|
+
return this.callNow(options);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** The call itself; the connection and the greeting are already settled. */
|
|
751
|
+
private async callNow(options: CallOptions): Promise<Incoming> {
|
|
752
|
+
if (!this.alive) throw new Error("dbus: not connected");
|
|
753
|
+
const socket = this.socket!;
|
|
754
|
+
const serial = ++this.serial;
|
|
755
|
+
const frame = buildMethodCall(serial, options);
|
|
756
|
+
return new Promise<Incoming>((resolve, reject) => {
|
|
757
|
+
const timer =
|
|
758
|
+
options.timeoutMs && options.timeoutMs > 0
|
|
759
|
+
? setTimeout(() => {
|
|
760
|
+
this.pending.delete(serial);
|
|
761
|
+
reject(new Error(`dbus: timeout after ${options.timeoutMs}ms on ${options.interface}.${options.member}`));
|
|
762
|
+
}, options.timeoutMs)
|
|
763
|
+
: undefined;
|
|
764
|
+
timer?.unref?.();
|
|
765
|
+
this.pending.set(serial, { resolve, reject, timer });
|
|
766
|
+
debug(`send ${options.interface}.${options.member} serial=${serial}: ${hex(frame)}`);
|
|
767
|
+
socket.write(frame, (error) => {
|
|
768
|
+
if (!error) return;
|
|
769
|
+
this.pending.delete(serial);
|
|
770
|
+
if (timer) clearTimeout(timer);
|
|
771
|
+
reject(error);
|
|
772
|
+
});
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Subscribe to signals. The match rule is registered on the bus, so the daemon
|
|
778
|
+
* only sends what is wanted; the same rule is never sent twice.
|
|
779
|
+
*/
|
|
780
|
+
async addMatch(rule: string): Promise<void> {
|
|
781
|
+
if (this.rules.has(rule)) return;
|
|
782
|
+
this.rules.add(rule);
|
|
783
|
+
await this.call({
|
|
784
|
+
destination: "org.freedesktop.DBus",
|
|
785
|
+
path: "/org/freedesktop/DBus",
|
|
786
|
+
interface: "org.freedesktop.DBus",
|
|
787
|
+
member: "AddMatch",
|
|
788
|
+
signature: "s",
|
|
789
|
+
args: [rule],
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
async nameHasOwner(service: string): Promise<boolean> {
|
|
794
|
+
const reply = await this.call({
|
|
795
|
+
destination: "org.freedesktop.DBus",
|
|
796
|
+
path: "/org/freedesktop/DBus",
|
|
797
|
+
interface: "org.freedesktop.DBus",
|
|
798
|
+
member: "NameHasOwner",
|
|
799
|
+
signature: "s",
|
|
800
|
+
args: [service],
|
|
801
|
+
});
|
|
802
|
+
return Boolean(reply.body[0]);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
close(): void {
|
|
806
|
+
this.closing = true;
|
|
807
|
+
this.socket?.destroy();
|
|
808
|
+
this.onClosed("closed");
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
export class DBusError extends Error {
|
|
813
|
+
/** The D-Bus error name, e.g. org.bluez.Error.NotConnected. */
|
|
814
|
+
readonly dbusName: string;
|
|
815
|
+
readonly body?: Incoming;
|
|
816
|
+
|
|
817
|
+
constructor(dbusName: string, message: string, body?: Incoming) {
|
|
818
|
+
super(message);
|
|
819
|
+
this.name = "DBusError";
|
|
820
|
+
this.dbusName = dbusName;
|
|
821
|
+
this.body = body;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** True for the D-Bus equivalent of "no such thing" / "not connected". */
|
|
825
|
+
matches(...names: string[]): boolean {
|
|
826
|
+
return names.some((needle) => this.dbusName === needle || this.message.includes(needle));
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function withPrefix(error: unknown, prefix: string): Error {
|
|
831
|
+
return error instanceof Error ? new Error(`${prefix}: ${error.message}`) : new Error(String(error));
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function alignTo(value: number, to: number): number {
|
|
835
|
+
return Math.ceil(value / to) * to;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function align8(value: number): number {
|
|
839
|
+
return Math.ceil(value / 8) * 8;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
function buildMethodCall(serial: number, options: CallOptions): Buffer {
|
|
843
|
+
// Header fields are a dict of `yv`: the key byte, the value's variant
|
|
844
|
+
// signature, then the variant payload itself.
|
|
845
|
+
const header = new Writer();
|
|
846
|
+
const put = (code: number, signature: string, value: BusValue) => {
|
|
847
|
+
header.pad(8);
|
|
848
|
+
header.byte(code);
|
|
849
|
+
// A variant is its own signature and then the value: writing a literal "v"
|
|
850
|
+
// in front makes the daemon read the field as a variant holding a variant
|
|
851
|
+
// and silently drop the call.
|
|
852
|
+
header.signature(signature);
|
|
853
|
+
writeValue(header, signature, value);
|
|
854
|
+
};
|
|
855
|
+
put(F_PATH, "o", options.path);
|
|
856
|
+
put(F_INTERFACE, "s", options.interface);
|
|
857
|
+
put(F_MEMBER, "s", options.member);
|
|
858
|
+
put(F_DESTINATION, "s", options.destination);
|
|
859
|
+
if (options.signature) put(F_SIGNATURE, "g", options.signature);
|
|
860
|
+
|
|
861
|
+
const body = options.signature ? marshal(options.signature, options.args ?? []) : Buffer.alloc(0);
|
|
862
|
+
const fieldsBuffer = header.toBuffer();
|
|
863
|
+
|
|
864
|
+
// The body starts on the 8-boundary after the fields array, so a fields array
|
|
865
|
+
// that is not a multiple of 8 is padded -- and the frame has to carry that
|
|
866
|
+
// padding even when the body is empty, or the peer reads a body that runs past
|
|
867
|
+
// the end and drops the call without answering it.
|
|
868
|
+
//
|
|
869
|
+
const out = Buffer.alloc(HEADER_FIXSIZE + 4 + align8(fieldsBuffer.length) + body.length);
|
|
870
|
+
out.writeUInt8(0x6c, 0); // 'l' little endian
|
|
871
|
+
out.writeUInt8(METHOD_CALL, 1);
|
|
872
|
+
out.writeUInt8(0, 2); // flags: no reply wanted would be 0x1; we always want one
|
|
873
|
+
out.writeUInt8(PROTOCOL_VERSION, 3);
|
|
874
|
+
out.writeUInt32LE(body.length, 4);
|
|
875
|
+
out.writeUInt32LE(serial, 8);
|
|
876
|
+
out.writeUInt32LE(fieldsBuffer.length, 12);
|
|
877
|
+
fieldsBuffer.copy(out, 16);
|
|
878
|
+
body.copy(out, 16 + align8(fieldsBuffer.length));
|
|
879
|
+
return out;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function parseMessage(frame: Buffer): Incoming {
|
|
883
|
+
const endian = String.fromCharCode(frame.readUInt8(0));
|
|
884
|
+
if (endian !== "l") throw new Error(`dbus: only little-endian messages are supported (got ${endian})`);
|
|
885
|
+
const type = frame.readUInt8(1);
|
|
886
|
+
const bodyLength = frame.readUInt32LE(4);
|
|
887
|
+
const serial = frame.readUInt32LE(8);
|
|
888
|
+
const arrayLength = frame.readUInt32LE(12);
|
|
889
|
+
const fields = new Reader(frame, 16);
|
|
890
|
+
const out: Incoming = { type, serial, signature: "", body: [] };
|
|
891
|
+
const end = 16 + arrayLength;
|
|
892
|
+
while (fields.offset < end) {
|
|
893
|
+
fields.align(8);
|
|
894
|
+
const code = fields.byte();
|
|
895
|
+
const inner = fields.signature(); // the variant's own signature
|
|
896
|
+
const value = readValue(fields, inner);
|
|
897
|
+
switch (code) {
|
|
898
|
+
case F_PATH:
|
|
899
|
+
out.path = String(value);
|
|
900
|
+
break;
|
|
901
|
+
case F_INTERFACE:
|
|
902
|
+
out.interface = String(value);
|
|
903
|
+
break;
|
|
904
|
+
case F_MEMBER:
|
|
905
|
+
out.member = String(value);
|
|
906
|
+
break;
|
|
907
|
+
case F_ERROR_NAME:
|
|
908
|
+
out.errorName = String(value);
|
|
909
|
+
break;
|
|
910
|
+
case F_REPLY_SERIAL:
|
|
911
|
+
out.replySerial = Number(value);
|
|
912
|
+
break;
|
|
913
|
+
case F_SENDER:
|
|
914
|
+
out.sender = String(value);
|
|
915
|
+
break;
|
|
916
|
+
case F_SIGNATURE:
|
|
917
|
+
out.signature = String(value);
|
|
918
|
+
break;
|
|
919
|
+
case 9: // UNIX_FDS: an fd-backed call we do not make; the count is all we need
|
|
920
|
+
break;
|
|
921
|
+
default:
|
|
922
|
+
break;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
if (bodyLength > 0 && out.signature) {
|
|
926
|
+
const bodyStart = end + (align8(arrayLength) - arrayLength);
|
|
927
|
+
try {
|
|
928
|
+
out.body = unmarshal(frame.subarray(bodyStart, bodyStart + bodyLength), out.signature);
|
|
929
|
+
} catch (error) {
|
|
930
|
+
out.decodeError = new Error(
|
|
931
|
+
`cannot decode ${out.signature} from ${out.interface ?? "?"}.${out.member ?? "reply"}: ${
|
|
932
|
+
error instanceof Error ? error.message : String(error)
|
|
933
|
+
}`,
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
return out;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
/** PI_PIPPI_DBUS_DEBUG=1 dumps frames; every wire bug so far was invisible without it. */
|
|
941
|
+
function debug(text: string): void {
|
|
942
|
+
if (process.env.PI_PIPPI_DBUS_DEBUG) console.error("[dbus]", text);
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** Frames are long; only `PI_PIPPI_DBUS_DEBUG=full` dumps them whole. */
|
|
946
|
+
function hex(buffer: Buffer): string {
|
|
947
|
+
const limit = process.env.PI_PIPPI_DBUS_DEBUG === "full" ? buffer.length : 240;
|
|
948
|
+
return buffer.toString("hex", 0, Math.min(buffer.length, limit));
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
export function systemBusAddress(): string {
|
|
952
|
+
const configured = process.env.DBUS_SYSTEM_BUS_ADDRESS;
|
|
953
|
+
if (configured) {
|
|
954
|
+
const unix = /^unix:([^]*)$/.exec(configured);
|
|
955
|
+
if (unix?.[1]) {
|
|
956
|
+
const parts = new Map(unix[1].split(",").map((part) => part.split("=") as [string, string]));
|
|
957
|
+
const path = parts.get("path");
|
|
958
|
+
if (path) return path;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
return "/run/dbus/system_bus_socket";
|
|
962
|
+
}
|