|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from .lib32100 import BaseP2PClientProtocol |
| 4 | +from .types import ( |
| 5 | + P2PClientProtocolRequestMessageType, |
| 6 | + P2PClientProtocolResponseMessageType, |
| 7 | +) |
| 8 | + |
| 9 | + |
| 10 | +class DiscoveryP2PClientProtocol(BaseP2PClientProtocol): |
| 11 | + def __init__(self, loop, p2p_did: str, key: str, on_conn_lost): |
| 12 | + self.loop = loop |
| 13 | + self.p2p_did = p2p_did |
| 14 | + self.key = key |
| 15 | + self.on_conn_lost = on_conn_lost |
| 16 | + self.transport = None |
| 17 | + self.addresses = [] |
| 18 | + self.response_count = 0 |
| 19 | + |
| 20 | + def connection_made(self, transport): |
| 21 | + self.transport = transport |
| 22 | + |
| 23 | + # Build payload |
| 24 | + p2p_did_components = self.p2p_did.split("-") |
| 25 | + payload = bytearray(p2p_did_components[0].encode()) |
| 26 | + payload.extend(int(p2p_did_components[1]).to_bytes(5, byteorder="big")) |
| 27 | + payload.extend(p2p_did_components[2].encode()) |
| 28 | + payload.extend([0x00, 0x00, 0x00, 0x00, 0x00]) |
| 29 | + ip, port = self.transport.get_extra_info("sockname") |
| 30 | + payload.extend(port.to_bytes(2, byteorder="little")) |
| 31 | + payload.extend([int(x) for x in ip.split(".")[::-1]]) |
| 32 | + payload.extend( |
| 33 | + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x04, 0x00, 0x00] |
| 34 | + ) |
| 35 | + payload.extend(self.key.encode()) |
| 36 | + payload.extend([0x00, 0x00, 0x00, 0x00]) |
| 37 | + |
| 38 | + self.transport.sendto( |
| 39 | + self.create_message( |
| 40 | + P2PClientProtocolRequestMessageType.LOOKUP_WITH_KEY, payload |
| 41 | + ) |
| 42 | + ) |
| 43 | + # Manually timeout if we don't get an answer |
| 44 | + self.loop.create_task(self.timeout(1.5)) |
| 45 | + |
| 46 | + async def timeout(self, seconds: float): |
| 47 | + await asyncio.sleep(seconds) |
| 48 | + self.transport.close() |
| 49 | + |
| 50 | + def process_response( |
| 51 | + self, msg_type: P2PClientProtocolResponseMessageType, payload: bytes |
| 52 | + ): |
| 53 | + msg = payload[2:] |
| 54 | + if msg_type == P2PClientProtocolResponseMessageType.LOOKUP_ADDR: |
| 55 | + port = payload[5] * 256 + payload[4] |
| 56 | + ip = f"{payload[9]}.{payload[8]}.{payload[7]}.{payload[6]}" |
| 57 | + self.addresses.append((ip, port)) |
| 58 | + |
| 59 | + # We expect at most two IP/port combos so we can bail early |
| 60 | + # if we received both |
| 61 | + self.response_count += 1 |
| 62 | + if self.response_count == 2: |
| 63 | + self.transport.close() |
| 64 | + |
| 65 | + def error_received(self, exc): |
| 66 | + _LOGGER.exception("Error received", exc_info=exc) |
| 67 | + |
| 68 | + def connection_lost(self, exc): |
| 69 | + self.on_conn_lost.set_result(self.addresses) |
0 commit comments