Publish Platina Linux source base for Xiaomi Mi 8 Lite

This commit is contained in:
Sukecz
2026-10-23 11:10:29 +02:00
commit b7eb4289b7
95 changed files with 275710 additions and 0 deletions
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
set -eu
test -f /usr/share/deviceinfo/deviceinfo
grep -q xiaomi-platina /usr/share/deviceinfo/deviceinfo
test -s /home/server/.ssh/authorized_keys
ssh-keygen -lf /home/server/.ssh/authorized_keys
awk -F: '$1 == "server" { if (substr($2,1,1) != "!") exit 1; print "server password locked"; found=1 } END { if (!found) exit 1 }' /etc/shadow
test ! -e /tmp/platina-audit-host-key
ssh-keygen -q -t ed25519 -N '' -f /tmp/platina-audit-host-key
trap 'rm -f /tmp/platina-audit-host-key /tmp/platina-audit-host-key.pub' EXIT
sshd_settings=$(/usr/sbin/sshd.pam -T -h /tmp/platina-audit-host-key)
for expected in 'passwordauthentication no' 'kbdinteractiveauthentication no' 'permitrootlogin no' 'pubkeyauthentication yes' 'usepam yes'; do
printf '%s\n' "$sshd_settings" | grep -Fx "$expected"
done
grep -q '^SSHD_BINARY="/usr/sbin/sshd.pam"' /etc/conf.d/sshd
visudo -c
test -f /usr/lib/security/pam_rundir.so
test -x /usr/sbin/avahi-daemon
test -x /usr/sbin/NetworkManager
test -x /usr/sbin/usb_moded
test -x /usr/sbin/chronyd
test -d /home/server/.config/rc/runlevels/default
test -s /etc/NetworkManager/system-connections/platina-usb.nmconnection
test "$(stat -c '%a:%u:%g' /etc/NetworkManager/system-connections/platina-usb.nmconnection)" = '600:0:0'
test -z "$(find /etc/NetworkManager/system-connections -type f -name '*.nmconnection' ! -name platina-usb.nmconnection -print)"
test -z "$(find /home -type f -name 'id_*' -print)"
grep -q '^wifi.scan-rand-mac-address=no$' /etc/NetworkManager/conf.d/30-platina-wifi.conf
grep -q '^nameserver 1.1.1.1$' /etc/resolv.conf
grep -q '^https://mirror.nura.eco/postmarketos/v26.06$' /etc/apk/repositories
for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos-qcom-sdm660; do
grep -q "^$package=" /etc/apk/world
done
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon; do
test -L "/etc/runlevels/default/$service"
done
for key in /etc/ssh/ssh_host_*_key; do
if [ -f "$key" ]; then
echo 'Build-time SSH host key found; needs removal before final export.'
exit 1
fi
done
echo 'Offline image audit passed; runtime networking and boot still need testing.'
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# Runs only inside the newly created phone image, never on MiniPC's host OS.
set -eu
test -f /usr/share/deviceinfo/deviceinfo
grep -q xiaomi-platina /usr/share/deviceinfo/deviceinfo
test "$(id -u)" = 0
test -s /home/server/.ssh/authorized_keys
command -v sudo >/dev/null
test -x /usr/sbin/sshd.pam
if ! grep -q '^SSHD_BINARY=' /etc/conf.d/sshd; then
printf '\nSSHD_BINARY="/usr/sbin/sshd.pam"\n' >> /etc/conf.d/sshd
fi
install -d -m755 /etc/ssh/sshd_config.d /etc/sudoers.d
cat > /etc/ssh/sshd_config.d/00-platina-server.conf <<'EOF'
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
UsePAM yes
EOF
if ! grep -q '^Include /etc/ssh/sshd_config.d/' /etc/ssh/sshd_config; then
sed -i '1i Include /etc/ssh/sshd_config.d/*.conf' /etc/ssh/sshd_config
fi
printf 'server ALL=(ALL) NOPASSWD: ALL\n' > /etc/sudoers.d/90-platina-server
chmod 440 /etc/sudoers.d/90-platina-server
chmod 440 /etc/sudoers
visudo -c
if ! awk -F: '$1 == "server" && substr($2,1,1) == "!" { found=1 } END { exit !found }' /etc/shadow; then
passwd -l server
fi
chmod 700 /home/server/.ssh
chmod 600 /home/server/.ssh/authorized_keys
chown -R server:server /home/server/.ssh
install -d -m700 -o server -g server /home/server/.config/rc/runlevels/default
test -f /usr/lib/security/pam_rundir.so
cat > /etc/resolv.conf <<'EOF'
nameserver 1.1.1.1
nameserver 1.0.0.1
EOF
cat > /etc/apk/repositories <<'EOF'
https://mirror.nura.eco/postmarketos/v26.06
https://cdn.alpinelinux.org/alpine/v3.24/main
https://cdn.alpinelinux.org/alpine/v3.24/community
EOF
chmod 644 /etc/resolv.conf /etc/apk/repositories
cat > /etc/local.d/platina-headless.start <<'EOF'
#!/bin/sh
for path in /sys/class/backlight/*/brightness; do
[ -w "$path" ] && printf '0\n' > "$path"
done
exit 0
EOF
chmod 755 /etc/local.d/platina-headless.start
# Hold the exact locally built boot-related packages during normal upgrades.
set --
for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos-qcom-sdm660; do
version=$(awk -v package="$package" '$0 == "P:" package { found=1; next } found && /^V:/ { print substr($0,3); exit }' /lib/apk/db/installed)
test -n "$version"
set -- "$@" "$package=$version"
done
apk add --no-network "$@"
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon; do
rc-update add "$service" default
done
printf 'Image configured for SSH keys and passwordless sudo for the dedicated administrator.\n'
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Check exported boot/rootfs consistency and early module dependencies, read-only."""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import re
import struct
import subprocess
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/candidate-7.2'
def cpio_files(data):
files = {}
offset = 0
while offset + 110 <= len(data):
header = data[offset:offset + 110]
assert header[:6] in (b'070701', b'070702'), 'Unsupported CPIO format'
size = int(header[54:62], 16)
namesize = int(header[94:102], 16)
name = data[offset + 110:offset + 110 + namesize - 1].decode()
offset = (offset + 110 + namesize + 3) & ~3
if name == 'TRAILER!!!':
break
files[name.removeprefix('./').lstrip('/')] = data[offset:offset + size]
offset = (offset + size + 3) & ~3
return files
def main():
global OUT
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--directory', type=Path, default=OUT)
args = parser.parse_args()
OUT = args.directory.resolve()
boot = (OUT / 'boot.img').read_bytes()
assert boot[:8] == b'ANDROID!'
kernel_size, _, ramdisk_size = struct.unpack_from('<III', boot, 8)
pagesize = struct.unpack_from('<I', boot, 36)[0]
header_version = struct.unpack_from('<I', boot, 40)[0]
assert header_version <= 2 and pagesize == 4096
assert len(boot) <= 0x3FFC000, 'Exceeds verified boot partition size'
cmdline = (boot[64:576].split(b'\0')[0] + b' ' + boot[608:1632].split(b'\0')[0]).decode().strip()
uuid = re.search(r'pmos_root_uuid=([0-9a-f-]+)', cmdline).group(1)
metadata = subprocess.check_output(['blkid', '-p', '-o', 'export',
str(OUT / 'xiaomi-platina.img')], text=True)
assert f'UUID={uuid}\n' in metadata and 'TYPE=ext4\n' in metadata
def root_file(path):
return subprocess.check_output(['debugfs', '-R', 'cat ' + path,
str(OUT / 'xiaomi-platina.img')],
stderr=subprocess.DEVNULL, text=True)
assert root_file('/etc/resolv.conf').splitlines() == ['nameserver 1.1.1.1', 'nameserver 1.0.0.1']
assert root_file('/etc/apk/repositories').splitlines() == [
'https://mirror.nura.eco/postmarketos/v26.06',
'https://cdn.alpinelinux.org/alpine/v3.24/main',
'https://cdn.alpinelinux.org/alpine/v3.24/community']
start = pagesize + ((kernel_size + pagesize - 1) // pagesize) * pagesize
ramdisk = boot[start:start + ramdisk_size]
assert ramdisk == (OUT / 'initramfs').read_bytes(), 'Boot/export initramfs mismatch'
files = cpio_files(gzip.decompress(ramdisk))
release = json.loads((OUT / 'manifest.json').read_text())['kernel']
assert re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+-sdm660', release), 'Invalid declared kernel release'
prefix = f'usr/lib/modules/{release}/'
# Some distributions use /lib instead of /usr/lib inside initramfs.
if not any(name.startswith(prefix) for name in files):
prefix = f'lib/modules/{release}/'
depfile = prefix + 'modules.dep'
assert depfile in files, 'Missing module dependency metadata'
dependencies = dict(line.split(':', 1) for line in files[depfile].decode().splitlines())
included = {name[len(prefix):] for name in files if name.startswith(prefix) and '.ko' in name}
missing = sorted({dependency for module in included
for dependency in dependencies.get(module, '').split()
if prefix + dependency not in files})
assert not missing, f'Initramfs modules have missing dependencies: {missing}'
required = ('qcom_pil_info', 'ath10k_core', 'snd_soc_core',
'qcom_vadc_common', 'snd_soc_qcom_common', 'btqca')
normal = {Path(name).name.split('.ko')[0].replace('-', '_') for name in included}
assert set(required) <= normal, 'Missing early-boot module'
for firmware in ('regulatory.db', 'regulatory.db.p7s'):
assert any(name.endswith('/firmware/' + firmware) for name in files), firmware
assert not any(name.endswith(('.nmconnection', 'id_ed25519', 'id_rsa')) for name in files)
report = {'passed': True, 'hardware_tested': False, 'flashed': False,
'boot_bytes': len(boot), 'boot_limit_bytes': 0x3FFC000,
'kernel': release, 'rootfs_uuid': uuid, 'cmdline': cmdline,
'initramfs_modules': len(included), 'missing_module_dependencies': missing,
'initramfs_sha256': hashlib.sha256(ramdisk).hexdigest()}
(ROOT / 'reports' / (OUT.name + '-artifact-audit.json')).write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
if __name__ == '__main__':
main()
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Build and audit isolated candidate images locally; never writes to a phone."""
import argparse
import configparser
import datetime
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
ROOT = Path(__file__).resolve().parents[1]
WORK = ROOT / 'work/pmbootstrap-candidate-7.2'
OUTPUT = ROOT / 'artifacts/candidate-7.2'
KERNEL_RELEASE = '7.2.12-sdm660'
STATUS = ROOT / 'logs/candidate-image-status.json'
PMB = ['nice', '-n', '10', 'python3', str(ROOT / 'tools/pmbootstrap/pmbootstrap.py'),
'-c', str(ROOT / 'config/pmbootstrap-candidate-7.2.cfg'), '-j', '2']
def provenance(config_path, config):
def revision(directory):
result = subprocess.run(['git', '-C', str(directory), 'rev-parse', 'HEAD'],
capture_output=True, text=True)
return result.stdout.strip() if result.returncode == 0 else None
recipes = Path(config['pmbootstrap']['aports']) / 'device/testing'
inputs = {}
for package in ('device-xiaomi-platina', 'firmware-xiaomi-platina',
'linux-postmarketos-qcom-sdm660'):
for path in sorted((recipes / package).iterdir()):
if path.is_file():
with path.open('rb') as stream:
inputs[str(path.relative_to(recipes))] = hashlib.file_digest(stream, 'sha256').hexdigest()
dirty = subprocess.run(['git', '-C', str(ROOT), 'status', '--porcelain'],
capture_output=True, text=True)
return {'project_commit': revision(ROOT),
'project_dirty': bool(dirty.stdout.strip()) if dirty.returncode == 0 else None,
'pmaports_commit': revision(recipes.parents[1]),
'pmbootstrap_commit': revision(ROOT / 'tools/pmbootstrap'),
'config_sha256': hashlib.sha256(config_path.read_bytes()).hexdigest(),
'recipe_inputs_sha256': inputs}
def record(phase, **details):
row = {'time': datetime.datetime.now().astimezone().isoformat(),
'phase': phase, 'flashed': False, **details}
STATUS.write_text(json.dumps(row, indent=2) + '\n')
print(phase, flush=True)
def run(*args, script=None):
if script:
with (ROOT / 'scripts' / script).open() as stream:
subprocess.run(PMB + list(args), cwd=ROOT, stdin=stream, check=True)
else:
subprocess.run(PMB + list(args), cwd=ROOT, check=True)
def main():
global OUTPUT, WORK, PMB, KERNEL_RELEASE
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--config', type=Path, default=ROOT / 'config/pmbootstrap-candidate-7.2.cfg',
help='Absolute project pmbootstrap config; work is derived from it')
parser.add_argument('--resume-image', action='store_true',
help='Resume hardening/audit of the already created candidate image')
parser.add_argument('--output-name', default='candidate-7.2',
help='New candidate-* directory under artifacts; existing output is preserved')
args = parser.parse_args()
config_path = args.config.resolve()
config = configparser.ConfigParser()
if not config.read(config_path):
raise ValueError('Missing pmbootstrap config')
WORK = Path(config['pmbootstrap']['work'])
if not WORK.is_absolute() or not WORK.resolve().is_relative_to(ROOT / 'work'):
raise ValueError('Build work must be an absolute path inside project work/')
PMB = ['nice', '-n', '10', 'python3', str(ROOT / 'tools/pmbootstrap/pmbootstrap.py'),
'-c', str(config_path), '-j', '2']
(ROOT / 'logs').mkdir(exist_ok=True)
(ROOT / 'artifacts').mkdir(exist_ok=True)
if not re.fullmatch(r'candidate-[A-Za-z0-9][A-Za-z0-9._-]*', args.output_name):
raise ValueError('Output name must be a simple candidate-* directory name')
OUTPUT = ROOT / 'artifacts' / args.output_name
if OUTPUT.exists():
raise RuntimeError('Preserve existing candidate artifacts; use a new output directory')
build_sources = provenance(config_path, config)
recipe = Path(config['pmbootstrap']['aports']) / 'device/testing/linux-postmarketos-qcom-sdm660/APKBUILD'
recipe_text = recipe.read_text()
version = re.search(r'^pkgver=([0-9][0-9.]*)$', recipe_text, re.M)
release = re.search(r'^pkgrel=([0-9]+)$', recipe_text, re.M)
if not version or not release:
raise ValueError('Cannot determine kernel version from APKBUILD')
KERNEL_RELEASE = version[1] + '-sdm660'
apk_version = version[1] + '-r' + release[1]
packages = list((WORK / 'packages').glob('**/linux-postmarketos-qcom-sdm660-' + apk_version + '.apk'))
if not packages:
raise RuntimeError('Kernel APK must finish successfully before building images')
if args.resume_image:
assert (WORK / 'chroot_native/home/pmos/rootfs/xiaomi-platina.img').is_file()
else:
record('building-device-and-firmware')
run('build', '--lax', '--arch', 'aarch64',
'firmware-xiaomi-platina', 'device-xiaomi-platina')
record('creating-rootfs')
# Disposable, public build placeholder; the account is locked before export.
run('install', '--single-partition', '--no-sparse', '--no-recommends',
'--password', 'locked-before-export',
'--add', 'python3,iw,iperf3,mmc-utils,avahi-tools')
record('hardening-and-auditing-image')
# Each pmbootstrap chroot entry restores build DNS/repositories. Configure
# and audit in one entry, then export without entering the image again.
scripts = '\n'.join((ROOT / 'scripts' / name).read_text()
for name in ('Harden-Server-Image.sh', 'Audit-Server-Image.sh'))
subprocess.run(PMB + ['chroot', '--image', '--', 'sh', '-s'],
cwd=ROOT, input=scripts, text=True, check=True)
record('exporting')
links = ROOT / 'artifacts' / (OUTPUT.name + '-links')
run('export', '--no-install', str(links))
# Stop all mounts before copying/hashing the mutable filesystem image.
run('shutdown')
OUTPUT.mkdir()
files = []
for source in sorted(links.rglob('*')):
if not source.is_file():
continue
target = OUTPUT / source.relative_to(links)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
with target.open('rb') as stream:
digest = hashlib.file_digest(stream, 'sha256').hexdigest()
files.append({'file': str(target.relative_to(OUTPUT)),
'bytes': target.stat().st_size, 'sha256': digest})
assert {'boot.img', 'xiaomi-platina.img', 'initramfs', 'vmlinuz'} <= {f['file'] for f in files}
if provenance(config_path, config) != build_sources:
raise RuntimeError('Build sources changed during the build; review before publishing artifacts')
manifest = {'kernel': KERNEL_RELEASE, 'hardware_tested': False,
'build_sources': build_sources,
'flashed': False, 'files': files}
(OUTPUT / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
record('exported-offline-audit-passed-hardware-test-pending', files=len(files))
if __name__ == '__main__':
try:
main()
except Exception as exc:
record('failed-needs-review', error=type(exc).__name__,
returncode=getattr(exc, 'returncode', None))
raise SystemExit(1)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Fail public CI when private files or host-specific data enter the Git index."""
import re
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def check(root=ROOT):
paths = subprocess.check_output(['git', 'ls-files', '-z'], cwd=root).decode().split('\0')
blocked = {'config', 'backups', 'artifacts', 'work', 'sources', 'tools', 'logs', 'reports', 'archive'}
patterns = [rb'-----BEGIN (?:OPENSSH |RSA |EC |DSA )?PRIVATE KEY-----',
rb'(?im)^\s*(?:psk|password|TELEGRAM_BOT_TOKEN|api_key)\s*=\s*["\']?[^\s"\'\n]{6,}',
rb'(?:ghp_|github_pat_|sk-proj-)[A-Za-z0-9_]{20,}',
rb'192\.168\.\d{1,3}\.\d{1,3}', rb'/home/(?!server/|pmos/)[A-Za-z0-9_.-]+/',
rb'C:\\Users\\']
for name in filter(None, paths):
path = Path(name)
lower = name.lower()
if (path.parts[0] in blocked or path.name.lower().startswith('agents.') or
path.suffix.lower() in ('.txt', '.env', '.key', '.pem', '.img', '.apk', '.bin', '.elf', '.zip') or
any(word in lower for word in ('private', 'secret', 'handoff'))):
raise ValueError('Private or generated path in public index: ' + name)
file = root / path
if file.is_symlink():
if not file.resolve().is_relative_to(root.resolve()):
raise ValueError('External symlink: ' + name)
data = file.read_bytes()
if path.suffix.lower() == '.png':
continue
if any(re.search(pattern, data) for pattern in patterns):
raise ValueError('Possible private data in public file (value suppressed): ' + name)
print('OK: public index excludes private files, credentials and maintainer host data')
if __name__ == '__main__':
check()
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# Read-only runtime inspection after Linux is installed. No package/service changes.
set -u
date -Is
uname -a
cat /etc/os-release
uptime
free -m
df -h
ip address show
ip route
ss -lnt 2>/dev/null || true
rc-status 2>/dev/null || true
printf '\nCPU frequency policies (kHz)\n'
for d in /sys/devices/system/cpu/cpufreq/policy*; do
[ -d "$d" ] || continue
for n in scaling_driver scaling_governor scaling_cur_freq scaling_min_freq scaling_max_freq; do
[ -r "$d/$n" ] && printf '%s: %s\n' "$d/$n" "$(cat "$d/$n")"
done
done
printf '\nThermal zones (normally millidegrees C)\n'
for d in /sys/class/thermal/thermal_zone*; do
[ -r "$d/temp" ] || continue
printf '%s %s: %s\n' "$d" "$(cat "$d/type")" "$(cat "$d/temp")"
done
printf '\nPower supplies: values are driver reports, not wall-power measurements\n'
for d in /sys/class/power_supply/*; do
[ -d "$d" ] || continue
for n in type status online capacity temp voltage_now current_now; do
[ -r "$d/$n" ] && printf '%s: %s\n' "$d/$n" "$(cat "$d/$n")"
done
done
printf '\nBacklight\n'
for d in /sys/class/backlight/*; do
[ -d "$d" ] || continue
for n in brightness actual_brightness max_brightness bl_power; do
[ -r "$d/$n" ] && printf '%s: %s\n' "$d/$n" "$(cat "$d/$n")"
done
done
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Temporary LCD power/wake session for the verified Platina 7.2.12 port.
No DRM detach, DT mutation or boot write. A matching, checksum-pinned module
must have been explicitly installed. A later proper panel port replaces this.
"""
import fcntl
import hashlib
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
BASE = Path('/usr/local/lib/platina/display')
PARAMS = Path('/sys/module/platina_panel_dcs/parameters')
def validate(base=BASE):
identity = json.loads((base / 'module.json').read_text())
if identity['kernel'] != os.uname().release:
raise ValueError('LCD helper requires its exact build kernel; rebuild after upgrade')
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('Not a Platina phone')
if 'mdss_dsi_tianma_fhd_nt36672a_video' not in Path('/proc/cmdline').read_text():
raise ValueError('Not the verified Tianma panel')
driver = Path('/sys/bus/mipi-dsi/devices/c994000.dsi.0/driver').resolve(strict=True).name
if driver != 'panel-simple-dsi':
raise ValueError('LCD workaround requires the original panel-simple driver')
module = base / 'platina_panel_dcs.ko'
if hashlib.sha256(module.read_bytes()).hexdigest() != identity['sha256']:
raise ValueError('LCD module checksum mismatch')
return module
def check_panel(params=PARAMS):
values = {name: int((params / name).read_text()) for name in
('io_enabled', 'read_result', 'wake_result', 'power_after')}
if (values['io_enabled'] != 1 or values['read_result'] != 1 or
values['wake_result'] != 0 or values['power_after'] & 0x14 != 0x14):
raise ValueError('LCD did not acknowledge sleep-out/display-on: ' + str(values))
return values
def session(arguments):
# Own the whole power/render/cleanup sequence, including manual invocations.
with Path('/run/platina-display-session.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
module = validate()
owned = False
try:
if not PARAMS.exists():
# Mark ownership before insmod so a signal also cleans up a
# module whose init completed just before the signal arrived.
owned = True
subprocess.run(['insmod', str(module), 'enable_iovcc=1', 'wake=1'], check=True)
print(json.dumps({'panel_ready': check_panel()}), flush=True)
renderer = subprocess.Popen(['/usr/local/sbin/platina-splash', *arguments])
try:
return renderer.wait()
finally:
if renderer.poll() is None:
renderer.terminate()
try:
renderer.wait(timeout=3)
except subprocess.TimeoutExpired:
renderer.kill()
renderer.wait()
finally:
if owned and PARAMS.exists():
# Brightness is cleared even if the renderer failed or timed out.
Path('/sys/class/backlight/backlight/brightness').write_text('0\n')
subprocess.run(['rmmod', 'platina_panel_dcs'], check=True)
if __name__ == '__main__':
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
try:
raise SystemExit(session(sys.argv[1:]))
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
print('platina-display-session:', error, file=sys.stderr)
raise SystemExit(1)
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Control the integrated Platina panel through fbdev/backlight; no module tricks."""
import argparse
from contextlib import contextmanager
import fcntl
import json
import mmap
import os
from pathlib import Path
import runpy
import signal
import struct
import sys
import time
BACKLIGHT = Path('/sys/class/backlight/backlight')
DRIVER = Path('/sys/bus/mipi-dsi/devices/c994000.dsi.0/driver')
PANEL = b'xiaomi,platina-tianma-nt36672a'
FBIOBLANK = 0x4611
def validate():
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('This command requires Platina')
if DRIVER.resolve(strict=True).name != 'panel-novatek-nt36672a':
raise ValueError('Integrated Tianma driver required; keep using the 0.1.1 session on the old boot')
# Follow the bound device's OF node instead of depending on the DT directory layout.
compatible = (DRIVER.parent / 'of_node/compatible').read_bytes().split(b'\0')
if PANEL not in compatible:
raise ValueError('Unexpected panel variant')
if Path('/sys/module/platina_panel_dcs').exists():
raise ValueError('Temporary LCD module is loaded; do not mix display owners')
def status():
result = {'kernel': os.uname().release,
'driver': DRIVER.resolve().name if DRIVER.exists() else None,
'temporary_module_loaded': Path('/sys/module/platina_panel_dcs').exists()}
for name in ('brightness', 'actual_brightness', 'max_brightness', 'bl_power'):
path = BACKLIGHT / name
result[name] = int(path.read_text()) if path.exists() else None
blank = Path('/sys/class/graphics/fb0/blank')
result['fb_blank'] = int(blank.read_text()) if blank.exists() else None
# Brightness zero alone does not establish that the panel rails are off.
return result
def brightness(percent):
if not 0 <= percent <= 100:
raise ValueError('Brightness must be 0–100 percent')
maximum = int((BACKLIGHT / 'max_brightness').read_text())
level = max(1, maximum * percent // 100) if percent else 0
(BACKLIGHT / 'brightness').write_text(str(level) + '\n')
def off(fb):
brightness(0)
fcntl.ioctl(fb, FBIOBLANK, 4) # FB_BLANK_POWERDOWN: DRM calls panel unprepare.
def on(fb, percent):
fcntl.ioctl(fb, FBIOBLANK, 0)
(BACKLIGHT / 'bl_power').write_text('0\n')
brightness(percent)
@contextmanager
def device():
if os.geteuid() != 0:
raise ValueError('Run display changes on the phone as root')
validate()
# Shares the existing splash lock: two renderers must not own fb0 together.
with Path('/run/platina-splash.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
fb = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
try:
yield fb
finally:
os.close(fb)
def show(fb, directory, seconds, percent, boot=False):
helper = runpy.run_path('/usr/local/sbin/platina-splash', run_name='display_helpers')
manifest, raw = helper['load_frame'](directory)
boot_id = Path('/proc/sys/kernel/random/boot_id').read_text().strip()
done = Path('/run/platina-splash.done')
if boot and done.exists() and done.read_text().strip() == boot_id:
return
tty, previous = None, None
try:
variable, fixed = bytearray(160), bytearray(80)
fcntl.ioctl(fb, 0x4600, variable, True)
fcntl.ioctl(fb, 0x4602, fixed, True)
layout = helper['geometry'](variable, fixed)
tty = os.open('/dev/tty0', os.O_RDWR | os.O_CLOEXEC)
mode = bytearray(4)
fcntl.ioctl(tty, 0x4B3B, mode, True)
previous = struct.unpack('=i', mode)[0]
fcntl.ioctl(tty, 0x4B3A, 1) # KD_GRAPHICS: don't interleave console text.
with mmap.mmap(fb, layout[4], access=mmap.ACCESS_WRITE) as screen:
# Prepare pixels while dark, then unblank the integrated panel.
brightness(0)
helper['paint'](screen, raw, layout)
on(fb, percent)
print(json.dumps({'framebuffer_written': manifest['version'], 'seconds': seconds,
'backend': 'integrated-tianma'}), flush=True)
time.sleep(seconds)
brightness(0)
screen[:] = b'\0' * layout[4]
if boot:
done.write_text(boot_id + '\n')
finally:
try:
if tty is not None:
try:
if previous is not None:
fcntl.ioctl(tty, 0x4B3A, previous)
finally:
os.close(tty)
finally:
# Restoring KD_TEXT can wake fbcon: power down after restoring it.
off(fb)
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('status', help='Read sysfs only; does not open or wake the display')
sub.add_parser('off', help='Backlight zero, then DRM panel powerdown')
for name in ('on', 'brightness', 'show'):
cmd = sub.add_parser(name)
cmd.add_argument('--brightness', type=int, default=25)
if name == 'show':
cmd.add_argument('--directory', type=Path, default=Path('/usr/local/share/platina/current'))
cmd.add_argument('--seconds', type=float, default=7)
cmd.add_argument('--boot', action='store_true')
args = parser.parse_args()
if not 0 <= getattr(args, 'brightness', 25) <= 100:
parser.error('Brightness must be 0–100 percent')
if args.command == 'show' and not 0 < args.seconds <= 3600:
parser.error('Choose a display duration above zero and at most 3600 seconds')
if args.command == 'status':
print(json.dumps(status(), indent=2))
return
with device() as fb:
if args.command == 'off':
off(fb)
elif args.command == 'on':
try:
on(fb, args.brightness)
except BaseException:
off(fb)
raise
elif args.command == 'brightness':
brightness(args.brightness)
else:
show(fb, args.directory, args.seconds, args.brightness, args.boot)
if __name__ == '__main__':
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
try:
main()
except (OSError, ValueError, KeyError) as error:
print('platina-display:', error, file=sys.stderr)
raise SystemExit(1)
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Always start dark. Display the installed release briefly in the background.
for path in /sys/class/backlight/*/brightness; do
[ -w "$path" ] && printf '0\n' > "$path"
done
if [ -x /usr/local/sbin/platina-splash ] && [ -r /usr/local/share/platina/current/release.json ]; then
umask 027
(
driver=$(readlink -f /sys/bus/mipi-dsi/devices/c994000.dsi.0/driver 2>/dev/null || true)
if [ "${driver##*/}" = panel-novatek-nt36672a ]; then
timeout -s TERM -k 3 15 /usr/local/sbin/platina-display show --boot --seconds 7
elif [ -r /usr/local/lib/platina/display/module.json ]; then
timeout -s TERM -k 3 15 /usr/local/sbin/platina-display-session --boot --seconds 7
else
timeout -s TERM -k 3 12 /usr/local/sbin/platina-splash --boot --seconds 7
fi
# Recover full panel powerdown even after the outer timeout killed a renderer.
if [ "${driver##*/}" = panel-novatek-nt36672a ]; then
/usr/local/sbin/platina-display off
fi
# Also recover brightness if timeout had to stop the renderer.
for path in /sys/class/backlight/*/brightness; do
[ -w "$path" ] && printf '0\n' > "$path"
done
) >> /var/log/platina-splash.log 2>&1 &
fi
exit 0
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Show the installed Platina release on fbdev briefly, then turn backlight off."""
import argparse
import fcntl
import gzip
import hashlib
import json
import mmap
import os
from pathlib import Path
import signal
import struct
import sys
import time
CURRENT = Path('/usr/local/share/platina/current')
def load_frame(directory):
# Pin the immutable release before reading several files across a deploy.
directory = directory.resolve(strict=True)
manifest = json.loads((directory / 'release.json').read_text())
if manifest.get('schema') != 1 or manifest.get('name') != 'Platina Linux':
raise ValueError('Unrecognized release manifest')
display = manifest['display']
if (display['width'], display['height'], display['format']) != (1080, 2280, 'BGRX8888'):
raise ValueError('Unsupported release display layout')
if display['frame'] != 'frame.bgrx.gz' or display['raw_bytes'] != 1080 * 2280 * 4:
raise ValueError('Invalid frame manifest')
frame_path = directory / display['frame']
if frame_path.stat().st_size > 12_000_000:
raise ValueError('Oversized compressed frame')
compressed = frame_path.read_bytes()
if hashlib.sha256(compressed).hexdigest() != display['compressed_sha256']:
raise ValueError('Frame checksum mismatch')
with gzip.open(frame_path, 'rb') as source:
raw = source.read(display['raw_bytes'] + 1)
if len(raw) != display['raw_bytes'] or hashlib.sha256(raw).hexdigest() != display['raw_sha256']:
raise ValueError('Decoded frame checksum/length mismatch')
return manifest, raw
def geometry(variable, fixed):
v = struct.unpack_from('=40I', variable)
memory = struct.unpack_from('=I', fixed, 24)[0]
stride = struct.unpack_from('=I', fixed, 48)[0]
width, height, virtual_width, virtual_height, xoff, yoff, bpp = v[:7]
if (width, height, bpp) != (1080, 2280, 32):
raise ValueError('Framebuffer resolution/pixel depth differs from release')
if (v[8:10], v[11:13], v[14:16]) != ((16, 8), (8, 8), (0, 8)):
raise ValueError('Framebuffer does not use BGRX byte order')
if xoff + width > virtual_width or yoff + height > virtual_height:
raise ValueError('Framebuffer viewport exceeds virtual dimensions')
if stride < (xoff + width) * 4 or not 0 < memory <= 64_000_000:
raise ValueError('Invalid framebuffer memory layout')
offset = yoff * stride + xoff * 4
if offset + (height - 1) * stride + width * 4 > memory:
raise ValueError('Framebuffer viewport exceeds mapped memory')
return width, height, stride, offset, memory
def paint(target, raw, layout):
width, height, stride, offset, _ = layout
row = width * 4
for y in range(height):
start = offset + y * stride
target[start:start + row] = raw[y * row:(y + 1) * row]
def show(directory, seconds, brightness, boot):
if os.geteuid() != 0:
raise ValueError('Run on the phone as root')
with Path('/run/platina-splash.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
boot_id = Path('/proc/sys/kernel/random/boot_id').read_text().strip()
done = Path('/run/platina-splash.done')
if boot and done.exists() and done.read_text().strip() == boot_id:
return
manifest, raw = load_frame(directory)
backlight = Path('/sys/class/backlight/backlight')
power = backlight / 'bl_power'
previous_power = power.read_text()
level = max(1, int((backlight / 'max_brightness').read_text()) * brightness // 100)
fb = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
tty, previous = None, None
try:
var, fixed = bytearray(160), bytearray(80)
fcntl.ioctl(fb, 0x4600, var, True) # FBIOGET_VSCREENINFO
fcntl.ioctl(fb, 0x4602, fixed, True) # FBIOGET_FSCREENINFO
layout = geometry(var, fixed)
tty = os.open('/dev/tty0', os.O_RDWR | os.O_CLOEXEC)
mode = bytearray(4)
fcntl.ioctl(tty, 0x4B3B, mode, True) # KDGETMODE
previous = struct.unpack('=i', mode)[0]
fcntl.ioctl(tty, 0x4B3A, 1) # KD_GRAPHICS: console does not overwrite logo.
fcntl.ioctl(fb, 0x4611, 0) # FBIOBLANK / UNBLANK after the VT mode change.
with mmap.mmap(fb, layout[4], access=mmap.ACCESS_WRITE) as screen:
paint(screen, raw, layout)
# FBIOBLANK can leave the backlight's independent power state off.
power.write_text('0\n')
(backlight / 'brightness').write_text(str(level) + '\n')
# This confirms a memory write, not physical panel illumination.
print(json.dumps({'framebuffer_written': manifest['version'], 'seconds': seconds,
'brightness': level, 'boot_id': boot_id}), flush=True)
time.sleep(seconds)
(backlight / 'brightness').write_text('0\n')
screen[:] = b'\0' * layout[4]
if boot:
done.write_text(boot_id + '\n')
finally:
(backlight / 'brightness').write_text('0\n')
power.write_text(previous_power)
if tty is not None:
try:
if previous is not None:
fcntl.ioctl(tty, 0x4B3A, previous)
finally:
os.close(tty)
os.close(fb)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--directory', type=Path, default=CURRENT)
parser.add_argument('--seconds', type=float, default=7)
parser.add_argument('--brightness', type=int, default=25)
parser.add_argument('--boot', action='store_true')
parser.add_argument('--check', action='store_true', help='Validate installed assets without touching display')
args = parser.parse_args()
if not 1 <= args.seconds <= 10 or not 1 <= args.brightness <= 50:
parser.error('Require 1–10 seconds and 1–50 percent brightness')
if args.check:
manifest, _ = load_frame(args.directory)
print(manifest['name'], manifest['version'])
return
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
show(args.directory, args.seconds, args.brightness, args.boot)
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, KeyError) as error:
print('platina-splash:', str(error), file=sys.stderr)
raise SystemExit(1)
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Single source of the project version and local splash/release bundle builder."""
import argparse
import datetime
import gzip
import hashlib
import json
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
RELEASE = ROOT / 'project/release.json'
def version_tuple(value):
if not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', value):
raise ValueError('Expected an explicit major.minor.patch version')
return tuple(map(int, value.split('.')))
def load_release(path=RELEASE):
data = json.loads(path.read_text())
if data['schema'] != 1 or data['name'] != 'Platina Linux':
raise ValueError('Unknown project release identity')
version_tuple(data['version'])
return data
def next_version(value, part):
major, minor, patch = version_tuple(value)
return {'major': f'{major + 1}.0.0', 'minor': f'{major}.{minor + 1}.0',
'patch': f'{major}.{minor}.{patch + 1}'}[part]
def build(output, release=None):
# Pillow is needed only on the build host. The phone uses the standard library.
from PIL import Image, ImageDraw, ImageFont
release = release or load_release()
if output.exists():
raise ValueError('Preserve existing release bundles; choose a new output path')
logo_path = ROOT / 'project/branding/platina-linux-logo.png'
provenance = json.loads((logo_path.parent / 'provenance.json').read_text())
if hashlib.sha256(logo_path.read_bytes()).hexdigest() != provenance['sha256']:
raise ValueError('Logo differs from its recorded provenance')
width, height = 1080, 2280
screen = Image.new('RGB', (width, height), '#000000')
# Render the reusable generated logo as a UI asset; its source is unchanged.
with Image.open(logo_path) as source:
logo = source.convert('RGB')
logo.thumbnail((960, 960), Image.Resampling.LANCZOS)
screen.paste(logo, ((width - logo.width) // 2, 410))
draw = ImageDraw.Draw(screen)
font_path = Path('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf')
font = ImageFont.truetype(str(font_path), 44)
label = 'v' + release['version']
box = draw.textbbox((0, 0), label, font=font)
text_width, text_height = box[2] - box[0], box[3] - box[1]
center_y = 1485
draw.rounded_rectangle((width // 2 - text_width // 2 - 36, center_y - 44,
width // 2 + text_width // 2 + 36, center_y + 44),
radius=36, fill='#090f13', outline='#24353e', width=2)
draw.text(((width - text_width) // 2 - box[0], center_y - text_height // 2 - box[1]),
label, font=font, fill='#d7e3eb')
output.mkdir(parents=True)
screen.save(output / 'preview.png')
raw = screen.tobytes('raw', 'BGRX')
frame = gzip.compress(raw, compresslevel=9, mtime=0)
(output / 'frame.bgrx.gz').write_bytes(frame)
(output / 'version').write_text(release['name'] + ' ' + release['version'] + '\n')
manifest = dict(release, display={
'width': width, 'height': height, 'format': 'BGRX8888', 'seconds': 7,
'brightness_percent': 25, 'frame': 'frame.bgrx.gz',
'raw_bytes': len(raw), 'raw_sha256': hashlib.sha256(raw).hexdigest(),
'compressed_sha256': hashlib.sha256(frame).hexdigest(),
}, logo_sha256=provenance['sha256'],
renderer_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
font_sha256=hashlib.sha256(font_path.read_bytes()).hexdigest())
(output / 'release.json').write_text(json.dumps(manifest, indent=2) + '\n')
print('Built locally:', output, '(not deployed)')
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('show')
bump = sub.add_parser('bump', help='Advance the local project version; never deploy')
bump.add_argument('part', choices=('major', 'minor', 'patch'))
command = sub.add_parser('build', help='Build a local versioned screen; never deploy')
command.add_argument('--output', type=Path)
args = parser.parse_args()
release = load_release()
if args.command == 'show':
print(release['version'])
elif args.command == 'bump':
release['version'] = next_version(release['version'], args.part)
release['released'] = datetime.date.today().isoformat()
RELEASE.write_text(json.dumps(release, indent=2) + '\n')
print('Local version:', release['version'], '; rebuild and deploy with the approved update')
else:
build(args.output or ROOT / ('artifacts/platina-linux-' + release['version']), release)
if __name__ == '__main__':
main()
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
project=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
exec "$project/tools/pmbootstrap/pmbootstrap.py" -c "$project/config/pmbootstrap-managed-candidate.cfg" "$@"
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Prepare an image for Platina locally; Pillow is required only on the build host."""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
from PIL import Image, ImageOps
ROOT = Path(__file__).resolve().parents[1]
def build(source, output):
if output.exists():
raise ValueError('Choose a new frame directory; existing bundles are immutable')
with Image.open(source) as image:
frame = ImageOps.pad(ImageOps.exif_transpose(image).convert('RGB'), (1080, 2280),
color='black', method=Image.Resampling.LANCZOS)
raw = frame.tobytes('raw', 'BGRX')
compressed = gzip.compress(raw, compresslevel=9, mtime=0)
manifest = json.loads((ROOT / 'project/release.json').read_text())
manifest.update(purpose='custom-display-frame', display={
'width': 1080, 'height': 2280, 'format': 'BGRX8888',
'frame': 'frame.bgrx.gz', 'raw_bytes': len(raw),
'raw_sha256': hashlib.sha256(raw).hexdigest(),
'compressed_sha256': hashlib.sha256(compressed).hexdigest(),
})
output.mkdir(parents=True)
frame.save(output / 'preview.png')
(output / 'frame.bgrx.gz').write_bytes(compressed)
(output / 'release.json').write_text(json.dumps(manifest, indent=2) + '\n')
return output
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('image', type=Path)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
print('Prepared locally:', build(args.image, args.output), '; no phone connection')
if __name__ == '__main__':
main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
"""Package user-owned stock firmware locally, verifying the pinned recipe hashes."""
import argparse
import gzip
import hashlib
import importlib.util
import io
from pathlib import Path
import shutil
import subprocess
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parents[1]
def archive_files(directory, group):
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', filename='', mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for source in sorted(directory.iterdir()):
if not source.is_file() or source.is_symlink():
raise ValueError('Unexpected firmware input')
member = tarfile.TarInfo(group + '/' + source.name)
member.mode, member.size = 0o644, source.stat().st_size
with source.open('rb') as stream:
archive.addfile(member, stream)
return output.getvalue()
def prepare(modem, gpu, output, recipe):
if output.exists():
raise ValueError('Preserve existing firmware; choose a new output directory')
if not shutil.which('mcopy'):
raise ValueError('Install mtools on the build host first')
spec = importlib.util.spec_from_file_location('project_workflow', ROOT / 'scripts/project.py')
workflow = importlib.util.module_from_spec(spec)
spec.loader.exec_module(workflow)
checksums = workflow.checksums(recipe)
with tempfile.TemporaryDirectory(prefix='platina-firmware-') as temp:
staging = Path(temp)
for group, patterns in {
'bdwlan': ('bdwlan.*', 'wlanmdsp.mbn'),
'modem': ('mba.mbn', 'modem.mdt', 'modem.b*'),
}.items():
target = staging / group
target.mkdir()
for pattern in patterns:
subprocess.run(['mcopy', '-i', str(modem.resolve()), '::/image/' + pattern, str(target)], check=True)
files = {'a512_zap.elf': gpu.read_bytes()}
for group in ('bdwlan', 'modem'):
files['firmware-xiaomi-platina-' + group + '.tar.gz'] = archive_files(staging / group, group)
for name, data in files.items():
if hashlib.sha512(data).hexdigest() != checksums[name]:
raise ValueError('Firmware differs from the pinned reference: ' + name)
output.mkdir(parents=True)
for name, data in files.items():
(output / name).write_bytes(data)
print('Prepared checksum-verified local firmware; no phone access or redistribution')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--modem-image', type=Path, required=True, help='NON-HLOS.bin from your matching stock ROM')
parser.add_argument('--gpu-firmware', type=Path, required=True, help='Matching a512_zap.elf from your own vendor firmware')
parser.add_argument('--output', type=Path, default=ROOT / 'config/firmware')
parser.add_argument('--recipe', type=Path, default=ROOT / 'ports/candidate/firmware-xiaomi-platina/APKBUILD')
args = parser.parse_args()
prepare(args.modem_image, args.gpu_firmware, args.output, args.recipe)
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
project=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
export PYTHONDONTWRITEBYTECODE=1
exec python3 "$project/scripts/project.py" "$@"
+373
View File
@@ -0,0 +1,373 @@
#!/usr/bin/env python3
"""Local project workflow: checks, pinned builds and offline audits; no deployment."""
import argparse
import configparser
from contextlib import contextmanager
import fcntl
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[1]
RECIPES = ('device-xiaomi-platina', 'firmware-xiaomi-platina', 'linux-postmarketos-qcom-sdm660')
ARCHIVES = {'linux-v6.19.10-sdm660.tar.gz',
'linux-dd1ed52c8ceef4f16715118ed0252fe75adbe71d.tar.gz'}
def run(command, **kwargs):
return subprocess.run(command, cwd=ROOT, check=True, **kwargs)
def lock():
data = json.loads((ROOT / 'project/sources.lock.json').read_text())
if data['schema'] != 1:
raise ValueError('Unsupported source lock schema')
return data
def digest(path, algorithm='sha256'):
with path.open('rb') as stream:
return hashlib.file_digest(stream, algorithm).hexdigest()
def child(directory, name):
relative = Path(name)
if not name or relative.is_absolute() or '..' in relative.parts:
raise ValueError('Unsafe manifest path')
target = directory / relative
if not target.resolve().is_relative_to(directory.resolve()):
raise ValueError('Manifest path escapes bundle')
if any((directory / Path(*relative.parts[:i])).is_symlink()
for i in range(1, len(relative.parts) + 1)):
raise ValueError('Manifest symlinks are not accepted')
if not target.is_file():
raise ValueError('Missing manifest file: ' + name)
return target
def verify(directory):
directory = directory.resolve()
files = json.loads((directory / 'manifest.json').read_text())['files']
if not isinstance(files, list) or not files:
raise ValueError('Manifest needs a nonempty files list')
seen = set()
for row in files:
name = row['file']
target = child(directory, name)
canonical = str(target.relative_to(directory))
if canonical in seen:
raise ValueError('Duplicate manifest file')
seen.add(canonical)
if not re.fullmatch(r'[a-f0-9]{64}', row['sha256']):
raise ValueError('Invalid SHA256')
if target.stat().st_size != row['bytes'] or digest(target) != row['sha256']:
raise ValueError('Artifact verification failed: ' + name)
print(f'OK: {len(files)} artifact hashes and lengths; hardware status unchanged')
def checksums(recipe):
rows = re.findall(r'^([a-f0-9]{128})[ \t]+([^\r\n]+)$', recipe.read_text(), re.M)
if not rows:
raise ValueError('No recipe checksums: ' + recipe.parent.name)
return {name.strip(): value for value, name in rows}
def recipe_checks(directory, external):
# Parse only: never evaluate arbitrary APKBUILD shell code on the host.
for name in RECIPES:
recipe = directory / name / 'APKBUILD'
for filename, expected in checksums(recipe).items():
if filename in external:
continue
if '/' in filename or filename in ('.', '..'):
raise ValueError('Unsafe recipe source path')
source = recipe.parent / filename
if not source.is_file() or source.is_symlink() or digest(source, 'sha512') != expected:
raise ValueError('Recipe input missing or changed: ' + name + '/' + filename)
install = re.search(r'^install="\$pkgname([^"\n]+)"$', recipe.read_text(), re.M)
if install and not (recipe.parent / (name + install[1])).is_file():
raise ValueError('Missing package install hook: ' + name)
def check():
# Explicit roots avoid traversing build mounts, private files and external repos.
candidates = [ROOT / name for name in
('README.md', 'AGENTS.md', 'CONTRIBUTING.md', 'CHANGELOG.md',
'Makefile', '.gitignore', '.gitattributes', 'LICENSE', 'NOTICE')
if (ROOT / name).is_file()]
for name in ('scripts', 'tests', 'ports', 'project', '.github', 'docs', 'LICENSES'):
candidates += [p for p in (ROOT / name).rglob('*')
if p.is_file() and '__pycache__' not in p.parts]
private_key = re.compile(rb'-----BEGIN (?:OPENSSH |RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----')
credential = re.compile(rb'(?im)^\s*(?:psk|password|TELEGRAM_BOT_TOKEN|api_key)\s*=\s*["\']?[^\s"\'\n]{6,}')
for path in candidates:
if path.is_symlink():
if not path.resolve().is_relative_to(ROOT) or not path.exists():
raise ValueError('Broken or external project symlink: ' + str(path.relative_to(ROOT)))
continue
data = path.read_bytes()
if private_key.search(data) or credential.search(data):
raise ValueError('Possible secret in project file (value suppressed): ' + str(path.relative_to(ROOT)))
if path.suffix == '.py':
compile(data, str(path), 'exec')
elif path.suffix in ('.sh', '.start', '.post-install') or path.name == 'APKBUILD' or data.startswith((b'#!/bin/sh', b'#!/sbin/openrc-run')):
run(['sh', '-n', str(path)], stdout=subprocess.DEVNULL)
release = json.loads((ROOT / 'project/release.json').read_text())
if (release.get('schema') != 1 or release.get('name') != 'Platina Linux'
or not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', release.get('version', ''))):
raise ValueError('Invalid Platina project version')
branding = ROOT / 'project/branding'
provenance = json.loads((branding / 'provenance.json').read_text())
if digest(branding / 'platina-linux-logo.png') != provenance['sha256']:
raise ValueError('Logo changed without updating provenance')
data = lock()
for profile in data['profiles'].values():
recipe_checks(ROOT / profile['ports'], set(data['local_firmware']) | ARCHIVES)
for package, field in zip(RECIPES, ('device_package', 'firmware_package', 'kernel_package')):
text = (ROOT / profile['ports'] / package / 'APKBUILD').read_text()
version = re.search(r'^pkgver=(\S+)$', text, re.M)[1]
release = re.search(r'^pkgrel=(\d+)$', text, re.M)[1]
if version + '-r' + release != profile[field]:
raise ValueError('Profile version differs from recipe: ' + package)
if (ROOT / '.git').is_dir():
tracked = subprocess.check_output(['git', 'ls-files', '-z'], cwd=ROOT).decode().split('\0')
allowed = {str(p.relative_to(ROOT)) for p in candidates} | {'PLAN.md'}
if any(name and name not in allowed for name in tracked):
raise ValueError('Unexpected tracked path; review Git index')
run(['git', 'diff', '--check'])
run(['git', 'diff', '--cached', '--check'])
run([sys.executable, '-m', 'unittest', 'discover', '-s', 'tests', '-v'])
print(f'OK: syntax, secret patterns, recipe checksums, profile versions and tests ({len(candidates)} files)')
def repo_at(path, source, fetch):
if path.exists():
actual = subprocess.check_output(['git', '-C', str(path), 'rev-parse', 'HEAD'], text=True).strip()
if actual != source['commit']:
raise ValueError('Checkout differs from source lock: ' + str(path.relative_to(ROOT)))
return
if not fetch:
raise ValueError('Missing checkout; use prepare --fetch for explicit source download')
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.platina-', dir=path.parent) as temporary:
temp = Path(temporary) / 'checkout'
run(['git', 'init', '-q', str(temp)])
run(['git', '-C', str(temp), 'remote', 'add', 'origin', source['url']])
run(['git', '-C', str(temp), 'fetch', '--depth=1', 'origin', source['commit']])
run(['git', '-C', str(temp), 'checkout', '--detach', source['commit']])
temp.rename(path)
def config_path(profile):
return ROOT / 'config' / ('pmbootstrap-managed-' + profile + '.cfg')
def managed_path(profile):
return ROOT / 'sources' / ('pmaports-managed-' + profile)
def port_files(directory):
result = {}
for name in RECIPES:
for path in sorted((directory / name).rglob('*')):
if path.is_symlink():
raise ValueError('Unexpected symlink in managed recipes')
if path.is_file():
result[str(path.relative_to(directory))] = digest(path)
return result
def write_stamp(profile):
destination = managed_path(profile)
data = {'profile': profile, 'files': port_files(destination / 'device/testing')}
(destination / '.platina-managed.json').write_text(json.dumps(data, indent=2) + '\n')
def sync(profile):
data = lock()
definition = data['profiles'][profile]
destination = managed_path(profile)
stamp = json.loads((destination / '.platina-managed.json').read_text())
if stamp['profile'] != profile or port_files(destination / 'device/testing') != stamp['files']:
raise ValueError('Managed recipes were edited locally; preserve and review before sync')
recipe_checks(ROOT / definition['ports'], set(data['local_firmware']) | ARCHIVES)
firmware = destination / 'device/testing/firmware-xiaomi-platina'
sums = checksums(ROOT / definition['ports'] / 'firmware-xiaomi-platina/APKBUILD')
for name in data['local_firmware']:
if digest(firmware / name, 'sha512') != sums[name]:
raise ValueError('Firmware changed; prepare a new isolated profile')
new_files = port_files(ROOT / definition['ports'])
for name in stamp['files'].keys() - new_files.keys():
if Path(name).name not in data['local_firmware']:
(destination / 'device/testing' / name).unlink()
for name in new_files:
target = destination / 'device/testing' / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / definition['ports'] / name, target)
write_stamp(profile)
print('Managed recipes synchronized; no build or device action performed.')
@contextmanager
def build_slot():
(ROOT / 'logs').mkdir(exist_ok=True)
with (ROOT / 'logs/managed-build.lock').open('a') as stream:
try:
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise ValueError('Another managed build/prepare/sync is running') from None
yield
def prepare(profile, fetch):
data = lock()
definition = data['profiles'][profile]
destination = managed_path(profile)
cfg_path = config_path(profile)
if destination.exists() or cfg_path.exists():
raise ValueError('Managed profile already exists; preserve it and review changes manually')
recipe_checks(ROOT / definition['ports'], set(data['local_firmware']) | ARCHIVES)
sums = checksums(ROOT / definition['ports'] / 'firmware-xiaomi-platina/APKBUILD')
blob_sources = []
for name in data['local_firmware']:
options = [ROOT / 'config/firmware' / name,
ROOT / 'sources/pmaports-server/device/testing/firmware-xiaomi-platina' / name]
source = next((p for p in options if p.is_file()), None)
if source is None or digest(source, 'sha512') != sums[name]:
raise ValueError('Missing or incorrect local firmware: ' + name + '; see docs/DEVELOPMENT.md')
blob_sources.append(source)
if not list((ROOT / 'config').glob('admin-*.pub')):
raise ValueError('Add your public SSH key as config/admin-*.pub before preparing a server image')
repo_at(ROOT / data['repositories']['pmbootstrap']['path'], data['repositories']['pmbootstrap'], fetch)
# Clone committed objects only; the existing pmaports index and edits are preserved.
source = ROOT / 'sources/pmaports-server'
if source.exists():
run(['git', 'clone', '--no-hardlinks', '--no-checkout', str(source), str(destination)])
run(['git', '-C', str(destination), 'checkout', '--detach', data['repositories']['pmaports']['commit']])
else:
repo_at(destination, data['repositories']['pmaports'], fetch)
# The channel table lives on main, independently of the pinned release tree.
channels = data['repositories']['pmaports'].get('channels_commit')
if channels:
run(['git', '-C', str(destination), 'fetch', '--depth=1',
str(source) if source.exists() else data['repositories']['pmaports']['url'],
channels])
run(['git', '-C', str(destination), 'update-ref', 'refs/remotes/origin/main', channels])
# pmbootstrap identifies the checkout by its canonical remote URL.
run(['git', '-C', str(destination), 'remote', 'set-url', 'origin',
data['repositories']['pmaports']['url']])
for name in RECIPES:
target = destination / 'device/testing' / name
if target.exists():
shutil.rmtree(target) # Only in the newly created checkout above.
shutil.copytree(ROOT / definition['ports'] / name, target)
for source in blob_sources:
shutil.copyfile(source, destination / 'device/testing/firmware-xiaomi-platina' / source.name)
write_stamp(profile)
for name in ('config', 'logs', 'reports', 'artifacts', 'work'):
(ROOT / name).mkdir(exist_ok=True)
cfg = configparser.ConfigParser()
cfg['pmbootstrap'] = {
'aports': str(destination), 'work': str(ROOT / 'work' / ('pmbootstrap-managed-' + profile)),
'device': 'xiaomi-platina', 'hostname': 'platina', 'user': 'server', 'ui': 'none',
'ui_extras': 'False', 'service_manager': 'openrc', 'timezone': 'Europe/Prague',
'locale': 'C.UTF-8', 'jobs': '2', 'ssh_keys': 'True', 'extra_packages': 'chrony',
'auto_zap_misconfigured_chroots': 'no',
'ssh_key_glob': str(ROOT / 'config/admin-*.pub'), 'is_default_channel': 'False'}
cfg['providers'] = {}
cfg['mirrors'] = {}
with cfg_path.open('x') as stream:
cfg.write(stream)
print('Prepared isolated ' + profile + ' profile. No build or device action performed.')
def pmb(profile):
cfg = config_path(profile)
if not cfg.is_file():
raise ValueError('Run prepare --profile ' + profile + ' first')
data = lock()
tool = ROOT / data['repositories']['pmbootstrap']['path']
repo_at(tool, data['repositories']['pmbootstrap'], False)
destination = managed_path(profile)
repo_at(destination, data['repositories']['pmaports'], False)
config = configparser.ConfigParser()
config.read(cfg)
if (config['pmbootstrap']['aports'] != str(destination)
or config['pmbootstrap']['work'] != str(ROOT / 'work' / ('pmbootstrap-managed-' + profile))):
raise ValueError('Managed config paths changed; review before building')
stamp = json.loads((destination / '.platina-managed.json').read_text())
if stamp['files'] != port_files(destination / 'device/testing'):
raise ValueError('Managed recipes changed; preserve and review local edits')
for name, expected in port_files(ROOT / data['profiles'][profile]['ports']).items():
if stamp['files'].get(name) != expected:
raise ValueError('Versioned recipes changed; run sync --profile ' + profile)
return ['nice', '-n', '10', sys.executable, str(tool / 'pmbootstrap.py'), '-c', str(cfg), '-j', '2']
def doctor():
for name in ('git', 'python3', 'make', 'sh', 'sudo', 'debugfs', 'blkid', 'ssh'):
print(name + ': ' + ('available' if shutil.which(name) else 'missing'))
data = lock()
tool = ROOT / data['repositories']['pmbootstrap']['path']
print('pmbootstrap checkout: ' + ('present' if tool.exists() else 'missing; prepare --fetch'))
for profile in data['profiles']:
print(profile + ' managed config: ' + ('present' if config_path(profile).is_file() else 'not prepared'))
print('Read-only local check; phone, USB ports and services were not probed.')
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
for name in ('check', 'doctor'):
commands.add_parser(name)
prep = commands.add_parser('prepare', help='Create isolated local build checkout/config')
prep.add_argument('--profile', choices=tuple(lock()['profiles']), default='candidate')
prep.add_argument('--fetch', action='store_true', help='Allow downloading pinned Git sources')
syncing = commands.add_parser('sync', help='Refresh managed recipes, preserving local edits on conflict')
syncing.add_argument('--profile', choices=tuple(lock()['profiles']), default='candidate')
kernel = commands.add_parser('kernel', help='Build a kernel locally; no phone connection')
kernel.add_argument('--profile', choices=tuple(lock()['profiles']), default='candidate')
images = commands.add_parser('images', help='Build candidate images locally')
images.add_argument('--output', required=True, help='New candidate-* artifact directory')
for name in ('verify', 'audit'):
command = commands.add_parser(name, help='Offline artifact ' + name)
command.add_argument('directory', type=Path)
args = parser.parse_args()
if args.command == 'check':
check()
elif args.command == 'doctor':
doctor()
elif args.command == 'prepare':
with build_slot():
prepare(args.profile, args.fetch)
elif args.command == 'sync':
with build_slot():
sync(args.profile)
elif args.command == 'kernel':
with build_slot():
run(pmb(args.profile) + ['build', '--arch', 'aarch64', 'linux-postmarketos-qcom-sdm660'])
elif args.command == 'images':
with build_slot():
pmb('candidate')
run([sys.executable, str(ROOT / 'scripts/build-candidate-images.py'),
'--config', str(config_path('candidate')), '--output-name', args.output])
elif args.command == 'verify':
verify(args.directory)
elif args.command == 'audit':
verify(args.directory)
(ROOT / 'reports').mkdir(exist_ok=True)
run([sys.executable, str(ROOT / 'scripts/audit-candidate-artifacts.py'),
'--directory', str(args.directory.resolve())])
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as exc:
print('ERROR: ' + str(exc), file=sys.stderr)
sys.exit(1)
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Rebuild initramfs module indexes for its actual files; never deploys.
mkinitfs 2.11 copies the complete rootfs module indexes into a partial module
archive. Early udev can then attempt to load drivers absent from that archive.
Run depmod against only the archived modules, preserving the kernel and cmdline.
Only the verified Android v0 layout used by this project is accepted.
"""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
import re
import stat
import struct
import subprocess
import tempfile
def unpack(data):
records = []
offset = 0
seen = set()
while offset + 110 <= len(data):
header = data[offset:offset + 110]
if header[:6] != b'070701':
raise ValueError('Expected newc archive')
fields = [int(header[i:i + 8], 16) for i in range(6, 110, 8)]
size, namesize = fields[6], fields[11]
rawname = data[offset + 110:offset + 110 + namesize]
if not rawname.endswith(b'\0'):
raise ValueError('Invalid archive name')
name = rawname[:-1].decode()
start = (offset + 110 + namesize + 3) & ~3
end = start + size
if end > len(data):
raise ValueError('Truncated archive')
if name == 'TRAILER!!!':
return records
name = name.removeprefix('./')
if name.startswith('/') or '..' in Path(name).parts or name in seen:
raise ValueError('Unsafe or duplicate archive path')
seen.add(name)
records.append((name, fields, data[start:end]))
offset = (end + 3) & ~3
raise ValueError('Missing archive trailer')
def pack(records):
output = bytearray()
trailer = ('TRAILER!!!', [0] * 13, b'')
for name, original, data in [*records, trailer]:
fields = original.copy()
encoded = name.encode() + b'\0'
fields[6], fields[11], fields[12] = len(data), len(encoded), 0
output.extend(b'070701' + ''.join(f'{v:08x}' for v in fields).encode())
output.extend(encoded)
output.extend(b'\0' * (-len(output) % 4))
output.extend(data)
output.extend(b'\0' * (-len(output) % 4))
output.extend(b'\0' * (-len(output) % 512))
return bytes(output)
def parts(boot):
if boot[:8] != b'ANDROID!':
raise ValueError('Not an Android boot image')
f = struct.unpack_from('<10I', boot, 8)
ksize, rsize, second, page, version = f[0], f[2], f[4], f[7], f[8]
if page != 4096 or version != 0 or second != 0:
raise ValueError('Unsupported boot layout')
start = page + ((ksize + page - 1) // page) * page
end = start + ((rsize + page - 1) // page) * page
if end != len(boot):
raise ValueError('Unexpected boot trailer or length')
kernel, ramdisk = boot[page:page + ksize], boot[start:start + rsize]
if boot[576:596] != boot_hash(kernel, ramdisk):
raise ValueError('Boot payload hash mismatch')
return kernel, ramdisk, start
def boot_hash(kernel, ramdisk):
h = hashlib.sha1()
for blob in (kernel, ramdisk, b''):
h.update(blob)
h.update(struct.pack('<I', len(blob)))
return h.digest()
def replace_ramdisk(boot, ramdisk):
kernel, _, start = parts(boot)
result = bytearray(boot[:start])
struct.pack_into('<I', result, 16, len(ramdisk))
result[576:608] = boot_hash(kernel, ramdisk).ljust(32, b'\0')
result.extend(ramdisk)
result.extend(b'\0' * (-len(result) % 4096))
if len(result) > 0x3FFC000:
raise ValueError('Boot partition limit exceeded')
parts(result)
return bytes(result)
def scope(boot, release):
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+-sdm660', release):
raise ValueError('Invalid kernel release')
_, ramdisk, _ = parts(boot)
records = unpack(gzip.decompress(ramdisk))
prefix = next((v for v in (f'usr/lib/modules/{release}/', f'lib/modules/{release}/')
if any(name.startswith(v) for name, _, _ in records)), None)
if not prefix:
raise ValueError('Kernel modules absent')
modules = {name[len(prefix):]: data for name, mode, data in records
if name.startswith(prefix) and '.ko' in name and stat.S_ISREG(mode[1])}
if not modules:
raise ValueError('Empty module archive')
with tempfile.TemporaryDirectory(prefix='platina-depmod-') as directory:
root = Path(directory)
target = root / 'lib/modules' / release
target.mkdir(parents=True)
for name, data in modules.items():
f = target / name
f.parent.mkdir(parents=True, exist_ok=True)
f.write_bytes(data)
for name, _, data in records:
if name.startswith(prefix + 'modules.builtin'):
(target / Path(name).name).write_bytes(data)
(target / 'modules.order').write_text('\n'.join(sorted(modules)) + '\n')
subprocess.run(['depmod', '-C', '/dev/null', '-b', directory, release],
check=True, capture_output=True)
metadata = {f.name: f.read_bytes() for f in target.glob('modules.*')}
dependencies = dict(line.split(':', 1) for line in metadata['modules.dep'].decode().splitlines())
if set(dependencies) != set(modules) or any(d not in modules for ds in dependencies.values() for d in ds.split()):
raise ValueError('Generated dependency index differs from archived files')
filtered = [(n, m, d) for n, m, d in records if not n.startswith(prefix + 'modules.')]
for i, (name, data) in enumerate(sorted(metadata.items())):
fields = [0, stat.S_IFREG | 0o644, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
fields[0] = 100000 + i
filtered.append((prefix + name, fields, data))
new_ramdisk = gzip.compress(pack(filtered), mtime=0)
new_boot = replace_ramdisk(boot, new_ramdisk)
return new_boot, new_ramdisk, len(modules)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('boot', type=Path)
parser.add_argument('--release', required=True)
parser.add_argument('--output', required=True, type=Path)
args = parser.parse_args()
if args.output.exists():
raise SystemExit('Preserve existing output; choose a new directory')
original = args.boot.read_bytes()
boot, ramdisk, count = scope(original, args.release)
args.output.mkdir(parents=True)
files = []
for name, data in [('boot.img', boot), ('initramfs', ramdisk)]:
(args.output / name).write_bytes(data)
files.append({'file': name, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()})
manifest = {'kernel': args.release, 'flashed': False, 'hardware_tested': False,
'source_sha256': hashlib.sha256(original).hexdigest(),
'initramfs_modules': count, 'module_indexes_scoped': True, 'files': files}
(args.output / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
print(json.dumps(manifest, indent=2))
if __name__ == '__main__':
main()