Debian Codegraph @

rcon/source/proto.py

raw
1 """Low-level protocol stuff."""
2
3 from __future__ import annotations
4 from asyncio import StreamReader
5 from enum import Enum
6 from functools import partial
7 from logging import getLogger
8 from random import randint
9 from typing import IO, NamedTuple
10
11 from rcon.exceptions import EmptyResponse, UnexpectedTerminator
12
13
14 __all__ = ["LittleEndianSignedInt32", "Type", "Packet", "random_request_id"]
15
16
17 LOGGER = getLogger(__file__)
18 TERMINATOR = b"\x00\x00"
19
20
21 class LittleEndianSignedInt32(int):
22 """A little-endian, signed int32."""
23
24 MIN = -2_147_483_648
25 MAX = 2_147_483_647
26
27 def __init__(self, *_):
28 """Check the boundaries."""
29 super().__init__()
30
31 if not self.MIN <= self <= self.MAX:
32 raise ValueError("Signed int32 out of bounds:", int(self))
33
34 def __bytes__(self):
35 """Return the integer as signed little endian."""
36 return self.to_bytes(4, "little", signed=True)
37
38 @classmethod
39 async def aread(cls, reader: StreamReader) -> LittleEndianSignedInt32:
40 """Read the integer from an asynchronous file-like object."""
41 return cls.from_bytes(await reader.read(4), "little", signed=True)
42
43 @classmethod
44 def read(cls, file: IO) -> LittleEndianSignedInt32:
45 """Read the integer from a file-like object."""
46 return cls.from_bytes(file.read(4), "little", signed=True)
47
48
49 class Type(LittleEndianSignedInt32, Enum):
50 """RCON packet types."""
51
52 SERVERDATA_AUTH = LittleEndianSignedInt32(3)
53 SERVERDATA_AUTH_RESPONSE = LittleEndianSignedInt32(2)
54 SERVERDATA_EXECCOMMAND = LittleEndianSignedInt32(2)
55 SERVERDATA_RESPONSE_VALUE = LittleEndianSignedInt32(0)
56
57 def __int__(self):
58 """Return the actual integer value."""
59 return int(self.value)
60
61 def __bytes__(self):
62 """Return the integer value as little endian."""
63 return bytes(self.value)
64
65 @classmethod
66 async def aread(cls, reader: StreamReader, *, prefix: str = "") -> Type:
67 """Read the type from an asynchronous file-like object."""
68 LOGGER.debug("%sReading type asynchronously.", prefix)
69 value = await LittleEndianSignedInt32.aread(reader)
70 LOGGER.debug("%s => value: %i", prefix, value)
71 return cls(value)
72
73 @classmethod
74 def read(cls, file: IO, *, prefix: str = "") -> Type:
75 """Read the type from a file-like object."""
76 LOGGER.debug("%sReading type.", prefix)
77 value = LittleEndianSignedInt32.read(file)
78 LOGGER.debug("%s => value: %i", prefix, value)
79 return cls(value)
80
81
82 class Packet(NamedTuple):
83 """An RCON packet."""
84
85 id: LittleEndianSignedInt32
86 type: Type
87 payload: bytes
88 terminator: bytes = TERMINATOR
89
90 def __add__(self, other: Packet | None) -> Packet:
91 if other is None:
92 return self
93
94 if other.id != self.id:
95 raise ValueError("Can only add packages with same id.")
96
97 if other.type != self.type:
98 raise ValueError("Can only add packages of same type.")
99
100 if other.terminator != self.terminator:
101 raise ValueError("Can only add packages with same terminator.")
102
103 return Packet(self.id, self.type, self.payload + other.payload, self.terminator)
104
105 def __radd__(self, other: Packet | None) -> Packet:
106 if other is None:
107 return self
108
109 return other.__add__(self)
110
111 def __bytes__(self):
112 """Return the packet as bytes with prepended length."""
113 payload = bytes(self.id)
114 payload += bytes(self.type)
115 payload += self.payload
116 payload += self.terminator
117 size = bytes(LittleEndianSignedInt32(len(payload)))
118 return size + payload
119
120 @classmethod
121 async def aread(
122 cls, reader: StreamReader, raise_unexpected_terminator: bool = False
123 ) -> Packet:
124 """Read a packet from an asynchronous file-like object."""
125 LOGGER.debug("Reading packet asynchronously.")
126 size = await LittleEndianSignedInt32.aread(reader)
127 LOGGER.debug(" => size: %i", size)
128
129 if not size:
130 raise EmptyResponse()
131
132 id_ = await LittleEndianSignedInt32.aread(reader)
133 LOGGER.debug(" => id: %i", id_)
134 type_ = await Type.aread(reader, prefix=" ")
135 LOGGER.debug(" => type: %i", type_)
136 payload = await reader.read(size - 10)
137 LOGGER.debug(" => payload: %s", payload)
138 terminator = await reader.read(2)
139 LOGGER.debug(" => terminator: %s", terminator)
140
141 if terminator != TERMINATOR:
142 if raise_unexpected_terminator:
143 raise UnexpectedTerminator(terminator)
144 LOGGER.warning("Unexpected terminator: %s", terminator)
145
146 return cls(id_, type_, payload, terminator)
147
148 @classmethod
149 def read(cls, file: IO, raise_unexpected_terminator: bool = False) -> Packet:
150 """Read a packet from a file-like object."""
151 LOGGER.debug("Reading packet.")
152 size = LittleEndianSignedInt32.read(file)
153 LOGGER.debug(" => size: %i", size)
154
155 if not size:
156 raise EmptyResponse()
157
158 id_ = LittleEndianSignedInt32.read(file)
159 LOGGER.debug(" => id: %i", id_)
160 type_ = Type.read(file, prefix=" ")
161 LOGGER.debug(" => type: %i", type_)
162 payload = file.read(size - 10)
163 LOGGER.debug(" => payload: %s", payload)
164 terminator = file.read(2)
165 LOGGER.debug(" => terminator: %s", terminator)
166
167 if terminator != TERMINATOR:
168 if raise_unexpected_terminator:
169 raise UnexpectedTerminator(terminator)
170 LOGGER.warning("Unexpected terminator: %s", terminator)
171
172 return cls(id_, type_, payload, terminator)
173
174 @classmethod
175 def make_command(cls, *args: str, encoding: str = "utf-8") -> Packet:
176 """Create a command packet."""
177 return cls(
178 random_request_id(),
179 Type.SERVERDATA_EXECCOMMAND,
180 b" ".join(map(partial(str.encode, encoding=encoding), args)),
181 )
182
183 @classmethod
184 def make_empty_response(cls) -> Packet:
185 """Create an empty response packet."""
186 return cls(random_request_id(), Type.SERVERDATA_RESPONSE_VALUE, b"")
187
188 @classmethod
189 def make_login(cls, passwd: str, *, encoding: str = "utf-8") -> Packet:
190 """Create a login packet."""
191 return cls(random_request_id(), Type.SERVERDATA_AUTH, passwd.encode(encoding))
192
193
194 def random_request_id() -> LittleEndianSignedInt32:
195 """Generate a random request ID."""
196
197 return LittleEndianSignedInt32(randint(0, LittleEndianSignedInt32.MAX))