Files
WoW-Hybrid-gateway/ops/casc_local_archive.py
2026-11-23 03:28:32 +02:00

387 lines
23 KiB
Python

#!/usr/bin/env python3
"""Offline CASC segment/index staging primitives, never an active installer.
Exact local70334 IDXv7/9+5+4 layout and BLTE span contracts, checked against
the installed index and CascLib CascIndexFiles/CascReadFile/CascStructs sources.
Uses the pinned local CascLib lookup3 implementation rather than inventing a
checksum. Original index records remain bit-identical; only additions allowed.
"""
import ctypes as C
import hashlib
import os
from pathlib import Path
import shutil
import struct
import subprocess
ROOT=Path(__file__).resolve().parents[1]
# Build70334 requires a complete trailing KMT update area in addition to the
# sorted entries. CascLib accepts a shorter file, but the native client rejects
# it with "Truncated KMT update section detected" before login. Preserve the
# observed native allocation granularity when entries grow across that reserve.
INDEX_UPDATE_RESERVE=32768
INDEX_ALLOCATION=65536
def vendor_archive_entry(raw,encoding_key):
"""Locate one exact public EKey in a local CDN archive index.
Pinned FILE_INDEX_FOOTER<8>/CaptureIndexEntry layout from CascLib. Group
indexes and loose-file indexes use different offset contracts and are not
interpreted as archive ranges. This function neither fetches nor installs.
"""
if not isinstance(raw,bytes)or not 36<=len(raw)<=536870912 or not isinstance(encoding_key,bytes)or len(encoding_key)!=16:
raise ValueError('Bounded vendor index and complete encoding key required')
footer=raw[-36:]
if footer[16:24]!=bytes((1,0,0,4,4,4,16,8)):raise ValueError('Unreviewed vendor archive index footer')
if hashlib.md5(footer[16:28]+bytes(8)).digest()[:8]!=footer[28:36]:raise ValueError('Vendor index footer checksum differs')
count=int.from_bytes(footer[24:28],'little');page=4096;entry=24
if not 0<count<=20000000:raise ValueError('Vendor archive index count bound')
pages=(count+(page//entry)-1)//(page//entry)
if pages*page>len(raw)-36:raise ValueError('Vendor archive index page extent')
found=[];start=0
while True:
at=raw.find(encoding_key,start,pages*page)
if at<0:break
start=at+1;within=at%page
if within%entry or within+entry>page:continue
ordinal=(at//page)*(page//entry)+within//entry
if ordinal>=count:continue
size=int.from_bytes(raw[at+16:at+20],'big');offset=int.from_bytes(raw[at+20:at+24],'big')
if not 0<size<1<<30 or offset+size>0x10000000:raise ValueError('Vendor archive range bound')
found.append(dict(offset=offset,encoded_size=size))
if len(found)>1:raise ValueError('Ambiguous vendor archive encoding key')
return found[0]if found else None
def lookup3_api():
source=ROOT.parent/'tools/casc-tool/vendor/CascLib/src/jenkins'
digest=hashlib.sha256((source/'lookup3.c').read_bytes()+(source/'lookup.h').read_bytes()).hexdigest()
out=ROOT/'build/casc-package-helpers';out.mkdir(parents=True,exist_ok=True)
library=out/('liblookup3.dll' if os.name=='nt' else 'liblookup3.so')
stamp=out/'source.sha256'
if not library.exists()or not stamp.exists()or stamp.read_text().strip()!=digest:
if os.name=='nt':
compiler=shutil.which('gcc') or r'C:\msys64\ucrt64\bin\gcc.exe'
command=[compiler,'-shared','-O2',str(source/'lookup3.c'),'-o',str(library)]
environment=os.environ.copy()
environment['PATH']=str(Path(compiler).parent)+os.pathsep+environment.get('PATH','')
else:
command=['cc','-shared','-fPIC','-O2',str(source/'lookup3.c'),'-o',str(library)]
environment=None
subprocess.run(command,check=True,env=environment)
stamp.write_text(digest+'\n')
api=C.CDLL(str(library));api.hashlittle.argtypes=[C.c_void_p,C.c_size_t,C.c_uint32];api.hashlittle.restype=C.c_uint32
api.hashlittle2.argtypes=[C.c_void_p,C.c_size_t,C.POINTER(C.c_uint32),C.POINTER(C.c_uint32)];api.hashlittle2.restype=None
return api,digest
def _entry_hash(api,raw):
high=C.c_uint32(0);low=C.c_uint32(0)
for at in range(0,len(raw),18):api.hashlittle2(raw[at:at+18],18,C.byref(high),C.byref(low))
return high.value
def parse_index(raw,bucket,api):
if not isinstance(raw,bytes)or not 58<=len(raw)<=16777216 or type(bucket)is not int or not 0<=bucket<=15:
raise ValueError('Bounded native index/bucket required')
length,digest=struct.unpack_from('<II',raw)
header=raw[8:24]
if length!=16 or api.hashlittle(header,len(header),0)!=digest:raise ValueError('Native index header checksum')
revision,actual_bucket,flags,size_bytes,offset_bytes,key_bytes,segment_bits,maximum=struct.unpack('<H6BQ',header)
if (revision,actual_bucket,flags,size_bytes,offset_bytes,key_bytes,segment_bits)!=(7,bucket,0,4,5,9,30):
raise ValueError('Pinned native IDXv7 layout required')
if any(raw[24:32]):raise ValueError('Unreviewed index header padding')
count_bytes,expected=struct.unpack_from('<II',raw,32)
if not count_bytes or count_bytes%18 or count_bytes>len(raw)-40:raise ValueError('Native index entry extent')
entries=raw[40:40+count_bytes]
if _entry_hash(api,entries)!=expected:raise ValueError('Native index entry checksum')
rows=[entries[at:at+18]for at in range(0,len(entries),18)]
if any(a[:9]>b[:9]for a,b in zip(rows,rows[1:])):raise ValueError('Native index entry order')
return dict(header=header,rows=rows,segment_bits=segment_bits,max_file_offset=maximum,
bytes=len(raw),sha256=hashlib.sha256(raw).hexdigest())
def encoding_bucket(encoding_key):
if not isinstance(encoding_key,bytes)or len(encoding_key)!=16:raise ValueError('Full encoding key required')
value=0
for b in encoding_key[:9]:value^=b
return(value^(value>>4))&15
def verified_existing_spans(raw,bucket,payloads,read_span,api):
"""Verify one bucket once and compare every requested complete archive span.
Index-prefix matches still require exact full encoded bytes. A local header
may retain only the indexed nine key bytes. That form requires its exact
size/flags/Jenkins hash; the final four opaque bytes are retained and hashed
as evidence, not interpreted as the publication writer's offset checksum.
CascLib CascReadFile.cpp explicitly permits variable encoded headers.
Batching avoids
rechecking the same IDX checksum/order for each asset, without caching or
accepting caller-supplied unverified index metadata.
"""
from casc_asset_package import blte_encoding_key
if not isinstance(payloads,list)or not 1<=len(payloads)<=8192 or not callable(read_span):
raise ValueError('Bounded encoded payload batch and archive reader required')
keys=[]
for blte in payloads:
if not isinstance(blte,bytes)or not 9<=len(blte)<=268435426:raise ValueError('Bounded encoded payload required')
key=blte_encoding_key(blte)
if encoding_bucket(key)!=bucket:raise ValueError('Wrong existing span bucket')
keys.append(key)
layout=parse_index(raw,bucket,api);prefixes={}
for row in layout['rows']:prefixes.setdefault(row[:9],[]).append(row)
result=[]
for blte,key in zip(payloads,keys):
matches=prefixes.get(key[:9],[])
if not matches:result.append(None);continue
if len(matches)!=1:raise ValueError('Ambiguous existing encoding prefix')
row=matches[0];position=int.from_bytes(row[9:14],'big');segment=position>>30;offset=position&((1<<30)-1)
size=struct.unpack_from('<I',row,14)[0]
if segment>=1024 or position>=layout['max_file_offset']or size!=len(blte)+30 or offset+size>1<<30:
raise ValueError('Existing archive span bounds differ')
actual=read_span(segment,offset,size)
expected=_archive_span_with_key(blte,offset,api,key)
header_form='full-encoding-key'
if actual!=expected:
shortened=_archive_span_with_key(blte,offset,api,key[:9]+bytes(7))
if (not isinstance(actual,bytes)or len(actual)!=len(shortened)or
actual[:26]!=shortened[:26]or actual[30:]!=blte):
raise ValueError('Existing encoding prefix has different archive bytes')
header_form='indexed-prefix-zero-tail'
result.append(dict(encoding_key=key.hex(),segment=segment,offset=offset,span_size=size,
exact_bytes_verified=True,archive_header_form=header_form,
existing_span_sha256=hashlib.sha256(actual).hexdigest(),
opaque_header_tail_preserved=actual[26:30].hex() if header_form=='indexed-prefix-zero-tail' else None))
return result
def verified_existing_span(raw,bucket,blte,read_span,api):
"""Compatibility entry point for one exact complete archive-span proof."""
return verified_existing_spans(raw,bucket,[blte],read_span,api)[0]
def extend_index(raw,bucket,additions,api):
layout=parse_index(raw,bucket,api)
if not isinstance(additions,list)or not 1<=len(additions)<=4096:raise ValueError('Bounded local index additions required')
original=layout['rows'];prefixes={row[:9]for row in original};new=[]
for r in additions:
if not isinstance(r,dict)or set(r)!={'encoding_key','segment','offset','span_size'}:raise ValueError('Complete local span identity required')
key=r['encoding_key'];segment=r['segment'];offset=r['offset'];size=r['span_size']
if encoding_bucket(key)!=bucket or key[:9]in prefixes:raise ValueError('Wrong bucket or encoding prefix collision')
if (any(type(v)is not int for v in(segment,offset,size))or not 0<=segment<1024 or not 0<=offset<1<<30 or
not 39<=size<1<<30 or offset+size>1<<30):raise ValueError('Native archive span bounds')
position=(segment<<30)|offset
if position>=layout['max_file_offset']:raise ValueError('Native maximum archive offset')
prefixes.add(key[:9]);new.append(key[:9]+position.to_bytes(5,'big')+struct.pack('<I',size))
rows=sorted(original+new,key=lambda row:row[:9]);entries=b''.join(rows)
old_end=40+18*len(original)
if any(raw[old_end:]):raise ValueError('Nonempty native index update area must be preserved; offline compaction unsupported')
header=layout['header'];result=struct.pack('<II',16,api.hashlittle(header,16,0))+header+bytes(8)+struct.pack('<II',len(entries),_entry_hash(api,entries))+entries
capacity=max(layout['bytes'],((len(result)+INDEX_UPDATE_RESERVE+INDEX_ALLOCATION-1)//INDEX_ALLOCATION)*INDEX_ALLOCATION)
result+=bytes(capacity-len(result))
checked=parse_index(result,bucket,api)
if checked['rows']!=rows:raise ValueError('Staged index roundtrip differs')
return result,dict(original_entries=len(original),new_entries=len(new),original_entries_bit_identical=True,
original_sha256=layout['sha256'],staged_sha256=checked['sha256'],
update_reserve_bytes=capacity-40-len(entries),allocation_bytes=capacity,installed=False)
def rebase_index_rows(raw,bucket,rows,api):
"""Write one fresh IDX generation for a separately proven retained span set.
Reachability belongs to the caller. This accepts only existing key prefixes,
validates the source generation, and never edits its bytes or drops rows by
itself. The caller must retain the complete selected parent preimage.
"""
layout=parse_index(raw,bucket,api)
if not isinstance(rows,list)or not rows or any(not isinstance(r,bytes)or len(r)!=18 for r in rows):
raise ValueError('Complete bounded native index rows required')
from collections import Counter
source=Counter(r[:9]for r in layout['rows'])
retained=Counter(r[:9]for r in rows)
if any(count>source[prefix]for prefix,count in retained.items()):
raise ValueError('Rebased index requires existing key-prefix multiplicities')
if any(a[:9]>b[:9]for a,b in zip(rows,rows[1:])):
raise ValueError('Rebased index rows must be sorted')
original_rows=set(layout['rows'])
for row in rows:
if row in original_rows:continue
position=int.from_bytes(row[9:14],'big');size=struct.unpack_from('<I',row,14)[0]
if position>=layout['max_file_offset']or position>>30>=1024 or not 39<=size<1<<30 or (position&((1<<30)-1))+size>1<<30:
raise ValueError('Rebased native span bounds differ')
end=40+18*len(layout['rows'])
if any(raw[end:]):raise ValueError('Nonempty native index update area cannot be rebased')
entries=b''.join(rows);header=layout['header']
result=struct.pack('<II',16,api.hashlittle(header,16,0))+header+bytes(8)+struct.pack('<II',len(entries),_entry_hash(api,entries))+entries
capacity=max(layout['bytes'],((len(result)+INDEX_UPDATE_RESERVE+INDEX_ALLOCATION-1)//INDEX_ALLOCATION)*INDEX_ALLOCATION)
result+=bytes(capacity-len(result))
checked=parse_index(result,bucket,api)
if checked['rows']!=rows:raise ValueError('Rebased native index roundtrip differs')
return result,dict(source_sha256=layout['sha256'],rebased_sha256=checked['sha256'],
source_rows=len(layout['rows']),retained_rows=len(rows),
update_reserve_bytes=capacity-40-len(entries),installed=False)
def relocate_archive_header(header,index_prefix,span_size,new_offset,api):
"""Move an existing encoded span without decoding or changing its BLTE body."""
if (not isinstance(header,bytes)or len(header)!=30 or not isinstance(index_prefix,bytes)or len(index_prefix)!=9
or type(span_size)is not int or not 39<=span_size<1<<30
or type(new_offset)is not int or not 0<=new_offset<1<<30 or new_offset+span_size>1<<30):
raise ValueError('Bounded existing archive header and destination required')
if (header[:16][::-1][:9]!=index_prefix or struct.unpack_from('<I',header,16)[0]!=span_size
or header[20:22]!=bytes(2) or struct.unpack_from('<I',header,22)[0]!=api.hashlittle(header[:22],22,0x3D6BE971)):
raise ValueError('Existing archive header/index relationship differs')
return _archive_header(header[:16][::-1],span_size,new_offset,api)
def _require_chunk_table(header):
if header == b'BLTE' + bytes(4):
raise ValueError('New client archive frames require a BLTE chunk table')
def archive_span(blte,offset,api):
from casc_asset_package import blte_encoding_key
key=blte_encoding_key(blte)
_require_chunk_table(blte[:8])
return _archive_span_with_key(blte,offset,api,key),key
def _archive_span_with_key(blte,offset,api,key):
"""Regenerate a complete header; publication always uses the full EKey.
The nine-byte/zero-tail form is admitted only for verified existing spans.
Unlike CascLib's permissive reader, this does not accept arbitrary headers.
"""
if type(offset)is not int or not 0<=offset<1<<30 or offset+len(blte)+30>1<<30:
raise ValueError('Archive span offset bound')
return _archive_header(key,len(blte)+30,offset,api)+blte
def _archive_header(key,span_size,offset,api):
"""Shared pinned native header/checksum writer for new and moved spans."""
if not isinstance(key,bytes)or len(key)!=16 or type(span_size)is not int or not 39<=span_size<1<<30:
raise ValueError('Bounded archive key and span size required')
header=key[::-1]+struct.pack('<I',span_size)+bytes(2)
header+=struct.pack('<I',api.hashlittle(header,len(header),0x3D6BE971))
table=(0x049396B8,0x72A82A9B,0xEE626CCA,0x9917754F,0x15DE40B1,0xF5A8A9B6,0x421EAC7E,0xA9D55C9A,0x317FD40C,0x04FAF80D,0x3D6BE971,0x52933CFD,0x27F64B7D,0xC6F5C11B,0xD5757E3A,0x6C388745)
encoded_offset=struct.pack('<I',table[(offset+30)&15]^(offset+30))
hashed=bytearray(4)
for i,b in enumerate(header):hashed[i&3]^=b
checksum=bytes(hashed[(len(header)+j)&3]^encoded_offset[(len(header)+j)&3]for j in range(4))
return header+checksum
def stage_fresh_archive_indexes(baseline_indexes,frames,output,first_segment,api):
"""Pack a qualified current EKey set into a FRESH native archive/index delta.
The caller retains the complete immutable baseline store. This writer does
not remove, edit or copy it, generate content, or decide reachability. Input
rows are existing encoded frame records (file, encoding_key, encoded_size),
already selected by current ROOT/TVFS/ENCODING/config closure. Only these
encoded bytes are read, once per EKey, while writing their new archive span.
Native BLTE payloads are not decoded or re-encoded. Old metadata must not be
supplied just because a historical store contains it.
No existing output is admitted. Baseline prefix collisions require an
existing qualified baseline binding and must be excluded by the caller;
this routine never guesses equality from a nine-byte local-index prefix.
"""
import json
from collections import defaultdict
from casc_asset_package import MAX_ASSET_BATCH
if (not isinstance(baseline_indexes,dict)or set(baseline_indexes)!=set(range(16))
or not isinstance(frames,list)or not 1<=len(frames)<=MAX_ASSET_BATCH
or type(first_segment)is not int or not 0<=first_segment<1024):
raise ValueError('Complete baseline indexes, bounded selected frames and segment required')
out=Path(output).resolve();baseline={};tokens={};prefixes={};maximum=-1
if out.exists()or out.is_symlink():raise ValueError('Fresh compact archive/index delta required')
def token(path):
st=path.stat();return(st.st_dev,st.st_ino,st.st_size,st.st_mtime_ns)
for bucket,path in sorted(baseline_indexes.items()):
path=Path(path).resolve()
if out.is_relative_to(path.parent):raise ValueError('Compaction output cannot modify baseline tree')
if path.is_symlink()or not path.is_file():raise ValueError('Regular baseline index required')
# Same native filename and next-generation policy as the accepted COW
# assembler. The old generation remains untouched in the baseline.
if (len(path.name)!=14 or not path.name.endswith('.idx')or
path.name[:2]!=f'{bucket:02x}'):
raise ValueError('Native baseline bucket/generation filename required')
try:generation=int(path.name[2:10],16)
except ValueError:raise ValueError('Native index generation required')from None
if generation>=0xffffffff:raise ValueError('Native index generation exhausted')
before=token(path);raw=path.read_bytes();layout=parse_index(raw,bucket,api)
if token(path)!=before:raise ValueError('Baseline index changed during read')
tokens[path]=before;baseline[bucket]=(raw,generation,path)
for row in layout['rows']:
position=int.from_bytes(row[9:14],'big');maximum=max(maximum,position>>30)
prefixes[row[:9]]=bucket
if first_segment<=maximum:raise ValueError('Fresh segments must follow every retained baseline span')
selected={}
for row in frames:
if not isinstance(row,dict):raise ValueError('Existing complete frame record required')
key=row.get('encoding_key');size=row.get('encoded_size')
# A frame is indivisible in an archive, but the native segment format
# permits any one span that fits below its 30-bit segment boundary.
# Keep this in lockstep with archive_span() instead of imposing the
# smaller asset-ingest bound on already encoded native frames.
if (not isinstance(key,str)or len(key)!=32 or any(c not in'0123456789abcdef'for c in key)
or key=='0'*32 or type(size)is not int or not 9<=size<=(1<<30)-30):
raise ValueError('Bounded full existing encoded-frame identity required')
if bytes.fromhex(key)[:9]in prefixes:
raise ValueError('Selected frame needs qualified baseline reuse instead of prefix replacement')
if key in selected:
old=selected[key]
if old['encoded_size']!=size or old.get('content_key')!=row.get('content_key'):
raise ValueError('Different retained frames share an EKey')
continue
path=Path(row['file'])
if not path.is_absolute()or path.is_symlink()or not path.is_file()or path.stat().st_size!=size:
raise ValueError('Existing encoded-frame path/size differs')
if out.is_relative_to(path.parent):raise ValueError('Compaction output cannot modify retained frame directory')
with path.open('rb') as stream:
_require_chunk_table(stream.read(8))
selected[key]=dict(row)
out.mkdir(parents=True);data=out/'Data/data';data.mkdir(parents=True)
additions=defaultdict(list);spans=[];created=[];stream=None;segment=first_segment;offset=0
try:
for key,row in sorted(selected.items()):
if stream is None or offset+row['encoded_size']+30>1<<30:
if stream is not None:stream.close();segment+=1
if segment>=1024:raise ValueError('Native archive segment namespace exhausted')
stream=(data/f'data.{segment:03d}').open('xb');created.append(segment);offset=0
path=Path(row['file']);before=token(path);encoded=path.read_bytes()
if len(encoded)!=row['encoded_size']:raise ValueError('Encoded input changed before packing')
span,actual=archive_span(encoded,offset,api)
if actual.hex()!=key or token(path)!=before:raise ValueError('Retained frame EKey or source stability differs')
written=stream.write(span)
if written!=len(span):raise OSError('Incomplete fresh archive write')
record=dict(encoding_key=key,segment=segment,offset=offset,span_size=len(span))
# Index extension consumes full binary EKeys; the JSON manifest
# keeps the printable hexadecimal form from ``record``.
additions[encoding_bucket(actual)].append(dict(record,encoding_key=actual))
spans.append(dict(record,source_file=str(path),encoded_payload_preserved=True))
offset+=len(span)
finally:
if stream is not None:stream.close()
audits={}
for bucket,rows in sorted(additions.items()):
if len(rows)>4096:raise ValueError('Existing single-bucket extension bound exceeded')
raw,generation,path=baseline[bucket]
updated,audit=extend_index(raw,bucket,rows,api)
name=f'{bucket:02x}{generation+1:08x}.idx'
(data/name).write_bytes(updated);audits[name]=audit
if any(token(path)!=before for path,before in tokens.items()):
raise ValueError('Immutable baseline index changed during fresh composition')
report=dict(kind='fresh-baseline-native-casc-archive-index-delta',installed=False,engine_verified=False,
baseline_indexes={str(k):str(v[2])for k,v in baseline.items()},baseline_original_entries_preserved=True,
baseline_files_modified=False,selected_EKeys=len(selected),duplicate_selected_EKeys_reused=len(frames)-len(selected),
created_segments=created,new_index_generations=audits,spans=spans,
native_encoded_frames_not_reencoded=True,all_new_spans_within_30bit_segments=True,
reachability_decided_by_caller=True,original_content_retention_required=True,
no_old_client_cleanup_performed=True)
(out/'manifest.json').write_text(json.dumps(report,indent=2)+'\n')
return report