- winproc: Kommandozeilen nativ (Toolhelp32 + NtQueryInformationProcess/PEB) statt WMI/PowerShell - ~43 ms statt ~10 s je Abfrage (100x), WMI nur noch als Rueckfall. Das war die Hauptquelle des 35-53-s-Zyklus. - tischkanal/runner: echo=False (feuern-und-vergessen) fuer die OHNE_ECHO- Zustandsbefehle (play_next/auto_post_bb/aussetzen/aufstehen/nachkauf) - kein 1,5-s-Leerwarten mehr je Leerlauf-Takt (offline bewiesen 1519 ms -> 0 ms). - runner: Sitz-TTL-Rennen - unmittelbar vor take_Seat frisch reservieren und den vom Server bestaetigten Sitz nehmen; Flut-Deckel ueber Prozesszahl statt Fensterzahl. Live bewiesen (Held sitzt, spielt, gewinnt). - hand/foto,mittler,notaus,press,sitzwache + werkzeuge/hover: Windows-Rand. - Tests: auffuellen_kappe_spec, sitz_reserve_frisch_spec (neu) + Anpassungen. WIP: Rest-Tail ~18% der Zuege >1 s Maschinenzeit noch offen; 12-Tisch-Last noch nicht gemessen. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
255 lines
10 KiB
Python
255 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Prozess-Fund unter Windows - der Ersatz fuer `ps -eo pid,command` / `kill -9`.
|
|
|
|
Auf dem Mac liest der Betrieb die Prozessliste mit `ps` und findet so die Tischprozesse
|
|
(`CoinPoker Game.app/.../CoinPoker`) samt ihrer Startargumente (`pipeName=`, `roomName=`,
|
|
`tableSize=`). Unter Windows gibt es kein `ps`.
|
|
|
|
WEG 1 (nativ, Standard): Prozesse per Toolhelp-Schnappschuss auflisten und die Kommandozeile
|
|
jedes Treffers direkt aus seinem Speicher lesen (`NtQueryInformationProcess` -> PEB ->
|
|
`RTL_USER_PROCESS_PARAMETERS.CommandLine`). Kein Unterprozess, keine Shell: 11.11. gemessen
|
|
~160 ms fuer alle CoinPoker-Prozesse gegen ~10 s bei WMI. Nur 64-bit-Ziele (CoinPoker und
|
|
unser Python sind 64-bit); ein Prozess, den wir nicht oeffnen koennen (fremdes/geschuetztes
|
|
Konto), traegt eine leere Kommandozeile - genau wie bei WMI.
|
|
|
|
WEG 2 (Fallback): scheitert der Schnappschuss selbst, liefert die Kommandozeile WMI
|
|
(`Win32_Process.CommandLine`) ueber PowerShell `Get-CimInstance` (`wmic` ist weg). Langsam,
|
|
aber nie der heisse Pfad. `toeten`/`lebt` gehen immer ueber kernel32 (kein Shell-Aufruf).
|
|
|
|
prozesse() -> [(pid, kommandozeile)] toeten(pid)
|
|
python3 client/winproc.py CoinPoker # zeigt die Treffer
|
|
"""
|
|
import ctypes
|
|
from ctypes import wintypes
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
_PS = ("Get-CimInstance Win32_Process {filt} | "
|
|
"Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress")
|
|
|
|
# ---- Weg 1: nativ (Toolhelp + PEB) ----
|
|
_TH32CS_SNAPPROCESS = 0x00000002
|
|
_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
_PROCESS_VM_READ = 0x0010
|
|
_INVALID = ctypes.c_void_p(-1).value # INVALID_HANDLE_VALUE
|
|
|
|
|
|
class _PROCESSENTRY32(ctypes.Structure):
|
|
_fields_ = [("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),
|
|
("th32ProcessID", wintypes.DWORD),
|
|
("th32DefaultHeapID", ctypes.POINTER(ctypes.c_ulong)),
|
|
("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),
|
|
("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", ctypes.c_long),
|
|
("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_char * 260)]
|
|
|
|
|
|
class _PROCESS_BASIC_INFORMATION(ctypes.Structure):
|
|
_fields_ = [("Reserved1", ctypes.c_void_p), ("PebBaseAddress", ctypes.c_void_p),
|
|
("Reserved2", ctypes.c_void_p * 2), ("UniqueProcessId", ctypes.c_void_p),
|
|
("Reserved3", ctypes.c_void_p)]
|
|
|
|
|
|
def _k32():
|
|
k = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
k.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
|
|
k.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
|
|
k.Process32First.argtypes = [wintypes.HANDLE, ctypes.POINTER(_PROCESSENTRY32)]
|
|
k.Process32Next.argtypes = [wintypes.HANDLE, ctypes.POINTER(_PROCESSENTRY32)]
|
|
k.OpenProcess.restype = wintypes.HANDLE
|
|
k.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
|
k.ReadProcessMemory.argtypes = [wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p,
|
|
ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)]
|
|
k.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
return k
|
|
|
|
|
|
def _enum_pids(k, name_lower):
|
|
"""(pid, exe) aller Prozesse per Toolhelp - None, wenn der Schnappschuss scheitert."""
|
|
snap = k.CreateToolhelp32Snapshot(_TH32CS_SNAPPROCESS, 0)
|
|
if not snap or snap == _INVALID:
|
|
return None
|
|
raus = []
|
|
e = _PROCESSENTRY32()
|
|
e.dwSize = ctypes.sizeof(_PROCESSENTRY32)
|
|
try:
|
|
if k.Process32First(snap, ctypes.byref(e)):
|
|
while True:
|
|
exe = e.szExeFile.decode("latin-1", "replace")
|
|
if name_lower is None or exe.lower() == name_lower:
|
|
raus.append((e.th32ProcessID, exe))
|
|
if not k.Process32Next(snap, ctypes.byref(e)):
|
|
break
|
|
finally:
|
|
k.CloseHandle(snap)
|
|
return raus
|
|
|
|
|
|
def _lese(k, h, addr, groesse):
|
|
buf = (ctypes.c_char * groesse)()
|
|
got = ctypes.c_size_t(0)
|
|
if not k.ReadProcessMemory(h, ctypes.c_void_p(addr), buf, groesse, ctypes.byref(got)):
|
|
return None
|
|
return buf.raw[:got.value]
|
|
|
|
|
|
def _kommandozeile(k, nt, pid):
|
|
"""Die Kommandozeile eines 64-bit-Prozesses aus seinem PEB - "" wenn unlesbar."""
|
|
h = k.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION | _PROCESS_VM_READ, False, pid)
|
|
if not h:
|
|
return ""
|
|
try:
|
|
pbi = _PROCESS_BASIC_INFORMATION()
|
|
rl = wintypes.ULONG(0)
|
|
if nt.NtQueryInformationProcess(h, 0, ctypes.byref(pbi), ctypes.sizeof(pbi),
|
|
ctypes.byref(rl)) != 0 or not pbi.PebBaseAddress:
|
|
return ""
|
|
peb = ctypes.cast(pbi.PebBaseAddress, ctypes.c_void_p).value
|
|
pp_raw = _lese(k, h, peb + 0x20, 8) # PEB -> ProcessParameters
|
|
if not pp_raw:
|
|
return ""
|
|
pp = int.from_bytes(pp_raw, "little")
|
|
us = _lese(k, h, pp + 0x70, 16) # -> CommandLine (UNICODE_STRING)
|
|
if not us:
|
|
return ""
|
|
laenge = int.from_bytes(us[0:2], "little")
|
|
zeiger = int.from_bytes(us[8:16], "little")
|
|
if not laenge or not zeiger:
|
|
return ""
|
|
roh = _lese(k, h, zeiger, laenge)
|
|
return roh.decode("utf-16-le", "replace") if roh else ""
|
|
finally:
|
|
k.CloseHandle(h)
|
|
|
|
|
|
def _prozesse_nativ(name):
|
|
"""[(pid, kommandozeile)] per Toolhelp+PEB - None, wenn der Schnappschuss scheitert."""
|
|
try:
|
|
k = _k32()
|
|
nt = ctypes.WinDLL("ntdll", use_last_error=True)
|
|
nt.NtQueryInformationProcess.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p,
|
|
wintypes.ULONG, ctypes.POINTER(wintypes.ULONG)]
|
|
except OSError:
|
|
return None
|
|
treffer = _enum_pids(k, name.lower() if name else None)
|
|
if treffer is None:
|
|
return None
|
|
return [(pid, _kommandozeile(k, nt, pid)) for pid, _exe in treffer]
|
|
|
|
|
|
def prozesse(name=None):
|
|
"""Alle Prozesse als (pid, kommandozeile). `name` filtert auf einen Exe-Namen
|
|
(z.B. 'CoinPoker.exe'). Standard ist der native Weg (Toolhelp+PEB, ~160 ms); nur wenn
|
|
dessen Schnappschuss scheitert, uebernimmt WMI (`_prozesse_wmi`, ~10 s)."""
|
|
nativ = _prozesse_nativ(name)
|
|
if nativ is not None:
|
|
return nativ
|
|
return _prozesse_wmi(name)
|
|
|
|
|
|
def _prozesse_wmi(name=None):
|
|
"""Fallback: Kommandozeilen per PowerShell `Get-CimInstance Win32_Process`.
|
|
|
|
Windows-Falle: `subprocess.run(capture_output=True, timeout=...)` kann nach dem Timeout
|
|
EWIG haengen - `run` ruft nach dem Kill noch `communicate()` OHNE Frist, und dessen
|
|
Leser-Thread joint auf das stdout-Pipe-Ende, das ein Enkel (conhost) noch haelt (10.11.
|
|
gemessen: der Oeffnen-Faden stand >5 min in genau diesem join). Darum schreibt PowerShell
|
|
nach OBEN in eine Datei statt in eine Pipe: keine Leser-Threads, der Timeout greift, und
|
|
`kill()` kehrt sofort zurueck. CREATE_NO_WINDOW spart das conhost-Fenster."""
|
|
filt = f"-Filter \"Name='{name}'\"" if name else ""
|
|
befehl = _PS.format(filt=filt)
|
|
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
fd, pfad = tempfile.mkstemp(suffix=".json", prefix="winproc_")
|
|
roh = ""
|
|
try:
|
|
with open(fd, "w+b") as aus:
|
|
try:
|
|
p = subprocess.Popen(
|
|
["powershell", "-NoProfile", "-NonInteractive", "-Command", befehl],
|
|
stdout=aus, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
|
|
creationflags=flags)
|
|
except OSError:
|
|
return []
|
|
try:
|
|
p.wait(timeout=20)
|
|
except subprocess.TimeoutExpired:
|
|
try:
|
|
p.kill()
|
|
except OSError:
|
|
pass
|
|
return []
|
|
aus.seek(0)
|
|
roh = aus.read().decode("utf-8", "replace").strip()
|
|
finally:
|
|
try:
|
|
os.unlink(pfad)
|
|
except OSError:
|
|
pass
|
|
if not roh:
|
|
return []
|
|
try:
|
|
daten = json.loads(roh)
|
|
except ValueError:
|
|
return []
|
|
if isinstance(daten, dict): # ConvertTo-Json gibt bei EINEM Treffer kein Array
|
|
daten = [daten]
|
|
raus = []
|
|
for e in daten:
|
|
pid = e.get("ProcessId")
|
|
if isinstance(pid, int):
|
|
raus.append((pid, e.get("CommandLine") or ""))
|
|
return raus
|
|
|
|
|
|
def lebt(pid):
|
|
"""Laeuft der Prozess noch? NICHT-toetend: `os.kill(pid, 0)` wuerde ihn unter Windows mit
|
|
TerminateProcess beenden - hier nur fragen (OpenProcess + Exit-Code). ERROR_ACCESS_DENIED
|
|
heisst: es gibt ihn, er gehoert einem anderen Konto (zaehlt als lebt)."""
|
|
try:
|
|
pid = int(pid)
|
|
except (TypeError, ValueError):
|
|
return False
|
|
if pid <= 0:
|
|
return False
|
|
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
STILL_ACTIVE = 259
|
|
k = ctypes.windll.kernel32
|
|
k.OpenProcess.restype = ctypes.c_void_p
|
|
k.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]
|
|
k.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
k.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong)]
|
|
h = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
|
if not h:
|
|
return k.GetLastError() == 5 # ERROR_ACCESS_DENIED: existiert, fremdes Konto
|
|
try:
|
|
code = ctypes.c_ulong()
|
|
return bool(k.GetExitCodeProcess(h, ctypes.byref(code))) and code.value == STILL_ACTIVE
|
|
finally:
|
|
k.CloseHandle(h)
|
|
|
|
|
|
def toeten(pid):
|
|
"""Prozess beenden (TerminateProcess) - ohne Shell, ohne Fenster."""
|
|
PROCESS_TERMINATE = 0x0001
|
|
k = ctypes.windll.kernel32
|
|
k.OpenProcess.restype = ctypes.c_void_p
|
|
k.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]
|
|
k.TerminateProcess.argtypes = [ctypes.c_void_p, ctypes.c_uint]
|
|
k.CloseHandle.argtypes = [ctypes.c_void_p]
|
|
h = k.OpenProcess(PROCESS_TERMINATE, False, int(pid))
|
|
if not h:
|
|
return False
|
|
try:
|
|
return bool(k.TerminateProcess(h, 1))
|
|
finally:
|
|
k.CloseHandle(h)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
nadel = sys.argv[1] if len(sys.argv) > 1 else None
|
|
for pid, cmd in prozesse("CoinPoker.exe"):
|
|
if not nadel or nadel.lower() in cmd.lower():
|
|
print(pid, cmd[:160])
|