Files
WoW-Hybrid-gateway/ops/client_installation.py
2026-11-19 03:33:51 +02:00

195 lines
12 KiB
Python

#!/usr/bin/env python3
"""Validate complete local Forever installations and make private CoW copies.
No DB2 conversion, schema edits, downloads, launcher updates or binary patches.
"""
import csv
import datetime
import hashlib
import json
import os
import re
from pathlib import Path
import shutil
import subprocess
import time
ROOT=Path(__file__).resolve().parents[1]
PRISTINE=ROOT/'runtime/pristine-forever/World of Warcraft'
COPY=ROOT/'runtime/native-client'
MARKER='native-complete-installation.json'
def client_debug_socket(root):
"""One private local AF_UNIX address for this canonical client root.
Client content may live on CIFS, which cannot host Unix socket inodes.
Keep the existing owner protocol and independent per-root ownership.
"""
identity=hashlib.sha256(os.fsencode(Path(root).resolve())).hexdigest()[:16]
uid=os.getuid();candidates=[];xdg=os.environ.get('XDG_RUNTIME_DIR')
if xdg:
base=Path(xdg)
try:
info=base.lstat()
if base.is_absolute()and not base.is_symlink()and base.is_dir()and info.st_uid==uid and not info.st_mode&0o077:candidates.append(base)
except OSError:pass
candidates.append(Path('/tmp'))
for base in candidates:
directory=base/('wowhybrid-ipc-'+str(uid)+'-'+identity)
try:
if not directory.exists():directory.mkdir(mode=0o700)
info=directory.lstat()
if directory.is_symlink()or not directory.is_dir()or info.st_uid!=uid or info.st_mode&0o077:raise ValueError('Existing owner IPC directory is not private; preserved')
address=directory/'owner.sock'
if len(os.fsencode(address))<108:return address
except PermissionError:
if base!=Path('/tmp'):continue
raise
raise ValueError('No private local owner IPC address within Unix socket bound')
def window_arguments(root=COPY):
"""Respect the owned client's native fullscreen-windowed preference.
A forced -windowed argument overrides GxMaximize on startup. Keep the
previous windowed default when no explicit native preference exists.
"""
path=Path(root)/'_classic_beta_/WTF/Config.wtf'
text=path.read_text()if path.exists()else''
values=re.findall(r'^[ \t]*SET[ \t]+gxMaximize[ \t]+"([01])"[ \t]*$', text, re.IGNORECASE | re.MULTILINE)
if len(values)>1:raise RuntimeError('Ambiguous display mode preference; preserve client configuration')
return []if values==['1']else['-windowed']
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def inspect_installation(root):
root=Path(root);game=root/'_classic_beta_'
required=('.build.info','.product.db','Launcher.db','_classic_beta_/.flavor.info',
'_classic_beta_/WowB.exe','_classic_beta_/WowB_loader.dll','_classic_beta_/icudt78l.dat')
for name in required:
if not (root/name).is_file():raise RuntimeError('Incomplete Forever installation: missing '+name)
if not (root/'Data/data').is_dir() or (root/'Data').is_symlink():raise RuntimeError('Experimental CASC must be a complete private directory, never a writable link to original assets')
flavor=(game/'.flavor.info').read_text().splitlines()
if flavor!=['Product Flavor!STRING:0','wow_classic_beta']:raise RuntimeError('Unexpected product flavor; no schema or product identifiers rewritten')
with (root/'.build.info').open() as f:rows=list(csv.reader(f,delimiter='|'))
headers=[v.split('!')[0] for v in rows[0]]
active=[dict(zip(headers,row)) for row in rows[1:] if row]
active=[row for row in active if row.get('Active')=='1' and row.get('Product')=='wow_classic_beta']
if len(active)!=1 or active[0].get('Version')!='1.60.1.70334':raise RuntimeError('Build metadata does not select the installed Forever70334 product')
return {'version':active[0]['Version'],'product':active[0]['Product'],'build_key':active[0].get('Build Key'),
'files':{name:{'bytes':(root/name).stat().st_size,'sha256':digest(root/name)} for name in required}}
def owns_client_arguments(arguments,executable=None):
"""Exact argv identity only; never infer ownership from a process title."""
path=str(executable or COPY/'_classic_beta_/WowB.exe')
return any(value.encode()in arguments for value in(path,'Z:'+path.replace('/','\\')))
def running_clients(*,owned_only=False):
result=[]
for p in Path('/proc').iterdir():
try:
if p.name.isdigit() and (p/'comm').read_text().strip()=='WowB.exe':
if not owned_only or owns_client_arguments((p/'cmdline').read_bytes().split(b'\0')):
result.append(int(p.name))
except OSError:pass
return result
def clone():
if COPY.exists() and (COPY/MARKER).exists():
inspect_installation(COPY);print('Complete private Forever copy already present; preserved.');return
for pid in running_clients():
command=(Path('/proc')/str(pid)/'cmdline').read_bytes().split(b'\0')
expected=str(COPY/'_classic_beta_/WowB.exe')
if expected.encode() in command or ('Z:'+expected.replace('/','\\')).encode() in command:
raise RuntimeError('Preserve active experimental WowB; close normally before replacing its directory')
source=inspect_installation(PRISTINE)
# A complete reflink clone preserves product selection, sidecars, installed
# data and caches together. File writes use independent CoW extents.
temporary=ROOT/'runtime/native-complete-installation.new'
if temporary.exists():raise RuntimeError('Existing staged copy preserved; inspect before repeating clone')
subprocess.run(['cp','--archive','--reflink=always',str(PRISTINE),str(temporary)],check=True)
cloned=inspect_installation(temporary)
if cloned!=source:raise RuntimeError('Complete clone identity changed; original copy preserved')
manifest={'source':'authorized untouched RAR extracted in private workspace','archive':'/mnt/Games/Games/World of Warcraft.rar',
'complete_private_casc':True,'reflink_cow':True,'baseline':source,
'rollback':'Close only experimental WowB. The archived original and installed original were not changed. The previous incomplete copy is preserved in recovery/native-partial-before-complete-*.'}
(temporary/MARKER).write_text(json.dumps(manifest,indent=2)+'\n')
if COPY.exists():
old=ROOT/'recovery'/('native-partial-before-complete-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
COPY.rename(old);print('Previous partial copy preserved:',old.relative_to(ROOT))
temporary.rename(COPY)
print('Created complete private CoW Forever70334 installation from authorized pristine archive; binaries and product metadata verified.')
def choose_close_window(rows,pid):
"""Close-only selector: a fatal modal must block input, not normal shutdown.
PID/path authorization is checked by the caller. No titles, OCR, focus or
keyboard input; never choose a separate error reporter or another client.
"""
candidates=[r for r in rows if r['pid']==pid and r['width']>=640 and r['height']>=400
and any('wowb' in c.lower() for c in r['classes'])
and not any('blizzarderror' in c.lower() for c in r['classes'])]
if not candidates:raise RuntimeError('No owned game window available for normal close')
largest=max(r['width']*r['height'] for r in candidates)
candidates=[r for r in candidates if r['width']*r['height']==largest]
if len(candidates)!=1:raise RuntimeError('Ambiguous owned game windows preserved')
return candidates[0]['id']
def close_test_client():
clients=running_clients(owned_only=True)
if not clients:return
if len(clients)!=1:raise RuntimeError('Multiple WowB processes preserved; no ambiguous close')
command=(Path('/proc')/str(clients[0])/'cmdline').read_bytes().split(b'\0')
paths=[str(COPY/'_classic_beta_/WowB.exe'),'/mnt/Games/Games/WoW-Forever/_classic_beta_/WowB.exe']
if not any(p.encode() in command or ('Z:'+p.replace('/','\\')).encode() in command for p in paths):raise RuntimeError('Unrecognized WowB installation preserved')
from Xlib import protocol,X,display
from client_ui import window_rows
# WM_DELETE_WINDOW does not type into or focus a window. Do not create an
# input device or require keyboard focus merely to close this verified sole
# client normally (KWin can refuse focus while Codex is the active window).
connection=display.Display()
try:
win=connection.create_resource_object('window',choose_close_window(window_rows(connection),clients[0]))
event=protocol.event.ClientMessage(window=win,client_type=connection.intern_atom('WM_PROTOCOLS'),data=(32,[connection.intern_atom('WM_DELETE_WINDOW'),X.CurrentTime,0,0,0]))
win.send_event(event);connection.flush()
finally:connection.close()
deadline=time.monotonic()+30
while running_clients(owned_only=True) and time.monotonic()<deadline:time.sleep(.1)
if running_clients(owned_only=True):raise RuntimeError('Normal client close still pending; no duplicate launch')
def control():
clone();close_test_client();identity=inspect_installation(COPY)
# Keep the proven Wine graphics/network environment. A network namespace
# prevented Vulkan initialization in the first control, so instead bind
# only this copy's authentication portal to the authorized local frontend.
import re
config=COPY/'_classic_beta_/WTF/Config.wtf'
original=config.read_text()
marker=ROOT/'recovery/pristine-control-config'
marker.mkdir(exist_ok=True,mode=0o700)
if not (marker/'Config.wtf').exists():shutil.copy2(config,marker/'Config.wtf');(marker/'Config.wtf').chmod(0o600)
text=re.sub(r'^SET portal .*$', 'SET portal "trinity.actual.battle.net"',original,flags=re.M)
if not re.search(r'^SET portal ',text,re.M):text+='\nSET portal "trinity.actual.battle.net"\n'
config.write_text(text);config.chmod(0o600)
before={p.name for p in (COPY/'_classic_beta_/Errors').glob('*Error*.txt')}
env=dict(os.environ)
for key in ('LD_PRELOAD','GW_NATIVE_BOOTSTRAP','GW_NATIVE_EXPECTED_EXE'):env.pop(key,None)
env.update(WINEPREFIX=str(Path.home()/'Projects/WoW-Hybrid/wine-forever'),WINEDEBUG='-all')
command=['wine',str(COPY/'_classic_beta_/WowB.exe'),'-console',*window_arguments()]
start=time.monotonic()
with (ROOT/'runtime/pristine-startup-control.log').open('wb') as log:
child=subprocess.Popen(command,cwd=COPY/'_classic_beta_',env=env,stdout=log,stderr=log,start_new_session=True)
(ROOT/'runtime/pristine-startup-owner.pid').write_text(str(child.pid))
from client_session import Session
with Session(startup_pid=child.pid) as session:
deadline=time.monotonic()+90
while time.monotonic()<deadline:
fresh={p.name for p in (COPY/'_classic_beta_/Errors').glob('*Error*.txt')}-before
if fresh:raise RuntimeError('Clean control produced a crash report; retained for investigation')
state=session.state()
if state in ('login','disconnected'):break
if child.poll() is not None:raise RuntimeError('Clean control exited before login readiness')
time.sleep(.1)
else:raise RuntimeError('Bounded clean startup control did not reach login readiness')
report={'kind':'complete-pristine-archive-startup-control','network_isolated':False,'local_frontend_portal':'trinity.actual.battle.net','native_module_loaded':False,
'login_screen_ready':True,'ui_state':state,'seconds':round(time.monotonic()-start,3),
'new_crash_reports':[],'identity':identity,'source_archive_unchanged':True}
(ROOT/'runtime/pristine-startup-result.json').write_text(json.dumps(report,indent=2)+'\n')
print('Actual clean-copy login screen ready; no native module, DB2/schema edits or new crash report. Only the clone portal is local. Seconds:',report['seconds'])
if __name__=='__main__':
import argparse
parser=argparse.ArgumentParser();parser.add_argument('action',choices=('inspect','clone','control'));parser.add_argument('--root',type=Path,default=COPY);args=parser.parse_args()
if args.action=='clone':clone()
elif args.action=='control':control()
else:print(json.dumps(inspect_installation(args.root),indent=2))