Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(os): factory reset from the power button, through a recovery partition (#2349)

Bubu-Dudu-52hz6c9ff1778ffd
diff --git a/os/button.py b/os/button.py
new file mode 100644
index 000000000..94b314c88
--- /dev/null
+++ b/os/button.py
@@ -0,0 +1,315 @@
+#!/usr/bin/env python3
+"""A factory reset from the power button, for a computer with no screen or keyboard.
+
+One press while the computer runs does nothing (logind.conf.d/20-harness-os.conf), so a touch by
+accident does not turn it off; it is turned off from a phone. Five presses in a row ask for a factory
+reset: the lights blink fast and a screen, if there is one, asks; one press more within CONFIRM
+seconds starts the computer in its recovery (setup.py recover), which installs it again as it came:
+everything of the person erased, a new disk key, the password 1234 — the same as a reset while its
+disk waits for its password (unlock/button). Nothing more and it stays as it was.
+Holding the button four seconds still forces the computer off: that is the hardware's.
+
+Presses are read beside logind, from every input device with KEY_POWER. Firmware reports a press,
+never how long it was held, and some reports one only once the button was held a moment (an MSI
+laptop: about a second), so presses are counted, never timed.
+"""
+import fcntl
+import os
+from pathlib import Path
+import pwd
+import select
+import signal
+import struct
+import subprocess
+import sys
+import threading
+import time
+
+INPUT = Path('/dev/input')
+LEDS = Path('/sys/class/leds')
+# The computer's own status lights, one /sys/class/leds name a line; without it, Caps Lock's.
+STATUS_LEDS = Path('/etc/harness-os/status-leds')
+SETUP = Path(__file__).with_name('setup.py')
+USER = 'me'
+EV_KEY = 1
+KEY_POWER = 116
+KEY_MAX = 0x2ff
+# struct input_event on a 64-bit kernel: the time, then type, code and value.
+EVENT = struct.Struct('llHHi')
+PRESSES = 5
+# A press further than this from the one before starts the count again.
+PRESS_GAP = 3
+# One press seen by two devices (ACPI's two power buttons, on some computers) is one press.
+SAME_PRESS = 0.15
+CONFIRM = 10
+# The presses of a person still pressing as it asks are not the answer.
+SETTLE = 1
+BLINK = 0.1
+# The console that asks while the session is locked, one with no getty; and the kernel's VT ioctls.
+CONSOLE = 9
+VT_GETSTATE = 0x5603
+VT_ACTIVATE = 0x5606
+
+
+def log(message):
+ print(f'harness-button: {message}', file=sys.stderr, flush=True)
+
+
+def has_power_key(fd):
+ """Whether an input device reports KEY_POWER (EVIOCGBIT for EV_KEY)."""
+ size = KEY_MAX // 8 + 1
+ request = (2 << 30) | (size << 16) | (ord('E') << 8) | (0x20 + EV_KEY)
+ try:
+ bits = fcntl.ioctl(fd, request, bytes(size))
+ except OSError:
+ return False
+ return bool(bits[KEY_POWER // 8] & (1 << KEY_POWER % 8))
+
+
+def power_buttons():
+ devices = []
+ for path in sorted(INPUT.glob('event*')):
+ try:
+ fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
+ except OSError:
+ continue
+ if has_power_key(fd):
+ devices.append(fd)
+ else:
+ os.close(fd)
+ return devices
+
+
+def presses(fd):
+ """The power-button presses waiting on [fd], as a count."""
+ count = 0
+ try:
+ data = os.read(fd, EVENT.size * 64)
+ except BlockingIOError:
+ return 0
+ for offset in range(0, len(data) - EVENT.size + 1, EVENT.size):
+ _, _, kind, code, value = EVENT.unpack_from(data, offset)
+ count += kind == EV_KEY and code == KEY_POWER and value == 1
+ return count
+
+
+class Count:
+ """The presses so far: `press` says 'ask' at the fifth in a row, 'reset' at one more after it asks."""
+
+ def __init__(self):
+ self.times = []
+ self.asked = None
+
+ def press(self, now):
+ if self.times and now - self.times[-1] < SAME_PRESS:
+ return None
+ if self.asked is not None:
+ if now - self.asked < SETTLE:
+ self.times.append(now)
+ return None
+ self.asked, self.times = None, []
+ return 'reset'
+ if self.times and now - self.times[-1] > PRESS_GAP:
+ self.times = []
+ self.times.append(now)
+ if len(self.times) < PRESSES:
+ return None
+ self.times, self.asked = [now], now
+ return 'ask'
+
+ def expired(self, now):
+ """Asked and not answered in time: back to nothing pressed."""
+ if self.asked is None or now - self.asked < CONFIRM:
+ return False
+ self.asked, self.times = None, []
+ return True
+
+
+class Lights:
+ """The status lights blinking fast, then as they were."""
+
+ def __init__(self):
+ self.stop = None
+
+ @staticmethod
+ def chosen():
+ try:
+ names = [line.strip() for line in STATUS_LEDS.read_text().splitlines() if line.strip()]
+ return [LEDS / name for name in names if (LEDS / name).is_dir()]
+ except OSError:
+ return sorted(LEDS.glob('*::capslock'))
+
+ def start(self):
+ if self.stop:
+ return
+ leds = []
+ for led in self.chosen():
+ try:
+ trigger = (led / 'trigger').read_text()
+ current = trigger.split('[', 1)[1].split(']', 1)[0] if '[' in trigger else 'none'
+ leds.append((led, current, (led / 'brightness').read_text().strip(),
+ (led / 'max_brightness').read_text().strip()))
+ (led / 'trigger').write_text('none')
+ except (OSError, IndexError):
+ continue
+ self.stop = threading.Event()
+ threading.Thread(target=self.blink, args=(leds, self.stop), daemon=True).start()
+
+ @staticmethod
+ def blink(leds, stop):
+ on = True
+ while not stop.wait(BLINK):
+ for led, _, _, brightest in leds:
+ try:
+ (led / 'brightness').write_text(brightest if on else '0')
+ except OSError:
+ pass
+ on = not on
+ for led, trigger, brightness, _ in leds:
+ try:
+ (led / 'brightness').write_text(brightness)
+ (led / 'trigger').write_text(trigger)
+ except OSError:
+ pass
+
+ def end(self):
+ if self.stop:
+ self.stop.set()
+ self.stop = None
+
+
+def locked(uid):
+ """Whether the person's session lock (gtklock) runs."""
+ for process in Path('/proc').glob('[0-9]*'):
+ try:
+ if (process / 'comm').read_text().strip() == 'gtklock' and process.stat().st_uid == uid:
+ return True
+ except OSError:
+ continue
+ return False
+
+
+class Screen:
+ """The question on the screen: in a window of the person's session, or, while the session is locked
+ (its lock covers every window) or there is none, on a console of its own, the screen switched to
+ it and back after."""
+
+ def __init__(self):
+ self.window = None
+ self.back = None
+
+ def ask(self):
+ try:
+ account = pwd.getpwnam(USER)
+ except KeyError:
+ self.console()
+ return
+ runtime = Path(f'/run/user/{account.pw_uid}')
+ display = next((path.name for path in sorted(runtime.glob('wayland-*')) if not path.name.endswith('.lock')), None)
+ # The marker of /usr/lib/harness-os/lock, there while the session is locked, or its gtklock.
+ if not display or (runtime / 'harness-os-locked').exists() or locked(account.pw_uid):
+ self.console()
+ return
+ environment = dict(HOME=account.pw_dir, USER=USER, LOGNAME=USER, PATH='/usr/bin', XDG_RUNTIME_DIR=str(runtime),
+ WAYLAND_DISPLAY=display)
+ try:
+ self.window = subprocess.Popen(
+ ['/usr/bin/runuser', '-u', USER, '--', '/usr/bin/foot', '--config=/usr/share/harness-os/foot.ini',
+ '--app-id=harness-reset', '--title=Factory reset', '--window-size-chars=76x6',
+ '/usr/bin/python3', str(Path(__file__).resolve()), 'ask'],
+ env=environment, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ except OSError as error:
+ log(f'could not ask on the screen ({error})')
+
+ def console(self):
+ try:
+ with open('/dev/tty0', 'wb', buffering=0) as switch, open(f'/dev/tty{CONSOLE}', 'w') as console:
+ active = struct.unpack('HHH', fcntl.ioctl(switch, VT_GETSTATE, bytes(6)))[0]
+ # Cleared, the cursor hidden.
+ console.write('\033[2J\033[H\033[?25l')
+ console.flush()
+ self.window = subprocess.Popen(['/usr/bin/python3', str(Path(__file__).resolve()), 'ask'],
+ stdout=console, stderr=subprocess.DEVNULL, start_new_session=True)
+ fcntl.ioctl(switch, VT_ACTIVATE, CONSOLE)
+ self.back = active
+ except OSError as error:
+ log(f'could not ask on the console ({error})')
+
+ def close(self):
+ if self.window and self.window.poll() is None:
+ try:
+ os.killpg(self.window.pid, signal.SIGTERM)
+ except OSError:
+ pass
+ self.window = None
+ if self.back:
+ try:
+ with open('/dev/tty0', 'wb', buffering=0) as switch:
+ fcntl.ioctl(switch, VT_ACTIVATE, self.back)
+ except OSError as error:
+ log(f'could not switch the screen back ({error})')
+ self.back = None
+
+
+def question():
+ """The window's text, counting down: shown by `button.py ask` inside foot. The same words as the
+ startup's while the disk is locked (the Plymouth theme's show_reset)."""
+ print('\n Factory reset? Press the power button once more to erase this computer.\n'
+ ' Do nothing to keep everything.\n')
+ for left in range(CONFIRM, 0, -1):
+ print(f'\r {left} seconds left ', end='', flush=True)
+ time.sleep(1)
+ print('\r Kept as it was. ', flush=True)
+ time.sleep(1)
+
+
+def reset():
+ """setup.py recover, the lights blinking meanwhile: the computer starts again in its recovery, and
+ comes back only if it could not."""
+ log('factory reset from the power button')
+ done = subprocess.run(['/usr/bin/python3', str(SETUP), 'recover'], capture_output=True, text=True)
+ if done.returncode:
+ log('the factory reset did not start: ' + (done.stderr.strip()[-300:] or 'setup.py failed'))
+
+
+def listen(devices):
+ count, lights, screen = Count(), Lights(), Screen()
+ while True:
+ ready, _, _ = select.select(devices, [], [], 1)
+ now = time.monotonic()
+ for fd in ready:
+ for _ in range(presses(fd)):
+ answer = count.press(now)
+ if answer == 'ask':
+ log(f'{PRESSES} presses: asking for a factory reset')
+ lights.start()
+ screen.ask()
+ elif answer == 'reset':
+ screen.close()
+ reset()
+ lights.end()
+ # Whatever was pressed while it reset counts for nothing.
+ for device in devices:
+ presses(device)
+ count = Count()
+ break
+ if count.expired(time.monotonic()):
+ log('no answer: nothing reset')
+ screen.close()
+ lights.end()
+
+
+def main():
+ if sys.argv[1:] == ['ask']:
+ question()
+ return
+ devices = power_buttons()
+ if not devices:
+ log('no power button to listen to')
+ return
+ log(f'listening to {len(devices)} power button device(s)')
+ listen(devices)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/os/installer.py b/os/installer.py
index e7d37eb24..e1d2dde75 100644
--- a/os/installer.py
+++ b/os/installer.py
@@ -23,6 +23,17 @@ import time
MIN_DISK_BYTES = 12 * 1024**3
LIVE_PAYLOADS = (Path('/run/archiso/copytoram/airootfs.sfs'),
Path('/run/archiso/bootmnt/arch/x86_64/airootfs.sfs'))
+LIVE_MEDIUM = Path('/run/archiso/bootmnt')
+# The recovery: the USB's own system, kept at the end of the disk unencrypted, to install this computer
+# again as it came when its power button asks (button.py, unlock/button): everything erased, a new
+# disk key, and this password. Its GRUB entry (/etc/grub.d/42_harness-recovery) reads RECOVERY_CONF.
+RECOVERY_LABEL = 'HN_RECOVERY'
+RECOVERY_SIZE = '4GiB'
+RECOVERY_MIN_DISK_BYTES = 24 * 1024**3
+RECOVERY_ENTRY = 'harness-recovery'
+RECOVERY_PASSWORD = '1234'
+RECOVERY_CONF = '/etc/harness-os/recovery.conf'
+GRUBENV_HEADER = '# GRUB Environment Block\n# WARNING: Do not edit this file by tools other than grub-editenv!!!\n'
WORDMARK = ('█ █ ▄▀█ █▀█ █▄ █ █▀▀ █▀ █▀', '█▀█ █▀█ █▀▄ █ ▀█ ██▄ ▄█ ▄█')
COMMAND_LOG = None
INSTALL_LOG = Path('/var/log/harness-install.log')
@@ -162,6 +173,17 @@ def partitions(disk):
return [f'{disk}{separator}{n}' for n in (1, 2, 3)]
+def recovery_partition(disk):
+ """The fourth, after the root: the root keeps its number, which everything else names."""
+ return partitions(disk)[0][:-1] + '4'
+
+
+def grubenv(next_entry=None):
+ """GRUB's environment block: [next_entry] is started once, at the next start, then forgotten."""
+ text = GRUBENV_HEADER + (f'next_entry={next_entry}\n' if next_entry else '')
+ return text.encode().ljust(1024, b'#')
+
+
def validate_config(config):
if not isinstance(config, dict) or any(not isinstance(config.get(key), str) for key in ['username', 'hostname', 'password', 'disk']):
raise ValueError('Account, computer, password and disk fields must be text.')
@@ -182,12 +204,15 @@ def validate_config(config):
raise ValueError('Select a whole /dev disk.')
-def validate_disk(device, expected_serial=None):
+def validate_disk(device, expected_serial=None, recovery=False):
if device.get('type') != 'disk' or device.get('ro'):
raise ValueError('Target must be a writable whole disk.')
if int(device.get('size') or 0) < MIN_DISK_BYTES:
raise ValueError('The target needs at least 12 GiB.')
def mounted(node):
+ # The recovery installs from its own partition, which it keeps (install_image).
+ if recovery and node.get('label') == RECOVERY_LABEL:
+ return False
return any(node.get('mountpoints') or []) or any(mounted(c) for c in node.get('children', []))
if mounted(device):
raise ValueError('The disk has mounted filesystems. The live USB and active disks cannot be erased.')
@@ -220,7 +245,7 @@ def selected_disk(config):
devices = [d for d in inventory() if d['name'] == config['disk']]
if len(devices) != 1:
raise ValueError('Target disk was not found.')
- validate_disk(devices[0], config.get('expected_serial'))
+ validate_disk(devices[0], config.get('expected_serial'), recovery=config.get('recovery') is True)
return devices[0]
@@ -367,6 +392,69 @@ def copy_image(source, target, broadcom=Path('/usr/share/harness-os/hardware/bro
run('unsquashfs', '-mem', '64M', '-f', '-no-progress', '-excludes', '-d', target, source, *excluded)
+def recovery_files(kernel):
+ """What the recovery boots, as the USB keeps it: its kernel, its startup and its system."""
+ return [f'arch/boot/x86_64/vmlinuz-{kernel}', f'arch/boot/x86_64/initramfs-{kernel}.img',
+ 'arch/x86_64/airootfs.sfs']
+
+
+@contextmanager
+def live_medium(kernel):
+ """The Harness USB's files, for the recovery; None when they are not at hand (a --source install,
+ another platform's boot). Copied to RAM, the USB is no longer mounted: mounted again, read-only."""
+ if all((LIVE_MEDIUM / name).is_file() for name in recovery_files(kernel)):
+ yield LIVE_MEDIUM
+ return
+ def find(nodes):
+ for node in nodes:
+ if node.get('fstype') == 'iso9660' and node.get('label') == 'HN_OS':
+ return node['name']
+ found = find(node.get('children', []))
+ if found:
+ return found
+ return None
+ try:
+ device = find(inventory())
+ except (ValueError, subprocess.SubprocessError):
+ device = None
+ if not device:
+ yield None
+ return
+ with tempfile.TemporaryDirectory(prefix='harness-usb-') as folder:
+ try:
+ run('mount', '-o', 'ro', device, folder)
+ except subprocess.CalledProcessError:
+ yield None
+ return
+ try:
+ yield Path(folder) if all((Path(folder) / name).is_file() for name in recovery_files(kernel)) else None
+ finally:
+ run('umount', folder)
+
+
+def write_recovery(partition, medium, kernel):
+ """The recovery partition made anew, with the USB's files."""
+ run('mkfs.ext4', '-F', '-q', '-L', RECOVERY_LABEL, partition)
+ with tempfile.TemporaryDirectory(prefix='harness-recovery-') as folder:
+ run('mount', partition, folder)
+ try:
+ for name in recovery_files(kernel):
+ destination = Path(folder) / name
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(medium / name, destination)
+ run('sync')
+ finally:
+ run('umount', folder)
+
+
+def recovery_conf(uuid, kernel, parameters):
+ """For 42_harness-recovery, as shell assignments. archisolabel: the live system finds itself on the
+ recovery partition; copytoram=n keeps it there, mounted, rather than in RAM (validate_disk)."""
+ arguments = ' '.join(['archisobasedir=arch', f'archisolabel={RECOVERY_LABEL}', 'copytoram=n',
+ 'harness.recovery', 'quiet', *parameters])
+ return f"RECOVERY_UUID='{uuid}'\nRECOVERY_KERNEL='{kernel}'\nRECOVERY_PARAMETERS='{arguments}'\n"
+
+
def install(config, source, target, progress=None):
# All preserved platform data must outlive disk erasure and be released only
# after installation/cleanup completes. There is no user-supplied platform
@@ -394,24 +482,44 @@ def install_image(config, source, target, progress, resources):
if platform['id'] == 'apple-t2':
report('Preserving this Mac’s wireless firmware…')
preserved = resources.enter_context(boot_module().module('t2_install').preserve(config['disk']))
- trial = trial_source(config)
+ recovering = config.get('recovery') is True
+ trial = None if recovering else trial_source(config)
selected_disk(config)
pbkdf_memory = encryption_memory() if config['encrypt'] else None
started = time.monotonic()
disk = config['disk']
_, boot, root_partition = partitions(disk)
+ recovery = recovery_partition(disk)
+ # A PC's installation keeps a recovery when the USB's files are at hand and the disk has room beside
+ # the system; the recovery keeps its own.
+ roomy = int(selected_disk(config).get('size') or 0) >= RECOVERY_MIN_DISK_BYTES
+ medium = (resources.enter_context(live_medium(platform['kernel']))
+ if not recovering and platform['id'] == 'pc' and roomy else None)
target.mkdir(parents=True, exist_ok=True)
mapper = f'hn-install-{os.getpid()}'
opened = False
mounted = False
try:
report('Preparing the disk…')
- run('sgdisk', '--zap-all', disk)
- run('sgdisk', '-n', '1:1MiB:+2MiB', '-t', '1:ef02', '-c', '1:HN BIOS',
- '-n', '2:0:+1GiB', '-t', '2:ef00', '-c', '2:HN BOOT',
- '-n', '3:0:0', '-t', '3:8309' if config['encrypt'] else '3:8300', '-c', '3:HN ROOT', disk)
+ if recovering:
+ # The same partitions: the recovery's own stays, and so does GRUB on the boot partition
+ # until it is installed again, so a start cut short comes back here (recover).
+ run('wipefs', '-a', root_partition)
+ else:
+ run('sgdisk', '--zap-all', disk)
+ layout = ['-n', '1:1MiB:+2MiB', '-t', '1:ef02', '-c', '1:HN BIOS',
+ '-n', '2:0:+1GiB', '-t', '2:ef00', '-c', '2:HN BOOT',
+ '-n', '3:0:' + (f'-{RECOVERY_SIZE}' if medium else '0'),
+ '-t', '3:8309' if config['encrypt'] else '3:8300', '-c', '3:HN ROOT']
+ if medium:
+ layout += ['-n', '4:0:0', '-t', '4:8300', '-c', '4:HN RECOVERY']
+ run('sgdisk', *layout, disk)
run('udevadm', 'settle')
- run('mkfs.fat', '-F', '32', '-n', 'HNBOOT', boot)
+ if not recovering:
+ run('mkfs.fat', '-F', '32', '-n', 'HNBOOT', boot)
+ if medium:
+ report('Keeping a recovery…')
+ write_recovery(recovery, medium, platform['kernel'])
if preserved:
# Make the validated firmware discoverable on a retry/reinstall,
# before encryption or the larger root copy can fail.
@@ -466,7 +574,9 @@ def install_image(config, source, target, progress, resources):
# live account passwords, agent credentials, SSH keys and sessions stay out.
for path in ['etc/sudoers.d/10-live', 'etc/mkinitcpio.conf.d/archiso.conf',
'etc/systemd/system/[email protected]/live.conf',
- 'etc/pacman.d/hooks/99-harness-live.hook', 'root/setup-live.sh']:
+ 'etc/pacman.d/hooks/99-harness-live.hook', 'root/setup-live.sh',
+ 'etc/systemd/system/harness-recovery.service',
+ 'etc/systemd/system/multi-user.target.wants/harness-recovery.service']:
(target / path).unlink(missing_ok=True)
for path in ['etc/systemd/system/[email protected]', 'root/.ssh']:
shutil.rmtree(target / path, ignore_errors=True)
@@ -540,6 +650,10 @@ def install_image(config, source, target, progress, resources):
write(target, '/etc/default/grub',
'GRUB_DEFAULT=0\nGRUB_TIMEOUT=1\nGRUB_DISTRIBUTOR="Harness"\n'
'GRUB_DISABLE_OS_PROBER=true\n' + f'GRUB_CMDLINE_LINUX="{kernel_args}"\n')
+ recovery_uuid = None
+ if medium or recovering:
+ recovery_uuid = run('blkid', '-s', 'UUID', '-o', 'value', recovery, capture=True)
+ write(target, RECOVERY_CONF, recovery_conf(recovery_uuid, platform['kernel'], platform['parameters']))
lock = json.loads((target / 'usr/share/harness-os/lock.json').read_text())
snapshot = lock['arch_snapshot']
write(target, '/etc/pacman.conf',
@@ -550,7 +664,7 @@ def install_image(config, source, target, progress, resources):
if networks.exists():
shutil.copytree(networks, target / 'etc/NetworkManager/system-connections', dirs_exist_ok=True)
chroot(target, 'systemctl', 'enable', 'NetworkManager', 'systemd-resolved', 'systemd-timesyncd',
- 'harness-setup.service')
+ 'harness-setup.service', 'harness-button.service')
chroot(target, 'systemctl', 'disable', 'sshd.service')
# Its account's daemon from the start (the user lingers), not only with a session at the
# screen: a computer set up and unlocked from a phone may have no screen, or nobody at it.
@@ -569,7 +683,7 @@ def install_image(config, source, target, progress, resources):
receipt = {'version': lock['version'], 'installed_at': datetime.now(timezone.utc).isoformat(),
'duration_seconds': round(time.monotonic() - started, 3), 'encrypted': config['encrypt'],
'disk_bytes': selected_size(config), 'root_uuid': root_uuid, 'boot_uuid': boot_uuid,
- 'platform': platform['id']}
+ 'platform': platform['id'], 'recovery_uuid': recovery_uuid, 'from_recovery': recovering}
if apple_firmware:
receipt['apple_firmware'] = apple_firmware
if pbkdf_memory is not None:
@@ -910,12 +1024,49 @@ def arguments():
parser.add_argument('--yes-erase-disk', action='store_true')
parser.add_argument('--source', type=Path, help='Override the automatically detected live system image')
parser.add_argument('--boot', action='store_true', help=argparse.SUPPRESS)
+ parser.add_argument('--recover', action='store_true', help=argparse.SUPPRESS)
args = parser.parse_args()
if args.boot and (args.config or not Path('/etc/harness-live').is_file()):
parser.error('--boot is only for the interactive Harness USB installer.')
+ if args.recover and (args.config or not Path('/etc/harness-live').is_file()):
+ parser.error('--recover is only for the recovery partition (harness-recovery.service).')
return args
+def next_start(boot, entry):
+ """What GRUB starts next, once (grubenv on the boot partition): [entry], or the system."""
+ with tempfile.TemporaryDirectory(prefix='harness-boot-') as folder:
+ run('mount', boot, folder)
+ try:
+ env = Path(folder) / 'grub/grubenv'
+ if env.parent.is_dir():
+ env.write_bytes(grubenv(entry))
+ run('sync')
+ finally:
+ run('umount', folder)
+
+
+def recover():
+ """The recovery started (harness-recovery.service, at a power button's reset): this computer installed
+ again from it, on the disk it is on, as it came — encrypted with a new key and RECOVERY_PASSWORD,
+ nothing of the person kept — then started again. Its GRUB entry is asked for again first: a start cut
+ short (the power went) comes back here, not to a half-written system."""
+ partition = run('blkid', '-L', RECOVERY_LABEL, capture=True)
+ disk = '/dev/' + run('lsblk', '-no', 'PKNAME', partition, capture=True).splitlines()[0].strip()
+ if recovery_partition(disk) != partition:
+ raise ValueError(f'The recovery is not where it belongs on {disk}.')
+ device = next(d for d in inventory() if d['name'] == disk)
+ boot = partitions(disk)[1]
+ print('Resetting Harness to as it came. This takes a few minutes; do not turn it off.', flush=True)
+ next_start(boot, RECOVERY_ENTRY)
+ config = dict(username='me', hostname='harness', password=RECOVERY_PASSWORD, encrypt=True, disk=disk,
+ confirm_erase=disk, expected_serial=str(device.get('serial') or '').strip(), recovery=True)
+ install(config, live_payload(), Path('/mnt/harness-os'), progress=lambda message: print(message, flush=True))
+ next_start(boot, None)
+ print('Reset. Starting again…', flush=True)
+ run('systemctl', 'reboot')
+
+
def finish_installation(boot=False):
# A failed poweroff must return to success, never restart disk installation.
while curses.wrapper(lambda screen: completion(screen, boot=boot)):
@@ -937,6 +1088,9 @@ def main(args=None):
if os.geteuid() != 0:
raise SystemExit('Run sudo harness install from the live USB.')
require_install_platform()
+ if getattr(args, 'recover', False):
+ recover()
+ return
if args.config:
if args.username is not None or args.hostname is not None or args.no_encryption:
raise ValueError('With --config, set account names and encryption in that file instead of command-line overrides.')
diff --git a/os/live/etc/systemd/system/[email protected]/recovery.conf b/os/live/etc/systemd/system/[email protected]/recovery.conf
new file mode 100644
index 000000000..2f6165af1
--- /dev/null
+++ b/os/live/etc/systemd/system/[email protected]/recovery.conf
@@ -0,0 +1,3 @@
+# The recovery's screen is its progress (harness-recovery.service), not the USB's installer.
+[Service]
+ExecCondition=/bin/sh -c '! grep -qw harness.recovery /proc/cmdline'
diff --git a/os/live/etc/systemd/system/harness-recovery.service b/os/live/etc/systemd/system/harness-recovery.service
new file mode 100644
index 000000000..8c7029c44
--- /dev/null
+++ b/os/live/etc/systemd/system/harness-recovery.service
@@ -0,0 +1,18 @@
+[Unit]
+Description=Harness Recovery: this computer installed again as it came
+# Only when started from the recovery partition (installer.py recovery_conf), never from a USB.
+ConditionKernelCommandLine=harness.recovery
+After=local-fs.target
+
+[Service]
+Type=oneshot
+# Its progress shown, whatever console the startup left on the screen.
+ExecStartPre=-/usr/bin/chvt 1
+ExecStart=/usr/bin/python3 /usr/lib/harness-os/install.py --recover
+# The console, not tty1 itself: the startup's end (plymouth-quit, the gettys) hangs tty1 up, and a
+# hung-up terminal fails every later write, the installer's progress with it (exit 120).
+StandardOutput=journal+console
+StandardError=journal+console
+
+[Install]
+WantedBy=multi-user.target
diff --git a/os/live/etc/systemd/system/[email protected]/recovery.conf b/os/live/etc/systemd/system/[email protected]/recovery.conf
new file mode 100644
index 000000000..a1a02b58d
--- /dev/null
+++ b/os/live/etc/systemd/system/[email protected]/recovery.conf
@@ -0,0 +1,4 @@
+# Started from the recovery partition (harness.recovery), the live session stays off: its linger
+# would start labwc (hn-screen), which takes the screen from the recovery's progress on tty1.
+[Unit]
+ConditionKernelCommandLine=!harness.recovery
diff --git a/os/root/etc/grub.d/42_harness-recovery b/os/root/etc/grub.d/42_harness-recovery
new file mode 100755
index 000000000..c4d2ebb18
--- /dev/null
+++ b/os/root/etc/grub.d/42_harness-recovery
@@ -0,0 +1,17 @@
+#!/bin/sh
+# GRUB's entry for the recovery partition (installer.py RECOVERY_CONF), started only when asked for
+# once (grubenv next_entry, by a power button's reset): the USB's own system, which installs this
+# computer again as it came. Nothing on a computer installed without one.
+set -e
+conf=/etc/harness-os/recovery.conf
+[ -r "$conf" ] || exit 0
+. "$conf"
+cat <<EOF
+menuentry 'Harness Recovery' --id harness-recovery {
+ insmod part_gpt
+ insmod ext2
+ search --no-floppy --fs-uuid --set=root $RECOVERY_UUID
+ linux /arch/boot/x86_64/vmlinuz-$RECOVERY_KERNEL $RECOVERY_PARAMETERS
+ initrd /arch/boot/x86_64/initramfs-$RECOVERY_KERNEL.img
+}
+EOF
diff --git a/os/root/etc/pacman.d/hooks/46-harness-unlock-startup.hook b/os/root/etc/pacman.d/hooks/46-harness-unlock-startup.hook
new file mode 100644
index 000000000..6136f4933
--- /dev/null
+++ b/os/root/etc/pacman.d/hooks/46-harness-unlock-startup.hook
@@ -0,0 +1,14 @@
+[Trigger]
+Operation = Install
+Operation = Upgrade
+Type = Path
+Target = usr/lib/harness-os/unlock/*
+Target = usr/share/plymouth/themes/harness/*
+
+[Action]
+Description = Carrying the new unlock and power button into an encrypted computer's startup
+When = PostTransaction
+# The startup holds copies of these (initcpio/install/harness-unlock, the plymouth hook), which
+# mkinitcpio's own hook refreshes only for files under usr/lib/initcpio: an update that changes only
+# them would leave the old ones waiting for the password.
+Exec = /usr/bin/sh -c 'test -e /etc/harness-live || ! grep -Eq "^HOOKS=\(.*[ (]harness-unlock[ )]" /etc/mkinitcpio.conf || mkinitcpio -P'
diff --git a/os/root/etc/pacman.d/hooks/50-harness-button.hook b/os/root/etc/pacman.d/hooks/50-harness-button.hook
new file mode 100644
index 000000000..e3ab6c729
--- /dev/null
+++ b/os/root/etc/pacman.d/hooks/50-harness-button.hook
@@ -0,0 +1,12 @@
+[Trigger]
+Operation = Install
+Operation = Upgrade
+Type = Path
+Target = usr/lib/systemd/system/harness-button.service
+Target = usr/lib/systemd/logind.conf.d/20-harness-os.conf
+
+[Action]
+Description = Listening to the power button for a factory reset
+When = PostTransaction
+# logind reads its settings again on SIGHUP: one press stops turning the computer off at once.
+Exec = /usr/bin/sh -c 'test -e /etc/harness-live || { systemctl enable harness-button.service; systemctl restart harness-button.service; systemctl kill -s HUP systemd-logind.service; }'
diff --git a/os/root/usr/lib/harness-os/lock b/os/root/usr/lib/harness-os/lock
index 048550d27..46e4dadb2 100644
--- a/os/root/usr/lib/harness-os/lock
+++ b/os/root/usr/lib/harness-os/lock
@@ -7,7 +7,11 @@
# -d returns only once the compositor has acknowledged the lock, so swayidle's before-sleep waits
# for it, as it did for swaylock -f. The marker says the same to the session checks
# (tests/session_vm.py): gtklock, unlike swaylock, leaves no session leader to look for.
+#
+# Already locked (Super+L or the idle timeout, then the lid closed), it stays as it is: a second
+# gtklock is refused by the compositor and would only have removed the marker of the first.
marker=${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/harness-os-locked
+pgrep -x -u "$(id -u)" gtklock >/dev/null && exit 0
rm -f "$marker"
exec gtklock -d \
-s /usr/share/harness-os/lock/style.css \
diff --git a/os/root/usr/lib/harness-os/unlock/button b/os/root/usr/lib/harness-os/unlock/button
new file mode 100755
index 000000000..94e3f10e0
--- /dev/null
+++ b/os/root/usr/lib/harness-os/unlock/button
@@ -0,0 +1,193 @@
+#!/bin/sh
+# Runs in the computer's startup (initramfs) while the disk waits for its password, beside `run`: the
+# power button's factory reset (os/button.py, once the system runs), for a computer whose password
+# nobody has. Five presses in a row ask — the lights blink fast, the screen says so — and one press
+# more within ten seconds starts the computer in its recovery (installer.py recover), which installs it
+# again as it came: everything erased, a new disk key, the password 1234. Nothing more and it waits for
+# its password as before. A computer installed without a recovery has nothing to start: this rests.
+#
+# busybox sh: presses read with od from every input device with KEY_POWER, timed by /proc/uptime in
+# hundredths of a second; the recovery asked for in GRUB's environment block on the boot partition.
+#
+# button devices the input devices it listens to, one a line (for the tests)
+# button grubenv F writes F as GRUB's environment block, the recovery its next start (the tests)
+set -u
+STATE=${HARNESS_BUTTON_STATE:-/run/harness-button}
+DEVICES=${HARNESS_BUTTON_DEVICES:-/proc/bus/input/devices}
+INPUT=${HARNESS_BUTTON_INPUT:-/dev/input}
+RECOVERY=${HARNESS_BUTTON_RECOVERY:-/dev/disk/by-label/HN_RECOVERY}
+BOOT=${HARNESS_BUTTON_BOOT:-/dev/disk/by-label/HNBOOT}
+LEDS=/sys/class/leds
+ENTRY=harness-recovery
+PRESSES=5
+# In hundredths of a second, as button.py's: a pause that starts the count again, one press seen by
+# two devices, presses still coming as it asks, and how long it waits for the answer.
+GAP=300
+SAME=15
+SETTLE=100
+CONFIRM=1000
+
+log() { echo "harness-button: $*"; }
+
+# The handlers of every device whose key bits have KEY_POWER (116): bit 52 of the second word from the
+# right, the words being the kernel's 64-bit longs. Through cat: busybox's read, on the /proc file
+# itself, reads it again and again without end.
+devices() {
+ handlers=
+ cat "$DEVICES" | while read -r line; do
+ case $line in
+ 'H: Handlers='*) handlers=${line#*Handlers=} ;;
+ 'B: KEY='*)
+ set -- ${line#B: KEY=}
+ [ $# -ge 2 ] || continue
+ eval "word=\${$(($# - 1))}"
+ # Bit 52 is the lowest of the 14th hex digit from the right: that digit alone, as
+ # the whole word overflows a shell's signed arithmetic (dash saturates it).
+ [ ${#word} -ge 14 ] || continue
+ digit=${word%?????????????}
+ digit=${digit#"${digit%?}"}
+ [ $((0x$digit & 1)) -eq 1 ] || continue
+ for handler in $handlers; do
+ case $handler in event*) echo "$handler" ;; esac
+ done ;;
+ esac
+ done
+}
+
+grubenv() {
+ text="# GRUB Environment Block
+# WARNING: Do not edit this file by tools other than grub-editenv!!!
+next_entry=$ENTRY
+"
+ { printf '%s' "$text"; head -c $((1024 - ${#text})) /dev/zero | tr '\0' '#'; } > "$1"
+}
+
+case ${1:-} in
+ devices) devices; exit 0 ;;
+ grubenv) grubenv "$2"; exit 0 ;;
+esac
+
+rest() { while :; do sleep 3600; done; }
+
+now() {
+ up=$(cat /proc/uptime)
+ up=${up%% *}
+ echo $((${up%.*} * 100 + 1${up#*.} - 100))
+}
+
+blink() {
+ for led in "$LEDS"/*::capslock; do
+ [ -e "$led/brightness" ] && echo none > "$led/trigger" 2>/dev/null
+ done
+ on=1
+ while :; do
+ for led in "$LEDS"/*::capslock; do
+ [ -e "$led/brightness" ] || continue
+ if [ $on = 1 ]; then cat "$led/max_brightness" > "$led/brightness"; else echo 0 > "$led/brightness"; fi
+ done 2>/dev/null
+ on=$((1 - on))
+ sleep 0.1
+ done
+}
+
+say() { command -v plymouth >/dev/null 2>&1 && plymouth display-message --text="reset:$1" 2>/dev/null; }
+
+ask() {
+ log "$PRESSES presses: asking for a factory reset"
+ blink &
+ echo $! > "$STATE/blink.pid"
+ shown=$((CONFIRM / 100))
+ say "ask:$shown"
+}
+
+# The seconds left to answer, on the screen as they change.
+countdown() {
+ left=$(((CONFIRM - ($(now) - asked) + 99) / 100))
+ [ "$left" -lt 1 ] || [ "$left" = "$shown" ] && return
+ shown=$left
+ say "ask:$left"
+}
+
+keep() {
+ log 'no answer: nothing reset'
+ [ -f "$STATE/blink.pid" ] && kill "$(cat "$STATE/blink.pid")" 2>/dev/null
+ for led in "$LEDS"/*::capslock; do
+ [ -e "$led/brightness" ] && echo 0 > "$led/brightness" 2>/dev/null
+ done
+ say ''
+}
+
+reset() {
+ log 'factory reset: starting again in the recovery'
+ say now
+ mkdir -p "$STATE/boot"
+ if mount -t vfat "$BOOT" "$STATE/boot"; then
+ [ -d "$STATE/boot/grub" ] && grubenv "$STATE/boot/grub/grubenv"
+ umount "$STATE/boot"
+ sync
+ systemctl reboot
+ rest
+ fi
+ log 'the boot partition did not open: nothing reset'
+ keep
+}
+
+mkdir -p "$STATE"
+# The recovery's partition label appears once udev has seen the disk.
+for _ in $(seq 30); do
+ [ -e "$RECOVERY" ] && break
+ sleep 1
+done
+[ -e "$RECOVERY" ] || { log 'no recovery on this computer'; rest; }
+events=$(devices)
+[ -n "$events" ] || { log 'no power button to listen to'; rest; }
+
+rm -f "$STATE/presses"
+mkfifo "$STATE/presses"
+# Read and write: the readers below open it without waiting, and read never meets its end.
+exec 3<> "$STATE/presses"
+# One event (24 bytes) a time, the device opened once: od on the whole device keeps what it reads
+# until it has 4096 bytes for its pipe, some forty presses.
+for event in $events; do
+ while line=$(dd bs=24 count=1 2>/dev/null <&4 | od -An -tx1 -w24 -v); do
+ [ -n "$line" ] || break
+ set -- $line
+ # type EV_KEY (1), code KEY_POWER (0x74), value 1: pressed.
+ [ $# -ge 21 ] && [ "${17}${18}${19}${20}${21}" = 0100740001 ] && echo pressed
+ done 4< "$INPUT/$event" > "$STATE/presses" &
+done
+log "listening to $(echo $events | wc -w) power button device(s)"
+
+count=0
+last=-10000
+asked=
+while :; do
+ if read -r -t 1 _ <&3; then
+ at=$(now)
+ [ $((at - last)) -lt $SAME ] && continue
+ if [ -n "$asked" ]; then
+ last=$at
+ [ $((at - asked)) -lt $SETTLE ] && continue
+ reset
+ asked=
+ count=0
+ continue
+ fi
+ [ $((at - last)) -gt $GAP ] && count=0
+ last=$at
+ count=$((count + 1))
+ if [ $count -ge $PRESSES ]; then
+ asked=$at
+ count=0
+ ask
+ fi
+ else
+ if [ -n "$asked" ] && [ $(($(now) - asked)) -ge $CONFIRM ]; then
+ asked=
+ count=0
+ keep
+ elif [ -n "$asked" ]; then
+ countdown
+ fi
+ fi
+done
diff --git a/os/root/usr/lib/harness-os/unlock/harness-unlock-button.service b/os/root/usr/lib/harness-os/unlock/harness-unlock-button.service
new file mode 100644
index 000000000..147364874
--- /dev/null
+++ b/os/root/usr/lib/harness-os/unlock/harness-unlock-button.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=Factory reset from the power button while the disk waits for its password
+Documentation=file:///usr/lib/harness-os/unlock/button
+DefaultDependencies=no
+ConditionPathExists=/etc/initrd-release
+After=systemd-udev-trigger.service
+Wants=systemd-udev-trigger.service
+# The system proper listens instead once the disk is open (harness-button.service).
+Conflicts=initrd-switch-root.target
+Before=initrd-switch-root.target initrd-cleanup.service
+
+[Service]
+Type=simple
+ExecStart=/usr/lib/harness-os/unlock/button
+KillMode=control-group
diff --git a/os/root/usr/lib/initcpio/install/harness-unlock b/os/root/usr/lib/initcpio/install/harness-unlock
index d5fba1bd4..ea02331d5 100755
--- a/os/root/usr/lib/initcpio/install/harness-unlock
+++ b/os/root/usr/lib/initcpio/install/harness-unlock
@@ -32,6 +32,16 @@ build() {
add_file "$unlock/harness-unlock.service" '/usr/lib/systemd/system/harness-unlock.service' 644
add_symlink '/usr/lib/systemd/system/initrd.target.wants/harness-unlock.service' \
'../harness-unlock.service'
+
+ # The power button's factory reset while the disk is locked: the boot partition (FAT) opened for
+ # GRUB's environment block, which starts the recovery next.
+ # The startup's busybox has neither od, tr nor mount: the button reads and writes with these.
+ map add_module 'vfat' 'nls_cp437?' 'nls_iso8859-1?' 'nls_ascii?'
+ map add_binary '/usr/bin/od' '/usr/bin/tr' '/usr/bin/mount'
+ add_file "$unlock/button" "$unlock/button" 755
+ add_file "$unlock/harness-unlock-button.service" '/usr/lib/systemd/system/harness-unlock-button.service' 644
+ add_symlink '/usr/lib/systemd/system/initrd.target.wants/harness-unlock-button.service' \
+ '../harness-unlock-button.service'
}
help() {
diff --git a/os/root/usr/lib/systemd/logind.conf.d/20-harness-os.conf b/os/root/usr/lib/systemd/logind.conf.d/20-harness-os.conf
new file mode 100644
index 000000000..139fc5ede
--- /dev/null
+++ b/os/root/usr/lib/systemd/logind.conf.d/20-harness-os.conf
@@ -0,0 +1,5 @@
+# One press of the power button while the computer runs does nothing: a touch by accident must not
+# turn off a computer with no screen, which is turned off from a phone. Five presses ask for a factory
+# reset (button.py, harness-button.service). Held four seconds, the hardware still forces it off.
+[Login]
+HandlePowerKey=ignore
diff --git a/os/root/usr/lib/systemd/system/harness-button.service b/os/root/usr/lib/systemd/system/harness-button.service
new file mode 100644
index 000000000..c269784b0
--- /dev/null
+++ b/os/root/usr/lib/systemd/system/harness-button.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=Factory reset from the power button: five presses, then one more
+ConditionPathExists=!/etc/harness-live
+
+[Service]
+Type=simple
+ExecStart=/usr/bin/python3 /usr/lib/harness-os/button.py
+Restart=on-failure
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
diff --git a/os/root/usr/share/plymouth/themes/harness/harness.script b/os/root/usr/share/plymouth/themes/harness/harness.script
index 53fb32c89..0aea3cf85 100644
--- a/os/root/usr/share/plymouth/themes/harness/harness.script
+++ b/os/root/usr/share/plymouth/themes/harness/harness.script
@@ -63,7 +63,36 @@ fun show_hotspot() {
phone.SetOpacity(1);
}
+# The power button's factory reset (initramfs harness-unlock-button): "reset:ask:N" while it waits for
+# one press more, "reset:now" once it starts again in the recovery, "reset:" when nothing was reset.
+reset_note = Sprite();
+
+fun show_reset(state) {
+ if (state == "") {
+ reset_note.SetOpacity(0);
+ return;
+ }
+ note = "Resetting this computer. Do not turn it off.";
+ if (state.SubString(0, 3) == "ask") {
+ note = "Factory reset? Press the power button once more to erase this computer.\n" +
+ "Do nothing to keep everything.";
+ # "ask:7": the seconds left to answer.
+ if (state.SubString(0, 4) == "ask:") {
+ note = note + "\n" + state.SubString(4, state.Length()) + " seconds left";
+ }
+ }
+ note_image = Image.Text(note, 0.85, 0.78, 0.1, 1, "monospace 14", "center");
+ reset_note.SetImage(note_image);
+ reset_note.SetPosition(Window.GetX() + (Window.GetWidth() - note_image.GetWidth()) / 2,
+ Window.GetY() + 48, 2);
+ reset_note.SetOpacity(1);
+}
+
fun display_message(text) {
+ if (text.SubString(0, 6) == "reset:") {
+ show_reset(text.SubString(6, text.Length()));
+ return;
+ }
if (text.SubString(0, 8) != "hotspot:") return;
hotspot = text.SubString(8, text.Length());
show_hotspot();
diff --git a/os/setup.py b/os/setup.py
index ae3eb2a1d..a4e31a3ee 100644
--- a/os/setup.py
+++ b/os/setup.py
@@ -781,6 +781,11 @@ HN = '/usr/lib/harness/harness-tui'
# The account's daemon on this computer (cli hookServer), for the desk.
DAEMON = 'http://127.0.0.1:18473'
RESET_UNIT = 'harness-factory-reset'
+# The recovery partition and its GRUB entry (installer.py RECOVERY_*), on a computer installed with one.
+RECOVERY_CONF = Path('/etc/harness-os/recovery.conf')
+RECOVERY_DEVICE = Path('/dev/disk/by-label/HN_RECOVERY')
+RECOVERY_ENTRY = 'harness-recovery'
+GRUBENV = Path('/boot/grub/grubenv')
SIGN_OUT_UNIT = 'harness-sign-out'
# The password as installed (installer.py INITIAL_ACCOUNT): root's, inside the encrypted disk.
INITIAL_ACCOUNT = STATE / 'initial-account.json'
@@ -1048,13 +1053,14 @@ def install_gh():
return {'installed': False, 'message': 'The GitHub CLI could not be installed: ' + reason[0][:200]}
-def factory_reset(keep_wifi=False, keep_ssh=False):
+def factory_reset(keep_wifi=False, keep_ssh=False, reboot=False):
"""This computer as just installed: off its account and a new computer to it (a new computer id and
device key), everything of the person gone — /home/me as the installer made it, so its projects,
the engines' sign-ins and the hn/CLI updates it downloaded too — its Wi-Fi forgotten, SSH off, the
password as installed, and its setup hotspot open for a phone. The installed Harness OS stays.
- For `harness factory-reset` at the computer (and, later, its reset button). [keep_wifi], [keep_ssh]:
- for a test machine reached over them."""
+ For `harness factory-reset` at the computer and its power button (button.py). [keep_wifi], [keep_ssh]:
+ for a test machine reached over them. [reboot]: started again instead, as the power button asks, so
+ an encrypted computer waits for its password (the installation's again) before anyone sets it up."""
log('factory reset: everything of the person goes')
# While signed in and its daemon up: off the account, then signed out.
forget_desk()
@@ -1080,6 +1086,11 @@ def factory_reset(keep_wifi=False, keep_ssh=False):
subprocess.run(['systemctl', 'disable', '--now', SSHD], capture_output=True, timeout=60)
if not keep_wifi:
forget_wifi()
+ if reboot:
+ # Not signed in, it opens its setup hotspot as it starts (hotspot_wait).
+ log('factory reset done; starting again')
+ subprocess.run(['systemctl', 'reboot'], capture_output=True, timeout=60)
+ return
# Started again as at boot: the person's daemon (lingering), and the screen's first use.
subprocess.run(['systemctl', 'start', f'user@{account.pw_uid}.service'], capture_output=True, timeout=120)
subprocess.run(['systemctl', 'restart', '[email protected]'], capture_output=True, timeout=60)
@@ -1087,20 +1098,38 @@ def factory_reset(keep_wifi=False, keep_ssh=False):
log('factory reset done')
+def recover():
+ """The power button's reset (button.py): off its account first, which the recovery cannot reach, then
+ started in its recovery (installer.py recover), which installs it again as it came — the same as a
+ reset while its disk is locked (unlock/button). Installed before there was a recovery: reset here,
+ and started again."""
+ if not (RECOVERY_CONF.is_file() and RECOVERY_DEVICE.exists()):
+ log('factory reset: no recovery on this computer; resetting it here')
+ factory_reset(reboot=True)
+ return
+ log('factory reset: starting again in the recovery')
+ forget_desk()
+ remove_from_account()
+ as_user('/usr/bin/harness', 'logout', timeout=60)
+ subprocess.run(['grub-editenv', str(GRUBENV), 'set', f'next_entry={RECOVERY_ENTRY}'], check=True, timeout=30)
+ subprocess.run(['systemctl', 'reboot'], capture_output=True, timeout=60)
+
+
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
- parser.add_argument('command', nargs='?', choices=['watch', 'now', 'name', 'join', 'reset', 'sign-out',
+ parser.add_argument('command', nargs='?', choices=['watch', 'now', 'name', 'join', 'reset', 'sign-out', 'recover',
'password', 'ssh', 'install-gh'], default='watch')
parser.add_argument('action', nargs='?', choices=['status', 'on', 'off'], help='ssh: status, on or off')
parser.add_argument('--keep-wifi', action='store_true', help='reset, sign-out: keep the saved Wi-Fi')
parser.add_argument('--keep-ssh', action='store_true', help='reset: leave SSH as it is')
+ parser.add_argument('--reboot', action='store_true', help='reset: start again once done')
parser.add_argument('--here', action='store_true', help=argparse.SUPPRESS)
arguments = parser.parse_args()
if arguments.command in ('reset', 'sign-out'):
reset = arguments.command == 'reset'
if arguments.here:
if reset:
- factory_reset(keep_wifi=arguments.keep_wifi, keep_ssh=arguments.keep_ssh)
+ factory_reset(keep_wifi=arguments.keep_wifi, keep_ssh=arguments.keep_ssh, reboot=arguments.reboot)
else:
sign_out(keep_wifi=arguments.keep_wifi)
return
@@ -1112,6 +1141,8 @@ def main():
command.append('--keep-wifi')
if arguments.keep_ssh:
command.append('--keep-ssh')
+ if arguments.reboot:
+ command.append('--reboot')
started = subprocess.run(command, capture_output=True, text=True)
if started.returncode:
raise SystemExit('Could not start: ' + (started.stderr.strip() or 'systemd-run failed'))
@@ -1124,6 +1155,10 @@ def main():
else:
print('Signing out. Its harnesses and projects stay; it opens its setup hotspot to be set up again.')
return
+ if arguments.command == 'recover':
+ # From button.py, root's own service: nothing it runs from goes with the Wi-Fi.
+ recover()
+ return
if arguments.command == 'password':
# From the daemon, through sudo: both passwords as JSON on stdin, never in argv; the answer on stdout.
try:
diff --git a/os/tests/test_button.py b/os/tests/test_button.py
new file mode 100644
index 000000000..516bb1ec4
--- /dev/null
+++ b/os/tests/test_button.py
@@ -0,0 +1,59 @@
+import importlib.util
+from pathlib import Path
+import unittest
+
+spec = importlib.util.spec_from_file_location('button', Path(__file__).resolve().parents[1] / 'button.py')
+button = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(button)
+
+
+def pressed(count, times):
+ return [count.press(at) for at in times]
+
+
+class Presses(unittest.TestCase):
+ def test_one_press_does_nothing(self):
+ count = button.Count()
+ self.assertEqual(pressed(count, [0]), [None])
+ self.assertFalse(count.expired(100))
+
+ def test_five_in_a_row_ask_and_one_more_resets(self):
+ count = button.Count()
+ self.assertEqual(pressed(count, [0, .4, .8, 1.2, 1.6]), [None, None, None, None, 'ask'])
+ self.assertEqual(count.press(4), 'reset')
+
+ def test_presses_held_a_moment_each_still_count(self):
+ # An MSI laptop reports a press only after it was held about a second: two seconds apart.
+ count = button.Count()
+ self.assertEqual(pressed(count, [0, 2, 4, 6, 8])[-1], 'ask')
+
+ def test_a_pause_starts_the_count_again(self):
+ count = button.Count()
+ self.assertEqual(pressed(count, [0, .5, 1, 1.5, 5, 5.5, 6, 6.5]), [None] * 8)
+ self.assertEqual(count.press(7), 'ask')
+
+ def test_no_answer_in_time_resets_nothing(self):
+ count = button.Count()
+ pressed(count, [0, .4, .8, 1.2, 1.6])
+ self.assertFalse(count.expired(1.6 + button.CONFIRM - .1))
+ self.assertTrue(count.expired(1.6 + button.CONFIRM))
+ self.assertIsNone(count.press(20))
+
+ def test_still_pressing_as_it_asks_is_not_the_answer(self):
+ count = button.Count()
+ self.assertEqual(pressed(count, [0, .4, .8, 1.2, 1.6, 2, 2.4]), [None, None, None, None, 'ask', None, None])
+ self.assertEqual(count.press(4), 'reset')
+
+ def test_one_press_seen_by_two_devices_is_one(self):
+ count = button.Count()
+ self.assertEqual(pressed(count, [0, .01, .5, .51, 1, 1.01, 1.5, 1.51, 2]), [None] * 8 + ['ask'])
+
+ def test_after_a_reset_the_count_starts_over(self):
+ count = button.Count()
+ pressed(count, [0, .4, .8, 1.2, 1.6])
+ self.assertEqual(count.press(4), 'reset')
+ self.assertEqual(pressed(count, [5, 5.4, 5.8, 6.2]), [None] * 4)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tests/test_installer.py b/os/tests/test_installer.py
index 2d505417b..d1bb79ebb 100644
--- a/os/tests/test_installer.py
+++ b/os/tests/test_installer.py
@@ -1,5 +1,5 @@
import importlib.util
-from contextlib import ExitStack, redirect_stdout
+from contextlib import ExitStack, nullcontext, redirect_stdout
import hashlib
import io
import json
@@ -15,6 +15,11 @@ installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)
+def no_usb(kernel):
+ """No Harness USB at hand: installed without a recovery."""
+ return nullcontext()
+
+
class DiskSafety(unittest.TestCase):
def disk(self, **changes):
return dict({'type': 'disk', 'ro': False, 'size': 32 * 1024**3,
@@ -43,6 +48,34 @@ class DiskSafety(unittest.TestCase):
with self.subTest(changes=changes), self.assertRaises(ValueError):
installer.validate_disk(self.disk(**changes))
+ def test_recovery_is_the_fourth_partition(self):
+ self.assertEqual(installer.recovery_partition('/dev/nvme0n1'), '/dev/nvme0n1p4')
+ self.assertEqual(installer.recovery_partition('/dev/sda'), '/dev/sda4')
+
+ def test_only_the_recovery_may_install_beside_its_own_mounted_partition(self):
+ disk = self.disk(children=[{'label': 'HN_RECOVERY', 'mountpoints': ['/run/archiso/bootmnt']}])
+ installer.validate_disk(disk, recovery=True)
+ with self.assertRaises(ValueError):
+ installer.validate_disk(disk)
+ other = self.disk(children=[{'label': 'HNROOT', 'mountpoints': ['/']}])
+ with self.assertRaises(ValueError):
+ installer.validate_disk(other, recovery=True)
+
+ def test_grubenv_is_one_block_that_names_the_next_start(self):
+ block = installer.grubenv('harness-recovery')
+ self.assertEqual(len(block), 1024)
+ self.assertIn(b'\nnext_entry=harness-recovery\n', block)
+ self.assertTrue(block.startswith(b'# GRUB Environment Block\n'))
+ self.assertNotIn(b'next_entry', installer.grubenv())
+ self.assertEqual(len(installer.grubenv()), 1024)
+
+ def test_recovery_entry_finds_itself_by_its_label_and_stays_on_disk(self):
+ conf = installer.recovery_conf('abcd-1234', 'linux-lts', ['intel_iommu=on'])
+ self.assertIn("RECOVERY_UUID='abcd-1234'", conf)
+ self.assertIn("RECOVERY_KERNEL='linux-lts'", conf)
+ for argument in ['archisolabel=HN_RECOVERY', 'copytoram=n', 'harness.recovery', 'intel_iommu=on']:
+ self.assertIn(argument, conf)
+
def test_unattended_serial_must_match(self):
installer.validate_disk(self.disk(), 'HN_TEST')
with self.assertRaises(ValueError):
@@ -267,6 +300,7 @@ class EncryptionMemory(unittest.TestCase):
with patch.object(installer, 'selected_disk'), \
patch.object(installer, 'preflight'), \
patch.object(installer, 'trial_source', return_value=None), \
+ patch.object(installer, 'live_medium', no_usb), \
patch.object(installer, 'encryption_memory', return_value=192 * 1024), \
patch.object(installer, 'run', side_effect=stop_at_open) as commands:
with self.assertRaisesRegex(OSError, 'stop before mapping'):
@@ -278,6 +312,56 @@ class EncryptionMemory(unittest.TestCase):
for option in ['--iter-time', '--pbkdf-force-iterations', '--pbkdf', '--cipher', '--key-size']:
self.assertNotIn(option, call.args)
+ def install_until_open(self, config, medium, size=64 * 1024**3):
+ """The commands of an encrypted installation up to opening its disk, with [medium] as the USB."""
+ def stop_at_open(*args, **kwargs):
+ if args[:2] == ('cryptsetup', 'open'):
+ raise OSError('stop before mapping a real disk')
+ with tempfile.TemporaryDirectory() as temp:
+ source = Path(temp) / 'payload'
+ source.touch()
+ with patch.object(installer, 'selected_disk', return_value={'size': size}), \
+ patch.object(installer, 'preflight'), \
+ patch.object(installer, 'trial_source', return_value=None), \
+ patch.object(installer, 'live_medium', return_value=nullcontext(medium)) as usb, \
+ patch.object(installer, 'write_recovery') as recovery, \
+ patch.object(installer, 'encryption_memory', return_value=192 * 1024), \
+ patch.object(installer, 'boot_module') as boot, \
+ patch.object(installer, 'run', side_effect=stop_at_open) as commands:
+ boot.return_value.selected.return_value = {'id': 'pc', 'kernel': 'linux-lts', 'parameters': [], 'modules': []}
+ with self.assertRaisesRegex(OSError, 'stop before mapping'):
+ installer.install(config, source, Path(temp) / 'target')
+ return [call.args for call in commands.call_args_list], recovery, usb
+
+ def test_an_installation_from_the_usb_keeps_a_recovery_at_the_end(self):
+ config = dict(username='me', hostname='harness', password='test-password',
+ encrypt=True, disk='/dev/vda', confirm_erase='/dev/vda')
+ commands, recovery, _ = self.install_until_open(config, Path('/run/archiso/bootmnt'))
+ sgdisk = next(args for args in commands if args[0] == 'sgdisk' and '-n' in args)
+ self.assertIn('3:0:-4GiB', sgdisk)
+ self.assertIn('4:0:0', sgdisk)
+ recovery.assert_called_once_with('/dev/vda4', Path('/run/archiso/bootmnt'), 'linux-lts')
+
+ def test_without_the_usb_or_room_the_root_takes_the_whole_disk(self):
+ config = dict(username='me', hostname='harness', password='test-password',
+ encrypt=True, disk='/dev/vda', confirm_erase='/dev/vda')
+ for medium, size in [(None, 64 * 1024**3), (Path('/run/archiso/bootmnt'), 16 * 1024**3)]:
+ with self.subTest(medium=medium, size=size):
+ commands, recovery, _ = self.install_until_open(config, medium, size)
+ sgdisk = next(args for args in commands if args[0] == 'sgdisk' and '-n' in args)
+ self.assertIn('3:0:0', sgdisk)
+ self.assertNotIn('4:0:0', sgdisk)
+ recovery.assert_not_called()
+
+ def test_the_recovery_keeps_its_partitions_and_the_boot_one(self):
+ config = dict(username='me', hostname='harness', password='1234', encrypt=True, disk='/dev/vda',
+ confirm_erase='/dev/vda', recovery=True)
+ commands, recovery, usb = self.install_until_open(config, Path('/run/archiso/bootmnt'))
+ self.assertFalse([args for args in commands if args[0] in ('sgdisk', 'mkfs.fat')])
+ self.assertIn(('wipefs', '-a', '/dev/vda3'), commands)
+ recovery.assert_not_called()
+ usb.assert_not_called()
+
def test_plain_install_does_not_require_an_encryption_budget(self):
config = dict(username='me', hostname='harness', password='test-password',
encrypt=False, disk='/dev/vda', confirm_erase='/dev/vda')
@@ -287,6 +371,7 @@ class EncryptionMemory(unittest.TestCase):
with patch.object(installer, 'selected_disk'), \
patch.object(installer, 'preflight'), \
patch.object(installer, 'trial_source', return_value=None), \
+ patch.object(installer, 'live_medium', no_usb), \
patch.object(installer, 'encryption_memory') as budget, \
patch.object(installer, 'run', side_effect=OSError('stop before erasing')):
with self.assertRaisesRegex(OSError, 'stop before erasing'):
@@ -365,6 +450,7 @@ class InstallerCleanup(unittest.TestCase):
with patch.object(installer, 'selected_disk'), \
patch.object(installer, 'preflight'), \
patch.object(installer, 'trial_source', return_value=None), \
+ patch.object(installer, 'live_medium', no_usb), \
patch.object(installer, 'encryption_memory', return_value=128 * 1024), \
patch.object(installer, 'run', side_effect=command), \
patch.object(installer, 'close_install_mapping', side_effect=cleanup) as close, \
diff --git a/os/tests/test_unlock_button.py b/os/tests/test_unlock_button.py
new file mode 100644
index 000000000..04420244a
--- /dev/null
+++ b/os/tests/test_unlock_button.py
@@ -0,0 +1,58 @@
+"""The power button's factory reset while the disk is locked (root/usr/lib/harness-os/unlock/button):
+which devices it listens to, and the GRUB environment block that starts the recovery."""
+import importlib.util
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+OS = Path(__file__).resolve().parents[1]
+BUTTON = OS / 'root/usr/lib/harness-os/unlock/button'
+spec = importlib.util.spec_from_file_location('installer', OS / 'installer.py')
+installer = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(installer)
+
+# /proc/bus/input/devices: ACPI's power button (KEY_POWER, bit 116), a keyboard without it, and one
+# with it among its many keys.
+DEVICES = '''I: Bus=0019 Vendor=0000 Product=0001 Version=0000
+N: Name="Power Button"
+H: Handlers=kbd event3
+B: EV=3
+B: KEY=10000000000000 0
+
+I: Bus=0011 Vendor=0001 Product=0001 Version=ab41
+N: Name="AT Translated Set 2 keyboard"
+H: Handlers=sysrq kbd leds event2
+B: EV=120013
+B: KEY=402000000 3803078f800d001 fecfffdfffefffff fffffffffffffffe
+
+I: Bus=0003 Vendor=046d Product=c52b Version=0111
+N: Name="Logitech K400"
+H: Handlers=sysrq kbd leds event7
+B: EV=120013
+B: KEY=1000000000007 ff9f207ac14057ff febeffdfffefffff fffffffffffffffe
+'''
+
+
+class Button(unittest.TestCase):
+ def run_button(self, *args, **env):
+ return subprocess.run(['sh', str(BUTTON), *args], capture_output=True, text=True, check=True,
+ env=dict(os.environ, **env)).stdout
+
+ def test_it_listens_to_every_device_with_the_power_key(self):
+ with tempfile.NamedTemporaryFile('w', suffix='devices') as devices:
+ devices.write(DEVICES)
+ devices.flush()
+ listed = self.run_button('devices', HARNESS_BUTTON_DEVICES=devices.name).split()
+ self.assertEqual(listed, ['event3', 'event7'])
+
+ def test_its_grub_block_is_the_installers(self):
+ with tempfile.TemporaryDirectory() as folder:
+ block = Path(folder) / 'grubenv'
+ self.run_button('grubenv', str(block))
+ self.assertEqual(block.read_bytes(), installer.grubenv('harness-recovery'))
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/os/tools/build-package.py b/os/tools/build-package.py
index aba1c2ee2..37ac3c0ca 100644
--- a/os/tools/build-package.py
+++ b/os/tools/build-package.py
@@ -69,6 +69,7 @@ def stage(source, runtime, destination, commit):
'os/onboarding.py': 'usr/lib/harness-os/onboarding.py',
'os/network.py': 'usr/lib/harness-os/network.py',
'os/setup.py': 'usr/lib/harness-os/setup.py',
+ 'os/button.py': 'usr/lib/harness-os/button.py',
'os/projects.py': 'usr/lib/harness-os/projects.py',
'os/trial_projects.py': 'usr/lib/harness-os/trial_projects.py',
'os/system.py': 'usr/lib/harness-os/system.py',
@@ -119,6 +120,7 @@ def stage(source, runtime, destination, commit):
for name in ['autostart', 'shutdown']:
(destination / 'usr/share/harness-os/labwc' / name).chmod(0o755)
(destination / 'usr/share/harness-os/labwc-install/autostart').chmod(0o755)
+ (destination / 'etc/grub.d/42_harness-recovery').chmod(0o755)
for path in (destination / 'etc/sudoers.d').iterdir():
path.chmod(0o440)
info.update(mode='source', files={p.name: {'sha256': digest(p), 'bytes': p.stat().st_size}
diff --git a/os/tools/customize-live.sh b/os/tools/customize-live.sh
index 3cf50bfdf..48d89e3eb 100644
--- a/os/tools/customize-live.sh
+++ b/os/tools/customize-live.sh
@@ -19,6 +19,8 @@ visudo -cf /etc/sudoers.d/20-harness-network
chown me:me /home/me/projects
systemctl enable NetworkManager systemd-resolved systemd-timesyncd [email protected]
systemctl enable harness-keyring.service
+# Started from the recovery partition only (harness.recovery): it installs the computer again.
+systemctl enable harness-recovery.service
# hn-screen starts the daemon after labwc has published the display environment.
# Linger keeps that runtime alive if its graphical client is restarted.
mkdir -p /var/lib/systemd/linger