summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.github/workflows/build.yml186
-rw-r--r--.gitignore39
-rw-r--r--COPYING502
-rw-r--r--LICENSE674
-rw-r--r--Makefile37
-rw-r--r--Makefile.am14
-rw-r--r--NEWS124
-rw-r--r--README22
-rw-r--r--README.md258
-rw-r--r--TODO15
-rwxr-xr-xautogen.sh26
-rw-r--r--configure.ac230
-rwxr-xr-xgit-version-gen20
-rw-r--r--include/Makefile.am1
-rw-r--r--include/libirecovery.h240
-rw-r--r--m4/as-compiler-flag.m462
-rw-r--r--scripts/boot.irs5
-rw-r--r--scripts/test.irs21
-rw-r--r--src/Makefile.am24
-rw-r--r--src/irecovery.c355
-rw-r--r--src/libirecovery-1.0.pc.in11
-rw-r--r--src/libirecovery.c3828
-rw-r--r--tools/Makefile.am13
-rw-r--r--tools/irecovery.c707
-rw-r--r--udev/39-libirecovery.rules.in8
-rw-r--r--udev/Makefile.am21
26 files changed, 5979 insertions, 1464 deletions
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..9d36f2a
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,186 @@
+name: build
+
+on:
+ push:
+ schedule:
+ - cron: '0 0 1 * *'
+
+jobs:
+ build-linux-ubuntu:
+ runs-on: ubuntu-latest
+ steps:
+ - name: install dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install libusb-1.0-0-dev
+ - name: prepare environment
+ run: |
+ echo "target_triplet=`gcc -dumpmachine`" >> $GITHUB_ENV
+ - name: fetch libplist
+ uses: dawidd6/action-download-artifact@v3
+ with:
+ github_token: ${{secrets.GITHUB_TOKEN}}
+ workflow: build.yml
+ name: libplist-latest_${{env.target_triplet}}
+ repo: libimobiledevice/libplist
+ - name: fetch libimobiledevice-glue
+ uses: dawidd6/action-download-artifact@v3
+ with:
+ github_token: ${{secrets.GITHUB_TOKEN}}
+ workflow: build.yml
+ name: libimobiledevice-glue-latest_${{env.target_triplet}}
+ repo: libimobiledevice/libimobiledevice-glue
+ - name: install external dependencies
+ run: |
+ mkdir extract
+ for I in *.tar; do
+ tar -C extract -xvf $I
+ done
+ sudo cp -r extract/* /
+ sudo ldconfig
+ - uses: actions/checkout@v4
+ - name: autogen
+ run: ./autogen.sh PKG_CONFIG_PATH=/usr/local/lib/pkgconfig LDFLAGS="-Wl,-rpath=/usr/local/lib"
+ - name: make
+ run: make
+ - name: make install
+ run: sudo make install
+ - name: prepare artifact
+ run: |
+ mkdir -p dest
+ DESTDIR=`pwd`/dest make install
+ tar -C dest -cf libirecovery.tar lib usr
+ - name: publish artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: libirecovery-latest_${{env.target_triplet}}
+ path: libirecovery.tar
+ build-macOS:
+ runs-on: macOS-latest
+ steps:
+ - name: install dependencies
+ run: |
+ if test -x "`which port`"; then
+ sudo port install libtool autoconf automake pkgconfig
+ else
+ brew install libtool autoconf automake pkgconfig
+ fi
+ shell: bash
+ - name: fetch libplist
+ uses: dawidd6/action-download-artifact@v3
+ with:
+ github_token: ${{secrets.GITHUB_TOKEN}}
+ workflow: build.yml
+ name: libplist-latest_macOS
+ repo: libimobiledevice/libplist
+ - name: fetch libimobiledevice-glue
+ uses: dawidd6/action-download-artifact@v3
+ with:
+ github_token: ${{secrets.GITHUB_TOKEN}}
+ workflow: build.yml
+ name: libimobiledevice-glue-latest_macOS
+ repo: libimobiledevice/libimobiledevice-glue
+ - name: install external dependencies
+ run: |
+ mkdir extract
+ for I in *.tar; do
+ tar -C extract -xvf $I
+ done
+ sudo cp -r extract/* /
+ - uses: actions/checkout@v4
+ - name: autogen
+ run: |
+ SDKDIR=`xcrun --sdk macosx --show-sdk-path`
+ TESTARCHS="arm64 x86_64"
+ USEARCHS=
+ for ARCH in $TESTARCHS; do
+ if echo "int main(int argc, char **argv) { return 0; }" |clang -arch $ARCH -o /dev/null -isysroot $SDKDIR -x c - 2>/dev/null; then
+ USEARCHS="$USEARCHS -arch $ARCH"
+ fi
+ done
+ export CFLAGS="$USEARCHS -isysroot $SDKDIR"
+ echo "Using CFLAGS: $CFLAGS"
+ ./autogen.sh PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
+ - name: make
+ run: make
+ - name: make install
+ run: sudo make install
+ - name: prepare artifact
+ run: |
+ mkdir -p dest
+ DESTDIR=`pwd`/dest make install
+ tar -C dest -cf libirecovery.tar usr
+ - name: publish artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: libirecovery-latest_macOS
+ path: libirecovery.tar
+ build-windows:
+ runs-on: windows-2019
+ defaults:
+ run:
+ shell: msys2 {0}
+ strategy:
+ fail-fast: false
+ matrix:
+ include: [
+ { msystem: MINGW64, arch: x86_64 },
+ { msystem: MINGW32, arch: i686 }
+ ]
+ steps:
+ - uses: msys2/setup-msys2@v2
+ with:
+ msystem: ${{ matrix.msystem }}
+ release: false
+ update: false
+ install: >-
+ base-devel
+ git
+ mingw-w64-${{ matrix.arch }}-gcc
+ make
+ libtool
+ autoconf
+ automake-wrapper
+ - name: prepare environment
+ run: |
+ dest=`echo ${{ matrix.msystem }} |tr [:upper:] [:lower:]`
+ echo "dest=$dest" >> $GITHUB_ENV
+ echo "target_triplet=`gcc -dumpmachine`" >> $GITHUB_ENV
+ - name: fetch libplist
+ uses: dawidd6/action-download-artifact@v3
+ with:
+ github_token: ${{secrets.GITHUB_TOKEN}}
+ workflow: build.yml
+ name: libplist-latest_${{ matrix.arch }}-${{ env.dest }}
+ repo: libimobiledevice/libplist
+ - name: fetch libimobiledevice-glue
+ uses: dawidd6/action-download-artifact@v3
+ with:
+ github_token: ${{secrets.GITHUB_TOKEN}}
+ workflow: build.yml
+ name: libimobiledevice-glue-latest_${{ matrix.arch }}-${{ env.dest }}
+ repo: libimobiledevice/libimobiledevice-glue
+ - name: install external dependencies
+ run: |
+ mkdir extract
+ for I in *.tar; do
+ tar -C extract -xvf $I
+ done
+ cp -r extract/* /
+ - uses: actions/checkout@v4
+ - name: autogen
+ run: ./autogen.sh CC=gcc CXX=g++
+ - name: make
+ run: make
+ - name: make install
+ run: make install
+ - name: prepare artifact
+ run: |
+ mkdir -p dest
+ DESTDIR=`pwd`/dest make install
+ tar -C dest -cf libirecovery.tar ${{ env.dest }}
+ - name: publish artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: libirecovery-latest_${{ matrix.arch }}-${{ env.dest }}
+ path: libirecovery.tar
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..1b7c628
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,39 @@
+*.[oa]
+*~
+*.po
+*.lo
+*.la
+autom4te.cache/*
+*.in
+*/.deps/*
+m4/*
+*.dll
+*.so
+*.dylib
+*.patch
+aclocal.m4
+config.h
+config.log
+config.sub
+config.guess
+config.status
+configure
+depcomp
+install-sh
+compile
+main
+ltmain.sh
+missing
+mkinstalldirs
+libtool
+*Makefile
+stamp-h1
+src/.libs
+*.pc
+tools/.libs/*
+tools/irecovery
+.irecovery
+udev/39-libirecovery.rules
+.idea
+.vscode
+.DS_Store
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..f166cc5
--- /dev/null
+++ b/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/LICENSE b/LICENSE
deleted file mode 100644
index 20d40b6..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU 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.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>. \ No newline at end of file
diff --git a/Makefile b/Makefile
deleted file mode 100644
index b7f3522..0000000
--- a/Makefile
+++ /dev/null
@@ -1,37 +0,0 @@
-all: linux
- @echo "Please choose either macosx, linux, or windows"
-
-static:
- gcc -o libirecovery.o -c src/libirecovery.c -g -I./include
- ar rs libirecovery.a libirecovery.o
- gcc -o irecovery src/irecovery.c -g -I./include -L. -lirecovery -lreadline -lusb-1.0
-
-linux:
- gcc -o libirecovery.o -c src/libirecovery.c -g -I./include -lreadline -fPIC
- gcc -o libirecovery.so libirecovery.o -g -shared -Wl,-soname,libirecovery.so -lusb-1.0
- gcc -o irecovery src/irecovery.c -g -I./include -L. -lirecovery -lreadline
-
-macosx:
- gcc -o libirecovery.dylib -c src/libirecovery.c -dynamiclib
- gcc -o irecovery src/irecovery.c -I./include -L. -lirecovery -lreadline -lusb-1.0
-
-windows:
- gcc -o libirecovery.dll -c src/libirecovery.c -I. -lusb-1.0 -lreadline -shared -fPIC
- gcc -o irecovery irecovery.c -I. -lirecovery -lreadline
-
-install:
- cp libirecovery.so /usr/local/lib/libirecovery.so
- cp include/libirecovery.h /usr/local/include/libirecovery.h
- cp irecovery /usr/local/bin/irecovery
- ldconfig
-
-uninstall:
- rm -rf /usr/local/lib/libirecovery.so
- rm -rf /usr/local/include/libirecovery.h
- rm -rf /usr/local/bin/irecovery
-
-clean:
- rm -rf irecovery libirecovery.o libirecovery.so libirecovery.a
-
-
-
diff --git a/Makefile.am b/Makefile.am
new file mode 100644
index 0000000..80b0eae
--- /dev/null
+++ b/Makefile.am
@@ -0,0 +1,14 @@
+AUTOMAKE_OPTIONS = foreign
+ACLOCAL_AMFLAGS = -I m4
+SUBDIRS = src include tools udev
+
+EXTRA_DIST = \
+ README.md \
+ git-version-gen
+
+dist-hook:
+ @if ! git diff --quiet; then echo "Uncommitted changes present; not releasing"; exit 1; fi
+ echo $(VERSION) > $(distdir)/.tarball-version
+
+DISTCHECK_CONFIGURE_FLAGS = \
+ --with-udevrulesdir=$$dc_install_base/$(udevrulesdir)
diff --git a/NEWS b/NEWS
new file mode 100644
index 0000000..cb06ea6
--- /dev/null
+++ b/NEWS
@@ -0,0 +1,124 @@
+Version 1.2.0
+~~~~~~~~~~~~~
+
+* Changes:
+ - Allow building --without-tools
+ - Add KIS (aka Debug USB) support for macOS, Linux, and Windows
+ (Windows note: requires up-to-date AppleMobileDeviceSupport64.msi package installed)
+ - Add Port DFU support (restore procedure is handled externally)
+ - irecovery: Print detailed mode for -q and -m commands
+ - Overall code cleanup and de-duplication
+ - Windows-specific code cleanup and improvements
+
+* Device database changes:
+ - Add Mac Pro, Mac Studio (M2) and MacBook Air (M2) models
+ - Add iPhone 15 family
+ - Add Apple Watch Series 9 and Ultra 2 models
+ - Add November 2023 iMac and MacBook Pro models
+ - Add support for Apple Vision Pro (RealityDevice14,1)
+
+* Bug Fixes:
+ - A few minor Windows-specific bug fixes
+
+Version 1.1.0
+~~~~~~~~~~~~~
+
+* Changes:
+ - Remove duplicated thread/collection code and use new libimobiledevice-glue instead
+ - Add new `irecv_send_command_breq` (for M1 restoring)
+ - Add new `setenvnp` command
+ - Add support for iPad 8 and iPad Air 4 models
+ - Add all current Apple Watch models (device lookup)
+ - Add support for HomePod and HomePod mini (device lookup)
+ - Add support for Apple Silicon/M1 Macs (device lookup) and remaining T2/iBridge devices
+ - Add iMac 24-inch M1 models
+ - Add iPad Pro 11-inch (3rd gen) and iPad Pro 12.9-inch (5th gen) devices
+ - Add Apple TV 4K (2nd gen)
+ - Add iPhone 13 family
+ - Add 9th gen iPad devices
+ - Add 6th gen iPad mini
+ - Add Apple Watch Series 7
+ - Add MacBook Pro 2021 models (device lookup)
+ - Add iPad Air (5th gen)
+ - Add iPhone SE (3rd gen)
+ - Add Mac Studio
+ - Add Studio Display (device lookup)
+ - Add device ID for macOS 12 Apple Silicon VMs
+ - Add M2 MacBook models
+ - Add iPhone 14 family
+ - Add Apple Watch SE 2, Series 8 and Ultra family
+ - Add iPad (10th gen)
+ - Add iPad Pro 11-inch (4th gen) and iPad Pro 12.9-inch (6th gen)
+ - Add Apple TV 4K 3rd gen
+ - Add January 2023 Macs and 2nd generation HomePod models
+ - [Windows] Add support for newer drivers
+ - irecovery: Add new "--devices" option to list internal device data
+ - irecovery: Output product, model and marketing name for device information
+
+* Bug Fixes:
+ - Send a ZLP in recovery mode if the buffer size is a multiple of 512
+ - Make sure DEVICE_ADD events are sent to additional event listeners
+ - [Windows] Use ANSI versions for SetupDI and CreateFile API to prevent errors when compiling with unicode support
+ - irecovery: Fix sending certain commands
+
+Version 1.0.0
+~~~~~~~~~~~~~
+
+* Changes:
+ - Output basic device information after connecting
+ - Remove obsolete "in-tree" copy of libusb-1.0
+ - Improve source code directory structure
+ - Clean up and update of build system files
+ - Major code refactoring
+ - Add getters to retrieve device model information
+ - Change exploit related wording to more accurate limera1n
+ - Various improvements/fixes for win32 build
+ - Add support for latest device models
+ - Fix some memory leaks
+ - Add requirement for autoconf 2.64
+ - Support IOKit on OSX (removes dependency on libusb)
+ - Add DFU mode error handling
+ - Add udev rules to allow non-root device access
+ - Support ECID in hex or decimal format
+ - Fix various compiler warnings
+ - Add device add/remove event subscription interface
+ - Convert README to markdown
+ - Print PWND string if present
+ - Add support for Apple T2 processors
+ - Allow compiling without USB functionality
+ - Support checkra1n DFU mode devices
+ - Allow toggling debug level using "LIBIRECOVERY_DEBUG_LEVEL" environment
+ variable
+ - Add long argument name variants to irecovery
+ - Add new "--version" argument to irecovery
+ - Add support for Apple Watch 1st gen devices
+ - Add support for missing iPad4,3 model and fix wrong device information
+ iPad7 variants
+ - Improve README.md with project description, installation, contributing and
+ usage sections
+ - Rename library and all related files by adding an API version resulting
+ in "libirecovery-1.0"
+
+Version 0.1.1
+~~~~~~~~~~~~~
+
+* Changes:
+ - Add serial number and imei getters
+ - Improve USB communication stability
+ - Add support for WTF mode
+ - Add option to target device by ECID
+ - Add nonce getter
+ - Improve win32 device detection and mingw compatibility
+ - Add support for new device models
+ - Switch to autotools build system instead of plain Makefile
+ - Expose control and bulk transfer methods in public interface
+ - Improve maintainability of device model information
+ - Change license to LGPL 2.1
+
+Version 0.1.0
+~~~~~~~~~~~~~
+
+* Changes:
+ - Implement initial interface and device communication
+ - Add basic irecovery tool
+ - Setup build system
diff --git a/README b/README
deleted file mode 100644
index 50baf0d..0000000
--- a/README
+++ /dev/null
@@ -1,22 +0,0 @@
-== What is iRecovery? ==
-
-iRecovery is a libusb-based commandline utility for Mac OS X, Windows, and Linux. It is able to talk to iBoot/iBSS in Apple's iPhone/iPod touch via USB.
-
-It's completely open-source, the source code is released under the terms of the GNU General Public License v3.
-The full license text can be found in the LICENSE file.
-
-Here's its usage:
-
-irecovery [args]
- -v Start irecovery in verbose mode.
- -c <cmd> Send command to client.
- -f <file> Send file to client.
- -k [payload] Send usb exploit to client.
- -h Show this help.
- -r Reset client.
- -s Start interactive shell.
- -e <script> Executes recovery shell script.
-
-You can get info on the shell commands here:
-http://code.google.com/p/chronicdev/wiki/iBootCommands
-
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ac49f5d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,258 @@
+# libirecovery
+
+*The libirecovery library allows communication with iBoot/iBSS of iOS devices
+via USB.*
+
+![](https://github.com/libimobiledevice/libirecovery/workflows/build/badge.svg)
+
+## Table of Contents
+- [Features](#features)
+- [Building](#building)
+ - [Prerequisites](#prerequisites)
+ - [Linux (Debian/Ubuntu based)](#linux-debianubuntu-based)
+ - [macOS](#macos)
+ - [Windows](#windows)
+ - [Configuring the source tree](#configuring-the-source-tree)
+ - [Building and installation](#building-and-installation)
+- [Usage](#usage)
+- [Contributing](#contributing)
+- [Links](#links)
+- [License](#license)
+- [Credits](#credits)
+
+## Features
+
+libirecovery is a cross-platform library which implements communication to
+iBoot/iBSS found on Apple's iOS devices via USB. A command-line utility named
+`irecovery` is also provided.
+
+This is a fork of an older version from former openjailbreak.org and is meant to
+be used with [idevicerestore](https://github.com/libimobiledevice/idevicerestore.git/) from the [libimobiledevice](https://github.com/libimobiledevice/) project.
+
+## Building
+
+### Prerequisites
+
+You need to have a working compiler (gcc/clang) and development environent
+available. This project uses autotools for the build process, allowing to
+have common build steps across different platforms.
+Only the prerequisites differ and they are described in this section.
+
+libirecovery requires [libimobiledevice-glue](https://github.com/libimobiledevice/libimobiledevice-glue).
+Check the [Building](https://github.com/libimobiledevice/libimobiledevice-glue?tab=readme-ov-file#building)
+section of the README on how to build it. Note that some platforms might have it as a package.
+
+#### Linux (Debian/Ubuntu based)
+
+* Install all required dependencies and build tools:
+ ```shell
+ sudo apt-get install \
+ build-essential \
+ pkg-config \
+ checkinstall \
+ git \
+ autoconf \
+ automake \
+ libtool-bin \
+ libimobiledevice-glue-dev \
+ libreadline-dev \
+ libusb-1.0-0-dev
+ ```
+
+ In case libimobiledevice-glue-dev is not available, you can manually build and install it. See note above.
+
+#### macOS
+
+* Make sure the Xcode command line tools are installed. Then, use either [MacPorts](https://www.macports.org/)
+ or [Homebrew](https://brew.sh/) to install `automake`, `autoconf`, `libtool`, etc.
+
+ Using MacPorts:
+ ```shell
+ sudo port install libtool autoconf automake pkgconfig
+ ```
+
+ Using Homebrew:
+ ```shell
+ brew install libtool autoconf automake pkg-config
+ ```
+
+#### Windows
+
+* Using [MSYS2](https://www.msys2.org/) is the official way of compiling this project on Windows. Download the MSYS2 installer
+ and follow the installation steps.
+
+ It is recommended to use the _MSYS2 MinGW 64-bit_ shell. Run it and make sure the required dependencies are installed:
+
+ ```shell
+ pacman -S base-devel \
+ git \
+ mingw-w64-x86_64-gcc \
+ make \
+ libtool \
+ autoconf \
+ automake-wrapper \
+ pkg-config
+ ```
+ NOTE: You can use a different shell and different compiler according to your needs. Adapt the above command accordingly.
+
+### Configuring the source tree
+
+You can build the source code from a git checkout, or from a `.tar.bz2` release tarball from [Releases](https://github.com/libimobiledevice/libirecovery/releases).
+Before we can build it, the source tree has to be configured for building. The steps depend on where you got the source from.
+
+Since libirecovery depends on other packages, you should set the pkg-config environment variable `PKG_CONFIG_PATH`
+accordingly. Make sure to use a path with the same prefix as the dependencies. If they are installed in `/usr/local` you would do
+
+```shell
+export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
+```
+
+* **From git**
+
+ If you haven't done already, clone the actual project repository and change into the directory.
+ ```shell
+ git clone https://github.com/libimobiledevice/libirecovery
+ cd libirecovery
+ ```
+
+ Configure the source tree for building:
+ ```shell
+ ./autogen.sh
+ ```
+
+* **From release tarball (.tar.bz2)**
+
+ When using an official [release tarball](https://github.com/libimobiledevice/libirecovery/releases) (`libirecovery-x.y.z.tar.bz2`)
+ the procedure is slightly different.
+
+ Extract the tarball:
+ ```shell
+ tar xjf libirecovery-x.y.z.tar.bz2
+ cd libirecovery-x.y.z
+ ```
+
+ Configure the source tree for building:
+ ```shell
+ ./configure
+ ```
+
+Both `./configure` and `./autogen.sh` (which generates and calls `configure`) accept a few options, for example `--prefix` to allow
+building for a different target folder. You can simply pass them like this:
+
+```shell
+./autogen.sh --prefix=/usr/local
+```
+or
+```shell
+./configure --prefix=/usr/local
+```
+
+Once the command is successful, the last few lines of output will look like this:
+```
+[...]
+config.status: creating config.h
+config.status: executing depfiles commands
+config.status: executing libtool commands
+
+Configuration for libirecovery 1.2.0:
+-------------------------------------------
+
+ Install prefix: .........: /usr/local
+ USB backend: ............: IOKit
+
+ Now type 'make' to build libirecovery 1.2.0,
+ and then 'make install' for installation.
+```
+
+### Building and installation
+
+If you followed all the steps successfully, and `autogen.sh` or `configure` did not print any errors,
+you are ready to build the project. This is simply done with
+
+```shell
+make
+```
+
+If no errors are emitted you are ready for installation. Depending on whether
+the current user has permissions to write to the destination directory or not,
+you would either run
+```shell
+make install
+```
+_OR_
+```shell
+sudo make install
+```
+
+If you are on Linux, you want to run `sudo ldconfig` after installation to
+make sure the installed libraries are made available.
+
+## Usage
+
+First of all attach your device to your machine. Make sure your device is not
+in normal mode. You can use the `ideviceenterrecovery` application from
+[libimobiledevice](https://github.com/libimobiledevice/libimobiledevice.git/)
+to let your device boot into recovery mode if you need it.
+
+Then simply run:
+```shell
+irecovery --shell
+```
+
+This connects to your device and opens a simple shell to interact with the
+device.
+
+For instance to make your device boot into normal mode again use:
+```shell
+setenv auto-boot true
+saveenv
+reboot
+```
+
+Please consult the usage information or manual page for a full documentation of
+available command line options:
+```shell
+irecovery --help
+man irecovery
+```
+
+## Contributing
+
+We welcome contributions from anyone and are grateful for every pull request!
+
+If you'd like to contribute, please fork the `master` branch, change, commit and
+send a pull request for review. Once approved it can be merged into the main
+code base.
+
+If you plan to contribute larger changes or a major refactoring, please create a
+ticket first to discuss the idea upfront to ensure less effort for everyone.
+
+Please make sure your contribution adheres to:
+* Try to follow the code style of the project
+* Commit messages should describe the change well without being too short
+* Try to split larger changes into individual commits of a common domain
+* Use your real name and a valid email address for your commits
+
+## Links
+
+* Homepage: https://libimobiledevice.org/
+* Repository: https://git.libimobiledevice.org/libirecovery.git
+* Repository (Mirror): https://github.com/libimobiledevice/libirecovery.git
+* Issue Tracker: https://github.com/libimobiledevice/libirecovery/issues
+* Mailing List: https://lists.libimobiledevice.org/mailman/listinfo/libimobiledevice-devel
+* Twitter: https://twitter.com/libimobiledev
+
+## License
+
+This project is licensed under the [GNU Lesser General Public License v2.1](https://www.gnu.org/licenses/lgpl-2.1.en.html),
+also included in the repository in the `COPYING` file.
+
+## Credits
+
+Apple, iPhone, iPad, iPod, iPod Touch, Apple TV, Apple Watch, Mac, iOS,
+iPadOS, tvOS, watchOS, and macOS are trademarks of Apple Inc.
+
+This project is an independent software library and has not been authorized,
+sponsored, or otherwise approved by Apple Inc.
+
+README Updated on: 2024-03-23
diff --git a/TODO b/TODO
deleted file mode 100644
index 411f6e6..0000000
--- a/TODO
+++ /dev/null
@@ -1,15 +0,0 @@
-TODO List
-------------------------------------------------
-
-o) Need to implement irecv_saveenv()
-o) Need to implement irecv_bootx()
-o) Neex to implement irecv_go()
-o) Need to implement irecv_bgcolor()
-o) Need to implememt irecv_setpicture()
-o) Need to impelemnt irecv_reboot()
-o) Should figure out a better place to store callbacks so the CONNECTED callback can actually be used
-o) would be nice to change to use asyncronous connections
-o) could add a function to identify whether we're connected to iBoot/iBEC/iBSS or DFU
-o) could add a function to identify which version we're connected to
-o) could add a function to return the device serial number
-o) fix command parsing to strip quotes \ No newline at end of file
diff --git a/autogen.sh b/autogen.sh
new file mode 100755
index 0000000..5a0ec43
--- /dev/null
+++ b/autogen.sh
@@ -0,0 +1,26 @@
+#!/bin/sh
+
+olddir=`pwd`
+srcdir=`dirname $0`
+test -z "$srcdir" && srcdir=.
+
+(
+ cd "$srcdir"
+
+ gprefix=`which glibtoolize 2>&1 >/dev/null`
+ if [ $? -eq 0 ]; then
+ glibtoolize --force
+ else
+ libtoolize --force
+ fi
+ aclocal -I m4
+ autoheader
+ automake --add-missing
+ autoconf
+
+ cd "$olddir"
+)
+
+if [ -z "$NOCONFIGURE" ]; then
+ $srcdir/configure "$@"
+fi
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..94bb793
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,230 @@
+# -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+
+AC_PREREQ(2.68)
+AC_INIT([libirecovery], [m4_esyscmd(./git-version-gen $RELEASE_VERSION)], [https://github.com/libimobiledevice/libirecovery/issues], [], [https://libimobiledevice.org])
+AM_INIT_AUTOMAKE([dist-bzip2 no-dist-gzip check-news])
+m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES])
+AC_CONFIG_SRCDIR([src/])
+AC_CONFIG_HEADERS([config.h])
+AC_CONFIG_MACRO_DIR([m4])
+
+dnl libtool versioning
+# +1 : 0 : +1 == adds new functions to the interface
+# +1 : 0 : 0 == changes or removes functions (changes include both
+# changes to the signature and the semantic)
+# ? :+1 : ? == just internal changes
+# CURRENT : REVISION : AGE
+LIBIRECOVERY_SO_VERSION=5:0:0
+
+dnl Minimum package versions
+LIBUSB_VERSION=1.0.3
+LIMD_GLUE_VERSION=1.2.0
+
+AC_SUBST(LIBIRECOVERY_SO_VERSION)
+AC_SUBST(LIMD_GLUE_VERSION)
+
+# Checks for programs.
+AC_PROG_CC
+#AC_PROG_CXX
+AM_PROG_CC_C_O
+LT_INIT
+
+# Checks for libraries.
+PKG_CHECK_MODULES(limd_glue, libimobiledevice-glue-1.0 >= $LIMD_GLUE_VERSION)
+
+# Checks for header files.
+AC_CHECK_HEADERS([stdint.h stdlib.h string.h])
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_TYPE_SIZE_T
+AC_TYPE_SSIZE_T
+AC_TYPE_UINT16_T
+AC_TYPE_UINT32_T
+AC_TYPE_UINT8_T
+
+# Checks for library functions.
+AC_CHECK_FUNCS([strdup strerror strcasecmp strndup malloc realloc calloc])
+
+# Check additional platform flags
+AC_MSG_CHECKING([for platform-specific build settings])
+case ${host_os} in
+ darwin*)
+ AC_MSG_RESULT([${host_os}])
+ AC_CHECK_HEADER(CoreFoundation/CoreFoundation.h, [
+ AC_CHECK_HEADER(IOKit/usb/IOUSBLib.h, [
+ GLOBAL_LDFLAGS+=" -framework IOKit -framework CoreFoundation"
+ have_iokit=yes
+ ], [])
+ ], [])
+ ;;
+ mingw32*)
+ AC_MSG_RESULT([${host_os}])
+ GLOBAL_LDFLAGS+=" -static-libgcc -lkernel32 -lsetupapi"
+ win32=true
+ ;;
+ cygwin*)
+ AC_MSG_RESULT([${host_os}])
+ CC=gcc-3
+ CFLAGS+=" -mno-cygwin"
+ GLOBAL_LDFLAGS+=" -static-libgcc -lkernel32 -lsetupapi"
+ win32=true
+ ;;
+ *)
+ AC_MSG_RESULT([${host_os}])
+ ;;
+esac
+AM_CONDITIONAL(WIN32, test x$win32 = xtrue)
+
+# Check if the C compiler supports __attribute__((constructor))
+AC_CACHE_CHECK([wether the C compiler supports constructor/destructor attributes],
+ ac_cv_attribute_constructor, [
+ ac_cv_attribute_constructor=no
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
+ [[
+ static void __attribute__((constructor)) test_constructor(void) {
+ }
+ static void __attribute__((destructor)) test_destructor(void) {
+ }
+ ]], [])],
+ [ac_cv_attribute_constructor=yes]
+ )]
+)
+if test "$ac_cv_attribute_constructor" = "yes"; then
+ AC_DEFINE(HAVE_ATTRIBUTE_CONSTRUCTOR, 1, [Define if the C compiler supports constructor/destructor attributes])
+fi
+
+AC_ARG_WITH([tools],
+ [AS_HELP_STRING([--with-tools], [Build irecovery tools. (requires readline) [default=yes]])],
+ [],
+ [with_tools=yes])
+
+AS_IF([test "x$with_tools" = "xyes"], [
+ AC_DEFINE(BUILD_TOOLS, 1, [Define if we are building irecovery tools])
+ AC_CHECK_HEADERS([readline/readline.h], [],
+ [AC_MSG_ERROR([Please install readline development headers])]
+ )]
+)
+AM_CONDITIONAL(BUILD_TOOLS, test "x$with_tools" = "xyes")
+
+AC_ARG_WITH([dummy],
+ [AS_HELP_STRING([--with-dummy], [Use no USB driver at all [default=no]. This is only useful if you just want to query the device list by product type or hardware model. All other operations are no-ops or will return IRECV_E_UNSUPPORTED.])],
+ [],
+ [with_dummy=no])
+
+AS_IF([test "x$have_iokit" = "xyes"], [
+ AC_ARG_WITH([iokit],
+ [AS_HELP_STRING([--with-iokit], [Use IOKit instead of libusb on OS X [default=yes]])],
+ [],
+ [with_iokit=yes])
+ ]
+)
+
+AS_IF([test "x$with_dummy" = "xyes"], [
+ AC_DEFINE(USE_DUMMY, 1, [Define if we are using dummy USB driver])
+ USB_BACKEND="dummy"
+], [
+ AS_IF([test "x$with_iokit" = "xyes" && test "x$have_iokit" = "xyes"], [
+ AC_DEFINE(HAVE_IOKIT, 1, [Define if we have IOKit])
+ USB_BACKEND="IOKit"
+ ], [
+ AS_IF([test "x$win32" = "xtrue"], [
+ USB_BACKEND="win32 native (setupapi)"
+ ], [
+ PKG_CHECK_MODULES(libusb, libusb-1.0 >= $LIBUSB_VERSION)
+ USB_BACKEND="libusb `$PKG_CONFIG --modversion libusb-1.0`"
+ LIBUSB_REQUIRED="libusb-1.0 >= $LIBUSB_VERSION"
+ AC_SUBST(LIBUSB_REQUIRED)
+ ])
+ ])
+])
+
+AS_COMPILER_FLAGS(GLOBAL_CFLAGS, "-Wall -Wextra -Wmissing-declarations -Wredundant-decls -Wshadow -Wpointer-arith -Wwrite-strings -Wswitch-default -Wno-unused-parameter -fvisibility=hidden")
+
+if test "x$enable_static" = "xyes" -a "x$enable_shared" = "xno"; then
+ GLOBAL_CFLAGS+=" -DIRECV_STATIC"
+fi
+
+AC_SUBST(GLOBAL_CFLAGS)
+AC_SUBST(GLOBAL_LDFLAGS)
+
+# check for large file support
+AC_SYS_LARGEFILE
+
+AC_ARG_WITH([udev],
+ AS_HELP_STRING([--with-udev],
+ [Configure and install udev rules file for DFU/Recovery mode devices]),
+ [],
+ [if $($PKG_CONFIG --exists udev); then with_udev=yes; else with_udev=no; fi])
+
+AC_ARG_WITH([udevrulesdir],
+ AS_HELP_STRING([--with-udevrulesdir=DIR],
+ [Directory for udev rules (implies --with-udev)]),
+ [with_udev=yes],
+ [with_udevrulesdir=auto])
+
+AC_ARG_WITH([udevrule],
+ AS_HELP_STRING([--with-udevrule="RULE"],
+ [udev activation rule (implies --with-udev)]),
+ [with_udev=yes],
+ [with_udevrule=auto])
+
+if test "x$with_udev" = "xyes"; then
+ if test "x$with_udevrule" = "xauto"; then
+ for I in plugdev storage disk staff; do
+ if grep $I /etc/group >/dev/null; then
+ USEGROUP=$I
+ break
+ fi
+ done
+ if test "x$USEGROUP" != "x"; then
+ if ! groups |grep $USEGROUP >/dev/null; then
+ AC_MSG_WARN([The group '$USEGROUP' was determined to be used for the udev rule, but the current user is not member of this group.])
+ fi
+ else
+ AC_MSG_ERROR([Could not determine an appropriate user group for the udev activation rule.
+ Please manually specify a udev activation rule using --with-udevrule=<RULE>
+ Example: --with-udevrule="OWNER=\\"root\\", GROUP=\\"myusergroup\\", MODE=\\"0660\\""])
+ fi
+ with_udevrule="OWNER=\"root\", GROUP=\"$USEGROUP\", MODE=\"0660\""
+ fi
+
+ if test "x$with_udevrulesdir" = "xauto"; then
+ udevdir=$($PKG_CONFIG --silence-errors --variable=udevdir udev)
+ if test "x$udevdir" != "x"; then
+ with_udevrulesdir=$udevdir"/rules.d"
+ else
+ with_udevrulesdir="\${prefix}/lib/udev/rules.d"
+ AC_MSG_WARN([Could not determine default udev rules directory. Using $with_udevrulesdir.])
+ fi
+ fi
+
+ AC_SUBST([udev_activation_rule], [$with_udevrule])
+ AC_SUBST([udevrulesdir], [$with_udevrulesdir])
+fi
+AM_CONDITIONAL(WITH_UDEV, test "x$with_udev" = "xyes")
+
+m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])
+
+AC_CONFIG_FILES([
+Makefile
+src/Makefile
+src/libirecovery-1.0.pc
+udev/39-libirecovery.rules
+include/Makefile
+tools/Makefile
+udev/Makefile
+])
+AC_OUTPUT
+
+echo "
+Configuration for $PACKAGE $VERSION:
+-------------------------------------------
+
+ Install prefix: .........: $prefix
+ USB backend: ............: $USB_BACKEND
+
+ Now type 'make' to build $PACKAGE $VERSION,
+ and then 'make install' for installation.
+"
diff --git a/git-version-gen b/git-version-gen
new file mode 100755
index 0000000..d868952
--- /dev/null
+++ b/git-version-gen
@@ -0,0 +1,20 @@
+#!/bin/sh
+SRCDIR=`dirname $0`
+if test -n "$1"; then
+ VER=$1
+else
+ if test -r "${SRCDIR}/.git" && test -x "`which git`" ; then
+ git update-index -q --refresh
+ if ! VER=`git describe --tags --dirty 2>/dev/null`; then
+ COMMIT=`git rev-parse --short HEAD`
+ DIRTY=`git diff --quiet HEAD || echo "-dirty"`
+ VER=`sed -n '1,/RE/s/Version \(.*\)/\1/p' ${SRCDIR}/NEWS`-git-${COMMIT}${DIRTY}
+ fi
+ else
+ if test -f "${SRCDIR}/.tarball-version"; then
+ VER=`cat "${SRCDIR}/.tarball-version"`
+ fi
+ fi
+fi
+VER=`printf %s "$VER" | head -n1`
+printf %s "$VER"
diff --git a/include/Makefile.am b/include/Makefile.am
new file mode 100644
index 0000000..aa885aa
--- /dev/null
+++ b/include/Makefile.am
@@ -0,0 +1 @@
+nobase_dist_include_HEADERS = libirecovery.h \ No newline at end of file
diff --git a/include/libirecovery.h b/include/libirecovery.h
index c459984..ec9255b 100644
--- a/include/libirecovery.h
+++ b/include/libirecovery.h
@@ -1,20 +1,22 @@
-/**
- * iRecovery - Utility for DFU 2.0, WTF and Recovery Mode
- * Copyright (C) 2008 - 2009 westbaer
+/*
+ * libirecovery.h
+ * Communication to iBoot/iBSS on Apple iOS devices via USB
*
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
+ * Copyright (c) 2012-2023 Nikias Bassen <nikias@gmx.li>
+ * Copyright (c) 2012-2013 Martin Szulecki <m.szulecki@libimobiledevice.org>
+ * Copyright (c) 2010 Chronic-Dev Team
+ * Copyright (c) 2010 Joshua Hill
*
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * 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
*
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- **/
+ * 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
@@ -23,93 +25,171 @@
extern "C" {
#endif
-#include <libusb-1.0/libusb.h>
+#include <stdint.h>
-#define APPLE_VENDOR_ID 0x05AC
+#ifndef IRECV_API
+ #ifdef IRECV_STATIC
+ #define IRECV_API
+ #elif defined(_WIN32)
+ #define IRECV_API __declspec(dllimport)
+ #else
+ #define IRECV_API
+ #endif
+#endif
-enum {
- kRecoveryMode1 = 0x1280,
- kRecoveryMode2 = 0x1281,
- kRecoveryMode3 = 0x1282,
- kRecoveryMode4 = 0x1283,
- kDfuMode = 0x1227
+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_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_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_UNKNOWN_ERROR = -255
+ 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_RECEIVED = 1,
+ IRECV_PRECOMMAND = 2,
+ IRECV_POSTCOMMAND = 3,
+ IRECV_CONNECTED = 4,
+ IRECV_DISCONNECTED = 5,
+ IRECV_PROGRESS = 6
} irecv_event_type;
typedef struct {
int size;
- char* data;
+ const char* data;
double progress;
irecv_event_type type;
} irecv_event_t;
-struct irecv_client;
-typedef struct irecv_client* irecv_client_t;
-typedef int(*irecv_event_cb_t)(irecv_client_t client, const irecv_event_t* event);
+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;
+};
-struct irecv_client {
- int debug;
- int config;
- int interface;
- int alt_interface;
- unsigned short mode;
- char serial[256];
- libusb_device_handle* handle;
- 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;
+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)
};
-void irecv_set_debug_level(int level);
-const char* irecv_strerror(irecv_error_t error);
-irecv_error_t irecv_open(irecv_client_t* client);
-irecv_error_t irecv_reset(irecv_client_t client);
-irecv_error_t irecv_close(irecv_client_t client);
-irecv_error_t irecv_receive(irecv_client_t client);
-irecv_error_t irecv_send_exploit(irecv_client_t client);
-irecv_error_t irecv_execute_script(irecv_client_t client, const char* filename);
-irecv_error_t irecv_set_configuration(irecv_client_t client, int configuration);
-
-irecv_error_t irecv_event_subscribe(irecv_client_t client, irecv_event_type type, irecv_event_cb_t callback, void *user_data);
-irecv_error_t irecv_event_unsubscribe(irecv_client_t client, irecv_event_type type);
-
-irecv_error_t irecv_send_file(irecv_client_t client, const char* filename);
-irecv_error_t irecv_send_command(irecv_client_t client, unsigned char* command);
-irecv_error_t irecv_send_buffer(irecv_client_t client, unsigned char* buffer, unsigned long length);
-
-irecv_error_t irecv_getenv(irecv_client_t client, const char* variable, char** value);
-irecv_error_t irecv_setenv(irecv_client_t client, const char* variable, const char* value);
-irecv_error_t irecv_set_interface(irecv_client_t client, int interface, int alt_interface);
-irecv_error_t irecv_get_cpid(irecv_client_t client, unsigned int* cpid);
-irecv_error_t irecv_get_bdid(irecv_client_t client, unsigned int* bdid);
-irecv_error_t irecv_get_ecid(irecv_client_t client, unsigned long long* ecid);
+/* library */
+IRECV_API void irecv_set_debug_level(int level);
+IRECV_API const char* irecv_strerror(irecv_error_t error);
+IRECV_API void irecv_init(void); /* deprecated: libirecovery has constructor now */
+IRECV_API void irecv_exit(void); /* deprecated: libirecovery has destructor now */
+
+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);
+
+/* 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
}
diff --git a/m4/as-compiler-flag.m4 b/m4/as-compiler-flag.m4
new file mode 100644
index 0000000..baab5d9
--- /dev/null
+++ b/m4/as-compiler-flag.m4
@@ -0,0 +1,62 @@
+dnl as-compiler-flag.m4 0.1.0
+
+dnl autostars m4 macro for detection of compiler flags
+
+dnl David Schleef <ds@schleef.org>
+
+dnl $Id: as-compiler-flag.m4,v 1.1 2005/12/15 23:35:19 ds Exp $
+
+dnl AS_COMPILER_FLAG(CFLAGS, ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED])
+dnl Tries to compile with the given CFLAGS.
+dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags,
+dnl and ACTION-IF-NOT-ACCEPTED otherwise.
+
+AC_DEFUN([AS_COMPILER_FLAG],
+[
+ AC_MSG_CHECKING([to see if compiler understands $1])
+
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $1"
+
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], [flag_ok=yes], [flag_ok=no])
+ CFLAGS="$save_CFLAGS"
+
+ if test "X$flag_ok" = Xyes ; then
+ m4_ifvaln([$2],[$2])
+ true
+ else
+ m4_ifvaln([$3],[$3])
+ true
+ fi
+ AC_MSG_RESULT([$flag_ok])
+])
+
+dnl AS_COMPILER_FLAGS(VAR, FLAGS)
+dnl Tries to compile with the given CFLAGS.
+
+AC_DEFUN([AS_COMPILER_FLAGS],
+[
+ list=$2
+ flags_supported=""
+ flags_unsupported=""
+ AC_MSG_CHECKING([for supported compiler flags])
+ for each in $list
+ do
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $each"
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], [flag_ok=yes], [flag_ok=no])
+ CFLAGS="$save_CFLAGS"
+
+ if test "X$flag_ok" = Xyes ; then
+ flags_supported="$flags_supported $each"
+ else
+ flags_unsupported="$flags_unsupported $each"
+ fi
+ done
+ AC_MSG_RESULT([$flags_supported])
+ if test "X$flags_unsupported" != X ; then
+ AC_MSG_WARN([unsupported compiler flags: $flags_unsupported])
+ fi
+ $1="$$1 $flags_supported"
+])
+
diff --git a/scripts/boot.irs b/scripts/boot.irs
deleted file mode 100644
index f989328..0000000
--- a/scripts/boot.irs
+++ /dev/null
@@ -1,5 +0,0 @@
-# Simple script to kick you out of recovery mode
-setenv auto-boot true
-saveenv
-reboot
-
diff --git a/scripts/test.irs b/scripts/test.irs
deleted file mode 100644
index 77f959d..0000000
--- a/scripts/test.irs
+++ /dev/null
@@ -1,21 +0,0 @@
-# This small script should make the device flash
-# Red, Green, Blue a few times then reboot.
-bgcolor 255 0 0
-bgcolor 0 255 0
-bgcolor 0 0 255
-bgcolor 255 0 0
-bgcolor 0 255 0
-bgcolor 0 0 255
-bgcolor 255 0 0
-bgcolor 0 255 0
-bgcolor 0 0 255
-bgcolor 255 0 0
-bgcolor 0 255 0
-bgcolor 0 0 255
-bgcolor 255 0 0
-bgcolor 0 255 0
-bgcolor 0 0 255
-bgcolor 255 0 0
-bgcolor 0 255 0
-bgcolor 0 0 255
-reboot
diff --git a/src/Makefile.am b/src/Makefile.am
new file mode 100644
index 0000000..f80ffa7
--- /dev/null
+++ b/src/Makefile.am
@@ -0,0 +1,24 @@
+AM_CPPFLAGS = -I$(top_srcdir)/include
+
+AM_CFLAGS = \
+ $(GLOBAL_CFLAGS) \
+ $(LFS_CFLAGS) \
+ $(limd_glue_CFLAGS) \
+ $(libusb_CFLAGS)
+
+AM_LDFLAGS = \
+ $(GLOBAL_LDFLAGS) \
+ $(limd_glue_LIBS) \
+ $(libusb_LIBS)
+
+lib_LTLIBRARIES = libirecovery-1.0.la
+libirecovery_1_0_la_CFLAGS = $(AM_CFLAGS)
+libirecovery_1_0_la_LDFLAGS = $(AM_LDFLAGS) -version-info $(LIBIRECOVERY_SO_VERSION) -no-undefined
+libirecovery_1_0_la_SOURCES = libirecovery.c
+
+if WIN32
+libirecovery_1_0_la_LDFLAGS += -avoid-version
+endif
+
+pkgconfigdir = $(libdir)/pkgconfig
+pkgconfig_DATA = libirecovery-1.0.pc
diff --git a/src/irecovery.c b/src/irecovery.c
deleted file mode 100644
index 5a59cd0..0000000
--- a/src/irecovery.c
+++ /dev/null
@@ -1,355 +0,0 @@
-/**
- * iRecovery - Utility for DFU 2.0, WTF and Recovery Mode
- * Copyright (C) 2008 - 2009 westbaer
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- **/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <libirecovery.h>
-#include <readline/readline.h>
-#include <readline/history.h>
-
-#define FILE_HISTORY_PATH ".irecovery"
-#define debug(...) if(verbose) fprintf(stderr, __VA_ARGS__)
-
-enum {
- kResetDevice, kStartShell, kSendCommand, kSendFile, kSendExploit, kSendScript
-};
-
-static unsigned int quit = 0;
-static unsigned int verbose = 0;
-
-void print_progress_bar(double progress);
-int received_cb(irecv_client_t client, const irecv_event_t* event);
-int progress_cb(irecv_client_t client, const irecv_event_t* event);
-int precommand_cb(irecv_client_t client, const irecv_event_t* event);
-int postcommand_cb(irecv_client_t client, const irecv_event_t* event);
-
-void shell_usage() {
- printf("Usage:\n");
- printf("\t/upload <file>\tSend file to client.\n");
- printf("\t/exploit [file]\tSend usb exploit with optional payload\n");
- printf("\t/help\t\tShow this help.\n");
- printf("\t/exit\t\tExit interactive shell.\n");
-}
-
-void parse_command(irecv_client_t client, unsigned char* command, unsigned int size) {
- irecv_error_t error = 0;
- char* cmd = strdup(command);
- char* action = strtok(cmd, " ");
- debug("Executing %s\n", action);
- if (!strcmp(cmd, "/exit")) {
- quit = 1;
- } else
-
- if (!strcmp(cmd, "/help")) {
- shell_usage();
- } else
-
- if (!strcmp(cmd, "/upload")) {
- char* filename = strtok(NULL, " ");
- debug("Uploading files %s\n", filename);
- if (filename != NULL) {
- error = irecv_send_file(client, filename);
- debug("%s\n", irecv_strerror(error));
- }
- } else
-
- if (!strcmp(cmd, "/exploit")) {
- char* filename = strtok(NULL, " ");
- debug("Sending exploit %s\n", filename);
- if (filename != NULL) {
- error = irecv_send_file(client, filename);
- debug("%s\n", irecv_strerror(error));
- }
- irecv_send_exploit(client);
- } else
-
- if (!strcmp(cmd, "/execute")) {
- char* filename = strtok(NULL, " ");
- debug("Executing script %s\n", filename);
- if (filename != NULL) {
- irecv_execute_script(client, filename);
- }
- }
-
-
- free(action);
-}
-
-void load_command_history() {
- read_history(FILE_HISTORY_PATH);
-}
-
-void append_command_to_history(char* cmd) {
- add_history(cmd);
- write_history(FILE_HISTORY_PATH);
-}
-
-void init_shell(irecv_client_t client) {
- irecv_error_t error = 0;
- load_command_history();
- irecv_event_subscribe(client, IRECV_PROGRESS, &progress_cb, NULL);
- irecv_event_subscribe(client, IRECV_RECEIVED, &received_cb, NULL);
- irecv_event_subscribe(client, IRECV_PRECOMMAND, &precommand_cb, NULL);
- irecv_event_subscribe(client, IRECV_POSTCOMMAND, &postcommand_cb, NULL);
-
- error = irecv_receive(client);
- if (error != IRECV_E_SUCCESS) {
- debug("%s\n", irecv_strerror(error));
- }
-
- while (!quit) {
- char* cmd = readline("> ");
- if (cmd && *cmd) {
- error = irecv_send_command(client, cmd);
- if (error != IRECV_E_SUCCESS) {
- quit = 1;
- }
-
- append_command_to_history(cmd);
- free(cmd);
- }
- }
-}
-
-int received_cb(irecv_client_t client, const irecv_event_t* event) {
- if (event->type == IRECV_RECEIVED) {
- int i = 0;
- int size = event->size;
- char* data = event->data;
- for (i = 0; i < size; i++) {
- printf("%c", data[i]);
- }
- }
- return 0;
-}
-
-int precommand_cb(irecv_client_t client, const irecv_event_t* event) {
- char* value = NULL;
- char* action = NULL;
- char* command = NULL;
- char* argument = NULL;
- irecv_error_t error = IRECV_E_SUCCESS;
-
- if (event->type == IRECV_PRECOMMAND) {
- if (event->data[0] == '/') {
- parse_command(client, event->data, event->size);
- return -1;
- }
-
- command = strdup(event->data);
- action = strtok(command, " ");
-
- if (!strcmp(action, "getenv")) {
- argument = strtok(NULL, " ");
- error = irecv_getenv(client, argument, &value);
- if (error != IRECV_E_SUCCESS) {
- debug("%s\n", irecv_strerror(error));
- free(command);
- return error;
- }
- if (value) {
- printf("%s\n", value);
- free(value);
- }
- return 1;
- }
- }
- return 0;
-}
-
-int postcommand_cb(irecv_client_t client, const irecv_event_t* event) {
- char* action = NULL;
- char* command = NULL;
-
- if (event->type == IRECV_POSTCOMMAND) {
- command = strdup(event->data);
- action = strtok(command, " ");
-
- if (!strcmp(action, "reboot")) {
- quit = 1;
- }
- }
-
- if (command) free(command);
- return 0;
-}
-
-int progress_cb(irecv_client_t client, const irecv_event_t* event) {
- if (event->type == IRECV_PROGRESS) {
- print_progress_bar(event->progress);
- }
- return 0;
-}
-
-void print_progress_bar(double progress) {
- int i = 0;
- if(progress < 0) {
- return;
- }
-
- if(progress > 100) {
- progress = 100;
- }
-
- printf("\r[");
- for(i = 0; i < 50; i++) {
- if(i < progress / 2) {
- printf("=");
- } else {
- printf(" ");
- }
- }
-
- printf("] %3.1f%%", progress);
- fflush(stdout);
- if(progress == 100) {
- printf("\n");
- }
-}
-
-void print_usage() {
- printf("iRecovery - iDevice Recovery Utility\n");
- printf("Usage: ./irecovery [args]\n");
- printf("\t-v\t\tStart irecovery in verbose mode.\n");
- printf("\t-c <cmd>\tSend command to client.\n");
- printf("\t-f <file>\tSend file to client.\n");
- printf("\t-k [payload]\tSend usb exploit to client.\n");
- printf("\t-h\t\tShow this help.\n");
- printf("\t-r\t\tReset client.\n");
- printf("\t-s\t\tStart interactive shell.\n");
- printf("\t-e <script>\tExecutes recovery shell script.\n");
- exit(1);
-}
-
-int main(int argc, char** argv) {
- int i = 0;
- int opt = 0;
- int action = 0;
- char* argument = NULL;
- irecv_error_t error = 0;
- if (argc == 1) print_usage();
- while ((opt = getopt(argc, argv, "vhrsc:f:e:k::")) > 0) {
- switch (opt) {
- case 'v':
- verbose += 1;
- break;
-
- case 'h':
- print_usage();
- break;
-
- case 'r':
- action = kResetDevice;
- break;
-
- case 's':
- action = kStartShell;
- break;
-
- case 'f':
- action = kSendFile;
- argument = optarg;
- break;
-
- case 'c':
- action = kSendCommand;
- argument = optarg;
- break;
-
- case 'k':
- action = kSendExploit;
- argument = optarg;
- break;
-
- case 'e':
- action = kSendScript;
- argument = optarg;
- break;
-
- default:
- fprintf(stderr, "Unknown argument\n");
- return -1;
- }
- }
-
- if (verbose) irecv_set_debug_level(verbose);
-
- irecv_client_t client = NULL;
- for (i = 0; i <= 5; i++) {
- debug("Attempting to connect... \n");
-
- if (irecv_open(&client) != IRECV_E_SUCCESS)
- sleep(1);
- else
- break;
-
- if (i == 5) {
- return -1;
- }
- }
-
- switch (action) {
- case kResetDevice:
- irecv_reset(client);
- break;
-
- case kSendFile:
- irecv_event_subscribe(client, IRECV_PROGRESS, &progress_cb, NULL);
- error = irecv_send_file(client, argument);
- debug("%s\n", irecv_strerror(error));
- break;
-
- case kSendCommand:
- error = irecv_send_command(client, argument);
- debug("%s\n", irecv_strerror(error));
- break;
-
- case kSendExploit:
- if (argument != NULL) {
- irecv_event_subscribe(client, IRECV_PROGRESS, &progress_cb, NULL);
- error = irecv_send_file(client, argument);
- if (error != IRECV_E_SUCCESS) {
- debug("%s\n", irecv_strerror(error));
- break;
- }
- }
- error = irecv_send_exploit(client);
- debug("%s\n", irecv_strerror(error));
- break;
-
- case kStartShell:
- init_shell(client);
- break;
-
- case kSendScript:
- error = irecv_execute_script(client, argument);
- if(error != IRECV_E_SUCCESS) {
- debug("%s\n", irecv_strerror(error));
- }
- break;
-
- default:
- fprintf(stderr, "Unknown action\n");
- break;
- }
-
- irecv_close(client);
- return 0;
-}
-
diff --git a/src/libirecovery-1.0.pc.in b/src/libirecovery-1.0.pc.in
new file mode 100644
index 0000000..e6c94a3
--- /dev/null
+++ b/src/libirecovery-1.0.pc.in
@@ -0,0 +1,11 @@
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: @PACKAGE_NAME@
+Description: A library to communicate with iBoot/iBSS on iOS devices via USB
+Version: @PACKAGE_VERSION@
+Libs: -L${libdir} -lirecovery-1.0
+Cflags: -I${includedir}
+Requires.private: libimobiledevice-glue-1.0 >= @LIMD_GLUE_VERSION@ @LIBUSB_REQUIRED@
diff --git a/src/libirecovery.c b/src/libirecovery.c
index 38e0fc3..6b110f1 100644
--- a/src/libirecovery.c
+++ b/src/libirecovery.c
@@ -1,117 +1,1905 @@
-/**
- * iRecovery - Utility for DFU 2.0, WTF and Recovery Mode
- * Copyright (C) 2008 - 2009 westbaer
+/*
+ * libirecovery.c
+ * Communication to iBoot/iBSS on Apple iOS devices via USB
*
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
+ * Copyright (c) 2011-2023 Nikias Bassen <nikias@gmx.li>
+ * Copyright (c) 2012-2020 Martin Szulecki <martin.szulecki@libimobiledevice.org>
+ * Copyright (c) 2010 Chronic-Dev Team
+ * Copyright (c) 2010 Joshua Hill
+ * Copyright (c) 2008-2011 Nicolas Haunold
*
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
+ * 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
*
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- **/
+ * 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 <libusb-1.0/libusb.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"
+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__)
+#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" },
+ /* 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)" },
+ { "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)" },
+ /* 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" },
+ /* 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)" },
+ /* 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" },
+ { 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
+
+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_init(void)
+{
+ 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
+}
+
+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
+}
+
+static thread_once_t init_once = THREAD_ONCE_INIT;
+static thread_once_t deinit_once = THREAD_ONCE_INIT;
+
+#ifndef HAVE_ATTRIBUTE_CONSTRUCTOR
+ #if defined(__llvm__) || defined(__GNUC__)
+ #define HAVE_ATTRIBUTE_CONSTRUCTOR
+ #endif
+#endif
+
+#ifdef HAVE_ATTRIBUTE_CONSTRUCTOR
+static void __attribute__((constructor)) libirecovery_initialize(void)
+{
+ thread_once(&init_once, _irecv_init);
+}
+
+static void __attribute__((destructor)) libirecovery_deinitialize(void)
+{
+ thread_once(&deinit_once, _irecv_deinit);
+}
+#elif defined(WIN32)
+BOOL WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpReserved)
+{
+ switch (dwReason) {
+ case DLL_PROCESS_ATTACH:
+ thread_once(&init_once, _irecv_init);
+ break;
+ case DLL_PROCESS_DETACH:
+ thread_once(&deinit_once, _irecv_deinit);
+ break;
+ default:
+ break;
+ }
+ return 1;
+}
+#else
+#warning No compiler support for constructor/destructor attributes, some features might not be available.
+#endif
+
+#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, 256);
+ memset(buffer, 0, size);
+
+ ret = irecv_usb_control_transfer(client, 0x80, 0x06, (0x03 << 8) | desc_index, langid, data, 255, 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);
+ }
+
+ ptr = strstr(iboot_string, "CPRV:");
+ if (ptr != NULL) {
+ sscanf(ptr, "CPRV:%x", &client->device_info.cprv);
+ }
+
+ ptr = strstr(iboot_string, "CPFM:");
+ if (ptr != NULL) {
+ sscanf(ptr, "CPFM:%x", &client->device_info.cpfm);
+ }
+
+ ptr = strstr(iboot_string, "SCEP:");
+ if (ptr != NULL) {
+ sscanf(ptr, "SCEP:%x", &client->device_info.scep);
+ }
-int irecv_write_file(const char* filename, const void* data, size_t size);
-int irecv_read_file(const char* filename, char** data, uint32_t* size);
+ ptr = strstr(iboot_string, "BDID:");
+ if (ptr != NULL) {
+ uint64_t bdid = 0;
+ sscanf(ptr, "BDID:%" SCNx64, &bdid);
+ client->device_info.bdid = (unsigned int)bdid;
+ }
+
+ ptr = strstr(iboot_string, "ECID:");
+ if (ptr != NULL) {
+ sscanf(ptr, "ECID:%" SCNx64, &client->device_info.ecid);
+ }
+
+ ptr = strstr(iboot_string, "IBFL:");
+ if (ptr != NULL) {
+ sscanf(ptr, "IBFL:%x", &client->device_info.ibfl);
+ }
+
+ 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;
+ }
-irecv_error_t irecv_open(irecv_client_t* pclient) {
int i = 0;
- char serial[256];
+ 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, 256);
+ len = irecv_get_string_descriptor_ascii(client, 1, (unsigned char*) buf, 255);
+ 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
+
+void irecv_init(void)
+{
+#ifndef USE_DUMMY
+ thread_once(&init_once, _irecv_init);
+#endif
+}
+
+void irecv_exit(void)
+{
+#ifndef USE_DUMMY
+ thread_once(&deinit_once, _irecv_deinit);
+#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;
+}
+#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
+}
+
+#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, 256);
+ irecv_get_string_descriptor_ascii(client, usb_descriptor->iSerialNumber, (unsigned char*)serial_str, 255);
+ 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_handle* usb_handle = NULL;
struct libusb_device_descriptor usb_descriptor;
*pclient = NULL;
- libusb_init(&libirecovery_context);
- if(libirecovery_debug) {
- irecv_set_debug_level(libirecovery_debug);
- }
-
- irecv_error_t error = IRECV_E_SUCCESS;
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 == kRecoveryMode1 ||
- usb_descriptor.idProduct == kRecoveryMode2 ||
- usb_descriptor.idProduct == kRecoveryMode3 ||
- usb_descriptor.idProduct == kRecoveryMode4 ||
- usb_descriptor.idProduct == kDfuMode) {
+ 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);
- libusb_open(usb_device, &usb_handle);
- if (usb_handle == NULL) {
- libusb_free_device_list(usb_device_list, 1);
+ 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);
- libusb_exit(libirecovery_context);
+ if (ecid != 0) {
+ continue;
+ }
+ libusb_free_device_list(usb_device_list, 1);
return IRECV_E_UNABLE_TO_CONNECT;
}
- libusb_free_device_list(usb_device_list, 1);
- irecv_client_t client = (irecv_client_t) malloc(sizeof(struct irecv_client));
- if (client == NULL) {
- libusb_close(usb_handle);
- libusb_exit(libirecovery_context);
- return IRECV_E_OUT_OF_MEMORY;
+ 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;
+ }
- memset(client, '\0', sizeof(struct irecv_client));
- client->interface = 0;
- client->handle = usb_handle;
- client->mode = usb_descriptor.idProduct;
+ 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;
+ }
- error = irecv_set_configuration(client, 1);
- if (error != IRECV_E_SUCCESS) {
- 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);
+ }
+ }
- error = irecv_set_interface(client, 1, 1);
- if (error != IRECV_E_SUCCESS) {
- return error;
- }
+ if (error != IRECV_E_SUCCESS) {
+ debug("Failed to set interface, error %d\n", error);
+ irecv_close(client);
+ return error;
+ }
- /* cache usb serial */
- libusb_get_string_descriptor_ascii(client->handle, usb_descriptor.iSerialNumber, client->serial, 255);
+ 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;
+ }
- *pclient = client;
- return IRECV_E_SUCCESS;
- }
+ 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);
}
- return IRECV_E_UNABLE_TO_CONNECT;
+ 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_set_configuration(irecv_client_t client, int configuration) {
- if (client == NULL || client->handle == NULL) {
+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) {
@@ -119,45 +1907,199 @@ irecv_error_t irecv_set_configuration(irecv_client_t client, int configuration)
return IRECV_E_USB_CONFIGURATION;
}
}
+#endif
+ client->usb_config = configuration;
+#endif
- client->config = configuration;
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_set_interface(irecv_client_t client, int interface, int alt_interface) {
- if (client == NULL || client->handle == NULL) {
- return IRECV_E_NO_DEVICE;
+#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);
- if (client->interface == interface) {
- return IRECV_E_SUCCESS;
+ 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;
}
- debug("Setting to interface %d:%d\n", interface, alt_interface);
- if (libusb_claim_interface(client->handle, interface) < 0) {
+ 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;
}
- if (libusb_set_interface_alt_setting(client->handle, interface, alt_interface) < 0) {
+ 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;
}
- client->interface = interface;
- client->alt_interface = alt_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;
-irecv_error_t irecv_reset(irecv_client_t client) {
- if (client == NULL || client->handle == NULL) {
+ 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_event_subscribe(irecv_client_t client, irecv_event_type type, irecv_event_cb_t callback, void* user_data) {
+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;
@@ -165,9 +2107,11 @@ irecv_error_t irecv_event_subscribe(irecv_client_t client, irecv_event_type type
case IRECV_PROGRESS:
client->progress_callback = callback;
+ break;
case IRECV_CONNECTED:
client->connected_callback = callback;
+ break;
case IRECV_PRECOMMAND:
client->precommand_callback = callback;
@@ -179,15 +2123,21 @@ irecv_error_t irecv_event_subscribe(irecv_client_t client, irecv_event_type type
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) {
+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;
@@ -195,9 +2145,11 @@ irecv_error_t irecv_event_unsubscribe(irecv_client_t client, irecv_event_type ty
case IRECV_PROGRESS:
client->progress_callback = NULL;
+ break;
case IRECV_CONNECTED:
client->connected_callback = NULL;
+ break;
case IRECV_PRECOMMAND:
client->precommand_callback = NULL;
@@ -209,17 +2161,844 @@ irecv_error_t irecv_event_unsubscribe(irecv_client_t client, irecv_event_type ty
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, 256);
+#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));
+ 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);
+
+ error = iokit_usb_open_service(&client, device);
+ 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, 255);
+ 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) {
+ 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 NULL;
+ }
+
+ error = irecv_usb_set_interface(client, 0, 0);
+ 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 = 0;
+ 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) {
+ 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
}
-irecv_error_t irecv_close(irecv_client_t client) {
+irecv_error_t irecv_close(irecv_client_t client)
+{
+#ifdef USE_DUMMY
+ return IRECV_E_UNSUPPORTED;
+#else
if (client != NULL) {
- if(client->disconnected_callback != NULL) {
+ if (client->disconnected_callback != NULL) {
irecv_event_t event;
event.size = 0;
event.data = NULL;
@@ -227,114 +3006,164 @@ irecv_error_t irecv_close(irecv_client_t client) {
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) {
- libusb_release_interface(client->handle, client->interface);
+ 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;
}
-
- if (libirecovery_context != NULL) {
- libusb_exit(libirecovery_context);
- libirecovery_context = 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);
free(client);
client = NULL;
}
return IRECV_E_SUCCESS;
+#endif
}
-void irecv_set_debug_level(int level) {
+void irecv_set_debug_level(int level)
+{
libirecovery_debug = level;
- if(libirecovery_context) {
- libusb_set_debug(libirecovery_context, libirecovery_debug);
+#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
}
-static irecv_error_t irecv_send_command_raw(irecv_client_t client, unsigned char* command) {
+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) {
- length = 0xFF;
+ return IRECV_E_INVALID_INPUT;
}
if (length > 0) {
- int ret = libusb_control_transfer(client->handle, 0x40, 0, 0, 0, command, length + 1, 100);
- if ((ret < 0) || (ret != (length + 1))) {
- if (ret == LIBUSB_ERROR_PIPE)
- return IRECV_E_PIPE;
- if (ret == LIBUSB_ERROR_TIMEOUT)
- return IRECV_E_TIMEOUT;
- return IRECV_E_UNKNOWN_ERROR;
- }
+ 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(irecv_client_t client, unsigned char* command) {
+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 (client == NULL || client->handle == NULL) {
+ if (check_context(client) != IRECV_E_SUCCESS)
return IRECV_E_NO_DEVICE;
- }
unsigned int length = strlen(command);
if (length >= 0x100) {
- length = 0xFF;
+ return IRECV_E_INVALID_INPUT;
}
irecv_event_t event;
- if(client->precommand_callback != NULL) {
+ if (client->precommand_callback != NULL) {
event.size = length;
event.data = command;
event.type = IRECV_PRECOMMAND;
- if(client->precommand_callback(client, &event)) {
+ if (client->precommand_callback(client, &event)) {
return IRECV_E_SUCCESS;
}
}
- error = irecv_send_command_raw(client, command);
+ 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) {
+ if (client->postcommand_callback != NULL) {
event.size = length;
event.data = command;
event.type = IRECV_POSTCOMMAND;
- if(client->postcommand_callback(client, &event)) {
+ if (client->postcommand_callback(client, &event)) {
return IRECV_E_SUCCESS;
}
}
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_send_file(irecv_client_t client, const char* filename) {
- if (client == NULL || client->handle == NULL) {
+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;
}
- fseek(file, 0, SEEK_END);
- long length = ftell(file);
- fseek(file, 0, SEEK_SET);
+ struct stat fst;
+ if (fstat(fileno(file), &fst) < 0) {
+ return IRECV_E_UNKNOWN_ERROR;
+ }
+ size_t length = fst.st_size;
- unsigned char* buffer = (unsigned char*) malloc(length);
+ char* buffer = (char*)malloc(length);
if (buffer == NULL) {
fclose(file);
return IRECV_E_OUT_OF_MEMORY;
}
- long bytes = fread(buffer, 1, length, file);
+ size_t bytes = fread(buffer, 1, length, file);
fclose(file);
if (bytes != length) {
@@ -342,53 +3171,179 @@ irecv_error_t irecv_send_file(irecv_client_t client, const char* filename) {
return IRECV_E_UNKNOWN_ERROR;
}
- irecv_error_t error = irecv_send_buffer(client, buffer, length);
+ irecv_error_t error = irecv_send_buffer(client, (unsigned char*)buffer, length, options);
free(buffer);
+
return error;
+#endif
}
-irecv_error_t irecv_get_status(irecv_client_t client, unsigned int* status) {
- if (client == NULL || client->handle == NULL) {
+#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', 6);
- if (libusb_control_transfer(client->handle, 0xA1, 3, 0, 0, buffer, 6, 1000) != 6) {
+ if (irecv_usb_control_transfer(client, 0xA1, 3, 0, 0, buffer, 6, USB_TIMEOUT) != 6) {
*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 irecv_send_buffer(irecv_client_t client, unsigned char* buffer, unsigned long length) {
irecv_error_t error = 0;
- int recovery_mode = (client->mode != kDfuMode);
+ int recovery_mode = ((client->mode != IRECV_K_DFU_MODE) && (client->mode != IRECV_K_PORT_DFU_MODE) && (client->mode != IRECV_K_WTF_MODE));
- if (client == NULL || client->handle == NULL) {
+ if (check_context(client) != IRECV_E_SUCCESS)
return IRECV_E_NO_DEVICE;
- }
- int packet_size = recovery_mode ? 0x4000: 0x800;
+ 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 (!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 (recovery_mode) {
- error = libusb_control_transfer(client->handle, 0x41, 0, 0, 0, NULL, 0, 1000);
- if (error != IRECV_E_SUCCESS) {
- return error;
+ 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 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;
- double progress = 0;
unsigned long count = 0;
unsigned int status = 0;
int bytes = 0;
@@ -397,9 +3352,48 @@ irecv_error_t irecv_send_buffer(irecv_client_t client, unsigned char* buffer, un
/* Use bulk transfer for recovery mode and control transfer for DFU and WTF mode */
if (recovery_mode) {
- error = libusb_bulk_transfer(client->handle, 0x04, &buffer[i * packet_size], size, &bytes, 1000);
+ error = irecv_usb_bulk_transfer(client, 0x04, &buffer[i * packet_size], size, &bytes, USB_TIMEOUT);
} else {
- bytes = libusb_control_transfer(client->handle, 0x21, 1, 0, 0, &buffer[i * packet_size], size, 1000);
+ 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) {
@@ -415,44 +3409,81 @@ irecv_error_t irecv_send_buffer(irecv_client_t client, unsigned char* buffer, un
}
if (!recovery_mode && status != 5) {
- return IRECV_E_USB_UPLOAD;
+ 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) {
+ if (client->progress_callback != NULL) {
irecv_event_t event;
event.progress = ((double) count/ (double) length) * 100.0;
event.type = IRECV_PROGRESS;
- event.data = "Uploading";
+ event.data = (char*)"Uploading";
event.size = count;
client->progress_callback(client, &event);
} else {
- debug("Sent: %d bytes - %d of %d\n", bytes, count, length);
+ debug("Sent: %d bytes - %lu of %lu\n", bytes, count, length);
}
}
- if (!recovery_mode) {
- libusb_control_transfer(client->handle, 0x21, 1, 0, 0, buffer, 0, 1000);
- for (i = 0; i < 3; i++) {
+ 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);
}
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_receive(irecv_client_t client) {
- unsigned char buffer[BUFFER_SIZE];
+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 (client == NULL || client->handle == NULL) {
+
+ if (check_context(client) != IRECV_E_SUCCESS)
return IRECV_E_NO_DEVICE;
- }
int bytes = 0;
- while (libusb_bulk_transfer(client->handle, 0x81, buffer, BUFFER_SIZE, &bytes, 100) == 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;
@@ -460,155 +3491,288 @@ irecv_error_t irecv_receive(irecv_client_t client) {
event.data = buffer;
event.type = IRECV_RECEIVED;
if (client->received_callback(client, &event) != 0) {
- return IRECV_E_SUCCESS;
+ break;
}
}
} else break;
}
-
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_getenv(irecv_client_t client, const char* variable, char** value) {
+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 (client == NULL || client->handle == NULL) {
+
+ if (check_context(client) != IRECV_E_SUCCESS)
return IRECV_E_NO_DEVICE;
- }
*value = NULL;
- if(variable == NULL) {
- return IRECV_E_UNKNOWN_ERROR;
+ if (variable == NULL) {
+ return IRECV_E_INVALID_INPUT;
}
memset(command, '\0', sizeof(command));
snprintf(command, sizeof(command)-1, "getenv %s", variable);
- irecv_error_t error = irecv_send_command_raw(client, command);
- if(error == IRECV_E_PIPE)
+ 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)
+ }
+
+ if (error != IRECV_E_SUCCESS) {
return error;
+ }
- unsigned char* response = (unsigned char*) malloc(256);
+ char* response = (char*) malloc(256);
if (response == NULL) {
return IRECV_E_OUT_OF_MEMORY;
}
memset(response, '\0', 256);
- int ret = libusb_control_transfer(client->handle, 0xC0, 0, 0, 0, response, 255, 500);
- if (ret < 0)
- return IRECV_E_UNKNOWN_ERROR;
+ irecv_usb_control_transfer(client, 0xC0, 0, 0, 0, (unsigned char*) response, 255, USB_TIMEOUT);
*value = response;
+
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_get_cpid(irecv_client_t client, unsigned int* cpid) {
- if (client == NULL || client->handle == NULL) {
+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;
- }
- unsigned char* cpid_string = strstr(client->serial, "CPID:");
- if (cpid_string == NULL) {
- *cpid = 0;
- return IRECV_E_UNKNOWN_ERROR;
+ *value = 0;
+
+ char* response = (char*) malloc(256);
+ if (response == NULL) {
+ return IRECV_E_OUT_OF_MEMORY;
}
- sscanf(cpid_string, "CPID:%d", cpid);
+
+ memset(response, '\0', 256);
+ irecv_usb_control_transfer(client, 0xC0, 0, 0, 0, (unsigned char*) response, 255, USB_TIMEOUT);
+
+ *value = (unsigned int) *response;
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_get_bdid(irecv_client_t client, unsigned int* bdid) {
- if (client == NULL || client->handle == NULL) {
+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;
- }
- unsigned char* bdid_string = strstr(client->serial, "BDID:");
- if (bdid_string == NULL) {
- *bdid = 0;
- return IRECV_E_UNKNOWN_ERROR;
- }
- sscanf(bdid_string, "BDID:%d", bdid);
+ *mode = client->mode;
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_get_ecid(irecv_client_t client, unsigned long long* ecid) {
- if (client == NULL || client->handle == NULL) {
- return IRECV_E_NO_DEVICE;
- }
-
- unsigned char* ecid_string = strstr(client->serial, "ECID:");
- if (ecid_string == NULL) {
- *ecid = 0;
- return IRECV_E_UNKNOWN_ERROR;
- }
- sscanf(ecid_string, "ECID:%qX", ecid);
+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 IRECV_E_SUCCESS;
+ return &client->device_info;
+#endif
}
-irecv_error_t irecv_send_exploit(irecv_client_t client) {
- if (client == NULL || client->handle == NULL) {
+#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
- libusb_control_transfer(client->handle, 0x21, 2, 0, 0, NULL, 0, 100);
return IRECV_E_SUCCESS;
+#endif
}
-irecv_error_t irecv_execute_script(irecv_client_t client, const char* filename) {
+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 (client == NULL || client->handle == NULL) {
+ if (check_context(client) != IRECV_E_SUCCESS)
return IRECV_E_NO_DEVICE;
- }
- int file_size = 0;
- char* file_data = NULL;
- if(irecv_read_file(filename, &file_data, &file_size) < 0) {
- return IRECV_E_FILE_NOT_FOUND;
- }
+ char* body = strdup(script);
+ char* line = strtok(body, "\n");
- char* line = strtok(file_data, "\n");
- while(line != NULL) {
- if(line[0] != '#') {
+ while (line != NULL) {
+ if (line[0] != '#') {
error = irecv_send_command(client, line);
- if(error != IRECV_E_SUCCESS) {
- return error;
+ if (error != IRECV_E_SUCCESS) {
+ break;
}
error = irecv_receive(client);
- if(error != IRECV_E_SUCCESS) {
- return error;
+ 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) {
+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 (client == NULL || client->handle == NULL) {
+
+ if (check_context(client) != IRECV_E_SUCCESS)
return IRECV_E_NO_DEVICE;
- }
- if(variable == NULL || value == NULL) {
+ 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);
- if(error != IRECV_E_SUCCESS) {
+ 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) {
+const char* irecv_strerror(irecv_error_t error)
+{
switch (error) {
case IRECV_E_SUCCESS:
return "Command completed successfully";
@@ -646,6 +3810,9 @@ const char* irecv_strerror(irecv_error_t error) {
case IRECV_E_TIMEOUT:
return "Timeout talking to device";
+ case IRECV_E_UNSUPPORTED:
+ return "Operation unsupported by driver";
+
default:
return "Unknown error";
}
@@ -653,64 +3820,215 @@ const char* irecv_strerror(irecv_error_t error) {
return NULL;
}
-int irecv_write_file(const char* filename, const void* data, size_t size) {
- size_t bytes = 0;
- FILE* file = 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;
- debug("Writing data to %s\n", filename);
- file = fopen(filename, "wb");
- if (file == NULL) {
- error("read_file: Unable to open file %s\n", filename);
- return -1;
+ 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);
}
- bytes = fwrite(data, 1, size, file);
- fclose(file);
+ return IRECV_E_SUCCESS;
+#endif
+}
- if (bytes != size) {
- error("ERROR: Unable to write entire file: %s: %d of %d\n", filename, bytes, size);
- return -1;
+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;
}
- return 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
}
-int irecv_read_file(const char* filename, char** data, uint32_t* size) {
- size_t bytes = 0;
- size_t length = 0;
- FILE* file = NULL;
- char* buffer = NULL;
- debug("Reading data from %s\n", filename);
+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;
- *size = 0;
- *data = NULL;
+ if (check_context(client) != IRECV_E_SUCCESS)
+ return IRECV_E_NO_DEVICE;
- file = fopen(filename, "rb");
- if (file == NULL) {
- error("read_file: File %s not found\n", filename);
- return -1;
+ irecv_usb_control_transfer(client, 0x21, 1, 0, 0, 0, 0, USB_TIMEOUT);
+
+ for (i = 0; i < 3; i++){
+ irecv_get_status(client, &status);
}
- fseek(file, 0, SEEK_END);
- length = ftell(file);
- rewind(file);
+ irecv_reset(client);
- buffer = (char*) malloc(length);
- if(buffer == NULL) {
- error("ERROR: Out of memory\n");
- fclose(file);
- return -1;
+ 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;
}
- bytes = fread(buffer, 1, length, file);
- fclose(file);
- if(bytes != length) {
- error("ERROR: Unable to read entire file\n");
- free(buffer);
- return -1;
+ 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;
}
- *size = length;
- *data = buffer;
- return 0;
+ 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_close(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;
+
+ 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/tools/Makefile.am b/tools/Makefile.am
new file mode 100644
index 0000000..ebb085c
--- /dev/null
+++ b/tools/Makefile.am
@@ -0,0 +1,13 @@
+if BUILD_TOOLS
+AM_CPPFLAGS = -I$(top_srcdir)/include
+
+AM_CFLAGS = $(GLOBAL_CFLAGS) $(libusb_CFLAGS)
+AM_LDFLAGS = $(libusb_LIBS) -lreadline
+
+bin_PROGRAMS = irecovery
+
+irecovery_SOURCES = irecovery.c
+irecovery_CFLAGS = $(AM_CFLAGS)
+irecovery_LDFLAGS = $(AM_LDFLAGS)
+irecovery_LDADD = $(top_builddir)/src/libirecovery-1.0.la
+endif
diff --git a/tools/irecovery.c b/tools/irecovery.c
new file mode 100644
index 0000000..61d053a
--- /dev/null
+++ b/tools/irecovery.c
@@ -0,0 +1,707 @@
+/*
+ * irecovery.c
+ * Software frontend for iBoot/iBSS communication with iOS devices
+ *
+ * Copyright (c) 2012-2023 Nikias Bassen <nikias@gmx.li>
+ * Copyright (c) 2012-2015 Martin Szulecki <martin.szulecki@libimobiledevice.org>
+ * Copyright (c) 2010-2011 Chronic-Dev Team
+ * Copyright (c) 2010-2011 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
+
+#define TOOL_NAME "irecovery"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <string.h>
+#include <getopt.h>
+#include <inttypes.h>
+#include <libirecovery.h>
+#include <readline/readline.h>
+#include <readline/history.h>
+
+#ifdef WIN32
+#include <windows.h>
+#ifndef sleep
+#define sleep(n) Sleep(1000 * n)
+#endif
+#endif
+
+#define FILE_HISTORY_PATH ".irecovery"
+#define debug(...) if (verbose) fprintf(stderr, __VA_ARGS__)
+
+enum {
+ kNoAction,
+ kResetDevice,
+ kStartShell,
+ kSendCommand,
+ kSendFile,
+ kSendExploit,
+ kSendScript,
+ kShowMode,
+ kRebootToNormalMode,
+ kQueryInfo,
+ kListDevices
+};
+
+static unsigned int quit = 0;
+static unsigned int verbose = 0;
+
+void print_progress_bar(double progress);
+int received_cb(irecv_client_t client, const irecv_event_t* event);
+int progress_cb(irecv_client_t client, const irecv_event_t* event);
+int precommand_cb(irecv_client_t client, const irecv_event_t* event);
+int postcommand_cb(irecv_client_t client, const irecv_event_t* event);
+
+static void shell_usage()
+{
+ printf("Usage:\n");
+ printf(" /upload FILE\t\tsend FILE to device\n");
+ printf(" /limera1n [FILE]\trun limera1n exploit and send optional payload from FILE\n");
+ printf(" /deviceinfo\t\tprint device information (ECID, IMEI, etc.)\n");
+ printf(" /help\t\t\tshow this help\n");
+ printf(" /exit\t\t\texit interactive shell\n");
+}
+
+static const char* mode_to_str(int mode)
+{
+ switch (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:
+ return "Recovery";
+ break;
+ case IRECV_K_DFU_MODE:
+ return "DFU";
+ break;
+ case IRECV_K_PORT_DFU_MODE:
+ return "Port DFU";
+ break;
+ case IRECV_K_WTF_MODE:
+ return "WTF";
+ break;
+ default:
+ return "Unknown";
+ break;
+ }
+}
+
+static void buffer_read_from_filename(const char *filename, char **buffer, uint64_t *length)
+{
+ FILE *f;
+ uint64_t size;
+
+ *length = 0;
+
+ f = fopen(filename, "rb");
+ if (!f) {
+ return;
+ }
+
+ fseek(f, 0, SEEK_END);
+ size = ftell(f);
+ rewind(f);
+
+ if (size == 0) {
+ fclose(f);
+ return;
+ }
+
+ *buffer = (char*)malloc(sizeof(char)*(size+1));
+ fread(*buffer, sizeof(char), size, f);
+ fclose(f);
+
+ *length = size;
+}
+
+static void print_hex(unsigned char *buf, size_t len)
+{
+ size_t i;
+ for (i = 0; i < len; i++) {
+ printf("%02x", buf[i]);
+ }
+}
+
+static void print_device_info(irecv_client_t client)
+{
+ int ret, mode;
+ irecv_device_t device = NULL;
+ const struct irecv_device_info *devinfo = irecv_get_device_info(client);
+ if (devinfo) {
+ printf("CPID: 0x%04x\n", devinfo->cpid);
+ printf("CPRV: 0x%02x\n", devinfo->cprv);
+ printf("BDID: 0x%02x\n", devinfo->bdid);
+ printf("ECID: 0x%016" PRIx64 "\n", devinfo->ecid);
+ printf("CPFM: 0x%02x\n", devinfo->cpfm);
+ printf("SCEP: 0x%02x\n", devinfo->scep);
+ printf("IBFL: 0x%02x\n", devinfo->ibfl);
+ printf("SRTG: %s\n", (devinfo->srtg) ? devinfo->srtg : "N/A");
+ printf("SRNM: %s\n", (devinfo->srnm) ? devinfo->srnm : "N/A");
+ printf("IMEI: %s\n", (devinfo->imei) ? devinfo->imei : "N/A");
+ printf("NONC: ");
+ if (devinfo->ap_nonce) {
+ print_hex(devinfo->ap_nonce, devinfo->ap_nonce_size);
+ } else {
+ printf("N/A");
+ }
+ printf("\n");
+ printf("SNON: ");
+ if (devinfo->sep_nonce) {
+ print_hex(devinfo->sep_nonce, devinfo->sep_nonce_size);
+ } else {
+ printf("N/A");
+ }
+ printf("\n");
+ char* p = strstr(devinfo->serial_string, "PWND:[");
+ if (p) {
+ p+=6;
+ char* pend = strchr(p, ']');
+ if (pend) {
+ printf("PWND: %.*s\n", (int)(pend-p), p);
+ }
+ }
+ } else {
+ printf("Could not get device info?!\n");
+ }
+
+ ret = irecv_get_mode(client, &mode);
+ if (ret == IRECV_E_SUCCESS) {
+ switch (devinfo->pid) {
+ case 0x1881:
+ printf("MODE: DFU via Debug USB (KIS)\n");
+ break;
+ default:
+ printf("MODE: %s\n", mode_to_str(mode));
+ break;
+ }
+ }
+
+ irecv_devices_get_device_by_client(client, &device);
+ if (device) {
+ printf("PRODUCT: %s\n", device->product_type);
+ printf("MODEL: %s\n", device->hardware_model);
+ printf("NAME: %s\n", device->display_name);
+ }
+}
+
+static void print_devices()
+{
+ struct irecv_device *devices = irecv_devices_get_all();
+ struct irecv_device *device = NULL;
+ int i = 0;
+
+ for (i = 0; devices[i].product_type != NULL; i++) {
+ device = &devices[i];
+
+ printf("%s %s 0x%02x 0x%04x %s\n", device->product_type, device->hardware_model, device->board_id, device->chip_id, device->display_name);
+ }
+}
+
+static int _is_breq_command(const char* cmd)
+{
+ return (
+ !strcmp(cmd, "go")
+ || !strcmp(cmd, "bootx")
+ || !strcmp(cmd, "reboot")
+ || !strcmp(cmd, "memboot")
+ );
+}
+
+static void parse_command(irecv_client_t client, unsigned char* command, unsigned int size)
+{
+ char* cmd = strdup((char*)command);
+ char* action = strtok(cmd, " ");
+
+ if (!strcmp(cmd, "/exit")) {
+ quit = 1;
+ } else if (!strcmp(cmd, "/help")) {
+ shell_usage();
+ } else if (!strcmp(cmd, "/upload")) {
+ char* filename = strtok(NULL, " ");
+ debug("Uploading file %s\n", filename);
+ if (filename != NULL) {
+ irecv_send_file(client, filename, 0);
+ }
+ } else if (!strcmp(cmd, "/deviceinfo")) {
+ print_device_info(client);
+ } else if (!strcmp(cmd, "/limera1n")) {
+ char* filename = strtok(NULL, " ");
+ debug("Sending limera1n payload %s\n", filename);
+ if (filename != NULL) {
+ irecv_send_file(client, filename, 0);
+ }
+ irecv_trigger_limera1n_exploit(client);
+ } else if (!strcmp(cmd, "/execute")) {
+ char* filename = strtok(NULL, " ");
+ debug("Executing script %s\n", filename);
+ if (filename != NULL) {
+ char* buffer = NULL;
+ uint64_t buffer_length = 0;
+ buffer_read_from_filename(filename, &buffer, &buffer_length);
+ if (buffer) {
+ buffer[buffer_length] = '\0';
+ irecv_execute_script(client, buffer);
+ free(buffer);
+ } else {
+ printf("Could not read file '%s'\n", filename);
+ }
+ }
+ } else {
+ printf("Unsupported command %s. Use /help to get a list of available commands.\n", cmd);
+ }
+
+ free(action);
+}
+
+static void load_command_history()
+{
+ read_history(FILE_HISTORY_PATH);
+}
+
+static void append_command_to_history(char* cmd)
+{
+ add_history(cmd);
+ write_history(FILE_HISTORY_PATH);
+}
+
+static void init_shell(irecv_client_t client)
+{
+ irecv_error_t error = 0;
+ load_command_history();
+ irecv_event_subscribe(client, IRECV_PROGRESS, &progress_cb, NULL);
+ irecv_event_subscribe(client, IRECV_RECEIVED, &received_cb, NULL);
+ irecv_event_subscribe(client, IRECV_PRECOMMAND, &precommand_cb, NULL);
+ irecv_event_subscribe(client, IRECV_POSTCOMMAND, &postcommand_cb, NULL);
+ while (!quit) {
+ error = irecv_receive(client);
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s\n", irecv_strerror(error));
+ break;
+ }
+
+ char* cmd = readline("> ");
+ if (cmd && *cmd) {
+ if (_is_breq_command(cmd)) {
+ error = irecv_send_command_breq(client, cmd, 1);
+ } else {
+ error = irecv_send_command(client, cmd);
+ }
+ if (error != IRECV_E_SUCCESS) {
+ quit = 1;
+ }
+
+ append_command_to_history(cmd);
+ free(cmd);
+ }
+ }
+}
+
+int received_cb(irecv_client_t client, const irecv_event_t* event)
+{
+ if (event->type == IRECV_RECEIVED) {
+ int i = 0;
+ int size = event->size;
+ const char* data = event->data;
+ for (i = 0; i < size; i++) {
+ printf("%c", data[i]);
+ }
+ }
+
+ return 0;
+}
+
+int precommand_cb(irecv_client_t client, const irecv_event_t* event)
+{
+ if (event->type == IRECV_PRECOMMAND) {
+ if (event->data[0] == '/') {
+ parse_command(client, (unsigned char*)event->data, event->size);
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+int postcommand_cb(irecv_client_t client, const irecv_event_t* event)
+{
+ char* value = NULL;
+ char* action = NULL;
+ char* command = NULL;
+ char* argument = NULL;
+ irecv_error_t error = IRECV_E_SUCCESS;
+
+ if (event->type == IRECV_POSTCOMMAND) {
+ command = strdup(event->data);
+ action = strtok(command, " ");
+ if (!strcmp(action, "getenv")) {
+ argument = strtok(NULL, " ");
+ error = irecv_getenv(client, argument, &value);
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s\n", irecv_strerror(error));
+ free(command);
+ return error;
+ }
+ printf("%s\n", value);
+ free(value);
+ }
+
+ if (!strcmp(action, "reboot")) {
+ quit = 1;
+ }
+ }
+
+ free(command);
+
+ return 0;
+}
+
+int progress_cb(irecv_client_t client, const irecv_event_t* event)
+{
+ if (event->type == IRECV_PROGRESS) {
+ print_progress_bar(event->progress);
+ }
+
+ return 0;
+}
+
+void print_progress_bar(double progress)
+{
+ int i = 0;
+
+ if (progress < 0) {
+ return;
+ }
+
+ if (progress > 100) {
+ progress = 100;
+ }
+
+ printf("\r[");
+
+ for (i = 0; i < 50; i++) {
+ if (i < progress / 2) {
+ printf("=");
+ } else {
+ printf(" ");
+ }
+ }
+
+ printf("] %3.1f%%", progress);
+
+ fflush(stdout);
+
+ if (progress == 100) {
+ printf("\n");
+ }
+}
+
+static void print_usage(int argc, char **argv)
+{
+ char *name = NULL;
+ name = strrchr(argv[0], '/');
+ printf("Usage: %s [OPTIONS]\n", (name ? name + 1: argv[0]));
+ printf("\n");
+ printf("Interact with an iOS device in DFU or recovery mode.\n");
+ printf("\n");
+ printf("OPTIONS:\n");
+ printf(" -i, --ecid ECID\tconnect to specific device by its ECID\n");
+ printf(" -c, --command CMD\trun CMD on device\n");
+ printf(" -m, --mode\t\tprint current device mode\n");
+ printf(" -f, --file FILE\tsend file to device\n");
+ printf(" -k, --payload FILE\tsend limera1n usb exploit payload from FILE\n");
+ printf(" -r, --reset\t\treset client\n");
+ printf(" -n, --normal\t\treboot device into normal mode (exit recovery loop)\n");
+ printf(" -e, --script FILE\texecutes recovery script from FILE\n");
+ printf(" -s, --shell\t\tstart an interactive shell\n");
+ printf(" -q, --query\t\tquery device info\n");
+ printf(" -a, --devices\t\tlist information for all known devices\n");
+ printf(" -v, --verbose\t\tenable verbose output, repeat for higher verbosity\n");
+ printf(" -h, --help\t\tprints this usage information\n");
+ printf(" -V, --version\t\tprints version information\n");
+ printf("\n");
+ printf("Homepage: <" PACKAGE_URL ">\n");
+ printf("Bug Reports: <" PACKAGE_BUGREPORT ">\n");
+}
+
+int main(int argc, char* argv[])
+{
+ static struct option longopts[] = {
+ { "ecid", required_argument, NULL, 'i' },
+ { "command", required_argument, NULL, 'c' },
+ { "mode", no_argument, NULL, 'm' },
+ { "file", required_argument, NULL, 'f' },
+ { "payload", required_argument, NULL, 'k' },
+ { "reset", no_argument, NULL, 'r' },
+ { "normal", no_argument, NULL, 'n' },
+ { "script", required_argument, NULL, 'e' },
+ { "shell", no_argument, NULL, 's' },
+ { "query", no_argument, NULL, 'q' },
+ { "devices", no_argument, NULL, 'a' },
+ { "verbose", no_argument, NULL, 'v' },
+ { "help", no_argument, NULL, 'h' },
+ { "version", no_argument, NULL, 'V' },
+ { NULL, 0, NULL, 0 }
+ };
+ int i = 0;
+ int opt = 0;
+ int action = kNoAction;
+ uint64_t ecid = 0;
+ int mode = -1;
+ char* argument = NULL;
+ irecv_error_t error = 0;
+
+ char* buffer = NULL;
+ uint64_t buffer_length = 0;
+
+ if (argc == 1) {
+ print_usage(argc, argv);
+ return 0;
+ }
+
+ while ((opt = getopt_long(argc, argv, "i:vVhrsmnc:f:e:k:qa", longopts, NULL)) > 0) {
+ switch (opt) {
+ case 'i':
+ if (optarg) {
+ char* tail = NULL;
+ ecid = strtoull(optarg, &tail, 0);
+ if (tail && (tail[0] != '\0')) {
+ ecid = 0;
+ }
+ if (ecid == 0) {
+ fprintf(stderr, "ERROR: Could not parse ECID from argument '%s'\n", optarg);
+ return -1;
+ }
+ }
+ break;
+
+ case 'v':
+ verbose += 1;
+ break;
+
+ case 'h':
+ print_usage(argc, argv);
+ return 0;
+
+ case 'm':
+ action = kShowMode;
+ break;
+
+ case 'n':
+ action = kRebootToNormalMode;
+ break;
+
+ case 'r':
+ action = kResetDevice;
+ break;
+
+ case 's':
+ action = kStartShell;
+ break;
+
+ case 'f':
+ action = kSendFile;
+ argument = optarg;
+ break;
+
+ case 'c':
+ action = kSendCommand;
+ argument = optarg;
+ break;
+
+ case 'k':
+ action = kSendExploit;
+ argument = optarg;
+ break;
+
+ case 'e':
+ action = kSendScript;
+ argument = optarg;
+ break;
+
+ case 'q':
+ action = kQueryInfo;
+ break;
+
+ case 'a':
+ action = kListDevices;
+ print_devices();
+ return 0;
+
+ case 'V':
+ printf("%s %s\n", TOOL_NAME, PACKAGE_VERSION);
+ return 0;
+
+ default:
+ fprintf(stderr, "Unknown argument\n");
+ return -1;
+ }
+ }
+
+ if (action == kNoAction) {
+ fprintf(stderr, "ERROR: Missing action option\n");
+ print_usage(argc, argv);
+ return -1;
+ }
+
+ if (verbose)
+ irecv_set_debug_level(verbose);
+
+ irecv_client_t client = NULL;
+ for (i = 0; i <= 5; i++) {
+ debug("Attempting to connect... \n");
+
+ irecv_error_t err = irecv_open_with_ecid(&client, ecid);
+ if (err == IRECV_E_UNSUPPORTED) {
+ fprintf(stderr, "ERROR: %s\n", irecv_strerror(err));
+ return -1;
+ }
+ else if (err != IRECV_E_SUCCESS)
+ sleep(1);
+ else
+ break;
+
+ if (i == 5) {
+ fprintf(stderr, "ERROR: %s\n", irecv_strerror(err));
+ return -1;
+ }
+ }
+
+ irecv_device_t device = NULL;
+ irecv_devices_get_device_by_client(client, &device);
+ if (device)
+ debug("Connected to %s, model %s, cpid 0x%04x, bdid 0x%02x\n", device->product_type, device->hardware_model, device->chip_id, device->board_id);
+
+ const struct irecv_device_info *devinfo = irecv_get_device_info(client);
+
+ switch (action) {
+ case kResetDevice:
+ irecv_reset(client);
+ break;
+
+ case kSendFile:
+ irecv_event_subscribe(client, IRECV_PROGRESS, &progress_cb, NULL);
+ error = irecv_send_file(client, argument, IRECV_SEND_OPT_DFU_NOTIFY_FINISH);
+ debug("%s\n", irecv_strerror(error));
+ break;
+
+ case kSendCommand:
+ if (devinfo->pid == 0x1881) {
+ printf("Shell is not available in Debug USB (KIS) mode.\n");
+ break;
+ }
+ if (_is_breq_command(argument)) {
+ error = irecv_send_command_breq(client, argument, 1);
+ } else {
+ error = irecv_send_command(client, argument);
+ }
+ debug("%s\n", irecv_strerror(error));
+ break;
+
+ case kSendExploit:
+ if (devinfo->pid == 0x1881) {
+ printf("Shell is not available in Debug USB (KIS) mode.\n");
+ break;
+ }
+ if (argument != NULL) {
+ irecv_event_subscribe(client, IRECV_PROGRESS, &progress_cb, NULL);
+ error = irecv_send_file(client, argument, 0);
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s\n", irecv_strerror(error));
+ break;
+ }
+ }
+ error = irecv_trigger_limera1n_exploit(client);
+ debug("%s\n", irecv_strerror(error));
+ break;
+
+ case kStartShell:
+ if (devinfo->pid == 0x1881) {
+ printf("This feature is not supported in Debug USB (KIS) mode.\n");
+ break;
+ }
+ init_shell(client);
+ break;
+
+ case kSendScript:
+ if (devinfo->pid == 0x1881) {
+ printf("This feature is not supported in Debug USB (KIS) mode.\n");
+ break;
+ }
+ buffer_read_from_filename(argument, &buffer, &buffer_length);
+ if (buffer) {
+ buffer[buffer_length] = '\0';
+
+ error = irecv_execute_script(client, buffer);
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s\n", irecv_strerror(error));
+ }
+
+ free(buffer);
+ } else {
+ fprintf(stderr, "Could not read file '%s'\n", argument);
+ }
+ break;
+
+ case kShowMode: {
+ irecv_get_mode(client, &mode);
+ printf("%s Mode", mode_to_str(mode));
+ if (devinfo->pid == 0x1881) {
+ printf(" via Debug USB (KIS)");
+ }
+ printf("\n");
+ break;
+ }
+ case kRebootToNormalMode:
+ if (devinfo->pid == 0x1881) {
+ printf("This feature is not supported in Debug USB (KIS) mode.\n");
+ break;
+ }
+ error = irecv_setenv(client, "auto-boot", "true");
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s\n", irecv_strerror(error));
+ break;
+ }
+
+ error = irecv_saveenv(client);
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s\n", irecv_strerror(error));
+ break;
+ }
+
+ error = irecv_reboot(client);
+ if (error != IRECV_E_SUCCESS) {
+ debug("%s\n", irecv_strerror(error));
+ } else {
+ debug("%s\n", irecv_strerror(error));
+ }
+ break;
+
+ case kQueryInfo:
+ print_device_info(client);
+ break;
+
+ default:
+ fprintf(stderr, "Unknown action\n");
+ break;
+ }
+
+ irecv_close(client);
+
+ return 0;
+}
diff --git a/udev/39-libirecovery.rules.in b/udev/39-libirecovery.rules.in
new file mode 100644
index 0000000..ea9f93a
--- /dev/null
+++ b/udev/39-libirecovery.rules.in
@@ -0,0 +1,8 @@
+# Handle iOS devices in DFU and Recovery mode - for use with libirecovery
+
+# Change group and permissions of iOS devices in DFU, legacy WTF, and Recovery mode
+ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="122[27]|128[0-3]", @udev_activation_rule@
+
+# Handle checkra1n DFU mode
+ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="1338", @udev_activation_rule@
+
diff --git a/udev/Makefile.am b/udev/Makefile.am
new file mode 100644
index 0000000..2a7ad98
--- /dev/null
+++ b/udev/Makefile.am
@@ -0,0 +1,21 @@
+if WITH_UDEV
+edit = \
+ $(SED) -r \
+ -e 's|@udev_activation_rule[@]|$(udev_activation_rule)|g' \
+ < $< > $@ || rm $@
+
+udevrules_DATA = \
+ 39-libirecovery.rules
+
+39-libirecovery.rules: 39-libirecovery.rules.in
+ $(edit)
+
+EXTRA_DIST = \
+ 39-libirecovery.rules.in
+
+MAINTAINERCLEANFILES = \
+ 39-libirecovery.rules
+
+CLEANFILES = \
+ 39-libirecovery.rules
+endif