Debian Codegraph @

tests/channels/test_l2cap.py

raw
1 """Tests for the L2CAP ATT socket transport."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import errno
7 import os
8 import re
9 import socket
10 import sys
11 from typing import TYPE_CHECKING
12 from unittest.mock import Mock, patch
13
14 import pytest
15 from bleak import BleakError
16
17 from habluetooth.channels.l2cap import (
18 AF_BLUETOOTH,
19 ATT_CID,
20 BT_SECURITY_HIGH,
21 BT_SECURITY_LOW,
22 BT_SECURITY_MEDIUM,
23 L2CAPSocket,
24 _set_result_if_pending,
25 _wait_connected,
26 can_use_l2cap,
27 make_sockaddr_l2,
28 str_to_bdaddr,
29 )
30 from habluetooth.const import BDADDR_LE_RANDOM
31
32 if TYPE_CHECKING:
33 from collections.abc import Callable, Iterator
34
35 pytestmark = [
36 pytest.mark.asyncio,
37 # L2CAP is Linux only; the transport drives the socket with add_reader /
38 # add_writer / sock_sendall, which the Windows proactor event loop does not
39 # implement. The selector loops on Linux and macOS run these fine.
40 pytest.mark.skipif(
41 sys.platform == "win32",
42 reason="L2CAP transport needs a selector event loop (Linux/macOS)",
43 ),
44 ]
45
46 _SOURCE = "00:11:22:33:44:55"
47 _PEER = "AA:BB:CC:DD:EE:FF"
48
49
50 @pytest.fixture
51 def pair() -> Iterator[tuple[socket.socket, socket.socket]]:
52 """Yield a connected socket pair and close both ends on teardown."""
53 left, right = socket.socketpair()
54 try:
55 yield left, right
56 finally:
57 left.close()
58 right.close()
59
60
61 async def _connect(
62 left: socket.socket,
63 *,
64 on_data: Callable[[bytes], None],
65 on_close: Callable[[Exception | None], None],
66 connect_result: int = 0,
67 bind_result: int = 0,
68 timeout: float = 1.0,
69 ) -> L2CAPSocket:
70 """Drive create_connection over an injected socket with patched syscalls."""
71 with (
72 patch("habluetooth.channels.l2cap._set_bt_security"),
73 patch("habluetooth.channels.l2cap._bind_fd", return_value=bind_result),
74 patch("habluetooth.channels.l2cap._connect_fd", return_value=connect_result),
75 ):
76 return await L2CAPSocket.create_connection(
77 source=_SOURCE,
78 address=_PEER,
79 address_type=BDADDR_LE_RANDOM,
80 on_data=on_data,
81 on_close=on_close,
82 timeout=timeout,
83 sock=left,
84 )
85
86
87 def _strerror(err: int) -> str:
88 """Return the platform error string for ``err`` as a regex-safe pattern."""
89 return re.escape(os.strerror(err))
90
91
92 # -- address packing ------------------------------------------------------
93 async def test_str_to_bdaddr_reverses_octets() -> None:
94 """A textual BD_ADDR is packed least-significant-octet first."""
95 assert str_to_bdaddr("AA:BB:CC:DD:EE:FF") == bytes(
96 [0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA]
97 )
98
99
100 @pytest.mark.parametrize("bad", ["AA:BB:CC", "", "AA:BB:CC:DD:EE:FF:00"])
101 async def test_str_to_bdaddr_rejects_malformed(bad: str) -> None:
102 """An address without exactly six octets is rejected."""
103 with pytest.raises(ValueError, match="Invalid MAC address"):
104 str_to_bdaddr(bad)
105
106
107 async def test_make_sockaddr_l2_layout() -> None:
108 """The packed sockaddr carries the family, channel, address, and type."""
109 addr = make_sockaddr_l2(_PEER, ATT_CID, BDADDR_LE_RANDOM)
110 assert addr.l2_family == AF_BLUETOOTH
111 assert addr.l2_psm == 0
112 assert bytes(addr.l2_bdaddr) == bytes([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
113 assert addr.l2_cid == ATT_CID
114 assert addr.l2_bdaddr_type == BDADDR_LE_RANDOM
115
116
117 # -- connect handshake ----------------------------------------------------
118 @pytest.mark.parametrize(
119 ("security_level", "expected_calls"),
120 [(2, 1), (0, 0)],
121 )
122 async def test_create_connection_security_level(
123 pair: tuple[socket.socket, socket.socket],
124 security_level: int,
125 expected_calls: int,
126 ) -> None:
127 """A non-zero security level requests kernel LE security; zero skips it."""
128 left, _right = pair
129 with (
130 patch("habluetooth.channels.l2cap._set_bt_security") as set_security,
131 patch("habluetooth.channels.l2cap._bind_fd", return_value=0),
132 patch("habluetooth.channels.l2cap._connect_fd", return_value=0),
133 ):
134 sock = await L2CAPSocket.create_connection(
135 source=_SOURCE,
136 address=_PEER,
137 address_type=BDADDR_LE_RANDOM,
138 on_data=lambda _d: None,
139 on_close=lambda _e: None,
140 timeout=1.0,
141 security_level=security_level,
142 sock=left,
143 )
144 sock.close()
145 assert set_security.call_count == expected_calls
146
147
148 async def test_default_security_level_is_low(
149 pair: tuple[socket.socket, socket.socket],
150 ) -> None:
151 """The connection starts at BT_SECURITY_LOW to match bluetoothd."""
152 left, _right = pair
153 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
154 assert sock.security_level == BT_SECURITY_LOW
155 sock.close()
156
157
158 async def test_set_security_level_raises_and_tracks(
159 pair: tuple[socket.socket, socket.socket],
160 ) -> None:
161 """Raising the level applies the socket option and records the new level."""
162 left, _right = pair
163 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
164 with patch("habluetooth.channels.l2cap._set_bt_security") as set_security:
165 assert sock.set_security_level(BT_SECURITY_MEDIUM) is True
166 assert sock.security_level == BT_SECURITY_MEDIUM
167 set_security.assert_called_once_with(sock._sock, BT_SECURITY_MEDIUM)
168 sock.close()
169
170
171 async def test_set_security_level_never_downgrades(
172 pair: tuple[socket.socket, socket.socket],
173 ) -> None:
174 """A level at or below the current one is a no-op and is not applied."""
175 left, _right = pair
176 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
177 with patch("habluetooth.channels.l2cap._set_bt_security"):
178 sock.set_security_level(BT_SECURITY_HIGH)
179 with patch("habluetooth.channels.l2cap._set_bt_security") as set_security:
180 assert sock.set_security_level(BT_SECURITY_MEDIUM) is False # lower
181 assert sock.set_security_level(BT_SECURITY_HIGH) is False # equal
182 set_security.assert_not_called()
183 assert sock.security_level == BT_SECURITY_HIGH
184 sock.close()
185
186
187 async def test_set_security_level_handles_oserror(
188 pair: tuple[socket.socket, socket.socket],
189 ) -> None:
190 """A kernel refusal leaves the tracked level unchanged and returns False."""
191 left, _right = pair
192 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
193 with patch(
194 "habluetooth.channels.l2cap._set_bt_security",
195 side_effect=OSError(errno.EPERM, "denied"),
196 ):
197 assert sock.set_security_level(BT_SECURITY_MEDIUM) is False
198 assert sock.security_level == BT_SECURITY_LOW
199 sock.close()
200
201
202 async def test_create_connection_immediate_success(
203 pair: tuple[socket.socket, socket.socket],
204 ) -> None:
205 """A connect that succeeds at once yields a live, readable socket."""
206 left, right = pair
207 received: list[bytes] = []
208 closed: list[Exception | None] = []
209 got = asyncio.Event()
210
211 def on_data(data: bytes) -> None:
212 received.append(data)
213 got.set()
214
215 sock = await _connect(left, on_data=on_data, on_close=closed.append)
216 right.send(b"\x1b\x05\x00\xab")
217 await got.wait()
218 assert received == [b"\x1b\x05\x00\xab"]
219 assert closed == []
220 sock.close()
221
222
223 async def test_create_connection_in_progress_then_writable(
224 pair: tuple[socket.socket, socket.socket],
225 ) -> None:
226 """An EINPROGRESS connect completes once the socket reports writable."""
227 left, _right = pair
228 sock = await _connect(
229 left,
230 on_data=lambda _d: None,
231 on_close=lambda _e: None,
232 connect_result=errno.EINPROGRESS,
233 )
234 assert sock._closed is False
235 sock.close()
236
237
238 async def test_create_connection_so_error_fails_and_closes(
239 pair: tuple[socket.socket, socket.socket],
240 ) -> None:
241 """A non-zero SO_ERROR after connect surfaces and closes the socket."""
242 left, _right = pair
243 with (
244 patch(
245 "habluetooth.channels.l2cap._so_error",
246 return_value=errno.EHOSTUNREACH,
247 ),
248 pytest.raises(OSError, match=_strerror(errno.EHOSTUNREACH)) as exc_info,
249 ):
250 await _connect(
251 left,
252 on_data=lambda _d: None,
253 on_close=lambda _e: None,
254 connect_result=errno.EINPROGRESS,
255 )
256 assert exc_info.value.errno == errno.EHOSTUNREACH
257 assert left.fileno() == -1 # the injected socket was closed on failure
258
259
260 @pytest.mark.parametrize(
261 ("connect_kwargs", "expected_errno"),
262 [
263 ({"connect_result": errno.EHOSTUNREACH}, errno.EHOSTUNREACH),
264 ({"bind_result": errno.EPERM}, errno.EPERM),
265 ],
266 )
267 async def test_create_connection_syscall_error_closes(
268 pair: tuple[socket.socket, socket.socket],
269 connect_kwargs: dict[str, int],
270 expected_errno: int,
271 ) -> None:
272 """A hard bind/connect error is raised and the socket is closed."""
273 left, _right = pair
274 with pytest.raises(OSError, match=_strerror(expected_errno)) as exc_info:
275 await _connect(
276 left,
277 on_data=lambda _d: None,
278 on_close=lambda _e: None,
279 **connect_kwargs,
280 )
281 assert exc_info.value.errno == expected_errno
282 assert left.fileno() == -1
283
284
285 async def test_wait_connected_times_out(
286 pair: tuple[socket.socket, socket.socket],
287 ) -> None:
288 """If the socket never reports writable, the connect times out."""
289 loop = asyncio.get_running_loop()
290 left, _right = pair
291 with (
292 patch.object(loop, "add_writer"),
293 pytest.raises(TimeoutError),
294 ):
295 await _wait_connected(left, loop, 0.01)
296
297
298 # -- send / receive / teardown -------------------------------------------
299 async def test_send_writes_one_pdu(
300 pair: tuple[socket.socket, socket.socket],
301 ) -> None:
302 """Send writes the PDU to the peer end of the channel."""
303 left, right = pair
304 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
305 await sock.send(b"\x02\x17\x00")
306 assert right.recv(64) == b"\x02\x17\x00"
307 sock.close()
308
309
310 async def test_send_serializes_concurrent_writes(
311 pair: tuple[socket.socket, socket.socket],
312 ) -> None:
313 """Concurrent sends are serialized so one cannot stall another mid-write."""
314 left, _right = pair
315 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
316 order: list[tuple[str, bytes]] = []
317 first_entered = asyncio.Event()
318 release_first = asyncio.Event()
319
320 async def fake_sendall(_sock: socket.socket, data: bytes) -> None:
321 order.append(("enter", data))
322 if data == b"A":
323 first_entered.set()
324 await release_first.wait()
325 order.append(("exit", data))
326
327 with patch.object(sock._loop, "sock_sendall", fake_sendall):
328 first = asyncio.create_task(sock.send(b"A"))
329 await first_entered.wait()
330 second = asyncio.create_task(sock.send(b"B"))
331 await asyncio.sleep(0)
332 # The second send is blocked on the lock while the first is in flight.
333 assert order == [("enter", b"A")]
334 release_first.set()
335 await asyncio.gather(first, second)
336 assert order == [
337 ("enter", b"A"),
338 ("exit", b"A"),
339 ("enter", b"B"),
340 ("exit", b"B"),
341 ]
342 sock.close()
343
344
345 async def test_send_rechecks_closed_after_acquiring_lock(
346 pair: tuple[socket.socket, socket.socket],
347 ) -> None:
348 """A send parked on the write lock raises BleakError if close() intervenes."""
349 left, _right = pair
350 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
351 in_flight = asyncio.Event()
352 release = asyncio.Event()
353
354 async def fake_sendall(_sock: socket.socket, _data: bytes) -> None:
355 in_flight.set()
356 await release.wait()
357
358 with patch.object(sock._loop, "sock_sendall", fake_sendall):
359 first = asyncio.create_task(sock.send(b"A"))
360 await in_flight.wait()
361 second = asyncio.create_task(sock.send(b"B"))
362 await asyncio.sleep(0) # the second send parks on the held lock
363 sock.close() # tear down while the second send is waiting
364 release.set()
365 await first # the first send already passed the closed check
366 with pytest.raises(BleakError, match="closed"):
367 await second
368
369
370 async def test_send_error_tears_down_channel(
371 pair: tuple[socket.socket, socket.socket],
372 ) -> None:
373 """A write-side socket error closes the channel and notifies on_close once."""
374 left, _right = pair
375 closed: list[Exception | None] = []
376 sock = await _connect(left, on_data=lambda _d: None, on_close=closed.append)
377 boom = OSError("epipe")
378
379 async def fake_sendall(_sock: socket.socket, _data: bytes) -> None:
380 raise boom
381
382 with (
383 patch.object(sock._loop, "sock_sendall", fake_sendall),
384 pytest.raises(OSError, match="epipe"),
385 ):
386 await sock.send(b"A")
387 assert sock._closed is True
388 assert closed == [boom]
389
390
391 async def test_send_after_close_raises(
392 pair: tuple[socket.socket, socket.socket],
393 ) -> None:
394 """Writing to a closed channel raises rather than touching the socket."""
395 left, _right = pair
396 sock = await _connect(left, on_data=lambda _d: None, on_close=lambda _e: None)
397 sock.close()
398 with pytest.raises(BleakError, match="closed"):
399 await sock.send(b"\x02\x17\x00")
400
401
402 async def test_peer_disconnect_reports_close_once(
403 pair: tuple[socket.socket, socket.socket],
404 ) -> None:
405 """A peer hangup is reported to on_close exactly once with no error."""
406 left, right = pair
407 closed: list[Exception | None] = []
408 hung_up = asyncio.Event()
409
410 def on_close(exc: Exception | None) -> None:
411 closed.append(exc)
412 hung_up.set()
413
414 sock = await _connect(left, on_data=lambda _d: None, on_close=on_close)
415 right.close()
416 await hung_up.wait()
417 assert closed == [None]
418 assert sock._closed is True
419
420
421 async def test_read_ready_ignores_would_block(
422 pair: tuple[socket.socket, socket.socket],
423 ) -> None:
424 """A spurious wakeup with no data is a no-op, not a disconnect."""
425 left, _right = pair
426 received: list[bytes] = []
427 closed: list[Exception | None] = []
428 sock = await _connect(left, on_data=received.append, on_close=closed.append)
429 sock._sock = Mock(recv=Mock(side_effect=BlockingIOError))
430 sock._read_ready()
431 assert received == []
432 assert closed == []
433 assert sock._closed is False
434
435
436 async def test_read_ready_reports_socket_error(
437 pair: tuple[socket.socket, socket.socket],
438 ) -> None:
439 """A read error tears the channel down and reports the exception once."""
440 left, _right = pair
441 closed: list[Exception | None] = []
442 sock = await _connect(left, on_data=lambda _d: None, on_close=closed.append)
443 fd = sock._sock.fileno()
444 boom = OSError("boom")
445 sock._sock = Mock(recv=Mock(side_effect=boom), fileno=Mock(return_value=fd))
446 sock._read_ready()
447 assert closed == [boom]
448 assert sock._closed is True
449
450
451 async def test_close_is_idempotent(
452 pair: tuple[socket.socket, socket.socket],
453 ) -> None:
454 """Closing twice is safe and does not double-report."""
455 left, _right = pair
456 closed: list[Exception | None] = []
457 sock = await _connect(left, on_data=lambda _d: None, on_close=closed.append)
458 sock.close()
459 sock.close()
460 # A subsequent failure does not call on_close again.
461 sock._fail(None)
462 assert closed == []
463
464
465 async def test_set_result_if_pending_is_idempotent() -> None:
466 """Resolving an already-finished future is a no-op."""
467 loop = asyncio.get_running_loop()
468 fut: asyncio.Future[None] = loop.create_future()
469 _set_result_if_pending(fut)
470 _set_result_if_pending(fut)
471 assert fut.result() is None
472
473
474 async def test_can_use_l2cap_true_when_socket_opens() -> None:
475 """can_use_l2cap returns True when an L2CAP socket can be created."""
476 sock = Mock()
477 with patch("socket.socket", return_value=sock) as make_socket:
478 assert can_use_l2cap() is True
479 make_socket.assert_called_once()
480 sock.close.assert_called_once()
481
482
483 async def test_can_use_l2cap_false_without_permission() -> None:
484 """can_use_l2cap returns False when the socket cannot be opened."""
485 with patch("socket.socket", side_effect=PermissionError):
486 assert can_use_l2cap() is False