"""Who is connected to a game server: count, names, IP addresses, connection time and ping. - Count and connection time come from the Steam server query (A2S) on the server's query port, which is what the game itself reports to the server browser. - IP addresses come from the host's conntrack table (gsm uses the host network, so it sees the NAT entries Docker makes for each client's UDP flow to the game port). - Names: Valheim leaves A2S names empty, so they are read from its "Got character ZDOID" log lines. - Ping is a plain ICMP echo. Many home routers don't answer it, so it is often unknown. """ import calendar import re import socket import struct import subprocess import time from pathlib import Path A2S_HEADER = b"\xff\xff\xff\xff" def _a2s(sock, addr, request): sock.sendto(request, addr) data = sock.recv(4096) if data[4:5] == b"A": # challenge: repeat the request with the number the server sent if request[4:5] == b"U": request = request[:5] + data[5:9] else: request = request + data[5:9] sock.sendto(request, addr) data = sock.recv(4096) return data def a2s_players(port, host="127.0.0.1", timeout=1.5): """[{name, duration}] from A2S_PLAYER, or None if the server doesn't answer.""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(timeout) try: data = _a2s(s, (host, port), A2S_HEADER + b"U" + A2S_HEADER) except OSError: return None finally: s.close() if data[:5] != A2S_HEADER + b"D": return None players, pos = [], 6 try: for _ in range(data[5]): end = data.index(b"\x00", pos + 1) name = data[pos + 1:end].decode(errors="replace") _score, duration = struct.unpack_from(" time gsm first saw the flow def udp_flows(port): """Live client flows to a UDP port, oldest first: [{ip, since}].""" try: text = CONNTRACK.read_text() except OSError: return [] now = time.time() seen, flows = set(), [] for m in _CT_RE.finditer(text): left, ip, sport, dport = int(m.group(1)), m.group(2), m.group(3), int(m.group(4)) key = (ip, sport, dport) seen.add(key) # Game clients send packets constantly, so their entry's timeout stays near the 120 s maximum. # A flow that has gone quiet for over 30 s belongs to someone who already left. if dport != port or left < 90 or ip.startswith("127."): continue flows.append({"ip": ip, "since": _first_seen.setdefault(key, now)}) for key in [k for k in _first_seen if k not in seen]: del _first_seen[key] return sorted(flows, key=lambda f: f["since"]) # ---------- Valheim player names from the log ---------- _VH_CONNECT = re.compile(r"Got connection SteamID (\d+)") _VH_CLOSE = re.compile(r"Closing socket (\d+)") _VH_CHARACTER = re.compile(r"Got character ZDOID from (.+?) : (-?\d+):(\d+)") def _docker_ts(line): """(sortable timestamp string, unix time) from a `docker logs --timestamps` line.""" ts = line.split(" ", 1)[0] sec, _, frac = ts.rstrip("Z").partition(".") return f"{sec}.{frac.ljust(9, '0')}", calendar.timegm(time.strptime(sec, "%Y-%m-%dT%H:%M:%S")) class ValheimSessions: """Follows a Valheim container's log to know who is connected and their character names.""" def __init__(self): self.started = None self.last_ts = "" self.sessions = [] # [{steam_id, since, name}] in join order def update(self, c): started = c.attrs.get("State", {}).get("StartedAt") if started != self.started: # new container or restarted: read its log from the start self.started, self.last_ts, self.sessions = started, "", [] since = calendar.timegm(time.strptime(self.last_ts[:19], "%Y-%m-%dT%H:%M:%S")) if self.last_ts else None raw = c.logs(timestamps=True, since=since) if since else c.logs(timestamps=True) for line in raw.decode(errors="replace").splitlines(): try: key, t = _docker_ts(line) except ValueError: continue if key <= self.last_ts: continue # `since` has 1 s granularity, so skip lines already handled self.last_ts = key if m := _VH_CONNECT.search(line): self.sessions = [s for s in self.sessions if s["steam_id"] != m.group(1)] self.sessions.append({"steam_id": m.group(1), "since": t, "name": None}) elif m := _VH_CLOSE.search(line): self.sessions = [s for s in self.sessions if s["steam_id"] != m.group(1)] elif (m := _VH_CHARACTER.search(line)) and (m.group(2), m.group(3)) != ("0", "0"): # Logged when a character spawns (0:0 is a death). The first spawn after joining names # the newest unnamed session; later ones are respawns. if not any(s["name"] == m.group(1) for s in self.sessions): for s in reversed(self.sessions): if s["name"] is None: s["name"] = m.group(1) break return self.sessions # ---------- ping ---------- def ping_ms(ip, timeout=1): """Round trip time in ms, or None when the host doesn't answer ICMP echo.""" try: out = subprocess.run(["ping", "-n", "-c", "1", "-W", str(timeout), ip], capture_output=True, text=True, timeout=timeout + 2).stdout except (OSError, subprocess.TimeoutExpired): return None m = re.search(r"time[=<]([\d.]+) ?ms", out) return round(float(m.group(1))) if m else None def combine(a2s, flows, sessions, now): """Merge the sources into [{name, ip, since}], longest connected first. A2S is the source of truth for who is online. IPs and log names don't carry a player ID that A2S shares, so they are matched up by join order, which is exact for one player and almost always right for more. """ if a2s is None: if sessions is None: return None a2s = [{"name": "", "duration": now - s["since"]} for s in sessions] players = sorted(a2s, key=lambda p: -p["duration"]) flows = flows[-len(players):] if players else [] # the newest flows, in case a stale one lingers named = [s["name"] for s in sessions] if sessions and len(sessions) == len(players) else [] out = [] for i, p in enumerate(players): name = p["name"] or (named[i] if i < len(named) else None) out.append({ "name": name or f"Player {i + 1}", "ip": flows[i]["ip"] if len(flows) == len(players) else None, "since": now - p["duration"], }) return out