diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..65c5e42
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,1551 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "approx"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "by_address"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "castaway"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
+dependencies = [
+ "rustversion",
+]
+
+[[package]]
+name = "cc"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "clap"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+ "terminal_size",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.8",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "compact_str"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"
+dependencies = [
+ "castaway",
+ "cfg-if",
+ "itoa",
+ "rustversion",
+ "ryu",
+ "static_assertions",
+]
+
+[[package]]
+name = "const-oid"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+
+[[package]]
+name = "convert_case"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "critical-section"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
+
+[[package]]
+name = "crossterm"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
+dependencies = [
+ "bitflags",
+ "crossterm_winapi",
+ "derive_more",
+ "document-features",
+ "mio",
+ "parking_lot",
+ "rustix",
+ "signal-hook",
+ "signal-hook-mio",
+ "winapi",
+]
+
+[[package]]
+name = "crossterm_winapi"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "darling"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
+dependencies = [
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 3.0.8",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 3.0.8",
+]
+
+[[package]]
+name = "deranged"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+
+[[package]]
+name = "derive_more"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
+dependencies = [
+ "derive_more-impl",
+]
+
+[[package]]
+name = "derive_more-impl"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
+dependencies = [
+ "convert_case",
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer",
+ "const-oid",
+ "crypto-common",
+]
+
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
+]
+
+[[package]]
+name = "either"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "filetime"
+version = "0.2.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
+dependencies = [
+ "cfg-if",
+ "libc",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
+
+[[package]]
+name = "flate2"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+ "zlib-rs",
+]
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "indoc"
+version = "2.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1"
+dependencies = [
+ "rustversion",
+]
+
+[[package]]
+name = "instability"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20"
+dependencies = [
+ "darling",
+ "indoc",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.8",
+]
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "kasuari"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bde5057d6143cc94e861d90f591b9303d6716c6b9602309150bd068853c10899"
+dependencies = [
+ "hashbrown 0.16.1",
+ "portable-atomic",
+ "thiserror",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.190"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "line-clipping"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e752191d037c44ad111a8caa762921926658402f01cc1253f7bef2020ece4f5e"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "litrs"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "lru"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5"
+dependencies = [
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mio"
+version = "1.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
+dependencies = [
+ "libc",
+ "log",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "num_threads"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
+[[package]]
+name = "palette"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64"
+dependencies = [
+ "approx",
+ "libm",
+ "palette_derive",
+ "palette_math",
+]
+
+[[package]]
+name = "palette_derive"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be"
+dependencies = [
+ "by_address",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "palette_math"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12"
+dependencies = [
+ "libm",
+]
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "plist"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb"
+dependencies = [
+ "base64",
+ "indexmap",
+ "quick-xml",
+ "serde",
+ "time",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
+[[package]]
+name = "powerfmt"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.42.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "ratatui"
+version = "0.30.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3274ba0a2c5e1bcad2a2005d20f4dc59dad26b2eb0940fb094500dba4099d57d"
+dependencies = [
+ "instability",
+ "ratatui-core",
+ "ratatui-crossterm",
+ "ratatui-widgets",
+ "serde",
+]
+
+[[package]]
+name = "ratatui-core"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbb175c433c8e28a809d1f5773a2ae96e68c0ce40db865cbab1020bf33ae479c"
+dependencies = [
+ "bitflags",
+ "compact_str",
+ "critical-section",
+ "hashbrown 0.17.1",
+ "itertools",
+ "kasuari",
+ "lru",
+ "palette",
+ "serde",
+ "strum",
+ "thiserror",
+ "unicode-segmentation",
+ "unicode-truncate",
+ "unicode-width",
+]
+
+[[package]]
+name = "ratatui-crossterm"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "567584a3b0e6a8203c23de40b4861497266725eb5363dbfd18a1edd603cca9f0"
+dependencies = [
+ "cfg-if",
+ "crossterm",
+ "instability",
+ "ratatui-core",
+]
+
+[[package]]
+name = "ratatui-widgets"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66e3d19bcc9130ca376277d93b60767ff121ace3be06f5f95f81dd68956407d1"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.17.1",
+ "indoc",
+ "instability",
+ "itertools",
+ "line-clipping",
+ "ratatui-core",
+ "serde",
+ "strum",
+ "time",
+ "unicode-segmentation",
+ "unicode-width",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "reims-util"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "crc32fast",
+ "flate2",
+ "getrandom 0.4.3",
+ "num-bigint",
+ "plist",
+ "ratatui",
+ "ruzstd",
+ "serde",
+ "serde_json",
+ "sha1",
+ "sha2",
+ "tar",
+ "ureq",
+ "zip",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+dependencies = [
+ "log",
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "ruzstd"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5"
+dependencies = [
+ "twox-hash",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.8",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "sha1"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "sha2"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "signal-hook"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
+dependencies = [
+ "libc",
+ "signal-hook-registry",
+]
+
+[[package]]
+name = "signal-hook-mio"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
+dependencies = [
+ "libc",
+ "mio",
+ "signal-hook",
+]
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "smallvec"
+version = "1.16.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "strum"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01016da373cd8f7ef12624f796309f5c31ba8d646dd08856c02cd741d823c622"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tar"
+version = "0.4.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
+dependencies = [
+ "filetime",
+ "libc",
+ "xattr",
+]
+
+[[package]]
+name = "terminal_size"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874"
+dependencies = [
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.8",
+]
+
+[[package]]
+name = "time"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
+dependencies = [
+ "deranged",
+ "libc",
+ "num-conv",
+ "num_threads",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+ "time-macros",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+
+[[package]]
+name = "time-macros"
+version = "0.2.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
+[[package]]
+name = "twox-hash"
+version = "2.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
+
+[[package]]
+name = "typed-path"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "unicode-truncate"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16b380a1238663e5f8a691f9039c73e1cdae598a30e9855f541d29b08b53e9a5"
+dependencies = [
+ "itertools",
+ "unicode-segmentation",
+ "unicode-width",
+]
+
+[[package]]
+name = "unicode-width"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "ureq"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
+dependencies = [
+ "base64",
+ "flate2",
+ "log",
+ "percent-encoding",
+ "rustls",
+ "rustls-pki-types",
+ "ureq-proto",
+ "utf8-zero",
+ "webpki-roots",
+]
+
+[[package]]
+name = "ureq-proto"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be"
+dependencies = [
+ "base64",
+ "http",
+ "httparse",
+ "log",
+]
+
+[[package]]
+name = "utf8-zero"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "xattr"
+version = "1.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
+dependencies = [
+ "libc",
+ "rustix",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
+
+[[package]]
+name = "zip"
+version = "9.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e2fc56a6707efb066c40aead2409ebb1224e6dde24a074e9fbc78ced500507b"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "nix",
+ "typed-path",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..1b2098d
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,51 @@
+# reims-util: makes the OpenCore boot image and OVMF firmware an x86-64 macOS VM boots through,
+# and online and offline macOS installers from Apple's own files (README.md).
+[package]
+name = "reims-util"
+version = "0.1.0"
+edition = "2024"
+rust-version = "1.98.1"
+publish = false
+license = "GPL-2.0-or-later OR LGPL-3.0-or-later"
+description = "Make OpenCore boot images and macOS installers for x86-64 macOS VMs"
+
+[dependencies]
+anyhow = "1.0.104"
+clap = { version = "4.6.7", features = ["derive", "wrap_help"] }
+crc32fast = "1.5.2"
+# The gzipped software update catalog (installer.rs).
+flate2 = "1.1.10"
+getrandom = "0.4.3"
+# The RSA check of a recovery image's chunklist signature (chunklist.rs).
+num-bigint = "0.5.1"
+plist = "1.10.1"
+# line_count: how many rows a wrapped summary takes in the scrollback (tui.rs). No default
+# features: their underline-color names the termwiz and termina backends, which Cargo.lock then
+# carries (with termwiz's old generic-array and psm) though nothing builds them.
+ratatui = { version = "0.30.2", default-features = false, features = [
+ "crossterm",
+ "layout-cache",
+ "unstable-rendered-line-info",
+] }
+# The OVMF package's zstd archive (ovmf.rs).
+ruzstd = "0.9.1"
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = "1.0.154"
+sha1 = "0.11.0"
+sha2 = "0.11.0"
+tar = "0.4.46"
+ureq = "3.4.2"
+# The OpenCore release (opencore/mod.rs): reading deflated entries only.
+zip = { version = "9.0.2", default-features = false, features = ["deflate-flate2"] }
+
+[lints.rust]
+unsafe_code = "forbid"
+
+[lints.clippy]
+unwrap_used = "deny"
+expect_used = "deny"
+panic = "deny"
+todo = "deny"
+
+[profile.release]
+debug = "line-tables-only"
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..435ff21
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,25 @@
+reims-util is free software: you can redistribute it and/or modify it under
+the terms of either of these licenses, at your option:
+
+- the GNU General Public License, version 2, or (at your option) any later
+ version: LICENSES/GPL-2.0-or-later.txt;
+- the GNU Lesser General Public License, version 3, or (at your option) any
+ later version: LICENSES/LGPL-3.0-or-later.txt. The LGPL's version 3 is a
+ set of permissions added to the GNU General Public License, version 3,
+ whose text is LICENSES/GPL-3.0-or-later.txt.
+
+As an SPDX license expression: GPL-2.0-or-later OR LGPL-3.0-or-later.
+
+It is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+A PARTICULAR PURPOSE. See the licenses for more details.
+
+src/opencore/smbios.rs takes its serial number tables and rules from
+OpenCorePkg's macserial (Copyright (c) 2018-2020 vit9696, Copyright (c) 2020
+Matis Schotte), so that file is also under OpenCorePkg's BSD-3-Clause license:
+LICENSES/BSD-3-Clause-OpenCorePkg.txt.
+
+What reims-util downloads and writes into images, such as OpenCore and OVMF,
+is not part of the repository, and keeps its own license; OVMF's licenses are
+written beside OVMF_CODE.fd. The crates the build takes from crates.io keep
+their own licenses too.
diff --git a/LICENSES/BSD-3-Clause-OpenCorePkg.txt b/LICENSES/BSD-3-Clause-OpenCorePkg.txt
new file mode 100644
index 0000000..9a15cce
--- /dev/null
+++ b/LICENSES/BSD-3-Clause-OpenCorePkg.txt
@@ -0,0 +1,16 @@
+Copyright (c) 2016-2017, The HermitCrabs Lab
+Copyright (c) 2016-2020, Download-Fritz
+Copyright (c) 2017-2020, savvas
+Copyright (c) 2016-2020, vit9696
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/LICENSES/GPL-2.0-or-later.txt b/LICENSES/GPL-2.0-or-later.txt
new file mode 100644
index 0000000..9efa6fb
--- /dev/null
+++ b/LICENSES/GPL-2.0-or-later.txt
@@ -0,0 +1,338 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ , 1 April 1989
+ Moe Ghoul, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/LICENSES/GPL-3.0-or-later.txt b/LICENSES/GPL-3.0-or-later.txt
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSES/GPL-3.0-or-later.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/LICENSES/LGPL-3.0-or-later.txt b/LICENSES/LGPL-3.0-or-later.txt
new file mode 100644
index 0000000..0a04128
--- /dev/null
+++ b/LICENSES/LGPL-3.0-or-later.txt
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/README.md b/README.md
index 85e6ff1..0f28c23 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,169 @@
-# WIP
+# reims-util
+
+[](LICENSE)
+
+reims-util gets an x86-64 macOS VM ready to boot. It makes:
+
+- **An OpenCore boot image**, with the OVMF firmware to boot it, set up for a q35 VM on KVM.
+- **macOS installers** that `reims-ctl` takes as they are, from Apple and checked against Apple's
+ own checksums and signatures:
+ - an **online installer**, which installs the newest release of macOS 10.13 to 26 over the
+ network;
+ - an **offline installer**, which installs one exact release of macOS 11 to 26 with no network
+ at all.
+
+Downloads pick up where they stopped when they're interrupted.
+
+It's made for [reims-vgpu](https://github.com/steelbrain/reims-vgpu)'s `reims-ctl`, and does the
+job you'd otherwise use OSX-KVM or ULTMOS for. It's a single program with no other tools to
+install, and it runs on Linux and macOS.
+
+## Install
+
+You need Rust 1.98.1 or later ([rustup.rs](https://rustup.rs)). Then:
+
+```sh
+cargo install --locked --git https://github.com/steelbrain/reims-util
+```
+
+Or, from a checkout, `cargo install --locked --path .`.
+
+## Make a VM with reims-ctl
+
+```sh
+mkdir -p ~/vms/mac && cd ~/vms/mac
+reims-util opencore # OpenCore.qcow2, OVMF_CODE.fd and OVMF_VARS.fd
+reims-util online-installer tahoe # macOS-Tahoe-online-installer.dmg
+reims-ctl create mac --opencore OpenCore.qcow2 \
+ --installer macOS-Tahoe-online-installer.dmg --start
+```
+
+`reims-ctl` copies the OpenCore image into the VM, finds OVMF beside it, and takes the installer
+as it is. OpenCore's picker boots "macOS Base System" after 5 seconds, and you're in macOS
+Recovery: erase the VM's disk in Disk Utility, then pick Reinstall macOS, which downloads the rest
+from Apple.
+
+## Use it interactively
+
+Run `reims-util` with no arguments. A small interface opens at the bottom of your terminal (it
+doesn't take over the screen): pick a job, fill in its form, and press Enter to start it. Esc
+stops a download (press it again to leave without waiting), and starting it again picks up where
+it left off. What each job wrote, or why it failed, stays in your terminal once you quit.
+
+## Use it from the command line
+
+Everything the interface does is a command too, which is what scripts and `reims-ctl` use.
+
+### OpenCore and OVMF
+
+```sh
+reims-util opencore -o OpenCore.qcow2
+```
+
+This writes a 128 MiB disk image with OpenCore 1.0.8 on its EFI partition: qcow2 for a `.qcow2`
+name, and a raw disk image for anything else (`.img`). Beside it go `OVMF_CODE.fd` and
+`OVMF_VARS.fd`, with OVMF's licenses. Both are downloaded from pinned releases (OpenCore's from
+GitHub, OVMF from Arch Linux's `edk2-ovmf` package), checked against the hashes reims-util knows,
+and cached in `~/.cache/reims-util`, so they're only downloaded once.
+
+Each image gets a Mac identity of its own: a serial number, logic board serial (MLB), system UUID
+and ROM, which it prints when it's done. Keep them if you'll want the same identity in another
+image (`--serial`, `--mlb`, `--uuid`, `--rom`). The model is an iMac20,1 unless you ask for
+another with `--model`:
+
+| Model | Runs |
+| ---------- | -------------------- |
+| iMac20,1 | macOS 10.15.6 to 26 |
+| iMacPro1,1 | macOS 10.13 to 15 |
+
+What's in the image, and why:
+
+- **No kexts.** QEMU's `isa-applesmc` is the SMC, and the GPU is reims-vgpu's, which macOS drives
+ with its own driver.
+- **The drivers a VM boots with**: OpenRuntime, OpenHfsPlus (recovery images and installers are
+ HFS+), OpenPartitionDxe (for older recovery images) and ResetNvramEntry.
+- **One ACPI table**, with the `EC` and `USBX` devices macOS looks for.
+- **The CPU reported as a Skylake-SP**, which every macOS from 10.13 to 26 knows, whatever CPU
+ model the VM has. `--no-cpuid-spoof` turns that off.
+- **macOS doesn't see it runs in a VM**, so iCloud and the App Store let you sign in.
+ `--show-vm` turns that off.
+- **System Integrity Protection on**, as on a real Mac. `--disable-sip` turns it off.
+
+`--timeout` sets how long the picker waits (0 waits for you), `--boot-args` the kernel's boot
+arguments, and `--verbose-boot` shows the kernel's messages while it boots.
+`reims-util opencore --help` lists the rest.
+
+### Online installers
+
+```sh
+reims-util online-installer list
+reims-util online-installer sonoma -o ~/vms/mac
+```
+
+An online installer is Apple's recovery image for a macOS, as a Mac's Internet Recovery gets it:
+about 1 GB, written as `macOS--online-installer.dmg`. A VM boots it into macOS Recovery,
+whose Reinstall macOS downloads and installs the newest release of that macOS. Name a version by
+name (`sonoma`, `big-sur`), number (`14`, `10.15`) or `latest`. The image is checked against its
+chunklist, which Apple signs, 10 MiB at a time, so what you get is byte for byte what Apple made.
+
+### Offline installers
+
+```sh
+reims-util offline-installer list
+reims-util offline-installer 26.6.2 -o ~/vms/mac
+```
+
+Recovery always installs the newest release of its macOS, downloaded as it goes. To install a
+particular one, such as 26.6.2 when 26.7.1 is out, or to install with no network, make an offline
+installer: a disk image, `macOS----offline-installer.img`, of 13 to 20 GB.
+It holds the recovery image of that macOS, which OpenCore boots as it would from a USB stick, and
+Apple's full installer for that release, with a script that installs it.
+
+`offline-installer list` shows the releases Apple's software update catalog has for Intel Macs;
+macOS 27 runs on Apple silicon only, so it isn't there. Name one by version (`26.6.2`, or `26` for
+the newest 26), build (`25G83`), name (`tahoe`, for the newest Tahoe), Apple's product ID
+(`140-93587`) or `latest`. Both of its files are downloaded straight into their places in the
+image, each checked against Apple's chunklist for it, so the installer, up to 18 GB, is never on
+your disk twice.
+
+```sh
+reims-ctl create mac --opencore OpenCore.qcow2 \
+ --installer macOS-Tahoe-26.6.2-25G83-offline-installer.img --start
+```
+
+reims-ctl uses the image where it is, read-only, so it isn't copied again. Once you're in Recovery:
+
+1. Open Disk Utility and erase the VM's disk as APFS. You can leave its name as it is.
+2. Quit Disk Utility, open Utilities > Terminal, and run:
+
+ ```sh
+ sh /Volumes/Installer/install-macos.sh
+ ```
+
+The script puts "Install macOS ….app" on the disk you erased and starts it; the VM restarts
+into the installer, and goes on from there as any macOS install does.
+
+### Interrupted downloads
+
+An installer is written as a `.part` file next to where it ends up. If it stops, whether you
+pressed Ctrl-C, the network dropped or the machine went to sleep, run the same command again:
+what's there is checked against Apple's chunklists and the download continues from there. An
+installer that's already complete and checks out isn't downloaded again, and one that doesn't is
+repaired. An offline installer whose recovery image Apple has since replaced is left as it is: it
+still boots, and a VM may be using it.
+
+### For scripts
+
+`--json` prints progress and the result as JSON lines on stdout. The last line is either
+`{"event":"done","result":{…}}`, with what was written (and for `opencore`, the identity it
+made) or, for `list`, the versions, or `{"event":"error","message":"…"}`.
+
+```sh
+reims-util --json online-installer tahoe -o ~/vms/mac
+```
+
+## License
+
+reims-util is licensed under GPL-2.0-or-later OR LGPL-3.0-or-later; see [LICENSE](LICENSE). The
+serial number tables come from OpenCorePkg's macserial, under its BSD-3-Clause license.
+OpenCore and OVMF, which reims-util downloads, keep their own licenses.
diff --git a/clippy.toml b/clippy.toml
new file mode 100644
index 0000000..7bada54
--- /dev/null
+++ b/clippy.toml
@@ -0,0 +1,3 @@
+allow-unwrap-in-tests = true
+allow-expect-in-tests = true
+allow-panic-in-tests = true
diff --git a/src/cache.rs b/src/cache.rs
new file mode 100644
index 0000000..5b11fbf
--- /dev/null
+++ b/src/cache.rs
@@ -0,0 +1,54 @@
+//! Files fetched once and kept: the OpenCore release and the OVMF package, each pinned to its
+//! SHA-256, under `$XDG_CACHE_HOME/reims-util` (`~/.cache/reims-util`).
+
+use crate::http::{self, Dest, Download, NoCheck};
+use crate::progress::Reporter;
+use anyhow::{Context, Result, bail};
+use std::path::PathBuf;
+
+pub fn dir() -> Result {
+ let base = match std::env::var_os("XDG_CACHE_HOME").filter(|v| !v.is_empty()) {
+ Some(v) => PathBuf::from(v),
+ None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".cache"),
+ };
+ Ok(base.join("reims-util"))
+}
+
+pub struct Pinned {
+ /// Its name in the cache.
+ pub name: &'static str,
+ pub url: &'static str,
+ pub sha256: &'static str,
+ /// What it is, for the progress line: "OpenCore 1.0.8".
+ pub what: &'static str,
+}
+
+/// The cached file, downloaded (or its download resumed) first if it is not there.
+pub fn fetch(p: &Pinned, r: &dyn Reporter) -> Result {
+ let path = dir()?.join(p.name);
+ if path.exists() {
+ if http::sha256_file(&path)? == p.sha256 {
+ return Ok(path);
+ }
+ std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
+ }
+ let agent = http::agent();
+ http::download(
+ &agent,
+ Download::new(p.url, format!("Downloading {}", p.what)),
+ Dest::File(&path),
+ &mut NoCheck,
+ r,
+ )?;
+ let got = http::sha256_file(&path)?;
+ if got != p.sha256 {
+ let _ = std::fs::remove_file(&path);
+ bail!(
+ "{} from {} has SHA-256 {got}, not the pinned {}",
+ p.what,
+ p.url,
+ p.sha256
+ );
+ }
+ Ok(path)
+}
diff --git a/src/chunklist.rs b/src/chunklist.rs
new file mode 100644
index 0000000..5dddb21
--- /dev/null
+++ b/src/chunklist.rs
@@ -0,0 +1,341 @@
+//! Apple's chunklists (`CNKL`): the SHA-256 of each chunk of a recovery image or an installer
+//! package, and a check of the list itself.
+//!
+//! The layout (little-endian), as macrecovery reads it (OpenCorePkg's Utilities/macrecovery,
+//! BSD-3-Clause):
+//! - a 0x24-byte header: magic `CNKL`, header size (0x24), file version 1, chunk method 1,
+//! signature method, a pad byte, the chunk count, the chunks' offset (0x24) and the signature's;
+//! - each chunk: its size (u32) and SHA-256;
+//! - the signature over the SHA-256 of the header and chunks: method 1 is a 2048-bit RSA
+//! signature (PKCS#1 v1.5) by Apple's EFI ROM key, method 2 the bare SHA-256.
+//!
+//! A recovery image's chunklist comes over plain HTTP from osrecovery.apple.com, so it must carry
+//! the signature: that makes the image's every byte Apple's. An installer's comes over HTTPS
+//! from the software update catalog (also HTTPS), with method 2.
+
+use crate::http::Check;
+use crate::progress::{self, Reporter};
+use anyhow::{Result, bail, ensure};
+use num_bigint::BigUint;
+use sha2::{Digest, Sha256};
+use std::fs::File;
+use std::io::{Read, Seek, SeekFrom};
+
+const HEADER_SIZE: usize = 0x24;
+const CHUNK_SIZE: usize = 0x24;
+
+/// Apple's EFI ROM public key 1, the modulus of the RSA key that signs recovery chunklists (its
+/// exponent is 65537).
+const APPLE_EFI_ROM_KEY_1: &str = "C3E748CAD9CD384329E10E25A91E43E1A762FF529ADE578C935BDDF9B13F2179\
+D4855E6FC89E9E29CA12517D17DFA1EDCE0BEBF0EA7B461FFE61D94E2BDF72C196F89ACD3536B644064014DAE25A15DB\
+6BB0852ECBD120916318D1CCDEA3C84C92ED743FC176D0BACA920D3FCF3158AFF731F88CE0623182A8ED67E650515F7\
+5745909F07D415F55FC15A35654D118C55A462D37A3ACDA08612F3F3F6571761EFCCBCC299AEE99B3A4FD6212CCFFF5E\
+F37A2C334E871191F7E1C31960E010A54E86FA3F62E6D6905E1CD57732410A3EB0C6B4DEFDABE9F59BF1618758C751C\
+D56CEF851D1C0EAA1C558E37AC108DA9089863D20E2E7E4BF475EC66FE6B3EFDCF";
+
+/// PKCS#1 v1.5's DigestInfo prefix for SHA-256.
+const SHA256_DIGEST_INFO: [u8; 19] = [
+ 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
+ 0x00, 0x04, 0x20,
+];
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Signature {
+ /// Signed by Apple's EFI ROM key, checked.
+ Rsa,
+ /// The bare digest of the list, checked.
+ Digest,
+}
+
+#[derive(Clone, Debug)]
+pub struct Chunklist {
+ pub chunks: Vec<(u32, [u8; 32])>,
+ pub signature: Signature,
+}
+
+impl Chunklist {
+ /// Parses a chunklist and checks its signature or digest.
+ pub fn parse(data: &[u8]) -> Result {
+ ensure!(data.len() >= HEADER_SIZE, "the chunklist is too short");
+ ensure!(&data[0..4] == b"CNKL", "not a chunklist");
+ let u32_at =
+ |o: usize| u32::from_le_bytes([data[o], data[o + 1], data[o + 2], data[o + 3]]);
+ let u64_at = |o: usize| {
+ let mut b = [0u8; 8];
+ b.copy_from_slice(&data[o..o + 8]);
+ u64::from_le_bytes(b)
+ };
+ ensure!(
+ u32_at(4) as usize == HEADER_SIZE,
+ "unknown chunklist header size"
+ );
+ ensure!(data[8] == 1 && data[9] == 1, "unknown chunklist version");
+ let method = data[10];
+ let count = u64_at(12);
+ let chunk_offset = u64_at(20);
+ let sig_offset = u64_at(28);
+ ensure!(count > 0 && count < 1 << 24, "chunklist has {count} chunks");
+ ensure!(
+ chunk_offset as usize == HEADER_SIZE,
+ "unknown chunklist layout"
+ );
+ let chunks_end = HEADER_SIZE + count as usize * CHUNK_SIZE;
+ ensure!(
+ sig_offset as usize == chunks_end,
+ "unknown chunklist layout"
+ );
+ ensure!(data.len() >= chunks_end, "the chunklist is cut short");
+ let digest: [u8; 32] = Sha256::digest(&data[..chunks_end]).into();
+ let sig = &data[chunks_end..];
+ let signature = match method {
+ 1 => {
+ ensure!(
+ sig.len() == 256,
+ "the chunklist's signature is {} bytes",
+ sig.len()
+ );
+ ensure!(
+ rsa_verify(APPLE_EFI_ROM_KEY_1, sig, &digest),
+ "the chunklist's signature is not Apple's"
+ );
+ Signature::Rsa
+ }
+ 2 => {
+ ensure!(
+ sig.len() == 32 && sig == digest,
+ "the chunklist's digest does not match"
+ );
+ Signature::Digest
+ }
+ m => bail!("unknown chunklist signature method {m}"),
+ };
+ let chunks = data[HEADER_SIZE..chunks_end]
+ .as_chunks::()
+ .0
+ .iter()
+ .map(|c| {
+ let size = u32::from_le_bytes([c[0], c[1], c[2], c[3]]);
+ let mut h = [0u8; 32];
+ h.copy_from_slice(&c[4..36]);
+ (size, h)
+ })
+ .collect();
+ Ok(Chunklist { chunks, signature })
+ }
+
+ pub fn total(&self) -> u64 {
+ self.chunks.iter().map(|(s, _)| *s as u64).sum()
+ }
+}
+
+/// Whether `sig` (little-endian, as chunklists store it) is the PKCS#1 v1.5 signature of
+/// `digest` by the 2048-bit key of modulus `modulus` (hex) and exponent 65537.
+fn rsa_verify(modulus: &str, sig: &[u8], digest: &[u8; 32]) -> bool {
+ let Some(n) = BigUint::parse_bytes(modulus.as_bytes(), 16) else {
+ return false;
+ };
+ let s = BigUint::from_bytes_le(sig);
+ if s >= n {
+ return false;
+ }
+ let m = s.modpow(&BigUint::from(65537u32), &n).to_bytes_be();
+ // The encoded message is 256 bytes, 00 01 FF..FF 00 DigestInfo digest; as a number its
+ // leading zero byte drops.
+ let mut expected = vec![0x01u8];
+ expected.resize(256 - 1 - 1 - SHA256_DIGEST_INFO.len() - 32, 0xff);
+ expected.push(0x00);
+ expected.extend_from_slice(&SHA256_DIGEST_INFO);
+ expected.extend_from_slice(digest);
+ m == expected
+}
+
+/// Checks a download against its chunklist as it arrives.
+pub struct ChunkCheck {
+ list: Chunklist,
+ /// The chunk being filled, and the bytes of it seen so far.
+ index: usize,
+ filled: u64,
+ hasher: Sha256,
+ /// Where the chunk being filled starts in the file.
+ chunk_start: u64,
+}
+
+impl ChunkCheck {
+ pub fn new(list: Chunklist) -> Self {
+ ChunkCheck {
+ list,
+ index: 0,
+ filled: 0,
+ hasher: Sha256::new(),
+ chunk_start: 0,
+ }
+ }
+
+ pub fn total(&self) -> u64 {
+ self.list.total()
+ }
+}
+
+impl Check for ChunkCheck {
+ fn resume(&mut self, file: &mut File, offset: u64, len: u64, r: &dyn Reporter) -> Result {
+ file.seek(SeekFrom::Start(offset))?;
+ let mut good = 0u64;
+ let mut buf = Vec::new();
+ for (size, hash) in &self.list.chunks {
+ progress::check(r)?;
+ let size = *size as u64;
+ if good + size > len {
+ break;
+ }
+ buf.resize(size as usize, 0);
+ file.read_exact(&mut buf)?;
+ if Sha256::digest(&buf)[..] != hash[..] {
+ break;
+ }
+ // Said once there is something to check: an empty image's first chunk fails.
+ if good == 0 {
+ r.step("Checking what is already downloaded");
+ }
+ good += size;
+ r.progress(good, Some(len));
+ }
+ Ok(good)
+ }
+
+ fn verifies(&self) -> bool {
+ true
+ }
+
+ fn feed(&mut self, mut data: &[u8]) -> std::result::Result<(), u64> {
+ while !data.is_empty() {
+ let Some((size, hash)) = self.list.chunks.get(self.index) else {
+ // More bytes than the chunklist lists.
+ return Err(self.chunk_start);
+ };
+ let take = ((*size as u64 - self.filled) as usize).min(data.len());
+ self.hasher.update(&data[..take]);
+ self.filled += take as u64;
+ data = &data[take..];
+ if self.filled == *size as u64 {
+ let h = std::mem::take(&mut self.hasher).finalize();
+ if h[..] != hash[..] {
+ let start = self.chunk_start;
+ self.restart_at(start);
+ return Err(start);
+ }
+ self.chunk_start += *size as u64;
+ self.index += 1;
+ self.filled = 0;
+ }
+ }
+ Ok(())
+ }
+
+ fn restart_at(&mut self, offset: u64) {
+ // `offset` is always a chunk boundary: 0, or one resume or feed returned.
+ let mut start = 0u64;
+ let mut index = 0;
+ for (size, _) in &self.list.chunks {
+ if start + *size as u64 > offset {
+ break;
+ }
+ start += *size as u64;
+ index += 1;
+ }
+ self.index = index;
+ self.chunk_start = start;
+ self.filled = 0;
+ self.hasher = Sha256::new();
+ }
+
+ fn finish(&mut self) -> Result<()> {
+ ensure!(
+ self.index == self.list.chunks.len() && self.filled == 0,
+ "the download ended at chunk {} of {}",
+ self.index,
+ self.list.chunks.len()
+ );
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A method-2 chunklist of the given chunks.
+ fn make(chunks: &[&[u8]]) -> Vec {
+ let mut v = Vec::new();
+ v.extend_from_slice(b"CNKL");
+ v.extend_from_slice(&(HEADER_SIZE as u32).to_le_bytes());
+ v.extend_from_slice(&[1, 1, 2, 0]);
+ v.extend_from_slice(&(chunks.len() as u64).to_le_bytes());
+ v.extend_from_slice(&(HEADER_SIZE as u64).to_le_bytes());
+ v.extend_from_slice(&((HEADER_SIZE + chunks.len() * CHUNK_SIZE) as u64).to_le_bytes());
+ for c in chunks {
+ v.extend_from_slice(&(c.len() as u32).to_le_bytes());
+ v.extend_from_slice(&Sha256::digest(c));
+ }
+ let d = Sha256::digest(&v);
+ v.extend_from_slice(&d);
+ v
+ }
+
+ #[test]
+ fn digest_chunklist_checks_chunks_across_feeds() {
+ let a = vec![1u8; 100];
+ let b = vec![2u8; 50];
+ let list = Chunklist::parse(&make(&[&a, &b])).unwrap();
+ assert_eq!(list.signature, Signature::Digest);
+ assert_eq!(list.total(), 150);
+ let mut c = ChunkCheck::new(list.clone());
+ let mut all = a.clone();
+ all.extend_from_slice(&b);
+ for piece in all.chunks(7) {
+ c.feed(piece).unwrap();
+ }
+ c.finish().unwrap();
+
+ // A damaged second chunk sends the download back to its start.
+ let mut c = ChunkCheck::new(list);
+ all[120] ^= 1;
+ assert_eq!(c.feed(&all), Err(100));
+ c.feed(&b).unwrap();
+ c.finish().unwrap();
+ }
+
+ #[test]
+ fn rejects_a_tampered_list() {
+ let mut v = make(&[b"abc"]);
+ v[40] ^= 1;
+ assert!(Chunklist::parse(&v).is_err());
+ }
+
+ #[test]
+ fn checks_pkcs1_signatures() {
+ // A throwaway key's signature of SHA-256("reims-util test"), made with `openssl pkeyutl
+ // -sign -pkeyopt digest:sha256`, its bytes reversed as a chunklist stores them.
+ const N: &str = "A4DEB083EE044B5441BAE670FD538C8E998FFEDE4913847A76A2B8C4D41C579E7F23A07DC4C9B04A08241710E856AE6F\
+326AFC90756F1924B05854EF415D876BA8E593FB83CD1CF62A0FC597EB27E199669C3790E17044688D09E0CBE9FE4EE2\
+FB5D66357BD89EEAD01FA8ED5D8E5D659C25E44F565CD133321355BD8E500332426BF2902C8D38063CD3520B2D280727\
+6E140EE16FA1CCC00FFEEB041149698D1CD85C782874F7A22DFED6D0D4210EA2E7F84199CB72360A95666D5B460397A3\
+07BEF86F38EA2A09E353B1F5B93DE25D2C31A6A16A13102CFF849CC970C6BDE3760CEA3F36FC163455293A8F4B4DC8CA\
+49B26EB73B72F2BE1FEC8EBDDE869CDF";
+ const S: &str = "1c1263853f9f2f87782f0acc863d8b6b9980ac4a9178844c6cb30010910b9ff175c2bd4dd2d95ee2f5d950c768cf7235\
+71b4c4f6ea9e62831c915361cde68bbfb0d26a96bef07c93e16f31c88a2acf141b613492e0bd72d5e89cedfbbc5c3f0f\
+6635a77439ea836fdb12ae5bb04f3392f8dcae195c4331c3726068109828a74ce80b09dcb87f8973c6514ef145201dcc\
+7dc943625c8bef3e99f4e9990a8f1d3848186df2ba74e19df8bec3ab60244d07c3a133ebe7fce3490e7928a794c43e90\
+fdfdadc37efae0fc45efaf4cb5f836c0db55644d1d9ee1327f7a0e71065bd64ec31d163f01b040624fff0fb2158a47cc\
+8d44e901c022bcf493c33875197b4682";
+ let sig: Vec = (0..S.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&S[i..i + 2], 16).unwrap())
+ .collect();
+ let digest: [u8; 32] = Sha256::digest(b"reims-util test").into();
+ assert!(rsa_verify(N, &sig, &digest));
+ let mut other = digest;
+ other[0] ^= 1;
+ assert!(!rsa_verify(N, &sig, &other));
+ assert!(!rsa_verify(APPLE_EFI_ROM_KEY_1, &sig, &digest));
+ }
+}
diff --git a/src/cli.rs b/src/cli.rs
new file mode 100644
index 0000000..348251f
--- /dev/null
+++ b/src/cli.rs
@@ -0,0 +1,353 @@
+//! The command line: each job as a subcommand, for scripts and for reims-ctl. With `--json`,
+//! progress and the result are JSON lines on stdout (progress.rs), and the last line is a `done`
+//! event with what was written, or an `error` event.
+
+use crate::opencore::{self, config, smbios};
+use crate::progress::{self, JsonReporter, Reporter, TextReporter};
+use crate::{installer, recovery};
+use anyhow::{Context, Result, bail};
+use clap::{Args, Parser, Subcommand};
+use serde::Serialize;
+use std::path::PathBuf;
+
+const AFTER_HELP: &str = "\
+Run it with no command for the interactive interface.
+
+Examples:
+ # OpenCore.qcow2, with OVMF_CODE.fd and OVMF_VARS.fd beside it
+ reims-util opencore -o ~/vms/mac/OpenCore.qcow2
+ # Installers, and what versions each has
+ reims-util online-installer tahoe -o ~/vms/mac
+ reims-util offline-installer 26.7.1 -o ~/vms/mac
+ reims-util offline-installer list
+
+Downloads resume: run the same command again after an interruption.";
+
+#[derive(Parser)]
+#[command(
+ name = "reims-util",
+ version,
+ about = "Make OpenCore boot images and OVMF for x86-64 macOS VMs, and macOS installers from \
+ Apple's own files: online, or offline for one exact release",
+ after_help = AFTER_HELP
+)]
+pub struct Cli {
+ /// Print progress and the result as JSON lines on stdout
+ #[arg(long, global = true)]
+ pub json: bool,
+ #[command(subcommand)]
+ pub command: Option,
+}
+
+#[derive(Subcommand)]
+pub enum Command {
+ /// Make an OpenCore boot image, and write OVMF beside it
+ #[command(after_help = OPENCORE_HELP)]
+ Opencore(OpencoreArgs),
+ /// Make an online installer: Apple's recovery image, which installs the newest release of
+ /// its macOS (10.13 to 26) over the network
+ #[command(after_help = ONLINE_HELP)]
+ OnlineInstaller(InstallerArgs),
+ /// Make an offline installer: a disk image that installs an exact release of macOS (11 to
+ /// 26) with no network
+ #[command(after_help = OFFLINE_HELP)]
+ OfflineInstaller(InstallerArgs),
+}
+
+const OPENCORE_HELP: &str = "\
+The image is a 128 MiB disk with OpenCore 1.0.8 on its EFI partition, set up for a q35 VM on KVM:
+a QEMU disk to boot first, ahead of the macOS disk and the installer. Each image gets an SMBIOS
+identity of its own (serial, MLB, UUID, ROM), which it prints; give one to keep it. OVMF_CODE.fd
+and OVMF_VARS.fd go beside the image, where reims-ctl finds them.
+
+ reims-util opencore -o OpenCore.qcow2
+ reims-ctl create mac --opencore OpenCore.qcow2 --installer macOS-Tahoe-online-installer.dmg";
+
+#[derive(Args, Clone, Debug)]
+pub struct OpencoreArgs {
+ /// The image to write: qcow2 for a .qcow2 name, else a raw disk image
+ #[arg(short, long, default_value = "OpenCore.qcow2")]
+ pub output: PathBuf,
+ /// The Mac model to claim to be: iMac20,1 (macOS 10.15.6 to 26) or iMacPro1,1 (10.13 to 15)
+ #[arg(long, default_value = "iMac20,1")]
+ pub model: String,
+ /// The serial number (default: a new one for the model)
+ #[arg(long)]
+ pub serial: Option,
+ /// The logic board serial (default: a new one, made for the serial)
+ #[arg(long)]
+ pub mlb: Option,
+ /// The system UUID (default: a new one)
+ #[arg(long)]
+ pub uuid: Option,
+ /// The ROM: 12 hex digits or a MAC address, such as the VM's (default: random)
+ #[arg(long)]
+ pub rom: Option,
+ /// Seconds the boot picker waits before it boots the default entry (0 waits for you)
+ #[arg(long, default_value_t = 5)]
+ pub timeout: u32,
+ /// The kernel's boot arguments
+ #[arg(long, default_value = config::DEFAULT_BOOT_ARGS)]
+ pub boot_args: String,
+ /// Show the kernel's messages while it boots (adds -v to the boot arguments)
+ #[arg(long)]
+ pub verbose_boot: bool,
+ /// Turn System Integrity Protection off
+ #[arg(long)]
+ pub disable_sip: bool,
+ /// Report the VM's own CPUID leaf 1 instead of a Skylake-SP's
+ #[arg(long)]
+ pub no_cpuid_spoof: bool,
+ /// Let macOS see that it runs in a VM (iCloud and the App Store then refuse to sign in)
+ #[arg(long)]
+ pub show_vm: bool,
+ /// Write no OVMF files
+ #[arg(long)]
+ pub no_ovmf: bool,
+ /// Where OVMF_CODE.fd and OVMF_VARS.fd go (default: beside the image)
+ #[arg(long)]
+ pub ovmf_dir: Option,
+}
+
+#[derive(Args, Clone, Debug)]
+pub struct InstallerArgs {
+ /// The version to make, or `list` (or nothing) to list them
+ version: Option,
+ /// The folder to write to
+ #[arg(short, long, default_value = ".")]
+ output: PathBuf,
+}
+
+const ONLINE_HELP: &str = "\
+VERSION is a name (tahoe, big-sur), a number (26, 10.15) or latest. The installer is
+macOS--online-installer.dmg, as Apple serves it, checked against Apple's signature.
+
+ reims-util online-installer tahoe
+ reims-ctl create mac --opencore OpenCore.qcow2 --installer macOS-Tahoe-online-installer.dmg
+
+In Recovery, erase the VM's disk in Disk Utility (APFS), then pick Reinstall macOS.";
+
+const OFFLINE_HELP: &str = "\
+VERSION is a version (26.7.1, or 26 for the newest 26), a build (25G241), Apple's product ID,
+a name (tahoe, for the newest Tahoe) or latest. The installer is
+macOS----offline-installer.img, a disk image of two volumes: the
+recovery image of the same macOS, which OpenCore boots, and Apple's full installer, with a
+script that installs it.
+
+ reims-util offline-installer 26.7.1
+ reims-ctl create mac --opencore OpenCore.qcow2 \\
+ --installer macOS-Tahoe-26.7.1-25G241-offline-installer.img
+
+In Recovery, erase the VM's disk in Disk Utility (APFS), then open Utilities > Terminal and
+run:
+
+ sh /Volumes/Installer/install-macos.sh";
+
+/// Whether an installer command lists, rather than makes, the versions.
+fn lists(version: &Option) -> bool {
+ version
+ .as_deref()
+ .is_none_or(|v| v.trim().eq_ignore_ascii_case("list"))
+}
+
+#[derive(Serialize)]
+#[serde(tag = "event", rename_all = "snake_case")]
+enum Final {
+ Done { result: T },
+ Error { message: String },
+}
+
+pub fn run(command: Command, json: bool) -> Result<()> {
+ let text = TextReporter::new();
+ let js = JsonReporter::new();
+ let r: &dyn Reporter = if json { &js } else { &text };
+ let result = run_command(command, json, r);
+ if let Err(e) = &result
+ && json
+ {
+ progress::json_line(&Final::<()>::Error {
+ message: format!("{e:#}"),
+ });
+ }
+ result
+}
+
+fn run_command(command: Command, json: bool, r: &dyn Reporter) -> Result<()> {
+ match command {
+ Command::Opencore(a) => opencore_options(&a).and_then(|o| {
+ let out = opencore::build(&o, r)?;
+ if !json {
+ print_opencore(&out);
+ }
+ finish(json, &out)
+ }),
+ Command::OnlineInstaller(a) if lists(&a.version) => {
+ #[derive(Serialize)]
+ struct V {
+ name: String,
+ slug: &'static str,
+ board_id: &'static str,
+ }
+ let vs: Vec = recovery::VERSIONS
+ .iter()
+ .map(|v| V {
+ name: v.title(),
+ slug: v.slug,
+ board_id: v.board_id,
+ })
+ .collect();
+ if !json {
+ for v in &vs {
+ println!("{:<14} {}", v.slug, v.name);
+ }
+ }
+ finish(json, &vs)
+ }
+ Command::OnlineInstaller(a) => {
+ let version = a.version.unwrap_or_default();
+ let v = recovery::find(&version).with_context(|| {
+ format!(
+ "no online installer for {version:?}: `reims-util online-installer list` \
+ lists them"
+ )
+ })?;
+ let out = recovery::online_installer(v, &a.output, r)?;
+ if !json {
+ println!("{}", out.image.display());
+ eprintln!(
+ "\nTo install {} in a VM:\n reims-ctl create mac --opencore OpenCore.qcow2 \
+ --installer {}\nthen, in Recovery, erase the VM's disk in Disk Utility \
+ (APFS) and pick Reinstall macOS.",
+ out.title,
+ out.image.display()
+ );
+ }
+ finish(json, &out)
+ }
+ Command::OfflineInstaller(a) if lists(&a.version) => {
+ let list = installer::list(r)?;
+ if !json {
+ for i in &list {
+ println!(
+ "{:<9} {:<8} {:<16} {:>9} posted {} ({})",
+ i.version,
+ i.build,
+ i.title,
+ progress::bytes(i.size),
+ i.posted,
+ i.product
+ );
+ }
+ }
+ finish(json, &list)
+ }
+ Command::OfflineInstaller(a) => {
+ let version = a.version.unwrap_or_default();
+ let list = installer::list(r)?;
+ let i = installer::find(&list, &version).with_context(|| {
+ format!(
+ "no offline installer for {version:?}: `reims-util offline-installer list` \
+ lists them"
+ )
+ })?;
+ let out = installer::offline_installer(i, &a.output, r)?;
+ if !json {
+ println!("{}", out.image.display());
+ eprintln!(
+ "\nTo install {} in a VM:\n reims-ctl create mac --opencore OpenCore.qcow2 \
+ --installer {}\nthen, in Recovery, erase the VM's disk in Disk Utility \
+ (APFS), open Utilities > Terminal and run:\n {}",
+ out.installer.label(),
+ out.image.display(),
+ installer::IMAGE_COMMAND
+ );
+ }
+ finish(json, &out)
+ }
+ }
+}
+
+fn finish(json: bool, v: &T) -> Result<()> {
+ if json {
+ progress::json_line(&Final::Done { result: v });
+ }
+ Ok(())
+}
+
+pub fn opencore_options(a: &OpencoreArgs) -> Result {
+ let m = smbios::model(&a.model).with_context(|| {
+ format!(
+ "unknown model {:?}: {} are known",
+ a.model,
+ smbios::MODELS
+ .iter()
+ .map(|m| m.name)
+ .collect::>()
+ .join(" and ")
+ )
+ })?;
+ let mut id = smbios::generate(m)?;
+ if let Some(s) = &a.serial {
+ let s = s.trim().to_ascii_uppercase();
+ if s.len() != 12 {
+ bail!("a serial number here is 12 characters, not {s:?}");
+ }
+ id.serial = s;
+ if a.mlb.is_none() {
+ id.mlb = smbios::mlb_for(m, &id.serial)?;
+ }
+ }
+ if let Some(s) = &a.mlb {
+ let s = s.trim().to_ascii_uppercase();
+ if s.len() != 17 && s.len() != 13 {
+ bail!("an MLB is 17 (or 13) characters, not {s:?}");
+ }
+ id.mlb = s;
+ }
+ if let Some(u) = &a.uuid {
+ id.uuid = smbios::parse_uuid(u)?;
+ }
+ if let Some(r) = &a.rom {
+ id.rom = smbios::parse_rom(r)?;
+ }
+ let mut boot_args = a.boot_args.trim().to_string();
+ if a.verbose_boot && !boot_args.split_whitespace().any(|w| w == "-v") {
+ boot_args = format!("-v {boot_args}").trim().to_string();
+ }
+ let ovmf_dir = if a.no_ovmf {
+ None
+ } else {
+ Some(a.ovmf_dir.clone().unwrap_or_else(|| {
+ a.output
+ .parent()
+ .filter(|p| !p.as_os_str().is_empty())
+ .map(PathBuf::from)
+ .unwrap_or_else(|| PathBuf::from("."))
+ }))
+ };
+ Ok(opencore::Options {
+ output: a.output.clone(),
+ config: config::Options {
+ smbios: id,
+ timeout: a.timeout,
+ boot_args,
+ sip: !a.disable_sip,
+ cpuid_spoof: !a.no_cpuid_spoof,
+ hide_vm: !a.show_vm,
+ },
+ ovmf_dir,
+ })
+}
+
+pub fn print_opencore(out: &opencore::Outputs) {
+ println!("{}", out.image.display());
+ if let Some(o) = &out.ovmf {
+ println!("{}", o.code.display());
+ println!("{}", o.vars.display());
+ }
+ let s = &out.smbios;
+ eprintln!(
+ "\nSMBIOS: {}, serial {}, MLB {}, UUID {}, ROM {}",
+ s.model, s.serial, s.mlb, s.uuid, s.rom
+ );
+}
diff --git a/src/http.rs b/src/http.rs
new file mode 100644
index 0000000..1f6e440
--- /dev/null
+++ b/src/http.rs
@@ -0,0 +1,465 @@
+//! HTTP: small fetches, and downloads that resume.
+//!
+//! A download writes `.part` and renames it to `` once every byte is in and checked,
+//! so an interrupted download (a dropped connection, Ctrl+C, a closed terminal) leaves a `.part`
+//! file that the next run continues from. Or it writes into its place in a bigger file, a disk
+//! image's ([`Dest::Region`]), where the next run continues after what the chunklist passes.
+//!
+//! It asks for the file in ranges of [`SEGMENT`] bytes, each with a time budget: a stalled
+//! connection fails within [`SEGMENT_BUDGET`] and the download goes on from its last byte, on a
+//! new connection. Apple's and GitHub's servers, and
+//! the Arch Linux archive, all answer ranges.
+
+use crate::progress::{self, Reporter};
+use anyhow::{Context, Result, bail};
+use std::fs::{File, OpenOptions};
+use std::io::{Read, Seek, SeekFrom, Write};
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+use ureq::Agent;
+
+/// The most each request asks for.
+pub const SEGMENT: u64 = 64 << 20;
+/// How long a request may take to send its range: a stall is noticed within this. (On a
+/// connection too slow to send a whole range in it, each request sends what it can.)
+pub const SEGMENT_BUDGET: Duration = Duration::from_secs(180);
+/// Failed requests in a row, with no byte received between them, before a download gives up.
+const MAX_FAILURES: u32 = 10;
+
+pub type Headers = Vec<(String, String)>;
+
+pub fn agent() -> Agent {
+ Agent::config_builder()
+ .http_status_as_error(false)
+ .timeout_connect(Some(Duration::from_secs(30)))
+ .timeout_recv_response(Some(Duration::from_secs(60)))
+ .user_agent(concat!("reims-util/", env!("CARGO_PKG_VERSION")))
+ .build()
+ .into()
+}
+
+/// A whole small response: a catalog, a chunklist, a release's manifest.
+pub fn get(agent: &Agent, url: &str, headers: &Headers, limit: u64) -> Result> {
+ let mut failures = 0;
+ loop {
+ let mut req = agent.get(url);
+ for (k, v) in headers {
+ req = req.header(k, v);
+ }
+ let attempt = req
+ .call()
+ .map_err(anyhow::Error::from)
+ .and_then(|mut resp| {
+ let status = resp.status().as_u16();
+ if status != 200 {
+ bail!("{url} answered HTTP {status}");
+ }
+ Ok(resp.body_mut().with_config().limit(limit).read_to_vec()?)
+ });
+ match attempt {
+ Ok(v) => return Ok(v),
+ Err(e) if failures < 3 && retryable(&e) => {
+ failures += 1;
+ std::thread::sleep(Duration::from_secs(1 << failures));
+ }
+ Err(e) => return Err(e.context(format!("fetch {url}"))),
+ }
+ }
+}
+
+fn retryable(e: &anyhow::Error) -> bool {
+ match e.downcast_ref::() {
+ Some(
+ ureq::Error::StatusCode(_) | ureq::Error::BadUri(_) | ureq::Error::BodyExceedsLimit(_),
+ ) => false,
+ Some(_) => true,
+ None => e.to_string().contains("HTTP 5"),
+ }
+}
+
+/// What a download checks as its bytes arrive: a chunklist's chunks, or nothing.
+pub trait Check {
+ /// Reads the `len` bytes from `offset` in `file` that a previous run wrote, and returns how
+ /// many of them are good: the download keeps those and continues after them.
+ fn resume(&mut self, file: &mut File, offset: u64, len: u64, r: &dyn Reporter) -> Result;
+ /// Whether `resume` reads the bytes: without that, only a file's own length says how much a
+ /// previous run wrote.
+ fn verifies(&self) -> bool;
+ /// The next bytes of the file. On a chunk that does not match, returns the offset the file is
+ /// good up to, where the download starts again.
+ fn feed(&mut self, data: &[u8]) -> std::result::Result<(), u64>;
+ /// The download starts again at `offset`, a value `resume` or `feed` returned, or 0.
+ fn restart_at(&mut self, offset: u64);
+ /// Every byte is in: the whole file is good.
+ fn finish(&mut self) -> Result<()>;
+}
+
+/// Checks nothing as the bytes arrive (a pinned file's hash is checked once it is complete).
+pub struct NoCheck;
+
+impl Check for NoCheck {
+ fn resume(&mut self, _: &mut File, _: u64, len: u64, _: &dyn Reporter) -> Result {
+ Ok(len)
+ }
+ fn verifies(&self) -> bool {
+ false
+ }
+ fn feed(&mut self, _: &[u8]) -> std::result::Result<(), u64> {
+ Ok(())
+ }
+ fn restart_at(&mut self, _: u64) {}
+ fn finish(&mut self) -> Result<()> {
+ Ok(())
+ }
+}
+
+pub struct Download<'a> {
+ pub url: String,
+ /// What the download is, as the step it reports: "Downloading OpenCore 1.0.8".
+ pub step: String,
+ pub headers: Headers,
+ /// The file's size, when the caller knows it (a catalog's, a chunklist's).
+ pub size: Option,
+ /// For requests the server refuses (401, 403): new headers, such as a fresh asset token.
+ pub refresh: Option<&'a mut dyn FnMut() -> Result>,
+ pub user_agent: Option<&'static str>,
+}
+
+impl Download<'_> {
+ pub fn new(url: &str, step: String) -> Self {
+ Download {
+ url: url.to_string(),
+ step,
+ headers: Vec::new(),
+ size: None,
+ refresh: None,
+ user_agent: None,
+ }
+ }
+}
+
+/// Where a download goes.
+pub enum Dest<'a> {
+ /// A file of its own: `.part`, renamed to `path` once complete.
+ File(&'a Path),
+ /// `len` bytes of `file` from `offset`, such as a file's place in a disk image. What is there
+ /// already counts as far as the check passes it, and none of it without a check that reads.
+ Region {
+ file: &'a mut File,
+ offset: u64,
+ len: u64,
+ },
+}
+
+pub fn part_path(dest: &Path) -> PathBuf {
+ let mut s = dest.as_os_str().to_owned();
+ s.push(".part");
+ PathBuf::from(s)
+}
+
+/// Downloads `d` to `dest`, continuing what a previous run left there. Returns once `dest`
+/// holds the whole file and `check` passed it.
+pub fn download(
+ agent: &Agent,
+ mut d: Download,
+ dest: Dest,
+ check: &mut dyn Check,
+ r: &dyn Reporter,
+) -> Result<()> {
+ let mut own;
+ let (file, base, part, existing) = match dest {
+ Dest::File(dest) => {
+ let part = part_path(dest);
+ if let Some(dir) = dest.parent()
+ && !dir.as_os_str().is_empty()
+ {
+ std::fs::create_dir_all(dir)
+ .with_context(|| format!("create {}", dir.display()))?;
+ }
+ own = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&part)
+ .with_context(|| format!("open {}", part.display()))?;
+ let len = own.metadata()?.len();
+ (&mut own, 0, Some((part, dest)), len)
+ }
+ Dest::Region { file, offset, len } => {
+ if d.size.is_some_and(|s| s != len) {
+ bail!("{} is not the size of its place", d.url);
+ }
+ d.size = Some(len);
+ let existing = if check.verifies() { len } else { 0 };
+ (file, offset, None, existing)
+ }
+ };
+ // A file of its own is cut back to what is good; a region's bytes stay, to be written over.
+ let cut = |file: &mut File, at: u64| -> Result<()> {
+ if part.is_some() {
+ file.set_len(at)?;
+ }
+ Ok(())
+ };
+ r.step(&d.step);
+ let mut have = if existing > 0 {
+ let good = check.resume(file, base, existing, r)?;
+ if good > 0 && check.verifies() {
+ // The check reported a step of its own; the rest is the download's.
+ r.step(&d.step);
+ }
+ if good < existing {
+ cut(file, good)?;
+ }
+ if good > 0 && d.size.is_none_or(|s| good < s) {
+ r.note(&format!("Resuming at {}", progress::bytes(good)));
+ }
+ good
+ } else {
+ 0
+ };
+ check.restart_at(have);
+ let mut total = d.size;
+ let mut failures = 0u32;
+ let mut bad_chunks = 0u32;
+ let mut buf = vec![0u8; 1 << 18];
+ r.progress(have, total);
+
+ 'requests: loop {
+ progress::check(r)?;
+ if total.is_some_and(|t| have >= t) {
+ break;
+ }
+ let end = match total {
+ Some(t) => (have + SEGMENT).min(t) - 1,
+ None => have + SEGMENT - 1,
+ };
+ let mut req = agent
+ .get(&d.url)
+ .header("Range", format!("bytes={have}-{end}"));
+ for (k, v) in &d.headers {
+ req = req.header(k, v);
+ }
+ let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET));
+ if let Some(ua) = d.user_agent {
+ cfg = cfg.user_agent(ua);
+ }
+ let resp = match cfg.build().call() {
+ Ok(resp) => resp,
+ Err(e) => {
+ failures += 1;
+ retry_or_fail(&mut failures, &format!("{e}"), &d.url, r)?;
+ continue;
+ }
+ };
+ let status = resp.status().as_u16();
+ match status {
+ 206 => {
+ let range = resp
+ .headers()
+ .get("content-range")
+ .and_then(|v| v.to_str().ok())
+ .and_then(content_range)
+ .with_context(|| format!("{} sent a range without Content-Range", d.url))?;
+ if range.0 != have {
+ bail!(
+ "{} sent bytes from {} when asked for {have}",
+ d.url,
+ range.0
+ );
+ }
+ match (total, range.1) {
+ (Some(t), Some(rt)) if t != rt => bail!(
+ "{} is {} long, not the expected {}: it changed on the server",
+ d.url,
+ rt,
+ t
+ ),
+ (None, Some(rt)) => {
+ total = Some(rt);
+ r.progress(have, total);
+ }
+ _ => {}
+ }
+ }
+ 200 => {
+ // The whole file: the server ignored the range.
+ if have > 0 {
+ cut(file, 0)?;
+ have = 0;
+ check.restart_at(0);
+ }
+ if total.is_none() {
+ total = resp.body().content_length();
+ }
+ }
+ 416 if total.is_some_and(|t| have >= t) => break,
+ 416 => {
+ // Past the end: the file on the server is shorter than what we have.
+ if have == 0 {
+ bail!("{} refused every range", d.url);
+ }
+ r.note("The file changed on the server: starting over");
+ cut(file, 0)?;
+ have = 0;
+ check.restart_at(0);
+ continue;
+ }
+ 401 | 403 if d.refresh.is_some() && failures < 3 => {
+ failures += 1;
+ if let Some(f) = d.refresh.as_mut() {
+ d.headers = f()?;
+ }
+ continue;
+ }
+ 408 | 429 | 500..=599 => {
+ failures += 1;
+ retry_or_fail(&mut failures, &format!("HTTP {status}"), &d.url, r)?;
+ continue;
+ }
+ _ => bail!("{} answered HTTP {status}", d.url),
+ }
+
+ file.seek(SeekFrom::Start(base + have))?;
+ let mut body = resp.into_body().into_reader();
+ let start = have;
+ loop {
+ if r.cancelled() {
+ file.flush()?;
+ return Err(progress::Cancelled.into());
+ }
+ let n = match body.read(&mut buf) {
+ Ok(0) => break,
+ Ok(n) => n,
+ Err(e) => {
+ file.flush()?;
+ if have > start {
+ // Cut off partway, which is how a request on a slow connection ends
+ // when its time is up: the next one goes on from here.
+ failures = 0;
+ continue 'requests;
+ }
+ failures += 1;
+ retry_or_fail(&mut failures, &format!("{e}"), &d.url, r)?;
+ continue 'requests;
+ }
+ };
+ let data = match total {
+ Some(t) => &buf[..n.min((t - have) as usize)],
+ None => &buf[..n],
+ };
+ file.write_all(data).context("write the download")?;
+ if let Err(good) = check.feed(data) {
+ bad_chunks += 1;
+ if bad_chunks > 3 {
+ bail!("{} keeps arriving damaged", d.url);
+ }
+ r.note(&format!(
+ "A chunk at {} did not match its checksum: downloading it again",
+ progress::bytes(good)
+ ));
+ file.flush()?;
+ cut(file, good)?;
+ have = good;
+ check.restart_at(good);
+ continue 'requests;
+ }
+ have += data.len() as u64;
+ failures = 0;
+ r.progress(have, total);
+ }
+ if total.is_none() && have < end + 1 {
+ // A server that ignored the range sent the whole file.
+ total = Some(have);
+ }
+ }
+ file.flush()?;
+ check.finish()?;
+ if let Some((part, dest)) = &part {
+ file.sync_all()?;
+ std::fs::rename(part, dest)
+ .with_context(|| format!("rename {} to {}", part.display(), dest.display()))?;
+ }
+ Ok(())
+}
+
+fn retry_or_fail(failures: &mut u32, why: &str, url: &str, r: &dyn Reporter) -> Result<()> {
+ if *failures > MAX_FAILURES {
+ bail!("{url}: {why} (gave up after {MAX_FAILURES} tries; run again to resume)");
+ }
+ let wait = Duration::from_secs((1u64 << (*failures).min(5)).min(30));
+ r.note(&format!(
+ "{why}: trying again in {}",
+ progress::duration(wait.as_secs())
+ ));
+ let until = std::time::Instant::now() + wait;
+ while std::time::Instant::now() < until {
+ progress::check(r)?;
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ Ok(())
+}
+
+/// "bytes 100-199/1000" as (100, Some(1000)); "bytes 100-199/*" as (100, None).
+fn content_range(v: &str) -> Option<(u64, Option)> {
+ let v = v.trim().strip_prefix("bytes")?.trim();
+ let (range, total) = v.split_once('/')?;
+ let (start, _) = range.split_once('-')?;
+ let total = match total.trim() {
+ "*" => None,
+ t => Some(t.parse().ok()?),
+ };
+ Some((start.trim().parse().ok()?, total))
+}
+
+/// Writes a small file whole: a `.part` file renamed over it.
+pub fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
+ let tmp = part_path(path);
+ std::fs::write(&tmp, data).with_context(|| format!("write {}", tmp.display()))?;
+ std::fs::rename(&tmp, path).with_context(|| format!("write {}", path.display()))?;
+ Ok(())
+}
+
+/// The SHA-256 of a file, in lowercase hex.
+pub fn sha256_file(path: &Path) -> Result {
+ use sha2::{Digest, Sha256};
+ let mut f = File::open(path).with_context(|| format!("open {}", path.display()))?;
+ let mut h = Sha256::new();
+ let mut buf = vec![0u8; 1 << 20];
+ loop {
+ let n = f.read(&mut buf)?;
+ if n == 0 {
+ break;
+ }
+ h.update(&buf[..n]);
+ }
+ Ok(hex(&h.finalize()))
+}
+
+pub fn hex(b: &[u8]) -> String {
+ b.iter().map(|x| format!("{x:02x}")).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_content_range() {
+ assert_eq!(
+ content_range("bytes 100-115/960530321"),
+ Some((100, Some(960530321)))
+ );
+ assert_eq!(content_range("bytes 0-0/*"), Some((0, None)));
+ assert_eq!(content_range("items 0-1/2"), None);
+ }
+
+ #[test]
+ fn part_path_appends() {
+ assert_eq!(
+ part_path(Path::new("/a/b.dmg")),
+ PathBuf::from("/a/b.dmg.part")
+ );
+ }
+}
diff --git a/src/image/exfat.rs b/src/image/exfat.rs
new file mode 100644
index 0000000..20906c8
--- /dev/null
+++ b/src/image/exfat.rs
@@ -0,0 +1,499 @@
+//! An exFAT volume holding files in its root folder, as Microsoft's exFAT File System
+//! Specification lays it out:
+//! - the main boot region, sectors 0 to 11: the boot sector, eight extended boot sectors, the
+//! OEM parameters, a reserved sector, and the boot checksum; its backup, sectors 12 to 23;
+//! - one FAT;
+//! - the cluster heap, from cluster 2: the allocation bitmap, the up-case table, the root
+//! folder, then each file in consecutive clusters, with its FAT chain written.
+//!
+//! exFAT is here for what FAT32 cannot hold: a file of 4 GiB or more, such as a macOS installer
+//! package (12 to 18 GB). macOS reads it, macOS Recovery included.
+
+use super::Data;
+use anyhow::{Result, ensure};
+
+const SECTOR: u64 = 512;
+/// Where the FAT starts: past both boot regions, 64 KiB in.
+const FAT_OFFSET: u64 = 128;
+const EOC: u32 = 0xffff_ffff;
+const ENTRY: usize = 32;
+
+/// A volume of `size` bytes (a whole partition) holding `files` in its root folder, as byte
+/// ranges from the volume's start. `partition_offset` is the sector the partition starts at on
+/// its disk; `label` is up to 11 characters; `serial` the volume serial number; `now` a FAT
+/// (date, time), which every file is given.
+pub fn make(
+ size: u64,
+ partition_offset: u64,
+ label: &str,
+ serial: u32,
+ files: &[(String, Data)],
+ now: (u16, u16),
+) -> Result> {
+ ensure!(
+ size.is_multiple_of(SECTOR) && size >= 1 << 20,
+ "an exFAT volume is 1 MiB at least, in whole sectors"
+ );
+ let label: Vec = label.encode_utf16().collect();
+ ensure!(label.len() <= 11, "an exFAT label is 11 characters at most");
+ let volume_sectors = size / SECTOR;
+ let shift = cluster_shift(size);
+ let per_cluster = 1u64 << shift;
+ let cluster_bytes = per_cluster * SECTOR;
+
+ // The FAT is sized for every cluster the volume could have; the heap starts on a cluster
+ // boundary after it.
+ let fat_len = ((volume_sectors / per_cluster + 2) * 4).div_ceil(SECTOR);
+ let heap = (FAT_OFFSET + fat_len).next_multiple_of(per_cluster);
+ ensure!(heap < volume_sectors, "the volume is too small");
+ let clusters = u32::try_from((volume_sectors - heap) / per_cluster)?;
+ ensure!(clusters <= 0xffff_fff5, "the volume has too many clusters");
+
+ let mut fat = vec![0u32; clusters as usize + 2];
+ fat[0] = 0xffff_fff8;
+ fat[1] = EOC;
+ let mut next = 2u32;
+ let mut alloc = |bytes: u64| -> Result {
+ let n = u32::try_from(bytes.div_ceil(cluster_bytes).max(1))?;
+ let first = next;
+ ensure!(
+ u64::from(first) + u64::from(n) <= u64::from(clusters) + 2,
+ "the files do not fit the volume"
+ );
+ for c in first..first + n {
+ fat[c as usize] = if c + 1 == first + n { EOC } else { c + 1 };
+ }
+ next += n;
+ Ok(first)
+ };
+
+ let bitmap_len = u64::from(clusters).div_ceil(8);
+ let bitmap_at = alloc(bitmap_len)?;
+ let upcase = upcase_table();
+ let upcase_at = alloc(upcase.len() as u64)?;
+ let upcase_map = expand_upcase(&upcase);
+
+ let mut entries: Vec<[u8; ENTRY]> = Vec::new();
+ let mut e = [0u8; ENTRY];
+ e[0] = 0x83;
+ e[1] = label.len() as u8;
+ for (i, c) in label.iter().enumerate() {
+ e[2 + i * 2..4 + i * 2].copy_from_slice(&c.to_le_bytes());
+ }
+ entries.push(e);
+ let mut e = [0u8; ENTRY];
+ e[0] = 0x81;
+ e[20..24].copy_from_slice(&bitmap_at.to_le_bytes());
+ e[24..32].copy_from_slice(&bitmap_len.to_le_bytes());
+ entries.push(e);
+ let mut e = [0u8; ENTRY];
+ e[0] = 0x82;
+ e[4..8].copy_from_slice(&checksum32(&upcase).to_le_bytes());
+ e[20..24].copy_from_slice(&upcase_at.to_le_bytes());
+ e[24..32].copy_from_slice(&(upcase.len() as u64).to_le_bytes());
+ entries.push(e);
+
+ let names: Vec> = files
+ .iter()
+ .map(|(name, _)| name.encode_utf16().collect())
+ .collect();
+ for ((name, _), units) in files.iter().zip(&names) {
+ ensure!(
+ !units.is_empty()
+ && units.len() <= 255
+ && !name.chars().any(|c| c < ' ' || "\"*/:<>?\\|".contains(c)),
+ "bad exFAT file name {name:?}"
+ );
+ }
+ let set_entries: usize = names.iter().map(|n| 2 + n.len().div_ceil(15)).sum();
+ // One entry more, unused, ends the folder.
+ let root_at = alloc(((entries.len() + set_entries + 1) * ENTRY) as u64)?;
+
+ let mut pieces = Vec::new();
+ let stamp = (u32::from(now.0) << 16) | u32::from(now.1);
+ for ((_, data), name) in files.iter().zip(&names) {
+ let first = if data.size() == 0 {
+ 0
+ } else {
+ alloc(data.size())?
+ };
+ if data.size() != 0 {
+ pieces.push((first, data.clone()));
+ }
+ entries.extend(file_set(name, &upcase_map, first, data.size(), stamp));
+ }
+ let used = next - 2;
+
+ let mut bitmap = vec![0u8; bitmap_len as usize];
+ for i in 0..used as usize {
+ bitmap[i / 8] |= 1 << (i % 8);
+ }
+
+ let boot = boot_region(&BootSector {
+ partition_offset,
+ volume_sectors,
+ fat_len: fat_len as u32,
+ heap: heap as u32,
+ clusters,
+ root: root_at,
+ serial,
+ shift,
+ percent_in_use: (u64::from(used) * 100 / u64::from(clusters)) as u8,
+ });
+ let cluster_at = |c: u32| (heap + u64::from(c - 2) * per_cluster) * SECTOR;
+ // Each structure fills its sectors or clusters, so none keeps what an earlier image left.
+ let whole = |mut b: Vec, unit: u64| {
+ b.resize(b.len().next_multiple_of(unit as usize), 0);
+ Data::Bytes(b)
+ };
+ let mut out = vec![
+ (0, Data::Bytes(boot.clone())),
+ (12 * SECTOR, Data::Bytes(boot)),
+ (
+ FAT_OFFSET * SECTOR,
+ whole(
+ fat.iter().flat_map(|v| v.to_le_bytes()).collect(),
+ fat_len * SECTOR,
+ ),
+ ),
+ (cluster_at(bitmap_at), whole(bitmap, cluster_bytes)),
+ (cluster_at(upcase_at), whole(upcase, cluster_bytes)),
+ (cluster_at(root_at), whole(entries.concat(), cluster_bytes)),
+ ];
+ out.extend(pieces.into_iter().map(|(c, d)| {
+ let d = match d {
+ Data::Bytes(b) => whole(b, cluster_bytes),
+ reserved => reserved,
+ };
+ (cluster_at(c), d)
+ }));
+ Ok(out)
+}
+
+/// Sectors per cluster, as a power of two, by Microsoft's defaults for the volume's size: 4 KiB
+/// clusters up to 256 MiB, 32 KiB up to 32 GiB, 128 KiB above.
+fn cluster_shift(size: u64) -> u8 {
+ if size <= 256 << 20 {
+ 3
+ } else if size <= 32 << 30 {
+ 6
+ } else {
+ 8
+ }
+}
+
+/// A file's directory entry set: the file entry, its stream extension, and its name in entries
+/// of 15 characters.
+fn file_set(name: &[u16], upcase: &[u16], first: u32, len: u64, stamp: u32) -> Vec<[u8; ENTRY]> {
+ let name_entries = name.len().div_ceil(15);
+ let mut set = Vec::with_capacity(2 + name_entries);
+ let mut e = [0u8; ENTRY];
+ e[0] = 0x85;
+ e[1] = (1 + name_entries) as u8;
+ e[4..6].copy_from_slice(&0x20u16.to_le_bytes()); // archive
+ for at in [8, 12, 16] {
+ e[at..at + 4].copy_from_slice(&stamp.to_le_bytes());
+ }
+ // The times are UTC: a valid offset of 0.
+ e[22..25].fill(0x80);
+ set.push(e);
+ let mut e = [0u8; ENTRY];
+ e[0] = 0xc0;
+ e[1] = 0x01; // allocation possible; the FAT holds the chain
+ e[3] = name.len() as u8;
+ let hashed: Vec = name
+ .iter()
+ .map(|&c| upcase.get(c as usize).copied().unwrap_or(c))
+ .collect();
+ e[4..6].copy_from_slice(&name_hash(&hashed).to_le_bytes());
+ e[8..16].copy_from_slice(&len.to_le_bytes());
+ e[20..24].copy_from_slice(&first.to_le_bytes());
+ e[24..32].copy_from_slice(&len.to_le_bytes());
+ set.push(e);
+ for part in name.chunks(15) {
+ let mut e = [0u8; ENTRY];
+ e[0] = 0xc1;
+ for (i, c) in part.iter().enumerate() {
+ e[2 + i * 2..4 + i * 2].copy_from_slice(&c.to_le_bytes());
+ }
+ set.push(e);
+ }
+ let sum = set_checksum(&set.concat());
+ set[0][2..4].copy_from_slice(&sum.to_le_bytes());
+ set
+}
+
+struct BootSector {
+ partition_offset: u64,
+ volume_sectors: u64,
+ fat_len: u32,
+ heap: u32,
+ clusters: u32,
+ root: u32,
+ serial: u32,
+ shift: u8,
+ percent_in_use: u8,
+}
+
+/// The 12 sectors of a boot region: the boot sector, the extended boot sectors, the OEM
+/// parameters and the reserved sector (both empty), and the checksum of the 11 before it.
+fn boot_region(b: &BootSector) -> Vec {
+ let mut r = vec![0u8; 12 * SECTOR as usize];
+ let s = &mut r[..SECTOR as usize];
+ s[0..3].copy_from_slice(&[0xeb, 0x76, 0x90]);
+ s[3..11].copy_from_slice(b"EXFAT ");
+ s[64..72].copy_from_slice(&b.partition_offset.to_le_bytes());
+ s[72..80].copy_from_slice(&b.volume_sectors.to_le_bytes());
+ s[80..84].copy_from_slice(&(FAT_OFFSET as u32).to_le_bytes());
+ s[84..88].copy_from_slice(&b.fat_len.to_le_bytes());
+ s[88..92].copy_from_slice(&b.heap.to_le_bytes());
+ s[92..96].copy_from_slice(&b.clusters.to_le_bytes());
+ s[96..100].copy_from_slice(&b.root.to_le_bytes());
+ s[100..104].copy_from_slice(&b.serial.to_le_bytes());
+ s[104..106].copy_from_slice(&[0x00, 0x01]); // revision 1.00
+ s[108] = 9; // 512-byte sectors
+ s[109] = b.shift;
+ s[110] = 1; // one FAT
+ s[111] = 0x80;
+ s[112] = b.percent_in_use;
+ // No boot code: halt.
+ s[120..510].fill(0xf4);
+ s[510] = 0x55;
+ s[511] = 0xaa;
+ for i in 1..=8 {
+ let end = (i + 1) * SECTOR as usize;
+ r[end - 2] = 0x55;
+ r[end - 1] = 0xaa;
+ }
+ let sum = boot_checksum(&r[..11 * SECTOR as usize]);
+ for c in r[11 * SECTOR as usize..].chunks_mut(4) {
+ c.copy_from_slice(&sum.to_le_bytes());
+ }
+ r
+}
+
+/// The boot checksum, which leaves out the boot sector's volume flags and percent in use.
+fn boot_checksum(sectors: &[u8]) -> u32 {
+ sectors
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| !matches!(i, 106 | 107 | 112))
+ .fold(0u32, |s, (_, b)| {
+ s.rotate_right(1).wrapping_add(u32::from(*b))
+ })
+}
+
+/// An entry set's checksum, which leaves out the checksum's own two bytes.
+fn set_checksum(set: &[u8]) -> u16 {
+ set.iter()
+ .enumerate()
+ .filter(|(i, _)| !matches!(i, 2 | 3))
+ .fold(0u16, |s, (_, b)| {
+ s.rotate_right(1).wrapping_add(u16::from(*b))
+ })
+}
+
+/// The hash of an up-cased name, over its UTF-16 code units' bytes.
+fn name_hash(upcased: &[u16]) -> u16 {
+ upcased
+ .iter()
+ .flat_map(|c| c.to_le_bytes())
+ .fold(0u16, |s, b| s.rotate_right(1).wrapping_add(u16::from(b)))
+}
+
+/// The up-case table's checksum.
+fn checksum32(bytes: &[u8]) -> u32 {
+ bytes
+ .iter()
+ .fold(0u32, |s, b| s.rotate_right(1).wrapping_add(u32::from(*b)))
+}
+
+/// The up-case table, compressed as the specification allows: each code unit's upper case in
+/// turn, with a run of ones that map to themselves written as 0xFFFF and the run's length. The
+/// mapping is Unicode's simple upper case of each BMP character.
+fn upcase_table() -> Vec {
+ let up = |c: u32| -> u32 {
+ let Some(ch) = char::from_u32(c) else {
+ return c;
+ };
+ let mut u = ch.to_uppercase();
+ match (u.next(), u.next()) {
+ (Some(x), None) if (x as u32) < 0x1_0000 => x as u32,
+ _ => c,
+ }
+ };
+ let mut table: Vec = Vec::new();
+ let mut c = 0u32;
+ while c < 0x1_0000 {
+ if up(c) != c {
+ table.push(up(c) as u16);
+ c += 1;
+ continue;
+ }
+ let start = c;
+ while c < 0x1_0000 && up(c) == c {
+ c += 1;
+ }
+ // A run that reaches 0xFFFF is always compressed, so 0xFFFF is never a mapping.
+ if c - start > 2 || c == 0x1_0000 {
+ table.push(0xffff);
+ table.push((c - start) as u16);
+ } else {
+ table.extend((start..c).map(|k| k as u16));
+ }
+ }
+ table.iter().flat_map(|u| u.to_le_bytes()).collect()
+}
+
+/// A compressed up-case table as a code unit's upper case, by index.
+fn expand_upcase(table: &[u8]) -> Vec {
+ let units: Vec = table
+ .as_chunks::<2>()
+ .0
+ .iter()
+ .map(|b| u16::from_le_bytes(*b))
+ .collect();
+ let mut map = Vec::with_capacity(0x1_0000);
+ let mut i = 0;
+ while i < units.len() {
+ if units[i] == 0xffff && i + 1 < units.len() {
+ let n = units[i + 1];
+ for _ in 0..n {
+ map.push(map.len() as u16);
+ }
+ i += 2;
+ } else {
+ map.push(units[i]);
+ i += 1;
+ }
+ }
+ map
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The files in the root folder of a volume `make` wrote, read back through its structures.
+ fn list(vol: &[u8]) -> Vec<(String, Vec)> {
+ let u32_at = |o: usize| u32::from_le_bytes(vol[o..o + 4].try_into().unwrap());
+ let fat_at = u32_at(80) as usize * 512;
+ let heap = u32_at(88) as usize * 512;
+ let cluster = 512usize << vol[109];
+ let chain = |first: u32, len: usize| -> Vec {
+ let mut out = Vec::new();
+ let mut c = first;
+ while (2..0xffff_fff7).contains(&c) {
+ let at = heap + (c as usize - 2) * cluster;
+ out.extend_from_slice(&vol[at..at + cluster]);
+ c = u32_at(fat_at + c as usize * 4);
+ }
+ out.truncate(len);
+ out
+ };
+ let root = chain(u32_at(96), usize::MAX);
+ let mut files = Vec::new();
+ let mut i = 0;
+ while root[i * 32] != 0 {
+ let e = &root[i * 32..i * 32 + 32];
+ if e[0] != 0x85 {
+ i += 1;
+ continue;
+ }
+ let n = e[1] as usize;
+ let set = &root[i * 32..(i + 1 + n) * 32];
+ assert_eq!(
+ set_checksum(set),
+ u16::from_le_bytes([e[2], e[3]]),
+ "the set checksum"
+ );
+ let s = &set[32..64];
+ let name_len = s[3] as usize;
+ let mut name: Vec = Vec::new();
+ for k in 0..n - 1 {
+ let f = &set[64 + k * 32..96 + k * 32];
+ for j in 0..15 {
+ name.push(u16::from_le_bytes([f[2 + j * 2], f[3 + j * 2]]));
+ }
+ }
+ name.truncate(name_len);
+ let len = u64::from_le_bytes(s[24..32].try_into().unwrap()) as usize;
+ let first = u32::from_le_bytes(s[20..24].try_into().unwrap());
+ files.push((String::from_utf16(&name).unwrap(), chain(first, len)));
+ i += 1 + n;
+ }
+ files
+ }
+
+ fn volume(size: u64, files: &[(&str, Vec)]) -> Vec {
+ let files: Vec<(String, Data)> = files
+ .iter()
+ .map(|(n, d)| (n.to_string(), Data::Bytes(d.clone())))
+ .collect();
+ let pieces = make(size, 2048, "Installer", 7, &files, (0x5b4c, 0)).unwrap();
+ super::super::Disk { size, pieces }.to_bytes().unwrap()
+ }
+
+ #[test]
+ fn writes_files_that_read_back() {
+ let big: Vec = (0..200_000u32).map(|i| (i % 253) as u8).collect();
+ let vol = volume(
+ 64 << 20,
+ &[
+ ("InstallAssistant.pkg", big.clone()),
+ ("install-macos.sh", b"#!/bin/sh\n".to_vec()),
+ ("empty", Vec::new()),
+ ],
+ );
+ let got = list(&vol);
+ assert_eq!(got[0], ("InstallAssistant.pkg".to_string(), big));
+ assert_eq!(got[1].1, b"#!/bin/sh\n");
+ assert_eq!(got[2], ("empty".to_string(), Vec::new()));
+ // The backup boot region is the main one.
+ assert_eq!(vol[..12 * 512], vol[12 * 512..24 * 512]);
+ assert_eq!(&vol[64..72], &2048u64.to_le_bytes());
+ }
+
+ #[test]
+ fn boot_checksum_covers_the_region() {
+ let vol = volume(64 << 20, &[("a", vec![1])]);
+ let sum = boot_checksum(&vol[..11 * 512]);
+ for c in vol[11 * 512..12 * 512].chunks(4) {
+ assert_eq!(c, sum.to_le_bytes());
+ }
+ // Volume flags and percent in use are left out.
+ let mut v = vol[..11 * 512].to_vec();
+ v[106] ^= 1;
+ v[112] ^= 0x7f;
+ assert_eq!(boot_checksum(&v), sum);
+ }
+
+ #[test]
+ fn upcase_table_maps_letters() {
+ let map = expand_upcase(&upcase_table());
+ assert_eq!(map.len(), 0x1_0000);
+ assert_eq!(map['a' as usize], 'A' as u16);
+ assert_eq!(map['z' as usize], 'Z' as u16);
+ assert_eq!(map['A' as usize], 'A' as u16);
+ assert_eq!(map['é' as usize], 'É' as u16);
+ assert_eq!(map['1' as usize], '1' as u16);
+ assert_eq!(map[0xffff], 0xffff);
+ }
+
+ #[test]
+ fn hashes_names_as_the_specification_does() {
+ // NameHash = ((NameHash & 1) ? 0x8000 : 0) + (NameHash >> 1) + byte, over each byte.
+ let mut h = 0u16;
+ for b in "ABC".encode_utf16().flat_map(|c| c.to_le_bytes()) {
+ h = (if h & 1 != 0 { 0x8000 } else { 0 }) + (h >> 1) + u16::from(b);
+ }
+ assert_eq!(name_hash(&"ABC".encode_utf16().collect::>()), h);
+ }
+
+ #[test]
+ fn picks_cluster_sizes() {
+ assert_eq!(cluster_shift(64 << 20), 3);
+ assert_eq!(cluster_shift(18 << 30), 6);
+ assert_eq!(cluster_shift(40 << 30), 8);
+ }
+}
diff --git a/src/image/fat32.rs b/src/image/fat32.rs
new file mode 100644
index 0000000..ac69c0c
--- /dev/null
+++ b/src/image/fat32.rs
@@ -0,0 +1,603 @@
+//! A FAT32 volume holding a list of files, as Microsoft's FAT specification (FAT: General
+//! Overview of On-Disk Format, 1.03) lays it out:
+//! - 32 reserved sectors: the boot sector, the FSInfo sector, and their backups at 6 and 7;
+//! - two FATs, sized by the specification's formula;
+//! - the data region, cluster 2 first, which is the root directory.
+//!
+//! Clusters are the size the specification's table gives the volume's (512 bytes up to 260 MiB,
+//! 4 KiB up to 8 GiB). Each folder and file takes consecutive clusters, folders first, in the
+//! order given. Names that are not plain upper-case 8.3 names get long-name entries, with a
+//! `~1`-style short name. The volume is made as the byte ranges it holds (image/mod.rs).
+
+use super::Data;
+use anyhow::{Result, bail, ensure};
+
+const SECTOR: usize = 512;
+const RESERVED: u32 = 32;
+const FATS: u32 = 2;
+const ATTR_DIRECTORY: u8 = 0x10;
+const ATTR_ARCHIVE: u8 = 0x20;
+const ATTR_VOLUME_ID: u8 = 0x08;
+const ATTR_LONG_NAME: u8 = 0x0f;
+const EOC: u32 = 0x0fff_ffff;
+
+/// A folder's contents, by name: a file's data, or a folder.
+#[derive(Default)]
+struct Dir {
+ entries: Vec<(String, Node)>,
+}
+
+enum Node {
+ File(Data),
+ Dir(Dir),
+}
+
+impl Dir {
+ fn insert(&mut self, path: &[&str], data: Option) -> Result<()> {
+ let Some((first, rest)) = path.split_first() else {
+ return Ok(());
+ };
+ let found = self
+ .entries
+ .iter_mut()
+ .find(|(n, _)| n.eq_ignore_ascii_case(first));
+ if rest.is_empty() {
+ match (found, data) {
+ (None, Some(d)) => self.entries.push((first.to_string(), Node::File(d))),
+ (None, None) => self
+ .entries
+ .push((first.to_string(), Node::Dir(Dir::default()))),
+ (Some((_, Node::Dir(_))), None) => {}
+ (Some(_), _) => bail!("{first} is given twice"),
+ }
+ return Ok(());
+ }
+ match found {
+ Some((_, Node::Dir(d))) => d.insert(rest, data),
+ Some(_) => bail!("{first} is a file and a folder"),
+ None => {
+ let mut d = Dir::default();
+ d.insert(rest, data)?;
+ self.entries.push((first.to_string(), Node::Dir(d)));
+ Ok(())
+ }
+ }
+ }
+}
+
+/// A volume of `size` bytes (a whole partition, in 512-byte sectors) holding `files` at their
+/// slash-separated paths, as byte ranges from the volume's start; a path ending in `/` is an
+/// empty folder. `hidden_sectors` is where the partition starts on its disk; `label` is up to 11
+/// characters; `serial` the volume ID.
+pub fn make(
+ size: u64,
+ hidden_sectors: u32,
+ label: &str,
+ serial: u32,
+ files: &[(String, Data)],
+ now: (u16, u16),
+) -> Result> {
+ let mut root = Dir::default();
+ for (path, data) in files {
+ let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
+ ensure!(!parts.is_empty(), "empty path");
+ let data = if path.ends_with('/') {
+ None
+ } else {
+ ensure!(
+ data.size() <= u64::from(u32::MAX),
+ "{path} is 4 GiB or more, which FAT32 cannot hold"
+ );
+ Some(data.clone())
+ };
+ root.insert(&parts, data)?;
+ }
+
+ ensure!(
+ size.is_multiple_of(SECTOR as u64),
+ "the volume is not whole sectors"
+ );
+ let total = u32::try_from(size / SECTOR as u64)?;
+ let per_cluster = sectors_per_cluster(total);
+ let cluster_bytes = u64::from(per_cluster) * SECTOR as u64;
+ let fat_size = {
+ let tmp1 = total - RESERVED;
+ let tmp2 = (256 * per_cluster + FATS) / 2;
+ tmp1.div_ceil(tmp2)
+ };
+ let data_start = RESERVED + FATS * fat_size;
+ let clusters = (total - data_start) / per_cluster;
+ ensure!(
+ (65525..268_435_445).contains(&clusters),
+ "{clusters} clusters is not a FAT32 volume"
+ );
+
+ // Lay the tree out: each folder's entries, and the clusters of every folder and file.
+ let mut fat = vec![0u32; clusters as usize + 2];
+ fat[0] = 0x0fff_fff8;
+ fat[1] = EOC;
+ let mut next = 2u32;
+ let mut alloc = |bytes: u64| -> Result {
+ let n = u32::try_from(bytes.div_ceil(cluster_bytes).max(1))?;
+ let first = next;
+ ensure!(
+ u64::from(first) + u64::from(n) <= u64::from(clusters) + 2,
+ "the files do not fit the volume"
+ );
+ for c in first..first + n {
+ fat[c as usize] = if c + 1 == first + n { EOC } else { c + 1 };
+ }
+ next += n;
+ Ok(first)
+ };
+ let mut writes: Vec<(u32, Data)> = Vec::new();
+ lay_out(&root, 0, true, label, now, &mut alloc, &mut writes)?;
+ let used = next - 2;
+
+ let sector = |n: u32| u64::from(n) * SECTOR as u64;
+ let bs = boot_sector(total, per_cluster, fat_size, hidden_sectors, label, serial);
+ let fsinfo = fsinfo(clusters - used, next);
+ // Each structure fills its sectors or clusters, so none keeps what an earlier image left.
+ let mut fat: Vec = fat.iter().flat_map(|v| v.to_le_bytes()).collect();
+ fat.resize(fat_size as usize * SECTOR, 0);
+ let mut out = vec![
+ (0, Data::Bytes(bs.to_vec())),
+ (sector(1), Data::Bytes(fsinfo.to_vec())),
+ (sector(6), Data::Bytes(bs.to_vec())),
+ (sector(7), Data::Bytes(fsinfo.to_vec())),
+ ];
+ for f in 0..FATS {
+ out.push((sector(RESERVED + f * fat_size), Data::Bytes(fat.clone())));
+ }
+ for (cluster, data) in writes {
+ let data = match data {
+ Data::Bytes(mut b) => {
+ b.resize(b.len().next_multiple_of(cluster_bytes as usize), 0);
+ Data::Bytes(b)
+ }
+ reserved => reserved,
+ };
+ out.push((sector(data_start + (cluster - 2) * per_cluster), data));
+ }
+ Ok(out)
+}
+
+/// Sectors per cluster, by the specification's table for FAT32 volumes of `total` sectors.
+fn sectors_per_cluster(total: u32) -> u32 {
+ match total {
+ 0..=532_480 => 1,
+ 532_481..=16_777_216 => 8,
+ 16_777_217..=33_554_432 => 16,
+ 33_554_433..=67_108_864 => 32,
+ _ => 64,
+ }
+}
+
+/// Allocates `dir` (at the root when `root`) and everything under it, depth first, and queues
+/// what each cluster run holds. Returns the folder's first cluster.
+fn lay_out(
+ dir: &Dir,
+ parent: u32,
+ root: bool,
+ label: &str,
+ now: (u16, u16),
+ alloc: &mut dyn FnMut(u64) -> Result,
+ writes: &mut Vec<(u32, Data)>,
+) -> Result {
+ // The folder's size first: its clusters come before its children's.
+ let mut shorts: Vec<[u8; 11]> = Vec::new();
+ let mut names = Vec::new();
+ for (name, _) in &dir.entries {
+ let (short, long) = short_name(name, &shorts)?;
+ shorts.push(short);
+ names.push((short, long));
+ }
+ let count = usize::from(root)
+ + if root { 0 } else { 2 }
+ + names
+ .iter()
+ .map(|(_, l)| 1 + l.as_ref().map_or(0, |u| u.len().div_ceil(13)))
+ .sum::();
+ let me = alloc(count as u64 * 32)?;
+
+ let mut entries: Vec<[u8; 32]> = Vec::new();
+ if root {
+ let mut l = [b' '; 11];
+ for (d, c) in l.iter_mut().zip(label.bytes()) {
+ *d = c.to_ascii_uppercase();
+ }
+ entries.push(entry(&l, ATTR_VOLUME_ID, 0, 0, now));
+ } else {
+ entries.push(entry(b". ", ATTR_DIRECTORY, me, 0, now));
+ // ".." names the root as cluster 0.
+ entries.push(entry(b".. ", ATTR_DIRECTORY, parent, 0, now));
+ }
+ for ((_, node), (short, long)) in dir.entries.iter().zip(names) {
+ let (attr, first, size) = match node {
+ Node::File(data) => {
+ let first = if data.size() == 0 {
+ 0
+ } else {
+ alloc(data.size())?
+ };
+ if data.size() != 0 {
+ writes.push((first, data.clone()));
+ }
+ (ATTR_ARCHIVE, first, data.size() as u32)
+ }
+ Node::Dir(d) => {
+ let first = lay_out(
+ d,
+ if root { 0 } else { me },
+ false,
+ label,
+ now,
+ alloc,
+ writes,
+ )?;
+ (ATTR_DIRECTORY, first, 0)
+ }
+ };
+ if let Some(long) = long {
+ entries.extend(long_entries(&long, &short));
+ }
+ entries.push(entry(&short, attr, first, size, now));
+ }
+ writes.push((me, Data::Bytes(entries.concat())));
+ Ok(me)
+}
+
+fn entry(name: &[u8; 11], attr: u8, cluster: u32, size: u32, (date, time): (u16, u16)) -> [u8; 32] {
+ let mut e = [0u8; 32];
+ e[0..11].copy_from_slice(name);
+ e[11] = attr;
+ e[14..16].copy_from_slice(&time.to_le_bytes());
+ e[16..18].copy_from_slice(&date.to_le_bytes());
+ e[18..20].copy_from_slice(&date.to_le_bytes());
+ e[20..22].copy_from_slice(&((cluster >> 16) as u16).to_le_bytes());
+ e[22..24].copy_from_slice(&time.to_le_bytes());
+ e[24..26].copy_from_slice(&date.to_le_bytes());
+ e[26..28].copy_from_slice(&(cluster as u16).to_le_bytes());
+ e[28..32].copy_from_slice(&size.to_le_bytes());
+ e
+}
+
+/// The 8.3 name for `name`, and its UTF-16 long name unless the short name holds it as it is. A
+/// name that fits 8.3 keeps it, upper-cased (`BOOTx64.efi` is `BOOTX64.EFI`, which firmware
+/// looking for the removable-media boot path finds); any other gets a `~1`-style one.
+fn short_name(name: &str, taken: &[[u8; 11]]) -> Result<([u8; 11], Option>)> {
+ ensure!(
+ !name.is_empty() && name.len() <= 255 && name != "." && name != "..",
+ "bad file name {name:?}"
+ );
+ let valid = |c: char| c.is_ascii_alphanumeric() || "$%'-_@~`!(){}^#&".contains(c);
+ let (base, ext) = match name.rfind('.') {
+ Some(i) if i > 0 => (&name[..i], &name[i + 1..]),
+ _ => (name, ""),
+ };
+ let long = || Some(name.encode_utf16().collect());
+ let fits = base.len() <= 8
+ && ext.len() <= 3
+ && !base.is_empty()
+ && base.chars().all(valid)
+ && ext.chars().all(valid);
+ if fits {
+ let mut short = [b' '; 11];
+ short[..base.len()].copy_from_slice(base.to_ascii_uppercase().as_bytes());
+ short[8..8 + ext.len()].copy_from_slice(ext.to_ascii_uppercase().as_bytes());
+ if !taken.contains(&short) {
+ let upper = !name.chars().any(|c| c.is_ascii_lowercase());
+ return Ok((short, if upper { None } else { long() }));
+ }
+ }
+ let clean = |s: &str, n: usize| -> Vec {
+ s.chars()
+ .filter(|c| *c != ' ' && *c != '.')
+ .map(|c| {
+ if valid(c) {
+ c.to_ascii_uppercase() as u8
+ } else {
+ b'_'
+ }
+ })
+ .take(n)
+ .collect()
+ };
+ let b = clean(base.trim_start_matches('.'), 6);
+ let e = clean(ext, 3);
+ for n in 1..1_000_000 {
+ let tail = format!("~{n}");
+ let keep = b.len().min(8 - tail.len());
+ let mut s = [b' '; 11];
+ s[..keep].copy_from_slice(&b[..keep]);
+ s[keep..keep + tail.len()].copy_from_slice(tail.as_bytes());
+ s[8..8 + e.len()].copy_from_slice(&e);
+ if !taken.contains(&s) {
+ return Ok((s, long()));
+ }
+ }
+ bail!("no short name for {name:?}")
+}
+
+fn checksum(short: &[u8; 11]) -> u8 {
+ short
+ .iter()
+ .fold(0u8, |s, c| s.rotate_right(1).wrapping_add(*c))
+}
+
+/// The long-name entries for `long`, in the order they are stored: the last part first.
+fn long_entries(long: &[u16], short: &[u8; 11]) -> Vec<[u8; 32]> {
+ let sum = checksum(short);
+ let parts = long.len().div_ceil(13);
+ let mut out = Vec::new();
+ for i in (0..parts).rev() {
+ let mut chars = [0xffffu16; 13];
+ for (j, slot) in chars.iter_mut().enumerate() {
+ let k = i * 13 + j;
+ if k < long.len() {
+ *slot = long[k];
+ } else if k == long.len() {
+ *slot = 0;
+ }
+ }
+ let mut e = [0u8; 32];
+ e[0] = (i as u8 + 1) | if i + 1 == parts { 0x40 } else { 0 };
+ e[11] = ATTR_LONG_NAME;
+ e[13] = sum;
+ for (j, c) in chars.iter().enumerate() {
+ let at = match j {
+ 0..5 => 1 + j * 2,
+ 5..11 => 14 + (j - 5) * 2,
+ _ => 28 + (j - 11) * 2,
+ };
+ e[at..at + 2].copy_from_slice(&c.to_le_bytes());
+ }
+ out.push(e);
+ }
+ out
+}
+
+fn boot_sector(
+ total: u32,
+ per_cluster: u32,
+ fat_size: u32,
+ hidden: u32,
+ label: &str,
+ serial: u32,
+) -> [u8; SECTOR] {
+ let mut b = [0u8; SECTOR];
+ b[0..3].copy_from_slice(&[0xeb, 0x58, 0x90]);
+ b[3..11].copy_from_slice(b"MSWIN4.1");
+ b[11..13].copy_from_slice(&(SECTOR as u16).to_le_bytes());
+ b[13] = per_cluster as u8;
+ b[14..16].copy_from_slice(&(RESERVED as u16).to_le_bytes());
+ b[16] = FATS as u8;
+ b[21] = 0xf8; // media: fixed disk
+ b[24..26].copy_from_slice(&63u16.to_le_bytes());
+ b[26..28].copy_from_slice(&255u16.to_le_bytes());
+ b[28..32].copy_from_slice(&hidden.to_le_bytes());
+ b[32..36].copy_from_slice(&total.to_le_bytes());
+ b[36..40].copy_from_slice(&fat_size.to_le_bytes());
+ b[44..48].copy_from_slice(&2u32.to_le_bytes()); // root cluster
+ b[48..50].copy_from_slice(&1u16.to_le_bytes()); // FSInfo sector
+ b[50..52].copy_from_slice(&6u16.to_le_bytes()); // backup boot sector
+ b[64] = 0x80;
+ b[66] = 0x29;
+ b[67..71].copy_from_slice(&serial.to_le_bytes());
+ let mut l = [b' '; 11];
+ for (d, c) in l.iter_mut().zip(label.bytes()) {
+ *d = c.to_ascii_uppercase();
+ }
+ b[71..82].copy_from_slice(&l);
+ b[82..90].copy_from_slice(b"FAT32 ");
+ b[510] = 0x55;
+ b[511] = 0xaa;
+ b
+}
+
+fn fsinfo(free: u32, next_free: u32) -> [u8; SECTOR] {
+ let mut b = [0u8; SECTOR];
+ b[0..4].copy_from_slice(&0x4161_5252u32.to_le_bytes());
+ b[484..488].copy_from_slice(&0x6141_7272u32.to_le_bytes());
+ b[488..492].copy_from_slice(&free.to_le_bytes());
+ b[492..496].copy_from_slice(&next_free.to_le_bytes());
+ b[508..512].copy_from_slice(&0xaa55_0000u32.to_le_bytes());
+ b
+}
+
+/// A UTC time as FAT's (date, time): days since 1980 and 2-second units.
+pub fn dos_time(t: std::time::SystemTime) -> (u16, u16) {
+ let secs = t
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ let (y, m, d) = civil(secs / 86400);
+ let s = secs % 86400;
+ if y < 1980 {
+ return (0x21, 0);
+ }
+ let date = (((y - 1980) as u16) << 9) | ((m as u16) << 5) | d as u16;
+ let time =
+ (((s / 3600) as u16) << 11) | ((((s / 60) % 60) as u16) << 5) | ((s % 60) / 2) as u16;
+ (date, time)
+}
+
+/// Days since 1970-01-01 as (year, month, day), by Howard Hinnant's civil_from_days.
+pub fn civil(days: u64) -> (i64, u32, u32) {
+ let z = days as i64 + 719468;
+ let era = z.div_euclid(146097);
+ let doe = z - era * 146097;
+ let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
+ (yoe + era * 400 + i64::from(m <= 2), m, d)
+}
+
+/// The files and folders of a volume `make` wrote, by path: for tests.
+#[cfg(test)]
+fn list(volume: &[u8]) -> std::collections::BTreeMap> {
+ let u16_at = |b: &[u8], o: usize| u16::from_le_bytes([b[o], b[o + 1]]) as u32;
+ let u32_at = |b: &[u8], o: usize| u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]);
+ let per_cluster = volume[13] as u32;
+ let fat_size = u32_at(volume, 36);
+ let data_start = RESERVED + FATS * fat_size;
+ let fat = |c: u32| u32_at(volume, RESERVED as usize * SECTOR + c as usize * 4);
+ let read = |first: u32, size: Option| -> Vec {
+ let mut out = Vec::new();
+ let mut c = first;
+ while (2..0x0fff_fff8).contains(&c) {
+ let at = (data_start + (c - 2) * per_cluster) as usize * SECTOR;
+ out.extend_from_slice(&volume[at..at + per_cluster as usize * SECTOR]);
+ c = fat(c);
+ }
+ if let Some(s) = size {
+ out.truncate(s as usize);
+ }
+ out
+ };
+ let mut files = std::collections::BTreeMap::new();
+ let mut stack = vec![(String::new(), 2u32)];
+ while let Some((path, cluster)) = stack.pop() {
+ let d = read(cluster, None);
+ let mut long: Vec = Vec::new();
+ for e in d.chunks(32) {
+ if e[0] == 0 {
+ break;
+ }
+ if e[11] == ATTR_LONG_NAME {
+ let mut part = Vec::new();
+ for at in [1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30] {
+ let c = u16_at(e, at) as u16;
+ if c == 0 || c == 0xffff {
+ break;
+ }
+ part.push(c);
+ }
+ part.extend(long);
+ long = part;
+ continue;
+ }
+ if e[11] & ATTR_VOLUME_ID != 0 || e[0] == b'.' {
+ long.clear();
+ continue;
+ }
+ let name = if long.is_empty() {
+ let b = String::from_utf8_lossy(&e[0..8]).trim_end().to_string();
+ let x = String::from_utf8_lossy(&e[8..11]).trim_end().to_string();
+ if x.is_empty() { b } else { format!("{b}.{x}") }
+ } else {
+ String::from_utf16_lossy(&long)
+ };
+ long.clear();
+ let first = (u16_at(e, 20) << 16) | u16_at(e, 26);
+ let p = format!("{path}/{name}");
+ if e[11] & ATTR_DIRECTORY != 0 {
+ files.insert(format!("{p}/"), Vec::new());
+ stack.push((p, first));
+ } else {
+ files.insert(p, read(first, Some(u32_at(e, 28))));
+ }
+ }
+ }
+ files
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn volume(size: u64, files: &[(&str, &[u8])]) -> Vec {
+ let files: Vec<(String, Data)> = files
+ .iter()
+ .map(|(p, d)| (p.to_string(), Data::Bytes(d.to_vec())))
+ .collect();
+ let pieces = make(size, 2048, "OPENCORE", 1, &files, (0x5b4c, 0)).unwrap();
+ super::super::Disk { size, pieces }.to_bytes().unwrap()
+ }
+
+ #[test]
+ fn writes_files_that_read_back() {
+ let big: Vec = (0..3000u32).map(|i| i as u8).collect();
+ let vol = volume(
+ 40 << 20,
+ &[
+ ("EFI/BOOT/BOOTx64.efi", b"boot"),
+ ("EFI/BOOT/.contentFlavour", b"OpenCore"),
+ ("EFI/OC/config.plist", &big),
+ ("EFI/OC/Kexts/", b""),
+ ("README.TXT", b"hi"),
+ ],
+ );
+ assert_eq!(vol[13], 1);
+ let got = list(&vol);
+ assert_eq!(got["/EFI/BOOT/BOOTx64.efi"], b"boot");
+ assert_eq!(got["/EFI/BOOT/.contentFlavour"], b"OpenCore");
+ assert_eq!(got["/EFI/OC/config.plist"], big);
+ assert!(got.contains_key("/EFI/OC/Kexts/"));
+ assert_eq!(got["/README.TXT"], b"hi");
+ assert_eq!(&vol[510..512], &[0x55, 0xaa]);
+ assert_eq!(&vol[82..90], b"FAT32 ");
+ }
+
+ #[test]
+ fn larger_volumes_take_larger_clusters() {
+ let big: Vec = (0..100_000u32).map(|i| (i % 7) as u8).collect();
+ let vol = volume(
+ 300 << 20,
+ &[
+ ("com.apple.recovery.boot/BaseSystem.dmg", &big),
+ ("com.apple.recovery.boot/BaseSystem.chunklist", b"CNKL"),
+ ],
+ );
+ assert_eq!(vol[13], 8);
+ let got = list(&vol);
+ assert_eq!(got["/com.apple.recovery.boot/BaseSystem.dmg"], big);
+ assert_eq!(
+ got["/com.apple.recovery.boot/BaseSystem.chunklist"],
+ b"CNKL"
+ );
+ }
+
+ #[test]
+ fn makes_short_names() {
+ let (s, l) = short_name("EFI", &[]).unwrap();
+ assert_eq!(&s, b"EFI ");
+ assert!(l.is_none());
+ let (s, l) = short_name("OpenCore.efi", &[]).unwrap();
+ assert_eq!(&s, b"OPENCOREEFI");
+ assert!(l.is_some());
+ let (s, _) = short_name("OpenRuntime.efi", &[]).unwrap();
+ assert_eq!(&s, b"OPENRU~1EFI");
+ let (s, l) = short_name("BOOTx64.efi", &[]).unwrap();
+ assert_eq!(&s, b"BOOTX64 EFI");
+ assert_eq!(String::from_utf16(&l.unwrap()).unwrap(), "BOOTx64.efi");
+ let (s, _) = short_name(".contentVisibility", &[]).unwrap();
+ assert_eq!(&s, b"CONTEN~1 ");
+ let (s, _) = short_name(".contentVisibility", &[*b"CONTEN~1 "]).unwrap();
+ assert_eq!(&s, b"CONTEN~2 ");
+ }
+
+ #[test]
+ fn checksums_short_names() {
+ // The specification's checksum of "OPENCO~1EFI", worked by hand-rotating each byte in.
+ let mut sum = 0u8;
+ for c in b"OPENCO~1EFI" {
+ sum = (if sum & 1 != 0 { 0x80 } else { 0 }) + (sum >> 1);
+ sum = sum.wrapping_add(*c);
+ }
+ assert_eq!(checksum(b"OPENCO~1EFI"), sum);
+ }
+
+ #[test]
+ fn converts_dates() {
+ assert_eq!(civil(0), (1970, 1, 1));
+ assert_eq!(civil(20738), (2026, 10, 12));
+ let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(20738 * 86400 + 3600 + 62);
+ assert_eq!(
+ dos_time(t),
+ ((46 << 9) | (10 << 5) | 12, (1 << 11) | (1 << 5) | 1)
+ );
+ }
+}
diff --git a/src/image/gpt.rs b/src/image/gpt.rs
new file mode 100644
index 0000000..176ccfd
--- /dev/null
+++ b/src/image/gpt.rs
@@ -0,0 +1,171 @@
+//! A GUID partition table, as UEFI specifies it (UEFI 2.10, section 5.3): a protective MBR, the
+//! primary header and its 128 entries at the start of the disk, and their backups at its end.
+
+use super::Data;
+
+pub const SECTOR: u64 = 512;
+const ENTRIES: u64 = 128;
+const ENTRY_SIZE: u64 = 128;
+/// Sectors the 128 entries take.
+const ENTRY_SECTORS: u64 = ENTRIES * ENTRY_SIZE / SECTOR;
+
+/// The EFI system partition's type, C12A7328-F81F-11D2-BA4B-00A0C93EC93B.
+pub const ESP_TYPE: [u8; 16] = guid(
+ 0xC12A7328,
+ 0xF81F,
+ 0x11D2,
+ [0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B],
+);
+
+/// Microsoft's basic data partition type, EBD0A0A2-B9E5-4433-87C0-68B6B72699C7, which FAT32
+/// and exFAT volumes that are not EFI system partitions take.
+pub const BASIC_DATA_TYPE: [u8; 16] = guid(
+ 0xEBD0A0A2,
+ 0xB9E5,
+ 0x4433,
+ [0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7],
+);
+
+/// A GUID in its on-disk form: the first three fields little-endian.
+pub const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] {
+ let a = a.to_le_bytes();
+ let b = b.to_le_bytes();
+ let c = c.to_le_bytes();
+ [
+ a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6],
+ d[7],
+ ]
+}
+
+/// A random (version 4) GUID in on-disk form.
+pub fn random_guid() -> anyhow::Result<[u8; 16]> {
+ let mut g = [0u8; 16];
+ getrandom::fill(&mut g).map_err(|e| anyhow::anyhow!("random: {e}"))?;
+ // The version is in the third field's high nibble, which is little-endian on disk.
+ g[7] = (g[7] & 0x0f) | 0x40;
+ g[8] = (g[8] & 0x3f) | 0x80;
+ Ok(g)
+}
+
+pub struct Partition {
+ pub type_guid: [u8; 16],
+ pub guid: [u8; 16],
+ pub first_lba: u64,
+ pub last_lba: u64,
+ pub name: &'static str,
+}
+
+/// The first sector a 1 MiB-aligned partition starts at.
+pub const FIRST_LBA: u64 = 2048;
+
+/// The last sector a partition may use on a disk of `sectors` sectors.
+pub fn last_usable(sectors: u64) -> u64 {
+ sectors - 1 - ENTRY_SECTORS - 1
+}
+
+/// The table of a disk of `sectors` 512-byte sectors holding `parts`, as the sectors it takes:
+/// the protective MBR, the primary header and entries, and their backups.
+pub fn table(sectors: u64, disk_guid: [u8; 16], parts: &[Partition]) -> Vec<(u64, Data)> {
+ let last = sectors - 1;
+
+ // The protective MBR: one partition of type 0xEE over the whole disk.
+ let mut mbr = vec![0u8; SECTOR as usize];
+ let e = &mut mbr[446..462];
+ e[1..4].copy_from_slice(&[0x00, 0x02, 0x00]);
+ e[4] = 0xee;
+ e[5..8].copy_from_slice(&[0xff, 0xff, 0xff]);
+ e[8..12].copy_from_slice(&1u32.to_le_bytes());
+ e[12..16].copy_from_slice(&((sectors - 1).min(u32::MAX as u64) as u32).to_le_bytes());
+ mbr[510] = 0x55;
+ mbr[511] = 0xaa;
+
+ let mut entries = vec![0u8; (ENTRIES * ENTRY_SIZE) as usize];
+ for (e, p) in entries.chunks_mut(ENTRY_SIZE as usize).zip(parts) {
+ e[0..16].copy_from_slice(&p.type_guid);
+ e[16..32].copy_from_slice(&p.guid);
+ e[32..40].copy_from_slice(&p.first_lba.to_le_bytes());
+ e[40..48].copy_from_slice(&p.last_lba.to_le_bytes());
+ for (i, u) in p.name.encode_utf16().take(36).enumerate() {
+ e[56 + i * 2..58 + i * 2].copy_from_slice(&u.to_le_bytes());
+ }
+ }
+ let entries_crc = crc32fast::hash(&entries);
+
+ let header = |my_lba: u64, alternate: u64, entries_lba: u64| -> Vec {
+ let mut h = vec![0u8; SECTOR as usize];
+ h[0..8].copy_from_slice(b"EFI PART");
+ h[8..12].copy_from_slice(&0x0001_0000u32.to_le_bytes());
+ h[12..16].copy_from_slice(&92u32.to_le_bytes());
+ h[24..32].copy_from_slice(&my_lba.to_le_bytes());
+ h[32..40].copy_from_slice(&alternate.to_le_bytes());
+ h[40..48].copy_from_slice(&(2 + ENTRY_SECTORS).to_le_bytes());
+ h[48..56].copy_from_slice(&last_usable(sectors).to_le_bytes());
+ h[56..72].copy_from_slice(&disk_guid);
+ h[72..80].copy_from_slice(&entries_lba.to_le_bytes());
+ h[80..84].copy_from_slice(&(ENTRIES as u32).to_le_bytes());
+ h[84..88].copy_from_slice(&(ENTRY_SIZE as u32).to_le_bytes());
+ h[88..92].copy_from_slice(&entries_crc.to_le_bytes());
+ let crc = crc32fast::hash(&h[..92]);
+ h[16..20].copy_from_slice(&crc.to_le_bytes());
+ h
+ };
+ let backup_entries = last - ENTRY_SECTORS;
+ vec![
+ (0, Data::Bytes(mbr)),
+ (SECTOR, Data::Bytes(header(1, last, 2))),
+ (2 * SECTOR, Data::Bytes(entries.clone())),
+ (backup_entries * SECTOR, Data::Bytes(entries)),
+ (last * SECTOR, Data::Bytes(header(last, 1, backup_entries))),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn esp_type_is_mixed_endian() {
+ assert_eq!(
+ ESP_TYPE,
+ [
+ 0x28, 0x73, 0x2a, 0xc1, 0x1f, 0xf8, 0xd2, 0x11, 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e,
+ 0xc9, 0x3b
+ ]
+ );
+ }
+
+ #[test]
+ fn headers_carry_valid_crcs() {
+ let size = 8u64 << 20;
+ let sectors = size / SECTOR;
+ let part = |first_lba, last_lba| Partition {
+ type_guid: BASIC_DATA_TYPE,
+ guid: [2; 16],
+ first_lba,
+ last_lba,
+ name: "Data",
+ };
+ let disk = super::super::Disk {
+ size,
+ pieces: table(
+ sectors,
+ [1; 16],
+ &[part(FIRST_LBA, 4095), part(4096, last_usable(sectors))],
+ ),
+ }
+ .to_bytes()
+ .unwrap();
+ for (lba, entries) in [(1, 2), (sectors - 1, sectors - 1 - ENTRY_SECTORS)] {
+ let h = &disk[(lba * SECTOR) as usize..(lba * SECTOR) as usize + 92];
+ assert_eq!(&h[0..8], b"EFI PART");
+ let mut z = h.to_vec();
+ z[16..20].fill(0);
+ assert_eq!(crc32fast::hash(&z).to_le_bytes(), h[16..20]);
+ let e =
+ &disk[(entries * SECTOR) as usize..((entries + ENTRY_SECTORS) * SECTOR) as usize];
+ assert_eq!(crc32fast::hash(e).to_le_bytes(), h[88..92]);
+ assert_eq!(&e[128 + 32..128 + 40], &4096u64.to_le_bytes());
+ }
+ assert_eq!(&disk[510..512], &[0x55, 0xaa]);
+ }
+}
diff --git a/src/image/mod.rs b/src/image/mod.rs
new file mode 100644
index 0000000..aa6c5e8
--- /dev/null
+++ b/src/image/mod.rs
@@ -0,0 +1,360 @@
+//! Disk images: GPT disks of FAT32 and exFAT volumes holding given files, written as a raw image
+//! or as qcow2.
+//!
+//! A disk is made as the byte ranges it holds ([`Disk`]): the volumes' structures and small files
+//! in memory, and room for big files that are downloaded into the image where they belong
+//! ([`Data::Reserved`], [`open_raw`]), so an installer image of up to 20 GB is never in memory,
+//! or on disk twice.
+
+pub mod exfat;
+pub mod fat32;
+pub mod gpt;
+pub mod qcow2;
+
+use anyhow::{Context, Result, bail, ensure};
+use std::fs::{File, OpenOptions};
+use std::io::{Seek, SeekFrom, Write};
+use std::path::Path;
+
+#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Format {
+ Raw,
+ Qcow2,
+}
+
+impl Format {
+ /// qcow2 for a `.qcow2` path, raw for any other (`.img`, `.raw`).
+ pub fn for_path(p: &Path) -> Format {
+ match p.extension().and_then(|e| e.to_str()) {
+ Some(e) if e.eq_ignore_ascii_case("qcow2") => Format::Qcow2,
+ _ => Format::Raw,
+ }
+ }
+}
+
+/// What a file on a volume holds: bytes, or room for `len` bytes written into the image later,
+/// such as a download, found by `name` ([`Disk::place`]).
+#[derive(Clone, Debug)]
+pub enum Data {
+ Bytes(Vec),
+ Reserved { name: &'static str, len: u64 },
+}
+
+impl Data {
+ pub fn size(&self) -> u64 {
+ match self {
+ Data::Bytes(b) => b.len() as u64,
+ Data::Reserved { len, .. } => *len,
+ }
+ }
+}
+
+/// A disk image of `size` bytes: what lies at each offset; the rest is zero.
+pub struct Disk {
+ pub size: u64,
+ pub pieces: Vec<(u64, Data)>,
+}
+
+impl Disk {
+ fn check(&self) -> Result<()> {
+ for (at, d) in &self.pieces {
+ ensure!(
+ at.checked_add(d.size()).is_some_and(|end| end <= self.size),
+ "a piece at {at} runs past the disk's end"
+ );
+ }
+ Ok(())
+ }
+
+ /// Where the reserved file `name` starts on the disk.
+ pub fn place(&self, name: &str) -> Option {
+ self.pieces.iter().find_map(|(at, d)| match d {
+ Data::Reserved { name: n, .. } if *n == name => Some(*at),
+ _ => None,
+ })
+ }
+
+ /// The whole disk in memory, for a small one; reserved files are zero.
+ pub fn to_bytes(&self) -> Result> {
+ self.check()?;
+ let mut disk = vec![0u8; usize::try_from(self.size)?];
+ for (at, d) in &self.pieces {
+ if let Data::Bytes(b) = d {
+ disk[*at as usize..*at as usize + b.len()].copy_from_slice(b);
+ }
+ }
+ Ok(disk)
+ }
+
+ /// Writes the disk's bytes into `f`, leaving reserved files as they are.
+ fn write_bytes(&self, f: &mut File) -> Result<()> {
+ for (at, d) in &self.pieces {
+ if let Data::Bytes(b) = d {
+ f.seek(SeekFrom::Start(*at))?;
+ f.write_all(b)?;
+ }
+ }
+ Ok(())
+ }
+}
+
+/// A disk of `size` bytes with an EFI system partition from 1 MiB to the end, formatted FAT32
+/// (fat32.rs; FAT32 needs 65525 clusters at least, 32 MiB of 512-byte ones), holding `files` at
+/// their slash-separated paths; a path ending in `/` is an empty folder.
+pub fn esp_disk(size: u64, label: &str, files: &[(String, Data)]) -> Result {
+ if size < 40 << 20 || !size.is_multiple_of(gpt::SECTOR) {
+ bail!("an EFI system partition disk needs 40 MiB at least, in whole sectors");
+ }
+ let sectors = size / gpt::SECTOR;
+ let first = gpt::FIRST_LBA;
+ let last = gpt::last_usable(sectors);
+ let volume = fat32::make(
+ (last + 1 - first) * gpt::SECTOR,
+ first as u32,
+ label,
+ serial()?,
+ files,
+ fat32::dos_time(std::time::SystemTime::now()),
+ )?;
+ let mut pieces = gpt::table(
+ sectors,
+ gpt::random_guid()?,
+ &[gpt::Partition {
+ type_guid: gpt::ESP_TYPE,
+ guid: gpt::random_guid()?,
+ first_lba: first,
+ last_lba: last,
+ name: "EFI System Partition",
+ }],
+ );
+ pieces.extend(
+ volume
+ .into_iter()
+ .map(|(at, d)| (first * gpt::SECTOR + at, d)),
+ );
+ Ok(Disk { size, pieces })
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Fs {
+ Fat32,
+ Exfat,
+}
+
+/// A volume for [`data_disk`]: its file system, volume label, partition name, and files.
+pub struct Volume<'a> {
+ pub fs: Fs,
+ pub label: &'a str,
+ pub name: &'static str,
+ pub files: &'a [(String, Data)],
+}
+
+/// A GPT disk of `volumes`, in order, each a basic data partition just big enough for its files
+/// and starting on a MiB boundary.
+pub fn data_disk(volumes: &[Volume]) -> Result {
+ const MIB: u64 = 1 << 20;
+ let sizes: Vec = volumes.iter().map(|v| fit(v.files)).collect();
+ // The first MiB for the primary table, and one at the end for the backup.
+ let size = MIB + sizes.iter().sum::() + MIB;
+ let now = fat32::dos_time(std::time::SystemTime::now());
+ let mut pieces = Vec::new();
+ let mut parts = Vec::new();
+ let mut at = MIB;
+ for (v, &len) in volumes.iter().zip(&sizes) {
+ let first = at / gpt::SECTOR;
+ let volume = match v.fs {
+ Fs::Fat32 => fat32::make(len, u32::try_from(first)?, v.label, serial()?, v.files, now)?,
+ Fs::Exfat => exfat::make(len, first, v.label, serial()?, v.files, now)?,
+ };
+ pieces.extend(volume.into_iter().map(|(o, d)| (at + o, d)));
+ parts.push(gpt::Partition {
+ type_guid: gpt::BASIC_DATA_TYPE,
+ guid: gpt::random_guid()?,
+ first_lba: first,
+ last_lba: first + len / gpt::SECTOR - 1,
+ name: v.name,
+ });
+ at += len;
+ }
+ pieces.extend(gpt::table(size / gpt::SECTOR, gpt::random_guid()?, &parts));
+ Ok(Disk { size, pieces })
+}
+
+/// A volume size that holds `files`: their bytes, each rounded up to the largest cluster either
+/// file system here uses (128 KiB), plus 1/64 for the FATs (FAT32's two, of 512-byte clusters,
+/// take 1/64 of a small volume) and 16 MiB for the rest, in whole MiB, 64 MiB at least.
+fn fit(files: &[(String, Data)]) -> u64 {
+ let data: u64 = files
+ .iter()
+ .map(|(_, d)| d.size().next_multiple_of(128 << 10))
+ .sum();
+ (data + data / 64 + (16 << 20))
+ .max(64 << 20)
+ .next_multiple_of(1 << 20)
+}
+
+fn serial() -> Result {
+ let mut s = [0u8; 4];
+ getrandom::fill(&mut s).map_err(|e| anyhow::anyhow!("random: {e}"))?;
+ Ok(u32::from_le_bytes(s))
+}
+
+/// Writes `disk` to `path` in `format`, through a `.part` file renamed over it. A raw image is
+/// sparse where the disk is zero.
+pub fn write(disk: &Disk, path: &Path, format: Format) -> Result<()> {
+ disk.check()?;
+ create_parent(path)?;
+ let part = crate::http::part_path(path);
+ let mut f = File::create(&part).with_context(|| format!("create {}", part.display()))?;
+ match format {
+ Format::Qcow2 => {
+ let bytes = disk.to_bytes()?;
+ let mut w = std::io::BufWriter::new(&mut f);
+ qcow2::write(&bytes, &mut w)?;
+ w.flush()?;
+ }
+ Format::Raw => {
+ f.set_len(disk.size)?;
+ disk.write_bytes(&mut f)?;
+ }
+ }
+ f.sync_all()?;
+ drop(f);
+ std::fs::rename(&part, path).with_context(|| format!("write {}", path.display()))?;
+ Ok(())
+}
+
+/// Opens `path` as a raw image of `disk` whose reserved files are written next, and writes the
+/// rest. What a previous run left in the file stays, sized to the disk, so downloads into the
+/// reserved places resume as far as their checks pass it; the structures written over it fill
+/// their sectors and clusters, so none keeps an earlier layout's bytes.
+pub fn open_raw(disk: &Disk, path: &Path) -> Result {
+ disk.check()?;
+ create_parent(path)?;
+ let mut f = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(path)
+ .with_context(|| format!("open {}", path.display()))?;
+ f.set_len(disk.size)?;
+ disk.write_bytes(&mut f)?;
+ Ok(f)
+}
+
+fn create_parent(path: &Path) -> Result<()> {
+ if let Some(dir) = path.parent()
+ && !dir.as_os_str().is_empty()
+ {
+ std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn esp_disk_is_gpt_around_fat32() {
+ let files = vec![(
+ "EFI/OC/config.plist".to_string(),
+ Data::Bytes(vec![7u8; 5000]),
+ )];
+ let disk = esp_disk(64 << 20, "OPENCORE", &files)
+ .unwrap()
+ .to_bytes()
+ .unwrap();
+ assert_eq!(&disk[512..520], b"EFI PART");
+ let vol = (gpt::FIRST_LBA * gpt::SECTOR) as usize;
+ assert_eq!(&disk[vol + 82..vol + 90], b"FAT32 ");
+ // The volume's hidden sectors are where the partition starts.
+ assert_eq!(&disk[vol + 28..vol + 32], &2048u32.to_le_bytes());
+ }
+
+ #[test]
+ fn data_disk_lays_volumes_end_to_end() {
+ let fat_files = vec![("a/b.txt".to_string(), Data::Bytes(vec![1; 100]))];
+ let ex_files = vec![("c.bin".to_string(), Data::Bytes(vec![2; 70_000]))];
+ let disk = data_disk(&[
+ Volume {
+ fs: Fs::Fat32,
+ label: "RECOVERY",
+ name: "one",
+ files: &fat_files,
+ },
+ Volume {
+ fs: Fs::Exfat,
+ label: "Installer",
+ name: "two",
+ files: &ex_files,
+ },
+ ])
+ .unwrap();
+ // 1 MiB, two 64 MiB volumes, 1 MiB.
+ assert_eq!(disk.size, 130 << 20);
+ let bytes = disk.to_bytes().unwrap();
+ assert_eq!(&bytes[(1 << 20) + 82..(1 << 20) + 90], b"FAT32 ");
+ assert_eq!(&bytes[(65 << 20) + 3..(65 << 20) + 11], b"EXFAT ");
+ let entry = |i: usize| &bytes[1024 + i * 128..1024 + (i + 1) * 128];
+ let u64_at = |e: &[u8], o: usize| u64::from_le_bytes(e[o..o + 8].try_into().unwrap());
+ assert_eq!(u64_at(entry(0), 32), 2048);
+ assert_eq!(u64_at(entry(1), 32), 65 << 11);
+ assert_eq!(u64_at(entry(1), 40), (129 << 11) - 1);
+ }
+
+ #[test]
+ fn raw_images_keep_what_reserved_places_hold() {
+ let dir = std::env::temp_dir().join(format!("reims-util-test-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let disk = Disk {
+ size: 32 << 20,
+ pieces: vec![
+ (512, Data::Bytes(b"head".to_vec())),
+ (
+ 1 << 20,
+ Data::Reserved {
+ name: "pkg",
+ len: 5 << 20,
+ },
+ ),
+ ],
+ };
+ assert_eq!(disk.place("pkg"), Some(1 << 20));
+ let path = dir.join("disk.img");
+ let mut f = open_raw(&disk, &path).unwrap();
+ f.seek(SeekFrom::Start(1 << 20)).unwrap();
+ f.write_all(b"downloaded").unwrap();
+ drop(f);
+ // Opened again, as a resumed run does: the structures are written again, the
+ // download's bytes stay.
+ drop(open_raw(&disk, &path).unwrap());
+ let got = std::fs::read(&path).unwrap();
+ assert_eq!(got.len(), 32 << 20);
+ assert_eq!(&got[512..516], b"head");
+ assert_eq!(&got[1 << 20..(1 << 20) + 10], b"downloaded");
+ // A file of another size is sized to the disk.
+ std::fs::OpenOptions::new()
+ .write(true)
+ .open(&path)
+ .unwrap()
+ .set_len(40 << 20)
+ .unwrap();
+ drop(open_raw(&disk, &path).unwrap());
+ let got = std::fs::read(&path).unwrap();
+ assert_eq!(got.len(), 32 << 20);
+ assert_eq!(&got[1 << 20..(1 << 20) + 10], b"downloaded");
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn format_follows_the_extension() {
+ assert_eq!(
+ Format::for_path(Path::new("a/OpenCore.qcow2")),
+ Format::Qcow2
+ );
+ assert_eq!(Format::for_path(Path::new("OpenCore.img")), Format::Raw);
+ }
+}
diff --git a/src/image/qcow2.rs b/src/image/qcow2.rs
new file mode 100644
index 0000000..14ce10b
--- /dev/null
+++ b/src/image/qcow2.rs
@@ -0,0 +1,157 @@
+//! A qcow2 image (version 3, as QEMU's docs/interop/qcow2.txt specifies it) of a disk held in
+//! memory: only its clusters that are not all zero are stored, so a 128 MiB disk holding a few
+//! MiB of files is a file of a few MiB.
+//!
+//! The layout, in 64 KiB clusters: the header; the refcount table; its refcount blocks; the L1
+//! table; an L2 table for each 512 MiB of the disk that has data; the data clusters. Every
+//! cluster is used once, so its refcount is 1 and every L1 and L2 entry carries QCOW_OFLAG_COPIED.
+
+use std::io::Write;
+
+const CLUSTER_BITS: u32 = 16;
+const CLUSTER: u64 = 1 << CLUSTER_BITS;
+/// 16-bit refcounts.
+const REFCOUNT_ORDER: u32 = 4;
+const L2_ENTRIES: u64 = CLUSTER / 8;
+const REFCOUNTS_PER_BLOCK: u64 = CLUSTER * 8 / (1 << REFCOUNT_ORDER);
+const COPIED: u64 = 1 << 63;
+const HEADER_LENGTH: u32 = 104;
+
+pub fn write(disk: &[u8], out: &mut impl Write) -> std::io::Result<()> {
+ let size = disk.len() as u64;
+ let clusters_in_disk = size.div_ceil(CLUSTER);
+ let data: Vec = (0..clusters_in_disk)
+ .filter(|&i| {
+ let start = (i * CLUSTER) as usize;
+ let end = (start + CLUSTER as usize).min(disk.len());
+ disk[start..end].iter().any(|b| *b != 0)
+ })
+ .collect();
+ let l1_entries = clusters_in_disk.div_ceil(L2_ENTRIES).max(1);
+ let l1_clusters = (l1_entries * 8).div_ceil(CLUSTER);
+ let mut l2_tables: Vec = data.iter().map(|c| c / L2_ENTRIES).collect();
+ l2_tables.dedup();
+
+ // The refcount blocks must cover every cluster, themselves included.
+ let fixed = 1 + 1 + l1_clusters + l2_tables.len() as u64 + data.len() as u64;
+ let mut refblocks = 1u64;
+ while (fixed + refblocks).div_ceil(REFCOUNTS_PER_BLOCK) > refblocks {
+ refblocks += 1;
+ }
+ // One refcount table cluster holds 8192 refcount blocks, for 16 TiB of clusters.
+ if refblocks > CLUSTER / 8 {
+ return Err(std::io::Error::other(
+ "the disk is too large for a one-cluster refcount table",
+ ));
+ }
+ let total = fixed + refblocks;
+
+ let refcount_table_at = 1;
+ let refblocks_at = 2;
+ let l1_at = refblocks_at + refblocks;
+ let l2_at = l1_at + l1_clusters;
+ let data_at = l2_at + l2_tables.len() as u64;
+
+ let mut header = vec![0u8; CLUSTER as usize];
+ header[0..4].copy_from_slice(b"QFI\xfb");
+ header[4..8].copy_from_slice(&3u32.to_be_bytes());
+ header[20..24].copy_from_slice(&CLUSTER_BITS.to_be_bytes());
+ header[24..32].copy_from_slice(&size.to_be_bytes());
+ header[36..40].copy_from_slice(&(l1_entries as u32).to_be_bytes());
+ header[40..48].copy_from_slice(&(l1_at * CLUSTER).to_be_bytes());
+ header[48..56].copy_from_slice(&(refcount_table_at * CLUSTER).to_be_bytes());
+ header[56..60].copy_from_slice(&1u32.to_be_bytes());
+ header[96..100].copy_from_slice(&REFCOUNT_ORDER.to_be_bytes());
+ header[100..104].copy_from_slice(&HEADER_LENGTH.to_be_bytes());
+ // The header extensions end at once (type 0, length 0), already zero.
+ out.write_all(&header)?;
+
+ let mut table = vec![0u8; CLUSTER as usize];
+ for i in 0..refblocks {
+ let at = (i * 8) as usize;
+ table[at..at + 8].copy_from_slice(&((refblocks_at + i) * CLUSTER).to_be_bytes());
+ }
+ out.write_all(&table)?;
+
+ for b in 0..refblocks {
+ let mut block = vec![0u8; CLUSTER as usize];
+ for j in 0..REFCOUNTS_PER_BLOCK {
+ let cluster = b * REFCOUNTS_PER_BLOCK + j;
+ if cluster >= total {
+ break;
+ }
+ let at = (j * 2) as usize;
+ block[at..at + 2].copy_from_slice(&1u16.to_be_bytes());
+ }
+ out.write_all(&block)?;
+ }
+
+ let mut l1 = vec![0u8; (l1_clusters * CLUSTER) as usize];
+ for (n, t) in l2_tables.iter().enumerate() {
+ let at = (*t * 8) as usize;
+ l1[at..at + 8].copy_from_slice(&(((l2_at + n as u64) * CLUSTER) | COPIED).to_be_bytes());
+ }
+ out.write_all(&l1)?;
+
+ let mut next_data = data_at;
+ for t in &l2_tables {
+ let mut l2 = vec![0u8; CLUSTER as usize];
+ for c in data.iter().filter(|c| *c / L2_ENTRIES == *t) {
+ let at = ((c % L2_ENTRIES) * 8) as usize;
+ l2[at..at + 8].copy_from_slice(&((next_data * CLUSTER) | COPIED).to_be_bytes());
+ next_data += 1;
+ }
+ out.write_all(&l2)?;
+ }
+
+ for c in &data {
+ let start = (c * CLUSTER) as usize;
+ let end = (start + CLUSTER as usize).min(disk.len());
+ out.write_all(&disk[start..end])?;
+ if end - start < CLUSTER as usize {
+ out.write_all(&vec![0u8; CLUSTER as usize - (end - start)])?;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn read_cluster(img: &[u8], virt: u64) -> Option<&[u8]> {
+ let be = |o: usize| u64::from_be_bytes(img[o..o + 8].try_into().unwrap());
+ let l1_at = be(40) as usize;
+ let l1 = be(l1_at + (virt / CLUSTER / L2_ENTRIES) as usize * 8) & !COPIED;
+ if l1 == 0 {
+ return None;
+ }
+ let l2 = be(l1 as usize + ((virt / CLUSTER) % L2_ENTRIES) as usize * 8) & !COPIED;
+ if l2 == 0 {
+ return None;
+ }
+ Some(&img[l2 as usize..l2 as usize + CLUSTER as usize])
+ }
+
+ #[test]
+ fn stores_only_clusters_with_data() {
+ let mut disk = vec![0u8; 3 * CLUSTER as usize + 512];
+ disk[5] = 1;
+ disk[3 * CLUSTER as usize + 10] = 2;
+ let mut img = Vec::new();
+ write(&disk, &mut img).unwrap();
+ // Header, refcount table, one refcount block, L1, one L2, two data clusters.
+ assert_eq!(img.len(), 7 * CLUSTER as usize);
+ assert_eq!(read_cluster(&img, 0).unwrap()[5], 1);
+ assert!(read_cluster(&img, CLUSTER).is_none());
+ assert_eq!(read_cluster(&img, 3 * CLUSTER).unwrap()[10], 2);
+ // Seven clusters, each counted once.
+ let block = &img[2 * CLUSTER as usize..3 * CLUSTER as usize];
+ let counts: Vec = block
+ .chunks(2)
+ .map(|c| u16::from_be_bytes([c[0], c[1]]))
+ .collect();
+ assert!(counts[..7].iter().all(|c| *c == 1));
+ assert!(counts[7..].iter().all(|c| *c == 0));
+ }
+}
diff --git a/src/installer.rs b/src/installer.rs
new file mode 100644
index 0000000..8cbde5c
--- /dev/null
+++ b/src/installer.rs
@@ -0,0 +1,659 @@
+//! Full macOS installers, from Apple's software update catalog: `InstallAssistant.pkg`, which
+//! holds "Install macOS .app" whole, for macOS 11 Big Sur and later.
+//!
+//! The catalog (an XML plist, gzipped, over HTTPS) lists products. A full installer is a product
+//! with `ExtendedMetaInfo > InstallAssistantPackageIdentifiers` and an `InstallAssistant.pkg`
+//! package, which has its size, its URL and its chunklist's (`IntegrityDataURL`, the SHA-256 of
+//! each 10 MiB). The product's distribution file names the macOS (``, and `VERSION` and
+//! `BUILD` under ``) and, in its installation check, the board IDs of the Macs it
+//! installs on: Intel Macs' are `Mac-` and 16 hex digits, Apple silicon Macs' model names
+//! (`J413AP`). A product that names no Intel board installs on Apple silicon alone, as macOS 27
+//! does, and is left out.
+//!
+//! A VM cannot boot the package, so the offline installer ([`offline_installer`]) is a disk
+//! image holding it and the recovery image of the same macOS, from which Recovery installs it
+//! without the network.
+
+use crate::chunklist::{ChunkCheck, Chunklist};
+use crate::http::{self, Check, Dest, Download, Headers};
+use crate::image::{self, Data, Fs, Volume};
+use crate::progress::{self, Reporter};
+use crate::recovery;
+use anyhow::{Context, Result, bail};
+use plist::Value;
+use std::fs::File;
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+/// The catalog that lists every release from 10.5 to 26, where x86-64 macOS ends.
+pub const CATALOG: &str = "https://swscan.apple.com/content/catalogs/others/index-26-15-14-13-12-10.16-10.15-10.14-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz";
+
+#[derive(Clone, Debug, PartialEq, serde::Serialize)]
+pub struct Installer {
+ /// Apple's product ID: "142-28081".
+ pub product: String,
+ /// "macOS Tahoe".
+ pub title: String,
+ pub version: String,
+ pub build: String,
+ /// When Apple posted it, as the catalog says: "2026-09-28".
+ pub posted: String,
+ pub size: u64,
+ pub url: String,
+ pub integrity_url: Option,
+ /// The SHA-1 of the package's table of contents, the catalog's `Digest`.
+ pub digest: Option,
+}
+
+impl Installer {
+ pub fn label(&self) -> String {
+ format!("{} {} ({})", self.title, self.version, self.build)
+ }
+
+ pub fn offline_installer_name(&self) -> String {
+ format!(
+ "{}-{}-{}-offline-installer.img",
+ self.title.replace(' ', "-"),
+ self.version,
+ self.build
+ )
+ }
+}
+
+/// A full installer in the catalog, before its distribution file is read.
+struct Candidate {
+ product: String,
+ posted: String,
+ size: u64,
+ url: String,
+ integrity_url: Option,
+ digest: Option,
+ dist_url: String,
+}
+
+/// The installers that run on Intel Macs, newest first.
+pub fn list(r: &dyn Reporter) -> Result> {
+ let agent = http::agent();
+ r.step("Reading Apple's software update catalog");
+ let gz = http::get(&agent, CATALOG, &Vec::new(), 64 << 20)?;
+ let mut xml = Vec::new();
+ std::io::Read::read_to_end(&mut flate2::read::GzDecoder::new(&gz[..]), &mut xml)
+ .context("unpack the software update catalog")?;
+ let candidates = parse_catalog(&xml)?;
+
+ r.step("Reading each installer's details");
+ let next = AtomicUsize::new(0);
+ let found: Mutex> = Mutex::new(Vec::new());
+ let failed: Mutex