diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/Makefile.am | 32 | ||||
-rw-r--r-- | src/client.c | 1058 | ||||
-rw-r--r-- | src/client.h | 47 | ||||
-rw-r--r-- | src/conf.c | 535 | ||||
-rw-r--r-- | src/conf.h | 40 | ||||
-rw-r--r-- | src/device.c | 1037 | ||||
-rw-r--r-- | src/device.h | 56 | ||||
-rw-r--r-- | src/log.c | 101 | ||||
-rw-r--r-- | src/log.h | 42 | ||||
-rw-r--r-- | src/main.c | 920 | ||||
-rw-r--r-- | src/preflight.c | 406 | ||||
-rw-r--r-- | src/preflight.h | 28 | ||||
-rw-r--r-- | src/usb.c | 1084 | ||||
-rw-r--r-- | src/usb.h | 73 | ||||
-rw-r--r-- | src/usbmuxd-proto.h | 95 | ||||
-rw-r--r-- | src/utils.c | 131 | ||||
-rw-r--r-- | src/utils.h | 49 |
17 files changed, 5734 insertions, 0 deletions
diff --git a/src/Makefile.am b/src/Makefile.am new file mode 100644 index 0000000..8a96e46 --- /dev/null +++ b/src/Makefile.am @@ -0,0 +1,32 @@ +AM_CPPFLAGS = \ + -I$(top_srcdir)/include \ + -I$(top_srcdir) + +AM_CFLAGS = \ + $(GLOBAL_CFLAGS) \ + $(libplist_CFLAGS) \ + $(libusb_CFLAGS) \ + $(limd_glue_CFLAGS) \ + $(libimobiledevice_CFLAGS) + +AM_LDFLAGS = \ + $(libplist_LIBS) \ + $(libusb_LIBS) \ + $(limd_glue_LIBS) \ + $(libimobiledevice_LIBS) \ + $(libpthread_LIBS) + +sbin_PROGRAMS = usbmuxd + +usbmuxd_CFLAGS = $(AM_CFLAGS) +usbmuxd_LDFLAGS = $(AM_LDFLAGS) -no-undefined +usbmuxd_SOURCES = \ + client.c client.h \ + device.c device.h \ + preflight.c preflight.h \ + log.c log.h \ + usbmuxd-proto.h \ + usb.c usb.h \ + utils.c utils.h \ + conf.c conf.h \ + main.c diff --git a/src/client.c b/src/client.c new file mode 100644 index 0000000..dbbdd5f --- /dev/null +++ b/src/client.c @@ -0,0 +1,1058 @@ +/* + * client.c + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#define _GNU_SOURCE 1 + +#include <stdlib.h> +#include <string.h> +#include <stdio.h> +#include <errno.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <sys/un.h> +#include <arpa/inet.h> +#include <fcntl.h> + +#include <plist/plist.h> +#include <libimobiledevice-glue/collection.h> +#include <libimobiledevice-glue/thread.h> + +#include "log.h" +#include "usb.h" +#include "client.h" +#include "device.h" +#include "conf.h" + +#define CMD_BUF_SIZE 0x10000 +#define REPLY_BUF_SIZE 0x10000 + +enum client_state { + CLIENT_COMMAND, // waiting for command + CLIENT_LISTEN, // listening for devices + CLIENT_CONNECTING1, // issued connection request + CLIENT_CONNECTING2, // connection established, but waiting for response message to get sent + CLIENT_CONNECTED, // connected + CLIENT_DEAD +}; + +struct mux_client { + int fd; + unsigned char *ob_buf; + uint32_t ob_size; + uint32_t ob_capacity; + unsigned char *ib_buf; + uint32_t ib_size; + uint32_t ib_capacity; + short events, devents; + uint32_t connect_tag; + int connect_device; + enum client_state state; + uint32_t proto_version; + uint32_t number; + plist_t info; +}; + +static struct collection client_list; +mutex_t client_list_mutex; +static uint32_t client_number = 0; + +#ifdef SO_PEERCRED +static char* _get_process_name_by_pid(const int pid) +{ + char* name = (char*)calloc(1024, sizeof(char)); + if(name) { + sprintf(name, "/proc/%d/cmdline", pid); + FILE* f = fopen(name, "r"); + if(f) { + size_t size; + size = fread(name, sizeof(char), 1024, f); + if(size > 0) { + if('\n' == name[size-1]) + name[size-1]='\0'; + } + fclose(f); + } + } + return name; +} +#endif + +/** + * Receive raw data from the client socket. + * + * @param client Client to read from. + * @param buffer Buffer to store incoming data. + * @param len Max number of bytes to read. + * @return Same as recv() system call. Number of bytes read; when < 0 errno will be set. + */ +int client_read(struct mux_client *client, void *buffer, uint32_t len) +{ + usbmuxd_log(LL_SPEW, "client_read fd %d buf %p len %d", client->fd, buffer, len); + if(client->state != CLIENT_CONNECTED) { + usbmuxd_log(LL_ERROR, "Attempted to read from client %d not in CONNECTED state", client->fd); + return -1; + } + return recv(client->fd, buffer, len, 0); +} + +/** + * Send raw data to the client socket. + * + * @param client Client to send to. + * @param buffer The data to send. + * @param len Number of bytes to write. + * @return Same as system call send(). Number of bytes written; when < 0 errno will be set. + */ +int client_write(struct mux_client *client, void *buffer, uint32_t len) +{ + int sret = -1; + + usbmuxd_log(LL_SPEW, "client_write fd %d buf %p len %d", client->fd, buffer, len); + if(client->state != CLIENT_CONNECTED) { + usbmuxd_log(LL_ERROR, "Attempted to write to client %d not in CONNECTED state", client->fd); + return -1; + } + + sret = send(client->fd, buffer, len, 0); + if (sret < 0) { + if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { + usbmuxd_log(LL_DEBUG, "client_write: fd %d not ready for writing", client->fd); + sret = 0; + } else { + usbmuxd_log(LL_ERROR, "ERROR: client_write: sending to fd %d failed: %s", client->fd, strerror(errno)); + } + } + return sret; +} + +/** + * Set event mask to use for ppoll()ing the client socket. + * Typically POLLOUT and/or POLLIN. Note that this overrides + * the current mask, that is, it is not ORing the argument + * into the current mask. + * + * @param client The client to set the event mask on. + * @param events The event mask to sert. + * @return 0 on success, -1 on error. + */ +int client_set_events(struct mux_client *client, short events) +{ + if((client->state != CLIENT_CONNECTED) && (client->state != CLIENT_CONNECTING2)) { + usbmuxd_log(LL_ERROR, "client_set_events to client %d not in CONNECTED state", client->fd); + return -1; + } + client->devents = events; + if(client->state == CLIENT_CONNECTED) + client->events = events; + return 0; +} + +/** + * Wait for an inbound connection on the usbmuxd socket + * and create a new mux_client instance for it, and store + * the client in the client list. + * + * @param listenfd the socket fd to accept() on. + * @return The connection fd for the client, or < 0 for error + * in which case errno will be set. + */ +int client_accept(int listenfd) +{ + struct sockaddr_un addr; + int cfd; + socklen_t len = sizeof(struct sockaddr_un); + cfd = accept(listenfd, (struct sockaddr *)&addr, &len); + if (cfd < 0) { + usbmuxd_log(LL_ERROR, "accept() failed (%s)", strerror(errno)); + return cfd; + } + + int flags = fcntl(cfd, F_GETFL, 0); + if (flags < 0) { + usbmuxd_log(LL_ERROR, "ERROR: Could not get socket flags!"); + } else { + if (fcntl(cfd, F_SETFL, flags | O_NONBLOCK) < 0) { + usbmuxd_log(LL_ERROR, "ERROR: Could not set socket to non-blocking mode"); + } + } + + int bufsize = 0x20000; + if (setsockopt(cfd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int)) == -1) { + usbmuxd_log(LL_WARNING, "Could not set send buffer for client socket"); + } + if (setsockopt(cfd, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int)) == -1) { + usbmuxd_log(LL_WARNING, "Could not set receive buffer for client socket"); + } + + int yes = 1; + setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, (void*)&yes, sizeof(int)); + + struct mux_client *client; + client = malloc(sizeof(struct mux_client)); + memset(client, 0, sizeof(struct mux_client)); + + client->fd = cfd; + client->ob_buf = malloc(REPLY_BUF_SIZE); + client->ob_size = 0; + client->ob_capacity = REPLY_BUF_SIZE; + client->ib_buf = malloc(CMD_BUF_SIZE); + client->ib_size = 0; + client->ib_capacity = CMD_BUF_SIZE; + client->state = CLIENT_COMMAND; + client->events = POLLIN; + client->info = NULL; + + mutex_lock(&client_list_mutex); + client->number = client_number++; + collection_add(&client_list, client); + mutex_unlock(&client_list_mutex); + +#ifdef SO_PEERCRED + if (log_level >= LL_INFO) { + struct ucred cr; + len = sizeof(struct ucred); + getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &cr, &len); + + if (getpid() == cr.pid) { + usbmuxd_log(LL_INFO, "Client %d accepted: %s[%d]", client->fd, PACKAGE_NAME, cr.pid); + } else { + char* process_name = _get_process_name_by_pid(cr.pid); + usbmuxd_log(LL_INFO, "Client %d accepted: %s[%d]", client->fd, process_name, cr.pid); + free(process_name); + } + } +#else + usbmuxd_log(LL_INFO, "Client %d accepted", client->fd); +#endif + return client->fd; +} + +void client_close(struct mux_client *client) +{ + int found = 0; + mutex_lock(&client_list_mutex); + FOREACH(struct mux_client *lc, &client_list) { + if (client == lc) { + found = 1; + break; + } + } ENDFOREACH + if (!found) { + // in case we get called again but client was already freed + usbmuxd_log(LL_DEBUG, "%s: ignoring for non-existing client %p", __func__, client); + mutex_unlock(&client_list_mutex); + return; + } +#ifdef SO_PEERCRED + if (log_level >= LL_INFO) { + struct ucred cr; + socklen_t len = sizeof(struct ucred); + getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &cr, &len); + + if (getpid() == cr.pid) { + usbmuxd_log(LL_INFO, "Client %d is going to be disconnected: %s[%d]", client->fd, PACKAGE_NAME, cr.pid); + } else { + char* process_name = _get_process_name_by_pid(cr.pid); + usbmuxd_log(LL_INFO, "Client %d is going to be disconnected: %s[%d]", client->fd, process_name, cr.pid); + free(process_name); + } + } +#else + usbmuxd_log(LL_INFO, "Client %d is going to be disconnected", client->fd); +#endif + if(client->state == CLIENT_CONNECTING1 || client->state == CLIENT_CONNECTING2) { + usbmuxd_log(LL_INFO, "Client died mid-connect, aborting device %d connection", client->connect_device); + client->state = CLIENT_DEAD; + device_abort_connect(client->connect_device, client); + } + close(client->fd); + free(client->ob_buf); + free(client->ib_buf); + plist_free(client->info); + + collection_remove(&client_list, client); + mutex_unlock(&client_list_mutex); + free(client); +} + +void client_get_fds(struct fdlist *list) +{ + mutex_lock(&client_list_mutex); + FOREACH(struct mux_client *client, &client_list) { + fdlist_add(list, FD_CLIENT, client->fd, client->events); + } ENDFOREACH + mutex_unlock(&client_list_mutex); +} + +static int output_buffer_add_message(struct mux_client *client, uint32_t tag, enum usbmuxd_msgtype msg, void *payload, int payload_length) +{ + struct usbmuxd_header hdr; + hdr.version = client->proto_version; + hdr.length = sizeof(hdr) + payload_length; + hdr.message = msg; + hdr.tag = tag; + usbmuxd_log(LL_DEBUG, "Client %d output buffer got tag %d msg %d payload_length %d", client->fd, tag, msg, payload_length); + + uint32_t available = client->ob_capacity - client->ob_size; + /* the output buffer _should_ be large enough, but just in case */ + if(available < hdr.length) { + unsigned char* new_buf; + uint32_t new_size = ((client->ob_capacity + hdr.length + 4096) / 4096) * 4096; + usbmuxd_log(LL_DEBUG, "%s: Enlarging client %d output buffer %d -> %d", __func__, client->fd, client->ob_capacity, new_size); + new_buf = realloc(client->ob_buf, new_size); + if (!new_buf) { + usbmuxd_log(LL_FATAL, "%s: Failed to realloc.", __func__); + return -1; + } + client->ob_buf = new_buf; + client->ob_capacity = new_size; + } + memcpy(client->ob_buf + client->ob_size, &hdr, sizeof(hdr)); + if(payload && payload_length) + memcpy(client->ob_buf + client->ob_size + sizeof(hdr), payload, payload_length); + client->ob_size += hdr.length; + client->events |= POLLOUT; + return hdr.length; +} + +static int send_plist(struct mux_client *client, uint32_t tag, plist_t plist) +{ + int res = -1; + char *xml = NULL; + uint32_t xmlsize = 0; + plist_to_xml(plist, &xml, &xmlsize); + if (xml) { + res = output_buffer_add_message(client, tag, MESSAGE_PLIST, xml, xmlsize); + free(xml); + } else { + usbmuxd_log(LL_ERROR, "%s: Could not convert plist to xml", __func__); + } + return res; +} + +static int send_result(struct mux_client *client, uint32_t tag, uint32_t result) +{ + int res = -1; + if (client->proto_version == 1) { + /* XML plist packet */ + plist_t dict = plist_new_dict(); + plist_dict_set_item(dict, "MessageType", plist_new_string("Result")); + plist_dict_set_item(dict, "Number", plist_new_uint(result)); + res = send_plist(client, tag, dict); + plist_free(dict); + } else { + /* binary packet */ + res = output_buffer_add_message(client, tag, MESSAGE_RESULT, &result, sizeof(uint32_t)); + } + return res; +} + +int client_notify_connect(struct mux_client *client, enum usbmuxd_result result) +{ + usbmuxd_log(LL_SPEW, "client_notify_connect fd %d result %d", client->fd, result); + if(client->state == CLIENT_DEAD) + return -1; + if(client->state != CLIENT_CONNECTING1) { + usbmuxd_log(LL_ERROR, "client_notify_connect when client %d is not in CONNECTING1 state", client->fd); + return -1; + } + if(send_result(client, client->connect_tag, result) < 0) + return -1; + if(result == RESULT_OK) { + client->state = CLIENT_CONNECTING2; + client->events = POLLOUT; // wait for the result packet to go through + // no longer need this + free(client->ib_buf); + client->ib_buf = NULL; + } else { + client->state = CLIENT_COMMAND; + } + return 0; +} + +static plist_t create_device_attached_plist(struct device_info *dev) +{ + plist_t dict = plist_new_dict(); + plist_dict_set_item(dict, "MessageType", plist_new_string("Attached")); + plist_dict_set_item(dict, "DeviceID", plist_new_uint(dev->id)); + plist_t props = plist_new_dict(); + plist_dict_set_item(props, "ConnectionSpeed", plist_new_uint(dev->speed)); + plist_dict_set_item(props, "ConnectionType", plist_new_string("USB")); + plist_dict_set_item(props, "DeviceID", plist_new_uint(dev->id)); + plist_dict_set_item(props, "LocationID", plist_new_uint(dev->location)); + plist_dict_set_item(props, "ProductID", plist_new_uint(dev->pid)); + plist_dict_set_item(props, "SerialNumber", plist_new_string(dev->serial)); + plist_dict_set_item(dict, "Properties", props); + return dict; +} + +static int send_device_list(struct mux_client *client, uint32_t tag) +{ + int res = -1; + plist_t dict = plist_new_dict(); + plist_t devices = plist_new_array(); + + struct device_info *devs = NULL; + struct device_info *dev; + int i; + + int count = device_get_list(0, &devs); + dev = devs; + for (i = 0; devs && i < count; i++) { + plist_t device = create_device_attached_plist(dev++); + if (device) { + plist_array_append_item(devices, device); + } + } + if (devs) + free(devs); + + plist_dict_set_item(dict, "DeviceList", devices); + res = send_plist(client, tag, dict); + plist_free(dict); + return res; +} + +static int send_listener_list(struct mux_client *client, uint32_t tag) +{ + int res = -1; + + plist_t dict = plist_new_dict(); + plist_t listeners = plist_new_array(); + + mutex_lock(&client_list_mutex); + FOREACH(struct mux_client *lc, &client_list) { + if (lc->state == CLIENT_LISTEN) { + plist_t n = NULL; + plist_t l = plist_new_dict(); + plist_dict_set_item(l, "Blacklisted", plist_new_bool(0)); + n = NULL; + if (lc->info) { + n = plist_dict_get_item(lc->info, "BundleID"); + } + if (n) { + plist_dict_set_item(l, "BundleID", plist_copy(n)); + } + plist_dict_set_item(l, "ConnType", plist_new_uint(0)); + + n = NULL; + char *progname = NULL; + if (lc->info) { + n = plist_dict_get_item(lc->info, "ProgName"); + } + if (n) { + plist_get_string_val(n, &progname); + } + if (!progname) { + progname = strdup("unknown"); + } + char *idstring = malloc(strlen(progname) + 12); + sprintf(idstring, "%u-%s", client->number, progname); + + plist_dict_set_item(l, "ID String", plist_new_string(idstring)); + free(idstring); + plist_dict_set_item(l, "ProgName", plist_new_string(progname)); + free(progname); + + n = NULL; + uint64_t version = 0; + if (lc->info) { + n = plist_dict_get_item(lc->info, "kLibUSBMuxVersion"); + } + if (n) { + plist_get_uint_val(n, &version); + } + plist_dict_set_item(l, "kLibUSBMuxVersion", plist_new_uint(version)); + + plist_array_append_item(listeners, l); + } + } ENDFOREACH + mutex_unlock(&client_list_mutex); + + plist_dict_set_item(dict, "ListenerList", listeners); + res = send_plist(client, tag, dict); + plist_free(dict); + + return res; +} + +static int send_system_buid(struct mux_client *client, uint32_t tag) +{ + int res = -1; + char* buid = NULL; + + config_get_system_buid(&buid); + + plist_t dict = plist_new_dict(); + plist_dict_set_item(dict, "BUID", plist_new_string(buid)); + free(buid); + res = send_plist(client, tag, dict); + plist_free(dict); + return res; +} + +static int send_pair_record(struct mux_client *client, uint32_t tag, const char* record_id) +{ + int res = -1; + char* record_data = NULL; + uint64_t record_size = 0; + + if (!record_id) { + return send_result(client, tag, EINVAL); + } + + config_get_device_record(record_id, &record_data, &record_size); + + if (record_data) { + plist_t dict = plist_new_dict(); + plist_dict_set_item(dict, "PairRecordData", plist_new_data(record_data, record_size)); + free(record_data); + res = send_plist(client, tag, dict); + plist_free(dict); + } else { + res = send_result(client, tag, ENOENT); + } + return res; +} + +static int send_device_add(struct mux_client *client, struct device_info *dev) +{ + int res = -1; + if (client->proto_version == 1) { + /* XML plist packet */ + plist_t dict = create_device_attached_plist(dev); + res = send_plist(client, 0, dict); + plist_free(dict); + } else { + /* binary packet */ + struct usbmuxd_device_record dmsg; + memset(&dmsg, 0, sizeof(dmsg)); + dmsg.device_id = dev->id; + strncpy(dmsg.serial_number, dev->serial, 256); + dmsg.serial_number[255] = 0; + dmsg.location = dev->location; + dmsg.product_id = dev->pid; + res = output_buffer_add_message(client, 0, MESSAGE_DEVICE_ADD, &dmsg, sizeof(dmsg)); + } + return res; +} + +static int send_device_remove(struct mux_client *client, uint32_t device_id) +{ + int res = -1; + if (client->proto_version == 1) { + /* XML plist packet */ + plist_t dict = plist_new_dict(); + plist_dict_set_item(dict, "MessageType", plist_new_string("Detached")); + plist_dict_set_item(dict, "DeviceID", plist_new_uint(device_id)); + res = send_plist(client, 0, dict); + plist_free(dict); + } else { + /* binary packet */ + res = output_buffer_add_message(client, 0, MESSAGE_DEVICE_REMOVE, &device_id, sizeof(uint32_t)); + } + return res; +} + +static int send_device_paired(struct mux_client *client, uint32_t device_id) +{ + int res = -1; + if (client->proto_version == 1) { + /* XML plist packet */ + plist_t dict = plist_new_dict(); + plist_dict_set_item(dict, "MessageType", plist_new_string("Paired")); + plist_dict_set_item(dict, "DeviceID", plist_new_uint(device_id)); + res = send_plist(client, 0, dict); + plist_free(dict); + } + else { + /* binary packet */ + res = output_buffer_add_message(client, 0, MESSAGE_DEVICE_PAIRED, &device_id, sizeof(uint32_t)); + } + return res; +} + +static int start_listen(struct mux_client *client) +{ + struct device_info *devs = NULL; + struct device_info *dev; + int count, i; + + client->state = CLIENT_LISTEN; + + count = device_get_list(0, &devs); + dev = devs; + for(i=0; devs && i < count; i++) { + if(send_device_add(client, dev++) < 0) { + free(devs); + return -1; + } + } + if (devs) + free(devs); + + return count; +} + +static char* plist_dict_get_string_val(plist_t dict, const char* key) +{ + if (!dict || plist_get_node_type(dict) != PLIST_DICT) + return NULL; + plist_t item = plist_dict_get_item(dict, key); + if (!item || plist_get_node_type(item) != PLIST_STRING) + return NULL; + char *str = NULL; + plist_get_string_val(item, &str); + return str; +} + +static void update_client_info(struct mux_client *client, plist_t dict) +{ + plist_t node = NULL; + plist_t info = plist_new_dict(); + + node = plist_dict_get_item(dict, "BundleID"); + if (node && (plist_get_node_type(node) == PLIST_STRING)) { + plist_dict_set_item(info, "BundleID", plist_copy(node)); + } + + node = plist_dict_get_item(dict, "ClientVersionString"); + if (node && (plist_get_node_type(node) == PLIST_STRING)) { + plist_dict_set_item(info, "ClientVersionString", plist_copy(node)); + } + + node = plist_dict_get_item(dict, "ProgName"); + if (node && (plist_get_node_type(node) == PLIST_STRING)) { + plist_dict_set_item(info, "ProgName", plist_copy(node)); + } + + node = plist_dict_get_item(dict, "kLibUSBMuxVersion"); + if (node && (plist_get_node_type(node) == PLIST_UINT)) { + plist_dict_set_item(info, "kLibUSBMuxVersion", plist_copy(node)); + } + plist_free(client->info); + client->info = info; +} + +static int handle_command(struct mux_client *client, struct usbmuxd_header *hdr) +{ + int res; + usbmuxd_log(LL_DEBUG, "Client %d command len %d ver %d msg %d tag %d", client->fd, hdr->length, hdr->version, hdr->message, hdr->tag); + + if(client->state != CLIENT_COMMAND) { + usbmuxd_log(LL_ERROR, "Client %d command received in the wrong state, got %d but want %d", client->fd, client->state, CLIENT_COMMAND); + if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) + return -1; + client_close(client); + return -1; + } + + if((hdr->version != 0) && (hdr->version != 1)) { + usbmuxd_log(LL_INFO, "Client %d version mismatch: expected 0 or 1, got %d", client->fd, hdr->version); + send_result(client, hdr->tag, RESULT_BADVERSION); + return 0; + } + + struct usbmuxd_connect_request *ch; + char *payload; + uint32_t payload_size; + + switch(hdr->message) { + case MESSAGE_PLIST: + client->proto_version = 1; + payload = (char*)(hdr) + sizeof(struct usbmuxd_header); + payload_size = hdr->length - sizeof(struct usbmuxd_header); + plist_t dict = NULL; + plist_from_xml(payload, payload_size, &dict); + if (!dict) { + usbmuxd_log(LL_ERROR, "Could not parse plist from payload!"); + return -1; + } else { + char *message = NULL; + plist_t node = plist_dict_get_item(dict, "MessageType"); + if (!node || plist_get_node_type(node) != PLIST_STRING) { + usbmuxd_log(LL_ERROR, "Could not read valid MessageType node from plist!"); + plist_free(dict); + return -1; + } + plist_get_string_val(node, &message); + if (!message) { + usbmuxd_log(LL_ERROR, "Could not extract MessageType from plist!"); + plist_free(dict); + return -1; + } + update_client_info(client, dict); + if (!strcmp(message, "Listen")) { + free(message); + plist_free(dict); + if (send_result(client, hdr->tag, 0) < 0) + return -1; + usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd); + return start_listen(client); + } else if (!strcmp(message, "Connect")) { + uint64_t val; + uint16_t portnum = 0; + uint32_t device_id = 0; + free(message); + // get device id + node = plist_dict_get_item(dict, "DeviceID"); + if (!node) { + usbmuxd_log(LL_ERROR, "Received connect request without device_id!"); + plist_free(dict); + if (send_result(client, hdr->tag, RESULT_BADDEV) < 0) + return -1; + return 0; + } + val = 0; + plist_get_uint_val(node, &val); + device_id = (uint32_t)val; + + // get port number + node = plist_dict_get_item(dict, "PortNumber"); + if (!node) { + usbmuxd_log(LL_ERROR, "Received connect request without port number!"); + plist_free(dict); + if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) + return -1; + return 0; + } + val = 0; + plist_get_uint_val(node, &val); + portnum = (uint16_t)val; + plist_free(dict); + + usbmuxd_log(LL_DEBUG, "Client %d requesting connection to device %d port %d", client->fd, device_id, ntohs(portnum)); + res = device_start_connect(device_id, ntohs(portnum), client); + if(res < 0) { + if (send_result(client, hdr->tag, -res) < 0) + return -1; + } else { + client->connect_tag = hdr->tag; + client->connect_device = device_id; + client->state = CLIENT_CONNECTING1; + } + return 0; + } else if (!strcmp(message, "ListDevices")) { + free(message); + plist_free(dict); + if (send_device_list(client, hdr->tag) < 0) + return -1; + return 0; + } else if (!strcmp(message, "ListListeners")) { + free(message); + plist_free(dict); + if (send_listener_list(client, hdr->tag) < 0) + return -1; + return 0; + } else if (!strcmp(message, "ReadBUID")) { + free(message); + plist_free(dict); + if (send_system_buid(client, hdr->tag) < 0) + return -1; + return 0; + } else if (!strcmp(message, "ReadPairRecord")) { + free(message); + char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); + plist_free(dict); + + res = send_pair_record(client, hdr->tag, record_id); + if (record_id) + free(record_id); + if (res < 0) + return -1; + return 0; + } else if (!strcmp(message, "SavePairRecord")) { + uint32_t rval = RESULT_OK; + free(message); + char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); + char* record_data = NULL; + uint64_t record_size = 0; + plist_t rdata = plist_dict_get_item(dict, "PairRecordData"); + if (rdata && plist_get_node_type(rdata) == PLIST_DATA) { + plist_get_data_val(rdata, &record_data, &record_size); + } + + if (record_id && record_data) { + res = config_set_device_record(record_id, record_data, record_size); + if (res < 0) { + rval = -res; + } else { + plist_t p_dev_id = plist_dict_get_item(dict, "DeviceID"); + uint32_t dev_id = 0; + if (p_dev_id && plist_get_node_type(p_dev_id) == PLIST_UINT) { + uint64_t u_dev_id = 0; + plist_get_uint_val(p_dev_id, &u_dev_id); + dev_id = (uint32_t)u_dev_id; + } + if (dev_id > 0) { + struct device_info *devs = NULL; + struct device_info *dev; + int i; + int count = device_get_list(1, &devs); + int found = 0; + dev = devs; + for (i = 0; devs && i < count; i++, dev++) { + if ((uint32_t)dev->id == dev_id && (strcmp(dev->serial, record_id) == 0)) { + found++; + break; + } + } + if (!found) { + usbmuxd_log(LL_ERROR, "ERROR: SavePairRecord: DeviceID %d (%s) is not connected\n", dev_id, record_id); + } else { + client_device_paired(dev_id); + } + free(devs); + } + } + free(record_id); + } else { + rval = EINVAL; + } + free(record_data); + plist_free(dict); + if (send_result(client, hdr->tag, rval) < 0) + return -1; + return 0; + } else if (!strcmp(message, "DeletePairRecord")) { + uint32_t rval = RESULT_OK; + free(message); + char* record_id = plist_dict_get_string_val(dict, "PairRecordID"); + plist_free(dict); + if (record_id) { + res = config_remove_device_record(record_id); + if (res < 0) { + rval = -res; + } + free(record_id); + } else { + rval = EINVAL; + } + if (send_result(client, hdr->tag, rval) < 0) + return -1; + return 0; + } else { + usbmuxd_log(LL_ERROR, "Unexpected command '%s' received!", message); + free(message); + plist_free(dict); + if (send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) + return -1; + return 0; + } + } + // should not be reached?! + return -1; + case MESSAGE_LISTEN: + if(send_result(client, hdr->tag, 0) < 0) + return -1; + usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd); + return start_listen(client); + case MESSAGE_CONNECT: + ch = (void*)hdr; + usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, ch->device_id, ntohs(ch->port)); + res = device_start_connect(ch->device_id, ntohs(ch->port), client); + if(res < 0) { + if(send_result(client, hdr->tag, -res) < 0) + return -1; + } else { + client->connect_tag = hdr->tag; + client->connect_device = ch->device_id; + client->state = CLIENT_CONNECTING1; + } + return 0; + default: + usbmuxd_log(LL_ERROR, "Client %d invalid command %d", client->fd, hdr->message); + if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) + return -1; + return 0; + } + return -1; +} + +static void output_buffer_process(struct mux_client *client) +{ + int res; + if(!client->ob_size) { + usbmuxd_log(LL_WARNING, "Client %d OUT process but nothing to send?", client->fd); + client->events &= ~POLLOUT; + return; + } + res = send(client->fd, client->ob_buf, client->ob_size, 0); + if(res <= 0) { + usbmuxd_log(LL_ERROR, "Sending to client fd %d failed: %d %s", client->fd, res, strerror(errno)); + client_close(client); + return; + } + if((uint32_t)res == client->ob_size) { + client->ob_size = 0; + client->events &= ~POLLOUT; + if(client->state == CLIENT_CONNECTING2) { + usbmuxd_log(LL_DEBUG, "Client %d switching to CONNECTED state", client->fd); + client->state = CLIENT_CONNECTED; + client->events = client->devents; + // no longer need this + free(client->ob_buf); + client->ob_buf = NULL; + } + } else { + client->ob_size -= res; + memmove(client->ob_buf, client->ob_buf + res, client->ob_size); + } +} +static void input_buffer_process(struct mux_client *client) +{ + int res; + int did_read = 0; + if(client->ib_size < sizeof(struct usbmuxd_header)) { + res = recv(client->fd, client->ib_buf + client->ib_size, sizeof(struct usbmuxd_header) - client->ib_size, 0); + if(res <= 0) { + if(res < 0) + usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno)); + else + usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd); + client_close(client); + return; + } + client->ib_size += res; + if(client->ib_size < sizeof(struct usbmuxd_header)) + return; + did_read = 1; + } + struct usbmuxd_header *hdr = (void*)client->ib_buf; + if(hdr->length > client->ib_capacity) { + usbmuxd_log(LL_INFO, "Client %d message is too long (%d bytes)", client->fd, hdr->length); + client_close(client); + return; + } + if(hdr->length < sizeof(struct usbmuxd_header)) { + usbmuxd_log(LL_ERROR, "Client %d message is too short (%d bytes)", client->fd, hdr->length); + client_close(client); + return; + } + if(client->ib_size < hdr->length) { + if(did_read) + return; //maybe we would block, so defer to next loop + res = recv(client->fd, client->ib_buf + client->ib_size, hdr->length - client->ib_size, 0); + if(res < 0) { + usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno)); + client_close(client); + return; + } else if(res == 0) { + usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd); + client_close(client); + return; + } + client->ib_size += res; + if(client->ib_size < hdr->length) + return; + } + handle_command(client, hdr); + client->ib_size = 0; +} + +void client_process(int fd, short events) +{ + struct mux_client *client = NULL; + mutex_lock(&client_list_mutex); + FOREACH(struct mux_client *lc, &client_list) { + if(lc->fd == fd) { + client = lc; + break; + } + } ENDFOREACH + mutex_unlock(&client_list_mutex); + + if(!client) { + usbmuxd_log(LL_INFO, "client_process: fd %d not found in client list", fd); + return; + } + + if(client->state == CLIENT_CONNECTED) { + usbmuxd_log(LL_SPEW, "client_process in CONNECTED state"); + device_client_process(client->connect_device, client, events); + } else { + if(events & POLLIN) { + input_buffer_process(client); + } else if(events & POLLOUT) { //not both in case client died as part of process_recv + output_buffer_process(client); + } + } + +} + +void client_device_add(struct device_info *dev) +{ + mutex_lock(&client_list_mutex); + usbmuxd_log(LL_DEBUG, "client_device_add: id %d, location 0x%x, serial %s", dev->id, dev->location, dev->serial); + device_set_visible(dev->id); + FOREACH(struct mux_client *client, &client_list) { + if(client->state == CLIENT_LISTEN) + send_device_add(client, dev); + } ENDFOREACH + mutex_unlock(&client_list_mutex); +} + +void client_device_remove(int device_id) +{ + mutex_lock(&client_list_mutex); + uint32_t id = device_id; + usbmuxd_log(LL_DEBUG, "client_device_remove: id %d", device_id); + FOREACH(struct mux_client *client, &client_list) { + if(client->state == CLIENT_LISTEN) + send_device_remove(client, id); + } ENDFOREACH + mutex_unlock(&client_list_mutex); +} + +void client_device_paired(int device_id) +{ + mutex_lock(&client_list_mutex); + uint32_t id = device_id; + usbmuxd_log(LL_DEBUG, "client_device_paired: id %d", device_id); + FOREACH(struct mux_client *client, &client_list) { + if (client->state == CLIENT_LISTEN) + send_device_paired(client, id); + } ENDFOREACH + mutex_unlock(&client_list_mutex); +} + +void client_init(void) +{ + usbmuxd_log(LL_DEBUG, "client_init"); + collection_init(&client_list); + mutex_init(&client_list_mutex); +} + +void client_shutdown(void) +{ + usbmuxd_log(LL_DEBUG, "client_shutdown"); + FOREACH(struct mux_client *client, &client_list) { + client_close(client); + } ENDFOREACH + mutex_destroy(&client_list_mutex); + collection_free(&client_list); +} diff --git a/src/client.h b/src/client.h new file mode 100644 index 0000000..6cac4db --- /dev/null +++ b/src/client.h @@ -0,0 +1,47 @@ +/* + * client.h + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef CLIENT_H +#define CLIENT_H + +#include <stdint.h> +#include "usbmuxd-proto.h" + +struct device_info; +struct mux_client; + +int client_read(struct mux_client *client, void *buffer, uint32_t len); +int client_write(struct mux_client *client, void *buffer, uint32_t len); +int client_set_events(struct mux_client *client, short events); +void client_close(struct mux_client *client); +int client_notify_connect(struct mux_client *client, enum usbmuxd_result result); + +void client_device_add(struct device_info *dev); +void client_device_remove(int device_id); +void client_device_paired(int device_id); + +int client_accept(int fd); +void client_get_fds(struct fdlist *list); +void client_process(int fd, short events); + +void client_init(void); +void client_shutdown(void); + +#endif diff --git a/src/conf.c b/src/conf.c new file mode 100644 index 0000000..2e6c97f --- /dev/null +++ b/src/conf.c @@ -0,0 +1,535 @@ +/* + * conf.c + * + * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#ifdef HAVE_SYS_TYPES_H +#include <sys/types.h> +#endif + +#include <dirent.h> +#include <libgen.h> +#include <sys/stat.h> +#include <errno.h> + +#ifdef WIN32 +#include <shlobj.h> +#endif + +#include <libimobiledevice-glue/utils.h> +#include <plist/plist.h> + +#include "conf.h" +#include "utils.h" +#include "log.h" + +#ifdef WIN32 +#define DIR_SEP '\\' +#define DIR_SEP_S "\\" +#else +#define DIR_SEP '/' +#define DIR_SEP_S "/" +#endif + +#define CONFIG_SYSTEM_BUID_KEY "SystemBUID" +#define CONFIG_HOST_ID_KEY "HostID" + +#define CONFIG_EXT ".plist" + +#ifdef WIN32 +#define CONFIG_DIR "Apple"DIR_SEP_S"Lockdown" +#else +#define CONFIG_DIR "lockdown" +#endif + +#define CONFIG_FILE "SystemConfiguration"CONFIG_EXT + +static char *__config_dir = NULL; + +#ifdef WIN32 +static char *config_utf16_to_utf8(wchar_t *unistr, long len, long *items_read, long *items_written) +{ + if (!unistr || (len <= 0)) return NULL; + char *outbuf = (char*)malloc(3*(len+1)); + int p = 0; + int i = 0; + + wchar_t wc; + + while (i < len) { + wc = unistr[i++]; + if (wc >= 0x800) { + outbuf[p++] = (char)(0xE0 + ((wc >> 12) & 0xF)); + outbuf[p++] = (char)(0x80 + ((wc >> 6) & 0x3F)); + outbuf[p++] = (char)(0x80 + (wc & 0x3F)); + } else if (wc >= 0x80) { + outbuf[p++] = (char)(0xC0 + ((wc >> 6) & 0x1F)); + outbuf[p++] = (char)(0x80 + (wc & 0x3F)); + } else { + outbuf[p++] = (char)(wc & 0x7F); + } + } + if (items_read) { + *items_read = i; + } + if (items_written) { + *items_written = p; + } + outbuf[p] = 0; + + return outbuf; +} +#endif + +const char *config_get_config_dir() +{ + char *base_config_dir = NULL; + + if (__config_dir) + return __config_dir; + +#ifdef WIN32 + wchar_t path[MAX_PATH+1]; + HRESULT hr; + LPITEMIDLIST pidl = NULL; + BOOL b = FALSE; + + hr = SHGetSpecialFolderLocation (NULL, CSIDL_COMMON_APPDATA, &pidl); + if (hr == S_OK) { + b = SHGetPathFromIDListW (pidl, path); + if (b) { + base_config_dir = config_utf16_to_utf8 (path, wcslen(path), NULL, NULL); + CoTaskMemFree (pidl); + } + } +#else +#ifdef __APPLE__ + base_config_dir = strdup("/var/db"); +#else + base_config_dir = strdup("/var/lib"); +#endif +#endif + __config_dir = string_concat(base_config_dir, DIR_SEP_S, CONFIG_DIR, NULL); + + if (__config_dir) { + int i = strlen(__config_dir)-1; + while ((i > 0) && (__config_dir[i] == DIR_SEP)) { + __config_dir[i--] = '\0'; + } + } + + free(base_config_dir); + + usbmuxd_log(LL_DEBUG, "Initialized config_dir to %s", __config_dir); + + return __config_dir; +} + +static int __mkdir(const char *dir, int mode) +{ +#ifdef WIN32 + return mkdir(dir); +#else + return mkdir(dir, mode); +#endif +} + +static int mkdir_with_parents(const char *dir, int mode) +{ + if (!dir) return -1; + if (__mkdir(dir, mode) == 0) { + return 0; + } else { + if (errno == EEXIST) return 0; + } + int res; + char *parent = strdup(dir); + char* parentdir = dirname(parent); + if (parentdir) { + res = mkdir_with_parents(parentdir, mode); + } else { + res = -1; + } + free(parent); + return res; +} + +/** + * Creates a freedesktop compatible configuration directory. + */ +static void config_create_config_dir(void) +{ + const char *config_path = config_get_config_dir(); + struct stat st; + if (stat(config_path, &st) != 0) { + mkdir_with_parents(config_path, 0755); + } +} + +static int get_rand(int min, int max) +{ + int retval = (rand() % (max - min)) + min; + return retval; +} + +static char *config_generate_uuid(int idx) +{ + char *uuid = (char *) malloc(sizeof(char) * 37); + const char *chars = "ABCDEF0123456789"; + srand(time(NULL) - idx); + int i = 0; + + for (i = 0; i < 36; i++) { + if (i == 8 || i == 13 || i == 18 || i == 23) { + uuid[i] = '-'; + continue; + } else { + uuid[i] = chars[get_rand(0, 16)]; + } + } + /* make it a real string */ + uuid[36] = '\0'; + return uuid; +} + +/** + * Generates a valid BUID for this system (which is actually a UUID). + * + * @return A null terminated string containing a valid BUID. + */ +static char *config_generate_system_buid() +{ + return config_generate_uuid(1); +} + +static int internal_set_value(const char *config_file, const char *key, plist_t value) +{ + if (!config_file) + return 0; + + /* read file into plist */ + plist_t config = NULL; + + plist_read_from_file(config_file, &config, NULL); + if (!config) { + config = plist_new_dict(); + plist_dict_set_item(config, key, value); + } else { + plist_t n = plist_dict_get_item(config, key); + if (n) { + plist_dict_remove_item(config, key); + } + plist_dict_set_item(config, key, value); + remove(config_file); + } + + /* store in config file */ + char *value_string = NULL; + if (plist_get_node_type(value) == PLIST_STRING) { + plist_get_string_val(value, &value_string); + usbmuxd_log(LL_DEBUG, "Setting key %s to %s in config file %s", key, value_string, config_file); + if (value_string) + free(value_string); + } else { + usbmuxd_log(LL_DEBUG, "Setting key %s in config file %s", key, config_file); + } + + int res = (plist_write_to_file(config, config_file, PLIST_FORMAT_XML, 0) == PLIST_ERR_SUCCESS); + + plist_free(config); + + return res; +} + +static int config_set_value(const char *key, plist_t value) +{ + const char *config_path = NULL; + char *config_file = NULL; + + /* Make sure config directory exists */ + config_create_config_dir(); + + config_path = config_get_config_dir(); + config_file = string_concat(config_path, DIR_SEP_S, CONFIG_FILE, NULL); + + int result = internal_set_value(config_file, key, value); + if (!result) { + usbmuxd_log(LL_ERROR, "ERROR: Failed to write to '%s'", config_file); + } + + free(config_file); + + return result; +} + +static int internal_get_value(const char* config_file, const char *key, plist_t *value) +{ + *value = NULL; + + /* now parse file to get the SystemBUID */ + plist_t config = NULL; + if (plist_read_from_file(config_file, &config, NULL) == PLIST_ERR_SUCCESS) { + usbmuxd_log(LL_DEBUG, "Reading key %s from config file %s", key, config_file); + plist_t n = plist_dict_get_item(config, key); + if (n) { + *value = plist_copy(n); + n = NULL; + } + } + plist_free(config); + + return 1; +} + +static int config_get_value(const char *key, plist_t *value) +{ + const char *config_path = NULL; + char *config_file = NULL; + + config_path = config_get_config_dir(); + config_file = string_concat(config_path, DIR_SEP_S, CONFIG_FILE, NULL); + + int result = internal_get_value(config_file, key, value); + + free(config_file); + + return result; +} + +/** + * Store SystemBUID in config file. + * + * @param system_buid A null terminated string containing a valid SystemBUID. + */ +static int config_set_system_buid(const char *system_buid) +{ + return config_set_value(CONFIG_SYSTEM_BUID_KEY, plist_new_string(system_buid)); +} + +/** + * Determines whether a pairing record is present for the given device. + * + * @param udid The device UDID as given by the device. + * + * @return 1 if there's a pairing record for the given udid or 0 otherwise. + */ +int config_has_device_record(const char *udid) +{ + int res = 0; + if (!udid) return 0; + + /* ensure config directory exists */ + config_create_config_dir(); + + /* build file path */ + const char *config_path = config_get_config_dir(); + char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); + + struct stat st; + + if ((stat(device_record_file, &st) == 0) && S_ISREG(st.st_mode)) + res = 1; + + free(device_record_file); + + return res; +} + +/** + * Reads the BUID from a previously generated configuration file. + * + * @param system_buid pointer to a variable that will be set to point to a + * newly allocated string containing the BUID. + * + * @note It is the responsibility of the calling function to free the returned system_buid + */ +void config_get_system_buid(char **system_buid) +{ + plist_t value = NULL; + + config_get_value(CONFIG_SYSTEM_BUID_KEY, &value); + + if (value && (plist_get_node_type(value) == PLIST_STRING)) { + plist_get_string_val(value, system_buid); + usbmuxd_log(LL_DEBUG, "Got %s %s", CONFIG_SYSTEM_BUID_KEY, *system_buid); + } + + if (value) + plist_free(value); + + if (!*system_buid) { + /* no config, generate system_buid */ + usbmuxd_log(LL_DEBUG, "No previous %s found", CONFIG_SYSTEM_BUID_KEY); + *system_buid = config_generate_system_buid(); + if (!config_set_system_buid(*system_buid)) { + usbmuxd_log(LL_WARNING, "WARNING: Failed to store SystemBUID, this might be a problem"); + } + } + + usbmuxd_log(LL_DEBUG, "Using %s as %s", *system_buid, CONFIG_SYSTEM_BUID_KEY); +} + +/** + * Store a pairing record for the given device identifier. + * + * @param udid device identifier + * @param record_data buffer containing a pairing record + * @param record_size size of buffer passed in record_data + * + * @return 0 on success or a negative errno otherwise. + */ +int config_set_device_record(const char *udid, char* record_data, uint64_t record_size) +{ + int res = 0; + + if (!udid || !record_data || record_size < 8) + return -EINVAL; + + plist_t plist = NULL; + if (memcmp(record_data, "bplist00", 8) == 0) { + plist_from_bin(record_data, record_size, &plist); + } else { + plist_from_xml(record_data, record_size, &plist); + } + + if (!plist || plist_get_node_type(plist) != PLIST_DICT) { + if (plist) + plist_free(plist); + return -EINVAL; + } + + /* ensure config directory exists */ + config_create_config_dir(); + + /* build file path */ + const char *config_path = config_get_config_dir(); + char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); + + remove(device_record_file); + + /* store file */ + if (!plist_write_to_file(plist, device_record_file, PLIST_FORMAT_XML, 0)) { + usbmuxd_log(LL_DEBUG, "Could not open '%s' for writing: %s", device_record_file, strerror(errno)); + res = -ENOENT; + } + free(device_record_file); + if (plist) + plist_free(plist); + + return res; +} + +/** + * Retrieve a pairing record for the given device identifier + * + * @param udid device identifier + * @param record_data pointer to a variable that will be set to point to a + * newly allocated buffer holding the pairing record + * @param record_size pointer to a variable that will be set to the size + * of the buffer given in record_data. + * + * @return 0 on success or a negative errno otherwise. + */ +int config_get_device_record(const char *udid, char **record_data, uint64_t *record_size) +{ + int res = 0; + + /* ensure config directory exists */ + config_create_config_dir(); + + /* build file path */ + const char *config_path = config_get_config_dir(); + char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); + + /* read file */ + buffer_read_from_filename(device_record_file, record_data, record_size); + if (!*record_data) { + usbmuxd_log(LL_ERROR, "ERROR: Failed to read '%s': %s", device_record_file, strerror(errno)); + res = -ENOENT; + } + free(device_record_file); + + return res; +} + +/** + * Remove the pairing record stored for a device from this host. + * + * @param udid The udid of the device + * + * @return 0 on success or a negative errno otherwise. + */ +int config_remove_device_record(const char *udid) +{ + int res = 0; + + /* build file path */ + const char *config_path = config_get_config_dir(); + char *device_record_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); + + /* remove file */ + if (remove(device_record_file) != 0) { + res = -errno; + usbmuxd_log(LL_DEBUG, "Could not remove %s: %s", device_record_file, strerror(errno)); + } + + free(device_record_file); + + return res; +} + +static int config_device_record_get_value(const char *udid, const char *key, plist_t *value) +{ + const char *config_path = NULL; + char *config_file = NULL; + + config_path = config_get_config_dir(); + config_file = string_concat(config_path, DIR_SEP_S, udid, CONFIG_EXT, NULL); + + int result = internal_get_value(config_file, key, value); + + free(config_file); + + return result; +} + +void config_device_record_get_host_id(const char *udid, char **host_id) +{ + plist_t value = NULL; + + config_device_record_get_value(udid, CONFIG_HOST_ID_KEY, &value); + + if (value && (plist_get_node_type(value) == PLIST_STRING)) { + plist_get_string_val(value, host_id); + } + + if (value) + plist_free(value); + + if (!*host_id) { + usbmuxd_log(LL_ERROR, "ERROR: Could not get HostID from pairing record for udid %s", udid); + } +} diff --git a/src/conf.h b/src/conf.h new file mode 100644 index 0000000..bbfa965 --- /dev/null +++ b/src/conf.h @@ -0,0 +1,40 @@ +/* + * conf.h + * + * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef CONF_H +#define CONF_H + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <plist/plist.h> + +const char *config_get_config_dir(); + +void config_get_system_buid(char **system_buid); + +int config_has_device_record(const char *udid); +int config_get_device_record(const char *udid, char **record_data, uint64_t *record_size); +int config_set_device_record(const char *udid, char* record_data, uint64_t record_size); +int config_remove_device_record(const char *udid); + +void config_device_record_get_host_id(const char *udid, char **host_id); + +#endif diff --git a/src/device.c b/src/device.c new file mode 100644 index 0000000..ce73718 --- /dev/null +++ b/src/device.c @@ -0,0 +1,1037 @@ +/* + * device.c + * + * Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com> + * Copyright (C) 2014 Mikkel Kamstrup Erlandsen <mikkel.kamstrup@xamarin.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define _DEFAULT_SOURCE +#define _BSD_SOURCE + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <sys/time.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <stdlib.h> +#include <string.h> +#include <stdint.h> +#include <inttypes.h> +#include <unistd.h> + +#include <libimobiledevice-glue/collection.h> +#include <libimobiledevice-glue/thread.h> + +#include "device.h" +#include "client.h" +#include "preflight.h" +#include "usb.h" +#include "log.h" + +int next_device_id; + +#define DEV_MRU 65536 + +#define CONN_INBUF_SIZE 262144 +#define CONN_OUTBUF_SIZE 65536 + +#define ACK_TIMEOUT 30 + +enum mux_protocol { + MUX_PROTO_VERSION = 0, + MUX_PROTO_CONTROL = 1, + MUX_PROTO_SETUP = 2, + MUX_PROTO_TCP = IPPROTO_TCP, +}; + +enum mux_dev_state { + MUXDEV_INIT, // sent version packet + MUXDEV_ACTIVE, // received version packet, active + MUXDEV_DEAD // dead +}; + +enum mux_conn_state { + CONN_CONNECTING, // SYN + CONN_CONNECTED, // SYN/SYNACK/ACK -> active + CONN_REFUSED, // RST received during SYN + CONN_DYING, // RST received + CONN_DEAD // being freed; used to prevent infinite recursion between client<->device freeing +}; + +struct mux_header +{ + uint32_t protocol; + uint32_t length; + uint32_t magic; + uint16_t tx_seq; + uint16_t rx_seq; +}; + +struct version_header +{ + uint32_t major; + uint32_t minor; + uint32_t padding; +}; + +struct mux_device; + +#define CONN_ACK_PENDING 1 + +struct mux_connection +{ + struct mux_device *dev; + struct mux_client *client; + enum mux_conn_state state; + uint16_t sport, dport; + uint32_t tx_seq, tx_ack, tx_acked, tx_win; + uint32_t rx_seq, rx_recvd, rx_ack, rx_win; + uint32_t max_payload; + uint32_t sendable; + int flags; + unsigned char *ib_buf; + uint32_t ib_size; + uint32_t ib_capacity; + unsigned char *ob_buf; + uint32_t ob_capacity; + short events; + uint64_t last_ack_time; +}; + +struct mux_device +{ + struct usb_device *usbdev; + int id; + enum mux_dev_state state; + int visible; + struct collection connections; + uint16_t next_sport; + unsigned char *pktbuf; + uint32_t pktlen; + void *preflight_cb_data; + int version; + uint16_t rx_seq; + uint16_t tx_seq; +}; + +static struct collection device_list; +mutex_t device_list_mutex; + +static struct mux_device* get_mux_device_for_id(int device_id) +{ + struct mux_device *dev = NULL; + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *cdev, &device_list) { + if(cdev->id == device_id) { + dev = cdev; + break; + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); + + return dev; +} + +static struct mux_connection* get_mux_connection(int device_id, struct mux_client *client) +{ + struct mux_connection *conn = NULL; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == device_id) { + FOREACH(struct mux_connection *lconn, &dev->connections) { + if(lconn->client == client) { + conn = lconn; + break; + } + } ENDFOREACH + break; + } + } ENDFOREACH + + return conn; +} + +static int get_next_device_id(void) +{ + while(1) { + int ok = 1; + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == next_device_id) { + next_device_id++; + ok = 0; + break; + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); + if(ok) + return next_device_id++; + } +} + +static int send_packet(struct mux_device *dev, enum mux_protocol proto, void *header, const void *data, int length) +{ + unsigned char *buffer; + int hdrlen; + int res; + + switch(proto) { + case MUX_PROTO_VERSION: + hdrlen = sizeof(struct version_header); + break; + case MUX_PROTO_SETUP: + hdrlen = 0; + break; + case MUX_PROTO_TCP: + hdrlen = sizeof(struct tcphdr); + break; + default: + usbmuxd_log(LL_ERROR, "Invalid protocol %d for outgoing packet (dev %d hdr %p data %p len %d)", proto, dev->id, header, data, length); + return -1; + } + usbmuxd_log(LL_SPEW, "send_packet(%d, 0x%x, %p, %p, %d)", dev->id, proto, header, data, length); + + int mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header)); + + int total = mux_header_size + hdrlen + length; + + if(total > USB_MTU) { + usbmuxd_log(LL_ERROR, "Tried to send packet larger than USB MTU (hdr %d data %d total %d) to device %d", hdrlen, length, total, dev->id); + return -1; + } + + buffer = malloc(total); + struct mux_header *mhdr = (struct mux_header *)buffer; + mhdr->protocol = htonl(proto); + mhdr->length = htonl(total); + if (dev->version >= 2) { + mhdr->magic = htonl(0xfeedface); + if (proto == MUX_PROTO_SETUP) { + dev->tx_seq = 0; + dev->rx_seq = 0xFFFF; + } + mhdr->tx_seq = htons(dev->tx_seq); + mhdr->rx_seq = htons(dev->rx_seq); + dev->tx_seq++; + } + memcpy(buffer + mux_header_size, header, hdrlen); + if(data && length) + memcpy(buffer + mux_header_size + hdrlen, data, length); + + if((res = usb_send(dev->usbdev, buffer, total)) < 0) { + usbmuxd_log(LL_ERROR, "usb_send failed while sending packet (len %d) to device %d: %d", total, dev->id, res); + free(buffer); + return res; + } + return total; +} + +static uint16_t find_sport(struct mux_device *dev) +{ + if(collection_count(&dev->connections) >= 65535) + return 0; //insanity + + while(1) { + int ok = 1; + FOREACH(struct mux_connection *conn, &dev->connections) { + if(dev->next_sport == conn->sport) { + dev->next_sport++; + ok = 0; + break; + } + } ENDFOREACH + if(ok) + return dev->next_sport++; + } +} + +static int send_anon_rst(struct mux_device *dev, uint16_t sport, uint16_t dport, uint32_t ack) +{ + struct tcphdr th; + memset(&th, 0, sizeof(th)); + th.th_sport = htons(sport); + th.th_dport = htons(dport); + th.th_ack = htonl(ack); + th.th_flags = TH_RST; + th.th_off = sizeof(th) / 4; + + usbmuxd_log(LL_DEBUG, "[OUT] dev=%d sport=%d dport=%d flags=0x%x", dev->id, sport, dport, th.th_flags); + + int res = send_packet(dev, MUX_PROTO_TCP, &th, NULL, 0); + return res; +} + +static int send_tcp(struct mux_connection *conn, uint8_t flags, const unsigned char *data, int length) +{ + struct tcphdr th; + memset(&th, 0, sizeof(th)); + th.th_sport = htons(conn->sport); + th.th_dport = htons(conn->dport); + th.th_seq = htonl(conn->tx_seq); + th.th_ack = htonl(conn->tx_ack); + th.th_flags = flags; + th.th_off = sizeof(th) / 4; + th.th_win = htons(conn->tx_win >> 8); + + usbmuxd_log(LL_DEBUG, "[OUT] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d", + conn->dev->id, conn->sport, conn->dport, conn->tx_seq, conn->tx_ack, flags, conn->tx_win, conn->tx_win >> 8, length); + + int res = send_packet(conn->dev, MUX_PROTO_TCP, &th, data, length); + if(res >= 0) { + conn->tx_acked = conn->tx_ack; + conn->last_ack_time = mstime64(); + conn->flags &= ~CONN_ACK_PENDING; + } + return res; +} + +static void connection_teardown(struct mux_connection *conn) +{ + int res; + int size; + if(conn->state == CONN_DEAD) + return; + usbmuxd_log(LL_DEBUG, "connection_teardown dev %d sport %d dport %d", conn->dev->id, conn->sport, conn->dport); + if(conn->dev->state != MUXDEV_DEAD && conn->state != CONN_DYING && conn->state != CONN_REFUSED) { + res = send_tcp(conn, TH_RST, NULL, 0); + if(res < 0) + usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", conn->dev->id, conn->sport, conn->dport); + } + if(conn->client) { + if(conn->state == CONN_REFUSED || conn->state == CONN_CONNECTING) { + client_notify_connect(conn->client, RESULT_CONNREFUSED); + } else { + conn->state = CONN_DEAD; + if((conn->events & POLLOUT) && conn->ib_size > 0){ + usbmuxd_log(LL_DEBUG, "%s: flushing buffer to client (%u bytes)", __func__, conn->ib_size); + uint64_t tm_last = mstime64(); + while(1){ + size = client_write(conn->client, conn->ib_buf, conn->ib_size); + if(size < 0) { + usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after error.", __func__); + break; + } else if (size == 0) { + uint64_t tm_now = mstime64(); + if (tm_now - tm_last > 1000) { + usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after unsuccessfully attempting for %dms.", __func__, (int)(tm_now - tm_last)); + break; + } + usleep(10000); + continue; + } + if(size == (int)conn->ib_size) { + conn->ib_size = 0; + break; + } else { + conn->ib_size -= size; + memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size); + } + tm_last = mstime64(); + } + } + client_close(conn->client); + } + } + free(conn->ib_buf); + free(conn->ob_buf); + collection_remove(&conn->dev->connections, conn); + free(conn); +} + +int device_start_connect(int device_id, uint16_t dport, struct mux_client *client) +{ + struct mux_device *dev = get_mux_device_for_id(device_id); + if(!dev) { + usbmuxd_log(LL_WARNING, "Attempted to connect to nonexistent device %d", device_id); + return -RESULT_BADDEV; + } + + uint16_t sport = find_sport(dev); + if(!sport) { + usbmuxd_log(LL_WARNING, "Unable to allocate port for device %d", device_id); + return -RESULT_BADDEV; + } + + struct mux_connection *conn; + conn = malloc(sizeof(struct mux_connection)); + memset(conn, 0, sizeof(struct mux_connection)); + + conn->dev = dev; + conn->client = client; + conn->state = CONN_CONNECTING; + conn->sport = sport; + conn->dport = dport; + conn->tx_seq = 0; + conn->tx_ack = 0; + conn->tx_acked = 0; + conn->tx_win = 131072; + conn->rx_recvd = 0; + conn->flags = 0; + conn->max_payload = USB_MTU - sizeof(struct mux_header) - sizeof(struct tcphdr); + + conn->ob_buf = malloc(CONN_OUTBUF_SIZE); + conn->ob_capacity = CONN_OUTBUF_SIZE; + conn->ib_buf = malloc(CONN_INBUF_SIZE); + conn->ib_capacity = CONN_INBUF_SIZE; + conn->ib_size = 0; + + int res; + + res = send_tcp(conn, TH_SYN, NULL, 0); + if(res < 0) { + usbmuxd_log(LL_ERROR, "Error sending TCP SYN to device %d (%d->%d)", dev->id, sport, dport); + free(conn->ib_buf); + free(conn->ob_buf); + free(conn); + return -RESULT_CONNREFUSED; //bleh + } + collection_add(&dev->connections, conn); + return 0; +} + +/** + * Examine the state of a connection's buffers and + * update all connection flags and masks accordingly. + * Does not do I/O. + * + * @param conn The connection to update. + */ +static void update_connection(struct mux_connection *conn) +{ + uint32_t sent = conn->tx_seq - conn->rx_ack; + + if(conn->rx_win > sent) + conn->sendable = conn->rx_win - sent; + else + conn->sendable = 0; + + if(conn->sendable > conn->ob_capacity) + conn->sendable = conn->ob_capacity; + if(conn->sendable > conn->max_payload) + conn->sendable = conn->max_payload; + + if(conn->sendable > 0) + conn->events |= POLLIN; + else + conn->events &= ~POLLIN; + + if(conn->ib_size) + conn->events |= POLLOUT; + else + conn->events &= ~POLLOUT; + + if(conn->tx_acked != conn->tx_ack) + conn->flags |= CONN_ACK_PENDING; + else + conn->flags &= ~CONN_ACK_PENDING; + + usbmuxd_log(LL_SPEW, "update_connection: sendable %d, events %d, flags %d", conn->sendable, conn->events, conn->flags); + client_set_events(conn->client, conn->events); +} + +static int send_tcp_ack(struct mux_connection *conn) +{ + if(send_tcp(conn, TH_ACK, NULL, 0) < 0) { + usbmuxd_log(LL_ERROR, "Error sending TCP ACK (%d->%d)", conn->sport, conn->dport); + connection_teardown(conn); + return -1; + } + + update_connection(conn); + + return 0; +} + +/** + * Flush input and output buffers for a client connection. + * + * @param device_id Numeric id for the device. + * @param client The client to flush buffers for. + * @param events event mask for the client. POLLOUT means that + * the client is ready to receive data, POLLIN that it has + * data to be read (and send along to the device). + */ +void device_client_process(int device_id, struct mux_client *client, short events) +{ + mutex_lock(&device_list_mutex); + struct mux_connection *conn = get_mux_connection(device_id, client); + mutex_unlock(&device_list_mutex); + if(!conn) { + usbmuxd_log(LL_WARNING, "Could not find connection for device %d client %p", device_id, client); + return; + } + usbmuxd_log(LL_SPEW, "device_client_process (%d)", events); + + int res; + int size; + if((events & POLLOUT) && conn->ib_size > 0) { + // Client is ready to receive data, send what we have + // in the client's connection buffer (if there is any) + size = client_write(conn->client, conn->ib_buf, conn->ib_size); + if(size <= 0) { + usbmuxd_log(LL_DEBUG, "error writing to client (%d)", size); + connection_teardown(conn); + return; + } + conn->tx_ack += size; + if(size == (int)conn->ib_size) { + conn->ib_size = 0; + } else { + conn->ib_size -= size; + memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size); + } + } + if((events & POLLIN) && conn->sendable > 0) { + // There is inbound trafic on the client socket, + // convert it to tcp and send to the device + // (if the device's input buffer is not full) + size = client_read(conn->client, conn->ob_buf, conn->sendable); + if(size <= 0) { + if (size < 0) { + usbmuxd_log(LL_DEBUG, "error reading from client (%d)", size); + } + connection_teardown(conn); + return; + } + res = send_tcp(conn, TH_ACK, conn->ob_buf, size); + if(res < 0) { + connection_teardown(conn); + return; + } + conn->tx_seq += size; + } + + update_connection(conn); +} + +/** + * Copy a payload to a connection's in-buffer and + * set the POLLOUT event mask on the connection so + * the next main_loop iteration will dispatch the + * buffer if the connection socket is writable. + * + * Connection buffers are flushed in the + * device_client_process() function. + * + * @param conn The connection to add incoming data to. + * @param payload Payload to prepare for writing. + * The payload will be copied immediately so you are + * free to alter or free the payload buffer when this + * function returns. + * @param payload_length number of bytes to copy from from + * the payload. + */ +static void connection_device_input(struct mux_connection *conn, unsigned char *payload, uint32_t payload_length) +{ + if((conn->ib_size + payload_length) > conn->ib_capacity) { + usbmuxd_log(LL_ERROR, "Input buffer overflow on device %d connection %d->%d (space=%d, payload=%d)", conn->dev->id, conn->sport, conn->dport, conn->ib_capacity-conn->ib_size, payload_length); + connection_teardown(conn); + return; + } + memcpy(conn->ib_buf + conn->ib_size, payload, payload_length); + conn->ib_size += payload_length; + conn->rx_recvd += payload_length; + update_connection(conn); +} + +void device_abort_connect(int device_id, struct mux_client *client) +{ + struct mux_connection *conn = get_mux_connection(device_id, client); + if (conn) { + conn->client = NULL; + connection_teardown(conn); + } else { + usbmuxd_log(LL_WARNING, "Attempted to abort for nonexistent connection for device %d", device_id); + } +} + +static void device_version_input(struct mux_device *dev, struct version_header *vh) +{ + if(dev->state != MUXDEV_INIT) { + usbmuxd_log(LL_WARNING, "Version packet from already initialized device %d", dev->id); + return; + } + vh->major = ntohl(vh->major); + vh->minor = ntohl(vh->minor); + if(vh->major != 2 && vh->major != 1) { + usbmuxd_log(LL_ERROR, "Device %d has unknown version %d.%d", dev->id, vh->major, vh->minor); + mutex_lock(&device_list_mutex); + collection_remove(&device_list, dev); + mutex_unlock(&device_list_mutex); + free(dev); + return; + } + dev->version = vh->major; + + if (dev->version >= 2) { + send_packet(dev, MUX_PROTO_SETUP, NULL, "\x07", 1); + } + + usbmuxd_log(LL_NOTICE, "Connected to v%d.%d device %d on location 0x%x with serial number %s", dev->version, vh->minor, dev->id, usb_get_location(dev->usbdev), usb_get_serial(dev->usbdev)); + dev->state = MUXDEV_ACTIVE; + collection_init(&dev->connections); + struct device_info info; + info.id = dev->id; + info.location = usb_get_location(dev->usbdev); + info.serial = usb_get_serial(dev->usbdev); + info.pid = usb_get_pid(dev->usbdev); + info.speed = usb_get_speed(dev->usbdev); + preflight_worker_device_add(&info); +} + +static void device_control_input(struct mux_device *dev, unsigned char *payload, uint32_t payload_length) +{ + if (payload_length > 0) { + switch (payload[0]) { + case 3: + if (payload_length > 1) { + usbmuxd_log(LL_ERROR, "Device %d: ERROR: %.*s", dev->id, payload_length-1, payload+1); + } else { + usbmuxd_log(LL_ERROR, "%s: Device %d: Got device error payload with empty message", __func__, dev->id); + } + break; + case 5: + if (payload_length > 1) { + usbmuxd_log(LL_WARNING, "Device %d: WARNING: %.*s", dev->id, payload_length-1, payload+1); + } else { + usbmuxd_log(LL_WARNING, "%s: Device %d: Got payload type %d with empty message", __func__, dev->id, payload[0]); + } + break; + case 7: + if (payload_length > 1) { + usbmuxd_log(LL_INFO, "Device %d: %.*s", dev->id, payload_length-1, payload+1); + } else { + usbmuxd_log(LL_WARNING, "%s: Device %d: Got payload type %d with empty message", __func__, dev->id, payload[0]); + } + break; + default: + usbmuxd_log(LL_WARNING, "%s: Device %d: Got unhandled payload type %d: %.*s", __func__, dev->id, payload[0], payload_length-1, payload+1); + break; + } + } else { + usbmuxd_log(LL_WARNING, "%s: Got a type 1 packet without payload for device %d", __func__, dev->id); + } +} + +/** + * Handle an incoming TCP packet from the device. + * + * @param dev The device handle TCP input on. + * @param th Pointer to the TCP header struct. + * @param payload Payload data. + * @param payload_length Number of bytes in payload. + */ +static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned char *payload, uint32_t payload_length) +{ + uint16_t sport = ntohs(th->th_dport); + uint16_t dport = ntohs(th->th_sport); + struct mux_connection *conn = NULL; + + usbmuxd_log(LL_DEBUG, "[IN] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d", + dev->id, dport, sport, ntohl(th->th_seq), ntohl(th->th_ack), th->th_flags, ntohs(th->th_win) << 8, ntohs(th->th_win), payload_length); + + if(dev->state != MUXDEV_ACTIVE) { + usbmuxd_log(LL_ERROR, "Received TCP packet from device %d but the device isn't active yet, discarding", dev->id); + return; + } + + // Find the connection on this device that has the right sport and dport + FOREACH(struct mux_connection *lconn, &dev->connections) { + if(lconn->sport == sport && lconn->dport == dport) { + conn = lconn; + break; + } + } ENDFOREACH + + if(!conn) { + if(!(th->th_flags & TH_RST)) { + usbmuxd_log(LL_INFO, "No connection for device %d incoming packet %d->%d", dev->id, dport, sport); + if(send_anon_rst(dev, sport, dport, ntohl(th->th_seq)) < 0) + usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", dev->id, sport, dport); + } + return; + } + + conn->rx_seq = ntohl(th->th_seq); + conn->rx_ack = ntohl(th->th_ack); + conn->rx_win = ntohs(th->th_win) << 8; + + if(th->th_flags & TH_RST) { + char *buf = malloc(payload_length+1); + memcpy(buf, payload, payload_length); + if(payload_length && (buf[payload_length-1] == '\n')) + buf[payload_length-1] = 0; + buf[payload_length] = 0; + usbmuxd_log(LL_DEBUG, "RST reason: %s", buf); + free(buf); + } + + if(conn->state == CONN_CONNECTING) { + if(th->th_flags != (TH_SYN|TH_ACK)) { + if(th->th_flags & TH_RST) + conn->state = CONN_REFUSED; + usbmuxd_log(LL_INFO, "Connection refused by device %d (%d->%d)", dev->id, sport, dport); + connection_teardown(conn); //this also sends the notification to the client + } else { + conn->tx_seq++; + conn->tx_ack++; + conn->rx_recvd = conn->rx_seq; + if(send_tcp(conn, TH_ACK, NULL, 0) < 0) { + usbmuxd_log(LL_ERROR, "Error sending TCP ACK to device %d (%d->%d)", dev->id, sport, dport); + connection_teardown(conn); + return; + } + conn->state = CONN_CONNECTED; + usbmuxd_log(LL_INFO, "Client connected to device %d (%d->%d)", dev->id, sport, dport); + if(client_notify_connect(conn->client, RESULT_OK) < 0) { + conn->client = NULL; + connection_teardown(conn); + } + update_connection(conn); + } + } else if(conn->state == CONN_CONNECTED) { + if(th->th_flags != TH_ACK) { + usbmuxd_log(LL_INFO, "Connection reset by device %d (%d->%d)", dev->id, sport, dport); + if(th->th_flags & TH_RST) + conn->state = CONN_DYING; + connection_teardown(conn); + } else { + connection_device_input(conn, payload, payload_length); + + // Device likes it best when we are prompty ACKing data + send_tcp_ack(conn); + } + } +} + +/** + * Take input data from the device that has been read into a buffer + * and dispatch it to the right protocol backend (eg. TCP). + * + * @param usbdev + * @param buffer + * @param length + */ +void device_data_input(struct usb_device *usbdev, unsigned char *buffer, uint32_t length) +{ + struct mux_device *dev = NULL; + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *tdev, &device_list) { + if(tdev->usbdev == usbdev) { + dev = tdev; + break; + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); + if(!dev) { + usbmuxd_log(LL_WARNING, "Cannot find device entry for RX input from USB device %p on location 0x%x", usbdev, usb_get_location(usbdev)); + return; + } + + if(!length) + return; + + // sanity check (should never happen with current USB implementation) + if((length > USB_MRU) || (length > DEV_MRU)) { + usbmuxd_log(LL_ERROR, "Too much data received from USB (%d), file a bug", length); + return; + } + + usbmuxd_log(LL_SPEW, "Mux data input for device %p: %p len %d", dev, buffer, length); + + // handle broken up transfers + if(dev->pktlen) { + if((length + dev->pktlen) > DEV_MRU) { + usbmuxd_log(LL_ERROR, "Incoming split packet is too large (%d so far), dropping!", length + dev->pktlen); + dev->pktlen = 0; + return; + } + memcpy(dev->pktbuf + dev->pktlen, buffer, length); + struct mux_header *mhdr = (struct mux_header *)dev->pktbuf; + if((length < USB_MRU) || (ntohl(mhdr->length) == (length + dev->pktlen))) { + buffer = dev->pktbuf; + length += dev->pktlen; + dev->pktlen = 0; + usbmuxd_log(LL_SPEW, "Gathered mux data from buffer (total size: %d)", length); + } else { + dev->pktlen += length; + usbmuxd_log(LL_SPEW, "Appended mux data to buffer (total size: %d)", dev->pktlen); + return; + } + } else { + struct mux_header *mhdr = (struct mux_header *)buffer; + if((length == USB_MRU) && (length < ntohl(mhdr->length))) { + memcpy(dev->pktbuf, buffer, length); + dev->pktlen = length; + usbmuxd_log(LL_SPEW, "Copied mux data to buffer (size: %d)", dev->pktlen); + return; + } + } + + struct mux_header *mhdr = (struct mux_header *)buffer; + int mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header)); + if(ntohl(mhdr->length) != length) { + usbmuxd_log(LL_ERROR, "Incoming packet size mismatch (dev %d, expected %d, got %d)", dev->id, ntohl(mhdr->length), length); + return; + } + + struct tcphdr *th; + unsigned char *payload; + uint32_t payload_length; + + if (dev->version >= 2) { + dev->rx_seq = ntohs(mhdr->rx_seq); + } + + switch(ntohl(mhdr->protocol)) { + case MUX_PROTO_VERSION: + if(length < (mux_header_size + sizeof(struct version_header))) { + usbmuxd_log(LL_ERROR, "Incoming version packet is too small (%d)", length); + return; + } + device_version_input(dev, (struct version_header *)((char*)mhdr+mux_header_size)); + break; + case MUX_PROTO_CONTROL: + payload = (unsigned char *)(mhdr+1); + payload_length = length - mux_header_size; + device_control_input(dev, payload, payload_length); + break; + case MUX_PROTO_TCP: + if(length < (mux_header_size + sizeof(struct tcphdr))) { + usbmuxd_log(LL_ERROR, "Incoming TCP packet is too small (%d)", length); + return; + } + th = (struct tcphdr *)((char*)mhdr+mux_header_size); + payload = (unsigned char *)(th+1); + payload_length = length - sizeof(struct tcphdr) - mux_header_size; + device_tcp_input(dev, th, payload, payload_length); + break; + default: + usbmuxd_log(LL_ERROR, "Incoming packet for device %d has unknown protocol 0x%x)", dev->id, ntohl(mhdr->protocol)); + break; + } + +} + +int device_add(struct usb_device *usbdev) +{ + int res; + int id = get_next_device_id(); + struct mux_device *dev; + usbmuxd_log(LL_NOTICE, "Connecting to new device on location 0x%x as ID %d", usb_get_location(usbdev), id); + dev = malloc(sizeof(struct mux_device)); + dev->id = id; + dev->usbdev = usbdev; + dev->state = MUXDEV_INIT; + dev->visible = 0; + dev->next_sport = 1; + dev->pktbuf = malloc(DEV_MRU); + dev->pktlen = 0; + dev->preflight_cb_data = NULL; + dev->version = 0; + struct version_header vh; + vh.major = htonl(2); + vh.minor = htonl(0); + vh.padding = 0; + if((res = send_packet(dev, MUX_PROTO_VERSION, &vh, NULL, 0)) < 0) { + usbmuxd_log(LL_ERROR, "Error sending version request packet to device %d", id); + free(dev->pktbuf); + free(dev); + return res; + } + mutex_lock(&device_list_mutex); + collection_add(&device_list, dev); + mutex_unlock(&device_list_mutex); + return 0; +} + +void device_remove(struct usb_device *usbdev) +{ + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->usbdev == usbdev) { + usbmuxd_log(LL_NOTICE, "Removed device %d on location 0x%x", dev->id, usb_get_location(usbdev)); + if(dev->state == MUXDEV_ACTIVE) { + dev->state = MUXDEV_DEAD; + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + client_device_remove(dev->id); + collection_free(&dev->connections); + } + if (dev->preflight_cb_data) { + preflight_device_remove_cb(dev->preflight_cb_data); + } + collection_remove(&device_list, dev); + mutex_unlock(&device_list_mutex); + free(dev->pktbuf); + free(dev); + return; + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); + + usbmuxd_log(LL_WARNING, "Cannot find device entry while removing USB device %p on location 0x%x", usbdev, usb_get_location(usbdev)); +} + +void device_set_visible(int device_id) +{ + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == device_id) { + dev->visible = 1; + break; + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); +} + +void device_set_preflight_cb_data(int device_id, void* data) +{ + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == device_id) { + dev->preflight_cb_data = data; + break; + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); +} + +int device_get_count(int include_hidden) +{ + int count = 0; + struct collection dev_list = {NULL, 0}; + mutex_lock(&device_list_mutex); + collection_copy(&dev_list, &device_list); + mutex_unlock(&device_list_mutex); + + FOREACH(struct mux_device *dev, &dev_list) { + if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible)) + count++; + } ENDFOREACH + + collection_free(&dev_list); + return count; +} + +int device_get_list(int include_hidden, struct device_info **devices) +{ + int count = 0; + struct collection dev_list = {NULL, 0}; + mutex_lock(&device_list_mutex); + collection_copy(&dev_list, &device_list); + mutex_unlock(&device_list_mutex); + + *devices = malloc(sizeof(struct device_info) * dev_list.capacity); + struct device_info *p = *devices; + + FOREACH(struct mux_device *dev, &dev_list) { + if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible)) { + p->id = dev->id; + p->serial = usb_get_serial(dev->usbdev); + p->location = usb_get_location(dev->usbdev); + p->pid = usb_get_pid(dev->usbdev); + p->speed = usb_get_speed(dev->usbdev); + count++; + p++; + } + } ENDFOREACH + + collection_free(&dev_list); + + return count; +} + +int device_get_timeout(void) +{ + uint64_t oldest = (uint64_t)-1LL; + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) { + FOREACH(struct mux_connection *conn, &dev->connections) { + if((conn->state == CONN_CONNECTED) && (conn->flags & CONN_ACK_PENDING) && conn->last_ack_time < oldest) + oldest = conn->last_ack_time; + } ENDFOREACH + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); + uint64_t ct = mstime64(); + if((int64_t)oldest == -1LL) + return 100000; //meh + if((ct - oldest) > ACK_TIMEOUT) + return 0; + return ACK_TIMEOUT - (ct - oldest); +} + +void device_check_timeouts(void) +{ + uint64_t ct = mstime64(); + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) { + FOREACH(struct mux_connection *conn, &dev->connections) { + if((conn->state == CONN_CONNECTED) && + (conn->flags & CONN_ACK_PENDING) && + (ct - conn->last_ack_time) > ACK_TIMEOUT) { + usbmuxd_log(LL_DEBUG, "Sending ACK due to expired timeout (%" PRIu64 " -> %" PRIu64 ")", conn->last_ack_time, ct); + send_tcp_ack(conn); + } + } ENDFOREACH + } + } ENDFOREACH + mutex_unlock(&device_list_mutex); +} + +void device_init(void) +{ + usbmuxd_log(LL_DEBUG, "device_init"); + collection_init(&device_list); + mutex_init(&device_list_mutex); + next_device_id = 1; +} + +void device_kill_connections(void) +{ + usbmuxd_log(LL_DEBUG, "device_kill_connections"); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state != MUXDEV_INIT) { + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + } + } ENDFOREACH + // give USB a while to send the final connection RSTs and the like + usb_process_timeout(100); +} + +void device_shutdown(void) +{ + usbmuxd_log(LL_DEBUG, "device_shutdown"); + mutex_lock(&device_list_mutex); + FOREACH(struct mux_device *dev, &device_list) { + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + collection_free(&dev->connections); + collection_remove(&device_list, dev); + free(dev); + } ENDFOREACH + mutex_unlock(&device_list_mutex); + mutex_destroy(&device_list_mutex); + collection_free(&device_list); +} diff --git a/src/device.h b/src/device.h new file mode 100644 index 0000000..85703e4 --- /dev/null +++ b/src/device.h @@ -0,0 +1,56 @@ +/* + * device.h + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef DEVICE_H +#define DEVICE_H + +#include "usb.h" +#include "client.h" + +struct device_info { + int id; + const char *serial; + uint32_t location; + uint16_t pid; + uint64_t speed; +}; + +void device_data_input(struct usb_device *dev, unsigned char *buf, uint32_t length); + +int device_add(struct usb_device *dev); +void device_remove(struct usb_device *dev); + +int device_start_connect(int device_id, uint16_t port, struct mux_client *client); +void device_client_process(int device_id, struct mux_client *client, short events); +void device_abort_connect(int device_id, struct mux_client *client); + +void device_set_visible(int device_id); +void device_set_preflight_cb_data(int device_id, void* data); + +int device_get_count(int include_hidden); +int device_get_list(int include_hidden, struct device_info **devices); + +int device_get_timeout(void); +void device_check_timeouts(void); + +void device_init(void); +void device_kill_connections(void); +void device_shutdown(void); + +#endif diff --git a/src/log.c b/src/log.c new file mode 100644 index 0000000..cd7c2d5 --- /dev/null +++ b/src/log.c @@ -0,0 +1,101 @@ +/* + * log.c + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <stdarg.h> +#include <time.h> +#include <sys/time.h> +#include <syslog.h> + +#include "log.h" +#include "utils.h" + +unsigned int log_level = LL_WARNING; + +int log_syslog = 0; + +void log_enable_syslog() +{ + if (!log_syslog) { + openlog("usbmuxd", LOG_PID, 0); + log_syslog = 1; + } +} + +void log_disable_syslog() +{ + if (log_syslog) { + closelog(); + } +} + +static int level_to_syslog_level(int level) +{ + int result = level + LOG_CRIT; + if (result > LOG_DEBUG) { + result = LOG_DEBUG; + } + return result; +} + +void usbmuxd_log(enum loglevel level, const char *fmt, ...) +{ + va_list ap; + char *fs; + + if(level > log_level) + return; + + fs = malloc(20 + strlen(fmt)); + + if(log_syslog) { + sprintf(fs, "[%d] %s\n", level, fmt); + } else { + struct timeval ts; + struct tm tp_; + struct tm *tp; + + gettimeofday(&ts, NULL); +#ifdef HAVE_LOCALTIME_R + tp = localtime_r(&ts.tv_sec, &tp_); +#else + tp = localtime(&ts.tv_sec); +#endif + + strftime(fs, 10, "[%H:%M:%S", tp); + sprintf(fs+9, ".%03d][%d] %s\n", (int)(ts.tv_usec / 1000), level, fmt); + } + + va_start(ap, fmt); + if (log_syslog) { + vsyslog(level_to_syslog_level(level), fs, ap); + } else { + vfprintf(stderr, fs, ap); + } + va_end(ap); + + free(fs); +} diff --git a/src/log.h b/src/log.h new file mode 100644 index 0000000..858e7d0 --- /dev/null +++ b/src/log.h @@ -0,0 +1,42 @@ +/* + * log.h + * + * Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef LOG_H +#define LOG_H + +enum loglevel { + LL_FATAL = 0, + LL_ERROR, + LL_WARNING, + LL_NOTICE, + LL_INFO, + LL_DEBUG, + LL_SPEW, + LL_FLOOD, +}; + +extern unsigned int log_level; + +void log_enable_syslog(); +void log_disable_syslog(); + +void usbmuxd_log(enum loglevel level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..8702a4b --- /dev/null +++ b/src/main.c @@ -0,0 +1,920 @@ +/* + * main.c + * + * Copyright (C) 2009-2021 Nikias Bassen <nikias@gmx.li> + * Copyright (C) 2013-2014 Martin Szulecki <m.szulecki@libimobiledevice.org> + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define _DEFAULT_SOURCE +#define _BSD_SOURCE +#define _GNU_SOURCE + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <errno.h> +#include <string.h> +#include <stdlib.h> +#include <signal.h> +#include <unistd.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <netinet/in.h> +#include <netdb.h> +#include <arpa/inet.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <sys/resource.h> +#include <fcntl.h> +#include <getopt.h> +#include <pwd.h> +#include <grp.h> + +#include "log.h" +#include "usb.h" +#include "device.h" +#include "client.h" +#include "conf.h" + +static const char *socket_path = "/var/run/usbmuxd"; +#define DEFAULT_LOCKFILE "/var/run/usbmuxd.pid" +static const char *lockfile = DEFAULT_LOCKFILE; + +// Global state used in other files +int should_exit; +int should_discover; +int use_logfile = 0; +int no_preflight = 0; + +// Global state for main.c +static int verbose = 0; +static int foreground = 0; +static int drop_privileges = 0; +static const char *drop_user = NULL; +static int opt_disable_hotplug = 0; +static int opt_enable_exit = 0; +static int opt_exit = 0; +static int exit_signal = 0; +static int daemon_pipe; +static const char *listen_addr = NULL; + +static int report_to_parent = 0; + +static int create_socket(void) +{ + int listenfd; + const char* socket_addr = socket_path; + const char* tcp_port; + char listen_addr_str[256]; + + if (listen_addr) { + socket_addr = listen_addr; + } + tcp_port = strrchr(socket_addr, ':'); + if (tcp_port) { + tcp_port++; + size_t nlen = tcp_port - socket_addr; + char* hostname = malloc(nlen); + struct addrinfo hints; + struct addrinfo *result, *rp; + int yes = 1; + int res; + + strncpy(hostname, socket_addr, nlen-1); + hostname[nlen-1] = '\0'; + + memset(&hints, '\0', sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV; + hints.ai_protocol = IPPROTO_TCP; + + res = getaddrinfo(hostname, tcp_port, &hints, &result); + free(hostname); + if (res != 0) { + usbmuxd_log(LL_FATAL, "%s: getaddrinfo() failed: %s\n", __func__, gai_strerror(res)); + return -1; + } + + for (rp = result; rp != NULL; rp = rp->ai_next) { + listenfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if (listenfd == -1) { + listenfd = -1; + continue; + } + + if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { + usbmuxd_log(LL_ERROR, "%s: setsockopt(): %s", __func__, strerror(errno)); + close(listenfd); + listenfd = -1; + continue; + } + +#ifdef SO_NOSIGPIPE + if (setsockopt(listenfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) { + usbmuxd_log(LL_ERROR, "%s: setsockopt(): %s", __func__, strerror(errno)); + close(listenfd); + listenfd = -1; + continue; + } +#endif + +#if defined(AF_INET6) && defined(IPV6_V6ONLY) + if (rp->ai_family == AF_INET6) { + if (setsockopt(listenfd, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&yes, sizeof(int)) == -1) { + usbmuxd_log(LL_ERROR, "%s: setsockopt() IPV6_V6ONLY: %s", __func__, strerror(errno)); + } + } +#endif + + if (bind(listenfd, rp->ai_addr, rp->ai_addrlen) < 0) { + usbmuxd_log(LL_FATAL, "%s: bind() failed: %s", __func__, strerror(errno)); + close(listenfd); + listenfd = -1; + continue; + } + + const void *addrdata = NULL; + if (rp->ai_family == AF_INET) { + addrdata = &((struct sockaddr_in*)rp->ai_addr)->sin_addr; + } +#ifdef AF_INET6 + else if (rp->ai_family == AF_INET6) { + addrdata = &((struct sockaddr_in6*)rp->ai_addr)->sin6_addr; + } +#endif + if (addrdata) { + char* endp = NULL; + uint16_t listen_port = 0; + if (rp->ai_family == AF_INET) { + listen_port = ntohs(((struct sockaddr_in*)rp->ai_addr)->sin_port); + if (inet_ntop(AF_INET, addrdata, listen_addr_str, sizeof(listen_addr_str)-6)) { + endp = &listen_addr_str[0] + strlen(listen_addr_str); + } + } +#ifdef AF_INET6 + else if (rp->ai_family == AF_INET6) { + listen_port = ntohs(((struct sockaddr_in6*)rp->ai_addr)->sin6_port); + listen_addr_str[0] = '['; + if (inet_ntop(AF_INET6, addrdata, listen_addr_str+1, sizeof(listen_addr_str)-8)) { + endp = &listen_addr_str[0] + strlen(listen_addr_str); + } + if (endp) { + *endp = ']'; + endp++; + } + } +#endif + if (endp) { + sprintf(endp, ":%u", listen_port); + } + } + break; + } + freeaddrinfo(result); + if (listenfd == -1) { + usbmuxd_log(LL_FATAL, "%s: Failed to create listening socket", __func__); + return -1; + } + } else { + struct sockaddr_un bind_addr; + + if (strcmp(socket_addr, socket_path) != 0) { + struct stat fst; + if (stat(socket_addr, &fst) == 0) { + if (!S_ISSOCK(fst.st_mode)) { + usbmuxd_log(LL_FATAL, "FATAL: File '%s' already exists and is not a socket file. Refusing to continue.", socket_addr); + return -1; + } + } + } + + if (unlink(socket_addr) == -1 && errno != ENOENT) { + usbmuxd_log(LL_FATAL, "%s: unlink(%s) failed: %s", __func__, socket_addr, strerror(errno)); + return -1; + } + + listenfd = socket(AF_UNIX, SOCK_STREAM, 0); + if (listenfd == -1) { + usbmuxd_log(LL_FATAL, "socket() failed: %s", strerror(errno)); + return -1; + } + + bzero(&bind_addr, sizeof(bind_addr)); + bind_addr.sun_family = AF_UNIX; + strncpy(bind_addr.sun_path, socket_addr, sizeof(bind_addr.sun_path)); + bind_addr.sun_path[sizeof(bind_addr.sun_path) - 1] = '\0'; + + if (bind(listenfd, (struct sockaddr*)&bind_addr, sizeof(bind_addr)) != 0) { + usbmuxd_log(LL_FATAL, "bind() failed: %s", strerror(errno)); + return -1; + } + chmod(socket_addr, 0666); + + snprintf(listen_addr_str, sizeof(listen_addr_str), "%s", socket_addr); + } + + int flags = fcntl(listenfd, F_GETFL, 0); + if (flags < 0) { + usbmuxd_log(LL_FATAL, "ERROR: Could not get flags for socket"); + } else { + if (fcntl(listenfd, F_SETFL, flags | O_NONBLOCK) < 0) { + usbmuxd_log(LL_FATAL, "ERROR: Could not set socket to non-blocking"); + } + } + + // Start listening + if (listen(listenfd, 256) != 0) { + usbmuxd_log(LL_FATAL, "listen() failed: %s", strerror(errno)); + return -1; + } + + usbmuxd_log(LL_INFO, "Listening on %s", listen_addr_str); + + return listenfd; +} + +static void handle_signal(int sig) +{ + if (sig != SIGUSR1 && sig != SIGUSR2) { + usbmuxd_log(LL_NOTICE,"Caught signal %d, exiting", sig); + should_exit = 1; + } else { + if(opt_enable_exit) { + if (sig == SIGUSR1) { + usbmuxd_log(LL_INFO, "Caught SIGUSR1, checking if we can terminate (no more devices attached)..."); + if (device_get_count(1) > 0) { + // we can't quit, there are still devices attached. + usbmuxd_log(LL_NOTICE, "Refusing to terminate, there are still devices attached. Kill me with signal 15 (TERM) to force quit."); + } else { + // it's safe to quit + should_exit = 1; + } + } else if (sig == SIGUSR2) { + usbmuxd_log(LL_INFO, "Caught SIGUSR2, scheduling device discovery"); + should_discover = 1; + } + } else { + usbmuxd_log(LL_INFO, "Caught SIGUSR1/2 but this instance was not started with \"--enable-exit\", ignoring."); + } + } +} + +static void set_signal_handlers(void) +{ + struct sigaction sa; + sigset_t set; + + // Mask all signals we handle. They will be unmasked by ppoll(). + sigemptyset(&set); + sigaddset(&set, SIGINT); + sigaddset(&set, SIGQUIT); + sigaddset(&set, SIGTERM); + sigaddset(&set, SIGUSR1); + sigaddset(&set, SIGUSR2); + sigprocmask(SIG_SETMASK, &set, NULL); + + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_handler = handle_signal; + sigaction(SIGINT, &sa, NULL); + sigaction(SIGQUIT, &sa, NULL); + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGUSR1, &sa, NULL); + sigaction(SIGUSR2, &sa, NULL); +} + +#ifndef HAVE_PPOLL +static int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask) +{ + int ready; + sigset_t origmask; + int to = timeout->tv_sec*1000 + timeout->tv_nsec/1000000; + + sigprocmask(SIG_SETMASK, sigmask, &origmask); + ready = poll(fds, nfds, to); + sigprocmask(SIG_SETMASK, &origmask, NULL); + + return ready; +} +#endif + +static int main_loop(int listenfd) +{ + int to, cnt, i, dto; + struct fdlist pollfds; + struct timespec tspec; + + sigset_t empty_sigset; + sigemptyset(&empty_sigset); // unmask all signals + + fdlist_create(&pollfds); + while(!should_exit) { + usbmuxd_log(LL_FLOOD, "main_loop iteration"); + to = usb_get_timeout(); + usbmuxd_log(LL_FLOOD, "USB timeout is %d ms", to); + dto = device_get_timeout(); + usbmuxd_log(LL_FLOOD, "Device timeout is %d ms", dto); + if(dto < to) + to = dto; + + fdlist_reset(&pollfds); + fdlist_add(&pollfds, FD_LISTEN, listenfd, POLLIN); + usb_get_fds(&pollfds); + client_get_fds(&pollfds); + usbmuxd_log(LL_FLOOD, "fd count is %d", pollfds.count); + + tspec.tv_sec = to / 1000; + tspec.tv_nsec = (to % 1000) * 1000000; + cnt = ppoll(pollfds.fds, pollfds.count, &tspec, &empty_sigset); + usbmuxd_log(LL_FLOOD, "poll() returned %d", cnt); + if(cnt == -1) { + if(errno == EINTR) { + if(should_exit) { + usbmuxd_log(LL_INFO, "Event processing interrupted"); + break; + } + if(should_discover) { + should_discover = 0; + usbmuxd_log(LL_INFO, "Device discovery triggered"); + usb_discover(); + } + } + } else if(cnt == 0) { + if(usb_process() < 0) { + usbmuxd_log(LL_FATAL, "usb_process() failed"); + fdlist_free(&pollfds); + return -1; + } + device_check_timeouts(); + } else { + int done_usb = 0; + for(i=0; i<pollfds.count; i++) { + if(pollfds.fds[i].revents) { + if(!done_usb && pollfds.owners[i] == FD_USB) { + if(usb_process() < 0) { + usbmuxd_log(LL_FATAL, "usb_process() failed"); + fdlist_free(&pollfds); + return -1; + } + done_usb = 1; + } + if(pollfds.owners[i] == FD_LISTEN) { + if(client_accept(listenfd) < 0) { + usbmuxd_log(LL_FATAL, "client_accept() failed"); + fdlist_free(&pollfds); + return -1; + } + } + if(pollfds.owners[i] == FD_CLIENT) { + client_process(pollfds.fds[i].fd, pollfds.fds[i].revents); + } + } + } + } + } + fdlist_free(&pollfds); + return 0; +} + +/** + * make this program run detached from the current console + */ +static int daemonize(void) +{ + pid_t pid; + pid_t sid; + int pfd[2]; + int res; + + // already a daemon + if (getppid() == 1) + return 0; + + if((res = pipe(pfd)) < 0) { + usbmuxd_log(LL_FATAL, "pipe() failed."); + return res; + } + + pid = fork(); + if (pid < 0) { + usbmuxd_log(LL_FATAL, "fork() failed."); + return pid; + } + + if (pid > 0) { + // exit parent process + int status; + close(pfd[1]); + + if((res = read(pfd[0],&status,sizeof(int))) != sizeof(int)) { + fprintf(stderr, "usbmuxd: ERROR: Failed to get init status from child, check syslog for messages.\n"); + exit(1); + } + if(status != 0) + fprintf(stderr, "usbmuxd: ERROR: Child process exited with error %d, check syslog for messages.\n", status); + exit(status); + } + // At this point we are executing as the child process + // but we need to do one more fork + + daemon_pipe = pfd[1]; + close(pfd[0]); + report_to_parent = 1; + + // Create a new SID for the child process + sid = setsid(); + if (sid < 0) { + usbmuxd_log(LL_FATAL, "setsid() failed."); + return -1; + } + + pid = fork(); + if (pid < 0) { + usbmuxd_log(LL_FATAL, "fork() failed (second)."); + return pid; + } + + if (pid > 0) { + // exit parent process + close(daemon_pipe); + exit(0); + } + + // Change the current working directory. + if ((chdir("/")) < 0) { + usbmuxd_log(LL_FATAL, "chdir() failed"); + return -2; + } + // Redirect standard files to /dev/null + if (!freopen("/dev/null", "r", stdin)) { + usbmuxd_log(LL_FATAL, "Redirection of stdin failed."); + return -3; + } + if (!freopen("/dev/null", "w", stdout)) { + usbmuxd_log(LL_FATAL, "Redirection of stdout failed."); + return -3; + } + + return 0; +} + +static int notify_parent(int status) +{ + int res; + + report_to_parent = 0; + if ((res = write(daemon_pipe, &status, sizeof(int))) != sizeof(int)) { + usbmuxd_log(LL_FATAL, "Could not notify parent!"); + if(res >= 0) + return -2; + else + return res; + } + close(daemon_pipe); + if (!freopen("/dev/null", "w", stderr)) { + usbmuxd_log(LL_FATAL, "Redirection of stderr failed."); + return -1; + } + return 0; +} + +static void usage() +{ + printf("Usage: %s [OPTIONS]\n", PACKAGE_NAME); + printf("\n"); + printf("Expose a socket to multiplex connections from and to iOS devices.\n"); + printf("\n"); + printf("OPTIONS:\n"); + printf(" -h, --help\t\tPrint this message.\n"); + printf(" -v, --verbose\t\tBe verbose (use twice or more to increase).\n"); + printf(" -f, --foreground\tDo not daemonize (implies one -v).\n"); + printf(" -U, --user USER\tChange to this user after startup (needs USB privileges).\n"); + printf(" -n, --disable-hotplug\tDisables automatic discovery of devices on hotplug.\n"); + printf(" \tStarting another instance will trigger discovery instead.\n"); + printf(" -z, --enable-exit\tEnable \"--exit\" request from other instances and exit\n"); + printf(" \tautomatically if no device is attached.\n"); + printf(" -p, --no-preflight\tDisable lockdownd preflight on new device.\n"); +#ifdef HAVE_UDEV + printf(" -u, --udev\t\tRun in udev operation mode (implies -n and -z).\n"); +#endif +#ifdef HAVE_SYSTEMD + printf(" -s, --systemd\t\tRun in systemd operation mode (implies -z and -f).\n"); +#endif + printf(" -S, --socket ADDR:PORT | PATH Specify source ADDR and PORT or a UNIX\n"); + printf(" \t\tsocket PATH to use for the listening socket.\n"); + printf(" \t\tDefault: %s\n", socket_path); + printf(" -P, --pidfile PATH\tSpecify a different location for the pid file, or pass\n"); + printf(" \t\tNONE to disable. Default: %s\n", DEFAULT_LOCKFILE); + printf(" -x, --exit\t\tNotify a running instance to exit if there are no devices\n"); + printf(" \t\tconnected (sends SIGUSR1 to running instance) and exit.\n"); + printf(" -X, --force-exit\tNotify a running instance to exit even if there are still\n"); + printf(" \tdevices connected (always works) and exit.\n"); + printf(" -l, --logfile=LOGFILE\tLog (append) to LOGFILE instead of stderr or syslog.\n"); + printf(" -V, --version\t\tPrint version information and exit.\n"); + printf("\n"); + printf("Homepage: <" PACKAGE_URL ">\n"); + printf("Bug Reports: <" PACKAGE_BUGREPORT ">\n"); +} + +static void parse_opts(int argc, char **argv) +{ + static struct option longopts[] = { + {"help", no_argument, NULL, 'h'}, + {"foreground", no_argument, NULL, 'f'}, + {"verbose", no_argument, NULL, 'v'}, + {"user", required_argument, NULL, 'U'}, + {"disable-hotplug", no_argument, NULL, 'n'}, + {"enable-exit", no_argument, NULL, 'z'}, + {"no-preflight", no_argument, NULL, 'p'}, +#ifdef HAVE_UDEV + {"udev", no_argument, NULL, 'u'}, +#endif +#ifdef HAVE_SYSTEMD + {"systemd", no_argument, NULL, 's'}, +#endif + {"socket", required_argument, NULL, 'S'}, + {"pidfile", required_argument, NULL, 'P'}, + {"exit", no_argument, NULL, 'x'}, + {"force-exit", no_argument, NULL, 'X'}, + {"logfile", required_argument, NULL, 'l'}, + {"version", no_argument, NULL, 'V'}, + {NULL, 0, NULL, 0} + }; + int c; + +#ifdef HAVE_SYSTEMD + const char* opts_spec = "hfvVuU:xXsnzl:pS:P:"; +#elif HAVE_UDEV + const char* opts_spec = "hfvVuU:xXnzl:pS:P:"; +#else + const char* opts_spec = "hfvVU:xXnzl:pS:P:"; +#endif + + while (1) { + c = getopt_long(argc, argv, opts_spec, longopts, (int *) 0); + if (c == -1) { + break; + } + + switch (c) { + case 'h': + usage(); + exit(0); + case 'f': + foreground = 1; + break; + case 'v': + ++verbose; + break; + case 'V': + printf("%s\n", PACKAGE_STRING); + exit(0); + case 'U': + drop_privileges = 1; + drop_user = optarg; + break; + case 'p': + no_preflight = 1; + break; +#ifdef HAVE_UDEV + case 'u': + opt_disable_hotplug = 1; + opt_enable_exit = 1; + break; +#endif +#ifdef HAVE_SYSTEMD + case 's': + opt_enable_exit = 1; + foreground = 1; + break; +#endif + case 'n': + opt_disable_hotplug = 1; + break; + case 'z': + opt_enable_exit = 1; + break; + case 'S': + if (!*optarg || *optarg == '-') { + usbmuxd_log(LL_FATAL, "ERROR: --socket requires an argument"); + usage(); + exit(2); + } + listen_addr = optarg; + break; + case 'P': + if (!*optarg || *optarg == '-') { + usbmuxd_log(LL_FATAL, "ERROR: --pidfile requires an argument"); + usage(); + exit(2); + } + if (!strcmp(optarg, "NONE")) { + lockfile = NULL; + } else { + lockfile = optarg; + } + break; + case 'x': + opt_exit = 1; + exit_signal = SIGUSR1; + break; + case 'X': + opt_exit = 1; + exit_signal = SIGTERM; + break; + case 'l': + if (!*optarg) { + usbmuxd_log(LL_FATAL, "ERROR: --logfile requires a non-empty filename"); + usage(); + exit(2); + } + if (use_logfile) { + usbmuxd_log(LL_FATAL, "ERROR: --logfile cannot be used multiple times"); + exit(2); + } + if (!freopen(optarg, "a", stderr)) { + usbmuxd_log(LL_FATAL, "ERROR: fdreopen: %s", strerror(errno)); + } else { + use_logfile = 1; + } + break; + default: + usage(); + exit(2); + } + } +} + +int main(int argc, char *argv[]) +{ + int listenfd; + int res = 0; + int lfd; + struct flock lock; + char pids[10]; + + parse_opts(argc, argv); + + argc -= optind; + argv += optind; + + if (!foreground && !use_logfile) { + verbose += LL_WARNING; + log_enable_syslog(); + } else { + verbose += LL_NOTICE; + } + + /* set log level to specified verbosity */ + log_level = verbose; + + usbmuxd_log(LL_NOTICE, "usbmuxd v%s starting up", PACKAGE_VERSION); + should_exit = 0; + should_discover = 0; + + set_signal_handlers(); + signal(SIGPIPE, SIG_IGN); + + if (lockfile) { + res = lfd = open(lockfile, O_WRONLY|O_CREAT, 0644); + if(res == -1) { + usbmuxd_log(LL_FATAL, "Could not open lockfile"); + goto terminate; + } + lock.l_type = F_WRLCK; + lock.l_whence = SEEK_SET; + lock.l_start = 0; + lock.l_len = 0; + lock.l_pid = 0; + fcntl(lfd, F_GETLK, &lock); + close(lfd); + } + if (lockfile && lock.l_type != F_UNLCK) { + if (opt_exit) { + if (lock.l_pid && !kill(lock.l_pid, 0)) { + usbmuxd_log(LL_NOTICE, "Sending signal %d to instance with pid %d", exit_signal, lock.l_pid); + res = 0; + if (kill(lock.l_pid, exit_signal) < 0) { + usbmuxd_log(LL_FATAL, "Could not deliver signal %d to pid %d", exit_signal, lock.l_pid); + res = -1; + } + goto terminate; + } else { + usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!"); + res = -1; + goto terminate; + } + } else { + if (!opt_disable_hotplug) { + usbmuxd_log(LL_ERROR, "Another instance is already running (pid %d). exiting.", lock.l_pid); + res = -1; + } else { + usbmuxd_log(LL_NOTICE, "Another instance is already running (pid %d). Telling it to check for devices.", lock.l_pid); + if (lock.l_pid && !kill(lock.l_pid, 0)) { + usbmuxd_log(LL_NOTICE, "Sending signal SIGUSR2 to instance with pid %d", lock.l_pid); + res = 0; + if (kill(lock.l_pid, SIGUSR2) < 0) { + usbmuxd_log(LL_FATAL, "Could not deliver SIGUSR2 to pid %d", lock.l_pid); + res = -1; + } + } else { + usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!"); + res = -1; + } + } + goto terminate; + } + } + if (lockfile) { + unlink(lockfile); + } + + if (opt_exit) { + usbmuxd_log(LL_NOTICE, "No running instance found, none killed. Exiting."); + goto terminate; + } + + if (!foreground) { + if ((res = daemonize()) < 0) { + fprintf(stderr, "usbmuxd: FATAL: Could not daemonize!\n"); + usbmuxd_log(LL_FATAL, "Could not daemonize!"); + goto terminate; + } + } + + if (lockfile) { + // now open the lockfile and place the lock + res = lfd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644); + if(res < 0) { + usbmuxd_log(LL_FATAL, "Could not open pidfile '%s'", lockfile); + goto terminate; + } + lock.l_type = F_WRLCK; + lock.l_whence = SEEK_SET; + lock.l_start = 0; + lock.l_len = 0; + if ((res = fcntl(lfd, F_SETLK, &lock)) < 0) { + usbmuxd_log(LL_FATAL, "Locking pidfile '%s' failed!", lockfile); + goto terminate; + } + sprintf(pids, "%d", getpid()); + if ((size_t)(res = write(lfd, pids, strlen(pids))) != strlen(pids)) { + usbmuxd_log(LL_FATAL, "Could not write pidfile!"); + if(res >= 0) + res = -2; + goto terminate; + } + } + + // set number of file descriptors to higher value + struct rlimit rlim; + getrlimit(RLIMIT_NOFILE, &rlim); + rlim.rlim_max = 65536; + setrlimit(RLIMIT_NOFILE, (const struct rlimit*)&rlim); + + usbmuxd_log(LL_INFO, "Creating socket"); + res = listenfd = create_socket(); + if(listenfd < 0) + goto terminate; + +#ifdef HAVE_LIBIMOBILEDEVICE + const char* userprefdir = config_get_config_dir(); + struct stat fst; + memset(&fst, '\0', sizeof(struct stat)); + if (stat(userprefdir, &fst) < 0) { + if (mkdir(userprefdir, 0775) < 0) { + usbmuxd_log(LL_FATAL, "Failed to create required directory '%s': %s", userprefdir, strerror(errno)); + res = -1; + goto terminate; + } + if (stat(userprefdir, &fst) < 0) { + usbmuxd_log(LL_FATAL, "stat() failed after creating directory '%s': %s", userprefdir, strerror(errno)); + res = -1; + goto terminate; + } + } + + // make sure permission bits are set correctly + if (fst.st_mode != 02775) { + if (chmod(userprefdir, 02775) < 0) { + usbmuxd_log(LL_WARNING, "chmod(%s, 02775) failed: %s", userprefdir, strerror(errno)); + } + } +#endif + + // drop elevated privileges + if (drop_privileges && (getuid() == 0 || geteuid() == 0)) { + struct passwd *pw; + if (!drop_user) { + usbmuxd_log(LL_FATAL, "No user to drop privileges to?"); + res = -1; + goto terminate; + } + pw = getpwnam(drop_user); + if (!pw) { + usbmuxd_log(LL_FATAL, "Dropping privileges failed, check if user '%s' exists!", drop_user); + res = -1; + goto terminate; + } + if (pw->pw_uid == 0) { + usbmuxd_log(LL_INFO, "Not dropping privileges to root"); + } else { +#ifdef HAVE_LIBIMOBILEDEVICE + /* make sure the non-privileged user has proper access to the config directory */ + if ((fst.st_uid != pw->pw_uid) || (fst.st_gid != pw->pw_gid)) { + if (chown(userprefdir, pw->pw_uid, pw->pw_gid) < 0) { + usbmuxd_log(LL_WARNING, "chown(%s, %d, %d) failed: %s", userprefdir, pw->pw_uid, pw->pw_gid, strerror(errno)); + } + } +#endif + + if ((res = initgroups(drop_user, pw->pw_gid)) < 0) { + usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set supplementary groups)"); + goto terminate; + } + if ((res = setgid(pw->pw_gid)) < 0) { + usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set group ID to %d)", pw->pw_gid); + goto terminate; + } + if ((res = setuid(pw->pw_uid)) < 0) { + usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set user ID to %d)", pw->pw_uid); + goto terminate; + } + + // security check + if (setuid(0) != -1) { + usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!"); + res = -1; + goto terminate; + } + if (getuid() != pw->pw_uid || getgid() != pw->pw_gid) { + usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!"); + res = -1; + goto terminate; + } + usbmuxd_log(LL_NOTICE, "Successfully dropped privileges to '%s'", drop_user); + } + } + + client_init(); + device_init(); + usbmuxd_log(LL_INFO, "Initializing USB"); + if((res = usb_init()) < 0) + goto terminate; + + usbmuxd_log(LL_INFO, "%d device%s detected", res, (res==1)?"":"s"); + + usbmuxd_log(LL_NOTICE, "Initialization complete"); + + if (report_to_parent) + if((res = notify_parent(0)) < 0) + goto terminate; + + if(opt_disable_hotplug) { + usbmuxd_log(LL_NOTICE, "Automatic device discovery on hotplug disabled."); + usb_autodiscover(0); // discovery to be triggered by new instance + } + if (opt_enable_exit) { + usbmuxd_log(LL_NOTICE, "Enabled exit on SIGUSR1 if no devices are attached. Start a new instance with \"--exit\" to trigger."); + } + + res = main_loop(listenfd); + if(res < 0) + usbmuxd_log(LL_FATAL, "main_loop failed"); + + usbmuxd_log(LL_NOTICE, "usbmuxd shutting down"); + device_kill_connections(); + usb_shutdown(); + device_shutdown(); + client_shutdown(); + usbmuxd_log(LL_NOTICE, "Shutdown complete"); + +terminate: + log_disable_syslog(); + + if (res < 0) + res = -res; + else + res = 0; + if (report_to_parent) + notify_parent(res); + + return res; +} diff --git a/src/preflight.c b/src/preflight.c new file mode 100644 index 0000000..9c57e98 --- /dev/null +++ b/src/preflight.c @@ -0,0 +1,406 @@ +/* + * preflight.c + * + * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdlib.h> +#include <string.h> +#include <unistd.h> +#include <errno.h> + +#include <sys/time.h> + +#ifdef HAVE_LIBIMOBILEDEVICE +#include <libimobiledevice/libimobiledevice.h> +#include <libimobiledevice/lockdown.h> +#include <libimobiledevice/notification_proxy.h> +#endif + +#include <libimobiledevice-glue/thread.h> + +#include "preflight.h" +#include "device.h" +#include "client.h" +#include "conf.h" +#include "log.h" +#include "usb.h" + +extern int no_preflight; + +#ifdef HAVE_LIBIMOBILEDEVICE +#ifndef HAVE_ENUM_IDEVICE_CONNECTION_TYPE +enum idevice_connection_type { + CONNECTION_USBMUXD = 1, + CONNECTION_NETWORK +}; +#endif + +struct idevice_private { + char *udid; + uint32_t mux_id; + enum idevice_connection_type conn_type; + void *conn_data; + int version; + int device_class; +}; + +struct cb_data { + idevice_t dev; + np_client_t np; + int is_device_connected; + int is_finished; +}; + +static void lockdownd_set_untrusted_host_buid(lockdownd_client_t lockdown) +{ + char* system_buid = NULL; + config_get_system_buid(&system_buid); + usbmuxd_log(LL_DEBUG, "%s: Setting UntrustedHostBUID to %s", __func__, system_buid); + lockdownd_set_value(lockdown, NULL, "UntrustedHostBUID", plist_new_string(system_buid)); + free(system_buid); +} + +void preflight_device_remove_cb(void *data) +{ + if (!data) + return; + struct cb_data *cbdata = (struct cb_data*)data; + cbdata->is_device_connected = 0; +} + +static void np_callback(const char* notification, void* userdata) +{ + struct cb_data *cbdata = (struct cb_data*)userdata; + idevice_t dev = cbdata->dev; + struct idevice_private *_dev = (struct idevice_private*)dev; + + lockdownd_client_t lockdown = NULL; + lockdownd_error_t lerr; + + if (strlen(notification) == 0) { + cbdata->np = NULL; + return; + } + + if (strcmp(notification, "com.apple.mobile.lockdown.request_pair") == 0) { + usbmuxd_log(LL_INFO, "%s: user trusted this computer on device %s, pairing now", __func__, _dev->udid); + lerr = lockdownd_client_new(dev, &lockdown, "usbmuxd"); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr); + cbdata->is_finished = 1; + return; + } + + lerr = lockdownd_pair(lockdown, NULL); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_ERROR, "%s: ERROR: Pair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr); + lockdownd_client_free(lockdown); + cbdata->is_finished = 1; + return; + } + lockdownd_client_free(lockdown); + cbdata->is_finished = 1; + + } else if (strcmp(notification, "com.apple.mobile.lockdown.request_host_buid") == 0) { + lerr = lockdownd_client_new(cbdata->dev, &lockdown, "usbmuxd"); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr); + } else { + lockdownd_set_untrusted_host_buid(lockdown); + lockdownd_client_free(lockdown); + } + } +} + +static void* preflight_worker_handle_device_add(void* userdata) +{ + struct device_info *info = (struct device_info*)userdata; + struct idevice_private *_dev = (struct idevice_private*)malloc(sizeof(struct idevice_private)); + _dev->udid = strdup(info->serial); + _dev->mux_id = info->id; + _dev->conn_type = CONNECTION_USBMUXD; + _dev->conn_data = NULL; + _dev->version = 0; + _dev->device_class = 0; + + idevice_t dev = (idevice_t)_dev; + + lockdownd_client_t lockdown = NULL; + lockdownd_error_t lerr; + + plist_t value = NULL; + char* version_str = NULL; + char* deviceclass_str = NULL; + + usbmuxd_log(LL_INFO, "%s: Starting preflight on device %s...", __func__, _dev->udid); + +retry: + lerr = lockdownd_client_new(dev, &lockdown, "usbmuxd"); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_ERROR, "%s: ERROR: Could not connect to lockdownd on device %s, lockdown error %d", __func__, _dev->udid, lerr); + goto leave; + } + + char *type = NULL; + lerr = lockdownd_query_type(lockdown, &type); + if (!type) { + usbmuxd_log(LL_ERROR, "%s: ERROR: Could not get lockdownd type from device %s, lockdown error %d", __func__, _dev->udid, lerr); + goto leave; + } + + if (strcmp(type, "com.apple.mobile.lockdown") != 0) { + // make restore mode devices visible + free(type); + usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); + client_device_add(info); + goto leave; + } + free(type); + + int is_device_paired = 0; + char *host_id = NULL; + if (config_has_device_record(dev->udid)) { + config_device_record_get_host_id(dev->udid, &host_id); + lerr = lockdownd_start_session(lockdown, host_id, NULL, NULL); + if (host_id) + free(host_id); + if (lerr == LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_INFO, "%s: StartSession success for device %s", __func__, _dev->udid); + usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); + client_device_add(info); + goto leave; + } + + usbmuxd_log(LL_INFO, "%s: StartSession failed on device %s, lockdown error %d", __func__, _dev->udid, lerr); + } else { + lerr = LOCKDOWN_E_INVALID_HOST_ID; + } + switch (lerr) { + case LOCKDOWN_E_INVALID_HOST_ID: + usbmuxd_log(LL_INFO, "%s: Device %s is not paired with this host.", __func__, _dev->udid); + break; + case LOCKDOWN_E_SSL_ERROR: + usbmuxd_log(LL_ERROR, "%s: The stored pair record for device %s is invalid. Removing.", __func__, _dev->udid); + if (config_remove_device_record(_dev->udid) == 0) { + lockdownd_client_free(lockdown); + lockdown = NULL; + goto retry; + } else { + usbmuxd_log(LL_ERROR, "%s: Could not remove pair record for device %s", __func__, _dev->udid); + } + break; + default: + is_device_paired = 1; + break; + } + + lerr = lockdownd_get_value(lockdown, NULL, "ProductVersion", &value); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_WARNING, "%s: Could not get ProductVersion from device %s, lockdown error %d", __func__, _dev->udid, lerr); + /* assume old iOS version */ + version_str = strdup("1.0"); + } else { + if (value && plist_get_node_type(value) == PLIST_STRING) { + plist_get_string_val(value, &version_str); + } + plist_free(value); + + if (!version_str) { + usbmuxd_log(LL_ERROR, "%s: Could not get ProductVersion string from device %s handle %d", __func__, _dev->udid, (int)(long)_dev->conn_data); + goto leave; + } + } + + lerr = lockdownd_get_value(lockdown, NULL, "DeviceClass", &value); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_ERROR, "%s: ERROR: Could not get DeviceClass from device %s, lockdown error %d", __func__, _dev->udid, lerr); + goto leave; + } + if (value && plist_get_node_type(value) == PLIST_STRING) { + plist_get_string_val(value, &deviceclass_str); + } + plist_free(value); + + if (!deviceclass_str) { + usbmuxd_log(LL_ERROR, "%s: Could not get DeviceClass string from device %s handle %d", __func__, _dev->udid, (int)(long)_dev->conn_data); + goto leave; + } + + int version_major = strtol(version_str, NULL, 10); + if (((!strcmp(deviceclass_str, "iPhone") || !strcmp(deviceclass_str, "iPad")) && version_major >= 7) + || (!strcmp(deviceclass_str, "Watch") && version_major >= 2) + || (!strcmp(deviceclass_str, "AppleTV") && version_major >= 9) + ) { + /* iOS 7.0 / watchOS 2.0 / tvOS 9.0 and later */ + usbmuxd_log(LL_INFO, "%s: Found %s %s device %s", __func__, deviceclass_str, version_str, _dev->udid); + + lockdownd_set_untrusted_host_buid(lockdown); + + /* if not paired, trigger the trust dialog to make sure it appears */ + if (!is_device_paired) { + if (lockdownd_pair(lockdown, NULL) == LOCKDOWN_E_SUCCESS) { + /* if device is still showing the setup screen it will pair even without trust dialog */ + usbmuxd_log(LL_INFO, "%s: Pair success for device %s", __func__, _dev->udid); + usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); + client_device_add(info); + goto leave; + } + } + + lockdownd_service_descriptor_t service = NULL; + lerr = lockdownd_start_service(lockdown, "com.apple.mobile.insecure_notification_proxy", &service); + if (lerr != LOCKDOWN_E_SUCCESS) { + /* even though we failed, simple mode should still work, so only warn of an error */ + usbmuxd_log(LL_INFO, "%s: ERROR: Could not start insecure_notification_proxy on %s, lockdown error %d", __func__, _dev->udid, lerr); + client_device_add(info); + goto leave; + } + + np_client_t np = NULL; + np_client_new(dev, service, &np); + + lockdownd_service_descriptor_free(service); + service = NULL; + + lockdownd_client_free(lockdown); + lockdown = NULL; + + struct cb_data cbdata; + cbdata.dev = dev; + cbdata.np = np; + cbdata.is_device_connected = 1; + cbdata.is_finished = 0; + + np_set_notify_callback(np, np_callback, (void*)&cbdata); + device_set_preflight_cb_data(info->id, (void*)&cbdata); + + const char* spec[] = { + "com.apple.mobile.lockdown.request_pair", + "com.apple.mobile.lockdown.request_host_buid", + NULL + }; + np_observe_notifications(np, spec); + + /* TODO send notification to user's desktop */ + + usbmuxd_log(LL_INFO, "%s: Waiting for user to trust this computer on device %s", __func__, _dev->udid); + + /* make device visible anyways */ + client_device_add(info); + + while (cbdata.np && cbdata.is_device_connected && !cbdata.is_finished) { + sleep(1); + } + device_set_preflight_cb_data(info->id, NULL); + + usbmuxd_log(LL_INFO, "%s: Finished waiting for notification from device %s, is_device_connected %d", __func__, _dev->udid, cbdata.is_device_connected); + + if (cbdata.np) { + np_client_free(cbdata.np); + } + } else { + /* iOS 6.x and earlier */ + lerr = lockdownd_pair(lockdown, NULL); + if (lerr != LOCKDOWN_E_SUCCESS) { + if (lerr == LOCKDOWN_E_PASSWORD_PROTECTED) { + usbmuxd_log(LL_INFO, "%s: Device %s is locked with a passcode. Cannot pair.", __func__, _dev->udid); + /* TODO send notification to user's desktop */ + } else { + usbmuxd_log(LL_ERROR, "%s: ERROR: Pair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr); + } + + usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); + + /* make device visible anyways */ + client_device_add(info); + + goto leave; + } + + host_id = NULL; + config_device_record_get_host_id(dev->udid, &host_id); + lerr = lockdownd_start_session(lockdown, host_id, NULL, NULL); + free(host_id); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_ERROR, "%s: ERROR StartSession failed on device %s, lockdown error %d", __func__, _dev->udid, lerr); + goto leave; + } + + lerr = lockdownd_validate_pair(lockdown, NULL); + if (lerr != LOCKDOWN_E_SUCCESS) { + usbmuxd_log(LL_ERROR, "%s: ERROR: ValidatePair failed for device %s, lockdown error %d", __func__, _dev->udid, lerr); + goto leave; + } + + usbmuxd_log(LL_INFO, "%s: Finished preflight on device %s", __func__, _dev->udid); + + /* emit device added event and thus make device visible to clients */ + client_device_add(info); + } + +leave: + free(deviceclass_str); + free(version_str); + if (lockdown) + lockdownd_client_free(lockdown); + if (dev) + idevice_free(dev); + + free((char*)info->serial); + free(info); + + return NULL; +} +#else +void preflight_device_remove_cb(void *data) +{ +} +#endif + +void preflight_worker_device_add(struct device_info* info) +{ + if (info->pid == PID_APPLE_T2_COPROCESSOR || no_preflight == 1) { + client_device_add(info); + return; + } + +#ifdef HAVE_LIBIMOBILEDEVICE + struct device_info *infocopy = (struct device_info*)malloc(sizeof(struct device_info)); + + memcpy(infocopy, info, sizeof(struct device_info)); + if (info->serial) { + infocopy->serial = strdup(info->serial); + } + + THREAD_T th; + int perr = thread_new(&th, preflight_worker_handle_device_add, infocopy); + if (perr != 0) { + free((char*)infocopy->serial); + free(infocopy); + usbmuxd_log(LL_ERROR, "ERROR: failed to start preflight worker thread for device %s: %s (%d). Invoking client_device_add() directly but things might not work as expected.", info->serial, strerror(perr), perr); + client_device_add(info); + } else { + thread_detach(th); + } +#else + client_device_add(info); +#endif +} diff --git a/src/preflight.h b/src/preflight.h new file mode 100644 index 0000000..dd8647e --- /dev/null +++ b/src/preflight.h @@ -0,0 +1,28 @@ +/* + * preflight.h + * + * Copyright (C) 2013 Nikias Bassen <nikias@gmx.li> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef PREFLIGHT_H +#define PREFLIGHT_H + +#include "device.h" + +void preflight_device_remove_cb(void *data); +void preflight_worker_device_add(struct device_info* info); + +#endif diff --git a/src/usb.c b/src/usb.c new file mode 100644 index 0000000..d3cb17c --- /dev/null +++ b/src/usb.c @@ -0,0 +1,1084 @@ +/* + * usb.c + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * Copyright (C) 2009-2020 Martin Szulecki <martin.szulecki@libimobiledevice.org> + * Copyright (C) 2014 Mikkel Kamstrup Erlandsen <mikkel.kamstrup@xamarin.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <stdint.h> +#include <string.h> + +#include <libusb.h> + +#include <libimobiledevice-glue/collection.h> + +#include "usb.h" +#include "log.h" +#include "device.h" +#include "utils.h" + +#if (defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01000102)) || (defined(LIBUSBX_API_VERSION) && (LIBUSBX_API_VERSION >= 0x01000102)) +#define HAVE_LIBUSB_HOTPLUG_API 1 +#endif + +// interval for device connection/disconnection polling, in milliseconds +// we need this because there is currently no asynchronous device discovery mechanism in libusb +#define DEVICE_POLL_TIME 1000 + +// Number of parallel bulk transfers we have running for reading data from the device. +// Older versions of usbmuxd kept only 1, which leads to a mostly dormant USB port. +// 3 seems to be an all round sensible number - giving better read perf than +// Apples usbmuxd, at least. +#define NUM_RX_LOOPS 3 + +struct usb_device { + libusb_device_handle *handle; + uint8_t bus, address; + char serial[256]; + int alive; + uint8_t interface, ep_in, ep_out; + struct collection rx_xfers; + struct collection tx_xfers; + int wMaxPacketSize; + uint64_t speed; + struct libusb_device_descriptor devdesc; +}; + +struct mode_context { + struct libusb_device* dev; + uint8_t bus, address; + uint8_t bRequest; + uint16_t wValue, wIndex, wLength; + unsigned int timeout; +}; + +static struct collection device_list; + +static struct timeval next_dev_poll_time; + +static int devlist_failures; +static int device_polling; +static int device_hotplug = 1; + +static void usb_disconnect(struct usb_device *dev) +{ + if(!dev->handle) { + return; + } + + // kill the rx xfer and tx xfers and try to make sure the callbacks + // get called before we free the device + FOREACH(struct libusb_transfer *xfer, &dev->rx_xfers) { + usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling RX xfer %p", xfer); + libusb_cancel_transfer(xfer); + } ENDFOREACH + + FOREACH(struct libusb_transfer *xfer, &dev->tx_xfers) { + usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling TX xfer %p", xfer); + libusb_cancel_transfer(xfer); + } ENDFOREACH + + // Busy-wait until all xfers are closed + while(collection_count(&dev->rx_xfers) || collection_count(&dev->tx_xfers)) { + struct timeval tv; + int res; + + tv.tv_sec = 0; + tv.tv_usec = 1000; + if((res = libusb_handle_events_timeout(NULL, &tv)) < 0) { + usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout for usb_disconnect failed: %s", libusb_error_name(res)); + break; + } + } + + collection_free(&dev->tx_xfers); + collection_free(&dev->rx_xfers); + libusb_release_interface(dev->handle, dev->interface); + libusb_close(dev->handle); + dev->handle = NULL; + collection_remove(&device_list, dev); + free(dev); +} + +static void reap_dead_devices(void) { + FOREACH(struct usb_device *usbdev, &device_list) { + if(!usbdev->alive) { + device_remove(usbdev); + usb_disconnect(usbdev); + } + } ENDFOREACH +} + +// Callback from write operation +static void tx_callback(struct libusb_transfer *xfer) +{ + struct usb_device *dev = xfer->user_data; + usbmuxd_log(LL_SPEW, "TX callback dev %d-%d len %d -> %d status %d", dev->bus, dev->address, xfer->length, xfer->actual_length, xfer->status); + if(xfer->status != LIBUSB_TRANSFER_COMPLETED) { + switch(xfer->status) { + case LIBUSB_TRANSFER_COMPLETED: //shut up compiler + case LIBUSB_TRANSFER_ERROR: + // funny, this happens when we disconnect the device while waiting for a transfer, sometimes + usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to error or disconnect", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_TIMED_OUT: + usbmuxd_log(LL_ERROR, "TX transfer timed out for device %d-%d", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_CANCELLED: + usbmuxd_log(LL_DEBUG, "Device %d-%d TX transfer cancelled", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_STALL: + usbmuxd_log(LL_ERROR, "TX transfer stalled for device %d-%d", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_NO_DEVICE: + // other times, this happens, and also even when we abort the transfer after device removal + usbmuxd_log(LL_INFO, "Device %d-%d TX aborted due to disconnect", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_OVERFLOW: + usbmuxd_log(LL_ERROR, "TX transfer overflow for device %d-%d", dev->bus, dev->address); + break; + // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad) + default: + // this should never be reached. + break; + } + // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events + // we'll do device_remove there too + dev->alive = 0; + } + if(xfer->buffer) + free(xfer->buffer); + collection_remove(&dev->tx_xfers, xfer); + libusb_free_transfer(xfer); +} + +int usb_send(struct usb_device *dev, const unsigned char *buf, int length) +{ + int res; + struct libusb_transfer *xfer = libusb_alloc_transfer(0); + libusb_fill_bulk_transfer(xfer, dev->handle, dev->ep_out, (void*)buf, length, tx_callback, dev, 0); + if((res = libusb_submit_transfer(xfer)) < 0) { + usbmuxd_log(LL_ERROR, "Failed to submit TX transfer %p len %d to device %d-%d: %s", buf, length, dev->bus, dev->address, libusb_error_name(res)); + libusb_free_transfer(xfer); + return res; + } + collection_add(&dev->tx_xfers, xfer); + if (length % dev->wMaxPacketSize == 0) { + usbmuxd_log(LL_DEBUG, "Send ZLP"); + // Send Zero Length Packet + xfer = libusb_alloc_transfer(0); + void *buffer = malloc(1); + libusb_fill_bulk_transfer(xfer, dev->handle, dev->ep_out, buffer, 0, tx_callback, dev, 0); + if((res = libusb_submit_transfer(xfer)) < 0) { + usbmuxd_log(LL_ERROR, "Failed to submit TX ZLP transfer to device %d-%d: %s", dev->bus, dev->address, libusb_error_name(res)); + libusb_free_transfer(xfer); + return res; + } + collection_add(&dev->tx_xfers, xfer); + } + return 0; +} + +// Callback from read operation +// Under normal operation this issues a new read transfer request immediately, +// doing a kind of read-callback loop +static void rx_callback(struct libusb_transfer *xfer) +{ + struct usb_device *dev = xfer->user_data; + usbmuxd_log(LL_SPEW, "RX callback dev %d-%d len %d status %d", dev->bus, dev->address, xfer->actual_length, xfer->status); + if(xfer->status == LIBUSB_TRANSFER_COMPLETED) { + device_data_input(dev, xfer->buffer, xfer->actual_length); + libusb_submit_transfer(xfer); + } else { + switch(xfer->status) { + case LIBUSB_TRANSFER_COMPLETED: //shut up compiler + case LIBUSB_TRANSFER_ERROR: + // funny, this happens when we disconnect the device while waiting for a transfer, sometimes + usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to error or disconnect", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_TIMED_OUT: + usbmuxd_log(LL_ERROR, "RX transfer timed out for device %d-%d", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_CANCELLED: + usbmuxd_log(LL_DEBUG, "Device %d-%d RX transfer cancelled", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_STALL: + usbmuxd_log(LL_ERROR, "RX transfer stalled for device %d-%d", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_NO_DEVICE: + // other times, this happens, and also even when we abort the transfer after device removal + usbmuxd_log(LL_INFO, "Device %d-%d RX aborted due to disconnect", dev->bus, dev->address); + break; + case LIBUSB_TRANSFER_OVERFLOW: + usbmuxd_log(LL_ERROR, "RX transfer overflow for device %d-%d", dev->bus, dev->address); + break; + // and nothing happens (this never gets called) if the device is freed after a disconnect! (bad) + default: + // this should never be reached. + break; + } + + free(xfer->buffer); + collection_remove(&dev->rx_xfers, xfer); + libusb_free_transfer(xfer); + + // we can't usb_disconnect here due to a deadlock, so instead mark it as dead and reap it after processing events + // we'll do device_remove there too + dev->alive = 0; + } +} + +// Start a read-callback loop for this device +static int start_rx_loop(struct usb_device *dev) +{ + int res; + void *buf; + struct libusb_transfer *xfer = libusb_alloc_transfer(0); + buf = malloc(USB_MRU); + libusb_fill_bulk_transfer(xfer, dev->handle, dev->ep_in, buf, USB_MRU, rx_callback, dev, 0); + if((res = libusb_submit_transfer(xfer)) != 0) { + usbmuxd_log(LL_ERROR, "Failed to submit RX transfer to device %d-%d: %s", dev->bus, dev->address, libusb_error_name(res)); + libusb_free_transfer(xfer); + return res; + } + + collection_add(&dev->rx_xfers, xfer); + + return 0; +} + +static void get_serial_callback(struct libusb_transfer *transfer) +{ + unsigned int di, si; + struct usb_device *usbdev = transfer->user_data; + + if(transfer->status != LIBUSB_TRANSFER_COMPLETED) { + usbmuxd_log(LL_ERROR, "Failed to request serial for device %d-%d (%i)", usbdev->bus, usbdev->address, transfer->status); + libusb_free_transfer(transfer); + return; + } + + /* De-unicode, taken from libusb */ + unsigned char *data = libusb_control_transfer_get_data(transfer); + for (di = 0, si = 2; si < data[0] && di < sizeof(usbdev->serial)-1; si += 2) { + if ((data[si] & 0x80) || (data[si + 1])) /* non-ASCII */ + usbdev->serial[di++] = '?'; + else if (data[si] == '\0') + break; + else + usbdev->serial[di++] = data[si]; + } + usbdev->serial[di] = '\0'; + + usbmuxd_log(LL_INFO, "Got serial '%s' for device %d-%d", usbdev->serial, usbdev->bus, usbdev->address); + + libusb_free_transfer(transfer); + + /* new style UDID: add hyphen between first 8 and following 16 digits */ + if (di == 24) { + memmove(&usbdev->serial[9], &usbdev->serial[8], 16); + usbdev->serial[8] = '-'; + usbdev->serial[di+1] = '\0'; + } + + /* Finish setup now */ + if(device_add(usbdev) < 0) { + usb_disconnect(usbdev); + return; + } + + // Spin up NUM_RX_LOOPS parallel usb data retrieval loops + // Old usbmuxds used only 1 rx loop, but that leaves the + // USB port sleeping most of the time + int rx_loops = NUM_RX_LOOPS; + for (rx_loops = NUM_RX_LOOPS; rx_loops > 0; rx_loops--) { + if(start_rx_loop(usbdev) < 0) { + usbmuxd_log(LL_WARNING, "Failed to start RX loop number %d", NUM_RX_LOOPS - rx_loops); + break; + } + } + + // Ensure we have at least 1 RX loop going + if (rx_loops == NUM_RX_LOOPS) { + usbmuxd_log(LL_FATAL, "Failed to start any RX loop for device %d-%d", + usbdev->bus, usbdev->address); + device_remove(usbdev); + usb_disconnect(usbdev); + return; + } else if (rx_loops > 0) { + usbmuxd_log(LL_WARNING, "Failed to start all %d RX loops. Going on with %d loops. " + "This may have negative impact on device read speed.", + NUM_RX_LOOPS, NUM_RX_LOOPS - rx_loops); + } else { + usbmuxd_log(LL_DEBUG, "All %d RX loops started successfully", NUM_RX_LOOPS); + } +} + +static void get_langid_callback(struct libusb_transfer *transfer) +{ + int res; + struct usb_device *usbdev = transfer->user_data; + + transfer->flags |= LIBUSB_TRANSFER_FREE_BUFFER; + + if(transfer->status != LIBUSB_TRANSFER_COMPLETED) { + usbmuxd_log(LL_ERROR, "Failed to request lang ID for device %d-%d (%i)", usbdev->bus, + usbdev->address, transfer->status); + libusb_free_transfer(transfer); + return; + } + + unsigned char *data = libusb_control_transfer_get_data(transfer); + uint16_t langid = (uint16_t)(data[2] | (data[3] << 8)); + usbmuxd_log(LL_INFO, "Got lang ID %u for device %d-%d", langid, usbdev->bus, usbdev->address); + + /* re-use the same transfer */ + libusb_fill_control_setup(transfer->buffer, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR, + (uint16_t)((LIBUSB_DT_STRING << 8) | usbdev->devdesc.iSerialNumber), + langid, 1024 + LIBUSB_CONTROL_SETUP_SIZE); + libusb_fill_control_transfer(transfer, usbdev->handle, transfer->buffer, get_serial_callback, usbdev, 1000); + + if((res = libusb_submit_transfer(transfer)) < 0) { + usbmuxd_log(LL_ERROR, "Could not request transfer for device %d-%d: %s", usbdev->bus, usbdev->address, libusb_error_name(res)); + libusb_free_transfer(transfer); + } +} + +static int submit_vendor_specific(struct libusb_device_handle *handle, struct mode_context *context, libusb_transfer_cb_fn callback) +{ + struct libusb_transfer* ctrl_transfer = libusb_alloc_transfer(0); + int ret = 0; + unsigned char* buffer = calloc(LIBUSB_CONTROL_SETUP_SIZE + context->wLength, 1); + uint8_t bRequestType = LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_DEVICE; + libusb_fill_control_setup(buffer, bRequestType, context->bRequest, context->wValue, context->wIndex, context->wLength); + + ctrl_transfer->flags = LIBUSB_TRANSFER_FREE_TRANSFER; + libusb_fill_control_transfer(ctrl_transfer, handle, buffer, callback, context, context->timeout); + + ret = libusb_submit_transfer(ctrl_transfer); + return ret; +} + +static struct usb_device* find_device(int bus, int address) +{ + FOREACH(struct usb_device *usbdev, &device_list) { + if(usbdev->bus == bus && usbdev->address == address) { + return usbdev; + } + } ENDFOREACH + return NULL; +} + +/// @brief guess the current mode +/// @param dev +/// @param usbdev +/// @param handle +/// @return 0 - undetermined, 1 - initial, 2 - valeria, 3 - cdc_ncm +static int guess_mode(struct libusb_device* dev, struct usb_device *usbdev) +{ + int res, j; + int has_valeria = 0, has_cdc_ncm = 0, has_usbmux = 0; + struct libusb_device_descriptor devdesc = usbdev->devdesc; + struct libusb_config_descriptor *config; + int bus = usbdev->bus; + int address = usbdev->address; + + if(devdesc.bNumConfigurations <= 4) { + // Assume this is initial mode + return 1; + } + + if(devdesc.bNumConfigurations != 5) { + // No known modes with more then 5 configurations + return 0; + } + + if((res = libusb_get_config_descriptor_by_value(dev, 5, &config)) != 0) { + usbmuxd_log(LL_NOTICE, "Could not get configuration 5 descriptor for device %i-%i: %s", bus, address, libusb_error_name(res)); + return 0; + } + + // Require both usbmux and one of the other interfaces to determine this is a valid configuration + for(j = 0 ; j < config->bNumInterfaces ; j++) { + const struct libusb_interface_descriptor *intf = &config->interface[j].altsetting[0]; + if(intf->bInterfaceClass == INTERFACE_CLASS && + intf->bInterfaceSubClass == 42 && + intf->bInterfaceProtocol == 255) { + has_valeria = 1; + } + // https://github.com/torvalds/linux/blob/72a85e2b0a1e1e6fb4ee51ae902730212b2de25c/include/uapi/linux/usb/cdc.h#L22 + // 2 for Communication class, 0xd for CDC NCM subclass + if(intf->bInterfaceClass == 2 && + intf->bInterfaceSubClass == 0xd) { + has_cdc_ncm = 1; + } + if(intf->bInterfaceClass == INTERFACE_CLASS && + intf->bInterfaceSubClass == INTERFACE_SUBCLASS && + intf->bInterfaceProtocol == INTERFACE_PROTOCOL) { + has_usbmux = 1; + } + } + + libusb_free_config_descriptor(config); + + if(has_valeria && has_usbmux) { + usbmuxd_log(LL_NOTICE, "Found Valeria and Apple USB Multiplexor in device %i-%i configuration 5", bus, address); + return 2; + } + + if(has_cdc_ncm && has_usbmux) { + usbmuxd_log(LL_NOTICE, "Found CDC-NCM and Apple USB Multiplexor in device %i-%i configuration 5", bus, address); + return 3; + } + + return 0; +} + +/// @brief Finds and sets the valid configuration, interface and endpoints on the usb_device +static int set_valid_configuration(struct libusb_device* dev, struct usb_device *usbdev, struct libusb_device_handle *handle) +{ + int j, k, res, found = 0; + struct libusb_config_descriptor *config; + const struct libusb_interface_descriptor *intf; + struct libusb_device_descriptor devdesc = usbdev->devdesc; + int bus = usbdev->bus; + int address = usbdev->address; + int current_config = 0; + + if((res = libusb_get_configuration(handle, ¤t_config)) != 0) { + usbmuxd_log(LL_WARNING, "Could not get current configuration for device %d-%d: %s", bus, address, libusb_error_name(res)); + return -1; + } + + for(j = devdesc.bNumConfigurations ; j > 0 ; j--) { + if((res = libusb_get_config_descriptor_by_value(dev, j, &config)) != 0) { + usbmuxd_log(LL_NOTICE, "Could not get configuration %i descriptor for device %i-%i: %s", j, bus, address, libusb_error_name(res)); + continue; + } + for(k = 0 ; k < config->bNumInterfaces ; k++) { + intf = &config->interface[k].altsetting[0]; + if(intf->bInterfaceClass == INTERFACE_CLASS || + intf->bInterfaceSubClass == INTERFACE_SUBCLASS || + intf->bInterfaceProtocol == INTERFACE_PROTOCOL) { + usbmuxd_log(LL_NOTICE, "Found usbmux interface for device %i-%i: %i", bus, address, intf->bInterfaceNumber); + if(intf->bNumEndpoints != 2) { + usbmuxd_log(LL_WARNING, "Endpoint count mismatch for interface %i of device %i-%i", intf->bInterfaceNumber, bus, address); + continue; + } + if((intf->endpoint[0].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_OUT && + (intf->endpoint[1].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN) { + usbdev->interface = intf->bInterfaceNumber; + usbdev->ep_out = intf->endpoint[0].bEndpointAddress; + usbdev->ep_in = intf->endpoint[1].bEndpointAddress; + usbmuxd_log(LL_INFO, "Found interface %i with endpoints %02x/%02x for device %i-%i", usbdev->interface, usbdev->ep_out, usbdev->ep_in, bus, address); + found = 1; + break; + } else if((intf->endpoint[1].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_OUT && + (intf->endpoint[0].bEndpointAddress & 0x80) == LIBUSB_ENDPOINT_IN) { + usbdev->interface = intf->bInterfaceNumber; + usbdev->ep_out = intf->endpoint[1].bEndpointAddress; + usbdev->ep_in = intf->endpoint[0].bEndpointAddress; + usbmuxd_log(LL_INFO, "Found interface %i with swapped endpoints %02x/%02x for device %i-%i", usbdev->interface, usbdev->ep_out, usbdev->ep_in, bus, address); + found = 1; + break; + } else { + usbmuxd_log(LL_WARNING, "Endpoint type mismatch for interface %i of device %i-%i", intf->bInterfaceNumber, bus, address); + } + } + } + if(!found) { + libusb_free_config_descriptor(config); + continue; + } + // If set configuration is required, try to first detach all kernel drivers + if (current_config == 0) { + usbmuxd_log(LL_DEBUG, "Device %d-%d is unconfigured", bus, address); + } + if(current_config == 0 || config->bConfigurationValue != current_config) { + usbmuxd_log(LL_NOTICE, "Changing configuration of device %i-%i: %i -> %i", bus, address, current_config, config->bConfigurationValue); + for(k=0 ; k < config->bNumInterfaces ; k++) { + const struct libusb_interface_descriptor *intf1 = &config->interface[k].altsetting[0]; + if((res = libusb_kernel_driver_active(handle, intf1->bInterfaceNumber)) < 0) { + usbmuxd_log(LL_NOTICE, "Could not check kernel ownership of interface %d for device %d-%d: %s", intf1->bInterfaceNumber, bus, address, libusb_error_name(res)); + continue; + } + if(res == 1) { + usbmuxd_log(LL_INFO, "Detaching kernel driver for device %d-%d, interface %d", bus, address, intf1->bInterfaceNumber); + if((res = libusb_detach_kernel_driver(handle, intf1->bInterfaceNumber)) < 0) { + usbmuxd_log(LL_WARNING, "Could not detach kernel driver, configuration change will probably fail! %s", libusb_error_name(res)); + continue; + } + } + } + if((res = libusb_set_configuration(handle, j)) != 0) { + usbmuxd_log(LL_WARNING, "Could not set configuration %d for device %d-%d: %s", j, bus, address, libusb_error_name(res)); + libusb_free_config_descriptor(config); + continue; + } + } + + libusb_free_config_descriptor(config); + break; + } + + if(!found) { + usbmuxd_log(LL_WARNING, "Could not find a suitable USB interface for device %i-%i", bus, address); + return -1; + } + + return 0; +} + +static void device_complete_initialization(struct mode_context *context, struct libusb_device_handle *handle) +{ + struct usb_device *usbdev = find_device(context->bus, context->address); + if(!usbdev) { + usbmuxd_log(LL_ERROR, "Device %d-%d is missing from device list, aborting initialization", context->bus, context->address); + return; + } + struct libusb_device *dev = context->dev; + struct libusb_device_descriptor devdesc = usbdev->devdesc; + int bus = context->bus; + int address = context->address; + int res; + struct libusb_transfer *transfer; + + if((res = set_valid_configuration(dev, usbdev, handle)) != 0) { + usbdev->alive = 0; + return; + } + + if((res = libusb_claim_interface(handle, usbdev->interface)) != 0) { + usbmuxd_log(LL_WARNING, "Could not claim interface %d for device %d-%d: %s", usbdev->interface, bus, address, libusb_error_name(res)); + usbdev->alive = 0; + return; + } + + transfer = libusb_alloc_transfer(0); + if(!transfer) { + usbmuxd_log(LL_WARNING, "Failed to allocate transfer for device %d-%d: %s", bus, address, libusb_error_name(res)); + usbdev->alive = 0; + return; + } + + unsigned char *transfer_buffer = malloc(1024 + LIBUSB_CONTROL_SETUP_SIZE + 8); + if (!transfer_buffer) { + usbmuxd_log(LL_WARNING, "Failed to allocate transfer buffer for device %d-%d: %s", bus, address, libusb_error_name(res)); + usbdev->alive = 0; + return; + } + memset(transfer_buffer, '\0', 1024 + LIBUSB_CONTROL_SETUP_SIZE + 8); + + usbdev->serial[0] = 0; + usbdev->bus = bus; + usbdev->address = address; + usbdev->devdesc = devdesc; + usbdev->speed = 480000000; + usbdev->handle = handle; + usbdev->alive = 1; + usbdev->wMaxPacketSize = libusb_get_max_packet_size(dev, usbdev->ep_out); + if (usbdev->wMaxPacketSize <= 0) { + usbmuxd_log(LL_ERROR, "Could not determine wMaxPacketSize for device %d-%d, setting to 64", usbdev->bus, usbdev->address); + usbdev->wMaxPacketSize = 64; + } else { + usbmuxd_log(LL_INFO, "Using wMaxPacketSize=%d for device %d-%d", usbdev->wMaxPacketSize, usbdev->bus, usbdev->address); + } + + switch (libusb_get_device_speed(dev)) { + case LIBUSB_SPEED_LOW: + usbdev->speed = 1500000; + break; + case LIBUSB_SPEED_FULL: + usbdev->speed = 12000000; + break; + case LIBUSB_SPEED_SUPER: + usbdev->speed = 5000000000; + break; + case LIBUSB_SPEED_HIGH: + case LIBUSB_SPEED_UNKNOWN: + default: + usbdev->speed = 480000000; + break; + } + + usbmuxd_log(LL_INFO, "USB Speed is %g MBit/s for device %d-%d", (double)(usbdev->speed / 1000000.0), usbdev->bus, usbdev->address); + + /** + * From libusb: + * Asking for the zero'th index is special - it returns a string + * descriptor that contains all the language IDs supported by the + * device. + **/ + libusb_fill_control_setup(transfer_buffer, LIBUSB_ENDPOINT_IN, LIBUSB_REQUEST_GET_DESCRIPTOR, LIBUSB_DT_STRING << 8, 0, 1024 + LIBUSB_CONTROL_SETUP_SIZE); + libusb_fill_control_transfer(transfer, handle, transfer_buffer, get_langid_callback, usbdev, 1000); + + if((res = libusb_submit_transfer(transfer)) < 0) { + usbmuxd_log(LL_ERROR, "Could not request transfer for device %d-%d: %s", usbdev->bus, usbdev->address, libusb_error_name(res)); + libusb_free_transfer(transfer); + free(transfer_buffer); + usbdev->alive = 0; + return; + } +} + +static void switch_mode_cb(struct libusb_transfer* transfer) +{ + // For old devices not supporting mode swtich, if anything goes wrong - continue in current mode + struct mode_context* context = transfer->user_data; + struct usb_device *dev = find_device(context->bus, context->address); + if(!dev) { + usbmuxd_log(LL_WARNING, "Device %d-%d is missing from device list", context->bus, context->address); + } + if(transfer->status != LIBUSB_TRANSFER_COMPLETED) { + usbmuxd_log(LL_ERROR, "Failed to request mode switch for device %i-%i (%i). Completing initialization in current mode", + context->bus, context->address, transfer->status); + device_complete_initialization(context, transfer->dev_handle); + } + else { + unsigned char *data = libusb_control_transfer_get_data(transfer); + if(data[0] != 0) { + usbmuxd_log(LL_INFO, "Received unexpected response for device %i-%i mode switch (%i). Completing initialization in current mode", + context->bus, context->address, data[0]); + device_complete_initialization(context, transfer->dev_handle); + } + } + free(context); + if(transfer->buffer) + free(transfer->buffer); +} + +static void get_mode_cb(struct libusb_transfer* transfer) +{ + // For old devices not supporting mode swtich, if anything goes wrong - continue in current mode + int res; + struct mode_context* context = transfer->user_data; + struct usb_device *dev = find_device(context->bus, context->address); + if(!dev) { + usbmuxd_log(LL_ERROR, "Device %d-%d is missing from device list, aborting mode switch", context->bus, context->address); + free(context); + return; + } + + if(transfer->status != LIBUSB_TRANSFER_COMPLETED) { + usbmuxd_log(LL_ERROR, "Failed to request get mode for device %i-%i (%i). Completing initialization in current mode", + context->bus, context->address, transfer->status); + device_complete_initialization(context, transfer->dev_handle); + free(context); + return; + } + + unsigned char *data = libusb_control_transfer_get_data(transfer); + + char* desired_mode_char = getenv(ENV_DEVICE_MODE); + int desired_mode = desired_mode_char ? atoi(desired_mode_char) : 3; + int guessed_mode = guess_mode(context->dev, dev); + + // Response is 3:3:3:0 for initial mode, 5:3:3:0 otherwise. + usbmuxd_log(LL_INFO, "Received response %i:%i:%i:%i for get_mode request for device %i-%i", data[0], data[1], data[2], data[3], context->bus, context->address); + if(desired_mode >= 1 && desired_mode <= 3 && + guessed_mode > 0 && // do not switch mode if guess failed + guessed_mode != desired_mode) { + usbmuxd_log(LL_WARNING, "Switching device %i-%i mode to %i", context->bus, context->address, desired_mode); + + context->bRequest = APPLE_VEND_SPECIFIC_SET_MODE; + context->wValue = 0; + context->wIndex = desired_mode; + context->wLength = 1; + + if((res = submit_vendor_specific(transfer->dev_handle, context, switch_mode_cb)) != 0) { + usbmuxd_log(LL_WARNING, "Could not request to switch mode %i for device %i-%i (%i)", context->wIndex, context->bus, context->address, res); + dev->alive = 0; + free(context); + } + } + else { + usbmuxd_log(LL_WARNING, "Skipping switch device %i-%i mode from %i to %i", context->bus, context->address, guessed_mode, desired_mode); + device_complete_initialization(context, transfer->dev_handle); + free(context); + } + if(transfer->buffer) + free(transfer->buffer); +} + +static int usb_device_add(libusb_device* dev) +{ + int res; + // the following are non-blocking operations on the device list + uint8_t bus = libusb_get_bus_number(dev); + uint8_t address = libusb_get_device_address(dev); + struct libusb_device_descriptor devdesc; + struct usb_device *usbdev = find_device(bus, address); + if(usbdev) { + usbdev->alive = 1; + return 0; //device already found + } + + if((res = libusb_get_device_descriptor(dev, &devdesc)) != 0) { + usbmuxd_log(LL_WARNING, "Could not get device descriptor for device %d-%d: %s", bus, address, libusb_error_name(res)); + return -1; + } + if(devdesc.idVendor != VID_APPLE) + return -1; + if((devdesc.idProduct != PID_APPLE_T2_COPROCESSOR) && + ((devdesc.idProduct < PID_APPLE_SILICON_RESTORE_LOW) || + (devdesc.idProduct > PID_APPLE_SILICON_RESTORE_MAX)) && + ((devdesc.idProduct < PID_RANGE_LOW) || + (devdesc.idProduct > PID_RANGE_MAX))) + return -1; + libusb_device_handle *handle; + usbmuxd_log(LL_INFO, "Found new device with v/p %04x:%04x at %d-%d", devdesc.idVendor, devdesc.idProduct, bus, address); + // No blocking operation can follow: it may be run in the libusb hotplug callback and libusb will refuse any + // blocking call + if((res = libusb_open(dev, &handle)) != 0) { + usbmuxd_log(LL_WARNING, "Could not open device %d-%d: %s", bus, address, libusb_error_name(res)); + return -1; + } + + // Add the created handle to the device list, so we can close it in case of failure/disconnection + usbdev = malloc(sizeof(struct usb_device)); + memset(usbdev, 0, sizeof(*usbdev)); + + usbdev->serial[0] = 0; + usbdev->bus = bus; + usbdev->address = address; + usbdev->devdesc = devdesc; + usbdev->speed = 0; + usbdev->handle = handle; + usbdev->alive = 1; + + collection_init(&usbdev->tx_xfers); + collection_init(&usbdev->rx_xfers); + + collection_add(&device_list, usbdev); + + // On top of configurations, Apple have multiple "modes" for devices, namely: + // 1: An "initial" mode with 4 configurations + // 2: "Valeria" mode, where configuration 5 is included with interface for H.265 video capture (activated when recording screen with QuickTime in macOS) + // 3: "CDC NCM" mode, where configuration 5 is included with interface for Ethernet/USB (activated using internet-sharing feature in macOS) + // Request current mode asynchroniously, so it can be changed in callback if needed + usbmuxd_log(LL_INFO, "Requesting current mode from device %i-%i", bus, address); + struct mode_context* context = malloc(sizeof(struct mode_context)); + context->dev = dev; + context->bus = bus; + context->address = address; + context->bRequest = APPLE_VEND_SPECIFIC_GET_MODE; + context->wValue = 0; + context->wIndex = 0; + context->wLength = 4; + context->timeout = 1000; + + if(submit_vendor_specific(handle, context, get_mode_cb) != 0) { + usbmuxd_log(LL_WARNING, "Could not request current mode from device %d-%d", bus, address); + // Schedule device for close and cleanup + usbdev->alive = 0; + return -1; + } + return 0; +} + +int usb_discover(void) +{ + int cnt, i; + int valid_count = 0; + libusb_device **devs; + + cnt = libusb_get_device_list(NULL, &devs); + if(cnt < 0) { + usbmuxd_log(LL_WARNING, "Could not get device list: %d", cnt); + devlist_failures++; + // sometimes libusb fails getting the device list if you've just removed something + if(devlist_failures > 5) { + usbmuxd_log(LL_FATAL, "Too many errors getting device list"); + return cnt; + } else { + get_tick_count(&next_dev_poll_time); + next_dev_poll_time.tv_usec += DEVICE_POLL_TIME * 1000; + next_dev_poll_time.tv_sec += next_dev_poll_time.tv_usec / 1000000; + next_dev_poll_time.tv_usec = next_dev_poll_time.tv_usec % 1000000; + return 0; + } + } + devlist_failures = 0; + + usbmuxd_log(LL_SPEW, "usb_discover: scanning %d devices", cnt); + + // Mark all devices as dead, and do a mark-sweep like + // collection of dead devices + FOREACH(struct usb_device *usbdev, &device_list) { + usbdev->alive = 0; + } ENDFOREACH + + // Enumerate all USB devices and mark the ones we already know + // about as live, again + for(i=0; i<cnt; i++) { + libusb_device *dev = devs[i]; + if (usb_device_add(dev) < 0) { + continue; + } + valid_count++; + } + + // Clean out any device we didn't mark back as live + reap_dead_devices(); + + libusb_free_device_list(devs, 1); + + get_tick_count(&next_dev_poll_time); + next_dev_poll_time.tv_usec += DEVICE_POLL_TIME * 1000; + next_dev_poll_time.tv_sec += next_dev_poll_time.tv_usec / 1000000; + next_dev_poll_time.tv_usec = next_dev_poll_time.tv_usec % 1000000; + + return valid_count; +} + +const char *usb_get_serial(struct usb_device *dev) +{ + if(!dev->handle) { + return NULL; + } + return dev->serial; +} + +uint32_t usb_get_location(struct usb_device *dev) +{ + if(!dev->handle) { + return 0; + } + return (dev->bus << 16) | dev->address; +} + +uint16_t usb_get_pid(struct usb_device *dev) +{ + if(!dev->handle) { + return 0; + } + return dev->devdesc.idProduct; +} + +uint64_t usb_get_speed(struct usb_device *dev) +{ + if (!dev->handle) { + return 0; + } + return dev->speed; +} + +void usb_get_fds(struct fdlist *list) +{ + const struct libusb_pollfd **usbfds; + const struct libusb_pollfd **p; + usbfds = libusb_get_pollfds(NULL); + if(!usbfds) { + usbmuxd_log(LL_ERROR, "libusb_get_pollfds failed"); + return; + } + p = usbfds; + while(*p) { + fdlist_add(list, FD_USB, (*p)->fd, (*p)->events); + p++; + } + free(usbfds); +} + +void usb_autodiscover(int enable) +{ + usbmuxd_log(LL_DEBUG, "usb polling enable: %d", enable); + device_polling = enable; + device_hotplug = enable; +} + +static int dev_poll_remain_ms(void) +{ + int msecs; + struct timeval tv; + if(!device_polling) + return 100000; // devices will never be polled if this is > 0 + get_tick_count(&tv); + msecs = (next_dev_poll_time.tv_sec - tv.tv_sec) * 1000; + msecs += (next_dev_poll_time.tv_usec - tv.tv_usec) / 1000; + if(msecs < 0) + return 0; + return msecs; +} + +int usb_get_timeout(void) +{ + struct timeval tv; + int msec; + int res; + int pollrem; + pollrem = dev_poll_remain_ms(); + res = libusb_get_next_timeout(NULL, &tv); + if(res == 0) + return pollrem; + if(res < 0) { + usbmuxd_log(LL_ERROR, "libusb_get_next_timeout failed: %s", libusb_error_name(res)); + return pollrem; + } + msec = tv.tv_sec * 1000; + msec += tv.tv_usec / 1000; + if(msec > pollrem) + return pollrem; + return msec; +} + +int usb_process(void) +{ + int res; + struct timeval tv; + tv.tv_sec = tv.tv_usec = 0; + res = libusb_handle_events_timeout(NULL, &tv); + if(res < 0) { + usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %s", libusb_error_name(res)); + return res; + } + + // reap devices marked dead due to an RX error + reap_dead_devices(); + + if(dev_poll_remain_ms() <= 0) { + res = usb_discover(); + if(res < 0) { + usbmuxd_log(LL_ERROR, "usb_discover failed: %s", libusb_error_name(res)); + return res; + } + } + return 0; +} + +int usb_process_timeout(int msec) +{ + int res; + struct timeval tleft, tcur, tfin; + get_tick_count(&tcur); + tfin.tv_sec = tcur.tv_sec + (msec / 1000); + tfin.tv_usec = tcur.tv_usec + (msec % 1000) * 1000; + tfin.tv_sec += tfin.tv_usec / 1000000; + tfin.tv_usec %= 1000000; + while((tfin.tv_sec > tcur.tv_sec) || ((tfin.tv_sec == tcur.tv_sec) && (tfin.tv_usec > tcur.tv_usec))) { + tleft.tv_sec = tfin.tv_sec - tcur.tv_sec; + tleft.tv_usec = tfin.tv_usec - tcur.tv_usec; + if(tleft.tv_usec < 0) { + tleft.tv_usec += 1000000; + tleft.tv_sec -= 1; + } + res = libusb_handle_events_timeout(NULL, &tleft); + if(res < 0) { + usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %s", libusb_error_name(res)); + return res; + } + // reap devices marked dead due to an RX error + reap_dead_devices(); + get_tick_count(&tcur); + } + return 0; +} + +#ifdef HAVE_LIBUSB_HOTPLUG_API +static libusb_hotplug_callback_handle usb_hotplug_cb_handle; + +static int usb_hotplug_cb(libusb_context *ctx, libusb_device *device, libusb_hotplug_event event, void *user_data) +{ + if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) { + if (device_hotplug) { + usb_device_add(device); + } + } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) { + uint8_t bus = libusb_get_bus_number(device); + uint8_t address = libusb_get_device_address(device); + FOREACH(struct usb_device *usbdev, &device_list) { + if(usbdev->bus == bus && usbdev->address == address) { + usbdev->alive = 0; + device_remove(usbdev); + break; + } + } ENDFOREACH + } else { + usbmuxd_log(LL_ERROR, "Unhandled event %d", event); + } + return 0; +} +#endif + +int usb_init(void) +{ + int res; + const struct libusb_version* libusb_version_info = libusb_get_version(); + usbmuxd_log(LL_NOTICE, "Using libusb %d.%d.%d", libusb_version_info->major, libusb_version_info->minor, libusb_version_info->micro); + + devlist_failures = 0; + device_polling = 1; + res = libusb_init(NULL); + + if (res != 0) { + usbmuxd_log(LL_FATAL, "libusb_init failed: %s", libusb_error_name(res)); + return -1; + } + +#if LIBUSB_API_VERSION >= 0x01000106 + libusb_set_option(NULL, LIBUSB_OPTION_LOG_LEVEL, (log_level >= LL_DEBUG ? LIBUSB_LOG_LEVEL_DEBUG: (log_level >= LL_WARNING ? LIBUSB_LOG_LEVEL_WARNING: LIBUSB_LOG_LEVEL_NONE))); +#else + libusb_set_debug(NULL, (log_level >= LL_DEBUG ? LIBUSB_LOG_LEVEL_DEBUG: (log_level >= LL_WARNING ? LIBUSB_LOG_LEVEL_WARNING: LIBUSB_LOG_LEVEL_NONE))); +#endif + + collection_init(&device_list); + +#ifdef HAVE_LIBUSB_HOTPLUG_API + if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { + usbmuxd_log(LL_INFO, "Registering for libusb hotplug events"); + res = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, LIBUSB_HOTPLUG_ENUMERATE, VID_APPLE, LIBUSB_HOTPLUG_MATCH_ANY, 0, usb_hotplug_cb, NULL, &usb_hotplug_cb_handle); + if (res == LIBUSB_SUCCESS) { + device_polling = 0; + } else { + usbmuxd_log(LL_ERROR, "ERROR: Could not register for libusb hotplug events. %s", libusb_error_name(res)); + } + } else { + usbmuxd_log(LL_ERROR, "libusb does not support hotplug events"); + } +#endif + if (device_polling) { + res = usb_discover(); + if (res >= 0) { + } + } else { + res = collection_count(&device_list); + } + return res; +} + +void usb_shutdown(void) +{ + usbmuxd_log(LL_DEBUG, "usb_shutdown"); + +#ifdef HAVE_LIBUSB_HOTPLUG_API + libusb_hotplug_deregister_callback(NULL, usb_hotplug_cb_handle); +#endif + + FOREACH(struct usb_device *usbdev, &device_list) { + device_remove(usbdev); + usb_disconnect(usbdev); + } ENDFOREACH + collection_free(&device_list); + libusb_exit(NULL); +} diff --git a/src/usb.h b/src/usb.h new file mode 100644 index 0000000..4e44cce --- /dev/null +++ b/src/usb.h @@ -0,0 +1,73 @@ +/* + * usb.h + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * Copyright (C) 2009 Martin Szulecki <opensuse@sukimashita.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef USB_H +#define USB_H + +#include <stdint.h> +#include "utils.h" + +#define INTERFACE_CLASS 255 +#define INTERFACE_SUBCLASS 254 +#define INTERFACE_PROTOCOL 2 + +// libusb fragments packets larger than this (usbfs limitation) +// on input, this creates race conditions and other issues +#define USB_MRU 16384 + +// max transmission packet size +// libusb fragments these too, but doesn't send ZLPs so we're safe +// but we need to send a ZLP ourselves at the end (see usb-linux.c) +// we're using 3 * 16384 to optimize for the fragmentation +// this results in three URBs per full transfer, 32 USB packets each +// if there are ZLP issues this should make them show up easily too +#define USB_MTU (3 * 16384) + +#define USB_PACKET_SIZE 512 + +#define VID_APPLE 0x5ac +#define PID_RANGE_LOW 0x1290 +#define PID_RANGE_MAX 0x12af +#define PID_APPLE_T2_COPROCESSOR 0x8600 +#define PID_APPLE_SILICON_RESTORE_LOW 0x1901 +#define PID_APPLE_SILICON_RESTORE_MAX 0x1905 + +#define ENV_DEVICE_MODE "USBMUXD_DEFAULT_DEVICE_MODE" +#define APPLE_VEND_SPECIFIC_GET_MODE 0x45 +#define APPLE_VEND_SPECIFIC_SET_MODE 0x52 + +struct usb_device; + +int usb_init(void); +void usb_shutdown(void); +const char *usb_get_serial(struct usb_device *dev); +uint32_t usb_get_location(struct usb_device *dev); +uint16_t usb_get_pid(struct usb_device *dev); +uint64_t usb_get_speed(struct usb_device *dev); +void usb_get_fds(struct fdlist *list); +int usb_get_timeout(void); +int usb_send(struct usb_device *dev, const unsigned char *buf, int length); +int usb_discover(void); +void usb_autodiscover(int enable); +int usb_process(void); +int usb_process_timeout(int msec); + +#endif diff --git a/src/usbmuxd-proto.h b/src/usbmuxd-proto.h new file mode 100644 index 0000000..93df00e --- /dev/null +++ b/src/usbmuxd-proto.h @@ -0,0 +1,95 @@ +/* + * usbmuxd-proto.h + * + * Copyright (C) 2009 Paul Sladen <libiphone@paul.sladen.org> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 or version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* Protocol definition for usbmuxd proxy protocol */ +#ifndef USBMUXD_PROTO_H +#define USBMUXD_PROTO_H + +#include <stdint.h> +#define USBMUXD_PROTOCOL_VERSION 0 + +#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 */ diff --git a/src/utils.c b/src/utils.c new file mode 100644 index 0000000..2cc5675 --- /dev/null +++ b/src/utils.c @@ -0,0 +1,131 @@ +/* + * utils.c + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * Copyright (c) 2013 Federico Mena Quintero + * + * This library is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the + * License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifdef HAVE_CONFIG_H +#include <config.h> +#endif + +#include <stdlib.h> +#include <string.h> +#include <stdio.h> +#include <stdarg.h> +#include <time.h> +#include <sys/time.h> +#include <errno.h> +#ifdef __APPLE__ +#include <mach/mach_time.h> +#endif + +#include "utils.h" + +#include "log.h" +#define util_error(...) usbmuxd_log(LL_ERROR, __VA_ARGS__) + +void fdlist_create(struct fdlist *list) +{ + list->count = 0; + list->capacity = 4; + list->owners = malloc(sizeof(*list->owners) * list->capacity); + list->fds = malloc(sizeof(*list->fds) * list->capacity); +} +void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events) +{ + if(list->count == list->capacity) { + list->capacity *= 2; + list->owners = realloc(list->owners, sizeof(*list->owners) * list->capacity); + list->fds = realloc(list->fds, sizeof(*list->fds) * list->capacity); + } + list->owners[list->count] = owner; + list->fds[list->count].fd = fd; + list->fds[list->count].events = events; + list->fds[list->count].revents = 0; + list->count++; +} + +void fdlist_free(struct fdlist *list) +{ + list->count = 0; + list->capacity = 0; + free(list->owners); + list->owners = NULL; + free(list->fds); + list->fds = NULL; +} + +void fdlist_reset(struct fdlist *list) +{ + list->count = 0; +} + +#ifndef HAVE_CLOCK_GETTIME +typedef int clockid_t; +#define CLOCK_MONOTONIC 1 + +static int clock_gettime(clockid_t clk_id, struct timespec *ts) +{ + // See http://developer.apple.com/library/mac/qa/qa1398 + + uint64_t mach_time, nano_sec; + + static mach_timebase_info_data_t base_info; + + mach_time = mach_absolute_time(); + + if (base_info.denom == 0) { + (void) mach_timebase_info(&base_info); + } + + if (base_info.numer == 1 && base_info.denom == 1) + nano_sec = mach_time; + else + nano_sec = mach_time * base_info.numer / base_info.denom; + + ts->tv_sec = nano_sec / 1000000000; + ts->tv_nsec = nano_sec % 1000000000; + + return 0; +} +#endif + +void get_tick_count(struct timeval * tv) +{ + struct timespec ts; + if(0 == clock_gettime(CLOCK_MONOTONIC, &ts)) { + tv->tv_sec = ts.tv_sec; + tv->tv_usec = ts.tv_nsec / 1000; + } else { + gettimeofday(tv, NULL); + } +} + +/** + * Get number of milliseconds since the epoch. + */ +uint64_t mstime64(void) +{ + struct timeval tv; + get_tick_count(&tv); + + // Careful, avoid overflow on 32 bit systems + // time_t could be 4 bytes + return ((long long)tv.tv_sec) * 1000LL + ((long long)tv.tv_usec) / 1000LL; +} diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 0000000..ce3b2e0 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,49 @@ +/* + * utils.h + * + * Copyright (C) 2009 Hector Martin <hector@marcansoft.com> + * Copyright (C) 2009 Nikias Bassen <nikias@gmx.li> + * + * This library is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the + * License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef UTILS_H +#define UTILS_H + +#include <poll.h> +#include <plist/plist.h> + +enum fdowner { + FD_LISTEN, + FD_CLIENT, + FD_USB +}; + +struct fdlist { + int count; + int capacity; + enum fdowner *owners; + struct pollfd *fds; +}; + +void fdlist_create(struct fdlist *list); +void fdlist_add(struct fdlist *list, enum fdowner owner, int fd, short events); +void fdlist_free(struct fdlist *list); +void fdlist_reset(struct fdlist *list); + +uint64_t mstime64(void); +void get_tick_count(struct timeval * tv); + +#endif |