fix: align tracker preprocessing and shared object lifecycle with native evidence

这个提交包含在:
mac 于 2026-11-05 03:49:21 +08:00 提交
1 父节点 9ba6eeb00a
当前提交 a0a97dfd88
14 个文件已更改
+312 -47

没有与搜索条件相匹配的文件

+171
查看文件
@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Read a user-exported CF plist/NSKeyedArchive as data; never instantiate classes."""
from pathlib import Path
from fractions import Fraction
import argparse, base64, hashlib, json, math, plistlib, struct, sys, uuid, zlib
MAX_BYTES=128*1024*1024
MAX_ARCHIVE=64*1024*1024
def inflate(data):
if data.startswith((b'bplist',b'<?xml')):return data
for window in (15,-15,31):
try:
d=zlib.decompressobj(window);out=d.decompress(data,MAX_ARCHIVE+1)
if len(out)>MAX_ARCHIVE or d.unconsumed_tail:raise ValueError('Decoded archive exceeds size limit')
out+=d.flush()
if len(out)>MAX_ARCHIVE:raise ValueError('Decoded archive exceeds size limit')
if d.eof and out.startswith((b'bplist',b'<?xml')):return out
except zlib.error:pass
raise ValueError('masks is neither a plist nor a supported zlib-compressed plist')
def decode_archive(data):
root=plistlib.loads(data)
if not isinstance(root,dict) or root.get('$archiver')!='NSKeyedArchiver':
raise ValueError('Expected an NSKeyedArchiver data container')
objects=root.get('$objects',[])
if not isinstance(objects,list) or len(objects)>200000:raise ValueError('Invalid object table')
expansions=0
def resolve(x,seen=frozenset(),depth=0):
nonlocal expansions
expansions+=1
if expansions>1000000:raise ValueError('Archive reference expansion exceeds limit')
if depth>100:raise ValueError('Archive nesting exceeds limit')
if isinstance(x,plistlib.UID):
i=x.data
if i==0:return None
if i<0 or i>=len(objects):raise ValueError('Archive UID out of range')
if i in seen:return {'$cycleUID':i}
return resolve(objects[i],seen|{i},depth+1)
if isinstance(x,list):return [resolve(y,seen,depth+1) for y in x]
if not isinstance(x,dict):return x
cls=x.get('$class');name=None
if isinstance(cls,plistlib.UID) and cls.data<len(objects):
descriptor=objects[cls.data]
if isinstance(descriptor,dict):name=descriptor.get('$classname')
values={k:resolve(v,seen,depth+1) for k,v in x.items() if k!='$class'}
if 'NS.keys' in values and 'NS.objects' in values:
return {str(k):v for k,v in zip(values['NS.keys'],values['NS.objects'])}
if name in ('NSArray','NSMutableArray','NSSet','NSMutableSet'):
return values.get('NS.objects',[])
if name in ('NSData','NSMutableData'):return values.get('NS.data',b'')
if name in ('NSString','NSMutableString'):return values.get('NS.string','')
if name:values['$class']=name
return values
top=root.get('$top',{});entry=top.get('root',next(iter(top.values()),None))
return resolve(entry)
def vector(value):
if isinstance(value,(int,float)):return [value]
if isinstance(value,(list,tuple)) and all(isinstance(v,(int,float)) for v in value):return list(value)
if isinstance(value,dict) and 'CICount' in value:
n=int(value['CICount'])
if 0<=n<=4:return [value.get('CI_'+str(i),0) for i in range(n)]
return None
def identifier(value):
if isinstance(value,dict) and isinstance(value.get('NS.uuidbytes'),bytes):
raw=value['NS.uuidbytes']
if len(raw)==16:return str(uuid.UUID(bytes=raw))
return str(value or '')
def keyframe(key):
if not isinstance(key,dict):raise ValueError('Unexpected keyframe representation')
data=key.get('data')
if isinstance(data,bytes):
if len(data)!=72 or struct.unpack_from('<I',data)[0]!=1:
raise ValueError('Unsupported FTKeyFrame binary version/size')
kind=struct.unpack_from('<Q',data,8)[0]
value,scale=struct.unpack_from('<qi',data,16)
epoch,count=struct.unpack_from('<qQ',data,32)
if scale<=0 or count>3:raise ValueError('Invalid keyframe time/vector count')
numbers=list(struct.unpack_from('<3d',data,48)[:count])
if any(not math.isfinite(x) for x in numbers):raise ValueError('Nonfinite keyframe value')
return {'time':{'value':value,'timescale':scale,'epoch':epoch,'seconds':value/scale},
'type':kind,'value':numbers}
time=key.get('time')
if isinstance(time,dict):
value=time.get('value',time.get('timeValue'));scale=time.get('timescale',time.get('timeScale'))
if value is not None and scale:
return {'time':{'value':int(value),'timescale':int(scale),'epoch':int(time.get('epoch',0)),
'seconds':int(value)/int(scale)},'type':key.get('type'),'value':vector(key.get('value'))}
raise ValueError('Legacy FTKeyFrame time encoding needs a verified fixture; preserved source required')
def parameter(value):
if not isinstance(value,dict):return {'staticValue':vector(value),'keys':[]}
keys=[keyframe(x) for x in value.get('keyFrames',[])]
keys.sort(key=lambda x:(x['time']['epoch'],Fraction(x['time']['value'],x['time']['timescale'])))
return {'type':value.get('type'),'staticValue':vector(value.get('value')),'keys':keys}
def geometry(scene):
result=[]
def walk(x):
if isinstance(x,list):
for v in x:walk(v)
elif isinstance(x,dict):
if all(k in x for k in ('position','rotation','scale')):
result.append({'id':identifier(x.get('identifier')),'name':x.get('name'),
'class':x.get('$class'),'enabled':x.get('enabled'),'inverted':x.get('inverted'),
'position':parameter(x['position']),'rotation':parameter(x['rotation']),'scale':parameter(x['scale'])})
for v in x.values():walk(v)
walk(scene);return result
def read_preset(path):
if path.stat().st_size>MAX_BYTES:raise ValueError('Input file exceeds size limit')
data=path.read_bytes()
outer=plistlib.loads(data if data.startswith((b'bplist',b'<?xml')) else inflate(data))
output={'input':str(path.resolve()),'inputSHA256':hashlib.sha256(data).hexdigest(),
'reader':'plistlib+zlib+struct; no Objective-C class loading',
'coordinateNote':'Raw authored position and radians; origin is not implicitly flipped or inferred.',
'versions':[]}
if isinstance(outer,dict) and outer.get('$archiver')=='NSKeyedArchiver':
items=[{'masks':data}]
elif isinstance(outer,dict):items=outer.get('versions',[outer])
else:raise ValueError('Expected an exported preset dictionary')
for index,item in enumerate(items):
if not isinstance(item,dict) or not item.get('masks'):continue
encoded=item['masks']
if isinstance(encoded,str):encoded=base64.b64decode(encoded,validate=True)
if not isinstance(encoded,bytes):raise ValueError('Expected masks data bytes')
archive=inflate(encoded);digest=hashlib.sha256(archive).digest();expected=item.get('masks_hash')
if isinstance(expected,str) and base64.b64encode(digest).decode()!=expected:
raise ValueError('masks_hash does not match the decompressed archive')
scene=decode_archive(archive)
if not isinstance(scene,dict):raise ValueError('Expected a tracker-scene dictionary')
output['versions'].append({'index':index,'name':item.get('name'),'active':item.get('active'),
'archiveSHA256':digest.hex(),'sceneID':identifier(scene.get('identifier')),
'aspectRatio':scene.get('aspectRatio'),'masks':geometry(scene)})
if not output['versions']:raise ValueError('No masks archive found; .cflook exports may omit trackerScene')
output['maskCount']=sum(len(x['masks']) for x in output['versions'])
output['keyCount']=sum(len(m[p]['keys']) for x in output['versions'] for m in x['masks'] for p in ('position','rotation','scale'))
return output
def self_test():
payload=bytearray(72);struct.pack_into('<I',payload,0,1);struct.pack_into('<Q',payload,8,2)
struct.pack_into('<qi',payload,16,1001,30000);struct.pack_into('<qQ',payload,32,0,2)
struct.pack_into('<3d',payload,48,.25,.75,0)
k=keyframe({'data':bytes(payload)})
assert k['time']['value']==1001 and k['time']['timescale']==30000 and k['value']==[.25,.75]
assert vector({'CICount':2,'CI_0':.25,'CI_1':.75})==[.25,.75]
data=plistlib.dumps({'$archiver':'NSKeyedArchiver','$version':100000,'$objects':['$null',
{'identifier':'fixture','nodes':plistlib.UID(2)}, {'NS.objects':[plistlib.UID(3)],'$class':plistlib.UID(4)},
{'position':{'value':{'CICount':2,'CI_0':.25,'CI_1':.75},'keyFrames':[{'data':bytes(payload)}]},
'rotation':{'value':0,'keyFrames':[]},'scale':{'value':[1,1],'keyFrames':[]}},
{'$classname':'NSArray','$classes':['NSArray','NSObject']}], '$top':{'root':plistlib.UID(1)}},fmt=plistlib.FMT_BINARY)
masks=geometry(decode_archive(inflate(zlib.compress(data))))
assert len(masks)==1 and masks[0]['position']['keys'][0]['value']==[.25,.75]
print(json.dumps({'pass':True,'checks':['72-byte-exact-rational-time','system-CIVector-field-layout',
'zlib-keyed-plist-UID-array-geometry'],'scope':'Generated data only; no original exported preset used.'}))
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('input',type=Path,nargs='?');p.add_argument('--output',type=Path);p.add_argument('--self-test',action='store_true');args=p.parse_args()
if args.self_test:self_test();return
if not args.input:p.error('a user-exported .plist or raw masks archive is required')
result=read_preset(args.input);text=json.dumps(result,ensure_ascii=False,indent=2,allow_nan=False)+'\n'
if args.output:args.output.write_text(text)
else:sys.stdout.write(text)
if __name__=='__main__':
try:main()
except (ValueError,TypeError,KeyError,IndexError,plistlib.InvalidFileException,OSError) as error:
print('Cannot extract verified tracks: '+str(error),file=sys.stderr);sys.exit(1)