diff options
Diffstat (limited to 'usbmuxd')
-rw-r--r-- | usbmuxd/.gitignore | 3 | ||||
-rw-r--r-- | usbmuxd/CMakeLists.txt | 16 | ||||
-rw-r--r-- | usbmuxd/COPYING | 674 | ||||
-rw-r--r-- | usbmuxd/FindUSB.cmake | 68 | ||||
-rw-r--r-- | usbmuxd/Modules/FindUSB.cmake | 31 | ||||
-rw-r--r-- | usbmuxd/Modules/LibFindMacros.cmake | 99 | ||||
-rw-r--r-- | usbmuxd/client.c | 430 | ||||
-rw-r--r-- | usbmuxd/client.h | 92 | ||||
-rw-r--r-- | usbmuxd/device.c | 731 | ||||
-rw-r--r-- | usbmuxd/device.h | 52 | ||||
-rw-r--r-- | usbmuxd/log.c | 58 | ||||
-rw-r--r-- | usbmuxd/log.h | 40 | ||||
-rw-r--r-- | usbmuxd/main.c | 201 | ||||
-rw-r--r-- | usbmuxd/usb-linux.c | 501 | ||||
-rw-r--r-- | usbmuxd/usb.h | 67 | ||||
-rw-r--r-- | usbmuxd/utils.c | 110 | ||||
-rw-r--r-- | usbmuxd/utils.h | 65 |
17 files changed, 3238 insertions, 0 deletions
diff --git a/usbmuxd/.gitignore b/usbmuxd/.gitignore new file mode 100644 index 0000000..0784410 --- /dev/null +++ b/usbmuxd/.gitignore @@ -0,0 +1,3 @@ +*~ +build + diff --git a/usbmuxd/CMakeLists.txt b/usbmuxd/CMakeLists.txt new file mode 100644 index 0000000..8d22ef6 --- /dev/null +++ b/usbmuxd/CMakeLists.txt @@ -0,0 +1,16 @@ +PROJECT(usbmuxd) + +cmake_minimum_required(VERSION 2.6) + +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/Modules/") + +find_package(USB REQUIRED) +include_directories(${USB_INCLUDE_DIRS}) +set(LIBS ${LIBS} ${USB_LIBRARIES}) + +#set(CMAKE_VERBOSE_MAKEFILE ON) + +add_definitions(-Wall -O2 -g) +add_executable(usbmuxd main.c usb-linux.c log.c utils.c device.c client.c) +target_link_libraries(usbmuxd ${LIBS}) + diff --git a/usbmuxd/COPYING b/usbmuxd/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/usbmuxd/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/usbmuxd/FindUSB.cmake b/usbmuxd/FindUSB.cmake new file mode 100644 index 0000000..e81d51e --- /dev/null +++ b/usbmuxd/FindUSB.cmake @@ -0,0 +1,68 @@ +# - Try to find USB +# Once done this will define +# +# USB_FOUND - system has USB +# USB_INCLUDE_DIRS - the USB include directory +# USB_LIBRARIES - Link these to use USB +# USB_DEFINITIONS - Compiler switches required for using USB +# +# Copyright (c) 2006 Andreas Schneider <mail@cynapses.org> +# Copyright (c) 2008 Andreas Schneider <mail@cynapses.org> +# +# Redistribution and use is allowed according to the terms of the New +# BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. +# + + +if (USB_LIBRARIES AND USB_INCLUDE_DIRS) + # in cache already + set(USB_FOUND TRUE) +else (USB_LIBRARIES AND USB_INCLUDE_DIRS) + find_path(USB_INCLUDE_DIR + NAMES + usb.h + PATHS + /usr/include + /usr/local/include + /opt/local/include + /sw/include + ) + + find_library(USB_LIBRARY + NAMES + usb + PATHS + /usr/lib + /usr/local/lib + /opt/local/lib + /sw/lib + ) + + set(USB_INCLUDE_DIRS + ${USB_INCLUDE_DIR} + ) + set(USB_LIBRARIES + ${USB_LIBRARY} +) + + if (USB_INCLUDE_DIRS AND USB_LIBRARIES) + set(USB_FOUND TRUE) + endif (USB_INCLUDE_DIRS AND USB_LIBRARIES) + + if (USB_FOUND) + if (NOT USB_FIND_QUIETLY) + message(STATUS "Found USB: ${USB_LIBRARIES}") + endif (NOT USB_FIND_QUIETLY) + else (USB_FOUND) + if (USB_FIND_REQUIRED) + message(FATAL_ERROR "Could not find USB") + endif (USB_FIND_REQUIRED) + endif (USB_FOUND) + + # show the USB_INCLUDE_DIRS and USB_LIBRARIES variables only in the advanced view + mark_as_advanced(USB_INCLUDE_DIRS USB_LIBRARIES) + +endif (USB_LIBRARIES AND USB_INCLUDE_DIRS) + + diff --git a/usbmuxd/Modules/FindUSB.cmake b/usbmuxd/Modules/FindUSB.cmake new file mode 100644 index 0000000..d562b98 --- /dev/null +++ b/usbmuxd/Modules/FindUSB.cmake @@ -0,0 +1,31 @@ +# - 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 + +# Use pkg-config to get hints about paths +libfind_pkg_check_modules(USB_PKGCONF libusb-1.0) + +# 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-1.0 + 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/usbmuxd/Modules/LibFindMacros.cmake b/usbmuxd/Modules/LibFindMacros.cmake new file mode 100644 index 0000000..795d6b7 --- /dev/null +++ b/usbmuxd/Modules/LibFindMacros.cmake @@ -0,0 +1,99 @@ +# 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/usbmuxd/client.c b/usbmuxd/client.c new file mode 100644 index 0000000..b33d892 --- /dev/null +++ b/usbmuxd/client.c @@ -0,0 +1,430 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdlib.h> +#include <errno.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <arpa/inet.h> + +#include "log.h" +#include "usb.h" +#include "client.h" +#include "device.h" + +#define CMD_BUF_SIZE 256 +#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; + int ob_size; + int ob_capacity; + unsigned char *ib_buf; + int ib_size; + int ib_capacity; + short events, devents; + uint32_t connect_tag; + int connect_device; + enum client_state state; +}; + +static struct collection client_list; + +int client_read(struct mux_client *client, void *buffer, int 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, int 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 client_msgtype msg, void *payload, int payload_length) +{ + struct client_header hdr; + hdr.version = CLIENT_PROTOCOL_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) +{ + return send_pkt(client, tag, MESSAGE_RESULT, &result, sizeof(uint32_t)); +} + +int client_notify_connect(struct mux_client *client, enum client_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(struct mux_client *client, struct device_info *dev) +{ + struct client_msg_dev dmsg; + memset(&dmsg, 0, sizeof(dmsg)); + dmsg.device_id = dev->id; + strncpy(dmsg.device_serial, dev->serial, 256); + dmsg.device_serial[255] = 0; + dmsg.location = dev->location; + dmsg.device_pid = dev->pid; + return send_pkt(client, 0, MESSAGE_DEVICE_ADD, &dmsg, sizeof(dmsg)); +} + +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 client_msg_dev) + sizeof(struct client_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(client, dev++) < 0) { + free(devs); + return -1; + } + } + free(devs); + return count; +} + +static int client_command(struct mux_client *client, struct client_header *hdr, const char *payload) +{ + 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 client_msg_connect *ch; + switch(hdr->message) { + 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*)payload; + 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 client_header)) { + res = recv(client->fd, client->ib_buf + client->ib_size, sizeof(struct client_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 client_header)) + return; + did_read = 1; + } + struct client_header *hdr = (void*)client->ib_buf; + if(hdr->version != CLIENT_PROTOCOL_VERSION) { + usbmuxd_log(LL_INFO, "Client %d version mismatch: expected %d, got %d", client->fd, CLIENT_PROTOCOL_VERSION, hdr->version); + client_close(client); + } + 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); + } + if(hdr->length < sizeof(struct client_header)) { + usbmuxd_log(LL_ERROR, "Client %d message is too short (%d bytes)", client->fd, hdr->length); + client_close(client); + } + 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, (char *)(hdr+1)); + 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_ERROR, "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(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) + send_pkt(client, 0, MESSAGE_DEVICE_REMOVE, &id, sizeof(uint32_t)); + } 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/usbmuxd/client.h b/usbmuxd/client.h new file mode 100644 index 0000000..0cda676 --- /dev/null +++ b/usbmuxd/client.h @@ -0,0 +1,92 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#ifndef __CLIENT_H__ +#define __CLIENT_H__ + +#include <stdint.h> + +struct device_info; +struct mux_client; + +enum client_result { + RESULT_OK = 0, + RESULT_BADCOMMAND = 1, + RESULT_BADDEV = 2, + RESULT_CONNREFUSED = 3, + // ??? + // ??? + RESULT_BADVERSION = 6, +}; + +enum client_msgtype { + MESSAGE_RESULT = 1, + MESSAGE_CONNECT = 2, + MESSAGE_LISTEN = 3, + MESSAGE_DEVICE_ADD = 4, + MESSAGE_DEVICE_REMOVE = 5, + //??? + //??? + //MESSAGE_PLIST = 8, +}; + +#define CLIENT_PROTOCOL_VERSION 0 + +struct client_header { + uint32_t length; + uint32_t version; + uint32_t message; + uint32_t tag; +}; + +struct client_msg_result { + uint32_t result; +}; + +struct client_msg_connect { + uint32_t device_id; + uint16_t port; +}; + +struct client_msg_dev { + uint32_t device_id; + uint16_t device_pid; + char device_serial[256]; + uint16_t padding; + uint32_t location; +}; + +int client_read(struct mux_client *client, void *buffer, int len); +int client_write(struct mux_client *client, void *buffer, int 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 client_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/usbmuxd/device.c b/usbmuxd/device.c new file mode 100644 index 0000000..c6ef75b --- /dev/null +++ b/usbmuxd/device.c @@ -0,0 +1,731 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#define _BSD_SOURCE + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <sys/time.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <stdlib.h> +#include <string.h> +#include <stdint.h> +#include <inttypes.h> +#include "device.h" +#include "client.h" +#include "usb.h" +#include "log.h" + +int next_device_id; + +#define DEV_PKTBUF_SIZE 65536 + +#define CONN_INBUF_SIZE 262144 +#define CONN_OUTBUF_SIZE 65536 + +#define ACK_TIMEOUT 60 + +enum mux_protocol { + MUX_PROTO_VERSION = 0, + MUX_PROTO_TCP = IPPROTO_TCP, +}; + +enum mux_dev_state { + MUXDEV_INIT, // sent version packet + MUXDEV_ACTIVE, // received version packet, active + MUXDEV_DEAD // dead +}; + +enum mux_conn_state { + CONN_CONNECTING, // SYN + CONN_CONNECTED, // SYN/SYNACK/ACK -> active + CONN_REFUSED, // RST received during SYN + CONN_DYING, // RST received + CONN_DEAD // being freed; used to prevent infinite recursion between client<->device freeing +}; + +struct mux_header +{ + uint32_t protocol; + uint32_t length; +}; + +struct version_header +{ + uint32_t major; + uint32_t minor; + uint32_t padding; +}; + +struct mux_device; + +#define CONN_ACK_PENDING 1 + +struct mux_connection +{ + struct mux_device *dev; + struct mux_client *client; + enum mux_conn_state state; + uint16_t sport, dport; + uint32_t tx_seq, tx_ack, tx_acked, tx_win; + uint32_t rx_seq, rx_recvd, rx_ack, rx_win; + int max_payload; + int sendable; + int flags; + unsigned char *ib_buf; + int ib_size; + int ib_capacity; + unsigned char *ob_buf; + int ob_capacity; + short events; + uint64_t last_ack_time; +}; + +struct mux_device +{ + struct usb_device *usbdev; + int id; + enum mux_dev_state state; + struct collection connections; + uint16_t next_sport; + unsigned char *pktbuf; + int pktlen; +}; + +static struct collection device_list; + +uint64_t mstime64(void) +{ + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * 1000 + tv.tv_usec / 1000; +} + +static int get_next_device_id(void) +{ + while(1) { + int ok = 1; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == next_device_id) { + next_device_id++; + ok = 0; + break; + } + } ENDFOREACH + if(ok) + return next_device_id++; + } +} + +static int send_packet(struct mux_device *dev, enum mux_protocol proto, void *header, const void *data, int length) +{ + unsigned char *buffer; + int hdrlen; + int res; + + switch(proto) { + case MUX_PROTO_VERSION: + hdrlen = sizeof(struct version_header); + break; + case MUX_PROTO_TCP: + hdrlen = sizeof(struct tcphdr); + break; + default: + usbmuxd_log(LL_ERROR, "Invalid protocol %d for outgoing packet (dev %d hdr %p data %p len %d)", proto, dev->id, header, data, length); + return -1; + } + 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; + + 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); + return -1; + } + + buffer = malloc(total); + 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(data && length) + memcpy(buffer + sizeof(struct mux_header) + 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); + free(buffer); + return res; + } + return total; +} + +static uint16_t find_sport(struct mux_device *dev) +{ + if(collection_count(&dev->connections) >= 65535) + return 0; //insanity + + while(1) { + int ok = 1; + FOREACH(struct mux_connection *conn, &dev->connections) { + if(dev->next_sport == conn->sport) { + dev->next_sport++; + ok = 0; + break; + } + } ENDFOREACH + if(ok) + return dev->next_sport++; + } +} + +static int send_tcp(struct mux_connection *conn, uint8_t flags, const unsigned char *data, int length) +{ + struct tcphdr th; + memset(&th, 0, sizeof(th)); + th.th_sport = htons(conn->sport); + th.th_dport = htons(conn->dport); + th.th_seq = htonl(conn->tx_seq); + th.th_ack = htonl(conn->tx_ack); + th.th_flags = flags; + th.th_off = sizeof(th) / 4; + th.th_win = htons(conn->tx_win >> 8); + + usbmuxd_log(LL_DEBUG, "[OUT] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d", + conn->dev->id, conn->sport, conn->dport, conn->tx_seq, conn->tx_ack, flags, conn->tx_win, conn->tx_win >> 8, length); + + int res = send_packet(conn->dev, MUX_PROTO_TCP, &th, data, length); + if(res >= 0) { + conn->tx_acked = conn->tx_ack; + conn->last_ack_time = mstime64(); + conn->flags &= ~CONN_ACK_PENDING; + } + return res; +} + +static void connection_teardown(struct mux_connection *conn) +{ + int res; + 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); + if(conn->dev->state != MUXDEV_DEAD && conn->state != CONN_DYING && conn->state != CONN_REFUSED) { + res = send_tcp(conn, TH_RST, NULL, 0); + if(res < 0) + usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", conn->dev->id, conn->sport, conn->dport); + } + if(conn->client) { + if(conn->state == CONN_REFUSED || conn->state == CONN_CONNECTING) { + client_notify_connect(conn->client, RESULT_CONNREFUSED); + } else { + conn->state = CONN_DEAD; + client_close(conn->client); + } + } + if(conn->ib_buf) + free(conn->ib_buf); + if(conn->ob_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 + if(!dev) { + usbmuxd_log(LL_WARNING, "Attempted to connect to nonexistent device %d", device_id); + return -RESULT_BADDEV; + } + + uint16_t sport = find_sport(dev); + if(!sport) { + usbmuxd_log(LL_WARNING, "Unable to allocate port for device %d", device_id); + return -RESULT_BADDEV; + } + + struct mux_connection *conn; + conn = malloc(sizeof(struct mux_connection)); + memset(conn, 0, sizeof(struct mux_connection)); + + conn->dev = dev; + conn->client = client; + conn->state = CONN_CONNECTING; + conn->sport = sport; + conn->dport = dport; + conn->tx_seq = 0; + conn->tx_ack = 0; + conn->tx_acked = 0; + conn->tx_win = 131072; + conn->rx_recvd = 0; + conn->flags = 0; + conn->max_payload = USB_MTU - sizeof(struct mux_header) - sizeof(struct tcphdr); + + conn->ob_buf = malloc(CONN_OUTBUF_SIZE); + conn->ob_capacity = CONN_OUTBUF_SIZE; + conn->ib_buf = malloc(CONN_INBUF_SIZE); + conn->ib_capacity = CONN_INBUF_SIZE; + conn->ib_size = 0; + + int res; + + 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); + return -RESULT_CONNREFUSED; //bleh + } + collection_add(&dev->connections, conn); + return 0; +} + +static void update_connection(struct mux_connection *conn) +{ + conn->sendable = conn->rx_win - (conn->tx_seq - conn->rx_ack); + + if(conn->sendable > conn->ob_capacity) + conn->sendable = conn->ob_capacity; + if(conn->sendable > conn->max_payload) + conn->sendable = conn->max_payload; + + if(conn->sendable > 0) + conn->events |= POLLIN; + else + conn->events &= ~POLLIN; + + if(conn->ib_size) + conn->events |= POLLOUT; + else + conn->events &= ~POLLOUT; + + if(conn->tx_acked != conn->tx_ack) + conn->flags |= CONN_ACK_PENDING; + else + conn->flags &= ~CONN_ACK_PENDING; + + usbmuxd_log(LL_SPEW, "update_connection: sendable %d, events %d, flags %d", conn->sendable, conn->events, conn->flags); + client_set_events(conn->client, conn->events); +} + +void device_client_process(int device_id, struct mux_client *client, short events) +{ + 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(!conn) { + usbmuxd_log(LL_WARNING, "Could not find connection for device %d client %p", device_id, client); + return; + } + usbmuxd_log(LL_SPEW, "device_client_process (%d)", events); + + int res; + int size; + if(events & POLLOUT) { + size = client_write(conn->client, conn->ib_buf, conn->ib_size); + if(size <= 0) { + usbmuxd_log(LL_DEBUG, "error writing to client (%d)", size); + connection_teardown(conn); + return; + } + conn->tx_ack += size; + if(size == 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) { + size = client_read(conn->client, conn->ob_buf, conn->sendable); + if(size <= 0) { + usbmuxd_log(LL_DEBUG, "error reading from client (%d)", size); + connection_teardown(conn); + return; + } + res = send_tcp(conn, TH_ACK, conn->ob_buf, size); + if(res < 0) { + connection_teardown(conn); + return; + } + conn->tx_seq += size; + } + + update_connection(conn); +} + +static void connection_device_input(struct mux_connection *conn, unsigned char *payload, int payload_length) +{ + if((conn->ib_size + payload_length) > conn->ib_capacity) { + usbmuxd_log(LL_ERROR, "Input buffer overflow on device %d connection %d->%d (space=%d, payload=%d)", conn->dev->id, conn->sport, conn->dport, conn->ib_capacity-conn->ib_size, payload_length); + connection_teardown(conn); + return; + } + memcpy(conn->ib_buf + conn->ib_size, payload, payload_length); + conn->ib_size += payload_length; + conn->rx_recvd += payload_length; + update_connection(conn); +} + +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); +} + +static void device_version_input(struct mux_device *dev, struct version_header *vh) +{ + if(dev->state != MUXDEV_INIT) { + usbmuxd_log(LL_WARNING, "Version packet from already initialized device %d", dev->id); + return; + } + 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); + collection_remove(&device_list, dev); + 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->state = MUXDEV_ACTIVE; + collection_init(&dev->connections); + struct device_info info; + info.id = dev->id; + 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); +} + +static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned char *payload, int payload_length) +{ + usbmuxd_log(LL_DEBUG, "[IN] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d", + dev->id, ntohs(th->th_sport), ntohs(th->th_dport), ntohl(th->th_seq), ntohl(th->th_ack), th->th_flags, ntohs(th->th_win) << 8, ntohs(th->th_win), payload_length); + + uint16_t sport = ntohs(th->th_dport); + uint16_t dport = ntohs(th->th_sport); + struct mux_connection *conn = NULL; + FOREACH(struct mux_connection *lconn, &dev->connections) { + if(lconn->sport == sport && lconn->dport == dport) { + conn = lconn; + break; + } + } ENDFOREACH + + if(!conn) { + usbmuxd_log(LL_WARNING, "No connection for device %d incoming packet %d->%d", dev->id, dport, sport); + return; + } + + conn->rx_seq = ntohl(th->th_seq); + conn->rx_ack = ntohl(th->th_ack); + conn->rx_win = ntohs(th->th_win) << 8; + + if(th->th_flags & TH_RST) { + char *buf = malloc(payload_length+1); + memcpy(buf, payload, payload_length); + if(payload_length && (buf[payload_length-1] == '\n')) + buf[payload_length-1] = 0; + buf[payload_length] = 0; + usbmuxd_log(LL_DEBUG, "RST reason: %s", buf); + free(buf); + } + + if(conn->state == CONN_CONNECTING) { + if(th->th_flags != (TH_SYN|TH_ACK)) { + if(th->th_flags & TH_RST) + conn->state = CONN_REFUSED; + usbmuxd_log(LL_INFO, "Connection refused by device %d (%d->%d)", dev->id, sport, dport); + connection_teardown(conn); //this also sends the notification to the client + } else { + conn->tx_seq++; + conn->tx_ack++; + conn->rx_recvd = conn->rx_seq; + if(send_tcp(conn, TH_ACK, NULL, 0) < 0) { + usbmuxd_log(LL_ERROR, "Error sending TCP ACK to device %d (%d->%d)", dev->id, sport, dport); + connection_teardown(conn); + return; + } + conn->state = CONN_CONNECTED; + if(client_notify_connect(conn->client, RESULT_OK) < 0) { + conn->client = NULL; + connection_teardown(conn); + } + update_connection(conn); + } + } else if(conn->state == CONN_CONNECTED) { + if(th->th_flags != TH_ACK) { + usbmuxd_log(LL_INFO, "Connection reset by device %d (%d->%d)", dev->id, sport, dport); + if(th->th_flags & TH_RST) + conn->state = CONN_DYING; + connection_teardown(conn); + } else { + connection_device_input(conn, payload, payload_length); + } + } +} + +void device_data_input(struct usb_device *usbdev, unsigned char *buffer, int length) +{ + struct mux_device *dev = NULL; + FOREACH(struct mux_device *tdev, &device_list) { + if(tdev->usbdev == usbdev) { + dev = tdev; + break; + } + } ENDFOREACH + 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; + } + + if(!length) + return; + + usbmuxd_log(LL_SPEW, "Mux data input for device %p: %p len %d", dev, buffer, length); + + // handle broken up transfers + if(dev->pktlen) { + memcpy(dev->pktbuf + dev->pktlen, buffer, length); + struct mux_header *mhdr = (struct mux_header *)dev->pktbuf; + if((length < USB_MRU) || (ntohl(mhdr->length) == length)) { + buffer = dev->pktbuf; + length += dev->pktlen; + dev->pktlen = 0; + usbmuxd_log(LL_SPEW, "Gathered mux data from buffer (total size: %d)", length); + } else { + dev->pktlen += length; + usbmuxd_log(LL_SPEW, "Appended mux data to buffer (total size: %d)", dev->pktlen); + return; + } + } else { + struct mux_header *mhdr = (struct mux_header *)buffer; + if((length == USB_MRU) && (length < ntohl(mhdr->length))) { + memcpy(dev->pktbuf, buffer, length); + dev->pktlen = length; + usbmuxd_log(LL_SPEW, "Copied mux data to buffer (size: %d)", dev->pktlen); + return; + } + } + + struct mux_header *mhdr = (struct mux_header *)buffer; + + 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; + } + + struct tcphdr *th; + unsigned char *payload; + int payload_length; + + switch(ntohl(mhdr->protocol)) { + case MUX_PROTO_VERSION: + device_version_input(dev, (struct version_header *)(mhdr+1)); + break; + case MUX_PROTO_TCP: + th = (struct tcphdr *)(mhdr+1); + 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); + break; + default: + usbmuxd_log(LL_ERROR, "Incoming packet for device %d has unknown protocol 0x%x)", dev->id, ntohl(mhdr->protocol)); + break; + } + +} + +int device_add(struct usb_device *usbdev) +{ + int res; + int id = get_next_device_id(); + struct mux_device *dev; + usbmuxd_log(LL_NOTICE, "Connecting to new device on location 0x%x as ID %d", usb_get_location(usbdev), id); + dev = malloc(sizeof(struct mux_device)); + dev->id = id; + dev->usbdev = usbdev; + dev->state = MUXDEV_INIT; + dev->next_sport = 1; + dev->pktbuf = malloc(DEV_PKTBUF_SIZE); + dev->pktlen = 0; + struct version_header vh; + vh.major = htonl(1); + 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\n", id); + free(dev); + return res; + } + collection_add(&device_list, dev); + return 0; +} + +void device_remove(struct usb_device *usbdev) +{ + 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)); + if(dev->state == MUXDEV_ACTIVE) { + dev->state = MUXDEV_DEAD; + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + client_device_remove(dev->id); + collection_free(&dev->connections); + } + collection_remove(&device_list, dev); + free(dev->pktbuf); + free(dev); + return; + } + } ENDFOREACH + 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) +{ + int count = 0; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) + count++; + } ENDFOREACH + return count; +} + +int device_get_list(struct device_info *p) +{ + int count = 0; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) { + 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); + count++; + p++; + } + } ENDFOREACH + return count; +} + +int device_get_timeout(void) +{ + uint64_t oldest = (uint64_t)-1; + 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) && conn->last_ack_time < oldest) + oldest = conn->last_ack_time; + } ENDFOREACH + } + } ENDFOREACH + uint64_t ct = mstime64(); + if(oldest == -1) + return 100000; //meh + if((ct - oldest) > ACK_TIMEOUT) + return 0; + return ACK_TIMEOUT - (ct - oldest); +} + +void device_check_timeouts(void) +{ + uint64_t ct = mstime64(); + 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) && + (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); + } + } + } ENDFOREACH + } + } ENDFOREACH +} + +void device_init(void) +{ + usbmuxd_log(LL_DEBUG, "device_init"); + collection_init(&device_list); + next_device_id = 1; +} + +void device_kill_connections(void) +{ + usbmuxd_log(LL_DEBUG, "device_kill_connections"); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state != MUXDEV_INIT) { + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + } + } ENDFOREACH + // give USB a while to send the final connection RSTs and the like + usb_process_timeout(100); +} + +void device_shutdown(void) +{ + usbmuxd_log(LL_DEBUG, "device_shutdown"); + FOREACH(struct mux_device *dev, &device_list) { + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + collection_free(&dev->connections); + collection_remove(&device_list, dev); + free(dev); + } ENDFOREACH + collection_free(&device_list); +} diff --git a/usbmuxd/device.h b/usbmuxd/device.h new file mode 100644 index 0000000..ce6c50b --- /dev/null +++ b/usbmuxd/device.h @@ -0,0 +1,52 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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, int 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/usbmuxd/log.c b/usbmuxd/log.c new file mode 100644 index 0000000..a70120b --- /dev/null +++ b/usbmuxd/log.c @@ -0,0 +1,58 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <stdarg.h> +#include <time.h> +#include <sys/time.h> + +#include "log.h" + +int log_level = LL_INFO; + +void usbmuxd_log(enum loglevel level, const char *fmt, ...) +{ + va_list ap; + char *fs; + struct timeval ts; + struct tm *tp; + + gettimeofday(&ts, NULL); + tp = localtime(&ts.tv_sec); + + if(level > log_level) + return; + + fs = malloc(20 + strlen(fmt)); + strftime(fs, 10, "[%H:%M:%S", tp); + sprintf(fs+9, ".%03d][%d] %s\n", (int)(ts.tv_usec / 1000), level, fmt); + + va_start(ap, fmt); + vfprintf(stderr, fs, ap); + va_end(ap); + + free(fs); +} diff --git a/usbmuxd/log.h b/usbmuxd/log.h new file mode 100644 index 0000000..f6eb5c1 --- /dev/null +++ b/usbmuxd/log.h @@ -0,0 +1,40 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 usbmuxd_log(enum loglevel level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); + + +#endif diff --git a/usbmuxd/main.c b/usbmuxd/main.c new file mode 100644 index 0000000..d39b416 --- /dev/null +++ b/usbmuxd/main.c @@ -0,0 +1,201 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#define _BSD_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 "log.h" +#include "usb.h" +#include "device.h" +#include "client.h" + +static const char *socket_path = "/tmp/usbmuxd"; //TODO: CHANGEME +int should_exit; + +struct sigaction sa_old; + +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; + } + + return listenfd; +} + +void handle_signal(int sig) +{ + if(sig == SIGINT) { + usbmuxd_log(LL_NOTICE,"Caught SIGINT"); + } else { + usbmuxd_log(LL_NOTICE,"Caught unknown signal %d", sig); + } + should_exit = 1; + sigaction(SIGINT, &sa_old, NULL); +} + +void set_signal_handlers(void) +{ + struct sigaction sa; + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_handler = handle_signal; + sigaction(SIGINT, &sa, &sa_old); +} + +int main_loop(int listenfd) +{ + int to, cnt, i, dto; + struct fdlist 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_create(&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); + + cnt = poll(pollfds.fds, pollfds.count, to); + usbmuxd_log(LL_FLOOD, "poll() returned %d", cnt); + + if(cnt == -1) { + if(errno == EINTR && should_exit) { + usbmuxd_log(LL_INFO, "event processing interrupted"); + fdlist_free(&pollfds); + return 0; + } + } 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; +} + +int main(int argc, char *argv[]) +{ + int listenfd; + int res; + + usbmuxd_log(LL_NOTICE, "usbmux v0.1 starting up"); + should_exit = 0; + + set_signal_handlers(); + + usbmuxd_log(LL_INFO, "Creating socket"); + listenfd = create_socket(); + if(listenfd < 0) + return 1; + + client_init(); + device_init(); + usbmuxd_log(LL_INFO, "Initializing USB"); + if((res = usb_init()) < 0) + return 2; + usbmuxd_log(LL_INFO, "%d device%s detected", res, (res==1)?"":"s"); + + usbmuxd_log(LL_NOTICE, "Initialization complete"); + + res = main_loop(listenfd); + if(res < 0) + usbmuxd_log(LL_FATAL, "main_loop failed"); + + usbmuxd_log(LL_NOTICE, "usbmux shutting down"); + device_kill_connections(); + usb_shutdown(); + device_shutdown(); + client_shutdown(); + usbmuxd_log(LL_NOTICE, "Shutdown complete"); + + if(res < 0) + return -res; + return 0; +} diff --git a/usbmuxd/usb-linux.c b/usbmuxd/usb-linux.c new file mode 100644 index 0000000..b401cde --- /dev/null +++ b/usbmuxd/usb-linux.c @@ -0,0 +1,501 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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; + struct libusb_transfer *rx_xfer; + struct collection tx_xfers; +}; + +static struct collection device_list; + +static struct timeval next_dev_poll_time; + +static int devlist_failures; + +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, USB_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_ERROR, "TX transfer cancelled for device %d-%d", 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, BULK_OUT, (void*)buf, length, tx_callback, dev, 0); + xfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK; + 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 % 512) == 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, BULK_OUT, buffer, 0, tx_callback, dev, 0); + xfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK; + 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_ERROR, "RX transfer cancelled for device %d-%d", 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, BULK_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; +} + +static int usb_discover(void) +{ + int cnt, i, 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_IPHONE2G) && + (devdesc.idProduct != PID_ITOUCH1G) && + (devdesc.idProduct != PID_IPHONE3G)) + 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; + } + if((res = libusb_set_configuration(handle, USB_CONFIGURATION)) != 0) { + usbmuxd_log(LL_WARNING, "Could not set configuration %d for device %d-%d: %d", USB_CONFIGURATION, bus, address, res); + libusb_close(handle); + continue; + } + if((res = libusb_claim_interface(handle, USB_INTERFACE)) != 0) { + usbmuxd_log(LL_WARNING, "Could not claim interface %d for device %d-%d: %d", USB_INTERFACE, bus, address, res); + libusb_close(handle); + continue; + } + struct usb_device *usbdev; + usbdev = malloc(sizeof(struct usb_device)); + + 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, USB_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; + 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); +} + +static int dev_poll_remain_ms(void) +{ + int msecs; + struct timeval tv; + 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; + 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/usbmuxd/usb.h b/usbmuxd/usb.h new file mode 100644 index 0000000..8a48308 --- /dev/null +++ b/usbmuxd/usb.h @@ -0,0 +1,67 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#ifndef __USB_H__ +#define __USB_H__ + +#include <stdint.h> +#include "utils.h" + +#define BULK_IN 0x85 +#define BULK_OUT 0x04 + +// libusb fragments packets larger than this (usbfs limitation) +// on input, this creates race conditions and other issues +// I don't think the device uses larger packets +// if it does then we're going to have to implement proper framing... +#define USB_MRU 16384 + +// max transmission packet size +// libusb fragments these too, but doesn't send ZLPs so we're safe +// but maybe we need to send a ZLP ourselves at the end (see usb-linux.h) +// 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 too +#define USB_MTU (3 * 16384) + +#define USB_PACKET_SIZE 512 + +#define VID_APPLE 0x5ac +#define PID_IPHONE2G 0x1290 +#define PID_ITOUCH1G 0x1291 +#define PID_IPHONE3G 0x1292 + +#define USB_CONFIGURATION 3 +#define USB_INTERFACE 1 + +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_process(void); +int usb_process_timeout(int msec); + +#endif diff --git a/usbmuxd/utils.c b/usbmuxd/utils.c new file mode 100644 index 0000000..1ffa04a --- /dev/null +++ b/usbmuxd/utils.c @@ -0,0 +1,110 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdlib.h> +#include <string.h> +#include "utils.h" +#include "log.h" + +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 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; + } + } + usbmuxd_log(LL_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/usbmuxd/utils.h b/usbmuxd/utils.h new file mode 100644 index 0000000..ad4ac9d --- /dev/null +++ b/usbmuxd/utils.h @@ -0,0 +1,65 @@ +/* + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +#ifndef __UTILS_H__ +#define __UTILS_H__ + +#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); + +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 |