Debian Codegraph @

src/libusbmuxd.c

raw
1 /*
2 * libusbmuxd.c
3 *
4 * Copyright (C) 2009-2019 Nikias Bassen <[email protected]>
5 * Copyright (C) 2009-2014 Martin Szulecki <[email protected]>
6 * Copyright (C) 2009 Paul Sladen <[email protected]>
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <stdio.h>
30 #include <string.h>
31
32 #ifdef LIBUSBMUXD_STATIC
33 #define USBMUXD_API
34 #elif defined(_WIN32)
35 #define USBMUXD_API __declspec( dllexport )
36 #else
37 #if __GNUC__ >= 4
38 #define USBMUXD_API __attribute__((visibility("default")))
39 #else
40 #define USBMUXD_API
41 #endif
42 #endif
43
44 #ifndef EPROTO
45 #define EPROTO 134
46 #endif
47 #ifndef EBADMSG
48 #define EBADMSG 104
49 #endif
50 #ifndef ECONNREFUSED
51 #define ECONNREFUSED 107
52 #endif
53
54 #ifdef _WIN32
55 #include <winsock2.h>
56 #include <windows.h>
57 #define sleep(x) Sleep(x*1000)
58 #else
59 #include <unistd.h>
60 #include <signal.h>
61 #include <sys/socket.h>
62 #include <arpa/inet.h>
63 #if defined(HAVE_PROGRAM_INVOCATION_SHORT_NAME) && !defined(HAVE_PROGRAM_INVOCATION_SHORT_NAME_ERRNO_H)
64 extern char *program_invocation_short_name;
65 #endif
66 #ifdef __APPLE__
67 extern int _NSGetExecutablePath(char* buf, uint32_t* bufsize);
68 #include <sys/stat.h>
69 #endif
70 #endif
71
72 #ifdef HAVE_INOTIFY
73 #include <sys/inotify.h>
74 #include <sys/select.h>
75 #include <pthread.h>
76 #define EVENT_SIZE (sizeof (struct inotify_event))
77 #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
78 #define USBMUXD_DIRNAME "/var/run"
79 #define USBMUXD_SOCKET_NAME "usbmuxd"
80 static int use_inotify = 1;
81 #endif /* HAVE_INOTIFY */
82
83 #ifndef HAVE_STPNCPY
84 static char* stpncpy(char *dst, const char *src, size_t len)
85 {
86 size_t n = strlen(src);
87 if (n > len)
88 n = len;
89 return strncpy(dst, src, len) + n;
90 }
91 #endif
92
93 #ifdef _MSC_VER
94 #define strcasecmp _stricmp
95 #endif
96
97 #include <plist/plist.h>
98 #define PLIST_LIBUSBMUX_VERSION 3
99
100 static char *bundle_id = NULL;
101 static char *prog_name = NULL;
102
103 // usbmuxd public interface
104 #include "usbmuxd.h"
105 // usbmuxd protocol
106 #include "usbmuxd-proto.h"
107 // socket utility functions
108 #include <libimobiledevice-glue/socket.h>
109 // misc utility functions
110 #include <libimobiledevice-glue/collection.h>
111 // threads
112 #include <libimobiledevice-glue/thread.h>
113
114 static int libusbmuxd_debug = 0;
115 #ifndef PACKAGE
116 #define PACKAGE "libusbmuxd"
117 #endif
118 #ifndef PACKAGE_NAME
119 #define PACKAGE_NAME PACKAGE
120 #endif
121 #define LIBUSBMUXD_DEBUG(level, format, ...) if (level <= libusbmuxd_debug) fprintf(stderr, ("[" PACKAGE "] " format), __VA_ARGS__); fflush(stderr);
122 #define LIBUSBMUXD_ERROR(format, ...) LIBUSBMUXD_DEBUG(0, format, __VA_ARGS__)
123
124 static struct collection devices;
125 static THREAD_T devmon = THREAD_T_NULL;
126 static int listenfd = -1;
127 static int running = 0;
128 static int cancelling = 0;
129
130 static volatile int use_tag = 0;
131 static volatile int proto_version = 1;
132 static volatile int try_list_devices = 1;
133
134 struct usbmuxd_subscription_context {
135 usbmuxd_event_cb_t callback;
136 void *user_data;
137 };
138
139 static struct usbmuxd_subscription_context *event_ctx = NULL;
140
141 static struct collection listeners;
142 thread_once_t listener_init_once = THREAD_ONCE_INIT;
143 mutex_t listener_mutex;
144
145 /**
146 * Finds a device info record by its handle.
147 * if the record is not found, NULL is returned.
148 */
149 static usbmuxd_device_info_t *devices_find(uint32_t handle)
150 {
151 FOREACH(usbmuxd_device_info_t *dev, &devices) {
152 if (dev && dev->handle == handle) {
153 return dev;
154 }
155 } ENDFOREACH
156 return NULL;
157 }
158
159 /**
160 * Creates a socket connection to usbmuxd.
161 * For Mac/Linux it is a unix domain socket,
162 * for Windows it is a tcp socket.
163 */
164 static int connect_usbmuxd_socket()
165 {
166 int res = -1;
167 char *usbmuxd_socket_addr = getenv("USBMUXD_SOCKET_ADDRESS");
168 if (usbmuxd_socket_addr) {
169 if (strncmp(usbmuxd_socket_addr, "UNIX:", 5) == 0) {
170 #if defined(_WIN32) || defined(__CYGWIN__)
171 /* not supported, ignore */
172 #else
173 if (usbmuxd_socket_addr[5] != '\0') {
174 res = socket_connect_unix(usbmuxd_socket_addr+5);
175 if (res < 0) {
176 res = -errno;
177 }
178 return res;
179 }
180 #endif
181 } else {
182 uint16_t port = 0;
183 char *p = strrchr(usbmuxd_socket_addr, ':');
184 if (p) {
185 char *endp = NULL;
186 long l_port = strtol(p+1, &endp, 10);
187 if (endp && *endp == '\0') {
188 if (l_port > 0 && l_port < 65536) {
189 port = (uint16_t)l_port;
190 }
191 }
192 }
193 if (p && port > 0) {
194 char *connect_addr = NULL;
195 if (usbmuxd_socket_addr[0] == '[') {
196 connect_addr = strdup(usbmuxd_socket_addr+1);
197 connect_addr[p - usbmuxd_socket_addr - 1] = '\0';
198 p = strrchr(connect_addr, ']');
199 if (p) {
200 *p = '\0';
201 }
202 } else {
203 connect_addr = strdup(usbmuxd_socket_addr);
204 connect_addr[p - usbmuxd_socket_addr] = '\0';
205 }
206 if (connect_addr && *connect_addr != '\0') {
207 res = socket_connect(connect_addr, port);
208 #ifdef HAVE_INOTIFY
209 use_inotify = 0;
210 #endif
211 free(connect_addr);
212 if (res < 0) {
213 res = -errno;
214 }
215 return res;
216 }
217 free(connect_addr);
218 }
219 }
220 }
221 #if defined(_WIN32) || defined(__CYGWIN__)
222 res = socket_connect("127.0.0.1", USBMUXD_SOCKET_PORT);
223 #else
224 res = socket_connect_unix(USBMUXD_SOCKET_FILE);
225 #endif
226 if (res < 0) {
227 res = -errno;
228 }
229 return res;
230 }
231
232 static void sanitize_udid(usbmuxd_device_info_t *devinfo)
233 {
234 if (!devinfo)
235 return;
236 if (strlen(devinfo->udid) == 24) {
237 memmove(&devinfo->udid[9], &devinfo->udid[8], 17);
238 devinfo->udid[8] = '-';
239 }
240 if (strcasecmp(devinfo->udid, "ffffffffffffffffffffffffffffffffffffffff") == 0) {
241 sprintf(devinfo->udid + 32, "%08x", devinfo->handle);
242 }
243 }
244
245 static usbmuxd_device_info_t *device_info_from_plist(plist_t props)
246 {
247 usbmuxd_device_info_t* devinfo = NULL;
248 plist_t n = NULL;
249 uint64_t val = 0;
250 char *strval = NULL;
251
252 devinfo = (usbmuxd_device_info_t*)malloc(sizeof(usbmuxd_device_info_t));
253 if (!devinfo)
254 return NULL;
255 memset(devinfo, 0, sizeof(usbmuxd_device_info_t));
256
257 n = plist_dict_get_item(props, "DeviceID");
258 if (n && plist_get_node_type(n) == PLIST_UINT) {
259 plist_get_uint_val(n, &val);
260 devinfo->handle = (uint32_t)val;
261 }
262
263 n = plist_dict_get_item(props, "ProductID");
264 if (n && plist_get_node_type(n) == PLIST_UINT) {
265 plist_get_uint_val(n, &val);
266 devinfo->product_id = (uint32_t)val;
267 }
268
269 n = plist_dict_get_item(props, "SerialNumber");
270 if (n && plist_get_node_type(n) == PLIST_STRING) {
271 plist_get_string_val(n, &strval);
272 if (strval) {
273 char *t = stpncpy(devinfo->udid, strval, sizeof(devinfo->udid)-1);
274 *t = '\0';
275 sanitize_udid(devinfo);
276 free(strval);
277 }
278 }
279
280 n = plist_dict_get_item(props, "ConnectionType");
281 if (n && plist_get_node_type(n) == PLIST_STRING) {
282 plist_get_string_val(n, &strval);
283 if (strval) {
284 if (strcmp(strval, "USB") == 0) {
285 devinfo->conn_type = CONNECTION_TYPE_USB;
286 } else if (strcmp(strval, "Network") == 0) {
287 devinfo->conn_type = CONNECTION_TYPE_NETWORK;
288 n = plist_dict_get_item(props, "NetworkAddress");
289 if (n && plist_get_node_type(n) == PLIST_DATA) {
290 uint64_t addr_len = 0;
291 const char *netaddr = plist_get_data_ptr(n, &addr_len);
292 if (netaddr && addr_len > 0 && addr_len < sizeof(devinfo->conn_data)) {
293 memcpy(devinfo->conn_data, netaddr, addr_len);
294 }
295 }
296 } else {
297 LIBUSBMUXD_ERROR("%s: Unexpected ConnectionType '%s'\n", __func__, strval);
298 }
299 free(strval);
300 }
301 }
302
303 if (!devinfo->udid[0]) {
304 LIBUSBMUXD_ERROR("%s: Failed to get SerialNumber (UDID)!\n", __func__);
305 free(devinfo);
306 return NULL;
307 }
308 if (!devinfo->conn_type) {
309 LIBUSBMUXD_ERROR("%s: Failed to get ConnectionType!\n", __func__);
310 free(devinfo);
311 devinfo = NULL;
312 } else if (devinfo->conn_type == CONNECTION_TYPE_NETWORK && !devinfo->conn_data[0]) {
313 LIBUSBMUXD_ERROR("%s: Failed to get EscapedFullServiceName!\n", __func__);
314 free(devinfo);
315 devinfo = NULL;
316 }
317
318 return devinfo;
319 }
320
321 static usbmuxd_device_info_t *device_info_from_device_record(struct usbmuxd_device_record *dev)
322 {
323 if (!dev) {
324 return NULL;
325 }
326 usbmuxd_device_info_t *devinfo = (usbmuxd_device_info_t*)malloc(sizeof(usbmuxd_device_info_t));
327 if (!devinfo) {
328 LIBUSBMUXD_ERROR("%s: Out of memory while allocating device info object\n", __func__);
329 return NULL;
330 }
331
332 devinfo->handle = dev->device_id;
333 devinfo->product_id = dev->product_id;
334 char *t = stpncpy(devinfo->udid, dev->serial_number, sizeof(devinfo->udid)-2);
335 *t = '\0';
336 sanitize_udid(devinfo);
337
338 return devinfo;
339 }
340
341 static int receive_packet(int sfd, struct usbmuxd_header *header, void **payload, int timeout)
342 {
343 int recv_len;
344 struct usbmuxd_header hdr;
345 char *payload_loc = NULL;
346
347 header->length = 0;
348 header->version = 0;
349 header->message = 0;
350 header->tag = 0;
351
352 recv_len = socket_receive_timeout(sfd, &hdr, sizeof(hdr), 0, timeout);
353 if (recv_len < 0) {
354 if (!cancelling) {
355 LIBUSBMUXD_DEBUG(1, "%s: Error receiving packet: %s\n", __func__, strerror(-recv_len));
356 }
357 return recv_len;
358 }
359
360 if ((size_t)recv_len < sizeof(hdr)) {
361 LIBUSBMUXD_DEBUG(1, "%s: Received packet is too small, got %d bytes!\n", __func__, recv_len);
362 return recv_len;
363 }
364
365 uint32_t payload_size = hdr.length - sizeof(hdr);
366 if (payload_size > 0) {
367 payload_loc = (char*)malloc(payload_size);
368 uint32_t rsize = 0;
369 do {
370 int res = socket_receive_timeout(sfd, payload_loc + rsize, payload_size - rsize, 0, 5000);
371 if (res < 0) {
372 break;
373 }
374 rsize += res;
375 } while (rsize < payload_size);
376 if (rsize != payload_size) {
377 LIBUSBMUXD_DEBUG(1, "%s: Error receiving payload of size %d (bytes received: %d)\n", __func__, payload_size, rsize);
378 free(payload_loc);
379 return -EBADMSG;
380 }
381 }
382
383 if (hdr.message == MESSAGE_PLIST) {
384 char *message = NULL;
385 plist_t plist = NULL;
386 plist_from_xml(payload_loc, payload_size, &plist);
387 free(payload_loc);
388
389 if (!plist) {
390 LIBUSBMUXD_DEBUG(1, "%s: Error getting plist from payload!\n", __func__);
391 return -EBADMSG;
392 }
393
394 plist_t node = plist_dict_get_item(plist, "MessageType");
395 if (!node || plist_get_node_type(node) != PLIST_STRING) {
396 *payload = plist;
397 hdr.length = sizeof(hdr);
398 memcpy(header, &hdr, sizeof(hdr));
399 return hdr.length;
400 }
401
402 plist_get_string_val(node, &message);
403 if (message) {
404 uint64_t val = 0;
405 if (strcmp(message, "Result") == 0) {
406 /* result message */
407 uint32_t dwval = 0;
408 plist_t n = plist_dict_get_item(plist, "Number");
409 plist_get_uint_val(n, &val);
410 *payload = malloc(sizeof(uint32_t));
411 dwval = val;
412 memcpy(*payload, &dwval, sizeof(dwval));
413 hdr.length = sizeof(hdr) + sizeof(dwval);
414 hdr.message = MESSAGE_RESULT;
415 } else if (strcmp(message, "Attached") == 0) {
416 /* device add message */
417 usbmuxd_device_info_t *devinfo = NULL;
418 plist_t props = plist_dict_get_item(plist, "Properties");
419 if (!props) {
420 LIBUSBMUXD_DEBUG(1, "%s: Could not get properties for message '%s' from plist!\n", __func__, message);
421 free(message);
422 plist_free(plist);
423 return -EBADMSG;
424 }
425
426 devinfo = device_info_from_plist(props);
427 if (!devinfo) {
428 LIBUSBMUXD_DEBUG(1, "%s: Could not create device info object from properties!\n", __func__);
429 free(message);
430 plist_free(plist);
431 return -EBADMSG;
432 }
433 *payload = (void*)devinfo;
434 hdr.length = sizeof(hdr) + sizeof(usbmuxd_device_info_t);
435 hdr.message = MESSAGE_DEVICE_ADD;
436 } else if (strcmp(message, "Detached") == 0) {
437 /* device remove message */
438 uint32_t dwval = 0;
439 plist_t n = plist_dict_get_item(plist, "DeviceID");
440 if (n) {
441 plist_get_uint_val(n, &val);
442 *payload = malloc(sizeof(uint32_t));
443 dwval = val;
444 memcpy(*payload, &dwval, sizeof(dwval));
445 hdr.length = sizeof(hdr) + sizeof(dwval);
446 hdr.message = MESSAGE_DEVICE_REMOVE;
447 }
448 } else if (strcmp(message, "Paired") == 0) {
449 /* device pair message */
450 uint32_t dwval = 0;
451 plist_t n = plist_dict_get_item(plist, "DeviceID");
452 if (n) {
453 plist_get_uint_val(n, &val);
454 *payload = malloc(sizeof(uint32_t));
455 dwval = val;
456 memcpy(*payload, &dwval, sizeof(dwval));
457 hdr.length = sizeof(hdr) + sizeof(dwval);
458 hdr.message = MESSAGE_DEVICE_PAIRED;
459 }
460 } else {
461 char *xml = NULL;
462 uint32_t len = 0;
463 plist_to_xml(plist, &xml, &len);
464 LIBUSBMUXD_DEBUG(1, "%s: Unexpected message '%s' in plist:\n%s\n", __func__, message, xml);
465 free(xml);
466 free(message);
467 plist_free(plist);
468 return -EBADMSG;
469 }
470 free(message);
471 }
472 plist_free(plist);
473 } else if (hdr.message == MESSAGE_DEVICE_ADD) {
474 usbmuxd_device_info_t *devinfo = device_info_from_device_record((struct usbmuxd_device_record*)payload_loc);
475 free(payload_loc);
476 *payload = devinfo;
477 } else {
478 *payload = payload_loc;
479 }
480
481 memcpy(header, &hdr, sizeof(hdr));
482
483 return hdr.length;
484 }
485
486 /**
487 * Retrieves the result code to a previously sent request.
488 */
489 static int usbmuxd_get_result(int sfd, uint32_t tag, uint32_t *result, void **result_plist)
490 {
491 struct usbmuxd_header hdr;
492 int recv_len;
493 uint32_t *res = NULL;
494
495 if (!result) {
496 return -EINVAL;
497 }
498 *result = -1;
499 if (result_plist) {
500 *result_plist = NULL;
501 }
502
503 recv_len = receive_packet(sfd, &hdr, (void**)&res, 5000);
504 if (recv_len < 0 || (size_t)recv_len < sizeof(hdr)) {
505 free(res);
506 return (recv_len < 0 ? recv_len : -EPROTO);
507 }
508
509 if (hdr.message == MESSAGE_RESULT) {
510 int ret = 0;
511 if (hdr.tag != tag) {
512 LIBUSBMUXD_DEBUG(1, "%s: WARNING: tag mismatch (%d != %d). Proceeding anyway.\n", __func__, hdr.tag, tag);
513 }
514 if (res) {
515 memcpy(result, res, sizeof(uint32_t));
516 ret = 1;
517 }
518 free(res);
519 return ret;
520 }
521
522 if (hdr.message == MESSAGE_PLIST) {
523 if (!result_plist) {
524 LIBUSBMUXD_DEBUG(1, "%s: MESSAGE_PLIST result but result_plist pointer is NULL!\n", __func__);
525 return -1;
526 }
527 *result_plist = (plist_t)res;
528 *result = RESULT_OK;
529 return 1;
530 }
531
532 LIBUSBMUXD_DEBUG(1, "%s: Unexpected message of type %d received!\n", __func__, hdr.message);
533 free(res);
534 return -EPROTO;
535 }
536
537 static int send_packet(int sfd, uint32_t message, uint32_t tag, void *payload, uint32_t payload_size)
538 {
539 struct usbmuxd_header header;
540
541 header.length = sizeof(struct usbmuxd_header);
542 header.version = proto_version;
543 header.message = message;
544 header.tag = tag;
545 if (payload && (payload_size > 0)) {
546 header.length += payload_size;
547 }
548 int sent = socket_send(sfd, &header, sizeof(header));
549 if (sent != sizeof(header)) {
550 LIBUSBMUXD_DEBUG(1, "%s: ERROR: could not send packet header\n", __func__);
551 return -1;
552 }
553 if (payload && (payload_size > 0)) {
554 uint32_t ssize = 0;
555 do {
556 int res = socket_send(sfd, (char*)payload + ssize, payload_size - ssize);
557 if (res < 0) {
558 break;
559 }
560 ssize += res;
561 } while (ssize < payload_size);
562 sent += ssize;
563 }
564 if (sent != (int)header.length) {
565 LIBUSBMUXD_DEBUG(1, "%s: ERROR: could not send whole packet (sent %d of %d)\n", __func__, sent, header.length);
566 socket_close(sfd);
567 return -1;
568 }
569 return sent;
570 }
571
572 static int send_plist_packet(int sfd, uint32_t tag, plist_t message)
573 {
574 int res;
575 char *payload = NULL;
576 uint32_t payload_size = 0;
577
578 plist_to_xml(message, &payload, &payload_size);
579 res = send_packet(sfd, MESSAGE_PLIST, tag, payload, payload_size);
580 free(payload);
581
582 return res;
583 }
584
585 static void get_bundle_id()
586 {
587 #if defined (__APPLE__)
588 char CONTENTS_INFO_PLIST[] = "Contents/Info.plist";
589 char* execpath = malloc(1024);
590 uint32_t size = 1024;
591 if (_NSGetExecutablePath(execpath, &size) != 0) {
592 free(execpath);
593 return;
594 }
595 // strip off executable name
596 char *p = execpath + strlen(execpath) - 1;
597 while (p > execpath && *p != '/') p--;
598 if (*p == '/') *p = '\0';
599 // now walk back trying to find "/Contents/MacOS", and strip it off
600 int macos_found = 0;
601 while (p > execpath) {
602 p--;
603 if (*p != '/') continue;
604 if (strcmp(p, "/.") == 0) {
605 *p = '\0';
606 } else if (!macos_found && strcmp(p, "/MacOS") == 0) {
607 *p = '\0';
608 macos_found++;
609 } else if (macos_found && strcmp(p, "/Contents") == 0) {
610 *p = '\0';
611 break;
612 } else {
613 break;
614 }
615 }
616 // now just append "/Contents/Info.plist"
617 size_t len = strlen(execpath) + sizeof(CONTENTS_INFO_PLIST) + 1;
618 char *infopl = malloc(len);
619 snprintf(infopl, len, "%s/%s", execpath, CONTENTS_INFO_PLIST);
620 free(execpath);
621 struct stat fst;
622 fst.st_size = 0;
623 if (stat(infopl, &fst) != 0) {
624 free(infopl);
625 return;
626 }
627 size_t fsize = fst.st_size;
628 if (fsize < 8) {
629 free(infopl);
630 return;
631 }
632 FILE *f = fopen(infopl, "r");
633 free(infopl);
634 if (!f)
635 return;
636 char *buf = malloc(fsize);
637 if (!buf)
638 return;
639 if (fread(buf, 1, fsize, f) == fsize) {
640 plist_t pl = NULL;
641 if (memcmp(buf, "bplist00", 8) == 0) {
642 plist_from_bin(buf, fst.st_size, &pl);
643 } else {
644 plist_from_xml(buf, fst.st_size, &pl);
645 }
646 if (pl) {
647 plist_t bid = plist_dict_get_item(pl, "CFBundleIdentifier");
648 if (plist_get_node_type(bid) == PLIST_STRING) {
649 plist_get_string_val(bid, &bundle_id);
650 }
651 plist_free(pl);
652 }
653 }
654 free(buf);
655 fclose(f);
656 #endif
657 }
658
659 static void get_prog_name()
660 {
661 #if defined(__APPLE__) || defined(__FreeBSD__)
662 const char *pname = getprogname();
663 if (pname) {
664 prog_name = strdup(pname);
665 }
666 #elif defined (_WIN32)
667 TCHAR *_pname = malloc((MAX_PATH+1) * sizeof(TCHAR));
668 if (GetModuleFileName(NULL, _pname, MAX_PATH+1) > 0) {
669 char* pname = NULL;
670 #if defined(UNICODE) || defined(_UNICODE)
671 char* __pname = NULL;
672 int l = WideCharToMultiByte(CP_UTF8, 0, _pname, -1, NULL, 0, NULL, NULL);
673 if (l > 0) {
674 __pname = malloc(l);
675 if (WideCharToMultiByte(CP_UTF8, 0, _pname, -1, __pname, l, NULL, NULL) > 0) {
676 pname = __pname;
677 }
678 }
679 #else
680 pname = _pname;
681 #endif
682 if (pname) {
683 char *p = pname+strlen(pname)-1;
684 while (p > pname && *p != '\\' && *p != '/') p--;
685 if (*p == '\\' || *p == '/') p++;
686 prog_name = strdup(p);
687 }
688 #if defined(UNICODE) || defined(_UNICODE)
689 free(__pname);
690 #endif
691 }
692 free(_pname);
693 #elif defined (HAVE_PROGRAM_INVOCATION_SHORT_NAME)
694 char *pname = program_invocation_short_name;
695 if (pname) {
696 prog_name = strdup(pname);
697 }
698 #elif defined (__linux__)
699 FILE *f = fopen("/proc/self/stat", "r");
700 if (!f) {
701 return;
702 }
703 char *tmpbuf = malloc(512);
704 size_t r = fread(tmpbuf, 1, 512, f);
705 if (r > 0) {
706 char *p = tmpbuf;
707 while (((size_t)(p-tmpbuf) < r) && (*p != '(') && (*p != '\0')) p++;
708 if (*p == '(') {
709 p++;
710 char *pname = p;
711 while (((size_t)(p-tmpbuf) < r) && (*p != ')') && (*p != '\0')) p++;
712 if (*p == ')') {
713 *p = '\0';
714 prog_name = strdup(pname);
715 }
716 }
717 }
718 free(tmpbuf);
719 fclose(f);
720 #else
721 #warning FIXME: no method to determine program name
722 #endif
723 }
724
725 static plist_t create_plist_message(const char* message_type)
726 {
727 char client_version[128];
728 snprintf(client_version, 128, PACKAGE_NAME " %s", libusbmuxd_version());
729 if (!bundle_id) {
730 get_bundle_id();
731 }
732 if (!prog_name) {
733 get_prog_name();
734 }
735 plist_t plist = plist_new_dict();
736 if (bundle_id) {
737 plist_dict_set_item(plist, "BundleID", plist_new_string(bundle_id));
738 }
739 plist_dict_set_item(plist, "ClientVersionString", plist_new_string(client_version));
740 plist_dict_set_item(plist, "MessageType", plist_new_string(message_type));
741 if (prog_name) {
742 plist_dict_set_item(plist, "ProgName", plist_new_string(prog_name));
743 }
744 plist_dict_set_item(plist, "kLibUSBMuxVersion", plist_new_uint(PLIST_LIBUSBMUX_VERSION));
745 return plist;
746 }
747
748 static int send_listen_packet(int sfd, uint32_t tag)
749 {
750 int res = 0;
751 if (proto_version == 1) {
752 /* construct message plist */
753 plist_t plist = create_plist_message("Listen");
754
755 res = send_plist_packet(sfd, tag, plist);
756 plist_free(plist);
757 } else {
758 /* binary packet */
759 res = send_packet(sfd, MESSAGE_LISTEN, tag, NULL, 0);
760 }
761 return res;
762 }
763
764 static int send_connect_packet(int sfd, uint32_t tag, uint32_t device_id, uint16_t port)
765 {
766 int res = 0;
767 if (proto_version == 1) {
768 /* construct message plist */
769 plist_t plist = create_plist_message("Connect");
770 plist_dict_set_item(plist, "DeviceID", plist_new_uint(device_id));
771 plist_dict_set_item(plist, "PortNumber", plist_new_uint(htons(port)));
772
773 res = send_plist_packet(sfd, tag, plist);
774 plist_free(plist);
775 } else {
776 /* binary packet */
777 struct {
778 uint32_t device_id;
779 uint16_t port;
780 uint16_t reserved;
781 } conninfo;
782
783 conninfo.device_id = device_id;
784 conninfo.port = htons(port);
785 conninfo.reserved = 0;
786
787 res = send_packet(sfd, MESSAGE_CONNECT, tag, &conninfo, sizeof(conninfo));
788 }
789 return res;
790 }
791
792 static int send_list_devices_packet(int sfd, uint32_t tag)
793 {
794 int res = -1;
795
796 /* construct message plist */
797 plist_t plist = create_plist_message("ListDevices");
798
799 res = send_plist_packet(sfd, tag, plist);
800 plist_free(plist);
801
802 return res;
803 }
804
805 static int send_read_buid_packet(int sfd, uint32_t tag)
806 {
807 int res = -1;
808
809 /* construct message plist */
810 plist_t plist = create_plist_message("ReadBUID");
811
812 res = send_plist_packet(sfd, tag, plist);
813 plist_free(plist);
814
815 return res;
816 }
817
818 static int send_pair_record_packet(int sfd, uint32_t tag, const char* msgtype, const char* pair_record_id, uint32_t device_id, plist_t data)
819 {
820 int res = -1;
821
822 /* construct message plist */
823 plist_t plist = create_plist_message(msgtype);
824 plist_dict_set_item(plist, "PairRecordID", plist_new_string(pair_record_id));
825 if (data) {
826 plist_dict_set_item(plist, "PairRecordData", plist_copy(data));
827 }
828 if (device_id > 0) {
829 plist_dict_set_item(plist, "DeviceID", plist_new_uint(device_id));
830 }
831
832 res = send_plist_packet(sfd, tag, plist);
833 plist_free(plist);
834
835 return res;
836 }
837
838 /**
839 * Generates an event, i.e. calls the callback function.
840 * A reference to a populated usbmuxd_event_t with information about the event
841 * and the corresponding device will be passed to the callback function.
842 */
843 static void generate_event(const usbmuxd_device_info_t *dev, enum usbmuxd_event_type event)
844 {
845 usbmuxd_event_t ev;
846
847 if (!dev) {
848 return;
849 }
850
851 ev.event = event;
852 memcpy(&ev.device, dev, sizeof(usbmuxd_device_info_t));
853
854 mutex_lock(&listener_mutex);
855 FOREACH(struct usbmuxd_subscription_context* context, &listeners) {
856 context->callback(&ev, context->user_data);
857 } ENDFOREACH
858 mutex_unlock(&listener_mutex);
859 }
860
861 static int usbmuxd_listen_poll()
862 {
863 int sfd;
864
865 sfd = connect_usbmuxd_socket();
866 if (sfd < 0) {
867 while (1) {
868 mutex_lock(&listener_mutex);
869 int num = collection_count(&listeners);
870 mutex_unlock(&listener_mutex);
871 if (num <= 0) {
872 break;
873 }
874 if ((sfd = connect_usbmuxd_socket()) >= 0) {
875 break;
876 }
877 sleep(1);
878 }
879 }
880
881 return sfd;
882 }
883
884 #ifdef HAVE_INOTIFY
885 #ifndef HAVE_PSELECT
886 static int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask)
887 {
888 int ready;
889 struct timeval tv;
890 struct timeval *p_timeout;
891 sigset_t origmask;
892
893 if (timeout) {
894 tv.tv_sec = timeout->tv_sec;
895 tv.tv_usec = timeout->tv_nsec / 1000;
896 p_timeout = &tv;
897 } else {
898 p_timeout = NULL;
899 }
900
901 pthread_sigmask(SIG_SETMASK, sigmask, &origmask);
902 ready = select(nfds, readfds, writefds, exceptfds, p_timeout);
903 pthread_sigmask(SIG_SETMASK, &origmask, NULL);
904
905 return ready;
906 }
907 #endif
908
909 static int usbmuxd_listen_inotify()
910 {
911 int inot_fd;
912 int watch_d;
913 int sfd;
914
915 if (!use_inotify) {
916 return -2;
917 }
918
919 sfd = connect_usbmuxd_socket();
920 if (sfd >= 0)
921 return sfd;
922
923 sfd = -1;
924 inot_fd = inotify_init1(IN_CLOEXEC);
925 if (inot_fd < 0) {
926 LIBUSBMUXD_DEBUG(1, "%s: Failed to setup inotify\n", __func__);
927 return -2;
928 }
929
930 /* inotify is setup, listen for events that concern us */
931 watch_d = inotify_add_watch (inot_fd, USBMUXD_DIRNAME, IN_CREATE);
932 if (watch_d < 0) {
933 LIBUSBMUXD_DEBUG(1, "%s: Failed to setup watch descriptor for socket dir\n", __func__);
934 close (inot_fd);
935 return -2;
936 }
937
938 while (1) {
939 fd_set rfds;
940 struct timespec tv = {1, 0};
941
942 FD_ZERO(&rfds);
943 FD_SET(inot_fd, &rfds);
944 int r = pselect(inot_fd+1, &rfds, NULL, NULL, &tv, NULL);
945 if (r < 0) {
946 break;
947 }
948
949 if (r == 0) {
950 continue;
951 }
952
953 ssize_t len, i;
954 char buff[EVENT_BUF_LEN] = {0};
955
956 i = 0;
957 len = read (inot_fd, buff, EVENT_BUF_LEN -1);
958 if (len < 0)
959 goto end;
960 while (i < len) {
961 struct inotify_event *pevent = (struct inotify_event *) & buff[i];
962
963 /* check that it's ours */
964 if (pevent->mask & IN_CREATE &&
965 pevent->len &&
966 pevent->name[0] != 0 &&
967 strcmp(pevent->name, USBMUXD_SOCKET_NAME) == 0) {
968 /* retry if usbmuxd isn't ready yet */
969 int retry = 10;
970 while (--retry >= 0) {
971 if ((sfd = connect_usbmuxd_socket ()) >= 0) {
972 break;
973 }
974 sleep(1);
975 }
976 goto end;
977 }
978 i += EVENT_SIZE + pevent->len;
979 }
980 }
981
982 end:
983 inotify_rm_watch(inot_fd, watch_d);
984 close(inot_fd);
985
986 return sfd;
987 }
988 #endif /* HAVE_INOTIFY */
989
990 /**
991 * Tries to connect to usbmuxd and wait if it is not running.
992 */
993 static int usbmuxd_listen()
994 {
995 int sfd;
996 uint32_t res = -1;
997 int tag;
998
999 retry:
1000
1001 #ifdef HAVE_INOTIFY
1002 sfd = usbmuxd_listen_inotify();
1003 if (sfd == -2)
1004 sfd = usbmuxd_listen_poll();
1005 #else
1006 sfd = usbmuxd_listen_poll();
1007 #endif
1008
1009 if (sfd < 0) {
1010 if (!cancelling) {
1011 LIBUSBMUXD_DEBUG(1, "%s: ERROR: usbmuxd was supposed to be running here...\n", __func__);
1012 }
1013 return sfd;
1014 }
1015
1016 tag = ++use_tag;
1017 if (send_listen_packet(sfd, tag) <= 0) {
1018 LIBUSBMUXD_DEBUG(1, "%s: ERROR: could not send listen packet\n", __func__);
1019 socket_close(sfd);
1020 return -1;
1021 }
1022 if ((usbmuxd_get_result(sfd, tag, &res, NULL) == 1) && (res != 0)) {
1023 socket_close(sfd);
1024 if ((res == RESULT_BADVERSION) && (proto_version == 1)) {
1025 proto_version = 0;
1026 goto retry;
1027 }
1028 LIBUSBMUXD_DEBUG(1, "%s: ERROR: did not get OK but %d\n", __func__, res);
1029 return -1;
1030 }
1031 return sfd;
1032 }
1033
1034 /**
1035 * Waits for an event to occur, i.e. a packet coming from usbmuxd.
1036 * Calls generate_event to pass the event via callback to the client program.
1037 */
1038 static int get_next_event(int sfd)
1039 {
1040 struct usbmuxd_header hdr;
1041 void *payload = NULL;
1042
1043 /* block until we receive something */
1044 if (receive_packet(sfd, &hdr, &payload, 0) < 0) {
1045 if (!cancelling) {
1046 LIBUSBMUXD_DEBUG(1, "%s: Error in usbmuxd connection, disconnecting all devices!\n", __func__);
1047 }
1048 // when then usbmuxd connection fails,
1049 // generate remove events for every device that
1050 // is still present so applications know about it
1051 FOREACH(usbmuxd_device_info_t *dev, &devices) {
1052 generate_event(dev, UE_DEVICE_REMOVE);
1053 collection_remove(&devices, dev);
1054 free(dev);
1055 } ENDFOREACH
1056 return -EIO;
1057 }
1058
1059 if ((hdr.length > sizeof(hdr)) && !payload) {
1060 LIBUSBMUXD_DEBUG(1, "%s: Invalid packet received, payload is missing!\n", __func__);
1061 return -EBADMSG;
1062 }
1063
1064 if (hdr.message == MESSAGE_DEVICE_ADD) {
1065 usbmuxd_device_info_t *devinfo = (usbmuxd_device_info_t*)payload;
1066 collection_add(&devices, devinfo);
1067 generate_event(devinfo, UE_DEVICE_ADD);
1068 payload = NULL;
1069 } else if (hdr.message == MESSAGE_DEVICE_REMOVE) {
1070 uint32_t handle;
1071 usbmuxd_device_info_t *devinfo;
1072
1073 memcpy(&handle, payload, sizeof(uint32_t));
1074
1075 devinfo = devices_find(handle);
1076 if (!devinfo) {
1077 LIBUSBMUXD_DEBUG(1, "%s: WARNING: got device remove message for handle %d, but couldn't find the corresponding handle in the device list. This event will be ignored.\n", __func__, handle);
1078 } else {
1079 generate_event(devinfo, UE_DEVICE_REMOVE);
1080 collection_remove(&devices, devinfo);
1081 free(devinfo);
1082 }
1083 } else if (hdr.message == MESSAGE_DEVICE_PAIRED) {
1084 uint32_t handle;
1085 usbmuxd_device_info_t *devinfo;
1086
1087 memcpy(&handle, payload, sizeof(uint32_t));
1088
1089 devinfo = devices_find(handle);
1090 if (!devinfo) {
1091 LIBUSBMUXD_DEBUG(1, "%s: WARNING: got paired message for device handle %d, but couldn't find the corresponding handle in the device list. This event will be ignored.\n", __func__, handle);
1092 } else {
1093 generate_event(devinfo, UE_DEVICE_PAIRED);
1094 }
1095 } else if (hdr.length > 0) {
1096 LIBUSBMUXD_DEBUG(1, "%s: Unexpected message type %d length %d received!\n", __func__, hdr.message, hdr.length);
1097 }
1098 free(payload);
1099 return 0;
1100 }
1101
1102 static void device_monitor_cleanup(void* data)
1103 {
1104 FOREACH(usbmuxd_device_info_t *dev, &devices) {
1105 collection_remove(&devices, dev);
1106 free(dev);
1107 } ENDFOREACH
1108 collection_free(&devices);
1109
1110 socket_close(listenfd);
1111 listenfd = -1;
1112 }
1113
1114 /**
1115 * Device Monitor thread function.
1116 *
1117 * This function sets up a connection to usbmuxd
1118 */
1119 static void *device_monitor(void *data)
1120 {
1121 running = 1;
1122 collection_init(&devices);
1123 cancelling = 0;
1124
1125 #ifdef HAVE_THREAD_CLEANUP
1126 thread_cleanup_push(device_monitor_cleanup, NULL);
1127 #endif
1128 do {
1129
1130 listenfd = usbmuxd_listen();
1131 if (listenfd < 0) {
1132 continue;
1133 }
1134
1135 while (running) {
1136 int res = get_next_event(listenfd);
1137 if (res < 0) {
1138 break;
1139 }
1140 }
1141
1142 mutex_lock(&listener_mutex);
1143 if (collection_count(&listeners) == 0) {
1144 running = 0;
1145 }
1146 mutex_unlock(&listener_mutex);
1147 } while (running);
1148
1149 #ifdef HAVE_THREAD_CLEANUP
1150 thread_cleanup_pop(1);
1151 #else
1152 device_monitor_cleanup(NULL);
1153 #endif
1154
1155 return NULL;
1156 }
1157
1158 static void init_listeners(void)
1159 {
1160 collection_init(&listeners);
1161 mutex_init(&listener_mutex);
1162 }
1163
1164 int usbmuxd_events_subscribe(usbmuxd_subscription_context_t *context, usbmuxd_event_cb_t callback, void *user_data)
1165 {
1166 if (!context || !callback) {
1167 return -EINVAL;
1168 }
1169
1170 thread_once(&listener_init_once, init_listeners);
1171
1172 mutex_lock(&listener_mutex);
1173 *context = malloc(sizeof(struct usbmuxd_subscription_context));
1174 if (!*context) {
1175 mutex_unlock(&listener_mutex);
1176 LIBUSBMUXD_ERROR("ERROR: %s: malloc failed\n", __func__);
1177 return -ENOMEM;
1178 }
1179 (*context)->callback = callback;
1180 (*context)->user_data = user_data;
1181
1182 collection_add(&listeners, *context);
1183
1184 if (devmon == THREAD_T_NULL || !thread_alive(devmon)) {
1185 mutex_unlock(&listener_mutex);
1186 int res = thread_new(&devmon, device_monitor, NULL);
1187 if (res != 0) {
1188 free(*context);
1189 LIBUSBMUXD_DEBUG(1, "%s: ERROR: Could not start device watcher thread!\n", __func__);
1190 return res;
1191 }
1192 } else {
1193 /* we need to submit DEVICE_ADD events to the new listener */
1194 FOREACH(usbmuxd_device_info_t *dev, &devices) {
1195 if (dev) {
1196 usbmuxd_event_t ev;
1197 ev.event = UE_DEVICE_ADD;
1198 memcpy(&ev.device, dev, sizeof(usbmuxd_device_info_t));
1199 (*context)->callback(&ev, (*context)->user_data);
1200 }
1201 } ENDFOREACH
1202 mutex_unlock(&listener_mutex);
1203 }
1204
1205 return 0;
1206 }
1207
1208 int usbmuxd_events_unsubscribe(usbmuxd_subscription_context_t context)
1209 {
1210 int ret = 0;
1211 int num = 0;
1212
1213 if (!context) {
1214 return -EINVAL;
1215 }
1216
1217 mutex_lock(&listener_mutex);
1218 if (collection_remove(&listeners, context) == 0) {
1219 FOREACH(usbmuxd_device_info_t *dev, &devices) {
1220 if (dev) {
1221 usbmuxd_event_t ev;
1222 ev.event = UE_DEVICE_REMOVE;
1223 memcpy(&ev.device, dev, sizeof(usbmuxd_device_info_t));
1224 (context)->callback(&ev, (context)->user_data);
1225 }
1226 } ENDFOREACH
1227 free(context);
1228 }
1229 num = collection_count(&listeners);
1230 mutex_unlock(&listener_mutex);
1231
1232 if (num == 0) {
1233 int res = 0;
1234 cancelling = 1;
1235 socket_shutdown(listenfd, SHUT_RDWR);
1236 if (thread_alive(devmon)) {
1237 if (thread_cancel(devmon) < 0) {
1238 running = 0;
1239 }
1240 #if defined(HAVE_INOTIFY) && !defined(HAVE_PTHREAD_CANCEL)
1241 pthread_kill(devmon, SIGINT);
1242 #endif
1243 res = thread_join(devmon);
1244 thread_free(devmon);
1245 devmon = THREAD_T_NULL;
1246 }
1247 if ((res != 0) && (res != ESRCH)) {
1248 ret = res;
1249 }
1250 }
1251
1252 return ret;
1253 }
1254
1255 int usbmuxd_subscribe(usbmuxd_event_cb_t callback, void *user_data)
1256 {
1257 if (!callback) {
1258 return -EINVAL;
1259 }
1260
1261 if (event_ctx) {
1262 usbmuxd_events_unsubscribe(event_ctx);
1263 event_ctx = NULL;
1264 }
1265 return usbmuxd_events_subscribe(&event_ctx, callback, user_data);
1266 }
1267
1268 int usbmuxd_unsubscribe(void)
1269 {
1270 int res = usbmuxd_events_unsubscribe(event_ctx);
1271 event_ctx = NULL;
1272 return res;
1273 }
1274
1275 int usbmuxd_get_device_list(usbmuxd_device_info_t **device_list)
1276 {
1277 int sfd;
1278 int tag;
1279 int listen_success = 0;
1280 uint32_t res;
1281 struct collection tmpdevs;
1282 usbmuxd_device_info_t *newlist = NULL;
1283 struct usbmuxd_header hdr;
1284 int dev_cnt = 0;
1285 void *payload = NULL;
1286
1287 *device_list = NULL;
1288
1289 retry:
1290 sfd = connect_usbmuxd_socket();
1291 if (sfd < 0) {
1292 LIBUSBMUXD_DEBUG(1, "%s: error opening socket!\n", __func__);
1293 return sfd;
1294 }
1295
1296 tag = ++use_tag;
1297 if ((proto_version == 1) && (try_list_devices)) {
1298 if (send_list_devices_packet(sfd, tag) > 0) {
1299 plist_t list = NULL;
1300 if ((usbmuxd_get_result(sfd, tag, &res, &list) == 1) && (res == 0)) {
1301 plist_t devlist = plist_dict_get_item(list, "DeviceList");
1302 if (devlist && plist_get_node_type(devlist) == PLIST_ARRAY) {
1303 collection_init(&tmpdevs);
1304 uint32_t numdevs = plist_array_get_size(devlist);
1305 uint32_t i;
1306 for (i = 0; i < numdevs; i++) {
1307 plist_t pdev = plist_array_get_item(devlist, i);
1308 plist_t props = plist_dict_get_item(pdev, "Properties");
1309 usbmuxd_device_info_t *devinfo = device_info_from_plist(props);
1310 if (!devinfo) {
1311 socket_close(sfd);
1312 LIBUSBMUXD_DEBUG(1, "%s: Could not create device info object from properties!\n", __func__);
1313 plist_free(list);
1314 return -1;
1315 }
1316 collection_add(&tmpdevs, devinfo);
1317 }
1318 plist_free(list);
1319 goto got_device_list;
1320 }
1321 } else {
1322 if (res == RESULT_BADVERSION) {
1323 proto_version = 0;
1324 }
1325 socket_close(sfd);
1326 try_list_devices = 0;
1327 plist_free(list);
1328 goto retry;
1329 }
1330 plist_free(list);
1331 }
1332 }
1333
1334 tag = ++use_tag;
1335 if (send_listen_packet(sfd, tag) > 0) {
1336 res = -1;
1337 // get response
1338 if ((usbmuxd_get_result(sfd, tag, &res, NULL) == 1) && (res == 0)) {
1339 listen_success = 1;
1340 } else {
1341 socket_close(sfd);
1342 if ((res == RESULT_BADVERSION) && (proto_version == 1)) {
1343 proto_version = 0;
1344 goto retry;
1345 }
1346 LIBUSBMUXD_DEBUG(1, "%s: Did not get response to scan request (with result=0)...\n", __func__);
1347 return res;
1348 }
1349 }
1350
1351 if (!listen_success) {
1352 socket_close(sfd);
1353 LIBUSBMUXD_DEBUG(1, "%s: Could not send listen request!\n", __func__);
1354 return -1;
1355 }
1356
1357 collection_init(&tmpdevs);
1358
1359 // receive device list
1360 while (1) {
1361 if (receive_packet(sfd, &hdr, &payload, 100) > 0) {
1362 if (hdr.message == MESSAGE_DEVICE_ADD) {
1363 usbmuxd_device_info_t *devinfo = payload;
1364 collection_add(&tmpdevs, devinfo);
1365 payload = NULL;
1366 } else if (hdr.message == MESSAGE_DEVICE_REMOVE) {
1367 uint32_t handle;
1368 usbmuxd_device_info_t *devinfo = NULL;
1369
1370 memcpy(&handle, payload, sizeof(uint32_t));
1371
1372 FOREACH(usbmuxd_device_info_t *di, &tmpdevs) {
1373 if (di && di->handle == handle) {
1374 devinfo = di;
1375 break;
1376 }
1377 } ENDFOREACH
1378 if (devinfo) {
1379 collection_remove(&tmpdevs, devinfo);
1380 free(devinfo);
1381 }
1382 } else {
1383 LIBUSBMUXD_DEBUG(1, "%s: Unexpected message %d\n", __func__, hdr.message);
1384 }
1385 free(payload);
1386 } else {
1387 // we _should_ have all of them now.
1388 // or perhaps an error occurred.
1389 break;
1390 }
1391 }
1392
1393 got_device_list:
1394
1395 // explicitly close connection
1396 socket_close(sfd);
1397
1398 // create copy of device info entries from collection
1399 newlist = (usbmuxd_device_info_t*)malloc(sizeof(usbmuxd_device_info_t) * (collection_count(&tmpdevs) + 1));
1400 dev_cnt = 0;
1401 FOREACH(usbmuxd_device_info_t *di, &tmpdevs) {
1402 if (di) {
1403 memcpy(&newlist[dev_cnt], di, sizeof(usbmuxd_device_info_t));
1404 free(di);
1405 dev_cnt++;
1406 }
1407 } ENDFOREACH
1408 collection_free(&tmpdevs);
1409
1410 memset(&newlist[dev_cnt], 0, sizeof(usbmuxd_device_info_t));
1411 *device_list = newlist;
1412
1413 return dev_cnt;
1414 }
1415
1416 int usbmuxd_device_list_free(usbmuxd_device_info_t **device_list)
1417 {
1418 if (device_list) {
1419 free(*device_list);
1420 }
1421 return 0;
1422 }
1423
1424 int usbmuxd_get_device_by_udid(const char *udid, usbmuxd_device_info_t *device)
1425 {
1426 usbmuxd_device_info_t *dev_list = NULL;
1427 usbmuxd_device_info_t *dev = NULL;
1428 int result = 0;
1429 int i;
1430
1431 if (!device) {
1432 return -EINVAL;
1433 }
1434 if (usbmuxd_get_device_list(&dev_list) < 0) {
1435 return -ENODEV;
1436 }
1437
1438 for (i = 0; dev_list[i].handle > 0; i++) {
1439 if (!udid) {
1440 if (dev_list[i].conn_type == CONNECTION_TYPE_USB) {
1441 dev = &dev_list[i];
1442 break;
1443 }
1444 } else if (!strcmp(udid, dev_list[i].udid)) {
1445 if (dev_list[i].conn_type == CONNECTION_TYPE_USB) {
1446 dev = &dev_list[i];
1447 break;
1448 }
1449 }
1450 }
1451
1452 if (dev) {
1453 device->handle = dev->handle;
1454 device->product_id = dev->product_id;
1455 char *t = stpncpy(device->udid, dev->udid, sizeof(device->udid)-1);
1456 *t = '\0';
1457 device->conn_type = dev->conn_type;
1458 memcpy(device->conn_data, dev->conn_data, sizeof(device->conn_data));
1459 result = 1;
1460 }
1461
1462 usbmuxd_device_list_free(&dev_list);
1463
1464 return result;
1465 }
1466
1467 int usbmuxd_get_device(const char *udid, usbmuxd_device_info_t *device, enum usbmux_lookup_options options)
1468 {
1469 usbmuxd_device_info_t *dev_list = NULL;
1470 usbmuxd_device_info_t *dev_network = NULL;
1471 usbmuxd_device_info_t *dev_usbmuxd = NULL;
1472 usbmuxd_device_info_t *dev = NULL;
1473 int result = 0;
1474 int i;
1475
1476 if (!device) {
1477 return -EINVAL;
1478 }
1479 if (usbmuxd_get_device_list(&dev_list) < 0) {
1480 return -ENODEV;
1481 }
1482
1483 if (options == 0) {
1484 options = DEVICE_LOOKUP_USBMUX;
1485 }
1486
1487 for (i = 0; dev_list[i].handle > 0; i++) {
1488 if (!udid) {
1489 if ((options & DEVICE_LOOKUP_USBMUX) && (dev_list[i].conn_type == CONNECTION_TYPE_USB)) {
1490 dev_usbmuxd = &dev_list[i];
1491 break;
1492 }
1493 if ((options & DEVICE_LOOKUP_NETWORK) && (dev_list[i].conn_type == CONNECTION_TYPE_NETWORK)) {
1494 dev_network = &dev_list[i];
1495 break;
1496 }
1497 } else if (!strcmp(udid, dev_list[i].udid)) {
1498 if ((options & DEVICE_LOOKUP_USBMUX) && (dev_list[i].conn_type == CONNECTION_TYPE_USB)) {
1499 dev_usbmuxd = &dev_list[i];
1500 } else if ((options & DEVICE_LOOKUP_NETWORK) && (dev_list[i].conn_type == CONNECTION_TYPE_NETWORK)) {
1501 dev_network = &dev_list[i];
1502 }
1503 }
1504 if (dev_usbmuxd && dev_network) {
1505 break;
1506 }
1507 }
1508
1509 if (dev_network && dev_usbmuxd) {
1510 dev = (options & DEVICE_LOOKUP_PREFER_NETWORK) ? dev_network : dev_usbmuxd;
1511 } else if (dev_network) {
1512 dev = dev_network;
1513 } else if (dev_usbmuxd) {
1514 dev = dev_usbmuxd;
1515 }
1516
1517 if (dev) {
1518 device->handle = dev->handle;
1519 device->product_id = dev->product_id;
1520 char *t = stpncpy(device->udid, dev->udid, sizeof(device->udid)-1);
1521 *t = '\0';
1522 device->conn_type = dev->conn_type;
1523 memcpy(device->conn_data, dev->conn_data, sizeof(device->conn_data));
1524 result = 1;
1525 }
1526
1527 free(dev_list);
1528
1529 return result;
1530 }
1531
1532 int usbmuxd_connect(const uint32_t handle, const unsigned short port)
1533 {
1534 int sfd;
1535 int tag;
1536 int connected = 0;
1537 int result = EBADF;
1538
1539 retry:
1540 sfd = connect_usbmuxd_socket();
1541 if (sfd < 0) {
1542 LIBUSBMUXD_DEBUG(1, "%s: Error: Connection to usbmuxd failed: %s\n", __func__, strerror(-sfd));
1543 return sfd;
1544 }
1545
1546 tag = ++use_tag;
1547 if (send_connect_packet(sfd, tag, handle, (uint16_t)port) <= 0) {
1548 LIBUSBMUXD_DEBUG(1, "%s: Error sending connect message!\n", __func__);
1549 } else {
1550 // read ACK
1551 uint32_t res = -1;
1552 LIBUSBMUXD_DEBUG(2, "%s: Reading connect result...\n", __func__);
1553 if (usbmuxd_get_result(sfd, tag, &res, NULL) == 1) {
1554 if (res == 0) {
1555 LIBUSBMUXD_DEBUG(2, "%s: Connect success!\n", __func__);
1556 connected = 1;
1557 } else {
1558 if ((res == RESULT_BADVERSION) && (proto_version == 1)) {
1559 proto_version = 0;
1560 socket_close(sfd);
1561 goto retry;
1562 }
1563 LIBUSBMUXD_DEBUG(1, "%s: Connect failed, Error code=%d\n", __func__, res);
1564 if (res == RESULT_CONNREFUSED) {
1565 result = ECONNREFUSED;
1566 } else if (res == RESULT_BADDEV) {
1567 result = ENODEV;
1568 } else {
1569 result = EBADF;
1570 }
1571 }
1572 }
1573 }
1574
1575 if (connected) {
1576 return sfd;
1577 }
1578
1579 socket_close(sfd);
1580
1581 return -result;
1582 }
1583
1584 int usbmuxd_disconnect(int sfd)
1585 {
1586 return socket_close(sfd);
1587 }
1588
1589 int usbmuxd_send(int sfd, const char *data, uint32_t len, uint32_t *sent_bytes)
1590 {
1591 int num_sent;
1592
1593 if (sfd < 0) {
1594 return -EINVAL;
1595 }
1596
1597 num_sent = socket_send(sfd, (void*)data, len);
1598 if (num_sent < 0) {
1599 *sent_bytes = 0;
1600 LIBUSBMUXD_DEBUG(1, "%s: Error %d when sending: %s\n", __func__, -num_sent, strerror(-num_sent));
1601 return num_sent;
1602 }
1603
1604 if ((uint32_t)num_sent < len) {
1605 LIBUSBMUXD_DEBUG(1, "%s: Warning: Did not send enough (only %d of %d)\n", __func__, num_sent, len);
1606 }
1607
1608 *sent_bytes = num_sent;
1609
1610 return 0;
1611 }
1612
1613 int usbmuxd_recv_timeout(int sfd, char *data, uint32_t len, uint32_t *recv_bytes, unsigned int timeout)
1614 {
1615 int num_recv = socket_receive_timeout(sfd, (void*)data, len, 0, timeout);
1616 if (num_recv < 0) {
1617 *recv_bytes = 0;
1618 return num_recv;
1619 }
1620
1621 *recv_bytes = num_recv;
1622
1623 return 0;
1624 }
1625
1626 int usbmuxd_recv(int sfd, char *data, uint32_t len, uint32_t *recv_bytes)
1627 {
1628 return usbmuxd_recv_timeout(sfd, data, len, recv_bytes, 5000);
1629 }
1630
1631 int usbmuxd_read_buid(char **buid)
1632 {
1633 int sfd;
1634 int tag;
1635 int ret = -1;
1636
1637 if (!buid) {
1638 return -EINVAL;
1639 }
1640 *buid = NULL;
1641
1642 sfd = connect_usbmuxd_socket();
1643 if (sfd < 0) {
1644 LIBUSBMUXD_DEBUG(1, "%s: Error: Connection to usbmuxd failed: %s\n", __func__, strerror(-sfd));
1645 return sfd;
1646 }
1647
1648 proto_version = 1;
1649 tag = ++use_tag;
1650 if (send_read_buid_packet(sfd, tag) <= 0) {
1651 LIBUSBMUXD_DEBUG(1, "%s: Error sending ReadBUID message!\n", __func__);
1652 } else {
1653 uint32_t rc = 0;
1654 plist_t pl = NULL;
1655 ret = usbmuxd_get_result(sfd, tag, &rc, &pl);
1656 if ((ret == 1) && (rc == 0)) {
1657 plist_t node = plist_dict_get_item(pl, "BUID");
1658 if (node && plist_get_node_type(node) == PLIST_STRING) {
1659 plist_get_string_val(node, buid);
1660 }
1661 ret = 0;
1662 } else if (ret == 1) {
1663 ret = -(int)rc;
1664 }
1665 plist_free(pl);
1666 }
1667 socket_close(sfd);
1668
1669 return ret;
1670 }
1671
1672 int usbmuxd_read_pair_record(const char* record_id, char **record_data, uint32_t *record_size)
1673 {
1674 int sfd;
1675 int tag;
1676 int ret = -1;
1677
1678 if (!record_id || !record_data || !record_size) {
1679 return -EINVAL;
1680 }
1681 *record_data = NULL;
1682 *record_size = 0;
1683
1684 sfd = connect_usbmuxd_socket();
1685 if (sfd < 0) {
1686 LIBUSBMUXD_DEBUG(1, "%s: Error: Connection to usbmuxd failed: %s\n", __func__, strerror(-sfd));
1687 return sfd;
1688 }
1689
1690 proto_version = 1;
1691 tag = ++use_tag;
1692
1693 if (send_pair_record_packet(sfd, tag, "ReadPairRecord", record_id, 0, NULL) <= 0) {
1694 LIBUSBMUXD_DEBUG(1, "%s: Error sending ReadPairRecord message!\n", __func__);
1695 } else {
1696 uint32_t rc = 0;
1697 plist_t pl = NULL;
1698 ret = usbmuxd_get_result(sfd, tag, &rc, &pl);
1699 if ((ret == 1) && (rc == 0)) {
1700 plist_t node = plist_dict_get_item(pl, "PairRecordData");
1701 if (node && plist_get_node_type(node) == PLIST_DATA) {
1702 uint64_t int64val = 0;
1703 plist_get_data_val(node, record_data, &int64val);
1704 if (*record_data && int64val > 0) {
1705 *record_size = (uint32_t)int64val;
1706 ret = 0;
1707 }
1708 }
1709 } else if (ret == 1) {
1710 ret = -(int)rc;
1711 }
1712 plist_free(pl);
1713 }
1714 socket_close(sfd);
1715
1716 return ret;
1717 }
1718
1719 int usbmuxd_save_pair_record_with_device_id(const char* record_id, uint32_t device_id, const char *record_data, uint32_t record_size)
1720 {
1721 int sfd;
1722 int tag;
1723 int ret = -1;
1724
1725 if (!record_id || !record_data || !record_size) {
1726 return -EINVAL;
1727 }
1728
1729 sfd = connect_usbmuxd_socket();
1730 if (sfd < 0) {
1731 LIBUSBMUXD_DEBUG(1, "%s: Error: Connection to usbmuxd failed: %s\n", __func__, strerror(-sfd));
1732 return sfd;
1733 }
1734
1735 proto_version = 1;
1736 tag = ++use_tag;
1737
1738 plist_t data = plist_new_data(record_data, record_size);
1739 if (send_pair_record_packet(sfd, tag, "SavePairRecord", record_id, device_id, data) <= 0) {
1740 LIBUSBMUXD_DEBUG(1, "%s: Error sending SavePairRecord message!\n", __func__);
1741 } else {
1742 uint32_t rc = 0;
1743 ret = usbmuxd_get_result(sfd, tag, &rc, NULL);
1744 if ((ret == 1) && (rc == 0)) {
1745 ret = 0;
1746 } else if (ret == 1) {
1747 ret = -(int)rc;
1748 LIBUSBMUXD_DEBUG(1, "%s: Error: saving pair record failed: %d\n", __func__, ret);
1749 }
1750 }
1751 plist_free(data);
1752 socket_close(sfd);
1753
1754 return ret;
1755 }
1756
1757 int usbmuxd_save_pair_record(const char* record_id, const char *record_data, uint32_t record_size)
1758 {
1759 return usbmuxd_save_pair_record_with_device_id(record_id, 0, record_data, record_size);
1760 }
1761
1762 int usbmuxd_delete_pair_record(const char* record_id)
1763 {
1764 int sfd;
1765 int tag;
1766 int ret = -1;
1767
1768 if (!record_id) {
1769 return -EINVAL;
1770 }
1771
1772 sfd = connect_usbmuxd_socket();
1773 if (sfd < 0) {
1774 LIBUSBMUXD_DEBUG(1, "%s: Error: Connection to usbmuxd failed: %s\n", __func__, strerror(-sfd));
1775 return sfd;
1776 }
1777
1778 proto_version = 1;
1779 tag = ++use_tag;
1780
1781 if (send_pair_record_packet(sfd, tag, "DeletePairRecord", record_id, 0, NULL) <= 0) {
1782 LIBUSBMUXD_DEBUG(1, "%s: Error sending DeletePairRecord message!\n", __func__);
1783 } else {
1784 uint32_t rc = 0;
1785 ret = usbmuxd_get_result(sfd, tag, &rc, NULL);
1786 if ((ret == 1) && (rc == 0)) {
1787 ret = 0;
1788 } else if (ret == 1) {
1789 ret = -(int)rc;
1790 LIBUSBMUXD_DEBUG(1, "%s: Error: deleting pair record failed: %d\n", __func__, ret);
1791 }
1792 }
1793 socket_close(sfd);
1794
1795 return ret;
1796 }
1797
1798 void libusbmuxd_set_use_inotify(int set)
1799 {
1800 #ifdef HAVE_INOTIFY
1801 use_inotify = set;
1802 #endif
1803 }
1804
1805 void libusbmuxd_set_debug_level(int level)
1806 {
1807 libusbmuxd_debug = level;
1808 socket_set_verbose(level);
1809 }
1810
1811 const char* libusbmuxd_version()
1812 {
1813 #ifndef PACKAGE_VERSION
1814 #error PACKAGE_VERSION is not defined
1815 #endif
1816 return PACKAGE_VERSION;
1817 }