Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ is on main, the release is published with that section as its notes (AGENTS.md,

### Installer and launcher

- The terminal installer shows 'Reconnect the cable' while you type your
password, instead of waiting silently.

- On Linux, a start through palera1n or checkra1n begins only once the
computer has given your account access to the device, so the tool is no
longer refused it in its first moment. When a tool is refused the device
Expand Down
211 changes: 188 additions & 23 deletions crates/cli/src/commands/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//! (exit 5) naming the flag. With --json each step is one JSON object per line
//! on stdout; the words for people go to the terminal.
use crate::args::Global;
use super::term::{bar, gradient, s, Span, Term, BLUE, FG, GREEN, MUTED, RED, SUB, TITLE, TRACK, YELLOW};
use super::term::{bar, gradient, s, KeyReader, Span, Term, Typed, BLUE, FG, GREEN, MUTED, RED, SUB, TITLE, TRACK, YELLOW};
use orchard_flow::recovery::{self, Phase, Run};
use orchard_flow::{Again, App, Event, Flow, Layout, Link, Sequence, State, UsbMode, MIN_OMARCHY_GB};
use orchard_runtime::disk_file::{Clash, DiskFile};
Expand All @@ -17,7 +17,7 @@ use std::io::BufRead;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, TryRecvError};
use std::time::{Duration, Instant};

/// Outcomes, as the exit status.
Expand Down Expand Up @@ -1491,16 +1491,21 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode {
let mut disk_said = false;
// After the end block, while the started system may still say it is ready.
let mut ready_wait: Option<Instant> = None;
// The newest flow the account's questions saw, not yet gone through here.
let mut followed: Option<Flow> = None;
loop {
out.term.tick();
shared.tick(&mut out);
for event in shared.keys(&mut out) {
send(event);
}
let flow = match rx.recv_timeout(Duration::from_millis(100)) {
Ok(flow) => Some(flow),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => return finish(&mut out, Exit::Failed, "driver", "the installer stopped"),
let flow = match followed.take() {
Some(flow) => Some(flow),
None => match rx.recv_timeout(Duration::from_millis(100)) {
Ok(flow) => Some(flow),
Err(RecvTimeoutError::Timeout) => None,
Err(RecvTimeoutError::Disconnected) => return finish(&mut out, Exit::Failed, "driver", "the installer stopped"),
},
};
let interrupts = INTERRUPTS.load(Ordering::SeqCst);
let busy = shared.last == "splitting" || shared.last == "installing";
Expand Down Expand Up @@ -1906,16 +1911,52 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode {
}
// The name this device gets for plain ssh, where it is certain already.
let ssh_name = flow.state.device().and_then(|d| orchard_runtime::ssh_config::coming_for(&handle.executor, d));
let Some(account) = make_account(&mut out, &user, password.clone(), pin.clone().filter(|_| wants_pin), wants_pin, ssh_name.as_deref(), args) else {
send(Event::Quit);
std::thread::sleep(Duration::from_secs(1));
return finish(&mut out, Exit::NeedsInput, "needs-input", if wants_pin { "--password-file/--pin-file" } else { "--password-file" });
// The device starts meanwhile: in a terminal, what it says
// shows above every question still asked (one a file
// answered isn't asked).
let mut follow = |out: &mut Out| loop {
match rx.try_recv() {
Ok(next) => {
let said = follow_flow(out, &mut shared, &next);
followed = Some(next);
if !matches!(said, Follow::Go) {
return said;
}
}
Err(TryRecvError::Empty) => return Follow::Go,
Err(TryRecvError::Disconnected) => return Follow::Exit(finish(out, Exit::Failed, "driver", "the installer stopped")),
}
};
let following = out.term.tty;
let asked = make_account(&mut out, &user, password.clone(), pin.clone().filter(|_| wants_pin), wants_pin, ssh_name.as_deref(), args, following.then_some(&mut follow as &mut dyn FnMut(&mut Out) -> Follow));
let account = match asked {
Ok(account) => account,
Err(Stop::NeedsInput) => {
send(Event::Quit);
std::thread::sleep(Duration::from_secs(1));
return finish(&mut out, Exit::NeedsInput, "needs-input", if wants_pin { "--password-file/--pin-file" } else { "--password-file" });
}
// Starting it didn't work: DFU mode again, and the
// questions again when the flow is back here.
Err(Stop::Left) => {
account_sent = false;
continue;
}
Err(Stop::Exit(code)) => return code,
};
ssh_chosen = account.ssh;
send(Event::EditAccount(account));
if env.is_none() {
let booting = match &followed {
Some(newer) => matches!(newer.state, State::CreateAccount { env: None, .. }),
None => env.is_none(),
};
if booting {
out.term.live_restart(vec![s(orchard_flow::for_device("Your iPad is getting ready"), SUB)]);
}
// What came meanwhile goes on from the newest flow.
if followed.is_some() {
continue;
}
}
// The device is ready; the install goes on once the
// system's files are there too.
Expand Down Expand Up @@ -2079,19 +2120,83 @@ pub fn install(global: &Global, args: &InstallArgs) -> ExitCode {
}
}

/// Why the account's questions ended without an account.
enum Stop {
/// Without a terminal, an answer no flag gave.
NeedsInput,
/// The flow left the account's step (starting the device didn't work).
Left,
/// The run ends (the flow said so meanwhile).
Exit(ExitCode),
}

/// What following the flow says while a question is open.
enum Follow {
Go,
Left,
Exit(ExitCode),
}

/// A flow that came while the account is typed: what the run says for it
/// goes above the question (a stalled start rings the bell too), and once
/// the flow has left the account's step the question gives way.
fn follow_flow(out: &mut Out, shared: &mut Shared, flow: &Flow) -> Follow {
if !matches!(flow.state, State::CreateAccount { .. }) {
return Follow::Left;
}
let stalled = shared.stalled;
if let Next::Exit(code) = shared.see(out, flow) {
return Follow::Exit(code);
}
if shared.stalled && !stalled {
out.term.bell();
}
Follow::Go
}

/// A question's answer, read key by key while FOLLOW keeps up with the
/// flow; as `Term::ask` without FOLLOW. None without a terminal.
fn ask(out: &mut Out, prompt: Vec<Span>, secret: bool, follow: &mut Option<&mut dyn FnMut(&mut Out) -> Follow>) -> Result<Option<String>, Stop> {
let Some(follow) = follow.as_mut().filter(|_| out.term.tty) else {
return Ok(out.term.ask(prompt, secret));
};
let Some(keys) = KeyReader::start() else {
return Ok(out.term.ask(prompt, secret));
};
out.term.open_prompt(prompt, secret);
let ended = loop {
match keys.next(Duration::from_millis(100)) {
Typed::Byte(byte) if out.term.prompt_key(byte) => break Ok(()),
// The terminal gone: what was typed, as a line read to its end.
Typed::Gone => break Ok(()),
Typed::Byte(_) | Typed::Nothing => {}
}
match follow(out) {
Follow::Go => {}
Follow::Left => break Err(Stop::Left),
Follow::Exit(code) => break Err(Stop::Exit(code)),
}
};
let typed = out.term.close_prompt(ended.is_ok());
drop(keys);
ended.map(|()| Some(typed))
}

/// The account from the flags or the prompts (T.6), checked as the window checks it;
/// the PIN only where the release asks for one (WANTS_PIN).
fn make_account(out: &mut Out, user: &str, password: Option<String>, pin: Option<String>, wants_pin: bool, ssh_name: Option<&str>, args: &InstallArgs) -> Option<orchard_flow::Account> {
/// the PIN only where the release asks for one (WANTS_PIN). FOLLOW keeps up
/// with the flow while a question is open.
#[allow(clippy::too_many_arguments)]
fn make_account(out: &mut Out, user: &str, password: Option<String>, pin: Option<String>, wants_pin: bool, ssh_name: Option<&str>, args: &InstallArgs, mut follow: Option<&mut dyn FnMut(&mut Out) -> Follow>) -> Result<orchard_flow::Account, Stop> {
out.term.blank();
out.heading("Create your account", Some(orchard_flow::for_device("Your iPad is getting ready in the meantime.").into()));
if cfg!(target_os = "macos") {
out.warn(orchard_flow::ALLOW_ACCESSORY);
}
out.term.blank();
out.term.line(vec![s(format!(" {:<19}", "Username"), SUB), s(user, FG)]);
let password = secret_pair(out, "Password", "Repeat password", "--password-file", password, "password", |p| (p.chars().count() >= 8).then_some(()).ok_or("The password needs 8 or more characters"))?;
let password = secret_pair(out, "Password", "Repeat password", "--password-file", password, "password", |p| (p.chars().count() >= 8).then_some(()).ok_or("The password needs 8 or more characters"), &mut follow)?;
let pin = if wants_pin {
secret_pair(out, "Lock screen PIN", "Repeat PIN", "--pin-file", pin, "PIN", |p| (p.len() == 6 && p.bytes().all(|b| b.is_ascii_digit())).then_some(()).ok_or("The PIN needs exactly 6 digits"))?
secret_pair(out, "Lock screen PIN", "Repeat PIN", "--pin-file", pin, "PIN", |p| (p.len() == 6 && p.bytes().all(|b| b.is_ascii_digit())).then_some(()).ok_or("The PIN needs exactly 6 digits"), &mut follow)?
} else {
String::new()
};
Expand All @@ -2101,35 +2206,39 @@ fn make_account(out: &mut Out, user: &str, password: Option<String>, pin: Option
false
} else {
out.term.blank();
let answer = out.term.ask(vec![s(" Allow SSH from this computer? ", FG), s("[y/N] ", MUTED)], false);
let answer = ask(out, vec![s(" Allow SSH from this computer? ", FG), s("[y/N] ", MUTED)], false, &mut follow)?;
let yes = matches!(answer.as_deref().map(str::trim), Some("y" | "Y" | "yes"));
if yes {
out.muted(format!("Adds this computer's keys: {} over the USB cable, no password.", orchard_flow::ssh_command(user, ssh_name)));
}
yes
};
Some(orchard_flow::Account { username: user.to_owned(), password: password.clone(), password_again: password, pin: pin.clone(), pin_again: pin, ssh, pin_asked: wants_pin })
Ok(orchard_flow::Account { username: user.to_owned(), password: password.clone(), password_again: password, pin: pin.clone(), pin_again: pin, ssh, pin_asked: wants_pin })
}

/// A password or PIN from its flag, or asked twice until both match and CHECK passes.
fn secret_pair(out: &mut Out, label: &str, again: &str, flag: &str, given: Option<String>, what: &str, check: impl Fn(&str) -> Result<(), &'static str>) -> Option<String> {
#[allow(clippy::too_many_arguments)]
fn secret_pair(out: &mut Out, label: &str, again: &str, flag: &str, given: Option<String>, what: &str, check: impl Fn(&str) -> Result<(), &'static str>, follow: &mut Option<&mut dyn FnMut(&mut Out) -> Follow>) -> Result<String, Stop> {
if let Some(v) = given {
out.term.line(vec![s(format!(" {label:<19}"), SUB), s(format!("from {flag}"), MUTED)]);
return Some(v);
return Ok(v);
}
loop {
let a = out.term.ask(vec![s(format!(" {label:<19}"), SUB)], true);
let b = a.as_ref().and_then(|_| out.term.ask(vec![s(format!(" {again:<19}"), SUB)], true));
let a = ask(out, vec![s(format!(" {label:<19}"), SUB)], true, follow)?;
let b = match a {
Some(_) => ask(out, vec![s(format!(" {again:<19}"), SUB)], true, follow)?,
None => None,
};
match (a, b) {
(Some(a), Some(b)) if a != b => out.warn(format!("The {what}s don't match. Once more:")),
(Some(a), Some(_)) => match check(&a) {
Ok(()) => return Some(a),
Ok(()) => return Ok(a),
Err(why) => out.warn(format!("{why}. Once more:")),
},
_ => {
out.event(json!({"event": "needs", "action": "input", "flag": flag}));
out.fail(format!("Run again with {flag} FILE (or - for stdin)"));
return None;
return Err(Stop::NeedsInput);
}
}
}
Expand Down Expand Up @@ -2400,6 +2509,62 @@ mod tests {
assert!(install_args(&["omarchy-a", "--kernel", "linux", "--demo"]).is_none());
}

/// What the terminal was given, shared with the test.
#[derive(Clone, Default)]
struct Screen(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

impl std::io::Write for Screen {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}

impl Screen {
fn take(&self) -> String {
String::from_utf8(std::mem::take(&mut *self.0.lock().unwrap())).unwrap()
}
}

#[test]
fn a_stalled_start_while_typing_shows_above_the_question_and_keeps_what_was_typed() {
use orchard_flow::{Account, Device, DeviceId, Model, OsVersion, Routes, Support};
let screen = Screen::default();
let mut out = Out { term: Term::to(Box::new(screen.clone())), json: false };
let cli = <crate::args::Cli as clap::Parser>::try_parse_from(["orchard", "install", "omarchy-a"]).unwrap();
let mut shared = Shared::new(App::Installer, 0, &cli.global);
let device = Device { id: DeviceId("e".into()), board: "j71b".into(), name: "iPad".into(), model: Model::IpadHome, sequence: Sequence::HomePower, support: Support::Supported, os: OsVersion::Unknown, routes: Routes::default() };
let account = Flow { state: State::CreateAccount { device: device.clone(), account: Account::default(), env: None, erase_approved: false, slow: false }, ..Flow::new() };
shared.see(&mut out, &account);
out.term.open_prompt(vec![s(" Password ", SUB)], true);
for &b in b"abc" {
assert!(!out.term.prompt_key(b));
}
screen.take();
// palera1n stalls: the hint above, the bell, the question again with its dots.
let stalled = Flow { boot_stalled: true, ..account.clone() };
assert!(matches!(follow_flow(&mut out, &mut shared, &stalled), Follow::Go));
let shown = screen.take();
let hint = shown.find("! Reconnect the cable at your ").expect(&shown);
let bell = shown.find('\x07').expect(&shown);
assert!(shown.starts_with("\r\x1b[2K"), "{shown:?}");
assert!(hint < bell && shown.replace('\x07', "").ends_with("\n Password •••"), "{shown:?}");
// Once: the same stall again says nothing.
assert!(matches!(follow_flow(&mut out, &mut shared, &stalled), Follow::Go));
assert_eq!(screen.take(), "");
assert!(out.term.prompt_key(b'\r'));
assert_eq!(out.term.close_prompt(true), "abc");
// Starting it didn't work: the question gives way to DFU mode again.
out.term.open_prompt(vec![s(" Password ", SUB)], true);
let failed = orchard_flow::step(App::Installer, account, Event::ChainFailed("palera1n: Unable to perform checkm8".into())).0;
assert!(matches!(follow_flow(&mut out, &mut shared, &failed), Follow::Left));
assert_eq!(out.term.close_prompt(false), "");
assert!(screen.take().ends_with("\r\x1b[2K"));
}

#[test]
fn a_layer_built_here_is_installed_from_its_file() {
let layer = orchard_build::layer::Layer {
Expand Down
Loading
Loading