dbus-fast 2.46.1__cp311-cp311-musllinux_1_2_aarch64.whl

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.

Potentially problematic release.


This version of dbus-fast might be problematic. Click here for more details.

Files changed (51) hide show
  1. dbus_fast/__init__.py +82 -0
  2. dbus_fast/__version__.py +10 -0
  3. dbus_fast/_private/__init__.py +1 -0
  4. dbus_fast/_private/_cython_compat.py +14 -0
  5. dbus_fast/_private/address.cpython-311-aarch64-linux-musl.so +0 -0
  6. dbus_fast/_private/address.pxd +15 -0
  7. dbus_fast/_private/address.py +117 -0
  8. dbus_fast/_private/constants.py +20 -0
  9. dbus_fast/_private/marshaller.cpython-311-aarch64-linux-musl.so +0 -0
  10. dbus_fast/_private/marshaller.pxd +110 -0
  11. dbus_fast/_private/marshaller.py +229 -0
  12. dbus_fast/_private/unmarshaller.cpython-311-aarch64-linux-musl.so +0 -0
  13. dbus_fast/_private/unmarshaller.pxd +261 -0
  14. dbus_fast/_private/unmarshaller.py +902 -0
  15. dbus_fast/_private/util.py +177 -0
  16. dbus_fast/aio/__init__.py +5 -0
  17. dbus_fast/aio/message_bus.py +579 -0
  18. dbus_fast/aio/message_reader.cpython-311-aarch64-linux-musl.so +0 -0
  19. dbus_fast/aio/message_reader.pxd +13 -0
  20. dbus_fast/aio/message_reader.py +49 -0
  21. dbus_fast/aio/proxy_object.py +207 -0
  22. dbus_fast/auth.py +125 -0
  23. dbus_fast/constants.py +152 -0
  24. dbus_fast/errors.py +81 -0
  25. dbus_fast/glib/__init__.py +3 -0
  26. dbus_fast/glib/message_bus.py +513 -0
  27. dbus_fast/glib/proxy_object.py +318 -0
  28. dbus_fast/introspection.py +682 -0
  29. dbus_fast/message.cpython-311-aarch64-linux-musl.so +0 -0
  30. dbus_fast/message.pxd +76 -0
  31. dbus_fast/message.py +387 -0
  32. dbus_fast/message_bus.cpython-311-aarch64-linux-musl.so +0 -0
  33. dbus_fast/message_bus.pxd +75 -0
  34. dbus_fast/message_bus.py +1326 -0
  35. dbus_fast/proxy_object.py +357 -0
  36. dbus_fast/py.typed +0 -0
  37. dbus_fast/send_reply.py +61 -0
  38. dbus_fast/service.cpython-311-aarch64-linux-musl.so +0 -0
  39. dbus_fast/service.pxd +50 -0
  40. dbus_fast/service.py +699 -0
  41. dbus_fast/signature.cpython-311-aarch64-linux-musl.so +0 -0
  42. dbus_fast/signature.pxd +31 -0
  43. dbus_fast/signature.py +482 -0
  44. dbus_fast/unpack.cpython-311-aarch64-linux-musl.so +0 -0
  45. dbus_fast/unpack.pxd +13 -0
  46. dbus_fast/unpack.py +24 -0
  47. dbus_fast/validators.py +199 -0
  48. dbus_fast-2.46.1.dist-info/METADATA +262 -0
  49. dbus_fast-2.46.1.dist-info/RECORD +51 -0
  50. dbus_fast-2.46.1.dist-info/WHEEL +4 -0
  51. dbus_fast-2.46.1.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,1326 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import logging
5
+ import socket
6
+ import traceback
7
+ import xml.etree.ElementTree as ET
8
+ from collections.abc import Callable
9
+ from contextlib import ExitStack
10
+ from functools import partial
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from . import introspection as intr
14
+ from ._private.address import get_bus_address, parse_address
15
+ from ._private.util import replace_fds_with_idx, replace_idx_with_fds
16
+ from .constants import (
17
+ BusType,
18
+ ErrorType,
19
+ MessageFlag,
20
+ MessageType,
21
+ NameFlag,
22
+ ReleaseNameReply,
23
+ RequestNameReply,
24
+ )
25
+ from .errors import DBusError, InvalidAddressError
26
+ from .message import Message
27
+ from .proxy_object import BaseProxyObject
28
+ from .send_reply import SendReply
29
+ from .service import HandlerType, ServiceInterface, _Method, _Property
30
+ from .signature import Variant
31
+ from .validators import assert_bus_name_valid, assert_object_path_valid
32
+
33
+ MESSAGE_TYPE_CALL = MessageType.METHOD_CALL
34
+ MESSAGE_TYPE_SIGNAL = MessageType.SIGNAL
35
+ NO_REPLY_EXPECTED_VALUE = MessageFlag.NO_REPLY_EXPECTED.value
36
+ NO_REPLY_EXPECTED = MessageFlag.NO_REPLY_EXPECTED
37
+ NONE = MessageFlag.NONE
38
+ _LOGGER = logging.getLogger(__name__)
39
+
40
+
41
+ _Message = Message
42
+
43
+
44
+ def _expects_reply(msg: _Message) -> bool:
45
+ """Whether a message expects a reply."""
46
+ if msg.flags is NO_REPLY_EXPECTED:
47
+ return False
48
+ if msg.flags is NONE:
49
+ return True
50
+ # Slow check for NO_REPLY_EXPECTED
51
+ flag_value = msg.flags.value
52
+ return not (flag_value & NO_REPLY_EXPECTED_VALUE)
53
+
54
+
55
+ def _block_unexpected_reply(reply: _Message) -> None:
56
+ """Block a reply if it's not expected.
57
+
58
+ Previously we silently ignored replies that were not expected, but this
59
+ lead to implementation errors that were hard to debug. Now we log a
60
+ debug message instead.
61
+ """
62
+ _LOGGER.debug(
63
+ "Blocked attempt to send a reply from handler "
64
+ "that received a message with flag "
65
+ "MessageFlag.NO_REPLY_EXPECTED: %s",
66
+ reply,
67
+ )
68
+
69
+
70
+ BLOCK_UNEXPECTED_REPLY = _block_unexpected_reply
71
+
72
+
73
+ class BaseMessageBus:
74
+ """An abstract class to manage a connection to a DBus message bus.
75
+
76
+ The message bus class is the entry point into all the features of the
77
+ library. It sets up a connection to the DBus daemon and exposes an
78
+ interface to send and receive messages and expose services.
79
+
80
+ This class is not meant to be used directly by users. For more information,
81
+ see the documentation for the implementation of the message bus you plan to
82
+ use.
83
+
84
+ :param bus_type: The type of bus to connect to. Affects the search path for
85
+ the bus address.
86
+ :type bus_type: :class:`BusType <dbus_fast.BusType>`
87
+ :param bus_address: A specific bus address to connect to. Should not be
88
+ used under normal circumstances.
89
+ :type bus_address: str
90
+ :param ProxyObject: The proxy object implementation for this message bus.
91
+ Must be passed in by an implementation that supports the high-level client.
92
+ :type ProxyObject: Type[:class:`BaseProxyObject
93
+ <dbus_fast.proxy_object.BaseProxyObject>`]
94
+
95
+ :ivar unique_name: The unique name of the message bus connection. It will
96
+ be :class:`None` until the message bus connects.
97
+ :vartype unique_name: str
98
+ :ivar connected: True if this message bus is expected to be able to send
99
+ and receive messages.
100
+ :vartype connected: bool
101
+ """
102
+
103
+ __slots__ = (
104
+ "_ProxyObject",
105
+ "_bus_address",
106
+ "_disconnected",
107
+ "_fd",
108
+ "_high_level_client_initialized",
109
+ "_machine_id",
110
+ "_match_rules",
111
+ "_method_return_handlers",
112
+ "_name_owner_match_rule",
113
+ "_name_owners",
114
+ "_negotiate_unix_fd",
115
+ "_path_exports",
116
+ "_serial",
117
+ "_sock",
118
+ "_stream",
119
+ "_user_disconnect",
120
+ "_user_message_handlers",
121
+ "unique_name",
122
+ )
123
+
124
+ def __init__(
125
+ self,
126
+ bus_address: str | None = None,
127
+ bus_type: BusType = BusType.SESSION,
128
+ ProxyObject: type[BaseProxyObject] | None = None,
129
+ negotiate_unix_fd: bool = False,
130
+ ) -> None:
131
+ self.unique_name: str | None = None
132
+ self._disconnected = False
133
+ self._negotiate_unix_fd = negotiate_unix_fd
134
+
135
+ # True if the user disconnected himself, so don't throw errors out of
136
+ # the main loop.
137
+ self._user_disconnect = False
138
+
139
+ self._method_return_handlers: dict[
140
+ int, Callable[[Message | None, Exception | None], None]
141
+ ] = {}
142
+ self._serial = 0
143
+ self._user_message_handlers: list[
144
+ Callable[[Message], Message | bool | None]
145
+ ] = []
146
+ # the key is the name and the value is the unique name of the owner.
147
+ # This cache is kept up to date by the NameOwnerChanged signal and is
148
+ # used to route messages to the correct proxy object. (used for the
149
+ # high level client only)
150
+ self._name_owners: dict[str, str] = {}
151
+ # used for the high level service
152
+ self._path_exports: dict[str, dict[str, ServiceInterface]] = {}
153
+ self._bus_address = (
154
+ parse_address(bus_address)
155
+ if bus_address
156
+ else parse_address(get_bus_address(bus_type))
157
+ )
158
+ # the bus implementations need this rule for the high level client to
159
+ # work correctly.
160
+ self._name_owner_match_rule = "sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',path='/org/freedesktop/DBus',member='NameOwnerChanged'"
161
+ # _match_rules: the keys are match rules and the values are ref counts
162
+ # (used for the high level client only)
163
+ self._match_rules: dict[str, int] = {}
164
+ self._high_level_client_initialized = False
165
+ self._ProxyObject = ProxyObject
166
+
167
+ # machine id is lazy loaded
168
+ self._machine_id: int | None = None
169
+ self._sock: socket.socket | None = None
170
+ self._fd: int | None = None
171
+ self._stream: Any | None = None
172
+
173
+ self._setup_socket()
174
+
175
+ @property
176
+ def connected(self) -> bool:
177
+ if self.unique_name is None or self._disconnected or self._user_disconnect:
178
+ return False
179
+ return True
180
+
181
+ def export(self, path: str, interface: ServiceInterface) -> None:
182
+ """Export the service interface on this message bus to make it available
183
+ to other clients.
184
+
185
+ :param path: The object path to export this interface on.
186
+ :type path: str
187
+ :param interface: The service interface to export.
188
+ :type interface: :class:`ServiceInterface
189
+ <dbus_fast.service.ServiceInterface>`
190
+
191
+ :raises:
192
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
193
+ - :class:`ValueError` - If an interface with this name is already exported on the message bus at this path
194
+ """
195
+ assert_object_path_valid(path)
196
+ if not isinstance(interface, ServiceInterface):
197
+ raise TypeError("interface must be a ServiceInterface")
198
+
199
+ if path not in self._path_exports:
200
+ self._path_exports[path] = {}
201
+ elif interface.name in self._path_exports[path]:
202
+ raise ValueError(
203
+ f'An interface with this name is already exported on this bus at path "{path}": "{interface.name}"'
204
+ )
205
+
206
+ ServiceInterface._add_bus(interface, self, self._make_method_handler)
207
+ self._path_exports[path][interface.name] = interface
208
+ self._emit_interface_added(path, interface)
209
+
210
+ def unexport(
211
+ self, path: str, interface: ServiceInterface | str | None = None
212
+ ) -> None:
213
+ """Unexport the path or service interface to make it no longer
214
+ available to clients.
215
+
216
+ :param path: The object path to unexport.
217
+ :type path: str
218
+ :param interface: The interface instance or the name of the interface
219
+ to unexport. If ``None``, unexport every interface on the path.
220
+ :type interface: :class:`ServiceInterface
221
+ <dbus_fast.service.ServiceInterface>` or str or None
222
+
223
+ :raises:
224
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
225
+ """
226
+ assert_object_path_valid(path)
227
+ interface_name: str | None
228
+ if interface is None:
229
+ interface_name = None
230
+ elif type(interface) is str:
231
+ interface_name = interface
232
+ elif isinstance(interface, ServiceInterface):
233
+ interface_name = interface.name
234
+ else:
235
+ raise TypeError(
236
+ f"interface must be a ServiceInterface or interface name not {type(interface)}"
237
+ )
238
+
239
+ if (interfaces := self._path_exports.get(path)) is None:
240
+ return
241
+ removed_interface_names: list[str] = []
242
+
243
+ if interface_name is not None:
244
+ if (removed_interface := interfaces.pop(interface_name, None)) is None:
245
+ return
246
+ removed_interface_names.append(interface_name)
247
+ if not interfaces:
248
+ del self._path_exports[path]
249
+ ServiceInterface._remove_bus(removed_interface, self)
250
+ else:
251
+ del self._path_exports[path]
252
+ for removed_interface in interfaces.values():
253
+ removed_interface_names.append(removed_interface.name)
254
+ ServiceInterface._remove_bus(removed_interface, self)
255
+
256
+ self._emit_interface_removed(path, removed_interface_names)
257
+
258
+ def introspect(
259
+ self,
260
+ bus_name: str,
261
+ path: str,
262
+ callback: Callable[[intr.Node | None, Exception | None], None],
263
+ check_callback_type: bool = True,
264
+ validate_property_names: bool = True,
265
+ ) -> None:
266
+ """Get introspection data for the node at the given path from the given
267
+ bus name.
268
+
269
+ Calls the standard ``org.freedesktop.DBus.Introspectable.Introspect``
270
+ on the bus for the path.
271
+
272
+ :param bus_name: The name to introspect.
273
+ :type bus_name: str
274
+ :param path: The path to introspect.
275
+ :type path: str
276
+ :param callback: A callback that will be called with the introspection
277
+ data as a :class:`Node <dbus_fast.introspection.Node>`.
278
+ :type callback: :class:`Callable`
279
+ :param check_callback_type: Whether to check callback type or not.
280
+ :type check_callback_type: bool
281
+ :param validate_property_names: Whether to validate property names or not.
282
+ :type validate_property_names: bool
283
+
284
+ :raises:
285
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
286
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
287
+ """
288
+ if check_callback_type:
289
+ BaseMessageBus._check_callback_type(callback)
290
+
291
+ def reply_notify(reply: Message | None, err: Exception | None) -> None:
292
+ try:
293
+ BaseMessageBus._check_method_return(reply, err, "s")
294
+ result = intr.Node.parse(
295
+ reply.body[0], # type: ignore[union-attr]
296
+ validate_property_names=validate_property_names,
297
+ )
298
+ except Exception as e:
299
+ callback(None, e)
300
+ return
301
+
302
+ callback(result, None)
303
+
304
+ self._call(
305
+ Message(
306
+ destination=bus_name,
307
+ path=path,
308
+ interface="org.freedesktop.DBus.Introspectable",
309
+ member="Introspect",
310
+ ),
311
+ reply_notify,
312
+ )
313
+
314
+ def _emit_interface_added(self, path: str, interface: ServiceInterface) -> None:
315
+ """Emit the ``org.freedesktop.DBus.ObjectManager.InterfacesAdded`` signal.
316
+
317
+ This signal is intended to be used to alert clients when
318
+ a new interface has been added.
319
+
320
+ :param path: Path of exported object.
321
+ :type path: str
322
+ :param interface: Exported service interface.
323
+ :type interface: :class:`ServiceInterface
324
+ <dbus_fast.service.ServiceInterface>`
325
+ """
326
+ if self._disconnected:
327
+ return
328
+
329
+ def get_properties_callback(
330
+ interface: ServiceInterface,
331
+ result: Any,
332
+ user_data: Any,
333
+ e: Exception | None,
334
+ ) -> None:
335
+ if e is not None:
336
+ try:
337
+ raise e
338
+ except Exception:
339
+ _LOGGER.error(
340
+ "An exception ocurred when emitting ObjectManager.InterfacesAdded for %s. "
341
+ "Some properties will not be included in the signal.",
342
+ interface.name,
343
+ exc_info=True,
344
+ )
345
+
346
+ body = {interface.name: result}
347
+
348
+ self.send(
349
+ Message.new_signal(
350
+ path=path,
351
+ interface="org.freedesktop.DBus.ObjectManager",
352
+ member="InterfacesAdded",
353
+ signature="oa{sa{sv}}",
354
+ body=[path, body],
355
+ )
356
+ )
357
+
358
+ ServiceInterface._get_all_property_values(interface, get_properties_callback)
359
+
360
+ def _emit_interface_removed(self, path: str, removed_interfaces: list[str]) -> None:
361
+ """Emit the ``org.freedesktop.DBus.ObjectManager.InterfacesRemoved` signal.
362
+
363
+ This signal is intended to be used to alert clients when
364
+ a interface has been removed.
365
+
366
+ :param path: Path of removed (unexported) object.
367
+ :type path: str
368
+ :param removed_interfaces: List of unexported service interfaces.
369
+ :type removed_interfaces: list[str]
370
+ """
371
+ if self._disconnected:
372
+ return
373
+
374
+ self.send(
375
+ Message.new_signal(
376
+ path=path,
377
+ interface="org.freedesktop.DBus.ObjectManager",
378
+ member="InterfacesRemoved",
379
+ signature="oas",
380
+ body=[path, removed_interfaces],
381
+ )
382
+ )
383
+
384
+ def request_name(
385
+ self,
386
+ name: str,
387
+ flags: NameFlag = NameFlag.NONE,
388
+ callback: None
389
+ | (Callable[[RequestNameReply | None, Exception | None], None]) = None,
390
+ check_callback_type: bool = True,
391
+ ) -> None:
392
+ """Request that this message bus owns the given name.
393
+
394
+ :param name: The name to request.
395
+ :type name: str
396
+ :param flags: Name flags that affect the behavior of the name request.
397
+ :type flags: :class:`NameFlag <dbus_fast.NameFlag>`
398
+ :param callback: A callback that will be called with the reply of the
399
+ request as a :class:`RequestNameReply <dbus_fast.RequestNameReply>`.
400
+ :type callback: :class:`Callable`
401
+
402
+ :raises:
403
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
404
+ """
405
+ assert_bus_name_valid(name)
406
+
407
+ if callback is not None and check_callback_type:
408
+ BaseMessageBus._check_callback_type(callback)
409
+
410
+ if type(flags) is not NameFlag:
411
+ flags = NameFlag(flags)
412
+
413
+ message = Message(
414
+ destination="org.freedesktop.DBus",
415
+ path="/org/freedesktop/DBus",
416
+ interface="org.freedesktop.DBus",
417
+ member="RequestName",
418
+ signature="su",
419
+ body=[name, flags],
420
+ )
421
+
422
+ if callback is None:
423
+ self._call(message, None)
424
+ return
425
+
426
+ def reply_notify(reply: Message | None, err: Exception | None) -> None:
427
+ try:
428
+ BaseMessageBus._check_method_return(reply, err, "u")
429
+ result = RequestNameReply(reply.body[0]) # type: ignore[union-attr]
430
+ except Exception as e:
431
+ callback(None, e)
432
+ return
433
+
434
+ callback(result, None)
435
+
436
+ self._call(message, reply_notify)
437
+
438
+ def release_name(
439
+ self,
440
+ name: str,
441
+ callback: None
442
+ | (Callable[[ReleaseNameReply | None, Exception | None], None]) = None,
443
+ check_callback_type: bool = True,
444
+ ) -> None:
445
+ """Request that this message bus release the given name.
446
+
447
+ :param name: The name to release.
448
+ :type name: str
449
+ :param callback: A callback that will be called with the reply of the
450
+ release request as a :class:`ReleaseNameReply
451
+ <dbus_fast.ReleaseNameReply>`.
452
+ :type callback: :class:`Callable`
453
+
454
+ :raises:
455
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
456
+ """
457
+ assert_bus_name_valid(name)
458
+
459
+ if callback is not None and check_callback_type:
460
+ BaseMessageBus._check_callback_type(callback)
461
+
462
+ message = Message(
463
+ destination="org.freedesktop.DBus",
464
+ path="/org/freedesktop/DBus",
465
+ interface="org.freedesktop.DBus",
466
+ member="ReleaseName",
467
+ signature="s",
468
+ body=[name],
469
+ )
470
+
471
+ if callback is None:
472
+ self._call(message, None)
473
+ return
474
+
475
+ def reply_notify(reply: Message | None, err: Exception | None) -> None:
476
+ try:
477
+ BaseMessageBus._check_method_return(reply, err, "u")
478
+ result = ReleaseNameReply(reply.body[0]) # type: ignore[union-attr]
479
+ except Exception as e:
480
+ callback(None, e)
481
+ return
482
+
483
+ callback(result, None)
484
+
485
+ self._call(message, reply_notify)
486
+
487
+ def get_proxy_object(
488
+ self, bus_name: str, path: str, introspection: intr.Node | str | ET.Element
489
+ ) -> BaseProxyObject:
490
+ """Get a proxy object for the path exported on the bus that owns the
491
+ name. The object is expected to export the interfaces and nodes
492
+ specified in the introspection data.
493
+
494
+ This is the entry point into the high-level client.
495
+
496
+ :param bus_name: The name on the bus to get the proxy object for.
497
+ :type bus_name: str
498
+ :param path: The path on the client for the proxy object.
499
+ :type path: str
500
+ :param introspection: XML introspection data used to build the
501
+ interfaces on the proxy object.
502
+ :type introspection: :class:`Node <dbus_fast.introspection.Node>` or str or :class:`ElementTree`
503
+
504
+ :returns: A proxy object for the given path on the given name.
505
+ :rtype: :class:`BaseProxyObject <dbus_fast.proxy_object.BaseProxyObject>`
506
+
507
+ :raises:
508
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
509
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
510
+ - :class:`InvalidIntrospectionError <dbus_fast.InvalidIntrospectionError>` - If the introspection data for the node is not valid.
511
+ """
512
+ if self._ProxyObject is None:
513
+ raise Exception(
514
+ "the message bus implementation did not provide a proxy object class"
515
+ )
516
+
517
+ self._init_high_level_client()
518
+
519
+ return self._ProxyObject(bus_name, path, introspection, self)
520
+
521
+ def disconnect(self) -> None:
522
+ """Disconnect the message bus by closing the underlying connection asynchronously.
523
+
524
+ All pending and future calls will error with a connection error.
525
+ """
526
+ self._user_disconnect = True
527
+ if self._sock:
528
+ try:
529
+ self._sock.shutdown(socket.SHUT_RDWR)
530
+ except Exception:
531
+ _LOGGER.warning("could not shut down socket", exc_info=True)
532
+
533
+ def next_serial(self) -> int:
534
+ """Get the next serial for this bus. This can be used as the ``serial``
535
+ attribute of a :class:`Message <dbus_fast.Message>` to manually handle
536
+ the serial of messages.
537
+
538
+ :returns: The next serial for the bus.
539
+ :rtype: int
540
+ """
541
+ self._serial += 1
542
+ return self._serial
543
+
544
+ def add_message_handler(
545
+ self, handler: Callable[[Message], Message | bool | None]
546
+ ) -> None:
547
+ """Add a custom message handler for incoming messages.
548
+
549
+ The handler should be a callable that takes a :class:`Message
550
+ <dbus_fast.Message>`. If the message is a method call, you may return
551
+ another Message as a reply and it will be marked as handled. You may
552
+ also return ``True`` to mark the message as handled without sending a
553
+ reply.
554
+
555
+ :param handler: A handler that will be run for every message the bus
556
+ connection received.
557
+ :type handler: :class:`Callable` or None
558
+ """
559
+ error_text = "a message handler must be callable with a single parameter"
560
+ if not callable(handler):
561
+ raise TypeError(error_text)
562
+
563
+ handler_signature = inspect.signature(handler)
564
+ if len(handler_signature.parameters) != 1:
565
+ raise TypeError(error_text)
566
+
567
+ self._user_message_handlers.append(handler)
568
+
569
+ def remove_message_handler(
570
+ self, handler: Callable[[Message], Message | bool | None]
571
+ ) -> None:
572
+ """Remove a message handler that was previously added by
573
+ :func:`add_message_handler()
574
+ <dbus_fast.message_bus.BaseMessageBus.add_message_handler>`.
575
+
576
+ :param handler: A message handler.
577
+ :type handler: :class:`Callable`
578
+ """
579
+ for i, h in enumerate(self._user_message_handlers):
580
+ if h == handler:
581
+ del self._user_message_handlers[i]
582
+ return
583
+
584
+ def send(self, msg: Message) -> None:
585
+ """Asynchronously send a message on the message bus.
586
+
587
+ :param msg: The message to send.
588
+ :type msg: :class:`Message <dbus_fast.Message>`
589
+ """
590
+ raise NotImplementedError(
591
+ 'the "send" method must be implemented in the inheriting class'
592
+ )
593
+
594
+ def _finalize(self, err: Exception | None) -> None:
595
+ """should be called after the socket disconnects with the disconnection
596
+ error to clean up resources and put the bus in a disconnected state"""
597
+ if self._disconnected:
598
+ return
599
+
600
+ self._disconnected = True
601
+
602
+ for handler in self._method_return_handlers.values():
603
+ try:
604
+ handler(None, err)
605
+ except Exception:
606
+ _LOGGER.warning(
607
+ "a message handler threw an exception on shutdown", exc_info=True
608
+ )
609
+
610
+ self._method_return_handlers.clear()
611
+
612
+ for path in list(self._path_exports):
613
+ self.unexport(path)
614
+
615
+ self._user_message_handlers.clear()
616
+
617
+ def _interface_signal_notify(
618
+ self,
619
+ interface: ServiceInterface,
620
+ interface_name: str,
621
+ member: str,
622
+ signature: str,
623
+ body: list[Any],
624
+ unix_fds: list[int] = [],
625
+ ) -> None:
626
+ path: str | None = None
627
+ for p, ifaces in self._path_exports.items():
628
+ for i in ifaces.values():
629
+ if i is interface:
630
+ path = p
631
+
632
+ if path is None:
633
+ raise Exception(
634
+ "Could not find interface on bus (this is a bug in dbus-fast)"
635
+ )
636
+
637
+ self.send(
638
+ Message.new_signal(
639
+ path=path,
640
+ interface=interface_name,
641
+ member=member,
642
+ signature=signature,
643
+ body=body,
644
+ unix_fds=unix_fds,
645
+ )
646
+ )
647
+
648
+ def _introspect_export_path(self, path: str) -> intr.Node:
649
+ assert_object_path_valid(path)
650
+
651
+ if (interfaces := self._path_exports.get(path)) is not None:
652
+ node = intr.Node.default(path)
653
+ for interface in interfaces.values():
654
+ node.interfaces.append(interface.introspect())
655
+ else:
656
+ node = intr.Node(path)
657
+
658
+ children = set()
659
+
660
+ for export_path in self._path_exports:
661
+ if not export_path.startswith(path):
662
+ continue
663
+
664
+ child_path = export_path.split(path, maxsplit=1)[1]
665
+ if path != "/" and child_path and child_path[0] != "/":
666
+ continue
667
+
668
+ child_path = child_path.lstrip("/")
669
+ child_name = child_path.split("/", maxsplit=1)[0]
670
+
671
+ children.add(child_name)
672
+
673
+ node.nodes = [intr.Node(name) for name in children if name]
674
+
675
+ return node
676
+
677
+ def _setup_socket(self) -> None:
678
+ last_err: Exception | None = None
679
+
680
+ for transport, options in self._bus_address:
681
+ filename: bytes | str | None = None
682
+ ip_addr = ""
683
+ ip_port = 0
684
+
685
+ with ExitStack() as stack:
686
+ if transport == "unix":
687
+ self._sock = stack.enter_context(
688
+ socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
689
+ )
690
+ self._stream = stack.enter_context(self._sock.makefile("rwb"))
691
+ self._fd = self._sock.fileno()
692
+
693
+ if "path" in options:
694
+ filename = options["path"]
695
+ elif "abstract" in options:
696
+ filename = b"\0" + options["abstract"].encode()
697
+ else:
698
+ raise InvalidAddressError(
699
+ "got unix transport with unknown path specifier"
700
+ )
701
+
702
+ try:
703
+ self._sock.connect(filename)
704
+ self._sock.setblocking(False)
705
+ except Exception as e:
706
+ last_err = e
707
+ else:
708
+ stack.pop_all() # responsibility to close sockets is deferred
709
+ return
710
+
711
+ elif transport == "tcp":
712
+ self._sock = stack.enter_context(
713
+ socket.socket(socket.AF_INET, socket.SOCK_STREAM)
714
+ )
715
+ self._stream = stack.enter_context(self._sock.makefile("rwb"))
716
+ self._fd = self._sock.fileno()
717
+
718
+ if "host" in options:
719
+ ip_addr = options["host"]
720
+ if "port" in options:
721
+ ip_port = int(options["port"])
722
+
723
+ try:
724
+ self._sock.connect((ip_addr, ip_port))
725
+ self._sock.setblocking(False)
726
+ except Exception as e:
727
+ last_err = e
728
+ else:
729
+ stack.pop_all()
730
+ return
731
+
732
+ else:
733
+ raise InvalidAddressError(
734
+ f"got unknown address transport: {transport}"
735
+ )
736
+
737
+ if last_err is None: # pragma: no branch
738
+ # Should not normally happen, but just in case
739
+ raise TypeError("empty list of bus addresses given") # pragma: no cover
740
+
741
+ raise last_err
742
+
743
+ def _reply_notify(
744
+ self,
745
+ msg: Message,
746
+ callback: Callable[[Message | None, Exception | None], None],
747
+ reply: Message | None,
748
+ err: Exception | None,
749
+ ) -> None:
750
+ """Callback on reply."""
751
+ if reply and msg.destination and reply.sender:
752
+ self._name_owners[msg.destination] = reply.sender
753
+ callback(reply, err)
754
+
755
+ def _call(
756
+ self,
757
+ msg: Message,
758
+ callback: Callable[[Message | None, Exception | None], None] | None,
759
+ ) -> None:
760
+ if not msg.serial:
761
+ msg.serial = self.next_serial()
762
+
763
+ # Make sure the return reply handler is installed
764
+ # before sending the message to avoid a race condition
765
+ # where the reply is lost in case the backend can
766
+ # send it right away.
767
+ if (reply_expected := _expects_reply(msg)) and callback is not None:
768
+ self._method_return_handlers[msg.serial] = partial(
769
+ self._reply_notify, msg, callback
770
+ )
771
+
772
+ self.send(msg)
773
+
774
+ if not reply_expected and callback is not None:
775
+ callback(None, None)
776
+
777
+ @staticmethod
778
+ def _check_callback_type(callback: Callable) -> None:
779
+ """Raise a TypeError if the user gives an invalid callback as a parameter"""
780
+
781
+ text = "a callback must be callable with two parameters"
782
+
783
+ if not callable(callback):
784
+ raise TypeError(text)
785
+
786
+ fn_signature = inspect.signature(callback)
787
+ if len(fn_signature.parameters) != 2:
788
+ raise TypeError(text)
789
+
790
+ @staticmethod
791
+ def _check_method_return(
792
+ msg: Message | None, err: Exception | None, signature: str
793
+ ) -> None:
794
+ if err:
795
+ raise err
796
+ if msg is None:
797
+ raise DBusError(
798
+ ErrorType.INTERNAL_ERROR, "invalid message type for method call", msg
799
+ )
800
+ if msg.message_type == MessageType.METHOD_RETURN and msg.signature == signature:
801
+ return
802
+ if msg.message_type == MessageType.ERROR:
803
+ raise DBusError._from_message(msg)
804
+ raise DBusError(
805
+ ErrorType.INTERNAL_ERROR, "invalid message type for method call", msg
806
+ )
807
+
808
+ def _process_message(self, msg: _Message) -> None:
809
+ """Process a message received from the message bus."""
810
+ handled = False
811
+ for user_handler in self._user_message_handlers:
812
+ try:
813
+ if result := user_handler(msg):
814
+ if type(result) is Message:
815
+ self.send(result)
816
+ handled = True
817
+ break
818
+ except DBusError as e:
819
+ if msg.message_type is MESSAGE_TYPE_CALL:
820
+ self.send(e._as_message(msg))
821
+ handled = True
822
+ break
823
+ _LOGGER.exception("A message handler raised an exception: %s", e)
824
+ except Exception as e:
825
+ _LOGGER.exception("A message handler raised an exception: %s", e)
826
+ if msg.message_type is MESSAGE_TYPE_CALL:
827
+ self.send(
828
+ Message.new_error(
829
+ msg,
830
+ ErrorType.INTERNAL_ERROR,
831
+ f"An internal error occurred: {e}.\n{traceback.format_exc()}",
832
+ )
833
+ )
834
+ handled = True
835
+ break
836
+
837
+ if msg.message_type is MESSAGE_TYPE_SIGNAL:
838
+ if (
839
+ msg.member == "NameOwnerChanged"
840
+ and msg.sender == "org.freedesktop.DBus"
841
+ and msg.path == "/org/freedesktop/DBus"
842
+ and msg.interface == "org.freedesktop.DBus"
843
+ ):
844
+ name = msg.body[0]
845
+ if new_owner := msg.body[2]:
846
+ self._name_owners[name] = new_owner
847
+ elif name in self._name_owners:
848
+ del self._name_owners[name]
849
+ return
850
+
851
+ if msg.message_type is MESSAGE_TYPE_CALL:
852
+ if not handled:
853
+ handler = self._find_message_handler(msg)
854
+ if not _expects_reply(msg):
855
+ if handler:
856
+ handler(msg, BLOCK_UNEXPECTED_REPLY) # type: ignore[arg-type]
857
+ else:
858
+ _LOGGER.error(
859
+ '"%s.%s" with signature "%s" could not be found',
860
+ msg.interface,
861
+ msg.member,
862
+ msg.signature,
863
+ )
864
+ return
865
+
866
+ send_reply = SendReply(self, msg)
867
+ with send_reply:
868
+ if handler:
869
+ handler(msg, send_reply)
870
+ else:
871
+ send_reply(
872
+ Message.new_error(
873
+ msg,
874
+ ErrorType.UNKNOWN_METHOD,
875
+ f"{msg.interface}.{msg.member} with signature "
876
+ f'"{msg.signature}" could not be found',
877
+ )
878
+ )
879
+ return
880
+
881
+ # An ERROR or a METHOD_RETURN
882
+ return_handler = self._method_return_handlers.get(msg.reply_serial)
883
+ if return_handler is not None:
884
+ if not handled:
885
+ return_handler(msg, None)
886
+ del self._method_return_handlers[msg.reply_serial]
887
+
888
+ def _callback_method_handler(
889
+ self,
890
+ interface: ServiceInterface,
891
+ method: _Method,
892
+ msg: Message,
893
+ send_reply: SendReply,
894
+ ) -> None:
895
+ """This is the callback that will be called when a method call is."""
896
+ args = ServiceInterface._c_msg_body_to_args(msg) if msg.unix_fds else msg.body
897
+ result = method.fn(interface, *args)
898
+ if send_reply is BLOCK_UNEXPECTED_REPLY or _expects_reply(msg) is False:
899
+ return
900
+ body_fds = ServiceInterface._c_fn_result_to_body(
901
+ result,
902
+ method.out_signature_tree,
903
+ self._negotiate_unix_fd,
904
+ )
905
+ send_reply(
906
+ Message(
907
+ message_type=MessageType.METHOD_RETURN,
908
+ reply_serial=msg.serial,
909
+ destination=msg.sender,
910
+ signature=method.out_signature,
911
+ body=body_fds[0],
912
+ unix_fds=body_fds[1],
913
+ )
914
+ )
915
+
916
+ def _make_method_handler(
917
+ self, interface: ServiceInterface, method: _Method
918
+ ) -> HandlerType:
919
+ return partial(self._callback_method_handler, interface, method)
920
+
921
+ def _find_message_handler(self, msg: _Message) -> HandlerType | None:
922
+ """Find the message handler for for METHOD_CALL messages."""
923
+ if TYPE_CHECKING:
924
+ assert msg.member is not None
925
+ assert msg.path is not None
926
+
927
+ if msg.interface is not None and "org.freedesktop.DBus." in msg.interface:
928
+ if (
929
+ msg.interface == "org.freedesktop.DBus.Introspectable"
930
+ and msg.member == "Introspect"
931
+ and msg.signature == ""
932
+ ):
933
+ return self._default_introspect_handler
934
+
935
+ if msg.interface == "org.freedesktop.DBus.Properties":
936
+ return self._default_properties_handler
937
+
938
+ if msg.interface == "org.freedesktop.DBus.Peer":
939
+ if msg.member == "Ping" and msg.signature == "":
940
+ return self._default_ping_handler
941
+ if msg.member == "GetMachineId" and msg.signature == "":
942
+ return self._default_get_machine_id_handler
943
+
944
+ if (
945
+ msg.interface == "org.freedesktop.DBus.ObjectManager"
946
+ and msg.member == "GetManagedObjects"
947
+ ):
948
+ return self._default_get_managed_objects_handler
949
+
950
+ if (interfaces := self._path_exports.get(msg.path)) is None:
951
+ return None
952
+
953
+ if msg.interface is None:
954
+ return self._find_any_message_handler_matching_signature(interfaces, msg)
955
+
956
+ if (interface := interfaces.get(msg.interface)) is not None and (
957
+ handler := ServiceInterface._get_enabled_handler_by_name_signature(
958
+ interface, self, msg.member, msg.signature
959
+ )
960
+ ) is not None:
961
+ return handler
962
+
963
+ return None
964
+
965
+ def _find_any_message_handler_matching_signature(
966
+ self, interfaces: dict[str, ServiceInterface], msg: _Message
967
+ ) -> HandlerType | None:
968
+ # No interface, so we need to search all interfaces for the method
969
+ # with a matching signature
970
+ for interface in interfaces.values():
971
+ if (
972
+ handler := ServiceInterface._get_enabled_handler_by_name_signature(
973
+ interface, self, msg.member, msg.signature
974
+ )
975
+ ) is not None:
976
+ return handler
977
+ return None
978
+
979
+ def _default_introspect_handler(self, msg: Message, send_reply: SendReply) -> None:
980
+ if TYPE_CHECKING:
981
+ assert msg.path is not None
982
+ introspection = self._introspect_export_path(msg.path).tostring()
983
+ send_reply(Message.new_method_return(msg, "s", [introspection]))
984
+
985
+ def _default_ping_handler(self, msg: Message, send_reply: SendReply) -> None:
986
+ send_reply(Message.new_method_return(msg))
987
+
988
+ def _send_machine_id_reply(self, msg: Message, send_reply: SendReply) -> None:
989
+ send_reply(Message.new_method_return(msg, "s", [self._machine_id]))
990
+
991
+ def _default_get_machine_id_handler(
992
+ self, msg: Message, send_reply: SendReply
993
+ ) -> None:
994
+ if self._machine_id:
995
+ self._send_machine_id_reply(msg, send_reply)
996
+ return
997
+
998
+ def reply_handler(reply: Message | None, err: Exception | None) -> None:
999
+ if err or reply is None:
1000
+ # the bus has been disconnected, cannot send a reply
1001
+ return
1002
+
1003
+ if reply.message_type == MessageType.METHOD_RETURN:
1004
+ self._machine_id = reply.body[0]
1005
+ self._send_machine_id_reply(msg, send_reply)
1006
+ elif (
1007
+ reply.message_type == MessageType.ERROR and reply.error_name is not None
1008
+ ):
1009
+ send_reply(Message.new_error(msg, reply.error_name, str(reply.body)))
1010
+ else:
1011
+ send_reply(
1012
+ Message.new_error(msg, ErrorType.FAILED, "could not get machine_id")
1013
+ )
1014
+
1015
+ self._call(
1016
+ Message(
1017
+ destination="org.freedesktop.DBus",
1018
+ path="/org/freedesktop/DBus",
1019
+ interface="org.freedesktop.DBus.Peer",
1020
+ member="GetMachineId",
1021
+ ),
1022
+ reply_handler,
1023
+ )
1024
+
1025
+ def _default_get_managed_objects_handler(
1026
+ self, msg: Message, send_reply: SendReply
1027
+ ) -> None:
1028
+ result_signature = "a{oa{sa{sv}}}"
1029
+ error_handled = False
1030
+
1031
+ def is_result_complete() -> bool:
1032
+ if not result:
1033
+ return True
1034
+ for n, interfaces in result.items():
1035
+ for value in interfaces.values():
1036
+ if value is None:
1037
+ return False
1038
+
1039
+ return True
1040
+
1041
+ if TYPE_CHECKING:
1042
+ assert msg.path is not None
1043
+
1044
+ nodes = [
1045
+ node
1046
+ for node in self._path_exports
1047
+ if msg.path == "/" or node.startswith(msg.path + "/")
1048
+ ]
1049
+
1050
+ # first build up the result object to know when it's complete
1051
+ result: dict[str, dict[str, Any]] = {
1052
+ node: dict.fromkeys(self._path_exports[node]) for node in nodes
1053
+ }
1054
+
1055
+ if is_result_complete():
1056
+ send_reply(Message.new_method_return(msg, result_signature, [result]))
1057
+ return
1058
+
1059
+ def get_all_properties_callback(
1060
+ interface: ServiceInterface, values: Any, node: str, err: Exception | None
1061
+ ) -> None:
1062
+ nonlocal error_handled
1063
+ if err is not None:
1064
+ if not error_handled:
1065
+ error_handled = True
1066
+ send_reply.send_error(err)
1067
+ return
1068
+
1069
+ result[node][interface.name] = values
1070
+
1071
+ if is_result_complete():
1072
+ send_reply(Message.new_method_return(msg, result_signature, [result]))
1073
+
1074
+ for node in nodes:
1075
+ for interface in self._path_exports[node].values():
1076
+ ServiceInterface._get_all_property_values(
1077
+ interface, get_all_properties_callback, node
1078
+ )
1079
+
1080
+ def _default_properties_handler(self, msg: Message, send_reply: SendReply) -> None:
1081
+ methods = {"Get": "ss", "Set": "ssv", "GetAll": "s"}
1082
+ if msg.member not in methods or methods[msg.member] != msg.signature:
1083
+ raise DBusError(
1084
+ ErrorType.UNKNOWN_METHOD,
1085
+ f'properties interface doesn\'t have method "{msg.member}" with signature "{msg.signature}"',
1086
+ )
1087
+
1088
+ interface_name = msg.body[0]
1089
+ if interface_name == "":
1090
+ raise DBusError(
1091
+ ErrorType.NOT_SUPPORTED,
1092
+ "getting and setting properties with an empty interface string is not supported yet",
1093
+ )
1094
+
1095
+ if msg.path not in self._path_exports:
1096
+ raise DBusError(
1097
+ ErrorType.UNKNOWN_OBJECT, f'no interfaces at path: "{msg.path}"'
1098
+ )
1099
+
1100
+ if (interface := self._path_exports[msg.path].get(interface_name)) is None:
1101
+ if interface_name in [
1102
+ "org.freedesktop.DBus.Properties",
1103
+ "org.freedesktop.DBus.Introspectable",
1104
+ "org.freedesktop.DBus.Peer",
1105
+ "org.freedesktop.DBus.ObjectManager",
1106
+ ]:
1107
+ # the standard interfaces do not have properties
1108
+ if msg.member == "Get" or msg.member == "Set":
1109
+ prop_name = msg.body[1]
1110
+ raise DBusError(
1111
+ ErrorType.UNKNOWN_PROPERTY,
1112
+ f'interface "{interface_name}" does not have property "{prop_name}"',
1113
+ )
1114
+ if msg.member == "GetAll":
1115
+ send_reply(Message.new_method_return(msg, "a{sv}", [{}]))
1116
+ return
1117
+ assert False
1118
+ raise DBusError(
1119
+ ErrorType.UNKNOWN_INTERFACE,
1120
+ f'could not find an interface "{interface_name}" at path: "{msg.path}"',
1121
+ )
1122
+
1123
+ properties = ServiceInterface._get_properties(interface)
1124
+
1125
+ if msg.member == "Get" or msg.member == "Set":
1126
+ prop_name = msg.body[1]
1127
+ match = [
1128
+ prop
1129
+ for prop in properties
1130
+ if prop.name == prop_name and not prop.disabled
1131
+ ]
1132
+ if not match:
1133
+ raise DBusError(
1134
+ ErrorType.UNKNOWN_PROPERTY,
1135
+ f'interface "{interface_name}" does not have property "{prop_name}"',
1136
+ )
1137
+
1138
+ prop = match[0]
1139
+ if msg.member == "Get":
1140
+ if not prop.access.readable():
1141
+ raise DBusError(
1142
+ ErrorType.UNKNOWN_PROPERTY,
1143
+ "the property does not have read access",
1144
+ )
1145
+
1146
+ def get_property_callback(
1147
+ interface: ServiceInterface,
1148
+ prop: _Property,
1149
+ prop_value: Any,
1150
+ err: Exception | None,
1151
+ ) -> None:
1152
+ try:
1153
+ if err is not None:
1154
+ send_reply.send_error(err)
1155
+ return
1156
+
1157
+ body, unix_fds = replace_fds_with_idx(
1158
+ prop.signature, [prop_value]
1159
+ )
1160
+
1161
+ send_reply(
1162
+ Message.new_method_return(
1163
+ msg,
1164
+ "v",
1165
+ [Variant(prop.signature, body[0])],
1166
+ unix_fds=unix_fds,
1167
+ )
1168
+ )
1169
+ except Exception as e:
1170
+ send_reply.send_error(e)
1171
+
1172
+ ServiceInterface._get_property_value(
1173
+ interface, prop, get_property_callback
1174
+ )
1175
+
1176
+ elif msg.member == "Set":
1177
+ if not prop.access.writable():
1178
+ raise DBusError(
1179
+ ErrorType.PROPERTY_READ_ONLY, "the property is readonly"
1180
+ )
1181
+ value = msg.body[2]
1182
+ if value.signature != prop.signature:
1183
+ raise DBusError(
1184
+ ErrorType.INVALID_SIGNATURE,
1185
+ f'wrong signature for property. expected "{prop.signature}"',
1186
+ )
1187
+ assert prop.prop_setter
1188
+
1189
+ def set_property_callback(
1190
+ interface: ServiceInterface, prop: _Property, err: Exception | None
1191
+ ) -> None:
1192
+ if err is not None:
1193
+ send_reply.send_error(err)
1194
+ return
1195
+ send_reply(Message.new_method_return(msg))
1196
+
1197
+ body = replace_idx_with_fds(
1198
+ value.signature, [value.value], msg.unix_fds
1199
+ )
1200
+ ServiceInterface._set_property_value(
1201
+ interface, prop, body[0], set_property_callback
1202
+ )
1203
+
1204
+ elif msg.member == "GetAll":
1205
+
1206
+ def get_all_properties_callback(
1207
+ interface: ServiceInterface,
1208
+ values: Any,
1209
+ user_data: Any,
1210
+ err: Exception | None,
1211
+ ) -> None:
1212
+ if err is not None:
1213
+ send_reply.send_error(err)
1214
+ return
1215
+ body, unix_fds = replace_fds_with_idx("a{sv}", [values])
1216
+ send_reply(
1217
+ Message.new_method_return(msg, "a{sv}", body, unix_fds=unix_fds)
1218
+ )
1219
+
1220
+ ServiceInterface._get_all_property_values(
1221
+ interface, get_all_properties_callback
1222
+ )
1223
+
1224
+ else:
1225
+ assert False
1226
+
1227
+ def _init_high_level_client(self) -> None:
1228
+ """The high level client is initialized when the first proxy object is
1229
+ gotten. Currently just sets up the match rules for the name owner cache
1230
+ so signals can be routed to the right objects."""
1231
+ if self._high_level_client_initialized:
1232
+ return
1233
+ self._high_level_client_initialized = True
1234
+
1235
+ def add_match_notify(msg: Message | None, err: Exception | None) -> None:
1236
+ if err:
1237
+ _LOGGER.error(
1238
+ f'add match request failed. match="{self._name_owner_match_rule}", {err}'
1239
+ )
1240
+ elif msg is not None and msg.message_type == MessageType.ERROR:
1241
+ _LOGGER.error(
1242
+ f'add match request failed. match="{self._name_owner_match_rule}", {msg.body[0]}'
1243
+ )
1244
+
1245
+ self._call(
1246
+ Message(
1247
+ destination="org.freedesktop.DBus",
1248
+ interface="org.freedesktop.DBus",
1249
+ path="/org/freedesktop/DBus",
1250
+ member="AddMatch",
1251
+ signature="s",
1252
+ body=[self._name_owner_match_rule],
1253
+ ),
1254
+ add_match_notify,
1255
+ )
1256
+
1257
+ def _add_match_rule(self, match_rule: str) -> None:
1258
+ """Add a match rule. Match rules added by this function are refcounted
1259
+ and must be removed by _remove_match_rule(). This is for use in the
1260
+ high level client only."""
1261
+ if match_rule == self._name_owner_match_rule:
1262
+ return
1263
+
1264
+ if match_rule in self._match_rules:
1265
+ self._match_rules[match_rule] += 1
1266
+ return
1267
+
1268
+ self._match_rules[match_rule] = 1
1269
+
1270
+ def add_match_notify(msg: Message | None, err: Exception | None) -> None:
1271
+ if err:
1272
+ _LOGGER.error(f'add match request failed. match="{match_rule}", {err}')
1273
+ elif msg is not None and msg.message_type == MessageType.ERROR:
1274
+ _LOGGER.error(
1275
+ f'add match request failed. match="{match_rule}", {msg.body[0]}'
1276
+ )
1277
+
1278
+ self._call(
1279
+ Message(
1280
+ destination="org.freedesktop.DBus",
1281
+ interface="org.freedesktop.DBus",
1282
+ path="/org/freedesktop/DBus",
1283
+ member="AddMatch",
1284
+ signature="s",
1285
+ body=[match_rule],
1286
+ ),
1287
+ add_match_notify,
1288
+ )
1289
+
1290
+ def _remove_match_rule(self, match_rule: str) -> None:
1291
+ """Remove a match rule added with _add_match_rule(). This is for use in
1292
+ the high level client only."""
1293
+ if match_rule == self._name_owner_match_rule:
1294
+ return
1295
+
1296
+ if match_rule in self._match_rules:
1297
+ self._match_rules[match_rule] -= 1
1298
+ if self._match_rules[match_rule] > 0:
1299
+ return
1300
+
1301
+ del self._match_rules[match_rule]
1302
+
1303
+ def remove_match_notify(msg: Message | None, err: Exception | None) -> None:
1304
+ if self._disconnected:
1305
+ return
1306
+
1307
+ if err:
1308
+ _LOGGER.error(
1309
+ f'remove match request failed. match="{match_rule}", {err}'
1310
+ )
1311
+ elif msg is not None and msg.message_type == MessageType.ERROR:
1312
+ _LOGGER.error(
1313
+ f'remove match request failed. match="{match_rule}", {msg.body[0]}'
1314
+ )
1315
+
1316
+ self._call(
1317
+ Message(
1318
+ destination="org.freedesktop.DBus",
1319
+ interface="org.freedesktop.DBus",
1320
+ path="/org/freedesktop/DBus",
1321
+ member="RemoveMatch",
1322
+ signature="s",
1323
+ body=[match_rule],
1324
+ ),
1325
+ remove_match_notify,
1326
+ )