summaryrefslogtreecommitdiffstats
path: root/iphone.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 /iphone.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 'iphone.c')
-rw-r--r--iphone.c1190
1 files changed, 0 insertions, 1190 deletions
diff --git a/iphone.c b/iphone.c
deleted file mode 100644
index cd91b2e..0000000
--- a/iphone.c
+++ /dev/null
@@ -1,1190 +0,0 @@
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 "iphone.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 iPhone. It keeps sending back 512 and seems to drop off a cliff
42// when the phone gets overwhelmed. In addition, the phone 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 phone 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 iphone_device_int {
59 char *buffer;
60 struct usb_dev_handle *device;
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 iphone_umux_client_int {
78 usbmux_tcp_header *header;
79 iphone_device_t phone;
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 phone.
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 iphone_error_t error;
102
103 int cleanup;
104};
105
106
107static pthread_mutex_t iphonemutex = PTHREAD_MUTEX_INITIALIZER;
108static iphone_umux_client_t *connlist = NULL;
109static int clients = 0;
110
111
112/**
113 */
114int toto_debug = 0;
115
116void iphone_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
125 va_list args;
126 /* run the real fprintf */
127 va_start(args, format);
128
129 if (toto_debug)
130 vfprintf(stderr, format, args);
131
132 va_end(args);
133
134#endif
135}
136
137#ifdef DEBUG
138/**
139 * for debugging purposes.
140 */
141static void print_buffer(const char *data, const int length)
142{
143 if (toto_debug > 0) {
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}
173#endif
174
175void hton_header(usbmux_tcp_header *hdr)
176{
177 if (hdr) {
178 hdr->length = htonl(hdr->length);
179 hdr->scnt = htonl(hdr->scnt);
180 hdr->ocnt = htonl(hdr->ocnt);
181 hdr->length16 = htons(hdr->length16);
182 }
183}
184
185void ntoh_header(usbmux_tcp_header *hdr)
186{
187 if (hdr) {
188 hdr->length = ntohl(hdr->length);
189 hdr->scnt = ntohl(hdr->scnt);
190 hdr->ocnt = ntohl(hdr->ocnt);
191 hdr->length16 = ntohs(hdr->length16);
192 }
193}
194
195/** Creates a USBMux header containing version information
196 *
197 * @return A USBMux header
198 */
199usbmux_version_header *version_header()
200{
201 usbmux_version_header *version = (usbmux_version_header *) malloc(sizeof(usbmux_version_header));
202 version->type = 0;
203 version->length = htonl(20);
204 version->major = htonl(1);
205 version->minor = 0;
206 version->allnull = 0;
207 return version;
208}
209
210/**
211 * This function sets the configuration of the given device to 3
212 * and claims the interface 1. If usb_set_configuration fails, it detaches
213 * the kernel driver that blocks the device, and retries configuration.
214 *
215 * @param phone which device to configure
216 */
217static iphone_error_t iphone_config_usb_device(iphone_device_t phone)
218{
219 int ret;
220 int bytes;
221 char buf[512];
222
223#if 0
224 log_debug_msg("checking configuration...\n");
225 if (phone->__device->config->bConfigurationValue != 3) {
226 log_debug_msg("WARNING: usb device configuration is not 3 as expected!\n");
227 }
228
229 log_debug_msg("setting configuration...\n");
230 ret = usb_set_configuration(phone->device, 3);
231 if (ret != 0) {
232 log_debug_msg("Hm, usb_set_configuration returned %d: %s\n", ret, strerror(-ret));
233#if LIBUSB_HAS_GET_DRIVER_NP
234 log_debug_msg("trying to fix:\n");
235 log_debug_msg("-> detaching kernel driver... ");
236 ret = usb_detach_kernel_driver_np(phone->device, phone->__device->config->interface->altsetting->bInterfaceNumber);
237 if (ret != 0) {
238 log_debug_msg("usb_detach_kernel_driver_np returned %d: %s\n", ret, strerror(-ret));
239 } else {
240 log_debug_msg("done.\n");
241 log_debug_msg("setting configuration again... ");
242 ret = usb_set_configuration(phone->device, 3);
243 if (ret != 0) {
244 log_debug_msg("Error: usb_set_configuration returned %d: %s\n", ret, strerror(-ret));
245 log_debug_msg("--> trying to continue anyway...\n");
246 } else {
247 log_debug_msg("done.\n");
248 }
249 }
250#else
251 log_debug_msg("--> trying to continue anyway...\n");
252#endif
253 } else {
254 log_debug_msg("done.\n");
255 }
256#endif
257
258 log_debug_msg("claiming interface... ");
259 ret = usb_claim_interface(phone->device, 1);
260 if (ret != 0) {
261 log_debug_msg("Error: usb_claim_interface returned %d: %s\n", ret, strerror(-ret));
262 return IPHONE_E_NO_DEVICE;
263 } else {
264 log_debug_msg("done.\n");
265 }
266
267 do {
268 bytes = usb_bulk_read(phone->device, BULKIN, buf, 512, 800);
269 } while (bytes > 0);
270
271 return IPHONE_E_SUCCESS;
272}
273
274/**
275 * Given a USB bus and device number, returns a device handle to the iPhone on
276 * that bus. To aid compatibility with future devices, this function does not
277 * check the vendor and device IDs! To do that, you should use
278 * iphone_get_device() or a system-specific API (e.g. HAL).
279 *
280 * @param bus_n The USB bus number.
281 * @param dev_n The USB device number.
282 * @param device A pointer to a iphone_device_t, which must be set to NULL upon
283 * calling iphone_get_specific_device, which will be filled with a device
284 * descriptor on return.
285 * @return IPHONE_E_SUCCESS if ok, otherwise an error code.
286 */
287iphone_error_t iphone_get_specific_device(int bus_n, int dev_n, iphone_device_t * device)
288{
289 struct usb_bus *bus;
290 struct usb_device *dev;
291 usbmux_version_header *version;
292 int bytes = 0;
293
294 //check we can actually write in device
295 if (!device || (device && *device))
296 return IPHONE_E_INVALID_ARG;
297
298 iphone_device_t phone = (iphone_device_t) malloc(sizeof(struct iphone_device_int));
299
300 // Initialize the struct
301 phone->device = NULL;
302 phone->__device = NULL;
303 phone->buffer = NULL;
304
305 // don't forget these:
306 phone->usbReceive.buffer = NULL;
307 phone->usbReceive.leftover = 0;
308 phone->usbReceive.capacity = 0;
309
310 // Initialize libusb
311 usb_init();
312 usb_find_busses();
313 usb_find_devices();
314
315 // Set the device configuration
316 for (bus = usb_get_busses(); bus; bus = bus->next)
317 //if (bus->location == bus_n)
318 for (dev = bus->devices; dev != NULL; dev = dev->next)
319 if (dev->devnum == dev_n) {
320 phone->__device = dev;
321 phone->device = usb_open(phone->__device);
322 if (iphone_config_usb_device(phone) == IPHONE_E_SUCCESS) {
323 goto found;
324 }
325 }
326
327 iphone_free_device(phone);
328
329 log_debug_msg("iphone_get_specific_device: iPhone not found\n");
330 return IPHONE_E_NO_DEVICE;
331
332 found:
333 // Send the version command to the phone
334 version = version_header();
335 bytes = usb_bulk_write(phone->device, BULKOUT, (char *) version, sizeof(*version), 800);
336 if (bytes < 20) {
337 log_debug_msg("get_iPhone(): libusb did NOT send enough!\n");
338 if (bytes < 0) {
339 log_debug_msg("get_iPhone(): libusb gave me the error %d: %s (%s)\n",
340 bytes, usb_strerror(), strerror(-bytes));
341 }
342 }
343 // Read the phone's response
344 bytes = usb_bulk_read(phone->device, BULKIN, (char *) version, sizeof(*version), 800);
345
346 // Check for bad response
347 if (bytes < 20) {
348 free(version);
349 iphone_free_device(phone);
350 log_debug_msg("get_iPhone(): Invalid version message -- header too short.\n");
351 if (bytes < 0)
352 log_debug_msg("get_iPhone(): libusb error message %d: %s (%s)\n", bytes, usb_strerror(), strerror(-bytes));
353 return IPHONE_E_NOT_ENOUGH_DATA;
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("get_iPhone() success\n");
359 free(version);
360 *device = phone;
361 return IPHONE_E_SUCCESS;
362 } else {
363 // Bad header
364 iphone_free_device(phone);
365 free(version);
366 log_debug_msg("get_iPhone(): Received a bad header/invalid version number.");
367 return IPHONE_E_BAD_HEADER;
368 }
369
370 // If it got to this point it's gotta be bad
371 log_debug_msg("get_iPhone(): Unknown error.\n");
372 iphone_free_device(phone);
373 free(version);
374 return IPHONE_E_UNKNOWN_ERROR; // if it got to this point it's gotta be bad
375}
376
377/** Cleans up an iPhone structure, then frees the structure itself.
378 * This is a library-level function; deals directly with the iPhone to tear
379 * down relations, but otherwise is mostly internal.
380 *
381 * @param phone A pointer to an iPhone structure.
382 */
383iphone_error_t iphone_free_device(iphone_device_t device)
384{
385 char buf[512];
386 int bytes;
387
388 if (!device)
389 return IPHONE_E_INVALID_ARG;
390 iphone_error_t ret = IPHONE_E_UNKNOWN_ERROR;
391
392 if (device->device) {
393 do {
394 bytes = usb_bulk_read(device->device, BULKIN, buf, 512, 800);
395 } while (bytes > 0);
396 }
397
398 if (device->buffer) {
399 free(device->buffer);
400 }
401 if (device->usbReceive.buffer) {
402 free(device->usbReceive.buffer);
403 }
404 if (device->device) {
405 usb_release_interface(device->device, 1);
406 usb_close(device->device);
407 ret = IPHONE_E_SUCCESS;
408 }
409 free(device);
410
411 return ret;
412}
413
414
415
416/** Sends data to the phone
417 * This is a low-level (i.e. directly to phone) function.
418 *
419 * @param phone The iPhone to send data to
420 * @param data The data to send to the iPhone
421 * @param datalen The length of the data
422 * @return The number of bytes sent, or -ERRNO on error
423 */
424int send_to_phone(iphone_device_t phone, char *data, int datalen)
425{
426 if (!phone)
427 return -1;
428
429 int timeout = 1000;
430 int retrycount = 0;
431 int bytes = 0;
432
433#ifdef DEBUG
434 #ifdef DEBUG_MORE
435 printf("===============================\n%s: trying to send\n", __func__);
436 print_buffer(data, datalen);
437 printf("===============================\n");
438 #endif
439#endif
440 do {
441 if (retrycount > 3) {
442 log_debug_msg("EPIC FAIL! aborting on retry count overload.\n");
443 return -1;
444 }
445
446 bytes = usb_bulk_write(phone->device, BULKOUT, data, datalen, timeout);
447 if (bytes == -ETIMEDOUT) {
448 // timed out waiting for write.
449 log_debug_msg("usb_bulk_write timeout error.\n");
450 return bytes;
451 }
452 else if (bytes < 0) {
453 log_debug_msg("usb_bulk_write failed with error. err:%d (%s)(%s)\n", bytes, usb_strerror(), strerror(-bytes));
454 return -1;
455 }
456 else if (bytes == 0) {
457 log_debug_msg("usb_bulk_write sent nothing. retrying.\n");
458 timeout = timeout * 4;
459 retrycount++;
460 continue;
461 }
462 else if (bytes < datalen) {
463 log_debug_msg("usb_bulk_write failed to send full dataload. %d of %d\n", bytes, datalen);
464 timeout = timeout * 4;
465 retrycount++;
466 data += bytes;
467 datalen -= bytes;
468 continue;
469 }
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 phone\n", __func__);
478 print_buffer(data, bytes);
479 printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
480 }
481 }
482#endif
483 return bytes;
484}
485
486/** Receives data from the phone
487 * This function is a low-level (i.e. direct from iPhone) function.
488 *
489 * @param phone The iPhone 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_phone_timeout(iphone_device_t phone, char *data, int datalen, int timeoutmillis)
497{
498 if (!phone)
499 return -EINVAL;
500 //log_debug_msg("recv_from_phone(): attempting to receive %i bytes\n", datalen);
501
502 int bytes = usb_bulk_read(phone->device, 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, "recv_from_phone(): libusb gave me the error %d: %s (%s)\n", bytes, usb_strerror(), strerror(-bytes));
513 log_debug_msg("recv_from_phone(): libusb gave me the error %d: %s (%s)\n", 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 phone:\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(iphone_umux_client_t connection)
562{
563 iphone_umux_client_t *newlist = NULL;
564
565 pthread_mutex_lock(&iphonemutex);
566
567 // update the global list of connections
568 if (clients > 1) {
569 newlist = (iphone_umux_client_t *) malloc(sizeof(iphone_umux_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(&iphonemutex);
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(iphone_umux_client_t connection)
607{
608 pthread_mutex_lock(&iphonemutex);
609 iphone_umux_client_t *newlist =
610 (iphone_umux_client_t *) realloc(connlist, sizeof(iphone_umux_client_t) * (clients + 1));
611 newlist[clients] = connection;
612 connlist = newlist;
613 clients++;
614 pthread_mutex_unlock(&iphonemutex);
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(&iphonemutex);
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(&iphonemutex);
652
653 return newport;
654}
655
656/** Initializes a connection on phone, with source port s_port and destination port d_port
657 *
658 * @param device The iPhone 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 IPHONE_E_SUCCESS on success, an error code otherwise.
663 */
664iphone_error_t iphone_mux_new_client(iphone_device_t device, uint16_t src_port, uint16_t dst_port,
665 iphone_umux_client_t * client)
666{
667 if (!device || !dst_port)
668 return IPHONE_E_INVALID_ARG;
669
670 src_port = get_free_port();
671
672 if (!src_port) {
673 // this is a special case, if we get 0, this is not good, so
674 return -EISCONN; // TODO: error code suitable?
675 }
676
677 // Initialize connection stuff
678 iphone_umux_client_t new_connection = (iphone_umux_client_t) malloc(sizeof(struct iphone_umux_client_int));
679 new_connection->header = new_mux_packet(src_port, dst_port);
680
681 // send TCP syn
682 if (new_connection && new_connection->header) {
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->phone = 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 = IPHONE_E_SUCCESS;
698 new_connection->cleanup = 0;
699 hton_header(new_connection->header);
700 log_debug_msg("%s: send_to_phone (%d --> %d)\n", __func__, ntohs(new_connection->header->sport), ntohs(new_connection->header->dport));
701 if (send_to_phone(device, (char *) new_connection->header, sizeof(usbmux_tcp_header)) >= 0) {
702 *client = new_connection;
703 return IPHONE_E_SUCCESS;
704 } else {
705 delete_connection(new_connection);
706 return IPHONE_E_NOT_ENOUGH_DATA;
707 }
708 }
709 // if we get to this point it's probably bad
710 return IPHONE_E_UNKNOWN_ERROR;
711}
712
713/** Cleans up the given USBMux connection.
714 * @note Once a connection is closed it may not be used again.
715 *
716 * @param connection The connection to close.
717 *
718 * @return IPHONE_E_SUCCESS on success.
719 */
720iphone_error_t iphone_mux_free_client(iphone_umux_client_t client)
721{
722 if (!client || !client->phone)
723 return IPHONE_E_INVALID_ARG;
724
725 iphone_error_t result = IPHONE_E_SUCCESS;
726 pthread_mutex_lock(&client->mutex);
727 client->header->tcp_flags = TCP_FIN;
728 client->header->length = 0x1C;
729 client->header->window = 0;
730 client->header->length16 = 0x1C;
731 hton_header(client->header);
732
733 if (send_to_phone(client->phone, (char*)client->header, sizeof(usbmux_tcp_header)) < 0) {
734 log_debug_msg("%s: error sending TCP_FIN\n", __func__);
735 result = IPHONE_E_UNKNOWN_ERROR;
736 }
737
738 client->cleanup = 1;
739
740 // make sure we don't have any last-minute laggards waiting on this.
741 // I put it after the mutex unlock because we have cases where the
742 // conditional wait is dependent on re-grabbing that mutex.
743 pthread_cond_broadcast(&client->wait);
744 pthread_cond_destroy(&client->wait);
745 pthread_cond_broadcast(&client->wr_wait);
746 pthread_cond_destroy(&client->wr_wait);
747
748 pthread_mutex_unlock(&client->mutex);
749
750 return result;
751}
752
753/** Sends the given data over the selected connection.
754 *
755 * @param phone The iPhone to send to.
756 * @param client The client we're sending data on.
757 * @param data A pointer to the data to send.
758 * @param datalen How much data we're sending.
759 * @param sent_bytes The number of bytes sent, minus the header (28)
760 *
761 * @return IPHONE_E_SUCCESS on success.
762 */
763iphone_error_t iphone_mux_send(iphone_umux_client_t client, const char *data, uint32_t datalen, uint32_t * sent_bytes)
764{
765 if (!client->phone || !client || !sent_bytes)
766 return IPHONE_E_INVALID_ARG;
767
768 if (client->error != IPHONE_E_SUCCESS) {
769 return client->error;
770 }
771
772 *sent_bytes = 0;
773 pthread_mutex_lock(&client->mutex);
774
775 int sendresult = 0;
776 uint32_t blocksize = 0;
777 if (client->wr_window <= 0) {
778 struct timespec ts;
779 clock_gettime(CLOCK_REALTIME, &ts);
780 //ts.tv_sec += 1;
781 ts.tv_nsec += 750 * 1000;
782 if (pthread_cond_timedwait(&client->wait, &client->mutex, &ts) == ETIMEDOUT) {
783 // timd out. optimistically grow the window and try to make progress
784 client->wr_window += WINDOW_INCREMENT;
785 }
786 }
787
788 blocksize = sizeof(usbmux_tcp_header) + datalen;
789
790 // client->scnt and client->ocnt should already be in host notation...
791 // we don't need to change them juuuust yet.
792 char *buffer = (char *) malloc(blocksize + 2); // allow 2 bytes of safety padding
793 // Set the length
794 client->header->length = blocksize;
795 client->header->length16 = blocksize;
796
797 // Put header into big-endian notation
798 hton_header(client->header);
799 // Concatenation of stuff in the buffer.
800 memcpy(buffer, client->header, sizeof(usbmux_tcp_header));
801 memcpy(buffer + sizeof(usbmux_tcp_header), data, datalen);
802
803 log_debug_msg("%s: send_to_phone(%d --> %d)\n", __func__, ntohs(client->header->sport), ntohs(client->header->dport));
804 sendresult = send_to_phone(client->phone, buffer, blocksize);
805 // Now that we've sent it off, we can clean up after our sloppy selves.
806 if (buffer)
807 free(buffer);
808
809 // revert header fields that have been swapped before trying to send
810 ntoh_header(client->header);
811
812 // update counts ONLY if the send succeeded.
813 if ((uint32_t)sendresult == blocksize) {
814 // Re-calculate scnt
815 client->header->scnt += datalen;
816 client->wr_window -= blocksize;
817 }
818
819
820 pthread_mutex_unlock(&client->mutex);
821
822
823 if (sendresult == -ETIMEDOUT || sendresult == 0) {
824 // no problem for now...
825 *sent_bytes = 0;
826 return IPHONE_E_TIMEOUT;
827 }
828 else if (sendresult < 0) {
829 return IPHONE_E_UNKNOWN_ERROR;
830 }
831 else if ((uint32_t)sendresult == blocksize) {
832 // actual number of data bytes sent.
833 *sent_bytes = sendresult - HEADERLEN;
834 return IPHONE_E_SUCCESS;
835 }
836 else {
837 fprintf(stderr, "usbsend managed to dump a packet that is not full size. %d of %d\n",
838 sendresult, blocksize);
839 return IPHONE_E_UNKNOWN_ERROR;
840 }
841}
842
843/** append the packet's DATA to the receive buffer for the client.
844 *
845 * this has a few other corner-case functions:
846 * 1. this will properly handle the handshake syn+ack.
847 * 2. for all receives, this will appropriately update the ocnt.
848 *
849 * @return number of bytes consumed (header + data)
850 */
851uint32_t append_receive_buffer(iphone_umux_client_t client, char* packet)
852{
853 if (client == NULL || packet == NULL) return 0;
854
855 usbmux_tcp_header *header = (usbmux_tcp_header *) packet;
856 char* data = &packet[HEADERLEN];
857 uint32_t packetlen = ntohl(header->length);
858 uint32_t datalen = packetlen-HEADERLEN;
859
860 int dobroadcast = 0;
861
862 pthread_mutex_lock(&client->mutex);
863
864 // we need to handle a few corner case tasks and book-keeping which
865 // falls on our responsibility because we are the ones reading in
866 // feedback.
867 if (client->header->scnt == 0 && client->header->ocnt == 0 ) {
868 log_debug_msg("client is still waiting for handshake.\n");
869 if (header->tcp_flags == (TCP_SYN | TCP_ACK)) {
870 log_debug_msg("yes, got syn+ack ; replying with ack.\n");
871 client->header->tcp_flags = TCP_ACK;
872 client->header->length = sizeof(usbmux_tcp_header);
873 client->header->length16 = sizeof(usbmux_tcp_header);
874 client->header->scnt += 1;
875 client->header->ocnt = header->ocnt;
876 hton_header(client->header);
877 // push it to USB
878 // TODO: need to check for error in the send here.... :(
879 log_debug_msg("%s: send_to_phone (%d --> %d)\n", __func__, ntohs(client->header->sport), ntohs(client->header->dport));
880 if (send_to_phone(client->phone, (char *)client->header, sizeof(usbmux_tcp_header)) <= 0) {
881 log_debug_msg("%s: error when pushing to usb...\n", __func__);
882 }
883 // need to revert some of the fields back to host notation.
884 ntoh_header(client->header);
885 }
886 else {
887 client->error = IPHONE_E_ECONNABORTED;
888 // woah... this connection failed us.
889 // TODO: somehow signal that this stream is a no-go.
890 log_debug_msg("WOAH! client failed to get proper syn+ack.\n");
891 }
892 }
893
894 // update TCP counters and windows.
895 //
896 // save the window that we're getting from the USB device.
897 // apparently the window is bigger than just the 512 that's typically
898 // advertised. iTunes apparently shifts this value by 8 to get a much
899 // larger number.
900 if (header->tcp_flags & TCP_RST) {
901 client->error = IPHONE_E_ECONNRESET;
902
903 if (datalen > 0) {
904 char e_msg[128];
905 e_msg[0] = 0;
906 if (datalen > 1) {
907 memcpy(e_msg, data+1, datalen-1);
908 e_msg[datalen-1] = 0;
909 }
910 // fetch the message
911 switch(data[0]) {
912 case 0:
913 // this is not an error, it's just a status message.
914 log_debug_msg("received status message: %s\n", e_msg);
915 datalen = 0;
916 break;
917 case 1:
918 log_debug_msg("received error message: %s\n", e_msg);
919 datalen = 0;
920 break;
921 default:
922 log_debug_msg("received unknown message (type 0x%02x): %s\n", data[0], e_msg);
923 //datalen = 0; // <-- we let this commented out for testing
924 break;
925 }
926 } else {
927 log_debug_msg("peer sent connection reset. setting error: %d\n", client->error);
928 }
929 }
930
931 // the packet's ocnt tells us how much of our data the device has received.
932 if (header->tcp_flags & TCP_ACK) {
933
934 // this is a hacky magic number condition. it seems that once the window
935 // reported by the phone starts to drop below this number, we quickly fall
936 // into connection reset problems. Once we see the reported window size
937 // start falling off, cut off and wait for solid acks to come back.
938 if (ntohs(header->window) < 256)
939 client->wr_window = 0;
940
941 // check what just got acked.
942 if (ntohl(header->ocnt) < client->header->scnt) {
943 // we got some kind of ack, but it hasn't caught up with the
944 // pending that have been sent.
945 pthread_cond_broadcast(&client->wr_wait);
946 }
947 else if (ntohl(header->ocnt) > /*client->wr_pending_scnt*/ client->header->scnt) {
948 fprintf(stderr, "WTF?! acks overtook pending outstanding. %u,%u\n",
949 ntohl(header->ocnt), client->wr_pending_scnt);
950 }
951 else {
952 // reset the window
953 client->wr_window = WINDOW_MAX;
954 pthread_cond_broadcast(&client->wr_wait);
955 }
956 }
957
958 // the packet's scnt will be our new ocnt.
959 client->header->ocnt = ntohl(header->scnt);
960
961 // ensure there is enough space, either by first malloc or realloc
962 if (datalen > 0) {
963 log_debug_msg("%s: putting %d bytes into client's recv_buffer\n", __func__, datalen);
964 if (client->r_len == 0) dobroadcast = 1;
965
966 if (client->recv_buffer == NULL) {
967 client->recv_buffer = malloc(datalen);
968 client->r_len = 0;
969 }
970 else {
971 client->recv_buffer = realloc(client->recv_buffer, client->r_len + datalen);
972 }
973
974 memcpy(&client->recv_buffer[client->r_len], data, datalen);
975 client->r_len += datalen;
976 }
977
978 pthread_mutex_unlock(&client->mutex);
979
980 // I put this outside the mutex unlock just so that when the threads
981 // wake, we don't have to do another round of unlock+try to grab.
982 if (dobroadcast)
983 pthread_cond_broadcast(&client->wait);
984
985
986 return packetlen;
987}
988
989/** NOTE! THERE IS NO MUTEX LOCK IN THIS FUNCTION!
990 because we're only called from one location, pullbulk, where the lock
991 is already held.
992 */
993iphone_umux_client_t find_client(usbmux_tcp_header* recv_header)
994{
995 // remember, as we're looking for the client, the receive header is
996 // coming from the USB into our client. This means that when we check
997 // the src/dst ports, we need to reverse them.
998 iphone_umux_client_t retval = NULL;
999
1000 // just for debugging check, I'm going to convert the numbers to host-endian.
1001 uint16_t hsport = ntohs(recv_header->sport);
1002 uint16_t hdport = ntohs(recv_header->dport);
1003
1004 pthread_mutex_lock(&iphonemutex);
1005 int i;
1006 for (i = 0; i < clients; i++) {
1007 uint16_t csport = ntohs(connlist[i]->header->sport);
1008 uint16_t cdport = ntohs(connlist[i]->header->dport);
1009
1010 if (hsport == cdport && hdport == csport) {
1011 retval = connlist[i];
1012 break;
1013 }
1014 }
1015 pthread_mutex_unlock(&iphonemutex);
1016
1017 return retval;
1018}
1019
1020/** pull in a big USB bulk packet and distribute it to queues appropriately.
1021 */
1022int iphone_mux_pullbulk(iphone_device_t phone)
1023{
1024 if (!phone)
1025 return -EINVAL;
1026
1027 int res = 0;
1028 static const int DEFAULT_CAPACITY = 128*1024;
1029 if (phone->usbReceive.buffer == NULL) {
1030 phone->usbReceive.capacity = DEFAULT_CAPACITY;
1031 phone->usbReceive.buffer = malloc(phone->usbReceive.capacity);
1032 phone->usbReceive.leftover = 0;
1033 }
1034
1035 // start the cursor off just ahead of the leftover.
1036 char* cursor = &phone->usbReceive.buffer[phone->usbReceive.leftover];
1037 // pull in content, note that the amount we can pull is capacity minus leftover
1038 int readlen = recv_from_phone_timeout(phone, cursor, phone->usbReceive.capacity - phone->usbReceive.leftover, 3000);
1039 if (readlen < 0) {
1040 res = readlen;
1041 //fprintf(stderr, "recv_from_phone_timeout gave us an error.\n");
1042 readlen = 0;
1043 }
1044 if (readlen > 0) {
1045 //fprintf(stdout, "recv_from_phone_timeout pulled an extra %d bytes\n", readlen);
1046 }
1047
1048 // the amount of content we have to work with is the remainder plus
1049 // what we managed to read
1050 phone->usbReceive.leftover += readlen;
1051
1052 // reset the cursor to the front of that buffer and work through
1053 // trying to decode packets out of them.
1054 cursor = phone->usbReceive.buffer;
1055 while (1) {
1056 // check if there's even sufficient data to decode a header
1057 if (phone->usbReceive.leftover < HEADERLEN) break;
1058 usbmux_tcp_header *header = (usbmux_tcp_header *) cursor;
1059
1060 log_debug_msg("%s: recv_from_phone_timeout (%d --> %d)\n", __func__, ntohs(header->sport), ntohs(header->dport));
1061
1062 // now that we have a header, check if there is sufficient data
1063 // to construct a full packet, including its data
1064 uint32_t packetlen = ntohl(header->length);
1065 if ((uint32_t)phone->usbReceive.leftover < packetlen) {
1066 fprintf(stderr, "%s: not enough data to construct a full packet\n", __func__);
1067 break;
1068 }
1069
1070 // ok... find the client this packet will get stuffed to.
1071 iphone_umux_client_t client = find_client(header);
1072 if (client == NULL) {
1073 log_debug_msg("WARNING: client for packet cannot be found. dropping packet.\n");
1074 }
1075 else {
1076 // stuff the data
1077 log_debug_msg("%s: found client, calling append_receive_buffer\n", __func__);
1078 append_receive_buffer(client, cursor);
1079
1080 // perhaps this is too general, == IPHONE_E_ECONNRESET
1081 // might be a better check here
1082 if (client->error != IPHONE_E_SUCCESS) {
1083 pthread_mutex_lock(&client->mutex);
1084 if (client->cleanup) {
1085 pthread_mutex_unlock(&client->mutex);
1086 log_debug_msg("freeing up connection (%d->%d)\n", ntohs(client->header->sport), ntohs(client->header->dport));
1087 delete_connection(client);
1088 } else {
1089 pthread_mutex_unlock(&client->mutex);
1090 }
1091 }
1092 }
1093
1094 // move the cursor and account for the consumption
1095 cursor += packetlen;
1096 phone->usbReceive.leftover -= packetlen;
1097 }
1098
1099 // now, we need to manage any leftovers.
1100 // I'm going to manage the leftovers by alloc'ing a new block and copying
1101 // the leftovers to it. This is just to prevent problems with memory
1102 // moves where there may be overlap. Besides, the leftovers should be
1103 // small enough that this copy is minimal in overhead.
1104 //
1105 // if there are no leftovers, we just leave the datastructure as is,
1106 // and re-use the block next time.
1107 if (phone->usbReceive.leftover > 0 && cursor != phone->usbReceive.buffer) {
1108 log_debug_msg("%s: we got a leftover, so handle it\n", __func__);
1109 char* newbuff = malloc(DEFAULT_CAPACITY);
1110 memcpy(newbuff, cursor, phone->usbReceive.leftover);
1111 free(phone->usbReceive.buffer);
1112 phone->usbReceive.buffer = newbuff;
1113 phone->usbReceive.capacity = DEFAULT_CAPACITY;
1114 }
1115
1116 return res;
1117}
1118
1119/**
1120 * return the error code stored in iphone_umux_client_t structure,
1121 * e.g. non-zero when an usb read error occurs.
1122 *
1123 * @param client the umux client
1124 *
1125 * @return IPHONE_E_* error codes.
1126 */
1127iphone_error_t iphone_mux_get_error(iphone_umux_client_t client)
1128{
1129 if (!client) {
1130 return 0;
1131 }
1132
1133 return client->error;
1134}
1135
1136/** This function reads from the client's recv_buffer.
1137 *
1138 * @param client The client to receive data from.
1139 * @param data Where to put the data we receive.
1140 * @param datalen How much data to read.
1141 * @param timeout How many milliseconds to wait for data
1142 *
1143 * @return IPHONE_E_SUCCESS or error code if failure.
1144 */
1145iphone_error_t iphone_mux_recv_timeout(iphone_umux_client_t client, char *data, uint32_t datalen, uint32_t * recv_bytes, int timeout)
1146{
1147
1148 if (!client || !data || datalen == 0 || !recv_bytes)
1149 return IPHONE_E_INVALID_ARG;
1150
1151 if (client->error != IPHONE_E_SUCCESS) return client->error;
1152
1153 pthread_mutex_lock(&client->mutex);
1154
1155 if (timeout > 0 && (client->recv_buffer == NULL ||client->r_len == 0)) {
1156 struct timespec ts;
1157 clock_gettime(CLOCK_REALTIME, &ts);
1158 ts.tv_sec += timeout/1000;
1159 ts.tv_nsec += (timeout-((int)(timeout/1000))*1000)*1000; //millis * 1000;
1160 pthread_cond_timedwait(&client->wait, &client->mutex, &ts);
1161 }
1162
1163 *recv_bytes = 0;
1164 if (client->recv_buffer != NULL && client->r_len > 0) {
1165 uint32_t foolen = datalen;
1166 if ((int)foolen > client->r_len) foolen = client->r_len;
1167 memcpy(data, client->recv_buffer, foolen);
1168 *recv_bytes = foolen;
1169
1170 // preserve any left-over unread amounts.
1171 int remainder = client->r_len - foolen;
1172 if (remainder > 0) {
1173 char* newbuf = malloc(remainder);
1174 memcpy(newbuf, client->recv_buffer + foolen, remainder);
1175 client->r_len = remainder;
1176 free(client->recv_buffer);
1177 client->recv_buffer = newbuf;
1178 }
1179 else {
1180 free(client->recv_buffer);
1181 client->recv_buffer = NULL;
1182 client->r_len = 0;
1183 }
1184 }
1185
1186 pthread_mutex_unlock(&client->mutex);
1187
1188
1189 return IPHONE_E_SUCCESS;
1190}