master 9ca1851a4998 cached
21 files
147.1 KB
37.5k tokens
54 symbols
1 requests
Download .txt
Repository: libimobiledevice/libideviceactivation
Branch: master
Commit: 9ca1851a4998
Files: 21
Total size: 147.1 KB

Directory structure:
gitextract_4pdngyja/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── build.yml
├── .gitignore
├── AUTHORS
├── COPYING
├── COPYING.LESSER
├── Makefile.am
├── NEWS
├── README.md
├── autogen.sh
├── configure.ac
├── git-version-gen
├── include/
│   ├── Makefile.am
│   └── libideviceactivation.h
├── man/
│   ├── Makefile.am
│   └── ideviceactivation.1
├── src/
│   ├── Makefile.am
│   ├── activation.c
│   └── libideviceactivation-1.0.pc.in
└── tools/
    ├── Makefile.am
    └── ideviceactivation.c

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
github: nikias
patreon: nikias
custom: ["https://www.paypal.me/NikiasBassen"]


================================================
FILE: .github/workflows/build.yml
================================================
name: 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 update
          sudo apt-get install libcurl4-openssl-dev libxml2-dev
    - 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: fetch libusbmuxd
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libusbmuxd-latest_${{env.target_triplet}}
        repo: libimobiledevice/libusbmuxd
    - name: fetch libimobiledevice-glue
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libimobiledevice-glue-latest_${{env.target_triplet}}
        repo: libimobiledevice/libimobiledevice-glue
    - name: fetch libimobiledevice
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libimobiledevice-latest_${{env.target_triplet}}
        repo: libimobiledevice/libimobiledevice
    - name: install external dependencies
      run: |
          mkdir extract
          for I in *.tar; do
            tar -C extract -xvf $I
          done
          rm -rf extract/lib
          sudo cp -r extract/* /
          sudo ldconfig
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0
    - name: autogen
      run: ./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 libideviceactivation.tar usr
    - name: publish artifact
      uses: actions/upload-artifact@v4
      with:
        name: libideviceactivation-latest_${{env.target_triplet}}
        path: libideviceactivation.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: fetch libusbmuxd
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libusbmuxd-latest_macOS
        repo: libimobiledevice/libusbmuxd
    - name: fetch libimobiledevice-glue
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libimobiledevice-glue-latest_macOS
        repo: libimobiledevice/libimobiledevice-glue
    - name: fetch libimobiledevice
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libimobiledevice-latest_macOS
        repo: libimobiledevice/libimobiledevice
    - 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: install additional requirements
      run: |
          SDKDIR=`xcrun --sdk macosx --show-sdk-path 2>/dev/null`
          echo "SDKDIR=$SDKDIR" >> $GITHUB_ENV
          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"
          echo "BUILD_CFLAGS=$CFLAGS" >> $GITHUB_ENV
    - name: autogen
      run: |
          export CFLAGS="${{env.BUILD_CFLAGS}} -Wno-nullability-completeness -Wno-expansion-to-defined"
          echo "Using CFLAGS: $CFLAGS"
          ./autogen.sh PKG_CONFIG_PATH=/usr/local/lib/pkgconfig \
              libcurl_CFLAGS="-I${{env.SDKDIR}}/usr/include" libcurl_LIBS="-lcurl" \
              libxml2_CFLAGS="-I${{env.SDKDIR}}/usr/include" libxml2_LIBS="-lxml2" \
              libimobiledevice_CFLAGS="-I/usr/local/include" libimobiledevice_LIBS="-L/usr/local/lib -limobiledevice-1.0"
    - 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 libideviceactivation.tar usr
    - name: publish artifact
      uses: actions/upload-artifact@v4
      with:
        name: libideviceactivation-latest_macOS
        path: libideviceactivation.tar
  build-windows:
    runs-on: windows-latest
    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
          mingw-w64-${{ matrix.arch }}-pkg-config
          mingw-w64-${{ matrix.arch }}-openssl
          mingw-w64-${{ matrix.arch }}-libxml2
          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: fetch libusbmuxd
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libusbmuxd-latest_${{ matrix.arch }}-${{ env.dest }}
        repo: libimobiledevice/libusbmuxd
    - name: fetch libimobiledevice-glue
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libimobiledevice-glue-latest_${{ matrix.arch }}-${{ env.dest }}
        repo: libimobiledevice/libimobiledevice-glue
    - name: fetch libimobiledevice
      uses: dawidd6/action-download-artifact@v6
      with:
        github_token: ${{secrets.GITHUB_TOKEN}}
        workflow: build.yml
        name: libimobiledevice-latest_${{ matrix.arch }}-${{ env.dest }}
        repo: libimobiledevice/libimobiledevice
    - 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: install additional requirements
      run: |
          mkdir deps
          FILENAME="libcurl-8.1.0-static.tar.bz2"
          curl -o $FILENAME.b64 -Ls "https://gist.github.com/nikias/6c397a0a2f4f4eafd91b81cccd22b761/raw/85216e60af6787f3b351291165eb91bd585ff09a/libcurl-8.1.0-static-${{matrix.arch}}-${{env.dest}}.tar.bz2"
          base64 -d < $FILENAME.b64 > $FILENAME
          tar -C deps -xjf $FILENAME
          echo "LIBCURL_CFLAGS=-I`pwd`/deps/include -DCURL_STATICLIB" >> $GITHUB_ENV
          echo "LIBCURL_LIBS=-Xlinker `pwd`/deps/lib/libcurl.a -Xlinker /${{env.dest}}/lib/libzstd.a -Xlinker /${{env.dest}}/lib/libz.a -Xlinker -lws2_32 -Xlinker -lcrypt32 -Xlinker -lwldap32 -Xlinker -lbcrypt -Xlinker -lssl -Xlinker -lcrypto" >> $GITHUB_ENV
    - name: autogen
      run: ./autogen.sh libcurl_CFLAGS="${{env.LIBCURL_CFLAGS}}" libcurl_LIBS="${{env.LIBCURL_LIBS}}"
    - 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 libideviceactivation.tar ${{ env.dest }}
    - name: publish artifact
      uses: actions/upload-artifact@v4
      with:
        name: libideviceactivation-latest_${{ matrix.arch }}-${{ env.dest }}
        path: libideviceactivation.tar


================================================
FILE: .gitignore
================================================
*.[oa]
*~
*.po
*.lo
*.la
.*.swp
*/.deps/*
*.patch
Makefile
Makefile.in
aclocal.m4
autom4te.cache
compile
config.guess
config.h
config.h.in
config.log
config.status
config.sub
configure
depcomp
install-sh
libideviceactivation-1.0.pc
libtool
ltmain.sh
m4
missing
src/.libs
tools/.libs
tools/ideviceactivation
stamp-h1


================================================
FILE: AUTHORS
================================================
Konstantin Sokolov
Martin Szulecki
Nikias Bassen


================================================
FILE: COPYING
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: COPYING.LESSER
================================================
		  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!


================================================
FILE: Makefile.am
================================================
AUTOMAKE_OPTIONS = foreign
ACLOCAL_AMFLAGS = -I m4
SUBDIRS = src include tools man

EXTRA_DIST = \
	README.md \
	git-version-gen

DISTCHECK_CONFIGURE_FLAGS =

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 dev/*.c


================================================
FILE: NEWS
================================================
Version 1.1.1
~~~~~~~~~~~~~

* Changes:
  - Ignore SIGPIPE signal
  - Add "--network" and "--version" options to ideviceactivation tool
  - Bump libimobiledevice dependency to 1.3.0
  - Bump libplist dependency to 2.2.0
  - Improve README.md with project description, installation, contributing and
    usage sections
  - Rename library and all related files by adding an API version resulting
    in "libideviceactivation-1.0"

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

* Changes:
  - Updated to use new mobileactivation service (requires latest libimobiledevice),
    introducing 'drmHandshake' / session mode for activating newer devices
  - Add API calls to query if an input field is secure and to get its placeholder (buddyml)
  - Mask input on console when querying secure input fields
  - Fix parsing of updated activation lock buddyml page
  - Add '-b' command line switch to run non-interactively
  - Remove length check on UDID argument to support newer devices
  - Set CURLOPT_FOLLOWLOCATION to handle 302 redirects from Apples activation server
  - Add new 'state' command to query device for activation state
  - Lots of other bug fixes

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

* Changes:
  - Add basic man page for ideviceactivation tool
  - Avoid exporting-non-public symbols
  - Add "--version" argument to print version number in ideviceactivation tool
  - Add "--service" argument to allow setting custom activaton service URL

Version 0.9.0
~~~~~~~~~~~~~

* Changes:
  - Refactor interface to allow handling forms
  - BuddyML and HTML parsing support
  - Minor fixes

Version 0.5.0
~~~~~~~~~~~~~

* Changes:
  - Add debug level setter to enable verbose curl debugging
  - Minor fixes

Version 0.1.0
~~~~~~~~~~~~~

* Changes:
  - Implement basic API to interact with activation webservice
  - Add basic ideviceactivation tool
  - Setup build system


================================================
FILE: README.md
================================================
# libideviceactivation

*A library to manage the activation process of Apple iOS devices.*

![](https://github.com/libimobiledevice/libideviceactivation/actions/workflows/build.yml/badge.svg)

## Features

This project provides an interface to activate and deactivate iOS devices by
talking to Apple's webservice alongside a command-line utility named
`ideviceactivation`.

Some key features are:

- **Status:** Implements complete activation and deactivation process
- **Compatibility**: Supports legacy and latest activation webservice APIs
- **Utility:** Provides `ideviceactivation` utility for command-line usage
- **Interactive:** Requests user input if the activation process uses forms
- **Cross-Platform:** Tested on Linux, macOS, Windows and Android platforms

## Installation / Getting started

### Debian / Ubuntu Linux

First install all required dependencies and build tools:
```shell
sudo apt-get install \
	build-essential \
	pkg-config \
	checkinstall \
	git \
	autoconf \
	automake \
	libtool-bin \
	libplist-dev \
	libimobiledevice-dev \
	libxml2-dev \
	libcurl4-openssl-dev \
	usbmuxd
```

Then clone the actual project repository:
```shell
git clone https://github.com/libimobiledevice/libideviceactivation.git
cd libideviceactivation
```

Now you can build and install it:
```shell
./autogen.sh
make
sudo make install
```

## Usage

To query the activation state of a device use:
```shell
ideviceactivation state
```

To activate a device use:
```shell
ideviceactivation activate
```

Please consult the usage information or manual page for a full documentation of
available command line options:
```shell
ideviceactivation --help
man ideviceactivation
```

## Contributing

We welcome contributions from anyone and are grateful for every pull request!

If you'd like to contribute, please fork the `master` branch, change, commit and
send a pull request for review. Once approved it can be merged into the main
code base.

If you plan to contribute larger changes or a major refactoring, please create a
ticket first to discuss the idea upfront to ensure less effort for everyone.

Please make sure your contribution adheres to:
* Try to follow the code style of the project
* Commit messages should describe the change well without being too short
* Try to split larger changes into individual commits of a common domain
* Use your real name and a valid email address for your commits

We are still working on the guidelines so bear with us!

## Links

* Homepage: https://libimobiledevice.org/
* Repository: https://github.com/libimobiledevice/libideviceactivation.git
* Repository (Mirror): https://git.libimobiledevice.org/libideviceactivation.git
* Issue Tracker: https://github.com/libimobiledevice/libideviceactivation/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.LESSER` file.

The `ideviceactivation` utility is licensed under the [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html),
also included in the repository in the `COPYING` file.

## Credits

Inspired by the activation utility from Joshua Hill aka p0sixninja:
https://github.com/posixninja/ideviceactivate/

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


================================================
FILE: 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


================================================
FILE: configure.ac
================================================
#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.

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

dnl Minimum package versions
LIBIMOBILEDEVICE_VERSION=1.3.0
LIBPLIST_VERSION=2.2.0
LIBCURL_VERSION=7.20
LIBXML2_VERSION=2.9

AC_SUBST(LIBIDEVICEACTIVATION_SO_VERSION)
AC_SUBST(LIBIMOBILEDEVICE_VERSION)
AC_SUBST(LIBPLIST_VERSION)
AC_SUBST(LIBCURL_VERSION)
AC_SUBST(LIBXML2_VERSION)

# Checks for programs.
AC_PROG_CC
#AC_PROG_CXX
AM_PROG_CC_C_O
LT_INIT

# Checks for libraries.
PKG_CHECK_MODULES(libimobiledevice, libimobiledevice-1.0 >= $LIBIMOBILEDEVICE_VERSION)
PKG_CHECK_MODULES(libplist, libplist-2.0 >= $LIBPLIST_VERSION)
PKG_CHECK_MODULES(libcurl, libcurl >= $LIBCURL_VERSION)
PKG_CHECK_MODULES(libxml2, libxml-2.0 >= $LIBXML2_VERSION)

# Checks for header files.
AC_CHECK_HEADERS([stdint.h stdlib.h string.h sys/socket.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([strcasecmp strdup strerror strndup])

# 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
    deplibs_check_method='pass_all'
    ;;
  darwin*|*android*)
    AC_MSG_RESULT([${host_os}])
    ;;
  *)
    AC_MSG_RESULT([${host_os}])
    ;;
esac
AM_CONDITIONAL(WIN32, test x$win32 = xtrue)

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+=" -DIDEVICE_ACTIVATION_STATIC"
fi

AC_SUBST(GLOBAL_CFLAGS)

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

AC_CONFIG_FILES([
Makefile
src/Makefile
src/libideviceactivation-1.0.pc
include/Makefile
tools/Makefile
man/Makefile
])
AC_OUTPUT

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

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

  Now type 'make' to build $PACKAGE $VERSION,
  and then 'make install' for installation.
"


================================================
FILE: 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"


================================================
FILE: include/Makefile.am
================================================
nobase_include_HEADERS = \
	libideviceactivation.h


================================================
FILE: include/libideviceactivation.h
================================================
/**
 * @file libideviceactivation.h
 * @brief Manage device activation process.
 *
 * Copyright (c) 2016-2019 Nikias Bassen, All Rights Reserved.
 * Copyright (c) 2014-2015 Martin Szulecki, All Rights Reserved.
 * Copyright (c) 2011-2014 Mirell Development, 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 LIBIDEVICEACTIVATION_H
#define LIBIDEVICEACTIVATION_H

#ifdef __cplusplus
extern "C" {
#endif

#include <libimobiledevice/lockdown.h>
#include <plist/plist.h>

#ifndef IDEVICE_ACTIVATION_API
  #ifdef IDEVICE_ACTIVATION_STATIC
    #define IDEVICE_ACTIVATION_API
  #elif defined(_WIN32)
    #define IDEVICE_ACTIVATION_API __declspec(dllimport)
  #else
    #define IDEVICE_ACTIVATION_API
  #endif
#endif

typedef enum {
	IDEVICE_ACTIVATION_E_SUCCESS                =  0,
	IDEVICE_ACTIVATION_E_INCOMPLETE_INFO        = -1,
	IDEVICE_ACTIVATION_E_OUT_OF_MEMORY          = -2,
	IDEVICE_ACTIVATION_E_UNKNOWN_CONTENT_TYPE   = -3,
	IDEVICE_ACTIVATION_E_BUDDYML_PARSING_ERROR  = -4,
	IDEVICE_ACTIVATION_E_PLIST_PARSING_ERROR    = -5,
	IDEVICE_ACTIVATION_E_HTML_PARSING_ERROR     = -6,
	IDEVICE_ACTIVATION_E_UNSUPPORTED_FIELD_TYPE = -7,
	IDEVICE_ACTIVATION_E_INTERNAL_ERROR         = -255
} idevice_activation_error_t;

typedef enum {
	IDEVICE_ACTIVATION_CLIENT_MOBILE_ACTIVATION,
	IDEVICE_ACTIVATION_CLIENT_ITUNES
} idevice_activation_client_type_t;

typedef struct idevice_activation_request_private idevice_activation_request;
typedef idevice_activation_request* idevice_activation_request_t;
typedef struct idevice_activation_response_private idevice_activation_response;
typedef idevice_activation_response* idevice_activation_response_t;

/* Interface */

IDEVICE_ACTIVATION_API void idevice_activation_set_debug_level(int level);

IDEVICE_ACTIVATION_API idevice_activation_error_t idevice_activation_request_new(idevice_activation_client_type_t activation_type, idevice_activation_request_t* request);
IDEVICE_ACTIVATION_API idevice_activation_error_t idevice_activation_request_new_from_lockdownd(idevice_activation_client_type_t activation_type, lockdownd_client_t lockdown, idevice_activation_request_t* request);
IDEVICE_ACTIVATION_API idevice_activation_error_t idevice_activation_drm_handshake_request_new(idevice_activation_client_type_t client_type, idevice_activation_request_t* request);
IDEVICE_ACTIVATION_API void idevice_activation_request_free(idevice_activation_request_t request);

IDEVICE_ACTIVATION_API void idevice_activation_request_get_fields(idevice_activation_request_t request, plist_t* fields);
IDEVICE_ACTIVATION_API void idevice_activation_request_set_fields(idevice_activation_request_t request, plist_t fields);
IDEVICE_ACTIVATION_API void idevice_activation_request_set_fields_from_response(idevice_activation_request_t request, const idevice_activation_response_t response);
IDEVICE_ACTIVATION_API void idevice_activation_request_set_field(idevice_activation_request_t request, const char* key, const char* value);
IDEVICE_ACTIVATION_API void idevice_activation_request_get_field(idevice_activation_request_t request, const char* key, char** value);

IDEVICE_ACTIVATION_API void idevice_activation_request_get_url(idevice_activation_request_t request, const char** url);
IDEVICE_ACTIVATION_API void idevice_activation_request_set_url(idevice_activation_request_t request, const char* url);

IDEVICE_ACTIVATION_API idevice_activation_error_t idevice_activation_response_new(idevice_activation_response_t* response);
IDEVICE_ACTIVATION_API idevice_activation_error_t idevice_activation_response_new_from_html(const char* content, idevice_activation_response_t* response);
IDEVICE_ACTIVATION_API idevice_activation_error_t idevice_activation_response_to_buffer(idevice_activation_response_t response, char** buffer, size_t* size);
IDEVICE_ACTIVATION_API void idevice_activation_response_free(idevice_activation_response_t response);

IDEVICE_ACTIVATION_API void idevice_activation_response_get_field(idevice_activation_response_t response, const char* key, char** value);
IDEVICE_ACTIVATION_API void idevice_activation_response_get_fields(idevice_activation_response_t response, plist_t* fields);
IDEVICE_ACTIVATION_API void idevice_activation_response_get_label(idevice_activation_response_t response, const char* key, char** value);
IDEVICE_ACTIVATION_API void idevice_activation_response_get_placeholder(idevice_activation_response_t response, const char* key, char **value);

IDEVICE_ACTIVATION_API void idevice_activation_response_get_title(idevice_activation_response_t response, const char** title);
IDEVICE_ACTIVATION_API void idevice_activation_response_get_description(idevice_activation_response_t response, const char** description);
IDEVICE_ACTIVATION_API void idevice_activation_response_get_activation_record(idevice_activation_response_t response, plist_t* activation_record);
IDEVICE_ACTIVATION_API void idevice_activation_response_get_headers(idevice_activation_response_t response, plist_t* headers);

IDEVICE_ACTIVATION_API int idevice_activation_response_is_activation_acknowledged(idevice_activation_response_t response);
IDEVICE_ACTIVATION_API int idevice_activation_response_is_authentication_required(idevice_activation_response_t response);
IDEVICE_ACTIVATION_API int idevice_activation_response_field_requires_input(idevice_activation_response_t response, const char* key);
IDEVICE_ACTIVATION_API int idevice_activation_response_field_secure_input(idevice_activation_response_t response, const char* key);
IDEVICE_ACTIVATION_API int idevice_activation_response_has_errors(idevice_activation_response_t response);

IDEVICE_ACTIVATION_API idevice_activation_error_t idevice_activation_send_request(idevice_activation_request_t request, idevice_activation_response_t* response);

#ifdef __cplusplus
}
#endif

#endif


================================================
FILE: man/Makefile.am
================================================
man_MANS = ideviceactivation.1
EXTRA_DIST = $(man_MANS)


================================================
FILE: man/ideviceactivation.1
================================================
.TH "ideviceactivation" 1
.SH NAME
ideviceactivation \- Activate or deactivate an iOS device.
.SH SYNOPSIS
.B ideviceactivation
activate [OPTIONS]

.B ideviceactivation
deactivate [OPTIONS]

.B ideviceactivation
state [OPTIONS]

.SH DESCRIPTION

Allows to activate and deactivate iOS devices by talking to Apple's webservice.

If the activation process uses forms, input will be requested from the user.

.SH COMMANDS
.TP
.B activate
Attempt to activate the device.
.TP
.B deactivate
Deactivates the device.
.TP
.B state
Query device for activation state.

.SH OPTIONS
.TP
.B \-d, \-\-debug
Enable communication debugging.
.TP
.B \-u, \-\-udid UDID
Target specific device by UDID.
.TP
.B \-n, \-\-network
Connect to network device.
.TP
.B \-b, \-\-batch
Explicitly run in non-interactive mode (default: auto-detect).
.TP
.B \-s, \-\-service URL
Use activation webservice at URL instead of default.
.TP
.B \-v, \-\-version
Print version information and exit.
.TP
.B \-h, \-\-help
Prints usage information.

.SH AUTHOR
Martin Szulecki

.SH ON THE WEB
http://www.libimobiledevice.org

https://github.com/libimobiledevice/libideviceactivation/


================================================
FILE: src/Makefile.am
================================================
AM_CPPFLAGS = \
	-I$(top_srcdir)/include

AM_CFLAGS = \
	$(GLOBAL_CFLAGS) \
	$(libimobiledevice_CFLAGS) \
	$(libplist_CFLAGS) \
	$(libcurl_CFLAGS) \
	$(libxml2_CFLAGS)

AM_LDFLAGS = \
	$(GLOBAL_LIBS) \
	$(libimobiledevice_LIBS) \
	$(libplist_LIBS) \
	$(libcurl_LIBS) \
	$(libxml2_LIBS)

lib_LTLIBRARIES = libideviceactivation-1.0.la
libideviceactivation_1_0_la_LDFLAGS = $(AM_LDFLAGS) -version-info $(LIBIDEVICEACTIVATION_SO_VERSION) -no-undefined
libideviceactivation_1_0_la_SOURCES = \
		activation.c

if WIN32
libideviceactivation_1_0_la_LDFLAGS += -avoid-version
endif

pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libideviceactivation-1.0.pc


================================================
FILE: src/activation.c
================================================
/**
 * @file activation.c
 *
 * Copyright (c) 2016-2019 Nikias Bassen, All Rights Reserved.
 * Copyright (c) 2014-2015 Martin Szulecki, All Rights Reserved.
 * Copyright (c) 2011-2014 Mirell Development, 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 <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/HTMLtree.h>
#include <curl/curl.h>

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

#ifdef _WIN32
#include <windows.h>
#define strncasecmp _strnicmp
#endif

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

#define IDEVICE_ACTIVATION_USER_AGENT_IOS "iOS Device Activator (MobileActivation-592.103.2)"
#define IDEVICE_ACTIVATION_USER_AGENT_ITUNES "iTunes/11.1.4 (Macintosh; OS X 10.9.1) AppleWebKit/537.73.11"
#define IDEVICE_ACTIVATION_DEFAULT_URL "https://albert.apple.com/deviceservices/deviceActivation"
#define IDEVICE_ACTIVATION_DRM_HANDSHAKE_DEFAULT_URL "https://albert.apple.com/deviceservices/drmHandshake"

typedef enum {
	IDEVICE_ACTIVATION_CONTENT_TYPE_URL_ENCODED,
	IDEVICE_ACTIVATION_CONTENT_TYPE_MULTIPART_FORMDATA,
	IDEVICE_ACTIVATION_CONTENT_TYPE_HTML,
	IDEVICE_ACTIVATION_CONTENT_TYPE_BUDDYML,
	IDEVICE_ACTIVATION_CONTENT_TYPE_PLIST,
	IDEVICE_ACTIVATION_CONTENT_TYPE_UNKNOWN
} idevice_activation_content_type_t;

struct idevice_activation_request_private {
	idevice_activation_client_type_t client_type;
	idevice_activation_content_type_t content_type;
	char* url;
	plist_t fields;
};

struct idevice_activation_response_private {
	char* raw_content;
	size_t raw_content_size;
	idevice_activation_content_type_t content_type;
	char* title;
	char* description;
	plist_t activation_record;
	plist_t headers;
	plist_t fields;
	plist_t fields_require_input;
	plist_t fields_secure_input;
	plist_t labels;
	plist_t labels_placeholder;
	int is_activation_ack;
	int is_auth_required;
	int has_errors;
};

static void internal_libideviceactivation_deinit(void)
{
	curl_global_cleanup();
}

INITIALIZER(internal_libideviceactivation_init)
{
	curl_global_init(CURL_GLOBAL_ALL);
	atexit(internal_libideviceactivation_deinit);
}

static int debug_level = 0;

void idevice_activation_set_debug_level(int level) {
	debug_level = level;
}

static idevice_activation_error_t idevice_activation_activation_record_from_plist(idevice_activation_response_t response, plist_t plist)
{
	plist_t record = plist_dict_get_item(plist, "ActivationRecord");
	if (record != NULL) {
		plist_t ack_received = plist_dict_get_item(record, "ack-received");
		if (ack_received) {
			uint8_t val = 0;
			plist_get_bool_val(ack_received, &val);
			if (val) {
				response->is_activation_ack = 1;
			}
		}
		response->activation_record = plist_new_data(response->raw_content, response->raw_content_size);
	} else {
		plist_t activation_node = plist_dict_get_item(plist, "iphone-activation");
		if (!activation_node) {
			activation_node = plist_dict_get_item(plist, "device-activation");
		}
		if (!activation_node) {
			return IDEVICE_ACTIVATION_E_PLIST_PARSING_ERROR;
		}
		plist_t ack_received = plist_dict_get_item(activation_node, "ack-received");
		if (ack_received) {
			uint8_t val = 0;
			plist_get_bool_val(ack_received, &val);
			if (val) {
				response->is_activation_ack = 1;
			}
		}
		record = plist_dict_get_item(activation_node, "activation-record");
		if (record) {
			response->activation_record = plist_copy(record);
		}
	}
	return IDEVICE_ACTIVATION_E_SUCCESS;
}

static void idevice_activation_response_add_field(idevice_activation_response_t response, const char* key, const char* value, int required_input, int secure_input)
{
	plist_dict_set_item(response->fields, key, plist_new_string(value));
	if (required_input) {
		plist_dict_set_item(response->fields_require_input, key, plist_new_bool(1));
	}
	if (secure_input) {
		plist_dict_set_item(response->fields_secure_input, key, plist_new_bool(1));
	}
}

static idevice_activation_error_t idevice_activation_parse_buddyml_response(idevice_activation_response_t response)
{
	idevice_activation_error_t result = IDEVICE_ACTIVATION_E_SUCCESS;
	xmlDocPtr doc = NULL;
	xmlXPathContextPtr context = NULL;
	xmlXPathObjectPtr xpath_result = NULL;
	int i = 0;

	if (response->content_type != IDEVICE_ACTIVATION_CONTENT_TYPE_BUDDYML)
		return IDEVICE_ACTIVATION_E_UNKNOWN_CONTENT_TYPE;

	doc = xmlReadMemory(response->raw_content, response->raw_content_size, "ideviceactivation.xml", NULL, XML_PARSE_NOERROR);
	if (!doc) {
		result = IDEVICE_ACTIVATION_E_BUDDYML_PARSING_ERROR;
		goto cleanup;
	}

	context = xmlXPathNewContext(doc);
	if (!context) {
		result = IDEVICE_ACTIVATION_E_BUDDYML_PARSING_ERROR;
		goto cleanup;
	}

	// check for an error
	// <navigationBar> appears directly under <xmlui> only in case of an error
	xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/navigationBar/@title", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval && xpath_result->nodesetval->nodeNr) {
		xmlChar* content =  xmlNodeListGetString(doc, xpath_result->nodesetval->nodeTab[0]->xmlChildrenNode, 1);
		if (content) {
			response->title = strdup((const char*) content);
			xmlFree(content);
		}

		response->has_errors = 1;
		goto cleanup;
	}

	// check for activation ack
	if (xpath_result) {
		xmlXPathFreeObject(xpath_result);
		xpath_result = NULL;
	}
	xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/clientInfo[@ack-received='true']", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval && xpath_result->nodesetval->nodeNr) {
		// existing activation_acknowledged
		response->is_activation_ack = 1;
		goto cleanup;
	}

	// retrieve response title
	if (xpath_result) {
		xmlXPathFreeObject(xpath_result);
		xpath_result = NULL;
	}
	xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/alert/@title", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval && xpath_result->nodesetval->nodeNr) {
		// incorrect credentials
		// <alert> exists only in case of incorrect credentials
		xmlChar* content =  xmlNodeListGetString(doc, xpath_result->nodesetval->nodeTab[0]->xmlChildrenNode, 1);
		if (content) {
			response->title = strdup((const char*) content);
			xmlFree(content);
		}
	} else {
		if (xpath_result) {
			xmlXPathFreeObject(xpath_result);
			xpath_result = NULL;
		}
		xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/page/navigationBar/@title", context);
		if (!xpath_result) {
			result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
			goto cleanup;
		}

		if (!xpath_result->nodesetval) {
			result =  IDEVICE_ACTIVATION_E_BUDDYML_PARSING_ERROR;
			goto cleanup;
		}
		xmlChar* content =  xmlNodeListGetString(doc, xpath_result->nodesetval->nodeTab[0]->xmlChildrenNode, 1);
		if (content) {
			response->title = strdup((const char*) content);
			xmlFree(content);
		}
	}

	// retrieve response description
	if (xpath_result) {
		xmlXPathFreeObject(xpath_result);
		xpath_result = NULL;
	}
	xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/page/tableView/section/footer[not (@url)]", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}
	if (!xpath_result->nodesetval) {
		xmlXPathFreeObject(xpath_result);
		xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/page/tableView/section[@footer and not(@footerLinkURL)]/@footer", context);
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval) {
		char* response_description = (char*) malloc(sizeof(char));
		response_description[0] = '\0';

		for(i = 0; i < xpath_result->nodesetval->nodeNr; i++) {
			xmlChar* content = xmlNodeListGetString(doc, xpath_result->nodesetval->nodeTab[i]->xmlChildrenNode, 1);
			if (content) {
				const size_t len = strlen(response_description);
				response_description = (char*) realloc(response_description, len + xmlStrlen(content) + 2);
				sprintf(&response_description[len], "%s\n", (const char*) content);
				xmlFree(content);
			}
		}

		if (strlen(response_description) > 0) {
			// remove the last '\n'
			response_description[strlen(response_description) - 1] = '\0';
			response->description = response_description;
		} else {
			free(response_description);
		}
	}

	// retrieve input fields
	if (xpath_result) {
		xmlXPathFreeObject(xpath_result);
		xpath_result = NULL;
	}

	xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/page//editableTextRow", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval) {
		for(i = 0; i < xpath_result->nodesetval->nodeNr; i++) {
			xmlChar* id = xmlGetProp(xpath_result->nodesetval->nodeTab[i], (const xmlChar*) "id");
			if (!id) {
				result = IDEVICE_ACTIVATION_E_BUDDYML_PARSING_ERROR;
				goto cleanup;
			}
			int secure_input = 0;
			xmlChar* secure = xmlGetProp(xpath_result->nodesetval->nodeTab[i], (const xmlChar*) "secure");
			if (secure) {
				if (!strcmp((const char*)secure, "true")) {
					secure_input = 1;
				}
				xmlFree(secure);
			}

			idevice_activation_response_add_field(response, (const char*) id, "", 1, secure_input);

			xmlChar* label = xmlGetProp(xpath_result->nodesetval->nodeTab[i], (const xmlChar*) "label");
			if (label) {
				plist_dict_set_item(response->labels, (const char*)id, plist_new_string((const char*) label));
				xmlFree(label);
			}
			xmlChar* placeholder = xmlGetProp(xpath_result->nodesetval->nodeTab[i], (const xmlChar*) "placeholder");
			if (placeholder) {
				plist_dict_set_item(response->labels_placeholder, (const char*)id, plist_new_string((const char*) placeholder));
				xmlFree(placeholder);
			}

			xmlFree(id);
		}
	}

	// retrieve server info fields
	if (xpath_result) {
		xmlXPathFreeObject(xpath_result);
		xpath_result = NULL;
	}

	xpath_result = xmlXPathEvalExpression((const xmlChar*) "/xmlui/serverInfo/@*", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval) {
		for(i = 0; i < xpath_result->nodesetval->nodeNr; i++) {
			xmlChar* content = xmlNodeGetContent(xpath_result->nodesetval->nodeTab[i]);
			if (content) {
				if (!xmlStrcmp(xpath_result->nodesetval->nodeTab[i]->name, (const xmlChar*) "isAuthRequired")) {
					response->is_auth_required = 1;
				}

				idevice_activation_response_add_field(response,
					(const char*) xpath_result->nodesetval->nodeTab[i]->name, (const char*) content, 0, 0);
				xmlFree(content);
			}
		}
	}

	if (plist_dict_get_size(response->fields) == 0) {
		response->has_errors = 1;
	}

cleanup:
	if (xpath_result)
		xmlXPathFreeObject(xpath_result);
	if (context)
		xmlXPathFreeContext(context);
	if (doc)
		xmlFreeDoc(doc);

	return result;
}

static idevice_activation_error_t idevice_activation_parse_html_response(idevice_activation_response_t response)
{
	idevice_activation_error_t result = IDEVICE_ACTIVATION_E_SUCCESS;
	xmlDocPtr doc = NULL;
	xmlXPathContextPtr context = NULL;
	xmlXPathObjectPtr xpath_result = NULL;

	if (response->content_type != IDEVICE_ACTIVATION_CONTENT_TYPE_HTML)
		return IDEVICE_ACTIVATION_E_UNKNOWN_CONTENT_TYPE;

	doc = xmlReadMemory(response->raw_content, response->raw_content_size, "ideviceactivation.xml", NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR);
	if (!doc) {
		result = IDEVICE_ACTIVATION_E_HTML_PARSING_ERROR;
		goto cleanup;
	}

	context = xmlXPathNewContext(doc);
	if (!context) {
		result = IDEVICE_ACTIVATION_E_HTML_PARSING_ERROR;
		goto cleanup;
	}

	// check for authentication required
	if (xpath_result) {
		xmlXPathFreeObject(xpath_result);
		xpath_result = NULL;
	}
	xpath_result = xmlXPathEvalExpression((const xmlChar*) "//input[@name='isAuthRequired' and @value='true']", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval && xpath_result->nodesetval->nodeNr) {
		response->is_auth_required = 1;
		goto cleanup;
	}

	// check for plist content
	xpath_result = xmlXPathEvalExpression((const xmlChar*) "//script[@type='text/x-apple-plist']/plist", context);
	if (!xpath_result) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	if (xpath_result->nodesetval && xpath_result->nodesetval->nodeNr) {
		plist_t plist = NULL;
		xmlBufferPtr plistNodeBuffer = xmlBufferCreate();
		if (htmlNodeDump(plistNodeBuffer, doc, xpath_result->nodesetval->nodeTab[0]) == -1) {
			result = IDEVICE_ACTIVATION_E_HTML_PARSING_ERROR;
			goto local_cleanup;
		}

		plist_from_xml((const char*) plistNodeBuffer->content, plistNodeBuffer->use, &plist);
		if (!plist) {
			result = IDEVICE_ACTIVATION_E_PLIST_PARSING_ERROR;
			goto local_cleanup;
		}
		result = idevice_activation_activation_record_from_plist(response, plist);
		plist_free(plist);

	local_cleanup:
		if (plistNodeBuffer)
			xmlBufferFree(plistNodeBuffer);
		goto cleanup;
	}

	response->has_errors = 1;

cleanup:
	if (xpath_result)
		xmlXPathFreeObject(xpath_result);
	if (context)
		xmlXPathFreeContext(context);
	if (doc)
		xmlFreeDoc(doc);

	return result;
}

static idevice_activation_error_t idevice_activation_parse_raw_response(idevice_activation_response_t response)
{
	switch(response->content_type)
	{
		case IDEVICE_ACTIVATION_CONTENT_TYPE_PLIST:
		{
			idevice_activation_error_t result = IDEVICE_ACTIVATION_E_SUCCESS;

			plist_t plist = NULL;
			plist_from_xml(response->raw_content, response->raw_content_size, &plist);

			if (plist == NULL) {
				return IDEVICE_ACTIVATION_E_PLIST_PARSING_ERROR;
			}

			/* check if this is a reply to drmHandshake request */
			if (plist_dict_get_item(plist, "HandshakeResponseMessage") != NULL) {
				result = IDEVICE_ACTIVATION_E_SUCCESS;
			} else {
				result = idevice_activation_activation_record_from_plist(response, plist);
			}

			plist_free(response->fields);
			response->fields = plist;

			return result;
		}
		case IDEVICE_ACTIVATION_CONTENT_TYPE_BUDDYML:
			return idevice_activation_parse_buddyml_response(response);
		case IDEVICE_ACTIVATION_CONTENT_TYPE_HTML:
			return idevice_activation_parse_html_response(response);
		default:
			return IDEVICE_ACTIVATION_E_UNKNOWN_CONTENT_TYPE;
	}

	return IDEVICE_ACTIVATION_E_SUCCESS;
}

static size_t idevice_activation_write_callback(char* data, size_t size, size_t nmemb, void* userdata)
{
	idevice_activation_response_t response = (idevice_activation_response_t)userdata;
	const size_t total = size * nmemb;

	if (total != 0) {
		response->raw_content = realloc(response->raw_content, response->raw_content_size + total + 1);
		memcpy(response->raw_content + response->raw_content_size, data, total);
		response->raw_content[response->raw_content_size + total] = '\0';
		response->raw_content_size += total;
	}

	return total;
}

static size_t idevice_activation_header_callback(void *data, size_t size, size_t nmemb, void *userdata)
{
	idevice_activation_response_t response = (idevice_activation_response_t)userdata;
	const size_t total = size * nmemb;
	if (total != 0) {
		char *header = malloc(total + 1);
		char *value = NULL;
		char *p = NULL;
		memcpy(header, data, total);
		header[total] = '\0';

		p = strchr(header, ':');
		if (p) {
			*p = '\0';
			p++;
			while (*p == ' ') {
				p++;
			}
			if (*p != '\0') {
				value = p;
				while (*p != '\0' && *p != '\n' && *p != '\r') {
					p++;
				}
				*p = '\0';
			}
		}
		if (value) {
			if (strncasecmp(header, "Content-Type", 12) == 0) {
				if (strncasecmp(value, "text/xml", 8) == 0) {
					response->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_PLIST;
				} else if (strncasecmp(value, "application/xml", 15) == 0) {
					response->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_PLIST;
				} else if (strncasecmp(value, "application/x-buddyml", 21) == 0) {
					response->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_BUDDYML;
				} else if (strncasecmp(value, "text/html", 9) == 0) {
					response->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_HTML;
				}
			}
			plist_dict_set_item(response->headers, header, plist_new_string(value));
		}
		free(header);
	}
	return total;
}

static char* urlencode(const char* buf)
{
	static const signed char conv_table[256] = {
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
		1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
		1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
	};

	unsigned int i;
	int count = 0;
	for (i = 0; i < strlen(buf); i++) {
		if (conv_table[(int)buf[i]]) {
			count++;
		}
	}
	int newsize = strlen(buf) + count*2 + 1;
	char* res = malloc(newsize);
	int o = 0;
	for (i = 0; i < strlen(buf); i++) {
		if (conv_table[(int)buf[i]]) {
			sprintf(&res[o], "%%%02X", (unsigned char)buf[i]);
			o+=3;
		} else {
			res[o] = buf[i];
			o++;
		}
	}
	res[o] = '\0';

	return res;
}

static int plist_strip_xml(char** xmlplist)
{
	if (!xmlplist || !*xmlplist)
		return -1;

	char* start = strstr(*xmlplist, "<plist version=\"1.0\">\n");
	if (!start)
		return -1;

	char* stop = strstr(*xmlplist, "\n</plist>");
	if (!stop)
		return -1;

	start += strlen("<plist version=\"1.0\">\n");
	uint32_t size = stop - start;
	char* stripped = malloc(size + 1);
	if (!stripped)
		return -1;

	memcpy(stripped, start, size);
	stripped[size] = '\0';
	free(*xmlplist);
	*xmlplist = stripped;

	return 0;
}

static int idevice_activation_curl_debug_callback(CURL *handle, curl_infotype type, char *data, size_t size, void *userptr)
{
	switch (type) {
	case CURLINFO_TEXT:
		fprintf(stderr, "* ");
		break;
	case CURLINFO_DATA_IN:
	case CURLINFO_HEADER_IN:
		fprintf(stderr, "< ");
		break;
	case CURLINFO_DATA_OUT:
	case CURLINFO_HEADER_OUT:
		fprintf(stderr, "> ");
		break;
	case CURLINFO_SSL_DATA_IN:
	case CURLINFO_SSL_DATA_OUT:
		return 0;
	default:
		return 0;
	}

	fwrite(data, 1, size, stderr);
	if (size > 0 && data[size-1] != '\n') {
		fprintf(stderr, "\n");
	}
	return 0;
}

idevice_activation_error_t idevice_activation_request_new(idevice_activation_client_type_t client_type, idevice_activation_request_t* request)
{
	if (!request)
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;

	idevice_activation_request_t tmp_request = (idevice_activation_request_t) malloc(sizeof(idevice_activation_request));

	if (!tmp_request) {
		return IDEVICE_ACTIVATION_E_OUT_OF_MEMORY;
	}

	tmp_request->client_type = client_type;
	tmp_request->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_URL_ENCODED;
	tmp_request->url = strdup(IDEVICE_ACTIVATION_DEFAULT_URL);
	tmp_request->fields = plist_new_dict();
	*request = tmp_request;

	return IDEVICE_ACTIVATION_E_SUCCESS;
}

idevice_activation_error_t idevice_activation_request_new_from_lockdownd(idevice_activation_client_type_t client_type, lockdownd_client_t lockdown, idevice_activation_request** request)
{
	if (!lockdown || !request) {
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
	}

	uint8_t has_telephony_capability = 0;
	uint8_t has_mobile_equipment_id = 0;
	lockdownd_error_t err;
	plist_t info = NULL;
	plist_t node = NULL;
	plist_t fields = plist_new_dict();

	// add InStoreActivation
	plist_dict_set_item(fields, "InStoreActivation", plist_new_string("false"));

	// get a bunch of information at once
	err = lockdownd_get_value(lockdown, NULL, NULL, &info);
	if (err != LOCKDOWN_E_SUCCESS) {
		if (debug_level > 0)
			fprintf(stderr, "%s: Unable to get basic information from lockdownd\n", __func__);
		plist_free(fields);
		return IDEVICE_ACTIVATION_E_INCOMPLETE_INFO;
	}

	// add AppleSerialNumber
	node = plist_dict_get_item(info, "SerialNumber");
	if (!node || plist_get_node_type(node) != PLIST_STRING) {
		if (debug_level > 0)
			fprintf(stderr, "%s: Unable to get SerialNumber from lockdownd\n", __func__);
		plist_free(fields);
		plist_free(info);
		return IDEVICE_ACTIVATION_E_INCOMPLETE_INFO;
	}
	plist_dict_set_item(fields, "AppleSerialNumber", plist_copy(node));
	node = NULL;


	// check if device has telephone capability
	node = plist_dict_get_item(info, "TelephonyCapability");
	if (!node || plist_get_node_type(node) != PLIST_BOOLEAN) {
		has_telephony_capability = 0;
	} else {
		plist_get_bool_val(node, &has_telephony_capability);
	}
	node = NULL;

	if (has_telephony_capability) {
		// add IMEI
		node = plist_dict_get_item(info, "InternationalMobileEquipmentIdentity");
		if (!node || plist_get_node_type(node) != PLIST_STRING) {
			has_mobile_equipment_id = 0;
		} else {
			plist_dict_set_item(fields, "IMEI", plist_copy(node));
			has_mobile_equipment_id = 1;
		}
		node = NULL;

		// add MEID
		node = plist_dict_get_item(info, "MobileEquipmentIdentifier");
		if (!node || plist_get_node_type(node) != PLIST_STRING) {
			if (debug_level > 0)
				fprintf(stderr, "%s: Unable to get MEID from lockdownd\n", __func__);
			if (!has_mobile_equipment_id) {
				plist_free(fields);
				plist_free(info);
				return IDEVICE_ACTIVATION_E_INCOMPLETE_INFO;
			}
		} else {
			plist_dict_set_item(fields, "MEID", plist_copy(node));
		}
		node = NULL;

		// add IMSI
		node = plist_dict_get_item(info, "InternationalMobileSubscriberIdentity");
		if (!node || plist_get_node_type(node) != PLIST_STRING) {
			if (debug_level > 0)
				fprintf(stderr, "%s: Unable to get IMSI from lockdownd\n", __func__);
		} else {
			plist_dict_set_item(fields, "IMSI", plist_copy(node));
		}
		node = NULL;

		// add ICCID
		node = plist_dict_get_item(info, "IntegratedCircuitCardIdentity");
		if (!node || plist_get_node_type(node) != PLIST_STRING) {
			if (debug_level > 0)
				fprintf(stderr, "%s: Unable to get ICCID from lockdownd\n", __func__);
		} else {
			plist_dict_set_item(fields, "ICCID", plist_copy(node));
		}
		node = NULL;
	}
	plist_free(info);
	info = NULL;

	// add activation-info
	err = lockdownd_get_value(lockdown, NULL, "ActivationInfo", &node);
	if (err != LOCKDOWN_E_SUCCESS || !node || plist_get_node_type(node) != PLIST_DICT) {
		fprintf(stderr, "%s: Unable to get ActivationInfo from lockdownd\n", __func__);
		plist_free(fields);
		return IDEVICE_ACTIVATION_E_INCOMPLETE_INFO;
	}
	plist_dict_set_item(fields, "activation-info", plist_copy(node));
	plist_free(node);
	node = NULL;

	idevice_activation_request* tmp_request = (idevice_activation_request*) malloc(sizeof(idevice_activation_request));

	if (!tmp_request) {
		plist_free(fields);
		return IDEVICE_ACTIVATION_E_OUT_OF_MEMORY;
	}

	tmp_request->client_type = client_type;
	tmp_request->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_MULTIPART_FORMDATA;
	tmp_request->url = strdup(IDEVICE_ACTIVATION_DEFAULT_URL);
	tmp_request->fields = fields;
	*request = tmp_request;

	return IDEVICE_ACTIVATION_E_SUCCESS;
}

idevice_activation_error_t idevice_activation_drm_handshake_request_new(idevice_activation_client_type_t client_type, idevice_activation_request_t* request)
{
	if (!request)
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;

	idevice_activation_request_t tmp_request = (idevice_activation_request_t) malloc(sizeof(idevice_activation_request));

	if (!tmp_request) {
		return IDEVICE_ACTIVATION_E_OUT_OF_MEMORY;
	}

	tmp_request->client_type = client_type;
	tmp_request->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_PLIST;
	tmp_request->url = strdup(IDEVICE_ACTIVATION_DRM_HANDSHAKE_DEFAULT_URL);
	tmp_request->fields = plist_new_dict();
	*request = tmp_request;

	return IDEVICE_ACTIVATION_E_SUCCESS;
}

void idevice_activation_request_free(idevice_activation_request_t request)
{
	if (!request)
		return;

	plist_free(request->fields);
	free(request);
}

void idevice_activation_request_get_fields(idevice_activation_request_t request, plist_t* fields)
{
	if (!request || !fields)
		return;

	*fields = plist_copy(request->fields);
}

void idevice_activation_request_set_fields(idevice_activation_request_t request, plist_t fields)
{
	if (!request || !fields)
		return;

	if (request->content_type == IDEVICE_ACTIVATION_CONTENT_TYPE_URL_ENCODED) {
		// if at least one of the new fields has a different type than string, we have to change the type
		plist_dict_iter iter = NULL;
		plist_dict_new_iter(fields, &iter);
		plist_t item = NULL;
		do {
			plist_dict_next_item(fields, iter, NULL, &item);
			if (item && plist_get_node_type(item) != PLIST_STRING) {
				request->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_MULTIPART_FORMDATA;
				break;
			}
		} while(item);
	}

	plist_dict_merge(&request->fields, fields);
}

void idevice_activation_request_set_fields_from_response(idevice_activation_request_t request, const idevice_activation_response_t response)
{
	if (!request || !response)
		return;

	plist_t response_fields = NULL;
	idevice_activation_response_get_fields(response, &response_fields);
	if (response_fields) {
		idevice_activation_request_set_fields(request, response_fields);
		free(response_fields);
	}
}

void idevice_activation_request_set_field(idevice_activation_request_t request, const char* key, const char* value)
{
	if (!request || !key || !value)
		return;

	plist_dict_set_item(request->fields, key, plist_new_string(value));
}

void idevice_activation_request_get_field(idevice_activation_request_t request, const char* key, char** value)
{
	if (!request || !key || !value)
		return;

	char* tmp_value = NULL;

	plist_t item = plist_dict_get_item(request->fields, key);

	if (item && plist_get_node_type(item) == PLIST_STRING) {
		plist_get_string_val(item, &tmp_value);
	} else {
		uint32_t data_size = 0;
		plist_to_xml(item, &tmp_value, &data_size);
		plist_strip_xml(&tmp_value);
	}

	*value = tmp_value;
}

void idevice_activation_request_get_url(idevice_activation_request_t request, const char** url)
{
	if (!request || !url)
		return;

	*url = request->url;
}

void idevice_activation_request_set_url(idevice_activation_request_t request, const char* url)
{
	if (!request || !url)
		return;

	free(request->url);
	request->url = strdup(url);
}

idevice_activation_error_t idevice_activation_response_new(idevice_activation_response_t* response)
{
	if (!response)
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;

	idevice_activation_response_t tmp_response = (idevice_activation_response_t) malloc(sizeof(idevice_activation_response));

	if (!tmp_response) {
		return IDEVICE_ACTIVATION_E_OUT_OF_MEMORY;
	}

	tmp_response->raw_content = NULL;
	tmp_response->raw_content_size = 0;
	tmp_response->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_UNKNOWN;
	tmp_response->title = NULL;
	tmp_response->description = NULL;
	tmp_response->activation_record = NULL;
	tmp_response->headers = plist_new_dict();
	tmp_response->fields = plist_new_dict();
	tmp_response->fields_require_input = plist_new_dict();
	tmp_response->fields_secure_input = plist_new_dict();
	tmp_response->labels = plist_new_dict();
	tmp_response->labels_placeholder = plist_new_dict();
	tmp_response->is_activation_ack = 0;
	tmp_response->is_auth_required = 0;
	tmp_response->has_errors = 0;
	*response = tmp_response;

	return IDEVICE_ACTIVATION_E_SUCCESS;
}

idevice_activation_error_t idevice_activation_response_new_from_html(const char* content, idevice_activation_response_t* response)
{
	if (!content || !response)
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;

	idevice_activation_response_t tmp_response = NULL;
	idevice_activation_error_t result = IDEVICE_ACTIVATION_E_SUCCESS;

	result = idevice_activation_response_new(&tmp_response);
	if (result != IDEVICE_ACTIVATION_E_SUCCESS) {
		return result;
	}

	const size_t tmp_size = strlen(content);
	char* tmp_content = (char*) malloc(sizeof(char) * tmp_size);

	if (!tmp_content) {
		idevice_activation_response_free(tmp_response);
		return IDEVICE_ACTIVATION_E_OUT_OF_MEMORY;
	}

	memcpy(tmp_content, content, tmp_size);

	tmp_response->raw_content = tmp_content;
	tmp_response->raw_content_size = tmp_size;
	tmp_response->content_type = IDEVICE_ACTIVATION_CONTENT_TYPE_HTML;

	result = idevice_activation_parse_html_response(tmp_response);
	if (result != IDEVICE_ACTIVATION_E_SUCCESS) {
		idevice_activation_response_free(tmp_response);
		return result;
	}

	*response = tmp_response;

	return result;
}

idevice_activation_error_t idevice_activation_response_to_buffer(idevice_activation_response_t response, char** buffer, size_t* size)
{
	if (!response || !buffer || !size)
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;

	char* tmp_buffer = (char*) malloc(sizeof(char) * response->raw_content_size);
	if (!tmp_buffer) {
		return IDEVICE_ACTIVATION_E_OUT_OF_MEMORY;
	}

	memcpy(tmp_buffer, response->raw_content, response->raw_content_size);

	*buffer = tmp_buffer;
	*size = response->raw_content_size;

	return IDEVICE_ACTIVATION_E_SUCCESS;
}

void idevice_activation_response_free(idevice_activation_response_t response)
{
	if (!response)
		return;

	free(response->raw_content);
	free(response->title);
	free(response->description);
	plist_free(response->activation_record);
	plist_free(response->headers);
	plist_free(response->fields);
	plist_free(response->fields_require_input);
	plist_free(response->fields_secure_input);
	plist_free(response->labels);
	plist_free(response->labels_placeholder);
	free(response);
}

void idevice_activation_response_get_field(idevice_activation_response_t response, const char* key, char** value)
{
	if (!response || !key || !value)
		return;

	*value = NULL;
	plist_t item = plist_dict_get_item(response->fields, key);

	if (item && plist_get_node_type(item) == PLIST_STRING) {
		plist_get_string_val(item, value);
	}
}

void idevice_activation_response_get_fields(idevice_activation_response_t response, plist_t* fields)
{
	if (response && response->fields && fields) {
		*fields = plist_copy(response->fields);
	}
}

void idevice_activation_response_get_label(idevice_activation_response_t response, const char* key, char** value)
{
	if (!response || !key || !value)
		return;

	*value = NULL;
	plist_t item = plist_dict_get_item(response->labels, key);
	if (item) {
		plist_get_string_val(item, value);
	}
}

void idevice_activation_response_get_placeholder(idevice_activation_response_t response, const char* key, char** value)
{
	if (!response || !key || !value)
		return;

	*value = NULL;
	plist_t item = plist_dict_get_item(response->labels_placeholder, key);
	if (item) {
		plist_get_string_val(item, value);
	}
}

void idevice_activation_response_get_title(idevice_activation_response_t response, const char** title)
{
	if (!response || !title)
		return;

	*title = response->title;
}

void idevice_activation_response_get_description(idevice_activation_response_t response, const char** description)
{
	if (!response || !description)
		return;

	*description = response->description;
}

void idevice_activation_response_get_activation_record(idevice_activation_response_t response, plist_t* activation_record)
{
	if (!response || !activation_record)
		return;

	if (response->activation_record) {
		*activation_record = plist_copy(response->activation_record);
	} else {
		*activation_record = NULL;
	}
}

void idevice_activation_response_get_headers(idevice_activation_response_t response, plist_t* headers)
{
	if (!response || !headers)
		return;

	*headers = plist_copy(response->headers);
}

int idevice_activation_response_is_activation_acknowledged(idevice_activation_response_t response)
{
	if (!response)
		return 0;

	return response->is_activation_ack;
}

int idevice_activation_response_is_authentication_required(idevice_activation_response_t response)
{
	if (!response)
		return 0;

	return response->is_auth_required;
}

int idevice_activation_response_field_requires_input(idevice_activation_response_t response, const char* key)
{
	if (!response || !key)
		return 0;

	return (plist_dict_get_item(response->fields_require_input, key) ? 1 : 0);
}

int idevice_activation_response_field_secure_input(idevice_activation_response_t response, const char* key)
{
	if (!response || !key)
		return 0;

	return (plist_dict_get_item(response->fields_secure_input, key) ? 1 : 0);
}

int idevice_activation_response_has_errors(idevice_activation_response_t response)
{
	if (!response)
		return 0;

	return response->has_errors;
}

idevice_activation_error_t idevice_activation_send_request(idevice_activation_request_t request, idevice_activation_response_t* response)
{
	idevice_activation_error_t result = IDEVICE_ACTIVATION_E_SUCCESS;

	// check arguments
	if (!request || !response) {
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
	}

	plist_dict_iter iter = NULL;
	plist_dict_new_iter(request->fields, &iter);
	if (!iter) {
		return IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
	}

	CURL* handle = curl_easy_init();
	struct curl_httppost* form = NULL;
	struct curl_slist* slist = NULL;

	if (!handle) {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	switch (request->client_type) {
		case IDEVICE_ACTIVATION_CLIENT_MOBILE_ACTIVATION:
			curl_easy_setopt(handle, CURLOPT_USERAGENT, IDEVICE_ACTIVATION_USER_AGENT_IOS);
			break;
		case IDEVICE_ACTIVATION_CLIENT_ITUNES:
			curl_easy_setopt(handle, CURLOPT_USERAGENT, IDEVICE_ACTIVATION_USER_AGENT_ITUNES);
			break;
		default:
			result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
			goto cleanup;
	}

	char* key = NULL;
	char* svalue = NULL;
	plist_t value_node = NULL;

	if (request->content_type == IDEVICE_ACTIVATION_CONTENT_TYPE_MULTIPART_FORMDATA) {
		struct curl_httppost* last = NULL;
		do {
			plist_dict_next_item(request->fields, iter, &key, &value_node);
			if (key != NULL) {
				if (value_node != NULL) {
					// serialize plist node as field value
					if (plist_get_node_type(value_node) == PLIST_STRING) {
						plist_get_string_val(value_node, &svalue);
					} else {
						uint32_t data_size = 0;
						plist_to_xml(value_node, &svalue, &data_size);
						plist_strip_xml(&svalue);
					}

					curl_formadd(&form, &last, CURLFORM_COPYNAME, key, CURLFORM_COPYCONTENTS, svalue, CURLFORM_END);

					free(svalue);
					svalue = NULL;
				}
			}
		} while(value_node != NULL);
		curl_easy_setopt(handle, CURLOPT_HTTPPOST, form);

	} else if (request->content_type == IDEVICE_ACTIVATION_CONTENT_TYPE_URL_ENCODED) {
		char* postdata = (char*) malloc(sizeof(char));
		postdata[0] = '\0';
		do {
			plist_dict_next_item(request->fields, iter, &key, &value_node);
			if (key != NULL) {
				if (value_node != NULL) {
					// serialize plist node as field value
					if (plist_get_node_type(value_node) == PLIST_STRING) {
						plist_get_string_val(value_node, &svalue);
					} else {
						// only strings supported
						free(postdata);
						result = IDEVICE_ACTIVATION_E_UNSUPPORTED_FIELD_TYPE;
						goto cleanup;
					}

					char* value_encoded = urlencode(svalue);
					if (value_encoded) {
						const size_t new_size = strlen(postdata) + strlen(key) + strlen(value_encoded) + 3;
						postdata = (char*) realloc(postdata, new_size);
						sprintf(&postdata[strlen(postdata)], "%s=%s&", key, value_encoded);
						free(value_encoded);
					}

					free(svalue);
					svalue = NULL;
				}
			}
		} while(value_node != NULL);

		// remove the last '&'
		const size_t postdata_len = strlen(postdata);
		if (postdata_len > 0)
			postdata[postdata_len - 1] = '\0';

		curl_easy_setopt(handle, CURLOPT_POST, 1);
		curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postdata);
		curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, strlen(postdata));
	} else if (request->content_type == IDEVICE_ACTIVATION_CONTENT_TYPE_PLIST) {
		char *postdata = NULL;
		uint32_t postdata_len = 0;
		plist_to_xml(request->fields, &postdata, &postdata_len);
		curl_easy_setopt(handle, CURLOPT_POST, 1);
		curl_easy_setopt(handle, CURLOPT_POSTFIELDS, postdata);
		curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, postdata_len);
		slist = curl_slist_append(NULL, "Content-Type: application/x-apple-plist");
		slist = curl_slist_append(slist, "Accept: application/xml");
		curl_easy_setopt(handle, CURLOPT_HTTPHEADER, slist);
	}
	else {
		result = IDEVICE_ACTIVATION_E_INTERNAL_ERROR;
		goto cleanup;
	}

	idevice_activation_response_t tmp_response = NULL;
	result = idevice_activation_response_new(&tmp_response);
	if (result != IDEVICE_ACTIVATION_E_SUCCESS) {
		goto cleanup;
	}

	curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, 0);
	curl_easy_setopt(handle, CURLOPT_WRITEDATA, tmp_response);
	curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &idevice_activation_write_callback);
	curl_easy_setopt(handle, CURLOPT_HEADERDATA, tmp_response);
	curl_easy_setopt(handle, CURLOPT_HEADERFUNCTION, &idevice_activation_header_callback);
	curl_easy_setopt(handle, CURLOPT_URL, request->url);
	curl_easy_setopt(handle, CURLOPT_FORBID_REUSE, 1);
	curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L);

	// enable communication debugging
	if (debug_level > 0) {
		curl_easy_setopt(handle, CURLOPT_VERBOSE, 1);
		curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, idevice_activation_curl_debug_callback);
	}

	curl_easy_perform(handle);

	result = idevice_activation_parse_raw_response(tmp_response);
	if (result != IDEVICE_ACTIVATION_E_SUCCESS) {
		goto cleanup;
	}

	*response = tmp_response;

	result = IDEVICE_ACTIVATION_E_SUCCESS;

cleanup:
	free(iter);
	if (form)
		curl_formfree(form);
	if (slist)
		curl_slist_free_all(slist);
	if (handle)
		curl_easy_cleanup(handle);

	return result;
}


================================================
FILE: src/libideviceactivation-1.0.pc.in
================================================
prefix=@prefix@
exec_prefix=@exec_prefix@
libdir=@libdir@
includedir=@includedir@

Name: @PACKAGE_NAME@
Description: A library to handle activation and deactivation of iOS devices.
Version: @PACKAGE_VERSION@
Libs: -L${libdir} -lideviceactivation-1.0
Cflags: -I${includedir}
Requires: libplist-2.0 >= @LIBPLIST_VERSION@ libimobiledevice-1.0 >= @LIBIMOBILEDEVICE_VERSION@
Requires.private: libcurl >= @LIBCURL_VERSION@ libxml-2.0 >= @LIBXML2_VERSION@


================================================
FILE: tools/Makefile.am
================================================
AM_CPPFLAGS = \
	-I$(top_srcdir)/include

AM_CFLAGS = \
	$(GLOBAL_CFLAGS) \
	$(libimobiledevice_CFLAGS) \
	$(libplist_CFLAGS)

AM_LDFLAGS = \
	$(GLOBAL_LIBS) \
	$(libimobiledevice_LIBS) \
	$(libplist_LIBS)

bin_PROGRAMS = ideviceactivation

ideviceactivation_SOURCES = ideviceactivation.c
ideviceactivation_CFLAGS = $(AM_CFLAGS)
ideviceactivation_LDFLAGS = $(AM_LDFLAGS)
ideviceactivation_LDADD = $(top_builddir)/src/libideviceactivation-1.0.la


================================================
FILE: tools/ideviceactivation.c
================================================
/*
 * ideviceactivation.c
 * A command line tool to handle the activation process
 *
 * Copyright (c) 2016-2019 Nikias Bassen, All Rights Reserved.
 * Copyright (c) 2014-2015 Martin Szulecki, All Rights Reserved.
 * Copyright (c) 2011-2015 Mirell Development, All Rights Reserved.
 *
 * 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, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#ifndef _WIN32
#include <signal.h>
#endif

#include <plist/plist.h>
#include <libimobiledevice/lockdown.h>
#include <libimobiledevice/libimobiledevice.h>
#include <libimobiledevice/mobileactivation.h>
#include <libideviceactivation.h>

#ifdef _WIN32
#include <windows.h>
#include <conio.h>
#else
#include <termios.h>
#endif

static void print_usage(int argc, char **argv)
{
	char *name = NULL;

	name = strrchr(argv[0], '/');
	printf("Usage: %s COMMAND [OPTIONS]\n", (name ? name + 1: argv[0]));
	printf("\n");
	printf("Activate or deactivate a device.\n");
	printf("\n");
	printf("Where COMMAND is one of:\n");
	printf("  activate\t\tattempt to activate the device\n");
	printf("  deactivate\t\tdeactivate the device\n");
	printf("  state\t\t\tquery device about its activation state\n");
	printf("  itunes\t\ttell the device that it has been connected to iTunes (useful for < iOS 4)\n");
	printf("\n");
	printf("The following OPTIONS are accepted:\n");
	printf("  -d, --debug\t\tenable communication debugging\n");
	printf("  -u, --udid UDID\ttarget specific device by UDID\n");
	printf("  -n, --network\t\tconnect to network device\n");
	printf("  -b, --batch\t\texplicitly run in non-interactive mode (default: auto-detect)\n");
	printf("  -s, --service URL\tuse activation webservice at URL instead of default\n");
	printf("  -v, --version\t\tprint version information and exit\n");
	printf("  -h, --help\t\tprints usage information\n");
	printf("\n");
	printf("Homepage:    <" PACKAGE_URL ">\n");
	printf("Bug Reports: <" PACKAGE_BUGREPORT ">\n");
}

#ifdef _WIN32
#define BS_CC '\b'
#define my_getch getch
#else
#define BS_CC 0x7f
static int my_getch(void)
{
	struct termios oldt, newt;
	int ch;
	tcgetattr(STDIN_FILENO, &oldt);
	newt = oldt;
	newt.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(STDIN_FILENO, TCSANOW, &newt);
	ch = getchar();
	tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
	return ch;
}
#endif

static void get_user_input(char *buf, int maxlen, int secure)
{
	int len = 0;
	int c;

	while ((c = my_getch())) {
		if ((c == '\r') || (c == '\n')) {
			break;
		} else if (isprint(c)) {
			if (len < maxlen-1)
				buf[len++] = c;
			fputc((secure) ? '*' : c, stdout);
		} else if (c == BS_CC) {
			if (len > 0) {
				fputs("\b \b", stdout);
				len--;
			}
		}
	}
	fputs("\n", stdout);
	buf[len] = 0;
}

int main(int argc, char *argv[])
{
	idevice_t device = NULL;
	idevice_error_t ret = IDEVICE_E_UNKNOWN_ERROR;
	lockdownd_client_t lockdown = NULL;
	mobileactivation_client_t ma = NULL;
	idevice_activation_request_t request = NULL;
	idevice_activation_response_t response = NULL;
	const char* response_title = NULL;
	const char* response_description = NULL;
	char* field_key = NULL;
	char* field_label = NULL;
	char input[1024];
	plist_t fields = NULL;
	plist_dict_iter iter = NULL;
	plist_t record = NULL;
	char *udid = NULL;
	char *signing_service_url = NULL;
	int use_mobileactivation = 0;
	int session_mode = 0;
	int i;
	int interactive = 1;
	int result = EXIT_FAILURE;
	int use_network = 0;

	typedef enum {
		OP_NONE = 0, OP_ACTIVATE, OP_DEACTIVATE, OP_GETSTATE, OP_ITUNES
	} op_t;
	op_t op = OP_NONE;

#ifndef _WIN32
	signal(SIGPIPE, SIG_IGN);
#endif
	/* parse cmdline args */
	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")) {
			idevice_set_debug_level(1);
			idevice_activation_set_debug_level(1);
			continue;
		}
		else if (!strcmp(argv[i], "-u") || !strcmp(argv[i], "--udid")) {
			i++;
			if (!argv[i] || !*argv[i]) {
				print_usage(argc, argv);
				return EXIT_FAILURE;
			}
			udid = argv[i];
			continue;
		}
		else if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "--network")) {
			use_network = 1;
			continue;
		}
		else if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--service")) {
			i++;
			if (!argv[i]) {
				print_usage(argc, argv);
				return EXIT_FAILURE;
			}
			signing_service_url = argv[i];
			continue;
		}
		else if (!strcmp(argv[i], "-b") || !strcmp(argv[i], "--batch")) {
			interactive = 0;
			continue;
		}
		else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
			print_usage(argc, argv);
			return EXIT_SUCCESS;
		}
		else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) {
			printf("ideviceactivation %s\n", PACKAGE_VERSION);
			return EXIT_SUCCESS;
		}
		else if (!strcmp(argv[i], "activate")) {
			op = OP_ACTIVATE;
			continue;
		}
		else if (!strcmp(argv[i], "deactivate")) {
			op = OP_DEACTIVATE;
			continue;
		}
		else if (!strcmp(argv[i], "state")) {
			op = OP_GETSTATE;
			continue;
		}
		else if (!strcmp(argv[i], "itunes")) {
			op = OP_ITUNES;
			continue;
		}
		else {
			print_usage(argc, argv);
			return EXIT_SUCCESS;
		}
	}

	if (interactive) {
		if (!isatty(fileno(stdin)) || !isatty(fileno(stdout))) {
			interactive = 0;
		}
	}

	if (op == OP_NONE) {
		print_usage(argc, argv);
		return EXIT_FAILURE;
	}

	ret = idevice_new_with_options(&device, udid, (use_network) ? IDEVICE_LOOKUP_NETWORK : IDEVICE_LOOKUP_USBMUX);
	if (ret != IDEVICE_E_SUCCESS) {
		if (udid) {
			printf("ERROR: Device %s not found!\n", udid);
		} else {
			printf("ERROR: No device found!\n");
		}
		return EXIT_FAILURE;
	}

	if (LOCKDOWN_E_SUCCESS != lockdownd_client_new_with_handshake(device, &lockdown, "ideviceactivation")) {
		fprintf(stderr, "Failed to connect to lockdownd\n");
		result = EXIT_FAILURE;
		goto cleanup;
	}

	plist_t p_version = NULL;
	uint32_t product_version = 0;
	if (lockdownd_get_value(lockdown, NULL, "ProductVersion", &p_version) == LOCKDOWN_E_SUCCESS) {
		int vers[3] = {0, 0, 0};
		char *s_version = NULL;
		plist_get_string_val(p_version, &s_version);
		if (s_version && sscanf(s_version, "%d.%d.%d", &vers[0], &vers[1], &vers[2]) >= 2) {
			product_version = ((vers[0] & 0xFF) << 16) | ((vers[1] & 0xFF) << 8) | (vers[2] & 0xFF);
		}
		free(s_version);
	}
	plist_free(p_version);

	if (op == OP_ACTIVATE && product_version >= 0x0A0200) {
		/* The activation server will not acknowledge the activation for iOS >= 10.2 anymore. Let's warn the user about this. */
		plist_t state = NULL;
		lockdownd_get_value(lockdown, NULL, "ActivationState", &state);
		if (state) {
			char *state_str = NULL;
			plist_get_string_val(state, &state_str);
			if (state_str && strcmp(state_str, "Unactivated") != 0) {
				printf("NOTE: This device appears to be already activated. The server might report an error 'Device Unknown' instead of acknowledging the activation.\n");
			}
			free(state_str);
			plist_free(state);
		}
	}

	// check if we should use the new mobileactivation service
	lockdownd_service_descriptor_t svc = NULL;
	if (lockdownd_start_service(lockdown, MOBILEACTIVATION_SERVICE_NAME, &svc) == LOCKDOWN_E_SUCCESS) {
		mobileactivation_error_t maerr = mobileactivation_client_new(device, svc, &ma);
		lockdownd_service_descriptor_free(svc);
		svc = NULL;
		if (maerr != MOBILEACTIVATION_E_SUCCESS) {
			fprintf(stderr, "Failed to connect to %s\n", MOBILEACTIVATION_SERVICE_NAME);
			result = EXIT_FAILURE;
			goto cleanup;
		}
		use_mobileactivation = 1;
	}

	switch (op) {
		case OP_DEACTIVATE:
			if (use_mobileactivation) {
				// deactivate device using mobileactivation
				if (MOBILEACTIVATION_E_SUCCESS != mobileactivation_deactivate(ma)) {
					fprintf(stderr, "Failed to deactivate device.\n");
					result = EXIT_FAILURE;
					goto cleanup;
				}
				mobileactivation_client_free(ma);
				ma = NULL;
			} else {
				// deactivate device using lockdown
				if (LOCKDOWN_E_SUCCESS != lockdownd_deactivate(lockdown)) {
					fprintf(stderr, "Failed to deactivate device.\n");
					result = EXIT_FAILURE;
					goto cleanup;
				}
			}

			result = EXIT_SUCCESS;
			printf("Successfully deactivated device.\n");
			break;
		case OP_ACTIVATE:
		default:
			if (use_mobileactivation) {
				// create activation request from mobileactivation
				plist_t ainfo = NULL;
				if ((product_version >= 0x0A0000) || (mobileactivation_create_activation_info(ma, &ainfo) != MOBILEACTIVATION_E_SUCCESS)) {
					session_mode = 1;
				}
				mobileactivation_client_free(ma);
				ma = NULL;
				if (session_mode) {
					/* first grab session blob from device required for drmHandshake */
					plist_t blob = NULL;
					if (mobileactivation_client_start_service(device, &ma, "ideviceactivation") != MOBILEACTIVATION_E_SUCCESS) {
						fprintf(stderr, "Failed to connect to %s\n", MOBILEACTIVATION_SERVICE_NAME);
						result = EXIT_FAILURE;
						goto cleanup;
					}
					if (mobileactivation_create_activation_session_info(ma, &blob) != MOBILEACTIVATION_E_SUCCESS) {
						fprintf(stderr, "Failed to get ActivationSessionInfo from mobileactivation\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}
					mobileactivation_client_free(ma);
					ma = NULL;

					/* create drmHandshake request with blob from device */
					if (idevice_activation_drm_handshake_request_new(IDEVICE_ACTIVATION_CLIENT_MOBILE_ACTIVATION, &request) != IDEVICE_ACTIVATION_E_SUCCESS) {
						fprintf(stderr, "Failed to create drmHandshake request.\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}
					idevice_activation_request_set_fields(request, blob);
					plist_free(blob);

					if (signing_service_url) {
						idevice_activation_request_set_url(request, signing_service_url);
					}

					/* send request to server and get response */
					if (idevice_activation_send_request(request, &response) != IDEVICE_ACTIVATION_E_SUCCESS) {
						fprintf(stderr, "Failed to get drmHandshake result from activation server.\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}
					plist_t handshake_response = NULL;
					idevice_activation_response_get_fields(response, &handshake_response);
					idevice_activation_response_free(response);
					response = NULL;

					/* use handshake response to get activation info from device */
					if (mobileactivation_client_start_service(device, &ma, "ideviceactivation") != MOBILEACTIVATION_E_SUCCESS) {
						fprintf(stderr, "Failed to connect to %s\n", MOBILEACTIVATION_SERVICE_NAME);
						result = EXIT_FAILURE;
						goto cleanup;
					}
					if ((mobileactivation_create_activation_info_with_session(ma, handshake_response, &ainfo) != MOBILEACTIVATION_E_SUCCESS) || !ainfo || (plist_get_node_type(ainfo) != PLIST_DICT)) {
						fprintf(stderr, "Failed to get ActivationInfo from mobileactivation\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}
					mobileactivation_client_free(ma);
					ma = NULL;
				} else if (!ainfo || plist_get_node_type(ainfo) != PLIST_DICT) {
					fprintf(stderr, "Failed to get ActivationInfo from mobileactivation\n");
					result = EXIT_FAILURE;
					goto cleanup;
				}

				/* create activation request */
				if (idevice_activation_request_new(IDEVICE_ACTIVATION_CLIENT_MOBILE_ACTIVATION, &request) != IDEVICE_ACTIVATION_E_SUCCESS) {
					fprintf(stderr, "Failed to create activation request.\n");
					result = EXIT_FAILURE;
					goto cleanup;
				}

				/* add activation info to request */
				plist_t request_fields = plist_new_dict();
				plist_dict_set_item(request_fields, "activation-info", ainfo);
				idevice_activation_request_set_fields(request, request_fields);
			} else {
				// create activation request from lockdown
				if (idevice_activation_request_new_from_lockdownd(
					IDEVICE_ACTIVATION_CLIENT_MOBILE_ACTIVATION, lockdown, &request) != IDEVICE_ACTIVATION_E_SUCCESS) {
					fprintf(stderr, "Failed to create activation request.\n");
					result = EXIT_FAILURE;
					goto cleanup;
				}
			}
			lockdownd_client_free(lockdown);
			lockdown = NULL;

			if (request && signing_service_url) {
				idevice_activation_request_set_url(request, signing_service_url);
			}

			while(1) {
				if (idevice_activation_send_request(request, &response) != IDEVICE_ACTIVATION_E_SUCCESS) {
					fprintf(stderr, "Failed to send request or retrieve response.\n");
					// Here response might have some content that could't be correctly interpreted (parsed)
					// by the library. Printing out the content could help to identify the cause of the error.
					result = EXIT_FAILURE;
					goto cleanup;
				}

				if (idevice_activation_response_has_errors(response)) {
					fprintf(stderr, "Activation server reports errors.\n");

					idevice_activation_response_get_title(response, &response_title);
					if (response_title) {
						fprintf(stderr, "\t%s\n", response_title);
					}

					idevice_activation_response_get_description(response, &response_description);
					if (response_description) {
						fprintf(stderr, "\t%s\n", response_description);
					}
					result = EXIT_FAILURE;
					goto cleanup;
				}

				idevice_activation_response_get_activation_record(response, &record);

				if (record) {
					if (LOCKDOWN_E_SUCCESS != lockdownd_client_new_with_handshake(device, &lockdown, "ideviceactivation")) {
						fprintf(stderr, "Failed to connect to lockdownd\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}
					if (use_mobileactivation) {
						svc = NULL;
						if (lockdownd_start_service(lockdown, MOBILEACTIVATION_SERVICE_NAME, &svc) != LOCKDOWN_E_SUCCESS) {
							fprintf(stderr, "Failed to start service %s\n", MOBILEACTIVATION_SERVICE_NAME);
							result = EXIT_FAILURE;
							goto cleanup;
						}
						mobileactivation_error_t maerr = mobileactivation_client_new(device, svc, &ma);
						lockdownd_service_descriptor_free(svc);
						svc = NULL;
						if (maerr != MOBILEACTIVATION_E_SUCCESS) {
							fprintf(stderr, "Failed to connect to %s\n", MOBILEACTIVATION_SERVICE_NAME);
							result = EXIT_FAILURE;
							goto cleanup;
						}

						if (session_mode) {
							plist_t headers = NULL;
							idevice_activation_response_get_headers(response, &headers);
							if (MOBILEACTIVATION_E_SUCCESS != mobileactivation_activate_with_session(ma, record, headers)) {
								plist_free(headers);
								fprintf(stderr, "Failed to activate device with record.\n");
								result = EXIT_FAILURE;
								goto cleanup;
							}
							plist_free(headers);
						} else {
							if (MOBILEACTIVATION_E_SUCCESS != mobileactivation_activate(ma, record)) {
								fprintf(stderr, "Failed to activate device with record.\n");
								result = EXIT_FAILURE;
								goto cleanup;
							}
						}
					} else {
						// activate device using lockdown
						if (LOCKDOWN_E_SUCCESS != lockdownd_activate(lockdown, record)) {
							plist_t state = NULL;
							lockdownd_get_value(lockdown, NULL, "ActivationState", &state);
							int success = 0;
							if (state && plist_get_node_type(state) == PLIST_STRING) {
								char *strval = NULL;
								plist_get_string_val(state, &strval);
								if (strval && strcmp(strval, "Unactivated")) {
									success = 1;
								}
								free(strval);
							}
							if (!success) {
								fprintf(stderr, "Failed to activate device with record.\n");
								result = EXIT_FAILURE;
								goto cleanup;
							}
						}
					}

					// set ActivationStateAcknowledged if we succeeded
					if (LOCKDOWN_E_SUCCESS != lockdownd_set_value(lockdown, NULL, "ActivationStateAcknowledged", plist_new_bool(1))) {
						fprintf(stderr, "Failed to set ActivationStateAcknowledged on device.\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}
					break;
				} else {
					if (idevice_activation_response_is_activation_acknowledged(response)) {
						printf("Activation server reports that device is already activated.\n");
						result = EXIT_SUCCESS;
						goto cleanup;
					}

					idevice_activation_response_get_title(response, &response_title);
					if (response_title) {
						fprintf(stderr, "Server reports:\n%s\n", response_title);
					}

					idevice_activation_response_get_description(response, &response_description);
					if (response_description) {
						fprintf(stderr, "Server reports:\n%s\n", response_description);
					}

					idevice_activation_response_get_fields(response, &fields);
					if (!fields || plist_dict_get_size(fields) == 0) {
						// we have no activation record, no reported erros, no acknowledgment and no fields to send
						fprintf(stderr, "Unknown error.\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}

					plist_dict_new_iter(fields, &iter);
					if (!iter) {
						fprintf(stderr, "Unknown error.\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}

					idevice_activation_request_free(request);
					request = NULL;
					if (idevice_activation_request_new(
						IDEVICE_ACTIVATION_CLIENT_MOBILE_ACTIVATION, &request) != IDEVICE_ACTIVATION_E_SUCCESS) {
						fprintf(stderr, "Could not create new request.\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}

					idevice_activation_request_set_fields_from_response(request, response);

					int interactive_count = 0;
					do {
						field_key = NULL;
						plist_dict_next_item(fields, iter, &field_key, NULL);
						if (field_key) {
							if (idevice_activation_response_field_requires_input(response, field_key)) {
								idevice_activation_response_get_label(response, field_key, &field_label);
								if (interactive) {
									char *field_placeholder = NULL;
									int secure = idevice_activation_response_field_secure_input(response, field_key);
									idevice_activation_response_get_placeholder(response, field_key, &field_placeholder);
									printf("input %s", field_label ? field_label : field_key);
									if (field_placeholder) {
										printf(" (%s)", field_placeholder);
										free(field_placeholder);
									}
									printf(": ");
									fflush(stdout);
									fflush(stdin);
									get_user_input(input, 1023, secure);
								} else {
									fprintf(stderr, "Server requires input for '%s' but we're not running interactively.\n", field_label ? field_label : field_key);
									strcpy(input, "");
									interactive_count++;
								}
								idevice_activation_request_set_field(request, field_key, input);
								if (field_label) {
									free(field_label);
									field_label = NULL;
								}
							}
						}
					} while(field_key);

					free(iter);
					iter = NULL;
					idevice_activation_response_free(response);
					response = NULL;

					if (interactive_count > 0 && !interactive) {
						fprintf(stderr, "Failed to activate device.\n");
						result = EXIT_FAILURE;
						goto cleanup;
					}
				}

			}

			result = EXIT_SUCCESS;
			printf("Successfully activated device.\n");
			break;
		case OP_GETSTATE: {
			plist_t state = NULL;
			if (use_mobileactivation) {
				mobileactivation_get_activation_state(ma, &state);
			} else {
				lockdownd_get_value(lockdown, NULL, "ActivationState", &state);
			}
			if (plist_get_node_type(state) == PLIST_STRING) {
				char *s_state = NULL;
				plist_get_string_val(state, &s_state);
				printf("ActivationState: %s\n", s_state);
				free(s_state);
			} else {
				printf("Error getting activation state.\n");
			}
			}
			break;

		case OP_ITUNES: {
			// set iTunesHasConnected if we succeeded
			if (LOCKDOWN_E_SUCCESS != lockdownd_set_value(lockdown, NULL, "iTunesHasConnected", plist_new_bool(1))) {
				fprintf(stderr, "Failed to set iTunesHasConnected on device.\n");
				result = EXIT_FAILURE;
				goto cleanup;
			}
			result = EXIT_SUCCESS;
			printf("Successfully set 'iTunesHasConnected'.\n");
			}
			break;
	}

cleanup:
	if (request)
		idevice_activation_request_free(request);

	if (response)
		idevice_activation_response_free(response);

	if (fields)
		plist_free(fields);

	if (field_label)
		free(field_label);

	if (iter)
		free(iter);

	if (record)
		plist_free(record);

	if (ma)
		mobileactivation_client_free(ma);

	if (lockdown)
		lockdownd_client_free(lockdown);

	if (device)
		idevice_free(device);

	return result;
}
Download .txt
gitextract_4pdngyja/

├── .github/
│   ├── FUNDING.yml
│   └── workflows/
│       └── build.yml
├── .gitignore
├── AUTHORS
├── COPYING
├── COPYING.LESSER
├── Makefile.am
├── NEWS
├── README.md
├── autogen.sh
├── configure.ac
├── git-version-gen
├── include/
│   ├── Makefile.am
│   └── libideviceactivation.h
├── man/
│   ├── Makefile.am
│   └── ideviceactivation.1
├── src/
│   ├── Makefile.am
│   ├── activation.c
│   └── libideviceactivation-1.0.pc.in
└── tools/
    ├── Makefile.am
    └── ideviceactivation.c
Download .txt
SYMBOL INDEX (54 symbols across 3 files)

FILE: include/libideviceactivation.h
  type idevice_activation_error_t (line 44) | typedef enum {
  type idevice_activation_client_type_t (line 56) | typedef enum {
  type idevice_activation_request (line 61) | typedef struct idevice_activation_request_private idevice_activation_req...
  type idevice_activation_request (line 62) | typedef idevice_activation_request* idevice_activation_request_t;
  type idevice_activation_response (line 63) | typedef struct idevice_activation_response_private idevice_activation_re...
  type idevice_activation_response (line 64) | typedef idevice_activation_response* idevice_activation_response_t;

FILE: src/activation.c
  type idevice_activation_content_type_t (line 86) | typedef enum {
  type idevice_activation_request_private (line 95) | struct idevice_activation_request_private {
  type idevice_activation_response_private (line 102) | struct idevice_activation_response_private {
  function internal_libideviceactivation_deinit (line 120) | static void internal_libideviceactivation_deinit(void)
  function INITIALIZER (line 125) | INITIALIZER(internal_libideviceactivation_init)
  function idevice_activation_set_debug_level (line 133) | void idevice_activation_set_debug_level(int level) {
  function idevice_activation_error_t (line 137) | static idevice_activation_error_t idevice_activation_activation_record_f...
  function idevice_activation_response_add_field (line 174) | static void idevice_activation_response_add_field(idevice_activation_res...
  function idevice_activation_error_t (line 185) | static idevice_activation_error_t idevice_activation_parse_buddyml_respo...
  function idevice_activation_error_t (line 412) | static idevice_activation_error_t idevice_activation_parse_html_response...
  function idevice_activation_error_t (line 492) | static idevice_activation_error_t idevice_activation_parse_raw_response(...
  function idevice_activation_write_callback (line 530) | static size_t idevice_activation_write_callback(char* data, size_t size,...
  function idevice_activation_header_callback (line 545) | static size_t idevice_activation_header_callback(void *data, size_t size...
  function plist_strip_xml (line 635) | static int plist_strip_xml(char** xmlplist)
  function idevice_activation_curl_debug_callback (line 662) | static int idevice_activation_curl_debug_callback(CURL *handle, curl_inf...
  function idevice_activation_error_t (line 690) | idevice_activation_error_t idevice_activation_request_new(idevice_activa...
  function idevice_activation_error_t (line 710) | idevice_activation_error_t idevice_activation_request_new_from_lockdownd...
  function idevice_activation_error_t (line 833) | idevice_activation_error_t idevice_activation_drm_handshake_request_new(...
  function idevice_activation_request_free (line 853) | void idevice_activation_request_free(idevice_activation_request_t request)
  function idevice_activation_request_get_fields (line 862) | void idevice_activation_request_get_fields(idevice_activation_request_t ...
  function idevice_activation_request_set_fields (line 870) | void idevice_activation_request_set_fields(idevice_activation_request_t ...
  function idevice_activation_request_set_fields_from_response (line 892) | void idevice_activation_request_set_fields_from_response(idevice_activat...
  function idevice_activation_request_set_field (line 905) | void idevice_activation_request_set_field(idevice_activation_request_t r...
  function idevice_activation_request_get_field (line 913) | void idevice_activation_request_get_field(idevice_activation_request_t r...
  function idevice_activation_request_get_url (line 933) | void idevice_activation_request_get_url(idevice_activation_request_t req...
  function idevice_activation_request_set_url (line 941) | void idevice_activation_request_set_url(idevice_activation_request_t req...
  function idevice_activation_error_t (line 950) | idevice_activation_error_t idevice_activation_response_new(idevice_activ...
  function idevice_activation_error_t (line 981) | idevice_activation_error_t idevice_activation_response_new_from_html(con...
  function idevice_activation_error_t (line 1019) | idevice_activation_error_t idevice_activation_response_to_buffer(idevice...
  function idevice_activation_response_free (line 1037) | void idevice_activation_response_free(idevice_activation_response_t resp...
  function idevice_activation_response_get_field (line 1055) | void idevice_activation_response_get_field(idevice_activation_response_t...
  function idevice_activation_response_get_fields (line 1068) | void idevice_activation_response_get_fields(idevice_activation_response_...
  function idevice_activation_response_get_label (line 1075) | void idevice_activation_response_get_label(idevice_activation_response_t...
  function idevice_activation_response_get_placeholder (line 1087) | void idevice_activation_response_get_placeholder(idevice_activation_resp...
  function idevice_activation_response_get_title (line 1099) | void idevice_activation_response_get_title(idevice_activation_response_t...
  function idevice_activation_response_get_description (line 1107) | void idevice_activation_response_get_description(idevice_activation_resp...
  function idevice_activation_response_get_activation_record (line 1115) | void idevice_activation_response_get_activation_record(idevice_activatio...
  function idevice_activation_response_get_headers (line 1127) | void idevice_activation_response_get_headers(idevice_activation_response...
  function idevice_activation_response_is_activation_acknowledged (line 1135) | int idevice_activation_response_is_activation_acknowledged(idevice_activ...
  function idevice_activation_response_is_authentication_required (line 1143) | int idevice_activation_response_is_authentication_required(idevice_activ...
  function idevice_activation_response_field_requires_input (line 1151) | int idevice_activation_response_field_requires_input(idevice_activation_...
  function idevice_activation_response_field_secure_input (line 1159) | int idevice_activation_response_field_secure_input(idevice_activation_re...
  function idevice_activation_response_has_errors (line 1167) | int idevice_activation_response_has_errors(idevice_activation_response_t...
  function idevice_activation_error_t (line 1175) | idevice_activation_error_t idevice_activation_send_request(idevice_activ...

FILE: tools/ideviceactivation.c
  function print_usage (line 50) | static void print_usage(int argc, char **argv)
  function my_getch (line 83) | static int my_getch(void)
  function get_user_input (line 97) | static void get_user_input(char *buf, int maxlen, int secure)
  function main (line 120) | int main(int argc, char *argv[])
Condensed preview — 21 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (160K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 78,
    "preview": "github: nikias\npatreon: nikias\ncustom: [\"https://www.paypal.me/NikiasBassen\"]\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "chars": 9110,
    "preview": "name: build\n\non:\n  push:\n  pull_request:\n  schedule:\n    - cron: '0 0 1 * *'\n\njobs:\n  build-linux-ubuntu:\n    runs-on: u"
  },
  {
    "path": ".gitignore",
    "chars": 316,
    "preview": "*.[oa]\n*~\n*.po\n*.lo\n*.la\n.*.swp\n*/.deps/*\n*.patch\nMakefile\nMakefile.in\naclocal.m4\nautom4te.cache\ncompile\nconfig.guess\nco"
  },
  {
    "path": "AUTHORS",
    "chars": 49,
    "preview": "Konstantin Sokolov\nMartin Szulecki\nNikias Bassen\n"
  },
  {
    "path": "COPYING",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "COPYING.LESSER",
    "chars": 26434,
    "preview": "\t\t  GNU LESSER GENERAL PUBLIC LICENSE\n\t\t       Version 2.1, February 1999\n\n Copyright (C) 1991, 1999 Free Software Found"
  },
  {
    "path": "Makefile.am",
    "chars": 369,
    "preview": "AUTOMAKE_OPTIONS = foreign\nACLOCAL_AMFLAGS = -I m4\nSUBDIRS = src include tools man\n\nEXTRA_DIST = \\\n\tREADME.md \\\n\tgit-ver"
  },
  {
    "path": "NEWS",
    "chars": 1844,
    "preview": "Version 1.1.1\n~~~~~~~~~~~~~\n\n* Changes:\n  - Ignore SIGPIPE signal\n  - Add \"--network\" and \"--version\" options to idevice"
  },
  {
    "path": "README.md",
    "chars": 3701,
    "preview": "# libideviceactivation\n\n*A library to manage the activation process of Apple iOS devices.*\n\n![](https://github.com/libim"
  },
  {
    "path": "autogen.sh",
    "chars": 365,
    "preview": "#!/bin/sh\n\nolddir=`pwd`\nsrcdir=`dirname $0`\ntest -z \"$srcdir\" && srcdir=.\n\n(\n  cd \"$srcdir\"\n\n  gprefix=`which glibtooliz"
  },
  {
    "path": "configure.ac",
    "chars": 2934,
    "preview": "#                                               -*- Autoconf -*-\n# Process this file with autoconf to produce a configur"
  },
  {
    "path": "git-version-gen",
    "chars": 579,
    "preview": "#!/bin/sh\nSRCDIR=`dirname $0`\nif test -n \"$1\"; then\n  VER=$1\nelse\n  if test -r \"${SRCDIR}/.git\" && test -x \"`which git`\""
  },
  {
    "path": "include/Makefile.am",
    "chars": 51,
    "preview": "nobase_include_HEADERS = \\\n\tlibideviceactivation.h\n"
  },
  {
    "path": "include/libideviceactivation.h",
    "chars": 6499,
    "preview": "/**\n * @file libideviceactivation.h\n * @brief Manage device activation process.\n *\n * Copyright (c) 2016-2019 Nikias Bas"
  },
  {
    "path": "man/Makefile.am",
    "chars": 56,
    "preview": "man_MANS = ideviceactivation.1\nEXTRA_DIST = $(man_MANS)\n"
  },
  {
    "path": "man/ideviceactivation.1",
    "chars": 1140,
    "preview": ".TH \"ideviceactivation\" 1\n.SH NAME\nideviceactivation \\- Activate or deactivate an iOS device.\n.SH SYNOPSIS\n.B ideviceact"
  },
  {
    "path": "src/Makefile.am",
    "chars": 654,
    "preview": "AM_CPPFLAGS = \\\n\t-I$(top_srcdir)/include\n\nAM_CFLAGS = \\\n\t$(GLOBAL_CFLAGS) \\\n\t$(libimobiledevice_CFLAGS) \\\n\t$(libplist_CF"
  },
  {
    "path": "src/activation.c",
    "chars": 39639,
    "preview": "/**\n * @file activation.c\n *\n * Copyright (c) 2016-2019 Nikias Bassen, All Rights Reserved.\n * Copyright (c) 2014-2015 M"
  },
  {
    "path": "src/libideviceactivation-1.0.pc.in",
    "chars": 449,
    "preview": "prefix=@prefix@\nexec_prefix=@exec_prefix@\nlibdir=@libdir@\nincludedir=@includedir@\n\nName: @PACKAGE_NAME@\nDescription: A l"
  },
  {
    "path": "tools/Makefile.am",
    "chars": 445,
    "preview": "AM_CPPFLAGS = \\\n\t-I$(top_srcdir)/include\n\nAM_CFLAGS = \\\n\t$(GLOBAL_CFLAGS) \\\n\t$(libimobiledevice_CFLAGS) \\\n\t$(libplist_CF"
  },
  {
    "path": "tools/ideviceactivation.c",
    "chars": 20772,
    "preview": "/*\n * ideviceactivation.c\n * A command line tool to handle the activation process\n *\n * Copyright (c) 2016-2019 Nikias B"
  }
]

About this extraction

This page contains the full source code of the libimobiledevice/libideviceactivation GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 21 files (147.1 KB), approximately 37.5k tokens, and a symbol index with 54 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!