Files
WoW-Hybrid-gateway/ops/debug_client_owner.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

669 lines
49 KiB
Python

#!/usr/bin/env python3
"""Own the local test child for bounded, read-only executable-code diagnostics.
Code reads are bounded. The explicit experimental probe may redirect one real
Lua callback; no arbitrary heap/authentication dumps or code patches.
"""
import json
import os
from pathlib import Path
from client_installation import client_debug_socket
import socket
import sys
import hashlib
import zlib
import importlib.machinery
import struct
import subprocess
import time
import client_ui
from client_installation import window_arguments
ROOT=Path(__file__).resolve().parents[1]
SOCKET=client_debug_socket(ROOT)
BASE=0x140000000
PINNED_CLIENT_SHA256 = 'c49ce22c3e0aaeb7a7007a5c5cb792e4c3e6cdecc55a1145a5933fc113e3e57f'
# Original 70334 .pdata/CHAININFO ranges retained by the Map activation job.
# Only these named CODE windows may be read without OS execute permission.
FIXED_IMAGE_CODE_WINDOWS = {
'row-ingestion': (0x649130, 475),
'post-ingestion': (0x649070, 178),
'registry-getter': (0x64f0e0, 211),
# Observed type4 request-path fallthrough; exact retained CHAININFO bounds.
'lod2-type4-continuation': (0x20c341e, 101),
'c49-native-lua-adapter-page':(0x4597000,4096),
}
FIXED_CODE_FUNCTION_INDEX = 'ops/data/c49-original-function-chain-index.json.zlib'
FIXED_CODE_FUNCTION_INDEX_SHA256 = '3cafcb79a3b43bee43846a0607550ae04ed1640329cb2c977d4d5866589155d9'
def load_fixed_code_function_index(path):
"""Load the immutable original exception-metadata index once at startup."""
from types import MappingProxyType
raw = Path(path).read_bytes()
if hashlib.sha256(raw).hexdigest() != FIXED_CODE_FUNCTION_INDEX_SHA256:
raise RuntimeError('Fixed function index identity differs')
data = json.loads(zlib.decompress(raw))
if (set(data) != {'schema', 'image_sha256', 'image_base', 'max_read_bytes', 'windows'}
or data['schema'] != 'c49-original-function-chain-code-index-v1'
or data['image_sha256'] != PINNED_CLIENT_SHA256
or data['image_base'] != BASE or data['max_read_bytes'] != 65536
or not isinstance(data['windows'], dict) or not data['windows']):
raise RuntimeError('Fixed function index contract differs')
windows = {}
for selector, spans in data['windows'].items():
parts = selector.split('-') if isinstance(selector, str) else []
if (len(parts) != 3 or parts[0] != 'c49' or parts[1] not in ('entry', 'function')
or len(parts[2]) != 8 or any(c not in '0123456789abcdef' for c in parts[2])
or not isinstance(spans, list) or not spans):
raise RuntimeError('Invalid fixed function selector')
frozen = []
end = -1
for span in spans:
if (not isinstance(span, list) or len(span) != 2
or any(type(v) is not int for v in span)
or span[0] < end or span[0] < 0 or span[1] <= 0):
raise RuntimeError('Invalid fixed function spans')
frozen.append(tuple(span)); end = span[0] + span[1]
if sum(size for rva, size in frozen) > 65536:
raise RuntimeError('Fixed function exceeds bounded read size')
windows[selector] = tuple(frozen)
return MappingProxyType(windows)
def read_fixed_image_code_window(request, *, image_sha256, image_header, mappings, read_memory, function_windows=None):
if not isinstance(request, dict) or set(request) != {'operation', 'window'} or request.get('operation') != 'read-fixed-image-code':
raise RuntimeError('Invalid fixed code-window request')
selector = request['window']
if not isinstance(selector, str):
raise RuntimeError('Unknown fixed code-window selector')
if selector in FIXED_IMAGE_CODE_WINDOWS:
spans = (FIXED_IMAGE_CODE_WINDOWS[selector],)
elif function_windows is not None and selector in function_windows:
spans = function_windows[selector]
else:
raise RuntimeError('Unknown fixed code-window selector')
if image_sha256 != PINNED_CLIENT_SHA256:
raise RuntimeError('Fixed code-window image identity differs')
# Reuse the startup image identity; only the cached PE header is needed.
try:
if image_header[:2] != b'MZ':
raise ValueError('DOS signature')
pe = struct.unpack_from('<I', image_header, 0x3c)[0]
if image_header[pe:pe + 4] != b'PE\0\0':
raise ValueError('PE signature')
machine, section_count = struct.unpack_from('<HH', image_header, pe + 4)
optional_size = struct.unpack_from('<H', image_header, pe + 20)[0]
optional = pe + 24
if machine != 0x8664 or struct.unpack_from('<H', image_header, optional)[0] != 0x20b:
raise ValueError('PE architecture')
if struct.unpack_from('<Q', image_header, optional + 24)[0] != BASE:
raise ValueError('PE image base')
section_table = optional + optional_size
if not 1 <= section_count <= 32 or section_table + section_count * 40 > len(image_header):
raise ValueError('PE section bounds')
executable_sections = []
for index in range(section_count):
at = section_table + index * 40
name = image_header[at:at + 8].rstrip(b'\0')
virtual_size, start, raw_size = struct.unpack_from('<III', image_header, at + 8)
flags = struct.unpack_from('<I', image_header, at + 36)[0]
if name == b'.text' and flags & 0x20000000:
executable_sections.append((start, start + min(virtual_size, raw_size)))
except (ValueError, struct.error) as error:
raise RuntimeError('Invalid pinned code-window PE header') from error
# Validate every original interval before any memory I/O. Noncontiguous
# chains remain separate reads; the private output concatenates only them.
if not spans or sum(size for rva, size in spans) > 65536:
raise RuntimeError('Fixed function exceeds bounded read size')
for rva, size in spans:
if (type(rva) is not int or type(size) is not int or size <= 0
or not any(lo <= rva and rva + size <= hi for lo, hi in executable_sections)):
raise RuntimeError('Fixed window is outside executable PE code')
address = BASE + rva
readable = False
for line in mappings:
fields = line.split()
if len(fields) < 2:
continue
lo, hi = (int(value, 16) for value in fields[0].split('-'))
if lo <= address and address + size <= hi and 'r' in fields[1]:
readable = True
break
if not readable:
raise RuntimeError('Fixed code window is not fully readable')
parts = []
for rva, size in spans:
data = read_memory(BASE + rva, size)
if len(data) != size:
raise RuntimeError('Incomplete fixed code-window read')
parts.append(data)
return b''.join(parts)
def send_diagnostic_error(connection,error):
"""A timed-out observer must not terminate the client-owning debugger."""
try:
connection.sendall(('ERROR '+str(error)+'\n').encode())
except (BrokenPipeError,ConnectionResetError):
return False
return True
class CodeSampler:
"""Fixed login/dispatch executable pages only, never heap/authentication data."""
# Fixed code pages only. 0x0ed2000 contains the registered
# C_CharacterCreation.GetAvailableRaces callback at RVA 0x0ed2f30; the
# guarded image does not map it executable until the normal character-
# creation UI first uses that API. Sampling it remains read-only and does
# not invoke the callback.
RVAS=(0x1341000,0x15b9000,0x23f8000,0x242d000,0x242e000,0x91a000,0x1e46000,0x1e47000,0x0ed2000,0x0ed3000,0x0f301000,0x22b8000)
def __init__(self,pid):
self.pid=pid;self.saved={rva:set() for rva in self.RVAS}
self.output=ROOT/'runtime/native-login-code';self.output.mkdir(exist_ok=True,mode=0o700)
def sample(self):
maps=Path(f'/proc/{self.pid}/maps').read_text().splitlines()
intervals=[]
for line in maps:
parts=line.split();lo,hi=(int(v,16) for v in parts[0].split('-'))
if parts[1].startswith('r') and 'x' in parts[1]:intervals.append((lo,hi))
fd=os.open(f'/proc/{self.pid}/mem',os.O_RDONLY)
try:
for rva in self.RVAS:
address=BASE+rva
if len(self.saved[rva])>=4 or not any(lo<=address and address+4096<=hi for lo,hi in intervals):continue
data=os.pread(fd,4096,address)
if len(data)!=4096:continue
digest=hashlib.sha256(data).hexdigest()
if digest in self.saved[rva]:continue
path=self.output/f'{address:x}-{digest[:16]}.bin';path.write_bytes(data);path.chmod(0o600)
self.saved[rva].add(digest)
finally:os.close(fd)
def start_exact_regional_registration(pid, *, clean_copy, poll_host, probe):
"""Reuse the bounded registration observer only in an owned ready world."""
if not clean_copy or not poll_host or (probe is not None and (probe.attached or not probe.done)):
raise RuntimeError('Exact registration observation requires an idle owned poll-host child')
import engine_channel_policy_host
from native_test_guard import require_native_gameplay_policy
policy=engine_channel_policy_host.inspect(pid)
require_native_gameplay_policy(policy)
if policy.get('owner_matches') is not True:
raise RuntimeError('Exact registration observation requires the current native owner')
import engine_pipe_host
pipe=engine_pipe_host.inspect(pid)
world=pipe.get('world')
if pipe.get('closed')!=0 or pipe.get('error')!=0 or pipe.get('world_auth')!=1 or not isinstance(world,dict) or world.get('login_sent')!=1 or world.get('self_create')!=1:
raise RuntimeError('Exact registration observation requires the authenticated current world')
from native_registration_trace import RegistrationTrace
result=ROOT/'runtime'/('native-registration-regional-'+str(pid)+'.json')
observer=RegistrationTrace(pid,exact_regional_global=True,owned_image_path=ROOT/'runtime/native-client/_classic_beta_/WowB.exe',result_path=result)
return observer,dict(kind='exact-regional-registration',pid=pid,status='started-not-yet-armed',result=str(result),credentials_submitted=False,code_bytes_modified=False)
def start_early_spellbook_registration(pid, *, clean_copy, poll_host, native_roster, lifecycle_identity, namespace_whitelist=None):
"""Read-only initial-child observation, separate from all input admission."""
if not clean_copy or not poll_host:
raise RuntimeError('Early spellbook registration requires the owned poll-host launch')
import native_client_lifecycle as lifecycle
current=lifecycle.read_launch(ROOT,pid)
if current is None or current!=lifecycle_identity:
raise RuntimeError('Early spellbook registration requires the current launch identity')
from native_registration_trace import RegistrationTrace
result=ROOT/'runtime'/(('native-registration-realm-' if namespace_whitelist is not None else 'native-registration-spellbook-')+current['launch_id']+'.json')
observer=RegistrationTrace(pid,exact_spellbook_tooltip=namespace_whitelist is None,namespace_whitelist=namespace_whitelist,
owned_image_path=ROOT/'runtime/native-client/_classic_beta_/WowB.exe',result_path=result)
observer.owned_lifetime=current
return observer,dict(kind=('early-exact-realm-registration' if namespace_whitelist is not None else 'early-exact-spellbook-registration'),pid=pid,
status='started-not-yet-armed',launch_id=current['launch_id'],native_starttime=current['native_starttime'],
result=str(result),credentials_submitted=False,code_bytes_modified=False)
def serve(experimental=False,clean_copy=False,local_trust=False,poll_host=False,native_roster=False,early_spellbook_registration=False,early_realm_registration=False):
if early_spellbook_registration and early_realm_registration:raise RuntimeError('Choose one early registration observer scope')
if (early_spellbook_registration or early_realm_registration) and (experimental or not clean_copy or not poll_host):
raise RuntimeError('Early spellbook registration requires the owned poll-host launch')
fixed_code_identity = None
fixed_code_header = b''
fixed_code_functions = None
if SOCKET.exists():raise RuntimeError('Debug owner already present; inspect it before restarting')
server=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);server.bind(str(SOCKET));SOCKET.chmod(0o600);server.listen(1)
if clean_copy:
from client_installation import COPY,inspect_installation,running_clients
if running_clients(owned_only=True):raise RuntimeError('Existing owned WowB preserved; close normally before clean diagnostic launch')
identity=inspect_installation(COPY)
if identity['files']['_classic_beta_/WowB.exe']['sha256']!=PINNED_CLIENT_SHA256:raise RuntimeError('Require pinned clean client')
fixed_code_identity = identity['files']['_classic_beta_/WowB.exe']['sha256']
with (COPY / '_classic_beta_/WowB.exe').open('rb') as image:
fixed_code_header = image.read(4096)
fixed_code_functions = load_fixed_code_function_index(ROOT / FIXED_CODE_FUNCTION_INDEX)
manifest=json.loads((ROOT/'runtime/native-engine-pe.json').read_text())
if bool(manifest.get('restored'))==poll_host:raise RuntimeError('Private dependency mode differs from requested diagnostic host')
dependency=ROOT/'runtime/native-wine-prefix/drive_c/windows/system32/d3d11.dll'
expected_dependency=manifest['dependency_patched_sha256'] if poll_host else manifest['dependency_baseline_sha256']
if hashlib.sha256(dependency.read_bytes()).hexdigest()!=expected_dependency:raise RuntimeError('Private graphics dependency identity differs')
if poll_host and hashlib.sha256((dependency.parent/'GWNativeBridge.dll').read_bytes()).hexdigest()!=manifest['dll_sha256']:raise RuntimeError('Owned poll-host module identity differs')
if poll_host:
for auxiliary in manifest.get('auxiliary_dependencies',[]):
if auxiliary.get('file')!='GWNativeWire.dll':raise RuntimeError('Unknown auxiliary dependency')
path=dependency.parent/auxiliary['file']
if path.is_symlink() or hashlib.sha256(path.read_bytes()).hexdigest()!=auxiliary['sha256']:raise RuntimeError('Owned auxiliary identity differs')
peer=manifest.get('wire_unix_library')
if peer:
for field,name in (('wire_unix','libgateway_wine_wire.so'),('core','libgateway_native.so'),('source_codec','forever-schema/libforever_codec.so')):
path=Path(peer[field+'_path'])
if path!=ROOT/'build'/name or hashlib.sha256(path.read_bytes()).hexdigest()!=peer[field+'_sha256']:raise RuntimeError('Owned Unix dependency identity differs')
env=dict(os.environ,WINEPREFIX=str(ROOT/'runtime/native-wine-prefix'),WINEDEBUG='-all')
for key in ('LD_PRELOAD','GW_NATIVE_BOOTSTRAP','GW_NATIVE_EXPECTED_EXE'):env.pop(key,None)
if native_roster:
config=ROOT/'secrets/native-roster-host.json';options=json.loads(config.read_text())
if not options.get('engine_packet_host') or any(options.get(key) for key in ('native_registration','engine_bridge_probe','engine_registration_trace')):raise RuntimeError('Native roster host must not enable Lua probes')
check=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
if check.connect_ex(('127.0.0.1',19085))==0:raise RuntimeError('Stop external gateway before native roster test')
finally:check.close()
env.update(LD_PRELOAD=str(ROOT/'build/libgateway_native_bootstrap.so'),GW_NATIVE_BOOTSTRAP=str(config),GW_NATIVE_EXPECTED_EXE=str(COPY/'_classic_beta_/WowB.exe'))
with (ROOT/'runtime/engine-session-client.log').open('ab') as log:
child=subprocess.Popen(['wine',str(COPY/'_classic_beta_/WowB.exe'),'-console',*window_arguments(COPY),'-d3d11'],cwd=COPY/'_classic_beta_',env=env,stdout=log,stderr=log,start_new_session=True)
pid=child.pid
(ROOT/'runtime/native-client.pid').write_text(str(pid))
elif experimental:
from native_local_test import COPY,CONFIG
options=json.loads(CONFIG.read_text())
prefix=client_ui.PREFIX
if options.get('engine_bridge_probe'):
manifest=json.loads((ROOT/'runtime/native-engine-pe.json').read_text())
if manifest.get('wine_prefix'):
prefix=Path(manifest['wine_prefix']).resolve()
if prefix!=ROOT/'runtime/native-wine-prefix':raise RuntimeError('Unexpected diagnostic Wine prefix')
env=dict(os.environ,WINEPREFIX=str(prefix),WINEDEBUG='-all',
LD_PRELOAD=str(ROOT/'build/libgateway_native_bootstrap.so'),
GW_NATIVE_BOOTSTRAP=str(CONFIG),GW_NATIVE_EXPECTED_EXE=str(COPY/'_classic_beta_/WowB.exe'))
env.pop('GW_NATIVE_REGISTER',None)
with (ROOT/'runtime/native-client.log').open('ab') as log:
child=subprocess.Popen(['wine',env['GW_NATIVE_EXPECTED_EXE'],'-console',*window_arguments(COPY),'-d3d11'],cwd=COPY/'_classic_beta_',env=env,stdout=log,stderr=log,start_new_session=True)
pid=child.pid;(ROOT/'runtime/native-client.pid').write_text(str(pid))
else:
child=client_ui.launch()
if child is None:raise RuntimeError('Existing client preserved; no diagnostic child')
pid=child.pid
server.settimeout(.1 if experimental else 1.0)
sampler=CodeSampler(pid) if experimental or clean_copy else None
import native_client_lifecycle as lifecycle
try:lifecycle_identity=lifecycle.begin(ROOT,pid)
except (OSError,ValueError,TypeError,IndexError):lifecycle_identity=None
def retain_child_exit(witness):
if lifecycle_identity is None:return
try:lifecycle.record_exit(ROOT,lifecycle_identity,witness)
except (OSError,ValueError,TypeError,IndexError):pass
probe=None
retirement_intent={} # Metadata only; never original input descriptors/payloads.
if early_spellbook_registration or early_realm_registration:
probe,report=start_early_spellbook_registration(pid,clean_copy=clean_copy,poll_host=poll_host,
native_roster=native_roster,lifecycle_identity=lifecycle_identity,
namespace_whitelist=['C_Login','C_RealmList'] if early_realm_registration else None)
path=ROOT/'runtime/native-registration-spellbook-launch.json'
path.write_text(json.dumps(report,indent=2)+'\n');path.chmod(0o600)
elif experimental:
options=json.loads(CONFIG.read_text())
if options.get('engine_bridge_probe'):
if options.get('native_registration'):
from native_namespace_probe import NamespaceProbe
probe=NamespaceProbe(pid)
elif options.get('engine_registration_trace'):
from native_registration_trace import RegistrationTrace
probe=RegistrationTrace(pid)
else:
from engine_main_thread_probe import Probe
probe=Probe(pid,wait_for_window=True)
# Reuse the existing reviewed public-key patch implementation, confined to
# this exact child. The root service and its original target stay unchanged.
trust=importlib.machinery.SourceFileLoader('local_trust_reference','/usr/local/bin/forever70334-autopatch').load_module() if experimental or local_trust else None
next_scan=0;table=None;next_sample=0
print('Code diagnostic owner ready; child pid',pid,flush=True)
try:
while True:
if probe:
try:probe.poll()
except (OSError,RuntimeError,ValueError) as error:
reasons=('Bridge outside owned executable module','Callback outside pinned PE code range','Host register ABI mismatch')
probe.record('probe-error',error_type=type(error).__name__,errno=getattr(error,'errno',None),reason=str(error) if str(error) in reasons else 'owned-child-operation-failed')
probe.cancel();probe.done=True
# Popen.poll must not consume a ptrace stop as process termination.
observed_exit=getattr(probe,'observed_child_exit',None) if probe else None
if observed_exit is not None:
retain_child_exit(observed_exit)
child.returncode=os.waitstatus_to_exitcode(observed_exit[1])
break
if not (probe and probe.attached):
observed_exit=lifecycle.poll_owned_child(child)
if observed_exit is not None:
if observed_exit is not lifecycle.UNKNOWN_EXIT:retain_child_exit(observed_exit)
break
# A guarded PE can legitimately generate many first-use Wine
# exceptions. Keep the tracing loop responsive and forward them;
# do not spend100ms/socket wait or scan memory at every stop.
tracing=bool(probe and probe.attached)
server.settimeout(.001 if tracing else (.1 if experimental else 1.0))
if sampler and not tracing and time.monotonic()>=next_sample:
next_sample=time.monotonic()+.5
try:sampler.sample()
except OSError:pass # PE pages are constructed during Wine startup.
if trust and not tracing and time.monotonic()>=next_scan:
next_scan=time.monotonic()+3
try:
if trust.is_target(pid,os.getuid(),str(ROOT/'runtime/native-client/_classic_beta_/WowB.exe')):
if table is None:table=trust.single_pass(pid)
elif trust.inspect_known_table(pid,table)=='original':trust.safe_patch(pid,table)
except OSError:pass
try:connection,_=server.accept()
except socket.timeout:continue
with connection:
connection.settimeout(2) # Never strand an attached child on a silent diagnostic peer.
try:
request=json.loads(connection.recv(1024))
if request.get('operation')=='observe-original-relogin-intent':
if not clean_copy or not poll_host or (probe is not None and (probe.attached or not probe.done)):
raise RuntimeError('Relogin intent requires idle owned poll-host child')
import engine_login_input_binding,engine_session_retirement
handoff=importlib.reload(engine_login_input_binding)
retirement=importlib.reload(engine_session_retirement)
profile=request.get('profile');handoff.prepare_context(profile)
retirement.inspect(pid) # Require the new owned ABI before arming.
arm_seconds=request.get('arm_seconds',300)
if type(arm_seconds)is not int or not 1<=arm_seconds<=300:raise ValueError('Manual intent arm bound1..300seconds')
retirement_intent.clear()
def observed_relogin(actual,registers):
handoff.isolated_modern_fallback()
facts=retirement.observe_intent(actual,registers)
retirement_intent['value']=facts
return facts
plan=ROOT/'runtime/original-relogin-intent-plan.json'
result=ROOT/'runtime/original-relogin-intent.json'
plan.write_text(json.dumps({'pid':pid,'login_callback':hex(handoff.ENTRY),'bridge_callback':'0x0'}));plan.chmod(0o600)
from engine_main_thread_probe import Probe
probe=Probe(pid,observe_only=True,plan_path=plan,result_path=result,armed_timeout=arm_seconds,
metadata_at_observation=observed_relogin)
connection.sendall(b'OK\noriginal-relogin-intent-armed\n');continue
if request.get('operation')=='request-native-session-retirement':
if(not clean_copy or not poll_host or probe is None or probe.attached or not probe.done or
retirement_intent.get('consumed')or not retirement_intent.get('value')):
raise RuntimeError('Fresh completed original Login intent required')
record=json.loads(probe.result_path.read_text())
if(record.get('pid')!=pid or record.get('status')!='real-callback-observed-only'or
record.get('hardware_registers_restored')is not True or
record.get('metadata')!=retirement_intent['value']):
raise RuntimeError('Original Login observation not restored/verified')
import engine_session_retirement
retirement_intent['consumed']=True # Consume before any native request write.
result=importlib.reload(engine_session_retirement).request(pid,retirement_intent['value'])
retirement_intent['request']=result
connection.sendall(b'OK\n'+json.dumps(result).encode());continue
if request.get('operation')=='inspect-native-session-retirement':
if not clean_copy or not poll_host:raise RuntimeError('Retirement inspection requires owned poll-host child')
import engine_session_retirement
result=importlib.reload(engine_session_retirement).inspect(pid)
connection.sendall(b'OK\n'+json.dumps(result).encode());continue
if request.get('operation')=='finalize-native-session-retirement':
if(not clean_copy or not poll_host or not retirement_intent.get('request')or retirement_intent.get('finalized')):
raise RuntimeError('One exact outstanding retirement request required')
import engine_session_retirement
result=importlib.reload(engine_session_retirement).finalize(pid,retirement_intent['request'])
retirement_intent['finalized']=True
connection.sendall(b'OK\n'+json.dumps(result).encode());continue
if request.get('operation') in ('bind-original-local-login','bind-original-login'):
if not clean_copy or not poll_host or (probe is not None and (probe.attached or not probe.done)):
raise RuntimeError('Original local Login requires idle owned poll-host child')
import engine_login_input_binding
handoff=importlib.reload(engine_login_input_binding)
profile='local' if request['operation']=='bind-original-local-login' else request.get('profile')
arm_seconds=request.get('arm_seconds',300 if profile=='octo' else 8)
if type(arm_seconds)is not int or not 1<=arm_seconds<=300:
raise ValueError('Manual original-login arm bound1..300seconds')
context=handoff.prepare_context(profile)
stem='original-octo-login-binding' if profile=='octo' else 'original-local-login-binding'
plan=ROOT/'runtime'/(stem+'-plan.json')
result=ROOT/'runtime'/(stem+'.json')
plan.write_text(json.dumps({'pid':pid,'login_callback':hex(handoff.ENTRY),'bridge_callback':'0x0'}));plan.chmod(0o600)
from engine_main_thread_probe import Probe
probe=Probe(pid,observe_only=True,plan_path=plan,result_path=result,armed_timeout=arm_seconds,
register_data_binding=lambda actual,registers:handoff.capture(actual,registers,context=context))
connection.sendall(b'OK\noriginal-local-login-binding-armed\n');continue
if request.get('operation')=='observe-exact-regional-registration':
probe,report=start_exact_regional_registration(pid,clean_copy=clean_copy,poll_host=poll_host,probe=probe)
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='request-native-channel-policy':
if not clean_copy or not poll_host or (probe is not None and (probe.attached or not probe.done)):
raise RuntimeError('Native policy request requires idle owned poll-host child')
import engine_channel_policy_host
report=importlib.reload(engine_channel_policy_host).request_enable(pid)
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='select-native-realm':
if not clean_copy or not poll_host or (probe is not None and (probe.attached or not probe.done)):
raise RuntimeError('Realm selection requires idle owned account worker')
import engine_wire_host
engine_wire_host.select_realm(pid,request.get('index'))
connection.sendall(b'OK\nreal-discovered-realm-selected\n');continue
if request.get('operation')=='resolve-native-ui-realm-request':
if not clean_copy or not poll_host or (probe is not None and (probe.attached or not probe.done)):
raise RuntimeError('UI realm acknowledgement requires idle owned account worker')
import engine_wire_host
engine_wire_host.resolve_ui_realm_request(pid,request.get('request'),request.get('error',0))
connection.sendall(b'OK\nowned-ui-proposal-acknowledged\n');continue
if request.get('operation')=='observe-character-data-ready':
if not clean_copy or (probe is not None and (probe.attached or not probe.done)):raise RuntimeError('Readiness watch requires idle owned private child')
import engine_readiness_watch
probe=importlib.reload(engine_readiness_watch).Watch(pid,timeout=30,component=request.get('component','character-order'))
connection.sendall(b'OK\npublic-readiness-watch-armed\n');continue
if request.get('operation')=='observe-race-class-table':
if not clean_copy or (probe is not None and (probe.attached or not probe.done)):raise RuntimeError('Race/class table watch requires idle owned private child')
import engine_race_class_watch
probe=importlib.reload(engine_race_class_watch).Watch(pid,timeout=8)
connection.sendall(b'OK\npublic-race-class-table-watch-armed\n');continue
if request.get('operation') in ('observe-realm-adoption','observe-engine-boundary'):
if not clean_copy or (probe is not None and (probe.attached or not probe.done)):raise RuntimeError('Boundary observation requires idle owned child')
boundary='realm-adoption' if request['operation']=='observe-realm-adoption' else request.get('boundary')
import engine_boundary_catalog
observer,stem=importlib.reload(engine_boundary_catalog).load(boundary)
address=observer.ENTRY
maps=Path(f'/proc/{pid}/maps').read_text().splitlines()
cold=engine_boundary_catalog.natural_first_use(boundary,address,observer)
# Fixed cold profiles merely arm hardware observation of
# normal first execution. No entry read/call/protection
# change occurs before the engine maps/decrypts it.
if not cold and not any(int(line.split()[0].split('-')[0],16)<=address<int(line.split()[0].split('-')[1],16) and 'x' in line.split()[1] for line in maps):raise RuntimeError('Boundary not naturally executable; no probe armed')
if not cold:
fd=os.open(f'/proc/{pid}/mem',os.O_RDONLY)
try:prefix=os.pread(fd,len(observer.PREFIX),address)
finally:os.close(fd)
if prefix!=observer.PREFIX:raise RuntimeError('Boundary entry identity differs; no probe armed')
plan=ROOT/'runtime'/(stem+'-plan.json')
result=ROOT/'runtime'/(stem+'.json')
target_pid=pid
thread=request.get('thread','main')
if thread in ('network','protocol') and boundary in ('resume-comms','resume-deferred'):
from engine_observation_thread import network_thread
target_pid=network_thread(pid,name='bs Network' if thread=='network' else 'NetThread 0')
elif thread!='main':raise RuntimeError('Unverified boundary/thread combination')
create_route_only=request.get('create_route_only',False)
if type(create_route_only) is not bool or (create_route_only and (boundary!='packet-send-route' or thread!='main')):raise RuntimeError('Fixed create route observation required')
plan.write_text(json.dumps({'pid':target_pid,'login_callback':hex(address),'bridge_callback':'0x0'}));plan.chmod(0o600)
from engine_main_thread_probe import Probe
# A fresh SRP plus native roster can take several
# measured seconds; keep this fixed copy-path probe
# alive long enough to span one controlled reconnect.
timeout=45 if boundary in ('race-class-vector-copy','resume-comms','resume-deferred') else 8
probe=Probe(target_pid,observe_only=True,plan_path=plan,result_path=result,armed_timeout=timeout,metadata_at_observation=observer.capture,create_route_only=create_route_only)
connection.sendall(b'OK\nrealm-observation-armed\n' if request['operation']=='observe-realm-adoption' else b'OK\nboundary-observation-armed\n');continue
if request.get('operation') in ('observe-engine-queue','install-engine-poll-host','install-engine-packet-host','install-engine-wire-ping','activate-source-realm-ui','start-engine-wire-account','probe-engine-wire-channel','open-native-engine-realm','open-native-engine-realm-with-pipe','restore-engine-pipe','restore-engine-poll-host','install-engine-listener-observer','restore-engine-listener-observer','enable-native-channel-policy','disable-native-channel-policy'):
if not clean_copy or (probe is not None and (probe.attached or not probe.done)):raise RuntimeError('Queue observation requires an idle owned clean child')
address=0x141e53d80
maps=Path(f'/proc/{pid}/maps').read_text().splitlines()
if not any(int(line.split()[0].split('-')[0],16)<=address<int(line.split()[0].split('-')[1],16) and 'x' in line.split()[1] for line in maps):raise RuntimeError('Known queue entry is not executable; no probe armed')
fd=os.open(f'/proc/{pid}/mem',os.O_RDONLY)
try:prefix=os.pread(fd,11,address)
finally:os.close(fd)
if prefix!=bytes.fromhex('4c8bdc534881ec80000000'):raise RuntimeError('Queue-entry code identity differs; no probe armed')
action=request['operation'];binding=None;followup=None
if action!='observe-engine-queue':
if not poll_host:raise RuntimeError('Data binding requires the explicit poll-host launch mode')
import engine_poll_host
if action in ('enable-native-channel-policy','disable-native-channel-policy'):
import engine_channel_policy_host
binding=engine_channel_policy_host.enable if action.startswith('enable') else engine_channel_policy_host.disable
elif action=='restore-engine-pipe':
import engine_pipe_host
binding=engine_pipe_host.restore
elif action in ('install-engine-listener-observer','restore-engine-listener-observer'):
import engine_listener_host
binding=engine_listener_host.install if action=='install-engine-listener-observer' else engine_listener_host.restore
elif action in ('install-engine-wire-ping','activate-source-realm-ui','start-engine-wire-account','probe-engine-wire-channel','open-native-engine-realm','open-native-engine-realm-with-pipe'):
import engine_wire_host
binding={'install-engine-wire-ping':engine_wire_host.install_ping,'activate-source-realm-ui':(lambda actual,point,readiness=request.get('readiness'):engine_wire_host.activate_realm_ui(actual,point,readiness=readiness)),'start-engine-wire-account':engine_wire_host.start_account,'probe-engine-wire-channel':engine_wire_host.probe_channel,'open-native-engine-realm':engine_wire_host.open_engine_realm,'open-native-engine-realm-with-pipe':engine_wire_host.open_engine_realm}[action]
if action=='open-native-engine-realm-with-pipe':
import engine_pipe_host
binding=engine_wire_host.preflight_pipe_open(pid)
followup=(engine_pipe_host.ENTRY,engine_pipe_host.PREFIX,engine_pipe_host.bind_setup_return)
else:binding=engine_poll_host.install if action=='install-engine-poll-host' else engine_poll_host.install_packet if action=='install-engine-packet-host' else engine_poll_host.restore
plan=ROOT/'runtime/engine-queue-trace-plan.json'
result=ROOT/'runtime'/('engine-queue-trace.json' if binding is None else action+'-trace.json')
plan.write_text(json.dumps({'pid':pid,'login_callback':hex(address),'bridge_callback':'0x0'}));plan.chmod(0o600)
from engine_main_thread_probe import Probe
probe=Probe(pid,observe_only=True,plan_path=plan,result_path=result,armed_timeout=3,at_observation=binding,followup=followup,followup_natural_first_use=action=='open-native-engine-realm-with-pipe')
connection.sendall(b'OK\nqueue-observation-armed\n');continue
if request.get('operation') in ('inspect-wire-frame','inspect-wire-account','inspect-native-engine-realm'):
if not clean_copy or not poll_host:raise RuntimeError('Wire inspection requires owned poll-host child')
import engine_wire_host
module=importlib.reload(engine_wire_host)
report={'inspect-wire-frame':module.inspect,'inspect-wire-account':module.inspect_account,'inspect-native-engine-realm':module.inspect_engine_realm}[request['operation']](pid)
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='observe-map-lod-role4-cell':
import map_lod_cell_trace
probe,report=map_lod_cell_trace.start(pid,clean_copy=clean_copy,existing_probe=probe)
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='inspect-engine-pipe':
if not clean_copy or not poll_host:raise RuntimeError('Pipe inspection requires owned poll-host child')
import engine_pipe_host
report=importlib.reload(engine_pipe_host).inspect(pid,request.get('entity_offset',0),request.get('unit_fields_only',False))
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='inspect-native-channel-policy':
if not clean_copy or not poll_host:raise RuntimeError('Channel diagnostics require owned native host')
import engine_channel_policy_host
report=engine_channel_policy_host.inspect(pid)
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='inspect-engine-listener':
if not clean_copy or not poll_host:raise RuntimeError('Listener observation requires owned poll-host child')
import engine_listener_host
report=importlib.reload(engine_listener_host).inspect(pid)
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='inspect-engine-session':
if not clean_copy:raise RuntimeError('Public session inspection requires the clean owned child')
# This fixed read-only diagnostic module can be updated
# without another game restart while tracing the ABI.
import engine_session_inspect
inspect=importlib.reload(engine_session_inspect).inspect
intervals=[]
for line in Path(f'/proc/{pid}/maps').read_text().splitlines():
fields=line.split();lo,hi=(int(v,16) for v in fields[0].split('-'))
intervals.append((lo,hi,fields[1]))
def mapped(address,size,execute=False):
return size>=0 and any(lo<=address and address+size<=hi and permissions.startswith('r') and (not execute or 'x' in permissions) for lo,hi,permissions in intervals)
fd=os.open(f'/proc/{pid}/mem',os.O_RDONLY)
try:
def bounded_read(address,size):
if size>512 or not mapped(address,size):raise ValueError('Fixed metadata read is unmapped')
data=os.pread(fd,size,address)
if len(data)!=size:raise ValueError('Short metadata read')
return data
packet_layout=None
if poll_host:
exports=json.loads((ROOT/'runtime/native-engine-pe.json').read_text())['exports']
if all(0<exports.get(key,0)<0x20000 for key in ('gw_packet_poll_callback','gw_packet_receive_callback','gw_packet_host_data')):packet_layout=exports
report=inspect(bounded_read,lambda address,size:mapped(address,size,True),packet_layout)
finally:os.close(fd)
connection.sendall(b'OK\n'+json.dumps(report).encode());continue
if request.get('operation')=='rearm-engine-probe':
if not experimental or probe is None or probe.attached or not probe.done:raise RuntimeError('Only an inactive opt-in experimental probe can be rearmed')
from engine_main_thread_probe import Probe
probe=Probe(pid,wait_for_window=True)
connection.sendall(b'OK\nprobe-rearmed\n');continue
if request.get('operation') == 'read-fixed-image-code':
def fixed_memory_read(address, size):
fd = os.open(f'/proc/{pid}/mem', os.O_RDONLY)
try:
return os.pread(fd, size, address)
finally:
os.close(fd)
data = read_fixed_image_code_window(
request, image_sha256=fixed_code_identity,
image_header=fixed_code_header,
mappings=Path(f'/proc/{pid}/maps').read_text().splitlines(),
read_memory=fixed_memory_read, function_windows=fixed_code_functions)
connection.sendall(b'OK\n' + data)
continue
rva=int(request['rva']);size=int(request.get('size',1024));address=BASE+rva
if not 0<=rva<0x5000000 or not 1<=size<=65536:raise RuntimeError('Code read outside bounded image range')
maps=Path(f'/proc/{pid}/maps').read_text().splitlines();allowed=False
for line in maps:
fields=line.split();lo,hi=[int(v,16) for v in fields[0].split('-')]
if lo<=address and address+size<=hi and 'x' in fields[1]:allowed=True;break
if not allowed:raise RuntimeError('Requested range is not executable client code')
fd=os.open(f'/proc/{pid}/mem',os.O_RDONLY)
try:data=os.pread(fd,size,address)
finally:os.close(fd)
if len(data)!=size:raise RuntimeError('Incomplete executable-code read')
connection.sendall(b'OK\n'+data)
except Exception as error:send_diagnostic_error(connection,error)
finally:
if probe:probe.cancel()
SOCKET.unlink(missing_ok=True)
def read():
rva=int(sys.argv[2],0);size=int(sys.argv[3],0)
output=Path(sys.argv[4]).resolve()
if not output.is_relative_to(ROOT/'runtime'):raise RuntimeError('Code diagnostics must stay in ignored runtime')
connection=socket.socket(socket.AF_UNIX,socket.SOCK_STREAM);connection.connect(str(SOCKET))
connection.sendall(json.dumps({'rva':rva,'size':size}).encode());data=b''
while chunk:=connection.recv(65536):data+=chunk
connection.close()
if not data.startswith(b'OK\n'):raise RuntimeError(data.decode(errors='replace'))
output.write_bytes(data[3:]);output.chmod(0o600);print('Read executable-code bytes:',len(data)-3,'; private output:',output)
def read_fixed_code():
if len(sys.argv) != 4:
raise RuntimeError('Use read-fixed-code WINDOW runtime/OUTPUT')
output = Path(sys.argv[3]).resolve()
if not output.is_relative_to(ROOT / 'runtime'):
raise RuntimeError('Fixed code output must remain under runtime')
connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
connection.connect(str(SOCKET))
connection.sendall(json.dumps({'operation': 'read-fixed-image-code', 'window': sys.argv[2]}).encode())
data = b''
while True:
part = connection.recv(65536)
if not part:
break
data += part
finally:
connection.close()
if not data.startswith(b'OK\n'):
raise RuntimeError(data.decode(errors='replace'))
output.write_bytes(data[3:])
output.chmod(0o600)
print('Read fixed pinned-image code bytes:', len(data) - 3, '; private output:', str(output))
def rearm():
with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as connection:
connection.settimeout(5);connection.connect(str(SOCKET));connection.sendall(b'{"operation":"rearm-engine-probe"}')
response=connection.recv(1024)
if response!=b'OK\nprobe-rearmed\n':raise RuntimeError('Inactive-probe rearm rejected')
print('Rearmed bounded read-only engine probe; active client session reused.')
if __name__=='__main__':
if sys.argv[1]=='serve':serve()
elif sys.argv[1]=='serve-copy':serve(True)
elif sys.argv[1]=='serve-clean-copy':serve(clean_copy=True)
elif sys.argv[1]=='serve-reference-copy':serve(clean_copy=True,local_trust=True)
elif sys.argv[1]=='serve-poll-host':serve(clean_copy=True,poll_host=True)
elif sys.argv[1]=='serve-poll-host-tooltip-registration':serve(clean_copy=True,poll_host=True,early_spellbook_registration=True)
elif sys.argv[1]=='serve-poll-host-realm-registration':serve(clean_copy=True,poll_host=True,early_realm_registration=True)
elif sys.argv[1]=='serve-reference-poll-host':serve(clean_copy=True,poll_host=True,local_trust=True)
elif sys.argv[1]=='serve-native-roster-host':serve(clean_copy=True,poll_host=True,native_roster=True)
elif sys.argv[1]=='serve-native-roster-host-tooltip-registration':serve(clean_copy=True,poll_host=True,native_roster=True,early_spellbook_registration=True)
elif sys.argv[1]=='serve-native-roster-host-realm-registration':serve(clean_copy=True,poll_host=True,native_roster=True,early_realm_registration=True)
elif sys.argv[1]=='read':read()
elif sys.argv[1]=='read-fixed-code':read_fixed_code()
elif sys.argv[1]=='probe':rearm()
else:raise RuntimeError('Use serve, or read RVA SIZE runtime/OUTPUT')