pax_global_header00006660000000000000000000000064135623127710014521gustar00rootroot0000000000000052 comment=9af2b12552693a47601347e1eafc1e94132d727e usbmuxd-1.1.1~git20191130.9af2b12/000077500000000000000000000000001356231277100160005ustar00rootroot00000000000000usbmuxd-1.1.1~git20191130.9af2b12/AUTHORS000066400000000000000000000003201356231277100170430ustar00rootroot00000000000000Aaron Burghardt Bastien Nocera Cerrato Renaud Christophe Fergeau David Sansome Hector Martin Jacob Myers John Maguire Martin Szulecki Mikkel Kamstrup Erlandsen Nikias Bassen Paul Sladen Peter Wu Satoshi Ohgohusbmuxd-1.1.1~git20191130.9af2b12/COPYING.GPLv2000066400000000000000000000431041356231277100177260ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE 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. 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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This 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. usbmuxd-1.1.1~git20191130.9af2b12/COPYING.GPLv3000066400000000000000000001045131356231277100177310ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . usbmuxd-1.1.1~git20191130.9af2b12/Makefile.am000066400000000000000000000004611356231277100200350ustar00rootroot00000000000000AUTOMAKE_OPTIONS = foreign ACLOCAL_AMFLAGS = -I m4 SUBDIRS = src $(UDEV_SUB) $(SYSTEMD_SUB) docs EXTRA_DIST = docs COPYING.GPLv2 COPYING.GPLv3 DISTCHECK_CONFIGURE_FLAGS = \ --with-udevrulesdir=$$dc_install_base/$(udevrulesdir) \ --with-systemdsystemunitdir=$$dc_install_base/$(systemdsystemunitdir)usbmuxd-1.1.1~git20191130.9af2b12/NEWS000066400000000000000000000055261356231277100165070ustar00rootroot00000000000000Version 1.1.1 ~~~~~~~~~~~~~ * Changes: - Make use of libusb hotplug events for device discovery - Use clock_gettime() instead of gettimeofday() to avoid timing issues when calculating packet timeouts - Get correct USB device speed instead of hardcoded value - Use non-blocking sockets for client communication to avoid hanging - Use correct manual section (8) for manpage Version 1.1.0 ~~~~~~~~~~~~~ * Changes: - Check for pkg-config availability in autogen.sh - Fix missing "usbmuxd-proto.h" in released tarbal - Fix typo which broke udev support in rule for udev activation mode - Fix broken configure summary on OS X and change activation method to "manual" - Compile bits of udev and systemd support only if needed - Bump autoconf requirement to 2.64 Version 1.0.9 ~~~~~~~~~~~~~ * Changes: - Fix broken handling of "--user" argument value - Add new "--enable-exit" argument to enable handling of "--exit" requests - Add new "--disable-hotplug" argument to disable automatic device discovery - Add new "--systemd" argument to startup with right settings for systemd - Add man page for usbmuxd - Update copyright headers to match best practice - Flush input buffer on connection teardown - Add systemd based activation with fallback for udev and manual activation - Add initial NEWS file and update README with latest information - Rename header guards according to C++ standard - Implement support for usbmux protocol version 2 which improves stability - Fix crash when old libusbmuxd was used as a client - Add "--version" argument to print version number and exit - Update command line usage to match best practice and other tools - Massively improve read performance by using 3 parallel transfers - Bump requirement to libplist 1.11 - Remove trailing "\n" from usbmuxd_log() messages - Improve thread safety - Fix crash on 64bit systems in process_send() - Fix possible leak of file descriptors - Implement "ReadBUID", "ReadPairRecord", "SavePairRecord" and "DeletePairRecord" commands - Make plist based protocol support mandatory - Return proper error packet on client version mismatch - Implement "ListDevices" command - Manage pair records in a directory compatible to native usbmuxd - Output USB configuration changes in log - Set "deactivated" USB configuration on iOS device by default as usbmuxd will bring device to "life" on it's own now - Add udev rule installation with autotools - Lower udev rules numbering to make sure to start as early as possible - Split out client library into "libusbmuxd" and depend on "libimobiledevice" - Implement preflight worker to support iOS 7 based trust dialog handling - Install usbmuxd binary to sbindir instead of bindir - Switch from CMake to autotools build system This is the first release after the usbmuxd/libusbmuxd project split. usbmuxd-1.1.1~git20191130.9af2b12/README.md000066400000000000000000000051211356231277100172560ustar00rootroot00000000000000# usbmuxd ## About A socket daemon to multiplex connections from and to iOS devices. ## Background usbmuxd stands for "USB multiplexing daemon". This daemon is in charge of multiplexing connections over USB to an iOS device. To users, it means you can sync your music, contacts, photos, etc. over USB. To developers, it means you can connect to any listening localhost socket on the device. usbmuxd is not used for tethering data transfer which uses a dedicated USB interface as a virtual network device. Multiple connections to different TCP ports can happen in parallel. The higher-level layers are handled by libimobiledevice. When usbmuxd is running (normally started or stopped as a result of _udev_ auto-insertion messages, or by _systemd_) it provides a socket interface in `/var/run/usbmuxd` that is designed to be compatible with the socket interface that is provided on macOS. You should also create a `usbmux` user that has access to USB devices on your system. Alternatively, you can pass a different username using the `-U` argument. The daemon also manages pairing records with iOS devices and the host in `/var/lib/lockdown` (Linux) or `/var/db/lockdown` (macOS). Ensure proper permissions are setup for the daemon to access the directory. ## Requirements Development Packages of: * libimobiledevice * libplist * libusb Software: * make * autoheader * automake * autoconf * libtool * pkg-config * gcc or clang * udev (Linux only) Optional: * systemd (Linux only) ## Installation To compile run: ```bash ./autogen.sh make sudo make install ``` The daemon is automatically started by udev or systemd depending on what you have configured it on hotplug of an iOS device and exits if the last device was unplugged. For debugging purposes it is helpful to start usbmuxd using the foreground `-f` argument and enable verbose mode `-v` to get suitable logs. ## Who/What/Where? * Home: https://www.libimobiledevice.org/ * Code: `git clone https://git.libimobiledevice.org/usbmuxd.git` * Code (Mirror): `git clone https://github.com/libimobiledevice/usbmuxd.git` * Tickets: https://github.com/libimobiledevice/usbmuxd/issues * Mailing List: https://lists.libimobiledevice.org/mailman/listinfo/libimobiledevice-devel * IRC: irc://irc.freenode.net#libimobiledevice * Twitter: https://twitter.com/libimobiledev ## Credits The first usbmuxd daemon implementation was authored by Hector Martin. Apple, iPhone, iPod, and iPod Touch are trademarks of Apple Inc. libimobiledevice is an independent software library and has not been authorized, sponsored, or otherwise approved by Apple Inc. README Updated on: 2019-05-16 usbmuxd-1.1.1~git20191130.9af2b12/autogen.sh000077500000000000000000000006261356231277100200050ustar00rootroot00000000000000#!/bin/sh gprefix=`which glibtoolize 2>&1 >/dev/null` if [ $? -eq 0 ]; then glibtoolize --force else libtoolize --force fi aclocal -I m4 autoheader automake --add-missing autoconf requires_pkgconfig=`which pkg-config 2>&1 >/dev/null` if [ $? -ne 0 ]; then echo "Missing required pkg-config. Please install it on your system and run again." fi if [ -z "$NOCONFIGURE" ]; then ./configure "$@" fi usbmuxd-1.1.1~git20191130.9af2b12/configure.ac000066400000000000000000000135461356231277100202770ustar00rootroot00000000000000# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ(2.64) AC_INIT([usbmuxd], [1.1.1], [https://github.com/libimobiledevice/usbmuxd/issues],, [http://libimobiledevice.org]) AM_INIT_AUTOMAKE([dist-bzip2 no-dist-gzip check-news]) m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES]) AC_CONFIG_SRCDIR([src/]) AC_CONFIG_HEADERS([config.h]) AC_CONFIG_MACRO_DIR([m4]) # Checks for programs. AC_PROG_CC AC_PROG_CXX AM_PROG_CC_C_O AC_PROG_LIBTOOL # Checks for libraries. PKG_CHECK_MODULES(libusb, libusb-1.0 >= 1.0.9) PKG_CHECK_MODULES(libplist, libplist >= 1.11) PKG_CHECK_MODULES(libimobiledevice, libimobiledevice-1.0 >= 1.2.1, have_limd=yes, have_limd=no) AC_CHECK_LIB(pthread, [pthread_create, pthread_mutex_lock], [AC_SUBST(libpthread_LIBS,[-lpthread])], [AC_MSG_ERROR([libpthread is required to build usbmuxd])]) AC_ARG_WITH([preflight], [AS_HELP_STRING([--without-preflight], [do not build with preflight worker support @<:@default=yes@:>@])], [with_preflight=no], [with_preflight=yes]) if test "x$have_limd" = "xyes"; then if test "x$with_preflight" != "xyes"; then have_limd=no echo "*** Note: preflight worker support has been disabled ***" else AC_DEFINE(HAVE_LIBIMOBILEDEVICE, 1, [Define if you have libimobiledevice support]) AC_SUBST(libimobiledevice_CFLAGS) AC_SUBST(libimobiledevice_LIBS) AC_CACHE_CHECK(for enum idevice_connection_type, ac_cv_enum_idevice_connection_type, AC_TRY_COMPILE([ #include ], [ enum idevice_connection_type conn_type = CONNECTION_USBMUXD; ], ac_cv_enum_idevice_connection_type=yes, ac_cv_enum_idevice_connection_type=no)) if (test "$ac_cv_enum_idevice_connection_type" = "yes"); then AC_DEFINE(HAVE_ENUM_IDEVICE_CONNECTION_TYPE, 1, [Define if enum idevice_connection_type is available]) fi fi else if test "x$with_preflight" == "xyes"; then AC_MSG_ERROR([preflight worker support requested but libimobiledevice could not be found]) fi fi AC_ARG_WITH([udevrulesdir], AS_HELP_STRING([--with-udevrulesdir=DIR], [Directory for udev rules]), [], [with_udevrulesdir=auto]) if test "x$with_udevrulesdir" = "xauto"; then udevdir=$($PKG_CONFIG --variable=udevdir udev) if test "x$udevdir" != "x"; then with_udevrulesdir=$udevdir"/rules.d" else with_udevrulesdir=$prefix/lib/udev/rules.d fi fi AC_ARG_WITH([systemd], [AS_HELP_STRING([--without-systemd], [do not build with systemd support @<:@default=yes@:>@])], [], [with_systemd=yes]) AC_ARG_WITH([systemdsystemunitdir], [AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [directory for systemd service files])], [with_systemdsystemunitdir=$withval], [with_systemdsystemunitdir=$($PKG_CONFIG --variable=systemdsystemunitdir systemd)]) if test "x$with_systemdsystemunitdir" != xno; then AC_SUBST([systemdsystemunitdir], [$with_systemdsystemunitdir]) fi AM_CONDITIONAL(WANT_SYSTEMD, [test -n "$with_systemdsystemunitdir" -a "x$with_systemdsystemunitdir" != xno -a "x$with_systemd" = "xyes" ]) if test "x$with_systemd" = xyes; then udev_activation_rule="ENV{SYSTEMD_WANTS}=\"usbmuxd.service\"" else udev_activation_rule="RUN+=\"@sbindir@/usbmuxd --user usbmux --udev\"" fi AC_SUBST(udev_activation_rule) # Checks for header files. AC_HEADER_STDC AC_CHECK_HEADERS([stdint.h stdlib.h string.h]) # Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_SIZE_T AC_TYPE_SSIZE_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT8_T # Check if clock_gettime requires -lrt (old GNU systems) AC_SEARCH_LIBS([clock_gettime],[rt posix4]) # Checks for library functions. AC_FUNC_MALLOC AC_FUNC_REALLOC AC_CHECK_FUNCS([strcasecmp strdup strerror strndup stpcpy]) AC_CHECK_FUNCS([ppoll clock_gettime localtime_r]) # Check for operating system AC_MSG_CHECKING([whether to enable WIN32 build settings]) UDEV_SUB= SYSTEMD_SUB= case ${host_os} in *mingw32*|*cygwin*) win32=true AC_MSG_RESULT([yes]) AC_CHECK_TOOL([WINDRES], [windres], AC_MSG_ERROR([windres not found])) AC_SUBST(WINDRES) activation_method="manual" ;; darwin*) win32=false AC_MSG_RESULT([no]) # No support for launchd yet activation_method="manual" ;; *) win32=false AC_MSG_RESULT([no]) UDEV_SUB=udev AC_SUBST([udevrulesdir], [$with_udevrulesdir]) AC_DEFINE(HAVE_UDEV, 1, [Define to enable udev support]) activation_method="systemd" if test "x$with_systemd" != "xyes"; then echo "*** Note: support for systemd activation has been disabled, using udev activation instead ***" activation_method="udev" else AC_DEFINE(HAVE_SYSTEMD, 1, [Define to enable systemd support]) SYSTEMD_SUB=systemd fi ;; esac AM_CONDITIONAL(WIN32, test x$win32 = xtrue) AC_SUBST([UDEV_SUB]) AC_SUBST([SYSTEMD_SUB]) AS_COMPILER_FLAGS(GLOBAL_CFLAGS, "-g -Wall -Wextra -Wmissing-declarations -Wredundant-decls -Wshadow -Wpointer-arith -Wwrite-strings -Wswitch-default -Wno-unused-parameter") AC_SUBST(GLOBAL_CFLAGS) m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])]) AC_OUTPUT([ Makefile src/Makefile udev/Makefile systemd/Makefile docs/Makefile ]) echo " Configuration for $PACKAGE $VERSION: ------------------------------------------- install prefix ............: $prefix preflight worker support ..: $have_limd activation method .........: $activation_method" if test "x$activation_method" = "xsystemd"; then echo " systemd unit directory ....: ${systemdsystemunitdir}" fi if test -n "$udevrulesdir"; then echo " udev rules directory ......: ${udevrulesdir}" fi echo " compiler ..................: ${CC} Now type 'make' to build $PACKAGE $VERSION, and then 'make install' for installation. " usbmuxd-1.1.1~git20191130.9af2b12/docs/000077500000000000000000000000001356231277100167305ustar00rootroot00000000000000usbmuxd-1.1.1~git20191130.9af2b12/docs/Makefile.am000066400000000000000000000000571356231277100207660ustar00rootroot00000000000000man_MANS = usbmuxd.8 EXTRA_DIST = $(man_MANS) usbmuxd-1.1.1~git20191130.9af2b12/docs/usbmuxd.8000066400000000000000000000051301356231277100205070ustar00rootroot00000000000000.TH "usbmuxd" 8 .SH NAME usbmuxd \- Expose a socket to multiplex connections from and to iOS devices. .SH SYNOPSIS .B usbmuxd [OPTIONS] .SH DESCRIPTION usbmuxd stands for "USB multiplexing daemon". This daemon is in charge of multiplexing connections over USB to an iOS device. To users, it means you can sync your music, contacts, photos, etc. over USB. To developers, it means you can connect to any listening localhost socket on the device. usbmuxd is not used for tethering data transfer which uses a dedicated USB interface as a virtual network device. Multiple connections to different TCP ports can happen in parallel. The higher-level layers are handled by libimobiledevice. When usbmuxd is running (normally started, or stopped as a result of "udev" auto-insertion messages or by systemd) it provides a socket interface in "/var/run/usbmuxd" that is designed to be compatible with the socket interface that is provided on Mac OS X. You should also create a "usbmux" user that has access to USB devices on your system. Alternatively, you can pass a different username using the -U argument. Due to iOS 7 the daemon now also manages pairing records with iOS devices and the host in "/var/lib/lockdown" (Linux) or "/var/db/lockdown" (Mac OS X). Ensure proper permissions are setup for the daemon to access the directory. .SH OPTIONS .TP .B \-U, \-\-user USER Change to this user after startup (needs USB privileges). .TP .B \-f, \-\-foreground Do not daemonize (implies one -v). .TP .B \-n, \-\-disable-hotplug Disables automatic discovery of devices on hotplug. Starting another instance will trigger discovery instead. .TP .B \-z, \-\-enable-exit Enable "--exit" request from other instances and exit automatically if no device is attached. .TP .B \-u, \-\-udev Run in udev operation mode (implies -n and -z). .TP .B \-s, \-\-systemd Run in systemd operation mode (implies -z and -f). .TP .B \-x, \-\-exit Notify a running instance to exit if there are no devices connected (sends SIGUSR1 to running instance) and exit. .TP .B \-X, \-\-force-exit Notify a running instance to exit even if there are still devices connected (always works) and exit. .TP .B \-v, \-\-verbose be verbose (use twice or more to increase verbose level). .TP .B \-V, \-\-version print version information and exit. .TP .B \-h, \-\-help prints usage information. .SH AUTHOR The first usbmuxd daemon implementation was authored by Hector Martin. Now mainly developed by Nikias Bassen, Martin Szulecki and contributors (see AUTHORS file). .SH SEE ALSO http://www.libimobiledevice.org http://github.com/libimobiledevice/usbmuxd/ idevice_id(1), iproxy(1). usbmuxd-1.1.1~git20191130.9af2b12/m4/000077500000000000000000000000001356231277100163205ustar00rootroot00000000000000usbmuxd-1.1.1~git20191130.9af2b12/m4/as-compiler-flag.m4000066400000000000000000000027371356231277100217150ustar00rootroot00000000000000dnl as-compiler-flag.m4 0.1.0 dnl autostars m4 macro for detection of compiler flags dnl David Schleef dnl $Id: as-compiler-flag.m4,v 1.1 2005/12/15 23:35:19 ds Exp $ dnl AS_COMPILER_FLAG(CFLAGS, ACTION-IF-ACCEPTED, [ACTION-IF-NOT-ACCEPTED]) dnl Tries to compile with the given CFLAGS. dnl Runs ACTION-IF-ACCEPTED if the compiler can compile with the flags, dnl and ACTION-IF-NOT-ACCEPTED otherwise. AC_DEFUN([AS_COMPILER_FLAG], [ AC_MSG_CHECKING([to see if compiler understands $1]) save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $1" AC_TRY_COMPILE([ ], [], [flag_ok=yes], [flag_ok=no]) CFLAGS="$save_CFLAGS" if test "X$flag_ok" = Xyes ; then m4_ifvaln([$2],[$2]) true else m4_ifvaln([$3],[$3]) true fi AC_MSG_RESULT([$flag_ok]) ]) dnl AS_COMPILER_FLAGS(VAR, FLAGS) dnl Tries to compile with the given CFLAGS. AC_DEFUN([AS_COMPILER_FLAGS], [ list=$2 flags_supported="" flags_unsupported="" AC_MSG_CHECKING([for supported compiler flags]) for each in $list do save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $each" AC_TRY_COMPILE([ ], [], [flag_ok=yes], [flag_ok=no]) CFLAGS="$save_CFLAGS" if test "X$flag_ok" = Xyes ; then flags_supported="$flags_supported $each" else flags_unsupported="$flags_unsupported $each" fi done AC_MSG_RESULT([$flags_supported]) if test "X$flags_unsupported" != X ; then AC_MSG_WARN([unsupported compiler flags: $flags_unsupported]) fi $1="$$1 $flags_supported" ]) usbmuxd-1.1.1~git20191130.9af2b12/src/000077500000000000000000000000001356231277100165675ustar00rootroot00000000000000usbmuxd-1.1.1~git20191130.9af2b12/src/Makefile.am000066400000000000000000000010101356231277100206130ustar00rootroot00000000000000AM_CPPFLAGS = -I$(top_srcdir)/include -I$(top_srcdir) AM_CFLAGS = $(GLOBAL_CFLAGS) $(libplist_CFLAGS) $(libusb_CFLAGS) $(libimobildevice_CFLAGS) AM_LDFLAGS = $(libplist_LIBS) $(libusb_LIBS) $(libimobiledevice_LIBS) $(libpthread_LIBS) sbin_PROGRAMS = usbmuxd usbmuxd_CFLAGS = $(AM_CFLAGS) usbmuxd_LDFLAGS = $(AM_LDFLAGS) -no-undefined usbmuxd_SOURCES = client.c client.h \ device.c device.h \ preflight.c preflight.h \ log.c log.h \ usbmuxd-proto.h usb.c usb.h \ utils.c utils.h \ conf.c conf.h \ main.c usbmuxd-1.1.1~git20191130.9af2b12/src/client.c000066400000000000000000000720731356231277100202220ustar00rootroot00000000000000/* * client.c * * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include #endif #define _GNU_SOURCE 1 #include #include #include #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "usb.h" #include "client.h" #include "device.h" #include "conf.h" #define CMD_BUF_SIZE 0x10000 #define REPLY_BUF_SIZE 0x10000 enum client_state { CLIENT_COMMAND, // waiting for command CLIENT_LISTEN, // listening for devices CLIENT_CONNECTING1, // issued connection request CLIENT_CONNECTING2, // connection established, but waiting for response message to get sent CLIENT_CONNECTED, // connected CLIENT_DEAD }; struct mux_client { int fd; unsigned char *ob_buf; uint32_t ob_size; uint32_t ob_capacity; unsigned char *ib_buf; uint32_t ib_size; uint32_t ib_capacity; short events, devents; uint32_t connect_tag; int connect_device; enum client_state state; uint32_t proto_version; uint32_t number; plist_t info; }; static struct collection client_list; pthread_mutex_t client_list_mutex; static uint32_t client_number = 0; /** * Receive raw data from the client socket. * * @param client Client to read from. * @param buffer Buffer to store incoming data. * @param len Max number of bytes to read. * @return Same as recv() system call. Number of bytes read; when < 0 errno will be set. */ int client_read(struct mux_client *client, void *buffer, uint32_t len) { usbmuxd_log(LL_SPEW, "client_read fd %d buf %p len %d", client->fd, buffer, len); if(client->state != CLIENT_CONNECTED) { usbmuxd_log(LL_ERROR, "Attempted to read from client %d not in CONNECTED state", client->fd); return -1; } return recv(client->fd, buffer, len, 0); } /** * Send raw data to the client socket. * * @param client Client to send to. * @param buffer The data to send. * @param len Number of bytes to write. * @return Same as system call send(). Number of bytes written; when < 0 errno will be set. */ int client_write(struct mux_client *client, void *buffer, uint32_t len) { int sret = -1; usbmuxd_log(LL_SPEW, "client_write fd %d buf %p len %d", client->fd, buffer, len); if(client->state != CLIENT_CONNECTED) { usbmuxd_log(LL_ERROR, "Attempted to write to client %d not in CONNECTED state", client->fd); return -1; } sret = send(client->fd, buffer, len, 0); if (sret < 0) { if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { usbmuxd_log(LL_DEBUG, "client_write: fd %d not ready for writing", client->fd); sret = 0; } else { usbmuxd_log(LL_ERROR, "ERROR: client_write: sending to fd %d failed: %s", client->fd, strerror(errno)); } } return sret; } /** * Set event mask to use for ppoll()ing the client socket. * Typically POLLOUT and/or POLLIN. Note that this overrides * the current mask, that is, it is not ORing the argument * into the current mask. * * @param client The client to set the event mask on. * @param events The event mask to sert. * @return 0 on success, -1 on error. */ int client_set_events(struct mux_client *client, short events) { if((client->state != CLIENT_CONNECTED) && (client->state != CLIENT_CONNECTING2)) { usbmuxd_log(LL_ERROR, "client_set_events to client %d not in CONNECTED state", client->fd); return -1; } client->devents = events; if(client->state == CLIENT_CONNECTED) client->events = events; return 0; } /** * Wait for an inbound connection on the usbmuxd socket * and create a new mux_client instance for it, and store * the client in the client list. * * @param listenfd the socket fd to accept() on. * @return The connection fd for the client, or < 0 for error * in which case errno will be set. */ int client_accept(int listenfd) { struct sockaddr_un addr; int cfd; socklen_t len = sizeof(struct sockaddr_un); cfd = accept(listenfd, (struct sockaddr *)&addr, &len); if (cfd < 0) { usbmuxd_log(LL_ERROR, "accept() failed (%s)", strerror(errno)); return cfd; } int flags = fcntl(cfd, F_GETFL, 0); if (flags < 0) { usbmuxd_log(LL_ERROR, "ERROR: Could not get socket flags!"); } else { if (fcntl(cfd, F_SETFL, flags | O_NONBLOCK) < 0) { usbmuxd_log(LL_ERROR, "ERROR: Could not set socket to non-blocking mode"); } } int bufsize = 0x20000; if (setsockopt(cfd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int)) == -1) { usbmuxd_log(LL_WARNING, "Could not set send buffer for client socket"); } if (setsockopt(cfd, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int)) == -1) { usbmuxd_log(LL_WARNING, "Could not set receive buffer for client socket"); } int yes = 1; setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(int)); struct mux_client *client; client = malloc(sizeof(struct mux_client)); memset(client, 0, sizeof(struct mux_client)); client->fd = cfd; client->ob_buf = malloc(REPLY_BUF_SIZE); client->ob_size = 0; client->ob_capacity = REPLY_BUF_SIZE; client->ib_buf = malloc(CMD_BUF_SIZE); client->ib_size = 0; client->ib_capacity = CMD_BUF_SIZE; client->state = CLIENT_COMMAND; client->events = POLLIN; client->info = NULL; pthread_mutex_lock(&client_list_mutex); client->number = client_number++; collection_add(&client_list, client); pthread_mutex_unlock(&client_list_mutex); #ifdef SO_PEERCRED if (log_level >= LL_INFO) { struct ucred cr; len = sizeof(struct ucred); getsockopt(cfd, SOL_SOCKET, SO_PEERCRED, &cr, &len); if (getpid() == cr.pid) { usbmuxd_log(LL_INFO, "New client on fd %d (self)", client->fd); } else { usbmuxd_log(LL_INFO, "New client on fd %d (pid %d)", client->fd, cr.pid); } } #else usbmuxd_log(LL_INFO, "New client on fd %d", client->fd); #endif 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); free(client->ob_buf); free(client->ib_buf); plist_free(client->info); pthread_mutex_lock(&client_list_mutex); collection_remove(&client_list, client); pthread_mutex_unlock(&client_list_mutex); free(client); } void client_get_fds(struct fdlist *list) { pthread_mutex_lock(&client_list_mutex); FOREACH(struct mux_client *client, &client_list) { fdlist_add(list, FD_CLIENT, client->fd, client->events); } ENDFOREACH pthread_mutex_unlock(&client_list_mutex); } static int send_pkt(struct mux_client *client, uint32_t tag, enum usbmuxd_msgtype msg, void *payload, int payload_length) { struct usbmuxd_header hdr; hdr.version = client->proto_version; hdr.length = sizeof(hdr) + payload_length; hdr.message = msg; hdr.tag = tag; usbmuxd_log(LL_DEBUG, "send_pkt fd %d tag %d msg %d payload_length %d", client->fd, tag, msg, payload_length); uint32_t available = client->ob_capacity - client->ob_size; /* the output buffer _should_ be large enough, but just in case */ if(available < hdr.length) { unsigned char* new_buf; uint32_t new_size = ((client->ob_capacity + hdr.length + 4096) / 4096) * 4096; usbmuxd_log(LL_DEBUG, "%s: Enlarging client %d output buffer %d -> %d", __func__, client->fd, client->ob_capacity, new_size); new_buf = realloc(client->ob_buf, new_size); if (!new_buf) { usbmuxd_log(LL_FATAL, "%s: Failed to realloc.", __func__); return -1; } client->ob_buf = new_buf; client->ob_capacity = new_size; } memcpy(client->ob_buf + client->ob_size, &hdr, sizeof(hdr)); if(payload && payload_length) memcpy(client->ob_buf + client->ob_size + sizeof(hdr), payload, payload_length); client->ob_size += hdr.length; client->events |= POLLOUT; return hdr.length; } static int send_plist_pkt(struct mux_client *client, uint32_t tag, plist_t plist) { int res = -1; char *xml = NULL; uint32_t xmlsize = 0; plist_to_xml(plist, &xml, &xmlsize); if (xml) { res = send_pkt(client, tag, MESSAGE_PLIST, xml, xmlsize); free(xml); } else { usbmuxd_log(LL_ERROR, "%s: Could not convert plist to xml", __func__); } return res; } static int send_result(struct mux_client *client, uint32_t tag, uint32_t result) { int res = -1; if (client->proto_version == 1) { /* XML plist packet */ plist_t dict = plist_new_dict(); plist_dict_set_item(dict, "MessageType", plist_new_string("Result")); plist_dict_set_item(dict, "Number", plist_new_uint(result)); res = send_plist_pkt(client, tag, dict); plist_free(dict); } else { /* binary packet */ res = send_pkt(client, tag, MESSAGE_RESULT, &result, sizeof(uint32_t)); } return res; } int client_notify_connect(struct mux_client *client, enum usbmuxd_result result) { usbmuxd_log(LL_SPEW, "client_notify_connect fd %d result %d", client->fd, result); if(client->state == CLIENT_DEAD) return -1; if(client->state != CLIENT_CONNECTING1) { usbmuxd_log(LL_ERROR, "client_notify_connect when client %d is not in CONNECTING1 state", client->fd); return -1; } if(send_result(client, client->connect_tag, result) < 0) return -1; if(result == RESULT_OK) { client->state = CLIENT_CONNECTING2; client->events = POLLOUT; // wait for the result packet to go through // no longer need this free(client->ib_buf); client->ib_buf = NULL; } else { client->state = CLIENT_COMMAND; } return 0; } static plist_t create_device_attached_plist(struct device_info *dev) { plist_t dict = plist_new_dict(); plist_dict_set_item(dict, "MessageType", plist_new_string("Attached")); plist_dict_set_item(dict, "DeviceID", plist_new_uint(dev->id)); plist_t props = plist_new_dict(); plist_dict_set_item(props, "ConnectionSpeed", plist_new_uint(dev->speed)); plist_dict_set_item(props, "ConnectionType", plist_new_string("USB")); plist_dict_set_item(props, "DeviceID", plist_new_uint(dev->id)); plist_dict_set_item(props, "LocationID", plist_new_uint(dev->location)); plist_dict_set_item(props, "ProductID", plist_new_uint(dev->pid)); plist_dict_set_item(props, "SerialNumber", plist_new_string(dev->serial)); plist_dict_set_item(dict, "Properties", props); return dict; } static int send_device_list(struct mux_client *client, uint32_t tag) { int res = -1; plist_t dict = plist_new_dict(); plist_t devices = plist_new_array(); struct device_info *devs = NULL; struct device_info *dev; int i; int count = device_get_list(0, &devs); dev = devs; for (i = 0; devs && i < count; i++) { plist_t device = create_device_attached_plist(dev++); if (device) { plist_array_append_item(devices, device); } } if (devs) free(devs); plist_dict_set_item(dict, "DeviceList", devices); res = send_plist_pkt(client, tag, dict); plist_free(dict); return res; } static int send_listener_list(struct mux_client *client, uint32_t tag) { int res = -1; plist_t dict = plist_new_dict(); plist_t listeners = plist_new_array(); pthread_mutex_lock(&client_list_mutex); FOREACH(struct mux_client *lc, &client_list) { if (lc->state == CLIENT_LISTEN) { plist_t n = NULL; plist_t l = plist_new_dict(); plist_dict_set_item(l, "Blacklisted", plist_new_bool(0)); n = NULL; if (lc->info) { n = plist_dict_get_item(lc->info, "BundleID"); } if (n) { plist_dict_set_item(l, "BundleID", plist_copy(n)); } plist_dict_set_item(l, "ConnType", plist_new_uint(0)); n = NULL; char *progname = NULL; if (lc->info) { n = plist_dict_get_item(lc->info, "ProgName"); } if (n) { plist_get_string_val(n, &progname); } if (!progname) { progname = strdup("unknown"); } char *idstring = malloc(strlen(progname) + 12); sprintf(idstring, "%u-%s", client->number, progname); plist_dict_set_item(l, "ID String", plist_new_string(idstring)); free(idstring); plist_dict_set_item(l, "ProgName", plist_new_string(progname)); free(progname); n = NULL; uint64_t version = 0; if (lc->info) { n = plist_dict_get_item(lc->info, "kLibUSBMuxVersion"); } if (n) { plist_get_uint_val(n, &version); } plist_dict_set_item(l, "kLibUSBMuxVersion", plist_new_uint(version)); plist_array_append_item(listeners, l); } } ENDFOREACH pthread_mutex_unlock(&client_list_mutex); plist_dict_set_item(dict, "ListenerList", listeners); res = send_plist_pkt(client, tag, dict); plist_free(dict); return res; } static int send_system_buid(struct mux_client *client, uint32_t tag) { int res = -1; char* buid = NULL; config_get_system_buid(&buid); plist_t dict = plist_new_dict(); plist_dict_set_item(dict, "BUID", plist_new_string(buid)); free(buid); res = send_plist_pkt(client, tag, dict); plist_free(dict); return res; } static int send_pair_record(struct mux_client *client, uint32_t tag, const char* record_id) { int res = -1; char* record_data = NULL; uint64_t record_size = 0; if (!record_id) { return send_result(client, tag, EINVAL); } config_get_device_record(record_id, &record_data, &record_size); if (record_data) { plist_t dict = plist_new_dict(); plist_dict_set_item(dict, "PairRecordData", plist_new_data(record_data, record_size)); free(record_data); res = send_plist_pkt(client, tag, dict); plist_free(dict); } else { res = send_result(client, tag, ENOENT); } return res; } static int notify_device_add(struct mux_client *client, struct device_info *dev) { int res = -1; if (client->proto_version == 1) { /* XML plist packet */ plist_t dict = create_device_attached_plist(dev); res = send_plist_pkt(client, 0, dict); plist_free(dict); } else { /* binary packet */ struct usbmuxd_device_record dmsg; memset(&dmsg, 0, sizeof(dmsg)); dmsg.device_id = dev->id; strncpy(dmsg.serial_number, dev->serial, 256); dmsg.serial_number[255] = 0; dmsg.location = dev->location; dmsg.product_id = dev->pid; res = send_pkt(client, 0, MESSAGE_DEVICE_ADD, &dmsg, sizeof(dmsg)); } return res; } static int notify_device_remove(struct mux_client *client, uint32_t device_id) { int res = -1; if (client->proto_version == 1) { /* XML plist packet */ plist_t dict = plist_new_dict(); plist_dict_set_item(dict, "MessageType", plist_new_string("Detached")); plist_dict_set_item(dict, "DeviceID", plist_new_uint(device_id)); res = send_plist_pkt(client, 0, dict); plist_free(dict); } else { /* binary packet */ res = send_pkt(client, 0, MESSAGE_DEVICE_REMOVE, &device_id, sizeof(uint32_t)); } return res; } static int notify_device_paired(struct mux_client *client, uint32_t device_id) { int res = -1; if (client->proto_version == 1) { /* XML plist packet */ plist_t dict = plist_new_dict(); plist_dict_set_item(dict, "MessageType", plist_new_string("Paired")); plist_dict_set_item(dict, "DeviceID", plist_new_uint(device_id)); res = send_plist_pkt(client, 0, dict); plist_free(dict); } else { /* binary packet */ res = send_pkt(client, 0, MESSAGE_DEVICE_PAIRED, &device_id, sizeof(uint32_t)); } return res; } static int start_listen(struct mux_client *client) { struct device_info *devs = NULL; struct device_info *dev; int count, i; client->state = CLIENT_LISTEN; count = device_get_list(0, &devs); dev = devs; for(i=0; devs && i < count; i++) { if(notify_device_add(client, dev++) < 0) { free(devs); return -1; } } if (devs) free(devs); return count; } static char* plist_dict_get_string_val(plist_t dict, const char* key) { if (!dict || plist_get_node_type(dict) != PLIST_DICT) return NULL; plist_t item = plist_dict_get_item(dict, key); if (!item || plist_get_node_type(item) != PLIST_STRING) return NULL; char *str = NULL; plist_get_string_val(item, &str); return str; } static void update_client_info(struct mux_client *client, plist_t dict) { plist_t node = NULL; plist_t info = plist_new_dict(); node = plist_dict_get_item(dict, "BundleID"); if (node && (plist_get_node_type(node) == PLIST_STRING)) { plist_dict_set_item(info, "BundleID", plist_copy(node)); } node = plist_dict_get_item(dict, "ClientVersionString"); if (node && (plist_get_node_type(node) == PLIST_STRING)) { plist_dict_set_item(info, "ClientVersionString", plist_copy(node)); } node = plist_dict_get_item(dict, "ProgName"); if (node && (plist_get_node_type(node) == PLIST_STRING)) { plist_dict_set_item(info, "ProgName", plist_copy(node)); } node = plist_dict_get_item(dict, "kLibUSBMuxVersion"); if (node && (plist_get_node_type(node) == PLIST_UINT)) { plist_dict_set_item(info, "kLibUSBMuxVersion", plist_copy(node)); } plist_free(client->info); client->info = info; } static int client_command(struct mux_client *client, struct usbmuxd_header *hdr) { int res; usbmuxd_log(LL_DEBUG, "Client command in fd %d len %d ver %d msg %d tag %d", client->fd, hdr->length, hdr->version, hdr->message, hdr->tag); if(client->state != CLIENT_COMMAND) { usbmuxd_log(LL_ERROR, "Client %d command received in the wrong state", client->fd); if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; client_close(client); return -1; } if((hdr->version != 0) && (hdr->version != 1)) { usbmuxd_log(LL_INFO, "Client %d version mismatch: expected 0 or 1, got %d", client->fd, hdr->version); send_result(client, hdr->tag, RESULT_BADVERSION); return 0; } struct usbmuxd_connect_request *ch; char *payload; uint32_t payload_size; switch(hdr->message) { case MESSAGE_PLIST: client->proto_version = 1; payload = (char*)(hdr) + sizeof(struct usbmuxd_header); payload_size = hdr->length - sizeof(struct usbmuxd_header); plist_t dict = NULL; plist_from_xml(payload, payload_size, &dict); if (!dict) { usbmuxd_log(LL_ERROR, "Could not parse plist from payload!"); return -1; } else { char *message = NULL; plist_t node = plist_dict_get_item(dict, "MessageType"); if (!node || plist_get_node_type(node) != PLIST_STRING) { usbmuxd_log(LL_ERROR, "Could not read valid MessageType node from plist!"); plist_free(dict); return -1; } plist_get_string_val(node, &message); if (!message) { usbmuxd_log(LL_ERROR, "Could not extract MessageType from plist!"); plist_free(dict); return -1; } update_client_info(client, dict); if (!strcmp(message, "Listen")) { free(message); plist_free(dict); if (send_result(client, hdr->tag, 0) < 0) return -1; usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd); return start_listen(client); } else if (!strcmp(message, "Connect")) { uint64_t val; uint16_t portnum = 0; uint32_t device_id = 0; free(message); // get device id node = plist_dict_get_item(dict, "DeviceID"); if (!node) { usbmuxd_log(LL_ERROR, "Received connect request without device_id!"); plist_free(dict); if (send_result(client, hdr->tag, RESULT_BADDEV) < 0) return -1; return 0; } val = 0; plist_get_uint_val(node, &val); device_id = (uint32_t)val; // get port number node = plist_dict_get_item(dict, "PortNumber"); if (!node) { usbmuxd_log(LL_ERROR, "Received connect request without port number!"); plist_free(dict); if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; return 0; } val = 0; plist_get_uint_val(node, &val); portnum = (uint16_t)val; plist_free(dict); usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, device_id, ntohs(portnum)); res = device_start_connect(device_id, ntohs(portnum), client); if(res < 0) { if (send_result(client, hdr->tag, -res) < 0) return -1; } else { client->connect_tag = hdr->tag; client->connect_device = device_id; client->state = CLIENT_CONNECTING1; } return 0; } else if (!strcmp(message, "ListDevices")) { free(message); plist_free(dict); if (send_device_list(client, hdr->tag) < 0) return -1; return 0; } else if (!strcmp(message, "ListListeners")) { free(message); plist_free(dict); if (send_listener_list(client, hdr->tag) < 0) return -1; return 0; } else if (!strcmp(message, "ReadBUID")) { free(message); plist_free(dict); if (send_system_buid(client, hdr->tag) < 0) return -1; return 0; } else if (!strcmp(message, "ReadPairRecord")) { free(message); char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); plist_free(dict); res = send_pair_record(client, hdr->tag, record_id); if (record_id) free(record_id); if (res < 0) return -1; return 0; } else if (!strcmp(message, "SavePairRecord")) { uint32_t rval = RESULT_OK; free(message); char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); char* record_data = NULL; uint64_t record_size = 0; plist_t rdata = plist_dict_get_item(dict, "PairRecordData"); if (rdata && plist_get_node_type(rdata) == PLIST_DATA) { plist_get_data_val(rdata, &record_data, &record_size); } if (record_id && record_data) { res = config_set_device_record(record_id, record_data, record_size); if (res < 0) { rval = -res; } else { plist_t p_dev_id = plist_dict_get_item(dict, "DeviceID"); uint32_t dev_id = 0; if (p_dev_id && plist_get_node_type(p_dev_id) == PLIST_UINT) { uint64_t u_dev_id = 0; plist_get_uint_val(p_dev_id, &u_dev_id); dev_id = (uint32_t)u_dev_id; } if (dev_id > 0) { struct device_info *devs = NULL; struct device_info *dev; int i; int count = device_get_list(1, &devs); int found = 0; dev = devs; for (i = 0; devs && i < count; i++, dev++) { if ((uint32_t)dev->id == dev_id && (strcmp(dev->serial, record_id) == 0)) { found++; break; } } if (!found) { usbmuxd_log(LL_ERROR, "ERROR: SavePairRecord: DeviceID %d (%s) is not connected\n", dev_id, record_id); } else { client_device_paired(dev_id); } free(devs); } } free(record_id); } else { rval = EINVAL; } free(record_data); plist_free(dict); if (send_result(client, hdr->tag, rval) < 0) return -1; return 0; } else if (!strcmp(message, "DeletePairRecord")) { uint32_t rval = RESULT_OK; free(message); char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); plist_free(dict); if (record_id) { res = config_remove_device_record(record_id); if (res < 0) { rval = -res; } free(record_id); } else { rval = EINVAL; } if (send_result(client, hdr->tag, rval) < 0) return -1; return 0; } else { usbmuxd_log(LL_ERROR, "Unexpected command '%s' received!", message); free(message); plist_free(dict); if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; return 0; } } // should not be reached?! return -1; case MESSAGE_LISTEN: if(send_result(client, hdr->tag, 0) < 0) return -1; usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd); return start_listen(client); case MESSAGE_CONNECT: ch = (void*)hdr; usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, ch->device_id, ntohs(ch->port)); res = device_start_connect(ch->device_id, ntohs(ch->port), client); if(res < 0) { if(send_result(client, hdr->tag, -res) < 0) return -1; } else { client->connect_tag = hdr->tag; client->connect_device = ch->device_id; client->state = CLIENT_CONNECTING1; } return 0; default: usbmuxd_log(LL_ERROR, "Client %d invalid command %d", client->fd, hdr->message); if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) return -1; return 0; } return -1; } static void 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((uint32_t)res == client->ob_size) { client->ob_size = 0; client->events &= ~POLLOUT; if(client->state == CLIENT_CONNECTING2) { usbmuxd_log(LL_DEBUG, "Client %d switching to CONNECTED state", client->fd); client->state = CLIENT_CONNECTED; client->events = client->devents; // no longer need this free(client->ob_buf); client->ob_buf = NULL; } } else { client->ob_size -= res; memmove(client->ob_buf, client->ob_buf + res, client->ob_size); } } static void process_recv(struct mux_client *client) { int res; int did_read = 0; if(client->ib_size < sizeof(struct usbmuxd_header)) { res = recv(client->fd, client->ib_buf + client->ib_size, sizeof(struct usbmuxd_header) - client->ib_size, 0); if(res <= 0) { if(res < 0) usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno)); else usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd); client_close(client); return; } client->ib_size += res; if(client->ib_size < sizeof(struct usbmuxd_header)) return; did_read = 1; } struct usbmuxd_header *hdr = (void*)client->ib_buf; if(hdr->length > client->ib_capacity) { usbmuxd_log(LL_INFO, "Client %d message is too long (%d bytes)", client->fd, hdr->length); client_close(client); return; } if(hdr->length < sizeof(struct usbmuxd_header)) { usbmuxd_log(LL_ERROR, "Client %d message is too short (%d bytes)", client->fd, hdr->length); client_close(client); return; } if(client->ib_size < hdr->length) { if(did_read) return; //maybe we would block, so defer to next loop res = recv(client->fd, client->ib_buf + client->ib_size, hdr->length - client->ib_size, 0); if(res < 0) { usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno)); client_close(client); return; } else if(res == 0) { usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd); client_close(client); return; } client->ib_size += res; if(client->ib_size < hdr->length) return; } client_command(client, hdr); client->ib_size = 0; } void client_process(int fd, short events) { struct mux_client *client = NULL; pthread_mutex_lock(&client_list_mutex); FOREACH(struct mux_client *lc, &client_list) { if(lc->fd == fd) { client = lc; break; } } ENDFOREACH pthread_mutex_unlock(&client_list_mutex); if(!client) { usbmuxd_log(LL_INFO, "client_process: fd %d not found in client list", fd); return; } if(client->state == CLIENT_CONNECTED) { usbmuxd_log(LL_SPEW, "client_process in CONNECTED state"); device_client_process(client->connect_device, client, events); } else { if(events & POLLIN) { 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) { pthread_mutex_lock(&client_list_mutex); usbmuxd_log(LL_DEBUG, "client_device_add: id %d, location 0x%x, serial %s", dev->id, dev->location, dev->serial); device_set_visible(dev->id); FOREACH(struct mux_client *client, &client_list) { if(client->state == CLIENT_LISTEN) notify_device_add(client, dev); } ENDFOREACH pthread_mutex_unlock(&client_list_mutex); } void client_device_remove(int device_id) { pthread_mutex_lock(&client_list_mutex); uint32_t id = device_id; usbmuxd_log(LL_DEBUG, "client_device_remove: id %d", device_id); FOREACH(struct mux_client *client, &client_list) { if(client->state == CLIENT_LISTEN) notify_device_remove(client, id); } ENDFOREACH pthread_mutex_unlock(&client_list_mutex); } void client_device_paired(int device_id) { pthread_mutex_lock(&client_list_mutex); uint32_t id = device_id; usbmuxd_log(LL_DEBUG, "client_device_paired: id %d", device_id); FOREACH(struct mux_client *client, &client_list) { if (client->state == CLIENT_LISTEN) notify_device_paired(client, id); } ENDFOREACH pthread_mutex_unlock(&client_list_mutex); } void client_init(void) { usbmuxd_log(LL_DEBUG, "client_init"); collection_init(&client_list); pthread_mutex_init(&client_list_mutex, NULL); } void client_shutdown(void) { usbmuxd_log(LL_DEBUG, "client_shutdown"); FOREACH(struct mux_client *client, &client_list) { client_close(client); } ENDFOREACH pthread_mutex_destroy(&client_list_mutex); collection_free(&client_list); } usbmuxd-1.1.1~git20191130.9af2b12/src/client.h000066400000000000000000000030541356231277100202200ustar00rootroot00000000000000/* * client.h * * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CLIENT_H #define CLIENT_H #include #include "usbmuxd-proto.h" struct device_info; struct mux_client; int client_read(struct mux_client *client, void *buffer, uint32_t len); int client_write(struct mux_client *client, void *buffer, uint32_t len); int client_set_events(struct mux_client *client, short events); void client_close(struct mux_client *client); int client_notify_connect(struct mux_client *client, enum usbmuxd_result result); void client_device_add(struct device_info *dev); void client_device_remove(int device_id); void client_device_paired(int device_id); int client_accept(int fd); void client_get_fds(struct fdlist *list); void client_process(int fd, short events); void client_init(void); void client_shutdown(void); #endif usbmuxd-1.1.1~git20191130.9af2b12/src/conf.c000066400000000000000000000307651356231277100176730ustar00rootroot00000000000000/* * conf.c * * Copyright (C) 2013 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #ifdef HAVE_SYS_TYPES_H #include #endif #include #include #include #include #ifdef WIN32 #include #endif #include "conf.h" #include "utils.h" #include "log.h" #ifdef WIN32 #define DIR_SEP '\\' #define DIR_SEP_S "\\" #else #define DIR_SEP '/' #define DIR_SEP_S "/" #endif #define CONFIG_SYSTEM_BUID_KEY "SystemBUID" #define CONFIG_HOST_ID_KEY "HostID" #define CONFIG_EXT ".plist" #ifdef WIN32 #define CONFIG_DIR "Apple"DIR_SEP_S"Lockdown" #else #define CONFIG_DIR "lockdown" #endif #define CONFIG_FILE "SystemConfiguration"CONFIG_EXT static char *__config_dir = NULL; #ifdef WIN32 static char *config_utf16_to_utf8(wchar_t *unistr, long len, long *items_read, long *items_written) { if (!unistr || (len <= 0)) return NULL; char *outbuf = (char*)malloc(3*(len+1)); int p = 0; int i = 0; wchar_t wc; while (i < len) { wc = unistr[i++]; if (wc >= 0x800) { outbuf[p++] = (char)(0xE0 + ((wc >> 12) & 0xF)); outbuf[p++] = (char)(0x80 + ((wc >> 6) & 0x3F)); outbuf[p++] = (char)(0x80 + (wc & 0x3F)); } else if (wc >= 0x80) { outbuf[p++] = (char)(0xC0 + ((wc >> 6) & 0x1F)); outbuf[p++] = (char)(0x80 + (wc & 0x3F)); } else { outbuf[p++] = (char)(wc & 0x7F); } } if (items_read) { *items_read = i; } if (items_written) { *items_written = p; } outbuf[p] = 0; return outbuf; } #endif const char *config_get_config_dir() { char *base_config_dir = NULL; if (__config_dir) return __config_dir; #ifdef WIN32 wchar_t path[MAX_PATH+1]; HRESULT hr; LPITEMIDLIST pidl = NULL; BOOL b = FALSE; hr = SHGetSpecialFolderLocation (NULL, CSIDL_COMMON_APPDATA, &pidl); if (hr == S_OK) { b = SHGetPathFromIDListW (pidl, path); if (b) { base_config_dir = config_utf16_to_utf8 (path, wcslen(path), NULL, NULL); CoTaskMemFree (pidl); } } #else #ifdef __APPLE__ base_config_dir = strdup("/var/db"); #else base_config_dir = strdup("/var/lib"); #endif #endif __config_dir = string_concat(base_config_dir, DIR_SEP_S, CONFIG_DIR, NULL); if (__config_dir) { int i = strlen(__config_dir)-1; while ((i > 0) && (__config_dir[i] == DIR_SEP)) { __config_dir[i--] = '\0'; } } free(base_config_dir); usbmuxd_log(LL_DEBUG, "initialized config_dir to %s", __config_dir); return __config_dir; } static int __mkdir(const char *dir, int mode) { #ifdef WIN32 return mkdir(dir); #else return mkdir(dir, mode); #endif } static int mkdir_with_parents(const char *dir, int mode) { if (!dir) return -1; if (__mkdir(dir, mode) == 0) { return 0; } else { if (errno == EEXIST) return 0; } int res; char *parent = strdup(dir); char* parentdir = dirname(parent); if (parentdir) { res = mkdir_with_parents(parentdir, mode); } else { res = -1; } free(parent); return res; } /** * Creates a freedesktop compatible configuration directory. */ static void config_create_config_dir(void) { const char *config_path = config_get_config_dir(); struct stat st; if (stat(config_path, &st) != 0) { mkdir_with_parents(config_path, 0755); } } static int get_rand(int min, int max) { int retval = (rand() % (max - min)) + min; return retval; } static char *config_generate_uuid(int idx) { char *uuid = (char *) malloc(sizeof(char) * 37); const char *chars = "ABCDEF0123456789"; srand(time(NULL) - idx); int i = 0; for (i = 0; i < 36; i++) { if (i == 8 || i == 13 || i == 18 || i == 23) { uuid[i] = '-'; continue; } else { uuid[i] = chars[get_rand(0, 16)]; } } /* make it a real string */ uuid[36] = '\0'; return uuid; } /** * Generates a valid BUID for this system (which is actually a UUID). * * @return A null terminated string containing a valid BUID. */ static char *config_generate_system_buid() { return config_generate_uuid(1); } static int internal_set_value(const char *config_file, const char *key, plist_t value) { if (!config_file) return 0; /* read file into plist */ plist_t config = NULL; plist_read_from_filename(&config, config_file); if (!config) { config = plist_new_dict(); plist_dict_set_item(config, key, value); } else { plist_t n = plist_dict_get_item(config, key); if (n) { plist_dict_remove_item(config, key); } plist_dict_set_item(config, key, value); remove(config_file); } /* store in config file */ char *value_string = NULL; if (plist_get_node_type(value) == PLIST_STRING) { plist_get_string_val(value, &value_string); usbmuxd_log(LL_DEBUG, "setting key %s to %s in config_file %s", key, value_string, config_file); if (value_string) free(value_string); } else { usbmuxd_log(LL_DEBUG, "setting key %s in config_file %s", key, config_file); } int res = plist_write_to_filename(config, config_file, PLIST_FORMAT_XML); plist_free(config); return res; } static int config_set_value(const char *key, plist_t value) { const char *config_path = NULL; char *config_file = NULL; /* Make sure config directory exists */ config_create_config_dir(); config_path = config_get_config_dir(); config_file = string_concat(config_path, DIR_SEP_S, CONFIG_FILE, NULL); int result = internal_set_value(config_file, key, value); if (!result) { usbmuxd_log(LL_ERROR, "ERROR: Failed to write to '%s': %s", config_file, strerror(errno)); } free(config_file); return result; } static int internal_get_value(const char* config_file, const char *key, plist_t *value) { *value = NULL; /* now parse file to get the SystemBUID */ plist_t config = NULL; if (plist_read_from_filename(&config, config_file)) { usbmuxd_log(LL_DEBUG, "reading key %s from config_file %s", key, config_file); plist_t n = plist_dict_get_item(config, key); if (n) { *value = plist_copy(n); n = NULL; } } plist_free(config); return 1; } static int config_get_value(const char *key, plist_t *value) { const char *config_path = NULL; char *config_file = NULL; config_path = config_get_config_dir(); config_file = string_concat(config_path, DIR_SEP_S, CONFIG_FILE, NULL); int result = internal_get_value(config_file, key, value); free(config_file); return result; } /** * Store SystemBUID in config file. * * @param system_buid A null terminated string containing a valid SystemBUID. */ static int config_set_system_buid(const char *system_buid) { return config_set_value(CONFIG_SYSTEM_BUID_KEY, plist_new_string(system_buid)); } /** * Determines whether a pairing record is present for the given device. * * @param udid The device UDID as given by the device. * * @return 1 if there's a pairing record for the given udid or 0 otherwise. */ int config_has_device_record(const char *udid) { int res = 0; if (!udid) return 0; /* ensure config directory exists */ config_create_config_dir(); /* build file path */ const char *config_path = config_get_config_dir(); char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); struct stat st; if ((stat(device_record_file, &st) == 0) && S_ISREG(st.st_mode)) res = 1; free(device_record_file); return res; } /** * Reads the BUID from a previously generated configuration file. * * @param system_buid pointer to a variable that will be set to point to a * newly allocated string containing the BUID. * * @note It is the responsibility of the calling function to free the returned system_buid */ void config_get_system_buid(char **system_buid) { plist_t value = NULL; config_get_value(CONFIG_SYSTEM_BUID_KEY, &value); if (value && (plist_get_node_type(value) == PLIST_STRING)) { plist_get_string_val(value, system_buid); usbmuxd_log(LL_DEBUG, "got %s %s", CONFIG_SYSTEM_BUID_KEY, *system_buid); } if (value) plist_free(value); if (!*system_buid) { /* no config, generate system_buid */ usbmuxd_log(LL_DEBUG, "no previous %s found", CONFIG_SYSTEM_BUID_KEY); *system_buid = config_generate_system_buid(); if (!config_set_system_buid(*system_buid)) { usbmuxd_log(LL_WARNING, "WARNING: Failed to store SystemBUID, this might be a problem"); } } usbmuxd_log(LL_DEBUG, "using %s as %s", *system_buid, CONFIG_SYSTEM_BUID_KEY); } /** * Store a pairing record for the given device identifier. * * @param udid device identifier * @param record_data buffer containing a pairing record * @param record_size size of buffer passed in record_data * * @return 0 on success or a negative errno otherwise. */ int config_set_device_record(const char *udid, char* record_data, uint64_t record_size) { int res = 0; if (!udid || !record_data || record_size < 8) return -EINVAL; plist_t plist = NULL; if (memcmp(record_data, "bplist00", 8) == 0) { plist_from_bin(record_data, record_size, &plist); } else { plist_from_xml(record_data, record_size, &plist); } if (!plist || plist_get_node_type(plist) != PLIST_DICT) { if (plist) plist_free(plist); return -EINVAL; } /* ensure config directory exists */ config_create_config_dir(); /* build file path */ const char *config_path = config_get_config_dir(); char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); remove(device_record_file); /* store file */ if (!plist_write_to_filename(plist, device_record_file, PLIST_FORMAT_XML)) { usbmuxd_log(LL_DEBUG, "could not open '%s' for writing: %s", device_record_file, strerror(errno)); res = -ENOENT; } free(device_record_file); if (plist) plist_free(plist); return res; } /** * Retrieve a pairing record for the given device identifier * * @param udid device identifier * @param record_data pointer to a variable that will be set to point to a * newly allocated buffer holding the pairing record * @param record_size pointer to a variable that will be set to the size * of the buffer given in record_data. * * @return 0 on success or a negative errno otherwise. */ int config_get_device_record(const char *udid, char **record_data, uint64_t *record_size) { int res = 0; /* ensure config directory exists */ config_create_config_dir(); /* build file path */ const char *config_path = config_get_config_dir(); char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); /* read file */ buffer_read_from_filename(device_record_file, record_data, record_size); if (!*record_data) { usbmuxd_log(LL_ERROR, "%s: failed to read '%s': %s", __func__, device_record_file, strerror(errno)); res = -ENOENT; } free(device_record_file); return res; } /** * Remove the pairing record stored for a device from this host. * * @param udid The udid of the device * * @return 0 on success or a negative errno otherwise. */ int config_remove_device_record(const char *udid) { int res = 0; /* build file path */ const char *config_path = config_get_config_dir(); char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); /* remove file */ if (remove(device_record_file) != 0) { res = -errno; usbmuxd_log(LL_DEBUG, "could not remove %s: %s", device_record_file, strerror(errno)); } free(device_record_file); return res; } static int config_device_record_get_value(const char *udid, const char *key, plist_t *value) { const char *config_path = NULL; char *config_file = NULL; config_path = config_get_config_dir(); config_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); int result = internal_get_value(config_file, key, value); free(config_file); return result; } void config_device_record_get_host_id(const char *udid, char **host_id) { plist_t value = NULL; config_device_record_get_value(udid, CONFIG_HOST_ID_KEY, &value); if (value && (plist_get_node_type(value) == PLIST_STRING)) { plist_get_string_val(value, host_id); } if (value) plist_free(value); if (!*host_id) { usbmuxd_log(LL_ERROR, "%s: ERROR couldn't get HostID from pairing record for udid %s", __func__, udid); } } usbmuxd-1.1.1~git20191130.9af2b12/src/conf.h000066400000000000000000000024311356231277100176650ustar00rootroot00000000000000/* * conf.h * * Copyright (C) 2013 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONF_H #define CONF_H #ifdef HAVE_CONFIG_H #include #endif #include const char *config_get_config_dir(); void config_get_system_buid(char **system_buid); int config_has_device_record(const char *udid); int config_get_device_record(const char *udid, char **record_data, uint64_t *record_size); int config_set_device_record(const char *udid, char* record_data, uint64_t record_size); int config_remove_device_record(const char *udid); void config_device_record_get_host_id(const char *udid, char **host_id); #endif usbmuxd-1.1.1~git20191130.9af2b12/src/device.c000066400000000000000000000716621356231277100202060ustar00rootroot00000000000000/* * device.c * * Copyright (C) 2009 Hector Martin "marcan" * Copyright (C) 2014 Mikkel Kamstrup Erlandsen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define _DEFAULT_SOURCE #define _BSD_SOURCE #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include "device.h" #include "client.h" #include "preflight.h" #include "usb.h" #include "log.h" int next_device_id; #define DEV_MRU 65536 #define CONN_INBUF_SIZE 262144 #define CONN_OUTBUF_SIZE 65536 #define ACK_TIMEOUT 30 enum mux_protocol { MUX_PROTO_VERSION = 0, MUX_PROTO_CONTROL = 1, MUX_PROTO_SETUP = 2, 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; uint32_t magic; uint16_t tx_seq; uint16_t rx_seq; }; 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; uint32_t max_payload; uint32_t sendable; int flags; unsigned char *ib_buf; uint32_t ib_size; uint32_t ib_capacity; unsigned char *ob_buf; uint32_t ob_capacity; short events; uint64_t last_ack_time; }; struct mux_device { struct usb_device *usbdev; int id; enum mux_dev_state state; int visible; struct collection connections; uint16_t next_sport; unsigned char *pktbuf; uint32_t pktlen; void *preflight_cb_data; int version; uint16_t rx_seq; uint16_t tx_seq; }; static struct collection device_list; pthread_mutex_t device_list_mutex; static struct mux_device* get_mux_device_for_id(int device_id) { struct mux_device *dev = NULL; pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *cdev, &device_list) { if(cdev->id == device_id) { dev = cdev; break; } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); return dev; } static struct mux_connection* get_mux_connection(int device_id, struct mux_client *client) { struct mux_connection *conn = NULL; pthread_mutex_lock(&device_list_mutex); 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 pthread_mutex_unlock(&device_list_mutex); return conn; } static int get_next_device_id(void) { while(1) { int ok = 1; pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *dev, &device_list) { if(dev->id == next_device_id) { next_device_id++; ok = 0; break; } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); 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_SETUP: hdrlen = 0; 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 mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header)); int total = mux_header_size + hdrlen + length; if(total > USB_MTU) { usbmuxd_log(LL_ERROR, "Tried to send packet larger than USB MTU (hdr %d data %d total %d) to device %d", hdrlen, length, total, dev->id); return -1; } buffer = malloc(total); struct mux_header *mhdr = (struct mux_header *)buffer; mhdr->protocol = htonl(proto); mhdr->length = htonl(total); if (dev->version >= 2) { mhdr->magic = htonl(0xfeedface); if (proto == MUX_PROTO_SETUP) { dev->tx_seq = 0; dev->rx_seq = 0xFFFF; } mhdr->tx_seq = htons(dev->tx_seq); mhdr->rx_seq = htons(dev->rx_seq); dev->tx_seq++; } memcpy(buffer + mux_header_size, header, hdrlen); if(data && length) memcpy(buffer + mux_header_size + hdrlen, data, length); if((res = usb_send(dev->usbdev, buffer, total)) < 0) { usbmuxd_log(LL_ERROR, "usb_send failed while sending packet (len %d) to device %d: %d", total, dev->id, res); 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_anon_rst(struct mux_device *dev, uint16_t sport, uint16_t dport, uint32_t ack) { struct tcphdr th; memset(&th, 0, sizeof(th)); th.th_sport = htons(sport); th.th_dport = htons(dport); th.th_ack = htonl(ack); th.th_flags = TH_RST; th.th_off = sizeof(th) / 4; usbmuxd_log(LL_DEBUG, "[OUT] dev=%d sport=%d dport=%d flags=0x%x", dev->id, sport, dport, th.th_flags); int res = send_packet(dev, MUX_PROTO_TCP, &th, NULL, 0); return res; } 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; int size; if(conn->state == CONN_DEAD) return; usbmuxd_log(LL_DEBUG, "connection_teardown dev %d sport %d dport %d", conn->dev->id, conn->sport, conn->dport); 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; if((conn->events & POLLOUT) && conn->ib_size > 0){ usbmuxd_log(LL_DEBUG, "%s: flushing buffer to client (%u bytes)", __func__, conn->ib_size); uint64_t tm_last = mstime64(); while(1){ size = client_write(conn->client, conn->ib_buf, conn->ib_size); if(size < 0) { usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after error.", __func__); break; } else if (size == 0) { uint64_t tm_now = mstime64(); if (tm_now - tm_last > 1000) { usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after unsuccessfully attempting for %dms.", __func__, (int)(tm_now - tm_last)); break; } usleep(10000); continue; } if(size == (int)conn->ib_size) { conn->ib_size = 0; break; } else { conn->ib_size -= size; memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size); } tm_last = mstime64(); } } client_close(conn->client); } } free(conn->ib_buf); free(conn->ob_buf); collection_remove(&conn->dev->connections, conn); free(conn); } int device_start_connect(int device_id, uint16_t dport, struct mux_client *client) { struct mux_device *dev = get_mux_device_for_id(device_id); if(!dev) { usbmuxd_log(LL_WARNING, "Attempted to connect to nonexistent device %d", device_id); return -RESULT_BADDEV; } 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->ib_buf); free(conn->ob_buf); free(conn); return -RESULT_CONNREFUSED; //bleh } collection_add(&dev->connections, conn); return 0; } /** * Examine the state of a connection's buffers and * update all connection flags and masks accordingly. * Does not do I/O. * * @param conn The connection to update. */ static void update_connection(struct mux_connection *conn) { uint32_t sent = conn->tx_seq - conn->rx_ack; if(conn->rx_win > sent) conn->sendable = conn->rx_win - sent; else conn->sendable = 0; 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); } static int send_tcp_ack(struct mux_connection *conn) { if(send_tcp(conn, TH_ACK, NULL, 0) < 0) { usbmuxd_log(LL_ERROR, "Error sending TCP ACK (%d->%d)", conn->sport, conn->dport); connection_teardown(conn); return -1; } update_connection(conn); return 0; } /** * Flush input and output buffers for a client connection. * * @param device_id Numeric id for the device. * @param client The client to flush buffers for. * @param events event mask for the client. POLLOUT means that * the client is ready to receive data, POLLIN that it has * data to be read (and send along to the device). */ void device_client_process(int device_id, struct mux_client *client, short events) { struct mux_connection *conn = get_mux_connection(device_id, client); 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) && conn->ib_size > 0) { // Client is ready to receive data, send what we have // in the client's connection buffer (if there is any) size = client_write(conn->client, conn->ib_buf, conn->ib_size); if(size <= 0) { usbmuxd_log(LL_DEBUG, "error writing to client (%d)", size); connection_teardown(conn); return; } conn->tx_ack += size; if(size == (int)conn->ib_size) { conn->ib_size = 0; } else { conn->ib_size -= size; memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size); } } if((events & POLLIN) && conn->sendable > 0) { // There is inbound trafic on the client socket, // convert it to tcp and send to the device // (if the device's input buffer is not full) size = client_read(conn->client, conn->ob_buf, conn->sendable); if(size <= 0) { 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); } /** * Copy a payload to a connection's in-buffer and * set the POLLOUT event mask on the connection so * the next main_loop iteration will dispatch the * buffer if the connection socket is writable. * * Connection buffers are flushed in the * device_client_process() function. * * @param conn The connection to add incoming data to. * @param payload Payload to prepare for writing. * The payload will be copied immediately so you are * free to alter or free the payload buffer when this * function returns. * @param payload_length number of bytes to copy from from * the payload. */ static void connection_device_input(struct mux_connection *conn, unsigned char *payload, uint32_t payload_length) { if((conn->ib_size + payload_length) > conn->ib_capacity) { 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) { struct mux_connection *conn = get_mux_connection(device_id, client); if (conn) { connection_teardown(conn); } else { usbmuxd_log(LL_WARNING, "Attempted to abort for nonexistent connection for device %d", device_id); } } static void device_version_input(struct mux_device *dev, struct version_header *vh) { 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 != 2 && vh->major != 1) { usbmuxd_log(LL_ERROR, "Device %d has unknown version %d.%d", dev->id, vh->major, vh->minor); pthread_mutex_lock(&device_list_mutex); collection_remove(&device_list, dev); pthread_mutex_unlock(&device_list_mutex); free(dev); return; } dev->version = vh->major; if (dev->version >= 2) { send_packet(dev, MUX_PROTO_SETUP, NULL, "\x07", 1); } usbmuxd_log(LL_NOTICE, "Connected to v%d.%d device %d on location 0x%x with serial number %s", dev->version, vh->minor, dev->id, usb_get_location(dev->usbdev), usb_get_serial(dev->usbdev)); dev->state = MUXDEV_ACTIVE; collection_init(&dev->connections); struct device_info info; 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); info.speed = usb_get_speed(dev->usbdev); preflight_worker_device_add(&info); } static void device_control_input(struct mux_device *dev, unsigned char *payload, uint32_t payload_length) { if (payload_length > 0) { switch (payload[0]) { case 3: if (payload_length > 1) { char* buf = malloc(payload_length); strncpy(buf, (char*)payload+1, payload_length-1); buf[payload_length-1] = '\0'; usbmuxd_log(LL_ERROR, "%s: ERROR: %s", __func__, buf); free(buf); } else { usbmuxd_log(LL_ERROR, "%s: Error occurred, but empty error message", __func__); } break; case 7: if (payload_length > 1) { char* buf = malloc(payload_length); strncpy(buf, (char*)payload+1, payload_length-1); buf[payload_length-1] = '\0'; usbmuxd_log(LL_INFO, "%s: %s", __func__, buf); free(buf); } break; default: break; } } else { usbmuxd_log(LL_WARNING, "%s: got a type 1 packet without payload", __func__); } } /** * Handle an incoming TCP packet from the device. * * @param dev The device handle TCP input on. * @param th Pointer to the TCP header struct. * @param payload Payload data. * @param payload_length Number of bytes in payload. */ static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned char *payload, uint32_t payload_length) { uint16_t sport = ntohs(th->th_dport); uint16_t dport = ntohs(th->th_sport); struct mux_connection *conn = NULL; 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, dport, sport, ntohl(th->th_seq), ntohl(th->th_ack), th->th_flags, ntohs(th->th_win) << 8, ntohs(th->th_win), payload_length); if(dev->state != MUXDEV_ACTIVE) { usbmuxd_log(LL_ERROR, "Received TCP packet from device %d but the device isn't active yet, discarding", dev->id); return; } // Find the connection on this device that has the right sport and dport FOREACH(struct mux_connection *lconn, &dev->connections) { if(lconn->sport == sport && lconn->dport == dport) { conn = lconn; break; } } ENDFOREACH if(!conn) { if(!(th->th_flags & TH_RST)) { usbmuxd_log(LL_INFO, "No connection for device %d incoming packet %d->%d", dev->id, dport, sport); if(send_anon_rst(dev, sport, dport, ntohl(th->th_seq)) < 0) usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", conn->dev->id, sport, dport); } 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); // Device likes it best when we are prompty ACKing data send_tcp_ack(conn); } } } /** * Take input data from the device that has been read into a buffer * and dispatch it to the right protocol backend (eg. TCP). * * @param usbdev * @param buffer * @param length */ void device_data_input(struct usb_device *usbdev, unsigned char *buffer, uint32_t length) { struct mux_device *dev = NULL; pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *tdev, &device_list) { if(tdev->usbdev == usbdev) { dev = tdev; break; } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); if(!dev) { usbmuxd_log(LL_WARNING, "Cannot find device entry for RX input from USB device %p on location 0x%x", usbdev, usb_get_location(usbdev)); return; } if(!length) return; // sanity check (should never happen with current USB implementation) if((length > USB_MRU) || (length > DEV_MRU)) { usbmuxd_log(LL_ERROR, "Too much data received from USB (%d), file a bug", 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) { if((length + dev->pktlen) > DEV_MRU) { usbmuxd_log(LL_ERROR, "Incoming split packet is too large (%d so far), dropping!", length + dev->pktlen); dev->pktlen = 0; return; } memcpy(dev->pktbuf + dev->pktlen, buffer, length); struct mux_header *mhdr = (struct mux_header *)dev->pktbuf; if((length < USB_MRU) || (ntohl(mhdr->length) == (length + dev->pktlen))) { 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; int mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header)); if(ntohl(mhdr->length) != length) { usbmuxd_log(LL_ERROR, "Incoming packet size mismatch (dev %d, expected %d, got %d)", dev->id, ntohl(mhdr->length), length); return; } struct tcphdr *th; unsigned char *payload; uint32_t payload_length; if (dev->version >= 2) { dev->rx_seq = ntohs(mhdr->rx_seq); } switch(ntohl(mhdr->protocol)) { case MUX_PROTO_VERSION: if(length < (mux_header_size + sizeof(struct version_header))) { usbmuxd_log(LL_ERROR, "Incoming version packet is too small (%d)", length); return; } device_version_input(dev, (struct version_header *)((char*)mhdr+mux_header_size)); break; case MUX_PROTO_CONTROL: payload = (unsigned char *)(mhdr+1); payload_length = length - mux_header_size; device_control_input(dev, payload, payload_length); break; case MUX_PROTO_TCP: if(length < (mux_header_size + sizeof(struct tcphdr))) { usbmuxd_log(LL_ERROR, "Incoming TCP packet is too small (%d)", length); return; } th = (struct tcphdr *)((char*)mhdr+mux_header_size); payload = (unsigned char *)(th+1); payload_length = length - sizeof(struct tcphdr) - mux_header_size; device_tcp_input(dev, th, payload, payload_length); break; default: usbmuxd_log(LL_ERROR, "Incoming packet for device %d has unknown protocol 0x%x)", dev->id, ntohl(mhdr->protocol)); 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->visible = 0; dev->next_sport = 1; dev->pktbuf = malloc(DEV_MRU); dev->pktlen = 0; dev->preflight_cb_data = NULL; dev->version = 0; struct version_header vh; vh.major = htonl(2); vh.minor = htonl(0); vh.padding = 0; if((res = send_packet(dev, MUX_PROTO_VERSION, &vh, NULL, 0)) < 0) { usbmuxd_log(LL_ERROR, "Error sending version request packet to device %d", id); free(dev->pktbuf); free(dev); return res; } pthread_mutex_lock(&device_list_mutex); collection_add(&device_list, dev); pthread_mutex_unlock(&device_list_mutex); return 0; } void device_remove(struct usb_device *usbdev) { pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *dev, &device_list) { if(dev->usbdev == usbdev) { usbmuxd_log(LL_NOTICE, "Removed device %d on location 0x%x", dev->id, usb_get_location(usbdev)); 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); } if (dev->preflight_cb_data) { preflight_device_remove_cb(dev->preflight_cb_data); } collection_remove(&device_list, dev); pthread_mutex_unlock(&device_list_mutex); free(dev->pktbuf); free(dev); return; } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); usbmuxd_log(LL_WARNING, "Cannot find device entry while removing USB device %p on location 0x%x", usbdev, usb_get_location(usbdev)); } void device_set_visible(int device_id) { pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *dev, &device_list) { if(dev->id == device_id) { dev->visible = 1; break; } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); } void device_set_preflight_cb_data(int device_id, void* data) { pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *dev, &device_list) { if(dev->id == device_id) { dev->preflight_cb_data = data; break; } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); } int device_get_count(int include_hidden) { int count = 0; struct collection dev_list = {NULL, 0}; pthread_mutex_lock(&device_list_mutex); collection_copy(&dev_list, &device_list); pthread_mutex_unlock(&device_list_mutex); FOREACH(struct mux_device *dev, &dev_list) { if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible)) count++; } ENDFOREACH collection_free(&dev_list); return count; } int device_get_list(int include_hidden, struct device_info **devices) { int count = 0; struct collection dev_list = {NULL, 0}; pthread_mutex_lock(&device_list_mutex); collection_copy(&dev_list, &device_list); pthread_mutex_unlock(&device_list_mutex); *devices = malloc(sizeof(struct device_info) * dev_list.capacity); struct device_info *p = *devices; FOREACH(struct mux_device *dev, &dev_list) { if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible)) { p->id = dev->id; p->serial = usb_get_serial(dev->usbdev); p->location = usb_get_location(dev->usbdev); p->pid = usb_get_pid(dev->usbdev); p->speed = usb_get_speed(dev->usbdev); count++; p++; } } ENDFOREACH collection_free(&dev_list); return count; } int device_get_timeout(void) { uint64_t oldest = (uint64_t)-1LL; pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *dev, &device_list) { if(dev->state == MUXDEV_ACTIVE) { FOREACH(struct mux_connection *conn, &dev->connections) { if((conn->state == CONN_CONNECTED) && (conn->flags & CONN_ACK_PENDING) && conn->last_ack_time < oldest) oldest = conn->last_ack_time; } ENDFOREACH } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); uint64_t ct = mstime64(); if((int64_t)oldest == -1LL) return 100000; //meh if((ct - oldest) > ACK_TIMEOUT) return 0; return ACK_TIMEOUT - (ct - oldest); } void device_check_timeouts(void) { uint64_t ct = mstime64(); pthread_mutex_lock(&device_list_mutex); FOREACH(struct mux_device *dev, &device_list) { if(dev->state == MUXDEV_ACTIVE) { FOREACH(struct mux_connection *conn, &dev->connections) { if((conn->state == CONN_CONNECTED) && (conn->flags & CONN_ACK_PENDING) && (ct - conn->last_ack_time) > ACK_TIMEOUT) { usbmuxd_log(LL_DEBUG, "Sending ACK due to expired timeout (%" PRIu64 " -> %" PRIu64 ")", conn->last_ack_time, ct); send_tcp_ack(conn); } } ENDFOREACH } } ENDFOREACH pthread_mutex_unlock(&device_list_mutex); } void device_init(void) { usbmuxd_log(LL_DEBUG, "device_init"); collection_init(&device_list); pthread_mutex_init(&device_list_mutex, NULL); 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"); pthread_mutex_lock(&device_list_mutex); 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 pthread_mutex_unlock(&device_list_mutex); pthread_mutex_destroy(&device_list_mutex); collection_free(&device_list); } usbmuxd-1.1.1~git20191130.9af2b12/src/device.h000066400000000000000000000032761356231277100202070ustar00rootroot00000000000000/* * device.h * * Copyright (C) 2009 Hector Martin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DEVICE_H #define DEVICE_H #include "usb.h" #include "client.h" struct device_info { int id; const char *serial; uint32_t location; uint16_t pid; uint64_t speed; }; void device_data_input(struct usb_device *dev, unsigned char *buf, uint32_t length); int device_add(struct usb_device *dev); void device_remove(struct usb_device *dev); int device_start_connect(int device_id, uint16_t port, struct mux_client *client); void device_client_process(int device_id, struct mux_client *client, short events); void device_abort_connect(int device_id, struct mux_client *client); void device_set_visible(int device_id); void device_set_preflight_cb_data(int device_id, void* data); int device_get_count(int include_hidden); int device_get_list(int include_hidden, struct device_info **devices); int device_get_timeout(void); void device_check_timeouts(void); void device_init(void); void device_kill_connections(void); void device_shutdown(void); #endif usbmuxd-1.1.1~git20191130.9af2b12/src/log.c000066400000000000000000000040611356231277100175150ustar00rootroot00000000000000/* * log.c * * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include "log.h" #include "utils.h" unsigned int log_level = LL_WARNING; int log_syslog = 0; void log_enable_syslog() { if (!log_syslog) { openlog("usbmuxd", LOG_PID, 0); log_syslog = 1; } } void log_disable_syslog() { if (log_syslog) { closelog(); } } static int level_to_syslog_level(int level) { int result = level + LOG_CRIT; if (result > LOG_DEBUG) { result = LOG_DEBUG; } return result; } void usbmuxd_log(enum loglevel level, const char *fmt, ...) { va_list ap; char *fs; if(level > log_level) return; fs = malloc(20 + strlen(fmt)); if(log_syslog) { sprintf(fs, "[%d] %s\n", level, fmt); } else { struct timeval ts; struct tm tp_; struct tm *tp; gettimeofday(&ts, NULL); #ifdef HAVE_LOCALTIME_R tp = localtime_r(&ts.tv_sec, &tp_); #else tp = localtime(&ts.tv_sec); #endif strftime(fs, 10, "[%H:%M:%S", tp); sprintf(fs+9, ".%03d][%d] %s\n", (int)(ts.tv_usec / 1000), level, fmt); } va_start(ap, fmt); if (log_syslog) { vsyslog(level_to_syslog_level(level), fs, ap); } else { vfprintf(stderr, fs, ap); } va_end(ap); free(fs); } usbmuxd-1.1.1~git20191130.9af2b12/src/log.h000066400000000000000000000022031356231277100175160ustar00rootroot00000000000000/* * log.h * * Copyright (C) 2009 Hector Martin "marcan" * Copyright (C) 2009 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LOG_H #define LOG_H enum loglevel { LL_FATAL = 0, LL_ERROR, LL_WARNING, LL_NOTICE, LL_INFO, LL_DEBUG, LL_SPEW, LL_FLOOD, }; extern unsigned int log_level; void log_enable_syslog(); void log_disable_syslog(); void usbmuxd_log(enum loglevel level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); #endif usbmuxd-1.1.1~git20191130.9af2b12/src/main.c000066400000000000000000000457771356231277100177030ustar00rootroot00000000000000/* * main.c * * Copyright (C) 2009-2019 Nikias Bassen * Copyright (C) 2013-2014 Martin Szulecki * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Paul Sladen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define _DEFAULT_SOURCE #define _BSD_SOURCE #define _GNU_SOURCE #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "usb.h" #include "device.h" #include "client.h" #include "conf.h" static const char *socket_path = "/var/run/usbmuxd"; static const char *lockfile = "/var/run/usbmuxd.pid"; int should_exit; int should_discover; int use_logfile = 0; static int verbose = 0; static int foreground = 0; static int drop_privileges = 0; static const char *drop_user = NULL; static int opt_disable_hotplug = 0; static int opt_enable_exit = 0; static int opt_exit = 0; static int exit_signal = 0; static int daemon_pipe; static int report_to_parent = 0; static 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; } int flags = fcntl(listenfd, F_GETFL, 0); if (flags < 0) { usbmuxd_log(LL_FATAL, "ERROR: Could not get flags for socket"); } else { if (fcntl(listenfd, F_SETFL, flags | O_NONBLOCK) < 0) { usbmuxd_log(LL_FATAL, "ERROR: Could not set socket to non-blocking"); } } bzero(&bind_addr, sizeof(bind_addr)); bind_addr.sun_family = AF_UNIX; strcpy(bind_addr.sun_path, socket_path); if (bind(listenfd, (struct sockaddr*)&bind_addr, sizeof(bind_addr)) != 0) { usbmuxd_log(LL_FATAL, "bind() failed: %s", strerror(errno)); return -1; } // Start listening if (listen(listenfd, 5) != 0) { usbmuxd_log(LL_FATAL, "listen() failed: %s", strerror(errno)); return -1; } chmod(socket_path, 0666); return listenfd; } static void handle_signal(int sig) { if (sig != SIGUSR1 && sig != SIGUSR2) { usbmuxd_log(LL_NOTICE,"Caught signal %d, exiting", sig); should_exit = 1; } else { if(opt_enable_exit) { if (sig == SIGUSR1) { usbmuxd_log(LL_INFO, "Caught SIGUSR1, checking if we can terminate (no more devices attached)..."); if (device_get_count(1) > 0) { // we can't quit, there are still devices attached. usbmuxd_log(LL_NOTICE, "Refusing to terminate, there are still devices attached. Kill me with signal 15 (TERM) to force quit."); } else { // it's safe to quit should_exit = 1; } } else if (sig == SIGUSR2) { usbmuxd_log(LL_INFO, "Caught SIGUSR2, scheduling device discovery"); should_discover = 1; } } else { usbmuxd_log(LL_INFO, "Caught SIGUSR1/2 but this instance was not started with \"--enable-exit\", ignoring."); } } } static void set_signal_handlers(void) { struct sigaction sa; sigset_t set; // Mask all signals we handle. They will be unmasked by ppoll(). sigemptyset(&set); sigaddset(&set, SIGINT); sigaddset(&set, SIGQUIT); sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR1); sigaddset(&set, SIGUSR2); sigprocmask(SIG_SETMASK, &set, NULL); memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = handle_signal; sigaction(SIGINT, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); sigaction(SIGUSR1, &sa, NULL); sigaction(SIGUSR2, &sa, NULL); } #ifndef HAVE_PPOLL static int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask) { int ready; sigset_t origmask; int to = timeout->tv_sec*1000 + timeout->tv_nsec/1000000; sigprocmask(SIG_SETMASK, sigmask, &origmask); ready = poll(fds, nfds, to); sigprocmask(SIG_SETMASK, &origmask, NULL); return ready; } #endif static int main_loop(int listenfd) { int to, cnt, i, dto; struct fdlist pollfds; struct timespec tspec; sigset_t empty_sigset; sigemptyset(&empty_sigset); // unmask all signals fdlist_create(&pollfds); while(!should_exit) { usbmuxd_log(LL_FLOOD, "main_loop iteration"); to = usb_get_timeout(); usbmuxd_log(LL_FLOOD, "USB timeout is %d ms", to); dto = device_get_timeout(); usbmuxd_log(LL_FLOOD, "Device timeout is %d ms", dto); if(dto < to) to = dto; fdlist_reset(&pollfds); fdlist_add(&pollfds, FD_LISTEN, listenfd, POLLIN); usb_get_fds(&pollfds); client_get_fds(&pollfds); usbmuxd_log(LL_FLOOD, "fd count is %d", pollfds.count); tspec.tv_sec = to / 1000; tspec.tv_nsec = (to % 1000) * 1000000; cnt = ppoll(pollfds.fds, pollfds.count, &tspec, &empty_sigset); usbmuxd_log(LL_FLOOD, "poll() returned %d", cnt); if(cnt == -1) { if(errno == EINTR) { if(should_exit) { usbmuxd_log(LL_INFO, "Event processing interrupted"); break; } if(should_discover) { should_discover = 0; usbmuxd_log(LL_INFO, "Device discovery triggered"); usb_discover(); } } } else if(cnt == 0) { if(usb_process() < 0) { usbmuxd_log(LL_FATAL, "usb_process() failed"); fdlist_free(&pollfds); return -1; } device_check_timeouts(); } else { int done_usb = 0; for(i=0; i 0) { // exit parent process int status; close(pfd[1]); if((res = read(pfd[0],&status,sizeof(int))) != sizeof(int)) { fprintf(stderr, "usbmuxd: ERROR: Failed to get init status from child, check syslog for messages.\n"); exit(1); } if(status != 0) fprintf(stderr, "usbmuxd: ERROR: Child process exited with error %d, check syslog for messages.\n", status); exit(status); } // At this point we are executing as the child process // but we need to do one more fork daemon_pipe = pfd[1]; close(pfd[0]); report_to_parent = 1; // Create a new SID for the child process sid = setsid(); if (sid < 0) { usbmuxd_log(LL_FATAL, "setsid() failed."); return -1; } pid = fork(); if (pid < 0) { usbmuxd_log(LL_FATAL, "fork() failed (second)."); return pid; } if (pid > 0) { // exit parent process close(daemon_pipe); exit(0); } // Change the current working directory. if ((chdir("/")) < 0) { usbmuxd_log(LL_FATAL, "chdir() failed"); return -2; } // Redirect standard files to /dev/null if (!freopen("/dev/null", "r", stdin)) { usbmuxd_log(LL_FATAL, "Redirection of stdin failed."); return -3; } if (!freopen("/dev/null", "w", stdout)) { usbmuxd_log(LL_FATAL, "Redirection of stdout failed."); return -3; } return 0; } static int notify_parent(int status) { int res; report_to_parent = 0; if ((res = write(daemon_pipe, &status, sizeof(int))) != sizeof(int)) { usbmuxd_log(LL_FATAL, "Could not notify parent!"); if(res >= 0) return -2; else return res; } close(daemon_pipe); if (!freopen("/dev/null", "w", stderr)) { usbmuxd_log(LL_FATAL, "Redirection of stderr failed."); return -1; } return 0; } static void usage() { printf("Usage: %s [OPTIONS]\n", PACKAGE_NAME); printf("Expose a socket to multiplex connections from and to iOS devices.\n\n"); printf(" -h, --help\t\tPrint this message.\n"); printf(" -v, --verbose\t\tBe verbose (use twice or more to increase).\n"); printf(" -f, --foreground\tDo not daemonize (implies one -v).\n"); printf(" -U, --user USER\tChange to this user after startup (needs USB privileges).\n"); printf(" -n, --disable-hotplug\tDisables automatic discovery of devices on hotplug.\n"); printf(" \tStarting another instance will trigger discovery instead.\n"); printf(" -z, --enable-exit\tEnable \"--exit\" request from other instances and exit\n"); printf(" \tautomatically if no device is attached.\n"); #ifdef HAVE_UDEV printf(" -u, --udev\t\tRun in udev operation mode (implies -n and -z).\n"); #endif #ifdef HAVE_SYSTEMD printf(" -s, --systemd\t\tRun in systemd operation mode (implies -z and -f).\n"); #endif printf(" -x, --exit\t\tNotify a running instance to exit if there are no devices\n"); printf(" \t\tconnected (sends SIGUSR1 to running instance) and exit.\n"); printf(" -X, --force-exit\tNotify a running instance to exit even if there are still\n"); printf(" \tdevices connected (always works) and exit.\n"); printf(" -l, --logfile=LOGFILE\tLog (append) to LOGFILE instead of stderr or syslog.\n"); printf(" -V, --version\t\tPrint version information and exit.\n"); printf("\n"); } static void parse_opts(int argc, char **argv) { static struct option longopts[] = { {"help", no_argument, NULL, 'h'}, {"foreground", no_argument, NULL, 'f'}, {"verbose", no_argument, NULL, 'v'}, {"user", required_argument, NULL, 'U'}, {"disable-hotplug", no_argument, NULL, 'n'}, {"enable-exit", no_argument, NULL, 'z'}, #ifdef HAVE_UDEV {"udev", no_argument, NULL, 'u'}, #endif #ifdef HAVE_SYSTEMD {"systemd", no_argument, NULL, 's'}, #endif {"exit", no_argument, NULL, 'x'}, {"force-exit", no_argument, NULL, 'X'}, {"logfile", required_argument, NULL, 'l'}, {"version", no_argument, NULL, 'V'}, {NULL, 0, NULL, 0} }; int c; #ifdef HAVE_SYSTEMD const char* opts_spec = "hfvVuU:xXsnzl:"; #elif HAVE_UDEV const char* opts_spec = "hfvVuU:xXnzl:"; #else const char* opts_spec = "hfvVU:xXnzl:"; #endif while (1) { c = getopt_long(argc, argv, opts_spec, longopts, (int *) 0); if (c == -1) { break; } switch (c) { case 'h': usage(); exit(0); case 'f': foreground = 1; break; case 'v': ++verbose; break; case 'V': printf("%s\n", PACKAGE_STRING); exit(0); case 'U': drop_privileges = 1; drop_user = optarg; break; #ifdef HAVE_UDEV case 'u': opt_disable_hotplug = 1; opt_enable_exit = 1; break; #endif #ifdef HAVE_SYSTEMD case 's': opt_enable_exit = 1; foreground = 1; break; #endif case 'n': opt_disable_hotplug = 1; break; case 'z': opt_enable_exit = 1; break; case 'x': opt_exit = 1; exit_signal = SIGUSR1; break; case 'X': opt_exit = 1; exit_signal = SIGTERM; break; case 'l': if (!*optarg) { usbmuxd_log(LL_FATAL, "ERROR: --logfile requires a non-empty filename"); usage(); exit(2); } if (use_logfile) { usbmuxd_log(LL_FATAL, "ERROR: --logfile cannot be used multiple times"); exit(2); } if (!freopen(optarg, "a", stderr)) { usbmuxd_log(LL_FATAL, "ERROR: fdreopen: %s", strerror(errno)); } else { use_logfile = 1; } break; default: usage(); exit(2); } } } int main(int argc, char *argv[]) { int listenfd; int res = 0; int lfd; struct flock lock; char pids[10]; parse_opts(argc, argv); argc -= optind; argv += optind; if (!foreground && !use_logfile) { verbose += LL_WARNING; log_enable_syslog(); } else { verbose += LL_NOTICE; } /* set log level to specified verbosity */ log_level = verbose; usbmuxd_log(LL_NOTICE, "usbmuxd v%s starting up", PACKAGE_VERSION); should_exit = 0; should_discover = 0; set_signal_handlers(); signal(SIGPIPE, SIG_IGN); res = lfd = open(lockfile, O_WRONLY|O_CREAT, 0644); if(res == -1) { usbmuxd_log(LL_FATAL, "Could not open lockfile"); goto terminate; } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; fcntl(lfd, F_GETLK, &lock); close(lfd); if (lock.l_type != F_UNLCK) { if (opt_exit) { if (lock.l_pid && !kill(lock.l_pid, 0)) { usbmuxd_log(LL_NOTICE, "Sending signal %d to instance with pid %d", exit_signal, lock.l_pid); res = 0; if (kill(lock.l_pid, exit_signal) < 0) { usbmuxd_log(LL_FATAL, "Could not deliver signal %d to pid %d", exit_signal, lock.l_pid); res = -1; } goto terminate; } else { usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!"); res = -1; goto terminate; } } else { if (!opt_disable_hotplug) { usbmuxd_log(LL_ERROR, "Another instance is already running (pid %d). exiting.", lock.l_pid); res = -1; } else { usbmuxd_log(LL_NOTICE, "Another instance is already running (pid %d). Telling it to check for devices.", lock.l_pid); if (lock.l_pid && !kill(lock.l_pid, 0)) { usbmuxd_log(LL_NOTICE, "Sending signal SIGUSR2 to instance with pid %d", lock.l_pid); res = 0; if (kill(lock.l_pid, SIGUSR2) < 0) { usbmuxd_log(LL_FATAL, "Could not deliver SIGUSR2 to pid %d", lock.l_pid); res = -1; } } else { usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!"); res = -1; } } goto terminate; } } unlink(lockfile); if (opt_exit) { usbmuxd_log(LL_NOTICE, "No running instance found, none killed. Exiting."); goto terminate; } if (!foreground) { if ((res = daemonize()) < 0) { fprintf(stderr, "usbmuxd: FATAL: Could not daemonize!\n"); usbmuxd_log(LL_FATAL, "Could not daemonize!"); goto terminate; } } // now open the lockfile and place the lock res = lfd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644); if(res < 0) { usbmuxd_log(LL_FATAL, "Could not open lockfile"); goto terminate; } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if ((res = fcntl(lfd, F_SETLK, &lock)) < 0) { usbmuxd_log(LL_FATAL, "Lockfile locking failed!"); goto terminate; } sprintf(pids, "%d", getpid()); if ((size_t)(res = write(lfd, pids, strlen(pids))) != strlen(pids)) { usbmuxd_log(LL_FATAL, "Could not write pidfile!"); if(res >= 0) res = -2; goto terminate; } // set number of file descriptors to higher value struct rlimit rlim; getrlimit(RLIMIT_NOFILE, &rlim); rlim.rlim_max = 65536; setrlimit(RLIMIT_NOFILE, (const struct rlimit*)&rlim); usbmuxd_log(LL_INFO, "Creating socket"); res = listenfd = create_socket(); if(listenfd < 0) goto terminate; #ifdef HAVE_LIBIMOBILEDEVICE const char* userprefdir = config_get_config_dir(); struct stat fst; memset(&fst, '\0', sizeof(struct stat)); if (stat(userprefdir, &fst) < 0) { if (mkdir(userprefdir, 0775) < 0) { usbmuxd_log(LL_FATAL, "Failed to create required directory '%s': %s", userprefdir, strerror(errno)); res = -1; goto terminate; } if (stat(userprefdir, &fst) < 0) { usbmuxd_log(LL_FATAL, "stat() failed after creating directory '%s': %s", userprefdir, strerror(errno)); res = -1; goto terminate; } } // make sure permission bits are set correctly if (fst.st_mode != 02775) { if (chmod(userprefdir, 02775) < 0) { usbmuxd_log(LL_WARNING, "chmod(%s, 02775) failed: %s", userprefdir, strerror(errno)); } } #endif // drop elevated privileges if (drop_privileges && (getuid() == 0 || geteuid() == 0)) { struct passwd *pw; if (!drop_user) { usbmuxd_log(LL_FATAL, "No user to drop privileges to?"); res = -1; goto terminate; } pw = getpwnam(drop_user); if (!pw) { usbmuxd_log(LL_FATAL, "Dropping privileges failed, check if user '%s' exists!", drop_user); res = -1; goto terminate; } if (pw->pw_uid == 0) { usbmuxd_log(LL_INFO, "Not dropping privileges to root"); } else { #ifdef HAVE_LIBIMOBILEDEVICE /* make sure the non-privileged user has proper access to the config directory */ if ((fst.st_uid != pw->pw_uid) || (fst.st_gid != pw->pw_gid)) { if (chown(userprefdir, pw->pw_uid, pw->pw_gid) < 0) { usbmuxd_log(LL_WARNING, "chown(%s, %d, %d) failed: %s", userprefdir, pw->pw_uid, pw->pw_gid, strerror(errno)); } } #endif if ((res = initgroups(drop_user, pw->pw_gid)) < 0) { usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set supplementary groups)"); goto terminate; } if ((res = setgid(pw->pw_gid)) < 0) { usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set group ID to %d)", pw->pw_gid); goto terminate; } if ((res = setuid(pw->pw_uid)) < 0) { usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set user ID to %d)", pw->pw_uid); goto terminate; } // security check if (setuid(0) != -1) { usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!"); res = -1; goto terminate; } if (getuid() != pw->pw_uid || getgid() != pw->pw_gid) { usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!"); res = -1; goto terminate; } usbmuxd_log(LL_NOTICE, "Successfully dropped privileges to '%s'", drop_user); } } client_init(); device_init(); usbmuxd_log(LL_INFO, "Initializing USB"); if((res = usb_init()) < 0) goto terminate; usbmuxd_log(LL_INFO, "%d device%s detected", res, (res==1)?"":"s"); usbmuxd_log(LL_NOTICE, "Initialization complete"); if (report_to_parent) if((res = notify_parent(0)) < 0) goto terminate; if(opt_disable_hotplug) { usbmuxd_log(LL_NOTICE, "Automatic device discovery on hotplug disabled."); usb_autodiscover(0); // discovery to be triggered by new instance } if (opt_enable_exit) { usbmuxd_log(LL_NOTICE, "Enabled exit on SIGUSR1 if no devices are attached. Start a new instance with \"--exit\" to trigger."); } res = main_loop(listenfd); if(res < 0) usbmuxd_log(LL_FATAL, "main_loop failed"); usbmuxd_log(LL_NOTICE, "usbmuxd shutting down"); device_kill_connections(); usb_shutdown(); device_shutdown(); client_shutdown(); usbmuxd_log(LL_NOTICE, "Shutdown complete"); terminate: log_disable_syslog(); if (res < 0) res = -res; else res = 0; if (report_to_parent) notify_parent(res); return res; } usbmuxd-1.1.1~git20191130.9af2b12/src/preflight.c000066400000000000000000000266061356231277100207310ustar00rootroot00000000000000/* * preflight.c * * Copyright (C) 2013 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef HAVE_LIBIMOBILEDEVICE #include #include #include #endif #include "preflight.h" #include "device.h" #include "client.h" #include "conf.h" #include "log.h" #ifdef HAVE_LIBIMOBILEDEVICE #ifndef HAVE_ENUM_IDEVICE_CONNECTION_TYPE enum idevice_connection_type { CONNECTION_USBMUXD = 1, CONNECTION_NETWORK }; #endif struct idevice_private { char *udid; uint32_t mux_id; enum idevice_connection_type conn_type; void *conn_data; int version; }; struct cb_data { idevice_t dev; np_client_t np; int is_device_connected; int is_finished; }; static void lockdownd_set_untrusted_host_buid(lockdownd_client_t lockdown) { char* system_buid = NULL; config_get_system_buid(&system_buid); usbmuxd_log(LL_DEBUG, "%s: Setting UntrustedHostBUID to %s", __func__, system_buid); lockdownd_set_value(lockdown, NULL, "UntrustedHostBUID", plist_new_string(system_buid)); free(system_buid); } void preflight_device_remove_cb(void *data) { if (!data) return; struct cb_data *cbdata = (struct cb_data*)data; cbdata->is_device_connected = 0; } static void np_callback(const char* notification, void* userdata) { struct cb_data *cbdata = (struct cb_data*)userdata; idevice_t dev = cbdata->dev; struct idevice_private *_dev = (struct idevice_private*)dev; lockdownd_client_t lockdown = NULL; lockdownd_error_t lerr; if (strlen(notification) == 0) { cbdata->np = NULL; return; } if (strcmp(notification, "com.apple.mobile.lockdown.request_pair") == 0) { usbmuxd_log(LL_INFO, "%s: user trusted this computer on device %s, pairing now", __func__, _dev->udid); lerr = lockdownd_client_new(dev, &lockdown, "usbmuxd"); if (lerr != LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr); cbdata->is_finished = 1; return; } lerr = lockdownd_pair(lockdown, NULL); if (lerr != LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_ERROR, "%s: ERROR: Pair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr); lockdownd_client_free(lockdown); cbdata->is_finished = 1; return; } lockdownd_client_free(lockdown); cbdata->is_finished = 1; } else if (strcmp(notification, "com.apple.mobile.lockdown.request_host_buid") == 0) { lerr = lockdownd_client_new(cbdata->dev, &lockdown, "usbmuxd"); if (lerr != LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr); } else { lockdownd_set_untrusted_host_buid(lockdown); lockdownd_client_free(lockdown); } } } static void* preflight_worker_handle_device_add(void* userdata) { struct device_info *info = (struct device_info*)userdata; struct idevice_private *_dev = (struct idevice_private*)malloc(sizeof(struct idevice_private)); _dev->udid = strdup(info->serial); _dev->mux_id = info->id; _dev->conn_type = CONNECTION_USBMUXD; _dev->conn_data = NULL; _dev->version = 0; idevice_t dev = (idevice_t)_dev; lockdownd_client_t lockdown = NULL; lockdownd_error_t lerr; plist_t value = NULL; char* version_str = NULL; usbmuxd_log(LL_INFO, "%s: Starting preflight on device %s...", __func__, _dev->udid); retry: lerr = lockdownd_client_new(dev, &lockdown, "usbmuxd"); if (lerr != LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr); goto leave; } char *type = NULL; lerr = lockdownd_query_type(lockdown, &type); if (!type) { usbmuxd_log(LL_ERROR, "%s: ERROR: Could not get lockdownd type from device %s, lockdown error %d", __func__, _dev->udid, lerr); goto leave; } if (strcmp(type, "com.apple.mobile.lockdown") != 0) { // make restore mode devices visible free(type); usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); client_device_add(info); goto leave; } free(type); int is_device_paired = 0; char *host_id = NULL; if (config_has_device_record(dev->udid)) { config_device_record_get_host_id(dev->udid, &host_id); lerr = lockdownd_start_session(lockdown, host_id, NULL, NULL); if (host_id) free(host_id); if (lerr == LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_INFO, "%s: StartSession success for device %s", __func__, _dev->udid); usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); client_device_add(info); goto leave; } usbmuxd_log(LL_INFO, "%s: StartSession failed on device %s, lockdown error %d", __func__, _dev->udid, lerr); } else { lerr = LOCKDOWN_E_INVALID_HOST_ID; } switch (lerr) { case LOCKDOWN_E_INVALID_HOST_ID: usbmuxd_log(LL_INFO, "%s: Device %s is not paired with this host.", __func__, _dev->udid); break; case LOCKDOWN_E_SSL_ERROR: usbmuxd_log(LL_ERROR, "%s: The stored pair record for device %s is invalid. Removing.", __func__, _dev->udid); if (config_remove_device_record(_dev->udid) == 0) { lockdownd_client_free(lockdown); lockdown = NULL; goto retry; } else { usbmuxd_log(LL_ERROR, "%s: Could not remove pair record for device %s", __func__, _dev->udid); } break; default: is_device_paired = 1; break; } lerr = lockdownd_get_value(lockdown, NULL, "ProductVersion", &value); if (lerr != LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_ERROR, "%s: ERROR: Could not get ProductVersion from device %s, lockdown error %d", __func__, _dev->udid, lerr); goto leave; } if (value && plist_get_node_type(value) == PLIST_STRING) { plist_get_string_val(value, &version_str); } if (!version_str) { usbmuxd_log(LL_ERROR, "%s: Could not get ProductVersion string from device %s handle %d", __func__, _dev->udid, (int)(long)_dev->conn_data); goto leave; } int version_major = strtol(version_str, NULL, 10); if (version_major >= 7) { /* iOS 7.0 and later */ usbmuxd_log(LL_INFO, "%s: Found ProductVersion %s device %s", __func__, version_str, _dev->udid); lockdownd_set_untrusted_host_buid(lockdown); /* if not paired, trigger the trust dialog to make sure it appears */ if (!is_device_paired) { if (lockdownd_pair(lockdown, NULL) == LOCKDOWN_E_SUCCESS) { /* if device is still showing the setup screen it will pair even without trust dialog */ usbmuxd_log(LL_INFO, "%s: Pair success for device %s", __func__, _dev->udid); usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); client_device_add(info); goto leave; } } lockdownd_service_descriptor_t service = NULL; lerr = lockdownd_start_service(lockdown, "com.apple.mobile.insecure_notification_proxy", &service); if (lerr != LOCKDOWN_E_SUCCESS) { /* even though we failed, simple mode should still work, so only warn of an error */ usbmuxd_log(LL_INFO, "%s: ERROR: Could not start insecure_notification_proxy on %s, lockdown error %d", __func__, _dev->udid, lerr); client_device_add(info); goto leave; } np_client_t np = NULL; np_client_new(dev, service, &np); lockdownd_service_descriptor_free(service); service = NULL; lockdownd_client_free(lockdown); lockdown = NULL; struct cb_data cbdata; cbdata.dev = dev; cbdata.np = np; cbdata.is_device_connected = 1; cbdata.is_finished = 0; np_set_notify_callback(np, np_callback, (void*)&cbdata); device_set_preflight_cb_data(info->id, (void*)&cbdata); const char* spec[] = { "com.apple.mobile.lockdown.request_pair", "com.apple.mobile.lockdown.request_host_buid", NULL }; np_observe_notifications(np, spec); /* TODO send notification to user's desktop */ usbmuxd_log(LL_INFO, "%s: Waiting for user to trust this computer on device %s", __func__, _dev->udid); /* make device visible anyways */ client_device_add(info); while (cbdata.np && cbdata.is_device_connected && !cbdata.is_finished) { sleep(1); } device_set_preflight_cb_data(info->id, NULL); usbmuxd_log(LL_INFO, "%s: Finished waiting for notification from device %s, is_device_connected %d", __func__, _dev->udid, cbdata.is_device_connected); if (cbdata.np) { np_client_free(cbdata.np); } } else { /* iOS 6.x and earlier */ lerr = lockdownd_pair(lockdown, NULL); if (lerr != LOCKDOWN_E_SUCCESS) { if (lerr == LOCKDOWN_E_PASSWORD_PROTECTED) { usbmuxd_log(LL_INFO, "%s: Device %s is locked with a passcode. Cannot pair.", __func__, _dev->udid); /* TODO send notification to user's desktop */ } else { usbmuxd_log(LL_ERROR, "%s: ERROR: Pair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr); } usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); /* make device visible anyways */ client_device_add(info); goto leave; } host_id = NULL; config_device_record_get_host_id(dev->udid, &host_id); lerr = lockdownd_start_session(lockdown, host_id, NULL, NULL); free(host_id); if (lerr != LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_ERROR, "%s: ERROR StartSession failed on device %s, lockdown error %d", __func__, _dev->udid, lerr); goto leave; } lerr = lockdownd_validate_pair(lockdown, NULL); if (lerr != LOCKDOWN_E_SUCCESS) { usbmuxd_log(LL_ERROR, "%s: ERROR: ValidatePair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr); goto leave; } usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); /* emit device added event and thus make device visible to clients */ client_device_add(info); } leave: if (value) plist_free(value); if (version_str) free(version_str); if (lockdown) lockdownd_client_free(lockdown); if (dev) idevice_free(dev); free((char*)info->serial); free(info); return NULL; } #else void preflight_device_remove_cb(void *data) { } #endif void preflight_worker_device_add(struct device_info* info) { #ifdef HAVE_LIBIMOBILEDEVICE struct device_info *infocopy = (struct device_info*)malloc(sizeof(struct device_info)); memcpy(infocopy, info, sizeof(struct device_info)); if (info->serial) { infocopy->serial = strdup(info->serial); } pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); int perr = pthread_create(&th, &attr, preflight_worker_handle_device_add, infocopy); if (perr != 0) { free((char*)infocopy->serial); free(infocopy); usbmuxd_log(LL_ERROR, "ERROR: failed to start preflight worker thread for device %s: %s (%d). Invoking client_device_add() directly but things might not work as expected.", info->serial, strerror(perr), perr); client_device_add(info); } #else client_device_add(info); #endif } usbmuxd-1.1.1~git20191130.9af2b12/src/preflight.h000066400000000000000000000016421356231277100207270ustar00rootroot00000000000000/* * preflight.h * * Copyright (C) 2013 Nikias Bassen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PREFLIGHT_H #define PREFLIGHT_H #include "device.h" void preflight_device_remove_cb(void *data); void preflight_worker_device_add(struct device_info* info); #endif usbmuxd-1.1.1~git20191130.9af2b12/src/usb.c000066400000000000000000000650501356231277100175320ustar00rootroot00000000000000/* * usb.c * * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Nikias Bassen * Copyright (C) 2009 Martin Szulecki * Copyright (C) 2014 Mikkel Kamstrup Erlandsen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include "usb.h" #include "log.h" #include "device.h" #include "utils.h" #if (defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000102)) || (defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x01000102)) #define HAVE_LIBUSB_HOTPLUG_API 1 #endif // interval for device connection/disconnection polling, in milliseconds // we need this because there is currently no asynchronous device discovery mechanism in libusb #define DEVICE_POLL_TIME 1000 // Number of parallel bulk transfers we have running for reading data from the device. // Older versions of usbmuxd kept only 1, which leads to a mostly dormant USB port. // 3 seems to be an all round sensible number - giving better read perf than // Apples usbmuxd, at least. #define NUM_RX_LOOPS 3 struct usb_device { libusb_device_handle *dev; uint8_t bus, address; char serial[256]; int alive; uint8_t interface, ep_in, ep_out; struct collection rx_xfers; struct collection tx_xfers; int wMaxPacketSize; uint64_t speed; struct libusb_device_descriptor devdesc; }; static struct collection device_list; static struct timeval next_dev_poll_time; static int devlist_failures; static int device_polling; static int device_hotplug = 1; static void usb_disconnect(struct usb_device *dev) { if(!dev->dev) { return; } // kill the rx xfer and tx xfers and try to make sure the callbacks // get called before we free the device FOREACH(struct libusb_transfer *xfer, &dev->rx_xfers) { usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling RX xfer %p", xfer); libusb_cancel_transfer(xfer); } ENDFOREACH FOREACH(struct libusb_transfer *xfer, &dev->tx_xfers) { usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling TX xfer %p", xfer); libusb_cancel_transfer(xfer); } ENDFOREACH // Busy-wait until all xfers are closed while(collection_count(&dev->rx_xfers) || collection_count(&dev->tx_xfers)) { struct timeval tv; int res; tv.tv_sec = 0; tv.tv_usec = 1000; if((res = libusb_handle_events_timeout(NULL, &tv)) < 0) { usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout for usb_disconnect failed: %d", res); break; } } collection_free(&dev->tx_xfers); collection_free(&dev->rx_xfers); libusb_release_interface(dev->dev, dev->interface); libusb_close(dev->dev); dev->dev = NULL; collection_remove(&device_list, dev); free(dev); } static void reap_dead_devices(void) { FOREACH(struct usb_device *usbdev, &device_list) { if(!usbdev->alive) { device_remove(usbdev); usb_disconnect(usbdev); } } ENDFOREACH } // Callback from write operation static void tx_callback(struct libusb_transfer *xfer) { struct usb_device *dev = xfer->user_data; usbmuxd_log(LL_SPEW, "TX callback dev %d-%d len %d -> %d status %d", dev->bus, dev->address, xfer->length, xfer->actual_length, xfer->status); if(xfer->status != LIBUSB_TRANSFER_COMPLETED) { switch(xfer->status) { case LIBUSB_TRANSFER_COMPLETED: //shut up compiler case LIBUSB_TRANSFER_ERROR: // funny, this happens when we disconnect the device while waiting for a transfer, sometimes usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to error or disconnect", dev->bus, dev->address); break; case LIBUSB_TRANSFER_TIMED_OUT: usbmuxd_log(LL_ERROR, "TX transfer timed out for device %d-%d", dev->bus, dev->address); break; case LIBUSB_TRANSFER_CANCELLED: usbmuxd_log(LL_DEBUG, "Device %d-%d TX transfer cancelled", dev->bus, dev->address); break; case LIBUSB_TRANSFER_STALL: usbmuxd_log(LL_ERROR, "TX transfer stalled for device %d-%d", dev->bus, dev->address); break; case LIBUSB_TRANSFER_NO_DEVICE: // other times, this happens, and also even when we abort the transfer after device removal usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to disconnect", dev->bus, dev->address); break; case LIBUSB_TRANSFER_OVERFLOW: usbmuxd_log(LL_ERROR, "TX transfer overflow for device %d-%d", dev->bus, dev->address); break; // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad) default: // this should never be reached. break; } // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events // we'll do device_remove there too dev->alive = 0; } if(xfer->buffer) free(xfer->buffer); collection_remove(&dev->tx_xfers, xfer); libusb_free_transfer(xfer); } int usb_send(struct usb_device *dev, const unsigned char *buf, int length) { int res; struct libusb_transfer *xfer = libusb_alloc_transfer(0); libusb_fill_bulk_transfer(xfer, dev->dev, dev->ep_out, (void*)buf, length, tx_callback, dev, 0); if((res = libusb_submit_transfer(xfer)) < 0) { usbmuxd_log(LL_ERROR, "Failed to submit TX transfer %p len %d to device %d-%d: %d", buf, length, dev->bus, dev->address, res); libusb_free_transfer(xfer); return res; } collection_add(&dev->tx_xfers, xfer); if (length % dev->wMaxPacketSize == 0) { usbmuxd_log(LL_DEBUG, "Send ZLP"); // Send Zero Length Packet xfer = libusb_alloc_transfer(0); void *buffer = malloc(1); libusb_fill_bulk_transfer(xfer, dev->dev, dev->ep_out, buffer, 0, tx_callback, dev, 0); if((res = libusb_submit_transfer(xfer)) < 0) { usbmuxd_log(LL_ERROR, "Failed to submit TX ZLP transfer to device %d-%d: %d", dev->bus, dev->address, res); libusb_free_transfer(xfer); return res; } collection_add(&dev->tx_xfers, xfer); } return 0; } // Callback from read operation // Under normal operation this issues a new read transfer request immediately, // doing a kind of read-callback loop static void rx_callback(struct libusb_transfer *xfer) { struct usb_device *dev = xfer->user_data; usbmuxd_log(LL_SPEW, "RX callback dev %d-%d len %d status %d", dev->bus, dev->address, xfer->actual_length, xfer->status); if(xfer->status == LIBUSB_TRANSFER_COMPLETED) { device_data_input(dev, xfer->buffer, xfer->actual_length); libusb_submit_transfer(xfer); } else { switch(xfer->status) { case LIBUSB_TRANSFER_COMPLETED: //shut up compiler case LIBUSB_TRANSFER_ERROR: // funny, this happens when we disconnect the device while waiting for a transfer, sometimes usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to error or disconnect", dev->bus, dev->address); break; case LIBUSB_TRANSFER_TIMED_OUT: usbmuxd_log(LL_ERROR, "RX transfer timed out for device %d-%d", dev->bus, dev->address); break; case LIBUSB_TRANSFER_CANCELLED: usbmuxd_log(LL_DEBUG, "Device %d-%d RX transfer cancelled", dev->bus, dev->address); break; case LIBUSB_TRANSFER_STALL: usbmuxd_log(LL_ERROR, "RX transfer stalled for device %d-%d", dev->bus, dev->address); break; case LIBUSB_TRANSFER_NO_DEVICE: // other times, this happens, and also even when we abort the transfer after device removal usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to disconnect", dev->bus, dev->address); break; case LIBUSB_TRANSFER_OVERFLOW: usbmuxd_log(LL_ERROR, "RX transfer overflow for device %d-%d", dev->bus, dev->address); break; // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad) default: // this should never be reached. break; } free(xfer->buffer); collection_remove(&dev->rx_xfers, xfer); libusb_free_transfer(xfer); // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events // we'll do device_remove there too dev->alive = 0; } } // Start a read-callback loop for this device static int start_rx_loop(struct usb_device *dev) { int res; void *buf; struct libusb_transfer *xfer = libusb_alloc_transfer(0); buf = malloc(USB_MRU); libusb_fill_bulk_transfer(xfer, dev->dev, dev->ep_in, buf, USB_MRU, rx_callback, dev, 0); if((res = libusb_submit_transfer(xfer)) != 0) { usbmuxd_log(LL_ERROR, "Failed to submit RX transfer to device %d-%d: %d", dev->bus, dev->address, res); libusb_free_transfer(xfer); return res; } collection_add(&dev->rx_xfers, xfer); return 0; } static void get_serial_callback(struct libusb_transfer *transfer) { unsigned int di, si; struct usb_device *usbdev = transfer->user_data; if(transfer->status != LIBUSB_TRANSFER_COMPLETED) { usbmuxd_log(LL_ERROR, "Failed to request serial for device %d-%d (%i)", usbdev->bus, usbdev->address, transfer->status); libusb_free_transfer(transfer); return; } /* De-unicode, taken from libusb */ unsigned char *data = libusb_control_transfer_get_data(transfer); for (di = 0, si = 2; si < data[0] && di < sizeof(usbdev->serial)-1; si += 2) { if ((data[si] & 0x80) || (data[si + 1])) /* non-ASCII */ usbdev->serial[di++] = '?'; else if (data[si] == '\0') break; else usbdev->serial[di++] = data[si]; } usbdev->serial[di] = '\0'; usbmuxd_log(LL_INFO, "Got serial '%s' for device %d-%d", usbdev->serial, usbdev->bus, usbdev->address); libusb_free_transfer(transfer); /* new style UDID: add hyphen between first 8 and following 16 digits */ if (di == 24) { memmove(&usbdev->serial[9], &usbdev->serial[8], 16); usbdev->serial[8] = '-'; usbdev->serial[di+1] = '\0'; } /* Finish setup now */ if(device_add(usbdev) < 0) { usb_disconnect(usbdev); return; } // Spin up NUM_RX_LOOPS parallel usb data retrieval loops // Old usbmuxds used only 1 rx loop, but that leaves the // USB port sleeping most of the time int rx_loops = NUM_RX_LOOPS; for (rx_loops = NUM_RX_LOOPS; rx_loops > 0; rx_loops--) { if(start_rx_loop(usbdev) < 0) { usbmuxd_log(LL_WARNING, "Failed to start RX loop number %d", NUM_RX_LOOPS - rx_loops); break; } } // Ensure we have at least 1 RX loop going if (rx_loops == NUM_RX_LOOPS) { usbmuxd_log(LL_FATAL, "Failed to start any RX loop for device %d-%d", usbdev->bus, usbdev->address); device_remove(usbdev); usb_disconnect(usbdev); return; } else if (rx_loops > 0) { usbmuxd_log(LL_WARNING, "Failed to start all %d RX loops. Going on with %d loops. " "This may have negative impact on device read speed.", NUM_RX_LOOPS, NUM_RX_LOOPS - rx_loops); } else { usbmuxd_log(LL_DEBUG, "All %d RX loops started successfully", NUM_RX_LOOPS); } } static void get_langid_callback(struct libusb_transfer *transfer) { int res; struct usb_device *usbdev = transfer->user_data; transfer->flags |= LIBUSB_TRANSFER_FREE_BUFFER; if(transfer->status != LIBUSB_TRANSFER_COMPLETED) { usbmuxd_log(LL_ERROR, "Failed to request lang ID for device %d-%d (%i)", usbdev->bus, usbdev->address, transfer->status); libusb_free_transfer(transfer); return; } unsigned char *data = libusb_control_transfer_get_data(transfer); uint16_t langid = (uint16_t)(data[2] | (data[3] << 8)); usbmuxd_log(LL_INFO, "Got lang ID %u for device %d-%d", langid, usbdev->bus, usbdev->address); /* re-use the same transfer */ libusb_fill_control_setup(transfer->buffer, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t)((LIBUSB_DT_STRING << 8) | usbdev->devdesc.iSerialNumber), langid, 1024 + LIBUSB_CONTROL_SETUP_SIZE); libusb_fill_control_transfer(transfer, usbdev->dev, transfer->buffer, get_serial_callback, usbdev, 1000); if((res = libusb_submit_transfer(transfer)) < 0) { usbmuxd_log(LL_ERROR, "Could not request transfer for device %d-%d (%d)", usbdev->bus, usbdev->address, res); libusb_free_transfer(transfer); } } static int usb_device_add(libusb_device* dev) { int j, res; // the following are non-blocking operations on the device list uint8_t bus = libusb_get_bus_number(dev); uint8_t address = libusb_get_device_address(dev); struct libusb_device_descriptor devdesc; struct libusb_transfer *transfer; int found = 0; FOREACH(struct usb_device *usbdev, &device_list) { if(usbdev->bus == bus && usbdev->address == address) { usbdev->alive = 1; found = 1; break; } } ENDFOREACH if(found) return 0; //device already found if((res = libusb_get_device_descriptor(dev, &devdesc)) != 0) { usbmuxd_log(LL_WARNING, "Could not get device descriptor for device %d-%d: %d", bus, address, res); return -1; } if(devdesc.idVendor != VID_APPLE) return -1; if((devdesc.idProduct < PID_RANGE_LOW) || (devdesc.idProduct > PID_RANGE_MAX)) return -1; libusb_device_handle *handle; usbmuxd_log(LL_INFO, "Found new device with v/p %04x:%04x at %d-%d", devdesc.idVendor, devdesc.idProduct, bus, address); // No blocking operation can follow: it may be run in the libusb hotplug callback and libusb will refuse any // blocking call if((res = libusb_open(dev, &handle)) != 0) { usbmuxd_log(LL_WARNING, "Could not open device %d-%d: %d", bus, address, res); return -1; } int desired_config = devdesc.bNumConfigurations; if (desired_config > 4) { desired_config = 4; } int current_config = 0; if((res = libusb_get_configuration(handle, ¤t_config)) != 0) { usbmuxd_log(LL_WARNING, "Could not get configuration for device %d-%d: %d", bus, address, res); libusb_close(handle); return -1; } if (current_config != desired_config) { struct libusb_config_descriptor *config; if((res = libusb_get_active_config_descriptor(dev, &config)) != 0) { usbmuxd_log(LL_NOTICE, "Could not get old configuration descriptor for device %d-%d: %d", bus, address, res); } else { for(j=0; jbNumInterfaces; j++) { const struct libusb_interface_descriptor *intf = &config->interface[j].altsetting[0]; if((res = libusb_kernel_driver_active(handle, intf->bInterfaceNumber)) < 0) { usbmuxd_log(LL_NOTICE, "Could not check kernel ownership of interface %d for device %d-%d: %d", intf->bInterfaceNumber, bus, address, res); continue; } if(res == 1) { usbmuxd_log(LL_INFO, "Detaching kernel driver for device %d-%d, interface %d", bus, address, intf->bInterfaceNumber); if((res = libusb_detach_kernel_driver(handle, intf->bInterfaceNumber)) < 0) { usbmuxd_log(LL_WARNING, "Could not detach kernel driver (%d), configuration change will probably fail!", res); continue; } } } libusb_free_config_descriptor(config); } usbmuxd_log(LL_INFO, "Setting configuration for device %d-%d, from %d to %d", bus, address, current_config, desired_config); if((res = libusb_set_configuration(handle, desired_config)) != 0) { usbmuxd_log(LL_WARNING, "Could not set configuration %d for device %d-%d: %d", desired_config, bus, address, res); libusb_close(handle); return -1; } } struct libusb_config_descriptor *config; if((res = libusb_get_active_config_descriptor(dev, &config)) != 0) { usbmuxd_log(LL_WARNING, "Could not get configuration descriptor for device %d-%d: %d", bus, address, res); libusb_close(handle); return -1; } struct usb_device *usbdev; usbdev = malloc(sizeof(struct usb_device)); memset(usbdev, 0, sizeof(*usbdev)); for(j=0; jbNumInterfaces; j++) { const struct libusb_interface_descriptor *intf = &config->interface[j].altsetting[0]; if(intf->bInterfaceClass != INTERFACE_CLASS || intf->bInterfaceSubClass != INTERFACE_SUBCLASS || intf->bInterfaceProtocol != INTERFACE_PROTOCOL) continue; if(intf->bNumEndpoints != 2) { usbmuxd_log(LL_WARNING, "Endpoint count mismatch for interface %d of device %d-%d", intf->bInterfaceNumber, bus, address); continue; } if((intf->endpoint[0].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_OUT && (intf->endpoint[1].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN) { usbdev->interface = intf->bInterfaceNumber; usbdev->ep_out = intf->endpoint[0].bEndpointAddress; usbdev->ep_in = intf->endpoint[1].bEndpointAddress; usbmuxd_log(LL_INFO, "Found interface %d with endpoints %02x/%02x for device %d-%d", usbdev->interface, usbdev->ep_out, usbdev->ep_in, bus, address); break; } else if((intf->endpoint[1].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_OUT && (intf->endpoint[0].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN) { usbdev->interface = intf->bInterfaceNumber; usbdev->ep_out = intf->endpoint[1].bEndpointAddress; usbdev->ep_in = intf->endpoint[0].bEndpointAddress; usbmuxd_log(LL_INFO, "Found interface %d with swapped endpoints %02x/%02x for device %d-%d", usbdev->interface, usbdev->ep_out, usbdev->ep_in, bus, address); break; } else { usbmuxd_log(LL_WARNING, "Endpoint type mismatch for interface %d of device %d-%d", intf->bInterfaceNumber, bus, address); } } if(j == config->bNumInterfaces) { usbmuxd_log(LL_WARNING, "Could not find a suitable USB interface for device %d-%d", bus, address); libusb_free_config_descriptor(config); libusb_close(handle); free(usbdev); return -1; } libusb_free_config_descriptor(config); if((res = libusb_claim_interface(handle, usbdev->interface)) != 0) { usbmuxd_log(LL_WARNING, "Could not claim interface %d for device %d-%d: %d", usbdev->interface, bus, address, res); libusb_close(handle); free(usbdev); return -1; } transfer = libusb_alloc_transfer(0); if(!transfer) { usbmuxd_log(LL_WARNING, "Failed to allocate transfer for device %d-%d: %d", bus, address, res); libusb_close(handle); free(usbdev); return -1; } unsigned char *transfer_buffer = malloc(1024 + LIBUSB_CONTROL_SETUP_SIZE + 8); if (!transfer_buffer) { usbmuxd_log(LL_WARNING, "Failed to allocate transfer buffer for device %d-%d: %d", bus, address, res); libusb_close(handle); free(usbdev); return -1; } memset(transfer_buffer, '\0', 1024 + LIBUSB_CONTROL_SETUP_SIZE + 8); usbdev->serial[0] = 0; usbdev->bus = bus; usbdev->address = address; usbdev->devdesc = devdesc; usbdev->speed = 480000000; usbdev->dev = handle; usbdev->alive = 1; usbdev->wMaxPacketSize = libusb_get_max_packet_size(dev, usbdev->ep_out); if (usbdev->wMaxPacketSize <= 0) { usbmuxd_log(LL_ERROR, "Could not determine wMaxPacketSize for device %d-%d, setting to 64", usbdev->bus, usbdev->address); usbdev->wMaxPacketSize = 64; } else { usbmuxd_log(LL_INFO, "Using wMaxPacketSize=%d for device %d-%d", usbdev->wMaxPacketSize, usbdev->bus, usbdev->address); } switch (libusb_get_device_speed(dev)) { case LIBUSB_SPEED_LOW: usbdev->speed = 1500000; break; case LIBUSB_SPEED_FULL: usbdev->speed = 12000000; break; case LIBUSB_SPEED_SUPER: usbdev->speed = 5000000000; break; case LIBUSB_SPEED_HIGH: case LIBUSB_SPEED_UNKNOWN: default: usbdev->speed = 480000000; break; } usbmuxd_log(LL_INFO, "USB Speed is %g MBit/s for device %d-%d", (double)(usbdev->speed / 1000000.0), usbdev->bus, usbdev->address); /** * From libusb: * Asking for the zero'th index is special - it returns a string * descriptor that contains all the language IDs supported by the * device. **/ libusb_fill_control_setup(transfer_buffer, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR, LIBUSB_DT_STRING << 8, 0, 1024 + LIBUSB_CONTROL_SETUP_SIZE); libusb_fill_control_transfer(transfer, handle, transfer_buffer, get_langid_callback, usbdev, 1000); if((res = libusb_submit_transfer(transfer)) < 0) { usbmuxd_log(LL_ERROR, "Could not request transfer for device %d-%d (%d)", usbdev->bus, usbdev->address, res); libusb_free_transfer(transfer); libusb_close(handle); free(transfer_buffer); free(usbdev); return -1; } collection_init(&usbdev->tx_xfers); collection_init(&usbdev->rx_xfers); collection_add(&device_list, usbdev); return 0; } int usb_discover(void) { int cnt, i; int valid_count = 0; libusb_device **devs; cnt = libusb_get_device_list(NULL, &devs); if(cnt < 0) { usbmuxd_log(LL_WARNING, "Could not get device list: %d", cnt); devlist_failures++; // sometimes libusb fails getting the device list if you've just removed something if(devlist_failures > 5) { usbmuxd_log(LL_FATAL, "Too many errors getting device list"); return cnt; } else { get_tick_count(&next_dev_poll_time); next_dev_poll_time.tv_usec += DEVICE_POLL_TIME * 1000; next_dev_poll_time.tv_sec += next_dev_poll_time.tv_usec / 1000000; next_dev_poll_time.tv_usec = next_dev_poll_time.tv_usec % 1000000; return 0; } } devlist_failures = 0; usbmuxd_log(LL_SPEW, "usb_discover: scanning %d devices", cnt); // Mark all devices as dead, and do a mark-sweep like // collection of dead devices FOREACH(struct usb_device *usbdev, &device_list) { usbdev->alive = 0; } ENDFOREACH // Enumerate all USB devices and mark the ones we already know // about as live, again for(i=0; idev) { 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->devdesc.idProduct; } uint64_t usb_get_speed(struct usb_device *dev) { if (!dev->dev) { return 0; } return dev->speed; } void usb_get_fds(struct fdlist *list) { const struct libusb_pollfd **usbfds; const struct libusb_pollfd **p; usbfds = libusb_get_pollfds(NULL); if(!usbfds) { usbmuxd_log(LL_ERROR, "libusb_get_pollfds failed"); return; } p = usbfds; while(*p) { fdlist_add(list, FD_USB, (*p)->fd, (*p)->events); p++; } free(usbfds); } void usb_autodiscover(int enable) { usbmuxd_log(LL_DEBUG, "usb polling enable: %d", enable); device_polling = enable; device_hotplug = enable; } static int dev_poll_remain_ms(void) { int msecs; struct timeval tv; if(!device_polling) return 100000; // devices will never be polled if this is > 0 get_tick_count(&tv); msecs = (next_dev_poll_time.tv_sec - tv.tv_sec) * 1000; msecs += (next_dev_poll_time.tv_usec - tv.tv_usec) / 1000; if(msecs < 0) return 0; return msecs; } int usb_get_timeout(void) { struct timeval tv; int msec; int res; int pollrem; pollrem = dev_poll_remain_ms(); res = libusb_get_next_timeout(NULL, &tv); if(res == 0) return pollrem; if(res < 0) { usbmuxd_log(LL_ERROR, "libusb_get_next_timeout failed: %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 reap_dead_devices(); 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; get_tick_count(&tcur); tfin.tv_sec = tcur.tv_sec + (msec / 1000); tfin.tv_usec = tcur.tv_usec + (msec % 1000) * 1000; tfin.tv_sec += tfin.tv_usec / 1000000; tfin.tv_usec %= 1000000; while((tfin.tv_sec > tcur.tv_sec) || ((tfin.tv_sec == tcur.tv_sec) && (tfin.tv_usec > tcur.tv_usec))) { tleft.tv_sec = tfin.tv_sec - tcur.tv_sec; tleft.tv_usec = tfin.tv_usec - tcur.tv_usec; if(tleft.tv_usec < 0) { tleft.tv_usec += 1000000; tleft.tv_sec -= 1; } res = libusb_handle_events_timeout(NULL, &tleft); if(res < 0) { usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %d", res); return res; } // reap devices marked dead due to an RX error reap_dead_devices(); get_tick_count(&tcur); } return 0; } #ifdef HAVE_LIBUSB_HOTPLUG_API static libusb_hotplug_callback_handle usb_hotplug_cb_handle; static int usb_hotplug_cb(libusb_context *ctx, libusb_device *device, libusb_hotplug_event event, void *user_data) { if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) { if (device_hotplug) { usb_device_add(device); } } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) { uint8_t bus = libusb_get_bus_number(device); uint8_t address = libusb_get_device_address(device); FOREACH(struct usb_device *usbdev, &device_list) { if(usbdev->bus == bus && usbdev->address == address) { usbdev->alive = 0; device_remove(usbdev); break; } } ENDFOREACH } else { usbmuxd_log(LL_ERROR, "Unhandled event %d", event); } return 0; } #endif int usb_init(void) { int res; usbmuxd_log(LL_DEBUG, "usb_init for linux / libusb 1.0"); devlist_failures = 0; device_polling = 1; res = libusb_init(NULL); //libusb_set_debug(NULL, 3); if(res != 0) { usbmuxd_log(LL_FATAL, "libusb_init failed: %d", res); return -1; } collection_init(&device_list); #ifdef HAVE_LIBUSB_HOTPLUG_API if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { usbmuxd_log(LL_INFO, "Registering for libusb hotplug events"); res = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, LIBUSB_HOTPLUG_ENUMERATE, VID_APPLE, LIBUSB_HOTPLUG_MATCH_ANY, 0, usb_hotplug_cb, NULL, &usb_hotplug_cb_handle); if (res == LIBUSB_SUCCESS) { device_polling = 0; } else { usbmuxd_log(LL_ERROR, "ERROR: Could not register for libusb hotplug events (%d)", res); } } else { usbmuxd_log(LL_ERROR, "libusb does not support hotplug events"); } #endif if (device_polling) { res = usb_discover(); if (res >= 0) { } } else { res = collection_count(&device_list); } return res; } void usb_shutdown(void) { usbmuxd_log(LL_DEBUG, "usb_shutdown"); #ifdef HAVE_LIBUSB_HOTPLUG_API libusb_hotplug_deregister_callback(NULL, usb_hotplug_cb_handle); #endif FOREACH(struct usb_device *usbdev, &device_list) { device_remove(usbdev); usb_disconnect(usbdev); } ENDFOREACH collection_free(&device_list); libusb_exit(NULL); } usbmuxd-1.1.1~git20191130.9af2b12/src/usb.h000066400000000000000000000042431356231277100175340ustar00rootroot00000000000000/* * usb.h * * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Nikias Bassen * Copyright (C) 2009 Martin Szulecki * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef USB_H #define USB_H #include #include "utils.h" #define INTERFACE_CLASS 255 #define INTERFACE_SUBCLASS 254 #define INTERFACE_PROTOCOL 2 // libusb fragments packets larger than this (usbfs limitation) // on input, this creates race conditions and other issues #define USB_MRU 16384 // max transmission packet size // libusb fragments these too, but doesn't send ZLPs so we're safe // but we need to send a ZLP ourselves at the end (see usb-linux.c) // we're using 3 * 16384 to optimize for the fragmentation // this results in three URBs per full transfer, 32 USB packets each // if there are ZLP issues this should make them show up easily too #define USB_MTU (3 * 16384) #define USB_PACKET_SIZE 512 #define VID_APPLE 0x5ac #define PID_RANGE_LOW 0x1290 #define PID_RANGE_MAX 0x12af struct usb_device; int usb_init(void); void usb_shutdown(void); const char *usb_get_serial(struct usb_device *dev); uint32_t usb_get_location(struct usb_device *dev); uint16_t usb_get_pid(struct usb_device *dev); uint64_t usb_get_speed(struct usb_device *dev); void usb_get_fds(struct fdlist *list); int usb_get_timeout(void); int usb_send(struct usb_device *dev, const unsigned char *buf, int length); int usb_discover(void); void usb_autodiscover(int enable); int usb_process(void); int usb_process_timeout(int msec); #endif usbmuxd-1.1.1~git20191130.9af2b12/src/usbmuxd-proto.h000066400000000000000000000046301356231277100215730ustar00rootroot00000000000000/* * usbmuxd-proto.h * * Copyright (C) 2009 Paul Sladen * Copyright (C) 2009 Nikias Bassen * Copyright (C) 2009 Hector Martin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 or version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Protocol defintion for usbmuxd proxy protocol */ #ifndef USBMUXD_PROTO_H #define USBMUXD_PROTO_H #include #define USBMUXD_PROTOCOL_VERSION 0 #if defined(WIN32) || defined(__CYGWIN__) #define USBMUXD_SOCKET_PORT 27015 #else #define USBMUXD_SOCKET_FILE "/var/run/usbmuxd" #endif #ifdef __cplusplus extern "C" { #endif enum usbmuxd_result { RESULT_OK = 0, RESULT_BADCOMMAND = 1, RESULT_BADDEV = 2, RESULT_CONNREFUSED = 3, // ??? // ??? RESULT_BADVERSION = 6, }; enum usbmuxd_msgtype { MESSAGE_RESULT = 1, MESSAGE_CONNECT = 2, MESSAGE_LISTEN = 3, MESSAGE_DEVICE_ADD = 4, MESSAGE_DEVICE_REMOVE = 5, MESSAGE_DEVICE_PAIRED = 6, //??? MESSAGE_PLIST = 8, }; struct usbmuxd_header { uint32_t length; // length of message, including header uint32_t version; // protocol version uint32_t message; // message type uint32_t tag; // responses to this query will echo back this tag } __attribute__((__packed__)); struct usbmuxd_result_msg { struct usbmuxd_header header; uint32_t result; } __attribute__((__packed__)); struct usbmuxd_connect_request { struct usbmuxd_header header; uint32_t device_id; uint16_t port; // TCP port number uint16_t reserved; // set to zero } __attribute__((__packed__)); struct usbmuxd_listen_request { struct usbmuxd_header header; } __attribute__((__packed__)); struct usbmuxd_device_record { uint32_t device_id; uint16_t product_id; char serial_number[256]; uint16_t padding; uint32_t location; } __attribute__((__packed__)); #ifdef __cplusplus } #endif #endif /* USBMUXD_PROTO_H */ usbmuxd-1.1.1~git20191130.9af2b12/src/utils.c000066400000000000000000000175711356231277100201060ustar00rootroot00000000000000/* * utils.c * * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Nikias Bassen * Copyright (c) 2013 Federico Mena Quintero * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #ifdef __APPLE__ #include #endif #include "utils.h" #include "log.h" #define util_error(...) usbmuxd_log(LL_ERROR, __VA_ARGS__) void fdlist_create(struct fdlist *list) { list->count = 0; list->capacity = 4; list->owners = malloc(sizeof(*list->owners) * list->capacity); list->fds = malloc(sizeof(*list->fds) * list->capacity); } void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events) { if(list->count == list->capacity) { list->capacity *= 2; list->owners = realloc(list->owners, sizeof(*list->owners) * list->capacity); list->fds = realloc(list->fds, sizeof(*list->fds) * list->capacity); } list->owners[list->count] = owner; list->fds[list->count].fd = fd; list->fds[list->count].events = events; list->fds[list->count].revents = 0; list->count++; } void fdlist_free(struct fdlist *list) { list->count = 0; list->capacity = 0; free(list->owners); list->owners = NULL; free(list->fds); list->fds = NULL; } void fdlist_reset(struct fdlist *list) { list->count = 0; } #define CAPACITY_STEP 8 void collection_init(struct collection *col) { col->list = malloc(sizeof(void *) * CAPACITY_STEP); memset(col->list, 0, sizeof(void *) * CAPACITY_STEP); col->capacity = CAPACITY_STEP; } void collection_free(struct collection *col) { free(col->list); col->list = NULL; col->capacity = 0; } void collection_add(struct collection *col, void *element) { int i; for(i=0; icapacity; i++) { if(!col->list[i]) { col->list[i] = element; return; } } col->list = realloc(col->list, sizeof(void*) * (col->capacity + CAPACITY_STEP)); memset(&col->list[col->capacity], 0, sizeof(void *) * CAPACITY_STEP); col->list[col->capacity] = element; col->capacity += CAPACITY_STEP; } void collection_remove(struct collection *col, void *element) { int i; for(i=0; icapacity; i++) { if(col->list[i] == element) { col->list[i] = NULL; return; } } util_error("collection_remove: element %p not present in collection %p (cap %d)", element, col, col->capacity); } int collection_count(struct collection *col) { int i, cnt = 0; for(i=0; icapacity; i++) { if(col->list[i]) cnt++; } return cnt; } void collection_copy(struct collection *dest, struct collection *src) { if (!dest || !src) return; dest->capacity = src->capacity; dest->list = malloc(sizeof(void*) * src->capacity); memcpy(dest->list, src->list, sizeof(void*) * src->capacity); } #ifndef HAVE_STPCPY /** * Copy characters from one string into another * * @note: The strings should not overlap, as the behavior is undefined. * * @s1: The source string. * @s2: The destination string. * * @return a pointer to the terminating `\0' character of @s1, * or NULL if @s1 or @s2 is NULL. */ char *stpcpy(char * s1, const char * s2) { if (s1 == NULL || s2 == NULL) return NULL; strcpy(s1, s2); return s1 + strlen(s2); } #endif /** * Concatenate strings into a newly allocated string * * @note: Specify NULL for the last string in the varargs list * * @str: The first string in the list * @...: Subsequent strings. Use NULL for the last item. * * @return a newly allocated string, or NULL if @str is NULL. This will also * return NULL and set errno to ENOMEM if memory is exhausted. */ char *string_concat(const char *str, ...) { size_t len; va_list args; char *s; char *result; char *dest; if (!str) return NULL; /* Compute final length */ len = strlen(str) + 1; /* plus 1 for the null terminator */ va_start(args, str); s = va_arg(args, char *); while (s) { len += strlen(s); s = va_arg(args, char*); } va_end(args); /* Concat each string */ result = malloc(len); if (!result) return NULL; /* errno remains set */ dest = result; dest = stpcpy(dest, str); va_start(args, str); s = va_arg(args, char *); while (s) { dest = stpcpy(dest, s); s = va_arg(args, char *); } va_end(args); return result; } int buffer_read_from_filename(const char *filename, char **buffer, uint64_t *length) { FILE *f; uint64_t size; *length = 0; f = fopen(filename, "rb"); if (!f) { return 0; } fseek(f, 0, SEEK_END); size = ftell(f); rewind(f); if (size == 0) { fclose(f); return 0; } *buffer = (char*)malloc(sizeof(char)*(size+1)); if (!buffer) { return 0; } int ret = 1; if (fread(*buffer, sizeof(char), size, f) != size) { usbmuxd_log(LL_ERROR, "%s: ERROR: couldn't read %d bytes from %s", __func__, (int)size, filename); free(*buffer); ret = 0; errno = EIO; } fclose(f); *length = size; return ret; } int buffer_write_to_filename(const char *filename, const char *buffer, uint64_t length) { FILE *f; f = fopen(filename, "wb"); if (f) { size_t written = fwrite(buffer, sizeof(char), length, f); fclose(f); if (written == length) { return 1; } else { // Not all data could be written. errno = EIO; return 0; } } else { // Failed to open the file, let the caller know. return 0; } } int plist_read_from_filename(plist_t *plist, const char *filename) { char *buffer = NULL; uint64_t length; if (!filename) return 0; if (!buffer_read_from_filename(filename, &buffer, &length)) { return 0; } if ((length > 8) && (memcmp(buffer, "bplist00", 8) == 0)) { plist_from_bin(buffer, length, plist); } else { plist_from_xml(buffer, length, plist); } free(buffer); return 1; } int plist_write_to_filename(plist_t plist, const char *filename, enum plist_format_t format) { char *buffer = NULL; uint32_t length; if (!plist || !filename) return 0; if (format == PLIST_FORMAT_XML) plist_to_xml(plist, &buffer, &length); else if (format == PLIST_FORMAT_BINARY) plist_to_bin(plist, &buffer, &length); else return 0; int res = buffer_write_to_filename(filename, buffer, length); free(buffer); return res; } #ifndef HAVE_CLOCK_GETTIME typedef int clockid_t; #define CLOCK_MONOTONIC 1 static int clock_gettime(clockid_t clk_id, struct timespec *ts) { // See http://developer.apple.com/library/mac/qa/qa1398 uint64_t mach_time, nano_sec; static mach_timebase_info_data_t base_info; mach_time = mach_absolute_time(); if (base_info.denom == 0) { (void) mach_timebase_info(&base_info); } if (base_info.numer == 1 && base_info.denom == 1) nano_sec = mach_time; else nano_sec = mach_time * base_info.numer / base_info.denom; ts->tv_sec = nano_sec / 1000000000; ts->tv_nsec = nano_sec % 1000000000; return 0; } #endif void get_tick_count(struct timeval * tv) { struct timespec ts; if(0 == clock_gettime(CLOCK_MONOTONIC, &ts)) { tv->tv_sec = ts.tv_sec; tv->tv_usec = ts.tv_nsec / 1000; } else { gettimeofday(tv, NULL); } } /** * Get number of milliseconds since the epoch. */ uint64_t mstime64(void) { struct timeval tv; get_tick_count(&tv); // Careful, avoid overflow on 32 bit systems // time_t could be 4 bytes return ((long long)tv.tv_sec) * 1000LL + ((long long)tv.tv_usec) / 1000LL; } usbmuxd-1.1.1~git20191130.9af2b12/src/utils.h000066400000000000000000000051461356231277100201060ustar00rootroot00000000000000/* * utils.h * * Copyright (C) 2009 Hector Martin * Copyright (C) 2009 Nikias Bassen * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef UTILS_H #define UTILS_H #include #include enum fdowner { FD_LISTEN, FD_CLIENT, FD_USB }; struct fdlist { int count; int capacity; enum fdowner *owners; struct pollfd *fds; }; void fdlist_create(struct fdlist *list); void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events); void fdlist_free(struct fdlist *list); void fdlist_reset(struct fdlist *list); 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); void collection_copy(struct collection *dest, struct collection *src); #define MERGE_(a,b) a ## _ ## b #define LABEL_(a,b) MERGE_(a, b) #define UNIQUE_VAR(a) LABEL_(a, __LINE__) #define FOREACH(var, col) \ do { \ int UNIQUE_VAR(_iter); \ for(UNIQUE_VAR(_iter)=0; UNIQUE_VAR(_iter)<(col)->capacity; UNIQUE_VAR(_iter)++) { \ if(!(col)->list[UNIQUE_VAR(_iter)]) continue; \ var = (col)->list[UNIQUE_VAR(_iter)]; #define ENDFOREACH \ } \ } while(0); #ifndef HAVE_STPCPY char *stpcpy(char * s1, const char * s2); #endif char *string_concat(const char *str, ...); int buffer_read_from_filename(const char *filename, char **buffer, uint64_t *length); int buffer_write_to_filename(const char *filename, const char *buffer, uint64_t length); enum plist_format_t { PLIST_FORMAT_XML, PLIST_FORMAT_BINARY }; int plist_read_from_filename(plist_t *plist, const char *filename); int plist_write_to_filename(plist_t plist, const char *filename, enum plist_format_t format); uint64_t mstime64(void); void get_tick_count(struct timeval * tv); #endif usbmuxd-1.1.1~git20191130.9af2b12/systemd/000077500000000000000000000000001356231277100174705ustar00rootroot00000000000000usbmuxd-1.1.1~git20191130.9af2b12/systemd/Makefile.am000066400000000000000000000004641356231277100215300ustar00rootroot00000000000000edit = \ $(SED) -r \ -e 's|@sbindir[@]|$(sbindir)|g' \ -e 's|@localstatedir[@]|$(localstatedir)|g' \ < $< > $@ || rm $@ if WANT_SYSTEMD systemdsystemunit_DATA = \ usbmuxd.service usbmuxd.service: usbmuxd.service.in $(edit) EXTRA_DIST = \ usbmuxd.service.in CLEANFILES = \ usbmuxd.service endif usbmuxd-1.1.1~git20191130.9af2b12/systemd/usbmuxd.service.in000066400000000000000000000003231356231277100231440ustar00rootroot00000000000000[Unit] Description=Socket daemon for the usbmux protocol used by Apple devices Documentation=man:usbmuxd(8) [Service] ExecStart=@sbindir@/usbmuxd --user usbmux --systemd PIDFile=@localstatedir@/run/usbmuxd.pid usbmuxd-1.1.1~git20191130.9af2b12/udev/000077500000000000000000000000001356231277100167435ustar00rootroot00000000000000usbmuxd-1.1.1~git20191130.9af2b12/udev/39-usbmuxd.rules.in000066400000000000000000000016271356231277100223520ustar00rootroot00000000000000# usbmuxd (Apple Mobile Device Muxer listening on /var/run/usbmuxd) # systemd should receive all events relating to device SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*", TAG+="systemd" # Initialize iOS devices into "deactivated" USB configuration state and activate usbmuxd SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*", ACTION=="add", ENV{USBMUX_SUPPORTED}="1", ATTR{bConfigurationValue}="0", OWNER="usbmux", @udev_activation_rule@ # Make sure properties don't get lost when bind action is called SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*", ACTION=="bind", ENV{USBMUX_SUPPORTED}="1", OWNER="usbmux", @udev_activation_rule@ # Exit usbmuxd when the last device is removed SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{PRODUCT}=="5ac/12[9a][0-9a-f]/*", ACTION=="remove", RUN+="@sbindir@/usbmuxd -x" usbmuxd-1.1.1~git20191130.9af2b12/udev/Makefile.am000066400000000000000000000005231356231277100207770ustar00rootroot00000000000000edit = \ $(SED) -r \ -e 's|@udev_activation_rule[@]|$(udev_activation_rule)|g' \ -e 's|@sbindir[@]|$(sbindir)|g' \ < $< > $@ || rm $@ udevrules_DATA = \ 39-usbmuxd.rules 39-usbmuxd.rules: 39-usbmuxd.rules.in $(edit) EXTRA_DIST = \ 39-usbmuxd.rules.in MAINTAINERCLEANFILES = \ 39-usbmuxd.rules CLEANFILES = \ 39-usbmuxd.rules