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
154 changes: 82 additions & 72 deletions companion/Helper/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,27 +81,29 @@ final class Launcher: @unchecked Sendable {
var registered = embedded != nil, lastRegister = Date.distantPast
while true {
Thread.sleep(forTimeInterval: 1)
lock.lock(); let open = wanted; lock.unlock()
if !registered {
if installed() {
registered = true
log("app registered with iPadOS")
} else if FileManager.default.fileExists(atPath: appPath + "/OrchardCompanion"),
Date().timeIntervalSince(lastRegister) > 3 {
lastRegister = Date()
log("registering the app: uicache exit \(spawn([uicache, "-p", appPath]))")
autoreleasepool {
lock.lock(); let open = wanted; lock.unlock()
if !registered {
if installed() {
registered = true
log("app registered with iPadOS")
} else if FileManager.default.fileExists(atPath: appPath + "/OrchardCompanion"),
Date().timeIntervalSince(lastRegister) > 3 {
lastRegister = Date()
log("registering the app: uicache exit \(spawn([uicache, "-p", appPath]))")
}
return
}
continue
}
guard open else { continue }
if oc_running(process) != 0 {
log("app running")
lock.lock(); wanted = false; lock.unlock()
continue
guard open else { return }
if oc_running(process) != 0 {
log("app running")
lock.lock(); wanted = false; lock.unlock()
return
}
let viaLS = openWithLaunchServices()
let viaSB = viaLS ? 0 : oc_springboard_launch(bundleID)
log("opening the app: LaunchServices \(viaLS), SpringBoard \(viaSB)")
}
let viaLS = openWithLaunchServices()
let viaSB = viaLS ? 0 : oc_springboard_launch(bundleID)
log("opening the app: LaunchServices \(viaLS), SpringBoard \(viaSB)")
}
}
}
Expand Down Expand Up @@ -264,18 +266,22 @@ final class Server: @unchecked Sendable {
launcher.run()
Thread.detachNewThread { [status] in
while true {
status.rewrite()
autoreleasepool {
status.rewrite()
}
Thread.sleep(forTimeInterval: 1)
}
}
// The engine's own loop: inspect, then publish (its own thread; the
// engine is synchronous and lock-guarded, iOS 12 has no async).
Thread.detachNewThread { [self] in
while true {
engine.refresh()
let snapshot = try? engine.snapshot()
publish(snapshot)
status.update(snapshot)
autoreleasepool {
engine.refresh()
let snapshot = try? engine.snapshot()
publish(snapshot)
status.update(snapshot)
}
Thread.sleep(forTimeInterval: 1)
}
}
Expand Down Expand Up @@ -346,58 +352,62 @@ final class Server: @unchecked Sendable {
var buffer = Data()
var authenticated = false
while let line = readLine(fd, &buffer) {
guard let object = try? JSONSerialization.jsonObject(with: line) as? [String: Any],
object.count == 1, let (name, body) = object.first else { return }
let args = body as? [String: Any] ?? [:]
if !authenticated {
guard name == "hello", let given = args["token"] as? String,
constantTimeEqual(given.lowercased(), token) else { return }
authenticated = true
adopt(fd)
let keepOpen: Bool = autoreleasepool {
guard let object = try? JSONSerialization.jsonObject(with: line) as? [String: Any],
object.count == 1, let (name, body) = object.first else { return false }
let args = body as? [String: Any] ?? [:]
if !authenticated {
guard name == "hello", let given = args["token"] as? String,
constantTimeEqual(given.lowercased(), token) else { return false }
authenticated = true
adopt(fd)
status.pinged()
// The app shows the computer as connected right away.
status.rewrite()
log("the computer connected")
launcher.want()
reply(fd, ok: ["protocol": protocolVersion, "ecid": ecid() as Any? ?? NSNull(), "machine": machine()])
return true
}
status.pinged()
// The app shows the computer as connected right away.
status.rewrite()
log("the computer connected")
launcher.want()
reply(fd, ok: ["protocol": protocolVersion, "ecid": ecid() as Any? ?? NSNull(), "machine": machine()])
continue
}
status.pinged()
do {
switch name {
case "ping": reply(fd, ok: [:])
case "restart":
// The installer quit: back to normal iPadOS.
guard engine.idleForRestart else { throw ResizeError("The storage is being split; restart later.") }
reply(fd, ok: [:])
log("restarting for the installer")
Thread.detachNewThread {
Thread.sleep(forTimeInterval: 0.5)
// The kernel's own restart (no tool needed: works on any route).
log("restart: \(oc_restart())")
do {
switch name {
case "ping": reply(fd, ok: [:])
case "restart":
// The installer quit: back to normal iPadOS.
guard engine.idleForRestart else { throw ResizeError("The storage is being split; restart later.") }
reply(fd, ok: [:])
log("restarting for the installer")
Thread.detachNewThread {
Thread.sleep(forTimeInterval: 0.5)
// The kernel's own restart (no tool needed: works on any route).
log("restart: \(oc_restart())")
}
case "log":
// The helper's own log (timings from boot to the app), its last 64 KiB.
let data = FileManager.default.contents(atPath: logPath) ?? Data()
reply(fd, ok: ["text": String(decoding: data.suffix(65536), as: UTF8.self)])
case "snapshot": try reply(fd, okJSON: latestSnapshot())
case "split":
guard let bytes = (args["apfs_bytes"] as? NSNumber)?.int64Value,
let revisionText = args["revision"] as? String, let revision = UUID(uuidString: revisionText)
else { throw ResizeError("A split needs apfs_bytes and the layout's revision.") }
// Partitions after APFS the user approved erasing, when the size needs their space.
let replacing = (args["replacing"] as? [String] ?? []).compactMap(UUID.init(uuidString:))
guard replacing.count == (args["replacing"] as? [String] ?? []).count else { throw ResizeError("replacing holds an invalid partition id.") }
let plan = try engine.plan(PlanRequest(revision: revision, requestedBytes: bytes, createLinux: false, replacing: replacing))
let data = try JSONEncoder().encode(engine.start(StartRequest(planID: plan.id, requestID: UUID())))
try reply(fd, okJSON: data)
// The copy shows the running split from now on.
publish(try? engine.snapshot())
default: throw ResizeError("Unknown request.")
}
case "log":
// The helper's own log (timings from boot to the app), its last 64 KiB.
let data = FileManager.default.contents(atPath: logPath) ?? Data()
reply(fd, ok: ["text": String(decoding: data.suffix(65536), as: UTF8.self)])
case "snapshot": try reply(fd, okJSON: latestSnapshot())
case "split":
guard let bytes = (args["apfs_bytes"] as? NSNumber)?.int64Value,
let revisionText = args["revision"] as? String, let revision = UUID(uuidString: revisionText)
else { throw ResizeError("A split needs apfs_bytes and the layout's revision.") }
// Partitions after APFS the user approved erasing, when the size needs their space.
let replacing = (args["replacing"] as? [String] ?? []).compactMap(UUID.init(uuidString:))
guard replacing.count == (args["replacing"] as? [String] ?? []).count else { throw ResizeError("replacing holds an invalid partition id.") }
let plan = try engine.plan(PlanRequest(revision: revision, requestedBytes: bytes, createLinux: false, replacing: replacing))
let data = try JSONEncoder().encode(engine.start(StartRequest(planID: plan.id, requestID: UUID())))
try reply(fd, okJSON: data)
// The copy shows the running split from now on.
publish(try? engine.snapshot())
default: throw ResizeError("Unknown request.")
} catch {
reply(fd, error: error.localizedDescription)
}
} catch {
reply(fd, error: error.localizedDescription)
return true
}
if !keepOpen { return }
}
}

Expand Down
14 changes: 14 additions & 0 deletions crates/runtime/src/overlay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,12 @@ fn job() -> Value {
d.insert("AbandonProcessGroup".into(), true.into());
d.insert("StandardOutPath".into(), "/cores/orchard-companion.log".into());
d.insert("StandardErrorPath".into(), "/cores/orchard-companion.err".into());
// Match resize-apfs's helper plist so iPadOS Jetsam does not kill the
// daemon at its default unlisted-daemon cap (~18 MB) during long shrinks.
let mut jetsam = plist::Dictionary::new();
jetsam.insert("JetsamPriority".into(), 160.into());
jetsam.insert("JetsamMemoryLimit".into(), 256.into());
d.insert("JetsamProperties".into(), Value::Dictionary(jetsam));
Value::Dictionary(d)
}

Expand Down Expand Up @@ -466,4 +472,12 @@ mod tests {
bad.app.push(("../escape".into(), vec![], 0o644));
assert!(build(&palera1n, &bad, &Identity::random()).is_err());
}

#[test]
fn the_helper_job_sets_jetsam_properties() {
let dict = job().into_dictionary().expect("job plist dictionary");
let jetsam = dict.get("JetsamProperties").and_then(Value::as_dictionary).expect("JetsamProperties");
assert_eq!(jetsam.get("JetsamPriority").and_then(Value::as_signed_integer), Some(160));
assert_eq!(jetsam.get("JetsamMemoryLimit").and_then(Value::as_signed_integer), Some(256));
}
}
38 changes: 22 additions & 16 deletions ios-installer/Helper/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ final class Resizer: @unchecked Sendable {
func run() {
Thread.detachNewThread { [self] in
while true {
engine.refresh()
report()
autoreleasepool {
engine.refresh()
report()
}
Thread.sleep(forTimeInterval: 1)
}
}
Expand Down Expand Up @@ -174,21 +176,25 @@ final class Server: @unchecked Sendable {
guard raf_peer_uid(fd, &uid) == 0, uid == mobileUID || uid == 0,
uid == 0 || appExecutable.map({ raf_peer_is_executable(fd, $0) == 1 }) == true else { return }
while let frame = try? LocalFrames.read(from: fd) {
let refused = { (message: String) in
(try? JSONSerialization.data(withJSONObject: ["error": ["message": message]])) ?? Data()
}
guard let object = try? JSONSerialization.jsonObject(with: frame) as? [String: Any],
let given = object["token"] as? String, constantTimeEqual(given, token) else {
try? LocalFrames.write(refused("Invalid helper credentials."), to: fd)
return
}
served.lock(); wasServed = true; served.unlock()
let answer: Data = String(decoding: frame, as: UTF8.self).withCString { request in
guard let raw = oi_request(request) else { return refused("The installer did not answer.") }
defer { oi_free(raw) }
return Data(String(cString: raw).utf8)
let keepOpen: Bool = autoreleasepool {
let refused = { (message: String) in
(try? JSONSerialization.data(withJSONObject: ["error": ["message": message]])) ?? Data()
}
guard let object = try? JSONSerialization.jsonObject(with: frame) as? [String: Any],
let given = object["token"] as? String, constantTimeEqual(given, token) else {
try? LocalFrames.write(refused("Invalid helper credentials."), to: fd)
return false
}
served.lock(); wasServed = true; served.unlock()
let answer: Data = String(decoding: frame, as: UTF8.self).withCString { request in
guard let raw = oi_request(request) else { return refused("The installer did not answer.") }
defer { oi_free(raw) }
return Data(String(cString: raw).utf8)
}
do { try LocalFrames.write(answer, to: fd) } catch { return false }
return true
}
do { try LocalFrames.write(answer, to: fd) } catch { return }
if !keepOpen { return }
}
}
}
Expand Down
Loading