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