summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.github/workflows/build.yml73
-rw-r--r--.gitignore39
-rw-r--r--AUTHORS15
-rw-r--r--CMakeLists.txt83
-rw-r--r--COPYING.LGPLv2.1502
-rw-r--r--Makefile.am13
-rw-r--r--Modules/CheckConstantExists.cmake38
-rw-r--r--Modules/FindPLIST.cmake31
-rw-r--r--Modules/FindUSB.cmake40
-rw-r--r--Modules/LibFindMacros.cmake99
-rw-r--r--Modules/VersionTag.cmake13
-rw-r--r--Modules/cmake_uninstall.cmake.in21
-rwxr-xr-xModules/describe.sh17
-rw-r--r--NEWS90
-rw-r--r--README218
-rw-r--r--README.devel50
-rw-r--r--README.md159
-rwxr-xr-xautogen.sh31
-rw-r--r--common/utils.c125
-rw-r--r--common/utils.h69
-rw-r--r--configure.ac195
-rw-r--r--daemon/CMakeLists.txt23
-rw-r--r--daemon/client.c616
-rw-r--r--daemon/client.h47
-rw-r--r--daemon/device.h52
-rw-r--r--daemon/log.h44
-rw-r--r--daemon/main.c618
-rw-r--r--daemon/usb-linux.c589
-rw-r--r--daemon/usb.h66
-rw-r--r--docs/Makefile.am3
-rw-r--r--docs/usbmuxd.880
-rwxr-xr-xgit-version-gen19
-rw-r--r--libusbmuxd.pc.in11
-rw-r--r--libusbmuxd/CMakeLists.txt29
-rw-r--r--libusbmuxd/libusbmuxd.c782
-rw-r--r--libusbmuxd/sock_stuff.c370
-rw-r--r--libusbmuxd/sock_stuff.h57
-rw-r--r--libusbmuxd/usbmuxd.h181
-rw-r--r--m4/as-compiler-flag.m462
-rw-r--r--python-client/.gitignore3
-rw-r--r--python-client/tcprelay.py148
-rw-r--r--python-client/usbmux.py246
-rw-r--r--src/Makefile.am32
-rw-r--r--src/client.c1058
-rw-r--r--src/client.h47
-rw-r--r--src/conf.c535
-rw-r--r--src/conf.h40
-rw-r--r--src/device.c (renamed from daemon/device.c)450
-rw-r--r--src/device.h56
-rw-r--r--src/log.c (renamed from daemon/log.c)56
-rw-r--r--src/log.h42
-rw-r--r--src/main.c920
-rw-r--r--src/preflight.c406
-rw-r--r--src/preflight.h28
-rw-r--r--src/usb.c1084
-rw-r--r--src/usb.h73
-rw-r--r--src/usbmuxd-proto.h (renamed from libusbmuxd/usbmuxd-proto.h)52
-rw-r--r--src/utils.c131
-rw-r--r--src/utils.h49
-rw-r--r--stuff/README25
-rw-r--r--stuff/com.openssh.sftp.plist41
-rw-r--r--systemd/Makefile.am21
-rw-r--r--systemd/usbmuxd.service.in7
-rw-r--r--tools/CMakeLists.txt11
-rw-r--r--tools/iproxy.c251
-rw-r--r--udev/39-usbmuxd.rules.in16
-rw-r--r--udev/85-usbmuxd.rules.in7
-rw-r--r--udev/CMakeLists.txt2
-rw-r--r--udev/Makefile.am20
69 files changed, 5748 insertions, 5679 deletions
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..f8c3f94
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,73 @@
+name: build
+
+on: [push]
+
+jobs:
+ build-linux-ubuntu:
+ runs-on: ubuntu-latest
+ steps:
+ - name: install dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install libusb-1.0-0-dev
+ - name: prepare environment
+ run: |
+ echo "target_triplet=`gcc -dumpmachine`" >> $GITHUB_ENV
+ - name: fetch libplist
+ uses: dawidd6/action-download-artifact@v2
+ 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@v2
+ 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@v2
+ 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@v2
+ 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
+ sudo cp -r extract/* /
+ sudo ldconfig
+ - uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+ - name: autogen
+ run: ./autogen.sh PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
+ - name: print config.log
+ if: ${{ failure() }}
+ run: cat config.log
+ - 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 usbmuxd.tar usr lib
+ - name: publish artifact
+ uses: actions/upload-artifact@v3
+ with:
+ name: usbmuxd-latest_${{env.target_triplet}}
+ path: usbmuxd.tar
diff --git a/.gitignore b/.gitignore
index 0784410..4e65390 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,38 @@
+# git-ls-files --others --exclude-from=.git/info/exclude
+# Lines that start with '#' are comments.
+# For a project mostly in C, the following would be a good set of
+# exclude patterns (uncomment them if you want to use them):
+*.[oa]
*~
-build
-
+*.po
+*.lo
+*.la
+autom4te.cache/*
+*.in
+*/.deps/*
+m4/*
+swig/*
+*.swp
+*.patch
+aclocal.m4
+config.h
+config.log
+config.sub
+config.guess
+config.status
+configure
+depcomp
+install-sh
+compile
+main
+ltmain.sh
+missing
+mkinstalldirs
+libtool
+*Makefile
+py-compile
+stamp-h1
+src/.libs
+src/usbmuxd
+udev/39-usbmuxd.rules
+systemd/usbmuxd.service
diff --git a/AUTHORS b/AUTHORS
index c196afd..e3b41fc 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,5 +1,14 @@
-Nikias Bassen
-Hector Martin
+Aaron Burghardt
Bastien Nocera
-Paul Sladen
+Cerrato Renaud
+Christophe Fergeau
+David Sansome
+Hector Martin
+Jacob Myers
+John Maguire
Martin Szulecki
+Mikkel Kamstrup Erlandsen
+Nikias Bassen
+Paul Sladen
+Peter Wu
+Satoshi Ohgoh \ No newline at end of file
diff --git a/CMakeLists.txt b/CMakeLists.txt
deleted file mode 100644
index 8ed2e37..0000000
--- a/CMakeLists.txt
+++ /dev/null
@@ -1,83 +0,0 @@
-PROJECT(usbmuxd)
-
-cmake_minimum_required(VERSION 2.6)
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/Modules/")
-
-include(VersionTag)
-
-set(USBMUXD_VERSION "${VERSION_TAG}")
-set(LIBUSBMUXD_VERSION "${VERSION_TAG}")
-set(LIBUSBMUXD_SOVERSION "1")
-
-message("-- Configuring usbmuxd v${VERSION_TAG}")
-
-if(NOT DEFINED LIB_SUFFIX)
- if(CMAKE_SIZEOF_VOID_P EQUAL 8 AND ${CMAKE_SYSTEM_NAME} MATCHES "Linux")
- set(LIB_SUFFIX "64" CACHE STRING "Define suffix of library directory name (32/64)" )
- else()
- set(LIB_SUFFIX "" CACHE STRING "Define suffix of library directory name (32/64)" )
- endif()
-endif()
-
-# let CFLAGS env override this
-if(CMAKE_C_FLAGS STREQUAL "")
- set(CMAKE_C_FLAGS "-O2")
-endif()
-
-option(WANT_PLIST "Build with protocol version 1 support using libplist" ON)
-
-set(OPT_INCLUDES "")
-set(OPT_LIBS "")
-if(WANT_PLIST)
- find_package(PLIST)
- if(PLIST_FOUND)
- set(HAVE_PLIST ON)
- set(OPT_INCLUDES ${OPT_INCLUDES} ${PLIST_INCLUDE_DIRS})
- set(OPT_LIBS ${OPT_LIBS} ${PLIST_LIBRARIES})
- else()
- message("* NOTE: libplist was not found!")
- message("* libusbmuxd/usbmuxd will be build WITHOUT support for version 1")
- message("* of the usbmux protocol (plist based).")
- endif()
-endif()
-
-option(WITH_USBMUXD "Build usbmux daemon (usbmuxd)" ON)
-if(WIN32 AND WITH_USBMUXD)
- message("** NOTE: usbmuxd cannot be built on WIN32 due to missing libusb-1.0 support!")
- message(" If you need your own usbmuxd you have to use usbmuxd-legacy which works")
- message(" with libusb-0.1; otherwise just use the one that ships with iTunes.")
- message(" Building of usbmuxd has been disabled.")
- set(WITH_USBMUXD OFF)
-endif()
-if(WITH_USBMUXD)
- message("-- Will build usbmuxd: YES")
-else()
- message("-- Will build usbmuxd: NO")
- message("** NOTE: will NOT build usbmuxd **")
- if(WIN32 OR APPLE)
- message("** Make sure iTunes is installed, otherwise this software will not work! **")
- else()
- message("** You'll need a working usbmuxd implementation for this software to work! **")
- endif()
-endif()
-
-add_definitions(-Wall)
-
-add_subdirectory (libusbmuxd)
-if (WITH_USBMUXD)
- add_subdirectory (daemon)
- if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
- add_subdirectory (udev)
- endif()
-endif()
-add_subdirectory (tools)
-
-# pkg-config
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/libusbmuxd.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/libusbmuxd.pc")
-# install pkg-config file
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libusbmuxd.pc" DESTINATION lib${LIB_SUFFIX}/pkgconfig/)
-
-# add uninstall target
-configure_file("${CMAKE_SOURCE_DIR}/Modules/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY)
-add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
diff --git a/COPYING.LGPLv2.1 b/COPYING.LGPLv2.1
deleted file mode 100644
index 732811e..0000000
--- a/COPYING.LGPLv2.1
+++ /dev/null
@@ -1,502 +0,0 @@
- 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!
diff --git a/Makefile.am b/Makefile.am
new file mode 100644
index 0000000..6da23b6
--- /dev/null
+++ b/Makefile.am
@@ -0,0 +1,13 @@
+AUTOMAKE_OPTIONS = foreign
+ACLOCAL_AMFLAGS = -I m4
+SUBDIRS = src $(UDEV_SUB) $(SYSTEMD_SUB) docs
+
+EXTRA_DIST = \
+ docs \
+ COPYING.GPLv2 \
+ COPYING.GPLv3 \
+ README.md
+
+DISTCHECK_CONFIGURE_FLAGS = \
+ --with-udevrulesdir=$$dc_install_base/$(udevrulesdir) \
+ --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir) \ No newline at end of file
diff --git a/Modules/CheckConstantExists.cmake b/Modules/CheckConstantExists.cmake
deleted file mode 100644
index 3d6d97e..0000000
--- a/Modules/CheckConstantExists.cmake
+++ /dev/null
@@ -1,38 +0,0 @@
-# - Check if the given constant exists (as an enum, define, or whatever)
-# CHECK_CONSTANT_EXISTS (CONSTANT HEADER VARIABLE)
-#
-# CONSTANT - the name of the constant you are interested in
-# HEADER - the header(s) where the prototype should be declared
-# VARIABLE - variable to store the result
-#
-# The following variables may be set before calling this macro to
-# modify the way the check is run:
-#
-# CMAKE_REQUIRED_FLAGS = string of compile command line flags
-# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
-# CMAKE_REQUIRED_INCLUDES = list of include directories
-#
-# Example: CHECK_CONSTANT_EXISTS(O_NOFOLLOW fcntl.h HAVE_O_NOFOLLOW)
-
-
-INCLUDE(CheckCSourceCompiles)
-
-MACRO (CHECK_CONSTANT_EXISTS _CONSTANT _HEADER _RESULT)
- SET(_INCLUDE_FILES)
- FOREACH (it ${_HEADER})
- SET(_INCLUDE_FILES "${_INCLUDE_FILES}#include <${it}>\n")
- ENDFOREACH (it)
-
- SET(_CHECK_CONSTANT_SOURCE_CODE "
-${_INCLUDE_FILES}
-void cmakeRequireConstant(int dummy,...){(void)dummy;}
-int main()
-{
- cmakeRequireConstant(0,${_CONSTANT});
- return 0;
-}
-")
- CHECK_C_SOURCE_COMPILES("${_CHECK_CONSTANT_SOURCE_CODE}" ${_RESULT})
-
-ENDMACRO (CHECK_CONSTANT_EXISTS)
-
diff --git a/Modules/FindPLIST.cmake b/Modules/FindPLIST.cmake
deleted file mode 100644
index d51aa74..0000000
--- a/Modules/FindPLIST.cmake
+++ /dev/null
@@ -1,31 +0,0 @@
-# - Try to find libplist
-# Once done, this will define
-#
-# PLIST_FOUND - system has libplist
-# PLIST_INCLUDE_DIRS - the libplist include directories
-# PLIST_LIBRARIES - link these to use libplist
-
-include(LibFindMacros)
-
-# Dependencies
-
-# Use pkg-config to get hints about paths
-libfind_pkg_check_modules(PLIST_PKGCONF libplist >= 0.15)
-
-# Include dir
-find_path(PLIST_INCLUDE_DIR
- NAMES plist/plist.h
- PATHS ${PLIST_PKGCONF_INCLUDE_DIRS}
-)
-
-# Finally the library itself
-find_library(PLIST_LIBRARY
- NAMES plist
- PATHS ${PLIST_PKGCONF_LIBRARY_DIRS}
-)
-
-# Set the include dir variables and the libraries and let libfind_process do the rest.
-# NOTE: Singular variables for this library, plural for libraries that this lib depends on.
-set(PLIST_PROCESS_INCLUDES PLIST_INCLUDE_DIR)
-set(PLIST_PROCESS_LIBS PLIST_LIBRARY)
-libfind_process(PLIST)
diff --git a/Modules/FindUSB.cmake b/Modules/FindUSB.cmake
deleted file mode 100644
index 486864f..0000000
--- a/Modules/FindUSB.cmake
+++ /dev/null
@@ -1,40 +0,0 @@
-# - Try to find libusb-1.0
-# Once done, this will define
-#
-# USB_FOUND - system has libusb-1.0
-# USB_INCLUDE_DIRS - the libusb-1.0 include directories
-# USB_LIBRARIES - link these to use libusb-1.0
-
-include(LibFindMacros)
-
-# Dependencies
-
-# pkg-config + libusb fails on FreeBSD, though libusb is in base
-if(NOT(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD"))
- # Use pkg-config to get hints about paths
- libfind_pkg_check_modules(USB_PKGCONF libusb-1.0>=1.0.3)
- # We want to look for libusb-1.0
- set(USB_LIBRARY_NAME usb-1.0)
-else()
- set(USB_PKGCONF_INCLUDE_DIRS /usr/include)
- set(USB_PKGCONF_LIBRARY_DIRS /usr/lib)
- set(USB_LIBRARY_NAME usb)
-endif()
-
-# Include dir
-find_path(USB_INCLUDE_DIR
- NAMES libusb.h
- PATHS ${USB_PKGCONF_INCLUDE_DIRS}
-)
-
-# Finally the library itself
-find_library(USB_LIBRARY
- NAMES ${USB_LIBRARY_NAME}
- PATHS ${USB_PKGCONF_LIBRARY_DIRS}
-)
-
-# Set the include dir variables and the libraries and let libfind_process do the rest.
-# NOTE: Singular variables for this library, plural for libraries this this lib depends on.
-set(USB_PROCESS_INCLUDES USB_INCLUDE_DIR)
-set(USB_PROCESS_LIBS USB_LIBRARY)
-libfind_process(USB)
diff --git a/Modules/LibFindMacros.cmake b/Modules/LibFindMacros.cmake
deleted file mode 100644
index 795d6b7..0000000
--- a/Modules/LibFindMacros.cmake
+++ /dev/null
@@ -1,99 +0,0 @@
-# Works the same as find_package, but forwards the "REQUIRED" and "QUIET" arguments
-# used for the current package. For this to work, the first parameter must be the
-# prefix of the current package, then the prefix of the new package etc, which are
-# passed to find_package.
-macro (libfind_package PREFIX)
- set (LIBFIND_PACKAGE_ARGS ${ARGN})
- if (${PREFIX}_FIND_QUIETLY)
- set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} QUIET)
- endif (${PREFIX}_FIND_QUIETLY)
- if (${PREFIX}_FIND_REQUIRED)
- set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} REQUIRED)
- endif (${PREFIX}_FIND_REQUIRED)
- find_package(${LIBFIND_PACKAGE_ARGS})
-endmacro (libfind_package)
-
-# Damn CMake developers made the UsePkgConfig system deprecated in the same release (2.6)
-# where they added pkg_check_modules. Consequently I need to support both in my scripts
-# to avoid those deprecated warnings. Here's a helper that does just that.
-# Works identically to pkg_check_modules, except that no checks are needed prior to use.
-macro (libfind_pkg_check_modules PREFIX PKGNAME)
- if (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
- include(UsePkgConfig)
- pkgconfig(${PKGNAME} ${PREFIX}_INCLUDE_DIRS ${PREFIX}_LIBRARY_DIRS ${PREFIX}_LDFLAGS ${PREFIX}_CFLAGS)
- else (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
- find_package(PkgConfig)
- if (PKG_CONFIG_FOUND)
- pkg_check_modules(${PREFIX} ${PKGNAME})
- endif (PKG_CONFIG_FOUND)
- endif (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4)
-endmacro (libfind_pkg_check_modules)
-
-# Do the final processing once the paths have been detected.
-# If include dirs are needed, ${PREFIX}_PROCESS_INCLUDES should be set to contain
-# all the variables, each of which contain one include directory.
-# Ditto for ${PREFIX}_PROCESS_LIBS and library files.
-# Will set ${PREFIX}_FOUND, ${PREFIX}_INCLUDE_DIRS and ${PREFIX}_LIBRARIES.
-# Also handles errors in case library detection was required, etc.
-macro (libfind_process PREFIX)
- # Skip processing if already processed during this run
- if (NOT ${PREFIX}_FOUND)
- # Start with the assumption that the library was found
- set (${PREFIX}_FOUND TRUE)
-
- # Process all includes and set _FOUND to false if any are missing
- foreach (i ${${PREFIX}_PROCESS_INCLUDES})
- if (${i})
- set (${PREFIX}_INCLUDE_DIRS ${${PREFIX}_INCLUDE_DIRS} ${${i}})
- mark_as_advanced(${i})
- else (${i})
- set (${PREFIX}_FOUND FALSE)
- endif (${i})
- endforeach (i)
-
- # Process all libraries and set _FOUND to false if any are missing
- foreach (i ${${PREFIX}_PROCESS_LIBS})
- if (${i})
- set (${PREFIX}_LIBRARIES ${${PREFIX}_LIBRARIES} ${${i}})
- mark_as_advanced(${i})
- else (${i})
- set (${PREFIX}_FOUND FALSE)
- endif (${i})
- endforeach (i)
-
- # Print message and/or exit on fatal error
- if (${PREFIX}_FOUND)
- if (NOT ${PREFIX}_FIND_QUIETLY)
- message (STATUS "Found ${PREFIX} ${${PREFIX}_VERSION}")
- endif (NOT ${PREFIX}_FIND_QUIETLY)
- else (${PREFIX}_FOUND)
- if (${PREFIX}_FIND_REQUIRED)
- foreach (i ${${PREFIX}_PROCESS_INCLUDES} ${${PREFIX}_PROCESS_LIBS})
- message("${i}=${${i}}")
- endforeach (i)
- message (FATAL_ERROR "Required library ${PREFIX} NOT FOUND.\nInstall the library (dev version) and try again. If the library is already installed, use ccmake to set the missing variables manually.")
- endif (${PREFIX}_FIND_REQUIRED)
- endif (${PREFIX}_FOUND)
- endif (NOT ${PREFIX}_FOUND)
-endmacro (libfind_process)
-
-macro(libfind_library PREFIX basename)
- set(TMP "")
- if(MSVC80)
- set(TMP -vc80)
- endif(MSVC80)
- if(MSVC90)
- set(TMP -vc90)
- endif(MSVC90)
- set(${PREFIX}_LIBNAMES ${basename}${TMP})
- if(${ARGC} GREATER 2)
- set(${PREFIX}_LIBNAMES ${basename}${TMP}-${ARGV2})
- string(REGEX REPLACE "\\." "_" TMP ${${PREFIX}_LIBNAMES})
- set(${PREFIX}_LIBNAMES ${${PREFIX}_LIBNAMES} ${TMP})
- endif(${ARGC} GREATER 2)
- find_library(${PREFIX}_LIBRARY
- NAMES ${${PREFIX}_LIBNAMES}
- PATHS ${${PREFIX}_PKGCONF_LIBRARY_DIRS}
- )
-endmacro(libfind_library)
-
diff --git a/Modules/VersionTag.cmake b/Modules/VersionTag.cmake
deleted file mode 100644
index 682ab3e..0000000
--- a/Modules/VersionTag.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-execute_process(
- COMMAND "sh" "${CMAKE_SOURCE_DIR}/Modules/describe.sh"
- WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
- OUTPUT_VARIABLE DESCRIBE
- OUTPUT_STRIP_TRAILING_WHITESPACE
-)
-
-if(DESCRIBE STREQUAL "")
- set (VERSION_TAG "UNKNOWN")
-else()
- string(REGEX REPLACE "^v" "" VERSION_TAG "${DESCRIBE}")
-endif()
-
diff --git a/Modules/cmake_uninstall.cmake.in b/Modules/cmake_uninstall.cmake.in
deleted file mode 100644
index 4bfb0bf..0000000
--- a/Modules/cmake_uninstall.cmake.in
+++ /dev/null
@@ -1,21 +0,0 @@
-IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
- MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"")
-ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
-
-FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
-STRING(REGEX REPLACE "\n" ";" files "${files}")
-FOREACH(file ${files})
- MESSAGE(STATUS "Uninstalling \"$ENV{DESTDIR}${file}\"")
- IF(EXISTS "$ENV{DESTDIR}${file}")
- EXEC_PROGRAM(
- "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
- OUTPUT_VARIABLE rm_out
- RETURN_VALUE rm_retval
- )
- IF(NOT "${rm_retval}" STREQUAL 0)
- MESSAGE(FATAL_ERROR "Problem when removing \"$ENV{DESTDIR}${file}\"")
- ENDIF(NOT "${rm_retval}" STREQUAL 0)
- ELSE(EXISTS "$ENV{DESTDIR}${file}")
- MESSAGE(STATUS "File \"$ENV{DESTDIR}${file}\" does not exist.")
- ENDIF(EXISTS "$ENV{DESTDIR}${file}")
-ENDFOREACH(file)
diff --git a/Modules/describe.sh b/Modules/describe.sh
deleted file mode 100755
index 6425ed5..0000000
--- a/Modules/describe.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/bash
-
-# Check for git and a git repo.
-if head=`git rev-parse --verify HEAD 2>/dev/null`; then
- /bin/echo -n `git describe`
-
- # Are there uncommitted changes?
- git update-index --refresh --unmerged > /dev/null
- git diff-index --quiet HEAD || /bin/echo -n -dirty
-else
-# Check for version tag
- if [ -e version.tag ]; then
- /bin/echo -n `cat version.tag`
- fi
-fi
-
-echo
diff --git a/NEWS b/NEWS
new file mode 100644
index 0000000..b2ba013
--- /dev/null
+++ b/NEWS
@@ -0,0 +1,90 @@
+Version 1.1.1
+~~~~~~~~~~~~~
+
+* Changes:
+ - Make use of libusb hotplug events for device discovery
+ - Use clock_gettime() instead of gettimeofday() to avoid timing issues
+ when calculating packet timeouts
+ - Get correct USB device speed instead of hardcoded value
+ - Bump libusb dependency to 1.0.9
+ - Use non-blocking sockets for client communication to avoid hanging
+ - Use correct manual section (8) for manpage
+ - Log pid of connecting clients if supported
+ - Implement device discovery using libusb hotplug events
+ - Fix wrong timeout value in debug messages
+ - Log error message if writing a config file fails
+ - Fix blocking by using libusb asynchronous I/O for getting initial device
+ information
+ - Tag all udev events with systemd tag
+ - Fix occasional USB reconfiguration due to udev rules being run again
+ - Fix wrong timestamps when running in foreground
+ - Set socket options for client connections to improve performance
+ - Implement "ListListeners" usbmux command handling
+ - Bump libimobiledevice dependency to 1.3.0
+ - Bump libplist dependency to 2.2.0
+ - Add support for iPhone XS/XR UDID format
+ - Add option to allow logging to dedicated logfile
+ - Convert README file to markdown format
+ - Fix USB reconnection issues on virtual machines with iOS 11+ devices
+ - Add support for connecting with T2 chip
+ - Various memory leak, deadlock and invalid free fixes
+ - Show actual libusb version in debug message on startup
+ - Enable libusb debugging output
+ - Log client process name alongside pid if possible on Linux
+ - Unify and improve log message output
+ - Improve README.md with project description, installation, contributing and
+ usage sections
+
+Version 1.1.0
+~~~~~~~~~~~~~
+
+* Changes:
+ - Check for pkg-config availability in autogen.sh
+ - Fix missing "usbmuxd-proto.h" in released tarbal
+ - Fix typo which broke udev support in rule for udev activation mode
+ - Fix broken configure summary on OS X and change activation method
+ to "manual"
+ - Compile bits of udev and systemd support only if needed
+ - Bump autoconf requirement to 2.64
+
+Version 1.0.9
+~~~~~~~~~~~~~
+
+* Changes:
+ - Fix broken handling of "--user" argument value
+ - Add new "--enable-exit" argument to enable handling of "--exit" requests
+ - Add new "--disable-hotplug" argument to disable automatic device discovery
+ - Add new "--systemd" argument to startup with right settings for systemd
+ - Add man page for usbmuxd
+ - Update copyright headers to match best practice
+ - Flush input buffer on connection teardown
+ - Add systemd based activation with fallback for udev and manual activation
+ - Add initial NEWS file and update README with latest information
+ - Rename header guards according to C++ standard
+ - Implement support for usbmux protocol version 2 which improves stability
+ - Fix crash when old libusbmuxd was used as a client
+ - Add "--version" argument to print version number and exit
+ - Update command line usage to match best practice and other tools
+ - Massively improve read performance by using 3 parallel transfers
+ - Bump requirement to libplist 1.11
+ - Remove trailing "\n" from usbmuxd_log() messages
+ - Improve thread safety
+ - Fix crash on 64bit systems in process_send()
+ - Fix possible leak of file descriptors
+ - Implement "ReadBUID", "ReadPairRecord", "SavePairRecord" and
+ "DeletePairRecord" commands
+ - Make plist based protocol support mandatory
+ - Return proper error packet on client version mismatch
+ - Implement "ListDevices" command
+ - Manage pair records in a directory compatible to native usbmuxd
+ - Output USB configuration changes in log
+ - Set "deactivated" USB configuration on iOS device by default as usbmuxd will
+ bring device to "life" on it's own now
+ - Add udev rule installation with autotools
+ - Lower udev rules numbering to make sure to start as early as possible
+ - Split out client library into "libusbmuxd" and depend on "libimobiledevice"
+ - Implement preflight worker to support iOS 7 based trust dialog handling
+ - Install usbmuxd binary to sbindir instead of bindir
+ - Switch from CMake to autotools build system
+
+This is the first release after the usbmuxd/libusbmuxd project split.
diff --git a/README b/README
deleted file mode 100644
index bad7531..0000000
--- a/README
+++ /dev/null
@@ -1,218 +0,0 @@
-Background
-==========
-
-'usbmuxd' stands for "USB multiplexing daemon". This daemon is in charge of
-multiplexing connections over USB to an iPhone or iPod touch. To users, it means
-you can sync your music, contacts, photos, etc. over USB. To developers, it
-means you can connect to any listening localhost socket on the device. usbmuxd
-is not used for tethering data transfer, which uses a dedicated USB interface as
-a virtual network device.
-
-Multiple connections to different TCP ports can happen in parallel. An example
-(and useful) tool called 'iproxy' is included that allows you to forward
-localhost ports to the device---allows SSH over USB on jailbroken devices, or
-allowing access the lockdown daemon (and then to all of the file access, sync,
-notification and backup services running on the device).
-
-The higher-level layers are handled by libimobiledevice. 'ifuse' is then able
-to sit on top of this and mount your device's AFC filesystem share.
-
-There is also a Python implementation of the client library in the python-client
-library, and an example tcprelay.py which performs a similar function to iproxy.
-This implementation supports OSX and Windows and the new iTunes plist-based
-usbmuxd protocol, so it is portable and will run on those operating systems with
-no modification, using Apple's native usbmuxd. This is useful if you need to
-tunnel to your device from another OS in a pinch. Run python tcpclient.py --help
-for usage information.
-
-License
-=======
-
-The contents of this package are licensed under the GNU General Public License,
-versions 2 or 3 (see COPYING.GPLv2 and COPYING.GPLv3), except for libuxbmuxd
-which is licensed under the GNU Lesser General Public License, version 2.1 or,
-at your option, any later version (see COPYING.LGPLv2.1). If a more permissive
-license is specified at the top of a source file, it takes precedence over this.
-
-Legal
-=====
-
-Apple, iPhone, and iPod touch are trademarks of Apple Inc., registered in the
-U.S. and other countries.
-
-Building
-========
-
- mkdir build
- cd build
- cmake ..
- make
- sudo make install
-
-You should also create a 'usbmux' user that has access to USB devices on your
-system. Alternatively, you can pass a different username after the -U argument.
-
-Running (with magic)
-====================
-
- (Unplug + replug your jailbroken device)
- ./iproxy 2222 22 &
- ssh -p 2222 root@localhost
-
-Hopefully you get the normal SSH login prompt. You may still lots of debugging
-output for the moment. If this is getting in the way of your ssh login, then
-run the 'ssh' command from a different xterminal or virtual console. Of course,
-you need to have OpenSSH installed on your jailbroken device for this to work.
-
-If you have iFuse, you can run "ifuse <mountpoint">. This doesn't require
-iproxy and works on all devices, jailbroken or not.
-
-Running (without magic)
-=======================
-
-If 'udev' is _not_ automatically running on your machine and picking up the new
-.rules file, you will need to start usbmuxd by hand first. Check it's running
-and that there is only one copy with 'ps aux | grep
-usbmuxd'.
-
- sudo usbmuxd -U -v -v &
- ./iproxy 2222 22 &
- ssh -p 2222 root@localhost
-
-Tip: Starting SSH if disabled
-=============================
-
-If your device is rooted, but SSH isn't started and you _cannot_ (for instance,
-cracked/broken screen) get to the Services control panel on the device, then you
-can start the SSH service over the USB by mounting the (jailbroken) filesystem.
-
-You will need to mount it using 'ifuse --afc2' (to access the root directory of
-the device), and then edit:
-
- /Library/LaunchDaemons/com.openssh.sshd.plist
-
-to _remove_ the lines:
-
- <key>Disabled</key>
- <true/>
-
-Reboot the device and then sshd should be running.
-
-TODO
-====
-
-The server currently assumes that the device is well-behaved and does not do a
-bunch of checks like looking for the expected SEQ and ACK numbers from it. This
-is normally not an issue, but it's annoying for debugging because lost packets
-(which shouldn't happen, but can happen if the code is buggy) mean that stuff
-gets out of sync and then might crash and burn dozens of packets later.
-
-The server needs more testing, and some optimizing.
-
-Someone should probably do some edge-case testing on the TCP stuff.
-
-The outgoing ACK handling on the server probably needs some thought. Currently,
-when there's an outstanding ACK, we send it after a timeout (to avoid sending
-a no-payload ACK packet for everything the phone sends us). However, there's
-probably a better way of doing this.
-
-Architecture information
-========================
-
-The iPhone / iPod Touch basically implements a rather strange USB networking
-system that operates at a higher level. It is of course completely proprietary.
-Generally speaking, this is what goes on in a typical usage scenario:
-
-0. iTunes opens a connection to usbmuxd and asks it for device notifications
-1. User inserts phone into computer
-2. usbmuxd notices the phone and pings it with a version packet
-3. phone replies
-4. usbmuxd now considers the phone to be connected and tells iTunes
-5. iTunes opens another separate connection to usbmuxd and asks it to connect
- to, say, the afc port on the device
-6. usbmuxd sends a pseudo-TCP SYN packet to the phone
-7. the phone's kernel driver receives the SYN packet and itself opens a
- TCP connection to localhost on the afc port
-8. the phone replies with a pseudo-TCP SYN/ACK indicating that the port is open
- and the connection can proceed
-7. usbmuxd sends a final ACK to the phone
-8. usbmuxd replies to iTunes with a "connection successful" message
-9. any data that iTunes writes to the usbmuxd socket from now on is forwarded,
- through pseudo-TCP, through USB, back into a more regular TCP connection to
- localhost, to the afc daemon on the phone, and vice versa
-
-The usbmuxd protocol is a relatively simple binary message protocol documented
-here:
-
-http://wikee.iphwn.org/usb:usbmux
-
-Note that once a connection is established the UNIX socket essentially becomes
-a dedicated pipe to the TCP connction and no more high-level control is
-possible (closing the socket closes the TCP connection). Ditto for the "listen
-for devices" mode - usbmuxd will reject any commands in such mode, and the
-socket essentially becomes a dedicated device notification pipe. This means
-that you need, at minimum, TWO connections to usbmuxd to do anything useful.
-
-On Windows, usbmuxd works the same way but a TCP connection to localhost port
-27015 replaces the UNIX socket. On OSX, the UNIX socket is /var/run/usbmuxd. The
-server and client implemented here default the same /var/run/usbmuxd socket.
-
-The phone protocol operates over a pair of USB bulk endpoints. There is an outer
-layer used for packet size info and a "protocol" (version and TCP are the only
-two options), and that header is followed by TCP headers for actual data comms.
-However, the protocol isn't actual TCP, just a custom protocol which for some
-reason uses a standard TCP header and leaves most fields unused.
-
-There is no reordering or retransmission. There are no checksums, no URG, no
-PSH, no non-ACK, no FIN. What there *is* is the SEQ/ACK/window mechanism used
-for flow control, and RST is used as the only connection teardown mechanism (and
-also for "connection refused"), and the connection startup is SYN/SYNACK/ACK.
-
-Windows are constant-scaled by 8 bits. This is legal TCP as long as the
-corresponding option is negotiated. Of course, no such negotiation happens on
-this protocol.
-
-Note that, since there are no retransmissions, there is some overlap between ACK
-and window for flow control. For example, the server doesn't ever touch its
-window size, and just refuses to ACK stuff if its buffers are full and the
-client isn't reading data. The phone happily seems to stop sending stuff.
-
-Also, if the phone RSTs you out of nowhere, look at the packet payload for a
-textual error message. Note: if it claims to suffer from amnesia, that probably
-means you overflowed its input buffer by ignoring its flow control / window
-size. Go figure. Probably a logic bug in the kernel code.
-
-Note that all normal packets need to have flags set to ACK (and only ACK). There
-is no support for, erm, not-acking. Keep the ack number field valid at all
-times.
-
-The usbmuxd CONNECT request port field is byte-swapped (network-endian). This is
-even more annoying for the plist based protocol, since it's even true there
-(where the field is plain text). So even for the plain text int, you need to
-swap the bytes (port 22 becomes <integer>5632</integer>). I have no clue if this
-is the case on the new plist protocol on PPC macs (is the newer iTunes available
-for those?)
-
-There are a bunch of gotchas due to the USB framing, and this is even worse
-because implementations tend to get it wrong (i.e. libusb, and this is the
-reason for the patch). Basically, USB Bulk offers, at the low level, the ability
-to transfer packets from 0 to wMaxPacketSize (512 here) bytes, period. There is
-no other support for higher level framing of transfers. The way you do those is
-by breaking them up into packets, and the final shorter packet marks the end of
-the transfer. The critical bit is that, if the transfer happens to be divisible
-by 512, you send a zero-length packet (ZLP) to indicate the end of the transfer.
-Libusb doesn't set this option by default and the iPhone gets packets stuck to
-each other, which it doesn't like. Actually, this framing is sort of redundant
-because the usbmux packet header includes a length field, but the phone still
-wants the ZLPs or else it breaks. To make matters worse, usbdevfs imposes a max
-transfer size of 16k, so libusb breaks transfers into that size. This is okay
-for sending as long as the ZLP is only added to the last transfer (the patch
-does that), but it can easily cause nasty race conditions on RX due to libusb
-doing multiple outstanding reads at the same time and then cancelling the rest
-when shorter data arrives (but what if some data got into the other requests
-already?), so we only do 16k reads and stick them together ourselves by looking
-at the packet size header. We still depend on ZLPs being sent to end transfers
-at non-16k boundaries that are multiples of 512, but that seems to work fine. I
-guess the ZLPs might cause spurious 0-byte transfers to show up on RX if things
-line up right, but we ignore those. By the way, the maximum packet/transfer size
-is 65535 bytes due to the 16-bit length header of the usbmux protocol.
diff --git a/README.devel b/README.devel
deleted file mode 100644
index 727e095..0000000
--- a/README.devel
+++ /dev/null
@@ -1,50 +0,0 @@
-Background
-==========
-
-'libusbmuxd' makes it really simple to talk to a running 'usbmuxd' and
-hides all the details for you. There are two function calls:
-
-usbmuxd_scan()
---------------
-
-This returns a list of all available iPhone-like devices that are
-available for talking to. The returned array contains the USB
-product_id, hex formatted serial_number of any iPhones/iTouches and a
-non-descript 'handle' for all those devices that are within range (as
-of March 2009, that means a device directly plugged into the
-computer's USB port).
-
-Once you have found the device you want to communicate with, take its
-'handle' and pass this to usbmuxd_connect().
-
-usbmuxd_connect()
------------------
-
-This takes a handle, a destination port number and tries to setup
-a proxy a connection. It returns a file-descriptor which you should
-be able to read(), write() and select() on like any other active network
-socket connection.
-
-
-Technical details
-=================
-
-When usbmuxd is running (normally started, or stopped as a result of
-'udev' auto-insertion messages), it provides a socket interface in
-'/var/run/usbmuxd' that is designed to be compatible with the socket
-interface that is provided on MacOSX.
-
-The structures for communicating over this device are documented
-in the 'usbmuxd-proto.h', but you shouldn't need to view them
-directly if you are using the libusbmuxd.so library for easy access.
-
-
-Example
-=======
-
-#include <usbmuxd.h>
-
-...
-
-gcc -o leetphone leetphone.c -lusbmuxd
-
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..8249358
--- /dev/null
+++ b/README.md
@@ -0,0 +1,159 @@
+# usbmuxd
+
+*A socket daemon to multiplex connections from and to iOS devices.*
+
+![build](https://github.com/libimobiledevice/usbmuxd/actions/workflows/build.yml/badge.svg)
+
+## Features
+
+usbmuxd stands for "USB multiplexing daemon". This daemon is in charge of
+multiplexing connections over USB to an iOS device.
+
+To users, it means you can use various applications to interact with your
+device.
+
+To developers, it means you can connect to any listening localhost socket on
+the device.
+
+Some key features are:
+
+- **Implementation**: Open-Source implementation of proprietary usbmuxd daemon
+- **Cross-Platform:** Tested on Linux, macOS, Windows and Android platforms
+- **Linux**: Supports udev and systemd for automatic activation
+- **Compatibility**: Supports latest device firmware releases
+- **Scalability**: Supports multiple connections to different ports in parallel
+
+usbmuxd is not used for tethering data transfers which uses a dedicated USB
+interface to act as a virtual network device.
+
+The higher-level layers, especially if you want to write an application to
+interact with the device, are handled by [libimobiledevice](https://github.com/libimobiledevice/libimobiledevice.git).
+
+The low-level layer is handled by [libusbmuxd](https://github.com/libimobiledevice/libusbmuxd.git).
+
+## 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 \
+ libusbmuxd-dev \
+ libimobiledevice-dev \
+ libimobiledevice-glue-dev \
+ libusb-1.0-0-dev \
+ udev
+```
+
+If systemd is not installed and should control spawning the daemon use:
+```shell
+sudo apt-get install \
+ systemd
+```
+
+Then clone the actual project repository:
+```shell
+git clone https://github.com/libimobiledevice/usbmuxd.git
+cd usbmuxd
+```
+
+Now you can build and install it:
+```shell
+./autogen.sh
+make
+sudo make install
+```
+
+If you require a custom prefix or other option being passed to `./configure`
+you can pass them directly to `./autogen.sh` like this:
+```bash
+./autogen.sh --prefix=/opt/local --without-preflight --without-systemd
+make
+sudo make install
+```
+
+To output a list of available configure options use:
+```bash
+./autogen.sh --help
+```
+
+## Usage
+
+The daemon is automatically started by udev or systemd depending on what you
+have configured upon hotplug of an iOS device and exits if the last device
+was unplugged.
+
+When usbmuxd is running it provides a socket interface at `/var/run/usbmuxd`
+that is designed to be compatible with the socket interface that is provided
+on macOS.
+
+You should also create an `usbmux` user that has access to USB devices on your
+system. Alternatively, just pass a different username using the `-U` argument.
+
+The daemon also manages pairing records with iOS devices and the host in
+`/var/lib/lockdown` (Linux) or `/var/db/lockdown` (macOS).
+
+Ensure proper permissions are setup for the daemon to access the directory.
+
+For debugging purposes it is helpful to start usbmuxd using the foreground `-f`
+argument and enable verbose mode `-v` to get suitable logs.
+
+Please consult the usage information or manual page for a full documentation of
+available command line options:
+```shell
+usbmuxd --help
+man usbmuxd
+```
+
+## 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://git.libimobiledevice.org/usbmuxd.git
+* Repository (Mirror): https://github.com/libimobiledevice/usbmuxd.git
+* Issue Tracker: https://github.com/libimobiledevice/usbmuxd/issues
+* Mailing List: https://lists.libimobiledevice.org/mailman/listinfo/libimobiledevice-devel
+* Twitter: https://twitter.com/libimobiledev
+
+## License
+
+This library and utilities are 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.GPLv3` file.
+
+## Credits
+
+The initial usbmuxd daemon implementation was authored by Hector Martin.
+
+Apple, iPhone, iPad, iPod, iPod Touch, Apple TV, Apple Watch, Mac, iOS,
+iPadOS, tvOS, watchOS, and macOS are trademarks of Apple Inc.
+
+usbmuxd is an independent software application and has not been
+authorized, sponsored, or otherwise approved by Apple Inc.
+
+README Updated on: 2022-04-04
diff --git a/autogen.sh b/autogen.sh
new file mode 100755
index 0000000..5936e8a
--- /dev/null
+++ b/autogen.sh
@@ -0,0 +1,31 @@
+#!/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
+
+ requires_pkgconfig=`which pkg-config 2>&1 >/dev/null`
+ if [ $? -ne 0 ]; then
+ echo "Missing required pkg-config. Please install it on your system and run again."
+ fi
+
+ cd "$olddir"
+)
+
+if [ -z "$NOCONFIGURE" ]; then
+ $srcdir/configure "$@"
+fi
diff --git a/common/utils.c b/common/utils.c
deleted file mode 100644
index db628ce..0000000
--- a/common/utils.c
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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 <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include "utils.h"
-
-#ifdef USBMUXD_DAEMON
-# include "log.h"
-# define util_error(...) usbmuxd_log(LL_ERROR, __VA_ARGS__)
-#else
-# define util_error(...) fprintf(stderr, __VA_ARGS__)
-#endif
-
-#ifdef USBMUXD_DAEMON
-void fdlist_create(struct fdlist *list)
-{
- list->count = 0;
- list->capacity = 4;
- list->owners = malloc(sizeof(*list->owners) * list->capacity);
- list->fds = malloc(sizeof(*list->fds) * list->capacity);
-}
-void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events)
-{
- if(list->count == list->capacity) {
- list->capacity *= 2;
- list->owners = realloc(list->owners, sizeof(*list->owners) * list->capacity);
- list->fds = realloc(list->fds, sizeof(*list->fds) * list->capacity);
- }
- list->owners[list->count] = owner;
- list->fds[list->count].fd = fd;
- list->fds[list->count].events = events;
- list->fds[list->count].revents = 0;
- list->count++;
-}
-
-void fdlist_free(struct fdlist *list)
-{
- list->count = 0;
- list->capacity = 0;
- free(list->owners);
- list->owners = NULL;
- free(list->fds);
- list->fds = NULL;
-}
-
-void fdlist_reset(struct fdlist *list)
-{
- list->count = 0;
-}
-#endif
-
-void collection_init(struct collection *col)
-{
- col->list = malloc(sizeof(void *));
- memset(col->list, 0, sizeof(void *));
- col->capacity = 1;
-}
-
-void collection_free(struct collection *col)
-{
- free(col->list);
- col->list = NULL;
- col->capacity = 0;
-}
-
-void collection_add(struct collection *col, void *element)
-{
- int i;
- for(i=0; i<col->capacity; i++) {
- if(!col->list[i]) {
- col->list[i] = element;
- return;
- }
- }
- col->list = realloc(col->list, sizeof(void*) * col->capacity * 2);
- memset(&col->list[col->capacity], 0, sizeof(void *) * col->capacity);
- col->list[col->capacity] = element;
- col->capacity *= 2;
-}
-
-void collection_remove(struct collection *col, void *element)
-{
- int i;
- for(i=0; i<col->capacity; i++) {
- if(col->list[i] == element) {
- col->list[i] = NULL;
- return;
- }
- }
- util_error("collection_remove: element %p not present in collection %p (cap %d)", element, col, col->capacity);
-}
-
-int collection_count(struct collection *col)
-{
- int i, cnt = 0;
- for(i=0; i<col->capacity; i++) {
- if(col->list[i])
- cnt++;
- }
- return cnt;
-}
diff --git a/common/utils.h b/common/utils.h
deleted file mode 100644
index ee79e48..0000000
--- a/common/utils.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
-
-#ifndef __UTILS_H__
-#define __UTILS_H__
-
-#ifdef USBMUXD_DAEMON
-#include <poll.h>
-
-enum fdowner {
- FD_LISTEN,
- FD_CLIENT,
- FD_USB
-};
-
-struct fdlist {
- int count;
- int capacity;
- enum fdowner *owners;
- struct pollfd *fds;
-};
-
-void fdlist_create(struct fdlist *list);
-void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events);
-void fdlist_free(struct fdlist *list);
-void fdlist_reset(struct fdlist *list);
-#endif
-
-struct collection {
- void **list;
- int capacity;
-};
-
-void collection_init(struct collection *col);
-void collection_add(struct collection *col, void *element);
-void collection_remove(struct collection *col, void *element);
-int collection_count(struct collection *col);
-void collection_free(struct collection *col);
-
-#define FOREACH(var, col) \
- do { \
- int _iter; \
- for(_iter=0; _iter<(col)->capacity; _iter++) { \
- if(!(col)->list[_iter]) continue; \
- var = (col)->list[_iter];
-
-#define ENDFOREACH \
- } \
- } while(0);
-
-#endif
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..c51d53a
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,195 @@
+# -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+
+AC_PREREQ([2.68])
+AC_INIT([usbmuxd], [m4_esyscmd(./git-version-gen $RELEASE_VERSION)], [https://github.com/libimobiledevice/usbmuxd/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])
+
+# Check if we have a version defined
+if test -z $PACKAGE_VERSION; then
+ AC_MSG_ERROR([PACKAGE_VERSION is not defined. Make sure to configure a source tree checked out from git or that .tarball-version is present.])
+fi
+
+# Checks for programs.
+AC_PROG_CC
+AM_PROG_CC_C_O
+LT_INIT
+
+# Checks for libraries.
+PKG_CHECK_MODULES(libusb, libusb-1.0 >= 1.0.9)
+PKG_CHECK_MODULES(libplist, libplist-2.0 >= 2.3.0)
+PKG_CHECK_MODULES(libimobiledevice, libimobiledevice-1.0 >= 1.3.0, have_limd=yes, have_limd=no)
+PKG_CHECK_MODULES(limd_glue, libimobiledevice-glue-1.0 >= 1.0.0)
+
+AC_ARG_WITH([preflight],
+ [AS_HELP_STRING([--without-preflight],
+ [do not build with preflight worker support @<:@default=yes@:>@])],
+ [with_preflight=$withval],
+ [with_preflight=yes])
+
+if test "x$have_limd" = "xyes"; then
+ if test "x$with_preflight" != "xyes"; then
+ have_limd=no
+ echo "*** Note: preflight worker support has been disabled ***"
+ else
+ AC_DEFINE(HAVE_LIBIMOBILEDEVICE, 1, [Define if you have libimobiledevice support])
+ AC_SUBST(libimobiledevice_CFLAGS)
+ AC_SUBST(libimobiledevice_LIBS)
+ CACHED_CFLAGS="$CFLAGS"
+ CFLAGS+=" $libimobiledevice_CFLAGS"
+ AC_CACHE_CHECK(for enum idevice_connection_type, ac_cv_enum_idevice_connection_type,
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
+ #include <libimobiledevice/libimobiledevice.h>
+ ], [
+ enum idevice_connection_type conn_type = CONNECTION_USBMUXD;
+ ])], ac_cv_enum_idevice_connection_type=yes, ac_cv_enum_idevice_connection_type=no))
+ CFLAGS="$CACHED_CFLAGS"
+ if (test "$ac_cv_enum_idevice_connection_type" = "yes"); then
+ AC_DEFINE(HAVE_ENUM_IDEVICE_CONNECTION_TYPE, 1, [Define if enum idevice_connection_type is available])
+ fi
+ fi
+else
+ if test "x$with_preflight" == "xyes"; then
+ AC_MSG_ERROR([preflight worker support requested but libimobiledevice could not be found])
+ fi
+fi
+
+AC_ARG_WITH([udevrulesdir],
+ AS_HELP_STRING([--with-udevrulesdir=DIR],
+ [Directory for udev rules]),
+ [],
+ [with_udevrulesdir=auto])
+if test "x$with_udevrulesdir" = "xauto"; then
+ udevdir=$($PKG_CONFIG --variable=udevdir udev)
+ if test "x$udevdir" != "x"; then
+ with_udevrulesdir=$udevdir"/rules.d"
+ else
+ with_udevrulesdir=$prefix/lib/udev/rules.d
+ fi
+fi
+
+AC_ARG_WITH([systemd],
+ [AS_HELP_STRING([--without-systemd],
+ [do not build with systemd support @<:@default=yes@:>@])],
+ [with_systemd=$withval],
+ [with_systemd=yes])
+
+AC_ARG_WITH([systemdsystemunitdir],
+ [AS_HELP_STRING([--with-systemdsystemunitdir=DIR],
+ [directory for systemd service files])],
+ [with_systemdsystemunitdir=$withval],
+ [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)])
+
+if test "x$with_systemdsystemunitdir" != xno; then
+ AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir])
+fi
+AM_CONDITIONAL(WANT_SYSTEMD, [test -n "$with_systemdsystemunitdir" -a "x$with_systemdsystemunitdir" != xno -a "x$with_systemd" = "xyes" ])
+
+if test "x$with_systemd" = xyes; then
+ udev_activation_rule="ENV{SYSTEMD_WANTS}=\"usbmuxd.service\""
+else
+ udev_activation_rule="RUN+=\"@sbindir@/usbmuxd --user usbmux --udev\""
+fi
+AC_SUBST(udev_activation_rule)
+
+# Checks for header files.
+AC_CHECK_HEADERS([stdint.h stdlib.h string.h])
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_TYPE_SIZE_T
+AC_TYPE_SSIZE_T
+AC_TYPE_UINT16_T
+AC_TYPE_UINT32_T
+AC_TYPE_UINT8_T
+
+# Check if clock_gettime requires -lrt (old GNU systems)
+AC_SEARCH_LIBS([clock_gettime],[rt posix4])
+
+# Checks for library functions.
+AC_CHECK_FUNCS([strcasecmp strdup strerror strndup malloc realloc])
+AC_CHECK_FUNCS([ppoll clock_gettime localtime_r])
+
+# Check for operating system
+AC_MSG_CHECKING([whether to enable WIN32 build settings])
+UDEV_SUB=
+SYSTEMD_SUB=
+case ${host_os} in
+ *mingw32*|*cygwin*)
+ win32=true
+ AC_MSG_RESULT([yes])
+ AC_CHECK_TOOL([WINDRES], [windres], AC_MSG_ERROR([windres not found]))
+ AC_SUBST(WINDRES)
+ activation_method="manual"
+ ;;
+ darwin*)
+ win32=false
+ AC_MSG_RESULT([no])
+ # No support for launchd yet
+ activation_method="manual"
+ ;;
+ *)
+ win32=false
+ AC_MSG_RESULT([no])
+ UDEV_SUB=udev
+ AC_SUBST([udevrulesdir], [$with_udevrulesdir])
+ AC_DEFINE(HAVE_UDEV, 1, [Define to enable udev support])
+ activation_method="systemd"
+ if test "x$with_systemd" != "xyes"; then
+ echo "*** Note: support for systemd activation has been disabled, using udev activation instead ***"
+ activation_method="udev"
+ else
+ AC_DEFINE(HAVE_SYSTEMD, 1, [Define to enable systemd support])
+ SYSTEMD_SUB=systemd
+ fi
+ ;;
+esac
+AM_CONDITIONAL(WIN32, test x$win32 = xtrue)
+
+AC_SUBST([UDEV_SUB])
+AC_SUBST([SYSTEMD_SUB])
+
+AS_COMPILER_FLAGS(GLOBAL_CFLAGS, "-g -Wall -Wextra -Wmissing-declarations -Wredundant-decls -Wshadow -Wpointer-arith -Wwrite-strings -Wswitch-default -Wno-unused-parameter")
+AC_SUBST(GLOBAL_CFLAGS)
+
+m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])
+
+# workaround for older autoconf versions
+if test "x$runstatedir" == "x"; then
+ runstatedir=$localstatedir/run
+fi
+
+AC_CONFIG_FILES([
+Makefile
+src/Makefile
+udev/Makefile
+systemd/Makefile
+docs/Makefile
+])
+AC_OUTPUT
+
+echo "
+Configuration for $PACKAGE $VERSION:
+-------------------------------------------
+
+ install prefix ............: $prefix
+ preflight worker support ..: $have_limd
+ activation method .........: $activation_method"
+
+if test "x$activation_method" = "xsystemd"; then
+ echo " systemd unit directory ....: ${systemdsystemunitdir}"
+fi
+
+if test -n "$udevrulesdir"; then
+ echo " udev rules directory ......: ${udevrulesdir}"
+fi
+
+echo " compiler ..................: ${CC}
+
+ Now type 'make' to build $PACKAGE $VERSION,
+ and then 'make install' for installation.
+"
diff --git a/daemon/CMakeLists.txt b/daemon/CMakeLists.txt
deleted file mode 100644
index c323f7b..0000000
--- a/daemon/CMakeLists.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-find_package(USB REQUIRED)
-include_directories(${USB_INCLUDE_DIRS})
-include_directories(${OPT_INCLUDES})
-set(LIBS ${LIBS} ${USB_LIBRARIES} ${OPT_LIBS})
-if(HAVE_PLIST)
- add_definitions("-DHAVE_PLIST")
- message("-- usbmuxd will be built with protocol version 1 support")
-endif()
-include_directories (${CMAKE_SOURCE_DIR}/common)
-include_directories (${CMAKE_SOURCE_DIR}/daemon)
-include_directories (${CMAKE_SOURCE_DIR}/libusbmuxd)
-
-add_definitions(-DUSBMUXD_DAEMON -DUSBMUXD_VERSION="${USBMUXD_VERSION}")
-add_executable(usbmuxd main.c usb-linux.c log.c ${CMAKE_SOURCE_DIR}/common/utils.c device.c client.c)
-target_link_libraries(usbmuxd ${LIBS})
-
-install(TARGETS usbmuxd RUNTIME DESTINATION sbin)
-
-message("
-* REMINDER
-* Remember to add a user named 'usbmux' with USB access permissions
-* for the udev hotplugging feature to work out of the box.
-")
diff --git a/daemon/client.c b/daemon/client.c
deleted file mode 100644
index ac1045a..0000000
--- a/daemon/client.c
+++ /dev/null
@@ -1,616 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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 <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <arpa/inet.h>
-
-#ifdef HAVE_PLIST
-#include <plist/plist.h>
-#endif
-
-#include "log.h"
-#include "usb.h"
-#include "client.h"
-#include "device.h"
-
-#ifdef HAVE_PLIST
-#define CMD_BUF_SIZE 1024
-#else
-#define CMD_BUF_SIZE 256
-#endif
-#define REPLY_BUF_SIZE 1024
-
-enum client_state {
- CLIENT_COMMAND, // waiting for command
- CLIENT_LISTEN, // listening for devices
- CLIENT_CONNECTING1, // issued connection request
- CLIENT_CONNECTING2, // connection established, but waiting for response message to get sent
- CLIENT_CONNECTED, // connected
- CLIENT_DEAD
-};
-
-struct mux_client {
- int fd;
- unsigned char *ob_buf;
- uint32_t ob_size;
- uint32_t ob_capacity;
- unsigned char *ib_buf;
- uint32_t ib_size;
- uint32_t ib_capacity;
- short events, devents;
- uint32_t connect_tag;
- int connect_device;
- enum client_state state;
- uint32_t proto_version;
-};
-
-static struct collection client_list;
-
-int client_read(struct mux_client *client, void *buffer, uint32_t len)
-{
- usbmuxd_log(LL_SPEW, "client_read fd %d buf %p len %d", client->fd, buffer, len);
- if(client->state != CLIENT_CONNECTED) {
- usbmuxd_log(LL_ERROR, "Attempted to read from client %d not in CONNECTED state", client->fd);
- return -1;
- }
- return recv(client->fd, buffer, len, 0);
-}
-
-int client_write(struct mux_client *client, void *buffer, uint32_t len)
-{
- usbmuxd_log(LL_SPEW, "client_write fd %d buf %p len %d", client->fd, buffer, len);
- if(client->state != CLIENT_CONNECTED) {
- usbmuxd_log(LL_ERROR, "Attempted to write to client %d not in CONNECTED state", client->fd);
- return -1;
- }
- return send(client->fd, buffer, len, 0);
-}
-
-int client_set_events(struct mux_client *client, short events)
-{
- if((client->state != CLIENT_CONNECTED) && (client->state != CLIENT_CONNECTING2)) {
- usbmuxd_log(LL_ERROR, "client_set_events to client %d not in CONNECTED state", client->fd);
- return -1;
- }
- client->devents = events;
- if(client->state == CLIENT_CONNECTED)
- client->events = events;
- return 0;
-}
-
-int client_accept(int listenfd)
-{
- struct sockaddr_un addr;
- int cfd;
- socklen_t len = sizeof(struct sockaddr_un);
- cfd = accept(listenfd, (struct sockaddr *)&addr, &len);
- if (cfd < 0) {
- usbmuxd_log(LL_ERROR, "accept() failed (%s)", strerror(errno));
- return cfd;
- }
-
- struct mux_client *client;
- client = malloc(sizeof(struct mux_client));
- memset(client, 0, sizeof(struct mux_client));
-
- client->fd = cfd;
- client->ob_buf = malloc(REPLY_BUF_SIZE);
- client->ob_size = 0;
- client->ob_capacity = REPLY_BUF_SIZE;
- client->ib_buf = malloc(CMD_BUF_SIZE);
- client->ib_size = 0;
- client->ib_capacity = CMD_BUF_SIZE;
- client->state = CLIENT_COMMAND;
- client->events = POLLIN;
-
- collection_add(&client_list, client);
-
- usbmuxd_log(LL_INFO, "New client on fd %d", client->fd);
- return client->fd;
-}
-
-void client_close(struct mux_client *client)
-{
- usbmuxd_log(LL_INFO, "Disconnecting client fd %d", client->fd);
- if(client->state == CLIENT_CONNECTING1 || client->state == CLIENT_CONNECTING2) {
- usbmuxd_log(LL_INFO, "Client died mid-connect, aborting device %d connection", client->connect_device);
- client->state = CLIENT_DEAD;
- device_abort_connect(client->connect_device, client);
- }
- close(client->fd);
- if(client->ob_buf)
- free(client->ob_buf);
- if(client->ib_buf)
- free(client->ib_buf);
- collection_remove(&client_list, client);
- free(client);
-}
-
-void client_get_fds(struct fdlist *list)
-{
- FOREACH(struct mux_client *client, &client_list) {
- fdlist_add(list, FD_CLIENT, client->fd, client->events);
- } ENDFOREACH
-}
-
-static int send_pkt(struct mux_client *client, uint32_t tag, enum usbmuxd_msgtype msg, void *payload, int payload_length)
-{
- struct usbmuxd_header hdr;
- hdr.version = client->proto_version;
- hdr.length = sizeof(hdr) + payload_length;
- hdr.message = msg;
- hdr.tag = tag;
- usbmuxd_log(LL_DEBUG, "send_pkt fd %d tag %d msg %d payload_length %d", client->fd, tag, msg, payload_length);
- if((client->ob_capacity - client->ob_size) < hdr.length) {
- usbmuxd_log(LL_ERROR, "Client %d output buffer full (%d bytes) while sending message %d (%d bytes)", client->fd, client->ob_capacity, hdr.message, hdr.length);
- client_close(client);
- return -1;
- }
- memcpy(client->ob_buf + client->ob_size, &hdr, sizeof(hdr));
- if(payload && payload_length)
- memcpy(client->ob_buf + client->ob_size + sizeof(hdr), payload, payload_length);
- client->ob_size += hdr.length;
- client->events |= POLLOUT;
- return hdr.length;
-}
-
-static int send_result(struct mux_client *client, uint32_t tag, uint32_t result)
-{
- int res = -1;
-#ifdef HAVE_PLIST
- if (client->proto_version == 1) {
- /* XML plist packet */
- char *xml = NULL;
- uint32_t xmlsize = 0;
- plist_t dict = plist_new_dict();
- plist_dict_insert_item(dict, "MessageType", plist_new_string("Result"));
- plist_dict_insert_item(dict, "Number", plist_new_uint(result));
- plist_to_xml(dict, &xml, &xmlsize);
- plist_free(dict);
- if (xml) {
- res = send_pkt(client, tag, MESSAGE_PLIST, xml, xmlsize);
- free(xml);
- } else {
- usbmuxd_log(LL_ERROR, "%s: Could not convert plist to xml", __func__);
- }
- } else
-#endif
- {
- /* binary packet */
- res = send_pkt(client, tag, MESSAGE_RESULT, &result, sizeof(uint32_t));
- }
- return res;
-}
-
-int client_notify_connect(struct mux_client *client, enum usbmuxd_result result)
-{
- usbmuxd_log(LL_SPEW, "client_notify_connect fd %d result %d", client->fd, result);
- if(client->state == CLIENT_DEAD)
- return -1;
- if(client->state != CLIENT_CONNECTING1) {
- usbmuxd_log(LL_ERROR, "client_notify_connect when client %d is not in CONNECTING1 state", client->fd);
- return -1;
- }
- if(send_result(client, client->connect_tag, result) < 0)
- return -1;
- if(result == RESULT_OK) {
- client->state = CLIENT_CONNECTING2;
- client->events = POLLOUT; // wait for the result packet to go through
- // no longer need this
- free(client->ib_buf);
- client->ib_buf = NULL;
- } else {
- client->state = CLIENT_COMMAND;
- }
- return 0;
-}
-
-static int notify_device_add(struct mux_client *client, struct device_info *dev)
-{
- int res = -1;
-#ifdef HAVE_PLIST
- if (client->proto_version == 1) {
- /* XML plist packet */
- char *xml = NULL;
- uint32_t xmlsize = 0;
- plist_t dict = plist_new_dict();
- plist_dict_insert_item(dict, "MessageType", plist_new_string("Attached"));
- plist_t props = plist_new_dict();
- // TODO: get current usb speed
- plist_dict_insert_item(props, "ConnectionSpeed", plist_new_uint(480000000));
- plist_dict_insert_item(props, "ConnectionType", plist_new_string("USB"));
- plist_dict_insert_item(props, "DeviceID", plist_new_uint(dev->id));
- plist_dict_insert_item(props, "LocationID", plist_new_uint(dev->location));
- plist_dict_insert_item(props, "ProductID", plist_new_uint(dev->pid));
- plist_dict_insert_item(props, "SerialNumber", plist_new_string(dev->serial));
- plist_dict_insert_item(dict, "Properties", props);
- plist_to_xml(dict, &xml, &xmlsize);
- plist_free(dict);
- if (xml) {
- res = send_pkt(client, 0, MESSAGE_PLIST, xml, xmlsize);
- free(xml);
- } else {
- usbmuxd_log(LL_ERROR, "%s: Could not convert plist to xml", __func__);
- }
- } else
-#endif
- {
- /* binary packet */
- struct usbmuxd_device_record dmsg;
- memset(&dmsg, 0, sizeof(dmsg));
- dmsg.device_id = dev->id;
- strncpy(dmsg.serial_number, dev->serial, 256);
- dmsg.serial_number[255] = 0;
- dmsg.location = dev->location;
- dmsg.product_id = dev->pid;
- res = send_pkt(client, 0, MESSAGE_DEVICE_ADD, &dmsg, sizeof(dmsg));
- }
- return res;
-}
-
-static int notify_device_remove(struct mux_client *client, uint32_t device_id)
-{
- int res = -1;
-#ifdef HAVE_PLIST
- if (client->proto_version == 1) {
- /* XML plist packet */
- char *xml = NULL;
- uint32_t xmlsize = 0;
- plist_t dict = plist_new_dict();
- plist_dict_insert_item(dict, "MessageType", plist_new_string("Detached"));
- plist_dict_insert_item(dict, "DeviceID", plist_new_uint(device_id));
- plist_to_xml(dict, &xml, &xmlsize);
- plist_free(dict);
- if (xml) {
- res = send_pkt(client, 0, MESSAGE_PLIST, xml, xmlsize);
- free(xml);
- } else {
- usbmuxd_log(LL_ERROR, "%s: Could not convert plist to xml", __func__);
- }
- } else
-#endif
- {
- /* binary packet */
- res = send_pkt(client, 0, MESSAGE_DEVICE_REMOVE, &device_id, sizeof(uint32_t));
- }
- return res;
-}
-
-static int start_listen(struct mux_client *client)
-{
- struct device_info *devs;
- struct device_info *dev;
- int count, i;
-
- client->state = CLIENT_LISTEN;
- count = device_get_count();
- if(!count)
- return 0;
- devs = malloc(sizeof(struct device_info) * count);
- count = device_get_list(devs);
-
- // going to need a larger buffer for many devices
- int needed_buffer = count * (sizeof(struct usbmuxd_device_record) + sizeof(struct usbmuxd_header)) + REPLY_BUF_SIZE;
- if(client->ob_capacity < needed_buffer) {
- usbmuxd_log(LL_DEBUG, "Enlarging client %d reply buffer %d -> %d to make space for device notifications", client->fd, client->ob_capacity, needed_buffer);
- client->ob_buf = realloc(client->ob_buf, needed_buffer);
- client->ob_capacity = needed_buffer;
- }
- dev = devs;
- for(i=0; i<count; i++) {
- if(notify_device_add(client, dev++) < 0) {
- free(devs);
- return -1;
- }
- }
- free(devs);
- return count;
-}
-
-static int client_command(struct mux_client *client, struct usbmuxd_header *hdr)
-{
- int res;
- usbmuxd_log(LL_DEBUG, "Client command in fd %d len %d ver %d msg %d tag %d", client->fd, hdr->length, hdr->version, hdr->message, hdr->tag);
-
- if(client->state != CLIENT_COMMAND) {
- usbmuxd_log(LL_ERROR, "Client %d command received in the wrong state", client->fd);
- if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
- return -1;
- client_close(client);
- return -1;
- }
-
- struct usbmuxd_connect_request *ch;
-#ifdef HAVE_PLIST
- char *payload;
- uint32_t payload_size;
-#endif
-
- switch(hdr->message) {
-#ifdef HAVE_PLIST
- case MESSAGE_PLIST:
- client->proto_version = 1;
- payload = (char*)(hdr) + sizeof(struct usbmuxd_header);
- payload_size = hdr->length - sizeof(struct usbmuxd_header);
- plist_t dict = NULL;
- plist_from_xml(payload, payload_size, &dict);
- if (!dict) {
- usbmuxd_log(LL_ERROR, "Could not parse plist from payload!");
- return -1;
- } else {
- char *message = NULL;
- plist_t node = plist_dict_get_item(dict, "MessageType");
- plist_get_string_val(node, &message);
- if (!message) {
- usbmuxd_log(LL_ERROR, "Could not extract MessageType from plist!");
- plist_free(dict);
- return -1;
- }
- if (!strcmp(message, "Listen")) {
- free(message);
- plist_free(dict);
- if (send_result(client, hdr->tag, 0) < 0)
- return -1;
- usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd);
- return start_listen(client);
- } else if (!strcmp(message, "Connect")) {
- uint64_t val;
- uint16_t portnum = 0;
- uint32_t device_id = 0;
- free(message);
- // get device id
- node = plist_dict_get_item(dict, "DeviceID");
- if (!node) {
- usbmuxd_log(LL_ERROR, "Received connect request without device_id!");
- plist_free(dict);
- if (send_result(client, hdr->tag, RESULT_BADDEV) < 0)
- return -1;
- return 0;
- }
- val = 0;
- plist_get_uint_val(node, &val);
- device_id = (uint32_t)val;
-
- // get port number
- node = plist_dict_get_item(dict, "PortNumber");
- if (!node) {
- usbmuxd_log(LL_ERROR, "Received connect request without port number!");
- plist_free(dict);
- if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
- return -1;
- return 0;
- }
- val = 0;
- plist_get_uint_val(node, &val);
- portnum = (uint16_t)val;
-
- usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, device_id, ntohs(portnum));
- res = device_start_connect(device_id, ntohs(portnum), client);
- if(res < 0) {
- if (send_result(client, hdr->tag, -res) < 0)
- return -1;
- } else {
- client->connect_tag = hdr->tag;
- client->connect_device = device_id;
- client->state = CLIENT_CONNECTING1;
- }
- return 0;
- } else {
- usbmuxd_log(LL_ERROR, "Unexpected command '%s' received!", message);
- free(message);
- plist_free(dict);
- if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
- return -1;
- return 0;
- }
- }
- // should not be reached?!
- return -1;
-#endif
- case MESSAGE_LISTEN:
- if(send_result(client, hdr->tag, 0) < 0)
- return -1;
- usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd);
- return start_listen(client);
- case MESSAGE_CONNECT:
- ch = (void*)hdr;
- usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, ch->device_id, ntohs(ch->port));
- res = device_start_connect(ch->device_id, ntohs(ch->port), client);
- if(res < 0) {
- if(send_result(client, hdr->tag, -res) < 0)
- return -1;
- } else {
- client->connect_tag = hdr->tag;
- client->connect_device = ch->device_id;
- client->state = CLIENT_CONNECTING1;
- }
- return 0;
- default:
- usbmuxd_log(LL_ERROR, "Client %d invalid command %d", client->fd, hdr->message);
- if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
- return -1;
- return 0;
- }
- return -1;
-}
-
-static void process_send(struct mux_client *client)
-{
- int res;
- if(!client->ob_size) {
- usbmuxd_log(LL_WARNING, "Client %d OUT process but nothing to send?", client->fd);
- client->events &= ~POLLOUT;
- return;
- }
- res = send(client->fd, client->ob_buf, client->ob_size, 0);
- if(res <= 0) {
- usbmuxd_log(LL_ERROR, "Send to client fd %d failed: %d %s", client->fd, res, strerror(errno));
- client_close(client);
- return;
- }
- if(res == client->ob_size) {
- client->ob_size = 0;
- client->events &= ~POLLOUT;
- if(client->state == CLIENT_CONNECTING2) {
- usbmuxd_log(LL_DEBUG, "Client %d switching to CONNECTED state", client->fd);
- client->state = CLIENT_CONNECTED;
- client->events = client->devents;
- // no longer need this
- free(client->ob_buf);
- client->ob_buf = NULL;
- }
- } else {
- client->ob_size -= res;
- memmove(client->ob_buf, client->ob_buf + res, client->ob_size);
- }
-}
-static void process_recv(struct mux_client *client)
-{
- int res;
- int did_read = 0;
- if(client->ib_size < sizeof(struct usbmuxd_header)) {
- res = recv(client->fd, client->ib_buf + client->ib_size, sizeof(struct usbmuxd_header) - client->ib_size, 0);
- if(res <= 0) {
- if(res < 0)
- usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno));
- else
- usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd);
- client_close(client);
- return;
- }
- client->ib_size += res;
- if(client->ib_size < sizeof(struct usbmuxd_header))
- return;
- did_read = 1;
- }
- struct usbmuxd_header *hdr = (void*)client->ib_buf;
-#ifdef HAVE_PLIST
- if((hdr->version != 0) && (hdr->version != 1)) {
- usbmuxd_log(LL_INFO, "Client %d version mismatch: expected 0 or 1, got %d", client->fd, hdr->version);
-#else
- if(hdr->version != USBMUXD_PROTOCOL_VERSION) {
- usbmuxd_log(LL_INFO, "Client %d version mismatch: expected %d, got %d", client->fd, USBMUXD_PROTOCOL_VERSION, hdr->version);
-#endif
- client_close(client);
- return;
- }
- if(hdr->length > client->ib_capacity) {
- usbmuxd_log(LL_INFO, "Client %d message is too long (%d bytes)", client->fd, hdr->length);
- client_close(client);
- return;
- }
- if(hdr->length < sizeof(struct usbmuxd_header)) {
- usbmuxd_log(LL_ERROR, "Client %d message is too short (%d bytes)", client->fd, hdr->length);
- client_close(client);
- return;
- }
- if(client->ib_size < hdr->length) {
- if(did_read)
- return; //maybe we would block, so defer to next loop
- res = recv(client->fd, client->ib_buf + client->ib_size, hdr->length - client->ib_size, 0);
- if(res < 0) {
- usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno));
- client_close(client);
- return;
- } else if(res == 0) {
- usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd);
- client_close(client);
- return;
- }
- client->ib_size += res;
- if(client->ib_size < hdr->length)
- return;
- }
- client_command(client, hdr);
- client->ib_size = 0;
-}
-
-void client_process(int fd, short events)
-{
- struct mux_client *client = NULL;
- FOREACH(struct mux_client *lc, &client_list) {
- if(lc->fd == fd) {
- client = lc;
- break;
- }
- } ENDFOREACH
-
- if(!client) {
- usbmuxd_log(LL_INFO, "client_process: fd %d not found in client list", fd);
- return;
- }
-
- if(client->state == CLIENT_CONNECTED) {
- usbmuxd_log(LL_SPEW, "client_process in CONNECTED state");
- device_client_process(client->connect_device, client, events);
- } else {
- if(events & POLLIN) {
- process_recv(client);
- } else if(events & POLLOUT) { //not both in case client died as part of process_recv
- process_send(client);
- }
- }
-
-}
-
-void client_device_add(struct device_info *dev)
-{
- usbmuxd_log(LL_DEBUG, "client_device_add: id %d, location 0x%x, serial %s", dev->id, dev->location, dev->serial);
- FOREACH(struct mux_client *client, &client_list) {
- if(client->state == CLIENT_LISTEN)
- notify_device_add(client, dev);
- } ENDFOREACH
-}
-void client_device_remove(int device_id)
-{
- uint32_t id = device_id;
- usbmuxd_log(LL_DEBUG, "client_device_remove: id %d", device_id);
- FOREACH(struct mux_client *client, &client_list) {
- if(client->state == CLIENT_LISTEN)
- notify_device_remove(client, id);
- } ENDFOREACH
-}
-
-
-void client_init(void)
-{
- usbmuxd_log(LL_DEBUG, "client_init");
- collection_init(&client_list);
-}
-
-void client_shutdown(void)
-{
- usbmuxd_log(LL_DEBUG, "client_shutdown");
- FOREACH(struct mux_client *client, &client_list) {
- client_close(client);
- } ENDFOREACH
- collection_free(&client_list);
-}
diff --git a/daemon/client.h b/daemon/client.h
deleted file mode 100644
index 60d8348..0000000
--- a/daemon/client.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
-
-#ifndef __CLIENT_H__
-#define __CLIENT_H__
-
-#include <stdint.h>
-#include "usbmuxd-proto.h"
-
-struct device_info;
-struct mux_client;
-
-int client_read(struct mux_client *client, void *buffer, uint32_t len);
-int client_write(struct mux_client *client, void *buffer, uint32_t len);
-int client_set_events(struct mux_client *client, short events);
-void client_close(struct mux_client *client);
-int client_notify_connect(struct mux_client *client, enum usbmuxd_result result);
-
-void client_device_add(struct device_info *dev);
-void client_device_remove(int device_id);
-
-int client_accept(int fd);
-void client_get_fds(struct fdlist *list);
-void client_process(int fd, short events);
-
-void client_init(void);
-void client_shutdown(void);
-
-#endif
diff --git a/daemon/device.h b/daemon/device.h
deleted file mode 100644
index ea77069..0000000
--- a/daemon/device.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
-
-#ifndef __DEVICE_H__
-#define __DEVICE_H__
-
-#include "usb.h"
-#include "client.h"
-
-struct device_info {
- int id;
- const char *serial;
- uint32_t location;
- uint16_t pid;
-};
-
-void device_data_input(struct usb_device *dev, unsigned char *buf, uint32_t length);
-
-int device_add(struct usb_device *dev);
-void device_remove(struct usb_device *dev);
-
-int device_start_connect(int device_id, uint16_t port, struct mux_client *client);
-void device_client_process(int device_id, struct mux_client *client, short events);
-void device_abort_connect(int device_id, struct mux_client *client);
-
-int device_get_count(void);
-int device_get_list(struct device_info *p);
-
-int device_get_timeout(void);
-void device_check_timeouts(void);
-
-void device_init(void);
-void device_kill_connections(void);
-void device_shutdown(void);
-#endif
diff --git a/daemon/log.h b/daemon/log.h
deleted file mode 100644
index eeefa41..0000000
--- a/daemon/log.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
-
-#ifndef __LOG_H__
-#define __LOG_H__
-
-enum loglevel {
- LL_FATAL = 0,
- LL_ERROR,
- LL_WARNING,
- LL_NOTICE,
- LL_INFO,
- LL_DEBUG,
- LL_SPEW,
- LL_FLOOD,
-};
-
-extern int log_level;
-
-void log_enable_syslog();
-void log_disable_syslog();
-
-void usbmuxd_log(enum loglevel level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
-
-
-#endif
diff --git a/daemon/main.c b/daemon/main.c
deleted file mode 100644
index 140bee1..0000000
--- a/daemon/main.c
+++ /dev/null
@@ -1,618 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
-
-#define _BSD_SOURCE
-#define _GNU_SOURCE
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <stdio.h>
-#include <errno.h>
-#include <string.h>
-#include <stdlib.h>
-#include <signal.h>
-#include <unistd.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <getopt.h>
-#include <pwd.h>
-#include <grp.h>
-
-#include "log.h"
-#include "usb.h"
-#include "device.h"
-#include "client.h"
-
-static const char *socket_path = "/var/run/usbmuxd";
-static const char *lockfile = "/var/run/usbmuxd.pid";
-
-int should_exit;
-int should_discover;
-
-static int verbose = 0;
-static int foreground = 0;
-static int drop_privileges = 0;
-static const char *drop_user = NULL;
-static int opt_udev = 0;
-static int opt_exit = 0;
-static int exit_signal = 0;
-static int daemon_pipe;
-
-static int report_to_parent = 0;
-
-int create_socket(void) {
- struct sockaddr_un bind_addr;
- int listenfd;
-
- if(unlink(socket_path) == -1 && errno != ENOENT) {
- usbmuxd_log(LL_FATAL, "unlink(%s) failed: %s", socket_path, strerror(errno));
- return -1;
- }
-
- listenfd = socket(AF_UNIX, SOCK_STREAM, 0);
- if (listenfd == -1) {
- usbmuxd_log(LL_FATAL, "socket() failed: %s", strerror(errno));
- return -1;
- }
-
- bzero(&bind_addr, sizeof(bind_addr));
- bind_addr.sun_family = AF_UNIX;
- strcpy(bind_addr.sun_path, socket_path);
- if (bind(listenfd, (struct sockaddr*)&bind_addr, sizeof(bind_addr)) != 0) {
- usbmuxd_log(LL_FATAL, "bind() failed: %s", strerror(errno));
- return -1;
- }
-
- // Start listening
- if (listen(listenfd, 5) != 0) {
- usbmuxd_log(LL_FATAL, "listen() failed: %s", strerror(errno));
- return -1;
- }
-
- chmod(socket_path, 0666);
-
- return listenfd;
-}
-
-void handle_signal(int sig)
-{
- if (sig != SIGUSR1 && sig != SIGUSR2) {
- usbmuxd_log(LL_NOTICE,"Caught signal %d, exiting", sig);
- should_exit = 1;
- } else {
- if(opt_udev) {
- if (sig == SIGUSR1) {
- usbmuxd_log(LL_INFO, "Caught SIGUSR1, checking if we can terminate (no more devices attached)...");
- if (device_get_count() > 0) {
- // we can't quit, there are still devices attached.
- usbmuxd_log(LL_NOTICE, "Refusing to terminate, there are still devices attached. Kill me with signal 15 (TERM) to force quit.");
- } else {
- // it's safe to quit
- should_exit = 1;
- }
- } else if (sig == SIGUSR2) {
- usbmuxd_log(LL_INFO, "Caught SIGUSR2, scheduling device discovery");
- should_discover = 1;
- }
- } else {
- usbmuxd_log(LL_INFO, "Caught SIGUSR1/2 but we weren't started in --udev mode, ignoring");
- }
- }
-}
-
-void set_signal_handlers(void)
-{
- struct sigaction sa;
- sigset_t set;
-
- // Mask all signals we handle. They will be unmasked by ppoll().
- sigemptyset(&set);
- sigaddset(&set, SIGINT);
- sigaddset(&set, SIGQUIT);
- sigaddset(&set, SIGTERM);
- sigaddset(&set, SIGUSR1);
- sigaddset(&set, SIGUSR2);
- sigprocmask(SIG_SETMASK, &set, NULL);
-
- memset(&sa, 0, sizeof(struct sigaction));
- sa.sa_handler = handle_signal;
- sigaction(SIGINT, &sa, NULL);
- sigaction(SIGQUIT, &sa, NULL);
- sigaction(SIGTERM, &sa, NULL);
- sigaction(SIGUSR1, &sa, NULL);
- sigaction(SIGUSR2, &sa, NULL);
-}
-
-#if defined(__FreeBSD__) || defined(__APPLE__)
-static int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask)
-{
- int ready;
- sigset_t origmask;
- int to = timeout->tv_sec*1000 + timeout->tv_nsec/1000000;
-
- sigprocmask(SIG_SETMASK, sigmask, &origmask);
- ready = poll(fds, nfds, to);
- sigprocmask(SIG_SETMASK, &origmask, NULL);
-
- return ready;
-}
-#endif
-
-int main_loop(int listenfd)
-{
- int to, cnt, i, dto;
- struct fdlist pollfds;
- struct timespec tspec;
-
- sigset_t empty_sigset;
- sigemptyset(&empty_sigset); // unmask all signals
-
- fdlist_create(&pollfds);
- while(!should_exit) {
- usbmuxd_log(LL_FLOOD, "main_loop iteration");
- to = usb_get_timeout();
- usbmuxd_log(LL_FLOOD, "USB timeout is %d ms", to);
- dto = device_get_timeout();
- usbmuxd_log(LL_FLOOD, "Device timeout is %d ms", to);
- if(dto < to)
- to = dto;
-
- fdlist_reset(&pollfds);
- fdlist_add(&pollfds, FD_LISTEN, listenfd, POLLIN);
- usb_get_fds(&pollfds);
- client_get_fds(&pollfds);
- usbmuxd_log(LL_FLOOD, "fd count is %d", pollfds.count);
-
- tspec.tv_sec = to / 1000;
- tspec.tv_nsec = (to % 1000) * 1000000;
- cnt = ppoll(pollfds.fds, pollfds.count, &tspec, &empty_sigset);
- usbmuxd_log(LL_FLOOD, "poll() returned %d", cnt);
- if(cnt == -1) {
- if(errno == EINTR) {
- if(should_exit) {
- usbmuxd_log(LL_INFO, "Event processing interrupted");
- break;
- }
- if(should_discover) {
- should_discover = 0;
- usbmuxd_log(LL_INFO, "Device discovery triggered by udev");
- usb_discover();
- }
- }
- } else if(cnt == 0) {
- if(usb_process() < 0) {
- usbmuxd_log(LL_FATAL, "usb_process() failed");
- fdlist_free(&pollfds);
- return -1;
- }
- device_check_timeouts();
- } else {
- int done_usb = 0;
- for(i=0; i<pollfds.count; i++) {
- if(pollfds.fds[i].revents) {
- if(!done_usb && pollfds.owners[i] == FD_USB) {
- if(usb_process() < 0) {
- usbmuxd_log(LL_FATAL, "usb_process() failed");
- fdlist_free(&pollfds);
- return -1;
- }
- done_usb = 1;
- }
- if(pollfds.owners[i] == FD_LISTEN) {
- if(client_accept(listenfd) < 0) {
- usbmuxd_log(LL_FATAL, "client_accept() failed");
- fdlist_free(&pollfds);
- return -1;
- }
- }
- if(pollfds.owners[i] == FD_CLIENT) {
- client_process(pollfds.fds[i].fd, pollfds.fds[i].revents);
- }
- }
- }
- }
- }
- fdlist_free(&pollfds);
- return 0;
-}
-
-/**
- * make this program run detached from the current console
- */
-static int daemonize(void)
-{
- pid_t pid;
- pid_t sid;
- int pfd[2];
- int res;
-
- // already a daemon
- if (getppid() == 1)
- return 0;
-
- if((res = pipe(pfd)) < 0) {
- usbmuxd_log(LL_FATAL, "pipe() failed.");
- return res;
- }
-
- pid = fork();
- if (pid < 0) {
- usbmuxd_log(LL_FATAL, "fork() failed.");
- return pid;
- }
-
- if (pid > 0) {
- // exit parent process
- int status;
- close(pfd[1]);
-
- if((res = read(pfd[0],&status,sizeof(int))) != sizeof(int)) {
- fprintf(stderr, "usbmuxd: ERROR: Failed to get init status from child, check syslog for messages.\n");
- exit(1);
- }
- if(status != 0)
- fprintf(stderr, "usbmuxd: ERROR: Child process exited with error %d, check syslog for messages.\n", status);
- exit(status);
- }
- // At this point we are executing as the child process
- // but we need to do one more fork
-
- daemon_pipe = pfd[1];
- close(pfd[0]);
- report_to_parent = 1;
-
- // Change the file mode mask
- umask(0);
-
- // Create a new SID for the child process
- sid = setsid();
- if (sid < 0) {
- usbmuxd_log(LL_FATAL, "setsid() failed.");
- return -1;
- }
-
- pid = fork();
- if (pid < 0) {
- usbmuxd_log(LL_FATAL, "fork() failed (second).");
- return pid;
- }
-
- if (pid > 0) {
- // exit parent process
- close(daemon_pipe);
- exit(0);
- }
-
- // Change the current working directory.
- if ((chdir("/")) < 0) {
- usbmuxd_log(LL_FATAL, "chdir() failed");
- return -2;
- }
- // Redirect standard files to /dev/null
- if (!freopen("/dev/null", "r", stdin)) {
- usbmuxd_log(LL_FATAL, "Redirection of stdin failed.");
- return -3;
- }
- if (!freopen("/dev/null", "w", stdout)) {
- usbmuxd_log(LL_FATAL, "Redirection of stdout failed.");
- return -3;
- }
-
- return 0;
-}
-
-static int notify_parent(int status)
-{
- int res;
-
- report_to_parent = 0;
- if ((res = write(daemon_pipe, &status, sizeof(int))) != sizeof(int)) {
- usbmuxd_log(LL_FATAL, "Could not notify parent!");
- if(res >= 0)
- return -2;
- else
- return res;
- }
- close(daemon_pipe);
- if (!freopen("/dev/null", "w", stderr)) {
- usbmuxd_log(LL_FATAL, "Redirection of stderr failed.");
- return -1;
- }
- return 0;
-}
-
-static void usage()
-{
- printf("usage: usbmuxd [options]\n");
- printf("\t-h|--help Print this message.\n");
- printf("\t-v|--verbose Be verbose (use twice or more to increase).\n");
- printf("\t-f|--foreground Do not daemonize (implies one -v).\n");
- printf("\t-U|--user USER Change to this user after startup (needs usb privileges).\n");
- printf("\t-u|--udev Run in udev operation mode.\n");
- printf("\t-x|--exit Tell a running instance to exit if there are no devices\n");
- printf("\t connected (must be in udev mode).\n");
- printf("\t-X|--force-exit Tell a running instance to exit, even if there are still\n");
- printf("\t devices connected (always works).\n");
- printf("\n");
-}
-
-static void parse_opts(int argc, char **argv)
-{
- static struct option longopts[] = {
- {"help", 0, NULL, 'h'},
- {"foreground", 0, NULL, 'f'},
- {"verbose", 0, NULL, 'v'},
- {"user", 2, NULL, 'U'},
- {"udev", 0, NULL, 'u'},
- {"exit", 0, NULL, 'x'},
- {"force-exit", 0, NULL, 'X'},
- {NULL, 0, NULL, 0}
- };
- int c;
-
- while (1) {
- c = getopt_long(argc, argv, "hfvuU:xX", longopts, (int *) 0);
- if (c == -1) {
- break;
- }
-
- switch (c) {
- case 'h':
- usage();
- exit(0);
- case 'f':
- foreground = 1;
- break;
- case 'v':
- ++verbose;
- break;
- case 'U':
- drop_privileges = 1;
- drop_user = optarg;
- break;
- case 'u':
- opt_udev = 1;
- break;
- case 'x':
- opt_exit = 1;
- exit_signal = SIGUSR1;
- break;
- case 'X':
- opt_exit = 1;
- exit_signal = SIGTERM;
- break;
- default:
- usage();
- exit(2);
- }
- }
-}
-
-int main(int argc, char *argv[])
-{
- int listenfd;
- int res = 0;
- int lfd;
- struct flock lock;
- char pids[10];
-
- parse_opts(argc, argv);
-
- argc -= optind;
- argv += optind;
-
- if (!foreground) {
- verbose += LL_WARNING;
- log_enable_syslog();
- } else {
- verbose += LL_NOTICE;
- }
-
- /* set log level to specified verbosity */
- log_level = verbose;
-
- usbmuxd_log(LL_NOTICE, "usbmuxd v%s starting up", USBMUXD_VERSION);
- should_exit = 0;
- should_discover = 0;
-
- set_signal_handlers();
- signal(SIGPIPE, SIG_IGN);
-
- res = lfd = open(lockfile, O_WRONLY|O_CREAT, 0644);
- if(res == -1) {
- usbmuxd_log(LL_FATAL, "Could not open lockfile");
- goto terminate;
- }
- lock.l_type = F_WRLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = 0;
- lock.l_len = 0;
- fcntl(lfd, F_GETLK, &lock);
- close(lfd);
- if (lock.l_type != F_UNLCK) {
- if (opt_exit) {
- if (lock.l_pid && !kill(lock.l_pid, 0)) {
- usbmuxd_log(LL_NOTICE, "Sending signal %d to instance with pid %d", exit_signal, lock.l_pid);
- res = 0;
- if (kill(lock.l_pid, exit_signal) < 0) {
- usbmuxd_log(LL_FATAL, "Could not deliver signal %d to pid %d", exit_signal, lock.l_pid);
- res = -1;
- }
- goto terminate;
- } else {
- usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
- res = -1;
- goto terminate;
- }
- } else {
- if (!opt_udev) {
- usbmuxd_log(LL_ERROR, "Another instance is already running (pid %d). exiting.", lock.l_pid);
- res = -1;
- } else {
- usbmuxd_log(LL_NOTICE, "Another instance is already running (pid %d). Telling it to check for devices.", lock.l_pid);
- if (lock.l_pid && !kill(lock.l_pid, 0)) {
- usbmuxd_log(LL_NOTICE, "Sending signal SIGUSR2 to instance with pid %d", lock.l_pid);
- res = 0;
- if (kill(lock.l_pid, SIGUSR2) < 0) {
- usbmuxd_log(LL_FATAL, "Could not deliver SIGUSR2 to pid %d", lock.l_pid);
- res = -1;
- }
- } else {
- usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
- res = -1;
- }
- }
- goto terminate;
- }
- }
- unlink(lockfile);
-
- if (opt_exit) {
- usbmuxd_log(LL_NOTICE, "No running instance found, none killed. exiting.");
- goto terminate;
- }
-
- if (!foreground) {
- if ((res = daemonize()) < 0) {
- fprintf(stderr, "usbmuxd: FATAL: Could not daemonize!\n");
- usbmuxd_log(LL_FATAL, "Could not daemonize!");
- goto terminate;
- }
- }
-
- // now open the lockfile and place the lock
- res = lfd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644);
- if(res < 0) {
- usbmuxd_log(LL_FATAL, "Could not open lockfile");
- goto terminate;
- }
- lock.l_type = F_WRLCK;
- lock.l_whence = SEEK_SET;
- lock.l_start = 0;
- lock.l_len = 0;
- if ((res = fcntl(lfd, F_SETLK, &lock)) < 0) {
- usbmuxd_log(LL_FATAL, "Lockfile locking failed!");
- goto terminate;
- }
- sprintf(pids, "%d", getpid());
- if ((res = write(lfd, pids, strlen(pids))) != strlen(pids)) {
- usbmuxd_log(LL_FATAL, "Could not write pidfile!");
- if(res >= 0)
- res = -2;
- goto terminate;
- }
-
- usbmuxd_log(LL_INFO, "Creating socket");
- res = listenfd = create_socket();
- if(listenfd < 0)
- goto terminate;
-
- // drop elevated privileges
- if (drop_privileges && (getuid() == 0 || geteuid() == 0)) {
- struct passwd *pw;
- if (!drop_user) {
- usbmuxd_log(LL_FATAL, "No user to drop privileges to?");
- res = -1;
- goto terminate;
- }
- pw = getpwnam(drop_user);
- if (!pw) {
- usbmuxd_log(LL_FATAL, "Dropping privileges failed, check if user '%s' exists!", drop_user);
- res = -1;
- goto terminate;
- }
- if (pw->pw_uid == 0) {
- usbmuxd_log(LL_INFO, "Not dropping privileges to root");
- } else {
- if ((res = initgroups(drop_user, pw->pw_gid)) < 0) {
- usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set supplementary groups)");
- goto terminate;
- }
- if ((res = setgid(pw->pw_gid)) < 0) {
- usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set group ID to %d)", pw->pw_gid);
- goto terminate;
- }
- if ((res = setuid(pw->pw_uid)) < 0) {
- usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set user ID to %d)", pw->pw_uid);
- goto terminate;
- }
-
- // security check
- if (setuid(0) != -1) {
- usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
- res = -1;
- goto terminate;
- }
- if (getuid() != pw->pw_uid || getgid() != pw->pw_gid) {
- usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
- res = -1;
- goto terminate;
- }
- usbmuxd_log(LL_NOTICE, "Successfully dropped privileges to '%s'", drop_user);
- }
- }
-
- client_init();
- device_init();
- usbmuxd_log(LL_INFO, "Initializing USB");
- if((res = usb_init()) < 0)
- goto terminate;
-
- usbmuxd_log(LL_INFO, "%d device%s detected", res, (res==1)?"":"s");
-
- usbmuxd_log(LL_NOTICE, "Initialization complete");
-
- if (report_to_parent)
- if((res = notify_parent(0)) < 0)
- goto terminate;
-
- if(opt_udev)
- usb_autodiscover(0); // discovery triggered by udev
-
- res = main_loop(listenfd);
- if(res < 0)
- usbmuxd_log(LL_FATAL, "main_loop failed");
-
- usbmuxd_log(LL_NOTICE, "usbmuxd shutting down");
- device_kill_connections();
- usb_shutdown();
- device_shutdown();
- client_shutdown();
- usbmuxd_log(LL_NOTICE, "Shutdown complete");
-
-terminate:
- log_disable_syslog();
-
- if (res < 0)
- res = -res;
- else
- res = 0;
- if (report_to_parent)
- notify_parent(res);
-
- return res;
-}
diff --git a/daemon/usb-linux.c b/daemon/usb-linux.c
deleted file mode 100644
index 0860b46..0000000
--- a/daemon/usb-linux.c
+++ /dev/null
@@ -1,589 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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 <stdint.h>
-#include <string.h>
-
-#include <libusb.h>
-
-#include "usb.h"
-#include "log.h"
-#include "device.h"
-
-// interval for device connection/disconnection polling, in milliseconds
-// we need this because there is currently no asynchronous device discovery mechanism in libusb
-#define DEVICE_POLL_TIME 1000
-
-struct usb_device {
- libusb_device_handle *dev;
- uint8_t bus, address;
- uint16_t vid, pid;
- char serial[256];
- int alive;
- uint8_t interface, ep_in, ep_out;
- struct libusb_transfer *rx_xfer;
- struct collection tx_xfers;
- int wMaxPacketSize;
-};
-
-static struct collection device_list;
-
-static struct timeval next_dev_poll_time;
-
-static int devlist_failures;
-static int device_polling;
-
-static void usb_disconnect(struct usb_device *dev)
-{
- if(!dev->dev) {
- return;
- }
-
- // kill the rx xfer and tx xfers and try to make sure the callbacks get called before we free the device
- if(dev->rx_xfer) {
- usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling RX xfer");
- libusb_cancel_transfer(dev->rx_xfer);
- }
- FOREACH(struct libusb_transfer *xfer, &dev->tx_xfers) {
- usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling TX xfer %p", xfer);
- libusb_cancel_transfer(xfer);
- } ENDFOREACH
-
- while(dev->rx_xfer || collection_count(&dev->tx_xfers)) {
- struct timeval tv;
- int res;
-
- tv.tv_sec = 0;
- tv.tv_usec = 1000;
- if((res = libusb_handle_events_timeout(NULL, &tv)) < 0) {
- usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout for usb_disconnect failed: %d", res);
- break;
- }
- }
- collection_free(&dev->tx_xfers);
- libusb_release_interface(dev->dev, dev->interface);
- libusb_close(dev->dev);
- dev->dev = NULL;
- collection_remove(&device_list, dev);
- free(dev);
-}
-
-static void tx_callback(struct libusb_transfer *xfer)
-{
- struct usb_device *dev = xfer->user_data;
- usbmuxd_log(LL_SPEW, "TX callback dev %d-%d len %d -> %d status %d", dev->bus, dev->address, xfer->length, xfer->actual_length, xfer->status);
- if(xfer->status != LIBUSB_TRANSFER_COMPLETED) {
- switch(xfer->status) {
- case LIBUSB_TRANSFER_COMPLETED: //shut up compiler
- case LIBUSB_TRANSFER_ERROR:
- // funny, this happens when we disconnect the device while waiting for a transfer, sometimes
- usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to error or disconnect", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_TIMED_OUT:
- usbmuxd_log(LL_ERROR, "TX transfer timed out for device %d-%d", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_CANCELLED:
- usbmuxd_log(LL_DEBUG, "Device %d-%d TX transfer cancelled", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_STALL:
- usbmuxd_log(LL_ERROR, "TX transfer stalled for device %d-%d", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_NO_DEVICE:
- // other times, this happens, and also even when we abort the transfer after device removal
- usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to disconnect", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_OVERFLOW:
- usbmuxd_log(LL_ERROR, "TX transfer overflow for device %d-%d", dev->bus, dev->address);
- break;
- // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad)
- }
- // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events
- // we'll do device_remove there too
- dev->alive = 0;
- }
- if(xfer->buffer)
- free(xfer->buffer);
- collection_remove(&dev->tx_xfers, xfer);
- libusb_free_transfer(xfer);
-}
-
-int usb_send(struct usb_device *dev, const unsigned char *buf, int length)
-{
- int res;
- struct libusb_transfer *xfer = libusb_alloc_transfer(0);
- libusb_fill_bulk_transfer(xfer, dev->dev, dev->ep_out, (void*)buf, length, tx_callback, dev, 0);
- if((res = libusb_submit_transfer(xfer)) < 0) {
- usbmuxd_log(LL_ERROR, "Failed to submit TX transfer %p len %d to device %d-%d: %d", buf, length, dev->bus, dev->address, res);
- libusb_free_transfer(xfer);
- return res;
- }
- collection_add(&dev->tx_xfers, xfer);
- if (length % dev->wMaxPacketSize == 0) {
- usbmuxd_log(LL_DEBUG, "Send ZLP");
- // Send Zero Length Packet
- xfer = libusb_alloc_transfer(0);
- void *buffer = malloc(1);
- libusb_fill_bulk_transfer(xfer, dev->dev, dev->ep_out, buffer, 0, tx_callback, dev, 0);
- if((res = libusb_submit_transfer(xfer)) < 0) {
- usbmuxd_log(LL_ERROR, "Failed to submit TX ZLP transfer to device %d-%d: %d", dev->bus, dev->address, res);
- libusb_free_transfer(xfer);
- return res;
- }
- collection_add(&dev->tx_xfers, xfer);
- }
- return 0;
-}
-
-static void rx_callback(struct libusb_transfer *xfer)
-{
- struct usb_device *dev = xfer->user_data;
- usbmuxd_log(LL_SPEW, "RX callback dev %d-%d len %d status %d", dev->bus, dev->address, xfer->actual_length, xfer->status);
- if(xfer->status == LIBUSB_TRANSFER_COMPLETED) {
- device_data_input(dev, xfer->buffer, xfer->actual_length);
- libusb_submit_transfer(xfer);
- } else {
- switch(xfer->status) {
- case LIBUSB_TRANSFER_COMPLETED: //shut up compiler
- case LIBUSB_TRANSFER_ERROR:
- // funny, this happens when we disconnect the device while waiting for a transfer, sometimes
- usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to error or disconnect", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_TIMED_OUT:
- usbmuxd_log(LL_ERROR, "RX transfer timed out for device %d-%d", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_CANCELLED:
- usbmuxd_log(LL_DEBUG, "Device %d-%d RX transfer cancelled", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_STALL:
- usbmuxd_log(LL_ERROR, "RX transfer stalled for device %d-%d", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_NO_DEVICE:
- // other times, this happens, and also even when we abort the transfer after device removal
- usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to disconnect", dev->bus, dev->address);
- break;
- case LIBUSB_TRANSFER_OVERFLOW:
- usbmuxd_log(LL_ERROR, "RX transfer overflow for device %d-%d", dev->bus, dev->address);
- break;
- // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad)
- }
- free(xfer->buffer);
- dev->rx_xfer = NULL;
- libusb_free_transfer(xfer);
- // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events
- // we'll do device_remove there too
- dev->alive = 0;
- }
-}
-
-static int start_rx(struct usb_device *dev)
-{
- int res;
- void *buf;
- dev->rx_xfer = libusb_alloc_transfer(0);
- buf = malloc(USB_MRU);
- libusb_fill_bulk_transfer(dev->rx_xfer, dev->dev, dev->ep_in, buf, USB_MRU, rx_callback, dev, 0);
- if((res = libusb_submit_transfer(dev->rx_xfer)) != 0) {
- usbmuxd_log(LL_ERROR, "Failed to submit RX transfer to device %d-%d: %d", dev->bus, dev->address, res);
- libusb_free_transfer(dev->rx_xfer);
- dev->rx_xfer = NULL;
- return res;
- }
- return 0;
-}
-
-int usb_discover(void)
-{
- int cnt, i, j, res;
- int valid_count = 0;
- libusb_device **devs;
-
- cnt = libusb_get_device_list(NULL, &devs);
- if(cnt < 0) {
- usbmuxd_log(LL_WARNING, "Could not get device list: %d", cnt);
- devlist_failures++;
- // sometimes libusb fails getting the device list if you've just removed something
- if(devlist_failures > 5) {
- usbmuxd_log(LL_FATAL, "Too many errors getting device list\n");
- return cnt;
- } else {
- gettimeofday(&next_dev_poll_time, NULL);
- next_dev_poll_time.tv_usec += DEVICE_POLL_TIME * 1000;
- next_dev_poll_time.tv_sec += next_dev_poll_time.tv_usec / 1000000;
- next_dev_poll_time.tv_usec = next_dev_poll_time.tv_usec % 1000000;
- return 0;
- }
- }
- devlist_failures = 0;
-
- usbmuxd_log(LL_SPEW, "usb_discover: scanning %d devices", cnt);
-
- FOREACH(struct usb_device *usbdev, &device_list) {
- usbdev->alive = 0;
- } ENDFOREACH
-
- for(i=0; i<cnt; i++) {
- // the following are non-blocking operations on the device list
- libusb_device *dev = devs[i];
- uint8_t bus = libusb_get_bus_number(dev);
- uint8_t address = libusb_get_device_address(dev);
- struct libusb_device_descriptor devdesc;
- int found = 0;
- FOREACH(struct usb_device *usbdev, &device_list) {
- if(usbdev->bus == bus && usbdev->address == address) {
- valid_count++;
- usbdev->alive = 1;
- found = 1;
- break;
- }
- } ENDFOREACH
- if(found)
- continue; //device already found
- if((res = libusb_get_device_descriptor(dev, &devdesc)) != 0) {
- usbmuxd_log(LL_WARNING, "Could not get device descriptor for device %d-%d: %d", bus, address, res);
- continue;
- }
- if(devdesc.idVendor != VID_APPLE)
- continue;
- if((devdesc.idProduct < PID_RANGE_LOW) ||
- (devdesc.idProduct > PID_RANGE_MAX))
- continue;
- libusb_device_handle *handle;
- usbmuxd_log(LL_INFO, "Found new device with v/p %04x:%04x at %d-%d", devdesc.idVendor, devdesc.idProduct, bus, address);
- // potentially blocking operations follow; they will only run when new devices are detected, which is acceptable
- if((res = libusb_open(dev, &handle)) != 0) {
- usbmuxd_log(LL_WARNING, "Could not open device %d-%d: %d", bus, address, res);
- continue;
- }
- int current_config = 0;
- if((res = libusb_get_configuration(handle, &current_config)) != 0) {
- usbmuxd_log(LL_WARNING, "Could not get configuration for device %d-%d: %d", bus, address, res);
- libusb_close(handle);
- continue;
- }
- if (current_config != devdesc.bNumConfigurations) {
- struct libusb_config_descriptor *config;
- if((res = libusb_get_active_config_descriptor(dev, &config)) != 0) {
- usbmuxd_log(LL_NOTICE, "Could not get old configuration descriptor for device %d-%d: %d", bus, address, res);
- } else {
- for(j=0; j<config->bNumInterfaces; j++) {
- const struct libusb_interface_descriptor *intf = &config->interface[j].altsetting[0];
- if((res = libusb_kernel_driver_active(handle, intf->bInterfaceNumber)) < 0) {
- usbmuxd_log(LL_NOTICE, "Could not check kernel ownership of interface %d for device %d-%d: %d", intf->bInterfaceNumber, bus, address, res);
- continue;
- }
- if(res == 1) {
- usbmuxd_log(LL_INFO, "Detaching kernel driver for device %d-%d, interface %d", bus, address, intf->bInterfaceNumber);
- if((res = libusb_detach_kernel_driver(handle, intf->bInterfaceNumber)) < 0) {
- usbmuxd_log(LL_WARNING, "Could not detach kernel driver (%d), configuration change will probably fail!", res);
- continue;
- }
- }
- }
- libusb_free_config_descriptor(config);
- }
- if((res = libusb_set_configuration(handle, devdesc.bNumConfigurations)) != 0) {
- usbmuxd_log(LL_WARNING, "Could not set configuration %d for device %d-%d: %d", devdesc.bNumConfigurations, bus, address, res);
- libusb_close(handle);
- continue;
- }
- }
-
- struct libusb_config_descriptor *config;
- if((res = libusb_get_active_config_descriptor(dev, &config)) != 0) {
- usbmuxd_log(LL_WARNING, "Could not get configuration descriptor for device %d-%d: %d", bus, address, res);
- libusb_close(handle);
- continue;
- }
-
- struct usb_device *usbdev;
- usbdev = malloc(sizeof(struct usb_device));
- memset(usbdev, 0, sizeof(*usbdev));
-
- for(j=0; j<config->bNumInterfaces; j++) {
- const struct libusb_interface_descriptor *intf = &config->interface[j].altsetting[0];
- if(intf->bInterfaceClass != INTERFACE_CLASS ||
- intf->bInterfaceSubClass != INTERFACE_SUBCLASS ||
- intf->bInterfaceProtocol != INTERFACE_PROTOCOL)
- continue;
- if(intf->bNumEndpoints != 2) {
- usbmuxd_log(LL_WARNING, "Endpoint count mismatch for interface %d of device %d-%d", intf->bInterfaceNumber, bus, address);
- continue;
- }
- if((intf->endpoint[0].bEndpointAddress & 0x80) != LIBUSB_ENDPOINT_OUT ||
- (intf->endpoint[1].bEndpointAddress & 0x80) != LIBUSB_ENDPOINT_IN) {
- usbmuxd_log(LL_WARNING, "Endpoint type mismatch for interface %d of device %d-%d", intf->bInterfaceNumber, bus, address);
- continue;
- }
- usbdev->interface = intf->bInterfaceNumber;
- usbdev->ep_out = intf->endpoint[0].bEndpointAddress;
- usbdev->ep_in = intf->endpoint[1].bEndpointAddress;
- usbmuxd_log(LL_INFO, "Found interface %d with endpoints %02x/%02x for device %d-%d", usbdev->interface, usbdev->ep_out, usbdev->ep_in, bus, address);
- break;
- }
- libusb_free_config_descriptor(config);
-
- if(j == config->bNumInterfaces) {
- usbmuxd_log(LL_WARNING, "Could not find a suitable USB interface for device %d-%d", bus, address);
- libusb_close(handle);
- free(usbdev);
- continue;
- }
-
- if((res = libusb_claim_interface(handle, usbdev->interface)) != 0) {
- usbmuxd_log(LL_WARNING, "Could not claim interface %d for device %d-%d: %d", usbdev->interface, bus, address, res);
- libusb_close(handle);
- free(usbdev);
- continue;
- }
-
- if((res = libusb_get_string_descriptor_ascii(handle, devdesc.iSerialNumber, (uint8_t *)usbdev->serial, 256)) <= 0) {
- usbmuxd_log(LL_WARNING, "Could not get serial number for device %d-%d: %d", bus, address, res);
- libusb_release_interface(handle, usbdev->interface);
- libusb_close(handle);
- free(usbdev);
- continue;
- }
- usbdev->serial[res] = 0;
- usbdev->bus = bus;
- usbdev->address = address;
- usbdev->vid = devdesc.idVendor;
- usbdev->pid = devdesc.idProduct;
- usbdev->dev = handle;
- usbdev->alive = 1;
- usbdev->wMaxPacketSize = libusb_get_max_packet_size(dev, usbdev->ep_out);
- if (usbdev->wMaxPacketSize <= 0) {
- usbmuxd_log(LL_ERROR, "Could not determine wMaxPacketSize for device %d-%d, setting to 64", usbdev->bus, usbdev->address);
- usbdev->wMaxPacketSize = 64;
- } else {
- usbmuxd_log(LL_INFO, "Using wMaxPacketSize=%d for device %d-%d", usbdev->wMaxPacketSize, usbdev->bus, usbdev->address);
- }
-
- collection_init(&usbdev->tx_xfers);
-
- collection_add(&device_list, usbdev);
-
- if(device_add(usbdev) < 0) {
- usb_disconnect(usbdev);
- continue;
- }
- if(start_rx(usbdev) < 0) {
- device_remove(usbdev);
- usb_disconnect(usbdev);
- continue;
- }
- valid_count++;
- }
- FOREACH(struct usb_device *usbdev, &device_list) {
- if(!usbdev->alive) {
- device_remove(usbdev);
- usb_disconnect(usbdev);
- }
- } ENDFOREACH
-
- libusb_free_device_list(devs, 1);
-
- gettimeofday(&next_dev_poll_time, NULL);
- next_dev_poll_time.tv_usec += DEVICE_POLL_TIME * 1000;
- next_dev_poll_time.tv_sec += next_dev_poll_time.tv_usec / 1000000;
- next_dev_poll_time.tv_usec = next_dev_poll_time.tv_usec % 1000000;
-
- return valid_count;
-}
-
-const char *usb_get_serial(struct usb_device *dev)
-{
- if(!dev->dev) {
- return NULL;
- }
- return dev->serial;
-}
-
-uint32_t usb_get_location(struct usb_device *dev)
-{
- if(!dev->dev) {
- return 0;
- }
- return (dev->bus << 16) | dev->address;
-}
-
-uint16_t usb_get_pid(struct usb_device *dev)
-{
- if(!dev->dev) {
- return 0;
- }
- return dev->pid;
-}
-
-void usb_get_fds(struct fdlist *list)
-{
- const struct libusb_pollfd **usbfds;
- const struct libusb_pollfd **p;
- usbfds = libusb_get_pollfds(NULL);
- if(!usbfds) {
- usbmuxd_log(LL_ERROR, "libusb_get_pollfds failed");
- return;
- }
- p = usbfds;
- while(*p) {
- fdlist_add(list, FD_USB, (*p)->fd, (*p)->events);
- p++;
- }
- free(usbfds);
-}
-
-void usb_autodiscover(int enable)
-{
- usbmuxd_log(LL_DEBUG, "usb polling enable: %d", enable);
- device_polling = enable;
-}
-
-static int dev_poll_remain_ms(void)
-{
- int msecs;
- struct timeval tv;
- if(!device_polling)
- return 100000; // devices will never be polled if this is > 0
- gettimeofday(&tv, NULL);
- msecs = (next_dev_poll_time.tv_sec - tv.tv_sec) * 1000;
- msecs += (next_dev_poll_time.tv_usec - tv.tv_usec) / 1000;
- if(msecs < 0)
- return 0;
- return msecs;
-}
-
-int usb_get_timeout(void)
-{
- struct timeval tv;
- int msec;
- int res;
- int pollrem;
- pollrem = dev_poll_remain_ms();
- res = libusb_get_next_timeout(NULL, &tv);
- if(res == 0)
- return pollrem;
- if(res < 0) {
- usbmuxd_log(LL_ERROR, "libusb_get_next_timeout failed: %d", res);
- return pollrem;
- }
- msec = tv.tv_sec * 1000;
- msec += tv.tv_usec / 1000;
- if(msec > pollrem)
- return pollrem;
- return msec;
-}
-
-int usb_process(void)
-{
- int res;
- struct timeval tv;
- tv.tv_sec = tv.tv_usec = 0;
- res = libusb_handle_events_timeout(NULL, &tv);
- if(res < 0) {
- usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %d", res);
- return res;
- }
- // reap devices marked dead due to an RX error
- FOREACH(struct usb_device *usbdev, &device_list) {
- if(!usbdev->alive) {
- device_remove(usbdev);
- usb_disconnect(usbdev);
- }
- } ENDFOREACH
-
- if(dev_poll_remain_ms() <= 0) {
- res = usb_discover();
- if(res < 0) {
- usbmuxd_log(LL_ERROR, "usb_discover failed: %d", res);
- return res;
- }
- }
- return 0;
-}
-
-int usb_process_timeout(int msec)
-{
- int res;
- struct timeval tleft, tcur, tfin;
- gettimeofday(&tcur, NULL);
- tfin.tv_sec = tcur.tv_sec + (msec / 1000);
- tfin.tv_usec = tcur.tv_usec + (msec % 1000) * 1000;
- tfin.tv_sec += tfin.tv_usec / 1000000;
- tfin.tv_usec %= 1000000;
- while((tfin.tv_sec > tcur.tv_sec) || ((tfin.tv_sec == tcur.tv_sec) && (tfin.tv_usec > tcur.tv_usec))) {
- tleft.tv_sec = tfin.tv_sec - tcur.tv_sec;
- tleft.tv_usec = tfin.tv_usec - tcur.tv_usec;
- if(tleft.tv_usec < 0) {
- tleft.tv_usec += 1000000;
- tleft.tv_sec -= 1;
- }
- res = libusb_handle_events_timeout(NULL, &tleft);
- if(res < 0) {
- usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %d", res);
- return res;
- }
- // reap devices marked dead due to an RX error
- FOREACH(struct usb_device *usbdev, &device_list) {
- if(!usbdev->alive) {
- device_remove(usbdev);
- usb_disconnect(usbdev);
- }
- } ENDFOREACH
- gettimeofday(&tcur, NULL);
- }
- return 0;
-}
-
-int usb_init(void)
-{
- int res;
- usbmuxd_log(LL_DEBUG, "usb_init for linux / libusb 1.0");
-
- devlist_failures = 0;
- device_polling = 1;
- res = libusb_init(NULL);
- //libusb_set_debug(NULL, 3);
- if(res != 0) {
- usbmuxd_log(LL_FATAL, "libusb_init failed: %d", res);
- return -1;
- }
-
- collection_init(&device_list);
-
- return usb_discover();
-}
-
-void usb_shutdown(void)
-{
- usbmuxd_log(LL_DEBUG, "usb_shutdown");
- FOREACH(struct usb_device *usbdev, &device_list) {
- device_remove(usbdev);
- usb_disconnect(usbdev);
- } ENDFOREACH
- collection_free(&device_list);
- libusb_exit(NULL);
-}
diff --git a/daemon/usb.h b/daemon/usb.h
deleted file mode 100644
index 9884d7f..0000000
--- a/daemon/usb.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
-
-#ifndef __USB_H__
-#define __USB_H__
-
-#include <stdint.h>
-#include "utils.h"
-
-#define INTERFACE_CLASS 255
-#define INTERFACE_SUBCLASS 254
-#define INTERFACE_PROTOCOL 2
-
-// libusb fragments packets larger than this (usbfs limitation)
-// on input, this creates race conditions and other issues
-#define USB_MRU 16384
-
-// max transmission packet size
-// libusb fragments these too, but doesn't send ZLPs so we're safe
-// but we need to send a ZLP ourselves at the end (see usb-linux.c)
-// we're using 3 * 16384 to optimize for the fragmentation
-// this results in three URBs per full transfer, 32 USB packets each
-// if there are ZLP issues this should make them show up easily too
-#define USB_MTU (3 * 16384)
-
-#define USB_PACKET_SIZE 512
-
-#define VID_APPLE 0x5ac
-#define PID_RANGE_LOW 0x1290
-#define PID_RANGE_MAX 0x129f
-
-struct usb_device;
-
-int usb_init(void);
-void usb_shutdown(void);
-const char *usb_get_serial(struct usb_device *dev);
-uint32_t usb_get_location(struct usb_device *dev);
-uint16_t usb_get_pid(struct usb_device *dev);
-void usb_get_fds(struct fdlist *list);
-int usb_get_timeout(void);
-int usb_send(struct usb_device *dev, const unsigned char *buf, int length);
-int usb_discover(void);
-void usb_autodiscover(int enable);
-int usb_process(void);
-int usb_process_timeout(int msec);
-
-#endif
diff --git a/docs/Makefile.am b/docs/Makefile.am
new file mode 100644
index 0000000..70a61ca
--- /dev/null
+++ b/docs/Makefile.am
@@ -0,0 +1,3 @@
+man_MANS = usbmuxd.8
+
+EXTRA_DIST = $(man_MANS)
diff --git a/docs/usbmuxd.8 b/docs/usbmuxd.8
new file mode 100644
index 0000000..590afdc
--- /dev/null
+++ b/docs/usbmuxd.8
@@ -0,0 +1,80 @@
+.TH "usbmuxd" 8
+.SH NAME
+usbmuxd \- Expose a socket to multiplex connections from and to iOS devices.
+.SH SYNOPSIS
+.B usbmuxd
+[OPTIONS]
+
+.SH DESCRIPTION
+
+usbmuxd stands for "USB multiplexing daemon". This daemon is in charge of
+multiplexing connections over USB to an iOS device. To users, it means
+you can sync your music, contacts, photos, etc. over USB. To developers, it
+means you can connect to any listening localhost socket on the device. usbmuxd
+is not used for tethering data transfer which uses a dedicated USB interface as
+a virtual network device. Multiple connections to different TCP ports can happen
+in parallel. The higher-level layers are handled by libimobiledevice.
+
+When usbmuxd is running (normally started, or stopped as a result of "udev"
+auto-insertion messages or by systemd) it provides a socket interface in
+"/var/run/usbmuxd" that is designed to be compatible with the socket interface
+that is provided on Mac OS X.
+
+You should also create a "usbmux" user that has access to USB devices on your
+system. Alternatively, you can pass a different username using the -U argument.
+
+Due to iOS 7 the daemon now also manages pairing records with iOS devices and
+the host in "/var/lib/lockdown" (Linux) or "/var/db/lockdown" (Mac OS X).
+Ensure proper permissions are setup for the daemon to access the directory.
+
+.SH OPTIONS
+.TP
+.B \-U, \-\-user USER
+Change to this user after startup (needs USB privileges).
+.TP
+.B \-f, \-\-foreground
+Do not daemonize (implies one -v).
+.TP
+.B \-n, \-\-disable-hotplug
+Disables automatic discovery of devices on hotplug. Starting another instance
+will trigger discovery instead.
+.TP
+.B \-z, \-\-enable-exit
+Enable "--exit" request from other instances and exit automatically if no
+device is attached.
+.TP
+.B \-u, \-\-udev
+Run in udev operation mode (implies -n and -z).
+.TP
+.B \-s, \-\-systemd
+Run in systemd operation mode (implies -z and -f).
+.TP
+.B \-x, \-\-exit
+Notify a running instance to exit if there are no devices connected (sends
+SIGUSR1 to running instance) and exit.
+.TP
+.B \-X, \-\-force-exit
+Notify a running instance to exit even if there are still devices connected
+(always works) and exit.
+.TP
+.B \-v, \-\-verbose
+be verbose (use twice or more to increase verbose level).
+.TP
+.B \-V, \-\-version
+print version information and exit.
+.TP
+.B \-h, \-\-help
+prints usage information.
+
+.SH AUTHOR
+The first usbmuxd daemon implementation was authored by Hector Martin.
+
+Now mainly developed by Nikias Bassen, Martin Szulecki and contributors (see AUTHORS file).
+
+.SH SEE ALSO
+idevice_id(1), iproxy(1).
+
+.SH ON THE WEB
+https://libimobiledevice.org
+
+https://github.com/libimobiledevice/usbmuxd
diff --git a/git-version-gen b/git-version-gen
new file mode 100755
index 0000000..3eb6a42
--- /dev/null
+++ b/git-version-gen
@@ -0,0 +1,19 @@
+#!/bin/sh
+SRCDIR=`dirname $0`
+if test -n "$1"; then
+ VER=$1
+else
+ if test -d "${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
+printf %s "$VER"
diff --git a/libusbmuxd.pc.in b/libusbmuxd.pc.in
deleted file mode 100644
index 1ecd8ed..0000000
--- a/libusbmuxd.pc.in
+++ /dev/null
@@ -1,11 +0,0 @@
-prefix=${CMAKE_INSTALL_PREFIX}
-exec_prefix=${CMAKE_INSTALL_PREFIX}
-libdir=${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}
-includedir=${CMAKE_INSTALL_PREFIX}/include
-
-Name: libusbmuxd
-Description: A library to communicate with the usbmux daemon
-Version: ${USBMUXD_VERSION}
-Libs: -L${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX} -lusbmuxd
-Cflags: -I${CMAKE_INSTALL_PREFIX}/include
-
diff --git a/libusbmuxd/CMakeLists.txt b/libusbmuxd/CMakeLists.txt
deleted file mode 100644
index 81203d3..0000000
--- a/libusbmuxd/CMakeLists.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-include_directories (${CMAKE_SOURCE_DIR}/common)
-find_package(Threads)
-
-add_library (libusbmuxd SHARED libusbmuxd.c sock_stuff.c ${CMAKE_SOURCE_DIR}/common/utils.c)
-find_library (PTHREAD pthread)
-
-if (HAVE_PLIST)
- add_definitions("-DHAVE_PLIST")
- message("-- libusbmuxd will be built with protocol version 1 support")
-endif()
-if(WIN32)
- set(OPT_LIBS ${OPT_LIBS} ws2_32)
-endif()
-include_directories(${OPT_INCLUDES})
-target_link_libraries (libusbmuxd ${CMAKE_THREAD_LIBS_INIT} ${OPT_LIBS})
-
-# 'lib' is a UNIXism, the proper CMake target is usbmuxd
-# But we can't use that due to the conflict with the usbmuxd daemon,
-# so instead change the library output base name to usbmuxd here
-set_target_properties(libusbmuxd PROPERTIES OUTPUT_NAME usbmuxd)
-set_target_properties(libusbmuxd PROPERTIES VERSION ${LIBUSBMUXD_VERSION})
-set_target_properties(libusbmuxd PROPERTIES SOVERSION ${LIBUSBMUXD_SOVERSION})
-
-install(TARGETS libusbmuxd
- RUNTIME DESTINATION bin
- ARCHIVE DESTINATION lib${LIB_SUFFIX}
- LIBRARY DESTINATION lib${LIB_SUFFIX}
-)
-install(FILES usbmuxd.h usbmuxd-proto.h DESTINATION include)
diff --git a/libusbmuxd/libusbmuxd.c b/libusbmuxd/libusbmuxd.c
deleted file mode 100644
index 5eaf8e6..0000000
--- a/libusbmuxd/libusbmuxd.c
+++ /dev/null
@@ -1,782 +0,0 @@
-/*
- libusbmuxd - client library to talk to usbmuxd
-
-Copyright (C) 2009-2010 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
-Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com>
-
-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 General Public License for more details.
-
-You should have received a copy of the GNU Lesser 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
-
-*/
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <stdio.h>
-#include <string.h>
-#ifdef WIN32
-#include <windows.h>
-#include <winsock2.h>
-#define sleep(x) Sleep(x*1000)
-#else
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#endif
-#include <unistd.h>
-#include <signal.h>
-#include <pthread.h>
-
-#ifdef HAVE_PLIST
-#include <plist/plist.h>
-#define PLIST_BUNDLE_ID "com.marcansoft.usbmuxd"
-#define PLIST_CLIENT_VERSION_STRING "usbmuxd built for freedom"
-#define PLIST_PROGNAME "libusbmuxd"
-#endif
-
-// usbmuxd public interface
-#include "usbmuxd.h"
-// usbmuxd protocol
-#include "usbmuxd-proto.h"
-// socket utility functions
-#include "sock_stuff.h"
-// misc utility functions
-#include "utils.h"
-
-static struct collection devices;
-static usbmuxd_event_cb_t event_cb = NULL;
-pthread_t devmon;
-static int listenfd = -1;
-
-static int use_tag = 0;
-static int proto_version = 0;
-
-/**
- * Finds a device info record by its handle.
- * if the record is not found, NULL is returned.
- */
-static usbmuxd_device_info_t *devices_find(int handle)
-{
- FOREACH(usbmuxd_device_info_t *dev, &devices) {
- if (dev && dev->handle == handle) {
- return dev;
- }
- } ENDFOREACH
- return NULL;
-}
-
-/**
- * Creates a socket connection to usbmuxd.
- * For Mac/Linux it is a unix domain socket,
- * for Windows it is a tcp socket.
- */
-static int connect_usbmuxd_socket()
-{
-#if defined(WIN32) || defined(__CYGWIN__)
- return connect_socket("127.0.0.1", USBMUXD_SOCKET_PORT);
-#else
- return connect_unix_socket(USBMUXD_SOCKET_FILE);
-#endif
-}
-
-static int receive_packet(int sfd, struct usbmuxd_header *header, void **payload, int timeout)
-{
- int recv_len;
- struct usbmuxd_header hdr;
- char *payload_loc = NULL;
-
- header->length = 0;
- header->version = 0;
- header->message = 0;
- header->tag = 0;
-
- recv_len = recv_buf_timeout(sfd, &hdr, sizeof(hdr), 0, timeout);
- if (recv_len < 0) {
- return recv_len;
- } else if (recv_len < sizeof(hdr)) {
- return recv_len;
- }
-
- uint32_t payload_size = hdr.length - sizeof(hdr);
- if (payload_size > 0) {
- payload_loc = (char*)malloc(payload_size);
- if (recv_buf_timeout(sfd, payload_loc, payload_size, 0, 5000) != payload_size) {
- fprintf(stderr, "%s: Error receiving payload of size %d\n", __func__, payload_size);
- free(payload_loc);
- return -EBADMSG;
- }
- }
-
-#ifdef HAVE_PLIST
- if (hdr.message == MESSAGE_PLIST) {
- char *message = NULL;
- plist_t plist = NULL;
- plist_from_xml(payload_loc, payload_size, &plist);
- free(payload_loc);
-
- if (!plist) {
- fprintf(stderr, "%s: Error getting plist from payload!\n", __func__);
- return -EBADMSG;
- }
-
- plist_t node = plist_dict_get_item(plist, "MessageType");
- if (plist_get_node_type(node) != PLIST_STRING) {
- fprintf(stderr, "%s: Error getting message type from plist!\n", __func__);
- free(plist);
- return -EBADMSG;
- }
-
- plist_get_string_val(node, &message);
- if (message) {
- uint64_t val = 0;
- if (strcmp(message, "Result") == 0) {
- /* result message */
- uint32_t dwval = 0;
- plist_t n = plist_dict_get_item(plist, "Number");
- plist_get_uint_val(n, &val);
- *payload = malloc(sizeof(uint32_t));
- dwval = val;
- memcpy(*payload, &dwval, sizeof(dwval));
- hdr.length = sizeof(hdr) + sizeof(dwval);
- hdr.message = MESSAGE_RESULT;
- } else if (strcmp(message, "Attached") == 0) {
- /* device add message */
- struct usbmuxd_device_record *dev = NULL;
- plist_t props = plist_dict_get_item(plist, "Properties");
- if (!props) {
- fprintf(stderr, "%s: Could not get properties for message '%s' from plist!\n", __func__, message);
- plist_free(plist);
- return -EBADMSG;
- }
- dev = (struct usbmuxd_device_record*)malloc(sizeof(struct usbmuxd_device_record));
- memset(dev, 0, sizeof(struct usbmuxd_device_record));
-
- plist_t n = plist_dict_get_item(props, "DeviceID");
- plist_get_uint_val(n, &val);
- dev->device_id = (uint32_t)val;
-
- n = plist_dict_get_item(props, "ProductID");
- plist_get_uint_val(n, &val);
- dev->product_id = (uint32_t)val;
-
- n = plist_dict_get_item(props, "SerialNumber");
- char *strval = NULL;
- plist_get_string_val(n, &strval);
- if (strval) {
- strcpy(dev->serial_number, strval);
- free(strval);
- }
- n = plist_dict_get_item(props, "LocationID");
- plist_get_uint_val(n, &val);
- dev->location = (uint32_t)val;
- *payload = (void*)dev;
- hdr.length = sizeof(hdr) + sizeof(struct usbmuxd_device_record);
- hdr.message = MESSAGE_DEVICE_ADD;
- } else if (strcmp(message, "Detached") == 0) {
- /* device remove message */
- uint32_t dwval = 0;
- plist_t n = plist_dict_get_item(plist, "DeviceID");
- if (n) {
- plist_get_uint_val(n, &val);
- *payload = malloc(sizeof(uint32_t));
- dwval = val;
- memcpy(*payload, &dwval, sizeof(dwval));
- hdr.length = sizeof(hdr) + sizeof(dwval);
- hdr.message = MESSAGE_DEVICE_REMOVE;
- }
- } else {
- fprintf(stderr, "%s: Unexpected message '%s' in plist!\n", __func__, message);
- plist_free(plist);
- return -EBADMSG;
- }
- }
- plist_free(plist);
- } else
-#endif
- {
- *payload = payload_loc;
- }
-
- memcpy(header, &hdr, sizeof(hdr));
-
- return hdr.length;
-}
-
-/**
- * Retrieves the result code to a previously sent request.
- */
-static int usbmuxd_get_result(int sfd, uint32_t tag, uint32_t * result)
-{
- struct usbmuxd_header hdr;
- int recv_len;
- uint32_t *res = NULL;
-
- if (!result) {
- return -EINVAL;
- }
- *result = -1;
-
- if ((recv_len = receive_packet(sfd, &hdr, (void**)&res, 5000)) < 0) {
- fprintf(stderr, "%s: Error receiving packet: %d\n", __func__, errno);
- if (res)
- free(res);
- return -errno;
- }
- if (recv_len < sizeof(hdr)) {
- fprintf(stderr, "%s: Received packet is too small!\n", __func__);
- if (res)
- free(res);
- return -EPROTO;
- }
-
- if (hdr.message == MESSAGE_RESULT) {
- int ret = 0;
- if (res && (hdr.tag == tag)) {
- memcpy(result, res, sizeof(uint32_t));
- ret = 1;
- }
- if (res)
- free(res);
- return ret;
- }
- fprintf(stderr, "%s: Unexpected message of type %d received!\n", __func__, hdr.message);
- if (res)
- free(res);
- return -EPROTO;
-}
-
-static int send_packet(int sfd, uint32_t message, uint32_t tag, void *payload, uint32_t payload_size)
-{
- struct usbmuxd_header header;
-
- header.length = sizeof(struct usbmuxd_header);
- header.version = proto_version;
- header.message = message;
- header.tag = tag;
- if (payload && (payload_size > 0)) {
- header.length += payload_size;
- }
- int sent = send_buf(sfd, &header, sizeof(header));
- if (sent != sizeof(header)) {
- fprintf(stderr, "%s: ERROR: could not send packet header\n", __func__);
- return -1;
- }
- if (payload && (payload_size > 0)) {
- sent += send_buf(sfd, payload, payload_size);
- }
- if (sent != (int)header.length) {
- fprintf(stderr, "%s: ERROR: could not send whole packet\n", __func__);
- close_socket(sfd);
- return -1;
- }
- return sent;
-}
-
-static int send_listen_packet(int sfd, uint32_t tag)
-{
- int res = 0;
-#ifdef HAVE_PLIST
- if (proto_version == 1) {
- /* plist packet */
- char *payload = NULL;
- uint32_t payload_size = 0;
- plist_t plist;
-
- /* construct message plist */
- plist = plist_new_dict();
- plist_dict_insert_item(plist, "BundleID", plist_new_string(PLIST_BUNDLE_ID));
- plist_dict_insert_item(plist, "ClientVersionString", plist_new_string(PLIST_CLIENT_VERSION_STRING));
- plist_dict_insert_item(plist, "MessageType", plist_new_string("Listen"));
- plist_dict_insert_item(plist, "ProgName", plist_new_string(PLIST_PROGNAME));
- plist_to_xml(plist, &payload, &payload_size);
- plist_free(plist);
-
- res = send_packet(sfd, MESSAGE_PLIST, tag, payload, payload_size);
- free(payload);
- } else
-#endif
- {
- /* binary packet */
- res = send_packet(sfd, MESSAGE_LISTEN, tag, NULL, 0);
- }
- return res;
-}
-
-static int send_connect_packet(int sfd, uint32_t tag, uint32_t device_id, uint16_t port)
-{
- int res = 0;
-#ifdef HAVE_PLIST
- if (proto_version == 1) {
- /* plist packet */
- char *payload = NULL;
- uint32_t payload_size = 0;
- plist_t plist;
-
- /* construct message plist */
- plist = plist_new_dict();
- plist_dict_insert_item(plist, "BundleID", plist_new_string(PLIST_BUNDLE_ID));
- plist_dict_insert_item(plist, "ClientVersionString", plist_new_string(PLIST_CLIENT_VERSION_STRING));
- plist_dict_insert_item(plist, "MessageType", plist_new_string("Connect"));
- plist_dict_insert_item(plist, "DeviceID", plist_new_uint(device_id));
- plist_dict_insert_item(plist, "PortNumber", plist_new_uint(htons(port)));
- plist_dict_insert_item(plist, "ProgName", plist_new_string(PLIST_PROGNAME));
- plist_to_xml(plist, &payload, &payload_size);
- plist_free(plist);
-
- res = send_packet(sfd, MESSAGE_PLIST, tag, (void*)payload, payload_size);
- free(payload);
- } else
-#endif
- {
- /* binary packet */
- struct {
- uint32_t device_id;
- uint16_t port;
- uint16_t reserved;
- } conninfo;
-
- conninfo.device_id = device_id;
- conninfo.port = htons(port);
- conninfo.reserved = 0;
-
- res = send_packet(sfd, MESSAGE_CONNECT, tag, &conninfo, sizeof(conninfo));
- }
- return res;
-}
-
-/**
- * Generates an event, i.e. calls the callback function.
- * A reference to a populated usbmuxd_event_t with information about the event
- * and the corresponding device will be passed to the callback function.
- */
-static void generate_event(usbmuxd_event_cb_t callback, const usbmuxd_device_info_t *dev, enum usbmuxd_event_type event, void *user_data)
-{
- usbmuxd_event_t ev;
-
- if (!callback || !dev) {
- return;
- }
-
- ev.event = event;
- memcpy(&ev.device, dev, sizeof(usbmuxd_device_info_t));
-
- callback(&ev, user_data);
-}
-
-/**
- * Tries to connect to usbmuxd and wait if it is not running.
- *
- * TODO inotify support should come here
- */
-static int usbmuxd_listen()
-{
- int sfd;
- uint32_t res = -1;
-
-#ifdef HAVE_PLIST
-retry:
-#endif
- sfd = connect_usbmuxd_socket();
- if (sfd < 0) {
- while (event_cb) {
- if ((sfd = connect_usbmuxd_socket()) > 0) {
- break;
- }
- sleep(1);
- }
- }
-
- if (sfd < 0) {
- fprintf(stderr, "%s: ERROR: usbmuxd was supposed to be running here...\n", __func__);
- return sfd;
- }
-
- use_tag++;
- if (send_listen_packet(sfd, use_tag) <= 0) {
- fprintf(stderr, "%s: ERROR: could not send listen packet\n", __func__);
- close_socket(sfd);
- return -1;
- }
- if (usbmuxd_get_result(sfd, use_tag, &res) && (res != 0)) {
- close_socket(sfd);
-#ifdef HAVE_PLIST
- if ((res == RESULT_BADVERSION) && (proto_version != 1)) {
- proto_version = 1;
- goto retry;
- }
-#endif
- fprintf(stderr, "%s: ERROR: did not get OK but %d\n", __func__, res);
- return -1;
- }
-
- return sfd;
-}
-
-/**
- * Waits for an event to occur, i.e. a packet coming from usbmuxd.
- * Calls generate_event to pass the event via callback to the client program.
- */
-int get_next_event(int sfd, usbmuxd_event_cb_t callback, void *user_data)
-{
- struct usbmuxd_header hdr;
- void *payload = NULL;
-
- /* block until we receive something */
- if (receive_packet(sfd, &hdr, &payload, 0) < 0) {
- // when then usbmuxd connection fails,
- // generate remove events for every device that
- // is still present so applications know about it
- FOREACH(usbmuxd_device_info_t *dev, &devices) {
- generate_event(callback, dev, UE_DEVICE_REMOVE, user_data);
- collection_remove(&devices, dev);
- } ENDFOREACH
- return -EIO;
- }
-
- if ((hdr.length > sizeof(hdr)) && !payload) {
- fprintf(stderr, "%s: Invalid packet received, payload is missing!\n", __func__);
- return -EBADMSG;
- }
-
- if (hdr.message == MESSAGE_DEVICE_ADD) {
- struct usbmuxd_device_record *dev = payload;
- usbmuxd_device_info_t *devinfo = (usbmuxd_device_info_t*)malloc(sizeof(usbmuxd_device_info_t));
- if (!devinfo) {
- fprintf(stderr, "%s: Out of memory!\n", __func__);
- free(payload);
- return -1;
- }
-
- devinfo->handle = dev->device_id;
- devinfo->product_id = dev->product_id;
- memset(devinfo->uuid, '\0', sizeof(devinfo->uuid));
- memcpy(devinfo->uuid, dev->serial_number, sizeof(devinfo->uuid));
-
- collection_add(&devices, devinfo);
- generate_event(callback, devinfo, UE_DEVICE_ADD, user_data);
- } else if (hdr.message == MESSAGE_DEVICE_REMOVE) {
- uint32_t handle;
- usbmuxd_device_info_t *devinfo;
-
- memcpy(&handle, payload, sizeof(uint32_t));
-
- devinfo = devices_find(handle);
- if (!devinfo) {
- fprintf(stderr, "%s: WARNING: got device remove message for handle %d, but couldn't find the corresponding handle in the device list. This event will be ignored.\n", __func__, handle);
- } else {
- generate_event(callback, devinfo, UE_DEVICE_REMOVE, user_data);
- collection_remove(&devices, devinfo);
- }
- } else {
- fprintf(stderr, "%s: Unexpected message type %d length %d received!\n", __func__, hdr.message, hdr.length);
- }
- if (payload) {
- free(payload);
- }
- return 0;
-}
-
-/**
- * Device Monitor thread function.
- *
- * This function sets up a connection to usbmuxd
- */
-static void *device_monitor(void *data)
-{
- collection_init(&devices);
-
- while (event_cb) {
-
- listenfd = usbmuxd_listen();
- if (listenfd < 0) {
- continue;
- }
-
- while (event_cb) {
- int res = get_next_event(listenfd, event_cb, data);
- if (res < 0) {
- break;
- }
- }
- }
-
- collection_free(&devices);
-
- return NULL;
-}
-
-int usbmuxd_subscribe(usbmuxd_event_cb_t callback, void *user_data)
-{
- int res;
-
- if (!callback) {
- return -EINVAL;
- }
- event_cb = callback;
-
- res = pthread_create(&devmon, NULL, device_monitor, user_data);
- if (res != 0) {
- fprintf(stderr, "%s: ERROR: Could not start device watcher thread!\n", __func__);
- return res;
- }
- return 0;
-}
-
-int usbmuxd_unsubscribe()
-{
- event_cb = NULL;
-
- if (pthread_kill(devmon, 0) == 0) {
- close_socket(listenfd);
- listenfd = -1;
- pthread_kill(devmon, SIGINT);
- pthread_join(devmon, NULL);
- }
-
- return 0;
-}
-
-int usbmuxd_get_device_list(usbmuxd_device_info_t **device_list)
-{
- int sfd;
- int listen_success = 0;
- uint32_t res;
- usbmuxd_device_info_t *newlist = NULL;
- struct usbmuxd_header hdr;
- struct usbmuxd_device_record *dev_info;
- int dev_cnt = 0;
- void *payload = NULL;
-
-#ifdef HAVE_PLIST
-retry:
-#endif
- sfd = connect_usbmuxd_socket();
- if (sfd < 0) {
- fprintf(stderr, "%s: error opening socket!\n", __func__);
- return sfd;
- }
-
- use_tag++;
- if (send_listen_packet(sfd, use_tag) > 0) {
- res = -1;
- // get response
- if (usbmuxd_get_result(sfd, use_tag, &res) && (res == 0)) {
- listen_success = 1;
- } else {
- close_socket(sfd);
-#ifdef HAVE_PLIST
- if ((res == RESULT_BADVERSION) && (proto_version != 1)) {
- proto_version = 1;
- goto retry;
- }
-#endif
- fprintf(stderr,
- "%s: Did not get response to scan request (with result=0)...\n",
- __func__);
- return res;
- }
- }
-
- if (!listen_success) {
- fprintf(stderr, "%s: Could not send listen request!\n", __func__);
- return -1;
- }
-
- *device_list = NULL;
- // receive device list
- while (1) {
- if (receive_packet(sfd, &hdr, &payload, 1000) > 0) {
- if (hdr.message == MESSAGE_DEVICE_ADD) {
- dev_info = payload;
- newlist = (usbmuxd_device_info_t *) realloc(*device_list, sizeof(usbmuxd_device_info_t) * (dev_cnt + 1));
- if (newlist) {
- newlist[dev_cnt].handle =
- (int) dev_info->device_id;
- newlist[dev_cnt].product_id =
- dev_info->product_id;
- memset(newlist[dev_cnt].uuid, '\0',
- sizeof(newlist[dev_cnt].uuid));
- memcpy(newlist[dev_cnt].uuid,
- dev_info->serial_number,
- sizeof(newlist[dev_cnt].uuid));
- *device_list = newlist;
- dev_cnt++;
- } else {
- fprintf(stderr,
- "%s: ERROR: out of memory when trying to realloc!\n",
- __func__);
- if (payload)
- free(payload);
- break;
- }
- } else {
- fprintf(stderr, "%s: Unexpected message %d\n", __func__, hdr.message);
- }
- if (payload)
- free(payload);
- } else {
- // we _should_ have all of them now.
- // or perhaps an error occured.
- break;
- }
- }
-
- // explicitly close connection
- close_socket(sfd);
-
- // terminating zero record
- newlist = (usbmuxd_device_info_t*) realloc(*device_list, sizeof(usbmuxd_device_info_t) * (dev_cnt + 1));
- memset(newlist + dev_cnt, 0, sizeof(usbmuxd_device_info_t));
- *device_list = newlist;
-
- return dev_cnt;
-}
-
-int usbmuxd_device_list_free(usbmuxd_device_info_t **device_list)
-{
- if (device_list) {
- free(*device_list);
- }
- return 0;
-}
-
-int usbmuxd_get_device_by_uuid(const char *uuid, usbmuxd_device_info_t *device)
-{
- usbmuxd_device_info_t *dev_list = NULL;
-
- if (!device) {
- return -EINVAL;
- }
- if (usbmuxd_get_device_list(&dev_list) < 0) {
- return -ENODEV;
- }
-
- int i;
- int result = 0;
- for (i = 0; dev_list[i].handle > 0; i++) {
- if (!uuid) {
- device->handle = dev_list[i].handle;
- device->product_id = dev_list[i].product_id;
- strcpy(device->uuid, dev_list[i].uuid);
- result = 1;
- break;
- }
- if (!strcmp(uuid, dev_list[i].uuid)) {
- device->handle = dev_list[i].handle;
- device->product_id = dev_list[i].product_id;
- strcpy(device->uuid, dev_list[i].uuid);
- result = 1;
- break;
- }
- }
-
- free(dev_list);
-
- return result;
-}
-
-int usbmuxd_connect(const int handle, const unsigned short port)
-{
- int sfd;
- int connected = 0;
- uint32_t res = -1;
-
-#ifdef HAVE_PLIST
-retry:
-#endif
- sfd = connect_usbmuxd_socket();
- if (sfd < 0) {
- fprintf(stderr, "%s: Error: Connection to usbmuxd failed: %s\n",
- __func__, strerror(errno));
- return sfd;
- }
-
- use_tag++;
- if (send_connect_packet(sfd, use_tag, (uint32_t)handle, (uint16_t)port) <= 0) {
- fprintf(stderr, "%s: Error sending connect message!\n", __func__);
- } else {
- // read ACK
- //fprintf(stderr, "%s: Reading connect result...\n", __func__);
- if (usbmuxd_get_result(sfd, use_tag, &res)) {
- if (res == 0) {
- //fprintf(stderr, "%s: Connect success!\n", __func__);
- connected = 1;
- } else {
-#ifdef HAVE_PLIST
- if ((res == RESULT_BADVERSION) && (proto_version == 0)) {
- proto_version = 1;
- close_socket(sfd);
- goto retry;
- }
-#endif
- fprintf(stderr, "%s: Connect failed, Error code=%d\n",
- __func__, res);
- }
- }
- }
-
- if (connected) {
- return sfd;
- }
-
- close_socket(sfd);
-
- return -1;
-}
-
-int usbmuxd_disconnect(int sfd)
-{
- return close_socket(sfd);
-}
-
-int usbmuxd_send(int sfd, const char *data, uint32_t len, uint32_t *sent_bytes)
-{
- int num_sent;
-
- if (sfd < 0) {
- return -EINVAL;
- }
-
- num_sent = send(sfd, (void*)data, len, 0);
- if (num_sent < 0) {
- *sent_bytes = 0;
- fprintf(stderr, "%s: Error %d when sending: %s\n", __func__, num_sent, strerror(errno));
- return num_sent;
- } else if ((uint32_t)num_sent < len) {
- fprintf(stderr, "%s: Warning: Did not send enough (only %d of %d)\n", __func__, num_sent, len);
- }
-
- *sent_bytes = num_sent;
-
- return 0;
-}
-
-int usbmuxd_recv_timeout(int sfd, char *data, uint32_t len, uint32_t *recv_bytes, unsigned int timeout)
-{
- int num_recv = recv_buf_timeout(sfd, (void*)data, len, 0, timeout);
- if (num_recv < 0) {
- *recv_bytes = 0;
- return num_recv;
- }
-
- *recv_bytes = num_recv;
-
- return 0;
-}
-
-int usbmuxd_recv(int sfd, char *data, uint32_t len, uint32_t *recv_bytes)
-{
- return usbmuxd_recv_timeout(sfd, data, len, recv_bytes, 5000);
-}
-
diff --git a/libusbmuxd/sock_stuff.c b/libusbmuxd/sock_stuff.c
deleted file mode 100644
index edc738e..0000000
--- a/libusbmuxd/sock_stuff.c
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- libusbmuxd - client library to talk to usbmuxd
-
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
-Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com>
-
-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 General Public License for more details.
-
-You should have received a copy of the GNU Lesser 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
-
-*/
-
-#include <stdio.h>
-#include <stddef.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#include <sys/time.h>
-#include <sys/stat.h>
-#ifdef WIN32
-#include <windows.h>
-#include <winsock2.h>
-static int wsa_init = 0;
-#else
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <netinet/in.h>
-#include <netdb.h>
-#include <arpa/inet.h>
-#endif
-#include "sock_stuff.h"
-
-#define RECV_TIMEOUT 20000
-
-static int verbose = 0;
-
-void sock_stuff_set_verbose(int level)
-{
- verbose = level;
-}
-
-#ifndef WIN32
-int create_unix_socket(const char *filename)
-{
- struct sockaddr_un name;
- int sock;
- size_t size;
-
- // remove if still present
- unlink(filename);
-
- /* Create the socket. */
- sock = socket(PF_LOCAL, SOCK_STREAM, 0);
- if (sock < 0) {
- perror("socket");
- return -1;
- }
-
- /* Bind a name to the socket. */
- name.sun_family = AF_LOCAL;
- strncpy(name.sun_path, filename, sizeof(name.sun_path));
- name.sun_path[sizeof(name.sun_path) - 1] = '\0';
-
- /* The size of the address is
- the offset of the start of the filename,
- plus its length,
- plus one for the terminating null byte.
- Alternatively you can just do:
- size = SUN_LEN (&name);
- */
- size = (offsetof(struct sockaddr_un, sun_path)
- + strlen(name.sun_path) + 1);
-
- if (bind(sock, (struct sockaddr *) &name, size) < 0) {
- perror("bind");
- close_socket(sock);
- return -1;
- }
-
- if (listen(sock, 10) < 0) {
- perror("listen");
- close_socket(sock);
- return -1;
- }
-
- return sock;
-}
-
-int connect_unix_socket(const char *filename)
-{
- struct sockaddr_un name;
- int sfd = -1;
- size_t size;
- struct stat fst;
-
- // check if socket file exists...
- if (stat(filename, &fst) != 0) {
- if (verbose >= 2)
- fprintf(stderr, "%s: stat '%s': %s\n", __func__, filename,
- strerror(errno));
- return -1;
- }
- // ... and if it is a unix domain socket
- if (!S_ISSOCK(fst.st_mode)) {
- if (verbose >= 2)
- fprintf(stderr, "%s: File '%s' is not a socket!\n", __func__,
- filename);
- return -1;
- }
- // make a new socket
- if ((sfd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
- if (verbose >= 2)
- fprintf(stderr, "%s: socket: %s\n", __func__, strerror(errno));
- return -1;
- }
- // and connect to 'filename'
- name.sun_family = AF_LOCAL;
- strncpy(name.sun_path, filename, sizeof(name.sun_path));
- name.sun_path[sizeof(name.sun_path) - 1] = 0;
-
- size = (offsetof(struct sockaddr_un, sun_path)
- + strlen(name.sun_path) + 1);
-
- if (connect(sfd, (struct sockaddr *) &name, size) < 0) {
- close_socket(sfd);
- if (verbose >= 2)
- fprintf(stderr, "%s: connect: %s\n", __func__,
- strerror(errno));
- return -1;
- }
-
- return sfd;
-}
-#endif
-
-int create_socket(uint16_t port)
-{
- int sfd = -1;
- int yes = 1;
-#ifdef WIN32
- WSADATA wsa_data;
- if (!wsa_init) {
- if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
- fprintf(stderr, "WSAStartup failed!\n");
- ExitProcess(-1);
- }
- wsa_init = 1;
- }
-#endif
- struct sockaddr_in saddr;
-
- if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) {
- perror("socket()");
- return -1;
- }
-
- if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
- perror("setsockopt()");
- close_socket(sfd);
- return -1;
- }
-
- memset((void *) &saddr, 0, sizeof(saddr));
- saddr.sin_family = AF_INET;
- saddr.sin_addr.s_addr = htonl(INADDR_ANY);
- saddr.sin_port = htons(port);
-
- if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) {
- perror("bind()");
- close_socket(sfd);
- return -1;
- }
-
- if (listen(sfd, 1) == -1) {
- perror("listen()");
- close_socket(sfd);
- return -1;
- }
-
- return sfd;
-}
-
-#if defined(WIN32) || defined(__CYGWIN__)
-int connect_socket(const char *addr, uint16_t port)
-{
- int sfd = -1;
- int yes = 1;
- struct hostent *hp;
- struct sockaddr_in saddr;
-#ifdef WIN32
- WSADATA wsa_data;
- if (!wsa_init) {
- if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
- fprintf(stderr, "WSAStartup failed!\n");
- ExitProcess(-1);
- }
- wsa_init = 1;
- }
-#endif
-
- if (!addr) {
- errno = EINVAL;
- return -1;
- }
-
- if ((hp = gethostbyname(addr)) == NULL) {
- if (verbose >= 2)
- fprintf(stderr, "%s: unknown host '%s'\n", __func__, addr);
- return -1;
- }
-
- if (!hp->h_addr) {
- if (verbose >= 2)
- fprintf(stderr, "%s: gethostbyname returned NULL address!\n",
- __func__);
- return -1;
- }
-
- if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) {
- perror("socket()");
- return -1;
- }
-
- if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
- perror("setsockopt()");
- close_socket(sfd);
- return -1;
- }
-
- memset((void *) &saddr, 0, sizeof(saddr));
- saddr.sin_family = AF_INET;
- saddr.sin_addr.s_addr = *(uint32_t *) hp->h_addr;
- saddr.sin_port = htons(port);
-
- if (connect(sfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) {
- perror("connect");
- close_socket(sfd);
- return -2;
- }
-
- return sfd;
-}
-#endif /* WIN32 || __CYGWIN__ */
-
-int check_fd(int fd, fd_mode fdm, unsigned int timeout)
-{
- fd_set fds;
- int sret;
- int eagain;
- struct timeval to;
- struct timeval *pto;
-
- if (fd <= 0) {
- if (verbose >= 2)
- fprintf(stderr, "ERROR: invalid fd in check_fd %d\n", fd);
- return -1;
- }
-
- FD_ZERO(&fds);
- FD_SET(fd, &fds);
-
- if (timeout > 0) {
- to.tv_sec = (time_t) (timeout / 1000);
- to.tv_usec = (time_t) ((timeout - (to.tv_sec * 1000)) * 1000);
- pto = &to;
- } else {
- pto = NULL;
- }
-
- sret = -1;
-
- do {
- eagain = 0;
- switch (fdm) {
- case FDM_READ:
- sret = select(fd + 1, &fds, NULL, NULL, pto);
- break;
- case FDM_WRITE:
- sret = select(fd + 1, NULL, &fds, NULL, pto);
- break;
- case FDM_EXCEPT:
- sret = select(fd + 1, NULL, NULL, &fds, pto);
- break;
- default:
- return -1;
- }
-
- if (sret < 0) {
- switch (errno) {
- case EINTR:
- // interrupt signal in select
- if (verbose >= 2)
- fprintf(stderr, "%s: EINTR\n", __func__);
- eagain = 1;
- break;
- case EAGAIN:
- if (verbose >= 2)
- fprintf(stderr, "%s: EAGAIN\n", __func__);
- break;
- default:
- if (verbose >= 2)
- fprintf(stderr, "%s: select failed: %s\n", __func__,
- strerror(errno));
- return -1;
- }
- }
- } while (eagain);
-
- return sret;
-}
-
-int close_socket(int fd) {
-#ifdef WIN32
- return closesocket(fd);
-#else
- return close(fd);
-#endif
-}
-
-int recv_buf(int fd, void *data, size_t length)
-{
- return recv_buf_timeout(fd, data, length, 0, RECV_TIMEOUT);
-}
-
-int peek_buf(int fd, void *data, size_t length)
-{
- return recv_buf_timeout(fd, data, length, MSG_PEEK, RECV_TIMEOUT);
-}
-
-int recv_buf_timeout(int fd, void *data, size_t length, int flags,
- unsigned int timeout)
-{
- int res;
- int result;
-
- // check if data is available
- res = check_fd(fd, FDM_READ, timeout);
- if (res <= 0) {
- return res;
- }
- // if we get here, there _is_ data available
- result = recv(fd, data, length, flags);
- if (res > 0 && result == 0) {
- // but this is an error condition
- if (verbose >= 3)
- fprintf(stderr, "%s: fd=%d recv returned 0\n", __func__, fd);
- return -EAGAIN;
- }
- if (result < 0) {
- return -errno;
- }
- return result;
-}
-
-int send_buf(int fd, void *data, size_t length)
-{
- return send(fd, data, length, 0);
-}
diff --git a/libusbmuxd/sock_stuff.h b/libusbmuxd/sock_stuff.h
deleted file mode 100644
index eb9622c..0000000
--- a/libusbmuxd/sock_stuff.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- libusbmuxd - client library to talk to usbmuxd
-
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
-Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com>
-
-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 General Public License for more details.
-
-You should have received a copy of the GNU Lesser 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
-
-*/
-
-#ifndef __SOCK_STUFF_H
-#define __SOCK_STUFF_H
-
-#include <stdint.h>
-
-enum fd_mode {
- FDM_READ,
- FDM_WRITE,
- FDM_EXCEPT
-};
-typedef enum fd_mode fd_mode;
-
-#ifndef WIN32
-int create_unix_socket(const char *filename);
-int connect_unix_socket(const char *filename);
-#endif
-int create_socket(uint16_t port);
-#if defined(WIN32) || defined(__CYGWIN__)
-int connect_socket(const char *addr, uint16_t port);
-#endif
-int check_fd(int fd, fd_mode fdm, unsigned int timeout);
-
-int close_socket(int fd);
-
-int recv_buf(int fd, void *data, size_t size);
-int peek_buf(int fd, void *data, size_t size);
-int recv_buf_timeout(int fd, void *data, size_t size, int flags,
- unsigned int timeout);
-
-int send_buf(int fd, void *data, size_t size);
-
-void sock_stuff_set_verbose(int level);
-
-#endif /* __SOCK_STUFF_H */
diff --git a/libusbmuxd/usbmuxd.h b/libusbmuxd/usbmuxd.h
deleted file mode 100644
index eabd216..0000000
--- a/libusbmuxd/usbmuxd.h
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- libusbmuxd - client library to talk to usbmuxd
-
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
-Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com>
-
-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 General Public License for more details.
-
-You should have received a copy of the GNU Lesser 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
-
-*/
-
-#ifndef __USBMUXD_H
-#define __USBMUXD_H
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Device information structure holding data to identify the device.
- * The relevant 'handle' should be passed to 'usbmuxd_connect()', to
- * start a proxy connection. The value 'handle' should be considered
- * opaque and no presumption made about the meaning of its value.
- */
-typedef struct {
- int handle;
- int product_id;
- char uuid[41];
-} usbmuxd_device_info_t;
-
-/**
- * event types for event callback function
- */
-enum usbmuxd_event_type {
- UE_DEVICE_ADD = 1,
- UE_DEVICE_REMOVE
-};
-
-/**
- * Event structure that will be passed to the callback function.
- * 'event' will contains the type of the event, and 'device' will contains
- * information about the device.
- */
-typedef struct {
- int event;
- usbmuxd_device_info_t device;
-} usbmuxd_event_t;
-
-/**
- * Callback function prototype.
- */
-typedef void (*usbmuxd_event_cb_t) (const usbmuxd_event_t *event, void *user_data);
-
-/**
- * Subscribe a callback function so that applications get to know about
- * device add/remove events.
- *
- * @param callback A callback function that is executed when an event occurs.
- *
- * @return 0 on success or negative on error.
- */
-int usbmuxd_subscribe(usbmuxd_event_cb_t callback, void *user_data);
-
-/**
- * Unsubscribe callback.
- *
- * @return only 0 for now.
- */
-int usbmuxd_unsubscribe();
-
-/**
- * Contacts usbmuxd and retrieves a list of connected devices.
- *
- * @param device_list A pointer to an array of usbmuxd_device_info_t
- * that will hold records of the connected devices. The last record
- * is a null-terminated record with all fields set to 0/NULL.
- * @note The user has to free the list returned.
- *
- * @return number of attached devices, zero on no devices, or negative
- * if an error occured.
- */
-int usbmuxd_get_device_list(usbmuxd_device_info_t **device_list);
-
-/**
- * Frees the device list returned by an usbmuxd_get_device_list call
- *
- * @param device_list A pointer to an array of usbmuxd_device_info_t to free.
- *
- * @return 0 on success, -1 on error.
- */
-int usbmuxd_device_list_free(usbmuxd_device_info_t **device_list);
-
-/**
- * Gets device information for the device specified by uuid.
- *
- * @param uuid A device uuid of the device to look for. If uuid is NULL,
- * This function will return the first device found.
- * @param device Pointer to a previously allocated (or static)
- * usbmuxd_device_info_t that will be filled with the device info.
- *
- * @return 0 if no matching device is connected, 1 if the device was found,
- * or a negative value on error.
- */
-int usbmuxd_get_device_by_uuid(const char *uuid, usbmuxd_device_info_t *device);
-
-/**
- * Request proxy connect to
- *
- * @param handle returned by 'usbmuxd_scan()'
- *
- * @param tcp_port TCP port number on device, in range 0-65535.
- * common values are 62078 for lockdown, and 22 for SSH.
- *
- * @return file descriptor socket of the connection, or -1 on error
- */
-int usbmuxd_connect(const int handle, const unsigned short tcp_port);
-
-/**
- * Disconnect. For now, this just closes the socket file descriptor.
- *
- * @param sfd socker file descriptor returned by usbmuxd_connect()
- *
- * @return 0 on success, -1 on error.
- */
-int usbmuxd_disconnect(int sfd);
-
-/**
- * Send data to the specified socket.
- *
- * @param sfd socket file descriptor returned by usbmuxd_connect()
- * @param data buffer to send
- * @param len size of buffer to send
- * @param sent_bytes how many bytes sent
- *
- * @return 0 on success, a negative errno value otherwise.
- */
-int usbmuxd_send(int sfd, const char *data, uint32_t len, uint32_t *sent_bytes);
-
-/**
- * Receive data from the specified socket.
- *
- * @param sfd socket file descriptor returned by usbmuxd_connect()
- * @param data buffer to put the data to
- * @param len number of bytes to receive
- * @param recv_bytes number of bytes received
- * @param timeout how many milliseconds to wait for data
- *
- * @return 0 on success, a negative errno value otherwise.
- */
-int usbmuxd_recv_timeout(int sfd, char *data, uint32_t len, uint32_t *recv_bytes, unsigned int timeout);
-
-/**
- * Receive data from the specified socket with a default timeout.
- *
- * @param sfd socket file descriptor returned by usbmuxd_connect()
- * @param data buffer to put the data to
- * @param len number of bytes to receive
- * @param recv_bytes number of bytes received
- *
- * @return 0 on success, a negative errno value otherwise.
- */
-int usbmuxd_recv(int sfd, char *data, uint32_t len, uint32_t *recv_bytes);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __USBMUXD_H */
diff --git a/m4/as-compiler-flag.m4 b/m4/as-compiler-flag.m4
new file mode 100644
index 0000000..baab5d9
--- /dev/null
+++ b/m4/as-compiler-flag.m4
@@ -0,0 +1,62 @@
+dnl as-compiler-flag.m4 0.1.0
+
+dnl autostars m4 macro for detection of compiler flags
+
+dnl David Schleef <ds@schleef.org>
+
+dnl $Id: as-compiler-flag.m4,v 1.1 2005/12/15 23:35:19 ds Exp $
+
+dnl AS_COMPILER_FLAG(CFLAGS, ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED])
+dnl Tries to compile with the given CFLAGS.
+dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags,
+dnl and ACTION-IF-NOT-ACCEPTED otherwise.
+
+AC_DEFUN([AS_COMPILER_FLAG],
+[
+ AC_MSG_CHECKING([to see if compiler understands $1])
+
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $1"
+
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], [flag_ok=yes], [flag_ok=no])
+ CFLAGS="$save_CFLAGS"
+
+ if test "X$flag_ok" = Xyes ; then
+ m4_ifvaln([$2],[$2])
+ true
+ else
+ m4_ifvaln([$3],[$3])
+ true
+ fi
+ AC_MSG_RESULT([$flag_ok])
+])
+
+dnl AS_COMPILER_FLAGS(VAR, FLAGS)
+dnl Tries to compile with the given CFLAGS.
+
+AC_DEFUN([AS_COMPILER_FLAGS],
+[
+ list=$2
+ flags_supported=""
+ flags_unsupported=""
+ AC_MSG_CHECKING([for supported compiler flags])
+ for each in $list
+ do
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $each"
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], [flag_ok=yes], [flag_ok=no])
+ CFLAGS="$save_CFLAGS"
+
+ if test "X$flag_ok" = Xyes ; then
+ flags_supported="$flags_supported $each"
+ else
+ flags_unsupported="$flags_unsupported $each"
+ fi
+ done
+ AC_MSG_RESULT([$flags_supported])
+ if test "X$flags_unsupported" != X ; then
+ AC_MSG_WARN([unsupported compiler flags: $flags_unsupported])
+ fi
+ $1="$$1 $flags_supported"
+])
+
diff --git a/python-client/.gitignore b/python-client/.gitignore
deleted file mode 100644
index 5da7ef5..0000000
--- a/python-client/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.pyc
-*.pyo
-
diff --git a/python-client/tcprelay.py b/python-client/tcprelay.py
deleted file mode 100644
index add200c..0000000
--- a/python-client/tcprelay.py
+++ /dev/null
@@ -1,148 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# tcprelay.py - TCP connection relay for usbmuxd
-#
-# Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 2 or version 3.
-#
-# 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
-
-import usbmux
-import SocketServer
-import select
-from optparse import OptionParser
-import sys
-import threading
-
-class SocketRelay(object):
- def __init__(self, a, b, maxbuf=65535):
- self.a = a
- self.b = b
- self.atob = ""
- self.btoa = ""
- self.maxbuf = maxbuf
- def handle(self):
- while True:
- rlist = []
- wlist = []
- xlist = [self.a, self.b]
- if self.atob:
- wlist.append(self.b)
- if self.btoa:
- wlist.append(self.a)
- if len(self.atob) < self.maxbuf:
- rlist.append(self.a)
- if len(self.btoa) < self.maxbuf:
- rlist.append(self.b)
- rlo, wlo, xlo = select.select(rlist, wlist, xlist)
- if xlo:
- return
- if self.a in wlo:
- n = self.a.send(self.btoa)
- self.btoa = self.btoa[n:]
- if self.b in wlo:
- n = self.b.send(self.atob)
- self.atob = self.atob[n:]
- if self.a in rlo:
- s = self.a.recv(self.maxbuf - len(self.atob))
- if not s:
- return
- self.atob += s
- if self.b in rlo:
- s = self.b.recv(self.maxbuf - len(self.btoa))
- if not s:
- return
- self.btoa += s
- #print "Relay iter: %8d atob, %8d btoa, lists: %r %r %r"%(len(self.atob), len(self.btoa), rlo, wlo, xlo)
-
-class TCPRelay(SocketServer.BaseRequestHandler):
- def handle(self):
- print "Incoming connection to %d"%self.server.server_address[1]
- mux = usbmux.USBMux(options.sockpath)
- print "Waiting for devices..."
- if not mux.devices:
- mux.process(1.0)
- if not mux.devices:
- print "No device found"
- self.request.close()
- return
- dev = mux.devices[0]
- print "Connecting to device %s"%str(dev)
- dsock = mux.connect(dev, self.server.rport)
- lsock = self.request
- print "Connection established, relaying data"
- try:
- fwd = SocketRelay(dsock, lsock, self.server.bufsize * 1024)
- fwd.handle()
- finally:
- dsock.close()
- lsock.close()
- print "Connection closed"
-
-class TCPServer(SocketServer.TCPServer):
- allow_reuse_address = True
-
-class ThreadedTCPServer(SocketServer.ThreadingMixIn, TCPServer):
- pass
-
-HOST = "localhost"
-
-parser = OptionParser(usage="usage: %prog [OPTIONS] RemotePort[:LocalPort] [RemotePort[:LocalPort]]...")
-parser.add_option("-t", "--threaded", dest='threaded', action='store_true', default=False, help="use threading to handle multiple connections at once")
-parser.add_option("-b", "--bufsize", dest='bufsize', action='store', metavar='KILOBYTES', type='int', default=128, help="specify buffer size for socket forwarding")
-parser.add_option("-s", "--socket", dest='sockpath', action='store', metavar='PATH', type='str', default=None, help="specify the path of the usbmuxd socket")
-
-options, args = parser.parse_args()
-
-serverclass = TCPServer
-if options.threaded:
- serverclass = ThreadedTCPServer
-
-if len(args) == 0:
- parser.print_help()
- sys.exit(1)
-
-ports = []
-
-for arg in args:
- try:
- if ':' in arg:
- rport, lport = arg.split(":")
- rport = int(rport)
- lport = int(lport)
- ports.append((rport, lport))
- else:
- ports.append((int(arg), int(arg)))
- except:
- parser.print_help()
- sys.exit(1)
-
-servers=[]
-
-for rport, lport in ports:
- print "Forwarding local port %d to remote port %d"%(lport, rport)
- server = serverclass((HOST, lport), TCPRelay)
- server.rport = rport
- server.bufsize = options.bufsize
- servers.append(server)
-
-alive = True
-
-while alive:
- try:
- rl, wl, xl = select.select(servers, [], [])
- for server in rl:
- server.handle_request()
- except:
- alive = False
diff --git a/python-client/usbmux.py b/python-client/usbmux.py
deleted file mode 100644
index 79ec26a..0000000
--- a/python-client/usbmux.py
+++ /dev/null
@@ -1,246 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# usbmux.py - usbmux client library for Python
-#
-# Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 2 or version 3.
-#
-# 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
-
-import socket, struct, select, sys
-
-try:
- import plistlib
- haveplist = True
-except:
- haveplist = False
-
-class MuxError(Exception):
- pass
-
-class MuxVersionError(MuxError):
- pass
-
-class SafeStreamSocket:
- def __init__(self, address, family):
- self.sock = socket.socket(family, socket.SOCK_STREAM)
- self.sock.connect(address)
- def send(self, msg):
- totalsent = 0
- while totalsent < len(msg):
- sent = self.sock.send(msg[totalsent:])
- if sent == 0:
- raise MuxError("socket connection broken")
- totalsent = totalsent + sent
- def recv(self, size):
- msg = ''
- while len(msg) < size:
- chunk = self.sock.recv(size-len(msg))
- if chunk == '':
- raise MuxError("socket connection broken")
- msg = msg + chunk
- return msg
-
-class MuxDevice(object):
- def __init__(self, devid, usbprod, serial, location):
- self.devid = devid
- self.usbprod = usbprod
- self.serial = serial
- self.location = location
- def __str__(self):
- return "<MuxDevice: ID %d ProdID 0x%04x Serial '%s' Location 0x%x>"%(self.devid, self.usbprod, self.serial, self.location)
-
-class BinaryProtocol(object):
- TYPE_RESULT = 1
- TYPE_CONNECT = 2
- TYPE_LISTEN = 3
- TYPE_DEVICE_ADD = 4
- TYPE_DEVICE_REMOVE = 5
- VERSION = 0
- def __init__(self, socket):
- self.socket = socket
- self.connected = False
-
- def _pack(self, req, payload):
- if req == self.TYPE_CONNECT:
- return struct.pack("IH", payload['DeviceID'], payload['PortNumber']) + "\x00\x00"
- elif req == self.TYPE_LISTEN:
- return ""
- else:
- raise ValueError("Invalid outgoing request type %d"%req)
-
- def _unpack(self, resp, payload):
- if resp == self.TYPE_RESULT:
- return {'Number':struct.unpack("I", payload)[0]}
- elif resp == self.TYPE_DEVICE_ADD:
- devid, usbpid, serial, pad, location = struct.unpack("IH256sHI", payload)
- serial = serial.split("\0")[0]
- return {'DeviceID': devid, 'Properties': {'LocationID': location, 'SerialNumber': serial, 'ProductID': usbpid}}
- elif resp == self.TYPE_DEVICE_REMOVE:
- devid = struct.unpack("I", payload)[0]
- return {'DeviceID': devid}
- else:
- raise MuxError("Invalid incoming request type %d"%req)
-
- def sendpacket(self, req, tag, payload={}):
- payload = self._pack(req, payload)
- if self.connected:
- raise MuxError("Mux is connected, cannot issue control packets")
- length = 16 + len(payload)
- data = struct.pack("IIII", length, self.VERSION, req, tag) + payload
- self.socket.send(data)
- def getpacket(self):
- if self.connected:
- raise MuxError("Mux is connected, cannot issue control packets")
- dlen = self.socket.recv(4)
- dlen = struct.unpack("I", dlen)[0]
- body = self.socket.recv(dlen - 4)
- version, resp, tag = struct.unpack("III",body[:0xc])
- if version != self.VERSION:
- raise MuxVersionError("Version mismatch: expected %d, got %d"%(self.VERSION,version))
- payload = self._unpack(resp, body[0xc:])
- return (resp, tag, payload)
-
-class PlistProtocol(BinaryProtocol):
- TYPE_RESULT = "Result"
- TYPE_CONNECT = "Connect"
- TYPE_LISTEN = "Listen"
- TYPE_DEVICE_ADD = "Attached"
- TYPE_DEVICE_REMOVE = "Detached" #???
- TYPE_PLIST = 8
- VERSION = 1
- def __init__(self, socket):
- if not haveplist:
- raise Exception("You need the plistlib module")
- BinaryProtocol.__init__(self, socket)
-
- def _pack(self, req, payload):
- return payload
-
- def _unpack(self, resp, payload):
- return payload
-
- def sendpacket(self, req, tag, payload={}):
- payload['ClientVersionString'] = 'usbmux.py by marcan'
- if isinstance(req, int):
- req = [self.TYPE_CONNECT, self.TYPE_LISTEN][req-2]
- payload['MessageType'] = req
- payload['ProgName'] = 'tcprelay'
- BinaryProtocol.sendpacket(self, self.TYPE_PLIST, tag, plistlib.writePlistToString(payload))
- def getpacket(self):
- resp, tag, payload = BinaryProtocol.getpacket(self)
- if resp != self.TYPE_PLIST:
- raise MuxError("Received non-plist type %d"%resp)
- payload = plistlib.readPlistFromString(payload)
- return payload['MessageType'], tag, payload
-
-class MuxConnection(object):
- def __init__(self, socketpath, protoclass):
- self.socketpath = socketpath
- if sys.platform in ['win32', 'cygwin']:
- family = socket.AF_INET
- address = ('127.0.0.1', 27015)
- else:
- family = socket.AF_UNIX
- address = self.socketpath
- self.socket = SafeStreamSocket(address, family)
- self.proto = protoclass(self.socket)
- self.pkttag = 1
- self.devices = []
-
- def _getreply(self):
- while True:
- resp, tag, data = self.proto.getpacket()
- if resp == self.proto.TYPE_RESULT:
- return tag, data
- else:
- raise MuxError("Invalid packet type received: %d"%resp)
- def _processpacket(self):
- resp, tag, data = self.proto.getpacket()
- if resp == self.proto.TYPE_DEVICE_ADD:
- self.devices.append(MuxDevice(data['DeviceID'], data['Properties']['ProductID'], data['Properties']['SerialNumber'], data['Properties']['LocationID']))
- elif resp == self.proto.TYPE_DEVICE_REMOVE:
- for dev in self.devices:
- if dev.devid == data['DeviceID']:
- self.devices.remove(dev)
- elif resp == self.proto.TYPE_RESULT:
- raise MuxError("Unexpected result: %d"%resp)
- else:
- raise MuxError("Invalid packet type received: %d"%resp)
- def _exchange(self, req, payload={}):
- mytag = self.pkttag
- self.pkttag += 1
- self.proto.sendpacket(req, mytag, payload)
- recvtag, data = self._getreply()
- if recvtag != mytag:
- raise MuxError("Reply tag mismatch: expected %d, got %d"%(mytag, recvtag))
- return data['Number']
-
- def listen(self):
- ret = self._exchange(self.proto.TYPE_LISTEN)
- if ret != 0:
- raise MuxError("Listen failed: error %d"%ret)
- def process(self, timeout=None):
- if self.proto.connected:
- raise MuxError("Socket is connected, cannot process listener events")
- rlo, wlo, xlo = select.select([self.socket.sock], [], [self.socket.sock], timeout)
- if xlo:
- self.socket.sock.close()
- raise MuxError("Exception in listener socket")
- if rlo:
- self._processpacket()
- def connect(self, device, port):
- ret = self._exchange(self.proto.TYPE_CONNECT, {'DeviceID':device.devid, 'PortNumber':((port<<8) & 0xFF00) | (port>>8)})
- if ret != 0:
- raise MuxError("Connect failed: error %d"%ret)
- self.proto.connected = True
- return self.socket.sock
- def close(self):
- self.socket.sock.close()
-
-class USBMux(object):
- def __init__(self, socketpath=None):
- if socketpath is None:
- if sys.platform == 'darwin':
- socketpath = "/var/run/usbmuxd"
- else:
- socketpath = "/var/run/usbmuxd"
- self.socketpath = socketpath
- self.listener = MuxConnection(socketpath, BinaryProtocol)
- try:
- self.listener.listen()
- self.version = 0
- self.protoclass = BinaryProtocol
- except MuxVersionError:
- self.listener = MuxConnection(socketpath, PlistProtocol)
- self.listener.listen()
- self.protoclass = PlistProtocol
- self.version = 1
- self.devices = self.listener.devices
- def process(self, timeout=None):
- self.listener.process(timeout)
- def connect(self, device, port):
- connector = MuxConnection(self.socketpath, self.protoclass)
- return connector.connect(device, port)
-
-if __name__ == "__main__":
- mux = USBMux()
- print "Waiting for devices..."
- if not mux.devices:
- mux.process(0.1)
- while True:
- print "Devices:"
- for dev in mux.devices:
- print dev
- mux.process()
diff --git a/src/Makefile.am b/src/Makefile.am
new file mode 100644
index 0000000..8a96e46
--- /dev/null
+++ b/src/Makefile.am
@@ -0,0 +1,32 @@
+AM_CPPFLAGS = \
+ -I$(top_srcdir)/include \
+ -I$(top_srcdir)
+
+AM_CFLAGS = \
+ $(GLOBAL_CFLAGS) \
+ $(libplist_CFLAGS) \
+ $(libusb_CFLAGS) \
+ $(limd_glue_CFLAGS) \
+ $(libimobiledevice_CFLAGS)
+
+AM_LDFLAGS = \
+ $(libplist_LIBS) \
+ $(libusb_LIBS) \
+ $(limd_glue_LIBS) \
+ $(libimobiledevice_LIBS) \
+ $(libpthread_LIBS)
+
+sbin_PROGRAMS = usbmuxd
+
+usbmuxd_CFLAGS = $(AM_CFLAGS)
+usbmuxd_LDFLAGS = $(AM_LDFLAGS) -no-undefined
+usbmuxd_SOURCES = \
+ client.c client.h \
+ device.c device.h \
+ preflight.c preflight.h \
+ log.c log.h \
+ usbmuxd-proto.h \
+ usb.c usb.h \
+ utils.c utils.h \
+ conf.c conf.h \
+ main.c
diff --git a/src/client.c b/src/client.c
new file mode 100644
index 0000000..dbbdd5f
--- /dev/null
+++ b/src/client.c
@@ -0,0 +1,1058 @@
+/*
+ * client.c
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+
+#define _GNU_SOURCE 1
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <sys/un.h>
+#include <arpa/inet.h>
+#include <fcntl.h>
+
+#include <plist/plist.h>
+#include <libimobiledevice-glue/collection.h>
+#include <libimobiledevice-glue/thread.h>
+
+#include "log.h"
+#include "usb.h"
+#include "client.h"
+#include "device.h"
+#include "conf.h"
+
+#define CMD_BUF_SIZE 0x10000
+#define REPLY_BUF_SIZE 0x10000
+
+enum client_state {
+ CLIENT_COMMAND, // waiting for command
+ CLIENT_LISTEN, // listening for devices
+ CLIENT_CONNECTING1, // issued connection request
+ CLIENT_CONNECTING2, // connection established, but waiting for response message to get sent
+ CLIENT_CONNECTED, // connected
+ CLIENT_DEAD
+};
+
+struct mux_client {
+ int fd;
+ unsigned char *ob_buf;
+ uint32_t ob_size;
+ uint32_t ob_capacity;
+ unsigned char *ib_buf;
+ uint32_t ib_size;
+ uint32_t ib_capacity;
+ short events, devents;
+ uint32_t connect_tag;
+ int connect_device;
+ enum client_state state;
+ uint32_t proto_version;
+ uint32_t number;
+ plist_t info;
+};
+
+static struct collection client_list;
+mutex_t client_list_mutex;
+static uint32_t client_number = 0;
+
+#ifdef SO_PEERCRED
+static char* _get_process_name_by_pid(const int pid)
+{
+ char* name = (char*)calloc(1024, sizeof(char));
+ if(name) {
+ sprintf(name, "/proc/%d/cmdline", pid);
+ FILE* f = fopen(name, "r");
+ if(f) {
+ size_t size;
+ size = fread(name, sizeof(char), 1024, f);
+ if(size > 0) {
+ if('\n' == name[size-1])
+ name[size-1]='\0';
+ }
+ fclose(f);
+ }
+ }
+ return name;
+}
+#endif
+
+/**
+ * Receive raw data from the client socket.
+ *
+ * @param client Client to read from.
+ * @param buffer Buffer to store incoming data.
+ * @param len Max number of bytes to read.
+ * @return Same as recv() system call. Number of bytes read; when < 0 errno will be set.
+ */
+int client_read(struct mux_client *client, void *buffer, uint32_t len)
+{
+ usbmuxd_log(LL_SPEW, "client_read fd %d buf %p len %d", client->fd, buffer, len);
+ if(client->state != CLIENT_CONNECTED) {
+ usbmuxd_log(LL_ERROR, "Attempted to read from client %d not in CONNECTED state", client->fd);
+ return -1;
+ }
+ return recv(client->fd, buffer, len, 0);
+}
+
+/**
+ * Send raw data to the client socket.
+ *
+ * @param client Client to send to.
+ * @param buffer The data to send.
+ * @param len Number of bytes to write.
+ * @return Same as system call send(). Number of bytes written; when < 0 errno will be set.
+ */
+int client_write(struct mux_client *client, void *buffer, uint32_t len)
+{
+ int sret = -1;
+
+ usbmuxd_log(LL_SPEW, "client_write fd %d buf %p len %d", client->fd, buffer, len);
+ if(client->state != CLIENT_CONNECTED) {
+ usbmuxd_log(LL_ERROR, "Attempted to write to client %d not in CONNECTED state", client->fd);
+ return -1;
+ }
+
+ sret = send(client->fd, buffer, len, 0);
+ if (sret < 0) {
+ if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
+ usbmuxd_log(LL_DEBUG, "client_write: fd %d not ready for writing", client->fd);
+ sret = 0;
+ } else {
+ usbmuxd_log(LL_ERROR, "ERROR: client_write: sending to fd %d failed: %s", client->fd, strerror(errno));
+ }
+ }
+ return sret;
+}
+
+/**
+ * Set event mask to use for ppoll()ing the client socket.
+ * Typically POLLOUT and/or POLLIN. Note that this overrides
+ * the current mask, that is, it is not ORing the argument
+ * into the current mask.
+ *
+ * @param client The client to set the event mask on.
+ * @param events The event mask to sert.
+ * @return 0 on success, -1 on error.
+ */
+int client_set_events(struct mux_client *client, short events)
+{
+ if((client->state != CLIENT_CONNECTED) && (client->state != CLIENT_CONNECTING2)) {
+ usbmuxd_log(LL_ERROR, "client_set_events to client %d not in CONNECTED state", client->fd);
+ return -1;
+ }
+ client->devents = events;
+ if(client->state == CLIENT_CONNECTED)
+ client->events = events;
+ return 0;
+}
+
+/**
+ * Wait for an inbound connection on the usbmuxd socket
+ * and create a new mux_client instance for it, and store
+ * the client in the client list.
+ *
+ * @param listenfd the socket fd to accept() on.
+ * @return The connection fd for the client, or < 0 for error
+ * in which case errno will be set.
+ */
+int client_accept(int listenfd)
+{
+ struct sockaddr_un addr;
+ int cfd;
+ socklen_t len = sizeof(struct sockaddr_un);
+ cfd = accept(listenfd, (struct sockaddr *)&addr, &len);
+ if (cfd < 0) {
+ usbmuxd_log(LL_ERROR, "accept() failed (%s)", strerror(errno));
+ return cfd;
+ }
+
+ int flags = fcntl(cfd, F_GETFL, 0);
+ if (flags < 0) {
+ usbmuxd_log(LL_ERROR, "ERROR: Could not get socket flags!");
+ } else {
+ if (fcntl(cfd, F_SETFL, flags | O_NONBLOCK) < 0) {
+ usbmuxd_log(LL_ERROR, "ERROR: Could not set socket to non-blocking mode");
+ }
+ }
+
+ int bufsize = 0x20000;
+ if (setsockopt(cfd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int)) == -1) {
+ usbmuxd_log(LL_WARNING, "Could not set send buffer for client socket");
+ }
+ if (setsockopt(cfd, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int)) == -1) {
+ usbmuxd_log(LL_WARNING, "Could not set receive buffer for client socket");
+ }
+
+ int yes = 1;
+ setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(int));
+
+ struct mux_client *client;
+ client = malloc(sizeof(struct mux_client));
+ memset(client, 0, sizeof(struct mux_client));
+
+ client->fd = cfd;
+ client->ob_buf = malloc(REPLY_BUF_SIZE);
+ client->ob_size = 0;
+ client->ob_capacity = REPLY_BUF_SIZE;
+ client->ib_buf = malloc(CMD_BUF_SIZE);
+ client->ib_size = 0;
+ client->ib_capacity = CMD_BUF_SIZE;
+ client->state = CLIENT_COMMAND;
+ client->events = POLLIN;
+ client->info = NULL;
+
+ mutex_lock(&client_list_mutex);
+ client->number = client_number++;
+ collection_add(&client_list, client);
+ mutex_unlock(&client_list_mutex);
+
+#ifdef SO_PEERCRED
+ if (log_level >= LL_INFO) {
+ struct ucred cr;
+ len = sizeof(struct ucred);
+ getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
+
+ if (getpid() == cr.pid) {
+ usbmuxd_log(LL_INFO, "Client %d accepted: %s[%d]", client->fd, PACKAGE_NAME, cr.pid);
+ } else {
+ char* process_name = _get_process_name_by_pid(cr.pid);
+ usbmuxd_log(LL_INFO, "Client %d accepted: %s[%d]", client->fd, process_name, cr.pid);
+ free(process_name);
+ }
+ }
+#else
+ usbmuxd_log(LL_INFO, "Client %d accepted", client->fd);
+#endif
+ return client->fd;
+}
+
+void client_close(struct mux_client *client)
+{
+ int found = 0;
+ mutex_lock(&client_list_mutex);
+ FOREACH(struct mux_client *lc, &client_list) {
+ if (client == lc) {
+ found = 1;
+ break;
+ }
+ } ENDFOREACH
+ if (!found) {
+ // in case we get called again but client was already freed
+ usbmuxd_log(LL_DEBUG, "%s: ignoring for non-existing client %p", __func__, client);
+ mutex_unlock(&client_list_mutex);
+ return;
+ }
+#ifdef SO_PEERCRED
+ if (log_level >= LL_INFO) {
+ struct ucred cr;
+ socklen_t len = sizeof(struct ucred);
+ getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
+
+ if (getpid() == cr.pid) {
+ usbmuxd_log(LL_INFO, "Client %d is going to be disconnected: %s[%d]", client->fd, PACKAGE_NAME, cr.pid);
+ } else {
+ char* process_name = _get_process_name_by_pid(cr.pid);
+ usbmuxd_log(LL_INFO, "Client %d is going to be disconnected: %s[%d]", client->fd, process_name, cr.pid);
+ free(process_name);
+ }
+ }
+#else
+ usbmuxd_log(LL_INFO, "Client %d is going to be disconnected", client->fd);
+#endif
+ if(client->state == CLIENT_CONNECTING1 || client->state == CLIENT_CONNECTING2) {
+ usbmuxd_log(LL_INFO, "Client died mid-connect, aborting device %d connection", client->connect_device);
+ client->state = CLIENT_DEAD;
+ device_abort_connect(client->connect_device, client);
+ }
+ close(client->fd);
+ free(client->ob_buf);
+ free(client->ib_buf);
+ plist_free(client->info);
+
+ collection_remove(&client_list, client);
+ mutex_unlock(&client_list_mutex);
+ free(client);
+}
+
+void client_get_fds(struct fdlist *list)
+{
+ mutex_lock(&client_list_mutex);
+ FOREACH(struct mux_client *client, &client_list) {
+ fdlist_add(list, FD_CLIENT, client->fd, client->events);
+ } ENDFOREACH
+ mutex_unlock(&client_list_mutex);
+}
+
+static int output_buffer_add_message(struct mux_client *client, uint32_t tag, enum usbmuxd_msgtype msg, void *payload, int payload_length)
+{
+ struct usbmuxd_header hdr;
+ hdr.version = client->proto_version;
+ hdr.length = sizeof(hdr) + payload_length;
+ hdr.message = msg;
+ hdr.tag = tag;
+ usbmuxd_log(LL_DEBUG, "Client %d output buffer got tag %d msg %d payload_length %d", client->fd, tag, msg, payload_length);
+
+ uint32_t available = client->ob_capacity - client->ob_size;
+ /* the output buffer _should_ be large enough, but just in case */
+ if(available < hdr.length) {
+ unsigned char* new_buf;
+ uint32_t new_size = ((client->ob_capacity + hdr.length + 4096) / 4096) * 4096;
+ usbmuxd_log(LL_DEBUG, "%s: Enlarging client %d output buffer %d -> %d", __func__, client->fd, client->ob_capacity, new_size);
+ new_buf = realloc(client->ob_buf, new_size);
+ if (!new_buf) {
+ usbmuxd_log(LL_FATAL, "%s: Failed to realloc.", __func__);
+ return -1;
+ }
+ client->ob_buf = new_buf;
+ client->ob_capacity = new_size;
+ }
+ memcpy(client->ob_buf + client->ob_size, &hdr, sizeof(hdr));
+ if(payload && payload_length)
+ memcpy(client->ob_buf + client->ob_size + sizeof(hdr), payload, payload_length);
+ client->ob_size += hdr.length;
+ client->events |= POLLOUT;
+ return hdr.length;
+}
+
+static int send_plist(struct mux_client *client, uint32_t tag, plist_t plist)
+{
+ int res = -1;
+ char *xml = NULL;
+ uint32_t xmlsize = 0;
+ plist_to_xml(plist, &xml, &xmlsize);
+ if (xml) {
+ res = output_buffer_add_message(client, tag, MESSAGE_PLIST, xml, xmlsize);
+ free(xml);
+ } else {
+ usbmuxd_log(LL_ERROR, "%s: Could not convert plist to xml", __func__);
+ }
+ return res;
+}
+
+static int send_result(struct mux_client *client, uint32_t tag, uint32_t result)
+{
+ int res = -1;
+ if (client->proto_version == 1) {
+ /* XML plist packet */
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "MessageType", plist_new_string("Result"));
+ plist_dict_set_item(dict, "Number", plist_new_uint(result));
+ res = send_plist(client, tag, dict);
+ plist_free(dict);
+ } else {
+ /* binary packet */
+ res = output_buffer_add_message(client, tag, MESSAGE_RESULT, &result, sizeof(uint32_t));
+ }
+ return res;
+}
+
+int client_notify_connect(struct mux_client *client, enum usbmuxd_result result)
+{
+ usbmuxd_log(LL_SPEW, "client_notify_connect fd %d result %d", client->fd, result);
+ if(client->state == CLIENT_DEAD)
+ return -1;
+ if(client->state != CLIENT_CONNECTING1) {
+ usbmuxd_log(LL_ERROR, "client_notify_connect when client %d is not in CONNECTING1 state", client->fd);
+ return -1;
+ }
+ if(send_result(client, client->connect_tag, result) < 0)
+ return -1;
+ if(result == RESULT_OK) {
+ client->state = CLIENT_CONNECTING2;
+ client->events = POLLOUT; // wait for the result packet to go through
+ // no longer need this
+ free(client->ib_buf);
+ client->ib_buf = NULL;
+ } else {
+ client->state = CLIENT_COMMAND;
+ }
+ return 0;
+}
+
+static plist_t create_device_attached_plist(struct device_info *dev)
+{
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "MessageType", plist_new_string("Attached"));
+ plist_dict_set_item(dict, "DeviceID", plist_new_uint(dev->id));
+ plist_t props = plist_new_dict();
+ plist_dict_set_item(props, "ConnectionSpeed", plist_new_uint(dev->speed));
+ plist_dict_set_item(props, "ConnectionType", plist_new_string("USB"));
+ plist_dict_set_item(props, "DeviceID", plist_new_uint(dev->id));
+ plist_dict_set_item(props, "LocationID", plist_new_uint(dev->location));
+ plist_dict_set_item(props, "ProductID", plist_new_uint(dev->pid));
+ plist_dict_set_item(props, "SerialNumber", plist_new_string(dev->serial));
+ plist_dict_set_item(dict, "Properties", props);
+ return dict;
+}
+
+static int send_device_list(struct mux_client *client, uint32_t tag)
+{
+ int res = -1;
+ plist_t dict = plist_new_dict();
+ plist_t devices = plist_new_array();
+
+ struct device_info *devs = NULL;
+ struct device_info *dev;
+ int i;
+
+ int count = device_get_list(0, &devs);
+ dev = devs;
+ for (i = 0; devs && i < count; i++) {
+ plist_t device = create_device_attached_plist(dev++);
+ if (device) {
+ plist_array_append_item(devices, device);
+ }
+ }
+ if (devs)
+ free(devs);
+
+ plist_dict_set_item(dict, "DeviceList", devices);
+ res = send_plist(client, tag, dict);
+ plist_free(dict);
+ return res;
+}
+
+static int send_listener_list(struct mux_client *client, uint32_t tag)
+{
+ int res = -1;
+
+ plist_t dict = plist_new_dict();
+ plist_t listeners = plist_new_array();
+
+ mutex_lock(&client_list_mutex);
+ FOREACH(struct mux_client *lc, &client_list) {
+ if (lc->state == CLIENT_LISTEN) {
+ plist_t n = NULL;
+ plist_t l = plist_new_dict();
+ plist_dict_set_item(l, "Blacklisted", plist_new_bool(0));
+ n = NULL;
+ if (lc->info) {
+ n = plist_dict_get_item(lc->info, "BundleID");
+ }
+ if (n) {
+ plist_dict_set_item(l, "BundleID", plist_copy(n));
+ }
+ plist_dict_set_item(l, "ConnType", plist_new_uint(0));
+
+ n = NULL;
+ char *progname = NULL;
+ if (lc->info) {
+ n = plist_dict_get_item(lc->info, "ProgName");
+ }
+ if (n) {
+ plist_get_string_val(n, &progname);
+ }
+ if (!progname) {
+ progname = strdup("unknown");
+ }
+ char *idstring = malloc(strlen(progname) + 12);
+ sprintf(idstring, "%u-%s", client->number, progname);
+
+ plist_dict_set_item(l, "ID String", plist_new_string(idstring));
+ free(idstring);
+ plist_dict_set_item(l, "ProgName", plist_new_string(progname));
+ free(progname);
+
+ n = NULL;
+ uint64_t version = 0;
+ if (lc->info) {
+ n = plist_dict_get_item(lc->info, "kLibUSBMuxVersion");
+ }
+ if (n) {
+ plist_get_uint_val(n, &version);
+ }
+ plist_dict_set_item(l, "kLibUSBMuxVersion", plist_new_uint(version));
+
+ plist_array_append_item(listeners, l);
+ }
+ } ENDFOREACH
+ mutex_unlock(&client_list_mutex);
+
+ plist_dict_set_item(dict, "ListenerList", listeners);
+ res = send_plist(client, tag, dict);
+ plist_free(dict);
+
+ return res;
+}
+
+static int send_system_buid(struct mux_client *client, uint32_t tag)
+{
+ int res = -1;
+ char* buid = NULL;
+
+ config_get_system_buid(&buid);
+
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "BUID", plist_new_string(buid));
+ free(buid);
+ res = send_plist(client, tag, dict);
+ plist_free(dict);
+ return res;
+}
+
+static int send_pair_record(struct mux_client *client, uint32_t tag, const char* record_id)
+{
+ int res = -1;
+ char* record_data = NULL;
+ uint64_t record_size = 0;
+
+ if (!record_id) {
+ return send_result(client, tag, EINVAL);
+ }
+
+ config_get_device_record(record_id, &record_data, &record_size);
+
+ if (record_data) {
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "PairRecordData", plist_new_data(record_data, record_size));
+ free(record_data);
+ res = send_plist(client, tag, dict);
+ plist_free(dict);
+ } else {
+ res = send_result(client, tag, ENOENT);
+ }
+ return res;
+}
+
+static int send_device_add(struct mux_client *client, struct device_info *dev)
+{
+ int res = -1;
+ if (client->proto_version == 1) {
+ /* XML plist packet */
+ plist_t dict = create_device_attached_plist(dev);
+ res = send_plist(client, 0, dict);
+ plist_free(dict);
+ } else {
+ /* binary packet */
+ struct usbmuxd_device_record dmsg;
+ memset(&dmsg, 0, sizeof(dmsg));
+ dmsg.device_id = dev->id;
+ strncpy(dmsg.serial_number, dev->serial, 256);
+ dmsg.serial_number[255] = 0;
+ dmsg.location = dev->location;
+ dmsg.product_id = dev->pid;
+ res = output_buffer_add_message(client, 0, MESSAGE_DEVICE_ADD, &dmsg, sizeof(dmsg));
+ }
+ return res;
+}
+
+static int send_device_remove(struct mux_client *client, uint32_t device_id)
+{
+ int res = -1;
+ if (client->proto_version == 1) {
+ /* XML plist packet */
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "MessageType", plist_new_string("Detached"));
+ plist_dict_set_item(dict, "DeviceID", plist_new_uint(device_id));
+ res = send_plist(client, 0, dict);
+ plist_free(dict);
+ } else {
+ /* binary packet */
+ res = output_buffer_add_message(client, 0, MESSAGE_DEVICE_REMOVE, &device_id, sizeof(uint32_t));
+ }
+ return res;
+}
+
+static int send_device_paired(struct mux_client *client, uint32_t device_id)
+{
+ int res = -1;
+ if (client->proto_version == 1) {
+ /* XML plist packet */
+ plist_t dict = plist_new_dict();
+ plist_dict_set_item(dict, "MessageType", plist_new_string("Paired"));
+ plist_dict_set_item(dict, "DeviceID", plist_new_uint(device_id));
+ res = send_plist(client, 0, dict);
+ plist_free(dict);
+ }
+ else {
+ /* binary packet */
+ res = output_buffer_add_message(client, 0, MESSAGE_DEVICE_PAIRED, &device_id, sizeof(uint32_t));
+ }
+ return res;
+}
+
+static int start_listen(struct mux_client *client)
+{
+ struct device_info *devs = NULL;
+ struct device_info *dev;
+ int count, i;
+
+ client->state = CLIENT_LISTEN;
+
+ count = device_get_list(0, &devs);
+ dev = devs;
+ for(i=0; devs && i < count; i++) {
+ if(send_device_add(client, dev++) < 0) {
+ free(devs);
+ return -1;
+ }
+ }
+ if (devs)
+ free(devs);
+
+ return count;
+}
+
+static char* plist_dict_get_string_val(plist_t dict, const char* key)
+{
+ if (!dict || plist_get_node_type(dict) != PLIST_DICT)
+ return NULL;
+ plist_t item = plist_dict_get_item(dict, key);
+ if (!item || plist_get_node_type(item) != PLIST_STRING)
+ return NULL;
+ char *str = NULL;
+ plist_get_string_val(item, &str);
+ return str;
+}
+
+static void update_client_info(struct mux_client *client, plist_t dict)
+{
+ plist_t node = NULL;
+ plist_t info = plist_new_dict();
+
+ node = plist_dict_get_item(dict, "BundleID");
+ if (node && (plist_get_node_type(node) == PLIST_STRING)) {
+ plist_dict_set_item(info, "BundleID", plist_copy(node));
+ }
+
+ node = plist_dict_get_item(dict, "ClientVersionString");
+ if (node && (plist_get_node_type(node) == PLIST_STRING)) {
+ plist_dict_set_item(info, "ClientVersionString", plist_copy(node));
+ }
+
+ node = plist_dict_get_item(dict, "ProgName");
+ if (node && (plist_get_node_type(node) == PLIST_STRING)) {
+ plist_dict_set_item(info, "ProgName", plist_copy(node));
+ }
+
+ node = plist_dict_get_item(dict, "kLibUSBMuxVersion");
+ if (node && (plist_get_node_type(node) == PLIST_UINT)) {
+ plist_dict_set_item(info, "kLibUSBMuxVersion", plist_copy(node));
+ }
+ plist_free(client->info);
+ client->info = info;
+}
+
+static int handle_command(struct mux_client *client, struct usbmuxd_header *hdr)
+{
+ int res;
+ usbmuxd_log(LL_DEBUG, "Client %d command len %d ver %d msg %d tag %d", client->fd, hdr->length, hdr->version, hdr->message, hdr->tag);
+
+ if(client->state != CLIENT_COMMAND) {
+ usbmuxd_log(LL_ERROR, "Client %d command received in the wrong state, got %d but want %d", client->fd, client->state, CLIENT_COMMAND);
+ if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
+ return -1;
+ client_close(client);
+ return -1;
+ }
+
+ if((hdr->version != 0) && (hdr->version != 1)) {
+ usbmuxd_log(LL_INFO, "Client %d version mismatch: expected 0 or 1, got %d", client->fd, hdr->version);
+ send_result(client, hdr->tag, RESULT_BADVERSION);
+ return 0;
+ }
+
+ struct usbmuxd_connect_request *ch;
+ char *payload;
+ uint32_t payload_size;
+
+ switch(hdr->message) {
+ case MESSAGE_PLIST:
+ client->proto_version = 1;
+ payload = (char*)(hdr) + sizeof(struct usbmuxd_header);
+ payload_size = hdr->length - sizeof(struct usbmuxd_header);
+ plist_t dict = NULL;
+ plist_from_xml(payload, payload_size, &dict);
+ if (!dict) {
+ usbmuxd_log(LL_ERROR, "Could not parse plist from payload!");
+ return -1;
+ } else {
+ char *message = NULL;
+ plist_t node = plist_dict_get_item(dict, "MessageType");
+ if (!node || plist_get_node_type(node) != PLIST_STRING) {
+ usbmuxd_log(LL_ERROR, "Could not read valid MessageType node from plist!");
+ plist_free(dict);
+ return -1;
+ }
+ plist_get_string_val(node, &message);
+ if (!message) {
+ usbmuxd_log(LL_ERROR, "Could not extract MessageType from plist!");
+ plist_free(dict);
+ return -1;
+ }
+ update_client_info(client, dict);
+ if (!strcmp(message, "Listen")) {
+ free(message);
+ plist_free(dict);
+ if (send_result(client, hdr->tag, 0) < 0)
+ return -1;
+ usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd);
+ return start_listen(client);
+ } else if (!strcmp(message, "Connect")) {
+ uint64_t val;
+ uint16_t portnum = 0;
+ uint32_t device_id = 0;
+ free(message);
+ // get device id
+ node = plist_dict_get_item(dict, "DeviceID");
+ if (!node) {
+ usbmuxd_log(LL_ERROR, "Received connect request without device_id!");
+ plist_free(dict);
+ if (send_result(client, hdr->tag, RESULT_BADDEV) < 0)
+ return -1;
+ return 0;
+ }
+ val = 0;
+ plist_get_uint_val(node, &val);
+ device_id = (uint32_t)val;
+
+ // get port number
+ node = plist_dict_get_item(dict, "PortNumber");
+ if (!node) {
+ usbmuxd_log(LL_ERROR, "Received connect request without port number!");
+ plist_free(dict);
+ if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
+ return -1;
+ return 0;
+ }
+ val = 0;
+ plist_get_uint_val(node, &val);
+ portnum = (uint16_t)val;
+ plist_free(dict);
+
+ usbmuxd_log(LL_DEBUG, "Client %d requesting connection to device %d port %d", client->fd, device_id, ntohs(portnum));
+ res = device_start_connect(device_id, ntohs(portnum), client);
+ if(res < 0) {
+ if (send_result(client, hdr->tag, -res) < 0)
+ return -1;
+ } else {
+ client->connect_tag = hdr->tag;
+ client->connect_device = device_id;
+ client->state = CLIENT_CONNECTING1;
+ }
+ return 0;
+ } else if (!strcmp(message, "ListDevices")) {
+ free(message);
+ plist_free(dict);
+ if (send_device_list(client, hdr->tag) < 0)
+ return -1;
+ return 0;
+ } else if (!strcmp(message, "ListListeners")) {
+ free(message);
+ plist_free(dict);
+ if (send_listener_list(client, hdr->tag) < 0)
+ return -1;
+ return 0;
+ } else if (!strcmp(message, "ReadBUID")) {
+ free(message);
+ plist_free(dict);
+ if (send_system_buid(client, hdr->tag) < 0)
+ return -1;
+ return 0;
+ } else if (!strcmp(message, "ReadPairRecord")) {
+ free(message);
+ char* record_id = plist_dict_get_string_val(dict, "PairRecordID");
+ plist_free(dict);
+
+ res = send_pair_record(client, hdr->tag, record_id);
+ if (record_id)
+ free(record_id);
+ if (res < 0)
+ return -1;
+ return 0;
+ } else if (!strcmp(message, "SavePairRecord")) {
+ uint32_t rval = RESULT_OK;
+ free(message);
+ char* record_id = plist_dict_get_string_val(dict, "PairRecordID");
+ char* record_data = NULL;
+ uint64_t record_size = 0;
+ plist_t rdata = plist_dict_get_item(dict, "PairRecordData");
+ if (rdata && plist_get_node_type(rdata) == PLIST_DATA) {
+ plist_get_data_val(rdata, &record_data, &record_size);
+ }
+
+ if (record_id && record_data) {
+ res = config_set_device_record(record_id, record_data, record_size);
+ if (res < 0) {
+ rval = -res;
+ } else {
+ plist_t p_dev_id = plist_dict_get_item(dict, "DeviceID");
+ uint32_t dev_id = 0;
+ if (p_dev_id && plist_get_node_type(p_dev_id) == PLIST_UINT) {
+ uint64_t u_dev_id = 0;
+ plist_get_uint_val(p_dev_id, &u_dev_id);
+ dev_id = (uint32_t)u_dev_id;
+ }
+ if (dev_id > 0) {
+ struct device_info *devs = NULL;
+ struct device_info *dev;
+ int i;
+ int count = device_get_list(1, &devs);
+ int found = 0;
+ dev = devs;
+ for (i = 0; devs && i < count; i++, dev++) {
+ if ((uint32_t)dev->id == dev_id && (strcmp(dev->serial, record_id) == 0)) {
+ found++;
+ break;
+ }
+ }
+ if (!found) {
+ usbmuxd_log(LL_ERROR, "ERROR: SavePairRecord: DeviceID %d (%s) is not connected\n", dev_id, record_id);
+ } else {
+ client_device_paired(dev_id);
+ }
+ free(devs);
+ }
+ }
+ free(record_id);
+ } else {
+ rval = EINVAL;
+ }
+ free(record_data);
+ plist_free(dict);
+ if (send_result(client, hdr->tag, rval) < 0)
+ return -1;
+ return 0;
+ } else if (!strcmp(message, "DeletePairRecord")) {
+ uint32_t rval = RESULT_OK;
+ free(message);
+ char* record_id = plist_dict_get_string_val(dict, "PairRecordID");
+ plist_free(dict);
+ if (record_id) {
+ res = config_remove_device_record(record_id);
+ if (res < 0) {
+ rval = -res;
+ }
+ free(record_id);
+ } else {
+ rval = EINVAL;
+ }
+ if (send_result(client, hdr->tag, rval) < 0)
+ return -1;
+ return 0;
+ } else {
+ usbmuxd_log(LL_ERROR, "Unexpected command '%s' received!", message);
+ free(message);
+ plist_free(dict);
+ if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
+ return -1;
+ return 0;
+ }
+ }
+ // should not be reached?!
+ return -1;
+ case MESSAGE_LISTEN:
+ if(send_result(client, hdr->tag, 0) < 0)
+ return -1;
+ usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd);
+ return start_listen(client);
+ case MESSAGE_CONNECT:
+ ch = (void*)hdr;
+ usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, ch->device_id, ntohs(ch->port));
+ res = device_start_connect(ch->device_id, ntohs(ch->port), client);
+ if(res < 0) {
+ if(send_result(client, hdr->tag, -res) < 0)
+ return -1;
+ } else {
+ client->connect_tag = hdr->tag;
+ client->connect_device = ch->device_id;
+ client->state = CLIENT_CONNECTING1;
+ }
+ return 0;
+ default:
+ usbmuxd_log(LL_ERROR, "Client %d invalid command %d", client->fd, hdr->message);
+ if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0)
+ return -1;
+ return 0;
+ }
+ return -1;
+}
+
+static void output_buffer_process(struct mux_client *client)
+{
+ int res;
+ if(!client->ob_size) {
+ usbmuxd_log(LL_WARNING, "Client %d OUT process but nothing to send?", client->fd);
+ client->events &= ~POLLOUT;
+ return;
+ }
+ res = send(client->fd, client->ob_buf, client->ob_size, 0);
+ if(res <= 0) {
+ usbmuxd_log(LL_ERROR, "Sending to client fd %d failed: %d %s", client->fd, res, strerror(errno));
+ client_close(client);
+ return;
+ }
+ if((uint32_t)res == client->ob_size) {
+ client->ob_size = 0;
+ client->events &= ~POLLOUT;
+ if(client->state == CLIENT_CONNECTING2) {
+ usbmuxd_log(LL_DEBUG, "Client %d switching to CONNECTED state", client->fd);
+ client->state = CLIENT_CONNECTED;
+ client->events = client->devents;
+ // no longer need this
+ free(client->ob_buf);
+ client->ob_buf = NULL;
+ }
+ } else {
+ client->ob_size -= res;
+ memmove(client->ob_buf, client->ob_buf + res, client->ob_size);
+ }
+}
+static void input_buffer_process(struct mux_client *client)
+{
+ int res;
+ int did_read = 0;
+ if(client->ib_size < sizeof(struct usbmuxd_header)) {
+ res = recv(client->fd, client->ib_buf + client->ib_size, sizeof(struct usbmuxd_header) - client->ib_size, 0);
+ if(res <= 0) {
+ if(res < 0)
+ usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno));
+ else
+ usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd);
+ client_close(client);
+ return;
+ }
+ client->ib_size += res;
+ if(client->ib_size < sizeof(struct usbmuxd_header))
+ return;
+ did_read = 1;
+ }
+ struct usbmuxd_header *hdr = (void*)client->ib_buf;
+ if(hdr->length > client->ib_capacity) {
+ usbmuxd_log(LL_INFO, "Client %d message is too long (%d bytes)", client->fd, hdr->length);
+ client_close(client);
+ return;
+ }
+ if(hdr->length < sizeof(struct usbmuxd_header)) {
+ usbmuxd_log(LL_ERROR, "Client %d message is too short (%d bytes)", client->fd, hdr->length);
+ client_close(client);
+ return;
+ }
+ if(client->ib_size < hdr->length) {
+ if(did_read)
+ return; //maybe we would block, so defer to next loop
+ res = recv(client->fd, client->ib_buf + client->ib_size, hdr->length - client->ib_size, 0);
+ if(res < 0) {
+ usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno));
+ client_close(client);
+ return;
+ } else if(res == 0) {
+ usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd);
+ client_close(client);
+ return;
+ }
+ client->ib_size += res;
+ if(client->ib_size < hdr->length)
+ return;
+ }
+ handle_command(client, hdr);
+ client->ib_size = 0;
+}
+
+void client_process(int fd, short events)
+{
+ struct mux_client *client = NULL;
+ mutex_lock(&client_list_mutex);
+ FOREACH(struct mux_client *lc, &client_list) {
+ if(lc->fd == fd) {
+ client = lc;
+ break;
+ }
+ } ENDFOREACH
+ mutex_unlock(&client_list_mutex);
+
+ if(!client) {
+ usbmuxd_log(LL_INFO, "client_process: fd %d not found in client list", fd);
+ return;
+ }
+
+ if(client->state == CLIENT_CONNECTED) {
+ usbmuxd_log(LL_SPEW, "client_process in CONNECTED state");
+ device_client_process(client->connect_device, client, events);
+ } else {
+ if(events & POLLIN) {
+ input_buffer_process(client);
+ } else if(events & POLLOUT) { //not both in case client died as part of process_recv
+ output_buffer_process(client);
+ }
+ }
+
+}
+
+void client_device_add(struct device_info *dev)
+{
+ mutex_lock(&client_list_mutex);
+ usbmuxd_log(LL_DEBUG, "client_device_add: id %d, location 0x%x, serial %s", dev->id, dev->location, dev->serial);
+ device_set_visible(dev->id);
+ FOREACH(struct mux_client *client, &client_list) {
+ if(client->state == CLIENT_LISTEN)
+ send_device_add(client, dev);
+ } ENDFOREACH
+ mutex_unlock(&client_list_mutex);
+}
+
+void client_device_remove(int device_id)
+{
+ mutex_lock(&client_list_mutex);
+ uint32_t id = device_id;
+ usbmuxd_log(LL_DEBUG, "client_device_remove: id %d", device_id);
+ FOREACH(struct mux_client *client, &client_list) {
+ if(client->state == CLIENT_LISTEN)
+ send_device_remove(client, id);
+ } ENDFOREACH
+ mutex_unlock(&client_list_mutex);
+}
+
+void client_device_paired(int device_id)
+{
+ mutex_lock(&client_list_mutex);
+ uint32_t id = device_id;
+ usbmuxd_log(LL_DEBUG, "client_device_paired: id %d", device_id);
+ FOREACH(struct mux_client *client, &client_list) {
+ if (client->state == CLIENT_LISTEN)
+ send_device_paired(client, id);
+ } ENDFOREACH
+ mutex_unlock(&client_list_mutex);
+}
+
+void client_init(void)
+{
+ usbmuxd_log(LL_DEBUG, "client_init");
+ collection_init(&client_list);
+ mutex_init(&client_list_mutex);
+}
+
+void client_shutdown(void)
+{
+ usbmuxd_log(LL_DEBUG, "client_shutdown");
+ FOREACH(struct mux_client *client, &client_list) {
+ client_close(client);
+ } ENDFOREACH
+ mutex_destroy(&client_list_mutex);
+ collection_free(&client_list);
+}
diff --git a/src/client.h b/src/client.h
new file mode 100644
index 0000000..6cac4db
--- /dev/null
+++ b/src/client.h
@@ -0,0 +1,47 @@
+/*
+ * client.h
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#ifndef CLIENT_H
+#define CLIENT_H
+
+#include <stdint.h>
+#include "usbmuxd-proto.h"
+
+struct device_info;
+struct mux_client;
+
+int client_read(struct mux_client *client, void *buffer, uint32_t len);
+int client_write(struct mux_client *client, void *buffer, uint32_t len);
+int client_set_events(struct mux_client *client, short events);
+void client_close(struct mux_client *client);
+int client_notify_connect(struct mux_client *client, enum usbmuxd_result result);
+
+void client_device_add(struct device_info *dev);
+void client_device_remove(int device_id);
+void client_device_paired(int device_id);
+
+int client_accept(int fd);
+void client_get_fds(struct fdlist *list);
+void client_process(int fd, short events);
+
+void client_init(void);
+void client_shutdown(void);
+
+#endif
diff --git a/src/conf.c b/src/conf.c
new file mode 100644
index 0000000..2e6c97f
--- /dev/null
+++ b/src/conf.c
@@ -0,0 +1,535 @@
+/*
+ * conf.c
+ *
+ * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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 <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#include <dirent.h>
+#include <libgen.h>
+#include <sys/stat.h>
+#include <errno.h>
+
+#ifdef WIN32
+#include <shlobj.h>
+#endif
+
+#include <libimobiledevice-glue/utils.h>
+#include <plist/plist.h>
+
+#include "conf.h"
+#include "utils.h"
+#include "log.h"
+
+#ifdef WIN32
+#define DIR_SEP '\\'
+#define DIR_SEP_S "\\"
+#else
+#define DIR_SEP '/'
+#define DIR_SEP_S "/"
+#endif
+
+#define CONFIG_SYSTEM_BUID_KEY "SystemBUID"
+#define CONFIG_HOST_ID_KEY "HostID"
+
+#define CONFIG_EXT ".plist"
+
+#ifdef WIN32
+#define CONFIG_DIR "Apple"DIR_SEP_S"Lockdown"
+#else
+#define CONFIG_DIR "lockdown"
+#endif
+
+#define CONFIG_FILE "SystemConfiguration"CONFIG_EXT
+
+static char *__config_dir = NULL;
+
+#ifdef WIN32
+static char *config_utf16_to_utf8(wchar_t *unistr, long len, long *items_read, long *items_written)
+{
+ if (!unistr || (len <= 0)) return NULL;
+ char *outbuf = (char*)malloc(3*(len+1));
+ int p = 0;
+ int i = 0;
+
+ wchar_t wc;
+
+ while (i < len) {
+ wc = unistr[i++];
+ if (wc >= 0x800) {
+ outbuf[p++] = (char)(0xE0 + ((wc >> 12) & 0xF));
+ outbuf[p++] = (char)(0x80 + ((wc >> 6) & 0x3F));
+ outbuf[p++] = (char)(0x80 + (wc & 0x3F));
+ } else if (wc >= 0x80) {
+ outbuf[p++] = (char)(0xC0 + ((wc >> 6) & 0x1F));
+ outbuf[p++] = (char)(0x80 + (wc & 0x3F));
+ } else {
+ outbuf[p++] = (char)(wc & 0x7F);
+ }
+ }
+ if (items_read) {
+ *items_read = i;
+ }
+ if (items_written) {
+ *items_written = p;
+ }
+ outbuf[p] = 0;
+
+ return outbuf;
+}
+#endif
+
+const char *config_get_config_dir()
+{
+ char *base_config_dir = NULL;
+
+ if (__config_dir)
+ return __config_dir;
+
+#ifdef WIN32
+ wchar_t path[MAX_PATH+1];
+ HRESULT hr;
+ LPITEMIDLIST pidl = NULL;
+ BOOL b = FALSE;
+
+ hr = SHGetSpecialFolderLocation (NULL, CSIDL_COMMON_APPDATA, &pidl);
+ if (hr == S_OK) {
+ b = SHGetPathFromIDListW (pidl, path);
+ if (b) {
+ base_config_dir = config_utf16_to_utf8 (path, wcslen(path), NULL, NULL);
+ CoTaskMemFree (pidl);
+ }
+ }
+#else
+#ifdef __APPLE__
+ base_config_dir = strdup("/var/db");
+#else
+ base_config_dir = strdup("/var/lib");
+#endif
+#endif
+ __config_dir = string_concat(base_config_dir, DIR_SEP_S, CONFIG_DIR, NULL);
+
+ if (__config_dir) {
+ int i = strlen(__config_dir)-1;
+ while ((i > 0) && (__config_dir[i] == DIR_SEP)) {
+ __config_dir[i--] = '\0';
+ }
+ }
+
+ free(base_config_dir);
+
+ usbmuxd_log(LL_DEBUG, "Initialized config_dir to %s", __config_dir);
+
+ return __config_dir;
+}
+
+static int __mkdir(const char *dir, int mode)
+{
+#ifdef WIN32
+ return mkdir(dir);
+#else
+ return mkdir(dir, mode);
+#endif
+}
+
+static int mkdir_with_parents(const char *dir, int mode)
+{
+ if (!dir) return -1;
+ if (__mkdir(dir, mode) == 0) {
+ return 0;
+ } else {
+ if (errno == EEXIST) return 0;
+ }
+ int res;
+ char *parent = strdup(dir);
+ char* parentdir = dirname(parent);
+ if (parentdir) {
+ res = mkdir_with_parents(parentdir, mode);
+ } else {
+ res = -1;
+ }
+ free(parent);
+ return res;
+}
+
+/**
+ * Creates a freedesktop compatible configuration directory.
+ */
+static void config_create_config_dir(void)
+{
+ const char *config_path = config_get_config_dir();
+ struct stat st;
+ if (stat(config_path, &st) != 0) {
+ mkdir_with_parents(config_path, 0755);
+ }
+}
+
+static int get_rand(int min, int max)
+{
+ int retval = (rand() % (max - min)) + min;
+ return retval;
+}
+
+static char *config_generate_uuid(int idx)
+{
+ char *uuid = (char *) malloc(sizeof(char) * 37);
+ const char *chars = "ABCDEF0123456789";
+ srand(time(NULL) - idx);
+ int i = 0;
+
+ for (i = 0; i < 36; i++) {
+ if (i == 8 || i == 13 || i == 18 || i == 23) {
+ uuid[i] = '-';
+ continue;
+ } else {
+ uuid[i] = chars[get_rand(0, 16)];
+ }
+ }
+ /* make it a real string */
+ uuid[36] = '\0';
+ return uuid;
+}
+
+/**
+ * Generates a valid BUID for this system (which is actually a UUID).
+ *
+ * @return A null terminated string containing a valid BUID.
+ */
+static char *config_generate_system_buid()
+{
+ return config_generate_uuid(1);
+}
+
+static int internal_set_value(const char *config_file, const char *key, plist_t value)
+{
+ if (!config_file)
+ return 0;
+
+ /* read file into plist */
+ plist_t config = NULL;
+
+ plist_read_from_file(config_file, &config, NULL);
+ if (!config) {
+ config = plist_new_dict();
+ plist_dict_set_item(config, key, value);
+ } else {
+ plist_t n = plist_dict_get_item(config, key);
+ if (n) {
+ plist_dict_remove_item(config, key);
+ }
+ plist_dict_set_item(config, key, value);
+ remove(config_file);
+ }
+
+ /* store in config file */
+ char *value_string = NULL;
+ if (plist_get_node_type(value) == PLIST_STRING) {
+ plist_get_string_val(value, &value_string);
+ usbmuxd_log(LL_DEBUG, "Setting key %s to %s in config file %s", key, value_string, config_file);
+ if (value_string)
+ free(value_string);
+ } else {
+ usbmuxd_log(LL_DEBUG, "Setting key %s in config file %s", key, config_file);
+ }
+
+ int res = (plist_write_to_file(config, config_file, PLIST_FORMAT_XML, 0) == PLIST_ERR_SUCCESS);
+
+ plist_free(config);
+
+ return res;
+}
+
+static int config_set_value(const char *key, plist_t value)
+{
+ const char *config_path = NULL;
+ char *config_file = NULL;
+
+ /* Make sure config directory exists */
+ config_create_config_dir();
+
+ config_path = config_get_config_dir();
+ config_file = string_concat(config_path, DIR_SEP_S, CONFIG_FILE, NULL);
+
+ int result = internal_set_value(config_file, key, value);
+ if (!result) {
+ usbmuxd_log(LL_ERROR, "ERROR: Failed to write to '%s'", config_file);
+ }
+
+ free(config_file);
+
+ return result;
+}
+
+static int internal_get_value(const char* config_file, const char *key, plist_t *value)
+{
+ *value = NULL;
+
+ /* now parse file to get the SystemBUID */
+ plist_t config = NULL;
+ if (plist_read_from_file(config_file, &config, NULL) == PLIST_ERR_SUCCESS) {
+ usbmuxd_log(LL_DEBUG, "Reading key %s from config file %s", key, config_file);
+ plist_t n = plist_dict_get_item(config, key);
+ if (n) {
+ *value = plist_copy(n);
+ n = NULL;
+ }
+ }
+ plist_free(config);
+
+ return 1;
+}
+
+static int config_get_value(const char *key, plist_t *value)
+{
+ const char *config_path = NULL;
+ char *config_file = NULL;
+
+ config_path = config_get_config_dir();
+ config_file = string_concat(config_path, DIR_SEP_S, CONFIG_FILE, NULL);
+
+ int result = internal_get_value(config_file, key, value);
+
+ free(config_file);
+
+ return result;
+}
+
+/**
+ * Store SystemBUID in config file.
+ *
+ * @param system_buid A null terminated string containing a valid SystemBUID.
+ */
+static int config_set_system_buid(const char *system_buid)
+{
+ return config_set_value(CONFIG_SYSTEM_BUID_KEY, plist_new_string(system_buid));
+}
+
+/**
+ * Determines whether a pairing record is present for the given device.
+ *
+ * @param udid The device UDID as given by the device.
+ *
+ * @return 1 if there's a pairing record for the given udid or 0 otherwise.
+ */
+int config_has_device_record(const char *udid)
+{
+ int res = 0;
+ if (!udid) return 0;
+
+ /* ensure config directory exists */
+ config_create_config_dir();
+
+ /* build file path */
+ const char *config_path = config_get_config_dir();
+ char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL);
+
+ struct stat st;
+
+ if ((stat(device_record_file, &st) == 0) && S_ISREG(st.st_mode))
+ res = 1;
+
+ free(device_record_file);
+
+ return res;
+}
+
+/**
+ * Reads the BUID from a previously generated configuration file.
+ *
+ * @param system_buid pointer to a variable that will be set to point to a
+ * newly allocated string containing the BUID.
+ *
+ * @note It is the responsibility of the calling function to free the returned system_buid
+ */
+void config_get_system_buid(char **system_buid)
+{
+ plist_t value = NULL;
+
+ config_get_value(CONFIG_SYSTEM_BUID_KEY, &value);
+
+ if (value && (plist_get_node_type(value) == PLIST_STRING)) {
+ plist_get_string_val(value, system_buid);
+ usbmuxd_log(LL_DEBUG, "Got %s %s", CONFIG_SYSTEM_BUID_KEY, *system_buid);
+ }
+
+ if (value)
+ plist_free(value);
+
+ if (!*system_buid) {
+ /* no config, generate system_buid */
+ usbmuxd_log(LL_DEBUG, "No previous %s found", CONFIG_SYSTEM_BUID_KEY);
+ *system_buid = config_generate_system_buid();
+ if (!config_set_system_buid(*system_buid)) {
+ usbmuxd_log(LL_WARNING, "WARNING: Failed to store SystemBUID, this might be a problem");
+ }
+ }
+
+ usbmuxd_log(LL_DEBUG, "Using %s as %s", *system_buid, CONFIG_SYSTEM_BUID_KEY);
+}
+
+/**
+ * Store a pairing record for the given device identifier.
+ *
+ * @param udid device identifier
+ * @param record_data buffer containing a pairing record
+ * @param record_size size of buffer passed in record_data
+ *
+ * @return 0 on success or a negative errno otherwise.
+ */
+int config_set_device_record(const char *udid, char* record_data, uint64_t record_size)
+{
+ int res = 0;
+
+ if (!udid || !record_data || record_size < 8)
+ return -EINVAL;
+
+ plist_t plist = NULL;
+ if (memcmp(record_data, "bplist00", 8) == 0) {
+ plist_from_bin(record_data, record_size, &plist);
+ } else {
+ plist_from_xml(record_data, record_size, &plist);
+ }
+
+ if (!plist || plist_get_node_type(plist) != PLIST_DICT) {
+ if (plist)
+ plist_free(plist);
+ return -EINVAL;
+ }
+
+ /* ensure config directory exists */
+ config_create_config_dir();
+
+ /* build file path */
+ const char *config_path = config_get_config_dir();
+ char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL);
+
+ remove(device_record_file);
+
+ /* store file */
+ if (!plist_write_to_file(plist, device_record_file, PLIST_FORMAT_XML, 0)) {
+ usbmuxd_log(LL_DEBUG, "Could not open '%s' for writing: %s", device_record_file, strerror(errno));
+ res = -ENOENT;
+ }
+ free(device_record_file);
+ if (plist)
+ plist_free(plist);
+
+ return res;
+}
+
+/**
+ * Retrieve a pairing record for the given device identifier
+ *
+ * @param udid device identifier
+ * @param record_data pointer to a variable that will be set to point to a
+ * newly allocated buffer holding the pairing record
+ * @param record_size pointer to a variable that will be set to the size
+ * of the buffer given in record_data.
+ *
+ * @return 0 on success or a negative errno otherwise.
+ */
+int config_get_device_record(const char *udid, char **record_data, uint64_t *record_size)
+{
+ int res = 0;
+
+ /* ensure config directory exists */
+ config_create_config_dir();
+
+ /* build file path */
+ const char *config_path = config_get_config_dir();
+ char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL);
+
+ /* read file */
+ buffer_read_from_filename(device_record_file, record_data, record_size);
+ if (!*record_data) {
+ usbmuxd_log(LL_ERROR, "ERROR: Failed to read '%s': %s", device_record_file, strerror(errno));
+ res = -ENOENT;
+ }
+ free(device_record_file);
+
+ return res;
+}
+
+/**
+ * Remove the pairing record stored for a device from this host.
+ *
+ * @param udid The udid of the device
+ *
+ * @return 0 on success or a negative errno otherwise.
+ */
+int config_remove_device_record(const char *udid)
+{
+ int res = 0;
+
+ /* build file path */
+ const char *config_path = config_get_config_dir();
+ char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL);
+
+ /* remove file */
+ if (remove(device_record_file) != 0) {
+ res = -errno;
+ usbmuxd_log(LL_DEBUG, "Could not remove %s: %s", device_record_file, strerror(errno));
+ }
+
+ free(device_record_file);
+
+ return res;
+}
+
+static int config_device_record_get_value(const char *udid, const char *key, plist_t *value)
+{
+ const char *config_path = NULL;
+ char *config_file = NULL;
+
+ config_path = config_get_config_dir();
+ config_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL);
+
+ int result = internal_get_value(config_file, key, value);
+
+ free(config_file);
+
+ return result;
+}
+
+void config_device_record_get_host_id(const char *udid, char **host_id)
+{
+ plist_t value = NULL;
+
+ config_device_record_get_value(udid, CONFIG_HOST_ID_KEY, &value);
+
+ if (value && (plist_get_node_type(value) == PLIST_STRING)) {
+ plist_get_string_val(value, host_id);
+ }
+
+ if (value)
+ plist_free(value);
+
+ if (!*host_id) {
+ usbmuxd_log(LL_ERROR, "ERROR: Could not get HostID from pairing record for udid %s", udid);
+ }
+}
diff --git a/src/conf.h b/src/conf.h
new file mode 100644
index 0000000..bbfa965
--- /dev/null
+++ b/src/conf.h
@@ -0,0 +1,40 @@
+/*
+ * conf.h
+ *
+ * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#ifndef CONF_H
+#define CONF_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <plist/plist.h>
+
+const char *config_get_config_dir();
+
+void config_get_system_buid(char **system_buid);
+
+int config_has_device_record(const char *udid);
+int config_get_device_record(const char *udid, char **record_data, uint64_t *record_size);
+int config_set_device_record(const char *udid, char* record_data, uint64_t record_size);
+int config_remove_device_record(const char *udid);
+
+void config_device_record_get_host_id(const char *udid, char **host_id);
+
+#endif
diff --git a/daemon/device.c b/src/device.c
index 0a143b2..ce73718 100644
--- a/daemon/device.c
+++ b/src/device.c
@@ -1,23 +1,24 @@
/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
-
+ * device.c
+ *
+ * Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
+ * Copyright (C) 2014 Mikkel Kamstrup Erlandsen <mikkel.kamstrup@xamarin.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#ifdef HAVE_CONFIG_H
@@ -31,8 +32,14 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
+#include <unistd.h>
+
+#include <libimobiledevice-glue/collection.h>
+#include <libimobiledevice-glue/thread.h>
+
#include "device.h"
#include "client.h"
+#include "preflight.h"
#include "usb.h"
#include "log.h"
@@ -47,6 +54,8 @@ int next_device_id;
enum mux_protocol {
MUX_PROTO_VERSION = 0,
+ MUX_PROTO_CONTROL = 1,
+ MUX_PROTO_SETUP = 2,
MUX_PROTO_TCP = IPPROTO_TCP,
};
@@ -68,6 +77,9 @@ struct mux_header
{
uint32_t protocol;
uint32_t length;
+ uint32_t magic;
+ uint16_t tx_seq;
+ uint16_t rx_seq;
};
struct version_header
@@ -106,25 +118,58 @@ struct mux_device
struct usb_device *usbdev;
int id;
enum mux_dev_state state;
+ int visible;
struct collection connections;
uint16_t next_sport;
unsigned char *pktbuf;
uint32_t pktlen;
+ void *preflight_cb_data;
+ int version;
+ uint16_t rx_seq;
+ uint16_t tx_seq;
};
static struct collection device_list;
+mutex_t device_list_mutex;
-uint64_t mstime64(void)
+static struct mux_device* get_mux_device_for_id(int device_id)
{
- struct timeval tv;
- gettimeofday(&tv, NULL);
- return tv.tv_sec * 1000 + tv.tv_usec / 1000;
+ struct mux_device *dev = NULL;
+ mutex_lock(&device_list_mutex);
+ FOREACH(struct mux_device *cdev, &device_list) {
+ if(cdev->id == device_id) {
+ dev = cdev;
+ break;
+ }
+ } ENDFOREACH
+ mutex_unlock(&device_list_mutex);
+
+ return dev;
+}
+
+static struct mux_connection* get_mux_connection(int device_id, struct mux_client *client)
+{
+ struct mux_connection *conn = NULL;
+ FOREACH(struct mux_device *dev, &device_list) {
+ if(dev->id == device_id) {
+ FOREACH(struct mux_connection *lconn, &dev->connections) {
+ if(lconn->client == client) {
+ conn = lconn;
+ break;
+ }
+ } ENDFOREACH
+ break;
+ }
+ } ENDFOREACH
+
+ return conn;
}
static int get_next_device_id(void)
{
while(1) {
int ok = 1;
+ mutex_lock(&device_list_mutex);
FOREACH(struct mux_device *dev, &device_list) {
if(dev->id == next_device_id) {
next_device_id++;
@@ -132,6 +177,7 @@ static int get_next_device_id(void)
break;
}
} ENDFOREACH
+ mutex_unlock(&device_list_mutex);
if(ok)
return next_device_id++;
}
@@ -147,6 +193,9 @@ static int send_packet(struct mux_device *dev, enum mux_protocol proto, void *he
case MUX_PROTO_VERSION:
hdrlen = sizeof(struct version_header);
break;
+ case MUX_PROTO_SETUP:
+ hdrlen = 0;
+ break;
case MUX_PROTO_TCP:
hdrlen = sizeof(struct tcphdr);
break;
@@ -156,7 +205,9 @@ static int send_packet(struct mux_device *dev, enum mux_protocol proto, void *he
}
usbmuxd_log(LL_SPEW, "send_packet(%d, 0x%x, %p, %p, %d)", dev->id, proto, header, data, length);
- int total = sizeof(struct mux_header) + hdrlen + length;
+ int mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header));
+
+ int total = mux_header_size + hdrlen + length;
if(total > USB_MTU) {
usbmuxd_log(LL_ERROR, "Tried to send packet larger than USB MTU (hdr %d data %d total %d) to device %d", hdrlen, length, total, dev->id);
@@ -167,9 +218,19 @@ static int send_packet(struct mux_device *dev, enum mux_protocol proto, void *he
struct mux_header *mhdr = (struct mux_header *)buffer;
mhdr->protocol = htonl(proto);
mhdr->length = htonl(total);
- memcpy(buffer + sizeof(struct mux_header), header, hdrlen);
+ if (dev->version >= 2) {
+ mhdr->magic = htonl(0xfeedface);
+ if (proto == MUX_PROTO_SETUP) {
+ dev->tx_seq = 0;
+ dev->rx_seq = 0xFFFF;
+ }
+ mhdr->tx_seq = htons(dev->tx_seq);
+ mhdr->rx_seq = htons(dev->rx_seq);
+ dev->tx_seq++;
+ }
+ memcpy(buffer + mux_header_size, header, hdrlen);
if(data && length)
- memcpy(buffer + sizeof(struct mux_header) + hdrlen, data, length);
+ memcpy(buffer + mux_header_size + hdrlen, data, length);
if((res = usb_send(dev->usbdev, buffer, total)) < 0) {
usbmuxd_log(LL_ERROR, "usb_send failed while sending packet (len %d) to device %d: %d", total, dev->id, res);
@@ -241,6 +302,7 @@ static int send_tcp(struct mux_connection *conn, uint8_t flags, const unsigned c
static void connection_teardown(struct mux_connection *conn)
{
int res;
+ int size;
if(conn->state == CONN_DEAD)
return;
usbmuxd_log(LL_DEBUG, "connection_teardown dev %d sport %d dport %d", conn->dev->id, conn->sport, conn->dport);
@@ -254,26 +316,45 @@ static void connection_teardown(struct mux_connection *conn)
client_notify_connect(conn->client, RESULT_CONNREFUSED);
} else {
conn->state = CONN_DEAD;
+ if((conn->events & POLLOUT) && conn->ib_size > 0){
+ usbmuxd_log(LL_DEBUG, "%s: flushing buffer to client (%u bytes)", __func__, conn->ib_size);
+ uint64_t tm_last = mstime64();
+ while(1){
+ size = client_write(conn->client, conn->ib_buf, conn->ib_size);
+ if(size < 0) {
+ usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after error.", __func__);
+ break;
+ } else if (size == 0) {
+ uint64_t tm_now = mstime64();
+ if (tm_now - tm_last > 1000) {
+ usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after unsuccessfully attempting for %dms.", __func__, (int)(tm_now - tm_last));
+ break;
+ }
+ usleep(10000);
+ continue;
+ }
+ if(size == (int)conn->ib_size) {
+ conn->ib_size = 0;
+ break;
+ } else {
+ conn->ib_size -= size;
+ memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size);
+ }
+ tm_last = mstime64();
+ }
+ }
client_close(conn->client);
}
}
- if(conn->ib_buf)
- free(conn->ib_buf);
- if(conn->ob_buf)
- free(conn->ob_buf);
+ free(conn->ib_buf);
+ free(conn->ob_buf);
collection_remove(&conn->dev->connections, conn);
free(conn);
}
int device_start_connect(int device_id, uint16_t dport, struct mux_client *client)
{
- struct mux_device *dev = NULL;
- FOREACH(struct mux_device *cdev, &device_list) {
- if(cdev->id == device_id) {
- dev = cdev;
- break;
- }
- } ENDFOREACH
+ struct mux_device *dev = get_mux_device_for_id(device_id);
if(!dev) {
usbmuxd_log(LL_WARNING, "Attempted to connect to nonexistent device %d", device_id);
return -RESULT_BADDEV;
@@ -313,6 +394,8 @@ int device_start_connect(int device_id, uint16_t dport, struct mux_client *clien
res = send_tcp(conn, TH_SYN, NULL, 0);
if(res < 0) {
usbmuxd_log(LL_ERROR, "Error sending TCP SYN to device %d (%d->%d)", dev->id, sport, dport);
+ free(conn->ib_buf);
+ free(conn->ob_buf);
free(conn);
return -RESULT_CONNREFUSED; //bleh
}
@@ -320,6 +403,13 @@ int device_start_connect(int device_id, uint16_t dport, struct mux_client *clien
return 0;
}
+/**
+ * Examine the state of a connection's buffers and
+ * update all connection flags and masks accordingly.
+ * Does not do I/O.
+ *
+ * @param conn The connection to update.
+ */
static void update_connection(struct mux_connection *conn)
{
uint32_t sent = conn->tx_seq - conn->rx_ack;
@@ -353,21 +443,33 @@ static void update_connection(struct mux_connection *conn)
client_set_events(conn->client, conn->events);
}
-void device_client_process(int device_id, struct mux_client *client, short events)
+static int send_tcp_ack(struct mux_connection *conn)
{
- struct mux_connection *conn = NULL;
- FOREACH(struct mux_device *dev, &device_list) {
- if(dev->id == device_id) {
- FOREACH(struct mux_connection *lconn, &dev->connections) {
- if(lconn->client == client) {
- conn = lconn;
- break;
- }
- } ENDFOREACH
- break;
- }
- } ENDFOREACH
+ if(send_tcp(conn, TH_ACK, NULL, 0) < 0) {
+ usbmuxd_log(LL_ERROR, "Error sending TCP ACK (%d->%d)", conn->sport, conn->dport);
+ connection_teardown(conn);
+ return -1;
+ }
+
+ update_connection(conn);
+ return 0;
+}
+
+/**
+ * Flush input and output buffers for a client connection.
+ *
+ * @param device_id Numeric id for the device.
+ * @param client The client to flush buffers for.
+ * @param events event mask for the client. POLLOUT means that
+ * the client is ready to receive data, POLLIN that it has
+ * data to be read (and send along to the device).
+ */
+void device_client_process(int device_id, struct mux_client *client, short events)
+{
+ mutex_lock(&device_list_mutex);
+ struct mux_connection *conn = get_mux_connection(device_id, client);
+ mutex_unlock(&device_list_mutex);
if(!conn) {
usbmuxd_log(LL_WARNING, "Could not find connection for device %d client %p", device_id, client);
return;
@@ -376,7 +478,9 @@ void device_client_process(int device_id, struct mux_client *client, short event
int res;
int size;
- if(events & POLLOUT) {
+ if((events & POLLOUT) && conn->ib_size > 0) {
+ // Client is ready to receive data, send what we have
+ // in the client's connection buffer (if there is any)
size = client_write(conn->client, conn->ib_buf, conn->ib_size);
if(size <= 0) {
usbmuxd_log(LL_DEBUG, "error writing to client (%d)", size);
@@ -384,17 +488,22 @@ void device_client_process(int device_id, struct mux_client *client, short event
return;
}
conn->tx_ack += size;
- if(size == conn->ib_size) {
+ if(size == (int)conn->ib_size) {
conn->ib_size = 0;
} else {
conn->ib_size -= size;
memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size);
}
}
- if(events & POLLIN) {
+ if((events & POLLIN) && conn->sendable > 0) {
+ // There is inbound trafic on the client socket,
+ // convert it to tcp and send to the device
+ // (if the device's input buffer is not full)
size = client_read(conn->client, conn->ob_buf, conn->sendable);
if(size <= 0) {
- usbmuxd_log(LL_DEBUG, "error reading from client (%d)", size);
+ if (size < 0) {
+ usbmuxd_log(LL_DEBUG, "error reading from client (%d)", size);
+ }
connection_teardown(conn);
return;
}
@@ -409,6 +518,23 @@ void device_client_process(int device_id, struct mux_client *client, short event
update_connection(conn);
}
+/**
+ * Copy a payload to a connection's in-buffer and
+ * set the POLLOUT event mask on the connection so
+ * the next main_loop iteration will dispatch the
+ * buffer if the connection socket is writable.
+ *
+ * Connection buffers are flushed in the
+ * device_client_process() function.
+ *
+ * @param conn The connection to add incoming data to.
+ * @param payload Payload to prepare for writing.
+ * The payload will be copied immediately so you are
+ * free to alter or free the payload buffer when this
+ * function returns.
+ * @param payload_length number of bytes to copy from from
+ * the payload.
+ */
static void connection_device_input(struct mux_connection *conn, unsigned char *payload, uint32_t payload_length)
{
if((conn->ib_size + payload_length) > conn->ib_capacity) {
@@ -424,19 +550,13 @@ static void connection_device_input(struct mux_connection *conn, unsigned char *
void device_abort_connect(int device_id, struct mux_client *client)
{
- FOREACH(struct mux_device *dev, &device_list) {
- if(dev->id == device_id) {
- FOREACH(struct mux_connection *conn, &dev->connections) {
- if(conn->client == client) {
- connection_teardown(conn);
- return;
- }
- } ENDFOREACH
- usbmuxd_log(LL_WARNING, "Attempted to abort for nonexistent connection for device %d", device_id);
- return;
- }
- } ENDFOREACH
- usbmuxd_log(LL_WARNING, "Attempted to abort connection for nonexistent device %d", device_id);
+ struct mux_connection *conn = get_mux_connection(device_id, client);
+ if (conn) {
+ conn->client = NULL;
+ connection_teardown(conn);
+ } else {
+ usbmuxd_log(LL_WARNING, "Attempted to abort for nonexistent connection for device %d", device_id);
+ }
}
static void device_version_input(struct mux_device *dev, struct version_header *vh)
@@ -447,13 +567,21 @@ static void device_version_input(struct mux_device *dev, struct version_header *
}
vh->major = ntohl(vh->major);
vh->minor = ntohl(vh->minor);
- if(vh->major != 1 || vh->minor != 0) {
- usbmuxd_log(LL_ERROR, "Device %d has unknown version %d.%d\n", dev->id, vh->major, vh->minor);
+ if(vh->major != 2 && vh->major != 1) {
+ usbmuxd_log(LL_ERROR, "Device %d has unknown version %d.%d", dev->id, vh->major, vh->minor);
+ mutex_lock(&device_list_mutex);
collection_remove(&device_list, dev);
+ mutex_unlock(&device_list_mutex);
free(dev);
return;
}
- usbmuxd_log(LL_NOTICE, "Connected to v%d.%d device %d on location 0x%x with serial number %s", vh->major, vh->minor, dev->id, usb_get_location(dev->usbdev), usb_get_serial(dev->usbdev));
+ dev->version = vh->major;
+
+ if (dev->version >= 2) {
+ send_packet(dev, MUX_PROTO_SETUP, NULL, "\x07", 1);
+ }
+
+ usbmuxd_log(LL_NOTICE, "Connected to v%d.%d device %d on location 0x%x with serial number %s", dev->version, vh->minor, dev->id, usb_get_location(dev->usbdev), usb_get_serial(dev->usbdev));
dev->state = MUXDEV_ACTIVE;
collection_init(&dev->connections);
struct device_info info;
@@ -461,9 +589,52 @@ static void device_version_input(struct mux_device *dev, struct version_header *
info.location = usb_get_location(dev->usbdev);
info.serial = usb_get_serial(dev->usbdev);
info.pid = usb_get_pid(dev->usbdev);
- client_device_add(&info);
+ info.speed = usb_get_speed(dev->usbdev);
+ preflight_worker_device_add(&info);
}
+static void device_control_input(struct mux_device *dev, unsigned char *payload, uint32_t payload_length)
+{
+ if (payload_length > 0) {
+ switch (payload[0]) {
+ case 3:
+ if (payload_length > 1) {
+ usbmuxd_log(LL_ERROR, "Device %d: ERROR: %.*s", dev->id, payload_length-1, payload+1);
+ } else {
+ usbmuxd_log(LL_ERROR, "%s: Device %d: Got device error payload with empty message", __func__, dev->id);
+ }
+ break;
+ case 5:
+ if (payload_length > 1) {
+ usbmuxd_log(LL_WARNING, "Device %d: WARNING: %.*s", dev->id, payload_length-1, payload+1);
+ } else {
+ usbmuxd_log(LL_WARNING, "%s: Device %d: Got payload type %d with empty message", __func__, dev->id, payload[0]);
+ }
+ break;
+ case 7:
+ if (payload_length > 1) {
+ usbmuxd_log(LL_INFO, "Device %d: %.*s", dev->id, payload_length-1, payload+1);
+ } else {
+ usbmuxd_log(LL_WARNING, "%s: Device %d: Got payload type %d with empty message", __func__, dev->id, payload[0]);
+ }
+ break;
+ default:
+ usbmuxd_log(LL_WARNING, "%s: Device %d: Got unhandled payload type %d: %.*s", __func__, dev->id, payload[0], payload_length-1, payload+1);
+ break;
+ }
+ } else {
+ usbmuxd_log(LL_WARNING, "%s: Got a type 1 packet without payload for device %d", __func__, dev->id);
+ }
+}
+
+/**
+ * Handle an incoming TCP packet from the device.
+ *
+ * @param dev The device handle TCP input on.
+ * @param th Pointer to the TCP header struct.
+ * @param payload Payload data.
+ * @param payload_length Number of bytes in payload.
+ */
static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned char *payload, uint32_t payload_length)
{
uint16_t sport = ntohs(th->th_dport);
@@ -474,10 +645,11 @@ static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned
dev->id, dport, sport, ntohl(th->th_seq), ntohl(th->th_ack), th->th_flags, ntohs(th->th_win) << 8, ntohs(th->th_win), payload_length);
if(dev->state != MUXDEV_ACTIVE) {
- usbmuxd_log(LL_ERROR, "Received TCP packet from device %d but the device isn't active yet, discarding\n", dev->id);
+ usbmuxd_log(LL_ERROR, "Received TCP packet from device %d but the device isn't active yet, discarding", dev->id);
return;
}
+ // Find the connection on this device that has the right sport and dport
FOREACH(struct mux_connection *lconn, &dev->connections) {
if(lconn->sport == sport && lconn->dport == dport) {
conn = lconn;
@@ -486,10 +658,10 @@ static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned
} ENDFOREACH
if(!conn) {
- usbmuxd_log(LL_INFO, "No connection for device %d incoming packet %d->%d", dev->id, dport, sport);
if(!(th->th_flags & TH_RST)) {
+ usbmuxd_log(LL_INFO, "No connection for device %d incoming packet %d->%d", dev->id, dport, sport);
if(send_anon_rst(dev, sport, dport, ntohl(th->th_seq)) < 0)
- usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", conn->dev->id, sport, dport);
+ usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", dev->id, sport, dport);
}
return;
}
@@ -524,6 +696,7 @@ static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned
return;
}
conn->state = CONN_CONNECTED;
+ usbmuxd_log(LL_INFO, "Client connected to device %d (%d->%d)", dev->id, sport, dport);
if(client_notify_connect(conn->client, RESULT_OK) < 0) {
conn->client = NULL;
connection_teardown(conn);
@@ -538,19 +711,32 @@ static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned
connection_teardown(conn);
} else {
connection_device_input(conn, payload, payload_length);
+
+ // Device likes it best when we are prompty ACKing data
+ send_tcp_ack(conn);
}
}
}
+/**
+ * Take input data from the device that has been read into a buffer
+ * and dispatch it to the right protocol backend (eg. TCP).
+ *
+ * @param usbdev
+ * @param buffer
+ * @param length
+ */
void device_data_input(struct usb_device *usbdev, unsigned char *buffer, uint32_t length)
{
struct mux_device *dev = NULL;
+ mutex_lock(&device_list_mutex);
FOREACH(struct mux_device *tdev, &device_list) {
if(tdev->usbdev == usbdev) {
dev = tdev;
break;
}
} ENDFOREACH
+ mutex_unlock(&device_list_mutex);
if(!dev) {
usbmuxd_log(LL_WARNING, "Cannot find device entry for RX input from USB device %p on location 0x%x", usbdev, usb_get_location(usbdev));
return;
@@ -576,7 +762,7 @@ void device_data_input(struct usb_device *usbdev, unsigned char *buffer, uint32_
}
memcpy(dev->pktbuf + dev->pktlen, buffer, length);
struct mux_header *mhdr = (struct mux_header *)dev->pktbuf;
- if((length < USB_MRU) || (ntohl(mhdr->length) == length)) {
+ if((length < USB_MRU) || (ntohl(mhdr->length) == (length + dev->pktlen))) {
buffer = dev->pktbuf;
length += dev->pktlen;
dev->pktlen = 0;
@@ -597,7 +783,7 @@ void device_data_input(struct usb_device *usbdev, unsigned char *buffer, uint32_
}
struct mux_header *mhdr = (struct mux_header *)buffer;
-
+ int mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header));
if(ntohl(mhdr->length) != length) {
usbmuxd_log(LL_ERROR, "Incoming packet size mismatch (dev %d, expected %d, got %d)", dev->id, ntohl(mhdr->length), length);
return;
@@ -607,23 +793,32 @@ void device_data_input(struct usb_device *usbdev, unsigned char *buffer, uint32_
unsigned char *payload;
uint32_t payload_length;
+ if (dev->version >= 2) {
+ dev->rx_seq = ntohs(mhdr->rx_seq);
+ }
+
switch(ntohl(mhdr->protocol)) {
case MUX_PROTO_VERSION:
- if(length < (sizeof(struct mux_header) + sizeof(struct version_header))) {
+ if(length < (mux_header_size + sizeof(struct version_header))) {
usbmuxd_log(LL_ERROR, "Incoming version packet is too small (%d)", length);
return;
}
- device_version_input(dev, (struct version_header *)(mhdr+1));
+ device_version_input(dev, (struct version_header *)((char*)mhdr+mux_header_size));
+ break;
+ case MUX_PROTO_CONTROL:
+ payload = (unsigned char *)(mhdr+1);
+ payload_length = length - mux_header_size;
+ device_control_input(dev, payload, payload_length);
break;
case MUX_PROTO_TCP:
- if(length < (sizeof(struct mux_header) + sizeof(struct tcphdr))) {
+ if(length < (mux_header_size + sizeof(struct tcphdr))) {
usbmuxd_log(LL_ERROR, "Incoming TCP packet is too small (%d)", length);
return;
}
- th = (struct tcphdr *)(mhdr+1);
+ th = (struct tcphdr *)((char*)mhdr+mux_header_size);
payload = (unsigned char *)(th+1);
- payload_length = length - sizeof(struct tcphdr) - sizeof(struct mux_header);
- device_tcp_input(dev, (struct tcphdr *)(mhdr+1), payload, payload_length);
+ payload_length = length - sizeof(struct tcphdr) - mux_header_size;
+ device_tcp_input(dev, th, payload, payload_length);
break;
default:
usbmuxd_log(LL_ERROR, "Incoming packet for device %d has unknown protocol 0x%x)", dev->id, ntohl(mhdr->protocol));
@@ -642,24 +837,31 @@ int device_add(struct usb_device *usbdev)
dev->id = id;
dev->usbdev = usbdev;
dev->state = MUXDEV_INIT;
+ dev->visible = 0;
dev->next_sport = 1;
dev->pktbuf = malloc(DEV_MRU);
dev->pktlen = 0;
+ dev->preflight_cb_data = NULL;
+ dev->version = 0;
struct version_header vh;
- vh.major = htonl(1);
+ vh.major = htonl(2);
vh.minor = htonl(0);
vh.padding = 0;
if((res = send_packet(dev, MUX_PROTO_VERSION, &vh, NULL, 0)) < 0) {
usbmuxd_log(LL_ERROR, "Error sending version request packet to device %d", id);
+ free(dev->pktbuf);
free(dev);
return res;
}
+ mutex_lock(&device_list_mutex);
collection_add(&device_list, dev);
+ mutex_unlock(&device_list_mutex);
return 0;
}
void device_remove(struct usb_device *usbdev)
{
+ mutex_lock(&device_list_mutex);
FOREACH(struct mux_device *dev, &device_list) {
if(dev->usbdev == usbdev) {
usbmuxd_log(LL_NOTICE, "Removed device %d on location 0x%x", dev->id, usb_get_location(usbdev));
@@ -671,44 +873,94 @@ void device_remove(struct usb_device *usbdev)
client_device_remove(dev->id);
collection_free(&dev->connections);
}
+ if (dev->preflight_cb_data) {
+ preflight_device_remove_cb(dev->preflight_cb_data);
+ }
collection_remove(&device_list, dev);
+ mutex_unlock(&device_list_mutex);
free(dev->pktbuf);
free(dev);
return;
}
} ENDFOREACH
+ mutex_unlock(&device_list_mutex);
+
usbmuxd_log(LL_WARNING, "Cannot find device entry while removing USB device %p on location 0x%x", usbdev, usb_get_location(usbdev));
}
-int device_get_count(void)
+void device_set_visible(int device_id)
{
- int count = 0;
+ mutex_lock(&device_list_mutex);
+ FOREACH(struct mux_device *dev, &device_list) {
+ if(dev->id == device_id) {
+ dev->visible = 1;
+ break;
+ }
+ } ENDFOREACH
+ mutex_unlock(&device_list_mutex);
+}
+
+void device_set_preflight_cb_data(int device_id, void* data)
+{
+ mutex_lock(&device_list_mutex);
FOREACH(struct mux_device *dev, &device_list) {
- if(dev->state == MUXDEV_ACTIVE)
+ if(dev->id == device_id) {
+ dev->preflight_cb_data = data;
+ break;
+ }
+ } ENDFOREACH
+ mutex_unlock(&device_list_mutex);
+}
+
+int device_get_count(int include_hidden)
+{
+ int count = 0;
+ struct collection dev_list = {NULL, 0};
+ mutex_lock(&device_list_mutex);
+ collection_copy(&dev_list, &device_list);
+ mutex_unlock(&device_list_mutex);
+
+ FOREACH(struct mux_device *dev, &dev_list) {
+ if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible))
count++;
} ENDFOREACH
+
+ collection_free(&dev_list);
return count;
}
-int device_get_list(struct device_info *p)
+int device_get_list(int include_hidden, struct device_info **devices)
{
int count = 0;
- FOREACH(struct mux_device *dev, &device_list) {
- if(dev->state == MUXDEV_ACTIVE) {
+ struct collection dev_list = {NULL, 0};
+ mutex_lock(&device_list_mutex);
+ collection_copy(&dev_list, &device_list);
+ mutex_unlock(&device_list_mutex);
+
+ *devices = malloc(sizeof(struct device_info) * dev_list.capacity);
+ struct device_info *p = *devices;
+
+ FOREACH(struct mux_device *dev, &dev_list) {
+ if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible)) {
p->id = dev->id;
p->serial = usb_get_serial(dev->usbdev);
p->location = usb_get_location(dev->usbdev);
p->pid = usb_get_pid(dev->usbdev);
+ p->speed = usb_get_speed(dev->usbdev);
count++;
p++;
}
} ENDFOREACH
+
+ collection_free(&dev_list);
+
return count;
}
int device_get_timeout(void)
{
- uint64_t oldest = (uint64_t)-1;
+ uint64_t oldest = (uint64_t)-1LL;
+ mutex_lock(&device_list_mutex);
FOREACH(struct mux_device *dev, &device_list) {
if(dev->state == MUXDEV_ACTIVE) {
FOREACH(struct mux_connection *conn, &dev->connections) {
@@ -717,8 +969,9 @@ int device_get_timeout(void)
} ENDFOREACH
}
} ENDFOREACH
+ mutex_unlock(&device_list_mutex);
uint64_t ct = mstime64();
- if(oldest == -1)
+ if((int64_t)oldest == -1LL)
return 100000; //meh
if((ct - oldest) > ACK_TIMEOUT)
return 0;
@@ -728,27 +981,27 @@ int device_get_timeout(void)
void device_check_timeouts(void)
{
uint64_t ct = mstime64();
+ mutex_lock(&device_list_mutex);
FOREACH(struct mux_device *dev, &device_list) {
if(dev->state == MUXDEV_ACTIVE) {
FOREACH(struct mux_connection *conn, &dev->connections) {
- if((conn->state == CONN_CONNECTED) &&
- (conn->flags & CONN_ACK_PENDING) &&
+ if((conn->state == CONN_CONNECTED) &&
+ (conn->flags & CONN_ACK_PENDING) &&
(ct - conn->last_ack_time) > ACK_TIMEOUT) {
usbmuxd_log(LL_DEBUG, "Sending ACK due to expired timeout (%" PRIu64 " -> %" PRIu64 ")", conn->last_ack_time, ct);
- if(send_tcp(conn, TH_ACK, NULL, 0) < 0) {
- usbmuxd_log(LL_ERROR, "Error sending TCP ACK to device %d (%d->%d)", dev->id, conn->sport, conn->dport);
- connection_teardown(conn);
- }
+ send_tcp_ack(conn);
}
} ENDFOREACH
}
} ENDFOREACH
+ mutex_unlock(&device_list_mutex);
}
void device_init(void)
{
usbmuxd_log(LL_DEBUG, "device_init");
collection_init(&device_list);
+ mutex_init(&device_list_mutex);
next_device_id = 1;
}
@@ -769,6 +1022,7 @@ void device_kill_connections(void)
void device_shutdown(void)
{
usbmuxd_log(LL_DEBUG, "device_shutdown");
+ mutex_lock(&device_list_mutex);
FOREACH(struct mux_device *dev, &device_list) {
FOREACH(struct mux_connection *conn, &dev->connections) {
connection_teardown(conn);
@@ -777,5 +1031,7 @@ void device_shutdown(void)
collection_remove(&device_list, dev);
free(dev);
} ENDFOREACH
+ mutex_unlock(&device_list_mutex);
+ mutex_destroy(&device_list_mutex);
collection_free(&device_list);
}
diff --git a/src/device.h b/src/device.h
new file mode 100644
index 0000000..85703e4
--- /dev/null
+++ b/src/device.h
@@ -0,0 +1,56 @@
+/*
+ * device.h
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#ifndef DEVICE_H
+#define DEVICE_H
+
+#include "usb.h"
+#include "client.h"
+
+struct device_info {
+ int id;
+ const char *serial;
+ uint32_t location;
+ uint16_t pid;
+ uint64_t speed;
+};
+
+void device_data_input(struct usb_device *dev, unsigned char *buf, uint32_t length);
+
+int device_add(struct usb_device *dev);
+void device_remove(struct usb_device *dev);
+
+int device_start_connect(int device_id, uint16_t port, struct mux_client *client);
+void device_client_process(int device_id, struct mux_client *client, short events);
+void device_abort_connect(int device_id, struct mux_client *client);
+
+void device_set_visible(int device_id);
+void device_set_preflight_cb_data(int device_id, void* data);
+
+int device_get_count(int include_hidden);
+int device_get_list(int include_hidden, struct device_info **devices);
+
+int device_get_timeout(void);
+void device_check_timeouts(void);
+
+void device_init(void);
+void device_kill_connections(void);
+void device_shutdown(void);
+
+#endif
diff --git a/daemon/log.c b/src/log.c
index 1973257..cd7c2d5 100644
--- a/daemon/log.c
+++ b/src/log.c
@@ -1,23 +1,22 @@
/*
- usbmuxd - iPhone/iPod Touch USB multiplex server daemon
-
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 or version 3.
-
-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
-
-*/
+ * log.c
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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>
@@ -32,8 +31,9 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <syslog.h>
#include "log.h"
+#include "utils.h"
-int log_level = LL_WARNING;
+unsigned int log_level = LL_WARNING;
int log_syslog = 0;
@@ -65,20 +65,26 @@ void usbmuxd_log(enum loglevel level, const char *fmt, ...)
{
va_list ap;
char *fs;
- struct timeval ts;
- struct tm *tp;
if(level > log_level)
return;
- gettimeofday(&ts, NULL);
- tp = localtime(&ts.tv_sec);
-
fs = malloc(20 + strlen(fmt));
if(log_syslog) {
sprintf(fs, "[%d] %s\n", level, fmt);
} else {
+ struct timeval ts;
+ struct tm tp_;
+ struct tm *tp;
+
+ gettimeofday(&ts, NULL);
+#ifdef HAVE_LOCALTIME_R
+ tp = localtime_r(&ts.tv_sec, &tp_);
+#else
+ tp = localtime(&ts.tv_sec);
+#endif
+
strftime(fs, 10, "[%H:%M:%S", tp);
sprintf(fs+9, ".%03d][%d] %s\n", (int)(ts.tv_usec / 1000), level, fmt);
}
diff --git a/src/log.h b/src/log.h
new file mode 100644
index 0000000..858e7d0
--- /dev/null
+++ b/src/log.h
@@ -0,0 +1,42 @@
+/*
+ * log.h
+ *
+ * Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#ifndef LOG_H
+#define LOG_H
+
+enum loglevel {
+ LL_FATAL = 0,
+ LL_ERROR,
+ LL_WARNING,
+ LL_NOTICE,
+ LL_INFO,
+ LL_DEBUG,
+ LL_SPEW,
+ LL_FLOOD,
+};
+
+extern unsigned int log_level;
+
+void log_enable_syslog();
+void log_disable_syslog();
+
+void usbmuxd_log(enum loglevel level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));
+
+#endif
diff --git a/src/main.c b/src/main.c
new file mode 100644
index 0000000..8702a4b
--- /dev/null
+++ b/src/main.c
@@ -0,0 +1,920 @@
+/*
+ * main.c
+ *
+ * Copyright (C) 2009-2021 Nikias Bassen <nikias@gmx.li>
+ * Copyright (C) 2013-2014 Martin Szulecki <m.szulecki@libimobiledevice.org>
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#define _DEFAULT_SOURCE
+#define _BSD_SOURCE
+#define _GNU_SOURCE
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <unistd.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <netinet/in.h>
+#include <netdb.h>
+#include <arpa/inet.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/resource.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <pwd.h>
+#include <grp.h>
+
+#include "log.h"
+#include "usb.h"
+#include "device.h"
+#include "client.h"
+#include "conf.h"
+
+static const char *socket_path = "/var/run/usbmuxd";
+#define DEFAULT_LOCKFILE "/var/run/usbmuxd.pid"
+static const char *lockfile = DEFAULT_LOCKFILE;
+
+// Global state used in other files
+int should_exit;
+int should_discover;
+int use_logfile = 0;
+int no_preflight = 0;
+
+// Global state for main.c
+static int verbose = 0;
+static int foreground = 0;
+static int drop_privileges = 0;
+static const char *drop_user = NULL;
+static int opt_disable_hotplug = 0;
+static int opt_enable_exit = 0;
+static int opt_exit = 0;
+static int exit_signal = 0;
+static int daemon_pipe;
+static const char *listen_addr = NULL;
+
+static int report_to_parent = 0;
+
+static int create_socket(void)
+{
+ int listenfd;
+ const char* socket_addr = socket_path;
+ const char* tcp_port;
+ char listen_addr_str[256];
+
+ if (listen_addr) {
+ socket_addr = listen_addr;
+ }
+ tcp_port = strrchr(socket_addr, ':');
+ if (tcp_port) {
+ tcp_port++;
+ size_t nlen = tcp_port - socket_addr;
+ char* hostname = malloc(nlen);
+ struct addrinfo hints;
+ struct addrinfo *result, *rp;
+ int yes = 1;
+ int res;
+
+ strncpy(hostname, socket_addr, nlen-1);
+ hostname[nlen-1] = '\0';
+
+ memset(&hints, '\0', sizeof(struct addrinfo));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
+ hints.ai_protocol = IPPROTO_TCP;
+
+ res = getaddrinfo(hostname, tcp_port, &hints, &result);
+ free(hostname);
+ if (res != 0) {
+ usbmuxd_log(LL_FATAL, "%s: getaddrinfo() failed: %s\n", __func__, gai_strerror(res));
+ return -1;
+ }
+
+ for (rp = result; rp != NULL; rp = rp->ai_next) {
+ listenfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+ if (listenfd == -1) {
+ listenfd = -1;
+ continue;
+ }
+
+ if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
+ usbmuxd_log(LL_ERROR, "%s: setsockopt(): %s", __func__, strerror(errno));
+ close(listenfd);
+ listenfd = -1;
+ continue;
+ }
+
+#ifdef SO_NOSIGPIPE
+ if (setsockopt(listenfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
+ usbmuxd_log(LL_ERROR, "%s: setsockopt(): %s", __func__, strerror(errno));
+ close(listenfd);
+ listenfd = -1;
+ continue;
+ }
+#endif
+
+#if defined(AF_INET6) && defined(IPV6_V6ONLY)
+ if (rp->ai_family == AF_INET6) {
+ if (setsockopt(listenfd, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&yes, sizeof(int)) == -1) {
+ usbmuxd_log(LL_ERROR, "%s: setsockopt() IPV6_V6ONLY: %s", __func__, strerror(errno));
+ }
+ }
+#endif
+
+ if (bind(listenfd, rp->ai_addr, rp->ai_addrlen) < 0) {
+ usbmuxd_log(LL_FATAL, "%s: bind() failed: %s", __func__, strerror(errno));
+ close(listenfd);
+ listenfd = -1;
+ continue;
+ }
+
+ const void *addrdata = NULL;
+ if (rp->ai_family == AF_INET) {
+ addrdata = &((struct sockaddr_in*)rp->ai_addr)->sin_addr;
+ }
+#ifdef AF_INET6
+ else if (rp->ai_family == AF_INET6) {
+ addrdata = &((struct sockaddr_in6*)rp->ai_addr)->sin6_addr;
+ }
+#endif
+ if (addrdata) {
+ char* endp = NULL;
+ uint16_t listen_port = 0;
+ if (rp->ai_family == AF_INET) {
+ listen_port = ntohs(((struct sockaddr_in*)rp->ai_addr)->sin_port);
+ if (inet_ntop(AF_INET, addrdata, listen_addr_str, sizeof(listen_addr_str)-6)) {
+ endp = &listen_addr_str[0] + strlen(listen_addr_str);
+ }
+ }
+#ifdef AF_INET6
+ else if (rp->ai_family == AF_INET6) {
+ listen_port = ntohs(((struct sockaddr_in6*)rp->ai_addr)->sin6_port);
+ listen_addr_str[0] = '[';
+ if (inet_ntop(AF_INET6, addrdata, listen_addr_str+1, sizeof(listen_addr_str)-8)) {
+ endp = &listen_addr_str[0] + strlen(listen_addr_str);
+ }
+ if (endp) {
+ *endp = ']';
+ endp++;
+ }
+ }
+#endif
+ if (endp) {
+ sprintf(endp, ":%u", listen_port);
+ }
+ }
+ break;
+ }
+ freeaddrinfo(result);
+ if (listenfd == -1) {
+ usbmuxd_log(LL_FATAL, "%s: Failed to create listening socket", __func__);
+ return -1;
+ }
+ } else {
+ struct sockaddr_un bind_addr;
+
+ if (strcmp(socket_addr, socket_path) != 0) {
+ struct stat fst;
+ if (stat(socket_addr, &fst) == 0) {
+ if (!S_ISSOCK(fst.st_mode)) {
+ usbmuxd_log(LL_FATAL, "FATAL: File '%s' already exists and is not a socket file. Refusing to continue.", socket_addr);
+ return -1;
+ }
+ }
+ }
+
+ if (unlink(socket_addr) == -1 && errno != ENOENT) {
+ usbmuxd_log(LL_FATAL, "%s: unlink(%s) failed: %s", __func__, socket_addr, strerror(errno));
+ return -1;
+ }
+
+ listenfd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (listenfd == -1) {
+ usbmuxd_log(LL_FATAL, "socket() failed: %s", strerror(errno));
+ return -1;
+ }
+
+ bzero(&bind_addr, sizeof(bind_addr));
+ bind_addr.sun_family = AF_UNIX;
+ strncpy(bind_addr.sun_path, socket_addr, sizeof(bind_addr.sun_path));
+ bind_addr.sun_path[sizeof(bind_addr.sun_path) - 1] = '\0';
+
+ if (bind(listenfd, (struct sockaddr*)&bind_addr, sizeof(bind_addr)) != 0) {
+ usbmuxd_log(LL_FATAL, "bind() failed: %s", strerror(errno));
+ return -1;
+ }
+ chmod(socket_addr, 0666);
+
+ snprintf(listen_addr_str, sizeof(listen_addr_str), "%s", socket_addr);
+ }
+
+ int flags = fcntl(listenfd, F_GETFL, 0);
+ if (flags < 0) {
+ usbmuxd_log(LL_FATAL, "ERROR: Could not get flags for socket");
+ } else {
+ if (fcntl(listenfd, F_SETFL, flags | O_NONBLOCK) < 0) {
+ usbmuxd_log(LL_FATAL, "ERROR: Could not set socket to non-blocking");
+ }
+ }
+
+ // Start listening
+ if (listen(listenfd, 256) != 0) {
+ usbmuxd_log(LL_FATAL, "listen() failed: %s", strerror(errno));
+ return -1;
+ }
+
+ usbmuxd_log(LL_INFO, "Listening on %s", listen_addr_str);
+
+ return listenfd;
+}
+
+static void handle_signal(int sig)
+{
+ if (sig != SIGUSR1 && sig != SIGUSR2) {
+ usbmuxd_log(LL_NOTICE,"Caught signal %d, exiting", sig);
+ should_exit = 1;
+ } else {
+ if(opt_enable_exit) {
+ if (sig == SIGUSR1) {
+ usbmuxd_log(LL_INFO, "Caught SIGUSR1, checking if we can terminate (no more devices attached)...");
+ if (device_get_count(1) > 0) {
+ // we can't quit, there are still devices attached.
+ usbmuxd_log(LL_NOTICE, "Refusing to terminate, there are still devices attached. Kill me with signal 15 (TERM) to force quit.");
+ } else {
+ // it's safe to quit
+ should_exit = 1;
+ }
+ } else if (sig == SIGUSR2) {
+ usbmuxd_log(LL_INFO, "Caught SIGUSR2, scheduling device discovery");
+ should_discover = 1;
+ }
+ } else {
+ usbmuxd_log(LL_INFO, "Caught SIGUSR1/2 but this instance was not started with \"--enable-exit\", ignoring.");
+ }
+ }
+}
+
+static void set_signal_handlers(void)
+{
+ struct sigaction sa;
+ sigset_t set;
+
+ // Mask all signals we handle. They will be unmasked by ppoll().
+ sigemptyset(&set);
+ sigaddset(&set, SIGINT);
+ sigaddset(&set, SIGQUIT);
+ sigaddset(&set, SIGTERM);
+ sigaddset(&set, SIGUSR1);
+ sigaddset(&set, SIGUSR2);
+ sigprocmask(SIG_SETMASK, &set, NULL);
+
+ memset(&sa, 0, sizeof(struct sigaction));
+ sa.sa_handler = handle_signal;
+ sigaction(SIGINT, &sa, NULL);
+ sigaction(SIGQUIT, &sa, NULL);
+ sigaction(SIGTERM, &sa, NULL);
+ sigaction(SIGUSR1, &sa, NULL);
+ sigaction(SIGUSR2, &sa, NULL);
+}
+
+#ifndef HAVE_PPOLL
+static int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask)
+{
+ int ready;
+ sigset_t origmask;
+ int to = timeout->tv_sec*1000 + timeout->tv_nsec/1000000;
+
+ sigprocmask(SIG_SETMASK, sigmask, &origmask);
+ ready = poll(fds, nfds, to);
+ sigprocmask(SIG_SETMASK, &origmask, NULL);
+
+ return ready;
+}
+#endif
+
+static int main_loop(int listenfd)
+{
+ int to, cnt, i, dto;
+ struct fdlist pollfds;
+ struct timespec tspec;
+
+ sigset_t empty_sigset;
+ sigemptyset(&empty_sigset); // unmask all signals
+
+ fdlist_create(&pollfds);
+ while(!should_exit) {
+ usbmuxd_log(LL_FLOOD, "main_loop iteration");
+ to = usb_get_timeout();
+ usbmuxd_log(LL_FLOOD, "USB timeout is %d ms", to);
+ dto = device_get_timeout();
+ usbmuxd_log(LL_FLOOD, "Device timeout is %d ms", dto);
+ if(dto < to)
+ to = dto;
+
+ fdlist_reset(&pollfds);
+ fdlist_add(&pollfds, FD_LISTEN, listenfd, POLLIN);
+ usb_get_fds(&pollfds);
+ client_get_fds(&pollfds);
+ usbmuxd_log(LL_FLOOD, "fd count is %d", pollfds.count);
+
+ tspec.tv_sec = to / 1000;
+ tspec.tv_nsec = (to % 1000) * 1000000;
+ cnt = ppoll(pollfds.fds, pollfds.count, &tspec, &empty_sigset);
+ usbmuxd_log(LL_FLOOD, "poll() returned %d", cnt);
+ if(cnt == -1) {
+ if(errno == EINTR) {
+ if(should_exit) {
+ usbmuxd_log(LL_INFO, "Event processing interrupted");
+ break;
+ }
+ if(should_discover) {
+ should_discover = 0;
+ usbmuxd_log(LL_INFO, "Device discovery triggered");
+ usb_discover();
+ }
+ }
+ } else if(cnt == 0) {
+ if(usb_process() < 0) {
+ usbmuxd_log(LL_FATAL, "usb_process() failed");
+ fdlist_free(&pollfds);
+ return -1;
+ }
+ device_check_timeouts();
+ } else {
+ int done_usb = 0;
+ for(i=0; i<pollfds.count; i++) {
+ if(pollfds.fds[i].revents) {
+ if(!done_usb && pollfds.owners[i] == FD_USB) {
+ if(usb_process() < 0) {
+ usbmuxd_log(LL_FATAL, "usb_process() failed");
+ fdlist_free(&pollfds);
+ return -1;
+ }
+ done_usb = 1;
+ }
+ if(pollfds.owners[i] == FD_LISTEN) {
+ if(client_accept(listenfd) < 0) {
+ usbmuxd_log(LL_FATAL, "client_accept() failed");
+ fdlist_free(&pollfds);
+ return -1;
+ }
+ }
+ if(pollfds.owners[i] == FD_CLIENT) {
+ client_process(pollfds.fds[i].fd, pollfds.fds[i].revents);
+ }
+ }
+ }
+ }
+ }
+ fdlist_free(&pollfds);
+ return 0;
+}
+
+/**
+ * make this program run detached from the current console
+ */
+static int daemonize(void)
+{
+ pid_t pid;
+ pid_t sid;
+ int pfd[2];
+ int res;
+
+ // already a daemon
+ if (getppid() == 1)
+ return 0;
+
+ if((res = pipe(pfd)) < 0) {
+ usbmuxd_log(LL_FATAL, "pipe() failed.");
+ return res;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ usbmuxd_log(LL_FATAL, "fork() failed.");
+ return pid;
+ }
+
+ if (pid > 0) {
+ // exit parent process
+ int status;
+ close(pfd[1]);
+
+ if((res = read(pfd[0],&status,sizeof(int))) != sizeof(int)) {
+ fprintf(stderr, "usbmuxd: ERROR: Failed to get init status from child, check syslog for messages.\n");
+ exit(1);
+ }
+ if(status != 0)
+ fprintf(stderr, "usbmuxd: ERROR: Child process exited with error %d, check syslog for messages.\n", status);
+ exit(status);
+ }
+ // At this point we are executing as the child process
+ // but we need to do one more fork
+
+ daemon_pipe = pfd[1];
+ close(pfd[0]);
+ report_to_parent = 1;
+
+ // Create a new SID for the child process
+ sid = setsid();
+ if (sid < 0) {
+ usbmuxd_log(LL_FATAL, "setsid() failed.");
+ return -1;
+ }
+
+ pid = fork();
+ if (pid < 0) {
+ usbmuxd_log(LL_FATAL, "fork() failed (second).");
+ return pid;
+ }
+
+ if (pid > 0) {
+ // exit parent process
+ close(daemon_pipe);
+ exit(0);
+ }
+
+ // Change the current working directory.
+ if ((chdir("/")) < 0) {
+ usbmuxd_log(LL_FATAL, "chdir() failed");
+ return -2;
+ }
+ // Redirect standard files to /dev/null
+ if (!freopen("/dev/null", "r", stdin)) {
+ usbmuxd_log(LL_FATAL, "Redirection of stdin failed.");
+ return -3;
+ }
+ if (!freopen("/dev/null", "w", stdout)) {
+ usbmuxd_log(LL_FATAL, "Redirection of stdout failed.");
+ return -3;
+ }
+
+ return 0;
+}
+
+static int notify_parent(int status)
+{
+ int res;
+
+ report_to_parent = 0;
+ if ((res = write(daemon_pipe, &status, sizeof(int))) != sizeof(int)) {
+ usbmuxd_log(LL_FATAL, "Could not notify parent!");
+ if(res >= 0)
+ return -2;
+ else
+ return res;
+ }
+ close(daemon_pipe);
+ if (!freopen("/dev/null", "w", stderr)) {
+ usbmuxd_log(LL_FATAL, "Redirection of stderr failed.");
+ return -1;
+ }
+ return 0;
+}
+
+static void usage()
+{
+ printf("Usage: %s [OPTIONS]\n", PACKAGE_NAME);
+ printf("\n");
+ printf("Expose a socket to multiplex connections from and to iOS devices.\n");
+ printf("\n");
+ printf("OPTIONS:\n");
+ printf(" -h, --help\t\tPrint this message.\n");
+ printf(" -v, --verbose\t\tBe verbose (use twice or more to increase).\n");
+ printf(" -f, --foreground\tDo not daemonize (implies one -v).\n");
+ printf(" -U, --user USER\tChange to this user after startup (needs USB privileges).\n");
+ printf(" -n, --disable-hotplug\tDisables automatic discovery of devices on hotplug.\n");
+ printf(" \tStarting another instance will trigger discovery instead.\n");
+ printf(" -z, --enable-exit\tEnable \"--exit\" request from other instances and exit\n");
+ printf(" \tautomatically if no device is attached.\n");
+ printf(" -p, --no-preflight\tDisable lockdownd preflight on new device.\n");
+#ifdef HAVE_UDEV
+ printf(" -u, --udev\t\tRun in udev operation mode (implies -n and -z).\n");
+#endif
+#ifdef HAVE_SYSTEMD
+ printf(" -s, --systemd\t\tRun in systemd operation mode (implies -z and -f).\n");
+#endif
+ printf(" -S, --socket ADDR:PORT | PATH Specify source ADDR and PORT or a UNIX\n");
+ printf(" \t\tsocket PATH to use for the listening socket.\n");
+ printf(" \t\tDefault: %s\n", socket_path);
+ printf(" -P, --pidfile PATH\tSpecify a different location for the pid file, or pass\n");
+ printf(" \t\tNONE to disable. Default: %s\n", DEFAULT_LOCKFILE);
+ printf(" -x, --exit\t\tNotify a running instance to exit if there are no devices\n");
+ printf(" \t\tconnected (sends SIGUSR1 to running instance) and exit.\n");
+ printf(" -X, --force-exit\tNotify a running instance to exit even if there are still\n");
+ printf(" \tdevices connected (always works) and exit.\n");
+ printf(" -l, --logfile=LOGFILE\tLog (append) to LOGFILE instead of stderr or syslog.\n");
+ printf(" -V, --version\t\tPrint version information and exit.\n");
+ printf("\n");
+ printf("Homepage: <" PACKAGE_URL ">\n");
+ printf("Bug Reports: <" PACKAGE_BUGREPORT ">\n");
+}
+
+static void parse_opts(int argc, char **argv)
+{
+ static struct option longopts[] = {
+ {"help", no_argument, NULL, 'h'},
+ {"foreground", no_argument, NULL, 'f'},
+ {"verbose", no_argument, NULL, 'v'},
+ {"user", required_argument, NULL, 'U'},
+ {"disable-hotplug", no_argument, NULL, 'n'},
+ {"enable-exit", no_argument, NULL, 'z'},
+ {"no-preflight", no_argument, NULL, 'p'},
+#ifdef HAVE_UDEV
+ {"udev", no_argument, NULL, 'u'},
+#endif
+#ifdef HAVE_SYSTEMD
+ {"systemd", no_argument, NULL, 's'},
+#endif
+ {"socket", required_argument, NULL, 'S'},
+ {"pidfile", required_argument, NULL, 'P'},
+ {"exit", no_argument, NULL, 'x'},
+ {"force-exit", no_argument, NULL, 'X'},
+ {"logfile", required_argument, NULL, 'l'},
+ {"version", no_argument, NULL, 'V'},
+ {NULL, 0, NULL, 0}
+ };
+ int c;
+
+#ifdef HAVE_SYSTEMD
+ const char* opts_spec = "hfvVuU:xXsnzl:pS:P:";
+#elif HAVE_UDEV
+ const char* opts_spec = "hfvVuU:xXnzl:pS:P:";
+#else
+ const char* opts_spec = "hfvVU:xXnzl:pS:P:";
+#endif
+
+ while (1) {
+ c = getopt_long(argc, argv, opts_spec, longopts, (int *) 0);
+ if (c == -1) {
+ break;
+ }
+
+ switch (c) {
+ case 'h':
+ usage();
+ exit(0);
+ case 'f':
+ foreground = 1;
+ break;
+ case 'v':
+ ++verbose;
+ break;
+ case 'V':
+ printf("%s\n", PACKAGE_STRING);
+ exit(0);
+ case 'U':
+ drop_privileges = 1;
+ drop_user = optarg;
+ break;
+ case 'p':
+ no_preflight = 1;
+ break;
+#ifdef HAVE_UDEV
+ case 'u':
+ opt_disable_hotplug = 1;
+ opt_enable_exit = 1;
+ break;
+#endif
+#ifdef HAVE_SYSTEMD
+ case 's':
+ opt_enable_exit = 1;
+ foreground = 1;
+ break;
+#endif
+ case 'n':
+ opt_disable_hotplug = 1;
+ break;
+ case 'z':
+ opt_enable_exit = 1;
+ break;
+ case 'S':
+ if (!*optarg || *optarg == '-') {
+ usbmuxd_log(LL_FATAL, "ERROR: --socket requires an argument");
+ usage();
+ exit(2);
+ }
+ listen_addr = optarg;
+ break;
+ case 'P':
+ if (!*optarg || *optarg == '-') {
+ usbmuxd_log(LL_FATAL, "ERROR: --pidfile requires an argument");
+ usage();
+ exit(2);
+ }
+ if (!strcmp(optarg, "NONE")) {
+ lockfile = NULL;
+ } else {
+ lockfile = optarg;
+ }
+ break;
+ case 'x':
+ opt_exit = 1;
+ exit_signal = SIGUSR1;
+ break;
+ case 'X':
+ opt_exit = 1;
+ exit_signal = SIGTERM;
+ break;
+ case 'l':
+ if (!*optarg) {
+ usbmuxd_log(LL_FATAL, "ERROR: --logfile requires a non-empty filename");
+ usage();
+ exit(2);
+ }
+ if (use_logfile) {
+ usbmuxd_log(LL_FATAL, "ERROR: --logfile cannot be used multiple times");
+ exit(2);
+ }
+ if (!freopen(optarg, "a", stderr)) {
+ usbmuxd_log(LL_FATAL, "ERROR: fdreopen: %s", strerror(errno));
+ } else {
+ use_logfile = 1;
+ }
+ break;
+ default:
+ usage();
+ exit(2);
+ }
+ }
+}
+
+int main(int argc, char *argv[])
+{
+ int listenfd;
+ int res = 0;
+ int lfd;
+ struct flock lock;
+ char pids[10];
+
+ parse_opts(argc, argv);
+
+ argc -= optind;
+ argv += optind;
+
+ if (!foreground && !use_logfile) {
+ verbose += LL_WARNING;
+ log_enable_syslog();
+ } else {
+ verbose += LL_NOTICE;
+ }
+
+ /* set log level to specified verbosity */
+ log_level = verbose;
+
+ usbmuxd_log(LL_NOTICE, "usbmuxd v%s starting up", PACKAGE_VERSION);
+ should_exit = 0;
+ should_discover = 0;
+
+ set_signal_handlers();
+ signal(SIGPIPE, SIG_IGN);
+
+ if (lockfile) {
+ res = lfd = open(lockfile, O_WRONLY|O_CREAT, 0644);
+ if(res == -1) {
+ usbmuxd_log(LL_FATAL, "Could not open lockfile");
+ goto terminate;
+ }
+ lock.l_type = F_WRLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = 0;
+ lock.l_len = 0;
+ lock.l_pid = 0;
+ fcntl(lfd, F_GETLK, &lock);
+ close(lfd);
+ }
+ if (lockfile && lock.l_type != F_UNLCK) {
+ if (opt_exit) {
+ if (lock.l_pid && !kill(lock.l_pid, 0)) {
+ usbmuxd_log(LL_NOTICE, "Sending signal %d to instance with pid %d", exit_signal, lock.l_pid);
+ res = 0;
+ if (kill(lock.l_pid, exit_signal) < 0) {
+ usbmuxd_log(LL_FATAL, "Could not deliver signal %d to pid %d", exit_signal, lock.l_pid);
+ res = -1;
+ }
+ goto terminate;
+ } else {
+ usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
+ res = -1;
+ goto terminate;
+ }
+ } else {
+ if (!opt_disable_hotplug) {
+ usbmuxd_log(LL_ERROR, "Another instance is already running (pid %d). exiting.", lock.l_pid);
+ res = -1;
+ } else {
+ usbmuxd_log(LL_NOTICE, "Another instance is already running (pid %d). Telling it to check for devices.", lock.l_pid);
+ if (lock.l_pid && !kill(lock.l_pid, 0)) {
+ usbmuxd_log(LL_NOTICE, "Sending signal SIGUSR2 to instance with pid %d", lock.l_pid);
+ res = 0;
+ if (kill(lock.l_pid, SIGUSR2) < 0) {
+ usbmuxd_log(LL_FATAL, "Could not deliver SIGUSR2 to pid %d", lock.l_pid);
+ res = -1;
+ }
+ } else {
+ usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
+ res = -1;
+ }
+ }
+ goto terminate;
+ }
+ }
+ if (lockfile) {
+ unlink(lockfile);
+ }
+
+ if (opt_exit) {
+ usbmuxd_log(LL_NOTICE, "No running instance found, none killed. Exiting.");
+ goto terminate;
+ }
+
+ if (!foreground) {
+ if ((res = daemonize()) < 0) {
+ fprintf(stderr, "usbmuxd: FATAL: Could not daemonize!\n");
+ usbmuxd_log(LL_FATAL, "Could not daemonize!");
+ goto terminate;
+ }
+ }
+
+ if (lockfile) {
+ // now open the lockfile and place the lock
+ res = lfd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644);
+ if(res < 0) {
+ usbmuxd_log(LL_FATAL, "Could not open pidfile '%s'", lockfile);
+ goto terminate;
+ }
+ lock.l_type = F_WRLCK;
+ lock.l_whence = SEEK_SET;
+ lock.l_start = 0;
+ lock.l_len = 0;
+ if ((res = fcntl(lfd, F_SETLK, &lock)) < 0) {
+ usbmuxd_log(LL_FATAL, "Locking pidfile '%s' failed!", lockfile);
+ goto terminate;
+ }
+ sprintf(pids, "%d", getpid());
+ if ((size_t)(res = write(lfd, pids, strlen(pids))) != strlen(pids)) {
+ usbmuxd_log(LL_FATAL, "Could not write pidfile!");
+ if(res >= 0)
+ res = -2;
+ goto terminate;
+ }
+ }
+
+ // set number of file descriptors to higher value
+ struct rlimit rlim;
+ getrlimit(RLIMIT_NOFILE, &rlim);
+ rlim.rlim_max = 65536;
+ setrlimit(RLIMIT_NOFILE, (const struct rlimit*)&rlim);
+
+ usbmuxd_log(LL_INFO, "Creating socket");
+ res = listenfd = create_socket();
+ if(listenfd < 0)
+ goto terminate;
+
+#ifdef HAVE_LIBIMOBILEDEVICE
+ const char* userprefdir = config_get_config_dir();
+ struct stat fst;
+ memset(&fst, '\0', sizeof(struct stat));
+ if (stat(userprefdir, &fst) < 0) {
+ if (mkdir(userprefdir, 0775) < 0) {
+ usbmuxd_log(LL_FATAL, "Failed to create required directory '%s': %s", userprefdir, strerror(errno));
+ res = -1;
+ goto terminate;
+ }
+ if (stat(userprefdir, &fst) < 0) {
+ usbmuxd_log(LL_FATAL, "stat() failed after creating directory '%s': %s", userprefdir, strerror(errno));
+ res = -1;
+ goto terminate;
+ }
+ }
+
+ // make sure permission bits are set correctly
+ if (fst.st_mode != 02775) {
+ if (chmod(userprefdir, 02775) < 0) {
+ usbmuxd_log(LL_WARNING, "chmod(%s, 02775) failed: %s", userprefdir, strerror(errno));
+ }
+ }
+#endif
+
+ // drop elevated privileges
+ if (drop_privileges && (getuid() == 0 || geteuid() == 0)) {
+ struct passwd *pw;
+ if (!drop_user) {
+ usbmuxd_log(LL_FATAL, "No user to drop privileges to?");
+ res = -1;
+ goto terminate;
+ }
+ pw = getpwnam(drop_user);
+ if (!pw) {
+ usbmuxd_log(LL_FATAL, "Dropping privileges failed, check if user '%s' exists!", drop_user);
+ res = -1;
+ goto terminate;
+ }
+ if (pw->pw_uid == 0) {
+ usbmuxd_log(LL_INFO, "Not dropping privileges to root");
+ } else {
+#ifdef HAVE_LIBIMOBILEDEVICE
+ /* make sure the non-privileged user has proper access to the config directory */
+ if ((fst.st_uid != pw->pw_uid) || (fst.st_gid != pw->pw_gid)) {
+ if (chown(userprefdir, pw->pw_uid, pw->pw_gid) < 0) {
+ usbmuxd_log(LL_WARNING, "chown(%s, %d, %d) failed: %s", userprefdir, pw->pw_uid, pw->pw_gid, strerror(errno));
+ }
+ }
+#endif
+
+ if ((res = initgroups(drop_user, pw->pw_gid)) < 0) {
+ usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set supplementary groups)");
+ goto terminate;
+ }
+ if ((res = setgid(pw->pw_gid)) < 0) {
+ usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set group ID to %d)", pw->pw_gid);
+ goto terminate;
+ }
+ if ((res = setuid(pw->pw_uid)) < 0) {
+ usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set user ID to %d)", pw->pw_uid);
+ goto terminate;
+ }
+
+ // security check
+ if (setuid(0) != -1) {
+ usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
+ res = -1;
+ goto terminate;
+ }
+ if (getuid() != pw->pw_uid || getgid() != pw->pw_gid) {
+ usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
+ res = -1;
+ goto terminate;
+ }
+ usbmuxd_log(LL_NOTICE, "Successfully dropped privileges to '%s'", drop_user);
+ }
+ }
+
+ client_init();
+ device_init();
+ usbmuxd_log(LL_INFO, "Initializing USB");
+ if((res = usb_init()) < 0)
+ goto terminate;
+
+ usbmuxd_log(LL_INFO, "%d device%s detected", res, (res==1)?"":"s");
+
+ usbmuxd_log(LL_NOTICE, "Initialization complete");
+
+ if (report_to_parent)
+ if((res = notify_parent(0)) < 0)
+ goto terminate;
+
+ if(opt_disable_hotplug) {
+ usbmuxd_log(LL_NOTICE, "Automatic device discovery on hotplug disabled.");
+ usb_autodiscover(0); // discovery to be triggered by new instance
+ }
+ if (opt_enable_exit) {
+ usbmuxd_log(LL_NOTICE, "Enabled exit on SIGUSR1 if no devices are attached. Start a new instance with \"--exit\" to trigger.");
+ }
+
+ res = main_loop(listenfd);
+ if(res < 0)
+ usbmuxd_log(LL_FATAL, "main_loop failed");
+
+ usbmuxd_log(LL_NOTICE, "usbmuxd shutting down");
+ device_kill_connections();
+ usb_shutdown();
+ device_shutdown();
+ client_shutdown();
+ usbmuxd_log(LL_NOTICE, "Shutdown complete");
+
+terminate:
+ log_disable_syslog();
+
+ if (res < 0)
+ res = -res;
+ else
+ res = 0;
+ if (report_to_parent)
+ notify_parent(res);
+
+ return res;
+}
diff --git a/src/preflight.c b/src/preflight.c
new file mode 100644
index 0000000..9c57e98
--- /dev/null
+++ b/src/preflight.c
@@ -0,0 +1,406 @@
+/*
+ * preflight.c
+ *
+ * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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 <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include <sys/time.h>
+
+#ifdef HAVE_LIBIMOBILEDEVICE
+#include <libimobiledevice/libimobiledevice.h>
+#include <libimobiledevice/lockdown.h>
+#include <libimobiledevice/notification_proxy.h>
+#endif
+
+#include <libimobiledevice-glue/thread.h>
+
+#include "preflight.h"
+#include "device.h"
+#include "client.h"
+#include "conf.h"
+#include "log.h"
+#include "usb.h"
+
+extern int no_preflight;
+
+#ifdef HAVE_LIBIMOBILEDEVICE
+#ifndef HAVE_ENUM_IDEVICE_CONNECTION_TYPE
+enum idevice_connection_type {
+ CONNECTION_USBMUXD = 1,
+ CONNECTION_NETWORK
+};
+#endif
+
+struct idevice_private {
+ char *udid;
+ uint32_t mux_id;
+ enum idevice_connection_type conn_type;
+ void *conn_data;
+ int version;
+ int device_class;
+};
+
+struct cb_data {
+ idevice_t dev;
+ np_client_t np;
+ int is_device_connected;
+ int is_finished;
+};
+
+static void lockdownd_set_untrusted_host_buid(lockdownd_client_t lockdown)
+{
+ char* system_buid = NULL;
+ config_get_system_buid(&system_buid);
+ usbmuxd_log(LL_DEBUG, "%s: Setting UntrustedHostBUID to %s", __func__, system_buid);
+ lockdownd_set_value(lockdown, NULL, "UntrustedHostBUID", plist_new_string(system_buid));
+ free(system_buid);
+}
+
+void preflight_device_remove_cb(void *data)
+{
+ if (!data)
+ return;
+ struct cb_data *cbdata = (struct cb_data*)data;
+ cbdata->is_device_connected = 0;
+}
+
+static void np_callback(const char* notification, void* userdata)
+{
+ struct cb_data *cbdata = (struct cb_data*)userdata;
+ idevice_t dev = cbdata->dev;
+ struct idevice_private *_dev = (struct idevice_private*)dev;
+
+ lockdownd_client_t lockdown = NULL;
+ lockdownd_error_t lerr;
+
+ if (strlen(notification) == 0) {
+ cbdata->np = NULL;
+ return;
+ }
+
+ if (strcmp(notification, "com.apple.mobile.lockdown.request_pair") == 0) {
+ usbmuxd_log(LL_INFO, "%s: user trusted this computer on device %s, pairing now", __func__, _dev->udid);
+ lerr = lockdownd_client_new(dev, &lockdown, "usbmuxd");
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ cbdata->is_finished = 1;
+ return;
+ }
+
+ lerr = lockdownd_pair(lockdown, NULL);
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: Pair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ lockdownd_client_free(lockdown);
+ cbdata->is_finished = 1;
+ return;
+ }
+ lockdownd_client_free(lockdown);
+ cbdata->is_finished = 1;
+
+ } else if (strcmp(notification, "com.apple.mobile.lockdown.request_host_buid") == 0) {
+ lerr = lockdownd_client_new(cbdata->dev, &lockdown, "usbmuxd");
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ } else {
+ lockdownd_set_untrusted_host_buid(lockdown);
+ lockdownd_client_free(lockdown);
+ }
+ }
+}
+
+static void* preflight_worker_handle_device_add(void* userdata)
+{
+ struct device_info *info = (struct device_info*)userdata;
+ struct idevice_private *_dev = (struct idevice_private*)malloc(sizeof(struct idevice_private));
+ _dev->udid = strdup(info->serial);
+ _dev->mux_id = info->id;
+ _dev->conn_type = CONNECTION_USBMUXD;
+ _dev->conn_data = NULL;
+ _dev->version = 0;
+ _dev->device_class = 0;
+
+ idevice_t dev = (idevice_t)_dev;
+
+ lockdownd_client_t lockdown = NULL;
+ lockdownd_error_t lerr;
+
+ plist_t value = NULL;
+ char* version_str = NULL;
+ char* deviceclass_str = NULL;
+
+ usbmuxd_log(LL_INFO, "%s: Starting preflight on device %s...", __func__, _dev->udid);
+
+retry:
+ lerr = lockdownd_client_new(dev, &lockdown, "usbmuxd");
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ goto leave;
+ }
+
+ char *type = NULL;
+ lerr = lockdownd_query_type(lockdown, &type);
+ if (!type) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: Could not get lockdownd type from device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ goto leave;
+ }
+
+ if (strcmp(type, "com.apple.mobile.lockdown") != 0) {
+ // make restore mode devices visible
+ free(type);
+ usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid);
+ client_device_add(info);
+ goto leave;
+ }
+ free(type);
+
+ int is_device_paired = 0;
+ char *host_id = NULL;
+ if (config_has_device_record(dev->udid)) {
+ config_device_record_get_host_id(dev->udid, &host_id);
+ lerr = lockdownd_start_session(lockdown, host_id, NULL, NULL);
+ if (host_id)
+ free(host_id);
+ if (lerr == LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_INFO, "%s: StartSession success for device %s", __func__, _dev->udid);
+ usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid);
+ client_device_add(info);
+ goto leave;
+ }
+
+ usbmuxd_log(LL_INFO, "%s: StartSession failed on device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ } else {
+ lerr = LOCKDOWN_E_INVALID_HOST_ID;
+ }
+ switch (lerr) {
+ case LOCKDOWN_E_INVALID_HOST_ID:
+ usbmuxd_log(LL_INFO, "%s: Device %s is not paired with this host.", __func__, _dev->udid);
+ break;
+ case LOCKDOWN_E_SSL_ERROR:
+ usbmuxd_log(LL_ERROR, "%s: The stored pair record for device %s is invalid. Removing.", __func__, _dev->udid);
+ if (config_remove_device_record(_dev->udid) == 0) {
+ lockdownd_client_free(lockdown);
+ lockdown = NULL;
+ goto retry;
+ } else {
+ usbmuxd_log(LL_ERROR, "%s: Could not remove pair record for device %s", __func__, _dev->udid);
+ }
+ break;
+ default:
+ is_device_paired = 1;
+ break;
+ }
+
+ lerr = lockdownd_get_value(lockdown, NULL, "ProductVersion", &value);
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_WARNING, "%s: Could not get ProductVersion from device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ /* assume old iOS version */
+ version_str = strdup("1.0");
+ } else {
+ if (value && plist_get_node_type(value) == PLIST_STRING) {
+ plist_get_string_val(value, &version_str);
+ }
+ plist_free(value);
+
+ if (!version_str) {
+ usbmuxd_log(LL_ERROR, "%s: Could not get ProductVersion string from device %s handle %d", __func__, _dev->udid, (int)(long)_dev->conn_data);
+ goto leave;
+ }
+ }
+
+ lerr = lockdownd_get_value(lockdown, NULL, "DeviceClass", &value);
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: Could not get DeviceClass from device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ goto leave;
+ }
+ if (value && plist_get_node_type(value) == PLIST_STRING) {
+ plist_get_string_val(value, &deviceclass_str);
+ }
+ plist_free(value);
+
+ if (!deviceclass_str) {
+ usbmuxd_log(LL_ERROR, "%s: Could not get DeviceClass string from device %s handle %d", __func__, _dev->udid, (int)(long)_dev->conn_data);
+ goto leave;
+ }
+
+ int version_major = strtol(version_str, NULL, 10);
+ if (((!strcmp(deviceclass_str, "iPhone") || !strcmp(deviceclass_str, "iPad")) && version_major >= 7)
+ || (!strcmp(deviceclass_str, "Watch") && version_major >= 2)
+ || (!strcmp(deviceclass_str, "AppleTV") && version_major >= 9)
+ ) {
+ /* iOS 7.0 / watchOS 2.0 / tvOS 9.0 and later */
+ usbmuxd_log(LL_INFO, "%s: Found %s %s device %s", __func__, deviceclass_str, version_str, _dev->udid);
+
+ lockdownd_set_untrusted_host_buid(lockdown);
+
+ /* if not paired, trigger the trust dialog to make sure it appears */
+ if (!is_device_paired) {
+ if (lockdownd_pair(lockdown, NULL) == LOCKDOWN_E_SUCCESS) {
+ /* if device is still showing the setup screen it will pair even without trust dialog */
+ usbmuxd_log(LL_INFO, "%s: Pair success for device %s", __func__, _dev->udid);
+ usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid);
+ client_device_add(info);
+ goto leave;
+ }
+ }
+
+ lockdownd_service_descriptor_t service = NULL;
+ lerr = lockdownd_start_service(lockdown, "com.apple.mobile.insecure_notification_proxy", &service);
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ /* even though we failed, simple mode should still work, so only warn of an error */
+ usbmuxd_log(LL_INFO, "%s: ERROR: Could not start insecure_notification_proxy on %s, lockdown error %d", __func__, _dev->udid, lerr);
+ client_device_add(info);
+ goto leave;
+ }
+
+ np_client_t np = NULL;
+ np_client_new(dev, service, &np);
+
+ lockdownd_service_descriptor_free(service);
+ service = NULL;
+
+ lockdownd_client_free(lockdown);
+ lockdown = NULL;
+
+ struct cb_data cbdata;
+ cbdata.dev = dev;
+ cbdata.np = np;
+ cbdata.is_device_connected = 1;
+ cbdata.is_finished = 0;
+
+ np_set_notify_callback(np, np_callback, (void*)&cbdata);
+ device_set_preflight_cb_data(info->id, (void*)&cbdata);
+
+ const char* spec[] = {
+ "com.apple.mobile.lockdown.request_pair",
+ "com.apple.mobile.lockdown.request_host_buid",
+ NULL
+ };
+ np_observe_notifications(np, spec);
+
+ /* TODO send notification to user's desktop */
+
+ usbmuxd_log(LL_INFO, "%s: Waiting for user to trust this computer on device %s", __func__, _dev->udid);
+
+ /* make device visible anyways */
+ client_device_add(info);
+
+ while (cbdata.np && cbdata.is_device_connected && !cbdata.is_finished) {
+ sleep(1);
+ }
+ device_set_preflight_cb_data(info->id, NULL);
+
+ usbmuxd_log(LL_INFO, "%s: Finished waiting for notification from device %s, is_device_connected %d", __func__, _dev->udid, cbdata.is_device_connected);
+
+ if (cbdata.np) {
+ np_client_free(cbdata.np);
+ }
+ } else {
+ /* iOS 6.x and earlier */
+ lerr = lockdownd_pair(lockdown, NULL);
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ if (lerr == LOCKDOWN_E_PASSWORD_PROTECTED) {
+ usbmuxd_log(LL_INFO, "%s: Device %s is locked with a passcode. Cannot pair.", __func__, _dev->udid);
+ /* TODO send notification to user's desktop */
+ } else {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: Pair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ }
+
+ usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid);
+
+ /* make device visible anyways */
+ client_device_add(info);
+
+ goto leave;
+ }
+
+ host_id = NULL;
+ config_device_record_get_host_id(dev->udid, &host_id);
+ lerr = lockdownd_start_session(lockdown, host_id, NULL, NULL);
+ free(host_id);
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR StartSession failed on device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ goto leave;
+ }
+
+ lerr = lockdownd_validate_pair(lockdown, NULL);
+ if (lerr != LOCKDOWN_E_SUCCESS) {
+ usbmuxd_log(LL_ERROR, "%s: ERROR: ValidatePair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr);
+ goto leave;
+ }
+
+ usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid);
+
+ /* emit device added event and thus make device visible to clients */
+ client_device_add(info);
+ }
+
+leave:
+ free(deviceclass_str);
+ free(version_str);
+ if (lockdown)
+ lockdownd_client_free(lockdown);
+ if (dev)
+ idevice_free(dev);
+
+ free((char*)info->serial);
+ free(info);
+
+ return NULL;
+}
+#else
+void preflight_device_remove_cb(void *data)
+{
+}
+#endif
+
+void preflight_worker_device_add(struct device_info* info)
+{
+ if (info->pid == PID_APPLE_T2_COPROCESSOR || no_preflight == 1) {
+ client_device_add(info);
+ return;
+ }
+
+#ifdef HAVE_LIBIMOBILEDEVICE
+ struct device_info *infocopy = (struct device_info*)malloc(sizeof(struct device_info));
+
+ memcpy(infocopy, info, sizeof(struct device_info));
+ if (info->serial) {
+ infocopy->serial = strdup(info->serial);
+ }
+
+ THREAD_T th;
+ int perr = thread_new(&th, preflight_worker_handle_device_add, infocopy);
+ if (perr != 0) {
+ free((char*)infocopy->serial);
+ free(infocopy);
+ usbmuxd_log(LL_ERROR, "ERROR: failed to start preflight worker thread for device %s: %s (%d). Invoking client_device_add() directly but things might not work as expected.", info->serial, strerror(perr), perr);
+ client_device_add(info);
+ } else {
+ thread_detach(th);
+ }
+#else
+ client_device_add(info);
+#endif
+}
diff --git a/src/preflight.h b/src/preflight.h
new file mode 100644
index 0000000..dd8647e
--- /dev/null
+++ b/src/preflight.h
@@ -0,0 +1,28 @@
+/*
+ * preflight.h
+ *
+ * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#ifndef PREFLIGHT_H
+#define PREFLIGHT_H
+
+#include "device.h"
+
+void preflight_device_remove_cb(void *data);
+void preflight_worker_device_add(struct device_info* info);
+
+#endif
diff --git a/src/usb.c b/src/usb.c
new file mode 100644
index 0000000..d3cb17c
--- /dev/null
+++ b/src/usb.c
@@ -0,0 +1,1084 @@
+/*
+ * usb.c
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ * Copyright (C) 2009-2020 Martin Szulecki <martin.szulecki@libimobiledevice.org>
+ * Copyright (C) 2014 Mikkel Kamstrup Erlandsen <mikkel.kamstrup@xamarin.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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 <stdint.h>
+#include <string.h>
+
+#include <libusb.h>
+
+#include <libimobiledevice-glue/collection.h>
+
+#include "usb.h"
+#include "log.h"
+#include "device.h"
+#include "utils.h"
+
+#if (defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000102)) || (defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x01000102))
+#define HAVE_LIBUSB_HOTPLUG_API 1
+#endif
+
+// interval for device connection/disconnection polling, in milliseconds
+// we need this because there is currently no asynchronous device discovery mechanism in libusb
+#define DEVICE_POLL_TIME 1000
+
+// Number of parallel bulk transfers we have running for reading data from the device.
+// Older versions of usbmuxd kept only 1, which leads to a mostly dormant USB port.
+// 3 seems to be an all round sensible number - giving better read perf than
+// Apples usbmuxd, at least.
+#define NUM_RX_LOOPS 3
+
+struct usb_device {
+ libusb_device_handle *handle;
+ uint8_t bus, address;
+ char serial[256];
+ int alive;
+ uint8_t interface, ep_in, ep_out;
+ struct collection rx_xfers;
+ struct collection tx_xfers;
+ int wMaxPacketSize;
+ uint64_t speed;
+ struct libusb_device_descriptor devdesc;
+};
+
+struct mode_context {
+ struct libusb_device* dev;
+ uint8_t bus, address;
+ uint8_t bRequest;
+ uint16_t wValue, wIndex, wLength;
+ unsigned int timeout;
+};
+
+static struct collection device_list;
+
+static struct timeval next_dev_poll_time;
+
+static int devlist_failures;
+static int device_polling;
+static int device_hotplug = 1;
+
+static void usb_disconnect(struct usb_device *dev)
+{
+ if(!dev->handle) {
+ return;
+ }
+
+ // kill the rx xfer and tx xfers and try to make sure the callbacks
+ // get called before we free the device
+ FOREACH(struct libusb_transfer *xfer, &dev->rx_xfers) {
+ usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling RX xfer %p", xfer);
+ libusb_cancel_transfer(xfer);
+ } ENDFOREACH
+
+ FOREACH(struct libusb_transfer *xfer, &dev->tx_xfers) {
+ usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling TX xfer %p", xfer);
+ libusb_cancel_transfer(xfer);
+ } ENDFOREACH
+
+ // Busy-wait until all xfers are closed
+ while(collection_count(&dev->rx_xfers) || collection_count(&dev->tx_xfers)) {
+ struct timeval tv;
+ int res;
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 1000;
+ if((res = libusb_handle_events_timeout(NULL, &tv)) < 0) {
+ usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout for usb_disconnect failed: %s", libusb_error_name(res));
+ break;
+ }
+ }
+
+ collection_free(&dev->tx_xfers);
+ collection_free(&dev->rx_xfers);
+ libusb_release_interface(dev->handle, dev->interface);
+ libusb_close(dev->handle);
+ dev->handle = NULL;
+ collection_remove(&device_list, dev);
+ free(dev);
+}
+
+static void reap_dead_devices(void) {
+ FOREACH(struct usb_device *usbdev, &device_list) {
+ if(!usbdev->alive) {
+ device_remove(usbdev);
+ usb_disconnect(usbdev);
+ }
+ } ENDFOREACH
+}
+
+// Callback from write operation
+static void tx_callback(struct libusb_transfer *xfer)
+{
+ struct usb_device *dev = xfer->user_data;
+ usbmuxd_log(LL_SPEW, "TX callback dev %d-%d len %d -> %d status %d", dev->bus, dev->address, xfer->length, xfer->actual_length, xfer->status);
+ if(xfer->status != LIBUSB_TRANSFER_COMPLETED) {
+ switch(xfer->status) {
+ case LIBUSB_TRANSFER_COMPLETED: //shut up compiler
+ case LIBUSB_TRANSFER_ERROR:
+ // funny, this happens when we disconnect the device while waiting for a transfer, sometimes
+ usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to error or disconnect", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_TIMED_OUT:
+ usbmuxd_log(LL_ERROR, "TX transfer timed out for device %d-%d", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_CANCELLED:
+ usbmuxd_log(LL_DEBUG, "Device %d-%d TX transfer cancelled", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_STALL:
+ usbmuxd_log(LL_ERROR, "TX transfer stalled for device %d-%d", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_NO_DEVICE:
+ // other times, this happens, and also even when we abort the transfer after device removal
+ usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to disconnect", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_OVERFLOW:
+ usbmuxd_log(LL_ERROR, "TX transfer overflow for device %d-%d", dev->bus, dev->address);
+ break;
+ // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad)
+ default:
+ // this should never be reached.
+ break;
+ }
+ // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events
+ // we'll do device_remove there too
+ dev->alive = 0;
+ }
+ if(xfer->buffer)
+ free(xfer->buffer);
+ collection_remove(&dev->tx_xfers, xfer);
+ libusb_free_transfer(xfer);
+}
+
+int usb_send(struct usb_device *dev, const unsigned char *buf, int length)
+{
+ int res;
+ struct libusb_transfer *xfer = libusb_alloc_transfer(0);
+ libusb_fill_bulk_transfer(xfer, dev->handle, dev->ep_out, (void*)buf, length, tx_callback, dev, 0);
+ if((res = libusb_submit_transfer(xfer)) < 0) {
+ usbmuxd_log(LL_ERROR, "Failed to submit TX transfer %p len %d to device %d-%d: %s", buf, length, dev->bus, dev->address, libusb_error_name(res));
+ libusb_free_transfer(xfer);
+ return res;
+ }
+ collection_add(&dev->tx_xfers, xfer);
+ if (length % dev->wMaxPacketSize == 0) {
+ usbmuxd_log(LL_DEBUG, "Send ZLP");
+ // Send Zero Length Packet
+ xfer = libusb_alloc_transfer(0);
+ void *buffer = malloc(1);
+ libusb_fill_bulk_transfer(xfer, dev->handle, dev->ep_out, buffer, 0, tx_callback, dev, 0);
+ if((res = libusb_submit_transfer(xfer)) < 0) {
+ usbmuxd_log(LL_ERROR, "Failed to submit TX ZLP transfer to device %d-%d: %s", dev->bus, dev->address, libusb_error_name(res));
+ libusb_free_transfer(xfer);
+ return res;
+ }
+ collection_add(&dev->tx_xfers, xfer);
+ }
+ return 0;
+}
+
+// Callback from read operation
+// Under normal operation this issues a new read transfer request immediately,
+// doing a kind of read-callback loop
+static void rx_callback(struct libusb_transfer *xfer)
+{
+ struct usb_device *dev = xfer->user_data;
+ usbmuxd_log(LL_SPEW, "RX callback dev %d-%d len %d status %d", dev->bus, dev->address, xfer->actual_length, xfer->status);
+ if(xfer->status == LIBUSB_TRANSFER_COMPLETED) {
+ device_data_input(dev, xfer->buffer, xfer->actual_length);
+ libusb_submit_transfer(xfer);
+ } else {
+ switch(xfer->status) {
+ case LIBUSB_TRANSFER_COMPLETED: //shut up compiler
+ case LIBUSB_TRANSFER_ERROR:
+ // funny, this happens when we disconnect the device while waiting for a transfer, sometimes
+ usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to error or disconnect", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_TIMED_OUT:
+ usbmuxd_log(LL_ERROR, "RX transfer timed out for device %d-%d", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_CANCELLED:
+ usbmuxd_log(LL_DEBUG, "Device %d-%d RX transfer cancelled", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_STALL:
+ usbmuxd_log(LL_ERROR, "RX transfer stalled for device %d-%d", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_NO_DEVICE:
+ // other times, this happens, and also even when we abort the transfer after device removal
+ usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to disconnect", dev->bus, dev->address);
+ break;
+ case LIBUSB_TRANSFER_OVERFLOW:
+ usbmuxd_log(LL_ERROR, "RX transfer overflow for device %d-%d", dev->bus, dev->address);
+ break;
+ // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad)
+ default:
+ // this should never be reached.
+ break;
+ }
+
+ free(xfer->buffer);
+ collection_remove(&dev->rx_xfers, xfer);
+ libusb_free_transfer(xfer);
+
+ // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events
+ // we'll do device_remove there too
+ dev->alive = 0;
+ }
+}
+
+// Start a read-callback loop for this device
+static int start_rx_loop(struct usb_device *dev)
+{
+ int res;
+ void *buf;
+ struct libusb_transfer *xfer = libusb_alloc_transfer(0);
+ buf = malloc(USB_MRU);
+ libusb_fill_bulk_transfer(xfer, dev->handle, dev->ep_in, buf, USB_MRU, rx_callback, dev, 0);
+ if((res = libusb_submit_transfer(xfer)) != 0) {
+ usbmuxd_log(LL_ERROR, "Failed to submit RX transfer to device %d-%d: %s", dev->bus, dev->address, libusb_error_name(res));
+ libusb_free_transfer(xfer);
+ return res;
+ }
+
+ collection_add(&dev->rx_xfers, xfer);
+
+ return 0;
+}
+
+static void get_serial_callback(struct libusb_transfer *transfer)
+{
+ unsigned int di, si;
+ struct usb_device *usbdev = transfer->user_data;
+
+ if(transfer->status != LIBUSB_TRANSFER_COMPLETED) {
+ usbmuxd_log(LL_ERROR, "Failed to request serial for device %d-%d (%i)", usbdev->bus, usbdev->address, transfer->status);
+ libusb_free_transfer(transfer);
+ return;
+ }
+
+ /* De-unicode, taken from libusb */
+ unsigned char *data = libusb_control_transfer_get_data(transfer);
+ for (di = 0, si = 2; si < data[0] && di < sizeof(usbdev->serial)-1; si += 2) {
+ if ((data[si] & 0x80) || (data[si + 1])) /* non-ASCII */
+ usbdev->serial[di++] = '?';
+ else if (data[si] == '\0')
+ break;
+ else
+ usbdev->serial[di++] = data[si];
+ }
+ usbdev->serial[di] = '\0';
+
+ usbmuxd_log(LL_INFO, "Got serial '%s' for device %d-%d", usbdev->serial, usbdev->bus, usbdev->address);
+
+ libusb_free_transfer(transfer);
+
+ /* new style UDID: add hyphen between first 8 and following 16 digits */
+ if (di == 24) {
+ memmove(&usbdev->serial[9], &usbdev->serial[8], 16);
+ usbdev->serial[8] = '-';
+ usbdev->serial[di+1] = '\0';
+ }
+
+ /* Finish setup now */
+ if(device_add(usbdev) < 0) {
+ usb_disconnect(usbdev);
+ return;
+ }
+
+ // Spin up NUM_RX_LOOPS parallel usb data retrieval loops
+ // Old usbmuxds used only 1 rx loop, but that leaves the
+ // USB port sleeping most of the time
+ int rx_loops = NUM_RX_LOOPS;
+ for (rx_loops = NUM_RX_LOOPS; rx_loops > 0; rx_loops--) {
+ if(start_rx_loop(usbdev) < 0) {
+ usbmuxd_log(LL_WARNING, "Failed to start RX loop number %d", NUM_RX_LOOPS - rx_loops);
+ break;
+ }
+ }
+
+ // Ensure we have at least 1 RX loop going
+ if (rx_loops == NUM_RX_LOOPS) {
+ usbmuxd_log(LL_FATAL, "Failed to start any RX loop for device %d-%d",
+ usbdev->bus, usbdev->address);
+ device_remove(usbdev);
+ usb_disconnect(usbdev);
+ return;
+ } else if (rx_loops > 0) {
+ usbmuxd_log(LL_WARNING, "Failed to start all %d RX loops. Going on with %d loops. "
+ "This may have negative impact on device read speed.",
+ NUM_RX_LOOPS, NUM_RX_LOOPS - rx_loops);
+ } else {
+ usbmuxd_log(LL_DEBUG, "All %d RX loops started successfully", NUM_RX_LOOPS);
+ }
+}
+
+static void get_langid_callback(struct libusb_transfer *transfer)
+{
+ int res;
+ struct usb_device *usbdev = transfer->user_data;
+
+ transfer->flags |= LIBUSB_TRANSFER_FREE_BUFFER;
+
+ if(transfer->status != LIBUSB_TRANSFER_COMPLETED) {
+ usbmuxd_log(LL_ERROR, "Failed to request lang ID for device %d-%d (%i)", usbdev->bus,
+ usbdev->address, transfer->status);
+ libusb_free_transfer(transfer);
+ return;
+ }
+
+ unsigned char *data = libusb_control_transfer_get_data(transfer);
+ uint16_t langid = (uint16_t)(data[2] | (data[3] << 8));
+ usbmuxd_log(LL_INFO, "Got lang ID %u for device %d-%d", langid, usbdev->bus, usbdev->address);
+
+ /* re-use the same transfer */
+ libusb_fill_control_setup(transfer->buffer, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR,
+ (uint16_t)((LIBUSB_DT_STRING << 8) | usbdev->devdesc.iSerialNumber),
+ langid, 1024 + LIBUSB_CONTROL_SETUP_SIZE);
+ libusb_fill_control_transfer(transfer, usbdev->handle, transfer->buffer, get_serial_callback, usbdev, 1000);
+
+ if((res = libusb_submit_transfer(transfer)) < 0) {
+ usbmuxd_log(LL_ERROR, "Could not request transfer for device %d-%d: %s", usbdev->bus, usbdev->address, libusb_error_name(res));
+ libusb_free_transfer(transfer);
+ }
+}
+
+static int submit_vendor_specific(struct libusb_device_handle *handle, struct mode_context *context, libusb_transfer_cb_fn callback)
+{
+ struct libusb_transfer* ctrl_transfer = libusb_alloc_transfer(0);
+ int ret = 0;
+ unsigned char* buffer = calloc(LIBUSB_CONTROL_SETUP_SIZE + context->wLength, 1);
+ uint8_t bRequestType = LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE;
+ libusb_fill_control_setup(buffer, bRequestType, context->bRequest, context->wValue, context->wIndex, context->wLength);
+
+ ctrl_transfer->flags = LIBUSB_TRANSFER_FREE_TRANSFER;
+ libusb_fill_control_transfer(ctrl_transfer, handle, buffer, callback, context, context->timeout);
+
+ ret = libusb_submit_transfer(ctrl_transfer);
+ return ret;
+}
+
+static struct usb_device* find_device(int bus, int address)
+{
+ FOREACH(struct usb_device *usbdev, &device_list) {
+ if(usbdev->bus == bus && usbdev->address == address) {
+ return usbdev;
+ }
+ } ENDFOREACH
+ return NULL;
+}
+
+/// @brief guess the current mode
+/// @param dev
+/// @param usbdev
+/// @param handle
+/// @return 0 - undetermined, 1 - initial, 2 - valeria, 3 - cdc_ncm
+static int guess_mode(struct libusb_device* dev, struct usb_device *usbdev)
+{
+ int res, j;
+ int has_valeria = 0, has_cdc_ncm = 0, has_usbmux = 0;
+ struct libusb_device_descriptor devdesc = usbdev->devdesc;
+ struct libusb_config_descriptor *config;
+ int bus = usbdev->bus;
+ int address = usbdev->address;
+
+ if(devdesc.bNumConfigurations <= 4) {
+ // Assume this is initial mode
+ return 1;
+ }
+
+ if(devdesc.bNumConfigurations != 5) {
+ // No known modes with more then 5 configurations
+ return 0;
+ }
+
+ if((res = libusb_get_config_descriptor_by_value(dev, 5, &config)) != 0) {
+ usbmuxd_log(LL_NOTICE, "Could not get configuration 5 descriptor for device %i-%i: %s", bus, address, libusb_error_name(res));
+ return 0;
+ }
+
+ // Require both usbmux and one of the other interfaces to determine this is a valid configuration
+ for(j = 0 ; j < config->bNumInterfaces ; j++) {
+ const struct libusb_interface_descriptor *intf = &config->interface[j].altsetting[0];
+ if(intf->bInterfaceClass == INTERFACE_CLASS &&
+ intf->bInterfaceSubClass == 42 &&
+ intf->bInterfaceProtocol == 255) {
+ has_valeria = 1;
+ }
+ // https://github.com/torvalds/linux/blob/72a85e2b0a1e1e6fb4ee51ae902730212b2de25c/include/uapi/linux/usb/cdc.h#L22
+ // 2 for Communication class, 0xd for CDC NCM subclass
+ if(intf->bInterfaceClass == 2 &&
+ intf->bInterfaceSubClass == 0xd) {
+ has_cdc_ncm = 1;
+ }
+ if(intf->bInterfaceClass == INTERFACE_CLASS &&
+ intf->bInterfaceSubClass == INTERFACE_SUBCLASS &&
+ intf->bInterfaceProtocol == INTERFACE_PROTOCOL) {
+ has_usbmux = 1;
+ }
+ }
+
+ libusb_free_config_descriptor(config);
+
+ if(has_valeria && has_usbmux) {
+ usbmuxd_log(LL_NOTICE, "Found Valeria and Apple USB Multiplexor in device %i-%i configuration 5", bus, address);
+ return 2;
+ }
+
+ if(has_cdc_ncm && has_usbmux) {
+ usbmuxd_log(LL_NOTICE, "Found CDC-NCM and Apple USB Multiplexor in device %i-%i configuration 5", bus, address);
+ return 3;
+ }
+
+ return 0;
+}
+
+/// @brief Finds and sets the valid configuration, interface and endpoints on the usb_device
+static int set_valid_configuration(struct libusb_device* dev, struct usb_device *usbdev, struct libusb_device_handle *handle)
+{
+ int j, k, res, found = 0;
+ struct libusb_config_descriptor *config;
+ const struct libusb_interface_descriptor *intf;
+ struct libusb_device_descriptor devdesc = usbdev->devdesc;
+ int bus = usbdev->bus;
+ int address = usbdev->address;
+ int current_config = 0;
+
+ if((res = libusb_get_configuration(handle, &current_config)) != 0) {
+ usbmuxd_log(LL_WARNING, "Could not get current configuration for device %d-%d: %s", bus, address, libusb_error_name(res));
+ return -1;
+ }
+
+ for(j = devdesc.bNumConfigurations ; j > 0 ; j--) {
+ if((res = libusb_get_config_descriptor_by_value(dev, j, &config)) != 0) {
+ usbmuxd_log(LL_NOTICE, "Could not get configuration %i descriptor for device %i-%i: %s", j, bus, address, libusb_error_name(res));
+ continue;
+ }
+ for(k = 0 ; k < config->bNumInterfaces ; k++) {
+ intf = &config->interface[k].altsetting[0];
+ if(intf->bInterfaceClass == INTERFACE_CLASS ||
+ intf->bInterfaceSubClass == INTERFACE_SUBCLASS ||
+ intf->bInterfaceProtocol == INTERFACE_PROTOCOL) {
+ usbmuxd_log(LL_NOTICE, "Found usbmux interface for device %i-%i: %i", bus, address, intf->bInterfaceNumber);
+ if(intf->bNumEndpoints != 2) {
+ usbmuxd_log(LL_WARNING, "Endpoint count mismatch for interface %i of device %i-%i", intf->bInterfaceNumber, bus, address);
+ continue;
+ }
+ if((intf->endpoint[0].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_OUT &&
+ (intf->endpoint[1].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN) {
+ usbdev->interface = intf->bInterfaceNumber;
+ usbdev->ep_out = intf->endpoint[0].bEndpointAddress;
+ usbdev->ep_in = intf->endpoint[1].bEndpointAddress;
+ usbmuxd_log(LL_INFO, "Found interface %i with endpoints %02x/%02x for device %i-%i", usbdev->interface, usbdev->ep_out, usbdev->ep_in, bus, address);
+ found = 1;
+ break;
+ } else if((intf->endpoint[1].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_OUT &&
+ (intf->endpoint[0].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN) {
+ usbdev->interface = intf->bInterfaceNumber;
+ usbdev->ep_out = intf->endpoint[1].bEndpointAddress;
+ usbdev->ep_in = intf->endpoint[0].bEndpointAddress;
+ usbmuxd_log(LL_INFO, "Found interface %i with swapped endpoints %02x/%02x for device %i-%i", usbdev->interface, usbdev->ep_out, usbdev->ep_in, bus, address);
+ found = 1;
+ break;
+ } else {
+ usbmuxd_log(LL_WARNING, "Endpoint type mismatch for interface %i of device %i-%i", intf->bInterfaceNumber, bus, address);
+ }
+ }
+ }
+ if(!found) {
+ libusb_free_config_descriptor(config);
+ continue;
+ }
+ // If set configuration is required, try to first detach all kernel drivers
+ if (current_config == 0) {
+ usbmuxd_log(LL_DEBUG, "Device %d-%d is unconfigured", bus, address);
+ }
+ if(current_config == 0 || config->bConfigurationValue != current_config) {
+ usbmuxd_log(LL_NOTICE, "Changing configuration of device %i-%i: %i -> %i", bus, address, current_config, config->bConfigurationValue);
+ for(k=0 ; k < config->bNumInterfaces ; k++) {
+ const struct libusb_interface_descriptor *intf1 = &config->interface[k].altsetting[0];
+ if((res = libusb_kernel_driver_active(handle, intf1->bInterfaceNumber)) < 0) {
+ usbmuxd_log(LL_NOTICE, "Could not check kernel ownership of interface %d for device %d-%d: %s", intf1->bInterfaceNumber, bus, address, libusb_error_name(res));
+ continue;
+ }
+ if(res == 1) {
+ usbmuxd_log(LL_INFO, "Detaching kernel driver for device %d-%d, interface %d", bus, address, intf1->bInterfaceNumber);
+ if((res = libusb_detach_kernel_driver(handle, intf1->bInterfaceNumber)) < 0) {
+ usbmuxd_log(LL_WARNING, "Could not detach kernel driver, configuration change will probably fail! %s", libusb_error_name(res));
+ continue;
+ }
+ }
+ }
+ if((res = libusb_set_configuration(handle, j)) != 0) {
+ usbmuxd_log(LL_WARNING, "Could not set configuration %d for device %d-%d: %s", j, bus, address, libusb_error_name(res));
+ libusb_free_config_descriptor(config);
+ continue;
+ }
+ }
+
+ libusb_free_config_descriptor(config);
+ break;
+ }
+
+ if(!found) {
+ usbmuxd_log(LL_WARNING, "Could not find a suitable USB interface for device %i-%i", bus, address);
+ return -1;
+ }
+
+ return 0;
+}
+
+static void device_complete_initialization(struct mode_context *context, struct libusb_device_handle *handle)
+{
+ struct usb_device *usbdev = find_device(context->bus, context->address);
+ if(!usbdev) {
+ usbmuxd_log(LL_ERROR, "Device %d-%d is missing from device list, aborting initialization", context->bus, context->address);
+ return;
+ }
+ struct libusb_device *dev = context->dev;
+ struct libusb_device_descriptor devdesc = usbdev->devdesc;
+ int bus = context->bus;
+ int address = context->address;
+ int res;
+ struct libusb_transfer *transfer;
+
+ if((res = set_valid_configuration(dev, usbdev, handle)) != 0) {
+ usbdev->alive = 0;
+ return;
+ }
+
+ if((res = libusb_claim_interface(handle, usbdev->interface)) != 0) {
+ usbmuxd_log(LL_WARNING, "Could not claim interface %d for device %d-%d: %s", usbdev->interface, bus, address, libusb_error_name(res));
+ usbdev->alive = 0;
+ return;
+ }
+
+ transfer = libusb_alloc_transfer(0);
+ if(!transfer) {
+ usbmuxd_log(LL_WARNING, "Failed to allocate transfer for device %d-%d: %s", bus, address, libusb_error_name(res));
+ usbdev->alive = 0;
+ return;
+ }
+
+ unsigned char *transfer_buffer = malloc(1024 + LIBUSB_CONTROL_SETUP_SIZE + 8);
+ if (!transfer_buffer) {
+ usbmuxd_log(LL_WARNING, "Failed to allocate transfer buffer for device %d-%d: %s", bus, address, libusb_error_name(res));
+ usbdev->alive = 0;
+ return;
+ }
+ memset(transfer_buffer, '\0', 1024 + LIBUSB_CONTROL_SETUP_SIZE + 8);
+
+ usbdev->serial[0] = 0;
+ usbdev->bus = bus;
+ usbdev->address = address;
+ usbdev->devdesc = devdesc;
+ usbdev->speed = 480000000;
+ usbdev->handle = handle;
+ usbdev->alive = 1;
+ usbdev->wMaxPacketSize = libusb_get_max_packet_size(dev, usbdev->ep_out);
+ if (usbdev->wMaxPacketSize <= 0) {
+ usbmuxd_log(LL_ERROR, "Could not determine wMaxPacketSize for device %d-%d, setting to 64", usbdev->bus, usbdev->address);
+ usbdev->wMaxPacketSize = 64;
+ } else {
+ usbmuxd_log(LL_INFO, "Using wMaxPacketSize=%d for device %d-%d", usbdev->wMaxPacketSize, usbdev->bus, usbdev->address);
+ }
+
+ switch (libusb_get_device_speed(dev)) {
+ case LIBUSB_SPEED_LOW:
+ usbdev->speed = 1500000;
+ break;
+ case LIBUSB_SPEED_FULL:
+ usbdev->speed = 12000000;
+ break;
+ case LIBUSB_SPEED_SUPER:
+ usbdev->speed = 5000000000;
+ break;
+ case LIBUSB_SPEED_HIGH:
+ case LIBUSB_SPEED_UNKNOWN:
+ default:
+ usbdev->speed = 480000000;
+ break;
+ }
+
+ usbmuxd_log(LL_INFO, "USB Speed is %g MBit/s for device %d-%d", (double)(usbdev->speed / 1000000.0), usbdev->bus, usbdev->address);
+
+ /**
+ * From libusb:
+ * Asking for the zero'th index is special - it returns a string
+ * descriptor that contains all the language IDs supported by the
+ * device.
+ **/
+ libusb_fill_control_setup(transfer_buffer, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR, LIBUSB_DT_STRING << 8, 0, 1024 + LIBUSB_CONTROL_SETUP_SIZE);
+ libusb_fill_control_transfer(transfer, handle, transfer_buffer, get_langid_callback, usbdev, 1000);
+
+ if((res = libusb_submit_transfer(transfer)) < 0) {
+ usbmuxd_log(LL_ERROR, "Could not request transfer for device %d-%d: %s", usbdev->bus, usbdev->address, libusb_error_name(res));
+ libusb_free_transfer(transfer);
+ free(transfer_buffer);
+ usbdev->alive = 0;
+ return;
+ }
+}
+
+static void switch_mode_cb(struct libusb_transfer* transfer)
+{
+ // For old devices not supporting mode swtich, if anything goes wrong - continue in current mode
+ struct mode_context* context = transfer->user_data;
+ struct usb_device *dev = find_device(context->bus, context->address);
+ if(!dev) {
+ usbmuxd_log(LL_WARNING, "Device %d-%d is missing from device list", context->bus, context->address);
+ }
+ if(transfer->status != LIBUSB_TRANSFER_COMPLETED) {
+ usbmuxd_log(LL_ERROR, "Failed to request mode switch for device %i-%i (%i). Completing initialization in current mode",
+ context->bus, context->address, transfer->status);
+ device_complete_initialization(context, transfer->dev_handle);
+ }
+ else {
+ unsigned char *data = libusb_control_transfer_get_data(transfer);
+ if(data[0] != 0) {
+ usbmuxd_log(LL_INFO, "Received unexpected response for device %i-%i mode switch (%i). Completing initialization in current mode",
+ context->bus, context->address, data[0]);
+ device_complete_initialization(context, transfer->dev_handle);
+ }
+ }
+ free(context);
+ if(transfer->buffer)
+ free(transfer->buffer);
+}
+
+static void get_mode_cb(struct libusb_transfer* transfer)
+{
+ // For old devices not supporting mode swtich, if anything goes wrong - continue in current mode
+ int res;
+ struct mode_context* context = transfer->user_data;
+ struct usb_device *dev = find_device(context->bus, context->address);
+ if(!dev) {
+ usbmuxd_log(LL_ERROR, "Device %d-%d is missing from device list, aborting mode switch", context->bus, context->address);
+ free(context);
+ return;
+ }
+
+ if(transfer->status != LIBUSB_TRANSFER_COMPLETED) {
+ usbmuxd_log(LL_ERROR, "Failed to request get mode for device %i-%i (%i). Completing initialization in current mode",
+ context->bus, context->address, transfer->status);
+ device_complete_initialization(context, transfer->dev_handle);
+ free(context);
+ return;
+ }
+
+ unsigned char *data = libusb_control_transfer_get_data(transfer);
+
+ char* desired_mode_char = getenv(ENV_DEVICE_MODE);
+ int desired_mode = desired_mode_char ? atoi(desired_mode_char) : 3;
+ int guessed_mode = guess_mode(context->dev, dev);
+
+ // Response is 3:3:3:0 for initial mode, 5:3:3:0 otherwise.
+ usbmuxd_log(LL_INFO, "Received response %i:%i:%i:%i for get_mode request for device %i-%i", data[0], data[1], data[2], data[3], context->bus, context->address);
+ if(desired_mode >= 1 && desired_mode <= 3 &&
+ guessed_mode > 0 && // do not switch mode if guess failed
+ guessed_mode != desired_mode) {
+ usbmuxd_log(LL_WARNING, "Switching device %i-%i mode to %i", context->bus, context->address, desired_mode);
+
+ context->bRequest = APPLE_VEND_SPECIFIC_SET_MODE;
+ context->wValue = 0;
+ context->wIndex = desired_mode;
+ context->wLength = 1;
+
+ if((res = submit_vendor_specific(transfer->dev_handle, context, switch_mode_cb)) != 0) {
+ usbmuxd_log(LL_WARNING, "Could not request to switch mode %i for device %i-%i (%i)", context->wIndex, context->bus, context->address, res);
+ dev->alive = 0;
+ free(context);
+ }
+ }
+ else {
+ usbmuxd_log(LL_WARNING, "Skipping switch device %i-%i mode from %i to %i", context->bus, context->address, guessed_mode, desired_mode);
+ device_complete_initialization(context, transfer->dev_handle);
+ free(context);
+ }
+ if(transfer->buffer)
+ free(transfer->buffer);
+}
+
+static int usb_device_add(libusb_device* dev)
+{
+ int res;
+ // the following are non-blocking operations on the device list
+ uint8_t bus = libusb_get_bus_number(dev);
+ uint8_t address = libusb_get_device_address(dev);
+ struct libusb_device_descriptor devdesc;
+ struct usb_device *usbdev = find_device(bus, address);
+ if(usbdev) {
+ usbdev->alive = 1;
+ return 0; //device already found
+ }
+
+ if((res = libusb_get_device_descriptor(dev, &devdesc)) != 0) {
+ usbmuxd_log(LL_WARNING, "Could not get device descriptor for device %d-%d: %s", bus, address, libusb_error_name(res));
+ return -1;
+ }
+ if(devdesc.idVendor != VID_APPLE)
+ return -1;
+ if((devdesc.idProduct != PID_APPLE_T2_COPROCESSOR) &&
+ ((devdesc.idProduct < PID_APPLE_SILICON_RESTORE_LOW) ||
+ (devdesc.idProduct > PID_APPLE_SILICON_RESTORE_MAX)) &&
+ ((devdesc.idProduct < PID_RANGE_LOW) ||
+ (devdesc.idProduct > PID_RANGE_MAX)))
+ return -1;
+ libusb_device_handle *handle;
+ usbmuxd_log(LL_INFO, "Found new device with v/p %04x:%04x at %d-%d", devdesc.idVendor, devdesc.idProduct, bus, address);
+ // No blocking operation can follow: it may be run in the libusb hotplug callback and libusb will refuse any
+ // blocking call
+ if((res = libusb_open(dev, &handle)) != 0) {
+ usbmuxd_log(LL_WARNING, "Could not open device %d-%d: %s", bus, address, libusb_error_name(res));
+ return -1;
+ }
+
+ // Add the created handle to the device list, so we can close it in case of failure/disconnection
+ usbdev = malloc(sizeof(struct usb_device));
+ memset(usbdev, 0, sizeof(*usbdev));
+
+ usbdev->serial[0] = 0;
+ usbdev->bus = bus;
+ usbdev->address = address;
+ usbdev->devdesc = devdesc;
+ usbdev->speed = 0;
+ usbdev->handle = handle;
+ usbdev->alive = 1;
+
+ collection_init(&usbdev->tx_xfers);
+ collection_init(&usbdev->rx_xfers);
+
+ collection_add(&device_list, usbdev);
+
+ // On top of configurations, Apple have multiple "modes" for devices, namely:
+ // 1: An "initial" mode with 4 configurations
+ // 2: "Valeria" mode, where configuration 5 is included with interface for H.265 video capture (activated when recording screen with QuickTime in macOS)
+ // 3: "CDC NCM" mode, where configuration 5 is included with interface for Ethernet/USB (activated using internet-sharing feature in macOS)
+ // Request current mode asynchroniously, so it can be changed in callback if needed
+ usbmuxd_log(LL_INFO, "Requesting current mode from device %i-%i", bus, address);
+ struct mode_context* context = malloc(sizeof(struct mode_context));
+ context->dev = dev;
+ context->bus = bus;
+ context->address = address;
+ context->bRequest = APPLE_VEND_SPECIFIC_GET_MODE;
+ context->wValue = 0;
+ context->wIndex = 0;
+ context->wLength = 4;
+ context->timeout = 1000;
+
+ if(submit_vendor_specific(handle, context, get_mode_cb) != 0) {
+ usbmuxd_log(LL_WARNING, "Could not request current mode from device %d-%d", bus, address);
+ // Schedule device for close and cleanup
+ usbdev->alive = 0;
+ return -1;
+ }
+ return 0;
+}
+
+int usb_discover(void)
+{
+ int cnt, i;
+ int valid_count = 0;
+ libusb_device **devs;
+
+ cnt = libusb_get_device_list(NULL, &devs);
+ if(cnt < 0) {
+ usbmuxd_log(LL_WARNING, "Could not get device list: %d", cnt);
+ devlist_failures++;
+ // sometimes libusb fails getting the device list if you've just removed something
+ if(devlist_failures > 5) {
+ usbmuxd_log(LL_FATAL, "Too many errors getting device list");
+ return cnt;
+ } else {
+ get_tick_count(&next_dev_poll_time);
+ next_dev_poll_time.tv_usec += DEVICE_POLL_TIME * 1000;
+ next_dev_poll_time.tv_sec += next_dev_poll_time.tv_usec / 1000000;
+ next_dev_poll_time.tv_usec = next_dev_poll_time.tv_usec % 1000000;
+ return 0;
+ }
+ }
+ devlist_failures = 0;
+
+ usbmuxd_log(LL_SPEW, "usb_discover: scanning %d devices", cnt);
+
+ // Mark all devices as dead, and do a mark-sweep like
+ // collection of dead devices
+ FOREACH(struct usb_device *usbdev, &device_list) {
+ usbdev->alive = 0;
+ } ENDFOREACH
+
+ // Enumerate all USB devices and mark the ones we already know
+ // about as live, again
+ for(i=0; i<cnt; i++) {
+ libusb_device *dev = devs[i];
+ if (usb_device_add(dev) < 0) {
+ continue;
+ }
+ valid_count++;
+ }
+
+ // Clean out any device we didn't mark back as live
+ reap_dead_devices();
+
+ libusb_free_device_list(devs, 1);
+
+ get_tick_count(&next_dev_poll_time);
+ next_dev_poll_time.tv_usec += DEVICE_POLL_TIME * 1000;
+ next_dev_poll_time.tv_sec += next_dev_poll_time.tv_usec / 1000000;
+ next_dev_poll_time.tv_usec = next_dev_poll_time.tv_usec % 1000000;
+
+ return valid_count;
+}
+
+const char *usb_get_serial(struct usb_device *dev)
+{
+ if(!dev->handle) {
+ return NULL;
+ }
+ return dev->serial;
+}
+
+uint32_t usb_get_location(struct usb_device *dev)
+{
+ if(!dev->handle) {
+ return 0;
+ }
+ return (dev->bus << 16) | dev->address;
+}
+
+uint16_t usb_get_pid(struct usb_device *dev)
+{
+ if(!dev->handle) {
+ return 0;
+ }
+ return dev->devdesc.idProduct;
+}
+
+uint64_t usb_get_speed(struct usb_device *dev)
+{
+ if (!dev->handle) {
+ return 0;
+ }
+ return dev->speed;
+}
+
+void usb_get_fds(struct fdlist *list)
+{
+ const struct libusb_pollfd **usbfds;
+ const struct libusb_pollfd **p;
+ usbfds = libusb_get_pollfds(NULL);
+ if(!usbfds) {
+ usbmuxd_log(LL_ERROR, "libusb_get_pollfds failed");
+ return;
+ }
+ p = usbfds;
+ while(*p) {
+ fdlist_add(list, FD_USB, (*p)->fd, (*p)->events);
+ p++;
+ }
+ free(usbfds);
+}
+
+void usb_autodiscover(int enable)
+{
+ usbmuxd_log(LL_DEBUG, "usb polling enable: %d", enable);
+ device_polling = enable;
+ device_hotplug = enable;
+}
+
+static int dev_poll_remain_ms(void)
+{
+ int msecs;
+ struct timeval tv;
+ if(!device_polling)
+ return 100000; // devices will never be polled if this is > 0
+ get_tick_count(&tv);
+ msecs = (next_dev_poll_time.tv_sec - tv.tv_sec) * 1000;
+ msecs += (next_dev_poll_time.tv_usec - tv.tv_usec) / 1000;
+ if(msecs < 0)
+ return 0;
+ return msecs;
+}
+
+int usb_get_timeout(void)
+{
+ struct timeval tv;
+ int msec;
+ int res;
+ int pollrem;
+ pollrem = dev_poll_remain_ms();
+ res = libusb_get_next_timeout(NULL, &tv);
+ if(res == 0)
+ return pollrem;
+ if(res < 0) {
+ usbmuxd_log(LL_ERROR, "libusb_get_next_timeout failed: %s", libusb_error_name(res));
+ return pollrem;
+ }
+ msec = tv.tv_sec * 1000;
+ msec += tv.tv_usec / 1000;
+ if(msec > pollrem)
+ return pollrem;
+ return msec;
+}
+
+int usb_process(void)
+{
+ int res;
+ struct timeval tv;
+ tv.tv_sec = tv.tv_usec = 0;
+ res = libusb_handle_events_timeout(NULL, &tv);
+ if(res < 0) {
+ usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %s", libusb_error_name(res));
+ return res;
+ }
+
+ // reap devices marked dead due to an RX error
+ reap_dead_devices();
+
+ if(dev_poll_remain_ms() <= 0) {
+ res = usb_discover();
+ if(res < 0) {
+ usbmuxd_log(LL_ERROR, "usb_discover failed: %s", libusb_error_name(res));
+ return res;
+ }
+ }
+ return 0;
+}
+
+int usb_process_timeout(int msec)
+{
+ int res;
+ struct timeval tleft, tcur, tfin;
+ get_tick_count(&tcur);
+ tfin.tv_sec = tcur.tv_sec + (msec / 1000);
+ tfin.tv_usec = tcur.tv_usec + (msec % 1000) * 1000;
+ tfin.tv_sec += tfin.tv_usec / 1000000;
+ tfin.tv_usec %= 1000000;
+ while((tfin.tv_sec > tcur.tv_sec) || ((tfin.tv_sec == tcur.tv_sec) && (tfin.tv_usec > tcur.tv_usec))) {
+ tleft.tv_sec = tfin.tv_sec - tcur.tv_sec;
+ tleft.tv_usec = tfin.tv_usec - tcur.tv_usec;
+ if(tleft.tv_usec < 0) {
+ tleft.tv_usec += 1000000;
+ tleft.tv_sec -= 1;
+ }
+ res = libusb_handle_events_timeout(NULL, &tleft);
+ if(res < 0) {
+ usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %s", libusb_error_name(res));
+ return res;
+ }
+ // reap devices marked dead due to an RX error
+ reap_dead_devices();
+ get_tick_count(&tcur);
+ }
+ return 0;
+}
+
+#ifdef HAVE_LIBUSB_HOTPLUG_API
+static libusb_hotplug_callback_handle usb_hotplug_cb_handle;
+
+static int usb_hotplug_cb(libusb_context *ctx, libusb_device *device, libusb_hotplug_event event, void *user_data)
+{
+ if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) {
+ if (device_hotplug) {
+ usb_device_add(device);
+ }
+ } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
+ uint8_t bus = libusb_get_bus_number(device);
+ uint8_t address = libusb_get_device_address(device);
+ FOREACH(struct usb_device *usbdev, &device_list) {
+ if(usbdev->bus == bus && usbdev->address == address) {
+ usbdev->alive = 0;
+ device_remove(usbdev);
+ break;
+ }
+ } ENDFOREACH
+ } else {
+ usbmuxd_log(LL_ERROR, "Unhandled event %d", event);
+ }
+ return 0;
+}
+#endif
+
+int usb_init(void)
+{
+ int res;
+ const struct libusb_version* libusb_version_info = libusb_get_version();
+ usbmuxd_log(LL_NOTICE, "Using libusb %d.%d.%d", libusb_version_info->major, libusb_version_info->minor, libusb_version_info->micro);
+
+ devlist_failures = 0;
+ device_polling = 1;
+ res = libusb_init(NULL);
+
+ if (res != 0) {
+ usbmuxd_log(LL_FATAL, "libusb_init failed: %s", libusb_error_name(res));
+ return -1;
+ }
+
+#if LIBUSB_API_VERSION >= 0x01000106
+ libusb_set_option(NULL, LIBUSB_OPTION_LOG_LEVEL, (log_level >= LL_DEBUG ? LIBUSB_LOG_LEVEL_DEBUG: (log_level >= LL_WARNING ? LIBUSB_LOG_LEVEL_WARNING: LIBUSB_LOG_LEVEL_NONE)));
+#else
+ libusb_set_debug(NULL, (log_level >= LL_DEBUG ? LIBUSB_LOG_LEVEL_DEBUG: (log_level >= LL_WARNING ? LIBUSB_LOG_LEVEL_WARNING: LIBUSB_LOG_LEVEL_NONE)));
+#endif
+
+ collection_init(&device_list);
+
+#ifdef HAVE_LIBUSB_HOTPLUG_API
+ if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
+ usbmuxd_log(LL_INFO, "Registering for libusb hotplug events");
+ res = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, LIBUSB_HOTPLUG_ENUMERATE, VID_APPLE, LIBUSB_HOTPLUG_MATCH_ANY, 0, usb_hotplug_cb, NULL, &usb_hotplug_cb_handle);
+ if (res == LIBUSB_SUCCESS) {
+ device_polling = 0;
+ } else {
+ usbmuxd_log(LL_ERROR, "ERROR: Could not register for libusb hotplug events. %s", libusb_error_name(res));
+ }
+ } else {
+ usbmuxd_log(LL_ERROR, "libusb does not support hotplug events");
+ }
+#endif
+ if (device_polling) {
+ res = usb_discover();
+ if (res >= 0) {
+ }
+ } else {
+ res = collection_count(&device_list);
+ }
+ return res;
+}
+
+void usb_shutdown(void)
+{
+ usbmuxd_log(LL_DEBUG, "usb_shutdown");
+
+#ifdef HAVE_LIBUSB_HOTPLUG_API
+ libusb_hotplug_deregister_callback(NULL, usb_hotplug_cb_handle);
+#endif
+
+ FOREACH(struct usb_device *usbdev, &device_list) {
+ device_remove(usbdev);
+ usb_disconnect(usbdev);
+ } ENDFOREACH
+ collection_free(&device_list);
+ libusb_exit(NULL);
+}
diff --git a/src/usb.h b/src/usb.h
new file mode 100644
index 0000000..4e44cce
--- /dev/null
+++ b/src/usb.h
@@ -0,0 +1,73 @@
+/*
+ * usb.h
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ * Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+#ifndef USB_H
+#define USB_H
+
+#include <stdint.h>
+#include "utils.h"
+
+#define INTERFACE_CLASS 255
+#define INTERFACE_SUBCLASS 254
+#define INTERFACE_PROTOCOL 2
+
+// libusb fragments packets larger than this (usbfs limitation)
+// on input, this creates race conditions and other issues
+#define USB_MRU 16384
+
+// max transmission packet size
+// libusb fragments these too, but doesn't send ZLPs so we're safe
+// but we need to send a ZLP ourselves at the end (see usb-linux.c)
+// we're using 3 * 16384 to optimize for the fragmentation
+// this results in three URBs per full transfer, 32 USB packets each
+// if there are ZLP issues this should make them show up easily too
+#define USB_MTU (3 * 16384)
+
+#define USB_PACKET_SIZE 512
+
+#define VID_APPLE 0x5ac
+#define PID_RANGE_LOW 0x1290
+#define PID_RANGE_MAX 0x12af
+#define PID_APPLE_T2_COPROCESSOR 0x8600
+#define PID_APPLE_SILICON_RESTORE_LOW 0x1901
+#define PID_APPLE_SILICON_RESTORE_MAX 0x1905
+
+#define ENV_DEVICE_MODE "USBMUXD_DEFAULT_DEVICE_MODE"
+#define APPLE_VEND_SPECIFIC_GET_MODE 0x45
+#define APPLE_VEND_SPECIFIC_SET_MODE 0x52
+
+struct usb_device;
+
+int usb_init(void);
+void usb_shutdown(void);
+const char *usb_get_serial(struct usb_device *dev);
+uint32_t usb_get_location(struct usb_device *dev);
+uint16_t usb_get_pid(struct usb_device *dev);
+uint64_t usb_get_speed(struct usb_device *dev);
+void usb_get_fds(struct fdlist *list);
+int usb_get_timeout(void);
+int usb_send(struct usb_device *dev, const unsigned char *buf, int length);
+int usb_discover(void);
+void usb_autodiscover(int enable);
+int usb_process(void);
+int usb_process_timeout(int msec);
+
+#endif
diff --git a/libusbmuxd/usbmuxd-proto.h b/src/usbmuxd-proto.h
index be9e709..93df00e 100644
--- a/libusbmuxd/usbmuxd-proto.h
+++ b/src/usbmuxd-proto.h
@@ -1,29 +1,27 @@
/*
- libusbmuxd - client library to talk to usbmuxd
-
-Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
-
-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 General Public License for more details.
-
-You should have received a copy of the GNU Lesser 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
-
-*/
-
-/* Protocol defintion for usbmuxd proxy protocol */
-#ifndef __USBMUXD_PROTO_H
-#define __USBMUXD_PROTO_H
+ * usbmuxd-proto.h
+ *
+ * Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 or version 3.
+ *
+ * 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
+ */
+
+/* Protocol definition for usbmuxd proxy protocol */
+#ifndef USBMUXD_PROTO_H
+#define USBMUXD_PROTO_H
#include <stdint.h>
#define USBMUXD_PROTOCOL_VERSION 0
@@ -54,7 +52,7 @@ enum usbmuxd_msgtype {
MESSAGE_LISTEN = 3,
MESSAGE_DEVICE_ADD = 4,
MESSAGE_DEVICE_REMOVE = 5,
- //???
+ MESSAGE_DEVICE_PAIRED = 6,
//???
MESSAGE_PLIST = 8,
};
@@ -94,4 +92,4 @@ struct usbmuxd_device_record {
}
#endif
-#endif /* __USBMUXD_PROTO_H */
+#endif /* USBMUXD_PROTO_H */
diff --git a/src/utils.c b/src/utils.c
new file mode 100644
index 0000000..2cc5675
--- /dev/null
+++ b/src/utils.c
@@ -0,0 +1,131 @@
+/*
+ * utils.c
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ * Copyright (c) 2013 Federico Mena Quintero
+ *
+ * This library is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 2.1 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser 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 <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <time.h>
+#include <sys/time.h>
+#include <errno.h>
+#ifdef __APPLE__
+#include <mach/mach_time.h>
+#endif
+
+#include "utils.h"
+
+#include "log.h"
+#define util_error(...) usbmuxd_log(LL_ERROR, __VA_ARGS__)
+
+void fdlist_create(struct fdlist *list)
+{
+ list->count = 0;
+ list->capacity = 4;
+ list->owners = malloc(sizeof(*list->owners) * list->capacity);
+ list->fds = malloc(sizeof(*list->fds) * list->capacity);
+}
+void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events)
+{
+ if(list->count == list->capacity) {
+ list->capacity *= 2;
+ list->owners = realloc(list->owners, sizeof(*list->owners) * list->capacity);
+ list->fds = realloc(list->fds, sizeof(*list->fds) * list->capacity);
+ }
+ list->owners[list->count] = owner;
+ list->fds[list->count].fd = fd;
+ list->fds[list->count].events = events;
+ list->fds[list->count].revents = 0;
+ list->count++;
+}
+
+void fdlist_free(struct fdlist *list)
+{
+ list->count = 0;
+ list->capacity = 0;
+ free(list->owners);
+ list->owners = NULL;
+ free(list->fds);
+ list->fds = NULL;
+}
+
+void fdlist_reset(struct fdlist *list)
+{
+ list->count = 0;
+}
+
+#ifndef HAVE_CLOCK_GETTIME
+typedef int clockid_t;
+#define CLOCK_MONOTONIC 1
+
+static int clock_gettime(clockid_t clk_id, struct timespec *ts)
+{
+ // See http://developer.apple.com/library/mac/qa/qa1398
+
+ uint64_t mach_time, nano_sec;
+
+ static mach_timebase_info_data_t base_info;
+
+ mach_time = mach_absolute_time();
+
+ if (base_info.denom == 0) {
+ (void) mach_timebase_info(&base_info);
+ }
+
+ if (base_info.numer == 1 && base_info.denom == 1)
+ nano_sec = mach_time;
+ else
+ nano_sec = mach_time * base_info.numer / base_info.denom;
+
+ ts->tv_sec = nano_sec / 1000000000;
+ ts->tv_nsec = nano_sec % 1000000000;
+
+ return 0;
+}
+#endif
+
+void get_tick_count(struct timeval * tv)
+{
+ struct timespec ts;
+ if(0 == clock_gettime(CLOCK_MONOTONIC, &ts)) {
+ tv->tv_sec = ts.tv_sec;
+ tv->tv_usec = ts.tv_nsec / 1000;
+ } else {
+ gettimeofday(tv, NULL);
+ }
+}
+
+/**
+ * Get number of milliseconds since the epoch.
+ */
+uint64_t mstime64(void)
+{
+ struct timeval tv;
+ get_tick_count(&tv);
+
+ // Careful, avoid overflow on 32 bit systems
+ // time_t could be 4 bytes
+ return ((long long)tv.tv_sec) * 1000LL + ((long long)tv.tv_usec) / 1000LL;
+}
diff --git a/src/utils.h b/src/utils.h
new file mode 100644
index 0000000..ce3b2e0
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,49 @@
+/*
+ * utils.h
+ *
+ * Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
+ * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
+ *
+ * This library is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 2.1 of the
+ * License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser 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
+ */
+
+#ifndef UTILS_H
+#define UTILS_H
+
+#include <poll.h>
+#include <plist/plist.h>
+
+enum fdowner {
+ FD_LISTEN,
+ FD_CLIENT,
+ FD_USB
+};
+
+struct fdlist {
+ int count;
+ int capacity;
+ enum fdowner *owners;
+ struct pollfd *fds;
+};
+
+void fdlist_create(struct fdlist *list);
+void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events);
+void fdlist_free(struct fdlist *list);
+void fdlist_reset(struct fdlist *list);
+
+uint64_t mstime64(void);
+void get_tick_count(struct timeval * tv);
+
+#endif
diff --git a/stuff/README b/stuff/README
deleted file mode 100644
index 290285d..0000000
--- a/stuff/README
+++ /dev/null
@@ -1,25 +0,0 @@
-*** NOTE:
-*** Doing this is mostly obsolete. The preferred method to sync music to an
-*** iPhone now is to use ifuse or some other afc-based client, which does not
-*** require jailbreaking or adding this service. Please take a look at the
-*** libiphone, ifuse, and libgpod projects.
-
-com.openssh.sft.plist is a launchd configuration to set up a bare SFTP server
-on TCP port 2299 localhost-only for USB use. It's nice for relatively fast music
-syncing and file transfer under Linux (and it avoids encryption). Con: it gives
-anyone with usb access root FS access on the phone, as well as anything running
-on the phone itself.
-
-Use it with a command like this:
-
-IPATH=/var/mobile/Media
-MOUNTPOINT=$HOME/media/iphone
-$ sshfs localhost:$IPATH $MOUNTPOINT -o workaround=rename -o directport=2299 \
- -o kernel_cache -o entry_timeout=30 -o attr_timeout=30
-
-Make sure you run tcprelay.py:
-$ python tcprelay.py -t 2299
-
-Remember that to bypass the stupid new iTunesDB hash you need to edit
-/System/Library/Lockdown/Checkpoint.xml and change DBVersion to 2.
-
diff --git a/stuff/com.openssh.sftp.plist b/stuff/com.openssh.sftp.plist
deleted file mode 100644
index 569fabc..0000000
--- a/stuff/com.openssh.sftp.plist
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-
-<dict>
- <key>Label</key>
- <string>com.openssh.sftpd</string>
-
- <key>Program</key>
- <string>/usr/libexec/sftp-server</string>
-
- <key>ProgramArguments</key>
- <array>
- <string>/usr/libexec/sftp-server</string>
- </array>
-
- <key>SessionCreate</key>
- <true/>
-
- <key>Sockets</key>
- <dict>
- <key>Listeners</key>
- <dict>
- <key>SockServiceName</key>
- <string>2299</string>
- <key>SockNodeName</key>
- <string>127.0.0.1</string>
- </dict>
- </dict>
-
- <key>StandardErrorPath</key>
- <string>/dev/null</string>
-
- <key>inetdCompatibility</key>
- <dict>
- <key>Wait</key>
- <false/>
- </dict>
-</dict>
-
-</plist>
diff --git a/systemd/Makefile.am b/systemd/Makefile.am
new file mode 100644
index 0000000..1d40c25
--- /dev/null
+++ b/systemd/Makefile.am
@@ -0,0 +1,21 @@
+edit = \
+ $(SED) -r \
+ -e 's|@sbindir[@]|$(sbindir)|g' \
+ -e 's|@runstatedir[@]|$(runstatedir)|g' \
+ < $< > $@ || rm $@
+
+if WANT_SYSTEMD
+
+systemdsystemunit_DATA = \
+ usbmuxd.service
+
+usbmuxd.service: usbmuxd.service.in
+ $(edit)
+
+EXTRA_DIST = \
+ usbmuxd.service.in
+
+CLEANFILES = \
+ usbmuxd.service
+
+endif
diff --git a/systemd/usbmuxd.service.in b/systemd/usbmuxd.service.in
new file mode 100644
index 0000000..3a27aee
--- /dev/null
+++ b/systemd/usbmuxd.service.in
@@ -0,0 +1,7 @@
+[Unit]
+Description=Socket daemon for the usbmux protocol used by Apple devices
+Documentation=man:usbmuxd(8)
+
+[Service]
+ExecStart=@sbindir@/usbmuxd --user usbmux --systemd
+PIDFile=@runstatedir@/usbmuxd.pid
diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt
deleted file mode 100644
index 64d0d0e..0000000
--- a/tools/CMakeLists.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-include_directories (${CMAKE_SOURCE_DIR}/libusbmuxd)
-link_directories (${CMAKE_BINARY_DIR}/libusbmuxd)
-
-add_executable(iproxy iproxy.c)
-if(WIN32)
- target_link_libraries(iproxy libusbmuxd pthread ws2_32)
-else()
- target_link_libraries(iproxy libusbmuxd pthread)
-endif()
-
-install(TARGETS iproxy RUNTIME DESTINATION bin)
diff --git a/tools/iproxy.c b/tools/iproxy.c
deleted file mode 100644
index 4469c48..0000000
--- a/tools/iproxy.c
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- iproxy -- proxy that enables tcp service access to iPhone/iPod
-
-Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
-Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
-
-Based upon iTunnel source code, Copyright (c) 2008 Jing Su.
-http://www.cs.toronto.edu/~jingsu/itunnel/
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-
-TODO: improve code...
-
-*/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <fcntl.h>
-#include <stddef.h>
-#include <unistd.h>
-#include <errno.h>
-#ifdef WIN32
-#include <windows.h>
-#include <winsock2.h>
-typedef unsigned int socklen_t;
-#else
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <arpa/inet.h>
-#endif
-#include <pthread.h>
-#include <netinet/in.h>
-#include "sock_stuff.h"
-#include "usbmuxd.h"
-
-static uint16_t listen_port = 0;
-static uint16_t device_port = 0;
-
-struct client_data {
- int fd;
- int sfd;
- volatile int stop_ctos;
- volatile int stop_stoc;
-};
-
-void *run_stoc_loop(void *arg)
-{
- struct client_data *cdata = (struct client_data*)arg;
- int recv_len;
- int sent;
- char buffer[131072];
-
- printf("%s: fd = %d\n", __func__, cdata->fd);
-
- while (!cdata->stop_stoc && cdata->fd>0 && cdata->sfd>0) {
- recv_len = recv_buf_timeout(cdata->sfd, buffer, sizeof(buffer), 0, 5000);
- if (recv_len <= 0) {
- if (recv_len == 0) {
- // try again
- continue;
- } else {
- fprintf(stderr, "recv failed: %s\n", strerror(errno));
- break;
- }
- } else {
-// printf("received %d bytes from server\n", recv_len);
- // send to socket
- sent = send_buf(cdata->fd, buffer, recv_len);
- if (sent < recv_len) {
- if (sent <= 0) {
- fprintf(stderr, "send failed: %s\n", strerror(errno));
- break;
- } else {
- fprintf(stderr, "only sent %d from %d bytes\n", sent, recv_len);
- }
- } else {
- // sending succeeded, receive from device
-// printf("pushed %d bytes to client\n", sent);
- }
- }
- }
- close(cdata->fd);
- cdata->fd = -1;
- cdata->stop_ctos = 1;
-
- return NULL;
-}
-
-void *run_ctos_loop(void *arg)
-{
- struct client_data *cdata = (struct client_data*)arg;
- int recv_len;
- int sent;
- char buffer[131072];
- pthread_t stoc;
-
- printf("%s: fd = %d\n", __func__, cdata->fd);
-
- cdata->stop_stoc = 0;
- pthread_create(&stoc, NULL, run_stoc_loop, cdata);
-
- while (!cdata->stop_ctos && cdata->fd>0 && cdata->sfd>0) {
- recv_len = recv_buf_timeout(cdata->fd, buffer, sizeof(buffer), 0, 5000);
- if (recv_len <= 0) {
- if (recv_len == 0) {
- // try again
- continue;
- } else {
- fprintf(stderr, "recv failed: %s\n", strerror(errno));
- break;
- }
- } else {
-// printf("pulled %d bytes from client\n", recv_len);
- // send to local socket
- sent = send_buf(cdata->sfd, buffer, recv_len);
- if (sent < recv_len) {
- if (sent <= 0) {
- fprintf(stderr, "send failed: %s\n", strerror(errno));
- break;
- } else {
- fprintf(stderr, "only sent %d from %d bytes\n", sent, recv_len);
- }
- } else {
- // sending succeeded, receive from device
-// printf("sent %d bytes to server\n", sent);
- }
- }
- }
- close(cdata->fd);
- cdata->fd = -1;
- cdata->stop_stoc = 1;
-
- pthread_join(stoc, NULL);
-
- return NULL;
-}
-
-void *acceptor_thread(void *arg)
-{
- struct client_data *cdata;
- usbmuxd_device_info_t *dev_list = NULL;
- pthread_t ctos;
- int count;
-
- if (!arg) {
- fprintf(stderr, "invalid client_data provided!\n");
- return NULL;
- }
-
- cdata = (struct client_data*)arg;
-
- if ((count = usbmuxd_get_device_list(&dev_list)) < 0) {
- printf("Connecting to usbmuxd failed, terminating.\n");
- free(dev_list);
- return NULL;
- }
-
- fprintf(stdout, "Number of available devices == %d\n", count);
-
- if (dev_list == NULL || dev_list[0].handle == 0) {
- printf("No connected device found, terminating.\n");
- free(dev_list);
- return NULL;
- }
-
- fprintf(stdout, "Requesting connecion to device handle == %d (serial: %s), port %d\n", dev_list[0].handle, dev_list[0].uuid, device_port);
-
- cdata->sfd = usbmuxd_connect(dev_list[0].handle, device_port);
- free(dev_list);
- if (cdata->sfd < 0) {
- fprintf(stderr, "Error connecting to device!\n");
- } else {
- cdata->stop_ctos = 0;
- pthread_create(&ctos, NULL, run_ctos_loop, cdata);
- pthread_join(ctos, NULL);
- }
-
- if (cdata->fd > 0) {
- close(cdata->fd);
- }
- if (cdata->sfd > 0) {
- close(cdata->sfd);
- }
-
- return NULL;
-}
-
-int main(int argc, char **argv)
-{
- int mysock = -1;
-
- if (argc != 3) {
- printf("usage: %s LOCAL_TCP_PORT DEVICE_TCP_PORT\n", argv[0]);
- return 0;
- }
-
- listen_port = atoi(argv[1]);
- device_port = atoi(argv[2]);
-
- if (!listen_port) {
- fprintf(stderr, "Invalid listen_port specified!\n");
- return -EINVAL;
- }
-
- if (!device_port) {
- fprintf(stderr, "Invalid device_port specified!\n");
- return -EINVAL;
- }
-
- // first create the listening socket endpoint waiting for connections.
- mysock = create_socket(listen_port);
- if (mysock < 0) {
- fprintf(stderr, "Error creating socket: %s\n", strerror(errno));
- return -errno;
- } else {
- pthread_t acceptor;
- struct sockaddr_in c_addr;
- socklen_t len = sizeof(struct sockaddr_in);
- struct client_data cdata;
- int c_sock;
- while (1) {
- printf("waiting for connection\n");
- c_sock = accept(mysock, (struct sockaddr*)&c_addr, &len);
- if (c_sock) {
- printf("accepted connection, fd = %d\n", c_sock);
- cdata.fd = c_sock;
- pthread_create(&acceptor, NULL, acceptor_thread, &cdata);
- pthread_join(acceptor, NULL);
- } else {
- break;
- }
- }
- close(c_sock);
- close(mysock);
- }
-
- return 0;
-}
diff --git a/udev/39-usbmuxd.rules.in b/udev/39-usbmuxd.rules.in
new file mode 100644
index 0000000..ac15593
--- /dev/null
+++ b/udev/39-usbmuxd.rules.in
@@ -0,0 +1,16 @@
+# usbmuxd (Apple Mobile Device Muxer listening on /var/run/usbmuxd)
+
+# systemd should receive all events relating to device
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*|5ac/190[1-5]/*|5ac/8600/*", TAG+="systemd"
+
+# Initialize iOS devices into "deactivated" USB configuration state and activate usbmuxd
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*|5ac/190[1-5]/*", ACTION=="add", ENV{USBMUX_SUPPORTED}="1", ATTR{bConfigurationValue}="0", OWNER="usbmux", @udev_activation_rule@
+# but make sure iBridge (T1) doesn't end up in an unconfigured state
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/8600/*", ACTION=="add", ENV{USBMUX_SUPPORTED}="1", ATTR{bConfigurationValue}="1", OWNER="usbmux", @udev_activation_rule@
+
+
+# Make sure properties don't get lost when bind action is called
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*|5ac/190[1-5]/*|5ac/8600/*", ACTION=="bind", ENV{USBMUX_SUPPORTED}="1", OWNER="usbmux"
+
+# Exit usbmuxd when the last device is removed
+SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*|5ac/190[1-5]/*|5ac/8600/*", ACTION=="remove", RUN+="@sbindir@/usbmuxd -x"
diff --git a/udev/85-usbmuxd.rules.in b/udev/85-usbmuxd.rules.in
deleted file mode 100644
index 3856c79..0000000
--- a/udev/85-usbmuxd.rules.in
+++ /dev/null
@@ -1,7 +0,0 @@
-# usbmuxd (iPhone "Apple Mobile Device" MUXer listening on /var/run/usbmuxd)
-
-# Forces iPhone 1.0, 3G, 3GS, iPodTouch 1/2 and iPad to USB configuration 3 and run usbmuxd
-ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="05ac", ATTR{idProduct}=="129[0-9a-f]", ENV{USBMUX_SUPPORTED}="1", ATTR{bConfigurationValue}!="$attr{bNumConfigurations}", ATTR{bConfigurationValue}="$attr{bNumConfigurations}", RUN+="@CMAKE_INSTALL_PREFIX@/sbin/usbmuxd -u -U usbmux"
-
-# Exit usbmuxd when the last device is removed
-ACTION=="remove", SUBSYSTEM=="usb", ENV{PRODUCT}=="5ac/129[0-9a-f]/*", ENV{INTERFACE}=="255/*", RUN+="@CMAKE_INSTALL_PREFIX@/sbin/usbmuxd -x"
diff --git a/udev/CMakeLists.txt b/udev/CMakeLists.txt
deleted file mode 100644
index 0f7042d..0000000
--- a/udev/CMakeLists.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/85-usbmuxd.rules.in ${CMAKE_CURRENT_BINARY_DIR}/85-usbmuxd.rules @ONLY)
-install(FILES ${CMAKE_CURRENT_BINARY_DIR}/85-usbmuxd.rules DESTINATION /lib/udev/rules.d/)
diff --git a/udev/Makefile.am b/udev/Makefile.am
new file mode 100644
index 0000000..95f565d
--- /dev/null
+++ b/udev/Makefile.am
@@ -0,0 +1,20 @@
+edit = \
+ $(SED) -r \
+ -e 's|@udev_activation_rule[@]|$(udev_activation_rule)|g' \
+ -e 's|@sbindir[@]|$(sbindir)|g' \
+ < $< > $@ || rm $@
+
+udevrules_DATA = \
+ 39-usbmuxd.rules
+
+39-usbmuxd.rules: 39-usbmuxd.rules.in
+ $(edit)
+
+EXTRA_DIST = \
+ 39-usbmuxd.rules.in
+
+MAINTAINERCLEANFILES = \
+ 39-usbmuxd.rules
+
+CLEANFILES = \
+ 39-usbmuxd.rules