2 * Copyright (c) 2001-2020 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
25 * Modification History
27 * May 20, 2006 Joe Liu <joe.liu@apple.com>
28 * Allan Nathanson <ajn@apple.com>
29 * - register interface by entryID (and not path)
31 * November 6, 2006 Allan Nathanson <ajn@apple.com>
32 * Dan Markarian <markarian@apple.com>
33 * Dieter Siegmund <dieter@apple.com>
34 * - updated code to name interfaces quicker (without need for
35 * calling IOKitWaitQuiet).
37 * October 3, 2003 Allan Nathanson <ajn@apple.com>
38 * - sort new interfaces by IOKit path (rather than MAC address) to
39 * help facilitate a more predictable interface-->name mapping for
40 * like hardware configurations.
42 * June 23, 2001 Allan Nathanson <ajn@apple.com>
43 * - update to public SystemConfiguration.framework APIs
45 * January 23, 2001 Dieter Siegmund <dieter@apple.com>
51 * - module that receives IOKit Network Interface messages
52 * and names any interface that currently does not have a name
53 * - uses Interface Type and MACAddress as the unique identifying
54 * keys; any interface that doesn't contain both of these properties
55 * is ignored and not processed
56 * - stores the Interface Type, MACAddress, and Unit in permanent storage
57 * to give persistent interface names
60 #include <TargetConditionals.h>
69 #endif // TARGET_OS_IPHONE
70 #include <sys/ioctl.h>
72 #include <sys/sysctl.h>
73 #include <sys/param.h>
74 #include <mach/mach.h>
75 #include <net/ethernet.h>
76 #include <net/if_types.h>
79 #include <CommonCrypto/CommonDigest.h>
81 #include <CoreFoundation/CoreFoundation.h>
83 #include <SystemConfiguration/SystemConfiguration.h>
84 #include <SystemConfiguration/SCDPlugin.h>
85 #include <SystemConfiguration/SCPrivate.h>
86 #include <SystemConfiguration/SCValidation.h>
87 #include "SCNetworkConfigurationInternal.h"
88 #include "SCPreferencesInternal.h"
89 #include "plugin_shared.h"
91 #include "InterfaceNamerControlPrefs.h"
92 #endif // !TARGET_OS_IPHONE
94 #ifdef TEST_INTERFACE_ASSIGNMENT
95 #undef INTERFACES_DEFAULT_CONFIG
96 #define INTERFACES_DEFAULT_CONFIG CFSTR("/tmp/ifnamer-test-NetworkInterfaces.plist")
97 #endif // TEST_INTERFACE_ASSIGNMENT
99 #include <IOKit/IOKitLib.h>
100 #include <IOKit/IOKitLibPrivate.h>
101 #include <IOKit/IOKitKeysPrivate.h>
102 #include <IOKit/IOBSD.h>
103 #include <IOKit/IOMessage.h>
104 #include <IOKit/network/IONetworkController.h>
105 #include <IOKit/network/IONetworkInterface.h>
106 #include <IOKit/network/IONetworkStack.h>
107 #include <IOKit/usb/USB.h>
109 #ifdef kIONetworkStackUserCommandKey
110 #define USE_REGISTRY_ENTRY_ID
113 #ifndef USE_REGISTRY_ENTRY_ID
114 // from <IOKit/network/IONetworkStack.h>
115 #define kIONetworkStackUserCommandKey "IONetworkStackUserCommand"
117 kRegisterInterfaceWithFixedUnit
= 0,
119 kRegisterAllInterfaces
121 #endif // !USE_REGISTRY_ENTRY_ID
123 #define MY_PLUGIN_NAME "InterfaceNamer"
124 #define MY_PLUGIN_ID CFSTR("com.apple.SystemConfiguration." MY_PLUGIN_NAME)
126 #define WAIT_STACK_TIMEOUT_KEY "WaitStackTimeout"
127 #define WAIT_STACK_TIMEOUT_DEFAULT 300.0
129 #define WAIT_QUIET_TIMEOUT_KEY "WaitQuietTimeout"
130 #define WAIT_QUIET_TIMEOUT_DEFAULT 240.0
134 * "IONetworkStack" connect object used to "name" an interface.
136 static io_connect_t S_connect
= MACH_PORT_NULL
;
140 * An array of CFDictionary's representing the interfaces
141 * that have been identified and [need to be] named.
143 static CFMutableArrayRef S_dblist
= NULL
;
147 * An array of SCNetworkInterface's representing the
148 * interfaces that have been identified.
150 static CFMutableArrayRef S_iflist
= NULL
;
154 * IOServiceAddMatchingNotification object used to watch for
155 * new network interfaces.
157 static io_iterator_t S_iter
= MACH_PORT_NULL
;
159 #if !TARGET_OS_IPHONE
162 * An array of CFData(WatchedInfo) objects representing those
163 * interfaces that have been connected to the system while
166 static CFMutableArrayRef S_locked
= NULL
;
167 #endif // !TARGET_OS_IPHONE
171 * notification object for receiving IOKit notifications of
172 * new devices or state changes.
174 static IONotificationPortRef S_notify
= NULL
;
178 * An array of CFData(WatchedInfo) objects representing those
179 * pre-configured interfaces that have been connected to the
182 static CFMutableArrayRef S_preconfigured
= NULL
;
184 /* S_prev_active_list
185 * An array of CFDictionary's representing the previously
188 static CFMutableArrayRef S_prev_active_list
= NULL
;
192 * IOServiceAddInterestNotification object used to watch for
193 * IOKit matching to quiesce.
195 static io_object_t S_quiet
= MACH_PORT_NULL
;
199 * IOServiceAddMatchingNotification object used to watch for
200 * the availability of the "IONetworkStack" object.
202 static io_iterator_t S_stack
= MACH_PORT_NULL
;
206 * A dictionary containing Information about each network
207 * interface. For now, the key is the BSD name and the
208 * value is a CFNumber noting how long (in milliseconds)
209 * it took for the interface to be recognized/named.
211 static CFMutableDictionaryRef S_state
= NULL
;
215 * S_trustedHostAttached
217 * Note: this global must only be updated on trustRequired_queue()
219 static Boolean S_trustedHostAttached
= FALSE
;
223 * Note: this global must only be updated on trustRequired_queue()
225 static CFIndex S_trustedHostCount
= 0;
229 * An array of CFData(WatchedInfo) objects representing those
230 * interfaces that require [lockdownd] trust.
232 static CFMutableArrayRef S_trustRequired
= NULL
;
233 #endif // TARGET_OS_IPHONE
237 * CFRunLoopTimer tracking how long we are willing to wait
238 * for IOKit matching to quiesce (IOKitWaitQuiet).
241 * time to wait for the IONetworkStack object to appear before timeout
244 * time to wait for the IOKit to quiesce (after the IONetworkStack is
247 static CFRunLoopTimerRef S_timer
= NULL
;
248 static double S_stack_timeout
= WAIT_STACK_TIMEOUT_DEFAULT
;
249 static double S_quiet_timeout
= WAIT_QUIET_TIMEOUT_DEFAULT
;
252 * Virtual network interface configuration
253 * S_prefs : SCPreferences to configuration
254 * S_bonds : most recently actived Bond configuration
255 * S_bridges : most recently actived Bridge configuration
256 * S_vlans : most recently actived VLAN configuration
258 static SCPreferencesRef S_prefs
= NULL
;
259 static CFArrayRef S_bonds
= NULL
;
260 static CFArrayRef S_bridges
= NULL
;
261 static CFArrayRef S_vlans
= NULL
;
268 __log_InterfaceNamer(void)
270 static os_log_t log
= NULL
;
273 log
= os_log_create("com.apple.SystemConfiguration", "InterfaceNamer");
281 addTimestamp(CFMutableDictionaryRef dict
, CFStringRef key
)
286 now
= CFAbsoluteTimeGetCurrent();
287 val
= CFNumberCreate(NULL
, kCFNumberDoubleType
, &now
);
288 CFDictionaryAddValue(dict
, key
, val
);
293 static CFComparisonResult
294 if_unit_compare(const void *val1
, const void *val2
, void *context
)
296 #pragma unused(context)
297 CFComparisonResult res
;
303 type1
= CFDictionaryGetValue((CFDictionaryRef
)val1
,
304 CFSTR(kIOInterfaceType
));
305 type2
= CFDictionaryGetValue((CFDictionaryRef
)val2
,
306 CFSTR(kIOInterfaceType
));
307 res
= CFNumberCompare(type1
, type2
, NULL
);
308 if (res
!= kCFCompareEqualTo
) {
311 unit1
= CFDictionaryGetValue((CFDictionaryRef
)val1
,
312 CFSTR(kIOInterfaceUnit
));
313 unit2
= CFDictionaryGetValue((CFDictionaryRef
)val2
,
314 CFSTR(kIOInterfaceUnit
));
315 return (CFNumberCompare(unit1
, unit2
, NULL
));
319 writeInterfaceListForModel(SCPreferencesRef prefs
, CFStringRef old_model
)
322 CFPropertyListRef plist
;
323 SCPreferencesRef savedPrefs
;
324 CFStringRef savedPrefsID
;
326 savedPrefsID
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%@-%@"),
327 INTERFACES_DEFAULT_CONFIG
,
329 savedPrefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":writeInterfaceListForModel"), savedPrefsID
);
330 CFRelease(savedPrefsID
);
331 if (savedPrefs
== NULL
) {
332 SC_log(LOG_NOTICE
, "SCPreferencesCreate(\"NetworkInterfaces-<model>.plist\") failed: %s", SCErrorString(SCError()));
336 plist
= SCPreferencesPathGetValue(prefs
, CFSTR("/"));
337 ok
= SCPreferencesPathSetValue(savedPrefs
, CFSTR("/"), plist
);
339 SC_log(LOG_NOTICE
, "SCPreferencesPathSetValue() failed: %s", SCErrorString(SCError()));
342 ok
= SCPreferencesCommitChanges(savedPrefs
);
343 CFRelease(savedPrefs
);
345 SC_log(LOG_NOTICE
, "SCPreferencesCommitChanges(\"NetworkInterfaces-<model>.plist\") failed: %s", SCErrorString(SCError()));
352 writeInterfaceList(CFArrayRef if_list
)
355 CFStringRef new_model
;
356 SCPreferencesRef ni_prefs
;
357 CFStringRef old_model
;
359 if (!isA_CFArray(if_list
)) {
363 ni_prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":writeInterfaceList"), INTERFACES_DEFAULT_CONFIG
);
364 if (ni_prefs
== NULL
) {
365 SC_log(LOG_NOTICE
, "SCPreferencesCreate(\"NetworkInterfaces.plist\") failed: %s", SCErrorString(SCError()));
369 cur_list
= SCPreferencesGetValue(ni_prefs
, INTERFACES
);
370 if (_SC_CFEqual(cur_list
, if_list
)) {
374 old_model
= SCPreferencesGetValue(ni_prefs
, MODEL
);
375 new_model
= _SC_hw_model(FALSE
);
376 if ((old_model
!= NULL
) && !_SC_CFEqual(old_model
, new_model
)) {
378 if ((old_model
!= NULL
) && (cur_list
!= NULL
)) {
379 SC_log(LOG_NOTICE
, "Hardware model changed\n"
380 " created on \"%@\"\n"
385 // save the interface list that was created on "other" hardware
386 writeInterfaceListForModel(ni_prefs
, old_model
);
389 SCPreferencesSetValue(ni_prefs
, MODEL
, new_model
);
392 SCPreferencesSetValue(ni_prefs
, INTERFACES
, if_list
);
394 if (cur_list
== NULL
) {
395 const int new_version
= NETWORK_CONFIGURATION_VERSION
;
398 version
= CFNumberCreate(NULL
, kCFNumberIntType
, &new_version
);
399 SCPreferencesSetValue(ni_prefs
, kSCPrefVersion
, version
);
403 if (!SCPreferencesCommitChanges(ni_prefs
)) {
404 if (SCError() != EROFS
) {
405 SC_log(LOG_NOTICE
, "SCPreferencesCommitChanges() failed: %s", SCErrorString(SCError()));
416 static CF_RETURNS_RETAINED CFMutableArrayRef
419 CFMutableArrayRef db_list
= NULL
;
421 SCPreferencesRef ni_prefs
;
422 CFStringRef old_model
;
424 ni_prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":readInterfaceList"), INTERFACES_DEFAULT_CONFIG
);
425 if (ni_prefs
== NULL
) {
426 SC_log(LOG_NOTICE
, "SCPreferencesCreate() failed: %s", SCErrorString(SCError()));
430 if_list
= SCPreferencesGetValue(ni_prefs
, INTERFACES
);
431 if_list
= isA_CFArray(if_list
);
433 old_model
= SCPreferencesGetValue(ni_prefs
, MODEL
);
434 if (old_model
!= NULL
) {
435 CFStringRef new_model
;
437 new_model
= _SC_hw_model(FALSE
);
438 if (!_SC_CFEqual(old_model
, new_model
)) {
440 * If the interface list was created on other hardware then
447 if (if_list
!= NULL
) {
448 CFIndex n
= CFArrayGetCount(if_list
);
450 db_list
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
451 for (CFIndex i
= 0; i
< n
; i
++) {
452 CFDictionaryRef dict
;
454 dict
= CFArrayGetValueAtIndex(if_list
, i
);
455 if (isA_CFDictionary(dict
) &&
456 CFDictionaryContainsKey(dict
, CFSTR(kIOInterfaceType
)) &&
457 CFDictionaryContainsKey(dict
, CFSTR(kIOInterfaceUnit
)) &&
458 CFDictionaryContainsKey(dict
, CFSTR(kIOMACAddress
))) {
459 CFArrayAppendValue(db_list
, dict
);
464 if (db_list
!= NULL
) {
465 CFIndex n
= CFArrayGetCount(db_list
);
468 CFArraySortValues(db_list
, CFRangeMake(0, n
), if_unit_compare
, NULL
);
476 static CF_RETURNS_RETAINED CFMutableArrayRef
477 previouslyActiveInterfaces()
479 CFMutableArrayRef active
;
482 if (S_dblist
== NULL
) {
486 active
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
488 n
= CFArrayGetCount(S_dblist
);
489 for (CFIndex i
= 0; i
< n
; i
++) {
490 CFDictionaryRef if_dict
;
492 if_dict
= CFArrayGetValueAtIndex(S_dblist
, i
);
493 if (CFDictionaryContainsKey(if_dict
, CFSTR(kSCNetworkInterfaceActive
))) {
494 CFMutableDictionaryRef new_dict
;
496 new_dict
= CFDictionaryCreateMutableCopy(NULL
, 0, if_dict
);
497 CFDictionaryRemoveValue(new_dict
, CFSTR(kSCNetworkInterfaceActive
));
498 CFArraySetValueAtIndex(S_dblist
, i
, new_dict
);
499 CFArrayAppendValue(active
, new_dict
);
508 updateInterfaces(void);
515 key
= SCDynamicStoreKeyCreate(NULL
, CFSTR("%@" MY_PLUGIN_NAME
), kSCDynamicStoreDomainPlugin
);
516 (void)SCDynamicStoreSetValue(NULL
, key
, S_state
);
522 #if !TARGET_OS_IPHONE
524 updateBondInterfaceConfiguration(SCPreferencesRef prefs
)
526 CFArrayRef interfaces
;
528 interfaces
= SCBondInterfaceCopyAll(prefs
);
529 if ((interfaces
!= NULL
) && (CFArrayGetCount(interfaces
) == 0)) {
530 CFRelease(interfaces
);
534 if (_SC_CFEqual(S_bonds
, interfaces
)) {
536 if (interfaces
!= NULL
) CFRelease(interfaces
);
540 if (S_bonds
!= NULL
) CFRelease(S_bonds
);
541 S_bonds
= interfaces
;
543 if (!_SCBondInterfaceUpdateConfiguration(prefs
)) {
544 SC_log(LOG_NOTICE
, "_SCBondInterfaceUpdateConfiguration() failed: %s",
545 SCErrorString(SCError()));
550 #endif // !TARGET_OS_IPHONE
553 updateBridgeInterfaceConfiguration(SCPreferencesRef prefs
)
555 CFArrayRef interfaces
;
557 interfaces
= SCBridgeInterfaceCopyAll(prefs
);
558 if ((interfaces
!= NULL
) && (CFArrayGetCount(interfaces
) == 0)) {
559 CFRelease(interfaces
);
563 if (_SC_CFEqual(S_bridges
, interfaces
)) {
565 if (interfaces
!= NULL
) CFRelease(interfaces
);
569 if (S_bridges
!= NULL
) CFRelease(S_bridges
);
570 S_bridges
= interfaces
;
572 if (!_SCBridgeInterfaceUpdateConfiguration(prefs
)) {
573 SC_log(LOG_NOTICE
, "_SCBridgeInterfaceUpdateConfiguration() failed: %s",
574 SCErrorString(SCError()));
581 updateVLANInterfaceConfiguration(SCPreferencesRef prefs
)
583 CFArrayRef interfaces
;
585 interfaces
= SCVLANInterfaceCopyAll(prefs
);
586 if ((interfaces
!= NULL
) && (CFArrayGetCount(interfaces
) == 0)) {
587 CFRelease(interfaces
);
591 if (_SC_CFEqual(S_vlans
, interfaces
)) {
593 if (interfaces
!= NULL
) CFRelease(interfaces
);
597 if (S_vlans
!= NULL
) CFRelease(S_vlans
);
598 S_vlans
= interfaces
;
600 if (!_SCVLANInterfaceUpdateConfiguration(prefs
)) {
601 SC_log(LOG_NOTICE
, "_SCVLANInterfaceUpdateConfiguration() failed: %s",
602 SCErrorString(SCError()));
609 updateVirtualNetworkInterfaceConfiguration(SCPreferencesRef prefs
,
610 SCPreferencesNotification notificationType
,
614 if ((notificationType
& kSCPreferencesNotificationApply
) != kSCPreferencesNotificationApply
) {
619 // if a new interface has been "named"
621 if (S_bonds
!= NULL
) {
625 if (S_bridges
!= NULL
) {
626 CFRelease(S_bridges
);
629 if (S_vlans
!= NULL
) {
635 #if !TARGET_OS_IPHONE
636 updateBondInterfaceConfiguration (prefs
);
637 #endif // !TARGET_OS_IPHONE
638 updateBridgeInterfaceConfiguration(prefs
);
639 updateVLANInterfaceConfiguration (prefs
);
641 // we are finished with current prefs, wait for changes
642 SCPreferencesSynchronize(prefs
);
650 updateBTPANInformation(const void *value
, void *context
)
652 #pragma unused(context)
654 CFDictionaryRef dict
= (CFDictionaryRef
)value
;
656 CFDictionaryRef info
;
659 if_name
= CFDictionaryGetValue(dict
, CFSTR(kIOBSDNameKey
));
660 if (!isA_CFString(if_name
)) {
665 info
= CFDictionaryGetValue(dict
, CFSTR(kSCNetworkInterfaceInfo
));
666 if (!isA_CFDictionary(info
)) {
667 // if no SCNetworkInterface info
671 name
= CFDictionaryGetValue(info
, kSCPropUserDefinedName
);
672 if (!isA_CFString(name
) || !CFEqual(name
, CFSTR(BT_PAN_NAME
))) {
673 // if not BT-PAN interface
677 CFDictionaryAddValue(S_state
, kInterfaceNamerKey_BT_PAN_Name
, if_name
);
679 addr
= CFDictionaryGetValue(dict
, CFSTR(kIOMACAddress
));
680 if (isA_CFData(addr
)) {
681 CFDictionaryAddValue(S_state
, kInterfaceNamerKey_BT_PAN_Mac
, addr
);
686 #endif // TARGET_OS_OSX
688 static CFDictionaryRef
689 createInterfaceDict(SCNetworkInterfaceRef interface
, CFArrayRef matchingMACs
)
691 CFMutableDictionaryRef new_if
;
694 new_if
= CFDictionaryCreateMutable(NULL
,
696 &kCFTypeDictionaryKeyCallBacks
,
697 &kCFTypeDictionaryValueCallBacks
);
699 val
= _SCNetworkInterfaceCopyInterfaceInfo(interface
);
701 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceInfo
), val
);
705 val
= _SCNetworkInterfaceGetIOPath(interface
);
707 CFDictionarySetValue(new_if
, CFSTR(kIOPathMatchKey
), val
);
710 val
= _SCNetworkInterfaceGetIOInterfaceNamePrefix(interface
);
712 CFDictionarySetValue(new_if
, CFSTR(kIOInterfaceNamePrefix
), val
);
715 val
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
717 CFDictionarySetValue(new_if
, CFSTR(kIOInterfaceType
), val
);
720 val
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
722 CFDictionarySetValue(new_if
, CFSTR(kIOInterfaceUnit
), val
);
725 val
= _SCNetworkInterfaceGetHardwareAddress(interface
);
727 CFDictionarySetValue(new_if
, CFSTR(kIOMACAddress
), val
);
730 val
= SCNetworkInterfaceGetBSDName(interface
);
732 CFDictionarySetValue(new_if
, CFSTR(kIOBSDNameKey
), val
);
735 val
= SCNetworkInterfaceGetInterfaceType(interface
);
737 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceType
), val
);
740 CFDictionarySetValue(new_if
,
742 _SCNetworkInterfaceIsBuiltin(interface
) ? kCFBooleanTrue
: kCFBooleanFalse
);
744 if (_SCNetworkInterfaceIsHiddenConfiguration(interface
)) {
745 CFDictionarySetValue(new_if
, kSCNetworkInterfaceHiddenConfigurationKey
, kCFBooleanTrue
);
748 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceActive
), kCFBooleanTrue
);
750 if (matchingMACs
!= NULL
) {
751 CFDictionarySetValue(new_if
, CFSTR(kSCNetworkInterfaceMatchingMACs
), matchingMACs
);
757 static CFDictionaryRef
758 lookupInterfaceByAddress(CFArrayRef db_list
, SCNetworkInterfaceRef interface
, CFIndex
* where
)
764 if (db_list
== NULL
) {
767 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
768 addr
= _SCNetworkInterfaceGetHardwareAddress(interface
);
769 if (type
== NULL
|| addr
== NULL
) {
773 n
= CFArrayGetCount(db_list
);
774 for (CFIndex i
= 0; i
< n
; i
++) {
776 CFDictionaryRef dict
= CFArrayGetValueAtIndex(db_list
, i
);
779 t
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
780 a
= CFDictionaryGetValue(dict
, CFSTR(kIOMACAddress
));
781 if (t
== NULL
|| a
== NULL
)
784 if (CFEqual(type
, t
) && CFEqual(addr
, a
)) {
794 static CFDictionaryRef
795 lookupInterfaceByName(CFArrayRef db_list
, CFStringRef bsdName
, CFIndex
* where
)
799 if (db_list
== NULL
) {
803 n
= CFArrayGetCount(db_list
);
804 for (CFIndex i
= 0; i
< n
; i
++) {
805 CFDictionaryRef dict
= CFArrayGetValueAtIndex(db_list
, i
);
808 name
= CFDictionaryGetValue(dict
, CFSTR(kIOBSDNameKey
));
809 if (_SC_CFEqual(name
, bsdName
)) {
819 static CFDictionaryRef
820 lookupInterfaceByUnit(CFArrayRef db_list
, SCNetworkInterfaceRef interface
, CFIndex
* where
)
826 if (db_list
== NULL
) {
829 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
830 unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
831 if (type
== NULL
|| unit
== NULL
) {
835 n
= CFArrayGetCount(db_list
);
836 for (CFIndex i
= 0; i
< n
; i
++) {
837 CFDictionaryRef dict
= CFArrayGetValueAtIndex(db_list
, i
);
841 t
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
842 u
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceUnit
));
843 if (t
== NULL
|| u
== NULL
) {
847 if (CFEqual(type
, t
) && CFEqual(unit
, u
)) {
857 CFDictionaryRef match_info
;
858 CFStringRef match_type
;
859 CFBooleanRef match_builtin
;
860 CFMutableArrayRef matches
;
861 } matchContext
, *matchContextRef
;
863 static CF_RETURNS_RETAINED CFDictionaryRef
864 thinInterfaceInfo(CFDictionaryRef info
)
869 if (CFDictionaryGetValueIfPresent(info
, CFSTR(kUSBVendorID
), (const void **)&num
)
871 && CFNumberGetValue(num
, kCFNumberIntType
, &vid
)
872 && (vid
== kIOUSBAppleVendorID
)) {
873 CFMutableDictionaryRef thin
;
875 // if this is an Apple USB device than we trust that
876 // the non-localized name will be correct.
877 thin
= CFDictionaryCreateMutableCopy(NULL
, 0, info
);
878 CFDictionaryRemoveValue(thin
, CFSTR(kUSBProductString
));
879 CFDictionaryRemoveValue(thin
, CFSTR(kUSBVendorID
));
880 CFDictionaryRemoveValue(thin
, CFSTR(kUSBProductID
));
884 return CFRetain(info
);
888 matchInterfaceInfo(CFDictionaryRef known_info
, CFDictionaryRef match_info
)
892 match
= _SC_CFEqual(known_info
, match_info
);
894 isA_CFDictionary(known_info
) &&
895 isA_CFDictionary(match_info
)) {
897 // if not an exact match, try thinning
898 known_info
= thinInterfaceInfo(known_info
);
899 match_info
= thinInterfaceInfo(match_info
);
900 match
= _SC_CFEqual(known_info
, match_info
);
901 if (known_info
!= NULL
) CFRelease(known_info
);
902 if (match_info
!= NULL
) CFRelease(match_info
);
909 matchKnown(const void *value
, void *context
)
911 CFDictionaryRef known_dict
= (CFDictionaryRef
)value
;
912 matchContextRef match_context
= (matchContextRef
)context
;
914 // match interface type
916 CFStringRef known_type
;
918 known_type
= CFDictionaryGetValue(known_dict
, CFSTR(kSCNetworkInterfaceType
));
919 if (!_SC_CFEqual(known_type
, match_context
->match_type
)) {
924 // match SCNetworkInterfaceInfo
926 CFDictionaryRef known_info
;
928 known_info
= CFDictionaryGetValue(known_dict
, CFSTR(kSCNetworkInterfaceInfo
));
929 if (!matchInterfaceInfo(known_info
, match_context
->match_info
)) {
934 // if requested, match [non-]builtin
935 if (match_context
->match_builtin
!= NULL
) {
936 CFBooleanRef known_builtin
;
938 known_builtin
= CFDictionaryGetValue(known_dict
, CFSTR(kIOBuiltin
));
939 if (!isA_CFBoolean(known_builtin
)) {
940 known_builtin
= kCFBooleanFalse
;
942 if (!_SC_CFEqual(known_builtin
, match_context
->match_builtin
)) {
947 // if we have a match
948 if (match_context
->matches
== NULL
) {
949 match_context
->matches
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
951 CFArrayAppendValue(match_context
->matches
, known_dict
);
957 matchUnnamed(const void *value
, void *context
)
959 SCNetworkInterfaceRef known_if
= (SCNetworkInterfaceRef
)value
;
960 matchContextRef match_context
= (matchContextRef
)context
;
962 if (match_context
->matches
== NULL
) {
966 // match interface type
968 CFStringRef known_type
;
970 known_type
= SCNetworkInterfaceGetInterfaceType(known_if
);
971 if (!_SC_CFEqual(known_type
, match_context
->match_type
)) {
976 // match SCNetworkInterfaceInfo
978 CFDictionaryRef known_info
;
981 known_info
= _SCNetworkInterfaceCopyInterfaceInfo(known_if
);
982 match
= matchInterfaceInfo(known_info
, match_context
->match_info
);
983 if (known_info
!= NULL
) CFRelease(known_info
);
989 // if requested, match [non-]builtin
990 if (match_context
->match_builtin
!= NULL
) {
991 CFBooleanRef known_builtin
;
993 known_builtin
= _SCNetworkInterfaceIsBuiltin(known_if
) ? kCFBooleanTrue
995 if (!_SC_CFEqual(known_builtin
, match_context
->match_builtin
)) {
1000 // if we have a match
1001 CFRelease(match_context
->matches
);
1002 match_context
->matches
= NULL
;
1008 interfaceExists(CFStringRef prefix
, CFNumberRef unit
)
1010 Boolean found
= FALSE
;
1011 CFDictionaryRef match_dict
;
1012 CFStringRef match_keys
[2];
1013 CFTypeRef match_vals
[2];
1014 CFDictionaryRef matching
;
1018 io_registry_entry_t entry
= MACH_PORT_NULL
;
1019 io_iterator_t iterator
= MACH_PORT_NULL
;
1021 mach_port_t masterPort
= MACH_PORT_NULL
;
1023 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
1024 if (kr
!= KERN_SUCCESS
) {
1025 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
1029 // look for kIONetworkInterface with matching prefix and unit
1030 match_keys
[0] = CFSTR(kIOInterfaceNamePrefix
);
1031 match_vals
[0] = prefix
;
1032 match_keys
[1] = CFSTR(kIOInterfaceUnit
);
1033 match_vals
[1] = unit
;
1034 match_dict
= CFDictionaryCreate(NULL
,
1035 (const void **)match_keys
,
1036 (const void **)match_vals
,
1038 &kCFTypeDictionaryKeyCallBacks
,
1039 &kCFTypeDictionaryValueCallBacks
);
1041 match_keys
[0] = CFSTR(kIOProviderClassKey
);
1042 match_vals
[0] = CFSTR(kIONetworkInterfaceClass
);
1043 match_keys
[1] = CFSTR(kIOPropertyMatchKey
);
1044 match_vals
[1] = match_dict
;
1045 matching
= CFDictionaryCreate(NULL
,
1046 (const void **)match_keys
,
1047 (const void **)match_vals
,
1048 sizeof(match_keys
)/sizeof(match_keys
[0]),
1049 &kCFTypeDictionaryKeyCallBacks
,
1050 &kCFTypeDictionaryValueCallBacks
);
1051 CFRelease(match_dict
);
1053 // note: the "matching" dictionary will be consumed by the following
1054 kr
= IOServiceGetMatchingServices(masterPort
, matching
, &iterator
);
1055 if ((kr
!= kIOReturnSuccess
) || (iterator
== MACH_PORT_NULL
)) {
1060 entry
= IOIteratorNext(iterator
);
1061 if (entry
== MACH_PORT_NULL
) {
1069 if (masterPort
!= MACH_PORT_NULL
) {
1070 mach_port_deallocate(mach_task_self(), masterPort
);
1072 if (entry
!= MACH_PORT_NULL
) {
1073 IOObjectRelease(entry
);
1075 if (iterator
!= MACH_PORT_NULL
) {
1076 IOObjectRelease(iterator
);
1083 * lookupMatchingInterface
1085 * Looks at the interfaces that have already been [or need to be] named with
1086 * the goal of allowing a system using a single network interface/adaptor of
1087 * a given type (vendor, model, ...) to not care about the specific adaptor
1088 * that is used (i.e. swapping dongle's is OK). Once a system has had more
1089 * than one interface/adaptor connected at the same time than we assume that
1090 * the network configuration is being setup for multi-homing that should be
1093 * If no matches are found or if more than one match is found, return NULL.
1094 * If a single match is found, return the match.
1096 static CFDictionaryRef
1097 lookupMatchingInterface(SCNetworkInterfaceRef interface
,
1098 CFArrayRef db_list
, // already named
1099 CFArrayRef if_list
, // to be named
1100 CFIndex if_list_index
,
1101 CFBooleanRef builtin
)
1103 CFStringRef if_type
;
1104 CFDictionaryRef match
= NULL
;
1105 matchContext match_context
;
1107 if_type
= SCNetworkInterfaceGetInterfaceType(interface
);
1108 if (if_type
== NULL
) {
1112 match_context
.match_type
= if_type
;
1113 match_context
.match_info
= _SCNetworkInterfaceCopyInterfaceInfo(interface
);
1114 match_context
.match_builtin
= builtin
;
1115 match_context
.matches
= NULL
;
1117 // check for matches to interfaces that have already been named
1118 // ... and append each match that we find to match_context.matches
1119 if (db_list
!= NULL
) {
1120 CFArrayApplyFunction(db_list
,
1121 CFRangeMake(0, CFArrayGetCount(db_list
)),
1126 // check for matches to interfaces that will be named
1127 // ... and CFRelease match_context.matches if we find another network
1128 // interface of the same type that also needs to be named
1129 if (if_list
!= NULL
) {
1130 CFIndex if_list_count
;
1132 if_list_count
= CFArrayGetCount(if_list
);
1133 if (if_list_index
< if_list_count
) {
1134 CFArrayApplyFunction(if_list
,
1135 CFRangeMake(if_list_index
, if_list_count
- if_list_index
),
1141 // check if we have a single match
1142 if (match_context
.matches
!= NULL
) {
1143 if (CFArrayGetCount(match_context
.matches
) == 1) {
1144 match
= CFArrayGetValueAtIndex(match_context
.matches
, 0);
1146 CFRelease(match_context
.matches
);
1149 if (match
!= NULL
) {
1150 Boolean active
= TRUE
;
1153 name
= CFDictionaryGetValue(match
, CFSTR(kIOBSDNameKey
));
1154 if (isA_CFString(name
)) {
1158 prefix
= CFDictionaryGetValue(match
, CFSTR(kIOInterfaceNamePrefix
));
1159 unit
= CFDictionaryGetValue(match
, CFSTR(kIOInterfaceUnit
));
1160 if (isA_CFString(prefix
) && isA_CFNumber(unit
)) {
1161 if (!interfaceExists(prefix
, unit
)) {
1172 if (match_context
.match_info
!= NULL
) CFRelease(match_context
.match_info
);
1177 insertInterface(CFMutableArrayRef db_list
, SCNetworkInterfaceRef interface
, CFDictionaryRef db_dict_match
)
1180 CFDictionaryRef if_dict
;
1181 CFStringRef if_name
;
1182 CFNumberRef if_type
;
1183 CFNumberRef if_unit
;
1184 CFArrayRef matchingMACs
= NULL
;
1185 CFIndex n
= CFArrayGetCount(db_list
);
1186 CFComparisonResult res
;
1188 if_name
= SCNetworkInterfaceGetBSDName(interface
);
1189 if (if_name
!= NULL
) {
1190 addTimestamp(S_state
, if_name
);
1193 if (!_SCNetworkInterfaceIsBuiltin(interface
) && (db_dict_match
!= NULL
)) {
1197 matchingMACs
= CFDictionaryGetValue(db_dict_match
, CFSTR(kSCNetworkInterfaceMatchingMACs
));
1198 if (matchingMACs
!= NULL
) {
1199 CFRetain(matchingMACs
);
1202 addr_old
= CFDictionaryGetValue(db_dict_match
, CFSTR(kIOMACAddress
));
1203 addr_cur
= _SCNetworkInterfaceGetHardwareAddress(interface
);
1204 if ((addr_old
!= NULL
) && (addr_cur
!= NULL
) && !CFEqual(addr_old
, addr_cur
)) {
1205 CFMutableArrayRef matching_new
;
1207 // if MAC address changed, add previous MAC to history
1208 if (matchingMACs
!= NULL
) {
1209 matching_new
= CFArrayCreateMutableCopy(NULL
, 0, matchingMACs
);
1210 CFRelease(matchingMACs
);
1212 // remove duplicates of the now current MAC from history
1213 i
= CFArrayGetFirstIndexOfValue(matching_new
, CFRangeMake(0, CFArrayGetCount(matching_new
)), addr_cur
);
1214 if (i
!= kCFNotFound
) {
1215 CFArrayRemoveValueAtIndex(matching_new
, i
);
1218 // remove duplicates of the previous MAC from history before re-inserting
1219 i
= CFArrayGetFirstIndexOfValue(matching_new
, CFRangeMake(0, CFArrayGetCount(matching_new
)), addr_old
);
1220 if (i
!= kCFNotFound
) {
1221 CFArrayRemoveValueAtIndex(matching_new
, i
);
1224 matching_new
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1226 CFArrayInsertValueAtIndex(matching_new
, 0, addr_old
);
1228 // limit history size
1229 #define MATCHING_HISTORY_MAXLEN 32
1230 for (i
= CFArrayGetCount(matching_new
); i
> MATCHING_HISTORY_MAXLEN
; i
--) {
1231 CFArrayRemoveValueAtIndex(matching_new
, i
- 1);
1234 matchingMACs
= matching_new
;
1238 if_dict
= createInterfaceDict(interface
, matchingMACs
);
1239 if (matchingMACs
!= NULL
) {
1240 CFRelease(matchingMACs
);
1243 if_type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
1244 if_unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
1245 if ((if_type
== NULL
) || (if_unit
== NULL
)) {
1250 for (i
= 0; i
< n
; i
++) {
1251 CFNumberRef db_type
;
1252 CFNumberRef db_unit
;
1253 CFDictionaryRef dict
= CFArrayGetValueAtIndex(db_list
, i
);
1255 db_type
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
1256 db_unit
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceUnit
));
1257 res
= CFNumberCompare(if_type
, db_type
, NULL
);
1258 if (res
== kCFCompareLessThan
1259 || (res
== kCFCompareEqualTo
1260 && (CFNumberCompare(if_unit
, db_unit
, NULL
)
1261 == kCFCompareLessThan
))) {
1262 CFArrayInsertValueAtIndex(db_list
, i
, if_dict
);
1268 CFArrayAppendValue(S_dblist
, if_dict
);
1271 updateBTPANInformation(if_dict
, NULL
);
1272 #endif // TARGET_OS_OSX
1279 removeInterface(CFMutableArrayRef db_list
, SCNetworkInterfaceRef interface
, CFDictionaryRef
*matched
)
1281 CFDictionaryRef db_dict
;
1285 // remove any dict that has our type/addr
1287 db_dict
= lookupInterfaceByAddress(db_list
, interface
, &where
);
1288 if (db_dict
== NULL
) {
1291 if ((matched
!= NULL
) && (*matched
== NULL
)) {
1292 *matched
= CFRetain(db_dict
);
1294 CFArrayRemoveValueAtIndex(db_list
, where
);
1298 // remove any dict that has the same type/unit
1300 db_dict
= lookupInterfaceByUnit(db_list
, interface
, &where
);
1301 if (db_dict
== NULL
) {
1304 if ((matched
!= NULL
) && (*matched
== NULL
)) {
1305 *matched
= CFRetain(db_dict
);
1307 CFArrayRemoveValueAtIndex(db_list
, where
);
1312 SC_log(LOG_ERR
, "Multiple interfaces removed from database (n = %d, %@)", n
, interface
);
1319 replaceInterface(SCNetworkInterfaceRef interface
)
1321 CFDictionaryRef matched
= NULL
;
1323 if (S_dblist
== NULL
) {
1324 S_dblist
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1326 // remove any matching interfaces
1327 removeInterface(S_dblist
, interface
, &matched
);
1330 // [re-]insert the new interface
1331 insertInterface(S_dblist
, interface
, matched
);
1333 if (matched
!= NULL
) {
1341 getNextUnitForType(CFNumberRef if_type
, int requested
)
1345 if (S_dblist
== NULL
) {
1349 n
= CFArrayGetCount(S_dblist
);
1350 for (CFIndex i
= 0; i
< n
; i
++) {
1351 CFDictionaryRef dict
= CFArrayGetValueAtIndex(S_dblist
, i
);
1354 type
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceType
));
1355 if (CFEqual(type
, if_type
)) {
1359 unit
= CFDictionaryGetValue(dict
, CFSTR(kIOInterfaceUnit
));
1360 if (!isA_CFNumber(unit
) ||
1361 !CFNumberGetValue(unit
, kCFNumberIntType
, &u
)) {
1365 if (u
< requested
) {
1366 // if we have not yet found our starting unit #
1370 if (u
== requested
) {
1371 // our starting (or now proposed) unit # is "in use" so
1372 // let's keep searching
1377 // we've found a unit # gap ... so let's re-assign it!
1385 * Function: ensureInterfaceHasUnit
1387 * Ensure that the SCNetworkInterfaceRef has a unit number. If it doesn't,
1388 * release the interface and return NULL.
1390 static SCNetworkInterfaceRef
1391 ensureInterfaceHasUnit(SCNetworkInterfaceRef net_if
)
1394 && _SCNetworkInterfaceGetIOInterfaceUnit(net_if
) == NULL
) {
1401 #ifdef USE_REGISTRY_ENTRY_ID
1402 static kern_return_t
1403 registerInterfaceWithIORegistryEntryID(io_connect_t connect
,
1409 CFMutableDictionaryRef dict
;
1413 dict
= CFDictionaryCreateMutable(NULL
, 0,
1414 &kCFTypeDictionaryKeyCallBacks
,
1415 &kCFTypeDictionaryValueCallBacks
);
1416 num
= CFNumberCreate(NULL
, kCFNumberIntType
, &command
);
1417 CFDictionarySetValue(dict
, CFSTR(kIONetworkStackUserCommandKey
), num
);
1419 data
= CFDataCreate(NULL
, (void *) &entryID
, sizeof(entryID
));
1420 CFDictionarySetValue(dict
, CFSTR(kIORegistryEntryIDKey
), data
);
1422 CFDictionarySetValue(dict
, CFSTR(kIOInterfaceUnit
), unit
);
1423 kr
= IOConnectSetCFProperties(connect
, dict
);
1428 static SCNetworkInterfaceRef
1429 copyInterfaceForIORegistryEntryID(uint64_t entryID
)
1431 io_registry_entry_t entry
= MACH_PORT_NULL
;
1432 SCNetworkInterfaceRef interface
= NULL
;
1433 io_iterator_t iterator
= MACH_PORT_NULL
;
1435 mach_port_t masterPort
= MACH_PORT_NULL
;
1437 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
1438 if (kr
!= KERN_SUCCESS
) {
1439 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
1443 kr
= IOServiceGetMatchingServices(masterPort
,
1444 IORegistryEntryIDMatching(entryID
),
1446 if ((kr
!= KERN_SUCCESS
) || (iterator
== MACH_PORT_NULL
)) {
1447 SC_log(LOG_NOTICE
, "IOServiceGetMatchingServices(0x%llx) returned 0x%x/%d",
1454 entry
= IOIteratorNext(iterator
);
1455 if (entry
== MACH_PORT_NULL
) {
1456 SC_log(LOG_NOTICE
, "IORegistryEntryIDMatching(0x%llx) failed", entryID
);
1460 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(entry
);
1463 if (masterPort
!= MACH_PORT_NULL
) {
1464 mach_port_deallocate(mach_task_self(), masterPort
);
1466 if (entry
!= MACH_PORT_NULL
) {
1467 IOObjectRelease(entry
);
1469 if (iterator
!= MACH_PORT_NULL
) {
1470 IOObjectRelease(iterator
);
1475 static SCNetworkInterfaceRef
1476 copyNamedInterfaceForIORegistryEntryID(uint64_t entryID
)
1478 SCNetworkInterfaceRef net_if
;
1480 net_if
= copyInterfaceForIORegistryEntryID(entryID
);
1481 return (ensureInterfaceHasUnit(net_if
));
1484 #else // USE_REGISTRY_ENTRY_ID
1486 * Function: registerInterface
1488 * Register a single interface with the given service path to the
1489 * data link layer (BSD), using the specified unit number.
1491 static kern_return_t
1492 registerInterfaceWithIOServicePath(io_connect_t connect
,
1497 CFMutableDictionaryRef dict
;
1501 dict
= CFDictionaryCreateMutable(NULL
, 0,
1502 &kCFTypeDictionaryKeyCallBacks
,
1503 &kCFTypeDictionaryValueCallBacks
);
1504 num
= CFNumberCreate(NULL
, kCFNumberIntType
, &command
);
1505 CFDictionarySetValue(dict
, CFSTR(kIONetworkStackUserCommandKey
), num
);
1507 CFDictionarySetValue(dict
, CFSTR(kIOPathMatchKey
), path
);
1508 CFDictionarySetValue(dict
, CFSTR(kIOInterfaceUnit
), unit
);
1509 kr
= IOConnectSetCFProperties(connect
, dict
);
1514 static SCNetworkInterfaceRef
1515 copyInterfaceForIOKitPath(CFStringRef if_path
)
1517 io_registry_entry_t entry
= MACH_PORT_NULL
;
1518 SCNetworkInterfaceRef interface
= NULL
;
1520 mach_port_t masterPort
= MACH_PORT_NULL
;
1523 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
1524 if (kr
!= KERN_SUCCESS
) {
1525 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
1528 _SC_cfstring_to_cstring(if_path
, path
, sizeof(path
), kCFStringEncodingASCII
);
1529 entry
= IORegistryEntryFromPath(masterPort
, path
);
1530 if (entry
== MACH_PORT_NULL
) {
1531 SC_log(LOG_NOTICE
, "IORegistryEntryFromPath(%@) failed", if_path
);
1535 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(entry
);
1538 if (masterPort
!= MACH_PORT_NULL
) {
1539 mach_port_deallocate(mach_task_self(), masterPort
);
1541 if (entry
!= MACH_PORT_NULL
) {
1542 IOObjectRelease(entry
);
1548 static SCNetworkInterfaceRef
1549 copyNamedInterfaceForIOKitPath(CFStringRef if_path
)
1551 SCNetworkInterfaceRef net_if
;
1553 net_if
= copyInterfaceForIOKitPath(if_path
);
1554 return (ensureInterfaceHasUnit(net_if
));
1557 #endif // USE_REGISTRY_ENTRY_ID
1560 displayInterface(SCNetworkInterfaceRef interface
)
1567 name
= SCNetworkInterfaceGetBSDName(interface
);
1568 unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
1569 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
1570 addr
= SCNetworkInterfaceGetHardwareAddressString(interface
);
1572 SC_log(LOG_INFO
, " %s%@%sType: %@, %s%@%sMAC address: %@",
1573 (name
!= NULL
) ? "BSD Name: " : "",
1574 (name
!= NULL
) ? name
: CFSTR(""),
1575 (name
!= NULL
) ? ", " : "",
1577 (unit
!= NULL
) ? "Unit: " : "",
1578 (unit
!= NULL
) ? (CFTypeRef
)unit
: (CFTypeRef
)CFSTR(""),
1579 (unit
!= NULL
) ? ", " : "",
1580 (addr
!= NULL
) ? addr
: CFSTR("?"));
1584 builtinAvailable(SCNetworkInterfaceRef interface
, // new interface
1585 CFNumberRef if_unit
) // desired unit
1588 CFNumberRef if_type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
1591 n
= (S_dblist
!= NULL
) ? CFArrayGetCount(S_dblist
) : 0;
1592 for (i
= 0; i
< n
; i
++) {
1593 CFStringRef if_path
;
1594 CFDictionaryRef known_dict
= CFArrayGetValueAtIndex(S_dblist
, i
);
1595 CFStringRef known_path
;
1596 CFNumberRef known_type
;
1597 CFNumberRef known_unit
;
1599 known_type
= CFDictionaryGetValue(known_dict
, CFSTR(kIOInterfaceType
));
1600 if (!_SC_CFEqual(if_type
, known_type
)) {
1601 continue; // if not the same interface type
1604 known_unit
= CFDictionaryGetValue(known_dict
, CFSTR(kIOInterfaceUnit
));
1605 if (!_SC_CFEqual(if_unit
, known_unit
)) {
1606 continue; // if not the same interface unit
1609 if_path
= _SCNetworkInterfaceGetIOPath(interface
);
1610 known_path
= CFDictionaryGetValue(known_dict
, CFSTR(kIOPathMatchKey
));
1611 if (!_SC_CFEqual(if_path
, known_path
)) {
1612 // if different IORegistry path
1616 // if same type, same unit, same path
1620 // if interface type/unit not found
1625 builtinCount(CFArrayRef if_list
, CFIndex last
, CFNumberRef if_type
)
1630 for (i
= 0; i
< last
; i
++) {
1631 SCNetworkInterfaceRef builtin_if
;
1632 CFNumberRef builtin_type
;
1634 builtin_if
= CFArrayGetValueAtIndex(if_list
, i
);
1635 builtin_type
= _SCNetworkInterfaceGetIOInterfaceType(builtin_if
);
1636 if (CFEqual(if_type
, builtin_type
)) {
1637 if (_SCNetworkInterfaceIsBuiltin(builtin_if
)) {
1638 n
++; // if built-in interface
1648 #pragma mark Interface monitoring (e.g. watch for "detach")
1651 typedef struct WatchedInfo
*WatchedInfoRef
;
1653 typedef void (*InterfaceUpdateCallBack
) (
1655 natural_t messageType
,
1656 void *messageArgument
1660 SCNetworkInterfaceRef interface
;
1661 io_service_t interface_node
;
1662 io_object_t notification
;
1663 InterfaceUpdateCallBack callback
;
1667 watcherRelease(CFDataRef watched
);
1670 updateWatchedInterface(void *refCon
, io_service_t service
, natural_t messageType
, void *messageArgument
)
1672 #pragma unused(service)
1673 #pragma unused(messageArgument)
1674 switch (messageType
) {
1675 case kIOMessageServiceIsTerminated
: { // if [watched] interface yanked
1676 SCNetworkInterfaceRef remove
= NULL
;
1677 CFDataRef watched
= (CFDataRef
)refCon
;
1678 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1680 remove
= watchedInfo
->interface
;
1681 if (!_SCNetworkInterfaceIsBuiltin(remove
) &&
1682 _SCNetworkInterfaceIsApplePreconfigured(remove
)) {
1683 // if not built-in *and* pre-configured, retain for cleanup
1690 watchedInfo
->callback(watched
, messageType
, messageArgument
);
1691 watcherRelease(watched
);
1694 if (remove
!= NULL
) {
1695 // if interface is not built-in *and* pre-configured
1696 SC_log(LOG_INFO
, "Interface released unit %@ (from database)",
1697 _SCNetworkInterfaceGetIOInterfaceUnit(remove
));
1698 removeInterface(S_dblist
, remove
, NULL
);
1701 // update the DB with the [remaining] interfaces that have been named
1702 writeInterfaceList(S_dblist
);
1716 watcherCreate(SCNetworkInterfaceRef interface
, InterfaceUpdateCallBack callback
)
1719 io_service_t interface_node
;
1721 CFDictionaryRef matching
;
1722 CFMutableDataRef watched
;
1723 WatchedInfo
*watchedInfo
;
1725 // get the IORegistry node
1726 entryID
= _SCNetworkInterfaceGetIORegistryEntryID(interface
);
1727 matching
= IORegistryEntryIDMatching(entryID
);
1728 interface_node
= IOServiceGetMatchingService(kIOMasterPortDefault
, matching
);
1729 if (interface_node
== MACH_PORT_NULL
) {
1730 // interface no longer present
1734 // create [locked/trusted] interface watcher
1735 watched
= CFDataCreateMutable(NULL
, sizeof(WatchedInfo
));
1736 CFDataSetLength(watched
, sizeof(WatchedInfo
));
1737 watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1738 memset(watchedInfo
, 0, sizeof(*watchedInfo
));
1741 watchedInfo
->interface
= CFRetain(interface
);
1743 // ... and the interface node
1744 watchedInfo
->interface_node
= interface_node
;
1746 // ... and set the callback
1747 watchedInfo
->callback
= callback
;
1749 kr
= IOServiceAddInterestNotification(S_notify
, // IONotificationPortRef
1750 watchedInfo
->interface_node
, // io_service_t
1751 kIOGeneralInterest
, // interestType
1752 updateWatchedInterface
, // IOServiceInterestCallback
1753 (void *)watched
, // refCon
1754 &watchedInfo
->notification
); // notification
1755 if (kr
!= KERN_SUCCESS
) {
1757 "IOServiceAddInterestNotification() failed, kr = 0x%x",
1759 watcherRelease(watched
);
1768 watcherRelease(CFDataRef watched
)
1770 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1773 if (watchedInfo
->notification
!= IO_OBJECT_NULL
) {
1774 IOObjectRelease(watchedInfo
->notification
);
1775 watchedInfo
->notification
= IO_OBJECT_NULL
;
1778 // release interface node
1779 if (watchedInfo
->interface_node
!= IO_OBJECT_NULL
) {
1780 IOObjectRelease(watchedInfo
->interface_node
);
1781 watchedInfo
->interface_node
= IO_OBJECT_NULL
;
1784 // release interface
1785 if (watchedInfo
->interface
!= NULL
) {
1786 CFRelease(watchedInfo
->interface
);
1787 watchedInfo
->interface
= NULL
;
1794 isWatchedInterface(CFArrayRef watchedInterfaces
, SCNetworkInterfaceRef interface
)
1798 n
= (watchedInterfaces
!= NULL
) ? CFArrayGetCount(watchedInterfaces
) : 0;
1799 for (CFIndex i
= 0; i
< n
; i
++) {
1800 CFDataRef watched
= CFArrayGetValueAtIndex(watchedInterfaces
, i
);
1801 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1803 if (CFEqual((watchedInfo
->interface
), interface
)) {
1813 #pragma mark Locked device support [macOS]
1816 #if !TARGET_OS_IPHONE
1822 n
= (S_locked
!= NULL
) ? CFArrayGetCount(S_locked
) : 0;
1824 CFMutableArrayRef locked
;
1826 locked
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
1828 for (CFIndex i
= 0; i
< n
; i
++) {
1833 CFDataRef watched
= CFArrayGetValueAtIndex(S_locked
, i
);
1834 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1836 name
= SCNetworkInterfaceGetLocalizedDisplayName(watchedInfo
->interface
);
1837 addr
= SCNetworkInterfaceGetHardwareAddressString(watchedInfo
->interface
);
1838 path
= _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
);
1839 str
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("%@: %@: %@"),
1840 (name
!= NULL
) ? name
: CFSTR("?"),
1841 (addr
!= NULL
) ? addr
: CFSTR("?"),
1843 CFArrayAppendValue(locked
, str
);
1847 CFDictionarySetValue(S_state
, kInterfaceNamerKey_LockedInterfaces
, locked
);
1850 CFDictionaryRemoveValue(S_state
, kInterfaceNamerKey_LockedInterfaces
);
1859 blockNewInterfaces()
1861 static boolean_t allow
= TRUE
;
1862 static dispatch_once_t once
;
1864 dispatch_once(&once
, ^{
1865 allow
= InterfaceNamerControlPrefsAllowNewInterfaces();
1874 CFArrayRef console_sessions
;
1875 boolean_t locked
= FALSE
;
1876 io_registry_entry_t root
;
1878 root
= IORegistryGetRootEntry(kIOMasterPortDefault
);
1879 console_sessions
= IORegistryEntryCreateCFProperty(root
,
1880 CFSTR(kIOConsoleUsersKey
),
1883 if (isA_CFArray(console_sessions
)) {
1886 n
= CFArrayGetCount(console_sessions
);
1887 for (CFIndex i
= 0; i
< n
; i
++) {
1888 CFBooleanRef isLocked
;
1889 CFBooleanRef isLoginDone
;
1890 CFBooleanRef onConsole
;
1891 CFDictionaryRef session
;
1893 session
= CFArrayGetValueAtIndex(console_sessions
, i
);
1894 if (!isA_CFDictionary(session
)) {
1895 // if not dictionary
1899 if (!CFDictionaryGetValueIfPresent(session
,
1900 CFSTR(kIOConsoleSessionOnConsoleKey
),
1901 (const void **)&onConsole
) ||
1902 !isA_CFBoolean(onConsole
) ||
1903 !CFBooleanGetValue(onConsole
)) {
1904 // if not "on console" session
1909 CFDictionaryGetValueIfPresent(session
,
1910 CFSTR(kIOConsoleSessionLoginDoneKey
),
1911 (const void **)&isLoginDone
) &&
1912 isA_CFBoolean(isLoginDone
) &&
1913 !CFBooleanGetValue(isLoginDone
)) {
1915 SC_log(LOG_INFO
, "multiple sessions, console @ loginwindow");
1920 if (CFDictionaryGetValueIfPresent(session
,
1921 CFSTR(kIOConsoleSessionScreenIsLockedKey
),
1922 (const void **)&isLocked
) &&
1923 isA_CFBoolean(isLocked
) &&
1924 CFBooleanGetValue(isLocked
)) {
1926 SC_log(LOG_INFO
, "console screen locked");
1933 SC_log(LOG_INFO
, "console not locked");
1937 if (console_sessions
!= NULL
) {
1938 CFRelease(console_sessions
);
1940 IOObjectRelease(root
);
1945 //#define ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
1946 #ifdef ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
1948 static CFUserNotificationRef userNotification
;
1949 static CFRunLoopSourceRef userRls
;
1952 lockedNotification_remove(void)
1954 if (userRls
!= NULL
) {
1955 CFRunLoopSourceInvalidate(userRls
);
1959 if (userNotification
!= NULL
) {
1962 status
= CFUserNotificationCancel(userNotification
);
1965 "CFUserNotificationCancel() failed, status=%d",
1968 CFRelease(userNotification
);
1969 userNotification
= NULL
;
1975 #define MY_ICON_PATH "/System/Library/PreferencePanes/Network.prefPane/Contents/Resources/Network.icns"
1978 lockedNotification_reply(CFUserNotificationRef userNotification
, CFOptionFlags response_flags
)
1980 #pragma unused(userNotification)
1984 n
= (S_locked
!= NULL
) ? CFArrayGetCount(S_locked
) : 0;
1985 for (CFIndex i
= 0; i
< n
; i
++) {
1986 CFDataRef watched
= CFArrayGetValueAtIndex(S_locked
, i
);
1987 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
1989 // process user response
1990 switch (response_flags
& 0x3) {
1991 case kCFUserNotificationDefaultResponse
: {
1992 // if OK'd, [re-]process new interfaces
1994 SC_log(LOG_INFO
, "Reprocessing %ld [locked] interface%s", n
, n
== 1 ? "" : "s");
1996 if (S_iflist
== NULL
) {
1997 S_iflist
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2001 // add the interface to those newly discovered
2002 CFArrayAppendValue(S_iflist
, watchedInfo
->interface
);
2006 // if cancelled, ignore [remaining] new interfaces
2007 SC_log(LOG_INFO
, "[locked] interface ignored");
2008 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
));
2014 watcherRelease(watched
);
2017 if (S_locked
!= NULL
) {
2018 CFRelease(S_locked
);
2022 lockedNotification_remove();
2024 if (S_iflist
!= NULL
) {
2032 lockedNotification_add(void)
2035 CFMutableDictionaryRef dict
;
2037 CFMutableArrayRef message
;
2039 CFURLRef url
= NULL
;
2041 n
= (S_locked
!= NULL
) ? CFArrayGetCount(S_locked
) : 0;
2043 // no locked interfaces, no notification needed
2047 dict
= CFDictionaryCreateMutable(NULL
,
2049 &kCFTypeDictionaryKeyCallBacks
,
2050 &kCFTypeDictionaryValueCallBacks
);
2052 // set localization URL
2053 bundle
= _SC_CFBundleGet();
2054 if (bundle
!= NULL
) {
2055 url
= CFBundleCopyBundleURL(bundle
);
2059 CFDictionarySetValue(dict
, kCFUserNotificationLocalizationURLKey
, url
);
2062 SC_log(LOG_ERR
, "can't find bundle");
2067 url
= CFURLCreateFromFileSystemRepresentation(NULL
,
2068 (const UInt8
*)MY_ICON_PATH
,
2069 sizeof(MY_ICON_PATH
) - 1,
2072 CFDictionarySetValue(dict
, kCFUserNotificationIconURLKey
, url
);
2077 CFDictionarySetValue(dict
,
2078 kCFUserNotificationAlertHeaderKey
,
2079 (n
== 1) ? CFSTR("LOCKED_SINGLE_INTERFACE_HEADER")
2080 : CFSTR("LOCKED_MULTIPLE_INTERFACES_HEADER"));
2083 message
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2084 CFArrayAppendValue(message
,
2085 (n
== 1) ? CFSTR("LOCKED_SINGLE_INTERFACE_MESSAGE")
2086 : CFSTR("LOCKED_MULTIPLE_INTERFACES_MESSAGE"));
2087 for (CFIndex i
= 0; i
< n
; i
++) {
2090 CFDataRef watched
= CFArrayGetValueAtIndex(S_locked
, i
);
2091 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2093 name
= SCNetworkInterfaceGetLocalizedDisplayName(watchedInfo
->interface
);
2094 str
= CFStringCreateWithFormat(NULL
, NULL
, CFSTR("\r\t%@"), name
);
2095 CFArrayAppendValue(message
, str
);
2098 CFDictionarySetValue(dict
, kCFUserNotificationAlertMessageKey
, message
);
2102 CFDictionarySetValue(dict
,
2103 kCFUserNotificationDefaultButtonTitleKey
,
2104 CFSTR("LOCKED_INTERFACES_IGNORE"));
2105 CFDictionarySetValue(dict
,
2106 kCFUserNotificationAlternateButtonTitleKey
,
2107 (n
== 1) ? CFSTR("LOCKED_SINGLE_INTERFACE_ADD")
2108 : CFSTR("LOCKED_MULTIPLE_INTERFACES_ADD"));
2110 // create and post notification
2111 userNotification
= CFUserNotificationCreate(NULL
,
2113 kCFUserNotificationNoteAlertLevel
,
2116 if (userNotification
== NULL
) {
2117 SC_log(LOG_ERR
, "CFUserNotificationCreate() failed: %d", (int)error
);
2121 // establish callback
2122 userRls
= CFUserNotificationCreateRunLoopSource(NULL
,
2124 lockedNotification_reply
,
2126 if (userRls
== NULL
) {
2127 SC_log(LOG_ERR
, "CFUserNotificationCreateRunLoopSource() failed");
2128 CFRelease(userNotification
);
2129 userNotification
= NULL
;
2132 CFRunLoopAddSource(CFRunLoopGetCurrent(), userRls
, kCFRunLoopDefaultMode
);
2136 if (dict
!= NULL
) CFRelease(dict
);
2141 lockedNotification_update(void)
2143 // if present, remove current notification
2144 lockedNotification_remove();
2146 // post notification (if needed)
2147 lockedNotification_add();
2152 #endif // ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2155 lockedInterfaceUpdated(CFDataRef watched
, natural_t messageType
, void *messageArgument
)
2157 #pragma unused(messageArgument)
2158 Boolean updated
= FALSE
;
2159 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2161 switch (messageType
) {
2162 case kIOMessageServiceIsTerminated
: { // if [locked] interface yanked
2163 SC_log(LOG_INFO
, "[locked] interface removed");
2164 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
));
2166 if (S_locked
!= NULL
) {
2168 CFIndex n
= CFArrayGetCount(S_locked
);
2170 i
= CFArrayGetFirstIndexOfValue(S_locked
, CFRangeMake(0, n
), watched
);
2171 if (i
!= kCFNotFound
) {
2172 CFArrayRemoveValueAtIndex(S_locked
, i
);
2173 if (CFArrayGetCount(S_locked
) == 0) {
2174 CFRelease(S_locked
);
2189 #ifdef ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2190 // update user notification after interface removed
2191 lockedNotification_update();
2192 #endif // ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2194 // post info about interfaces not added because the console is locked
2202 watchLockedInterface(SCNetworkInterfaceRef interface
)
2204 Boolean updated
= FALSE
;
2207 watched
= watcherCreate(interface
, lockedInterfaceUpdated
);
2208 if (watched
!= NULL
) {
2209 SC_log(LOG_INFO
, "watching [locked] interface");
2210 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(interface
));
2212 if (S_locked
== NULL
) {
2213 S_locked
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2215 CFArrayAppendValue(S_locked
, watched
);
2220 // post info about interfaces not added because the console is locked
2223 #ifdef ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2224 // post/update user notification with new interface
2225 lockedNotification_update();
2226 #endif // ENABLE_LOCKED_CONSOLE_INTERFACE_NOTIFICATIONS
2231 #endif // !TARGET_OS_IPHONE
2235 #pragma mark Trust required support [iOS]
2238 #if TARGET_OS_IPHONE
2240 #include <SoftLinking/WeakLinking.h>
2241 WEAK_LINK_FORCE_IMPORT(lockdown_is_host_trusted
);
2242 WEAK_LINK_FORCE_IMPORT(kLockdownNotificationHostAttached
);
2243 WEAK_LINK_FORCE_IMPORT(kLockdownNotificationHostDetached
);
2244 WEAK_LINK_FORCE_IMPORT(kLockdownNotificationTrustedHostAttached
);
2245 WEAK_LINK_FORCE_IMPORT(kLockdownNotificationTrustedPTPAttached
);
2250 Boolean haveLibrary
;
2252 haveLibrary
= ((lockdown_is_host_trusted
!= NULL
) &&
2253 (&kLockdownNotificationHostAttached
!= NULL
) &&
2254 (&kLockdownNotificationHostDetached
!= NULL
) &&
2255 (&kLockdownNotificationTrustedHostAttached
!= NULL
) &&
2256 (&kLockdownNotificationTrustedPTPAttached
!= NULL
)
2266 n
= (S_trustRequired
!= NULL
) ? CFArrayGetCount(S_trustRequired
) : 0;
2267 if ((n
> 0) && !S_trustedHostAttached
) {
2268 CFMutableArrayRef excluded
;
2270 // if we have interfaces that require not [yet] granted "trust".
2272 excluded
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2274 for (CFIndex i
= 0; i
< n
; i
++) {
2275 CFStringRef bsdName
;
2276 CFDataRef watched
= CFArrayGetValueAtIndex(S_trustRequired
, i
);
2277 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2279 bsdName
= SCNetworkInterfaceGetBSDName(watchedInfo
->interface
);
2280 if (bsdName
== NULL
) {
2281 SC_log(LOG_NOTICE
, "[trust required] interface w/no BSD name not excluded");
2282 SC_log(LOG_NOTICE
, " interface = %@", watchedInfo
->interface
);
2285 CFArrayAppendValue(excluded
, bsdName
);
2288 CFDictionarySetValue(S_state
, kInterfaceNamerKey_ExcludedInterfaces
, excluded
);
2289 CFRelease(excluded
);
2291 CFDictionaryRemoveValue(S_state
, kInterfaceNamerKey_ExcludedInterfaces
);
2299 static dispatch_queue_t
2300 trustRequired_queue()
2302 static dispatch_once_t once
;
2303 static dispatch_queue_t q
;
2305 dispatch_once(&once
, ^{
2306 q
= dispatch_queue_create("Trust Required queue", NULL
);
2313 // runs on "Trust Required" dispatch queue
2315 trustRequiredNotification_update(CFRunLoopRef rl
, CFStringRef reason
)
2317 Boolean changed
= FALSE
;
2318 CFStringRef error
= NULL
;
2323 * determine whether the device has "trusted" the host (or other device)
2325 trusted
= lockdown_is_host_trusted(MY_PLUGIN_ID
, NULL
, &error
);
2326 n
= (S_trustRequired
!= NULL
) ? CFArrayGetCount(S_trustRequired
) : 0;
2327 if ((S_trustedHostCount
!= n
) || (S_trustedHostAttached
!= trusted
)) {
2331 SC_log(LOG_INFO
, "%@, trusted = %s%s%@, %ld interface%s)%s",
2333 trusted
? "Yes" : "No",
2334 (error
!= NULL
) ? ", error = " : "",
2335 (error
!= NULL
) ? error
: CFSTR(""),
2337 (n
== 1) ? "" : "s",
2338 changed
? " *" : "");
2341 S_trustedHostAttached
= trusted
;
2342 S_trustedHostCount
= n
;
2343 CFRunLoopPerformBlock(rl
, kCFRunLoopDefaultMode
, ^{
2346 CFRunLoopWakeUp(rl
);
2349 if (error
!= NULL
) {
2357 trustRequiredInterfaceUpdated(CFDataRef watched
, natural_t messageType
, void *messageArgument
)
2359 #pragma unused(messageArgument)
2360 Boolean updated
= FALSE
;
2361 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2363 switch (messageType
) {
2364 case kIOMessageServiceIsTerminated
: { // if [locked] interface yanked
2365 SC_log(LOG_INFO
, "[trust required] interface removed");
2366 SC_log(LOG_INFO
, " path = %@", _SCNetworkInterfaceGetIOPath(watchedInfo
->interface
));
2368 if (S_trustRequired
!= NULL
) {
2370 CFIndex n
= CFArrayGetCount(S_trustRequired
);
2372 i
= CFArrayGetFirstIndexOfValue(S_trustRequired
, CFRangeMake(0, n
), watched
);
2373 if (i
!= kCFNotFound
) {
2374 CFArrayRemoveValueAtIndex(S_trustRequired
, i
);
2375 if (CFArrayGetCount(S_trustRequired
) == 0) {
2376 CFRelease(S_trustRequired
);
2377 S_trustRequired
= NULL
;
2391 CFRunLoopRef rl
= CFRunLoopGetCurrent();
2394 dispatch_async(trustRequired_queue(), ^{
2395 trustRequiredNotification_update(rl
, CFSTR("TrustRequired interface removed"));
2404 watchTrustedStatus(CFStringRef notification
, CFStringRef reason
)
2407 int notify_token
= -1;
2409 CFRunLoopRef rl
= CFRunLoopGetCurrent();
2411 key
= CFStringGetCStringPtr(notification
, kCFStringEncodingUTF8
);
2412 assert(key
!= NULL
);
2416 ret
= notify_register_dispatch(key
,
2418 trustRequired_queue(),
2420 #pragma unused(token)
2421 trustRequiredNotification_update(rl
, reason
);
2423 if (ret
!= NOTIFY_STATUS_OK
) {
2424 SC_log(LOG_ERR
, "notify_register_dispatch(%@) failed: %u", notification
, ret
);
2433 updateTrustRequiredInterfaces(CFArrayRef interfaces
)
2436 Boolean updated
= FALSE
;
2438 n
= (interfaces
!= NULL
) ? CFArrayGetCount(interfaces
) : 0;
2439 for (CFIndex i
= 0; i
< n
; i
++) {
2440 SCNetworkInterfaceRef interface
;
2442 interface
= CFArrayGetValueAtIndex(interfaces
, i
);
2443 if (_SCNetworkInterfaceIsTrustRequired(interface
) &&
2444 !isWatchedInterface(S_trustRequired
, interface
)) {
2447 watched
= watcherCreate(interface
, trustRequiredInterfaceUpdated
);
2448 if (watched
!= NULL
) {
2449 CFStringRef bsdName
;
2451 bsdName
= SCNetworkInterfaceGetBSDName(interface
);
2452 if (bsdName
!= NULL
) {
2453 SC_log(LOG_INFO
, "watching [trust required] interface: %@", bsdName
);
2455 SC_log(LOG_INFO
, "watching [trust required] interface w/no BSD name");
2456 SC_log(LOG_INFO
, " interface = %@", interface
);
2459 if (S_trustRequired
== NULL
) {
2460 S_trustRequired
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2462 CFArrayAppendValue(S_trustRequired
, watched
);
2469 static dispatch_once_t once
;
2470 CFRunLoopRef rl
= CFRunLoopGetCurrent();
2472 dispatch_once(&once
, ^{
2473 // watch for "Host attached"
2474 watchTrustedStatus(kLockdownNotificationHostAttached
,
2475 CFSTR("Host attached"));
2477 // watch for "Host detached"
2478 watchTrustedStatus(kLockdownNotificationHostDetached
,
2479 CFSTR("Host detached"));
2481 // watch for "Trusted host attached"
2482 watchTrustedStatus(kLockdownNotificationTrustedHostAttached
,
2483 CFSTR("Trusted Host attached"));
2485 // watch for "Trusted PDP attached"
2486 watchTrustedStatus(kLockdownNotificationTrustedPTPAttached
,
2487 CFSTR("Trusted PTP attached"));
2491 dispatch_async(trustRequired_queue(), ^{
2492 trustRequiredNotification_update(rl
, CFSTR("TrustRequired interface added"));
2499 #endif // TARGET_OS_IPHONE
2503 #pragma mark Pre-configured interface support
2507 sharePreconfigured()
2511 n
= (S_preconfigured
!= NULL
) ? CFArrayGetCount(S_preconfigured
) : 0;
2513 CFMutableArrayRef preconfigured
;
2515 preconfigured
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2517 for (CFIndex i
= 0; i
< n
; i
++) {
2518 CFStringRef bsdName
;
2519 CFDataRef watched
= CFArrayGetValueAtIndex(S_preconfigured
, i
);
2520 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2522 bsdName
= SCNetworkInterfaceGetBSDName(watchedInfo
->interface
);
2523 if (bsdName
== NULL
) {
2524 SC_log(LOG_NOTICE
, "pre-configured interface w/no BSD name");
2525 SC_log(LOG_NOTICE
, " interface = %@", watchedInfo
->interface
);
2528 CFArrayAppendValue(preconfigured
, bsdName
);
2531 CFDictionarySetValue(S_state
, kInterfaceNamerKey_PreConfiguredInterfaces
, preconfigured
);
2532 CFRelease(preconfigured
);
2534 CFDictionaryRemoveValue(S_state
, kInterfaceNamerKey_PreConfiguredInterfaces
);
2543 preconfiguredInterfaceUpdated(CFDataRef watched
, natural_t messageType
, void *messageArgument
)
2545 Boolean updated
= FALSE
;
2546 WatchedInfo
*watchedInfo
= (WatchedInfo
*)(void *)CFDataGetBytePtr(watched
);
2548 #pragma unused(messageArgument)
2549 switch (messageType
) {
2550 case kIOMessageServiceIsTerminated
: { // if [locked] interface yanked
2551 CFStringRef bsdName
;
2553 bsdName
= SCNetworkInterfaceGetBSDName(watchedInfo
->interface
);
2554 if (bsdName
!= NULL
) {
2555 SC_log(LOG_INFO
, "[pre-configured] interface removed: %@", bsdName
);
2557 SC_log(LOG_INFO
, "[pre-configured] interface w/no BSD name removed");
2558 SC_log(LOG_INFO
, " interface = %@", watchedInfo
->interface
);
2561 if (S_preconfigured
!= NULL
) {
2563 CFIndex n
= CFArrayGetCount(S_preconfigured
);
2565 i
= CFArrayGetFirstIndexOfValue(S_preconfigured
, CFRangeMake(0, n
), watched
);
2566 if (i
!= kCFNotFound
) {
2567 CFArrayRemoveValueAtIndex(S_preconfigured
, i
);
2568 if (CFArrayGetCount(S_preconfigured
) == 0) {
2569 CFRelease(S_preconfigured
);
2570 S_preconfigured
= NULL
;
2584 sharePreconfigured();
2591 updatePreConfiguredInterfaces(CFArrayRef interfaces
)
2594 Boolean updated
= FALSE
;
2596 n
= (interfaces
!= NULL
) ? CFArrayGetCount(interfaces
) : 0;
2597 for (CFIndex i
= 0; i
< n
; i
++) {
2598 SCNetworkInterfaceRef interface
;
2600 interface
= CFArrayGetValueAtIndex(interfaces
, i
);
2601 if (_SCNetworkInterfaceIsApplePreconfigured(interface
) &&
2602 !isWatchedInterface(S_preconfigured
, interface
)) {
2605 watched
= watcherCreate(interface
, preconfiguredInterfaceUpdated
);
2606 if (watched
!= NULL
) {
2607 CFStringRef bsdName
;
2609 bsdName
= SCNetworkInterfaceGetBSDName(interface
);
2610 if (bsdName
!= NULL
) {
2611 SC_log(LOG_INFO
, "watching [pre-configured] interface: %@", bsdName
);
2613 SC_log(LOG_INFO
, "watching [pre-configured] interface w/no BSD name");
2614 SC_log(LOG_INFO
, " interface = %@", interface
);
2617 if (S_preconfigured
== NULL
) {
2618 S_preconfigured
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
2620 CFArrayAppendValue(S_preconfigured
, watched
);
2627 sharePreconfigured();
2635 #pragma mark Interface naming
2638 static __inline__ boolean_t
2641 return (S_quiet
== MACH_PORT_NULL
);
2645 wasPreviouslyUsedInterface(CFDictionaryRef dbdict
, SCNetworkInterfaceRef interface
)
2647 CFArrayRef matchingMACs
;
2649 matchingMACs
= CFDictionaryGetValue(dbdict
, CFSTR(kSCNetworkInterfaceMatchingMACs
));
2650 if (matchingMACs
!= NULL
) {
2653 addr
= _SCNetworkInterfaceGetHardwareAddress(interface
);
2655 if (CFArrayContainsValue(matchingMACs
,
2656 CFRangeMake(0, CFArrayGetCount(matchingMACs
)),
2667 nameInterfaces(CFMutableArrayRef if_list
)
2670 CFIndex n
= CFArrayGetCount(if_list
);
2672 for (i
= 0; i
< n
; i
++) {
2674 SCNetworkInterfaceRef interface
;
2675 SCNetworkInterfaceRef new_interface
;
2681 interface
= CFArrayGetValueAtIndex(if_list
, i
);
2682 path
= _SCNetworkInterfaceGetIOPath(interface
);
2683 type
= _SCNetworkInterfaceGetIOInterfaceType(interface
);
2684 unit
= _SCNetworkInterfaceGetIOInterfaceUnit(interface
);
2685 entryID
= _SCNetworkInterfaceGetIORegistryEntryID(interface
);
2688 CFStringRef if_name
;
2690 if_name
= SCNetworkInterfaceGetBSDName(interface
);
2691 if ((if_name
== NULL
) || !CFDictionaryContainsKey(S_state
, if_name
)) {
2692 SC_log(LOG_INFO
, "Interface already has a unit number");
2693 displayInterface(interface
);
2696 // update the list of interfaces that were previously named
2697 if ((S_prev_active_list
!= NULL
)
2698 && lookupInterfaceByAddress(S_prev_active_list
, interface
, &where
) != NULL
) {
2699 CFArrayRemoveValueAtIndex(S_prev_active_list
, where
);
2702 replaceInterface(interface
);
2704 CFDictionaryRef dbdict
;
2705 boolean_t is_builtin
;
2709 dbdict
= lookupInterfaceByAddress(S_dblist
, interface
, NULL
);
2710 if (dbdict
!= NULL
) {
2711 unit
= CFDictionaryGetValue(dbdict
, CFSTR(kIOInterfaceUnit
));
2714 SC_log(LOG_INFO
, "Interface assigned unit %@ (from database)", unit
);
2717 if ((dbdict
== NULL
) && !isQuiet()) {
2718 // if new interface, wait until quiet before naming
2719 addTimestamp(S_state
, path
);
2723 is_builtin
= _SCNetworkInterfaceIsBuiltin(interface
);
2725 if (dbdict
== NULL
) {
2726 dbdict
= lookupMatchingInterface(interface
,
2730 is_builtin
? kCFBooleanTrue
: kCFBooleanFalse
);
2732 if ((dbdict
!= NULL
) && wasPreviouslyUsedInterface(dbdict
, interface
)) {
2733 unit
= CFDictionaryGetValue(dbdict
, CFSTR(kIOInterfaceUnit
));
2736 SC_log(LOG_INFO
, "Interface assigned unit %@ (updating database w/previously used interface)", unit
);
2739 #if !TARGET_OS_IPHONE
2740 if ((unit
== NULL
) &&
2743 blockNewInterfaces() &&
2744 !_SCNetworkInterfaceIsApplePreconfigured(interface
) &&
2745 isConsoleLocked()) {
2748 // if new (but matching) interface and console locked, ignore
2749 addr
= SCNetworkInterfaceGetHardwareAddressString(interface
);
2750 SC_log(LOG_NOTICE
, "Console locked, network interface* ignored");
2751 SC_log(LOG_INFO
, " path = %@, addr = %@",
2753 (addr
!= NULL
) ? addr
: CFSTR("?"));
2754 watchLockedInterface(interface
);
2757 #endif // !TARGET_OS_IPHONE
2759 if ((unit
== NULL
) && (dbdict
!= NULL
)) {
2760 unit
= CFDictionaryGetValue(dbdict
, CFSTR(kIOInterfaceUnit
));
2763 SC_log(LOG_INFO
, "Interface assigned unit %@ (updating database w/new interface)", unit
);
2767 if ((dbdict
!= NULL
) && (S_prev_active_list
!= NULL
)) {
2768 // update the list of interfaces that were previously named
2769 where
= CFArrayGetFirstIndexOfValue(S_prev_active_list
,
2770 CFRangeMake(0, CFArrayGetCount(S_prev_active_list
)),
2772 if (where
!= kCFNotFound
) {
2773 CFArrayRemoveValueAtIndex(S_prev_active_list
, where
);
2777 if (dbdict
== NULL
) {
2781 // built-in interface, try to use the reserved slots
2782 next_unit
= builtinCount(if_list
, i
, type
);
2784 // But, before claiming a reserved slot we check to see if the
2785 // slot had previously been used. If so, and if the slot had been
2786 // assigned to the same type of interface, then we will perform a
2787 // replacement (e.g. assume that this was a board swap). But, if
2788 // the new interface is a different type then we assume that the
2789 // built-in configuration has changed and allocate a new unit from
2790 // the non-reserved slots.
2792 unit
= CFNumberCreate(NULL
, kCFNumberIntType
, &next_unit
);
2793 if (!builtinAvailable(interface
, unit
)) {
2794 // if [built-in] unit not available
2795 SC_log(LOG_INFO
, "Interface not assigned [built-in] unit %@", unit
);
2801 #if !TARGET_OS_IPHONE
2804 blockNewInterfaces() &&
2805 !_SCNetworkInterfaceIsApplePreconfigured(interface
) &&
2806 isConsoleLocked()) {
2809 // if new interface and console locked, ignore
2810 addr
= SCNetworkInterfaceGetHardwareAddressString(interface
);
2811 SC_log(LOG_NOTICE
, "Console locked, network interface ignored");
2812 SC_log(LOG_INFO
, " path = %@, addr = %@",
2814 (addr
!= NULL
) ? addr
: CFSTR("?"));
2815 watchLockedInterface(interface
);
2818 #endif // !TARGET_OS_IPHONE
2821 // not built-in (or built-in unit not available), allocate from
2822 // the non-reserved slots
2823 next_unit
= builtinCount(if_list
, n
, type
);
2824 next_unit
= getNextUnitForType(type
, next_unit
);
2825 unit
= CFNumberCreate(NULL
, kCFNumberIntType
, &next_unit
);
2828 SC_log(LOG_INFO
, "Interface assigned unit %@ (%s)",
2830 is_builtin
? "built-in" : "next available");
2835 #ifdef USE_REGISTRY_ENTRY_ID
2836 kr
= registerInterfaceWithIORegistryEntryID(S_connect
,
2839 (dbdict
== NULL
) ? kIONetworkStackRegisterInterfaceWithLowestUnit
2840 : kIONetworkStackRegisterInterfaceWithUnit
);
2841 new_interface
= copyNamedInterfaceForIORegistryEntryID(entryID
);
2842 #else // USE_REGISTRY_ENTRY_ID
2843 kr
= registerInterfaceWithIOServicePath(S_connect
,
2846 (dbdict
== NULL
) ? kRegisterInterface
2847 : kRegisterInterfaceWithFixedUnit
);
2848 new_interface
= copyNamedInterfaceForIOKitPath(path
);
2849 #endif // USE_REGISTRY_ENTRY_ID
2850 if (new_interface
== NULL
) {
2851 const char *signature
;
2853 signature
= (dbdict
== NULL
) ? "failed to name new interface"
2854 : "failed to name known interface";
2856 SC_log(LOG_NOTICE
, "%s, kr=0x%x\n"
2866 displayInterface(interface
);
2868 if ((dbdict
!= NULL
) && (retries
++ < 5)) {
2869 usleep(50 * 1000); // sleep 50ms between attempts
2874 CFNumberRef new_unit
;
2877 SC_log(LOG_INFO
, "%s interface named after %d %s\n"
2880 (dbdict
== NULL
) ? "New" : "Known",
2882 (retries
== 1) ? "try" : "tries",
2886 #ifdef SHOW_NAMING_FAILURE
2887 str
= CFStringCreateWithFormat(NULL
,
2889 CFSTR("\"%s\" interface named after %d %s, unit = %@"),
2890 (dbdict
== NULL
) ? "New" : "Known",
2892 (retries
== 1) ? "try" : "tries",
2894 CFUserNotificationDisplayNotice(0,
2895 kCFUserNotificationStopAlertLevel
,
2900 CFSTR("Please report repeated failures."),
2903 #endif // SHOW_NAMING_FAILURE
2906 new_unit
= _SCNetworkInterfaceGetIOInterfaceUnit(new_interface
);
2907 if (!CFEqual(unit
, new_unit
)) {
2908 SC_log(LOG_INFO
, "interface type %@ assigned unit %@ instead of %@",
2909 type
, new_unit
, unit
);
2912 displayInterface(new_interface
);
2914 // update if_list (with the interface name & unit)
2915 CFArraySetValueAtIndex(if_list
, i
, new_interface
);
2916 CFRelease(new_interface
);
2917 interface
= new_interface
; // if_list holds the reference
2919 if (is_builtin
&& (S_prev_active_list
!= NULL
)) {
2922 // update the list of [built-in] interfaces that were previously named
2923 if (lookupInterfaceByUnit(S_prev_active_list
, interface
, &where
) != NULL
) {
2924 SC_log(LOG_DEBUG
, " and updated database (new address)");
2925 CFArrayRemoveValueAtIndex(S_prev_active_list
, where
);
2928 replaceInterface(interface
);
2936 #if !TARGET_OS_IPHONE
2938 #define INSTALL_ENVIRONMENT "__OSINSTALL_ENVIRONMENT"
2943 static Boolean isRecovery
= FALSE
;
2944 static dispatch_once_t once
;
2947 * We check to see if the __OSINSTALL_ENVIRONMENT env var is present. If
2948 * so, then we are most likely booted into the Recovery OS with no [Aqua]
2949 * "SCMonitor" [UserEventAgent] plugin.
2951 dispatch_once(&once
, ^{
2952 if (getenv(INSTALL_ENVIRONMENT
) != NULL
) {
2962 updateNetworkConfiguration(CFArrayRef if_list
)
2964 Boolean do_commit
= FALSE
;
2967 SCPreferencesRef prefs
= NULL
;
2968 SCNetworkSetRef set
= NULL
;
2970 prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":updateNetworkConfiguration"), NULL
);
2971 if (prefs
== NULL
) {
2972 SC_log(LOG_NOTICE
, "SCPreferencesCreate() failed: %s", SCErrorString(SCError()));
2976 set
= SCNetworkSetCopyCurrent(prefs
);
2978 SC_log(LOG_INFO
, "No current set, adding default");
2979 set
= _SCNetworkSetCreateDefault(prefs
);
2981 SC_log(LOG_NOTICE
, "_SCNetworkSetCreateDefault() failed: %s", SCErrorString(SCError()));
2986 n
= (if_list
!= NULL
) ? CFArrayGetCount(if_list
) : 0;
2987 for (i
= 0; i
< n
; i
++) {
2988 SCNetworkInterfaceRef interface
;
2990 interface
= CFArrayGetValueAtIndex(if_list
, i
);
2991 if (SCNetworkSetEstablishDefaultInterfaceConfiguration(set
, interface
)) {
2992 SC_log(LOG_INFO
, "adding default configuration for %@",
2993 SCNetworkInterfaceGetBSDName(interface
));
3001 ok
= SCPreferencesCommitChanges(prefs
);
3003 SC_log(LOG_NOTICE
, "SCPreferencesCommitChanges() failed: %s", SCErrorString(SCError()));
3007 ok
= SCPreferencesApplyChanges(prefs
);
3009 SC_log(LOG_NOTICE
, "SCPreferencesApplyChanges() failed: %s", SCErrorString(SCError()));
3021 if (prefs
!= NULL
) {
3028 #endif // !TARGET_OS_IPHONE
3031 upgradeNetworkConfiguration()
3033 static dispatch_once_t once
;
3036 * Once, per start of InterfaceNamer, we check/ensure that the
3037 * configuration has been upgraded.
3039 * Note: this check should not be performed until we know that
3040 * the __wait_for_IOKit_to_quiesce() conditions have been
3044 dispatch_once(&once
, ^{
3045 SCPreferencesRef ni_prefs
;
3048 // save the [current] DB with the interfaces that have been named
3049 writeInterfaceList(S_dblist
);
3051 // upgrade the configuration
3052 ni_prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":upgradeNetworkConfiguration"), INTERFACES_DEFAULT_CONFIG
);
3053 if (ni_prefs
== NULL
) {
3054 SC_log(LOG_NOTICE
, "SCPreferencesCreate() failed: %s", SCErrorString(SCError()));
3057 updated
= __SCNetworkConfigurationUpgrade(NULL
, &ni_prefs
, TRUE
);
3058 CFRelease(ni_prefs
);
3061 // re-read list of previously named network interfaces
3062 if (S_dblist
!= NULL
) {
3063 CFRelease(S_dblist
);
3065 S_dblist
= readInterfaceList();
3067 addTimestamp(S_state
, CFSTR("*UPGRADED*"));
3068 SC_log(LOG_INFO
, "network configuration upgraded");
3077 removeInactiveInterfaces(void)
3082 * remove any previous interfaces that were built-in,
3083 * were active, and were hidden (pre-configured) that
3084 * are no longer plugged in.
3087 if ((S_dblist
== NULL
) || (S_prev_active_list
== NULL
)) {
3091 n
= CFArrayGetCount(S_prev_active_list
);
3092 for (CFIndex i
= n
- 1; i
>= 0; i
--) {
3093 CFBooleanRef builtin
;
3094 CFBooleanRef hidden
;
3095 CFDictionaryRef if_dict
;
3096 CFDictionaryRef info
;
3100 if_dict
= CFArrayGetValueAtIndex(S_prev_active_list
, i
);
3102 // Note: keep the following logic in sync with _SCNetworkInterfaceIsApplePreconfigured()
3104 name
= CFDictionaryGetValue(if_dict
, CFSTR(kIOBSDNameKey
));
3105 if (!isA_CFString(name
)) {
3110 hidden
= CFDictionaryGetValue(if_dict
, kSCNetworkInterfaceHiddenConfigurationKey
);
3111 if (!isA_CFBoolean(hidden
) || !CFBooleanGetValue(hidden
)) {
3116 builtin
= CFDictionaryGetValue(if_dict
, CFSTR(kIOBuiltin
));
3117 if (isA_CFBoolean(builtin
) && CFBooleanGetValue(builtin
)) {
3118 // if [hidden] builtin
3122 info
= CFDictionaryGetValue(if_dict
, CFSTR(kSCNetworkInterfaceInfo
));
3123 if (isA_CFDictionary(info
)) {
3127 if (CFDictionaryGetValueIfPresent(info
, CFSTR(kUSBVendorID
), (const void **)&vidNum
) &&
3128 isA_CFNumber(vidNum
) &&
3129 CFNumberGetValue(vidNum
, kCFNumberIntType
, &vid
) &&
3130 (vid
== kIOUSBAppleVendorID
)) {
3131 // if [hidden] Apple interface
3140 SC_log(LOG_INFO
, "Removing no-longer-active \"hidden\" interface: %@", name
);
3142 if (lookupInterfaceByName(S_dblist
, name
, &where
) != NULL
) {
3143 // remove from the list of interfaces we know about
3144 CFArrayRemoveValueAtIndex(S_dblist
, where
);
3145 // remove from the previously active list
3146 CFArrayRemoveValueAtIndex(S_prev_active_list
, i
);
3154 reportInactiveInterfaces(void)
3159 * report any previous interfaces that are not [yet] active
3162 if (S_prev_active_list
== NULL
) {
3166 n
= CFArrayGetCount(S_prev_active_list
);
3168 SC_log(LOG_INFO
, "Interface%s not [yet] active",
3169 (n
> 1) ? "s" : "");
3171 for (CFIndex i
= 0; i
< n
; i
++) {
3172 CFDictionaryRef if_dict
;
3177 if_dict
= CFArrayGetValueAtIndex(S_prev_active_list
, i
);
3178 name
= CFDictionaryGetValue(if_dict
, CFSTR(kIOBSDNameKey
));
3179 type
= CFDictionaryGetValue(if_dict
, CFSTR(kIOInterfaceType
));
3180 unit
= CFDictionaryGetValue(if_dict
, CFSTR(kIOInterfaceUnit
));
3181 SC_log(LOG_INFO
, " %s%@%sType: %@, Unit: %@",
3182 (name
!= NULL
) ? "BSD Name: " : "",
3183 (name
!= NULL
) ? name
: CFSTR(""),
3184 (name
!= NULL
) ? ", " : "",
3193 updateInterfaces(void)
3195 if (S_connect
== MACH_PORT_NULL
) {
3196 // if we don't have the "IONetworkStack" connect object
3200 if (S_iflist
!= NULL
) {
3203 n
= CFArrayGetCount(S_iflist
);
3205 CFArraySortValues(S_iflist
, CFRangeMake(0, n
), _SCNetworkInterfaceCompare
, NULL
);
3207 nameInterfaces(S_iflist
);
3211 * Update the list of [Apple] pre-configured interfaces
3213 updatePreConfiguredInterfaces(S_iflist
);
3215 #if TARGET_OS_IPHONE
3217 * Update the list of "trust required" interfaces
3219 if (haveLockdown()) {
3220 updateTrustRequiredInterfaces(S_iflist
);
3222 #endif // TARGET_OS_IPHONE
3226 * The registry [matching] has quiesced
3229 // remove any inactive interfaces
3230 removeInactiveInterfaces();
3232 // save the DB with the interfaces that have been named
3233 writeInterfaceList(S_dblist
);
3235 // update the VLAN/BOND configuration
3236 updateVirtualNetworkInterfaceConfiguration(NULL
, kSCPreferencesNotificationApply
, NULL
);
3238 #if !TARGET_OS_IPHONE
3239 if (isRecoveryOS()) {
3241 * We are most likely booted into the Recovery OS with no "SCMonitor"
3242 * UserEventAgent plugin running so let's make sure we update the
3243 * network configuration for new interfaces.
3245 updateNetworkConfiguration(S_iflist
);
3247 #endif // !TARGET_OS_IPHONE
3249 // tell everyone that we've finished (at least for now)
3252 // log those interfaces which are no longer present in
3253 // the HW config (or have yet to show up).
3254 reportInactiveInterfaces();
3256 if (S_prev_active_list
!= NULL
) {
3257 CFRelease(S_prev_active_list
);
3258 S_prev_active_list
= NULL
;
3261 if (S_iflist
!= NULL
) {
3262 CFRelease(S_iflist
);
3266 if ((S_prev_active_list
!= NULL
) && (CFArrayGetCount(S_prev_active_list
) == 0)) {
3268 * if we've named all of the interfaces that
3269 * were used during the previous boot.
3271 addTimestamp(S_state
, kInterfaceNamerKey_Complete
);
3272 SC_log(LOG_INFO
, "last boot interfaces have been named");
3274 CFRelease(S_prev_active_list
);
3275 S_prev_active_list
= NULL
;
3283 interfaceArrivalCallback(void *refcon
, io_iterator_t iter
)
3285 #pragma unused(refcon)
3288 while ((obj
= IOIteratorNext(iter
)) != MACH_PORT_NULL
) {
3289 SCNetworkInterfaceRef interface
;
3291 interface
= _SCNetworkInterfaceCreateWithIONetworkInterfaceObject(obj
);
3292 if (interface
!= NULL
) {
3293 if (S_iflist
== NULL
) {
3294 S_iflist
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
3296 CFArrayAppendValue(S_iflist
, interface
);
3297 CFRelease(interface
);
3299 IOObjectRelease(obj
);
3308 * Function: stackCallback
3310 * Get a reference to the single IONetworkStack object instance in
3311 * the kernel. Naming requests must be sent to this object, which is
3312 * attached as a client to all network interface objects in the system.
3314 * Call IOObjectRelease on the returned object.
3317 stackCallback(void *refcon
, io_iterator_t iter
)
3319 #pragma unused(refcon)
3323 stack
= IOIteratorNext(iter
);
3324 if (stack
== MACH_PORT_NULL
) {
3328 kr
= IOServiceOpen(stack
, mach_task_self(), 0, &S_connect
);
3329 if (kr
!= KERN_SUCCESS
) {
3330 SC_log(LOG_ERR
, "IOServiceOpen returned 0x%x", kr
);
3334 addTimestamp(S_state
, CFSTR("*STACK*"));
3335 SC_log(LOG_INFO
, "IONetworkStack found");
3337 if (S_stack
!= MACH_PORT_NULL
) {
3338 IOObjectRelease(S_stack
);
3339 S_stack
= MACH_PORT_NULL
;
3342 if ((S_timer
!= NULL
) && CFRunLoopTimerIsValid(S_timer
)) {
3343 // With the IONetworkStack object now available we can
3344 // reset (shorten?) the time we are willing to wait for
3345 // IOKit to quiesce.
3346 CFRunLoopTimerSetNextFireDate(S_timer
,
3347 CFAbsoluteTimeGetCurrent() + S_quiet_timeout
);
3354 if (stack
!= MACH_PORT_NULL
) {
3355 IOObjectRelease(stack
);
3362 quietCallback(void *refcon
,
3363 io_service_t service
,
3364 natural_t messageType
,
3365 void *messageArgument
)
3367 #pragma unused(refcon)
3368 #pragma unused(service)
3369 if (messageArgument
!= NULL
) {
3374 if (messageType
== kIOMessageServiceBusyStateChange
) {
3375 addTimestamp(S_state
, kInterfaceNamerKey_Quiet
);
3376 SC_log(LOG_INFO
, "IOKit quiet");
3379 if (S_connect
== MACH_PORT_NULL
) {
3380 SC_log(LOG_ERR
, "No network stack object");
3384 if (S_quiet
!= MACH_PORT_NULL
) {
3385 IOObjectRelease(S_quiet
);
3386 S_quiet
= MACH_PORT_NULL
;
3389 if (S_timer
!= NULL
) {
3390 CFRunLoopTimerInvalidate(S_timer
);
3395 // grab (and name) any additional interfaces.
3396 interfaceArrivalCallback((void *)S_notify
, S_iter
);
3398 if (messageType
== kIOMessageServiceBusyStateChange
) {
3399 addTimestamp(S_state
, CFSTR("*QUIET&NAMED*"));
3401 upgradeNetworkConfiguration();
3408 iterateRegistryBusy(io_iterator_t iterator
, CFArrayRef nodes
, int *count
)
3410 kern_return_t kr
= kIOReturnSuccess
;;
3413 while ((kr
== kIOReturnSuccess
) &&
3414 ((obj
= IOIteratorNext(iterator
)) != MACH_PORT_NULL
)) {
3415 uint64_t accumulated_busy_time
;
3416 uint32_t busy_state
;
3419 CFMutableArrayRef newNodes
;
3421 CFMutableStringRef str
= NULL
;
3423 if (nodes
== NULL
) {
3424 newNodes
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
3426 newNodes
= CFArrayCreateMutableCopy(NULL
, 0, nodes
);
3428 assert(newNodes
!= NULL
);
3430 kr
= IORegistryEntryGetName(obj
, name
);
3431 if (kr
!= kIOReturnSuccess
) {
3432 SC_log(LOG_NOTICE
, "IORegistryEntryGetName() returned 0x%x", kr
);
3436 str
= CFStringCreateMutable(NULL
, 0);
3437 CFStringAppendCString(str
, name
, kCFStringEncodingUTF8
);
3439 kr
= IORegistryEntryGetLocationInPlane(obj
, kIOServicePlane
, location
);
3441 case kIOReturnSuccess
:
3442 CFStringAppendCString(str
, "@", kCFStringEncodingUTF8
);
3443 CFStringAppendCString(str
, location
, kCFStringEncodingUTF8
);
3445 case kIOReturnNotFound
:
3448 SC_log(LOG_NOTICE
, "IORegistryEntryGetLocationInPlane() returned 0x%x", kr
);
3453 CFArrayAppendValue(newNodes
, str
);
3456 kr
= IOServiceGetBusyStateAndTime(obj
, &state
, &busy_state
, &accumulated_busy_time
);
3457 if (kr
!= kIOReturnSuccess
) {
3458 SC_log(LOG_NOTICE
, "IOServiceGetBusyStateAndTime() returned 0x%x", kr
);
3462 #ifdef TEST_SNAPSHOT
3465 #endif // TEST_SNAPSHOT
3467 if (busy_state
!= 0) {
3470 if ((*count
)++ == 0) {
3471 SC_log(LOG_ERR
, "Busy services :");
3474 path
= CFStringCreateByCombiningStrings(NULL
, newNodes
, CFSTR("/"));
3475 SC_log(LOG_ERR
, " %@ [%s%s%s%d, %lld ms]",
3477 (state
& kIOServiceRegisteredState
) ? "" : "!registered, ",
3478 (state
& kIOServiceMatchedState
) ? "" : "!matched, ",
3479 (state
& kIOServiceInactiveState
) ? "inactive, " : "",
3481 accumulated_busy_time
/ kMillisecondScale
);
3485 kr
= IORegistryIteratorEnterEntry(iterator
);
3486 if (kr
!= kIOReturnSuccess
) {
3487 SC_log(LOG_NOTICE
, "IORegistryIteratorEnterEntry() returned 0x%x", kr
);
3491 iterateRegistryBusy(iterator
, newNodes
, count
);
3493 kr
= IORegistryIteratorExitEntry(iterator
);
3494 if (kr
!= kIOReturnSuccess
) {
3495 SC_log(LOG_NOTICE
, "IORegistryIteratorExitEntry() returned 0x%x", kr
);
3500 CFRelease(newNodes
);
3501 IOObjectRelease(obj
);
3511 io_iterator_t iterator
= MACH_PORT_NULL
;
3514 kr
= IORegistryCreateIterator(kIOMasterPortDefault
,
3518 if (kr
!= kIOReturnSuccess
) {
3519 SC_log(LOG_NOTICE
, "IORegistryCreateIterator() returned 0x%x", kr
);
3523 iterateRegistryBusy(iterator
, NULL
, &count
);
3525 SC_log(LOG_ERR
, "w/no busy services");
3528 IOObjectRelease(iterator
);
3532 timerCallback(CFRunLoopTimerRef timer
, void *info
)
3534 #pragma unused(timer)
3535 #pragma unused(info)
3536 // We've been waiting for IOKit to quiesce and it just
3537 // hasn't happenned. Time to just move on!
3538 addTimestamp(S_state
, kInterfaceNamerKey_Timeout
);
3541 SC_log(LOG_ERR
, "timed out waiting for IOKit to quiesce");
3544 quietCallback((void *)S_notify
, MACH_PORT_NULL
, 0, NULL
);
3546 addTimestamp(S_state
, CFSTR("*TIMEOUT&NAMED*"));
3548 upgradeNetworkConfiguration();
3554 setup_IOKit(CFBundleRef bundle
)
3556 #pragma unused(bundle)
3559 mach_port_t masterPort
= MACH_PORT_NULL
;
3561 io_object_t root
= MACH_PORT_NULL
;
3563 // read DB of previously named network interfaces
3564 S_dblist
= readInterfaceList();
3566 // get interfaces that were named during the last boot
3567 S_prev_active_list
= previouslyActiveInterfaces();
3569 // track how long we've waited to see each interface.
3570 S_state
= CFDictionaryCreateMutable(NULL
,
3572 &kCFTypeDictionaryKeyCallBacks
,
3573 &kCFTypeDictionaryValueCallBacks
);
3574 addTimestamp(S_state
, CFSTR("*START*"));
3576 // Creates and returns a notification object for receiving IOKit
3577 // notifications of new devices or state changes.
3578 kr
= IOMasterPort(bootstrap_port
, &masterPort
);
3579 if (kr
!= KERN_SUCCESS
) {
3580 SC_log(LOG_ERR
, "IOMasterPort returned 0x%x", kr
);
3584 S_notify
= IONotificationPortCreate(masterPort
);
3585 if (S_notify
== NULL
) {
3586 SC_log(LOG_ERR
, "IONotificationPortCreate failed");
3590 // watch IOKit matching activity
3591 root
= IORegistryEntryFromPath(masterPort
, kIOServicePlane
":/");
3592 if (root
== MACH_PORT_NULL
) {
3593 SC_log(LOG_ERR
, "IORegistryEntryFromPath failed");
3597 kr
= IOServiceAddInterestNotification(S_notify
,
3601 (void *)S_notify
, // refCon
3602 &S_quiet
); // notification
3603 if (kr
!= KERN_SUCCESS
) {
3604 SC_log(LOG_ERR
, "IOServiceAddInterestNotification returned 0x%x", kr
);
3608 kr
= IOServiceGetBusyState(root
, &busy
);
3609 if (kr
!= KERN_SUCCESS
) {
3610 SC_log(LOG_ERR
, "IOServiceGetBusyState returned 0x%x", kr
);
3614 // add a timer so we don't wait forever for IOKit to quiesce
3615 S_timer
= CFRunLoopTimerCreate(NULL
,
3616 CFAbsoluteTimeGetCurrent() + S_stack_timeout
,
3622 if (S_timer
== NULL
) {
3623 SC_log(LOG_ERR
, "CFRunLoopTimerCreate failed");
3627 CFRunLoopAddTimer(CFRunLoopGetCurrent(), S_timer
, kCFRunLoopDefaultMode
);
3629 // watch for the introduction of the IONetworkStack
3630 kr
= IOServiceAddMatchingNotification(S_notify
,
3631 kIOFirstMatchNotification
,
3632 IOServiceMatching("IONetworkStack"),
3634 (void *)S_notify
, // refCon
3635 &S_stack
); // notification
3636 if (kr
!= KERN_SUCCESS
) {
3637 SC_log(LOG_ERR
, "IOServiceAddMatchingNotification returned 0x%x", kr
);
3641 // check and see if the stack is already available and arm the
3642 // notification for its introduction.
3643 stackCallback((void *)S_notify
, S_stack
);
3645 // watch for the introduction of new network interfaces
3646 kr
= IOServiceAddMatchingNotification(S_notify
,
3647 kIOFirstMatchNotification
,
3648 IOServiceMatching("IONetworkInterface"),
3649 &interfaceArrivalCallback
,
3650 (void *)S_notify
, // refCon
3651 &S_iter
); // notification
3652 if (kr
!= KERN_SUCCESS
) {
3653 SC_log(LOG_ERR
, "IOServiceAddMatchingNotification returned 0x%x", kr
);
3657 // Get the current list of matches and arm the notification for
3658 // future interface arrivals.
3659 interfaceArrivalCallback((void *)S_notify
, S_iter
);
3661 // Check if IOKit has already quiesced.
3662 quietCallback((void *)S_notify
,
3664 kIOMessageServiceBusyStateChange
,
3665 (void *)(uintptr_t)busy
);
3667 CFRunLoopAddSource(CFRunLoopGetCurrent(),
3668 IONotificationPortGetRunLoopSource(S_notify
),
3669 kCFRunLoopDefaultMode
);
3671 #ifdef WAIT_PREVIOUS_BOOT_INTERFACES_OR_QUIET
3673 * Start the wheels turning until we've named all of
3674 * the interfaces that were used during the previous
3675 * boot, until IOKit [matching] has quiesced, or
3676 * until we've waited long enough.
3678 CFRunLoopAddTimer(CFRunLoopGetCurrent(), S_timer
, MY_PLUGIN_ID
);
3679 CFRunLoopAddSource(CFRunLoopGetCurrent(),
3680 IONotificationPortGetRunLoopSource(S_notify
),
3682 while (S_prev_active_list
!= NULL
) {
3685 rlStatus
= CFRunLoopRunInMode(MY_PLUGIN_ID
, 1.0e10
, TRUE
);
3687 #endif /* WAIT_PREVIOUS_BOOT_INTERFACES_OR_QUIET */
3690 if (S_dblist
!= NULL
) {
3691 // apply special handling for the BT-PAN interface (if present)
3692 CFArrayApplyFunction(S_dblist
,
3693 CFRangeMake(0, CFArrayGetCount(S_dblist
)),
3694 updateBTPANInformation
,
3697 #endif // TARGET_OS_OSX
3702 if (root
!= MACH_PORT_NULL
) {
3703 IOObjectRelease(root
);
3705 if (masterPort
!= MACH_PORT_NULL
) {
3706 mach_port_deallocate(mach_task_self(), masterPort
);
3713 setup_Virtual(CFBundleRef bundle
)
3715 #pragma unused(bundle)
3716 // open a SCPreferences session
3717 S_prefs
= SCPreferencesCreate(NULL
, CFSTR(MY_PLUGIN_NAME
":setup_Virtual"), NULL
);
3718 if (S_prefs
== NULL
) {
3719 SC_log(LOG_ERR
, "SCPreferencesCreate() failed: %s",
3720 SCErrorString(SCError()));
3724 // register for change notifications.
3725 if (!SCPreferencesSetCallback(S_prefs
, updateVirtualNetworkInterfaceConfiguration
, NULL
)) {
3726 SC_log(LOG_ERR
, "SCPreferencesSetCallBack() failed: %s", SCErrorString(SCError()));
3732 if (!SCPreferencesScheduleWithRunLoop(S_prefs
, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode
)) {
3733 if (SCError() != kSCStatusNoStoreServer
) {
3734 SC_log(LOG_ERR
, "SCPreferencesScheduleWithRunLoop() failed: %s", SCErrorString(SCError()));
3744 exec_InterfaceNamer(void *arg
)
3746 CFBundleRef bundle
= (CFBundleRef
)arg
;
3747 CFDictionaryRef dict
;
3749 pthread_setname_np(MY_PLUGIN_NAME
" thread");
3751 dict
= CFBundleGetInfoDictionary(bundle
);
3752 if (isA_CFDictionary(dict
)) {
3755 num
= CFDictionaryGetValue(dict
, CFSTR(WAIT_STACK_TIMEOUT_KEY
));
3757 if (!isA_CFNumber(num
) ||
3758 !CFNumberGetValue(num
, kCFNumberDoubleType
, &S_stack_timeout
) ||
3759 (S_stack_timeout
<= 0.0)) {
3760 SC_log(LOG_NOTICE
, WAIT_STACK_TIMEOUT_KEY
" value error");
3761 S_stack_timeout
= WAIT_STACK_TIMEOUT_DEFAULT
;
3765 num
= CFDictionaryGetValue(dict
, CFSTR(WAIT_QUIET_TIMEOUT_KEY
));
3767 if (!isA_CFNumber(num
) ||
3768 !CFNumberGetValue(num
, kCFNumberDoubleType
, &S_quiet_timeout
) ||
3769 (S_quiet_timeout
<= 0.0)) {
3770 SC_log(LOG_NOTICE
, WAIT_QUIET_TIMEOUT_KEY
" value error");
3771 S_quiet_timeout
= WAIT_QUIET_TIMEOUT_DEFAULT
;
3776 // setup virtual network interface monitoring
3777 if (!setup_Virtual(bundle
)) {
3781 // setup [IOKit] network interface monitoring
3782 if (!setup_IOKit(bundle
)) {
3789 if (S_connect
!= MACH_PORT_NULL
) {
3790 IOServiceClose(S_connect
);
3791 S_connect
= MACH_PORT_NULL
;
3793 if (S_dblist
!= NULL
) {
3794 CFRelease(S_dblist
);
3797 if (S_iter
!= MACH_PORT_NULL
) {
3798 IOObjectRelease(S_iter
);
3799 S_iter
= MACH_PORT_NULL
;
3801 if (S_notify
!= MACH_PORT_NULL
) {
3802 IONotificationPortDestroy(S_notify
);
3804 if (S_quiet
!= MACH_PORT_NULL
) {
3805 IOObjectRelease(S_quiet
);
3806 S_quiet
= MACH_PORT_NULL
;
3808 if (S_stack
!= MACH_PORT_NULL
) {
3809 IOObjectRelease(S_stack
);
3810 S_stack
= MACH_PORT_NULL
;
3812 if (S_state
!= NULL
) {
3816 if (S_timer
!= NULL
) {
3817 CFRunLoopTimerInvalidate(S_timer
);
3831 load_InterfaceNamer(CFBundleRef bundle
, Boolean bundleVerbose
)
3833 #pragma unused(bundleVerbose)
3834 pthread_attr_t tattr
;
3837 CFRetain(bundle
); // released in exec_InterfaceNamer
3839 pthread_attr_init(&tattr
);
3840 pthread_attr_setscope(&tattr
, PTHREAD_SCOPE_SYSTEM
);
3841 pthread_attr_setdetachstate(&tattr
, PTHREAD_CREATE_DETACHED
);
3842 // pthread_attr_setstacksize(&tattr, 96 * 1024); // each thread gets a 96K stack
3843 pthread_create(&tid
, &tattr
, exec_InterfaceNamer
, bundle
);
3844 pthread_attr_destroy(&tattr
);
3849 //------------------------------------------------------------------------
3851 #ifdef TEST_INTERFACE_ASSIGNMENT
3853 main(int argc
, char ** argv
)
3855 #pragma unused(argv)
3857 CFMutableArrayRef interfaces
;
3858 CFArrayRef interfaces_all
;
3862 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
3864 bundle
= CFBundleGetMainBundle();
3865 CFRetain(bundle
); // released in exec_InterfaceNamer
3868 setup_IOKit(bundle
);
3870 // but, when running this test we know that the IORegistry has already quiesced
3871 IOObjectRelease(S_quiet
);
3872 S_quiet
= MACH_PORT_NULL
;
3874 // collect the interfaces
3875 interfaces
= CFArrayCreateMutable(NULL
, 0, &kCFTypeArrayCallBacks
);
3876 interfaces_all
= SCNetworkInterfaceCopyAll();
3877 n
= CFArrayGetCount(interfaces_all
);
3878 for (CFIndex i
= 0; i
< n
; i
++) {
3879 SCNetworkInterfaceRef interface
= CFArrayGetValueAtIndex(interfaces_all
, i
);
3880 SCNetworkInterfacePrivateRef interfacePrivate
= (SCNetworkInterfacePrivateRef
)interface
;
3882 if (interfacePrivate
->type
== NULL
) {
3883 // skip interfaces with a kIOInterfaceType property
3887 if (interfacePrivate
->unit
!= NULL
) {
3888 // remove any already assigned unit #
3889 CFRelease(interfacePrivate
->unit
);
3890 interfacePrivate
->unit
= NULL
;
3893 CFArrayAppendValue(interfaces
, interface
);
3895 CFRelease(interfaces_all
);
3896 SC_log(LOG_INFO
, "interfaces = %@", interfaces
);
3898 // exercise the interface naming assignments
3899 nameInterfaces(interfaces
);
3900 CFRelease(interfaces
);
3907 #ifdef TEST_SNAPSHOT
3909 main(int argc
, char ** argv
)
3912 _sc_verbose
= (argc
> 1) ? TRUE
: FALSE
;
3919 #endif /* TEST_SNAPSHOT */