2023-11-01 04:57:08 +00:00
|
|
|
"""Packet streams"""
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
from asyncio import Event, Queue
|
2017-05-25 10:47:01 +00:00
|
|
|
from enum import Enum
|
2023-11-01 06:16:17 +00:00
|
|
|
import logging
|
2018-05-06 12:55:00 +00:00
|
|
|
from math import ceil
|
2023-11-01 06:16:17 +00:00
|
|
|
import struct
|
|
|
|
from time import time
|
2023-11-01 06:22:29 +00:00
|
|
|
from typing import Any, AsyncIterator, Dict, Optional, Tuple, Union
|
2017-05-25 10:47:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
from secret_handshake.network import SHSDuplexStream
|
2017-05-25 10:47:01 +00:00
|
|
|
import simplejson
|
2023-11-01 06:22:29 +00:00
|
|
|
from typing_extensions import Self
|
2017-08-01 20:34:06 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
PSHandler = Union["PSRequestHandler", "PSStreamHandler"]
|
2023-11-01 06:22:29 +00:00
|
|
|
PSMessageData = Union[bytes, bool, Dict[str, Any], str]
|
2023-11-01 06:22:29 +00:00
|
|
|
logger = logging.getLogger("packet_stream")
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
class PSMessageType(Enum):
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Available message types"""
|
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
BUFFER = 0
|
|
|
|
TEXT = 1
|
|
|
|
JSON = 2
|
|
|
|
|
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
class PSStreamHandler:
|
|
|
|
"""Packet stream handler"""
|
|
|
|
|
2023-11-02 09:50:42 +00:00
|
|
|
def __init__(self, req: int):
|
2017-07-29 09:54:03 +00:00
|
|
|
self.req = req
|
2023-11-02 09:50:42 +00:00
|
|
|
self.queue: Queue[Optional["PSMessage"]] = Queue()
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def process(self, msg: "PSMessage") -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Process a pending message"""
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
await self.queue.put(msg)
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def stop(self) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Stop a pending request"""
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
await self.queue.put(None)
|
|
|
|
|
2023-11-02 09:50:42 +00:00
|
|
|
def __aiter__(self) -> AsyncIterator[Optional["PSMessage"]]:
|
2023-11-01 05:03:06 +00:00
|
|
|
return self
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def __anext__(self) -> Optional["PSMessage"]:
|
2023-11-01 05:03:06 +00:00
|
|
|
elem = await self.queue.get()
|
|
|
|
|
|
|
|
if not elem:
|
|
|
|
raise StopAsyncIteration()
|
|
|
|
|
|
|
|
return elem
|
2017-07-29 09:54:03 +00:00
|
|
|
|
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
class PSRequestHandler:
|
|
|
|
"""Packet stream request handler"""
|
|
|
|
|
2023-11-02 09:50:42 +00:00
|
|
|
def __init__(self, req: int):
|
2017-07-30 08:14:26 +00:00
|
|
|
self.req = req
|
2017-07-30 12:08:18 +00:00
|
|
|
self.event = Event()
|
2023-11-01 06:22:29 +00:00
|
|
|
self._msg: Optional[PSMessage] = None
|
2017-07-30 08:14:26 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def process(self, msg: "PSMessage") -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Process a message request"""
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
self._msg = msg
|
2017-07-30 12:08:18 +00:00
|
|
|
self.event.set()
|
2017-07-30 08:14:26 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def stop(self) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Stop a pending event request"""
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
if not self.event.is_set():
|
|
|
|
self.event.set()
|
2017-07-30 08:14:26 +00:00
|
|
|
|
2023-11-02 09:50:42 +00:00
|
|
|
def __aiter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
async def __anext__(self) -> Optional["PSMessage"]:
|
2017-07-30 12:08:18 +00:00
|
|
|
# wait until 'process' is called
|
2023-11-01 04:57:08 +00:00
|
|
|
await self.event.wait()
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
return self._msg
|
|
|
|
|
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
class PSMessage:
|
|
|
|
"""Packet Stream message"""
|
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
@classmethod
|
2023-11-01 06:22:29 +00:00
|
|
|
def from_header_body(cls, flags: int, req: int, body: bytes) -> Self:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Parse a raw message"""
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
type_ = PSMessageType(flags & 0x03)
|
|
|
|
|
|
|
|
if type_ == PSMessageType.TEXT:
|
2023-11-01 06:22:29 +00:00
|
|
|
body_s = body.decode("utf-8")
|
2017-07-29 09:54:03 +00:00
|
|
|
elif type_ == PSMessageType.JSON:
|
2023-11-01 06:22:29 +00:00
|
|
|
body_s = simplejson.loads(body)
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
return cls(type_, body_s, bool(flags & 0x08), bool(flags & 0x04), req=req)
|
2017-05-25 10:47:01 +00:00
|
|
|
|
|
|
|
@property
|
2023-11-01 06:22:29 +00:00
|
|
|
def data(self) -> bytes:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""The raw message data"""
|
|
|
|
|
2017-05-25 10:47:01 +00:00
|
|
|
if self.type == PSMessageType.TEXT:
|
2023-11-01 06:22:29 +00:00
|
|
|
assert isinstance(self.body, str)
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
return self.body.encode("utf-8")
|
2023-11-01 04:57:08 +00:00
|
|
|
|
|
|
|
if self.type == PSMessageType.JSON:
|
2023-11-01 04:04:43 +00:00
|
|
|
return simplejson.dumps(self.body).encode("utf-8")
|
2023-11-01 04:57:08 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
assert isinstance(self.body, bytes)
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
return self.body
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(
|
|
|
|
self, type_: PSMessageType, body: Any, stream: bool, end_err: bool, req: Optional[int] = None
|
|
|
|
): # pylint: disable=too-many-arguments
|
2017-07-29 09:54:03 +00:00
|
|
|
self.stream = stream
|
|
|
|
self.end_err = end_err
|
|
|
|
self.type = type_
|
|
|
|
self.body = body
|
|
|
|
self.req = req
|
2017-05-25 10:47:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __repr__(self) -> str:
|
2017-07-30 09:51:11 +00:00
|
|
|
if self.type == PSMessageType.BUFFER:
|
2023-11-01 04:57:08 +00:00
|
|
|
body = f"{len(self.body)} bytes"
|
2017-07-30 09:51:11 +00:00
|
|
|
else:
|
|
|
|
body = self.body
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
req = "" if self.req is None else f" [{self.req}]"
|
|
|
|
is_stream = "~" if self.stream else ""
|
|
|
|
err = "!" if self.end_err else ""
|
|
|
|
|
|
|
|
return f"<PSMessage ({self.type.name}): {body}{req} {is_stream}{err}>"
|
|
|
|
|
|
|
|
|
|
|
|
class PacketStream:
|
|
|
|
"""SSB Packet stream"""
|
2017-05-25 10:47:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __init__(self, connection: SHSDuplexStream):
|
2018-02-04 21:18:36 +00:00
|
|
|
self.connection = connection
|
2017-07-29 09:54:03 +00:00
|
|
|
self.req_counter = 1
|
2023-11-01 06:22:29 +00:00
|
|
|
self._event_map: Dict[int, Tuple[float, PSHandler]] = {}
|
2023-11-01 04:57:08 +00:00
|
|
|
self._connected = False
|
2017-07-30 12:08:18 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def register_handler(self, handler: PSHandler) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Register an RPC handler"""
|
|
|
|
|
2018-02-04 21:18:36 +00:00
|
|
|
self._event_map[handler.req] = (time(), handler)
|
2017-07-30 12:08:18 +00:00
|
|
|
|
|
|
|
@property
|
2023-11-01 06:22:29 +00:00
|
|
|
def is_connected(self) -> bool:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Check if the stream is connected"""
|
|
|
|
|
2018-02-04 21:18:36 +00:00
|
|
|
return self.connection.is_connected
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def __aiter__(self) -> AsyncIterator[Optional[PSMessage]]:
|
2023-11-01 05:03:06 +00:00
|
|
|
return self
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def __anext__(self) -> Optional[PSMessage]:
|
2023-11-01 05:03:06 +00:00
|
|
|
msg = await self.read()
|
|
|
|
|
|
|
|
if not msg:
|
|
|
|
raise StopAsyncIteration()
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
if msg.req is not None and msg.req >= 0:
|
2023-11-01 05:03:06 +00:00
|
|
|
return msg
|
|
|
|
|
|
|
|
return None
|
2018-02-04 21:18:36 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def __await__(self) -> None:
|
2018-02-04 21:18:36 +00:00
|
|
|
async for data in self:
|
2023-11-01 04:04:43 +00:00
|
|
|
logger.info("RECV: %r", data)
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2018-02-04 21:18:36 +00:00
|
|
|
if data is None:
|
|
|
|
return
|
2017-05-25 10:47:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def _read(self) -> Optional[PSMessage]:
|
2017-06-04 22:27:44 +00:00
|
|
|
try:
|
|
|
|
header = await self.connection.read()
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
if not header or header == b"\x00" * 9:
|
2023-11-01 06:22:29 +00:00
|
|
|
return None
|
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
flags, length, req = struct.unpack(">BIi", header)
|
2017-07-30 09:51:11 +00:00
|
|
|
|
2018-05-06 12:55:00 +00:00
|
|
|
n_packets = ceil(length / 4096)
|
2017-07-30 09:51:11 +00:00
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
body = b""
|
2023-11-01 04:57:08 +00:00
|
|
|
|
|
|
|
for _ in range(n_packets):
|
2023-11-01 06:22:29 +00:00
|
|
|
read_data = await self.connection.read()
|
|
|
|
|
|
|
|
if read_data is not None:
|
|
|
|
body += read_data
|
2017-07-30 09:51:11 +00:00
|
|
|
|
2023-11-01 04:04:43 +00:00
|
|
|
logger.debug("READ %s %s", header, len(body))
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-30 09:51:11 +00:00
|
|
|
return PSMessage.from_header_body(flags, req, body)
|
2017-06-04 22:27:44 +00:00
|
|
|
except StopAsyncIteration:
|
2023-11-01 04:04:43 +00:00
|
|
|
logger.debug("DISCONNECT")
|
2017-07-31 21:15:52 +00:00
|
|
|
self.connection.disconnect()
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-06-04 22:27:44 +00:00
|
|
|
return None
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
async def read(self) -> Optional[PSMessage]:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Read data from the packet stream"""
|
|
|
|
|
2017-07-30 20:28:42 +00:00
|
|
|
msg = await self._read()
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-30 20:28:42 +00:00
|
|
|
if not msg:
|
|
|
|
return None
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-30 20:28:42 +00:00
|
|
|
# check whether it's a reply and handle accordingly
|
2023-11-01 06:22:29 +00:00
|
|
|
if msg.req is not None and msg.req < 0:
|
2023-11-01 04:57:08 +00:00
|
|
|
_, handler = self._event_map[-msg.req]
|
2017-07-30 20:28:42 +00:00
|
|
|
await handler.process(msg)
|
2023-11-01 04:04:43 +00:00
|
|
|
logger.info("RESPONSE [%d]: %r", -msg.req, msg)
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-30 20:28:42 +00:00
|
|
|
if msg.end_err:
|
|
|
|
await handler.stop()
|
|
|
|
del self._event_map[-msg.req]
|
2023-11-01 04:04:43 +00:00
|
|
|
logger.info("RESPONSE [%d]: EOS", -msg.req)
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-30 20:28:42 +00:00
|
|
|
return msg
|
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def _write(self, msg: PSMessage) -> None:
|
2023-11-01 04:04:43 +00:00
|
|
|
logger.info("SEND [%d]: %r", msg.req, msg)
|
|
|
|
header = struct.pack(
|
|
|
|
">BIi", (int(msg.stream) << 3) | (int(msg.end_err) << 2) | msg.type.value, len(msg.data), msg.req
|
|
|
|
)
|
2017-06-04 22:27:44 +00:00
|
|
|
self.connection.write(header)
|
2017-07-30 08:14:26 +00:00
|
|
|
self.connection.write(msg.data)
|
2023-11-01 04:04:43 +00:00
|
|
|
logger.debug("WRITE HDR: %s", header)
|
|
|
|
logger.debug("WRITE DATA: %s", msg.data)
|
2017-07-29 09:54:03 +00:00
|
|
|
|
2023-11-01 04:57:08 +00:00
|
|
|
def send( # pylint: disable=too-many-arguments
|
2023-11-01 06:22:29 +00:00
|
|
|
self,
|
|
|
|
data: Any,
|
|
|
|
msg_type: PSMessageType = PSMessageType.JSON,
|
|
|
|
stream: bool = False,
|
|
|
|
end_err: bool = False,
|
|
|
|
req: Optional[int] = None,
|
2023-11-01 06:22:29 +00:00
|
|
|
) -> PSHandler:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Send data through the packet stream"""
|
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
update_counter = False
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-30 08:14:26 +00:00
|
|
|
if req is None:
|
|
|
|
update_counter = True
|
|
|
|
req = self.req_counter
|
|
|
|
|
|
|
|
msg = PSMessage(msg_type, data, stream=stream, end_err=end_err, req=req)
|
|
|
|
|
|
|
|
# send request
|
|
|
|
self._write(msg)
|
|
|
|
|
|
|
|
if stream:
|
2023-11-01 06:22:29 +00:00
|
|
|
handler: PSHandler = PSStreamHandler(self.req_counter)
|
2017-07-30 08:14:26 +00:00
|
|
|
else:
|
|
|
|
handler = PSRequestHandler(self.req_counter)
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
self.register_handler(handler)
|
2017-07-30 08:14:26 +00:00
|
|
|
|
|
|
|
if update_counter:
|
|
|
|
self.req_counter += 1
|
2023-11-01 06:22:29 +00:00
|
|
|
|
2017-07-29 09:54:03 +00:00
|
|
|
return handler
|
2017-05-25 10:47:01 +00:00
|
|
|
|
2023-11-01 06:22:29 +00:00
|
|
|
def disconnect(self) -> None:
|
2023-11-01 04:57:08 +00:00
|
|
|
"""Disconnect the stream"""
|
|
|
|
|
2017-07-30 12:08:18 +00:00
|
|
|
self._connected = False
|
|
|
|
self.connection.disconnect()
|