1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
2 /*
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2023 Nathan Hjelm <hjelmn@cs.unm.edu>
5 * Copyright © 2019-2023 Google LLC. All rights reserved.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <config.h>
23 #include <assert.h>
24 #include <time.h>
25 #include <ctype.h>
26 #include <pthread.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <sys/sysctl.h>
34
35 #include <mach/mach_time.h>
36
37 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
38 * function. Its use is also conditionalized to only older deployment targets. */
39 #define OBJC_SILENCE_GC_DEPRECATIONS 1
40
41 /* Default timeout to 10s for reenumerate. This is needed because USBDeviceReEnumerate
42 * does not return error status on macOS. */
43 #define DARWIN_REENUMERATE_TIMEOUT_US (10ULL * USEC_PER_SEC)
44
45 #include <AvailabilityMacros.h>
46 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
47 #include <objc/objc-auto.h>
48 #endif
49
50 #include "darwin_usb.h"
51
52 static int init_count = 0;
53
54 /* Both kIOMasterPortDefault or kIOMainPortDefault are synonyms for 0. */
55 static const mach_port_t darwin_default_master_port = 0;
56
57 /* async event thread */
58 /* if both this mutex and darwin_cached_devices_mutex are to be acquired then
59 darwin_cached_devices_mutex must be acquired first. */
60 static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER;
61 static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER;
62
63 #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
64
65 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
66 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
67
68 static usbi_mutex_t darwin_cached_devices_mutex = PTHREAD_MUTEX_INITIALIZER;
69 static struct list_head darwin_cached_devices;
70 static const char *darwin_device_class = "IOUSBDevice";
71
72 uint32_t libusb_testonly_fake_running_version __attribute__ ((visibility ("hidden")));
73 uint32_t libusb_testonly_using_running_interface_version __attribute__ ((visibility ("hidden")));
74 uint32_t libusb_testonly_using_running_device_version __attribute__ ((visibility ("hidden")));
75 bool libusb_testonly_clear_running_version_cache __attribute__ ((visibility ("hidden")));
76
77 #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
78
79 /* async event thread */
80 static pthread_t libusb_darwin_at;
81
82 /* protected by libusb_darwin_at_mutex */
83 static bool libusb_darwin_at_started;
84
85 static void darwin_exit(struct libusb_context *ctx);
86 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
87 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
88 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
89 static int darwin_reenumerate_device(struct libusb_device_handle *dev_handle, bool capture);
90 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
91 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
92 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface);
93 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
94
95 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
96 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
97 UInt64 old_session_id);
98
99 static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service, struct darwin_cached_device **cached_out,
100 UInt64 *old_session_id);
101
102 struct darwin_iokit_interface {
103 uint32_t min_os_version;
104 uint32_t version;
105 CFUUIDRef interface_id;
106 };
107
get_interface_interface(void)108 static const struct darwin_iokit_interface *get_interface_interface(void) {
109 const struct darwin_iokit_interface interfaces[] = {
110 #if defined(kIOUSBInterfaceInterfaceID800)
111 {
112 .min_os_version = 101200,
113 .version = 800,
114 .interface_id = kIOUSBInterfaceInterfaceID800,
115 },
116 #endif
117 #if defined(kIOUSBInterfaceInterfaceID700)
118 {
119 .min_os_version = 101000,
120 .version = 700,
121 .interface_id = kIOUSBInterfaceInterfaceID700,
122 },
123 #endif
124 #if defined(kIOUSBInterfaceInterfaceID650)
125 {
126 .min_os_version = 100900,
127 .version = 650,
128 .interface_id = kIOUSBInterfaceInterfaceID650
129 },
130 #endif
131 #if defined(kIOUSBInterfaceInterfaceID550)
132 {
133 .min_os_version = 100803,
134 .version = 550,
135 .interface_id = kIOUSBInterfaceInterfaceID550,
136 },
137 #endif
138 #if defined(kIOUSBInterfaceInterfaceID245)
139 {
140 .min_os_version = 100407,
141 .version = 245,
142 .interface_id = kIOUSBInterfaceInterfaceID245,
143 },
144 #endif
145 {
146 .min_os_version = 100000,
147 .version = 220,
148 .interface_id = kIOUSBInterfaceInterfaceID220,
149 },
150 {
151 .version = 0,
152 },
153 };
154 static struct darwin_iokit_interface cached_interface = {.version = 0};
155 if (libusb_testonly_clear_running_version_cache) {
156 memset (&cached_interface, 0, sizeof (cached_interface));
157 }
158 if (0 == cached_interface.version) {
159 uint32_t os_version = get_running_version();
160 for (int i = 0 ; interfaces[i].version > 0 ; ++i) {
161 if (os_version >= interfaces[i].min_os_version && cached_interface.min_os_version < interfaces[i].min_os_version) {
162 cached_interface = interfaces[i];
163 }
164 }
165
166 libusb_testonly_using_running_interface_version = cached_interface.version;
167 }
168
169 return &cached_interface;
170 }
171
get_interface_interface_id(void)172 static CFUUIDRef get_interface_interface_id(void) {
173 return get_interface_interface()->interface_id;
174 }
175
get_interface_interface_version(void)176 static uint32_t get_interface_interface_version(void) {
177 return get_interface_interface()->version;
178 }
179
get_device_interface(void)180 static const struct darwin_iokit_interface *get_device_interface(void) {
181 struct darwin_iokit_interface interfaces[] = {
182 #if defined(kIOUSBDeviceInterfaceID650)
183 {
184 .min_os_version = 100900,
185 .version = 650,
186 .interface_id = kIOUSBDeviceInterfaceID650,
187 },
188 #endif
189 #if defined(kIOUSBDeviceInterfaceID500)
190 {
191 .min_os_version = 100703,
192 .version = 500,
193 .interface_id = kIOUSBDeviceInterfaceID500,
194 },
195 #endif
196 #if defined(kIOUSBDeviceInterfaceID320)
197 {
198 .min_os_version = 100504,
199 .version = 320,
200 .interface_id = kIOUSBDeviceInterfaceID320,
201 },
202 #endif
203 #if defined(kIOUSBDeviceInterfaceID300)
204 {
205 .min_os_version = 100500,
206 .version = 300,
207 .interface_id = kIOUSBDeviceInterfaceID300,
208 },
209 #endif
210 #if defined(kIOUSBDeviceInterfaceID245)
211 {
212 .min_os_version = 100407,
213 .version = 245,
214 .interface_id = kIOUSBDeviceInterfaceID245,
215 },
216 #endif
217 {
218 .min_os_version = 100000,
219 .version = 197,
220 .interface_id = kIOUSBDeviceInterfaceID197,
221 },
222 {
223 .version = 0,
224 },
225 };
226 static struct darwin_iokit_interface cached_interface = {.version = 0};
227 if (libusb_testonly_clear_running_version_cache) {
228 memset (&cached_interface, 0, sizeof (cached_interface));
229 }
230 if (0 == cached_interface.version) {
231 uint32_t os_version = get_running_version();
232 for (int i = 0 ; interfaces[i].version > 0 ; ++i) {
233 if (os_version >= interfaces[i].min_os_version && cached_interface.min_os_version < interfaces[i].min_os_version) {
234 cached_interface = interfaces[i];
235 }
236 }
237 libusb_testonly_using_running_device_version = cached_interface.version;
238 }
239
240 return &cached_interface;
241 }
242
get_device_interface_id(void)243 static CFUUIDRef get_device_interface_id(void) {
244 return get_device_interface()->interface_id;
245 }
246
get_device_interface_version(void)247 static uint32_t get_device_interface_version(void) {
248 return get_device_interface()->version;
249 }
250
251 struct darwin_pipe_properties {
252 uint8_t number;
253 uint8_t direction;
254 uint8_t transfer_type;
255 uint16_t max_packet_size;
256 uint8_t interval;
257 };
258 typedef struct darwin_pipe_properties darwin_pipe_properties_t;
259
darwin_get_pipe_properties(struct darwin_interface * cInterface,uint8_t pipe,darwin_pipe_properties_t * out)260 static IOReturn darwin_get_pipe_properties(struct darwin_interface *cInterface, uint8_t pipe, darwin_pipe_properties_t *out) {
261 IOReturn kresult;
262
263 #if (MAX_INTERFACE_VERSION >= 550)
264 if (get_interface_interface_version() >= 550) {
265 IOUSBEndpointProperties pipe_properties = {.bVersion = kUSBEndpointPropertiesVersion3};
266 kresult = (*IOINTERFACE_V(cInterface, 550))->GetPipePropertiesV3 (IOINTERFACE(cInterface), pipe, &pipe_properties);
267 if (kIOReturnSuccess == kresult) {
268 out->number = pipe_properties.bEndpointNumber;
269 out->direction = pipe_properties.bDirection;
270 out->transfer_type = pipe_properties.bTransferType;
271 out->max_packet_size = pipe_properties.wMaxPacketSize;
272 out->interval = pipe_properties.bInterval;
273 }
274 return kresult;
275 }
276 #endif
277 return (*IOINTERFACE(cInterface))->GetPipeProperties(IOINTERFACE(cInterface), pipe, &out->direction,
278 &out->number, &out->transfer_type, &out->max_packet_size,
279 &out->interval);
280 }
281
282 #if defined(ENABLE_LOGGING)
darwin_error_str(IOReturn result)283 static const char *darwin_error_str (IOReturn result) {
284 static char string_buffer[50];
285 switch (result) {
286 case kIOReturnSuccess:
287 return "no error";
288 case kIOReturnNotOpen:
289 return "device not opened for exclusive access";
290 case kIOReturnNoDevice:
291 return "no connection to an IOService";
292 case kIOUSBNoAsyncPortErr:
293 return "no async port has been opened for interface";
294 case kIOReturnExclusiveAccess:
295 return "another process has device opened for exclusive access";
296 case kIOUSBPipeStalled:
297 #if defined(kUSBHostReturnPipeStalled)
298 case kUSBHostReturnPipeStalled:
299 #endif
300 return "pipe is stalled";
301 case kIOReturnError:
302 return "could not establish a connection to the Darwin kernel";
303 case kIOUSBTransactionTimeout:
304 return "transaction timed out";
305 case kIOReturnBadArgument:
306 return "invalid argument";
307 case kIOReturnAborted:
308 return "transaction aborted";
309 case kIOReturnNotResponding:
310 return "device not responding";
311 case kIOReturnOverrun:
312 return "data overrun";
313 case kIOReturnCannotWire:
314 return "physical memory can not be wired down";
315 case kIOReturnNoResources:
316 return "out of resources";
317 case kIOUSBHighSpeedSplitError:
318 return "high speed split error";
319 case kIOUSBUnknownPipeErr:
320 return "pipe ref not recognized";
321 default:
322 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
323 return string_buffer;
324 }
325 }
326 #endif
327
darwin_to_libusb(IOReturn result)328 static enum libusb_error darwin_to_libusb (IOReturn result) {
329 switch (result) {
330 case kIOReturnUnderrun:
331 case kIOReturnSuccess:
332 return LIBUSB_SUCCESS;
333 case kIOReturnNotOpen:
334 case kIOReturnNoDevice:
335 return LIBUSB_ERROR_NO_DEVICE;
336 case kIOReturnExclusiveAccess:
337 return LIBUSB_ERROR_ACCESS;
338 case kIOUSBPipeStalled:
339 #if defined(kUSBHostReturnPipeStalled)
340 case kUSBHostReturnPipeStalled:
341 #endif
342 return LIBUSB_ERROR_PIPE;
343 case kIOReturnBadArgument:
344 return LIBUSB_ERROR_INVALID_PARAM;
345 case kIOUSBTransactionTimeout:
346 return LIBUSB_ERROR_TIMEOUT;
347 case kIOUSBUnknownPipeErr:
348 return LIBUSB_ERROR_NOT_FOUND;
349 case kIOReturnNotResponding:
350 case kIOReturnAborted:
351 case kIOReturnError:
352 case kIOUSBNoAsyncPortErr:
353 default:
354 return LIBUSB_ERROR_OTHER;
355 }
356 }
357
get_running_version(void)358 uint32_t get_running_version(void) {
359 if (libusb_testonly_fake_running_version > 0) {
360 return libusb_testonly_fake_running_version;
361 }
362
363 int ret;
364 #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
365 char os_version_string[64] = {'\0'};;
366 size_t os_version_string_len = sizeof(os_version_string) - 1;
367
368 /* newer versions of macOS provide a sysctl for the OS version but this is not useful for iOS without
369 * code detecting this is iOS and a mapping from iOS -> macOS version. it is still useful to have since
370 * it provides the exact macOS version instead of the approximate version (as below). */
371 ret = sysctlbyname("kern.osproductversion", os_version_string, &os_version_string_len, NULL, 0);
372 if (ret == 0) {
373 unsigned int major = 10, minor = 0, patch = 0;
374 ret = sscanf(os_version_string, "%u.%u.%u", &major, &minor, &patch);
375 if (ret < 2) {
376 usbi_err (NULL, "could not determine the running OS version, assuming 10.0, kern.osproductversion=%s", os_version_string);
377 return 10 * 10000;
378 }
379 return (major * 10000) + (minor * 100) + patch;
380 }
381 #endif
382
383 char os_release_string[64] = {'\0'};
384 size_t os_release_string_len = sizeof(os_release_string) - 1;
385 /* if the version can not be detected libusb assumes 10.0 so ignore any error here */
386 ret = sysctlbyname("kern.osrelease", os_release_string, &os_release_string_len, NULL, 0);
387 if (ret != 0) {
388 usbi_err (NULL, "could not read kern.osrelease, errno=", errno);
389 return 10 * 10000;
390 }
391
392 unsigned int darwin_major = 1, darwin_minor = 0;
393 ret = sscanf(os_release_string, "%u.%u", &darwin_major, &darwin_minor);
394 if (ret < 1) {
395 usbi_err (NULL, "could not determine the running Darwin version, assuming 1.3 (OS X 10.0), kern.osrelease=%s", os_release_string);
396 return 10 * 10000;
397 }
398
399 unsigned int major = 10, minor = 0, patch = 0;
400
401 if (1 == darwin_major && darwin_minor < 4) {
402 /* 10.0.x */
403 } else if (darwin_major < 6) {
404 /* assume 10.1 for anything in this range */
405 minor = 1;
406 } else if (darwin_major < 20) {
407 /* from macOS 10.2 through 10.15 the minor version can be calculated from the darwin_major by subtracting 4 and
408 * the patch level almost always matches darwin_minor. when the darwin_minor does not match the OS X patch level
409 * it is usually because Apple did not change it in a particular point release. when darwin_minor is changed it
410 * always matches the OS X/macOS patch level. */
411 minor = darwin_major - 4;
412 patch = darwin_minor;
413 } else {
414 /* unlikely to be used as kern.osproductversion is available from 10.10 on */
415 major = darwin_major - 9;
416 minor = darwin_minor;
417 /* ignore the patch level in this range */
418 }
419
420 return (major * 10000) + (minor * 100) + patch;
421 }
422
423 /* this function must be called with the darwin_cached_devices_mutex held */
darwin_deref_cached_device(struct darwin_cached_device * cached_dev)424 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
425 cached_dev->refcount--;
426 /* free the device and remove it from the cache */
427 if (0 == cached_dev->refcount) {
428 list_del(&cached_dev->list);
429
430 if (cached_dev->device) {
431 (*cached_dev->device)->Release(cached_dev->device);
432 cached_dev->device = NULL;
433 }
434 IOObjectRelease (cached_dev->service);
435 free (cached_dev);
436 }
437 }
438
darwin_ref_cached_device(struct darwin_cached_device * cached_dev)439 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
440 cached_dev->refcount++;
441 }
442
ep_to_pipeRef(struct libusb_device_handle * dev_handle,uint8_t ep,uint8_t * pipep,uint8_t * ifcp,struct darwin_interface ** interface_out)443 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
444 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
445
446 /* current interface */
447 struct darwin_interface *cInterface;
448
449 uint8_t i, iface;
450
451 struct libusb_context *ctx = HANDLE_CTX(dev_handle);
452
453 usbi_dbg (ctx, "converting ep address 0x%02x to pipeRef and interface", ep);
454
455 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
456 cInterface = &priv->interfaces[iface];
457
458 if (dev_handle->claimed_interfaces & (1U << iface)) {
459 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
460 if (cInterface->endpoint_addrs[i] == ep) {
461 *pipep = i + 1;
462
463 if (ifcp)
464 *ifcp = iface;
465
466 if (interface_out)
467 *interface_out = cInterface;
468
469 usbi_dbg (ctx, "pipe %d on interface %d matches", *pipep, iface);
470 return LIBUSB_SUCCESS;
471 }
472 }
473 }
474 }
475
476 /* No pipe found with the correct endpoint address */
477 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
478
479 return LIBUSB_ERROR_NOT_FOUND;
480 }
481
usb_setup_device_iterator(io_iterator_t * deviceIterator,UInt32 location)482 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
483 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
484
485 if (!matchingDict)
486 return kIOReturnError;
487
488 if (location) {
489 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
490 &kCFTypeDictionaryKeyCallBacks,
491 &kCFTypeDictionaryValueCallBacks);
492
493 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
494 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
495 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
496
497 if (propertyMatchDict && locationCF) {
498 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
499 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
500 }
501 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
502
503 /* release our references as per the Create Rule */
504 if (propertyMatchDict)
505 CFRelease (propertyMatchDict);
506 if (locationCF)
507 CFRelease (locationCF);
508 }
509
510 return IOServiceGetMatchingServices(darwin_default_master_port, matchingDict, deviceIterator);
511 }
512
513 /* Returns 1 on success, 0 on failure. */
get_ioregistry_value_number(io_service_t service,CFStringRef property,CFNumberType type,void * p)514 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
515 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
516 Boolean success = 0;
517
518 if (cfNumber) {
519 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
520 success = CFNumberGetValue(cfNumber, type, p);
521 }
522
523 CFRelease (cfNumber);
524 }
525
526 return (success != 0);
527 }
528
529 /* Returns 1 on success, 0 on failure. */
get_ioregistry_value_data(io_service_t service,CFStringRef property,ssize_t size,void * p)530 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
531 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
532 bool success = false;
533
534 if (cfData) {
535 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
536 CFIndex length = CFDataGetLength (cfData);
537 if (length < size) {
538 size = length;
539 }
540
541 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
542 success = true;
543 }
544
545 CFRelease (cfData);
546 }
547
548 return success;
549 }
550
darwin_device_from_service(struct libusb_context * ctx,io_service_t service,usb_device_t * device)551 static int darwin_device_from_service (struct libusb_context *ctx, io_service_t service, usb_device_t* device)
552 {
553 io_cf_plugin_ref_t *plugInInterface = NULL;
554 IOReturn kresult;
555 SInt32 score;
556
557 const int max_retries = 5;
558
559 /* The IOCreatePlugInInterfaceForService function might consistently return
560 an "out of resources" error with certain USB devices the first time we run
561 it. The reason is still unclear, but retrying fixes the problem */
562 for (int count = 0; count < max_retries; count++) {
563 kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
564 kIOCFPlugInInterfaceID, &plugInInterface,
565 &score);
566 if (kIOReturnSuccess == kresult && plugInInterface) {
567 break;
568 }
569
570 usbi_dbg (ctx, "set up plugin for service retry: %s", darwin_error_str (kresult));
571
572 /* sleep for a little while before trying again */
573 nanosleep(&(struct timespec){.tv_sec = 0, .tv_nsec = 1000}, NULL);
574 }
575
576 if (kIOReturnSuccess != kresult) {
577 usbi_dbg (ctx, "could not set up plugin for service: %s", darwin_error_str (kresult));
578 return darwin_to_libusb(kresult);
579 }
580 if (!plugInInterface) {
581 usbi_dbg (ctx, "could not set up plugin for service");
582 return LIBUSB_ERROR_OTHER;
583 }
584
585 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(get_device_interface_id()),
586 (LPVOID)device);
587 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
588 (*plugInInterface)->Release (plugInInterface);
589
590 return LIBUSB_SUCCESS;
591 }
592
darwin_devices_attached(void * ptr,io_iterator_t add_devices)593 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
594 UNUSED(ptr);
595 struct darwin_cached_device *cached_device;
596 UInt64 old_session_id;
597 struct libusb_context *ctx;
598 io_service_t service;
599 int ret;
600
601 usbi_mutex_lock(&active_contexts_lock);
602
603 while ((service = IOIteratorNext(add_devices))) {
604 ret = darwin_get_cached_device (NULL, service, &cached_device, &old_session_id);
605 if (ret < 0 || !cached_device->can_enumerate) {
606 continue;
607 }
608
609 /* add this device to each active context's device list */
610 for_each_context(ctx) {
611 process_new_device (ctx, cached_device, old_session_id);
612 }
613
614 if (cached_device->in_reenumerate) {
615 usbi_dbg (NULL, "cached device in reset state. reset complete...");
616 cached_device->in_reenumerate = false;
617 }
618
619 IOObjectRelease(service);
620 }
621
622 usbi_mutex_unlock(&active_contexts_lock);
623 }
624
darwin_devices_detached(void * ptr,io_iterator_t rem_devices)625 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
626 UNUSED(ptr);
627 struct libusb_device *dev = NULL;
628 struct libusb_context *ctx;
629 struct darwin_cached_device *old_device;
630
631 io_service_t device;
632
633 usbi_mutex_lock(&active_contexts_lock);
634
635 while ((device = IOIteratorNext (rem_devices)) != 0) {
636 bool is_reenumerating = false;
637
638 /* get the location from the i/o registry */
639 UInt64 session = 0;
640 bool ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
641 UInt32 locationID = 0;
642 (void) get_ioregistry_value_number (device, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
643 IOObjectRelease (device);
644 if (!ret)
645 continue;
646
647 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
648 otherwise no cached device will ever get freed */
649 usbi_mutex_lock(&darwin_cached_devices_mutex);
650 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
651 if (old_device->session == session) {
652 if (old_device->in_reenumerate) {
653 /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
654 * will deref if needed. */
655 usbi_dbg (NULL, "detected device detached due to re-enumeration. sessionID: 0x%" PRIx64
656 ", locationID: 0x%" PRIx32, session, locationID);
657
658 /* the device object is no longer usable so go ahead and release it */
659 if (old_device->device) {
660 (*old_device->device)->Release(old_device->device);
661 old_device->device = NULL;
662 }
663
664 is_reenumerating = true;
665 } else {
666 darwin_deref_cached_device (old_device);
667 }
668
669 break;
670 }
671 }
672
673 usbi_mutex_unlock(&darwin_cached_devices_mutex);
674 if (is_reenumerating) {
675 continue;
676 }
677
678 for_each_context(ctx) {
679 usbi_dbg (ctx, "notifying context %p of device disconnect", ctx);
680
681 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
682 if (dev) {
683 /* signal the core that this device has been disconnected. the core will tear down this device
684 when the reference count reaches 0 */
685 usbi_disconnect_device(dev);
686 libusb_unref_device(dev);
687 }
688 }
689 }
690
691 usbi_mutex_unlock(&active_contexts_lock);
692 }
693
darwin_hotplug_poll(void)694 static void darwin_hotplug_poll (void)
695 {
696 /* not sure if 1 ms will be too long/short but it should work ok */
697 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000ul};
698
699 /* since a kernel thread may notify the IOIterators used for
700 * hotplug notification we can't just clear the iterators.
701 * instead just wait until all IOService providers are quiet */
702 (void) IOKitWaitQuiet (darwin_default_master_port, &timeout);
703 }
704
darwin_clear_iterator(io_iterator_t iter)705 static void darwin_clear_iterator (io_iterator_t iter) {
706 io_service_t device;
707
708 while ((device = IOIteratorNext (iter)) != 0)
709 IOObjectRelease (device);
710 }
711
darwin_fail_startup(void)712 static void darwin_fail_startup(void) {
713 pthread_mutex_lock (&libusb_darwin_at_mutex);
714 libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
715 pthread_cond_signal (&libusb_darwin_at_cond);
716 pthread_mutex_unlock (&libusb_darwin_at_mutex);
717 pthread_exit (NULL);
718 }
719
darwin_event_thread_main(void * arg0)720 static void *darwin_event_thread_main (void *arg0) {
721 UNUSED(arg0);
722 IOReturn kresult;
723 CFRunLoopRef runloop;
724 CFRunLoopSourceRef libusb_shutdown_cfsource;
725 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
726
727 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
728 /* Set this thread's name, so it can be seen in the debugger
729 and crash reports. */
730 pthread_setname_np ("org.libusb.device-hotplug");
731 #endif
732
733 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
734 /* Tell the Objective-C garbage collector about this thread.
735 This is required because, unlike NSThreads, pthreads are
736 not automatically registered. Although we don't use
737 Objective-C, we use CoreFoundation, which does.
738 Garbage collection support was entirely removed in 10.12,
739 so don't bother there. */
740 objc_registerThreadWithCollector();
741 #endif
742
743 /* hotplug (device arrival/removal) sources */
744 CFRunLoopSourceRef libusb_notification_cfsource;
745 io_notification_port_t libusb_notification_port;
746 io_iterator_t libusb_rem_device_iterator;
747 io_iterator_t libusb_add_device_iterator;
748
749 /* ctx must only be used for logging during thread startup */
750 usbi_dbg (NULL, "creating hotplug event source");
751
752 runloop = CFRunLoopGetCurrent ();
753 CFRetain (runloop);
754
755 /* add the shutdown cfsource to the run loop */
756 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
757 libusb_shutdown_cfsourcectx.info = runloop;
758 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
759 libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
760 CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
761
762 /* add the notification port to the run loop */
763 libusb_notification_port = IONotificationPortCreate (darwin_default_master_port);
764 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
765 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
766
767 /* create notifications for removed devices */
768 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
769 IOServiceMatching(darwin_device_class),
770 darwin_devices_detached,
771 NULL, &libusb_rem_device_iterator);
772
773 if (kresult != kIOReturnSuccess) {
774 usbi_err (NULL, "could not add hotplug event source: %s", darwin_error_str (kresult));
775 CFRelease (libusb_shutdown_cfsource);
776 CFRelease (runloop);
777 darwin_fail_startup ();
778 }
779
780 /* create notifications for attached devices */
781 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
782 IOServiceMatching(darwin_device_class),
783 darwin_devices_attached,
784 NULL, &libusb_add_device_iterator);
785
786 if (kresult != kIOReturnSuccess) {
787 usbi_err (NULL, "could not add hotplug event source: %s", darwin_error_str (kresult));
788 CFRelease (libusb_shutdown_cfsource);
789 CFRelease (runloop);
790 darwin_fail_startup ();
791 }
792
793 /* arm notifiers */
794 darwin_clear_iterator (libusb_rem_device_iterator);
795 darwin_clear_iterator (libusb_add_device_iterator);
796
797 usbi_dbg (NULL, "darwin event thread ready to receive events");
798
799 /* signal the main thread that the hotplug runloop has been created. */
800 pthread_mutex_lock (&libusb_darwin_at_mutex);
801 libusb_darwin_acfl = runloop;
802 libusb_darwin_acfls = libusb_shutdown_cfsource;
803 pthread_cond_signal (&libusb_darwin_at_cond);
804 pthread_mutex_unlock (&libusb_darwin_at_mutex);
805
806 /* run the runloop */
807 CFRunLoopRun();
808
809 usbi_dbg (NULL, "darwin event thread exiting");
810
811 /* signal the main thread that the hotplug runloop has finished. */
812 pthread_mutex_lock (&libusb_darwin_at_mutex);
813 libusb_darwin_acfls = NULL;
814 libusb_darwin_acfl = NULL;
815 pthread_cond_signal (&libusb_darwin_at_cond);
816 pthread_mutex_unlock (&libusb_darwin_at_mutex);
817
818 /* remove the notification cfsource */
819 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
820
821 /* remove the shutdown cfsource */
822 CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
823
824 /* delete notification port */
825 IONotificationPortDestroy (libusb_notification_port);
826
827 /* delete iterators */
828 IOObjectRelease (libusb_rem_device_iterator);
829 IOObjectRelease (libusb_add_device_iterator);
830
831 CFRelease (libusb_shutdown_cfsource);
832 CFRelease (runloop);
833
834 pthread_exit (NULL);
835 }
836
837 /* cleanup function to destroy cached devices. must be called with a lock on darwin_cached_devices_mutex */
darwin_cleanup_devices(void)838 static void darwin_cleanup_devices(void) {
839 struct darwin_cached_device *dev, *next;
840
841 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
842 if (dev->refcount > 1) {
843 usbi_err(NULL, "device still referenced at libusb_exit");
844 }
845 darwin_deref_cached_device(dev);
846 }
847 }
848
849 /* must be called with a lock on darwin_cached_devices_mutex */
darwin_first_time_init(void)850 static int darwin_first_time_init(void) {
851 if (NULL == darwin_cached_devices.next) {
852 list_init (&darwin_cached_devices);
853 }
854
855 /* cache the interface versions that will be used. as a sanity check verify
856 * that the interface versions are non-zero. */
857 const struct darwin_iokit_interface *interface_interface = get_interface_interface();
858 const struct darwin_iokit_interface *device_interface = get_device_interface();
859 if (0 == interface_interface->version || 0 == device_interface->version) {
860 usbi_err(NULL, "could not determine the device or interface interface to use with this version "
861 "of macOS (or MacOS X), current_running_version = %" PRIu32, get_running_version());
862 return LIBUSB_ERROR_OTHER;
863 }
864
865 if (!list_empty(&darwin_cached_devices)) {
866 usbi_err(NULL, "libusb_device reference not released on last exit. will not continue");
867 return LIBUSB_ERROR_OTHER;
868 }
869
870 int rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, NULL);
871 if (0 != rc) {
872 usbi_err (NULL, "could not create event thread, error %d", rc);
873 return LIBUSB_ERROR_OTHER;
874 }
875
876 pthread_mutex_lock (&libusb_darwin_at_mutex);
877 libusb_darwin_at_started = true;
878 while (NULL == libusb_darwin_acfl) {
879 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
880 }
881
882 if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
883 libusb_darwin_acfl = NULL;
884 rc = LIBUSB_ERROR_OTHER;
885 }
886 pthread_mutex_unlock (&libusb_darwin_at_mutex);
887
888 return rc;
889 }
890
darwin_init_context(struct libusb_context * ctx)891 static int darwin_init_context(struct libusb_context *ctx) {
892 usbi_mutex_lock(&darwin_cached_devices_mutex);
893
894 bool first_init = (1 == ++init_count);
895
896 if (first_init) {
897 int rc = darwin_first_time_init();
898 if (LIBUSB_SUCCESS != rc) {
899 usbi_mutex_unlock(&darwin_cached_devices_mutex);
900 return rc;
901 }
902 }
903 usbi_mutex_unlock(&darwin_cached_devices_mutex);
904
905 return darwin_scan_devices (ctx);
906 }
907
darwin_init(struct libusb_context * ctx)908 static int darwin_init(struct libusb_context *ctx) {
909 int rc = darwin_init_context(ctx);
910 if (LIBUSB_SUCCESS != rc) {
911 /* clean up any allocated resources */
912 darwin_exit(ctx);
913 }
914
915 return rc;
916 }
917
darwin_exit(struct libusb_context * ctx)918 static void darwin_exit (struct libusb_context *ctx) {
919 UNUSED(ctx);
920
921 usbi_mutex_lock(&darwin_cached_devices_mutex);
922 if (0 == --init_count) {
923 /* stop the event runloop and wait for the thread to terminate. */
924 pthread_mutex_lock (&libusb_darwin_at_mutex);
925 if (NULL != libusb_darwin_acfls) {
926 CFRunLoopSourceSignal (libusb_darwin_acfls);
927 CFRunLoopWakeUp (libusb_darwin_acfl);
928 while (libusb_darwin_acfl)
929 pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
930 }
931
932 if (libusb_darwin_at_started) {
933 pthread_join (libusb_darwin_at, NULL);
934 libusb_darwin_at_started = false;
935 }
936 pthread_mutex_unlock (&libusb_darwin_at_mutex);
937
938 darwin_cleanup_devices ();
939 }
940 usbi_mutex_unlock(&darwin_cached_devices_mutex);
941 }
942
get_configuration_index(struct libusb_device * dev,UInt8 config_value)943 static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
944 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
945 UInt8 i, numConfig;
946 IOUSBConfigurationDescriptorPtr desc;
947 IOReturn kresult;
948
949 /* is there a simpler way to determine the index? */
950 kresult = (*priv->device)->GetNumberOfConfigurations (priv->device, &numConfig);
951 if (kresult != kIOReturnSuccess)
952 return darwin_to_libusb (kresult);
953
954 for (i = 0 ; i < numConfig ; i++) {
955 (*priv->device)->GetConfigurationDescriptorPtr (priv->device, i, &desc);
956
957 if (desc->bConfigurationValue == config_value)
958 return i;
959 }
960
961 /* configuration not found */
962 return LIBUSB_ERROR_NOT_FOUND;
963 }
964
darwin_get_active_config_descriptor(struct libusb_device * dev,void * buffer,size_t len)965 static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
966 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
967 int config_index;
968
969 if (0 == priv->active_config)
970 return LIBUSB_ERROR_NOT_FOUND;
971
972 config_index = get_configuration_index (dev, priv->active_config);
973 if (config_index < 0)
974 return config_index;
975
976 assert(config_index >= 0 && config_index <= UINT8_MAX);
977 return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
978 }
979
darwin_get_config_descriptor(struct libusb_device * dev,uint8_t config_index,void * buffer,size_t len)980 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
981 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
982 IOUSBConfigurationDescriptorPtr desc;
983 IOReturn kresult;
984 int ret;
985
986 if (!priv || !priv->device)
987 return LIBUSB_ERROR_OTHER;
988
989 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
990 if (kresult == kIOReturnSuccess) {
991 /* copy descriptor */
992 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
993 len = libusb_le16_to_cpu(desc->wTotalLength);
994
995 memmove (buffer, desc, len);
996 }
997
998 ret = darwin_to_libusb (kresult);
999 if (ret != LIBUSB_SUCCESS)
1000 return ret;
1001
1002 return (int) len;
1003 }
1004
1005 /* check whether the os has configured the device */
darwin_check_configuration(struct libusb_context * ctx,struct darwin_cached_device * dev)1006 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
1007 usb_device_t darwin_device = dev->device;
1008
1009 IOUSBConfigurationDescriptorPtr configDesc;
1010 IOUSBFindInterfaceRequest request;
1011 IOReturn kresult;
1012 io_iterator_t interface_iterator;
1013 io_service_t firstInterface;
1014
1015 if (dev->dev_descriptor.bNumConfigurations < 1) {
1016 usbi_err (ctx, "device has no configurations");
1017 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
1018 }
1019
1020 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
1021 not usable anyway */
1022 if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
1023 0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
1024 usbi_dbg (ctx, "ignoring configuration on root hub simulation");
1025 dev->active_config = 0;
1026 return LIBUSB_SUCCESS;
1027 }
1028
1029 /* find the first configuration */
1030 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
1031 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
1032
1033 /* check if the device is already configured. there is probably a better way than iterating over the
1034 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
1035 might lock up on the device request) */
1036
1037 /* Setup the Interface Request */
1038 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1039 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1040 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1041 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1042
1043 kresult = (*darwin_device)->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1044 if (kresult != kIOReturnSuccess)
1045 return darwin_to_libusb (kresult);
1046
1047 /* iterate once */
1048 firstInterface = IOIteratorNext(interface_iterator);
1049
1050 /* done with the interface iterator */
1051 IOObjectRelease(interface_iterator);
1052
1053 if (firstInterface) {
1054 IOObjectRelease (firstInterface);
1055
1056 /* device is configured */
1057 if (dev->dev_descriptor.bNumConfigurations == 1)
1058 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
1059 dev->active_config = dev->first_config;
1060 else
1061 /* devices with more than one configuration should work with GetConfiguration */
1062 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
1063 } else
1064 /* not configured */
1065 dev->active_config = 0;
1066
1067 usbi_dbg (ctx, "active config: %u, first config: %u", dev->active_config, dev->first_config);
1068
1069 return LIBUSB_SUCCESS;
1070 }
1071
darwin_request_descriptor(usb_device_t device,UInt8 desc,UInt8 desc_index,void * buffer,size_t buffer_size)1072 static IOReturn darwin_request_descriptor (usb_device_t device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
1073 IOUSBDevRequestTO req;
1074
1075 assert(buffer_size <= UINT16_MAX);
1076
1077 memset (buffer, 0, buffer_size);
1078
1079 /* Set up request for descriptor/ */
1080 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
1081 req.bRequest = kUSBRqGetDescriptor;
1082 req.wValue = (UInt16)(desc << 8);
1083 req.wIndex = desc_index;
1084 req.wLength = (UInt16)buffer_size;
1085 req.pData = buffer;
1086 req.noDataTimeout = 20;
1087 req.completionTimeout = 100;
1088
1089 return (*device)->DeviceRequestTO (device, &req);
1090 }
1091
darwin_cache_device_descriptor(struct libusb_context * ctx,struct darwin_cached_device * dev)1092 static enum libusb_error darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
1093 usb_device_t device = dev->device;
1094 int retries = 1;
1095 long delay = 30000; /* microseconds */
1096 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
1097 int is_open = 0;
1098 IOReturn ret = 0, ret2;
1099 UInt8 bDeviceClass;
1100 UInt16 idProduct, idVendor;
1101
1102 dev->can_enumerate = 0;
1103
1104 (*device)->GetDeviceClass (device, &bDeviceClass);
1105 (*device)->GetDeviceProduct (device, &idProduct);
1106 (*device)->GetDeviceVendor (device, &idVendor);
1107
1108 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
1109 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
1110 * to follow the spec as closely as possible, try opening the device */
1111 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
1112
1113 do {
1114 /**** retrieve device descriptor ****/
1115 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
1116
1117 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
1118 /* received an overrun error but we still received a device descriptor */
1119 ret = kIOReturnSuccess;
1120
1121 if (kIOUSBVendorIDAppleComputer == idVendor) {
1122 /* NTH: don't bother retrying or unsuspending Apple devices */
1123 break;
1124 }
1125
1126 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
1127 0 == dev->dev_descriptor.bcdUSB)) {
1128 /* work around for incorrectly configured devices */
1129 if (try_reconfigure && is_open) {
1130 usbi_dbg(ctx, "descriptor appears to be invalid. resetting configuration before trying again...");
1131
1132 /* set the first configuration */
1133 (*device)->SetConfiguration(device, 1);
1134
1135 /* don't try to reconfigure again */
1136 try_reconfigure = 0;
1137 }
1138
1139 ret = kIOUSBPipeStalled;
1140 }
1141
1142 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
1143 /* device may be suspended. unsuspend it and try again */
1144 #if MAX_DEVICE_VERSION >= 320
1145 if (get_device_interface_version() >= 320) {
1146 UInt32 info = 0;
1147
1148 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
1149 (void)(*IODEVICE_V(device, 320))->GetUSBDeviceInformation (device, &info);
1150
1151 /* note that the device was suspended */
1152 if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
1153 try_unsuspend = 1;
1154 }
1155 #endif
1156
1157 if (try_unsuspend) {
1158 /* try to unsuspend the device */
1159 ret2 = (*device)->USBDeviceSuspend (device, 0);
1160 if (kIOReturnSuccess != ret2) {
1161 /* prevent log spew from poorly behaving devices. this indicates the
1162 os actually had trouble communicating with the device */
1163 usbi_dbg(ctx, "could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
1164 } else
1165 unsuspended = 1;
1166
1167 try_unsuspend = 0;
1168 }
1169 }
1170
1171 if (kIOReturnSuccess != ret) {
1172 usbi_dbg(ctx, "kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
1173 /* sleep for a little while before trying again */
1174 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000}, NULL);
1175 }
1176 } while (kIOReturnSuccess != ret && retries--);
1177
1178 if (unsuspended)
1179 /* resuspend the device */
1180 (void)(*device)->USBDeviceSuspend (device, 1);
1181
1182 if (is_open)
1183 (void) (*device)->USBDeviceClose (device);
1184
1185 if (ret != kIOReturnSuccess) {
1186 /* a debug message was already printed out for this error */
1187 if (LIBUSB_CLASS_HUB == bDeviceClass)
1188 usbi_dbg (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
1189 idVendor, idProduct, darwin_error_str (ret), ret);
1190 else
1191 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
1192 idVendor, idProduct, darwin_error_str (ret), ret);
1193 return darwin_to_libusb (ret);
1194 }
1195
1196 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
1197 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
1198 /* not a valid device */
1199 usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
1200 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
1201 return LIBUSB_ERROR_NO_DEVICE;
1202 }
1203
1204 usbi_dbg (ctx, "cached device descriptor:");
1205 usbi_dbg (ctx, " bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
1206 usbi_dbg (ctx, " bcdUSB: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
1207 usbi_dbg (ctx, " bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
1208 usbi_dbg (ctx, " bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
1209 usbi_dbg (ctx, " bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
1210 usbi_dbg (ctx, " bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
1211 usbi_dbg (ctx, " idVendor: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
1212 usbi_dbg (ctx, " idProduct: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
1213 usbi_dbg (ctx, " bcdDevice: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
1214 usbi_dbg (ctx, " iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
1215 usbi_dbg (ctx, " iProduct: 0x%02x", dev->dev_descriptor.iProduct);
1216 usbi_dbg (ctx, " iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
1217 usbi_dbg (ctx, " bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
1218
1219 dev->can_enumerate = 1;
1220
1221 return LIBUSB_SUCCESS;
1222 }
1223
1224 /* Returns 1 on success, 0 on failure. */
get_device_port(io_service_t service,UInt8 * port)1225 static bool get_device_port (io_service_t service, UInt8 *port) {
1226 IOReturn kresult;
1227 io_service_t parent;
1228 bool ret = false;
1229
1230 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
1231 return true;
1232 }
1233
1234 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
1235 if (kIOReturnSuccess == kresult) {
1236 ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port);
1237 IOObjectRelease (parent);
1238 }
1239
1240 return ret;
1241 }
1242
1243 /* Returns 1 on success, 0 on failure. */
get_device_parent_sessionID(io_service_t service,UInt64 * parent_sessionID)1244 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
1245 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
1246 io_service_t parent = service;
1247 do {
1248 IOReturn kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent);
1249 if (kresult != kIOReturnSuccess) {
1250 break;
1251 }
1252 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
1253 /* Success */
1254 return true;
1255 }
1256 } while (true);
1257
1258 /* We ran out of parents */
1259 return false;
1260 }
1261
darwin_get_cached_device(struct libusb_context * ctx,io_service_t service,struct darwin_cached_device ** cached_out,UInt64 * old_session_id)1262 static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service, struct darwin_cached_device **cached_out,
1263 UInt64 *old_session_id) {
1264 struct darwin_cached_device *new_device;
1265 UInt64 sessionID = 0, parent_sessionID = 0;
1266 UInt32 locationID = 0;
1267 enum libusb_error ret = LIBUSB_SUCCESS;
1268 usb_device_t device;
1269 UInt8 port = 0;
1270
1271 /* assuming sessionID != 0 normally (never seen it be 0) */
1272 *old_session_id = 0;
1273 *cached_out = NULL;
1274
1275 /* get some info from the io registry */
1276 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
1277 (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
1278 if (!get_device_port (service, &port)) {
1279 usbi_dbg(ctx, "could not get connected port number");
1280 }
1281
1282 usbi_dbg(ctx, "finding cached device for sessionID 0x%" PRIx64, sessionID);
1283
1284 if (get_device_parent_sessionID(service, &parent_sessionID)) {
1285 usbi_dbg(ctx, "parent sessionID: 0x%" PRIx64, parent_sessionID);
1286 }
1287
1288 usbi_mutex_lock(&darwin_cached_devices_mutex);
1289 do {
1290 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
1291 usbi_dbg(ctx, "matching sessionID/locationID 0x%" PRIx64 "/0x%" PRIx32 " against cached device with sessionID/locationID 0x%" PRIx64 "/0x%" PRIx32,
1292 sessionID, locationID, new_device->session, new_device->location);
1293 if (new_device->location == locationID && new_device->in_reenumerate) {
1294 usbi_dbg (ctx, "found cached device with matching location that is being re-enumerated");
1295 *old_session_id = new_device->session;
1296 break;
1297 }
1298
1299 if (new_device->session == sessionID) {
1300 usbi_dbg(ctx, "using cached device for device");
1301 *cached_out = new_device;
1302 break;
1303 }
1304 }
1305
1306 if (*cached_out)
1307 break;
1308
1309 usbi_dbg(ctx, "caching new device with sessionID 0x%" PRIx64, sessionID);
1310
1311 ret = darwin_device_from_service (ctx, service, &device);
1312 if (LIBUSB_SUCCESS != ret) {
1313 break;
1314 }
1315
1316 if (!(*old_session_id)) {
1317 new_device = calloc (1, sizeof (*new_device));
1318 if (!new_device) {
1319 ret = LIBUSB_ERROR_NO_MEM;
1320 break;
1321 }
1322
1323 /* add this device to the cached device list */
1324 list_add(&new_device->list, &darwin_cached_devices);
1325
1326 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
1327
1328 /* keep a reference to this device */
1329 darwin_ref_cached_device(new_device);
1330
1331 (*device)->GetLocationID (device, &new_device->location);
1332 new_device->port = port;
1333 new_device->parent_session = parent_sessionID;
1334 } else {
1335 /* release the ref to old device's service */
1336 IOObjectRelease (new_device->service);
1337 }
1338
1339 /* keep track of devices regardless of if we successfully enumerate them to
1340 prevent them from being enumerated multiple times */
1341 *cached_out = new_device;
1342
1343 new_device->session = sessionID;
1344 new_device->device = device;
1345 new_device->service = service;
1346
1347 /* retain the service */
1348 IOObjectRetain (service);
1349
1350 /* cache the device descriptor */
1351 ret = darwin_cache_device_descriptor(ctx, new_device);
1352 if (ret)
1353 break;
1354
1355 if (new_device->can_enumerate) {
1356 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
1357 libusb_le16_to_cpu (new_device->dev_descriptor.idVendor),
1358 libusb_le16_to_cpu (new_device->dev_descriptor.idProduct),
1359 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
1360 }
1361 } while (0);
1362
1363 usbi_mutex_unlock(&darwin_cached_devices_mutex);
1364
1365 assert((ret == LIBUSB_SUCCESS) ? (*cached_out != NULL) : true);
1366
1367 return ret;
1368 }
1369
process_new_device(struct libusb_context * ctx,struct darwin_cached_device * cached_device,UInt64 old_session_id)1370 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
1371 UInt64 old_session_id) {
1372 struct darwin_device_priv *priv;
1373 struct libusb_device *dev = NULL;
1374 UInt8 devSpeed;
1375 enum libusb_error ret = LIBUSB_SUCCESS;
1376
1377 do {
1378 /* check current active configuration (and cache the first configuration value--
1379 which may be used by claim_interface) */
1380 ret = darwin_check_configuration (ctx, cached_device);
1381 if (ret)
1382 break;
1383
1384 if (0 != old_session_id) {
1385 usbi_dbg (ctx, "re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
1386 ctx, old_session_id, cached_device->session);
1387 /* save the libusb device before the session id is updated */
1388 dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
1389 }
1390
1391 if (!dev) {
1392 usbi_dbg (ctx, "allocating new device in context %p for with session 0x%" PRIx64,
1393 ctx, cached_device->session);
1394
1395 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1396 if (!dev) {
1397 return LIBUSB_ERROR_NO_MEM;
1398 }
1399
1400 priv = usbi_get_device_priv(dev);
1401
1402 priv->dev = cached_device;
1403 darwin_ref_cached_device (priv->dev);
1404 dev->port_number = cached_device->port;
1405 /* the location ID encodes the path to the device. the top byte of the location ID contains the bus number
1406 (numbered from 0). the remaining bytes can be used to construct the device tree for that bus. */
1407 dev->bus_number = cached_device->location >> 24;
1408 assert(cached_device->address <= UINT8_MAX);
1409 dev->device_address = (uint8_t)cached_device->address;
1410 } else {
1411 priv = usbi_get_device_priv(dev);
1412 }
1413
1414 static_assert(sizeof(dev->device_descriptor) == sizeof(cached_device->dev_descriptor),
1415 "mismatch between libusb and IOKit device descriptor sizes");
1416 memcpy(&dev->device_descriptor, &cached_device->dev_descriptor, LIBUSB_DT_DEVICE_SIZE);
1417 usbi_localize_device_descriptor(&dev->device_descriptor);
1418 dev->session_data = cached_device->session;
1419
1420 if (NULL != dev->parent_dev) {
1421 libusb_unref_device(dev->parent_dev);
1422 dev->parent_dev = NULL;
1423 }
1424
1425 if (cached_device->parent_session > 0) {
1426 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1427 }
1428
1429 (*priv->dev->device)->GetDeviceSpeed (priv->dev->device, &devSpeed);
1430
1431 switch (devSpeed) {
1432 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1433 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1434 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1435 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
1436 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1437 #endif
1438 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1439 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1440 #endif
1441 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101500
1442 case kUSBDeviceSpeedSuperPlusBy2: dev->speed = LIBUSB_SPEED_SUPER_PLUS_X2; break;
1443 #endif
1444 default:
1445 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1446 }
1447
1448 ret = usbi_sanitize_device (dev);
1449 if (ret < 0)
1450 break;
1451
1452 usbi_dbg (ctx, "found device with address %d port = %d parent = %p at %p", dev->device_address,
1453 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1454
1455 } while (0);
1456
1457 if (!cached_device->in_reenumerate && 0 == ret) {
1458 usbi_connect_device (dev);
1459 } else {
1460 libusb_unref_device (dev);
1461 }
1462
1463 return ret;
1464 }
1465
darwin_scan_devices(struct libusb_context * ctx)1466 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1467 struct darwin_cached_device *cached_device;
1468 UInt64 old_session_id;
1469 io_iterator_t deviceIterator;
1470 io_service_t service;
1471 IOReturn kresult;
1472 int ret;
1473
1474 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1475 if (kresult != kIOReturnSuccess)
1476 return darwin_to_libusb (kresult);
1477
1478 while ((service = IOIteratorNext (deviceIterator))) {
1479 ret = darwin_get_cached_device (ctx, service, &cached_device, &old_session_id);
1480 assert((ret >= 0) ? (cached_device != NULL) : true);
1481 if (ret < 0 || !cached_device->can_enumerate) {
1482 continue;
1483 }
1484
1485 (void) process_new_device (ctx, cached_device, old_session_id);
1486
1487 IOObjectRelease(service);
1488 }
1489
1490 IOObjectRelease(deviceIterator);
1491
1492 return LIBUSB_SUCCESS;
1493 }
1494
darwin_open(struct libusb_device_handle * dev_handle)1495 static int darwin_open (struct libusb_device_handle *dev_handle) {
1496 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1497 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1498 IOReturn kresult;
1499
1500 if (0 == dpriv->open_count) {
1501 /* try to open the device */
1502 kresult = (*dpriv->device)->USBDeviceOpenSeize (dpriv->device);
1503 if (kresult != kIOReturnSuccess) {
1504 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1505
1506 if (kIOReturnExclusiveAccess != kresult) {
1507 return darwin_to_libusb (kresult);
1508 }
1509
1510 /* it is possible to perform some actions on a device that is not open so do not return an error */
1511 priv->is_open = false;
1512 } else {
1513 priv->is_open = true;
1514 }
1515
1516 /* create async event source */
1517 kresult = (*dpriv->device)->CreateDeviceAsyncEventSource (dpriv->device,
1518 &priv->cfSource);
1519 if (kresult != kIOReturnSuccess) {
1520 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1521
1522 if (priv->is_open) {
1523 (*dpriv->device)->USBDeviceClose (dpriv->device);
1524 }
1525
1526 priv->is_open = false;
1527
1528 return darwin_to_libusb (kresult);
1529 }
1530
1531 CFRetain (libusb_darwin_acfl);
1532
1533 /* add the cfSource to the async run loop */
1534 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1535 }
1536
1537 /* device opened successfully */
1538 dpriv->open_count++;
1539
1540 usbi_dbg (HANDLE_CTX(dev_handle), "device open for access");
1541
1542 return 0;
1543 }
1544
darwin_close(struct libusb_device_handle * dev_handle)1545 static void darwin_close (struct libusb_device_handle *dev_handle) {
1546 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1547 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1548 IOReturn kresult;
1549 int i;
1550
1551 if (dpriv->open_count == 0) {
1552 /* something is probably very wrong if this is the case */
1553 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1554 return;
1555 }
1556
1557 dpriv->open_count--;
1558 if (NULL == dpriv->device) {
1559 usbi_warn (HANDLE_CTX (dev_handle), "darwin_close device missing IOService");
1560 return;
1561 }
1562
1563 /* make sure all interfaces are released */
1564 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1565 if (dev_handle->claimed_interfaces & (1U << i))
1566 libusb_release_interface (dev_handle, i);
1567
1568 if (0 == dpriv->open_count) {
1569 /* delete the device's async event source */
1570 if (priv->cfSource) {
1571 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1572 CFRelease (priv->cfSource);
1573 priv->cfSource = NULL;
1574 CFRelease (libusb_darwin_acfl);
1575 }
1576
1577 if (priv->is_open) {
1578 /* close the device */
1579 kresult = (*dpriv->device)->USBDeviceClose(dpriv->device);
1580 if (kresult != kIOReturnSuccess) {
1581 /* Log the fact that we had a problem closing the file, however failing a
1582 * close isn't really an error, so return success anyway */
1583 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1584 }
1585 }
1586 }
1587 }
1588
darwin_get_configuration(struct libusb_device_handle * dev_handle,uint8_t * config)1589 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config) {
1590 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1591
1592 *config = dpriv->active_config;
1593
1594 return LIBUSB_SUCCESS;
1595 }
1596
darwin_set_configuration(struct libusb_device_handle * dev_handle,int config)1597 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1598 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1599 IOReturn kresult;
1600 uint8_t i;
1601
1602 if (config == -1)
1603 config = 0;
1604
1605 /* Setting configuration will invalidate the interface, so we need
1606 to reclaim it. First, dispose of existing interfaces, if any. */
1607 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1608 if (dev_handle->claimed_interfaces & (1U << i))
1609 darwin_release_interface (dev_handle, i);
1610
1611 kresult = (*dpriv->device)->SetConfiguration (dpriv->device, (UInt8)config);
1612 if (kresult != kIOReturnSuccess)
1613 return darwin_to_libusb (kresult);
1614
1615 /* Reclaim any interfaces. */
1616 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1617 if (dev_handle->claimed_interfaces & (1U << i))
1618 darwin_claim_interface (dev_handle, i);
1619
1620 dpriv->active_config = (UInt8)config;
1621
1622 return LIBUSB_SUCCESS;
1623 }
1624
darwin_get_interface(usb_device_t darwin_device,uint8_t ifc,io_service_t * usbInterfacep)1625 static IOReturn darwin_get_interface (usb_device_t darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1626 IOUSBFindInterfaceRequest request;
1627 IOReturn kresult;
1628 io_iterator_t interface_iterator;
1629 UInt8 bInterfaceNumber;
1630 bool ret;
1631
1632 *usbInterfacep = IO_OBJECT_NULL;
1633
1634 /* Setup the Interface Request */
1635 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1636 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1637 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1638 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1639
1640 kresult = (*darwin_device)->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1641 if (kresult != kIOReturnSuccess)
1642 return kresult;
1643
1644 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1645 /* find the interface number */
1646 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1647 &bInterfaceNumber);
1648
1649 if (ret && bInterfaceNumber == ifc) {
1650 break;
1651 }
1652
1653 (void) IOObjectRelease (*usbInterfacep);
1654 }
1655
1656 /* done with the interface iterator */
1657 IOObjectRelease(interface_iterator);
1658
1659 return kIOReturnSuccess;
1660 }
1661
get_interface_descriptor_by_number(struct libusb_device_handle * dev_handle,struct libusb_config_descriptor * conf_desc,int iface,uint8_t altsetting)1662 static const struct libusb_interface_descriptor *get_interface_descriptor_by_number(struct libusb_device_handle *dev_handle, struct libusb_config_descriptor *conf_desc, int iface, uint8_t altsetting)
1663 {
1664 int i;
1665
1666 for (i = 0; i < conf_desc->bNumInterfaces; i++) {
1667 if (altsetting < conf_desc->interface[i].num_altsetting && conf_desc->interface[i].altsetting[altsetting].bInterfaceNumber == iface) {
1668 return &conf_desc->interface[i].altsetting[altsetting];
1669 }
1670 }
1671
1672 usbi_err(HANDLE_CTX(dev_handle), "interface %d with altsetting %d not found for device", iface, (int)altsetting);
1673 return NULL;
1674 }
1675
get_endpoints(struct libusb_device_handle * dev_handle,uint8_t iface)1676 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, uint8_t iface) {
1677 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1678
1679 /* current interface */
1680 struct darwin_interface *cInterface = &priv->interfaces[iface];
1681 IOReturn kresult;
1682 uint8_t numep;
1683 int rc;
1684 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
1685
1686 usbi_dbg (ctx, "building table of endpoints.");
1687
1688 /* retrieve the total number of endpoints on this interface */
1689 kresult = (*IOINTERFACE(cInterface))->GetNumEndpoints(IOINTERFACE(cInterface), &numep);
1690 if (kresult != kIOReturnSuccess) {
1691 usbi_err (ctx, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1692 return darwin_to_libusb (kresult);
1693 }
1694
1695 /* iterate through pipe references */
1696 for (UInt8 i = 1 ; i <= numep ; i++) {
1697 darwin_pipe_properties_t pipe_properties;
1698 kresult = darwin_get_pipe_properties(cInterface, i, &pipe_properties);
1699 if (kresult != kIOReturnSuccess) {
1700 /* probably a buggy device. try to get the endpoint address from the descriptors */
1701 struct libusb_config_descriptor *config;
1702 const struct libusb_interface_descriptor *if_desc;
1703 const struct libusb_endpoint_descriptor *endpoint_desc;
1704 UInt8 alt_setting;
1705
1706 kresult = (*IOINTERFACE(cInterface))->GetAlternateSetting (IOINTERFACE(cInterface), &alt_setting);
1707 if (kresult != kIOReturnSuccess) {
1708 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1709 return darwin_to_libusb (kresult);
1710 }
1711
1712 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1713 if (LIBUSB_SUCCESS != rc) {
1714 return rc;
1715 }
1716
1717 if_desc = get_interface_descriptor_by_number (dev_handle, config, iface, alt_setting);
1718 if (if_desc == NULL) {
1719 libusb_free_config_descriptor (config);
1720 return LIBUSB_ERROR_NOT_FOUND;
1721 }
1722
1723 endpoint_desc = if_desc->endpoint + i - 1;
1724
1725 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1726 libusb_free_config_descriptor (config);
1727 } else {
1728 cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == pipe_properties.direction) << kUSBRqDirnShift) |
1729 (pipe_properties.number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1730 }
1731
1732 usbi_dbg (ctx, "interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1733 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1734 }
1735
1736 cInterface->num_endpoints = numep;
1737
1738 return LIBUSB_SUCCESS;
1739 }
1740
darwin_claim_interface(struct libusb_device_handle * dev_handle,uint8_t iface)1741 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1742 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1743 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1744 io_service_t usbInterface = IO_OBJECT_NULL;
1745 IOReturn kresult;
1746 enum libusb_error ret;
1747 IOCFPlugInInterface **plugInInterface = NULL;
1748 SInt32 score;
1749
1750 /* current interface */
1751 struct darwin_interface *cInterface = &priv->interfaces[iface];
1752
1753 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
1754
1755 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1756 if (kresult != kIOReturnSuccess)
1757 return darwin_to_libusb (kresult);
1758
1759 /* make sure we have an interface */
1760 if (!usbInterface && dpriv->first_config != 0) {
1761 usbi_info (ctx, "no interface found; setting configuration: %d", dpriv->first_config);
1762
1763 /* set the configuration */
1764 ret = darwin_set_configuration (dev_handle, (int) dpriv->first_config);
1765 if (ret != LIBUSB_SUCCESS) {
1766 usbi_err (ctx, "could not set configuration");
1767 return ret;
1768 }
1769
1770 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1771 if (kresult != kIOReturnSuccess) {
1772 usbi_err (ctx, "darwin_get_interface: %s", darwin_error_str(kresult));
1773 return darwin_to_libusb (kresult);
1774 }
1775 }
1776
1777 if (!usbInterface) {
1778 usbi_info (ctx, "interface not found");
1779 return LIBUSB_ERROR_NOT_FOUND;
1780 }
1781
1782 /* get an interface to the device's interface */
1783 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1784 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1785
1786 /* ignore release error */
1787 (void)IOObjectRelease (usbInterface);
1788
1789 if (kresult != kIOReturnSuccess) {
1790 usbi_err (ctx, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1791 return darwin_to_libusb (kresult);
1792 }
1793
1794 if (!plugInInterface) {
1795 usbi_err (ctx, "plugin interface not found");
1796 return LIBUSB_ERROR_NOT_FOUND;
1797 }
1798
1799 /* Do the actual claim */
1800 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1801 CFUUIDGetUUIDBytes(get_interface_interface_id()),
1802 (LPVOID)&IOINTERFACE(cInterface));
1803 /* We no longer need the intermediate plug-in */
1804 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1805 (*plugInInterface)->Release (plugInInterface);
1806 if (kresult != kIOReturnSuccess) {
1807 usbi_err (ctx, "QueryInterface: %s", darwin_error_str(kresult));
1808 return darwin_to_libusb (kresult);
1809 }
1810 if (!IOINTERFACE(cInterface)) {
1811 usbi_err (ctx, "QueryInterface: returned null interface");
1812 return LIBUSB_ERROR_OTHER;
1813 }
1814
1815 /* claim the interface */
1816 kresult = (*IOINTERFACE(cInterface))->USBInterfaceOpen(IOINTERFACE(cInterface));
1817 if (kresult != kIOReturnSuccess) {
1818 usbi_info (ctx, "USBInterfaceOpen: %s", darwin_error_str(kresult));
1819 return darwin_to_libusb (kresult);
1820 }
1821
1822 /* update list of endpoints */
1823 ret = get_endpoints (dev_handle, iface);
1824 if (ret) {
1825 /* this should not happen */
1826 darwin_release_interface (dev_handle, iface);
1827 usbi_err (ctx, "could not build endpoint table");
1828 return ret;
1829 }
1830
1831 cInterface->cfSource = NULL;
1832
1833 /* create async event source */
1834 kresult = (*IOINTERFACE(cInterface))->CreateInterfaceAsyncEventSource (IOINTERFACE(cInterface), &cInterface->cfSource);
1835 if (kresult != kIOReturnSuccess) {
1836 usbi_err (ctx, "could not create async event source");
1837
1838 /* can't continue without an async event source */
1839 (void)darwin_release_interface (dev_handle, iface);
1840
1841 return darwin_to_libusb (kresult);
1842 }
1843
1844 /* add the cfSource to the async thread's run loop */
1845 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1846
1847 usbi_dbg (ctx, "interface opened");
1848
1849 return LIBUSB_SUCCESS;
1850 }
1851
darwin_release_interface(struct libusb_device_handle * dev_handle,uint8_t iface)1852 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1853 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1854 IOReturn kresult;
1855
1856 /* current interface */
1857 struct darwin_interface *cInterface = &priv->interfaces[iface];
1858
1859 /* Check to see if an interface is open */
1860 if (!IOINTERFACE(cInterface)) {
1861 return LIBUSB_SUCCESS;
1862 }
1863
1864 /* clean up endpoint data */
1865 cInterface->num_endpoints = 0;
1866
1867 /* delete the interface's async event source */
1868 if (cInterface->cfSource) {
1869 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1870 CFRelease (cInterface->cfSource);
1871 cInterface->cfSource = NULL;
1872 }
1873
1874 kresult = (*IOINTERFACE(cInterface))->USBInterfaceClose(IOINTERFACE(cInterface));
1875 if (kresult != kIOReturnSuccess)
1876 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1877
1878 ULONG refCount = (*IOINTERFACE(cInterface))->Release(IOINTERFACE(cInterface));
1879 if (refCount != 0) {
1880 usbi_warn (HANDLE_CTX (dev_handle), "Release final refCount: %u", refCount);
1881 }
1882
1883 IOINTERFACE(cInterface) = NULL;
1884
1885 return darwin_to_libusb (kresult);
1886 }
1887
check_alt_setting_and_clear_halt(struct libusb_device_handle * dev_handle,uint8_t altsetting,struct darwin_interface * cInterface)1888 static int check_alt_setting_and_clear_halt(struct libusb_device_handle *dev_handle, uint8_t altsetting, struct darwin_interface *cInterface) {
1889 enum libusb_error ret;
1890 IOReturn kresult;
1891 uint8_t current_alt_setting;
1892
1893 kresult = (*IOINTERFACE(cInterface))->GetAlternateSetting (IOINTERFACE(cInterface), ¤t_alt_setting);
1894 if (kresult == kIOReturnSuccess && altsetting != current_alt_setting) {
1895 return LIBUSB_ERROR_PIPE;
1896 }
1897
1898 for (int i = 0 ; i < cInterface->num_endpoints ; i++) {
1899 ret = darwin_clear_halt(dev_handle, cInterface->endpoint_addrs[i]);
1900 if (LIBUSB_SUCCESS != ret) {
1901 usbi_warn(HANDLE_CTX (dev_handle), "error clearing pipe halt for endpoint %d", i);
1902 if (LIBUSB_ERROR_NOT_FOUND == ret) {
1903 /* may need to re-open the interface */
1904 return ret;
1905 }
1906 }
1907 }
1908
1909 return LIBUSB_SUCCESS;
1910 }
1911
darwin_set_interface_altsetting(struct libusb_device_handle * dev_handle,uint8_t iface,uint8_t altsetting)1912 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting) {
1913 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1914 IOReturn kresult;
1915 enum libusb_error ret;
1916
1917 /* current interface */
1918 struct darwin_interface *cInterface = &priv->interfaces[iface];
1919
1920 if (!IOINTERFACE(cInterface)) {
1921 return LIBUSB_ERROR_NO_DEVICE;
1922 }
1923
1924 kresult = (*IOINTERFACE(cInterface))->SetAlternateInterface (IOINTERFACE(cInterface), altsetting);
1925 if (kresult == kIOReturnSuccess) {
1926 /* update the list of endpoints */
1927 ret = get_endpoints (dev_handle, iface);
1928 if (ret) {
1929 /* this should not happen */
1930 darwin_release_interface (dev_handle, iface);
1931 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
1932 }
1933 return ret;
1934 }
1935
1936 usbi_warn (HANDLE_CTX (dev_handle), "SetAlternateInterface: %s", darwin_error_str(kresult));
1937
1938 ret = darwin_to_libusb(kresult);
1939 if (ret != LIBUSB_ERROR_PIPE) {
1940 return ret;
1941 }
1942
1943 /* If a device only supports a default setting for the specified interface, then a STALL
1944 (kIOUSBPipeStalled) may be returned. Ref: USB 2.0 specs 9.4.10.
1945 Mimic the behaviour in e.g. the Linux kernel: in such case, reset all endpoints
1946 of the interface (as would have been done per 9.1.1.5) and return success. */
1947
1948 ret = check_alt_setting_and_clear_halt(dev_handle, altsetting, cInterface);
1949 if (LIBUSB_ERROR_NOT_FOUND == ret) {
1950 /* For some reason we need to reclaim the interface after the pipe error with some versions of macOS */
1951 ret = darwin_claim_interface (dev_handle, iface);
1952 if (LIBUSB_SUCCESS != ret) {
1953 darwin_release_interface (dev_handle, iface);
1954 usbi_err (HANDLE_CTX (dev_handle), "could not reclaim interface: %s", darwin_error_str(kresult));
1955 }
1956 ret = check_alt_setting_and_clear_halt(dev_handle, altsetting, cInterface);
1957 }
1958
1959 return ret;
1960 }
1961
darwin_clear_halt(struct libusb_device_handle * dev_handle,unsigned char endpoint)1962 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
1963 /* current interface */
1964 struct darwin_interface *cInterface;
1965 IOReturn kresult;
1966 uint8_t pipeRef;
1967
1968 /* determine the interface/endpoint to use */
1969 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
1970 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
1971
1972 return LIBUSB_ERROR_NOT_FOUND;
1973 }
1974
1975 /* newer versions of darwin support clearing additional bits on the device's endpoint */
1976 kresult = (*IOINTERFACE(cInterface))->ClearPipeStallBothEnds(IOINTERFACE(cInterface), pipeRef);
1977 if (kresult != kIOReturnSuccess)
1978 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
1979
1980 return darwin_to_libusb (kresult);
1981 }
1982
darwin_restore_state(struct libusb_device_handle * dev_handle,uint8_t active_config,unsigned long claimed_interfaces)1983 static int darwin_restore_state (struct libusb_device_handle *dev_handle, uint8_t active_config,
1984 unsigned long claimed_interfaces) {
1985 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1986 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1987 int open_count = dpriv->open_count;
1988 int ret;
1989
1990 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
1991
1992 /* clear claimed interfaces temporarily */
1993 dev_handle->claimed_interfaces = 0;
1994
1995 /* close and re-open the device */
1996 priv->is_open = false;
1997 dpriv->open_count = 1;
1998
1999 /* clean up open interfaces */
2000 (void) darwin_close (dev_handle);
2001
2002 /* re-open the device */
2003 ret = darwin_open (dev_handle);
2004 dpriv->open_count = open_count;
2005 if (LIBUSB_SUCCESS != ret) {
2006 /* could not restore configuration */
2007 return LIBUSB_ERROR_NOT_FOUND;
2008 }
2009
2010 if (dpriv->active_config != active_config) {
2011 usbi_dbg (ctx, "darwin/restore_state: restoring configuration %d...", active_config);
2012
2013 ret = darwin_set_configuration (dev_handle, active_config);
2014 if (LIBUSB_SUCCESS != ret) {
2015 usbi_dbg (ctx, "darwin/restore_state: could not restore configuration");
2016 return LIBUSB_ERROR_NOT_FOUND;
2017 }
2018 }
2019
2020 usbi_dbg (ctx, "darwin/restore_state: reclaiming interfaces");
2021
2022 if (claimed_interfaces) {
2023 for (uint8_t iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
2024 if (!(claimed_interfaces & (1U << iface))) {
2025 continue;
2026 }
2027
2028 usbi_dbg (ctx, "darwin/restore_state: re-claiming interface %u", iface);
2029
2030 ret = darwin_claim_interface (dev_handle, iface);
2031 if (LIBUSB_SUCCESS != ret) {
2032 usbi_dbg (ctx, "darwin/restore_state: could not claim interface %u", iface);
2033 return LIBUSB_ERROR_NOT_FOUND;
2034 }
2035
2036 dev_handle->claimed_interfaces |= 1U << iface;
2037 }
2038 }
2039
2040 usbi_dbg (ctx, "darwin/restore_state: device state restored");
2041
2042 return LIBUSB_SUCCESS;
2043 }
2044
darwin_reenumerate_device(struct libusb_device_handle * dev_handle,bool capture)2045 static int darwin_reenumerate_device (struct libusb_device_handle *dev_handle, bool capture) {
2046 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2047 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
2048 uint8_t active_config = dpriv->active_config;
2049 UInt32 options = 0;
2050 IOUSBDeviceDescriptor descriptor;
2051 IOUSBConfigurationDescriptorPtr cached_configuration;
2052 IOUSBConfigurationDescriptor *cached_configurations;
2053 IOReturn kresult;
2054 UInt8 i;
2055
2056 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
2057
2058 if (dpriv->in_reenumerate) {
2059 /* ack, two (or more) threads are trying to reset the device! abort! */
2060 return LIBUSB_ERROR_NOT_FOUND;
2061 }
2062
2063 dpriv->in_reenumerate = true;
2064
2065 /* store copies of descriptors so they can be compared after the reset */
2066 memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
2067 cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
2068
2069 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
2070 (*dpriv->device)->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
2071 memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
2072 }
2073
2074 /* if we need to release capture */
2075 if (get_running_version() >= 101000) {
2076 if (capture) {
2077 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000
2078 options |= kUSBReEnumerateCaptureDeviceMask;
2079 #endif
2080 }
2081 } else {
2082 capture = false;
2083 }
2084
2085 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
2086 kresult = (*dpriv->device)->USBDeviceReEnumerate (dpriv->device, options);
2087 if (kresult != kIOReturnSuccess) {
2088 usbi_err (ctx, "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
2089 dpriv->in_reenumerate = false;
2090 return darwin_to_libusb (kresult);
2091 }
2092
2093 /* capture mode does not re-enumerate but it does require re-open */
2094 if (capture) {
2095 usbi_dbg (ctx, "darwin/reenumerate_device: restoring state...");
2096 dpriv->in_reenumerate = false;
2097 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
2098 }
2099
2100 usbi_dbg (ctx, "darwin/reenumerate_device: waiting for re-enumeration to complete...");
2101
2102 struct timespec start;
2103 usbi_get_monotonic_time(&start);
2104
2105 while (dpriv->in_reenumerate) {
2106 struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
2107 nanosleep (&delay, NULL);
2108
2109 struct timespec now;
2110 usbi_get_monotonic_time(&now);
2111 long delta_sec = now.tv_sec - start.tv_sec;
2112 long delta_nsec = now.tv_nsec - start.tv_nsec;
2113 unsigned long long elapsed_us = (unsigned long long)delta_sec * USEC_PER_SEC +
2114 (unsigned long long)delta_nsec / 1000ULL;
2115
2116 if (elapsed_us >= DARWIN_REENUMERATE_TIMEOUT_US) {
2117 usbi_err (ctx, "darwin/reenumerate_device: timeout waiting for reenumerate");
2118 dpriv->in_reenumerate = false;
2119 return LIBUSB_ERROR_TIMEOUT;
2120 }
2121 }
2122
2123 /* compare descriptors */
2124 usbi_dbg (ctx, "darwin/reenumerate_device: checking whether descriptors changed");
2125
2126 if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor))) {
2127 /* device descriptor changed. need to return not found. */
2128 usbi_dbg (ctx, "darwin/reenumerate_device: device descriptor changed");
2129 return LIBUSB_ERROR_NOT_FOUND;
2130 }
2131
2132 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
2133 (void) (*dpriv->device)->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
2134 if (memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i]))) {
2135 usbi_dbg (ctx, "darwin/reenumerate_device: configuration descriptor %d changed", i);
2136 return LIBUSB_ERROR_NOT_FOUND;
2137 }
2138 }
2139
2140 usbi_dbg (ctx, "darwin/reenumerate_device: device reset complete. restoring state...");
2141
2142 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
2143 }
2144
darwin_reset_device(struct libusb_device_handle * dev_handle)2145 static int darwin_reset_device (struct libusb_device_handle *dev_handle) {
2146 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2147 IOReturn kresult;
2148 enum libusb_error ret;
2149
2150 #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
2151 if (dpriv->capture_count > 0) {
2152 /* we have to use ResetDevice as USBDeviceReEnumerate() loses the authorization for capture */
2153 kresult = (*dpriv->device)->ResetDevice (dpriv->device);
2154 ret = darwin_to_libusb (kresult);
2155 } else {
2156 ret = darwin_reenumerate_device (dev_handle, false);
2157 }
2158 #else
2159 /* ResetDevice() is missing on non-macOS platforms */
2160 ret = darwin_reenumerate_device (dev_handle, false);
2161 if ((ret == LIBUSB_SUCCESS || ret == LIBUSB_ERROR_NOT_FOUND) && dpriv->capture_count > 0) {
2162 int capture_count;
2163 uint8_t active_config = dpriv->active_config;
2164 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
2165
2166 /* save old capture_count */
2167 capture_count = dpriv->capture_count;
2168 /* reset capture count */
2169 dpriv->capture_count = 0;
2170 /* attempt to detach kernel driver again as it is now re-attached */
2171 ret = darwin_detach_kernel_driver (dev_handle, 0);
2172 if (ret != LIBUSB_SUCCESS) {
2173 return ret;
2174 }
2175 /* restore capture_count */
2176 dpriv->capture_count = capture_count;
2177 /* restore configuration */
2178 ret = darwin_restore_state (dev_handle, active_config, claimed_interfaces);
2179 }
2180 #endif
2181 return ret;
2182 }
2183
usb_find_interface_matching_location(const io_name_t class_name,UInt8 interface_number,UInt32 location)2184 static io_service_t usb_find_interface_matching_location (const io_name_t class_name, UInt8 interface_number, UInt32 location) {
2185 CFMutableDictionaryRef matchingDict = IOServiceMatching (class_name);
2186 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable (kCFAllocatorDefault, 0,
2187 &kCFTypeDictionaryKeyCallBacks,
2188 &kCFTypeDictionaryValueCallBacks);
2189 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
2190 CFTypeRef interfaceCF = CFNumberCreate (NULL, kCFNumberSInt8Type, &interface_number);
2191
2192 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
2193 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
2194 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBHostMatchingPropertyInterfaceNumber), interfaceCF);
2195
2196 CFRelease (interfaceCF);
2197 CFRelease (locationCF);
2198 CFRelease (propertyMatchDict);
2199
2200 return IOServiceGetMatchingService (darwin_default_master_port, matchingDict);
2201 }
2202
darwin_kernel_driver_active(struct libusb_device_handle * dev_handle,uint8_t interface)2203 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
2204 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2205 io_service_t usb_interface, child = IO_OBJECT_NULL;
2206
2207 /* locate the IO registry entry for this interface */
2208 usb_interface = usb_find_interface_matching_location (kIOUSBHostInterfaceClassName, interface, dpriv->location);
2209 if (0 == usb_interface) {
2210 /* check for the legacy class entry */
2211 usb_interface = usb_find_interface_matching_location (kIOUSBInterfaceClassName, interface, dpriv->location);
2212 if (0 == usb_interface) {
2213 return LIBUSB_ERROR_NOT_FOUND;
2214 }
2215 }
2216
2217 /* if the IO object has a child entry in the IO Registry it has a kernel driver attached */
2218 (void) IORegistryEntryGetChildEntry (usb_interface, kIOServicePlane, &child);
2219 IOObjectRelease (usb_interface);
2220 if (IO_OBJECT_NULL != child) {
2221 IOObjectRelease (child);
2222 return 1;
2223 }
2224
2225 /* no driver */
2226 return 0;
2227 }
2228
darwin_destroy_device(struct libusb_device * dev)2229 static void darwin_destroy_device(struct libusb_device *dev) {
2230 struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
2231
2232 if (dpriv->dev) {
2233 /* need to hold the lock in case this is the last reference to the device */
2234 usbi_mutex_lock(&darwin_cached_devices_mutex);
2235 darwin_deref_cached_device (dpriv->dev);
2236 dpriv->dev = NULL;
2237 usbi_mutex_unlock(&darwin_cached_devices_mutex);
2238 }
2239 }
2240
submit_bulk_transfer(struct usbi_transfer * itransfer)2241 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
2242 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2243
2244 IOReturn ret;
2245 uint8_t pipeRef;
2246
2247 struct darwin_interface *cInterface;
2248 darwin_pipe_properties_t pipe_properties;
2249
2250 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2251 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2252
2253 return LIBUSB_ERROR_NOT_FOUND;
2254 }
2255
2256 ret = darwin_get_pipe_properties(cInterface, pipeRef, &pipe_properties);
2257 if (kIOReturnSuccess != ret) {
2258 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
2259 darwin_error_str(ret), ret);
2260 return darwin_to_libusb (ret);
2261 }
2262
2263 if (0 != (transfer->length % pipe_properties.max_packet_size)) {
2264 /* do not need a zero packet */
2265 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
2266 }
2267
2268 /* submit the request */
2269 /* timeouts are unavailable on interrupt endpoints */
2270 if (pipe_properties.transfer_type == kUSBInterrupt) {
2271 if (IS_XFERIN(transfer))
2272 ret = (*IOINTERFACE(cInterface))->ReadPipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2273 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
2274 else
2275 ret = (*IOINTERFACE(cInterface))->WritePipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2276 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
2277 } else {
2278 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2279
2280 if (IS_XFERIN(transfer))
2281 ret = (*IOINTERFACE(cInterface))->ReadPipeAsyncTO(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2282 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
2283 darwin_async_io_callback, itransfer);
2284 else
2285 ret = (*IOINTERFACE(cInterface))->WritePipeAsyncTO(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2286 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
2287 darwin_async_io_callback, itransfer);
2288 }
2289
2290 if (ret)
2291 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
2292 darwin_error_str(ret), ret);
2293
2294 return darwin_to_libusb (ret);
2295 }
2296
2297 #if MAX_INTERFACE_VERSION >= 550
submit_stream_transfer(struct usbi_transfer * itransfer)2298 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
2299 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2300 struct darwin_interface *cInterface;
2301 uint8_t pipeRef;
2302 IOReturn ret;
2303
2304 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2305 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2306
2307 return LIBUSB_ERROR_NOT_FOUND;
2308 }
2309
2310 if (get_interface_interface_version() < 550) {
2311 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version %d does not support bulk stream transfers",
2312 get_interface_interface_version());
2313 return LIBUSB_ERROR_NOT_SUPPORTED;
2314 }
2315
2316 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2317
2318 if (IS_XFERIN(transfer))
2319 ret = (*IOINTERFACE_V(cInterface, 550))->ReadStreamsPipeAsyncTO(IOINTERFACE(cInterface), pipeRef, itransfer->stream_id,
2320 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
2321 transfer->timeout, darwin_async_io_callback, itransfer);
2322 else
2323 ret = (*IOINTERFACE_V(cInterface, 550))->WriteStreamsPipeAsyncTO(IOINTERFACE(cInterface), pipeRef, itransfer->stream_id,
2324 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
2325 transfer->timeout, darwin_async_io_callback, itransfer);
2326
2327 if (ret)
2328 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
2329 darwin_error_str(ret), ret);
2330
2331 return darwin_to_libusb (ret);
2332 }
2333 #endif
2334
submit_iso_transfer(struct usbi_transfer * itransfer)2335 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
2336 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2337 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2338
2339 IOReturn kresult;
2340 uint8_t pipeRef;
2341 UInt64 frame;
2342 AbsoluteTime atTime;
2343 int i;
2344 darwin_pipe_properties_t pipe_properties;
2345 struct darwin_interface *cInterface;
2346
2347 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
2348 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
2349 free(tpriv->isoc_framelist);
2350 tpriv->isoc_framelist = NULL;
2351 }
2352
2353 if (!tpriv->isoc_framelist) {
2354 tpriv->num_iso_packets = transfer->num_iso_packets;
2355 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
2356 if (!tpriv->isoc_framelist)
2357 return LIBUSB_ERROR_NO_MEM;
2358 }
2359
2360 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
2361 for (i = 0 ; i < transfer->num_iso_packets ; i++) {
2362 unsigned int length = transfer->iso_packet_desc[i].length;
2363 assert(length <= UINT16_MAX);
2364 tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
2365 }
2366
2367 /* determine the interface/endpoint to use */
2368 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2369 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2370
2371 return LIBUSB_ERROR_NOT_FOUND;
2372 }
2373
2374 /* determine the properties of this endpoint and the speed of the device */
2375 kresult = darwin_get_pipe_properties(cInterface, pipeRef, &pipe_properties);
2376 if (kresult != kIOReturnSuccess) {
2377 usbi_err (TRANSFER_CTX (transfer), "failed to get pipe properties: %d", kresult);
2378 free(tpriv->isoc_framelist);
2379 tpriv->isoc_framelist = NULL;
2380
2381 return darwin_to_libusb (kresult);
2382 }
2383
2384 /* Last but not least we need the bus frame number */
2385 kresult = (*IOINTERFACE(cInterface))->GetBusFrameNumber(IOINTERFACE(cInterface), &frame, &atTime);
2386 if (kresult != kIOReturnSuccess) {
2387 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
2388 free(tpriv->isoc_framelist);
2389 tpriv->isoc_framelist = NULL;
2390
2391 return darwin_to_libusb (kresult);
2392 }
2393
2394 /* schedule for a frame a little in the future */
2395 frame += 4;
2396
2397 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
2398 frame = cInterface->frames[transfer->endpoint];
2399
2400 /* submit the request */
2401 if (IS_XFERIN(transfer))
2402 kresult = (*IOINTERFACE(cInterface))->ReadIsochPipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer, frame,
2403 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
2404 itransfer);
2405 else
2406 kresult = (*IOINTERFACE(cInterface))->WriteIsochPipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer, frame,
2407 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
2408 itransfer);
2409
2410 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
2411 /* Full speed */
2412 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (pipe_properties.interval - 1));
2413 else
2414 /* High/super speed */
2415 cInterface->frames[transfer->endpoint] = frame + (UInt32)transfer->num_iso_packets * (1U << (pipe_properties.interval - 1)) / 8;
2416
2417 if (kresult != kIOReturnSuccess) {
2418 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
2419 darwin_error_str(kresult));
2420 free (tpriv->isoc_framelist);
2421 tpriv->isoc_framelist = NULL;
2422 }
2423
2424 return darwin_to_libusb (kresult);
2425 }
2426
submit_control_transfer(struct usbi_transfer * itransfer)2427 static int submit_control_transfer(struct usbi_transfer *itransfer) {
2428 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2429 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
2430 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2431 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2432
2433 IOReturn kresult;
2434
2435 memset(&tpriv->req, 0, sizeof(tpriv->req));
2436
2437 /* IOUSBDeviceInterface expects the request in cpu endianness */
2438 tpriv->req.bmRequestType = setup->bmRequestType;
2439 tpriv->req.bRequest = setup->bRequest;
2440 /* these values should be in bus order from libusb_fill_control_setup */
2441 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
2442 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
2443 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
2444 /* data is stored after the libusb control block */
2445 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
2446 tpriv->req.completionTimeout = transfer->timeout;
2447 tpriv->req.noDataTimeout = transfer->timeout;
2448
2449 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2450
2451 /* all transfers in libusb-1.0 are async */
2452
2453 if (transfer->endpoint) {
2454 struct darwin_interface *cInterface;
2455 uint8_t pipeRef;
2456
2457 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2458 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2459
2460 return LIBUSB_ERROR_NOT_FOUND;
2461 }
2462
2463 kresult = (*IOINTERFACE(cInterface))->ControlRequestAsyncTO (IOINTERFACE(cInterface), pipeRef,
2464 &(tpriv->req), darwin_async_io_callback, itransfer);
2465 } else
2466 /* control request on endpoint 0 */
2467 kresult = (*dpriv->device)->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
2468
2469 if (kresult != kIOReturnSuccess)
2470 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
2471
2472 return darwin_to_libusb (kresult);
2473 }
2474
darwin_submit_transfer(struct usbi_transfer * itransfer)2475 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
2476 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2477
2478 switch (transfer->type) {
2479 case LIBUSB_TRANSFER_TYPE_CONTROL:
2480 return submit_control_transfer(itransfer);
2481 case LIBUSB_TRANSFER_TYPE_BULK:
2482 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2483 return submit_bulk_transfer(itransfer);
2484 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2485 return submit_iso_transfer(itransfer);
2486 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2487 #if MAX_INTERFACE_VERSION >= 550
2488 return submit_stream_transfer(itransfer);
2489 #else
2490 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
2491 return LIBUSB_ERROR_NOT_SUPPORTED;
2492 #endif
2493 default:
2494 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2495 return LIBUSB_ERROR_INVALID_PARAM;
2496 }
2497 }
2498
cancel_control_transfer(struct usbi_transfer * itransfer)2499 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
2500 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2501 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2502 IOReturn kresult;
2503
2504 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
2505
2506 if (!dpriv->device) {
2507 return LIBUSB_ERROR_NO_DEVICE;
2508 }
2509
2510 kresult = (*dpriv->device)->USBDeviceAbortPipeZero (dpriv->device);
2511
2512 return darwin_to_libusb (kresult);
2513 }
2514
darwin_abort_transfers(struct usbi_transfer * itransfer)2515 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
2516 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2517 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2518 struct darwin_interface *cInterface;
2519 uint8_t pipeRef, iface;
2520 IOReturn kresult;
2521
2522 struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
2523
2524 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
2525 usbi_err (ctx, "endpoint not found on any open interface");
2526
2527 return LIBUSB_ERROR_NOT_FOUND;
2528 }
2529
2530 if (!dpriv->device) {
2531 return LIBUSB_ERROR_NO_DEVICE;
2532 }
2533
2534 usbi_warn (ctx, "aborting all transactions on interface %d pipe %d", iface, pipeRef);
2535
2536 /* abort transactions */
2537 #if MAX_INTERFACE_VERSION >= 550
2538 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type && get_interface_interface_version() >= 550) {
2539 kresult = (*IOINTERFACE_V(cInterface, 550))->AbortStreamsPipe (IOINTERFACE(cInterface), pipeRef, itransfer->stream_id);
2540 } else
2541 #endif
2542 {
2543 kresult = (*IOINTERFACE(cInterface))->AbortPipe (IOINTERFACE(cInterface), pipeRef);
2544 }
2545
2546
2547 if (get_interface_interface_version() <= 245) {
2548 /* with older releases of IOUSBFamily the OS always clears the host side data toggle. for
2549 consistency also clear the data toggle on the device. */
2550 usbi_dbg (ctx, "calling ClearPipeStallBothEnds to clear the data toggle bit");
2551 kresult = (*IOINTERFACE(cInterface))->ClearPipeStallBothEnds(IOINTERFACE(cInterface), pipeRef);
2552 }
2553
2554 return darwin_to_libusb (kresult);
2555 }
2556
darwin_cancel_transfer(struct usbi_transfer * itransfer)2557 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
2558 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2559
2560 switch (transfer->type) {
2561 case LIBUSB_TRANSFER_TYPE_CONTROL:
2562 return cancel_control_transfer(itransfer);
2563 case LIBUSB_TRANSFER_TYPE_BULK:
2564 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2565 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2566 return darwin_abort_transfers (itransfer);
2567 default:
2568 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2569 return LIBUSB_ERROR_INVALID_PARAM;
2570 }
2571 }
2572
darwin_async_io_callback(void * refcon,IOReturn result,void * arg0)2573 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2574 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2575 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2576 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2577
2578 usbi_dbg (TRANSFER_CTX(transfer), "an async io operation has completed");
2579
2580 /* if requested write a zero packet */
2581 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2582 struct darwin_interface *cInterface;
2583 uint8_t pipeRef;
2584
2585 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2586
2587 (*IOINTERFACE(cInterface))->WritePipe (IOINTERFACE(cInterface), pipeRef, transfer->buffer, 0);
2588 }
2589
2590 tpriv->result = result;
2591 tpriv->size = (UInt32) (uintptr_t) arg0;
2592
2593 /* signal the core that this transfer is complete */
2594 usbi_signal_transfer_completion(itransfer);
2595 }
2596
darwin_transfer_status(struct usbi_transfer * itransfer,IOReturn result)2597 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2598 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2599 result = kIOUSBTransactionTimeout;
2600
2601 struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
2602
2603 switch (result) {
2604 case kIOReturnUnderrun:
2605 case kIOReturnSuccess:
2606 return LIBUSB_TRANSFER_COMPLETED;
2607 case kIOReturnAborted:
2608 return LIBUSB_TRANSFER_CANCELLED;
2609 case kIOUSBPipeStalled:
2610 usbi_dbg (ctx, "transfer error: pipe is stalled");
2611 return LIBUSB_TRANSFER_STALL;
2612 case kIOReturnOverrun:
2613 usbi_warn (ctx, "transfer error: data overrun");
2614 return LIBUSB_TRANSFER_OVERFLOW;
2615 case kIOUSBTransactionTimeout:
2616 usbi_warn (ctx, "transfer error: timed out");
2617 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2618 return LIBUSB_TRANSFER_TIMED_OUT;
2619 default:
2620 usbi_warn (ctx, "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2621 return LIBUSB_TRANSFER_ERROR;
2622 }
2623 }
2624
darwin_handle_transfer_completion(struct usbi_transfer * itransfer)2625 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2626 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2627 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2628 const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
2629 const char *transfer_types[] = {"control", "isoc", "bulk", "interrupt", "bulk-stream", NULL};
2630 bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2631 struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
2632
2633 if (transfer->type > max_transfer_type) {
2634 usbi_err (ctx, "unknown endpoint type %d", transfer->type);
2635 return LIBUSB_ERROR_INVALID_PARAM;
2636 }
2637
2638 if (NULL == tpriv) {
2639 usbi_err (ctx, "malformed request is missing transfer priv");
2640 return LIBUSB_ERROR_INVALID_PARAM;
2641 }
2642
2643 usbi_dbg (ctx, "handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
2644
2645 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result || kIOUSBTransactionTimeout == tpriv->result) {
2646 if (is_isoc && tpriv->isoc_framelist) {
2647 /* copy isochronous results back */
2648
2649 for (int i = 0; i < transfer->num_iso_packets ; i++) {
2650 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2651 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2652 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2653 }
2654 } else if (!is_isoc) {
2655 itransfer->transferred += tpriv->size;
2656 }
2657 }
2658
2659 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2660 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2661 }
2662
usbi_get_monotonic_time(struct timespec * tp)2663 void usbi_get_monotonic_time(struct timespec *tp) {
2664 /* Check if the SDK is new enough to declare clock_gettime(), and the deployment target is at least 10.12. */
2665 #if ((MAC_OS_X_VERSION_MAX_ALLOWED >= 101200) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 101200))
2666 clock_gettime(CLOCK_MONOTONIC, tp);
2667 #else
2668 mach_timebase_info_data_t machTimeBaseInfo;
2669 mach_timebase_info(&machTimeBaseInfo);
2670
2671 uint64_t uptime = mach_absolute_time();
2672 uint64_t uptimeNano = uptime * machTimeBaseInfo.numer / machTimeBaseInfo.denom;
2673
2674 uint64_t uptimeSeconds = uptimeNano / NSEC_PER_SEC;
2675 uint64_t uptimeNanoRemainder = uptimeNano - (uptimeSeconds * NSEC_PER_SEC);
2676
2677 tp->tv_sec = uptimeSeconds;
2678 tp->tv_nsec = uptimeNanoRemainder;
2679 #endif
2680 }
2681
usbi_get_real_time(struct timespec * tp)2682 void usbi_get_real_time(struct timespec *tp) {
2683 /* Check if the SDK is new enough to declare clock_gettime(), and the deployment target is at least 10.12. */
2684 #if ((MAC_OS_X_VERSION_MAX_ALLOWED >= 101200) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 101200))
2685 clock_gettime(CLOCK_REALTIME, tp);
2686 #else
2687 struct timeval tv;
2688 gettimeofday(&tv, NULL);
2689 tp->tv_sec = tv.tv_sec;
2690 tp->tv_nsec = tv.tv_usec * NSEC_PER_USEC;
2691 #endif
2692 }
2693
2694 #if MAX_INTERFACE_VERSION >= 550
darwin_alloc_streams(struct libusb_device_handle * dev_handle,uint32_t num_streams,unsigned char * endpoints,int num_endpoints)2695 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2696 int num_endpoints) {
2697 struct darwin_interface *cInterface;
2698 UInt32 supportsStreams;
2699 uint8_t pipeRef;
2700 int rc, i;
2701
2702 /* find the minimum number of supported streams on the endpoint list */
2703 for (i = 0 ; i < num_endpoints ; ++i) {
2704 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) {
2705 return rc;
2706 }
2707
2708 (*IOINTERFACE_V(cInterface, 550))->SupportsStreams (IOINTERFACE(cInterface), pipeRef, &supportsStreams);
2709 if (num_streams > supportsStreams)
2710 num_streams = supportsStreams;
2711 }
2712
2713 /* it is an error if any endpoint in endpoints does not support streams */
2714 if (0 == num_streams)
2715 return LIBUSB_ERROR_INVALID_PARAM;
2716
2717 /* create the streams */
2718 for (i = 0 ; i < num_endpoints ; ++i) {
2719 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2720
2721 rc = (*IOINTERFACE_V(cInterface, 550))->CreateStreams (IOINTERFACE(cInterface), pipeRef, num_streams);
2722 if (kIOReturnSuccess != rc)
2723 return darwin_to_libusb(rc);
2724 }
2725
2726 assert(num_streams <= INT_MAX);
2727 return (int)num_streams;
2728 }
2729
darwin_free_streams(struct libusb_device_handle * dev_handle,unsigned char * endpoints,int num_endpoints)2730 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2731 struct darwin_interface *cInterface;
2732 UInt32 supportsStreams;
2733 uint8_t pipeRef;
2734 int rc;
2735
2736 for (int i = 0 ; i < num_endpoints ; ++i) {
2737 if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface)))
2738 return rc;
2739
2740 (*IOINTERFACE_V(cInterface, 550))->SupportsStreams (IOINTERFACE(cInterface), pipeRef, &supportsStreams);
2741 if (0 == supportsStreams)
2742 return LIBUSB_ERROR_INVALID_PARAM;
2743
2744 rc = (*IOINTERFACE_V(cInterface, 550))->CreateStreams (IOINTERFACE(cInterface), pipeRef, 0);
2745 if (kIOReturnSuccess != rc)
2746 return darwin_to_libusb(rc);
2747 }
2748
2749 return LIBUSB_SUCCESS;
2750 }
2751 #endif
2752
2753 #if MAX_INTERFACE_VERSION >= 700
2754
2755 /* macOS APIs for getting entitlement values */
2756
2757 #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
2758 #include <Security/Security.h>
2759 #else
2760 typedef struct __SecTask *SecTaskRef;
2761 extern SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator);
2762 extern CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error);
2763 #endif
2764
darwin_has_capture_entitlements(void)2765 static bool darwin_has_capture_entitlements (void) {
2766 SecTaskRef task;
2767 CFTypeRef value;
2768 bool entitled;
2769
2770 task = SecTaskCreateFromSelf (kCFAllocatorDefault);
2771 if (task == NULL) {
2772 return false;
2773 }
2774 value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.vm.device-access"), NULL);
2775 CFRelease (task);
2776 entitled = value && (CFGetTypeID (value) == CFBooleanGetTypeID ()) && CFBooleanGetValue (value);
2777 if (value) {
2778 CFRelease (value);
2779 }
2780 return entitled;
2781 }
2782
darwin_reload_device(struct libusb_device_handle * dev_handle)2783 static int darwin_reload_device (struct libusb_device_handle *dev_handle) {
2784 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2785 enum libusb_error err;
2786
2787 usbi_mutex_lock(&darwin_cached_devices_mutex);
2788 (*dpriv->device)->Release(dpriv->device);
2789 err = darwin_device_from_service (HANDLE_CTX (dev_handle), dpriv->service, &dpriv->device);
2790 usbi_mutex_unlock(&darwin_cached_devices_mutex);
2791
2792 return err;
2793 }
2794
2795 /* On macOS, we capture an entire device at once, not individual interfaces. */
2796
darwin_detach_kernel_driver(struct libusb_device_handle * dev_handle,uint8_t interface)2797 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2798 UNUSED(interface);
2799 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2800 IOReturn kresult;
2801 enum libusb_error err;
2802 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
2803
2804 if (get_interface_interface_version() < 700) {
2805 return LIBUSB_ERROR_NOT_SUPPORTED;
2806 }
2807
2808 if (dpriv->capture_count == 0) {
2809 usbi_dbg (ctx, "attempting to detach kernel driver from device");
2810
2811 if (darwin_has_capture_entitlements ()) {
2812 /* request authorization */
2813 kresult = IOServiceAuthorize (dpriv->service, kIOServiceInteractionAllowed);
2814 if (kresult != kIOReturnSuccess) {
2815 usbi_warn (ctx, "IOServiceAuthorize: %s", darwin_error_str(kresult));
2816 return darwin_to_libusb (kresult);
2817 }
2818
2819 /* we need start() to be called again for authorization status to refresh */
2820 err = darwin_reload_device (dev_handle);
2821 if (err != LIBUSB_SUCCESS) {
2822 return err;
2823 }
2824 } else {
2825 usbi_info (ctx, "no capture entitlements. may not be able to detach the kernel driver for this device");
2826 if (0 != geteuid()) {
2827 usbi_warn (ctx, "USB device capture requires either an entitlement (com.apple.vm.device-access) or root privilege");
2828 return LIBUSB_ERROR_ACCESS;
2829 }
2830 }
2831
2832 /* reset device to release existing drivers */
2833 err = darwin_reenumerate_device (dev_handle, true);
2834 if (err != LIBUSB_SUCCESS) {
2835 return err;
2836 }
2837 }
2838 dpriv->capture_count++;
2839 return LIBUSB_SUCCESS;
2840 }
2841
2842
darwin_attach_kernel_driver(struct libusb_device_handle * dev_handle,uint8_t interface)2843 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2844 UNUSED(interface);
2845 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2846
2847 if (get_interface_interface_version() < 700) {
2848 return LIBUSB_ERROR_NOT_SUPPORTED;
2849 }
2850
2851 dpriv->capture_count--;
2852 if (dpriv->capture_count > 0) {
2853 return LIBUSB_SUCCESS;
2854 }
2855
2856 usbi_dbg (HANDLE_CTX (dev_handle), "reenumerating device for kernel driver attach");
2857
2858 /* reset device to attach kernel drivers */
2859 return darwin_reenumerate_device (dev_handle, false);
2860 }
2861
darwin_capture_claim_interface(struct libusb_device_handle * dev_handle,uint8_t iface)2862 static int darwin_capture_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2863 enum libusb_error ret;
2864 if (dev_handle->auto_detach_kernel_driver && darwin_kernel_driver_active(dev_handle, iface)) {
2865 ret = darwin_detach_kernel_driver (dev_handle, iface);
2866 if (ret != LIBUSB_SUCCESS) {
2867 usbi_info (HANDLE_CTX (dev_handle), "failed to auto-detach the kernel driver for this device, ret=%d", ret);
2868 }
2869 }
2870
2871 return darwin_claim_interface (dev_handle, iface);
2872 }
2873
darwin_capture_release_interface(struct libusb_device_handle * dev_handle,uint8_t iface)2874 static int darwin_capture_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2875 enum libusb_error ret;
2876 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2877
2878 ret = darwin_release_interface (dev_handle, iface);
2879 if (ret != LIBUSB_SUCCESS) {
2880 return ret;
2881 }
2882
2883 if (dev_handle->auto_detach_kernel_driver && dpriv->capture_count > 0) {
2884 ret = darwin_attach_kernel_driver (dev_handle, iface);
2885 if (LIBUSB_SUCCESS != ret) {
2886 usbi_info (HANDLE_CTX (dev_handle), "on attempt to reattach the kernel driver got ret=%d", ret);
2887 }
2888 /* ignore the error as the interface was successfully released */
2889 }
2890
2891 return LIBUSB_SUCCESS;
2892 }
2893
2894 #endif
2895
2896 const struct usbi_os_backend usbi_backend = {
2897 .name = "Darwin",
2898 .caps = USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2899 .init = darwin_init,
2900 .exit = darwin_exit,
2901 .set_option = NULL,
2902 .get_device_list = NULL,
2903 .hotplug_poll = darwin_hotplug_poll,
2904 .wrap_sys_device = NULL,
2905 .open = darwin_open,
2906 .close = darwin_close,
2907 .get_active_config_descriptor = darwin_get_active_config_descriptor,
2908 .get_config_descriptor = darwin_get_config_descriptor,
2909 .get_config_descriptor_by_value = NULL,
2910 .get_configuration = darwin_get_configuration,
2911 .set_configuration = darwin_set_configuration,
2912
2913 #if MAX_INTERFACE_VERSION >= 700
2914 .claim_interface = darwin_capture_claim_interface,
2915 .release_interface = darwin_capture_release_interface,
2916 #else
2917 .claim_interface = darwin_claim_interface,
2918 .release_interface = darwin_release_interface,
2919 #endif
2920
2921 .set_interface_altsetting = darwin_set_interface_altsetting,
2922 .clear_halt = darwin_clear_halt,
2923 .reset_device = darwin_reset_device,
2924
2925 #if MAX_INTERFACE_VERSION >= 550
2926 .alloc_streams = darwin_alloc_streams,
2927 .free_streams = darwin_free_streams,
2928 #endif
2929
2930 .dev_mem_alloc = NULL,
2931 .dev_mem_free = NULL,
2932 .kernel_driver_active = darwin_kernel_driver_active,
2933
2934 #if MAX_INTERFACE_VERSION >= 700
2935 .detach_kernel_driver = darwin_detach_kernel_driver,
2936 .attach_kernel_driver = darwin_attach_kernel_driver,
2937 #endif
2938
2939 .destroy_device = darwin_destroy_device,
2940
2941 .submit_transfer = darwin_submit_transfer,
2942 .cancel_transfer = darwin_cancel_transfer,
2943 .clear_transfer_priv = NULL,
2944 .handle_events = NULL,
2945 .handle_transfer_completion = darwin_handle_transfer_completion,
2946
2947 .context_priv_size = 0,
2948 .device_priv_size = sizeof(struct darwin_device_priv),
2949 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
2950 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
2951 };
2952