diff --git a/Cargo.lock b/Cargo.lock index 8338184..c0987f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -157,6 +157,7 @@ dependencies = [ "toml", "unicode-truncate", "unicode-width", + "zeroize", ] [[package]] @@ -2170,3 +2171,9 @@ name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" diff --git a/Cargo.toml b/Cargo.toml index 8634706..75b510d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ needless_for_each = "allow" clap = { version = "4.5", features = ["derive"] } crossterm = "0.29" dbus = "0.9" -jiff = { version = "0.2", default-features = false, features = ["std"] } +jiff = { version = "0.2", default-features = false, features = ["serde", "std"] } ratatui = { version = "0.30", features = ["serde"] } rustix = { version = "1", features = ["fs", "process", "stdio", "system", "termios", "time"] } serde = { version = "1.0.229", features = ["derive"] } @@ -20,6 +20,7 @@ signal-hook = "0.4" toml = "1.1.8" unicode-truncate = "2.0" unicode-width = "0.2" +zeroize = "1.9.0" [profile.release] lto = "thin" diff --git a/README.md b/README.md index 63e5835..5bf9809 100644 --- a/README.md +++ b/README.md @@ -43,8 +43,9 @@ initrd, add `bootvine` to `add_dracutmodules` (dracut) or `sd-bootvine` after ## Configure -`/etc/bootvine.toml`, or `services.bootvine.palette` on NixOS. Every key is -optional; these are the defaults: +`/etc/bootvine.toml`, or `services.bootvine.palette` and +`services.bootvine.timing` on NixOS. Every key is optional; these are the +defaults: ```toml [palette] @@ -55,9 +56,20 @@ running = "yellow" done = "green" failed = "light-red" target = "cyan" + +[timing] +keep_finished_units_for = "2s" +hide_runs_shorter_than = "1s" +keep_final_frame_for = "1s" ``` -Values are the 16 console colour names. To change how those look, set the -console palette: `console.colors` on NixOS, or the `vt.default_red`, `_grn` and -`_blu` kernel parameters elsewhere. The initrd hooks copy the file into the -initramfs, so rebuild it after editing. +Palette values are the 16 console colour names. To change how those look, set +the console palette: `console.colors` on NixOS, or the `vt.default_red`, `_grn` +and `_blu` kernel parameters elsewhere. + +`keep_finished_units_for` is how long a finished unit stays in the tree, faded, +before it leaves. Runs shorter than `hide_runs_shorter_than` get no timer and no +timeline bar. `keep_final_frame_for` is how long the last frame stays before the +console is handed back; `--hold` overrides it. + +The initrd hooks copy the file into the initramfs, so rebuild it after editing. diff --git a/demo/luks-test.nix b/demo/luks-test.nix index b86e86c..0ead19b 100644 --- a/demo/luks-test.nix +++ b/demo/luks-test.nix @@ -29,6 +29,8 @@ }; testScript = '' + import time + passphrase = "quietly unlocked" machine.wait_for_unit("multi-user.target") @@ -39,6 +41,9 @@ machine.start() machine.wait_for_text("passphrase") + machine.send_chars("not the passphrase\n") + time.sleep(5) + machine.wait_for_text("passphrase") machine.screenshot("passphrase") machine.send_chars(f"{passphrase}\n") machine.wait_for_unit("multi-user.target") @@ -47,6 +52,6 @@ journal = machine.succeed("journalctl -b -u bootvine -o cat") print(journal) assert "in initrd" in journal, "never ran in the initrd" - assert "taking the console back" in journal, "never took the console back after the prompt" + assert journal.count("answered a password prompt") == 2, "did not answer both attempts itself" ''; } diff --git a/examples/demo.rs b/examples/demo.rs index b3a7a70..45cff1f 100644 --- a/examples/demo.rs +++ b/examples/demo.rs @@ -5,6 +5,7 @@ use std::{ }; use bootvine::{ + config::Timing, glyphs::Glyphs, model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts}, origin::BootOrigin, @@ -362,10 +363,12 @@ fn play(terminal: &mut DefaultTerminal) -> io::Result<()> { BootView { state: &state, palette: &Palette::default(), + timing: &Timing::default(), glyphs: &Glyphs::default(), now: now(), origin: &origin, frame, + password_prompt: None, }, canvas.area(), ); diff --git a/nixos-module.nix b/nixos-module.nix index 2e3fae4..a7f9f8d 100644 --- a/nixos-module.nix +++ b/nixos-module.nix @@ -7,8 +7,23 @@ }: let cfg = config.services.bootvine; - chosenColors = lib.filterAttrs (_: color: color != null) cfg.palette; - configFile = (pkgs.formats.toml { }).generate "bootvine.toml" { palette = chosenColors; }; + chosen = lib.filterAttrs (_: value: value != null); + settings = lib.filterAttrs (_: table: table != { }) { + palette = chosen cfg.palette; + timing = chosen cfg.timing; + }; + configFile = (pkgs.formats.toml { }).generate "bootvine.toml" settings; + durationOption = + purpose: default: + lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "500ms"; + description = '' + ${purpose}; unset keeps `${default}`. A duration such as `2s`, + `500ms` or `1m 30s`. + ''; + }; colorOption = role: default: lib.mkOption { @@ -48,12 +63,18 @@ in failed = colorOption "failed units" "light-red"; target = colorOption "targets in the tree" "cyan"; }; + + timing = { + keep_finished_units_for = durationOption "How long a finished unit stays in the tree, faded, before it leaves" "2s"; + hide_runs_shorter_than = durationOption "Runs shorter than this get no timer in the tree and no bar on the timeline" "1s"; + keep_final_frame_for = durationOption "How long the last frame stays on screen before the console is handed back" "1s"; + }; }; config = lib.mkIf cfg.enable { environment = { systemPackages = [ cfg.package ]; - etc."bootvine.toml" = lib.mkIf (chosenColors != { }) { source = configFile; }; + etc."bootvine.toml" = lib.mkIf (settings != { }) { source = configFile; }; }; systemd = { @@ -66,7 +87,7 @@ in packages = [ cfg.package ]; storePaths = [ (lib.getExe cfg.package) ]; services.bootvine.wantedBy = [ "sysinit.target" ]; - contents."/etc/bootvine.toml" = lib.mkIf (chosenColors != { }) { source = configFile; }; + contents."/etc/bootvine.toml" = lib.mkIf (settings != { }) { source = configFile; }; }; }; } diff --git a/packaging/dracut/90bootvine/module-setup.sh b/packaging/dracut/90bootvine/module-setup.sh index fa91a27..642560a 100755 --- a/packaging/dracut/90bootvine/module-setup.sh +++ b/packaging/dracut/90bootvine/module-setup.sh @@ -11,8 +11,7 @@ depends() { install() { inst_binary bootvine - inst_simple "$systemdsystemunitdir/bootvine.service" - if [[ -f /etc/bootvine.toml ]]; then + inst_simple "$systemdsystemunitdir/bootvine.service" if [[ -f /etc/bootvine.toml ]]; then inst_simple /etc/bootvine.toml fi $SYSTEMCTL -q --root "$initdir" enable bootvine.service diff --git a/packaging/mkinitcpio/install/sd-bootvine b/packaging/mkinitcpio/install/sd-bootvine index 84df0a3..74d0200 100755 --- a/packaging/mkinitcpio/install/sd-bootvine +++ b/packaging/mkinitcpio/install/sd-bootvine @@ -2,8 +2,7 @@ build() { add_binary bootvine - add_systemd_unit bootvine.service - if [[ -f /etc/bootvine.toml ]]; then + add_systemd_unit bootvine.service if [[ -f /etc/bootvine.toml ]]; then add_file /etc/bootvine.toml fi add_symlink /usr/lib/systemd/system/sysinit.target.wants/bootvine.service \ diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..a1ac253 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,57 @@ +use std::time::Duration; + +use serde::Deserialize; + +use crate::palette::Palette; + +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields)] +pub struct Config { + pub palette: Palette, + pub timing: Timing, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields)] +pub struct Timing { + #[serde(with = "jiff::fmt::serde::unsigned_duration::friendly::compact::required")] + pub keep_finished_units_for: Duration, + #[serde(with = "jiff::fmt::serde::unsigned_duration::friendly::compact::required")] + pub hide_runs_shorter_than: Duration, + #[serde(with = "jiff::fmt::serde::unsigned_duration::friendly::compact::required")] + pub keep_final_frame_for: Duration, +} + +impl Default for Timing { + fn default() -> Self { + Self { + keep_finished_units_for: Duration::from_secs(2), + hide_runs_shorter_than: Duration::from_secs(1), + keep_final_frame_for: Duration::from_secs(1), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn timing_reads_friendly_durations_and_keeps_unset_defaults() { + let config: Config = toml::from_str("[timing]\nkeep_finished_units_for = \"500ms\"\n") + .expect("valid config"); + assert_eq!( + config.timing.keep_finished_units_for, + Duration::from_millis(500) + ); + assert_eq!( + config.timing.keep_final_frame_for, + Timing::default().keep_final_frame_for + ); + } + + #[test] + fn nonsense_durations_are_rejected() { + assert!(toml::from_str::("[timing]\nkeep_final_frame_for = \"soon\"\n").is_err()); + } +} diff --git a/src/console.rs b/src/console.rs index 851d1ff..f92a7c0 100644 --- a/src/console.rs +++ b/src/console.rs @@ -8,6 +8,8 @@ use rustix::{ termios::ttyname, }; +use crate::password; + const GIO_UNIMAP: Opcode = 0x4B66; const VT_GETSTATE: Opcode = 0x5603; const VT_ACTIVATE: Opcode = 0x5606; @@ -15,56 +17,44 @@ const VT_WAITACTIVE: Opcode = 0x5607; const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty"; const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk"; const ALERTS_ONLY: &str = "1"; -const PASSWORD_REQUESTS: &str = "/run/systemd/ask-password"; -const PASSWORD_REQUEST_PREFIX: &str = "ask."; - pub struct Console { quiet_kernel: Option, foreground: Option, - yields_to_password_prompts: bool, + for_system: bool, pub glyphs: Glyphs, } impl Console { pub fn take(for_system: bool) -> Self { - let prompt_showing = for_system && password_requested(); + let prompt_elsewhere = for_system && password::requested(); + if prompt_elsewhere { + eprintln!("bootvine: a password prompt is already showing, staying behind it"); + } Self { quiet_kernel: for_system.then(QuietKernelConsole::take).flatten(), - foreground: if prompt_showing { + foreground: if prompt_elsewhere { None } else { ForegroundVt::take() }, - yields_to_password_prompts: for_system, + for_system, glyphs: font_glyphs(), } } - pub fn make_way_for_password_prompts(&mut self) { - if !self.yields_to_password_prompts { - return; - } - if password_requested() { - self.step_aside(); - } else { - self.come_forward(); - } + pub fn answers_password_prompts(&self) -> bool { + self.for_system && self.foreground.is_some() } - fn step_aside(&mut self) { - if self.foreground.take().is_some() { - eprintln!("bootvine: stepping aside for a password prompt"); - } - } - - fn come_forward(&mut self) { - if self.foreground.is_some() { - return; + pub fn come_forward_once_prompts_are_gone(&mut self) -> bool { + if !self.for_system || self.foreground.is_some() || password::requested() { + return false; } self.foreground = ForegroundVt::take(); if self.foreground.is_some() { eprintln!("bootvine: password prompt answered, taking the console back"); } + self.foreground.is_some() } pub fn keep_up(&mut self) { @@ -101,17 +91,6 @@ impl QuietKernelConsole { } } -fn password_requested() -> bool { - fs::read_dir(PASSWORD_REQUESTS).is_ok_and(|entries| { - entries.flatten().any(|entry| { - entry - .file_name() - .to_string_lossy() - .starts_with(PASSWORD_REQUEST_PREFIX) - }) - }) -} - fn font_glyphs() -> Glyphs { font_characters().map_or_else(Glyphs::default, |characters| { Glyphs::fitting(|symbol| symbol.is_ascii() || characters.contains(&symbol)) @@ -199,6 +178,10 @@ impl ForegroundVt { impl Drop for ForegroundVt { fn drop(&mut self) { + if password::requested() { + eprintln!("bootvine: leaving a password prompt to the console agent on this terminal"); + return; + } let _ = activate(self.previous); } } diff --git a/src/lib.rs b/src/lib.rs index 1dadba6..363e005 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub mod config; pub mod glyphs; pub mod model; pub mod origin; diff --git a/src/main.rs b/src/main.rs index 81f982c..93e86ae 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,15 +2,16 @@ mod clock; mod console; mod error; mod feed; +mod password; mod run; mod sysroot; mod systemd; use std::{fs, io::ErrorKind, path::PathBuf, process::ExitCode, time::Duration}; -use bootvine::palette::Config; +use bootvine::config::{Config, Timing}; use clap::Parser; -use jiff::SignedDuration; +use jiff::fmt::friendly::SpanParser; use crate::{ run::{Options, run}, @@ -34,24 +35,19 @@ struct Cli { target: Option, #[arg( long, - default_value = "1s", - value_parser = parse_duration, - help = "How long the final frame stays on screen, e.g. 1s or 500ms" + value_parser = |raw: &str| SpanParser::new().parse_unsigned_duration(raw), + help = "How long the final frame stays on screen, e.g. 1s or 500ms; overrides \ + timing.keep_final_frame_for" )] - hold: Duration, + hold: Option, #[arg( long, default_value = "/etc/bootvine.toml", - help = "TOML file with a [palette] table" + help = "TOML file with [palette] and [timing] tables" )] config: PathBuf, } -fn parse_duration(raw: &str) -> Result { - let signed: SignedDuration = raw.parse().map_err(|error| format!("{error}"))?; - Duration::try_from(signed).map_err(|error| format!("{error}")) -} - fn main() -> ExitCode { let cli = Cli::parse(); let config = match fs::read_to_string(&cli.config) { @@ -69,7 +65,10 @@ fn main() -> ExitCode { scope: if cli.user { Scope::User } else { Scope::System }, shutdown: cli.shutdown, target: cli.target, - hold: cli.hold, + timing: Timing { + keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for), + ..config.timing + }, palette: config.palette, }; match run(&options) { diff --git a/src/model.rs b/src/model.rs index 2c5f594..3669847 100644 --- a/src/model.rs +++ b/src/model.rs @@ -588,12 +588,17 @@ impl BootState { } #[must_use] - pub fn tree_rows(&self) -> Vec { + pub fn tree_rows(&self, finished_since: Duration) -> Vec { let pending: HashSet<&str> = self .units .iter() .filter(|(name, record)| { + let finished_recently = matches!( + record.outcome, + Some(Outcome::Succeeded { at }) if at >= finished_since + ); record.job.is_some() + || finished_recently || record.outcome == Some(Outcome::Failed) || (self.is_milestone(name) && record.outcome.is_some()) }) @@ -752,6 +757,9 @@ impl BootState { let record = &self.units[name]; match (record.running_since(), record.outcome) { (Some(since), _) => SiblingRank::RunningSince(since), + (None, Some(Outcome::Succeeded { at })) => { + SiblingRank::RunningSince(record.inactive_exit.unwrap_or(at)) + } (None, Some(Outcome::Failed)) => SiblingRank::Failed, (None, _) => SiblingRank::Waiting, } @@ -1035,7 +1043,7 @@ mod tests { #[test] fn pending_units_nest_under_what_waits_on_them() { let outline: Vec = sample() - .tree_rows() + .tree_rows(Duration::MAX) .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect(); @@ -1055,7 +1063,7 @@ mod tests { #[test] fn only_chains_leading_to_running_units_stay_in_view() { - let rows = fit_to_height(sample().tree_rows(), 0); + let rows = fit_to_height(sample().tree_rows(Duration::MAX), 0); let outline: Vec = rows .iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) @@ -1091,7 +1099,7 @@ mod tests { "b.service", ); let outline = |budget| -> Vec { - fit_to_height(state.tree_rows(), budget) + fit_to_height(state.tree_rows(Duration::MAX), budget) .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect() @@ -1124,7 +1132,7 @@ mod tests { state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO); }); let outline: Vec = state - .tree_rows() + .tree_rows(Duration::MAX) .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect(); @@ -1181,7 +1189,7 @@ mod tests { } fn folded_outline(state: &BootState) -> Vec { - fold_chains(fit_to_height(state.tree_rows(), 0)) + fold_chains(fit_to_height(state.tree_rows(Duration::MAX), 0)) .into_iter() .map(|row| { let chain = once(row.label.as_str()) @@ -1237,7 +1245,7 @@ mod tests { folded_outline(&state), ["root.target", " a", " b", " d"] ); - let rows = fold_chains(fit_to_height(both.tree_rows(), 0)); + let rows = fold_chains(fit_to_height(both.tree_rows(Duration::MAX), 0)); let lasts: Vec = rows .iter() .map(|row| *row.is_last_sibling.last().unwrap()) @@ -1253,7 +1261,7 @@ mod tests { state.track_unit(facts("idle.service", &[]), Activity::default()); state.queue_job(1, "demo.target", JobKind::BringsUp, Duration::ZERO); state.queue_job(2, "idle.service", JobKind::BringsUp, Duration::ZERO); - let rows = fit_to_height(state.tree_rows(), 0); + let rows = fit_to_height(state.tree_rows(Duration::MAX), 0); assert_eq!(rows.len(), 1); assert_eq!(rows[0].label, "demo.target"); } @@ -1272,7 +1280,7 @@ mod tests { active_exit: None, }, ); - let rows = state.tree_rows(); + let rows = state.tree_rows(Duration::MAX); assert!( rows.iter() .all(|row| row.label != "containerd" && row.label != "basic.target") @@ -1338,7 +1346,7 @@ mod tests { ); assert_eq!(state.milestones()[0].reached_at, Some(2000 * MS)); assert_eq!(state.tally().done, 2); - assert!(state.tree_rows().is_empty()); + assert!(state.tree_rows(Duration::MAX).is_empty()); } #[test] @@ -1354,7 +1362,10 @@ mod tests { Activity::default(), ); state.queue_job(1, "dev-nvme1n1.device", JobKind::BringsUp, Duration::ZERO); - assert_eq!(state.tree_rows()[0].label, "Lexar SSD NM790 2TB"); + assert_eq!( + state.tree_rows(Duration::MAX)[0].label, + "Lexar SSD NM790 2TB" + ); } #[test] @@ -1378,7 +1389,7 @@ mod tests { state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO); }); let outline: Vec = state - .tree_rows() + .tree_rows(Duration::MAX) .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect(); @@ -1394,7 +1405,7 @@ mod tests { fn outline(state: &BootState) -> Vec { state - .tree_rows() + .tree_rows(Duration::MAX) .into_iter() .map(|row| format!("{}{}", " ".repeat(row.depth), row.label)) .collect() @@ -1478,7 +1489,10 @@ mod tests { ..Activity::default() }, ); - assert_eq!(state.tree_rows()[0].running_since, Some(1200 * MS)); + assert_eq!( + state.tree_rows(Duration::MAX)[0].running_since, + Some(1200 * MS) + ); state.finish_job(1, JobResult::Done, 1700 * MS); assert_eq!( state.finished_runs, @@ -1517,6 +1531,6 @@ mod tests { state.track_unit(facts("b.service", &["a.service"]), Activity::default()); state.queue_job(1, "a.service", JobKind::BringsUp, Duration::ZERO); state.queue_job(2, "b.service", JobKind::BringsUp, Duration::ZERO); - assert_eq!(state.tree_rows().len(), 2); + assert_eq!(state.tree_rows(Duration::MAX).len(), 2); } } diff --git a/src/palette.rs b/src/palette.rs index bd2c0f8..ee17ee1 100644 --- a/src/palette.rs +++ b/src/palette.rs @@ -26,9 +26,3 @@ impl Default for Palette { } } } - -#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] -#[serde(default, deny_unknown_fields)] -pub struct Config { - pub palette: Palette, -} diff --git a/src/password.rs b/src/password.rs new file mode 100644 index 0000000..7831f06 --- /dev/null +++ b/src/password.rs @@ -0,0 +1,252 @@ +use std::{ + fs, io, + os::unix::net::UnixDatagram, + path::{Path, PathBuf}, + time::Duration, +}; + +use bootvine::view::PasswordPrompt; +use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; +use rustix::process::{Pid, test_kill_process}; +use zeroize::Zeroizing; + +use crate::clock::monotonic_now; + +const REQUESTS: &str = "/run/systemd/ask-password"; +const REQUEST_PREFIX: &str = "ask."; +const ASK_SECTION: &str = "[Ask]"; +const ROOM_FOR_TYPING: usize = 512; + +#[derive(Debug, PartialEq, Eq)] +pub struct PasswordRequest { + pub file: PathBuf, + pub message: String, + socket: PathBuf, + echo: bool, + silent: bool, + not_after: Option, + asker: Option, +} + +pub fn requested() -> bool { + !request_files().is_empty() +} + +fn request_files() -> Vec { + let mut files: Vec = fs::read_dir(REQUESTS) + .into_iter() + .flatten() + .flatten() + .filter(|entry| { + entry + .file_name() + .to_string_lossy() + .starts_with(REQUEST_PREFIX) + }) + .map(|entry| entry.path()) + .collect(); + files.sort(); + files +} + +impl PasswordRequest { + fn first_live() -> Option { + request_files() + .iter() + .filter_map(|file| Self::read(file)) + .find(Self::is_live) + } + + fn read(file: &Path) -> Option { + Self::parse(file, &fs::read_to_string(file).ok()?) + } + + fn parse(file: &Path, text: &str) -> Option { + let fields: Vec<(&str, &str)> = text + .lines() + .map(str::trim) + .skip_while(|line| *line != ASK_SECTION) + .skip(1) + .take_while(|line| !line.starts_with('[')) + .filter_map(|line| line.split_once('=')) + .collect(); + let field = |key: &str| { + fields + .iter() + .find(|(name, _)| *name == key) + .map(|(_, value)| *value) + }; + let flag = |key: &str| field(key).is_some_and(is_true); + Some(Self { + file: file.to_owned(), + message: field("Message").unwrap_or_default().to_owned(), + socket: PathBuf::from(field("Socket")?), + echo: flag("Echo"), + silent: flag("Silent"), + not_after: field("NotAfter") + .and_then(|value| value.parse().ok()) + .filter(|micros| *micros > 0) + .map(Duration::from_micros), + asker: field("PID") + .and_then(|value| value.parse().ok()) + .and_then(Pid::from_raw), + }) + } + + fn is_live(&self) -> bool { + self.file.exists() + && self + .not_after + .is_none_or(|deadline| monotonic_now() <= deadline) + && self + .asker + .is_none_or(|asker| test_kill_process(asker).is_ok()) + } + + fn answer(&self, password: &str) -> io::Result<()> { + let mut packet = Zeroizing::new(Vec::with_capacity(password.len() + 1)); + packet.push(b'+'); + packet.extend_from_slice(password.as_bytes()); + UnixDatagram::unbound()?.send_to(&packet, &self.socket)?; + Ok(()) + } +} + +fn is_true(value: &str) -> bool { + matches!( + value.to_ascii_lowercase().as_str(), + "1" | "yes" | "y" | "true" | "t" | "on" + ) +} + +pub struct PasswordEntry { + request: PasswordRequest, + typed: Zeroizing, + sent: bool, +} + +impl PasswordEntry { + pub fn follow(current: Option) -> Option { + if let Some(entry) = current.filter(|entry| entry.request.is_live()) { + return Some(entry); + } + let request = PasswordRequest::first_live()?; + eprintln!( + "bootvine: asking for a password: {}", + request.file.display() + ); + Some(Self { + request, + typed: Zeroizing::new(String::with_capacity(ROOM_FOR_TYPING)), + sent: false, + }) + } + + pub fn prompt(&self) -> PasswordPrompt<'_> { + let input = match (self.sent, self.request.echo, self.request.silent) { + (true, _, _) | (false, _, true) => String::new(), + (false, true, false) => self.typed.as_str().to_owned(), + (false, false, false) => "*".repeat(self.typed.chars().count()), + }; + PasswordPrompt { + message: &self.request.message, + input, + sent: self.sent, + } + } + + pub fn type_key(&mut self, event: &Event) -> io::Result<()> { + let Event::Key(KeyEvent { + code, + modifiers, + kind: KeyEventKind::Press, + .. + }) = event + else { + return Ok(()); + }; + if self.sent { + return Ok(()); + } + match code { + KeyCode::Enter => { + self.request.answer(&self.typed)?; + self.sent = true; + self.typed.clear(); + eprintln!("bootvine: answered a password prompt"); + } + KeyCode::Backspace => { + self.typed.pop(); + } + KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => self.typed.clear(), + KeyCode::Char(_) if modifiers.contains(KeyModifiers::CONTROL) => {} + KeyCode::Char(character) + if self.typed.len() + character.len_utf8() <= ROOM_FOR_TYPING => + { + self.typed.push(*character); + } + _ => {} + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const CRYPTSETUP_ASK: &str = concat!( + "[Ask]\n", + "PID=1\n", + "Socket=/run/systemd/ask-password/sck.1\n", + "AcceptCached=1\n", + "Echo=0\n", + "NotAfter=0\n", + "Message=Please enter passphrase for disk secret:\n", + "Icon=drive-harddisk\n", + "Id=cryptsetup:/dev/vdb\n", + ); + + #[test] + fn reads_what_cryptsetup_asks() { + let request = PasswordRequest::parse(Path::new("ask.x"), CRYPTSETUP_ASK).expect("parsed"); + assert_eq!( + request, + PasswordRequest { + file: PathBuf::from("ask.x"), + message: "Please enter passphrase for disk secret:".to_owned(), + socket: PathBuf::from("/run/systemd/ask-password/sck.1"), + echo: false, + silent: false, + not_after: None, + asker: Pid::from_raw(1), + } + ); + } + + #[test] + fn ignores_requests_without_a_socket() { + assert_eq!( + PasswordRequest::parse(Path::new("ask.x"), "[Ask]\nMessage=hi\n"), + None + ); + } + + #[test] + fn hides_what_is_typed() { + let mut entry = PasswordEntry { + request: PasswordRequest::parse(Path::new("ask.x"), CRYPTSETUP_ASK).expect("parsed"), + typed: Zeroizing::new(String::new()), + sent: false, + }; + "secret".chars().for_each(|character| { + entry + .type_key(&Event::Key(KeyEvent::from(KeyCode::Char(character)))) + .expect("typed"); + }); + entry + .type_key(&Event::Key(KeyEvent::from(KeyCode::Backspace))) + .expect("erased"); + assert_eq!(entry.prompt().input, "*****"); + } +} diff --git a/src/run.rs b/src/run.rs index bac9353..18918d3 100644 --- a/src/run.rs +++ b/src/run.rs @@ -9,6 +9,7 @@ use std::{ }; use bootvine::{ + config::Timing, model::{BootState, Phase}, origin::BootOrigin, palette::Palette, @@ -27,6 +28,7 @@ use crate::{ console::Console, error::Error, feed::Feed, + password::PasswordEntry, sysroot::INITRD_RELEASE, systemd::{Scope, Session}, }; @@ -38,7 +40,7 @@ pub struct Options { pub scope: Scope, pub shutdown: bool, pub target: Option, - pub hold: Duration, + pub timing: Timing, pub palette: Palette, } @@ -71,7 +73,7 @@ pub fn run(options: &Options) -> Result<(), Error> { &terminate, &options.palette, &mut console, - options.hold, + &options.timing, ); ratatui::restore(); watched @@ -110,20 +112,28 @@ fn watch( terminate: &AtomicBool, palette: &Palette, console: &mut Console, - hold: Duration, + timing: &Timing, ) -> Result<(), Error> { let mut origin = BootOrigin::read(); let mut origin_phase = state.phase; let mut frame: u64 = 0; let mut painted_connections = feed.connections; let mut last_full_repaint = Instant::now(); + let mut password_entry: Option = None; loop { feed.pump(state, FRAME_INTERVAL)?; if state.phase != origin_phase { origin = BootOrigin::read(); origin_phase = state.phase; } - console.make_way_for_password_prompts(); + if console.come_forward_once_prompts_are_gone() { + terminal.clear()?; + } + password_entry = if console.answers_password_prompts() { + PasswordEntry::follow(password_entry.take()) + } else { + None + }; let repaint_due = feed.connections != painted_connections || last_full_repaint.elapsed() >= FULL_REPAINT_INTERVAL; if repaint_due { @@ -134,10 +144,12 @@ fn watch( BootView { state, palette, + timing, glyphs: &console.glyphs, now: monotonic_now(), origin: &origin, frame, + password_prompt: password_entry.as_ref().map(PasswordEntry::prompt), }, canvas.area(), ); @@ -153,14 +165,23 @@ fn watch( "bootvine: {} reached, handing the console over", state.root.as_deref().unwrap_or("boot") ); - sleep(hold); + sleep(timing.keep_final_frame_for); return Ok(()); } if terminate.load(Ordering::Relaxed) { return Ok(()); } - if event::poll(Duration::ZERO)? && asks_to_quit(&event::read()?) { - return Ok(()); + while event::poll(Duration::ZERO)? { + let event = event::read()?; + match &mut password_entry { + Some(entry) => { + if let Err(error) = entry.type_key(&event) { + eprintln!("bootvine: cannot answer the password prompt: {error}"); + } + } + None if asks_to_quit(&event) => return Ok(()), + None => {} + } } frame += 1; } diff --git a/src/view.rs b/src/view.rs index 40b8ad1..acc8975 100644 --- a/src/view.rs +++ b/src/view.rs @@ -1,5 +1,6 @@ mod footer; mod header; +mod prompt; mod stages; mod timeline; mod tree; @@ -16,8 +17,13 @@ use ratatui::{ use unicode_truncate::UnicodeTruncateStr; use unicode_width::UnicodeWidthStr; -use self::{footer::Footer, header::Header, stages::Stages, timeline::Timeline, tree::UnitTree}; +pub use self::prompt::PasswordPrompt; +use self::{ + footer::Footer, header::Header, prompt::PasswordBar, stages::Stages, timeline::Timeline, + tree::UnitTree, +}; use crate::{ + config::Timing, glyphs::Glyphs, model::{BootState, RowStatus, TreeRow, UnitKind, fit_to_height, fold_chains}, origin::BootOrigin, @@ -28,7 +34,6 @@ const DURATION_WIDTH: u16 = 8; const MIN_BAR_WIDTH: u16 = 12; const MIN_HEIGHT_FOR_TIMELINE: u16 = 12; const MIN_TIMELINE_HEIGHT: u16 = timeline::CHROME_HEIGHT + 4; -const NOTEWORTHY_DURATION: Duration = Duration::from_secs(1); const HEADER_HEIGHT: u16 = 1; const BRANCH: &str = "├─ "; const LAST_BRANCH: &str = "└─ "; @@ -44,10 +49,12 @@ const ELAPSED: SpanPrinter = SpanPrinter::new() pub struct BootView<'a> { pub state: &'a BootState, pub palette: &'a Palette, + pub timing: &'a Timing, pub glyphs: &'a Glyphs, pub now: Duration, pub origin: &'a BootOrigin, pub frame: u64, + pub password_prompt: Option>, } impl BootView<'_> { @@ -76,7 +83,10 @@ impl BootView<'_> { .state .finished_runs .iter() - .filter(|run| run.finished_at.saturating_sub(run.started_at) >= NOTEWORTHY_DURATION) + .filter(|run| { + run.finished_at.saturating_sub(run.started_at) + >= self.timing.hide_runs_shorter_than + }) .collect(), running, palette: self.palette, @@ -87,7 +97,9 @@ impl BootView<'_> { impl Widget for BootView<'_> { fn render(self, area: Rect, buf: &mut Buffer) { - let all_rows = self.state.tree_rows(); + let all_rows = self + .state + .tree_rows(self.now.saturating_sub(self.timing.keep_finished_units_for)); let pending_count = all_rows.len(); let pruned_rows = fold_chains(fit_to_height(all_rows.clone(), 0)); let header = Header { @@ -107,6 +119,7 @@ impl Widget for BootView<'_> { rows: &pruned_rows, hidden: pending_count - shown_units(&pruned_rows), now: self.now, + hide_runs_shorter_than: self.timing.hide_runs_shorter_than, frame: self.frame, palette: self.palette, glyphs: self.glyphs, @@ -164,7 +177,15 @@ impl Widget for BootView<'_> { if heights.timeline > 0 { timeline.render(timeline_area, buf); } - footer.render(footer_area, buf); + match &self.password_prompt { + Some(asking) => PasswordBar { + asking, + palette: self.palette, + glyphs: self.glyphs, + } + .render(footer_area, buf), + None => footer.render(footer_area, buf), + } } } @@ -237,6 +258,7 @@ mod tests { BootView { state, palette: &Palette::default(), + timing: &Timing::default(), glyphs: &Glyphs::default(), now, origin: &BootOrigin { @@ -246,6 +268,7 @@ mod tests { kernel: "Linux 7.2.9".to_owned(), }, frame: 1, + password_prompt: None, }, frame.area(), ); @@ -386,7 +409,7 @@ mod tests { state.finish_job(3, JobResult::Failed, 1000 * MS); state.finish_job(4, JobResult::Done, 1000 * MS); state.finish_job(2, JobResult::Done, 1500 * MS); - let lines = render(&state, 3000 * MS, 110, 24); + let lines = render(&state, 5000 * MS, 110, 24); let screen = lines.join("\n"); assert!(lines[2].starts_with(" ├─ √ basic.target"), "{screen}"); assert!(lines[3].starts_with(" │ └─ [×] flaky"), "{screen}"); @@ -398,6 +421,44 @@ mod tests { assert!(!screen.contains("quick"), "{screen}"); } + #[test] + fn finished_units_linger_in_place_before_leaving() { + let mut state = BootState::new(Phase::Host); + state.set_root("multi-user.target".to_owned()); + [ + facts("multi-user.target", &["early.service", "late.service"]), + facts("early.service", &[]), + facts("late.service", &[]), + ] + .into_iter() + .zip(1..) + .for_each(|(unit, id)| { + let name = unit.name.clone(); + let activity = if name.ends_with(".service") { + running_since(Duration::ZERO) + } else { + Activity::default() + }; + state.track_unit(unit, activity); + state.queue_job(id, &name, JobKind::BringsUp, Duration::ZERO); + }); + state.finish_job(2, JobResult::Done, 3000 * MS); + let lingering = render(&state, 4000 * MS, 110, 24); + let screen = lingering.join("\n"); + assert!(lingering[3].starts_with(" ├─ [√] early"), "{screen}"); + assert!(lingering[4].starts_with(" └─ [/] late"), "{screen}"); + let gone = render(&state, 5500 * MS, 110, 24); + let tree: Vec<&String> = gone + .iter() + .take_while(|line| !line.contains(" timeline ")) + .collect(); + assert!( + tree.iter().all(|line| !line.contains("early")), + "{}", + gone.join("\n") + ); + } + #[test] fn only_running_units_carry_a_timer() { let lines = render(&boot_in_progress(), 12_400 * MS, 110, 24); diff --git a/src/view/prompt.rs b/src/view/prompt.rs new file mode 100644 index 0000000..14177bc --- /dev/null +++ b/src/view/prompt.rs @@ -0,0 +1,41 @@ +use ratatui::{ + buffer::Buffer, + layout::Rect, + style::Stylize, + text::Line, + widgets::{Paragraph, Widget}, +}; + +use super::rule; +use crate::{glyphs::Glyphs, palette::Palette}; + +pub struct PasswordPrompt<'a> { + pub message: &'a str, + pub input: String, + pub sent: bool, +} + +pub struct PasswordBar<'a> { + pub asking: &'a PasswordPrompt<'a>, + pub palette: &'a Palette, + pub glyphs: &'a Glyphs, +} + +impl Widget for PasswordBar<'_> { + fn render(self, area: Rect, buf: &mut Buffer) { + let status = if self.asking.sent { + format!(" checking{}", self.glyphs.ellipsis).fg(self.palette.waiting) + } else { + format!(" {}_", self.asking.input).fg(self.palette.text) + }; + Paragraph::new(Line::from(vec![ + self.asking.message.fg(self.palette.running).bold(), + status, + ])) + .block(rule( + self.palette, + Line::from(" password ".fg(self.palette.running)), + )) + .render(area, buf); + } +} diff --git a/src/view/tree.rs b/src/view/tree.rs index 0507121..a364a0d 100644 --- a/src/view/tree.rs +++ b/src/view/tree.rs @@ -9,10 +9,7 @@ use ratatui::{ }; use unicode_width::UnicodeWidthStr; -use super::{ - BRANCH, DURATION_WIDTH, ELAPSED, ENDED_TRUNK, LAST_BRANCH, NOTEWORTHY_DURATION, PASSING_TRUNK, - fit_width, -}; +use super::{BRANCH, DURATION_WIDTH, ELAPSED, ENDED_TRUNK, LAST_BRANCH, PASSING_TRUNK, fit_width}; use crate::{ glyphs::Glyphs, model::{RowStatus, TreeRow, UnitKind}, @@ -29,6 +26,7 @@ pub struct UnitTree<'a> { pub rows: &'a [TreeRow], pub hidden: usize, pub now: Duration, + pub hide_runs_shorter_than: Duration, pub frame: u64, pub palette: &'a Palette, pub glyphs: &'a Glyphs, @@ -105,7 +103,8 @@ impl UnitTree<'_> { (_, _, RowStatus::Failed) => Style::from(self.palette.failed).bold(), (_, UnitKind::Target, _) => self.palette.target.into(), (_, _, RowStatus::Running) => self.palette.text.into(), - (_, _, RowStatus::Waiting | RowStatus::Done) => self.palette.waiting.into(), + (_, _, RowStatus::Waiting) => self.palette.waiting.into(), + (_, _, RowStatus::Done) => self.palette.muted.into(), } } @@ -203,7 +202,7 @@ impl UnitTree<'_> { let timer = row .running_since .map(|since| self.now.saturating_sub(since)) - .filter(|running_for| *running_for >= NOTEWORTHY_DURATION) + .filter(|running_for| *running_for >= self.hide_runs_shorter_than) .map(|running_for| ELAPSED.unsigned_duration_to_string(&running_for)) .unwrap_or_default(); let style = self.label_style(row, stage);