Integrate boot and shutdown runtime into new images

This commit is contained in:
Sukecz
2026-10-23 20:28:26 +02:00
parent b7eb4289b7
commit 9c49f58b33
27 changed files with 1087 additions and 80 deletions
+4
View File
@@ -16,5 +16,9 @@ jobs:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: Install host tools for screen integration tests
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends python3-pil fonts-dejavu-core
- name: Validate sources and run offline tests
run: make check
+29 -11
View File
@@ -1,18 +1,36 @@
# Changelog
## Unreleased — integrated display candidate
## 0.3.1 — fresh-image integration
- Kernel 7.2.12-r1 adds the Platina Tianma NT36672A panel to the normal driver and device tree.
- Full kernel and module build passed; the existing-installation boot candidate passed offline checks.
- Added display on/off/brightness/status, timed images and host-side image preparation.
- Panel activation, repeated power cycles and power use still require physical testing.
- New local images include versioned boot and shutdown screens, display helpers,
the headless boot hook and the enabled OpenRC shutdown-button service.
- Image audits verify decoded screens, file hashes, permissions and service links.
- Exported boot images automatically receive module indexes matching the actual
initramfs contents; the final boot/rootfs pair is audited before build success.
- A full local image passed offline audits. This image has not been flashed or
physically tested; the tested phone remains on integration 0.3.0.
## 0.1.1 — verified integration
## 0.3.0 — verified shutdown buttons and screen
- Boot into headless postmarketOS from eMMC with SSH over Wi-Fi or USB networking.
- Key-only SSH, disabled root/password login, NetworkManager reconnect and OpenRC autostart.
- Corrected initramfs module indexes and verified normal restarts.
- Displayed the Platina logo for seven seconds using an explicitly loaded temporary LCD helper.
- Automatic logo and backlight shutdown were physically confirmed on a Tianma Mi 8 Lite.
- Hold Power + Volume Up for three seconds and release both for orderly shutdown.
- Show the Platina logo, release version and Power off screen during shutdown.
- Preview, button handling and shutdown on battery were physically verified.
- Disconnect USB/the charger first to remain powered off. Attached power triggers
a charger-mode boot and starts Linux again; this remains an accepted limitation.
- No experimental PMIC trigger changes are included in new images.
## 0.2.0 — verified integrated display
- Kernel 7.2.12-r1 integrates the Platina Tianma NT36672A panel and device tree.
- RAM boot, normal eMMC boot, logo, brightness and ten display off/on cycles passed
physical testing. VSP/VSN full rail shutdown and power savings remain unproven.
- Display on/off/brightness/status, timed images and host-side image preparation.
## 0.1.1 — historical integration
- Headless postmarketOS from eMMC with key-only SSH over Wi-Fi or USB networking.
- NetworkManager reconnect and OpenRC autostart; corrected initramfs indexes.
- Seven-second boot logo using a temporary LCD helper, now superseded on the
tested Tianma phone by the integrated driver.
The integration version is separate from the kernel and distribution versions.
+24 -13
View File
@@ -14,10 +14,15 @@ this is not Android, a container inside Android, or a desktop phone OS.
[![License: GPL v2](https://img.shields.io/badge/License-GPL_v2-blue.svg)](LICENSE)
[![Device: Xiaomi Mi 8 Lite](https://img.shields.io/badge/device-Xiaomi_Mi_8_Lite-ff6900)](docs/HARDWARE.md)
**Verified integration: 0.1.1** · **Kernel: 7.2.12-sdm660** · **Development / early hardware testing**
**Verified integration: 0.3.0** · **Kernel: 7.2.12-r1 / 7.2.12-sdm660** · **Development / early hardware testing**
**Source/build integration: 0.3.1.** Fresh image builds include both screens,
display helpers and the shutdown service. This packaging update has not been
flashed to the tested phone; its installed integration remains 0.3.0.
[Installation](docs/INSTALLATION.md) · [Build from source](docs/BUILDING.md)
· [Display development](docs/DISPLAY.md) · [Changelog](CHANGELOG.md) · [Licensing](docs/LICENSING.md)
· [Display development](docs/DISPLAY.md) · [Shutdown](docs/SHUTDOWN.md)
· [Changelog](CHANGELOG.md) · [Licensing](docs/LICENSING.md)
## What it does
@@ -28,9 +33,8 @@ this is not Android, a container inside Android, or a desktop phone OS.
USB networking provides a separate local administration path.
- **Headless by default:** keep the backlight dark while running background services.
- **Battery and charger operation:** use Wi-Fi while running on the battery or a separate charger.
- **A useful display foundation:** the existing logo works with a temporary helper;
the integrated Tianma driver and commands for brightness, power and custom images
are prepared for their next hardware test.
- **Integrated Tianma display:** boot logo, brightness and ten repeated display
off/on cycles have been physically verified. Full LCD rail shutdown remains pending.
- **Repeatable development:** pinned source revisions, versioned recipes, checksum
verification, offline tests and separate build/export/audit steps.
@@ -59,9 +63,11 @@ not a guarantee for every device or panel variant.
| Battery operation | 🟢 | Wi-Fi administration with data USB physically disconnected |
| Separate charger operation | 🟢 | Operation and charging confirmed with a suitable charger/cable |
| Battery / thermal telemetry | 🟢 | Battery information and CPU, GPU and battery temperature readings |
| Short boot logo | 🟢 | Logo and subsequent backlight shutdown physically confirmed in 0.1.1 |
| Integrated Tianma NT36672A panel driver | 🟠 | Kernel 7.2.12-r1 built; boot/module candidate audited offline, not yet boot-tested |
| Display power, brightness and custom images | 🟠 | Control tools and image conversion tested offline; panel power cycles await hardware test |
| Physical shutdown buttons and screen | 🟢 | Power + Volume Up held for 3 s, release both; Power off logo and battery shutdown physically verified |
| Staying off while USB power is connected | 🔴 | Accepted limitation: disconnect USB/charger before shutdown; otherwise the bootloader starts Linux again |
| Short boot logo | 🟢 | Automatic logo and subsequent shutdown physically confirmed after normal boot in 0.2.0 |
| Integrated Tianma NT36672A panel driver | 🟢 | Kernel 7.2.12-r1: RAM boot, normal eMMC boot, image and ten off/on cycles verified |
| Display power, brightness and custom images | 🟠 | Brightness and driver powerdown verified; VSP/VSN remain fixed always-on. Custom-image conversion tested offline |
| Beszel monitoring | 🟠 | Native monitoring tested separately; optional custom hub/power-chart integration is outside this source base |
| VPN access from outside the home network | 🟠 | A LAN jump-host route was tested; a real off-site client test is pending |
| Continuous 48–72-hour uptime | 🟠 | Qualification is pending; shorter successful tests are not a soak test |
@@ -73,9 +79,14 @@ not a guarantee for every device or panel variant.
| Android apps / Android services | 🔴 | This system replaces the running Android environment |
| Other Xiaomi Mi 8 models / other phones | 🔴 | This port targets **Mi 8 Lite / platina only** |
The checked-in candidate sources are **kernel 7.2.12-r1 + device 5-r31**. They include
the new display work; **they are not the same as the physically verified 0.1.1
installation**. The public firmware recipe is 2-r5, with a newly written packaging
To switch the phone off and keep it off, **disconnect USB/the charger first**,
hold **Power + Volume Up for at least 3 seconds**, then release both buttons.
The Platina logo and Power off screen appear during shutdown. The shutdown
service is enabled; experimental PMIC trigger changes are not loaded automatically.
The checked-in candidate sources are **kernel 7.2.12-r1 + device 5-r31**. The
physically verified 0.2.0 installation uses that kernel with device 5-r30 and
the documented runtime initramfs adjustments. The public firmware recipe is 2-r5, with a newly written packaging
helper; proprietary firmware payloads are supplied locally by each builder.
No prebuilt installation images or binary firmware are published here.
@@ -112,8 +123,8 @@ means **built**, an offline audit means **audited**, and a physical phone test m
**hardware verified**. These states are recorded separately.
Platina's integration version lives in `project/release.json`; it is independent
of the Linux and Alpine version numbers. The integrated display candidate will
become a new integration version only after installation and hardware validation.
of the Linux and Alpine version numbers. Integration 0.2.0 records the physically tested Tianma driver; 0.3.0 adds
the shutdown chord and screen. Display rail and USB charger-boot limits are documented.
## Credits and license
+30 -21
View File
@@ -1,8 +1,9 @@
# Building Platina Linux
This is a source-only development port. The candidate kernel builds, but the new
integrated Tianma display still needs its first successful physical boot test.
An image built here is a candidate, not a ready-made stable release.
This is a source-only development port. Integration 0.3.0 and kernel 7.2.12-r1
were physically tested on a Tianma Mi 8 Lite. Source version 0.3.1 integrates
that runtime into newly built images; the new full image still requires its own
hardware acceptance. There is no ready-made stable release.
## Build host
@@ -14,14 +15,14 @@ On Debian/Ubuntu, typical host tools are:
```sh
sudo apt install git python3 make sudo openssh-client e2fsprogs util-linux kmod mtools fastboot
# Optional: only needed for make splash / custom image conversion.
# Required for the versioned boot/shutdown screens included by make images.
sudo apt install python3-pil fonts-dejavu-core
```
`make doctor` reports missing core tools without installing them. Kernel compilers
and package dependencies are installed inside the build chroots by pmbootstrap.
Python's standard library is enough for the basic offline test suite; image
conversion uses Pillow on the build host.
Python's standard library is enough for the basic offline test suite; the image
runtime integration tests and full image builder also need Pillow and DejaVu Sans.
## Personal build inputs
@@ -77,26 +78,33 @@ The builder stops pmbootstrap mounts before copying/hashing filesystem images.
Source revisions are pinned, but external Alpine repositories/toolchain packages
are not fully frozen; bit-for-bit reproducible full builds are not promised.
## Scope initramfs module indexes
## Integrated runtime and initramfs audit
`make images` builds the versioned boot logo and Power off screen, installs the
Python display/shutdown helpers and headless hook, and enables the OpenRC
Power + Volume Up service with the verified three-second policy. The image audit
checks file hashes, decoded frames, permissions and service links without touching
the display or invoking shutdown. No experimental PMIC module is included.
The USB current helper and NetworkManager dispatcher are also included. They are
inert without a separately supplied `/etc/platina/usb-power.json` policy; no host
identity or increased-current allowance is cloned from the development phone.
Wi-Fi credentials and monitoring credentials also remain per-installation inputs.
The mkinitfs version used by this port can copy full-rootfs module indexes into
an initramfs containing only some modules. Before booting or flashing, regenerate
indexes for the modules that are actually included:
an initramfs containing only some modules. The builder automatically regenerates
indexes for the modules actually included in the exported boot image. The final
boot.img and initramfs are hashed only after this correction. The unmodified
pmbootstrap export links are intermediate files, not the accepted output bundle.
```sh
python3 scripts/scope-initramfs-modules.py artifacts/candidate-local/boot.img \
--release 7.2.12-sdm660 --output artifacts/candidate-local-scoped
make verify DIR=artifacts/candidate-local-scoped
```
Use **candidate-local-scoped/boot.img** with **candidate-local/xiaomi-platina.img**.
The scoping tool preserves the kernel, DTB and rootfs command line; it does not
create a second root filesystem and does not flash anything.
Use boot.img and xiaomi-platina.img from the **same final candidate-local bundle**.
For manually exported older images, `scripts/scope-initramfs-modules.py` remains
available. The correction preserves the kernel, DTB and rootfs command line.
Exported files include boot.img, xiaomi-platina.img, initramfs, kernel and DTB.
Keep the manifest and corresponding APKs for your own rollback records.
## Optional display assets
## Separate display asset bundles
```sh
make splash
@@ -104,5 +112,6 @@ python3 scripts/prepare-display-frame.py your-image.png --output artifacts/custo
```
The original logo is preserved; the integration version is added during rendering.
These commands create local bundles. `make images` does not yet install the
versioned splash bundle automatically; see [display setup](DISPLAY.md).
These commands create separate local bundles for review or an explicitly planned
existing-installation update. A fresh `make images` already includes both release
screens. See [display setup](DISPLAY.md) and [shutdown behavior](SHUTDOWN.md).
+21 -10
View File
@@ -5,8 +5,9 @@ has two separate states:
| State | Status |
|---|---|
| Integration 0.1.1 logo with a temporary LCD power/wake helper | 🟢 Physically verified, including automatic start and subsequent backlight shutdown |
| Integrated driver / DT in kernel 7.2.12-r1 | 🟠 Compiled and audited offline; physical boot and power cycles pending |
| Integration 0.1.1 temporary LCD power/wake helper | Historical fallback, superseded on the tested phone |
| Integration 0.2.0, integrated driver / DT in kernel 7.2.12-r1 | 🟢 RAM boot, normal boot, logo, brightness and ten off/on cycles physically verified |
| Complete LCD rail shutdown | 🟠 Driver votes released, but VSP/VSN remain fixed always-on |
The candidate is in `ports/candidate/linux-postmarketos-qcom-sdm660/0030-platina-tianma-panel.patch`.
It adds the panel-specific command sequence, correct regulator names, reset timing,
@@ -14,7 +15,15 @@ DT binding and initialization-error cleanup to the NT36672A driver. The stock
command sequence is recorded in `project/display/tianma-reference.json` and
compared by offline tests. This is not a verified BOE TD4320 configuration.
## Optional controller setup
## Built-in controller and screens
From source version 0.3.1, fresh `make images` builds include the controller,
headless boot hook, versioned boot logo and shutdown screen automatically.
Hardware verification of integration 0.3.0 does not qualify every new full image.
The following manual steps are for an existing installation that lacks those
files; they are not required after installing a newly integrated image.
## Manual controller setup for an existing installation
After testing a successful boot with the integrated driver, install the renderer
and controller on **your phone**. The files listed below are source files from
@@ -27,9 +36,9 @@ sudo install -m755 phone-display.py /usr/local/sbin/platina-display
```
For the logo, run `make splash` on the build host. Transfer its three runtime files
`release.json`, `version` and `frame.bgrx.gz` from `artifacts/platina-linux-0.1.1/`
into a new phone directory `/usr/local/share/platina/releases/0.1.1/`, then create
`/usr/local/share/platina/current` pointing to `releases/0.1.1`. If updating an
`release.json`, `version` and `frame.bgrx.gz` from `artifacts/platina-linux-0.2.0/`
into a new phone directory `/usr/local/share/platina/releases/0.2.0/`, then create
`/usr/local/share/platina/current` pointing to `releases/0.2.0`. If updating an
existing setup, back up its assets/hook first and use a new versioned directory.
The phone renderer uses Python's standard library, without Pillow or a desktop.
@@ -51,7 +60,9 @@ lock. An external SIGKILL cannot run Python cleanup.
`off` requests `FB_BLANK_POWERDOWN` through DRM after clearing the backlight.
A brightness value of zero alone is not proof that the LCD rails are powered off.
Regulator counts and actual repeated wake behavior must be checked on the device.
Tests on the maintainer's phone confirmed all three driver consumer votes return
to zero and vddio is released. VSP/VSN still use inherited fixed always-on
definitions, so full physical rail shutdown and power savings are not established.
Prepare another image on the build host:
@@ -71,9 +82,9 @@ new controller. On the old boot it selects the temporary session only when that
kernel-specific module was explicitly installed. Do not install the old helper
blindly, or auto-load it alongside the integrated driver.
Only install the hook after manual rendering and powerdown have worked. The
current clean-image builder keeps the backlight dark and does not automatically
install a generated splash bundle. SSH must remain independent of splash success.
For a manual existing-installation update, install the hook only after rendering
and powerdown have worked. The clean-image builder installs the full hook and
both screens; SSH remains independent of splash success.
## Hardware acceptance
+5 -4
View File
@@ -1,8 +1,9 @@
# Install Linux on Xiaomi Mi 8 Lite (platina)
**Development port.** The maintainer's existing installation boots and provides
SSH, but the checked-in integrated Tianma display candidate has not yet passed
its physical boot/power-cycle test. There is no supported prebuilt installer.
SSH; kernel 7.2.12-r1 and integration 0.3.0 passed physical Tianma display and
shutdown tests. New full images built from 0.3.1 have a separate acceptance
requirement. There is no supported prebuilt installer.
Build your own images using [BUILDING.md](BUILDING.md).
These steps are for a **fresh installation** on **Mi 8 Lite / platina**.
@@ -51,9 +52,9 @@ The examples below assume these files exist:
```sh
ROOTFS=artifacts/candidate-local/xiaomi-platina.img
BOOT=artifacts/candidate-local-scoped/boot.img
BOOT=artifacts/candidate-local/boot.img
make verify DIR=artifacts/candidate-local
make verify DIR=artifacts/candidate-local-scoped
make audit DIR=artifacts/candidate-local
```
The boot command line must refer to the UUID of that root filesystem. Do not mix
+36
View File
@@ -0,0 +1,36 @@
# Shutdown buttons and screen
The tested Mi 8 Lite uses **Power + Volume Up** for an orderly Linux shutdown.
The OpenRC service `platina-power-chord` is enabled in newly built images.
1. Disconnect USB/the charger so the phone runs on its battery.
2. Hold Power and Volume Up together for at least three seconds.
3. Release both buttons. The Platina logo, version and Power off screen appear
while Linux shuts down. On battery, the tested phone stays off.
With USB power attached, shutdown still runs, but the bootloader starts the phone
again in charger mode and Linux boots normally. This is an accepted limitation.
Reconnecting a charger can also start the phone. There is no automatic waiting
for cable removal and no separate charging-only operating mode.
The service uses both evdev inputs. Short combinations, individual keys, repeats
and lost input events do not request shutdown. It acts only after both keys have
been released. This requires a running kernel and userspace service; it is not
an independent emergency power cut for a frozen phone. Existing long-Power reset
and bootloader key combinations are unchanged.
The screen indicates shutdown is in progress. Physical darkness alone is not
proof that the phone is fully off. Integration 0.3.0 was physically verified;
the 0.3.1 fresh-image packaging is verified separately without flashing a phone.
For diagnosis on a phone running a newly built 0.3.1 image:
```sh
rc-service platina-power-chord status
sudo platina-poweroff --preview
sudo python3 /usr/local/libexec/platina-image-runtime audit
```
Preview only shows the screen for five seconds. The audit reads installed files
and checksums without accessing display/input hardware or requesting shutdown.
The image runtime contains no experimental PMIC module or PMIC autoload rule.
+2 -2
View File
@@ -1,7 +1,7 @@
{
"schema": 1,
"name": "Platina Linux",
"version": "0.1.1",
"version": "0.3.1",
"channel": "development",
"released": "2026-10-22"
"released": "2026-10-23"
}
+2 -1
View File
@@ -30,7 +30,8 @@ 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
python3 /usr/local/libexec/platina-image-runtime audit
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord; do
test -L "/etc/runlevels/default/$service"
done
for key in /etc/ssh/ssh_host_*_key; do
+5 -9
View File
@@ -43,14 +43,10 @@ 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
# The versioned runtime overlay supplies the complete display hook and screens.
test -x /etc/local.d/platina-headless.start
test -x /usr/local/libexec/platina-image-runtime
python3 /usr/local/libexec/platina-image-runtime audit
# 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
@@ -59,7 +55,7 @@ for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos-
set -- "$@" "$package=$version"
done
apk add --no-network "$@"
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon; do
for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord; do
rc-update add "$service" default
done
printf 'Image configured for SSH keys and passwordless sudo for the dedicated administrator.\n'
+19 -2
View File
@@ -6,6 +6,7 @@ import hashlib
import json
from pathlib import Path
import re
import runpy
import struct
import subprocess
@@ -48,10 +49,12 @@ def main():
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):
def root_blob(path):
return subprocess.check_output(['debugfs', '-R', 'cat ' + path,
str(OUT / 'xiaomi-platina.img')],
stderr=subprocess.DEVNULL, text=True)
stderr=subprocess.DEVNULL)
def root_file(path):
return root_blob(path).decode()
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',
@@ -82,11 +85,25 @@ def main():
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)
runtime_info = None
build_manifest = json.loads((OUT / 'manifest.json').read_text())
if 'integration' in build_manifest:
runtime = runpy.run_path(str(ROOT / 'scripts/image-runtime.py'))
runtime_manifest = json.loads(root_file('/' + runtime['MANIFEST']))
runtime_info = runtime['audit_contents'](runtime_manifest, lambda name: root_blob('/' + name))
assert runtime_info == build_manifest['integration'], 'Rootfs runtime differs from build manifest'
for name, target in runtime_manifest['symlinks'].items():
details = subprocess.check_output(['debugfs', '-R', 'stat /' + name,
str(OUT / 'xiaomi-platina.img')],
stderr=subprocess.DEVNULL, text=True)
assert 'Type: symlink' in details and f'Fast link dest: "{target}"' in details, name
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()}
if runtime_info:
report['integration'] = runtime_info
(ROOT / 'reports' / (OUT.name + '-artifact-audit.json')).write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
+36 -6
View File
@@ -7,8 +7,11 @@ import hashlib
import json
from pathlib import Path
import re
import runpy
import shutil
import subprocess
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parents[1]
WORK = ROOT / 'work/pmbootstrap-candidate-7.2'
@@ -34,12 +37,14 @@ def provenance(config_path, config):
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)
runtime = runpy.run_path(str(ROOT / 'scripts/image-runtime.py'))
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}
'recipe_inputs_sha256': inputs,
'runtime_inputs_sha256': runtime['source_inputs']()}
def record(phase, **details):
@@ -95,6 +100,10 @@ def main():
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')
record('preparing-image-runtime')
runtime = runpy.run_path(str(ROOT / 'scripts/image-runtime.py'))
overlay = WORK / ('runtime-' + args.output_name)
runtime_info = runtime['prepare'](overlay)
if args.resume_image:
assert (WORK / 'chroot_native/home/pmos/rootfs/xiaomi-platina.img').is_file()
else:
@@ -106,6 +115,16 @@ def main():
run('install', '--single-partition', '--no-sparse', '--no-recommends',
'--password', 'locked-before-export',
'--add', 'python3,iw,iperf3,mmc-utils,avahi-tools')
record('installing-image-runtime', **runtime_info)
# Only generated, reviewed runtime files enter this newly built image.
# No live device, private config or PMIC experiment is part of this overlay.
with tempfile.TemporaryFile() as archive:
with tarfile.open(fileobj=archive, mode='w') as stream:
for path in sorted(overlay.rglob('*')):
stream.add(path, arcname=str(path.relative_to(overlay)), recursive=False)
archive.seek(0)
subprocess.run(PMB + ['chroot', '--image', '--', 'tar', '-xf', '-', '-C', '/',
'--no-same-owner'], cwd=ROOT, stdin=archive, check=True)
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.
@@ -119,24 +138,35 @@ def main():
# 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})
record('scoping-exported-initramfs')
scope = runpy.run_path(str(ROOT / 'scripts/scope-initramfs-modules.py'))['scope']
boot, ramdisk, module_count = scope((OUTPUT / 'boot.img').read_bytes(), KERNEL_RELEASE)
(OUTPUT / 'boot.img').write_bytes(boot)
(OUTPUT / 'initramfs').write_bytes(ramdisk)
files = []
for target in sorted(OUTPUT.rglob('*')):
if target.is_file():
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,
'integration': runtime_info,
'module_indexes_scoped': True, 'initramfs_modules': module_count,
'flashed': False, 'files': files}
(OUTPUT / 'manifest.json').write_text(json.dumps(manifest, indent=2) + '\n')
subprocess.run(['python3', str(ROOT / 'scripts/audit-candidate-artifacts.py'),
'--directory', str(OUTPUT)], cwd=ROOT, check=True)
record('exported-offline-audit-passed-hardware-test-pending', files=len(files))
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Prepare or audit the runtime overlay for a new offline Platina image."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import re
import runpy
import shutil
import stat
import tempfile
ROOT = Path(__file__).resolve().parents[1]
MANIFEST = 'usr/local/share/platina/image-runtime.json'
HELPERS = {
'scripts/phone-splash.py': 'usr/local/sbin/platina-splash',
'scripts/phone-display.py': 'usr/local/sbin/platina-display',
'scripts/phone-display-session.py': 'usr/local/sbin/platina-display-session',
'scripts/phone-poweroff.py': 'usr/local/sbin/platina-poweroff',
'scripts/phone-power-chord.py': 'usr/local/sbin/platina-power-chord',
'scripts/phone-power-chord.openrc': 'etc/init.d/platina-power-chord',
'scripts/phone-headless.start': 'etc/local.d/platina-headless.start',
'scripts/phone-usb-power.py': 'usr/local/sbin/platina-usb-power',
'scripts/phone-usb-power-dispatcher.sh': 'etc/NetworkManager/dispatcher.d/90-platina-usb-power',
'scripts/image-runtime.py': 'usr/local/libexec/platina-image-runtime',
}
CONFIG = 'etc/conf.d/platina-power-chord'
def layout(version):
if not re.fullmatch(r'(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)', version):
raise ValueError('Invalid runtime release')
base = 'usr/local/share/platina/releases/' + version
modes = {name: 0o755 for name in HELPERS.values()}
modes[CONFIG] = 0o644
for sub in ('', 'poweroff/'):
for name in ('release.json', 'version', 'frame.bgrx.gz'):
modes[base + '/' + sub + name] = 0o644
links = {'usr/local/share/platina/current': 'releases/' + version,
'etc/platina-release': '../usr/local/share/platina/current/version',
'etc/runlevels/default/platina-power-chord': '../../init.d/platina-power-chord'}
return base, modes, links
def source_inputs():
names = list(HELPERS) + ['scripts/phone-power-chord.conf',
'scripts/platina-release.py', 'project/release.json',
'project/branding/platina-linux-logo.png',
'project/branding/provenance.json']
return {n: hashlib.sha256((ROOT / n).read_bytes()).hexdigest() for n in names}
def audit_contents(manifest, read):
"""Also used against the exported ext4 image, with a read-only debugfs reader."""
if manifest.get('schema') != 1 or manifest.get('name') != 'Platina Linux image runtime':
raise ValueError('Unknown image runtime manifest')
version = manifest['version']
base, modes, links = layout(version)
if set(manifest['files']) != set(modes) or manifest['symlinks'] != links:
raise ValueError('Image runtime file set differs from the supported layout')
payload = {}
for name, mode in modes.items():
data = read(name)
row = manifest['files'][name]
if row['mode'] != mode or row['bytes'] != len(data) or row['sha256'] != hashlib.sha256(data).hexdigest():
raise ValueError('Image runtime checksum/metadata mismatch: ' + name)
payload[name] = data
if b'hold_seconds=3\n' not in payload[CONFIG] or b'dry_run=no\n' not in payload[CONFIG]:
raise ValueError('Shutdown chord must use the verified active policy')
for sub in ('', 'poweroff/'):
prefix = base + '/' + sub
release = json.loads(payload[prefix + 'release.json'])
if release['name'] != 'Platina Linux' or release['version'] != version:
raise ValueError('Runtime and screen release differ')
if payload[prefix + 'version'] != ('Platina Linux ' + version + '\n').encode():
raise ValueError('Screen version file differs')
display = release['display']
if (display['width'], display['height'], display['format'], display['raw_bytes'], display['frame']) != (
1080, 2280, 'BGRX8888', 1080 * 2280 * 4, 'frame.bgrx.gz'):
raise ValueError('Unsupported image screen layout')
compressed = payload[prefix + 'frame.bgrx.gz']
if hashlib.sha256(compressed).hexdigest() != display['compressed_sha256']:
raise ValueError('Screen compressed checksum mismatch')
with gzip.GzipFile(fileobj=io.BytesIO(compressed)) as stream:
raw = stream.read(display['raw_bytes'] + 1)
if len(raw) != display['raw_bytes'] or hashlib.sha256(raw).hexdigest() != display['raw_sha256']:
raise ValueError('Screen decoded checksum mismatch')
return {'version': version, 'runtime_files': len(modes), 'screens_verified': 2,
'power_chord_active': True, 'usb_poweroff_requires_unplug': True}
def audit(root):
root = root.resolve()
manifest = json.loads((root / MANIFEST).read_text())
result = audit_contents(manifest, lambda n: (root / n).read_bytes())
_, modes, links = layout(manifest['version'])
for name, mode in modes.items():
path = root / name
if path.is_symlink() or stat.S_IMODE(path.stat().st_mode) != mode:
raise ValueError('Runtime file mode/type mismatch: ' + name)
if not path.resolve().is_relative_to(root):
raise ValueError('Runtime file escapes image root')
for name, target in links.items():
path = root / name
if not path.is_symlink() or str(path.readlink()) != target or not path.exists():
raise ValueError('Runtime symlink mismatch: ' + name)
return result
def prepare(output):
if output.exists():
raise ValueError('Preserve existing runtime overlay; choose a new directory')
before = source_inputs()
release = runpy.run_path(str(ROOT / 'scripts/platina-release.py'))
version = release['load_release']()['version']
base, modes, links = layout(version)
output.parent.mkdir(parents=True, exist_ok=True)
# Build completely in a private sibling directory before publishing the overlay.
with tempfile.TemporaryDirectory(prefix='.platina-runtime-', dir=output.parent) as temporary:
stage = Path(temporary) / 'rootfs'
stage.mkdir()
screens = Path(temporary) / 'screens'
release['build'](screens)
for source, target in HELPERS.items():
dest = stage / target
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / source, dest)
conf = (ROOT / 'scripts/phone-power-chord.conf').read_bytes()
if conf.count(b'dry_run=yes\n') != 1:
raise ValueError('Manual deployment config changed; review image activation')
dest = stage / CONFIG
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(conf.replace(b'dry_run=yes\n', b'dry_run=no\n'))
for sub in ('', 'poweroff/'):
for name in ('release.json', 'version', 'frame.bgrx.gz'):
dest = stage / base / sub / name
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(screens / sub / name, dest)
for name, mode in modes.items():
(stage / name).chmod(mode)
for name, target in links.items():
dest = stage / name
dest.parent.mkdir(parents=True, exist_ok=True)
dest.symlink_to(target)
for directory in stage.rglob('*'):
if directory.is_dir() and not directory.is_symlink():
directory.chmod(0o755)
manifest = {'schema': 1, 'name': 'Platina Linux image runtime', 'version': version,
'source_inputs_sha256': before, 'symlinks': links,
'files': {name: {'mode': mode, 'bytes': (stage / name).stat().st_size,
'sha256': hashlib.sha256((stage / name).read_bytes()).hexdigest()}
for name, mode in modes.items()}}
(stage / MANIFEST).write_text(json.dumps(manifest, indent=2) + '\n')
(stage / MANIFEST).chmod(0o644)
result = audit(stage)
if source_inputs() != before:
raise ValueError('Runtime sources changed during asset generation')
stage.rename(output)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
build = sub.add_parser('prepare', help='Build local rootfs overlay; never deploy')
build.add_argument('--output', type=Path, required=True)
check = sub.add_parser('audit', help='Verify installed files without accessing hardware')
check.add_argument('--root', type=Path, default=Path('/'))
args = parser.parse_args()
print(json.dumps(prepare(args.output.resolve()) if args.command == 'prepare' else audit(args.root)))
if __name__ == '__main__':
main()
+3 -1
View File
@@ -79,7 +79,7 @@ def device():
os.close(fb)
def show(fb, directory, seconds, percent, boot=False):
def show(fb, directory, seconds, percent, boot=False, after_display=None):
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()
@@ -105,6 +105,8 @@ def show(fb, directory, seconds, percent, boot=False):
print(json.dumps({'framebuffer_written': manifest['version'], 'seconds': seconds,
'backend': 'integrated-tianma'}), flush=True)
time.sleep(seconds)
if after_display is not None:
after_display()
brightness(0)
screen[:] = b'\0' * layout[4]
if boot:
+4
View File
@@ -0,0 +1,4 @@
# Physical Power + Volume Up only. PMIC emergency reset remains unchanged.
hold_seconds=3
# Start in observation mode until the physical gesture has been checked.
dry_run=yes
+24
View File
@@ -0,0 +1,24 @@
#!/sbin/openrc-run
description="Platina Power + Volume Up: hold together, release both to shut down"
command="/usr/local/sbin/platina-power-chord"
command_user="root:root"
command_args="--hold-seconds ${hold_seconds:-3}"
supervisor="supervise-daemon"
pidfile="/run/platina-power-chord.pid"
respawn_delay=5
respawn_max=5
respawn_period=1800
output_log="/var/log/platina-power-chord.log"
error_log="/var/log/platina-power-chord.log"
depend() {
need localmount
after udev-trigger
}
start_pre() {
checkpath --file --mode 0640 --owner root:root "$output_log"
if yesno "${dry_run:-yes}"; then
command_args="$command_args --dry-run"
fi
}
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Power + Volume Up, held together and fully released, requests orderly shutdown."""
import argparse
import fcntl
import os
from pathlib import Path
import select
import signal
import stat
import struct
import subprocess
import sys
KEY_POWER, KEY_VOLUMEUP = 116, 115
KEYS = {KEY_POWER, KEY_VOLUMEUP}
DEVICES = {KEY_POWER: 'pm8941_pwrkey', KEY_VOLUMEUP: 'Volume up'}
EVENT = struct.Struct('@llHHi')
class ChordPolicy:
def __init__(self, seconds=3, held=()):
if not 1 <= seconds <= 5:
raise ValueError('Choose a hold of 1 to 5 seconds, below the PMIC emergency reset')
self.seconds = seconds
self.last = None
self.resync(held)
def resync(self, held):
self.pressed = set(held) & KEYS
self.blocked = bool(self.pressed)
self.started = None
self.qualified = False
def event(self, key, value, timestamp):
if key not in KEYS or value not in (0, 1):
return None
if self.last is not None and timestamp < self.last:
self.resync(self.pressed | {key})
self.last = timestamp
if value == 1:
if key in self.pressed:
return None
if self.qualified: # A re-press before both releases cancels the gesture.
self.blocked, self.qualified = True, False
self.pressed.add(key)
if self.pressed == KEYS and not self.blocked:
self.started = timestamp
return None
if key not in self.pressed:
return None
if self.started is not None:
self.qualified = not self.blocked and timestamp - self.started >= self.seconds
self.started = None
self.pressed.remove(key)
if not self.pressed:
action = 'poweroff' if self.qualified and not self.blocked else None
self.resync(())
return action
return None
def find_devices(sys_input=Path('/sys/class/input'), dev_input=Path('/dev/input')):
result = {}
for key, name in DEVICES.items():
matches = []
for entry in sys_input.glob('event*'):
try:
if (entry / 'device/name').read_text().strip() == name:
matches.append(dev_input / entry.name)
except OSError:
continue
if len(matches) != 1:
raise ValueError('Expected exactly one physical input: ' + name)
result[key] = matches[0]
return result
def key_held(fd, key):
bits = bytearray(96)
fcntl.ioctl(fd, 0x80004518 | (len(bits) << 16), bits, True)
return bool(bits[key // 8] & (1 << (key % 8)))
def log(message):
print('platina-power-chord:', message, flush=True)
def dispatch(dry_run):
if dry_run:
log('TEST ONLY: Power + Volume Up accepted; would show Power off and shut down')
return
# A separate session keeps the renderer alive while OpenRC stops this monitor.
child = subprocess.Popen(['/usr/local/sbin/platina-poweroff'], start_new_session=True)
code = child.wait()
if code:
raise RuntimeError('Shutdown helper failed; exit ' + str(code))
def monitor(seconds, dry_run):
if os.geteuid() != 0:
raise ValueError('Run on the phone as root')
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('This service requires Platina')
descriptors, dropped = {}, set()
try:
for key, device in find_devices().items():
fd = os.open(device, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
descriptors[fd] = key
if not stat.S_ISCHR(os.fstat(fd).st_mode):
raise ValueError('Input is not a character device')
name = bytearray(128)
fcntl.ioctl(fd, 0x80004506 | (len(name) << 16), name, True)
if bytes(name).split(b'\0')[0].decode() != DEVICES[key]:
raise ValueError('Input identity changed')
fcntl.ioctl(fd, 0x400445A0, struct.pack('i', 1)) # Monotonic timestamps.
fcntl.ioctl(fd, 0x40044590, 1) # EVIOCGRAB; no console actions.
def held():
return {key for fd, key in descriptors.items() if key_held(fd, key)}
policy = ChordPolicy(seconds, held())
log(('TEST ONLY' if dry_run else 'ACTIVE') + f'; hold both >= {seconds:g}s; release BOTH to power off')
while True:
ready, _, _ = select.select(list(descriptors), [], [])
events = []
for fd in ready:
data = os.read(fd, EVENT.size * 64)
if not data or len(data) % EVENT.size:
raise ValueError('Disconnected or truncated input')
for offset in range(0, len(data), EVENT.size):
sec, usec, typ, code, value = EVENT.unpack_from(data, offset)
events.append((sec + usec / 1e6, fd, typ, code, value))
for timestamp, fd, typ, code, value in sorted(events):
if typ == 0 and code == 3: # SYN_DROPPED: cancel both keys.
dropped.add(fd)
policy.resync(KEYS)
log('lost input events; pending chord cancelled')
elif typ == 0 and code == 0 and fd in dropped:
dropped.remove(fd)
policy.resync(held())
elif typ == 1 and code == descriptors[fd] and not dropped:
action = policy.event(code, value, timestamp)
if value in (0, 1):
log(DEVICES[code] + (' pressed' if value else ' released'))
if action:
log('complete chord accepted')
dispatch(dry_run)
finally:
for fd in descriptors:
os.close(fd)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--hold-seconds', type=float, default=3)
parser.add_argument('--dry-run', action='store_true')
args = parser.parse_args()
ChordPolicy(args.hold_seconds)
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
monitor(args.hold_seconds, args.dry_run)
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, RuntimeError) as error:
log(str(error))
raise SystemExit(1)
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Show the verified Power off screen, then request an orderly init shutdown."""
import argparse
import fcntl
import os
from pathlib import Path
import runpy
import signal
import subprocess
import sys
import time
def request_shutdown():
subprocess.run(['/usr/sbin/poweroff'], check=True, timeout=10)
print('platina-poweroff: init accepted shutdown; keeping screen until shutdown', flush=True)
# Shutdown should terminate this process. If it does not, restore the display
# instead of leaving an indefinite claim that the phone is already off.
time.sleep(30)
raise RuntimeError('Shutdown did not finish within 30 seconds')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--preview', action='store_true', help='Show the screen for 5s without shutting down')
args = parser.parse_args()
if os.geteuid() != 0:
raise ValueError('Run on the phone as root')
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
control = runpy.run_path('/usr/local/sbin/platina-display', run_name='poweroff_display')
directory = Path('/usr/local/share/platina/current/poweroff')
with Path('/run/platina-poweroff.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
with control['device']() as fb:
control['show'](fb, directory, 5 if args.preview else 3, 25,
after_display=None if args.preview else request_shutdown)
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
print('platina-poweroff:', error, file=sys.stderr)
raise SystemExit(1)
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# NetworkManager dispatcher on the phone. No routes or network settings changed.
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH
case "${1:-}:${2:-}" in
usb0:up|usb0:dhcp4-change|usb0:reapply)
umask 077
{ date -u '+%Y-%m-%dT%H:%M:%SZ'; /usr/local/sbin/platina-usb-power; } > /run/platina-usb-power-last 2>&1
;;
esac
exit 0
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Apply an explicitly configured phone SDP limit only for a pinned USB host.
Install on the phone, not on either server. Unconfigured systems are unchanged.
The RPi hardware budget must be rechecked when its USB devices/PSU change.
"""
import json
import os
from pathlib import Path
import subprocess
CONFIG = Path('/etc/platina/usb-power.json')
SUPPLY = Path('/sys/class/power_supply/pm660-charger')
def apply(config, supply=SUPPLY, run=subprocess.run):
if (supply / 'online').read_text().strip() != '1':
return 'offline; unchanged'
if '[SDP]' not in (supply / 'usb_type').read_text():
return 'non-SDP supply; automatic charger policy unchanged'
requested = config['max_current_uA']
if requested not in (500000, 750000, 900000):
raise ValueError('Unsupported SDP current limit')
expected = config['rpi_host_ed25519'].split()
if len(expected) < 2 or expected[0] != 'ssh-ed25519':
raise ValueError('Invalid pinned host key')
if config['other_usb_max_mA'] + requested // 1000 > config['rpi_usb_budget_mA']:
raise ValueError('Configured RPi USB budget exceeded')
route = run(['ip', 'route', 'get', '172.16.42.2'], capture_output=True, text=True, timeout=3)
direct_usb = route.returncode == 0 and 'dev usb0' in route.stdout.splitlines()[0]
matched = False
if direct_usb:
scan = run(['ssh-keyscan', '-4', '-T', '2', '-t', 'ed25519', '172.16.42.2'],
capture_output=True, text=True, timeout=4)
for line in scan.stdout.splitlines():
fields = line.split()
if len(fields) >= 3 and fields[1:3] == expected[:2]:
matched = True
break
# An unknown USB host gets the standard limit, never the RPi exception.
target = requested if matched else 500000
(supply / 'current_max').write_text(str(target) + '\n')
return ('pinned RPi' if matched else 'unverified host') + ': SDP limit requested ' + str(target) + ' uA'
def main():
if os.geteuid() != 0:
raise SystemExit('Run on the phone as root')
if not CONFIG.exists():
return
metadata = CONFIG.stat()
if metadata.st_uid != 0 or metadata.st_mode & 0o022:
raise SystemExit('Unsafe power policy ownership/permissions')
try:
print('platina-usb-power:', apply(json.loads(CONFIG.read_text())))
except (OSError, ValueError, KeyError, IndexError, subprocess.TimeoutExpired) as error:
# Do not expose host keys or command output in dispatcher logs.
try:
if '[SDP]' in (SUPPLY / 'usb_type').read_text():
(SUPPLY / 'current_max').write_text('500000\n')
except OSError:
pass
print('platina-usb-power: standard SDP limit retained;', type(error).__name__)
if __name__ == '__main__':
main()
+20
View File
@@ -76,6 +76,26 @@ def build(output, release=None):
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')
shutdown = screen.copy()
shutdown_draw = ImageDraw.Draw(shutdown)
for text, size, y, color in [('Power off', 76, 1670, '#d7e3eb'),
('Shutting down...', 38, 1790, '#91a8b6')]:
face = ImageFont.truetype(str(font_path), size)
bounds = shutdown_draw.textbbox((0, 0), text, font=face)
shutdown_draw.text(((width - bounds[2] + bounds[0]) // 2 - bounds[0], y),
text, font=face, fill=color)
poweroff = output / 'poweroff'
poweroff.mkdir()
shutdown.save(poweroff / 'preview.png')
shutdown_raw = shutdown.tobytes('raw', 'BGRX')
shutdown_frame = gzip.compress(shutdown_raw, compresslevel=9, mtime=0)
(poweroff / 'frame.bgrx.gz').write_bytes(shutdown_frame)
(poweroff / 'version').write_text(release['name'] + ' ' + release['version'] + '\n')
shutdown_manifest = dict(manifest, purpose='poweroff-screen', display=dict(
manifest['display'], seconds=3,
raw_sha256=hashlib.sha256(shutdown_raw).hexdigest(),
compressed_sha256=hashlib.sha256(shutdown_frame).hexdigest()))
(poweroff / 'release.json').write_text(json.dumps(shutdown_manifest, indent=2) + '\n')
print('Built locally:', output, '(not deployed)')
+25
View File
@@ -21,6 +21,31 @@ splash = load('display_splash', 'phone-splash.py')
class ControlTests(unittest.TestCase):
def test_shutdown_request_happens_after_visible_frame_and_before_cleanup(self):
events, screen = [], bytearray(b'....')
def paint(target, raw, layout):
target[:] = raw
events.append('paint')
def request():
self.assertEqual(screen, b'logo')
events.append('shutdown-request')
helper = {'load_frame': lambda _: ({'version': '0.3.0'}, b'logo'),
'geometry': lambda *_: (1, 1, 4, 0, 4), 'paint': paint}
with patch.object(control.runpy, 'run_path', return_value=helper), \
patch.object(control, 'Path') as path, \
patch.object(control.fcntl, 'ioctl'), \
patch.object(control.os, 'open', return_value=12), \
patch.object(control.os, 'close'), \
patch.object(control.mmap, 'mmap') as memory, \
patch.object(control, 'brightness'), \
patch.object(control, 'on', side_effect=lambda *_: events.append('visible')), \
patch.object(control.time, 'sleep', side_effect=lambda _: events.append('readable-delay')), \
patch.object(control, 'off', side_effect=lambda _: events.append('cleanup')):
path.return_value.read_text.return_value = 'boot-id'
memory.return_value.__enter__.return_value = screen
control.show(12, ROOT, 3, 25, after_display=request)
self.assertEqual(events, ['paint', 'visible', 'readable-delay', 'shutdown-request', 'cleanup'])
def test_powerdown_clears_backlight_before_drm(self):
events = MagicMock()
with patch.object(control, 'brightness', events.brightness), \
+83
View File
@@ -0,0 +1,83 @@
"""Exercise the actual image overlay and reject missing/corrupt runtime assets."""
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import shutil
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('image_runtime', ROOT / 'scripts/image-runtime.py')
runtime = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runtime)
class ImageRuntimeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
try:
import PIL
except ImportError:
raise unittest.SkipTest('Asset integration requires host Pillow')
cls.temp = tempfile.TemporaryDirectory()
cls.addClassCleanup(cls.temp.cleanup)
cls.overlay = Path(cls.temp.name) / 'overlay'
with contextlib.redirect_stdout(io.StringIO()):
cls.result = runtime.prepare(cls.overlay)
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / 'rootfs'
shutil.copytree(self.overlay, self.root, symlinks=True)
def test_complete_overlay_has_both_screens_and_active_shutdown(self):
self.assertEqual(runtime.audit(self.root), self.result)
self.assertEqual(self.result['screens_verified'], 2)
self.assertTrue((self.root / 'etc/runlevels/default/platina-power-chord').is_file())
self.assertIn('dry_run=no', (self.root / runtime.CONFIG).read_text())
self.assertEqual((self.root / 'etc/platina-release').read_text(),
'Platina Linux ' + self.result['version'] + '\n')
files = {str(p.relative_to(self.root)) for p in self.root.rglob('*') if p.is_file()}
self.assertFalse(any('usb-off' in name or name.endswith('.ko') for name in files))
self.assertTrue((self.root / 'etc/NetworkManager/dispatcher.d/90-platina-usb-power').is_file())
self.assertFalse((self.root / 'etc/platina/usb-power.json').exists())
def test_missing_shutdown_helper_is_rejected(self):
(self.root / 'usr/local/sbin/platina-poweroff').unlink()
with self.assertRaises(FileNotFoundError):
runtime.audit(self.root)
def test_corrupt_poweroff_frame_is_rejected(self):
frame = next(self.root.glob('usr/local/share/platina/releases/*/poweroff/frame.bgrx.gz'))
frame.write_bytes(b'corrupt')
with self.assertRaisesRegex(ValueError, 'checksum'):
runtime.audit(self.root)
def test_inactive_shutdown_or_bad_permissions_are_rejected(self):
(self.root / 'usr/local/sbin/platina-power-chord').chmod(0o644)
with self.assertRaisesRegex(ValueError, 'mode/type'):
runtime.audit(self.root)
def test_service_not_enabled_is_rejected(self):
(self.root / 'etc/runlevels/default/platina-power-chord').unlink()
with self.assertRaisesRegex(ValueError, 'symlink'):
runtime.audit(self.root)
def test_manifest_cannot_add_unrelated_or_traversing_files(self):
path = self.root / runtime.MANIFEST
manifest = json.loads(path.read_text())
manifest['files']['../../outside'] = {'mode': 0o644, 'bytes': 0, 'sha256': '0' * 64}
path.write_text(json.dumps(manifest))
with self.assertRaisesRegex(ValueError, 'file set'):
runtime.audit(self.root)
def test_prepare_refuses_existing_output(self):
with self.assertRaisesRegex(ValueError, 'Preserve'):
runtime.prepare(self.root)
if __name__ == '__main__':
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
"""Power policy tests use a temporary sysfs fixture and fake network commands."""
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import tempfile
import unittest
spec = importlib.util.spec_from_file_location('phone_power', Path(__file__).resolve().parents[1] / 'scripts/phone-usb-power.py')
policy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(policy)
class PowerPolicyTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.supply = Path(self.temp.name)
for name, value in [('online', '1'), ('usb_type', 'Unknown [SDP] DCP CDP'), ('current_max', '500000')]:
(self.supply / name).write_text(value)
self.config = {'max_current_uA': 900000, 'rpi_host_ed25519': 'ssh-ed25519 fixture-host-key',
'other_usb_max_mA': 598, 'rpi_usb_budget_mA': 1600}
self.calls = []
def runner(self, command, **kwargs):
self.calls.append(command)
if command[0] == 'ip':
return SimpleNamespace(returncode=0, stdout='172.16.42.2 dev usb0 src 172.16.42.1\n')
return SimpleNamespace(returncode=0, stdout='172.16.42.2 ssh-ed25519 fixture-host-key\n')
def test_verified_host_applies_configured_limit(self):
policy.apply(self.config, self.supply, self.runner)
self.assertEqual((self.supply / 'current_max').read_text(), '900000\n')
def test_different_host_restores_standard_limit(self):
self.config['rpi_host_ed25519'] = 'ssh-ed25519 another-host'
(self.supply / 'current_max').write_text('900000')
policy.apply(self.config, self.supply, self.runner)
self.assertEqual((self.supply / 'current_max').read_text(), '500000\n')
def test_wifi_route_cannot_authorize_rpi_exception(self):
def runner(command, **kwargs):
self.assertEqual(command[0], 'ip')
return SimpleNamespace(returncode=0, stdout='172.16.42.2 via 198.51.100.1 dev wlan0\n')
policy.apply(self.config, self.supply, runner)
self.assertEqual((self.supply / 'current_max').read_text(), '500000\n')
def test_dcp_keeps_automatic_policy(self):
(self.supply / 'usb_type').write_text('Unknown SDP [DCP] CDP')
(self.supply / 'current_max').write_text('1500000')
policy.apply(self.config, self.supply, self.runner)
self.assertEqual((self.supply / 'current_max').read_text(), '1500000')
self.assertEqual(self.calls, [])
def test_offline_keeps_policy(self):
(self.supply / 'online').write_text('0')
policy.apply(self.config, self.supply, self.runner)
self.assertEqual(self.calls, [])
def test_budget_overrun_refused_before_write(self):
self.config['other_usb_max_mA'] = 800
with self.assertRaisesRegex(ValueError, 'budget exceeded'):
policy.apply(self.config, self.supply, self.runner)
self.assertEqual((self.supply / 'current_max').read_text(), '500000')
def test_unreviewed_higher_limit_refused(self):
self.config['max_current_uA'] = 1500000
with self.assertRaisesRegex(ValueError, 'Unsupported'):
policy.apply(self.config, self.supply, self.runner)
if __name__ == '__main__':
unittest.main()
+108
View File
@@ -0,0 +1,108 @@
"""Verify physical chord decisions and shutdown dispatch without real device I/O."""
import importlib.util
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('power_chord', ROOT / 'scripts/phone-power-chord.py')
chord = importlib.util.module_from_spec(spec)
spec.loader.exec_module(chord)
P, U = chord.KEY_POWER, chord.KEY_VOLUMEUP
class ChordTests(unittest.TestCase):
def gesture(self, policy=None, order=(P, U), releases=(P, U), duration=3.2):
policy = policy or chord.ChordPolicy()
self.assertIsNone(policy.event(order[0], 1, 100))
self.assertIsNone(policy.event(order[1], 1, 100.1))
self.assertIsNone(policy.event(releases[0], 0, 100.1 + duration))
return policy.event(releases[1], 0, 100.2 + duration)
def test_both_press_and_release_orders_work_once(self):
for presses in ((P, U), (U, P)):
for releases in ((P, U), (U, P)):
self.assertEqual(self.gesture(order=presses, releases=releases), 'poweroff')
def test_single_keys_and_short_chord_do_nothing(self):
for key in (P, U):
policy = chord.ChordPolicy()
self.assertIsNone(policy.event(key, 1, 100))
self.assertIsNone(policy.event(key, 0, 106))
self.assertIsNone(self.gesture(duration=2.9))
def test_duration_starts_only_when_both_are_pressed(self):
p = chord.ChordPolicy()
p.event(U, 1, 100)
p.event(P, 1, 104)
self.assertIsNone(p.event(P, 0, 105))
self.assertIsNone(p.event(U, 0, 105.1))
def test_repeat_or_duplicate_press_does_not_change_hold(self):
p = chord.ChordPolicy()
p.event(P, 1, 100)
p.event(U, 1, 100.1)
p.event(P, 2, 102)
p.event(U, 1, 103)
self.assertIsNone(p.event(U, 0, 103.2))
self.assertEqual(p.event(P, 0, 103.3), 'poweroff')
def test_held_at_start_and_lost_events_cancel(self):
p = chord.ChordPolicy(held=(P, U))
self.assertIsNone(p.event(P, 0, 100))
self.assertIsNone(p.event(U, 0, 101))
p.event(P, 1, 200)
p.event(U, 1, 200.1)
self.assertIsNone(p.event(P, 0, 203.2))
self.assertEqual(p.event(U, 0, 203.3), 'poweroff')
p = chord.ChordPolicy()
p.event(P, 1, 100)
p.event(U, 1, 101)
p.resync((P, U))
self.assertIsNone(p.event(P, 0, 105))
self.assertIsNone(p.event(U, 0, 106))
def test_repress_before_both_released_cancels(self):
p = chord.ChordPolicy()
p.event(P, 1, 100)
p.event(U, 1, 100.1)
p.event(U, 0, 103.2)
p.event(U, 1, 103.3)
self.assertIsNone(p.event(P, 0, 107))
self.assertIsNone(p.event(U, 0, 108))
def test_backwards_clock_and_synthetic_press_cancel(self):
p = chord.ChordPolicy()
p.event(P, 1, 100)
p.event(U, 1, 101)
p.event(P, 0, 99)
self.assertIsNone(p.event(U, 0, 110))
p = chord.ChordPolicy()
p.event(P, 1, 100)
p.event(U, 1, 101)
p.event(U, 0, 101)
self.assertIsNone(p.event(P, 0, 105))
def test_dry_run_never_launches_helper(self):
with patch.object(chord.subprocess, 'Popen') as child:
chord.dispatch(True)
child.assert_not_called()
def test_dispatch_uses_only_screen_and_orderly_shutdown_helper(self):
with patch.object(chord.subprocess, 'Popen') as child:
child.return_value.wait.return_value = 0
chord.dispatch(False)
child.assert_called_once_with(['/usr/local/sbin/platina-poweroff'], start_new_session=True)
def test_device_identity_does_not_depend_on_event_number(self):
with tempfile.TemporaryDirectory() as temp:
base = Path(temp)
for n, name in ((7, 'pm8941_pwrkey'), (9, 'Volume up')):
(base / f'event{n}/device').mkdir(parents=True)
(base / f'event{n}/device/name').write_text(name)
self.assertEqual(chord.find_devices(base), {P: Path('/dev/input/event7'), U: Path('/dev/input/event9')})
if __name__ == '__main__':
unittest.main()
+56
View File
@@ -0,0 +1,56 @@
"""No power action is permitted in preview or before the shutdown frame is shown."""
from contextlib import contextmanager
import importlib.util
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('poweroff_screen', ROOT / 'scripts/phone-poweroff.py')
poweroff = importlib.util.module_from_spec(spec)
spec.loader.exec_module(poweroff)
class PoweroffTests(unittest.TestCase):
def test_orderly_command_and_bounded_failure_cleanup(self):
with patch.object(poweroff.subprocess, 'run') as run, patch.object(poweroff.time, 'sleep'):
with self.assertRaisesRegex(RuntimeError, 'did not finish'):
poweroff.request_shutdown()
run.assert_called_once_with(['/usr/sbin/poweroff'], check=True, timeout=10)
def test_preview_has_no_poweroff_callback(self):
@contextmanager
def device():
yield 12
show = Mock()
with tempfile.TemporaryDirectory() as temp, \
patch.object(poweroff.sys, 'argv', ['platina-poweroff', '--preview']), \
patch.object(poweroff.os, 'geteuid', return_value=0), \
patch.object(poweroff.signal, 'signal'), \
patch.object(poweroff.runpy, 'run_path', return_value={'device': device, 'show': show}), \
patch.object(poweroff, 'Path', side_effect=lambda _: Path(temp) / 'lock'), \
patch.object(poweroff.subprocess, 'run') as command:
poweroff.main()
self.assertIsNone(show.call_args.kwargs['after_display'])
command.assert_not_called()
def test_display_failure_cannot_request_shutdown(self):
@contextmanager
def device():
raise ValueError('panel missing')
yield
with tempfile.TemporaryDirectory() as temp, \
patch.object(poweroff.sys, 'argv', ['platina-poweroff']), \
patch.object(poweroff.os, 'geteuid', return_value=0), \
patch.object(poweroff.signal, 'signal'), \
patch.object(poweroff.runpy, 'run_path', return_value={'device': device, 'show': Mock()}), \
patch.object(poweroff, 'Path', side_effect=lambda _: Path(temp) / 'lock'), \
patch.object(poweroff.subprocess, 'run') as command:
with self.assertRaisesRegex(ValueError, 'panel missing'):
poweroff.main()
command.assert_not_called()
if __name__ == '__main__':
unittest.main()
+15
View File
@@ -92,6 +92,21 @@ class FramebufferTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'checksum'):
splash.load_frame(root)
def test_generated_poweroff_frame_is_separate_and_checksum_valid(self):
try:
import PIL
except ImportError:
self.skipTest('Host-only asset builder needs Pillow')
with tempfile.TemporaryDirectory() as temp:
directory = Path(temp) / 'release'
release.build(directory)
boot, raw_boot = splash.load_frame(directory)
shutdown, raw_shutdown = splash.load_frame(directory / 'poweroff')
self.assertEqual(shutdown['purpose'], 'poweroff-screen')
self.assertEqual(shutdown['version'], boot['version'])
self.assertEqual(len(raw_shutdown), len(raw_boot))
self.assertNotEqual(raw_shutdown, raw_boot)
if __name__ == '__main__':
unittest.main()