asyncdbus 0.6.1__tar.gz → 0.7.1__tar.gz

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.
Files changed (98) hide show
  1. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/Dockerfile +10 -8
  2. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/Makefile +19 -3
  3. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/PKG-INFO +14 -5
  4. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/_private/constants.py +3 -0
  5. asyncdbus-0.7.1/asyncdbus/_private/unmarshaller.py +334 -0
  6. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/constants.py +7 -0
  7. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/message.py +13 -15
  8. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/proxy_object.py +1 -1
  9. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/signature.py +40 -52
  10. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/validators.py +7 -1
  11. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus.egg-info/PKG-INFO +14 -5
  12. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus.egg-info/SOURCES.txt +2 -0
  13. asyncdbus-0.7.1/bench/unmarshall.py +22 -0
  14. asyncdbus-0.7.1/dbus_next/glib/message_bus.py +472 -0
  15. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/high-level-service/index.rst +1 -1
  16. asyncdbus-0.7.1/requirements.txt +51 -0
  17. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_disconnect.py +1 -1
  18. asyncdbus-0.7.1/test/test_marshaller.py +158 -0
  19. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_validators.py +5 -5
  20. asyncdbus-0.6.1/asyncdbus/_private/unmarshaller.py +0 -308
  21. asyncdbus-0.6.1/requirements.txt +0 -5
  22. asyncdbus-0.6.1/test/test_marshaller.py +0 -114
  23. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/.flake8 +0 -0
  24. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/.gitignore +0 -0
  25. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/.style.yapf +0 -0
  26. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/.travis.yml +0 -0
  27. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/CHANGELOG.md +0 -0
  28. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/LICENSE +0 -0
  29. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/MANIFEST.in +0 -0
  30. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/README.md +0 -0
  31. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/__init__.py +0 -0
  32. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/_private/__init__.py +0 -0
  33. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/_private/address.py +0 -0
  34. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/_private/marshaller.py +0 -0
  35. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/_private/util.py +0 -0
  36. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/auth.py +0 -0
  37. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/errors.py +0 -0
  38. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/introspection.py +0 -0
  39. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/message_bus.py +0 -0
  40. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/py.typed +0 -0
  41. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus/service.py +0 -0
  42. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus.egg-info/dependency_links.txt +0 -0
  43. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus.egg-info/requires.txt +0 -0
  44. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/asyncdbus.egg-info/top_level.txt +0 -0
  45. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/Makefile +0 -0
  46. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/_static/.gitignore +0 -0
  47. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/_templates/.gitignore +0 -0
  48. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/authentication.rst +0 -0
  49. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/conf.py +0 -0
  50. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/constants.rst +0 -0
  51. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/errors.rst +0 -0
  52. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/high-level-client/index.rst +0 -0
  53. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/high-level-client/proxy-interface.rst +0 -0
  54. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/high-level-client/proxy-object.rst +0 -0
  55. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/high-level-service/service-interface.rst +0 -0
  56. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/index.rst +0 -0
  57. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/introspection.rst +0 -0
  58. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/low-level-interface/index.rst +0 -0
  59. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/low-level-interface/message.rst +0 -0
  60. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/message-bus/index.rst +0 -0
  61. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/message-bus/message-bus.rst +0 -0
  62. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/type-system/index.rst +0 -0
  63. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/type-system/signature-tree.rst +0 -0
  64. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/type-system/signature-type.rst +0 -0
  65. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/type-system/variant.rst +0 -0
  66. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/docs/validators.rst +0 -0
  67. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/examples/aio-list-names.py +0 -0
  68. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/examples/aio-tcp-notification.py +0 -0
  69. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/examples/dbus-name.py +0 -0
  70. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/examples/dbus-next-send.py +0 -0
  71. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/examples/example-service.py +0 -0
  72. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/examples/mpris.py +0 -0
  73. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/pytest.ini +0 -0
  74. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/requirements-dev.txt +0 -0
  75. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/setup.cfg +0 -0
  76. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/setup.py +0 -0
  77. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/__init__.py +0 -0
  78. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/client/test_methods.py +0 -0
  79. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/client/test_properties.py +0 -0
  80. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/client/test_signals.py +0 -0
  81. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/conftest.py +0 -0
  82. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/data/introspection.xml +0 -0
  83. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/data/messages.json +0 -0
  84. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/service/__init__.py +0 -0
  85. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/service/test_decorators.py +0 -0
  86. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/service/test_export.py +0 -0
  87. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/service/test_methods.py +0 -0
  88. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/service/test_properties.py +0 -0
  89. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/service/test_signals.py +0 -0
  90. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/service/test_standard_interfaces.py +0 -0
  91. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_address_parser.py +0 -0
  92. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_aio_low_level.py +0 -0
  93. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_big_message.py +0 -0
  94. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_fd_passing.py +0 -0
  95. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_introspection.py +0 -0
  96. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_request_name.py +0 -0
  97. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_signature.py +0 -0
  98. {asyncdbus-0.6.1 → asyncdbus-0.7.1}/test/test_tcp_address.py +0 -0
@@ -16,8 +16,8 @@ RUN export DEBIAN_FRONTEND=noninteractive; \
16
16
  build-essential \
17
17
  python3-pip \
18
18
  python3 \
19
- python3.6 \
20
19
  python3.7 \
20
+ python3.7-distutils \
21
21
  python3.9 \
22
22
  python3.9-distutils \
23
23
  python3.10 \
@@ -26,13 +26,15 @@ RUN export DEBIAN_FRONTEND=noninteractive; \
26
26
  dbus \
27
27
  python3-gi
28
28
 
29
- RUN pip3 install yapf flake8 && \
30
- for py in python3 python3.6 python3.7 python3.9 python3.10; do \
31
- curl https://bootstrap.pypa.io/get-pip.py | $py; \
32
- $py -m pip install \
33
- pytest \
34
- pytest-timeout \
35
- pytest-cov; \
29
+ RUN set -e -x; \
30
+ pip3 install 'yapf' 'flake8'; \
31
+ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py; \
32
+ for py in python3.8 python3.9 python3.10 python3.11 ; do \
33
+ ${py} get-pip.py; \
34
+ PYTHONPATH=/usr/lib/${py}/site-packages ${py} -m pip install \
35
+ 'pytest' \
36
+ 'pytest-timeout' \
37
+ 'pytest-cov'; \
36
38
  done
37
39
 
38
40
  ADD . /app
@@ -15,9 +15,9 @@ format:
15
15
  python3 -m yapf -rip $(source_dirs)
16
16
 
17
17
  test:
18
- for py in python3.6 python3.7 python3.9 python3.10 python3.8 ; do \
19
- if hash $$py; then \
20
- dbus-run-session $$py -m pytest -sv --cov=asyncdbus || exit 1 ; \
18
+ for py in python3.9 python3.10 python3.11 python3.8 ; do \
19
+ if hash $${py}; then \
20
+ PYTHONPATH=/usr/lib/$${py}/site-packages dbus-run-session $${py} -m pytest -sv --cov=asyncdbus || exit 1 ; \
21
21
  fi \
22
22
  done \
23
23
 
@@ -41,3 +41,19 @@ livedocs:
41
41
  sphinx-autobuild docs docs/_build/html --watch asyncdbus
42
42
 
43
43
  all: format lint test
44
+
45
+ pypi: tagged
46
+ if test -f dist/${PYPI}-$(shell git describe --tags --exact-match).tar.gz ; then \
47
+ echo "Source package exists."; \
48
+ elif test -f setup.py ; then \
49
+ python3 setup.py sdist bdist_wheel ; \
50
+ else \
51
+ python3 -mbuild -snw ; \
52
+ fi
53
+ twine upload \
54
+ dist/${PYPI}-$(shell git describe --tags --exact-match).tar.gz \
55
+ dist/$(subst -,_,${PYPI})-$(shell git describe --tags --exact-match)-py3-none-any.whl
56
+
57
+ tagged:
58
+ git describe --tags --exact-match
59
+ test $$(git ls-files -m | wc -l) = 0
@@ -1,12 +1,11 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: asyncdbus
3
- Version: 0.6.1
3
+ Version: 0.7.1
4
4
  Summary: A zero-dependency async DBus library
5
5
  Home-page: https://github.com/M-o-a-T/asyncdbus
6
6
  Author: Matthias Urlichs
7
7
  Author-email: matthias@urlichs.de
8
8
  License: MIT
9
- Platform: UNKNOWN
10
9
  Classifier: Development Status :: 3 - Alpha
11
10
  Classifier: Environment :: X11 Applications
12
11
  Classifier: Environment :: X11 Applications :: Gnome
@@ -26,6 +25,18 @@ Classifier: Typing :: Typed
26
25
  Requires-Python: >=3.7.0
27
26
  Description-Content-Type: text/markdown
28
27
  License-File: LICENSE
28
+ Requires-Dist: anyio>=3
29
+ Dynamic: author
30
+ Dynamic: author-email
31
+ Dynamic: classifier
32
+ Dynamic: description
33
+ Dynamic: description-content-type
34
+ Dynamic: home-page
35
+ Dynamic: license
36
+ Dynamic: license-file
37
+ Dynamic: requires-dist
38
+ Dynamic: requires-python
39
+ Dynamic: summary
29
40
 
30
41
 
31
42
  # asyncdbus
@@ -217,5 +228,3 @@ Before you commit, run `make` to run the linter, code formatter, and the test su
217
228
  You can use this code under an MIT license (see LICENSE).
218
229
 
219
230
  © 2019, Tony Crisci
220
-
221
-
@@ -16,3 +16,6 @@ class HeaderField(Enum):
16
16
  SENDER = 7
17
17
  SIGNATURE = 8
18
18
  UNIX_FDS = 9
19
+
20
+
21
+ HEADER_NAME_MAP = {field.value: field.name for field in HeaderField}
@@ -0,0 +1,334 @@
1
+ from typing import Any, Callable, Dict, List, Optional, Tuple
2
+ from ..message import Message
3
+ from .constants import (
4
+ HeaderField,
5
+ LITTLE_ENDIAN,
6
+ BIG_ENDIAN,
7
+ PROTOCOL_VERSION,
8
+ HEADER_NAME_MAP,
9
+ )
10
+ from ..constants import MessageType, MessageFlag, MESSAGE_FLAG_MAP, MESSAGE_TYPE_MAP
11
+ from ..signature import SignatureTree, SignatureType, Variant
12
+ from ..errors import InvalidMessageError
13
+
14
+ import array
15
+ import io
16
+ import socket
17
+ import sys
18
+ from struct import Struct
19
+
20
+ MAX_UNIX_FDS = 16
21
+
22
+ UNPACK_SYMBOL = {LITTLE_ENDIAN: "<", BIG_ENDIAN: ">"}
23
+ UNPACK_LENGTHS = {BIG_ENDIAN: Struct(">III"), LITTLE_ENDIAN: Struct("<III")}
24
+ IS_BIG_ENDIAN = sys.byteorder == "big"
25
+ IS_LITTLE_ENDIAN = sys.byteorder == "little"
26
+
27
+ DBUS_TO_CTYPE = {
28
+ "y": ("B", 1), # byte
29
+ "n": ("h", 2), # int16
30
+ "q": ("H", 2), # uint16
31
+ "i": ("i", 4), # int32
32
+ "u": ("I", 4), # uint32
33
+ "x": ("q", 8), # int64
34
+ "t": ("Q", 8), # uint64
35
+ "d": ("d", 8), # double
36
+ "h": ("I", 4), # uint32
37
+ }
38
+
39
+ HEADER_SIGNATURE_SIZE = 16
40
+ HEADER_ARRAY_OF_STRUCT_SIGNATURE_POSITION = 12
41
+
42
+ UINT32_SIGNATURE = SignatureTree._get("u").types[0]
43
+
44
+ HEADER_DESTINATION = HeaderField.DESTINATION.name
45
+ HEADER_PATH = HeaderField.PATH.name
46
+ HEADER_INTERFACE = HeaderField.INTERFACE.name
47
+ HEADER_MEMBER = HeaderField.MEMBER.name
48
+ HEADER_ERROR_NAME = HeaderField.ERROR_NAME.name
49
+ HEADER_REPLY_SERIAL = HeaderField.REPLY_SERIAL.name
50
+ HEADER_SENDER = HeaderField.SENDER.name
51
+
52
+ READER_TYPE = Dict[str, Tuple[Optional[Callable[["Unmarshaller", SignatureType], Any]],
53
+ Optional[str], Optional[int], Optional[Struct], ], ]
54
+
55
+
56
+ class MarshallerStreamEndError(Exception):
57
+ """This exception is raised when the end of the stream is reached.
58
+
59
+ This means more data is expected on the wire that has not yet been
60
+ received. The caller should call unmarshall later when more data is
61
+ available.
62
+ """
63
+
64
+ pass
65
+
66
+
67
+ #
68
+ # Alignment padding is handled with the following formula below
69
+ #
70
+ # For any align value, the correct padding formula is:
71
+ #
72
+ # (align - (offset % align)) % align
73
+ #
74
+ # However, if align is a power of 2 (always the case here), the slow MOD
75
+ # operator can be replaced by a bitwise AND:
76
+ #
77
+ # (align - (offset & (align - 1))) & (align - 1)
78
+ #
79
+ # Which can be simplified to:
80
+ #
81
+ # (-offset) & (align - 1)
82
+ #
83
+ #
84
+ class Unmarshaller:
85
+ buf: bytearray
86
+ view: memoryview
87
+ message: Message
88
+ unpack: Dict[str, Struct]
89
+ readers: READER_TYPE
90
+
91
+ def __init__(self):
92
+ self.unix_fds = []
93
+ self.buf = bytearray()
94
+ self.view = None # Memory view of the buffer
95
+ self.offset = 0
96
+ self.message = None
97
+ self.readers = None
98
+ self.body_len: int | None = None
99
+ self.serial: int | None = None
100
+ self.header_len: int | None = None
101
+ self.message_type: MessageType | None = None
102
+ self.flag: MessageFlag | None = None
103
+
104
+ def read_to_offset(self, offset: int) -> None:
105
+ """
106
+ Read from underlying socket into buffer.
107
+
108
+ Raises MarshallerStreamEndError if there is not enough data to be read.
109
+
110
+ :arg offset:
111
+ The offset to read to. If not enough bytes are available in the
112
+ buffer, read more from it.
113
+
114
+ :returns:
115
+ None
116
+ """
117
+ if len(self.buf) < offset:
118
+ raise MarshallerStreamEndError()
119
+
120
+ def read_boolean(self, _=None):
121
+ return bool(self.read_argument(UINT32_SIGNATURE))
122
+
123
+ def read_string(self, _=None):
124
+ str_length = self.read_argument(UINT32_SIGNATURE)
125
+ str_start = self.offset
126
+ # read terminating '\0' byte as well (str_length + 1)
127
+ self.offset += str_length + 1
128
+ return self.buf[str_start:str_start + str_length].decode()
129
+
130
+ def read_signature(self, _=None):
131
+ signature_len = self.view[self.offset] # byte
132
+ o = self.offset + 1
133
+ # read terminating '\0' byte as well (str_length + 1)
134
+ self.offset = o + signature_len + 1
135
+ return self.buf[o:o + signature_len].decode()
136
+
137
+ def read_variant(self, _=None):
138
+ tree = SignatureTree._get(self.read_signature())
139
+ # verify in Variant is only useful on construction not unmarshalling
140
+ return Variant(tree, self.read_argument(tree.types[0]), verify=False)
141
+
142
+ def read_struct(self, type_: SignatureType):
143
+ self.offset += -self.offset & 7 # align 8
144
+ return [self.read_argument(child_type) for child_type in type_.children]
145
+
146
+ def read_dict_entry(self, type_: SignatureType):
147
+ self.offset += -self.offset & 7 # align 8
148
+ return self.read_argument(type_.children[0]), self.read_argument(type_.children[1])
149
+
150
+ def read_array(self, type_: SignatureType):
151
+ self.offset += -self.offset & 3 # align 4 for the array
152
+ array_length = self.read_argument(UINT32_SIGNATURE)
153
+
154
+ child_type = type_.children[0]
155
+ if child_type.token in "xtd{(":
156
+ # the first alignment is not included in the array size
157
+ self.offset += -self.offset & 7 # align 8
158
+
159
+ if child_type.token == "y":
160
+ self.offset += array_length
161
+ return self.buf[self.offset - array_length:self.offset]
162
+
163
+ beginning_offset = self.offset
164
+
165
+ if child_type.token == "{":
166
+ result_dict = {}
167
+ while self.offset - beginning_offset < array_length:
168
+ key, value = self.read_dict_entry(child_type)
169
+ result_dict[key] = value
170
+ return result_dict
171
+
172
+ result_list = []
173
+ while self.offset - beginning_offset < array_length:
174
+ result_list.append(self.read_argument(child_type))
175
+ return result_list
176
+
177
+ def read_argument(self, type_: SignatureType) -> Any:
178
+ """Dispatch to an argument reader or cast/unpack a C type."""
179
+ token = type_.token
180
+ reader, ctype, size, struct = self.readers[token]
181
+ if reader: # complex type
182
+ return reader(self, type_)
183
+ self.offset += size + (-self.offset & (size - 1)) # align
184
+ if self.can_cast:
185
+ return self.view[self.offset - size:self.offset].cast(ctype)[0]
186
+ return struct.unpack_from(self.view, self.offset - size)[0]
187
+
188
+ def header_fields(self, header_length):
189
+ """Header fields are always a(yv)."""
190
+ beginning_offset = self.offset
191
+ headers = {}
192
+ while self.offset - beginning_offset < header_length:
193
+ # Now read the y (byte) of struct (yv)
194
+ self.offset += (-self.offset & 7) + 1 # align 8 + 1 for 'y' byte
195
+ field_0 = self.view[self.offset - 1]
196
+
197
+ # Now read the v (variant) of struct (yv)
198
+ signature_len = self.view[self.offset] # byte
199
+ o = self.offset + 1
200
+ self.offset += signature_len + 2 # one for the byte, one for the '\0'
201
+ tree = SignatureTree._get(self.buf[o:o + signature_len].decode())
202
+ headers[HEADER_NAME_MAP[field_0]] = self.read_argument(tree.types[0])
203
+ return headers
204
+
205
+ def _read_header(self):
206
+ """Read the header of the message."""
207
+ # Signature is of the header is
208
+ # BYTE, BYTE, BYTE, BYTE, UINT32, UINT32, ARRAY of STRUCT of (BYTE,VARIANT)
209
+ self.read_to_offset(HEADER_SIGNATURE_SIZE)
210
+ buffer = self.buf
211
+ endian = buffer[0]
212
+ self.message_type = MESSAGE_TYPE_MAP[buffer[1]]
213
+ self.flag = buffer[2]
214
+ protocol_version = buffer[3]
215
+
216
+ if endian != LITTLE_ENDIAN and endian != BIG_ENDIAN:
217
+ raise InvalidMessageError(
218
+ f"Expecting endianness as the first byte, got {endian} from {buffer}")
219
+ if protocol_version != PROTOCOL_VERSION:
220
+ raise InvalidMessageError(f"got unknown protocol version: {protocol_version}")
221
+
222
+ self.body_len, self.serial, self.header_len = UNPACK_LENGTHS[endian].unpack_from(buffer, 4)
223
+ self.msg_len = (self.header_len + (-self.header_len & 7) + self.body_len) # align 8
224
+ if IS_BIG_ENDIAN and endian == BIG_ENDIAN:
225
+ self.can_cast = True
226
+ elif IS_LITTLE_ENDIAN and endian == LITTLE_ENDIAN:
227
+ self.can_cast = True
228
+ self.readers = self._readers_by_type[endian]
229
+
230
+ def _read_body(self):
231
+ """Read the body of the message."""
232
+ self.read_to_offset(HEADER_SIGNATURE_SIZE + self.msg_len)
233
+ self.view = memoryview(self.buf)
234
+ self.offset = HEADER_ARRAY_OF_STRUCT_SIGNATURE_POSITION
235
+ header_fields = self.header_fields(self.header_len)
236
+ self.offset += -self.offset & 7 # align 8
237
+ tree = SignatureTree._get(header_fields.get(HeaderField.SIGNATURE.name, ""))
238
+ if self.unix_fds:
239
+ fds = self.unix_fds.pop(0)
240
+ else:
241
+ fds = []
242
+ self.message = Message(
243
+ destination=header_fields.get(HEADER_DESTINATION),
244
+ path=header_fields.get(HEADER_PATH),
245
+ interface=header_fields.get(HEADER_INTERFACE),
246
+ member=header_fields.get(HEADER_MEMBER),
247
+ message_type=self.message_type,
248
+ flags=self.flag,
249
+ error_name=header_fields.get(HEADER_ERROR_NAME),
250
+ reply_serial=header_fields.get(HEADER_REPLY_SERIAL),
251
+ sender=header_fields.get(HEADER_SENDER),
252
+ unix_fds=fds,
253
+ signature=tree.signature,
254
+ body=[self.read_argument(t) for t in tree.types] if self.body_len else [],
255
+ serial=self.serial,
256
+ )
257
+
258
+ def unmarshall(self):
259
+ """Unmarshall the message.
260
+
261
+ The underlying read function will raise MarshallerStreamEndError
262
+ if there are not enough bytes in the buffer. This allows unmarshall
263
+ to be resumed when more data comes in over the wire.
264
+ """
265
+ try:
266
+ if self.message_type is None:
267
+ self._read_header()
268
+ self._read_body()
269
+ except MarshallerStreamEndError:
270
+ return None
271
+ self.buf = self.buf[HEADER_SIGNATURE_SIZE + self.msg_len:]
272
+ self.message_type = None
273
+ return self.message
274
+
275
+ _complex_parsers: Dict[str, Tuple[Callable[["Unmarshaller", SignatureType], Any], None, None,
276
+ None]] = {
277
+ "b": (read_boolean, None, None, None),
278
+ "o": (read_string, None, None, None),
279
+ "s": (read_string, None, None, None),
280
+ "g": (read_signature, None, None, None),
281
+ "a": (read_array, None, None, None),
282
+ "(": (read_struct, None, None, None),
283
+ "{": (read_dict_entry, None, None, None),
284
+ "v": (read_variant, None, None, None),
285
+ }
286
+
287
+ _ctype_by_endian: Dict[int, Dict[str, Tuple[None, str, int, Struct]]] = {
288
+ endian: {
289
+ dbus_type: (
290
+ None,
291
+ *ctype_size,
292
+ Struct(f"{UNPACK_SYMBOL[endian]}{ctype_size[0]}"),
293
+ )
294
+ for dbus_type, ctype_size in DBUS_TO_CTYPE.items()
295
+ }
296
+ for endian in (BIG_ENDIAN, LITTLE_ENDIAN)
297
+ }
298
+
299
+ _readers_by_type: Dict[int, READER_TYPE] = {
300
+ BIG_ENDIAN: {
301
+ **_ctype_by_endian[BIG_ENDIAN],
302
+ **_complex_parsers
303
+ },
304
+ LITTLE_ENDIAN: {
305
+ **_ctype_by_endian[LITTLE_ENDIAN],
306
+ **_complex_parsers
307
+ },
308
+ }
309
+
310
+
311
+ def feed(self, data: bytes, ancdata=()):
312
+ """
313
+ Add these bytes to the unmarshaller's input buffer.
314
+ """
315
+ self.buf.extend(data)
316
+ for level, type_, data in ancdata:
317
+ if level == socket.SOL_SOCKET and type_ == socket.SCM_RIGHTS:
318
+ unix_fd_list = array.array("i")
319
+ unix_fd_list.frombytes(data[:len(data) - (len(data) % unix_fd_list.itemsize)])
320
+ self.unix_fds.append(list(unix_fd_list))
321
+
322
+ def __iter__(self):
323
+ return self
324
+
325
+ def __next__(self):
326
+ """
327
+ Decode the next message. Stops iteration if the buffer doesn't
328
+ contain a complete message.
329
+ """
330
+ msg = self.unmarshall()
331
+ if msg is None:
332
+ raise StopIteration
333
+ return msg
334
+
@@ -18,6 +18,9 @@ class MessageType(Enum):
18
18
  SIGNAL = 4 #: A broadcast signal to subscribed connections
19
19
 
20
20
 
21
+ MESSAGE_TYPE_MAP = {field.value: field for field in MessageType}
22
+
23
+
21
24
  class MessageFlag(IntFlag):
22
25
  """Flags that affect the behavior of sent and received messages
23
26
  """
@@ -27,6 +30,10 @@ class MessageFlag(IntFlag):
27
30
  ALLOW_INTERACTIVE_AUTHORIZATION = 4
28
31
 
29
32
 
33
+ MESSAGE_FLAG_MAP = {field.value: field for field in MessageFlag}
34
+ MESSAGE_FLAG_MAP[0] = "NONE"
35
+
36
+
30
37
  class NameFlag(IntFlag):
31
38
  """A flag that affects the behavior of a name request.
32
39
  """
@@ -10,6 +10,13 @@ from typing import List, Any
10
10
  import logging
11
11
  logger = logging.getLogger(__name__)
12
12
 
13
+ REQUIRED_FIELDS = {
14
+ MessageType.METHOD_CALL: ('path', 'member'),
15
+ MessageType.SIGNAL: ('path', 'member', 'interface'),
16
+ MessageType.ERROR: ('error_name', 'reply_serial'),
17
+ MessageType.METHOD_RETURN: ('reply_serial', ),
18
+ }
19
+
13
20
  class Message:
14
21
  """A class for sending and receiving messages through the
15
22
  :class:`MessageBus <asyncdbus.message_bus.MessageBus>` with the
@@ -91,7 +98,7 @@ class Message:
91
98
  self.interface = interface
92
99
  self.member = member
93
100
  self.message_type = message_type
94
- self.flags = flags if type(flags) is MessageFlag else MessageFlag(bytes([flags]))
101
+ self.flags = flags if type(flags) is MessageFlag else MessageFlag(flags)
95
102
  self.error_name = error_name if type(error_name) is not ErrorType else error_name.value
96
103
  self.reply_serial = reply_serial
97
104
  self.sender = sender
@@ -113,21 +120,12 @@ class Message:
113
120
  if self.error_name is not None:
114
121
  assert_interface_name_valid(self.error_name)
115
122
 
116
- def require_fields(*fields):
117
- for field in fields:
118
- if not getattr(self, field):
119
- raise InvalidMessageError(f'missing required field: {field}')
120
-
121
- if self.message_type == MessageType.METHOD_CALL:
122
- require_fields('path', 'member')
123
- elif self.message_type == MessageType.SIGNAL:
124
- require_fields('path', 'member', 'interface')
125
- elif self.message_type == MessageType.ERROR:
126
- require_fields('error_name', 'reply_serial')
127
- elif self.message_type == MessageType.METHOD_RETURN:
128
- require_fields('reply_serial')
129
- else:
123
+ required_fields = REQUIRED_FIELDS.get(self.message_type)
124
+ if not required_fields:
130
125
  raise InvalidMessageError(f'got unknown message type: {self.message_type}')
126
+ for field in required_fields:
127
+ if not getattr(self, field):
128
+ raise InvalidMessageError(f'missing required field: {field}')
131
129
 
132
130
  @staticmethod
133
131
  def new_error(msg: 'Message', error_name: str, error_text: str) -> 'Message':
@@ -3,7 +3,7 @@ from . import message_bus
3
3
  from .message import Message
4
4
  from .constants import MessageType, ErrorType, MessageFlag
5
5
  from . import introspection as intr
6
- from .errors import DBusError, InterfaceNotFoundError
6
+ from .errors import DBusError, InterfaceNotFoundError, NameNotFoundError
7
7
  from ._private.util import replace_idx_with_fds, replace_fds_with_idx
8
8
  from .signature import Variant, Str, Var, Tuple
9
9
 
@@ -2,6 +2,7 @@ from .validators import is_object_path_valid
2
2
  from .errors import InvalidSignatureError, SignatureBodyMismatchError
3
3
 
4
4
  from typing import Any, List as _List, Union, Tuple as _Tuple, Dict as _Dict, Generic, TypeVar
5
+ from functools import lru_cache
5
6
 
6
7
 
7
8
  class SignatureType:
@@ -20,9 +21,9 @@ class SignatureType:
20
21
  """
21
22
  _tokens = 'ybnqiuxtdsogavh({'
22
23
 
23
- def __init__(self, token):
24
+ def __init__(self, token: str) -> None:
24
25
  self.token = token
25
- self.children = []
26
+ self.children: List[SignatureType] = []
26
27
  self._signature = None
27
28
 
28
29
  def __eq__(self, other):
@@ -56,8 +57,10 @@ class SignatureType:
56
57
 
57
58
  @staticmethod
58
59
  def _parse_next(signature):
59
- if not signature:
60
+ if not signature or signature in ('""',"''"):
60
61
  return (None, '')
62
+ if signature[0] in "'\"":
63
+ signature = signature[1:-1]
61
64
 
62
65
  token = signature[0]
63
66
 
@@ -216,7 +219,7 @@ class SignatureType:
216
219
  child_type.children[0].verify(key)
217
220
  child_type.children[1].verify(value)
218
221
  elif child_type.token == 'y':
219
- if not isinstance(body, bytes):
222
+ if not isinstance(body, (bytearray, bytes)):
220
223
  raise SignatureBodyMismatchError(
221
224
  f'DBus ARRAY type "a" with BYTE child must be Python type "bytes", got {type(body)}'
222
225
  )
@@ -257,43 +260,33 @@ class SignatureType:
257
260
  """
258
261
  if body is None:
259
262
  raise SignatureBodyMismatchError('Cannot serialize Python type "None"')
260
- if self.token == 'y':
261
- self._verify_byte(body)
262
- elif self.token == 'b':
263
- self._verify_boolean(body)
264
- elif self.token == 'n':
265
- self._verify_int16(body)
266
- elif self.token == 'q':
267
- self._verify_uint16(body)
268
- elif self.token == 'i':
269
- self._verify_int32(body)
270
- elif self.token == 'u':
271
- self._verify_uint32(body)
272
- elif self.token == 'x':
273
- self._verify_int64(body)
274
- elif self.token == 't':
275
- self._verify_uint64(body)
276
- elif self.token == 'd':
277
- self._verify_double(body)
278
- elif self.token == 'h':
279
- self._verify_unix_fd(body)
280
- elif self.token == 'o':
281
- self._verify_object_path(body)
282
- elif self.token == 's':
283
- self._verify_string(body)
284
- elif self.token == 'g':
285
- self._verify_signature(body)
286
- elif self.token == 'a':
287
- self._verify_array(body)
288
- elif self.token == '(':
289
- self._verify_struct(body)
290
- elif self.token == 'v':
291
- self._verify_variant(body)
263
+ validator = self.validators.get(self.token)
264
+ if validator:
265
+ validator(self, body)
292
266
  else:
293
267
  raise Exception(f'cannot verify type with token {self.token}')
294
268
 
295
269
  return True
296
270
 
271
+ validators = {
272
+ "y": _verify_byte,
273
+ "b": _verify_boolean,
274
+ "n": _verify_int16,
275
+ "q": _verify_uint16,
276
+ "i": _verify_int32,
277
+ "u": _verify_uint32,
278
+ "x": _verify_int64,
279
+ "t": _verify_uint64,
280
+ "d": _verify_double,
281
+ "h": _verify_uint32,
282
+ "o": _verify_string,
283
+ "s": _verify_string,
284
+ "g": _verify_signature,
285
+ "a": _verify_array,
286
+ "(": _verify_struct,
287
+ "v": _verify_variant,
288
+ }
289
+
297
290
 
298
291
  class SignatureTree:
299
292
  """A class that represents a signature as a tree structure for conveniently
@@ -310,22 +303,15 @@ class SignatureTree:
310
303
  :raises:
311
304
  :class:`InvalidSignatureError` if the given signature is not valid.
312
305
  """
313
-
314
- _cache = {}
315
-
316
306
  @staticmethod
317
- def _get(signature: str = ''):
318
- if hasattr(signature, 'tree'):
319
- signature = signature.tree.signature
320
- if signature in SignatureTree._cache:
321
- return SignatureTree._cache[signature]
322
- SignatureTree._cache[signature] = SignatureTree(signature)
323
- return SignatureTree._cache[signature]
307
+ @lru_cache(maxsize=None)
308
+ def _get(signature: str = '') -> "SignatureTree":
309
+ return SignatureTree(signature)
324
310
 
325
311
  def __init__(self, signature: str = ''):
326
312
  self.signature = signature
327
313
 
328
- self.types = []
314
+ self.types: List[SignatureType] = []
329
315
 
330
316
  if hasattr(signature, 'tree'):
331
317
  signature = signature.tree.signature
@@ -501,9 +487,10 @@ class Variant(Generic[T]):
501
487
  :class:`InvalidSignatureError` if the signature is not valid.
502
488
  :class:`SignatureBodyMismatchError` if the signature does not match the body.
503
489
  """
504
- tree = SignatureTree._get('v')
505
-
506
- def __init__(self, signature: Union[str, SignatureTree, SignatureType], value: Any):
490
+ def __init__(self,
491
+ signature: Union[str, SignatureTree, SignatureType],
492
+ value: Any,
493
+ verify: bool = True):
507
494
  signature_str = ''
508
495
  signature_tree = None
509
496
  signature_type = None
@@ -520,12 +507,13 @@ class Variant(Generic[T]):
520
507
  raise TypeError('signature must be a SignatureTree, SignatureType, or a string')
521
508
 
522
509
  if signature_tree:
523
- if len(signature_tree.types) != 1:
510
+ if verify and len(signature_tree.types) != 1:
524
511
  raise ValueError('variants must have a signature for a single complete type')
525
512
  signature_str = signature_tree.signature
526
513
  signature_type = signature_tree.types[0]
527
514
 
528
- signature_type.verify(value)
515
+ if verify:
516
+ signature_type.verify(value)
529
517
 
530
518
  self.type = signature_type
531
519
  self.signature = signature_str