Debian Codegraph @

rcon/source/client.py

raw
1 """Synchronous client."""
2
3 from socket import SOCK_STREAM
4
5 from rcon.client import BaseClient
6 from rcon.exceptions import SessionTimeout, WrongPassword
7 from rcon.source.proto import Packet, Type
8
9 __all__ = ["Client"]
10
11
12 class Client(BaseClient, socket_type=SOCK_STREAM):
13 """An RCON client."""
14
15 def __init__(self, *args, frag_threshold: int = 4096, **kwargs):
16 """Set an optional fragmentation threshold and
17 command in order to detect fragmented packets.
18
19 For details see: https://wiki.vg/RCON#Fragmentation
20 """
21 super().__init__(*args, **kwargs)
22 self.frag_threshold = frag_threshold
23
24 def communicate(
25 self, packet: Packet, raise_unexpected_terminator: bool = False
26 ) -> Packet:
27 """Send and receive a packet."""
28 self.send(packet)
29 return self.read(raise_unexpected_terminator)
30
31 def send(self, packet: Packet) -> None:
32 """Send a packet to the server."""
33 with self._socket.makefile("wb") as file:
34 file.write(bytes(packet))
35
36 def read(self, raise_unexpected_terminator: bool = False) -> Packet:
37 """Read a packet from the server."""
38 with self._socket.makefile("rb") as file:
39 response = Packet.read(file, raise_unexpected_terminator)
40
41 if len(response.payload) < self.frag_threshold:
42 return response
43
44 self.send(Packet.make_empty_response())
45
46 while (successor := Packet.read(file)).id == response.id:
47 response += successor
48
49 return response
50
51 def login(self, passwd: str, *, encoding: str = "utf-8") -> bool:
52 """Perform a login."""
53 self.send(Packet.make_login(passwd, encoding=encoding))
54
55 # Wait for SERVERDATA_AUTH_RESPONSE according to:
56 # https://developer.valvesoftware.com/wiki/Source_RCON_Protocol
57 while (response := self.read()).type != Type.SERVERDATA_AUTH_RESPONSE:
58 pass
59
60 if response.id == -1:
61 raise WrongPassword()
62
63 return True
64
65 def run(
66 self,
67 command: str,
68 *args: str,
69 encoding: str = "utf-8",
70 enforce_id: bool = True,
71 raise_unexpected_terminator: bool = False,
72 ) -> str:
73 """Run a command."""
74 request = Packet.make_command(command, *args, encoding=encoding)
75 response = self.communicate(request, raise_unexpected_terminator)
76
77 if enforce_id and response.id != request.id:
78 raise SessionTimeout("packet ID mismatch")
79
80 return response.payload.decode(encoding)