"""Bounded Qt RCC and VESC package containers. Never evaluates QML or Lisp.""" import hashlib import re import struct import zlib MAX_ARCHIVE=8*1024*1024 MAX_PACKAGE=1024*1024 MAX_EXPANDED=4*1024*1024 def digest(data):return hashlib.sha256(data).hexdigest() def uncompress(data,limit=MAX_EXPANDED): if len(data)<5:raise ValueError('Truncated Qt compressed data') size=int.from_bytes(data[:4],'big') if not 0len(raw):raise ValueError('Invalid package field') name=raw[at:end].decode('ascii');size=struct.unpack_from('>i',raw,end+1)[0];at=end+5 if name in out or size<0 or size>len(raw)-at or len(out)>=32:raise ValueError('Duplicate, truncated or excessive package field') out[name]=raw[at:at+size];at+=size if not out.get('name') or len(out['name'])>256:raise ValueError('Package name required') for k in ('name','description','description_md','qmlFile','pkgDescQml'): if k in out and b'\0' in out[k]:raise ValueError('Invalid text field') if k in out:out[k].decode('utf-8') if out.get('qmlIsFullscreen',b'\0') not in (b'\0',b'\1'):raise ValueError('Invalid fullscreen flag') return out def metadata(data,path='import.vescpkg'): f=fields(data) return {'id':digest(data),'path':path,'name':f['name'].decode(),'library':path.split('/')[0].startswith('lib_'), 'bytes':len(data),'lisp_bytes':len(f.get('lispData',b'')),'qml_bytes':len(f.get('qmlFile',b'')), 'description':f.get('description_md',b'').decode()[:65536], 'has_compatibility':bool(f.get('pkgDescQml'))} def archive(data): if not 24<=len(data)<=MAX_ARCHIVE or data[:4]!=b'qres':raise ValueError('Invalid Qt package archive') version,tree,blobs,names,features=struct.unpack_from('>5I',data,4) if version not in (2,3) or features!=0 or not 24<=blobs5:raise ValueError('Invalid RCC tree') seen.add(index);at=tree+index*22;name_offset,flags=struct.unpack_from('>IH',data,at) if flags&~3:raise ValueError('Unsupported RCC compression') if index==0:path='' else: n=names+name_offset if not names<=ntree:raise ValueError('RCC name exceeds bound') name=data[n+6:n+6+size*2].decode('utf-16-be') if not re.fullmatch(r'[A-Za-z0-9_. -]{1,128}',name) or name in ('.','..'):raise ValueError('Invalid RCC path') path=parent+'/'+name if parent else name if flags&2: children,first=struct.unpack_from('>II',data,at+6) if children<1 or first+children>count:raise ValueError('Invalid RCC children') for i in range(first,first+children):visit(i,path,depth+1) else: offset=int.from_bytes(data[at+10:at+14],'big');pos=blobs+offset if not blobs<=posnames:raise ValueError('Invalid RCC file size') blob=data[pos+4:pos+4+size] if flags&1:blob=uncompress(blob,MAX_PACKAGE) if not path.startswith('vesc_packages/') or not path.endswith('.vescpkg') or path in out:raise ValueError('Unexpected RCC member') total+=len(blob) if total>MAX_ARCHIVE or len(out)>=128:raise ValueError('Catalog exceeds bound') fields(blob);out[path.removeprefix('vesc_packages/')]=blob visit(0,'',0) if len(seen)!=count or not out:raise ValueError('Incomplete RCC tree') return out