Skip to content
Open
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ 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.
- On iOS 12 to 14, an installer started again while iOS runs as
checkra1n started it goes on at the split, without another round
through DFU 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 @@ -179,7 +179,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 @@ -1172,9 +1172,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
148 changes: 122 additions & 26 deletions crates/runtime/src/access_checkra1n.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,30 +69,65 @@ 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)))
}

/// Other devices 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.
fn in_checkra1ns_way(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),
};
orchard_usb::list()
.unwrap_or_default()
.into_iter()
.filter(|d| matches!(d.mode, orchard_usb::Mode::Dfu | orchard_usb::Mode::Recovery | orchard_usb::Mode::Pongo) && !ours(d))
.map(|d| format!("{} in {} mode at {}", d.product.clone().unwrap_or_else(|| "a device".into()), d.mode.as_str(), d.location))
.collect()
}

/// usbmuxd is not running: on Linux it may start only once iOS is on USB.
Expand Down Expand Up @@ -128,7 +163,26 @@ 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, while it is in DFU mode: what it is known by in
// the modes that don't tell an ECID.
let at: Option<String> = orchard_usb::list().unwrap_or_default().into_iter().find_map(|d| {
let named = ecid.is_some_and(|e| d.identity.ecid.as_deref().is_some_and(|k| crate::ecid_key(k) == crate::ecid_key(e)));
(d.mode == orchard_usb::Mode::Dfu && named).then(|| d.location.clone())
});
// 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 +221,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 +480,29 @@ 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)?;
put_helper(udid, ssh, helper, token, system)
}

/// The UDID of the device with this ECID when iOS on it already runs as
/// checkra1n started it (its SSH server answers): an installer started again
/// goes on from there, without another round through DFU mode.
pub fn running(ecid: &str) -> Option<String> {
ssh_answers(Some(ecid)).ok().flatten()
}

/// Puts the companion's helper on a device checkra1n has started and starts
/// it. A helper an earlier session left is stopped first; a split it was
/// doing is in the engine's journal, and the new helper goes on with it.
pub fn companion_on(udid: String, helper: &[u8], token: &str, system: &str) -> Result<Companion> {
let ssh = Ssh::open(&udid)?;
put_helper(udid, ssh, helper, token, system)
}

/// The helper onto the device over `ssh`, and started there.
fn put_helper(udid: String, ssh: Ssh, helper: &[u8], token: &str, system: &str) -> Result<Companion> {
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 +581,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
Loading
Loading