summaryrefslogtreecommitdiffstats
path: root/usbmux.c
diff options
context:
space:
mode:
authorGravatar Nikias Bassen2009-04-24 18:40:11 +0200
committerGravatar Nikias Bassen2009-04-24 18:40:11 +0200
commit25273957cbfa16dc908c4a56f48f2c847d5e7ab2 (patch)
tree561be098ac1ffa9bce6a79666173a065832b54e2 /usbmux.c
parentf7a7b349947235a0fac57159e3883b05dd51db29 (diff)
downloadusbmuxd-25273957cbfa16dc908c4a56f48f2c847d5e7ab2.tar.gz
usbmuxd-25273957cbfa16dc908c4a56f48f2c847d5e7ab2.tar.bz2
1. renamed iphone.c to usbmux.c and iphone.h to usbmux.h
2. renamed iphone* function to usbmux* 3. got rid of iphone_error_t type and constants 4. indentation adjustments
Diffstat (limited to 'usbmux.c')
-rw-r--r--usbmux.c1181
1 files changed, 1181 insertions, 0 deletions
diff --git a/usbmux.c b/usbmux.c
new file mode 100644
index 0000000..0a175ed
--- /dev/null
+++ b/usbmux.c
@@ -0,0 +1,1181 @@
1/*
2 * Copyright (c) 2008 Jing Su. All Rights Reserved.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18#include <stdint.h>
19#include <stdarg.h>
20#include <stdlib.h>
21#include <string.h>
22#include <usb.h>
23#include <stdio.h>
24#include <arpa/inet.h>
25#include <errno.h>
26#include <pthread.h>
27#include "usbmux.h"
28
29#define BULKIN 0x85
30#define BULKOUT 0x04
31#define HEADERLEN 28
32
33static const uint8_t TCP_FIN = 1;
34static const uint8_t TCP_SYN = 1 << 1;
35static const uint8_t TCP_RST = 1 << 2;
36static const uint8_t TCP_PSH = 1 << 3;
37static const uint8_t TCP_ACK = 1 << 4;
38static const uint8_t TCP_URG = 1 << 5;
39
40// I have trouble figuring out how to properly manage the windowing to
41// the device. It keeps sending back 512 and seems to drop off a cliff
42// when the device gets overwhelmed. In addition, the device likes to
43// panic and send out RESETS before the window hits zero. Also, waiting
44// for responses seems to not be a winning strategy.
45//
46// Since I'm not sure how in the hell to interpret the window sizes that
47// the device is sending back to us, I've figured out some magic number
48// constants which seem to work okay.
49static const uint32_t WINDOW_MAX = 5 * 1024;
50static const uint32_t WINDOW_INCREMENT = 512;
51
52typedef struct {
53 char* buffer;
54 int leftover;
55 int capacity;
56} receivebuf_t;
57
58struct usbmux_device_int {
59 char *buffer;
60 struct usb_dev_handle *usbdev;
61 struct usb_device *__device;
62 receivebuf_t usbReceive;
63};
64
65typedef struct {
66 uint32_t type, length, major, minor, allnull;
67} usbmux_version_header;
68
69typedef struct {
70 uint32_t type, length;
71 uint16_t sport, dport;
72 uint32_t scnt, ocnt;
73 uint8_t offset, tcp_flags;
74 uint16_t window, nullnull, length16;
75} usbmux_tcp_header;
76
77struct usbmux_client_int {
78 usbmux_tcp_header *header;
79 usbmux_device_t device;
80
81 char *recv_buffer;
82 int r_len;
83 pthread_cond_t wait;
84
85 // this contains a conditional variable which usb-writers can wait
86 // on while waiting for window updates from the device.
87 pthread_cond_t wr_wait;
88 // I'm going to do something really cheesy here. We are going to
89 // just record the most recent scnt that we are expecting to hear
90 // back on. We will actually halt progress by limiting the number
91 // of outstanding un-acked bulk sends that we have beamed out.
92 uint32_t wr_pending_scnt;
93 long wr_window;
94
95 pthread_mutex_t mutex;
96
97 // this variable is not protected by the mutex. This will always
98 // be E_SUCCESS, unless an error of some kind breaks this stream.
99 // this will then be set to the error that caused the broken stream.
100 // no further operations other than free_client will be allowed.
101 int error;
102
103 int cleanup;
104};
105
106
107static pthread_mutex_t usbmuxmutex = PTHREAD_MUTEX_INITIALIZER;
108static usbmux_client_t *connlist = NULL;
109static int clients = 0;
110
111
112/**
113 */
114int toto_debug = 0;
115
116void usbmux_set_debug(int e)
117{
118 toto_debug = e;
119}
120
121void log_debug_msg(const char *format, ...)
122{
123#ifndef STRIP_DEBUG_CODE
124 va_list args;
125 /* run the real fprintf */
126 va_start(args, format);
127
128 if (toto_debug)
129 vfprintf(stderr, format, args);
130
131 va_end(args);
132#endif
133}
134
135#ifdef DEBUG
136/**
137 * for debugging purposes.
138 */
139static void print_buffer(const char *data, const int length)
140{
141 if (toto_debug <= 0) {
142 return;
143 }
144 int i;
145 int j;
146 unsigned char c;
147
148 for(i=0; i<length; i+=16) {
149 printf("%04x: ", i);
150 for (j=0;j<16;j++) {
151 if (i+j >= length) {
152 printf(" ");
153 continue;
154 }
155 printf("%02hhx ", *(data+i+j));
156 }
157 printf(" | ");
158 for(j=0;j<16;j++) {
159 if (i+j >= length)
160 break;
161 c = *(data+i+j);
162 if ((c < 32) || (c > 127)) {
163 printf(".");
164 continue;
165 }
166 printf("%c", c);
167 }
168 printf("\n");
169 }
170 printf("\n");
171}
172#endif
173
174void hton_header(usbmux_tcp_header *hdr)
175{
176 if (hdr) {
177 hdr->length = htonl(hdr->length);
178 hdr->scnt = htonl(hdr->scnt);
179 hdr->ocnt = htonl(hdr->ocnt);
180 hdr->length16 = htons(hdr->length16);
181 }
182}
183
184void ntoh_header(usbmux_tcp_header *hdr)
185{
186 if (hdr) {
187 hdr->length = ntohl(hdr->length);
188 hdr->scnt = ntohl(hdr->scnt);
189 hdr->ocnt = ntohl(hdr->ocnt);
190 hdr->length16 = ntohs(hdr->length16);
191 }
192}
193
194/** Creates a USBMux header containing version information
195 *
196 * @return A USBMux header
197 */
198usbmux_version_header *version_header()
199{
200 usbmux_version_header *version = (usbmux_version_header *) malloc(sizeof(usbmux_version_header));
201 version->type = 0;
202 version->length = htonl(20);
203 version->major = htonl(1);
204 version->minor = 0;
205 version->allnull = 0;
206 return version;
207}
208
209/**
210 * This function sets the configuration of the given device to 3
211 * and claims the interface 1. If usb_set_configuration fails, it detaches
212 * the kernel driver that blocks the device, and retries configuration.
213 *
214 * @param device which device to configure
215 */
216static int usbmux_config_usb_device(usbmux_device_t device)
217{
218 int ret;
219 int bytes;
220 char buf[512];
221
222#if 0
223 log_debug_msg("checking configuration...\n");
224 if (device->__device->config->bConfigurationValue != 3) {
225 log_debug_msg("WARNING: usb device configuration is not 3 as expected!\n");
226 }
227
228 log_debug_msg("setting configuration...\n");
229 ret = usb_set_configuration(device->device, 3);
230 if (ret != 0) {
231 log_debug_msg("Hm, usb_set_configuration returned %d: %s\n", ret, strerror(-ret));
232#if LIBUSB_HAS_GET_DRIVER_NP
233 log_debug_msg("trying to fix:\n");
234 log_debug_msg("-> detaching kernel driver... ");
235 ret = usb_detach_kernel_driver_np(device->device, device->__device->config->interface->altsetting->bInterfaceNumber);
236 if (ret != 0) {
237 log_debug_msg("usb_detach_kernel_driver_np returned %d: %s\n", ret, strerror(-ret));
238 } else {
239 log_debug_msg("done.\n");
240 log_debug_msg("setting configuration again... ");
241 ret = usb_set_configuration(device->device, 3);
242 if (ret != 0) {
243 log_debug_msg("Error: usb_set_configuration returned %d: %s\n", ret, strerror(-ret));
244 log_debug_msg("--> trying to continue anyway...\n");
245 } else {
246 log_debug_msg("done.\n");
247 }
248 }
249#else
250 log_debug_msg("--> trying to continue anyway...\n");
251#endif
252 } else {
253 log_debug_msg("done.\n");
254 }
255#endif
256
257 log_debug_msg("claiming interface... ");
258 ret = usb_claim_interface(device->usbdev, 1);
259 if (ret != 0) {
260 log_debug_msg("Error: usb_claim_interface returned %d: %s\n", ret, strerror(-ret));
261 return -ENODEV;
262 } else {
263 log_debug_msg("done.\n");
264 }
265
266 do {
267 bytes = usb_bulk_read(device->usbdev, BULKIN, buf, 512, 800);
268 } while (bytes > 0);
269
270 return 0;
271}
272
273/**
274 * Given a USB bus and device number, returns a device handle to the device on
275 * that bus. To aid compatibility with future devices, this function does not
276 * check the vendor and device IDs! To do that, you should use
277 * usbmux_get_device() or a system-specific API (e.g. HAL).
278 *
279 * @param bus_n The USB bus number.
280 * @param dev_n The USB device number.
281 * @param device A pointer to a usbmux_device_t, which must be set to NULL upon
282 * calling usbmux_get_specific_device, which will be filled with a device
283 * descriptor on return.
284 * @return 0 if ok, otherwise a negative errno value.
285 */
286int usbmux_get_specific_device(int bus_n, int dev_n, usbmux_device_t * device)
287{
288 struct usb_bus *bus;
289 struct usb_device *dev;
290 usbmux_version_header *version;
291 int bytes = 0;
292
293 //check we can actually write in device
294 if (!device || (device && *device))
295 return -EINVAL;
296
297 usbmux_device_t newdevice = (usbmux_device_t) malloc(sizeof(struct usbmux_device_int));
298
299 // Initialize the struct
300 newdevice->usbdev = NULL;
301 newdevice->__device = NULL;
302 newdevice->buffer = NULL;
303
304 // don't forget these:
305 newdevice->usbReceive.buffer = NULL;
306 newdevice->usbReceive.leftover = 0;
307 newdevice->usbReceive.capacity = 0;
308
309 // Initialize libusb
310 usb_init();
311 usb_find_busses();
312 usb_find_devices();
313
314 // Set the device configuration
315 for (bus = usb_get_busses(); bus; bus = bus->next)
316 //if (bus->location == bus_n)
317 for (dev = bus->devices; dev != NULL; dev = dev->next)
318 if (dev->devnum == dev_n) {
319 newdevice->__device = dev;
320 newdevice->usbdev = usb_open(newdevice->__device);
321 if (usbmux_config_usb_device(newdevice) == 0) {
322 goto found;
323 }
324 }
325
326 usbmux_free_device(newdevice);
327
328 log_debug_msg("usbmux_get_specific_device: device not found\n");
329 return -ENODEV;
330
331found:
332 // Send the version command to the device
333 version = version_header();
334 bytes = usb_bulk_write(newdevice->usbdev, BULKOUT, (char *) version, sizeof(*version), 800);
335 if (bytes < 20) {
336 log_debug_msg("%s: libusb did NOT send enough!\n", __func__);
337 if (bytes < 0) {
338 log_debug_msg("%s: libusb gave me the error %d: %s (%s)\n", __func__, bytes, usb_strerror(), strerror(-bytes));
339 }
340 }
341 // Read the device's response
342 bytes = usb_bulk_read(newdevice->usbdev, BULKIN, (char *) version, sizeof(*version), 800);
343
344 // Check for bad response
345 if (bytes < 20) {
346 free(version);
347 usbmux_free_device(newdevice);
348 log_debug_msg("%s: Invalid version message -- header too short.\n", __func__);
349 if (bytes < 0) {
350 log_debug_msg("%s: libusb error message %d: %s (%s)\n", __func__, bytes, usb_strerror(), strerror(-bytes));
351 return bytes;
352 }
353 return -EBADMSG;
354 }
355 // Check for correct version
356 if (ntohl(version->major) == 1 && ntohl(version->minor) == 0) {
357 // We're all ready to roll.
358 log_debug_msg("%s: success\n", __func__);
359 free(version);
360 *device = newdevice;
361 return 0;
362 } else {
363 // Bad header
364 usbmux_free_device(newdevice);
365 free(version);
366 log_debug_msg("%s: Received a bad header/invalid version number.", __func__);
367 return -EBADMSG;
368 }
369
370 // If it got to this point it's gotta be bad
371 log_debug_msg("%s: Unknown error.\n", __func__);
372 usbmux_free_device(newdevice);
373 free(version);
374 return -EBADMSG; // if it got to this point it's gotta be bad
375}
376
377/** Cleans up an usbmux_device_t structure, then frees the structure itself.
378 * This is a library-level function; deals directly with the device to tear
379 * down relations, but otherwise is mostly internal.
380 *
381 * @param device A pointer to an usbmux_device_t structure.
382 */
383int usbmux_free_device(usbmux_device_t device)
384{
385 char buf[512];
386 int bytes;
387
388 if (!device)
389 return -EINVAL;
390 int ret = 0;
391
392 if (device->usbdev) {
393 do {
394 bytes = usb_bulk_read(device->usbdev, BULKIN, buf, 512, 800);
395 } while (bytes > 0);
396 }
397
398 if (bytes < 0) {
399 ret = bytes;
400 }
401
402 if (device->buffer) {
403 free(device->buffer);
404 }
405 if (device->usbReceive.buffer) {
406 free(device->usbReceive.buffer);
407 }
408 if (device->usbdev) {
409 usb_release_interface(device->usbdev, 1);
410 usb_close(device->usbdev);
411 ret = 0;
412 }
413 free(device);
414
415 return ret;
416}
417
418
419
420/** Sends data to the device
421 * This is a low-level (i.e. directly to device) function.
422 *
423 * @param device The device to send data to
424 * @param data The data to send
425 * @param datalen The length of the data
426 * @return The number of bytes sent, or -ERRNO on error
427 */
428int send_to_device(usbmux_device_t device, char *data, int datalen)
429{
430 if (!device)
431 return -EINVAL;
432
433 int timeout = 1000;
434 int retrycount = 0;
435 int bytes = 0;
436
437#ifdef DEBUG
438 #ifdef DEBUG_MORE
439 printf("===============================\n%s: trying to send\n", __func__);
440 print_buffer(data, datalen);
441 printf("===============================\n");
442 #endif
443#endif
444 do {
445 if (retrycount > 3) {
446 log_debug_msg("EPIC FAIL! aborting on retry count overload.\n");
447 return -ECOMM;
448 }
449
450 bytes = usb_bulk_write(device->usbdev, BULKOUT, data, datalen, timeout);
451 if (bytes == -ETIMEDOUT) {
452 // timed out waiting for write.
453 log_debug_msg("usb_bulk_write timeout error.\n");
454 return bytes;
455 } else if (bytes < 0) {
456 log_debug_msg("usb_bulk_write failed with error. err:%d (%s)(%s)\n", bytes, usb_strerror(), strerror(-bytes));
457 return bytes;
458 } else if (bytes == 0) {
459 log_debug_msg("usb_bulk_write sent nothing. retrying.\n");
460 timeout = timeout * 4;
461 retrycount++;
462 continue;
463 } else if (bytes < datalen) {
464 log_debug_msg("usb_bulk_write failed to send full dataload. %d of %d\n", bytes, datalen);
465 timeout = timeout * 4;
466 retrycount++;
467 data += bytes;
468 datalen -= bytes;
469 continue;
470 }
471 } while(0); // fall out
472
473#ifdef DEBUG
474 if (bytes > 0) {
475 if (toto_debug > 0) {
476 printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
477 printf("%s: sent to device\n", __func__);
478 print_buffer(data, bytes);
479 printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
480 }
481 }
482#endif
483 return bytes;
484}
485
486/** Receives data from the device
487 * This function is a low-level (i.e. direct from device) function.
488 *
489 * @param device The device to receive data from
490 * @param data Where to put data read
491 * @param datalen How much data to read in
492 * @param timeout How many milliseconds to wait for data
493 *
494 * @return How many bytes were read in, or -1 on error.
495 */
496int recv_from_device_timeout(usbmux_device_t device, char *data, int datalen, int timeoutmillis)
497{
498 if (!device)
499 return -EINVAL;
500 //log_debug_msg("%s: attempting to receive %i bytes\n", __func__, datalen);
501
502 int bytes = usb_bulk_read(device->usbdev, BULKIN, data, datalen, timeoutmillis);
503 // There are some things which are errors, others which are no problem.
504 // It's not documented in libUSB, but it seems that the error values
505 // returned are just negated ERRNO values.
506 if (bytes < 0) {
507 if (bytes == -ETIMEDOUT) {
508 // ignore this. it just means timeout reached before we
509 // picked up any data. no problem.
510 return 0;
511 } else {
512 fprintf(stderr, "%s: libusb gave me the error %d: %s (%s)\n", __func__, bytes, usb_strerror(), strerror(-bytes));
513 log_debug_msg("%s: libusb gave me the error %d: %s (%s)\n", __func__, bytes, usb_strerror(), strerror(-bytes));
514 }
515 return bytes;
516 }
517
518#ifdef DEBUG
519 if (bytes > 0) {
520 if (toto_debug > 0) {
521 printf("<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
522 printf("%s: received from device:\n", __func__);
523 print_buffer(data, bytes);
524 printf("<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
525 }
526 }
527#endif
528
529 return bytes;
530}
531
532/** Creates a USBMux packet for the given set of ports.
533 *
534 * @param s_port The source port for the connection.
535 * @param d_port The destination port for the connection.
536 *
537 * @return A USBMux packet
538 */
539usbmux_tcp_header *new_mux_packet(uint16_t s_port, uint16_t d_port)
540{
541 usbmux_tcp_header *conn = (usbmux_tcp_header *) malloc(sizeof(usbmux_tcp_header));
542 conn->type = htonl(6);
543 conn->length = HEADERLEN;
544 conn->sport = htons(s_port);
545 conn->dport = htons(d_port);
546 conn->scnt = 0;
547 conn->ocnt = 0;
548 conn->offset = 0x50;
549 conn->window = htons(0x0200);
550 conn->nullnull = 0x0000;
551 conn->length16 = HEADERLEN;
552 return conn;
553}
554
555
556/** Removes a connection from the list of connections made.
557 * The list of connections is necessary for buffering.
558 *
559 * @param connection The connection to delete from the tracking list.
560 */
561static void delete_connection(usbmux_client_t connection)
562{
563 usbmux_client_t *newlist = NULL;
564
565 pthread_mutex_lock(&usbmuxmutex);
566
567 // update the global list of connections
568 if (clients > 1) {
569 newlist = (usbmux_client_t *) malloc(sizeof(usbmux_client_t) * (clients - 1));
570 int i = 0, j = 0;
571 for (i = 0; i < clients; i++) {
572 if (connlist[i] == connection)
573 continue;
574 else {
575 newlist[j] = connlist[i];
576 j++;
577 }
578 }
579 }
580 if (connlist) {
581 free(connlist);
582 }
583 connlist = newlist;
584 clients--;
585
586 // free up this connection
587 pthread_mutex_lock(&connection->mutex);
588 if (connection->recv_buffer)
589 free(connection->recv_buffer);
590 if (connection->header)
591 free(connection->header);
592 connection->r_len = 0;
593 pthread_mutex_unlock(&connection->mutex);
594 pthread_mutex_destroy(&connection->mutex);
595 free(connection);
596
597 pthread_mutex_unlock(&usbmuxmutex);
598}
599
600/** Adds a connection to the list of connections made.
601 * The connection list is necessary for buffering.
602 *
603 * @param connection The connection to add to the global list of connections.
604 */
605
606static void add_connection(usbmux_client_t connection)
607{
608 pthread_mutex_lock(&usbmuxmutex);
609 usbmux_client_t *newlist =
610 (usbmux_client_t *) realloc(connlist, sizeof(usbmux_client_t) * (clients + 1));
611 newlist[clients] = connection;
612 connlist = newlist;
613 clients++;
614 pthread_mutex_unlock(&usbmuxmutex);
615}
616
617/**
618 * Get a source port number that is not used by one of our connections
619 * This is needed for us to make sure we are not sending on another
620 * connection.
621 */
622static uint16_t get_free_port()
623{
624 int i;
625 uint16_t newport = 30000;
626 int cnt = 0;
627
628 pthread_mutex_lock(&usbmuxmutex);
629 while (1) {
630 cnt = 0;
631 for (i = 0; i < clients; i++) {
632 if (ntohs(connlist[i]->header->sport) == newport) {
633 cnt++;
634 }
635 }
636 if (cnt == 0) {
637 // newport is not used in our list of connections!
638 break;
639 } else {
640 newport++;
641 if (newport < 30000) {
642 // if all ports from 30000 to 65535 are in use,
643 // the value wraps (16-bit overflow)
644 // return 0, no port is available.
645 // This should not happen, but just in case ;)
646 newport = 0;
647 break;
648 }
649 }
650 }
651 pthread_mutex_unlock(&usbmuxmutex);
652
653 return newport;
654}
655
656/** Initializes a connection to 'device' with source port s_port and destination port d_port
657 *
658 * @param device The device to initialize a connection on.
659 * @param src_port The source port
660 * @param dst_port The destination port -- 0xf27e for lockdownd.
661 * @param client A mux TCP header for the connection which is used for tracking and data transfer.
662 * @return 0 on success, a negative errno value otherwise.
663 */
664int usbmux_new_client(usbmux_device_t device, uint16_t src_port, uint16_t dst_port, usbmux_client_t * client)
665{
666 if (!device || !dst_port)
667 return -EINVAL;
668
669 src_port = get_free_port();
670
671 if (!src_port) {
672 // this is a special case, if we get 0, this is not good, so
673 return -EISCONN; // TODO: error code suitable?
674 }
675
676 // Initialize connection stuff
677 usbmux_client_t new_connection = (usbmux_client_t) malloc(sizeof(struct usbmux_client_int));
678 new_connection->header = new_mux_packet(src_port, dst_port);
679
680 // send TCP syn
681 if (new_connection && new_connection->header) {
682 int err = 0;
683 new_connection->header->tcp_flags = TCP_SYN;
684 new_connection->header->length = new_connection->header->length;
685 new_connection->header->length16 = new_connection->header->length16;
686 new_connection->header->scnt = 0;
687 new_connection->header->ocnt = 0;
688 new_connection->device = device;
689 new_connection->recv_buffer = NULL;
690 new_connection->r_len = 0;
691 pthread_cond_init(&new_connection->wait, NULL);
692 pthread_mutex_init(&new_connection->mutex, NULL);
693 pthread_cond_init(&new_connection->wr_wait, NULL);
694 new_connection->wr_pending_scnt = 0;
695 new_connection->wr_window = 0;
696 add_connection(new_connection);
697 new_connection->error = 0;
698 new_connection->cleanup = 0;
699 hton_header(new_connection->header);
700 log_debug_msg("%s: send_to_device (%d --> %d)\n", __func__, ntohs(new_connection->header->sport), ntohs(new_connection->header->dport));
701 err = send_to_device(device, (char *) new_connection->header, sizeof(usbmux_tcp_header));
702 if (err >= 0) {
703 *client = new_connection;
704 return 0;
705 } else {
706 delete_connection(new_connection);
707 return err;
708 }
709 }
710 // if we get to this point it's probably bad
711 return -ENOMEM;
712}
713
714/** Cleans up the given USBMux connection.
715 * @note Once a connection is closed it may not be used again.
716 *
717 * @param connection The connection to close.
718 *
719 * @return 0 on success or a negative errno value on error.
720 */
721int usbmux_free_client(usbmux_client_t client)
722{
723 if (!client || !client->device)
724 return -EINVAL;
725
726 int err = 0;
727 int result = 0;
728 pthread_mutex_lock(&client->mutex);
729 client->header->tcp_flags = TCP_FIN;
730 client->header->length = 0x1C;
731 client->header->window = 0;
732 client->header->length16 = 0x1C;
733 hton_header(client->header);
734
735 err = send_to_device(client->device, (char*)client->header, sizeof(usbmux_tcp_header));
736 if (err < 0) {
737 log_debug_msg("%s: error sending TCP_FIN\n", __func__);
738 result = err;
739 }
740
741 client->cleanup = 1;
742
743 // make sure we don't have any last-minute laggards waiting on this.
744 // I put it after the mutex unlock because we have cases where the
745 // conditional wait is dependent on re-grabbing that mutex.
746 pthread_cond_broadcast(&client->wait);
747 pthread_cond_destroy(&client->wait);
748 pthread_cond_broadcast(&client->wr_wait);
749 pthread_cond_destroy(&client->wr_wait);
750
751 pthread_mutex_unlock(&client->mutex);
752
753 return result;
754}
755
756/** Sends the given data over the selected connection.
757 *
758 * @param client The client we're sending data on.
759 * @param data A pointer to the data to send.
760 * @param datalen How much data we're sending.
761 * @param sent_bytes The number of bytes sent, minus the header (28)
762 *
763 * @return 0 on success or a negative errno value on error.
764 */
765int usbmux_send(usbmux_client_t client, const char *data, uint32_t datalen, uint32_t * sent_bytes)
766{
767 if (!client->device || !client || !sent_bytes)
768 return -EINVAL;
769
770 if (client->error < 0) {
771 return client->error;
772 }
773
774 *sent_bytes = 0;
775 pthread_mutex_lock(&client->mutex);
776
777 int sendresult = 0;
778 uint32_t blocksize = 0;
779 if (client->wr_window <= 0) {
780 struct timespec ts;
781 clock_gettime(CLOCK_REALTIME, &ts);
782 //ts.tv_sec += 1;
783 ts.tv_nsec += 750 * 1000;
784 if (pthread_cond_timedwait(&client->wait, &client->mutex, &ts) == ETIMEDOUT) {
785 // timed out. optimistically grow the window and try to make progress
786 client->wr_window += WINDOW_INCREMENT;
787 }
788 }
789
790 blocksize = sizeof(usbmux_tcp_header) + datalen;
791
792 // client->scnt and client->ocnt should already be in host notation...
793 // we don't need to change them juuuust yet.
794 char *buffer = (char *) malloc(blocksize + 2); // allow 2 bytes of safety padding
795 // Set the length
796 client->header->length = blocksize;
797 client->header->length16 = blocksize;
798
799 // Put header into big-endian notation
800 hton_header(client->header);
801 // Concatenation of stuff in the buffer.
802 memcpy(buffer, client->header, sizeof(usbmux_tcp_header));
803 memcpy(buffer + sizeof(usbmux_tcp_header), data, datalen);
804
805 log_debug_msg("%s: send_to_device(%d --> %d)\n", __func__, ntohs(client->header->sport), ntohs(client->header->dport));
806 sendresult = send_to_device(client->device, buffer, blocksize);
807 // Now that we've sent it off, we can clean up after our sloppy selves.
808 if (buffer)
809 free(buffer);
810
811 // revert header fields that have been swapped before trying to send
812 ntoh_header(client->header);
813
814 // update counts ONLY if the send succeeded.
815 if ((uint32_t)sendresult == blocksize) {
816 // Re-calculate scnt
817 client->header->scnt += datalen;
818 client->wr_window -= blocksize;
819 }
820
821 pthread_mutex_unlock(&client->mutex);
822
823 if (sendresult == -ETIMEDOUT || sendresult == 0) {
824 // no problem for now...
825 *sent_bytes = 0;
826 return -ETIMEDOUT;
827 } else if (sendresult < 0) {
828 return sendresult;
829 } else if ((uint32_t)sendresult == blocksize) {
830 // actual number of data bytes sent.
831 *sent_bytes = sendresult - HEADERLEN;
832 return 0;
833 } else {
834 fprintf(stderr, "usbsend managed to dump a packet that is not full size. %d of %d\n", sendresult, blocksize);
835 return -EBADMSG;
836 }
837}
838
839/** append the packet's DATA to the receive buffer for the client.
840 *
841 * this has a few other corner-case functions:
842 * 1. this will properly handle the handshake syn+ack.
843 * 2. for all receives, this will appropriately update the ocnt.
844 *
845 * @return number of bytes consumed (header + data)
846 */
847uint32_t append_receive_buffer(usbmux_client_t client, char* packet)
848{
849 if (client == NULL || packet == NULL) return 0;
850
851 usbmux_tcp_header *header = (usbmux_tcp_header *) packet;
852 char* data = &packet[HEADERLEN];
853 uint32_t packetlen = ntohl(header->length);
854 uint32_t datalen = packetlen-HEADERLEN;
855
856 int dobroadcast = 0;
857
858 pthread_mutex_lock(&client->mutex);
859
860 // we need to handle a few corner case tasks and book-keeping which
861 // falls on our responsibility because we are the ones reading in
862 // feedback.
863 if (client->header->scnt == 0 && client->header->ocnt == 0 ) {
864 log_debug_msg("client is still waiting for handshake.\n");
865 if (header->tcp_flags == (TCP_SYN | TCP_ACK)) {
866 log_debug_msg("yes, got syn+ack ; replying with ack.\n");
867 client->header->tcp_flags = TCP_ACK;
868 client->header->length = sizeof(usbmux_tcp_header);
869 client->header->length16 = sizeof(usbmux_tcp_header);
870 client->header->scnt += 1;
871 client->header->ocnt = header->ocnt;
872 hton_header(client->header);
873 // push it to USB
874 // TODO: need to check for error in the send here.... :(
875 log_debug_msg("%s: send_to_device (%d --> %d)\n", __func__, ntohs(client->header->sport), ntohs(client->header->dport));
876 if (send_to_device(client->device, (char *)client->header, sizeof(usbmux_tcp_header)) <= 0) {
877 log_debug_msg("%s: error when pushing to usb...\n", __func__);
878 }
879 // need to revert some of the fields back to host notation.
880 ntoh_header(client->header);
881 } else {
882 client->error = -ECONNABORTED;
883 // woah... this connection failed us.
884 // TODO: somehow signal that this stream is a no-go.
885 log_debug_msg("WOAH! client failed to get proper syn+ack.\n");
886 }
887 }
888
889 // update TCP counters and windows.
890 //
891 // save the window that we're getting from the USB device.
892 // apparently the window is bigger than just the 512 that's typically
893 // advertised. iTunes apparently shifts this value by 8 to get a much
894 // larger number.
895 if (header->tcp_flags & TCP_RST) {
896 client->error = -ECONNRESET;
897
898 if (datalen > 0) {
899 char e_msg[128];
900 e_msg[0] = 0;
901 if (datalen > 1) {
902 memcpy(e_msg, data+1, datalen-1);
903 e_msg[datalen-1] = 0;
904 }
905 // fetch the message
906 switch(data[0]) {
907 case 0:
908 // this is not an error, it's just a status message.
909 log_debug_msg("received status message: %s\n", e_msg);
910 datalen = 0;
911 break;
912 case 1:
913 log_debug_msg("received error message: %s\n", e_msg);
914 datalen = 0;
915 break;
916 default:
917 log_debug_msg("received unknown message (type 0x%02x): %s\n", data[0], e_msg);
918 //datalen = 0; // <-- we let this commented out for testing
919 break;
920 }
921 } else {
922 log_debug_msg("peer sent connection reset. setting error: %d\n", client->error);
923 }
924 }
925
926 // the packet's ocnt tells us how much of our data the device has received.
927 if (header->tcp_flags & TCP_ACK) {
928 // this is a hacky magic number condition. it seems that once
929 // the window reported by the device starts to drop below this
930 // number, we quickly fall into connection reset problems.
931 // Once we see the reported window size start falling off,
932 // ut off and wait for solid acks to come back.
933 if (ntohs(header->window) < 256)
934 client->wr_window = 0;
935
936 // check what just got acked.
937 if (ntohl(header->ocnt) < client->header->scnt) {
938 // we got some kind of ack, but it hasn't caught up
939 // with the pending that have been sent.
940 pthread_cond_broadcast(&client->wr_wait);
941 } else if (ntohl(header->ocnt) > /*client->wr_pending_scnt*/ client->header->scnt) {
942 fprintf(stderr, "WTF?! acks overtook pending outstanding. %u,%u\n", ntohl(header->ocnt), client->wr_pending_scnt);
943 } else {
944 // reset the window
945 client->wr_window = WINDOW_MAX;
946 pthread_cond_broadcast(&client->wr_wait);
947 }
948 }
949
950 // the packet's scnt will be our new ocnt.
951 client->header->ocnt = ntohl(header->scnt);
952
953 // ensure there is enough space, either by first malloc or realloc
954 if (datalen > 0) {
955 log_debug_msg("%s: putting %d bytes into client's recv_buffer\n", __func__, datalen);
956 if (client->r_len == 0)
957 dobroadcast = 1;
958
959 if (client->recv_buffer == NULL) {
960 client->recv_buffer = malloc(datalen);
961 client->r_len = 0;
962 } else {
963 client->recv_buffer = realloc(client->recv_buffer, client->r_len + datalen);
964 }
965
966 memcpy(&client->recv_buffer[client->r_len], data, datalen);
967 client->r_len += datalen;
968 }
969
970 pthread_mutex_unlock(&client->mutex);
971
972 // I put this outside the mutex unlock just so that when the threads
973 // wake, we don't have to do another round of unlock+try to grab.
974 if (dobroadcast)
975 pthread_cond_broadcast(&client->wait);
976
977 return packetlen;
978}
979
980/**
981 * @note THERE IS NO MUTEX LOCK IN THIS FUNCTION!
982 * because we're only called from one location, pullbulk, where the lock
983 * is already held.
984 */
985usbmux_client_t find_client(usbmux_tcp_header* recv_header)
986{
987 // remember, as we're looking for the client, the receive header is
988 // coming from the USB into our client. This means that when we check
989 // the src/dst ports, we need to reverse them.
990 usbmux_client_t retval = NULL;
991
992 // just for debugging check, I'm going to convert the numbers to host-endian.
993 uint16_t hsport = ntohs(recv_header->sport);
994 uint16_t hdport = ntohs(recv_header->dport);
995
996 pthread_mutex_lock(&usbmuxmutex);
997 int i;
998 for (i = 0; i < clients; i++) {
999 uint16_t csport = ntohs(connlist[i]->header->sport);
1000 uint16_t cdport = ntohs(connlist[i]->header->dport);
1001
1002 if (hsport == cdport && hdport == csport) {
1003 retval = connlist[i];
1004 break;
1005 }
1006 }
1007 pthread_mutex_unlock(&usbmuxmutex);
1008
1009 return retval;
1010}
1011
1012/** pull in a big USB bulk packet and distribute it to queues appropriately.
1013 */
1014int usbmux_pullbulk(usbmux_device_t device)
1015{
1016 if (!device)
1017 return -EINVAL;
1018
1019 int res = 0;
1020 static const int DEFAULT_CAPACITY = 128*1024;
1021 if (device->usbReceive.buffer == NULL) {
1022 device->usbReceive.capacity = DEFAULT_CAPACITY;
1023 device->usbReceive.buffer = malloc(device->usbReceive.capacity);
1024 device->usbReceive.leftover = 0;
1025 }
1026
1027 // start the cursor off just ahead of the leftover.
1028 char* cursor = &device->usbReceive.buffer[device->usbReceive.leftover];
1029 // pull in content, note that the amount we can pull is capacity minus leftover
1030 int readlen = recv_from_device_timeout(device, cursor, device->usbReceive.capacity - device->usbReceive.leftover, 3000);
1031 if (readlen < 0) {
1032 res = readlen;
1033 //fprintf(stderr, "recv_from_device_timeout gave us an error.\n");
1034 readlen = 0;
1035 }
1036 if (readlen > 0) {
1037 //fprintf(stdout, "recv_from_device_timeout pulled an extra %d bytes\n", readlen);
1038 }
1039
1040 // the amount of content we have to work with is the remainder plus
1041 // what we managed to read
1042 device->usbReceive.leftover += readlen;
1043
1044 // reset the cursor to the front of that buffer and work through
1045 // trying to decode packets out of them.
1046 cursor = device->usbReceive.buffer;
1047 while (1) {
1048 // check if there's even sufficient data to decode a header
1049 if (device->usbReceive.leftover < HEADERLEN)
1050 break;
1051 usbmux_tcp_header *header = (usbmux_tcp_header *) cursor;
1052
1053 log_debug_msg("%s: recv_from_device_timeout (%d --> %d)\n", __func__, ntohs(header->sport), ntohs(header->dport));
1054
1055 // now that we have a header, check if there is sufficient data
1056 // to construct a full packet, including its data
1057 uint32_t packetlen = ntohl(header->length);
1058 if ((uint32_t)device->usbReceive.leftover < packetlen) {
1059 fprintf(stderr, "%s: not enough data to construct a full packet\n", __func__);
1060 break;
1061 }
1062
1063 // ok... find the client this packet will get stuffed to.
1064 usbmux_client_t client = find_client(header);
1065 if (client == NULL) {
1066 log_debug_msg("WARNING: client for packet cannot be found. dropping packet.\n");
1067 } else {
1068 // stuff the data
1069 log_debug_msg("%s: found client, calling append_receive_buffer\n", __func__);
1070 append_receive_buffer(client, cursor);
1071
1072 // perhaps this is too general, == -ECONNRESET
1073 // might be a better check here
1074 if (client->error < 0) {
1075 pthread_mutex_lock(&client->mutex);
1076 if (client->cleanup) {
1077 pthread_mutex_unlock(&client->mutex);
1078 log_debug_msg("freeing up connection (%d->%d)\n", ntohs(client->header->sport), ntohs(client->header->dport));
1079 delete_connection(client);
1080 } else {
1081 pthread_mutex_unlock(&client->mutex);
1082 }
1083 }
1084 }
1085
1086 // move the cursor and account for the consumption
1087 cursor += packetlen;
1088 device->usbReceive.leftover -= packetlen;
1089 }
1090
1091 // now, we need to manage any leftovers.
1092 // I'm going to manage the leftovers by alloc'ing a new block and
1093 // copyingthe leftovers to it. This is just to prevent problems with
1094 // memory moves where there may be overlap. Besides, the leftovers
1095 // should be small enough that this copy is minimal in overhead.
1096 //
1097 // if there are no leftovers, we just leave the datastructure as is,
1098 // and re-use the block next time.
1099 if (device->usbReceive.leftover > 0 && cursor != device->usbReceive.buffer) {
1100 log_debug_msg("%s: we got a leftover, so handle it\n", __func__);
1101 char* newbuff = malloc(DEFAULT_CAPACITY);
1102 memcpy(newbuff, cursor, device->usbReceive.leftover);
1103 free(device->usbReceive.buffer);
1104 device->usbReceive.buffer = newbuff;
1105 device->usbReceive.capacity = DEFAULT_CAPACITY;
1106 }
1107
1108 return res;
1109}
1110
1111/**
1112 * return the error code stored in usbmux_client_t structure,
1113 * e.g. non-zero when an usb read error occurs.
1114 *
1115 * @param client the usbmux client
1116 *
1117 * @return 0 or a negative errno value.
1118 */
1119int usbmux_get_error(usbmux_client_t client)
1120{
1121 if (!client) {
1122 return 0;
1123 }
1124 return client->error;
1125}
1126
1127/** This function reads from the client's recv_buffer.
1128 *
1129 * @param client The client to receive data from.
1130 * @param data Where to put the data we receive.
1131 * @param datalen How much data to read.
1132 * @param timeout How many milliseconds to wait for data
1133 *
1134 * @return 0 on success or a negative errno value on failure.
1135 */
1136int usbmux_recv_timeout(usbmux_client_t client, char *data, uint32_t datalen, uint32_t * recv_bytes, int timeout)
1137{
1138
1139 if (!client || !data || datalen == 0 || !recv_bytes)
1140 return -EINVAL;
1141
1142 if (client->error < 0)
1143 return client->error;
1144
1145 pthread_mutex_lock(&client->mutex);
1146
1147 if (timeout > 0 && (client->recv_buffer == NULL || client->r_len == 0)) {
1148 struct timespec ts;
1149 clock_gettime(CLOCK_REALTIME, &ts);
1150 ts.tv_sec += timeout/1000;
1151 ts.tv_nsec += (timeout-((int)(timeout/1000))*1000)*1000;
1152 pthread_cond_timedwait(&client->wait, &client->mutex, &ts);
1153 }
1154
1155 *recv_bytes = 0;
1156 if (client->recv_buffer != NULL && client->r_len > 0) {
1157 uint32_t foolen = datalen;
1158 if ((int)foolen > client->r_len)
1159 foolen = client->r_len;
1160 memcpy(data, client->recv_buffer, foolen);
1161 *recv_bytes = foolen;
1162
1163 // preserve any left-over unread amounts.
1164 int remainder = client->r_len - foolen;
1165 if (remainder > 0) {
1166 char* newbuf = malloc(remainder);
1167 memcpy(newbuf, client->recv_buffer + foolen, remainder);
1168 client->r_len = remainder;
1169 free(client->recv_buffer);
1170 client->recv_buffer = newbuf;
1171 } else {
1172 free(client->recv_buffer);
1173 client->recv_buffer = NULL;
1174 client->r_len = 0;
1175 }
1176 }
1177
1178 pthread_mutex_unlock(&client->mutex);
1179
1180 return 0;
1181}