mirror of
https://github.com/saphid/frame-control.git
synced 2026-10-06 02:00:19 +02:00
Detect VR APKs and repair launchers with pure Python v2 signing
This commit is contained in:
1 parent
724b020e93
commit
a1bc6522c3
8 files changed
+761
-8
No files matched your search
+56
-4
@@ -6,12 +6,18 @@ apps, the lepton-show-flatscreen marker; plus a non-Steam shortcut, so it shows
|
||||
in the Steam library and gets its own SteamVR panel. Nothing goes through
|
||||
Lepton Development, which wipes its apps on exit. See docs/apks.md.
|
||||
|
||||
Python stdlib only. CLI: python3 ui/frame_android.py {install APK|list|launch PKG|stop PKG|remove PKG|probe PKG}
|
||||
Python stdlib only. CLI: python3 ui/frame_android.py
|
||||
install APK [--vr|--flat] | info APK | patch SRC DST [--add NAME=PATH ...]
|
||||
list | launch PKG | stop PKG | remove PKG | probe PKG
|
||||
"""
|
||||
import json, os, re, shlex, shutil, subprocess, sys, threading, time, zlib
|
||||
|
||||
import frame_apk
|
||||
import frame_host
|
||||
import tempfile
|
||||
import zipfile
|
||||
from frame_apk_vr import add_launcher_category
|
||||
from frame_apk_sign import repack
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
FRAME = os.environ.get('FRAME_ALIAS', 'frame')
|
||||
@@ -106,7 +112,7 @@ def _write_meta(d, meta):
|
||||
ssh(f'cat > {d}/meta.json.tmp && mv {d}/meta.json.tmp {d}/meta.json', input=json.dumps(meta, indent=1))
|
||||
|
||||
|
||||
def install(apk_path, flatscreen=True, name=None, source=None, icon_png=None):
|
||||
def install(apk_path, flatscreen=None, name=None, source=None, icon_png=None):
|
||||
info = apk_info(apk_path)
|
||||
if icon_png:
|
||||
info['icon_png'] = icon_png
|
||||
@@ -114,7 +120,16 @@ def install(apk_path, flatscreen=True, name=None, source=None, icon_png=None):
|
||||
pkg = info['package']
|
||||
if not PKG_RE.match(pkg):
|
||||
raise FrameError(f'unexpected package name {pkg!r}')
|
||||
if flatscreen is None:
|
||||
flatscreen = not info['vr']
|
||||
with _install_lock:
|
||||
if not info['launchable'] and info['vr_activity']:
|
||||
with tempfile.TemporaryDirectory(prefix='frame-vr-') as tmp:
|
||||
patched = os.path.join(tmp, 'app.apk')
|
||||
patch(apk_path, patched)
|
||||
info['patched'] = ['launcher']
|
||||
info['launchable'] = True
|
||||
return _install(patched, info, pkg, flatscreen, name, source or os.path.basename(apk_path))
|
||||
return _install(apk_path, info, pkg, flatscreen, name, source)
|
||||
|
||||
|
||||
@@ -143,6 +158,8 @@ def _install(apk_path, info, pkg, flatscreen, name, source):
|
||||
raise FrameError(f'Steam did not return a shortcut id (got {reply[:80]!r})')
|
||||
meta = {'package': pkg, 'label': name or info['label'], 'version': info['version'],
|
||||
'instance': iid, 'shortcut': shortcut, 'game_id': game_id(shortcut),
|
||||
'vr': info.get('vr', False), 'vr_issues': info.get('vr_issues', []),
|
||||
'launchable': info.get('launchable', False), 'patched': info.get('patched', []),
|
||||
'flatscreen': flatscreen, 'installed': time.strftime('%Y-%m-%dT%H:%M:%S'),
|
||||
'source': source or os.path.basename(apk_path)}
|
||||
_write_meta(d, meta)
|
||||
@@ -273,11 +290,46 @@ def probe(pkg, wait=20):
|
||||
'container_up': ctr in running_instances()}
|
||||
|
||||
|
||||
def patch(src, dst, add=None):
|
||||
try:
|
||||
info = apk_info(src)
|
||||
with zipfile.ZipFile(src) as z:
|
||||
original = frame_apk._read(z, 'AndroidManifest.xml', frame_apk.MAX_MANIFEST)
|
||||
manifest = add_launcher_category(original) if info['vr_activity'] else original
|
||||
if not info['launchable'] and not info['vr_activity']:
|
||||
raise FrameError('APK has no MAIN/LAUNCHER or patchable VR activity')
|
||||
repack(src, dst, replace={'AndroidManifest.xml': manifest}, add=add)
|
||||
result = apk_info(dst)
|
||||
result.pop('icon_png', None)
|
||||
result['patched'] = ['launcher'] if manifest != original else []
|
||||
return result
|
||||
except (OSError, ValueError, zipfile.BadZipFile, frame_apk.ApkError) as e:
|
||||
raise FrameError(str(e)) from e
|
||||
|
||||
|
||||
def main():
|
||||
cmd, *args = sys.argv[1:] or ['help']
|
||||
try:
|
||||
if cmd == 'install':
|
||||
r = install(args[0], flatscreen='--vr' not in args)
|
||||
r = install(args[0], flatscreen=False if '--vr' in args else True if '--flat' in args else None)
|
||||
elif cmd in ('info', 'describe'):
|
||||
r = apk_info(args[0])
|
||||
r.pop('icon_png', None)
|
||||
elif cmd == 'patch':
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description='Patch and v2-sign an APK locally')
|
||||
parser.add_argument('src')
|
||||
parser.add_argument('dst')
|
||||
parser.add_argument('--add', action='append', default=[], metavar='NAME=PATH')
|
||||
opts = parser.parse_args(args)
|
||||
additions = {}
|
||||
for item in opts.add:
|
||||
if '=' not in item:
|
||||
raise FrameError('--add requires NAME=PATH')
|
||||
entry, path = item.split('=', 1)
|
||||
with open(path, 'rb') as f:
|
||||
additions[entry] = f.read()
|
||||
r = patch(opts.src, opts.dst, additions)
|
||||
elif cmd == 'list':
|
||||
r = list_apps()
|
||||
elif cmd in ('launch', 'stop', 'probe'):
|
||||
@@ -286,7 +338,7 @@ def main():
|
||||
r = remove(args[0], keep_data='--keep-data' in args)
|
||||
else:
|
||||
sys.exit(__doc__)
|
||||
except FrameError as e:
|
||||
except (FrameError, OSError) as e:
|
||||
sys.exit(f'error: {e}')
|
||||
print(json.dumps(r, indent=1))
|
||||
|
||||
|
||||
+6
-2
@@ -10,7 +10,7 @@ import zipfile
|
||||
|
||||
# android: attribute resource ids; names can be stripped by shrinkers, ids can't.
|
||||
ATTR = {0x01010001: 'label', 0x01010002: 'icon', 0x01010003: 'name',
|
||||
0x0101021b: 'versionCode', 0x0101021c: 'versionName', 0x0101020c: 'minSdkVersion'}
|
||||
0x01010024: 'value', 0x0101021b: 'versionCode', 0x0101021c: 'versionName', 0x0101020c: 'minSdkVersion'}
|
||||
T_REF, T_STRING, T_INT_DEC, T_INT_HEX = 0x01, 0x03, 0x10, 0x11
|
||||
# APKs can come from websites (install links), so nothing read from one may be
|
||||
# unbounded. zipfile stops at a member's declared size, so checking it is enough.
|
||||
@@ -215,8 +215,11 @@ def apk_info(path):
|
||||
if 'AndroidManifest.xml' not in names:
|
||||
raise ApkError('not an APK: no AndroidManifest.xml')
|
||||
try:
|
||||
elements = manifest_elements(_read(z, 'AndroidManifest.xml', MAX_MANIFEST))
|
||||
manifest_data = _read(z, 'AndroidManifest.xml', MAX_MANIFEST)
|
||||
elements = manifest_elements(manifest_data)
|
||||
res = Resources(_read(z, 'resources.arsc', MAX_ARSC) if 'resources.arsc' in names else b'')
|
||||
from frame_apk_vr import detection
|
||||
vr_info = detection(manifest_data, names)
|
||||
except (struct.error, IndexError, zipfile.BadZipFile) as e:
|
||||
raise ApkError(f'could not read the APK manifest: {e}')
|
||||
tags = {}
|
||||
@@ -235,6 +238,7 @@ def apk_info(path):
|
||||
'min_sdk': min_sdk[1] if min_sdk and min_sdk[0] in (T_INT_DEC, T_INT_HEX) else None,
|
||||
'icon_png': None,
|
||||
}
|
||||
info.update(vr_info)
|
||||
try:
|
||||
info['icon_png'] = _icon_png(z, names, _icons(app.get('icon'), res))
|
||||
except Exception: # noqa: BLE001 - any unreadable icon just means no icon
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
"""Lossless ZIP repacking and APK v2 RSA/SHA-256 signing, Python 3.9 stdlib.
|
||||
|
||||
Spec: https://source.android.com/docs/security/features/apksigning/v2
|
||||
Sections: APK Signing Block; APK Signature Scheme v2 Block; Integrity-protected
|
||||
contents; Verification. No verity algorithm is used, so no verity padding.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import struct
|
||||
import tempfile
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
import frame_host
|
||||
|
||||
MAGIC = b'APK Sig Block 42'
|
||||
V2 = 0x7109871a
|
||||
ALG = 0x0103
|
||||
SHA256_DER = bytes.fromhex('3031300d060960864801650304020105000420')
|
||||
|
||||
|
||||
def u32(n):
|
||||
return struct.pack('<I', n)
|
||||
|
||||
|
||||
def lp(b):
|
||||
return u32(len(b)) + b
|
||||
|
||||
|
||||
def der(tag, b):
|
||||
n = len(b)
|
||||
length = bytes([n]) if n < 128 else bytes([128 + (n.bit_length() + 7) // 8]) + n.to_bytes((n.bit_length() + 7) // 8, 'big')
|
||||
return bytes([tag]) + length + b
|
||||
|
||||
|
||||
def integer(n):
|
||||
b = n.to_bytes((n.bit_length() + 7) // 8 or 1, 'big')
|
||||
return der(2, (b'\0' if b[0] & 128 else b'') + b)
|
||||
|
||||
|
||||
def sequence(*items):
|
||||
return der(0x30, b''.join(items))
|
||||
|
||||
|
||||
RSA_ALG = bytes.fromhex('300d06092a864886f70d0101010500')
|
||||
CERT_ALG = bytes.fromhex('300d06092a864886f70d01010b0500')
|
||||
|
||||
|
||||
def public_key(key):
|
||||
return sequence(RSA_ALG, der(3, b'\0' + sequence(integer(key['n']), integer(key['e']))))
|
||||
|
||||
|
||||
def encoded_hash(data, size):
|
||||
digest = SHA256_DER + hashlib.sha256(data).digest()
|
||||
return b'\0\1' + b'\xff' * (size - len(digest) - 3) + b'\0' + digest
|
||||
|
||||
|
||||
def rsa_sign(data, key):
|
||||
size = (key['n'].bit_length() + 7) // 8
|
||||
return pow(int.from_bytes(encoded_hash(data, size), 'big'), key['d'], key['n']).to_bytes(size, 'big')
|
||||
|
||||
|
||||
def rsa_verify(data, sig, n, e):
|
||||
size = (n.bit_length() + 7) // 8
|
||||
if len(sig) != size or int.from_bytes(sig, 'big') >= n:
|
||||
raise ValueError('invalid RSA signature size/value')
|
||||
actual = pow(int.from_bytes(sig, 'big'), e, n).to_bytes(size, 'big')
|
||||
if actual != encoded_hash(data, size):
|
||||
raise ValueError('RSA signature mismatch')
|
||||
|
||||
|
||||
def certificate(key):
|
||||
name = sequence(der(0x31, sequence(bytes.fromhex('0603550403'), der(12, b'Frame Control APK signer'))))
|
||||
validity = sequence(der(0x17, b'200101000000Z'), der(0x18, b'21200101000000Z'))
|
||||
tbs = sequence(der(0xa0, integer(2)), integer(1), CERT_ALG, name, validity, name, public_key(key))
|
||||
return sequence(tbs, CERT_ALG, der(3, b'\0' + rsa_sign(tbs, key)))
|
||||
|
||||
|
||||
def _prime(bits):
|
||||
small = (3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)
|
||||
while True:
|
||||
n = secrets.randbits(bits) | (3 << (bits - 2)) | 1
|
||||
if any(n % p == 0 for p in small) or (n - 1) % 65537 == 0:
|
||||
continue
|
||||
d, s = n - 1, 0
|
||||
while d % 2 == 0:
|
||||
d //= 2
|
||||
s += 1
|
||||
for _ in range(40): # Miller-Rabin error bound <= 2^-80
|
||||
x = pow(secrets.randbelow(n - 3) + 2, d, n)
|
||||
if x in (1, n - 1):
|
||||
continue
|
||||
for _ in range(s - 1):
|
||||
x = pow(x, 2, n)
|
||||
if x == n - 1:
|
||||
break
|
||||
else:
|
||||
break
|
||||
else:
|
||||
return n
|
||||
|
||||
|
||||
def signing_key(path=None):
|
||||
"""Persistent identity in app data, never an evictable cache. Atomic publication.
|
||||
|
||||
Hard-linking a fully written private temp file prevents concurrent first-use
|
||||
callers from selecting different identities or reading a partial key.
|
||||
"""
|
||||
path = Path(path) if path is not None else frame_host.data_dir('apk-signing-key.json')
|
||||
if not path.exists():
|
||||
p, q = _prime(1024), _prime(1024)
|
||||
while q == p:
|
||||
q = _prime(1024)
|
||||
key = {'n': p * q, 'e': 65537, 'd': pow(65537, -1, math.lcm(p - 1, q - 1))}
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(prefix='.apk-key-', dir=str(path.parent))
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
json.dump(key, f)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
try:
|
||||
os.link(tmp, path)
|
||||
except FileExistsError:
|
||||
pass
|
||||
finally:
|
||||
os.unlink(tmp)
|
||||
os.chmod(path, 0o600)
|
||||
key = json.loads(path.read_text())
|
||||
if key['n'].bit_length() != 2048 or key['e'] != 65537:
|
||||
raise ValueError('invalid cached APK signing key')
|
||||
rsa_verify(b'key check', rsa_sign(b'key check', key), key['n'], key['e'])
|
||||
return key
|
||||
|
||||
|
||||
def _eocd(data):
|
||||
# ZIP comments can contain the EOCD signature; accept only an exact EOF fit.
|
||||
for at in range(len(data) - 22, max(-1, len(data) - 65558), -1):
|
||||
if data[at:at + 4] == b'PK\5\6' and at + 22 + struct.unpack_from('<H', data, at + 20)[0] == len(data):
|
||||
disk, cd_disk, count_disk, count, size, cd = struct.unpack_from('<HHHHII', data, at + 4)
|
||||
if disk or cd_disk or count_disk != count or count == 65535 or cd + size != at:
|
||||
raise ValueError('multi-disk/ZIP64 or invalid APK directory')
|
||||
return at, cd
|
||||
raise ValueError('missing ZIP end record')
|
||||
|
||||
|
||||
def content_digest(sections):
|
||||
chunks = []
|
||||
for section in sections:
|
||||
for off in range(0, len(section), 1024 * 1024):
|
||||
part = section[off:off + 1024 * 1024]
|
||||
chunks.append(hashlib.sha256(b'\xa5' + u32(len(part)) + part).digest())
|
||||
return hashlib.sha256(b'\x5a' + u32(len(chunks)) + b''.join(chunks)).digest()
|
||||
|
||||
|
||||
def sign_apk(data, key):
|
||||
eo, cd = _eocd(data)
|
||||
digest = content_digest((memoryview(data)[:cd], memoryview(data)[cd:eo], data[eo:]))
|
||||
signed = lp(lp(u32(ALG) + lp(digest))) + lp(lp(certificate(key))) + lp(b'')
|
||||
signer = lp(signed) + lp(lp(u32(ALG) + lp(rsa_sign(signed, key)))) + lp(public_key(key))
|
||||
value = lp(lp(signer))
|
||||
pair = struct.pack('<Q', 4 + len(value)) + u32(V2) + value
|
||||
size = len(pair) + 24
|
||||
block = struct.pack('<Q', size) + pair + struct.pack('<Q', size) + MAGIC
|
||||
end = bytearray(data[eo:])
|
||||
struct.pack_into('<I', end, 16, cd + len(block))
|
||||
return data[:cd] + block + data[cd:eo] + end
|
||||
|
||||
|
||||
def _parts(data):
|
||||
result, off = [], 0
|
||||
while off < len(data):
|
||||
if off + 4 > len(data):
|
||||
raise ValueError('truncated length prefix')
|
||||
size = struct.unpack_from('<I', data, off)[0]
|
||||
off += 4
|
||||
if off + size > len(data):
|
||||
raise ValueError('length prefix outside block')
|
||||
result.append(data[off:off + size])
|
||||
off += size
|
||||
return result
|
||||
|
||||
|
||||
def _der_parts(data):
|
||||
result, off = [], 0
|
||||
while off < len(data):
|
||||
start = off
|
||||
tag, size = data[off:off + 2]
|
||||
off += 2
|
||||
if size & 128:
|
||||
count = size & 127
|
||||
if not count or count > 4:
|
||||
raise ValueError('invalid DER length')
|
||||
size = int.from_bytes(data[off:off + count], 'big')
|
||||
off += count
|
||||
if off + size > len(data):
|
||||
raise ValueError('truncated DER')
|
||||
result.append((tag, data[off:off + size], data[start:off + size]))
|
||||
off += size
|
||||
return result
|
||||
|
||||
|
||||
def _cert_key(cert):
|
||||
outer = _der_parts(cert)
|
||||
if len(outer) != 1 or outer[0][0] != 0x30:
|
||||
raise ValueError('invalid certificate')
|
||||
fields = _der_parts(outer[0][1])
|
||||
tbs = _der_parts(fields[0][1])
|
||||
spki = tbs[6 if tbs[0][0] == 0xa0 else 5][2]
|
||||
pub = _der_parts(_der_parts(spki)[0][1])
|
||||
if pub[0][2] != RSA_ALG or pub[1][1][:1] != b'\0':
|
||||
raise ValueError('certificate is not RSA')
|
||||
numbers = _der_parts(_der_parts(pub[1][1][1:])[0][1])
|
||||
n, e = [int.from_bytes(item[1], 'big') for item in numbers]
|
||||
return n, e, spki
|
||||
|
||||
|
||||
def verify(path):
|
||||
"""Verify this v2-only format; return True or raise ValueError on corruption.
|
||||
|
||||
A valid signature establishes integrity, not trust in the APK publisher.
|
||||
"""
|
||||
data = Path(path).read_bytes()
|
||||
try:
|
||||
eo, cd = _eocd(data)
|
||||
if data[cd - 16:cd] != MAGIC:
|
||||
raise ValueError('no APK signing block')
|
||||
size = struct.unpack_from('<Q', data, cd - 24)[0]
|
||||
start = cd - size - 8
|
||||
if start < 0 or struct.unpack_from('<Q', data, start)[0] != size:
|
||||
raise ValueError('invalid signing block size')
|
||||
off, values = start + 8, []
|
||||
while off < cd - 24:
|
||||
length = struct.unpack_from('<Q', data, off)[0]
|
||||
if length < 4 or off + 8 + length > cd - 24:
|
||||
raise ValueError('invalid signing pair')
|
||||
ident = struct.unpack_from('<I', data, off + 8)[0]
|
||||
if ident == V2:
|
||||
values.append(data[off + 12:off + 8 + length])
|
||||
off += 8 + length
|
||||
if off != cd - 24 or len(values) != 1:
|
||||
raise ValueError('missing or duplicate v2 signer block')
|
||||
end = bytearray(data[eo:])
|
||||
struct.pack_into('<I', end, 16, start)
|
||||
digest = content_digest((memoryview(data)[:start], memoryview(data)[cd:eo], end))
|
||||
wrappers = _parts(values[0])
|
||||
if len(wrappers) != 1:
|
||||
raise ValueError('invalid signers sequence')
|
||||
signers = _parts(wrappers[0])
|
||||
if not signers:
|
||||
raise ValueError('no signers')
|
||||
for signer in signers:
|
||||
signed, signatures, pub = _parts(signer)
|
||||
digests, certs, attrs = _parts(signed)
|
||||
cert = _parts(certs)[0]
|
||||
n, e, cert_pub = _cert_key(cert)
|
||||
if cert_pub != pub:
|
||||
raise ValueError('public key differs from certificate')
|
||||
sigs, digs = _parts(signatures), _parts(digests)
|
||||
if len(sigs) != 1 or len(digs) != 1 or sigs[0][:4] != u32(ALG) or digs[0][:4] != u32(ALG):
|
||||
raise ValueError('unsupported signature algorithm')
|
||||
if _parts(digs[0][4:]) != [digest]:
|
||||
raise ValueError('APK content digest mismatch')
|
||||
sig = _parts(sigs[0][4:])
|
||||
if len(sig) != 1:
|
||||
raise ValueError('invalid signature sequence')
|
||||
rsa_verify(signed, sig[0], n, e)
|
||||
return True
|
||||
except (IndexError, struct.error, OverflowError) as exc:
|
||||
raise ValueError('malformed APK signature: ' + str(exc)) from exc
|
||||
|
||||
|
||||
def repack(src, dst, replace=None, add=None, sign=True):
|
||||
"""Copy raw compressed members; reconstruct ZIP headers without descriptors.
|
||||
|
||||
Reject ZIP64/encrypted archives. Output is atomically replaced after signing.
|
||||
"""
|
||||
replace, add = dict(replace or {}), dict(add or {})
|
||||
central, output = [], io.BytesIO()
|
||||
with open(src, 'rb') as raw, zipfile.ZipFile(raw) as archive:
|
||||
names = archive.namelist()
|
||||
if len(set(names)) != len(names):
|
||||
raise ValueError('duplicate ZIP member names')
|
||||
if set(replace) - set(names) or set(add) & set(names) or set(add) & set(replace):
|
||||
raise ValueError('replace must exist and add must be new')
|
||||
items = archive.infolist() + [zipfile.ZipInfo(name) for name in add]
|
||||
for info in items:
|
||||
name = info.filename
|
||||
if re.match(r'^META-INF/(?:[^/]+\.(?:SF|RSA|EC|DSA)|MANIFEST\.MF)$', name, re.I):
|
||||
continue
|
||||
if info.flag_bits & 1 or info.compress_type not in (0, 8):
|
||||
raise ValueError('unsupported ZIP encryption/compression')
|
||||
method = info.compress_type
|
||||
content = add.get(name) if name in add else replace.get(name)
|
||||
if content is None:
|
||||
raw.seek(info.header_offset)
|
||||
header = raw.read(30)
|
||||
if header[:4] != b'PK\3\4':
|
||||
raise ValueError('invalid local ZIP header')
|
||||
nl, el = struct.unpack_from('<HH', header, 26)
|
||||
raw.seek(nl + el, 1)
|
||||
compressed = raw.read(info.compress_size)
|
||||
crc, usize = info.CRC, info.file_size
|
||||
if len(compressed) != info.compress_size:
|
||||
raise ValueError('truncated ZIP member')
|
||||
else:
|
||||
crc, usize = zlib.crc32(content), len(content)
|
||||
if method == 8:
|
||||
compressor = zlib.compressobj(6, zlib.DEFLATED, -15)
|
||||
compressed = compressor.compress(content) + compressor.flush()
|
||||
else:
|
||||
compressed = content
|
||||
encoded = name.encode('utf-8')
|
||||
offset = output.tell()
|
||||
align = 16384 if name.endswith('.so') else 4
|
||||
needs_alignment = method == 0 or name.endswith('.so')
|
||||
padding = (-(offset + 30 + len(encoded) + 6) % align) if needs_alignment else 0
|
||||
# Android zipalign extra: alignment (uint16), then padding bytes.
|
||||
extra = struct.pack('<HHH', 0xd935, padding + 2, align) + bytes(padding) if needs_alignment else b''
|
||||
dt = info.date_time
|
||||
dos_time = (dt[3] << 11) | (dt[4] << 5) | (dt[5] // 2)
|
||||
dos_date = ((dt[0] - 1980) << 9) | (dt[1] << 5) | dt[2]
|
||||
csize = len(compressed)
|
||||
if max(offset, csize, usize) >= 0xffffffff:
|
||||
raise ValueError('ZIP64 APKs are unsupported')
|
||||
output.write(struct.pack('<IHHHHHIIIHH', 0x04034b50, 20, 0x800, method, dos_time, dos_date,
|
||||
crc, csize, usize, len(encoded), len(extra)) + encoded + extra + compressed)
|
||||
central.append(struct.pack('<IHHHHHHIIIHHHHHII', 0x02014b50, 0x314, 20, 0x800, method,
|
||||
dos_time, dos_date, crc, csize, usize, len(encoded), 0, len(info.comment),
|
||||
0, info.internal_attr, info.external_attr, offset) + encoded + info.comment)
|
||||
cd = output.tell()
|
||||
directory = b''.join(central)
|
||||
if len(central) >= 65535 or cd + len(directory) >= 0xffffffff:
|
||||
raise ValueError('ZIP64 APKs are unsupported')
|
||||
output.write(directory)
|
||||
output.write(struct.pack('<IHHHHIIH', 0x06054b50, 0, 0, len(central), len(central), len(directory), cd, len(archive.comment)) + archive.comment)
|
||||
data = output.getvalue()
|
||||
if sign:
|
||||
data = sign_apk(data, signing_key())
|
||||
dst = Path(dst)
|
||||
fd, tmp = tempfile.mkstemp(prefix='.apk-', dir=str(dst.parent))
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as f:
|
||||
f.write(data)
|
||||
if sign:
|
||||
verify(tmp)
|
||||
os.replace(tmp, dst)
|
||||
finally:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Binary-manifest VR inspection and minimal launcher repair (stdlib only)."""
|
||||
import struct
|
||||
import frame_apk
|
||||
|
||||
MAIN = 'android.intent.action.MAIN'
|
||||
LAUNCHER = 'android.intent.category.LAUNCHER'
|
||||
VR = {'com.oculus.intent.category.VR', 'org.khronos.openxr.intent.category.IMMERSIVE_HMD'}
|
||||
|
||||
|
||||
def inspect(data):
|
||||
elements = iter(frame_apk.manifest_elements(data))
|
||||
stack, filters, samsung = [], [], False
|
||||
current = None
|
||||
for kind, hs, off, size in frame_apk._chunks(data, 8, len(data)):
|
||||
if kind == 0x0102:
|
||||
tag, attrs = next(elements)
|
||||
value = attrs.get('name', (None, None, None))[2]
|
||||
if tag == 'intent-filter' and stack and stack[-1] in ('activity', 'activity-alias'):
|
||||
current = {'actions': set(), 'categories': set(), 'templates': []}
|
||||
if current is not None and stack and stack[-1] == 'intent-filter':
|
||||
if tag == 'action':
|
||||
current['actions'].add(value)
|
||||
if tag == 'category':
|
||||
current['categories'].add(value)
|
||||
current['templates'].append((off, size, hs))
|
||||
if tag == 'meta-data' and stack and stack[-1] == 'application':
|
||||
samsung |= value == 'com.samsung.android.vr.application.mode' and attrs.get('value', (0, 0, None))[2] == 'vr_only'
|
||||
stack.append(tag)
|
||||
elif kind == 0x0103 and stack:
|
||||
tag = stack.pop()
|
||||
if tag == 'intent-filter' and current is not None:
|
||||
current['end'] = off
|
||||
filters.append(current)
|
||||
current = None
|
||||
mains = [f for f in filters if MAIN in f['actions']]
|
||||
vr_filters = [f for f in mains if VR & f['categories']]
|
||||
return {'launchable': any(LAUNCHER in f['categories'] for f in mains),
|
||||
'vr_activity': bool(vr_filters), 'vr': bool(vr_filters) or samsung}, vr_filters
|
||||
|
||||
|
||||
def _append_string(chunk, text):
|
||||
_, hs, size, count, styles, flags, start, style_start = struct.unpack_from('<HHIIIIII', chunk)
|
||||
strings_end = style_start or size
|
||||
encoded = text.encode('utf-8' if flags & 0x100 else 'utf-16-le')
|
||||
# LAUNCHER is short enough for both single-unit length encodings.
|
||||
new = (bytes([len(text), len(encoded)]) + encoded + b'\0' if flags & 0x100
|
||||
else struct.pack('<H', len(text)) + encoded + b'\0\0')
|
||||
string_data = chunk[start:strings_end] + new
|
||||
string_data += bytes(-len(string_data) % 4)
|
||||
header = bytearray(chunk[:hs])
|
||||
new_start = start + 4
|
||||
new_styles = new_start + len(string_data) if style_start else 0
|
||||
body = (chunk[hs:hs + count * 4] + struct.pack('<I', strings_end - start)
|
||||
+ chunk[hs + count * 4:start] + string_data + (chunk[style_start:] if style_start else b''))
|
||||
struct.pack_into('<IIIII', header, 8, count + 1, styles, flags & ~1, new_start, new_styles)
|
||||
struct.pack_into('<I', header, 4, len(header) + len(body))
|
||||
return bytes(header) + body, count
|
||||
|
||||
|
||||
def add_launcher_category(axml_bytes):
|
||||
info, filters = inspect(axml_bytes)
|
||||
if info['launchable']:
|
||||
return axml_bytes
|
||||
if not filters:
|
||||
raise frame_apk.ApkError('no VR activity with a MAIN intent filter to patch')
|
||||
target = filters[0]
|
||||
chunks = list(frame_apk._chunks(axml_bytes, 8, len(axml_bytes)))
|
||||
pool = next(c for c in chunks if c[0] == 1)
|
||||
_, _, po, ps = pool
|
||||
new_pool, index = _append_string(axml_bytes[po:po + ps], LAUNCHER)
|
||||
off, size, hs = target['templates'][0]
|
||||
start = bytearray(axml_bytes[off:off + size])
|
||||
attr_start, attr_size, count = struct.unpack_from('<HHH', start, hs + 8)
|
||||
strings = frame_apk._string_pool(axml_bytes, po)
|
||||
resmap = []
|
||||
for kind, header_size, offset, chunk_size in chunks:
|
||||
if kind == 0x180:
|
||||
resmap = struct.unpack_from('<%dI' % ((chunk_size - header_size) // 4),
|
||||
axml_bytes, offset + header_size)
|
||||
for i in range(count):
|
||||
a = hs + attr_start + i * attr_size
|
||||
name = struct.unpack_from('<I', start, a + 4)[0]
|
||||
if (name < len(resmap) and resmap[name] == 0x01010003) or strings[name] == 'name':
|
||||
struct.pack_into('<I', start, a + 8, index)
|
||||
struct.pack_into('<HBBI', start, a + 12, 8, 0, 3, index)
|
||||
break
|
||||
else:
|
||||
raise frame_apk.ApkError('VR category has no name attribute')
|
||||
end = struct.pack('<HHI', 0x0103, hs, hs + 8) + start[8:hs] + start[hs:hs + 8]
|
||||
result = bytearray(axml_bytes[:8])
|
||||
for _, _, off, size in chunks:
|
||||
if off == target['end']:
|
||||
result += start + end
|
||||
result += new_pool if off == po else axml_bytes[off:off + size]
|
||||
struct.pack_into('<I', result, 4, len(result))
|
||||
result = bytes(result)
|
||||
if not inspect(result)[0]['launchable']:
|
||||
raise frame_apk.ApkError('launcher repair failed verification')
|
||||
return result
|
||||
|
||||
|
||||
def detection(data, names):
|
||||
info, _ = inspect(data)
|
||||
issues = []
|
||||
if 'lib/arm64-v8a/libvrapi.so' in names:
|
||||
issues.append("Uses Meta's legacy VrApi, which the Frame doesn't have; it won't run.")
|
||||
if any(n.endswith('/libovrplatformloader.so') for n in names):
|
||||
issues.append("Uses Meta's platform SDK; if it checks your Quest store licence it will quit.")
|
||||
if 'lib/arm64-v8a/libopenxr_loader.so' in names:
|
||||
info['vr'] = True
|
||||
issues.append('Uses OpenXR (good).')
|
||||
info['vr_issues'] = issues
|
||||
return info
|
||||
@@ -473,6 +473,12 @@
|
||||
a game's <code>.zip</code>, folder or <code>.exe</code> becomes a title in the Steam library.
|
||||
<input type="file" id="fileInput" multiple hidden>
|
||||
</div>
|
||||
<label class="sub" for="apkDisplay">Android display</label>
|
||||
<select id="apkDisplay" aria-label="Android app display mode">
|
||||
<option value="auto">Automatic (detect VR)</option>
|
||||
<option value="flat">Flat screen</option>
|
||||
<option value="vr">VR app</option>
|
||||
</select>
|
||||
<div class="progress" id="prog"><i></i></div>
|
||||
<div class="shelf-head" style="margin-top:16px"><h2>Sideloaded titles</h2><span class="count" id="titleCount"></span></div>
|
||||
<div class="list" id="titleList"><div class="sub">Loading…</div></div>
|
||||
@@ -1138,6 +1144,7 @@ function upload(file, mode) {
|
||||
xhr.setRequestHeader("X-Frame-UI", "1");
|
||||
xhr.setRequestHeader("X-Filename", encodeURIComponent(file.name));
|
||||
xhr.setRequestHeader("X-Mode", mode);
|
||||
if (mode === "apk") xhr.setRequestHeader("X-APK-Display", $("apkDisplay").value);
|
||||
const bar = $("prog").firstElementChild;
|
||||
$("prog").style.display = "block"; bar.style.width = "0";
|
||||
xhr.upload.onprogress = e => { if (e.lengthComputable) bar.style.width = (100 * e.loaded / e.total) + "%"; };
|
||||
|
||||
+8
-2
@@ -1337,10 +1337,16 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if mode == "apk":
|
||||
ensure_master()
|
||||
try:
|
||||
m = frame_android.install(str(dest), source=name)
|
||||
display = self.headers.get("X-APK-Display", "auto")
|
||||
if display not in ("auto", "flat", "vr"):
|
||||
raise frame_android.FrameError("invalid APK display mode")
|
||||
m = frame_android.install(str(dest), source=name,
|
||||
flatscreen=None if display == "auto" else display == "flat")
|
||||
except frame_android.FrameError as e:
|
||||
raise Failure(str(e), 400)
|
||||
return {"message": f"Installed {m['label']} as its own app in the Steam library", "app": m}
|
||||
kind = "VR app" if not m['flatscreen'] else "app"
|
||||
notes = " ".join(m.get("vr_issues", []))
|
||||
return {"message": f"Installed {m['label']} as its own {kind} in the Steam library. {notes}".strip(), "app": m}
|
||||
return {"message": push_file(dest)}
|
||||
finally:
|
||||
if not keep:
|
||||
|
||||
Reference in new issue
Block a user