This repository was archived by the owner on Mar 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
Implement P2P protocol for device control #44
Open
keshavdv
wants to merge
7
commits into
FuzzyMistborn:dev
Choose a base branch
from
keshavdv:p2p
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ed37df3
Implement P2P protocol for device control
keshavdv ce0661e
Add additional discovery servers
keshavdv 3c7c728
Mark connection healthy sooner
keshavdv 33711e3
Share UDP socket instance for NAT hole punching
keshavdv 46e6776
Add local discovery mechanism
keshavdv b471e0a
Make it py3.6 compatible
keshavdv 76f78ab
Add test requirement
keshavdv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,3 +6,4 @@ coverage.xml | |
| poetry.lock | ||
| tags | ||
| __pycache__ | ||
| .vscode/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import asyncio | ||
|
|
||
|
|
||
| class ConnectionManager(asyncio.DatagramProtocol): | ||
| def __init__(self): | ||
| self.connection_map = {} | ||
|
|
||
| def connect(self, target, protocol): | ||
| self.connection_map[target] = protocol | ||
| protocol.connection_made(self.transport, target) | ||
|
|
||
| def connection_made(self, transport): | ||
| self.transport = transport | ||
|
|
||
| def datagram_received(self, data, addr): | ||
| if addr in self.connection_map: | ||
| self.connection_map[addr].datagram_received(data, addr) | ||
|
|
||
| def connection_lost(self, exc): | ||
| for _, protocol in self.connection_map.items(): | ||
| protocol.connection_lost(exc) | ||
|
|
||
| def close(self): | ||
| self.transport.close() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| import asyncio | ||
| from typing import Tuple | ||
|
|
||
| from .lib32100 import BaseP2PClientProtocol | ||
| from .types import ( | ||
| P2PClientProtocolRequestMessageType, | ||
| P2PClientProtocolResponseMessageType, | ||
| ) | ||
|
|
||
|
|
||
| class DiscoveryP2PClientProtocol(BaseP2PClientProtocol): | ||
| def __init__(self, loop, p2p_did: str, key: str, on_lookup_complete): | ||
| self.loop = loop | ||
| self.p2p_did = p2p_did | ||
| self.key = key | ||
| self.on_lookup_complete = on_lookup_complete | ||
| self.addresses = [] | ||
| self.response_count = 0 | ||
|
|
||
| def connection_made(self, transport, addr): | ||
| # Build payload | ||
| p2p_did_components = self.p2p_did.split("-") | ||
| payload = bytearray(p2p_did_components[0].encode()) | ||
| payload.extend(int(p2p_did_components[1]).to_bytes(5, byteorder="big")) | ||
| payload.extend(p2p_did_components[2].encode()) | ||
| payload.extend([0x00, 0x00, 0x00, 0x00, 0x00]) | ||
| ip, port = transport.get_extra_info("sockname") | ||
| payload.extend(port.to_bytes(2, byteorder="little")) | ||
| payload.extend([int(x) for x in ip.split(".")[::-1]]) | ||
| payload.extend( | ||
| [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x04, 0x00, 0x00] | ||
| ) | ||
| payload.extend(self.key.encode()) | ||
| payload.extend([0x00, 0x00, 0x00, 0x00]) | ||
|
|
||
| transport.sendto( | ||
| self.create_message( | ||
| P2PClientProtocolRequestMessageType.LOOKUP_WITH_KEY, payload | ||
| ), | ||
| addr, | ||
| ) | ||
| # Manually timeout if we don't get an answer | ||
| self.loop.create_task(self.timeout(1.5)) | ||
|
|
||
| async def timeout(self, seconds: float): | ||
| await asyncio.sleep(seconds) | ||
| self.return_candidates() | ||
|
|
||
| def process_response( | ||
| self, | ||
| msg_type: P2PClientProtocolResponseMessageType, | ||
| payload: bytes, | ||
| addr: Tuple[str, int], | ||
| ): | ||
| msg = payload[2:] | ||
| if msg_type == P2PClientProtocolResponseMessageType.LOOKUP_ADDR: | ||
| port = payload[5] * 256 + payload[4] | ||
| ip = f"{payload[9]}.{payload[8]}.{payload[7]}.{payload[6]}" | ||
| self.addresses.append((ip, port)) | ||
|
|
||
| # We expect at most two IP/port combos so we can bail early | ||
| # if we received both | ||
| self.response_count += 1 | ||
| if self.response_count == 2: | ||
| self.return_candidates() | ||
|
|
||
| def return_candidates(self): | ||
| if not self.on_lookup_complete.done(): | ||
| self.on_lookup_complete.set_result(self.addresses) | ||
|
|
||
|
|
||
| class LocalDiscoveryP2PClientProtocol(BaseP2PClientProtocol): | ||
| def __init__(self, loop, target: str, on_lookup_complete): | ||
| self.loop = loop | ||
| self.target = target | ||
| self.addresses = [] | ||
| self.on_lookup_complete = on_lookup_complete | ||
|
|
||
| def connection_made(self, transport): | ||
| # Build payload | ||
| payload = bytearray([0] * 2) | ||
| transport.sendto( | ||
| self.create_message( | ||
| P2PClientProtocolRequestMessageType.LOCAL_LOOKUP, payload | ||
| ), | ||
| addr=(self.target, 32108), | ||
| ) | ||
| # Manually timeout if we don't get an answer | ||
| self.loop.create_task(self.timeout(1.5)) | ||
|
|
||
| async def timeout(self, seconds: float): | ||
| await asyncio.sleep(seconds) | ||
| self.return_candidates() | ||
|
|
||
| def process_response( | ||
| self, | ||
| msg_type: P2PClientProtocolResponseMessageType, | ||
| payload: bytes, | ||
| addr: Tuple[str, int], | ||
| ): | ||
| if msg_type == P2PClientProtocolResponseMessageType.LOCAL_LOOKUP_RESP: | ||
| self.addresses.append(addr) | ||
| self.return_candidates() | ||
|
|
||
| def return_candidates(self): | ||
| if not self.on_lookup_complete.done(): | ||
| self.on_lookup_complete.set_result(self.addresses) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| import asyncio | ||
| import math | ||
| from typing import Tuple | ||
|
|
||
| from .types import ( | ||
| P2PClientProtocolRequestMessageType, | ||
| P2PClientProtocolResponseMessageType, | ||
| ) | ||
|
|
||
|
|
||
| class BaseP2PClientProtocol(asyncio.DatagramProtocol): | ||
| def create_message( | ||
| self, msg_type: P2PClientProtocolRequestMessageType, payload=bytearray() | ||
| ): | ||
| msg = bytearray() | ||
| msg.extend(msg_type.value) | ||
| payload_size = len(payload) | ||
| msg.append(math.floor(payload_size / 256)) | ||
| msg.append(payload_size % 256) | ||
| msg.extend(payload) | ||
| return msg | ||
|
|
||
| def datagram_received(self, data, addr): | ||
| msg_type = P2PClientProtocolResponseMessageType(bytes(data[0:2])) | ||
| payload = data[2:] | ||
| self.process_response(msg_type, payload, addr) | ||
|
|
||
| def process_response( | ||
| self, | ||
| msg_type: P2PClientProtocolResponseMessageType, | ||
| payload: bytes, | ||
| addr: Tuple[str, int], | ||
| ): | ||
| raise NotImplementedError() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we need to import logging here and add something like:
_LOGGER: logging.Logger = logging.getLogger(__name__)