From 71d8775f865b431135cd3c178763d0a294b8ff9e Mon Sep 17 00:00:00 2001 From: Nikias Bassen Date: Fri, 20 Feb 2009 11:24:52 +0100 Subject: initial import --- Makefile | 26 ++ iphone.c | 1089 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ iphone.h | 79 +++++ iproxy.c | 329 ++++++++++++++++++ sock_stuff.c | 277 +++++++++++++++ sock_stuff.h | 27 ++ testclient.c | 148 ++++++++ usbmuxd.c | 795 ++++++++++++++++++++++++++++++++++++++++++ usbmuxd.h | 44 +++ 9 files changed, 2814 insertions(+) create mode 100644 Makefile create mode 100644 iphone.c create mode 100644 iphone.h create mode 100644 iproxy.c create mode 100644 sock_stuff.c create mode 100644 sock_stuff.h create mode 100644 testclient.c create mode 100644 usbmuxd.c create mode 100644 usbmuxd.h diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..04a36b3 --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +TARGET=usbmuxd +CFLAGS=-Wall +LDFLAGS=-lpthread -lusb -lrt + +objects = sock_stuff.o usbmuxd.o iphone.o + +all: $(TARGET) + +%.o: %.c %.h + $(CC) -o $@ $(CFLAGS) -c $< + +$(TARGET): $(objects) + $(CC) -o $@ $(LDFLAGS) $^ + +clean: + rm -f *.o $(TARGET) + +realclean: clean + rm -f *~ + +testclient: testclient.c sock_stuff.o + $(CC) $(LDFLAGS) -o testclient $(CFLAGS) $< sock_stuff.o + +iproxy: iproxy.c sock_stuff.o + $(CC) -lpthread -o iproxy $(CFLAGS) $< sock_stuff.o + diff --git a/iphone.c b/iphone.c new file mode 100644 index 0000000..9035be9 --- /dev/null +++ b/iphone.c @@ -0,0 +1,1089 @@ +/* + * Copyright (c) 2008 Jing Su. 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 + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "iphone.h" + +#define BULKIN 0x85 +#define BULKOUT 0x04 +#define HEADERLEN 28 + +typedef uint16_t uint16; +typedef uint32_t uint32; +typedef uint8_t uint8; + +static const uint8 TCP_FIN = 1; +static const uint8 TCP_SYN = 1 << 1; +static const uint8 TCP_RST = 1 << 2; +static const uint8 TCP_PSH = 1 << 3; +static const uint8 TCP_ACK = 1 << 4; +static const uint8 TCP_URG = 1 << 5; + +// I have trouble figuring out how to properly manage the windowing to +// the iPhone. It keeps sending back 512 and seems to drop off a cliff +// when the phone gets overwhelmed. In addition, the phone likes to +// panic and send out RESETS before the window hits zero. Also, waiting +// for responses seems to not be a winning strategy. +// +// Since I'm not sure how in the hell to interpret the window sizes that +// the phone is sending back to us, I've figured out some magic number +// constants which seem to work okay. +static const uint32 WINDOW_MAX = 5 * 1024; +static const uint32 WINDOW_INCREMENT = 512; + + +struct iphone_device_int { + char *buffer; + struct usb_dev_handle *device; + struct usb_device *__device; +}; + +typedef struct { + uint32 type, length, major, minor, allnull; +} usbmux_version_header; + +typedef struct { + uint32 type, length; + uint16 sport, dport; + uint32 scnt, ocnt; + uint8 offset, tcp_flags; + uint16 window, nullnull, length16; +} usbmux_tcp_header; + +struct iphone_umux_client_int { + usbmux_tcp_header *header; + iphone_device_t phone; + + char *recv_buffer; + int r_len; + pthread_cond_t wait; + + // this contains a conditional variable which usb-writers can wait + // on while waiting for window updates from the phone. + pthread_cond_t wr_wait; + // I'm going to do something really cheesy here. We are going to + // just record the most recent scnt that we are expecting to hear + // back on. We will actually halt progress by limiting the number + // of outstanding un-acked bulk sends that we have beamed out. + uint32 wr_pending_scnt; + long wr_window; + + pthread_mutex_t mutex; + + // this variable is not protected by the mutex. This will always + // be E_SUCCESS, unless an error of some kind breaks this stream. + // this will then be set to the error that caused the broken stream. + // no further operations other than free_client will be allowed. + iphone_error_t error; +}; + + +typedef struct { + char* buffer; + int leftover; + int capacity; +} receivebuf_t; + + +static pthread_mutex_t iphonemutex = PTHREAD_MUTEX_INITIALIZER; +static iphone_umux_client_t *connlist = NULL; +static int clients = 0; +static receivebuf_t usbReceive = {NULL, 0, 0}; + + +/** + */ +int toto_debug = 0; +void log_debug_msg(const char *format, ...) +{ +#ifndef STRIP_DEBUG_CODE + + va_list args; + /* run the real fprintf */ + va_start(args, format); + + if (toto_debug) + fprintf(stderr, format, args); + + va_end(args); + +#endif +} + + +/** Creates a USBMux header containing version information + * + * @return A USBMux header + */ +usbmux_version_header *version_header() +{ + usbmux_version_header *version = (usbmux_version_header *) malloc(sizeof(usbmux_version_header)); + version->type = 0; + version->length = htonl(20); + version->major = htonl(1); + version->minor = 0; + version->allnull = 0; + return version; +} + +/** + * This function sets the configuration of the given device to 3 + * and claims the interface 1. If usb_set_configuration fails, it detaches + * the kernel driver that blocks the device, and retries configuration. + * + * @param phone which device to configure + */ +static iphone_error_t iphone_config_usb_device(iphone_device_t phone) +{ + int ret; + int bytes; + char buf[512]; + + log_debug_msg("setting configuration...\n"); + ret = usb_set_configuration(phone->device, 3); + if (ret != 0) { + log_debug_msg("Hm, usb_set_configuration returned %d: %s\n", ret, strerror(-ret)); +#if LIBUSB_HAS_GET_DRIVER_NP + log_debug_msg("trying to fix:\n"); + log_debug_msg("-> detaching kernel driver... "); + ret = usb_detach_kernel_driver_np(phone->device, phone->__device->config->interface->altsetting->bInterfaceNumber); + if (ret != 0) { + log_debug_msg("usb_detach_kernel_driver_np returned %d: %s\n", ret, strerror(-ret)); + } else { + log_debug_msg("done.\n"); + log_debug_msg("setting configuration again... "); + ret = usb_set_configuration(phone->device, 3); + if (ret != 0) { + log_debug_msg("Error: usb_set_configuration returned %d: %s\n", ret, strerror(-ret)); + log_debug_msg("--> trying to continue anyway...\n"); + } else { + log_debug_msg("done.\n"); + } + } +#else + log_debug_msg("--> trying to continue anyway...\n"); +#endif + } else { + log_debug_msg("done.\n"); + } + + log_debug_msg("claiming interface... "); + ret = usb_claim_interface(phone->device, 1); + if (ret != 0) { + log_debug_msg("Error: usb_claim_interface returned %d: %s\n", ret, strerror(-ret)); + return IPHONE_E_NO_DEVICE; + } else { + log_debug_msg("done.\n"); + } + + do { + bytes = usb_bulk_read(phone->device, BULKIN, buf, 512, 800); + } while (bytes > 0); + + return IPHONE_E_SUCCESS; +} + +/** + * Given a USB bus and device number, returns a device handle to the iPhone on + * that bus. To aid compatibility with future devices, this function does not + * check the vendor and device IDs! To do that, you should use + * iphone_get_device() or a system-specific API (e.g. HAL). + * + * @param bus_n The USB bus number. + * @param dev_n The USB device number. + * @param device A pointer to a iphone_device_t, which must be set to NULL upon + * calling iphone_get_specific_device, which will be filled with a device + * descriptor on return. + * @return IPHONE_E_SUCCESS if ok, otherwise an error code. + */ +iphone_error_t iphone_get_specific_device(int bus_n, int dev_n, iphone_device_t * device) +{ + struct usb_bus *bus, *busses; + struct usb_device *dev; + usbmux_version_header *version; + int bytes = 0; + + //check we can actually write in device + if (!device || (device && *device)) + return IPHONE_E_INVALID_ARG; + + iphone_device_t phone = (iphone_device_t) malloc(sizeof(struct iphone_device_int)); + + // Initialize the struct + phone->device = NULL; + phone->__device = NULL; + phone->buffer = NULL; + + // Initialize libusb + usb_init(); + usb_find_busses(); + usb_find_devices(); + busses = usb_get_busses(); + + // Set the device configuration + for (bus = busses; bus; bus = bus->next) + if (bus->location == bus_n) + for (dev = bus->devices; dev != NULL; dev = dev->next) + if (dev->devnum == dev_n) { + phone->__device = dev; + phone->device = usb_open(phone->__device); + iphone_config_usb_device(phone); + goto found; + } + + iphone_free_device(phone); + + log_debug_msg("iphone_get_specific_device: iPhone not found\n"); + return IPHONE_E_NO_DEVICE; + + found: + // Send the version command to the phone + version = version_header(); + bytes = usb_bulk_write(phone->device, BULKOUT, (char *) version, sizeof(*version), 800); + if (bytes < 20) { + log_debug_msg("get_iPhone(): libusb did NOT send enough!\n"); + if (bytes < 0) { + log_debug_msg("get_iPhone(): libusb gave me the error %d: %s (%s)\n", + bytes, usb_strerror(), strerror(-bytes)); + } + } + // Read the phone's response + bytes = usb_bulk_read(phone->device, BULKIN, (char *) version, sizeof(*version), 800); + + // Check for bad response + if (bytes < 20) { + free(version); + iphone_free_device(phone); + log_debug_msg("get_iPhone(): Invalid version message -- header too short.\n"); + if (bytes < 0) + log_debug_msg("get_iPhone(): libusb error message %d: %s (%s)\n", bytes, usb_strerror(), strerror(-bytes)); + return IPHONE_E_NOT_ENOUGH_DATA; + } + // Check for correct version + if (ntohl(version->major) == 1 && ntohl(version->minor) == 0) { + // We're all ready to roll. + fprintf(stderr, "get_iPhone() success\n"); + free(version); + *device = phone; + return IPHONE_E_SUCCESS; + } else { + // Bad header + iphone_free_device(phone); + free(version); + log_debug_msg("get_iPhone(): Received a bad header/invalid version number."); + return IPHONE_E_BAD_HEADER; + } + + // If it got to this point it's gotta be bad + log_debug_msg("get_iPhone(): Unknown error.\n"); + iphone_free_device(phone); + free(version); + return IPHONE_E_UNKNOWN_ERROR; // if it got to this point it's gotta be bad +} + + +/** + * Scans all USB busses and devices for a known AFC-compatible device and + * returns a handle to the first such device it finds. Known devices include + * those with vendor ID 0x05ac and product ID between 0x1290 and 0x1293 + * inclusive. + * + * This function is convenient, but on systems where higher-level abstractions + * (such as HAL) are available it may be preferable to use + * iphone_get_specific_device instead, because it can deal with multiple + * connected devices as well as devices not known to libiphone. + * + * @param device Upon calling this function, a pointer to a location of type + * iphone_device_t, which must have the value NULL. On return, this location + * will be filled with a handle to the device. + * @return IPHONE_E_SUCCESS if ok, otherwise an error code. + */ +iphone_error_t iphone_get_device(iphone_device_t * device) +{ + struct usb_bus *bus; + struct usb_device *dev; + + pthread_mutex_init(&iphonemutex, NULL); + + usb_init(); + usb_find_busses(); + usb_find_devices(); + + for (bus = usb_get_busses(); bus != NULL; bus = bus->next) + for (dev = bus->devices; dev != NULL; dev = dev->next) + if (dev->descriptor.idVendor == 0x05ac + && dev->descriptor.idProduct >= 0x1290 && dev->descriptor.idProduct <= 0x1293) + return iphone_get_specific_device(bus->location, dev->devnum, device); + + return IPHONE_E_NO_DEVICE; +} + +/** Cleans up an iPhone structure, then frees the structure itself. + * This is a library-level function; deals directly with the iPhone to tear + * down relations, but otherwise is mostly internal. + * + * @param phone A pointer to an iPhone structure. + */ +iphone_error_t iphone_free_device(iphone_device_t device) +{ + char buf[512]; + int bytes; + + if (!device) + return IPHONE_E_INVALID_ARG; + iphone_error_t ret = IPHONE_E_UNKNOWN_ERROR; + + do { + bytes = usb_bulk_read(device->device, BULKIN, buf, 512, 800); + } while (bytes > 0); + + if (device->buffer) { + free(device->buffer); + } + if (device->device) { + usb_release_interface(device->device, 1); + usb_close(device->device); + ret = IPHONE_E_SUCCESS; + } + free(device); + + pthread_mutex_destroy(&iphonemutex); + + return ret; +} + + + +/** Sends data to the phone + * This is a low-level (i.e. directly to phone) function. + * + * @param phone The iPhone to send data to + * @param data The data to send to the iPhone + * @param datalen The length of the data + * @return The number of bytes sent, or -ERRNO on error + */ +int send_to_phone(iphone_device_t phone, char *data, int datalen) +{ + if (!phone) + return -1; + + int timeout = 1000; + int retrycount = 0; + int bytes = 0; + do { + if (retrycount > 3) { + fprintf(stderr, "EPIC FAIL! aborting on retry count overload.\n"); + return -1; + } + + bytes = usb_bulk_write(phone->device, BULKOUT, data, datalen, timeout); + if (bytes == -ETIMEDOUT) { + // timed out waiting for write. + fprintf(stderr, "usb_bulk_write timeout error.\n"); + return bytes; + } + else if (bytes < 0) { + fprintf(stderr, "usb_bulk_write failed with error. err:%d (%s)(%s)\n", + bytes, usb_strerror(), strerror(-bytes)); + return -1; + } + else if (bytes == 0) { + fprintf(stderr, "usb_bulk_write sent nothing. retrying.\n"); + timeout = timeout * 4; + retrycount++; + continue; + } + else if (bytes < datalen) { + fprintf(stderr, "usb_bulk_write failed to send full dataload. %d of %d\n", bytes, datalen); + timeout = timeout * 4; + retrycount++; + data += bytes; + datalen -= bytes; + continue; + } + } + while(0); // fall out + + return bytes; +} + +/** + */ +int recv_from_phone_timeout(iphone_device_t phone, char *data, int datalen, int timeoutmillis) +{ + if (!phone) + return -1; + int bytes = 0; + + if (!phone) + return -1; + log_debug_msg("recv_from_phone(): attempting to receive %i bytes\n", datalen); + + bytes = usb_bulk_read(phone->device, BULKIN, data, datalen, timeoutmillis); + if (bytes < 0) { + // there are some things which are errors, others which are no problem. + // it's not documented in libUSB, but it seems that the error returns are + // just negated ERRNO values. + if (bytes == -ETIMEDOUT) { + // ignore this. it just means timeout reached before we + // picked up any data. no problem. + } + else { + fprintf(stderr, "recv_from_phone(): libusb gave me the error %d: %s (%s)\n", bytes, usb_strerror(), + strerror(-bytes)); + log_debug_msg("recv_from_phone(): libusb gave me the error %d: %s (%s)\n", bytes, usb_strerror(), + strerror(-bytes)); + } + return -1; + } + + return bytes; +} + +/** This function is a low-level (i.e. direct to iPhone) function. + * + * @param phone The iPhone to receive data from + * @param data Where to put data read + * @param datalen How much data to read in + * + * @return How many bytes were read in, or -1 on error. + */ +int recv_from_phone(iphone_device_t phone, char *data, int datalen) { + return recv_from_phone_timeout(phone, data, datalen, 100); +} + + +/** Creates a USBMux packet for the given set of ports. + * + * @param s_port The source port for the connection. + * @param d_port The destination port for the connection. + * + * @return A USBMux packet + */ +usbmux_tcp_header *new_mux_packet(uint16 s_port, uint16 d_port) +{ + usbmux_tcp_header *conn = (usbmux_tcp_header *) malloc(sizeof(usbmux_tcp_header)); + conn->type = htonl(6); + conn->length = HEADERLEN; + conn->sport = htons(s_port); + conn->dport = htons(d_port); + conn->scnt = 0; + conn->ocnt = 0; + conn->offset = 0x50; + conn->window = htons(0x0200); + conn->nullnull = 0x0000; + conn->length16 = HEADERLEN; + return conn; +} + + +/** Removes a connection from the list of connections made. + * The list of connections is necessary for buffering. + * + * @param connection The connection to delete from the tracking list. + */ +static void delete_connection(iphone_umux_client_t connection) +{ + pthread_mutex_lock(&iphonemutex); + + // update the global list of connections + iphone_umux_client_t *newlist = (iphone_umux_client_t *) malloc(sizeof(iphone_umux_client_t) * (clients - 1)); + int i = 0, j = 0; + for (i = 0; i < clients; i++) { + if (connlist[i] == connection) + continue; + else { + newlist[j] = connlist[i]; + j++; + } + } + free(connlist); + connlist = newlist; + clients--; + + // free up this connection + pthread_mutex_lock(&connection->mutex); + if (connection->recv_buffer) + free(connection->recv_buffer); + if (connection->header) + free(connection->header); + connection->r_len = 0; + pthread_mutex_unlock(&connection->mutex); + pthread_mutex_destroy(&connection->mutex); + free(connection); + + pthread_mutex_unlock(&iphonemutex); +} + +/** Adds a connection to the list of connections made. + * The connection list is necessary for buffering. + * + * @param connection The connection to add to the global list of connections. + */ + +static void add_connection(iphone_umux_client_t connection) +{ + pthread_mutex_lock(&iphonemutex); + iphone_umux_client_t *newlist = + (iphone_umux_client_t *) realloc(connlist, sizeof(iphone_umux_client_t) * (clients + 1)); + newlist[clients] = connection; + connlist = newlist; + clients++; + pthread_mutex_unlock(&iphonemutex); +} + +/** + * Get a source port number that is not used by one of our connections + * This is needed for us to make sure we are not sending on another + * connection. + */ +static uint16_t get_free_port() +{ + int i; + uint16_t newport = 30000; + int cnt = 0; + + pthread_mutex_lock(&iphonemutex); + while (1) { + cnt = 0; + for (i = 0; i < clients; i++) { + if (ntohs(connlist[i]->header->sport) == newport) { + cnt++; + } + } + if (cnt == 0) { + // newport is not used in our list of connections! + break; + } else { + newport++; + if (newport < 30000) { + // if all ports from 30000 to 65535 are in use, + // the value wraps (16-bit overflow) + // return 0, no port is available. + // This should not happen, but just in case ;) + newport = 0; + break; + } + } + } + pthread_mutex_unlock(&iphonemutex); + + return newport; +} + +/** Initializes a connection on phone, with source port s_port and destination port d_port + * + * @param device The iPhone to initialize a connection on. + * @param src_port The source port + * @param dst_port The destination port -- 0xf27e for lockdownd. + * @param client A mux TCP header for the connection which is used for tracking and data transfer. + * @return IPHONE_E_SUCCESS on success, an error code otherwise. + */ +iphone_error_t iphone_mux_new_client(iphone_device_t device, uint16_t src_port, uint16_t dst_port, + iphone_umux_client_t * client) +{ + if (!device || !dst_port) + return IPHONE_E_INVALID_ARG; + + src_port = get_free_port(); + + if (!src_port) { + // this is a special case, if we get 0, this is not good, so + return -EISCONN; // TODO: error code suitable? + } + + // Initialize connection stuff + iphone_umux_client_t new_connection = (iphone_umux_client_t) malloc(sizeof(struct iphone_umux_client_int)); + new_connection->header = new_mux_packet(src_port, dst_port); + + // send TCP syn + if (new_connection && new_connection->header) { + new_connection->header->tcp_flags = TCP_SYN; + new_connection->header->length = htonl(new_connection->header->length); + new_connection->header->length16 = htons(new_connection->header->length16); + new_connection->header->scnt = 0; + new_connection->header->ocnt = 0; + new_connection->phone = device; + new_connection->recv_buffer = NULL; + new_connection->r_len = 0; + pthread_cond_init(&new_connection->wait, NULL); + pthread_mutex_init(&new_connection->mutex, NULL); + pthread_cond_init(&new_connection->wr_wait, NULL); + new_connection->wr_pending_scnt = 0; + new_connection->wr_window = 0; + add_connection(new_connection); + new_connection->error = IPHONE_E_SUCCESS; + if (send_to_phone(device, (char *) new_connection->header, sizeof(usbmux_tcp_header)) >= 0) { + *client = new_connection; + return IPHONE_E_SUCCESS; + } else { + delete_connection(new_connection); + return IPHONE_E_NOT_ENOUGH_DATA; + } + } + // if we get to this point it's probably bad + return IPHONE_E_UNKNOWN_ERROR; +} + +/** Cleans up the given USBMux connection. + * @note Once a connection is closed it may not be used again. + * + * @param connection The connection to close. + * + * @return IPHONE_E_SUCCESS on success. + */ +iphone_error_t iphone_mux_free_client(iphone_umux_client_t client) +{ + if (!client || !client->phone) + return IPHONE_E_INVALID_ARG; + + pthread_mutex_lock(&client->mutex); + client->header->tcp_flags = TCP_FIN; + client->header->length = htonl(0x1C); + client->header->scnt = htonl(client->header->scnt); + client->header->ocnt = htonl(client->header->ocnt); + client->header->window = 0; + client->header->length16 = htons(0x1C); + int bytes = 0; + + bytes = usb_bulk_write(client->phone->device, BULKOUT, (char *) client->header, sizeof(usbmux_tcp_header), 800); + if (bytes < 0) + log_debug_msg("iphone_mux_free_client(): when writing, libusb gave me the error: %s\n", usb_strerror()); + + bytes = usb_bulk_read(client->phone->device, BULKIN, (char *) client->header, sizeof(usbmux_tcp_header), 800); + if (bytes < 0) + log_debug_msg("get_iPhone(): when reading, libusb gave me the error: %s\n", usb_strerror()); + + pthread_mutex_unlock(&client->mutex); + // make sure we don't have any last-minute laggards waiting on this. + // I put it after the mutex unlock because we have cases where the + // conditional wait is dependent on re-grabbing that mutex. + pthread_cond_broadcast(&client->wait); + pthread_cond_destroy(&client->wait); + pthread_cond_broadcast(&client->wr_wait); + pthread_cond_destroy(&client->wr_wait); + + delete_connection(client); + + return IPHONE_E_SUCCESS; +} + + +/** Sends the given data over the selected connection. + * + * @param phone The iPhone to send to. + * @param client The client we're sending data on. + * @param data A pointer to the data to send. + * @param datalen How much data we're sending. + * @param sent_bytes The number of bytes sent, minus the header (28) + * + * @return IPHONE_E_SUCCESS on success. + */ +iphone_error_t iphone_mux_send(iphone_umux_client_t client, const char *data, uint32_t datalen, uint32_t * sent_bytes) +{ + if (!client->phone || !client || !sent_bytes) + return IPHONE_E_INVALID_ARG; + + if (client->error != IPHONE_E_SUCCESS) { + return client->error; + } + + *sent_bytes = 0; + pthread_mutex_lock(&client->mutex); + + int sendresult = 0; + uint32 blocksize = 0; + if (client->wr_window <= 0) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + //ts.tv_sec += 1; + ts.tv_nsec += 750 * 1000; + if (pthread_cond_timedwait(&client->wait, &client->mutex, &ts) == ETIMEDOUT) { + // timd out. optimistically grow the window and try to make progress + client->wr_window += WINDOW_INCREMENT; + } + } + + blocksize = sizeof(usbmux_tcp_header) + datalen; + + // client->scnt and client->ocnt should already be in host notation... + // we don't need to change them juuuust yet. + char *buffer = (char *) malloc(blocksize + 2); // allow 2 bytes of safety padding + // Set the length and pre-emptively htonl/htons it + client->header->length = htonl(blocksize); + client->header->length16 = htons(blocksize); + + // Put scnt and ocnt into big-endian notation + client->header->scnt = htonl(client->header->scnt); + client->header->ocnt = htonl(client->header->ocnt); + // Concatenation of stuff in the buffer. + memcpy(buffer, client->header, sizeof(usbmux_tcp_header)); + memcpy(buffer + sizeof(usbmux_tcp_header), data, datalen); + + sendresult = send_to_phone(client->phone, buffer, blocksize); + // Now that we've sent it off, we can clean up after our sloppy selves. + if (buffer) + free(buffer); + + // update counts ONLY if the send succeeded. + if (sendresult == blocksize) { + // Re-calculate scnt and ocnt + client->header->scnt = ntohl(client->header->scnt) + datalen; + client->header->ocnt = ntohl(client->header->ocnt); + // Revert lengths + client->header->length = ntohl(client->header->length); + client->header->length16 = ntohs(client->header->length16); + + client->wr_window -= blocksize; + } + + + pthread_mutex_unlock(&client->mutex); + + + if (sendresult == -ETIMEDOUT || sendresult == 0) { + // no problem for now... + *sent_bytes = 0; + return IPHONE_E_TIMEOUT; + } + else if (sendresult < 0) { + return IPHONE_E_UNKNOWN_ERROR; + } + else if (sendresult == blocksize) { + // actual number of data bytes sent. + *sent_bytes = sendresult - HEADERLEN; + return IPHONE_E_SUCCESS; + } + else { + fprintf(stderr, "usbsend managed to dump a packet that is not full size. %d of %d\n", + sendresult, blocksize); + return IPHONE_E_UNKNOWN_ERROR; + } +} + +/** append the packet's DATA to the receive buffer for the client. + * + * this has a few other corner-case functions: + * 1. this will properly handle the handshake syn+ack. + * 2. for all receives, this will appropriately update the ocnt. + * + * @return number of bytes consumed (header + data) + */ +uint32 append_receive_buffer(iphone_umux_client_t client, char* packet) +{ + if (client == NULL || packet == NULL) return 0; + + usbmux_tcp_header *header = (usbmux_tcp_header *) packet; + char* data = &packet[HEADERLEN]; + uint32 packetlen = ntohl(header->length); + uint32 datalen = packetlen-HEADERLEN; + + int dobroadcast = 0; + + pthread_mutex_lock(&client->mutex); + + // we need to handle a few corner case tasks and book-keeping which + // falls on our responsibility because we are the ones reading in + // feedback. + if (client->header->scnt == 0 && client->header->ocnt == 0 ) { + fprintf(stdout, "client is still waiting for handshake.\n"); + if (header->tcp_flags == (TCP_SYN | TCP_ACK)) { + fprintf(stdout, "yes, got syn+ack ; replying with ack.\n"); + client->header->tcp_flags = TCP_ACK; + client->header->length = htonl(sizeof(usbmux_tcp_header)); + client->header->length16 = htons(sizeof(usbmux_tcp_header)); + client->header->scnt = htonl(client->header->scnt + 1); + client->header->ocnt = header->ocnt; + // push it to USB + // TODO: need to check for error in the send here.... :( + if (send_to_phone(client->phone, (char *)client->header, sizeof(usbmux_tcp_header)) <= 0) { + fprintf(stdout, "%s: error when pushing to usb...\n", __func__); + } + // need to revert some of the fields back to host notation. + client->header->scnt = ntohl(client->header->scnt); + client->header->ocnt = ntohl(client->header->ocnt); + client->header->length = ntohl(client->header->length); + client->header->length16 = ntohs(client->header->length16); + } + else { + client->error = IPHONE_E_ECONNABORTED; + // woah... this connection failed us. + // TODO: somehow signal that this stream is a no-go. + fprintf(stderr, "WOAH! client failed to get proper syn+ack.\n"); + } + } + + // update TCP counters and windows. + // + // save the window that we're getting from the USB device. + // apparently the window is bigger than just the 512 that's typically + // advertised. iTunes apparently shifts this value by 8 to get a much + // larger number. + if (header->tcp_flags & TCP_RST) { + client->error = IPHONE_E_ECONNRESET; + fprintf(stderr, "peer sent connection reset. setting error: %d\n", client->error); + } + + // the packet's ocnt tells us how much of our data the device has received. + if (header->tcp_flags & TCP_ACK) { + + // this is a hacky magic number condition. it seems that once the window + // reported by the phone starts to drop below this number, we quickly fall + // into connection reset problems. Once we see the reported window size + // start falling off, cut off and wait for solid acks to come back. + if (ntohs(header->window) < 256) + client->wr_window = 0; + + // check what just got acked. + if (ntohl(header->ocnt) < client->header->scnt) { + // we got some kind of ack, but it hasn't caught up with the + // pending that have been sent. + pthread_cond_broadcast(&client->wr_wait); + } + else if (ntohl(header->ocnt) > /*client->wr_pending_scnt*/ client->header->scnt) { + fprintf(stderr, "WTF?! acks overtook pending outstanding. %u,%u\n", + ntohl(header->ocnt), client->wr_pending_scnt); + } + else { + // reset the window + client->wr_window = WINDOW_MAX; + pthread_cond_broadcast(&client->wr_wait); + } + } + + // the packet's scnt will be our new ocnt. + client->header->ocnt = ntohl(header->scnt); + + // ensure there is enough space, either by first malloc or realloc + if (datalen > 0) { + if (client->r_len == 0) dobroadcast = 1; + + if (client->recv_buffer == NULL) { + client->recv_buffer = malloc(datalen); + client->r_len = 0; + } + else { + client->recv_buffer = realloc(client->recv_buffer, client->r_len + datalen); + } + + memcpy(&client->recv_buffer[client->r_len], data, datalen); + client->r_len += datalen; + } + + pthread_mutex_unlock(&client->mutex); + + // I put this outside the mutex unlock just so that when the threads + // wake, we don't have to do another round of unlock+try to grab. + if (dobroadcast) + pthread_cond_broadcast(&client->wait); + + + return packetlen; +} + +/** NOTE! THERE IS NO MUTEX LOCK IN THIS FUNCTION! + because we're only called from one location, pullbulk, where the lock + is already held. + */ +iphone_umux_client_t find_client(usbmux_tcp_header* recv_header) +{ + // remember, as we're looking for the client, the receive header is + // coming from the USB into our client. This means that when we check + // the src/dst ports, we need to reverse them. + iphone_umux_client_t retval = NULL; + + // just for debugging check, I'm going to convert the numbers to host-endian. + uint16 hsport = ntohs(recv_header->sport); + uint16 hdport = ntohs(recv_header->dport); + + pthread_mutex_lock(&iphonemutex); + int i; + for (i = 0; i < clients; i++) { + uint16 csport = ntohs(connlist[i]->header->sport); + uint16 cdport = ntohs(connlist[i]->header->dport); + + if (hsport == cdport && hdport == csport) { + retval = connlist[i]; + break; + } + } + pthread_mutex_unlock(&iphonemutex); + + return retval; +} + +/** pull in a big USB bulk packet and distribute it to queues appropriately. + */ +void iphone_mux_pullbulk(iphone_device_t phone) +{ + static const int DEFAULT_CAPACITY = 128*1024; + if (usbReceive.buffer == NULL) { + usbReceive.capacity = DEFAULT_CAPACITY; + usbReceive.buffer = malloc(usbReceive.capacity); + usbReceive.leftover = 0; + } + + // start the cursor off just ahead of the leftover. + char* cursor = &usbReceive.buffer[usbReceive.leftover]; + // pull in content, note that the amount we can pull is capacity minus leftover + int readlen = recv_from_phone_timeout(phone, cursor, usbReceive.capacity - usbReceive.leftover, 5000); + if (readlen < 0) { + //fprintf(stderr, "recv_from_phone_timeout gave us an error.\n"); + readlen = 0; + } + if (readlen > 0) { + //fprintf(stdout, "recv_from_phone_timeout pulled an extra %d bytes\n", readlen); + } + + // the amount of content we have to work with is the remainder plus + // what we managed to read + usbReceive.leftover += readlen; + + // reset the cursor to the front of that buffer and work through + // trying to decode packets out of them. + cursor = usbReceive.buffer; + while (1) { + // check if there's even sufficient data to decode a header + if (usbReceive.leftover < HEADERLEN) break; + usbmux_tcp_header *header = (usbmux_tcp_header *) cursor; + + // now that we have a header, check if there is sufficient data + // to construct a full packet, including its data + uint32 packetlen = ntohl(header->length); + if (usbReceive.leftover < packetlen) { + break; + } + + // ok... find the client this packet will get stuffed to. + iphone_umux_client_t client = find_client(header); + if (client == NULL) { + fprintf(stderr, "WARNING: client for packet cannot be found. dropping packet.\n"); + } + else { + // stuff the data + append_receive_buffer(client, cursor); + } + + // move the cursor and account for the consumption + cursor += packetlen; + usbReceive.leftover -= packetlen; + } + + // now, we need to manage any leftovers. + // I'm going to manage the leftovers by alloc'ing a new block and copying + // the leftovers to it. This is just to prevent problems with memory + // moves where there may be overlap. Besides, the leftovers should be + // small enough that this copy is minimal in overhead. + // + // if there are no leftovers, we just leave the datastructure as is, + // and re-use the block next time. + if (usbReceive.leftover > 0 && cursor != usbReceive.buffer) { + char* newbuff = malloc(DEFAULT_CAPACITY); + memcpy(newbuff, cursor, usbReceive.leftover); + free(usbReceive.buffer); + usbReceive.buffer = newbuff; + usbReceive.capacity = DEFAULT_CAPACITY; + } +} + +/** + * return the error code stored in iphone_umux_client_t structure, + * e.g. non-zero when an usb read error occurs. + * + * @param client the umux client + * + * @return IPHONE_E_* error codes. + */ +iphone_error_t iphone_mux_get_error(iphone_umux_client_t client) +{ + if (!client) { + return 0; + } + + return client->error; +} + +/** This is a higher-level USBMuxTCP-like function + * + * @param connection The connection to receive data on. + * @param data Where to put the data we receive. + * @param datalen How much data to read. + * + * @return IPHONE_E_SUCCESS or error code if failure. + */ +iphone_error_t iphone_mux_recv(iphone_umux_client_t client, char *data, uint32_t datalen, uint32_t * recv_bytes) +{ + return iphone_mux_recv_timeout(client, data, datalen, recv_bytes, 0); +} + +/** + @param timeout + */ +iphone_error_t iphone_mux_recv_timeout(iphone_umux_client_t client, char *data, uint32_t datalen, uint32_t * recv_bytes, int timeout) +{ + + if (!client || !data || datalen == 0 || !recv_bytes) + return IPHONE_E_INVALID_ARG; + + if (client->error != IPHONE_E_SUCCESS) return client->error; + + pthread_mutex_lock(&client->mutex); + + if (timeout > 0 && (client->recv_buffer == NULL ||client->r_len == 0)) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout/1000; + ts.tv_nsec += (timeout-((int)(timeout/1000))*1000)*1000; //millis * 1000; + pthread_cond_timedwait(&client->wait, &client->mutex, &ts); + } + + *recv_bytes = 0; + if (client->recv_buffer != NULL && client->r_len > 0) { + uint32_t foolen = datalen; + if (foolen > client->r_len) foolen = client->r_len; + memcpy(data, client->recv_buffer, foolen); + *recv_bytes = foolen; + + // preserve any left-over unread amounts. + int remainder = client->r_len - foolen; + if (remainder > 0) { + char* newbuf = malloc(remainder); + memcpy(newbuf, client->recv_buffer + foolen, remainder); + client->r_len = remainder; + free(client->recv_buffer); + client->recv_buffer = newbuf; + } + else { + free(client->recv_buffer); + client->recv_buffer = NULL; + client->r_len = 0; + } + } + + pthread_mutex_unlock(&client->mutex); + + + return IPHONE_E_SUCCESS; +} diff --git a/iphone.h b/iphone.h new file mode 100644 index 0000000..e132cd5 --- /dev/null +++ b/iphone.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2008 Jing Su. 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 __IPHONE_H__ +#define __IPHONE_H__ + +#include +#include +#include + +//general errors +#define IPHONE_E_SUCCESS 0 +#define IPHONE_E_INVALID_ARG -1 +#define IPHONE_E_UNKNOWN_ERROR -2 +#define IPHONE_E_NO_DEVICE -3 +#define IPHONE_E_TIMEOUT -4 +#define IPHONE_E_NOT_ENOUGH_DATA -5 +#define IPHONE_E_BAD_HEADER -6 + +//lockdownd specific error +#define IPHONE_E_INVALID_CONF -7 +#define IPHONE_E_PAIRING_FAILED -8 +#define IPHONE_E_SSL_ERROR -9 +#define IPHONE_E_PLIST_ERROR -10 +#define IPHONE_E_DICT_ERROR -11 + +//afc specific error +#define IPHONE_E_NO_SUCH_FILE -12 + +//general TCP-style errors and conditions +#define IPHONE_E_ECONNABORTED -ECONNABORTED +#define IPHONE_E_ECONNRESET -ECONNRESET +#define IPHONE_E_ENOTCONN -ENOTCONN +#define IPHONE_E_ESHUTDOWN -ESHUTDOWN +#define IPHONE_E_ETIMEDOUT -ETIMEDOUT +#define IPHONE_E_ECONNREFUSED -ECONNREFUSED + + +typedef int16_t iphone_error_t; + +struct iphone_device_int; +typedef struct iphone_device_int *iphone_device_t; + +struct iphone_umux_client_int; +typedef struct iphone_umux_client_int *iphone_umux_client_t; + +iphone_error_t iphone_get_device ( iphone_device_t *device ); +iphone_error_t iphone_get_specific_device(int bus_n, int dev_n, iphone_device_t * device); +iphone_error_t iphone_free_device ( iphone_device_t device ); + + +iphone_error_t iphone_mux_new_client ( iphone_device_t device, uint16_t src_port, uint16_t dst_port, iphone_umux_client_t *client ); +iphone_error_t iphone_mux_free_client ( iphone_umux_client_t client ); + +iphone_error_t iphone_mux_send(iphone_umux_client_t client, const char *data, uint32_t datalen, uint32_t * sent_bytes); + +iphone_error_t iphone_mux_recv(iphone_umux_client_t client, char *data, uint32_t datalen, uint32_t * recv_bytes); +iphone_error_t iphone_mux_recv_timeout(iphone_umux_client_t client, char *data, uint32_t datalen, uint32_t * recv_bytes, int timeout); + +void iphone_mux_pullbulk(iphone_device_t phone); + +iphone_error_t iphone_mux_get_error(iphone_umux_client_t client); + +#endif diff --git a/iproxy.c b/iproxy.c new file mode 100644 index 0000000..df3d689 --- /dev/null +++ b/iproxy.c @@ -0,0 +1,329 @@ +/* + * iproxy -- proxy that enables tcp service access to iPhone/iPod + * via USB cable + * TODO: improve code... + * + * Copyright (c) 2009 Nikias Bassen. All Rights Reserved. + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "usbmuxd.h" +#include "sock_stuff.h" + +#define SOCKET_FILE "/var/run/usbmuxd" + +volatile int stop_ctos = 0; +volatile int stop_stoc = 0; + +static uint16_t listen_port = 0; +static uint16_t device_port = 0; + +pthread_mutex_t smutex = PTHREAD_MUTEX_INITIALIZER; + +struct client_data { + int fd; + int sfd; +}; + +int usbmuxd_get_result(int sfd, uint32_t tag, uint32_t *result) +{ + struct usbmux_result res; + int recv_len; + int i; + uint32_t rrr[5]; + + if (!result) { + return -EINVAL; + } + + if ((recv_len = recv_buf(sfd, &res, sizeof(res))) <= 0) { + perror("recv"); + return -errno; + } else { + memcpy(&rrr, &res, recv_len); + for (i = 0; i < recv_len/4; i++) { + fprintf(stderr, "%08x ", rrr[i]); + } + fprintf(stderr, "\n"); + if ((recv_len == sizeof(res)) + && (res.header.length == recv_len) + && (res.header.reserved == 0) + && (res.header.type == usbmux_result) + ) { + *result = res.result; + if (res.header.tag == tag) { + return 1; + } else { + return 0; + } + } + } + + return -1; +} + +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 (!stop_stoc && cdata->fd>0 && cdata->sfd>0) { + recv_len = recv_buf_timeout(cdata->sfd, buffer, sizeof(buffer), 0, 5000); + if (recv_len <= 0) { + if (recv_len == 0) { + // try again + continue; + } else { + fprintf(stderr, "recv failed: %s\n", strerror(errno)); + break; + } + } else { + printf("received %d bytes from server\n", recv_len); + // send to socket + sent = send_buf(cdata->fd, buffer, recv_len); + if (sent < recv_len) { + if (sent <= 0) { + fprintf(stderr, "send failed: %s\n", strerror(errno)); + break; + } else { + fprintf(stderr, "only sent %d from %d bytes\n", sent, recv_len); + } + } else { + // sending succeeded, receive from device + printf("pushed %d bytes to client\n", sent); + } + } + } + close(cdata->fd); + cdata->fd = -1; + stop_ctos = 1; + + return NULL; +} + +void *run_ctos_loop(void *arg) +{ + struct client_data *cdata = (struct client_data*)arg; + int recv_len; + int sent; + char buffer[131072]; + pthread_t stoc = 0; + + printf("%s: fd = %d\n", __func__, cdata->fd); + + stop_stoc = 0; + pthread_create(&stoc, NULL, run_stoc_loop, cdata); + + while (!stop_ctos && cdata->fd>0 && cdata->sfd>0) { + recv_len = recv_buf_timeout(cdata->fd, buffer, sizeof(buffer), 0, 5000); + if (recv_len <= 0) { + if (recv_len == 0) { + // try again + continue; + } else { + fprintf(stderr, "recv failed: %s\n", strerror(errno)); + break; + } + } else { + printf("pulled %d bytes from client\n", recv_len); + // send to local socket + sent = send_buf(cdata->sfd, buffer, recv_len); + if (sent < recv_len) { + if (sent <= 0) { + fprintf(stderr, "send failed: %s\n", strerror(errno)); + break; + } else { + fprintf(stderr, "only sent %d from %d bytes\n", sent, recv_len); + } + } else { + // sending succeeded, receive from device + printf("sent %d bytes to server\n", sent); + } + } + } + close(cdata->fd); + cdata->fd = -1; + stop_stoc = 1; + + pthread_join(stoc, NULL); + + return NULL; +} + +int main(int argc, char **argv) +{ + int recv_len = 0; + int hello_done; + int connected; + uint32_t pktlen; + unsigned char *buf; + struct usbmux_header hello; + struct usbmux_dev_info device_info; + int sfd = -1; + + if (argc != 3) { + printf("usage: %s LOCAL_PORT DEVICE_PORT\n", argv[0]); + return 0; + } + + listen_port = atoi(argv[1]); + device_port = atoi(argv[2]); + + if (!listen_port) { + fprintf(stderr, "Invalid listen_port specified!\n"); + return -EINVAL; + } + + if (!device_port) { + fprintf(stderr, "Invalid device_port specified!\n"); + return -EINVAL; + } + + sfd = connect_unix_socket(SOCKET_FILE); + if (sfd < 0) { + printf("error opening socket, terminating.\n"); + return -1; + } + + // send hello + hello.length = sizeof(struct usbmux_header); + hello.reserved = 0; + hello.type = usbmux_hello; + hello.tag = 2; + + hello_done = 0; + connected = 0; + + fprintf(stdout, "sending Hello packet\n"); + if (send(sfd, &hello, hello.length, 0) == hello.length) { + uint32_t res = -1; + // get response + if (usbmuxd_get_result(sfd, hello.tag, &res) && (res==0)) { + fprintf(stdout, "Got Hello Response!\n"); + hello_done = 1; + } else { + fprintf(stderr, "Did not get Hello response (with result=0)...\n"); + close(sfd); + return -1; + } + + device_info.device_id = 0; + + if (hello_done) { + // get all devices + while (1) { + if (recv_buf_timeout(sfd, &pktlen, 4, MSG_PEEK, 1000) == 4) { + buf = (unsigned char*)malloc(pktlen); + if (!buf) { + exit(-ENOMEM); + } + recv_len = recv_buf(sfd, buf, pktlen); + if (recv_len < pktlen) { + fprintf(stdout, "received less data than specified in header!\n"); + } + fprintf(stdout, "Received device data\n"); + //log_debug_buffer(stdout, (char*)buf, pktlen); + memcpy(&device_info, buf + sizeof(struct usbmux_header), sizeof(device_info)); + free(buf); + } else { + // we _should_ have all of them now. + // or perhaps an error occured. + break; + } + } + } + + if (device_info.device_id > 0) { + struct usbmux_connect_request c_req; + + fprintf(stdout, "Requesting connecion to device %d port %d\n", device_info.device_id, device_port); + + // try to connect to last device found + c_req.header.length = sizeof(c_req); + c_req.header.reserved = 0; + c_req.header.type = usbmux_connect; + c_req.header.tag = 3; + c_req.device_id = device_info.device_id; + c_req.port = htons(device_port); + c_req.reserved = 0; + + if (send_buf(sfd, &c_req, sizeof(c_req)) < 0) { + perror("send"); + } else { + // read ACK + res = -1; + fprintf(stdout, "Reading connect result...\n"); + if (usbmuxd_get_result(sfd, c_req.header.tag, &res)) { + if (res == 0) { + fprintf(stdout, "Connect success!\n"); + connected = 1; + } else { + fprintf(stderr, "Connect failed, Error code=%d\n", res); + } + } + } + } + + if (connected) { + int mysock = create_socket(listen_port); + if (mysock < 0) { + fprintf(stderr, "Error creating socket: %s\n", strerror(errno)); + } else { + pthread_t ctos; + struct sockaddr_in c_addr; + socklen_t len = sizeof(struct sockaddr_in); + struct client_data cdata; + int c_sock; + while (1) { + printf("waiting for connection\n"); + c_sock = accept(mysock, (struct sockaddr*)&c_addr, &len); + if (c_sock) { + printf("accepted connection, fd = %d\n", c_sock); + cdata.fd = c_sock; + cdata.sfd = sfd; + stop_ctos = 0; + pthread_create(&ctos, NULL, run_ctos_loop, &cdata); + pthread_join(ctos, NULL); + } else { + break; + } + } + close(c_sock); + close(mysock); + } + } else { + fprintf(stderr, "No attached device found?!\n"); + } + } + close(sfd); + + return 0; +} diff --git a/sock_stuff.c b/sock_stuff.c new file mode 100644 index 0000000..1a23bc1 --- /dev/null +++ b/sock_stuff.c @@ -0,0 +1,277 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "sock_stuff.h" + +#define RECV_TIMEOUT 10000 + +int create_unix_socket (const char *filename) +{ + struct sockaddr_un name; + int sock; + size_t size; + + // remove if still present + unlink(filename); + + /* Create the socket. */ + sock = socket (PF_LOCAL, SOCK_STREAM, 0); + if (sock < 0) { + perror ("socket"); + return -1; + } + + /* Bind a name to the socket. */ + name.sun_family = AF_LOCAL; + strncpy (name.sun_path, filename, sizeof (name.sun_path)); + name.sun_path[sizeof (name.sun_path) - 1] = '\0'; + + /* The size of the address is + the offset of the start of the filename, + plus its length, + plus one for the terminating null byte. + Alternatively you can just do: + size = SUN_LEN (&name); + */ + size = (offsetof (struct sockaddr_un, sun_path) + + strlen (name.sun_path) + 1); + + if (bind (sock, (struct sockaddr *) &name, size) < 0) { + perror("bind"); + close(sock); + return -1; + } + + if (listen(sock, 10) < 0) { + perror("listen"); + close(sock); + return -1; + } + + return sock; +} + +int connect_unix_socket(const char *filename) +{ + struct sockaddr_un name; + int sfd = -1; + size_t size; + struct stat fst; + + // check if socket file exists... + if (stat(filename, &fst) != 0) { + 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)) { + fprintf(stderr, "%s: File '%s' is not a socket!\n", __func__, filename); + return -1; + } + + // make a new socket + if ((sfd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) { + fprintf(stderr, "%s: socket: %s\n", __func__, strerror(errno)); + return -1; + } + + // and connect to 'filename' + name.sun_family = AF_LOCAL; + strncpy(name.sun_path, filename, sizeof(name.sun_path)); + name.sun_path[sizeof(name.sun_path) - 1] = 0; + + size = (offsetof (struct sockaddr_un, sun_path) + + strlen (name.sun_path) + 1); + + if (connect(sfd, (struct sockaddr*)&name, size) < 0) { + close(sfd); + fprintf(stderr, "%s: connect: %s\n", __func__, strerror(errno)); + return -1; + } + + return sfd; +} + +int create_socket(uint16_t port) +{ + int sfd = -1; + int yes = 1; + 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, &yes, sizeof(int)) == -1) { + perror("setsockopt()"); + close(sfd); + return -1; + } + + memset((void *)&saddr, 0, sizeof(saddr)); + saddr.sin_family = AF_INET; + saddr.sin_addr.s_addr = htonl(INADDR_ANY); + saddr.sin_port = htons(port); + + if(0 > bind(sfd, (struct sockaddr *)&saddr , sizeof(saddr))) { + perror("bind()"); + close(sfd); + return -1; + } + + if (listen(sfd, 1) == -1) { + perror("listen()"); + close(sfd); + return -1; + } + + return sfd; +} + +int connect_socket(const char *addr, uint16_t port) +{ + int sfd = -1; + int yes = 1; + struct hostent *hp; + struct sockaddr_in saddr; + + if (!addr) { + errno = EINVAL; + return -1; + } + + if ((hp = gethostbyname(addr)) == NULL) { + fprintf(stderr, "%s: unknown host '%s'\n", __func__, addr); + return -1; + } + + if (!hp->h_addr) { + fprintf(stderr, "%s: gethostbyname returned NULL address!\n", __func__); + return -1; + } + + if ( 0 > ( sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) ) ) { + perror("socket()"); + return -1; + } + + if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { + perror("setsockopt()"); + close(sfd); + return -1; + } + + memset((void *)&saddr, 0, sizeof(saddr)); + saddr.sin_family = AF_INET; + saddr.sin_addr.s_addr = (uint32_t)hp->h_addr; + saddr.sin_port = htons(port); + + if (connect(sfd, (struct sockaddr*)&saddr, sizeof(saddr)) < 0) { + perror("connect"); + close(sfd); + return -2; + } + + return sfd; +} + +int check_fd(int fd, fd_mode fdm, unsigned int timeout) +{ + fd_set fds; + int sret; + int eagain; + struct timeval to; + + if (fd <= 0) { + fprintf(stderr, "ERROR: invalid fd in check_fd %d\n", fd); + return -1; + } + + FD_ZERO(&fds); + FD_SET(fd, &fds); + + to.tv_sec = (time_t)(timeout/1000); + to.tv_usec = (time_t)((timeout-(to.tv_sec*1000))*1000); + + sret = -1; + + do { + eagain = 0; + switch(fdm) { + case fdread: + sret = select(fd+1,&fds,NULL,NULL,&to); + break; + case fdwrite: + sret = select(fd+1,NULL,&fds,NULL,&to); + break; + case fdexcept: + sret = select(fd+1,NULL,NULL,&fds,&to); + break; + } + + if (sret < 0) { + switch(errno) { + case EINTR: + // interrupt signal in select + fprintf(stderr, "%s: EINTR\n", __func__); + eagain = 1; + break; + case EAGAIN: + fprintf(stderr, "%s: EAGAIN\n", __func__); + break; + default: + fprintf(stderr, "%s: select failed: %s\n", __func__, strerror(errno)); + return -1; + } + } + } while (eagain); + + return sret; +} + +int recv_buf(int fd, void *data, size_t length) +{ + return recv_buf_timeout(fd, data, length, 0, RECV_TIMEOUT); +} + +int peek_buf(int fd, void *data, size_t length) +{ + return recv_buf_timeout(fd, data, length, MSG_PEEK, RECV_TIMEOUT); +} + +int recv_buf_timeout(int fd, void *data, size_t length, int flags, unsigned int timeout) +{ + int res; + int result; + + // check if data is available + res = check_fd(fd, fdread, 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 + fprintf(stderr, "%s: fd=%d\n", __func__, fd); + return -1; + } + return result; +} + +int send_buf(int fd, void *data, size_t length) +{ + return send(fd, data, length, 0); +} + diff --git a/sock_stuff.h b/sock_stuff.h new file mode 100644 index 0000000..01082d1 --- /dev/null +++ b/sock_stuff.h @@ -0,0 +1,27 @@ +#ifndef __SOCK_STUFF_H +#define __SOCK_STUFF_H + +#include + +enum fd_mode +{ + fdread, + fdwrite, + fdexcept +}; +typedef enum fd_mode fd_mode; + +int create_unix_socket(const char *filename); +int connect_unix_socket(const char *filename); +int create_socket(uint16_t port); +int connect_socket(const char *addr, uint16_t port); +int check_fd(int fd, fd_mode fdm, unsigned int timeout); + +int recv_buf(int fd, void *data, size_t size); +int peek_buf(int fd, void *data, size_t size); +int recv_buf_timeout(int fd, void *data, size_t size, int flags, unsigned int timeout); + +int send_buf(int fd, void *data, size_t size); + +#endif /* __SOCK_STUFF_H */ + diff --git a/testclient.c b/testclient.c new file mode 100644 index 0000000..fafbf23 --- /dev/null +++ b/testclient.c @@ -0,0 +1,148 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "usbmuxd.h" +#include "sock_stuff.h" + +#define SOCKET_FILE "/var/run/usbmuxd" + +int usbmuxd_get_result(int sfd, uint32_t tag, uint32_t *result) +{ + struct usbmux_result res; + int recv_len; + + if (!result) { + return -EINVAL; + } + + if ((recv_len = recv_buf(sfd, &res, sizeof(res))) <= 0) { + perror("recv"); + return -errno; + } else { + if ((recv_len == sizeof(res)) + && (res.header.length == recv_len) + && (res.header.reserved == 0) + && (res.header.type == usbmux_result) + ) { + *result = res.result; + if (res.header.tag == tag) { + return 1; + } else { + return 0; + } + } + } + + return -1; +} + +int main(int argc, char **argv) +{ + int sfd; + int recv_len = 0; + int hello_done; + int connected; + uint32_t pktlen; + unsigned char *buf; + struct usbmux_header hello; + struct usbmux_dev_info device_info; + + sfd = connect_unix_socket(SOCKET_FILE); + if (sfd < 0) { + printf("error opening socket, terminating.\n"); + return -1; + } + + // send hello + hello.length = sizeof(struct usbmux_header); + hello.reserved = 0; + hello.type = usbmux_hello; + hello.tag = 2; + + hello_done = 0; + connected = 0; + + fprintf(stdout, "sending Hello packet\n"); + if (send(sfd, &hello, hello.length, 0) == hello.length) { + uint32_t res = -1; + // get response + if (usbmuxd_get_result(sfd, hello.tag, &res) && (res==0)) { + fprintf(stdout, "Got Hello Response!\n"); + hello_done = 1; + } else { + fprintf(stderr, "Did not get Hello response (with result=0)...\n"); + close(sfd); + return -1; + } + + device_info.device_id = 0; + + if (hello_done) { + // get all devices + while (1) { + if (recv_buf_timeout(sfd, &pktlen, 4, MSG_PEEK, 1000) == 4) { + buf = (unsigned char*)malloc(pktlen); + if (!buf) { + exit(-ENOMEM); + } + recv_len = recv_buf(sfd, buf, pktlen); + if (recv_len < pktlen) { + fprintf(stdout, "received less data than specified in header!\n"); + } + fprintf(stdout, "got device data:\n"); + //log_debug_buffer(stdout, (char*)buf, pktlen); + memcpy(&device_info, buf + sizeof(struct usbmux_header), sizeof(device_info)); + free(buf); + } else { + // we _should_ have all of them now. + // or perhaps an error occured. + break; + } + } + } + + if (device_info.device_id > 0) { + struct usbmux_connect_request c_req; + + // try to connect to last device found + c_req.header.length = sizeof(c_req); + c_req.header.reserved = 0; + c_req.header.type = usbmux_connect; + c_req.header.tag = 3; + c_req.device_id = device_info.device_id; + c_req.port = htons(22); + c_req.reserved = 0; + + if (send_buf(sfd, &c_req, sizeof(c_req)) < 0) { + perror("send"); + } else { + // read ACK + res = -1; + if (usbmuxd_get_result(sfd, c_req.header.tag, &res)) { + if (res == 0) { + fprintf(stdout, "Connect success!\n"); + connected = 1; + } else { + fprintf(stderr, "Connect failed, Error code=%d\n", res); + } + } + } + } + + if (connected) { + + + // do communication now. + sleep(10); + } + } + close(sfd); + + return 0; +} diff --git a/usbmuxd.c b/usbmuxd.c new file mode 100644 index 0000000..37a7f9e --- /dev/null +++ b/usbmuxd.c @@ -0,0 +1,795 @@ +/* + * usbmuxd -- daemon for communication with iPhone/iPod via USB + * + * Copyright (c) 2009 Nikias Bassen. All Rights Reserved. + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "usbmuxd.h" +#include "sock_stuff.h" + +#include "iphone.h" + +#define SOCKET_FILE "/var/run/usbmuxd" + +#define DEFAULT_TIMEOUT 4000 +#define DEFAULT_CHILDREN_CAPACITY 10 + +static int quit_flag = 0; +static int fsock = -1; + +struct client_data { + volatile int dead; + int socket; + int tag; + pthread_t thread; + pthread_t handler; + pthread_t reader; + int reader_quit; + int reader_dead; + int handler_dead; + iphone_umux_client_t muxclient; +}; + +struct device_use_info { + uint32_t device_id; + iphone_device_t phone; + int use_count; +}; + +static struct device_use_info **device_use_list = NULL; +static int device_use_count = 0; +static pthread_mutex_t usbmux_mutex = PTHREAD_MUTEX_INITIALIZER; + +static void print_buffer(const char *data, const int length) +{ + int i; + int j; + unsigned char c; + + for(i=0; i= length) { + printf(" "); + continue; + } + printf("%02hhx ", *(data+i+j)); + } + printf(" | "); + for(j=0;j<16;j++) { + if (i+j >= length) + break; + c = *(data+i+j); + if ((c < 32) || (c > 127)) { + printf("."); + continue; + } + printf("%c", c); + } + printf("\n"); + } + printf("\n"); +} + +static int usbmuxd_get_request(int fd, void *data, size_t len) +{ + uint32_t pktlen; + int recv_len; + + if (peek_buf(fd, &pktlen, sizeof(pktlen)) < sizeof(pktlen)) { + return -errno; + } + + if (len < pktlen) { + // target buffer is to small to hold this packet! fix it! + fprintf(stderr, "%s: WARNING -- packet (%d) is larger than target buffer (%d)! Truncating.\n", __func__, pktlen, len); + pktlen = len; + } + + recv_len = recv_buf(fd, data, pktlen); + if (recv_len < pktlen) { + fprintf(stderr, "%s: Uh-oh, we got less than the packet's size, %d instead of %d...\n", __func__, recv_len, pktlen); + } + + return recv_len; +} + +static int usbmuxd_send_result(int fd, uint32_t tag, uint32_t result_code) +{ + struct usbmux_result res; + + res.header.length = sizeof(res); + res.header.reserved = 0; + res.header.type = usbmux_result; + res.header.tag = tag; + res.result = result_code; + + fprintf(stderr, "%s: tag=%d result=%d\n", __func__, res.header.tag, res.result); + + return send_buf(fd, &res, sizeof(res)); +} + +/** + * + */ +static void *usbmuxd_client_reader_thread(void *arg) +{ + struct client_data *cdata; + + char rbuffer[512]; + uint32_t rbuffersize = 512; + uint32_t rlen; + iphone_error_t err; + char *cursor; + ssize_t len; + int result; + + if (!arg) { + fprintf(stderr, "%s: invalid client_data supplied!\n", __func__); + cdata->reader_dead = 1; + return NULL; + } + + cdata = (struct client_data*)arg; + + cdata->reader_dead = 0; + + fprintf(stdout, "%s: started\n", __func__); + + while (!quit_flag && !cdata->reader_quit) { + result = check_fd(cdata->socket, fdwrite, DEFAULT_TIMEOUT); + if (result <= 0) { + if (result < 0) { + fprintf(stderr, "%s: select error: %s\n", __func__, strerror(errno)); + } + continue; + } + + rlen = 0; + err = iphone_mux_recv_timeout(cdata->muxclient, rbuffer, rbuffersize, &rlen, DEFAULT_TIMEOUT); + if (err != 0) { + fprintf(stderr, "%s: encountered USB read error: %d\n", __func__, err); + break; + } + + cursor = rbuffer; + while (rlen > 0) { + //printf("%s: \n", __func__); + //print_buffer(cursor, rlen); + //if ((rlen > 4) && !cursor[3]) { + len = send_buf(cdata->socket, cursor, rlen); + /*} else if (cursor[0] == 1) { + fprintf(stderr, "%s: Error message received: %s\n", __func__, cursor+1); + // we got an error message and no data. don't send it. + // TODO parse the error code and put it in the right place! + len = rlen; + }*/ + // calculate remainder + rlen -= len; + // advance cursor + cursor += len; + } + fsync(cdata->socket); + } + + fprintf(stdout, "%s: terminated\n", __func__); + + cdata->reader_dead = 1; + + return NULL; +} + +static int usbmuxd_handleConnectResult(struct client_data *cdata) +{ + int result; + char buffer[512]; + char err_type[64]; + int err_code; + ssize_t maxlen = 512; + uint32_t rlen; + iphone_error_t err; + + // trigger connection attempt if ready to write to client + result = check_fd(cdata->socket, fdwrite, DEFAULT_TIMEOUT); + if (result <= 0) { + if (result < 0) { + fprintf(stderr, "%s: select error: %s\n", __func__, strerror(errno)); + return result; + } + } else { + result = 0; + err = iphone_mux_recv_timeout(cdata->muxclient, buffer, maxlen, &rlen, DEFAULT_TIMEOUT); + if (err != 0) { + fprintf(stderr, "%s: encountered USB read error: %d\n", __func__, err); + usbmuxd_send_result(cdata->socket, cdata->tag, err); + } else { + if (rlen > 0) { + //print_buffer(buffer, rlen); + if ((buffer[0] == 1) && (rlen > 20) && !memcmp(buffer+1, "handleConnectResult:", 20)) { + // hm... we got an error message! + buffer[rlen] = 0; + fprintf(stderr, "%s: %s\n", __func__, buffer+22); + + if (sscanf(buffer+22, "%s - %d\n", err_type, &err_code) == 2) { + usbmuxd_send_result(cdata->socket, cdata->tag, err_code); + } else { + usbmuxd_send_result(cdata->socket, cdata->tag, ENODATA); + } + return -2; + } else { + // send success result + usbmuxd_send_result(cdata->socket, cdata->tag, 0); + // and the server greeting message + send_buf(cdata->socket, buffer, rlen); + } + } else { + // no server greeting? this seems to be ok. send success. + usbmuxd_send_result(cdata->socket, cdata->tag, 0); + return 0; + } + } + //fsync(cdata->socket); + } + return 0; +} + +/** + * This thread handles the communication between the connected iPhone/iPod + * and the client that created the connection. + */ +static void *usbmuxd_client_handler_thread(void *arg) +{ + struct client_data *cdata; + int result; + char *cursor; + char buffer[1024]; + ssize_t len; + ssize_t maxlen = sizeof(buffer); + uint32_t wlen; + iphone_error_t err; + + if (!arg) { + fprintf(stderr, "%s: invalid client_data provided!\n", __func__); + return NULL; + } + + cdata = (struct client_data*)arg; + + fprintf(stdout, "%s: started\n", __func__); + + if (usbmuxd_handleConnectResult(cdata)) { + goto leave; + } + + // starting mux reader thread + cdata->reader_quit = 0; + cdata->reader_dead = 0; + if (pthread_create(&cdata->reader, NULL, usbmuxd_client_reader_thread, cdata) != 0) { + fprintf(stderr, "%s: could not start client_reader thread\n", __func__); + cdata->reader = 0; + } + + while (!quit_flag && !cdata->reader_dead) { + result = check_fd(cdata->socket, fdread, DEFAULT_TIMEOUT); + if (result <= 0) { + if (result < 0) { + fprintf(stderr, "%s: Error: checkfd: %s\n", __func__, strerror(errno)); + } + continue; + } + + // check_fd told us there's data available, so read from client + // and push to USB device. + len = recv(cdata->socket, buffer, maxlen, 0); + if (len == 0) { + break; + } + if (len < 0) { + fprintf(stderr, "%s: Error: recv: %s\n", __func__, strerror(errno)); + break; + } + + cursor = buffer; + do { + wlen = 0; + err = iphone_mux_send(cdata->muxclient, cursor, len, &wlen); + if (err == IPHONE_E_TIMEOUT) { + // some kind of timeout... just be patient and retry. + } else if (err != IPHONE_E_SUCCESS) { + fprintf(stderr, "%s: USB write error: %d\n", __func__, err); + len = -1; + break; + } + + // calculate remainder. + len -= wlen; + // advance cursor appropiately. + cursor += wlen; + } while ((len > 0) && !quit_flag); + if (len < 0) { + break; + } + } + +leave: + // cleanup + fprintf(stdout, "%s: terminating\n", __func__); + if (cdata->reader != 0) { + cdata->reader_quit = 1; + pthread_join(cdata->reader, NULL); + } + + cdata->handler_dead = 1; + + fprintf(stdout, "%s: terminated\n", __func__); + return NULL; +} + +/** + * This thread is started when a new connection is accepted. + * It performs the handshake, then waits for the connect packet and + * on success it starts the usbmuxd_client_handler thread. + */ +static void *usbmuxd_client_init_thread(void *arg) +{ + struct client_data *cdata; + struct usbmux_header hello; + struct usbmux_dev_info_request dev_info_req; + struct usbmux_connect_request c_req; + + struct usb_bus *bus; + struct usb_device *dev; + + int recv_len; + int found = 0; + int res; + int i; + int sent_result; + iphone_error_t err; + + iphone_device_t phone; + struct device_use_info *cur_dev = NULL; + + if (!arg) { + fprintf(stderr, "%s: invalid client_data provided!\n", __func__); + return NULL; + } + + cdata = (struct client_data*)arg; + cdata->dead = 0; + + fprintf(stdout, "%s: started (fd=%d)\n", __func__, cdata->socket); + + if ((recv_len = usbmuxd_get_request(cdata->socket, &hello, sizeof(hello))) <= 0) { + fprintf(stderr, "%s: No Hello packet received, error %s\n", __func__, strerror(errno)); + goto leave; + } + + if ((recv_len == 16) && (hello.length == 16) + && (hello.reserved == 0) && (hello.type == usbmux_hello)) { + // send success response + usbmuxd_send_result(cdata->socket, hello.tag, 0); + } else { + // send error response and exit + fprintf(stderr, "%s: Invalid Hello packet received.\n", __func__); + // TODO is this required?! + usbmuxd_send_result(cdata->socket, hello.tag, EINVAL); + goto leave; + } + + // gather data about all iPhones/iPods attached + usb_init(); + usb_find_busses(); + usb_find_devices(); + + for (bus = usb_get_busses(); bus; bus = bus->next) { + for (dev = bus->devices; dev; dev = dev->next) { + if (dev->descriptor.idVendor == 0x05ac + && dev->descriptor.idProduct >= 0x1290 + && dev->descriptor.idProduct <= 0x1293) + { + fprintf(stdout, "%s: Found device on bus %d, id %d\n", __func__, bus->location, dev->devnum); + found++; + + // construct packet + memset(&dev_info_req, 0, sizeof(dev_info_req)); + dev_info_req.header.length = sizeof(dev_info_req); + dev_info_req.header.type = usbmux_device_info; + dev_info_req.dev_info.device_id = dev->devnum; + dev_info_req.dev_info.product_id = dev->descriptor.idProduct; + if (dev->descriptor.iSerialNumber) { + usb_dev_handle *udev; + //pthread_mutex_lock(&usbmux_mutex); + udev = usb_open(dev); + if (udev) { + usb_get_string_simple(udev, dev->descriptor.iSerialNumber, dev_info_req.dev_info.serial_number, sizeof(dev_info_req.dev_info.serial_number)+1); + usb_close(udev); + } + //pthread_mutex_unlock(&usbmux_mutex); + } + + print_buffer((char*)&dev_info_req, sizeof(dev_info_req)); + + // send it + if (send_buf(cdata->socket, &dev_info_req, sizeof(dev_info_req)) <= 0) { + fprintf(stderr, "%s: Error: Could not send device info: %s\n", __func__, strerror(errno)); + found--; + } + } + } + } + + // now wait for connect request + if (found <= 0) { + fprintf(stderr, "%s: No attached iPhone/iPod devices found.\n", __func__); + goto leave; + } + + memset(&c_req, 0, sizeof(c_req)); + if ((recv_len = usbmuxd_get_request(cdata->socket, &c_req, sizeof(c_req))) <= 0) { + fprintf(stderr, "%s: Did not receive any connect request.\n", __func__); + goto leave; + } + + if (c_req.header.type != usbmux_connect) { + fprintf(stderr, "%s: Unexpected packet of type %d received.\n", __func__, c_req.header.type); + goto leave; + } + + fprintf(stdout, "%s: Setting up connection to usb device #%d on port %d\n", __func__, c_req.device_id, ntohs(c_req.port)); + + // find the device, and open usb connection + phone = NULL; + cur_dev = NULL; + // first check if we already have an open connection + if (device_use_list) { + pthread_mutex_lock(&usbmux_mutex); + for (i = 0; i < device_use_count; i++) { + if (device_use_list[i]) { + if (device_use_list[i]->device_id == c_req.device_id) { + device_use_list[i]->use_count++; + cur_dev = device_use_list[i]; + phone = cur_dev->phone; + break; + } + } + } + pthread_mutex_unlock(&usbmux_mutex); + } + if (!phone) { + // if not found, make a new connection + if (iphone_get_specific_device(0, c_req.device_id, &phone) != IPHONE_E_SUCCESS) { + fprintf(stderr, "%s: device_id %d could not be opened\n", __func__, c_req.device_id); + usbmuxd_send_result(cdata->socket, c_req.header.tag, ENODEV); + goto leave; + } + // add to device list + cur_dev = (struct device_use_info*)malloc(sizeof(struct device_use_info)); + memset(cur_dev, 0, sizeof(struct device_use_info)); + cur_dev->use_count = 1; + cur_dev->device_id = c_req.device_id; + cur_dev->phone = phone; + + pthread_mutex_lock(&usbmux_mutex); + device_use_list = (struct device_use_info**)realloc(device_use_list, sizeof(struct device_use_info*) * (device_use_count+1)); + if (device_use_list) { + device_use_list[device_use_count] = cur_dev; + device_use_count++; + } + pthread_mutex_unlock(&usbmux_mutex); + } else { + fprintf(stdout, "%s: reusing usb connection device_id %d\n", __func__, c_req.device_id); + } + + // setup connection to iPhone/iPod +// pthread_mutex_lock(&usbmux_mutex); + res = iphone_mux_new_client(cur_dev->phone, 0, ntohs(c_req.port), &(cdata->muxclient)); +// pthread_mutex_unlock(&usbmux_mutex); + + if (res != 0) { + usbmuxd_send_result(cdata->socket, c_req.header.tag, res); + fprintf(stderr, "%s: mux_new_client returned %d, aborting.\n", __func__, res); + goto leave; + } + + // start connection handler thread + cdata->handler_dead = 0; + cdata->tag = c_req.header.tag; + if (pthread_create(&cdata->handler, NULL, usbmuxd_client_handler_thread, cdata) != 0) { + fprintf(stderr, "%s: could not create usbmuxd_client_handler_thread!\n", __func__); + cdata->handler = 0; + goto leave; + } + + sent_result = 0; + + // start reading data from the connected device + while (!quit_flag && !cdata->handler_dead) { + iphone_mux_pullbulk(cur_dev->phone); + err = iphone_mux_get_error(cdata->muxclient); + if (err != IPHONE_E_SUCCESS) { + break; + /*} else if (!sent_result) { + usbmuxd_send_result(cdata->socket, c_req.header.tag, 0); + sent_result = 1;*/ + } + } + + if (!sent_result) { + //fprintf(stderr, "Sending error message %d tag %d\n", err, c_req.header.tag); + err = iphone_mux_get_error(cdata->muxclient); + //usbmuxd_send_result(cdata->socket, c_req.header.tag, err); + } + + fprintf(stdout, "%s: terminating\n", __func__); + + // wait for handler thread to finish its work + if (cdata->handler != 0) { + pthread_join(cdata->handler, NULL); + } + + // time to clean up + if (cdata && cdata->muxclient) { // should be non-NULL + iphone_mux_free_client(cdata->muxclient); + } + +leave: + // this has to be freed only if it's not in use anymore as it closes + // the USB connection + if (cur_dev) { + if (cur_dev->use_count > 1) { + cur_dev->use_count--; + } else { + iphone_free_device(cur_dev->phone); + cur_dev->use_count = 0; + free(cur_dev); + cur_dev = NULL; + pthread_mutex_lock(&usbmux_mutex); + if (device_use_count > 1) { + struct device_use_info **newlist; + int j; + + newlist = (struct device_use_info**)malloc(sizeof(struct device_use_info*) * device_use_count-1); + for (i = 0; i < device_use_count; i++) { + if (device_use_list[i] != NULL) { + newlist[j++] = device_use_list[i]; + } + } + free(device_use_list); + device_use_list = newlist; + } else { + free(device_use_list); + device_use_list = NULL; + } + pthread_mutex_unlock(&usbmux_mutex); + } + } + + cdata->dead = 1; + + fprintf(stdout, "%s: terminated\n", __func__); + + return NULL; +} + +/** + * make this program run detached from the current console + */ +static int daemonize() +{ + // TODO still to be implemented, also logging is missing! + return 0; +} + +/** + * signal handler function for cleaning up stuff + */ +static void clean_exit(int sig) +{ + if (sig == SIGINT) { + fprintf(stdout, "CTRL+C pressed\n"); + } + quit_flag = 1; +} + +/** + * thread function that performs accept() and starts the required child + * threads to perform the rest of the communication stuff. + */ +static void *usbmuxd_accept_thread(void *arg) +{ + struct sockaddr_un c_addr; + socklen_t len = sizeof(struct sockaddr_un); + struct client_data *cdata; + struct client_data **children = NULL; + int children_capacity = DEFAULT_CHILDREN_CAPACITY; + int i = 0; + int result = 0; + int cnt; + + // Reserve space for 10 clients which should be enough. If not, the + // buffer gets enlarged later. + children = (struct client_data**)malloc(sizeof(struct client_data*) * children_capacity); + if (!children) { + fprintf(stderr, "%s: Out of memory when allocating memory for child threads. Terminating.\n", __func__); + exit(EXIT_FAILURE); + } + memset(children, 0, sizeof(struct client_data*) * children_capacity); + + fprintf(stdout, "%s: waiting for connection\n", __func__); + while (!quit_flag) { + // Check the file descriptor before accepting a connection. + // If no connection attempt is made, just repeat... + result = check_fd(fsock, fdread, DEFAULT_TIMEOUT); + if (result <= 0) { + if (result == 0) { + // cleanup + for (i = 0; i < children_capacity; i++) { + if (children[i]) { + if (children[i]->dead != 0) { + pthread_join(children[i]->thread, NULL); + fprintf(stdout, "%s: reclaimed client thread (fd=%d)\n", __func__, children[i]->socket); + free(children[i]); + children[i] = NULL; + cnt++; + } else { + cnt = 0; + } + } else { + cnt++; + } + } + + if ((children_capacity > DEFAULT_CHILDREN_CAPACITY) + && ((children_capacity - cnt) <= DEFAULT_CHILDREN_CAPACITY)) { + children_capacity = DEFAULT_CHILDREN_CAPACITY; + children = realloc(children, sizeof(struct client_data*) * children_capacity); + } + continue; + } else { + fprintf(stderr, "select error: %s\n", strerror(errno)); + continue; + } + } + + cdata = (struct client_data*)malloc(sizeof(struct client_data)); + memset(cdata, 0, sizeof(struct client_data)); + if (!cdata) { + quit_flag = 1; + fprintf(stderr, "%s: Error: Out of memory! Terminating.\n", __func__); + break; + } + + cdata->socket = accept(fsock, (struct sockaddr*)&c_addr, &len); + if (cdata->socket < 0) { + free(cdata); + if (errno == EINTR) { + continue; + } else { + fprintf(stderr, "%s: Error in accept: %s\n", __func__, strerror(errno)); + continue; + } + } + + fprintf(stdout, "%s: new client connected (fd=%d)\n", __func__, cdata->socket); + + // create client thread: + if (pthread_create(&cdata->thread, NULL, usbmuxd_client_init_thread, cdata) == 0) { + for (i = 0; i < children_capacity; i++) { + if (children[i] == NULL) break; + } + if (i == children_capacity) { + // enlarge buffer + children_capacity++; + children = realloc(children, sizeof(struct client_data*) * children_capacity); + if (!children) { + fprintf(stderr, "%s: Out of memory when enlarging child thread buffer\n", __func__); + } + } + children[i] = cdata; + } else { + fprintf(stderr, "%s: Failed to create client_init_thread.\n", __func__); + close(cdata->socket); + free(cdata); + cdata = NULL; + } + } + + fprintf(stdout, "%s: terminating\n", __func__); + + // preparing for shutdown: wait for child threads to terminate (if any) + fprintf(stdout, "%s: waiting for child threads to terminate...\n", __func__); + for (i = 0; i < children_capacity; i++) { + if (children[i] != NULL) { + pthread_join(children[i]->thread, NULL); + free(children[i]); + } + } + + // delete the children set. + free(children); + children = NULL; + + fprintf(stdout, "%s: terminated.\n", __func__); + + return NULL; +} + +int main(int argc, char **argv) +{ + int foreground = 1; + pthread_t acceptor; + + fprintf(stdout, "usbmuxd: starting\n"); + + // TODO: Parameter checking. + + fsock = create_unix_socket(SOCKET_FILE); + if (fsock < 0) { + fprintf(stderr, "Could not create socket, exiting\n"); + return -1; + } + + chmod(SOCKET_FILE, 0666); + + if (!foreground) { + if (daemonize() < 0) { + exit(EXIT_FAILURE); + } + } + + // signal(SIGHUP, reload_conf); // none yet + signal(SIGINT, clean_exit); + signal(SIGQUIT, clean_exit); + signal(SIGTERM, clean_exit); + signal(SIGPIPE, SIG_IGN); + + if (pthread_create(&acceptor, NULL, usbmuxd_accept_thread, NULL) != 0) { + fprintf(stderr, "Failed to create server thread.\n"); + close(fsock); + return -1; + } + + // Relax here. Just wait for the accept thread to terminate. + pthread_join(acceptor, NULL); + + fprintf(stdout, "usbmuxd: terminating\n"); + if (fsock >= 0) { + close(fsock); + } + + unlink(SOCKET_FILE); + + return 0; +} + diff --git a/usbmuxd.h b/usbmuxd.h new file mode 100644 index 0000000..fcbee52 --- /dev/null +++ b/usbmuxd.h @@ -0,0 +1,44 @@ +#ifndef __USBMUXD_H +#define __USBMUXD_H + +#include + +struct usbmux_header { + uint32_t length; // length of message, including header + uint32_t reserved; // always zero + uint32_t type; // message type + uint32_t tag; // responses to this query will echo back this tag +}; + +struct usbmux_result { + struct usbmux_header header; + uint32_t result; +}; + +struct usbmux_connect_request { + struct usbmux_header header; + uint32_t device_id; + uint16_t port; // TCP port number + uint16_t reserved; // set to zero +}; + +struct usbmux_dev_info { + uint32_t device_id; + uint16_t product_id; + char serial_number[40]; +}; + +struct usbmux_dev_info_request { + struct usbmux_header header; + struct usbmux_dev_info dev_info; + unsigned char padding[222]; +}; + +enum { + usbmux_result = 1, + usbmux_connect = 2, + usbmux_hello = 3, + usbmux_device_info = 4, +}; + +#endif -- cgit v1.1-32-gdbae