More spm fixes

This commit is contained in:
Joe Mattiello
2023-03-01 08:52:01 -05:00
parent f3a70e1e47
commit 364b11ec9d
516 changed files with 154395 additions and 803 deletions

View File

@@ -0,0 +1,39 @@
# git-ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
*.[oa]
*~
*.po
*.lo
*.la
autom4te.cache/*
*.in
*/.deps/*
m4/*
swig/*
*.swp
*.patch
aclocal.m4
config.h
config.log
config.sub
config.guess
config.status
configure
depcomp
install-sh
compile
main
ltmain.sh
missing
mkinstalldirs
libtool
*Makefile
py-compile
stamp-h1
src/.libs
docs/html
libusbmuxd.pc
tools/.libs/*
tools/iproxy

View File

@@ -0,0 +1,10 @@
Aaron Burghardt
Bastien Nocera
Cerrato Renaud
Chow Loong Jin
David Sansome
Eric Day
Hector Martin
Martin Szulecki
Nikias Bassen
Paul Sladen

View File

@@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -0,0 +1,6 @@
AUTOMAKE_OPTIONS = foreign
ACLOCAL_AMFLAGS = -I m4
SUBDIRS = common src include tools
pkgconfigdir = $(libdir)/pkgconfig
pkgconfig_DATA = libusbmuxd.pc

View File

@@ -0,0 +1,39 @@
Version 1.0.10
~~~~~~~~~~~~~~
* Changes:
- Retry to connect to usbmuxd socket if first attempt failed (Linux/inotify)
- Avoid exporting non-public symbols
- Allow multiple connections to iproxy listen port
- Add ability to target device by UDID to iproxy
- Remove outdated/unmaintained Python and sftp examples
- Update README and rename license to more generic COPYING
- Rename header guards according to C++ standard
- Fix a few crashes related to using old usbmuxd daemon and broken pair
records
- Fix out of tree build
- Fix leaking socket handles by properly closing them
- Check for validity of socket file descriptor
- Properly handle segmented send/receive situations to improve reliability
Version 1.0.9
~~~~~~~~~~~~~
* Changes:
- Avoid SIGPIPE where possible
- Plugged several memory leaks and invalid frees
- Fixed concurrency issues caused by tag mismatch
- Added new interface functions for pair record management via usbmuxd:
- usbmuxd_read_pair_record()
- usbmuxd_save_pair_record()
- usbmuxd_delete_pair_record()
- usbmuxd_read_buid()
- Made libplist dependency (and thus protocol v1 support) mandatory
- Improved usbmuxd_get_device_list() with new ListDevices usbmuxd command
- Fix various memory leaks
- Add libusbmuxd_set_use_inotify() to control inotify support (Linux)
- Add libusbmuxd_set_debug_level() to enable debugging
- Fixed WIN32 (MinGW) build
This is the first release after the usbmuxd/libusbmuxd project split.

View File

@@ -0,0 +1,70 @@
About
=====
A client library to multiplex connections from and to iOS devices by connecting
to a socket provided by a usbmuxd daemon.
Requirements
============
Development Packages of:
libplist
Software:
usbmuxd (Windows and Mac OS X can use the one provided by iTunes)
make
autoheader
automake
autoconf
libtool
pkg-config
gcc
Optional:
inotify (Linux only)
Installation
============
To compile run:
./autogen.sh
make
sudo make install
If dependent packages cannot be found when running autogen.sh (or configure)
make sure that pkg-config is installed and set the PKG_CONFIG_PATH environment
variable if required. It can be passed directly like this:
PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ./autogen.sh
Who/What/Where?
===============
Home:
http://www.libimobiledevice.org/
Code:
git clone http://git.sukimashita.com/libusbmuxd.git
Code (Mirror):
git clone https://github.com/libimobiledevice/libusbmuxd.git
Tickets:
https://github.com/libimobiledevice/libusbmuxd/issues
Mailing List:
http://lists.libimobiledevice.org/mailman/listinfo/libimobiledevice-devel
IRC:
irc://irc.freenode.net#libimobiledevice
Credits
=======
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:
2017-05-21

View File

@@ -0,0 +1,15 @@
#!/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
if [ -z "$NOCONFIGURE" ]; then
./configure "$@"
fi

View File

@@ -0,0 +1,16 @@
AM_CFLAGS = $(GLOBAL_CFLAGS)
noinst_LTLIBRARIES = libinternalcommon.la
libinternalcommon_la_LIBADD =
libinternalcommon_la_SOURCES = \
socket.c \
thread.c \
collection.c \
socket.h \
thread.h \
collection.h
if WIN32
libinternalcommon_la_LIBADD += -lws2_32
endif

View File

@@ -0,0 +1,81 @@
/*
* collection.c
*
* Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
* Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "collection.h"
void collection_init(struct collection *col)
{
col->list = malloc(sizeof(void *));
memset(col->list, 0, sizeof(void *));
col->capacity = 1;
}
void collection_free(struct collection *col)
{
free(col->list);
col->list = NULL;
col->capacity = 0;
}
void collection_add(struct collection *col, void *element)
{
int i;
for(i=0; i<col->capacity; i++) {
if(!col->list[i]) {
col->list[i] = element;
return;
}
}
col->list = realloc(col->list, sizeof(void*) * col->capacity * 2);
memset(&col->list[col->capacity], 0, sizeof(void *) * col->capacity);
col->list[col->capacity] = element;
col->capacity *= 2;
}
int collection_remove(struct collection *col, void *element)
{
int i;
for(i=0; i<col->capacity; i++) {
if(col->list[i] == element) {
col->list[i] = NULL;
return 0;
}
}
fprintf(stderr, "%s: WARNING: element %p not present in collection %p (cap %d)", __func__, element, col, col->capacity);
return -1;
}
int collection_count(struct collection *col)
{
int i, cnt = 0;
for(i=0; i<col->capacity; i++) {
if(col->list[i])
cnt++;
}
return cnt;
}

View File

@@ -0,0 +1,47 @@
/*
* collection.h
*
* Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
* Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef COLLECTION_H
#define COLLECTION_H
struct collection {
void **list;
int capacity;
};
void collection_init(struct collection *col);
void collection_add(struct collection *col, void *element);
int collection_remove(struct collection *col, void *element);
int collection_count(struct collection *col);
void collection_free(struct collection *col);
#define FOREACH(var, col) \
do { \
int _iter; \
for(_iter=0; _iter<(col)->capacity; _iter++) { \
if(!(col)->list[_iter]) continue; \
var = (col)->list[_iter];
#define ENDFOREACH \
} \
} while(0);
#endif

View File

@@ -0,0 +1,497 @@
/*
* socket.c
*
* Copyright (C) 2012-2018 Nikias Bassen <nikias@gmx.li>
* Copyright (C) 2012 Martin Szulecki <m.szulecki@libimobiledevice.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/stat.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
static int wsa_init = 0;
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#endif
#include "socket.h"
#define RECV_TIMEOUT 20000
#define CONNECT_TIMEOUT 5000
#ifndef ECONNRESET
#define ECONNRESET 108
#endif
static int verbose = 0;
void socket_set_verbose(int level)
{
verbose = level;
}
#ifndef WIN32
int socket_create_unix(const char *filename)
{
struct sockaddr_un name;
int sock;
#ifdef SO_NOSIGPIPE
int yes = 1;
#endif
// remove if still present
unlink(filename);
/* Create the socket. */
sock = socket(PF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket");
return -1;
}
#ifdef SO_NOSIGPIPE
if (setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sock);
return -1;
}
#endif
/* Bind a name to the socket. */
name.sun_family = AF_UNIX;
strncpy(name.sun_path, filename, sizeof(name.sun_path));
name.sun_path[sizeof(name.sun_path) - 1] = '\0';
if (bind(sock, (struct sockaddr*)&name, sizeof(name)) < 0) {
perror("bind");
socket_close(sock);
return -1;
}
if (listen(sock, 10) < 0) {
perror("listen");
socket_close(sock);
return -1;
}
return sock;
}
int socket_connect_unix(const char *filename)
{
struct sockaddr_un name;
int sfd = -1;
struct stat fst;
#ifdef SO_NOSIGPIPE
int yes = 1;
#endif
int bufsize = 0x20000;
// check if socket file exists...
if (stat(filename, &fst) != 0) {
if (verbose >= 2)
fprintf(stderr, "%s: stat '%s': %s\n", __func__, filename,
strerror(errno));
return -1;
}
// ... and if it is a unix domain socket
if (!S_ISSOCK(fst.st_mode)) {
if (verbose >= 2)
fprintf(stderr, "%s: File '%s' is not a socket!\n", __func__,
filename);
return -1;
}
// make a new socket
if ((sfd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
if (verbose >= 2)
fprintf(stderr, "%s: socket: %s\n", __func__, strerror(errno));
return -1;
}
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void*)&bufsize, sizeof(int)) == -1) {
perror("Could not set send buffer for socket");
}
if (setsockopt(sfd, SOL_SOCKET, SO_RCVBUF, (void*)&bufsize, sizeof(int)) == -1) {
perror("Could not set receive buffer for socket");
}
#ifdef SO_NOSIGPIPE
if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#endif
// and connect to 'filename'
name.sun_family = AF_UNIX;
strncpy(name.sun_path, filename, sizeof(name.sun_path));
name.sun_path[sizeof(name.sun_path) - 1] = 0;
if (connect(sfd, (struct sockaddr*)&name, sizeof(name)) < 0) {
socket_close(sfd);
if (verbose >= 2)
fprintf(stderr, "%s: connect: %s\n", __func__,
strerror(errno));
return -1;
}
return sfd;
}
#endif
int socket_create(uint16_t port)
{
int sfd = -1;
int yes = 1;
#ifdef WIN32
WSADATA wsa_data;
if (!wsa_init) {
if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
fprintf(stderr, "WSAStartup failed!\n");
ExitProcess(-1);
}
wsa_init = 1;
}
#endif
struct sockaddr_in saddr;
if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) {
perror("socket()");
return -1;
}
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#ifdef SO_NOSIGPIPE
if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#endif
memset((void *) &saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
saddr.sin_port = htons(port);
if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) {
perror("bind()");
socket_close(sfd);
return -1;
}
if (listen(sfd, 1) == -1) {
perror("listen()");
socket_close(sfd);
return -1;
}
return sfd;
}
int socket_connect(const char *addr, uint16_t port)
{
int sfd = -1;
int yes = 1;
int bufsize = 0x20000;
struct addrinfo hints;
struct addrinfo *result, *rp;
char portstr[8];
int res;
#ifdef WIN32
u_long l_yes = 1;
u_long l_no = 0;
WSADATA wsa_data;
if (!wsa_init) {
if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
fprintf(stderr, "WSAStartup failed!\n");
ExitProcess(-1);
}
wsa_init = 1;
}
#else
int flags = 0;
#endif
if (!addr) {
errno = EINVAL;
return -1;
}
memset(&hints, '\0', sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_TCP;
sprintf(portstr, "%d", port);
res = getaddrinfo(addr, portstr, &hints, &result);
if (res != 0) {
fprintf(stderr, "%s: getaddrinfo: %s\n", __func__, gai_strerror(res));
return -1;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1) {
continue;
}
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
continue;
}
#ifdef WIN32
ioctlsocket(sfd, FIONBIO, &l_yes);
#else
fcntl(sfd, F_SETFL, O_NONBLOCK);
#endif
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1) {
break;
}
#ifdef WIN32
if (WSAGetLastError() == WSAEWOULDBLOCK)
#else
if (errno == EINPROGRESS)
#endif
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(sfd, &fds);
struct timeval timeout;
timeout.tv_sec = CONNECT_TIMEOUT / 1000;
timeout.tv_usec = (CONNECT_TIMEOUT - (timeout.tv_sec * 1000)) * 1000;
if (select(sfd + 1, NULL, &fds, NULL, &timeout) == 1) {
int so_error;
socklen_t len = sizeof(so_error);
getsockopt(sfd, SOL_SOCKET, SO_ERROR, (void*)&so_error, &len);
if (so_error == 0) {
break;
}
}
}
socket_close(sfd);
}
freeaddrinfo(result);
if (rp == NULL) {
if (verbose >= 2)
fprintf(stderr, "%s: Could not connect to %s:%d\n", __func__, addr, port);
return -1;
}
#ifdef WIN32
ioctlsocket(sfd, FIONBIO, &l_no);
#else
flags = fcntl(sfd, F_GETFL, 0);
fcntl(sfd, F_SETFL, flags & (~O_NONBLOCK));
#endif
#ifdef SO_NOSIGPIPE
if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#endif
if (setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(int)) == -1) {
perror("Could not set TCP_NODELAY on socket");
}
if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void*)&bufsize, sizeof(int)) == -1) {
perror("Could not set send buffer for socket");
}
if (setsockopt(sfd, SOL_SOCKET, SO_RCVBUF, (void*)&bufsize, sizeof(int)) == -1) {
perror("Could not set receive buffer for socket");
}
return sfd;
}
int socket_check_fd(int fd, fd_mode fdm, unsigned int timeout)
{
fd_set fds;
int sret;
int eagain;
struct timeval to;
struct timeval *pto;
if (fd < 0) {
if (verbose >= 2)
fprintf(stderr, "ERROR: invalid fd in check_fd %d\n", fd);
return -1;
}
FD_ZERO(&fds);
FD_SET(fd, &fds);
sret = -1;
do {
if (timeout > 0) {
to.tv_sec = (time_t) (timeout / 1000);
to.tv_usec = (time_t) ((timeout - (to.tv_sec * 1000)) * 1000);
pto = &to;
} else {
pto = NULL;
}
eagain = 0;
switch (fdm) {
case FDM_READ:
sret = select(fd + 1, &fds, NULL, NULL, pto);
break;
case FDM_WRITE:
sret = select(fd + 1, NULL, &fds, NULL, pto);
break;
case FDM_EXCEPT:
sret = select(fd + 1, NULL, NULL, &fds, pto);
break;
default:
return -1;
}
if (sret < 0) {
switch (errno) {
case EINTR:
// interrupt signal in select
if (verbose >= 2)
fprintf(stderr, "%s: EINTR\n", __func__);
eagain = 1;
break;
case EAGAIN:
if (verbose >= 2)
fprintf(stderr, "%s: EAGAIN\n", __func__);
break;
default:
if (verbose >= 2)
fprintf(stderr, "%s: select failed: %s\n", __func__,
strerror(errno));
return -1;
}
}
} while (eagain);
return sret;
}
int socket_accept(int fd, uint16_t port)
{
#ifdef WIN32
int addr_len;
#else
socklen_t addr_len;
#endif
int result;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
addr_len = sizeof(addr);
result = accept(fd, (struct sockaddr*)&addr, &addr_len);
return result;
}
int socket_shutdown(int fd, int how)
{
return shutdown(fd, how);
}
int socket_close(int fd) {
#ifdef WIN32
return closesocket(fd);
#else
return close(fd);
#endif
}
int socket_receive(int fd, void *data, size_t length)
{
return socket_receive_timeout(fd, data, length, 0, RECV_TIMEOUT);
}
int socket_peek(int fd, void *data, size_t length)
{
return socket_receive_timeout(fd, data, length, MSG_PEEK, RECV_TIMEOUT);
}
int socket_receive_timeout(int fd, void *data, size_t length, int flags,
unsigned int timeout)
{
int res;
int result;
// check if data is available
res = socket_check_fd(fd, FDM_READ, timeout);
if (res <= 0) {
return res;
}
// if we get here, there _is_ data available
result = recv(fd, data, length, flags);
if (res > 0 && result == 0) {
// but this is an error condition
if (verbose >= 3)
fprintf(stderr, "%s: fd=%d recv returned 0\n", __func__, fd);
return -ECONNRESET;
}
if (result < 0) {
return -errno;
}
return result;
}
int socket_send(int fd, void *data, size_t length)
{
int flags = 0;
#ifdef MSG_NOSIGNAL
flags |= MSG_NOSIGNAL;
#endif
return send(fd, data, length, flags);
}

View File

@@ -0,0 +1,65 @@
/*
* socket.h
*
* Copyright (C) 2012 Martin Szulecki <m.szulecki@libimobiledevice.org>
* Copyright (C) 2012 Nikias Bassen <nikias@gmx.li>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef SOCKET_SOCKET_H
#define SOCKET_SOCKET_H
#include <stdlib.h>
#include <stdint.h>
enum fd_mode {
FDM_READ,
FDM_WRITE,
FDM_EXCEPT
};
typedef enum fd_mode fd_mode;
#ifdef WIN32
#include <winsock2.h>
#define SHUT_RD SD_READ
#define SHUT_WR SD_WRITE
#define SHUT_RDWR SD_BOTH
#else
#include <sys/socket.h>
#endif
#ifndef WIN32
int socket_create_unix(const char *filename);
int socket_connect_unix(const char *filename);
#endif
int socket_create(uint16_t port);
int socket_connect(const char *addr, uint16_t port);
int socket_check_fd(int fd, fd_mode fdm, unsigned int timeout);
int socket_accept(int fd, uint16_t port);
int socket_shutdown(int fd, int how);
int socket_close(int fd);
int socket_receive(int fd, void *data, size_t size);
int socket_peek(int fd, void *data, size_t size);
int socket_receive_timeout(int fd, void *data, size_t size, int flags,
unsigned int timeout);
int socket_send(int fd, void *data, size_t size);
void socket_set_verbose(int level);
#endif /* SOCKET_SOCKET_H */

View File

@@ -0,0 +1,140 @@
/*
* thread.c
*
* Copyright (c) 2012-2019 Nikias Bassen, All Rights Reserved.
* Copyright (c) 2012 Martin Szulecki, All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "thread.h"
int thread_new(THREAD_T *thread, thread_func_t thread_func, void* data)
{
#ifdef WIN32
HANDLE th = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread_func, data, 0, NULL);
if (th == NULL) {
return -1;
}
*thread = th;
return 0;
#else
int res = pthread_create(thread, NULL, thread_func, data);
return res;
#endif
}
void thread_detach(THREAD_T thread)
{
#ifdef WIN32
CloseHandle(thread);
#else
pthread_detach(thread);
#endif
}
void thread_free(THREAD_T thread)
{
#ifdef WIN32
CloseHandle(thread);
#endif
}
int thread_join(THREAD_T thread)
{
/* wait for thread to complete */
#ifdef WIN32
return (int)WaitForSingleObject(thread, INFINITE);
#else
return pthread_join(thread, NULL);
#endif
}
int thread_alive(THREAD_T thread)
{
#ifdef WIN32
return WaitForSingleObject(thread, 0) == WAIT_TIMEOUT;
#else
return pthread_kill(thread, 0) == 0;
#endif
}
int thread_cancel(THREAD_T thread)
{
#ifdef WIN32
return 0;
#else
#ifdef HAVE_PTHREAD_CANCEL
return pthread_cancel(thread);
#else
return 0;
#endif
#endif
}
void mutex_init(mutex_t* mutex)
{
#ifdef WIN32
InitializeCriticalSection(mutex);
#else
pthread_mutex_init(mutex, NULL);
#endif
}
void mutex_destroy(mutex_t* mutex)
{
#ifdef WIN32
DeleteCriticalSection(mutex);
#else
pthread_mutex_destroy(mutex);
#endif
}
void mutex_lock(mutex_t* mutex)
{
#ifdef WIN32
EnterCriticalSection(mutex);
#else
pthread_mutex_lock(mutex);
#endif
}
void mutex_unlock(mutex_t* mutex)
{
#ifdef WIN32
LeaveCriticalSection(mutex);
#else
pthread_mutex_unlock(mutex);
#endif
}
void thread_once(thread_once_t *once_control, void (*init_routine)(void))
{
#ifdef WIN32
while (InterlockedExchange(&(once_control->lock), 1) != 0) {
Sleep(1);
}
if (!once_control->state) {
once_control->state = 1;
init_routine();
}
InterlockedExchange(&(once_control->lock), 0);
#else
pthread_once(once_control, init_routine);
#endif
}

View File

@@ -0,0 +1,76 @@
/*
* thread.h
*
* Copyright (c) 2012-2019 Nikias Bassen, All Rights Reserved.
* Copyright (c) 2012 Martin Szulecki, All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __THREAD_H
#define __THREAD_H
#include <stddef.h>
#ifdef WIN32
#include <windows.h>
typedef HANDLE THREAD_T;
typedef CRITICAL_SECTION mutex_t;
typedef volatile struct {
LONG lock;
int state;
} thread_once_t;
#define THREAD_ONCE_INIT {0, 0}
#define THREAD_ID GetCurrentThreadId()
#define THREAD_T_NULL (THREAD_T)NULL
#else
#include <pthread.h>
#include <signal.h>
typedef pthread_t THREAD_T;
typedef pthread_mutex_t mutex_t;
typedef pthread_once_t thread_once_t;
#define THREAD_ONCE_INIT PTHREAD_ONCE_INIT
#define THREAD_ID pthread_self()
#define THREAD_T_NULL (THREAD_T)NULL
#endif
typedef void* (*thread_func_t)(void* data);
int thread_new(THREAD_T* thread, thread_func_t thread_func, void* data);
void thread_detach(THREAD_T thread);
void thread_free(THREAD_T thread);
int thread_join(THREAD_T thread);
int thread_alive(THREAD_T thread);
int thread_cancel(THREAD_T thread);
#ifdef WIN32
#undef HAVE_THREAD_CLEANUP
#else
#ifdef HAVE_PTHREAD_CANCEL
#define HAVE_THREAD_CLEANUP 1
#define thread_cleanup_push(routine, arg) pthread_cleanup_push(routine, arg)
#define thread_cleanup_pop(execute) pthread_cleanup_pop(execute)
#endif
#endif
void mutex_init(mutex_t* mutex);
void mutex_destroy(mutex_t* mutex);
void mutex_lock(mutex_t* mutex);
void mutex_unlock(mutex_t* mutex);
void thread_once(thread_once_t *once_control, void (*init_routine)(void));
#endif

View File

@@ -0,0 +1,140 @@
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.61)
AC_INIT(libusbmuxd, 1.1.0, nospam@nowhere.com)
AM_INIT_AUTOMAKE([dist-bzip2 no-dist-gzip check-news])
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES])
AC_CONFIG_SRCDIR([src/])
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_MACRO_DIR([m4])
dnl libtool versioning
# +1 : 0 : +1 == adds new functions to the interface
# +1 : 0 : 0 == changes or removes functions (changes include both
# changes to the signature and the semantic)
# ? :+1 : ? == just internal changes
# CURRENT : REVISION : AGE
LIBUSBMUXD_SO_VERSION=5:0:1
dnl Minimum package versions
LIBPLIST_VERSION=1.11
AC_SUBST(LIBUSBMUXD_SO_VERSION)
AC_SUBST(LIBPLIST_VERSION)
AC_GNU_SOURCE
# Checks for programs.
AC_PROG_CC
AC_PROG_CXX
AM_PROG_CC_C_O
AC_PROG_LIBTOOL
# Checks for libraries.
PKG_CHECK_MODULES(libplist, libplist >= $LIBPLIST_VERSION)
AC_CHECK_HEADERS([sys/inotify.h], have_inotify=yes, have_inotify=no)
AC_ARG_WITH([inotify],
[AS_HELP_STRING([--without-inotify],
[(Linux only) do not build with inotify support (default is yes)])],
[with_inotify=no],
[with_inotify=yes])
if test "x$have_inotify" = "xyes"; then
if test "x$with_inotify" != "xyes"; then
have_inotify=no
echo "*** Note: inotify support has been disabled ***"
else
AC_DEFINE(HAVE_INOTIFY, 1, [Define if you have inotify support (linux only)])
fi
fi
# 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
# Checks for library functions.
AC_FUNC_MALLOC
AC_FUNC_REALLOC
AC_CHECK_FUNCS([strcasecmp strdup strerror stpncpy sleep])
# Check for operating system
AC_MSG_CHECKING([for platform-specific build settings])
case ${host_os} in
*mingw32*|*cygwin*)
AC_MSG_RESULT([${host_os}])
win32=true
AC_DEFINE(WINVER, 0x0501, [minimum Windows version])
;;
darwin*)
AC_MSG_RESULT([${host_os}])
AX_PTHREAD([], [AC_MSG_ERROR([pthread is required to build $PACKAGE])])
AC_CHECK_FUNCS([pthread_cancel])
;;
*)
AC_MSG_RESULT([${host_os}])
AX_PTHREAD([], [AC_MSG_ERROR([pthread is required to build $PACKAGE])])
AC_CHECK_FUNCS([pthread_cancel])
AC_CACHE_CHECK(for program_invocation_short_name, ac_cv_program_invocation_short_name,[
AC_TRY_LINK([extern char* program_invocation_short_name;],[return program_invocation_short_name;],
[ac_cv_program_invocation_short_name=yes],
[ac_cv_program_invocation_short_name=no]
)
])
if test "x$ac_cv_program_invocation_short_name" = "xyes"; then
AC_DEFINE(HAVE_PROGRAM_INVOCATION_SHORT_NAME, 1, [Define if you have program_invocation_short_name])
AC_CACHE_CHECK(if program_invocation_short_name is declared in errno.h, ac_cv_program_invocation_short_name_errno_h,[
AC_TRY_LINK([#include <errno.h>],[return program_invocation_short_name;],
[ac_cv_program_invocation_short_name_errno_h=yes],
[ac_cv_program_invocation_short_name_errno_h=no]
)
])
if test "x$ac_cv_program_invocation_short_name_errno_h" = "xyes"; then
AC_DEFINE(HAVE_PROGRAM_INVOCATION_SHORT_NAME_ERRNO_H, 1, [Define if program_invocation_short_name is declared in errno.h])
fi
fi
;;
esac
AM_CONDITIONAL(WIN32, test x$win32 = xtrue)
AS_COMPILER_FLAGS(GLOBAL_CFLAGS, "-Wall -Wextra -Wmissing-declarations -Wredundant-decls -Wshadow -Wpointer-arith -Wwrite-strings -Wswitch-default -Wno-unused-parameter -fvisibility=hidden $PTHREAD_CFLAGS")
GLOBAL_LDFLAGS="$PTHREAD_LIBS"
AC_SUBST(GLOBAL_CFLAGS)
AC_SUBST(GLOBAL_LDFLAGS)
case "$GLOBAL_CFLAGS" in
*-fvisibility=hidden*)
AC_DEFINE([HAVE_FVISIBILITY], [1], [Define if compiled with -fvisibility=hidden])
esac
m4_ifdef([AM_SILENT_RULES],[AM_SILENT_RULES([yes])])
AC_OUTPUT([
Makefile
common/Makefile
src/Makefile
include/Makefile
tools/Makefile
libusbmuxd.pc
])
echo "
Configuration for $PACKAGE $VERSION:
-------------------------------------------
Install prefix: .........: $prefix
inotify support (Linux) .: $have_inotify
Now type 'make' to build $PACKAGE $VERSION,
and then 'make install' for installation.
"

View File

@@ -0,0 +1,4 @@
EXTRA_DIST =
nobase_include_HEADERS = usbmuxd.h \
usbmuxd-proto.h

View File

@@ -0,0 +1,95 @@
/*
* usbmuxd-proto.h - Protocol definition for the usbmux protocol.
*
* Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
* Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
* Copyright (C) 2009 Hector Martin <hector@marcansoft.com>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef USBMUXD_PROTO_H
#define USBMUXD_PROTO_H
#include <stdint.h>
#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 */

View File

@@ -0,0 +1,331 @@
/*
* usbmuxd.h - A client library to talk to the usbmuxd daemon.
*
* Copyright (C) 2009-2018 Nikias Bassen <nikias@gmx.li>
* Copyright (C) 2014 Martin Szulecki <m.szulecki@libimobiledevice.org>
* Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef USBMUXD_H
#define USBMUXD_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Device lookup options for usbmuxd_get_device. */
enum usbmux_lookup_options {
DEVICE_LOOKUP_USBMUX = 1 << 1, /** include USBMUX devices during lookup */
DEVICE_LOOKUP_NETWORK = 1 << 2, /** include network devices during lookup */
DEVICE_LOOKUP_PREFER_NETWORK = 1 << 3 /** prefer network connection if device is available via USBMUX *and* network */
};
/** Type of connection a device is available on */
enum usbmux_connection_type {
CONNECTION_TYPE_USB = 1,
CONNECTION_TYPE_NETWORK
};
/**
* Device information structure holding data to identify the device.
* The relevant 'handle' should be passed to 'usbmuxd_connect()', to
* start a proxy connection. The value 'handle' should be considered
* opaque and no presumption made about the meaning of its value.
*/
typedef struct {
uint32_t handle;
uint32_t product_id;
char udid[44];
enum usbmux_connection_type conn_type;
char conn_data[200];
} usbmuxd_device_info_t;
/**
* event types for event callback function
*/
enum usbmuxd_event_type {
UE_DEVICE_ADD = 1,
UE_DEVICE_REMOVE,
UE_DEVICE_PAIRED
};
/**
* Event structure that will be passed to the callback function.
* 'event' will contains the type of the event, and 'device' will contains
* information about the device.
*/
typedef struct {
int event;
usbmuxd_device_info_t device;
} usbmuxd_event_t;
/**
* Callback function prototype.
*/
typedef void (*usbmuxd_event_cb_t) (const usbmuxd_event_t *event, void *user_data);
/**
* Subscription context type.
*/
typedef struct usbmuxd_subscription_context* usbmuxd_subscription_context_t;
/**
* Subscribe a callback function to be called upon device add/remove events.
* This method can be called multiple times to register multiple callbacks
* since every subscription will have its own context (returned in the
* first parameter).
*
* @param context A pointer to a usbmuxd_subscription_context_t that will be
* set upon creation of the subscription. The returned context must be
* passed to usbmuxd_events_unsubscribe() to unsubscribe the callback.
* @param callback A callback function that is executed when an event occurs.
* @param user_data Custom data passed on to the callback function. The data
* needs to be kept available until the callback function is unsubscribed.
*
* @return 0 on success or a negative errno value.
*/
int usbmuxd_events_subscribe(usbmuxd_subscription_context_t *context, usbmuxd_event_cb_t callback, void *user_data);
/**
* Unsubscribe callback function
*
* @param context A valid context as returned from usbmuxd_events_subscribe().
*
* @return 0 on success or a negative errno value.
*/
int usbmuxd_events_unsubscribe(usbmuxd_subscription_context_t context);
/**
* Subscribe a callback (deprecated)
*
* @param callback A callback function that is executed when an event occurs.
* @param user_data Custom data passed on to the callback function. The data
* needs to be kept available until the callback function is unsubscribed.
*
* @return 0 on success or negative on error.
*
* @note Deprecated. Use usbmuxd_events_subscribe and usbmuxd_events_unsubscribe instead.
* @see usbmuxd_events_subscribe
*/
int usbmuxd_subscribe(usbmuxd_event_cb_t callback, void *user_data);
/**
* Unsubscribe callback (deprecated)
*
* @return 0 on success or negative on error.
*
* @note Deprecated. Use usbmuxd_events_subscribe and usbmuxd_events_unsubscribe instead.
* @see usbmuxd_events_unsubscribe
*/
int usbmuxd_unsubscribe();
/**
* Contacts usbmuxd and retrieves a list of connected devices.
*
* @param device_list A pointer to an array of usbmuxd_device_info_t
* that will hold records of the connected devices. The last record
* is a null-terminated record with all fields set to 0/NULL.
* @note The user has to free the list returned.
*
* @return number of attached devices, zero on no devices, or negative
* if an error occured.
*/
int usbmuxd_get_device_list(usbmuxd_device_info_t **device_list);
/**
* Frees the device list returned by an usbmuxd_get_device_list call
*
* @param device_list A pointer to an array of usbmuxd_device_info_t to free.
*
* @return 0 on success, -1 on error.
*/
int usbmuxd_device_list_free(usbmuxd_device_info_t **device_list);
/**
* Looks up the device specified by UDID and returns device information.
*
* @note This function only considers devices connected through USB. To
* query devices available via network, use usbmuxd_get_device().
*
* @see usbmuxd_get_device
*
* @param udid A device UDID of the device to look for. If udid is NULL,
* This function will return the first device found.
* @param device Pointer to a previously allocated (or static)
* usbmuxd_device_info_t that will be filled with the device info.
*
* @return 0 if no matching device is connected, 1 if the device was found,
* or a negative value on error.
*/
int usbmuxd_get_device_by_udid(const char *udid, usbmuxd_device_info_t *device);
/**
* Looks up the device specified by UDID with given options and returns
* device information.
*
* @param udid A device UDID of the device to look for. If udid is NULL,
* this function will return the first device found.
* @param device Pointer to a previously allocated (or static)
* usbmuxd_device_info_t that will be filled with the device info.
* @param options Specifying what device connection types should be
* considered during lookup. Accepts bitwise or'ed values of
* usbmux_lookup_options.
* If 0 (no option) is specified it will default to DEVICE_LOOKUP_USBMUX.
* To lookup both USB and network-connected devices, pass
* DEVICE_LOOKUP_USBMUX | DEVICE_LOOKUP_NETWORK. If a device is available
* both via USBMUX *and* network, it will select the USB connection.
* This behavior can be changed by adding DEVICE_LOOKUP_PREFER_NETWORK
* to the options in which case it will select the network connection.
*
* @see enum usbmux_lookup_options
*
* @return 0 if no matching device is connected, 1 if the device was found,
* or a negative value on error.
*/
int usbmuxd_get_device(const char *udid, usbmuxd_device_info_t *device, enum usbmux_lookup_options options);
/**
* Request proxy connection to the specified device and port.
*
* @param handle returned in the usbmux_device_info_t structure via
* usbmuxd_get_device() or usbmuxd_get_device_list().
*
* @param tcp_port TCP port number on device, in range 0-65535.
* common values are 62078 for lockdown, and 22 for SSH.
*
* @return socket file descriptor of the connection, or a negative errno
* value on error.
*/
int usbmuxd_connect(const uint32_t handle, const unsigned short tcp_port);
/**
* Disconnect. For now, this just closes the socket file descriptor.
*
* @param sfd socket file descriptor returned by usbmuxd_connect()
*
* @return 0 on success, -1 on error.
*/
int usbmuxd_disconnect(int sfd);
/**
* Send data to the specified socket.
*
* @param sfd socket file descriptor returned by usbmuxd_connect()
* @param data buffer to send
* @param len size of buffer to send
* @param sent_bytes how many bytes sent
*
* @return 0 on success, a negative errno value otherwise.
*/
int usbmuxd_send(int sfd, const char *data, uint32_t len, uint32_t *sent_bytes);
/**
* Receive data from the specified socket.
*
* @param sfd socket file descriptor returned by usbmuxd_connect()
* @param data buffer to put the data to
* @param len number of bytes to receive
* @param recv_bytes number of bytes received
* @param timeout how many milliseconds to wait for data
*
* @return 0 on success, a negative errno value otherwise.
*/
int usbmuxd_recv_timeout(int sfd, char *data, uint32_t len, uint32_t *recv_bytes, unsigned int timeout);
/**
* Receive data from the specified socket with a default timeout.
*
* @param sfd socket file descriptor returned by usbmuxd_connect()
* @param data buffer to put the data to
* @param len number of bytes to receive
* @param recv_bytes number of bytes received
*
* @return 0 on success, a negative errno value otherwise.
*/
int usbmuxd_recv(int sfd, char *data, uint32_t len, uint32_t *recv_bytes);
/**
* Reads the SystemBUID
*
* @param buid pointer to a variable that will be set to point to a newly
* allocated string with the System BUID returned by usbmuxd
*
* @return 0 on success, a negative errno value otherwise.
*/
int usbmuxd_read_buid(char** buid);
/**
* Read a pairing record
*
* @param record_id the record identifier of the pairing record to retrieve
* @param record_data pointer to a variable that will be set to point to a
* newly allocated buffer containing the pairing record data
* @param record_size pointer to a variable that will be set to the size of
* the buffer returned in record_data
*
* @return 0 on success, a negative error value otherwise.
*/
int usbmuxd_read_pair_record(const char* record_id, char **record_data, uint32_t *record_size);
/**
* Save a pairing record
*
* @param record_id the record identifier of the pairing record to save
* @param record_data buffer containing the pairing record data
* @param record_size size of the buffer passed in record_data
*
* @return 0 on success, a negative error value otherwise.
*/
int usbmuxd_save_pair_record(const char* record_id, const char *record_data, uint32_t record_size);
/**
* Save a pairing record with device identifier
*
* @param record_id the record identifier of the pairing record to save
* @param device_id the device identifier of the connected device, or 0
* @param record_data buffer containing the pairing record data
* @param record_size size of the buffer passed in record_data
*
* @return 0 on success, a negative error value otherwise.
*/
int usbmuxd_save_pair_record_with_device_id(const char* record_id, uint32_t device_id, const char *record_data, uint32_t record_size);
/**
* Delete a pairing record
*
* @param record_id the record identifier of the pairing record to delete.
*
* @return 0 on success, a negative errno value otherwise.
*/
int usbmuxd_delete_pair_record(const char* record_id);
/**
* Enable or disable the use of inotify extension. Enabled by default.
* Use 0 to disable and 1 to enable inotify support.
* This only has an effect on linux systems if inotify support has been built
* in. Otherwise and on all other platforms this function has no effect.
*/
void libusbmuxd_set_use_inotify(int set);
void libusbmuxd_set_debug_level(int level);
#ifdef __cplusplus
}
#endif
#endif /* USBMUXD_H */

View File

@@ -0,0 +1,14 @@
AM_CPPFLAGS = -I$(top_srcdir)/include -I$(top_srcdir)/common
AM_CFLAGS = $(GLOBAL_CFLAGS) $(libplist_CFLAGS)
AM_LDFLAGS = $(GLOBAL_LIBS) $(libplist_LIBS)
lib_LTLIBRARIES = libusbmuxd.la
libusbmuxd_la_LDFLAGS = $(AM_LDFLAGS) -version-info $(LIBUSBMUXD_SO_VERSION) -no-undefined
libusbmuxd_la_LIBADD = $(top_builddir)/common/libinternalcommon.la
libusbmuxd_la_SOURCES = libusbmuxd.c
if WIN32
libusbmuxd_la_LDFLAGS += -avoid-version -static-libgcc
libusbmuxd_la_LIBADD += -lws2_32
endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
AM_CFLAGS = $(GLOBAL_CFLAGS) -I$(top_srcdir)/common -I$(top_srcdir)/src -I$(top_srcdir)/include
AM_LDFLAGS = $(libpthread_LIBS)
bin_PROGRAMS = iproxy
iproxy_SOURCES = iproxy.c
iproxy_CFLAGS = $(AM_CFLAGS)
iproxy_LDFLAGS = $(AM_LDFLAGS)
iproxy_LDADD = $(top_builddir)/src/libusbmuxd.la $(top_builddir)/common/libinternalcommon.la

View File

@@ -0,0 +1,317 @@
/*
* iproxy.c -- proxy that enables tcp service access to iOS devices
*
* Copyright (C) 2014 Martin Szulecki <m.szulecki@libimobiledevice.org>
* Copyright (C) 2009 Nikias Bassen <nikias@gmx.li>
* Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org>
*
* Based upon iTunnel source code, Copyright (c) 2008 Jing Su.
* http://www.cs.toronto.edu/~jingsu/itunnel/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <stddef.h>
#include <unistd.h>
#include <errno.h>
#ifdef WIN32
#include <windows.h>
#include <winsock2.h>
typedef unsigned int socklen_t;
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <netinet/in.h>
#endif
#include "socket.h"
#include "usbmuxd.h"
static uint16_t listen_port = 0;
static uint16_t device_port = 0;
static char* device_udid = NULL;
struct client_data {
int fd;
int sfd;
volatile int stop_ctos;
volatile int stop_stoc;
};
static void *run_stoc_loop(void *arg)
{
struct client_data *cdata = (struct client_data*)arg;
int recv_len;
int sent;
char buffer[131072];
printf("%s: fd = %d\n", __func__, cdata->fd);
while (!cdata->stop_stoc && cdata->fd > 0 && cdata->sfd > 0) {
recv_len = socket_receive_timeout(cdata->sfd, buffer, sizeof(buffer), 0, 5000);
if (recv_len <= 0) {
if (recv_len == 0) {
// try again
continue;
} else {
fprintf(stderr, "recv failed: %s\n", strerror(-recv_len));
break;
}
} else {
// send to socket
sent = socket_send(cdata->fd, buffer, recv_len);
if (sent < recv_len) {
if (sent <= 0) {
fprintf(stderr, "send failed: %s\n", strerror(errno));
break;
} else {
fprintf(stderr, "only sent %d from %d bytes\n", sent, recv_len);
}
}
}
}
socket_close(cdata->fd);
cdata->fd = -1;
cdata->stop_ctos = 1;
return NULL;
}
static void *run_ctos_loop(void *arg)
{
struct client_data *cdata = (struct client_data*)arg;
int recv_len;
int sent;
char buffer[131072];
#ifdef WIN32
HANDLE stoc = NULL;
#else
pthread_t stoc;
#endif
printf("%s: fd = %d\n", __func__, cdata->fd);
cdata->stop_stoc = 0;
#ifdef WIN32
stoc = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)run_stoc_loop, cdata, 0, NULL);
#else
pthread_create(&stoc, NULL, run_stoc_loop, cdata);
#endif
while (!cdata->stop_ctos && cdata->fd>0 && cdata->sfd>0) {
recv_len = socket_receive_timeout(cdata->fd, buffer, sizeof(buffer), 0, 5000);
if (recv_len <= 0) {
if (recv_len == 0) {
// try again
continue;
} else {
fprintf(stderr, "recv failed: %s\n", strerror(-recv_len));
break;
}
} else {
// send to local socket
sent = socket_send(cdata->sfd, buffer, recv_len);
if (sent < recv_len) {
if (sent <= 0) {
fprintf(stderr, "send failed: %s\n", strerror(errno));
break;
} else {
fprintf(stderr, "only sent %d from %d bytes\n", sent, recv_len);
}
}
}
}
socket_close(cdata->fd);
cdata->fd = -1;
cdata->stop_stoc = 1;
#ifdef WIN32
WaitForSingleObject(stoc, INFINITE);
#else
pthread_join(stoc, NULL);
#endif
return NULL;
}
static void *acceptor_thread(void *arg)
{
struct client_data *cdata;
usbmuxd_device_info_t *dev_list = NULL;
#ifdef WIN32
HANDLE ctos = NULL;
#else
pthread_t ctos;
#endif
int count;
if (!arg) {
fprintf(stderr, "invalid client_data provided!\n");
return NULL;
}
cdata = (struct client_data*)arg;
if ((count = usbmuxd_get_device_list(&dev_list)) < 0) {
printf("Connecting to usbmuxd failed, terminating.\n");
free(dev_list);
if (cdata->fd > 0) {
socket_close(cdata->fd);
}
free(cdata);
return NULL;
}
fprintf(stdout, "Number of available devices == %d\n", count);
if (dev_list == NULL || dev_list[0].handle == 0) {
printf("No connected device found, terminating.\n");
free(dev_list);
if (cdata->fd > 0) {
socket_close(cdata->fd);
}
free(cdata);
return NULL;
}
usbmuxd_device_info_t *dev = NULL;
if (device_udid) {
int i;
for (i = 0; i < count; i++) {
if (strncmp(dev_list[i].udid, device_udid, sizeof(dev_list[0].udid)) == 0) {
dev = &(dev_list[i]);
break;
}
}
} else {
dev = &(dev_list[0]);
}
if (dev == NULL || dev->handle == 0) {
printf("No connected/matching device found, disconnecting client.\n");
free(dev_list);
if (cdata->fd > 0) {
socket_close(cdata->fd);
}
free(cdata);
return NULL;
}
fprintf(stdout, "Requesting connecion to device handle == %d (serial: %s), port %d\n", dev->handle, dev->udid, device_port);
cdata->sfd = usbmuxd_connect(dev->handle, device_port);
free(dev_list);
if (cdata->sfd < 0) {
fprintf(stderr, "Error connecting to device!\n");
} else {
cdata->stop_ctos = 0;
#ifdef WIN32
ctos = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)run_ctos_loop, cdata, 0, NULL);
WaitForSingleObject(ctos, INFINITE);
#else
pthread_create(&ctos, NULL, run_ctos_loop, cdata);
pthread_join(ctos, NULL);
#endif
}
if (cdata->fd > 0) {
socket_close(cdata->fd);
}
if (cdata->sfd > 0) {
socket_close(cdata->sfd);
}
free(cdata);
return NULL;
}
int main(int argc, char **argv)
{
int mysock = -1;
if (argc < 3) {
printf("usage: %s LOCAL_TCP_PORT DEVICE_TCP_PORT [UDID]\n", argv[0]);
return 0;
}
listen_port = atoi(argv[1]);
device_port = atoi(argv[2]);
if (argc > 3) {
device_udid = argv[3];
}
if (!listen_port) {
fprintf(stderr, "Invalid listen_port specified!\n");
return -EINVAL;
}
if (!device_port) {
fprintf(stderr, "Invalid device_port specified!\n");
return -EINVAL;
}
// first create the listening socket endpoint waiting for connections.
mysock = socket_create(listen_port);
if (mysock < 0) {
fprintf(stderr, "Error creating socket: %s\n", strerror(errno));
return -errno;
} else {
#ifdef WIN32
HANDLE acceptor = NULL;
#else
pthread_t acceptor;
#endif
struct client_data *cdata;
int c_sock;
while (1) {
printf("waiting for connection\n");
c_sock = socket_accept(mysock, listen_port);
if (c_sock) {
printf("accepted connection, fd = %d\n", c_sock);
cdata = (struct client_data*)malloc(sizeof(struct client_data));
if (!cdata) {
socket_close(c_sock);
fprintf(stderr, "ERROR: Out of memory\n");
return -1;
}
cdata->fd = c_sock;
#ifdef WIN32
acceptor = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)acceptor_thread, cdata, 0, NULL);
CloseHandle(acceptor);
#else
pthread_create(&acceptor, NULL, acceptor_thread, cdata);
pthread_detach(acceptor);
#endif
} else {
break;
}
}
socket_close(c_sock);
socket_close(mysock);
}
return 0;
}