summaryrefslogtreecommitdiffstats
path: root/src/device.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/device.c')
-rw-r--r--src/device.c1037
1 files changed, 1037 insertions, 0 deletions
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 @@
1/*
2 * device.c
3 *
4 * Copyright (C) 2009 Hector Martin "marcan" <hector@marcansoft.com>
5 * Copyright (C) 2014 Mikkel Kamstrup Erlandsen <mikkel.kamstrup@xamarin.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 or version 3.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#define _DEFAULT_SOURCE
22#define _BSD_SOURCE
23
24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
28#include <sys/time.h>
29#include <netinet/in.h>
30#include <netinet/tcp.h>
31#include <stdlib.h>
32#include <string.h>
33#include <stdint.h>
34#include <inttypes.h>
35#include <unistd.h>
36
37#include <libimobiledevice-glue/collection.h>
38#include <libimobiledevice-glue/thread.h>
39
40#include "device.h"
41#include "client.h"
42#include "preflight.h"
43#include "usb.h"
44#include "log.h"
45
46int next_device_id;
47
48#define DEV_MRU 65536
49
50#define CONN_INBUF_SIZE 262144
51#define CONN_OUTBUF_SIZE 65536
52
53#define ACK_TIMEOUT 30
54
55enum mux_protocol {
56 MUX_PROTO_VERSION = 0,
57 MUX_PROTO_CONTROL = 1,
58 MUX_PROTO_SETUP = 2,
59 MUX_PROTO_TCP = IPPROTO_TCP,
60};
61
62enum mux_dev_state {
63 MUXDEV_INIT, // sent version packet
64 MUXDEV_ACTIVE, // received version packet, active
65 MUXDEV_DEAD // dead
66};
67
68enum mux_conn_state {
69 CONN_CONNECTING, // SYN
70 CONN_CONNECTED, // SYN/SYNACK/ACK -> active
71 CONN_REFUSED, // RST received during SYN
72 CONN_DYING, // RST received
73 CONN_DEAD // being freed; used to prevent infinite recursion between client<->device freeing
74};
75
76struct mux_header
77{
78 uint32_t protocol;
79 uint32_t length;
80 uint32_t magic;
81 uint16_t tx_seq;
82 uint16_t rx_seq;
83};
84
85struct version_header
86{
87 uint32_t major;
88 uint32_t minor;
89 uint32_t padding;
90};
91
92struct mux_device;
93
94#define CONN_ACK_PENDING 1
95
96struct mux_connection
97{
98 struct mux_device *dev;
99 struct mux_client *client;
100 enum mux_conn_state state;
101 uint16_t sport, dport;
102 uint32_t tx_seq, tx_ack, tx_acked, tx_win;
103 uint32_t rx_seq, rx_recvd, rx_ack, rx_win;
104 uint32_t max_payload;
105 uint32_t sendable;
106 int flags;
107 unsigned char *ib_buf;
108 uint32_t ib_size;
109 uint32_t ib_capacity;
110 unsigned char *ob_buf;
111 uint32_t ob_capacity;
112 short events;
113 uint64_t last_ack_time;
114};
115
116struct mux_device
117{
118 struct usb_device *usbdev;
119 int id;
120 enum mux_dev_state state;
121 int visible;
122 struct collection connections;
123 uint16_t next_sport;
124 unsigned char *pktbuf;
125 uint32_t pktlen;
126 void *preflight_cb_data;
127 int version;
128 uint16_t rx_seq;
129 uint16_t tx_seq;
130};
131
132static struct collection device_list;
133mutex_t device_list_mutex;
134
135static struct mux_device* get_mux_device_for_id(int device_id)
136{
137 struct mux_device *dev = NULL;
138 mutex_lock(&device_list_mutex);
139 FOREACH(struct mux_device *cdev, &device_list) {
140 if(cdev->id == device_id) {
141 dev = cdev;
142 break;
143 }
144 } ENDFOREACH
145 mutex_unlock(&device_list_mutex);
146
147 return dev;
148}
149
150static struct mux_connection* get_mux_connection(int device_id, struct mux_client *client)
151{
152 struct mux_connection *conn = NULL;
153 FOREACH(struct mux_device *dev, &device_list) {
154 if(dev->id == device_id) {
155 FOREACH(struct mux_connection *lconn, &dev->connections) {
156 if(lconn->client == client) {
157 conn = lconn;
158 break;
159 }
160 } ENDFOREACH
161 break;
162 }
163 } ENDFOREACH
164
165 return conn;
166}
167
168static int get_next_device_id(void)
169{
170 while(1) {
171 int ok = 1;
172 mutex_lock(&device_list_mutex);
173 FOREACH(struct mux_device *dev, &device_list) {
174 if(dev->id == next_device_id) {
175 next_device_id++;
176 ok = 0;
177 break;
178 }
179 } ENDFOREACH
180 mutex_unlock(&device_list_mutex);
181 if(ok)
182 return next_device_id++;
183 }
184}
185
186static int send_packet(struct mux_device *dev, enum mux_protocol proto, void *header, const void *data, int length)
187{
188 unsigned char *buffer;
189 int hdrlen;
190 int res;
191
192 switch(proto) {
193 case MUX_PROTO_VERSION:
194 hdrlen = sizeof(struct version_header);
195 break;
196 case MUX_PROTO_SETUP:
197 hdrlen = 0;
198 break;
199 case MUX_PROTO_TCP:
200 hdrlen = sizeof(struct tcphdr);
201 break;
202 default:
203 usbmuxd_log(LL_ERROR, "Invalid protocol %d for outgoing packet (dev %d hdr %p data %p len %d)", proto, dev->id, header, data, length);
204 return -1;
205 }
206 usbmuxd_log(LL_SPEW, "send_packet(%d, 0x%x, %p, %p, %d)", dev->id, proto, header, data, length);
207
208 int mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header));
209
210 int total = mux_header_size + hdrlen + length;
211
212 if(total > USB_MTU) {
213 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);
214 return -1;
215 }
216
217 buffer = malloc(total);
218 struct mux_header *mhdr = (struct mux_header *)buffer;
219 mhdr->protocol = htonl(proto);
220 mhdr->length = htonl(total);
221 if (dev->version >= 2) {
222 mhdr->magic = htonl(0xfeedface);
223 if (proto == MUX_PROTO_SETUP) {
224 dev->tx_seq = 0;
225 dev->rx_seq = 0xFFFF;
226 }
227 mhdr->tx_seq = htons(dev->tx_seq);
228 mhdr->rx_seq = htons(dev->rx_seq);
229 dev->tx_seq++;
230 }
231 memcpy(buffer + mux_header_size, header, hdrlen);
232 if(data && length)
233 memcpy(buffer + mux_header_size + hdrlen, data, length);
234
235 if((res = usb_send(dev->usbdev, buffer, total)) < 0) {
236 usbmuxd_log(LL_ERROR, "usb_send failed while sending packet (len %d) to device %d: %d", total, dev->id, res);
237 free(buffer);
238 return res;
239 }
240 return total;
241}
242
243static uint16_t find_sport(struct mux_device *dev)
244{
245 if(collection_count(&dev->connections) >= 65535)
246 return 0; //insanity
247
248 while(1) {
249 int ok = 1;
250 FOREACH(struct mux_connection *conn, &dev->connections) {
251 if(dev->next_sport == conn->sport) {
252 dev->next_sport++;
253 ok = 0;
254 break;
255 }
256 } ENDFOREACH
257 if(ok)
258 return dev->next_sport++;
259 }
260}
261
262static int send_anon_rst(struct mux_device *dev, uint16_t sport, uint16_t dport, uint32_t ack)
263{
264 struct tcphdr th;
265 memset(&th, 0, sizeof(th));
266 th.th_sport = htons(sport);
267 th.th_dport = htons(dport);
268 th.th_ack = htonl(ack);
269 th.th_flags = TH_RST;
270 th.th_off = sizeof(th) / 4;
271
272 usbmuxd_log(LL_DEBUG, "[OUT] dev=%d sport=%d dport=%d flags=0x%x", dev->id, sport, dport, th.th_flags);
273
274 int res = send_packet(dev, MUX_PROTO_TCP, &th, NULL, 0);
275 return res;
276}
277
278static int send_tcp(struct mux_connection *conn, uint8_t flags, const unsigned char *data, int length)
279{
280 struct tcphdr th;
281 memset(&th, 0, sizeof(th));
282 th.th_sport = htons(conn->sport);
283 th.th_dport = htons(conn->dport);
284 th.th_seq = htonl(conn->tx_seq);
285 th.th_ack = htonl(conn->tx_ack);
286 th.th_flags = flags;
287 th.th_off = sizeof(th) / 4;
288 th.th_win = htons(conn->tx_win >> 8);
289
290 usbmuxd_log(LL_DEBUG, "[OUT] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d",
291 conn->dev->id, conn->sport, conn->dport, conn->tx_seq, conn->tx_ack, flags, conn->tx_win, conn->tx_win >> 8, length);
292
293 int res = send_packet(conn->dev, MUX_PROTO_TCP, &th, data, length);
294 if(res >= 0) {
295 conn->tx_acked = conn->tx_ack;
296 conn->last_ack_time = mstime64();
297 conn->flags &= ~CONN_ACK_PENDING;
298 }
299 return res;
300}
301
302static void connection_teardown(struct mux_connection *conn)
303{
304 int res;
305 int size;
306 if(conn->state == CONN_DEAD)
307 return;
308 usbmuxd_log(LL_DEBUG, "connection_teardown dev %d sport %d dport %d", conn->dev->id, conn->sport, conn->dport);
309 if(conn->dev->state != MUXDEV_DEAD && conn->state != CONN_DYING && conn->state != CONN_REFUSED) {
310 res = send_tcp(conn, TH_RST, NULL, 0);
311 if(res < 0)
312 usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", conn->dev->id, conn->sport, conn->dport);
313 }
314 if(conn->client) {
315 if(conn->state == CONN_REFUSED || conn->state == CONN_CONNECTING) {
316 client_notify_connect(conn->client, RESULT_CONNREFUSED);
317 } else {
318 conn->state = CONN_DEAD;
319 if((conn->events & POLLOUT) && conn->ib_size > 0){
320 usbmuxd_log(LL_DEBUG, "%s: flushing buffer to client (%u bytes)", __func__, conn->ib_size);
321 uint64_t tm_last = mstime64();
322 while(1){
323 size = client_write(conn->client, conn->ib_buf, conn->ib_size);
324 if(size < 0) {
325 usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after error.", __func__);
326 break;
327 } else if (size == 0) {
328 uint64_t tm_now = mstime64();
329 if (tm_now - tm_last > 1000) {
330 usbmuxd_log(LL_ERROR, "%s: aborting buffer flush to client after unsuccessfully attempting for %dms.", __func__, (int)(tm_now - tm_last));
331 break;
332 }
333 usleep(10000);
334 continue;
335 }
336 if(size == (int)conn->ib_size) {
337 conn->ib_size = 0;
338 break;
339 } else {
340 conn->ib_size -= size;
341 memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size);
342 }
343 tm_last = mstime64();
344 }
345 }
346 client_close(conn->client);
347 }
348 }
349 free(conn->ib_buf);
350 free(conn->ob_buf);
351 collection_remove(&conn->dev->connections, conn);
352 free(conn);
353}
354
355int device_start_connect(int device_id, uint16_t dport, struct mux_client *client)
356{
357 struct mux_device *dev = get_mux_device_for_id(device_id);
358 if(!dev) {
359 usbmuxd_log(LL_WARNING, "Attempted to connect to nonexistent device %d", device_id);
360 return -RESULT_BADDEV;
361 }
362
363 uint16_t sport = find_sport(dev);
364 if(!sport) {
365 usbmuxd_log(LL_WARNING, "Unable to allocate port for device %d", device_id);
366 return -RESULT_BADDEV;
367 }
368
369 struct mux_connection *conn;
370 conn = malloc(sizeof(struct mux_connection));
371 memset(conn, 0, sizeof(struct mux_connection));
372
373 conn->dev = dev;
374 conn->client = client;
375 conn->state = CONN_CONNECTING;
376 conn->sport = sport;
377 conn->dport = dport;
378 conn->tx_seq = 0;
379 conn->tx_ack = 0;
380 conn->tx_acked = 0;
381 conn->tx_win = 131072;
382 conn->rx_recvd = 0;
383 conn->flags = 0;
384 conn->max_payload = USB_MTU - sizeof(struct mux_header) - sizeof(struct tcphdr);
385
386 conn->ob_buf = malloc(CONN_OUTBUF_SIZE);
387 conn->ob_capacity = CONN_OUTBUF_SIZE;
388 conn->ib_buf = malloc(CONN_INBUF_SIZE);
389 conn->ib_capacity = CONN_INBUF_SIZE;
390 conn->ib_size = 0;
391
392 int res;
393
394 res = send_tcp(conn, TH_SYN, NULL, 0);
395 if(res < 0) {
396 usbmuxd_log(LL_ERROR, "Error sending TCP SYN to device %d (%d->%d)", dev->id, sport, dport);
397 free(conn->ib_buf);
398 free(conn->ob_buf);
399 free(conn);
400 return -RESULT_CONNREFUSED; //bleh
401 }
402 collection_add(&dev->connections, conn);
403 return 0;
404}
405
406/**
407 * Examine the state of a connection's buffers and
408 * update all connection flags and masks accordingly.
409 * Does not do I/O.
410 *
411 * @param conn The connection to update.
412 */
413static void update_connection(struct mux_connection *conn)
414{
415 uint32_t sent = conn->tx_seq - conn->rx_ack;
416
417 if(conn->rx_win > sent)
418 conn->sendable = conn->rx_win - sent;
419 else
420 conn->sendable = 0;
421
422 if(conn->sendable > conn->ob_capacity)
423 conn->sendable = conn->ob_capacity;
424 if(conn->sendable > conn->max_payload)
425 conn->sendable = conn->max_payload;
426
427 if(conn->sendable > 0)
428 conn->events |= POLLIN;
429 else
430 conn->events &= ~POLLIN;
431
432 if(conn->ib_size)
433 conn->events |= POLLOUT;
434 else
435 conn->events &= ~POLLOUT;
436
437 if(conn->tx_acked != conn->tx_ack)
438 conn->flags |= CONN_ACK_PENDING;
439 else
440 conn->flags &= ~CONN_ACK_PENDING;
441
442 usbmuxd_log(LL_SPEW, "update_connection: sendable %d, events %d, flags %d", conn->sendable, conn->events, conn->flags);
443 client_set_events(conn->client, conn->events);
444}
445
446static int send_tcp_ack(struct mux_connection *conn)
447{
448 if(send_tcp(conn, TH_ACK, NULL, 0) < 0) {
449 usbmuxd_log(LL_ERROR, "Error sending TCP ACK (%d->%d)", conn->sport, conn->dport);
450 connection_teardown(conn);
451 return -1;
452 }
453
454 update_connection(conn);
455
456 return 0;
457}
458
459/**
460 * Flush input and output buffers for a client connection.
461 *
462 * @param device_id Numeric id for the device.
463 * @param client The client to flush buffers for.
464 * @param events event mask for the client. POLLOUT means that
465 * the client is ready to receive data, POLLIN that it has
466 * data to be read (and send along to the device).
467 */
468void device_client_process(int device_id, struct mux_client *client, short events)
469{
470 mutex_lock(&device_list_mutex);
471 struct mux_connection *conn = get_mux_connection(device_id, client);
472 mutex_unlock(&device_list_mutex);
473 if(!conn) {
474 usbmuxd_log(LL_WARNING, "Could not find connection for device %d client %p", device_id, client);
475 return;
476 }
477 usbmuxd_log(LL_SPEW, "device_client_process (%d)", events);
478
479 int res;
480 int size;
481 if((events & POLLOUT) && conn->ib_size > 0) {
482 // Client is ready to receive data, send what we have
483 // in the client's connection buffer (if there is any)
484 size = client_write(conn->client, conn->ib_buf, conn->ib_size);
485 if(size <= 0) {
486 usbmuxd_log(LL_DEBUG, "error writing to client (%d)", size);
487 connection_teardown(conn);
488 return;
489 }
490 conn->tx_ack += size;
491 if(size == (int)conn->ib_size) {
492 conn->ib_size = 0;
493 } else {
494 conn->ib_size -= size;
495 memmove(conn->ib_buf, conn->ib_buf + size, conn->ib_size);
496 }
497 }
498 if((events & POLLIN) && conn->sendable > 0) {
499 // There is inbound trafic on the client socket,
500 // convert it to tcp and send to the device
501 // (if the device's input buffer is not full)
502 size = client_read(conn->client, conn->ob_buf, conn->sendable);
503 if(size <= 0) {
504 if (size < 0) {
505 usbmuxd_log(LL_DEBUG, "error reading from client (%d)", size);
506 }
507 connection_teardown(conn);
508 return;
509 }
510 res = send_tcp(conn, TH_ACK, conn->ob_buf, size);
511 if(res < 0) {
512 connection_teardown(conn);
513 return;
514 }
515 conn->tx_seq += size;
516 }
517
518 update_connection(conn);
519}
520
521/**
522 * Copy a payload to a connection's in-buffer and
523 * set the POLLOUT event mask on the connection so
524 * the next main_loop iteration will dispatch the
525 * buffer if the connection socket is writable.
526 *
527 * Connection buffers are flushed in the
528 * device_client_process() function.
529 *
530 * @param conn The connection to add incoming data to.
531 * @param payload Payload to prepare for writing.
532 * The payload will be copied immediately so you are
533 * free to alter or free the payload buffer when this
534 * function returns.
535 * @param payload_length number of bytes to copy from from
536 * the payload.
537 */
538static void connection_device_input(struct mux_connection *conn, unsigned char *payload, uint32_t payload_length)
539{
540 if((conn->ib_size + payload_length) > conn->ib_capacity) {
541 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);
542 connection_teardown(conn);
543 return;
544 }
545 memcpy(conn->ib_buf + conn->ib_size, payload, payload_length);
546 conn->ib_size += payload_length;
547 conn->rx_recvd += payload_length;
548 update_connection(conn);
549}
550
551void device_abort_connect(int device_id, struct mux_client *client)
552{
553 struct mux_connection *conn = get_mux_connection(device_id, client);
554 if (conn) {
555 conn->client = NULL;
556 connection_teardown(conn);
557 } else {
558 usbmuxd_log(LL_WARNING, "Attempted to abort for nonexistent connection for device %d", device_id);
559 }
560}
561
562static void device_version_input(struct mux_device *dev, struct version_header *vh)
563{
564 if(dev->state != MUXDEV_INIT) {
565 usbmuxd_log(LL_WARNING, "Version packet from already initialized device %d", dev->id);
566 return;
567 }
568 vh->major = ntohl(vh->major);
569 vh->minor = ntohl(vh->minor);
570 if(vh->major != 2 && vh->major != 1) {
571 usbmuxd_log(LL_ERROR, "Device %d has unknown version %d.%d", dev->id, vh->major, vh->minor);
572 mutex_lock(&device_list_mutex);
573 collection_remove(&device_list, dev);
574 mutex_unlock(&device_list_mutex);
575 free(dev);
576 return;
577 }
578 dev->version = vh->major;
579
580 if (dev->version >= 2) {
581 send_packet(dev, MUX_PROTO_SETUP, NULL, "\x07", 1);
582 }
583
584 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));
585 dev->state = MUXDEV_ACTIVE;
586 collection_init(&dev->connections);
587 struct device_info info;
588 info.id = dev->id;
589 info.location = usb_get_location(dev->usbdev);
590 info.serial = usb_get_serial(dev->usbdev);
591 info.pid = usb_get_pid(dev->usbdev);
592 info.speed = usb_get_speed(dev->usbdev);
593 preflight_worker_device_add(&info);
594}
595
596static void device_control_input(struct mux_device *dev, unsigned char *payload, uint32_t payload_length)
597{
598 if (payload_length > 0) {
599 switch (payload[0]) {
600 case 3:
601 if (payload_length > 1) {
602 usbmuxd_log(LL_ERROR, "Device %d: ERROR: %.*s", dev->id, payload_length-1, payload+1);
603 } else {
604 usbmuxd_log(LL_ERROR, "%s: Device %d: Got device error payload with empty message", __func__, dev->id);
605 }
606 break;
607 case 5:
608 if (payload_length > 1) {
609 usbmuxd_log(LL_WARNING, "Device %d: WARNING: %.*s", dev->id, payload_length-1, payload+1);
610 } else {
611 usbmuxd_log(LL_WARNING, "%s: Device %d: Got payload type %d with empty message", __func__, dev->id, payload[0]);
612 }
613 break;
614 case 7:
615 if (payload_length > 1) {
616 usbmuxd_log(LL_INFO, "Device %d: %.*s", dev->id, payload_length-1, payload+1);
617 } else {
618 usbmuxd_log(LL_WARNING, "%s: Device %d: Got payload type %d with empty message", __func__, dev->id, payload[0]);
619 }
620 break;
621 default:
622 usbmuxd_log(LL_WARNING, "%s: Device %d: Got unhandled payload type %d: %.*s", __func__, dev->id, payload[0], payload_length-1, payload+1);
623 break;
624 }
625 } else {
626 usbmuxd_log(LL_WARNING, "%s: Got a type 1 packet without payload for device %d", __func__, dev->id);
627 }
628}
629
630/**
631 * Handle an incoming TCP packet from the device.
632 *
633 * @param dev The device handle TCP input on.
634 * @param th Pointer to the TCP header struct.
635 * @param payload Payload data.
636 * @param payload_length Number of bytes in payload.
637 */
638static void device_tcp_input(struct mux_device *dev, struct tcphdr *th, unsigned char *payload, uint32_t payload_length)
639{
640 uint16_t sport = ntohs(th->th_dport);
641 uint16_t dport = ntohs(th->th_sport);
642 struct mux_connection *conn = NULL;
643
644 usbmuxd_log(LL_DEBUG, "[IN] dev=%d sport=%d dport=%d seq=%d ack=%d flags=0x%x window=%d[%d] len=%d",
645 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);
646
647 if(dev->state != MUXDEV_ACTIVE) {
648 usbmuxd_log(LL_ERROR, "Received TCP packet from device %d but the device isn't active yet, discarding", dev->id);
649 return;
650 }
651
652 // Find the connection on this device that has the right sport and dport
653 FOREACH(struct mux_connection *lconn, &dev->connections) {
654 if(lconn->sport == sport && lconn->dport == dport) {
655 conn = lconn;
656 break;
657 }
658 } ENDFOREACH
659
660 if(!conn) {
661 if(!(th->th_flags & TH_RST)) {
662 usbmuxd_log(LL_INFO, "No connection for device %d incoming packet %d->%d", dev->id, dport, sport);
663 if(send_anon_rst(dev, sport, dport, ntohl(th->th_seq)) < 0)
664 usbmuxd_log(LL_ERROR, "Error sending TCP RST to device %d (%d->%d)", dev->id, sport, dport);
665 }
666 return;
667 }
668
669 conn->rx_seq = ntohl(th->th_seq);
670 conn->rx_ack = ntohl(th->th_ack);
671 conn->rx_win = ntohs(th->th_win) << 8;
672
673 if(th->th_flags & TH_RST) {
674 char *buf = malloc(payload_length+1);
675 memcpy(buf, payload, payload_length);
676 if(payload_length && (buf[payload_length-1] == '\n'))
677 buf[payload_length-1] = 0;
678 buf[payload_length] = 0;
679 usbmuxd_log(LL_DEBUG, "RST reason: %s", buf);
680 free(buf);
681 }
682
683 if(conn->state == CONN_CONNECTING) {
684 if(th->th_flags != (TH_SYN|TH_ACK)) {
685 if(th->th_flags & TH_RST)
686 conn->state = CONN_REFUSED;
687 usbmuxd_log(LL_INFO, "Connection refused by device %d (%d->%d)", dev->id, sport, dport);
688 connection_teardown(conn); //this also sends the notification to the client
689 } else {
690 conn->tx_seq++;
691 conn->tx_ack++;
692 conn->rx_recvd = conn->rx_seq;
693 if(send_tcp(conn, TH_ACK, NULL, 0) < 0) {
694 usbmuxd_log(LL_ERROR, "Error sending TCP ACK to device %d (%d->%d)", dev->id, sport, dport);
695 connection_teardown(conn);
696 return;
697 }
698 conn->state = CONN_CONNECTED;
699 usbmuxd_log(LL_INFO, "Client connected to device %d (%d->%d)", dev->id, sport, dport);
700 if(client_notify_connect(conn->client, RESULT_OK) < 0) {
701 conn->client = NULL;
702 connection_teardown(conn);
703 }
704 update_connection(conn);
705 }
706 } else if(conn->state == CONN_CONNECTED) {
707 if(th->th_flags != TH_ACK) {
708 usbmuxd_log(LL_INFO, "Connection reset by device %d (%d->%d)", dev->id, sport, dport);
709 if(th->th_flags & TH_RST)
710 conn->state = CONN_DYING;
711 connection_teardown(conn);
712 } else {
713 connection_device_input(conn, payload, payload_length);
714
715 // Device likes it best when we are prompty ACKing data
716 send_tcp_ack(conn);
717 }
718 }
719}
720
721/**
722 * Take input data from the device that has been read into a buffer
723 * and dispatch it to the right protocol backend (eg. TCP).
724 *
725 * @param usbdev
726 * @param buffer
727 * @param length
728 */
729void device_data_input(struct usb_device *usbdev, unsigned char *buffer, uint32_t length)
730{
731 struct mux_device *dev = NULL;
732 mutex_lock(&device_list_mutex);
733 FOREACH(struct mux_device *tdev, &device_list) {
734 if(tdev->usbdev == usbdev) {
735 dev = tdev;
736 break;
737 }
738 } ENDFOREACH
739 mutex_unlock(&device_list_mutex);
740 if(!dev) {
741 usbmuxd_log(LL_WARNING, "Cannot find device entry for RX input from USB device %p on location 0x%x", usbdev, usb_get_location(usbdev));
742 return;
743 }
744
745 if(!length)
746 return;
747
748 // sanity check (should never happen with current USB implementation)
749 if((length > USB_MRU) || (length > DEV_MRU)) {
750 usbmuxd_log(LL_ERROR, "Too much data received from USB (%d), file a bug", length);
751 return;
752 }
753
754 usbmuxd_log(LL_SPEW, "Mux data input for device %p: %p len %d", dev, buffer, length);
755
756 // handle broken up transfers
757 if(dev->pktlen) {
758 if((length + dev->pktlen) > DEV_MRU) {
759 usbmuxd_log(LL_ERROR, "Incoming split packet is too large (%d so far), dropping!", length + dev->pktlen);
760 dev->pktlen = 0;
761 return;
762 }
763 memcpy(dev->pktbuf + dev->pktlen, buffer, length);
764 struct mux_header *mhdr = (struct mux_header *)dev->pktbuf;
765 if((length < USB_MRU) || (ntohl(mhdr->length) == (length + dev->pktlen))) {
766 buffer = dev->pktbuf;
767 length += dev->pktlen;
768 dev->pktlen = 0;
769 usbmuxd_log(LL_SPEW, "Gathered mux data from buffer (total size: %d)", length);
770 } else {
771 dev->pktlen += length;
772 usbmuxd_log(LL_SPEW, "Appended mux data to buffer (total size: %d)", dev->pktlen);
773 return;
774 }
775 } else {
776 struct mux_header *mhdr = (struct mux_header *)buffer;
777 if((length == USB_MRU) && (length < ntohl(mhdr->length))) {
778 memcpy(dev->pktbuf, buffer, length);
779 dev->pktlen = length;
780 usbmuxd_log(LL_SPEW, "Copied mux data to buffer (size: %d)", dev->pktlen);
781 return;
782 }
783 }
784
785 struct mux_header *mhdr = (struct mux_header *)buffer;
786 int mux_header_size = ((dev->version < 2) ? 8 : sizeof(struct mux_header));
787 if(ntohl(mhdr->length) != length) {
788 usbmuxd_log(LL_ERROR, "Incoming packet size mismatch (dev %d, expected %d, got %d)", dev->id, ntohl(mhdr->length), length);
789 return;
790 }
791
792 struct tcphdr *th;
793 unsigned char *payload;
794 uint32_t payload_length;
795
796 if (dev->version >= 2) {
797 dev->rx_seq = ntohs(mhdr->rx_seq);
798 }
799
800 switch(ntohl(mhdr->protocol)) {
801 case MUX_PROTO_VERSION:
802 if(length < (mux_header_size + sizeof(struct version_header))) {
803 usbmuxd_log(LL_ERROR, "Incoming version packet is too small (%d)", length);
804 return;
805 }
806 device_version_input(dev, (struct version_header *)((char*)mhdr+mux_header_size));
807 break;
808 case MUX_PROTO_CONTROL:
809 payload = (unsigned char *)(mhdr+1);
810 payload_length = length - mux_header_size;
811 device_control_input(dev, payload, payload_length);
812 break;
813 case MUX_PROTO_TCP:
814 if(length < (mux_header_size + sizeof(struct tcphdr))) {
815 usbmuxd_log(LL_ERROR, "Incoming TCP packet is too small (%d)", length);
816 return;
817 }
818 th = (struct tcphdr *)((char*)mhdr+mux_header_size);
819 payload = (unsigned char *)(th+1);
820 payload_length = length - sizeof(struct tcphdr) - mux_header_size;
821 device_tcp_input(dev, th, payload, payload_length);
822 break;
823 default:
824 usbmuxd_log(LL_ERROR, "Incoming packet for device %d has unknown protocol 0x%x)", dev->id, ntohl(mhdr->protocol));
825 break;
826 }
827
828}
829
830int device_add(struct usb_device *usbdev)
831{
832 int res;
833 int id = get_next_device_id();
834 struct mux_device *dev;
835 usbmuxd_log(LL_NOTICE, "Connecting to new device on location 0x%x as ID %d", usb_get_location(usbdev), id);
836 dev = malloc(sizeof(struct mux_device));
837 dev->id = id;
838 dev->usbdev = usbdev;
839 dev->state = MUXDEV_INIT;
840 dev->visible = 0;
841 dev->next_sport = 1;
842 dev->pktbuf = malloc(DEV_MRU);
843 dev->pktlen = 0;
844 dev->preflight_cb_data = NULL;
845 dev->version = 0;
846 struct version_header vh;
847 vh.major = htonl(2);
848 vh.minor = htonl(0);
849 vh.padding = 0;
850 if((res = send_packet(dev, MUX_PROTO_VERSION, &vh, NULL, 0)) < 0) {
851 usbmuxd_log(LL_ERROR, "Error sending version request packet to device %d", id);
852 free(dev->pktbuf);
853 free(dev);
854 return res;
855 }
856 mutex_lock(&device_list_mutex);
857 collection_add(&device_list, dev);
858 mutex_unlock(&device_list_mutex);
859 return 0;
860}
861
862void device_remove(struct usb_device *usbdev)
863{
864 mutex_lock(&device_list_mutex);
865 FOREACH(struct mux_device *dev, &device_list) {
866 if(dev->usbdev == usbdev) {
867 usbmuxd_log(LL_NOTICE, "Removed device %d on location 0x%x", dev->id, usb_get_location(usbdev));
868 if(dev->state == MUXDEV_ACTIVE) {
869 dev->state = MUXDEV_DEAD;
870 FOREACH(struct mux_connection *conn, &dev->connections) {
871 connection_teardown(conn);
872 } ENDFOREACH
873 client_device_remove(dev->id);
874 collection_free(&dev->connections);
875 }
876 if (dev->preflight_cb_data) {
877 preflight_device_remove_cb(dev->preflight_cb_data);
878 }
879 collection_remove(&device_list, dev);
880 mutex_unlock(&device_list_mutex);
881 free(dev->pktbuf);
882 free(dev);
883 return;
884 }
885 } ENDFOREACH
886 mutex_unlock(&device_list_mutex);
887
888 usbmuxd_log(LL_WARNING, "Cannot find device entry while removing USB device %p on location 0x%x", usbdev, usb_get_location(usbdev));
889}
890
891void device_set_visible(int device_id)
892{
893 mutex_lock(&device_list_mutex);
894 FOREACH(struct mux_device *dev, &device_list) {
895 if(dev->id == device_id) {
896 dev->visible = 1;
897 break;
898 }
899 } ENDFOREACH
900 mutex_unlock(&device_list_mutex);
901}
902
903void device_set_preflight_cb_data(int device_id, void* data)
904{
905 mutex_lock(&device_list_mutex);
906 FOREACH(struct mux_device *dev, &device_list) {
907 if(dev->id == device_id) {
908 dev->preflight_cb_data = data;
909 break;
910 }
911 } ENDFOREACH
912 mutex_unlock(&device_list_mutex);
913}
914
915int device_get_count(int include_hidden)
916{
917 int count = 0;
918 struct collection dev_list = {NULL, 0};
919 mutex_lock(&device_list_mutex);
920 collection_copy(&dev_list, &device_list);
921 mutex_unlock(&device_list_mutex);
922
923 FOREACH(struct mux_device *dev, &dev_list) {
924 if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible))
925 count++;
926 } ENDFOREACH
927
928 collection_free(&dev_list);
929 return count;
930}
931
932int device_get_list(int include_hidden, struct device_info **devices)
933{
934 int count = 0;
935 struct collection dev_list = {NULL, 0};
936 mutex_lock(&device_list_mutex);
937 collection_copy(&dev_list, &device_list);
938 mutex_unlock(&device_list_mutex);
939
940 *devices = malloc(sizeof(struct device_info) * dev_list.capacity);
941 struct device_info *p = *devices;
942
943 FOREACH(struct mux_device *dev, &dev_list) {
944 if((dev->state == MUXDEV_ACTIVE) && (include_hidden || dev->visible)) {
945 p->id = dev->id;
946 p->serial = usb_get_serial(dev->usbdev);
947 p->location = usb_get_location(dev->usbdev);
948 p->pid = usb_get_pid(dev->usbdev);
949 p->speed = usb_get_speed(dev->usbdev);
950 count++;
951 p++;
952 }
953 } ENDFOREACH
954
955 collection_free(&dev_list);
956
957 return count;
958}
959
960int device_get_timeout(void)
961{
962 uint64_t oldest = (uint64_t)-1LL;
963 mutex_lock(&device_list_mutex);
964 FOREACH(struct mux_device *dev, &device_list) {
965 if(dev->state == MUXDEV_ACTIVE) {
966 FOREACH(struct mux_connection *conn, &dev->connections) {
967 if((conn->state == CONN_CONNECTED) && (conn->flags & CONN_ACK_PENDING) && conn->last_ack_time < oldest)
968 oldest = conn->last_ack_time;
969 } ENDFOREACH
970 }
971 } ENDFOREACH
972 mutex_unlock(&device_list_mutex);
973 uint64_t ct = mstime64();
974 if((int64_t)oldest == -1LL)
975 return 100000; //meh
976 if((ct - oldest) > ACK_TIMEOUT)
977 return 0;
978 return ACK_TIMEOUT - (ct - oldest);
979}
980
981void device_check_timeouts(void)
982{
983 uint64_t ct = mstime64();
984 mutex_lock(&device_list_mutex);
985 FOREACH(struct mux_device *dev, &device_list) {
986 if(dev->state == MUXDEV_ACTIVE) {
987 FOREACH(struct mux_connection *conn, &dev->connections) {
988 if((conn->state == CONN_CONNECTED) &&
989 (conn->flags & CONN_ACK_PENDING) &&
990 (ct - conn->last_ack_time) > ACK_TIMEOUT) {
991 usbmuxd_log(LL_DEBUG, "Sending ACK due to expired timeout (%" PRIu64 " -> %" PRIu64 ")", conn->last_ack_time, ct);
992 send_tcp_ack(conn);
993 }
994 } ENDFOREACH
995 }
996 } ENDFOREACH
997 mutex_unlock(&device_list_mutex);
998}
999
1000void device_init(void)
1001{
1002 usbmuxd_log(LL_DEBUG, "device_init");
1003 collection_init(&device_list);
1004 mutex_init(&device_list_mutex);
1005 next_device_id = 1;
1006}
1007
1008void device_kill_connections(void)
1009{
1010 usbmuxd_log(LL_DEBUG, "device_kill_connections");
1011 FOREACH(struct mux_device *dev, &device_list) {
1012 if(dev->state != MUXDEV_INIT) {
1013 FOREACH(struct mux_connection *conn, &dev->connections) {
1014 connection_teardown(conn);
1015 } ENDFOREACH
1016 }
1017 } ENDFOREACH
1018 // give USB a while to send the final connection RSTs and the like
1019 usb_process_timeout(100);
1020}
1021
1022void device_shutdown(void)
1023{
1024 usbmuxd_log(LL_DEBUG, "device_shutdown");
1025 mutex_lock(&device_list_mutex);
1026 FOREACH(struct mux_device *dev, &device_list) {
1027 FOREACH(struct mux_connection *conn, &dev->connections) {
1028 connection_teardown(conn);
1029 } ENDFOREACH
1030 collection_free(&dev->connections);
1031 collection_remove(&device_list, dev);
1032 free(dev);
1033 } ENDFOREACH
1034 mutex_unlock(&device_list_mutex);
1035 mutex_destroy(&device_list_mutex);
1036 collection_free(&device_list);
1037}