/
dbus_client.dart
1205 lines (1085 loc) · 40.9 KB
/
dbus_client.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dbus_address.dart';
import 'dbus_auth_client.dart';
import 'dbus_bus_name.dart';
import 'dbus_error_name.dart';
import 'dbus_interface_name.dart';
import 'dbus_introspectable.dart';
import 'dbus_match_rule.dart';
import 'dbus_member_name.dart';
import 'dbus_message.dart';
import 'dbus_method_call.dart';
import 'dbus_method_response.dart';
import 'dbus_object.dart';
import 'dbus_object_manager.dart';
import 'dbus_object_tree.dart';
import 'dbus_peer.dart';
import 'dbus_properties.dart';
import 'dbus_read_buffer.dart';
import 'dbus_signal.dart';
import 'dbus_value.dart';
import 'dbus_write_buffer.dart';
import 'getuid.dart';
/// Reply received when calling [DBusClient.requestName].
enum DBusRequestNameReply { primaryOwner, inQueue, exists, alreadyOwner }
/// Flags passed to [DBusClient.requestName].
enum DBusRequestNameFlag { allowReplacement, replaceExisting, doNotQueue }
/// Reply received when calling [DBusClient.releaseName].
enum DBusReleaseNameReply { released, nonExistant, notOwner }
/// Reply received when calling [DBusClient.startServiceByName].
enum DBusStartServiceByNameReply { success, alreadyRunning }
/// Credentials returned in [DBusClient.getConnectionCredentials].
class DBusProcessCredentials {
/// Unix user ID, if known.
final int? unixUserId;
/// Unix group IDs, if known.
final List<int>? unixGroupIds;
/// Process ID, if known.
final int? processId;
/// Windows security identifier, if known.
final String? windowsSid;
/// Security label, if known and format dependant on the security system in use.
final List<int>? linuxSecurityLabel;
/// Non-standard credentials.
final Map<String, DBusValue> otherCredentials;
const DBusProcessCredentials(
{this.unixUserId,
this.unixGroupIds,
this.processId,
this.windowsSid,
this.linuxSecurityLabel,
this.otherCredentials = const {}});
@override
String toString() {
var parameters = <String, String?>{
'unixUserId': unixUserId?.toString(),
'unixGroupIds': unixGroupIds?.toString(),
'processId': processId?.toString(),
'windowsSid': windowsSid?.toString(),
'linuxSecurityLabel': linuxSecurityLabel?.toString(),
'otherCredentials':
otherCredentials.isNotEmpty ? otherCredentials.toString() : null
};
return 'DBusProcessCredentials(' +
parameters.keys
.where((key) => parameters[key] != null)
.map((key) => '$key=${parameters[key]}')
.join(', ') +
')';
}
}
/// A stream of signals.
class DBusSignalStream extends Stream<DBusSignal> {
final DBusClient _client;
final DBusMatchRule _rule;
final DBusSignature? _signature;
final _controller = StreamController<DBusSignal>();
/// Creates a stream of signals that match [sender], [interface], [name], [path] and/or [pathNamespace].
///
/// If [signature] is provided this causes the stream to throw a
/// [DBusSignalSignatureException] if a signal is received that does not
/// match the provided signature.
DBusSignalStream(DBusClient client,
{String? sender,
String? interface,
String? name,
DBusObjectPath? path,
DBusObjectPath? pathNamespace,
DBusSignature? signature})
: _client = client,
_rule = DBusMatchRule(
type: DBusMessageType.signal,
sender: sender != null ? DBusBusName(sender) : null,
interface: interface != null ? DBusInterfaceName(interface) : null,
member: name != null ? DBusMemberName(name) : null,
path: path,
pathNamespace: pathNamespace),
_signature = signature {
_controller.onListen = _onListen;
_controller.onCancel = _onCancel;
}
@override
StreamSubscription<DBusSignal> listen(
void Function(DBusSignal signal)? onData,
{Function? onError,
void Function()? onDone,
bool? cancelOnError}) {
_client._signalStreams.add(this);
return _controller.stream.listen(onData,
onError: onError, onDone: onDone, cancelOnError: cancelOnError);
}
void _onListen() {
if (_rule.sender != null) {
_client._findUniqueName(_rule.sender!);
}
_client._addMatch(_rule.toDBusString());
}
Future<void> _onCancel() async {
await _client._removeMatch(_rule.toDBusString());
_client._signalStreams.remove(this);
}
}
/// Exception thrown when a D-Bus method call returns values that don't match the expected signature.
class DBusReplySignatureException implements Exception {
/// The name of the method call.
final String methodName;
/// The response that generated the exception.
final DBusMethodSuccessResponse response;
DBusReplySignatureException(this.methodName, this.response);
@override
String toString() {
return '$methodName returned invalid values: ${response.returnValues}';
}
}
/// Exception thrown when a D-Bus signal contains values that don't match the expected signature.
class DBusSignalSignatureException implements Exception {
/// The name of the signal.
final String signalName;
/// The signal that generated the exception.
final DBusSignal signal;
DBusSignalSignatureException(this.signalName, this.signal);
@override
String toString() {
return '$signalName received with invalid values: ${signal.values}';
}
}
/// Event generated when a bus name ownership changes.
class DBusNameOwnerChangedEvent {
/// The bus name that has changed ownership.
final String name;
/// The unique bus name of the owner of this name, or null if it was previously unowned.
final String? oldOwner;
/// The unique bus name of the new owner of this name, or null if it is no longer owned.
final String? newOwner;
const DBusNameOwnerChangedEvent(this.name, {this.oldOwner, this.newOwner});
@override
String toString() =>
'DBusNameOwnerChangedEvent($name, oldOwner: $oldOwner, newOwner: $newOwner)';
@override
bool operator ==(other) =>
other is DBusNameOwnerChangedEvent &&
other.name == name &&
other.oldOwner == oldOwner &&
other.newOwner == newOwner;
@override
int get hashCode =>
name.hashCode | (oldOwner?.hashCode ?? 0) | (newOwner?.hashCode ?? 0);
}
/// Exception thrown when a request is sent and the connection to the D-Bus server is closed.
class DBusClosedException implements Exception {}
/// A client connection to a D-Bus server.
class DBusClient {
final DBusAddress _address;
Socket? _socket;
var _socketClosed = false;
final _readBuffer = DBusReadBuffer();
final _authClient = DBusAuthClient();
var _authComplete = false;
Completer? _connectCompleter;
var _lastSerial = 0;
final _methodCalls = <int, Completer<DBusMethodResponse>>{};
final _signalStreams = <DBusSignalStream>[];
StreamSubscription<String>? _nameAcquiredSubscription;
StreamSubscription<String>? _nameLostSubscription;
StreamSubscription<DBusNameOwnerChangedEvent>? _nameOwnerSubscription;
final _objectTree = DBusObjectTree();
final _matchRules = <String, int>{};
// Maps D-Bus names (e.g. 'org.freedesktop.DBus') to unique names (e.g. ':1').
final _nameOwners = <DBusBusName, DBusBusName>{};
// Names owned by this client. e.g. [ 'com.example.Foo', 'com.example.Bar' ].
final _ownedNames = <DBusBusName>{};
// Unique name of this client, e.g. ':42'.
DBusBusName? _uniqueName;
/// True if this client allows other clients to introspect it.
final bool introspectable;
/// Creates a new DBus client to connect on [address].
DBusClient(DBusAddress address, {this.introspectable = true})
: _address = address;
/// Creates a new DBus client to communicate with the system bus.
factory DBusClient.system({bool introspectable = true}) {
var address = Platform.environment['DBUS_SYSTEM_BUS_ADDRESS'];
return DBusClient(
DBusAddress(address ??= 'unix:path=/var/run/dbus/system_bus_socket'),
introspectable: introspectable);
}
/// Creates a new DBus client to communicate with the session bus.
factory DBusClient.session({bool introspectable = true}) {
var address = Platform.environment['DBUS_SESSION_BUS_ADDRESS'];
if (address == null) {
var runtimeDir = Platform.environment['XDG_USER_DIR'];
if (runtimeDir == null) {
var uid = getuid();
runtimeDir = '/run/user/$uid';
}
address = 'unix:path=$runtimeDir/bus';
}
return DBusClient(DBusAddress(address), introspectable: introspectable);
}
/// Terminates all active connections. If a client remains unclosed, the Dart process may not terminate.
Future<void> close() async {
if (_nameAcquiredSubscription != null) {
await _nameAcquiredSubscription?.cancel();
}
if (_nameLostSubscription != null) {
await _nameLostSubscription?.cancel();
}
if (_nameOwnerSubscription != null) {
await _nameOwnerSubscription?.cancel();
}
if (_socket != null) {
await _socket?.close();
}
}
/// Gets the unique name this connection uses.
String get uniqueName => _uniqueName?.value ?? '';
/// Gets the names owned by this connection.
Iterable<String> get ownedNames => _ownedNames.map((name) => name.value);
/// Stream of names as they are acquired by this client.
Stream<String> get nameAcquired => DBusSignalStream(this,
sender: 'org.freedesktop.DBus',
interface: 'org.freedesktop.DBus',
name: 'NameAcquired',
signature: DBusSignature('s'))
.map((signal) => (signal.values[0] as DBusString).value);
/// Stream of names as this client loses them.
Stream<String> get nameLost => DBusSignalStream(this,
sender: 'org.freedesktop.DBus',
interface: 'org.freedesktop.DBus',
name: 'NameLost',
signature: DBusSignature('s'))
.map((signal) => (signal.values[0] as DBusString).value);
/// Stream of name change events as this client loses them.
Stream<DBusNameOwnerChangedEvent> get nameOwnerChanged =>
DBusSignalStream(this,
sender: 'org.freedesktop.DBus',
interface: 'org.freedesktop.DBus',
name: 'NameOwnerChanged',
signature: DBusSignature('sss'))
.map((signal) {
var name = (signal.values[0] as DBusString).value;
var oldOwner = (signal.values[1] as DBusString).value;
var newOwner = (signal.values[2] as DBusString).value;
return DBusNameOwnerChangedEvent(name,
oldOwner: oldOwner != '' ? oldOwner : null,
newOwner: newOwner != '' ? newOwner : null);
});
/// Requests usage of [name] as a D-Bus object name.
Future<DBusRequestNameReply> requestName(String name,
{Set<DBusRequestNameFlag> flags = const {}}) async {
var flagsValue = 0;
for (var flag in flags) {
switch (flag) {
case DBusRequestNameFlag.allowReplacement:
flagsValue |= 0x1;
break;
case DBusRequestNameFlag.replaceExisting:
flagsValue |= 0x2;
break;
case DBusRequestNameFlag.doNotQueue:
flagsValue |= 0x4;
break;
}
}
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'RequestName',
values: [DBusString(name), DBusUint32(flagsValue)],
replySignature: DBusSignature('u'));
var returnCode = (result.returnValues[0] as DBusUint32).value;
switch (returnCode) {
case 1:
_ownedNames.add(DBusBusName(name));
return DBusRequestNameReply.primaryOwner;
case 2:
return DBusRequestNameReply.inQueue;
case 3:
return DBusRequestNameReply.exists;
case 4:
return DBusRequestNameReply.alreadyOwner;
default:
throw 'org.freedesktop.DBusRequestName returned unknown return code: $returnCode';
}
}
/// Releases the D-Bus object name previously acquired using requestName().
Future<DBusReleaseNameReply> releaseName(String name) async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'ReleaseName',
values: [DBusString(name)],
replySignature: DBusSignature('u'));
var returnCode = (result.returnValues[0] as DBusUint32).value;
switch (returnCode) {
case 1:
_ownedNames.remove(DBusBusName(name));
return DBusReleaseNameReply.released;
case 2:
return DBusReleaseNameReply.nonExistant;
case 3:
return DBusReleaseNameReply.notOwner;
default:
throw 'org.freedesktop.DBus.ReleaseName returned unknown return code: $returnCode';
}
}
/// Lists the unique bus names of the clients queued to own the well-known bus [name].
Future<List<String>> listQueuedOwners(String name) async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'ListQueuedOwners',
values: [DBusString(name)],
replySignature: DBusSignature('as'));
return (result.returnValues[0] as DBusArray)
.children
.map((v) => (v as DBusString).value)
.toList();
}
/// Lists the registered names on the bus.
Future<List<String>> listNames() async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'ListNames',
replySignature: DBusSignature('as'));
return (result.returnValues[0] as DBusArray)
.children
.map((v) => (v as DBusString).value)
.toList();
}
/// Returns a list of names that activate services.
Future<List<String>> listActivatableNames() async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'ListActivatableNames',
replySignature: DBusSignature('as'));
return (result.returnValues[0] as DBusArray)
.children
.map((v) => (v as DBusString).value)
.toList();
}
/// Starts the service with [name].
Future<DBusStartServiceByNameReply> startServiceByName(String name) async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'StartServiceByName',
values: [DBusString(name), DBusUint32(0)],
replySignature: DBusSignature('u'));
var returnCode = (result.returnValues[0] as DBusUint32).value;
switch (returnCode) {
case 1:
return DBusStartServiceByNameReply.success;
case 2:
return DBusStartServiceByNameReply.alreadyRunning;
default:
throw 'org.freedesktop.DBus.StartServiceByName returned unknown return code: $returnCode';
}
}
/// Returns true if the [name] is currently registered on the bus.
Future<bool> nameHasOwner(String name) async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'NameHasOwner',
values: [DBusString(name)],
replySignature: DBusSignature('b'));
return (result.returnValues[0] as DBusBoolean).value;
}
/// Returns the unique connection name of the client that owns [name].
Future<String?> getNameOwner(String name) async {
DBusMethodSuccessResponse result;
try {
result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'GetNameOwner',
values: [DBusString(name)],
replySignature: DBusSignature('s'));
} on DBusMethodResponseException catch (e) {
if (e.response.errorName == 'org.freedesktop.DBus.Error.NameHasNoOwner') {
return null;
}
rethrow;
}
return (result.returnValues[0] as DBusString).value;
}
/// Returns the Unix user ID of the process running the client that owns [name].
Future<int> getConnectionUnixUser(String name) async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'GetConnectionUnixUser',
values: [DBusString(name)],
replySignature: DBusSignature('u'));
return (result.returnValues[0] as DBusUint32).value;
}
/// Returns the Unix process ID of the process running the client that owns [name].
Future<int> getConnectionUnixProcessId(String name) async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'GetConnectionUnixProcessID',
values: [DBusString(name)],
replySignature: DBusSignature('u'));
return (result.returnValues[0] as DBusUint32).value;
}
/// Returns credentials for the process running the client that owns [name].
Future<DBusProcessCredentials> getConnectionCredentials(String name) async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'GetConnectionCredentials',
values: [DBusString(name)],
replySignature: DBusSignature('a{sv}'));
var credentials = (result.returnValues[0] as DBusDict)
.children
.map((key, value) => MapEntry((key as DBusString).value, value));
int? unixUserId;
List<int>? unixGroupIds;
int? processId;
String? windowsSid;
List<int>? linuxSecurityLabel;
var otherCredentials = <String, DBusValue>{};
credentials.forEach((key, v) {
var value = (v as DBusVariant).value;
switch (key) {
case 'UnixUserID':
if (value.signature != DBusSignature('u')) {
throw 'org.freedesktop.DBus.GetConnectionCredentials returned invalid signature on UnixUserID: ${value.signature.value}';
}
unixUserId = (value as DBusUint32).value;
break;
case 'UnixGroupIDs':
if (value.signature != DBusSignature('au')) {
throw 'org.freedesktop.DBus.GetConnectionCredentials returned invalid signature on UnixGroupIDs: ${value.signature.value}';
}
unixGroupIds = (value as DBusArray)
.children
.map((v) => (v as DBusUint32).value)
.toList();
break;
case 'ProcessID':
if (value.signature != DBusSignature('u')) {
throw 'org.freedesktop.DBus.GetConnectionCredentials returned invalid signature on ProcessID: ${value.signature.value}';
}
processId = (value as DBusUint32).value;
break;
case 'WindowsSID':
if (value.signature != DBusSignature('s')) {
throw 'org.freedesktop.DBus.GetConnectionCredentials returned invalid signature on WindowsSID: ${value.signature.value}';
}
windowsSid = (value as DBusString).value;
break;
case 'LinuxSecurityLabel':
if (value.signature != DBusSignature('ay')) {
throw 'org.freedesktop.DBus.GetConnectionCredentials returned invalid signature on LinuxSecurityLabel: ${value.signature.value}';
}
linuxSecurityLabel = (value as DBusArray)
.children
.map((v) => (v as DBusByte).value)
.toList();
break;
default:
otherCredentials[key] = value;
break;
}
});
return DBusProcessCredentials(
unixUserId: unixUserId,
unixGroupIds: unixGroupIds,
processId: processId,
windowsSid: windowsSid,
linuxSecurityLabel: linuxSecurityLabel,
otherCredentials: otherCredentials);
}
/// Gets the unique ID of the bus.
Future<String> getId() async {
var result = await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'GetId',
replySignature: DBusSignature('s'));
return (result.returnValues[0] as DBusString).value;
}
/// Sends a ping request to the client at the given [destination].
/// If [destination] is not set, pings the D-Bus server.
Future<void> ping([String destination = 'org.freedesktop.DBus']) async {
await callMethod(
destination: destination,
path: DBusObjectPath('/'),
interface: 'org.freedesktop.DBus.Peer',
name: 'Ping',
replySignature: DBusSignature(''));
}
/// Gets the machine ID of the client at the given [destination].
/// If [destination] is not set, gets the machine the D-Bus server is running on.
Future<String> getMachineId(
[String destination = 'org.freedesktop.DBus']) async {
var result = await callMethod(
destination: destination,
path: DBusObjectPath('/'),
interface: 'org.freedesktop.DBus.Peer',
name: 'GetMachineId',
replySignature: DBusSignature('s'));
return (result.returnValues[0] as DBusString).value;
}
/// Invokes a method on a D-Bus object.
/// Throws [DBusMethodResponseException] if the remote side returns an error.
///
/// If [replySignature] is provided this causes this method to throw a
/// [DBusReplySignatureException] if the result is successful but the returned
/// values do not match the provided signature.
///
/// Throws [DBusServiceUnknownException] if [destination] is not a provided service.
/// Throws [DBusUnknownObjectException] if no object is provided at [path].
/// Throws [DBusUnknownInterfaceException] if [interface] is not provided by this object.
/// Throws [DBusUnknownMethodException] if the method with [name] is not available.
/// Throws [DBusInvalidArgsException] if [values] aren't correct.
Future<DBusMethodSuccessResponse> callMethod(
{String? destination,
required DBusObjectPath path,
String? interface,
required String name,
Iterable<DBusValue> values = const [],
DBusSignature? replySignature,
bool noReplyExpected = false,
bool noAutoStart = false,
bool allowInteractiveAuthorization = false}) async {
await _connect();
return await _callMethod(
destination: destination != null ? DBusBusName(destination) : null,
path: path,
interface: interface != null ? DBusInterfaceName(interface) : null,
name: DBusMemberName(name),
values: values,
replySignature: replySignature,
noReplyExpected: noReplyExpected,
noAutoStart: noAutoStart,
allowInteractiveAuthorization: allowInteractiveAuthorization);
}
/// Find the unique name for a D-Bus client.
Future<DBusBusName?> _findUniqueName(DBusBusName name) async {
if (_nameOwners.containsValue(name)) return _nameOwners[name];
var uniqueName = await getNameOwner(name.value);
if (uniqueName == null) {
return null;
}
var uniqueName_ = DBusBusName(uniqueName);
_nameOwners[name] = uniqueName_;
return uniqueName_;
}
/// Emits a signal from a D-Bus object.
Future<void> emitSignal(
{String? destination,
required DBusObjectPath path,
required String interface,
required String name,
Iterable<DBusValue> values = const []}) async {
await _connect();
_sendSignal(destination != null ? DBusBusName(destination) : null, path,
DBusInterfaceName(interface), DBusMemberName(name), values);
}
/// Searches for an object manager in [node] or any of its parents.
DBusObject? _findObjectManager(DBusObjectTreeNode? node) {
if (node == null) {
return null;
}
var object = node.object;
if (object != null) {
if (object.isObjectManager) {
return object;
}
}
return _findObjectManager(node.parent);
}
/// Registers an [object] on the bus.
Future<void> registerObject(DBusObject object) async {
if (object.client != null) {
if (object.client == this) {
throw 'Object already registered';
} else {
throw 'Object already registered on other client';
}
}
object.client = this;
var node = _objectTree.add(object.path, object);
await _connect();
// If has an object manager as a parent, emit a signal to indicate this was added.
var objectManager = _findObjectManager(node.parent);
if (objectManager != null) {
var interfacesAndProperties = expandObjectInterfaceAndProperties(object,
introspectable: introspectable);
await objectManager.emitInterfacesAdded(
object.path, interfacesAndProperties);
}
}
/// Unregisters an [object] on the bus.
Future<void> unregisterObject(DBusObject object) async {
if (object.client == null) {
throw 'Object not registered';
}
if (object.client != this) {
throw 'Object registered on other client';
}
var node = _objectTree.lookup(object.path);
if (node == null) {
return;
}
_objectTree.remove(object.path);
// If has an object manager as a parent, emit a signal to indicate this was removed.
var objectManager = _findObjectManager(node.parent);
if (objectManager != null) {
var interfacesAndProperties = expandObjectInterfaceAndProperties(object,
introspectable: introspectable);
await objectManager.emitInterfacesRemoved(
object.path, interfacesAndProperties.keys);
}
}
/// Open a socket connection to the D-Bus server.
Future<void> _openSocket() async {
InternetAddress socketAddress;
var port = 0;
switch (_address.transport) {
case 'unix':
var path = _address.properties['path'];
if (path == null) {
path = _address.properties['abstract'];
if (path == null) {
throw "Unable to determine D-Bus unix address path from address '$_address'";
}
// Dart expects abstract unix socket paths to be prepended with '@'.
path = '@$path';
}
socketAddress = InternetAddress(path, type: InternetAddressType.unix);
break;
case 'tcp':
var host = _address.properties['host'];
if (host == null) {
throw "'Unable to determine hostname from address '$_address'";
}
InternetAddressType type;
var family = _address.properties['family'];
switch (family) {
case null:
type = InternetAddressType.any;
break;
case 'ipv4':
type = InternetAddressType.IPv4;
break;
case 'ipv6':
type = InternetAddressType.IPv6;
break;
default:
throw "Invalid D-Bus address family: '$family'";
}
try {
port = int.parse(_address.properties['port'] ?? '0');
} on FormatException {
throw "Invalid port number in address '$_address'";
}
var addresses = await InternetAddress.lookup(host, type: type);
if (addresses.isEmpty) {
throw "Failed to resolve host '$host'";
}
socketAddress = addresses[0];
break;
default:
throw 'D-Bus address transport not supported: $_address';
}
_socket = await Socket.connect(socketAddress, port);
if (_socket != null) {
_socket!.listen(_processData,
onError: (error) {}, onDone: () => _socket!.close());
// ignore: unawaited_futures
_socket!.done.then((value) {
_socketClosed = true;
});
}
}
/// Connects to the D-Bus server.
Future<void> _connect() async {
// If already connecting, wait for that to complete.
if (_connectCompleter != null) {
return _connectCompleter?.future;
}
_connectCompleter = Completer();
await _openSocket();
_authClient.requests.listen((message) => _socket?.write(message + '\r\n'));
await _authClient.done;
_authComplete = true;
if (!_authClient.isAuthenticated) {
await _socket?.close();
return;
}
// The first message to the bus must be this call, note requireConnect is
// false as the _connect call hasn't yet completed and would otherwise have
// been called again.
var result = await _callMethod(
destination: DBusBusName('org.freedesktop.DBus'),
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: DBusInterfaceName('org.freedesktop.DBus'),
name: DBusMemberName('Hello'),
replySignature: DBusSignature('s'));
_uniqueName = DBusBusName((result.returnValues[0] as DBusString).value);
// Notify anyone else awaiting connection.
_connectCompleter?.complete();
// Monitor name ownership so we know what names we have, and can match incoming signals from other clients.
_nameAcquiredSubscription = nameAcquired.listen((name) {
var busName = DBusBusName(name);
_nameOwners[busName] = _uniqueName!;
_ownedNames.add(busName);
});
_nameLostSubscription = nameLost.listen((name) {
var busName = DBusBusName(name);
_nameOwners.remove(busName);
_ownedNames.remove(busName);
});
_nameOwnerSubscription = nameOwnerChanged.listen((event) {
var busName = DBusBusName(event.name);
if (event.newOwner != null) {
_nameOwners[busName] = DBusBusName(event.newOwner!);
} else {
_nameOwners.remove(busName);
}
});
}
/// Adds a rule to match which messages to receive.
Future<void> _addMatch(String rule) async {
var count = _matchRules[rule];
if (count == null) {
_matchRules[rule] = 1;
await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'AddMatch',
values: [DBusString(rule)],
replySignature: DBusSignature(''));
} else {
_matchRules[rule] = count + 1;
}
}
/// Removes an existing rule to match which messages to receive.
Future<void> _removeMatch(String rule) async {
var count = _matchRules[rule];
if (count == null) {
throw 'Attempted to remove match that is not added: $rule';
}
if (count == 1) {
_matchRules.remove(rule);
if (!_socketClosed) {
await callMethod(
destination: 'org.freedesktop.DBus',
path: DBusObjectPath('/org/freedesktop/DBus'),
interface: 'org.freedesktop.DBus',
name: 'RemoveMatch',
values: [DBusString(rule)],
replySignature: DBusSignature(''));
}
} else {
_matchRules[rule] = count - 1;
}
}
/// Processes incoming data from the D-Bus server.
void _processData(Uint8List data) {
_readBuffer.writeBytes(data);
var complete = false;
while (!complete) {
if (!_authComplete) {
complete = _processAuth();
} else {
complete = _processMessages();
}
_readBuffer.flush();
}
}
/// Processes authentication messages received from the D-Bus server.
bool _processAuth() {
var line = _readBuffer.readLine();
if (line == null) {
return true;
}
_authClient.processResponse(line);
return false;
}
/// Processes messages (method calls/returns/errors/signals) received from the D-Bus server.
bool _processMessages() {
var start = _readBuffer.readOffset;
var message = _readBuffer.readMessage();
if (message == null) {
_readBuffer.readOffset = start;
return true;
}
if (message.type == DBusMessageType.methodCall) {
_processMethodCall(message);
} else if (message.type == DBusMessageType.methodReturn ||
message.type == DBusMessageType.error) {
_processMethodResponse(message);
} else if (message.type == DBusMessageType.signal) {
_processSignal(message);
}
return false;
}
/// Processes a method call from the D-Bus server.
Future<void> _processMethodCall(DBusMessage message) async {
DBusObjectTreeNode? node;
if (message.path != null) {
node = _objectTree.lookup(message.path!);
}
var object = node?.object;
var methodCall = DBusMethodCall(
sender: message.sender?.value ?? '',
interface: message.interface?.value,
name: message.member?.value ?? '',
values: message.values,
noReplyExpected:
message.flags.contains(DBusMessageFlag.noReplyExpected),
noAutoStart: message.flags.contains(DBusMessageFlag.noAutoStart),
allowInteractiveAuthorization: message.flags
.contains(DBusMessageFlag.allowInteractiveAuthorization));
DBusMethodResponse response;
if (message.member == null) {
response = DBusMethodErrorResponse.unknownMethod();
} else if (message.interface?.value == 'org.freedesktop.DBus.Peer') {
response = await handlePeerMethodCall(methodCall);
} else if (introspectable &&
message.interface?.value == 'org.freedesktop.DBus.Introspectable') {
response = handleIntrospectableMethodCall(node, methodCall);
} else if (object == null) {
response = DBusMethodErrorResponse.unknownObject();
} else if (message.interface?.value == 'org.freedesktop.DBus.Properties') {
response = await handlePropertiesMethodCall(object, methodCall);
} else if (object.isObjectManager &&
message.interface?.value == 'org.freedesktop.DBus.ObjectManager') {
response = handleObjectManagerMethodCall(_objectTree, methodCall,
introspectable: introspectable);
} else {
response = await object.handleMethodCall(methodCall);
}
if (message.flags.contains(DBusMessageFlag.noReplyExpected)) {
return;
}
if (_socketClosed) {
return;
}
if (response is DBusMethodErrorResponse) {
_sendError(
message.serial, message.sender, response.errorName, response.values);
} else if (response is DBusMethodSuccessResponse) {
_sendReturn(message.serial, message.sender, response.values);
}
}
/// Processes a method return or error result from the D-Bus server.
void _processMethodResponse(DBusMessage message) {
// Check has required fields.
if (message.replySerial == null) {
return;
}
var completer = _methodCalls[message.replySerial];
if (completer == null) {