fix(matrixbot): replace mcrcon with a thread-safe RCON client
mcrcon implements its read timeout with signal.SIGALRM, which only works on the main thread. The Minecraft commands call it from a worker thread via loop.run_in_executor, so it raised "signal only works in main thread of the main interpreter" on every invocation. The replacement uses socket.settimeout(), which has no such restriction. This code was already deployed on LXC 151 but had never been committed, so any matrixbot deploy would have reverted it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -155,3 +155,50 @@ def sanitize_input(text: str, max_length: int = MAX_INPUT_LENGTH) -> str:
|
||||
text = text.strip()[:max_length]
|
||||
text = "".join(char for char in text if char.isprintable())
|
||||
return text
|
||||
|
||||
|
||||
class RconError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def rcon_command(host: str, password: str, command: str, port: int = 25575, timeout: float = 5.0) -> str:
|
||||
"""Minimal Source RCON client (Minecraft protocol) using socket timeouts.
|
||||
|
||||
Deliberately avoids the `mcrcon` package: it implements its read timeout
|
||||
via signal.SIGALRM, which only works on the main thread — this is always
|
||||
called from a worker thread (via loop.run_in_executor), so that library
|
||||
raises "signal only works in main thread of the main interpreter" every
|
||||
time. socket.settimeout() has no such restriction.
|
||||
"""
|
||||
import socket
|
||||
import struct
|
||||
|
||||
def send_packet(sock, pkt_id, pkt_type, payload):
|
||||
body = struct.pack("<ii", pkt_id, pkt_type) + payload.encode("utf-8") + b"\x00\x00"
|
||||
sock.sendall(struct.pack("<i", len(body)) + body)
|
||||
|
||||
def read_packet(sock):
|
||||
def recv_exact(n):
|
||||
buf = b""
|
||||
while len(buf) < n:
|
||||
chunk = sock.recv(n - len(buf))
|
||||
if not chunk:
|
||||
raise RconError("Connection closed by server")
|
||||
buf += chunk
|
||||
return buf
|
||||
|
||||
length = struct.unpack("<i", recv_exact(4))[0]
|
||||
data = recv_exact(length)
|
||||
pkt_id, _pkt_type = struct.unpack("<ii", data[:8])
|
||||
return pkt_id, data[8:-2].decode("utf-8", "replace")
|
||||
|
||||
with socket.create_connection((host, port), timeout=timeout) as sock:
|
||||
sock.settimeout(timeout)
|
||||
send_packet(sock, 1, 3, password)
|
||||
auth_id, _ = read_packet(sock)
|
||||
if auth_id == -1:
|
||||
raise RconError("RCON authentication failed (wrong password)")
|
||||
|
||||
send_packet(sock, 2, 2, command)
|
||||
_, response = read_packet(sock)
|
||||
return response
|
||||
|
||||
Reference in New Issue
Block a user