166 lines
9.4 KiB
Python
166 lines
9.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Offline Source keyring routing and isolated codec-tail/mask fixtures."""
|
|
import argparse
|
|
import concurrent.futures
|
|
import ctypes
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
G=Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0,str(G/'ops'))
|
|
import keyring_serializer as adapter
|
|
|
|
parser=argparse.ArgumentParser(add_help=False)
|
|
parser.add_argument('--protocol-library',type=Path,default=G/'build/libgateway_protocol.a')
|
|
args,remaining=parser.parse_known_args()
|
|
CXX=shutil.which('c++')
|
|
SDK_ROOT=Path.home()/'Projects/WoW-Hybrid/servers/trinity-forever'
|
|
SDK_RELATIVE='src/server/game/Entities/Object/Updates/UpdateFields.cpp'
|
|
SDK=SDK_ROOT/SDK_RELATIVE
|
|
SDK_REVISION='3b77f715f40e2052f9fe9aedb2cde5e77aeeaae5'
|
|
|
|
def pinned_sdk():
|
|
expected=json.loads((G/'docs/FOREVER_SCHEMA_PROFILE.json').read_text())['forever_sha256'][SDK_RELATIVE]
|
|
raw=SDK.read_bytes()
|
|
if hashlib.sha256(raw).hexdigest()!=expected:
|
|
# The shared SDK checkout may advance independently. Read the audited
|
|
# object without modifying it; the original digest remains mandatory.
|
|
raw=subprocess.check_output(['git','-C',str(SDK_ROOT),'show',SDK_REVISION+':'+SDK_RELATIVE])
|
|
if hashlib.sha256(raw).hexdigest()!=expected:
|
|
raise AssertionError('Pinned SDK serializer digest differs')
|
|
return raw
|
|
|
|
|
|
def method(text,needle):
|
|
start=text.index(needle);brace=text.index('{',start);depth=1;end=brace+1
|
|
while depth:
|
|
depth+=(text[end]=='{')-(text[end]=='}');end+=1
|
|
return text[start:end]
|
|
|
|
class KeyringProjectionTest(unittest.TestCase):
|
|
def test_actual_pinned_serializer_boundaries_and_drift(self):
|
|
if not SDK.exists():self.skipTest('Pinned SDK is required for original serializer-fragment integration')
|
|
raw=pinned_sdk();profile=json.loads((G/'docs/FOREVER_SCHEMA_PROFILE.json').read_text())
|
|
self.assertEqual(hashlib.sha256(raw).hexdigest(),profile['forever_sha256']['src/server/game/Entities/Object/Updates/UpdateFields.cpp'])
|
|
text=raw.decode();create=method(text,'void ActivePlayerData::WriteCreate(');update=method(text,'void ActivePlayerData::WriteUpdate(Mask const&')
|
|
self.assertEqual(adapter.create(create).count('keyring_wire::create_tail<ObjectGuid>'),1)
|
|
self.assertEqual(adapter.update(update).count('keyring_wire::update_tail<ObjectGuid>'),1)
|
|
mask=text[text.index('template<std::size_t ClassicBlockCount'):text.index('void UnitData::WriteUpdate(Mask const&')]
|
|
self.assertEqual(adapter.mask_header(mask).count('keyring_wire::overlay_mask<ObjectGuid>'),1)
|
|
for transform,fragment in [(adapter.create,create),(adapter.update,update),(adapter.mask_header,mask)]:
|
|
with self.assertRaises(ValueError):transform(fragment+fragment)
|
|
with self.assertRaises(ValueError):transform('unqualified different SDK body')
|
|
|
|
def test_real_inventory_translation_all32_controls_events_and_clears(self):
|
|
if sys.platform!='linux':self.skipTest('Host Linux archive/linker fixture; Windows codec acceptance is separate')
|
|
if not CXX:self.skipTest('C++ compiler unavailable')
|
|
if not args.protocol_library.exists():self.skipTest('Matching protocol archive required for native inventory fixture')
|
|
with args.protocol_library.open('rb')as stream:self.assertEqual(stream.read(8),b'!<arch>\n')
|
|
with tempfile.TemporaryDirectory(dir=G/'build',prefix='keyring-inventory-')as directory:
|
|
binary=Path(directory)/'fixture'
|
|
command=[CXX,'-std=c++20','-O1','-ffunction-sections','-fdata-sections','-I'+str(G/'include'),'-I'+str(G/'native'),str(G/'tests/keyring_inventory_test.cpp'),str(G/'native/inventory_translation.cpp'),str(args.protocol_library),'-Wl,--gc-sections','-lcrypto','-lz','-pthread','-o',str(binary)]
|
|
result=subprocess.run(command,capture_output=True,text=True)
|
|
self.assertEqual(result.returncode,0,result.stderr)
|
|
result=subprocess.run([str(binary)],capture_output=True,text=True)
|
|
self.assertEqual(result.returncode,0,result.stdout+result.stderr)
|
|
self.assertIn('All32',result.stdout)
|
|
|
|
def test_same_codec_two_tus_tls_lifetime_masks_and_other_dll_isolation(self):
|
|
if sys.platform!='linux':self.skipTest('ELF module-isolation fixture; Windows codec acceptance is separate')
|
|
if not CXX:self.skipTest('C++ compiler unavailable')
|
|
if not SDK.exists():self.skipTest('Pinned original mask helper required')
|
|
text=pinned_sdk().decode()
|
|
generic=text[text.index('template<std::size_t ClassicBlockCount'):text.index('void UnitData::WriteUpdate(Mask const&')]
|
|
generic=adapter.mask_header(generic)
|
|
active=text[text.index('static uint32 ClassicActivePlayerDataBit('):text.index('void ActivePlayerData::WriteUpdate(Mask const&')]
|
|
consumer=r'''
|
|
#include "gateway/keyring_wire.hpp"
|
|
#include <vector>
|
|
#include <utility>
|
|
using uint32=uint32_t;
|
|
using ObjectGuid=std::array<uint64_t,2>;
|
|
struct ByteBuffer {
|
|
std::vector<ObjectGuid> guids;
|
|
std::vector<std::pair<uint32_t,unsigned>> bits;
|
|
ByteBuffer& operator<<(ObjectGuid const& guid){guids.push_back(guid);return *this;}
|
|
void WriteBits(uint32_t value,unsigned width){bits.emplace_back(value,width);}
|
|
};
|
|
struct Mask {static constexpr unsigned BlockCount=14;std::array<bool,448> flags{};bool operator[](unsigned i)const{return flags.at(i);}};
|
|
'''+generic+'\n'+active+r'''
|
|
__attribute__((visibility("hidden"))) int consume(uint64_t seed,uint32_t changed) {
|
|
using namespace gateway::keyring_wire;
|
|
if(!current<ObjectGuid> || current<ObjectGuid>->changed!=changed)return 1;
|
|
ByteBuffer create;
|
|
for(unsigned slot=108;slot<145;++slot)create_tail<ObjectGuid>(create,slot);
|
|
if(create.guids.size()!=37)return 2;
|
|
for(unsigned i=0;i<37;++i){
|
|
ObjectGuid want{};unsigned slot=108+i;
|
|
if(slot>=112&&slot<144)want={seed+slot-112,uint64_t(3)<<58};
|
|
if(create.guids[i]!=want)return 3;
|
|
}
|
|
for(bool ordinary:{false,true}){
|
|
Mask original;if(ordinary)original.flags[164+35]=true;
|
|
ByteBuffer out;auto blocks=WriteClassicChangesMaskHeader<14>(out,original,&ClassicActivePlayerDataBit,ClassicActivePlayerDataGroups);
|
|
auto bit=[&](unsigned n){return (blocks[n/32]>>(n%32))&1;};
|
|
if(bit(204)!=ordinary || bit(168)!=(ordinary||changed))return 4;
|
|
for(unsigned i=0;i<32;++i)if(bit(281+i)!=((changed>>i)&1))return 5;
|
|
for(unsigned i:{277u,278u,279u,280u,313u})if(bit(i))return 6;
|
|
}
|
|
ByteBuffer updates;update_tail<ObjectGuid>(updates);
|
|
unsigned at=0;for(unsigned i=0;i<32;++i)if((changed>>i)&1){if(updates.guids.at(at++)!=ObjectGuid{seed+i,uint64_t(3)<<58})return 7;}
|
|
if(updates.guids.size()!=at)return 8;
|
|
return 0;
|
|
}
|
|
'''
|
|
producer=r'''
|
|
#include "gateway/keyring_wire.hpp"
|
|
using Guid=std::array<uint64_t,2>;
|
|
__attribute__((visibility("hidden"))) int consume(uint64_t,uint32_t);
|
|
extern "C" int active(){return gateway::keyring_wire::current<Guid>!=nullptr;}
|
|
extern "C" int run(uint64_t seed,uint32_t mask,int(*other)()){
|
|
using namespace gateway::keyring_wire;
|
|
if(current<Guid>)return 10;
|
|
View<Guid> view;view.changed=mask;
|
|
for(unsigned i=0;i<32;++i)view.guids[i]={seed+i,uint64_t(3)<<58};
|
|
{
|
|
Scope<Guid> scope(view);if(other && other())return 11;
|
|
if(int e=consume(seed,mask))return e;
|
|
try{View<Guid> nested=view;for(auto& guid:nested.guids)guid[0]+=1000;Scope<Guid> inner(nested);if(int e=consume(seed+1000,mask))return e;throw 1;}catch(int){}
|
|
if(int e=consume(seed,mask))return e;
|
|
}
|
|
if(current<Guid>)return 12;
|
|
struct Buffer{unsigned count=0;bool zeros=true;Buffer& operator<<(Guid const& guid){++count;zeros&=guid==Guid{};return *this;}};
|
|
Buffer original;for(unsigned slot=108;slot<145;++slot)create_tail<Guid>(original,slot);
|
|
if(original.count!=37||!original.zeros)return 13;
|
|
std::array<uint32_t,14> empty{};overlay_mask<Guid>(empty);for(auto v:empty)if(v)return 14;
|
|
update_tail<Guid>(original);if(original.count!=37)return 15;
|
|
try{create_tail<Guid>(original,145);return 16;}catch(std::out_of_range const&){}
|
|
return 0;
|
|
}
|
|
'''
|
|
with tempfile.TemporaryDirectory(dir=G/'build',prefix='keyring-codec-scope-')as directory:
|
|
folder=Path(directory);(folder/'consumer.cpp').write_text(consumer);(folder/'producer.cpp').write_text(producer)
|
|
libraries=[]
|
|
for i in range(2):
|
|
target=folder/f'codec{i}.so';result=subprocess.run([CXX,'-std=c++20','-O0','-fPIC','-shared','-I'+str(G/'include'),str(folder/'consumer.cpp'),str(folder/'producer.cpp'),'-o',str(target)],capture_output=True,text=True)
|
|
self.assertEqual(result.returncode,0,result.stderr)
|
|
library=ctypes.CDLL(str(target),mode=os.RTLD_GLOBAL);library.active.restype=ctypes.c_int
|
|
libraries.append(library)
|
|
callback=ctypes.CFUNCTYPE(ctypes.c_int)
|
|
callbacks=[callback(libraries[1].active),callback(libraries[0].active)]
|
|
for i,library in enumerate(libraries):
|
|
library.run.argtypes=[ctypes.c_uint64,ctypes.c_uint32,callback];library.run.restype=ctypes.c_int
|
|
for mask in [0,1,0x80000000,0x80000001,0xffffffff]:self.assertEqual(library.run(1000,mask,callbacks[i]),0)
|
|
self.assertEqual(library.active(),0)
|
|
def task(i):return libraries[i%2].run(10000+i*100,1<<(i%32),callbacks[i%2])
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=4)as pool:self.assertEqual(list(pool.map(task,range(32))),[0]*32)
|
|
|
|
if __name__=='__main__':unittest.main(argv=[sys.argv[0],*remaining])
|