🆕 Make OpenCore images and macOS installers for x86-64 VMs

reims-ctl and its docs send people to OSX-KVM or ULTMOS for two things: an
OpenCore boot image with OVMF, and a way to install macOS. This does both in
one program with no other tools to install, on Linux and macOS, so reims-ctl
can point at it instead. Each job writes one file that reims-ctl takes as it
is.

- opencore: a 128 MiB GPT disk (qcow2 or raw) whose FAT32 EFI partition holds
  OpenCore 1.0.8 with a config.plist made from the release's Sample.plist for
  a q35 VM on KVM (no kexts, one SSDT for EC and USBX, a fresh SMBIOS
  identity), plus OVMF from a pinned Arch edk2-ovmf package. Both downloads
  are pinned by SHA-256 and cached.
- online-installer VERSION: Apple's recovery image for High Sierra to Tahoe,
  as macOS-<name>-online-installer.dmg, checked chunk by chunk against its
  chunklist, whose RSA signature must be Apple's, since both come over plain
  HTTP. It installs the newest release of its macOS over the network.
- offline-installer VERSION: one exact release of macOS 11 to 26 for Intel
  Macs, from the software update catalog, as one raw GPT disk,
  macOS-<name>-<version>-<build>-offline-installer.img:
  - FAT32 RECOVERY: com.apple.recovery.boot/BaseSystem.dmg and its chunklist,
    which OpenCore boots, checking Apple's signature, as from a USB stick;
  - exFAT Installer: InstallAssistant.pkg (12 to 18 GB, past FAT32's 4 GiB
    limit), checked against its chunklist and the catalog's digest of its
    table of contents, and install-macos.sh, run from Recovery's Terminal.

The script installs the package onto the erased disk and starts the app's
startosinstall. The package's postinstall writes to $3Applications, which
for a volume lands beside it on Recovery's RAM disk, so a link sends it onto
the volume; it also sets CM_BUILD and fixes the app's modes, as mist-cli does.

Both of the offline installer's files are downloaded straight into their
places in the image, so the package is never on disk twice. A disk is built
as byte ranges, with a reserved place for each download, and the package's
volume first so its place stays put when Apple's recovery image changes size.
The FAT32, exFAT and GPT writers are our own (fatfs made volumes macOS's
fsck_msdos rejected); fsck_exfat and fsck_msdos pass the volumes. An image
already there is checked read-only, since a VM may be running from it, kept
when its package checks out, and repaired otherwise.

Downloads resume from a .part file (or the image's place) after checking what
is already there against Apple's chunklists, and carry on through slow or
dropped connections. The same jobs run from a small inline terminal
interface, from subcommands, and with --json for scripts.

Licensed GPL-2.0-or-later OR LGPL-3.0-or-later, as reims-vgpu is. The serial
number tables come from OpenCorePkg's macserial, so its BSD-3-Clause license
is kept beside ours for that file.
This commit is contained in:
Anees Iqbal committed 2026-10-12 17:57:06 +03:00
1 parent a56f9fa998
commit 2686f02b38
29 files changed
+9350 -1

No files matched your search

+1
View File
@@ -0,0 +1 @@
/target
Generated
+1551
View File
File diff suppressed because it is too large. Load diff
+51
View File
@@ -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"
+25
View File
@@ -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.
+16
View File
@@ -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.
+338
View File
@@ -0,0 +1,338 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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.
<signature of Moe Ghoul>, 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.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
+169 -1
View File
@@ -1 +1,169 @@
# WIP
# reims-util
[![License: GPL-2.0-or-later OR LGPL-3.0-or-later](https://img.shields.io/badge/License-GPL--2.0--or--later%20OR%20LGPL--3.0--or--later-blue.svg)](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-<name>-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-<name>-<version>-<build>-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.
+3
View File
@@ -0,0 +1,3 @@
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
+54
View File
@@ -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<PathBuf> {
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<PathBuf> {
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)
}
+341
View File
@@ -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<Chunklist> {
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::<CHUNK_SIZE>()
.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<u64> {
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<u8> {
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<u8> = (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));
}
}
+353
View File
@@ -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<Command>,
}
#[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<String>,
/// The logic board serial (default: a new one, made for the serial)
#[arg(long)]
pub mlb: Option<String>,
/// The system UUID (default: a new one)
#[arg(long)]
pub uuid: Option<String>,
/// The ROM: 12 hex digits or a MAC address, such as the VM's (default: random)
#[arg(long)]
pub rom: Option<String>,
/// 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<PathBuf>,
}
#[derive(Args, Clone, Debug)]
pub struct InstallerArgs {
/// The version to make, or `list` (or nothing) to list them
version: Option<String>,
/// 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-<name>-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-<name>-<version>-<build>-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<String>) -> 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<T: Serialize> {
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<V> = 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<T: Serialize>(json: bool, v: &T) -> Result<()> {
if json {
progress::json_line(&Final::Done { result: v });
}
Ok(())
}
pub fn opencore_options(a: &OpencoreArgs) -> Result<opencore::Options> {
let m = smbios::model(&a.model).with_context(|| {
format!(
"unknown model {:?}: {} are known",
a.model,
smbios::MODELS
.iter()
.map(|m| m.name)
.collect::<Vec<_>>()
.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
);
}
+465
View File
@@ -0,0 +1,465 @@
//! HTTP: small fetches, and downloads that resume.
//!
//! A download writes `<dest>.part` and renames it to `<dest>` 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<Vec<u8>> {
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::<ureq::Error>() {
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<u64>;
/// 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<u64> {
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<u64>,
/// For requests the server refuses (401, 403): new headers, such as a fresh asset token.
pub refresh: Option<&'a mut dyn FnMut() -> Result<Headers>>,
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: `<path>.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<u64>)> {
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<String> {
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")
);
}
}
+499
View File
@@ -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<Vec<(u64, Data)>> {
ensure!(
size.is_multiple_of(SECTOR) && size >= 1 << 20,
"an exFAT volume is 1 MiB at least, in whole sectors"
);
let label: Vec<u16> = 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<u32> {
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<Vec<u16>> = 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<u8>, 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<u16> = 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<u8> {
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<u8> {
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<u16> = 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<u16> {
let units: Vec<u16> = 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<u8>)> {
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<u8> {
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<u16> = 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<u8>)]) -> Vec<u8> {
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<u8> = (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::<Vec<_>>()), 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);
}
}
+603
View File
@@ -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<Data>) -> 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<Vec<(u64, Data)>> {
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<u32> {
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<u8> = 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<u32>,
writes: &mut Vec<(u32, Data)>,
) -> Result<u32> {
// 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::<usize>();
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<Vec<u16>>)> {
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<u8> {
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<String, Vec<u8>> {
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<u32>| -> Vec<u8> {
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<u16> = 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<u8> {
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<u8> = (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<u8> = (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)
);
}
}
+171
View File
@@ -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<u8> {
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]);
}
}
+360
View File
@@ -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<u8>),
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<u64> {
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<Vec<u8>> {
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<Disk> {
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<Disk> {
const MIB: u64 = 1 << 20;
let sizes: Vec<u64> = 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::<u64>() + 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<u32> {
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<File> {
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);
}
}
+157
View File
@@ -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<u64> = (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<u64> = 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<u16> = 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));
}
}
+659
View File
@@ -0,0 +1,659 @@
//! Full macOS installers, from Apple's software update catalog: `InstallAssistant.pkg`, which
//! holds "Install macOS <name>.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 (`<title>`, and `VERSION` and
//! `BUILD` under `<auxinfo>`) 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<String>,
/// The SHA-1 of the package's table of contents, the catalog's `Digest`.
pub digest: Option<String>,
}
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<String>,
digest: Option<String>,
dist_url: String,
}
/// The installers that run on Intel Macs, newest first.
pub fn list(r: &dyn Reporter) -> Result<Vec<Installer>> {
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<Vec<Installer>> = Mutex::new(Vec::new());
let failed: Mutex<Option<anyhow::Error>> = Mutex::new(None);
std::thread::scope(|s| {
for _ in 0..8 {
s.spawn(|| {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
let Some(c) = candidates.get(i) else {
break;
};
if r.cancelled() {
break;
}
match http::get(&agent, &c.dist_url, &Vec::new(), 4 << 20) {
Ok(d) => {
if let Some(info) = parse_dist(&String::from_utf8_lossy(&d))
&& info.intel
&& let Ok(mut f) = found.lock()
{
f.push(Installer {
product: c.product.clone(),
title: info.title,
version: info.version,
build: info.build,
posted: c.posted.clone(),
size: c.size,
url: c.url.clone(),
integrity_url: c.integrity_url.clone(),
digest: c.digest.clone(),
});
}
}
Err(e) => {
if let Ok(mut f) = failed.lock() {
f.get_or_insert(e);
}
}
}
}
});
}
});
crate::progress::check(r)?;
if let Ok(mut f) = failed.lock()
&& let Some(e) = f.take()
{
return Err(e.context("read an installer's distribution file"));
}
let mut found = found.into_inner().unwrap_or_default();
found.sort_by(|a, b| {
version_key(&b.version)
.cmp(&version_key(&a.version))
.then(b.posted.cmp(&a.posted))
});
Ok(found)
}
fn parse_catalog(xml: &[u8]) -> Result<Vec<Candidate>> {
let root: Value = plist::from_bytes(xml).context("read the software update catalog")?;
let products = root
.as_dictionary()
.and_then(|d| d.get("Products"))
.and_then(Value::as_dictionary)
.context("the catalog lists no products")?;
let mut out = Vec::new();
for (id, p) in products {
let Some(p) = p.as_dictionary() else {
continue;
};
let is_full = p
.get("ExtendedMetaInfo")
.and_then(Value::as_dictionary)
.is_some_and(|e| e.contains_key("InstallAssistantPackageIdentifiers"));
if !is_full {
continue;
}
let Some(pkg) = p
.get("Packages")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_dictionary)
.find(|k| {
k.get("URL")
.and_then(Value::as_string)
.is_some_and(|u| u.ends_with("/InstallAssistant.pkg"))
})
else {
continue;
};
let dists = p.get("Distributions").and_then(Value::as_dictionary);
let Some(dist_url) = dists
.and_then(|d| d.get("English").or_else(|| d.get("en")))
.and_then(Value::as_string)
else {
continue;
};
let s = |k: &str| pkg.get(k).and_then(Value::as_string).map(str::to_string);
let posted = match p.get("PostDate") {
Some(Value::Date(d)) => {
let st: std::time::SystemTime = (*d).into();
date_string(st)
}
_ => String::new(),
};
out.push(Candidate {
product: id.clone(),
posted,
size: pkg
.get("Size")
.and_then(Value::as_unsigned_integer)
.unwrap_or(0),
url: s("URL").unwrap_or_default(),
integrity_url: s("IntegrityDataURL"),
digest: s("Digest"),
dist_url: dist_url.to_string(),
});
}
Ok(out)
}
#[derive(Debug, PartialEq)]
struct DistInfo {
title: String,
version: String,
build: String,
intel: bool,
}
fn parse_dist(s: &str) -> Option<DistInfo> {
let between = |from: &str, open: &str, close: &str| -> Option<String> {
let i = s.find(from)? + from.len();
let rest = &s[i..];
let a = rest.find(open)? + open.len();
let b = rest[a..].find(close)?;
Some(rest[a..a + b].trim().to_string())
};
let title = between("<title", ">", "</title>").unwrap_or_default();
let version = between("<key>VERSION</key>", "<string>", "</string>")?;
let build = between("<key>BUILD</key>", "<string>", "</string>")?;
Some(DistInfo {
title,
version,
build,
intel: has_intel_board(s),
})
}
/// Whether the text names an Intel Mac's board ID: `Mac-` and 16 hex digits.
fn has_intel_board(s: &str) -> bool {
s.match_indices("Mac-").any(|(i, _)| {
let id = &s.as_bytes()[i + 4..];
id.len() >= 16 && id[..16].iter().all(u8::is_ascii_hexdigit)
})
}
fn version_key(v: &str) -> Vec<u32> {
v.split('.').map(|p| p.parse().unwrap_or(0)).collect()
}
/// A UTC date as YYYY-MM-DD.
fn date_string(t: std::time::SystemTime) -> String {
let days = t
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() / 86400)
.unwrap_or(0);
let (y, m, d) = crate::image::fat32::civil(days);
format!("{y:04}-{m:02}-{d:02}")
}
/// An installer by version ("26.7.1", or "26" for the newest 26), build ("25G241"), product ID,
/// name ("tahoe", the newest Tahoe) or "latest".
pub fn find<'a>(list: &'a [Installer], q: &str) -> Option<&'a Installer> {
let q = q.trim().to_ascii_lowercase();
if q == "latest" {
return list.first();
}
let q = q.strip_prefix("macos").unwrap_or(&q).trim().to_string();
// A name matches without its spaces and hyphens: "big sur", "big-sur" and "bigsur".
let squash = |s: &str| s.replace([' ', '-'], "");
let name = squash(&q);
list.iter()
.find(|i| i.version == q || i.build.to_ascii_lowercase() == q || i.product == q)
.or_else(|| {
list.iter().find(|i| {
i.version.split('.').next() == Some(q.as_str())
|| i.title
.to_ascii_lowercase()
.strip_prefix("macos ")
.is_some_and(|t| squash(t) == name)
})
})
}
/// Checks that the package at `offset` in `f` is the one the catalog lists: a xar archive whose
/// table of contents has the SHA-1 the catalog gives as the package's `Digest` (the xar header's
/// 28 bytes, then the zlib-compressed table of contents, whose SHA-1 also opens the heap).
fn check_toc(f: &mut File, offset: u64, digest: &str) -> Result<()> {
use sha1::Digest;
use std::io::{Read, Seek, SeekFrom};
f.seek(SeekFrom::Start(offset))?;
let mut h = [0u8; 28];
f.read_exact(&mut h)?;
if &h[0..4] != b"xar!" {
bail!("the installer package is not a package");
}
let header_size = u16::from_be_bytes([h[4], h[5]]) as u64;
let toc_size = u64::from_be_bytes([h[8], h[9], h[10], h[11], h[12], h[13], h[14], h[15]]);
if toc_size > 64 << 20 {
bail!("the installer package's table of contents is {toc_size} bytes");
}
f.seek(SeekFrom::Start(offset + header_size))?;
let mut toc = vec![0u8; toc_size as usize];
f.read_exact(&mut toc)?;
let got = http::hex(&sha1::Sha1::digest(&toc));
if !got.eq_ignore_ascii_case(digest) {
bail!(
"the installer package's table of contents has SHA-1 {got}, the catalog says {digest}"
);
}
Ok(())
}
/// The command that installs macOS from an installer image, in Recovery's Terminal: the image's
/// exFAT volume, labelled `Installer`, mounts at `/Volumes/Installer`.
pub const IMAGE_COMMAND: &str = "sh /Volumes/Installer/install-macos.sh";
#[derive(Clone, Debug, serde::Serialize)]
pub struct Outputs {
pub installer: Installer,
/// The product of the recovery image it boots, or None for an image made before Apple's
/// current recovery image came out, which boots the earlier one.
pub recovery: Option<String>,
pub image: PathBuf,
}
const PACKAGE: &str = "InstallAssistant.pkg";
const BASE_SYSTEM: &str = "BaseSystem.dmg";
/// Makes `inst`'s offline installer in `dir`: a disk image, which reims-ctl attaches as the VM's
/// installer, named `macOS-<name>-<version>-<build>-offline-installer.img`, of two volumes:
/// - exFAT `Installer` (FAT32 holds no file of 4 GiB): `InstallAssistant.pkg`, and
/// `install-macos.sh`, which Recovery's Terminal runs to put the package's Install macOS app on
/// the VM's disk and start the app's `startosinstall`;
/// - FAT32 `RECOVERY`: the recovery image of the same macOS (major version), as
/// `com.apple.recovery.boot/BaseSystem.dmg` and its chunklist, which OpenCore boots, checking
/// Apple's signature, as it would from a USB stick.
///
/// Both files are downloaded straight into their places in the image, checked against their
/// chunklists, so the package is never on disk twice; an interrupted run is continued, and an
/// image already there is checked, and repaired if it needs it.
pub fn offline_installer(inst: &Installer, dir: &Path, r: &dyn Reporter) -> Result<Outputs> {
let major = inst.version.split('.').next().unwrap_or_default();
let v = recovery::find(major)
.with_context(|| format!("no recovery image for macOS {major} to boot the installer"))?;
let rec = recovery::ask(v, r)?;
let agent = http::agent();
let mut pkg_check: Box<dyn Check> = match &inst.integrity_url {
Some(u) => {
r.step(&format!("Reading {}'s chunklist", inst.label()));
let raw = http::get(&agent, u, &Headers::new(), 16 << 20)?;
let list = Chunklist::parse(&raw).context("the installer's chunklist")?;
if list.total() != inst.size {
bail!(
"the installer's chunklist covers {} bytes, the catalog says {}",
list.total(),
inst.size
);
}
Box::new(ChunkCheck::new(list))
}
// The size, and the table of contents below, are all there is to check.
None => Box::new(http::NoCheck),
};
let install_files = [
(
PACKAGE.to_string(),
Data::Reserved {
name: PACKAGE,
len: inst.size,
},
),
(
"install-macos.sh".to_string(),
Data::Bytes(install_script(inst).into_bytes()),
),
];
let recovery_files = [
(
format!("com.apple.recovery.boot/{BASE_SYSTEM}"),
Data::Reserved {
name: BASE_SYSTEM,
len: rec.size(),
},
),
(
"com.apple.recovery.boot/BaseSystem.chunklist".to_string(),
Data::Bytes(rec.chunklist.clone()),
),
];
// The package's volume first, so its place stays where it is when Apple's recovery image
// changes size between runs.
let disk = image::data_disk(&[
Volume {
fs: Fs::Exfat,
label: "Installer",
name: "macOS Installer",
files: &install_files,
},
Volume {
fs: Fs::Fat32,
label: "RECOVERY",
name: "macOS Recovery",
files: &recovery_files,
},
])?;
let (Some(pkg_at), Some(dmg_at)) = (disk.place(PACKAGE), disk.place(BASE_SYSTEM)) else {
bail!("the image has no place for its files");
};
let path = dir.join(inst.offline_installer_name());
let mut out = Outputs {
installer: inst.clone(),
recovery: Some(rec.product.clone()),
image: path.clone(),
};
let mut rec_check = rec.check();
if path.exists() {
// Read only: a VM may be running from it.
let mut f = File::open(&path).with_context(|| format!("open {}", path.display()))?;
// The package's place doesn't depend on the recovery image, so it's checked first.
let package = holds(&mut f, pkg_at, inst.size, pkg_check.as_mut(), r)?
&& inst
.digest
.as_deref()
.is_none_or(|d| check_toc(&mut f, pkg_at, d).is_ok());
if package {
if f.metadata()?.len() == disk.size
&& holds(&mut f, dmg_at, rec.size(), &mut rec_check, r)?
{
r.note(&format!(
"{} is already here and checks out",
path.display()
));
} else {
// Apple has a newer recovery image than the one the image was made with. The
// image is whole as it is (it was checked when it was made, and OpenCore checks
// its recovery image against its chunklist as it boots), and a VM may be running
// from it, so it's left alone.
r.note(&format!(
"{} is already here; its installer checks out, and its recovery image is \
an earlier one of Apple's",
path.display()
));
out.recovery = None;
}
return Ok(out);
}
std::fs::rename(&path, http::part_path(&path))
.with_context(|| format!("rename {}", path.display()))?;
}
let part = http::part_path(&path);
let mut f = image::open_raw(&disk, &part)?;
let dmg = Dest::Region {
file: &mut f,
offset: dmg_at,
len: rec.size(),
};
rec.download(dmg, &mut rec_check, r)?;
progress::check(r)?;
let mut d = Download::new(&inst.url, format!("Downloading {}", inst.label()));
d.size = Some(inst.size);
let pkg = Dest::Region {
file: &mut f,
offset: pkg_at,
len: inst.size,
};
http::download(&agent, d, pkg, pkg_check.as_mut(), r)?;
if let Some(digest) = &inst.digest {
check_toc(&mut f, pkg_at, digest)?;
}
f.sync_all()?;
drop(f);
std::fs::rename(&part, &path).with_context(|| format!("write {}", path.display()))?;
r.note(&format!("Wrote {}", path.display()));
Ok(out)
}
/// Whether `len` bytes at `offset` in `f` pass `check` whole (a check that reads nothing passes
/// them); leaves `check` ready for a download from the start.
fn holds(
f: &mut File,
offset: u64,
len: u64,
check: &mut dyn Check,
r: &dyn Reporter,
) -> Result<bool> {
if f.metadata()?.len() < offset + len {
return Ok(false);
}
let good = check.resume(f, offset, len, r)?;
check.restart_at(0);
Ok(good == len)
}
/// The script on an installer image that installs its macOS from Recovery's Terminal.
fn install_script(inst: &Installer) -> String {
format!(
r#"#!/bin/sh
# Installs {label} from the InstallAssistant.pkg beside this script, with no
# network needed. In macOS Recovery, erase the VM's disk in Disk Utility (APFS), then open
# Utilities > Terminal and run:
#
# {command}
#
# It installs onto the volume named Macintosh HD, or else Untitled (Disk Utility's name for
# it); for another, give its path after the script's.
#
# It installs the package's Install macOS app onto that volume, then runs the app's
# startosinstall, which restarts the VM into the installer.
set -e
here=$(cd "$(dirname "$0")" && pwd)
target=${{1:-}}
if [ -z "$target" ]; then
# Disk Utility names an erased disk Untitled unless told otherwise.
for v in "/Volumes/Macintosh HD" "/Volumes/Untitled"; do
if [ -d "$v" ]; then target=$v; break; fi
done
fi
target=${{target%/}}
if [ -z "$target" ] || [ ! -d "$target" ]; then
echo "There is no ${{target:-/Volumes/Macintosh HD}}: erase the VM's disk in Disk Utility" >&2
echo "first, or give the volume to install onto. These are mounted:" >&2
ls /Volumes >&2
exit 1
fi
# The package's postinstall script copies the package into the app as $3Applications/...,
# which is the app's folder only when $3, the target, is /. For a volume it is a path beside
# the volume, here on Recovery's small RAM disk, so a link puts it on the volume. (mist-cli,
# installing to a disk image, moves <volume>Applications into <volume>/Applications after.)
link="${{target}}Applications"
mkdir -p "$target/Applications"
ln -sfn "$target/Applications" "$link"
trap 'rm -f "$link"' EXIT
echo "Installing the Install macOS app onto $target, which takes a few minutes"
# CM_BUILD as mist-cli sets it, installing the package anywhere but /.
CM_BUILD=CM_BUILD installer -pkg "$here/InstallAssistant.pkg" -target "$target"
app=
for a in "$target"/Applications/Install\ macOS*.app; do
if [ -d "$a" ]; then app=$a; fi
done
if [ -z "$app" ] || [ ! -f "$app/Contents/SharedSupport/SharedSupport.dmg" ]; then
echo "The package left no complete Install macOS app in $target/Applications" >&2
exit 1
fi
rm -f "$link"
# As mist-cli does: the app's files can come out without the modes they need.
chmod -R 755 "$app"
echo "Starting $app; the VM restarts when it is ready"
exec "$app/Contents/Resources/startosinstall" --agreetolicense --volume "$target"
"#,
label = inst.label(),
command = IMAGE_COMMAND,
)
}
#[cfg(test)]
mod tests {
use super::*;
const DIST: &str = r#"<installer-gui-script minSpecVersion="2">
<title>macOS Tahoe</title>
<script>var boardIds = ['Mac-CFF7D910A743CAAF','Mac-AF89B6D9451A490B']; var models = ['J413AP'];</script>
<auxinfo>
<dict>
<key>BUILD</key>
<string>25G241</string>
<key>VERSION</key>
<string>26.7.1</string>
</dict>
</auxinfo></installer-gui-script>"#;
#[test]
fn install_script_is_valid_sh() {
let i = Installer {
product: "142-28081".into(),
title: "macOS Tahoe".into(),
version: "26.7.1".into(),
build: "25G241".into(),
posted: "2026-09-28".into(),
size: 0,
url: String::new(),
integrity_url: None,
digest: None,
};
let script = install_script(&i);
assert!(script.contains("# Installs macOS Tahoe 26.7.1 (25G241) from"));
assert!(script.contains(IMAGE_COMMAND));
let mut sh = std::process::Command::new("sh")
.arg("-n")
.stdin(std::process::Stdio::piped())
.spawn()
.unwrap();
std::io::Write::write_all(&mut sh.stdin.take().unwrap(), script.as_bytes()).unwrap();
assert!(sh.wait().unwrap().success());
}
#[test]
fn reads_a_distribution_file() {
assert_eq!(
parse_dist(DIST),
Some(DistInfo {
title: "macOS Tahoe".into(),
version: "26.7.1".into(),
build: "25G241".into(),
intel: true,
})
);
let arm_only = DIST
.replace("Mac-CFF7D910A743CAAF", "J414AP")
.replace("Mac-AF89B6D9451A490B", "J415AP");
assert!(!parse_dist(&arm_only).unwrap().intel);
assert!(!has_intel_board("Mac-XYZ"));
}
#[test]
fn finds_installers() {
let mk = |v: &str, b: &str, t: &str| Installer {
product: format!("p-{b}"),
title: t.into(),
version: v.into(),
build: b.into(),
posted: String::new(),
size: 0,
url: String::new(),
integrity_url: None,
digest: None,
};
let list = vec![
mk("26.7.1", "25G241", "macOS Tahoe"),
mk("26.7", "25G229", "macOS Tahoe"),
mk("15.8.1", "24H32", "macOS Sequoia"),
mk("11.7.11", "20G1443", "macOS Big Sur"),
];
assert_eq!(find(&list, "latest").unwrap().build, "25G241");
assert_eq!(find(&list, "26.7").unwrap().build, "25G229");
assert_eq!(find(&list, "26").unwrap().build, "25G241");
assert_eq!(find(&list, "24h32").unwrap().version, "15.8.1");
assert_eq!(find(&list, "sequoia").unwrap().version, "15.8.1");
assert_eq!(find(&list, "macOS Tahoe").unwrap().version, "26.7.1");
assert!(find(&list, "27").is_none());
for q in ["big sur", "Big Sur", "big-sur", "bigsur"] {
assert_eq!(find(&list, q).unwrap().version, "11.7.11", "{q}");
}
}
#[test]
fn sorts_versions_numerically() {
assert!(version_key("26.10") > version_key("26.9"));
assert!(version_key("11.7.10") > version_key("11.7.9"));
}
#[test]
fn formats_dates() {
let t = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_790_000_000);
assert_eq!(date_string(t), "2026-09-21");
}
}
+48
View File
@@ -0,0 +1,48 @@
//! reims-util: makes the OpenCore boot image and OVMF an x86-64 macOS VM boots through, and the
//! macOS installers it installs from, out of Apple's own files: online (Apple's recovery image)
//! and offline (a disk image of one exact release). With no command it opens its interactive
//! interface (tui.rs), in the terminal's lines rather than a full screen; each job is also a
//! command (cli.rs).
mod cache;
mod chunklist;
mod cli;
mod http;
mod image;
mod installer;
mod opencore;
mod ovmf;
mod progress;
mod recovery;
mod tui;
use clap::{CommandFactory, Parser};
use std::io::IsTerminal;
use std::process::ExitCode;
fn main() -> ExitCode {
let args = cli::Cli::parse();
let result = match args.command {
Some(c) => cli::run(c, args.json),
None if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() && !args.json => {
tui::run()
}
None => {
let _ = cli::Cli::command().print_help();
return ExitCode::from(2);
}
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) if e.is::<progress::Cancelled>() => {
eprintln!("Stopped. Run the same command again to resume.");
ExitCode::from(130)
}
Err(e) => {
if !args.json {
eprintln!("error: {e:#}");
}
ExitCode::FAILURE
}
}
}
+291
View File
@@ -0,0 +1,291 @@
//! The one ACPI table the OpenCore image adds, `SSDT-EC-USBX.aml`, encoded here in AML.
//!
//! macOS 10.15 and later look for an embedded controller named `EC` and for USB power
//! properties on a `USBX` device; q35 has neither. The table adds both, for macOS alone
//! (`_OSI ("Darwin")`), as this ASL, which OpenCorePkg's SSDT-EC-USBX sample is, with `EC` under
//! q35's `\_SB.PCI0` in place of a laptop's `LPCB`:
//!
//! ```text
//! DefinitionBlock ("", "SSDT", 2, "REIMS ", "EcUsbx", 0x00001000)
//! {
//! Scope (\_SB)
//! {
//! Device (USBX)
//! {
//! Name (_ADR, Zero)
//! Method (_DSM, 4, NotSerialized)
//! {
//! If ((Arg2 == Zero)) { Return (Buffer (One) { 0x03 }) }
//! Return (Package (0x08) {
//! "kUSBSleepPowerSupply", 0x13EC, "kUSBSleepPortCurrentLimit", 0x0834,
//! "kUSBWakePowerSupply", 0x13EC, "kUSBWakePortCurrentLimit", 0x0834 })
//! }
//! Method (_STA, 0, NotSerialized)
//! {
//! If (_OSI ("Darwin")) { Return (0x0F) } Else { Return (Zero) }
//! }
//! }
//! }
//! Scope (\_SB.PCI0)
//! {
//! Device (EC)
//! {
//! Name (_HID, "ACID0001")
//! Method (_STA, 0, NotSerialized)
//! {
//! If (_OSI ("Darwin")) { Return (0x0F) } Else { Return (Zero) }
//! }
//! }
//! }
//! }
//! ```
pub const FILE_NAME: &str = "SSDT-EC-USBX.aml";
const SCOPE_OP: u8 = 0x10;
const NAME_OP: u8 = 0x08;
const METHOD_OP: u8 = 0x14;
const DEVICE_OP: [u8; 2] = [0x5b, 0x82];
const IF_OP: u8 = 0xa0;
const ELSE_OP: u8 = 0xa1;
const RETURN_OP: u8 = 0xa4;
const LEQUAL_OP: u8 = 0x93;
const BUFFER_OP: u8 = 0x11;
const PACKAGE_OP: u8 = 0x12;
const ARG2_OP: u8 = 0x6a;
/// The table, header and checksum included.
pub fn ssdt_ec_usbx() -> Vec<u8> {
let usbx = device(
"USBX",
[
name("_ADR", integer(0)),
method(
"_DSM",
4,
[
if_(
[vec![LEQUAL_OP, ARG2_OP], integer(0)].concat(),
ret(pkg(&[BUFFER_OP], [integer(1), vec![0x03]].concat())),
),
ret(pkg(
&[PACKAGE_OP],
[
vec![0x08],
string("kUSBSleepPowerSupply"),
integer(0x13ec),
string("kUSBSleepPortCurrentLimit"),
integer(0x0834),
string("kUSBWakePowerSupply"),
integer(0x13ec),
string("kUSBWakePortCurrentLimit"),
integer(0x0834),
]
.concat(),
)),
]
.concat(),
),
sta_darwin_only(),
]
.concat(),
);
let ec = device(
"EC",
[name("_HID", string("ACID0001")), sta_darwin_only()].concat(),
);
let body = [
pkg(&[SCOPE_OP], [name_path("\\_SB"), usbx].concat()),
pkg(&[SCOPE_OP], [name_path("\\_SB.PCI0"), ec].concat()),
]
.concat();
table(*b"SSDT", 2, *b"REIMS ", *b"EcUsbx ", 0x1000, &body)
}
/// `Method (_STA) { If (_OSI ("Darwin")) { Return (0x0F) } Else { Return (Zero) } }`
fn sta_darwin_only() -> Vec<u8> {
method(
"_STA",
0,
[
if_(
[name_seg("_OSI").to_vec(), string("Darwin")].concat(),
ret(integer(0x0f)),
),
pkg(&[ELSE_OP], ret(integer(0))),
]
.concat(),
)
}
fn table(
signature: [u8; 4],
revision: u8,
oem_id: [u8; 6],
oem_table_id: [u8; 8],
oem_revision: u32,
body: &[u8],
) -> Vec<u8> {
let mut t = Vec::with_capacity(36 + body.len());
t.extend_from_slice(&signature);
t.extend_from_slice(&((36 + body.len()) as u32).to_le_bytes());
t.push(revision);
t.push(0); // checksum, below
t.extend_from_slice(&oem_id);
t.extend_from_slice(&oem_table_id);
t.extend_from_slice(&oem_revision.to_le_bytes());
t.extend_from_slice(b"RUTL");
t.extend_from_slice(&1u32.to_le_bytes());
t.extend_from_slice(body);
let sum = t.iter().fold(0u8, |a, b| a.wrapping_add(*b));
t[9] = 0u8.wrapping_sub(sum);
t
}
/// An op with a PkgLength: the length counts its own bytes and the body's.
fn pkg(op: &[u8], body: Vec<u8>) -> Vec<u8> {
let n = body.len();
let len_bytes = if n + 1 < 0x40 {
1
} else if n + 2 < 0x1000 {
2
} else if n + 3 < 0x10_0000 {
3
} else {
4
};
let total = n + len_bytes;
let mut v = op.to_vec();
if len_bytes == 1 {
v.push(total as u8);
} else {
v.push((((len_bytes - 1) as u8) << 6) | (total & 0x0f) as u8);
for i in 0..len_bytes - 1 {
v.push((total >> (4 + 8 * i)) as u8);
}
}
v.extend(body);
v
}
fn name_seg(s: &str) -> [u8; 4] {
let mut seg = [b'_'; 4];
for (d, c) in seg.iter_mut().zip(s.bytes()) {
*d = c;
}
seg
}
/// A path from the root: `\_SB`, `\_SB.PCI0`.
fn name_path(path: &str) -> Vec<u8> {
let segs: Vec<[u8; 4]> = path
.trim_start_matches('\\')
.split('.')
.map(name_seg)
.collect();
let mut v = vec![b'\\'];
match segs.len() {
1 => {}
2 => v.push(0x2e),
n => {
v.push(0x2f);
v.push(n as u8);
}
}
for s in segs {
v.extend_from_slice(&s);
}
v
}
fn integer(x: u64) -> Vec<u8> {
match x {
0 => vec![0x00],
1 => vec![0x01],
2..=0xff => vec![0x0a, x as u8],
0x100..=0xffff => [vec![0x0b], (x as u16).to_le_bytes().to_vec()].concat(),
0x1_0000..=0xffff_ffff => [vec![0x0c], (x as u32).to_le_bytes().to_vec()].concat(),
_ => [vec![0x0e], x.to_le_bytes().to_vec()].concat(),
}
}
fn string(s: &str) -> Vec<u8> {
[vec![0x0d], s.as_bytes().to_vec(), vec![0]].concat()
}
fn name(n: &str, value: Vec<u8>) -> Vec<u8> {
[vec![NAME_OP], name_seg(n).to_vec(), value].concat()
}
fn device(n: &str, body: Vec<u8>) -> Vec<u8> {
pkg(&DEVICE_OP, [name_seg(n).to_vec(), body].concat())
}
/// A NotSerialized method of `args` arguments.
fn method(n: &str, args: u8, body: Vec<u8>) -> Vec<u8> {
pkg(
&[METHOD_OP],
[name_seg(n).to_vec(), vec![args & 7], body].concat(),
)
}
fn if_(predicate: Vec<u8>, body: Vec<u8>) -> Vec<u8> {
pkg(&[IF_OP], [predicate, body].concat())
}
fn ret(value: Vec<u8>) -> Vec<u8> {
[vec![RETURN_OP], value].concat()
}
#[cfg(test)]
mod tests {
use super::*;
fn unhex(s: &str) -> Vec<u8> {
let s: String = s.split_whitespace().collect();
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
.collect()
}
#[test]
fn encodes_the_ec_device_as_iasl_does() {
let ec = device(
"EC",
[name("_HID", string("ACID0001")), sta_darwin_only()].concat(),
);
assert_eq!(
ec,
unhex(
"5b82 30 45435f5f 08 5f484944 0d 4143494430303031 00
14 1b 5f535441 00 a0 10 5f4f5349 0d 44617277696e 00 a4 0a0f a1 03 a4 00"
)
);
}
#[test]
fn encodes_two_byte_package_lengths() {
// 0x8f bytes in all: lead byte 0x4f (one more byte, low nibble f), then 0x08.
let v = pkg(&DEVICE_OP, vec![0; 0x8d]);
assert_eq!(&v[..4], &[0x5b, 0x82, 0x4f, 0x08]);
assert_eq!(v.len(), 2 + 0x8f);
}
#[test]
fn table_sums_to_zero() {
let t = ssdt_ec_usbx();
assert_eq!(&t[0..4], b"SSDT");
assert_eq!(
u32::from_le_bytes([t[4], t[5], t[6], t[7]]) as usize,
t.len()
);
assert_eq!(t.iter().fold(0u8, |a, b| a.wrapping_add(*b)), 0);
// The USBX method's return value starts as iasl writes it.
let usbx = t.windows(4).position(|w| w == b"USBX").unwrap();
assert_eq!(
&t[usbx + 4..usbx + 10],
&[0x08, b'_', b'A', b'D', b'R', 0x00]
);
}
}
+288
View File
@@ -0,0 +1,288 @@
//! OpenCore's `config.plist`, made from the `Sample.plist` of the release it boots with, so its
//! keys are always that release's.
//!
//! What changes from the sample is what a q35 VM on KVM needs, following the configuration the
//! reims-vgpu x86-64 guests were measured with (docs/qemu.md in reims-vgpu): an image built with
//! ULTMOS, whose kexts and settings for hardware a VM does not have (Bluetooth, audio codecs, GPU
//! power management, USB port maps, Intel graphics) are left out:
//! - the drivers a VM boots with: OpenRuntime, OpenHfsPlus (recovery images and installers are
//! HFS+), OpenPartitionDxe (older recovery images' Apple partition maps) and ResetNvramEntry;
//! - no kexts: QEMU's `isa-applesmc` is the SMC, and the GPU is reims-vgpu's, which macOS drives
//! with its own driver;
//! - one ACPI table, the `EC` and `USBX` devices macOS looks for (acpi.rs);
//! - CPUID leaf 1 reported as a Skylake-SP (family 6, model 85, stepping 4), a CPU every x86-64
//! macOS from 10.13 to 26 knows, whatever `-cpu` model the VM has;
//! - the kernel quirks a hypervisor needs (`ProvideCurrentCpuInfo`, `DummyPowerManagement`,
//! `ForceSecureBootScheme`), with Apple Secure Boot off, any volume scanned, no vault;
//! - optionally, the kernel's `kern.hv_vmm_present` swapped with `kern.hibernatecount`, so macOS
//! does not see it runs in a VM and lets iCloud and the App Store sign in;
//! - the SMBIOS identity (smbios.rs), and the picker's timeout and boot arguments.
use super::smbios::Smbios;
use anyhow::{Context, Result, bail};
use plist::{Dictionary, Value};
/// The drivers the image carries and loads, in order.
pub const DRIVERS: &[&str] = &[
"OpenRuntime.efi",
"OpenHfsPlus.efi",
"OpenPartitionDxe.efi",
"ResetNvramEntry.efi",
];
/// Arguments for every boot: kernel symbols in panic logs, and no panics on a TLB shootdown or a
/// timeout a vCPU took because the host descheduled it.
pub const DEFAULT_BOOT_ARGS: &str = "keepsyms=1 tlbto_us=0 vti=9";
/// Apple's NVRAM variables' GUID.
const APPLE_NVRAM: &str = "7C436110-AB2A-4BBB-A880-FE41995C9F82";
#[derive(Clone, Debug)]
pub struct Options {
pub smbios: Smbios,
/// Seconds the picker waits before it boots the default entry; 0 waits for a choice.
pub timeout: u32,
pub boot_args: String,
/// System Integrity Protection on (`csr-active-config` 0), or off (0x67, as the measured
/// guests ran).
pub sip: bool,
pub cpuid_spoof: bool,
pub hide_vm: bool,
}
pub fn make(sample: &[u8], o: &Options) -> Result<Vec<u8>> {
let mut root: Value = plist::from_bytes(sample).context("read Sample.plist")?;
let c = root
.as_dictionary_mut()
.context("Sample.plist is not a dictionary")?;
// ACPI: our table alone.
let acpi_entry = {
let mut e = template(c, &["ACPI", "Add"])?;
e.insert(
"Comment".into(),
"EC and USBX devices macOS looks for".into(),
);
e.insert("Enabled".into(), true.into());
e.insert("Path".into(), super::acpi::FILE_NAME.into());
e
};
set(c, &["ACPI"], "Add", vec![acpi_entry.into()].into())?;
set(c, &["ACPI"], "Delete", Value::Array(vec![]))?;
set(c, &["ACPI"], "Patch", Value::Array(vec![]))?;
set(c, &["Booter"], "MmioWhitelist", Value::Array(vec![]))?;
set(c, &["Booter"], "Patch", Value::Array(vec![]))?;
set(
c,
&["Booter", "Quirks"],
"FixupAppleEfiImages",
false.into(),
)?;
set(c, &["Booter", "Quirks"], "SetupVirtualMap", false.into())?;
set(
c,
&["DeviceProperties"],
"Add",
Value::Dictionary(Dictionary::new()),
)?;
set(
c,
&["DeviceProperties"],
"Delete",
Value::Dictionary(Dictionary::new()),
)?;
set(c, &["Kernel"], "Add", Value::Array(vec![]))?;
set(c, &["Kernel"], "Block", Value::Array(vec![]))?;
set(c, &["Kernel"], "Force", Value::Array(vec![]))?;
let (data, mask) = if o.cpuid_spoof {
(
[0x54, 0x06, 0x05, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].to_vec(),
[0xff, 0xff, 0xff, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].to_vec(),
)
} else {
(vec![], vec![])
};
set(c, &["Kernel", "Emulate"], "Cpuid1Data", Value::Data(data))?;
set(c, &["Kernel", "Emulate"], "Cpuid1Mask", Value::Data(mask))?;
set(
c,
&["Kernel", "Emulate"],
"DummyPowerManagement",
true.into(),
)?;
let mut patches = Vec::new();
if o.hide_vm {
for (comment, find, replace) in [
(
"Hide the VM: kern.hibernatecount reads kern.hv_vmm_present (1 of 2)",
&b"hibernatehidready\0hibernatecount\0"[..],
&b"hibernatehidready\0hv_vmm_present\0"[..],
),
(
"Hide the VM: kern.hv_vmm_present reads kern.hibernatecount (2 of 2)",
&b"boot session UUID\0hv_vmm_present\0"[..],
&b"boot session UUID\0hibernatecount\0"[..],
),
] {
let mut p = template(c, &["Kernel", "Patch"])?;
p.insert("Arch".into(), "x86_64".into());
p.insert("Base".into(), "".into());
p.insert("Comment".into(), comment.into());
p.insert("Count".into(), 1.into());
p.insert("Enabled".into(), true.into());
p.insert("Find".into(), Value::Data(find.to_vec()));
p.insert("Identifier".into(), "kernel".into());
p.insert("Limit".into(), 0.into());
p.insert("Mask".into(), Value::Data(vec![]));
p.insert("MaxKernel".into(), "".into());
p.insert("MinKernel".into(), "".into());
p.insert("Replace".into(), Value::Data(replace.to_vec()));
p.insert("ReplaceMask".into(), Value::Data(vec![]));
p.insert("Skip".into(), 0.into());
patches.push(Value::Dictionary(p));
}
}
set(c, &["Kernel"], "Patch", Value::Array(patches))?;
set(
c,
&["Kernel", "Quirks"],
"ForceSecureBootScheme",
true.into(),
)?;
set(
c,
&["Kernel", "Quirks"],
"ProvideCurrentCpuInfo",
true.into(),
)?;
set(c, &["Kernel", "Quirks"], "SetApfsTrimTimeout", 0.into())?;
set(c, &["Misc", "Boot"], "HideAuxiliary", false.into())?;
set(c, &["Misc", "Boot"], "PickerMode", "Builtin".into())?;
set(c, &["Misc", "Boot"], "PollAppleHotKeys", true.into())?;
set(c, &["Misc", "Boot"], "ShowPicker", true.into())?;
set(c, &["Misc", "Boot"], "Timeout", (o.timeout as i64).into())?;
set(c, &["Misc"], "Entries", Value::Array(vec![]))?;
set(c, &["Misc"], "Tools", Value::Array(vec![]))?;
set(c, &["Misc", "Security"], "AllowSetDefault", true.into())?;
set(c, &["Misc", "Security"], "ScanPolicy", 0.into())?;
set(
c,
&["Misc", "Security"],
"SecureBootModel",
"Disabled".into(),
)?;
set(c, &["Misc", "Security"], "Vault", "Optional".into())?;
let nvram = &["NVRAM", "Add", APPLE_NVRAM];
set(c, nvram, "boot-args", o.boot_args.trim().into())?;
let csr: u32 = if o.sip { 0 } else { 0x67 };
set(
c,
nvram,
"csr-active-config",
Value::Data(csr.to_le_bytes().to_vec()),
)?;
set(c, nvram, "prev-lang:kbd", Value::Data(b"en-US:0".to_vec()))?;
// Deleted before they are added, so the image's values win over what NVRAM holds.
let delete = dict(c, &["NVRAM", "Delete"])?;
let mut names: Vec<Value> = match delete.get(APPLE_NVRAM) {
Some(Value::Array(a)) => a.clone(),
_ => vec![],
};
for n in ["boot-args", "csr-active-config", "prev-lang:kbd"] {
if !names.iter().any(|v| v.as_string() == Some(n)) {
names.push(n.into());
}
}
delete.insert(APPLE_NVRAM.into(), Value::Array(names));
let g = &["PlatformInfo", "Generic"];
set(c, &["PlatformInfo"], "Automatic", true.into())?;
set(c, g, "SystemProductName", o.smbios.model.as_str().into())?;
set(c, g, "SystemSerialNumber", o.smbios.serial.as_str().into())?;
set(c, g, "MLB", o.smbios.mlb.as_str().into())?;
set(c, g, "SystemUUID", o.smbios.uuid.as_str().into())?;
set(c, g, "ROM", Value::Data(unhex(&o.smbios.rom)?))?;
set(c, &["UEFI", "APFS"], "MinDate", (-1i64).into())?;
set(c, &["UEFI", "APFS"], "MinVersion", (-1i64).into())?;
set(c, &["UEFI", "Output"], "Resolution", "".into())?;
let sample_drivers: Vec<Value> = match dict(c, &["UEFI"])?.get("Drivers") {
Some(Value::Array(a)) => a.clone(),
_ => bail!("Sample.plist has no UEFI > Drivers"),
};
let mut drivers = Vec::new();
for name in DRIVERS {
let mut e = sample_drivers
.iter()
.filter_map(Value::as_dictionary)
.find(|d| d.get("Path").and_then(Value::as_string) == Some(name))
.cloned()
.or_else(|| {
sample_drivers
.first()
.and_then(Value::as_dictionary)
.cloned()
})
.context("Sample.plist lists no drivers")?;
e.insert("Path".into(), (*name).into());
e.insert("Arguments".into(), "".into());
e.insert("Enabled".into(), true.into());
e.insert("LoadEarly".into(), false.into());
drivers.push(Value::Dictionary(e));
}
set(c, &["UEFI"], "Drivers", Value::Array(drivers))?;
set(c, &["UEFI"], "ReservedMemory", Value::Array(vec![]))?;
let mut out = Vec::new();
root.to_writer_xml(&mut out).context("write config.plist")?;
Ok(out)
}
fn dict<'a>(root: &'a mut Dictionary, path: &[&str]) -> Result<&'a mut Dictionary> {
let mut d = root;
for (i, k) in path.iter().enumerate() {
d = d
.get_mut(k)
.and_then(Value::as_dictionary_mut)
.with_context(|| format!("Sample.plist has no {}", path[..=i].join(" > ")))?;
}
Ok(d)
}
/// Sets a key that the sample has, so a key a later release renamed fails here, not at boot.
fn set(root: &mut Dictionary, path: &[&str], key: &str, value: Value) -> Result<()> {
let d = dict(root, path)?;
if !d.contains_key(key) {
bail!("Sample.plist has no {} > {key}", path.join(" > "));
}
d.insert(key.into(), value);
Ok(())
}
/// The first entry of an array of dictionaries: a new entry has its keys.
fn template(root: &mut Dictionary, path: &[&str]) -> Result<Dictionary> {
let (parent, key) = path.split_at(path.len() - 1);
let d = dict(root, parent)?;
d.get(key[0])
.and_then(Value::as_array)
.and_then(|a| a.first())
.and_then(Value::as_dictionary)
.cloned()
.with_context(|| format!("Sample.plist has no entry in {}", path.join(" > ")))
}
fn unhex(s: &str) -> Result<Vec<u8>> {
(0..s.len())
.step_by(2)
.map(|i| {
s.get(i..i + 2)
.and_then(|b| u8::from_str_radix(b, 16).ok())
.with_context(|| format!("not hex: {s}"))
})
.collect()
}
+122
View File
@@ -0,0 +1,122 @@
//! The OpenCore boot image: a 128 MiB GPT disk whose EFI system partition holds a pinned
//! OpenCore release, the drivers and ACPI table a VM needs, and a `config.plist` made for a q35
//! VM (config.rs) with an SMBIOS identity of its own (smbios.rs). OVMF goes beside it (ovmf.rs),
//! where reims-ctl looks for it.
pub mod acpi;
pub mod config;
pub mod smbios;
use crate::cache::{self, Pinned};
use crate::image::{self, Data, Format};
use crate::progress::{self, Reporter};
use anyhow::{Context, Result};
use std::io::Read;
use std::path::{Path, PathBuf};
pub const VERSION: &str = "1.0.8";
const RELEASE: Pinned = Pinned {
name: "OpenCore-1.0.8-RELEASE.zip",
url: "https://github.com/acidanthera/OpenCorePkg/releases/download/1.0.8/OpenCore-1.0.8-RELEASE.zip",
sha256: "2011e8b7216ecb2645d97ea710df965947edd406846e92050b9bc4190be6d27b",
what: "OpenCore 1.0.8",
};
/// The image's size: room for OpenCore (about 2 MiB of it here) and for what a person may add.
const DISK_SIZE: u64 = 128 << 20;
#[derive(Clone, Debug)]
pub struct Options {
pub output: PathBuf,
pub config: config::Options,
/// Where OVMF's files go, or None to write none.
pub ovmf_dir: Option<PathBuf>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct Outputs {
pub image: PathBuf,
pub format: Format,
pub opencore: &'static str,
pub smbios: smbios::Smbios,
pub ovmf: Option<crate::ovmf::Outputs>,
}
pub fn build(o: &Options, r: &dyn Reporter) -> Result<Outputs> {
let zip_path = cache::fetch(&RELEASE, r)?;
progress::check(r)?;
r.step(&format!("Building the OpenCore {VERSION} image"));
let files = files(&zip_path, &o.config)?;
let files: Vec<(String, Data)> = files
.into_iter()
.map(|(p, d)| (p, Data::Bytes(d)))
.collect();
let disk = image::esp_disk(DISK_SIZE, "OPENCORE", &files)?;
let format = Format::for_path(&o.output);
image::write(&disk, &o.output, format)?;
r.note(&format!("Wrote {}", o.output.display()));
let ovmf = match &o.ovmf_dir {
Some(dir) => {
progress::check(r)?;
let out = crate::ovmf::write(dir, r)?;
r.note(&format!(
"Wrote {} and {}",
out.code.display(),
out.vars.display()
));
Some(out)
}
None => None,
};
Ok(Outputs {
image: o.output.clone(),
format,
opencore: VERSION,
smbios: o.config.smbios.clone(),
ovmf,
})
}
/// The partition's files, from the release's X64 tree, and the made config.plist and ACPI table.
fn files(zip_path: &Path, c: &config::Options) -> Result<Vec<(String, Vec<u8>)>> {
let f =
std::fs::File::open(zip_path).with_context(|| format!("open {}", zip_path.display()))?;
let mut zip = zip::ZipArchive::new(f).context("read the OpenCore release")?;
let mut read = |name: &str| -> Result<Vec<u8>> {
let mut e = zip
.by_name(name)
.with_context(|| format!("the OpenCore release has no {name}"))?;
let mut v = Vec::new();
e.read_to_end(&mut v)?;
Ok(v)
};
let mut files = Vec::new();
for p in [
"EFI/BOOT/BOOTx64.efi",
"EFI/BOOT/.contentFlavour",
"EFI/BOOT/.contentVisibility",
"EFI/OC/OpenCore.efi",
"EFI/OC/.contentFlavour",
"EFI/OC/.contentVisibility",
] {
files.push((p.to_string(), read(&format!("X64/{p}"))?));
}
for d in config::DRIVERS {
files.push((
format!("EFI/OC/Drivers/{d}"),
read(&format!("X64/EFI/OC/Drivers/{d}"))?,
));
}
let sample = read("Docs/Sample.plist")?;
files.push(("EFI/OC/config.plist".into(), config::make(&sample, c)?));
files.push((
format!("EFI/OC/ACPI/{}", acpi::FILE_NAME),
acpi::ssdt_ec_usbx(),
));
// The release's other folders, empty, for what a person adds.
for d in ["EFI/OC/Kexts/", "EFI/OC/Resources/", "EFI/OC/Tools/"] {
files.push((d.to_string(), Vec::new()));
}
Ok(files)
}
+306
View File
@@ -0,0 +1,306 @@
//! The Mac a VM claims to be: its model, serial number, logic board serial (MLB), system UUID and
//! ROM, which OpenCore writes into SMBIOS and NVRAM.
//!
//! Serials follow the format Apple's are in, as macserial generates them (OpenCorePkg's
//! Utilities/macserial, BSD-3-Clause; Copyright (c) 2018-2020 vit9696, Copyright (c) 2020 Matis
//! Schotte), from its tables for the models below. Its FORMAT.md describes the fields:
//! - a 12-character serial: location (3), year (1), week (1), production line (3), model (4);
//! - a 17-character MLB: location (3), year (1 digit), week (2 digits), two random blocks, the
//! board code (4), a random suffix (2), with a base-34 checksum over the whole.
//!
//! A serial made this way has the right shape for its model; whether Apple knows it is chance.
use anyhow::{Result, bail, ensure};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Model {
pub name: &'static str,
/// The macOS versions it runs, for the interface.
pub runs: &'static str,
location: &'static str,
years: &'static [u32],
model_code: &'static str,
board_code: &'static str,
}
/// iMac20,1 runs macOS 10.15.6 to 26: every x86-64 macOS a reims-vgpu guest runs. iMacPro1,1 runs
/// 10.13 to 15, for older guests.
pub const MODELS: &[Model] = &[
Model {
name: "iMac20,1",
runs: "macOS 10.15.6 to 26",
location: "C02",
years: &[2020, 2021, 2022],
model_code: "PN5T",
board_code: "PHC1",
},
Model {
name: "iMacPro1,1",
runs: "macOS 10.13 to 15",
location: "C02",
years: &[2017, 2018, 2019, 2020, 2021],
model_code: "HX87",
board_code: "JG36",
},
];
pub fn model(name: &str) -> Option<&'static Model> {
MODELS
.iter()
.find(|m| m.name.eq_ignore_ascii_case(name.trim()))
}
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct Smbios {
pub model: String,
pub serial: String,
pub mlb: String,
pub uuid: String,
/// Six bytes, as 12 hex digits.
pub rom: String,
}
const BASE34: &[u8] = b"0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const YEAR_CODES: &[u8] = b"CDFGHJKLMNPQRSTVWXYZ";
/// Week 1 to 53: the first 26 in the year's first half, the rest in its second, after a 0 that
/// has no week.
const WEEK_CODES: &[u8] = b"0123456789CDFGHJKLMNPQRTVWX123456789CDFGHJKLMNPQRTVWXY";
const MLB_BLOCK1: &[&str] = &[
"200", "600", "403", "404", "405", "303", "108", "207", "609", "501", "306", "102", "701",
"301", "501", "101", "300", "130", "100", "270", "310", "902", "104", "401", "902", "500",
"700", "802",
];
const MLB_BLOCK2: &[&str] = &["GU", "4N", "J9", "QX", "OP", "CD", "GU"];
const MLB_BLOCK3: &[&str] = &[
"1H", "1M", "AD", "1F", "A8", "UE", "JA", "JC", "8C", "CB", "FB",
];
/// The highest production line a first copy can encode (macserial's SERIAL_LINE_REPR_MAX).
const LINE_REPR_MAX: u32 = 1155;
const LINE_MAX: u32 = 3399;
pub struct Rng;
impl Rng {
pub fn u32(&mut self) -> Result<u32> {
getrandom::u32().map_err(|e| anyhow::anyhow!("random: {e}"))
}
pub fn below(&mut self, n: u32) -> Result<u32> {
Ok(self.u32()? % n)
}
pub fn bytes(&mut self, b: &mut [u8]) -> Result<()> {
getrandom::fill(b).map_err(|e| anyhow::anyhow!("random: {e}"))
}
}
/// A new identity for `m`. The ROM is random, with the locally administered bit set, unless the
/// caller gives one (the VM's MAC address is the usual choice).
pub fn generate(m: &Model) -> Result<Smbios> {
let mut rng = Rng;
let year = m.years[rng.below(m.years.len() as u32)? as usize];
let week = 1 + rng.below(52)?;
let line = rng.below(LINE_MAX + 1)?;
let serial = serial(m, year, week, line)?;
let mlb = mlb(m, &serial, &mut rng)?;
let mut uuid = [0u8; 16];
rng.bytes(&mut uuid)?;
let mut rom = [0u8; 6];
rng.bytes(&mut rom)?;
rom[0] = (rom[0] & 0xfe) | 0x02;
Ok(Smbios {
model: m.name.to_string(),
serial,
mlb,
uuid: uuid_v4(uuid),
rom: crate::http::hex(&rom).to_ascii_uppercase(),
})
}
fn serial(m: &Model, year: u32, week: u32, line: u32) -> Result<String> {
ensure!((2010..=2030).contains(&year), "year {year} out of range");
ensure!((1..=53).contains(&week), "week {week} out of range");
let base = if year >= 2020 { 2020 } else { 2010 };
let year_code = YEAR_CODES[((year - base) * 2 + u32::from(week >= 27)) as usize];
let week_code = WEEK_CODES[week as usize];
// The line as three base-34 digits, weighted 68, 34 and 1, with the smallest first digit
// that reaches it (its first copy).
let rmin = if line > LINE_REPR_MAX {
(line - LINE_REPR_MAX).div_ceil(68)
} else {
0
};
let rest = line - rmin * 68;
let mut s = String::from(m.location);
s.push(year_code as char);
s.push(week_code as char);
s.push(BASE34[rmin as usize] as char);
s.push(BASE34[(rest / 34) as usize] as char);
s.push(BASE34[(rest % 34) as usize] as char);
s.push_str(m.model_code);
Ok(s)
}
/// A new MLB for a serial number someone gave, made to go with it.
pub fn mlb_for(m: &Model, serial: &str) -> Result<String> {
mlb(m, serial, &mut Rng)
}
/// The MLB for `serial`, made on the same week or just before, as macserial derives it.
fn mlb(m: &Model, serial: &str, rng: &mut Rng) -> Result<String> {
let b = serial.as_bytes();
ensure!(
b.len() == 12,
"a 12-character serial is needed for a 17-character MLB"
);
let (year_code, week_code) = (b[3], b[4]);
let mut year = YEAR_CODES
.iter()
.position(|c| *c == year_code)
.map(|i| (i / 2) as u32)
.unwrap_or(0);
let mut week = if b"DGJLNQSVXZ".contains(&year_code) {
27
} else {
0
};
if let Some(i) = b"123456789CDFGHJKLMNPQRSTVWXYZ"
.iter()
.position(|c| *c == week_code)
{
week += i as u32 + 1;
}
ensure!(week >= 1, "serial {serial} has no week");
week -= 1;
if week == 0 {
week = 53;
year = if year == 0 { 9 } else { year - 1 };
}
for _ in 0..100_000 {
let s = format!(
"{}{}{:02}{}{}{}{}",
m.location,
year,
week,
MLB_BLOCK1[rng.below(MLB_BLOCK1.len() as u32)? as usize],
MLB_BLOCK2[rng.below(MLB_BLOCK2.len() as u32)? as usize],
m.board_code,
MLB_BLOCK3[rng.below(MLB_BLOCK3.len() as u32)? as usize],
);
if mlb_checksum_ok(&s) {
return Ok(s);
}
}
bail!("no MLB with a valid checksum found")
}
/// The 17-character MLB checksum: base-34 digits weighted 3 and 1 alternately, summing to a
/// multiple of 34.
pub fn mlb_checksum_ok(mlb: &str) -> bool {
let len = mlb.len();
let mut sum = 0usize;
for (i, c) in mlb.bytes().enumerate() {
let Some(v) = BASE34.iter().position(|x| *x == c) else {
return false;
};
sum += if (i & 1) == (len & 1) { 3 } else { 1 } * v;
}
sum.is_multiple_of(34)
}
fn uuid_v4(mut b: [u8; 16]) -> String {
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
let h = crate::http::hex(&b).to_ascii_uppercase();
format!(
"{}-{}-{}-{}-{}",
&h[0..8],
&h[8..12],
&h[12..16],
&h[16..20],
&h[20..32]
)
}
/// A ROM given as 12 hex digits or as a MAC address (`52:54:00:12:34:56`).
pub fn parse_rom(s: &str) -> Result<String> {
let h: String = s
.chars()
.filter(|c| !matches!(c, ':' | '-' | ' '))
.collect();
ensure!(
h.len() == 12 && h.chars().all(|c| c.is_ascii_hexdigit()),
"a ROM is six bytes: 12 hex digits or a MAC address, not {s:?}"
);
Ok(h.to_ascii_uppercase())
}
pub fn parse_uuid(s: &str) -> Result<String> {
let h: String = s.chars().filter(|c| *c != '-').collect();
ensure!(
h.len() == 32 && h.chars().all(|c| c.is_ascii_hexdigit()),
"not a UUID: {s:?}"
);
let h = h.to_ascii_uppercase();
Ok(format!(
"{}-{}-{}-{}-{}",
&h[0..8],
&h[8..12],
&h[12..16],
&h[16..20],
&h[20..32]
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serial_fields_follow_the_format() {
let m = model("iMac20,1").unwrap();
// The second half of 2020 is D; week 30 there is 4 (30 - 26); line 1000 is 0, V (29), E (14).
assert_eq!(serial(m, 2020, 30, 1000).unwrap(), "C02D40VEPN5T");
// First half of 2017 is T, week 5; a line past the first copies' range moves the first
// digit.
let p = model("imacpro1,1").unwrap();
assert_eq!(serial(p, 2017, 5, 3399).unwrap(), "C02T5ZZZHX87");
}
#[test]
fn known_mlbs_pass_the_checksum() {
// The MLB of macrecovery's selfcheck, and one macserial made for iMac20,1.
assert!(mlb_checksum_ok("F5K105303J9K3F71M"));
assert!(mlb_checksum_ok("C02051310QXPHC11F"));
assert!(!mlb_checksum_ok("C02051310QXPHC11G"));
}
#[test]
fn generated_identities_are_well_formed() {
for m in MODELS {
for _ in 0..50 {
let s = generate(m).unwrap();
assert_eq!(s.serial.len(), 12);
assert!(s.serial.ends_with(m.model_code));
assert_eq!(s.mlb.len(), 17);
assert!(mlb_checksum_ok(&s.mlb));
assert_eq!(&s.mlb[11..15], m.board_code);
assert_eq!(s.uuid.len(), 36);
assert_eq!(&s.uuid[14..15], "4");
assert_eq!(s.rom.len(), 12);
// An MLB made for a given serial is from the same week as the one made with it.
let mlb = mlb_for(m, &s.serial).unwrap();
assert!(mlb_checksum_ok(&mlb));
assert_eq!(mlb[..6], s.mlb[..6]);
}
}
}
#[test]
fn parses_roms_and_uuids() {
assert_eq!(parse_rom("52:54:00:d7:83:02").unwrap(), "525400D78302");
assert!(parse_rom("5254").is_err());
assert_eq!(
parse_uuid("ce36c47babd64d3585db37abe424cb5d").unwrap(),
"CE36C47B-ABD6-4D35-85DB-37ABE424CB5D"
);
}
}
+90
View File
@@ -0,0 +1,90 @@
//! OVMF, the UEFI firmware an x86-64 VM boots OpenCore with: its code and its variable store,
//! from Arch Linux's `edk2-ovmf` package, pinned.
//!
//! The pinned build is the one the reims-vgpu macOS 26 guest on homelab-ms01 boots: its
//! `OVMF_CODE.4m.fd` and `OVMF_VARS.4m.fd` are those files' bytes. It is built without SMM and
//! without Secure Boot, so it runs on q35 under KVM as reims-ctl starts it. Its licenses
//! (BSD-2-Clause-Patent, with Apache-2.0 and MIT parts) are in the package, and are written
//! beside the firmware.
use crate::cache::{self, Pinned};
use crate::progress::Reporter;
use anyhow::{Context, Result, bail};
use std::io::Read;
use std::path::{Path, PathBuf};
pub const VERSION: &str = "edk2-ovmf 202608-1";
const PACKAGE: Pinned = Pinned {
name: "edk2-ovmf-202608-1-any.pkg.tar.zst",
url: "https://archive.archlinux.org/packages/e/edk2-ovmf/edk2-ovmf-202608-1-any.pkg.tar.zst",
sha256: "bee34c6036ebd0e96562b7330d2d3ddf75e240cfc44a6d506a5ccb6390eafb91",
what: "OVMF (Arch Linux's edk2-ovmf 202608-1)",
};
/// The package's files, what each is written as, and its SHA-256.
const FILES: &[(&str, &str, Option<&str>)] = &[
(
"usr/share/edk2/x64/OVMF_CODE.4m.fd",
"OVMF_CODE.fd",
Some("2febd26c0b4cf95a636a941afa37d64a552723443ed9ac72f763f6840da98cb4"),
),
(
"usr/share/edk2/x64/OVMF_VARS.4m.fd",
"OVMF_VARS.fd",
Some("5d2ac383371b408398accee7ec27c8c09ea5b74a0de0ceea6513388b15be5d1e"),
),
(
"usr/share/licenses/edk2-ovmf/License.txt",
"OVMF-License.txt",
None,
),
(
"usr/share/licenses/edk2-ovmf/OvmfPkg.License.txt",
"OVMF-OvmfPkg-License.txt",
None,
),
];
#[derive(Clone, Debug, serde::Serialize)]
pub struct Outputs {
pub code: PathBuf,
pub vars: PathBuf,
}
/// Writes `OVMF_CODE.fd` and `OVMF_VARS.fd`, and the firmware's licenses, into `dir`.
pub fn write(dir: &Path, r: &dyn Reporter) -> Result<Outputs> {
let pkg = cache::fetch(&PACKAGE, r)?;
r.step("Writing OVMF's code and variables");
let f = std::fs::File::open(&pkg).with_context(|| format!("open {}", pkg.display()))?;
let zst = ruzstd::decoding::StreamingDecoder::new(std::io::BufReader::new(f))
.map_err(|e| anyhow::anyhow!("read {}: {e}", pkg.display()))?;
let mut tar = tar::Archive::new(zst);
std::fs::create_dir_all(dir).with_context(|| format!("create {}", dir.display()))?;
let mut found = 0;
for entry in tar.entries()? {
let mut entry = entry?;
let path = entry.path()?.to_string_lossy().into_owned();
let Some((_, out, sha)) = FILES.iter().find(|(p, _, _)| *p == path) else {
continue;
};
let mut data = Vec::new();
entry.read_to_end(&mut data)?;
if let Some(sha) = sha {
use sha2::{Digest, Sha256};
let got = crate::http::hex(&Sha256::digest(&data));
if got != *sha {
bail!("{path} in the OVMF package has SHA-256 {got}, not the pinned {sha}");
}
}
crate::http::write_atomic(&dir.join(out), &data)?;
found += 1;
}
if found != FILES.len() {
bail!("the OVMF package lacks some of its files");
}
Ok(Outputs {
code: dir.join("OVMF_CODE.fd"),
vars: dir.join("OVMF_VARS.fd"),
})
}
+295
View File
@@ -0,0 +1,295 @@
//! How slow work reports what it is doing, and learns that it should stop.
//!
//! Each job (building an image, a download) takes a [`Reporter`]. The interactive interface's
//! reporter sends the events to its screen from the job's thread; the command line's prints them,
//! as text on stderr or as JSON lines on stdout (`--json`), which is what reims-ctl reads.
use serde::Serialize;
use std::io::Write;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum Event {
/// A new phase of the job: "Downloading OpenCore 1.0.8".
Step { message: String },
/// Bytes done in the current phase, of `total` when it is known.
Progress { done: u64, total: Option<u64> },
/// A line worth keeping: a retry, a file written.
Note { message: String },
}
pub trait Reporter: Sync {
fn event(&self, e: Event);
/// Whether the job should stop. A download stops between reads, keeping what it has, so
/// running it again resumes.
fn cancelled(&self) -> bool {
false
}
fn step(&self, message: &str) {
self.event(Event::Step {
message: message.to_string(),
});
}
fn progress(&self, done: u64, total: Option<u64>) {
self.event(Event::Progress { done, total });
}
fn note(&self, message: &str) {
self.event(Event::Note {
message: message.to_string(),
});
}
}
/// The error a job returns when its reporter cancelled it.
#[derive(Debug)]
pub struct Cancelled;
impl std::fmt::Display for Cancelled {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("cancelled")
}
}
impl std::error::Error for Cancelled {}
pub fn check(r: &dyn Reporter) -> anyhow::Result<()> {
if r.cancelled() {
return Err(Cancelled.into());
}
Ok(())
}
/// Prints events for a person at a terminal, on stderr: each step and note on a line of its own,
/// and progress on one line rewritten in place (at most ten times a second), or, when stderr is
/// not a terminal, a line every ten seconds.
pub struct TextReporter {
tty: bool,
state: Mutex<TextState>,
pub cancel: AtomicBool,
}
struct TextState {
last: Option<Instant>,
on_progress_line: bool,
rate: Rate,
}
impl TextReporter {
pub fn new() -> Self {
use std::io::IsTerminal;
TextReporter {
tty: std::io::stderr().is_terminal(),
state: Mutex::new(TextState {
last: None,
on_progress_line: false,
rate: Rate::default(),
}),
cancel: AtomicBool::new(false),
}
}
}
impl Reporter for TextReporter {
fn event(&self, e: Event) {
let Ok(mut s) = self.state.lock() else {
return;
};
let mut err = std::io::stderr().lock();
match e {
Event::Step { message } | Event::Note { message } => {
if s.on_progress_line {
let _ = writeln!(err);
s.on_progress_line = false;
}
let _ = writeln!(err, "{message}");
s.last = None;
s.rate = Rate::default();
}
Event::Progress { done, total } => {
s.rate.add(done);
let every = if self.tty {
Duration::from_millis(100)
} else {
Duration::from_secs(10)
};
let finished = total == Some(done);
if !finished && s.last.is_some_and(|t| t.elapsed() < every) {
return;
}
// A log's first line waits for something done.
if !self.tty && done == 0 && !finished {
return;
}
s.last = Some(Instant::now());
let line = progress_line(done, total, s.rate.per_second());
if self.tty {
let _ = write!(err, "\r\x1b[2K {line}");
s.on_progress_line = true;
if finished {
let _ = writeln!(err);
s.on_progress_line = false;
}
} else {
let _ = writeln!(err, " {line}");
}
}
}
let _ = err.flush();
}
fn cancelled(&self) -> bool {
self.cancel.load(Ordering::Relaxed)
}
}
/// Prints each event as a line of JSON on stdout, at most ten progress events a second.
pub struct JsonReporter {
last: Mutex<Option<Instant>>,
}
impl JsonReporter {
pub fn new() -> Self {
JsonReporter {
last: Mutex::new(None),
}
}
}
impl Reporter for JsonReporter {
fn event(&self, e: Event) {
if let Event::Progress { done, total } = e
&& total != Some(done)
&& let Ok(mut last) = self.last.lock()
{
if last.is_some_and(|t| t.elapsed() < Duration::from_millis(100)) {
return;
}
*last = Some(Instant::now());
}
json_line(&e);
}
}
pub fn json_line<T: Serialize>(v: &T) {
if let Ok(s) = serde_json::to_string(v) {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "{s}");
let _ = out.flush();
}
}
/// "1.2 GiB of 15.6 GiB (8%), 24.0 MiB/s, 10 min left"
pub fn progress_line(done: u64, total: Option<u64>, per_second: Option<f64>) -> String {
let mut s = match total {
Some(t) if t > 0 => format!(
"{} of {} ({}%)",
bytes(done),
bytes(t),
(done as u128 * 100 / t as u128)
),
_ => bytes(done),
};
if let Some(r) = per_second.filter(|r| *r > 0.0) {
s.push_str(&format!(", {}/s", bytes(r as u64)));
if let Some(t) = total
&& t > done
{
s.push_str(&format!(
", {} left",
duration(((t - done) as f64 / r) as u64)
));
}
}
s
}
pub fn bytes(n: u64) -> String {
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut v = n as f64;
let mut u = 0;
while v >= 1024.0 && u + 1 < UNITS.len() {
v /= 1024.0;
u += 1;
}
if u == 0 {
format!("{n} B")
} else {
format!("{v:.1} {}", UNITS[u])
}
}
pub fn duration(secs: u64) -> String {
match secs {
0..60 => format!("{secs} s"),
60..3600 => format!("{} min", secs.div_ceil(60)),
_ => format!("{} h {} min", secs / 3600, (secs % 3600) / 60),
}
}
/// A transfer rate over the last few seconds.
#[derive(Default)]
pub struct Rate {
samples: std::collections::VecDeque<(Instant, u64)>,
}
impl Rate {
pub fn add(&mut self, done: u64) {
let now = Instant::now();
if self.samples.back().is_some_and(|(_, d)| done < *d) {
self.samples.clear();
}
self.samples.push_back((now, done));
while self
.samples
.front()
.is_some_and(|(t, _)| now.duration_since(*t) > Duration::from_secs(5))
{
self.samples.pop_front();
}
}
pub fn per_second(&self) -> Option<f64> {
let (t0, d0) = self.samples.front()?;
let (t1, d1) = self.samples.back()?;
let secs = t1.duration_since(*t0).as_secs_f64();
if secs < 0.5 {
return None;
}
Some((d1 - d0) as f64 / secs)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_sizes_and_times() {
assert_eq!(bytes(512), "512 B");
assert_eq!(bytes(1536), "1.5 KiB");
assert_eq!(bytes(15_664_523_626), "14.6 GiB");
assert_eq!(duration(59), "59 s");
assert_eq!(duration(61), "2 min");
assert_eq!(duration(3700), "1 h 1 min");
assert_eq!(
progress_line(1 << 30, Some(4 << 30), Some(1024.0 * 1024.0)),
"1.0 GiB of 4.0 GiB (25%), 1.0 MiB/s, 52 min left"
);
}
#[test]
fn events_serialize_as_tagged_json() {
let e = Event::Progress {
done: 5,
total: Some(10),
};
assert_eq!(
serde_json::to_string(&e).unwrap(),
r#"{"event":"progress","done":5,"total":10}"#
);
}
}
+412
View File
@@ -0,0 +1,412 @@
//! x86-64 macOS recovery images, from osrecovery.apple.com, as a Mac's Internet Recovery fetches
//! them.
//!
//! The exchange, as macrecovery does it (OpenCorePkg's Utilities/macrecovery, BSD-3-Clause):
//! 1. `GET http://osrecovery.apple.com/` with the `InternetRecovery/1.0` user agent sets a
//! `session` cookie.
//! 2. `POST /InstallationPayload/RecoveryImage` with that cookie and a body of `key=value` lines
//! (a random client ID `cid`, the logic board serial `sn`, the board ID `bid`, random `k` and
//! `fg`, and `os`) answers `key: value` lines: the product (`AP`), the image's URL (`AU`) and
//! asset token (`AT`), and its chunklist's (`CU`, `CT`).
//! 3. Each file is fetched with the cookie `AssetToken=<token>`; a token lasts about 45 minutes,
//! and a refused request asks for a new one.
//!
//! A board ID with an all-zero serial gets the newest recovery that board runs, so each version
//! below names the board of a Mac whose last macOS it is. Every image here is x86-64: these are
//! Intel Macs' boards.
//!
//! The image is `BaseSystem.dmg`, checked chunk by chunk against its chunklist, whose RSA
//! signature is Apple's (chunklist.rs): both come over plain HTTP.
//!
//! It is the online installer as it is ([`online_installer`]): reims-ctl takes a DMG and
//! converts it, and a VM boots it into Recovery, whose Reinstall macOS downloads the newest
//! release of its macOS. The offline installer boots it too (installer.rs).
use crate::chunklist::{ChunkCheck, Chunklist, Signature};
use crate::http::{self, Dest, Download, Headers};
use crate::progress::Reporter;
use anyhow::{Context, Result, bail, ensure};
use std::path::{Path, PathBuf};
use ureq::Agent;
const SERVER: &str = "http://osrecovery.apple.com";
const USER_AGENT: &str = "InternetRecovery/1.0";
const MLB_ZERO: &str = "00000000000000000";
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Version {
pub name: &'static str,
pub number: &'static str,
/// Its name in file names and on the command line: "tahoe".
pub slug: &'static str,
pub board_id: &'static str,
pub mlb: &'static str,
pub os: &'static str,
}
impl Version {
pub fn title(&self) -> String {
format!("macOS {} {}", self.name, self.number)
}
pub fn online_installer_name(&self) -> String {
format!("macOS-{}-online-installer.dmg", self.name.replace(' ', "-"))
}
}
/// Newest first. The board IDs and serials are macrecovery's (its recovery_urls.txt), whose
/// authors found which board gets which recovery.
pub const VERSIONS: &[Version] = &[
Version {
name: "Tahoe",
number: "26",
slug: "tahoe",
board_id: "Mac-CFF7D910A743CAAF",
mlb: MLB_ZERO,
os: "latest",
},
Version {
name: "Sequoia",
number: "15",
slug: "sequoia",
board_id: "Mac-7BA5B2D9E42DDD94",
mlb: MLB_ZERO,
os: "default",
},
Version {
name: "Sonoma",
number: "14",
slug: "sonoma",
board_id: "Mac-827FAC58A8FDFA22",
mlb: MLB_ZERO,
os: "default",
},
Version {
name: "Ventura",
number: "13",
slug: "ventura",
board_id: "Mac-B4831CEBD52A0C4C",
mlb: MLB_ZERO,
os: "default",
},
Version {
name: "Monterey",
number: "12",
slug: "monterey",
board_id: "Mac-E43C1C25D4880AD6",
mlb: MLB_ZERO,
os: "default",
},
Version {
name: "Big Sur",
number: "11",
slug: "big-sur",
board_id: "Mac-2BD1B31983FE1663",
mlb: MLB_ZERO,
os: "default",
},
Version {
name: "Catalina",
number: "10.15",
slug: "catalina",
board_id: "Mac-00BE6ED71E35EB86",
mlb: MLB_ZERO,
os: "default",
},
Version {
name: "Mojave",
number: "10.14",
slug: "mojave",
board_id: "Mac-7BA5B2DFE22DDD8C",
mlb: "00000000000KXPG00",
os: "default",
},
Version {
name: "High Sierra",
number: "10.13",
slug: "high-sierra",
board_id: "Mac-7BA5B2D9E42DDD94",
mlb: "00000000000J80300",
os: "default",
},
];
/// A version by its slug, name or number: "tahoe", "Big Sur", "26", "10.15", or "latest".
pub fn find(s: &str) -> Option<&'static Version> {
let s = s.trim().to_ascii_lowercase();
if s == "latest" {
return VERSIONS.first();
}
let s = s.strip_prefix("macos").unwrap_or(&s).trim().to_string();
VERSIONS.iter().find(|v| {
v.slug == s
|| v.name.to_ascii_lowercase() == s
|| v.number == s
|| v.slug.replace('-', "") == s.replace([' ', '-'], "")
})
}
#[derive(Debug, PartialEq)]
pub struct ImageInfo {
pub product: String,
pub image_url: String,
pub image_token: String,
pub chunklist_url: String,
pub chunklist_token: String,
}
fn session(agent: &Agent) -> Result<String> {
let resp = agent
.get(&format!("{SERVER}/"))
.config()
.user_agent(USER_AGENT)
.build()
.call()
.context("connect to osrecovery.apple.com")?;
for v in resp.headers().get_all("set-cookie") {
if let Ok(v) = v.to_str()
&& let Some(c) = v
.split(';')
.map(str::trim)
.find(|c| c.starts_with("session="))
{
return Ok(c.to_string());
}
}
bail!("osrecovery.apple.com set no session cookie")
}
fn random_hex(n: usize) -> Result<String> {
let mut b = vec![0u8; n.div_ceil(2)];
getrandom::fill(&mut b).map_err(|e| anyhow::anyhow!("random: {e}"))?;
let mut s: String = b.iter().map(|x| format!("{x:02X}")).collect();
s.truncate(n);
Ok(s)
}
pub fn image_info(agent: &Agent, v: &Version) -> Result<ImageInfo> {
let session = session(agent)?;
let body = format!(
"cid={}\nsn={}\nbid={}\nk={}\nfg={}\nos={}",
random_hex(16)?,
v.mlb,
v.board_id,
random_hex(64)?,
random_hex(64)?,
v.os
);
let mut resp = agent
.post(&format!("{SERVER}/InstallationPayload/RecoveryImage"))
.header("Cookie", &session)
.header("Content-Type", "text/plain")
.config()
.user_agent(USER_AGENT)
.build()
.send(body)
.context("ask osrecovery.apple.com for the image")?;
let status = resp.status().as_u16();
let text = resp
.body_mut()
.with_config()
.limit(1 << 16)
.read_to_string()?;
if status != 200 {
bail!(
"osrecovery.apple.com answered HTTP {status} for {}",
v.title()
);
}
parse_info(&text)
}
fn parse_info(text: &str) -> Result<ImageInfo> {
let get = |k: &str| -> Result<String> {
text.lines()
.filter_map(|l| l.split_once(": "))
.find(|(key, _)| key.trim() == k)
.map(|(_, v)| v.trim().to_string())
.with_context(|| format!("osrecovery.apple.com's answer has no {k}"))
};
Ok(ImageInfo {
product: get("AP")?,
image_url: get("AU")?,
image_token: get("AT")?,
chunklist_url: get("CU")?,
chunklist_token: get("CT")?,
})
}
fn asset_headers(token: &str) -> Headers {
vec![("Cookie".to_string(), format!("AssetToken={token}"))]
}
/// A version's recovery image as Apple serves it now: its product, and its chunklist, whose
/// signature is checked, and which gives the image's size.
pub struct Image {
agent: Agent,
version: Version,
pub product: String,
info: ImageInfo,
pub chunklist: Vec<u8>,
list: Chunklist,
}
/// Asks Apple for `v`'s recovery image.
pub fn ask(v: &Version, r: &dyn Reporter) -> Result<Image> {
let agent = http::agent();
r.step(&format!(
"Asking Apple for the {} recovery image",
v.title()
));
let info = image_info(&agent, v)?;
r.note(&format!("Apple's product {}", info.product));
let chunklist = get_with_ua(
&agent,
&info.chunklist_url,
&asset_headers(&info.chunklist_token),
)?;
let list = Chunklist::parse(&chunklist).context("the recovery image's chunklist")?;
ensure!(
list.signature == Signature::Rsa,
"the recovery image's chunklist is not signed"
);
Ok(Image {
agent,
version: *v,
product: info.product.clone(),
info,
chunklist,
list,
})
}
impl Image {
pub fn size(&self) -> u64 {
self.list.total()
}
pub fn check(&self) -> ChunkCheck {
ChunkCheck::new(self.list.clone())
}
/// Downloads the image to `dest`, checked by `check` (from [`Image::check`]). An asset token
/// that runs out on the way is renewed, as long as Apple still serves the same image.
pub fn download(&self, dest: Dest, check: &mut ChunkCheck, r: &dyn Reporter) -> Result<()> {
let v = self.version;
let image_path = url_path(&self.info.image_url).to_string();
let mut refresh = || -> Result<Headers> {
let fresh = image_info(&self.agent, &v)?;
ensure!(
url_path(&fresh.image_url) == image_path,
"Apple now serves a different {} recovery ({}): run again to start over",
v.title(),
fresh.product
);
Ok(asset_headers(&fresh.image_token))
};
let d = Download {
url: self.info.image_url.clone(),
step: format!("Downloading the {} recovery image", v.title()),
headers: asset_headers(&self.info.image_token),
size: Some(self.size()),
refresh: Some(&mut refresh),
user_agent: Some(USER_AGENT),
};
http::download(&self.agent, d, dest, check, r)
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct Outputs {
pub title: String,
pub product: String,
pub image: PathBuf,
}
/// Makes `v`'s online installer in `dir`: its recovery image, as
/// `macOS-<name>-online-installer.dmg`. A previous run's download is continued; an image already
/// there is checked, kept if it is Apple's current one, and repaired or replaced if not.
pub fn online_installer(v: &Version, dir: &Path, r: &dyn Reporter) -> Result<Outputs> {
let image = ask(v, r)?;
let path = dir.join(v.online_installer_name());
let mut check = image.check();
let out = Outputs {
title: v.title(),
product: image.product.clone(),
image: path.clone(),
};
if path.exists() {
if verify_whole(&path, &mut check, r)? {
r.note(&format!(
"{} is already here and checks out",
path.display()
));
return Ok(out);
}
// Continued from its last good chunk, which for another product is none.
std::fs::rename(&path, http::part_path(&path))
.with_context(|| format!("rename {}", path.display()))?;
}
image.download(Dest::File(&path), &mut check, r)?;
Ok(out)
}
fn get_with_ua(agent: &Agent, url: &str, headers: &Headers) -> Result<Vec<u8>> {
let mut req = agent.get(url);
for (k, v) in headers {
req = req.header(k, v);
}
let mut resp = req.config().user_agent(USER_AGENT).build().call()?;
let status = resp.status().as_u16();
if status != 200 {
bail!("{url} answered HTTP {status}");
}
Ok(resp
.body_mut()
.with_config()
.limit(16 << 20)
.read_to_vec()?)
}
/// Checks a whole file against `check`; leaves `check` ready for a fresh download either way.
fn verify_whole(path: &Path, check: &mut ChunkCheck, r: &dyn Reporter) -> Result<bool> {
use crate::http::Check;
let mut f = std::fs::File::open(path)?;
let len = f.metadata()?.len();
let good = check.resume(&mut f, 0, len, r)?;
check.restart_at(0);
Ok(good == len && len == check.total())
}
fn url_path(url: &str) -> &str {
url.split(['?', '#']).next().unwrap_or(url)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_versions_by_any_name() {
assert_eq!(find("tahoe").map(|v| v.number), Some("26"));
assert_eq!(find("Big Sur").map(|v| v.slug), Some("big-sur"));
assert_eq!(find("bigsur").map(|v| v.slug), Some("big-sur"));
assert_eq!(find("macOS Sonoma").map(|v| v.number), Some("14"));
assert_eq!(find("10.15").map(|v| v.name), Some("Catalina"));
assert_eq!(find("latest").map(|v| v.name), Some("Tahoe"));
assert_eq!(find("27"), None);
}
#[test]
fn parses_the_servers_answer() {
let text = "AP: 140-93589\nAU: http://oscdn.apple.com/x/BaseSystem.dmg\nAH: 17F6\n\
AT: expires=1~access=/x~md5=3\nCU: http://oscdn.apple.com/x/BaseSystem.chunklist\n\
CH: 6286\nCT: expires=1~access=/y~md5=e\n";
let info = parse_info(text).unwrap();
assert_eq!(info.product, "140-93589");
assert_eq!(info.image_url, "http://oscdn.apple.com/x/BaseSystem.dmg");
assert_eq!(info.image_token, "expires=1~access=/x~md5=3");
assert_eq!(info.chunklist_token, "expires=1~access=/y~md5=e");
assert!(parse_info("AP: 1\n").is_err());
}
}
+843
View File
@@ -0,0 +1,843 @@
//! The interactive interface: [`HEIGHT`] lines drawn below the prompt, not a full screen, with
//! the keys on the last. Each finished job prints what it wrote, or why it failed, above them,
//! into the terminal's scrollback, where it stays after reims-util exits.
//!
//! A job runs on a thread of its own and reports through a channel (progress.rs); stopping one
//! (Esc) lets a download end between reads, so starting it again resumes it, and Esc again
//! leaves without waiting for that.
use crate::cli::{self, OpencoreArgs};
use crate::installer::Installer;
use crate::opencore::{config, smbios};
use crate::progress::{self, Event, Rate, Reporter};
use crate::{installer, opencore, recovery};
use anyhow::Result;
use ratatui::crossterm::event::{
self, Event as TermEvent, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style, Stylize};
use ratatui::text::{Line, Span};
use ratatui::widgets::{LineGauge, Paragraph, Wrap};
use ratatui::{DefaultTerminal, Frame, TerminalOptions, Viewport};
use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
const HEIGHT: u16 = 13;
pub fn run() -> Result<()> {
let mut terminal = ratatui::try_init_with_options(TerminalOptions {
viewport: Viewport::Inline(HEIGHT),
})?;
let result = App::new().run(&mut terminal);
// Leave the scrollback as the jobs wrote it: the interface goes.
let _ = terminal.clear();
let top = terminal.get_frame().area().as_position();
let _ = terminal.set_cursor_position(top);
ratatui::restore();
result
}
const MENU: &[(&str, &str)] = &[
(
"Make an OpenCore boot image",
"OpenCore 1.0.8 for a q35 VM on KVM, with a Mac identity of its own, and OVMF's \
OVMF_CODE.fd and OVMF_VARS.fd beside it, where reims-ctl finds them.",
),
(
"Make an online installer",
"Apple's recovery image for macOS 10.13 to 26, about 1 GB. A VM boots it, and Recovery's \
Reinstall macOS downloads and installs the newest release of that macOS.",
),
(
"Make an offline installer",
"A disk image with the whole installer for one exact release of macOS 11 to 26, 13 to 20 \
GB. A VM boots it, and installs that release from it with no network.",
),
];
enum Screen {
Menu(usize),
Form(Job, Form),
Running(Running),
}
#[derive(Clone)]
enum Job {
OpenCore,
Online,
Offline(Vec<Installer>),
}
enum Msg {
Event(Event),
/// A finished job: the lines to keep in the scrollback, or the error.
Done(std::result::Result<Vec<Line<'static>>, String>),
Catalog(std::result::Result<Vec<Installer>, String>),
}
struct Running {
title: String,
step: String,
progress: Option<(u64, Option<u64>)>,
rate: Rate,
notes: VecDeque<String>,
cancel: Arc<AtomicBool>,
rx: Receiver<Msg>,
}
struct ChannelReporter {
tx: Sender<Msg>,
cancel: Arc<AtomicBool>,
}
impl Reporter for ChannelReporter {
fn event(&self, e: Event) {
let _ = self.tx.send(Msg::Event(e));
}
fn cancelled(&self) -> bool {
self.cancel.load(Ordering::Relaxed)
}
}
struct App {
screen: Screen,
/// The line under the box: the last job's outcome.
status: Option<(String, bool)>,
quit: bool,
}
impl App {
fn new() -> App {
App {
screen: Screen::Menu(0),
status: None,
quit: false,
}
}
fn run(&mut self, t: &mut DefaultTerminal) -> Result<()> {
while !self.quit {
t.draw(|f| self.draw(f))?;
if event::poll(Duration::from_millis(100))?
&& let TermEvent::Key(k) = event::read()?
&& k.kind != KeyEventKind::Release
{
self.key(k);
}
self.drain(t)?;
}
Ok(())
}
fn drain(&mut self, t: &mut DefaultTerminal) -> Result<()> {
let Screen::Running(r) = &mut self.screen else {
return Ok(());
};
let mut finished = None;
while let Ok(m) = r.rx.try_recv() {
match m {
Msg::Event(Event::Step { message }) => {
r.step = message;
r.progress = None;
r.rate = Rate::default();
}
Msg::Event(Event::Progress { done, total }) => {
r.rate.add(done);
r.progress = Some((done, total));
}
Msg::Event(Event::Note { message }) => {
r.notes.push_back(message);
while r.notes.len() > 3 {
r.notes.pop_front();
}
}
Msg::Done(d) => finished = Some(Ok(d)),
Msg::Catalog(c) => finished = Some(Err(c)),
}
}
match finished {
None => {}
Some(Ok(Ok(lines))) => {
print_above(t, lines)?;
self.status = Some(("Done: what it wrote is above.".into(), false));
self.screen = Screen::Menu(0);
}
Some(Ok(Err(e))) | Some(Err(Err(e))) => {
if r.cancel.load(Ordering::Relaxed) {
self.status = Some(("Stopped. Start it again to resume.".into(), false));
} else {
// Above, where it's wrapped whole: an error often starts with a long URL.
let red = Style::new().fg(Color::Red);
print_above(
t,
vec![
Line::styled(format!("Failed: {}", r.title), red.bold()),
Line::styled(format!(" {e}"), red),
],
)?;
self.status = Some(("Failed: why is above.".into(), true));
}
self.screen = Screen::Menu(0);
}
Some(Err(Ok(list))) => {
let form = offline_form(&list);
self.screen = Screen::Form(Job::Offline(list), form);
}
}
Ok(())
}
fn key(&mut self, k: KeyEvent) {
let ctrl_c = k.modifiers.contains(KeyModifiers::CONTROL) && k.code == KeyCode::Char('c');
match &mut self.screen {
Screen::Menu(i) => match k.code {
_ if ctrl_c => self.quit = true,
KeyCode::Char('q') | KeyCode::Esc => self.quit = true,
KeyCode::Up | KeyCode::Char('k') => *i = i.checked_sub(1).unwrap_or(MENU.len() - 1),
KeyCode::Down | KeyCode::Char('j') | KeyCode::Tab => *i = (*i + 1) % MENU.len(),
KeyCode::Char(c @ '1'..='3') => self.open(c as usize - '1' as usize),
KeyCode::Enter => {
let i = *i;
self.open(i);
}
_ => {}
},
Screen::Form(job, form) => {
if ctrl_c || k.code == KeyCode::Esc {
self.screen = Screen::Menu(match job {
Job::OpenCore => 0,
Job::Online => 1,
Job::Offline(_) => 2,
});
} else if k.code == KeyCode::Enter {
let (job, form) = (job.clone(), form.clone());
self.start(job, &form);
} else {
form.key(k);
}
}
Screen::Running(r) => {
if ctrl_c || matches!(k.code, KeyCode::Esc | KeyCode::Char('q')) {
if r.cancel.swap(true, Ordering::Relaxed) {
// A second press leaves at once, for a download stalled in a read that
// only its time budget ends; it resumes next time.
self.quit = true;
}
r.step = "Stopping… (press Esc again to leave now)".into();
}
}
}
}
fn open(&mut self, i: usize) {
self.status = None;
match i {
0 => self.screen = Screen::Form(Job::OpenCore, opencore_form()),
1 => self.screen = Screen::Form(Job::Online, online_form()),
_ => self.spawn("Offline installers".into(), |r, tx| {
let _ = tx.send(Msg::Catalog(
installer::list(r).map_err(|e| format!("{e:#}")),
));
}),
}
}
fn start(&mut self, job: Job, form: &Form) {
match job {
Job::OpenCore => {
let a = OpencoreArgs {
output: expand(&form.text(0)),
model: form.choice(1).to_string(),
serial: None,
mlb: None,
uuid: None,
rom: None,
timeout: match form.text(2).trim().parse() {
Ok(t) => t,
Err(_) => {
self.status =
Some(("The picker timeout is a number of seconds.".into(), true));
return;
}
},
boot_args: config::DEFAULT_BOOT_ARGS.into(),
verbose_boot: form.toggle(6),
disable_sip: !form.toggle(4),
no_cpuid_spoof: false,
show_vm: !form.toggle(5),
no_ovmf: !form.toggle(3),
ovmf_dir: None,
};
let o = match cli::opencore_options(&a) {
Ok(o) => o,
Err(e) => {
self.status = Some((format!("{e:#}"), true));
return;
}
};
self.spawn("OpenCore boot image".into(), move |r, tx| {
let res = opencore::build(&o, r).map(|out| opencore_lines(&out));
let _ = tx.send(Msg::Done(res.map_err(|e| format!("{e:#}"))));
});
}
Job::Online => {
let Some(v) = recovery::VERSIONS.get(form.choice_index(0)).copied() else {
return;
};
let dir = expand(&form.text(1));
self.spawn(format!("{} online installer", v.title()), move |r, tx| {
let res = recovery::online_installer(&v, &dir, r).map(|out| {
vec![
ok_line(&format!(
"{} online installer (Apple's product {})",
out.title, out.product
)),
detail("Installer", &abs(&out.image)),
next_line(&format!(
"reims-ctl create mac --opencore OpenCore.qcow2 --installer {}",
shell(&abs(&out.image))
)),
detail(
"Then",
"in Recovery, erase the VM's disk in Disk Utility (APFS) and \
pick Reinstall macOS",
),
]
});
let _ = tx.send(Msg::Done(res.map_err(|e| format!("{e:#}"))));
});
}
Job::Offline(list) => {
let Some(inst) = list.get(form.choice_index(0)).cloned() else {
return;
};
let dir = expand(&form.text(1));
self.spawn(
format!("{} offline installer", inst.label()),
move |r, tx| {
let res = installer::offline_installer(&inst, &dir, r)
.map(|out| offline_lines(&out));
let _ = tx.send(Msg::Done(res.map_err(|e| format!("{e:#}"))));
},
);
}
}
}
fn spawn(
&mut self,
title: String,
work: impl FnOnce(&ChannelReporter, &Sender<Msg>) + Send + 'static,
) {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
let reporter = ChannelReporter {
tx: tx.clone(),
cancel: cancel.clone(),
};
std::thread::spawn(move || work(&reporter, &tx));
self.screen = Screen::Running(Running {
title,
step: "Starting".into(),
progress: None,
rate: Rate::default(),
notes: VecDeque::new(),
cancel,
rx,
});
}
fn draw(&self, f: &mut Frame) {
let [main, status, keys_row] = Layout::vertical([
Constraint::Min(3),
Constraint::Length(1),
Constraint::Length(1),
])
.areas(f.area());
// The menu needs no title: the prompt above it says reims-util.
let (title, keys) = match &self.screen {
Screen::Menu(_) => (None, " ↑↓ choose · Enter open · q quit"),
Screen::Form(_, form) => (
Some(form.title.as_str()),
" ↑↓ field · ←→ or Space change · Enter start · Esc back",
),
Screen::Running(r) => (
Some(r.title.as_str()),
" Esc stop (a download resumes when started again)",
),
};
let main = match title {
Some(t) => {
let [head, rest] =
Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).areas(main);
f.render_widget(
Paragraph::new(Line::styled(
format!(" {t}"),
Style::new().fg(Color::Cyan).add_modifier(Modifier::BOLD),
)),
head,
);
rest
}
None => main,
};
match &self.screen {
Screen::Menu(i) => draw_menu(f, main, *i),
Screen::Form(_, form) => form.draw(f, main),
Screen::Running(r) => draw_running(f, main, r),
}
f.render_widget(Paragraph::new(Line::from(keys).dim()), keys_row);
if let Some((s, err)) = &self.status {
let style = if *err {
Style::new().fg(Color::Red)
} else {
Style::new().fg(Color::Green)
};
f.render_widget(Paragraph::new(Line::styled(format!(" {s}"), style)), status);
}
}
}
fn draw_menu(f: &mut Frame, area: Rect, index: usize) {
let mut lines: Vec<Line> = MENU
.iter()
.enumerate()
.map(|(i, (label, _))| {
if i == index {
Line::from(vec![
Span::styled(" ▸ ", Style::new().fg(Color::Cyan)),
Span::styled(*label, Style::new().bold()),
])
} else {
Line::from(format!(" {label}"))
}
})
.collect();
lines.push(Line::default());
let [list, help] =
Layout::vertical([Constraint::Length(lines.len() as u16), Constraint::Min(1)]).areas(area);
f.render_widget(Paragraph::new(lines), list);
f.render_widget(
Paragraph::new(MENU[index].1)
.wrap(Wrap { trim: true })
.dim(),
help.inner(ratatui::layout::Margin::new(1, 0)),
);
}
fn draw_running(f: &mut Frame, area: Rect, r: &Running) {
let area = area.inner(ratatui::layout::Margin::new(1, 0));
let [step, gauge, _, notes] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Length(1),
Constraint::Min(0),
])
.areas(area);
f.render_widget(Paragraph::new(Line::from(r.step.as_str()).bold()), step);
if let Some((done, total)) = r.progress {
let label = progress::progress_line(done, total, r.rate.per_second());
let ratio = match total {
Some(t) if t > 0 => (done as f64 / t as f64).clamp(0.0, 1.0),
_ => 0.0,
};
f.render_widget(
LineGauge::default()
.filled_style(Style::new().fg(Color::Cyan))
.unfilled_style(Style::new().fg(Color::DarkGray))
.label(label)
.ratio(ratio),
gauge,
);
}
let lines: Vec<Line> = r
.notes
.iter()
.map(|n| Line::from(n.as_str()).dim())
.collect();
f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), notes);
}
#[derive(Clone)]
struct Form {
title: String,
fields: Vec<Field>,
focus: usize,
}
#[derive(Clone)]
struct Field {
label: &'static str,
help: String,
kind: Kind,
}
#[derive(Clone)]
enum Kind {
/// The text, and what shows dim while it is empty.
Text(String, &'static str),
Choice(Vec<String>, usize),
Toggle(bool),
}
impl Form {
fn text(&self, i: usize) -> String {
match &self.fields[i].kind {
Kind::Text(s, _) => s.clone(),
_ => String::new(),
}
}
fn choice_index(&self, i: usize) -> usize {
match &self.fields[i].kind {
Kind::Choice(_, n) => *n,
_ => 0,
}
}
fn choice(&self, i: usize) -> &str {
match &self.fields[i].kind {
Kind::Choice(o, n) => o[*n].split(' ').next().unwrap_or(""),
_ => "",
}
}
fn toggle(&self, i: usize) -> bool {
matches!(self.fields[i].kind, Kind::Toggle(true))
}
fn key(&mut self, k: KeyEvent) {
let n = self.fields.len();
match k.code {
KeyCode::Up | KeyCode::BackTab => self.focus = (self.focus + n - 1) % n,
KeyCode::Down | KeyCode::Tab => self.focus = (self.focus + 1) % n,
_ => match &mut self.fields[self.focus].kind {
Kind::Text(s, _) => match k.code {
KeyCode::Backspace => {
s.pop();
}
KeyCode::Char('u') if k.modifiers.contains(KeyModifiers::CONTROL) => s.clear(),
KeyCode::Char(c) if !k.modifiers.contains(KeyModifiers::CONTROL) => s.push(c),
_ => {}
},
Kind::Choice(o, i) => match k.code {
KeyCode::Left | KeyCode::Char('h') => *i = (*i + o.len() - 1) % o.len(),
KeyCode::Right | KeyCode::Char('l') | KeyCode::Char(' ') => {
*i = (*i + 1) % o.len()
}
KeyCode::Home => *i = 0,
KeyCode::End => *i = o.len() - 1,
_ => {}
},
Kind::Toggle(b) => {
if matches!(k.code, KeyCode::Left | KeyCode::Right | KeyCode::Char(' ')) {
*b = !*b;
}
}
},
}
}
fn draw(&self, f: &mut Frame, area: Rect) {
let area = area.inner(ratatui::layout::Margin::new(1, 0));
let width = self.fields.iter().map(|x| x.label.len()).max().unwrap_or(0) + 2;
let mut lines: Vec<Line> = Vec::new();
for (i, field) in self.fields.iter().enumerate() {
let focused = i == self.focus;
let value = match &field.kind {
Kind::Text(s, _) if focused => format!("{s}▏"),
Kind::Text(s, _) => s.clone(),
Kind::Choice(o, n) if focused => format!("◂ {} ▸", o[*n]),
Kind::Choice(o, n) => o[*n].clone(),
Kind::Toggle(b) => if *b { "[x] yes" } else { "[ ] no" }.to_string(),
};
let label = format!("{:<width$}", field.label);
let mut line = if focused {
Line::from(vec![
Span::styled(label, Style::new().fg(Color::Cyan).bold()),
Span::styled(value, Style::new().bold()),
])
} else {
Line::from(vec![Span::raw(label).dim(), Span::raw(value)])
};
if let Kind::Text(s, placeholder) = &field.kind
&& s.is_empty()
{
line.push_span(Span::raw(*placeholder).dim());
}
lines.push(line);
}
let [list, _, help] = Layout::vertical([
Constraint::Length(lines.len() as u16),
Constraint::Length(1),
Constraint::Min(1),
])
.areas(area);
f.render_widget(Paragraph::new(lines), list);
f.render_widget(
Paragraph::new(self.fields[self.focus].help.as_str())
.wrap(Wrap { trim: true })
.dim(),
help,
);
}
}
fn cwd() -> String {
std::env::current_dir()
.map(|d| d.display().to_string())
.unwrap_or_else(|_| ".".into())
}
fn opencore_form() -> Form {
Form {
title: "Make an OpenCore boot image".into(),
focus: 0,
fields: vec![
Field {
label: "Save as",
help: format!(
"The image: qcow2 for a .qcow2 name, else a raw disk image. A relative path is \
from {}.",
cwd()
),
kind: Kind::Text("OpenCore.qcow2".into(), ""),
},
Field {
label: "Mac model",
help: format!(
"The Mac the VM claims to be, and the macOS releases it runs: {}.",
smbios::MODELS
.iter()
.map(|m| format!("{}, {}", m.name, m.runs))
.collect::<Vec<_>>()
.join("; ")
),
kind: Kind::Choice(
smbios::MODELS
.iter()
.map(|m| format!("{} ({})", m.name, m.runs))
.collect(),
0,
),
},
Field {
label: "Picker timeout",
help: "Seconds OpenCore's boot picker waits before it boots the default entry; \
0 waits for you."
.into(),
kind: Kind::Text("5".into(), ""),
},
Field {
label: "Write OVMF",
help: format!(
"Write OVMF_CODE.fd and OVMF_VARS.fd (Arch Linux's {}) beside the image, \
where reims-ctl finds them.",
crate::ovmf::VERSION
),
kind: Kind::Toggle(true),
},
Field {
label: "SIP on",
help: "System Integrity Protection. Leave it on unless you need it off.".into(),
kind: Kind::Toggle(true),
},
Field {
label: "Hide the VM",
help: "Keep macOS from seeing it runs in a VM, so iCloud and the App Store let \
you sign in."
.into(),
kind: Kind::Toggle(true),
},
Field {
label: "Verbose boot",
help: "Show the kernel's messages while macOS boots, instead of the Apple logo."
.into(),
kind: Kind::Toggle(false),
},
],
}
}
fn online_form() -> Form {
Form {
title: "Make an online installer".into(),
focus: 0,
fields: vec![
Field {
label: "Version",
help: "The newest recovery Apple serves for it, which installs the newest release \
of that macOS over the network."
.into(),
kind: Kind::Choice(recovery::VERSIONS.iter().map(|v| v.title()).collect(), 0),
},
Field {
label: "Save to",
help: format!(
"The folder for macOS-<name>-online-installer.dmg: empty for the current \
directory, {}, which a relative path is from too.",
cwd()
),
kind: Kind::Text(String::new(), "current directory"),
},
],
}
}
fn offline_form(list: &[Installer]) -> Form {
Form {
title: "Make an offline installer".into(),
focus: 0,
fields: vec![
Field {
label: "Version",
help: format!(
"{} releases run on Intel Macs, newest first; Home and End jump to the ends. \
The image is about the size given.",
list.len()
),
kind: Kind::Choice(
list.iter()
.map(|i| {
format!(
"{}, {}, posted {}",
i.label(),
progress::bytes(i.size),
i.posted
)
})
.collect(),
0,
),
},
Field {
label: "Save to",
help: format!(
"The folder for macOS-<name>-<version>-<build>-offline-installer.img: empty \
for the current directory, {}, which a relative path is from too.",
cwd()
),
kind: Kind::Text(String::new(), "current directory"),
},
],
}
}
fn offline_lines(out: &installer::Outputs) -> Vec<Line<'static>> {
let mut v = vec![
ok_line(&format!("{} offline installer", out.installer.label())),
detail("Installer", &abs(&out.image)),
];
v.push(next_line(&format!(
"reims-ctl create mac --opencore OpenCore.qcow2 --installer {}",
shell(&abs(&out.image))
)));
v.push(detail(
"Then",
"in Recovery, erase the VM's disk in Disk Utility (APFS), and in Utilities > Terminal run",
));
v.push(command_line("", installer::IMAGE_COMMAND));
v
}
fn opencore_lines(out: &opencore::Outputs) -> Vec<Line<'static>> {
let mut v = vec![
ok_line(&format!("OpenCore {} boot image", out.opencore)),
detail("Image", &abs(&out.image)),
];
if let Some(o) = &out.ovmf {
v.push(detail("OVMF", &abs(&o.code)));
v.push(detail("", &abs(&o.vars)));
}
let s = &out.smbios;
v.push(detail(
"Identity",
&format!(
"{}, serial {}, MLB {}, UUID {}, ROM {}",
s.model, s.serial, s.mlb, s.uuid, s.rom
),
));
// The newest macOS the model runs.
let name = if s.model == "iMac20,1" {
"Tahoe"
} else {
"Sequoia"
};
v.push(next_line(&format!(
"reims-ctl create mac --opencore {} --installer macOS-{name}-online-installer.dmg",
shell(&abs(&out.image))
)));
v
}
fn ok_line(s: &str) -> Line<'static> {
Line::from(vec![
Span::styled("✓ ", Style::new().fg(Color::Green).bold()),
Span::styled(s.to_string(), Style::new().bold()),
])
}
fn detail(label: &str, value: &str) -> Line<'static> {
Line::from(vec![
Span::raw(format!(" {label:<10}")).dim(),
Span::raw(value.to_string()),
])
}
fn next_line(cmd: &str) -> Line<'static> {
command_line("Next", cmd)
}
fn command_line(label: &str, cmd: &str) -> Line<'static> {
Line::from(vec![
Span::raw(format!(" {label:<10}")).dim(),
Span::styled(cmd.to_string(), Style::new().fg(Color::Cyan)),
])
}
/// Prints `lines` above the box, into the scrollback, wrapping long ones.
fn print_above(t: &mut DefaultTerminal, lines: Vec<Line<'static>>) -> Result<()> {
let width = t.size()?.width.max(20);
let p = Paragraph::new(lines).wrap(Wrap { trim: false });
// Rows as the paragraph wraps them, at word boundaries.
let height = p.line_count(width) as u16 + 1;
t.insert_before(height, |buf| {
use ratatui::widgets::Widget;
let area = Rect::new(0, 0, buf.area.width, height - 1);
p.render(area, buf);
})?;
Ok(())
}
/// `~/x` as `$HOME/x`.
fn expand(s: &str) -> PathBuf {
let s = s.trim();
match (s.strip_prefix("~/"), std::env::var_os("HOME")) {
(Some(rest), Some(home)) => PathBuf::from(home).join(rest),
_ if s == "~" => std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_default(),
_ if s.is_empty() => PathBuf::from("."),
_ => PathBuf::from(s),
}
}
fn abs(p: &Path) -> String {
std::path::absolute(p)
.unwrap_or_else(|_| p.to_path_buf())
.display()
.to_string()
}
/// A path as a shell word.
fn shell(s: &str) -> String {
if s.chars()
.all(|c| c.is_ascii_alphanumeric() || "/._-+,:@%".contains(c))
{
s.to_string()
} else {
format!("'{}'", s.replace('\'', r"'\''"))
}
}