1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use std::path::PathBuf;
use clap::{Parser, Subcommand};
mod commands;
#[derive(Parser)]
#[command(name = "restorekit", version, about = "DFU-restore Apple Silicon Macs")]
struct Cli {
/// Emit machine-readable JSON lines instead of human output.
#[arg(long, global = true)]
json: bool,
/// Firmware cache directory (default: $XDG_CONFIG_HOME/restorekit/firmwares).
#[arg(long, global = true)]
cache_dir: Option<PathBuf>,
/// Verbose output (streams idevicerestore's detailed restore log).
#[arg(short, long, global = true)]
verbose: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// List every connected Apple device, with its mode and ECID.
List {
/// Re-render every 2 seconds until interrupted (NDJSON when --json).
#[arg(long, short)]
watch: bool,
},
/// Put the cabled target Mac into DFU mode — via a dongle (any host) or the
/// host's own port (Apple Silicon macOS, root). See `--dongle` / `--ecid`.
Dfu(TargetArgs),
/// Reboot the cabled target Mac back into normal mode (dongle or host).
Reboot(TargetArgs),
/// Resolve and download firmware for the detected (or specified) Mac.
Download {
/// Model identifier (e.g. MacBookPro17,1). Defaults to the DFU device.
#[arg(long)]
identifier: Option<String>,
/// Pin a macOS version (e.g. 26.5.2). Defaults to the latest signed build.
#[arg(long)]
os_version: Option<String>,
/// Detect the model from a specific Mac by ECID (hex like 0xc60a812345678,
/// or decimal) when several are in DFU mode. See `restorekit list`.
#[arg(long, value_parser = parse_ecid)]
ecid: Option<u64>,
},
/// Erase and restore the target Mac: triggers DFU entry if needed, then
/// downloads firmware and restores. This wipes all data on the target.
#[command(alias = "restore")]
Erase(RestoreArgs),
/// Revive the target Mac: reinstall firmware without erasing user data —
/// use this to recover a Mac bricked by a failed update.
Revive(ReviveArgs),
/// Show or manage the firmware cache.
Cache {
/// Delete all cached firmware.
#[arg(long)]
clear: bool,
/// Print only the cache directory path.
#[arg(long)]
path: bool,
},
/// Inspect and manage RecoverKit dongles (list, serial console, firmware
/// updates). Use the top-level `dfu` / `reboot` with `--dongle` or
/// `--ecid` to act on the cabled Mac.
#[command(arg_required_else_help = true)]
Dongle {
#[command(subcommand)]
action: DongleAction,
},
/// Show, export, or clear the capture/restore history.
#[cfg(feature = "history")]
History {
#[command(subcommand)]
action: HistoryAction,
},
/// Generate shell completions on stdout (e.g. `restorekit completions
/// zsh > "${fpath[1]}/_restorekit"`). Hidden: the packaged installs
/// (brew, tarball) ship these pre-generated.
#[command(hide = true)]
Completions {
/// The shell to generate completions for.
shell: clap_complete::Shell,
},
/// Bind the WinUSB driver so restorekit can reach the cabled Mac (elevates).
#[cfg(target_os = "windows")]
SetupDriver {
/// Internal: this copy was relaunched already elevated.
#[arg(long, hide = true)]
elevated: bool,
/// Internal: file the elevated copy writes its outcome to.
#[arg(long, hide = true)]
result_file: Option<PathBuf>,
},
}
/// Which target `dfu` / `reboot` should act on, and how to reach it. With no
/// flags: a connected dongle is used if one is present, otherwise the host's
/// own sole DFU-capable port.
#[derive(clap::Args)]
struct TargetArgs {
/// Trigger via a specific dongle by its id (USB serial, e.g. DL-1A2B3C4D)
/// or any unambiguous fragment of it. See `restorekit dongle list`.
#[arg(long, conflicts_with_all = ["ecid", "port"])]
dongle: Option<String>,
/// Target the Mac with this ECID (hex like 0xc60a812345678, or decimal).
/// Auto-routes through the dongle it's cabled to, else the host DFU port.
#[arg(long, value_parser = parse_ecid, conflicts_with = "port")]
ecid: Option<u64>,
/// Target a specific host DFU-capable port by its RID (host trigger only).
#[arg(long)]
port: Option<i32>,
}
#[derive(Subcommand)]
enum DongleAction {
/// List connected dongles: firmware, PD state, and what each has cabled
/// to it. Name one (id or --ecid) to show just that dongle.
#[command(alias = "status")]
List(DongleSelect),
/// Print the dongle's serial-console tty paths (control console and the
/// target's UART bridge).
Console(DongleSelect),
/// Reboot a dongle into its RP2040 bootrom for a factory reflash. Hidden:
/// normal updates go through `dongle update`, which needs no bootloader
/// mode; this is the recovery path (`just fw-flash-full`).
#[command(hide = true)]
Bootsel(DongleSelect),
/// Update a dongle's firmware over USB (no bootloader mode, no drive).
///
/// The image is staged to the dongle's spare flash slot, verified, and
/// swapped in by its bootloader; an image that fails to boot is rolled
/// back. With no --file, the latest published firmware release is
/// fetched and installed if it's newer than what the dongle runs.
Update {
/// A raw firmware image (.bin) to install, instead of the latest
/// published release.
#[arg(long, short)]
file: Option<std::path::PathBuf>,
/// Only report whether an update is available; don't install it.
#[arg(long, conflicts_with = "file")]
check: bool,
#[command(flatten)]
select: DongleSelect,
},
}
/// Which dongle to act on. With no selector, the sole connected dongle is used.
#[derive(clap::Args)]
struct DongleSelect {
/// The dongle's id (USB serial, e.g. DL-1A2B3C4D) or any unambiguous
/// fragment of it (e.g. 1a2b). See `restorekit dongle list`.
id: Option<String>,
/// Target the dongle the Mac with this ECID is cabled to (hex like
/// 0xc60a812345678, or decimal), resolved by USB topology.
#[arg(long, value_parser = parse_ecid, conflicts_with = "id")]
ecid: Option<u64>,
}
impl DongleSelect {
fn into_target(self) -> restorekit::DongleTarget {
match (self.id, self.ecid) {
(Some(id), _) => restorekit::DongleTarget::Id(id),
(_, Some(e)) => restorekit::DongleTarget::Ecid(e),
_ => restorekit::DongleTarget::Auto,
}
}
}
#[cfg(feature = "history")]
#[derive(Subcommand)]
enum HistoryAction {
/// List logged devices, newest first.
List,
/// Export the whole history to a CSV file.
Export {
/// Destination CSV path.
path: PathBuf,
},
/// Delete all logged history.
Clear,
}
/// Firmware selection and target arguments shared by `restore` and `revive`.
#[derive(clap::Args)]
struct FirmwareArgs {
/// Restore from a local IPSW instead of downloading.
#[arg(long)]
ipsw: Option<PathBuf>,
/// Pin a macOS version (e.g. 26.5.2).
#[arg(long)]
os_version: Option<String>,
/// Override the detected model identifier.
#[arg(long)]
identifier: Option<String>,
/// Target a specific Mac by ECID (hex like 0xc60a812345678, or decimal)
/// when several are in DFU mode. See `restorekit list`.
#[arg(long, value_parser = parse_ecid)]
ecid: Option<u64>,
/// Trigger DFU entry via a specific dongle by its id (USB serial, or any
/// unambiguous fragment). Lets you restore from any host OS. See
/// `restorekit dongle list`.
#[arg(long)]
dongle: Option<String>,
}
#[derive(clap::Args)]
struct RestoreArgs {
#[command(flatten)]
firmware: FirmwareArgs,
/// Skip the erase confirmation prompt.
#[arg(long)]
yes: bool,
}
#[derive(clap::Args)]
struct ReviveArgs {
#[command(flatten)]
firmware: FirmwareArgs,
}
/// Parse an ECID: `0x`-prefixed or bare hex, or decimal.
fn parse_ecid(s: &str) -> Result<u64, String> {
let s = s.trim();
let parsed = if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
u64::from_str_radix(hex, 16)
} else if s.bytes().all(|b| b.is_ascii_digit()) {
s.parse()
} else {
u64::from_str_radix(s, 16)
};
parsed.map_err(|_| format!("invalid ECID '{s}': expected hex (0x…) or decimal"))
}
impl FirmwareArgs {
fn into_opts(
self,
revive: bool,
yes: bool,
cache_dir: Option<PathBuf>,
json: bool,
verbose: bool,
) -> commands::restore::Opts {
commands::restore::Opts {
revive,
ipsw: self.ipsw,
os_version: self.os_version,
identifier: self.identifier,
ecid: self.ecid,
dongle: self.dongle,
yes,
cache_dir,
json,
verbose,
}
}
}
fn main() {
// Die quietly when a pipe closes (`restorekit list --json | head`), like
// any other unix tool, instead of panicking on EPIPE.
#[cfg(unix)]
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
// Internal: this copy was relaunched elevated to run the restore-mode driver
// watcher (see restorekit::driver). Handle it before clap and exit.
#[cfg(target_os = "windows")]
{
let args: Vec<String> = std::env::args().collect();
if let Some(i) = args
.iter()
.position(|a| a == restorekit::driver::RESTORE_WATCH_ARG)
{
if let Some(liveness) = args.get(i + 1) {
restorekit::driver::run_restore_mode_watch_worker(std::path::Path::new(liveness));
}
return;
}
}
let cli = Cli::parse();
let result = match cli.command {
Command::List { watch } => commands::list::run(cli.json, watch),
Command::Dfu(t) => commands::dfu::enter(cli.json, t.dongle, t.ecid, t.port),
Command::Reboot(t) => commands::dfu::reboot(cli.json, t.dongle, t.ecid, t.port),
Command::Download {
identifier,
os_version,
ecid,
} => commands::download::run(identifier, os_version, ecid, cli.cache_dir, cli.json),
Command::Erase(args) => commands::restore::run(args.firmware.into_opts(
false,
args.yes,
cli.cache_dir,
cli.json,
cli.verbose,
)),
Command::Revive(args) => commands::restore::run(args.firmware.into_opts(
true,
false,
cli.cache_dir,
cli.json,
cli.verbose,
)),
Command::Completions { shell } => {
use clap::CommandFactory;
clap_complete::generate(
shell,
&mut Cli::command(),
"restorekit",
&mut std::io::stdout(),
);
Ok(())
}
Command::Cache { clear, path } => commands::cache::run(cli.cache_dir, clear, path),
Command::Dongle { action } => match action {
DongleAction::List(s) => {
// No selector lists every dongle rather than the sole one.
let target = (s.id.is_some() || s.ecid.is_some()).then(|| s.into_target());
commands::dongle::list(cli.json, target)
}
DongleAction::Console(s) => commands::dongle::console(cli.json, s.into_target()),
DongleAction::Bootsel(s) => commands::dongle::bootsel(cli.json, s.into_target()),
DongleAction::Update {
file,
check,
select,
} => commands::dongle::update(cli.json, select.into_target(), file.as_deref(), check),
},
#[cfg(feature = "history")]
Command::History { action } => match action {
HistoryAction::List => commands::history::list(cli.json),
HistoryAction::Export { path } => commands::history::export(path),
HistoryAction::Clear => commands::history::clear(),
},
#[cfg(target_os = "windows")]
Command::SetupDriver {
elevated,
result_file,
} => commands::setup_driver::run(cli.json, elevated, result_file),
};
if let Err(e) = result {
if cli.json {
println!(
"{}",
serde_json::json!({ "event": "error", "message": e.to_string() })
);
} else {
eprintln!("error: {e}");
}
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use super::parse_ecid;
#[test]
fn parses_ecid_forms() {
assert_eq!(parse_ecid("0xC60A812345678").unwrap(), 0xc60a812345678);
assert_eq!(parse_ecid("0Xc60a812345678").unwrap(), 0xc60a812345678);
assert_eq!(parse_ecid("12345").unwrap(), 12345);
assert_eq!(parse_ecid("c60a812345678").unwrap(), 0xc60a812345678);
assert!(parse_ecid("nope!").is_err());
assert!(parse_ecid("").is_err());
}
}