diff options
author | Hector Martin | 2009-04-30 05:52:10 +0200 |
---|---|---|
committer | Hector Martin | 2009-04-30 05:52:10 +0200 |
commit | 49a8ef4fcbc8e76ca0f484e6b2d2d9eea70596b6 (patch) | |
tree | d42281bbc3b17af0f92daa5d35429f46bdd2130f | |
parent | 53fb582e7729d5b7ed40ff04d912fcf5add7ce1c (diff) | |
download | usbmuxd-49a8ef4fcbc8e76ca0f484e6b2d2d9eea70596b6.tar.gz usbmuxd-49a8ef4fcbc8e76ca0f484e6b2d2d9eea70596b6.tar.bz2 |
too much stuff and it WORKS
-rw-r--r-- | CMakeLists.txt | 2 | ||||
-rw-r--r-- | client.c | 402 | ||||
-rw-r--r-- | client.h | 69 | ||||
-rw-r--r-- | device.c | 583 | ||||
-rw-r--r-- | device.h | 19 | ||||
-rw-r--r-- | log.c | 2 | ||||
-rw-r--r-- | main.c | 61 | ||||
-rw-r--r-- | usb-linux.c | 197 | ||||
-rw-r--r-- | usb.h | 21 | ||||
-rw-r--r-- | utils.c | 53 | ||||
-rw-r--r-- | utils.h | 22 |
11 files changed, 1301 insertions, 130 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt index cd4a427..e0e4e3f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,7 +10,7 @@ set(LIBS ${LIBS} ${USB_LIBRARIES}) #set(CMAKE_VERBOSE_MAKEFILE ON) -add_definitions(-Wall -O2) +add_definitions(-Wall -O0 -g) add_executable(usbmuxd main.c usb-linux.c log.c utils.c device.c client.c) target_link_libraries(usbmuxd ${LIBS}) @@ -22,7 +22,409 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <config.h> #endif +#include <stdlib.h> +#include <errno.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/socket.h> +#include <sys/un.h> +#include <arpa/inet.h> + #include "log.h" #include "usb.h" #include "client.h" +#include "device.h" + +#define CMD_BUF_SIZE 256 +#define REPLY_BUF_SIZE 1024 + +enum client_state { + CLIENT_COMMAND, // waiting for command + CLIENT_LISTEN, // listening for devices + CLIENT_CONNECTING1, // issued connection request + CLIENT_CONNECTING2, // connection established, but waiting for response message to get sent + CLIENT_CONNECTED, // connected + CLIENT_DEAD +}; + +struct mux_client { + int fd; + unsigned char *ob_buf; + int ob_size; + int ob_capacity; + unsigned char *ib_buf; + int ib_size; + int ib_capacity; + short events, devents; + uint32_t connect_tag; + int connect_device; + enum client_state state; +}; + +static struct collection client_list; + +int client_read(struct mux_client *client, void *buffer, int len) +{ + usbmuxd_log(LL_SPEW, "client_read fd %d buf %p len %d", client->fd, buffer, len); + if(client->state != CLIENT_CONNECTED) { + usbmuxd_log(LL_ERROR, "Attempted to read from client %d not in CONNECTED state", client->fd); + return -1; + } + return recv(client->fd, buffer, len, 0); +} + +int client_write(struct mux_client *client, void *buffer, int len) +{ + usbmuxd_log(LL_SPEW, "client_write fd %d buf %p len %d", client->fd, buffer, len); + if(client->state != CLIENT_CONNECTED) { + usbmuxd_log(LL_ERROR, "Attempted to write to client %d not in CONNECTED state", client->fd); + return -1; + } + return send(client->fd, buffer, len, 0); +} + +int client_set_events(struct mux_client *client, short events) +{ + if((client->state != CLIENT_CONNECTED) && (client->state != CLIENT_CONNECTING2)) { + usbmuxd_log(LL_ERROR, "client_set_events to client %d not in CONNECTED state", client->fd); + return -1; + } + client->devents = events; + if(client->state == CLIENT_CONNECTED) + client->events = events; + return 0; +} + +int client_accept(int listenfd) +{ + struct sockaddr_un addr; + int cfd; + socklen_t len = sizeof(struct sockaddr_un); + cfd = accept(listenfd, (struct sockaddr *)&addr, &len); + if (cfd < 0) { + usbmuxd_log(LL_ERROR, "accept() failed (%s)", strerror(errno)); + return cfd; + } + + struct mux_client *client; + client = malloc(sizeof(struct mux_client)); + memset(client, 0, sizeof(struct mux_client)); + + client->fd = cfd; + client->ob_buf = malloc(REPLY_BUF_SIZE); + client->ob_size = 0; + client->ob_capacity = REPLY_BUF_SIZE; + client->ib_buf = malloc(CMD_BUF_SIZE); + client->ib_size = 0; + client->ib_capacity = CMD_BUF_SIZE; + client->state = CLIENT_COMMAND; + client->events = POLLIN; + + collection_add(&client_list, client); + + usbmuxd_log(LL_INFO, "New client on fd %d", client->fd); + return client->fd; +} + +void client_close(struct mux_client *client) +{ + usbmuxd_log(LL_INFO, "Disconnecting client fd %d", client->fd); + if(client->state == CLIENT_CONNECTING1 || client->state == CLIENT_CONNECTING2) { + usbmuxd_log(LL_INFO, "Client died mid-connect, aborting device %d connection", client->connect_device); + client->state = CLIENT_DEAD; + device_abort_connect(client->connect_device, client); + } + close(client->fd); + if(client->ob_buf) + free(client->ob_buf); + if(client->ib_buf) + free(client->ib_buf); + collection_remove(&client_list, client); + free(client); +} + +void client_get_fds(struct fdlist *list) +{ + FOREACH(struct mux_client *client, &client_list) { + fdlist_add(list, FD_CLIENT, client->fd, client->events); + } ENDFOREACH +} + +static int send_pkt(struct mux_client *client, uint32_t tag, enum client_msgtype msg, void *payload, int payload_length) +{ + struct client_header hdr; + hdr.version = CLIENT_PROTOCOL_VERSION; + hdr.length = sizeof(hdr) + payload_length; + hdr.message = msg; + hdr.tag = tag; + usbmuxd_log(LL_DEBUG, "send_pkt fd %d tag %d msg %d payload_length %d", client->fd, tag, msg, payload_length); + if((client->ob_capacity - client->ob_size) < hdr.length) { + usbmuxd_log(LL_ERROR, "Client %d output buffer full (%d bytes) while sending message %d (%d bytes)", client->fd, client->ob_capacity, hdr.message, hdr.length); + client_close(client); + return -1; + } + memcpy(client->ob_buf + client->ob_size, &hdr, sizeof(hdr)); + if(payload && payload_length) + memcpy(client->ob_buf + client->ob_size + sizeof(hdr), payload, payload_length); + client->ob_size += hdr.length; + client->events |= POLLOUT; + return hdr.length; +} + +static int send_result(struct mux_client *client, uint32_t tag, uint32_t result) +{ + return send_pkt(client, tag, MESSAGE_RESULT, &result, sizeof(uint32_t)); +} + +int client_notify_connect(struct mux_client *client, enum client_result result) +{ + usbmuxd_log(LL_SPEW, "client_notify_connect fd %d result %d", client->fd, result); + if(client->state == CLIENT_DEAD) + return -1; + if(client->state != CLIENT_CONNECTING1) { + usbmuxd_log(LL_ERROR, "client_notify_connect when client %d is not in CONNECTING1 state", client->fd); + return -1; + } + if(send_result(client, client->connect_tag, result) < 0) + return -1; + if(result == RESULT_OK) { + client->state = CLIENT_CONNECTING2; + client->events = POLLOUT; // wait for the result packet to go through + // no longer need this + free(client->ib_buf); + client->ib_buf = NULL; + } else { + client->state = CLIENT_COMMAND; + } + return 0; +} + +static int notify_device(struct mux_client *client, struct device_info *dev) +{ + struct client_msg_dev dmsg; + memset(&dmsg, 0, sizeof(dmsg)); + dmsg.device_id = dev->id; + strncpy(dmsg.device_serial, dev->serial, 256); + dmsg.device_serial[255] = 0; + dmsg.location = dev->location; + dmsg.device_pid = dev->pid; + return send_pkt(client, 0, MESSAGE_DEVICE_ADD, &dmsg, sizeof(dmsg)); +} + +static int start_listen(struct mux_client *client) +{ + struct device_info *devs; + struct device_info *dev; + int count, i; + + client->state = CLIENT_LISTEN; + count = device_get_count(); + if(!count) + return 0; + devs = malloc(sizeof(struct device_info) * count); + count = device_get_list(devs); + + // going to need a larger buffer for many devices + int needed_buffer = count * (sizeof(struct client_msg_dev) + sizeof(struct client_header)) + REPLY_BUF_SIZE; + if(client->ob_capacity < needed_buffer) { + usbmuxd_log(LL_DEBUG, "Enlarging client %d reply buffer %d -> %d to make space for device notifications", client->fd, client->ob_capacity, needed_buffer); + client->ob_buf = realloc(client->ob_buf, needed_buffer); + client->ob_capacity = needed_buffer; + } + dev = devs; + for(i=0; i<count; i++) { + if(notify_device(client, dev++) < 0) { + free(devs); + return -1; + } + } + free(devs); + return count; +} + +static int client_command(struct mux_client *client, struct client_header *hdr, const char *payload) +{ + int res; + usbmuxd_log(LL_DEBUG, "Client command in fd %d len %d ver %d msg %d tag %d", client->fd, hdr->length, hdr->version, hdr->message, hdr->tag); + + if(client->state != CLIENT_COMMAND) { + usbmuxd_log(LL_ERROR, "Client %d command received in the wrong state", client->fd); + if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) + return -1; + client_close(client); + return -1; + } + + struct client_msg_connect *ch; + switch(hdr->message) { + case MESSAGE_LISTEN: + if(send_result(client, hdr->tag, 0) < 0) + return -1; + usbmuxd_log(LL_DEBUG, "Client %d now LISTENING", client->fd); + return start_listen(client); + case MESSAGE_CONNECT: + ch = (void*)payload; + usbmuxd_log(LL_DEBUG, "Client %d connection request to device %d port %d", client->fd, ch->device_id, ntohs(ch->port)); + res = device_start_connect(ch->device_id, ntohs(ch->port), client); + if(res < 0) { + if(send_result(client, hdr->tag, -res) < 0) + return -1; + } else { + client->connect_tag = hdr->tag; + client->connect_device = ch->device_id; + client->state = CLIENT_CONNECTING1; + } + return 0; + default: + usbmuxd_log(LL_ERROR, "Client %d invalid command %d", client->fd, hdr->message); + if(send_result(client, hdr->tag, RESULT_BADCOMMAND) < 0) + return -1; + return 0; + } + return -1; +} + +static void process_send(struct mux_client *client) +{ + int res; + if(!client->ob_size) { + usbmuxd_log(LL_WARNING, "Client %d OUT process but nothing to send?", client->fd); + client->events &= ~POLLOUT; + return; + } + res = send(client->fd, client->ob_buf, client->ob_size, 0); + if(res <= 0) { + usbmuxd_log(LL_ERROR, "Send to client fd %d failed: %d %s", client->fd, res, strerror(errno)); + client_close(client); + return; + } + if(res == client->ob_size) { + client->ob_size = 0; + client->events &= ~POLLOUT; + if(client->state == CLIENT_CONNECTING2) { + usbmuxd_log(LL_DEBUG, "Client %d switching to CONNECTED state", client->fd); + client->state = CLIENT_CONNECTED; + client->events = client->devents; + // no longer need this + free(client->ob_buf); + client->ob_buf = NULL; + } + } else { + client->ob_size -= res; + memmove(client->ob_buf, client->ob_buf + res, client->ob_size); + } +} +static void process_recv(struct mux_client *client) +{ + int res; + int did_read = 0; + if(client->ib_size < sizeof(struct client_header)) { + res = recv(client->fd, client->ib_buf + client->ib_size, sizeof(struct client_header) - client->ib_size, 0); + if(res <= 0) { + if(res < 0) + usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno)); + else + usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd); + client_close(client); + return; + } + client->ib_size += res; + if(client->ib_size < sizeof(struct client_header)) + return; + did_read = 1; + } + struct client_header *hdr = (void*)client->ib_buf; + if(hdr->version != CLIENT_PROTOCOL_VERSION) { + usbmuxd_log(LL_INFO, "Client %d version mismatch: expected %d, got %d", client->fd, CLIENT_PROTOCOL_VERSION, hdr->version); + client_close(client); + } + if(hdr->length > client->ib_capacity) { + usbmuxd_log(LL_INFO, "Client %d message is too long (%d bytes)", client->fd, hdr->length); + client_close(client); + } + if(hdr->length < sizeof(struct client_header)) { + usbmuxd_log(LL_ERROR, "Client %d message is too short (%d bytes)", client->fd, hdr->length); + client_close(client); + } + if(client->ib_size < hdr->length) { + if(did_read) + return; //maybe we would block, so defer to next loop + res = recv(client->fd, client->ib_buf + client->ib_size, hdr->length - client->ib_size, 0); + if(res < 0) { + usbmuxd_log(LL_ERROR, "Receive from client fd %d failed: %s", client->fd, strerror(errno)); + client_close(client); + return; + } else if(res == 0) { + usbmuxd_log(LL_INFO, "Client %d connection closed", client->fd); + client_close(client); + return; + } + client->ib_size += res; + if(client->ib_size < hdr->length) + return; + } + client_command(client, hdr, (char *)(hdr+1)); + client->ib_size = 0; +} + +void client_process(int fd, short events) +{ + struct mux_client *client = NULL; + FOREACH(struct mux_client *lc, &client_list) { + if(lc->fd == fd) { + client = lc; + break; + } + } ENDFOREACH + + if(!client) { + usbmuxd_log(LL_ERROR, "client_process: fd %d not found in client list", fd); + return; + } + + if(client->state == CLIENT_CONNECTED) { + usbmuxd_log(LL_SPEW, "client_process in CONNECTED state"); + device_client_process(client->connect_device, client, events); + } else { + if(events & POLLIN) { + process_recv(client); + } else if(events & POLLOUT) { //not both in case client died as part of process_recv + process_send(client); + } + } + +} + +void client_device_add(struct device_info *dev) +{ + usbmuxd_log(LL_DEBUG, "client_device_add: id %d, location 0x%x, serial %s", dev->id, dev->location, dev->serial); + FOREACH(struct mux_client *client, &client_list) { + if(client->state == CLIENT_LISTEN) + notify_device(client, dev); + } ENDFOREACH +} +void client_device_remove(int device_id) +{ + uint32_t id = device_id; + usbmuxd_log(LL_DEBUG, "client_device_remove: id %d", device_id); + FOREACH(struct mux_client *client, &client_list) { + if(client->state == CLIENT_LISTEN) + send_pkt(client, 0, MESSAGE_DEVICE_REMOVE, &id, sizeof(uint32_t)); + } ENDFOREACH +} + + +void client_init(void) +{ + usbmuxd_log(LL_DEBUG, "client_init"); + collection_init(&client_list); +} +void client_shutdown(void) +{ + usbmuxd_log(LL_DEBUG, "client_shutdown"); + FOREACH(struct mux_client *client, &client_list) { + client_close(client); + } ENDFOREACH + collection_free(&client_list); +} @@ -21,7 +21,72 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifndef __CLIENT_H__ #define __CLIENT_H__ -#endif +#include <stdint.h> + +struct device_info; +struct mux_client; + +enum client_result { + RESULT_OK = 0, + RESULT_BADCOMMAND = 1, + RESULT_BADDEV = 2, + RESULT_CONNREFUSED = 3, + // ??? + // ??? + RESULT_BADVERSION = 6, +}; + +enum client_msgtype { + MESSAGE_RESULT = 1, + MESSAGE_CONNECT = 2, + MESSAGE_LISTEN = 3, + MESSAGE_DEVICE_ADD = 4, + MESSAGE_DEVICE_REMOVE = 5, + //??? + //??? + //MESSAGE_PLIST = 8, +}; + +#define CLIENT_PROTOCOL_VERSION 0 + +struct client_header { + uint32_t length; + uint32_t version; + uint32_t message; + uint32_t tag; +}; + +struct client_msg_result { + uint32_t result; +}; -void client_accept(int fd); +struct client_msg_connect { + uint32_t device_id; + uint16_t port; +}; + +struct client_msg_dev { + uint32_t device_id; + uint16_t device_pid; + char device_serial[256]; + uint16_t padding; + uint32_t location; +}; + +int client_read(struct mux_client *client, void *buffer, int len); +int client_write(struct mux_client *client, void *buffer, int len); +int client_set_events(struct mux_client *client, short events); +void client_close(struct mux_client *client); +int client_notify_connect(struct mux_client *client, enum client_result result); + +void client_device_add(struct device_info *dev); +void client_device_remove(int device_id); + +int client_accept(int fd); void client_get_fds(struct fdlist *list); +void client_process(int fd, short events); + +void client_init(void); +void client_shutdown(void); + +#endif @@ -24,25 +24,43 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <config.h> #endif +#include <sys/time.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <stdlib.h> #include <string.h> +#include <stdint.h> +#include <inttypes.h> #include "device.h" +#include "client.h" #include "usb.h" #include "log.h" int next_device_id; +#define DEV_PKTBUF_SIZE 65536 + +#define CONN_INBUF_SIZE 262144 +#define CONN_OUTBUF_SIZE 65536 + +#define ACK_TIMEOUT 60 + enum mux_protocol { MUX_PROTO_VERSION = 0, MUX_PROTO_TCP = IPPROTO_TCP, }; enum mux_dev_state { - MUXDEV_INIT, - MUXDEV_ACTIVE, - MUXDEV_DEAD + 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_DYING, // RST received + CONN_DEAD // being freed; used to prevent infinite recursion between client<->device freeing }; struct mux_header @@ -58,45 +76,67 @@ struct version_header uint32_t padding; }; +struct mux_device; + +#define CONN_ACK_PENDING 1 + +struct mux_connection +{ + struct mux_device *dev; + struct mux_client *client; + enum mux_conn_state state; + uint16_t sport, dport; + uint32_t tx_seq, tx_ack, tx_acked, tx_win; + uint32_t rx_seq, rx_recvd, rx_ack, rx_win; + int max_payload; + int sendable; + int flags; + unsigned char *ib_buf; + int ib_size; + int ib_capacity; + unsigned char *ob_buf; + int ob_capacity; + short events; + uint64_t last_ack_time; +}; + struct mux_device { struct usb_device *usbdev; int id; enum mux_dev_state state; + struct collection connections; + uint16_t next_sport; + unsigned char *pktbuf; + int pktlen; }; -static int num_devs; -static struct mux_device *device_list; +static struct collection device_list; -static int alloc_device(void) +uint64_t mstime64(void) { - int i; - for(i=0; i<num_devs; i++) { - if(!device_list[i].usbdev) - return i; - } - num_devs++; - device_list = realloc(device_list, sizeof(*device_list) * num_devs); - memset(&device_list[num_devs-1], 0, sizeof(*device_list)); - return num_devs - 1; + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * 1000 + tv.tv_usec / 1000; } static int get_next_device_id(void) { - int i; while(1) { - for(i=0; i<num_devs; i++) { - if(device_list[i].usbdev && device_list[i].id == next_device_id) { + int ok = 1; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == next_device_id) { next_device_id++; + ok = 0; break; } - } - if(i >= num_devs) + } ENDFOREACH + if(ok) return next_device_id++; } } -int send_packet(struct mux_device *dev, enum mux_protocol proto, void *header, void *data, int length) +static int send_packet(struct mux_device *dev, enum mux_protocol proto, void *header, const void *data, int length) { unsigned char *buffer; int hdrlen; @@ -135,7 +175,246 @@ int send_packet(struct mux_device *dev, enum mux_protocol proto, void *header, v free(buffer); return res; } - return mhdr->length; + return total; +} + +static uint16_t find_sport(struct mux_device *dev) +{ + if(collection_count(&dev->connections) >= 65535) + return 0; //insanity + + while(1) { + int ok = 1; + FOREACH(struct mux_connection *conn, &dev->connections) { + if(dev->next_sport == conn->sport) { + dev->next_sport++; + ok = 0; + break; + } + } ENDFOREACH + if(ok) + return dev->next_sport++; + } +} + +static int send_tcp(struct mux_connection *conn, uint8_t flags, const unsigned char *data, int length) +{ + struct tcphdr th; + memset(&th, 0, sizeof(th)); + th.th_sport = htons(conn->sport); + th.th_dport = htons(conn->dport); + th.th_seq = htonl(conn->tx_seq); + th.th_ack = htonl(conn->tx_ack); + th.th_flags = flags; + th.th_off = sizeof(th) / 4; + th.th_win = htons(conn->tx_win >> 8); + + usbmuxd_log(LL_DEBUG, "[OUT] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d", + conn->dev->id, conn->sport, conn->dport, conn->tx_seq, conn->tx_ack, flags, conn->tx_win, conn->tx_win >> 8, length); + + int res = send_packet(conn->dev, MUX_PROTO_TCP, &th, data, length); + if(res >= 0) { + conn->tx_acked = conn->tx_ack; + conn->last_ack_time = mstime64(); + conn->flags &= ~CONN_ACK_PENDING; + } + return res; +} + +static void connection_teardown(struct mux_connection *conn) +{ + int res; + if(conn->state == CONN_DEAD) + return; + usbmuxd_log(LL_DEBUG, "connection_teardown dev %d sport %d dport %d", conn->dev->id, conn->sport, conn->dport); + if(conn->dev->state != MUXDEV_DEAD && conn->state != CONN_DYING) { + 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_CONNECTING) { + client_notify_connect(conn->client, RESULT_CONNREFUSED); + } else { + conn->state = CONN_DEAD; + client_close(conn->client); + } + } + if(conn->ib_buf) + free(conn->ib_buf); + if(conn->ob_buf) + free(conn->ob_buf); + collection_remove(&conn->dev->connections, conn); + free(conn); +} + +int device_start_connect(int device_id, uint16_t dport, struct mux_client *client) +{ + struct mux_device *dev = NULL; + FOREACH(struct mux_device *cdev, &device_list) { + if(cdev->id == device_id) { + dev = cdev; + break; + } + } ENDFOREACH + if(!dev) { + usbmuxd_log(LL_WARNING, "Attempted to connect to nonexistent device %d", device_id); + return -RESULT_BADDEV; + } + + uint16_t sport = find_sport(dev); + if(!sport) { + usbmuxd_log(LL_WARNING, "Unable to allocate port for device %d", device_id); + return -RESULT_BADDEV; + } + + struct mux_connection *conn; + conn = malloc(sizeof(struct mux_connection)); + memset(conn, 0, sizeof(struct mux_connection)); + + conn->dev = dev; + conn->client = client; + conn->state = CONN_CONNECTING; + conn->sport = sport; + conn->dport = dport; + conn->tx_seq = 0; + conn->tx_ack = 0; + conn->tx_acked = 0; + conn->tx_win = 131072; + conn->rx_recvd = 0; + conn->flags = 0; + conn->max_payload = USB_MTU - sizeof(struct mux_header) - sizeof(struct tcphdr); + + conn->ob_buf = malloc(CONN_OUTBUF_SIZE); + conn->ob_capacity = CONN_OUTBUF_SIZE; + conn->ib_buf = malloc(CONN_INBUF_SIZE); + conn->ib_capacity = CONN_INBUF_SIZE; + conn->ib_size = 0; + + int res; + + res = send_tcp(conn, TH_SYN, NULL, 0); + if(res < 0) { + usbmuxd_log(LL_ERROR, "Error sending TCP SYN to device %d (%d->%d)", dev->id, sport, dport); + free(conn); + return -RESULT_CONNREFUSED; //bleh + } + collection_add(&dev->connections, conn); + return 0; +} + +static void update_connection(struct mux_connection *conn) +{ + conn->sendable = conn->rx_win - (conn->tx_seq - conn->rx_ack); + + if(conn->sendable > conn->ob_capacity) + conn->sendable = conn->ob_capacity; + if(conn->sendable > conn->max_payload) + conn->sendable = conn->max_payload; + + if(conn->sendable > 0) + conn->events |= POLLIN; + else + conn->events &= ~POLLIN; + + if(conn->ib_size) + conn->events |= POLLOUT; + else + conn->events &= ~POLLOUT; + + if(conn->tx_acked != conn->tx_ack) + conn->flags |= CONN_ACK_PENDING; + else + conn->flags &= ~CONN_ACK_PENDING; + + usbmuxd_log(LL_SPEW, "update_connection: sendable %d, events %d, flags %d", conn->sendable, conn->events, conn->flags); + client_set_events(conn->client, conn->events); +} + +void device_client_process(int device_id, struct mux_client *client, short events) +{ + struct mux_connection *conn = NULL; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == device_id) { + FOREACH(struct mux_connection *lconn, &dev->connections) { + if(lconn->client == client) { + conn = lconn; + break; + } + } ENDFOREACH + break; + } + } ENDFOREACH + + if(!conn) { + usbmuxd_log(LL_WARNING, "Could not find connection for device %d client %p", device_id, client); + return; + } + usbmuxd_log(LL_SPEW, "device_client_process (%d)", events); + + int res; + int size; + if(events & POLLOUT) { + size = client_write(conn->client, conn->ib_buf, conn->ib_size); + if(size <= 0) { + usbmuxd_log(LL_DEBUG, "error writing to client (%d)", size); + connection_teardown(conn); + return; + } + conn->tx_ack += size; + if(size == conn->ib_size) { + conn->ib_size = 0; + } else { + conn->ib_size -= size; + memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size); + } + } + if(events & POLLIN) { + size = client_read(conn->client, conn->ob_buf, conn->sendable); + if(size <= 0) { + usbmuxd_log(LL_DEBUG, "error reading from client (%d)", size); + connection_teardown(conn); + return; + } + res = send_tcp(conn, TH_ACK, conn->ob_buf, size); + if(res < 0) { + connection_teardown(conn); + return; + } + conn->tx_seq += size; + } + + update_connection(conn); +} + +static void connection_device_input(struct mux_connection *conn, unsigned char *payload, int payload_length) +{ + if((conn->ib_size + payload_length) > conn->ib_capacity) { + usbmuxd_log(LL_ERROR, "Input buffer overflow on device %d connection %d->%d (space=%d, payload=%d)", conn->dev->id, conn->sport, conn->dport, conn->ib_capacity-conn->ib_size, payload_length); + connection_teardown(conn); + return; + } + memcpy(conn->ib_buf + conn->ib_size, payload, payload_length); + conn->ib_size += payload_length; + conn->rx_recvd += payload_length; + update_connection(conn); +} + +void device_abort_connect(int device_id, struct mux_client *client) +{ + FOREACH(struct mux_device *dev, &device_list) { + if(dev->id == device_id) { + FOREACH(struct mux_connection *conn, &dev->connections) { + if(conn->client == client) { + connection_teardown(conn); + return; + } + } ENDFOREACH + usbmuxd_log(LL_WARNING, "Attempted to abort for nonexistent connection for device %d", device_id); + return; + } + } ENDFOREACH + usbmuxd_log(LL_WARNING, "Attempted to abort connection for nonexistent device %d", device_id); } static void device_version_input(struct mux_device *dev, struct version_header *vh) @@ -148,33 +427,131 @@ static void device_version_input(struct mux_device *dev, struct version_header * vh->minor = ntohl(vh->minor); if(vh->major != 1 || vh->minor != 0) { usbmuxd_log(LL_ERROR, "Device %d has unknown version %d.%d\n", dev->id, vh->major, vh->minor); + collection_remove(&device_list, dev); + free(dev); return; } usbmuxd_log(LL_NOTICE, "Connected to v%d.%d device %d on location 0x%x with serial number %s", vh->major, vh->minor, dev->id, usb_get_location(dev->usbdev), usb_get_serial(dev->usbdev)); + dev->state = MUXDEV_ACTIVE; + collection_init(&dev->connections); + struct device_info info; + info.id = dev->id; + info.location = usb_get_location(dev->usbdev); + info.serial = usb_get_serial(dev->usbdev); + info.pid = usb_get_pid(dev->usbdev); + client_device_add(&info); } static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned char *payload, int payload_length) { - + usbmuxd_log(LL_DEBUG, "[IN] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d", + dev->id, ntohs(th->th_sport), ntohs(th->th_dport), ntohl(th->th_seq), ntohl(th->th_ack), th->th_flags, ntohs(th->th_win) << 8, ntohs(th->th_win), payload_length); + + uint16_t sport = ntohs(th->th_dport); + uint16_t dport = ntohs(th->th_sport); + struct mux_connection *conn = NULL; + FOREACH(struct mux_connection *lconn, &dev->connections) { + if(lconn->sport == sport && lconn->dport == dport) { + conn = lconn; + break; + } + } ENDFOREACH + + if(!conn) { + usbmuxd_log(LL_WARNING, "No connection for device %d incoming packet %d->%d", dev->id, dport, sport); + return; + } + + conn->rx_seq = ntohl(th->th_seq); + conn->rx_ack = ntohl(th->th_ack); + conn->rx_win = ntohs(th->th_win) << 8; + + if(th->th_flags & TH_RST) { + char *buf = malloc(payload_length+1); + memcpy(buf, payload, payload_length); + if(payload_length && (buf[payload_length-1] == '\n')) + buf[payload_length-1] = 0; + buf[payload_length] = 0; + usbmuxd_log(LL_DEBUG, "RST reason: %s", buf); + free(buf); + } + + if(conn->state == CONN_CONNECTING) { + if(th->th_flags != (TH_SYN|TH_ACK)) { + if(th->th_flags & TH_RST) + conn->state = CONN_DYING; + usbmuxd_log(LL_INFO, "Connection refused by device %d (%d->%d)", dev->id, sport, dport); + connection_teardown(conn); //this also sends the notification to the client + } else { + conn->tx_seq++; + conn->tx_ack++; + conn->rx_recvd = conn->rx_seq; + if(send_tcp(conn, TH_ACK, NULL, 0) < 0) { + usbmuxd_log(LL_ERROR, "Error sending TCP ACK to device %d (%d->%d)", dev->id, sport, dport); + connection_teardown(conn); + return; + } + conn->state = CONN_CONNECTED; + if(client_notify_connect(conn->client, RESULT_OK) < 0) { + conn->client = NULL; + connection_teardown(conn); + } + update_connection(conn); + } + } else if(conn->state == CONN_CONNECTED) { + if(th->th_flags != TH_ACK) { + usbmuxd_log(LL_INFO, "Connection reset by device %d (%d->%d)", dev->id, sport, dport); + if(th->th_flags & TH_RST) + conn->state = CONN_DYING; + connection_teardown(conn); + } else { + connection_device_input(conn, payload, payload_length); + } + } } - void device_data_input(struct usb_device *usbdev, unsigned char *buffer, int length) { - int i; - struct mux_device *dev; - for(i=0; i<num_devs; i++) { - if(device_list[i].usbdev == usbdev) { - dev = &device_list[i]; + struct mux_device *dev = NULL; + FOREACH(struct mux_device *tdev, &device_list) { + if(tdev->usbdev == usbdev) { + dev = tdev; break; } - } - if(i >= num_devs) { + } ENDFOREACH + if(!dev) { usbmuxd_log(LL_WARNING, "Cannot find device entry for RX input from USB device %p on location 0x%x", usbdev, usb_get_location(usbdev)); return; } + if(!length) + return; + usbmuxd_log(LL_SPEW, "Mux data input for device %p: %p len %d", dev, buffer, length); + + // handle broken up transfers + if(dev->pktlen) { + memcpy(dev->pktbuf + dev->pktlen, buffer, length); + struct mux_header *mhdr = (struct mux_header *)dev->pktbuf; + if((length < USB_MRU) || (ntohl(mhdr->length) == length)) { + buffer = dev->pktbuf; + length += dev->pktlen; + dev->pktlen = 0; + usbmuxd_log(LL_SPEW, "Gathered mux data from buffer (total size: %d)", length); + } else { + dev->pktlen += length; + usbmuxd_log(LL_SPEW, "Appended mux data to buffer (total size: %d)", dev->pktlen); + return; + } + } else { + struct mux_header *mhdr = (struct mux_header *)buffer; + if((length == USB_MRU) && (length < ntohl(mhdr->length))) { + memcpy(dev->pktbuf, buffer, length); + dev->pktlen = length; + usbmuxd_log(LL_SPEW, "Copied mux data to buffer (size: %d)", dev->pktlen); + return; + } + } struct mux_header *mhdr = (struct mux_header *)buffer; @@ -204,56 +581,150 @@ void device_data_input(struct usb_device *usbdev, unsigned char *buffer, int len } -int device_add(struct usb_device *dev) +int device_add(struct usb_device *usbdev) { int res; int id = get_next_device_id(); - int idx = alloc_device(); - usbmuxd_log(LL_NOTICE, "Connecting to new device on location 0x%x as ID %d", usb_get_location(dev), id); - device_list[idx].id = id; - device_list[idx].usbdev = dev; - device_list[idx].state = MUXDEV_INIT; + struct mux_device *dev; + usbmuxd_log(LL_NOTICE, "Connecting to new device on location 0x%x as ID %d", usb_get_location(usbdev), id); + dev = malloc(sizeof(struct mux_device)); + dev->id = id; + dev->usbdev = usbdev; + dev->state = MUXDEV_INIT; + dev->next_sport = 1; + dev->pktbuf = malloc(DEV_PKTBUF_SIZE); + dev->pktlen = 0; struct version_header vh; vh.major = htonl(1); vh.minor = htonl(0); vh.padding = 0; - if((res = send_packet(&device_list[idx], MUX_PROTO_VERSION, &vh, NULL, 0)) < 0) { + if((res = send_packet(dev, MUX_PROTO_VERSION, &vh, NULL, 0)) < 0) { usbmuxd_log(LL_ERROR, "Error sending version request packet to device %d\n", id); - device_list[idx].usbdev = NULL; - device_list[idx].state = MUXDEV_DEAD; + free(dev); return res; } + collection_add(&device_list, dev); return 0; } -void device_remove(struct usb_device *dev) +void device_remove(struct usb_device *usbdev) { - int i; - for(i=0; i<num_devs; i++) { - if(device_list[i].usbdev == dev) { - usbmuxd_log(LL_NOTICE, "Removed device %d on location 0x%x", device_list[i].id, usb_get_location(dev)); - device_list[i].usbdev = NULL; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->usbdev == usbdev) { + usbmuxd_log(LL_NOTICE, "Removed device %d on location 0x%x", dev->id, usb_get_location(usbdev)); + if(dev->state == MUXDEV_ACTIVE) { + dev->state = MUXDEV_DEAD; + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + client_device_remove(dev->id); + collection_free(&dev->connections); + } + collection_remove(&device_list, dev); + free(dev->pktbuf); + free(dev); return; } - } - usbmuxd_log(LL_WARNING, "Cannot find device entry while removing USB device %p on location 0x%x", dev, usb_get_location(dev)); + } ENDFOREACH + usbmuxd_log(LL_WARNING, "Cannot find device entry while removing USB device %p on location 0x%x", usbdev, usb_get_location(usbdev)); +} + +int device_get_count(void) +{ + int count = 0; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) + count++; + } ENDFOREACH + return count; +} + +int device_get_list(struct device_info *p) +{ + int count = 0; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) { + p->id = dev->id; + p->serial = usb_get_serial(dev->usbdev); + p->location = usb_get_location(dev->usbdev); + p->pid = usb_get_pid(dev->usbdev); + count++; + p++; + } + } ENDFOREACH + return count; +} + +int device_get_timeout(void) +{ + uint64_t oldest = (uint64_t)-1; + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) { + FOREACH(struct mux_connection *conn, &dev->connections) { + if((conn->state == CONN_CONNECTED) && (conn->flags & CONN_ACK_PENDING) && conn->last_ack_time < oldest) + oldest = conn->last_ack_time; + } ENDFOREACH + } + } ENDFOREACH + uint64_t ct = mstime64(); + if(oldest == -1) + return 100000; //meh + if((ct - oldest) > ACK_TIMEOUT) + return 0; + return ACK_TIMEOUT - (ct - oldest); +} + +void device_check_timeouts(void) +{ + uint64_t ct = mstime64(); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state == MUXDEV_ACTIVE) { + FOREACH(struct mux_connection *conn, &dev->connections) { + if((conn->state == CONN_CONNECTED) && + (conn->flags & CONN_ACK_PENDING) && + (ct - conn->last_ack_time) > ACK_TIMEOUT) { + usbmuxd_log(LL_DEBUG, "Sending ACK due to expired timeout (%" PRIu64 " -> %" PRIu64 ")", conn->last_ack_time, ct); + if(send_tcp(conn, TH_ACK, NULL, 0) < 0) { + usbmuxd_log(LL_ERROR, "Error sending TCP ACK to device %d (%d->%d)", dev->id, conn->sport, conn->dport); + connection_teardown(conn); + } + } + } ENDFOREACH + } + } ENDFOREACH } void device_init(void) { usbmuxd_log(LL_DEBUG, "device_init"); - num_devs = 1; - device_list = malloc(sizeof(*device_list) * num_devs); - memset(device_list, 0, sizeof(*device_list) * num_devs); + collection_init(&device_list); next_device_id = 1; } +void device_kill_connections(void) +{ + usbmuxd_log(LL_DEBUG, "device_kill_connections"); + FOREACH(struct mux_device *dev, &device_list) { + if(dev->state != MUXDEV_INIT) { + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + } + } ENDFOREACH + // give USB a while to send the final connection RSTs and the like + usb_process_timeout(100); +} + void device_shutdown(void) { - int i; usbmuxd_log(LL_DEBUG, "device_shutdown"); - for(i=0; i<num_devs; i++) - device_remove(device_list[i].usbdev); - free(device_list); - device_list = NULL; + FOREACH(struct mux_device *dev, &device_list) { + FOREACH(struct mux_connection *conn, &dev->connections) { + connection_teardown(conn); + } ENDFOREACH + collection_free(&dev->connections); + collection_remove(&device_list, dev); + free(dev); + } ENDFOREACH + collection_free(&device_list); } @@ -22,12 +22,31 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #define __DEVICE_H__ #include "usb.h" +#include "client.h" + +struct device_info { + int id; + const char *serial; + uint32_t location; + uint16_t pid; +}; void device_data_input(struct usb_device *dev, unsigned char *buf, int length); int device_add(struct usb_device *dev); void device_remove(struct usb_device *dev); +int device_start_connect(int device_id, uint16_t port, struct mux_client *client); +void device_client_process(int device_id, struct mux_client *client, short events); +void device_abort_connect(int device_id, struct mux_client *client); + +int device_get_count(void); +int device_get_list(struct device_info *p); + +int device_get_timeout(void); +void device_check_timeouts(void); + void device_init(void); +void device_kill_connections(void); void device_shutdown(void); #endif @@ -31,7 +31,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "log.h" -int log_level = LL_SPEW; +int log_level = LL_INFO; void usbmuxd_log(enum loglevel level, const char *fmt, ...) { @@ -28,6 +28,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <errno.h> #include <string.h> #include <stdlib.h> +#include <signal.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> @@ -35,8 +36,12 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "log.h" #include "usb.h" #include "device.h" +#include "client.h" static const char *socket_path = "/tmp/usbmuxd"; //TODO: CHANGEME +int should_exit; + +struct sigaction sa_old; int create_socket(void) { struct sockaddr_un bind_addr; @@ -70,29 +75,61 @@ int create_socket(void) { return listenfd; } +void handle_signal(int sig) +{ + if(sig == SIGINT) { + usbmuxd_log(LL_NOTICE,"Caught SIGINT"); + } else { + usbmuxd_log(LL_NOTICE,"Caught unknown signal %d", sig); + } + should_exit = 1; + sigaction(SIGINT, &sa_old, NULL); +} + +void set_signal_handlers(void) +{ + struct sigaction sa; + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_handler = handle_signal; + sigaction(SIGINT, &sa, &sa_old); +} + int main_loop(int listenfd) { - int to, cnt, i; + int to, cnt, i, dto; struct fdlist pollfds; - while(1) { + while(!should_exit) { usbmuxd_log(LL_FLOOD, "main_loop iteration"); to = usb_get_timeout(); usbmuxd_log(LL_FLOOD, "USB timeout is %d ms", to); + dto = device_get_timeout(); + usbmuxd_log(LL_FLOOD, "Device timeout is %d ms", to); + if(dto < to) + to = dto; fdlist_create(&pollfds); fdlist_add(&pollfds, FD_LISTEN, listenfd, POLLIN); usb_get_fds(&pollfds); + client_get_fds(&pollfds); usbmuxd_log(LL_FLOOD, "fd count is %d", pollfds.count); cnt = poll(pollfds.fds, pollfds.count, to); usbmuxd_log(LL_FLOOD, "poll() returned %d", cnt); - if(cnt == 0) { + if(cnt == -1) { + if(errno == EINTR && should_exit) { + usbmuxd_log(LL_INFO, "event processing interrupted"); + fdlist_free(&pollfds); + return 0; + } + } else if(cnt == 0) { if(usb_process() < 0) { usbmuxd_log(LL_FATAL, "usb_process() failed"); + fdlist_free(&pollfds); return -1; } + device_check_timeouts(); } else { int done_usb = 0; for(i=0; i<pollfds.count; i++) { @@ -100,15 +137,27 @@ int main_loop(int listenfd) if(!done_usb && pollfds.owners[i] == FD_USB) { if(usb_process() < 0) { usbmuxd_log(LL_FATAL, "usb_process() failed"); + fdlist_free(&pollfds); return -1; } done_usb = 1; } + if(pollfds.owners[i] == FD_LISTEN) { + if(client_accept(listenfd) < 0) { + usbmuxd_log(LL_FATAL, "client_accept() failed"); + fdlist_free(&pollfds); + return -1; + } + } + if(pollfds.owners[i] == FD_CLIENT) { + client_process(pollfds.fds[i].fd, pollfds.fds[i].revents); + } } } } fdlist_free(&pollfds); } + return 0; } int main(int argc, char *argv[]) @@ -117,12 +166,16 @@ int main(int argc, char *argv[]) int res; usbmuxd_log(LL_NOTICE, "usbmux v0.1 starting up"); + should_exit = 0; + + set_signal_handlers(); usbmuxd_log(LL_INFO, "Creating socket"); listenfd = create_socket(); if(listenfd < 0) return 1; + client_init(); device_init(); usbmuxd_log(LL_INFO, "Initializing USB"); if((res = usb_init()) < 0) @@ -136,8 +189,10 @@ int main(int argc, char *argv[]) usbmuxd_log(LL_FATAL, "main_loop failed"); usbmuxd_log(LL_NOTICE, "usbmux shutting down"); + device_kill_connections(); usb_shutdown(); device_shutdown(); + client_shutdown(); usbmuxd_log(LL_NOTICE, "Shutdown complete"); if(res < 0) diff --git a/usb-linux.c b/usb-linux.c index 27a7bb1..3a87ba6 100644 --- a/usb-linux.c +++ b/usb-linux.c @@ -40,48 +40,50 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA struct usb_device { libusb_device_handle *dev; uint8_t bus, address; + uint16_t vid, pid; char serial[256]; int alive; struct libusb_transfer *rx_xfer; + struct collection tx_xfers; }; -static int num_devs; -static struct usb_device *device_list; +static struct collection device_list; static struct timeval next_dev_poll_time; -static int alloc_device(void) -{ - int i; - for(i=0; i<num_devs; i++) { - if(!device_list[i].dev) - return i; - } - num_devs++; - device_list = realloc(device_list, sizeof(*device_list) * num_devs); - memset(&device_list[num_devs-1], 0, sizeof(*device_list)); - return num_devs - 1; -} - static void usb_disconnect(struct usb_device *dev) { if(!dev->dev) { return; } + + // kill the rx xfer and tx xfers and try to make sure the callbacks get called before we free the device if(dev->rx_xfer) { - // kill the rx xfer and try to make sure the rx callback gets called before we free the device + usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling RX xfer"); + libusb_cancel_transfer(dev->rx_xfer); + } + FOREACH(struct libusb_transfer *xfer, &dev->tx_xfers) { + usbmuxd_log(LL_DEBUG, "usb_disconnect: cancelling TX xfer %p", xfer); + libusb_cancel_transfer(xfer); + } ENDFOREACH + + while(dev->rx_xfer || collection_count(&dev->tx_xfers)) { struct timeval tv; int res; - // TODO: BUG: outstanding TX xfers are not listed but we need to free them - libusb_cancel_transfer(dev->rx_xfer); - tv.tv_sec = tv.tv_usec = 0; + + 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 device removal failed: %d", res); + usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout for usb_disconnect failed: %d", res); + break; } } + collection_free(&dev->tx_xfers); libusb_release_interface(dev->dev, USB_INTERFACE); libusb_close(dev->dev); dev->dev = NULL; + collection_remove(&device_list, dev); + free(dev); } static void tx_callback(struct libusb_transfer *xfer) @@ -117,7 +119,9 @@ static void tx_callback(struct libusb_transfer *xfer) // we'll do device_remove there too dev->alive = 0; } - free(xfer->buffer); + if(xfer->buffer) + free(xfer->buffer); + collection_remove(&dev->tx_xfers, xfer); libusb_free_transfer(xfer); } @@ -132,6 +136,21 @@ int usb_send(struct usb_device *dev, const unsigned char *buf, int length) libusb_free_transfer(xfer); return res; } + collection_add(&dev->tx_xfers, xfer);/* + if((length % 512) == 0) { + usbmuxd_log(LL_DEBUG, "Send ZLP"); + // Send Zero Length Packet + xfer = libusb_alloc_transfer(0); + void *buffer = malloc(1); + libusb_fill_bulk_transfer(xfer, dev->dev, BULK_OUT, buffer, 0, tx_callback, dev, 0); + xfer->flags = LIBUSB_TRANSFER_SHORT_NOT_OK; + if((res = libusb_submit_transfer(xfer)) < 0) { + usbmuxd_log(LL_ERROR, "Failed to submit TX ZLP transfer to device %d-%d: %d", dev->bus, dev->address, res); + libusb_free_transfer(xfer); + return res; + } + collection_add(&dev->tx_xfers, xfer); + }*/ return 0; } @@ -181,8 +200,8 @@ static int start_rx(struct usb_device *dev) int res; void *buf; dev->rx_xfer = libusb_alloc_transfer(0); - buf = malloc(USB_MTU); - libusb_fill_bulk_transfer(dev->rx_xfer, dev->dev, BULK_IN, buf, USB_MTU, rx_callback, dev, 0); + buf = malloc(USB_MRU); + libusb_fill_bulk_transfer(dev->rx_xfer, dev->dev, BULK_IN, buf, USB_MRU, rx_callback, dev, 0); if((res = libusb_submit_transfer(dev->rx_xfer)) != 0) { usbmuxd_log(LL_ERROR, "Failed to submit RX transfer to device %d-%d: %d", dev->bus, dev->address, res); libusb_free_transfer(dev->rx_xfer); @@ -194,7 +213,7 @@ static int start_rx(struct usb_device *dev) static int usb_discover(void) { - int cnt, i, j, res; + int cnt, i, res; int valid_count = 0; libusb_device **devs; @@ -206,23 +225,26 @@ static int usb_discover(void) usbmuxd_log(LL_SPEW, "usb_discover: scanning %d devices", cnt); - for(j=0; j<num_devs; j++) { - device_list[j].alive = 0; - } + FOREACH(struct usb_device *usbdev, &device_list) { + usbdev->alive = 0; + } ENDFOREACH + for(i=0; i<cnt; i++) { // the following are non-blocking operations on the device list libusb_device *dev = devs[i]; uint8_t bus = libusb_get_bus_number(dev); uint8_t address = libusb_get_device_address(dev); struct libusb_device_descriptor devdesc; - for(j=0; j<num_devs; j++) { - if(device_list[j].dev && device_list[j].bus == bus && device_list[j].address == address) { + int found = 0; + FOREACH(struct usb_device *usbdev, &device_list) { + if(usbdev->bus == bus && usbdev->address == address) { valid_count++; - device_list[j].alive = 1; + usbdev->alive = 1; + found = 1; break; } - } - if(j < num_devs) + } ENDFOREACH + if(found) continue; //device already found if((res = libusb_get_device_descriptor(dev, &devdesc)) != 0) { usbmuxd_log(LL_WARNING, "Could not get device descriptor for device %d-%d: %d", bus, address, res); @@ -251,37 +273,45 @@ static int usb_discover(void) libusb_close(handle); continue; } - int idx = alloc_device(); + struct usb_device *usbdev; + usbdev = malloc(sizeof(struct usb_device)); - if((res = libusb_get_string_descriptor_ascii(handle, devdesc.iSerialNumber, (uint8_t *)device_list[idx].serial, 256)) <= 0) { + if((res = libusb_get_string_descriptor_ascii(handle, devdesc.iSerialNumber, (uint8_t *)usbdev->serial, 256)) <= 0) { usbmuxd_log(LL_WARNING, "Could not get serial number for device %d-%d: %d", bus, address, res); libusb_release_interface(handle, USB_INTERFACE); libusb_close(handle); + free(usbdev); continue; } - device_list[idx].serial[res] = 0; - device_list[idx].bus = bus; - device_list[idx].address = address; - device_list[idx].dev = handle; - device_list[idx].alive = 1; + usbdev->serial[res] = 0; + usbdev->bus = bus; + usbdev->address = address; + usbdev->vid = devdesc.idVendor; + usbdev->pid = devdesc.idProduct; + usbdev->dev = handle; + usbdev->alive = 1; + collection_init(&usbdev->tx_xfers); + + collection_add(&device_list, usbdev); - if(device_add(&device_list[idx]) < 0) { - usb_disconnect(&device_list[j]); + if(device_add(usbdev) < 0) { + usb_disconnect(usbdev); continue; } - if(start_rx(&device_list[idx]) < 0) { - device_remove(&device_list[j]); - usb_disconnect(&device_list[j]); + if(start_rx(usbdev) < 0) { + device_remove(usbdev); + usb_disconnect(usbdev); continue; } valid_count++; } - for(j=0; j<num_devs; j++) { - if(device_list[j].dev && !device_list[j].alive) { - device_remove(&device_list[j]); - usb_disconnect(&device_list[j]); + FOREACH(struct usb_device *usbdev, &device_list) { + if(!usbdev->alive) { + device_remove(usbdev); + usb_disconnect(usbdev); } - } + } ENDFOREACH + libusb_free_device_list(devs, 1); gettimeofday(&next_dev_poll_time, NULL); @@ -300,7 +330,7 @@ const char *usb_get_serial(struct usb_device *dev) return dev->serial; } -int usb_get_location(struct usb_device *dev) +uint32_t usb_get_location(struct usb_device *dev) { if(!dev->dev) { return 0; @@ -308,6 +338,14 @@ int usb_get_location(struct usb_device *dev) return (dev->bus << 16) | dev->address; } +uint16_t usb_get_pid(struct usb_device *dev) +{ + if(!dev->dev) { + return 0; + } + return dev->pid; +} + void usb_get_fds(struct fdlist *list) { const struct libusb_pollfd **usbfds; @@ -360,7 +398,7 @@ int usb_get_timeout(void) int usb_process(void) { - int i, res; + int res; struct timeval tv; tv.tv_sec = tv.tv_usec = 0; res = libusb_handle_events_timeout(NULL, &tv); @@ -369,12 +407,12 @@ int usb_process(void) return res; } // reap devices marked dead due to an RX error - for(i=0; i<num_devs; i++) { - if(device_list[i].dev && !device_list[i].alive) { - device_remove(&device_list[i]); - usb_disconnect(&device_list[i]); + FOREACH(struct usb_device *usbdev, &device_list) { + if(!usbdev->alive) { + device_remove(usbdev); + usb_disconnect(usbdev); } - } + } ENDFOREACH if(dev_poll_remain_ms() <= 0) { res = usb_discover(); @@ -386,6 +424,39 @@ int usb_process(void) return 0; } +int usb_process_timeout(int msec) +{ + int res; + struct timeval tleft, tcur, tfin; + gettimeofday(&tcur, NULL); + tfin.tv_sec = tcur.tv_sec + (msec / 1000); + tfin.tv_usec = tcur.tv_usec + (msec % 1000) * 1000; + tfin.tv_sec += tfin.tv_usec / 1000000; + tfin.tv_usec %= 1000000; + while((tfin.tv_sec > tcur.tv_sec) || ((tfin.tv_sec == tcur.tv_sec) && (tfin.tv_usec > tcur.tv_usec))) { + tleft.tv_sec = tfin.tv_sec - tcur.tv_sec; + tleft.tv_usec = tfin.tv_usec - tcur.tv_usec; + if(tleft.tv_usec < 0) { + tleft.tv_usec += 1000000; + tleft.tv_sec -= 1; + } + res = libusb_handle_events_timeout(NULL, &tleft); + if(res < 0) { + usbmuxd_log(LL_ERROR, "libusb_handle_events_timeout failed: %d", res); + return res; + } + // reap devices marked dead due to an RX error + FOREACH(struct usb_device *usbdev, &device_list) { + if(!usbdev->alive) { + device_remove(usbdev); + usb_disconnect(usbdev); + } + } ENDFOREACH + gettimeofday(&tcur, NULL); + } + return 0; +} + int usb_init(void) { int res; @@ -398,20 +469,18 @@ int usb_init(void) return -1; } - num_devs = 1; - device_list = malloc(sizeof(*device_list) * num_devs); - memset(device_list, 0, sizeof(*device_list) * num_devs); + collection_init(&device_list); return usb_discover(); } void usb_shutdown(void) { - int i; usbmuxd_log(LL_DEBUG, "usb_shutdown"); - for(i=0; i<num_devs; i++) - usb_disconnect(&device_list[i]); - free(device_list); - device_list = NULL; + FOREACH(struct usb_device *usbdev, &device_list) { + device_remove(usbdev); + usb_disconnect(usbdev); + } ENDFOREACH + collection_free(&device_list); libusb_exit(NULL); } @@ -21,12 +21,27 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifndef __USB_H__ #define __USB_H__ +#include <stdint.h> #include "utils.h" #define BULK_IN 0x85 #define BULK_OUT 0x04 -#define USB_MTU 65536 +// libusb fragments packets larger than this (usbfs limitation) +// on input, this creates race conditions and other issues +// I don't think the device uses larger packets +// if it does then we're going to have to implement proper framing... +#define USB_MRU 16384 + +// max transmission packet size +// libusb fragments these too, but doesn't send ZLPs so we're safe +// but maybe we need to send a ZLP ourselves at the end (see usb-linux.h) +// we're using 3 * 16384 to optimize for the fragmentation +// this results in three URBs per full transfer, 32 USB packets each +// if there are ZLP issues this should make them show up too +#define USB_MTU (3 * 16384) + +#define USB_PACKET_SIZE 512 #define VID_APPLE 0x5ac #define PID_IPHONE2G 0x1290 @@ -41,10 +56,12 @@ struct usb_device; int usb_init(void); void usb_shutdown(void); const char *usb_get_serial(struct usb_device *dev); -int usb_get_location(struct usb_device *dev); +uint32_t usb_get_location(struct usb_device *dev); +uint16_t usb_get_pid(struct usb_device *dev); void usb_get_fds(struct fdlist *list); int usb_get_timeout(void); int usb_send(struct usb_device *dev, const unsigned char *buf, int length); int usb_process(void); +int usb_process_timeout(int msec); #endif @@ -23,7 +23,9 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #endif #include <stdlib.h> +#include <string.h> #include "utils.h" +#include "log.h" void fdlist_create(struct fdlist *list) { @@ -55,3 +57,54 @@ void fdlist_free(struct fdlist *list) free(list->fds); list->fds = NULL; } + +void collection_init(struct collection *col) +{ + col->list = malloc(sizeof(void *)); + memset(col->list, 0, sizeof(void *)); + col->capacity = 1; +} + +void collection_free(struct collection *col) +{ + free(col->list); + col->list = NULL; + col->capacity = 0; +} + +void collection_add(struct collection *col, void *element) +{ + int i; + for(i=0; i<col->capacity; i++) { + if(!col->list[i]) { + col->list[i] = element; + return; + } + } + col->list = realloc(col->list, sizeof(void*) * col->capacity * 2); + memset(&col->list[col->capacity], 0, sizeof(void *) * col->capacity); + col->list[col->capacity] = element; + col->capacity *= 2; +} + +void collection_remove(struct collection *col, void *element) +{ + int i; + for(i=0; i<col->capacity; i++) { + if(col->list[i] == element) { + col->list[i] = NULL; + return; + } + } + usbmuxd_log(LL_ERROR, "collection_remove: element %p not present in collection %p (cap %d)", element, col, col->capacity); +} + +int collection_count(struct collection *col) +{ + int i, cnt = 0; + for(i=0; i<col->capacity; i++) { + if(col->list[i]) + cnt++; + } + return cnt; +} @@ -40,6 +40,26 @@ 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); -#define MIN(X, Y) ((X) < (Y) ? (X) : (Y)) +struct collection { + void **list; + int capacity; +}; + +void collection_init(struct collection *col); +void collection_add(struct collection *col, void *element); +void collection_remove(struct collection *col, void *element); +int collection_count(struct collection *col); +void collection_free(struct collection *col); + +#define FOREACH(var, col) \ + do { \ + int _iter; \ + for(_iter=0; _iter<(col)->capacity; _iter++) { \ + if(!(col)->list[_iter]) continue; \ + var = (col)->list[_iter]; + +#define ENDFOREACH \ + } \ + } while(0); #endif |