VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/darwin/iokit.cpp@ 94134

Last change on this file since 94134 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 78.8 KB
Line 
1/* $Id: iokit.cpp 93115 2022-01-01 11:31:46Z vboxsync $ */
2/** @file
3 * Main - Darwin IOKit Routines.
4 *
5 * Because IOKit makes use of COM like interfaces, it does not mix very
6 * well with COM/XPCOM and must therefore be isolated from it using a
7 * simpler C interface.
8 */
9
10/*
11 * Copyright (C) 2006-2022 Oracle Corporation
12 *
13 * This file is part of VirtualBox Open Source Edition (OSE), as
14 * available from http://www.virtualbox.org. This file is free software;
15 * you can redistribute it and/or modify it under the terms of the GNU
16 * General Public License (GPL) as published by the Free Software
17 * Foundation, in version 2 as it comes in the "COPYING" file of the
18 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
19 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
20 */
21
22
23/*********************************************************************************************************************************
24* Header Files *
25*********************************************************************************************************************************/
26#define LOG_GROUP LOG_GROUP_MAIN
27#ifdef STANDALONE_TESTCASE
28# define VBOX_WITH_USB
29#endif
30
31#include <mach/mach.h>
32#include <Carbon/Carbon.h>
33#include <CoreFoundation/CFBase.h>
34#include <IOKit/IOKitLib.h>
35#include <IOKit/IOBSD.h>
36#include <IOKit/storage/IOStorageDeviceCharacteristics.h>
37#include <IOKit/storage/IOBlockStorageDevice.h>
38#include <IOKit/storage/IOMedia.h>
39#include <IOKit/storage/IOCDMedia.h>
40#include <IOKit/scsi/SCSITaskLib.h>
41#include <SystemConfiguration/SystemConfiguration.h>
42#include <mach/mach_error.h>
43#include <sys/param.h>
44#include <paths.h>
45#ifdef VBOX_WITH_USB
46# include <IOKit/usb/IOUSBLib.h>
47# include <IOKit/IOCFPlugIn.h>
48#endif
49
50#include <VBox/log.h>
51#include <VBox/usblib.h>
52#include <iprt/errcore.h>
53#include <iprt/mem.h>
54#include <iprt/string.h>
55#include <iprt/process.h>
56#include <iprt/assert.h>
57#include <iprt/system.h>
58#include <iprt/thread.h>
59#include <iprt/uuid.h>
60#ifdef STANDALONE_TESTCASE
61# include <iprt/initterm.h>
62# include <iprt/stream.h>
63#endif
64
65#include "iokit.h"
66
67/* A small hack... */
68#ifdef STANDALONE_TESTCASE
69# define DarwinFreeUSBDeviceFromIOKit(a) do { } while (0)
70#endif
71
72
73/*********************************************************************************************************************************
74* Defined Constants And Macros *
75*********************************************************************************************************************************/
76/** An attempt at catching reference leaks. */
77#define MY_CHECK_CREFS(cRefs) do { AssertMsg(cRefs < 25, ("%ld\n", cRefs)); NOREF(cRefs); } while (0)
78
79/** Contains the pid of the current client. If 0, the kernel is the current client. */
80#define VBOXUSB_CLIENT_KEY "VBoxUSB-Client"
81/** Contains the pid of the filter owner (i.e. the VBoxSVC pid). */
82#define VBOXUSB_OWNER_KEY "VBoxUSB-Owner"
83/** The VBoxUSBDevice class name. */
84#define VBOXUSBDEVICE_CLASS_NAME "org_virtualbox_VBoxUSBDevice"
85
86/** Define the constant for the IOUSBHostDevice class name added in El Capitan. */
87#ifndef kIOUSBHostDeviceClassName
88# define kIOUSBHostDeviceClassName "IOUSBHostDevice"
89#endif
90
91/** The major darwin version indicating OS X El Captian, used to take care of the USB changes. */
92#define VBOX_OSX_EL_CAPTIAN_VER 15
93
94
95/*********************************************************************************************************************************
96* Global Variables *
97*********************************************************************************************************************************/
98/** The IO Master Port. */
99static mach_port_t g_MasterPort = MACH_PORT_NULL;
100/** Major darwin version as returned by uname -r. */
101static uint32_t g_uMajorDarwin = 0;
102
103
104/**
105 * Lazily opens the master port.
106 *
107 * @returns true if the port is open, false on failure (very unlikely).
108 */
109static bool darwinOpenMasterPort(void)
110{
111 if (!g_MasterPort)
112 {
113 kern_return_t krc = IOMasterPort(MACH_PORT_NULL, &g_MasterPort);
114 AssertReturn(krc == KERN_SUCCESS, false);
115
116 /* Get the darwin version we are running on. */
117 char szVersion[64];
118 int rc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, &szVersion[0], sizeof(szVersion));
119 if (RT_SUCCESS(rc))
120 {
121 rc = RTStrToUInt32Ex(&szVersion[0], NULL, 10, &g_uMajorDarwin);
122 AssertLogRelMsg(rc == VINF_SUCCESS || rc == VWRN_TRAILING_CHARS,
123 ("Failed to convert the major part of the version string '%s' into an integer: %Rrc\n",
124 szVersion, rc));
125 }
126 else
127 AssertLogRelMsgFailed(("Failed to query the OS release version with %Rrc\n", rc));
128 }
129 return true;
130}
131
132
133/**
134 * Checks whether the value exists.
135 *
136 * @returns true / false accordingly.
137 * @param DictRef The dictionary.
138 * @param KeyStrRef The key name.
139 */
140static bool darwinDictIsPresent(CFDictionaryRef DictRef, CFStringRef KeyStrRef)
141{
142 return !!CFDictionaryGetValue(DictRef, KeyStrRef);
143}
144
145
146/**
147 * Gets a boolean value.
148 *
149 * @returns Success indicator (true/false).
150 * @param DictRef The dictionary.
151 * @param KeyStrRef The key name.
152 * @param pf Where to store the key value.
153 */
154static bool darwinDictGetBool(CFDictionaryRef DictRef, CFStringRef KeyStrRef, bool *pf)
155{
156 CFTypeRef BoolRef = CFDictionaryGetValue(DictRef, KeyStrRef);
157 if ( BoolRef
158 && CFGetTypeID(BoolRef) == CFBooleanGetTypeID())
159 {
160 *pf = CFBooleanGetValue((CFBooleanRef)BoolRef);
161 return true;
162 }
163 *pf = false;
164 return false;
165}
166
167
168/**
169 * Gets an unsigned 8-bit integer value.
170 *
171 * @returns Success indicator (true/false).
172 * @param DictRef The dictionary.
173 * @param KeyStrRef The key name.
174 * @param pu8 Where to store the key value.
175 */
176static bool darwinDictGetU8(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint8_t *pu8)
177{
178 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
179 if (ValRef)
180 {
181 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt8Type, pu8))
182 return true;
183 }
184 *pu8 = 0;
185 return false;
186}
187
188
189/**
190 * Gets an unsigned 16-bit integer value.
191 *
192 * @returns Success indicator (true/false).
193 * @param DictRef The dictionary.
194 * @param KeyStrRef The key name.
195 * @param pu16 Where to store the key value.
196 */
197static bool darwinDictGetU16(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint16_t *pu16)
198{
199 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
200 if (ValRef)
201 {
202 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt16Type, pu16))
203 return true;
204 }
205 *pu16 = 0;
206 return false;
207}
208
209
210/**
211 * Gets an unsigned 32-bit integer value.
212 *
213 * @returns Success indicator (true/false).
214 * @param DictRef The dictionary.
215 * @param KeyStrRef The key name.
216 * @param pu32 Where to store the key value.
217 */
218static bool darwinDictGetU32(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint32_t *pu32)
219{
220 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
221 if (ValRef)
222 {
223 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt32Type, pu32))
224 return true;
225 }
226 *pu32 = 0;
227 return false;
228}
229
230
231/**
232 * Gets an unsigned 64-bit integer value.
233 *
234 * @returns Success indicator (true/false).
235 * @param DictRef The dictionary.
236 * @param KeyStrRef The key name.
237 * @param pu64 Where to store the key value.
238 */
239static bool darwinDictGetU64(CFDictionaryRef DictRef, CFStringRef KeyStrRef, uint64_t *pu64)
240{
241 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
242 if (ValRef)
243 {
244 if (CFNumberGetValue((CFNumberRef)ValRef, kCFNumberSInt64Type, pu64))
245 return true;
246 }
247 *pu64 = 0;
248 return false;
249}
250
251
252/**
253 * Gets a RTPROCESS value.
254 *
255 * @returns Success indicator (true/false).
256 * @param DictRef The dictionary.
257 * @param KeyStrRef The key name.
258 * @param pProcess Where to store the key value.
259 */
260static bool darwinDictGetProcess(CFMutableDictionaryRef DictRef, CFStringRef KeyStrRef, PRTPROCESS pProcess)
261{
262 switch (sizeof(*pProcess))
263 {
264 case sizeof(uint16_t): return darwinDictGetU16(DictRef, KeyStrRef, (uint16_t *)pProcess);
265 case sizeof(uint32_t): return darwinDictGetU32(DictRef, KeyStrRef, (uint32_t *)pProcess);
266 case sizeof(uint64_t): return darwinDictGetU64(DictRef, KeyStrRef, (uint64_t *)pProcess);
267 default:
268 AssertMsgFailedReturn(("%d\n", sizeof(*pProcess)), false);
269 }
270}
271
272
273/**
274 * Gets string value, converted to UTF-8 and put in user buffer.
275 *
276 * @returns Success indicator (true/false).
277 * @param DictRef The dictionary.
278 * @param KeyStrRef The key name.
279 * @param psz The string buffer. On failure this will be an empty string ("").
280 * @param cch The size of the buffer.
281 */
282static bool darwinDictGetString(CFDictionaryRef DictRef, CFStringRef KeyStrRef, char *psz, size_t cch)
283{
284 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
285 if (ValRef)
286 {
287 if (CFStringGetCString((CFStringRef)ValRef, psz, (CFIndex)cch, kCFStringEncodingUTF8))
288 return true;
289 }
290 Assert(cch > 0);
291 *psz = '\0';
292 return false;
293}
294
295
296/**
297 * Gets string value, converted to UTF-8 and put in a IPRT string buffer.
298 *
299 * @returns Success indicator (true/false).
300 * @param DictRef The dictionary.
301 * @param KeyStrRef The key name.
302 * @param ppsz Where to store the key value. Free with RTStrFree. Set to NULL on failure.
303 */
304static bool darwinDictDupString(CFDictionaryRef DictRef, CFStringRef KeyStrRef, char **ppsz)
305{
306 char szBuf[512];
307 if (darwinDictGetString(DictRef, KeyStrRef, szBuf, sizeof(szBuf)))
308 {
309 USBLibPurgeEncoding(szBuf);
310 *ppsz = RTStrDup(szBuf);
311 if (*ppsz)
312 return true;
313 }
314 *ppsz = NULL;
315 return false;
316}
317
318
319/**
320 * Gets a byte string (data) of a specific size.
321 *
322 * @returns Success indicator (true/false).
323 * @param DictRef The dictionary.
324 * @param KeyStrRef The key name.
325 * @param pvBuf The buffer to store the bytes in.
326 * @param cbBuf The size of the buffer. This must exactly match the data size.
327 */
328static bool darwinDictGetData(CFDictionaryRef DictRef, CFStringRef KeyStrRef, void *pvBuf, size_t cbBuf)
329{
330 CFTypeRef ValRef = CFDictionaryGetValue(DictRef, KeyStrRef);
331 if (ValRef)
332 {
333 CFIndex cbActual = CFDataGetLength((CFDataRef)ValRef);
334 if (cbActual >= 0 && cbBuf == (size_t)cbActual)
335 {
336 CFDataGetBytes((CFDataRef)ValRef, CFRangeMake(0, (CFIndex)cbBuf), (uint8_t *)pvBuf);
337 return true;
338 }
339 }
340 memset(pvBuf, '\0', cbBuf);
341 return false;
342}
343
344
345#if 1 && !defined(STANDALONE_TESTCASE) /* dumping disabled */
346# define DARWIN_IOKIT_LOG(a) Log(a)
347# define DARWIN_IOKIT_LOG_FLUSH() do {} while (0)
348# define DARWIN_IOKIT_DUMP_OBJ(o) do {} while (0)
349#else
350# if defined(STANDALONE_TESTCASE)
351# include <iprt/stream.h>
352# define DARWIN_IOKIT_LOG(a) RTPrintf a
353# define DARWIN_IOKIT_LOG_FLUSH() RTStrmFlush(g_pStdOut)
354# else
355# define DARWIN_IOKIT_LOG(a) RTLogPrintf a
356# define DARWIN_IOKIT_LOG_FLUSH() RTLogFlush(NULL)
357# endif
358# define DARWIN_IOKIT_DUMP_OBJ(o) darwinDumpObj(o)
359
360/**
361 * Callback for dumping a dictionary key.
362 *
363 * @param pvKey The key name.
364 * @param pvValue The key value
365 * @param pvUser The recursion depth.
366 */
367static void darwinDumpDictCallback(const void *pvKey, const void *pvValue, void *pvUser)
368{
369 /* display the key name. */
370 char *pszKey = (char *)RTMemTmpAlloc(1024);
371 if (!CFStringGetCString((CFStringRef)pvKey, pszKey, 1024, kCFStringEncodingUTF8))
372 strcpy(pszKey, "CFStringGetCString failure");
373 DARWIN_IOKIT_LOG(("%+*s%s", (int)(uintptr_t)pvUser, "", pszKey));
374 RTMemTmpFree(pszKey);
375
376 /* display the value type */
377 CFTypeID Type = CFGetTypeID(pvValue);
378 DARWIN_IOKIT_LOG((" [%d-", Type));
379
380 /* display the value */
381 if (Type == CFDictionaryGetTypeID())
382 {
383 DARWIN_IOKIT_LOG(("dictionary] =\n"
384 "%-*s{\n", (int)(uintptr_t)pvUser, ""));
385 CFDictionaryApplyFunction((CFDictionaryRef)pvValue, darwinDumpDictCallback, (void *)((uintptr_t)pvUser + 4));
386 DARWIN_IOKIT_LOG(("%-*s}\n", (int)(uintptr_t)pvUser, ""));
387 }
388 else if (Type == CFBooleanGetTypeID())
389 DARWIN_IOKIT_LOG(("bool] = %s\n", CFBooleanGetValue((CFBooleanRef)pvValue) ? "true" : "false"));
390 else if (Type == CFNumberGetTypeID())
391 {
392 union
393 {
394 SInt8 s8;
395 SInt16 s16;
396 SInt32 s32;
397 SInt64 s64;
398 Float32 rf32;
399 Float64 rd64;
400 char ch;
401 short s;
402 int i;
403 long l;
404 long long ll;
405 float rf;
406 double rd;
407 CFIndex iCF;
408 } u;
409 RT_ZERO(u);
410 CFNumberType NumType = CFNumberGetType((CFNumberRef)pvValue);
411 if (CFNumberGetValue((CFNumberRef)pvValue, NumType, &u))
412 {
413 switch (CFNumberGetType((CFNumberRef)pvValue))
414 {
415 case kCFNumberSInt8Type: DARWIN_IOKIT_LOG(("SInt8] = %RI8 (%#RX8)\n", NumType, u.s8, u.s8)); break;
416 case kCFNumberSInt16Type: DARWIN_IOKIT_LOG(("SInt16] = %RI16 (%#RX16)\n", NumType, u.s16, u.s16)); break;
417 case kCFNumberSInt32Type: DARWIN_IOKIT_LOG(("SInt32] = %RI32 (%#RX32)\n", NumType, u.s32, u.s32)); break;
418 case kCFNumberSInt64Type: DARWIN_IOKIT_LOG(("SInt64] = %RI64 (%#RX64)\n", NumType, u.s64, u.s64)); break;
419 case kCFNumberFloat32Type: DARWIN_IOKIT_LOG(("float32] = %#lx\n", NumType, u.l)); break;
420 case kCFNumberFloat64Type: DARWIN_IOKIT_LOG(("float64] = %#llx\n", NumType, u.ll)); break;
421 case kCFNumberFloatType: DARWIN_IOKIT_LOG(("float] = %#lx\n", NumType, u.l)); break;
422 case kCFNumberDoubleType: DARWIN_IOKIT_LOG(("double] = %#llx\n", NumType, u.ll)); break;
423 case kCFNumberCharType: DARWIN_IOKIT_LOG(("char] = %hhd (%hhx)\n", NumType, u.ch, u.ch)); break;
424 case kCFNumberShortType: DARWIN_IOKIT_LOG(("short] = %hd (%hx)\n", NumType, u.s, u.s)); break;
425 case kCFNumberIntType: DARWIN_IOKIT_LOG(("int] = %d (%#x)\n", NumType, u.i, u.i)); break;
426 case kCFNumberLongType: DARWIN_IOKIT_LOG(("long] = %ld (%#lx)\n", NumType, u.l, u.l)); break;
427 case kCFNumberLongLongType: DARWIN_IOKIT_LOG(("long long] = %lld (%#llx)\n", NumType, u.ll, u.ll)); break;
428 case kCFNumberCFIndexType: DARWIN_IOKIT_LOG(("CFIndex] = %lld (%#llx)\n", NumType, (long long)u.iCF, (long long)u.iCF)); break;
429 break;
430 default: DARWIN_IOKIT_LOG(("%d?] = %lld (%llx)\n", NumType, u.ll, u.ll)); break;
431 }
432 }
433 else
434 DARWIN_IOKIT_LOG(("number] = CFNumberGetValue failed\n"));
435 }
436 else if (Type == CFBooleanGetTypeID())
437 DARWIN_IOKIT_LOG(("boolean] = %RTbool\n", CFBooleanGetValue((CFBooleanRef)pvValue)));
438 else if (Type == CFStringGetTypeID())
439 {
440 DARWIN_IOKIT_LOG(("string] = "));
441 char *pszValue = (char *)RTMemTmpAlloc(16*_1K);
442 if (!CFStringGetCString((CFStringRef)pvValue, pszValue, 16*_1K, kCFStringEncodingUTF8))
443 strcpy(pszValue, "CFStringGetCString failure");
444 DARWIN_IOKIT_LOG(("\"%s\"\n", pszValue));
445 RTMemTmpFree(pszValue);
446 }
447 else if (Type == CFDataGetTypeID())
448 {
449 CFIndex cb = CFDataGetLength((CFDataRef)pvValue);
450 DARWIN_IOKIT_LOG(("%zu bytes] =", (size_t)cb));
451 void *pvData = RTMemTmpAlloc(cb + 8);
452 CFDataGetBytes((CFDataRef)pvValue, CFRangeMake(0, cb), (uint8_t *)pvData);
453 if (!cb)
454 DARWIN_IOKIT_LOG((" \n"));
455 else if (cb <= 32)
456 DARWIN_IOKIT_LOG((" %.*Rhxs\n", cb, pvData));
457 else
458 DARWIN_IOKIT_LOG(("\n%.*Rhxd\n", cb, pvData));
459 RTMemTmpFree(pvData);
460 }
461 else
462 DARWIN_IOKIT_LOG(("??] = %p\n", pvValue));
463}
464
465
466/**
467 * Dumps a dictionary to the log.
468 *
469 * @param DictRef The dictionary to dump.
470 */
471static void darwinDumpDict(CFDictionaryRef DictRef, unsigned cIndents)
472{
473 CFDictionaryApplyFunction(DictRef, darwinDumpDictCallback, (void *)(uintptr_t)cIndents);
474 DARWIN_IOKIT_LOG_FLUSH();
475}
476
477
478/**
479 * Dumps an I/O kit registry object and all it children.
480 * @param Object The object to dump.
481 * @param cIndents The number of indents to use.
482 */
483static void darwinDumpObjInt(io_object_t Object, unsigned cIndents)
484{
485 static io_string_t s_szPath;
486 kern_return_t krc = IORegistryEntryGetPath(Object, kIOServicePlane, s_szPath);
487 if (krc != KERN_SUCCESS)
488 strcpy(s_szPath, "IORegistryEntryGetPath failed");
489 DARWIN_IOKIT_LOG(("Dumping %p - %s:\n", (const void *)Object, s_szPath));
490
491 CFMutableDictionaryRef PropsRef = 0;
492 krc = IORegistryEntryCreateCFProperties(Object, &PropsRef, kCFAllocatorDefault, kNilOptions);
493 if (krc == KERN_SUCCESS)
494 {
495 darwinDumpDict(PropsRef, cIndents + 4);
496 CFRelease(PropsRef);
497 }
498
499 /*
500 * Children.
501 */
502 io_iterator_t Children;
503 krc = IORegistryEntryGetChildIterator(Object, kIOServicePlane, &Children);
504 if (krc == KERN_SUCCESS)
505 {
506 io_object_t Child;
507 while ((Child = IOIteratorNext(Children)) != IO_OBJECT_NULL)
508 {
509 darwinDumpObjInt(Child, cIndents + 4);
510 IOObjectRelease(Child);
511 }
512 IOObjectRelease(Children);
513 }
514 else
515 DARWIN_IOKIT_LOG(("IORegistryEntryGetChildIterator -> %#x\n", krc));
516}
517
518/**
519 * Dumps an I/O kit registry object and all it children.
520 * @param Object The object to dump.
521 */
522static void darwinDumpObj(io_object_t Object)
523{
524 darwinDumpObjInt(Object, 0);
525}
526
527#endif /* helpers for dumping registry dictionaries */
528
529
530#ifdef VBOX_WITH_USB
531
532/**
533 * Notification data created by DarwinSubscribeUSBNotifications, used by
534 * the callbacks and finally freed by DarwinUnsubscribeUSBNotifications.
535 */
536typedef struct DARWINUSBNOTIFY
537{
538 /** The notification port.
539 * It's shared between the notification callbacks. */
540 IONotificationPortRef NotifyPort;
541 /** The run loop source for NotifyPort. */
542 CFRunLoopSourceRef NotifyRLSrc;
543 /** The attach notification iterator. */
544 io_iterator_t AttachIterator;
545 /** The 2nd attach notification iterator. */
546 io_iterator_t AttachIterator2;
547 /** The detach notification iterator. */
548 io_iterator_t DetachIterator;
549} DARWINUSBNOTIFY, *PDARWINUSBNOTIFY;
550
551
552/**
553 * Run thru an iterator.
554 *
555 * The docs says this is necessary to start getting notifications,
556 * so this function is called in the callbacks and right after
557 * registering the notification.
558 *
559 * @param pIterator The iterator reference.
560 */
561static void darwinDrainIterator(io_iterator_t pIterator)
562{
563 io_object_t Object;
564 while ((Object = IOIteratorNext(pIterator)) != IO_OBJECT_NULL)
565 {
566 DARWIN_IOKIT_DUMP_OBJ(Object);
567 IOObjectRelease(Object);
568 }
569}
570
571
572/**
573 * Callback for the 1st attach notification.
574 *
575 * @param pvNotify Our data.
576 * @param NotifyIterator The notification iterator.
577 */
578static void darwinUSBAttachNotification1(void *pvNotify, io_iterator_t NotifyIterator)
579{
580 DARWIN_IOKIT_LOG(("USB Attach Notification1\n"));
581 NOREF(pvNotify); //PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvNotify;
582 darwinDrainIterator(NotifyIterator);
583}
584
585
586/**
587 * Callback for the 2nd attach notification.
588 *
589 * @param pvNotify Our data.
590 * @param NotifyIterator The notification iterator.
591 */
592static void darwinUSBAttachNotification2(void *pvNotify, io_iterator_t NotifyIterator)
593{
594 DARWIN_IOKIT_LOG(("USB Attach Notification2\n"));
595 NOREF(pvNotify); //PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvNotify;
596 darwinDrainIterator(NotifyIterator);
597}
598
599
600/**
601 * Callback for the detach notifications.
602 *
603 * @param pvNotify Our data.
604 * @param NotifyIterator The notification iterator.
605 */
606static void darwinUSBDetachNotification(void *pvNotify, io_iterator_t NotifyIterator)
607{
608 DARWIN_IOKIT_LOG(("USB Detach Notification\n"));
609 NOREF(pvNotify); //PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvNotify;
610 darwinDrainIterator(NotifyIterator);
611}
612
613
614/**
615 * Subscribes the run loop to USB notification events relevant to
616 * device attach/detach.
617 *
618 * The source mode for these events is defined as VBOX_IOKIT_MODE_STRING
619 * so that the caller can listen to events from this mode only and
620 * re-evalutate the list of attached devices whenever an event arrives.
621 *
622 * @returns opaque for passing to the unsubscribe function. If NULL
623 * something unexpectedly failed during subscription.
624 */
625void *DarwinSubscribeUSBNotifications(void)
626{
627 AssertReturn(darwinOpenMasterPort(), NULL);
628
629 PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)RTMemAllocZ(sizeof(*pNotify));
630 AssertReturn(pNotify, NULL);
631
632 /*
633 * Create the notification port, bake it into a runloop source which we
634 * then add to our run loop.
635 */
636 pNotify->NotifyPort = IONotificationPortCreate(g_MasterPort);
637 Assert(pNotify->NotifyPort);
638 if (pNotify->NotifyPort)
639 {
640 pNotify->NotifyRLSrc = IONotificationPortGetRunLoopSource(pNotify->NotifyPort);
641 Assert(pNotify->NotifyRLSrc);
642 if (pNotify->NotifyRLSrc)
643 {
644 CFRunLoopRef RunLoopRef = CFRunLoopGetCurrent();
645 CFRetain(RunLoopRef); /* Workaround for crash when cleaning up the TLS / runloop((sub)mode). See @bugref{2807}. */
646 CFRunLoopAddSource(RunLoopRef, pNotify->NotifyRLSrc, CFSTR(VBOX_IOKIT_MODE_STRING));
647
648 /*
649 * Create the notification callbacks.
650 */
651 kern_return_t rc = IOServiceAddMatchingNotification(pNotify->NotifyPort,
652 kIOPublishNotification,
653 IOServiceMatching(kIOUSBDeviceClassName),
654 darwinUSBAttachNotification1,
655 pNotify,
656 &pNotify->AttachIterator);
657 if (rc == KERN_SUCCESS)
658 {
659 darwinDrainIterator(pNotify->AttachIterator);
660 rc = IOServiceAddMatchingNotification(pNotify->NotifyPort,
661 kIOMatchedNotification,
662 IOServiceMatching(kIOUSBDeviceClassName),
663 darwinUSBAttachNotification2,
664 pNotify,
665 &pNotify->AttachIterator2);
666 if (rc == KERN_SUCCESS)
667 {
668 darwinDrainIterator(pNotify->AttachIterator2);
669 rc = IOServiceAddMatchingNotification(pNotify->NotifyPort,
670 kIOTerminatedNotification,
671 IOServiceMatching(kIOUSBDeviceClassName),
672 darwinUSBDetachNotification,
673 pNotify,
674 &pNotify->DetachIterator);
675 {
676 darwinDrainIterator(pNotify->DetachIterator);
677 return pNotify;
678 }
679 IOObjectRelease(pNotify->AttachIterator2);
680 }
681 IOObjectRelease(pNotify->AttachIterator);
682 }
683 CFRunLoopRemoveSource(RunLoopRef, pNotify->NotifyRLSrc, CFSTR(VBOX_IOKIT_MODE_STRING));
684 }
685 IONotificationPortDestroy(pNotify->NotifyPort);
686 }
687
688 RTMemFree(pNotify);
689 return NULL;
690}
691
692
693/**
694 * Unsubscribe the run loop from USB notification subscribed to
695 * by DarwinSubscribeUSBNotifications.
696 *
697 * @param pvOpaque The return value from DarwinSubscribeUSBNotifications.
698 */
699void DarwinUnsubscribeUSBNotifications(void *pvOpaque)
700{
701 PDARWINUSBNOTIFY pNotify = (PDARWINUSBNOTIFY)pvOpaque;
702 if (!pNotify)
703 return;
704
705 IOObjectRelease(pNotify->AttachIterator);
706 pNotify->AttachIterator = IO_OBJECT_NULL;
707 IOObjectRelease(pNotify->AttachIterator2);
708 pNotify->AttachIterator2 = IO_OBJECT_NULL;
709 IOObjectRelease(pNotify->DetachIterator);
710 pNotify->DetachIterator = IO_OBJECT_NULL;
711
712 CFRunLoopRemoveSource(CFRunLoopGetCurrent(), pNotify->NotifyRLSrc, CFSTR(VBOX_IOKIT_MODE_STRING));
713 IONotificationPortDestroy(pNotify->NotifyPort);
714 pNotify->NotifyRLSrc = NULL;
715 pNotify->NotifyPort = NULL;
716
717 RTMemFree(pNotify);
718}
719
720
721/**
722 * Descends recursively into a IORegistry tree locating the first object of a given class.
723 *
724 * The search is performed depth first.
725 *
726 * @returns Object reference if found, NULL if not.
727 * @param Object The current tree root.
728 * @param pszClass The name of the class we're looking for.
729 * @param pszNameBuf A scratch buffer for query the class name in to avoid
730 * wasting 128 bytes on an io_name_t object for every recursion.
731 */
732static io_object_t darwinFindObjectByClass(io_object_t Object, const char *pszClass, io_name_t pszNameBuf)
733{
734 io_iterator_t Children;
735 kern_return_t krc = IORegistryEntryGetChildIterator(Object, kIOServicePlane, &Children);
736 if (krc != KERN_SUCCESS)
737 return IO_OBJECT_NULL;
738 io_object_t Child;
739 while ((Child = IOIteratorNext(Children)) != IO_OBJECT_NULL)
740 {
741 krc = IOObjectGetClass(Child, pszNameBuf);
742 if ( krc == KERN_SUCCESS
743 && !strcmp(pszNameBuf, pszClass))
744 break;
745
746 io_object_t GrandChild = darwinFindObjectByClass(Child, pszClass, pszNameBuf);
747 IOObjectRelease(Child);
748 if (GrandChild)
749 {
750 Child = GrandChild;
751 break;
752 }
753 }
754 IOObjectRelease(Children);
755 return Child;
756}
757
758
759/**
760 * Descends recursively into IOUSBMassStorageClass tree to check whether
761 * the MSD is mounted or not.
762 *
763 * The current heuristic is to look for the IOMedia class.
764 *
765 * @returns true if mounted, false if not.
766 * @param MSDObj The IOUSBMassStorageClass object.
767 * @param pszNameBuf A scratch buffer for query the class name in to avoid
768 * wasting 128 bytes on an io_name_t object for every recursion.
769 */
770static bool darwinIsMassStorageInterfaceInUse(io_object_t MSDObj, io_name_t pszNameBuf)
771{
772 io_object_t MediaObj = darwinFindObjectByClass(MSDObj, kIOMediaClass, pszNameBuf);
773 if (MediaObj)
774 {
775 CFMutableDictionaryRef pProperties;
776 kern_return_t krc;
777 bool fInUse = true;
778
779 krc = IORegistryEntryCreateCFProperties(MediaObj, &pProperties, kCFAllocatorDefault, kNilOptions);
780 if (krc == KERN_SUCCESS)
781 {
782 CFBooleanRef pBoolValue = (CFBooleanRef)CFDictionaryGetValue(pProperties, CFSTR(kIOMediaOpenKey));
783 if (pBoolValue)
784 fInUse = CFBooleanGetValue(pBoolValue);
785
786 CFRelease(pProperties);
787 }
788
789 /* more checks? */
790 IOObjectRelease(MediaObj);
791 return fInUse;
792 }
793
794 return false;
795}
796
797
798/**
799 * Finds the matching IOUSBHostDevice registry entry for the given legacy USB device interface (IOUSBDevice).
800 *
801 * @returns kern_return_t error code.
802 * @param USBDeviceLegacy The legacy device I/O Kit object.
803 * @param pUSBDevice Where to store the IOUSBHostDevice object on success.
804 */
805static kern_return_t darwinGetUSBHostDeviceFromLegacyDevice(io_object_t USBDeviceLegacy, io_object_t *pUSBDevice)
806{
807 kern_return_t krc = KERN_SUCCESS;
808 uint64_t uIoRegEntryId = 0;
809
810 *pUSBDevice = 0;
811
812 /* Get the registry entry ID to match against. */
813 krc = IORegistryEntryGetRegistryEntryID(USBDeviceLegacy, &uIoRegEntryId);
814 if (krc != KERN_SUCCESS)
815 return krc;
816
817 /*
818 * Create a matching dictionary for searching for USB Devices in the IOKit.
819 */
820 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOUSBHostDeviceClassName);
821 AssertReturn(RefMatchingDict, KERN_FAILURE);
822
823 /*
824 * Perform the search and get a collection of USB Device back.
825 */
826 io_iterator_t USBDevices = IO_OBJECT_NULL;
827 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &USBDevices);
828 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), KERN_FAILURE);
829 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
830
831 /*
832 * Walk the devices and check for the matching alternate registry entry ID.
833 */
834 io_object_t USBDevice;
835 while ((USBDevice = IOIteratorNext(USBDevices)) != IO_OBJECT_NULL)
836 {
837 DARWIN_IOKIT_DUMP_OBJ(USBDevice);
838
839 CFMutableDictionaryRef PropsRef = 0;
840 krc = IORegistryEntryCreateCFProperties(USBDevice, &PropsRef, kCFAllocatorDefault, kNilOptions);
841 if (krc == KERN_SUCCESS)
842 {
843 uint64_t uAltRegId = 0;
844 if ( darwinDictGetU64(PropsRef, CFSTR("AppleUSBAlternateServiceRegistryID"), &uAltRegId)
845 && uAltRegId == uIoRegEntryId)
846 {
847 *pUSBDevice = USBDevice;
848 CFRelease(PropsRef);
849 break;
850 }
851
852 CFRelease(PropsRef);
853 }
854 IOObjectRelease(USBDevice);
855 }
856 IOObjectRelease(USBDevices);
857
858 return krc;
859}
860
861
862static bool darwinUSBDeviceIsGrabbedDetermineState(PUSBDEVICE pCur, io_object_t USBDevice)
863{
864 /*
865 * Iterate the interfaces (among the children of the IOUSBDevice object).
866 */
867 io_iterator_t Interfaces;
868 kern_return_t krc = IORegistryEntryGetChildIterator(USBDevice, kIOServicePlane, &Interfaces);
869 if (krc != KERN_SUCCESS)
870 return false;
871
872 bool fHaveOwner = false;
873 RTPROCESS Owner = NIL_RTPROCESS;
874 bool fHaveClient = false;
875 RTPROCESS Client = NIL_RTPROCESS;
876 io_object_t Interface;
877 while ((Interface = IOIteratorNext(Interfaces)) != IO_OBJECT_NULL)
878 {
879 io_name_t szName;
880 krc = IOObjectGetClass(Interface, szName);
881 if ( krc == KERN_SUCCESS
882 && !strcmp(szName, VBOXUSBDEVICE_CLASS_NAME))
883 {
884 CFMutableDictionaryRef PropsRef = 0;
885 krc = IORegistryEntryCreateCFProperties(Interface, &PropsRef, kCFAllocatorDefault, kNilOptions);
886 if (krc == KERN_SUCCESS)
887 {
888 fHaveOwner = darwinDictGetProcess(PropsRef, CFSTR(VBOXUSB_OWNER_KEY), &Owner);
889 fHaveClient = darwinDictGetProcess(PropsRef, CFSTR(VBOXUSB_CLIENT_KEY), &Client);
890 CFRelease(PropsRef);
891 }
892 }
893
894 IOObjectRelease(Interface);
895 }
896 IOObjectRelease(Interfaces);
897
898 /*
899 * Calc the status.
900 */
901 if (fHaveOwner)
902 {
903 if (Owner == RTProcSelf())
904 pCur->enmState = !fHaveClient || Client == NIL_RTPROCESS || !Client
905 ? USBDEVICESTATE_HELD_BY_PROXY
906 : USBDEVICESTATE_USED_BY_GUEST;
907 else
908 pCur->enmState = USBDEVICESTATE_USED_BY_HOST;
909 }
910
911 return fHaveOwner;
912}
913
914
915/**
916 * Worker for determining the USB device state for devices which are not captured by the VBoxUSB driver
917 * Works for both, IOUSBDevice (legacy on release >= El Capitan) and IOUSBHostDevice (available on >= El Capitan).
918 *
919 * @returns nothing.
920 * @param pCur The USB device data.
921 * @param USBDevice I/O Kit USB device object (either IOUSBDevice or IOUSBHostDevice).
922 */
923static void darwinDetermineUSBDeviceStateWorker(PUSBDEVICE pCur, io_object_t USBDevice)
924{
925 /*
926 * Iterate the interfaces (among the children of the IOUSBDevice object).
927 */
928 io_iterator_t Interfaces;
929 kern_return_t krc = IORegistryEntryGetChildIterator(USBDevice, kIOServicePlane, &Interfaces);
930 if (krc != KERN_SUCCESS)
931 return;
932
933 bool fUserClientOnly = true;
934 bool fConfigured = false;
935 bool fInUse = false;
936 bool fSeizable = true;
937 io_object_t Interface;
938 while ((Interface = IOIteratorNext(Interfaces)) != IO_OBJECT_NULL)
939 {
940 io_name_t szName;
941 krc = IOObjectGetClass(Interface, szName);
942 if ( krc == KERN_SUCCESS
943 && ( !strcmp(szName, "IOUSBInterface")
944 || !strcmp(szName, "IOUSBHostInterface")))
945 {
946 fConfigured = true;
947
948 /*
949 * Iterate the interface children looking for stuff other than
950 * IOUSBUserClientInit objects.
951 */
952 io_iterator_t Children1;
953 krc = IORegistryEntryGetChildIterator(Interface, kIOServicePlane, &Children1);
954 if (krc == KERN_SUCCESS)
955 {
956 io_object_t Child1;
957 while ((Child1 = IOIteratorNext(Children1)) != IO_OBJECT_NULL)
958 {
959 krc = IOObjectGetClass(Child1, szName);
960 if ( krc == KERN_SUCCESS
961 && strcmp(szName, "IOUSBUserClientInit"))
962 {
963 fUserClientOnly = false;
964
965 if ( !strcmp(szName, "IOUSBMassStorageClass")
966 || !strcmp(szName, "IOUSBMassStorageInterfaceNub"))
967 {
968 /* Only permit capturing MSDs that aren't mounted, at least
969 until the GUI starts poping up warnings about data loss
970 and such when capturing a busy device. */
971 fSeizable = false;
972 fInUse |= darwinIsMassStorageInterfaceInUse(Child1, szName);
973 }
974 else if (!strcmp(szName, "IOUSBHIDDriver")
975 || !strcmp(szName, "AppleHIDMouse")
976 /** @todo more? */)
977 {
978 /* For now, just assume that all HID devices are inaccessible
979 because of the greedy HID service. */
980 fSeizable = false;
981 fInUse = true;
982 }
983 else
984 fInUse = true;
985 }
986 IOObjectRelease(Child1);
987 }
988 IOObjectRelease(Children1);
989 }
990 }
991
992 IOObjectRelease(Interface);
993 }
994 IOObjectRelease(Interfaces);
995
996 /*
997 * Calc the status.
998 */
999 if (!fInUse)
1000 pCur->enmState = USBDEVICESTATE_UNUSED;
1001 else
1002 pCur->enmState = fSeizable
1003 ? USBDEVICESTATE_USED_BY_HOST_CAPTURABLE
1004 : USBDEVICESTATE_USED_BY_HOST;
1005}
1006
1007
1008/**
1009 * Worker function for DarwinGetUSBDevices() that tries to figure out
1010 * what state the device is in and set enmState.
1011 *
1012 * This is mostly a matter of distinguishing between devices that nobody
1013 * uses, devices that can be seized and devices that cannot be grabbed.
1014 *
1015 * @param pCur The USB device data.
1016 * @param USBDevice The USB device object.
1017 * @param PropsRef The USB device properties.
1018 */
1019static void darwinDeterminUSBDeviceState(PUSBDEVICE pCur, io_object_t USBDevice, CFMutableDictionaryRef /* PropsRef */)
1020{
1021
1022 if (!darwinUSBDeviceIsGrabbedDetermineState(pCur, USBDevice))
1023 {
1024 /*
1025 * The USB stack was completely reworked on El Capitan and the IOUSBDevice and IOUSBInterface
1026 * are deprecated and don't return the information required for the additional checks below.
1027 * We also can't directly make use of the new classes (IOUSBHostDevice and IOUSBHostInterface)
1028 * because VBoxUSB only exposes the legacy interfaces. Trying to use the new classes results in errors
1029 * because the I/O Kit USB library wants to use the new interfaces. The result is us losing the device
1030 * form the list when VBoxUSB has attached to the USB device.
1031 *
1032 * To make the checks below work we have to get hold of the IOUSBHostDevice and IOUSBHostInterface
1033 * instances for the current device. Fortunately the IOUSBHostDevice instance contains a
1034 * "AppleUSBAlternateServiceRegistryID" which points to the legacy class instance for the same device.
1035 * So just iterate over the list of IOUSBHostDevice instances and check whether the
1036 * AppleUSBAlternateServiceRegistryID property matches with the legacy instance.
1037 *
1038 * The upside is that we can keep VBoxUSB untouched and still compatible with older OS X releases.
1039 */
1040 if (g_uMajorDarwin >= VBOX_OSX_EL_CAPTIAN_VER)
1041 {
1042 io_object_t IOUSBDeviceNew = IO_OBJECT_NULL;
1043 kern_return_t krc = darwinGetUSBHostDeviceFromLegacyDevice(USBDevice, &IOUSBDeviceNew);
1044 if ( krc == KERN_SUCCESS
1045 && IOUSBDeviceNew != IO_OBJECT_NULL)
1046 {
1047 darwinDetermineUSBDeviceStateWorker(pCur, IOUSBDeviceNew);
1048 IOObjectRelease(IOUSBDeviceNew);
1049 }
1050 }
1051 else
1052 darwinDetermineUSBDeviceStateWorker(pCur, USBDevice);
1053 }
1054}
1055
1056
1057/**
1058 * Enumerate the USB devices returning a FIFO of them.
1059 *
1060 * @returns Pointer to the head.
1061 * USBProxyService::freeDevice is expected to free each of the list elements.
1062 */
1063PUSBDEVICE DarwinGetUSBDevices(void)
1064{
1065 AssertReturn(darwinOpenMasterPort(), NULL);
1066 //DARWIN_IOKIT_LOG(("DarwinGetUSBDevices\n"));
1067
1068 /*
1069 * Create a matching dictionary for searching for USB Devices in the IOKit.
1070 */
1071 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching(kIOUSBDeviceClassName);
1072 AssertReturn(RefMatchingDict, NULL);
1073
1074 /*
1075 * Perform the search and get a collection of USB Device back.
1076 */
1077 io_iterator_t USBDevices = IO_OBJECT_NULL;
1078 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &USBDevices);
1079 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), NULL);
1080 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1081
1082 /*
1083 * Enumerate the USB Devices.
1084 */
1085 PUSBDEVICE pHead = NULL;
1086 PUSBDEVICE pTail = NULL;
1087 unsigned i = 0;
1088 io_object_t USBDevice;
1089 while ((USBDevice = IOIteratorNext(USBDevices)) != IO_OBJECT_NULL)
1090 {
1091 DARWIN_IOKIT_DUMP_OBJ(USBDevice);
1092
1093 /*
1094 * Query the device properties from the registry.
1095 *
1096 * We could alternatively use the device and such, but that will be
1097 * slower and we would have to resort to the registry for the three
1098 * string anyway.
1099 */
1100 CFMutableDictionaryRef PropsRef = 0;
1101 kern_return_t krc = IORegistryEntryCreateCFProperties(USBDevice, &PropsRef, kCFAllocatorDefault, kNilOptions);
1102 if (krc == KERN_SUCCESS)
1103 {
1104 bool fOk = false;
1105 PUSBDEVICE pCur = (PUSBDEVICE)RTMemAllocZ(sizeof(*pCur));
1106 do /* loop for breaking out of on failure. */
1107 {
1108 AssertBreak(pCur);
1109
1110 /*
1111 * Mandatory
1112 */
1113 pCur->bcdUSB = 0; /* we've no idea. */
1114 pCur->enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE; /* just a default, we'll try harder in a bit. */
1115
1116 /* Skip hubs. On 10.11 beta 3, the root hub simulations does not have a USBDeviceClass property, so
1117 simply ignore failures to retrieve it. */
1118 if (!darwinDictGetU8(PropsRef, CFSTR(kUSBDeviceClass), &pCur->bDeviceClass))
1119 {
1120#ifdef VBOX_STRICT
1121 char szTmp[80];
1122 Assert( darwinDictGetString(PropsRef, CFSTR("IOClassNameOverride"), szTmp, sizeof(szTmp))
1123 && strcmp(szTmp, "IOUSBRootHubDevice") == 0);
1124#endif
1125 break;
1126 }
1127 if (pCur->bDeviceClass == 0x09 /* hub, find a define! */)
1128 break;
1129 AssertBreak(darwinDictGetU8(PropsRef, CFSTR(kUSBDeviceSubClass), &pCur->bDeviceSubClass));
1130 AssertBreak(darwinDictGetU8(PropsRef, CFSTR(kUSBDeviceProtocol), &pCur->bDeviceProtocol));
1131 AssertBreak(darwinDictGetU16(PropsRef, CFSTR(kUSBVendorID), &pCur->idVendor));
1132 AssertBreak(darwinDictGetU16(PropsRef, CFSTR(kUSBProductID), &pCur->idProduct));
1133 AssertBreak(darwinDictGetU16(PropsRef, CFSTR(kUSBDeviceReleaseNumber), &pCur->bcdDevice));
1134 uint32_t u32LocationId;
1135 AssertBreak(darwinDictGetU32(PropsRef, CFSTR(kUSBDevicePropertyLocationID), &u32LocationId));
1136 uint64_t u64SessionId;
1137 AssertBreak(darwinDictGetU64(PropsRef, CFSTR("sessionID"), &u64SessionId));
1138 char szAddress[64];
1139 RTStrPrintf(szAddress, sizeof(szAddress), "p=0x%04RX16;v=0x%04RX16;s=0x%016RX64;l=0x%08RX32",
1140 pCur->idProduct, pCur->idVendor, u64SessionId, u32LocationId);
1141 pCur->pszAddress = RTStrDup(szAddress);
1142 AssertBreak(pCur->pszAddress);
1143 pCur->bBus = u32LocationId >> 24;
1144 darwinDictGetU8(PropsRef, CFSTR("PortNum"), &pCur->bPort); /* Not present in 10.11 beta 3, so ignore failure. (Is set to zero.) */
1145 uint8_t bSpeed;
1146 AssertBreak(darwinDictGetU8(PropsRef, CFSTR(kUSBDevicePropertySpeed), &bSpeed));
1147 Assert(bSpeed <= 3);
1148 pCur->enmSpeed = bSpeed == 3 ? USBDEVICESPEED_SUPER
1149 : bSpeed == 2 ? USBDEVICESPEED_HIGH
1150 : bSpeed == 1 ? USBDEVICESPEED_FULL
1151 : bSpeed == 0 ? USBDEVICESPEED_LOW
1152 : USBDEVICESPEED_UNKNOWN;
1153
1154 /*
1155 * Optional.
1156 * There are some nameless device in the iMac, apply names to them.
1157 */
1158 darwinDictDupString(PropsRef, CFSTR("USB Vendor Name"), (char **)&pCur->pszManufacturer);
1159 if ( !pCur->pszManufacturer
1160 && pCur->idVendor == kIOUSBVendorIDAppleComputer)
1161 pCur->pszManufacturer = RTStrDup("Apple Computer, Inc.");
1162 darwinDictDupString(PropsRef, CFSTR("USB Product Name"), (char **)&pCur->pszProduct);
1163 if ( !pCur->pszProduct
1164 && pCur->bDeviceClass == 224 /* Wireless */
1165 && pCur->bDeviceSubClass == 1 /* Radio Frequency */
1166 && pCur->bDeviceProtocol == 1 /* Bluetooth */)
1167 pCur->pszProduct = RTStrDup("Bluetooth");
1168 darwinDictDupString(PropsRef, CFSTR("USB Serial Number"), (char **)&pCur->pszSerialNumber);
1169
1170 pCur->pszBackend = RTStrDup("host");
1171 AssertBreak(pCur->pszBackend);
1172
1173#if 0 /* leave the remainder as zero for now. */
1174 /*
1175 * Create a plugin interface for the service and query its USB Device interface.
1176 */
1177 SInt32 Score = 0;
1178 IOCFPlugInInterface **ppPlugInInterface = NULL;
1179 rc = IOCreatePlugInInterfaceForService(USBDevice, kIOUSBDeviceUserClientTypeID,
1180 kIOCFPlugInInterfaceID, &ppPlugInInterface, &Score);
1181 if (rc == kIOReturnSuccess)
1182 {
1183 IOUSBDeviceInterface245 **ppUSBDevI = NULL;
1184 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
1185 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID245),
1186 (LPVOID *)&ppUSBDevI);
1187 rc = IODestroyPlugInInterface(ppPlugInInterface); Assert(rc == kIOReturnSuccess);
1188 ppPlugInInterface = NULL;
1189 if (hrc == S_OK)
1190 {
1191 /** @todo enumerate configurations and interfaces if we actually need them. */
1192 //IOReturn (*GetNumberOfConfigurations)(void *self, UInt8 *numConfig);
1193 //IOReturn (*GetConfigurationDescriptorPtr)(void *self, UInt8 configIndex, IOUSBConfigurationDescriptorPtr *desc);
1194 //IOReturn (*CreateInterfaceIterator)(void *self, IOUSBFindInterfaceRequest *req, io_iterator_t *iter);
1195 }
1196 long cReft = (*ppUSBDeviceInterface)->Release(ppUSBDeviceInterface); MY_CHECK_CREFS(cRefs);
1197 }
1198#endif
1199 /*
1200 * Try determine the state.
1201 */
1202 darwinDeterminUSBDeviceState(pCur, USBDevice, PropsRef);
1203
1204 /*
1205 * We're good. Link the device.
1206 */
1207 pCur->pPrev = pTail;
1208 if (pTail)
1209 pTail = pTail->pNext = pCur;
1210 else
1211 pTail = pHead = pCur;
1212 fOk = true;
1213 } while (0);
1214
1215 /* cleanup on failure / skipped device. */
1216 if (!fOk && pCur)
1217 DarwinFreeUSBDeviceFromIOKit(pCur);
1218
1219 CFRelease(PropsRef);
1220 }
1221 else
1222 AssertMsgFailed(("krc=%#x\n", krc));
1223
1224 IOObjectRelease(USBDevice);
1225 i++;
1226 }
1227
1228 IOObjectRelease(USBDevices);
1229 //DARWIN_IOKIT_LOG_FLUSH();
1230
1231 /*
1232 * Some post processing. There are a couple of things we have to
1233 * make 100% sure about, and that is that the (Apple) keyboard
1234 * and mouse most likely to be in use by the user aren't available
1235 * for capturing. If there is no Apple mouse or keyboard we'll
1236 * take the first one from another vendor.
1237 */
1238 /* As it turns out, the HID service will take all keyboards and mice
1239 and we're not currently able to seize them. */
1240 PUSBDEVICE pMouse = NULL;
1241 PUSBDEVICE pKeyboard = NULL;
1242 for (PUSBDEVICE pCur = pHead; pCur; pCur = pCur->pNext)
1243 if (pCur->idVendor == kIOUSBVendorIDAppleComputer)
1244 {
1245 /*
1246 * This test is a bit rough, should check device class/protocol but
1247 * we don't have interface info yet so that might be a bit tricky.
1248 */
1249 if ( ( !pKeyboard
1250 || pKeyboard->idVendor != kIOUSBVendorIDAppleComputer)
1251 && pCur->pszProduct
1252 && strstr(pCur->pszProduct, " Keyboard"))
1253 pKeyboard = pCur;
1254 else if ( ( !pMouse
1255 || pMouse->idVendor != kIOUSBVendorIDAppleComputer)
1256 && pCur->pszProduct
1257 && strstr(pCur->pszProduct, " Mouse")
1258 )
1259 pMouse = pCur;
1260 }
1261 else if (!pKeyboard || !pMouse)
1262 {
1263 if ( pCur->bDeviceClass == 3 /* HID */
1264 && pCur->bDeviceProtocol == 1 /* Keyboard */)
1265 pKeyboard = pCur;
1266 else if ( pCur->bDeviceClass == 3 /* HID */
1267 && pCur->bDeviceProtocol == 2 /* Mouse */)
1268 pMouse = pCur;
1269 /** @todo examin interfaces */
1270 }
1271
1272 if (pKeyboard)
1273 pKeyboard->enmState = USBDEVICESTATE_USED_BY_HOST;
1274 if (pMouse)
1275 pMouse->enmState = USBDEVICESTATE_USED_BY_HOST;
1276
1277 return pHead;
1278}
1279
1280#endif /* VBOX_WITH_USB */
1281
1282
1283/**
1284 * Enumerate the CD, DVD and BlueRay drives returning a FIFO of device name strings.
1285 *
1286 * @returns Pointer to the head.
1287 * The caller is responsible for calling RTMemFree() on each of the nodes.
1288 */
1289PDARWINDVD DarwinGetDVDDrives(void)
1290{
1291 AssertReturn(darwinOpenMasterPort(), NULL);
1292
1293 /*
1294 * Create a matching dictionary for searching for CD, DVD and BlueRay services in the IOKit.
1295 *
1296 * The idea is to find all the devices which are of class IOCDBlockStorageDevice.
1297 * CD devices are represented by IOCDBlockStorageDevice class itself, while DVD and BlueRay ones
1298 * have it as a parent class.
1299 */
1300 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IOCDBlockStorageDevice");
1301 AssertReturn(RefMatchingDict, NULL);
1302
1303 /*
1304 * Perform the search and get a collection of DVD services.
1305 */
1306 io_iterator_t DVDServices = IO_OBJECT_NULL;
1307 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &DVDServices);
1308 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), NULL);
1309 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1310
1311 /*
1312 * Enumerate the matching services.
1313 * (This enumeration must be identical to the one performed in DrvHostBase.cpp.)
1314 */
1315 PDARWINDVD pHead = NULL;
1316 PDARWINDVD pTail = NULL;
1317 unsigned i = 0;
1318 io_object_t DVDService;
1319 while ((DVDService = IOIteratorNext(DVDServices)) != IO_OBJECT_NULL)
1320 {
1321 DARWIN_IOKIT_DUMP_OBJ(DVDService);
1322
1323 /*
1324 * Get the properties we use to identify the DVD drive.
1325 *
1326 * While there is a (weird 12 byte) GUID, it isn't persistent
1327 * across boots. So, we have to use a combination of the
1328 * vendor name and product name properties with an optional
1329 * sequence number for identification.
1330 */
1331 CFMutableDictionaryRef PropsRef = 0;
1332 kern_return_t krc = IORegistryEntryCreateCFProperties(DVDService, &PropsRef, kCFAllocatorDefault, kNilOptions);
1333 if (krc == KERN_SUCCESS)
1334 {
1335 /* Get the Device Characteristics dictionary. */
1336 CFDictionaryRef DevCharRef = (CFDictionaryRef)CFDictionaryGetValue(PropsRef, CFSTR(kIOPropertyDeviceCharacteristicsKey));
1337 if (DevCharRef)
1338 {
1339 /* The vendor name. */
1340 char szVendor[128];
1341 char *pszVendor = &szVendor[0];
1342 CFTypeRef ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyVendorNameKey));
1343 if ( ValueRef
1344 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
1345 && CFStringGetCString((CFStringRef)ValueRef, szVendor, sizeof(szVendor), kCFStringEncodingUTF8))
1346 pszVendor = RTStrStrip(szVendor);
1347 else
1348 *pszVendor = '\0';
1349
1350 /* The product name. */
1351 char szProduct[128];
1352 char *pszProduct = &szProduct[0];
1353 ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyProductNameKey));
1354 if ( ValueRef
1355 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
1356 && CFStringGetCString((CFStringRef)ValueRef, szProduct, sizeof(szProduct), kCFStringEncodingUTF8))
1357 pszProduct = RTStrStrip(szProduct);
1358 else
1359 *pszProduct = '\0';
1360
1361 /* Construct the name and check for duplicates. */
1362 char szName[256 + 32];
1363 if (*pszVendor || *pszProduct)
1364 {
1365 if (*pszVendor && *pszProduct)
1366 RTStrPrintf(szName, sizeof(szName), "%s %s", pszVendor, pszProduct);
1367 else
1368 strcpy(szName, *pszVendor ? pszVendor : pszProduct);
1369
1370 for (PDARWINDVD pCur = pHead; pCur; pCur = pCur->pNext)
1371 {
1372 if (!strcmp(szName, pCur->szName))
1373 {
1374 if (*pszVendor && *pszProduct)
1375 RTStrPrintf(szName, sizeof(szName), "%s %s (#%u)", pszVendor, pszProduct, i);
1376 else
1377 RTStrPrintf(szName, sizeof(szName), "%s (#%u)", *pszVendor ? pszVendor : pszProduct, i);
1378 break;
1379 }
1380 }
1381 }
1382 else
1383 RTStrPrintf(szName, sizeof(szName), "(#%u)", i);
1384
1385 /* Create the device. */
1386 size_t cbName = strlen(szName) + 1;
1387 PDARWINDVD pNew = (PDARWINDVD)RTMemAlloc(RT_UOFFSETOF_DYN(DARWINDVD, szName[cbName]));
1388 if (pNew)
1389 {
1390 pNew->pNext = NULL;
1391 memcpy(pNew->szName, szName, cbName);
1392 if (pTail)
1393 pTail = pTail->pNext = pNew;
1394 else
1395 pTail = pHead = pNew;
1396 }
1397 }
1398 CFRelease(PropsRef);
1399 }
1400 else
1401 AssertMsgFailed(("krc=%#x\n", krc));
1402
1403 IOObjectRelease(DVDService);
1404 i++;
1405 }
1406
1407 IOObjectRelease(DVDServices);
1408
1409 return pHead;
1410}
1411
1412
1413/**
1414 * Enumerate the fixed drives (HDDs, SSD, ++) returning a FIFO of device paths
1415 * strings and model strings separated by ':'.
1416 *
1417 * @returns Pointer to the head.
1418 * The caller is responsible for calling RTMemFree() on each of the nodes.
1419 */
1420PDARWINFIXEDDRIVE DarwinGetFixedDrives(void)
1421{
1422 AssertReturn(darwinOpenMasterPort(), NULL);
1423
1424 /*
1425 * Create a matching dictionary for searching drives in the IOKit.
1426 *
1427 * The idea is to find all the IOMedia objects with "Whole"="True" which identify the disks but
1428 * not partitions.
1429 */
1430 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IOMedia");
1431 AssertReturn(RefMatchingDict, NULL);
1432 CFDictionaryAddValue(RefMatchingDict, CFSTR(kIOMediaWholeKey), kCFBooleanTrue);
1433
1434 /*
1435 * Perform the search and get a collection of IOMedia objects.
1436 */
1437 io_iterator_t MediaServices = IO_OBJECT_NULL;
1438 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &MediaServices);
1439 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), NULL);
1440 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1441
1442 /*
1443 * Enumerate the matching services.
1444 * (This enumeration must be identical to the one performed in DrvHostBase.cpp.)
1445 */
1446 PDARWINFIXEDDRIVE pHead = NULL;
1447 PDARWINFIXEDDRIVE pTail = NULL;
1448 unsigned i = 0;
1449 io_object_t MediaService;
1450 while ((MediaService = IOIteratorNext(MediaServices)) != IO_OBJECT_NULL)
1451 {
1452 DARWIN_IOKIT_DUMP_OBJ(MediaService);
1453
1454 /*
1455 * Find the IOMedia parents having the IOBlockStorageDevice type and check they have "device-type" = "Generic".
1456 * If the IOMedia object hasn't IOBlockStorageDevices with such device-type in parents the one is not general
1457 * disk but either CDROM-like device or some another device which has no interest for the function.
1458 */
1459
1460 /*
1461 * Just avoid parents enumeration if the IOMedia is IOCDMedia, i.e. CDROM-like disk
1462 */
1463 if (IOObjectConformsTo(MediaService, kIOCDMediaClass))
1464 {
1465 IOObjectRelease(MediaService);
1466 continue;
1467 }
1468
1469 bool fIsGenericStorage = false;
1470 io_registry_entry_t ChildEntry = MediaService;
1471 io_registry_entry_t ParentEntry = IO_OBJECT_NULL;
1472 kern_return_t krc = KERN_SUCCESS;
1473 while ( !fIsGenericStorage
1474 && (krc = IORegistryEntryGetParentEntry(ChildEntry, kIOServicePlane, &ParentEntry)) == KERN_SUCCESS)
1475 {
1476 if (!IOObjectIsEqualTo(ChildEntry, MediaService))
1477 IOObjectRelease(ChildEntry);
1478
1479 DARWIN_IOKIT_DUMP_OBJ(ParentEntry);
1480 if (IOObjectConformsTo(ParentEntry, kIOBlockStorageDeviceClass))
1481 {
1482 CFTypeRef DeviceTypeValueRef = IORegistryEntryCreateCFProperty(ParentEntry,
1483 CFSTR("device-type"),
1484 kCFAllocatorDefault, 0);
1485 if ( DeviceTypeValueRef
1486 && CFGetTypeID(DeviceTypeValueRef) == CFStringGetTypeID()
1487 && CFStringCompare((CFStringRef)DeviceTypeValueRef, CFSTR("Generic"),
1488 kCFCompareCaseInsensitive) == kCFCompareEqualTo)
1489 fIsGenericStorage = true;
1490
1491 if (DeviceTypeValueRef != NULL)
1492 CFRelease(DeviceTypeValueRef);
1493 }
1494 ChildEntry = ParentEntry;
1495 }
1496 if (ChildEntry != IO_OBJECT_NULL && !IOObjectIsEqualTo(ChildEntry, MediaService))
1497 IOObjectRelease(ChildEntry);
1498
1499 if (!fIsGenericStorage)
1500 {
1501 IOObjectRelease(MediaService);
1502 continue;
1503 }
1504
1505 CFTypeRef DeviceName;
1506 DeviceName = IORegistryEntryCreateCFProperty(MediaService,
1507 CFSTR(kIOBSDNameKey),
1508 kCFAllocatorDefault,0);
1509 if (DeviceName)
1510 {
1511 char szDeviceFilePath[MAXPATHLEN];
1512 strcpy(szDeviceFilePath, _PATH_DEV);
1513 size_t cchPathSize = strlen(szDeviceFilePath);
1514 if (CFStringGetCString((CFStringRef)DeviceName,
1515 &szDeviceFilePath[cchPathSize],
1516 (CFIndex)(sizeof(szDeviceFilePath) - cchPathSize),
1517 kCFStringEncodingUTF8))
1518 {
1519 PDARWINFIXEDDRIVE pDuplicate = pHead;
1520 while (pDuplicate && strcmp(szDeviceFilePath, pDuplicate->szName) != 0)
1521 pDuplicate = pDuplicate->pNext;
1522 if (pDuplicate == NULL)
1523 {
1524 /* Get model for the IOMedia object.
1525 *
1526 * Due to vendor and product property names are different and
1527 * depend on interface and device type, the best way to get a drive
1528 * model is get IORegistry name for the IOMedia object. Usually,
1529 * it takes "<vendor> <product> <revision> Media" form. Noticed,
1530 * such naming are used by only IOMedia objects having
1531 * "Whole" = True and "BSDName" properties set.
1532 */
1533 io_name_t szEntryName = { 0 };
1534 if ((krc = IORegistryEntryGetName(MediaService, szEntryName)) == KERN_SUCCESS)
1535 {
1536 /* remove " Media" from the end of the name */
1537 char *pszMedia = strrchr(szEntryName, ' ');
1538 if ( pszMedia != NULL
1539 && (uintptr_t)pszMedia < (uintptr_t)&szEntryName[sizeof(szEntryName)]
1540 && strcmp(pszMedia, " Media") == 0)
1541 {
1542 *pszMedia = '\0';
1543 RTStrPurgeEncoding(szEntryName);
1544 }
1545 }
1546 /* Create the device path and model name in form "/device/path:model". */
1547 cchPathSize = strlen(szDeviceFilePath);
1548 size_t const cchModelSize = strlen(szEntryName);
1549 size_t const cbExtra = cchPathSize + 1 + cchModelSize + !!cchModelSize;
1550 PDARWINFIXEDDRIVE pNew = (PDARWINFIXEDDRIVE)RTMemAlloc(RT_UOFFSETOF_DYN(DARWINFIXEDDRIVE, szName[cbExtra]));
1551 if (pNew)
1552 {
1553 pNew->pNext = NULL;
1554 memcpy(pNew->szName, szDeviceFilePath, cchPathSize + 1);
1555 pNew->pszModel = NULL;
1556 if (cchModelSize)
1557 pNew->pszModel = (const char *)memcpy(&pNew->szName[cchPathSize + 1], szEntryName, cchModelSize + 1);
1558
1559 if (pTail)
1560 pTail = pTail->pNext = pNew;
1561 else
1562 pTail = pHead = pNew;
1563 }
1564 }
1565 }
1566 CFRelease(DeviceName);
1567 }
1568 IOObjectRelease(MediaService);
1569 i++;
1570 }
1571 IOObjectRelease(MediaServices);
1572
1573 return pHead;
1574}
1575
1576
1577/**
1578 * Enumerate the ethernet capable network devices returning a FIFO of them.
1579 *
1580 * @returns Pointer to the head.
1581 */
1582PDARWINETHERNIC DarwinGetEthernetControllers(void)
1583{
1584 AssertReturn(darwinOpenMasterPort(), NULL);
1585
1586 /*
1587 * Create a matching dictionary for searching for ethernet controller
1588 * services in the IOKit.
1589 *
1590 * For some really stupid reason I don't get all the controllers if I look for
1591 * objects that are instances of IOEthernetController or its descendants (only
1592 * get the AirPort on my mac pro). But fortunately using IOEthernetInterface
1593 * seems to work. Weird s**t!
1594 */
1595 //CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IOEthernetController"); - this doesn't work :-(
1596 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IOEthernetInterface");
1597 AssertReturn(RefMatchingDict, NULL);
1598
1599 /*
1600 * Perform the search and get a collection of ethernet controller services.
1601 */
1602 io_iterator_t EtherIfServices = IO_OBJECT_NULL;
1603 IOReturn rc = IOServiceGetMatchingServices(g_MasterPort, RefMatchingDict, &EtherIfServices);
1604 AssertMsgReturn(rc == kIOReturnSuccess, ("rc=%d\n", rc), NULL);
1605 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
1606
1607 /*
1608 * Get a copy of the current network interfaces from the system configuration service.
1609 * We'll use this for looking up the proper interface names.
1610 */
1611 CFArrayRef IfsRef = SCNetworkInterfaceCopyAll();
1612 CFIndex cIfs = IfsRef ? CFArrayGetCount(IfsRef) : 0;
1613
1614 /*
1615 * Get the current preferences and make a copy of the network services so we
1616 * can look up the right interface names. The IfsRef is just for fallback.
1617 */
1618 CFArrayRef ServicesRef = NULL;
1619 CFIndex cServices = 0;
1620 SCPreferencesRef PrefsRef = SCPreferencesCreate(kCFAllocatorDefault, CFSTR("org.virtualbox.VBoxSVC"), NULL);
1621 if (PrefsRef)
1622 {
1623 SCNetworkSetRef SetRef = SCNetworkSetCopyCurrent(PrefsRef);
1624 CFRelease(PrefsRef);
1625 if (SetRef)
1626 {
1627 ServicesRef = SCNetworkSetCopyServices(SetRef);
1628 CFRelease(SetRef);
1629 cServices = ServicesRef ? CFArrayGetCount(ServicesRef) : 0;
1630 }
1631 }
1632
1633 /*
1634 * Enumerate the ethernet controller services.
1635 */
1636 PDARWINETHERNIC pHead = NULL;
1637 PDARWINETHERNIC pTail = NULL;
1638 io_object_t EtherIfService;
1639 while ((EtherIfService = IOIteratorNext(EtherIfServices)) != IO_OBJECT_NULL)
1640 {
1641 /*
1642 * Dig up the parent, meaning the IOEthernetController.
1643 */
1644 io_object_t EtherNICService;
1645 kern_return_t krc = IORegistryEntryGetParentEntry(EtherIfService, kIOServicePlane, &EtherNICService);
1646 /*krc = IORegistryEntryGetChildEntry(EtherNICService, kIOServicePlane, &EtherIfService); */
1647 if (krc == KERN_SUCCESS)
1648 {
1649 DARWIN_IOKIT_DUMP_OBJ(EtherNICService);
1650 /*
1651 * Get the properties we use to identify and name the Ethernet NIC.
1652 * We need the both the IOEthernetController and it's IONetworkInterface child.
1653 */
1654 CFMutableDictionaryRef PropsRef = 0;
1655 krc = IORegistryEntryCreateCFProperties(EtherNICService, &PropsRef, kCFAllocatorDefault, kNilOptions);
1656 if (krc == KERN_SUCCESS)
1657 {
1658 CFMutableDictionaryRef IfPropsRef = 0;
1659 krc = IORegistryEntryCreateCFProperties(EtherIfService, &IfPropsRef, kCFAllocatorDefault, kNilOptions);
1660 if (krc == KERN_SUCCESS)
1661 {
1662 /*
1663 * Gather the required data.
1664 * We'll create a UUID from the MAC address and the BSD name.
1665 */
1666 char szTmp[256];
1667 do
1668 {
1669 /* Check if airport (a bit heuristical - it's com.apple.driver.AirPortBrcm43xx here). */
1670 darwinDictGetString(PropsRef, CFSTR("CFBundleIdentifier"), szTmp, sizeof(szTmp));
1671 bool fWireless;
1672 bool fAirPort = fWireless = strstr(szTmp, ".AirPort") != NULL;
1673
1674 /* Check if it's USB. */
1675 darwinDictGetString(PropsRef, CFSTR("IOProviderClass"), szTmp, sizeof(szTmp));
1676 bool fUSB = strstr(szTmp, "USB") != NULL;
1677
1678
1679 /* Is it builtin? */
1680 bool fBuiltin;
1681 darwinDictGetBool(IfPropsRef, CFSTR("IOBuiltin"), &fBuiltin);
1682
1683 /* Is it the primary interface */
1684 bool fPrimaryIf;
1685 darwinDictGetBool(IfPropsRef, CFSTR("IOPrimaryInterface"), &fPrimaryIf);
1686
1687 /* Get the MAC address. */
1688 RTMAC Mac;
1689 AssertBreak(darwinDictGetData(PropsRef, CFSTR("IOMACAddress"), &Mac, sizeof(Mac)));
1690
1691 /* The BSD Name from the interface dictionary. No assert here as the belkin USB-C gadget
1692 does not always end up with a BSD name, typically requiring replugging. */
1693 char szBSDName[RT_SIZEOFMEMB(DARWINETHERNIC, szBSDName)];
1694 if (RT_UNLIKELY(!darwinDictGetString(IfPropsRef, CFSTR("BSD Name"), szBSDName, sizeof(szBSDName))))
1695 {
1696 LogRelMax(32, ("DarwinGetEthernetControllers: Warning! Failed to get 'BSD Name'; provider class %s\n", szTmp));
1697 break;
1698 }
1699
1700 /* Check if it's really wireless. */
1701 if ( darwinDictIsPresent(IfPropsRef, CFSTR("IO80211CountryCode"))
1702 || darwinDictIsPresent(IfPropsRef, CFSTR("IO80211DriverVersion"))
1703 || darwinDictIsPresent(IfPropsRef, CFSTR("IO80211HardwareVersion"))
1704 || darwinDictIsPresent(IfPropsRef, CFSTR("IO80211Locale")))
1705 fWireless = true;
1706 else
1707 fAirPort = fWireless = false;
1708
1709 /** @todo IOPacketFilters / IONetworkFilterGroup? */
1710 /*
1711 * Create the interface name.
1712 *
1713 * Note! The ConsoleImpl2.cpp code ASSUMES things about the name. It is also
1714 * stored in the VM config files. (really bright idea)
1715 */
1716 strcpy(szTmp, szBSDName);
1717 char *psz = strchr(szTmp, '\0');
1718 *psz++ = ':';
1719 *psz++ = ' ';
1720 size_t cchLeft = sizeof(szTmp) - (size_t)(psz - &szTmp[0]) - (sizeof(" (Wireless)") - 1);
1721 bool fFound = false;
1722 CFIndex i;
1723
1724 /* look it up among the current services */
1725 for (i = 0; i < cServices; i++)
1726 {
1727 SCNetworkServiceRef ServiceRef = (SCNetworkServiceRef)CFArrayGetValueAtIndex(ServicesRef, i);
1728 SCNetworkInterfaceRef IfRef = SCNetworkServiceGetInterface(ServiceRef);
1729 if (IfRef)
1730 {
1731 CFStringRef BSDNameRef = SCNetworkInterfaceGetBSDName(IfRef);
1732 if ( BSDNameRef
1733 && CFStringGetCString(BSDNameRef, psz, (CFIndex)cchLeft, kCFStringEncodingUTF8)
1734 && !strcmp(psz, szBSDName))
1735 {
1736 CFStringRef ServiceNameRef = SCNetworkServiceGetName(ServiceRef);
1737 if ( ServiceNameRef
1738 && CFStringGetCString(ServiceNameRef, psz, (CFIndex)cchLeft, kCFStringEncodingUTF8))
1739 {
1740 fFound = true;
1741 break;
1742 }
1743 }
1744 }
1745 }
1746 /* Look it up in the interface list. */
1747 if (!fFound)
1748 for (i = 0; i < cIfs; i++)
1749 {
1750 SCNetworkInterfaceRef IfRef = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(IfsRef, i);
1751 CFStringRef BSDNameRef = SCNetworkInterfaceGetBSDName(IfRef);
1752 if ( BSDNameRef
1753 && CFStringGetCString(BSDNameRef, psz, (CFIndex)cchLeft, kCFStringEncodingUTF8)
1754 && !strcmp(psz, szBSDName))
1755 {
1756 CFStringRef DisplayNameRef = SCNetworkInterfaceGetLocalizedDisplayName(IfRef);
1757 if ( DisplayNameRef
1758 && CFStringGetCString(DisplayNameRef, psz, (CFIndex)cchLeft, kCFStringEncodingUTF8))
1759 {
1760 fFound = true;
1761 break;
1762 }
1763 }
1764 }
1765 /* Generate a half plausible name if we for some silly reason didn't find the interface. */
1766 if (!fFound)
1767 RTStrPrintf(szTmp, sizeof(szTmp), "%s: %s%s(?)",
1768 szBSDName,
1769 fUSB ? "USB " : "",
1770 fWireless ? fAirPort ? "AirPort " : "Wireless" : "Ethernet");
1771 /* If we did find it and it's wireless but without "AirPort" or "Wireless", fix it */
1772 else if ( fWireless
1773 && !strstr(psz, "AirPort")
1774 && !strstr(psz, "Wireless"))
1775 strcat(szTmp, fAirPort ? " (AirPort)" : " (Wireless)");
1776
1777 /*
1778 * Create the list entry.
1779 */
1780 DARWIN_IOKIT_LOG(("Found: if=%s mac=%.6Rhxs fWireless=%RTbool fAirPort=%RTbool fBuiltin=%RTbool fPrimaryIf=%RTbool fUSB=%RTbool\n",
1781 szBSDName, &Mac, fWireless, fAirPort, fBuiltin, fPrimaryIf, fUSB));
1782
1783 size_t cchName = strlen(szTmp);
1784 PDARWINETHERNIC pNew = (PDARWINETHERNIC)RTMemAlloc(RT_UOFFSETOF_DYN(DARWINETHERNIC, szName[cchName + 1]));
1785 if (pNew)
1786 {
1787 strncpy(pNew->szBSDName, szBSDName, sizeof(pNew->szBSDName)); /* the '\0' padding is intentional! */
1788
1789 RTUuidClear(&pNew->Uuid);
1790 memcpy(&pNew->Uuid, pNew->szBSDName, RT_MIN(sizeof(pNew->szBSDName), sizeof(pNew->Uuid)));
1791 pNew->Uuid.Gen.u8ClockSeqHiAndReserved = (pNew->Uuid.Gen.u8ClockSeqHiAndReserved & 0x3f) | 0x80;
1792 pNew->Uuid.Gen.u16TimeHiAndVersion = (pNew->Uuid.Gen.u16TimeHiAndVersion & 0x0fff) | 0x4000;
1793 pNew->Uuid.Gen.au8Node[0] = Mac.au8[0];
1794 pNew->Uuid.Gen.au8Node[1] = Mac.au8[1];
1795 pNew->Uuid.Gen.au8Node[2] = Mac.au8[2];
1796 pNew->Uuid.Gen.au8Node[3] = Mac.au8[3];
1797 pNew->Uuid.Gen.au8Node[4] = Mac.au8[4];
1798 pNew->Uuid.Gen.au8Node[5] = Mac.au8[5];
1799
1800 pNew->Mac = Mac;
1801 pNew->fWireless = fWireless;
1802 pNew->fAirPort = fAirPort;
1803 pNew->fBuiltin = fBuiltin;
1804 pNew->fUSB = fUSB;
1805 pNew->fPrimaryIf = fPrimaryIf;
1806 memcpy(pNew->szName, szTmp, cchName + 1);
1807
1808 /*
1809 * Link it into the list, keep the list sorted by fPrimaryIf and the BSD name.
1810 */
1811 if (pTail)
1812 {
1813 PDARWINETHERNIC pPrev = pTail;
1814 if (strcmp(pNew->szBSDName, pPrev->szBSDName) < 0)
1815 {
1816 pPrev = NULL;
1817 for (PDARWINETHERNIC pCur = pHead; pCur; pPrev = pCur, pCur = pCur->pNext)
1818 if ( (int)pNew->fPrimaryIf - (int)pCur->fPrimaryIf > 0
1819 || ( (int)pNew->fPrimaryIf - (int)pCur->fPrimaryIf == 0
1820 && strcmp(pNew->szBSDName, pCur->szBSDName) >= 0))
1821 break;
1822 }
1823 if (pPrev)
1824 {
1825 /* tail or in list. */
1826 pNew->pNext = pPrev->pNext;
1827 pPrev->pNext = pNew;
1828 if (pPrev == pTail)
1829 pTail = pNew;
1830 }
1831 else
1832 {
1833 /* head */
1834 pNew->pNext = pHead;
1835 pHead = pNew;
1836 }
1837 }
1838 else
1839 {
1840 /* empty list */
1841 pNew->pNext = NULL;
1842 pTail = pHead = pNew;
1843 }
1844 }
1845 } while (0);
1846
1847 CFRelease(IfPropsRef);
1848 }
1849 CFRelease(PropsRef);
1850 }
1851 IOObjectRelease(EtherNICService);
1852 }
1853 else
1854 AssertMsgFailed(("krc=%#x\n", krc));
1855 IOObjectRelease(EtherIfService);
1856 }
1857
1858 IOObjectRelease(EtherIfServices);
1859 if (ServicesRef)
1860 CFRelease(ServicesRef);
1861 if (IfsRef)
1862 CFRelease(IfsRef);
1863 return pHead;
1864}
1865
1866#ifdef STANDALONE_TESTCASE
1867/**
1868 * This file can optionally be compiled into a testcase, this is the main function.
1869 * To build:
1870 * g++ -I ../../../../include -D IN_RING3 iokit.cpp ../../../../out/darwin.x86/debug/lib/RuntimeR3.a ../../../../out/darwin.x86/debug/lib/SUPR3.a ../../../../out/darwin.x86/debug/lib/RuntimeR3.a ../../../../out/darwin.x86/debug/lib/VBox-kStuff.a ../../../../out/darwin.x86/debug/lib/RuntimeR3.a -framework CoreFoundation -framework IOKit -framework SystemConfiguration -liconv -D STANDALONE_TESTCASE -o iokit -g && ./iokit
1871 */
1872int main(int argc, char **argv)
1873{
1874 RTR3InitExe(argc, &argv, 0);
1875
1876 if (1)
1877 {
1878 /*
1879 * Network preferences.
1880 */
1881 RTPrintf("Preferences: Network Services\n");
1882 SCPreferencesRef PrefsRef = SCPreferencesCreate(kCFAllocatorDefault, CFSTR("org.virtualbox.VBoxSVC"), NULL);
1883 if (PrefsRef)
1884 {
1885 CFDictionaryRef NetworkServiceRef = (CFDictionaryRef)SCPreferencesGetValue(PrefsRef, kSCPrefNetworkServices);
1886 darwinDumpDict(NetworkServiceRef, 4);
1887 CFRelease(PrefsRef);
1888 }
1889 }
1890
1891 if (1)
1892 {
1893 /*
1894 * Network services interfaces in the current config.
1895 */
1896 RTPrintf("Preferences: Network Service Interfaces\n");
1897 SCPreferencesRef PrefsRef = SCPreferencesCreate(kCFAllocatorDefault, CFSTR("org.virtualbox.VBoxSVC"), NULL);
1898 if (PrefsRef)
1899 {
1900 SCNetworkSetRef SetRef = SCNetworkSetCopyCurrent(PrefsRef);
1901 if (SetRef)
1902 {
1903 CFArrayRef ServicesRef = SCNetworkSetCopyServices(SetRef);
1904 CFIndex cServices = CFArrayGetCount(ServicesRef);
1905 for (CFIndex i = 0; i < cServices; i++)
1906 {
1907 SCNetworkServiceRef ServiceRef = (SCNetworkServiceRef)CFArrayGetValueAtIndex(ServicesRef, i);
1908 char szServiceName[128] = {0};
1909 CFStringGetCString(SCNetworkServiceGetName(ServiceRef), szServiceName, sizeof(szServiceName), kCFStringEncodingUTF8);
1910
1911 SCNetworkInterfaceRef IfRef = SCNetworkServiceGetInterface(ServiceRef);
1912 char szBSDName[16] = {0};
1913 if (SCNetworkInterfaceGetBSDName(IfRef))
1914 CFStringGetCString(SCNetworkInterfaceGetBSDName(IfRef), szBSDName, sizeof(szBSDName), kCFStringEncodingUTF8);
1915 char szDisplayName[128] = {0};
1916 if (SCNetworkInterfaceGetLocalizedDisplayName(IfRef))
1917 CFStringGetCString(SCNetworkInterfaceGetLocalizedDisplayName(IfRef), szDisplayName, sizeof(szDisplayName), kCFStringEncodingUTF8);
1918
1919 RTPrintf(" #%u ServiceName=\"%s\" IfBSDName=\"%s\" IfDisplayName=\"%s\"\n",
1920 i, szServiceName, szBSDName, szDisplayName);
1921 }
1922
1923 CFRelease(ServicesRef);
1924 CFRelease(SetRef);
1925 }
1926
1927 CFRelease(PrefsRef);
1928 }
1929 }
1930
1931 if (1)
1932 {
1933 /*
1934 * Network interfaces.
1935 */
1936 RTPrintf("Preferences: Network Interfaces\n");
1937 CFArrayRef IfsRef = SCNetworkInterfaceCopyAll();
1938 if (IfsRef)
1939 {
1940 CFIndex cIfs = CFArrayGetCount(IfsRef);
1941 for (CFIndex i = 0; i < cIfs; i++)
1942 {
1943 SCNetworkInterfaceRef IfRef = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(IfsRef, i);
1944 char szBSDName[16] = {0};
1945 if (SCNetworkInterfaceGetBSDName(IfRef))
1946 CFStringGetCString(SCNetworkInterfaceGetBSDName(IfRef), szBSDName, sizeof(szBSDName), kCFStringEncodingUTF8);
1947 char szDisplayName[128] = {0};
1948 if (SCNetworkInterfaceGetLocalizedDisplayName(IfRef))
1949 CFStringGetCString(SCNetworkInterfaceGetLocalizedDisplayName(IfRef), szDisplayName, sizeof(szDisplayName), kCFStringEncodingUTF8);
1950 RTPrintf(" #%u BSDName=\"%s\" DisplayName=\"%s\"\n",
1951 i, szBSDName, szDisplayName);
1952 }
1953
1954 CFRelease(IfsRef);
1955 }
1956 }
1957
1958 if (1)
1959 {
1960 /*
1961 * Get and display the ethernet controllers.
1962 */
1963 RTPrintf("Ethernet controllers:\n");
1964 PDARWINETHERNIC pEtherNICs = DarwinGetEthernetControllers();
1965 for (PDARWINETHERNIC pCur = pEtherNICs; pCur; pCur = pCur->pNext)
1966 {
1967 RTPrintf("%s\n", pCur->szName);
1968 RTPrintf(" szBSDName=%s\n", pCur->szBSDName);
1969 RTPrintf(" UUID=%RTuuid\n", &pCur->Uuid);
1970 RTPrintf(" Mac=%.6Rhxs\n", &pCur->Mac);
1971 RTPrintf(" fWireless=%RTbool\n", pCur->fWireless);
1972 RTPrintf(" fAirPort=%RTbool\n", pCur->fAirPort);
1973 RTPrintf(" fBuiltin=%RTbool\n", pCur->fBuiltin);
1974 RTPrintf(" fUSB=%RTbool\n", pCur->fUSB);
1975 RTPrintf(" fPrimaryIf=%RTbool\n", pCur->fPrimaryIf);
1976 }
1977 }
1978
1979
1980 return 0;
1981}
1982#endif
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette