Integrate boot and shutdown runtime into new images
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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)')
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user