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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ is on main, the release is published with that section as its notes (AGENTS.md,

- On Linux, running Orchard as root leaves the USB access rule for your
regular account in place.
- With the device named (`--ecid`, `--location`), other devices on USB no
longer hold the install or launch up: devices running m1n1 or Linux
elsewhere don't count, and the ibss route and checkra1n's start of iOS
go ahead beside them. checkra1n waits, and stops, while another device
it could take is in DFU, recovery or Pongo mode.

### Command line

Expand Down
10 changes: 9 additions & 1 deletion crates/cli/src/commands/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,15 @@ fn flow_options(access: Option<&str>, tool: &ToolFlags, busy_cpu: bool) -> Resul
let seconds = tool.port_reset.or_else(|| env("ORCHARD_PORT_RESET_SECONDS")?.parse::<f64>().ok().map(|s| s.clamp(0., 15.).round() as u8)).unwrap_or(10);
Ok(Some(orchard_flow::Options {
helper,
start: None,
// The route named with --boot (or its short forms, or ORCHARD_BOOT):
// the flow has to know it too, since it decides by it whether other
// devices on USB hold a start up (the ibss route is addressed).
start: orchard_runtime::flags::chosen_boot().or_else(|| env("ORCHARD_BOOT")).and_then(|b| match b.as_str() {
"ibss" => Some(orchard_flow::Start::Ibss),
"checkra1n" => Some(orchard_flow::Start::Checkra1n),
"palera1n" => Some(orchard_flow::Start::Palera1n),
_ => None,
}),
palera1n: if two { Palera1n::Two } else { Palera1n::Three },
port_reset: (seconds > 0).then_some(seconds),
busy_cpu: busy_cpu || orchard_runtime::flags::busy_cpu(),
Expand Down
15 changes: 14 additions & 1 deletion crates/flow/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1449,9 +1449,22 @@ fn step_inner(app: App, mut flow: Flow, event: Event) -> (Flow, Vec<Effect>) {
/// start of the device while other Apple devices are on USB.
fn route(flow: &mut Flow, effects: Vec<Effect>, out: &mut Vec<Effect>) {
let fetch = |assets: Vec<Asset>| assets.into_iter().map(Effect::Fetch);
// Starts that are addressed to the device itself don't wait for other
// devices to go: the ibss route (gaster's worker matches the ECID, chip
// and board, and everything after it goes to the device's port), and
// checkra1n's start of iOS, which waits by itself for the devices
// checkra1n could take (access_checkra1n::start_ios). palera1n and
// checkra1n as boot routes take the first device they find, and wait.
let own_start = flow.state.device().is_some_and(|d| rules::start(&flow.options, d, false) == Some(Start::Ibss));
let own_helper = flow.helper() == Some(Helper::Checkra1n);
for effect in effects {
let addressed = match effect {
Effect::BootIpadosWithOverlay(_) => own_helper,
Effect::BootInstallEnv(_) | Effect::ListEntries(_) => own_start,
_ => false,
};
match effect {
Effect::BootIpadosWithOverlay(_) | Effect::BootInstallEnv(_) | Effect::ListEntries(_) if !flow.others.is_empty() => {
Effect::BootIpadosWithOverlay(_) | Effect::BootInstallEnv(_) | Effect::ListEntries(_) if !flow.others.is_empty() && !addressed => {
if matches!(effect, Effect::BootIpadosWithOverlay(_)) {
out.extend(fetch(flow.assets.start(&[Asset::Overlay])));
}
Expand Down
198 changes: 172 additions & 26 deletions crates/runtime/src/access_checkra1n.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,30 +69,95 @@ fn on_host(mut error: Error, soc: &str, linux: bool) -> Error {

/// checkra1n's start on the device, and the SSH connection it brings; a
/// failure of either says what helps on this host.
fn start(executor: &Executor, soc: &str) -> Result<(String, Ssh)> {
let started = start_ios(executor).and_then(|udid| Ssh::open(&udid).map(|ssh| (udid, ssh)));
fn start(executor: &Executor, soc: &str, ecid: Option<&str>) -> Result<(String, Ssh)> {
let started = start_ios(executor, ecid).and_then(|udid| Ssh::open(&udid).map(|ssh| (udid, ssh)));
started.map_err(|e| on_host(e, soc, cfg!(target_os = "linux")))
}

/// The one device running iOS on USB, by its UDID.
fn udid() -> Result<Option<String>> {
let mut usb: Vec<_> = usbmux::devices(Path::new(usbmux::SOCKET))?.into_iter().filter(|d| d.usb).collect();
match usb.len() {
0 => Ok(None),
1 => Ok(Some(usb.remove(0).udid)),
_ => Err(fail("more than one device running iOS is connected; connect only the one to resize")),
}
/// The devices running iOS on USB, by their UDIDs.
fn udids() -> Result<Vec<String>> {
Ok(usbmux::devices(Path::new(usbmux::SOCKET))?.into_iter().filter(|d| d.usb).map(|d| d.udid).collect())
}

/// Whether checkra1n's SSH server greets on this device.
fn greets(udid: &str) -> bool {
let Ok(mut stream) = usbmux::connect(Path::new(usbmux::SOCKET), udid, SSH_PORT) else { return false };
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let mut greeting = [0u8; 4];
stream.read_exact(&mut greeting).is_ok() && &greeting == b"SSH-"
}

/// The device whose SSH server sends its greeting over the cable: that, not
/// checkra1n's exit, is the start having worked (its command line goes on
/// waiting for the next DFU device).
fn ssh_answers() -> Result<Option<String>> {
let Some(udid) = udid()? else { return Ok(None) };
let Ok(mut stream) = usbmux::connect(Path::new(usbmux::SOCKET), &udid, SSH_PORT) else { return Ok(None) };
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let mut greeting = [0u8; 4];
Ok((stream.read_exact(&mut greeting).is_ok() && &greeting == b"SSH-").then_some(udid))
///
/// With the target's ECID (`ecid`), other devices running iOS may stay
/// connected: only the device that tells this ECID over lockdown is asked
/// for the greeting, and nothing is sent to port 44 of any other. Without
/// an ECID there must be one device running iOS, as before.
fn ssh_answers(ecid: Option<&str>) -> Result<Option<String>> {
let mut usb = udids()?;
let udid = match ecid {
Some(wanted) => {
let is = |udid: &String| {
crate::lockdown::ask(Path::new(usbmux::SOCKET), udid).ok().and_then(|a| a.ecid).is_some_and(|e| crate::ecid_key(&e) == crate::ecid_key(wanted))
};
usb.into_iter().find(is)
}
None => match usb.len() {
0 => None,
1 => Some(usb.remove(0)),
_ => return Err(fail("more than one device running iOS is connected; connect only the one to resize, or name it with --ecid")),
},
};
Ok(udid.filter(|u| greets(u)))
}

/// The modes checkra1n takes a device in, or starts it from.
fn checkra1n_takes(mode: orchard_usb::Mode) -> bool {
matches!(mode, orchard_usb::Mode::Dfu | orchard_usb::Mode::Recovery | orchard_usb::Mode::Pongo)
}

/// The target's port in `listing`, what it is known by in the modes that
/// don't tell an ECID: the device in DFU mode with `ecid`, or, without an
/// ECID, the one device checkra1n could take (the target, as the route
/// has always required one there).
fn target_port(listing: &[orchard_usb::Device], ecid: Option<&str>) -> Option<String> {
match ecid {
Some(e) => listing
.iter()
.find(|d| d.mode == orchard_usb::Mode::Dfu && d.identity.ecid.as_deref().is_some_and(|k| crate::ecid_key(k) == crate::ecid_key(e)))
.map(|d| d.location.clone()),
None => {
let mut takeable = listing.iter().filter(|d| checkra1n_takes(d.mode));
match (takeable.next(), takeable.next()) {
(Some(d), None) => Some(d.location.clone()),
_ => None,
}
}
}
}

/// Other devices in `listing` checkra1n would take or disturb: it has no
/// way to be told which device it is for, and goes for any in DFU mode.
/// Recovery mode and Pongo count too (it starts devices from there). `ecid`
/// and `at` (the target's port) say which one is ours; the target itself is
/// never counted.
fn in_the_way(listing: &[orchard_usb::Device], ecid: Option<&str>, at: Option<&str>) -> Vec<String> {
let ours = |d: &orchard_usb::Device| match (d.identity.ecid.as_deref(), ecid) {
(Some(a), Some(b)) => crate::ecid_key(a) == crate::ecid_key(b),
_ => at.is_some_and(|at| d.location == at),
};
listing
.iter()
.filter(|d| checkra1n_takes(d.mode) && !ours(d))
.map(|d| format!("{} in {} mode at {}", d.product.clone().unwrap_or_else(|| "a device".into()), d.mode.as_str(), d.location))
.collect()
}

/// [`in_the_way`], on the devices on USB now.
fn in_checkra1ns_way(ecid: Option<&str>, at: Option<&str>) -> Vec<String> {
in_the_way(&orchard_usb::list().unwrap_or_default(), ecid, at)
}

/// usbmuxd is not running: on Linux it may start only once iOS is on USB.
Expand Down Expand Up @@ -128,7 +193,23 @@ fn timed_out(log: &str, usbmuxd_down: Option<Error>) -> Error {

/// Runs checkra1n until the device's SSH server answers, and returns the
/// device's UDID.
fn start_ios(executor: &Executor) -> Result<String> {
fn start_ios(executor: &Executor, ecid: Option<&str>) -> Result<String> {
// The target's port: what it is known by in the modes that don't tell
// an ECID. Without it, the target would count as a device in the way.
let at = target_port(&orchard_usb::list().unwrap_or_default(), ecid);
// checkra1n takes any device in DFU mode: it only starts once ours is
// the only one it could take. Others are waited for, a minute at most.
let clear = Instant::now() + Duration::from_secs(60);
loop {
let others = in_checkra1ns_way(ecid, at.as_deref());
if others.is_empty() {
break;
}
if Instant::now() > clear {
return Err(fail(format!("checkra1n would also take another device ({}); it can't be told which one to start. Start again once that device has left DFU and recovery mode", others.join(", "))));
}
std::thread::sleep(Duration::from_secs(1));
}
// 0.12.4: the build whose start brings its loader and SSH server.
let (pin, release) = crate::flags::checkra1n_jailbreak_pin().ok_or_else(|| Error::new(Code::NotFound, "checkra1n publishes no build for this computer"))?;
let checkra1n = executor.palera1n(pin, release)?;
Expand Down Expand Up @@ -167,16 +248,38 @@ fn start_ios(executor: &Executor) -> Result<String> {
let until = Instant::now() + BOOT;
let read_log = || std::fs::read(&log_path).map(|t| String::from_utf8_lossy(&t).into_owned()).unwrap_or_default();
let (mut seen, mut changed) = (0usize, Instant::now());
// Once checkra1n says it is done with our device it is stopped: left
// running, it waits for the next device in DFU mode and takes it.
let mut done = false;
let mut ticks = 0u32;
let outcome = loop {
std::thread::sleep(Duration::from_secs(3));
let usbmuxd_down = match ssh_answers() {
std::thread::sleep(Duration::from_secs(1));
ticks += 1;
if !done {
// Another device came into its reach while it runs: stop it at once.
let others = in_checkra1ns_way(ecid, at.as_deref());
if !others.is_empty() {
break Err(fail(format!("another device came into DFU or recovery mode while checkra1n ran ({}); checkra1n was stopped so that it does not start that one", others.join(", "))));
}
if std::fs::read_to_string(&log_path).is_ok_and(|l| l.contains("All Done")) {
done = true;
let _ = child.kill();
let _ = child.wait();
}
}
if ticks % 3 != 0 {
continue;
}
let usbmuxd_down = match ssh_answers(ecid) {
Ok(Some(udid)) => break Ok(udid),
Err(e) if !not_running(&e) => break Err(e),
waiting => waiting.err(),
};
if let Ok(Some(status)) = child.try_wait() {
if !status.success() {
break Err(fail(format!("checkra1n failed ({status}); its log: {}", log_path.display())));
if !done {
if let Ok(Some(status)) = child.try_wait() {
if !status.success() {
break Err(fail(format!("checkra1n failed ({status}); its log: {}", log_path.display())));
}
}
}
let text = read_log();
Expand Down Expand Up @@ -404,9 +507,9 @@ const COMPANION: &str = "/private/var/OrchardCompanion";

/// Starts iOS on the device in DFU mode, on a chip with `soc`, with
/// checkra1n and the companion's `helper` there, taking `token` and saying
/// `system` for what is installed.
pub fn companion(executor: &Executor, soc: &str, helper: &[u8], token: &str, system: &str) -> Result<Companion> {
let (udid, ssh) = start(executor, soc)?;
/// `system` for what is installed. With `ecid`, only that device is started.
pub fn companion(executor: &Executor, soc: &str, ecid: Option<&str>, helper: &[u8], token: &str, system: &str) -> Result<Companion> {
let (udid, ssh) = start(executor, soc, ecid)?;
let (program, pidfile) = (format!("{COMPANION}/orchard-companion"), format!("{COMPANION}/helper.pid"));
ssh.must(
&format!("if [ -f {pidfile} ]; then kill \"$(cat {pidfile})\" 2>/dev/null; fi; rm -rf {COMPANION}; umask 077; mkdir -p {COMPANION}"),
Expand Down Expand Up @@ -485,7 +588,7 @@ pub fn run(executor: &Executor, soc: &str, app: &Older, say: &dyn Fn(&str), done
/// One checkra1n start and one session.
fn round(executor: &Executor, soc: &str, app: &Older, say: &dyn Fn(&str), done: &mut dyn FnMut(&dyn Fn() -> bool) -> Result<Asked>) -> Result<Asked> {
say("Starting iOS with checkra1n");
let (udid, ssh) = start(executor, soc)?;
let (udid, ssh) = start(executor, soc, None)?;
say("iOS is up; copying Resize APFS");
ssh.must(&format!("{}; {}", leftover(OLD_SESSION, OLD_APP), leftover(SESSION, APP)), "Removing an earlier session", None)?;
// 755: the app runs as mobile and must read its bundle; the helper trusts
Expand Down Expand Up @@ -558,6 +661,49 @@ fn round(executor: &Executor, soc: &str, app: &Older, say: &dyn Fn(&str), done:
mod tests {
use super::*;

fn usb(mode: orchard_usb::Mode, location: &str, ecid: Option<&str>) -> orchard_usb::Device {
orchard_usb::Device {
mode,
system: None,
location: location.into(),
product: None,
identity: orchard_usb::Identity { ecid: ecid.map(str::to_owned), ..Default::default() },
}
}

#[test]
fn without_an_ecid_the_lone_device_in_dfu_mode_is_the_target() {
use orchard_usb::Mode;
// orchard resize on iOS 12 to 14 names no device: the one in DFU
// mode is the target, also once it is in Pongo or recovery mode.
let listing = [usb(Mode::Dfu, "0x1100000", None), usb(Mode::Normal, "0x1200000", Some("0xAA"))];
let at = target_port(&listing, None);
assert_eq!(at.as_deref(), Some("0x1100000"));
assert!(in_the_way(&listing, None, at.as_deref()).is_empty());
assert!(in_the_way(&[usb(Mode::Pongo, "0x1100000", None)], None, at.as_deref()).is_empty());
// A second device checkra1n could take still counts.
let two = [usb(Mode::Dfu, "0x1100000", None), usb(Mode::Recovery, "0x1300000", None)];
assert_eq!(target_port(&two, None), None);
assert_eq!(in_the_way(&two, None, at.as_deref()).len(), 1);
}

#[test]
fn with_an_ecid_only_other_devices_checkra1n_could_take_count() {
use orchard_usb::Mode;
let listing = [
usb(Mode::Dfu, "0x1100000", Some("0x0011223344556677")),
usb(Mode::Dfu, "0x1200000", Some("0x00AABBCCDDEEFF00")),
usb(Mode::Normal, "0x1300000", Some("0x0099887766554433")),
usb(Mode::M1n1, "0x1400000", None),
];
let at = target_port(&listing, Some("11223344556677"));
assert_eq!(at.as_deref(), Some("0x1100000"));
let way = in_the_way(&listing, Some("11223344556677"), at.as_deref());
assert_eq!(way, ["a device in dfu mode at 0x1200000"]);
// The target in Pongo, which tells no ECID, is known by its port.
assert!(in_the_way(&[usb(Mode::Pongo, "0x1100000", None)], Some("11223344556677"), at.as_deref()).is_empty());
}

#[test]
fn device_paths_are_quoted_and_executables_told_apart() {
assert_eq!(quote("/a b/it's"), "'/a b/it'\\''s'");
Expand Down
Loading
Loading