File libimobiledevice-glue-1.3.1+git18.20250213.obscpio of Package libimobiledevice-glue

07070100000000000041ED00000000000000000000000367AD5DE900000000000000000000000000000000000000000000003300000000libimobiledevice-glue-1.3.1+git18.20250213/.github07070100000001000041ED00000000000000000000000267AD5DE900000000000000000000000000000000000000000000003D00000000libimobiledevice-glue-1.3.1+git18.20250213/.github/workflows07070100000002000081A400000000000000000000000167AD5DE90000135E000000000000000000000000000000000000004700000000libimobiledevice-glue-1.3.1+git18.20250213/.github/workflows/build.ymlname: build

on:
  push:
  pull_request:
  schedule:
    - cron: '0 0 1 * *'

jobs:
  build-linux-ubuntu:
    runs-on: ubuntu-latest
    steps:
    - name: install dependencies
      run: |
          #sudo apt-get install cython
    - name: prepare environment
      run: |
          echo "target_triplet=`gcc -dumpmachine`" >> $GITHUB_ENV
    - name: fetch libplist
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libplist-latest_${{env.target_triplet}}
        repo: libimobiledevice/libplist
    - 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 libimobiledevice-glue.tar usr
    - name: publish artifact
      uses: actions/upload-artifact@v4
      with:
        name: libimobiledevice-glue-latest_${{env.target_triplet}}
        path: libimobiledevice-glue.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@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libplist-latest_macOS
        repo: libimobiledevice/libplist
    - 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 libimobiledevice-glue.tar usr
    - name: publish artifact
      uses: actions/upload-artifact@v4
      with:
        name: libimobiledevice-glue-latest_macOS
        path: libimobiledevice-glue.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@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libplist-latest_${{ matrix.arch }}-${{ env.dest }}
        repo: libimobiledevice/libplist
    - 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 libimobiledevice-glue.tar ${{ env.dest }}
    - name: publish artifact
      uses: actions/upload-artifact@v4
      with:
        name: libimobiledevice-glue-latest_${{ matrix.arch }}-${{ env.dest }}
        path: libimobiledevice-glue.tar
07070100000003000081A400000000000000000000000167AD5DE90000022E000000000000000000000000000000000000003600000000libimobiledevice-glue-1.3.1+git18.20250213/.gitignore# git-ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
*.[oa]
*~
*.po
*.lo
*.la
autom4te.cache/*
*.in
*/.deps/*
m4/*
swig/*
*.swp
*.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
py-compile
stamp-h1
src/.libs
src/libimobiledevice-glue-1.0.pc
.idea/
.DS_Store
.vscode/07070100000004000081A400000000000000000000000167AD5DE900006742000000000000000000000000000000000000003300000000libimobiledevice-glue-1.3.1+git18.20250213/COPYING		  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!
07070100000005000081A400000000000000000000000167AD5DE900000143000000000000000000000000000000000000003700000000libimobiledevice-glue-1.3.1+git18.20250213/Makefile.amAUTOMAKE_OPTIONS = foreign
ACLOCAL_AMFLAGS = -I m4
SUBDIRS = src include

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

indent:
	indent -kr -ut -ts4 -l120 src/*.c src/*.h

07070100000006000081A400000000000000000000000167AD5DE9000003C7000000000000000000000000000000000000003000000000libimobiledevice-glue-1.3.1+git18.20250213/NEWSVersion 1.3.1
~~~~~~~~~~~~~

- Fixes:
  * socket: Fix scope_id lookup for socket_connect_addr()

Version 1.3.0
~~~~~~~~~~~~~

- Changes:
  * Add SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 functions to interface
  * socket: Create an IPv4 compatible IPv6 socket when NULL is passed to socket_create
  * socket: Haiku compilation fixes

Version 1.2.0
~~~~~~~~~~~~~

- Changes:
  * Add helper code to deal with NSKeyedArchiver plist data

- Bugfixes:
  * socket: Make sure errno is always set on error, and always return a meaningful error code

Version 1.1.0
~~~~~~~~~~~~~

- Changes:
  * socket: Use poll() - when available - instead of select()
  * socket: Allow NULL as address for socket_create() and socket_connect()
  * win32: Remove windows.h from public headers
  * Add version function to interface

- Bugfixes:
  * opack: Fixed 32bit buffer overflow
  * opack: Fix parsing of 32 and 64 bit packed values

Version 1.0.0
~~~~~~~~~~~~~

First public release.
07070100000007000081A400000000000000000000000167AD5DE900001EB8000000000000000000000000000000000000003500000000libimobiledevice-glue-1.3.1+git18.20250213/README.md# libimobiledevice-glue

Library with common code used by the libraries and tools around the
**libimobiledevice** project.

![](https://github.com/libimobiledevice/libimobiledevice-glue/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

The main functionality provided by this library are **socket** helper
functions and a platform independent **thread/mutex** implementation.
Besides that it comes with a number of string, file, and plist helper
functions, as well as some other commonly used code that was originally
duplicated in the dedicated projects.

Tested on Linux, macOS, and Windows.

## Projects using this library

- [libusbmuxd](https://github.com/libimobiledevice/libusbmuxd)
- [libimobiledevice](https://github.com/libimobiledevice/libimobiledevice)
- [usbmuxd](https://github.com/libimobiledevice/usbmuxd)
- [libirecovery](https://github.com/libimobiledevice/libirecovery)
- [idevicerestore](https://github.com/libimobiledevice/idevicerestore)

## 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.

libimobiledevice-glue requires [libplist](https://github.com/libimobiledevice/libplist).
Check the [Building](https://github.com/libimobiledevice/libplist?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 \
  	libplist-dev
  ```

  In case libplist-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/libimobiledevice-glue/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 libimobiledevice-glue 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/libimobiledevice-glue
  cd libimobiledevice-glue
  ```

  Configure the source tree for building:
  ```shell
  ./autogen.sh
  ```

* **From release tarball (.tar.bz2)**

  When using an official [release tarball](https://github.com/libimobiledevice/libimobiledevice-glue/releases) (`libimobiledevice-glue-x.y.z.tar.bz2`)
  the procedure is slightly different.

  Extract the tarball:
  ```shell
  tar xjf libimobiledevice-glue-x.y.z.tar.bz2
  cd libimobiledevice-glue-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 libimobiledevice-glue 1.0.1:
-------------------------------------------

  Install prefix: .........: /usr/local

  Now type 'make' to build libimobiledevice-glue 1.0.1,
  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

This library is directly used by libusbmuxd, libimobiledevice, etc., so there
is no need to do anything in particular. Feel free to use it in your project,
check the header files for available functions. A documentation might be added
later.

## 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

## Links

* Homepage: https://libimobiledevice.org/
* Repository: https://github.com/libimobiledevice/libimobiledevice-glue.git
* Repository (Mirror): https://git.libimobiledevice.org/libimobiledevice-glue.git
* Issue Tracker: https://github.com/libimobiledevice/libimobiledevice-glue/issues
* Mailing List: https://lists.libimobiledevice.org/mailman/listinfo/libimobiledevice-devel
* Twitter: https://twitter.com/libimobiledev

## License

This library 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-10-09

07070100000008000081ED00000000000000000000000167AD5DE90000016D000000000000000000000000000000000000003600000000libimobiledevice-glue-1.3.1+git18.20250213/autogen.sh#!/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
07070100000009000081A400000000000000000000000167AD5DE90000100E000000000000000000000000000000000000003800000000libimobiledevice-glue-1.3.1+git18.20250213/configure.ac#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.

AC_PREREQ([2.68])
AC_INIT([libimobiledevice-glue], [m4_esyscmd(./git-version-gen $RELEASE_VERSION)], [https://github.com/libimobiledevice/libimobiledevice-glue/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
LIBIMOBILEDEVICE_GLUE_SO_VERSION=3:1:3

# Check if we have a version defined
if test -z $PACKAGE_VERSION; then
  AC_MSG_ERROR([PACKAGE_VERSION is not defined. Make sure to configure a source tree checked out from git or that .tarball-version is present.])
fi

dnl Minimum package versions
LIBPLIST_VERSION=2.3.0

AC_SUBST(LIBIMOBILEDEVICE_GLUE_SO_VERSION)
AC_SUBST(LIBPLIST_VERSION)

# Checks for programs.
AC_PROG_CC
#AC_PROG_CXX
AM_PROG_CC_C_O
LT_INIT

# Checks for libraries.
PKG_CHECK_MODULES(libplist, libplist-2.0 >= $LIBPLIST_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([asprintf strcasecmp strdup strerror strndup stpcpy vasprintf getifaddrs poll])
# Checks for additional library requirements
AC_SEARCH_LIBS(socket, network)

AC_CHECK_HEADER(endian.h, [ac_cv_have_endian_h="yes"], [ac_cv_have_endian_h="no"])
if test "x$ac_cv_have_endian_h" = "xno"; then
  AC_DEFINE(__LITTLE_ENDIAN,1234,[little endian])
  AC_DEFINE(__BIG_ENDIAN,4321,[big endian])
  AC_C_BIGENDIAN([ac_cv_c_bigendian="yes"], [ac_cv_c_bigendian="no"], [], [])
  if test "x$ac_cv_c_bigendian" = "xyes"; then
    AC_DEFINE(__BYTE_ORDER,4321,[big endian byte order])
  else
    AC_DEFINE(__BYTE_ORDER,1234,[little endian byte order])
  fi
fi

# Check for operating system
AC_MSG_CHECKING([for platform-specific build settings])
case ${host_os} in
  *mingw32*|*cygwin*)
    AC_MSG_RESULT([${host_os}])
    win32=true
    AC_DEFINE(WINVER, 0x0501, [minimum Windows version])
    ;;
  darwin*)
    AC_MSG_RESULT([${host_os}])
    AX_PTHREAD([], [AC_MSG_ERROR([pthread is required to build $PACKAGE])])
    AC_CHECK_FUNCS([pthread_once pthread_cancel])
    ;;
  *)
    AC_MSG_RESULT([${host_os}])
    AX_PTHREAD([], [AC_MSG_ERROR([pthread is required to build $PACKAGE_NAME])])
    AC_CHECK_FUNC(pthread_cancel, [AC_DEFINE(HAVE_PTHREAD_CANCEL)], [
      AC_CHECK_LIB(pthread, [pthread_cancel],[AC_DEFINE(HAVE_PTHREAD_CANCEL)])
    ])
    AC_CHECK_FUNC(pthread_once, [AC_DEFINE(HAVE_PTHREAD_ONCE)], [
      AC_CHECK_LIB(pthread, [pthread_once], [], [AC_MSG_ERROR([pthread with pthread_once required to build $PACKAGE_NAME])])
    ])
    ;;
esac
AM_CONDITIONAL(WIN32, test x$win32 = xtrue)

AC_CHECK_MEMBER(struct dirent.d_type, AC_DEFINE(HAVE_DIRENT_D_TYPE, 1, [define if struct dirent has member d_type]),, [#include <dirent.h>])

AS_COMPILER_FLAGS(GLOBAL_CFLAGS, "-Wall -Wextra -Wmissing-declarations -Wredundant-decls -Wshadow -Wpointer-arith -Wwrite-strings -Wswitch-default -Wno-unused-parameter -fsigned-char -fvisibility=hidden")

if test "x$enable_static" = "xyes" -a "x$enable_shared" = "xno"; then
  GLOBAL_CFLAGS+=" -DLIMD_GLUE_STATIC"
fi

AC_SUBST(GLOBAL_CFLAGS)

# check for large file support
AC_SYS_LARGEFILE

m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])

AC_CONFIG_FILES([
Makefile
src/Makefile
src/libimobiledevice-glue-1.0.pc
include/Makefile
])
AC_OUTPUT

echo "
Configuration for $PACKAGE $VERSION:
-------------------------------------------

  Install prefix: .........: $prefix

  Now type 'make' to build $PACKAGE $VERSION,
  and then 'make install' for installation.
"
0707010000000A000081ED00000000000000000000000167AD5DE900000243000000000000000000000000000000000000003B00000000libimobiledevice-glue-1.3.1+git18.20250213/git-version-gen#!/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"
0707010000000B000041ED00000000000000000000000367AD5DE900000000000000000000000000000000000000000000003300000000libimobiledevice-glue-1.3.1+git18.20250213/include0707010000000C000081A400000000000000000000000167AD5DE9000001B8000000000000000000000000000000000000003F00000000libimobiledevice-glue-1.3.1+git18.20250213/include/Makefile.amEXTRA_DIST = \
        endianness.h

nobase_include_HEADERS = \
	libimobiledevice-glue/glue.h \
	libimobiledevice-glue/socket.h \
	libimobiledevice-glue/thread.h \
	libimobiledevice-glue/utils.h \
	libimobiledevice-glue/nskeyedarchive.h \
	libimobiledevice-glue/collection.h \
	libimobiledevice-glue/termcolors.h \
	libimobiledevice-glue/cbuf.h \
	libimobiledevice-glue/opack.h \
	libimobiledevice-glue/tlv.h \
	libimobiledevice-glue/sha.h
0707010000000D000081A400000000000000000000000167AD5DE9000009E3000000000000000000000000000000000000004000000000libimobiledevice-glue-1.3.1+git18.20250213/include/endianness.h#ifndef ENDIANNESS_H
#define ENDIANNESS_H

#ifndef __LITTLE_ENDIAN
#define __LITTLE_ENDIAN 1234
#endif

#ifndef __BIG_ENDIAN
#define __BIG_ENDIAN 4321
#endif

#ifndef __BYTE_ORDER
#ifdef __LITTLE_ENDIAN__
#define __BYTE_ORDER __LITTLE_ENDIAN
#else
#ifdef __BIG_ENDIAN__
#define __BYTE_ORDER __BIG_ENDIAN
#endif
#endif
#endif

#ifndef be16toh
#if __BYTE_ORDER == __BIG_ENDIAN
#define be16toh(x) (x)
#else
#define be16toh(x) ((((x) & 0xFF00) >> 8) | (((x) & 0x00FF) << 8))
#endif
#endif

#ifndef htobe16
#define htobe16 be16toh
#endif

#ifndef le16toh
#if __BYTE_ORDER == __BIG_ENDIAN
#define le16toh(x) ((((x) & 0xFF00) >> 8) | (((x) & 0x00FF) << 8))
#else
#define le16toh(x) (x)
#endif
#endif

#ifndef htole16
#define htole16 le16toh
#endif

#ifndef __bswap_32
#define __bswap_32(x) ((((x) & 0xFF000000) >> 24) \
                    | (((x) & 0x00FF0000) >> 8) \
                    | (((x) & 0x0000FF00) << 8) \
                    | (((x) & 0x000000FF) << 24))
#endif

#ifndef be32toh
#if __BYTE_ORDER == __BIG_ENDIAN
#define be32toh(x) (x)
#else
#define be32toh(x) __bswap_32(x)
#endif
#endif

#ifndef htobe32
#define htobe32 be32toh
#endif

#ifndef le32toh
#if __BYTE_ORDER == __BIG_ENDIAN
#define le32toh(x) __bswap_32(x)
#else
#define le32toh(x) (x)
#endif
#endif

#ifndef htole32
#define htole32 le32toh
#endif

#ifndef __bswap_64
#define __bswap_64(x) ((((x) & 0xFF00000000000000ull) >> 56) \
                    | (((x) & 0x00FF000000000000ull) >> 40) \
                    | (((x) & 0x0000FF0000000000ull) >> 24) \
                    | (((x) & 0x000000FF00000000ull) >> 8) \
                    | (((x) & 0x00000000FF000000ull) << 8) \
                    | (((x) & 0x0000000000FF0000ull) << 24) \
                    | (((x) & 0x000000000000FF00ull) << 40) \
                    | (((x) & 0x00000000000000FFull) << 56))
#endif

#ifndef htobe64
#if __BYTE_ORDER == __BIG_ENDIAN
#define htobe64(x) (x)
#else
#define htobe64(x) __bswap_64(x)
#endif
#endif

#ifndef be64toh
#define be64toh htobe64
#endif

#ifndef le64toh
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define le64toh(x) (x)
#else
#define le64toh(x) __bswap_64(x)
#endif
#endif

#ifndef htole64
#define htole64 le64toh
#endif

#if (defined(__BIG_ENDIAN__) \
     && !defined(__FLOAT_WORD_ORDER__)) \
 || (defined(__FLOAT_WORD_ORDER__) \
     && __FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__)
#define float_bswap64(x) __bswap_64(x)
#define float_bswap32(x) __bswap_32(x)
#else
#define float_bswap64(x) (x)
#define float_bswap32(x) (x)
#endif

#endif /* ENDIANNESS_H */
0707010000000E000041ED00000000000000000000000267AD5DE900000000000000000000000000000000000000000000004900000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue0707010000000F000081A400000000000000000000000167AD5DE90000052C000000000000000000000000000000000000005000000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/cbuf.h/*
 * cbuf.h
 * Simple char buffer implementation.
 *
 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef __CBUF_H
#define __CBUF_H

#include <libimobiledevice-glue/glue.h>

struct char_buf {
	unsigned char* data;
	unsigned int length;
	unsigned int capacity;
};

#ifdef __cplusplus
extern "C" {
#endif

LIMD_GLUE_API struct char_buf* char_buf_new();
LIMD_GLUE_API void char_buf_free(struct char_buf* cbuf);
LIMD_GLUE_API void char_buf_append(struct char_buf* cbuf, unsigned int length, unsigned char* data);

#ifdef __cplusplus
}
#endif

#endif /* __CBUF_H */
07070100000010000081A400000000000000000000000167AD5DE900000770000000000000000000000000000000000000005600000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/collection.h/*
 * collection.h
 *
 * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
 * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef COLLECTION_H
#define COLLECTION_H

#include <libimobiledevice-glue/glue.h>

struct collection {
	void **list;
	int capacity;
};

#ifdef __cplusplus
extern "C" {
#endif

LIMD_GLUE_API void collection_init(struct collection *col);
LIMD_GLUE_API void collection_add(struct collection *col, void *element);
LIMD_GLUE_API int collection_remove(struct collection *col, void *element);
LIMD_GLUE_API int collection_count(struct collection *col);
LIMD_GLUE_API void collection_free(struct collection *col);
LIMD_GLUE_API void collection_copy(struct collection *dest, struct collection *src);

#define MERGE_(a,b) a ## _ ## b
#define LABEL_(a,b) MERGE_(a, b)
#define UNIQUE_VAR(a) LABEL_(a, __LINE__)

#define FOREACH(var, col) \
	do { \
		int UNIQUE_VAR(_iter); \
		for(UNIQUE_VAR(_iter)=0; UNIQUE_VAR(_iter)<(col)->capacity; UNIQUE_VAR(_iter)++) { \
			if(!(col)->list[UNIQUE_VAR(_iter)]) continue; \
			var = (col)->list[UNIQUE_VAR(_iter)];

#define ENDFOREACH \
		} \
	} while(0);

#ifdef __cplusplus
}
#endif

#endif
07070100000011000081A400000000000000000000000167AD5DE9000004BD000000000000000000000000000000000000005000000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/glue.h/*
 * glue.h
 * Common definitions
 *
 * Copyright (c) 2024 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef __GLUE_H
#define __GLUE_H

#ifndef LIMD_GLUE_API
  #ifdef LIMD_GLUE_STATIC
    #define LIMD_GLUE_API
  #elif defined(_WIN32)
    #define LIMD_GLUE_API __declspec(dllimport)
  #else
    #define LIMD_GLUE_API
  #endif
#endif

#ifdef __cplusplus
extern "C" {
#endif

LIMD_GLUE_API const char* libimobiledevice_glue_version();

#ifdef __cplusplus
}
#endif

#endif
07070100000012000081A400000000000000000000000167AD5DE9000010DE000000000000000000000000000000000000005A00000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/nskeyedarchive.h/*
 * nskeyedarchive.h
 * Helper code to work with plist files containing NSKeyedArchiver data.
 *
 * Copyright (c) 2019 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#ifndef __NSKEYEDARCHIVE_H
#define __NSKEYEDARCHIVE_H

#include <stdint.h>
#include <libimobiledevice-glue/glue.h>
#include <plist/plist.h>

enum nskeyedarchive_class_type_t {
	NSTYPE_INTEGER = 1,
	NSTYPE_BOOLEAN,
	NSTYPE_CHARS,
	NSTYPE_STRING,
	NSTYPE_REAL,
	NSTYPE_ARRAY,
	NSTYPE_DATA,
	NSTYPE_INTREF,
	NSTYPE_NSMUTABLESTRING,
	NSTYPE_NSSTRING,
	NSTYPE_NSMUTABLEARRAY,
	NSTYPE_NSARRAY,
	NSTYPE_NSMUTABLEDICTIONARY,
	NSTYPE_NSDICTIONARY,
	NSTYPE_NSDATE,
	NSTYPE_NSURL,
	NSTYPE_NSMUTABLEDATA,
	NSTYPE_NSDATA,
	NSTYPE_NSKEYEDARCHIVE,
	NSTYPE_FROM_PLIST
};

typedef struct nskeyedarchive_st *nskeyedarchive_t;

#ifdef __cplusplus
extern "C" {
#endif

LIMD_GLUE_API nskeyedarchive_t nskeyedarchive_new(void);
LIMD_GLUE_API nskeyedarchive_t nskeyedarchive_new_from_plist(plist_t plist);
LIMD_GLUE_API nskeyedarchive_t nskeyedarchive_new_from_data(const void* data, uint32_t size);
LIMD_GLUE_API void nskeyedarchive_free(nskeyedarchive_t ka);

LIMD_GLUE_API void nskeyedarchive_set_top_ref_key_name(nskeyedarchive_t ka, const char* keyname);

LIMD_GLUE_API uint64_t nskeyedarchive_add_top_class(nskeyedarchive_t ka, const char* classname, ...);
LIMD_GLUE_API void nskeyedarchive_add_top_class_uid(nskeyedarchive_t ka, uint64_t uid);
LIMD_GLUE_API void nskeyedarchive_append_class(nskeyedarchive_t ka, const char* classname, ...);
LIMD_GLUE_API void nskeyedarchive_append_object(nskeyedarchive_t ka, plist_t object);

LIMD_GLUE_API void nskeyedarchive_nsarray_append_item(nskeyedarchive_t ka, uint64_t uid, enum nskeyedarchive_class_type_t type, ...);
LIMD_GLUE_API void nskeyedarchive_nsdictionary_add_item(nskeyedarchive_t ka, uint64_t uid, const char* key, enum nskeyedarchive_class_type_t type, ...);

LIMD_GLUE_API void nskeyedarchive_append_class_type_v(nskeyedarchive_t ka, enum nskeyedarchive_class_type_t type, va_list* va);
LIMD_GLUE_API void nskeyedarchive_append_class_type(nskeyedarchive_t ka, enum nskeyedarchive_class_type_t type, ...);

LIMD_GLUE_API void nskeyedarchive_merge_object(nskeyedarchive_t ka, nskeyedarchive_t pka, plist_t object);

LIMD_GLUE_API void nskeyedarchive_print(nskeyedarchive_t ka);
LIMD_GLUE_API plist_t nskeyedarchive_get_plist_ref(nskeyedarchive_t ka);
LIMD_GLUE_API plist_t nskeyedarchive_get_object_by_uid(nskeyedarchive_t ka, uint64_t uid);
LIMD_GLUE_API plist_t nskeyedarchive_get_class_by_uid(nskeyedarchive_t ka, uint64_t uid);
LIMD_GLUE_API plist_t nskeyedarchive_get_objects(nskeyedarchive_t ka);

LIMD_GLUE_API uint64_t nskeyedarchive_get_class_uid(nskeyedarchive_t ka, const char* classref);
LIMD_GLUE_API const char* nskeyedarchive_get_classname(nskeyedarchive_t ka, uint64_t uid);

LIMD_GLUE_API void nskeyedarchive_set_class_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, enum nskeyedarchive_class_type_t proptype, ...);
LIMD_GLUE_API int nskeyedarchive_get_class_uint64_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, uint64_t* value);
LIMD_GLUE_API int nskeyedarchive_get_class_int_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, int* value);
LIMD_GLUE_API int nskeyedarchive_get_class_string_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, char** value);
LIMD_GLUE_API int nskeyedarchive_get_class_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, plist_t* value);

LIMD_GLUE_API plist_t nskeyedarchive_to_plist(nskeyedarchive_t ka);

#ifdef __cplusplus
}
#endif

#endif
07070100000013000081A400000000000000000000000167AD5DE9000004FB000000000000000000000000000000000000005100000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/opack.h/*
 * opack.h
 * "opack" format encoder/decoder implementation.
 *
 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#ifndef __OPACK_H
#define __OPACK_H

#include <libimobiledevice-glue/glue.h>
#include <plist/plist.h>

#ifdef __cplusplus
extern "C" {
#endif

LIMD_GLUE_API void opack_encode_from_plist(plist_t plist, unsigned char** out, unsigned int* out_len);
LIMD_GLUE_API int opack_decode_to_plist(unsigned char* buf, unsigned int buf_len, plist_t* plist_out);

#ifdef __cplusplus
}
#endif

#endif /* __OPACK_H */
07070100000014000081A400000000000000000000000167AD5DE900000AFB000000000000000000000000000000000000004F00000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/sha.h#ifndef __SHA_H
#define __SHA_H

#include <stddef.h>
#include <stdint.h>

#include <libimobiledevice-glue/glue.h>

#ifdef __cplusplus
extern "C" {
#endif

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

/* SHA-1 */
typedef struct sha1_context_ {
    uint64_t length;
    uint32_t state[5];
    size_t curlen;
    unsigned char buf[64];
} sha1_context;

#define SHA1_DIGEST_LENGTH 20

LIMD_GLUE_API int sha1_init(sha1_context * md);
LIMD_GLUE_API int sha1_final(sha1_context * md, unsigned char *out);
LIMD_GLUE_API int sha1_update(sha1_context * md, const void *data, size_t inlen);
LIMD_GLUE_API int sha1(const unsigned char *message, size_t message_len, unsigned char *out);

/* SHA-256 */
typedef struct sha256_context_ {
    uint64_t length;
    uint32_t state[8];
    size_t curlen;
    unsigned char buf[64];
    int num_dwords;
} sha256_context;

#define SHA256_DIGEST_LENGTH 32

LIMD_GLUE_API int sha256_init(sha256_context * md);
LIMD_GLUE_API int sha256_final(sha256_context * md, unsigned char *out);
LIMD_GLUE_API int sha256_update(sha256_context * md, const void *data, size_t inlen);
LIMD_GLUE_API int sha256(const unsigned char *message, size_t message_len, unsigned char *out);

/* SHA-224 */
#define sha224_context sha256_context

#define SHA224_DIGEST_LENGTH 28

LIMD_GLUE_API int sha224_init(sha224_context * md);
LIMD_GLUE_API int sha224_final(sha224_context * md, unsigned char *out);
LIMD_GLUE_API int sha224_update(sha224_context * md, const void *data, size_t inlen);
LIMD_GLUE_API int sha224(const unsigned char *message, size_t message_len, unsigned char *out);

/* SHA-512 */
typedef struct sha512_context_ {
    uint64_t length, state[8];
    size_t curlen;
    unsigned char buf[128];
    int num_qwords;
} sha512_context;

#define SHA512_DIGEST_LENGTH 64

LIMD_GLUE_API int sha512_init(sha512_context * md);
LIMD_GLUE_API int sha512_final(sha512_context * md, unsigned char *out);
LIMD_GLUE_API int sha512_update(sha512_context * md, const void *data, size_t inlen);
LIMD_GLUE_API int sha512(const unsigned char *message, size_t message_len, unsigned char *out);

/* SHA-384 */
#define sha384_context sha512_context

#define SHA384_DIGEST_LENGTH 48

LIMD_GLUE_API int sha384_init(sha384_context * md);
LIMD_GLUE_API int sha384_final(sha384_context * md, unsigned char *out);
LIMD_GLUE_API int sha384_update(sha384_context * md, const void *data, size_t inlen);
LIMD_GLUE_API int sha384(const unsigned char *message, size_t message_len, unsigned char *out);

#ifdef __cplusplus
}
#endif

#endif
07070100000015000081A400000000000000000000000167AD5DE9000009FB000000000000000000000000000000000000005200000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/socket.h/*
 * socket.h
 *
 * Copyright (C) 2012-2020 Nikias Bassen <nikias@gmx.li>
 * Copyright (C) 2012 Martin Szulecki <m.szulecki@libimobiledevice.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef SOCKET_SOCKET_H
#define SOCKET_SOCKET_H

#include <stdlib.h>
#include <stdint.h>

enum fd_mode {
	FDM_READ,
	FDM_WRITE,
	FDM_EXCEPT
};
typedef enum fd_mode fd_mode;

#ifdef _WIN32
#include <winsock2.h>
#define SHUT_RD SD_READ
#define SHUT_WR SD_WRITE
#define SHUT_RDWR SD_BOTH
#else
#include <sys/socket.h>
#endif

#include <libimobiledevice-glue/glue.h>

#ifdef __cplusplus
extern "C" {
#endif

#ifndef _WIN32
LIMD_GLUE_API int socket_create_unix(const char *filename);
LIMD_GLUE_API int socket_connect_unix(const char *filename);
#endif
LIMD_GLUE_API int socket_create(const char *addr, uint16_t port);
LIMD_GLUE_API int socket_connect_addr(struct sockaddr *addr, uint16_t port);
LIMD_GLUE_API int socket_connect(const char *addr, uint16_t port);
LIMD_GLUE_API int socket_check_fd(int fd, fd_mode fdm, unsigned int timeout);
LIMD_GLUE_API int socket_accept(int fd, uint16_t port);

LIMD_GLUE_API int socket_shutdown(int fd, int how);
LIMD_GLUE_API int socket_close(int fd);

LIMD_GLUE_API int socket_receive(int fd, void *data, size_t length);
LIMD_GLUE_API int socket_peek(int fd, void *data, size_t length);
LIMD_GLUE_API int socket_receive_timeout(int fd, void *data, size_t length, int flags, unsigned int timeout);
LIMD_GLUE_API int socket_send(int fd, void *data, size_t length);

LIMD_GLUE_API int socket_get_socket_port(int fd, uint16_t *port);

LIMD_GLUE_API void socket_set_verbose(int level);

LIMD_GLUE_API const char *socket_addr_to_string(struct sockaddr *addr, char *addr_out, size_t addr_out_size);

LIMD_GLUE_API int get_primary_mac_address(unsigned char mac_addr_buf[6]);

#ifdef __cplusplus
}
#endif

#endif	/* SOCKET_SOCKET_H */
07070100000016000081A400000000000000000000000167AD5DE900000CDC000000000000000000000000000000000000005600000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/termcolors.h/*
 * termcolors.h
 *
 * Copyright (c) 2020-2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#ifndef TERMCOLORS_H
#define TERMCOLORS_H

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdarg.h>
#include <stdio.h>
#include <libimobiledevice-glue/glue.h>

#define COLOR_RESET           "\e[m"
#define STYLE_NORMAL          "\e[0m"
#define STYLE_BRIGHT          "\e[1m"
#define STYLE_DARK            "\e[2m"
#define FG_BLACK              "\e[0;30m"
#define FG_DARK_GRAY          "\e[1;30m"
#define FG_RED                "\e[0;31m"
#define FG_BRIGHT_RED         "\e[1;31m"
#define FG_DARK_RED           "\e[2;31m"
#define FG_GREEN              "\e[0;32m"
#define FG_BRIGHT_GREEN       "\e[1;32m"
#define FG_DARK_GREEN         "\e[2;32m"
#define FG_YELLOW             "\e[0;33m"
#define FG_BRIGHT_YELLOW      "\e[1;33m"
#define FG_DARK_YELLOW        "\e[2;33m"
#define FG_BLUE               "\e[0;34m"
#define FG_BRIGHT_BLUE        "\e[1;34m"
#define FG_DARK_BLUE          "\e[2;34m"
#define FG_MAGENTA            "\e[0;35m"
#define FG_BRIGHT_MAGENTA     "\e[1;35m"
#define FG_DARK_MAGENTA       "\e[2;35m"
#define FG_CYAN               "\e[0;36m"
#define FG_BRIGHT_CYAN        "\e[1;36m"
#define FG_DARK_CYAN          "\e[2;36m"
#define FG_LIGHT_GRAY         "\e[0;37m"
#define FG_WHITE              "\e[1;37m"
#define FG_GRAY               "\e[2;37m"
#define FG_DEFAULT            "\e[39m"
#define BG_BLACK              "\e[40m"
#define BG_GRAY               "\e[100m"
#define BG_RED                "\e[41m"
#define BG_BRIGHT_RED         "\e[101m"
#define BG_GREEN              "\e[42m"
#define BG_BRIGHT_GREEN       "\e[102m"
#define BG_YELLOW             "\e[43m"
#define BG_BRIGHT_YELLOW      "\e[103m"
#define BG_BLUE               "\e[44m"
#define BG_BRIGHT_BLUE        "\e[104m"
#define BG_MAGENTA            "\e[45m"
#define BG_BRIGHT_MAGENTA     "\e[105m"
#define BG_CYAN               "\e[46m"
#define BG_BRIGHT_CYAN        "\e[106m"
#define BG_LIGHT_GRAY         "\e[47m"
#define BG_WHITE              "\e[107m"
#define BG_DEFAULT            "\e[49m"

#ifdef __cplusplus
extern "C" {
#endif

/* automatically called by library constructor */
LIMD_GLUE_API void term_colors_init();

/* enable / disable terminal colors */
LIMD_GLUE_API void term_colors_set_enabled(int en);

/* color-aware *printf variants */
LIMD_GLUE_API int cprintf(const char* fmt, ...);
LIMD_GLUE_API int cfprintf(FILE* stream, const char* fmt, ...);
LIMD_GLUE_API int cvfprintf(FILE* stream, const char* fmt, va_list vargs);

#ifdef __cplusplus
}
#endif

#endif
07070100000017000081A400000000000000000000000167AD5DE900000C70000000000000000000000000000000000000005200000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/thread.h/*
 * thread.h
 *
 * Copyright (c) 2012-2019 Nikias Bassen, All Rights Reserved.
 * Copyright (c) 2012 Martin Szulecki, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef __THREAD_H
#define __THREAD_H

#include <stddef.h>
#include <libimobiledevice-glue/glue.h>

#ifdef _WIN32
typedef void* HANDLE;
typedef HANDLE THREAD_T;
#pragma pack(push, 8)
struct _CRITICAL_SECTION_ST {
	void* DebugInfo;
	long LockCount;
	long RecursionCount;
	HANDLE OwningThread;
	HANDLE LockSemaphore;
#if defined(_WIN64)
	unsigned __int64 SpinCount;
#else
	unsigned long SpinCount;
#endif
};
#pragma pack(pop)
typedef struct _CRITICAL_SECTION_ST mutex_t;
typedef struct {
	HANDLE sem;
} cond_t;
typedef volatile struct {
	long lock;
	int state;
} thread_once_t;
#define THREAD_ONCE_INIT {0, 0}
#define THREAD_ID GetCurrentThreadId()
#define THREAD_T_NULL (THREAD_T)NULL
#else
#include <pthread.h>
#include <signal.h>
#include <sys/time.h>
typedef pthread_t THREAD_T;
typedef pthread_mutex_t mutex_t;
typedef pthread_cond_t cond_t;
typedef pthread_once_t thread_once_t;
#define THREAD_ONCE_INIT PTHREAD_ONCE_INIT
#define THREAD_ID pthread_self()
#define THREAD_T_NULL (THREAD_T)NULL
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef void* (*thread_func_t)(void* data);

LIMD_GLUE_API int thread_new(THREAD_T* thread, thread_func_t thread_func, void* data);
LIMD_GLUE_API void thread_detach(THREAD_T thread);
LIMD_GLUE_API void thread_free(THREAD_T thread);
LIMD_GLUE_API int thread_join(THREAD_T thread);
LIMD_GLUE_API int thread_alive(THREAD_T thread);

LIMD_GLUE_API int thread_cancel(THREAD_T thread);

#ifdef _WIN32
#undef HAVE_THREAD_CLEANUP
#else
#ifdef HAVE_PTHREAD_CANCEL
#define HAVE_THREAD_CLEANUP 1
#define thread_cleanup_push(routine, arg) pthread_cleanup_push(routine, arg)
#define thread_cleanup_pop(execute) pthread_cleanup_pop(execute)
#endif
#endif

LIMD_GLUE_API void mutex_init(mutex_t* mutex);
LIMD_GLUE_API void mutex_destroy(mutex_t* mutex);
LIMD_GLUE_API void mutex_lock(mutex_t* mutex);
LIMD_GLUE_API void mutex_unlock(mutex_t* mutex);

LIMD_GLUE_API void thread_once(thread_once_t *once_control, void (*init_routine)(void));

LIMD_GLUE_API void cond_init(cond_t* cond);
LIMD_GLUE_API void cond_destroy(cond_t* cond);
LIMD_GLUE_API int cond_signal(cond_t* cond);
LIMD_GLUE_API int cond_wait(cond_t* cond, mutex_t* mutex);
LIMD_GLUE_API int cond_wait_timeout(cond_t* cond, mutex_t* mutex, unsigned int timeout_ms);

#ifdef __cplusplus
}
#endif

#endif
07070100000018000081A400000000000000000000000167AD5DE90000071B000000000000000000000000000000000000004F00000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/tlv.h/*
 * tlv.h
 * Simple TLV implementation.
 *
 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
#ifndef __TLV_H
#define __TLV_H

#include <stdint.h>
#include <libimobiledevice-glue/glue.h>

struct tlv_buf {
	unsigned char* data;
	unsigned int length;
	unsigned int capacity;
};
typedef struct tlv_buf* tlv_buf_t;

#ifdef __cplusplus
extern "C" {
#endif

LIMD_GLUE_API tlv_buf_t tlv_buf_new();
LIMD_GLUE_API void tlv_buf_free(tlv_buf_t tlv);

LIMD_GLUE_API void tlv_buf_append(tlv_buf_t tlv, uint8_t tag, unsigned int length, void* data);
LIMD_GLUE_API unsigned char* tlv_get_data_ptr(const void* tlv_data, void* tlv_end, uint8_t tag, uint8_t* length);
LIMD_GLUE_API int tlv_data_get_uint(const void* tlv_data, unsigned int tlv_length, uint8_t tag, uint64_t* value);
LIMD_GLUE_API int tlv_data_get_uint8(const void* tlv_data, unsigned int tlv_length, uint8_t tag, uint8_t* value);
LIMD_GLUE_API int tlv_data_copy_data(const void* tlv_data, unsigned int tlv_length, uint8_t tag, void** out, unsigned int* out_len);

#ifdef __cplusplus
}
#endif

#endif /* __TLV_H */
07070100000019000081A400000000000000000000000167AD5DE9000006E1000000000000000000000000000000000000005100000000libimobiledevice-glue-1.3.1+git18.20250213/include/libimobiledevice-glue/utils.h/*
 * utils.h
 * Miscellaneous utilities for string manipulation,
 * file I/O and plist helper.
 *
 * Copyright (c) 2014-2019 Nikias Bassen, All Rights Reserved.
 * Copyright (c) 2013-2014 Martin Szulecki, All Rights Reserved.
 * Copyright (c) 2013 Federico Mena Quintero
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef __UTILS_H
#define __UTILS_H

#include <stdio.h>
#include <stdint.h>
#include <libimobiledevice-glue/glue.h>

#define MAC_EPOCH 978307200

#ifdef __cplusplus
extern "C" {
#endif

LIMD_GLUE_API char *string_concat(const char *str, ...);
LIMD_GLUE_API char *string_append(char *str, ...);
LIMD_GLUE_API char *string_build_path(const char *elem, ...);
LIMD_GLUE_API char *string_format_size(uint64_t size);
LIMD_GLUE_API char *string_toupper(char *str);
LIMD_GLUE_API char *generate_uuid(void);

LIMD_GLUE_API int buffer_read_from_filename(const char *filename, char **buffer, uint64_t *length);
LIMD_GLUE_API int buffer_write_to_filename(const char *filename, const char *buffer, uint64_t length);

#ifdef __cplusplus
}
#endif

#endif
0707010000001A000041ED00000000000000000000000267AD5DE900000000000000000000000000000000000000000000002E00000000libimobiledevice-glue-1.3.1+git18.20250213/m40707010000001B000081A400000000000000000000000167AD5DE900000607000000000000000000000000000000000000004200000000libimobiledevice-glue-1.3.1+git18.20250213/m4/as-compiler-flag.m4dnl 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"
])

0707010000001C000081A400000000000000000000000167AD5DE90000581C000000000000000000000000000000000000003C00000000libimobiledevice-glue-1.3.1+git18.20250213/m4/ax_pthread.m4# ===========================================================================
#        https://www.gnu.org/software/autoconf-archive/ax_pthread.html
# ===========================================================================
#
# SYNOPSIS
#
#   AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
#
# DESCRIPTION
#
#   This macro figures out how to build C programs using POSIX threads. It
#   sets the PTHREAD_LIBS output variable to the threads library and linker
#   flags, and the PTHREAD_CFLAGS output variable to any special C compiler
#   flags that are needed. (The user can also force certain compiler
#   flags/libs to be tested by setting these environment variables.)
#
#   Also sets PTHREAD_CC and PTHREAD_CXX to any special C compiler that is
#   needed for multi-threaded programs (defaults to the value of CC
#   respectively CXX otherwise). (This is necessary on e.g. AIX to use the
#   special cc_r/CC_r compiler alias.)
#
#   NOTE: You are assumed to not only compile your program with these flags,
#   but also to link with them as well. For example, you might link with
#   $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
#   $PTHREAD_CXX $CXXFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
#
#   If you are only building threaded programs, you may wish to use these
#   variables in your default LIBS, CFLAGS, and CC:
#
#     LIBS="$PTHREAD_LIBS $LIBS"
#     CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
#     CXXFLAGS="$CXXFLAGS $PTHREAD_CFLAGS"
#     CC="$PTHREAD_CC"
#     CXX="$PTHREAD_CXX"
#
#   In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
#   has a nonstandard name, this macro defines PTHREAD_CREATE_JOINABLE to
#   that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
#
#   Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
#   PTHREAD_PRIO_INHERIT symbol is defined when compiling with
#   PTHREAD_CFLAGS.
#
#   ACTION-IF-FOUND is a list of shell commands to run if a threads library
#   is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
#   is not found. If ACTION-IF-FOUND is not specified, the default action
#   will define HAVE_PTHREAD.
#
#   Please let the authors know if this macro fails on any platform, or if
#   you have any other suggestions or comments. This macro was based on work
#   by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help
#   from M. Frigo), as well as ac_pthread and hb_pthread macros posted by
#   Alejandro Forero Cuervo to the autoconf macro repository. We are also
#   grateful for the helpful feedback of numerous users.
#
#   Updated for Autoconf 2.68 by Daniel Richard G.
#
# LICENSE
#
#   Copyright (c) 2008 Steven G. Johnson <stevenj@alum.mit.edu>
#   Copyright (c) 2011 Daniel Richard G. <skunk@iSKUNK.ORG>
#   Copyright (c) 2019 Marc Stevens <marc.stevens@cwi.nl>
#
#   This program is free software: you can redistribute it and/or modify it
#   under the terms of the GNU General Public License as published by the
#   Free Software Foundation, either version 3 of the License, or (at your
#   option) any later version.
#
#   This program is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
#   Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program. If not, see <https://www.gnu.org/licenses/>.
#
#   As a special exception, the respective Autoconf Macro's copyright owner
#   gives unlimited permission to copy, distribute and modify the configure
#   scripts that are the output of Autoconf when processing the Macro. You
#   need not follow the terms of the GNU General Public License when using
#   or distributing such scripts, even though portions of the text of the
#   Macro appear in them. The GNU General Public License (GPL) does govern
#   all other use of the material that constitutes the Autoconf Macro.
#
#   This special exception to the GPL applies to versions of the Autoconf
#   Macro released by the Autoconf Archive. When you make and distribute a
#   modified version of the Autoconf Macro, you may extend this special
#   exception to the GPL to apply to your modified version as well.

#serial 31

AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
AC_DEFUN([AX_PTHREAD], [
AC_REQUIRE([AC_CANONICAL_HOST])
AC_REQUIRE([AC_PROG_CC])
AC_REQUIRE([AC_PROG_SED])
AC_LANG_PUSH([C])
ax_pthread_ok=no

# We used to check for pthread.h first, but this fails if pthread.h
# requires special compiler flags (e.g. on Tru64 or Sequent).
# It gets checked for in the link test anyway.

# First of all, check if the user has set any of the PTHREAD_LIBS,
# etcetera environment variables, and if threads linking works using
# them:
if test "x$PTHREAD_CFLAGS$PTHREAD_LIBS" != "x"; then
        ax_pthread_save_CC="$CC"
        ax_pthread_save_CFLAGS="$CFLAGS"
        ax_pthread_save_LIBS="$LIBS"
        AS_IF([test "x$PTHREAD_CC" != "x"], [CC="$PTHREAD_CC"])
        AS_IF([test "x$PTHREAD_CXX" != "x"], [CXX="$PTHREAD_CXX"])
        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
        LIBS="$PTHREAD_LIBS $LIBS"
        AC_MSG_CHECKING([for pthread_join using $CC $PTHREAD_CFLAGS $PTHREAD_LIBS])
        AC_LINK_IFELSE([AC_LANG_CALL([], [pthread_join])], [ax_pthread_ok=yes])
        AC_MSG_RESULT([$ax_pthread_ok])
        if test "x$ax_pthread_ok" = "xno"; then
                PTHREAD_LIBS=""
                PTHREAD_CFLAGS=""
        fi
        CC="$ax_pthread_save_CC"
        CFLAGS="$ax_pthread_save_CFLAGS"
        LIBS="$ax_pthread_save_LIBS"
fi

# We must check for the threads library under a number of different
# names; the ordering is very important because some systems
# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
# libraries is broken (non-POSIX).

# Create a list of thread flags to try. Items with a "," contain both
# C compiler flags (before ",") and linker flags (after ","). Other items
# starting with a "-" are C compiler flags, and remaining items are
# library names, except for "none" which indicates that we try without
# any flags at all, and "pthread-config" which is a program returning
# the flags for the Pth emulation library.

ax_pthread_flags="pthreads none -Kthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"

# The ordering *is* (sometimes) important.  Some notes on the
# individual items follow:

# pthreads: AIX (must check this before -lpthread)
# none: in case threads are in libc; should be tried before -Kthread and
#       other compiler flags to prevent continual compiler warnings
# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads), Tru64
#           (Note: HP C rejects this with "bad form for `-t' option")
# -pthreads: Solaris/gcc (Note: HP C also rejects)
# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
#      doesn't hurt to check since this sometimes defines pthreads and
#      -D_REENTRANT too), HP C (must be checked before -lpthread, which
#      is present but should not be used directly; and before -mthreads,
#      because the compiler interprets this as "-mt" + "-hreads")
# -mthreads: Mingw32/gcc, Lynx/gcc
# pthread: Linux, etcetera
# --thread-safe: KAI C++
# pthread-config: use pthread-config program (for GNU Pth library)

case $host_os in

        freebsd*)

        # -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
        # lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)

        ax_pthread_flags="-kthread lthread $ax_pthread_flags"
        ;;

        hpux*)

        # From the cc(1) man page: "[-mt] Sets various -D flags to enable
        # multi-threading and also sets -lpthread."

        ax_pthread_flags="-mt -pthread pthread $ax_pthread_flags"
        ;;

        openedition*)

        # IBM z/OS requires a feature-test macro to be defined in order to
        # enable POSIX threads at all, so give the user a hint if this is
        # not set. (We don't define these ourselves, as they can affect
        # other portions of the system API in unpredictable ways.)

        AC_EGREP_CPP([AX_PTHREAD_ZOS_MISSING],
            [
#            if !defined(_OPEN_THREADS) && !defined(_UNIX03_THREADS)
             AX_PTHREAD_ZOS_MISSING
#            endif
            ],
            [AC_MSG_WARN([IBM z/OS requires -D_OPEN_THREADS or -D_UNIX03_THREADS to enable pthreads support.])])
        ;;

        solaris*)

        # On Solaris (at least, for some versions), libc contains stubbed
        # (non-functional) versions of the pthreads routines, so link-based
        # tests will erroneously succeed. (N.B.: The stubs are missing
        # pthread_cleanup_push, or rather a function called by this macro,
        # so we could check for that, but who knows whether they'll stub
        # that too in a future libc.)  So we'll check first for the
        # standard Solaris way of linking pthreads (-mt -lpthread).

        ax_pthread_flags="-mt,-lpthread pthread $ax_pthread_flags"
        ;;
esac

# Are we compiling with Clang?

AC_CACHE_CHECK([whether $CC is Clang],
    [ax_cv_PTHREAD_CLANG],
    [ax_cv_PTHREAD_CLANG=no
     # Note that Autoconf sets GCC=yes for Clang as well as GCC
     if test "x$GCC" = "xyes"; then
        AC_EGREP_CPP([AX_PTHREAD_CC_IS_CLANG],
            [/* Note: Clang 2.7 lacks __clang_[a-z]+__ */
#            if defined(__clang__) && defined(__llvm__)
             AX_PTHREAD_CC_IS_CLANG
#            endif
            ],
            [ax_cv_PTHREAD_CLANG=yes])
     fi
    ])
ax_pthread_clang="$ax_cv_PTHREAD_CLANG"


# GCC generally uses -pthread, or -pthreads on some platforms (e.g. SPARC)

# Note that for GCC and Clang -pthread generally implies -lpthread,
# except when -nostdlib is passed.
# This is problematic using libtool to build C++ shared libraries with pthread:
# [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25460
# [2] https://bugzilla.redhat.com/show_bug.cgi?id=661333
# [3] https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=468555
# To solve this, first try -pthread together with -lpthread for GCC

AS_IF([test "x$GCC" = "xyes"],
      [ax_pthread_flags="-pthread,-lpthread -pthread -pthreads $ax_pthread_flags"])

# Clang takes -pthread (never supported any other flag), but we'll try with -lpthread first

AS_IF([test "x$ax_pthread_clang" = "xyes"],
      [ax_pthread_flags="-pthread,-lpthread -pthread"])


# The presence of a feature test macro requesting re-entrant function
# definitions is, on some systems, a strong hint that pthreads support is
# correctly enabled

case $host_os in
        darwin* | hpux* | linux* | osf* | solaris*)
        ax_pthread_check_macro="_REENTRANT"
        ;;

        aix*)
        ax_pthread_check_macro="_THREAD_SAFE"
        ;;

        *)
        ax_pthread_check_macro="--"
        ;;
esac
AS_IF([test "x$ax_pthread_check_macro" = "x--"],
      [ax_pthread_check_cond=0],
      [ax_pthread_check_cond="!defined($ax_pthread_check_macro)"])


if test "x$ax_pthread_ok" = "xno"; then
for ax_pthread_try_flag in $ax_pthread_flags; do

        case $ax_pthread_try_flag in
                none)
                AC_MSG_CHECKING([whether pthreads work without any flags])
                ;;

                *,*)
                PTHREAD_CFLAGS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\1/"`
                PTHREAD_LIBS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\2/"`
                AC_MSG_CHECKING([whether pthreads work with "$PTHREAD_CFLAGS" and "$PTHREAD_LIBS"])
                ;;

                -*)
                AC_MSG_CHECKING([whether pthreads work with $ax_pthread_try_flag])
                PTHREAD_CFLAGS="$ax_pthread_try_flag"
                ;;

                pthread-config)
                AC_CHECK_PROG([ax_pthread_config], [pthread-config], [yes], [no])
                AS_IF([test "x$ax_pthread_config" = "xno"], [continue])
                PTHREAD_CFLAGS="`pthread-config --cflags`"
                PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
                ;;

                *)
                AC_MSG_CHECKING([for the pthreads library -l$ax_pthread_try_flag])
                PTHREAD_LIBS="-l$ax_pthread_try_flag"
                ;;
        esac

        ax_pthread_save_CFLAGS="$CFLAGS"
        ax_pthread_save_LIBS="$LIBS"
        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
        LIBS="$PTHREAD_LIBS $LIBS"

        # Check for various functions.  We must include pthread.h,
        # since some functions may be macros.  (On the Sequent, we
        # need a special flag -Kthread to make this header compile.)
        # We check for pthread_join because it is in -lpthread on IRIX
        # while pthread_create is in libc.  We check for pthread_attr_init
        # due to DEC craziness with -lpthreads.  We check for
        # pthread_cleanup_push because it is one of the few pthread
        # functions on Solaris that doesn't have a non-functional libc stub.
        # We try pthread_create on general principles.

        AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>
#                       if $ax_pthread_check_cond
#                        error "$ax_pthread_check_macro must be defined"
#                       endif
                        static void *some_global = NULL;
                        static void routine(void *a)
                          {
                             /* To avoid any unused-parameter or
                                unused-but-set-parameter warning.  */
                             some_global = a;
                          }
                        static void *start_routine(void *a) { return a; }],
                       [pthread_t th; pthread_attr_t attr;
                        pthread_create(&th, 0, start_routine, 0);
                        pthread_join(th, 0);
                        pthread_attr_init(&attr);
                        pthread_cleanup_push(routine, 0);
                        pthread_cleanup_pop(0) /* ; */])],
            [ax_pthread_ok=yes],
            [])

        CFLAGS="$ax_pthread_save_CFLAGS"
        LIBS="$ax_pthread_save_LIBS"

        AC_MSG_RESULT([$ax_pthread_ok])
        AS_IF([test "x$ax_pthread_ok" = "xyes"], [break])

        PTHREAD_LIBS=""
        PTHREAD_CFLAGS=""
done
fi


# Clang needs special handling, because older versions handle the -pthread
# option in a rather... idiosyncratic way

if test "x$ax_pthread_clang" = "xyes"; then

        # Clang takes -pthread; it has never supported any other flag

        # (Note 1: This will need to be revisited if a system that Clang
        # supports has POSIX threads in a separate library.  This tends not
        # to be the way of modern systems, but it's conceivable.)

        # (Note 2: On some systems, notably Darwin, -pthread is not needed
        # to get POSIX threads support; the API is always present and
        # active.  We could reasonably leave PTHREAD_CFLAGS empty.  But
        # -pthread does define _REENTRANT, and while the Darwin headers
        # ignore this macro, third-party headers might not.)

        # However, older versions of Clang make a point of warning the user
        # that, in an invocation where only linking and no compilation is
        # taking place, the -pthread option has no effect ("argument unused
        # during compilation").  They expect -pthread to be passed in only
        # when source code is being compiled.
        #
        # Problem is, this is at odds with the way Automake and most other
        # C build frameworks function, which is that the same flags used in
        # compilation (CFLAGS) are also used in linking.  Many systems
        # supported by AX_PTHREAD require exactly this for POSIX threads
        # support, and in fact it is often not straightforward to specify a
        # flag that is used only in the compilation phase and not in
        # linking.  Such a scenario is extremely rare in practice.
        #
        # Even though use of the -pthread flag in linking would only print
        # a warning, this can be a nuisance for well-run software projects
        # that build with -Werror.  So if the active version of Clang has
        # this misfeature, we search for an option to squash it.

        AC_CACHE_CHECK([whether Clang needs flag to prevent "argument unused" warning when linking with -pthread],
            [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG],
            [ax_cv_PTHREAD_CLANG_NO_WARN_FLAG=unknown
             # Create an alternate version of $ac_link that compiles and
             # links in two steps (.c -> .o, .o -> exe) instead of one
             # (.c -> exe), because the warning occurs only in the second
             # step
             ax_pthread_save_ac_link="$ac_link"
             ax_pthread_sed='s/conftest\.\$ac_ext/conftest.$ac_objext/g'
             ax_pthread_link_step=`AS_ECHO(["$ac_link"]) | sed "$ax_pthread_sed"`
             ax_pthread_2step_ac_link="($ac_compile) && (echo ==== >&5) && ($ax_pthread_link_step)"
             ax_pthread_save_CFLAGS="$CFLAGS"
             for ax_pthread_try in '' -Qunused-arguments -Wno-unused-command-line-argument unknown; do
                AS_IF([test "x$ax_pthread_try" = "xunknown"], [break])
                CFLAGS="-Werror -Wunknown-warning-option $ax_pthread_try -pthread $ax_pthread_save_CFLAGS"
                ac_link="$ax_pthread_save_ac_link"
                AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
                    [ac_link="$ax_pthread_2step_ac_link"
                     AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
                         [break])
                    ])
             done
             ac_link="$ax_pthread_save_ac_link"
             CFLAGS="$ax_pthread_save_CFLAGS"
             AS_IF([test "x$ax_pthread_try" = "x"], [ax_pthread_try=no])
             ax_cv_PTHREAD_CLANG_NO_WARN_FLAG="$ax_pthread_try"
            ])

        case "$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG" in
                no | unknown) ;;
                *) PTHREAD_CFLAGS="$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG $PTHREAD_CFLAGS" ;;
        esac

fi # $ax_pthread_clang = yes



# Various other checks:
if test "x$ax_pthread_ok" = "xyes"; then
        ax_pthread_save_CFLAGS="$CFLAGS"
        ax_pthread_save_LIBS="$LIBS"
        CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
        LIBS="$PTHREAD_LIBS $LIBS"

        # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
        AC_CACHE_CHECK([for joinable pthread attribute],
            [ax_cv_PTHREAD_JOINABLE_ATTR],
            [ax_cv_PTHREAD_JOINABLE_ATTR=unknown
             for ax_pthread_attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
                 AC_LINK_IFELSE([AC_LANG_PROGRAM([#include <pthread.h>],
                                                 [int attr = $ax_pthread_attr; return attr /* ; */])],
                                [ax_cv_PTHREAD_JOINABLE_ATTR=$ax_pthread_attr; break],
                                [])
             done
            ])
        AS_IF([test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xunknown" && \
               test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xPTHREAD_CREATE_JOINABLE" && \
               test "x$ax_pthread_joinable_attr_defined" != "xyes"],
              [AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE],
                                  [$ax_cv_PTHREAD_JOINABLE_ATTR],
                                  [Define to necessary symbol if this constant
                                   uses a non-standard name on your system.])
               ax_pthread_joinable_attr_defined=yes
              ])

        AC_CACHE_CHECK([whether more special flags are required for pthreads],
            [ax_cv_PTHREAD_SPECIAL_FLAGS],
            [ax_cv_PTHREAD_SPECIAL_FLAGS=no
             case $host_os in
             solaris*)
             ax_cv_PTHREAD_SPECIAL_FLAGS="-D_POSIX_PTHREAD_SEMANTICS"
             ;;
             esac
            ])
        AS_IF([test "x$ax_cv_PTHREAD_SPECIAL_FLAGS" != "xno" && \
               test "x$ax_pthread_special_flags_added" != "xyes"],
              [PTHREAD_CFLAGS="$ax_cv_PTHREAD_SPECIAL_FLAGS $PTHREAD_CFLAGS"
               ax_pthread_special_flags_added=yes])

        AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
            [ax_cv_PTHREAD_PRIO_INHERIT],
            [AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <pthread.h>]],
                                             [[int i = PTHREAD_PRIO_INHERIT;
                                               return i;]])],
                            [ax_cv_PTHREAD_PRIO_INHERIT=yes],
                            [ax_cv_PTHREAD_PRIO_INHERIT=no])
            ])
        AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes" && \
               test "x$ax_pthread_prio_inherit_defined" != "xyes"],
              [AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.])
               ax_pthread_prio_inherit_defined=yes
              ])

        CFLAGS="$ax_pthread_save_CFLAGS"
        LIBS="$ax_pthread_save_LIBS"

        # More AIX lossage: compile with *_r variant
        if test "x$GCC" != "xyes"; then
            case $host_os in
                aix*)
                AS_CASE(["x/$CC"],
                    [x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
                    [#handle absolute path differently from PATH based program lookup
                     AS_CASE(["x$CC"],
                         [x/*],
                         [
			   AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])
			   AS_IF([test "x${CXX}" != "x"], [AS_IF([AS_EXECUTABLE_P([${CXX}_r])],[PTHREAD_CXX="${CXX}_r"])])
			 ],
                         [
			   AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])
			   AS_IF([test "x${CXX}" != "x"], [AC_CHECK_PROGS([PTHREAD_CXX],[${CXX}_r],[$CXX])])
			 ]
                     )
                    ])
                ;;
            esac
        fi
fi

test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
test -n "$PTHREAD_CXX" || PTHREAD_CXX="$CXX"

AC_SUBST([PTHREAD_LIBS])
AC_SUBST([PTHREAD_CFLAGS])
AC_SUBST([PTHREAD_CC])
AC_SUBST([PTHREAD_CXX])

# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
if test "x$ax_pthread_ok" = "xyes"; then
        ifelse([$1],,[AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])],[$1])
        :
else
        ax_pthread_ok=no
        $2
fi
AC_LANG_POP
])dnl AX_PTHREAD
0707010000001D000041ED00000000000000000000000267AD5DE900000000000000000000000000000000000000000000002F00000000libimobiledevice-glue-1.3.1+git18.20250213/src0707010000001E000081A400000000000000000000000167AD5DE90000035D000000000000000000000000000000000000003B00000000libimobiledevice-glue-1.3.1+git18.20250213/src/Makefile.amAM_CPPFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)

AM_CFLAGS = $(GLOBAL_CFLAGS) $(PTHREAD_CFLAGS) $(libplist_CFLAGS)

AM_LDFLAGS = $(PTHREAD_LIBS) $(libplist_LIBS)

lib_LTLIBRARIES = libimobiledevice-glue-1.0.la
libimobiledevice_glue_1_0_la_LDFLAGS = $(AM_LDFLAGS) -version-info $(LIBIMOBILEDEVICE_GLUE_SO_VERSION) -no-undefined
libimobiledevice_glue_1_0_la_LIBADD =
libimobiledevice_glue_1_0_la_SOURCES =	\
	glue.c	\
	socket.c	\
	thread.c	\
	utils.c		\
	nskeyedarchive.c \
	collection.c	\
	termcolors.c	\
	cbuf.c          \
	opack.c         \
	tlv.c           \
	sha1.c          \
	sha256.c        \
	sha512.c        \
	common.h

if WIN32
libimobiledevice_glue_1_0_la_LDFLAGS += -avoid-version -static-libgcc
libimobiledevice_glue_1_0_la_LIBADD += -lws2_32 -lIphlpapi
endif

pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libimobiledevice-glue-1.0.pc
0707010000001F000081A400000000000000000000000167AD5DE900000768000000000000000000000000000000000000003600000000libimobiledevice-glue-1.3.1+git18.20250213/src/cbuf.c/*
 * cbuf.c
 * Simple char buffer implementation.
 *
 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "common.h"
#include "libimobiledevice-glue/cbuf.h"

struct char_buf* char_buf_new()
{
	struct char_buf* cbuf = (struct char_buf*)malloc(sizeof(struct char_buf));
	cbuf->capacity = 256;
	cbuf->length = 0;
	cbuf->data = (unsigned char*)malloc(cbuf->capacity);
	return cbuf;
}

void char_buf_free(struct char_buf* cbuf)
{
	if (cbuf) {
		free(cbuf->data);
		free(cbuf);
	}
}

void char_buf_append(struct char_buf* cbuf, unsigned int length, unsigned char* data)
{
	if (!cbuf || !cbuf->data) {
		return;
	}
	if (cbuf->length + length > cbuf->capacity) {
		unsigned int newcapacity = cbuf->capacity + ((length / 256) + 1) * 256;
		unsigned char* newdata = realloc(cbuf->data, newcapacity);
		if (!newdata) {
			fprintf(stderr, "%s: ERROR: Failed to realloc\n", __func__);
			return;
		}
		cbuf->data = newdata;
		cbuf->capacity = newcapacity;
	}
	memcpy(cbuf->data + cbuf->length, data, length);
	cbuf->length += length;
}
07070100000020000081A400000000000000000000000167AD5DE900000AD6000000000000000000000000000000000000003C00000000libimobiledevice-glue-1.3.1+git18.20250213/src/collection.c/*
 * collection.c
 *
 * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
 * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "common.h"
#include "libimobiledevice-glue/collection.h"

#undef NDEBUG // we need to make sure we still get assertions because we can't handle memory allocation errors
#include <assert.h>

#define INIT_NULL(addr, count) { unsigned int i_ = 0; for (i_ = 0; i_ < (count); i_++) ((void**)(addr))[i_] = NULL; }

#define CAPACITY_STEP 8

void collection_init(struct collection *col)
{
	col->list = malloc(sizeof(void *) * CAPACITY_STEP);
	assert(col->list);
	INIT_NULL(col->list, CAPACITY_STEP);
	col->capacity = CAPACITY_STEP;
}

void collection_free(struct collection *col)
{
	free(col->list);
	col->list = NULL;
	col->capacity = 0;
}

void collection_add(struct collection *col, void *element)
{
	int i;
	for(i=0; i<col->capacity; i++) {
		if(!col->list[i]) {
			col->list[i] = element;
			return;
		}
	}
	void **newlist = realloc(col->list, sizeof(void*) * (col->capacity + CAPACITY_STEP));
	assert(newlist);
	col->list = newlist;
	INIT_NULL(&col->list[col->capacity], CAPACITY_STEP);
	col->list[col->capacity] = element;
	col->capacity += CAPACITY_STEP;
}

int collection_remove(struct collection *col, void *element)
{
	int i;
	for(i=0; i<col->capacity; i++) {
		if(col->list[i] == element) {
			col->list[i] = NULL;
			return 0;
		}
	}
	fprintf(stderr, "%s: WARNING: element %p not present in collection %p (cap %d)", __func__, element, col, col->capacity);
	return -1;
}

int collection_count(struct collection *col)
{
	int i, cnt = 0;
	for(i=0; i<col->capacity; i++) {
		if(col->list[i])
			cnt++;
	}
	return cnt;
}

void collection_copy(struct collection *dest, struct collection *src)
{
	if (!dest || !src) return;
	dest->capacity = src->capacity;
	dest->list = malloc(sizeof(void*) * src->capacity);
	memcpy(dest->list, src->list, sizeof(void*) * src->capacity);
}
07070100000021000081A400000000000000000000000167AD5DE9000004DA000000000000000000000000000000000000003800000000libimobiledevice-glue-1.3.1+git18.20250213/src/common.h/*
 * common.h
 *
 * Copyright (c) 2020 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef __COMMON_H
#define __COMMON_H

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef LIMD_GLUE_STATIC
  #define LIMD_GLUE_API
#elif defined(_WIN32)
  #define LIMD_GLUE_API __declspec( dllexport )
#else
  #if __GNUC__ >= 4
    #define LIMD_GLUE_API __attribute__((visibility("default")))
  #else
    #define LIMD_GLUE_API
  #endif
#endif

#include "libimobiledevice-glue/glue.h"

void socket_init();

#endif
07070100000022000081A400000000000000000000000167AD5DE900000856000000000000000000000000000000000000003600000000libimobiledevice-glue-1.3.1+git18.20250213/src/glue.c/*
 * glue.c
 *
 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef _WIN32
#include <windows.h>
#endif

#include "common.h"
#include "libimobiledevice-glue/thread.h"

// Reference: https://stackoverflow.com/a/2390626/1806760
// Initializer/finalizer sample for MSVC and GCC/Clang.
// 2010-2016 Joe Lowe. Released into the public domain.

#ifdef __cplusplus
    #define INITIALIZER(f) \
        static void f(void); \
        struct f##_t_ { f##_t_(void) { f(); } }; static f##_t_ f##_; \
        static void f(void)
#elif defined(_MSC_VER)
    #pragma section(".CRT$XCU",read)
    #define INITIALIZER2_(f,p) \
        static void f(void); \
        __declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f; \
        __pragma(comment(linker,"/include:" p #f "_")) \
        static void f(void)
    #ifdef _WIN64
        #define INITIALIZER(f) INITIALIZER2_(f,"")
    #else
        #define INITIALIZER(f) INITIALIZER2_(f,"_")
    #endif
#else
    #define INITIALIZER(f) \
        static void f(void) __attribute__((__constructor__)); \
        static void f(void)
#endif

extern void term_colors_init();

INITIALIZER(internal_glue_init)
{
	socket_init();
	term_colors_init();
}

const char* libimobiledevice_glue_version()
{
#ifndef PACKAGE_VERSION
#error PACKAGE_VERSION is not defined!
#endif
    return PACKAGE_VERSION;
}
07070100000023000081A400000000000000000000000167AD5DE90000012C000000000000000000000000000000000000004F00000000libimobiledevice-glue-1.3.1+git18.20250213/src/libimobiledevice-glue-1.0.pc.inprefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@

Name: @PACKAGE_NAME@
Description: Common library for libimobiledevice and co.
Version: @PACKAGE_VERSION@
Libs: -L${libdir} -limobiledevice-glue-1.0
Cflags: -I${includedir}
Requires: libplist-2.0 >= @LIBPLIST_VERSION@
07070100000024000081A400000000000000000000000167AD5DE90000890B000000000000000000000000000000000000004000000000libimobiledevice-glue-1.3.1+git18.20250213/src/nskeyedarchive.c/*
 * nskeyedarchive.c
 * Helper code to work with plist files containing NSKeyedArchiver data.
 *
 * Copyright (c) 2019 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <plist/plist.h>
#include "common.h"
#include "libimobiledevice-glue/nskeyedarchive.h"

#define NS_KEYED_ARCHIVER_NAME "NSKeyedArchiver"
#define NS_KEYED_ARCHIVER_VERSION 100000

struct nskeyedarchive_st {
	plist_t dict;
	uint64_t uid;
};

nskeyedarchive_t nskeyedarchive_new(void)
{
	plist_t dict = plist_new_dict();
	plist_dict_set_item(dict, "$version", plist_new_uint(NS_KEYED_ARCHIVER_VERSION));
	plist_t objects = plist_new_array();
	plist_array_append_item(objects, plist_new_string("$null"));
	plist_dict_set_item(dict, "$objects", objects);
	plist_dict_set_item(dict, "$archiver", plist_new_string(NS_KEYED_ARCHIVER_NAME));

	nskeyedarchive_t nskeyed = (nskeyedarchive_t)malloc(sizeof(struct nskeyedarchive_st));
	nskeyed->dict = dict;
	nskeyed->uid = 1;
	return nskeyed;
}

void nskeyedarchive_free(nskeyedarchive_t ka)
{
	if (ka) {
		if (ka->dict) {
			plist_free(ka->dict);
		}
		free(ka);
	}
}

void nskeyedarchive_set_top_ref_key_name(nskeyedarchive_t ka, const char* keyname)
{
	if (!ka) {
		return;
	}
	plist_t top = plist_dict_get_item(ka->dict, "$top");
	if (top) {
		plist_dict_iter iter = NULL;
		plist_dict_new_iter(top, &iter);
		if (iter) {
			plist_t node = NULL;
			char* keyn = NULL;
			plist_dict_next_item(top, iter, &keyn, &node);
			plist_t keynode = plist_dict_item_get_key(node);
			plist_set_key_val(keynode, keyname);
			free(keyn);
			free(iter);
		}
	}
}

plist_t nskeyedarchive_get_objects(nskeyedarchive_t ka)
{
	plist_t objects = plist_dict_get_item(ka->dict, "$objects");
	if (!objects || (plist_get_node_type(objects) != PLIST_ARRAY)) {
		fprintf(stderr, "ERROR: $objects node not found!\n");
		return NULL;
	}

	return objects;
}

plist_t nskeyedarchive_get_object_by_uid(nskeyedarchive_t ka, uint64_t uid)
{
	plist_t objects = nskeyedarchive_get_objects(ka);
	if (!objects) {
		return NULL;
	}

	plist_t obj = plist_array_get_item(objects, (uint32_t)uid);
	if (!obj) {
		fprintf(stderr, "ERROR: unable to get object node with uid %llu\n", (long long)uid);
		return NULL;
	}

	return obj;
}

plist_t nskeyedarchive_get_class_by_uid(nskeyedarchive_t ka, uint64_t uid)
{
	plist_t ret = nskeyedarchive_get_object_by_uid(ka, uid);
	if (ret && (plist_get_node_type(ret) != PLIST_DICT)) {
		fprintf(stderr, "ERROR: the uid %llu does not reference a valid class with node type PLIST_DICT!\n", (long long)uid);
		return NULL;
	}

	return ret;
}

void nskeyedarchive_append_object(nskeyedarchive_t ka, plist_t object)
{
	plist_t objects = nskeyedarchive_get_objects(ka);
	if (objects && plist_get_node_type(objects) != PLIST_ARRAY) {
		fprintf(stderr, "ERROR: unable to append object\n");
		return;
	}

	plist_array_append_item(objects, object);
}

static void nskeyedarchive_append_class_v(nskeyedarchive_t ka, const char* classname, va_list* va)
{
	if (!ka) {
		fprintf(stderr, "%s: ERROR: invalid keyed archive!\n", __func__);
		return;
	} else if (!classname) {
		fprintf(stderr, "%s: ERROR: missing classname!\n", __func__);
		return;
	}

	char* arg = NULL;
	plist_t classes = NULL;
	do {
		arg = (char*)va_arg(*va, char*);
		if (!arg) {
			break;
		}
		if (!classes) {
			classes = plist_new_array();
			plist_array_append_item(classes, plist_new_string(classname));
		}
		plist_array_append_item(classes, plist_new_string(arg));
	} while (arg);

	plist_t cls = plist_new_dict();
	plist_dict_set_item(cls, "$class", plist_new_uid(++ka->uid));

	nskeyedarchive_append_object(ka, cls);

	cls = plist_new_dict();
	if (classes) {
		plist_dict_set_item(cls, "$classes", classes);
	}
	plist_dict_set_item(cls, "$classname", plist_new_string(classname));

	nskeyedarchive_append_object(ka, cls);
}

void nskeyedarchive_append_class(nskeyedarchive_t ka, const char* classname, ...)
{
	if (!ka) {
		fprintf(stderr, "%s: ERROR: invalid keyed archive!\n", __func__);
		return;
	} else if (!classname) {
		fprintf(stderr, "%s: ERROR: missing classname!\n", __func__);
		return;
	}

	va_list va;
	va_start(va, classname);
	nskeyedarchive_append_class_v(ka, classname, &va);
	va_end(va);
}

void nskeyedarchive_add_top_class_uid(nskeyedarchive_t ka, uint64_t uid)
{
	plist_t top = plist_dict_get_item(ka->dict, "$top");
	if (!top) {
		top = plist_new_dict();
		plist_dict_set_item(top, "$0", plist_new_uid(uid));
		plist_dict_set_item(ka->dict, "$top", top);
	} else {
		uint32_t num = plist_dict_get_size(top);
		char newkey[8];
		sprintf(newkey, "$%d", num);
		plist_dict_set_item(top, newkey, plist_new_uid(uid));
	}
}

uint64_t nskeyedarchive_add_top_class(nskeyedarchive_t ka, const char* classname, ...)
{
	if (!ka) {
		fprintf(stderr, "%s: ERROR: invalid keyed archive!\n", __func__);
		return 0;
	} else if (!classname) {
		fprintf(stderr, "%s: ERROR: missing classname!\n", __func__);
		return 0;
	}

	uint64_t uid = ka->uid;

	va_list va;
	va_start(va, classname);
	nskeyedarchive_append_class_v(ka, classname, &va);
	va_end(va);

	nskeyedarchive_add_top_class_uid(ka, uid);
	return uid;
}

static void nskeyedarchive_set_class_property_v(nskeyedarchive_t ka, uint64_t uid, const char* propname, enum nskeyedarchive_class_type_t proptype, va_list* va);

static void nskeyedarchive_nsarray_append(nskeyedarchive_t ka, plist_t array, enum nskeyedarchive_class_type_t type, ...);

static void nskeyedarchive_nsarray_append_v(nskeyedarchive_t ka, plist_t array, enum nskeyedarchive_class_type_t type, va_list* va)
{
	if (!ka) {
		fprintf(stderr, "%s: ERROR: invalid keyed archive!\n", __func__);
		return;
	} else if (!array) {
		fprintf(stderr, "%s: ERROR: missing plist!\n", __func__);
		return;
	}

	uint64_t newuid;

	switch (type) {
	case NSTYPE_INTEGER:
		plist_array_append_item(array, plist_new_uint(va_arg(*va, int)));
		break;
	case NSTYPE_INTREF:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		nskeyedarchive_append_object(ka, plist_new_uint(va_arg(*va, int)));
		break;
	case NSTYPE_BOOLEAN:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		nskeyedarchive_append_object(ka, plist_new_bool(va_arg(*va, int)));
		break;
	case NSTYPE_CHARS:
		plist_array_append_item(array, plist_new_string(va_arg(*va, char*)));
		break;
	case NSTYPE_STRING:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		nskeyedarchive_append_object(ka, plist_new_string(va_arg(*va, char*)));
		break;
	case NSTYPE_REAL:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		nskeyedarchive_append_object(ka, plist_new_real(va_arg(*va, double)));
		break;
	case NSTYPE_NSMUTABLESTRING:
	case NSTYPE_NSSTRING:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		newuid = ka->uid;
		if (type == NSTYPE_NSMUTABLESTRING) {
			nskeyedarchive_append_class(ka, "NSMutableString", "NSString", "NSObject", NULL);
		} else {
			nskeyedarchive_append_class(ka, "NSString", "NSObject", NULL);
		}
		nskeyedarchive_set_class_property(ka, newuid, "NS.string", NSTYPE_CHARS, va_arg(*va, char*));
		break;
	case NSTYPE_NSMUTABLEARRAY:
	case NSTYPE_NSARRAY:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		newuid = ka->uid;
		if (type == NSTYPE_NSMUTABLEARRAY) {
			nskeyedarchive_append_class(ka, "NSMutableArray", "NSArray", "NSObject", NULL);
		} else {
			nskeyedarchive_append_class(ka, "NSArray", "NSObject", NULL);
		}
		{
		plist_t arr = plist_new_array();
		do {
			int ptype = va_arg(*va, int);
			if (ptype == 0)
				 break;
			nskeyedarchive_nsarray_append_v(ka, arr, ptype, va);
		} while (1);
		nskeyedarchive_set_class_property(ka, newuid, "NS.objects", NSTYPE_ARRAY, arr);
		plist_free(arr);
		}
		break;
	case NSTYPE_NSMUTABLEDICTIONARY:
	case NSTYPE_NSDICTIONARY:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		newuid = ka->uid;
		if (type == NSTYPE_NSMUTABLEDICTIONARY) {
			nskeyedarchive_append_class(ka, "NSMutableDictionary", "NSDictionary", "NSObject", NULL);
		} else {
			nskeyedarchive_append_class(ka, "NSDictionary", "NSObject", NULL);
		}
		{
		plist_t keyarr = plist_new_array();
		plist_t valarr = plist_new_array();
		do {
			char* key = va_arg(*va, char*);
			if (!key)
				break;
			int ptype = va_arg(*va, int);
			if (ptype == 0)
				break;
			nskeyedarchive_nsarray_append(ka, keyarr, NSTYPE_STRING, key);
			nskeyedarchive_nsarray_append_v(ka, valarr, ptype, va);
		} while (1);
		nskeyedarchive_set_class_property(ka, newuid, "NS.keys", NSTYPE_ARRAY, keyarr);
		nskeyedarchive_set_class_property(ka, newuid, "NS.objects", NSTYPE_ARRAY, valarr);
		plist_free(keyarr);
		plist_free(valarr);
		}
		break;
	case NSTYPE_NSDATE:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		newuid = ka->uid;
		nskeyedarchive_append_class(ka, "NSDate", "NSObject", NULL);
		nskeyedarchive_set_class_property(ka, newuid, "NS.time", NSTYPE_REAL, va_arg(*va, double));
		break;
	case NSTYPE_NSMUTABLEDATA:
	case NSTYPE_NSDATA:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		newuid = ka->uid;
		nskeyedarchive_append_class(ka, "NSMutableData", "NSData", "NSObject", NULL);
		nskeyedarchive_set_class_property(ka, newuid, "NS.data", NSTYPE_DATA, va_arg(*va, char*));
		break;
	case NSTYPE_NSURL:
		plist_array_append_item(array, plist_new_uid(++ka->uid));
		newuid = ka->uid;
		nskeyedarchive_append_class(ka, "NSURL", "NSObject", NULL);
		{
		int ptype = va_arg(*va, int);
		if (ptype == 0)
			break;
		nskeyedarchive_set_class_property_v(ka, newuid, "NS.base", ptype, va);
		ptype = va_arg(*va, int);
		if (ptype == 0)
			break;
		nskeyedarchive_set_class_property_v(ka, newuid, "NS.relative",  ptype, va);
		}
		break;
	case NSTYPE_NSKEYEDARCHIVE:
		{
		nskeyedarchive_t pka = va_arg(*va, nskeyedarchive_t);
		if (!pka) {
			fprintf(stderr, "%s: ERROR: no nskeyedarchive argument given for type NSTYPE_NSKEYEDARCHIVE\n", __func__);
			return;
		}
		uint64_t top = nskeyedarchive_get_class_uid(pka, NULL);
		if (top != 0) {
			plist_array_append_item(array, plist_new_uid(++ka->uid));

			plist_t object = nskeyedarchive_get_object_by_uid(pka, top);
			if (!object) {
				fprintf(stderr, "%s: ERROR: can't get object for uid %lld\n", __func__, (long long)top);
				return;
			}

			plist_t objcopy = plist_copy(object);
			nskeyedarchive_append_object(ka, objcopy);
			nskeyedarchive_merge_object(ka, pka, objcopy);
		}
		}
		break;
	case NSTYPE_FROM_PLIST:
		{
		plist_t plist = va_arg(*va, plist_t);
		if (!plist) {
			fprintf(stderr, "%s: ERROR: no plist argument given for NSTYPE_PLIST\n", __func__);
			return;
		}
		switch (plist_get_node_type(plist)) {
		case PLIST_STRING:
		{
			char* str = NULL;
			plist_get_string_val(plist, &str);
			nskeyedarchive_nsarray_append(ka, array, NSTYPE_NSMUTABLESTRING, str, NULL);
		} break;
		case PLIST_DICT:
		{
			plist_array_append_item(array, plist_new_uid(++ka->uid));
			newuid = ka->uid;
			nskeyedarchive_append_class(ka, "NSDictionary", "NSObject", NULL);

			plist_t keyarr = plist_new_array();
			plist_t valarr = plist_new_array();

			plist_dict_iter iter = NULL;
			plist_dict_new_iter(plist, &iter);

			char *key = NULL;
			plist_t node = NULL;

			do {
				plist_dict_next_item(plist, iter, &key, &node);
				if (key) {
					int ptype = 0;
					uint8_t bv = 0;
					uint64_t u64val = 0;
					int intval = 0;
					char *str = NULL;
					void *val = NULL;
					nskeyedarchive_nsarray_append(ka, keyarr, NSTYPE_STRING, key);
					switch (plist_get_node_type(node)) {
					case PLIST_BOOLEAN: {
						ptype = NSTYPE_BOOLEAN;
						plist_get_bool_val(node, &bv);
						intval = bv;
						val = &intval;
						} break;
					case PLIST_UINT:
						ptype = NSTYPE_INTEGER;
						plist_get_uint_val(node, &u64val);
						val = &u64val;
						break;
					case PLIST_STRING:
						ptype = NSTYPE_STRING;
						plist_get_string_val(node, &str);
						val = str;
						break;
					default:
						fprintf(stderr, "Unhandled plist type when parsing plist_dict\n");
						break;
					}
					nskeyedarchive_nsarray_append(ka, valarr, ptype, val);
				}
				free(key);
			} while (node);

			free(iter);

			nskeyedarchive_set_class_property(ka, newuid, "NS.keys", NSTYPE_ARRAY, keyarr);
			nskeyedarchive_set_class_property(ka, newuid, "NS.objects", NSTYPE_ARRAY, valarr);
			plist_free(keyarr);
			plist_free(valarr);
		} break;
		default:
			fprintf(stderr, "%s: ERROR: unhandled plist type %d\n", __func__, plist_get_node_type(plist));
			return;
		}
		}
		break;
	default:
		fprintf(stderr, "%s: unexpected type %d\n", __func__, type);
		break;
	}
}

static void nskeyedarchive_nsarray_append(nskeyedarchive_t ka, plist_t array, enum nskeyedarchive_class_type_t type, ...)
{
	va_list va;
	va_start(va, type);
	nskeyedarchive_nsarray_append_v(ka, array, type, &va);
	va_end(va);
}

void nskeyedarchive_nsarray_append_item(nskeyedarchive_t ka, uint64_t uid, enum nskeyedarchive_class_type_t type, ...)
{
	if (!ka) {
		return;
	}
	plist_t objects = NULL;
	nskeyedarchive_get_class_property(ka, uid, "NS.objects", &objects);
	if (!objects) {
		fprintf(stderr, "ERROR: invalid NSArray object in archive: missing NS.objects property\n");
		return;
	}
	va_list va;
	va_start(va, type);
	nskeyedarchive_nsarray_append_v(ka, objects, type, &va);
	va_end(va);
}

void nskeyedarchive_nsdictionary_add_item(nskeyedarchive_t ka, uint64_t uid, const char* key, enum nskeyedarchive_class_type_t type, ...)
{
	if (!ka) {
		return;
	}
	plist_t keys = NULL;
	nskeyedarchive_get_class_property(ka, uid, "NS.keys", &keys);
	if (!keys) {
		fprintf(stderr, "ERROR: invalid NSDictionary object in archive: missing NS.keys property\n");
		return;
	}
	plist_t objects = NULL;
	nskeyedarchive_get_class_property(ka, uid, "NS.objects", &objects);
	if (!objects) {
		fprintf(stderr, "ERROR: invalid NSDictionary object in archive: missing NS.objects property\n");
		return;
	}
	va_list va;
	va_start(va, type);
	nskeyedarchive_nsarray_append(ka, keys, NSTYPE_STRING, key);
	nskeyedarchive_nsarray_append_v(ka, objects, type, &va);
	va_end(va);
}

void nskeyedarchive_append_class_type_v(nskeyedarchive_t ka, enum nskeyedarchive_class_type_t type, va_list* va)
{
	uint64_t newuid = 0;

	switch (type) {
	case NSTYPE_INTEGER:
		fprintf(stderr, "%s: ERROR: NSTYPE_INTEGER is not an object type, can't add it as class!.\n", __func__);
		break;
	case NSTYPE_INTREF:
		nskeyedarchive_append_object(ka, plist_new_uint(va_arg(*va, int)));
		break;
	case NSTYPE_BOOLEAN:
		nskeyedarchive_append_object(ka, plist_new_bool(va_arg(*va, int)));
		break;
	case NSTYPE_CHARS:
		fprintf(stderr, "%s: ERROR: NSTYPE_CHARS is not an object type, can't add it as class!\n", __func__);
		break;
	case NSTYPE_STRING:
		{
		char* strval = va_arg(*va, char*);
		if (strval) {
			if (strcmp(strval, "$null") != 0) {
				nskeyedarchive_append_object(ka, plist_new_string(strval));
			} else {
				// make $null the top class if required
				plist_t top = plist_dict_get_item(ka->dict, "$top");
				if (!top) {
					top = plist_new_dict();
					plist_dict_set_item(top, "$0", plist_new_uid(0));
					plist_dict_set_item(ka->dict, "$top", top);
				}
			}
		}
		}
		break;
	case NSTYPE_REAL:
		nskeyedarchive_append_object(ka, plist_new_real(va_arg(*va, double)));
		break;
	case NSTYPE_ARRAY:
		fprintf(stderr, "%s: ERROR: NSTYPE_ARRAY is not an object type, can't add it as class!\n", __func__);
		return;
	case NSTYPE_NSMUTABLESTRING:
	case NSTYPE_NSSTRING:
		newuid = ka->uid;
		if (type == NSTYPE_NSMUTABLESTRING) {
			nskeyedarchive_append_class(ka, "NSMutableString", "NSString", "NSObject", NULL);
		} else {
			nskeyedarchive_append_class(ka, "NSString", "NSObject", NULL);
		}
		nskeyedarchive_set_class_property(ka, newuid, "NS.string", NSTYPE_STRING, va_arg(*va, char*));
		break;
	case NSTYPE_NSMUTABLEARRAY:
	case NSTYPE_NSARRAY:
		newuid = ka->uid;
		if (type == NSTYPE_NSMUTABLEARRAY) {
			nskeyedarchive_append_class(ka, "NSMutableArray", "NSArray", "NSObject", NULL);
		} else {
			nskeyedarchive_append_class(ka, "NSArray", "NSObject", NULL);
		}
		{
		plist_t arr = plist_new_array();
		do {
			int ptype = va_arg(*va, int);
			if (ptype == 0)
				 break;
			nskeyedarchive_nsarray_append_v(ka, arr, ptype, va);
		} while (1);
		nskeyedarchive_set_class_property(ka, newuid, "NS.objects", NSTYPE_ARRAY, arr);
		plist_free(arr);
		}
		break;
	case NSTYPE_NSMUTABLEDICTIONARY:
	case NSTYPE_NSDICTIONARY:
		newuid = ka->uid;
		if (type == NSTYPE_NSMUTABLEDICTIONARY) {
			nskeyedarchive_append_class(ka, "NSMutableDictionary", "NSDictionary", "NSObject", NULL);
		} else {
			nskeyedarchive_append_class(ka, "NSDictionary", "NSObject", NULL);
		}
		{
		plist_t keyarr = plist_new_array();
		plist_t valarr = plist_new_array();
		do {
			char* key = va_arg(*va, char*);
			if (!key)
				break;
			int ptype = va_arg(*va, int);
			if (ptype == 0)
				break;
			nskeyedarchive_nsarray_append(ka, keyarr, NSTYPE_STRING, key);
			nskeyedarchive_nsarray_append_v(ka, valarr, ptype, va);
		} while (1);
		nskeyedarchive_set_class_property(ka, newuid, "NS.keys", NSTYPE_ARRAY, keyarr);
		nskeyedarchive_set_class_property(ka, newuid, "NS.objects", NSTYPE_ARRAY, valarr);
		plist_free(keyarr);
		plist_free(valarr);
		}
		break;
	case NSTYPE_NSDATE:
		newuid = ka->uid;
		nskeyedarchive_append_class(ka, "NSDate", "NSObject", NULL);
		nskeyedarchive_set_class_property(ka, newuid, "NS.time", NSTYPE_REAL, va_arg(*va, double));
		break;
	case NSTYPE_NSMUTABLEDATA:
	case NSTYPE_NSDATA:
		newuid = ka->uid;
		nskeyedarchive_append_class(ka, "NSMutableData", "NSData", "NSObject", NULL);
		nskeyedarchive_set_class_property(ka, newuid, "NS.data", NSTYPE_DATA, va_arg(*va, char*));
		break;
	case NSTYPE_NSURL:
		newuid = ka->uid;
		nskeyedarchive_append_class(ka, "NSURL", "NSObject", NULL);
		{
		int ptype = va_arg(*va, int);
		if (ptype == 0)
			break;
		nskeyedarchive_set_class_property_v(ka, newuid, "NS.base", ptype, va);
		ptype = va_arg(*va, int);
		if (ptype == 0)
			break;
		nskeyedarchive_set_class_property_v(ka, newuid, "NS.relative",  ptype, va);
		}
		break;
	default:
		fprintf(stderr, "unexpected class type %d\n", type);
		return;
	}

	plist_t top = plist_dict_get_item(ka->dict, "$top");
	if (!top) {
		top = plist_new_dict();
		plist_dict_set_item(top, "$0", plist_new_uid(1));
		plist_dict_set_item(ka->dict, "$top", top);
	}
}

void nskeyedarchive_append_class_type(nskeyedarchive_t ka, enum nskeyedarchive_class_type_t type, ...)
{
	if (!ka) {
		fprintf(stderr, "%s: ERROR: invalid keyed archive!\n", __func__);
		return;
	} else if (!type) {
		fprintf(stderr, "%s: ERROR: invalid class type!\n", __func__);
		return;
	}

	va_list va;
	va_start(va, type);
	nskeyedarchive_append_class_type_v(ka, type, &va);
	va_end(va);
}

void nskeyedarchive_merge_object(nskeyedarchive_t ka, nskeyedarchive_t pka, plist_t object)
{
	if (!ka || !pka || !object) {
		return;
	}

	switch (plist_get_node_type(object)) {
	case PLIST_DICT:
		{
		plist_dict_iter iter = NULL;
		plist_dict_new_iter(object, &iter);
		if (iter) {
			plist_t val;
			char* key;
			do {
				key = NULL;
				val = NULL;
				plist_dict_next_item(object, iter, &key, &val);
				if (key) {
					switch (plist_get_node_type(val)) {
					case PLIST_UID:
						{
						uint64_t thisuid = 0;
						plist_get_uid_val(val, &thisuid);
						if (thisuid > 0) {
							// remap thisuid to ka->uid+1
							plist_t nextobj = nskeyedarchive_get_object_by_uid(pka, thisuid);
							plist_set_uid_val(val, ++ka->uid);
							plist_t nextcopy = plist_copy(nextobj);
							nskeyedarchive_append_object(ka, nextcopy);
							nskeyedarchive_merge_object(ka, pka, nextcopy);
						}
						}
						break;
					case PLIST_DICT:
					case PLIST_ARRAY:
						nskeyedarchive_merge_object(ka, pka, val);
						break;
					default:
						break;
					}
					free(key);
				}
			} while (val);
			free(iter);
		}
		}
		break;
	case PLIST_ARRAY:
		{
		uint32_t i;
		for (i = 0; i < plist_array_get_size(object); i++) {
			plist_t val = plist_array_get_item(object, i);
			switch (plist_get_node_type(val)) {
			case PLIST_UID:
				{
				uint64_t thisuid = 0;
				plist_get_uid_val(val, &thisuid);
				if (thisuid > 0) {
					// remap thisuid to ka->uid+1
					plist_t nextobj = nskeyedarchive_get_object_by_uid(pka, thisuid);
					plist_set_uid_val(val, ++ka->uid);
					plist_t nextcopy = plist_copy(nextobj);
					nskeyedarchive_append_object(ka, nextcopy);
					nskeyedarchive_merge_object(ka, pka, nextcopy);
				}
				}
				break;
			case PLIST_ARRAY:
			case PLIST_DICT:
				nskeyedarchive_merge_object(ka, pka, val);
				break;
			default:
				break;
			}
		}
		}
		break;
	default:
		break;
	}

}

static void nskeyedarchive_set_class_property_v(nskeyedarchive_t ka, uint64_t uid, const char* propname, enum nskeyedarchive_class_type_t proptype, va_list* va)
{
	plist_t a = nskeyedarchive_get_class_by_uid(ka, uid);
	if (a == NULL)
		return;

	uint64_t newuid;

	switch (proptype) {
	case NSTYPE_INTEGER:
		plist_dict_set_item(a, propname, plist_new_uint(va_arg(*va, int)));
		break;
	case NSTYPE_INTREF:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_object(ka, plist_new_uint(va_arg(*va, int)));
		break;
	case NSTYPE_BOOLEAN:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_object(ka, plist_new_bool(va_arg(*va, int)));
		break;
	case NSTYPE_CHARS:
		plist_dict_set_item(a, propname, plist_new_string(va_arg(*va, char*)));
		break;
	case NSTYPE_STRING:
		{
		char* strval = va_arg(*va, char*);
		if (strval && (strcmp(strval, "$null") == 0)) {
			plist_dict_set_item(a, propname, plist_new_uid(0));
		} else {
			plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
			nskeyedarchive_append_object(ka, plist_new_string(strval));
		}
		}
		break;
	case NSTYPE_REAL:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_class_type_v(ka, proptype, va);
		break;
	case NSTYPE_ARRAY:
		plist_dict_set_item(a, propname, plist_copy(va_arg(*va, plist_t)));
		break;
	case NSTYPE_NSMUTABLESTRING:
	case NSTYPE_NSSTRING:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_class_type_v(ka, proptype, va);
		break;
	case NSTYPE_NSMUTABLEARRAY:
	case NSTYPE_NSARRAY:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_class_type_v(ka, proptype, va);
		break;
	case NSTYPE_NSMUTABLEDICTIONARY:
	case NSTYPE_NSDICTIONARY:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_class_type_v(ka, proptype, va);
		break;
	case NSTYPE_NSDATE:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_class_type_v(ka, proptype, va);
		break;
	case NSTYPE_NSMUTABLEDATA:
	case NSTYPE_NSDATA:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_class_type_v(ka, proptype, va);
		break;
	case NSTYPE_NSURL:
		plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
		nskeyedarchive_append_class_type_v(ka, proptype, va);
		break;
	case NSTYPE_NSKEYEDARCHIVE:
		{
		nskeyedarchive_t pka = va_arg(*va, nskeyedarchive_t);
		if (!pka) {
			fprintf(stderr, "%s: ERROR: no nskeyedarchive argument given for type NSTYPE_NSKEYEDARCHIVE\n", __func__);
			return;
		}
		uint64_t top = nskeyedarchive_get_class_uid(pka, NULL);
		if (top != 0) {
			plist_t object = nskeyedarchive_get_object_by_uid(pka, top);
			if (!object) {
				fprintf(stderr, "%s: ERROR: can't get object for uid %lld\n", __func__, (long long)top);
				return;
			}

			plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
			plist_t objcopy = plist_copy(object);
			nskeyedarchive_append_object(ka, objcopy);
			nskeyedarchive_merge_object(ka, pka, objcopy);
		} else {
			plist_dict_set_item(a, propname, plist_new_uid(0));
		}
		}
		break;
	case NSTYPE_FROM_PLIST:
		{
		plist_t plist = va_arg(*va, plist_t);
		if (!plist) {
			fprintf(stderr, "%s: ERROR: no plist argument given for NSTYPE_PLIST\n", __func__);
			return;
		}
		switch (plist_get_node_type(plist)) {
		case PLIST_ARRAY:
			plist_dict_set_item(a, propname, plist_new_uid(++ka->uid));
			newuid = ka->uid;
			nskeyedarchive_append_class(ka, "NSMutableArray", "NSArray", "NSObject", NULL);
			{
			plist_t arr = plist_new_array();
			uint32_t ai;
			for (ai = 0; ai < plist_array_get_size(plist); ai++) {
				plist_t ae = plist_array_get_item(plist, ai);
				nskeyedarchive_nsarray_append(ka, arr, NSTYPE_FROM_PLIST, ae);
			}
			nskeyedarchive_set_class_property(ka, newuid, "NS.objects", NSTYPE_ARRAY, arr);
			}
			break;
		default:
			fprintf(stderr, "%s: sorry, plist type %d is not implemented for conversion.\n", __func__, plist_get_node_type(plist));
			break;
		}
		}
		break;
	default:
		fprintf(stderr, "unexpected property type %d\n", proptype);
		break;
	}
}

void nskeyedarchive_set_class_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, enum nskeyedarchive_class_type_t proptype, ...)
{
	plist_t a = nskeyedarchive_get_class_by_uid(ka, uid);
	if (a == NULL) {
		return;
	}

	va_list va;
	va_start(va, proptype);
	nskeyedarchive_set_class_property_v(ka, uid, propname, proptype, &va);
	va_end(va);
}


void nskeyedarchive_print(nskeyedarchive_t ka)
{
	char* xml = NULL;
	uint32_t xlen = 0;
	plist_to_xml(ka->dict, &xml, &xlen);
	puts(xml);
	free(xml);
}

plist_t nskeyedarchive_get_plist_ref(nskeyedarchive_t ka)
{
	return ka->dict;
}

nskeyedarchive_t nskeyedarchive_new_from_plist(plist_t plist)
{
	if (!plist || (plist_get_node_type(plist) != PLIST_DICT)) {
		fprintf(stderr, "%s: ERROR: invalid parameter, PLIST_DICT expected\n", __func__);
		return NULL;
	}

	plist_t node;
	char* strval = NULL;
	uint64_t uintval = 0;

	// check for $archiver key
	node = plist_dict_get_item(plist, "$archiver");
	if (node && (plist_get_node_type(node) == PLIST_STRING)) {
		plist_get_string_val(node, &strval);
	}
	if (!strval || (strcmp(strval, "NSKeyedArchiver") != 0)) {
		fprintf(stderr, "%s: ERROR: plist is not in NSKeyedArchiver format ($archiver key not found or invalid)!\n", __func__);
		if (strval)
			free(strval);
		return NULL;
	}
	if (strval)
		free(strval);
	strval = NULL;

	// check for $version key
	node = plist_dict_get_item(plist, "$version");
	if (node && (plist_get_node_type(node) == PLIST_UINT)) {
		plist_get_uint_val(node, &uintval);
	}
	if (uintval != 100000) {
		fprintf(stderr, "%s: ERROR: unexpected NSKeyedArchiver version encountered (%lld != 100000)!\n", __func__, (long long int)uintval);
		return NULL;
	}
	uintval = 0;

	// check for $top key
	node = plist_dict_get_item(plist, "$top");
	if (!node || (plist_get_node_type(node) != PLIST_DICT)) {
		fprintf(stderr, "%s: ERROR: $top node not found\n", __func__);
		return NULL;
	}
	plist_t topuid = plist_dict_get_item(node, "$0");
	if (!topuid) {
		topuid = plist_dict_get_item(node, "root");
	}
	if (!topuid || (plist_get_node_type(topuid) != PLIST_UID)) {
		fprintf(stderr, "%s: ERROR: uid '$0' or 'root' not found in $top dict!\n", __func__);
		return NULL;
	}

	uintval = -1LL;
	plist_get_uid_val(topuid, (uint64_t*)&uintval);

	if (uintval == (uint64_t)-1LL) {
		fprintf(stderr, "%s: ERROR: could not get UID value.\n", __func__);
		return NULL;
	}

	// check for $objects key
	plist_t objects = plist_dict_get_item(plist, "$objects");
	if (!objects || (plist_get_node_type(objects) != PLIST_ARRAY)) {
		fprintf(stderr, "%s: ERROR: $objects node not found!\n", __func__);
		return NULL;
	}
	plist_t obj = plist_array_get_item(objects, (uint32_t)uintval);
	if (!obj) {
		fprintf(stderr, "%s: ERROR: can't get object node\n", __func__);
		return NULL;
	}

	nskeyedarchive_t archive = (nskeyedarchive_t)malloc(sizeof(struct nskeyedarchive_st));
	archive->dict = plist_copy(plist);
	archive->uid = plist_array_get_size(objects) - 1;

	return archive;
}

nskeyedarchive_t nskeyedarchive_new_from_data(const void* data, uint32_t size)
{
	if (!data || (size < 8)) {
		fprintf(stderr, "%s: ERROR: invalid parameter\n", __func__);
		return NULL;
	}


	plist_t plist = NULL;
	if (memcmp(data, "bplist00", 8) == 0) {
		plist_from_bin(data, size, &plist);
	} else if ((memcmp(data, "<?xml", 5) == 0) || (memcmp(data, "<plist", 6) == 0)) {
		plist_from_xml(data, size, &plist);
	} else {
		// fail silently
		return NULL;
	}
	if (!plist) {
		fprintf(stderr, "%s: ERROR: Can't parse plist from data\n", __func__);
		return NULL;
	}

	nskeyedarchive_t ka = nskeyedarchive_new_from_plist(plist);
	plist_free(plist);
	return ka;
}

uint64_t nskeyedarchive_get_class_uid(nskeyedarchive_t ka, const char* classref)
{
	uint64_t uintval = -1LL;
	if (!ka) {
		return uintval;
	}
	if (!ka->dict) {
		return uintval;
	}

	plist_t node;

	node = plist_dict_get_item(ka->dict, "$top");
	if (!node || (plist_get_node_type(node) != PLIST_DICT)) {
		fprintf(stderr, "%s: ERROR: $top node not found\n", __func__);
		return 0;
	}
	plist_t topuid = plist_dict_get_item(node, (classref) ? classref : "$0");
	if (!topuid && !classref) {
		topuid = plist_dict_get_item(node, "root");
	}
	if (!topuid || (plist_get_node_type(topuid) != PLIST_UID)) {
		fprintf(stderr, "%s: ERROR: uid for '%s' not found in $top dict!\n", __func__, classref);
		return 0;
	}

	plist_get_uid_val(topuid, (uint64_t*)&uintval);

	return uintval;
}

const char* nskeyedarchive_get_classname(nskeyedarchive_t ka, uint64_t uid)
{
	if (!ka) {
		return NULL;
	}
	if (!ka->dict) {
		return NULL;
	}

	plist_t obj = nskeyedarchive_get_object_by_uid(ka, uid);
	if (!obj) {
		return NULL;
	}

	plist_t classuid = plist_dict_get_item(obj, "$class");
	if (plist_get_node_type(classuid) != PLIST_UID) {
		fprintf(stderr, "ERROR: $class is not a uid node\n");
		return NULL;
	}

	uint64_t uintval = 0;
	plist_get_uid_val(classuid, &uintval);
	if (uintval == 0) {
		fprintf(stderr, "ERROR: can't get $class uid val\n");
		return NULL;
	}

	plist_t cls = nskeyedarchive_get_class_by_uid(ka, uintval);
	if (!cls) {
		return NULL;
	}

	plist_t classname = plist_dict_get_item(cls, "$classname");
	if (!classname || (plist_get_node_type(classname) != PLIST_STRING)) {
		fprintf(stderr, "ERROR: invalid $classname in class dict\n");
		return NULL;
	}

	return plist_get_string_ptr(classname, NULL);
}

int nskeyedarchive_get_class_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, plist_t* value)
{
	if (!ka || !ka->dict || !value) {
		return -1;
	}

	plist_t obj = nskeyedarchive_get_class_by_uid(ka, uid);
	if (!obj) {
		return -1;
	}

	*value = plist_dict_get_item(obj, propname);
	if (!*value) {
		return -1;
	}

	return 0;
}

int nskeyedarchive_get_class_uint64_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, uint64_t* value)
{
	plist_t prop = NULL;

	nskeyedarchive_get_class_property(ka, uid, propname, &prop);
	if (!prop) {
		fprintf(stderr, "%s: ERROR: no such property '%s'\n", __func__, propname);
		return -1;
	}

	if (plist_get_node_type(prop) == PLIST_UID) {
		uint64_t uintval = 0;
		plist_get_uid_val(prop, &uintval);
		prop = nskeyedarchive_get_object_by_uid(ka, uintval);
	}

	if (plist_get_node_type(prop) != PLIST_UINT) {
		fprintf(stderr, "%s: ERROR: property '%s' is not of type integer.\n", __func__, propname);
		return -1;
	}

	plist_get_uint_val(prop, value);

	return 0;
}

int nskeyedarchive_get_class_int_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, int* value)
{
	uint64_t uintval = 0;
	int res = nskeyedarchive_get_class_uint64_property(ka, uid, propname, &uintval);
	if (res < 0) {
		return res;
	}
	*value = (int)uintval;
	return 0;
}

int nskeyedarchive_get_class_string_property(nskeyedarchive_t ka, uint64_t uid, const char* propname, char** value)
{
	plist_t node = NULL;

	nskeyedarchive_get_class_property(ka, uid, propname, &node);
	if (!node || (plist_get_node_type(node) != PLIST_UID)) {
		return -1;
	}

	uint64_t uintval = 0;
	plist_get_uid_val(node, &uintval);

	plist_t prop = nskeyedarchive_get_object_by_uid(ka, uintval);
	if (!prop || (plist_get_node_type(prop) != PLIST_STRING)) {
		fprintf(stderr, "%s: ERROR: property '%s' is not a string\n", __func__, propname);
		return -1;
	}

	plist_get_string_val(prop, value);

	return 0;
}

static plist_t _nska_parse_object(nskeyedarchive_t ka, uint64_t uid)
{
	plist_t obj = nskeyedarchive_get_object_by_uid(ka, uid);
	switch (plist_get_node_type(obj)) {
		case PLIST_BOOLEAN:
		case PLIST_INT:
		case PLIST_STRING:
			return plist_copy(obj);
		default:
			break;
	}

	const char* clsn = nskeyedarchive_get_classname(ka, uid);
	plist_t pl = NULL;
	if (!strcmp(clsn, "NSMutableDictionary") || !strcmp(clsn, "NSDictionary")) {
		plist_t keys = NULL;
		nskeyedarchive_get_class_property(ka, uid, "NS.keys", &keys);
		plist_t vals = NULL;
		nskeyedarchive_get_class_property(ka, uid, "NS.objects", &vals);

		uint32_t count = plist_array_get_size(keys);
		if (count != plist_array_get_size(vals)) {
			printf("ERROR: %s: inconsistent number of keys vs. values in dictionary object\n", __func__);
			return NULL;
		}
		pl = plist_new_dict();
		uint32_t i = 0;
		for (i = 0; i < count; i++) {
			plist_t knode = plist_array_get_item(keys, i);
			plist_t vnode = plist_array_get_item(vals, i);

			uint64_t subuid = 0;
			plist_get_uid_val(knode, &subuid);
			plist_t newkey = _nska_parse_object(ka, subuid);

			subuid = 0;
			plist_get_uid_val(vnode, &subuid);
			plist_t newval = _nska_parse_object(ka, subuid);

			if (!PLIST_IS_STRING(newkey)) {
				printf("ERROR: %s: key node is not of string type.\n", __func__);
				return NULL;
			}

			plist_dict_set_item(pl, plist_get_string_ptr(newkey, NULL), newval);
			plist_free(newkey);
		}
	} else if (!strcmp(clsn, "NSMutableArray") || !strcmp(clsn, "NSArray")) {
		plist_t vals = NULL;
		nskeyedarchive_get_class_property(ka, uid, "NS.objects", &vals);

		uint32_t count = plist_array_get_size(vals);
		pl = plist_new_array();
		uint32_t i = 0;
		for (i = 0; i < count; i++) {
			plist_t vnode = plist_array_get_item(vals, i);
			uint64_t subuid = 0;
			plist_get_uid_val(vnode, &subuid);
			plist_t newval = _nska_parse_object(ka, subuid);
			plist_array_append_item(pl, newval);
		}	
	} else {
		printf("ERROR: %s: unhandled class type '%s'\n", __func__, clsn);
	}
	return pl;
}

plist_t nskeyedarchive_to_plist(nskeyedarchive_t ka)
{
	uint64_t obj_uid = nskeyedarchive_get_class_uid(ka, NULL);
	return _nska_parse_object(ka, obj_uid);
}
07070100000025000081A400000000000000000000000167AD5DE900003072000000000000000000000000000000000000003700000000libimobiledevice-glue-1.3.1+git18.20250213/src/opack.c/*
 * opack.c
 * "opack" format encoder/decoder implementation.
 *
 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>

#include "common.h"
#include "libimobiledevice-glue/cbuf.h"
#include "libimobiledevice-glue/opack.h"
#include "endianness.h"

#define MAC_EPOCH 978307200

static void opack_encode_node(plist_t node, struct char_buf* cbuf)
{
	plist_type type = plist_get_node_type(node);
	switch (type) {
		case PLIST_DICT: {
			uint32_t count = plist_dict_get_size(node);
			uint8_t blen = 0xEF;
			if (count < 15)
				blen = (uint8_t)count-32;	
			char_buf_append(cbuf, 1, &blen);
			plist_dict_iter iter = NULL;
			plist_dict_new_iter(node, &iter);
			if (iter) {
				plist_t sub = NULL;
				do {
					sub = NULL;
					plist_dict_next_item(node, iter, NULL, &sub);
					if (sub) {
						plist_t key = plist_dict_item_get_key(sub);
						opack_encode_node(key, cbuf);
						opack_encode_node(sub, cbuf);
					}
				} while (sub);
				free(iter);
				if (count > 14) {
					uint8_t term = 0x03;
					char_buf_append(cbuf, 1, &term);
				}
			}
		}	break;
		case PLIST_ARRAY: {
			uint32_t count = plist_array_get_size(node);
			uint8_t blen = 0xDF;
			if (count < 15)
				blen = (uint8_t)(count-48);
			char_buf_append(cbuf, 1, &blen);
			plist_array_iter iter = NULL;
			plist_array_new_iter(node, &iter);
			if (iter) {
				plist_t sub = NULL;
				do {
					sub = NULL;
					plist_array_next_item(node, iter, &sub);
					if (sub) {
						opack_encode_node(sub, cbuf);
					}
				} while (sub);
				free(iter);
				if (count > 14) {
					uint8_t term = 0x03;
					char_buf_append(cbuf, 1, &term);
				}
			}
		}	break;
		case PLIST_BOOLEAN: {
			uint8_t bval = 2 - plist_bool_val_is_true(node);
			char_buf_append(cbuf, 1, &bval);
		}	break;
		case PLIST_UINT: {
			uint64_t u64val = 0;
			plist_get_uint_val(node, &u64val);
			if ((uint8_t)u64val == u64val) {
				uint8_t u8val = (uint8_t)u64val;
				if (u8val > 0x27) {
					uint8_t blen = 0x30;
					char_buf_append(cbuf, 1, &blen);
					char_buf_append(cbuf, 1, &u8val);
				} else {
					u8val += 8;
					char_buf_append(cbuf, 1, &u8val);
				}
			} else if ((uint32_t)u64val == u64val) {
				uint8_t blen = 0x32;
				char_buf_append(cbuf, 1, &blen);
				uint32_t u32val = (uint32_t)u64val;
				u32val = htole32(u32val);
				char_buf_append(cbuf, 4, (unsigned char*)&u32val);
			} else {
				uint8_t blen = 0x33;
				char_buf_append(cbuf, 1, &blen);
				u64val = htole64(u64val);
				char_buf_append(cbuf, 8, (unsigned char*)&u64val);
			}
		}	break;
		case PLIST_REAL: {
			double dval = 0;
			plist_get_real_val(node, &dval);
			if ((float)dval == dval) {
				float fval = (float)dval;
				uint32_t u32val = 0;
				memcpy(&u32val, &fval, 4);
				u32val = float_bswap32(u32val);
				uint8_t blen = 0x35;
				char_buf_append(cbuf, 1, &blen);
				char_buf_append(cbuf, 4, (unsigned char*)&u32val);
			} else {
				uint64_t u64val = 0;
				memcpy(&u64val, &dval, 8);
				u64val = float_bswap64(u64val);
				uint8_t blen = 0x36;
				char_buf_append(cbuf, 1, &blen);
				char_buf_append(cbuf, 8, (unsigned char*)&u64val);
			}
		}	break;
		case PLIST_DATE: {
			int32_t sec = 0;
			int32_t usec = 0;	
			plist_get_date_val(node, &sec, &usec);
			time_t tsec = sec;
			tsec -= MAC_EPOCH;
			double dval = (double)tsec + ((double)usec / 1000000);
			uint8_t blen = 0x06;
			char_buf_append(cbuf, 1, &blen);
			uint64_t u64val = 0;
			memcpy(&u64val, &dval, 8);
			u64val = float_bswap64(u64val);
			char_buf_append(cbuf, 8, (unsigned char*)&u64val);
		}	break;
		case PLIST_STRING:
		case PLIST_KEY: {
			uint64_t len = 0;
			char* str = NULL;
			if (type == PLIST_KEY) {
				plist_get_key_val(node, &str);
				len = strlen(str);
			} else {
				str = (char*)plist_get_string_ptr(node, &len);
			}
			if (len > 0x20) {
				if (len > 0xFF) {
					if (len > 0xFFFF) {
						if (len >> 32) {
							uint8_t blen = 0x64;
							char_buf_append(cbuf, 1, &blen);
							uint64_t u64val = htole64(len);
							char_buf_append(cbuf, 8, (unsigned char*)&u64val);
						} else {
							uint8_t blen = 0x63;
							char_buf_append(cbuf, 1, &blen);
							uint32_t u32val = htole32((uint32_t)len);
							char_buf_append(cbuf, 4, (unsigned char*)&u32val);
						}
					} else {
						uint8_t blen = 0x62;
						char_buf_append(cbuf, 1, &blen);
						uint16_t u16val = htole16((uint16_t)len);
						char_buf_append(cbuf, 2, (unsigned char*)&u16val);
					}
				} else {
					uint8_t blen = 0x61;
					char_buf_append(cbuf, 1, &blen);
					char_buf_append(cbuf, 1, (unsigned char*)&len);
				}
			} else {
				uint8_t blen = 0x40 + len;
				char_buf_append(cbuf, 1, &blen);
			}
			char_buf_append(cbuf, len, (unsigned char*)str);
			if (type == PLIST_KEY) {
				free(str);
			}
		}	break;
		case PLIST_DATA: {
			uint64_t len = 0;
			const char* data = plist_get_data_ptr(node, &len);
			if (len > 0x20) {
				if (len > 0xFF) {
					if (len > 0xFFFF) {
						if (len >> 32) {
							uint8_t blen = 0x94;
							char_buf_append(cbuf, 1, &blen);
							uint64_t u64val = htole64(len);
							char_buf_append(cbuf, 8, (unsigned char*)&u64val);
						} else {
							uint8_t blen = 0x93;
							char_buf_append(cbuf, 1, &blen);
							uint32_t u32val = htole32((uint32_t)len);
							char_buf_append(cbuf, 4, (unsigned char*)&u32val);
						}
					} else {
						uint8_t blen = 0x92;
						char_buf_append(cbuf, 1, &blen);
						uint16_t u16val = htole16((uint16_t)len);
						char_buf_append(cbuf, 2, (unsigned char*)&u16val);
					}
				} else {
					uint8_t blen = 0x91;
					char_buf_append(cbuf, 1, &blen);
					char_buf_append(cbuf, 1, (unsigned char*)&len);
				}
			} else {
				uint8_t blen = 0x70 + len;
				char_buf_append(cbuf, 1, &blen);
			}
			char_buf_append(cbuf, len, (unsigned char*)data);
		}	break;
		default:
			fprintf(stderr, "%s: ERROR: Unsupported data type in plist\n", __func__);
			break;
	}
}

void opack_encode_from_plist(plist_t plist, unsigned char** out, unsigned int* out_len)
{
	if (!plist || !out || !out_len) {
		return;
	}
	struct char_buf* cbuf = char_buf_new();
	opack_encode_node(plist, cbuf);
	*out = cbuf->data;
	*out_len = cbuf->length;
	cbuf->data = NULL;
	char_buf_free(cbuf);
}

static int opack_decode_obj(unsigned char** p, unsigned char* end, plist_t* plist_out, uint32_t level)
{
	uint8_t type = **p;
	if (type == 0x02) {
		/* bool: false */
		*plist_out = plist_new_bool(0);
		(*p)++;
		return 0;
	} else if (type == 0x01) {
		/* bool: true */
		*plist_out = plist_new_bool(1);
		(*p)++;
		return 0;
	} else if (type == 0x03) {
		/* NULL / structured type child node terminator */
		(*p)++;
		return -2;
	} else if (type == 0x06) {
		/* date type */
		(*p)++;
		double value = *(double*)*p;
		time_t sec = (time_t)value;
		value -= sec;
		uint32_t usec = value * 1000000;
		(*p)+=8;
		*plist_out = plist_new_date(sec, usec);
	} else if (type >= 0x08 && type <= 0x36) {
		/* numerical type */
		(*p)++;
		uint64_t value = 0;
		if (type == 0x36) {
			/* double */
			uint64_t u64val = float_bswap64(*(uint64_t*)(*p));
			(*p)+=8;
			double dval = 0;
			memcpy(&dval, &u64val, 8);
			*plist_out = plist_new_real(dval);
			return 0;
		} else if (type == 0x35) {
			/* float */
			uint32_t u32val = float_bswap32(*(uint32_t*)(*p));
			(*p)+=4;
			float fval = 0;
			memcpy(&fval, &u32val, 4);
			*plist_out = plist_new_real((double)fval);
			return 0;
		} else if (type < 0x30) {
			value = type - 8;
		} else if (type == 0x30) {
			value = (int8_t)**p;
			(*p)++;
		} else if (type == 0x32) {
			uint32_t u32val = *(uint32_t*)*p;
			value = (int32_t)le32toh(u32val);
			(*p)+=4;
		} else if (type == 0x33) {
			uint64_t u64val = *(uint64_t*)*p;
			value = le64toh(u64val);
			(*p)+=8;
		} else {
			fprintf(stderr, "%s: ERROR: Invalid encoded byte '%02x'\n", __func__, type);
			*p = end;
			return -1;
		}
		*plist_out = plist_new_uint(value);
	} else if (type >= 0x40 && type <= 0x64) {
		/* string */
		(*p)++;
		size_t slen = 0;
		if (type < 0x61) {
			slen = type - 0x40;
		} else {
			if (type == 0x61) {
				slen = **p;
				(*p)++;
			} else if (type == 0x62) {
				uint16_t u16val = *(uint16_t*)*p;
				slen = le16toh(u16val);
				(*p)+=2;
			} else if (type == 0x63) {
				uint32_t u32val = *(uint32_t*)*p;
				slen = le32toh(u32val);
				(*p)+=4;
			} else if (type == 0x64) {
				uint64_t u64val = *(uint64_t*)*p;
				slen = le64toh(u64val);
				(*p)+=8;
			}
		}
		if (*p + slen > end) {
			fprintf(stderr, "%s: ERROR: Size points past end of data\n", __func__);
			*p = end;
			return -1;
		}
		char* str = malloc(slen+1);
		strncpy(str, (const char*)*p, slen);
		str[slen] = '\0';
		*plist_out = plist_new_string(str);
		(*p)+=slen;
		free(str);
	} else if (type >= 0x70 && type <= 0x94) {
		/* data */
		(*p)++;
		size_t dlen = 0;
		if (type < 0x91) {
			dlen = type - 0x70;
		} else {
			if (type == 0x91) {
				dlen = **p;
				(*p)++;
			} else if (type == 0x92) {
				uint16_t u16val = *(uint16_t*)*p;
				dlen = le16toh(u16val);
				(*p)+=2;
			} else if (type == 0x93) {
				uint32_t u32val = *(uint32_t*)*p;
				dlen = le32toh(u32val);
				(*p)+=4;
			} else if (type == 0x94) {
				uint64_t u64val = *(uint64_t*)*p;
				dlen = le64toh(u64val);
				(*p)+=8;
			}
		}
		if (*p + dlen > end) {
			fprintf(stderr, "%s: ERROR: Size points past end of data\n", __func__);
			*p = end;
			return -1;
		}
		*plist_out = plist_new_data((const char*)*p, dlen);
		(*p)+=dlen;
	} else if (type >= 0xE0 && type <= 0xEF) {
		/* dictionary */
		(*p)++;
		plist_t dict = plist_new_dict();
		uint32_t num_children = 0xFFFFFFFF;
		if (type < 0xEF) {
			/* explicit number of children */
			num_children = type - 0xE0;
		}
		if (!*plist_out) {
			*plist_out = dict;	
		}
		uint32_t i = 0;
		while (i++ < num_children) {
			plist_t keynode = NULL;
			int res = opack_decode_obj(p, end, &keynode, level+1);
			if (res == -2) {
				break;
			} else if (res < 0) {
				return -1;
			}
			if (!PLIST_IS_STRING(keynode)) {
				plist_free(keynode);
				fprintf(stderr, "%s: ERROR: Invalid node type for dictionary key node\n", __func__);
				*p = end;
				return -1;
			}
			char* key = NULL;
			plist_get_string_val(keynode, &key);
			plist_free(keynode);
			plist_t valnode = NULL;
			if (opack_decode_obj(p, end, &valnode, level+1) < 0) {
				free(key);
				return -1;
			}
			plist_dict_set_item(dict, key, valnode);
		}
		if (level == 0) {
			*p = end;
			return 0;
		}
	} else if (type >= 0xD0 && type <= 0xDF) {
		/* array */
		(*p)++;
		plist_t array = plist_new_array();
		if (!*plist_out) {
			*plist_out = array;
		}
		uint32_t num_children = 0xFFFFFFFF;
		if (type < 0xDF) {
			/* explicit number of children */
			num_children = type - 0xD0;
		}
		uint32_t i = 0;
		while (i++ < num_children) {
			plist_t child = NULL;
			int res = opack_decode_obj(p, end, &child, level+1);
			if (res == -2) {
				if (type < 0xDF) {
					fprintf(stderr, "%s: ERROR: Expected child node, found terminator\n", __func__);
					*p = end;
					return -1;
				}
				break;
			} else if (res < 0) {
				return -1;
			}
			plist_array_append_item(array, child);
		}
		if (level == 0) {
			*p = end;
			return 0;
		}
	} else {
		fprintf(stderr, "%s: ERROR: Unexpected character '%02x encountered\n", __func__, type);
		*p = end;
		return -1;
	}
	return 0;
}

int opack_decode_to_plist(unsigned char* buf, unsigned int buf_len, plist_t* plist_out)
{
	if (!buf || buf_len == 0 || !plist_out) {
		return -1;
	}
	unsigned char* p = buf;
	unsigned char* end = buf + buf_len;
	while (p < end) {
		opack_decode_obj(&p, end, plist_out, 0);
	}
	return 0;
}
07070100000026000081A400000000000000000000000167AD5DE9000019C1000000000000000000000000000000000000003600000000libimobiledevice-glue-1.3.1+git18.20250213/src/sha1.c/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com
 */

#include "common.h"
#include "libimobiledevice-glue/sha.h"

#include <stdint.h>

#define ROLc(x, y) \
     ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | \
       (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define ROL ROLc

#define STORE32H(x, y)                                                                    \
    { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255);   \
      (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }

#define LOAD32H(x, y)                           \
    { x = ((unsigned long)((y)[0] & 255)<<24) | \
          ((unsigned long)((y)[1] & 255)<<16) | \
          ((unsigned long)((y)[2] & 255)<<8)  | \
          ((unsigned long)((y)[3] & 255)); }

#define STORE64H(x, y)                                                                     \
   { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
     (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
     (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
     (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }

#define F0(x,y,z)  (z ^ (x & (y ^ z)))
#define F1(x,y,z)  (x ^ y ^ z)
#define F2(x,y,z)  ((x & y) | (z & (x | y)))
#define F3(x,y,z)  (x ^ y ^ z)
#ifndef MIN
   #define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif

static int  sha1_compress(sha1_context *md, unsigned char *buf)
{
    uint32_t a,b,c,d,e,W[80],i;
    uint32_t t;
    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD32H(W[i], buf + (4*i));
    }
    /* copy state */
    a = md->state[0];
    b = md->state[1];
    c = md->state[2];
    d = md->state[3];
    e = md->state[4];
    /* expand it */
    for (i = 16; i < 80; i++) {
        W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); 
    }
    /* compress */
    /* round one */
    #define FF0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
    #define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
    #define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
    #define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);

    for (i = 0; i < 20; ) {
       FF0(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }
    for (; i < 40; ) {
       FF1(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }
    for (; i < 60; ) {
       FF2(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }
    for (; i < 80; ) {
       FF3(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

    #undef FF0
    #undef FF1
    #undef FF2
    #undef FF3

    /* store */
    md->state[0] = md->state[0] + a;
    md->state[1] = md->state[1] + b;
    md->state[2] = md->state[2] + c;
    md->state[3] = md->state[3] + d;
    md->state[4] = md->state[4] + e;
    return 0;
}

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return 0 if successful
*/
int sha1_init(sha1_context * md)
{
    if (md == NULL) return 1;
    md->state[0] = 0x67452301UL;
    md->state[1] = 0xefcdab89UL;
    md->state[2] = 0x98badcfeUL;
    md->state[3] = 0x10325476UL;
    md->state[4] = 0xc3d2e1f0UL;
    md->curlen = 0;
    md->length = 0;
    return 0;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param data   The data to hash
   @param inlen  The length of the data (octets)
   @return 0 if successful
*/
int sha1_update (sha1_context * md, const void *data, size_t inlen)
{
    const unsigned char* in = (const unsigned char*)data;
    size_t n;
    size_t i;
    int           err;
    if (md == NULL) return 1;
    if (in == NULL) return 1;
    if (md->curlen > sizeof(md->buf)) {
       return 1;
    }
    while (inlen > 0) {
        if (md->curlen == 0 && inlen >= 64) {
           if ((err = sha1_compress (md, (unsigned char *)in)) != 0) {
              return err;
           }
           md->length += 64 * 8;
           in             += 64;
           inlen          -= 64;
        } else {
           n = MIN(inlen, (64 - md->curlen));

           for (i = 0; i < n; i++) {
            md->buf[i + md->curlen] = in[i];
           }


           md->curlen += n;
           in             += n;
           inlen          -= n;
           if (md->curlen == 64) {
              if ((err = sha1_compress (md, md->buf)) != 0) {
                 return err;
              }
              md->length += 8*64;
              md->curlen = 0;
           }
       }
    }
    return 0;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return 0 if successful
*/
int sha1_final(sha1_context * md, unsigned char *out)
{
    int i;
    if (md == NULL) return 1;
    if (out == NULL) return 1;
    if (md->curlen >= sizeof(md->buf)) {
        return 1;
    }
    /* increase the length of the message */
    md->length += md->curlen * 8;
    /* append the '1' bit */
    md->buf[md->curlen++] = (unsigned char)0x80;
    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->curlen > 56) {
        while (md->curlen < 64) {
            md->buf[md->curlen++] = (unsigned char)0;
        }
        sha1_compress(md, md->buf);
        md->curlen = 0;
    }
    /* pad upto 56 bytes of zeroes */
    while (md->curlen < 56) {
        md->buf[md->curlen++] = (unsigned char)0;
    }
    /* store length */
    STORE64H(md->length, md->buf+56);
    sha1_compress(md, md->buf);
    /* copy output */
    for (i = 0; i < 5; i++) {
        STORE32H(md->state[i], out+(4*i));
    }
    return 0;
}

int sha1(const unsigned char *message, size_t message_len, unsigned char *out)
{
    sha1_context ctx;
    int ret;
    if ((ret = sha1_init(&ctx))) return ret;
    if ((ret = sha1_update(&ctx, message, message_len))) return ret;
    if ((ret = sha1_final(&ctx, out))) return ret;
    return 0;
}
07070100000027000081A400000000000000000000000167AD5DE9000020DB000000000000000000000000000000000000003800000000libimobiledevice-glue-1.3.1+git18.20250213/src/sha256.c/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com
 */

#include "common.h"
#include "libimobiledevice-glue/sha.h"

#include <stdint.h>

/* the K array */
static const uint32_t K[64] = {
    0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
    0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
    0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
    0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
    0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
    0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
    0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
    0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
    0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
    0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
    0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
    0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
    0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};

/* Various logical functions */

#define RORc(x, y) \
    ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \
      ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)

#define STORE32H(x, y)                                                                    \
    { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255);   \
      (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }

#define LOAD32H(x, y)                           \
    { x = ((unsigned long)((y)[0] & 255)<<24) | \
          ((unsigned long)((y)[1] & 255)<<16) | \
          ((unsigned long)((y)[2] & 255)<<8)  | \
          ((unsigned long)((y)[3] & 255)); }

#define STORE64H(x, y)                                                                     \
   { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
     (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
     (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
     (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }

#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         RORc((x),(n))
#define R(x, n)         (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))
#ifndef MIN
   #define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif

/* compress 256-bits */
static int sha256_compress(sha256_context * md, unsigned char *buf)
{
    uint32_t S[8], W[64], t0, t1;
    uint32_t t;
    int i;
    /* copy state into S */
    for (i = 0; i < 8; i++) {
        S[i] = md->state[i];
    }
    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD32H(W[i], buf + (4*i));
    }
    /* fill W[16..63] */
    for (i = 16; i < 64; i++) {
        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
    }
    /* Compress */
    #define RND(a,b,c,d,e,f,g,h,i) \
    t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
    t1 = Sigma0(a) + Maj(a, b, c); \
    d += t0; \
    h  = t0 + t1;
    for (i = 0; i < 64; ++i) {
        RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);
        t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; 
        S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
    }
    #undef RND
    /* feedback */
    for (i = 0; i < 8; i++) {
        md->state[i] = md->state[i] + S[i];
    }
    return 0;
}

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int sha256_init(sha256_context * md)
{
    if (md == NULL) return 1;
    md->curlen = 0;
    md->length = 0;
    md->state[0] = 0x6A09E667UL;
    md->state[1] = 0xBB67AE85UL;
    md->state[2] = 0x3C6EF372UL;
    md->state[3] = 0xA54FF53AUL;
    md->state[4] = 0x510E527FUL;
    md->state[5] = 0x9B05688CUL;
    md->state[6] = 0x1F83D9ABUL;
    md->state[7] = 0x5BE0CD19UL;
    md->num_dwords = 8;
    return 0;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param data   The data to hash
   @param inlen  The length of the data (octets)
   @return 0 if successful
*/
int sha256_update (sha256_context * md, const void *data, size_t inlen)
{
    const unsigned char* in = (const unsigned char*)data;
    size_t n;
    size_t i;
    int           err;
    if (md == NULL) return 1;
    if (in == NULL) return 1;
    if (md->curlen > sizeof(md->buf)) {
       return 1;
    }
    while (inlen > 0) {
        if (md->curlen == 0 && inlen >= 64) {
           if ((err = sha256_compress (md, (unsigned char *)in)) != 0) {
              return err;
           }
           md->length += 64 * 8;
           in             += 64;
           inlen          -= 64;
        } else {
           n = MIN(inlen, (64 - md->curlen));

           for (i = 0; i < n; i++) {
            md->buf[i + md->curlen] = in[i];
           }


           md->curlen += n;
           in             += n;
           inlen          -= n;
           if (md->curlen == 64) {
              if ((err = sha256_compress (md, md->buf)) != 0) {
                 return err;
              }
              md->length += 8*64;
              md->curlen = 0;
           }
       }
    }
    return 0;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (32 bytes)
   @return 0 if successful
*/
int sha256_final(sha256_context * md, unsigned char *out)
{
    int i;
    if (md == NULL) return 1;
    if (out == NULL) return 1;
    if (md->curlen >= sizeof(md->buf)) {
       return 1;
    }
    /* increase the length of the message */
    md->length += md->curlen * 8;
    /* append the '1' bit */
    md->buf[md->curlen++] = (unsigned char)0x80;
    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->curlen > 56) {
        while (md->curlen < 64) {
            md->buf[md->curlen++] = (unsigned char)0;
        }
        sha256_compress(md, md->buf);
        md->curlen = 0;
    }
    /* pad upto 56 bytes of zeroes */
    while (md->curlen < 56) {
        md->buf[md->curlen++] = (unsigned char)0;
    }
    /* store length */
    STORE64H(md->length, md->buf+56);
    sha256_compress(md, md->buf);
    /* copy output */
    for (i = 0; i < md->num_dwords; i++) {
        STORE32H(md->state[i], out+(4*i));
    }
    return 0;
}

int sha256(const unsigned char *message, size_t message_len, unsigned char *out)
{
    sha256_context ctx;
    int ret;
    if ((ret = sha256_init(&ctx))) return ret;
    if ((ret = sha256_update(&ctx, message, message_len))) return ret;
    if ((ret = sha256_final(&ctx, out))) return ret;
    return 0;
}

int sha224_init(sha224_context * md) {
    if (md == NULL) return 1;

    md->curlen = 0;
    md->length = 0;
    md->state[0] = 0xc1059ed8UL;
    md->state[1] = 0x367cd507UL;
    md->state[2] = 0x3070dd17UL;
    md->state[3] = 0xf70e5939UL;
    md->state[4] = 0xffc00b31UL;
    md->state[5] = 0x68581511UL;
    md->state[6] = 0x64f98fa7UL;
    md->state[7] = 0xbefa4fa4UL;
    md->num_dwords = 6;

    return 0;
}

int sha224_update(sha224_context * md, const void *data, size_t inlen)
{
    return sha256_update(md, data, inlen);
}

int sha224_final(sha224_context * md, unsigned char* out)
{
    return sha256_final(md, out);
}

int sha224(const unsigned char *message, size_t message_len, unsigned char *out)
{
    sha224_context ctx;
    int ret;
    if ((ret = sha224_init(&ctx))) return ret;
    if ((ret = sha224_update(&ctx, message, message_len))) return ret;
    if ((ret = sha224_final(&ctx, out))) return ret;
    return 0;
}
07070100000028000081A400000000000000000000000167AD5DE900002998000000000000000000000000000000000000003800000000libimobiledevice-glue-1.3.1+git18.20250213/src/sha512.c/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

#include <stdint.h>

#include "common.h"
#include "libimobiledevice-glue/sha.h"

/* the K array */
static const uint64_t K[80] = {
    UINT64_C(0x428a2f98d728ae22), UINT64_C(0x7137449123ef65cd), 
    UINT64_C(0xb5c0fbcfec4d3b2f), UINT64_C(0xe9b5dba58189dbbc),
    UINT64_C(0x3956c25bf348b538), UINT64_C(0x59f111f1b605d019), 
    UINT64_C(0x923f82a4af194f9b), UINT64_C(0xab1c5ed5da6d8118),
    UINT64_C(0xd807aa98a3030242), UINT64_C(0x12835b0145706fbe), 
    UINT64_C(0x243185be4ee4b28c), UINT64_C(0x550c7dc3d5ffb4e2),
    UINT64_C(0x72be5d74f27b896f), UINT64_C(0x80deb1fe3b1696b1), 
    UINT64_C(0x9bdc06a725c71235), UINT64_C(0xc19bf174cf692694),
    UINT64_C(0xe49b69c19ef14ad2), UINT64_C(0xefbe4786384f25e3), 
    UINT64_C(0x0fc19dc68b8cd5b5), UINT64_C(0x240ca1cc77ac9c65),
    UINT64_C(0x2de92c6f592b0275), UINT64_C(0x4a7484aa6ea6e483), 
    UINT64_C(0x5cb0a9dcbd41fbd4), UINT64_C(0x76f988da831153b5),
    UINT64_C(0x983e5152ee66dfab), UINT64_C(0xa831c66d2db43210), 
    UINT64_C(0xb00327c898fb213f), UINT64_C(0xbf597fc7beef0ee4),
    UINT64_C(0xc6e00bf33da88fc2), UINT64_C(0xd5a79147930aa725), 
    UINT64_C(0x06ca6351e003826f), UINT64_C(0x142929670a0e6e70),
    UINT64_C(0x27b70a8546d22ffc), UINT64_C(0x2e1b21385c26c926), 
    UINT64_C(0x4d2c6dfc5ac42aed), UINT64_C(0x53380d139d95b3df),
    UINT64_C(0x650a73548baf63de), UINT64_C(0x766a0abb3c77b2a8), 
    UINT64_C(0x81c2c92e47edaee6), UINT64_C(0x92722c851482353b),
    UINT64_C(0xa2bfe8a14cf10364), UINT64_C(0xa81a664bbc423001),
    UINT64_C(0xc24b8b70d0f89791), UINT64_C(0xc76c51a30654be30),
    UINT64_C(0xd192e819d6ef5218), UINT64_C(0xd69906245565a910), 
    UINT64_C(0xf40e35855771202a), UINT64_C(0x106aa07032bbd1b8),
    UINT64_C(0x19a4c116b8d2d0c8), UINT64_C(0x1e376c085141ab53), 
    UINT64_C(0x2748774cdf8eeb99), UINT64_C(0x34b0bcb5e19b48a8),
    UINT64_C(0x391c0cb3c5c95a63), UINT64_C(0x4ed8aa4ae3418acb), 
    UINT64_C(0x5b9cca4f7763e373), UINT64_C(0x682e6ff3d6b2b8a3),
    UINT64_C(0x748f82ee5defb2fc), UINT64_C(0x78a5636f43172f60), 
    UINT64_C(0x84c87814a1f0ab72), UINT64_C(0x8cc702081a6439ec),
    UINT64_C(0x90befffa23631e28), UINT64_C(0xa4506cebde82bde9), 
    UINT64_C(0xbef9a3f7b2c67915), UINT64_C(0xc67178f2e372532b),
    UINT64_C(0xca273eceea26619c), UINT64_C(0xd186b8c721c0c207), 
    UINT64_C(0xeada7dd6cde0eb1e), UINT64_C(0xf57d4f7fee6ed178),
    UINT64_C(0x06f067aa72176fba), UINT64_C(0x0a637dc5a2c898a6), 
    UINT64_C(0x113f9804bef90dae), UINT64_C(0x1b710b35131c471b),
    UINT64_C(0x28db77f523047d84), UINT64_C(0x32caab7b40c72493), 
    UINT64_C(0x3c9ebe0a15c9bebc), UINT64_C(0x431d67c49c100d4c),
    UINT64_C(0x4cc5d4becb3e42b6), UINT64_C(0x597f299cfc657e2a), 
    UINT64_C(0x5fcb6fab3ad6faec), UINT64_C(0x6c44198c4a475817)
};

/* Various logical functions */

#define ROR64c(x, y) \
    ( ((((x)&UINT64_C(0xFFFFFFFFFFFFFFFF))>>((uint64_t)(y)&UINT64_C(63))) | \
      ((x)<<((uint64_t)(64-((y)&UINT64_C(63)))))) & UINT64_C(0xFFFFFFFFFFFFFFFF))

#define STORE64H(x, y)                                                                     \
   { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
     (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
     (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
     (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }

#define LOAD64H(x, y)                                                      \
   { x = (((uint64_t)((y)[0] & 255))<<56)|(((uint64_t)((y)[1] & 255))<<48) | \
         (((uint64_t)((y)[2] & 255))<<40)|(((uint64_t)((y)[3] & 255))<<32) | \
         (((uint64_t)((y)[4] & 255))<<24)|(((uint64_t)((y)[5] & 255))<<16) | \
         (((uint64_t)((y)[6] & 255))<<8)|(((uint64_t)((y)[7] & 255))); }


#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         ROR64c(x, n)
#define R(x, n)         (((x) &UINT64_C(0xFFFFFFFFFFFFFFFF))>>((uint64_t)n))
#define Sigma0(x)       (S(x, 28) ^ S(x, 34) ^ S(x, 39))
#define Sigma1(x)       (S(x, 14) ^ S(x, 18) ^ S(x, 41))
#define Gamma0(x)       (S(x, 1) ^ S(x, 8) ^ R(x, 7))
#define Gamma1(x)       (S(x, 19) ^ S(x, 61) ^ R(x, 6))
#ifndef MIN
   #define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif

/* compress 1024-bits */
static int sha512_compress(sha512_context *md, unsigned char *buf)
{
    uint64_t S[8], W[80], t0, t1;
    int i;

    /* copy state into S */
    for (i = 0; i < 8; i++) {
        S[i] = md->state[i];
    }

    /* copy the state into 1024-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD64H(W[i], buf + (8*i));
    }

    /* fill W[16..79] */
    for (i = 16; i < 80; i++) {
        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
    }

    /* Compress */
    #define RND(a,b,c,d,e,f,g,h,i) \
    t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
    t1 = Sigma0(a) + Maj(a, b, c);\
    d += t0; \
    h  = t0 + t1;

    for (i = 0; i < 80; i += 8) {
        RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i+0);
        RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],i+1);
        RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],i+2);
        RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],i+3);
        RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],i+4);
        RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],i+5);
        RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],i+6);
        RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],i+7);
    }

    #undef RND

    /* feedback */
    for (i = 0; i < 8; i++) {
        md->state[i] = md->state[i] + S[i];
    }

    return 0;
}


/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return 0 if successful
*/
int sha512_init(sha512_context * md) {
    if (md == NULL) return 1;

    md->curlen = 0;
    md->length = 0;
    md->state[0] = UINT64_C(0x6a09e667f3bcc908);
    md->state[1] = UINT64_C(0xbb67ae8584caa73b);
    md->state[2] = UINT64_C(0x3c6ef372fe94f82b);
    md->state[3] = UINT64_C(0xa54ff53a5f1d36f1);
    md->state[4] = UINT64_C(0x510e527fade682d1);
    md->state[5] = UINT64_C(0x9b05688c2b3e6c1f);
    md->state[6] = UINT64_C(0x1f83d9abfb41bd6b);
    md->state[7] = UINT64_C(0x5be0cd19137e2179);
    md->num_qwords = 8;

    return 0;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param data   The data to hash
   @param inlen  The length of the data (octets)
   @return 0 if successful
*/
int sha512_update (sha512_context * md, const void *data, size_t inlen)
{
    const unsigned char* in = (const unsigned char*)data;
    size_t n;
    size_t i;
    int           err;
    if (md == NULL) return 1;
    if (in == NULL) return 1;
    if (md->curlen > sizeof(md->buf)) {
       return 1;
    }
    while (inlen > 0) {
        if (md->curlen == 0 && inlen >= 128) {
           if ((err = sha512_compress (md, (unsigned char *)in)) != 0) {
              return err;
           }
           md->length += 128 * 8;
           in             += 128;
           inlen          -= 128;
        } else {
           n = MIN(inlen, (128 - md->curlen));

           for (i = 0; i < n; i++) {
            md->buf[i + md->curlen] = in[i];
           }


           md->curlen += n;
           in             += n;
           inlen          -= n;
           if (md->curlen == 128) {
              if ((err = sha512_compress (md, md->buf)) != 0) {
                 return err;
              }
              md->length += 8*128;
              md->curlen = 0;
           }
       }
    }
    return 0;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (64 bytes)
   @return 0 if successful
*/
int sha512_final(sha512_context * md, unsigned char *out)
{
    int i;

    if (md == NULL) return 1;
    if (out == NULL) return 1;

    if (md->curlen >= sizeof(md->buf)) {
        return 1;
    }

    /* increase the length of the message */
    md->length += md->curlen * UINT64_C(8);

    /* append the '1' bit */
    md->buf[md->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 112 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->curlen > 112) {
        while (md->curlen < 128) {
            md->buf[md->curlen++] = (unsigned char)0;
        }
        sha512_compress(md, md->buf);
        md->curlen = 0;
    }

    /* pad upto 120 bytes of zeroes 
     * note: that from 112 to 120 is the 64 MSB of the length.  We assume that you won't hash
     * > 2^64 bits of data... :-)
     */
    while (md->curlen < 120) {
        md->buf[md->curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64H(md->length, md->buf+120);
    sha512_compress(md, md->buf);

    /* copy output */
    for (i = 0; i < md->num_qwords; i++) {
        STORE64H(md->state[i], out+(8*i));
    }

    return 0;
}

int sha512(const unsigned char *message, size_t message_len, unsigned char *out)
{
    sha512_context ctx;
    int ret;
    if ((ret = sha512_init(&ctx))) return ret;
    if ((ret = sha512_update(&ctx, message, message_len))) return ret;
    if ((ret = sha512_final(&ctx, out))) return ret;
    return 0;
}

int sha384_init(sha384_context * md) {
    if (md == NULL) return 1;

    md->curlen = 0;
    md->length = 0;
    md->state[0] = UINT64_C(0xcbbb9d5dc1059ed8);
    md->state[1] = UINT64_C(0x629a292a367cd507);
    md->state[2] = UINT64_C(0x9159015a3070dd17);
    md->state[3] = UINT64_C(0x152fecd8f70e5939);
    md->state[4] = UINT64_C(0x67332667ffc00b31);
    md->state[5] = UINT64_C(0x8eb44a8768581511);
    md->state[6] = UINT64_C(0xdb0c2e0d64f98fa7);
    md->state[7] = UINT64_C(0x47b5481dbefa4fa4);
    md->num_qwords = 6;

    return 0;
}

int sha384_update(sha384_context * md, const void *data, size_t inlen)
{
    return sha512_update(md, data, inlen);
}

int sha384_final(sha384_context * md, unsigned char* out)
{
    return sha512_final(md, out);
}

int sha384(const unsigned char *message, size_t message_len, unsigned char *out)
{
    sha384_context ctx;
    int ret;
    if ((ret = sha384_init(&ctx))) return ret;
    if ((ret = sha384_update(&ctx, message, message_len))) return ret;
    if ((ret = sha384_final(&ctx, out))) return ret;
    return 0;
}
07070100000029000081A400000000000000000000000167AD5DE900008D6C000000000000000000000000000000000000003800000000libimobiledevice-glue-1.3.1+git18.20250213/src/socket.c/*
 * socket.c
 *
 * Copyright (C) 2012-2020 Nikias Bassen <nikias@gmx.li>
 * Copyright (C) 2012 Martin Szulecki <m.szulecki@libimobiledevice.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#ifndef _MSC_VER
#include <unistd.h>
#include <sys/time.h>
#include <sys/stat.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#ifndef HAVE_GETIFADDRS
#include <iphlpapi.h>
#endif
#ifndef IFF_RUNNING
#define IFF_RUNNING IFF_UP
#endif
#ifndef AI_NUMERICSERV
#define AI_NUMERICSERV 0
#endif
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#ifdef AF_INET6
#include <net/if.h>
#include <ifaddrs.h>
#if defined (__APPLE__) || defined (__FreeBSD__) || defined (__HAIKU__)
#include <net/if_dl.h>
#endif
#ifdef __linux__
#include <netpacket/packet.h>
#endif
#endif
#endif
#include "common.h"
#include "libimobiledevice-glue/socket.h"
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif

#define RECV_TIMEOUT 20000
#define SEND_TIMEOUT 10000
#define CONNECT_TIMEOUT 5000

#ifndef EAFNOSUPPORT
#define EAFNOSUPPORT 102
#endif
#ifndef ECONNRESET
#define ECONNRESET 108
#endif
#ifndef ETIMEDOUT
#define ETIMEDOUT 138
#endif

#ifndef AI_NUMERICSERV
#define AI_NUMERICSERV 0
#endif

static int verbose = 0;

#define SOCKET_ERR(level, msg, ...) \
	if (verbose >= level) { \
		fprintf(stderr, "[socket] " msg __VA_OPT__(,) __VA_ARGS__); \
	}

void socket_init(void)
{
#ifdef _WIN32
	WSADATA wsa_data;
	if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
		SOCKET_ERR(0, "WSAStartup failed!\n");
		ExitProcess(1);
	}
#endif
	char *env_debug = getenv("SOCKET_DEBUG");
        if (env_debug) {
		verbose = (int)strtol(env_debug, NULL, 10);
	}
}

void socket_set_verbose(int level)
{
	verbose = level;
}

const char *socket_addr_to_string(struct sockaddr *addr, char *addr_out, size_t addr_out_size)
{
#ifdef _WIN32
	DWORD addr_out_len = addr_out_size;
	DWORD addrlen = 0;

	if (addr->sa_family == AF_INET) {
		addrlen = sizeof(struct sockaddr_in);
	}
#ifdef AF_INET6
	else if (addr->sa_family == AF_INET6) {
		addrlen = sizeof(struct sockaddr_in6);
	}
#endif
	else {
		errno = EAFNOSUPPORT;
		return NULL;
	}

	if (WSAAddressToString(addr, addrlen, NULL, addr_out, &addr_out_len) == 0) {
		return addr_out;
	}
#else
	const void *addrdata = NULL;

	if (addr->sa_family == AF_INET) {
		addrdata = &((struct sockaddr_in*)addr)->sin_addr;
	}
#ifdef AF_INET6
	else if (addr->sa_family == AF_INET6) {
		addrdata = &((struct sockaddr_in6*)addr)->sin6_addr;
	}
#endif
	else {
		errno = EAFNOSUPPORT;
		return NULL;
	}

	if (inet_ntop(addr->sa_family, addrdata, addr_out, addr_out_size)) {
		return addr_out;
	}
#endif
	return NULL;
}

enum poll_status
{
	poll_status_success,
	poll_status_timeout,
	poll_status_error
};

#ifdef _MSC_VER
#define ALWAYS_INLINE __forceinline
#else
#define ALWAYS_INLINE __inline__ __attribute__((__always_inline__))
#endif

#ifdef _WIN32
static ALWAYS_INLINE int WSAError_to_errno(int wsaerr)
{
	switch (wsaerr) {
		case WSAEINVAL:
			return EINVAL;
		case WSAENOTSOCK:
			return ENOTSOCK;
		case WSAENOTCONN:
			return ENOTCONN;
		case WSAESHUTDOWN:
			return ENOTCONN;
		case WSAECONNRESET:
			return ECONNRESET;
		case WSAECONNABORTED:
			return ECONNABORTED;
		case WSAECONNREFUSED:
			return ECONNREFUSED;
		case WSAENETDOWN:
			return ENETDOWN;
		case WSAENETRESET:
			return ENETRESET;
		case WSAEHOSTUNREACH:
			return EHOSTUNREACH;
		case WSAETIMEDOUT:
			return ETIMEDOUT;
		case WSAEWOULDBLOCK:
			return EWOULDBLOCK;
		case WSAEINPROGRESS:
			return EINPROGRESS;
		case WSAENOBUFS:
			return ENOBUFS;
		case WSAEINTR:
			return EINTR;
		case WSAEACCES:
			return EACCES;
		case WSAEFAULT:
			return EFAULT;
		default:
			break;
	}
	return wsaerr;
}
#endif

// timeout of -1 means infinity
static ALWAYS_INLINE enum poll_status poll_wrapper(int fd, fd_mode mode, int timeout)
{
#ifdef HAVE_POLL
	// https://man7.org/linux/man-pages/man2/select.2.html
	// Correspondence between select() and poll() notifications
	// #define POLLIN_SET  (EPOLLRDNORM | EPOLLRDBAND | EPOLLIN |
	//                      EPOLLHUP | EPOLLERR)
	//                    /* Ready for reading */
	// #define POLLOUT_SET (EPOLLWRBAND | EPOLLWRNORM | EPOLLOUT |
	//                      EPOLLERR)
	//                    /* Ready for writing */
	// #define POLLEX_SET  (EPOLLPRI)
	//                    /* Exceptional condition */

	short events;
	switch (mode) {
		case FDM_READ:
			events = POLLRDNORM | POLLRDBAND | POLLIN | POLLHUP | POLLERR;
			break;
		case FDM_WRITE:
			events = POLLWRBAND | POLLWRNORM | POLLOUT | POLLERR;
			break;
		case FDM_EXCEPT:
			events = POLLPRI;
			break;
		default:
			SOCKET_ERR(2, "%s: fd_mode %d unsupported\n", __func__, mode);
			return poll_status_error;
	}
	while (1) {
		struct pollfd pfd = {
			.fd = fd,
			.events = events,
		};
		switch (poll(&pfd, 1, timeout)) {
			case 1:
				if((pfd.revents & (POLLNVAL | POLLERR)) != 0)
				{
					SOCKET_ERR(2, "%s: poll unexpected events: %d\n", __func__, (int)pfd.revents);
					return poll_status_error;
				}
				return poll_status_success;
			case 0:
				return poll_status_timeout;
			case -1:
				if(errno == EINTR)
				{
					SOCKET_ERR(2, "%s: EINTR\n", __func__);
					continue;
				}
				// fallthrough
			default:
				SOCKET_ERR(2, "%s: poll failed: %s\n", __func__, strerror(errno));
				return poll_status_error;
		}
	}
#else
	fd_set fds;
	int sret;
	int eagain;
	struct timeval to;
	struct timeval *pto;

	FD_ZERO(&fds);
	FD_SET(fd, &fds);

	sret = poll_status_error;

	do {
		if (timeout > 0) {
			to.tv_sec = (time_t) (timeout / 1000);
			to.tv_usec = (time_t) ((timeout - (to.tv_sec * 1000)) * 1000);
			pto = &to;
		} else {
			pto = NULL;
		}
		eagain = 0;
		switch (mode) {
		case FDM_READ:
			sret = select(fd + 1, &fds, NULL, NULL, pto);
			break;
		case FDM_WRITE:
			sret = select(fd + 1, NULL, &fds, NULL, pto);
			break;
		case FDM_EXCEPT:
			sret = select(fd + 1, NULL, NULL, &fds, pto);
			break;
		default:
			SOCKET_ERR(2, "%s: fd_mode %d unsupported\n", __func__, mode);
			return poll_status_error;
		}

		if (sret == 1) {
			return poll_status_success;
		} else if (sret == 0) {
			return poll_status_timeout;
		} else {
#ifdef _WIN32
			errno = WSAError_to_errno(WSAGetLastError());
#endif
			switch (errno) {
			case EINTR:
				// interrupt signal in select
				SOCKET_ERR(2, "%s: EINTR\n", __func__);
				eagain = 1;
				break;
			case EAGAIN:
				SOCKET_ERR(2, "%s: EAGAIN\n", __func__);
				break;
			default:
				SOCKET_ERR(2, "%s: select failed: %s\n", __func__, strerror(errno));
				return poll_status_error;
			}
		}
	} while (eagain);

	return sret;
#endif
}

#ifndef _WIN32
int socket_create_unix(const char *filename)
{
	struct sockaddr_un name;
	int sock;
#ifdef SO_NOSIGPIPE
	int yes = 1;
#endif

	// remove if still present
	unlink(filename);

	/* Create the socket. */
	sock = socket(PF_UNIX, SOCK_STREAM, 0);
	if (sock < 0) {
		SOCKET_ERR(1, "socket(): %s\n", strerror(errno));
		return -1;
	}

#ifdef SO_NOSIGPIPE
	if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
		SOCKET_ERR(1, "setsockopt(): %s\n", strerror(errno));
		return -1;
	}
#endif

	/* Bind a name to the socket. */
	name.sun_family = AF_UNIX;
	strncpy(name.sun_path, filename, sizeof(name.sun_path));
	name.sun_path[sizeof(name.sun_path) - 1] = '\0';

	if (bind(sock, (struct sockaddr*)&name, sizeof(name)) < 0) {
		SOCKET_ERR(1, "bind(): %s\n", strerror(errno));
		socket_close(sock);
		return -1;
	}

	if (listen(sock, 100) < 0) {
		SOCKET_ERR(1, "listen(): %s\n", strerror(errno));
		socket_close(sock);
		return -1;
	}

	return sock;
}

int socket_connect_unix(const char *filename)
{
	struct sockaddr_un name;
	int sfd = -1;
	struct stat fst;
#ifdef SO_NOSIGPIPE
	int yes = 1;
#endif
	int bufsize = 0x20000;

	// check if socket file exists...
	if (stat(filename, &fst) != 0) {
		SOCKET_ERR(2, "%s: stat '%s': %s\n", __func__, filename, strerror(errno));
		return -1;
	}
	// ... and if it is a unix domain socket
	if (!S_ISSOCK(fst.st_mode)) {
		SOCKET_ERR(2, "%s: File '%s' is not a socket!\n", __func__, filename);
		return -1;
	}
	// make a new socket
	if ((sfd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
		SOCKET_ERR(2, "%s: socket: %s\n", __func__, strerror(errno));
		return -1;
	}

	if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void*)&bufsize, sizeof(int)) == -1) {
		SOCKET_ERR(1, "Could not set send buffer for socket: %s\n", strerror(errno));
	}

	if (setsockopt(sfd, SOL_SOCKET, SO_RCVBUF, (void*)&bufsize, sizeof(int)) == -1) {
		SOCKET_ERR(1, "Could not set receive buffer for socket: %s\n", strerror(errno));
	}

#ifdef SO_NOSIGPIPE
	if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
		SOCKET_ERR(1, "setsockopt(): %s\n", strerror(errno));
		socket_close(sfd);
		return -1;
	}
#endif
	// and connect to 'filename'
	name.sun_family = AF_UNIX;
	strncpy(name.sun_path, filename, sizeof(name.sun_path));
	name.sun_path[sizeof(name.sun_path) - 1] = 0;

	int flags = fcntl(sfd, F_GETFL, 0);
	fcntl(sfd, F_SETFL, flags | O_NONBLOCK);

	do {
		if (connect(sfd, (struct sockaddr*)&name, sizeof(name)) != -1) {
			break;
		}
		if (errno == EINPROGRESS) {
			if (poll_wrapper(sfd, FDM_WRITE, CONNECT_TIMEOUT) == poll_status_success) {
				int so_error;
				socklen_t len = sizeof(so_error);
				getsockopt(sfd, SOL_SOCKET, SO_ERROR, (void*)&so_error, &len);
				if (so_error == 0) {
					errno = 0;
					break;
				}
				errno = so_error;
			} else {
				int so_error = 0;
				socklen_t len = sizeof(so_error);
				getsockopt(sfd, SOL_SOCKET, SO_ERROR, (void*)&so_error, &len);
				if (so_error != 0) {
					errno = so_error;
				}
			}
		}
		socket_close(sfd);
		sfd = -1;
	} while (0);

	if (sfd < 0) {
		SOCKET_ERR(2, "%s: connect: %s\n", __func__, strerror(errno));
		return -1;
	}

	return sfd;
}
#endif

int socket_create(const char* addr, uint16_t port)
{
	int sfd = -1;
	int yes = 1;
	int no = 0;
	struct addrinfo hints;
	struct addrinfo *result, *rp;
	char portstr[8];
	int res;

	memset(&hints, '\0', sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
	hints.ai_protocol = IPPROTO_TCP;

	snprintf(portstr, 8, "%d", port);

	res = getaddrinfo(addr, portstr, &hints, &result);
	if (res != 0) {
		SOCKET_ERR(1, "%s: getaddrinfo: %s\n", __func__, gai_strerror(res));
		return -1;
	}

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (sfd == -1) {
			continue;
		}

		if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
#ifdef _WIN32
			errno = WSAError_to_errno(WSAGetLastError());
#endif
			SOCKET_ERR(1, "setsockopt() SO_REUSEADDR: %s\n", strerror(errno));
			socket_close(sfd);
			continue;
		}

#ifdef SO_NOSIGPIPE
		if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
			SOCKET_ERR(1, "setsockopt() SO_NOSIGPIPE: %s\n", strerror(errno));
			socket_close(sfd);
			continue;
		}
#endif

#if defined(AF_INET6) && defined(IPV6_V6ONLY)
		if (rp->ai_family == AF_INET6) {
			if (setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (addr) ? (void*)&yes : (void*)&no, sizeof(int)) == -1) {
#ifdef _WIN32
				errno = WSAError_to_errno(WSAGetLastError());
#endif
				SOCKET_ERR(1, "setsockopt() IPV6_V6ONLY: %s\n", strerror(errno));
			}
		}
#endif

		if (bind(sfd, rp->ai_addr, rp->ai_addrlen) < 0) {
#ifdef _WIN32
			errno = WSAError_to_errno(WSAGetLastError());
#endif
			SOCKET_ERR(1, "bind(): %s\n", strerror(errno));
			socket_close(sfd);
			continue;
		}

		if (listen(sfd, 100) < 0) {
#ifdef _WIN32
			errno = WSAError_to_errno(WSAGetLastError());
#endif
			SOCKET_ERR(1, "listen(): %s\n", strerror(errno));
			socket_close(sfd);
			continue;
		}
		break;
	}

	freeaddrinfo(result);

	if (rp == NULL) {
		return -1;
	}

	return sfd;
}

#ifdef AF_INET6
static uint32_t _in6_addr_scope(struct in6_addr* addr)
{
	uint32_t scope = 0;

	if (IN6_IS_ADDR_MULTICAST(addr)) {
		if (IN6_IS_ADDR_MC_NODELOCAL(addr)) {
			scope = 1;
		} else if (IN6_IS_ADDR_MC_LINKLOCAL(addr)) {
			scope = 2;
		} else if (IN6_IS_ADDR_MC_SITELOCAL(addr)) {
			scope = 5;
		}

		return scope;
	}

	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
		scope = 2;
	} else if (IN6_IS_ADDR_LOOPBACK(addr)) {
		scope = 2;
	} else if (IN6_IS_ADDR_SITELOCAL(addr)) {
		scope = 5;
	} else if (IN6_IS_ADDR_UNSPECIFIED(addr)) {
		scope = 0;
	}

	return scope;
}

#ifndef HAVE_GETIFADDRS
#ifdef _WIN32

struct ifaddrs {
	struct ifaddrs  *ifa_next;    /* Next item in list */
	char            *ifa_name;    /* Name of interface */
	unsigned int     ifa_flags;   /* Flags from SIOCGIFFLAGS */
	struct sockaddr *ifa_addr;    /* Address of interface */
	struct sockaddr *ifa_netmask; /* Netmask of interface */
	union {
		struct sockaddr *ifu_broadaddr; /* Broadcast address of interface */
		struct sockaddr *ifu_dstaddr;   /* Point-to-point destination address */
	} ifa_ifu;
#define                  ifa_broadaddr ifa_ifu.ifu_broadaddr
#define                  ifa_dstaddr   ifa_ifu.ifu_dstaddr
	void            *ifa_data;    /* Address-specific data */
};

#define WORKING_BUFFER_SIZE 15000
#define MAX_TRIES 3

static void freeifaddrs(struct ifaddrs *ifa)
{
	if (!ifa) {
		return;
	}
	free(ifa->ifa_name);
	free(ifa->ifa_addr);
	free(ifa->ifa_netmask);
	free(ifa->ifa_dstaddr);
	free(ifa->ifa_data);
	freeifaddrs(ifa->ifa_next);
	free(ifa);
}

/*
 * getifaddrs() reference implementation for win32.
 * Heavily based on openpgm's implementation found here:
 * https://github.com/steve-o/openpgm/blob/master/openpgm/pgm/getifaddrs.c
 */
static int getifaddrs(struct ifaddrs** ifap)
{
	struct ifaddrs* ifa = NULL;

	DWORD dwRetVal = 0;

	PIP_ADAPTER_ADDRESSES pAddresses = NULL;
	ULONG outBufLen = 0;
	ULONG Iterations = 0;

	ULONG flags = GAA_FLAG_INCLUDE_PREFIX |
		GAA_FLAG_SKIP_ANYCAST |
		GAA_FLAG_SKIP_DNS_SERVER |
		GAA_FLAG_SKIP_FRIENDLY_NAME |
		GAA_FLAG_SKIP_MULTICAST;

	PIP_ADAPTER_ADDRESSES adapter = NULL;

	if (!ifap) {
		errno = EINVAL;
		return -1;
	}
	*ifap = NULL;

	outBufLen = WORKING_BUFFER_SIZE;
	do {
		pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen);
		if (pAddresses == NULL) {
			SOCKET_ERR(1, "Memory allocation failed for IP_ADAPTER_ADDRESSES struct\n");
			return -1;
		}
		dwRetVal = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAddresses, &outBufLen);
		if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
			free(pAddresses);
			pAddresses = NULL;
		} else {
			break;
		}
		Iterations++;
	} while ((dwRetVal == ERROR_BUFFER_OVERFLOW) && (Iterations < MAX_TRIES));

	if (dwRetVal != NO_ERROR) {
		free(pAddresses);
		return -1;
	}

	for (adapter = pAddresses; adapter; adapter = adapter->Next) {
		int unicastIndex = 0;
		for (IP_ADAPTER_UNICAST_ADDRESS *unicast = adapter->FirstUnicastAddress; unicast; unicast = unicast->Next, ++unicastIndex) {
			/* ensure IP adapter */
			if (AF_INET != unicast->Address.lpSockaddr->sa_family && AF_INET6 != unicast->Address.lpSockaddr->sa_family) {
				continue;
			}

			if (!ifa) {
				ifa = calloc(1, sizeof(struct ifaddrs));
				if (!ifa) {
					errno = ENOMEM;
					free(pAddresses);
					return -1;
				}
				*ifap = ifa;
				ifa->ifa_next = NULL;
			} else {
				struct ifaddrs* ifanew = calloc(1, sizeof(struct ifaddrs));
				if (!ifanew) {
					freeifaddrs(*ifap);
					free(pAddresses);
					errno = ENOMEM;
					return -1;
				}
				ifa->ifa_next = ifanew;
				ifa = ifanew;
				ifa->ifa_next = NULL;
			}
			ifa->ifa_data = NULL;

			/* name */
			ifa->ifa_name = strdup(adapter->AdapterName);

			/* flags */
			ifa->ifa_flags = 0;
			if (IfOperStatusUp == adapter->OperStatus)
				ifa->ifa_flags |= IFF_UP;
			if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
				ifa->ifa_flags |= IFF_LOOPBACK;
			if (!(adapter->Flags & IP_ADAPTER_NO_MULTICAST))
				ifa->ifa_flags |= IFF_MULTICAST;

			/* address */
			ifa->ifa_addr = (struct sockaddr*)malloc(sizeof(struct sockaddr_storage));
			memcpy(ifa->ifa_addr, unicast->Address.lpSockaddr, unicast->Address.iSockaddrLength);

			/* netmask */
			ifa->ifa_netmask = (struct sockaddr*)calloc(1, sizeof(struct sockaddr_storage));

			/* store mac address */
			if (adapter->PhysicalAddressLength == 6) {
				ifa->ifa_data = malloc(6);
				memcpy(ifa->ifa_data, adapter->PhysicalAddress, 6);
			}

/* pre-Vista must hunt for matching prefix in linked list, otherwise use
 * OnLinkPrefixLength from IP_ADAPTER_UNICAST_ADDRESS structure.
 * FirstPrefix requires Windows XP SP1, from SP1 to pre-Vista provides a
 * single adapter prefix for each IP address.  Vista and later provides
 * host IP address prefix, subnet IP address, and subnet broadcast IP
 * address.  In addition there is a multicast and broadcast address prefix.
 */
			ULONG prefixLength = 0;

#if defined( _WIN32 ) && ( _WIN32_WINNT >= 0x0600 )
/* For a unicast IPv4 address, any value greater than 32 is an illegal
 * value. For a unicast IPv6 address, any value greater than 128 is an
 * illegal value. A value of 255 is commonly used to represent an illegal
 * value.
 *
 * Windows 7 SP1 returns 64 for Teredo links which is incorrect.
 */

#define IN6_IS_ADDR_TEREDO(addr) \
	(((const uint32_t *)(addr))[0] == ntohl (0x20010000))

			if (AF_INET6 == unicast->Address.lpSockaddr->sa_family &&
/* TunnelType only applies to one interface on the adapter and no
 * convenient method is provided to determine which.
 */
				TUNNEL_TYPE_TEREDO == adapter->TunnelType &&
/* Test the interface with the known Teredo network prefix.
 */
				IN6_IS_ADDR_TEREDO( &((struct sockaddr_in6*)(unicast->Address.lpSockaddr))->sin6_addr) &&
/* Test that this version is actually wrong, subsequent releases from Microsoft
 * may resolve the issue.
 */
				32 != unicast->OnLinkPrefixLength)
			{
				prefixLength = 32;
			}
			else
				prefixLength = unicast->OnLinkPrefixLength;
#else
/* The order of linked IP_ADAPTER_UNICAST_ADDRESS structures pointed to by
 * the FirstUnicastAddress member does not have any relationship with the
 * order of linked IP_ADAPTER_PREFIX structures pointed to by the FirstPrefix
 * member.
 *
 * Example enumeration:
 *    [ no subnet ]
 *   ::1/128            - address
 *   ff00::%1/8         - multicast (no IPv6 broadcast)
 *   127.0.0.0/8        - subnet
 *   127.0.0.1/32       - address
 *   127.255.255.255/32 - subnet broadcast
 *   224.0.0.0/4        - multicast
 *   255.255.255.255/32 - broadcast
 *
 * Which differs from most adapters listing three IPv6:
 *   fe80::%10/64       - subnet
 *   fe80::51e9:5fe5:4202:325a%10/128 - address
 *   ff00::%10/8        - multicast
 *
 * !IfOperStatusUp IPv4 addresses are skipped:
 *   fe80::%13/64       - subnet
 *   fe80::d530:946d:e8df:8c91%13/128 - address
 *   ff00::%13/8        - multicast
 *    [ no subnet  ]
 *    [ no address ]
 *   224.0.0.0/4        - multicast
 *   255.255.255.255/32 - broadcast
 *
 * On PTP links no multicast or broadcast addresses are returned:
 *    [ no subnet ]
 *   fe80::5efe:10.203.9.30/128 - address
 *    [ no multicast ]
 *    [ no multicast ]
 *    [ no broadcast ]
 *
 * Active primary IPv6 interfaces are a bit overloaded:
 *   ::/0               - default route
 *   2001::/32          - global subnet
 *   2001:0:4137:9e76:2443:d6:ba87:1a2a/128 - global address
 *   fe80::/64          - link-local subnet
 *   fe80::2443:d6:ba87:1a2a/128 - link-local address
 *   ff00::/8           - multicast
 */

#define IN_LINKLOCAL(a)	((((uint32_t) (a)) & 0xaffff0000) == 0xa9fe0000)

			for (IP_ADAPTER_PREFIX *prefix = adapter->FirstPrefix; prefix; prefix = prefix->Next) {
				LPSOCKADDR lpSockaddr = prefix->Address.lpSockaddr;
				if (lpSockaddr->sa_family != unicast->Address.lpSockaddr->sa_family)
					continue;
/* special cases */
/* RFC2863: IPv4 interface not up */
				if (AF_INET == lpSockaddr->sa_family && adapter->OperStatus != IfOperStatusUp) {
/* RFC3927: link-local IPv4 always has 16-bit CIDR */
					if (IN_LINKLOCAL( ntohl (((struct sockaddr_in*)(unicast->Address.lpSockaddr))->sin_addr.s_addr))) {
						prefixLength = 16;
					}
					break;
				}
/* default IPv6 route */
				if (AF_INET6 == lpSockaddr->sa_family && 0 == prefix->PrefixLength && IN6_IS_ADDR_UNSPECIFIED( &((struct sockaddr_in6*)(lpSockaddr))->sin6_addr)) {
					continue;
				}
/* Assume unicast address for first prefix of operational adapter */
				if (AF_INET == lpSockaddr->sa_family)
					if (IN_MULTICAST( ntohl (((struct sockaddr_in*)(lpSockaddr))->sin_addr.s_addr))) {
						SOCKET_ERR(1, "FATAL: first prefix is non a unicast address\n");
						break;
					}
				if (AF_INET6 == lpSockaddr->sa_family)
					if (IN6_IS_ADDR_MULTICAST( &((struct sockaddr_in6*)(lpSockaddr))->sin6_addr)) {
						SOCKET_ERR(1, "FATAL: first prefix is not a unicast address\n");
						break;
					}
/* Assume subnet or host IP address for XP backward compatibility */

				prefixLength = prefix->PrefixLength;
				break;
			}
#endif /* defined( _WIN32 ) && ( _WIN32_WINNT >= 0x0600 ) */

/* map prefix to netmask */
			ifa->ifa_netmask->sa_family = unicast->Address.lpSockaddr->sa_family;
			switch (unicast->Address.lpSockaddr->sa_family) {
			case AF_INET:
				if (0 == prefixLength || prefixLength > 32) {
					prefixLength = 32;
				}
#if defined( _WIN32) && ( _WIN32_WINNT >= 0x0600 )
/* Added in Vista, but no IPv6 equivalent. */
				{
				ULONG Mask;
				ConvertLengthToIpv4Mask (prefixLength, &Mask);
				((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr.s_addr = Mask;	/* network order */
				}
#else
/* NB: left-shift of full bit-width is undefined in C standard. */
				((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr.s_addr = htonl( 0xffffffffU << ( 32 - prefixLength ) );
#endif
				break;

			case AF_INET6:
				if (0 == prefixLength || prefixLength > 128) {
					prefixLength = 128;
				}
				for (LONG i = prefixLength, j = 0; i > 0; i -= 8, ++j) {
					((struct sockaddr_in6*)ifa->ifa_netmask)->sin6_addr.s6_addr[ j ] = i >= 8 ? 0xff : (ULONG)(( 0xffU << ( 8 - i ) ) & 0xffU );
				}
				break;
			default:
				break;
			}
		}
	}
	free(pAddresses);

	return 0;
}
#else
#error No reference implementation for getifaddrs available for this platform.
#endif
#endif

int get_primary_mac_address(unsigned char mac_addr_buf[6])
{
	int result = -1;
	struct ifaddrs *ifaddr = NULL, *ifa = NULL;
	if (getifaddrs(&ifaddr) != -1) {
		for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
			if (ifa->ifa_addr == NULL) {
				continue;
			}
			if ((ifa->ifa_flags & IFF_UP) == 0) {
				continue;
			}
			if (ifa->ifa_flags & IFF_LOOPBACK) {
				continue;
			}
#if defined(__APPLE__) || defined (__FreeBSD__) || defined (__HAIKU__)
			if (ifa->ifa_addr->sa_family != AF_LINK) {
				continue;
			}
#if defined (__APPLE__)
			if (!strcmp(ifa->ifa_name, "en0")) {
#elif defined (__FreeBSD__) || defined (__HAIKU__)
			{
#endif
				memcpy(mac_addr_buf, (unsigned char *)LLADDR((struct sockaddr_dl *)(ifa)->ifa_addr), 6);
				result = 0;
				break;
			}
#elif defined (__linux__)
			if (ifa->ifa_addr->sa_family != AF_PACKET) {
				continue;
			}
			if (strcmp(ifa->ifa_name, "lo") != 0) {
				memcpy(mac_addr_buf, ((struct sockaddr_ll*)ifa->ifa_addr)->sll_addr, 6);
				result = 0;
				break;
			}
#elif defined (WIN32)
			if (ifa->ifa_data) {
				memcpy(mac_addr_buf, ifa->ifa_data, 6);
				result = 0;
				break;
			}
#elif defined(__CYGWIN__)
			if (ifa->ifa_data) {
				memcpy(mac_addr_buf, ((struct ifaddrs_hwdata *)ifa->ifa_data)->ifa_hwaddr.sa_data, 6);
				result = 0;
				break;
			}
#else
#error get_primary_mac_address is not supported on this platform.
#endif
		}
		freeifaddrs(ifaddr);
	}
	return result;
}

static int32_t _sockaddr_in6_scope_id(struct sockaddr_in6* addr)
{
	int32_t res = -1;
	struct ifaddrs *ifaddr = NULL, *ifa = NULL;
	uint32_t addr_scope;

	/* get scope for requested address */
	addr_scope = _in6_addr_scope(&addr->sin6_addr);
	if (addr_scope == 0) {
		/* global scope doesn't need a specific scope id */
		return addr_scope;
	}

	/* get interfaces */
	if (getifaddrs(&ifaddr) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "getifaddrs(): %s\n", strerror(errno));
		return res;
	}

	/* loop over interfaces */
	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
		/* skip if no address is available */
		if (ifa->ifa_addr == NULL) {
			continue;
		}

		/* skip if wrong family */
		if (ifa->ifa_addr->sa_family != AF_INET6) {
			continue;
		}

		/* skip if not up */
		if ((ifa->ifa_flags & IFF_UP) == 0) {
			continue;
		}

#ifndef __HAIKU__
		/* skip if not running */
		if ((ifa->ifa_flags & IFF_RUNNING) == 0) {
			continue;
		}
#endif

		struct sockaddr_in6* addr_in = (struct sockaddr_in6*)ifa->ifa_addr;

		/* skip if scopes do not match */
		if (_in6_addr_scope(&addr_in->sin6_addr) != addr_scope) {
			continue;
		}

		/* use if address is equal */
		if (memcmp(&addr->sin6_addr.s6_addr, &addr_in->sin6_addr.s6_addr, sizeof(addr_in->sin6_addr.s6_addr)) == 0) {
			/* if scope id equals the requested one then assume it was valid */
			if (addr->sin6_scope_id == addr_in->sin6_scope_id) {
				res = addr_in->sin6_scope_id;
				break;
			}
			res = addr_in->sin6_scope_id;
			continue;
		}

		/* skip loopback interface if not already matched exactly above */
		if ((ifa->ifa_flags & IFF_LOOPBACK) != 0) {
			continue;
		}

		res = addr_in->sin6_scope_id;

		/* if scope id equals the requested one then assume it was valid */
		if (addr->sin6_scope_id == addr_in->sin6_scope_id) {
			/* set the scope id of this interface as most likely candidate */
			break;
		}
	}

	freeifaddrs(ifaddr);

	return res;
}
#endif

int socket_connect_addr(struct sockaddr* addr, uint16_t port)
{
	int sfd = -1;
	int yes = 1;
	int bufsize = 0x20000;
	int addrlen = 0;
#ifdef _WIN32
	u_long l_yes = 1;
#endif

	if (addr->sa_family == AF_INET) {
		struct sockaddr_in* addr_in = (struct sockaddr_in*)addr;
		addr_in->sin_port = htons(port);
		addrlen = sizeof(struct sockaddr_in);
	}
#ifdef AF_INET6
	else if (addr->sa_family == AF_INET6) {
		struct sockaddr_in6* addr_in = (struct sockaddr_in6*)addr;
		addr_in->sin6_port = htons(port);

		/*
		 * IPv6 Routing Magic:
		 *
		 * If the scope of the address is a link-local one, IPv6 requires the
		 * scope id set to an interface number to allow proper routing. However,
		 * as the provided sockaddr might contain a wrong scope id, we must find
		 * a scope id from a suitable interface on this system or routing might
		 * fail. An IPv6 guru should have another look though...
		 */
		addr_in->sin6_scope_id = _sockaddr_in6_scope_id(addr_in);

		addrlen = sizeof(struct sockaddr_in6);
	}
#endif
	else {
		SOCKET_ERR(1, "ERROR: Unsupported address family\n");
		return -1;
	}

	sfd = socket(addr->sa_family, SOCK_STREAM, IPPROTO_TCP);
	if (sfd == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "socket(): %s\n", strerror(errno));
		return -1;
	}

#ifdef SO_NOSIGPIPE
	if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
		SOCKET_ERR(1, "setsockopt() SO_NOSIGPIPE: %s\n", strerror(errno));
		socket_close(sfd);
		return -1;
	}
#endif

	if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "setsockopt() SO_REUSEADDR: %s\n", strerror(errno));
		socket_close(sfd);
		return -1;
	}

#ifdef _WIN32
	ioctlsocket(sfd, FIONBIO, &l_yes);
#else
	int flags = fcntl(sfd, F_GETFL, 0);
	fcntl(sfd, F_SETFL, flags | O_NONBLOCK);
#endif

	do {
		if (connect(sfd, addr, addrlen) != -1) {
			break;
		}
#ifdef _WIN32
		if (WSAGetLastError() == WSAEWOULDBLOCK)
#else
		if (errno == EINPROGRESS)
#endif
		{
			if (poll_wrapper(sfd, FDM_WRITE, CONNECT_TIMEOUT) == poll_status_success) {
				int so_error;
				socklen_t len = sizeof(so_error);
				getsockopt(sfd, SOL_SOCKET, SO_ERROR, (void*)&so_error, &len);
				if (so_error == 0) {
					errno = 0;
					break;
				}
#ifdef _WIN32
				so_error = WSAError_to_errno(so_error);
#endif
				errno = so_error;
			} else {
				int so_error = 0;
				socklen_t len = sizeof(so_error);
				getsockopt(sfd, SOL_SOCKET, SO_ERROR, (void*)&so_error, &len);
				if (so_error != 0) {
#ifdef _WIN32
					so_error = WSAError_to_errno(so_error);
#endif
					errno = so_error;
				}
			}
		}
		socket_close(sfd);
		sfd = -1;
	} while (0);

	if (sfd < 0) {
		if (verbose >= 2) {
			char addrtxt[48];
			socket_addr_to_string(addr, addrtxt, sizeof(addrtxt));
			SOCKET_ERR(2, "%s: Could not connect to %s port %d\n", __func__, addrtxt, port);
		}
		return -1;
	}

	if (setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(int)) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "Could not set TCP_NODELAY on socket: %s\n", strerror(errno));
	}

	if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void*)&bufsize, sizeof(int)) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "Could not set send buffer for socket: %s\n", strerror(errno));
	}

	if (setsockopt(sfd, SOL_SOCKET, SO_RCVBUF, (void*)&bufsize, sizeof(int)) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "Could not set receive buffer for socket: %s\n", strerror(errno));
	}

	return sfd;
}

int socket_connect(const char *addr, uint16_t port)
{
	int sfd = -1;
	int yes = 1;
	int bufsize = 0x20000;
	struct addrinfo hints;
	struct addrinfo *result, *rp;
	char portstr[8];
	int res;
#ifdef _WIN32
	u_long l_yes = 1;
#else
	int flags = 0;
#endif

	memset(&hints, '\0', sizeof(struct addrinfo));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_NUMERICSERV;
	hints.ai_protocol = IPPROTO_TCP;

	snprintf(portstr, 8, "%d", port);

	res = getaddrinfo(addr, portstr, &hints, &result);
	if (res != 0) {
		SOCKET_ERR(1, "%s: getaddrinfo: %s\n", __func__, gai_strerror(res));
		return -1;
	}

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (sfd == -1) {
			continue;
		}

#ifdef SO_NOSIGPIPE
		if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
			SOCKET_ERR(1, "setsockopt() SO_NOSIGPIPE: %s\n", strerror(errno));
			socket_close(sfd);
			return -1;
		}
#endif

		if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
#ifdef _WIN32
			errno = WSAError_to_errno(WSAGetLastError());
#endif
			SOCKET_ERR(1, "setsockopt() SO_REUSEADDR: %s\n", strerror(errno));
			socket_close(sfd);
			continue;
		}

#ifdef _WIN32
		ioctlsocket(sfd, FIONBIO, &l_yes);
#else
		flags = fcntl(sfd, F_GETFL, 0);
		fcntl(sfd, F_SETFL, flags | O_NONBLOCK);
#endif

		if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1) {
			break;
		}
#ifdef _WIN32
		if (WSAGetLastError() == WSAEWOULDBLOCK)
#else
		if (errno == EINPROGRESS)
#endif
		{
			if (poll_wrapper(sfd, FDM_WRITE, CONNECT_TIMEOUT) == poll_status_success) {
				int so_error;
				socklen_t len = sizeof(so_error);
				getsockopt(sfd, SOL_SOCKET, SO_ERROR, (void*)&so_error, &len);
				if (so_error == 0) {
					errno = 0;
					break;
				}
#ifdef _WIN32
				so_error = WSAError_to_errno(so_error);
#endif
				errno = so_error;
			} else {
				int so_error = 0;
				socklen_t len = sizeof(so_error);
				getsockopt(sfd, SOL_SOCKET, SO_ERROR, (void*)&so_error, &len);
				if (so_error != 0) {
#ifdef _WIN32
					so_error = WSAError_to_errno(so_error);
#endif
					errno = so_error;
				}
			}
		}
		socket_close(sfd);
	}

	freeaddrinfo(result);

	if (rp == NULL) {
		SOCKET_ERR(2, "%s: Could not connect to %s:%d\n", __func__, addr, port);
		return -1;
	}

	if (setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(int)) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "Could not set TCP_NODELAY on socket: %s\n", strerror(errno));
	}

	if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void*)&bufsize, sizeof(int)) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "Could not set send buffer for socket: %s\n", strerror(errno));
	}

	if (setsockopt(sfd, SOL_SOCKET, SO_RCVBUF, (void*)&bufsize, sizeof(int)) == -1) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		SOCKET_ERR(1, "Could not set receive buffer for socket: %s\n", strerror(errno));
	}

	return sfd;
}

int socket_check_fd(int fd, fd_mode fdm, unsigned int timeout)
{
	if (fd < 0) {
		SOCKET_ERR(2, "ERROR: invalid fd in check_fd %d\n", fd);
		return -EINVAL;
	}

	int timeout_ms;
	if (timeout > 0) {
		timeout_ms = (int)timeout;
		if (timeout_ms <= 0)
			timeout_ms = -1;
	} else {
		timeout_ms = -1;
	}

	switch (poll_wrapper(fd, fdm, timeout_ms)) {
		case poll_status_success:
			return 1;
		case poll_status_timeout:
			return -ETIMEDOUT;
		case poll_status_error:
		default:
			SOCKET_ERR(2, "%s: poll_wrapper failed\n", __func__);
			return -ECONNRESET;
	}

	return -ECONNRESET;
}

int socket_accept(int fd, uint16_t port)
{
#ifdef _WIN32
	int addr_len;
#else
	socklen_t addr_len;
#endif
	int result;
	struct sockaddr_storage addr;
	addr_len = sizeof(addr);

	result = accept(fd, (struct sockaddr*)&addr, &addr_len);
#ifdef _WIN32
	if (result < 0) {
		errno = WSAError_to_errno(WSAGetLastError());
	}
#endif
	return result;
}

int socket_shutdown(int fd, int how)
{
	int result = shutdown(fd, how);
#ifdef _WIN32
	if (result < 0) {
		errno = WSAError_to_errno(WSAGetLastError());
	}
#endif
	return result;
}

int socket_close(int fd)
{
#ifdef _WIN32
	int result = closesocket(fd);
	if (result < 0) {
		errno = WSAError_to_errno(WSAGetLastError());
	}
	return result;
#else
	return close(fd);
#endif
}

int socket_receive(int fd, void *data, size_t length)
{
	return socket_receive_timeout(fd, data, length, 0, RECV_TIMEOUT);
}

int socket_peek(int fd, void *data, size_t length)
{
	return socket_receive_timeout(fd, data, length, MSG_PEEK, RECV_TIMEOUT);
}

int socket_receive_timeout(int fd, void *data, size_t length, int flags, unsigned int timeout)
{
	int res;
	int result;

	// check if data is available
	res = socket_check_fd(fd, FDM_READ, timeout);
	if (res <= 0) {
		return res;
	}
	// if we get here, there _is_ data available
	result = recv(fd, data, length, flags);
	if (result == 0) {
		// but this is an error condition
		SOCKET_ERR(3, "%s: fd=%d recv returned 0\n", __func__, fd);
		return -ECONNRESET;
	}
	if (result < 0) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		return -errno;
	}
	return result;
}

int socket_send(int fd, void *data, size_t length)
{
	int flags = 0;
	int res = socket_check_fd(fd, FDM_WRITE, SEND_TIMEOUT);
	if (res <= 0) {
		return res;
	}
#ifdef MSG_NOSIGNAL
	flags |= MSG_NOSIGNAL;
#endif
	int s = (int)send(fd, data, length, flags);
	if (s < 0) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		return -errno;
	}
	return s;
}

int socket_get_socket_port(int fd, uint16_t *port)
{
#ifdef _WIN32
	int addr_len;
#else
	socklen_t addr_len;
#endif
	struct sockaddr_in addr;

	memset(&addr, 0, sizeof(addr));

	addr_len = sizeof(addr);
	if (0 > getsockname(fd, (struct sockaddr*)&addr, &addr_len)) {
#ifdef _WIN32
		errno = WSAError_to_errno(WSAGetLastError());
#endif
		return -1;
	}

	*port = ntohs(addr.sin_port);
	return 0;
}
0707010000002A000081A400000000000000000000000167AD5DE9000020C6000000000000000000000000000000000000003C00000000libimobiledevice-glue-1.3.1+git18.20250213/src/termcolors.c/*
 * termcolors.c
 *
 * Copyright (c) 2020-2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef _WIN32
#include <windows.h>
#endif

#include <stdio.h>
#include <stdlib.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <string.h>
#include <stdarg.h>

#include "common.h"
#include "libimobiledevice-glue/termcolors.h"

static int use_colors = 0;

#ifdef _WIN32
static int WIN32_LEGACY_MODE = 1;
static WORD COLOR_RESET_ATTR = 0;
static WORD DEFAULT_FG_ATTR = 0;
static WORD DEFAULT_BG_ATTR = 0;
static HANDLE h_stdout = INVALID_HANDLE_VALUE;
static HANDLE h_stderr = INVALID_HANDLE_VALUE;

#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif

#define STYLE_DIM (1 << 16)

#define FG_COLOR_MASK (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
#define BG_COLOR_MASK (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
#define FG_COLOR_ATTR_MASK (FG_COLOR_MASK | FOREGROUND_INTENSITY)
#define BG_COLOR_ATTR_MASK (BG_COLOR_MASK | BACKGROUND_INTENSITY)

static int style_map[9] = {
	/* RESET ALL   */ 0,
	/* BRIGHT      */ FOREGROUND_INTENSITY,
	/* DIM         */ STYLE_DIM,
	/* (n/a)       */ 0,
        /* UNDERLINED  */ 0, // COMMON_LVB_UNDERSCORE ?
	/* BLINK       */ 0, // NOT SUPPORTED
	/* (n/a)       */ 0,
	/* REVERSE CLR */ 0, // COMMON_LVB_REVERSE_VIDEO ?
	/* HIDDEN      */ 0  // NOT SUPPORTED
};

static int fgcolor_map[8] = {
	/* BLACK   */ 0,
	/* RED     */ FOREGROUND_RED,
	/* GREEN   */ FOREGROUND_GREEN,
	/* YELLOW  */ FOREGROUND_GREEN | FOREGROUND_RED,
	/* BLUE    */ FOREGROUND_BLUE,
	/* MAGENTA */ FOREGROUND_BLUE | FOREGROUND_RED,
	/* CYAN    */ FOREGROUND_BLUE | FOREGROUND_GREEN,
	/* WHITE   */ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
};
static int bgcolor_map[8] = {
	/* BLACK   */ 0,
	/* RED     */ BACKGROUND_RED,
	/* GREEN   */ BACKGROUND_GREEN,
	/* YELLOW  */ BACKGROUND_GREEN | BACKGROUND_RED,
	/* BLUE    */ BACKGROUND_BLUE,
	/* MAGENTA */ BACKGROUND_BLUE | BACKGROUND_RED,
	/* CYAN    */ BACKGROUND_BLUE | BACKGROUND_GREEN,
	/* WHITE   */ BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
};
#else
static int WIN32_LEGACY_MODE = 0;
#endif

void term_colors_init()
{	
#ifdef _WIN32
	DWORD conmode = 0;
	h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
	GetConsoleMode(h_stdout, &conmode);
	if (conmode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
		WIN32_LEGACY_MODE = 0;
	} else {
		conmode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
		if (SetConsoleMode(h_stdout, conmode)) {
			WIN32_LEGACY_MODE = 0;
		} else {
			WIN32_LEGACY_MODE = 1;
		}
	}
	if (WIN32_LEGACY_MODE) {
		CONSOLE_SCREEN_BUFFER_INFO csbi;
		if (GetConsoleScreenBufferInfo(h_stdout, &csbi)) {
			COLOR_RESET_ATTR = csbi.wAttributes;
			DEFAULT_FG_ATTR = csbi.wAttributes & FG_COLOR_ATTR_MASK;
			DEFAULT_BG_ATTR = csbi.wAttributes & BG_COLOR_ATTR_MASK;
		}
		h_stderr = GetStdHandle(STD_ERROR_HANDLE);
	}
#endif
	use_colors = isatty(1);
	const char* color_env = getenv("COLOR");
	if (color_env) {
		long val = strtol(color_env, NULL, 10);
		use_colors = (val != 0);
	}
}

void term_colors_set_enabled(int en)
{
	use_colors = en;
}

int cvfprintf(FILE* stream, const char* fmt, va_list vargs)
{
	int res = 0;
	int colorize = use_colors;
#ifdef _WIN32
	struct esc_item {
		int pos;
		WORD attr;
	};
	HANDLE h_stream = h_stdout;

	if (WIN32_LEGACY_MODE) {
		if (stream == stdout) {
			h_stream = h_stdout;
		} else if (stream == stderr) {
			h_stream = h_stderr;
		} else {
			colorize = 0;
		}
	}
#endif
	if (!colorize || WIN32_LEGACY_MODE) {
		// first, we need to print the string WITH escape sequences
		va_list vargs_copy;
		va_copy(vargs_copy, vargs);
		int len = vsnprintf(NULL, 0, fmt, vargs);
		char* newbuf = (char*)malloc(len+1);
		res = vsnprintf(newbuf, len+1, fmt, vargs_copy);
		va_end(vargs_copy);

		// then, we need to remove the escape sequences, if any
#ifdef _WIN32
		// if colorize is on, we need to keep their positions for later
		struct esc_item* esc_items = NULL;
		int attr = 0;
		if (colorize) {
			esc_items = (struct esc_item*)malloc(sizeof(struct esc_item) * ((len/3)+1));
			CONSOLE_SCREEN_BUFFER_INFO csbi;
			if (GetConsoleScreenBufferInfo(h_stream, &csbi)) {
				attr = csbi.wAttributes;
			}
		}
#endif
		int num_esc = 0;
		char* start = &newbuf[0];
		char* p = start;
		char* end = start + len + 1;
		while (p < end-1) {
			char* cur = p;
			if (*p == '\x1b' && end-p > 2 && *(p+1) == '[') {
				p+=2;
				if (*p == 'm') {
#ifdef _WIN32
					attr = COLOR_RESET_ATTR;
#endif
					int move_by = (p+1)-cur;
					int move_amount = end-(p+1);
					memmove(cur, p+1, move_amount);
					end -= move_by;
					p = cur;
				} else {
					char* endp = NULL;
					do {
						long lval = strtol(p, &endp, 10);
						if (!endp || (*endp != ';' && *endp != 'm')) {
							fprintf(stderr, "\n*** %s: Invalid escape sequence in format string, expected ';' or 'm' ***\n", __func__);
#ifdef _WIN32
							free(esc_items);
#endif
							free(newbuf);
							return -1;
						}
#ifdef _WIN32
						if (colorize) {
							if (lval >= 0 && lval <= 8) {
								/* style attributes */
								attr &= ~FOREGROUND_INTENSITY;
								attr |= style_map[lval];
							} else if (lval >= 30 && lval <= 37) {
								/* foreground color */
								attr &= ~FG_COLOR_MASK;
								attr |= fgcolor_map[lval-30];
							} else if (lval == 39) {
								/* default foreground color */
								attr &= ~FG_COLOR_ATTR_MASK;
								attr |= DEFAULT_FG_ATTR;
							} else if (lval >= 40 && lval <= 47) {
								/* background color */
								attr &= ~BG_COLOR_MASK;
								attr |= bgcolor_map[lval-40];
							} else if (lval == 49) {
								/* default background color */
								attr &= ~BG_COLOR_ATTR_MASK;
								attr |= DEFAULT_BG_ATTR;
							} else if (lval >= 90 && lval <= 97) {
								/* foreground color bright */
								attr &= ~FG_COLOR_ATTR_MASK;
								attr |= fgcolor_map[lval-90];
								attr |= FOREGROUND_INTENSITY;
							} else if (lval >= 100 && lval <= 107) {
								/* background color bright */
								attr &= ~BG_COLOR_MASK;
								attr |= bgcolor_map[lval-100];
								attr |= BACKGROUND_INTENSITY;
							}
						}
#else
						(void)lval; // suppress compiler warning about unused variable
#endif
						p = endp+1;
					} while (p < end && *endp == ';');

					int move_by = (endp+1)-cur;
					int move_amount = end-(endp+1);
					memmove(cur, endp+1, move_amount);
					end -= move_by;
					p = cur;
				}
#ifdef _WIN32
				if (colorize) {
					esc_items[num_esc].pos = p-start;
					if (attr & STYLE_DIM) {
						attr &= ~STYLE_DIM;
						attr &= ~FOREGROUND_INTENSITY;
					}
					esc_items[num_esc].attr = (WORD)attr;
					num_esc++;
				}
#endif
			} else {
				p++;
			}
		}

		if (num_esc == 0) {
			res = fputs(newbuf, stream);
			free(newbuf);
#ifdef _WIN32
			free(esc_items);
#endif
			return res;
		}
#ifdef _WIN32
		else {
			p = &newbuf[0];
			char* lastp = &newbuf[0];
			int i;
			for (i = 0; i < num_esc; i++) {
				p = &newbuf[esc_items[i].pos];
				if (lastp < p) {
					fprintf(stream, "%.*s", (int)(p-lastp), lastp);
					lastp = p;
				}
				SetConsoleTextAttribute(h_stream, esc_items[i].attr);
			}
			if (lastp < end) {
				fprintf(stream, "%.*s", (int)(end-lastp), lastp);
			}
			return res;
		}
#endif
	} else {
		res = vfprintf(stream, fmt, vargs);
	}
	return res;
}

int cfprintf(FILE* stream, const char* fmt, ...)
{
	int res = 0;
	va_list va;
	va_start(va, fmt);
	res = cvfprintf(stream, fmt, va);
	va_end(va);
	return res;
}

int cprintf(const char* fmt, ...)
{
	int res = 0;
	va_list va;
	va_start(va, fmt);
	res = cvfprintf(stdout, fmt, va);
	va_end(va);
	return res;
}
0707010000002B000081A400000000000000000000000167AD5DE900001125000000000000000000000000000000000000003800000000libimobiledevice-glue-1.3.1+git18.20250213/src/thread.c/*
 * thread.c
 *
 * Copyright (c) 2012-2019 Nikias Bassen, All Rights Reserved.
 * Copyright (c) 2012 Martin Szulecki, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef _WIN32
#include <windows.h>
#endif
#include "common.h"
#include "libimobiledevice-glue/thread.h"

int thread_new(THREAD_T *thread, thread_func_t thread_func, void* data)
{
#ifdef _WIN32
	HANDLE th = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)(void*)thread_func, data, 0, NULL);
	if (th == NULL) {
		return -1;
	}
	*thread = th;
	return 0;
#else
	int res = pthread_create(thread, NULL, thread_func, data);
	return res;
#endif
}

void thread_detach(THREAD_T thread)
{
#ifdef _WIN32
	CloseHandle(thread);
#else
	pthread_detach(thread);
#endif
}

void thread_free(THREAD_T thread)
{
#ifdef _WIN32
	CloseHandle(thread);
#endif
}

int thread_join(THREAD_T thread)
{
	/* wait for thread to complete */
#ifdef _WIN32
	return (int)WaitForSingleObject(thread, INFINITE);
#else
	return pthread_join(thread, NULL);
#endif
}

int thread_alive(THREAD_T thread)
{
	if (!thread)
		return 0;
#ifdef _WIN32
	return WaitForSingleObject(thread, 0) == WAIT_TIMEOUT;
#else
	return pthread_kill(thread, 0) == 0;
#endif
}

int thread_cancel(THREAD_T thread)
{
#ifdef _WIN32
	return -1;
#else
#ifdef HAVE_PTHREAD_CANCEL
	return pthread_cancel(thread);
#else
	return -1;
#endif
#endif
}

void mutex_init(mutex_t* mutex)
{
#ifdef _WIN32
	InitializeCriticalSection((LPCRITICAL_SECTION)mutex);
#else
	pthread_mutex_init(mutex, NULL);
#endif
}

void mutex_destroy(mutex_t* mutex)
{
#ifdef _WIN32
	DeleteCriticalSection((LPCRITICAL_SECTION)mutex);
#else
	pthread_mutex_destroy(mutex);
#endif
}

void mutex_lock(mutex_t* mutex)
{
#ifdef _WIN32
	EnterCriticalSection((LPCRITICAL_SECTION)mutex);
#else
	pthread_mutex_lock(mutex);
#endif
}

void mutex_unlock(mutex_t* mutex)
{
#ifdef _WIN32
	LeaveCriticalSection((LPCRITICAL_SECTION)mutex);
#else
	pthread_mutex_unlock(mutex);
#endif
}

void thread_once(thread_once_t *once_control, void (*init_routine)(void))
{
#ifdef _WIN32
	while (InterlockedExchange(&(once_control->lock), 1) != 0) {
		Sleep(1);
	}
	if (!once_control->state) {
		once_control->state = 1;
		init_routine();
	}
	InterlockedExchange(&(once_control->lock), 0);
#else
	pthread_once(once_control, init_routine);
#endif
}

void cond_init(cond_t* cond)
{
#ifdef _WIN32
	cond->sem = CreateSemaphore(NULL, 0, 32767, NULL);
#else
	pthread_cond_init(cond, NULL);
#endif
}

void cond_destroy(cond_t* cond)
{
#ifdef _WIN32
	CloseHandle(cond->sem);
#else
	pthread_cond_destroy(cond);
#endif
}

int cond_signal(cond_t* cond)
{
#ifdef _WIN32
	int result = 0;
	if (!ReleaseSemaphore(cond->sem, 1, NULL)) {
		result = -1;
	}
	return result;
#else
	return pthread_cond_signal(cond);
#endif
}

int cond_wait(cond_t* cond, mutex_t* mutex)
{
#ifdef _WIN32
	mutex_unlock(mutex);
	DWORD res = WaitForSingleObject(cond->sem, INFINITE);
	switch (res) {
		case WAIT_OBJECT_0:
			return 0;
		default:
			return -1;
	}
#else
	return pthread_cond_wait(cond, mutex);
#endif
}

int cond_wait_timeout(cond_t* cond, mutex_t* mutex, unsigned int timeout_ms)
{
#ifdef _WIN32
	mutex_unlock(mutex);
	DWORD res = WaitForSingleObject(cond->sem, timeout_ms);
	switch (res) {
		case WAIT_OBJECT_0:
		case WAIT_TIMEOUT:
			return 0;
		default:
			return -1;
	}
#else
	struct timespec ts;
	struct timeval now;
	gettimeofday(&now, NULL);

	ts.tv_sec = now.tv_sec + timeout_ms / 1000;
	ts.tv_nsec = now.tv_usec * 1000 + 1000 * 1000 * (timeout_ms % 1000);
	ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
	ts.tv_nsec %= (1000 * 1000 * 1000);

	return pthread_cond_timedwait(cond, mutex, &ts);
#endif
}
0707010000002C000081A400000000000000000000000167AD5DE900001256000000000000000000000000000000000000003500000000libimobiledevice-glue-1.3.1+git18.20250213/src/tlv.c/*
 * tlv.c
 * Simple TLV implementation.
 *
 * Copyright (c) 2021 Nikias Bassen, All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>

#include "common.h"
#include "libimobiledevice-glue/tlv.h"
#include "endianness.h"

tlv_buf_t tlv_buf_new()
{
	tlv_buf_t tlv = malloc(sizeof(struct tlv_buf));
	tlv->capacity = 1024;
	tlv->length = 0;
	tlv->data = malloc(tlv->capacity);
	return tlv;	
}

void tlv_buf_free(tlv_buf_t tlv)
{
	if (tlv) {
		free(tlv->data);
		free(tlv);
	}
}

void tlv_buf_append(tlv_buf_t tlv, uint8_t tag, unsigned int length, void* data)
{
	if (!tlv || !tlv->data) {
		return;
	}
	unsigned int req_len = (length > 255) ? (length / 255) * 257 + (2 + (length % 255)) : length;
	if (tlv->length + req_len > tlv->capacity) {
		unsigned int newcapacity = tlv->capacity + ((req_len / 1024) + 1) * 1024;
		unsigned char* newdata = realloc(tlv->data, newcapacity);
		if (!newdata) {
			fprintf(stderr, "%s: ERROR: Failed to realloc\n", __func__);
			return;
		}
		tlv->data = newdata;
		tlv->capacity = newcapacity;
	}
	unsigned char* p = tlv->data + tlv->length;
	unsigned int cur = 0;
	while (length - cur > 0) {
		if (length - cur > 255) {
			*(p++) = tag;
			*(p++) = 0xFF;
			memcpy(p, (unsigned char*)data + cur, 255);
			p += 255;
			cur += 255;
		} else {
			uint8_t rem = length - cur;
			*(p++) = tag;
			*(p++) = rem;
			memcpy(p, (unsigned char*)data + cur, rem);
			p += rem;
			cur += rem;
		}
	}
	tlv->length = p - tlv->data;
}

unsigned char* tlv_get_data_ptr(const void* tlv_data, void* tlv_end, uint8_t tag, uint8_t* length)
{
	unsigned char* p = (unsigned char*)tlv_data;
	unsigned char* end = (unsigned char*)tlv_end;
	while (p < end) {
		uint8_t cur_tag = *(p++);
		uint8_t len = *(p++);
		if (cur_tag == tag) {
			*length = len;
			return p;
		}
		p+=len;
	}
	return NULL;
}

int tlv_data_get_uint(const void* tlv_data, unsigned int tlv_length, uint8_t tag, uint64_t* value)
{
	if (!tlv_data || tlv_length < 2 || !value) {
		return 0;
	}
	uint8_t length = 0;
	unsigned char* ptr = tlv_get_data_ptr(tlv_data, (unsigned char*)tlv_data+tlv_length, tag, &length);
	if (!ptr) {
		return 0;
	}
	if (ptr + length > (unsigned char*)tlv_data + tlv_length) {
		return 0;
	}
	if (length == 1) {
		uint8_t val = *ptr;
		*value = val;
	} else if (length == 2) {
		uint16_t val = *(uint16_t*)ptr;
		val = le16toh(val);
		*value = val;
	} else if (length == 4) {
		uint32_t val = *(uint32_t*)ptr;
		val = le32toh(val);
		*value = val;
	} else if (length == 8) {
		uint64_t val = *(uint64_t*)ptr;
		val = le64toh(val);
		*value = val;
	} else {
		return 0;
	}
	return 1;
}

int tlv_data_get_uint8(const void* tlv_data, unsigned int tlv_length, uint8_t tag, uint8_t* value)
{
	if (!tlv_data || tlv_length < 2 || !value) {
		return 0;
	}
	uint8_t length = 0;
	unsigned char* ptr = tlv_get_data_ptr(tlv_data, (unsigned char*)tlv_data+tlv_length, tag, &length);
	if (!ptr) {
		return 0;
	}
	if (length != 1) {
		return 0;
	}
	if (ptr + length > (unsigned char*)tlv_data + tlv_length) {
		return 0;
	}
	*value = *ptr;
	return 1;
}

int tlv_data_copy_data(const void* tlv_data, unsigned int tlv_length, uint8_t tag, void** out, unsigned int* out_len)
{
	if (!tlv_data || tlv_length < 2 || !out || !out_len) {
		return 0;
	}
	*out = NULL;
	*out_len = 0;

	unsigned char* dest = NULL;
	unsigned int dest_len = 0;

	unsigned char* ptr = (unsigned char*)tlv_data;
	unsigned char* end = (unsigned char*)tlv_data + tlv_length;
	while (ptr < end) {
		uint8_t length = 0;
		ptr = tlv_get_data_ptr(ptr, end, tag, &length);
		if (!ptr) {
			break;
		}
		unsigned char* newdest = realloc(dest, dest_len + length);
		if (!newdest) {
			free(dest);
			return 0;
		}
		dest = newdest;
		memcpy(dest + dest_len, ptr, length);
		dest_len += length;
		ptr += length;
	}
	if (!dest) {
		return 0;
	}

	*out = (void*)dest;
	*out_len = dest_len;

	return 1;
}
0707010000002D000081A400000000000000000000000167AD5DE900001841000000000000000000000000000000000000003700000000libimobiledevice-glue-1.3.1+git18.20250213/src/utils.c/*
 * utils.c
 * Miscellaneous utilities for string manipulation,
 * file I/O and plist helper.
 *
 * Copyright (c) 2014-2023 Nikias Bassen, All Rights Reserved.
 * Copyright (c) 2013-2014 Martin Szulecki, All Rights Reserved.
 * Copyright (c) 2013 Federico Mena Quintero
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifndef _MSC_VER
#include <sys/time.h>
#endif
#include <inttypes.h>
#include <ctype.h>
#include <errno.h>

#include "common.h"
#include "libimobiledevice-glue/utils.h"

#ifndef HAVE_STPCPY
#undef stpcpy
char *stpcpy(char *s1, const char *s2);

/**
 * Copy characters from one string into another
 *
 * @note: The strings should not overlap, as the behavior is undefined.
 *
 * @s1: The source string.
 * @s2: The destination string.
 *
 * @return a pointer to the terminating `\0' character of @s1,
 * or NULL if @s1 or @s2 is NULL.
 */
char *stpcpy(char *s1, const char *s2)
{
	if (s1 == NULL || s2 == NULL)
		return NULL;

	strcpy(s1, s2);

	return s1 + strlen(s2);
}
#endif

/**
 * Concatenate strings into a newly allocated string
 *
 * @note: Specify NULL for the last string in the varargs list
 *
 * @str: The first string in the list
 * @...: Subsequent strings.  Use NULL for the last item.
 *
 * @return a newly allocated string, or NULL if @str is NULL.  This will also
 * return NULL and set errno to ENOMEM if memory is exhausted.
 */
char *string_concat(const char *str, ...)
{
	size_t len;
	va_list args;
	char *s;
	char *result;
	char *dest;

	if (!str)
		return NULL;

	/* Compute final length */

	len = strlen(str) + 1; /* plus 1 for the null terminator */

	va_start(args, str);
	s = va_arg(args, char *);
	while (s) {
		len += strlen(s);
		s = va_arg(args, char*);
	}
	va_end(args);

	/* Concat each string */

	result = malloc(len);
	if (!result)
		return NULL; /* errno remains set */

	dest = result;

	dest = stpcpy(dest, str);

	va_start(args, str);
	s = va_arg(args, char *);
	while (s) {
		dest = stpcpy(dest, s);
		s = va_arg(args, char *);
	}
	va_end(args);

	return result;
}

char *string_append(char* str, ...)
{
	size_t len = 0;
	size_t slen;
	va_list args;
	char *s;
	char *result;
	char *dest;

	/* Compute final length */

	if (str) {
		len = strlen(str);
	}
	slen = len;
	len++; /* plus 1 for the null terminator */

	va_start(args, str);
	s = va_arg(args, char *);
	while (s) {
		len += strlen(s);
		s = va_arg(args, char*);
	}
	va_end(args);

	result = realloc(str, len);
	if (!result)
		return NULL; /* errno remains set */

	dest = result + slen;

	/* Concat additional strings */

	va_start(args, str);
	s = va_arg(args, char *);
	while (s) {
		dest = stpcpy(dest, s);
		s = va_arg(args, char *);
	}
	va_end(args);

	return result;
}

char *string_build_path(const char *elem, ...)
{
	if (!elem)
		return NULL;
	va_list args;
	int len = strlen(elem)+1;
	va_start(args, elem);
	char *arg = va_arg(args, char*);
	while (arg) {
		len += strlen(arg)+1;
		arg = va_arg(args, char*);
	}
	va_end(args);

	char* out = (char*)malloc(len);
	strcpy(out, elem);

	va_start(args, elem);
	arg = va_arg(args, char*);
	while (arg) {
		strcat(out, "/");
		strcat(out, arg);
		arg = va_arg(args, char*);
	}
	va_end(args);
	return out;
}

char *string_format_size(uint64_t size)
{
	char buf[80];
	double sz;
	if (size >= 1000000000000LL) {
		sz = ((double)size / 1000000000000.0F);
		sprintf(buf, "%0.1f TB", sz);
	} else if (size >= 1000000000LL) {
		sz = ((double)size / 1000000000.0F);
		sprintf(buf, "%0.1f GB", sz);
	} else if (size >= 1000000LL) {
		sz = ((double)size / 1000000.0F);
		sprintf(buf, "%0.1f MB", sz);
	} else if (size >= 1000LL) {
		sz = ((double)size / 1000.0F);
		sprintf(buf, "%0.1f KB", sz);
	} else {
		sprintf(buf, "%d Bytes", (int)size);
	}
	return strdup(buf);
}

char *string_toupper(char* str)
{
	char *res = strdup(str);
	size_t i;
	for (i = 0; i < strlen(res); i++) {
		res[i] = toupper(res[i]);
	}
	return res;
}

static int get_rand(int min, int max)
{
	int retval = (rand() % (max - min)) + min;
	return retval;
}

char *generate_uuid()
{
	const char *chars = "ABCDEF0123456789";
	int i = 0;
	char *uuid = (char *) malloc(sizeof(char) * 37);

	srand(time(NULL));

	for (i = 0; i < 36; i++) {
		if (i == 8 || i == 13 || i == 18 || i == 23) {
			uuid[i] = '-';
			continue;
		}
		uuid[i] = chars[get_rand(0, 16)];
	}

	/* make it a real string */
	uuid[36] = '\0';

	return uuid;
}

int buffer_read_from_filename(const char *filename, char **buffer, uint64_t *length)
{
	FILE *f;
	uint64_t size;

	if (!filename || !buffer || !length) {
		return 0;
	}

	*length = 0;

	f = fopen(filename, "rb");
	if (!f) {
		return 0;
	}

	fseek(f, 0, SEEK_END);
	size = ftell(f);
	rewind(f);

	if (size == 0) {
		fclose(f);
		return 0;
	}

	*buffer = (char*)malloc(sizeof(char)*(size+1));

	if (*buffer == NULL) {
		fclose(f);
		return 0;
	}

	int ret = 1;
	if (fread(*buffer, sizeof(char), size, f) != size) {
		free(*buffer);
		ret = 0;
		errno = EIO;
	}
	fclose(f);

	*length = size;
	return ret;
}

int buffer_write_to_filename(const char *filename, const char *buffer, uint64_t length)
{
	FILE *f;

	f = fopen(filename, "wb");
	if (f) {
		size_t written = fwrite(buffer, sizeof(char), length, f);
		fclose(f);

		if (written == length) {
			return 1;
		}
		else {
			// Not all data could be written.
			errno = EIO;
			return 0;
		}
	}
	else {
		// Failed to open the file, let the caller know.
		return 0;
	}
}
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!487 blocks
openSUSE Build Service is sponsored by