Debian Codegraph @

src/bluetooth_data_tools/gap.py

raw symbols SCIP
1 """GATT Advertisement and Scan Response Data (GAP)."""
2
3 import logging
4 from collections.abc import Iterable
5 from enum import IntEnum
6 from functools import lru_cache
7 from typing import TYPE_CHECKING
8
9 BLE_UUID = "0000-1000-8000-00805f9b34fb"
10 _LOGGER = logging.getLogger(__name__)
11
12
13 class BLEGAPAdvertisement:
14 """GATT Advertisement and Scan Response Data (GAP).
15
16 Instances are produced by ``parse_advertisement_data`` and are cached, so
17 the same instance -- and the same ``service_uuids`` / ``service_data`` /
18 ``manufacturer_data`` containers -- is handed to every caller that parses
19 the same payload. Treat all attributes as read-only; copy before mutating.
20 """
21
22 __slots__ = (
23 "local_name",
24 "manufacturer_data",
25 "service_data",
26 "service_uuids",
27 "tx_power",
28 )
29
30 def __init__(
31 self,
32 local_name: str | None,
33 service_uuids: list[str],
34 service_data: dict[str, bytes],
35 manufacturer_data: dict[int, bytes],
36 tx_power: int | None,
37 ) -> None:
38 """Initialize GAP Advertisement."""
39 self.local_name = local_name
40 self.service_uuids = service_uuids
41 self.service_data = service_data
42 self.manufacturer_data = manufacturer_data
43 self.tx_power = tx_power
44
45
46 class BLEGAPType(IntEnum):
47 """Advertising data types."""
48
49 TYPE_UNKNOWN = 0x00
50 TYPE_FLAGS = 0x01
51 TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE = 0x02
52 TYPE_16BIT_SERVICE_UUID_COMPLETE = 0x03
53 TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE = 0x04
54 TYPE_32BIT_SERVICE_UUID_COMPLETE = 0x05
55 TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE = 0x06
56 TYPE_128BIT_SERVICE_UUID_COMPLETE = 0x07
57 TYPE_SHORT_LOCAL_NAME = 0x08
58 TYPE_COMPLETE_LOCAL_NAME = 0x09
59 TYPE_TX_POWER_LEVEL = 0x0A
60 TYPE_CLASS_OF_DEVICE = 0x0D
61 TYPE_SIMPLE_PAIRING_HASH_C = 0x0E
62 TYPE_SIMPLE_PAIRING_RANDOMIZER_R = 0x0F
63 TYPE_SECURITY_MANAGER_TK_VALUE = 0x10
64 TYPE_SECURITY_MANAGER_OOB_FLAGS = 0x11
65 TYPE_SLAVE_CONNECTION_INTERVAL_RANGE = 0x12
66 TYPE_SOLICITED_SERVICE_UUIDS_16BIT = 0x14
67 TYPE_SOLICITED_SERVICE_UUIDS_128BIT = 0x15
68 TYPE_SERVICE_DATA = 0x16
69 TYPE_PUBLIC_TARGET_ADDRESS = 0x17
70 TYPE_RANDOM_TARGET_ADDRESS = 0x18
71 TYPE_APPEARANCE = 0x19
72 TYPE_ADVERTISING_INTERVAL = 0x1A
73 TYPE_LE_BLUETOOTH_DEVICE_ADDRESS = 0x1B
74 TYPE_LE_ROLE = 0x1C
75 TYPE_SIMPLE_PAIRING_HASH_C256 = 0x1D
76 TYPE_SIMPLE_PAIRING_RANDOMIZER_R256 = 0x1E
77 TYPE_SERVICE_DATA_32BIT_UUID = 0x20
78 TYPE_SERVICE_DATA_128BIT_UUID = 0x21
79 TYPE_URI = 0x24
80 TYPE_3D_INFORMATION_DATA = 0x3D
81 TYPE_MANUFACTURER_SPECIFIC_DATA = 0xFF
82
83
84 # Signed-fold constants for the one-byte TX Power Level decode.
85 # A uint8 value at or above _INT8_SIGN_THRESHOLD is negative when interpreted
86 # as int8, and recovers its signed value via subtraction of _INT8_RANGE.
87 _INT8_SIGN_THRESHOLD = 128
88 _INT8_RANGE = 256
89
90 TYPE_FLAGS = BLEGAPType.TYPE_FLAGS.value
91 TYPE_SHORT_LOCAL_NAME = BLEGAPType.TYPE_SHORT_LOCAL_NAME.value
92 TYPE_COMPLETE_LOCAL_NAME = BLEGAPType.TYPE_COMPLETE_LOCAL_NAME.value
93 TYPE_MANUFACTURER_SPECIFIC_DATA = BLEGAPType.TYPE_MANUFACTURER_SPECIFIC_DATA.value
94 TYPE_16BIT_SERVICE_UUID_COMPLETE = BLEGAPType.TYPE_16BIT_SERVICE_UUID_COMPLETE.value
95 TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE = (
96 BLEGAPType.TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE.value
97 )
98 TYPE_32BIT_SERVICE_UUID_COMPLETE = BLEGAPType.TYPE_32BIT_SERVICE_UUID_COMPLETE.value
99 TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE = (
100 BLEGAPType.TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE.value
101 )
102 TYPE_128BIT_SERVICE_UUID_COMPLETE = BLEGAPType.TYPE_128BIT_SERVICE_UUID_COMPLETE.value
103 TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE = (
104 BLEGAPType.TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE.value
105 )
106 TYPE_SERVICE_DATA = BLEGAPType.TYPE_SERVICE_DATA.value
107 TYPE_SERVICE_DATA_32BIT_UUID = BLEGAPType.TYPE_SERVICE_DATA_32BIT_UUID.value
108 TYPE_SERVICE_DATA_128BIT_UUID = BLEGAPType.TYPE_SERVICE_DATA_128BIT_UUID.value
109 TYPE_TX_POWER_LEVEL = BLEGAPType.TYPE_TX_POWER_LEVEL.value
110
111 bytes_ = bytes
112
113 BLEGAPAdvertisementTupleType = tuple[
114 str | None, list[str], dict[str, bytes], dict[int, bytes], int | None
115 ]
116
117
118 @lru_cache(maxsize=256)
119 def _uint128_bytes_as_uuid(uint128_bytes: bytes_) -> str:
120 """Convert 16 little-endian bytes to a canonical UUID str."""
121 # bytes.hex() is a single C call; reversing the 16-byte slice yields the
122 # big-endian hex form directly, skipping the int.from_bytes + format-spec
123 # round-trip used previously (~40% faster on the cache-miss path).
124 hex = uint128_bytes[::-1].hex()
125 return f"{hex[:8]}-{hex[8:12]}-{hex[12:16]}-{hex[16:20]}-{hex[20:]}"
126
127
128 _cached_uint128_bytes_as_uuid = _uint128_bytes_as_uuid
129
130
131 @lru_cache(maxsize=256)
132 def _uint16_int_as_uuid(uuid16_int: int) -> str:
133 """Convert a 16-bit UUID integer to a UUID str."""
134 return f"0000{uuid16_int:04x}-{BLE_UUID}"
135
136
137 _cached_uint16_int_as_uuid = _uint16_int_as_uuid
138
139
140 @lru_cache(maxsize=256)
141 def _uint32_int_as_uuid(uuid32_int: int) -> str:
142 """Convert a 32-bit UUID integer to a UUID str."""
143 return f"{uuid32_int:08x}-{BLE_UUID}"
144
145
146 _cached_uint32_int_as_uuid = _uint32_int_as_uuid
147
148
149 # Shared empty containers, returned as-is when an advertisement carries none of
150 # the corresponding AD types (the common case) to avoid allocating on the parse
151 # path. They are handed out unguarded, so mutating a returned container is
152 # process-wide corruption, not a local mistake -- see the note on
153 # parse_advertisement_data_bytes.
154 _EMPTY_MANUFACTURER_DATA: dict[int, bytes] = {}
155 _EMPTY_SERVICE_DATA: dict[str, bytes] = {}
156 _EMPTY_SERVICE_UUIDS: list[str] = []
157
158
159 @lru_cache(maxsize=256)
160 def _parse_advertisement_data(
161 data: bytes,
162 ) -> BLEGAPAdvertisement:
163 """Parse advertisement data and return a BLEGAPAdvertisement."""
164 return _uncached_parse_advertisement_data(data)
165
166
167 _cached_parse_advertisement_data = _parse_advertisement_data
168
169
170 @lru_cache(maxsize=256)
171 def _parse_advertisement_data_from_tuple(
172 data: tuple[bytes, ...],
173 ) -> BLEGAPAdvertisement:
174 """Parse a multi-chunk advertisement tuple, caching on the tuple itself.
175
176 Hashing a tuple of bytes elements skips the per-call ``b"".join`` allocation
177 on cache hits, which is the hot path when the same scan callback delivers
178 the same (adv_data, scan_response_data) tuple repeatedly.
179 """
180 return _cached_parse_advertisement_data(b"".join(data))
181
182
183 _cached_parse_advertisement_data_from_tuple = _parse_advertisement_data_from_tuple
184
185
186 def parse_advertisement_data(
187 data: Iterable[bytes],
188 ) -> BLEGAPAdvertisement:
189 """Parse advertisement data and return a BLEGAPAdvertisement.
190
191 The result is cached and shared between callers -- see BLEGAPAdvertisement.
192 """
193 if type(data) is tuple:
194 if len(data) == 1:
195 return _cached_parse_advertisement_data(data[0])
196 return _cached_parse_advertisement_data_from_tuple(data)
197 return _cached_parse_advertisement_data(b"".join(data))
198
199
200 def _uncached_parse_advertisement_data(data: bytes) -> BLEGAPAdvertisement:
201 # Route BLEGAPAdvertisement-cache misses through the bytes-keyed cache
202 # (symmetric with _uncached_parse_advertisement_tuple, see #261). When the
203 # bytes-tuple cache already holds the parsed result, the miss path skips
204 # the full parse loop; a true miss populates that cache so subsequent
205 # parse_advertisement_data_bytes / parse_advertisement_data_tuple calls
206 # on the same payload also win.
207 return BLEGAPAdvertisement(*parse_advertisement_data_bytes(data))
208
209
210 def _uncached_parse_advertisement_tuple(
211 data: tuple[bytes, ...],
212 ) -> BLEGAPAdvertisementTupleType:
213 # Route tuple-cache misses through the bytes-keyed cache so identical
214 # content arriving via a fresh tuple identity still skips the full parse.
215 # The outer lru_cache around parse_advertisement_data_tuple owns the
216 # hit-path (C-level hash on the tuple, no join).
217 if len(data) == 1:
218 return parse_advertisement_data_bytes(data[0])
219 return parse_advertisement_data_bytes(b"".join(data))
220
221
222 def _uncached_parse_advertisement_bytes(
223 gap_bytes: bytes,
224 ) -> BLEGAPAdvertisementTupleType:
225 """Parse raw advertisement bytes into a BLEGAPAdvertisementTupleType.
226
227 The returned containers are shared: the public entry points are cached, and
228 an advertisement carrying none of a given AD type yields a module-level
229 empty container. Callers MUST treat the result as read-only -- appending to
230 a returned ``service_uuids`` list mutates what every other caller sees,
231 including for unrelated payloads. Copy first if you need to modify.
232 """
233 manufacturer_data = _EMPTY_MANUFACTURER_DATA
234 service_data = _EMPTY_SERVICE_DATA
235 service_uuids = _EMPTY_SERVICE_UUIDS
236 local_name: str | None = None
237 tx_power: int | None = None
238
239 offset = 0
240 total_length = len(gap_bytes)
241 gap_data = gap_bytes
242 # IMPORTANT: All data must be manually bounds checked
243 # because the data is untrusted and can be malformed.
244 while offset + 2 <= total_length:
245 if not (length := gap_data[offset]):
246 offset += 1 # Handle zero padding
247 continue
248 if not (gap_type_num := gap_data[offset + 1]):
249 offset += 1 + length # Skip empty type
250 continue
251 start = offset + 2
252 end = start + length - 1
253 offset += 1 + length
254 if end > total_length or end - start <= 0:
255 _LOGGER.debug(
256 "Invalid BLE GAP AD structure at offset %s: %s (length=%s)",
257 # ``offset`` has already advanced past this structure, so report
258 # where it actually started (``start`` is its offset plus the
259 # length and type bytes).
260 start - 2,
261 gap_bytes,
262 length,
263 )
264 continue
265 # FLAGS (0x01) appears in nearly every legacy advertisement and is
266 # unhandled here โ€” short-circuit it before the elif dispatch chain so
267 # the common case doesn't pay for ten failed type comparisons.
268 if gap_type_num == TYPE_FLAGS:
269 continue
270 if (
271 gap_type_num == TYPE_SHORT_LOCAL_NAME
272 and local_name is None
273 or gap_type_num == TYPE_COMPLETE_LOCAL_NAME
274 ):
275 local_name = gap_data[start:end].decode("utf-8", "replace")
276 elif gap_type_num == TYPE_MANUFACTURER_SPECIFIC_DATA:
277 splice_pos = start + 2
278 if splice_pos > end:
279 continue
280 if manufacturer_data is _EMPTY_MANUFACTURER_DATA:
281 manufacturer_data = {}
282 manufacturer_data[gap_data[start] | (gap_data[start + 1] << 8)] = gap_data[
283 splice_pos:end
284 ]
285 elif gap_type_num in {
286 TYPE_16BIT_SERVICE_UUID_COMPLETE,
287 TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE,
288 }:
289 if service_uuids is _EMPTY_SERVICE_UUIDS:
290 service_uuids = []
291 # Parse multiple 16-bit UUIDs (each is 2 little-endian bytes).
292 # Decode inline to an int and look up by int key to skip the
293 # per-iteration bytes-slice allocation.
294 for i in range(start, end, 2):
295 if i + 2 <= end:
296 service_uuids.append(
297 _cached_uint16_int_as_uuid(gap_data[i] | (gap_data[i + 1] << 8))
298 )
299 elif gap_type_num in {
300 TYPE_32BIT_SERVICE_UUID_COMPLETE,
301 TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE,
302 }:
303 if service_uuids is _EMPTY_SERVICE_UUIDS:
304 service_uuids = []
305 # Parse multiple 32-bit UUIDs (each is 4 little-endian bytes).
306 for i in range(start, end, 4):
307 if i + 4 <= end:
308 # Assemble via uint local: in Cython the shift-by-24 of an
309 # unsigned char promotes to signed int and would yield a
310 # negative value when bit 31 is set; assigning to a
311 # cython.uint local recovers the unsigned 32-bit value.
312 uuid32_int = (
313 gap_data[i]
314 | (gap_data[i + 1] << 8)
315 | (gap_data[i + 2] << 16)
316 | (gap_data[i + 3] << 24)
317 )
318 service_uuids.append(_cached_uint32_int_as_uuid(uuid32_int))
319 elif gap_type_num in {
320 TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE,
321 TYPE_128BIT_SERVICE_UUID_COMPLETE,
322 }:
323 if service_uuids is _EMPTY_SERVICE_UUIDS:
324 service_uuids = []
325 # Parse multiple 128-bit UUIDs (each is 16 bytes). The AD length
326 # may not be a clean multiple of 16 for malformed input โ€” skip
327 # any trailing remainder rather than emitting a truncated UUID.
328 for i in range(start, end, 16):
329 if i + 16 <= end:
330 service_uuids.append(
331 _cached_uint128_bytes_as_uuid(gap_data[i : i + 16])
332 )
333 elif gap_type_num == TYPE_SERVICE_DATA:
334 splice_pos = start + 2
335 if splice_pos > end:
336 continue
337 if service_data is _EMPTY_SERVICE_DATA:
338 service_data = {}
339 service_data[
340 _cached_uint16_int_as_uuid(gap_data[start] | (gap_data[start + 1] << 8))
341 ] = gap_data[splice_pos:end]
342 elif gap_type_num == TYPE_SERVICE_DATA_32BIT_UUID:
343 splice_pos = start + 4
344 if splice_pos > end:
345 continue
346 if service_data is _EMPTY_SERVICE_DATA:
347 service_data = {}
348 uuid32_int = (
349 gap_data[start]
350 | (gap_data[start + 1] << 8)
351 | (gap_data[start + 2] << 16)
352 | (gap_data[start + 3] << 24)
353 )
354 service_data[_cached_uint32_int_as_uuid(uuid32_int)] = gap_data[
355 splice_pos:end
356 ]
357 elif gap_type_num == TYPE_SERVICE_DATA_128BIT_UUID:
358 splice_pos = start + 16
359 if splice_pos > end:
360 continue
361 if service_data is _EMPTY_SERVICE_DATA:
362 service_data = {}
363 service_data[_cached_uint128_bytes_as_uuid(gap_data[start:splice_pos])] = (
364 gap_data[splice_pos:end]
365 )
366 elif gap_type_num == TYPE_TX_POWER_LEVEL:
367 # BLE Core Spec Vol 3 Part C ยง11: TX Power Level is exactly one
368 # signed octet. Anything else is malformed โ€” skip instead of
369 # decoding the bytes as a wider little-endian signed integer.
370 if end - start == 1:
371 tx_power_byte = gap_data[start]
372 tx_power = (
373 tx_power_byte - _INT8_RANGE
374 if tx_power_byte >= _INT8_SIGN_THRESHOLD
375 else tx_power_byte
376 )
377
378 return (local_name, service_uuids, service_data, manufacturer_data, tx_power)
379
380
381 if TYPE_CHECKING:
382
383 @lru_cache(maxsize=1024)
384 def parse_advertisement_data_bytes(
385 gap_bytes: bytes,
386 ) -> BLEGAPAdvertisementTupleType:
387 """Parse a tuple of raw advertisement data and return a tuple of BLEGAPAdvertisementTupleType.
388
389 The format of the tuple is:
390 (local_name, service_uuids, service_data, manufacturer_data, tx_power)
391
392 This is tightly coupled to bleak. If you are not using bleak
393 it is recommended to use parse_advertisement_data instead.
394
395 local_name: str | None
396 service_uuids: list[str]
397 service_data: dict[str, bytes]
398 manufacturer_data: dict[int, bytes]
399 tx_power: int | None
400
401 The returned containers are shared between callers and MUST be treated
402 as read-only; see _uncached_parse_advertisement_bytes.
403 """
404 return _uncached_parse_advertisement_bytes(gap_bytes)
405
406 @lru_cache(maxsize=256)
407 def parse_advertisement_data_tuple(
408 data: tuple[bytes, ...],
409 ) -> BLEGAPAdvertisementTupleType:
410 """Parse raw advertisement bytes and return a tuple of BLEGAPAdvertisementTupleType.
411
412 The format of the tuple is:
413 (local_name, service_uuids, service_data, manufacturer_data, tx_power)
414
415 This is tightly coupled to bleak. If you are not using bleak
416 it is recommended to use parse_advertisement_data instead.
417
418 local_name: str | None
419 service_uuids: list[str]
420 service_data: dict[str, bytes]
421 manufacturer_data: dict[int, bytes]
422 tx_power: int | None
423
424 The returned containers are shared between callers and MUST be treated
425 as read-only; see _uncached_parse_advertisement_bytes.
426 """
427 return _uncached_parse_advertisement_tuple(data)
428 else:
429 parse_advertisement_data_bytes = lru_cache(maxsize=1024)(
430 _uncached_parse_advertisement_bytes
431 )
432 parse_advertisement_data_tuple = lru_cache(maxsize=256)(
433 _uncached_parse_advertisement_tuple
434 )