Files
WoW-Hybrid-gateway/ops/engine_channel_policy_host.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

272 lines
17 KiB
Python

"""Data-only opt-in for authenticated, one-world-stream Turtle queue routing.
No instruction patch, route-register edit, connection alias or auth-state write.
The DLL calls only the source-audited original send/destroy/release contracts.
"""
import hashlib,json,os,struct,time,ntpath
from pathlib import Path
import native_runtime_paths
import engine_poll_host as host
import engine_wire_host as wire
import engine_pipe_host
ROOT=Path(__file__).resolve().parents[1]
_WINDOWS=os.name=='nt'
SIZE=48
TARGETS=((0x141e46a80,'405657415441554883ec68'),
(0x1445b7db0,'48895c2408574883ec2041833800'),
(0x14452a5d0,'48895c241048896c2418'))
def enable(pid,caller):
host.require_safepoint(caller)
from native_lifecycle_audit import audit
audit() # Fixed source contracts, not permission to skip actual ownership.
proof=json.loads((ROOT/'docs/evidence/gameplay/reference-instance-deferred-buffer-contract.json').read_text())
if proof.get('status')!='real-callback-observed-only' or not proof.get('hardware_registers_restored') or proof.get('metadata',{}).get('cursor')!=16:raise ValueError('Original live buffer contract missing')
access=host.Access(pid)
try:
base,info,_=wire.module(access);data=base+info['exports']['gw_wire_channel_policy']
if access.read(data,8)!=struct.pack('<2I',1,SIZE) or any(access.read(data+8,SIZE-8)):raise ValueError('Native channel policy must be idle')
owner=access.u64(0x145e7a098)
pipe=engine_pipe_host.inspect(pid)
if pipe['error'] or pipe['closed'] or not pipe['world_auth'] or not pipe['world']['login_sent'] or not pipe['world']['self_create']:raise ValueError('Require real authenticated native world')
if struct.unpack('<I',access.read(owner+0x98,4))[0]!=5 or access.read(owner+0x218,2)!=b'\0\1':raise ValueError('Native channel lifecycle differs')
connections=struct.unpack('<4Q',access.read(owner+0x1a0,32))
if not connections[0] or connections[1] or connections[3]:raise ValueError('Require sole authenticated native realm transport')
for address,value in TARGETS:
prefix=bytes.fromhex(value)
if not access.allowed(address,len(prefix),'x') or access.read(address,len(prefix))!=prefix:raise ValueError('Original queue contract code not naturally ready at '+hex(address))
record=dict(pid=pid,data=data,owner=owner,requested=True,disabled=False,executable_code_modified=False)
path=native_runtime_paths.state_file(ROOT,'native-channel-policy-binding.json');path.write_text(json.dumps(record,indent=2)+'\n');path.chmod(0o600)
access.write(data+40,struct.pack('<Q',owner));access.write(data+8,struct.pack('<I',1))
except ValueError as error:
label=str(error)
allowed=('Original queue contract code not naturally ready at ','Native channel policy must be idle',
'Require real authenticated native world','Native channel lifecycle differs','Require sole authenticated native realm transport')
value=label if any(label.startswith(prefix) for prefix in allowed) else 'fixed-contract-rejected'
path=native_runtime_paths.state_file(ROOT,'native-channel-policy-preflight.json')
path.write_text(json.dumps(dict(pid=pid,status='rejected',validation=value),indent=2)+'\n');path.chmod(0o600)
raise
finally:access.close()
def _request_process(pid):
"""An asynchronous request still belongs only to the exact owned child."""
if _WINDOWS:
from windows_native_bootstrap import Kernel
meta=json.loads((native_runtime_paths.engine_journal(ROOT)).read_text())
executable=(ROOT/'runtime/native-client/_classic_beta_/WowB.exe').resolve()
if (type(pid)is not int or pid<=0 or meta.get('windows_native_bootstrap')is not True or
type(meta.get('pid'))is not int or meta['pid']!=pid or
type(meta.get('starttime'))is not int or meta['starttime']<=0 or
_request_path(meta.get('image_path',''))!=_request_path(executable)):
raise ValueError('Require exact bootstrap-owned native child')
access=host.Access(pid)
try:
created,image=Kernel().identity(access.handle)
if created!=meta['starttime'] or _request_path(image)!=_request_path(executable):
raise ValueError('Bootstrap-owned process identity differs')
return str(created)
finally:access.close()
from client_installation import owns_client_arguments
proc=Path('/proc')/str(pid);executable=ROOT/'runtime/native-client/_classic_beta_/WowB.exe'
if(type(pid)is not int or pid<=0 or proc.stat().st_uid!=os.getuid() or
(proc/'comm').read_text().strip()!='WowB.exe' or
not owns_client_arguments((proc/'cmdline').read_bytes().split(b'\0'),executable)):
raise ValueError('Require exact owned native child')
return (proc/'stat').read_text().rsplit(')',1)[1].split()[19]
def _request_path(value):
return ntpath.normcase(ntpath.normpath(str(value))) if _WINDOWS else str(value)
def _request_libraries(access,meta):
"""Keep the installed matched native libraries, never accept a filename alone."""
executable=ROOT/'runtime/native-client/_classic_beta_/WowB.exe'
if executable.is_symlink() or hashlib.sha256(executable.read_bytes()).hexdigest()!=meta['patched_sha256']:
raise ValueError('Owned native image identity differs')
pins=meta['wire_unix_library']
for key in ('core','wire_unix','source_codec'):
path=Path(pins[key+'_path'])
if(not path.is_relative_to(ROOT/'build') or path.is_symlink() or
hashlib.sha256(path.read_bytes()).hexdigest()!=pins[key+'_sha256'] or
not any(_request_path(name)==_request_path(path) for _,_,_,_,name in access.maps)):
raise ValueError('Matched native library identity differs')
def _request_frame(access,pid,base,exports,owner):
binding=json.loads((native_runtime_paths.state_file(ROOT,'engine-poll-binding.json')).read_text())
frame=base+exports['gw_wire_frame_data'];callback=base+exports['gw_wire_frame_callback']
values=struct.unpack('<9IiIIQ',access.read(frame,56))
if(binding.get('pid')!=pid or binding.get('restored') or binding.get('wire_ping_only') or
binding.get('owner')!=owner or binding.get('wire_frame_data')!=frame or
binding.get('wire_frame_callback')!=callback or
access.u64(owner)!=binding.get('bound_vtable') or
access.u64(binding['bound_vtable']+40)!=callback or not access.allowed(callback,1,'x') or
values[:2]!=(1,wire.SIZE) or values[2]!=8 or values[3]!=1 or not values[4] or
not values[5] or any(values[6:10]) or values[12]!=binding.get('data')):
raise ValueError('Existing owned native frame differs')
return dict(binding=binding,calls=values[4],windows_thread=values[5])
class NativeTargetTemporarilyProtected(ValueError):
"""A mapped original code span currently has neither read nor execute access."""
def _request_targets(access):
for address,value in TARGETS:
prefix=bytes.fromhex(value);n=len(prefix)
readable=access.allowed(address,n,'r');executable=access.allowed(address,n,'x')
if not readable and not executable and any(lo<=address and address+n<=hi and permissions[:3]=='---' for lo,hi,permissions,*_ in access.maps):
raise NativeTargetTemporarilyProtected('Original queue contract temporarily protected')
if not readable or not executable or access.read(address,n)!=prefix:
raise ValueError('Original queue contract code not naturally ready at '+hex(address))
def _refresh_request_maps(access,pid):
if _WINDOWS:
access.refresh_maps();return
rows=[]
for line in (Path('/proc')/str(pid)/'maps').read_text().splitlines():
fields=line.split();lo,hi=(int(v,16)for v in fields[0].split('-'))
rows.append((lo,hi,fields[1],fields[2],fields[-1]))
access.maps=rows
def request_enable(pid,*,publish=True):
"""Publish only an owned request; the existing natural frame validates/applies it.
Unlike enable(), this never waits for another queue-entry breakpoint. It
writes no engine object, enabled bit, authentication result or success flag.
The DLL's unchanged main-thread consumer owns all native lifecycle checks.
"""
if type(publish)is not bool:raise ValueError('Explicit mailbox publication mode required')
identity=_request_process(pid)
from native_lifecycle_audit import audit
audit()
from native_realm_contract import require_realm
account=wire.inspect_account(pid)
binding=json.loads((native_runtime_paths.state_file(ROOT,'engine-poll-binding.json')).read_text())
profile=binding.get('endpoint_profile')
if profile=='local':profile='local-explicit'
require_realm(account,account.get('selected_index'),profile)
if(account.get('state')!=2 or account.get('transport_prepared')!=1):
raise ValueError('Require genuine prepared source world')
proof=json.loads((ROOT/'docs/evidence/gameplay/reference-instance-deferred-buffer-contract.json').read_text())
if proof.get('status')!='real-callback-observed-only' or not proof.get('hardware_registers_restored') or proof.get('metadata',{}).get('cursor')!=16:
raise ValueError('Original live buffer contract missing')
access=host.Access(pid)
try:
base,info,meta=wire.module(access);_request_libraries(access,meta)
data=base+info['exports']['gw_wire_channel_policy'];owner=access.u64(0x145e7a098)
if access.read(data,8)!=struct.pack('<2I',1,SIZE) or any(access.read(data+8,SIZE-8)):
raise ValueError('Native channel policy must be idle; pending/error/result preserved')
first=_request_frame(access,pid,base,info['exports'],owner);sample_started=time.monotonic_ns()
pipe=engine_pipe_host.inspect(pid)
if(pipe['error'] or pipe['closed'] or not pipe['world_auth'] or
not pipe['world']['login_sent'] or not pipe['world']['self_create']):
raise ValueError('Require real authenticated native world')
if(struct.unpack('<I',access.read(owner+0x98,4))[0]!=5 or access.read(owner+0x218,2)!=b'\0\1'):
raise ValueError('Native channel lifecycle differs')
connections=struct.unpack('<4Q',access.read(owner+0x1a0,32))
if not connections[0] or connections[1] or connections[3]:
raise ValueError('Require sole authenticated native realm transport')
# A valid natural callback may pause during world loading/background rendering.
# Keep this proof plus the 0.5s protection wait within the caller 5s RPC budget.
deadline=time.monotonic()+3.0
while True:
fresh=_request_frame(access,pid,base,info['exports'],owner)
if fresh['windows_thread']!=first['windows_thread'] or fresh['calls']<first['calls']:
raise ValueError('Owned native frame changed during freshness proof')
if fresh['calls']>first['calls']:break
if time.monotonic()>=deadline:
raise ValueError(f"Existing native frame did not advance within3s (calls {first['calls']}->{fresh['calls']}, thread {first['windows_thread']})")
time.sleep(.02)
frame_proof=dict(calls_before=first['calls'],calls_after=fresh['calls'],
windows_thread=first['windows_thread'],owner_matches=True,
elapsed_ns=time.monotonic_ns()-sample_started)
protection_deadline=time.monotonic()+.5;protection_samples=0
while True:
try:
_request_targets(access);break
except NativeTargetTemporarilyProtected:
if time.monotonic()>=protection_deadline:raise
protection_samples+=1;time.sleep(.02);_refresh_request_maps(access,pid)
check=_request_frame(access,pid,base,info['exports'],owner)
current=engine_pipe_host.inspect(pid);account=wire.inspect_account(pid)
require_realm(account,account.get('selected_index'),profile)
if(check['windows_thread']!=first['windows_thread'] or check['calls']<fresh['calls'] or
account.get('state')!=2 or account.get('transport_prepared')!=1 or
current['error'] or current['closed'] or not current['world_auth'] or
not current['world']['login_sent'] or not current['world']['self_create']):
raise ValueError('Current owned world changed during protection wait')
fresh=check
frame_proof['target_protection_retries']=protection_samples
frame_proof['calls_after']=fresh['calls']
frame_proof['elapsed_ns']=time.monotonic_ns()-sample_started
if _request_process(pid)!=identity or access.u64(0x145e7a098)!=owner:
raise ValueError('Owned native frame changed before request')
if access.read(data,8)!=struct.pack('<2I',1,SIZE) or any(access.read(data+8,SIZE-8)):
raise ValueError('Native channel policy changed before request')
if not publish:
return dict(request_published=False,native_result_pending=False,
enabled_outcome_written=False,frame_freshness=frame_proof,
strict_owned_frame_preflight_verified=True)
record=dict(pid=pid,data=data,owner=owner,requested=True,disabled=False,
publication='existing-owned-frame-mailbox',native_result_pending=True,
executable_code_modified=False,enabled_outcome_written=False,frame_freshness=frame_proof)
path=native_runtime_paths.state_file(ROOT,'native-channel-policy-binding.json');path.write_text(json.dumps(record,indent=2)+'\n');path.chmod(0o600)
# Aligned owner value first; command LAST. Native consumer rechecks the
# live owner/thread/world, then alone writes enabled/error/outcomes.
access.write(data+40,struct.pack('<Q',owner))
try:
access.write(data+8,struct.pack('<I',1))
except ValueError as error:
# The natural frame consumes this command with InterlockedExchange.
# Generic write/readback stays strict. Only this final consumable
# command may acknowledge its already-completed native outcome.
if str(error)!='Binding data write failed':raise
values=_read_policy_values(access,data)
from native_test_guard import require_native_gameplay_policy
outcome=dict(command=values[2],enabled=values[3]==1,error=values[4],
windows_thread=values[5],owner_matches=values[10]==access.u64(0x145e7a098))
try:require_native_gameplay_policy(outcome)
except RuntimeError:raise error
if (outcome['command']!=0 or not outcome['owner_matches'] or
values[10]!=owner or values[5]!=fresh['windows_thread']):raise error
record.update(native_result_pending=False,native_outcome_observed=outcome,
consumed_command_readback_admitted=True)
path.write_text(json.dumps(record,indent=2)+'\n');path.chmod(0o600)
return dict(request_published=True,native_result_pending=False,
enabled_outcome_written=False,native_outcome_observed=outcome,
consumed_command_readback_admitted=True,frame_freshness=frame_proof)
return dict(request_published=True,native_result_pending=True,enabled_outcome_written=False,frame_freshness=frame_proof)
finally:access.close()
def disable(pid,caller):
host.require_safepoint(caller);access=host.Access(pid)
try:
base,info,_=wire.module(access);data=base+info['exports']['gw_wire_channel_policy']
if access.read(data,8)!=struct.pack('<2I',1,SIZE):raise ValueError('Native channel ABI differs')
access.write(data+8,struct.pack('<I',2))
path=native_runtime_paths.state_file(ROOT,'native-channel-policy-binding.json')
if path.exists():
record=json.loads(path.read_text())
if record['pid']==pid:record['disabled']=True;path.write_text(json.dumps(record,indent=2)+'\n')
finally:access.close()
def _read_policy_values(access,data):
values=struct.unpack('<10IQ',access.read(data,SIZE))
if values[:2]!=(1,SIZE):raise ValueError('Native channel ABI differs')
return values
def inspect(pid):
access=host.Access(pid)
try:
base,info,_=wire.module(access);data=base+info['exports']['gw_wire_channel_policy']
values=_read_policy_values(access,data)
contracts=engine_pipe_host.inspect_code_contracts(access,TARGETS)
failure=None
if 'gw_wire_channel_contracts' in info['exports']:
row=struct.unpack('<8I',access.read(base+info['exports']['gw_wire_channel_contracts'],32))
if row[:2]!=(1,32):raise ValueError('Channel contract diagnostics ABI differs')
failure=dict(zip(('samples','failures','send_status','store_status','release_status','protection_deferrals'),row[2:8]))
return dict(contract_failure=failure,code_contracts=contracts,kind='native-authenticated-single-channel-policy',command=values[2],enabled=bool(values[3]),error=values[4],windows_thread=values[5],polls=values[6],drained=values[7],bytes=values[8],last_requested_route=values[9],
owner_matches=values[10]==access.u64(0x145e7a098),executable_code_modified=False,authentication_state_written=False,native_movement_verified=False)
finally:access.close()