python-pylan 0.0.2__py3-none-any.whl → 0.0.3__py3-none-any.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.
- pylan/__init__.py +17 -2
- pylan/__main__.py +29 -0
- pylan/cli/__init__.py +25 -0
- pylan/cli/cli.py +36 -0
- pylan/cli/receive.py +201 -0
- pylan/cli/scan.py +103 -0
- pylan/cli/send.py +106 -0
- pylan/client/__init__.py +14 -0
- pylan/core/__init__.py +103 -0
- pylan/core/discovery.py +475 -0
- pylan/core/handshake.py +145 -0
- pylan/core/models.py +77 -0
- pylan/core/net.py +88 -0
- pylan/core/protocol.py +132 -0
- pylan/core/transfer.py +420 -0
- pylan/errors/__init__.py +28 -0
- pylan/errors/base.py +13 -0
- pylan/main.py +6 -0
- pylan/ui/__init__.py +21 -0
- pylan/ui/app.py +188 -0
- pylan/ui/assets/icon.ico +0 -0
- pylan/ui/assets/icon.png +0 -0
- pylan/ui/assets/logo.svg +51 -0
- pylan/ui/components/__init__.py +14 -0
- pylan/ui/components/file_picker.py +243 -0
- pylan/ui/components/navbar.py +250 -0
- pylan/ui/components/peer_tile.py +152 -0
- pylan/ui/components/transfer_row.py +224 -0
- pylan/ui/state.py +823 -0
- pylan/ui/views/__init__.py +13 -0
- pylan/ui/views/home_view.py +245 -0
- pylan/ui/views/receive_view.py +249 -0
- pylan/ui/views/send_view.py +200 -0
- pylan/ui/views/settings_view.py +233 -0
- pylan/utils/utils.py +21 -0
- {python_pylan-0.0.2.dist-info → python_pylan-0.0.3.dist-info}/METADATA +13 -3
- python_pylan-0.0.3.dist-info/RECORD +39 -0
- {python_pylan-0.0.2.dist-info → python_pylan-0.0.3.dist-info}/WHEEL +1 -1
- python_pylan-0.0.3.dist-info/entry_points.txt +2 -0
- python_pylan-0.0.2.dist-info/RECORD +0 -4
pylan/core/discovery.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
1
|
+
"""Discover peers on a local network through multicast and TCP probes.
|
|
2
|
+
|
|
3
|
+
The module provides an asyncio-based discovery protocol and engine. Peers
|
|
4
|
+
announce themselves over UDP multicast; the engine can also actively probe
|
|
5
|
+
known TCP endpoints and sweep local IPv4 /24 networks when multicast and
|
|
6
|
+
known endpoints do not reveal any devices. Successful probes are normalized
|
|
7
|
+
into :class:`DiscoveredDevice` records and stored in a :class:`DeviceStore`.
|
|
8
|
+
|
|
9
|
+
The discovery engine does not own a long-running listener lifecycle. Callers
|
|
10
|
+
are responsible for closing the transport returned by
|
|
11
|
+
:meth:`DiscoveryEngine.start_multicast_listener`.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import ipaddress
|
|
16
|
+
import json
|
|
17
|
+
import logging
|
|
18
|
+
import socket
|
|
19
|
+
from typing import Callable, Optional
|
|
20
|
+
|
|
21
|
+
from pylan.core.models import (
|
|
22
|
+
DeviceStore,
|
|
23
|
+
DiscoveredDevice,
|
|
24
|
+
HttpChannel,
|
|
25
|
+
ProtocolType,
|
|
26
|
+
StatefulDevice,
|
|
27
|
+
)
|
|
28
|
+
from pylan.core.protocol import pack_message, read_frame
|
|
29
|
+
from pylan.core.net import get_active_interface_details, get_arp_neighbors
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
DEFAULT_MULTICAST_GROUP = "224.0.0.167"
|
|
34
|
+
DEFAULT_MULTICAST_PORT = 53317
|
|
35
|
+
DEFAULT_DISCOVERY_TIMEOUT = 0.5
|
|
36
|
+
SCAN_CONCURRENCY = 50
|
|
37
|
+
|
|
38
|
+
MSG_TYPE_ANNOUNCE = 10
|
|
39
|
+
MSG_TYPE_PROBE_REQUEST = 11
|
|
40
|
+
MSG_TYPE_PROBE_RESPONSE = 12
|
|
41
|
+
|
|
42
|
+
MAX_SEQUENTIAL_SWEEP_HOSTS = 512
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class DiscoveryProtocol(asyncio.DatagramProtocol):
|
|
46
|
+
"""Asyncio datagram protocol for handling incoming UDP multicast frames.
|
|
47
|
+
|
|
48
|
+
Decodes inbound datagram payloads as UTF-8 JSON and dispatches successfully
|
|
49
|
+
decoded values to the registered callback. Malformed payloads and callback
|
|
50
|
+
errors are logged at debug level and do not escape the event-loop callback.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self, on_message: Callable[[dict, tuple[str, int]], None]
|
|
55
|
+
) -> None:
|
|
56
|
+
"""Initialize the datagram protocol handler.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
on_message: Callback function executed when a valid JSON datagram
|
|
60
|
+
is parsed. Receives the decoded payload dictionary and the
|
|
61
|
+
source (host, port) tuple.
|
|
62
|
+
"""
|
|
63
|
+
self.on_message = on_message
|
|
64
|
+
self.transport: Optional[asyncio.BaseTransport] = None
|
|
65
|
+
|
|
66
|
+
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
|
67
|
+
"""Invoked when the underlying datagram endpoint socket is established.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
transport: The initialized datagram transport instance.
|
|
71
|
+
"""
|
|
72
|
+
self.transport = transport
|
|
73
|
+
|
|
74
|
+
def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
|
|
75
|
+
"""Process an incoming raw UDP datagram.
|
|
76
|
+
|
|
77
|
+
Attempts to decode the packet as a UTF-8 encoded JSON object.
|
|
78
|
+
Malformed packets and callback errors are suppressed and logged at
|
|
79
|
+
debug severity.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
data: Raw packet bytes received from the network socket.
|
|
83
|
+
addr: Source network address represented as a (host, port) tuple.
|
|
84
|
+
"""
|
|
85
|
+
try:
|
|
86
|
+
payload = json.loads(data.decode("utf-8"))
|
|
87
|
+
self.on_message(payload, addr)
|
|
88
|
+
except Exception as e:
|
|
89
|
+
logger.debug(
|
|
90
|
+
"Failed to decode multicast packet from %s: %s", addr, e
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class DiscoveryEngine:
|
|
95
|
+
"""Orchestrates network peer discovery, registration, and health sweeps.
|
|
96
|
+
|
|
97
|
+
Provides high-level coordination between multicast broadcasting, inbound
|
|
98
|
+
datagram listening, framed TCP probing handshakes, and parallel subnet
|
|
99
|
+
port sweeps. Each engine owns an in-memory :class:`DeviceStore`; repeated
|
|
100
|
+
discoveries of the same fingerprint update that record rather than
|
|
101
|
+
creating another device.
|
|
102
|
+
The engine starts without an active multicast listener or subnet scan.
|
|
103
|
+
A caller may start the listener separately and close its returned
|
|
104
|
+
transport when discovery is no longer needed.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
alias: str,
|
|
110
|
+
fingerprint: str,
|
|
111
|
+
tcp_port: int,
|
|
112
|
+
device_type: str = "desktop",
|
|
113
|
+
device_model: Optional[str] = None,
|
|
114
|
+
multicast_group: str = DEFAULT_MULTICAST_GROUP,
|
|
115
|
+
multicast_port: int = DEFAULT_MULTICAST_PORT,
|
|
116
|
+
timeout: float = DEFAULT_DISCOVERY_TIMEOUT,
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Initialize the discovery engine with local identity and network
|
|
119
|
+
parameters.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
alias: Human-readable display name of this node.
|
|
123
|
+
fingerprint: Unique persistent identifier for this host instance.
|
|
124
|
+
tcp_port: Port where the local TCP framing service listens.
|
|
125
|
+
device_type: Form factor category (e.g., 'desktop', 'mobile').
|
|
126
|
+
device_model: Hardware or platform model identifier.
|
|
127
|
+
multicast_group: IPv4 multicast address used for group
|
|
128
|
+
announcements.
|
|
129
|
+
multicast_port: UDP port assigned for multicast traffic.
|
|
130
|
+
timeout: Network socket timeout in seconds for handshake
|
|
131
|
+
operations.
|
|
132
|
+
"""
|
|
133
|
+
self.alias = alias
|
|
134
|
+
self.fingerprint = fingerprint
|
|
135
|
+
self.tcp_port = tcp_port
|
|
136
|
+
self.device_type = device_type
|
|
137
|
+
self.device_model = device_model
|
|
138
|
+
self.multicast_group = multicast_group
|
|
139
|
+
self.multicast_port = multicast_port
|
|
140
|
+
self.timeout = timeout
|
|
141
|
+
|
|
142
|
+
self.store = DeviceStore()
|
|
143
|
+
self.is_scanning = False
|
|
144
|
+
self._active_subnet_scans: set[str] = set()
|
|
145
|
+
|
|
146
|
+
def get_announcement_payload(self) -> dict:
|
|
147
|
+
"""Build this node's discovery metadata.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
A JSON-serializable dictionary containing the node alias,
|
|
151
|
+
software version, optional model, device type, persistent
|
|
152
|
+
fingerprint, TCP service port, protocol identifier, and download
|
|
153
|
+
capability. The same payload is used in multicast announcements
|
|
154
|
+
and framed TCP probe requests.
|
|
155
|
+
"""
|
|
156
|
+
return {
|
|
157
|
+
"alias": self.alias,
|
|
158
|
+
"version": "0.0.3",
|
|
159
|
+
"device_model": self.device_model,
|
|
160
|
+
"device_type": self.device_type,
|
|
161
|
+
"fingerprint": self.fingerprint,
|
|
162
|
+
"port": self.tcp_port,
|
|
163
|
+
"protocol": ProtocolType.TCP.value,
|
|
164
|
+
"download": True,
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async def start_multicast_listener(
|
|
168
|
+
self,
|
|
169
|
+
) -> Optional[asyncio.DatagramTransport]:
|
|
170
|
+
"""Configure and bind an asynchronous UDP multicast receiver socket.
|
|
171
|
+
|
|
172
|
+
Configures address/port reuse flags, binds to the configured UDP port,
|
|
173
|
+
joins the specified multicast IGMP group on the default interface,
|
|
174
|
+
and registers an asyncio datagram endpoint. A configuration, bind,
|
|
175
|
+
membership, or endpoint-creation failure is logged and selects
|
|
176
|
+
fallback discovery by returning ``None``.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
The active DatagramTransport if binding succeeds; None if socket
|
|
180
|
+
configuration or membership join fails.
|
|
181
|
+
"""
|
|
182
|
+
loop = asyncio.get_running_loop()
|
|
183
|
+
sock = socket.socket(
|
|
184
|
+
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP
|
|
185
|
+
)
|
|
186
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
187
|
+
|
|
188
|
+
try:
|
|
189
|
+
if hasattr(socket, "SO_REUSEPORT"):
|
|
190
|
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
|
191
|
+
sock.bind(("", self.multicast_port))
|
|
192
|
+
|
|
193
|
+
mreq = socket.inet_aton(self.multicast_group) + socket.inet_aton(
|
|
194
|
+
"0.0.0.0"
|
|
195
|
+
)
|
|
196
|
+
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
|
|
197
|
+
sock.setblocking(False)
|
|
198
|
+
|
|
199
|
+
transport, _ = await loop.create_datagram_endpoint(
|
|
200
|
+
lambda: DiscoveryProtocol(self._on_multicast_received),
|
|
201
|
+
sock=sock,
|
|
202
|
+
)
|
|
203
|
+
logger.info(
|
|
204
|
+
"Multicast listener active on %s:%d",
|
|
205
|
+
self.multicast_group,
|
|
206
|
+
self.multicast_port,
|
|
207
|
+
)
|
|
208
|
+
return transport
|
|
209
|
+
except Exception as e:
|
|
210
|
+
logger.info(
|
|
211
|
+
"Could not bind multicast socket (%s). "
|
|
212
|
+
"Continuing in fallback mode.",
|
|
213
|
+
e,
|
|
214
|
+
)
|
|
215
|
+
return None
|
|
216
|
+
|
|
217
|
+
def _on_multicast_received(
|
|
218
|
+
self,
|
|
219
|
+
data: dict,
|
|
220
|
+
addr: tuple[str, int],
|
|
221
|
+
) -> None:
|
|
222
|
+
"""Handle incoming multicast discovery packets from peer devices.
|
|
223
|
+
|
|
224
|
+
Filters out announcements without a fingerprint and this engine's own
|
|
225
|
+
fingerprint. For other peers, it schedules a direct TCP probe to the
|
|
226
|
+
packet's source host and advertised port; if the packet omits a port,
|
|
227
|
+
this engine's local TCP port is used.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
data: Decoded JSON dictionary transmitted by the peer.
|
|
231
|
+
addr: Source address tuple containing (ip_address,
|
|
232
|
+
ephemeral_port).
|
|
233
|
+
"""
|
|
234
|
+
peer_fp = data.get("fingerprint")
|
|
235
|
+
if not peer_fp or peer_fp == self.fingerprint:
|
|
236
|
+
return
|
|
237
|
+
|
|
238
|
+
peer_host = addr[0]
|
|
239
|
+
peer_port = data.get("port", self.tcp_port)
|
|
240
|
+
asyncio.create_task(self.probe(peer_host, peer_port))
|
|
241
|
+
|
|
242
|
+
async def announce(self) -> None:
|
|
243
|
+
"""Transmit a UDP multicast announcement datagram to the local subnet.
|
|
244
|
+
|
|
245
|
+
Serializes :meth:`get_announcement_payload` as UTF-8 JSON and sends it
|
|
246
|
+
using a transient IPv4 UDP socket with multicast TTL 2. The socket is
|
|
247
|
+
always closed after the send attempt. Socket errors are allowed to
|
|
248
|
+
propagate to the caller.
|
|
249
|
+
"""
|
|
250
|
+
payload = json.dumps(self.get_announcement_payload()).encode("utf-8")
|
|
251
|
+
sock = socket.socket(
|
|
252
|
+
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP
|
|
253
|
+
)
|
|
254
|
+
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
|
|
255
|
+
try:
|
|
256
|
+
sock.sendto(payload, (self.multicast_group, self.multicast_port))
|
|
257
|
+
finally:
|
|
258
|
+
sock.close()
|
|
259
|
+
|
|
260
|
+
async def probe(self, host: str, port: int) -> Optional[StatefulDevice]:
|
|
261
|
+
"""Perform a framed TCP discovery handshake with a network endpoint.
|
|
262
|
+
|
|
263
|
+
Connects over TCP, sends an envelope-wrapped registration request,
|
|
264
|
+
reads the fixed-length protocol header and declared response body,
|
|
265
|
+
then parses the body as JSON. Responses without a fingerprint or
|
|
266
|
+
matching this engine's fingerprint are ignored. Valid peers are
|
|
267
|
+
upserted by fingerprint, allowing their metadata and channels to be
|
|
268
|
+
refreshed.
|
|
269
|
+
|
|
270
|
+
Args:
|
|
271
|
+
host: Destination IPv4 or hostname string.
|
|
272
|
+
port: Destination TCP service port.
|
|
273
|
+
|
|
274
|
+
Returns:
|
|
275
|
+
The upserted ``StatefulDevice`` when the response identifies a
|
|
276
|
+
peer; otherwise ``None`` when connection establishment fails,
|
|
277
|
+
the response cannot be read or decoded, or the response identifies
|
|
278
|
+
this engine itself.
|
|
279
|
+
"""
|
|
280
|
+
try:
|
|
281
|
+
reader, writer = await asyncio.wait_for(
|
|
282
|
+
asyncio.open_connection(host, port),
|
|
283
|
+
timeout=self.timeout,
|
|
284
|
+
)
|
|
285
|
+
except (OSError, asyncio.TimeoutError):
|
|
286
|
+
return None
|
|
287
|
+
|
|
288
|
+
try:
|
|
289
|
+
request_data = pack_message(
|
|
290
|
+
MSG_TYPE_PROBE_REQUEST, self.get_announcement_payload()
|
|
291
|
+
)
|
|
292
|
+
writer.write(request_data)
|
|
293
|
+
await writer.drain()
|
|
294
|
+
|
|
295
|
+
_, body_bytes = await read_frame(reader, timeout=self.timeout)
|
|
296
|
+
response = json.loads(body_bytes.decode("utf-8"))
|
|
297
|
+
|
|
298
|
+
peer_fp = response.get("fingerprint")
|
|
299
|
+
if not peer_fp or peer_fp == self.fingerprint:
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
device = DiscoveredDevice(
|
|
303
|
+
alias=response.get("alias", "Unknown"),
|
|
304
|
+
version=response.get("version", "0.0.1"),
|
|
305
|
+
device_model=response.get("device_model"),
|
|
306
|
+
device_type=response.get("device_type", "desktop"),
|
|
307
|
+
fingerprint=peer_fp,
|
|
308
|
+
channel=HttpChannel(
|
|
309
|
+
host=host, port=port, protocol=ProtocolType.TCP
|
|
310
|
+
),
|
|
311
|
+
download=response.get("download", True),
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
is_new, stateful = self.store.upsert(device)
|
|
315
|
+
logger.info(
|
|
316
|
+
"Discovered device: %s at %s:%d (New: %s)",
|
|
317
|
+
device.alias,
|
|
318
|
+
host,
|
|
319
|
+
port,
|
|
320
|
+
is_new,
|
|
321
|
+
)
|
|
322
|
+
return stateful
|
|
323
|
+
except Exception as e:
|
|
324
|
+
logger.debug(
|
|
325
|
+
"Failed probe handshake with %s:%d: %s", host, port, e
|
|
326
|
+
)
|
|
327
|
+
return None
|
|
328
|
+
finally:
|
|
329
|
+
writer.close()
|
|
330
|
+
await writer.wait_closed()
|
|
331
|
+
|
|
332
|
+
async def scan_subnet(
|
|
333
|
+
self,
|
|
334
|
+
interface_ip: str,
|
|
335
|
+
port: Optional[int] = None,
|
|
336
|
+
netmask: Optional[str] = None,
|
|
337
|
+
) -> list[StatefulDevice]:
|
|
338
|
+
"""Perform a concurrent probe sweep across an entire /24 IPv4 subnet.
|
|
339
|
+
|
|
340
|
+
Calculates host addresses within the interface's /24 block and
|
|
341
|
+
dispatches TCP probe attempts throttled by an asynchronous semaphore
|
|
342
|
+
capped at :data:`SCAN_CONCURRENCY`. The interface's own address is
|
|
343
|
+
skipped. Concurrent scans for the same interface are ignored, while
|
|
344
|
+
scans on different interfaces can proceed independently.
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
interface_ip: Local IPv4 address identifying the subnet to scan.
|
|
348
|
+
port: Destination TCP port for all probes. If omitted or falsey,
|
|
349
|
+
the engine's configured TCP port is used.
|
|
350
|
+
|
|
351
|
+
Returns:
|
|
352
|
+
Successfully discovered ``StatefulDevice`` instances in subnet
|
|
353
|
+
host order. Returns an empty list if a scan on the same interface
|
|
354
|
+
is already running.
|
|
355
|
+
|
|
356
|
+
Raises:
|
|
357
|
+
ValueError: If ``interface_ip`` cannot be used to construct an
|
|
358
|
+
IPv4 /24 network.
|
|
359
|
+
"""
|
|
360
|
+
target_port = port or self.tcp_port
|
|
361
|
+
network = ipaddress.ip_network(f"{interface_ip}/24", strict=False)
|
|
362
|
+
|
|
363
|
+
if interface_ip in self._active_subnet_scans:
|
|
364
|
+
return []
|
|
365
|
+
|
|
366
|
+
if not netmask:
|
|
367
|
+
detected_ip, detected_mask = get_active_interface_details()
|
|
368
|
+
netmask = (
|
|
369
|
+
detected_mask
|
|
370
|
+
if detected_ip == interface_ip
|
|
371
|
+
else "255.255.255.0"
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
try:
|
|
375
|
+
interface = ipaddress.ip_interface(f"{interface_ip}/{netmask}")
|
|
376
|
+
network = interface.network
|
|
377
|
+
except ValueError:
|
|
378
|
+
network = ipaddress.ip_network(f"{interface_ip}/24", strict=False)
|
|
379
|
+
|
|
380
|
+
arp_entries = get_arp_neighbors()
|
|
381
|
+
target_ips = {
|
|
382
|
+
ip_str for ip_str in arp_entries
|
|
383
|
+
if ipaddress.ip_address(ip_str) in network
|
|
384
|
+
and ip_str != interface_ip
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
total_hosts = network.num_addresses - 2
|
|
388
|
+
if total_hosts <= MAX_SEQUENTIAL_SWEEP_HOSTS:
|
|
389
|
+
for host in network.hosts():
|
|
390
|
+
ip_str = str(host)
|
|
391
|
+
if ip_str != interface_ip:
|
|
392
|
+
target_ips.add(ip_str)
|
|
393
|
+
else:
|
|
394
|
+
slice_mask = "255.255.254.0"
|
|
395
|
+
try:
|
|
396
|
+
local_slice = ipaddress.ip_interface(
|
|
397
|
+
f"{interface_ip}/{slice_mask}"
|
|
398
|
+
).network
|
|
399
|
+
for host in local_slice.hosts():
|
|
400
|
+
ip_str = str(host)
|
|
401
|
+
if ip_str != interface_ip and host in network:
|
|
402
|
+
target_ips.add(ip_str)
|
|
403
|
+
except ValueError:
|
|
404
|
+
pass
|
|
405
|
+
self._active_subnet_scans.add(interface_ip)
|
|
406
|
+
semaphore = asyncio.Semaphore(SCAN_CONCURRENCY)
|
|
407
|
+
|
|
408
|
+
async def _bounded_probe(ip_str: str) -> Optional[StatefulDevice]:
|
|
409
|
+
if ip_str == interface_ip:
|
|
410
|
+
return None
|
|
411
|
+
async with semaphore:
|
|
412
|
+
return await self.probe(ip_str, target_port)
|
|
413
|
+
|
|
414
|
+
try:
|
|
415
|
+
tasks = [_bounded_probe(str(ip)) for ip in sorted(target_ips)]
|
|
416
|
+
results = await asyncio.gather(*tasks)
|
|
417
|
+
return [d for d in results if d is not None]
|
|
418
|
+
finally:
|
|
419
|
+
self._active_subnet_scans.discard(interface_ip)
|
|
420
|
+
|
|
421
|
+
async def discover_staged(
|
|
422
|
+
self,
|
|
423
|
+
interface_ips: list[str],
|
|
424
|
+
known_channels: Optional[list[HttpChannel]] = None,
|
|
425
|
+
grace_period: float = 1.0,
|
|
426
|
+
) -> list[StatefulDevice]:
|
|
427
|
+
"""Execute a staged discovery pipeline with escalation fallbacks.
|
|
428
|
+
|
|
429
|
+
The discovery progression operates as follows:
|
|
430
|
+
1. Broadcasts an initial UDP multicast announcement.
|
|
431
|
+
2. Probes pre-existing or cached endpoint channels concurrently.
|
|
432
|
+
3. Sleeps for a grace period to collect passive responses.
|
|
433
|
+
4. If the device-store size has not changed since entry, runs a /24
|
|
434
|
+
scan for each supplied interface concurrently.
|
|
435
|
+
|
|
436
|
+
Args:
|
|
437
|
+
interface_ips: Local interface IPv4 addresses to scan if initial
|
|
438
|
+
discovery does not add any devices.
|
|
439
|
+
known_channels: Optional collection of previously discovered or
|
|
440
|
+
favorited communication channels to probe before subnet
|
|
441
|
+
sweeps.
|
|
442
|
+
grace_period: Time in seconds to wait for initial responses before
|
|
443
|
+
deciding whether to initiate subnet scans.
|
|
444
|
+
|
|
445
|
+
Returns:
|
|
446
|
+
A snapshot of all devices currently held by this engine's store.
|
|
447
|
+
|
|
448
|
+
Raises:
|
|
449
|
+
OSError: If sending the initial multicast announcement fails.
|
|
450
|
+
"""
|
|
451
|
+
known_channels = known_channels or []
|
|
452
|
+
count_before = len(self.store.all_devices())
|
|
453
|
+
|
|
454
|
+
transport = await self.start_multicast_listener()
|
|
455
|
+
try:
|
|
456
|
+
await self.announce()
|
|
457
|
+
probe_tasks = [
|
|
458
|
+
self.probe(ch.host, ch.port) for ch in known_channels
|
|
459
|
+
]
|
|
460
|
+
if probe_tasks:
|
|
461
|
+
await asyncio.gather(*probe_tasks)
|
|
462
|
+
|
|
463
|
+
await asyncio.sleep(grace_period)
|
|
464
|
+
|
|
465
|
+
if len(self.store.all_devices()) == count_before:
|
|
466
|
+
logger.info(
|
|
467
|
+
"No peers discovered via multicast/favorites. "
|
|
468
|
+
"Escalating to subnet sweep..."
|
|
469
|
+
)
|
|
470
|
+
scan_tasks = [self.scan_subnet(ip) for ip in interface_ips]
|
|
471
|
+
await asyncio.gather(*scan_tasks)
|
|
472
|
+
finally:
|
|
473
|
+
if transport:
|
|
474
|
+
transport.close()
|
|
475
|
+
return self.store.all_devices()
|
pylan/core/handshake.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Synchronous length-prefixed JSON handshake framing manager.
|
|
2
|
+
|
|
3
|
+
This module provides the :class:`HandshakeManager` for transmitting and
|
|
4
|
+
receiving length-prefixed JSON payloads over synchronous TCP sockets.
|
|
5
|
+
Messages are framed using a fixed 4-byte big-endian unsigned integer header
|
|
6
|
+
that specifies the length of the upcoming UTF-8 encoded JSON body.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import socket
|
|
11
|
+
import struct
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
DEFAULT_MAX_PAYLOAD_SIZE: int = 10 * 1024 * 1024 # 10 MB limit
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class HandshakeManager:
|
|
18
|
+
"""Manages synchronous JSON message exchanges over a stream socket.
|
|
19
|
+
|
|
20
|
+
Frames outgoing messages with a 4-byte big-endian length prefix and
|
|
21
|
+
reads framed responses from incoming socket streams with explicit buffer
|
|
22
|
+
bounds to prevent unbounded memory allocation from untrusted input.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
sock: The underlying connected stream socket.
|
|
26
|
+
max_payload_size: Maximum acceptable payload size in bytes.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
HEADER_STRUCT: str = ">I"
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
sock: socket.socket,
|
|
34
|
+
max_payload_size: int = DEFAULT_MAX_PAYLOAD_SIZE,
|
|
35
|
+
) -> None:
|
|
36
|
+
"""Initialize the handshake manager with an active socket.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
sock: A connected :class:`socket.socket` instance.
|
|
40
|
+
max_payload_size: Maximum incoming payload size in bytes.
|
|
41
|
+
Defaults to 10 MB.
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
ValueError: If `max_payload_size` is not positive.
|
|
45
|
+
"""
|
|
46
|
+
if max_payload_size <= 0:
|
|
47
|
+
raise ValueError("max_payload_size must be positive.")
|
|
48
|
+
self.sock = sock
|
|
49
|
+
self.max_payload_size = max_payload_size
|
|
50
|
+
|
|
51
|
+
def send_handshake(self, payload: dict[str, Any]) -> None:
|
|
52
|
+
"""Serialize and send a JSON payload with a length prefix.
|
|
53
|
+
|
|
54
|
+
Encodes the dictionary to UTF-8 JSON, prepends a 4-byte big-endian
|
|
55
|
+
length header, and transmits the entire frame via the socket.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
payload: A JSON-serializable dictionary to transmit.
|
|
59
|
+
|
|
60
|
+
Raises:
|
|
61
|
+
TypeError: If `payload` is not a dictionary.
|
|
62
|
+
OSError: If a network transmission error occurs.
|
|
63
|
+
"""
|
|
64
|
+
if not isinstance(payload, dict):
|
|
65
|
+
raise TypeError(
|
|
66
|
+
f"Payload must be a dict, got {type(payload).__name__}"
|
|
67
|
+
)
|
|
68
|
+
raw_data = json.dumps(payload).encode("utf-8")
|
|
69
|
+
header = struct.pack(self.HEADER_STRUCT, len(raw_data))
|
|
70
|
+
self.sock.sendall(header + raw_data)
|
|
71
|
+
|
|
72
|
+
def receive_handshake(self) -> dict[str, Any]:
|
|
73
|
+
"""Receive and decode a length-prefixed JSON payload.
|
|
74
|
+
|
|
75
|
+
Reads the exact 4-byte length prefix, verifies that the payload
|
|
76
|
+
size does not exceed `max_payload_size`, collects the declared byte
|
|
77
|
+
count, and deserializes the JSON body into a dictionary.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
The parsed JSON dictionary received from the remote peer.
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
ConnectionResetError: If the connection is closed prematurely.
|
|
84
|
+
ValueError: If the declared payload size is invalid, exceeds
|
|
85
|
+
`max_payload_size`, or the decoded JSON is not a dictionary.
|
|
86
|
+
UnicodeDecodeError: If payload bytes are not valid UTF-8.
|
|
87
|
+
json.JSONDecodeError: If payload bytes cannot be parsed as JSON.
|
|
88
|
+
OSError: If a network read error occurs.
|
|
89
|
+
"""
|
|
90
|
+
header_size = struct.calcsize(self.HEADER_STRUCT)
|
|
91
|
+
raw_length = self._recv_exact(header_size)
|
|
92
|
+
length = struct.unpack(self.HEADER_STRUCT, raw_length)[0]
|
|
93
|
+
|
|
94
|
+
if length <= 0:
|
|
95
|
+
raise ValueError("Handshake payload length must be positive.")
|
|
96
|
+
|
|
97
|
+
if length > self.max_payload_size:
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"Payload length {length} exceeds maximum allowed size "
|
|
100
|
+
f"({self.max_payload_size} bytes)."
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
raw_data = self._recv_exact(length)
|
|
104
|
+
parsed: Any = json.loads(raw_data.decode("utf-8"))
|
|
105
|
+
if not isinstance(parsed, dict):
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"Expected JSON object (dict), got {type(parsed).__name__}"
|
|
108
|
+
)
|
|
109
|
+
return parsed
|
|
110
|
+
|
|
111
|
+
def _recv_exact(self, num_bytes: int) -> bytes:
|
|
112
|
+
"""Read an exact number of bytes from the underlying socket.
|
|
113
|
+
|
|
114
|
+
Loops until all requested bytes are gathered in chunks or raises
|
|
115
|
+
an error if the peer terminates the connection before completion.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
num_bytes: The exact number of bytes to receive.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
A bytes object of exact length `num_bytes`.
|
|
122
|
+
|
|
123
|
+
Raises:
|
|
124
|
+
ValueError: If `num_bytes` is negative.
|
|
125
|
+
ConnectionResetError: If the socket closes before `num_bytes`
|
|
126
|
+
are read.
|
|
127
|
+
OSError: If a network error occurs during socket read.
|
|
128
|
+
"""
|
|
129
|
+
if num_bytes < 0:
|
|
130
|
+
raise ValueError("num_bytes cannot be negative.")
|
|
131
|
+
if num_bytes == 0:
|
|
132
|
+
return b""
|
|
133
|
+
|
|
134
|
+
chunks: list[bytes] = []
|
|
135
|
+
bytes_left = num_bytes
|
|
136
|
+
while bytes_left > 0:
|
|
137
|
+
chunk = self.sock.recv(min(bytes_left, 4096))
|
|
138
|
+
if not chunk:
|
|
139
|
+
raise ConnectionResetError(
|
|
140
|
+
"Connection closed before reading complete "
|
|
141
|
+
"handshake frame."
|
|
142
|
+
)
|
|
143
|
+
chunks.append(chunk)
|
|
144
|
+
bytes_left -= len(chunk)
|
|
145
|
+
return b"".join(chunks)
|
pylan/core/models.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Data models for PyLan discovery and node identities."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ProtocolType(str, Enum):
|
|
10
|
+
TCP = "tcp"
|
|
11
|
+
HTTP = "http"
|
|
12
|
+
HTTPS = "https"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class HttpChannel:
|
|
17
|
+
host: str
|
|
18
|
+
port: int
|
|
19
|
+
protocol: ProtocolType = ProtocolType.TCP
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class DiscoveredDevice:
|
|
24
|
+
alias: str
|
|
25
|
+
version: str
|
|
26
|
+
device_model: Optional[str]
|
|
27
|
+
device_type: str
|
|
28
|
+
fingerprint: str
|
|
29
|
+
channel: HttpChannel
|
|
30
|
+
download: bool = True
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class StatefulDevice:
|
|
35
|
+
device: DiscoveredDevice
|
|
36
|
+
first_seen: datetime
|
|
37
|
+
last_seen: datetime
|
|
38
|
+
channels: list[HttpChannel] = field(default_factory=list)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class DeviceStore:
|
|
42
|
+
"""Thread-safe and async-safe in-memory store for discovered peers."""
|
|
43
|
+
|
|
44
|
+
def __init__(self) -> None:
|
|
45
|
+
self._devices: dict[str, StatefulDevice] = {} # keyed by fingerprint
|
|
46
|
+
|
|
47
|
+
def upsert(self, device: DiscoveredDevice) -> tuple[bool, StatefulDevice]:
|
|
48
|
+
"""Insert or update a device record.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
A tuple of (is_new, stateful_device).
|
|
52
|
+
"""
|
|
53
|
+
now = datetime.now()
|
|
54
|
+
fp = device.fingerprint
|
|
55
|
+
|
|
56
|
+
if fp in self._devices:
|
|
57
|
+
entry = self._devices[fp]
|
|
58
|
+
entry.device = device
|
|
59
|
+
entry.last_seen = now
|
|
60
|
+
if device.channel not in entry.channels:
|
|
61
|
+
entry.channels.append(device.channel)
|
|
62
|
+
return False, entry
|
|
63
|
+
else:
|
|
64
|
+
stateful = StatefulDevice(
|
|
65
|
+
device=device,
|
|
66
|
+
first_seen=now,
|
|
67
|
+
last_seen=now,
|
|
68
|
+
channels=[device.channel],
|
|
69
|
+
)
|
|
70
|
+
self._devices[fp] = stateful
|
|
71
|
+
return True, stateful
|
|
72
|
+
|
|
73
|
+
def all_devices(self) -> list[StatefulDevice]:
|
|
74
|
+
return list(self._devices.values())
|
|
75
|
+
|
|
76
|
+
def get_by_fingerprint(self, fingerprint: str) -> Optional[StatefulDevice]:
|
|
77
|
+
return self._devices.get(fingerprint)
|