Debian Codegraph @

airos/discovery.py

raw
1 """Discover Ubiquiti UISP airOS device broadcasts."""
2
3 import asyncio
4 from collections.abc import Callable
5 import logging
6 import socket
7 import struct
8 from typing import Any
9
10 from .exceptions import AirOSDiscoveryError, AirOSEndpointError, AirOSListenerError
11
12 _LOGGER = logging.getLogger(__name__)
13
14 DISCOVERY_PORT: int = 10002
15 BUFFER_SIZE: int = 1024
16
17
18 class AirOSDiscoveryProtocol(asyncio.DatagramProtocol):
19 """A UDP protocol implementation for discovering Ubiquiti airOS devices.
20
21 This class listens for UDP broadcast announcements from airOS devices
22 on a specific port (10002) and parses the proprietary packet format
23 to extract device information. It acts as the low-level listener.
24
25 Attributes:
26 callback: An asynchronous callable that will be invoked with
27 the parsed device information upon discovery.
28 transport: The UDP transport layer object, set once the connection is made.
29
30 """
31
32 def __init__(self, callback: Callable[[dict[str, Any]], Any]) -> None:
33 """Initialize AirOSDiscoveryProtocol.
34
35 Args:
36 callback: An asynchronous function to call when a device is discovered.
37 It should accept a dictionary containing device information.
38
39 """
40 self.callback = callback
41 self.transport: asyncio.DatagramTransport | None = None
42
43 def connection_made(self, transport: asyncio.BaseTransport) -> None:
44 """Set up the UDP socket for broadcasting and reusing the address."""
45 self.transport = transport # type: ignore[assignment] # transport is DatagramTransport
46 sock: socket.socket = transport.get_extra_info("socket")
47 sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
48 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
49 log = f"AirOS discovery listener (low-level) started on UDP port {DISCOVERY_PORT}."
50 _LOGGER.debug(log)
51
52 def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
53 """Parse the received UDP packet and, if successful, schedules the callback.
54
55 Errors during parsing are logged internally by parse_airos_packet.
56 """
57 host_ip: str = addr[0]
58 try:
59 parsed_data: dict[str, Any] | None = self.parse_airos_packet(data, host_ip)
60 if parsed_data:
61 # Schedule the user-provided callback, don't await to keep listener responsive
62 asyncio.create_task(self.callback(parsed_data)) # noqa: RUF006
63 except (AirOSEndpointError, AirOSListenerError) as err:
64 # These are expected types of malformed packets. Log the specific error
65 # and then re-raise as AirOSDiscoveryError.
66 log = f"Parsing failed for packet from {host_ip}: {err}"
67 _LOGGER.exception(log)
68 raise AirOSDiscoveryError(f"Malformed packet from {host_ip}") from err
69 except Exception as err:
70 # General error during datagram reception (e.g., in callback itself)
71 log = f"Error processing AirOS discovery packet from {host_ip}. Data hex: {data.hex()}"
72 _LOGGER.exception(log)
73 raise AirOSDiscoveryError from err
74
75 def error_received(self, exc: Exception | None) -> None:
76 """Handle send or receive operation raises an OSError."""
77 if exc:
78 log = f"UDP error received in AirOSDiscoveryProtocol: {exc}"
79 _LOGGER.error(log)
80
81 def connection_lost(self, exc: Exception | None) -> None:
82 """Handle connection is lost or closed."""
83 _LOGGER.debug("AirOSDiscoveryProtocol connection lost.")
84 if exc:
85 _LOGGER.exception("AirOSDiscoveryProtocol connection lost due to")
86 raise AirOSDiscoveryError from None
87
88 def parse_airos_packet(self, data: bytes, host_ip: str) -> dict[str, Any] | None:
89 """Parse a raw airOS discovery UDP packet.
90
91 This method extracts various pieces of information from the proprietary
92 Ubiquiti airOS discovery packet format, which includes a fixed header
93 followed by a series of Type-Length-Value (TLV) entries. Different
94 TLV types use different length encoding schemes (fixed, 1-byte, 2-byte).
95
96 Args:
97 data: The raw byte data of the UDP packet payload.
98 host_ip: The IP address of the sender, used as a fallback or initial IP.
99
100 Returns:
101 A dictionary containing parsed device information if successful,
102 otherwise None. Values will be None if not found or cannot be parsed.
103
104 """
105 parsed_info: dict[str, str | int | None] = {
106 "ip_address": host_ip,
107 "mac_address": None,
108 "hostname": None,
109 "model": None,
110 "firmware_version": None,
111 "uptime_seconds": None,
112 "ssid": None,
113 "full_model_name": None,
114 }
115
116 # --- Fixed Header (6 bytes) ---
117 if len(data) < 6:
118 log = f"Packet too short for initial fixed header. Length: {len(data)}. Data: {data.hex()}"
119 _LOGGER.debug(log)
120 raise AirOSEndpointError(f"Malformed packet: {log}")
121
122 if data[0] != 0x01 or data[1] != 0x06:
123 log = f"Packet does not start with expected AirOS header (0x01 0x06). Actual: {data[0:2].hex()}"
124 _LOGGER.debug(log)
125 raise AirOSEndpointError(f"Malformed packet: {log}")
126
127 offset: int = 6
128
129 # --- Main TLV Parsing Loop ---
130 try:
131 while offset < len(data):
132 if (len(data) - offset) < 1:
133 log = f"Not enough bytes for next TLV type. Remaining: {data[offset:].hex()}"
134 _LOGGER.debug(log)
135 break
136
137 tlv_type: int = data[offset]
138 offset += 1
139
140 if tlv_type == 0x06: # Device MAC Address (fixed 6-byte value)
141 expected_length: int = 6
142 if (len(data) - offset) >= expected_length:
143 mac_bytes: bytes = data[offset : offset + expected_length]
144 parsed_info["mac_address"] = ":".join(
145 f"{b:02x}" for b in mac_bytes
146 ).upper()
147 offset += expected_length
148 log = f"Parsed MAC from type 0x06: {parsed_info['mac_address']}"
149 _LOGGER.debug(log)
150 else:
151 log = f"Truncated MAC address TLV (Type 0x06). Expected {expected_length}, got {len(data) - offset} bytes. Remaining: {data[offset:].hex()}"
152 _LOGGER.warning(log)
153 log = f"Malformed packet: {log}"
154 raise AirOSEndpointError(log) from None # noqa: TRY301
155
156 elif tlv_type in [
157 0x02,
158 0x03,
159 0x0A,
160 0x0B,
161 0x0C,
162 0x0D,
163 0x0E,
164 0x10,
165 0x14,
166 0x18,
167 ]:
168 if (len(data) - offset) < 2:
169 log = f"Truncated TLV (Type {tlv_type:#x}), no 2-byte length field. Remaining: {data[offset:].hex()}"
170 _LOGGER.warning(log)
171 log = f"Malformed packet: {log}"
172 raise AirOSEndpointError(log) from None # noqa: TRY301
173
174 tlv_length: int = struct.unpack_from(">H", data, offset)[0]
175 offset += 2
176
177 if tlv_length > (len(data) - offset):
178 log = (
179 f"TLV type {tlv_type:#x} length {tlv_length} exceeds remaining data "
180 f"({len(data) - offset} bytes left). Packet malformed. "
181 f"Data from TLV start: {data[offset - 3 :].hex()}"
182 )
183 _LOGGER.warning(log)
184 raise AirOSEndpointError(f"Malformed packet: {log}") from None # noqa: TRY301
185
186 tlv_value: bytes = data[offset : offset + tlv_length]
187
188 if tlv_type == 0x02:
189 if tlv_length == 10:
190 ip_bytes: bytes = tlv_value[6:10]
191 parsed_info["ip_address"] = ".".join(map(str, ip_bytes))
192 log = f"Parsed IP from type 0x02 block: {parsed_info['ip_address']}"
193 _LOGGER.debug(log)
194 else:
195 log = f"Unexpected length for 0x02 TLV (MAC+IP). Expected 10, got {tlv_length}. Value: {tlv_value.hex()}"
196 _LOGGER.warning(log)
197 raise AirOSEndpointError( # noqa: TRY301
198 f"Malformed packet: {log}"
199 ) from None
200
201 elif tlv_type == 0x03:
202 parsed_info["firmware_version"] = tlv_value.decode(
203 "ascii", errors="ignore"
204 )
205 log = f"Parsed Firmware: {parsed_info['firmware_version']}"
206 _LOGGER.debug(log)
207
208 elif tlv_type == 0x0A:
209 if tlv_length == 4:
210 parsed_info["uptime_seconds"] = struct.unpack(
211 ">I", tlv_value
212 )[0]
213 log = f"Parsed Uptime: {parsed_info['uptime_seconds']}s"
214 _LOGGER.debug(log)
215 else:
216 log = f"Unexpected length for Uptime (Type 0x0A): {tlv_length}. Value: {tlv_value.hex()}"
217 _LOGGER.warning(log)
218 raise AirOSEndpointError( # noqa: TRY301
219 f"Malformed packet: {log}"
220 ) from None
221
222 elif tlv_type == 0x0B:
223 parsed_info["hostname"] = tlv_value.decode(
224 "utf-8", errors="ignore"
225 )
226 log = f"Parsed Hostname: {parsed_info['hostname']}"
227 _LOGGER.debug(log)
228
229 elif tlv_type == 0x0C:
230 parsed_info["model"] = tlv_value.decode(
231 "ascii", errors="ignore"
232 )
233 log = f"Parsed Model: {parsed_info['model']}"
234 _LOGGER.debug(log)
235
236 elif tlv_type == 0x0D:
237 parsed_info["ssid"] = tlv_value.decode("utf-8", errors="ignore")
238 log = f"Parsed SSID: {parsed_info['ssid']}"
239 _LOGGER.debug(log)
240
241 elif tlv_type == 0x14:
242 parsed_info["full_model_name"] = tlv_value.decode(
243 "utf-8", errors="ignore"
244 )
245 log = (
246 f"Parsed Full Model Name: {parsed_info['full_model_name']}"
247 )
248 _LOGGER.debug(log)
249
250 elif tlv_type == 0x18:
251 if tlv_length == 4 and tlv_value == b"\x00\x00\x00\x00":
252 _LOGGER.debug("Detected end marker (Type 0x18).")
253 else:
254 log = f"Unhandled TLV type: {tlv_type:#x} with length {tlv_length}. Value: {tlv_value.hex()}"
255 _LOGGER.debug(log)
256 elif tlv_type in [0x0E, 0x10]:
257 log = f"Unhandled TLV type: {tlv_type:#x} with length {tlv_length}. Value: {tlv_value.hex()}"
258 _LOGGER.debug(log)
259
260 offset += tlv_length
261
262 else:
263 log = f"Unhandled TLV type: {tlv_type:#x} at offset {offset - 1}. "
264 log += f"Cannot determine length, stopping parsing. Remaining: {data[offset - 1 :].hex()}"
265 _LOGGER.warning(log)
266 log = f"Malformed packet: {log}"
267 raise AirOSEndpointError(log) from None # noqa: TRY301
268
269 except (struct.error, IndexError) as err:
270 log = f"Parsing error (struct/index) in AirOSDiscoveryProtocol: {err} at offset {offset}. Remaining data: {data[offset:].hex()}"
271 _LOGGER.debug(log)
272 log = f"Malformed packet: {log}"
273 raise AirOSEndpointError(log) from err
274 except AirOSEndpointError: # Catch AirOSEndpointError specifically, re-raise it
275 raise
276 except Exception as err:
277 _LOGGER.exception("Unexpected error during AirOS packet parsing")
278 raise AirOSListenerError from err
279
280 return parsed_info
281
282
283 async def airos_discover_devices(
284 timeout: int = 30, listen_ip: str = "0.0.0.0", port: int = DISCOVERY_PORT
285 ) -> dict[str, dict[str, Any]]:
286 """Discover unconfigured airOS devices on the network for a given timeout.
287
288 This function sets up a listener, waits for a period, and returns
289 all discovered devices.
290 """
291 _LOGGER.debug("Starting AirOS device discovery for %s seconds", timeout)
292 discovered_devices: dict[str, dict[str, Any]] = {}
293
294 async def _async_airos_device_found(device_info: dict[str, Any]) -> None:
295 """Handle discovered device."""
296 mac_address = device_info.get("mac_address")
297 if mac_address:
298 discovered_devices[mac_address] = device_info
299 _LOGGER.debug(
300 "Discovered device: %s", device_info.get("hostname", mac_address)
301 )
302
303 transport: asyncio.DatagramTransport | None = None
304 try:
305 (
306 transport,
307 protocol,
308 ) = await asyncio.get_running_loop().create_datagram_endpoint(
309 lambda: AirOSDiscoveryProtocol(_async_airos_device_found),
310 local_addr=(listen_ip, port),
311 )
312 try:
313 await asyncio.sleep(timeout)
314 finally:
315 if transport:
316 _LOGGER.debug("Closing AirOS discovery listener")
317 transport.close()
318 except OSError as err:
319 if err.errno == 98:
320 _LOGGER.error("Address in use, another instance may be running.")
321 raise AirOSEndpointError("address_in_use") from err
322 _LOGGER.exception("Network endpoint error during discovery")
323 raise AirOSEndpointError("cannot_connect") from err
324 except asyncio.CancelledError as err:
325 _LOGGER.warning("Discovery listener cancelled: %s", err)
326 raise AirOSListenerError("cannot_connect") from err
327 except Exception as err:
328 _LOGGER.exception("An unexpected error occurred during discovery")
329 raise AirOSListenerError("cannot_connect") from err
330
331 return discovered_devices